v0.2 step 1 — remove the agent code (#31)
razorbill becomes an OpenAI-compatible MLX model server. Removed the TUI, agent loop, bash tool, tool registry, agent YAML loader/writer and the init/run/chat/tui/config commands. Kept what the server reuses: models list/pull/rm, ModelStore, MLX engine, FakeEngine, ThinkingSplitter, ConfigReader, Quantities, GenerationSettings. Tickets: #31 task 6 closed, #17 last task closed, new spike #47 (KV cache). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
132c60f parent: 84bebb1 modified
.memory/handoffs/2026-11-24-v0-1-implementation.md +7 -0 | @@ -45,3 +45,10 @@ v0.1 implemented, quality gate PASS, docs EN+FR written, README and `summary.md` | ||
| 45 | 45 | The user wants razorbill to become a model server (MLX only, OpenAI-compatible API) and to leave the agent aside. Tickets #31–#46 written (milestone `v0.2 — OpenAI-compatible MLX server`; #46 in `v0.3 — Decision models`). **Start with #31**: its decisions (keep / freeze / remove `rzb run|chat|tui` — never delete without agreement; `rzb serve` vs separate executable; HTTP framework; v0.2 API surface) gate everything else. Then #32 (server skeleton, testable on Linux with FakeEngine) and #38 (constrained-decoding spike, Mac only). The sbxenv.yaml / qlty-in-sandbox proposal (lifecycle `postCreate` + `sbx env exec`, or a kit) is still waiting for the user's go. |
| 46 | 46 | #31's decisions are taken (see its comment #1): next is removing the agent code (task 6 of #31 — the user has agreed to the removal, keep the reused pieces) and the agent-only tickets' fate (#16, #21, #22, #23, #27, #29 not asked yet), then #32. |
| 47 | 47 | Agent-only tickets #16, #21, #22, #23, #27, #29 closed as wontfix (2026-11-25). #17 is agent-related and still open: ask the user. Next: task 6 of #31 (remove agent code) and #32. |
| 48 | + | |
| 49 | +## Update 2026-11-25 — v0.2 step 1 done (agent code removed), awaiting approval | |
| 50 | + | |
| 51 | +- v0.1 committed as `84bebb1` on `feature/v0.1-agent-mvp` (author k33g, local only, not pushed), local tag `v0.1-agent`; `__pycache__/` and `*.profraw` added to `.gitignore` (default.profraw left untracked). Work continues on `feature/v0.2-openai-server` (nothing committed there yet). | |
| 52 | +- Ticket #47 created: spike on the KV cache (prefix reuse across stateless requests, quantized/TurboQuant KV, save/load prompt cache, memory per token). | |
| 53 | +- Step 1 (#31 task 6, closed): removed TUI module, agent loop, bash tool and tool registry, agent YAML loader/writer/locator/prompt templates, commands init/run/chat/tui/config, examples/agent.yaml and their tests. Kept: models list/pull/rm, version, ModelStore, RecommendedModels, MLX engine, FakeEngine, ThinkingSplitter, ToolSpec/ToolCall, ConfigReader/ConfigError/ConfigValue (now tested directly in ConfigReaderTests), `Quantities` (duration/size parsing, from OptionReader), `GenerationSettings` (moved to Engine/), `DownloadProgress` (from AgentLauncher). Tests: Linux 32, Mac 37 (`host.sh test . razorbill`), swiftlint clean, Release build OK, `rzb --help` shows only models/version. | |
| 54 | +- Not done yet: docs/README still describe the agent (docs phase at the end of the plan); `razorbill.yaml` at the repo root (user's agent file from `rzb init`) left in place — ask. Next: step 2 = #32 (Hummingbird 2, RazorbillServer, `rzb serve`). | |
| @@ -45,3 +45,10 @@ v0.1 implemented, quality gate PASS, docs EN+FR written, README and `summary.md` | |||
| 45 | The user wants razorbill to become a model server (MLX only, OpenAI-compatible API) and to leave the agent aside. Tickets #31–#46 written (milestone `v0.2 — OpenAI-compatible MLX server`; #46 in `v0.3 — Decision models`). **Start with #31**: its decisions (keep / freeze / remove `rzb run|chat|tui` — never delete without agreement; `rzb serve` vs separate executable; HTTP framework; v0.2 API surface) gate everything else. Then #32 (server skeleton, testable on Linux with FakeEngine) and #38 (constrained-decoding spike, Mac only). The sbxenv.yaml / qlty-in-sandbox proposal (lifecycle `postCreate` + `sbx env exec`, or a kit) is still waiting for the user's go. | 45 | The user wants razorbill to become a model server (MLX only, OpenAI-compatible API) and to leave the agent aside. Tickets #31–#46 written (milestone `v0.2 — OpenAI-compatible MLX server`; #46 in `v0.3 — Decision models`). **Start with #31**: its decisions (keep / freeze / remove `rzb run|chat|tui` — never delete without agreement; `rzb serve` vs separate executable; HTTP framework; v0.2 API surface) gate everything else. Then #32 (server skeleton, testable on Linux with FakeEngine) and #38 (constrained-decoding spike, Mac only). The sbxenv.yaml / qlty-in-sandbox proposal (lifecycle `postCreate` + `sbx env exec`, or a kit) is still waiting for the user's go. |
| 46 | #31's decisions are taken (see its comment #1): next is removing the agent code (task 6 of #31 — the user has agreed to the removal, keep the reused pieces) and the agent-only tickets' fate (#16, #21, #22, #23, #27, #29 not asked yet), then #32. | 46 | #31's decisions are taken (see its comment #1): next is removing the agent code (task 6 of #31 — the user has agreed to the removal, keep the reused pieces) and the agent-only tickets' fate (#16, #21, #22, #23, #27, #29 not asked yet), then #32. |
| 47 | Agent-only tickets #16, #21, #22, #23, #27, #29 closed as wontfix (2026-11-25). #17 is agent-related and still open: ask the user. Next: task 6 of #31 (remove agent code) and #32. | 47 | Agent-only tickets #16, #21, #22, #23, #27, #29 closed as wontfix (2026-11-25). #17 is agent-related and still open: ask the user. Next: task 6 of #31 (remove agent code) and #32. |
| 48 | + | ||
| 49 | +## Update 2026-11-25 — v0.2 step 1 done (agent code removed), awaiting approval | ||
| 50 | + | ||
| 51 | +- v0.1 committed as `84bebb1` on `feature/v0.1-agent-mvp` (author k33g, local only, not pushed), local tag `v0.1-agent`; `__pycache__/` and `*.profraw` added to `.gitignore` (default.profraw left untracked). Work continues on `feature/v0.2-openai-server` (nothing committed there yet). | ||
| 52 | +- Ticket #47 created: spike on the KV cache (prefix reuse across stateless requests, quantized/TurboQuant KV, save/load prompt cache, memory per token). | ||
| 53 | +- Step 1 (#31 task 6, closed): removed TUI module, agent loop, bash tool and tool registry, agent YAML loader/writer/locator/prompt templates, commands init/run/chat/tui/config, examples/agent.yaml and their tests. Kept: models list/pull/rm, version, ModelStore, RecommendedModels, MLX engine, FakeEngine, ThinkingSplitter, ToolSpec/ToolCall, ConfigReader/ConfigError/ConfigValue (now tested directly in ConfigReaderTests), `Quantities` (duration/size parsing, from OptionReader), `GenerationSettings` (moved to Engine/), `DownloadProgress` (from AgentLauncher). Tests: Linux 32, Mac 37 (`host.sh test . razorbill`), swiftlint clean, Release build OK, `rzb --help` shows only models/version. | ||
| 54 | +- Not done yet: docs/README still describe the agent (docs phase at the end of the plan); `razorbill.yaml` at the repo root (user's agent file from `rzb init`) left in place — ask. Next: step 2 = #32 (Hummingbird 2, RazorbillServer, `rzb serve`). | ||
modified
.memory/history.md +8 -0 | @@ -124,3 +124,11 @@ | ||
| 124 | 124 | - **Direction change (end of session)**: the user asked to set the agent aside and go back to a **model server dedicated to MLX exposing an OpenAI-compatible API** (chat, structured output, function calling, embeddings; "decision models" later). Only tickets written, no code: milestones `v0.2 — OpenAI-compatible MLX server` and `v0.3 — Decision models`, 6 epics (OpenAI-compatible server, Chat completions, Structured output, Function calling, Embeddings, Decision models), labels `area::server` / `area::embeddings`, issues #31–#46 (#31 = pivot decisions: fate of the agent commands, `rzb serve` vs separate binary, Hummingbird 2, API surface; #38 spike MLXGuidedGeneration; #46 spike on what "decision models" means). Checked in the resolved mlx-swift-lm 3.32.3 checkout: `MLXGuidedGeneration` (XGrammar: JSON Schema/EBNF/structural tags), `MLXEmbedders` (Bert, NomicBert, Gemma3, Qwen3, LFM2), `MLXRerankers`, `ToolCallFormat` (json, qwen3_5, llama3, mistral, gemma/gemma4, glm4, gpt_oss, kimi_k2…). Validator OK (46 issues). |
| 125 | 125 | - **#31 decided by the user**: drop the agent code but reuse model list/pull/rm, ModelStore, MLX loading, thinking handling, FakeEngine, YAML loader; binary `rzb` (`rzb serve`); Hummingbird 2; OpenAI-compatible API only; 127.0.0.1 default and 0.0.0.0 allowed. Recorded as comment #1 on #31 (tasks 1–4 closed, task 6 "remove the agent code" added), #32 (bind address + warning without API key) and #45 (agent doc pages removed) updated. |
| 126 | 126 | - **2026-11-25**: agent-only tickets #16, #21, #22, #23, #27, #29 closed as `wontfix` (user agreed), each with a comment pointing to #31; #24, #25, #26, #28, #30 kept open. #17 (example custom tool for the agent) still open, not asked. |
| 127 | + | |
| 128 | +## 2026-11-25 — v0.2 step 1: agent code removed (awaiting approval); session resumed | |
| 129 | + | |
| 130 | +- Step 1 of the v0.2 plan (#31 task 6) done on `feature/v0.2-openai-server`, uncommitted: TUI module, | |
| 131 | + agent loop, bash tool, agent YAML loader/writer, commands init/run/chat/tui/config removed; reused | |
| 132 | + pieces kept (details in handoff `2026-11-24-v0-1-implementation.md`). Tests Linux 32, Mac 37. | |
| 133 | +- Resumed in a new session: read memory and ticket #32, no code changed; waiting for the user's | |
| 134 | + approval of step 1 before starting step 2 (#32). | |
| @@ -124,3 +124,11 @@ | |||
| 124 | - **Direction change (end of session)**: the user asked to set the agent aside and go back to a **model server dedicated to MLX exposing an OpenAI-compatible API** (chat, structured output, function calling, embeddings; "decision models" later). Only tickets written, no code: milestones `v0.2 — OpenAI-compatible MLX server` and `v0.3 — Decision models`, 6 epics (OpenAI-compatible server, Chat completions, Structured output, Function calling, Embeddings, Decision models), labels `area::server` / `area::embeddings`, issues #31–#46 (#31 = pivot decisions: fate of the agent commands, `rzb serve` vs separate binary, Hummingbird 2, API surface; #38 spike MLXGuidedGeneration; #46 spike on what "decision models" means). Checked in the resolved mlx-swift-lm 3.32.3 checkout: `MLXGuidedGeneration` (XGrammar: JSON Schema/EBNF/structural tags), `MLXEmbedders` (Bert, NomicBert, Gemma3, Qwen3, LFM2), `MLXRerankers`, `ToolCallFormat` (json, qwen3_5, llama3, mistral, gemma/gemma4, glm4, gpt_oss, kimi_k2…). Validator OK (46 issues). | 124 | - **Direction change (end of session)**: the user asked to set the agent aside and go back to a **model server dedicated to MLX exposing an OpenAI-compatible API** (chat, structured output, function calling, embeddings; "decision models" later). Only tickets written, no code: milestones `v0.2 — OpenAI-compatible MLX server` and `v0.3 — Decision models`, 6 epics (OpenAI-compatible server, Chat completions, Structured output, Function calling, Embeddings, Decision models), labels `area::server` / `area::embeddings`, issues #31–#46 (#31 = pivot decisions: fate of the agent commands, `rzb serve` vs separate binary, Hummingbird 2, API surface; #38 spike MLXGuidedGeneration; #46 spike on what "decision models" means). Checked in the resolved mlx-swift-lm 3.32.3 checkout: `MLXGuidedGeneration` (XGrammar: JSON Schema/EBNF/structural tags), `MLXEmbedders` (Bert, NomicBert, Gemma3, Qwen3, LFM2), `MLXRerankers`, `ToolCallFormat` (json, qwen3_5, llama3, mistral, gemma/gemma4, glm4, gpt_oss, kimi_k2…). Validator OK (46 issues). |
| 125 | - **#31 decided by the user**: drop the agent code but reuse model list/pull/rm, ModelStore, MLX loading, thinking handling, FakeEngine, YAML loader; binary `rzb` (`rzb serve`); Hummingbird 2; OpenAI-compatible API only; 127.0.0.1 default and 0.0.0.0 allowed. Recorded as comment #1 on #31 (tasks 1–4 closed, task 6 "remove the agent code" added), #32 (bind address + warning without API key) and #45 (agent doc pages removed) updated. | 125 | - **#31 decided by the user**: drop the agent code but reuse model list/pull/rm, ModelStore, MLX loading, thinking handling, FakeEngine, YAML loader; binary `rzb` (`rzb serve`); Hummingbird 2; OpenAI-compatible API only; 127.0.0.1 default and 0.0.0.0 allowed. Recorded as comment #1 on #31 (tasks 1–4 closed, task 6 "remove the agent code" added), #32 (bind address + warning without API key) and #45 (agent doc pages removed) updated. |
| 126 | - **2026-11-25**: agent-only tickets #16, #21, #22, #23, #27, #29 closed as `wontfix` (user agreed), each with a comment pointing to #31; #24, #25, #26, #28, #30 kept open. #17 (example custom tool for the agent) still open, not asked. | 126 | - **2026-11-25**: agent-only tickets #16, #21, #22, #23, #27, #29 closed as `wontfix` (user agreed), each with a comment pointing to #31; #24, #25, #26, #28, #30 kept open. #17 (example custom tool for the agent) still open, not asked. |
| 127 | + | ||
| 128 | +## 2026-11-25 — v0.2 step 1: agent code removed (awaiting approval); session resumed | ||
| 129 | + | ||
| 130 | +- Step 1 of the v0.2 plan (#31 task 6) done on `feature/v0.2-openai-server`, uncommitted: TUI module, | ||
| 131 | + agent loop, bash tool, agent YAML loader/writer, commands init/run/chat/tui/config removed; reused | ||
| 132 | + pieces kept (details in handoff `2026-11-24-v0-1-implementation.md`). Tests Linux 32, Mac 37. | ||
| 133 | +- Resumed in a new session: read memory and ticket #32, no code changed; waiting for the user's | ||
| 134 | + approval of step 1 before starting step 2 (#32). | ||
modified
.tickets/issues/0017-extension-points-for-tools-engines-and-front-end.yaml +4 -2 | @@ -6,7 +6,7 @@ author: | ||
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-23T17:21:09.000Z |
| 9 | -updatedAt: 2026-11-25T04:51:58.000Z | |
| 9 | +updatedAt: 2026-11-25T06:00:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "wontfix" |
| 12 | 12 | - "kind::feature" |
| @@ -38,12 +38,14 @@ tasks: | ||
| 38 | 38 | closedAt: 2026-11-23T18:21:17.000Z |
| 39 | 39 | - id: 2 |
| 40 | 40 | title: "Example custom tool" |
| 41 | - state: open | |
| 41 | + state: closed | |
| 42 | 42 | priority: low |
| 43 | 43 | author: |
| 44 | 44 | name: k33g |
| 45 | 45 | email: ph.charriere@gmail.com |
| 46 | 46 | createdAt: 2026-11-23T17:21:09.000Z |
| 47 | + updatedAt: 2026-11-25T06:00:00.000Z | |
| 48 | + closedAt: 2026-11-25T06:00:00.000Z | |
| 47 | 49 | - id: 3 |
| 48 | 50 | title: "How-to: add a tool" |
| 49 | 51 | state: closed |
| @@ -6,7 +6,7 @@ author: | |||
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-23T17:21:09.000Z | 8 | createdAt: 2026-11-23T17:21:09.000Z |
| 9 | -updatedAt: 2026-11-25T04:51:58.000Z | 9 | +updatedAt: 2026-11-25T06:00:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "wontfix" | 11 | - "wontfix" |
| 12 | - "kind::feature" | 12 | - "kind::feature" |
| @@ -38,12 +38,14 @@ tasks: | |||
| 38 | closedAt: 2026-11-23T18:21:17.000Z | 38 | closedAt: 2026-11-23T18:21:17.000Z |
| 39 | - id: 2 | 39 | - id: 2 |
| 40 | title: "Example custom tool" | 40 | title: "Example custom tool" |
| 41 | - state: open | 41 | + state: closed |
| 42 | priority: low | 42 | priority: low |
| 43 | author: | 43 | author: |
| 44 | name: k33g | 44 | name: k33g |
| 45 | email: ph.charriere@gmail.com | 45 | email: ph.charriere@gmail.com |
| 46 | createdAt: 2026-11-23T17:21:09.000Z | 46 | createdAt: 2026-11-23T17:21:09.000Z |
| 47 | + updatedAt: 2026-11-25T06:00:00.000Z | ||
| 48 | + closedAt: 2026-11-25T06:00:00.000Z | ||
| 47 | - id: 3 | 49 | - id: 3 |
| 48 | title: "How-to: add a tool" | 50 | title: "How-to: add a tool" |
| 49 | state: closed | 51 | state: closed |
modified
.tickets/issues/0031-pivot-razorbill-as-an-openai-compatible-mlx-mode.yaml +4 -2 | @@ -6,7 +6,7 @@ author: | ||
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:29:15.000Z | |
| 9 | +updatedAt: 2026-11-25T05:04:45.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::chore" |
| 12 | 12 | - "area::server" |
| @@ -91,12 +91,14 @@ tasks: | ||
| 91 | 91 | createdAt: 2026-11-24T21:17:08.000Z |
| 92 | 92 | - id: 6 |
| 93 | 93 | title: "Remove the agent code, keeping what the server reuses (model list/pull/rm, ModelStore, MLX loading, ThinkingSplitter, FakeEngine, YAML loader)" |
| 94 | - state: open | |
| 94 | + state: closed | |
| 95 | 95 | priority: high |
| 96 | 96 | author: |
| 97 | 97 | name: k33g |
| 98 | 98 | email: ph.charriere@gmail.com |
| 99 | 99 | createdAt: 2026-11-24T21:29:15.000Z |
| 100 | + updatedAt: 2026-11-25T05:04:45.000Z | |
| 101 | + closedAt: 2026-11-25T05:04:45.000Z | |
| 100 | 102 | comments: |
| 101 | 103 | - id: 1 |
| 102 | 104 | author: |
| @@ -6,7 +6,7 @@ author: | |||
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:29:15.000Z | 9 | +updatedAt: 2026-11-25T05:04:45.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::chore" | 11 | - "kind::chore" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -91,12 +91,14 @@ tasks: | |||
| 91 | createdAt: 2026-11-24T21:17:08.000Z | 91 | createdAt: 2026-11-24T21:17:08.000Z |
| 92 | - id: 6 | 92 | - id: 6 |
| 93 | title: "Remove the agent code, keeping what the server reuses (model list/pull/rm, ModelStore, MLX loading, ThinkingSplitter, FakeEngine, YAML loader)" | 93 | title: "Remove the agent code, keeping what the server reuses (model list/pull/rm, ModelStore, MLX loading, ThinkingSplitter, FakeEngine, YAML loader)" |
| 94 | - state: open | 94 | + state: closed |
| 95 | priority: high | 95 | priority: high |
| 96 | author: | 96 | author: |
| 97 | name: k33g | 97 | name: k33g |
| 98 | email: ph.charriere@gmail.com | 98 | email: ph.charriere@gmail.com |
| 99 | createdAt: 2026-11-24T21:29:15.000Z | 99 | createdAt: 2026-11-24T21:29:15.000Z |
| 100 | + updatedAt: 2026-11-25T05:04:45.000Z | ||
| 101 | + closedAt: 2026-11-25T05:04:45.000Z | ||
| 100 | comments: | 102 | comments: |
| 101 | - id: 1 | 103 | - id: 1 |
| 102 | author: | 104 | author: |
added
.tickets/issues/0047-spike-kv-cache-how-it-works-and-what-a-server-ca.yaml +92 -0 | new file mode 100644 | ||
| @@ -0,0 +1,92 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 47 | |
| 3 | +title: "Spike: KV cache — how it works and what a server can do with it" | |
| 4 | +state: open | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-25T04:56:08.000Z | |
| 9 | +updatedAt: 2026-11-25T04:56:08.000Z | |
| 10 | +labels: | |
| 11 | + - "spike" | |
| 12 | + - "area::engine" | |
| 13 | + - "mac-only" | |
| 14 | + - "priority::high" | |
| 15 | +milestone: "v0.2 — OpenAI-compatible MLX server" | |
| 16 | +epic: "Inference engine" | |
| 17 | +related: | |
| 18 | + - 34 | |
| 19 | + - 35 | |
| 20 | + - 26 | |
| 21 | + - 29 | |
| 22 | +body: | | |
| 23 | + Asked by the user (2026-11-25): a ticket on how the KV cache works and what is possible to do with it. | |
| 24 | + | |
| 25 | + ## Why it matters for the server | |
| 26 | + The KV cache holds the attention keys/values of every token already processed, so the model does not recompute the prompt at each new token. An OpenAI client is **stateless**: each `/v1/chat/completions` request resends the whole conversation (#35). Without cache reuse, every turn re-runs the prefill of the full history (system prompt, tool definitions, previous turns) — the main latency cost for long conversations and agents calling us in a loop. The cache is also the biggest memory consumer after the weights (#26, #34). | |
| 27 | + | |
| 28 | + ## What mlx-swift-lm 3.32.3 provides (seen in the resolved checkout) | |
| 29 | + - Cache types: `KVCacheSimple`, `RotatingKVCache` (sliding window, `maxKVSize`), `QuantizedKVCache` (`kvBits` / `kvGroupSize` / `quantizedKVStart`, "affine4" / "affine8"), `TurboQuantKVCache` (`TurboQuantKVCacheConfiguration`), `ChunkedKVCache`. | |
| 30 | + - Prompt-cache helpers: `makePromptCache`, `savePromptCache` / `loadPromptCache` (to disk), `canTrimPromptCache` / `trimPromptCache` (drop the last N tokens). | |
| 31 | + - `KVCacheConfiguration`, `applyKVCacheConfiguration`, `validateKVCacheCompatibility`, `KVCacheRuntimeReport` / `KVCacheStatus` (diagnostics per layer); `KVCacheTree` / `KVCachePlan` / `KVCacheRound` (internal: nested cache topologies, e.g. hybrid models with non-attention state such as Qwen3.5 / Qwen3-Next GatedDelta layers). | |
| 32 | + | |
| 33 | + ## Questions to answer | |
| 34 | + 1. **How it works**, written up for the docs (explanation page): what is stored per layer, size formula (layers × KV heads × head dim × tokens × bytes), why GQA / quantization / sliding windows reduce it, what hybrid models change. | |
| 35 | + 2. **Prefix reuse across requests**: keep the cache of the last request per model and reuse the longest common token prefix of the next one (trim the rest). Compare with a multi-entry prefix cache (LRU of caches keyed by token-prefix hash, like llama-server slots / vLLM automatic prefix caching). Can trimming work for every cache type (rotating, quantized, hybrid state)? | |
| 36 | + 3. **Cached system prompt / tools**: precompute the cache of a fixed prefix declared in the server config, and persist it with `savePromptCache` to start fast. | |
| 37 | + 4. **Memory**: measure cache size per token for 2-3 models; quantized KV (4/8 bits, TurboQuant) — quality and speed cost; a server-wide memory budget for caches; eviction. | |
| 38 | + 5. **Configuration and API**: server settings (`kv_bits`, `max_kv_size`, prefix cache on/off, number of cached entries); report `usage.prompt_tokens_details.cached_tokens` like OpenAI. | |
| 39 | + 6. **Interactions**: thinking (reasoning tokens are usually dropped from history by the chat template, which breaks the prefix — how much reuse remains?), constrained decoding (#38), cancellation, concurrent requests on one model (#34). | |
| 40 | + | |
| 41 | + ## Output | |
| 42 | + A report as a comment (with measurements on the Mac: prefill time with/without reuse on a 4k-token conversation, memory per token), a decision, and implementation tickets. | |
| 43 | +tasks: | |
| 44 | + - id: 1 | |
| 45 | + title: "Read the mlx-swift-lm cache code and write how it works (types, sizes, hybrid models)" | |
| 46 | + state: open | |
| 47 | + priority: high | |
| 48 | + author: | |
| 49 | + name: k33g | |
| 50 | + email: ph.charriere@gmail.com | |
| 51 | + createdAt: 2026-11-25T04:56:08.000Z | |
| 52 | + - id: 2 | |
| 53 | + title: "Prototype prefix reuse between two stateless requests and measure prefill time" | |
| 54 | + state: open | |
| 55 | + priority: high | |
| 56 | + author: | |
| 57 | + name: k33g | |
| 58 | + email: ph.charriere@gmail.com | |
| 59 | + createdAt: 2026-11-25T04:56:08.000Z | |
| 60 | + - id: 3 | |
| 61 | + title: "Check trimming on rotating, quantized and hybrid (GatedDelta) caches" | |
| 62 | + state: open | |
| 63 | + priority: medium | |
| 64 | + author: | |
| 65 | + name: k33g | |
| 66 | + email: ph.charriere@gmail.com | |
| 67 | + createdAt: 2026-11-25T04:56:08.000Z | |
| 68 | + - id: 4 | |
| 69 | + title: "Measure memory per token and the cost of quantized / TurboQuant KV" | |
| 70 | + state: open | |
| 71 | + priority: medium | |
| 72 | + author: | |
| 73 | + name: k33g | |
| 74 | + email: ph.charriere@gmail.com | |
| 75 | + createdAt: 2026-11-25T04:56:08.000Z | |
| 76 | + - id: 5 | |
| 77 | + title: "Evaluate persisted prompt caches (savePromptCache) for fixed system prompts" | |
| 78 | + state: open | |
| 79 | + priority: low | |
| 80 | + author: | |
| 81 | + name: k33g | |
| 82 | + email: ph.charriere@gmail.com | |
| 83 | + createdAt: 2026-11-25T04:56:08.000Z | |
| 84 | + - id: 6 | |
| 85 | + title: "Write the report, decide, and create the implementation tickets" | |
| 86 | + state: open | |
| 87 | + priority: high | |
| 88 | + author: | |
| 89 | + name: k33g | |
| 90 | + email: ph.charriere@gmail.com | |
| 91 | + createdAt: 2026-11-25T04:56:08.000Z | |
| 92 | +comments: [] | |
| new file mode 100644 | |||
| @@ -0,0 +1,92 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 47 | ||
| 3 | +title: "Spike: KV cache — how it works and what a server can do with it" | ||
| 4 | +state: open | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-25T04:56:08.000Z | ||
| 9 | +updatedAt: 2026-11-25T04:56:08.000Z | ||
| 10 | +labels: | ||
| 11 | + - "spike" | ||
| 12 | + - "area::engine" | ||
| 13 | + - "mac-only" | ||
| 14 | + - "priority::high" | ||
| 15 | +milestone: "v0.2 — OpenAI-compatible MLX server" | ||
| 16 | +epic: "Inference engine" | ||
| 17 | +related: | ||
| 18 | + - 34 | ||
| 19 | + - 35 | ||
| 20 | + - 26 | ||
| 21 | + - 29 | ||
| 22 | +body: | | ||
| 23 | + Asked by the user (2026-11-25): a ticket on how the KV cache works and what is possible to do with it. | ||
| 24 | + | ||
| 25 | + ## Why it matters for the server | ||
| 26 | + The KV cache holds the attention keys/values of every token already processed, so the model does not recompute the prompt at each new token. An OpenAI client is **stateless**: each `/v1/chat/completions` request resends the whole conversation (#35). Without cache reuse, every turn re-runs the prefill of the full history (system prompt, tool definitions, previous turns) — the main latency cost for long conversations and agents calling us in a loop. The cache is also the biggest memory consumer after the weights (#26, #34). | ||
| 27 | + | ||
| 28 | + ## What mlx-swift-lm 3.32.3 provides (seen in the resolved checkout) | ||
| 29 | + - Cache types: `KVCacheSimple`, `RotatingKVCache` (sliding window, `maxKVSize`), `QuantizedKVCache` (`kvBits` / `kvGroupSize` / `quantizedKVStart`, "affine4" / "affine8"), `TurboQuantKVCache` (`TurboQuantKVCacheConfiguration`), `ChunkedKVCache`. | ||
| 30 | + - Prompt-cache helpers: `makePromptCache`, `savePromptCache` / `loadPromptCache` (to disk), `canTrimPromptCache` / `trimPromptCache` (drop the last N tokens). | ||
| 31 | + - `KVCacheConfiguration`, `applyKVCacheConfiguration`, `validateKVCacheCompatibility`, `KVCacheRuntimeReport` / `KVCacheStatus` (diagnostics per layer); `KVCacheTree` / `KVCachePlan` / `KVCacheRound` (internal: nested cache topologies, e.g. hybrid models with non-attention state such as Qwen3.5 / Qwen3-Next GatedDelta layers). | ||
| 32 | + | ||
| 33 | + ## Questions to answer | ||
| 34 | + 1. **How it works**, written up for the docs (explanation page): what is stored per layer, size formula (layers × KV heads × head dim × tokens × bytes), why GQA / quantization / sliding windows reduce it, what hybrid models change. | ||
| 35 | + 2. **Prefix reuse across requests**: keep the cache of the last request per model and reuse the longest common token prefix of the next one (trim the rest). Compare with a multi-entry prefix cache (LRU of caches keyed by token-prefix hash, like llama-server slots / vLLM automatic prefix caching). Can trimming work for every cache type (rotating, quantized, hybrid state)? | ||
| 36 | + 3. **Cached system prompt / tools**: precompute the cache of a fixed prefix declared in the server config, and persist it with `savePromptCache` to start fast. | ||
| 37 | + 4. **Memory**: measure cache size per token for 2-3 models; quantized KV (4/8 bits, TurboQuant) — quality and speed cost; a server-wide memory budget for caches; eviction. | ||
| 38 | + 5. **Configuration and API**: server settings (`kv_bits`, `max_kv_size`, prefix cache on/off, number of cached entries); report `usage.prompt_tokens_details.cached_tokens` like OpenAI. | ||
| 39 | + 6. **Interactions**: thinking (reasoning tokens are usually dropped from history by the chat template, which breaks the prefix — how much reuse remains?), constrained decoding (#38), cancellation, concurrent requests on one model (#34). | ||
| 40 | + | ||
| 41 | + ## Output | ||
| 42 | + A report as a comment (with measurements on the Mac: prefill time with/without reuse on a 4k-token conversation, memory per token), a decision, and implementation tickets. | ||
| 43 | +tasks: | ||
| 44 | + - id: 1 | ||
| 45 | + title: "Read the mlx-swift-lm cache code and write how it works (types, sizes, hybrid models)" | ||
| 46 | + state: open | ||
| 47 | + priority: high | ||
| 48 | + author: | ||
| 49 | + name: k33g | ||
| 50 | + email: ph.charriere@gmail.com | ||
| 51 | + createdAt: 2026-11-25T04:56:08.000Z | ||
| 52 | + - id: 2 | ||
| 53 | + title: "Prototype prefix reuse between two stateless requests and measure prefill time" | ||
| 54 | + state: open | ||
| 55 | + priority: high | ||
| 56 | + author: | ||
| 57 | + name: k33g | ||
| 58 | + email: ph.charriere@gmail.com | ||
| 59 | + createdAt: 2026-11-25T04:56:08.000Z | ||
| 60 | + - id: 3 | ||
| 61 | + title: "Check trimming on rotating, quantized and hybrid (GatedDelta) caches" | ||
| 62 | + state: open | ||
| 63 | + priority: medium | ||
| 64 | + author: | ||
| 65 | + name: k33g | ||
| 66 | + email: ph.charriere@gmail.com | ||
| 67 | + createdAt: 2026-11-25T04:56:08.000Z | ||
| 68 | + - id: 4 | ||
| 69 | + title: "Measure memory per token and the cost of quantized / TurboQuant KV" | ||
| 70 | + state: open | ||
| 71 | + priority: medium | ||
| 72 | + author: | ||
| 73 | + name: k33g | ||
| 74 | + email: ph.charriere@gmail.com | ||
| 75 | + createdAt: 2026-11-25T04:56:08.000Z | ||
| 76 | + - id: 5 | ||
| 77 | + title: "Evaluate persisted prompt caches (savePromptCache) for fixed system prompts" | ||
| 78 | + state: open | ||
| 79 | + priority: low | ||
| 80 | + author: | ||
| 81 | + name: k33g | ||
| 82 | + email: ph.charriere@gmail.com | ||
| 83 | + createdAt: 2026-11-25T04:56:08.000Z | ||
| 84 | + - id: 6 | ||
| 85 | + title: "Write the report, decide, and create the implementation tickets" | ||
| 86 | + state: open | ||
| 87 | + priority: high | ||
| 88 | + author: | ||
| 89 | + name: k33g | ||
| 90 | + email: ph.charriere@gmail.com | ||
| 91 | + createdAt: 2026-11-25T04:56:08.000Z | ||
| 92 | +comments: [] | ||
modified
Package.swift +3 -10 | @@ -1,5 +1,5 @@ | ||
| 1 | 1 | // swift-tools-version: 6.2 |
| 2 | -// razorbill — a local AI agent (command `rzb`) that runs its own MLX models on Apple Metal. | |
| 2 | +// razorbill — an MLX model server for Apple Silicon (command `rzb`). | |
| 3 | 3 | // |
| 4 | 4 | // MLX is only declared for macOS: on Linux the whole package still builds and its tests run |
| 5 | 5 | // (`swift test`), simply without the MLX engine. On the Mac, build with `xcodebuild`, because |
| @@ -31,7 +31,7 @@ let package = Package( | ||
| 31 | 31 | .package(url: "https://github.com/jpsim/Yams", from: "5.1.0"), |
| 32 | 32 | ], |
| 33 | 33 | targets: [ |
| 34 | - // Configuration, agent loop, engine and tool protocols, built-in tools. No MLX. | |
| 34 | + // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. | |
| 35 | 35 | .target( |
| 36 | 36 | name: "RazorbillCore", |
| 37 | 37 | dependencies: [.product(name: "Yams", package: "Yams")] |
| @@ -48,20 +48,14 @@ let package = Package( | ||
| 48 | 48 | macOnly("Tokenizers", "swift-transformers"), |
| 49 | 49 | ] |
| 50 | 50 | ), |
| 51 | - // Command-line front-end: commands, line-mode chat, `rzb init` wizard. | |
| 51 | + // Command-line front-end: `rzb models`, `rzb version`. | |
| 52 | 52 | .target( |
| 53 | 53 | name: "RazorbillCLI", |
| 54 | 54 | dependencies: [ |
| 55 | 55 | "RazorbillCore", |
| 56 | - "RazorbillTUI", | |
| 57 | 56 | .product(name: "ArgumentParser", package: "swift-argument-parser"), |
| 58 | 57 | ] |
| 59 | 58 | ), |
| 60 | - // Full-screen terminal front-end on a small ANSI layer of our own. | |
| 61 | - .target( | |
| 62 | - name: "RazorbillTUI", | |
| 63 | - dependencies: ["RazorbillCore"] | |
| 64 | - ), | |
| 65 | 59 | // The `rzb` executable: registers the engines and starts the CLI. |
| 66 | 60 | .executableTarget( |
| 67 | 61 | name: "rzb", |
| @@ -69,7 +63,6 @@ let package = Package( | ||
| 69 | 63 | ), |
| 70 | 64 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), |
| 71 | 65 | .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI"]), |
| 72 | - .testTarget(name: "RazorbillTUITests", dependencies: ["RazorbillTUI"]), | |
| 73 | 66 | // Empty on Linux: the MLX engine only exists on macOS. |
| 74 | 67 | .testTarget( |
| 75 | 68 | name: "RazorbillMLXTests", |
| @@ -1,5 +1,5 @@ | |||
| 1 | // swift-tools-version: 6.2 | 1 | // swift-tools-version: 6.2 |
| 2 | -// razorbill — a local AI agent (command `rzb`) that runs its own MLX models on Apple Metal. | 2 | +// razorbill — an MLX model server for Apple Silicon (command `rzb`). |
| 3 | // | 3 | // |
| 4 | // MLX is only declared for macOS: on Linux the whole package still builds and its tests run | 4 | // MLX is only declared for macOS: on Linux the whole package still builds and its tests run |
| 5 | // (`swift test`), simply without the MLX engine. On the Mac, build with `xcodebuild`, because | 5 | // (`swift test`), simply without the MLX engine. On the Mac, build with `xcodebuild`, because |
| @@ -31,7 +31,7 @@ let package = Package( | |||
| 31 | .package(url: "https://github.com/jpsim/Yams", from: "5.1.0"), | 31 | .package(url: "https://github.com/jpsim/Yams", from: "5.1.0"), |
| 32 | ], | 32 | ], |
| 33 | targets: [ | 33 | targets: [ |
| 34 | - // Configuration, agent loop, engine and tool protocols, built-in tools. No MLX. | 34 | + // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. |
| 35 | .target( | 35 | .target( |
| 36 | name: "RazorbillCore", | 36 | name: "RazorbillCore", |
| 37 | dependencies: [.product(name: "Yams", package: "Yams")] | 37 | dependencies: [.product(name: "Yams", package: "Yams")] |
| @@ -48,20 +48,14 @@ let package = Package( | |||
| 48 | macOnly("Tokenizers", "swift-transformers"), | 48 | macOnly("Tokenizers", "swift-transformers"), |
| 49 | ] | 49 | ] |
| 50 | ), | 50 | ), |
| 51 | - // Command-line front-end: commands, line-mode chat, `rzb init` wizard. | 51 | + // Command-line front-end: `rzb models`, `rzb version`. |
| 52 | .target( | 52 | .target( |
| 53 | name: "RazorbillCLI", | 53 | name: "RazorbillCLI", |
| 54 | dependencies: [ | 54 | dependencies: [ |
| 55 | "RazorbillCore", | 55 | "RazorbillCore", |
| 56 | - "RazorbillTUI", | ||
| 57 | .product(name: "ArgumentParser", package: "swift-argument-parser"), | 56 | .product(name: "ArgumentParser", package: "swift-argument-parser"), |
| 58 | ] | 57 | ] |
| 59 | ), | 58 | ), |
| 60 | - // Full-screen terminal front-end on a small ANSI layer of our own. | ||
| 61 | - .target( | ||
| 62 | - name: "RazorbillTUI", | ||
| 63 | - dependencies: ["RazorbillCore"] | ||
| 64 | - ), | ||
| 65 | // The `rzb` executable: registers the engines and starts the CLI. | 59 | // The `rzb` executable: registers the engines and starts the CLI. |
| 66 | .executableTarget( | 60 | .executableTarget( |
| 67 | name: "rzb", | 61 | name: "rzb", |
| @@ -69,7 +63,6 @@ let package = Package( | |||
| 69 | ), | 63 | ), |
| 70 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), | 64 | .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]), |
| 71 | .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI"]), | 65 | .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI"]), |
| 72 | - .testTarget(name: "RazorbillTUITests", dependencies: ["RazorbillTUI"]), | ||
| 73 | // Empty on Linux: the MLX engine only exists on macOS. | 66 | // Empty on Linux: the MLX engine only exists on macOS. |
| 74 | .testTarget( | 67 | .testTarget( |
| 75 | name: "RazorbillMLXTests", | 68 | name: "RazorbillMLXTests", |
deleted
Sources/RazorbillCLI/AgentLauncher.swift +0 -68 | deleted file mode 100644 | ||
| @@ -1,68 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | - | |
| 4 | -/// Builds a ready-to-use ``Agent`` from the command line: finds and loads the YAML file, | |
| 5 | -/// applies the overrides, creates the tools and the engine, then loads the model. | |
| 6 | -struct AgentLauncher { | |
| 7 | - let environment: CLIEnvironment | |
| 8 | - | |
| 9 | - /// `toolContext` replaces the console confirmations (the TUI asks in its own screen). | |
| 10 | - func launch(_ options: AgentOptions, toolContext: ToolContext? = nil) async throws -> Agent { | |
| 11 | - let path = try environment.configLocator.locate(explicitPath: options.config) | |
| 12 | - let loaded = try environment.configLoader.load(file: path) | |
| 13 | - let config = options.apply( | |
| 14 | - to: loaded, cwd: environment.currentDirectory, home: environment.homeDirectory) | |
| 15 | - let tools = try environment.tools.makeTools( | |
| 16 | - for: config, environment: ToolEnvironment(baseDirectory: environment.currentDirectory)) | |
| 17 | - let engine = try environment.engines.make(options.engine) | |
| 18 | - let agent = Agent( | |
| 19 | - config: config, engine: engine, tools: tools, | |
| 20 | - toolContext: toolContext ?? self.toolContext()) | |
| 21 | - try await agent.load( | |
| 22 | - offline: options.offline, progress: progressReporter(for: config.model)) | |
| 23 | - return agent | |
| 24 | - } | |
| 25 | - | |
| 26 | - /// Tools ask for confirmation on the console. | |
| 27 | - func toolContext() -> ToolContext { | |
| 28 | - let console = environment.console | |
| 29 | - return ToolContext(isInteractive: console.isInteractive) { request in | |
| 30 | - console.writeErrorLine("\n\(request.toolName) wants to run: \(request.summary)") | |
| 31 | - let prompter = Prompter(console: console) | |
| 32 | - return (try? prompter.confirm("Allow?", default: false)) ?? false | |
| 33 | - } | |
| 34 | - } | |
| 35 | - | |
| 36 | - /// Shows download progress on one line (only called when something is downloaded). | |
| 37 | - func progressReporter(for model: ModelReference) -> @Sendable (Double) -> Void { | |
| 38 | - let console = environment.console | |
| 39 | - let state = ProgressLine() | |
| 40 | - return { fraction in | |
| 41 | - guard state.shouldPrint(fraction) else { return } | |
| 42 | - if console.usesColor { | |
| 43 | - console.writeError( | |
| 44 | - "\r\u{1B}[2KDownloading \(model)… \(Formatting.percent(fraction))") | |
| 45 | - if fraction >= 1 { console.writeError("\n") } | |
| 46 | - } else { | |
| 47 | - console.writeErrorLine("Downloading \(model)… \(Formatting.percent(fraction))") | |
| 48 | - } | |
| 49 | - } | |
| 50 | - } | |
| 51 | -} | |
| 52 | - | |
| 53 | -/// Throttles progress output: a new line only when the percentage changes (every 10% without | |
| 54 | -/// colours, so logs stay short). | |
| 55 | -final class ProgressLine: @unchecked Sendable { | |
| 56 | - private let lock = NSLock() | |
| 57 | - private var last = -1 | |
| 58 | - | |
| 59 | - func shouldPrint(_ fraction: Double) -> Bool { | |
| 60 | - let percent = Int(min(max(fraction, 0), 1) * 100) | |
| 61 | - return lock.withLock { | |
| 62 | - let step = percent == 100 ? 100 : percent / 10 * 10 | |
| 63 | - guard step != last else { return false } | |
| 64 | - last = step | |
| 65 | - return true | |
| 66 | - } | |
| 67 | - } | |
| 68 | -} | |
| deleted file mode 100644 | |||
| @@ -1,68 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | - | ||
| 4 | -/// Builds a ready-to-use ``Agent`` from the command line: finds and loads the YAML file, | ||
| 5 | -/// applies the overrides, creates the tools and the engine, then loads the model. | ||
| 6 | -struct AgentLauncher { | ||
| 7 | - let environment: CLIEnvironment | ||
| 8 | - | ||
| 9 | - /// `toolContext` replaces the console confirmations (the TUI asks in its own screen). | ||
| 10 | - func launch(_ options: AgentOptions, toolContext: ToolContext? = nil) async throws -> Agent { | ||
| 11 | - let path = try environment.configLocator.locate(explicitPath: options.config) | ||
| 12 | - let loaded = try environment.configLoader.load(file: path) | ||
| 13 | - let config = options.apply( | ||
| 14 | - to: loaded, cwd: environment.currentDirectory, home: environment.homeDirectory) | ||
| 15 | - let tools = try environment.tools.makeTools( | ||
| 16 | - for: config, environment: ToolEnvironment(baseDirectory: environment.currentDirectory)) | ||
| 17 | - let engine = try environment.engines.make(options.engine) | ||
| 18 | - let agent = Agent( | ||
| 19 | - config: config, engine: engine, tools: tools, | ||
| 20 | - toolContext: toolContext ?? self.toolContext()) | ||
| 21 | - try await agent.load( | ||
| 22 | - offline: options.offline, progress: progressReporter(for: config.model)) | ||
| 23 | - return agent | ||
| 24 | - } | ||
| 25 | - | ||
| 26 | - /// Tools ask for confirmation on the console. | ||
| 27 | - func toolContext() -> ToolContext { | ||
| 28 | - let console = environment.console | ||
| 29 | - return ToolContext(isInteractive: console.isInteractive) { request in | ||
| 30 | - console.writeErrorLine("\n\(request.toolName) wants to run: \(request.summary)") | ||
| 31 | - let prompter = Prompter(console: console) | ||
| 32 | - return (try? prompter.confirm("Allow?", default: false)) ?? false | ||
| 33 | - } | ||
| 34 | - } | ||
| 35 | - | ||
| 36 | - /// Shows download progress on one line (only called when something is downloaded). | ||
| 37 | - func progressReporter(for model: ModelReference) -> @Sendable (Double) -> Void { | ||
| 38 | - let console = environment.console | ||
| 39 | - let state = ProgressLine() | ||
| 40 | - return { fraction in | ||
| 41 | - guard state.shouldPrint(fraction) else { return } | ||
| 42 | - if console.usesColor { | ||
| 43 | - console.writeError( | ||
| 44 | - "\r\u{1B}[2KDownloading \(model)… \(Formatting.percent(fraction))") | ||
| 45 | - if fraction >= 1 { console.writeError("\n") } | ||
| 46 | - } else { | ||
| 47 | - console.writeErrorLine("Downloading \(model)… \(Formatting.percent(fraction))") | ||
| 48 | - } | ||
| 49 | - } | ||
| 50 | - } | ||
| 51 | -} | ||
| 52 | - | ||
| 53 | -/// Throttles progress output: a new line only when the percentage changes (every 10% without | ||
| 54 | -/// colours, so logs stay short). | ||
| 55 | -final class ProgressLine: @unchecked Sendable { | ||
| 56 | - private let lock = NSLock() | ||
| 57 | - private var last = -1 | ||
| 58 | - | ||
| 59 | - func shouldPrint(_ fraction: Double) -> Bool { | ||
| 60 | - let percent = Int(min(max(fraction, 0), 1) * 100) | ||
| 61 | - return lock.withLock { | ||
| 62 | - let step = percent == 100 ? 100 : percent / 10 * 10 | ||
| 63 | - guard step != last else { return false } | ||
| 64 | - last = step | ||
| 65 | - return true | ||
| 66 | - } | ||
| 67 | - } | ||
| 68 | -} | ||
deleted
Sources/RazorbillCLI/AgentOptions.swift +0 -81 | deleted file mode 100644 | ||
| @@ -1,81 +0,0 @@ | ||
| 1 | -import ArgumentParser | |
| 2 | -import Foundation | |
| 3 | -import RazorbillCore | |
| 4 | - | |
| 5 | -/// Options shared by the commands that talk to the agent (`run`, `chat`, `tui`). | |
| 6 | -/// Each option overrides the matching value of the YAML file. | |
| 7 | -public struct AgentOptions: ParsableArguments { | |
| 8 | - @Option( | |
| 9 | - name: .shortAndLong, | |
| 10 | - help: "Agent file (default: ./razorbill.yaml, then ~/.config/razorbill/agent.yaml).") | |
| 11 | - public var config: String? | |
| 12 | - | |
| 13 | - @Option( | |
| 14 | - name: .shortAndLong, | |
| 15 | - help: "Model to use instead of the file's: a Hugging Face id or a local directory.") | |
| 16 | - public var model: String? | |
| 17 | - | |
| 18 | - @Option(help: "Sampling temperature (0 = deterministic).") | |
| 19 | - public var temperature: Double? | |
| 20 | - | |
| 21 | - @Option(help: "Maximum number of tokens per answer.") | |
| 22 | - public var maxTokens: Int? | |
| 23 | - | |
| 24 | - @Flag( | |
| 25 | - inversion: .prefixedNo, | |
| 26 | - help: "Let reasoning models think first (shown unless ui.show_thinking is false).") | |
| 27 | - public var think: Bool? | |
| 28 | - | |
| 29 | - @Option(help: "Most tokens a reasoning model may spend thinking (needs --think).") | |
| 30 | - public var thinkingBudget: Int? | |
| 31 | - | |
| 32 | - @Flag(help: "Use only the models already downloaded; never touch the network.") | |
| 33 | - public var offline = false | |
| 34 | - | |
| 35 | - @Option(help: "Engine running the model (mlx, fake). Default: the first one this build has.") | |
| 36 | - public var engine: String? | |
| 37 | - | |
| 38 | - public init() {} | |
| 39 | - | |
| 40 | - /// `config` with this command line's overrides applied. | |
| 41 | - func apply(to config: AgentConfig, cwd: String, home: String) -> AgentConfig { | |
| 42 | - var config = config | |
| 43 | - if let model { | |
| 44 | - config.model = Self.modelReference(model, cwd: cwd, home: home) | |
| 45 | - } | |
| 46 | - if let temperature { config.generation.temperature = temperature } | |
| 47 | - if let maxTokens { config.generation.maxTokens = maxTokens } | |
| 48 | - if let think { config.generation.thinking = think } | |
| 49 | - if let thinkingBudget { config.generation.thinkingBudget = thinkingBudget } | |
| 50 | - return config | |
| 51 | - } | |
| 52 | - | |
| 53 | - /// A path (`/…`, `./…`, `../…`, `~/…`) is a local model; anything else is a Hugging Face id. | |
| 54 | - static func modelReference(_ text: String, cwd: String, home: String) -> ModelReference { | |
| 55 | - if text.hasPrefix("~/") { | |
| 56 | - return .local( | |
| 57 | - path: URL(fileURLWithPath: home + text.dropFirst()).standardizedFileURL) | |
| 58 | - } | |
| 59 | - if text.hasPrefix("/") { | |
| 60 | - return .local(path: URL(fileURLWithPath: text).standardizedFileURL) | |
| 61 | - } | |
| 62 | - if text.hasPrefix("./") || text.hasPrefix("../") { | |
| 63 | - return .local( | |
| 64 | - path: URL(fileURLWithPath: cwd).appendingPathComponent(text) | |
| 65 | - .standardizedFileURL) | |
| 66 | - } | |
| 67 | - return .huggingFace(id: text, revision: ModelReference.defaultRevision) | |
| 68 | - } | |
| 69 | - | |
| 70 | - public func validate() throws { | |
| 71 | - if let temperature, temperature < 0 { | |
| 72 | - throw ValidationError("--temperature must be 0 or more") | |
| 73 | - } | |
| 74 | - if let maxTokens, maxTokens <= 0 { | |
| 75 | - throw ValidationError("--max-tokens must be more than 0") | |
| 76 | - } | |
| 77 | - if let thinkingBudget, thinkingBudget < 0 { | |
| 78 | - throw ValidationError("--thinking-budget must be 0 or more") | |
| 79 | - } | |
| 80 | - } | |
| 81 | -} | |
| deleted file mode 100644 | |||
| @@ -1,81 +0,0 @@ | |||
| 1 | -import ArgumentParser | ||
| 2 | -import Foundation | ||
| 3 | -import RazorbillCore | ||
| 4 | - | ||
| 5 | -/// Options shared by the commands that talk to the agent (`run`, `chat`, `tui`). | ||
| 6 | -/// Each option overrides the matching value of the YAML file. | ||
| 7 | -public struct AgentOptions: ParsableArguments { | ||
| 8 | - @Option( | ||
| 9 | - name: .shortAndLong, | ||
| 10 | - help: "Agent file (default: ./razorbill.yaml, then ~/.config/razorbill/agent.yaml).") | ||
| 11 | - public var config: String? | ||
| 12 | - | ||
| 13 | - @Option( | ||
| 14 | - name: .shortAndLong, | ||
| 15 | - help: "Model to use instead of the file's: a Hugging Face id or a local directory.") | ||
| 16 | - public var model: String? | ||
| 17 | - | ||
| 18 | - @Option(help: "Sampling temperature (0 = deterministic).") | ||
| 19 | - public var temperature: Double? | ||
| 20 | - | ||
| 21 | - @Option(help: "Maximum number of tokens per answer.") | ||
| 22 | - public var maxTokens: Int? | ||
| 23 | - | ||
| 24 | - @Flag( | ||
| 25 | - inversion: .prefixedNo, | ||
| 26 | - help: "Let reasoning models think first (shown unless ui.show_thinking is false).") | ||
| 27 | - public var think: Bool? | ||
| 28 | - | ||
| 29 | - @Option(help: "Most tokens a reasoning model may spend thinking (needs --think).") | ||
| 30 | - public var thinkingBudget: Int? | ||
| 31 | - | ||
| 32 | - @Flag(help: "Use only the models already downloaded; never touch the network.") | ||
| 33 | - public var offline = false | ||
| 34 | - | ||
| 35 | - @Option(help: "Engine running the model (mlx, fake). Default: the first one this build has.") | ||
| 36 | - public var engine: String? | ||
| 37 | - | ||
| 38 | - public init() {} | ||
| 39 | - | ||
| 40 | - /// `config` with this command line's overrides applied. | ||
| 41 | - func apply(to config: AgentConfig, cwd: String, home: String) -> AgentConfig { | ||
| 42 | - var config = config | ||
| 43 | - if let model { | ||
| 44 | - config.model = Self.modelReference(model, cwd: cwd, home: home) | ||
| 45 | - } | ||
| 46 | - if let temperature { config.generation.temperature = temperature } | ||
| 47 | - if let maxTokens { config.generation.maxTokens = maxTokens } | ||
| 48 | - if let think { config.generation.thinking = think } | ||
| 49 | - if let thinkingBudget { config.generation.thinkingBudget = thinkingBudget } | ||
| 50 | - return config | ||
| 51 | - } | ||
| 52 | - | ||
| 53 | - /// A path (`/…`, `./…`, `../…`, `~/…`) is a local model; anything else is a Hugging Face id. | ||
| 54 | - static func modelReference(_ text: String, cwd: String, home: String) -> ModelReference { | ||
| 55 | - if text.hasPrefix("~/") { | ||
| 56 | - return .local( | ||
| 57 | - path: URL(fileURLWithPath: home + text.dropFirst()).standardizedFileURL) | ||
| 58 | - } | ||
| 59 | - if text.hasPrefix("/") { | ||
| 60 | - return .local(path: URL(fileURLWithPath: text).standardizedFileURL) | ||
| 61 | - } | ||
| 62 | - if text.hasPrefix("./") || text.hasPrefix("../") { | ||
| 63 | - return .local( | ||
| 64 | - path: URL(fileURLWithPath: cwd).appendingPathComponent(text) | ||
| 65 | - .standardizedFileURL) | ||
| 66 | - } | ||
| 67 | - return .huggingFace(id: text, revision: ModelReference.defaultRevision) | ||
| 68 | - } | ||
| 69 | - | ||
| 70 | - public func validate() throws { | ||
| 71 | - if let temperature, temperature < 0 { | ||
| 72 | - throw ValidationError("--temperature must be 0 or more") | ||
| 73 | - } | ||
| 74 | - if let maxTokens, maxTokens <= 0 { | ||
| 75 | - throw ValidationError("--max-tokens must be more than 0") | ||
| 76 | - } | ||
| 77 | - if let thinkingBudget, thinkingBudget < 0 { | ||
| 78 | - throw ValidationError("--thinking-budget must be 0 or more") | ||
| 79 | - } | ||
| 80 | - } | ||
| 81 | -} | ||
modified
Sources/RazorbillCLI/CLIEnvironment.swift +3 -27 | @@ -1,4 +1,3 @@ | ||
| 1 | -import Foundation | |
| 2 | 1 | import RazorbillCore |
| 3 | 2 | |
| 4 | 3 | /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests |
| @@ -13,45 +12,22 @@ import RazorbillCore | ||
| 13 | 12 | /// ``` |
| 14 | 13 | public struct CLIEnvironment: Sendable { |
| 15 | 14 | public var engines: EngineRegistry |
| 16 | - public var tools: ToolRegistry | |
| 17 | 15 | public var console: any Console |
| 18 | 16 | public var modelStore: ModelStore |
| 19 | - public var currentDirectory: String | |
| 20 | - public var homeDirectory: String | |
| 21 | - public var templateContext: TemplateContext | |
| 22 | 17 | |
| 23 | - public init( | |
| 24 | - engines: EngineRegistry, tools: ToolRegistry, console: any Console, modelStore: ModelStore, | |
| 25 | - currentDirectory: String, homeDirectory: String, templateContext: TemplateContext | |
| 26 | - ) { | |
| 18 | + public init(engines: EngineRegistry, console: any Console, modelStore: ModelStore) { | |
| 27 | 19 | self.engines = engines |
| 28 | - self.tools = tools | |
| 29 | 20 | self.console = console |
| 30 | 21 | self.modelStore = modelStore |
| 31 | - self.currentDirectory = currentDirectory | |
| 32 | - self.homeDirectory = homeDirectory | |
| 33 | - self.templateContext = templateContext | |
| 34 | 22 | } |
| 35 | 23 | |
| 36 | - /// The real terminal, file system and environment, with the given engines. | |
| 24 | + /// The real terminal and model cache, with the given engines. | |
| 37 | 25 | public static func standard(engines: EngineRegistry) -> CLIEnvironment { |
| 38 | - CLIEnvironment( | |
| 39 | - engines: engines, tools: .builtIn, console: StandardConsole(), modelStore: ModelStore(), | |
| 40 | - currentDirectory: FileManager.default.currentDirectoryPath, | |
| 41 | - homeDirectory: NSHomeDirectory(), | |
| 42 | - templateContext: .current) | |
| 26 | + CLIEnvironment(engines: engines, console: StandardConsole(), modelStore: ModelStore()) | |
| 43 | 27 | } |
| 44 | 28 | |
| 45 | 29 | /// The environment the running command uses. |
| 46 | 30 | @TaskLocal public static var current: CLIEnvironment = .standard(engines: EngineRegistry()) |
| 47 | 31 | |
| 48 | - var configLoader: ConfigLoader { | |
| 49 | - ConfigLoader(context: templateContext, homeDirectory: homeDirectory) | |
| 50 | - } | |
| 51 | - | |
| 52 | - var configLocator: ConfigLocator { | |
| 53 | - ConfigLocator(currentDirectory: currentDirectory, homeDirectory: homeDirectory) | |
| 54 | - } | |
| 55 | - | |
| 56 | 32 | var prompter: Prompter { Prompter(console: console) } |
| 57 | 33 | } |
| @@ -1,4 +1,3 @@ | |||
| 1 | -import Foundation | ||
| 2 | import RazorbillCore | 1 | import RazorbillCore |
| 3 | 2 | ||
| 4 | /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests | 3 | /// Everything the commands depend on. The `rzb` executable fills it in at start-up; tests |
| @@ -13,45 +12,22 @@ import RazorbillCore | |||
| 13 | /// ``` | 12 | /// ``` |
| 14 | public struct CLIEnvironment: Sendable { | 13 | public struct CLIEnvironment: Sendable { |
| 15 | public var engines: EngineRegistry | 14 | public var engines: EngineRegistry |
| 16 | - public var tools: ToolRegistry | ||
| 17 | public var console: any Console | 15 | public var console: any Console |
| 18 | public var modelStore: ModelStore | 16 | public var modelStore: ModelStore |
| 19 | - public var currentDirectory: String | ||
| 20 | - public var homeDirectory: String | ||
| 21 | - public var templateContext: TemplateContext | ||
| 22 | 17 | ||
| 23 | - public init( | 18 | + public init(engines: EngineRegistry, console: any Console, modelStore: ModelStore) { |
| 24 | - engines: EngineRegistry, tools: ToolRegistry, console: any Console, modelStore: ModelStore, | ||
| 25 | - currentDirectory: String, homeDirectory: String, templateContext: TemplateContext | ||
| 26 | - ) { | ||
| 27 | self.engines = engines | 19 | self.engines = engines |
| 28 | - self.tools = tools | ||
| 29 | self.console = console | 20 | self.console = console |
| 30 | self.modelStore = modelStore | 21 | self.modelStore = modelStore |
| 31 | - self.currentDirectory = currentDirectory | ||
| 32 | - self.homeDirectory = homeDirectory | ||
| 33 | - self.templateContext = templateContext | ||
| 34 | } | 22 | } |
| 35 | 23 | ||
| 36 | - /// The real terminal, file system and environment, with the given engines. | 24 | + /// The real terminal and model cache, with the given engines. |
| 37 | public static func standard(engines: EngineRegistry) -> CLIEnvironment { | 25 | public static func standard(engines: EngineRegistry) -> CLIEnvironment { |
| 38 | - CLIEnvironment( | 26 | + CLIEnvironment(engines: engines, console: StandardConsole(), modelStore: ModelStore()) |
| 39 | - engines: engines, tools: .builtIn, console: StandardConsole(), modelStore: ModelStore(), | ||
| 40 | - currentDirectory: FileManager.default.currentDirectoryPath, | ||
| 41 | - homeDirectory: NSHomeDirectory(), | ||
| 42 | - templateContext: .current) | ||
| 43 | } | 27 | } |
| 44 | 28 | ||
| 45 | /// The environment the running command uses. | 29 | /// The environment the running command uses. |
| 46 | @TaskLocal public static var current: CLIEnvironment = .standard(engines: EngineRegistry()) | 30 | @TaskLocal public static var current: CLIEnvironment = .standard(engines: EngineRegistry()) |
| 47 | 31 | ||
| 48 | - var configLoader: ConfigLoader { | ||
| 49 | - ConfigLoader(context: templateContext, homeDirectory: homeDirectory) | ||
| 50 | - } | ||
| 51 | - | ||
| 52 | - var configLocator: ConfigLocator { | ||
| 53 | - ConfigLocator(currentDirectory: currentDirectory, homeDirectory: homeDirectory) | ||
| 54 | - } | ||
| 55 | - | ||
| 56 | var prompter: Prompter { Prompter(console: console) } | 32 | var prompter: Prompter { Prompter(console: console) } |
| 57 | } | 33 | } |
deleted
Sources/RazorbillCLI/Commands/ChatCommand.swift +0 -57 | deleted file mode 100644 | ||
| @@ -1,57 +0,0 @@ | ||
| 1 | -import ArgumentParser | |
| 2 | -import RazorbillCore | |
| 3 | - | |
| 4 | -/// `rzb chat`: a conversation, line by line, in a plain terminal. | |
| 5 | -struct ChatCommand: AsyncParsableCommand { | |
| 6 | - static let configuration = CommandConfiguration( | |
| 7 | - commandName: "chat", | |
| 8 | - abstract: | |
| 9 | - "Talk with the agent line by line (/reset to start over, /exit or Ctrl-D to quit)." | |
| 10 | - ) | |
| 11 | - | |
| 12 | - @OptionGroup var agent: AgentOptions | |
| 13 | - | |
| 14 | - func run() async throws { | |
| 15 | - let environment = CLIEnvironment.current | |
| 16 | - let console = environment.console | |
| 17 | - try await reportingErrors(console) { | |
| 18 | - let agent = try await AgentLauncher(environment: environment).launch(self.agent) | |
| 19 | - console.writeErrorLine( | |
| 20 | - console.dimmed( | |
| 21 | - "\(agent.config.name) · \(agent.config.model) · \(agent.engineName) — /help for commands" | |
| 22 | - )) | |
| 23 | - try await Self.loop(agent, console: console) | |
| 24 | - } | |
| 25 | - } | |
| 26 | - | |
| 27 | - static func loop(_ agent: Agent, console: any Console) async throws { | |
| 28 | - while true { | |
| 29 | - console.writeError("› ") | |
| 30 | - guard let line = console.readLine() else { | |
| 31 | - console.writeError("\n") | |
| 32 | - return | |
| 33 | - } | |
| 34 | - let input = line.trimmingCharacters(in: .whitespaces) | |
| 35 | - switch input { | |
| 36 | - case "": | |
| 37 | - continue | |
| 38 | - case "/exit", "/quit": | |
| 39 | - return | |
| 40 | - case "/reset": | |
| 41 | - await agent.reset() | |
| 42 | - console.writeErrorLine(console.dimmed("(new conversation)")) | |
| 43 | - case "/help": | |
| 44 | - console.writeErrorLine("/reset start a new conversation\n/exit quit (or Ctrl-D)") | |
| 45 | - default: | |
| 46 | - do { | |
| 47 | - try await answer(input, with: agent, on: console) | |
| 48 | - } catch let error as CancellationError { | |
| 49 | - throw error | |
| 50 | - } catch { | |
| 51 | - // One failed answer does not end the conversation. | |
| 52 | - console.writeErrorLine("error: \(error)") | |
| 53 | - } | |
| 54 | - } | |
| 55 | - } | |
| 56 | - } | |
| 57 | -} | |
| deleted file mode 100644 | |||
| @@ -1,57 +0,0 @@ | |||
| 1 | -import ArgumentParser | ||
| 2 | -import RazorbillCore | ||
| 3 | - | ||
| 4 | -/// `rzb chat`: a conversation, line by line, in a plain terminal. | ||
| 5 | -struct ChatCommand: AsyncParsableCommand { | ||
| 6 | - static let configuration = CommandConfiguration( | ||
| 7 | - commandName: "chat", | ||
| 8 | - abstract: | ||
| 9 | - "Talk with the agent line by line (/reset to start over, /exit or Ctrl-D to quit)." | ||
| 10 | - ) | ||
| 11 | - | ||
| 12 | - @OptionGroup var agent: AgentOptions | ||
| 13 | - | ||
| 14 | - func run() async throws { | ||
| 15 | - let environment = CLIEnvironment.current | ||
| 16 | - let console = environment.console | ||
| 17 | - try await reportingErrors(console) { | ||
| 18 | - let agent = try await AgentLauncher(environment: environment).launch(self.agent) | ||
| 19 | - console.writeErrorLine( | ||
| 20 | - console.dimmed( | ||
| 21 | - "\(agent.config.name) · \(agent.config.model) · \(agent.engineName) — /help for commands" | ||
| 22 | - )) | ||
| 23 | - try await Self.loop(agent, console: console) | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | - | ||
| 27 | - static func loop(_ agent: Agent, console: any Console) async throws { | ||
| 28 | - while true { | ||
| 29 | - console.writeError("› ") | ||
| 30 | - guard let line = console.readLine() else { | ||
| 31 | - console.writeError("\n") | ||
| 32 | - return | ||
| 33 | - } | ||
| 34 | - let input = line.trimmingCharacters(in: .whitespaces) | ||
| 35 | - switch input { | ||
| 36 | - case "": | ||
| 37 | - continue | ||
| 38 | - case "/exit", "/quit": | ||
| 39 | - return | ||
| 40 | - case "/reset": | ||
| 41 | - await agent.reset() | ||
| 42 | - console.writeErrorLine(console.dimmed("(new conversation)")) | ||
| 43 | - case "/help": | ||
| 44 | - console.writeErrorLine("/reset start a new conversation\n/exit quit (or Ctrl-D)") | ||
| 45 | - default: | ||
| 46 | - do { | ||
| 47 | - try await answer(input, with: agent, on: console) | ||
| 48 | - } catch let error as CancellationError { | ||
| 49 | - throw error | ||
| 50 | - } catch { | ||
| 51 | - // One failed answer does not end the conversation. | ||
| 52 | - console.writeErrorLine("error: \(error)") | ||
| 53 | - } | ||
| 54 | - } | ||
| 55 | - } | ||
| 56 | - } | ||
| 57 | -} | ||
deleted
Sources/RazorbillCLI/Commands/ConfigCommand.swift +0 -34 | deleted file mode 100644 | ||
| @@ -1,34 +0,0 @@ | ||
| 1 | -import ArgumentParser | |
| 2 | -import RazorbillCore | |
| 3 | - | |
| 4 | -/// `rzb config validate [file]`. | |
| 5 | -struct ConfigCommand: AsyncParsableCommand { | |
| 6 | - static let configuration = CommandConfiguration( | |
| 7 | - commandName: "config", | |
| 8 | - abstract: "Work with agent files.", | |
| 9 | - subcommands: [Validate.self] | |
| 10 | - ) | |
| 11 | - | |
| 12 | - struct Validate: AsyncParsableCommand { | |
| 13 | - static let configuration = CommandConfiguration( | |
| 14 | - abstract: "Check an agent file: keys, types, values, variables and tools.") | |
| 15 | - | |
| 16 | - @Argument(help: "The file (default: the one rzb would use).") | |
| 17 | - var file: String? | |
| 18 | - | |
| 19 | - func run() async throws { | |
| 20 | - let environment = CLIEnvironment.current | |
| 21 | - try await reportingErrors(environment.console) { | |
| 22 | - let path = try environment.configLocator.locate(explicitPath: file) | |
| 23 | - let config = try environment.configLoader.load(file: path) | |
| 24 | - _ = try environment.tools.makeTools( | |
| 25 | - for: config, | |
| 26 | - environment: ToolEnvironment(baseDirectory: environment.currentDirectory)) | |
| 27 | - let tools = config.tools.keys.sorted().joined(separator: ", ") | |
| 28 | - environment.console.write( | |
| 29 | - "\(path) is valid: agent \"\(config.name)\", model \(config.model), " | |
| 30 | - + "tools: \(tools.isEmpty ? "none" : tools)\n") | |
| 31 | - } | |
| 32 | - } | |
| 33 | - } | |
| 34 | -} | |
| deleted file mode 100644 | |||
| @@ -1,34 +0,0 @@ | |||
| 1 | -import ArgumentParser | ||
| 2 | -import RazorbillCore | ||
| 3 | - | ||
| 4 | -/// `rzb config validate [file]`. | ||
| 5 | -struct ConfigCommand: AsyncParsableCommand { | ||
| 6 | - static let configuration = CommandConfiguration( | ||
| 7 | - commandName: "config", | ||
| 8 | - abstract: "Work with agent files.", | ||
| 9 | - subcommands: [Validate.self] | ||
| 10 | - ) | ||
| 11 | - | ||
| 12 | - struct Validate: AsyncParsableCommand { | ||
| 13 | - static let configuration = CommandConfiguration( | ||
| 14 | - abstract: "Check an agent file: keys, types, values, variables and tools.") | ||
| 15 | - | ||
| 16 | - @Argument(help: "The file (default: the one rzb would use).") | ||
| 17 | - var file: String? | ||
| 18 | - | ||
| 19 | - func run() async throws { | ||
| 20 | - let environment = CLIEnvironment.current | ||
| 21 | - try await reportingErrors(environment.console) { | ||
| 22 | - let path = try environment.configLocator.locate(explicitPath: file) | ||
| 23 | - let config = try environment.configLoader.load(file: path) | ||
| 24 | - _ = try environment.tools.makeTools( | ||
| 25 | - for: config, | ||
| 26 | - environment: ToolEnvironment(baseDirectory: environment.currentDirectory)) | ||
| 27 | - let tools = config.tools.keys.sorted().joined(separator: ", ") | ||
| 28 | - environment.console.write( | ||
| 29 | - "\(path) is valid: agent \"\(config.name)\", model \(config.model), " | ||
| 30 | - + "tools: \(tools.isEmpty ? "none" : tools)\n") | ||
| 31 | - } | ||
| 32 | - } | ||
| 33 | - } | ||
| 34 | -} | ||
deleted
Sources/RazorbillCLI/Commands/InitCommand.swift +0 -221 | deleted file mode 100644 | ||
| @@ -1,221 +0,0 @@ | ||
| 1 | -import ArgumentParser | |
| 2 | -import Foundation | |
| 3 | -import RazorbillCore | |
| 4 | - | |
| 5 | -/// `rzb init`: asks a few questions and writes the agent's YAML file. | |
| 6 | -struct InitCommand: AsyncParsableCommand { | |
| 7 | - static let configuration = CommandConfiguration( | |
| 8 | - commandName: "init", | |
| 9 | - abstract: "Create an agent file with a wizard (pick a model, a prompt, tools).", | |
| 10 | - discussion: | |
| 11 | - "Without a terminal, use --yes: rzb init --yes --name helper --model mlx-community/Qwen3-1.7B-4bit" | |
| 12 | - ) | |
| 13 | - | |
| 14 | - @Option(name: .shortAndLong, help: "File to write.") | |
| 15 | - var output = ConfigLocator.localFileName | |
| 16 | - | |
| 17 | - @Flag(help: "Overwrite the file if it exists.") | |
| 18 | - var force = false | |
| 19 | - | |
| 20 | - @Option(help: "Agent name.") | |
| 21 | - var name: String? | |
| 22 | - | |
| 23 | - @Option(help: "Model: a Hugging Face id or a local directory.") | |
| 24 | - var model: String? | |
| 25 | - | |
| 26 | - @Flag(name: .shortAndLong, help: "Ask nothing: use the options given and the defaults.") | |
| 27 | - var yes = false | |
| 28 | - | |
| 29 | - @Flag(help: "Do not offer to download the model.") | |
| 30 | - var noDownload = false | |
| 31 | - | |
| 32 | - func run() async throws { | |
| 33 | - let environment = CLIEnvironment.current | |
| 34 | - try await reportingErrors(environment.console) { | |
| 35 | - try await InitWizard(environment: environment, command: self).run() | |
| 36 | - } | |
| 37 | - } | |
| 38 | -} | |
| 39 | - | |
| 40 | -/// The questions of `rzb init`, in order. | |
| 41 | -struct InitWizard { | |
| 42 | - let environment: CLIEnvironment | |
| 43 | - let command: InitCommand | |
| 44 | - | |
| 45 | - private var console: any Console { environment.console } | |
| 46 | - private var prompter: Prompter { environment.prompter } | |
| 47 | - | |
| 48 | - func run() async throws { | |
| 49 | - let interactive = !command.yes | |
| 50 | - if interactive, !console.isInteractive { | |
| 51 | - console.writeErrorLine( | |
| 52 | - "error: rzb init needs a terminal; without one, use --yes (with --name and --model)" | |
| 53 | - ) | |
| 54 | - throw ExitStatus.failure | |
| 55 | - } | |
| 56 | - let path = absolute(command.output) | |
| 57 | - if FileManager.default.fileExists(atPath: path), !command.force { | |
| 58 | - guard interactive, | |
| 59 | - try prompter.confirm("\(command.output) exists. Overwrite it?", default: false) | |
| 60 | - else { | |
| 61 | - console.writeErrorLine("error: \(command.output) exists (use --force to overwrite)") | |
| 62 | - throw ExitStatus.failure | |
| 63 | - } | |
| 64 | - } | |
| 65 | - | |
| 66 | - let draft = interactive ? try askDraft() : try defaultDraft() | |
| 67 | - let yaml = ConfigWriter.yaml(for: draft) | |
| 68 | - // Never write a file rzb cannot load. | |
| 69 | - _ = try environment.configLoader.parse(yaml, file: command.output) | |
| 70 | - | |
| 71 | - if interactive { | |
| 72 | - console.writeErrorLine("\n" + console.dimmed(yaml)) | |
| 73 | - guard try prompter.confirm("Write \(command.output)?", default: true) else { return } | |
| 74 | - } | |
| 75 | - try yaml.write(toFile: path, atomically: true, encoding: .utf8) | |
| 76 | - console.writeErrorLine("Wrote \(command.output). Next: rzb chat --config \(command.output)") | |
| 77 | - try await offerDownload(draft.model, interactive: interactive) | |
| 78 | - } | |
| 79 | - | |
| 80 | - private func defaultDraft() throws -> AgentDraft { | |
| 81 | - AgentDraft( | |
| 82 | - name: command.name ?? "assistant", | |
| 83 | - model: command.model.map(modelReference) | |
| 84 | - ?? .huggingFace(id: RecommendedModels.all[1].id, revision: "main")) | |
| 85 | - } | |
| 86 | - | |
| 87 | - private func askDraft() throws -> AgentDraft { | |
| 88 | - console.writeErrorLine( | |
| 89 | - "Let's create an agent. Press Enter to keep the value in [brackets].\n") | |
| 90 | - let name = try prompter.ask("Agent name", default: command.name ?? "assistant") { | |
| 91 | - $0.isEmpty ? nil : $0 | |
| 92 | - } | |
| 93 | - let description = try prompter.ask("Description (optional)") | |
| 94 | - let model = try command.model.map(modelReference) ?? askModel() | |
| 95 | - let system = try prompter.ask("System prompt", default: ConfigWriter.defaultSystemPrompt) | |
| 96 | - let generation = try askGeneration() | |
| 97 | - // Only worth asking when the model thinks; otherwise keep the default. | |
| 98 | - let showThinking = | |
| 99 | - generation.thinking | |
| 100 | - ? try prompter.confirm("Show the model's thinking?", default: true) : true | |
| 101 | - let tools = try environment.tools.names.filter { tool in | |
| 102 | - try prompter.confirm( | |
| 103 | - "Enable the built-in tool `\(tool)`\(Self.toolHint(tool))?", default: false) | |
| 104 | - } | |
| 105 | - return AgentDraft( | |
| 106 | - name: name, description: description, model: model, system: system, | |
| 107 | - generation: generation, tools: tools, showThinking: showThinking) | |
| 108 | - } | |
| 109 | - | |
| 110 | - private func askGeneration() throws -> GenerationSettings { | |
| 111 | - let temperature = try prompter.ask( | |
| 112 | - "Temperature (0 = deterministic)", default: "0.6", parse: Self.nonNegativeNumber) | |
| 113 | - let maxTokens = try prompter.ask( | |
| 114 | - "Maximum tokens per answer", default: "1024", parse: Self.positiveInteger) | |
| 115 | - let thinking = try prompter.confirm( | |
| 116 | - "Let reasoning models think before answering?", default: false) | |
| 117 | - let budget = | |
| 118 | - thinking | |
| 119 | - ? try prompter.ask("Thinking budget in tokens (empty = no limit)", default: "") { | |
| 120 | - Self.thinkingBudget($0, maxTokens: maxTokens) | |
| 121 | - } : nil | |
| 122 | - return GenerationSettings( | |
| 123 | - temperature: temperature, maxTokens: maxTokens, thinking: thinking, | |
| 124 | - thinkingBudget: budget) | |
| 125 | - } | |
| 126 | - | |
| 127 | - /// The available models: downloaded ones first, then recommended ones, then free input. | |
| 128 | - private func askModel() throws -> ModelReference { | |
| 129 | - let choices = ModelChoices.make(store: environment.modelStore) | |
| 130 | - let labels = | |
| 131 | - choices.map(\.label) + ["Another Hugging Face id…", "A local model directory…"] | |
| 132 | - let index = try prompter.choose("\nWhich model?", options: labels) | |
| 133 | - if index < choices.count { | |
| 134 | - return .huggingFace(id: choices[index].id, revision: ModelReference.defaultRevision) | |
| 135 | - } | |
| 136 | - if index == choices.count { | |
| 137 | - let id = try prompter.ask( | |
| 138 | - "Hugging Face id (MLX format, e.g. mlx-community/…)", default: "" | |
| 139 | - ) { $0.contains("/") ? $0 : nil } | |
| 140 | - return .huggingFace(id: id, revision: ModelReference.defaultRevision) | |
| 141 | - } | |
| 142 | - let path = try prompter.ask("Directory", default: "") { $0.isEmpty ? nil : $0 } | |
| 143 | - return modelReference( | |
| 144 | - path.hasPrefix("/") || path.hasPrefix("~") || path.hasPrefix(".") ? path : "./" + path) | |
| 145 | - } | |
| 146 | - | |
| 147 | - private func offerDownload(_ model: ModelReference, interactive: Bool) async throws { | |
| 148 | - guard !command.noDownload, case .huggingFace = model, | |
| 149 | - !environment.modelStore.isAvailableLocally(model) | |
| 150 | - else { | |
| 151 | - return | |
| 152 | - } | |
| 153 | - guard interactive, | |
| 154 | - try prompter.confirm("\(model) is not downloaded yet. Download it now?", default: true) | |
| 155 | - else { | |
| 156 | - console.writeErrorLine( | |
| 157 | - "It will be downloaded on first use (or now with: rzb models pull \(model)).") | |
| 158 | - return | |
| 159 | - } | |
| 160 | - let launcher = AgentLauncher(environment: environment) | |
| 161 | - try await environment.engines.make().download( | |
| 162 | - model, progress: launcher.progressReporter(for: model)) | |
| 163 | - } | |
| 164 | - | |
| 165 | - private func modelReference(_ text: String) -> ModelReference { | |
| 166 | - AgentOptions.modelReference( | |
| 167 | - text, cwd: environment.currentDirectory, home: environment.homeDirectory) | |
| 168 | - } | |
| 169 | - | |
| 170 | - private func absolute(_ path: String) -> String { | |
| 171 | - path.hasPrefix("/") | |
| 172 | - ? path | |
| 173 | - : URL(fileURLWithPath: environment.currentDirectory).appendingPathComponent(path).path | |
| 174 | - } | |
| 175 | - | |
| 176 | - static func nonNegativeNumber(_ text: String) -> Double? { | |
| 177 | - Double(text).flatMap { $0 >= 0 ? $0 : nil } | |
| 178 | - } | |
| 179 | - | |
| 180 | - static func positiveInteger(_ text: String) -> Int? { | |
| 181 | - Int(text).flatMap { $0 > 0 ? $0 : nil } | |
| 182 | - } | |
| 183 | - | |
| 184 | - /// Empty is "no limit" (`.some(nil)`); a number must leave room for the answer. | |
| 185 | - static func thinkingBudget(_ text: String, maxTokens: Int) -> Int?? { | |
| 186 | - if text.isEmpty { return .some(nil) } | |
| 187 | - guard let budget = Int(text), budget >= 0, budget < maxTokens else { return nil } | |
| 188 | - return .some(budget) | |
| 189 | - } | |
| 190 | - | |
| 191 | - static func toolHint(_ tool: String) -> String { | |
| 192 | - tool == BashTool.name ? " (runs shell commands, asks before each one)" : "" | |
| 193 | - } | |
| 194 | -} | |
| 195 | - | |
| 196 | -/// One line of the model menu of `rzb init`. | |
| 197 | -struct ModelChoices { | |
| 198 | - let id: String | |
| 199 | - let label: String | |
| 200 | - | |
| 201 | - /// Downloaded models (marked, with their size) then the recommended ones not downloaded yet. | |
| 202 | - static func make(store: ModelStore) -> [ModelChoices] { | |
| 203 | - let downloaded = ((try? store.list()) ?? []).filter { | |
| 204 | - store.isAvailableLocally( | |
| 205 | - .huggingFace(id: $0.id, revision: ModelReference.defaultRevision)) | |
| 206 | - } | |
| 207 | - var choices = downloaded.map { | |
| 208 | - ModelChoices( | |
| 209 | - id: $0.id, label: "\($0.id) (downloaded, \(Formatting.bytes($0.sizeInBytes)))") | |
| 210 | - } | |
| 211 | - let downloadedIDs = Set(downloaded.map(\.id)) | |
| 212 | - for model in RecommendedModels.all where !downloadedIDs.contains(model.id) { | |
| 213 | - let size = Formatting.bytes(model.approximateSize) | |
| 214 | - choices.append( | |
| 215 | - ModelChoices( | |
| 216 | - id: model.id, | |
| 217 | - label: "\(model.id) (about \(size) to download) — \(model.summary)")) | |
| 218 | - } | |
| 219 | - return choices | |
| 220 | - } | |
| 221 | -} | |
| deleted file mode 100644 | |||
| @@ -1,221 +0,0 @@ | |||
| 1 | -import ArgumentParser | ||
| 2 | -import Foundation | ||
| 3 | -import RazorbillCore | ||
| 4 | - | ||
| 5 | -/// `rzb init`: asks a few questions and writes the agent's YAML file. | ||
| 6 | -struct InitCommand: AsyncParsableCommand { | ||
| 7 | - static let configuration = CommandConfiguration( | ||
| 8 | - commandName: "init", | ||
| 9 | - abstract: "Create an agent file with a wizard (pick a model, a prompt, tools).", | ||
| 10 | - discussion: | ||
| 11 | - "Without a terminal, use --yes: rzb init --yes --name helper --model mlx-community/Qwen3-1.7B-4bit" | ||
| 12 | - ) | ||
| 13 | - | ||
| 14 | - @Option(name: .shortAndLong, help: "File to write.") | ||
| 15 | - var output = ConfigLocator.localFileName | ||
| 16 | - | ||
| 17 | - @Flag(help: "Overwrite the file if it exists.") | ||
| 18 | - var force = false | ||
| 19 | - | ||
| 20 | - @Option(help: "Agent name.") | ||
| 21 | - var name: String? | ||
| 22 | - | ||
| 23 | - @Option(help: "Model: a Hugging Face id or a local directory.") | ||
| 24 | - var model: String? | ||
| 25 | - | ||
| 26 | - @Flag(name: .shortAndLong, help: "Ask nothing: use the options given and the defaults.") | ||
| 27 | - var yes = false | ||
| 28 | - | ||
| 29 | - @Flag(help: "Do not offer to download the model.") | ||
| 30 | - var noDownload = false | ||
| 31 | - | ||
| 32 | - func run() async throws { | ||
| 33 | - let environment = CLIEnvironment.current | ||
| 34 | - try await reportingErrors(environment.console) { | ||
| 35 | - try await InitWizard(environment: environment, command: self).run() | ||
| 36 | - } | ||
| 37 | - } | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -/// The questions of `rzb init`, in order. | ||
| 41 | -struct InitWizard { | ||
| 42 | - let environment: CLIEnvironment | ||
| 43 | - let command: InitCommand | ||
| 44 | - | ||
| 45 | - private var console: any Console { environment.console } | ||
| 46 | - private var prompter: Prompter { environment.prompter } | ||
| 47 | - | ||
| 48 | - func run() async throws { | ||
| 49 | - let interactive = !command.yes | ||
| 50 | - if interactive, !console.isInteractive { | ||
| 51 | - console.writeErrorLine( | ||
| 52 | - "error: rzb init needs a terminal; without one, use --yes (with --name and --model)" | ||
| 53 | - ) | ||
| 54 | - throw ExitStatus.failure | ||
| 55 | - } | ||
| 56 | - let path = absolute(command.output) | ||
| 57 | - if FileManager.default.fileExists(atPath: path), !command.force { | ||
| 58 | - guard interactive, | ||
| 59 | - try prompter.confirm("\(command.output) exists. Overwrite it?", default: false) | ||
| 60 | - else { | ||
| 61 | - console.writeErrorLine("error: \(command.output) exists (use --force to overwrite)") | ||
| 62 | - throw ExitStatus.failure | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - | ||
| 66 | - let draft = interactive ? try askDraft() : try defaultDraft() | ||
| 67 | - let yaml = ConfigWriter.yaml(for: draft) | ||
| 68 | - // Never write a file rzb cannot load. | ||
| 69 | - _ = try environment.configLoader.parse(yaml, file: command.output) | ||
| 70 | - | ||
| 71 | - if interactive { | ||
| 72 | - console.writeErrorLine("\n" + console.dimmed(yaml)) | ||
| 73 | - guard try prompter.confirm("Write \(command.output)?", default: true) else { return } | ||
| 74 | - } | ||
| 75 | - try yaml.write(toFile: path, atomically: true, encoding: .utf8) | ||
| 76 | - console.writeErrorLine("Wrote \(command.output). Next: rzb chat --config \(command.output)") | ||
| 77 | - try await offerDownload(draft.model, interactive: interactive) | ||
| 78 | - } | ||
| 79 | - | ||
| 80 | - private func defaultDraft() throws -> AgentDraft { | ||
| 81 | - AgentDraft( | ||
| 82 | - name: command.name ?? "assistant", | ||
| 83 | - model: command.model.map(modelReference) | ||
| 84 | - ?? .huggingFace(id: RecommendedModels.all[1].id, revision: "main")) | ||
| 85 | - } | ||
| 86 | - | ||
| 87 | - private func askDraft() throws -> AgentDraft { | ||
| 88 | - console.writeErrorLine( | ||
| 89 | - "Let's create an agent. Press Enter to keep the value in [brackets].\n") | ||
| 90 | - let name = try prompter.ask("Agent name", default: command.name ?? "assistant") { | ||
| 91 | - $0.isEmpty ? nil : $0 | ||
| 92 | - } | ||
| 93 | - let description = try prompter.ask("Description (optional)") | ||
| 94 | - let model = try command.model.map(modelReference) ?? askModel() | ||
| 95 | - let system = try prompter.ask("System prompt", default: ConfigWriter.defaultSystemPrompt) | ||
| 96 | - let generation = try askGeneration() | ||
| 97 | - // Only worth asking when the model thinks; otherwise keep the default. | ||
| 98 | - let showThinking = | ||
| 99 | - generation.thinking | ||
| 100 | - ? try prompter.confirm("Show the model's thinking?", default: true) : true | ||
| 101 | - let tools = try environment.tools.names.filter { tool in | ||
| 102 | - try prompter.confirm( | ||
| 103 | - "Enable the built-in tool `\(tool)`\(Self.toolHint(tool))?", default: false) | ||
| 104 | - } | ||
| 105 | - return AgentDraft( | ||
| 106 | - name: name, description: description, model: model, system: system, | ||
| 107 | - generation: generation, tools: tools, showThinking: showThinking) | ||
| 108 | - } | ||
| 109 | - | ||
| 110 | - private func askGeneration() throws -> GenerationSettings { | ||
| 111 | - let temperature = try prompter.ask( | ||
| 112 | - "Temperature (0 = deterministic)", default: "0.6", parse: Self.nonNegativeNumber) | ||
| 113 | - let maxTokens = try prompter.ask( | ||
| 114 | - "Maximum tokens per answer", default: "1024", parse: Self.positiveInteger) | ||
| 115 | - let thinking = try prompter.confirm( | ||
| 116 | - "Let reasoning models think before answering?", default: false) | ||
| 117 | - let budget = | ||
| 118 | - thinking | ||
| 119 | - ? try prompter.ask("Thinking budget in tokens (empty = no limit)", default: "") { | ||
| 120 | - Self.thinkingBudget($0, maxTokens: maxTokens) | ||
| 121 | - } : nil | ||
| 122 | - return GenerationSettings( | ||
| 123 | - temperature: temperature, maxTokens: maxTokens, thinking: thinking, | ||
| 124 | - thinkingBudget: budget) | ||
| 125 | - } | ||
| 126 | - | ||
| 127 | - /// The available models: downloaded ones first, then recommended ones, then free input. | ||
| 128 | - private func askModel() throws -> ModelReference { | ||
| 129 | - let choices = ModelChoices.make(store: environment.modelStore) | ||
| 130 | - let labels = | ||
| 131 | - choices.map(\.label) + ["Another Hugging Face id…", "A local model directory…"] | ||
| 132 | - let index = try prompter.choose("\nWhich model?", options: labels) | ||
| 133 | - if index < choices.count { | ||
| 134 | - return .huggingFace(id: choices[index].id, revision: ModelReference.defaultRevision) | ||
| 135 | - } | ||
| 136 | - if index == choices.count { | ||
| 137 | - let id = try prompter.ask( | ||
| 138 | - "Hugging Face id (MLX format, e.g. mlx-community/…)", default: "" | ||
| 139 | - ) { $0.contains("/") ? $0 : nil } | ||
| 140 | - return .huggingFace(id: id, revision: ModelReference.defaultRevision) | ||
| 141 | - } | ||
| 142 | - let path = try prompter.ask("Directory", default: "") { $0.isEmpty ? nil : $0 } | ||
| 143 | - return modelReference( | ||
| 144 | - path.hasPrefix("/") || path.hasPrefix("~") || path.hasPrefix(".") ? path : "./" + path) | ||
| 145 | - } | ||
| 146 | - | ||
| 147 | - private func offerDownload(_ model: ModelReference, interactive: Bool) async throws { | ||
| 148 | - guard !command.noDownload, case .huggingFace = model, | ||
| 149 | - !environment.modelStore.isAvailableLocally(model) | ||
| 150 | - else { | ||
| 151 | - return | ||
| 152 | - } | ||
| 153 | - guard interactive, | ||
| 154 | - try prompter.confirm("\(model) is not downloaded yet. Download it now?", default: true) | ||
| 155 | - else { | ||
| 156 | - console.writeErrorLine( | ||
| 157 | - "It will be downloaded on first use (or now with: rzb models pull \(model)).") | ||
| 158 | - return | ||
| 159 | - } | ||
| 160 | - let launcher = AgentLauncher(environment: environment) | ||
| 161 | - try await environment.engines.make().download( | ||
| 162 | - model, progress: launcher.progressReporter(for: model)) | ||
| 163 | - } | ||
| 164 | - | ||
| 165 | - private func modelReference(_ text: String) -> ModelReference { | ||
| 166 | - AgentOptions.modelReference( | ||
| 167 | - text, cwd: environment.currentDirectory, home: environment.homeDirectory) | ||
| 168 | - } | ||
| 169 | - | ||
| 170 | - private func absolute(_ path: String) -> String { | ||
| 171 | - path.hasPrefix("/") | ||
| 172 | - ? path | ||
| 173 | - : URL(fileURLWithPath: environment.currentDirectory).appendingPathComponent(path).path | ||
| 174 | - } | ||
| 175 | - | ||
| 176 | - static func nonNegativeNumber(_ text: String) -> Double? { | ||
| 177 | - Double(text).flatMap { $0 >= 0 ? $0 : nil } | ||
| 178 | - } | ||
| 179 | - | ||
| 180 | - static func positiveInteger(_ text: String) -> Int? { | ||
| 181 | - Int(text).flatMap { $0 > 0 ? $0 : nil } | ||
| 182 | - } | ||
| 183 | - | ||
| 184 | - /// Empty is "no limit" (`.some(nil)`); a number must leave room for the answer. | ||
| 185 | - static func thinkingBudget(_ text: String, maxTokens: Int) -> Int?? { | ||
| 186 | - if text.isEmpty { return .some(nil) } | ||
| 187 | - guard let budget = Int(text), budget >= 0, budget < maxTokens else { return nil } | ||
| 188 | - return .some(budget) | ||
| 189 | - } | ||
| 190 | - | ||
| 191 | - static func toolHint(_ tool: String) -> String { | ||
| 192 | - tool == BashTool.name ? " (runs shell commands, asks before each one)" : "" | ||
| 193 | - } | ||
| 194 | -} | ||
| 195 | - | ||
| 196 | -/// One line of the model menu of `rzb init`. | ||
| 197 | -struct ModelChoices { | ||
| 198 | - let id: String | ||
| 199 | - let label: String | ||
| 200 | - | ||
| 201 | - /// Downloaded models (marked, with their size) then the recommended ones not downloaded yet. | ||
| 202 | - static func make(store: ModelStore) -> [ModelChoices] { | ||
| 203 | - let downloaded = ((try? store.list()) ?? []).filter { | ||
| 204 | - store.isAvailableLocally( | ||
| 205 | - .huggingFace(id: $0.id, revision: ModelReference.defaultRevision)) | ||
| 206 | - } | ||
| 207 | - var choices = downloaded.map { | ||
| 208 | - ModelChoices( | ||
| 209 | - id: $0.id, label: "\($0.id) (downloaded, \(Formatting.bytes($0.sizeInBytes)))") | ||
| 210 | - } | ||
| 211 | - let downloadedIDs = Set(downloaded.map(\.id)) | ||
| 212 | - for model in RecommendedModels.all where !downloadedIDs.contains(model.id) { | ||
| 213 | - let size = Formatting.bytes(model.approximateSize) | ||
| 214 | - choices.append( | ||
| 215 | - ModelChoices( | ||
| 216 | - id: model.id, | ||
| 217 | - label: "\(model.id) (about \(size) to download) — \(model.summary)")) | ||
| 218 | - } | ||
| 219 | - return choices | ||
| 220 | - } | ||
| 221 | -} | ||
modified
Sources/RazorbillCLI/Commands/ModelsCommand.swift +3 -3 | @@ -58,7 +58,7 @@ struct ModelsCommand: AsyncParsableCommand { | ||
| 58 | 58 | struct Pull: AsyncParsableCommand { |
| 59 | 59 | static let configuration = CommandConfiguration( |
| 60 | 60 | commandName: "pull", |
| 61 | - abstract: "Download a model (or update it) without starting a chat.") | |
| 61 | + abstract: "Download a model (or update it) into the cache.") | |
| 62 | 62 | |
| 63 | 63 | @Argument(help: "Hugging Face id, e.g. mlx-community/Qwen3-1.7B-4bit.") |
| 64 | 64 | var id: String |
| @@ -73,9 +73,9 @@ struct ModelsCommand: AsyncParsableCommand { | ||
| 73 | 73 | let environment = CLIEnvironment.current |
| 74 | 74 | try await reportingErrors(environment.console) { |
| 75 | 75 | let model = ModelReference.huggingFace(id: id, revision: revision) |
| 76 | - let launcher = AgentLauncher(environment: environment) | |
| 76 | + let progress = DownloadProgress(console: environment.console) | |
| 77 | 77 | try await environment.engines.make(engine).download( |
| 78 | - model, progress: launcher.progressReporter(for: model)) | |
| 78 | + model, progress: progress.reporter(for: model)) | |
| 79 | 79 | environment.console.writeErrorLine("\(model) is downloaded.") |
| 80 | 80 | } |
| 81 | 81 | } |
| @@ -58,7 +58,7 @@ struct ModelsCommand: AsyncParsableCommand { | |||
| 58 | struct Pull: AsyncParsableCommand { | 58 | struct Pull: AsyncParsableCommand { |
| 59 | static let configuration = CommandConfiguration( | 59 | static let configuration = CommandConfiguration( |
| 60 | commandName: "pull", | 60 | commandName: "pull", |
| 61 | - abstract: "Download a model (or update it) without starting a chat.") | 61 | + abstract: "Download a model (or update it) into the cache.") |
| 62 | 62 | ||
| 63 | @Argument(help: "Hugging Face id, e.g. mlx-community/Qwen3-1.7B-4bit.") | 63 | @Argument(help: "Hugging Face id, e.g. mlx-community/Qwen3-1.7B-4bit.") |
| 64 | var id: String | 64 | var id: String |
| @@ -73,9 +73,9 @@ struct ModelsCommand: AsyncParsableCommand { | |||
| 73 | let environment = CLIEnvironment.current | 73 | let environment = CLIEnvironment.current |
| 74 | try await reportingErrors(environment.console) { | 74 | try await reportingErrors(environment.console) { |
| 75 | let model = ModelReference.huggingFace(id: id, revision: revision) | 75 | let model = ModelReference.huggingFace(id: id, revision: revision) |
| 76 | - let launcher = AgentLauncher(environment: environment) | 76 | + let progress = DownloadProgress(console: environment.console) |
| 77 | try await environment.engines.make(engine).download( | 77 | try await environment.engines.make(engine).download( |
| 78 | - model, progress: launcher.progressReporter(for: model)) | 78 | + model, progress: progress.reporter(for: model)) |
| 79 | environment.console.writeErrorLine("\(model) is downloaded.") | 79 | environment.console.writeErrorLine("\(model) is downloaded.") |
| 80 | } | 80 | } |
| 81 | } | 81 | } |
deleted
Sources/RazorbillCLI/Commands/RunCommand.swift +0 -42 | deleted file mode 100644 | ||
| @@ -1,42 +0,0 @@ | ||
| 1 | -import ArgumentParser | |
| 2 | -import RazorbillCore | |
| 3 | - | |
| 4 | -/// `rzb run "prompt"`: one answer, then exit. Works in scripts and pipes. | |
| 5 | -struct RunCommand: AsyncParsableCommand { | |
| 6 | - static let configuration = CommandConfiguration( | |
| 7 | - commandName: "run", | |
| 8 | - abstract: "Ask the agent once and print the answer.", | |
| 9 | - discussion: """ | |
| 10 | - The answer goes to standard output; progress, tool calls and statistics go to standard \ | |
| 11 | - error. Piped input is appended to the prompt: git diff | rzb run "Review this change" | |
| 12 | - """ | |
| 13 | - ) | |
| 14 | - | |
| 15 | - @OptionGroup var agent: AgentOptions | |
| 16 | - | |
| 17 | - @Argument(help: "The prompt. When standard input is piped, it is added after the prompt.") | |
| 18 | - var prompt: [String] = [] | |
| 19 | - | |
| 20 | - func run() async throws { | |
| 21 | - let environment = CLIEnvironment.current | |
| 22 | - try await reportingErrors(environment.console) { | |
| 23 | - let text = try Self.compose(prompt, console: environment.console) | |
| 24 | - let agent = try await AgentLauncher(environment: environment).launch(self.agent) | |
| 25 | - try await answer(text, with: agent, on: environment.console) | |
| 26 | - } | |
| 27 | - } | |
| 28 | - | |
| 29 | - /// The arguments, followed by piped standard input when there is some. | |
| 30 | - static func compose(_ words: [String], console: any Console) throws -> String { | |
| 31 | - let argument = words.joined(separator: " ") | |
| 32 | - let piped = | |
| 33 | - console.inputIsTerminal | |
| 34 | - ? "" : console.readAll().trimmingCharacters(in: .whitespacesAndNewlines) | |
| 35 | - let parts = [argument, piped].filter { !$0.isEmpty } | |
| 36 | - guard !parts.isEmpty else { | |
| 37 | - throw ValidationError( | |
| 38 | - "give a prompt, e.g. rzb run \"What is Swift?\", or pipe text into rzb run") | |
| 39 | - } | |
| 40 | - return parts.joined(separator: "\n\n") | |
| 41 | - } | |
| 42 | -} | |
| deleted file mode 100644 | |||
| @@ -1,42 +0,0 @@ | |||
| 1 | -import ArgumentParser | ||
| 2 | -import RazorbillCore | ||
| 3 | - | ||
| 4 | -/// `rzb run "prompt"`: one answer, then exit. Works in scripts and pipes. | ||
| 5 | -struct RunCommand: AsyncParsableCommand { | ||
| 6 | - static let configuration = CommandConfiguration( | ||
| 7 | - commandName: "run", | ||
| 8 | - abstract: "Ask the agent once and print the answer.", | ||
| 9 | - discussion: """ | ||
| 10 | - The answer goes to standard output; progress, tool calls and statistics go to standard \ | ||
| 11 | - error. Piped input is appended to the prompt: git diff | rzb run "Review this change" | ||
| 12 | - """ | ||
| 13 | - ) | ||
| 14 | - | ||
| 15 | - @OptionGroup var agent: AgentOptions | ||
| 16 | - | ||
| 17 | - @Argument(help: "The prompt. When standard input is piped, it is added after the prompt.") | ||
| 18 | - var prompt: [String] = [] | ||
| 19 | - | ||
| 20 | - func run() async throws { | ||
| 21 | - let environment = CLIEnvironment.current | ||
| 22 | - try await reportingErrors(environment.console) { | ||
| 23 | - let text = try Self.compose(prompt, console: environment.console) | ||
| 24 | - let agent = try await AgentLauncher(environment: environment).launch(self.agent) | ||
| 25 | - try await answer(text, with: agent, on: environment.console) | ||
| 26 | - } | ||
| 27 | - } | ||
| 28 | - | ||
| 29 | - /// The arguments, followed by piped standard input when there is some. | ||
| 30 | - static func compose(_ words: [String], console: any Console) throws -> String { | ||
| 31 | - let argument = words.joined(separator: " ") | ||
| 32 | - let piped = | ||
| 33 | - console.inputIsTerminal | ||
| 34 | - ? "" : console.readAll().trimmingCharacters(in: .whitespacesAndNewlines) | ||
| 35 | - let parts = [argument, piped].filter { !$0.isEmpty } | ||
| 36 | - guard !parts.isEmpty else { | ||
| 37 | - throw ValidationError( | ||
| 38 | - "give a prompt, e.g. rzb run \"What is Swift?\", or pipe text into rzb run") | ||
| 39 | - } | ||
| 40 | - return parts.joined(separator: "\n\n") | ||
| 41 | - } | ||
| 42 | -} | ||
modified
Sources/RazorbillCLI/Commands/Rzb.swift +3 -19 | @@ -9,13 +9,9 @@ import RazorbillCore | ||
| 9 | 9 | public struct Rzb: AsyncParsableCommand { |
| 10 | 10 | public static let configuration = CommandConfiguration( |
| 11 | 11 | commandName: "rzb", |
| 12 | - abstract: "razorbill — a local AI agent running its own MLX models.", | |
| 12 | + abstract: "razorbill — an MLX model server for Apple Silicon.", | |
| 13 | 13 | version: Razorbill.version, |
| 14 | - subcommands: [ | |
| 15 | - InitCommand.self, RunCommand.self, ChatCommand.self, TUICommand.self, | |
| 16 | - ModelsCommand.self, | |
| 17 | - ConfigCommand.self, VersionCommand.self, | |
| 18 | - ] | |
| 14 | + subcommands: [ModelsCommand.self, VersionCommand.self] | |
| 19 | 15 | ) |
| 20 | 16 | |
| 21 | 17 | public init() {} |
| @@ -25,7 +21,7 @@ public struct Rzb: AsyncParsableCommand { | ||
| 25 | 21 | enum ExitStatus { |
| 26 | 22 | /// Something failed while running. |
| 27 | 23 | static let failure = ExitCode(1) |
| 28 | - /// The agent file is missing or invalid. | |
| 24 | + /// The configuration file is invalid. | |
| 29 | 25 | static let configuration = ExitCode(2) |
| 30 | 26 | /// Interrupted. |
| 31 | 27 | static let interrupted = ExitCode(130) |
| @@ -42,9 +38,6 @@ func reportingErrors(_ console: any Console, _ body: () async throws -> Void) as | ||
| 42 | 38 | } catch let error as ConfigError { |
| 43 | 39 | console.writeErrorLine("error: \(error)") |
| 44 | 40 | throw ExitStatus.configuration |
| 45 | - } catch let error as ConfigLocator.NotFound { | |
| 46 | - console.writeErrorLine("error: \(error)") | |
| 47 | - throw ExitStatus.configuration | |
| 48 | 41 | } catch is CancellationError { |
| 49 | 42 | throw ExitStatus.interrupted |
| 50 | 43 | } catch { |
| @@ -52,12 +45,3 @@ func reportingErrors(_ console: any Console, _ body: () async throws -> Void) as | ||
| 52 | 45 | throw ExitStatus.failure |
| 53 | 46 | } |
| 54 | 47 | } |
| 55 | - | |
| 56 | -/// Streams one answer of `agent` to the console. | |
| 57 | -func answer(_ prompt: String, with agent: Agent, on console: any Console) async throws { | |
| 58 | - var printer = EventPrinter(console: console, config: agent.config) | |
| 59 | - defer { printer.finish() } | |
| 60 | - for try await event in agent.send(prompt) { | |
| 61 | - printer.print(event) | |
| 62 | - } | |
| 63 | -} | |
| @@ -9,13 +9,9 @@ import RazorbillCore | |||
| 9 | public struct Rzb: AsyncParsableCommand { | 9 | public struct Rzb: AsyncParsableCommand { |
| 10 | public static let configuration = CommandConfiguration( | 10 | public static let configuration = CommandConfiguration( |
| 11 | commandName: "rzb", | 11 | commandName: "rzb", |
| 12 | - abstract: "razorbill — a local AI agent running its own MLX models.", | 12 | + abstract: "razorbill — an MLX model server for Apple Silicon.", |
| 13 | version: Razorbill.version, | 13 | version: Razorbill.version, |
| 14 | - subcommands: [ | 14 | + subcommands: [ModelsCommand.self, VersionCommand.self] |
| 15 | - InitCommand.self, RunCommand.self, ChatCommand.self, TUICommand.self, | ||
| 16 | - ModelsCommand.self, | ||
| 17 | - ConfigCommand.self, VersionCommand.self, | ||
| 18 | - ] | ||
| 19 | ) | 15 | ) |
| 20 | 16 | ||
| 21 | public init() {} | 17 | public init() {} |
| @@ -25,7 +21,7 @@ public struct Rzb: AsyncParsableCommand { | |||
| 25 | enum ExitStatus { | 21 | enum ExitStatus { |
| 26 | /// Something failed while running. | 22 | /// Something failed while running. |
| 27 | static let failure = ExitCode(1) | 23 | static let failure = ExitCode(1) |
| 28 | - /// The agent file is missing or invalid. | 24 | + /// The configuration file is invalid. |
| 29 | static let configuration = ExitCode(2) | 25 | static let configuration = ExitCode(2) |
| 30 | /// Interrupted. | 26 | /// Interrupted. |
| 31 | static let interrupted = ExitCode(130) | 27 | static let interrupted = ExitCode(130) |
| @@ -42,9 +38,6 @@ func reportingErrors(_ console: any Console, _ body: () async throws -> Void) as | |||
| 42 | } catch let error as ConfigError { | 38 | } catch let error as ConfigError { |
| 43 | console.writeErrorLine("error: \(error)") | 39 | console.writeErrorLine("error: \(error)") |
| 44 | throw ExitStatus.configuration | 40 | throw ExitStatus.configuration |
| 45 | - } catch let error as ConfigLocator.NotFound { | ||
| 46 | - console.writeErrorLine("error: \(error)") | ||
| 47 | - throw ExitStatus.configuration | ||
| 48 | } catch is CancellationError { | 41 | } catch is CancellationError { |
| 49 | throw ExitStatus.interrupted | 42 | throw ExitStatus.interrupted |
| 50 | } catch { | 43 | } catch { |
| @@ -52,12 +45,3 @@ func reportingErrors(_ console: any Console, _ body: () async throws -> Void) as | |||
| 52 | throw ExitStatus.failure | 45 | throw ExitStatus.failure |
| 53 | } | 46 | } |
| 54 | } | 47 | } |
| 55 | - | ||
| 56 | -/// Streams one answer of `agent` to the console. | ||
| 57 | -func answer(_ prompt: String, with agent: Agent, on console: any Console) async throws { | ||
| 58 | - var printer = EventPrinter(console: console, config: agent.config) | ||
| 59 | - defer { printer.finish() } | ||
| 60 | - for try await event in agent.send(prompt) { | ||
| 61 | - printer.print(event) | ||
| 62 | - } | ||
| 63 | -} | ||
deleted
Sources/RazorbillCLI/Commands/TUICommand.swift +0 -37 | deleted file mode 100644 | ||
| @@ -1,37 +0,0 @@ | ||
| 1 | -import ArgumentParser | |
| 2 | -import RazorbillCore | |
| 3 | -import RazorbillTUI | |
| 4 | - | |
| 5 | -/// `rzb tui`: the full-screen chat. The model is loaded (and downloaded if needed) first, in the | |
| 6 | -/// normal terminal, then the screen switches to the TUI. | |
| 7 | -struct TUICommand: AsyncParsableCommand { | |
| 8 | - static let configuration = CommandConfiguration( | |
| 9 | - commandName: "tui", | |
| 10 | - abstract: "Talk with the agent in a full-screen terminal UI.", | |
| 11 | - discussion: """ | |
| 12 | - Keys: Enter send · Ctrl-T show/hide thinking · Ctrl-N new conversation · \ | |
| 13 | - PgUp/PgDn or ↑/↓ scroll · Ctrl-C stop the answer, or quit · Ctrl-D quit. \ | |
| 14 | - Commands: /reset, /exit. | |
| 15 | - """ | |
| 16 | - ) | |
| 17 | - | |
| 18 | - @OptionGroup var agent: AgentOptions | |
| 19 | - | |
| 20 | - func run() async throws { | |
| 21 | - let environment = CLIEnvironment.current | |
| 22 | - try await reportingErrors(environment.console) { | |
| 23 | - guard PosixTerminal.isAvailable else { | |
| 24 | - environment.console.writeErrorLine( | |
| 25 | - "error: rzb tui needs a terminal; use rzb run or rzb chat instead") | |
| 26 | - throw ExitStatus.failure | |
| 27 | - } | |
| 28 | - let bridge = ConfirmationBridge() | |
| 29 | - let agent = try await AgentLauncher(environment: environment) | |
| 30 | - .launch(self.agent, toolContext: bridge.toolContext) | |
| 31 | - let app = TUIApp( | |
| 32 | - agent: agent, terminal: PosixTerminal(), bridge: bridge, | |
| 33 | - colors: environment.console.usesColor) | |
| 34 | - await app.run() | |
| 35 | - } | |
| 36 | - } | |
| 37 | -} | |
| deleted file mode 100644 | |||
| @@ -1,37 +0,0 @@ | |||
| 1 | -import ArgumentParser | ||
| 2 | -import RazorbillCore | ||
| 3 | -import RazorbillTUI | ||
| 4 | - | ||
| 5 | -/// `rzb tui`: the full-screen chat. The model is loaded (and downloaded if needed) first, in the | ||
| 6 | -/// normal terminal, then the screen switches to the TUI. | ||
| 7 | -struct TUICommand: AsyncParsableCommand { | ||
| 8 | - static let configuration = CommandConfiguration( | ||
| 9 | - commandName: "tui", | ||
| 10 | - abstract: "Talk with the agent in a full-screen terminal UI.", | ||
| 11 | - discussion: """ | ||
| 12 | - Keys: Enter send · Ctrl-T show/hide thinking · Ctrl-N new conversation · \ | ||
| 13 | - PgUp/PgDn or ↑/↓ scroll · Ctrl-C stop the answer, or quit · Ctrl-D quit. \ | ||
| 14 | - Commands: /reset, /exit. | ||
| 15 | - """ | ||
| 16 | - ) | ||
| 17 | - | ||
| 18 | - @OptionGroup var agent: AgentOptions | ||
| 19 | - | ||
| 20 | - func run() async throws { | ||
| 21 | - let environment = CLIEnvironment.current | ||
| 22 | - try await reportingErrors(environment.console) { | ||
| 23 | - guard PosixTerminal.isAvailable else { | ||
| 24 | - environment.console.writeErrorLine( | ||
| 25 | - "error: rzb tui needs a terminal; use rzb run or rzb chat instead") | ||
| 26 | - throw ExitStatus.failure | ||
| 27 | - } | ||
| 28 | - let bridge = ConfirmationBridge() | ||
| 29 | - let agent = try await AgentLauncher(environment: environment) | ||
| 30 | - .launch(self.agent, toolContext: bridge.toolContext) | ||
| 31 | - let app = TUIApp( | ||
| 32 | - agent: agent, terminal: PosixTerminal(), bridge: bridge, | ||
| 33 | - colors: environment.console.usesColor) | ||
| 34 | - await app.run() | ||
| 35 | - } | ||
| 36 | - } | ||
| 37 | -} | ||
modified
Sources/RazorbillCLI/Console.swift +3 -43 | @@ -7,8 +7,8 @@ import Glibc | ||
| 7 | 7 | #endif |
| 8 | 8 | |
| 9 | 9 | /// The terminal, seen by the commands. Answers go to standard output; everything else |
| 10 | -/// (progress, tool calls, stats, questions) goes to standard error, so `rzb run ... > file` | |
| 11 | -/// keeps only the answer. | |
| 10 | +/// (progress, messages, questions) goes to standard error, so redirecting standard output | |
| 11 | +/// keeps only the results (such as `rzb models list > models.txt`). | |
| 12 | 12 | /// |
| 13 | 13 | /// Tests replace it with a scripted console. |
| 14 | 14 | public protocol Console: Sendable { |
| @@ -18,12 +18,8 @@ public protocol Console: Sendable { | ||
| 18 | 18 | func writeError(_ text: String) |
| 19 | 19 | /// Reads one line of standard input, without its newline; `nil` at the end of input. |
| 20 | 20 | func readLine() -> String? |
| 21 | - /// Reads standard input to its end. | |
| 22 | - func readAll() -> String | |
| 23 | 21 | /// A person can answer questions: standard input and standard error are terminals. |
| 24 | 22 | var isInteractive: Bool { get } |
| 25 | - /// Standard input is a terminal (nothing was piped in). | |
| 26 | - var inputIsTerminal: Bool { get } | |
| 27 | 23 | /// Standard error is a terminal that understands colours. |
| 28 | 24 | var usesColor: Bool { get } |
| 29 | 25 | } |
| @@ -56,15 +52,7 @@ public struct StandardConsole: Console { | ||
| 56 | 52 | Swift.readLine(strippingNewline: true) |
| 57 | 53 | } |
| 58 | 54 | |
| 59 | - /// Piped text that is not UTF-8 is read as Latin-1 rather than dropped. | |
| 60 | - public func readAll() -> String { | |
| 61 | - let data = FileHandle.standardInput.readDataToEndOfFile() | |
| 62 | - return String(bytes: data, encoding: .utf8) ?? String(bytes: data, encoding: .isoLatin1) | |
| 63 | - ?? "" | |
| 64 | - } | |
| 65 | - | |
| 66 | 55 | public var isInteractive: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDERR_FILENO) == 1 } |
| 67 | - public var inputIsTerminal: Bool { isatty(STDIN_FILENO) == 1 } | |
| 68 | 56 | public var usesColor: Bool { |
| 69 | 57 | isatty(STDERR_FILENO) == 1 && ProcessInfo.processInfo.environment["NO_COLOR"] == nil |
| 70 | 58 | } |
| @@ -79,8 +67,7 @@ public struct InputEnded: Error, CustomStringConvertible { | ||
| 79 | 67 | /// |
| 80 | 68 | /// ```swift |
| 81 | 69 | /// let prompter = Prompter(console: StandardConsole()) |
| 82 | -/// let name = try prompter.ask("Agent name", default: "assistant") | |
| 83 | -/// if try prompter.confirm("Download it now?", default: true) { ... } | |
| 70 | +/// if try prompter.confirm("Delete it?", default: false) { ... } | |
| 84 | 71 | /// ``` |
| 85 | 72 | public struct Prompter: Sendable { |
| 86 | 73 | public let console: any Console |
| @@ -111,31 +98,4 @@ public struct Prompter: Sendable { | ||
| 111 | 98 | } |
| 112 | 99 | } |
| 113 | 100 | } |
| 114 | - | |
| 115 | - /// One of `options`, chosen by number (1-based); returns its index. | |
| 116 | - public func choose(_ title: String, options: [String], default index: Int = 0) throws -> Int { | |
| 117 | - console.writeErrorLine(title) | |
| 118 | - for (index, option) in options.enumerated() { | |
| 119 | - console.writeErrorLine(" \(index + 1). \(option)") | |
| 120 | - } | |
| 121 | - while true { | |
| 122 | - let answer = try ask("Choice", default: "\(index + 1)") | |
| 123 | - if let number = Int(answer), (1 ... options.count).contains(number) { | |
| 124 | - return number - 1 | |
| 125 | - } | |
| 126 | - console.writeErrorLine("Please type a number between 1 and \(options.count).") | |
| 127 | - } | |
| 128 | - } | |
| 129 | - | |
| 130 | - /// A value parsed by `parse`, asked again until it is valid. | |
| 131 | - public func ask<Value>( | |
| 132 | - _ question: String, default defaultValue: String, parse: (String) -> Value? | |
| 133 | - ) throws -> Value { | |
| 134 | - while true { | |
| 135 | - if let value = parse(try ask(question, default: defaultValue)) { | |
| 136 | - return value | |
| 137 | - } | |
| 138 | - console.writeErrorLine("That value is not valid.") | |
| 139 | - } | |
| 140 | - } | |
| 141 | 101 | } |
| @@ -7,8 +7,8 @@ import Glibc | |||
| 7 | #endif | 7 | #endif |
| 8 | 8 | ||
| 9 | /// The terminal, seen by the commands. Answers go to standard output; everything else | 9 | /// The terminal, seen by the commands. Answers go to standard output; everything else |
| 10 | -/// (progress, tool calls, stats, questions) goes to standard error, so `rzb run ... > file` | 10 | +/// (progress, messages, questions) goes to standard error, so redirecting standard output |
| 11 | -/// keeps only the answer. | 11 | +/// keeps only the results (such as `rzb models list > models.txt`). |
| 12 | /// | 12 | /// |
| 13 | /// Tests replace it with a scripted console. | 13 | /// Tests replace it with a scripted console. |
| 14 | public protocol Console: Sendable { | 14 | public protocol Console: Sendable { |
| @@ -18,12 +18,8 @@ public protocol Console: Sendable { | |||
| 18 | func writeError(_ text: String) | 18 | func writeError(_ text: String) |
| 19 | /// Reads one line of standard input, without its newline; `nil` at the end of input. | 19 | /// Reads one line of standard input, without its newline; `nil` at the end of input. |
| 20 | func readLine() -> String? | 20 | func readLine() -> String? |
| 21 | - /// Reads standard input to its end. | ||
| 22 | - func readAll() -> String | ||
| 23 | /// A person can answer questions: standard input and standard error are terminals. | 21 | /// A person can answer questions: standard input and standard error are terminals. |
| 24 | var isInteractive: Bool { get } | 22 | var isInteractive: Bool { get } |
| 25 | - /// Standard input is a terminal (nothing was piped in). | ||
| 26 | - var inputIsTerminal: Bool { get } | ||
| 27 | /// Standard error is a terminal that understands colours. | 23 | /// Standard error is a terminal that understands colours. |
| 28 | var usesColor: Bool { get } | 24 | var usesColor: Bool { get } |
| 29 | } | 25 | } |
| @@ -56,15 +52,7 @@ public struct StandardConsole: Console { | |||
| 56 | Swift.readLine(strippingNewline: true) | 52 | Swift.readLine(strippingNewline: true) |
| 57 | } | 53 | } |
| 58 | 54 | ||
| 59 | - /// Piped text that is not UTF-8 is read as Latin-1 rather than dropped. | ||
| 60 | - public func readAll() -> String { | ||
| 61 | - let data = FileHandle.standardInput.readDataToEndOfFile() | ||
| 62 | - return String(bytes: data, encoding: .utf8) ?? String(bytes: data, encoding: .isoLatin1) | ||
| 63 | - ?? "" | ||
| 64 | - } | ||
| 65 | - | ||
| 66 | public var isInteractive: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDERR_FILENO) == 1 } | 55 | public var isInteractive: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDERR_FILENO) == 1 } |
| 67 | - public var inputIsTerminal: Bool { isatty(STDIN_FILENO) == 1 } | ||
| 68 | public var usesColor: Bool { | 56 | public var usesColor: Bool { |
| 69 | isatty(STDERR_FILENO) == 1 && ProcessInfo.processInfo.environment["NO_COLOR"] == nil | 57 | isatty(STDERR_FILENO) == 1 && ProcessInfo.processInfo.environment["NO_COLOR"] == nil |
| 70 | } | 58 | } |
| @@ -79,8 +67,7 @@ public struct InputEnded: Error, CustomStringConvertible { | |||
| 79 | /// | 67 | /// |
| 80 | /// ```swift | 68 | /// ```swift |
| 81 | /// let prompter = Prompter(console: StandardConsole()) | 69 | /// let prompter = Prompter(console: StandardConsole()) |
| 82 | -/// let name = try prompter.ask("Agent name", default: "assistant") | 70 | +/// if try prompter.confirm("Delete it?", default: false) { ... } |
| 83 | -/// if try prompter.confirm("Download it now?", default: true) { ... } | ||
| 84 | /// ``` | 71 | /// ``` |
| 85 | public struct Prompter: Sendable { | 72 | public struct Prompter: Sendable { |
| 86 | public let console: any Console | 73 | public let console: any Console |
| @@ -111,31 +98,4 @@ public struct Prompter: Sendable { | |||
| 111 | } | 98 | } |
| 112 | } | 99 | } |
| 113 | } | 100 | } |
| 114 | - | ||
| 115 | - /// One of `options`, chosen by number (1-based); returns its index. | ||
| 116 | - public func choose(_ title: String, options: [String], default index: Int = 0) throws -> Int { | ||
| 117 | - console.writeErrorLine(title) | ||
| 118 | - for (index, option) in options.enumerated() { | ||
| 119 | - console.writeErrorLine(" \(index + 1). \(option)") | ||
| 120 | - } | ||
| 121 | - while true { | ||
| 122 | - let answer = try ask("Choice", default: "\(index + 1)") | ||
| 123 | - if let number = Int(answer), (1 ... options.count).contains(number) { | ||
| 124 | - return number - 1 | ||
| 125 | - } | ||
| 126 | - console.writeErrorLine("Please type a number between 1 and \(options.count).") | ||
| 127 | - } | ||
| 128 | - } | ||
| 129 | - | ||
| 130 | - /// A value parsed by `parse`, asked again until it is valid. | ||
| 131 | - public func ask<Value>( | ||
| 132 | - _ question: String, default defaultValue: String, parse: (String) -> Value? | ||
| 133 | - ) throws -> Value { | ||
| 134 | - while true { | ||
| 135 | - if let value = parse(try ask(question, default: defaultValue)) { | ||
| 136 | - return value | ||
| 137 | - } | ||
| 138 | - console.writeErrorLine("That value is not valid.") | ||
| 139 | - } | ||
| 140 | - } | ||
| 141 | } | 101 | } |
added
Sources/RazorbillCLI/DownloadProgress.swift +46 -0 | new file mode 100644 | ||
| @@ -0,0 +1,46 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | + | |
| 4 | +/// Shows the download progress of a model on standard error, on one line when colours are | |
| 5 | +/// available, otherwise one line every 10% so logs stay short. | |
| 6 | +/// | |
| 7 | +/// ```swift | |
| 8 | +/// let progress = DownloadProgress(console: console).reporter(for: model) | |
| 9 | +/// try await engine.download(model, progress: progress) | |
| 10 | +/// ``` | |
| 11 | +struct DownloadProgress { | |
| 12 | + let console: any Console | |
| 13 | + | |
| 14 | + /// A progress callback for `model` (only called when something is downloaded). | |
| 15 | + func reporter(for model: ModelReference) -> @Sendable (Double) -> Void { | |
| 16 | + let console = self.console | |
| 17 | + let state = ProgressLine() | |
| 18 | + return { fraction in | |
| 19 | + guard state.shouldPrint(fraction) else { return } | |
| 20 | + if console.usesColor { | |
| 21 | + console.writeError( | |
| 22 | + "\r\u{1B}[2KDownloading \(model)… \(Formatting.percent(fraction))") | |
| 23 | + if fraction >= 1 { console.writeError("\n") } | |
| 24 | + } else { | |
| 25 | + console.writeErrorLine("Downloading \(model)… \(Formatting.percent(fraction))") | |
| 26 | + } | |
| 27 | + } | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +/// Throttles progress output: a new line only when the percentage changes (every 10% without | |
| 32 | +/// colours, so logs stay short). | |
| 33 | +final class ProgressLine: @unchecked Sendable { | |
| 34 | + private let lock = NSLock() | |
| 35 | + private var last = -1 | |
| 36 | + | |
| 37 | + func shouldPrint(_ fraction: Double) -> Bool { | |
| 38 | + let percent = Int(min(max(fraction, 0), 1) * 100) | |
| 39 | + return lock.withLock { | |
| 40 | + let step = percent == 100 ? 100 : percent / 10 * 10 | |
| 41 | + guard step != last else { return false } | |
| 42 | + last = step | |
| 43 | + return true | |
| 44 | + } | |
| 45 | + } | |
| 46 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | + | ||
| 4 | +/// Shows the download progress of a model on standard error, on one line when colours are | ||
| 5 | +/// available, otherwise one line every 10% so logs stay short. | ||
| 6 | +/// | ||
| 7 | +/// ```swift | ||
| 8 | +/// let progress = DownloadProgress(console: console).reporter(for: model) | ||
| 9 | +/// try await engine.download(model, progress: progress) | ||
| 10 | +/// ``` | ||
| 11 | +struct DownloadProgress { | ||
| 12 | + let console: any Console | ||
| 13 | + | ||
| 14 | + /// A progress callback for `model` (only called when something is downloaded). | ||
| 15 | + func reporter(for model: ModelReference) -> @Sendable (Double) -> Void { | ||
| 16 | + let console = self.console | ||
| 17 | + let state = ProgressLine() | ||
| 18 | + return { fraction in | ||
| 19 | + guard state.shouldPrint(fraction) else { return } | ||
| 20 | + if console.usesColor { | ||
| 21 | + console.writeError( | ||
| 22 | + "\r\u{1B}[2KDownloading \(model)… \(Formatting.percent(fraction))") | ||
| 23 | + if fraction >= 1 { console.writeError("\n") } | ||
| 24 | + } else { | ||
| 25 | + console.writeErrorLine("Downloading \(model)… \(Formatting.percent(fraction))") | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// Throttles progress output: a new line only when the percentage changes (every 10% without | ||
| 32 | +/// colours, so logs stay short). | ||
| 33 | +final class ProgressLine: @unchecked Sendable { | ||
| 34 | + private let lock = NSLock() | ||
| 35 | + private var last = -1 | ||
| 36 | + | ||
| 37 | + func shouldPrint(_ fraction: Double) -> Bool { | ||
| 38 | + let percent = Int(min(max(fraction, 0), 1) * 100) | ||
| 39 | + return lock.withLock { | ||
| 40 | + let step = percent == 100 ? 100 : percent / 10 * 10 | ||
| 41 | + guard step != last else { return false } | ||
| 42 | + last = step | ||
| 43 | + return true | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | +} | ||
deleted
Sources/RazorbillCLI/EventPrinter.swift +0 -74 | deleted file mode 100644 | ||
| @@ -1,74 +0,0 @@ | ||
| 1 | -import RazorbillCore | |
| 2 | - | |
| 3 | -/// Prints an agent's events on the console: the answer on standard output, everything else | |
| 4 | -/// (thinking, tool calls, statistics) on standard error. | |
| 5 | -struct EventPrinter { | |
| 6 | - let console: any Console | |
| 7 | - let showThinking: Bool | |
| 8 | - let showStats: Bool | |
| 9 | - /// The answer printed so far does not end with a newline. | |
| 10 | - private var openLine = false | |
| 11 | - private var thinkingOpen = false | |
| 12 | - | |
| 13 | - init(console: any Console, config: AgentConfig) { | |
| 14 | - self.console = console | |
| 15 | - self.showThinking = config.userInterface.showThinking | |
| 16 | - self.showStats = config.userInterface.showStats | |
| 17 | - } | |
| 18 | - | |
| 19 | - mutating func print(_ event: AgentEvent) { | |
| 20 | - switch event { | |
| 21 | - case .text(let text): | |
| 22 | - closeThinking() | |
| 23 | - console.write(text) | |
| 24 | - openLine = !text.hasSuffix("\n") | |
| 25 | - case .thinking(let text): | |
| 26 | - // Models told not to think often still send an empty block: never open one for it. | |
| 27 | - guard showThinking, thinkingOpen || !Self.isBlank(text) else { return } | |
| 28 | - thinkingOpen = true | |
| 29 | - console.writeError(console.dimmed(text)) | |
| 30 | - case .toolCall(let call): | |
| 31 | - endLine() | |
| 32 | - console.writeErrorLine(console.dimmed("→ \(call.name) \(Self.summary(of: call))")) | |
| 33 | - case .toolResult(let name, let output): | |
| 34 | - let firstLine = output.content.split(separator: "\n").first.map(String.init) ?? "" | |
| 35 | - let more = output.content.split(separator: "\n").count > 1 ? " …" : "" | |
| 36 | - console.writeErrorLine(console.dimmed("← \(name): \(firstLine)\(more)")) | |
| 37 | - case .stats(let stats): | |
| 38 | - guard showStats else { return } | |
| 39 | - endLine() | |
| 40 | - console.writeErrorLine(console.dimmed(Formatting.stats(stats))) | |
| 41 | - } | |
| 42 | - } | |
| 43 | - | |
| 44 | - /// Ends the answer with a newline so the shell prompt starts on its own line. | |
| 45 | - mutating func finish() { | |
| 46 | - endLine() | |
| 47 | - closeThinking() | |
| 48 | - } | |
| 49 | - | |
| 50 | - private mutating func endLine() { | |
| 51 | - if openLine { | |
| 52 | - console.write("\n") | |
| 53 | - openLine = false | |
| 54 | - } | |
| 55 | - } | |
| 56 | - | |
| 57 | - private mutating func closeThinking() { | |
| 58 | - if thinkingOpen { | |
| 59 | - console.writeError("\n") | |
| 60 | - thinkingOpen = false | |
| 61 | - } | |
| 62 | - } | |
| 63 | - | |
| 64 | - static func isBlank(_ text: String) -> Bool { | |
| 65 | - text.allSatisfy(\.isWhitespace) | |
| 66 | - } | |
| 67 | - | |
| 68 | - /// `command="ls -la"`, or the arguments in short form. | |
| 69 | - static func summary(of call: ToolCall) -> String { | |
| 70 | - call.arguments.sorted { $0.key < $1.key }.map { key, value in | |
| 71 | - "\(key)=\(value.stringValue.map { "\"\($0)\"" } ?? "\(value)")" | |
| 72 | - }.joined(separator: " ") | |
| 73 | - } | |
| 74 | -} | |
| deleted file mode 100644 | |||
| @@ -1,74 +0,0 @@ | |||
| 1 | -import RazorbillCore | ||
| 2 | - | ||
| 3 | -/// Prints an agent's events on the console: the answer on standard output, everything else | ||
| 4 | -/// (thinking, tool calls, statistics) on standard error. | ||
| 5 | -struct EventPrinter { | ||
| 6 | - let console: any Console | ||
| 7 | - let showThinking: Bool | ||
| 8 | - let showStats: Bool | ||
| 9 | - /// The answer printed so far does not end with a newline. | ||
| 10 | - private var openLine = false | ||
| 11 | - private var thinkingOpen = false | ||
| 12 | - | ||
| 13 | - init(console: any Console, config: AgentConfig) { | ||
| 14 | - self.console = console | ||
| 15 | - self.showThinking = config.userInterface.showThinking | ||
| 16 | - self.showStats = config.userInterface.showStats | ||
| 17 | - } | ||
| 18 | - | ||
| 19 | - mutating func print(_ event: AgentEvent) { | ||
| 20 | - switch event { | ||
| 21 | - case .text(let text): | ||
| 22 | - closeThinking() | ||
| 23 | - console.write(text) | ||
| 24 | - openLine = !text.hasSuffix("\n") | ||
| 25 | - case .thinking(let text): | ||
| 26 | - // Models told not to think often still send an empty block: never open one for it. | ||
| 27 | - guard showThinking, thinkingOpen || !Self.isBlank(text) else { return } | ||
| 28 | - thinkingOpen = true | ||
| 29 | - console.writeError(console.dimmed(text)) | ||
| 30 | - case .toolCall(let call): | ||
| 31 | - endLine() | ||
| 32 | - console.writeErrorLine(console.dimmed("→ \(call.name) \(Self.summary(of: call))")) | ||
| 33 | - case .toolResult(let name, let output): | ||
| 34 | - let firstLine = output.content.split(separator: "\n").first.map(String.init) ?? "" | ||
| 35 | - let more = output.content.split(separator: "\n").count > 1 ? " …" : "" | ||
| 36 | - console.writeErrorLine(console.dimmed("← \(name): \(firstLine)\(more)")) | ||
| 37 | - case .stats(let stats): | ||
| 38 | - guard showStats else { return } | ||
| 39 | - endLine() | ||
| 40 | - console.writeErrorLine(console.dimmed(Formatting.stats(stats))) | ||
| 41 | - } | ||
| 42 | - } | ||
| 43 | - | ||
| 44 | - /// Ends the answer with a newline so the shell prompt starts on its own line. | ||
| 45 | - mutating func finish() { | ||
| 46 | - endLine() | ||
| 47 | - closeThinking() | ||
| 48 | - } | ||
| 49 | - | ||
| 50 | - private mutating func endLine() { | ||
| 51 | - if openLine { | ||
| 52 | - console.write("\n") | ||
| 53 | - openLine = false | ||
| 54 | - } | ||
| 55 | - } | ||
| 56 | - | ||
| 57 | - private mutating func closeThinking() { | ||
| 58 | - if thinkingOpen { | ||
| 59 | - console.writeError("\n") | ||
| 60 | - thinkingOpen = false | ||
| 61 | - } | ||
| 62 | - } | ||
| 63 | - | ||
| 64 | - static func isBlank(_ text: String) -> Bool { | ||
| 65 | - text.allSatisfy(\.isWhitespace) | ||
| 66 | - } | ||
| 67 | - | ||
| 68 | - /// `command="ls -la"`, or the arguments in short form. | ||
| 69 | - static func summary(of call: ToolCall) -> String { | ||
| 70 | - call.arguments.sorted { $0.key < $1.key }.map { key, value in | ||
| 71 | - "\(key)=\(value.stringValue.map { "\"\($0)\"" } ?? "\(value)")" | ||
| 72 | - }.joined(separator: " ") | ||
| 73 | - } | ||
| 74 | -} | ||
modified
Sources/RazorbillCLI/Formatting.swift +0 -6 | @@ -14,12 +14,6 @@ enum Formatting { | ||
| 14 | 14 | return "\(count) B" |
| 15 | 15 | } |
| 16 | 16 | |
| 17 | - /// `[12 prompt tokens, 30 generated, 45.2 tokens/s]` | |
| 18 | - static func stats(_ stats: GenerationStats) -> String { | |
| 19 | - "[\(stats.promptTokens) prompt tokens, \(stats.generatedTokens) generated, " | |
| 20 | - + String(format: "%.1f tokens/s]", stats.tokensPerSecond) | |
| 21 | - } | |
| 22 | - | |
| 23 | 17 | /// `42%` |
| 24 | 18 | static func percent(_ fraction: Double) -> String { |
| 25 | 19 | String(format: "%.0f%%", min(max(fraction, 0), 1) * 100) |
| @@ -14,12 +14,6 @@ enum Formatting { | |||
| 14 | return "\(count) B" | 14 | return "\(count) B" |
| 15 | } | 15 | } |
| 16 | 16 | ||
| 17 | - /// `[12 prompt tokens, 30 generated, 45.2 tokens/s]` | ||
| 18 | - static func stats(_ stats: GenerationStats) -> String { | ||
| 19 | - "[\(stats.promptTokens) prompt tokens, \(stats.generatedTokens) generated, " | ||
| 20 | - + String(format: "%.1f tokens/s]", stats.tokensPerSecond) | ||
| 21 | - } | ||
| 22 | - | ||
| 23 | /// `42%` | 17 | /// `42%` |
| 24 | static func percent(_ fraction: Double) -> String { | 18 | static func percent(_ fraction: Double) -> String { |
| 25 | String(format: "%.0f%%", min(max(fraction, 0), 1) * 100) | 19 | String(format: "%.0f%%", min(max(fraction, 0), 1) * 100) |
deleted
Sources/RazorbillCore/Agent/Agent.swift +0 -141 | deleted file mode 100644 | ||
| @@ -1,141 +0,0 @@ | ||
| 1 | -/// The razorbill agent: a configured model, a conversation and tools. | |
| 2 | -/// | |
| 3 | -/// ```swift | |
| 4 | -/// let agent = Agent(config: config, engine: FakeEngine(), tools: []) | |
| 5 | -/// try await agent.load { fraction in print(fraction) } | |
| 6 | -/// for try await event in agent.send("Hello") { | |
| 7 | -/// if case .text(let piece) = event { print(piece, terminator: "") } | |
| 8 | -/// } | |
| 9 | -/// ``` | |
| 10 | -public actor Agent { | |
| 11 | - public nonisolated let config: AgentConfig | |
| 12 | - private let engine: any InferenceEngine | |
| 13 | - private let tools: [String: any AgentTool] | |
| 14 | - private let toolContext: ToolContext | |
| 15 | - /// Maximum model ↔ tool round trips for one prompt. | |
| 16 | - public nonisolated let maxToolRounds: Int | |
| 17 | - private var session: (any EngineSession)? | |
| 18 | - /// Every message of the conversation so far. | |
| 19 | - public private(set) var transcript: [ChatMessage] = [] | |
| 20 | - | |
| 21 | - public init( | |
| 22 | - config: AgentConfig, engine: any InferenceEngine, tools: [any AgentTool] = [], | |
| 23 | - toolContext: ToolContext = .nonInteractive, maxToolRounds: Int = 8 | |
| 24 | - ) { | |
| 25 | - self.config = config | |
| 26 | - self.engine = engine | |
| 27 | - self.tools = Dictionary( | |
| 28 | - tools.map { ($0.spec.name, $0) }, uniquingKeysWith: { first, _ in first }) | |
| 29 | - self.toolContext = toolContext | |
| 30 | - self.maxToolRounds = maxToolRounds | |
| 31 | - } | |
| 32 | - | |
| 33 | - /// Name of the engine running the model (`mlx`, `fake`...). | |
| 34 | - public nonisolated var engineName: String { engine.name } | |
| 35 | - | |
| 36 | - /// Loads the configured model. `progress` receives 0...1 while downloading. | |
| 37 | - public func load( | |
| 38 | - offline: Bool = false, progress: @escaping @Sendable (Double) -> Void = { _ in } | |
| 39 | - ) async throws { | |
| 40 | - try await engine.load(config.model, offline: offline, progress: progress) | |
| 41 | - } | |
| 42 | - | |
| 43 | - /// Forgets the conversation; the next prompt starts a new one. | |
| 44 | - public func reset() { | |
| 45 | - session = nil | |
| 46 | - transcript = [] | |
| 47 | - } | |
| 48 | - | |
| 49 | - /// Sends a prompt and streams what happens until the final answer. | |
| 50 | - /// Cancelling the consuming task stops the generation and any running tool. | |
| 51 | - public nonisolated func send(_ prompt: String) -> AsyncThrowingStream<AgentEvent, Error> { | |
| 52 | - AsyncThrowingStream { continuation in | |
| 53 | - let task = Task { | |
| 54 | - do { | |
| 55 | - try await self.run(prompt, continuation: continuation) | |
| 56 | - continuation.finish() | |
| 57 | - } catch { | |
| 58 | - continuation.finish(throwing: error) | |
| 59 | - } | |
| 60 | - } | |
| 61 | - continuation.onTermination = { _ in task.cancel() } | |
| 62 | - } | |
| 63 | - } | |
| 64 | - | |
| 65 | - private func run( | |
| 66 | - _ prompt: String, continuation: AsyncThrowingStream<AgentEvent, Error>.Continuation | |
| 67 | - ) async throws { | |
| 68 | - let session = try await currentSession() | |
| 69 | - var pending: [ChatMessage] = [.user(prompt)] | |
| 70 | - | |
| 71 | - for _ in 0 ..< maxToolRounds { | |
| 72 | - transcript += pending | |
| 73 | - let (answer, calls) = try await stream(session.send(pending), into: continuation) | |
| 74 | - transcript.append(.assistant(answer, toolCalls: calls)) | |
| 75 | - if calls.isEmpty { | |
| 76 | - return | |
| 77 | - } | |
| 78 | - pending = [] | |
| 79 | - for call in calls { | |
| 80 | - try Task.checkCancellation() | |
| 81 | - continuation.yield(.toolCall(call)) | |
| 82 | - let output = await runTool(call) | |
| 83 | - continuation.yield(.toolResult(name: call.name, output: output)) | |
| 84 | - pending.append(.tool(output.content, name: call.name, callID: call.id)) | |
| 85 | - } | |
| 86 | - } | |
| 87 | - throw AgentError.tooManyToolRounds(maxToolRounds) | |
| 88 | - } | |
| 89 | - | |
| 90 | - /// Forwards the engine's events and returns the answer text and the tool calls it contained. | |
| 91 | - private func stream( | |
| 92 | - _ events: AsyncThrowingStream<EngineEvent, Error>, | |
| 93 | - into continuation: AsyncThrowingStream<AgentEvent, Error>.Continuation | |
| 94 | - ) async throws -> (String, [ToolCall]) { | |
| 95 | - var answer = "" | |
| 96 | - var calls: [ToolCall] = [] | |
| 97 | - for try await event in events { | |
| 98 | - try Task.checkCancellation() | |
| 99 | - switch event { | |
| 100 | - case .text(let piece): | |
| 101 | - answer += piece | |
| 102 | - continuation.yield(.text(piece)) | |
| 103 | - case .thinking(let piece): | |
| 104 | - continuation.yield(.thinking(piece)) | |
| 105 | - case .toolCall(let call): | |
| 106 | - calls.append(call) | |
| 107 | - case .stats(let stats): | |
| 108 | - continuation.yield(.stats(stats)) | |
| 109 | - } | |
| 110 | - } | |
| 111 | - return (answer, calls) | |
| 112 | - } | |
| 113 | - | |
| 114 | - private func runTool(_ call: ToolCall) async -> ToolOutput { | |
| 115 | - guard let tool = tools[call.name] else { | |
| 116 | - let known = tools.keys.sorted().joined(separator: ", ") | |
| 117 | - return ToolOutput( | |
| 118 | - "unknown tool \(call.name) (available: \(known.isEmpty ? "none" : known))", | |
| 119 | - isError: true) | |
| 120 | - } | |
| 121 | - do { | |
| 122 | - return try await tool.call(call.arguments, context: toolContext) | |
| 123 | - } catch { | |
| 124 | - return ToolOutput("error: \(error)", isError: true) | |
| 125 | - } | |
| 126 | - } | |
| 127 | - | |
| 128 | - private func currentSession() async throws -> any EngineSession { | |
| 129 | - if let session { | |
| 130 | - return session | |
| 131 | - } | |
| 132 | - let setup = SessionSetup( | |
| 133 | - system: config.system, | |
| 134 | - tools: tools.values.map(\.spec).sorted { $0.name < $1.name }, | |
| 135 | - generation: config.generation | |
| 136 | - ) | |
| 137 | - let created = try await engine.makeSession(setup) | |
| 138 | - session = created | |
| 139 | - return created | |
| 140 | - } | |
| 141 | -} | |
| deleted file mode 100644 | |||
| @@ -1,141 +0,0 @@ | |||
| 1 | -/// The razorbill agent: a configured model, a conversation and tools. | ||
| 2 | -/// | ||
| 3 | -/// ```swift | ||
| 4 | -/// let agent = Agent(config: config, engine: FakeEngine(), tools: []) | ||
| 5 | -/// try await agent.load { fraction in print(fraction) } | ||
| 6 | -/// for try await event in agent.send("Hello") { | ||
| 7 | -/// if case .text(let piece) = event { print(piece, terminator: "") } | ||
| 8 | -/// } | ||
| 9 | -/// ``` | ||
| 10 | -public actor Agent { | ||
| 11 | - public nonisolated let config: AgentConfig | ||
| 12 | - private let engine: any InferenceEngine | ||
| 13 | - private let tools: [String: any AgentTool] | ||
| 14 | - private let toolContext: ToolContext | ||
| 15 | - /// Maximum model ↔ tool round trips for one prompt. | ||
| 16 | - public nonisolated let maxToolRounds: Int | ||
| 17 | - private var session: (any EngineSession)? | ||
| 18 | - /// Every message of the conversation so far. | ||
| 19 | - public private(set) var transcript: [ChatMessage] = [] | ||
| 20 | - | ||
| 21 | - public init( | ||
| 22 | - config: AgentConfig, engine: any InferenceEngine, tools: [any AgentTool] = [], | ||
| 23 | - toolContext: ToolContext = .nonInteractive, maxToolRounds: Int = 8 | ||
| 24 | - ) { | ||
| 25 | - self.config = config | ||
| 26 | - self.engine = engine | ||
| 27 | - self.tools = Dictionary( | ||
| 28 | - tools.map { ($0.spec.name, $0) }, uniquingKeysWith: { first, _ in first }) | ||
| 29 | - self.toolContext = toolContext | ||
| 30 | - self.maxToolRounds = maxToolRounds | ||
| 31 | - } | ||
| 32 | - | ||
| 33 | - /// Name of the engine running the model (`mlx`, `fake`...). | ||
| 34 | - public nonisolated var engineName: String { engine.name } | ||
| 35 | - | ||
| 36 | - /// Loads the configured model. `progress` receives 0...1 while downloading. | ||
| 37 | - public func load( | ||
| 38 | - offline: Bool = false, progress: @escaping @Sendable (Double) -> Void = { _ in } | ||
| 39 | - ) async throws { | ||
| 40 | - try await engine.load(config.model, offline: offline, progress: progress) | ||
| 41 | - } | ||
| 42 | - | ||
| 43 | - /// Forgets the conversation; the next prompt starts a new one. | ||
| 44 | - public func reset() { | ||
| 45 | - session = nil | ||
| 46 | - transcript = [] | ||
| 47 | - } | ||
| 48 | - | ||
| 49 | - /// Sends a prompt and streams what happens until the final answer. | ||
| 50 | - /// Cancelling the consuming task stops the generation and any running tool. | ||
| 51 | - public nonisolated func send(_ prompt: String) -> AsyncThrowingStream<AgentEvent, Error> { | ||
| 52 | - AsyncThrowingStream { continuation in | ||
| 53 | - let task = Task { | ||
| 54 | - do { | ||
| 55 | - try await self.run(prompt, continuation: continuation) | ||
| 56 | - continuation.finish() | ||
| 57 | - } catch { | ||
| 58 | - continuation.finish(throwing: error) | ||
| 59 | - } | ||
| 60 | - } | ||
| 61 | - continuation.onTermination = { _ in task.cancel() } | ||
| 62 | - } | ||
| 63 | - } | ||
| 64 | - | ||
| 65 | - private func run( | ||
| 66 | - _ prompt: String, continuation: AsyncThrowingStream<AgentEvent, Error>.Continuation | ||
| 67 | - ) async throws { | ||
| 68 | - let session = try await currentSession() | ||
| 69 | - var pending: [ChatMessage] = [.user(prompt)] | ||
| 70 | - | ||
| 71 | - for _ in 0 ..< maxToolRounds { | ||
| 72 | - transcript += pending | ||
| 73 | - let (answer, calls) = try await stream(session.send(pending), into: continuation) | ||
| 74 | - transcript.append(.assistant(answer, toolCalls: calls)) | ||
| 75 | - if calls.isEmpty { | ||
| 76 | - return | ||
| 77 | - } | ||
| 78 | - pending = [] | ||
| 79 | - for call in calls { | ||
| 80 | - try Task.checkCancellation() | ||
| 81 | - continuation.yield(.toolCall(call)) | ||
| 82 | - let output = await runTool(call) | ||
| 83 | - continuation.yield(.toolResult(name: call.name, output: output)) | ||
| 84 | - pending.append(.tool(output.content, name: call.name, callID: call.id)) | ||
| 85 | - } | ||
| 86 | - } | ||
| 87 | - throw AgentError.tooManyToolRounds(maxToolRounds) | ||
| 88 | - } | ||
| 89 | - | ||
| 90 | - /// Forwards the engine's events and returns the answer text and the tool calls it contained. | ||
| 91 | - private func stream( | ||
| 92 | - _ events: AsyncThrowingStream<EngineEvent, Error>, | ||
| 93 | - into continuation: AsyncThrowingStream<AgentEvent, Error>.Continuation | ||
| 94 | - ) async throws -> (String, [ToolCall]) { | ||
| 95 | - var answer = "" | ||
| 96 | - var calls: [ToolCall] = [] | ||
| 97 | - for try await event in events { | ||
| 98 | - try Task.checkCancellation() | ||
| 99 | - switch event { | ||
| 100 | - case .text(let piece): | ||
| 101 | - answer += piece | ||
| 102 | - continuation.yield(.text(piece)) | ||
| 103 | - case .thinking(let piece): | ||
| 104 | - continuation.yield(.thinking(piece)) | ||
| 105 | - case .toolCall(let call): | ||
| 106 | - calls.append(call) | ||
| 107 | - case .stats(let stats): | ||
| 108 | - continuation.yield(.stats(stats)) | ||
| 109 | - } | ||
| 110 | - } | ||
| 111 | - return (answer, calls) | ||
| 112 | - } | ||
| 113 | - | ||
| 114 | - private func runTool(_ call: ToolCall) async -> ToolOutput { | ||
| 115 | - guard let tool = tools[call.name] else { | ||
| 116 | - let known = tools.keys.sorted().joined(separator: ", ") | ||
| 117 | - return ToolOutput( | ||
| 118 | - "unknown tool \(call.name) (available: \(known.isEmpty ? "none" : known))", | ||
| 119 | - isError: true) | ||
| 120 | - } | ||
| 121 | - do { | ||
| 122 | - return try await tool.call(call.arguments, context: toolContext) | ||
| 123 | - } catch { | ||
| 124 | - return ToolOutput("error: \(error)", isError: true) | ||
| 125 | - } | ||
| 126 | - } | ||
| 127 | - | ||
| 128 | - private func currentSession() async throws -> any EngineSession { | ||
| 129 | - if let session { | ||
| 130 | - return session | ||
| 131 | - } | ||
| 132 | - let setup = SessionSetup( | ||
| 133 | - system: config.system, | ||
| 134 | - tools: tools.values.map(\.spec).sorted { $0.name < $1.name }, | ||
| 135 | - generation: config.generation | ||
| 136 | - ) | ||
| 137 | - let created = try await engine.makeSession(setup) | ||
| 138 | - session = created | ||
| 139 | - return created | ||
| 140 | - } | ||
| 141 | -} | ||
deleted
Sources/RazorbillCore/Agent/AgentEvent.swift +0 -26 | deleted file mode 100644 | ||
| @@ -1,26 +0,0 @@ | ||
| 1 | -/// What the agent reports while answering. Front-ends (CLI, TUI) render only these. | |
| 2 | -public enum AgentEvent: Sendable, Equatable { | |
| 3 | - /// A piece of the answer. | |
| 4 | - case text(String) | |
| 5 | - /// A piece of the model's reasoning. | |
| 6 | - case thinking(String) | |
| 7 | - /// The model called a tool; it is about to run. | |
| 8 | - case toolCall(ToolCall) | |
| 9 | - /// The tool finished (or failed, or was refused). | |
| 10 | - case toolResult(name: String, output: ToolOutput) | |
| 11 | - /// Statistics of one model answer (a turn with tools has several). | |
| 12 | - case stats(GenerationStats) | |
| 13 | -} | |
| 14 | - | |
| 15 | -/// Errors of the agent loop itself. | |
| 16 | -public enum AgentError: Error, Equatable, CustomStringConvertible { | |
| 17 | - /// The model kept calling tools beyond the allowed number of rounds. | |
| 18 | - case tooManyToolRounds(Int) | |
| 19 | - | |
| 20 | - public var description: String { | |
| 21 | - switch self { | |
| 22 | - case .tooManyToolRounds(let rounds): | |
| 23 | - "the model called tools \(rounds) times in a row without answering; stopped" | |
| 24 | - } | |
| 25 | - } | |
| 26 | -} | |
| deleted file mode 100644 | |||
| @@ -1,26 +0,0 @@ | |||
| 1 | -/// What the agent reports while answering. Front-ends (CLI, TUI) render only these. | ||
| 2 | -public enum AgentEvent: Sendable, Equatable { | ||
| 3 | - /// A piece of the answer. | ||
| 4 | - case text(String) | ||
| 5 | - /// A piece of the model's reasoning. | ||
| 6 | - case thinking(String) | ||
| 7 | - /// The model called a tool; it is about to run. | ||
| 8 | - case toolCall(ToolCall) | ||
| 9 | - /// The tool finished (or failed, or was refused). | ||
| 10 | - case toolResult(name: String, output: ToolOutput) | ||
| 11 | - /// Statistics of one model answer (a turn with tools has several). | ||
| 12 | - case stats(GenerationStats) | ||
| 13 | -} | ||
| 14 | - | ||
| 15 | -/// Errors of the agent loop itself. | ||
| 16 | -public enum AgentError: Error, Equatable, CustomStringConvertible { | ||
| 17 | - /// The model kept calling tools beyond the allowed number of rounds. | ||
| 18 | - case tooManyToolRounds(Int) | ||
| 19 | - | ||
| 20 | - public var description: String { | ||
| 21 | - switch self { | ||
| 22 | - case .tooManyToolRounds(let rounds): | ||
| 23 | - "the model called tools \(rounds) times in a row without answering; stopped" | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | -} | ||
deleted
Sources/RazorbillCore/Config/AgentConfig.swift +0 -82 | deleted file mode 100644 | ||
| @@ -1,82 +0,0 @@ | ||
| 1 | -/// Sampling settings used for every answer of the agent. | |
| 2 | -public struct GenerationSettings: Sendable, Equatable { | |
| 3 | - /// Sampling temperature; 0 makes the answer deterministic. Default 0.6. | |
| 4 | - public var temperature: Double | |
| 5 | - /// Nucleus sampling threshold, in (0, 1]. Default 1 (disabled). | |
| 6 | - public var topP: Double | |
| 7 | - /// Maximum number of tokens generated per answer. Default 1024. | |
| 8 | - public var maxTokens: Int | |
| 9 | - /// Let reasoning models think before answering. Default false. | |
| 10 | - public var thinking: Bool | |
| 11 | - /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. | |
| 12 | - /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. | |
| 13 | - public var thinkingBudget: Int? | |
| 14 | - | |
| 15 | - public init( | |
| 16 | - temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, | |
| 17 | - thinking: Bool = false, thinkingBudget: Int? = nil | |
| 18 | - ) { | |
| 19 | - self.temperature = temperature | |
| 20 | - self.topP = topP | |
| 21 | - self.maxTokens = maxTokens | |
| 22 | - self.thinking = thinking | |
| 23 | - self.thinkingBudget = thinkingBudget | |
| 24 | - } | |
| 25 | -} | |
| 26 | - | |
| 27 | -/// Display preferences shared by the CLI and TUI front-ends. | |
| 28 | -public struct UISettings: Sendable, Equatable { | |
| 29 | - /// Print token counts and speed after each answer. Default true. | |
| 30 | - public var showStats: Bool | |
| 31 | - /// Show the model's reasoning when it thinks (see ``GenerationSettings/thinking``). | |
| 32 | - /// Default true. The TUI starts with it shown or hidden, and Ctrl-T toggles it. | |
| 33 | - public var showThinking: Bool | |
| 34 | - | |
| 35 | - public init(showStats: Bool = true, showThinking: Bool = true) { | |
| 36 | - self.showStats = showStats | |
| 37 | - self.showThinking = showThinking | |
| 38 | - } | |
| 39 | -} | |
| 40 | - | |
| 41 | -/// An agent, as described by its YAML file. One agent per file. | |
| 42 | -/// | |
| 43 | -/// Load one with ``ConfigLoader``: | |
| 44 | -/// | |
| 45 | -/// ```swift | |
| 46 | -/// let config = try ConfigLoader().load(file: "razorbill.yaml") | |
| 47 | -/// print(config.name, config.model) | |
| 48 | -/// ``` | |
| 49 | -public struct AgentConfig: Sendable, Equatable { | |
| 50 | - /// Short name, shown in the UI. | |
| 51 | - public var name: String | |
| 52 | - /// Optional one-line description. | |
| 53 | - public var description: String? | |
| 54 | - /// The model the agent runs. | |
| 55 | - public var model: ModelReference | |
| 56 | - /// Sampling settings. | |
| 57 | - public var generation: GenerationSettings | |
| 58 | - /// System prompt, with its `{{variables}}` already replaced. Empty when not set. | |
| 59 | - public var system: String | |
| 60 | - /// Enabled tools and their options, by tool name. A tool is enabled by being listed. | |
| 61 | - public var tools: [String: ConfigValue] | |
| 62 | - /// Display preferences. | |
| 63 | - public var userInterface: UISettings | |
| 64 | - | |
| 65 | - public init( | |
| 66 | - name: String, | |
| 67 | - description: String? = nil, | |
| 68 | - model: ModelReference, | |
| 69 | - generation: GenerationSettings = GenerationSettings(), | |
| 70 | - system: String = "", | |
| 71 | - tools: [String: ConfigValue] = [:], | |
| 72 | - userInterface: UISettings = UISettings() | |
| 73 | - ) { | |
| 74 | - self.name = name | |
| 75 | - self.description = description | |
| 76 | - self.model = model | |
| 77 | - self.generation = generation | |
| 78 | - self.system = system | |
| 79 | - self.tools = tools | |
| 80 | - self.userInterface = userInterface | |
| 81 | - } | |
| 82 | -} | |
| deleted file mode 100644 | |||
| @@ -1,82 +0,0 @@ | |||
| 1 | -/// Sampling settings used for every answer of the agent. | ||
| 2 | -public struct GenerationSettings: Sendable, Equatable { | ||
| 3 | - /// Sampling temperature; 0 makes the answer deterministic. Default 0.6. | ||
| 4 | - public var temperature: Double | ||
| 5 | - /// Nucleus sampling threshold, in (0, 1]. Default 1 (disabled). | ||
| 6 | - public var topP: Double | ||
| 7 | - /// Maximum number of tokens generated per answer. Default 1024. | ||
| 8 | - public var maxTokens: Int | ||
| 9 | - /// Let reasoning models think before answering. Default false. | ||
| 10 | - public var thinking: Bool | ||
| 11 | - /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. | ||
| 12 | - /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. | ||
| 13 | - public var thinkingBudget: Int? | ||
| 14 | - | ||
| 15 | - public init( | ||
| 16 | - temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, | ||
| 17 | - thinking: Bool = false, thinkingBudget: Int? = nil | ||
| 18 | - ) { | ||
| 19 | - self.temperature = temperature | ||
| 20 | - self.topP = topP | ||
| 21 | - self.maxTokens = maxTokens | ||
| 22 | - self.thinking = thinking | ||
| 23 | - self.thinkingBudget = thinkingBudget | ||
| 24 | - } | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -/// Display preferences shared by the CLI and TUI front-ends. | ||
| 28 | -public struct UISettings: Sendable, Equatable { | ||
| 29 | - /// Print token counts and speed after each answer. Default true. | ||
| 30 | - public var showStats: Bool | ||
| 31 | - /// Show the model's reasoning when it thinks (see ``GenerationSettings/thinking``). | ||
| 32 | - /// Default true. The TUI starts with it shown or hidden, and Ctrl-T toggles it. | ||
| 33 | - public var showThinking: Bool | ||
| 34 | - | ||
| 35 | - public init(showStats: Bool = true, showThinking: Bool = true) { | ||
| 36 | - self.showStats = showStats | ||
| 37 | - self.showThinking = showThinking | ||
| 38 | - } | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | -/// An agent, as described by its YAML file. One agent per file. | ||
| 42 | -/// | ||
| 43 | -/// Load one with ``ConfigLoader``: | ||
| 44 | -/// | ||
| 45 | -/// ```swift | ||
| 46 | -/// let config = try ConfigLoader().load(file: "razorbill.yaml") | ||
| 47 | -/// print(config.name, config.model) | ||
| 48 | -/// ``` | ||
| 49 | -public struct AgentConfig: Sendable, Equatable { | ||
| 50 | - /// Short name, shown in the UI. | ||
| 51 | - public var name: String | ||
| 52 | - /// Optional one-line description. | ||
| 53 | - public var description: String? | ||
| 54 | - /// The model the agent runs. | ||
| 55 | - public var model: ModelReference | ||
| 56 | - /// Sampling settings. | ||
| 57 | - public var generation: GenerationSettings | ||
| 58 | - /// System prompt, with its `{{variables}}` already replaced. Empty when not set. | ||
| 59 | - public var system: String | ||
| 60 | - /// Enabled tools and their options, by tool name. A tool is enabled by being listed. | ||
| 61 | - public var tools: [String: ConfigValue] | ||
| 62 | - /// Display preferences. | ||
| 63 | - public var userInterface: UISettings | ||
| 64 | - | ||
| 65 | - public init( | ||
| 66 | - name: String, | ||
| 67 | - description: String? = nil, | ||
| 68 | - model: ModelReference, | ||
| 69 | - generation: GenerationSettings = GenerationSettings(), | ||
| 70 | - system: String = "", | ||
| 71 | - tools: [String: ConfigValue] = [:], | ||
| 72 | - userInterface: UISettings = UISettings() | ||
| 73 | - ) { | ||
| 74 | - self.name = name | ||
| 75 | - self.description = description | ||
| 76 | - self.model = model | ||
| 77 | - self.generation = generation | ||
| 78 | - self.system = system | ||
| 79 | - self.tools = tools | ||
| 80 | - self.userInterface = userInterface | ||
| 81 | - } | ||
| 82 | -} | ||
modified
Sources/RazorbillCore/Config/ConfigError.swift +3 -3 | @@ -1,4 +1,4 @@ | ||
| 1 | -/// One problem found in an agent configuration file. | |
| 1 | +/// One problem found in a configuration file. | |
| 2 | 2 | /// |
| 3 | 3 | /// ```swift |
| 4 | 4 | /// let issue = ConfigIssue(keyPath: "generation.temperature", line: 7, message: "must be >= 0") |
| @@ -28,8 +28,8 @@ public struct ConfigIssue: Sendable, Equatable, CustomStringConvertible { | ||
| 28 | 28 | /// The configuration could not be loaded. Lists every problem found, not just the first. |
| 29 | 29 | /// |
| 30 | 30 | /// ```swift |
| 31 | -/// do { _ = try ConfigLoader().load(file: path) } | |
| 32 | -/// catch let error as ConfigError { print(error) } | |
| 31 | +/// let error = ConfigError(file: "server.yaml", issues: [issue]) | |
| 32 | +/// print(error) // invalid configuration server.yaml\n - … | |
| 33 | 33 | /// ``` |
| 34 | 34 | public struct ConfigError: Error, Sendable, Equatable, CustomStringConvertible { |
| 35 | 35 | /// The file that was read, or `nil` when loading from a string. |
| @@ -1,4 +1,4 @@ | |||
| 1 | -/// One problem found in an agent configuration file. | 1 | +/// One problem found in a configuration file. |
| 2 | /// | 2 | /// |
| 3 | /// ```swift | 3 | /// ```swift |
| 4 | /// let issue = ConfigIssue(keyPath: "generation.temperature", line: 7, message: "must be >= 0") | 4 | /// let issue = ConfigIssue(keyPath: "generation.temperature", line: 7, message: "must be >= 0") |
| @@ -28,8 +28,8 @@ public struct ConfigIssue: Sendable, Equatable, CustomStringConvertible { | |||
| 28 | /// The configuration could not be loaded. Lists every problem found, not just the first. | 28 | /// The configuration could not be loaded. Lists every problem found, not just the first. |
| 29 | /// | 29 | /// |
| 30 | /// ```swift | 30 | /// ```swift |
| 31 | -/// do { _ = try ConfigLoader().load(file: path) } | 31 | +/// let error = ConfigError(file: "server.yaml", issues: [issue]) |
| 32 | -/// catch let error as ConfigError { print(error) } | 32 | +/// print(error) // invalid configuration server.yaml\n - … |
| 33 | /// ``` | 33 | /// ``` |
| 34 | public struct ConfigError: Error, Sendable, Equatable, CustomStringConvertible { | 34 | public struct ConfigError: Error, Sendable, Equatable, CustomStringConvertible { |
| 35 | /// The file that was read, or `nil` when loading from a string. | 35 | /// The file that was read, or `nil` when loading from a string. |
deleted
Sources/RazorbillCore/Config/ConfigLoader.swift +0 -250 | deleted file mode 100644 | ||
| @@ -1,250 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import Yams | |
| 3 | - | |
| 4 | -/// Loads and validates an agent YAML file into an ``AgentConfig``. | |
| 5 | -/// | |
| 6 | -/// Every problem is collected and thrown at once as a ``ConfigError``: unknown keys, wrong types, | |
| 7 | -/// missing values, out-of-range numbers and unresolved `{{variables}}`, each with its line. | |
| 8 | -/// | |
| 9 | -/// ```swift | |
| 10 | -/// let loader = ConfigLoader() | |
| 11 | -/// let config = try loader.load(file: "razorbill.yaml") | |
| 12 | -/// // or, from a string (tests, `rzb init`): | |
| 13 | -/// let other = try loader.parse("name: demo\nmodel: mlx-community/Qwen3-0.6B-4bit\n") | |
| 14 | -/// ``` | |
| 15 | -public struct ConfigLoader: Sendable { | |
| 16 | - /// Values for the `{{variables}}` of the system prompt. | |
| 17 | - public var context: TemplateContext | |
| 18 | - /// Directory that `~` stands for in local model paths. | |
| 19 | - public var homeDirectory: String | |
| 20 | - | |
| 21 | - public init(context: TemplateContext = .current, homeDirectory: String = NSHomeDirectory()) { | |
| 22 | - self.context = context | |
| 23 | - self.homeDirectory = homeDirectory | |
| 24 | - } | |
| 25 | - | |
| 26 | - /// Reads and validates the file at `path`. Relative model paths are resolved from its folder. | |
| 27 | - public func load(file path: String) throws -> AgentConfig { | |
| 28 | - let text: String | |
| 29 | - do { | |
| 30 | - text = try String(contentsOfFile: path, encoding: .utf8) | |
| 31 | - } catch { | |
| 32 | - throw ConfigError( | |
| 33 | - file: path, | |
| 34 | - issues: [ConfigIssue(keyPath: "", line: nil, message: "cannot read the file")]) | |
| 35 | - } | |
| 36 | - let folder = URL(fileURLWithPath: path).deletingLastPathComponent().path | |
| 37 | - return try parse(text, file: path, baseDirectory: folder) | |
| 38 | - } | |
| 39 | - | |
| 40 | - /// Validates YAML `text`. `file` only labels the errors; relative model paths start at `baseDirectory`. | |
| 41 | - public func parse( | |
| 42 | - _ text: String, file: String? = nil, baseDirectory: String? = nil | |
| 43 | - ) throws -> AgentConfig { | |
| 44 | - let root: Node? | |
| 45 | - do { | |
| 46 | - root = try Yams.compose(yaml: text) | |
| 47 | - } catch { | |
| 48 | - throw ConfigError( | |
| 49 | - file: file, | |
| 50 | - issues: [ConfigIssue(keyPath: "", line: nil, message: "not valid YAML: \(error)")]) | |
| 51 | - } | |
| 52 | - let reader = ConfigReader() | |
| 53 | - let config = root.flatMap { | |
| 54 | - build( | |
| 55 | - from: $0, reader: reader, baseDirectory: baseDirectory ?? context.currentDirectory) | |
| 56 | - } | |
| 57 | - if root == nil { | |
| 58 | - reader.report("", nil, "the file is empty") | |
| 59 | - } | |
| 60 | - guard reader.issues.isEmpty, let config else { | |
| 61 | - throw ConfigError(file: file, issues: reader.issues) | |
| 62 | - } | |
| 63 | - return config | |
| 64 | - } | |
| 65 | - | |
| 66 | - static let topLevelKeys = [ | |
| 67 | - "name", "description", "model", "generation", "system", "tools", "ui", | |
| 68 | - ] | |
| 69 | - | |
| 70 | - private func build( | |
| 71 | - from root: Node, reader: ConfigReader, baseDirectory: String | |
| 72 | - ) -> AgentConfig? { | |
| 73 | - guard let document = reader.mapping(root, path: "") else { return nil } | |
| 74 | - reader.rejectUnknownKeys(document, allowed: Self.topLevelKeys, path: "") | |
| 75 | - | |
| 76 | - let name = reader.string(document, "name", path: "") | |
| 77 | - if name == nil, document["name"] == nil { | |
| 78 | - reader.report("name", root, "is required") | |
| 79 | - } else if let name, name.trimmingCharacters(in: .whitespaces).isEmpty { | |
| 80 | - reader.report("name", document["name"], "must not be empty") | |
| 81 | - } | |
| 82 | - let model = readModel(document, reader: reader, root: root, baseDirectory: baseDirectory) | |
| 83 | - let generation = readGeneration(document["generation"], reader: reader) | |
| 84 | - let system = readSystem(document, reader: reader) | |
| 85 | - let tools = readTools(document["tools"], reader: reader) | |
| 86 | - let userInterface = readUI(document["ui"], reader: reader) | |
| 87 | - | |
| 88 | - guard let name, let model else { return nil } | |
| 89 | - return AgentConfig( | |
| 90 | - name: name, | |
| 91 | - description: reader.string(document, "description", path: ""), | |
| 92 | - model: model, | |
| 93 | - generation: generation, | |
| 94 | - system: system, | |
| 95 | - tools: tools, | |
| 96 | - userInterface: userInterface | |
| 97 | - ) | |
| 98 | - } | |
| 99 | - | |
| 100 | - private func readModel( | |
| 101 | - _ document: Node.Mapping, reader: ConfigReader, root: Node, baseDirectory: String | |
| 102 | - ) -> ModelReference? { | |
| 103 | - guard let node = document["model"], !reader.isNull(node) else { | |
| 104 | - reader.report("model", root, "is required (a Hugging Face id or a local path)") | |
| 105 | - return nil | |
| 106 | - } | |
| 107 | - if node.scalar != nil { | |
| 108 | - guard let id = reader.string(document, "model", path: "") else { return nil } | |
| 109 | - return .huggingFace(id: id, revision: ModelReference.defaultRevision) | |
| 110 | - } | |
| 111 | - guard let mapping = reader.mapping(node, path: "model") else { return nil } | |
| 112 | - reader.rejectUnknownKeys(mapping, allowed: ["id", "revision", "path"], path: "model") | |
| 113 | - let id = reader.string(mapping, "id", path: "model") | |
| 114 | - let revision = reader.string(mapping, "revision", path: "model") | |
| 115 | - let path = reader.string(mapping, "path", path: "model") | |
| 116 | - | |
| 117 | - switch (id, path) { | |
| 118 | - case (let id?, nil): | |
| 119 | - return .huggingFace(id: id, revision: revision ?? ModelReference.defaultRevision) | |
| 120 | - case (nil, let path?): | |
| 121 | - if revision != nil { | |
| 122 | - reader.report( | |
| 123 | - "model.revision", mapping["revision"], "only applies to a Hugging Face id") | |
| 124 | - } | |
| 125 | - return .local(path: resolve(path, from: baseDirectory)) | |
| 126 | - case (.some, .some): | |
| 127 | - reader.report("model", node, "give either id or path, not both") | |
| 128 | - case (nil, nil): | |
| 129 | - reader.report("model", node, "needs an id (Hugging Face) or a path (local directory)") | |
| 130 | - } | |
| 131 | - return nil | |
| 132 | - } | |
| 133 | - | |
| 134 | - /// Expands `~` and makes a relative path start at `baseDirectory`. | |
| 135 | - private func resolve(_ path: String, from baseDirectory: String) -> URL { | |
| 136 | - if path == "~" || path.hasPrefix("~/") { | |
| 137 | - return URL(fileURLWithPath: homeDirectory + path.dropFirst()).standardizedFileURL | |
| 138 | - } | |
| 139 | - if path.hasPrefix("/") { | |
| 140 | - return URL(fileURLWithPath: path).standardizedFileURL | |
| 141 | - } | |
| 142 | - return URL(fileURLWithPath: baseDirectory).appendingPathComponent(path).standardizedFileURL | |
| 143 | - } | |
| 144 | - | |
| 145 | - private func readGeneration(_ node: Node?, reader: ConfigReader) -> GenerationSettings { | |
| 146 | - var settings = GenerationSettings() | |
| 147 | - guard let node, !reader.isNull(node), let mapping = reader.mapping(node, path: "generation") | |
| 148 | - else { | |
| 149 | - return settings | |
| 150 | - } | |
| 151 | - let path = "generation" | |
| 152 | - reader.rejectUnknownKeys( | |
| 153 | - mapping, | |
| 154 | - allowed: ["temperature", "top_p", "max_tokens", "thinking", "thinking_budget"], | |
| 155 | - path: path) | |
| 156 | - if let value = reader.double(mapping, "temperature", path: path) { | |
| 157 | - if value < 0 { | |
| 158 | - reader.report("generation.temperature", mapping["temperature"], "must be 0 or more") | |
| 159 | - } | |
| 160 | - settings.temperature = value | |
| 161 | - } | |
| 162 | - if let value = reader.double(mapping, "top_p", path: path) { | |
| 163 | - if value <= 0 || value > 1 { | |
| 164 | - reader.report("generation.top_p", mapping["top_p"], "must be in (0, 1]") | |
| 165 | - } | |
| 166 | - settings.topP = value | |
| 167 | - } | |
| 168 | - if let value = reader.int(mapping, "max_tokens", path: path) { | |
| 169 | - if value <= 0 { | |
| 170 | - reader.report("generation.max_tokens", mapping["max_tokens"], "must be more than 0") | |
| 171 | - } | |
| 172 | - settings.maxTokens = value | |
| 173 | - } | |
| 174 | - readThinking(mapping, into: &settings, reader: reader) | |
| 175 | - return settings | |
| 176 | - } | |
| 177 | - | |
| 178 | - private func readThinking( | |
| 179 | - _ mapping: Node.Mapping, into settings: inout GenerationSettings, reader: ConfigReader | |
| 180 | - ) { | |
| 181 | - if let value = reader.bool(mapping, "thinking", path: "generation") { | |
| 182 | - settings.thinking = value | |
| 183 | - } | |
| 184 | - guard let budget = reader.int(mapping, "thinking_budget", path: "generation") else { | |
| 185 | - return | |
| 186 | - } | |
| 187 | - if budget < 0 { | |
| 188 | - reader.report( | |
| 189 | - "generation.thinking_budget", mapping["thinking_budget"], "must be 0 or more") | |
| 190 | - } else if budget >= settings.maxTokens { | |
| 191 | - reader.report( | |
| 192 | - "generation.thinking_budget", mapping["thinking_budget"], | |
| 193 | - "must be smaller than max_tokens (\(settings.maxTokens)), which also counts the answer" | |
| 194 | - ) | |
| 195 | - } | |
| 196 | - settings.thinkingBudget = budget | |
| 197 | - } | |
| 198 | - | |
| 199 | - private func readSystem(_ document: Node.Mapping, reader: ConfigReader) -> String { | |
| 200 | - guard let text = reader.string(document, "system", path: "") else { return "" } | |
| 201 | - do { | |
| 202 | - return try PromptTemplate.render(text, context: context) | |
| 203 | - } catch { | |
| 204 | - reader.report("system", document["system"], "\(error)") | |
| 205 | - return text | |
| 206 | - } | |
| 207 | - } | |
| 208 | - | |
| 209 | - /// `tools` is a mapping `name: options` (options may be empty), or a list of names. | |
| 210 | - private func readTools(_ node: Node?, reader: ConfigReader) -> [String: ConfigValue] { | |
| 211 | - guard let node, !reader.isNull(node) else { return [:] } | |
| 212 | - var tools: [String: ConfigValue] = [:] | |
| 213 | - if let sequence = node.sequence { | |
| 214 | - for item in sequence { | |
| 215 | - guard let name = item.string, reader.tagName(item) == .str else { | |
| 216 | - reader.report("tools", item, "list entries must be tool names") | |
| 217 | - continue | |
| 218 | - } | |
| 219 | - tools[name] = .map([:]) | |
| 220 | - } | |
| 221 | - return tools | |
| 222 | - } | |
| 223 | - guard let mapping = reader.mapping(node, path: "tools") else { return [:] } | |
| 224 | - for (key, options) in mapping { | |
| 225 | - let name = key.string ?? "" | |
| 226 | - switch reader.value(options) { | |
| 227 | - case .null: tools[name] = .map([:]) | |
| 228 | - case .map(let entries): tools[name] = .map(entries) | |
| 229 | - default: | |
| 230 | - reader.report("tools.\(name)", options, "options must be a mapping, or left empty") | |
| 231 | - } | |
| 232 | - } | |
| 233 | - return tools | |
| 234 | - } | |
| 235 | - | |
| 236 | - private func readUI(_ node: Node?, reader: ConfigReader) -> UISettings { | |
| 237 | - var settings = UISettings() | |
| 238 | - guard let node, !reader.isNull(node), let mapping = reader.mapping(node, path: "ui") else { | |
| 239 | - return settings | |
| 240 | - } | |
| 241 | - reader.rejectUnknownKeys(mapping, allowed: ["show_stats", "show_thinking"], path: "ui") | |
| 242 | - if let value = reader.bool(mapping, "show_stats", path: "ui") { | |
| 243 | - settings.showStats = value | |
| 244 | - } | |
| 245 | - if let value = reader.bool(mapping, "show_thinking", path: "ui") { | |
| 246 | - settings.showThinking = value | |
| 247 | - } | |
| 248 | - return settings | |
| 249 | - } | |
| 250 | -} | |
| deleted file mode 100644 | |||
| @@ -1,250 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import Yams | ||
| 3 | - | ||
| 4 | -/// Loads and validates an agent YAML file into an ``AgentConfig``. | ||
| 5 | -/// | ||
| 6 | -/// Every problem is collected and thrown at once as a ``ConfigError``: unknown keys, wrong types, | ||
| 7 | -/// missing values, out-of-range numbers and unresolved `{{variables}}`, each with its line. | ||
| 8 | -/// | ||
| 9 | -/// ```swift | ||
| 10 | -/// let loader = ConfigLoader() | ||
| 11 | -/// let config = try loader.load(file: "razorbill.yaml") | ||
| 12 | -/// // or, from a string (tests, `rzb init`): | ||
| 13 | -/// let other = try loader.parse("name: demo\nmodel: mlx-community/Qwen3-0.6B-4bit\n") | ||
| 14 | -/// ``` | ||
| 15 | -public struct ConfigLoader: Sendable { | ||
| 16 | - /// Values for the `{{variables}}` of the system prompt. | ||
| 17 | - public var context: TemplateContext | ||
| 18 | - /// Directory that `~` stands for in local model paths. | ||
| 19 | - public var homeDirectory: String | ||
| 20 | - | ||
| 21 | - public init(context: TemplateContext = .current, homeDirectory: String = NSHomeDirectory()) { | ||
| 22 | - self.context = context | ||
| 23 | - self.homeDirectory = homeDirectory | ||
| 24 | - } | ||
| 25 | - | ||
| 26 | - /// Reads and validates the file at `path`. Relative model paths are resolved from its folder. | ||
| 27 | - public func load(file path: String) throws -> AgentConfig { | ||
| 28 | - let text: String | ||
| 29 | - do { | ||
| 30 | - text = try String(contentsOfFile: path, encoding: .utf8) | ||
| 31 | - } catch { | ||
| 32 | - throw ConfigError( | ||
| 33 | - file: path, | ||
| 34 | - issues: [ConfigIssue(keyPath: "", line: nil, message: "cannot read the file")]) | ||
| 35 | - } | ||
| 36 | - let folder = URL(fileURLWithPath: path).deletingLastPathComponent().path | ||
| 37 | - return try parse(text, file: path, baseDirectory: folder) | ||
| 38 | - } | ||
| 39 | - | ||
| 40 | - /// Validates YAML `text`. `file` only labels the errors; relative model paths start at `baseDirectory`. | ||
| 41 | - public func parse( | ||
| 42 | - _ text: String, file: String? = nil, baseDirectory: String? = nil | ||
| 43 | - ) throws -> AgentConfig { | ||
| 44 | - let root: Node? | ||
| 45 | - do { | ||
| 46 | - root = try Yams.compose(yaml: text) | ||
| 47 | - } catch { | ||
| 48 | - throw ConfigError( | ||
| 49 | - file: file, | ||
| 50 | - issues: [ConfigIssue(keyPath: "", line: nil, message: "not valid YAML: \(error)")]) | ||
| 51 | - } | ||
| 52 | - let reader = ConfigReader() | ||
| 53 | - let config = root.flatMap { | ||
| 54 | - build( | ||
| 55 | - from: $0, reader: reader, baseDirectory: baseDirectory ?? context.currentDirectory) | ||
| 56 | - } | ||
| 57 | - if root == nil { | ||
| 58 | - reader.report("", nil, "the file is empty") | ||
| 59 | - } | ||
| 60 | - guard reader.issues.isEmpty, let config else { | ||
| 61 | - throw ConfigError(file: file, issues: reader.issues) | ||
| 62 | - } | ||
| 63 | - return config | ||
| 64 | - } | ||
| 65 | - | ||
| 66 | - static let topLevelKeys = [ | ||
| 67 | - "name", "description", "model", "generation", "system", "tools", "ui", | ||
| 68 | - ] | ||
| 69 | - | ||
| 70 | - private func build( | ||
| 71 | - from root: Node, reader: ConfigReader, baseDirectory: String | ||
| 72 | - ) -> AgentConfig? { | ||
| 73 | - guard let document = reader.mapping(root, path: "") else { return nil } | ||
| 74 | - reader.rejectUnknownKeys(document, allowed: Self.topLevelKeys, path: "") | ||
| 75 | - | ||
| 76 | - let name = reader.string(document, "name", path: "") | ||
| 77 | - if name == nil, document["name"] == nil { | ||
| 78 | - reader.report("name", root, "is required") | ||
| 79 | - } else if let name, name.trimmingCharacters(in: .whitespaces).isEmpty { | ||
| 80 | - reader.report("name", document["name"], "must not be empty") | ||
| 81 | - } | ||
| 82 | - let model = readModel(document, reader: reader, root: root, baseDirectory: baseDirectory) | ||
| 83 | - let generation = readGeneration(document["generation"], reader: reader) | ||
| 84 | - let system = readSystem(document, reader: reader) | ||
| 85 | - let tools = readTools(document["tools"], reader: reader) | ||
| 86 | - let userInterface = readUI(document["ui"], reader: reader) | ||
| 87 | - | ||
| 88 | - guard let name, let model else { return nil } | ||
| 89 | - return AgentConfig( | ||
| 90 | - name: name, | ||
| 91 | - description: reader.string(document, "description", path: ""), | ||
| 92 | - model: model, | ||
| 93 | - generation: generation, | ||
| 94 | - system: system, | ||
| 95 | - tools: tools, | ||
| 96 | - userInterface: userInterface | ||
| 97 | - ) | ||
| 98 | - } | ||
| 99 | - | ||
| 100 | - private func readModel( | ||
| 101 | - _ document: Node.Mapping, reader: ConfigReader, root: Node, baseDirectory: String | ||
| 102 | - ) -> ModelReference? { | ||
| 103 | - guard let node = document["model"], !reader.isNull(node) else { | ||
| 104 | - reader.report("model", root, "is required (a Hugging Face id or a local path)") | ||
| 105 | - return nil | ||
| 106 | - } | ||
| 107 | - if node.scalar != nil { | ||
| 108 | - guard let id = reader.string(document, "model", path: "") else { return nil } | ||
| 109 | - return .huggingFace(id: id, revision: ModelReference.defaultRevision) | ||
| 110 | - } | ||
| 111 | - guard let mapping = reader.mapping(node, path: "model") else { return nil } | ||
| 112 | - reader.rejectUnknownKeys(mapping, allowed: ["id", "revision", "path"], path: "model") | ||
| 113 | - let id = reader.string(mapping, "id", path: "model") | ||
| 114 | - let revision = reader.string(mapping, "revision", path: "model") | ||
| 115 | - let path = reader.string(mapping, "path", path: "model") | ||
| 116 | - | ||
| 117 | - switch (id, path) { | ||
| 118 | - case (let id?, nil): | ||
| 119 | - return .huggingFace(id: id, revision: revision ?? ModelReference.defaultRevision) | ||
| 120 | - case (nil, let path?): | ||
| 121 | - if revision != nil { | ||
| 122 | - reader.report( | ||
| 123 | - "model.revision", mapping["revision"], "only applies to a Hugging Face id") | ||
| 124 | - } | ||
| 125 | - return .local(path: resolve(path, from: baseDirectory)) | ||
| 126 | - case (.some, .some): | ||
| 127 | - reader.report("model", node, "give either id or path, not both") | ||
| 128 | - case (nil, nil): | ||
| 129 | - reader.report("model", node, "needs an id (Hugging Face) or a path (local directory)") | ||
| 130 | - } | ||
| 131 | - return nil | ||
| 132 | - } | ||
| 133 | - | ||
| 134 | - /// Expands `~` and makes a relative path start at `baseDirectory`. | ||
| 135 | - private func resolve(_ path: String, from baseDirectory: String) -> URL { | ||
| 136 | - if path == "~" || path.hasPrefix("~/") { | ||
| 137 | - return URL(fileURLWithPath: homeDirectory + path.dropFirst()).standardizedFileURL | ||
| 138 | - } | ||
| 139 | - if path.hasPrefix("/") { | ||
| 140 | - return URL(fileURLWithPath: path).standardizedFileURL | ||
| 141 | - } | ||
| 142 | - return URL(fileURLWithPath: baseDirectory).appendingPathComponent(path).standardizedFileURL | ||
| 143 | - } | ||
| 144 | - | ||
| 145 | - private func readGeneration(_ node: Node?, reader: ConfigReader) -> GenerationSettings { | ||
| 146 | - var settings = GenerationSettings() | ||
| 147 | - guard let node, !reader.isNull(node), let mapping = reader.mapping(node, path: "generation") | ||
| 148 | - else { | ||
| 149 | - return settings | ||
| 150 | - } | ||
| 151 | - let path = "generation" | ||
| 152 | - reader.rejectUnknownKeys( | ||
| 153 | - mapping, | ||
| 154 | - allowed: ["temperature", "top_p", "max_tokens", "thinking", "thinking_budget"], | ||
| 155 | - path: path) | ||
| 156 | - if let value = reader.double(mapping, "temperature", path: path) { | ||
| 157 | - if value < 0 { | ||
| 158 | - reader.report("generation.temperature", mapping["temperature"], "must be 0 or more") | ||
| 159 | - } | ||
| 160 | - settings.temperature = value | ||
| 161 | - } | ||
| 162 | - if let value = reader.double(mapping, "top_p", path: path) { | ||
| 163 | - if value <= 0 || value > 1 { | ||
| 164 | - reader.report("generation.top_p", mapping["top_p"], "must be in (0, 1]") | ||
| 165 | - } | ||
| 166 | - settings.topP = value | ||
| 167 | - } | ||
| 168 | - if let value = reader.int(mapping, "max_tokens", path: path) { | ||
| 169 | - if value <= 0 { | ||
| 170 | - reader.report("generation.max_tokens", mapping["max_tokens"], "must be more than 0") | ||
| 171 | - } | ||
| 172 | - settings.maxTokens = value | ||
| 173 | - } | ||
| 174 | - readThinking(mapping, into: &settings, reader: reader) | ||
| 175 | - return settings | ||
| 176 | - } | ||
| 177 | - | ||
| 178 | - private func readThinking( | ||
| 179 | - _ mapping: Node.Mapping, into settings: inout GenerationSettings, reader: ConfigReader | ||
| 180 | - ) { | ||
| 181 | - if let value = reader.bool(mapping, "thinking", path: "generation") { | ||
| 182 | - settings.thinking = value | ||
| 183 | - } | ||
| 184 | - guard let budget = reader.int(mapping, "thinking_budget", path: "generation") else { | ||
| 185 | - return | ||
| 186 | - } | ||
| 187 | - if budget < 0 { | ||
| 188 | - reader.report( | ||
| 189 | - "generation.thinking_budget", mapping["thinking_budget"], "must be 0 or more") | ||
| 190 | - } else if budget >= settings.maxTokens { | ||
| 191 | - reader.report( | ||
| 192 | - "generation.thinking_budget", mapping["thinking_budget"], | ||
| 193 | - "must be smaller than max_tokens (\(settings.maxTokens)), which also counts the answer" | ||
| 194 | - ) | ||
| 195 | - } | ||
| 196 | - settings.thinkingBudget = budget | ||
| 197 | - } | ||
| 198 | - | ||
| 199 | - private func readSystem(_ document: Node.Mapping, reader: ConfigReader) -> String { | ||
| 200 | - guard let text = reader.string(document, "system", path: "") else { return "" } | ||
| 201 | - do { | ||
| 202 | - return try PromptTemplate.render(text, context: context) | ||
| 203 | - } catch { | ||
| 204 | - reader.report("system", document["system"], "\(error)") | ||
| 205 | - return text | ||
| 206 | - } | ||
| 207 | - } | ||
| 208 | - | ||
| 209 | - /// `tools` is a mapping `name: options` (options may be empty), or a list of names. | ||
| 210 | - private func readTools(_ node: Node?, reader: ConfigReader) -> [String: ConfigValue] { | ||
| 211 | - guard let node, !reader.isNull(node) else { return [:] } | ||
| 212 | - var tools: [String: ConfigValue] = [:] | ||
| 213 | - if let sequence = node.sequence { | ||
| 214 | - for item in sequence { | ||
| 215 | - guard let name = item.string, reader.tagName(item) == .str else { | ||
| 216 | - reader.report("tools", item, "list entries must be tool names") | ||
| 217 | - continue | ||
| 218 | - } | ||
| 219 | - tools[name] = .map([:]) | ||
| 220 | - } | ||
| 221 | - return tools | ||
| 222 | - } | ||
| 223 | - guard let mapping = reader.mapping(node, path: "tools") else { return [:] } | ||
| 224 | - for (key, options) in mapping { | ||
| 225 | - let name = key.string ?? "" | ||
| 226 | - switch reader.value(options) { | ||
| 227 | - case .null: tools[name] = .map([:]) | ||
| 228 | - case .map(let entries): tools[name] = .map(entries) | ||
| 229 | - default: | ||
| 230 | - reader.report("tools.\(name)", options, "options must be a mapping, or left empty") | ||
| 231 | - } | ||
| 232 | - } | ||
| 233 | - return tools | ||
| 234 | - } | ||
| 235 | - | ||
| 236 | - private func readUI(_ node: Node?, reader: ConfigReader) -> UISettings { | ||
| 237 | - var settings = UISettings() | ||
| 238 | - guard let node, !reader.isNull(node), let mapping = reader.mapping(node, path: "ui") else { | ||
| 239 | - return settings | ||
| 240 | - } | ||
| 241 | - reader.rejectUnknownKeys(mapping, allowed: ["show_stats", "show_thinking"], path: "ui") | ||
| 242 | - if let value = reader.bool(mapping, "show_stats", path: "ui") { | ||
| 243 | - settings.showStats = value | ||
| 244 | - } | ||
| 245 | - if let value = reader.bool(mapping, "show_thinking", path: "ui") { | ||
| 246 | - settings.showThinking = value | ||
| 247 | - } | ||
| 248 | - return settings | ||
| 249 | - } | ||
| 250 | -} | ||
deleted
Sources/RazorbillCore/Config/ConfigLocator.swift +0 -69 | deleted file mode 100644 | ||
| @@ -1,69 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -/// Finds the agent file to use when none is given explicitly. | |
| 4 | -/// | |
| 5 | -/// Lookup order: | |
| 6 | -/// 1. the path given with `--config`; | |
| 7 | -/// 2. `./razorbill.yaml`; | |
| 8 | -/// 3. `~/.config/razorbill/agent.yaml`. | |
| 9 | -/// | |
| 10 | -/// ```swift | |
| 11 | -/// let path = try ConfigLocator().locate(explicitPath: nil) | |
| 12 | -/// ``` | |
| 13 | -public struct ConfigLocator: Sendable { | |
| 14 | - /// File name looked up in the current directory. | |
| 15 | - public static let localFileName = "razorbill.yaml" | |
| 16 | - /// Path of the user-wide default, relative to the home directory. | |
| 17 | - public static let userFilePath = ".config/razorbill/agent.yaml" | |
| 18 | - | |
| 19 | - /// No agent file was found. | |
| 20 | - public struct NotFound: Error, Equatable, CustomStringConvertible { | |
| 21 | - /// The paths that were tried, in order. | |
| 22 | - public let searched: [String] | |
| 23 | - | |
| 24 | - public init(searched: [String]) { | |
| 25 | - self.searched = searched | |
| 26 | - } | |
| 27 | - | |
| 28 | - public var description: String { | |
| 29 | - "no agent configuration found (searched: \(searched.joined(separator: ", "))). Create one with `rzb init`." | |
| 30 | - } | |
| 31 | - } | |
| 32 | - | |
| 33 | - public var currentDirectory: String | |
| 34 | - public var homeDirectory: String | |
| 35 | - /// Tells whether a file exists; replaceable in tests. | |
| 36 | - public var fileExists: @Sendable (String) -> Bool | |
| 37 | - | |
| 38 | - public init( | |
| 39 | - currentDirectory: String = FileManager.default.currentDirectoryPath, | |
| 40 | - homeDirectory: String = NSHomeDirectory(), | |
| 41 | - fileExists: @escaping @Sendable (String) -> Bool = { | |
| 42 | - FileManager.default.fileExists(atPath: $0) | |
| 43 | - } | |
| 44 | - ) { | |
| 45 | - self.currentDirectory = currentDirectory | |
| 46 | - self.homeDirectory = homeDirectory | |
| 47 | - self.fileExists = fileExists | |
| 48 | - } | |
| 49 | - | |
| 50 | - /// The candidate paths, in lookup order. | |
| 51 | - public func candidates(explicitPath: String?) -> [String] { | |
| 52 | - if let explicitPath { | |
| 53 | - return [explicitPath] | |
| 54 | - } | |
| 55 | - return [ | |
| 56 | - URL(fileURLWithPath: currentDirectory).appendingPathComponent(Self.localFileName).path, | |
| 57 | - URL(fileURLWithPath: homeDirectory).appendingPathComponent(Self.userFilePath).path, | |
| 58 | - ] | |
| 59 | - } | |
| 60 | - | |
| 61 | - /// The first candidate that exists. An explicit path must exist: no fallback when it does not. | |
| 62 | - public func locate(explicitPath: String?) throws -> String { | |
| 63 | - let paths = candidates(explicitPath: explicitPath) | |
| 64 | - guard let found = paths.first(where: fileExists) else { | |
| 65 | - throw NotFound(searched: paths) | |
| 66 | - } | |
| 67 | - return found | |
| 68 | - } | |
| 69 | -} | |
| deleted file mode 100644 | |||
| @@ -1,69 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -/// Finds the agent file to use when none is given explicitly. | ||
| 4 | -/// | ||
| 5 | -/// Lookup order: | ||
| 6 | -/// 1. the path given with `--config`; | ||
| 7 | -/// 2. `./razorbill.yaml`; | ||
| 8 | -/// 3. `~/.config/razorbill/agent.yaml`. | ||
| 9 | -/// | ||
| 10 | -/// ```swift | ||
| 11 | -/// let path = try ConfigLocator().locate(explicitPath: nil) | ||
| 12 | -/// ``` | ||
| 13 | -public struct ConfigLocator: Sendable { | ||
| 14 | - /// File name looked up in the current directory. | ||
| 15 | - public static let localFileName = "razorbill.yaml" | ||
| 16 | - /// Path of the user-wide default, relative to the home directory. | ||
| 17 | - public static let userFilePath = ".config/razorbill/agent.yaml" | ||
| 18 | - | ||
| 19 | - /// No agent file was found. | ||
| 20 | - public struct NotFound: Error, Equatable, CustomStringConvertible { | ||
| 21 | - /// The paths that were tried, in order. | ||
| 22 | - public let searched: [String] | ||
| 23 | - | ||
| 24 | - public init(searched: [String]) { | ||
| 25 | - self.searched = searched | ||
| 26 | - } | ||
| 27 | - | ||
| 28 | - public var description: String { | ||
| 29 | - "no agent configuration found (searched: \(searched.joined(separator: ", "))). Create one with `rzb init`." | ||
| 30 | - } | ||
| 31 | - } | ||
| 32 | - | ||
| 33 | - public var currentDirectory: String | ||
| 34 | - public var homeDirectory: String | ||
| 35 | - /// Tells whether a file exists; replaceable in tests. | ||
| 36 | - public var fileExists: @Sendable (String) -> Bool | ||
| 37 | - | ||
| 38 | - public init( | ||
| 39 | - currentDirectory: String = FileManager.default.currentDirectoryPath, | ||
| 40 | - homeDirectory: String = NSHomeDirectory(), | ||
| 41 | - fileExists: @escaping @Sendable (String) -> Bool = { | ||
| 42 | - FileManager.default.fileExists(atPath: $0) | ||
| 43 | - } | ||
| 44 | - ) { | ||
| 45 | - self.currentDirectory = currentDirectory | ||
| 46 | - self.homeDirectory = homeDirectory | ||
| 47 | - self.fileExists = fileExists | ||
| 48 | - } | ||
| 49 | - | ||
| 50 | - /// The candidate paths, in lookup order. | ||
| 51 | - public func candidates(explicitPath: String?) -> [String] { | ||
| 52 | - if let explicitPath { | ||
| 53 | - return [explicitPath] | ||
| 54 | - } | ||
| 55 | - return [ | ||
| 56 | - URL(fileURLWithPath: currentDirectory).appendingPathComponent(Self.localFileName).path, | ||
| 57 | - URL(fileURLWithPath: homeDirectory).appendingPathComponent(Self.userFilePath).path, | ||
| 58 | - ] | ||
| 59 | - } | ||
| 60 | - | ||
| 61 | - /// The first candidate that exists. An explicit path must exist: no fallback when it does not. | ||
| 62 | - public func locate(explicitPath: String?) throws -> String { | ||
| 63 | - let paths = candidates(explicitPath: explicitPath) | ||
| 64 | - guard let found = paths.first(where: fileExists) else { | ||
| 65 | - throw NotFound(searched: paths) | ||
| 66 | - } | ||
| 67 | - return found | ||
| 68 | - } | ||
| 69 | -} | ||
modified
Sources/RazorbillCore/Config/ConfigReader.swift +3 -2 | @@ -2,8 +2,9 @@ import Yams | ||
| 2 | 2 | |
| 3 | 3 | /// Reads typed values out of a YAML tree and records every problem it meets, with its line. |
| 4 | 4 | /// |
| 5 | -/// Internal helper of ``ConfigLoader``: each accessor returns `nil` and records an issue when the | |
| 6 | -/// value is missing or has the wrong type, so loading can continue and report all problems at once. | |
| 5 | +/// Internal helper for configuration loaders: each accessor returns `nil` and records an issue when | |
| 6 | +/// the value is missing or has the wrong type, so loading can continue and report all problems at | |
| 7 | +/// once. Kept from the v0.1 agent loader for the server configuration file (ticket #33). | |
| 7 | 8 | final class ConfigReader { |
| 8 | 9 | private(set) var issues: [ConfigIssue] = [] |
| 9 | 10 | |
| @@ -2,8 +2,9 @@ import Yams | |||
| 2 | 2 | ||
| 3 | /// Reads typed values out of a YAML tree and records every problem it meets, with its line. | 3 | /// Reads typed values out of a YAML tree and records every problem it meets, with its line. |
| 4 | /// | 4 | /// |
| 5 | -/// Internal helper of ``ConfigLoader``: each accessor returns `nil` and records an issue when the | 5 | +/// Internal helper for configuration loaders: each accessor returns `nil` and records an issue when |
| 6 | -/// value is missing or has the wrong type, so loading can continue and report all problems at once. | 6 | +/// the value is missing or has the wrong type, so loading can continue and report all problems at |
| 7 | +/// once. Kept from the v0.1 agent loader for the server configuration file (ticket #33). | ||
| 7 | final class ConfigReader { | 8 | final class ConfigReader { |
| 8 | private(set) var issues: [ConfigIssue] = [] | 9 | private(set) var issues: [ConfigIssue] = [] |
| 9 | 10 | ||
modified
Sources/RazorbillCore/Config/ConfigValue.swift +3 -5 | @@ -1,10 +1,8 @@ | ||
| 1 | -/// A YAML value kept as data, used for the free-form options of each tool. | |
| 2 | -/// | |
| 3 | -/// Tools read their own options from it, so adding a tool never changes the configuration types. | |
| 1 | +/// A YAML value kept as data, for free-form sections of a configuration file. | |
| 4 | 2 | /// |
| 5 | 3 | /// ```swift |
| 6 | -/// let options: ConfigValue = .map(["confirm": .bool(true), "timeout": .string("30s")]) | |
| 7 | -/// options["confirm"]?.boolValue // true | |
| 4 | +/// let options: ConfigValue = .map(["preload": .bool(true), "keep_alive": .string("10m")]) | |
| 5 | +/// options["preload"]?.boolValue // true | |
| 8 | 6 | /// ``` |
| 9 | 7 | public indirect enum ConfigValue: Sendable, Equatable { |
| 10 | 8 | case null |
| @@ -1,10 +1,8 @@ | |||
| 1 | -/// A YAML value kept as data, used for the free-form options of each tool. | 1 | +/// A YAML value kept as data, for free-form sections of a configuration file. |
| 2 | -/// | ||
| 3 | -/// Tools read their own options from it, so adding a tool never changes the configuration types. | ||
| 4 | /// | 2 | /// |
| 5 | /// ```swift | 3 | /// ```swift |
| 6 | -/// let options: ConfigValue = .map(["confirm": .bool(true), "timeout": .string("30s")]) | 4 | +/// let options: ConfigValue = .map(["preload": .bool(true), "keep_alive": .string("10m")]) |
| 7 | -/// options["confirm"]?.boolValue // true | 5 | +/// options["preload"]?.boolValue // true |
| 8 | /// ``` | 6 | /// ``` |
| 9 | public indirect enum ConfigValue: Sendable, Equatable { | 7 | public indirect enum ConfigValue: Sendable, Equatable { |
| 10 | case null | 8 | case null |
deleted
Sources/RazorbillCore/Config/ConfigWriter.swift +0 -125 | deleted file mode 100644 | ||
| @@ -1,125 +0,0 @@ | ||
| 1 | -/// What `rzb init` asks for, before it becomes a YAML file. | |
| 2 | -public struct AgentDraft: Sendable, Equatable { | |
| 3 | - public var name: String | |
| 4 | - public var description: String | |
| 5 | - public var model: ModelReference | |
| 6 | - public var system: String | |
| 7 | - public var generation: GenerationSettings | |
| 8 | - /// Names of the built-in tools to enable, with their default options. | |
| 9 | - public var tools: [String] | |
| 10 | - public var showStats: Bool | |
| 11 | - public var showThinking: Bool | |
| 12 | - | |
| 13 | - public init( | |
| 14 | - name: String, description: String = "", model: ModelReference, | |
| 15 | - system: String = ConfigWriter.defaultSystemPrompt, | |
| 16 | - generation: GenerationSettings = GenerationSettings(), tools: [String] = [], | |
| 17 | - showStats: Bool = true, showThinking: Bool = true | |
| 18 | - ) { | |
| 19 | - self.name = name | |
| 20 | - self.description = description | |
| 21 | - self.model = model | |
| 22 | - self.system = system | |
| 23 | - self.generation = generation | |
| 24 | - self.tools = tools | |
| 25 | - self.showStats = showStats | |
| 26 | - self.showThinking = showThinking | |
| 27 | - } | |
| 28 | -} | |
| 29 | - | |
| 30 | -/// Writes an agent YAML file with a comment on each key, so the file explains itself. | |
| 31 | -/// | |
| 32 | -/// ```swift | |
| 33 | -/// let yaml = ConfigWriter.yaml(for: AgentDraft(name: "helper", model: .huggingFace(id: "m/x", revision: "main"))) | |
| 34 | -/// let config = try ConfigLoader().parse(yaml) // always loads back | |
| 35 | -/// ``` | |
| 36 | -public enum ConfigWriter { | |
| 37 | - public static let defaultSystemPrompt = "You are a helpful assistant. Today is {{date}}." | |
| 38 | - | |
| 39 | - public static func yaml(for draft: AgentDraft) -> String { | |
| 40 | - var lines = [ | |
| 41 | - "# razorbill agent — created by `rzb init`. Use it with: rzb chat --config <this file>", | |
| 42 | - "", | |
| 43 | - "name: \(quoted(draft.name))", | |
| 44 | - ] | |
| 45 | - if !draft.description.isEmpty { | |
| 46 | - lines.append("description: \(quoted(draft.description))") | |
| 47 | - } | |
| 48 | - lines += | |
| 49 | - ["", "# Hugging Face id (MLX format) or local directory (path: ...)."] | |
| 50 | - + modelLines(draft.model) | |
| 51 | - let generation = draft.generation | |
| 52 | - lines += [ | |
| 53 | - "", | |
| 54 | - "generation:", | |
| 55 | - " temperature: \(number(generation.temperature)) # 0 = deterministic", | |
| 56 | - " top_p: \(number(generation.topP)) # (0, 1]", | |
| 57 | - " max_tokens: \(generation.maxTokens) # per answer", | |
| 58 | - " thinking: \(generation.thinking) # let reasoning models think first", | |
| 59 | - ] | |
| 60 | - lines += | |
| 61 | - generation.thinkingBudget.map { | |
| 62 | - [" thinking_budget: \($0) # most thinking tokens before answering"] | |
| 63 | - } ?? [] | |
| 64 | - lines += [ | |
| 65 | - "", | |
| 66 | - "# Variables: {{date}}, {{cwd}}, {{env.NAME}}.", | |
| 67 | - "system: |", | |
| 68 | - ] | |
| 69 | - lines += | |
| 70 | - (draft.system.isEmpty | |
| 71 | - ? [""] : draft.system.split(separator: "\n", omittingEmptySubsequences: false)) | |
| 72 | - .map { $0.isEmpty ? "" : " \($0)" } | |
| 73 | - lines += ["", "# Built-in tools, enabled by being listed."] + toolLines(draft.tools) | |
| 74 | - lines += [ | |
| 75 | - "", "ui:", | |
| 76 | - " show_stats: \(draft.showStats) # tokens and speed after each answer", | |
| 77 | - " show_thinking: \(draft.showThinking) # the model's reasoning, when it thinks", "", | |
| 78 | - ] | |
| 79 | - return lines.joined(separator: "\n") | |
| 80 | - } | |
| 81 | - | |
| 82 | - private static func modelLines(_ model: ModelReference) -> [String] { | |
| 83 | - switch model { | |
| 84 | - case .huggingFace(let id, let revision): | |
| 85 | - ["model:", " id: \(quoted(id))", " revision: \(quoted(revision))"] | |
| 86 | - case .local(let path): | |
| 87 | - ["model:", " path: \(quoted(path.path))"] | |
| 88 | - } | |
| 89 | - } | |
| 90 | - | |
| 91 | - private static func toolLines(_ tools: [String]) -> [String] { | |
| 92 | - guard !tools.isEmpty else { return ["tools: {}"] } | |
| 93 | - var lines = ["tools:"] | |
| 94 | - for tool in tools.sorted() { | |
| 95 | - if tool == BashTool.name { | |
| 96 | - lines += [ | |
| 97 | - " bash:", " confirm: true # ask before running each command", | |
| 98 | - ] | |
| 99 | - } else { | |
| 100 | - lines.append(" \(tool): {}") | |
| 101 | - } | |
| 102 | - } | |
| 103 | - return lines | |
| 104 | - } | |
| 105 | - | |
| 106 | - /// A YAML double-quoted scalar. | |
| 107 | - static func quoted(_ text: String) -> String { | |
| 108 | - var escaped = "" | |
| 109 | - for character in text { | |
| 110 | - switch character { | |
| 111 | - case "\\": escaped += "\\\\" | |
| 112 | - case "\"": escaped += "\\\"" | |
| 113 | - case "\n": escaped += "\\n" | |
| 114 | - case "\t": escaped += "\\t" | |
| 115 | - default: escaped.append(character) | |
| 116 | - } | |
| 117 | - } | |
| 118 | - return "\"\(escaped)\"" | |
| 119 | - } | |
| 120 | - | |
| 121 | - /// A number without a trailing `.0` noise but always readable as a number. | |
| 122 | - static func number(_ value: Double) -> String { | |
| 123 | - value == value.rounded() ? String(format: "%.1f", value) : "\(value)" | |
| 124 | - } | |
| 125 | -} | |
| deleted file mode 100644 | |||
| @@ -1,125 +0,0 @@ | |||
| 1 | -/// What `rzb init` asks for, before it becomes a YAML file. | ||
| 2 | -public struct AgentDraft: Sendable, Equatable { | ||
| 3 | - public var name: String | ||
| 4 | - public var description: String | ||
| 5 | - public var model: ModelReference | ||
| 6 | - public var system: String | ||
| 7 | - public var generation: GenerationSettings | ||
| 8 | - /// Names of the built-in tools to enable, with their default options. | ||
| 9 | - public var tools: [String] | ||
| 10 | - public var showStats: Bool | ||
| 11 | - public var showThinking: Bool | ||
| 12 | - | ||
| 13 | - public init( | ||
| 14 | - name: String, description: String = "", model: ModelReference, | ||
| 15 | - system: String = ConfigWriter.defaultSystemPrompt, | ||
| 16 | - generation: GenerationSettings = GenerationSettings(), tools: [String] = [], | ||
| 17 | - showStats: Bool = true, showThinking: Bool = true | ||
| 18 | - ) { | ||
| 19 | - self.name = name | ||
| 20 | - self.description = description | ||
| 21 | - self.model = model | ||
| 22 | - self.system = system | ||
| 23 | - self.generation = generation | ||
| 24 | - self.tools = tools | ||
| 25 | - self.showStats = showStats | ||
| 26 | - self.showThinking = showThinking | ||
| 27 | - } | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | -/// Writes an agent YAML file with a comment on each key, so the file explains itself. | ||
| 31 | -/// | ||
| 32 | -/// ```swift | ||
| 33 | -/// let yaml = ConfigWriter.yaml(for: AgentDraft(name: "helper", model: .huggingFace(id: "m/x", revision: "main"))) | ||
| 34 | -/// let config = try ConfigLoader().parse(yaml) // always loads back | ||
| 35 | -/// ``` | ||
| 36 | -public enum ConfigWriter { | ||
| 37 | - public static let defaultSystemPrompt = "You are a helpful assistant. Today is {{date}}." | ||
| 38 | - | ||
| 39 | - public static func yaml(for draft: AgentDraft) -> String { | ||
| 40 | - var lines = [ | ||
| 41 | - "# razorbill agent — created by `rzb init`. Use it with: rzb chat --config <this file>", | ||
| 42 | - "", | ||
| 43 | - "name: \(quoted(draft.name))", | ||
| 44 | - ] | ||
| 45 | - if !draft.description.isEmpty { | ||
| 46 | - lines.append("description: \(quoted(draft.description))") | ||
| 47 | - } | ||
| 48 | - lines += | ||
| 49 | - ["", "# Hugging Face id (MLX format) or local directory (path: ...)."] | ||
| 50 | - + modelLines(draft.model) | ||
| 51 | - let generation = draft.generation | ||
| 52 | - lines += [ | ||
| 53 | - "", | ||
| 54 | - "generation:", | ||
| 55 | - " temperature: \(number(generation.temperature)) # 0 = deterministic", | ||
| 56 | - " top_p: \(number(generation.topP)) # (0, 1]", | ||
| 57 | - " max_tokens: \(generation.maxTokens) # per answer", | ||
| 58 | - " thinking: \(generation.thinking) # let reasoning models think first", | ||
| 59 | - ] | ||
| 60 | - lines += | ||
| 61 | - generation.thinkingBudget.map { | ||
| 62 | - [" thinking_budget: \($0) # most thinking tokens before answering"] | ||
| 63 | - } ?? [] | ||
| 64 | - lines += [ | ||
| 65 | - "", | ||
| 66 | - "# Variables: {{date}}, {{cwd}}, {{env.NAME}}.", | ||
| 67 | - "system: |", | ||
| 68 | - ] | ||
| 69 | - lines += | ||
| 70 | - (draft.system.isEmpty | ||
| 71 | - ? [""] : draft.system.split(separator: "\n", omittingEmptySubsequences: false)) | ||
| 72 | - .map { $0.isEmpty ? "" : " \($0)" } | ||
| 73 | - lines += ["", "# Built-in tools, enabled by being listed."] + toolLines(draft.tools) | ||
| 74 | - lines += [ | ||
| 75 | - "", "ui:", | ||
| 76 | - " show_stats: \(draft.showStats) # tokens and speed after each answer", | ||
| 77 | - " show_thinking: \(draft.showThinking) # the model's reasoning, when it thinks", "", | ||
| 78 | - ] | ||
| 79 | - return lines.joined(separator: "\n") | ||
| 80 | - } | ||
| 81 | - | ||
| 82 | - private static func modelLines(_ model: ModelReference) -> [String] { | ||
| 83 | - switch model { | ||
| 84 | - case .huggingFace(let id, let revision): | ||
| 85 | - ["model:", " id: \(quoted(id))", " revision: \(quoted(revision))"] | ||
| 86 | - case .local(let path): | ||
| 87 | - ["model:", " path: \(quoted(path.path))"] | ||
| 88 | - } | ||
| 89 | - } | ||
| 90 | - | ||
| 91 | - private static func toolLines(_ tools: [String]) -> [String] { | ||
| 92 | - guard !tools.isEmpty else { return ["tools: {}"] } | ||
| 93 | - var lines = ["tools:"] | ||
| 94 | - for tool in tools.sorted() { | ||
| 95 | - if tool == BashTool.name { | ||
| 96 | - lines += [ | ||
| 97 | - " bash:", " confirm: true # ask before running each command", | ||
| 98 | - ] | ||
| 99 | - } else { | ||
| 100 | - lines.append(" \(tool): {}") | ||
| 101 | - } | ||
| 102 | - } | ||
| 103 | - return lines | ||
| 104 | - } | ||
| 105 | - | ||
| 106 | - /// A YAML double-quoted scalar. | ||
| 107 | - static func quoted(_ text: String) -> String { | ||
| 108 | - var escaped = "" | ||
| 109 | - for character in text { | ||
| 110 | - switch character { | ||
| 111 | - case "\\": escaped += "\\\\" | ||
| 112 | - case "\"": escaped += "\\\"" | ||
| 113 | - case "\n": escaped += "\\n" | ||
| 114 | - case "\t": escaped += "\\t" | ||
| 115 | - default: escaped.append(character) | ||
| 116 | - } | ||
| 117 | - } | ||
| 118 | - return "\"\(escaped)\"" | ||
| 119 | - } | ||
| 120 | - | ||
| 121 | - /// A number without a trailing `.0` noise but always readable as a number. | ||
| 122 | - static func number(_ value: Double) -> String { | ||
| 123 | - value == value.rounded() ? String(format: "%.1f", value) : "\(value)" | ||
| 124 | - } | ||
| 125 | -} | ||
modified
Sources/RazorbillCore/Config/ModelReference.swift +1 -1 | @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import Foundation |
| 2 | 2 | |
| 3 | -/// Where the agent's model comes from. | |
| 3 | +/// Where a model comes from. | |
| 4 | 4 | /// |
| 5 | 5 | /// In YAML, either a Hugging Face repository id or a local MLX model directory: |
| 6 | 6 | /// |
| @@ -1,6 +1,6 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | 2 | ||
| 3 | -/// Where the agent's model comes from. | 3 | +/// Where a model comes from. |
| 4 | /// | 4 | /// |
| 5 | /// In YAML, either a Hugging Face repository id or a local MLX model directory: | 5 | /// In YAML, either a Hugging Face repository id or a local MLX model directory: |
| 6 | /// | 6 | /// |
deleted
Sources/RazorbillCore/Config/PromptTemplate.swift +0 -99 | deleted file mode 100644 | ||
| @@ -1,99 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -/// Values available to `{{variables}}` in the system prompt. | |
| 4 | -/// | |
| 5 | -/// ```swift | |
| 6 | -/// let context = TemplateContext(date: Date(), currentDirectory: "/tmp", environment: ["USER": "bob"]) | |
| 7 | -/// ``` | |
| 8 | -public struct TemplateContext: Sendable { | |
| 9 | - public var date: Date | |
| 10 | - public var currentDirectory: String | |
| 11 | - public var environment: [String: String] | |
| 12 | - public var timeZone: TimeZone | |
| 13 | - | |
| 14 | - public init( | |
| 15 | - date: Date, | |
| 16 | - currentDirectory: String, | |
| 17 | - environment: [String: String], | |
| 18 | - timeZone: TimeZone = .current | |
| 19 | - ) { | |
| 20 | - self.date = date | |
| 21 | - self.currentDirectory = currentDirectory | |
| 22 | - self.environment = environment | |
| 23 | - self.timeZone = timeZone | |
| 24 | - } | |
| 25 | - | |
| 26 | - /// The real date, working directory and environment of this process. | |
| 27 | - public static var current: TemplateContext { | |
| 28 | - TemplateContext( | |
| 29 | - date: Date(), | |
| 30 | - currentDirectory: FileManager.default.currentDirectoryPath, | |
| 31 | - environment: ProcessInfo.processInfo.environment | |
| 32 | - ) | |
| 33 | - } | |
| 34 | -} | |
| 35 | - | |
| 36 | -/// Replaces the variables of a system prompt. Deliberately small: no loops, no conditions. | |
| 37 | -/// | |
| 38 | -/// | Variable | Value | | |
| 39 | -/// | --- | --- | | |
| 40 | -/// | `{{date}}` | today, `YYYY-MM-DD` | | |
| 41 | -/// | `{{cwd}}` | the current directory | | |
| 42 | -/// | `{{env.NAME}}` | the environment variable `NAME` (an error if it is not set) | | |
| 43 | -/// | |
| 44 | -/// ```swift | |
| 45 | -/// let text = try PromptTemplate.render("Today is {{date}}.", context: .current) | |
| 46 | -/// ``` | |
| 47 | -public enum PromptTemplate { | |
| 48 | - /// A variable that is unknown or has no value. | |
| 49 | - public struct UnresolvedVariable: Error, Equatable, CustomStringConvertible { | |
| 50 | - public let name: String | |
| 51 | - public let reason: String | |
| 52 | - public var description: String { "{{\(name)}}: \(reason)" } | |
| 53 | - } | |
| 54 | - | |
| 55 | - /// Returns `text` with every `{{variable}}` replaced; spaces inside the braces are allowed. | |
| 56 | - public static func render(_ text: String, context: TemplateContext) throws -> String { | |
| 57 | - var output = "" | |
| 58 | - var rest = Substring(text) | |
| 59 | - while let open = rest.range(of: "{{") { | |
| 60 | - output += rest[..<open.lowerBound] | |
| 61 | - guard let close = rest[open.upperBound...].range(of: "}}") else { | |
| 62 | - output += rest[open.lowerBound...] | |
| 63 | - return output | |
| 64 | - } | |
| 65 | - let name = rest[open.upperBound ..< close.lowerBound].trimmingCharacters( | |
| 66 | - in: .whitespaces) | |
| 67 | - output += try value(of: name, context: context) | |
| 68 | - rest = rest[close.upperBound...] | |
| 69 | - } | |
| 70 | - return output + rest | |
| 71 | - } | |
| 72 | - | |
| 73 | - private static func value(of name: String, context: TemplateContext) throws -> String { | |
| 74 | - switch name { | |
| 75 | - case "date": | |
| 76 | - return isoDay(context.date, timeZone: context.timeZone) | |
| 77 | - case "cwd": | |
| 78 | - return context.currentDirectory | |
| 79 | - default: | |
| 80 | - guard name.hasPrefix("env.") else { | |
| 81 | - throw UnresolvedVariable( | |
| 82 | - name: name, reason: "unknown variable (use date, cwd or env.NAME)") | |
| 83 | - } | |
| 84 | - let variable = String(name.dropFirst("env.".count)) | |
| 85 | - guard let value = context.environment[variable] else { | |
| 86 | - throw UnresolvedVariable( | |
| 87 | - name: name, reason: "environment variable \(variable) is not set") | |
| 88 | - } | |
| 89 | - return value | |
| 90 | - } | |
| 91 | - } | |
| 92 | - | |
| 93 | - private static func isoDay(_ date: Date, timeZone: TimeZone) -> String { | |
| 94 | - var calendar = Calendar(identifier: .gregorian) | |
| 95 | - calendar.timeZone = timeZone | |
| 96 | - let parts = calendar.dateComponents([.year, .month, .day], from: date) | |
| 97 | - return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0) | |
| 98 | - } | |
| 99 | -} | |
| deleted file mode 100644 | |||
| @@ -1,99 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -/// Values available to `{{variables}}` in the system prompt. | ||
| 4 | -/// | ||
| 5 | -/// ```swift | ||
| 6 | -/// let context = TemplateContext(date: Date(), currentDirectory: "/tmp", environment: ["USER": "bob"]) | ||
| 7 | -/// ``` | ||
| 8 | -public struct TemplateContext: Sendable { | ||
| 9 | - public var date: Date | ||
| 10 | - public var currentDirectory: String | ||
| 11 | - public var environment: [String: String] | ||
| 12 | - public var timeZone: TimeZone | ||
| 13 | - | ||
| 14 | - public init( | ||
| 15 | - date: Date, | ||
| 16 | - currentDirectory: String, | ||
| 17 | - environment: [String: String], | ||
| 18 | - timeZone: TimeZone = .current | ||
| 19 | - ) { | ||
| 20 | - self.date = date | ||
| 21 | - self.currentDirectory = currentDirectory | ||
| 22 | - self.environment = environment | ||
| 23 | - self.timeZone = timeZone | ||
| 24 | - } | ||
| 25 | - | ||
| 26 | - /// The real date, working directory and environment of this process. | ||
| 27 | - public static var current: TemplateContext { | ||
| 28 | - TemplateContext( | ||
| 29 | - date: Date(), | ||
| 30 | - currentDirectory: FileManager.default.currentDirectoryPath, | ||
| 31 | - environment: ProcessInfo.processInfo.environment | ||
| 32 | - ) | ||
| 33 | - } | ||
| 34 | -} | ||
| 35 | - | ||
| 36 | -/// Replaces the variables of a system prompt. Deliberately small: no loops, no conditions. | ||
| 37 | -/// | ||
| 38 | -/// | Variable | Value | | ||
| 39 | -/// | --- | --- | | ||
| 40 | -/// | `{{date}}` | today, `YYYY-MM-DD` | | ||
| 41 | -/// | `{{cwd}}` | the current directory | | ||
| 42 | -/// | `{{env.NAME}}` | the environment variable `NAME` (an error if it is not set) | | ||
| 43 | -/// | ||
| 44 | -/// ```swift | ||
| 45 | -/// let text = try PromptTemplate.render("Today is {{date}}.", context: .current) | ||
| 46 | -/// ``` | ||
| 47 | -public enum PromptTemplate { | ||
| 48 | - /// A variable that is unknown or has no value. | ||
| 49 | - public struct UnresolvedVariable: Error, Equatable, CustomStringConvertible { | ||
| 50 | - public let name: String | ||
| 51 | - public let reason: String | ||
| 52 | - public var description: String { "{{\(name)}}: \(reason)" } | ||
| 53 | - } | ||
| 54 | - | ||
| 55 | - /// Returns `text` with every `{{variable}}` replaced; spaces inside the braces are allowed. | ||
| 56 | - public static func render(_ text: String, context: TemplateContext) throws -> String { | ||
| 57 | - var output = "" | ||
| 58 | - var rest = Substring(text) | ||
| 59 | - while let open = rest.range(of: "{{") { | ||
| 60 | - output += rest[..<open.lowerBound] | ||
| 61 | - guard let close = rest[open.upperBound...].range(of: "}}") else { | ||
| 62 | - output += rest[open.lowerBound...] | ||
| 63 | - return output | ||
| 64 | - } | ||
| 65 | - let name = rest[open.upperBound ..< close.lowerBound].trimmingCharacters( | ||
| 66 | - in: .whitespaces) | ||
| 67 | - output += try value(of: name, context: context) | ||
| 68 | - rest = rest[close.upperBound...] | ||
| 69 | - } | ||
| 70 | - return output + rest | ||
| 71 | - } | ||
| 72 | - | ||
| 73 | - private static func value(of name: String, context: TemplateContext) throws -> String { | ||
| 74 | - switch name { | ||
| 75 | - case "date": | ||
| 76 | - return isoDay(context.date, timeZone: context.timeZone) | ||
| 77 | - case "cwd": | ||
| 78 | - return context.currentDirectory | ||
| 79 | - default: | ||
| 80 | - guard name.hasPrefix("env.") else { | ||
| 81 | - throw UnresolvedVariable( | ||
| 82 | - name: name, reason: "unknown variable (use date, cwd or env.NAME)") | ||
| 83 | - } | ||
| 84 | - let variable = String(name.dropFirst("env.".count)) | ||
| 85 | - guard let value = context.environment[variable] else { | ||
| 86 | - throw UnresolvedVariable( | ||
| 87 | - name: name, reason: "environment variable \(variable) is not set") | ||
| 88 | - } | ||
| 89 | - return value | ||
| 90 | - } | ||
| 91 | - } | ||
| 92 | - | ||
| 93 | - private static func isoDay(_ date: Date, timeZone: TimeZone) -> String { | ||
| 94 | - var calendar = Calendar(identifier: .gregorian) | ||
| 95 | - calendar.timeZone = timeZone | ||
| 96 | - let parts = calendar.dateComponents([.year, .month, .day], from: date) | ||
| 97 | - return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0) | ||
| 98 | - } | ||
| 99 | -} | ||
added
Sources/RazorbillCore/Config/Quantities.swift +40 -0 | new file mode 100644 | ||
| @@ -0,0 +1,40 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// Parses the durations and sizes written in configuration files. | |
| 4 | +/// | |
| 5 | +/// ```swift | |
| 6 | +/// Quantities.duration("10m") // .seconds(600) | |
| 7 | +/// Quantities.byteCount("16KB") // 16_384 | |
| 8 | +/// ``` | |
| 9 | +public enum Quantities { | |
| 10 | + /// A positive duration written as a number followed by `ms`, `s`, `m` or `h`; `nil` otherwise. | |
| 11 | + public static func duration(_ text: String) -> Duration? { | |
| 12 | + let units: [Unit] = [ | |
| 13 | + ("ms", 1), ("s", 1000), ("m", 60_000), ("h", 3_600_000), | |
| 14 | + ] | |
| 15 | + return parse(text, units: units).map { .milliseconds(Int64($0)) } | |
| 16 | + } | |
| 17 | + | |
| 18 | + /// A positive size written as a number followed by `B`, `KB` or `MB` (1 KB = 1024 bytes), | |
| 19 | + /// in any case; `nil` otherwise. | |
| 20 | + public static func byteCount(_ text: String) -> Int? { | |
| 21 | + let units: [Unit] = [ | |
| 22 | + ("KB", 1024), ("MB", 1024 * 1024), ("B", 1), | |
| 23 | + ] | |
| 24 | + return parse(text.uppercased(), units: units).map { Int($0) } | |
| 25 | + } | |
| 26 | + | |
| 27 | + /// A unit suffix and how many base units (milliseconds or bytes) it stands for. | |
| 28 | + private typealias Unit = (suffix: String, factor: Double) | |
| 29 | + | |
| 30 | + /// `<number><suffix>` → number × factor, for the first suffix that matches; `nil` otherwise. | |
| 31 | + private static func parse(_ text: String, units: [Unit]) -> Double? { | |
| 32 | + let trimmed = text.trimmingCharacters(in: .whitespaces) | |
| 33 | + for unit in units where trimmed.hasSuffix(unit.suffix) { | |
| 34 | + let number = trimmed.dropLast(unit.suffix.count).trimmingCharacters(in: .whitespaces) | |
| 35 | + guard let value = Double(number), value > 0 else { return nil } | |
| 36 | + return value * unit.factor | |
| 37 | + } | |
| 38 | + return nil | |
| 39 | + } | |
| 40 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,40 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// Parses the durations and sizes written in configuration files. | ||
| 4 | +/// | ||
| 5 | +/// ```swift | ||
| 6 | +/// Quantities.duration("10m") // .seconds(600) | ||
| 7 | +/// Quantities.byteCount("16KB") // 16_384 | ||
| 8 | +/// ``` | ||
| 9 | +public enum Quantities { | ||
| 10 | + /// A positive duration written as a number followed by `ms`, `s`, `m` or `h`; `nil` otherwise. | ||
| 11 | + public static func duration(_ text: String) -> Duration? { | ||
| 12 | + let units: [Unit] = [ | ||
| 13 | + ("ms", 1), ("s", 1000), ("m", 60_000), ("h", 3_600_000), | ||
| 14 | + ] | ||
| 15 | + return parse(text, units: units).map { .milliseconds(Int64($0)) } | ||
| 16 | + } | ||
| 17 | + | ||
| 18 | + /// A positive size written as a number followed by `B`, `KB` or `MB` (1 KB = 1024 bytes), | ||
| 19 | + /// in any case; `nil` otherwise. | ||
| 20 | + public static func byteCount(_ text: String) -> Int? { | ||
| 21 | + let units: [Unit] = [ | ||
| 22 | + ("KB", 1024), ("MB", 1024 * 1024), ("B", 1), | ||
| 23 | + ] | ||
| 24 | + return parse(text.uppercased(), units: units).map { Int($0) } | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + /// A unit suffix and how many base units (milliseconds or bytes) it stands for. | ||
| 28 | + private typealias Unit = (suffix: String, factor: Double) | ||
| 29 | + | ||
| 30 | + /// `<number><suffix>` → number × factor, for the first suffix that matches; `nil` otherwise. | ||
| 31 | + private static func parse(_ text: String, units: [Unit]) -> Double? { | ||
| 32 | + let trimmed = text.trimmingCharacters(in: .whitespaces) | ||
| 33 | + for unit in units where trimmed.hasSuffix(unit.suffix) { | ||
| 34 | + let number = trimmed.dropLast(unit.suffix.count).trimmingCharacters(in: .whitespaces) | ||
| 35 | + guard let value = Double(number), value > 0 else { return nil } | ||
| 36 | + return value * unit.factor | ||
| 37 | + } | ||
| 38 | + return nil | ||
| 39 | + } | ||
| 40 | +} | ||
added
Sources/RazorbillCore/Engine/GenerationSettings.swift +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +/// Sampling settings for one answer. | |
| 2 | +/// | |
| 3 | +/// ```swift | |
| 4 | +/// let settings = GenerationSettings(temperature: 0, maxTokens: 256, thinking: true, thinkingBudget: 64) | |
| 5 | +/// ``` | |
| 6 | +public struct GenerationSettings: Sendable, Equatable { | |
| 7 | + /// Sampling temperature; 0 makes the answer deterministic. Default 0.6. | |
| 8 | + public var temperature: Double | |
| 9 | + /// Nucleus sampling threshold, in (0, 1]. Default 1 (disabled). | |
| 10 | + public var topP: Double | |
| 11 | + /// Maximum number of tokens generated per answer. Default 1024. | |
| 12 | + public var maxTokens: Int | |
| 13 | + /// Let reasoning models think before answering. Default false. | |
| 14 | + public var thinking: Bool | |
| 15 | + /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. | |
| 16 | + /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. | |
| 17 | + public var thinkingBudget: Int? | |
| 18 | + | |
| 19 | + public init( | |
| 20 | + temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, | |
| 21 | + thinking: Bool = false, thinkingBudget: Int? = nil | |
| 22 | + ) { | |
| 23 | + self.temperature = temperature | |
| 24 | + self.topP = topP | |
| 25 | + self.maxTokens = maxTokens | |
| 26 | + self.thinking = thinking | |
| 27 | + self.thinkingBudget = thinkingBudget | |
| 28 | + } | |
| 29 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +/// Sampling settings for one answer. | ||
| 2 | +/// | ||
| 3 | +/// ```swift | ||
| 4 | +/// let settings = GenerationSettings(temperature: 0, maxTokens: 256, thinking: true, thinkingBudget: 64) | ||
| 5 | +/// ``` | ||
| 6 | +public struct GenerationSettings: Sendable, Equatable { | ||
| 7 | + /// Sampling temperature; 0 makes the answer deterministic. Default 0.6. | ||
| 8 | + public var temperature: Double | ||
| 9 | + /// Nucleus sampling threshold, in (0, 1]. Default 1 (disabled). | ||
| 10 | + public var topP: Double | ||
| 11 | + /// Maximum number of tokens generated per answer. Default 1024. | ||
| 12 | + public var maxTokens: Int | ||
| 13 | + /// Let reasoning models think before answering. Default false. | ||
| 14 | + public var thinking: Bool | ||
| 15 | + /// Most tokens a model may spend thinking before it is made to answer; `nil` = no limit. | ||
| 16 | + /// Counted inside ``maxTokens``, so it must be smaller. Default `nil`. | ||
| 17 | + public var thinkingBudget: Int? | ||
| 18 | + | ||
| 19 | + public init( | ||
| 20 | + temperature: Double = 0.6, topP: Double = 1.0, maxTokens: Int = 1024, | ||
| 21 | + thinking: Bool = false, thinkingBudget: Int? = nil | ||
| 22 | + ) { | ||
| 23 | + self.temperature = temperature | ||
| 24 | + self.topP = topP | ||
| 25 | + self.maxTokens = maxTokens | ||
| 26 | + self.thinking = thinking | ||
| 27 | + self.thinkingBudget = thinkingBudget | ||
| 28 | + } | ||
| 29 | +} | ||
modified
Sources/RazorbillCore/Engine/InferenceEngine.swift +3 -3 | @@ -4,7 +4,7 @@ public enum EngineEvent: Sendable, Equatable { | ||
| 4 | 4 | case text(String) |
| 5 | 5 | /// A piece of the model's reasoning, for models that think before answering. |
| 6 | 6 | case thinking(String) |
| 7 | - /// The model wants a tool to run. The turn ends after its text; the agent answers with the result. | |
| 7 | + /// The model wants a tool to run. The answer ends after its text; the caller runs the tool. | |
| 8 | 8 | case toolCall(ToolCall) |
| 9 | 9 | /// Statistics, sent once at the end of the answer. |
| 10 | 10 | case stats(GenerationStats) |
| @@ -23,8 +23,8 @@ public struct SessionSetup: Sendable, Equatable { | ||
| 23 | 23 | } |
| 24 | 24 | } |
| 25 | 25 | |
| 26 | -/// Runs a model. razorbill talks to models only through this protocol, which keeps the agent, | |
| 27 | -/// the CLI and the TUI independent of MLX (and testable on Linux with ``FakeEngine``). | |
| 26 | +/// Runs a model. razorbill talks to models only through this protocol, which keeps the server | |
| 27 | +/// and the CLI independent of MLX (and testable on Linux with ``FakeEngine``). | |
| 28 | 28 | /// |
| 29 | 29 | /// ```swift |
| 30 | 30 | /// try await engine.load(.huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main"), |
| @@ -4,7 +4,7 @@ public enum EngineEvent: Sendable, Equatable { | |||
| 4 | case text(String) | 4 | case text(String) |
| 5 | /// A piece of the model's reasoning, for models that think before answering. | 5 | /// A piece of the model's reasoning, for models that think before answering. |
| 6 | case thinking(String) | 6 | case thinking(String) |
| 7 | - /// The model wants a tool to run. The turn ends after its text; the agent answers with the result. | 7 | + /// The model wants a tool to run. The answer ends after its text; the caller runs the tool. |
| 8 | case toolCall(ToolCall) | 8 | case toolCall(ToolCall) |
| 9 | /// Statistics, sent once at the end of the answer. | 9 | /// Statistics, sent once at the end of the answer. |
| 10 | case stats(GenerationStats) | 10 | case stats(GenerationStats) |
| @@ -23,8 +23,8 @@ public struct SessionSetup: Sendable, Equatable { | |||
| 23 | } | 23 | } |
| 24 | } | 24 | } |
| 25 | 25 | ||
| 26 | -/// Runs a model. razorbill talks to models only through this protocol, which keeps the agent, | 26 | +/// Runs a model. razorbill talks to models only through this protocol, which keeps the server |
| 27 | -/// the CLI and the TUI independent of MLX (and testable on Linux with ``FakeEngine``). | 27 | +/// and the CLI independent of MLX (and testable on Linux with ``FakeEngine``). |
| 28 | /// | 28 | /// |
| 29 | /// ```swift | 29 | /// ```swift |
| 30 | /// try await engine.load(.huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main"), | 30 | /// try await engine.load(.huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main"), |
modified
Sources/RazorbillCore/Engine/Messages.swift +2 -2 | @@ -1,8 +1,8 @@ | ||
| 1 | -/// One message of a conversation, as exchanged between the agent and the engine. | |
| 1 | +/// One message of a conversation, as passed to the engine. | |
| 2 | 2 | /// |
| 3 | 3 | /// ```swift |
| 4 | 4 | /// let question = ChatMessage.user("What is Swift?") |
| 5 | -/// let result = ChatMessage.tool("README.md", name: "bash", callID: "call-1") | |
| 5 | +/// let result = ChatMessage.tool("12°C", name: "get_weather", callID: "call-1") | |
| 6 | 6 | /// ``` |
| 7 | 7 | public struct ChatMessage: Sendable, Equatable { |
| 8 | 8 | public enum Role: String, Sendable { |
| @@ -1,8 +1,8 @@ | |||
| 1 | -/// One message of a conversation, as exchanged between the agent and the engine. | 1 | +/// One message of a conversation, as passed to the engine. |
| 2 | /// | 2 | /// |
| 3 | /// ```swift | 3 | /// ```swift |
| 4 | /// let question = ChatMessage.user("What is Swift?") | 4 | /// let question = ChatMessage.user("What is Swift?") |
| 5 | -/// let result = ChatMessage.tool("README.md", name: "bash", callID: "call-1") | 5 | +/// let result = ChatMessage.tool("12°C", name: "get_weather", callID: "call-1") |
| 6 | /// ``` | 6 | /// ``` |
| 7 | public struct ChatMessage: Sendable, Equatable { | 7 | public struct ChatMessage: Sendable, Equatable { |
| 8 | public enum Role: String, Sendable { | 8 | public enum Role: String, Sendable { |
modified
Sources/RazorbillCore/Razorbill.swift +1 -1 | @@ -1,4 +1,4 @@ | ||
| 1 | -/// Identity of the razorbill agent. | |
| 1 | +/// Identity of razorbill. | |
| 2 | 2 | /// |
| 3 | 3 | /// ```swift |
| 4 | 4 | /// print("\(Razorbill.commandName) \(Razorbill.version)") // "rzb 0.1.0" |
| @@ -1,4 +1,4 @@ | |||
| 1 | -/// Identity of the razorbill agent. | 1 | +/// Identity of razorbill. |
| 2 | /// | 2 | /// |
| 3 | /// ```swift | 3 | /// ```swift |
| 4 | /// print("\(Razorbill.commandName) \(Razorbill.version)") // "rzb 0.1.0" | 4 | /// print("\(Razorbill.commandName) \(Razorbill.version)") // "rzb 0.1.0" |
deleted
Sources/RazorbillCore/Tools/AgentTool.swift +0 -68 | deleted file mode 100644 | ||
| @@ -1,68 +0,0 @@ | ||
| 1 | -/// What a tool may ask of the front-end while it runs. | |
| 2 | -/// | |
| 3 | -/// ```swift | |
| 4 | -/// let context = ToolContext(isInteractive: true) { request in | |
| 5 | -/// print(request.summary); return readLine() == "y" | |
| 6 | -/// } | |
| 7 | -/// ``` | |
| 8 | -public struct ToolContext: Sendable { | |
| 9 | - /// Asked before a tool does something that needs the user's consent. | |
| 10 | - public struct ConfirmationRequest: Sendable, Equatable { | |
| 11 | - public var toolName: String | |
| 12 | - /// One line shown to the user, e.g. the command about to run. | |
| 13 | - public var summary: String | |
| 14 | - | |
| 15 | - public init(toolName: String, summary: String) { | |
| 16 | - self.toolName = toolName | |
| 17 | - self.summary = summary | |
| 18 | - } | |
| 19 | - } | |
| 20 | - | |
| 21 | - /// Whether someone can answer a confirmation (a terminal is attached). | |
| 22 | - public var isInteractive: Bool | |
| 23 | - /// Asks the user; returns `true` when they accept. Never called when not interactive. | |
| 24 | - public var confirm: @Sendable (ConfirmationRequest) async -> Bool | |
| 25 | - | |
| 26 | - public init( | |
| 27 | - isInteractive: Bool, confirm: @escaping @Sendable (ConfirmationRequest) async -> Bool | |
| 28 | - ) { | |
| 29 | - self.isInteractive = isInteractive | |
| 30 | - self.confirm = confirm | |
| 31 | - } | |
| 32 | - | |
| 33 | - /// No terminal: confirmations are impossible. | |
| 34 | - public static let nonInteractive = ToolContext(isInteractive: false) { _ in false } | |
| 35 | -} | |
| 36 | - | |
| 37 | -/// The outcome of a tool call, sent back to the model. | |
| 38 | -public struct ToolOutput: Sendable, Equatable { | |
| 39 | - public var content: String | |
| 40 | - /// `true` when the tool failed or refused; the model still receives `content`. | |
| 41 | - public var isError: Bool | |
| 42 | - | |
| 43 | - public init(_ content: String, isError: Bool = false) { | |
| 44 | - self.content = content | |
| 45 | - self.isError = isError | |
| 46 | - } | |
| 47 | -} | |
| 48 | - | |
| 49 | -/// A tool the model can call. | |
| 50 | -/// | |
| 51 | -/// Adding a tool means writing one type that conforms to this protocol (and registering it, | |
| 52 | -/// see ``ToolRegistry``): | |
| 53 | -/// | |
| 54 | -/// ```swift | |
| 55 | -/// struct Clock: AgentTool { | |
| 56 | -/// let spec = ToolSpec(name: "clock", description: "Current time", | |
| 57 | -/// parameters: .map(["type": .string("object")])) | |
| 58 | -/// func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | |
| 59 | -/// ToolOutput("\(Date())") | |
| 60 | -/// } | |
| 61 | -/// } | |
| 62 | -/// ``` | |
| 63 | -public protocol AgentTool: Sendable { | |
| 64 | - var spec: ToolSpec { get } | |
| 65 | - | |
| 66 | - /// Runs the tool. Throwing is reported to the model as an error result, not as a crash. | |
| 67 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput | |
| 68 | -} | |
| deleted file mode 100644 | |||
| @@ -1,68 +0,0 @@ | |||
| 1 | -/// What a tool may ask of the front-end while it runs. | ||
| 2 | -/// | ||
| 3 | -/// ```swift | ||
| 4 | -/// let context = ToolContext(isInteractive: true) { request in | ||
| 5 | -/// print(request.summary); return readLine() == "y" | ||
| 6 | -/// } | ||
| 7 | -/// ``` | ||
| 8 | -public struct ToolContext: Sendable { | ||
| 9 | - /// Asked before a tool does something that needs the user's consent. | ||
| 10 | - public struct ConfirmationRequest: Sendable, Equatable { | ||
| 11 | - public var toolName: String | ||
| 12 | - /// One line shown to the user, e.g. the command about to run. | ||
| 13 | - public var summary: String | ||
| 14 | - | ||
| 15 | - public init(toolName: String, summary: String) { | ||
| 16 | - self.toolName = toolName | ||
| 17 | - self.summary = summary | ||
| 18 | - } | ||
| 19 | - } | ||
| 20 | - | ||
| 21 | - /// Whether someone can answer a confirmation (a terminal is attached). | ||
| 22 | - public var isInteractive: Bool | ||
| 23 | - /// Asks the user; returns `true` when they accept. Never called when not interactive. | ||
| 24 | - public var confirm: @Sendable (ConfirmationRequest) async -> Bool | ||
| 25 | - | ||
| 26 | - public init( | ||
| 27 | - isInteractive: Bool, confirm: @escaping @Sendable (ConfirmationRequest) async -> Bool | ||
| 28 | - ) { | ||
| 29 | - self.isInteractive = isInteractive | ||
| 30 | - self.confirm = confirm | ||
| 31 | - } | ||
| 32 | - | ||
| 33 | - /// No terminal: confirmations are impossible. | ||
| 34 | - public static let nonInteractive = ToolContext(isInteractive: false) { _ in false } | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | -/// The outcome of a tool call, sent back to the model. | ||
| 38 | -public struct ToolOutput: Sendable, Equatable { | ||
| 39 | - public var content: String | ||
| 40 | - /// `true` when the tool failed or refused; the model still receives `content`. | ||
| 41 | - public var isError: Bool | ||
| 42 | - | ||
| 43 | - public init(_ content: String, isError: Bool = false) { | ||
| 44 | - self.content = content | ||
| 45 | - self.isError = isError | ||
| 46 | - } | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -/// A tool the model can call. | ||
| 50 | -/// | ||
| 51 | -/// Adding a tool means writing one type that conforms to this protocol (and registering it, | ||
| 52 | -/// see ``ToolRegistry``): | ||
| 53 | -/// | ||
| 54 | -/// ```swift | ||
| 55 | -/// struct Clock: AgentTool { | ||
| 56 | -/// let spec = ToolSpec(name: "clock", description: "Current time", | ||
| 57 | -/// parameters: .map(["type": .string("object")])) | ||
| 58 | -/// func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | ||
| 59 | -/// ToolOutput("\(Date())") | ||
| 60 | -/// } | ||
| 61 | -/// } | ||
| 62 | -/// ``` | ||
| 63 | -public protocol AgentTool: Sendable { | ||
| 64 | - var spec: ToolSpec { get } | ||
| 65 | - | ||
| 66 | - /// Runs the tool. Throwing is reported to the model as an error result, not as a crash. | ||
| 67 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput | ||
| 68 | -} | ||
deleted
Sources/RazorbillCore/Tools/BashTool.swift +0 -143 | deleted file mode 100644 | ||
| @@ -1,143 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -/// Built-in tool `bash`: lets the model run shell commands on the user's machine. | |
| 4 | -/// | |
| 5 | -/// It runs real commands with the user's rights, so it is guarded: | |
| 6 | -/// - it exists only when listed under `tools:` in the agent file; | |
| 7 | -/// - `deny` patterns always win, then `allow` patterns (when given) must match; | |
| 8 | -/// - with `confirm: true` (the default) the user accepts each command; with no terminal to ask, | |
| 9 | -/// commands are refused unless `confirm: false` is set explicitly; | |
| 10 | -/// - each command is killed (with everything it started) after `timeout`; | |
| 11 | -/// - output beyond `max_output` is dropped, with a marker. | |
| 12 | -/// | |
| 13 | -/// Patterns are a convenience, not a sandbox: `ls *` also matches `ls; rm -rf ~`. | |
| 14 | -/// | |
| 15 | -/// ```yaml | |
| 16 | -/// tools: | |
| 17 | -/// bash: | |
| 18 | -/// confirm: true | |
| 19 | -/// workdir: . | |
| 20 | -/// timeout: 30s | |
| 21 | -/// max_output: 16KB | |
| 22 | -/// allow: ["ls*", "git status"] | |
| 23 | -/// deny: ["rm -rf*", "sudo *"] | |
| 24 | -/// ``` | |
| 25 | -public struct BashTool: AgentTool { | |
| 26 | - public static let name = "bash" | |
| 27 | - static let optionKeys = ["confirm", "workdir", "timeout", "max_output", "allow", "deny"] | |
| 28 | - | |
| 29 | - public var confirm: Bool | |
| 30 | - /// Absolute directory the commands run in. | |
| 31 | - public var workingDirectory: String | |
| 32 | - public var timeout: Duration | |
| 33 | - public var maxOutputBytes: Int | |
| 34 | - public var allow: [String] | |
| 35 | - public var deny: [String] | |
| 36 | - | |
| 37 | - public let spec = ToolSpec( | |
| 38 | - name: BashTool.name, | |
| 39 | - description: """ | |
| 40 | - Run a shell command with bash on the user's computer and return its exit code, \ | |
| 41 | - standard output and standard error. Use it to inspect files, run builds or tests. \ | |
| 42 | - Commands may need the user's approval and are stopped after a time limit. | |
| 43 | - """, | |
| 44 | - parameters: .map([ | |
| 45 | - "type": .string("object"), | |
| 46 | - "properties": .map(["command": commandParameter]), | |
| 47 | - "required": .list([.string("command")]), | |
| 48 | - ]) | |
| 49 | - ) | |
| 50 | - | |
| 51 | - /// JSON Schema of the single `command` argument. | |
| 52 | - private static let commandParameter: ConfigValue = .map([ | |
| 53 | - "type": .string("string"), | |
| 54 | - "description": .string("The command line to run, e.g. `ls -la`."), | |
| 55 | - ]) | |
| 56 | - | |
| 57 | - public init( | |
| 58 | - confirm: Bool = true, workingDirectory: String, timeout: Duration = .seconds(30), | |
| 59 | - maxOutputBytes: Int = 16 * 1024, allow: [String] = [], deny: [String] = [] | |
| 60 | - ) { | |
| 61 | - self.confirm = confirm | |
| 62 | - self.workingDirectory = workingDirectory | |
| 63 | - self.timeout = timeout | |
| 64 | - self.maxOutputBytes = maxOutputBytes | |
| 65 | - self.allow = allow | |
| 66 | - self.deny = deny | |
| 67 | - } | |
| 68 | - | |
| 69 | - /// Builds the tool from its YAML options (see the type documentation). | |
| 70 | - public init(options: ConfigValue, environment: ToolEnvironment) throws { | |
| 71 | - let reader = OptionReader(options) | |
| 72 | - try reader.rejectUnknownKeys(Self.optionKeys) | |
| 73 | - let workdir = try reader.string("workdir", default: ".") | |
| 74 | - self.init( | |
| 75 | - confirm: try reader.bool("confirm", default: true), | |
| 76 | - workingDirectory: Self.absolute(workdir, from: environment.baseDirectory), | |
| 77 | - timeout: try reader.duration("timeout", default: .seconds(30)), | |
| 78 | - maxOutputBytes: try reader.byteCount("max_output", default: 16 * 1024), | |
| 79 | - allow: try reader.stringList("allow"), | |
| 80 | - deny: try reader.stringList("deny") | |
| 81 | - ) | |
| 82 | - } | |
| 83 | - | |
| 84 | - public func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | |
| 85 | - guard | |
| 86 | - let command = arguments["command"]?.stringValue?.trimmingCharacters( | |
| 87 | - in: .whitespacesAndNewlines), | |
| 88 | - !command.isEmpty | |
| 89 | - else { | |
| 90 | - return ToolOutput("refused: the `command` argument (text) is missing", isError: true) | |
| 91 | - } | |
| 92 | - if let refusal = await refusal(for: command, context: context) { | |
| 93 | - return ToolOutput("refused: \(refusal)", isError: true) | |
| 94 | - } | |
| 95 | - let result = try await ProcessRunner.run( | |
| 96 | - ["/bin/bash", "-c", command], directory: workingDirectory, timeout: timeout, | |
| 97 | - maxOutputBytes: maxOutputBytes) | |
| 98 | - return Self.format(result, timeout: timeout) | |
| 99 | - } | |
| 100 | - | |
| 101 | - /// Why `command` must not run, or `nil` when it may. | |
| 102 | - func refusal(for command: String, context: ToolContext) async -> String? { | |
| 103 | - if let pattern = CommandPattern.firstMatch(command, in: deny) { | |
| 104 | - return "the command matches the deny pattern `\(pattern)`" | |
| 105 | - } | |
| 106 | - if !allow.isEmpty, CommandPattern.firstMatch(command, in: allow) == nil { | |
| 107 | - return "the command matches none of the allow patterns" | |
| 108 | - } | |
| 109 | - guard confirm else { return nil } | |
| 110 | - guard context.isInteractive else { | |
| 111 | - return | |
| 112 | - "no terminal to ask the user for confirmation (set `confirm: false` to allow this)" | |
| 113 | - } | |
| 114 | - let request = ToolContext.ConfirmationRequest( | |
| 115 | - toolName: Self.name, summary: "\(command) (in \(workingDirectory))") | |
| 116 | - return await context.confirm(request) ? nil : "the user declined to run it" | |
| 117 | - } | |
| 118 | - | |
| 119 | - static func format(_ result: ProcessResult, timeout: Duration) -> ToolOutput { | |
| 120 | - var lines: [String] = [] | |
| 121 | - if result.timedOut { | |
| 122 | - // Not `formatted()`: text for the model must not depend on the user's locale. | |
| 123 | - let seconds = String(format: "%g", timeout.seconds) | |
| 124 | - lines.append("timed out after \(seconds)s: the command was killed") | |
| 125 | - } | |
| 126 | - lines.append("exit code: \(result.exitCode)") | |
| 127 | - if !result.stdout.isEmpty { lines.append("stdout:\n\(result.stdout)") } | |
| 128 | - if !result.stderr.isEmpty { lines.append("stderr:\n\(result.stderr)") } | |
| 129 | - if result.droppedBytes > 0 { | |
| 130 | - lines.append("[output truncated: \(result.droppedBytes) more bytes]") | |
| 131 | - } | |
| 132 | - return ToolOutput( | |
| 133 | - lines.joined(separator: "\n"), isError: result.timedOut || result.exitCode != 0) | |
| 134 | - } | |
| 135 | - | |
| 136 | - static func absolute(_ path: String, from base: String) -> String { | |
| 137 | - let url = | |
| 138 | - path.hasPrefix("/") | |
| 139 | - ? URL(fileURLWithPath: path) | |
| 140 | - : URL(fileURLWithPath: base).appendingPathComponent(path) | |
| 141 | - return url.standardizedFileURL.path | |
| 142 | - } | |
| 143 | -} | |
| deleted file mode 100644 | |||
| @@ -1,143 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -/// Built-in tool `bash`: lets the model run shell commands on the user's machine. | ||
| 4 | -/// | ||
| 5 | -/// It runs real commands with the user's rights, so it is guarded: | ||
| 6 | -/// - it exists only when listed under `tools:` in the agent file; | ||
| 7 | -/// - `deny` patterns always win, then `allow` patterns (when given) must match; | ||
| 8 | -/// - with `confirm: true` (the default) the user accepts each command; with no terminal to ask, | ||
| 9 | -/// commands are refused unless `confirm: false` is set explicitly; | ||
| 10 | -/// - each command is killed (with everything it started) after `timeout`; | ||
| 11 | -/// - output beyond `max_output` is dropped, with a marker. | ||
| 12 | -/// | ||
| 13 | -/// Patterns are a convenience, not a sandbox: `ls *` also matches `ls; rm -rf ~`. | ||
| 14 | -/// | ||
| 15 | -/// ```yaml | ||
| 16 | -/// tools: | ||
| 17 | -/// bash: | ||
| 18 | -/// confirm: true | ||
| 19 | -/// workdir: . | ||
| 20 | -/// timeout: 30s | ||
| 21 | -/// max_output: 16KB | ||
| 22 | -/// allow: ["ls*", "git status"] | ||
| 23 | -/// deny: ["rm -rf*", "sudo *"] | ||
| 24 | -/// ``` | ||
| 25 | -public struct BashTool: AgentTool { | ||
| 26 | - public static let name = "bash" | ||
| 27 | - static let optionKeys = ["confirm", "workdir", "timeout", "max_output", "allow", "deny"] | ||
| 28 | - | ||
| 29 | - public var confirm: Bool | ||
| 30 | - /// Absolute directory the commands run in. | ||
| 31 | - public var workingDirectory: String | ||
| 32 | - public var timeout: Duration | ||
| 33 | - public var maxOutputBytes: Int | ||
| 34 | - public var allow: [String] | ||
| 35 | - public var deny: [String] | ||
| 36 | - | ||
| 37 | - public let spec = ToolSpec( | ||
| 38 | - name: BashTool.name, | ||
| 39 | - description: """ | ||
| 40 | - Run a shell command with bash on the user's computer and return its exit code, \ | ||
| 41 | - standard output and standard error. Use it to inspect files, run builds or tests. \ | ||
| 42 | - Commands may need the user's approval and are stopped after a time limit. | ||
| 43 | - """, | ||
| 44 | - parameters: .map([ | ||
| 45 | - "type": .string("object"), | ||
| 46 | - "properties": .map(["command": commandParameter]), | ||
| 47 | - "required": .list([.string("command")]), | ||
| 48 | - ]) | ||
| 49 | - ) | ||
| 50 | - | ||
| 51 | - /// JSON Schema of the single `command` argument. | ||
| 52 | - private static let commandParameter: ConfigValue = .map([ | ||
| 53 | - "type": .string("string"), | ||
| 54 | - "description": .string("The command line to run, e.g. `ls -la`."), | ||
| 55 | - ]) | ||
| 56 | - | ||
| 57 | - public init( | ||
| 58 | - confirm: Bool = true, workingDirectory: String, timeout: Duration = .seconds(30), | ||
| 59 | - maxOutputBytes: Int = 16 * 1024, allow: [String] = [], deny: [String] = [] | ||
| 60 | - ) { | ||
| 61 | - self.confirm = confirm | ||
| 62 | - self.workingDirectory = workingDirectory | ||
| 63 | - self.timeout = timeout | ||
| 64 | - self.maxOutputBytes = maxOutputBytes | ||
| 65 | - self.allow = allow | ||
| 66 | - self.deny = deny | ||
| 67 | - } | ||
| 68 | - | ||
| 69 | - /// Builds the tool from its YAML options (see the type documentation). | ||
| 70 | - public init(options: ConfigValue, environment: ToolEnvironment) throws { | ||
| 71 | - let reader = OptionReader(options) | ||
| 72 | - try reader.rejectUnknownKeys(Self.optionKeys) | ||
| 73 | - let workdir = try reader.string("workdir", default: ".") | ||
| 74 | - self.init( | ||
| 75 | - confirm: try reader.bool("confirm", default: true), | ||
| 76 | - workingDirectory: Self.absolute(workdir, from: environment.baseDirectory), | ||
| 77 | - timeout: try reader.duration("timeout", default: .seconds(30)), | ||
| 78 | - maxOutputBytes: try reader.byteCount("max_output", default: 16 * 1024), | ||
| 79 | - allow: try reader.stringList("allow"), | ||
| 80 | - deny: try reader.stringList("deny") | ||
| 81 | - ) | ||
| 82 | - } | ||
| 83 | - | ||
| 84 | - public func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | ||
| 85 | - guard | ||
| 86 | - let command = arguments["command"]?.stringValue?.trimmingCharacters( | ||
| 87 | - in: .whitespacesAndNewlines), | ||
| 88 | - !command.isEmpty | ||
| 89 | - else { | ||
| 90 | - return ToolOutput("refused: the `command` argument (text) is missing", isError: true) | ||
| 91 | - } | ||
| 92 | - if let refusal = await refusal(for: command, context: context) { | ||
| 93 | - return ToolOutput("refused: \(refusal)", isError: true) | ||
| 94 | - } | ||
| 95 | - let result = try await ProcessRunner.run( | ||
| 96 | - ["/bin/bash", "-c", command], directory: workingDirectory, timeout: timeout, | ||
| 97 | - maxOutputBytes: maxOutputBytes) | ||
| 98 | - return Self.format(result, timeout: timeout) | ||
| 99 | - } | ||
| 100 | - | ||
| 101 | - /// Why `command` must not run, or `nil` when it may. | ||
| 102 | - func refusal(for command: String, context: ToolContext) async -> String? { | ||
| 103 | - if let pattern = CommandPattern.firstMatch(command, in: deny) { | ||
| 104 | - return "the command matches the deny pattern `\(pattern)`" | ||
| 105 | - } | ||
| 106 | - if !allow.isEmpty, CommandPattern.firstMatch(command, in: allow) == nil { | ||
| 107 | - return "the command matches none of the allow patterns" | ||
| 108 | - } | ||
| 109 | - guard confirm else { return nil } | ||
| 110 | - guard context.isInteractive else { | ||
| 111 | - return | ||
| 112 | - "no terminal to ask the user for confirmation (set `confirm: false` to allow this)" | ||
| 113 | - } | ||
| 114 | - let request = ToolContext.ConfirmationRequest( | ||
| 115 | - toolName: Self.name, summary: "\(command) (in \(workingDirectory))") | ||
| 116 | - return await context.confirm(request) ? nil : "the user declined to run it" | ||
| 117 | - } | ||
| 118 | - | ||
| 119 | - static func format(_ result: ProcessResult, timeout: Duration) -> ToolOutput { | ||
| 120 | - var lines: [String] = [] | ||
| 121 | - if result.timedOut { | ||
| 122 | - // Not `formatted()`: text for the model must not depend on the user's locale. | ||
| 123 | - let seconds = String(format: "%g", timeout.seconds) | ||
| 124 | - lines.append("timed out after \(seconds)s: the command was killed") | ||
| 125 | - } | ||
| 126 | - lines.append("exit code: \(result.exitCode)") | ||
| 127 | - if !result.stdout.isEmpty { lines.append("stdout:\n\(result.stdout)") } | ||
| 128 | - if !result.stderr.isEmpty { lines.append("stderr:\n\(result.stderr)") } | ||
| 129 | - if result.droppedBytes > 0 { | ||
| 130 | - lines.append("[output truncated: \(result.droppedBytes) more bytes]") | ||
| 131 | - } | ||
| 132 | - return ToolOutput( | ||
| 133 | - lines.joined(separator: "\n"), isError: result.timedOut || result.exitCode != 0) | ||
| 134 | - } | ||
| 135 | - | ||
| 136 | - static func absolute(_ path: String, from base: String) -> String { | ||
| 137 | - let url = | ||
| 138 | - path.hasPrefix("/") | ||
| 139 | - ? URL(fileURLWithPath: path) | ||
| 140 | - : URL(fileURLWithPath: base).appendingPathComponent(path) | ||
| 141 | - return url.standardizedFileURL.path | ||
| 142 | - } | ||
| 143 | -} | ||
deleted
Sources/RazorbillCore/Tools/OptionValues.swift +0 -144 | deleted file mode 100644 | ||
| @@ -1,144 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -/// Reads typed tool options (durations, sizes, booleans, string lists) out of a ``ConfigValue``. | |
| 4 | -/// | |
| 5 | -/// ```swift | |
| 6 | -/// let reader = OptionReader(options) | |
| 7 | -/// let timeout = try reader.duration("timeout", default: .seconds(30)) | |
| 8 | -/// ``` | |
| 9 | -public struct OptionReader: Sendable { | |
| 10 | - public let options: ConfigValue | |
| 11 | - | |
| 12 | - public init(_ options: ConfigValue) { | |
| 13 | - self.options = options | |
| 14 | - } | |
| 15 | - | |
| 16 | - /// Fails on keys that are not in `allowed`, so typos are not silently ignored. | |
| 17 | - public func rejectUnknownKeys(_ allowed: [String]) throws { | |
| 18 | - guard case .map(let entries) = options else { return } | |
| 19 | - for key in entries.keys.sorted() where !allowed.contains(key) { | |
| 20 | - throw ToolOptionError( | |
| 21 | - key: key, | |
| 22 | - message: "unknown option (expected one of: \(allowed.joined(separator: ", ")))") | |
| 23 | - } | |
| 24 | - } | |
| 25 | - | |
| 26 | - public func bool(_ key: String, default value: Bool) throws -> Bool { | |
| 27 | - guard let raw = options[key], raw != .null else { return value } | |
| 28 | - guard let bool = raw.boolValue else { | |
| 29 | - throw ToolOptionError(key: key, message: "must be true or false") | |
| 30 | - } | |
| 31 | - return bool | |
| 32 | - } | |
| 33 | - | |
| 34 | - public func string(_ key: String, default value: String) throws -> String { | |
| 35 | - guard let raw = options[key], raw != .null else { return value } | |
| 36 | - guard let text = raw.stringValue else { | |
| 37 | - throw ToolOptionError(key: key, message: "must be text") | |
| 38 | - } | |
| 39 | - return text | |
| 40 | - } | |
| 41 | - | |
| 42 | - public func stringList(_ key: String) throws -> [String] { | |
| 43 | - guard let raw = options[key], raw != .null else { return [] } | |
| 44 | - guard let list = raw.stringListValue else { | |
| 45 | - throw ToolOptionError(key: key, message: "must be a list of text") | |
| 46 | - } | |
| 47 | - return list | |
| 48 | - } | |
| 49 | - | |
| 50 | - /// A duration: a number of seconds, or text such as `500ms`, `30s`, `2m`, `1h`. | |
| 51 | - public func duration(_ key: String, default value: Duration) throws -> Duration { | |
| 52 | - guard let raw = options[key], raw != .null else { return value } | |
| 53 | - if let seconds = raw.doubleValue, seconds > 0 { | |
| 54 | - return .milliseconds(Int64(seconds * 1000)) | |
| 55 | - } | |
| 56 | - if let text = raw.stringValue, let parsed = Self.parseDuration(text) { | |
| 57 | - return parsed | |
| 58 | - } | |
| 59 | - throw ToolOptionError( | |
| 60 | - key: key, message: "must be a positive duration such as 30s, 2m or 500ms") | |
| 61 | - } | |
| 62 | - | |
| 63 | - /// A size in bytes: a number, or text such as `512B`, `16KB`, `1MB` (1 KB = 1024 bytes). | |
| 64 | - public func byteCount(_ key: String, default value: Int) throws -> Int { | |
| 65 | - guard let raw = options[key], raw != .null else { return value } | |
| 66 | - if let bytes = raw.intValue, bytes > 0 { | |
| 67 | - return bytes | |
| 68 | - } | |
| 69 | - if let text = raw.stringValue, let parsed = Self.parseByteCount(text) { | |
| 70 | - return parsed | |
| 71 | - } | |
| 72 | - throw ToolOptionError(key: key, message: "must be a positive size such as 16KB or 1MB") | |
| 73 | - } | |
| 74 | - | |
| 75 | - static func parseDuration(_ text: String) -> Duration? { | |
| 76 | - let units: [Unit] = [ | |
| 77 | - ("ms", 1), ("s", 1000), ("m", 60_000), ("h", 3_600_000), | |
| 78 | - ] | |
| 79 | - return parse(text, units: units).map { .milliseconds(Int64($0)) } | |
| 80 | - } | |
| 81 | - | |
| 82 | - static func parseByteCount(_ text: String) -> Int? { | |
| 83 | - let units: [Unit] = [ | |
| 84 | - ("KB", 1024), ("MB", 1024 * 1024), ("B", 1), | |
| 85 | - ] | |
| 86 | - return parse(text.uppercased(), units: units).map { Int($0) } | |
| 87 | - } | |
| 88 | - | |
| 89 | - /// A unit suffix and how many base units (milliseconds or bytes) it stands for. | |
| 90 | - private typealias Unit = (suffix: String, factor: Double) | |
| 91 | - | |
| 92 | - /// `<number><suffix>` → number × factor, for the first suffix that matches; `nil` otherwise. | |
| 93 | - private static func parse(_ text: String, units: [Unit]) -> Double? { | |
| 94 | - let trimmed = text.trimmingCharacters(in: .whitespaces) | |
| 95 | - for unit in units where trimmed.hasSuffix(unit.suffix) { | |
| 96 | - let number = trimmed.dropLast(unit.suffix.count).trimmingCharacters(in: .whitespaces) | |
| 97 | - guard let value = Double(number), value > 0 else { return nil } | |
| 98 | - return value * unit.factor | |
| 99 | - } | |
| 100 | - return nil | |
| 101 | - } | |
| 102 | -} | |
| 103 | - | |
| 104 | -/// Matches a command against shell-style patterns: `*` is any text, `?` any one character. | |
| 105 | -/// | |
| 106 | -/// ```swift | |
| 107 | -/// CommandPattern.matches("git status", pattern: "git *") // true | |
| 108 | -/// ``` | |
| 109 | -public enum CommandPattern { | |
| 110 | - public static func matches(_ command: String, pattern: String) -> Bool { | |
| 111 | - let text = Array(command) | |
| 112 | - let glob = Array(pattern) | |
| 113 | - var textIndex = 0 | |
| 114 | - var globIndex = 0 | |
| 115 | - var starGlob = -1 | |
| 116 | - var starText = 0 | |
| 117 | - while textIndex < text.count { | |
| 118 | - let current = globIndex < glob.count ? glob[globIndex] : nil | |
| 119 | - if current == "?" || current == text[textIndex] { | |
| 120 | - textIndex += 1 | |
| 121 | - globIndex += 1 | |
| 122 | - } else if current == "*" { | |
| 123 | - starGlob = globIndex | |
| 124 | - starText = textIndex | |
| 125 | - globIndex += 1 | |
| 126 | - } else if starGlob >= 0 { | |
| 127 | - globIndex = starGlob + 1 | |
| 128 | - starText += 1 | |
| 129 | - textIndex = starText | |
| 130 | - } else { | |
| 131 | - return false | |
| 132 | - } | |
| 133 | - } | |
| 134 | - while globIndex < glob.count, glob[globIndex] == "*" { | |
| 135 | - globIndex += 1 | |
| 136 | - } | |
| 137 | - return globIndex == glob.count | |
| 138 | - } | |
| 139 | - | |
| 140 | - /// The first pattern of `patterns` that matches `command`. | |
| 141 | - public static func firstMatch(_ command: String, in patterns: [String]) -> String? { | |
| 142 | - patterns.first { matches(command, pattern: $0) } | |
| 143 | - } | |
| 144 | -} | |
| deleted file mode 100644 | |||
| @@ -1,144 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -/// Reads typed tool options (durations, sizes, booleans, string lists) out of a ``ConfigValue``. | ||
| 4 | -/// | ||
| 5 | -/// ```swift | ||
| 6 | -/// let reader = OptionReader(options) | ||
| 7 | -/// let timeout = try reader.duration("timeout", default: .seconds(30)) | ||
| 8 | -/// ``` | ||
| 9 | -public struct OptionReader: Sendable { | ||
| 10 | - public let options: ConfigValue | ||
| 11 | - | ||
| 12 | - public init(_ options: ConfigValue) { | ||
| 13 | - self.options = options | ||
| 14 | - } | ||
| 15 | - | ||
| 16 | - /// Fails on keys that are not in `allowed`, so typos are not silently ignored. | ||
| 17 | - public func rejectUnknownKeys(_ allowed: [String]) throws { | ||
| 18 | - guard case .map(let entries) = options else { return } | ||
| 19 | - for key in entries.keys.sorted() where !allowed.contains(key) { | ||
| 20 | - throw ToolOptionError( | ||
| 21 | - key: key, | ||
| 22 | - message: "unknown option (expected one of: \(allowed.joined(separator: ", ")))") | ||
| 23 | - } | ||
| 24 | - } | ||
| 25 | - | ||
| 26 | - public func bool(_ key: String, default value: Bool) throws -> Bool { | ||
| 27 | - guard let raw = options[key], raw != .null else { return value } | ||
| 28 | - guard let bool = raw.boolValue else { | ||
| 29 | - throw ToolOptionError(key: key, message: "must be true or false") | ||
| 30 | - } | ||
| 31 | - return bool | ||
| 32 | - } | ||
| 33 | - | ||
| 34 | - public func string(_ key: String, default value: String) throws -> String { | ||
| 35 | - guard let raw = options[key], raw != .null else { return value } | ||
| 36 | - guard let text = raw.stringValue else { | ||
| 37 | - throw ToolOptionError(key: key, message: "must be text") | ||
| 38 | - } | ||
| 39 | - return text | ||
| 40 | - } | ||
| 41 | - | ||
| 42 | - public func stringList(_ key: String) throws -> [String] { | ||
| 43 | - guard let raw = options[key], raw != .null else { return [] } | ||
| 44 | - guard let list = raw.stringListValue else { | ||
| 45 | - throw ToolOptionError(key: key, message: "must be a list of text") | ||
| 46 | - } | ||
| 47 | - return list | ||
| 48 | - } | ||
| 49 | - | ||
| 50 | - /// A duration: a number of seconds, or text such as `500ms`, `30s`, `2m`, `1h`. | ||
| 51 | - public func duration(_ key: String, default value: Duration) throws -> Duration { | ||
| 52 | - guard let raw = options[key], raw != .null else { return value } | ||
| 53 | - if let seconds = raw.doubleValue, seconds > 0 { | ||
| 54 | - return .milliseconds(Int64(seconds * 1000)) | ||
| 55 | - } | ||
| 56 | - if let text = raw.stringValue, let parsed = Self.parseDuration(text) { | ||
| 57 | - return parsed | ||
| 58 | - } | ||
| 59 | - throw ToolOptionError( | ||
| 60 | - key: key, message: "must be a positive duration such as 30s, 2m or 500ms") | ||
| 61 | - } | ||
| 62 | - | ||
| 63 | - /// A size in bytes: a number, or text such as `512B`, `16KB`, `1MB` (1 KB = 1024 bytes). | ||
| 64 | - public func byteCount(_ key: String, default value: Int) throws -> Int { | ||
| 65 | - guard let raw = options[key], raw != .null else { return value } | ||
| 66 | - if let bytes = raw.intValue, bytes > 0 { | ||
| 67 | - return bytes | ||
| 68 | - } | ||
| 69 | - if let text = raw.stringValue, let parsed = Self.parseByteCount(text) { | ||
| 70 | - return parsed | ||
| 71 | - } | ||
| 72 | - throw ToolOptionError(key: key, message: "must be a positive size such as 16KB or 1MB") | ||
| 73 | - } | ||
| 74 | - | ||
| 75 | - static func parseDuration(_ text: String) -> Duration? { | ||
| 76 | - let units: [Unit] = [ | ||
| 77 | - ("ms", 1), ("s", 1000), ("m", 60_000), ("h", 3_600_000), | ||
| 78 | - ] | ||
| 79 | - return parse(text, units: units).map { .milliseconds(Int64($0)) } | ||
| 80 | - } | ||
| 81 | - | ||
| 82 | - static func parseByteCount(_ text: String) -> Int? { | ||
| 83 | - let units: [Unit] = [ | ||
| 84 | - ("KB", 1024), ("MB", 1024 * 1024), ("B", 1), | ||
| 85 | - ] | ||
| 86 | - return parse(text.uppercased(), units: units).map { Int($0) } | ||
| 87 | - } | ||
| 88 | - | ||
| 89 | - /// A unit suffix and how many base units (milliseconds or bytes) it stands for. | ||
| 90 | - private typealias Unit = (suffix: String, factor: Double) | ||
| 91 | - | ||
| 92 | - /// `<number><suffix>` → number × factor, for the first suffix that matches; `nil` otherwise. | ||
| 93 | - private static func parse(_ text: String, units: [Unit]) -> Double? { | ||
| 94 | - let trimmed = text.trimmingCharacters(in: .whitespaces) | ||
| 95 | - for unit in units where trimmed.hasSuffix(unit.suffix) { | ||
| 96 | - let number = trimmed.dropLast(unit.suffix.count).trimmingCharacters(in: .whitespaces) | ||
| 97 | - guard let value = Double(number), value > 0 else { return nil } | ||
| 98 | - return value * unit.factor | ||
| 99 | - } | ||
| 100 | - return nil | ||
| 101 | - } | ||
| 102 | -} | ||
| 103 | - | ||
| 104 | -/// Matches a command against shell-style patterns: `*` is any text, `?` any one character. | ||
| 105 | -/// | ||
| 106 | -/// ```swift | ||
| 107 | -/// CommandPattern.matches("git status", pattern: "git *") // true | ||
| 108 | -/// ``` | ||
| 109 | -public enum CommandPattern { | ||
| 110 | - public static func matches(_ command: String, pattern: String) -> Bool { | ||
| 111 | - let text = Array(command) | ||
| 112 | - let glob = Array(pattern) | ||
| 113 | - var textIndex = 0 | ||
| 114 | - var globIndex = 0 | ||
| 115 | - var starGlob = -1 | ||
| 116 | - var starText = 0 | ||
| 117 | - while textIndex < text.count { | ||
| 118 | - let current = globIndex < glob.count ? glob[globIndex] : nil | ||
| 119 | - if current == "?" || current == text[textIndex] { | ||
| 120 | - textIndex += 1 | ||
| 121 | - globIndex += 1 | ||
| 122 | - } else if current == "*" { | ||
| 123 | - starGlob = globIndex | ||
| 124 | - starText = textIndex | ||
| 125 | - globIndex += 1 | ||
| 126 | - } else if starGlob >= 0 { | ||
| 127 | - globIndex = starGlob + 1 | ||
| 128 | - starText += 1 | ||
| 129 | - textIndex = starText | ||
| 130 | - } else { | ||
| 131 | - return false | ||
| 132 | - } | ||
| 133 | - } | ||
| 134 | - while globIndex < glob.count, glob[globIndex] == "*" { | ||
| 135 | - globIndex += 1 | ||
| 136 | - } | ||
| 137 | - return globIndex == glob.count | ||
| 138 | - } | ||
| 139 | - | ||
| 140 | - /// The first pattern of `patterns` that matches `command`. | ||
| 141 | - public static func firstMatch(_ command: String, in patterns: [String]) -> String? { | ||
| 142 | - patterns.first { matches(command, pattern: $0) } | ||
| 143 | - } | ||
| 144 | -} | ||
deleted
Sources/RazorbillCore/Tools/ProcessRunner.swift +0 -222 | deleted file mode 100644 | ||
| @@ -1,222 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -#if canImport(Darwin) | |
| 4 | -import Darwin | |
| 5 | -#else | |
| 6 | -import Glibc | |
| 7 | -#endif | |
| 8 | - | |
| 9 | -/// The outcome of a command run by ``ProcessRunner``. | |
| 10 | -public struct ProcessResult: Sendable, Equatable { | |
| 11 | - /// Exit status; 128 + signal number when the process was killed by a signal. | |
| 12 | - public var exitCode: Int32 | |
| 13 | - public var stdout: String | |
| 14 | - public var stderr: String | |
| 15 | - /// Bytes dropped because the output was longer than the limit. | |
| 16 | - public var droppedBytes: Int | |
| 17 | - /// The process ran past its time limit and was killed. | |
| 18 | - public var timedOut: Bool | |
| 19 | -} | |
| 20 | - | |
| 21 | -/// Runs a command in its own process group, so a timeout or a cancellation kills the command | |
| 22 | -/// **and** everything it started. Output beyond `maxOutputBytes` (stdout + stderr) is dropped. | |
| 23 | -/// | |
| 24 | -/// ```swift | |
| 25 | -/// let result = try await ProcessRunner.run( | |
| 26 | -/// ["/bin/bash", "-c", "echo hi"], directory: "/tmp", timeout: .seconds(5), maxOutputBytes: 1024) | |
| 27 | -/// ``` | |
| 28 | -public enum ProcessRunner { | |
| 29 | - public struct LaunchError: Error, Equatable, CustomStringConvertible { | |
| 30 | - public var description: String | |
| 31 | - } | |
| 32 | - | |
| 33 | - public static func run( | |
| 34 | - _ arguments: [String], directory: String, timeout: Duration, maxOutputBytes: Int | |
| 35 | - ) async throws -> ProcessResult { | |
| 36 | - let child = try spawn(arguments, directory: directory) | |
| 37 | - let budget = OutputBudget(limit: maxOutputBytes) | |
| 38 | - let timer = DispatchWorkItem { child.kill(timedOut: true) } | |
| 39 | - DispatchQueue.global().asyncAfter(deadline: .now() + timeout.seconds, execute: timer) | |
| 40 | - defer { timer.cancel() } | |
| 41 | - | |
| 42 | - return await withTaskCancellationHandler { | |
| 43 | - await withCheckedContinuation { continuation in | |
| 44 | - Thread { | |
| 45 | - let result = child.collect(budget: budget) | |
| 46 | - continuation.resume(returning: result) | |
| 47 | - }.start() | |
| 48 | - } | |
| 49 | - } onCancel: { | |
| 50 | - child.kill(timedOut: false) | |
| 51 | - } | |
| 52 | - } | |
| 53 | - | |
| 54 | - private static func spawn(_ arguments: [String], directory: String) throws -> Child { | |
| 55 | - var stdoutPipe: [Int32] = [0, 0] | |
| 56 | - var stderrPipe: [Int32] = [0, 0] | |
| 57 | - guard pipe(&stdoutPipe) == 0, pipe(&stderrPipe) == 0 else { | |
| 58 | - throw LaunchError(description: "cannot create pipes") | |
| 59 | - } | |
| 60 | - #if canImport(Darwin) | |
| 61 | - var actions: posix_spawn_file_actions_t? | |
| 62 | - var attributes: posix_spawnattr_t? | |
| 63 | - #else | |
| 64 | - var actions = posix_spawn_file_actions_t() | |
| 65 | - var attributes = posix_spawnattr_t() | |
| 66 | - #endif | |
| 67 | - posix_spawn_file_actions_init(&actions) | |
| 68 | - posix_spawnattr_init(&attributes) | |
| 69 | - defer { | |
| 70 | - posix_spawn_file_actions_destroy(&actions) | |
| 71 | - posix_spawnattr_destroy(&attributes) | |
| 72 | - } | |
| 73 | - posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0) | |
| 74 | - posix_spawn_file_actions_adddup2(&actions, stdoutPipe[1], 1) | |
| 75 | - posix_spawn_file_actions_adddup2(&actions, stderrPipe[1], 2) | |
| 76 | - for descriptor in stdoutPipe + stderrPipe { | |
| 77 | - posix_spawn_file_actions_addclose(&actions, descriptor) | |
| 78 | - } | |
| 79 | - posix_spawn_file_actions_addchdir_np(&actions, directory) | |
| 80 | - // A new process group whose id is the child's pid: kill(-pid) then reaches all its children. | |
| 81 | - posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_SETPGROUP)) | |
| 82 | - posix_spawnattr_setpgroup(&attributes, 0) | |
| 83 | - | |
| 84 | - let argv = arguments.map { strdup($0) } + [nil] | |
| 85 | - let environment = | |
| 86 | - ProcessInfo.processInfo.environment.map { strdup("\($0.key)=\($0.value)") } + [nil] | |
| 87 | - defer { | |
| 88 | - for pointer in argv + environment { | |
| 89 | - free(pointer) | |
| 90 | - } | |
| 91 | - } | |
| 92 | - var pid: pid_t = 0 | |
| 93 | - let status = posix_spawn(&pid, arguments[0], &actions, &attributes, argv, environment) | |
| 94 | - close(stdoutPipe[1]) | |
| 95 | - close(stderrPipe[1]) | |
| 96 | - guard status == 0 else { | |
| 97 | - close(stdoutPipe[0]) | |
| 98 | - close(stderrPipe[0]) | |
| 99 | - throw LaunchError( | |
| 100 | - description: "cannot start \(arguments[0]): \(String(cString: strerror(status)))") | |
| 101 | - } | |
| 102 | - return Child(pid: pid, stdout: stdoutPipe[0], stderr: stderrPipe[0]) | |
| 103 | - } | |
| 104 | - | |
| 105 | - /// A running child process and the read ends of its output pipes. | |
| 106 | - private final class Child: @unchecked Sendable { | |
| 107 | - let pid: pid_t | |
| 108 | - let stdout: Int32 | |
| 109 | - let stderr: Int32 | |
| 110 | - private let lock = NSLock() | |
| 111 | - private var finished = false | |
| 112 | - private var killedByTimeout = false | |
| 113 | - | |
| 114 | - init(pid: pid_t, stdout: Int32, stderr: Int32) { | |
| 115 | - self.pid = pid | |
| 116 | - self.stdout = stdout | |
| 117 | - self.stderr = stderr | |
| 118 | - } | |
| 119 | - | |
| 120 | - /// Kills the whole process group, unless the process already finished. | |
| 121 | - func kill(timedOut: Bool) { | |
| 122 | - lock.withLock { | |
| 123 | - guard !finished else { return } | |
| 124 | - killedByTimeout = killedByTimeout || timedOut | |
| 125 | - _ = sendSignal(SIGKILL, toGroup: pid) | |
| 126 | - } | |
| 127 | - } | |
| 128 | - | |
| 129 | - /// Reads both pipes to the end, waits for the process and builds the result. Blocking. | |
| 130 | - func collect(budget: OutputBudget) -> ProcessResult { | |
| 131 | - // Both pipes are read at the same time: reading one to the end first could block | |
| 132 | - // the child forever on a full second pipe. | |
| 133 | - let group = DispatchGroup() | |
| 134 | - let errors = BytesBox() | |
| 135 | - DispatchQueue.global().async(group: group) { | |
| 136 | - errors.bytes = Self.drain(self.stderr, budget: budget) | |
| 137 | - } | |
| 138 | - let output = Self.drain(stdout, budget: budget) | |
| 139 | - group.wait() | |
| 140 | - | |
| 141 | - var status: Int32 = 0 | |
| 142 | - while waitpid(pid, &status, 0) == -1, errno == EINTR {} | |
| 143 | - let timedOut = lock.withLock { | |
| 144 | - finished = true | |
| 145 | - return killedByTimeout | |
| 146 | - } | |
| 147 | - return ProcessResult( | |
| 148 | - exitCode: Self.exitCode(status), | |
| 149 | - stdout: Self.text(output), | |
| 150 | - stderr: Self.text(errors.bytes), | |
| 151 | - droppedBytes: budget.dropped, | |
| 152 | - timedOut: timedOut | |
| 153 | - ) | |
| 154 | - } | |
| 155 | - | |
| 156 | - private static func drain(_ descriptor: Int32, budget: OutputBudget) -> [UInt8] { | |
| 157 | - var kept: [UInt8] = [] | |
| 158 | - var buffer = [UInt8](repeating: 0, count: 65_536) | |
| 159 | - while true { | |
| 160 | - let count = read(descriptor, &buffer, buffer.count) | |
| 161 | - if count < 0, errno == EINTR { continue } | |
| 162 | - if count <= 0 { break } | |
| 163 | - kept.append(contentsOf: buffer[0 ..< budget.take(count)]) | |
| 164 | - } | |
| 165 | - close(descriptor) | |
| 166 | - return kept | |
| 167 | - } | |
| 168 | - | |
| 169 | - /// Output as text. Commands may print bytes that are not UTF-8 (binary files...): they are | |
| 170 | - /// replaced with U+FFFD so the readable part still reaches the model, instead of losing it all. | |
| 171 | - private static func text(_ bytes: [UInt8]) -> String { | |
| 172 | - // swiftlint:disable:next optional_data_string_conversion | |
| 173 | - String(decoding: bytes, as: UTF8.self) | |
| 174 | - } | |
| 175 | - | |
| 176 | - /// Decodes a `waitpid` status (the WIFEXITED / WEXITSTATUS macros are not visible in Swift). | |
| 177 | - private static func exitCode(_ status: Int32) -> Int32 { | |
| 178 | - let signal = status & 0x7f | |
| 179 | - return signal == 0 ? (status >> 8) & 0xff : 128 + signal | |
| 180 | - } | |
| 181 | - } | |
| 182 | - | |
| 183 | - /// Bytes written by one thread and read by another after `DispatchGroup.wait()`. | |
| 184 | - private final class BytesBox: @unchecked Sendable { | |
| 185 | - var bytes: [UInt8] = [] | |
| 186 | - } | |
| 187 | - | |
| 188 | - /// Shared byte budget for stdout and stderr together. | |
| 189 | - final class OutputBudget: @unchecked Sendable { | |
| 190 | - private let lock = NSLock() | |
| 191 | - private var remaining: Int | |
| 192 | - private(set) var dropped = 0 | |
| 193 | - | |
| 194 | - init(limit: Int) { | |
| 195 | - remaining = limit | |
| 196 | - } | |
| 197 | - | |
| 198 | - /// How many of `count` new bytes may be kept; the rest is counted as dropped. | |
| 199 | - func take(_ count: Int) -> Int { | |
| 200 | - lock.withLock { | |
| 201 | - let kept = min(count, remaining) | |
| 202 | - remaining -= kept | |
| 203 | - dropped += count - kept | |
| 204 | - return kept | |
| 205 | - } | |
| 206 | - } | |
| 207 | - } | |
| 208 | -} | |
| 209 | - | |
| 210 | -/// Sends `signal` to every process of the group `group` (`kill(-group, signal)`). | |
| 211 | -/// A free function so it does not clash with the `kill` methods above. | |
| 212 | -private func sendSignal(_ signal: Int32, toGroup group: pid_t) -> Int32 { | |
| 213 | - kill(-group, signal) | |
| 214 | -} | |
| 215 | - | |
| 216 | -extension Duration { | |
| 217 | - /// The duration in seconds, as a `Double`. | |
| 218 | - var seconds: Double { | |
| 219 | - let parts = components | |
| 220 | - return Double(parts.seconds) + Double(parts.attoseconds) / 1e18 | |
| 221 | - } | |
| 222 | -} | |
| deleted file mode 100644 | |||
| @@ -1,222 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -#if canImport(Darwin) | ||
| 4 | -import Darwin | ||
| 5 | -#else | ||
| 6 | -import Glibc | ||
| 7 | -#endif | ||
| 8 | - | ||
| 9 | -/// The outcome of a command run by ``ProcessRunner``. | ||
| 10 | -public struct ProcessResult: Sendable, Equatable { | ||
| 11 | - /// Exit status; 128 + signal number when the process was killed by a signal. | ||
| 12 | - public var exitCode: Int32 | ||
| 13 | - public var stdout: String | ||
| 14 | - public var stderr: String | ||
| 15 | - /// Bytes dropped because the output was longer than the limit. | ||
| 16 | - public var droppedBytes: Int | ||
| 17 | - /// The process ran past its time limit and was killed. | ||
| 18 | - public var timedOut: Bool | ||
| 19 | -} | ||
| 20 | - | ||
| 21 | -/// Runs a command in its own process group, so a timeout or a cancellation kills the command | ||
| 22 | -/// **and** everything it started. Output beyond `maxOutputBytes` (stdout + stderr) is dropped. | ||
| 23 | -/// | ||
| 24 | -/// ```swift | ||
| 25 | -/// let result = try await ProcessRunner.run( | ||
| 26 | -/// ["/bin/bash", "-c", "echo hi"], directory: "/tmp", timeout: .seconds(5), maxOutputBytes: 1024) | ||
| 27 | -/// ``` | ||
| 28 | -public enum ProcessRunner { | ||
| 29 | - public struct LaunchError: Error, Equatable, CustomStringConvertible { | ||
| 30 | - public var description: String | ||
| 31 | - } | ||
| 32 | - | ||
| 33 | - public static func run( | ||
| 34 | - _ arguments: [String], directory: String, timeout: Duration, maxOutputBytes: Int | ||
| 35 | - ) async throws -> ProcessResult { | ||
| 36 | - let child = try spawn(arguments, directory: directory) | ||
| 37 | - let budget = OutputBudget(limit: maxOutputBytes) | ||
| 38 | - let timer = DispatchWorkItem { child.kill(timedOut: true) } | ||
| 39 | - DispatchQueue.global().asyncAfter(deadline: .now() + timeout.seconds, execute: timer) | ||
| 40 | - defer { timer.cancel() } | ||
| 41 | - | ||
| 42 | - return await withTaskCancellationHandler { | ||
| 43 | - await withCheckedContinuation { continuation in | ||
| 44 | - Thread { | ||
| 45 | - let result = child.collect(budget: budget) | ||
| 46 | - continuation.resume(returning: result) | ||
| 47 | - }.start() | ||
| 48 | - } | ||
| 49 | - } onCancel: { | ||
| 50 | - child.kill(timedOut: false) | ||
| 51 | - } | ||
| 52 | - } | ||
| 53 | - | ||
| 54 | - private static func spawn(_ arguments: [String], directory: String) throws -> Child { | ||
| 55 | - var stdoutPipe: [Int32] = [0, 0] | ||
| 56 | - var stderrPipe: [Int32] = [0, 0] | ||
| 57 | - guard pipe(&stdoutPipe) == 0, pipe(&stderrPipe) == 0 else { | ||
| 58 | - throw LaunchError(description: "cannot create pipes") | ||
| 59 | - } | ||
| 60 | - #if canImport(Darwin) | ||
| 61 | - var actions: posix_spawn_file_actions_t? | ||
| 62 | - var attributes: posix_spawnattr_t? | ||
| 63 | - #else | ||
| 64 | - var actions = posix_spawn_file_actions_t() | ||
| 65 | - var attributes = posix_spawnattr_t() | ||
| 66 | - #endif | ||
| 67 | - posix_spawn_file_actions_init(&actions) | ||
| 68 | - posix_spawnattr_init(&attributes) | ||
| 69 | - defer { | ||
| 70 | - posix_spawn_file_actions_destroy(&actions) | ||
| 71 | - posix_spawnattr_destroy(&attributes) | ||
| 72 | - } | ||
| 73 | - posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0) | ||
| 74 | - posix_spawn_file_actions_adddup2(&actions, stdoutPipe[1], 1) | ||
| 75 | - posix_spawn_file_actions_adddup2(&actions, stderrPipe[1], 2) | ||
| 76 | - for descriptor in stdoutPipe + stderrPipe { | ||
| 77 | - posix_spawn_file_actions_addclose(&actions, descriptor) | ||
| 78 | - } | ||
| 79 | - posix_spawn_file_actions_addchdir_np(&actions, directory) | ||
| 80 | - // A new process group whose id is the child's pid: kill(-pid) then reaches all its children. | ||
| 81 | - posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_SETPGROUP)) | ||
| 82 | - posix_spawnattr_setpgroup(&attributes, 0) | ||
| 83 | - | ||
| 84 | - let argv = arguments.map { strdup($0) } + [nil] | ||
| 85 | - let environment = | ||
| 86 | - ProcessInfo.processInfo.environment.map { strdup("\($0.key)=\($0.value)") } + [nil] | ||
| 87 | - defer { | ||
| 88 | - for pointer in argv + environment { | ||
| 89 | - free(pointer) | ||
| 90 | - } | ||
| 91 | - } | ||
| 92 | - var pid: pid_t = 0 | ||
| 93 | - let status = posix_spawn(&pid, arguments[0], &actions, &attributes, argv, environment) | ||
| 94 | - close(stdoutPipe[1]) | ||
| 95 | - close(stderrPipe[1]) | ||
| 96 | - guard status == 0 else { | ||
| 97 | - close(stdoutPipe[0]) | ||
| 98 | - close(stderrPipe[0]) | ||
| 99 | - throw LaunchError( | ||
| 100 | - description: "cannot start \(arguments[0]): \(String(cString: strerror(status)))") | ||
| 101 | - } | ||
| 102 | - return Child(pid: pid, stdout: stdoutPipe[0], stderr: stderrPipe[0]) | ||
| 103 | - } | ||
| 104 | - | ||
| 105 | - /// A running child process and the read ends of its output pipes. | ||
| 106 | - private final class Child: @unchecked Sendable { | ||
| 107 | - let pid: pid_t | ||
| 108 | - let stdout: Int32 | ||
| 109 | - let stderr: Int32 | ||
| 110 | - private let lock = NSLock() | ||
| 111 | - private var finished = false | ||
| 112 | - private var killedByTimeout = false | ||
| 113 | - | ||
| 114 | - init(pid: pid_t, stdout: Int32, stderr: Int32) { | ||
| 115 | - self.pid = pid | ||
| 116 | - self.stdout = stdout | ||
| 117 | - self.stderr = stderr | ||
| 118 | - } | ||
| 119 | - | ||
| 120 | - /// Kills the whole process group, unless the process already finished. | ||
| 121 | - func kill(timedOut: Bool) { | ||
| 122 | - lock.withLock { | ||
| 123 | - guard !finished else { return } | ||
| 124 | - killedByTimeout = killedByTimeout || timedOut | ||
| 125 | - _ = sendSignal(SIGKILL, toGroup: pid) | ||
| 126 | - } | ||
| 127 | - } | ||
| 128 | - | ||
| 129 | - /// Reads both pipes to the end, waits for the process and builds the result. Blocking. | ||
| 130 | - func collect(budget: OutputBudget) -> ProcessResult { | ||
| 131 | - // Both pipes are read at the same time: reading one to the end first could block | ||
| 132 | - // the child forever on a full second pipe. | ||
| 133 | - let group = DispatchGroup() | ||
| 134 | - let errors = BytesBox() | ||
| 135 | - DispatchQueue.global().async(group: group) { | ||
| 136 | - errors.bytes = Self.drain(self.stderr, budget: budget) | ||
| 137 | - } | ||
| 138 | - let output = Self.drain(stdout, budget: budget) | ||
| 139 | - group.wait() | ||
| 140 | - | ||
| 141 | - var status: Int32 = 0 | ||
| 142 | - while waitpid(pid, &status, 0) == -1, errno == EINTR {} | ||
| 143 | - let timedOut = lock.withLock { | ||
| 144 | - finished = true | ||
| 145 | - return killedByTimeout | ||
| 146 | - } | ||
| 147 | - return ProcessResult( | ||
| 148 | - exitCode: Self.exitCode(status), | ||
| 149 | - stdout: Self.text(output), | ||
| 150 | - stderr: Self.text(errors.bytes), | ||
| 151 | - droppedBytes: budget.dropped, | ||
| 152 | - timedOut: timedOut | ||
| 153 | - ) | ||
| 154 | - } | ||
| 155 | - | ||
| 156 | - private static func drain(_ descriptor: Int32, budget: OutputBudget) -> [UInt8] { | ||
| 157 | - var kept: [UInt8] = [] | ||
| 158 | - var buffer = [UInt8](repeating: 0, count: 65_536) | ||
| 159 | - while true { | ||
| 160 | - let count = read(descriptor, &buffer, buffer.count) | ||
| 161 | - if count < 0, errno == EINTR { continue } | ||
| 162 | - if count <= 0 { break } | ||
| 163 | - kept.append(contentsOf: buffer[0 ..< budget.take(count)]) | ||
| 164 | - } | ||
| 165 | - close(descriptor) | ||
| 166 | - return kept | ||
| 167 | - } | ||
| 168 | - | ||
| 169 | - /// Output as text. Commands may print bytes that are not UTF-8 (binary files...): they are | ||
| 170 | - /// replaced with U+FFFD so the readable part still reaches the model, instead of losing it all. | ||
| 171 | - private static func text(_ bytes: [UInt8]) -> String { | ||
| 172 | - // swiftlint:disable:next optional_data_string_conversion | ||
| 173 | - String(decoding: bytes, as: UTF8.self) | ||
| 174 | - } | ||
| 175 | - | ||
| 176 | - /// Decodes a `waitpid` status (the WIFEXITED / WEXITSTATUS macros are not visible in Swift). | ||
| 177 | - private static func exitCode(_ status: Int32) -> Int32 { | ||
| 178 | - let signal = status & 0x7f | ||
| 179 | - return signal == 0 ? (status >> 8) & 0xff : 128 + signal | ||
| 180 | - } | ||
| 181 | - } | ||
| 182 | - | ||
| 183 | - /// Bytes written by one thread and read by another after `DispatchGroup.wait()`. | ||
| 184 | - private final class BytesBox: @unchecked Sendable { | ||
| 185 | - var bytes: [UInt8] = [] | ||
| 186 | - } | ||
| 187 | - | ||
| 188 | - /// Shared byte budget for stdout and stderr together. | ||
| 189 | - final class OutputBudget: @unchecked Sendable { | ||
| 190 | - private let lock = NSLock() | ||
| 191 | - private var remaining: Int | ||
| 192 | - private(set) var dropped = 0 | ||
| 193 | - | ||
| 194 | - init(limit: Int) { | ||
| 195 | - remaining = limit | ||
| 196 | - } | ||
| 197 | - | ||
| 198 | - /// How many of `count` new bytes may be kept; the rest is counted as dropped. | ||
| 199 | - func take(_ count: Int) -> Int { | ||
| 200 | - lock.withLock { | ||
| 201 | - let kept = min(count, remaining) | ||
| 202 | - remaining -= kept | ||
| 203 | - dropped += count - kept | ||
| 204 | - return kept | ||
| 205 | - } | ||
| 206 | - } | ||
| 207 | - } | ||
| 208 | -} | ||
| 209 | - | ||
| 210 | -/// Sends `signal` to every process of the group `group` (`kill(-group, signal)`). | ||
| 211 | -/// A free function so it does not clash with the `kill` methods above. | ||
| 212 | -private func sendSignal(_ signal: Int32, toGroup group: pid_t) -> Int32 { | ||
| 213 | - kill(-group, signal) | ||
| 214 | -} | ||
| 215 | - | ||
| 216 | -extension Duration { | ||
| 217 | - /// The duration in seconds, as a `Double`. | ||
| 218 | - var seconds: Double { | ||
| 219 | - let parts = components | ||
| 220 | - return Double(parts.seconds) + Double(parts.attoseconds) / 1e18 | ||
| 221 | - } | ||
| 222 | -} | ||
deleted
Sources/RazorbillCore/Tools/ToolRegistry.swift +0 -86 | deleted file mode 100644 | ||
| @@ -1,86 +0,0 @@ | ||
| 1 | -/// Where tools are created: lets a tool resolve relative paths. | |
| 2 | -public struct ToolEnvironment: Sendable { | |
| 3 | - /// Directory that relative paths in tool options start from. | |
| 4 | - public var baseDirectory: String | |
| 5 | - | |
| 6 | - public init(baseDirectory: String) { | |
| 7 | - self.baseDirectory = baseDirectory | |
| 8 | - } | |
| 9 | -} | |
| 10 | - | |
| 11 | -/// A tool option has a wrong value. Reported as a configuration error at `tools.<tool>.<key>`. | |
| 12 | -public struct ToolOptionError: Error, Equatable, CustomStringConvertible { | |
| 13 | - public var key: String | |
| 14 | - public var message: String | |
| 15 | - | |
| 16 | - public init(key: String, message: String) { | |
| 17 | - self.key = key | |
| 18 | - self.message = message | |
| 19 | - } | |
| 20 | - | |
| 21 | - public var description: String { "\(key): \(message)" } | |
| 22 | -} | |
| 23 | - | |
| 24 | -/// The catalogue of tools `rzb` knows, by name. The agent's YAML file enables some of them. | |
| 25 | -/// | |
| 26 | -/// Adding a built-in tool is one type plus one registration line: | |
| 27 | -/// | |
| 28 | -/// ```swift | |
| 29 | -/// var registry = ToolRegistry.builtIn | |
| 30 | -/// registry.register("clock") { options, environment in Clock() } | |
| 31 | -/// let tools = try registry.makeTools(for: config, environment: ToolEnvironment(baseDirectory: ".")) | |
| 32 | -/// ``` | |
| 33 | -public struct ToolRegistry: Sendable { | |
| 34 | - /// Builds a tool from its options in the YAML file (a mapping, possibly empty). | |
| 35 | - public typealias Factory = | |
| 36 | - @Sendable (_ options: ConfigValue, _ environment: ToolEnvironment) throws -> any AgentTool | |
| 37 | - | |
| 38 | - private var factories: [String: Factory] = [:] | |
| 39 | - | |
| 40 | - public init() {} | |
| 41 | - | |
| 42 | - /// The tools shipped with razorbill. | |
| 43 | - public static var builtIn: ToolRegistry { | |
| 44 | - var registry = ToolRegistry() | |
| 45 | - registry.register(BashTool.name, factory: BashTool.init(options:environment:)) | |
| 46 | - return registry | |
| 47 | - } | |
| 48 | - | |
| 49 | - /// Adds or replaces the tool called `name`. | |
| 50 | - public mutating func register(_ name: String, factory: @escaping Factory) { | |
| 51 | - factories[name] = factory | |
| 52 | - } | |
| 53 | - | |
| 54 | - /// Names of the registered tools, sorted. | |
| 55 | - public var names: [String] { factories.keys.sorted() } | |
| 56 | - | |
| 57 | - /// Builds the tools enabled in `config`. Unknown tool names and invalid options are reported | |
| 58 | - /// together as a ``ConfigError``. | |
| 59 | - public func makeTools( | |
| 60 | - for config: AgentConfig, environment: ToolEnvironment | |
| 61 | - ) throws -> [any AgentTool] { | |
| 62 | - var tools: [any AgentTool] = [] | |
| 63 | - var issues: [ConfigIssue] = [] | |
| 64 | - for (name, options) in config.tools.sorted(by: { $0.key < $1.key }) { | |
| 65 | - guard let factory = factories[name] else { | |
| 66 | - let known = names.joined(separator: ", ") | |
| 67 | - issues.append( | |
| 68 | - ConfigIssue( | |
| 69 | - keyPath: "tools.\(name)", line: nil, | |
| 70 | - message: "unknown tool (available: \(known))")) | |
| 71 | - continue | |
| 72 | - } | |
| 73 | - do { | |
| 74 | - tools.append(try factory(options, environment)) | |
| 75 | - } catch let error as ToolOptionError { | |
| 76 | - issues.append( | |
| 77 | - ConfigIssue( | |
| 78 | - keyPath: "tools.\(name).\(error.key)", line: nil, message: error.message)) | |
| 79 | - } | |
| 80 | - } | |
| 81 | - guard issues.isEmpty else { | |
| 82 | - throw ConfigError(file: nil, issues: issues) | |
| 83 | - } | |
| 84 | - return tools | |
| 85 | - } | |
| 86 | -} | |
| deleted file mode 100644 | |||
| @@ -1,86 +0,0 @@ | |||
| 1 | -/// Where tools are created: lets a tool resolve relative paths. | ||
| 2 | -public struct ToolEnvironment: Sendable { | ||
| 3 | - /// Directory that relative paths in tool options start from. | ||
| 4 | - public var baseDirectory: String | ||
| 5 | - | ||
| 6 | - public init(baseDirectory: String) { | ||
| 7 | - self.baseDirectory = baseDirectory | ||
| 8 | - } | ||
| 9 | -} | ||
| 10 | - | ||
| 11 | -/// A tool option has a wrong value. Reported as a configuration error at `tools.<tool>.<key>`. | ||
| 12 | -public struct ToolOptionError: Error, Equatable, CustomStringConvertible { | ||
| 13 | - public var key: String | ||
| 14 | - public var message: String | ||
| 15 | - | ||
| 16 | - public init(key: String, message: String) { | ||
| 17 | - self.key = key | ||
| 18 | - self.message = message | ||
| 19 | - } | ||
| 20 | - | ||
| 21 | - public var description: String { "\(key): \(message)" } | ||
| 22 | -} | ||
| 23 | - | ||
| 24 | -/// The catalogue of tools `rzb` knows, by name. The agent's YAML file enables some of them. | ||
| 25 | -/// | ||
| 26 | -/// Adding a built-in tool is one type plus one registration line: | ||
| 27 | -/// | ||
| 28 | -/// ```swift | ||
| 29 | -/// var registry = ToolRegistry.builtIn | ||
| 30 | -/// registry.register("clock") { options, environment in Clock() } | ||
| 31 | -/// let tools = try registry.makeTools(for: config, environment: ToolEnvironment(baseDirectory: ".")) | ||
| 32 | -/// ``` | ||
| 33 | -public struct ToolRegistry: Sendable { | ||
| 34 | - /// Builds a tool from its options in the YAML file (a mapping, possibly empty). | ||
| 35 | - public typealias Factory = | ||
| 36 | - @Sendable (_ options: ConfigValue, _ environment: ToolEnvironment) throws -> any AgentTool | ||
| 37 | - | ||
| 38 | - private var factories: [String: Factory] = [:] | ||
| 39 | - | ||
| 40 | - public init() {} | ||
| 41 | - | ||
| 42 | - /// The tools shipped with razorbill. | ||
| 43 | - public static var builtIn: ToolRegistry { | ||
| 44 | - var registry = ToolRegistry() | ||
| 45 | - registry.register(BashTool.name, factory: BashTool.init(options:environment:)) | ||
| 46 | - return registry | ||
| 47 | - } | ||
| 48 | - | ||
| 49 | - /// Adds or replaces the tool called `name`. | ||
| 50 | - public mutating func register(_ name: String, factory: @escaping Factory) { | ||
| 51 | - factories[name] = factory | ||
| 52 | - } | ||
| 53 | - | ||
| 54 | - /// Names of the registered tools, sorted. | ||
| 55 | - public var names: [String] { factories.keys.sorted() } | ||
| 56 | - | ||
| 57 | - /// Builds the tools enabled in `config`. Unknown tool names and invalid options are reported | ||
| 58 | - /// together as a ``ConfigError``. | ||
| 59 | - public func makeTools( | ||
| 60 | - for config: AgentConfig, environment: ToolEnvironment | ||
| 61 | - ) throws -> [any AgentTool] { | ||
| 62 | - var tools: [any AgentTool] = [] | ||
| 63 | - var issues: [ConfigIssue] = [] | ||
| 64 | - for (name, options) in config.tools.sorted(by: { $0.key < $1.key }) { | ||
| 65 | - guard let factory = factories[name] else { | ||
| 66 | - let known = names.joined(separator: ", ") | ||
| 67 | - issues.append( | ||
| 68 | - ConfigIssue( | ||
| 69 | - keyPath: "tools.\(name)", line: nil, | ||
| 70 | - message: "unknown tool (available: \(known))")) | ||
| 71 | - continue | ||
| 72 | - } | ||
| 73 | - do { | ||
| 74 | - tools.append(try factory(options, environment)) | ||
| 75 | - } catch let error as ToolOptionError { | ||
| 76 | - issues.append( | ||
| 77 | - ConfigIssue( | ||
| 78 | - keyPath: "tools.\(name).\(error.key)", line: nil, message: error.message)) | ||
| 79 | - } | ||
| 80 | - } | ||
| 81 | - guard issues.isEmpty else { | ||
| 82 | - throw ConfigError(file: nil, issues: issues) | ||
| 83 | - } | ||
| 84 | - return tools | ||
| 85 | - } | ||
| 86 | -} | ||
modified
Sources/RazorbillMLX/MLXEngine.swift +2 -1 | @@ -133,7 +133,8 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 133 | 133 | } |
| 134 | 134 | |
| 135 | 135 | /// One conversation: keeps mlx-swift-lm's `ChatSession` (history and KV cache). |
| 136 | -/// The agent never sends twice at the same time, which is what makes it safe to share. | |
| 136 | +/// Callers must not send twice at the same time on one session, which is what makes it safe to | |
| 137 | +/// share (the server will queue requests per model, ticket #34). | |
| 137 | 138 | private final class MLXSession: EngineSession, @unchecked Sendable { |
| 138 | 139 | private let session: ChatSession |
| 139 | 140 | private let startsInsideThinking: Bool |
| @@ -133,7 +133,8 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 133 | } | 133 | } |
| 134 | 134 | ||
| 135 | /// One conversation: keeps mlx-swift-lm's `ChatSession` (history and KV cache). | 135 | /// One conversation: keeps mlx-swift-lm's `ChatSession` (history and KV cache). |
| 136 | -/// The agent never sends twice at the same time, which is what makes it safe to share. | 136 | +/// Callers must not send twice at the same time on one session, which is what makes it safe to |
| 137 | +/// share (the server will queue requests per model, ticket #34). | ||
| 137 | private final class MLXSession: EngineSession, @unchecked Sendable { | 138 | private final class MLXSession: EngineSession, @unchecked Sendable { |
| 138 | private let session: ChatSession | 139 | private let session: ChatSession |
| 139 | private let startsInsideThinking: Bool | 140 | private let startsInsideThinking: Bool |
deleted
Sources/RazorbillTUI/ChatState.swift +0 -246 | deleted file mode 100644 | ||
| @@ -1,246 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | - | |
| 4 | -/// One block of the conversation shown by the TUI. | |
| 5 | -public struct ChatBlock: Sendable, Equatable { | |
| 6 | - public enum Kind: Sendable, Equatable { | |
| 7 | - case user, assistant, thinking, toolCall, toolResult, stats, notice, error | |
| 8 | - } | |
| 9 | - | |
| 10 | - public var kind: Kind | |
| 11 | - public var text: String | |
| 12 | -} | |
| 13 | - | |
| 14 | -/// What the full-screen chat shows and how it reacts to keys and agent events. No terminal I/O: | |
| 15 | -/// ``ScreenRenderer`` draws it and ``TUIApp`` feeds it. | |
| 16 | -public struct ChatState: Sendable { | |
| 17 | - /// What the app must do after a key. | |
| 18 | - public enum Action: Sendable, Equatable { | |
| 19 | - case none | |
| 20 | - case send(String) | |
| 21 | - case stop | |
| 22 | - case reset | |
| 23 | - case quit | |
| 24 | - case answerConfirmation(Bool) | |
| 25 | - } | |
| 26 | - | |
| 27 | - public var agentName: String | |
| 28 | - public var modelName: String | |
| 29 | - public var engineName: String | |
| 30 | - public private(set) var blocks: [ChatBlock] = [] | |
| 31 | - public private(set) var input: [Character] = [] | |
| 32 | - public private(set) var cursor = 0 | |
| 33 | - /// Lines scrolled up from the bottom; 0 follows the conversation. | |
| 34 | - public private(set) var scrollOffset = 0 | |
| 35 | - public var showThinking: Bool | |
| 36 | - public var showStats: Bool | |
| 37 | - public private(set) var isBusy = false | |
| 38 | - public private(set) var lastSpeed: Double? | |
| 39 | - /// The question a tool is waiting on, if any. | |
| 40 | - public private(set) var pendingConfirmation: String? | |
| 41 | - | |
| 42 | - public init( | |
| 43 | - agentName: String, modelName: String, engineName: String, showThinking: Bool, | |
| 44 | - showStats: Bool | |
| 45 | - ) { | |
| 46 | - self.agentName = agentName | |
| 47 | - self.modelName = modelName | |
| 48 | - self.engineName = engineName | |
| 49 | - self.showThinking = showThinking | |
| 50 | - self.showStats = showStats | |
| 51 | - } | |
| 52 | - | |
| 53 | - public var inputText: String { String(input) } | |
| 54 | - | |
| 55 | - // MARK: Keys | |
| 56 | - | |
| 57 | - /// Applies `key` and tells the app what to do next. `pageSize` is the PgUp/PgDn step. | |
| 58 | - public mutating func handle(_ key: Key, pageSize: Int = 10) -> Action { | |
| 59 | - if pendingConfirmation != nil { | |
| 60 | - return handleConfirmation(key) | |
| 61 | - } | |
| 62 | - if edit(key) || scroll(key, pageSize: pageSize) { | |
| 63 | - return .none | |
| 64 | - } | |
| 65 | - return command(key) | |
| 66 | - } | |
| 67 | - | |
| 68 | - /// Keys that change the input line; `true` when `key` was one of them. | |
| 69 | - private mutating func edit(_ key: Key) -> Bool { | |
| 70 | - moveCursor(key) || changeText(key) | |
| 71 | - } | |
| 72 | - | |
| 73 | - private mutating func moveCursor(_ key: Key) -> Bool { | |
| 74 | - switch key { | |
| 75 | - case .arrowLeft: cursor = max(0, cursor - 1) | |
| 76 | - case .arrowRight: cursor = min(input.count, cursor + 1) | |
| 77 | - case .home, .control("a"): cursor = 0 | |
| 78 | - case .end, .control("e"): cursor = input.count | |
| 79 | - default: return false | |
| 80 | - } | |
| 81 | - return true | |
| 82 | - } | |
| 83 | - | |
| 84 | - private mutating func changeText(_ key: Key) -> Bool { | |
| 85 | - switch key { | |
| 86 | - case .character(let character): insert(character) | |
| 87 | - case .tab: insert(" ") | |
| 88 | - case .backspace where cursor > 0: | |
| 89 | - cursor -= 1 | |
| 90 | - input.remove(at: cursor) | |
| 91 | - case .delete where cursor < input.count: input.remove(at: cursor) | |
| 92 | - case .backspace, .delete: break // nothing to delete | |
| 93 | - case .control("u"): clearInput() | |
| 94 | - default: return false | |
| 95 | - } | |
| 96 | - return true | |
| 97 | - } | |
| 98 | - | |
| 99 | - /// Keys that scroll the conversation; `true` when `key` was one of them. | |
| 100 | - private mutating func scroll(_ key: Key, pageSize: Int) -> Bool { | |
| 101 | - switch key { | |
| 102 | - case .arrowUp: scrollOffset += 1 | |
| 103 | - case .pageUp: scrollOffset += pageSize | |
| 104 | - case .arrowDown: scrollOffset = max(0, scrollOffset - 1) | |
| 105 | - case .pageDown: scrollOffset = max(0, scrollOffset - pageSize) | |
| 106 | - default: return false | |
| 107 | - } | |
| 108 | - return true | |
| 109 | - } | |
| 110 | - | |
| 111 | - /// Keys that act on the conversation or the app. | |
| 112 | - private mutating func command(_ key: Key) -> Action { | |
| 113 | - switch key { | |
| 114 | - case .control("t"): | |
| 115 | - showThinking.toggle() | |
| 116 | - return .none | |
| 117 | - case .control("n"): return isBusy ? .none : .reset | |
| 118 | - case .control("c"): return isBusy ? .stop : .quit | |
| 119 | - case .control("d"): return input.isEmpty ? .quit : .none | |
| 120 | - case .enter: return submit() | |
| 121 | - default: return .none | |
| 122 | - } | |
| 123 | - } | |
| 124 | - | |
| 125 | - private mutating func handleConfirmation(_ key: Key) -> Action { | |
| 126 | - switch key { | |
| 127 | - case .character("y"), .character("Y"): | |
| 128 | - return .answerConfirmation(true) | |
| 129 | - case .character("n"), .character("N"), .enter, .escape, .control("c"): | |
| 130 | - return .answerConfirmation(false) | |
| 131 | - default: | |
| 132 | - return .none | |
| 133 | - } | |
| 134 | - } | |
| 135 | - | |
| 136 | - private mutating func submit() -> Action { | |
| 137 | - let text = inputText.trimmingCharacters(in: .whitespaces) | |
| 138 | - guard !text.isEmpty else { return .none } | |
| 139 | - switch text { | |
| 140 | - case "/exit", "/quit": | |
| 141 | - clearInput() | |
| 142 | - return .quit | |
| 143 | - case "/reset", "/new": | |
| 144 | - clearInput() | |
| 145 | - return isBusy ? .none : .reset | |
| 146 | - default: | |
| 147 | - // While an answer runs, the text stays in the input line for later. | |
| 148 | - guard !isBusy else { return .none } | |
| 149 | - clearInput() | |
| 150 | - return .send(text) | |
| 151 | - } | |
| 152 | - } | |
| 153 | - | |
| 154 | - private mutating func insert(_ character: Character) { | |
| 155 | - input.insert(character, at: cursor) | |
| 156 | - cursor += 1 | |
| 157 | - } | |
| 158 | - | |
| 159 | - private mutating func clearInput() { | |
| 160 | - input.removeAll() | |
| 161 | - cursor = 0 | |
| 162 | - } | |
| 163 | - | |
| 164 | - // MARK: Conversation | |
| 165 | - | |
| 166 | - /// A prompt was sent: show it and wait for the answer. | |
| 167 | - public mutating func begin(_ prompt: String) { | |
| 168 | - blocks.append(ChatBlock(kind: .user, text: prompt)) | |
| 169 | - isBusy = true | |
| 170 | - scrollOffset = 0 | |
| 171 | - } | |
| 172 | - | |
| 173 | - public mutating func apply(_ event: AgentEvent) { | |
| 174 | - switch event { | |
| 175 | - case .text(let text): | |
| 176 | - append(text, as: .assistant) | |
| 177 | - case .thinking(let text): | |
| 178 | - append(text, as: .thinking) | |
| 179 | - case .toolCall(let call): | |
| 180 | - let arguments = call.arguments.sorted { $0.key < $1.key } | |
| 181 | - .map { "\($0.key)=\($0.value.stringValue ?? "\($0.value)")" }.joined(separator: " ") | |
| 182 | - blocks.append(ChatBlock(kind: .toolCall, text: "→ \(call.name) \(arguments)")) | |
| 183 | - case .toolResult(let name, let output): | |
| 184 | - let lines = output.content.split(separator: "\n", omittingEmptySubsequences: false) | |
| 185 | - let shown = lines.prefix(6).joined(separator: "\n") + (lines.count > 6 ? "\n…" : "") | |
| 186 | - blocks.append(ChatBlock(kind: .toolResult, text: "← \(name): \(shown)")) | |
| 187 | - case .stats(let stats): | |
| 188 | - lastSpeed = stats.tokensPerSecond | |
| 189 | - guard showStats else { return } | |
| 190 | - let speed = (stats.tokensPerSecond * 10).rounded() / 10 | |
| 191 | - let counts = "\(stats.promptTokens) prompt tokens, \(stats.generatedTokens) generated" | |
| 192 | - blocks.append(ChatBlock(kind: .stats, text: "[\(counts), \(speed) tokens/s]")) | |
| 193 | - } | |
| 194 | - } | |
| 195 | - | |
| 196 | - /// The answer is complete (or failed, or was stopped). | |
| 197 | - public mutating func end(error: String? = nil, stopped: Bool = false) { | |
| 198 | - isBusy = false | |
| 199 | - if stopped { | |
| 200 | - notice("(stopped)") | |
| 201 | - } else if let error { | |
| 202 | - blocks.append(ChatBlock(kind: .error, text: "error: \(error)")) | |
| 203 | - } | |
| 204 | - } | |
| 205 | - | |
| 206 | - public mutating func notice(_ text: String) { | |
| 207 | - blocks.append(ChatBlock(kind: .notice, text: text)) | |
| 208 | - } | |
| 209 | - | |
| 210 | - /// Clears the conversation shown (after a reset of the agent). | |
| 211 | - public mutating func clear() { | |
| 212 | - blocks.removeAll() | |
| 213 | - scrollOffset = 0 | |
| 214 | - lastSpeed = nil | |
| 215 | - notice("(new conversation)") | |
| 216 | - } | |
| 217 | - | |
| 218 | - /// A tool waits for the user's answer to `question`. | |
| 219 | - public mutating func ask(_ question: String) { | |
| 220 | - pendingConfirmation = question | |
| 221 | - notice(question) | |
| 222 | - } | |
| 223 | - | |
| 224 | - public mutating func answered(_ accepted: Bool) { | |
| 225 | - pendingConfirmation = nil | |
| 226 | - notice(accepted ? "(allowed)" : "(refused)") | |
| 227 | - } | |
| 228 | - | |
| 229 | - /// Keeps the scroll offset within the content once the renderer knows its height. | |
| 230 | - public mutating func clampScroll(maximum: Int) { | |
| 231 | - scrollOffset = min(scrollOffset, max(0, maximum)) | |
| 232 | - } | |
| 233 | - | |
| 234 | - /// Streamed pieces of the same kind go into the same block. | |
| 235 | - private mutating func append(_ text: String, as kind: ChatBlock.Kind) { | |
| 236 | - if let last = blocks.indices.last, blocks[last].kind == kind { | |
| 237 | - blocks[last].text += text | |
| 238 | - return | |
| 239 | - } | |
| 240 | - // A block does not start with the blank lines models often emit first, and an empty | |
| 241 | - // thinking block (a model told not to think) is not shown at all. | |
| 242 | - let trimmed = String(text.drop { $0.isNewline }) | |
| 243 | - guard !trimmed.allSatisfy(\.isWhitespace) else { return } | |
| 244 | - blocks.append(ChatBlock(kind: kind, text: trimmed)) | |
| 245 | - } | |
| 246 | -} | |
| deleted file mode 100644 | |||
| @@ -1,246 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | - | ||
| 4 | -/// One block of the conversation shown by the TUI. | ||
| 5 | -public struct ChatBlock: Sendable, Equatable { | ||
| 6 | - public enum Kind: Sendable, Equatable { | ||
| 7 | - case user, assistant, thinking, toolCall, toolResult, stats, notice, error | ||
| 8 | - } | ||
| 9 | - | ||
| 10 | - public var kind: Kind | ||
| 11 | - public var text: String | ||
| 12 | -} | ||
| 13 | - | ||
| 14 | -/// What the full-screen chat shows and how it reacts to keys and agent events. No terminal I/O: | ||
| 15 | -/// ``ScreenRenderer`` draws it and ``TUIApp`` feeds it. | ||
| 16 | -public struct ChatState: Sendable { | ||
| 17 | - /// What the app must do after a key. | ||
| 18 | - public enum Action: Sendable, Equatable { | ||
| 19 | - case none | ||
| 20 | - case send(String) | ||
| 21 | - case stop | ||
| 22 | - case reset | ||
| 23 | - case quit | ||
| 24 | - case answerConfirmation(Bool) | ||
| 25 | - } | ||
| 26 | - | ||
| 27 | - public var agentName: String | ||
| 28 | - public var modelName: String | ||
| 29 | - public var engineName: String | ||
| 30 | - public private(set) var blocks: [ChatBlock] = [] | ||
| 31 | - public private(set) var input: [Character] = [] | ||
| 32 | - public private(set) var cursor = 0 | ||
| 33 | - /// Lines scrolled up from the bottom; 0 follows the conversation. | ||
| 34 | - public private(set) var scrollOffset = 0 | ||
| 35 | - public var showThinking: Bool | ||
| 36 | - public var showStats: Bool | ||
| 37 | - public private(set) var isBusy = false | ||
| 38 | - public private(set) var lastSpeed: Double? | ||
| 39 | - /// The question a tool is waiting on, if any. | ||
| 40 | - public private(set) var pendingConfirmation: String? | ||
| 41 | - | ||
| 42 | - public init( | ||
| 43 | - agentName: String, modelName: String, engineName: String, showThinking: Bool, | ||
| 44 | - showStats: Bool | ||
| 45 | - ) { | ||
| 46 | - self.agentName = agentName | ||
| 47 | - self.modelName = modelName | ||
| 48 | - self.engineName = engineName | ||
| 49 | - self.showThinking = showThinking | ||
| 50 | - self.showStats = showStats | ||
| 51 | - } | ||
| 52 | - | ||
| 53 | - public var inputText: String { String(input) } | ||
| 54 | - | ||
| 55 | - // MARK: Keys | ||
| 56 | - | ||
| 57 | - /// Applies `key` and tells the app what to do next. `pageSize` is the PgUp/PgDn step. | ||
| 58 | - public mutating func handle(_ key: Key, pageSize: Int = 10) -> Action { | ||
| 59 | - if pendingConfirmation != nil { | ||
| 60 | - return handleConfirmation(key) | ||
| 61 | - } | ||
| 62 | - if edit(key) || scroll(key, pageSize: pageSize) { | ||
| 63 | - return .none | ||
| 64 | - } | ||
| 65 | - return command(key) | ||
| 66 | - } | ||
| 67 | - | ||
| 68 | - /// Keys that change the input line; `true` when `key` was one of them. | ||
| 69 | - private mutating func edit(_ key: Key) -> Bool { | ||
| 70 | - moveCursor(key) || changeText(key) | ||
| 71 | - } | ||
| 72 | - | ||
| 73 | - private mutating func moveCursor(_ key: Key) -> Bool { | ||
| 74 | - switch key { | ||
| 75 | - case .arrowLeft: cursor = max(0, cursor - 1) | ||
| 76 | - case .arrowRight: cursor = min(input.count, cursor + 1) | ||
| 77 | - case .home, .control("a"): cursor = 0 | ||
| 78 | - case .end, .control("e"): cursor = input.count | ||
| 79 | - default: return false | ||
| 80 | - } | ||
| 81 | - return true | ||
| 82 | - } | ||
| 83 | - | ||
| 84 | - private mutating func changeText(_ key: Key) -> Bool { | ||
| 85 | - switch key { | ||
| 86 | - case .character(let character): insert(character) | ||
| 87 | - case .tab: insert(" ") | ||
| 88 | - case .backspace where cursor > 0: | ||
| 89 | - cursor -= 1 | ||
| 90 | - input.remove(at: cursor) | ||
| 91 | - case .delete where cursor < input.count: input.remove(at: cursor) | ||
| 92 | - case .backspace, .delete: break // nothing to delete | ||
| 93 | - case .control("u"): clearInput() | ||
| 94 | - default: return false | ||
| 95 | - } | ||
| 96 | - return true | ||
| 97 | - } | ||
| 98 | - | ||
| 99 | - /// Keys that scroll the conversation; `true` when `key` was one of them. | ||
| 100 | - private mutating func scroll(_ key: Key, pageSize: Int) -> Bool { | ||
| 101 | - switch key { | ||
| 102 | - case .arrowUp: scrollOffset += 1 | ||
| 103 | - case .pageUp: scrollOffset += pageSize | ||
| 104 | - case .arrowDown: scrollOffset = max(0, scrollOffset - 1) | ||
| 105 | - case .pageDown: scrollOffset = max(0, scrollOffset - pageSize) | ||
| 106 | - default: return false | ||
| 107 | - } | ||
| 108 | - return true | ||
| 109 | - } | ||
| 110 | - | ||
| 111 | - /// Keys that act on the conversation or the app. | ||
| 112 | - private mutating func command(_ key: Key) -> Action { | ||
| 113 | - switch key { | ||
| 114 | - case .control("t"): | ||
| 115 | - showThinking.toggle() | ||
| 116 | - return .none | ||
| 117 | - case .control("n"): return isBusy ? .none : .reset | ||
| 118 | - case .control("c"): return isBusy ? .stop : .quit | ||
| 119 | - case .control("d"): return input.isEmpty ? .quit : .none | ||
| 120 | - case .enter: return submit() | ||
| 121 | - default: return .none | ||
| 122 | - } | ||
| 123 | - } | ||
| 124 | - | ||
| 125 | - private mutating func handleConfirmation(_ key: Key) -> Action { | ||
| 126 | - switch key { | ||
| 127 | - case .character("y"), .character("Y"): | ||
| 128 | - return .answerConfirmation(true) | ||
| 129 | - case .character("n"), .character("N"), .enter, .escape, .control("c"): | ||
| 130 | - return .answerConfirmation(false) | ||
| 131 | - default: | ||
| 132 | - return .none | ||
| 133 | - } | ||
| 134 | - } | ||
| 135 | - | ||
| 136 | - private mutating func submit() -> Action { | ||
| 137 | - let text = inputText.trimmingCharacters(in: .whitespaces) | ||
| 138 | - guard !text.isEmpty else { return .none } | ||
| 139 | - switch text { | ||
| 140 | - case "/exit", "/quit": | ||
| 141 | - clearInput() | ||
| 142 | - return .quit | ||
| 143 | - case "/reset", "/new": | ||
| 144 | - clearInput() | ||
| 145 | - return isBusy ? .none : .reset | ||
| 146 | - default: | ||
| 147 | - // While an answer runs, the text stays in the input line for later. | ||
| 148 | - guard !isBusy else { return .none } | ||
| 149 | - clearInput() | ||
| 150 | - return .send(text) | ||
| 151 | - } | ||
| 152 | - } | ||
| 153 | - | ||
| 154 | - private mutating func insert(_ character: Character) { | ||
| 155 | - input.insert(character, at: cursor) | ||
| 156 | - cursor += 1 | ||
| 157 | - } | ||
| 158 | - | ||
| 159 | - private mutating func clearInput() { | ||
| 160 | - input.removeAll() | ||
| 161 | - cursor = 0 | ||
| 162 | - } | ||
| 163 | - | ||
| 164 | - // MARK: Conversation | ||
| 165 | - | ||
| 166 | - /// A prompt was sent: show it and wait for the answer. | ||
| 167 | - public mutating func begin(_ prompt: String) { | ||
| 168 | - blocks.append(ChatBlock(kind: .user, text: prompt)) | ||
| 169 | - isBusy = true | ||
| 170 | - scrollOffset = 0 | ||
| 171 | - } | ||
| 172 | - | ||
| 173 | - public mutating func apply(_ event: AgentEvent) { | ||
| 174 | - switch event { | ||
| 175 | - case .text(let text): | ||
| 176 | - append(text, as: .assistant) | ||
| 177 | - case .thinking(let text): | ||
| 178 | - append(text, as: .thinking) | ||
| 179 | - case .toolCall(let call): | ||
| 180 | - let arguments = call.arguments.sorted { $0.key < $1.key } | ||
| 181 | - .map { "\($0.key)=\($0.value.stringValue ?? "\($0.value)")" }.joined(separator: " ") | ||
| 182 | - blocks.append(ChatBlock(kind: .toolCall, text: "→ \(call.name) \(arguments)")) | ||
| 183 | - case .toolResult(let name, let output): | ||
| 184 | - let lines = output.content.split(separator: "\n", omittingEmptySubsequences: false) | ||
| 185 | - let shown = lines.prefix(6).joined(separator: "\n") + (lines.count > 6 ? "\n…" : "") | ||
| 186 | - blocks.append(ChatBlock(kind: .toolResult, text: "← \(name): \(shown)")) | ||
| 187 | - case .stats(let stats): | ||
| 188 | - lastSpeed = stats.tokensPerSecond | ||
| 189 | - guard showStats else { return } | ||
| 190 | - let speed = (stats.tokensPerSecond * 10).rounded() / 10 | ||
| 191 | - let counts = "\(stats.promptTokens) prompt tokens, \(stats.generatedTokens) generated" | ||
| 192 | - blocks.append(ChatBlock(kind: .stats, text: "[\(counts), \(speed) tokens/s]")) | ||
| 193 | - } | ||
| 194 | - } | ||
| 195 | - | ||
| 196 | - /// The answer is complete (or failed, or was stopped). | ||
| 197 | - public mutating func end(error: String? = nil, stopped: Bool = false) { | ||
| 198 | - isBusy = false | ||
| 199 | - if stopped { | ||
| 200 | - notice("(stopped)") | ||
| 201 | - } else if let error { | ||
| 202 | - blocks.append(ChatBlock(kind: .error, text: "error: \(error)")) | ||
| 203 | - } | ||
| 204 | - } | ||
| 205 | - | ||
| 206 | - public mutating func notice(_ text: String) { | ||
| 207 | - blocks.append(ChatBlock(kind: .notice, text: text)) | ||
| 208 | - } | ||
| 209 | - | ||
| 210 | - /// Clears the conversation shown (after a reset of the agent). | ||
| 211 | - public mutating func clear() { | ||
| 212 | - blocks.removeAll() | ||
| 213 | - scrollOffset = 0 | ||
| 214 | - lastSpeed = nil | ||
| 215 | - notice("(new conversation)") | ||
| 216 | - } | ||
| 217 | - | ||
| 218 | - /// A tool waits for the user's answer to `question`. | ||
| 219 | - public mutating func ask(_ question: String) { | ||
| 220 | - pendingConfirmation = question | ||
| 221 | - notice(question) | ||
| 222 | - } | ||
| 223 | - | ||
| 224 | - public mutating func answered(_ accepted: Bool) { | ||
| 225 | - pendingConfirmation = nil | ||
| 226 | - notice(accepted ? "(allowed)" : "(refused)") | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - /// Keeps the scroll offset within the content once the renderer knows its height. | ||
| 230 | - public mutating func clampScroll(maximum: Int) { | ||
| 231 | - scrollOffset = min(scrollOffset, max(0, maximum)) | ||
| 232 | - } | ||
| 233 | - | ||
| 234 | - /// Streamed pieces of the same kind go into the same block. | ||
| 235 | - private mutating func append(_ text: String, as kind: ChatBlock.Kind) { | ||
| 236 | - if let last = blocks.indices.last, blocks[last].kind == kind { | ||
| 237 | - blocks[last].text += text | ||
| 238 | - return | ||
| 239 | - } | ||
| 240 | - // A block does not start with the blank lines models often emit first, and an empty | ||
| 241 | - // thinking block (a model told not to think) is not shown at all. | ||
| 242 | - let trimmed = String(text.drop { $0.isNewline }) | ||
| 243 | - guard !trimmed.allSatisfy(\.isWhitespace) else { return } | ||
| 244 | - blocks.append(ChatBlock(kind: kind, text: trimmed)) | ||
| 245 | - } | ||
| 246 | -} | ||
deleted
Sources/RazorbillTUI/Key.swift +0 -103 | deleted file mode 100644 | ||
| @@ -1,103 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -/// A key press, or a terminal event, as the TUI understands it. | |
| 4 | -public enum Key: Sendable, Equatable { | |
| 5 | - case character(Character) | |
| 6 | - case enter, backspace, delete, tab, escape | |
| 7 | - case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown | |
| 8 | - /// Ctrl + a letter, e.g. `.control("c")`. | |
| 9 | - case control(Character) | |
| 10 | - /// The terminal changed size. | |
| 11 | - case resize | |
| 12 | -} | |
| 13 | - | |
| 14 | -/// Turns the bytes read from a terminal in raw mode into ``Key``s. | |
| 15 | -/// | |
| 16 | -/// Bytes arrive in arbitrary pieces: an escape sequence or a multi-byte UTF-8 character can be | |
| 17 | -/// cut in two, so incomplete input is kept until the next call. | |
| 18 | -/// | |
| 19 | -/// ```swift | |
| 20 | -/// var decoder = KeyDecoder() | |
| 21 | -/// decoder.decode(Array("hi\r".utf8)) // [.character("h"), .character("i"), .enter] | |
| 22 | -/// decoder.decode([27, 91, 65]) // [.arrowUp] | |
| 23 | -/// ``` | |
| 24 | -public struct KeyDecoder: Sendable { | |
| 25 | - private var pending: [UInt8] = [] | |
| 26 | - | |
| 27 | - public init() {} | |
| 28 | - | |
| 29 | - public mutating func decode(_ bytes: [UInt8]) -> [Key] { | |
| 30 | - pending += bytes | |
| 31 | - var keys: [Key] = [] | |
| 32 | - while !pending.isEmpty { | |
| 33 | - guard let (key, length) = Self.next(in: pending) else { break } | |
| 34 | - keys.append(key) | |
| 35 | - pending.removeFirst(length) | |
| 36 | - } | |
| 37 | - return keys | |
| 38 | - } | |
| 39 | - | |
| 40 | - /// A lone escape stays pending (it may start a sequence); call this when no more bytes come. | |
| 41 | - public mutating func flush() -> [Key] { | |
| 42 | - defer { pending = [] } | |
| 43 | - return pending == [27] ? [.escape] : [] | |
| 44 | - } | |
| 45 | - | |
| 46 | - /// The first key of `bytes` and how many bytes it used; `nil` when more bytes are needed. | |
| 47 | - static func next(in bytes: [UInt8]) -> (Key, Int)? { | |
| 48 | - let first = bytes[0] | |
| 49 | - switch first { | |
| 50 | - case 27: | |
| 51 | - return escapeSequence(bytes) | |
| 52 | - case 13, 10: | |
| 53 | - return (.enter, 1) | |
| 54 | - case 127, 8: | |
| 55 | - return (.backspace, 1) | |
| 56 | - case 9: | |
| 57 | - return (.tab, 1) | |
| 58 | - case 1 ... 26: | |
| 59 | - return (.control(Character(Unicode.Scalar(first + 96))), 1) | |
| 60 | - case 0 ..< 32: | |
| 61 | - return (.escape, 1) // other control bytes are ignored as a harmless key | |
| 62 | - default: | |
| 63 | - return utf8Character(bytes) | |
| 64 | - } | |
| 65 | - } | |
| 66 | - | |
| 67 | - private static func escapeSequence(_ bytes: [UInt8]) -> (Key, Int)? { | |
| 68 | - guard bytes.count >= 2 else { return nil } | |
| 69 | - guard bytes[1] == 91 || bytes[1] == 79 else { return (.escape, 1) } // ESC [ or ESC O | |
| 70 | - guard bytes.count >= 3 else { return nil } | |
| 71 | - let simple: [UInt8: Key] = [ | |
| 72 | - 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end, | |
| 73 | - ] | |
| 74 | - if let key = simple[bytes[2]] { | |
| 75 | - return (key, 3) | |
| 76 | - } | |
| 77 | - // ESC [ <number> ~ | |
| 78 | - guard let tilde = bytes.dropFirst(2).firstIndex(of: 126) else { | |
| 79 | - return bytes.count < 8 ? nil : (.escape, 1) | |
| 80 | - } | |
| 81 | - let number = String(bytes: bytes[2 ..< tilde], encoding: .ascii) ?? "" | |
| 82 | - let tilded: [String: Key] = [ | |
| 83 | - "1": .home, "7": .home, "4": .end, "8": .end, "3": .delete, "5": .pageUp, | |
| 84 | - "6": .pageDown, | |
| 85 | - ] | |
| 86 | - return (tilded[number] ?? .escape, tilde + 1) | |
| 87 | - } | |
| 88 | - | |
| 89 | - private static func utf8Character(_ bytes: [UInt8]) -> (Key, Int)? { | |
| 90 | - let first = bytes[0] | |
| 91 | - let length = | |
| 92 | - switch first { | |
| 93 | - case 0xF0...: 4 | |
| 94 | - case 0xE0...: 3 | |
| 95 | - case 0xC0...: 2 | |
| 96 | - default: 1 | |
| 97 | - } | |
| 98 | - guard bytes.count >= length else { return nil } | |
| 99 | - // Invalid UTF-8 becomes a harmless, ignored key. | |
| 100 | - let character = String(bytes: bytes[0 ..< length], encoding: .utf8)?.first | |
| 101 | - return (character.map(Key.character) ?? .escape, length) | |
| 102 | - } | |
| 103 | -} | |
| deleted file mode 100644 | |||
| @@ -1,103 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -/// A key press, or a terminal event, as the TUI understands it. | ||
| 4 | -public enum Key: Sendable, Equatable { | ||
| 5 | - case character(Character) | ||
| 6 | - case enter, backspace, delete, tab, escape | ||
| 7 | - case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown | ||
| 8 | - /// Ctrl + a letter, e.g. `.control("c")`. | ||
| 9 | - case control(Character) | ||
| 10 | - /// The terminal changed size. | ||
| 11 | - case resize | ||
| 12 | -} | ||
| 13 | - | ||
| 14 | -/// Turns the bytes read from a terminal in raw mode into ``Key``s. | ||
| 15 | -/// | ||
| 16 | -/// Bytes arrive in arbitrary pieces: an escape sequence or a multi-byte UTF-8 character can be | ||
| 17 | -/// cut in two, so incomplete input is kept until the next call. | ||
| 18 | -/// | ||
| 19 | -/// ```swift | ||
| 20 | -/// var decoder = KeyDecoder() | ||
| 21 | -/// decoder.decode(Array("hi\r".utf8)) // [.character("h"), .character("i"), .enter] | ||
| 22 | -/// decoder.decode([27, 91, 65]) // [.arrowUp] | ||
| 23 | -/// ``` | ||
| 24 | -public struct KeyDecoder: Sendable { | ||
| 25 | - private var pending: [UInt8] = [] | ||
| 26 | - | ||
| 27 | - public init() {} | ||
| 28 | - | ||
| 29 | - public mutating func decode(_ bytes: [UInt8]) -> [Key] { | ||
| 30 | - pending += bytes | ||
| 31 | - var keys: [Key] = [] | ||
| 32 | - while !pending.isEmpty { | ||
| 33 | - guard let (key, length) = Self.next(in: pending) else { break } | ||
| 34 | - keys.append(key) | ||
| 35 | - pending.removeFirst(length) | ||
| 36 | - } | ||
| 37 | - return keys | ||
| 38 | - } | ||
| 39 | - | ||
| 40 | - /// A lone escape stays pending (it may start a sequence); call this when no more bytes come. | ||
| 41 | - public mutating func flush() -> [Key] { | ||
| 42 | - defer { pending = [] } | ||
| 43 | - return pending == [27] ? [.escape] : [] | ||
| 44 | - } | ||
| 45 | - | ||
| 46 | - /// The first key of `bytes` and how many bytes it used; `nil` when more bytes are needed. | ||
| 47 | - static func next(in bytes: [UInt8]) -> (Key, Int)? { | ||
| 48 | - let first = bytes[0] | ||
| 49 | - switch first { | ||
| 50 | - case 27: | ||
| 51 | - return escapeSequence(bytes) | ||
| 52 | - case 13, 10: | ||
| 53 | - return (.enter, 1) | ||
| 54 | - case 127, 8: | ||
| 55 | - return (.backspace, 1) | ||
| 56 | - case 9: | ||
| 57 | - return (.tab, 1) | ||
| 58 | - case 1 ... 26: | ||
| 59 | - return (.control(Character(Unicode.Scalar(first + 96))), 1) | ||
| 60 | - case 0 ..< 32: | ||
| 61 | - return (.escape, 1) // other control bytes are ignored as a harmless key | ||
| 62 | - default: | ||
| 63 | - return utf8Character(bytes) | ||
| 64 | - } | ||
| 65 | - } | ||
| 66 | - | ||
| 67 | - private static func escapeSequence(_ bytes: [UInt8]) -> (Key, Int)? { | ||
| 68 | - guard bytes.count >= 2 else { return nil } | ||
| 69 | - guard bytes[1] == 91 || bytes[1] == 79 else { return (.escape, 1) } // ESC [ or ESC O | ||
| 70 | - guard bytes.count >= 3 else { return nil } | ||
| 71 | - let simple: [UInt8: Key] = [ | ||
| 72 | - 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end, | ||
| 73 | - ] | ||
| 74 | - if let key = simple[bytes[2]] { | ||
| 75 | - return (key, 3) | ||
| 76 | - } | ||
| 77 | - // ESC [ <number> ~ | ||
| 78 | - guard let tilde = bytes.dropFirst(2).firstIndex(of: 126) else { | ||
| 79 | - return bytes.count < 8 ? nil : (.escape, 1) | ||
| 80 | - } | ||
| 81 | - let number = String(bytes: bytes[2 ..< tilde], encoding: .ascii) ?? "" | ||
| 82 | - let tilded: [String: Key] = [ | ||
| 83 | - "1": .home, "7": .home, "4": .end, "8": .end, "3": .delete, "5": .pageUp, | ||
| 84 | - "6": .pageDown, | ||
| 85 | - ] | ||
| 86 | - return (tilded[number] ?? .escape, tilde + 1) | ||
| 87 | - } | ||
| 88 | - | ||
| 89 | - private static func utf8Character(_ bytes: [UInt8]) -> (Key, Int)? { | ||
| 90 | - let first = bytes[0] | ||
| 91 | - let length = | ||
| 92 | - switch first { | ||
| 93 | - case 0xF0...: 4 | ||
| 94 | - case 0xE0...: 3 | ||
| 95 | - case 0xC0...: 2 | ||
| 96 | - default: 1 | ||
| 97 | - } | ||
| 98 | - guard bytes.count >= length else { return nil } | ||
| 99 | - // Invalid UTF-8 becomes a harmless, ignored key. | ||
| 100 | - let character = String(bytes: bytes[0 ..< length], encoding: .utf8)?.first | ||
| 101 | - return (character.map(Key.character) ?? .escape, length) | ||
| 102 | - } | ||
| 103 | -} | ||
deleted
Sources/RazorbillTUI/ScreenRenderer.swift +0 -115 | deleted file mode 100644 | ||
| @@ -1,115 +0,0 @@ | ||
| 1 | -/// Draws a ``ChatState`` as the lines of a terminal screen. | |
| 2 | -/// | |
| 3 | -/// Layout, top to bottom: a title bar, the conversation (wrapped, scrolled), a help or | |
| 4 | -/// confirmation line, and the input line. | |
| 5 | -/// | |
| 6 | -/// ```swift | |
| 7 | -/// let screen = ScreenRenderer(colors: false).render(state, rows: 24, columns: 80) | |
| 8 | -/// print(screen.lines.joined(separator: "\n")) | |
| 9 | -/// ``` | |
| 10 | -public struct ScreenRenderer: Sendable { | |
| 11 | - /// A drawn screen: one string per row, and where the cursor goes (0-based). | |
| 12 | - public struct Screen: Sendable, Equatable { | |
| 13 | - public var lines: [String] | |
| 14 | - public var cursorRow: Int | |
| 15 | - public var cursorColumn: Int | |
| 16 | - } | |
| 17 | - | |
| 18 | - public var colors: Bool | |
| 19 | - | |
| 20 | - public init(colors: Bool) { | |
| 21 | - self.colors = colors | |
| 22 | - } | |
| 23 | - | |
| 24 | - static let help = | |
| 25 | - "Enter send · Ctrl-T thinking · Ctrl-N new · PgUp/PgDn scroll · Ctrl-C stop/quit" | |
| 26 | - static let prompt = "› " | |
| 27 | - | |
| 28 | - public func render(_ state: ChatState, rows: Int, columns: Int) -> Screen { | |
| 29 | - let width = max(columns, 10) | |
| 30 | - let height = max(rows, 4) | |
| 31 | - let conversationHeight = height - 3 | |
| 32 | - let conversation = conversationLines(state, width: width) | |
| 33 | - let bottom = max(0, conversation.count - conversationHeight) | |
| 34 | - let offset = min(state.scrollOffset, bottom) | |
| 35 | - let start = bottom - offset | |
| 36 | - var visible = Array( | |
| 37 | - conversation[start ..< min(conversation.count, start + conversationHeight)]) | |
| 38 | - visible += Array(repeating: "", count: conversationHeight - visible.count) | |
| 39 | - | |
| 40 | - let (inputLine, cursorColumn) = inputLine(state, width: width) | |
| 41 | - return Screen( | |
| 42 | - lines: [titleBar(state, width: width, scrolled: offset > 0)] + visible | |
| 43 | - + [statusLine(state, width: width), inputLine], | |
| 44 | - cursorRow: height - 1, cursorColumn: cursorColumn) | |
| 45 | - } | |
| 46 | - | |
| 47 | - /// How many lines the conversation would take; used to bound scrolling. | |
| 48 | - public func conversationLineCount(_ state: ChatState, columns: Int) -> Int { | |
| 49 | - conversationLines(state, width: max(columns, 10)).count | |
| 50 | - } | |
| 51 | - | |
| 52 | - private func titleBar(_ state: ChatState, width: Int, scrolled: Bool) -> String { | |
| 53 | - let left = " rzb · \(state.agentName) · \(state.modelName) · \(state.engineName)" | |
| 54 | - var right = state.isBusy ? "● answering " : "" | |
| 55 | - if !state.isBusy, let speed = state.lastSpeed { | |
| 56 | - right = "\((speed * 10).rounded() / 10) tokens/s " | |
| 57 | - } | |
| 58 | - if scrolled { right = "↑ scrolled " + right } | |
| 59 | - let space = max(1, width - left.count - right.count) | |
| 60 | - let text = TextLayout.truncate( | |
| 61 | - left + String(repeating: " ", count: space) + right, width: width) | |
| 62 | - return style(text.padding(to: width), "7") // inverse video | |
| 63 | - } | |
| 64 | - | |
| 65 | - private func statusLine(_ state: ChatState, width: Int) -> String { | |
| 66 | - if let question = state.pendingConfirmation { | |
| 67 | - return style(TextLayout.truncate("\(question) Allow? (y/n)", width: width), "1;33") | |
| 68 | - } | |
| 69 | - return style(TextLayout.truncate(Self.help, width: width), "2") | |
| 70 | - } | |
| 71 | - | |
| 72 | - private func inputLine(_ state: ChatState, width: Int) -> (String, Int) { | |
| 73 | - let room = width - Self.prompt.count - 1 | |
| 74 | - let input = state.inputText | |
| 75 | - // Keep the cursor visible: show the end of a long input. | |
| 76 | - let skip = max(0, state.cursor - room) | |
| 77 | - let visible = String(input.dropFirst(skip).prefix(room)) | |
| 78 | - return (Self.prompt + visible, Self.prompt.count + state.cursor - skip) | |
| 79 | - } | |
| 80 | - | |
| 81 | - private func conversationLines(_ state: ChatState, width: Int) -> [String] { | |
| 82 | - var lines: [String] = [] | |
| 83 | - for block in state.blocks { | |
| 84 | - if block.kind == .thinking, !state.showThinking { continue } | |
| 85 | - if block.kind == .user, !lines.isEmpty { lines.append("") } | |
| 86 | - let prefix = block.kind == .user ? Self.prompt : "" | |
| 87 | - let wrapped = TextLayout.wrap(prefix + block.text, width: width) | |
| 88 | - lines += wrapped.map { style($0, Self.code(for: block.kind)) } | |
| 89 | - } | |
| 90 | - return lines | |
| 91 | - } | |
| 92 | - | |
| 93 | - static func code(for kind: ChatBlock.Kind) -> String? { | |
| 94 | - switch kind { | |
| 95 | - case .user: "1" | |
| 96 | - case .assistant: nil | |
| 97 | - case .thinking, .stats, .toolResult: "2" | |
| 98 | - case .toolCall: "36" | |
| 99 | - case .notice: "33" | |
| 100 | - case .error: "31" | |
| 101 | - } | |
| 102 | - } | |
| 103 | - | |
| 104 | - private func style(_ text: String, _ code: String?) -> String { | |
| 105 | - guard colors, let code else { return text } | |
| 106 | - return "\u{1B}[\(code)m\(text)\u{1B}[0m" | |
| 107 | - } | |
| 108 | -} | |
| 109 | - | |
| 110 | -extension String { | |
| 111 | - /// The string followed by spaces up to `width` characters. | |
| 112 | - func padding(to width: Int) -> String { | |
| 113 | - count >= width ? self : self + String(repeating: " ", count: width - count) | |
| 114 | - } | |
| 115 | -} | |
| deleted file mode 100644 | |||
| @@ -1,115 +0,0 @@ | |||
| 1 | -/// Draws a ``ChatState`` as the lines of a terminal screen. | ||
| 2 | -/// | ||
| 3 | -/// Layout, top to bottom: a title bar, the conversation (wrapped, scrolled), a help or | ||
| 4 | -/// confirmation line, and the input line. | ||
| 5 | -/// | ||
| 6 | -/// ```swift | ||
| 7 | -/// let screen = ScreenRenderer(colors: false).render(state, rows: 24, columns: 80) | ||
| 8 | -/// print(screen.lines.joined(separator: "\n")) | ||
| 9 | -/// ``` | ||
| 10 | -public struct ScreenRenderer: Sendable { | ||
| 11 | - /// A drawn screen: one string per row, and where the cursor goes (0-based). | ||
| 12 | - public struct Screen: Sendable, Equatable { | ||
| 13 | - public var lines: [String] | ||
| 14 | - public var cursorRow: Int | ||
| 15 | - public var cursorColumn: Int | ||
| 16 | - } | ||
| 17 | - | ||
| 18 | - public var colors: Bool | ||
| 19 | - | ||
| 20 | - public init(colors: Bool) { | ||
| 21 | - self.colors = colors | ||
| 22 | - } | ||
| 23 | - | ||
| 24 | - static let help = | ||
| 25 | - "Enter send · Ctrl-T thinking · Ctrl-N new · PgUp/PgDn scroll · Ctrl-C stop/quit" | ||
| 26 | - static let prompt = "› " | ||
| 27 | - | ||
| 28 | - public func render(_ state: ChatState, rows: Int, columns: Int) -> Screen { | ||
| 29 | - let width = max(columns, 10) | ||
| 30 | - let height = max(rows, 4) | ||
| 31 | - let conversationHeight = height - 3 | ||
| 32 | - let conversation = conversationLines(state, width: width) | ||
| 33 | - let bottom = max(0, conversation.count - conversationHeight) | ||
| 34 | - let offset = min(state.scrollOffset, bottom) | ||
| 35 | - let start = bottom - offset | ||
| 36 | - var visible = Array( | ||
| 37 | - conversation[start ..< min(conversation.count, start + conversationHeight)]) | ||
| 38 | - visible += Array(repeating: "", count: conversationHeight - visible.count) | ||
| 39 | - | ||
| 40 | - let (inputLine, cursorColumn) = inputLine(state, width: width) | ||
| 41 | - return Screen( | ||
| 42 | - lines: [titleBar(state, width: width, scrolled: offset > 0)] + visible | ||
| 43 | - + [statusLine(state, width: width), inputLine], | ||
| 44 | - cursorRow: height - 1, cursorColumn: cursorColumn) | ||
| 45 | - } | ||
| 46 | - | ||
| 47 | - /// How many lines the conversation would take; used to bound scrolling. | ||
| 48 | - public func conversationLineCount(_ state: ChatState, columns: Int) -> Int { | ||
| 49 | - conversationLines(state, width: max(columns, 10)).count | ||
| 50 | - } | ||
| 51 | - | ||
| 52 | - private func titleBar(_ state: ChatState, width: Int, scrolled: Bool) -> String { | ||
| 53 | - let left = " rzb · \(state.agentName) · \(state.modelName) · \(state.engineName)" | ||
| 54 | - var right = state.isBusy ? "● answering " : "" | ||
| 55 | - if !state.isBusy, let speed = state.lastSpeed { | ||
| 56 | - right = "\((speed * 10).rounded() / 10) tokens/s " | ||
| 57 | - } | ||
| 58 | - if scrolled { right = "↑ scrolled " + right } | ||
| 59 | - let space = max(1, width - left.count - right.count) | ||
| 60 | - let text = TextLayout.truncate( | ||
| 61 | - left + String(repeating: " ", count: space) + right, width: width) | ||
| 62 | - return style(text.padding(to: width), "7") // inverse video | ||
| 63 | - } | ||
| 64 | - | ||
| 65 | - private func statusLine(_ state: ChatState, width: Int) -> String { | ||
| 66 | - if let question = state.pendingConfirmation { | ||
| 67 | - return style(TextLayout.truncate("\(question) Allow? (y/n)", width: width), "1;33") | ||
| 68 | - } | ||
| 69 | - return style(TextLayout.truncate(Self.help, width: width), "2") | ||
| 70 | - } | ||
| 71 | - | ||
| 72 | - private func inputLine(_ state: ChatState, width: Int) -> (String, Int) { | ||
| 73 | - let room = width - Self.prompt.count - 1 | ||
| 74 | - let input = state.inputText | ||
| 75 | - // Keep the cursor visible: show the end of a long input. | ||
| 76 | - let skip = max(0, state.cursor - room) | ||
| 77 | - let visible = String(input.dropFirst(skip).prefix(room)) | ||
| 78 | - return (Self.prompt + visible, Self.prompt.count + state.cursor - skip) | ||
| 79 | - } | ||
| 80 | - | ||
| 81 | - private func conversationLines(_ state: ChatState, width: Int) -> [String] { | ||
| 82 | - var lines: [String] = [] | ||
| 83 | - for block in state.blocks { | ||
| 84 | - if block.kind == .thinking, !state.showThinking { continue } | ||
| 85 | - if block.kind == .user, !lines.isEmpty { lines.append("") } | ||
| 86 | - let prefix = block.kind == .user ? Self.prompt : "" | ||
| 87 | - let wrapped = TextLayout.wrap(prefix + block.text, width: width) | ||
| 88 | - lines += wrapped.map { style($0, Self.code(for: block.kind)) } | ||
| 89 | - } | ||
| 90 | - return lines | ||
| 91 | - } | ||
| 92 | - | ||
| 93 | - static func code(for kind: ChatBlock.Kind) -> String? { | ||
| 94 | - switch kind { | ||
| 95 | - case .user: "1" | ||
| 96 | - case .assistant: nil | ||
| 97 | - case .thinking, .stats, .toolResult: "2" | ||
| 98 | - case .toolCall: "36" | ||
| 99 | - case .notice: "33" | ||
| 100 | - case .error: "31" | ||
| 101 | - } | ||
| 102 | - } | ||
| 103 | - | ||
| 104 | - private func style(_ text: String, _ code: String?) -> String { | ||
| 105 | - guard colors, let code else { return text } | ||
| 106 | - return "\u{1B}[\(code)m\(text)\u{1B}[0m" | ||
| 107 | - } | ||
| 108 | -} | ||
| 109 | - | ||
| 110 | -extension String { | ||
| 111 | - /// The string followed by spaces up to `width` characters. | ||
| 112 | - func padding(to width: Int) -> String { | ||
| 113 | - count >= width ? self : self + String(repeating: " ", count: width - count) | ||
| 114 | - } | ||
| 115 | -} | ||
deleted
Sources/RazorbillTUI/TUIApp.swift +0 -152 | deleted file mode 100644 | ||
| @@ -1,152 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | - | |
| 4 | -/// Lets tools ask the user for confirmation through the TUI. Create it before the agent (the | |
| 5 | -/// agent's ``ToolContext`` needs it) and hand it to the ``TUIApp``. | |
| 6 | -/// | |
| 7 | -/// ```swift | |
| 8 | -/// let bridge = ConfirmationBridge() | |
| 9 | -/// let agent = Agent(config: config, engine: engine, tools: tools, toolContext: bridge.toolContext) | |
| 10 | -/// try await TUIApp(agent: agent, terminal: PosixTerminal(), bridge: bridge).run() | |
| 11 | -/// ``` | |
| 12 | -public final class ConfirmationBridge: @unchecked Sendable { | |
| 13 | - private let lock = NSLock() | |
| 14 | - private var handler: (@Sendable (ToolContext.ConfirmationRequest) async -> Bool)? | |
| 15 | - | |
| 16 | - public init() {} | |
| 17 | - | |
| 18 | - /// A tool context whose confirmations are answered in the TUI. | |
| 19 | - public var toolContext: ToolContext { | |
| 20 | - ToolContext(isInteractive: true) { request in await self.confirm(request) } | |
| 21 | - } | |
| 22 | - | |
| 23 | - func attach(_ handler: @escaping @Sendable (ToolContext.ConfirmationRequest) async -> Bool) { | |
| 24 | - lock.withLock { self.handler = handler } | |
| 25 | - } | |
| 26 | - | |
| 27 | - private func confirm(_ request: ToolContext.ConfirmationRequest) async -> Bool { | |
| 28 | - guard let handler = lock.withLock({ handler }) else { return false } | |
| 29 | - return await handler(request) | |
| 30 | - } | |
| 31 | -} | |
| 32 | - | |
| 33 | -/// The full-screen chat: reads keys, sends prompts to the agent, draws its events. | |
| 34 | -public actor TUIApp { | |
| 35 | - private let agent: Agent | |
| 36 | - private let terminal: any Terminal | |
| 37 | - private let renderer: ScreenRenderer | |
| 38 | - private var state: ChatState | |
| 39 | - private var turn: Task<Void, Never>? | |
| 40 | - private var pendingAnswer: CheckedContinuation<Bool, Never>? | |
| 41 | - | |
| 42 | - public init( | |
| 43 | - agent: Agent, terminal: any Terminal, bridge: ConfirmationBridge, colors: Bool = true | |
| 44 | - ) { | |
| 45 | - self.agent = agent | |
| 46 | - self.terminal = terminal | |
| 47 | - self.renderer = ScreenRenderer(colors: colors) | |
| 48 | - self.state = ChatState( | |
| 49 | - agentName: agent.config.name, modelName: "\(agent.config.model)", | |
| 50 | - engineName: agent.engineName, | |
| 51 | - showThinking: agent.config.userInterface.showThinking, | |
| 52 | - showStats: agent.config.userInterface.showStats) | |
| 53 | - bridge.attach { [weak self] request in | |
| 54 | - guard let self else { return false } | |
| 55 | - return await self.confirm(request) | |
| 56 | - } | |
| 57 | - } | |
| 58 | - | |
| 59 | - /// The current state (for tests). | |
| 60 | - public var currentState: ChatState { state } | |
| 61 | - | |
| 62 | - /// Runs until the user quits or the input closes; the terminal is always restored. | |
| 63 | - public func run() async { | |
| 64 | - terminal.enter() | |
| 65 | - defer { terminal.leave() } | |
| 66 | - redraw() | |
| 67 | - for await key in terminal.keys() { | |
| 68 | - let rows = terminal.size.rows | |
| 69 | - let action = state.handle(key, pageSize: max(1, rows - 4)) | |
| 70 | - if await perform(action) == false { | |
| 71 | - break | |
| 72 | - } | |
| 73 | - redraw() | |
| 74 | - } | |
| 75 | - await stopTurn() | |
| 76 | - } | |
| 77 | - | |
| 78 | - /// Returns `false` to quit. | |
| 79 | - private func perform(_ action: ChatState.Action) async -> Bool { | |
| 80 | - switch action { | |
| 81 | - case .none: | |
| 82 | - return true | |
| 83 | - case .quit: | |
| 84 | - return false | |
| 85 | - case .send(let prompt): | |
| 86 | - start(prompt) | |
| 87 | - case .stop: | |
| 88 | - await stopTurn() | |
| 89 | - state.end(stopped: true) | |
| 90 | - case .reset: | |
| 91 | - await agent.reset() | |
| 92 | - state.clear() | |
| 93 | - case .answerConfirmation(let accepted): | |
| 94 | - state.answered(accepted) | |
| 95 | - pendingAnswer?.resume(returning: accepted) | |
| 96 | - pendingAnswer = nil | |
| 97 | - } | |
| 98 | - return true | |
| 99 | - } | |
| 100 | - | |
| 101 | - private func start(_ prompt: String) { | |
| 102 | - state.begin(prompt) | |
| 103 | - let agent = self.agent | |
| 104 | - turn = Task { | |
| 105 | - do { | |
| 106 | - for try await event in agent.send(prompt) { | |
| 107 | - self.receive(event) | |
| 108 | - } | |
| 109 | - self.finish(error: nil) | |
| 110 | - } catch is CancellationError { | |
| 111 | - self.finish(error: nil) | |
| 112 | - } catch { | |
| 113 | - self.finish(error: "\(error)") | |
| 114 | - } | |
| 115 | - } | |
| 116 | - } | |
| 117 | - | |
| 118 | - private func receive(_ event: AgentEvent) { | |
| 119 | - state.apply(event) | |
| 120 | - redraw() | |
| 121 | - } | |
| 122 | - | |
| 123 | - private func finish(error: String?) { | |
| 124 | - guard state.isBusy else { return } | |
| 125 | - state.end(error: error) | |
| 126 | - turn = nil | |
| 127 | - redraw() | |
| 128 | - } | |
| 129 | - | |
| 130 | - private func stopTurn() async { | |
| 131 | - pendingAnswer?.resume(returning: false) | |
| 132 | - pendingAnswer = nil | |
| 133 | - turn?.cancel() | |
| 134 | - await turn?.value | |
| 135 | - turn = nil | |
| 136 | - } | |
| 137 | - | |
| 138 | - private func confirm(_ request: ToolContext.ConfirmationRequest) async -> Bool { | |
| 139 | - await withCheckedContinuation { continuation in | |
| 140 | - pendingAnswer = continuation | |
| 141 | - state.ask("\(request.toolName) wants to run: \(request.summary)") | |
| 142 | - redraw() | |
| 143 | - } | |
| 144 | - } | |
| 145 | - | |
| 146 | - private func redraw() { | |
| 147 | - let size = terminal.size | |
| 148 | - let total = renderer.conversationLineCount(state, columns: size.columns) | |
| 149 | - state.clampScroll(maximum: total - (size.rows - 3)) | |
| 150 | - terminal.draw(renderer.render(state, rows: size.rows, columns: size.columns)) | |
| 151 | - } | |
| 152 | -} | |
| deleted file mode 100644 | |||
| @@ -1,152 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | - | ||
| 4 | -/// Lets tools ask the user for confirmation through the TUI. Create it before the agent (the | ||
| 5 | -/// agent's ``ToolContext`` needs it) and hand it to the ``TUIApp``. | ||
| 6 | -/// | ||
| 7 | -/// ```swift | ||
| 8 | -/// let bridge = ConfirmationBridge() | ||
| 9 | -/// let agent = Agent(config: config, engine: engine, tools: tools, toolContext: bridge.toolContext) | ||
| 10 | -/// try await TUIApp(agent: agent, terminal: PosixTerminal(), bridge: bridge).run() | ||
| 11 | -/// ``` | ||
| 12 | -public final class ConfirmationBridge: @unchecked Sendable { | ||
| 13 | - private let lock = NSLock() | ||
| 14 | - private var handler: (@Sendable (ToolContext.ConfirmationRequest) async -> Bool)? | ||
| 15 | - | ||
| 16 | - public init() {} | ||
| 17 | - | ||
| 18 | - /// A tool context whose confirmations are answered in the TUI. | ||
| 19 | - public var toolContext: ToolContext { | ||
| 20 | - ToolContext(isInteractive: true) { request in await self.confirm(request) } | ||
| 21 | - } | ||
| 22 | - | ||
| 23 | - func attach(_ handler: @escaping @Sendable (ToolContext.ConfirmationRequest) async -> Bool) { | ||
| 24 | - lock.withLock { self.handler = handler } | ||
| 25 | - } | ||
| 26 | - | ||
| 27 | - private func confirm(_ request: ToolContext.ConfirmationRequest) async -> Bool { | ||
| 28 | - guard let handler = lock.withLock({ handler }) else { return false } | ||
| 29 | - return await handler(request) | ||
| 30 | - } | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -/// The full-screen chat: reads keys, sends prompts to the agent, draws its events. | ||
| 34 | -public actor TUIApp { | ||
| 35 | - private let agent: Agent | ||
| 36 | - private let terminal: any Terminal | ||
| 37 | - private let renderer: ScreenRenderer | ||
| 38 | - private var state: ChatState | ||
| 39 | - private var turn: Task<Void, Never>? | ||
| 40 | - private var pendingAnswer: CheckedContinuation<Bool, Never>? | ||
| 41 | - | ||
| 42 | - public init( | ||
| 43 | - agent: Agent, terminal: any Terminal, bridge: ConfirmationBridge, colors: Bool = true | ||
| 44 | - ) { | ||
| 45 | - self.agent = agent | ||
| 46 | - self.terminal = terminal | ||
| 47 | - self.renderer = ScreenRenderer(colors: colors) | ||
| 48 | - self.state = ChatState( | ||
| 49 | - agentName: agent.config.name, modelName: "\(agent.config.model)", | ||
| 50 | - engineName: agent.engineName, | ||
| 51 | - showThinking: agent.config.userInterface.showThinking, | ||
| 52 | - showStats: agent.config.userInterface.showStats) | ||
| 53 | - bridge.attach { [weak self] request in | ||
| 54 | - guard let self else { return false } | ||
| 55 | - return await self.confirm(request) | ||
| 56 | - } | ||
| 57 | - } | ||
| 58 | - | ||
| 59 | - /// The current state (for tests). | ||
| 60 | - public var currentState: ChatState { state } | ||
| 61 | - | ||
| 62 | - /// Runs until the user quits or the input closes; the terminal is always restored. | ||
| 63 | - public func run() async { | ||
| 64 | - terminal.enter() | ||
| 65 | - defer { terminal.leave() } | ||
| 66 | - redraw() | ||
| 67 | - for await key in terminal.keys() { | ||
| 68 | - let rows = terminal.size.rows | ||
| 69 | - let action = state.handle(key, pageSize: max(1, rows - 4)) | ||
| 70 | - if await perform(action) == false { | ||
| 71 | - break | ||
| 72 | - } | ||
| 73 | - redraw() | ||
| 74 | - } | ||
| 75 | - await stopTurn() | ||
| 76 | - } | ||
| 77 | - | ||
| 78 | - /// Returns `false` to quit. | ||
| 79 | - private func perform(_ action: ChatState.Action) async -> Bool { | ||
| 80 | - switch action { | ||
| 81 | - case .none: | ||
| 82 | - return true | ||
| 83 | - case .quit: | ||
| 84 | - return false | ||
| 85 | - case .send(let prompt): | ||
| 86 | - start(prompt) | ||
| 87 | - case .stop: | ||
| 88 | - await stopTurn() | ||
| 89 | - state.end(stopped: true) | ||
| 90 | - case .reset: | ||
| 91 | - await agent.reset() | ||
| 92 | - state.clear() | ||
| 93 | - case .answerConfirmation(let accepted): | ||
| 94 | - state.answered(accepted) | ||
| 95 | - pendingAnswer?.resume(returning: accepted) | ||
| 96 | - pendingAnswer = nil | ||
| 97 | - } | ||
| 98 | - return true | ||
| 99 | - } | ||
| 100 | - | ||
| 101 | - private func start(_ prompt: String) { | ||
| 102 | - state.begin(prompt) | ||
| 103 | - let agent = self.agent | ||
| 104 | - turn = Task { | ||
| 105 | - do { | ||
| 106 | - for try await event in agent.send(prompt) { | ||
| 107 | - self.receive(event) | ||
| 108 | - } | ||
| 109 | - self.finish(error: nil) | ||
| 110 | - } catch is CancellationError { | ||
| 111 | - self.finish(error: nil) | ||
| 112 | - } catch { | ||
| 113 | - self.finish(error: "\(error)") | ||
| 114 | - } | ||
| 115 | - } | ||
| 116 | - } | ||
| 117 | - | ||
| 118 | - private func receive(_ event: AgentEvent) { | ||
| 119 | - state.apply(event) | ||
| 120 | - redraw() | ||
| 121 | - } | ||
| 122 | - | ||
| 123 | - private func finish(error: String?) { | ||
| 124 | - guard state.isBusy else { return } | ||
| 125 | - state.end(error: error) | ||
| 126 | - turn = nil | ||
| 127 | - redraw() | ||
| 128 | - } | ||
| 129 | - | ||
| 130 | - private func stopTurn() async { | ||
| 131 | - pendingAnswer?.resume(returning: false) | ||
| 132 | - pendingAnswer = nil | ||
| 133 | - turn?.cancel() | ||
| 134 | - await turn?.value | ||
| 135 | - turn = nil | ||
| 136 | - } | ||
| 137 | - | ||
| 138 | - private func confirm(_ request: ToolContext.ConfirmationRequest) async -> Bool { | ||
| 139 | - await withCheckedContinuation { continuation in | ||
| 140 | - pendingAnswer = continuation | ||
| 141 | - state.ask("\(request.toolName) wants to run: \(request.summary)") | ||
| 142 | - redraw() | ||
| 143 | - } | ||
| 144 | - } | ||
| 145 | - | ||
| 146 | - private func redraw() { | ||
| 147 | - let size = terminal.size | ||
| 148 | - let total = renderer.conversationLineCount(state, columns: size.columns) | ||
| 149 | - state.clampScroll(maximum: total - (size.rows - 3)) | ||
| 150 | - terminal.draw(renderer.render(state, rows: size.rows, columns: size.columns)) | ||
| 151 | - } | ||
| 152 | -} | ||
deleted
Sources/RazorbillTUI/Terminal.swift +0 -124 | deleted file mode 100644 | ||
| @@ -1,124 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | - | |
| 3 | -#if canImport(Darwin) | |
| 4 | -import Darwin | |
| 5 | -#else | |
| 6 | -import Glibc | |
| 7 | -#endif | |
| 8 | - | |
| 9 | -/// The terminal the TUI draws on. ``PosixTerminal`` is the real one; tests use a fake. | |
| 10 | -public protocol Terminal: Sendable { | |
| 11 | - /// Rows and columns. | |
| 12 | - var size: (rows: Int, columns: Int) { get } | |
| 13 | - /// Switches to raw mode and the alternate screen. | |
| 14 | - func enter() | |
| 15 | - /// Restores the terminal as it was. Safe to call twice. | |
| 16 | - func leave() | |
| 17 | - /// Keys typed, and `.resize` when the window changes size. Ends when input closes. | |
| 18 | - func keys() -> AsyncStream<Key> | |
| 19 | - /// Replaces the whole screen with `screen`. | |
| 20 | - func draw(_ screen: ScreenRenderer.Screen) | |
| 21 | -} | |
| 22 | - | |
| 23 | -/// The process's terminal (standard input and output), driven with termios and ANSI codes. | |
| 24 | -public final class PosixTerminal: Terminal, @unchecked Sendable { | |
| 25 | - /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable. | |
| 26 | - private var resizeSource: (any DispatchSourceSignal)? | |
| 27 | - | |
| 28 | - public init() {} | |
| 29 | - | |
| 30 | - /// Both standard input and standard output are terminals. | |
| 31 | - public static var isAvailable: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDOUT_FILENO) == 1 } | |
| 32 | - | |
| 33 | - public var size: (rows: Int, columns: Int) { | |
| 34 | - var window = winsize() | |
| 35 | - guard ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &window) == 0 else { return (24, 80) } | |
| 36 | - let rows = Int(window.ws_row) | |
| 37 | - let columns = Int(window.ws_col) | |
| 38 | - return rows > 0 && columns > 0 ? (rows, columns) : (24, 80) | |
| 39 | - } | |
| 40 | - | |
| 41 | - public func enter() { | |
| 42 | - TerminalRestorer.save() | |
| 43 | - var raw = TerminalRestorer.original ?? termios() | |
| 44 | - cfmakeraw(&raw) | |
| 45 | - tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) | |
| 46 | - // Alternate screen, cleared. | |
| 47 | - write("\u{1B}[?1049h\u{1B}[2J") | |
| 48 | - TerminalRestorer.installSignalHandlers() | |
| 49 | - } | |
| 50 | - | |
| 51 | - public func leave() { | |
| 52 | - TerminalRestorer.restore() | |
| 53 | - } | |
| 54 | - | |
| 55 | - public func keys() -> AsyncStream<Key> { | |
| 56 | - AsyncStream { continuation in | |
| 57 | - let resize = DispatchSource.makeSignalSource(signal: SIGWINCH) | |
| 58 | - signal(SIGWINCH, SIG_IGN) | |
| 59 | - resize.setEventHandler { continuation.yield(.resize) } | |
| 60 | - resize.resume() | |
| 61 | - resizeSource = resize | |
| 62 | - let reader = Thread { | |
| 63 | - var decoder = KeyDecoder() | |
| 64 | - var buffer = [UInt8](repeating: 0, count: 256) | |
| 65 | - while true { | |
| 66 | - let count = read(STDIN_FILENO, &buffer, buffer.count) | |
| 67 | - if count < 0, errno == EINTR { continue } | |
| 68 | - if count <= 0 { break } | |
| 69 | - var keys = decoder.decode(Array(buffer[0 ..< count])) | |
| 70 | - keys += decoder.flush() // a lone ESC read alone is the Escape key | |
| 71 | - for key in keys { continuation.yield(key) } | |
| 72 | - } | |
| 73 | - self.resizeSource?.cancel() | |
| 74 | - continuation.finish() | |
| 75 | - } | |
| 76 | - reader.start() | |
| 77 | - } | |
| 78 | - } | |
| 79 | - | |
| 80 | - public func draw(_ screen: ScreenRenderer.Screen) { | |
| 81 | - var output = "\u{1B}[?25l" // hide the cursor while drawing | |
| 82 | - for (row, line) in screen.lines.enumerated() { | |
| 83 | - output += "\u{1B}[\(row + 1);1H\u{1B}[2K\(line)" | |
| 84 | - } | |
| 85 | - output += "\u{1B}[\(screen.cursorRow + 1);\(screen.cursorColumn + 1)H\u{1B}[?25h" | |
| 86 | - write(output) | |
| 87 | - } | |
| 88 | - | |
| 89 | - private func write(_ text: String) { | |
| 90 | - FileHandle.standardOutput.write(Data(text.utf8)) | |
| 91 | - } | |
| 92 | -} | |
| 93 | - | |
| 94 | -/// Puts the terminal back when the TUI ends, including on SIGTERM / SIGHUP, so the user never | |
| 95 | -/// gets stuck in raw mode. (Signal handlers cannot capture context, hence the global state.) | |
| 96 | -enum TerminalRestorer { | |
| 97 | - nonisolated(unsafe) static var original: termios? | |
| 98 | - | |
| 99 | - static func save() { | |
| 100 | - var current = termios() | |
| 101 | - if tcgetattr(STDIN_FILENO, ¤t) == 0 { | |
| 102 | - original = current | |
| 103 | - } | |
| 104 | - } | |
| 105 | - | |
| 106 | - static func restore() { | |
| 107 | - guard var saved = original else { return } | |
| 108 | - tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved) | |
| 109 | - let reset = "\u{1B}[?25h\u{1B}[?1049l" | |
| 110 | - _ = reset.withCString { Foundation.write(STDOUT_FILENO, $0, strlen($0)) } | |
| 111 | - original = nil | |
| 112 | - } | |
| 113 | - | |
| 114 | - static func installSignalHandlers() { | |
| 115 | - atexit { TerminalRestorer.restore() } | |
| 116 | - for signalNumber in [SIGTERM, SIGHUP, SIGQUIT] { | |
| 117 | - signal(signalNumber) { received in | |
| 118 | - TerminalRestorer.restore() | |
| 119 | - signal(received, SIG_DFL) | |
| 120 | - raise(received) | |
| 121 | - } | |
| 122 | - } | |
| 123 | - } | |
| 124 | -} | |
| deleted file mode 100644 | |||
| @@ -1,124 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | - | ||
| 3 | -#if canImport(Darwin) | ||
| 4 | -import Darwin | ||
| 5 | -#else | ||
| 6 | -import Glibc | ||
| 7 | -#endif | ||
| 8 | - | ||
| 9 | -/// The terminal the TUI draws on. ``PosixTerminal`` is the real one; tests use a fake. | ||
| 10 | -public protocol Terminal: Sendable { | ||
| 11 | - /// Rows and columns. | ||
| 12 | - var size: (rows: Int, columns: Int) { get } | ||
| 13 | - /// Switches to raw mode and the alternate screen. | ||
| 14 | - func enter() | ||
| 15 | - /// Restores the terminal as it was. Safe to call twice. | ||
| 16 | - func leave() | ||
| 17 | - /// Keys typed, and `.resize` when the window changes size. Ends when input closes. | ||
| 18 | - func keys() -> AsyncStream<Key> | ||
| 19 | - /// Replaces the whole screen with `screen`. | ||
| 20 | - func draw(_ screen: ScreenRenderer.Screen) | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -/// The process's terminal (standard input and output), driven with termios and ANSI codes. | ||
| 24 | -public final class PosixTerminal: Terminal, @unchecked Sendable { | ||
| 25 | - /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable. | ||
| 26 | - private var resizeSource: (any DispatchSourceSignal)? | ||
| 27 | - | ||
| 28 | - public init() {} | ||
| 29 | - | ||
| 30 | - /// Both standard input and standard output are terminals. | ||
| 31 | - public static var isAvailable: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDOUT_FILENO) == 1 } | ||
| 32 | - | ||
| 33 | - public var size: (rows: Int, columns: Int) { | ||
| 34 | - var window = winsize() | ||
| 35 | - guard ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &window) == 0 else { return (24, 80) } | ||
| 36 | - let rows = Int(window.ws_row) | ||
| 37 | - let columns = Int(window.ws_col) | ||
| 38 | - return rows > 0 && columns > 0 ? (rows, columns) : (24, 80) | ||
| 39 | - } | ||
| 40 | - | ||
| 41 | - public func enter() { | ||
| 42 | - TerminalRestorer.save() | ||
| 43 | - var raw = TerminalRestorer.original ?? termios() | ||
| 44 | - cfmakeraw(&raw) | ||
| 45 | - tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) | ||
| 46 | - // Alternate screen, cleared. | ||
| 47 | - write("\u{1B}[?1049h\u{1B}[2J") | ||
| 48 | - TerminalRestorer.installSignalHandlers() | ||
| 49 | - } | ||
| 50 | - | ||
| 51 | - public func leave() { | ||
| 52 | - TerminalRestorer.restore() | ||
| 53 | - } | ||
| 54 | - | ||
| 55 | - public func keys() -> AsyncStream<Key> { | ||
| 56 | - AsyncStream { continuation in | ||
| 57 | - let resize = DispatchSource.makeSignalSource(signal: SIGWINCH) | ||
| 58 | - signal(SIGWINCH, SIG_IGN) | ||
| 59 | - resize.setEventHandler { continuation.yield(.resize) } | ||
| 60 | - resize.resume() | ||
| 61 | - resizeSource = resize | ||
| 62 | - let reader = Thread { | ||
| 63 | - var decoder = KeyDecoder() | ||
| 64 | - var buffer = [UInt8](repeating: 0, count: 256) | ||
| 65 | - while true { | ||
| 66 | - let count = read(STDIN_FILENO, &buffer, buffer.count) | ||
| 67 | - if count < 0, errno == EINTR { continue } | ||
| 68 | - if count <= 0 { break } | ||
| 69 | - var keys = decoder.decode(Array(buffer[0 ..< count])) | ||
| 70 | - keys += decoder.flush() // a lone ESC read alone is the Escape key | ||
| 71 | - for key in keys { continuation.yield(key) } | ||
| 72 | - } | ||
| 73 | - self.resizeSource?.cancel() | ||
| 74 | - continuation.finish() | ||
| 75 | - } | ||
| 76 | - reader.start() | ||
| 77 | - } | ||
| 78 | - } | ||
| 79 | - | ||
| 80 | - public func draw(_ screen: ScreenRenderer.Screen) { | ||
| 81 | - var output = "\u{1B}[?25l" // hide the cursor while drawing | ||
| 82 | - for (row, line) in screen.lines.enumerated() { | ||
| 83 | - output += "\u{1B}[\(row + 1);1H\u{1B}[2K\(line)" | ||
| 84 | - } | ||
| 85 | - output += "\u{1B}[\(screen.cursorRow + 1);\(screen.cursorColumn + 1)H\u{1B}[?25h" | ||
| 86 | - write(output) | ||
| 87 | - } | ||
| 88 | - | ||
| 89 | - private func write(_ text: String) { | ||
| 90 | - FileHandle.standardOutput.write(Data(text.utf8)) | ||
| 91 | - } | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | -/// Puts the terminal back when the TUI ends, including on SIGTERM / SIGHUP, so the user never | ||
| 95 | -/// gets stuck in raw mode. (Signal handlers cannot capture context, hence the global state.) | ||
| 96 | -enum TerminalRestorer { | ||
| 97 | - nonisolated(unsafe) static var original: termios? | ||
| 98 | - | ||
| 99 | - static func save() { | ||
| 100 | - var current = termios() | ||
| 101 | - if tcgetattr(STDIN_FILENO, ¤t) == 0 { | ||
| 102 | - original = current | ||
| 103 | - } | ||
| 104 | - } | ||
| 105 | - | ||
| 106 | - static func restore() { | ||
| 107 | - guard var saved = original else { return } | ||
| 108 | - tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved) | ||
| 109 | - let reset = "\u{1B}[?25h\u{1B}[?1049l" | ||
| 110 | - _ = reset.withCString { Foundation.write(STDOUT_FILENO, $0, strlen($0)) } | ||
| 111 | - original = nil | ||
| 112 | - } | ||
| 113 | - | ||
| 114 | - static func installSignalHandlers() { | ||
| 115 | - atexit { TerminalRestorer.restore() } | ||
| 116 | - for signalNumber in [SIGTERM, SIGHUP, SIGQUIT] { | ||
| 117 | - signal(signalNumber) { received in | ||
| 118 | - TerminalRestorer.restore() | ||
| 119 | - signal(received, SIG_DFL) | ||
| 120 | - raise(received) | ||
| 121 | - } | ||
| 122 | - } | ||
| 123 | - } | ||
| 124 | -} | ||
deleted
Sources/RazorbillTUI/TextLayout.swift +0 -37 | deleted file mode 100644 | ||
| @@ -1,37 +0,0 @@ | ||
| 1 | -/// Breaks text into lines that fit a width, at spaces when possible. | |
| 2 | -/// | |
| 3 | -/// ```swift | |
| 4 | -/// TextLayout.wrap("hello wide world", width: 10) // ["hello wide", "world"] | |
| 5 | -/// ``` | |
| 6 | -public enum TextLayout { | |
| 7 | - public static func wrap(_ text: String, width: Int) -> [String] { | |
| 8 | - guard width > 0 else { return [] } | |
| 9 | - return text.split(separator: "\n", omittingEmptySubsequences: false).flatMap { | |
| 10 | - wrapLine(String($0), width: width) | |
| 11 | - } | |
| 12 | - } | |
| 13 | - | |
| 14 | - private static func wrapLine(_ line: String, width: Int) -> [String] { | |
| 15 | - var rest = Substring(line) | |
| 16 | - var lines: [String] = [] | |
| 17 | - while rest.count > width { | |
| 18 | - let window = rest.prefix(width + 1) | |
| 19 | - if let space = window.lastIndex(of: " "), space > rest.startIndex { | |
| 20 | - lines.append(String(rest[..<space])) | |
| 21 | - rest = rest[rest.index(after: space)...] | |
| 22 | - } else { | |
| 23 | - lines.append(String(rest.prefix(width))) | |
| 24 | - rest = rest.dropFirst(width) | |
| 25 | - } | |
| 26 | - } | |
| 27 | - lines.append(String(rest)) | |
| 28 | - return lines | |
| 29 | - } | |
| 30 | - | |
| 31 | - /// `text` cut to `width` characters, with `…` when cut. | |
| 32 | - public static func truncate(_ text: String, width: Int) -> String { | |
| 33 | - guard text.count > width else { return text } | |
| 34 | - guard width > 1 else { return String(text.prefix(width)) } | |
| 35 | - return String(text.prefix(width - 1)) + "…" | |
| 36 | - } | |
| 37 | -} | |
| deleted file mode 100644 | |||
| @@ -1,37 +0,0 @@ | |||
| 1 | -/// Breaks text into lines that fit a width, at spaces when possible. | ||
| 2 | -/// | ||
| 3 | -/// ```swift | ||
| 4 | -/// TextLayout.wrap("hello wide world", width: 10) // ["hello wide", "world"] | ||
| 5 | -/// ``` | ||
| 6 | -public enum TextLayout { | ||
| 7 | - public static func wrap(_ text: String, width: Int) -> [String] { | ||
| 8 | - guard width > 0 else { return [] } | ||
| 9 | - return text.split(separator: "\n", omittingEmptySubsequences: false).flatMap { | ||
| 10 | - wrapLine(String($0), width: width) | ||
| 11 | - } | ||
| 12 | - } | ||
| 13 | - | ||
| 14 | - private static func wrapLine(_ line: String, width: Int) -> [String] { | ||
| 15 | - var rest = Substring(line) | ||
| 16 | - var lines: [String] = [] | ||
| 17 | - while rest.count > width { | ||
| 18 | - let window = rest.prefix(width + 1) | ||
| 19 | - if let space = window.lastIndex(of: " "), space > rest.startIndex { | ||
| 20 | - lines.append(String(rest[..<space])) | ||
| 21 | - rest = rest[rest.index(after: space)...] | ||
| 22 | - } else { | ||
| 23 | - lines.append(String(rest.prefix(width))) | ||
| 24 | - rest = rest.dropFirst(width) | ||
| 25 | - } | ||
| 26 | - } | ||
| 27 | - lines.append(String(rest)) | ||
| 28 | - return lines | ||
| 29 | - } | ||
| 30 | - | ||
| 31 | - /// `text` cut to `width` characters, with `…` when cut. | ||
| 32 | - public static func truncate(_ text: String, width: Int) -> String { | ||
| 33 | - guard text.count > width else { return text } | ||
| 34 | - guard width > 1 else { return String(text.prefix(width)) } | ||
| 35 | - return String(text.prefix(width - 1)) + "…" | ||
| 36 | - } | ||
| 37 | -} | ||
modified
Tests/RazorbillCLITests/Harness.swift +4 -29 | @@ -9,19 +9,16 @@ import Testing | ||
| 9 | 9 | final class ScriptedConsole: Console, @unchecked Sendable { |
| 10 | 10 | private let lock = NSLock() |
| 11 | 11 | private var inputs: [String] |
| 12 | - private var piped: String? | |
| 13 | 12 | private var out = "" |
| 14 | 13 | private var err = "" |
| 15 | 14 | let isInteractive: Bool |
| 16 | 15 | let usesColor = false |
| 17 | 16 | |
| 18 | - init(inputs: [String] = [], interactive: Bool = true, piped: String? = nil) { | |
| 17 | + init(inputs: [String] = [], interactive: Bool = true) { | |
| 19 | 18 | self.inputs = inputs |
| 20 | - self.isInteractive = interactive && piped == nil | |
| 21 | - self.piped = piped | |
| 19 | + self.isInteractive = interactive | |
| 22 | 20 | } |
| 23 | 21 | |
| 24 | - var inputIsTerminal: Bool { piped == nil } | |
| 25 | 22 | var stdout: String { lock.withLock { out } } |
| 26 | 23 | var stderr: String { lock.withLock { err } } |
| 27 | 24 | |
| @@ -30,12 +27,6 @@ final class ScriptedConsole: Console, @unchecked Sendable { | ||
| 30 | 27 | func readLine() -> String? { |
| 31 | 28 | lock.withLock { inputs.isEmpty ? nil : inputs.removeFirst() } |
| 32 | 29 | } |
| 33 | - func readAll() -> String { | |
| 34 | - lock.withLock { | |
| 35 | - defer { piped = nil } | |
| 36 | - return piped ?? "" | |
| 37 | - } | |
| 38 | - } | |
| 39 | 30 | } |
| 40 | 31 | |
| 41 | 32 | /// The result of one `rzb` invocation. |
| @@ -67,22 +58,8 @@ struct World { | ||
| 67 | 58 | var engines = EngineRegistry() |
| 68 | 59 | engines.register("fake") { engine } |
| 69 | 60 | return CLIEnvironment( |
| 70 | - engines: engines, tools: .builtIn, console: console, | |
| 71 | - modelStore: ModelStore(cacheDirectory: cacheDirectory), | |
| 72 | - currentDirectory: directory, homeDirectory: directory + "/home", | |
| 73 | - templateContext: TemplateContext( | |
| 74 | - date: Date(timeIntervalSince1970: 0), currentDirectory: directory, environment: [:], | |
| 75 | - timeZone: TimeZone(identifier: "UTC")!) | |
| 76 | - ) | |
| 77 | - } | |
| 78 | - | |
| 79 | - /// Writes `razorbill.yaml` in the world's directory. | |
| 80 | - func writeAgent(_ yaml: String, named name: String = "razorbill.yaml") throws { | |
| 81 | - try yaml.write(toFile: directory + "/" + name, atomically: true, encoding: .utf8) | |
| 82 | - } | |
| 83 | - | |
| 84 | - func file(_ name: String) -> String? { | |
| 85 | - try? String(contentsOfFile: directory + "/" + name, encoding: .utf8) | |
| 61 | + engines: engines, console: console, | |
| 62 | + modelStore: ModelStore(cacheDirectory: cacheDirectory)) | |
| 86 | 63 | } |
| 87 | 64 | |
| 88 | 65 | /// Parses and runs `rzb <arguments>` like the executable does, without exiting. |
| @@ -103,5 +80,3 @@ struct World { | ||
| 103 | 80 | return Invocation(exitCode: code, stdout: console.stdout, stderr: console.stderr) |
| 104 | 81 | } |
| 105 | 82 | } |
| 106 | - | |
| 107 | -let simpleAgent = "name: helper\nmodel: mlx-community/Qwen3-0.6B-4bit\n" | |
| @@ -9,19 +9,16 @@ import Testing | |||
| 9 | final class ScriptedConsole: Console, @unchecked Sendable { | 9 | final class ScriptedConsole: Console, @unchecked Sendable { |
| 10 | private let lock = NSLock() | 10 | private let lock = NSLock() |
| 11 | private var inputs: [String] | 11 | private var inputs: [String] |
| 12 | - private var piped: String? | ||
| 13 | private var out = "" | 12 | private var out = "" |
| 14 | private var err = "" | 13 | private var err = "" |
| 15 | let isInteractive: Bool | 14 | let isInteractive: Bool |
| 16 | let usesColor = false | 15 | let usesColor = false |
| 17 | 16 | ||
| 18 | - init(inputs: [String] = [], interactive: Bool = true, piped: String? = nil) { | 17 | + init(inputs: [String] = [], interactive: Bool = true) { |
| 19 | self.inputs = inputs | 18 | self.inputs = inputs |
| 20 | - self.isInteractive = interactive && piped == nil | 19 | + self.isInteractive = interactive |
| 21 | - self.piped = piped | ||
| 22 | } | 20 | } |
| 23 | 21 | ||
| 24 | - var inputIsTerminal: Bool { piped == nil } | ||
| 25 | var stdout: String { lock.withLock { out } } | 22 | var stdout: String { lock.withLock { out } } |
| 26 | var stderr: String { lock.withLock { err } } | 23 | var stderr: String { lock.withLock { err } } |
| 27 | 24 | ||
| @@ -30,12 +27,6 @@ final class ScriptedConsole: Console, @unchecked Sendable { | |||
| 30 | func readLine() -> String? { | 27 | func readLine() -> String? { |
| 31 | lock.withLock { inputs.isEmpty ? nil : inputs.removeFirst() } | 28 | lock.withLock { inputs.isEmpty ? nil : inputs.removeFirst() } |
| 32 | } | 29 | } |
| 33 | - func readAll() -> String { | ||
| 34 | - lock.withLock { | ||
| 35 | - defer { piped = nil } | ||
| 36 | - return piped ?? "" | ||
| 37 | - } | ||
| 38 | - } | ||
| 39 | } | 30 | } |
| 40 | 31 | ||
| 41 | /// The result of one `rzb` invocation. | 32 | /// The result of one `rzb` invocation. |
| @@ -67,22 +58,8 @@ struct World { | |||
| 67 | var engines = EngineRegistry() | 58 | var engines = EngineRegistry() |
| 68 | engines.register("fake") { engine } | 59 | engines.register("fake") { engine } |
| 69 | return CLIEnvironment( | 60 | return CLIEnvironment( |
| 70 | - engines: engines, tools: .builtIn, console: console, | 61 | + engines: engines, console: console, |
| 71 | - modelStore: ModelStore(cacheDirectory: cacheDirectory), | 62 | + modelStore: ModelStore(cacheDirectory: cacheDirectory)) |
| 72 | - currentDirectory: directory, homeDirectory: directory + "/home", | ||
| 73 | - templateContext: TemplateContext( | ||
| 74 | - date: Date(timeIntervalSince1970: 0), currentDirectory: directory, environment: [:], | ||
| 75 | - timeZone: TimeZone(identifier: "UTC")!) | ||
| 76 | - ) | ||
| 77 | - } | ||
| 78 | - | ||
| 79 | - /// Writes `razorbill.yaml` in the world's directory. | ||
| 80 | - func writeAgent(_ yaml: String, named name: String = "razorbill.yaml") throws { | ||
| 81 | - try yaml.write(toFile: directory + "/" + name, atomically: true, encoding: .utf8) | ||
| 82 | - } | ||
| 83 | - | ||
| 84 | - func file(_ name: String) -> String? { | ||
| 85 | - try? String(contentsOfFile: directory + "/" + name, encoding: .utf8) | ||
| 86 | } | 63 | } |
| 87 | 64 | ||
| 88 | /// Parses and runs `rzb <arguments>` like the executable does, without exiting. | 65 | /// Parses and runs `rzb <arguments>` like the executable does, without exiting. |
| @@ -103,5 +80,3 @@ struct World { | |||
| 103 | return Invocation(exitCode: code, stdout: console.stdout, stderr: console.stderr) | 80 | return Invocation(exitCode: code, stdout: console.stdout, stderr: console.stderr) |
| 104 | } | 81 | } |
| 105 | } | 82 | } |
| 106 | - | ||
| 107 | -let simpleAgent = "name: helper\nmodel: mlx-community/Qwen3-0.6B-4bit\n" | ||
modified
Tests/RazorbillCLITests/OtherCommandsTests.swift +6 -121 | @@ -4,31 +4,6 @@ import Testing | ||
| 4 | 4 | |
| 5 | 5 | @testable import RazorbillCLI |
| 6 | 6 | |
| 7 | -@Suite struct ConfigValidateTests { | |
| 8 | - @Test func reportsAValidFile() async throws { | |
| 9 | - let world = try World() | |
| 10 | - try world.writeAgent(simpleAgent + "tools: [bash]\n") | |
| 11 | - | |
| 12 | - let result = await world.rzb("config", "validate") | |
| 13 | - | |
| 14 | - #expect(result.exitCode == 0) | |
| 15 | - #expect( | |
| 16 | - result.stdout.hasSuffix( | |
| 17 | - "razorbill.yaml is valid: agent \"helper\", model mlx-community/Qwen3-0.6B-4bit, tools: bash\n" | |
| 18 | - )) | |
| 19 | - } | |
| 20 | - | |
| 21 | - @Test func reportsUnknownToolsAndKeys() async throws { | |
| 22 | - let world = try World() | |
| 23 | - try world.writeAgent(simpleAgent + "tools: [web]\n", named: "a.yaml") | |
| 24 | - | |
| 25 | - let result = await world.rzb("config", "validate", world.directory + "/a.yaml") | |
| 26 | - | |
| 27 | - #expect(result.exitCode == 2) | |
| 28 | - #expect(result.stderr.contains("tools.web: unknown tool (available: bash)")) | |
| 29 | - } | |
| 30 | -} | |
| 31 | - | |
| 32 | 7 | @Suite struct ModelsCommandTests { |
| 33 | 8 | func worldWithModel(console: ScriptedConsole = ScriptedConsole()) throws -> World { |
| 34 | 9 | let world = try World(console: console) |
| @@ -86,106 +61,16 @@ import Testing | ||
| 86 | 61 | } |
| 87 | 62 | } |
| 88 | 63 | |
| 89 | -@Suite struct InitCommandTests { | |
| 90 | - @Test func yesWritesALoadableFileWithDefaults() async throws { | |
| 91 | - let world = try World(console: ScriptedConsole(interactive: false)) | |
| 92 | - | |
| 93 | - let result = await world.rzb("init", "--yes", "--name", "bot", "--model", "org/M") | |
| 94 | - | |
| 95 | - #expect(result.exitCode == 0) | |
| 96 | - let config = try world.environment.configLoader.load( | |
| 97 | - file: world.directory + "/razorbill.yaml") | |
| 98 | - #expect(config.name == "bot") | |
| 99 | - #expect(config.model == .huggingFace(id: "org/M", revision: "main")) | |
| 100 | - #expect(config.system == "You are a helpful assistant. Today is 1970-01-01.\n") | |
| 101 | - } | |
| 102 | - | |
| 103 | - @Test func existingFileIsKeptWithoutForce() async throws { | |
| 104 | - let world = try World(console: ScriptedConsole(interactive: false)) | |
| 105 | - try world.writeAgent("keep me") | |
| 106 | - | |
| 107 | - #expect(await world.rzb("init", "--yes").exitCode == 1) | |
| 108 | - #expect(world.file("razorbill.yaml") == "keep me") | |
| 109 | - #expect(await world.rzb("init", "--yes", "--force").exitCode == 0) | |
| 110 | - } | |
| 111 | - | |
| 112 | - @Test func withoutATerminalTheWizardNeedsYes() async throws { | |
| 113 | - let world = try World(console: ScriptedConsole(interactive: false)) | |
| 114 | - #expect(await world.rzb("init").exitCode == 1) | |
| 115 | - } | |
| 116 | - | |
| 117 | - @Test func wizardAsksForEachValueAndOffersTheModels() async throws { | |
| 118 | - let answers = [ | |
| 119 | - "coder", // name | |
| 120 | - "Writes Swift", // description | |
| 121 | - "2", // model: second recommended one | |
| 122 | - "", // system prompt: default | |
| 123 | - "abc", "0.2", // temperature: invalid, then valid | |
| 124 | - "", // max tokens: default | |
| 125 | - "y", // thinking | |
| 126 | - "2000", "256", // thinking budget: more than max tokens, then valid | |
| 127 | - "n", // do not show the thinking | |
| 128 | - "y", // enable bash | |
| 129 | - "", // write the file: yes | |
| 130 | - "n", // do not download | |
| 131 | - ] | |
| 132 | - let world = try World(console: ScriptedConsole(inputs: answers)) | |
| 133 | - | |
| 134 | - let result = await world.rzb("init", "-o", "coder.yaml") | |
| 135 | - | |
| 136 | - #expect(result.exitCode == 0) | |
| 137 | - #expect( | |
| 138 | - result.stderr.contains("1. mlx-community/Qwen3-0.6B-4bit (about 350 MB to download)")) | |
| 139 | - #expect(result.stderr.contains("That value is not valid.")) | |
| 140 | - let config = try world.environment.configLoader.load(file: world.directory + "/coder.yaml") | |
| 141 | - #expect(config.name == "coder") | |
| 142 | - #expect(config.description == "Writes Swift") | |
| 143 | - #expect(config.model == .huggingFace(id: RecommendedModels.all[1].id, revision: "main")) | |
| 144 | - #expect( | |
| 145 | - config.generation | |
| 146 | - == GenerationSettings( | |
| 147 | - temperature: 0.2, maxTokens: 1024, thinking: true, thinkingBudget: 256)) | |
| 148 | - #expect(!config.userInterface.showThinking) | |
| 149 | - #expect(config.tools["bash"]?["confirm"] == .bool(true)) | |
| 150 | - #expect(world.engine.loadedModels.isEmpty) | |
| 151 | - } | |
| 152 | - | |
| 153 | - @Test func downloadedModelsAreListedFirst() throws { | |
| 154 | - let world = try World() | |
| 155 | - let snapshot = world.cacheDirectory.appendingPathComponent( | |
| 156 | - "models--org--Mine/snapshots/abc") | |
| 157 | - try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true) | |
| 158 | - try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json")) | |
| 159 | - try Data(count: 10).write(to: snapshot.appendingPathComponent("m.safetensors")) | |
| 160 | - try FileManager.default.createDirectory( | |
| 161 | - at: world.cacheDirectory.appendingPathComponent("models--org--Mine/refs"), | |
| 162 | - withIntermediateDirectories: true) | |
| 163 | - try "abc".write( | |
| 164 | - to: world.cacheDirectory.appendingPathComponent("models--org--Mine/refs/main"), | |
| 165 | - atomically: true, encoding: .utf8) | |
| 166 | - | |
| 167 | - let choices = ModelChoices.make(store: world.environment.modelStore) | |
| 168 | - | |
| 169 | - #expect(choices.first?.id == "org/Mine") | |
| 170 | - #expect(choices.first?.label.contains("downloaded") == true) | |
| 171 | - #expect(choices.count == RecommendedModels.all.count + 1) | |
| 172 | - } | |
| 173 | -} | |
| 174 | - | |
| 175 | 64 | @Suite struct SmallPieces { |
| 176 | 65 | @Test func versionListsTheEngines() async throws { |
| 177 | 66 | #expect(VersionCommand.line(engines: ["fake", "mlx"]) == "rzb 0.1.0 (engines: fake, mlx)") |
| 178 | 67 | #expect((await (try World()).rzb("version")).stdout == "rzb 0.1.0 (engines: fake)\n") |
| 179 | 68 | } |
| 180 | 69 | |
| 181 | - @Test func modelOptionTellsPathsFromIds() { | |
| 182 | - func reference(_ text: String) -> ModelReference { | |
| 183 | - AgentOptions.modelReference(text, cwd: "/work", home: "/home/ada") | |
| 184 | - } | |
| 185 | - #expect(reference("org/model") == .huggingFace(id: "org/model", revision: "main")) | |
| 186 | - #expect(reference("/m") == .local(path: URL(fileURLWithPath: "/m"))) | |
| 187 | - #expect(reference("./m") == .local(path: URL(fileURLWithPath: "/work/m"))) | |
| 188 | - #expect(reference("~/m") == .local(path: URL(fileURLWithPath: "/home/ada/m"))) | |
| 70 | + @Test func downloadProgressPrintsEveryTenPercentWithoutColours() { | |
| 71 | + let line = ProgressLine() | |
| 72 | + let printed = [0.0, 0.05, 0.1, 0.15, 0.5, 1.0, 1.0].filter(line.shouldPrint) | |
| 73 | + #expect(printed == [0.0, 0.1, 0.5, 1.0]) | |
| 189 | 74 | } |
| 190 | 75 | |
| 191 | 76 | @Test func formattingIsLocaleIndependent() { |
| @@ -196,10 +81,10 @@ import Testing | ||
| 196 | 81 | } |
| 197 | 82 | |
| 198 | 83 | @Test func prompterRetriesUntilTheAnswerIsValid() throws { |
| 199 | - let console = ScriptedConsole(inputs: ["maybe", "y", "9", "2"]) | |
| 84 | + let console = ScriptedConsole(inputs: ["maybe", "y", ""]) | |
| 200 | 85 | let prompter = Prompter(console: console) |
| 201 | 86 | #expect(try prompter.confirm("Ok?", default: false)) |
| 202 | - #expect(try prompter.choose("Pick", options: ["a", "b"]) == 1) | |
| 87 | + #expect(try !prompter.confirm("Again?", default: false)) | |
| 203 | 88 | #expect(throws: InputEnded.self) { try prompter.ask("More") } |
| 204 | 89 | } |
| 205 | 90 | } |
| @@ -4,31 +4,6 @@ import Testing | |||
| 4 | 4 | ||
| 5 | @testable import RazorbillCLI | 5 | @testable import RazorbillCLI |
| 6 | 6 | ||
| 7 | -@Suite struct ConfigValidateTests { | ||
| 8 | - @Test func reportsAValidFile() async throws { | ||
| 9 | - let world = try World() | ||
| 10 | - try world.writeAgent(simpleAgent + "tools: [bash]\n") | ||
| 11 | - | ||
| 12 | - let result = await world.rzb("config", "validate") | ||
| 13 | - | ||
| 14 | - #expect(result.exitCode == 0) | ||
| 15 | - #expect( | ||
| 16 | - result.stdout.hasSuffix( | ||
| 17 | - "razorbill.yaml is valid: agent \"helper\", model mlx-community/Qwen3-0.6B-4bit, tools: bash\n" | ||
| 18 | - )) | ||
| 19 | - } | ||
| 20 | - | ||
| 21 | - @Test func reportsUnknownToolsAndKeys() async throws { | ||
| 22 | - let world = try World() | ||
| 23 | - try world.writeAgent(simpleAgent + "tools: [web]\n", named: "a.yaml") | ||
| 24 | - | ||
| 25 | - let result = await world.rzb("config", "validate", world.directory + "/a.yaml") | ||
| 26 | - | ||
| 27 | - #expect(result.exitCode == 2) | ||
| 28 | - #expect(result.stderr.contains("tools.web: unknown tool (available: bash)")) | ||
| 29 | - } | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | @Suite struct ModelsCommandTests { | 7 | @Suite struct ModelsCommandTests { |
| 33 | func worldWithModel(console: ScriptedConsole = ScriptedConsole()) throws -> World { | 8 | func worldWithModel(console: ScriptedConsole = ScriptedConsole()) throws -> World { |
| 34 | let world = try World(console: console) | 9 | let world = try World(console: console) |
| @@ -86,106 +61,16 @@ import Testing | |||
| 86 | } | 61 | } |
| 87 | } | 62 | } |
| 88 | 63 | ||
| 89 | -@Suite struct InitCommandTests { | ||
| 90 | - @Test func yesWritesALoadableFileWithDefaults() async throws { | ||
| 91 | - let world = try World(console: ScriptedConsole(interactive: false)) | ||
| 92 | - | ||
| 93 | - let result = await world.rzb("init", "--yes", "--name", "bot", "--model", "org/M") | ||
| 94 | - | ||
| 95 | - #expect(result.exitCode == 0) | ||
| 96 | - let config = try world.environment.configLoader.load( | ||
| 97 | - file: world.directory + "/razorbill.yaml") | ||
| 98 | - #expect(config.name == "bot") | ||
| 99 | - #expect(config.model == .huggingFace(id: "org/M", revision: "main")) | ||
| 100 | - #expect(config.system == "You are a helpful assistant. Today is 1970-01-01.\n") | ||
| 101 | - } | ||
| 102 | - | ||
| 103 | - @Test func existingFileIsKeptWithoutForce() async throws { | ||
| 104 | - let world = try World(console: ScriptedConsole(interactive: false)) | ||
| 105 | - try world.writeAgent("keep me") | ||
| 106 | - | ||
| 107 | - #expect(await world.rzb("init", "--yes").exitCode == 1) | ||
| 108 | - #expect(world.file("razorbill.yaml") == "keep me") | ||
| 109 | - #expect(await world.rzb("init", "--yes", "--force").exitCode == 0) | ||
| 110 | - } | ||
| 111 | - | ||
| 112 | - @Test func withoutATerminalTheWizardNeedsYes() async throws { | ||
| 113 | - let world = try World(console: ScriptedConsole(interactive: false)) | ||
| 114 | - #expect(await world.rzb("init").exitCode == 1) | ||
| 115 | - } | ||
| 116 | - | ||
| 117 | - @Test func wizardAsksForEachValueAndOffersTheModels() async throws { | ||
| 118 | - let answers = [ | ||
| 119 | - "coder", // name | ||
| 120 | - "Writes Swift", // description | ||
| 121 | - "2", // model: second recommended one | ||
| 122 | - "", // system prompt: default | ||
| 123 | - "abc", "0.2", // temperature: invalid, then valid | ||
| 124 | - "", // max tokens: default | ||
| 125 | - "y", // thinking | ||
| 126 | - "2000", "256", // thinking budget: more than max tokens, then valid | ||
| 127 | - "n", // do not show the thinking | ||
| 128 | - "y", // enable bash | ||
| 129 | - "", // write the file: yes | ||
| 130 | - "n", // do not download | ||
| 131 | - ] | ||
| 132 | - let world = try World(console: ScriptedConsole(inputs: answers)) | ||
| 133 | - | ||
| 134 | - let result = await world.rzb("init", "-o", "coder.yaml") | ||
| 135 | - | ||
| 136 | - #expect(result.exitCode == 0) | ||
| 137 | - #expect( | ||
| 138 | - result.stderr.contains("1. mlx-community/Qwen3-0.6B-4bit (about 350 MB to download)")) | ||
| 139 | - #expect(result.stderr.contains("That value is not valid.")) | ||
| 140 | - let config = try world.environment.configLoader.load(file: world.directory + "/coder.yaml") | ||
| 141 | - #expect(config.name == "coder") | ||
| 142 | - #expect(config.description == "Writes Swift") | ||
| 143 | - #expect(config.model == .huggingFace(id: RecommendedModels.all[1].id, revision: "main")) | ||
| 144 | - #expect( | ||
| 145 | - config.generation | ||
| 146 | - == GenerationSettings( | ||
| 147 | - temperature: 0.2, maxTokens: 1024, thinking: true, thinkingBudget: 256)) | ||
| 148 | - #expect(!config.userInterface.showThinking) | ||
| 149 | - #expect(config.tools["bash"]?["confirm"] == .bool(true)) | ||
| 150 | - #expect(world.engine.loadedModels.isEmpty) | ||
| 151 | - } | ||
| 152 | - | ||
| 153 | - @Test func downloadedModelsAreListedFirst() throws { | ||
| 154 | - let world = try World() | ||
| 155 | - let snapshot = world.cacheDirectory.appendingPathComponent( | ||
| 156 | - "models--org--Mine/snapshots/abc") | ||
| 157 | - try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true) | ||
| 158 | - try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json")) | ||
| 159 | - try Data(count: 10).write(to: snapshot.appendingPathComponent("m.safetensors")) | ||
| 160 | - try FileManager.default.createDirectory( | ||
| 161 | - at: world.cacheDirectory.appendingPathComponent("models--org--Mine/refs"), | ||
| 162 | - withIntermediateDirectories: true) | ||
| 163 | - try "abc".write( | ||
| 164 | - to: world.cacheDirectory.appendingPathComponent("models--org--Mine/refs/main"), | ||
| 165 | - atomically: true, encoding: .utf8) | ||
| 166 | - | ||
| 167 | - let choices = ModelChoices.make(store: world.environment.modelStore) | ||
| 168 | - | ||
| 169 | - #expect(choices.first?.id == "org/Mine") | ||
| 170 | - #expect(choices.first?.label.contains("downloaded") == true) | ||
| 171 | - #expect(choices.count == RecommendedModels.all.count + 1) | ||
| 172 | - } | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | @Suite struct SmallPieces { | 64 | @Suite struct SmallPieces { |
| 176 | @Test func versionListsTheEngines() async throws { | 65 | @Test func versionListsTheEngines() async throws { |
| 177 | #expect(VersionCommand.line(engines: ["fake", "mlx"]) == "rzb 0.1.0 (engines: fake, mlx)") | 66 | #expect(VersionCommand.line(engines: ["fake", "mlx"]) == "rzb 0.1.0 (engines: fake, mlx)") |
| 178 | #expect((await (try World()).rzb("version")).stdout == "rzb 0.1.0 (engines: fake)\n") | 67 | #expect((await (try World()).rzb("version")).stdout == "rzb 0.1.0 (engines: fake)\n") |
| 179 | } | 68 | } |
| 180 | 69 | ||
| 181 | - @Test func modelOptionTellsPathsFromIds() { | 70 | + @Test func downloadProgressPrintsEveryTenPercentWithoutColours() { |
| 182 | - func reference(_ text: String) -> ModelReference { | 71 | + let line = ProgressLine() |
| 183 | - AgentOptions.modelReference(text, cwd: "/work", home: "/home/ada") | 72 | + let printed = [0.0, 0.05, 0.1, 0.15, 0.5, 1.0, 1.0].filter(line.shouldPrint) |
| 184 | - } | 73 | + #expect(printed == [0.0, 0.1, 0.5, 1.0]) |
| 185 | - #expect(reference("org/model") == .huggingFace(id: "org/model", revision: "main")) | ||
| 186 | - #expect(reference("/m") == .local(path: URL(fileURLWithPath: "/m"))) | ||
| 187 | - #expect(reference("./m") == .local(path: URL(fileURLWithPath: "/work/m"))) | ||
| 188 | - #expect(reference("~/m") == .local(path: URL(fileURLWithPath: "/home/ada/m"))) | ||
| 189 | } | 74 | } |
| 190 | 75 | ||
| 191 | @Test func formattingIsLocaleIndependent() { | 76 | @Test func formattingIsLocaleIndependent() { |
| @@ -196,10 +81,10 @@ import Testing | |||
| 196 | } | 81 | } |
| 197 | 82 | ||
| 198 | @Test func prompterRetriesUntilTheAnswerIsValid() throws { | 83 | @Test func prompterRetriesUntilTheAnswerIsValid() throws { |
| 199 | - let console = ScriptedConsole(inputs: ["maybe", "y", "9", "2"]) | 84 | + let console = ScriptedConsole(inputs: ["maybe", "y", ""]) |
| 200 | let prompter = Prompter(console: console) | 85 | let prompter = Prompter(console: console) |
| 201 | #expect(try prompter.confirm("Ok?", default: false)) | 86 | #expect(try prompter.confirm("Ok?", default: false)) |
| 202 | - #expect(try prompter.choose("Pick", options: ["a", "b"]) == 1) | 87 | + #expect(try !prompter.confirm("Again?", default: false)) |
| 203 | #expect(throws: InputEnded.self) { try prompter.ask("More") } | 88 | #expect(throws: InputEnded.self) { try prompter.ask("More") } |
| 204 | } | 89 | } |
| 205 | } | 90 | } |
deleted
Tests/RazorbillCLITests/RunAndChatTests.swift +0 -144 | deleted file mode 100644 | ||
| @@ -1,144 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -@testable import RazorbillCLI | |
| 6 | - | |
| 7 | -@Suite struct RunCommandTests { | |
| 8 | - @Test func printsTheAnswerOnStdoutAndStatsOnStderr() async throws { | |
| 9 | - let world = try World() | |
| 10 | - try world.writeAgent(simpleAgent) | |
| 11 | - | |
| 12 | - let result = await world.rzb("run", "hello", "there") | |
| 13 | - | |
| 14 | - #expect(result.exitCode == 0) | |
| 15 | - #expect(result.stdout == "echo: hello there\n") | |
| 16 | - #expect(result.stderr.contains("[1 prompt tokens, 1 generated, 1.0 tokens/s]")) | |
| 17 | - #expect( | |
| 18 | - world.engine.loadedModels == [ | |
| 19 | - .huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main") | |
| 20 | - ]) | |
| 21 | - } | |
| 22 | - | |
| 23 | - @Test func pipedInputIsAddedAfterThePrompt() async throws { | |
| 24 | - let world = try World(console: ScriptedConsole(piped: "some diff\n")) | |
| 25 | - try world.writeAgent(simpleAgent) | |
| 26 | - | |
| 27 | - let result = await world.rzb("run", "Review") | |
| 28 | - | |
| 29 | - #expect(result.stdout == "echo: Review\n\nsome diff\n") | |
| 30 | - } | |
| 31 | - | |
| 32 | - @Test func commandLineOptionsOverrideTheFile() async throws { | |
| 33 | - let world = try World() | |
| 34 | - try world.writeAgent(simpleAgent) | |
| 35 | - | |
| 36 | - _ = await world.rzb( | |
| 37 | - "run", "-m", "org/Other", "--temperature", "0", "--max-tokens", "9", "--think", | |
| 38 | - "--thinking-budget", "4", "x") | |
| 39 | - | |
| 40 | - #expect(world.engine.loadedModels == [.huggingFace(id: "org/Other", revision: "main")]) | |
| 41 | - #expect( | |
| 42 | - world.engine.sessionSetups.first?.generation | |
| 43 | - == GenerationSettings( | |
| 44 | - temperature: 0, maxTokens: 9, thinking: true, thinkingBudget: 4)) | |
| 45 | - } | |
| 46 | - | |
| 47 | - @Test func aNegativeThinkingBudgetIsAUsageError() async throws { | |
| 48 | - let world = try World() | |
| 49 | - try world.writeAgent(simpleAgent) | |
| 50 | - #expect(await world.rzb("run", "--thinking-budget", "-1", "x").exitCode == 64) | |
| 51 | - } | |
| 52 | - | |
| 53 | - @Test func missingPromptIsAUsageError() async throws { | |
| 54 | - let world = try World() | |
| 55 | - try world.writeAgent(simpleAgent) | |
| 56 | - #expect(await world.rzb("run").exitCode == 64) | |
| 57 | - } | |
| 58 | - | |
| 59 | - @Test func missingOrInvalidAgentFileExitsWithTwo() async throws { | |
| 60 | - let world = try World() | |
| 61 | - let missing = await world.rzb("run", "hi") | |
| 62 | - #expect(missing.exitCode == 2) | |
| 63 | - #expect(missing.stderr.contains("Create one with `rzb init`")) | |
| 64 | - | |
| 65 | - try world.writeAgent("name: x\n") | |
| 66 | - let invalid = await world.rzb("run", "hi") | |
| 67 | - #expect(invalid.exitCode == 2) | |
| 68 | - #expect(invalid.stderr.contains("model: is required")) | |
| 69 | - } | |
| 70 | - | |
| 71 | - @Test func bashAsksBeforeRunningAndShowsTheCall() async throws { | |
| 72 | - let call = ToolCall(name: "bash", arguments: ["command": .string("echo tool-ran")]) | |
| 73 | - let world = try World( | |
| 74 | - script: [[.toolCall(call)], [.text("done")]], console: ScriptedConsole(inputs: ["y"])) | |
| 75 | - try world.writeAgent(simpleAgent + "tools:\n bash:\n") | |
| 76 | - | |
| 77 | - let result = await world.rzb("run", "go") | |
| 78 | - | |
| 79 | - #expect(result.stdout == "done\n") | |
| 80 | - #expect(result.stderr.contains("bash wants to run: echo tool-ran")) | |
| 81 | - #expect(result.stderr.contains("→ bash command=\"echo tool-ran\"")) | |
| 82 | - #expect( | |
| 83 | - world.engine.receivedMessages.last?.first?.content | |
| 84 | - == "exit code: 0\nstdout:\ntool-ran\n") | |
| 85 | - } | |
| 86 | - | |
| 87 | - @Test func bashIsRefusedWhenNobodyCanConfirm() async throws { | |
| 88 | - let call = ToolCall(name: "bash", arguments: ["command": .string("echo x")]) | |
| 89 | - let world = try World( | |
| 90 | - script: [[.toolCall(call)], [.text("ok")]], console: ScriptedConsole(piped: "data")) | |
| 91 | - try world.writeAgent(simpleAgent + "tools:\n bash:\n") | |
| 92 | - | |
| 93 | - _ = await world.rzb("run", "go") | |
| 94 | - | |
| 95 | - #expect( | |
| 96 | - world.engine.receivedMessages.last?.first?.content.hasPrefix("refused: no terminal") | |
| 97 | - == true) | |
| 98 | - } | |
| 99 | - | |
| 100 | - @Test func thinkingIsShownUnlessTheFileHidesIt() async throws { | |
| 101 | - let script: [[EngineEvent]] = [[.thinking("hmm"), .text("A")]] | |
| 102 | - let shown = try World(script: script) | |
| 103 | - try shown.writeAgent(simpleAgent + "generation:\n thinking: true\n") | |
| 104 | - #expect((await shown.rzb("run", "q")).stderr.contains("hmm")) | |
| 105 | - | |
| 106 | - let hidden = try World(script: script) | |
| 107 | - try hidden.writeAgent( | |
| 108 | - simpleAgent + "generation:\n thinking: true\nui:\n show_thinking: false\n") | |
| 109 | - #expect(!(await hidden.rzb("run", "q")).stderr.contains("hmm")) | |
| 110 | - } | |
| 111 | - | |
| 112 | - @Test func anEmptyThinkingBlockPrintsNothing() async throws { | |
| 113 | - let world = try World(script: [[.thinking("\n\n"), .text("A")]]) | |
| 114 | - try world.writeAgent(simpleAgent) | |
| 115 | - let result = await world.rzb("run", "q") | |
| 116 | - #expect(result.stdout == "A\n") | |
| 117 | - #expect(!result.stderr.contains("\n\n")) | |
| 118 | - } | |
| 119 | -} | |
| 120 | - | |
| 121 | -@Suite struct ChatCommandTests { | |
| 122 | - @Test func talksUntilEndOfInputAndHandlesCommands() async throws { | |
| 123 | - let world = try World( | |
| 124 | - console: ScriptedConsole(inputs: ["hello", "", "/help", "/reset", "again"])) | |
| 125 | - try world.writeAgent(simpleAgent) | |
| 126 | - | |
| 127 | - let result = await world.rzb("chat") | |
| 128 | - | |
| 129 | - #expect(result.exitCode == 0) | |
| 130 | - #expect(result.stdout == "echo: hello\necho: again\n") | |
| 131 | - #expect(result.stderr.contains("helper · mlx-community/Qwen3-0.6B-4bit · fake")) | |
| 132 | - #expect(result.stderr.contains("(new conversation)")) | |
| 133 | - #expect(world.engine.sessionSetups.count == 2) | |
| 134 | - } | |
| 135 | - | |
| 136 | - @Test func exitCommandStopsTheLoop() async throws { | |
| 137 | - let world = try World(console: ScriptedConsole(inputs: ["/exit", "never sent"])) | |
| 138 | - try world.writeAgent(simpleAgent) | |
| 139 | - | |
| 140 | - _ = await world.rzb("chat") | |
| 141 | - | |
| 142 | - #expect(world.engine.receivedMessages.isEmpty) | |
| 143 | - } | |
| 144 | -} | |
| deleted file mode 100644 | |||
| @@ -1,144 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -@testable import RazorbillCLI | ||
| 6 | - | ||
| 7 | -@Suite struct RunCommandTests { | ||
| 8 | - @Test func printsTheAnswerOnStdoutAndStatsOnStderr() async throws { | ||
| 9 | - let world = try World() | ||
| 10 | - try world.writeAgent(simpleAgent) | ||
| 11 | - | ||
| 12 | - let result = await world.rzb("run", "hello", "there") | ||
| 13 | - | ||
| 14 | - #expect(result.exitCode == 0) | ||
| 15 | - #expect(result.stdout == "echo: hello there\n") | ||
| 16 | - #expect(result.stderr.contains("[1 prompt tokens, 1 generated, 1.0 tokens/s]")) | ||
| 17 | - #expect( | ||
| 18 | - world.engine.loadedModels == [ | ||
| 19 | - .huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main") | ||
| 20 | - ]) | ||
| 21 | - } | ||
| 22 | - | ||
| 23 | - @Test func pipedInputIsAddedAfterThePrompt() async throws { | ||
| 24 | - let world = try World(console: ScriptedConsole(piped: "some diff\n")) | ||
| 25 | - try world.writeAgent(simpleAgent) | ||
| 26 | - | ||
| 27 | - let result = await world.rzb("run", "Review") | ||
| 28 | - | ||
| 29 | - #expect(result.stdout == "echo: Review\n\nsome diff\n") | ||
| 30 | - } | ||
| 31 | - | ||
| 32 | - @Test func commandLineOptionsOverrideTheFile() async throws { | ||
| 33 | - let world = try World() | ||
| 34 | - try world.writeAgent(simpleAgent) | ||
| 35 | - | ||
| 36 | - _ = await world.rzb( | ||
| 37 | - "run", "-m", "org/Other", "--temperature", "0", "--max-tokens", "9", "--think", | ||
| 38 | - "--thinking-budget", "4", "x") | ||
| 39 | - | ||
| 40 | - #expect(world.engine.loadedModels == [.huggingFace(id: "org/Other", revision: "main")]) | ||
| 41 | - #expect( | ||
| 42 | - world.engine.sessionSetups.first?.generation | ||
| 43 | - == GenerationSettings( | ||
| 44 | - temperature: 0, maxTokens: 9, thinking: true, thinkingBudget: 4)) | ||
| 45 | - } | ||
| 46 | - | ||
| 47 | - @Test func aNegativeThinkingBudgetIsAUsageError() async throws { | ||
| 48 | - let world = try World() | ||
| 49 | - try world.writeAgent(simpleAgent) | ||
| 50 | - #expect(await world.rzb("run", "--thinking-budget", "-1", "x").exitCode == 64) | ||
| 51 | - } | ||
| 52 | - | ||
| 53 | - @Test func missingPromptIsAUsageError() async throws { | ||
| 54 | - let world = try World() | ||
| 55 | - try world.writeAgent(simpleAgent) | ||
| 56 | - #expect(await world.rzb("run").exitCode == 64) | ||
| 57 | - } | ||
| 58 | - | ||
| 59 | - @Test func missingOrInvalidAgentFileExitsWithTwo() async throws { | ||
| 60 | - let world = try World() | ||
| 61 | - let missing = await world.rzb("run", "hi") | ||
| 62 | - #expect(missing.exitCode == 2) | ||
| 63 | - #expect(missing.stderr.contains("Create one with `rzb init`")) | ||
| 64 | - | ||
| 65 | - try world.writeAgent("name: x\n") | ||
| 66 | - let invalid = await world.rzb("run", "hi") | ||
| 67 | - #expect(invalid.exitCode == 2) | ||
| 68 | - #expect(invalid.stderr.contains("model: is required")) | ||
| 69 | - } | ||
| 70 | - | ||
| 71 | - @Test func bashAsksBeforeRunningAndShowsTheCall() async throws { | ||
| 72 | - let call = ToolCall(name: "bash", arguments: ["command": .string("echo tool-ran")]) | ||
| 73 | - let world = try World( | ||
| 74 | - script: [[.toolCall(call)], [.text("done")]], console: ScriptedConsole(inputs: ["y"])) | ||
| 75 | - try world.writeAgent(simpleAgent + "tools:\n bash:\n") | ||
| 76 | - | ||
| 77 | - let result = await world.rzb("run", "go") | ||
| 78 | - | ||
| 79 | - #expect(result.stdout == "done\n") | ||
| 80 | - #expect(result.stderr.contains("bash wants to run: echo tool-ran")) | ||
| 81 | - #expect(result.stderr.contains("→ bash command=\"echo tool-ran\"")) | ||
| 82 | - #expect( | ||
| 83 | - world.engine.receivedMessages.last?.first?.content | ||
| 84 | - == "exit code: 0\nstdout:\ntool-ran\n") | ||
| 85 | - } | ||
| 86 | - | ||
| 87 | - @Test func bashIsRefusedWhenNobodyCanConfirm() async throws { | ||
| 88 | - let call = ToolCall(name: "bash", arguments: ["command": .string("echo x")]) | ||
| 89 | - let world = try World( | ||
| 90 | - script: [[.toolCall(call)], [.text("ok")]], console: ScriptedConsole(piped: "data")) | ||
| 91 | - try world.writeAgent(simpleAgent + "tools:\n bash:\n") | ||
| 92 | - | ||
| 93 | - _ = await world.rzb("run", "go") | ||
| 94 | - | ||
| 95 | - #expect( | ||
| 96 | - world.engine.receivedMessages.last?.first?.content.hasPrefix("refused: no terminal") | ||
| 97 | - == true) | ||
| 98 | - } | ||
| 99 | - | ||
| 100 | - @Test func thinkingIsShownUnlessTheFileHidesIt() async throws { | ||
| 101 | - let script: [[EngineEvent]] = [[.thinking("hmm"), .text("A")]] | ||
| 102 | - let shown = try World(script: script) | ||
| 103 | - try shown.writeAgent(simpleAgent + "generation:\n thinking: true\n") | ||
| 104 | - #expect((await shown.rzb("run", "q")).stderr.contains("hmm")) | ||
| 105 | - | ||
| 106 | - let hidden = try World(script: script) | ||
| 107 | - try hidden.writeAgent( | ||
| 108 | - simpleAgent + "generation:\n thinking: true\nui:\n show_thinking: false\n") | ||
| 109 | - #expect(!(await hidden.rzb("run", "q")).stderr.contains("hmm")) | ||
| 110 | - } | ||
| 111 | - | ||
| 112 | - @Test func anEmptyThinkingBlockPrintsNothing() async throws { | ||
| 113 | - let world = try World(script: [[.thinking("\n\n"), .text("A")]]) | ||
| 114 | - try world.writeAgent(simpleAgent) | ||
| 115 | - let result = await world.rzb("run", "q") | ||
| 116 | - #expect(result.stdout == "A\n") | ||
| 117 | - #expect(!result.stderr.contains("\n\n")) | ||
| 118 | - } | ||
| 119 | -} | ||
| 120 | - | ||
| 121 | -@Suite struct ChatCommandTests { | ||
| 122 | - @Test func talksUntilEndOfInputAndHandlesCommands() async throws { | ||
| 123 | - let world = try World( | ||
| 124 | - console: ScriptedConsole(inputs: ["hello", "", "/help", "/reset", "again"])) | ||
| 125 | - try world.writeAgent(simpleAgent) | ||
| 126 | - | ||
| 127 | - let result = await world.rzb("chat") | ||
| 128 | - | ||
| 129 | - #expect(result.exitCode == 0) | ||
| 130 | - #expect(result.stdout == "echo: hello\necho: again\n") | ||
| 131 | - #expect(result.stderr.contains("helper · mlx-community/Qwen3-0.6B-4bit · fake")) | ||
| 132 | - #expect(result.stderr.contains("(new conversation)")) | ||
| 133 | - #expect(world.engine.sessionSetups.count == 2) | ||
| 134 | - } | ||
| 135 | - | ||
| 136 | - @Test func exitCommandStopsTheLoop() async throws { | ||
| 137 | - let world = try World(console: ScriptedConsole(inputs: ["/exit", "never sent"])) | ||
| 138 | - try world.writeAgent(simpleAgent) | ||
| 139 | - | ||
| 140 | - _ = await world.rzb("chat") | ||
| 141 | - | ||
| 142 | - #expect(world.engine.receivedMessages.isEmpty) | ||
| 143 | - } | ||
| 144 | -} | ||
deleted
Tests/RazorbillCoreTests/AgentTests.swift +0 -203 | deleted file mode 100644 | ||
| @@ -1,203 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -let demoConfig = AgentConfig( | |
| 6 | - name: "demo", model: .huggingFace(id: "m/x", revision: "main"), system: "Be brief.") | |
| 7 | - | |
| 8 | -/// A tool that returns its `text` argument upper-cased, or fails when asked to. | |
| 9 | -struct UpperTool: AgentTool { | |
| 10 | - let spec = ToolSpec(name: "upper", description: "Upper-case text", parameters: .map([:])) | |
| 11 | - | |
| 12 | - struct Failure: Error, CustomStringConvertible { | |
| 13 | - var description: String { "boom" } | |
| 14 | - } | |
| 15 | - | |
| 16 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | |
| 17 | - let text = arguments["text"]?.stringValue ?? "" | |
| 18 | - if text == "fail" { throw Failure() } | |
| 19 | - return ToolOutput(text.uppercased()) | |
| 20 | - } | |
| 21 | -} | |
| 22 | - | |
| 23 | -/// Collects every event of one prompt. | |
| 24 | -func events(_ agent: Agent, _ prompt: String) async throws -> [AgentEvent] { | |
| 25 | - var collected: [AgentEvent] = [] | |
| 26 | - for try await event in agent.send(prompt) { | |
| 27 | - collected.append(event) | |
| 28 | - } | |
| 29 | - return collected | |
| 30 | -} | |
| 31 | - | |
| 32 | -func call(_ text: String, id: String? = "c1") -> ToolCall { | |
| 33 | - ToolCall(id: id, name: "upper", arguments: ["text": .string(text)]) | |
| 34 | -} | |
| 35 | - | |
| 36 | -@Suite struct AgentConversation { | |
| 37 | - @Test func streamsTheAnswerAndItsStats() async throws { | |
| 38 | - let stats = GenerationStats(promptTokens: 3, generatedTokens: 2, tokensPerSecond: 10) | |
| 39 | - let engine = FakeEngine(script: [ | |
| 40 | - [.thinking("hmm"), .text("Hel"), .text("lo"), .stats(stats)] | |
| 41 | - ]) | |
| 42 | - let agent = Agent(config: demoConfig, engine: engine) | |
| 43 | - | |
| 44 | - let result = try await events(agent, "Hi") | |
| 45 | - | |
| 46 | - #expect(result == [.thinking("hmm"), .text("Hel"), .text("lo"), .stats(stats)]) | |
| 47 | - #expect(await agent.transcript == [.user("Hi"), .assistant("Hello")]) | |
| 48 | - } | |
| 49 | - | |
| 50 | - @Test func sessionIsCreatedOnceWithSystemPromptAndToolSpecs() async throws { | |
| 51 | - let engine = FakeEngine() | |
| 52 | - let agent = Agent(config: demoConfig, engine: engine, tools: [UpperTool()]) | |
| 53 | - | |
| 54 | - _ = try await events(agent, "one") | |
| 55 | - _ = try await events(agent, "two") | |
| 56 | - | |
| 57 | - #expect(engine.sessionSetups.count == 1) | |
| 58 | - #expect(engine.sessionSetups.first?.system == "Be brief.") | |
| 59 | - #expect(engine.sessionSetups.first?.tools.map(\.name) == ["upper"]) | |
| 60 | - #expect(engine.receivedMessages == [[.user("one")], [.user("two")]]) | |
| 61 | - } | |
| 62 | - | |
| 63 | - @Test func resetStartsANewSession() async throws { | |
| 64 | - let engine = FakeEngine() | |
| 65 | - let agent = Agent(config: demoConfig, engine: engine) | |
| 66 | - | |
| 67 | - _ = try await events(agent, "one") | |
| 68 | - await agent.reset() | |
| 69 | - #expect(await agent.transcript.isEmpty) | |
| 70 | - _ = try await events(agent, "two") | |
| 71 | - | |
| 72 | - #expect(engine.sessionSetups.count == 2) | |
| 73 | - } | |
| 74 | - | |
| 75 | - @Test func loadPassesTheModelAndReportsProgress() async throws { | |
| 76 | - let engine = FakeEngine() | |
| 77 | - let agent = Agent(config: demoConfig, engine: engine) | |
| 78 | - let seen = ProgressLog() | |
| 79 | - | |
| 80 | - try await agent.load { fraction in seen.add(fraction) } | |
| 81 | - | |
| 82 | - #expect(engine.loadedModels == [demoConfig.model]) | |
| 83 | - #expect(seen.values == [0.5, 1]) | |
| 84 | - #expect(agent.engineName == "fake") | |
| 85 | - } | |
| 86 | - | |
| 87 | - @Test func echoesWhenTheScriptIsExhausted() async throws { | |
| 88 | - let result = try await events(Agent(config: demoConfig, engine: FakeEngine()), "ping") | |
| 89 | - #expect(result.first == .text("echo: ping")) | |
| 90 | - } | |
| 91 | -} | |
| 92 | - | |
| 93 | -@Suite struct AgentTools { | |
| 94 | - @Test func runsToolsAndSendsTheirResultsBack() async throws { | |
| 95 | - let engine = FakeEngine(script: [ | |
| 96 | - [.text("Let me check."), .toolCall(call("abc"))], | |
| 97 | - [.text("It is ABC.")], | |
| 98 | - ]) | |
| 99 | - let agent = Agent(config: demoConfig, engine: engine, tools: [UpperTool()]) | |
| 100 | - | |
| 101 | - let result = try await events(agent, "upper abc") | |
| 102 | - | |
| 103 | - #expect( | |
| 104 | - result == [ | |
| 105 | - .text("Let me check."), .toolCall(call("abc")), | |
| 106 | - .toolResult(name: "upper", output: ToolOutput("ABC")), .text("It is ABC."), | |
| 107 | - ]) | |
| 108 | - #expect(engine.receivedMessages.last == [.tool("ABC", name: "upper", callID: "c1")]) | |
| 109 | - #expect(await agent.transcript.count == 4) | |
| 110 | - } | |
| 111 | - | |
| 112 | - @Test func unknownToolsAndFailuresAreReportedToTheModel() async throws { | |
| 113 | - let unknown = ToolCall(name: "nope") | |
| 114 | - let engine = FakeEngine(script: [ | |
| 115 | - [.toolCall(unknown), .toolCall(call("fail"))], [.text("ok")], | |
| 116 | - ]) | |
| 117 | - let agent = Agent(config: demoConfig, engine: engine, tools: [UpperTool()]) | |
| 118 | - | |
| 119 | - let results = try await events(agent, "go").compactMap { event -> ToolOutput? in | |
| 120 | - if case .toolResult(_, let output) = event { return output } | |
| 121 | - return nil | |
| 122 | - } | |
| 123 | - | |
| 124 | - #expect( | |
| 125 | - results == [ | |
| 126 | - ToolOutput("unknown tool nope (available: upper)", isError: true), | |
| 127 | - ToolOutput("error: boom", isError: true), | |
| 128 | - ]) | |
| 129 | - #expect(engine.receivedMessages.last?.count == 2) | |
| 130 | - } | |
| 131 | - | |
| 132 | - @Test func stopsAfterTooManyToolRounds() async throws { | |
| 133 | - let looping = Array(repeating: [EngineEvent.toolCall(call("x"))], count: 5) | |
| 134 | - let agent = Agent( | |
| 135 | - config: demoConfig, engine: FakeEngine(script: looping), tools: [UpperTool()], | |
| 136 | - maxToolRounds: 3) | |
| 137 | - | |
| 138 | - await #expect(throws: AgentError.tooManyToolRounds(3)) { | |
| 139 | - _ = try await events(agent, "loop") | |
| 140 | - } | |
| 141 | - } | |
| 142 | - | |
| 143 | - @Test func toolsReceiveTheContextOfTheFrontEnd() async throws { | |
| 144 | - struct AskingTool: AgentTool { | |
| 145 | - let spec = ToolSpec(name: "ask", description: "", parameters: .map([:])) | |
| 146 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | |
| 147 | - let accepted = await context.confirm(.init(toolName: "ask", summary: "do it?")) | |
| 148 | - return ToolOutput(accepted ? "accepted" : "refused") | |
| 149 | - } | |
| 150 | - } | |
| 151 | - let engine = FakeEngine(script: [[.toolCall(ToolCall(name: "ask"))], [.text("done")]]) | |
| 152 | - let context = ToolContext(isInteractive: true) { request in request.summary == "do it?" } | |
| 153 | - let agent = Agent( | |
| 154 | - config: demoConfig, engine: engine, tools: [AskingTool()], toolContext: context) | |
| 155 | - | |
| 156 | - let result = try await events(agent, "go") | |
| 157 | - | |
| 158 | - #expect(result.contains(.toolResult(name: "ask", output: ToolOutput("accepted")))) | |
| 159 | - } | |
| 160 | -} | |
| 161 | - | |
| 162 | -/// A tool that waits 30 s and reports when it is cancelled instead. | |
| 163 | -struct SlowTool: AgentTool { | |
| 164 | - let spec = ToolSpec(name: "slow", description: "", parameters: .map([:])) | |
| 165 | - let cancelled: AsyncStream<Void>.Continuation | |
| 166 | - | |
| 167 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | |
| 168 | - do { | |
| 169 | - try await Task.sleep(for: .seconds(30)) | |
| 170 | - } catch { | |
| 171 | - cancelled.yield() | |
| 172 | - } | |
| 173 | - return ToolOutput("done") | |
| 174 | - } | |
| 175 | -} | |
| 176 | - | |
| 177 | -@Test(.timeLimit(.minutes(1))) | |
| 178 | -func stoppingToReadCancelsTheRunningTool() async throws { | |
| 179 | - let (cancellations, cancelled) = AsyncStream<Void>.makeStream() | |
| 180 | - let engine = FakeEngine(script: [[.toolCall(ToolCall(name: "slow"))]]) | |
| 181 | - let agent = Agent(config: demoConfig, engine: engine, tools: [SlowTool(cancelled: cancelled)]) | |
| 182 | - | |
| 183 | - for try await event in agent.send("go") { | |
| 184 | - if case .toolCall = event { break } // the consumer stops reading | |
| 185 | - } | |
| 186 | - | |
| 187 | - var iterator = cancellations.makeAsyncIterator() | |
| 188 | - #expect(await iterator.next() != nil) // reached long before the 30 s sleep ends | |
| 189 | -} | |
| 190 | - | |
| 191 | -/// Thread-safe list of progress values. | |
| 192 | -final class ProgressLog: @unchecked Sendable { | |
| 193 | - private var stored: [Double] = [] | |
| 194 | - private let lock = NSLockShim() | |
| 195 | - func add(_ value: Double) { lock.run { stored.append(value) } } | |
| 196 | - var values: [Double] { lock.run { stored } } | |
| 197 | -} | |
| 198 | - | |
| 199 | -/// NSLock wrapper usable from synchronous closures. | |
| 200 | -struct NSLockShim { | |
| 201 | - private let lock = NSLock() | |
| 202 | - func run<T>(_ body: () -> T) -> T { lock.withLock(body) } | |
| 203 | -} | |
| deleted file mode 100644 | |||
| @@ -1,203 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -let demoConfig = AgentConfig( | ||
| 6 | - name: "demo", model: .huggingFace(id: "m/x", revision: "main"), system: "Be brief.") | ||
| 7 | - | ||
| 8 | -/// A tool that returns its `text` argument upper-cased, or fails when asked to. | ||
| 9 | -struct UpperTool: AgentTool { | ||
| 10 | - let spec = ToolSpec(name: "upper", description: "Upper-case text", parameters: .map([:])) | ||
| 11 | - | ||
| 12 | - struct Failure: Error, CustomStringConvertible { | ||
| 13 | - var description: String { "boom" } | ||
| 14 | - } | ||
| 15 | - | ||
| 16 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | ||
| 17 | - let text = arguments["text"]?.stringValue ?? "" | ||
| 18 | - if text == "fail" { throw Failure() } | ||
| 19 | - return ToolOutput(text.uppercased()) | ||
| 20 | - } | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -/// Collects every event of one prompt. | ||
| 24 | -func events(_ agent: Agent, _ prompt: String) async throws -> [AgentEvent] { | ||
| 25 | - var collected: [AgentEvent] = [] | ||
| 26 | - for try await event in agent.send(prompt) { | ||
| 27 | - collected.append(event) | ||
| 28 | - } | ||
| 29 | - return collected | ||
| 30 | -} | ||
| 31 | - | ||
| 32 | -func call(_ text: String, id: String? = "c1") -> ToolCall { | ||
| 33 | - ToolCall(id: id, name: "upper", arguments: ["text": .string(text)]) | ||
| 34 | -} | ||
| 35 | - | ||
| 36 | -@Suite struct AgentConversation { | ||
| 37 | - @Test func streamsTheAnswerAndItsStats() async throws { | ||
| 38 | - let stats = GenerationStats(promptTokens: 3, generatedTokens: 2, tokensPerSecond: 10) | ||
| 39 | - let engine = FakeEngine(script: [ | ||
| 40 | - [.thinking("hmm"), .text("Hel"), .text("lo"), .stats(stats)] | ||
| 41 | - ]) | ||
| 42 | - let agent = Agent(config: demoConfig, engine: engine) | ||
| 43 | - | ||
| 44 | - let result = try await events(agent, "Hi") | ||
| 45 | - | ||
| 46 | - #expect(result == [.thinking("hmm"), .text("Hel"), .text("lo"), .stats(stats)]) | ||
| 47 | - #expect(await agent.transcript == [.user("Hi"), .assistant("Hello")]) | ||
| 48 | - } | ||
| 49 | - | ||
| 50 | - @Test func sessionIsCreatedOnceWithSystemPromptAndToolSpecs() async throws { | ||
| 51 | - let engine = FakeEngine() | ||
| 52 | - let agent = Agent(config: demoConfig, engine: engine, tools: [UpperTool()]) | ||
| 53 | - | ||
| 54 | - _ = try await events(agent, "one") | ||
| 55 | - _ = try await events(agent, "two") | ||
| 56 | - | ||
| 57 | - #expect(engine.sessionSetups.count == 1) | ||
| 58 | - #expect(engine.sessionSetups.first?.system == "Be brief.") | ||
| 59 | - #expect(engine.sessionSetups.first?.tools.map(\.name) == ["upper"]) | ||
| 60 | - #expect(engine.receivedMessages == [[.user("one")], [.user("two")]]) | ||
| 61 | - } | ||
| 62 | - | ||
| 63 | - @Test func resetStartsANewSession() async throws { | ||
| 64 | - let engine = FakeEngine() | ||
| 65 | - let agent = Agent(config: demoConfig, engine: engine) | ||
| 66 | - | ||
| 67 | - _ = try await events(agent, "one") | ||
| 68 | - await agent.reset() | ||
| 69 | - #expect(await agent.transcript.isEmpty) | ||
| 70 | - _ = try await events(agent, "two") | ||
| 71 | - | ||
| 72 | - #expect(engine.sessionSetups.count == 2) | ||
| 73 | - } | ||
| 74 | - | ||
| 75 | - @Test func loadPassesTheModelAndReportsProgress() async throws { | ||
| 76 | - let engine = FakeEngine() | ||
| 77 | - let agent = Agent(config: demoConfig, engine: engine) | ||
| 78 | - let seen = ProgressLog() | ||
| 79 | - | ||
| 80 | - try await agent.load { fraction in seen.add(fraction) } | ||
| 81 | - | ||
| 82 | - #expect(engine.loadedModels == [demoConfig.model]) | ||
| 83 | - #expect(seen.values == [0.5, 1]) | ||
| 84 | - #expect(agent.engineName == "fake") | ||
| 85 | - } | ||
| 86 | - | ||
| 87 | - @Test func echoesWhenTheScriptIsExhausted() async throws { | ||
| 88 | - let result = try await events(Agent(config: demoConfig, engine: FakeEngine()), "ping") | ||
| 89 | - #expect(result.first == .text("echo: ping")) | ||
| 90 | - } | ||
| 91 | -} | ||
| 92 | - | ||
| 93 | -@Suite struct AgentTools { | ||
| 94 | - @Test func runsToolsAndSendsTheirResultsBack() async throws { | ||
| 95 | - let engine = FakeEngine(script: [ | ||
| 96 | - [.text("Let me check."), .toolCall(call("abc"))], | ||
| 97 | - [.text("It is ABC.")], | ||
| 98 | - ]) | ||
| 99 | - let agent = Agent(config: demoConfig, engine: engine, tools: [UpperTool()]) | ||
| 100 | - | ||
| 101 | - let result = try await events(agent, "upper abc") | ||
| 102 | - | ||
| 103 | - #expect( | ||
| 104 | - result == [ | ||
| 105 | - .text("Let me check."), .toolCall(call("abc")), | ||
| 106 | - .toolResult(name: "upper", output: ToolOutput("ABC")), .text("It is ABC."), | ||
| 107 | - ]) | ||
| 108 | - #expect(engine.receivedMessages.last == [.tool("ABC", name: "upper", callID: "c1")]) | ||
| 109 | - #expect(await agent.transcript.count == 4) | ||
| 110 | - } | ||
| 111 | - | ||
| 112 | - @Test func unknownToolsAndFailuresAreReportedToTheModel() async throws { | ||
| 113 | - let unknown = ToolCall(name: "nope") | ||
| 114 | - let engine = FakeEngine(script: [ | ||
| 115 | - [.toolCall(unknown), .toolCall(call("fail"))], [.text("ok")], | ||
| 116 | - ]) | ||
| 117 | - let agent = Agent(config: demoConfig, engine: engine, tools: [UpperTool()]) | ||
| 118 | - | ||
| 119 | - let results = try await events(agent, "go").compactMap { event -> ToolOutput? in | ||
| 120 | - if case .toolResult(_, let output) = event { return output } | ||
| 121 | - return nil | ||
| 122 | - } | ||
| 123 | - | ||
| 124 | - #expect( | ||
| 125 | - results == [ | ||
| 126 | - ToolOutput("unknown tool nope (available: upper)", isError: true), | ||
| 127 | - ToolOutput("error: boom", isError: true), | ||
| 128 | - ]) | ||
| 129 | - #expect(engine.receivedMessages.last?.count == 2) | ||
| 130 | - } | ||
| 131 | - | ||
| 132 | - @Test func stopsAfterTooManyToolRounds() async throws { | ||
| 133 | - let looping = Array(repeating: [EngineEvent.toolCall(call("x"))], count: 5) | ||
| 134 | - let agent = Agent( | ||
| 135 | - config: demoConfig, engine: FakeEngine(script: looping), tools: [UpperTool()], | ||
| 136 | - maxToolRounds: 3) | ||
| 137 | - | ||
| 138 | - await #expect(throws: AgentError.tooManyToolRounds(3)) { | ||
| 139 | - _ = try await events(agent, "loop") | ||
| 140 | - } | ||
| 141 | - } | ||
| 142 | - | ||
| 143 | - @Test func toolsReceiveTheContextOfTheFrontEnd() async throws { | ||
| 144 | - struct AskingTool: AgentTool { | ||
| 145 | - let spec = ToolSpec(name: "ask", description: "", parameters: .map([:])) | ||
| 146 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | ||
| 147 | - let accepted = await context.confirm(.init(toolName: "ask", summary: "do it?")) | ||
| 148 | - return ToolOutput(accepted ? "accepted" : "refused") | ||
| 149 | - } | ||
| 150 | - } | ||
| 151 | - let engine = FakeEngine(script: [[.toolCall(ToolCall(name: "ask"))], [.text("done")]]) | ||
| 152 | - let context = ToolContext(isInteractive: true) { request in request.summary == "do it?" } | ||
| 153 | - let agent = Agent( | ||
| 154 | - config: demoConfig, engine: engine, tools: [AskingTool()], toolContext: context) | ||
| 155 | - | ||
| 156 | - let result = try await events(agent, "go") | ||
| 157 | - | ||
| 158 | - #expect(result.contains(.toolResult(name: "ask", output: ToolOutput("accepted")))) | ||
| 159 | - } | ||
| 160 | -} | ||
| 161 | - | ||
| 162 | -/// A tool that waits 30 s and reports when it is cancelled instead. | ||
| 163 | -struct SlowTool: AgentTool { | ||
| 164 | - let spec = ToolSpec(name: "slow", description: "", parameters: .map([:])) | ||
| 165 | - let cancelled: AsyncStream<Void>.Continuation | ||
| 166 | - | ||
| 167 | - func call(_ arguments: ToolArguments, context: ToolContext) async throws -> ToolOutput { | ||
| 168 | - do { | ||
| 169 | - try await Task.sleep(for: .seconds(30)) | ||
| 170 | - } catch { | ||
| 171 | - cancelled.yield() | ||
| 172 | - } | ||
| 173 | - return ToolOutput("done") | ||
| 174 | - } | ||
| 175 | -} | ||
| 176 | - | ||
| 177 | -@Test(.timeLimit(.minutes(1))) | ||
| 178 | -func stoppingToReadCancelsTheRunningTool() async throws { | ||
| 179 | - let (cancellations, cancelled) = AsyncStream<Void>.makeStream() | ||
| 180 | - let engine = FakeEngine(script: [[.toolCall(ToolCall(name: "slow"))]]) | ||
| 181 | - let agent = Agent(config: demoConfig, engine: engine, tools: [SlowTool(cancelled: cancelled)]) | ||
| 182 | - | ||
| 183 | - for try await event in agent.send("go") { | ||
| 184 | - if case .toolCall = event { break } // the consumer stops reading | ||
| 185 | - } | ||
| 186 | - | ||
| 187 | - var iterator = cancellations.makeAsyncIterator() | ||
| 188 | - #expect(await iterator.next() != nil) // reached long before the 30 s sleep ends | ||
| 189 | -} | ||
| 190 | - | ||
| 191 | -/// Thread-safe list of progress values. | ||
| 192 | -final class ProgressLog: @unchecked Sendable { | ||
| 193 | - private var stored: [Double] = [] | ||
| 194 | - private let lock = NSLockShim() | ||
| 195 | - func add(_ value: Double) { lock.run { stored.append(value) } } | ||
| 196 | - var values: [Double] { lock.run { stored } } | ||
| 197 | -} | ||
| 198 | - | ||
| 199 | -/// NSLock wrapper usable from synchronous closures. | ||
| 200 | -struct NSLockShim { | ||
| 201 | - private let lock = NSLock() | ||
| 202 | - func run<T>(_ body: () -> T) -> T { lock.withLock(body) } | ||
| 203 | -} | ||
deleted
Tests/RazorbillCoreTests/BashToolTests.swift +0 -241 | deleted file mode 100644 | ||
| @@ -1,241 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -/// A fresh temporary directory per test. | |
| 6 | -func temporaryDirectory() throws -> String { | |
| 7 | - let url = FileManager.default.temporaryDirectory.appendingPathComponent( | |
| 8 | - "rzb-\(UUID().uuidString)") | |
| 9 | - try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | |
| 10 | - return url.path | |
| 11 | -} | |
| 12 | - | |
| 13 | -/// Answers every confirmation with `answer` and remembers what was asked. | |
| 14 | -final class ConfirmationLog: @unchecked Sendable { | |
| 15 | - private let lock = NSLock() | |
| 16 | - private var asked: [String] = [] | |
| 17 | - var summaries: [String] { lock.withLock { asked } } | |
| 18 | - | |
| 19 | - func context(answer: Bool) -> ToolContext { | |
| 20 | - ToolContext(isInteractive: true) { request in | |
| 21 | - self.lock.withLock { self.asked.append(request.summary) } | |
| 22 | - return answer | |
| 23 | - } | |
| 24 | - } | |
| 25 | -} | |
| 26 | - | |
| 27 | -func run( | |
| 28 | - _ tool: BashTool, _ command: String, context: ToolContext = .nonInteractive | |
| 29 | -) async throws -> ToolOutput { | |
| 30 | - try await tool.call(["command": .string(command)], context: context) | |
| 31 | -} | |
| 32 | - | |
| 33 | -@Suite struct BashToolRuns { | |
| 34 | - @Test func returnsExitCodeAndBothOutputs() async throws { | |
| 35 | - let tool = BashTool(confirm: false, workingDirectory: try temporaryDirectory()) | |
| 36 | - | |
| 37 | - let output = try await run(tool, "echo out; echo err >&2; exit 3") | |
| 38 | - | |
| 39 | - #expect(output.content == "exit code: 3\nstdout:\nout\n\nstderr:\nerr\n") | |
| 40 | - #expect(output.isError) | |
| 41 | - } | |
| 42 | - | |
| 43 | - @Test func runsInTheWorkingDirectory() async throws { | |
| 44 | - let directory = try temporaryDirectory() | |
| 45 | - let output = try await run(BashTool(confirm: false, workingDirectory: directory), "pwd -P") | |
| 46 | - | |
| 47 | - // realpath, not resolvingSymlinksInPath: on macOS the latter keeps /var instead of /private/var. | |
| 48 | - let expected = String(cString: realpath(directory, nil)) | |
| 49 | - #expect(output.content == "exit code: 0\nstdout:\n\(expected)\n") | |
| 50 | - #expect(!output.isError) | |
| 51 | - } | |
| 52 | - | |
| 53 | - @Test func timeoutKillsTheCommandAndWhatItStarted() async throws { | |
| 54 | - let tool = BashTool( | |
| 55 | - confirm: false, workingDirectory: try temporaryDirectory(), timeout: .milliseconds(300)) | |
| 56 | - let start = ContinuousClock.now | |
| 57 | - | |
| 58 | - let output = try await run(tool, "sleep 20 & sleep 20; echo never") | |
| 59 | - | |
| 60 | - #expect(ContinuousClock.now - start < .seconds(10)) | |
| 61 | - #expect( | |
| 62 | - output.content.hasPrefix("timed out after 0.3s: the command was killed\nexit code: 137") | |
| 63 | - ) | |
| 64 | - #expect(output.isError) | |
| 65 | - } | |
| 66 | - | |
| 67 | - @Test func longOutputIsTruncated() async throws { | |
| 68 | - let tool = BashTool( | |
| 69 | - confirm: false, workingDirectory: try temporaryDirectory(), maxOutputBytes: 10) | |
| 70 | - | |
| 71 | - let output = try await run(tool, "printf '%0100d' 0") | |
| 72 | - | |
| 73 | - #expect( | |
| 74 | - output.content == "exit code: 0\nstdout:\n0000000000\n[output truncated: 90 more bytes]" | |
| 75 | - ) | |
| 76 | - } | |
| 77 | - | |
| 78 | - @Test func missingCommandIsRefused() async throws { | |
| 79 | - let tool = BashTool(confirm: false, workingDirectory: "/") | |
| 80 | - let output = try await tool.call([:], context: .nonInteractive) | |
| 81 | - #expect( | |
| 82 | - output == ToolOutput("refused: the `command` argument (text) is missing", isError: true) | |
| 83 | - ) | |
| 84 | - } | |
| 85 | -} | |
| 86 | - | |
| 87 | -@Suite struct BashToolSafety { | |
| 88 | - @Test func denyPatternsWinOverAllowPatterns() async throws { | |
| 89 | - let tool = BashTool( | |
| 90 | - confirm: false, workingDirectory: "/", allow: ["rm *"], deny: ["rm -rf*"]) | |
| 91 | - | |
| 92 | - let output = try await run(tool, "rm -rf /tmp/x") | |
| 93 | - | |
| 94 | - #expect( | |
| 95 | - output | |
| 96 | - == ToolOutput( | |
| 97 | - "refused: the command matches the deny pattern `rm -rf*`", isError: true)) | |
| 98 | - } | |
| 99 | - | |
| 100 | - @Test func commandsOutsideTheAllowListAreRefused() async throws { | |
| 101 | - let tool = BashTool(confirm: false, workingDirectory: "/", allow: ["ls*"]) | |
| 102 | - #expect( | |
| 103 | - try await run(tool, "whoami").content | |
| 104 | - == "refused: the command matches none of the allow patterns") | |
| 105 | - #expect(try await run(tool, "ls -d /").content == "exit code: 0\nstdout:\n/\n") | |
| 106 | - } | |
| 107 | - | |
| 108 | - @Test func withoutATerminalConfirmationIsImpossible() async throws { | |
| 109 | - let output = try await run(BashTool(workingDirectory: "/"), "echo hi") | |
| 110 | - #expect(output.content.hasPrefix("refused: no terminal to ask the user for confirmation")) | |
| 111 | - } | |
| 112 | - | |
| 113 | - @Test func theUserIsAskedBeforeEachCommand() async throws { | |
| 114 | - let directory = try temporaryDirectory() | |
| 115 | - let tool = BashTool(workingDirectory: directory) | |
| 116 | - let accept = ConfirmationLog() | |
| 117 | - let decline = ConfirmationLog() | |
| 118 | - | |
| 119 | - let accepted = try await run(tool, "echo yes", context: accept.context(answer: true)) | |
| 120 | - let declined = try await run(tool, "echo no", context: decline.context(answer: false)) | |
| 121 | - | |
| 122 | - #expect(accepted.content == "exit code: 0\nstdout:\nyes\n") | |
| 123 | - #expect(accept.summaries == ["echo yes (in \(directory))"]) | |
| 124 | - #expect(declined == ToolOutput("refused: the user declined to run it", isError: true)) | |
| 125 | - } | |
| 126 | -} | |
| 127 | - | |
| 128 | -@Suite struct ToolRegistryBuildsTools { | |
| 129 | - let environment = ToolEnvironment(baseDirectory: "/work") | |
| 130 | - | |
| 131 | - func config(tools: [String: ConfigValue]) -> AgentConfig { | |
| 132 | - AgentConfig(name: "a", model: .huggingFace(id: "m/x", revision: "main"), tools: tools) | |
| 133 | - } | |
| 134 | - | |
| 135 | - @Test func bashIsBuiltInWithSafeDefaults() throws { | |
| 136 | - let tools = try ToolRegistry.builtIn.makeTools( | |
| 137 | - for: config(tools: ["bash": .map([:])]), environment: environment) | |
| 138 | - let bash = try #require(tools.first as? BashTool) | |
| 139 | - | |
| 140 | - #expect(ToolRegistry.builtIn.names == ["bash"]) | |
| 141 | - #expect(bash.confirm) | |
| 142 | - #expect(bash.workingDirectory == "/work") | |
| 143 | - #expect(bash.timeout == .seconds(30)) | |
| 144 | - #expect(bash.maxOutputBytes == 16_384) | |
| 145 | - } | |
| 146 | - | |
| 147 | - @Test func optionsAreRead() throws { | |
| 148 | - let options: ConfigValue = .map([ | |
| 149 | - "confirm": .bool(false), "workdir": .string("sub"), "timeout": .string("2m"), | |
| 150 | - "max_output": .string("1MB"), "allow": .list([.string("ls*")]), | |
| 151 | - "deny": .list([.string("sudo *")]), | |
| 152 | - ]) | |
| 153 | - let tools = try ToolRegistry.builtIn.makeTools( | |
| 154 | - for: config(tools: ["bash": options]), environment: environment) | |
| 155 | - let bash = try #require(tools.first as? BashTool) | |
| 156 | - | |
| 157 | - #expect(!bash.confirm) | |
| 158 | - #expect(bash.workingDirectory == "/work/sub") | |
| 159 | - #expect(bash.timeout == .seconds(120)) | |
| 160 | - #expect(bash.maxOutputBytes == 1_048_576) | |
| 161 | - #expect(bash.allow == ["ls*"]) | |
| 162 | - #expect(bash.deny == ["sudo *"]) | |
| 163 | - } | |
| 164 | - | |
| 165 | - @Test func unknownToolsAndBadOptionsAreConfigErrors() { | |
| 166 | - let bad = config(tools: [ | |
| 167 | - "web": .map([:]), "bash": .map(["timeout": .string("soon"), "confrim": .bool(true)]), | |
| 168 | - ]) | |
| 169 | - #expect { | |
| 170 | - try ToolRegistry.builtIn.makeTools(for: bad, environment: environment) | |
| 171 | - } throws: { error in | |
| 172 | - let keys = (error as? ConfigError)?.issues.map(\.keyPath) | |
| 173 | - return keys == ["tools.bash.confrim", "tools.web"] | |
| 174 | - } | |
| 175 | - } | |
| 176 | - | |
| 177 | - @Test func customToolsCanBeRegistered() throws { | |
| 178 | - var registry = ToolRegistry.builtIn | |
| 179 | - registry.register("upper") { _, _ in UpperTool() } | |
| 180 | - | |
| 181 | - let tools = try registry.makeTools( | |
| 182 | - for: config(tools: ["upper": .map([:])]), environment: environment) | |
| 183 | - | |
| 184 | - #expect(tools.map(\.spec.name) == ["upper"]) | |
| 185 | - #expect(registry.names == ["bash", "upper"]) | |
| 186 | - } | |
| 187 | -} | |
| 188 | - | |
| 189 | -@Suite struct OptionValues { | |
| 190 | - @Test func durationsAndSizesAcceptNumbersAndUnits() throws { | |
| 191 | - let reader = OptionReader( | |
| 192 | - .map([ | |
| 193 | - "a": .int(2), "b": .string("500ms"), "c": .string("1h"), "d": .double(0.25), | |
| 194 | - "size": .string("16kb"), "bytes": .int(10), | |
| 195 | - ])) | |
| 196 | - #expect(try reader.duration("a", default: .zero) == .seconds(2)) | |
| 197 | - #expect(try reader.duration("b", default: .zero) == .milliseconds(500)) | |
| 198 | - #expect(try reader.duration("c", default: .zero) == .seconds(3600)) | |
| 199 | - #expect(try reader.duration("d", default: .zero) == .milliseconds(250)) | |
| 200 | - #expect(try reader.duration("missing", default: .seconds(9)) == .seconds(9)) | |
| 201 | - #expect(try reader.byteCount("size", default: 0) == 16_384) | |
| 202 | - #expect(try reader.byteCount("bytes", default: 0) == 10) | |
| 203 | - } | |
| 204 | - | |
| 205 | - @Test func invalidValuesAreRejected() { | |
| 206 | - let reader = OptionReader( | |
| 207 | - .map(["t": .string("-1s"), "s": .string("big"), "b": .string("yes")])) | |
| 208 | - #expect(throws: ToolOptionError.self) { try reader.duration("t", default: .zero) } | |
| 209 | - #expect(throws: ToolOptionError.self) { try reader.byteCount("s", default: 0) } | |
| 210 | - #expect(throws: ToolOptionError.self) { try reader.bool("b", default: true) } | |
| 211 | - } | |
| 212 | - | |
| 213 | - @Test func commandPatternsUseShellWildcards() { | |
| 214 | - #expect(CommandPattern.matches("git status", pattern: "git *")) | |
| 215 | - #expect(CommandPattern.matches("ls", pattern: "l?")) | |
| 216 | - #expect(CommandPattern.matches("anything", pattern: "*")) | |
| 217 | - #expect(!CommandPattern.matches("git", pattern: "git *")) | |
| 218 | - #expect(!CommandPattern.matches("sudo ls", pattern: "ls*")) | |
| 219 | - #expect(CommandPattern.firstMatch("rm -rf /", in: ["ls*", "rm *"]) == "rm *") | |
| 220 | - } | |
| 221 | -} | |
| 222 | - | |
| 223 | -@Suite struct EngineRegistryChoosesEngines { | |
| 224 | - @Test func firstRegisteredEngineIsTheDefault() throws { | |
| 225 | - var engines = EngineRegistry() | |
| 226 | - engines.register("fake") { FakeEngine() } | |
| 227 | - engines.register("other") { FakeEngine() } | |
| 228 | - | |
| 229 | - #expect(engines.defaultName == "fake") | |
| 230 | - #expect(try engines.make().name == "fake") | |
| 231 | - #expect(engines.names == ["fake", "other"]) | |
| 232 | - } | |
| 233 | - | |
| 234 | - @Test func unknownEngineListsTheAvailableOnes() { | |
| 235 | - var engines = EngineRegistry() | |
| 236 | - engines.register("fake") { FakeEngine() } | |
| 237 | - #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { | |
| 238 | - try engines.make("mlx") | |
| 239 | - } | |
| 240 | - } | |
| 241 | -} | |
| deleted file mode 100644 | |||
| @@ -1,241 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -/// A fresh temporary directory per test. | ||
| 6 | -func temporaryDirectory() throws -> String { | ||
| 7 | - let url = FileManager.default.temporaryDirectory.appendingPathComponent( | ||
| 8 | - "rzb-\(UUID().uuidString)") | ||
| 9 | - try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | ||
| 10 | - return url.path | ||
| 11 | -} | ||
| 12 | - | ||
| 13 | -/// Answers every confirmation with `answer` and remembers what was asked. | ||
| 14 | -final class ConfirmationLog: @unchecked Sendable { | ||
| 15 | - private let lock = NSLock() | ||
| 16 | - private var asked: [String] = [] | ||
| 17 | - var summaries: [String] { lock.withLock { asked } } | ||
| 18 | - | ||
| 19 | - func context(answer: Bool) -> ToolContext { | ||
| 20 | - ToolContext(isInteractive: true) { request in | ||
| 21 | - self.lock.withLock { self.asked.append(request.summary) } | ||
| 22 | - return answer | ||
| 23 | - } | ||
| 24 | - } | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -func run( | ||
| 28 | - _ tool: BashTool, _ command: String, context: ToolContext = .nonInteractive | ||
| 29 | -) async throws -> ToolOutput { | ||
| 30 | - try await tool.call(["command": .string(command)], context: context) | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -@Suite struct BashToolRuns { | ||
| 34 | - @Test func returnsExitCodeAndBothOutputs() async throws { | ||
| 35 | - let tool = BashTool(confirm: false, workingDirectory: try temporaryDirectory()) | ||
| 36 | - | ||
| 37 | - let output = try await run(tool, "echo out; echo err >&2; exit 3") | ||
| 38 | - | ||
| 39 | - #expect(output.content == "exit code: 3\nstdout:\nout\n\nstderr:\nerr\n") | ||
| 40 | - #expect(output.isError) | ||
| 41 | - } | ||
| 42 | - | ||
| 43 | - @Test func runsInTheWorkingDirectory() async throws { | ||
| 44 | - let directory = try temporaryDirectory() | ||
| 45 | - let output = try await run(BashTool(confirm: false, workingDirectory: directory), "pwd -P") | ||
| 46 | - | ||
| 47 | - // realpath, not resolvingSymlinksInPath: on macOS the latter keeps /var instead of /private/var. | ||
| 48 | - let expected = String(cString: realpath(directory, nil)) | ||
| 49 | - #expect(output.content == "exit code: 0\nstdout:\n\(expected)\n") | ||
| 50 | - #expect(!output.isError) | ||
| 51 | - } | ||
| 52 | - | ||
| 53 | - @Test func timeoutKillsTheCommandAndWhatItStarted() async throws { | ||
| 54 | - let tool = BashTool( | ||
| 55 | - confirm: false, workingDirectory: try temporaryDirectory(), timeout: .milliseconds(300)) | ||
| 56 | - let start = ContinuousClock.now | ||
| 57 | - | ||
| 58 | - let output = try await run(tool, "sleep 20 & sleep 20; echo never") | ||
| 59 | - | ||
| 60 | - #expect(ContinuousClock.now - start < .seconds(10)) | ||
| 61 | - #expect( | ||
| 62 | - output.content.hasPrefix("timed out after 0.3s: the command was killed\nexit code: 137") | ||
| 63 | - ) | ||
| 64 | - #expect(output.isError) | ||
| 65 | - } | ||
| 66 | - | ||
| 67 | - @Test func longOutputIsTruncated() async throws { | ||
| 68 | - let tool = BashTool( | ||
| 69 | - confirm: false, workingDirectory: try temporaryDirectory(), maxOutputBytes: 10) | ||
| 70 | - | ||
| 71 | - let output = try await run(tool, "printf '%0100d' 0") | ||
| 72 | - | ||
| 73 | - #expect( | ||
| 74 | - output.content == "exit code: 0\nstdout:\n0000000000\n[output truncated: 90 more bytes]" | ||
| 75 | - ) | ||
| 76 | - } | ||
| 77 | - | ||
| 78 | - @Test func missingCommandIsRefused() async throws { | ||
| 79 | - let tool = BashTool(confirm: false, workingDirectory: "/") | ||
| 80 | - let output = try await tool.call([:], context: .nonInteractive) | ||
| 81 | - #expect( | ||
| 82 | - output == ToolOutput("refused: the `command` argument (text) is missing", isError: true) | ||
| 83 | - ) | ||
| 84 | - } | ||
| 85 | -} | ||
| 86 | - | ||
| 87 | -@Suite struct BashToolSafety { | ||
| 88 | - @Test func denyPatternsWinOverAllowPatterns() async throws { | ||
| 89 | - let tool = BashTool( | ||
| 90 | - confirm: false, workingDirectory: "/", allow: ["rm *"], deny: ["rm -rf*"]) | ||
| 91 | - | ||
| 92 | - let output = try await run(tool, "rm -rf /tmp/x") | ||
| 93 | - | ||
| 94 | - #expect( | ||
| 95 | - output | ||
| 96 | - == ToolOutput( | ||
| 97 | - "refused: the command matches the deny pattern `rm -rf*`", isError: true)) | ||
| 98 | - } | ||
| 99 | - | ||
| 100 | - @Test func commandsOutsideTheAllowListAreRefused() async throws { | ||
| 101 | - let tool = BashTool(confirm: false, workingDirectory: "/", allow: ["ls*"]) | ||
| 102 | - #expect( | ||
| 103 | - try await run(tool, "whoami").content | ||
| 104 | - == "refused: the command matches none of the allow patterns") | ||
| 105 | - #expect(try await run(tool, "ls -d /").content == "exit code: 0\nstdout:\n/\n") | ||
| 106 | - } | ||
| 107 | - | ||
| 108 | - @Test func withoutATerminalConfirmationIsImpossible() async throws { | ||
| 109 | - let output = try await run(BashTool(workingDirectory: "/"), "echo hi") | ||
| 110 | - #expect(output.content.hasPrefix("refused: no terminal to ask the user for confirmation")) | ||
| 111 | - } | ||
| 112 | - | ||
| 113 | - @Test func theUserIsAskedBeforeEachCommand() async throws { | ||
| 114 | - let directory = try temporaryDirectory() | ||
| 115 | - let tool = BashTool(workingDirectory: directory) | ||
| 116 | - let accept = ConfirmationLog() | ||
| 117 | - let decline = ConfirmationLog() | ||
| 118 | - | ||
| 119 | - let accepted = try await run(tool, "echo yes", context: accept.context(answer: true)) | ||
| 120 | - let declined = try await run(tool, "echo no", context: decline.context(answer: false)) | ||
| 121 | - | ||
| 122 | - #expect(accepted.content == "exit code: 0\nstdout:\nyes\n") | ||
| 123 | - #expect(accept.summaries == ["echo yes (in \(directory))"]) | ||
| 124 | - #expect(declined == ToolOutput("refused: the user declined to run it", isError: true)) | ||
| 125 | - } | ||
| 126 | -} | ||
| 127 | - | ||
| 128 | -@Suite struct ToolRegistryBuildsTools { | ||
| 129 | - let environment = ToolEnvironment(baseDirectory: "/work") | ||
| 130 | - | ||
| 131 | - func config(tools: [String: ConfigValue]) -> AgentConfig { | ||
| 132 | - AgentConfig(name: "a", model: .huggingFace(id: "m/x", revision: "main"), tools: tools) | ||
| 133 | - } | ||
| 134 | - | ||
| 135 | - @Test func bashIsBuiltInWithSafeDefaults() throws { | ||
| 136 | - let tools = try ToolRegistry.builtIn.makeTools( | ||
| 137 | - for: config(tools: ["bash": .map([:])]), environment: environment) | ||
| 138 | - let bash = try #require(tools.first as? BashTool) | ||
| 139 | - | ||
| 140 | - #expect(ToolRegistry.builtIn.names == ["bash"]) | ||
| 141 | - #expect(bash.confirm) | ||
| 142 | - #expect(bash.workingDirectory == "/work") | ||
| 143 | - #expect(bash.timeout == .seconds(30)) | ||
| 144 | - #expect(bash.maxOutputBytes == 16_384) | ||
| 145 | - } | ||
| 146 | - | ||
| 147 | - @Test func optionsAreRead() throws { | ||
| 148 | - let options: ConfigValue = .map([ | ||
| 149 | - "confirm": .bool(false), "workdir": .string("sub"), "timeout": .string("2m"), | ||
| 150 | - "max_output": .string("1MB"), "allow": .list([.string("ls*")]), | ||
| 151 | - "deny": .list([.string("sudo *")]), | ||
| 152 | - ]) | ||
| 153 | - let tools = try ToolRegistry.builtIn.makeTools( | ||
| 154 | - for: config(tools: ["bash": options]), environment: environment) | ||
| 155 | - let bash = try #require(tools.first as? BashTool) | ||
| 156 | - | ||
| 157 | - #expect(!bash.confirm) | ||
| 158 | - #expect(bash.workingDirectory == "/work/sub") | ||
| 159 | - #expect(bash.timeout == .seconds(120)) | ||
| 160 | - #expect(bash.maxOutputBytes == 1_048_576) | ||
| 161 | - #expect(bash.allow == ["ls*"]) | ||
| 162 | - #expect(bash.deny == ["sudo *"]) | ||
| 163 | - } | ||
| 164 | - | ||
| 165 | - @Test func unknownToolsAndBadOptionsAreConfigErrors() { | ||
| 166 | - let bad = config(tools: [ | ||
| 167 | - "web": .map([:]), "bash": .map(["timeout": .string("soon"), "confrim": .bool(true)]), | ||
| 168 | - ]) | ||
| 169 | - #expect { | ||
| 170 | - try ToolRegistry.builtIn.makeTools(for: bad, environment: environment) | ||
| 171 | - } throws: { error in | ||
| 172 | - let keys = (error as? ConfigError)?.issues.map(\.keyPath) | ||
| 173 | - return keys == ["tools.bash.confrim", "tools.web"] | ||
| 174 | - } | ||
| 175 | - } | ||
| 176 | - | ||
| 177 | - @Test func customToolsCanBeRegistered() throws { | ||
| 178 | - var registry = ToolRegistry.builtIn | ||
| 179 | - registry.register("upper") { _, _ in UpperTool() } | ||
| 180 | - | ||
| 181 | - let tools = try registry.makeTools( | ||
| 182 | - for: config(tools: ["upper": .map([:])]), environment: environment) | ||
| 183 | - | ||
| 184 | - #expect(tools.map(\.spec.name) == ["upper"]) | ||
| 185 | - #expect(registry.names == ["bash", "upper"]) | ||
| 186 | - } | ||
| 187 | -} | ||
| 188 | - | ||
| 189 | -@Suite struct OptionValues { | ||
| 190 | - @Test func durationsAndSizesAcceptNumbersAndUnits() throws { | ||
| 191 | - let reader = OptionReader( | ||
| 192 | - .map([ | ||
| 193 | - "a": .int(2), "b": .string("500ms"), "c": .string("1h"), "d": .double(0.25), | ||
| 194 | - "size": .string("16kb"), "bytes": .int(10), | ||
| 195 | - ])) | ||
| 196 | - #expect(try reader.duration("a", default: .zero) == .seconds(2)) | ||
| 197 | - #expect(try reader.duration("b", default: .zero) == .milliseconds(500)) | ||
| 198 | - #expect(try reader.duration("c", default: .zero) == .seconds(3600)) | ||
| 199 | - #expect(try reader.duration("d", default: .zero) == .milliseconds(250)) | ||
| 200 | - #expect(try reader.duration("missing", default: .seconds(9)) == .seconds(9)) | ||
| 201 | - #expect(try reader.byteCount("size", default: 0) == 16_384) | ||
| 202 | - #expect(try reader.byteCount("bytes", default: 0) == 10) | ||
| 203 | - } | ||
| 204 | - | ||
| 205 | - @Test func invalidValuesAreRejected() { | ||
| 206 | - let reader = OptionReader( | ||
| 207 | - .map(["t": .string("-1s"), "s": .string("big"), "b": .string("yes")])) | ||
| 208 | - #expect(throws: ToolOptionError.self) { try reader.duration("t", default: .zero) } | ||
| 209 | - #expect(throws: ToolOptionError.self) { try reader.byteCount("s", default: 0) } | ||
| 210 | - #expect(throws: ToolOptionError.self) { try reader.bool("b", default: true) } | ||
| 211 | - } | ||
| 212 | - | ||
| 213 | - @Test func commandPatternsUseShellWildcards() { | ||
| 214 | - #expect(CommandPattern.matches("git status", pattern: "git *")) | ||
| 215 | - #expect(CommandPattern.matches("ls", pattern: "l?")) | ||
| 216 | - #expect(CommandPattern.matches("anything", pattern: "*")) | ||
| 217 | - #expect(!CommandPattern.matches("git", pattern: "git *")) | ||
| 218 | - #expect(!CommandPattern.matches("sudo ls", pattern: "ls*")) | ||
| 219 | - #expect(CommandPattern.firstMatch("rm -rf /", in: ["ls*", "rm *"]) == "rm *") | ||
| 220 | - } | ||
| 221 | -} | ||
| 222 | - | ||
| 223 | -@Suite struct EngineRegistryChoosesEngines { | ||
| 224 | - @Test func firstRegisteredEngineIsTheDefault() throws { | ||
| 225 | - var engines = EngineRegistry() | ||
| 226 | - engines.register("fake") { FakeEngine() } | ||
| 227 | - engines.register("other") { FakeEngine() } | ||
| 228 | - | ||
| 229 | - #expect(engines.defaultName == "fake") | ||
| 230 | - #expect(try engines.make().name == "fake") | ||
| 231 | - #expect(engines.names == ["fake", "other"]) | ||
| 232 | - } | ||
| 233 | - | ||
| 234 | - @Test func unknownEngineListsTheAvailableOnes() { | ||
| 235 | - var engines = EngineRegistry() | ||
| 236 | - engines.register("fake") { FakeEngine() } | ||
| 237 | - #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { | ||
| 238 | - try engines.make("mlx") | ||
| 239 | - } | ||
| 240 | - } | ||
| 241 | -} | ||
deleted
Tests/RazorbillCoreTests/ConfigLoaderTests.swift +0 -183 | deleted file mode 100644 | ||
| @@ -1,183 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -/// A loader with a fixed date, directory and environment, so tests are deterministic. | |
| 6 | -func makeLoader() -> ConfigLoader { | |
| 7 | - let context = TemplateContext( | |
| 8 | - date: Date(timeIntervalSince1970: 1_794_873_600), // 2026-11-17 00:00 UTC | |
| 9 | - currentDirectory: "/work", | |
| 10 | - environment: ["USER_NAME": "Ada"], | |
| 11 | - timeZone: TimeZone(identifier: "UTC")! | |
| 12 | - ) | |
| 13 | - return ConfigLoader(context: context, homeDirectory: "/home/ada") | |
| 14 | -} | |
| 15 | - | |
| 16 | -/// The issues thrown for `yaml`, or a test failure when it loads. | |
| 17 | -func issues(_ yaml: String) -> [ConfigIssue] { | |
| 18 | - do { | |
| 19 | - _ = try makeLoader().parse(yaml) | |
| 20 | - Issue.record("expected the configuration to be rejected") | |
| 21 | - return [] | |
| 22 | - } catch let error as ConfigError { | |
| 23 | - return error.issues | |
| 24 | - } catch { | |
| 25 | - Issue.record("unexpected error \(error)") | |
| 26 | - return [] | |
| 27 | - } | |
| 28 | -} | |
| 29 | - | |
| 30 | -@Suite struct ValidConfigurations { | |
| 31 | - @Test func theExampleFileLoadsWithItsValues() throws { | |
| 32 | - let path = URL(fileURLWithPath: #filePath) | |
| 33 | - .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() | |
| 34 | - .appendingPathComponent("examples/agent.yaml").path | |
| 35 | - let config = try makeLoader().load(file: path) | |
| 36 | - | |
| 37 | - #expect(config.name == "swift-helper") | |
| 38 | - #expect(config.model == .huggingFace(id: "mlx-community/Qwen3-1.7B-4bit", revision: "main")) | |
| 39 | - #expect( | |
| 40 | - config.generation | |
| 41 | - == GenerationSettings(temperature: 0.6, topP: 1.0, maxTokens: 1024, thinking: false) | |
| 42 | - ) | |
| 43 | - #expect(config.system.hasPrefix("You are a concise Swift expert. Today is 2026-11-17.")) | |
| 44 | - #expect(config.system.contains("The user works in /work.")) | |
| 45 | - #expect(config.tools["bash"]?["confirm"] == .bool(true)) | |
| 46 | - #expect(config.userInterface == UISettings(showStats: true, showThinking: true)) | |
| 47 | - } | |
| 48 | - | |
| 49 | - @Test func thinkingAndItsDisplayAreSetSeparately() throws { | |
| 50 | - let config = try makeLoader().parse( | |
| 51 | - "name: a\nmodel: m/x\ngeneration:\n thinking: true\nui:\n show_thinking: false\n") | |
| 52 | - #expect(config.generation.thinking) | |
| 53 | - #expect(config.userInterface == UISettings(showStats: true, showThinking: false)) | |
| 54 | - } | |
| 55 | - | |
| 56 | - @Test func minimalFileGetsDefaults() throws { | |
| 57 | - let config = try makeLoader().parse("name: demo\nmodel: mlx-community/Qwen3-0.6B-4bit\n") | |
| 58 | - | |
| 59 | - #expect(config.model == .huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main")) | |
| 60 | - #expect(config.generation == GenerationSettings()) | |
| 61 | - #expect(config.system == "") | |
| 62 | - #expect(config.tools.isEmpty) | |
| 63 | - #expect(config.userInterface == UISettings()) | |
| 64 | - #expect(config.description == nil) | |
| 65 | - } | |
| 66 | - | |
| 67 | - @Test func localModelPathsExpandHomeAndResolveRelativePaths() throws { | |
| 68 | - let home = try makeLoader().parse("name: a\nmodel:\n path: ~/models/m\n") | |
| 69 | - #expect(home.model == .local(path: URL(fileURLWithPath: "/home/ada/models/m"))) | |
| 70 | - | |
| 71 | - let relative = try makeLoader().parse( | |
| 72 | - "name: a\nmodel:\n path: models/m\n", baseDirectory: "/cfg") | |
| 73 | - #expect(relative.model == .local(path: URL(fileURLWithPath: "/cfg/models/m"))) | |
| 74 | - } | |
| 75 | - | |
| 76 | - @Test func toolsCanBeAListOfNamesOrEmptyOptions() throws { | |
| 77 | - let list = try makeLoader().parse("name: a\nmodel: m/x\ntools: [bash]\n") | |
| 78 | - #expect(list.tools == ["bash": .map([:])]) | |
| 79 | - | |
| 80 | - let empty = try makeLoader().parse("name: a\nmodel: m/x\ntools:\n bash:\n") | |
| 81 | - #expect(empty.tools == ["bash": .map([:])]) | |
| 82 | - } | |
| 83 | - | |
| 84 | - @Test func environmentVariablesAreReplaced() throws { | |
| 85 | - let config = try makeLoader().parse( | |
| 86 | - "name: a\nmodel: m/x\nsystem: Hello {{ env.USER_NAME }}\n") | |
| 87 | - #expect(config.system == "Hello Ada") | |
| 88 | - } | |
| 89 | -} | |
| 90 | - | |
| 91 | -@Suite struct InvalidConfigurations { | |
| 92 | - @Test func missingNameAndModelAreBothReported() { | |
| 93 | - let found = issues("description: nothing else\n") | |
| 94 | - #expect(found.map(\.keyPath) == ["name", "model"]) | |
| 95 | - } | |
| 96 | - | |
| 97 | - @Test func unknownKeysAreReportedWithTheirLine() { | |
| 98 | - let found = issues("name: a\nmodel: m/x\ngeneration:\n temprature: 0.2\n") | |
| 99 | - #expect(found.count == 1) | |
| 100 | - #expect(found.first?.keyPath == "generation.temprature") | |
| 101 | - #expect(found.first?.line == 4) | |
| 102 | - #expect(found.first?.message.contains("temperature") == true) | |
| 103 | - } | |
| 104 | - | |
| 105 | - @Test func wrongTypesAreReported() { | |
| 106 | - let found = issues( | |
| 107 | - "name: a\nmodel: m/x\ngeneration:\n temperature: hot\n max_tokens: 1.5\n thinking: maybe\n" | |
| 108 | - ) | |
| 109 | - #expect( | |
| 110 | - found.map(\.keyPath) == [ | |
| 111 | - "generation.temperature", "generation.max_tokens", "generation.thinking", | |
| 112 | - ]) | |
| 113 | - } | |
| 114 | - | |
| 115 | - @Test func outOfRangeValuesAreReported() { | |
| 116 | - let found = issues( | |
| 117 | - "name: a\nmodel: m/x\ngeneration:\n temperature: -1\n top_p: 0\n max_tokens: 0\n") | |
| 118 | - #expect( | |
| 119 | - found.map(\.keyPath) == [ | |
| 120 | - "generation.temperature", "generation.top_p", "generation.max_tokens", | |
| 121 | - ]) | |
| 122 | - } | |
| 123 | - | |
| 124 | - @Test func theThinkingBudgetMustLeaveRoomForTheAnswer() throws { | |
| 125 | - let config = try makeLoader().parse( | |
| 126 | - "name: a\nmodel: m/x\ngeneration:\n max_tokens: 2048\n thinking_budget: 512\n") | |
| 127 | - #expect(config.generation.thinkingBudget == 512) | |
| 128 | - #expect(try makeLoader().parse("name: a\nmodel: m/x\n").generation.thinkingBudget == nil) | |
| 129 | - | |
| 130 | - for budget in ["-1", "1024", "many"] { | |
| 131 | - let found = issues("name: a\nmodel: m/x\ngeneration:\n thinking_budget: \(budget)\n") | |
| 132 | - #expect(found.map(\.keyPath) == ["generation.thinking_budget"]) | |
| 133 | - #expect(found.first?.line == 4) | |
| 134 | - } | |
| 135 | - } | |
| 136 | - | |
| 137 | - @Test func modelNeedsExactlyOneOfIdOrPath() { | |
| 138 | - #expect( | |
| 139 | - issues("name: a\nmodel:\n id: m/x\n path: /m\n").first?.message.contains("not both") | |
| 140 | - == true) | |
| 141 | - #expect( | |
| 142 | - issues("name: a\nmodel:\n revision: main\n").first?.message.contains("needs an id") | |
| 143 | - == true) | |
| 144 | - #expect( | |
| 145 | - issues("name: a\nmodel:\n path: /m\n revision: v1\n").first?.keyPath | |
| 146 | - == "model.revision") | |
| 147 | - } | |
| 148 | - | |
| 149 | - @Test func unresolvedVariablesAreReported() { | |
| 150 | - let unknown = issues("name: a\nmodel: m/x\nsystem: \"{{weather}}\"\n") | |
| 151 | - #expect(unknown.first?.keyPath == "system") | |
| 152 | - #expect(unknown.first?.message.contains("unknown variable") == true) | |
| 153 | - | |
| 154 | - let unset = issues("name: a\nmodel: m/x\nsystem: \"{{env.NOPE}}\"\n") | |
| 155 | - #expect(unset.first?.message.contains("NOPE is not set") == true) | |
| 156 | - } | |
| 157 | - | |
| 158 | - @Test func emptyAndMalformedFilesAreReported() { | |
| 159 | - #expect(issues("").first?.message == "the file is empty") | |
| 160 | - #expect(issues("name: [unclosed\n").first?.message.hasPrefix("not valid YAML") == true) | |
| 161 | - #expect(issues("- just\n- a list\n").first?.message.contains("mapping") == true) | |
| 162 | - } | |
| 163 | - | |
| 164 | - @Test func toolOptionsMustBeAMapping() { | |
| 165 | - #expect(issues("name: a\nmodel: m/x\ntools:\n bash: yes\n").first?.keyPath == "tools.bash") | |
| 166 | - } | |
| 167 | - | |
| 168 | - @Test func missingFileIsReported() { | |
| 169 | - #expect(throws: ConfigError.self) { try makeLoader().load(file: "/does/not/exist.yaml") } | |
| 170 | - } | |
| 171 | - | |
| 172 | - @Test func errorDescriptionListsEveryIssue() { | |
| 173 | - let error = ConfigError( | |
| 174 | - file: "a.yaml", | |
| 175 | - issues: [ | |
| 176 | - ConfigIssue(keyPath: "name", line: 1, message: "is required"), | |
| 177 | - ConfigIssue(keyPath: "", line: nil, message: "oops"), | |
| 178 | - ]) | |
| 179 | - #expect( | |
| 180 | - error.description | |
| 181 | - == "invalid configuration a.yaml\n - line 1: name: is required\n - oops") | |
| 182 | - } | |
| 183 | -} | |
| deleted file mode 100644 | |||
| @@ -1,183 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -/// A loader with a fixed date, directory and environment, so tests are deterministic. | ||
| 6 | -func makeLoader() -> ConfigLoader { | ||
| 7 | - let context = TemplateContext( | ||
| 8 | - date: Date(timeIntervalSince1970: 1_794_873_600), // 2026-11-17 00:00 UTC | ||
| 9 | - currentDirectory: "/work", | ||
| 10 | - environment: ["USER_NAME": "Ada"], | ||
| 11 | - timeZone: TimeZone(identifier: "UTC")! | ||
| 12 | - ) | ||
| 13 | - return ConfigLoader(context: context, homeDirectory: "/home/ada") | ||
| 14 | -} | ||
| 15 | - | ||
| 16 | -/// The issues thrown for `yaml`, or a test failure when it loads. | ||
| 17 | -func issues(_ yaml: String) -> [ConfigIssue] { | ||
| 18 | - do { | ||
| 19 | - _ = try makeLoader().parse(yaml) | ||
| 20 | - Issue.record("expected the configuration to be rejected") | ||
| 21 | - return [] | ||
| 22 | - } catch let error as ConfigError { | ||
| 23 | - return error.issues | ||
| 24 | - } catch { | ||
| 25 | - Issue.record("unexpected error \(error)") | ||
| 26 | - return [] | ||
| 27 | - } | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | -@Suite struct ValidConfigurations { | ||
| 31 | - @Test func theExampleFileLoadsWithItsValues() throws { | ||
| 32 | - let path = URL(fileURLWithPath: #filePath) | ||
| 33 | - .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() | ||
| 34 | - .appendingPathComponent("examples/agent.yaml").path | ||
| 35 | - let config = try makeLoader().load(file: path) | ||
| 36 | - | ||
| 37 | - #expect(config.name == "swift-helper") | ||
| 38 | - #expect(config.model == .huggingFace(id: "mlx-community/Qwen3-1.7B-4bit", revision: "main")) | ||
| 39 | - #expect( | ||
| 40 | - config.generation | ||
| 41 | - == GenerationSettings(temperature: 0.6, topP: 1.0, maxTokens: 1024, thinking: false) | ||
| 42 | - ) | ||
| 43 | - #expect(config.system.hasPrefix("You are a concise Swift expert. Today is 2026-11-17.")) | ||
| 44 | - #expect(config.system.contains("The user works in /work.")) | ||
| 45 | - #expect(config.tools["bash"]?["confirm"] == .bool(true)) | ||
| 46 | - #expect(config.userInterface == UISettings(showStats: true, showThinking: true)) | ||
| 47 | - } | ||
| 48 | - | ||
| 49 | - @Test func thinkingAndItsDisplayAreSetSeparately() throws { | ||
| 50 | - let config = try makeLoader().parse( | ||
| 51 | - "name: a\nmodel: m/x\ngeneration:\n thinking: true\nui:\n show_thinking: false\n") | ||
| 52 | - #expect(config.generation.thinking) | ||
| 53 | - #expect(config.userInterface == UISettings(showStats: true, showThinking: false)) | ||
| 54 | - } | ||
| 55 | - | ||
| 56 | - @Test func minimalFileGetsDefaults() throws { | ||
| 57 | - let config = try makeLoader().parse("name: demo\nmodel: mlx-community/Qwen3-0.6B-4bit\n") | ||
| 58 | - | ||
| 59 | - #expect(config.model == .huggingFace(id: "mlx-community/Qwen3-0.6B-4bit", revision: "main")) | ||
| 60 | - #expect(config.generation == GenerationSettings()) | ||
| 61 | - #expect(config.system == "") | ||
| 62 | - #expect(config.tools.isEmpty) | ||
| 63 | - #expect(config.userInterface == UISettings()) | ||
| 64 | - #expect(config.description == nil) | ||
| 65 | - } | ||
| 66 | - | ||
| 67 | - @Test func localModelPathsExpandHomeAndResolveRelativePaths() throws { | ||
| 68 | - let home = try makeLoader().parse("name: a\nmodel:\n path: ~/models/m\n") | ||
| 69 | - #expect(home.model == .local(path: URL(fileURLWithPath: "/home/ada/models/m"))) | ||
| 70 | - | ||
| 71 | - let relative = try makeLoader().parse( | ||
| 72 | - "name: a\nmodel:\n path: models/m\n", baseDirectory: "/cfg") | ||
| 73 | - #expect(relative.model == .local(path: URL(fileURLWithPath: "/cfg/models/m"))) | ||
| 74 | - } | ||
| 75 | - | ||
| 76 | - @Test func toolsCanBeAListOfNamesOrEmptyOptions() throws { | ||
| 77 | - let list = try makeLoader().parse("name: a\nmodel: m/x\ntools: [bash]\n") | ||
| 78 | - #expect(list.tools == ["bash": .map([:])]) | ||
| 79 | - | ||
| 80 | - let empty = try makeLoader().parse("name: a\nmodel: m/x\ntools:\n bash:\n") | ||
| 81 | - #expect(empty.tools == ["bash": .map([:])]) | ||
| 82 | - } | ||
| 83 | - | ||
| 84 | - @Test func environmentVariablesAreReplaced() throws { | ||
| 85 | - let config = try makeLoader().parse( | ||
| 86 | - "name: a\nmodel: m/x\nsystem: Hello {{ env.USER_NAME }}\n") | ||
| 87 | - #expect(config.system == "Hello Ada") | ||
| 88 | - } | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -@Suite struct InvalidConfigurations { | ||
| 92 | - @Test func missingNameAndModelAreBothReported() { | ||
| 93 | - let found = issues("description: nothing else\n") | ||
| 94 | - #expect(found.map(\.keyPath) == ["name", "model"]) | ||
| 95 | - } | ||
| 96 | - | ||
| 97 | - @Test func unknownKeysAreReportedWithTheirLine() { | ||
| 98 | - let found = issues("name: a\nmodel: m/x\ngeneration:\n temprature: 0.2\n") | ||
| 99 | - #expect(found.count == 1) | ||
| 100 | - #expect(found.first?.keyPath == "generation.temprature") | ||
| 101 | - #expect(found.first?.line == 4) | ||
| 102 | - #expect(found.first?.message.contains("temperature") == true) | ||
| 103 | - } | ||
| 104 | - | ||
| 105 | - @Test func wrongTypesAreReported() { | ||
| 106 | - let found = issues( | ||
| 107 | - "name: a\nmodel: m/x\ngeneration:\n temperature: hot\n max_tokens: 1.5\n thinking: maybe\n" | ||
| 108 | - ) | ||
| 109 | - #expect( | ||
| 110 | - found.map(\.keyPath) == [ | ||
| 111 | - "generation.temperature", "generation.max_tokens", "generation.thinking", | ||
| 112 | - ]) | ||
| 113 | - } | ||
| 114 | - | ||
| 115 | - @Test func outOfRangeValuesAreReported() { | ||
| 116 | - let found = issues( | ||
| 117 | - "name: a\nmodel: m/x\ngeneration:\n temperature: -1\n top_p: 0\n max_tokens: 0\n") | ||
| 118 | - #expect( | ||
| 119 | - found.map(\.keyPath) == [ | ||
| 120 | - "generation.temperature", "generation.top_p", "generation.max_tokens", | ||
| 121 | - ]) | ||
| 122 | - } | ||
| 123 | - | ||
| 124 | - @Test func theThinkingBudgetMustLeaveRoomForTheAnswer() throws { | ||
| 125 | - let config = try makeLoader().parse( | ||
| 126 | - "name: a\nmodel: m/x\ngeneration:\n max_tokens: 2048\n thinking_budget: 512\n") | ||
| 127 | - #expect(config.generation.thinkingBudget == 512) | ||
| 128 | - #expect(try makeLoader().parse("name: a\nmodel: m/x\n").generation.thinkingBudget == nil) | ||
| 129 | - | ||
| 130 | - for budget in ["-1", "1024", "many"] { | ||
| 131 | - let found = issues("name: a\nmodel: m/x\ngeneration:\n thinking_budget: \(budget)\n") | ||
| 132 | - #expect(found.map(\.keyPath) == ["generation.thinking_budget"]) | ||
| 133 | - #expect(found.first?.line == 4) | ||
| 134 | - } | ||
| 135 | - } | ||
| 136 | - | ||
| 137 | - @Test func modelNeedsExactlyOneOfIdOrPath() { | ||
| 138 | - #expect( | ||
| 139 | - issues("name: a\nmodel:\n id: m/x\n path: /m\n").first?.message.contains("not both") | ||
| 140 | - == true) | ||
| 141 | - #expect( | ||
| 142 | - issues("name: a\nmodel:\n revision: main\n").first?.message.contains("needs an id") | ||
| 143 | - == true) | ||
| 144 | - #expect( | ||
| 145 | - issues("name: a\nmodel:\n path: /m\n revision: v1\n").first?.keyPath | ||
| 146 | - == "model.revision") | ||
| 147 | - } | ||
| 148 | - | ||
| 149 | - @Test func unresolvedVariablesAreReported() { | ||
| 150 | - let unknown = issues("name: a\nmodel: m/x\nsystem: \"{{weather}}\"\n") | ||
| 151 | - #expect(unknown.first?.keyPath == "system") | ||
| 152 | - #expect(unknown.first?.message.contains("unknown variable") == true) | ||
| 153 | - | ||
| 154 | - let unset = issues("name: a\nmodel: m/x\nsystem: \"{{env.NOPE}}\"\n") | ||
| 155 | - #expect(unset.first?.message.contains("NOPE is not set") == true) | ||
| 156 | - } | ||
| 157 | - | ||
| 158 | - @Test func emptyAndMalformedFilesAreReported() { | ||
| 159 | - #expect(issues("").first?.message == "the file is empty") | ||
| 160 | - #expect(issues("name: [unclosed\n").first?.message.hasPrefix("not valid YAML") == true) | ||
| 161 | - #expect(issues("- just\n- a list\n").first?.message.contains("mapping") == true) | ||
| 162 | - } | ||
| 163 | - | ||
| 164 | - @Test func toolOptionsMustBeAMapping() { | ||
| 165 | - #expect(issues("name: a\nmodel: m/x\ntools:\n bash: yes\n").first?.keyPath == "tools.bash") | ||
| 166 | - } | ||
| 167 | - | ||
| 168 | - @Test func missingFileIsReported() { | ||
| 169 | - #expect(throws: ConfigError.self) { try makeLoader().load(file: "/does/not/exist.yaml") } | ||
| 170 | - } | ||
| 171 | - | ||
| 172 | - @Test func errorDescriptionListsEveryIssue() { | ||
| 173 | - let error = ConfigError( | ||
| 174 | - file: "a.yaml", | ||
| 175 | - issues: [ | ||
| 176 | - ConfigIssue(keyPath: "name", line: 1, message: "is required"), | ||
| 177 | - ConfigIssue(keyPath: "", line: nil, message: "oops"), | ||
| 178 | - ]) | ||
| 179 | - #expect( | ||
| 180 | - error.description | ||
| 181 | - == "invalid configuration a.yaml\n - line 1: name: is required\n - oops") | ||
| 182 | - } | ||
| 183 | -} | ||
deleted
Tests/RazorbillCoreTests/ConfigLocatorTests.swift +0 -34 | deleted file mode 100644 | ||
| @@ -1,34 +0,0 @@ | ||
| 1 | -import RazorbillCore | |
| 2 | -import Testing | |
| 3 | - | |
| 4 | -func locator(existing: Set<String>) -> ConfigLocator { | |
| 5 | - ConfigLocator( | |
| 6 | - currentDirectory: "/work", homeDirectory: "/home/ada", fileExists: { existing.contains($0) } | |
| 7 | - ) | |
| 8 | -} | |
| 9 | - | |
| 10 | -@Test func explicitPathWinsAndHasNoFallback() throws { | |
| 11 | - let both: Set = ["/x/agent.yaml", "/work/razorbill.yaml"] | |
| 12 | - #expect(try locator(existing: both).locate(explicitPath: "/x/agent.yaml") == "/x/agent.yaml") | |
| 13 | - #expect(throws: ConfigLocator.NotFound.self) { | |
| 14 | - try locator(existing: ["/work/razorbill.yaml"]).locate(explicitPath: "/missing.yaml") | |
| 15 | - } | |
| 16 | -} | |
| 17 | - | |
| 18 | -@Test func localFileComesBeforeTheUserFile() throws { | |
| 19 | - let both: Set = ["/work/razorbill.yaml", "/home/ada/.config/razorbill/agent.yaml"] | |
| 20 | - #expect(try locator(existing: both).locate(explicitPath: nil) == "/work/razorbill.yaml") | |
| 21 | - #expect( | |
| 22 | - try locator(existing: ["/home/ada/.config/razorbill/agent.yaml"]).locate(explicitPath: nil) | |
| 23 | - == "/home/ada/.config/razorbill/agent.yaml") | |
| 24 | -} | |
| 25 | - | |
| 26 | -@Test func notFoundListsWhatWasSearched() { | |
| 27 | - #expect( | |
| 28 | - throws: ConfigLocator.NotFound(searched: [ | |
| 29 | - "/work/razorbill.yaml", "/home/ada/.config/razorbill/agent.yaml", | |
| 30 | - ]) | |
| 31 | - ) { | |
| 32 | - try locator(existing: []).locate(explicitPath: nil) | |
| 33 | - } | |
| 34 | -} | |
| deleted file mode 100644 | |||
| @@ -1,34 +0,0 @@ | |||
| 1 | -import RazorbillCore | ||
| 2 | -import Testing | ||
| 3 | - | ||
| 4 | -func locator(existing: Set<String>) -> ConfigLocator { | ||
| 5 | - ConfigLocator( | ||
| 6 | - currentDirectory: "/work", homeDirectory: "/home/ada", fileExists: { existing.contains($0) } | ||
| 7 | - ) | ||
| 8 | -} | ||
| 9 | - | ||
| 10 | -@Test func explicitPathWinsAndHasNoFallback() throws { | ||
| 11 | - let both: Set = ["/x/agent.yaml", "/work/razorbill.yaml"] | ||
| 12 | - #expect(try locator(existing: both).locate(explicitPath: "/x/agent.yaml") == "/x/agent.yaml") | ||
| 13 | - #expect(throws: ConfigLocator.NotFound.self) { | ||
| 14 | - try locator(existing: ["/work/razorbill.yaml"]).locate(explicitPath: "/missing.yaml") | ||
| 15 | - } | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -@Test func localFileComesBeforeTheUserFile() throws { | ||
| 19 | - let both: Set = ["/work/razorbill.yaml", "/home/ada/.config/razorbill/agent.yaml"] | ||
| 20 | - #expect(try locator(existing: both).locate(explicitPath: nil) == "/work/razorbill.yaml") | ||
| 21 | - #expect( | ||
| 22 | - try locator(existing: ["/home/ada/.config/razorbill/agent.yaml"]).locate(explicitPath: nil) | ||
| 23 | - == "/home/ada/.config/razorbill/agent.yaml") | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -@Test func notFoundListsWhatWasSearched() { | ||
| 27 | - #expect( | ||
| 28 | - throws: ConfigLocator.NotFound(searched: [ | ||
| 29 | - "/work/razorbill.yaml", "/home/ada/.config/razorbill/agent.yaml", | ||
| 30 | - ]) | ||
| 31 | - ) { | ||
| 32 | - try locator(existing: []).locate(explicitPath: nil) | ||
| 33 | - } | ||
| 34 | -} | ||
added
Tests/RazorbillCoreTests/ConfigReaderTests.swift +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +import Testing | |
| 2 | +import Yams | |
| 3 | + | |
| 4 | +@testable import RazorbillCore | |
| 5 | + | |
| 6 | +/// The typed YAML reader kept for configuration files: wrong types and unknown keys become | |
| 7 | +/// issues with their line, and reading goes on so every problem is reported at once. | |
| 8 | +@Suite struct ConfigReaderReportsEveryProblem { | |
| 9 | + func mapping(_ yaml: String) throws -> Node.Mapping { | |
| 10 | + try #require(try Yams.compose(yaml: yaml)?.mapping) | |
| 11 | + } | |
| 12 | + | |
| 13 | + @Test func readsValuesOfTheRightType() throws { | |
| 14 | + let reader = ConfigReader() | |
| 15 | + let root = try mapping("name: qwen\nport: 8080\nratio: 0.5\npreload: true\n") | |
| 16 | + #expect(reader.string(root, "name", path: "") == "qwen") | |
| 17 | + #expect(reader.int(root, "port", path: "") == 8080) | |
| 18 | + #expect(reader.double(root, "ratio", path: "") == 0.5) | |
| 19 | + #expect(reader.double(root, "port", path: "") == 8080) | |
| 20 | + #expect(reader.bool(root, "preload", path: "") == true) | |
| 21 | + #expect(reader.string(root, "missing", path: "") == nil) | |
| 22 | + #expect(reader.issues.isEmpty) | |
| 23 | + } | |
| 24 | + | |
| 25 | + @Test func wrongTypesAreIssuesWithTheirLine() throws { | |
| 26 | + let reader = ConfigReader() | |
| 27 | + let root = try mapping("server:\n port: \"8080\"\n preload: yes please\n") | |
| 28 | + let serverNode = try #require(root["server"]) | |
| 29 | + let server = try #require(reader.mapping(serverNode, path: "server")) | |
| 30 | + #expect(reader.int(server, "port", path: "server") == nil) | |
| 31 | + #expect(reader.bool(server, "preload", path: "server") == nil) | |
| 32 | + #expect( | |
| 33 | + reader.issues.map(\.description) == [ | |
| 34 | + "line 2: server.port: must be a whole number", | |
| 35 | + "line 3: server.preload: must be true or false", | |
| 36 | + ]) | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Test func unknownKeysListTheExpectedOnes() throws { | |
| 40 | + let reader = ConfigReader() | |
| 41 | + let root = try mapping("host: 0.0.0.0\nprot: 80\n") | |
| 42 | + reader.rejectUnknownKeys(root, allowed: ["host", "port"], path: "server") | |
| 43 | + #expect( | |
| 44 | + reader.issues.map(\.description) == [ | |
| 45 | + "line 2: server.prot: unknown key (expected one of: host, port)" | |
| 46 | + ]) | |
| 47 | + } | |
| 48 | + | |
| 49 | + @Test func anySubtreeBecomesAConfigValue() throws { | |
| 50 | + let root = try #require(try Yams.compose(yaml: "a: [1, two, 2.5, true, null]\n")) | |
| 51 | + #expect( | |
| 52 | + ConfigReader().value(root) | |
| 53 | + == .map(["a": .list([.int(1), .string("two"), .double(2.5), .bool(true), .null])])) | |
| 54 | + } | |
| 55 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +import Testing | ||
| 2 | +import Yams | ||
| 3 | + | ||
| 4 | +@testable import RazorbillCore | ||
| 5 | + | ||
| 6 | +/// The typed YAML reader kept for configuration files: wrong types and unknown keys become | ||
| 7 | +/// issues with their line, and reading goes on so every problem is reported at once. | ||
| 8 | +@Suite struct ConfigReaderReportsEveryProblem { | ||
| 9 | + func mapping(_ yaml: String) throws -> Node.Mapping { | ||
| 10 | + try #require(try Yams.compose(yaml: yaml)?.mapping) | ||
| 11 | + } | ||
| 12 | + | ||
| 13 | + @Test func readsValuesOfTheRightType() throws { | ||
| 14 | + let reader = ConfigReader() | ||
| 15 | + let root = try mapping("name: qwen\nport: 8080\nratio: 0.5\npreload: true\n") | ||
| 16 | + #expect(reader.string(root, "name", path: "") == "qwen") | ||
| 17 | + #expect(reader.int(root, "port", path: "") == 8080) | ||
| 18 | + #expect(reader.double(root, "ratio", path: "") == 0.5) | ||
| 19 | + #expect(reader.double(root, "port", path: "") == 8080) | ||
| 20 | + #expect(reader.bool(root, "preload", path: "") == true) | ||
| 21 | + #expect(reader.string(root, "missing", path: "") == nil) | ||
| 22 | + #expect(reader.issues.isEmpty) | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + @Test func wrongTypesAreIssuesWithTheirLine() throws { | ||
| 26 | + let reader = ConfigReader() | ||
| 27 | + let root = try mapping("server:\n port: \"8080\"\n preload: yes please\n") | ||
| 28 | + let serverNode = try #require(root["server"]) | ||
| 29 | + let server = try #require(reader.mapping(serverNode, path: "server")) | ||
| 30 | + #expect(reader.int(server, "port", path: "server") == nil) | ||
| 31 | + #expect(reader.bool(server, "preload", path: "server") == nil) | ||
| 32 | + #expect( | ||
| 33 | + reader.issues.map(\.description) == [ | ||
| 34 | + "line 2: server.port: must be a whole number", | ||
| 35 | + "line 3: server.preload: must be true or false", | ||
| 36 | + ]) | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + @Test func unknownKeysListTheExpectedOnes() throws { | ||
| 40 | + let reader = ConfigReader() | ||
| 41 | + let root = try mapping("host: 0.0.0.0\nprot: 80\n") | ||
| 42 | + reader.rejectUnknownKeys(root, allowed: ["host", "port"], path: "server") | ||
| 43 | + #expect( | ||
| 44 | + reader.issues.map(\.description) == [ | ||
| 45 | + "line 2: server.prot: unknown key (expected one of: host, port)" | ||
| 46 | + ]) | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + @Test func anySubtreeBecomesAConfigValue() throws { | ||
| 50 | + let root = try #require(try Yams.compose(yaml: "a: [1, two, 2.5, true, null]\n")) | ||
| 51 | + #expect( | ||
| 52 | + ConfigReader().value(root) | ||
| 53 | + == .map(["a": .list([.int(1), .string("two"), .double(2.5), .bool(true), .null])])) | ||
| 54 | + } | ||
| 55 | +} | ||
deleted
Tests/RazorbillCoreTests/ConfigWriterTests.swift +0 -30 | deleted file mode 100644 | ||
| @@ -1,30 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -@Test func writtenFilesLoadBackToTheSameValues() throws { | |
| 6 | - let draft = AgentDraft( | |
| 7 | - name: "a \"quoted\" name", description: "line\twith tab", | |
| 8 | - model: .local(path: URL(fileURLWithPath: "/m")), | |
| 9 | - system: "Line one\n\nLine {{cwd}}", | |
| 10 | - generation: GenerationSettings( | |
| 11 | - temperature: 0.25, topP: 0.9, maxTokens: 64, thinking: true, thinkingBudget: 32), | |
| 12 | - tools: ["bash"], showStats: false, showThinking: false) | |
| 13 | - | |
| 14 | - let config = try makeLoader().parse(ConfigWriter.yaml(for: draft)) | |
| 15 | - | |
| 16 | - #expect(config.name == draft.name) | |
| 17 | - #expect(config.description == draft.description) | |
| 18 | - #expect(config.model == draft.model) | |
| 19 | - #expect(config.system == "Line one\n\nLine /work\n") | |
| 20 | - #expect(config.generation == draft.generation) | |
| 21 | - #expect(config.tools == ["bash": .map(["confirm": .bool(true)])]) | |
| 22 | - #expect(config.userInterface == UISettings(showStats: false, showThinking: false)) | |
| 23 | -} | |
| 24 | - | |
| 25 | -@Test func noToolsAndEmptyPromptStillLoad() throws { | |
| 26 | - let draft = AgentDraft(name: "x", model: .huggingFace(id: "o/m", revision: "v1"), system: "") | |
| 27 | - let config = try makeLoader().parse(ConfigWriter.yaml(for: draft)) | |
| 28 | - #expect(config.tools.isEmpty) | |
| 29 | - #expect(config.model == .huggingFace(id: "o/m", revision: "v1")) | |
| 30 | -} | |
| deleted file mode 100644 | |||
| @@ -1,30 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -@Test func writtenFilesLoadBackToTheSameValues() throws { | ||
| 6 | - let draft = AgentDraft( | ||
| 7 | - name: "a \"quoted\" name", description: "line\twith tab", | ||
| 8 | - model: .local(path: URL(fileURLWithPath: "/m")), | ||
| 9 | - system: "Line one\n\nLine {{cwd}}", | ||
| 10 | - generation: GenerationSettings( | ||
| 11 | - temperature: 0.25, topP: 0.9, maxTokens: 64, thinking: true, thinkingBudget: 32), | ||
| 12 | - tools: ["bash"], showStats: false, showThinking: false) | ||
| 13 | - | ||
| 14 | - let config = try makeLoader().parse(ConfigWriter.yaml(for: draft)) | ||
| 15 | - | ||
| 16 | - #expect(config.name == draft.name) | ||
| 17 | - #expect(config.description == draft.description) | ||
| 18 | - #expect(config.model == draft.model) | ||
| 19 | - #expect(config.system == "Line one\n\nLine /work\n") | ||
| 20 | - #expect(config.generation == draft.generation) | ||
| 21 | - #expect(config.tools == ["bash": .map(["confirm": .bool(true)])]) | ||
| 22 | - #expect(config.userInterface == UISettings(showStats: false, showThinking: false)) | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -@Test func noToolsAndEmptyPromptStillLoad() throws { | ||
| 26 | - let draft = AgentDraft(name: "x", model: .huggingFace(id: "o/m", revision: "v1"), system: "") | ||
| 27 | - let config = try makeLoader().parse(ConfigWriter.yaml(for: draft)) | ||
| 28 | - #expect(config.tools.isEmpty) | ||
| 29 | - #expect(config.model == .huggingFace(id: "o/m", revision: "v1")) | ||
| 30 | -} | ||
added
Tests/RazorbillCoreTests/EngineAndQuantityTests.swift +47 -0 | new file mode 100644 | ||
| @@ -0,0 +1,47 @@ | ||
| 1 | +import RazorbillCore | |
| 2 | +import Testing | |
| 3 | + | |
| 4 | +@Suite struct QuantitiesParseConfigurationValues { | |
| 5 | + @Test func durationsAcceptUnits() { | |
| 6 | + #expect(Quantities.duration("500ms") == .milliseconds(500)) | |
| 7 | + #expect(Quantities.duration("30s") == .seconds(30)) | |
| 8 | + #expect(Quantities.duration(" 10m ") == .seconds(600)) | |
| 9 | + #expect(Quantities.duration("1h") == .seconds(3600)) | |
| 10 | + #expect(Quantities.duration("1.5s") == .milliseconds(1500)) | |
| 11 | + } | |
| 12 | + | |
| 13 | + @Test func sizesAcceptUnitsInAnyCase() { | |
| 14 | + #expect(Quantities.byteCount("512B") == 512) | |
| 15 | + #expect(Quantities.byteCount("16kb") == 16_384) | |
| 16 | + #expect(Quantities.byteCount("2MB") == 2 * 1024 * 1024) | |
| 17 | + } | |
| 18 | + | |
| 19 | + @Test func invalidValuesGiveNil() { | |
| 20 | + #expect(Quantities.duration("-1s") == nil) | |
| 21 | + #expect(Quantities.duration("0s") == nil) | |
| 22 | + #expect(Quantities.duration("10") == nil) | |
| 23 | + #expect(Quantities.duration("soon") == nil) | |
| 24 | + #expect(Quantities.byteCount("big") == nil) | |
| 25 | + #expect(Quantities.byteCount("1GB") == nil) | |
| 26 | + } | |
| 27 | +} | |
| 28 | + | |
| 29 | +@Suite struct EngineRegistryChoosesEngines { | |
| 30 | + @Test func firstRegisteredEngineIsTheDefault() throws { | |
| 31 | + var engines = EngineRegistry() | |
| 32 | + engines.register("fake") { FakeEngine() } | |
| 33 | + engines.register("other") { FakeEngine() } | |
| 34 | + | |
| 35 | + #expect(engines.defaultName == "fake") | |
| 36 | + #expect(try engines.make().name == "fake") | |
| 37 | + #expect(engines.names == ["fake", "other"]) | |
| 38 | + } | |
| 39 | + | |
| 40 | + @Test func unknownEngineListsTheAvailableOnes() { | |
| 41 | + var engines = EngineRegistry() | |
| 42 | + engines.register("fake") { FakeEngine() } | |
| 43 | + #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { | |
| 44 | + try engines.make("mlx") | |
| 45 | + } | |
| 46 | + } | |
| 47 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,47 @@ | |||
| 1 | +import RazorbillCore | ||
| 2 | +import Testing | ||
| 3 | + | ||
| 4 | +@Suite struct QuantitiesParseConfigurationValues { | ||
| 5 | + @Test func durationsAcceptUnits() { | ||
| 6 | + #expect(Quantities.duration("500ms") == .milliseconds(500)) | ||
| 7 | + #expect(Quantities.duration("30s") == .seconds(30)) | ||
| 8 | + #expect(Quantities.duration(" 10m ") == .seconds(600)) | ||
| 9 | + #expect(Quantities.duration("1h") == .seconds(3600)) | ||
| 10 | + #expect(Quantities.duration("1.5s") == .milliseconds(1500)) | ||
| 11 | + } | ||
| 12 | + | ||
| 13 | + @Test func sizesAcceptUnitsInAnyCase() { | ||
| 14 | + #expect(Quantities.byteCount("512B") == 512) | ||
| 15 | + #expect(Quantities.byteCount("16kb") == 16_384) | ||
| 16 | + #expect(Quantities.byteCount("2MB") == 2 * 1024 * 1024) | ||
| 17 | + } | ||
| 18 | + | ||
| 19 | + @Test func invalidValuesGiveNil() { | ||
| 20 | + #expect(Quantities.duration("-1s") == nil) | ||
| 21 | + #expect(Quantities.duration("0s") == nil) | ||
| 22 | + #expect(Quantities.duration("10") == nil) | ||
| 23 | + #expect(Quantities.duration("soon") == nil) | ||
| 24 | + #expect(Quantities.byteCount("big") == nil) | ||
| 25 | + #expect(Quantities.byteCount("1GB") == nil) | ||
| 26 | + } | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +@Suite struct EngineRegistryChoosesEngines { | ||
| 30 | + @Test func firstRegisteredEngineIsTheDefault() throws { | ||
| 31 | + var engines = EngineRegistry() | ||
| 32 | + engines.register("fake") { FakeEngine() } | ||
| 33 | + engines.register("other") { FakeEngine() } | ||
| 34 | + | ||
| 35 | + #expect(engines.defaultName == "fake") | ||
| 36 | + #expect(try engines.make().name == "fake") | ||
| 37 | + #expect(engines.names == ["fake", "other"]) | ||
| 38 | + } | ||
| 39 | + | ||
| 40 | + @Test func unknownEngineListsTheAvailableOnes() { | ||
| 41 | + var engines = EngineRegistry() | ||
| 42 | + engines.register("fake") { FakeEngine() } | ||
| 43 | + #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { | ||
| 44 | + try engines.make("mlx") | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | +} | ||
deleted
Tests/RazorbillCoreTests/PromptTemplateTests.swift +0 -33 | deleted file mode 100644 | ||
| @@ -1,33 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -let fixedContext = TemplateContext( | |
| 6 | - date: Date(timeIntervalSince1970: 1_794_873_600), | |
| 7 | - currentDirectory: "/work", | |
| 8 | - environment: ["A": "1"], | |
| 9 | - timeZone: TimeZone(identifier: "UTC")! | |
| 10 | -) | |
| 11 | - | |
| 12 | -@Test func replacesEveryKnownVariable() throws { | |
| 13 | - #expect( | |
| 14 | - try PromptTemplate.render("{{date}} {{cwd}} {{env.A}}", context: fixedContext) | |
| 15 | - == "2026-11-17 /work 1") | |
| 16 | -} | |
| 17 | - | |
| 18 | -@Test func textWithoutVariablesIsUnchanged() throws { | |
| 19 | - #expect(try PromptTemplate.render("plain {text}", context: fixedContext) == "plain {text}") | |
| 20 | -} | |
| 21 | - | |
| 22 | -@Test func unclosedBracesAreKeptAsText() throws { | |
| 23 | - #expect(try PromptTemplate.render("a {{date", context: fixedContext) == "a {{date") | |
| 24 | -} | |
| 25 | - | |
| 26 | -@Test func unknownOrUnsetVariablesThrow() { | |
| 27 | - #expect(throws: PromptTemplate.UnresolvedVariable.self) { | |
| 28 | - try PromptTemplate.render("{{x}}", context: fixedContext) | |
| 29 | - } | |
| 30 | - #expect(throws: PromptTemplate.UnresolvedVariable.self) { | |
| 31 | - try PromptTemplate.render("{{env.B}}", context: fixedContext) | |
| 32 | - } | |
| 33 | -} | |
| deleted file mode 100644 | |||
| @@ -1,33 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -let fixedContext = TemplateContext( | ||
| 6 | - date: Date(timeIntervalSince1970: 1_794_873_600), | ||
| 7 | - currentDirectory: "/work", | ||
| 8 | - environment: ["A": "1"], | ||
| 9 | - timeZone: TimeZone(identifier: "UTC")! | ||
| 10 | -) | ||
| 11 | - | ||
| 12 | -@Test func replacesEveryKnownVariable() throws { | ||
| 13 | - #expect( | ||
| 14 | - try PromptTemplate.render("{{date}} {{cwd}} {{env.A}}", context: fixedContext) | ||
| 15 | - == "2026-11-17 /work 1") | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -@Test func textWithoutVariablesIsUnchanged() throws { | ||
| 19 | - #expect(try PromptTemplate.render("plain {text}", context: fixedContext) == "plain {text}") | ||
| 20 | -} | ||
| 21 | - | ||
| 22 | -@Test func unclosedBracesAreKeptAsText() throws { | ||
| 23 | - #expect(try PromptTemplate.render("a {{date", context: fixedContext) == "a {{date") | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -@Test func unknownOrUnsetVariablesThrow() { | ||
| 27 | - #expect(throws: PromptTemplate.UnresolvedVariable.self) { | ||
| 28 | - try PromptTemplate.render("{{x}}", context: fixedContext) | ||
| 29 | - } | ||
| 30 | - #expect(throws: PromptTemplate.UnresolvedVariable.self) { | ||
| 31 | - try PromptTemplate.render("{{env.B}}", context: fixedContext) | ||
| 32 | - } | ||
| 33 | -} | ||
added
Tests/RazorbillCoreTests/TestSupport.swift +9 -0 | new file mode 100644 | ||
| @@ -0,0 +1,9 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// A fresh temporary directory per test. | |
| 4 | +func temporaryDirectory() throws -> String { | |
| 5 | + let url = FileManager.default.temporaryDirectory.appendingPathComponent( | |
| 6 | + "rzb-\(UUID().uuidString)") | |
| 7 | + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | |
| 8 | + return url.path | |
| 9 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,9 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// A fresh temporary directory per test. | ||
| 4 | +func temporaryDirectory() throws -> String { | ||
| 5 | + let url = FileManager.default.temporaryDirectory.appendingPathComponent( | ||
| 6 | + "rzb-\(UUID().uuidString)") | ||
| 7 | + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) | ||
| 8 | + return url.path | ||
| 9 | +} | ||
deleted
Tests/RazorbillTUITests/ChatStateTests.swift +0 -118 | deleted file mode 100644 | ||
| @@ -1,118 +0,0 @@ | ||
| 1 | -import RazorbillCore | |
| 2 | -import RazorbillTUI | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -typealias Action = ChatState.Action | |
| 6 | - | |
| 7 | -func makeState(thinking: Bool = false) -> ChatState { | |
| 8 | - ChatState( | |
| 9 | - agentName: "helper", modelName: "org/m", engineName: "fake", showThinking: thinking, | |
| 10 | - showStats: true) | |
| 11 | -} | |
| 12 | - | |
| 13 | -/// Types `text` then presses `last`. | |
| 14 | -func type(_ text: String, then last: Key = .enter, into state: inout ChatState) -> Action { | |
| 15 | - for character in text { | |
| 16 | - _ = state.handle(.character(character)) | |
| 17 | - } | |
| 18 | - return state.handle(last) | |
| 19 | -} | |
| 20 | - | |
| 21 | -@Suite struct ChatStateKeys { | |
| 22 | - @Test func enterSendsTheInputAndClearsIt() { | |
| 23 | - var state = makeState() | |
| 24 | - #expect(type(" hi there ", into: &state) == .send("hi there")) | |
| 25 | - #expect(state.inputText.isEmpty) | |
| 26 | - #expect(state.handle(.enter) == .none) // empty input | |
| 27 | - } | |
| 28 | - | |
| 29 | - @Test func editingKeysMoveTheCursor() { | |
| 30 | - var state = makeState() | |
| 31 | - _ = type("abc", then: .arrowLeft, into: &state) | |
| 32 | - _ = state.handle(.backspace) | |
| 33 | - _ = state.handle(.character("X")) | |
| 34 | - #expect(state.inputText == "aXc") | |
| 35 | - _ = state.handle(.home) | |
| 36 | - _ = state.handle(.delete) | |
| 37 | - #expect(state.inputText == "Xc") | |
| 38 | - _ = state.handle(.control("u")) | |
| 39 | - #expect(state.inputText.isEmpty) | |
| 40 | - } | |
| 41 | - | |
| 42 | - @Test func controlKeysDependOnWhetherAnAnswerIsRunning() { | |
| 43 | - var state = makeState() | |
| 44 | - #expect(state.handle(.control("c")) == .quit) | |
| 45 | - #expect(state.handle(.control("n")) == .reset) | |
| 46 | - #expect(type("/exit", into: &state) == .quit) | |
| 47 | - | |
| 48 | - state.begin("q") | |
| 49 | - #expect(state.handle(.control("c")) == .stop) | |
| 50 | - #expect(state.handle(.control("n")) == .none) | |
| 51 | - #expect(type("another", into: &state) == .none) // one answer at a time | |
| 52 | - state.end() | |
| 53 | - #expect(state.handle(.enter) == .send("another")) | |
| 54 | - } | |
| 55 | - | |
| 56 | - @Test func confirmationsCaptureTheKeys() { | |
| 57 | - var state = makeState() | |
| 58 | - state.ask("bash wants to run: ls") | |
| 59 | - #expect(state.handle(.character("x")) == .none) | |
| 60 | - #expect(state.handle(.character("y")) == .answerConfirmation(true)) | |
| 61 | - #expect(state.handle(.enter) == .answerConfirmation(false)) | |
| 62 | - state.answered(true) | |
| 63 | - #expect(state.pendingConfirmation == nil) | |
| 64 | - #expect(state.blocks.last?.text == "(allowed)") | |
| 65 | - } | |
| 66 | -} | |
| 67 | - | |
| 68 | -@Suite struct ChatStateEvents { | |
| 69 | - @Test func streamedTextIsJoinedIntoOneBlock() { | |
| 70 | - var state = makeState() | |
| 71 | - state.begin("hi") | |
| 72 | - state.apply(.text("\nHel")) | |
| 73 | - state.apply(.text("lo")) | |
| 74 | - state.apply(.thinking("hm")) | |
| 75 | - state.apply(.toolCall(ToolCall(name: "bash", arguments: ["command": .string("ls")]))) | |
| 76 | - state.apply(.toolResult(name: "bash", output: ToolOutput("a\nb"))) | |
| 77 | - state.apply( | |
| 78 | - .stats(GenerationStats(promptTokens: 3, generatedTokens: 2, tokensPerSecond: 12.34))) | |
| 79 | - state.end() | |
| 80 | - | |
| 81 | - #expect( | |
| 82 | - state.blocks.map(\.kind) == [ | |
| 83 | - .user, .assistant, .thinking, .toolCall, .toolResult, .stats, | |
| 84 | - ]) | |
| 85 | - #expect(state.blocks[1].text == "Hello") | |
| 86 | - #expect(state.blocks[3].text == "→ bash command=ls") | |
| 87 | - #expect(state.blocks[5].text == "[3 prompt tokens, 2 generated, 12.3 tokens/s]") | |
| 88 | - #expect(state.lastSpeed == 12.34) | |
| 89 | - #expect(!state.isBusy) | |
| 90 | - } | |
| 91 | - | |
| 92 | - @Test func emptyThinkingMakesNoBlock() { | |
| 93 | - var state = makeState(thinking: true) | |
| 94 | - state.begin("hi") | |
| 95 | - state.apply(.thinking("\n\n")) | |
| 96 | - state.apply(.text("\nHi")) | |
| 97 | - #expect(state.blocks.map(\.kind) == [.user, .assistant]) | |
| 98 | - #expect(state.blocks[1].text == "Hi") | |
| 99 | - } | |
| 100 | - | |
| 101 | - @Test func errorsAndStopsAreShown() { | |
| 102 | - var state = makeState() | |
| 103 | - state.begin("a") | |
| 104 | - state.end(error: "boom") | |
| 105 | - state.begin("b") | |
| 106 | - state.end(stopped: true) | |
| 107 | - #expect(state.blocks.map(\.text).suffix(3) == ["error: boom", "b", "(stopped)"]) | |
| 108 | - } | |
| 109 | - | |
| 110 | - @Test func longToolResultsAreShortened() { | |
| 111 | - var state = makeState() | |
| 112 | - state.apply( | |
| 113 | - .toolResult( | |
| 114 | - name: "bash", | |
| 115 | - output: ToolOutput((1 ... 10).map(String.init).joined(separator: "\n")))) | |
| 116 | - #expect(state.blocks.last?.text == "← bash: 1\n2\n3\n4\n5\n6\n…") | |
| 117 | - } | |
| 118 | -} | |
| deleted file mode 100644 | |||
| @@ -1,118 +0,0 @@ | |||
| 1 | -import RazorbillCore | ||
| 2 | -import RazorbillTUI | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -typealias Action = ChatState.Action | ||
| 6 | - | ||
| 7 | -func makeState(thinking: Bool = false) -> ChatState { | ||
| 8 | - ChatState( | ||
| 9 | - agentName: "helper", modelName: "org/m", engineName: "fake", showThinking: thinking, | ||
| 10 | - showStats: true) | ||
| 11 | -} | ||
| 12 | - | ||
| 13 | -/// Types `text` then presses `last`. | ||
| 14 | -func type(_ text: String, then last: Key = .enter, into state: inout ChatState) -> Action { | ||
| 15 | - for character in text { | ||
| 16 | - _ = state.handle(.character(character)) | ||
| 17 | - } | ||
| 18 | - return state.handle(last) | ||
| 19 | -} | ||
| 20 | - | ||
| 21 | -@Suite struct ChatStateKeys { | ||
| 22 | - @Test func enterSendsTheInputAndClearsIt() { | ||
| 23 | - var state = makeState() | ||
| 24 | - #expect(type(" hi there ", into: &state) == .send("hi there")) | ||
| 25 | - #expect(state.inputText.isEmpty) | ||
| 26 | - #expect(state.handle(.enter) == .none) // empty input | ||
| 27 | - } | ||
| 28 | - | ||
| 29 | - @Test func editingKeysMoveTheCursor() { | ||
| 30 | - var state = makeState() | ||
| 31 | - _ = type("abc", then: .arrowLeft, into: &state) | ||
| 32 | - _ = state.handle(.backspace) | ||
| 33 | - _ = state.handle(.character("X")) | ||
| 34 | - #expect(state.inputText == "aXc") | ||
| 35 | - _ = state.handle(.home) | ||
| 36 | - _ = state.handle(.delete) | ||
| 37 | - #expect(state.inputText == "Xc") | ||
| 38 | - _ = state.handle(.control("u")) | ||
| 39 | - #expect(state.inputText.isEmpty) | ||
| 40 | - } | ||
| 41 | - | ||
| 42 | - @Test func controlKeysDependOnWhetherAnAnswerIsRunning() { | ||
| 43 | - var state = makeState() | ||
| 44 | - #expect(state.handle(.control("c")) == .quit) | ||
| 45 | - #expect(state.handle(.control("n")) == .reset) | ||
| 46 | - #expect(type("/exit", into: &state) == .quit) | ||
| 47 | - | ||
| 48 | - state.begin("q") | ||
| 49 | - #expect(state.handle(.control("c")) == .stop) | ||
| 50 | - #expect(state.handle(.control("n")) == .none) | ||
| 51 | - #expect(type("another", into: &state) == .none) // one answer at a time | ||
| 52 | - state.end() | ||
| 53 | - #expect(state.handle(.enter) == .send("another")) | ||
| 54 | - } | ||
| 55 | - | ||
| 56 | - @Test func confirmationsCaptureTheKeys() { | ||
| 57 | - var state = makeState() | ||
| 58 | - state.ask("bash wants to run: ls") | ||
| 59 | - #expect(state.handle(.character("x")) == .none) | ||
| 60 | - #expect(state.handle(.character("y")) == .answerConfirmation(true)) | ||
| 61 | - #expect(state.handle(.enter) == .answerConfirmation(false)) | ||
| 62 | - state.answered(true) | ||
| 63 | - #expect(state.pendingConfirmation == nil) | ||
| 64 | - #expect(state.blocks.last?.text == "(allowed)") | ||
| 65 | - } | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -@Suite struct ChatStateEvents { | ||
| 69 | - @Test func streamedTextIsJoinedIntoOneBlock() { | ||
| 70 | - var state = makeState() | ||
| 71 | - state.begin("hi") | ||
| 72 | - state.apply(.text("\nHel")) | ||
| 73 | - state.apply(.text("lo")) | ||
| 74 | - state.apply(.thinking("hm")) | ||
| 75 | - state.apply(.toolCall(ToolCall(name: "bash", arguments: ["command": .string("ls")]))) | ||
| 76 | - state.apply(.toolResult(name: "bash", output: ToolOutput("a\nb"))) | ||
| 77 | - state.apply( | ||
| 78 | - .stats(GenerationStats(promptTokens: 3, generatedTokens: 2, tokensPerSecond: 12.34))) | ||
| 79 | - state.end() | ||
| 80 | - | ||
| 81 | - #expect( | ||
| 82 | - state.blocks.map(\.kind) == [ | ||
| 83 | - .user, .assistant, .thinking, .toolCall, .toolResult, .stats, | ||
| 84 | - ]) | ||
| 85 | - #expect(state.blocks[1].text == "Hello") | ||
| 86 | - #expect(state.blocks[3].text == "→ bash command=ls") | ||
| 87 | - #expect(state.blocks[5].text == "[3 prompt tokens, 2 generated, 12.3 tokens/s]") | ||
| 88 | - #expect(state.lastSpeed == 12.34) | ||
| 89 | - #expect(!state.isBusy) | ||
| 90 | - } | ||
| 91 | - | ||
| 92 | - @Test func emptyThinkingMakesNoBlock() { | ||
| 93 | - var state = makeState(thinking: true) | ||
| 94 | - state.begin("hi") | ||
| 95 | - state.apply(.thinking("\n\n")) | ||
| 96 | - state.apply(.text("\nHi")) | ||
| 97 | - #expect(state.blocks.map(\.kind) == [.user, .assistant]) | ||
| 98 | - #expect(state.blocks[1].text == "Hi") | ||
| 99 | - } | ||
| 100 | - | ||
| 101 | - @Test func errorsAndStopsAreShown() { | ||
| 102 | - var state = makeState() | ||
| 103 | - state.begin("a") | ||
| 104 | - state.end(error: "boom") | ||
| 105 | - state.begin("b") | ||
| 106 | - state.end(stopped: true) | ||
| 107 | - #expect(state.blocks.map(\.text).suffix(3) == ["error: boom", "b", "(stopped)"]) | ||
| 108 | - } | ||
| 109 | - | ||
| 110 | - @Test func longToolResultsAreShortened() { | ||
| 111 | - var state = makeState() | ||
| 112 | - state.apply( | ||
| 113 | - .toolResult( | ||
| 114 | - name: "bash", | ||
| 115 | - output: ToolOutput((1 ... 10).map(String.init).joined(separator: "\n")))) | ||
| 116 | - #expect(state.blocks.last?.text == "← bash: 1\n2\n3\n4\n5\n6\n…") | ||
| 117 | - } | ||
| 118 | -} | ||
deleted
Tests/RazorbillTUITests/KeyAndLayoutTests.swift +0 -61 | deleted file mode 100644 | ||
| @@ -1,61 +0,0 @@ | ||
| 1 | -import RazorbillTUI | |
| 2 | -import Testing | |
| 3 | - | |
| 4 | -@Suite struct KeyDecoding { | |
| 5 | - func decode(_ bytes: [UInt8]) -> [Key] { | |
| 6 | - var decoder = KeyDecoder() | |
| 7 | - return decoder.decode(bytes) | |
| 8 | - } | |
| 9 | - | |
| 10 | - @Test func printableAndUnicodeCharacters() { | |
| 11 | - #expect(decode(Array("hé🙂".utf8)) == [.character("h"), .character("é"), .character("🙂")]) | |
| 12 | - } | |
| 13 | - | |
| 14 | - @Test func controlKeys() { | |
| 15 | - #expect( | |
| 16 | - decode([13, 127, 9, 3, 4, 20]) == [ | |
| 17 | - .enter, .backspace, .tab, .control("c"), .control("d"), .control("t"), | |
| 18 | - ]) | |
| 19 | - } | |
| 20 | - | |
| 21 | - @Test func escapeSequences() { | |
| 22 | - #expect( | |
| 23 | - decode([27, 91, 65, 27, 91, 66, 27, 91, 67, 27, 91, 68]) == [ | |
| 24 | - .arrowUp, .arrowDown, .arrowRight, .arrowLeft, | |
| 25 | - ]) | |
| 26 | - #expect( | |
| 27 | - decode(Array("\u{1B}[5~\u{1B}[6~\u{1B}[3~\u{1B}[H\u{1B}[F".utf8)) == [ | |
| 28 | - .pageUp, .pageDown, .delete, .home, .end, | |
| 29 | - ]) | |
| 30 | - #expect(decode([27, 79, 72]) == [.home]) | |
| 31 | - } | |
| 32 | - | |
| 33 | - @Test func sequencesCutBetweenReadsAreJoined() { | |
| 34 | - var decoder = KeyDecoder() | |
| 35 | - #expect(decoder.decode([27]).isEmpty) | |
| 36 | - #expect(decoder.decode([91]).isEmpty) | |
| 37 | - #expect(decoder.decode([65]) == [.arrowUp]) | |
| 38 | - let euro = Array("€".utf8) | |
| 39 | - #expect(decoder.decode(Array(euro.prefix(2))).isEmpty) | |
| 40 | - #expect(decoder.decode(Array(euro.suffix(1))) == [.character("€")]) | |
| 41 | - } | |
| 42 | - | |
| 43 | - @Test func aLoneEscapeIsTheEscapeKeyOnceInputPauses() { | |
| 44 | - var decoder = KeyDecoder() | |
| 45 | - #expect(decoder.decode([27]).isEmpty) | |
| 46 | - #expect(decoder.flush() == [.escape]) | |
| 47 | - } | |
| 48 | -} | |
| 49 | - | |
| 50 | -@Suite struct Layout { | |
| 51 | - @Test func wrapsAtSpacesAndCutsLongWords() { | |
| 52 | - #expect(TextLayout.wrap("hello wide world", width: 10) == ["hello wide", "world"]) | |
| 53 | - #expect(TextLayout.wrap("abcdefghij", width: 4) == ["abcd", "efgh", "ij"]) | |
| 54 | - #expect(TextLayout.wrap("a\n\nb", width: 5) == ["a", "", "b"]) | |
| 55 | - } | |
| 56 | - | |
| 57 | - @Test func truncatesWithAnEllipsis() { | |
| 58 | - #expect(TextLayout.truncate("abcdef", width: 4) == "abc…") | |
| 59 | - #expect(TextLayout.truncate("abc", width: 4) == "abc") | |
| 60 | - } | |
| 61 | -} | |
| deleted file mode 100644 | |||
| @@ -1,61 +0,0 @@ | |||
| 1 | -import RazorbillTUI | ||
| 2 | -import Testing | ||
| 3 | - | ||
| 4 | -@Suite struct KeyDecoding { | ||
| 5 | - func decode(_ bytes: [UInt8]) -> [Key] { | ||
| 6 | - var decoder = KeyDecoder() | ||
| 7 | - return decoder.decode(bytes) | ||
| 8 | - } | ||
| 9 | - | ||
| 10 | - @Test func printableAndUnicodeCharacters() { | ||
| 11 | - #expect(decode(Array("hé🙂".utf8)) == [.character("h"), .character("é"), .character("🙂")]) | ||
| 12 | - } | ||
| 13 | - | ||
| 14 | - @Test func controlKeys() { | ||
| 15 | - #expect( | ||
| 16 | - decode([13, 127, 9, 3, 4, 20]) == [ | ||
| 17 | - .enter, .backspace, .tab, .control("c"), .control("d"), .control("t"), | ||
| 18 | - ]) | ||
| 19 | - } | ||
| 20 | - | ||
| 21 | - @Test func escapeSequences() { | ||
| 22 | - #expect( | ||
| 23 | - decode([27, 91, 65, 27, 91, 66, 27, 91, 67, 27, 91, 68]) == [ | ||
| 24 | - .arrowUp, .arrowDown, .arrowRight, .arrowLeft, | ||
| 25 | - ]) | ||
| 26 | - #expect( | ||
| 27 | - decode(Array("\u{1B}[5~\u{1B}[6~\u{1B}[3~\u{1B}[H\u{1B}[F".utf8)) == [ | ||
| 28 | - .pageUp, .pageDown, .delete, .home, .end, | ||
| 29 | - ]) | ||
| 30 | - #expect(decode([27, 79, 72]) == [.home]) | ||
| 31 | - } | ||
| 32 | - | ||
| 33 | - @Test func sequencesCutBetweenReadsAreJoined() { | ||
| 34 | - var decoder = KeyDecoder() | ||
| 35 | - #expect(decoder.decode([27]).isEmpty) | ||
| 36 | - #expect(decoder.decode([91]).isEmpty) | ||
| 37 | - #expect(decoder.decode([65]) == [.arrowUp]) | ||
| 38 | - let euro = Array("€".utf8) | ||
| 39 | - #expect(decoder.decode(Array(euro.prefix(2))).isEmpty) | ||
| 40 | - #expect(decoder.decode(Array(euro.suffix(1))) == [.character("€")]) | ||
| 41 | - } | ||
| 42 | - | ||
| 43 | - @Test func aLoneEscapeIsTheEscapeKeyOnceInputPauses() { | ||
| 44 | - var decoder = KeyDecoder() | ||
| 45 | - #expect(decoder.decode([27]).isEmpty) | ||
| 46 | - #expect(decoder.flush() == [.escape]) | ||
| 47 | - } | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -@Suite struct Layout { | ||
| 51 | - @Test func wrapsAtSpacesAndCutsLongWords() { | ||
| 52 | - #expect(TextLayout.wrap("hello wide world", width: 10) == ["hello wide", "world"]) | ||
| 53 | - #expect(TextLayout.wrap("abcdefghij", width: 4) == ["abcd", "efgh", "ij"]) | ||
| 54 | - #expect(TextLayout.wrap("a\n\nb", width: 5) == ["a", "", "b"]) | ||
| 55 | - } | ||
| 56 | - | ||
| 57 | - @Test func truncatesWithAnEllipsis() { | ||
| 58 | - #expect(TextLayout.truncate("abcdef", width: 4) == "abc…") | ||
| 59 | - #expect(TextLayout.truncate("abc", width: 4) == "abc") | ||
| 60 | - } | ||
| 61 | -} | ||
deleted
Tests/RazorbillTUITests/RendererTests.swift +0 -76 | deleted file mode 100644 | ||
| @@ -1,76 +0,0 @@ | ||
| 1 | -import RazorbillCore | |
| 2 | -import RazorbillTUI | |
| 3 | -import Testing | |
| 4 | - | |
| 5 | -@Suite struct Rendering { | |
| 6 | - let renderer = ScreenRenderer(colors: false) | |
| 7 | - | |
| 8 | - @Test func layoutHasTitleConversationHelpAndInput() { | |
| 9 | - var state = makeState() | |
| 10 | - state.begin("hi") | |
| 11 | - state.apply(.text("Hello!")) | |
| 12 | - state.end() | |
| 13 | - _ = type("draft", then: .arrowLeft, into: &state) | |
| 14 | - | |
| 15 | - let screen = renderer.render(state, rows: 6, columns: 30) | |
| 16 | - | |
| 17 | - #expect(screen.lines.count == 6) | |
| 18 | - #expect(screen.lines[0].hasPrefix(" rzb · helper · org/m · fake")) | |
| 19 | - #expect(screen.lines[0].count == 30) | |
| 20 | - #expect(Array(screen.lines[1 ... 3]) == ["› hi", "Hello!", ""]) | |
| 21 | - #expect(screen.lines[4].hasPrefix("Enter send")) | |
| 22 | - #expect(screen.lines[5] == "› draft") | |
| 23 | - #expect(screen.cursorRow == 5) | |
| 24 | - #expect(screen.cursorColumn == 6) | |
| 25 | - } | |
| 26 | - | |
| 27 | - @Test func conversationFollowsTheBottomUnlessScrolled() { | |
| 28 | - var state = makeState() | |
| 29 | - for number in 1 ... 5 { | |
| 30 | - state.begin("q\(number)") | |
| 31 | - state.end() | |
| 32 | - } | |
| 33 | - // 5 prompts separated by blank lines: 9 lines, 3 visible. | |
| 34 | - #expect( | |
| 35 | - Array(renderer.render(state, rows: 6, columns: 20).lines[1 ... 3]) == [ | |
| 36 | - "› q4", "", "› q5", | |
| 37 | - ]) | |
| 38 | - | |
| 39 | - _ = state.handle(.arrowUp) | |
| 40 | - _ = state.handle(.arrowUp) | |
| 41 | - let scrolled = renderer.render(state, rows: 6, columns: 40) | |
| 42 | - #expect(Array(scrolled.lines[1 ... 3]) == ["› q3", "", "› q4"]) | |
| 43 | - #expect(scrolled.lines[0].contains("↑ scrolled")) | |
| 44 | - } | |
| 45 | - | |
| 46 | - @Test func thinkingIsHiddenUntilToggled() { | |
| 47 | - var state = makeState() | |
| 48 | - state.apply(.thinking("secret")) | |
| 49 | - #expect(!renderer.render(state, rows: 5, columns: 20).lines.contains("secret")) | |
| 50 | - _ = state.handle(.control("t")) | |
| 51 | - #expect(renderer.render(state, rows: 5, columns: 20).lines.contains("secret")) | |
| 52 | - } | |
| 53 | - | |
| 54 | - @Test func pendingConfirmationReplacesTheHelpLine() { | |
| 55 | - var state = makeState() | |
| 56 | - state.ask("bash wants to run: ls") | |
| 57 | - #expect( | |
| 58 | - renderer.render(state, rows: 5, columns: 60).lines[3] | |
| 59 | - == "bash wants to run: ls Allow? (y/n)") | |
| 60 | - } | |
| 61 | - | |
| 62 | - @Test func longInputKeepsTheCursorVisible() { | |
| 63 | - var state = makeState() | |
| 64 | - _ = type(String(repeating: "x", count: 50), then: .end, into: &state) | |
| 65 | - let screen = renderer.render(state, rows: 5, columns: 20) | |
| 66 | - #expect(screen.lines[4].count <= 20) | |
| 67 | - #expect(screen.cursorColumn < 20) | |
| 68 | - } | |
| 69 | - | |
| 70 | - @Test func colorsWrapStyledLinesInEscapeCodes() { | |
| 71 | - var state = makeState() | |
| 72 | - state.begin("hi") | |
| 73 | - let line = ScreenRenderer(colors: true).render(state, rows: 5, columns: 20).lines[1] | |
| 74 | - #expect(line == "\u{1B}[1m› hi\u{1B}[0m") | |
| 75 | - } | |
| 76 | -} | |
| deleted file mode 100644 | |||
| @@ -1,76 +0,0 @@ | |||
| 1 | -import RazorbillCore | ||
| 2 | -import RazorbillTUI | ||
| 3 | -import Testing | ||
| 4 | - | ||
| 5 | -@Suite struct Rendering { | ||
| 6 | - let renderer = ScreenRenderer(colors: false) | ||
| 7 | - | ||
| 8 | - @Test func layoutHasTitleConversationHelpAndInput() { | ||
| 9 | - var state = makeState() | ||
| 10 | - state.begin("hi") | ||
| 11 | - state.apply(.text("Hello!")) | ||
| 12 | - state.end() | ||
| 13 | - _ = type("draft", then: .arrowLeft, into: &state) | ||
| 14 | - | ||
| 15 | - let screen = renderer.render(state, rows: 6, columns: 30) | ||
| 16 | - | ||
| 17 | - #expect(screen.lines.count == 6) | ||
| 18 | - #expect(screen.lines[0].hasPrefix(" rzb · helper · org/m · fake")) | ||
| 19 | - #expect(screen.lines[0].count == 30) | ||
| 20 | - #expect(Array(screen.lines[1 ... 3]) == ["› hi", "Hello!", ""]) | ||
| 21 | - #expect(screen.lines[4].hasPrefix("Enter send")) | ||
| 22 | - #expect(screen.lines[5] == "› draft") | ||
| 23 | - #expect(screen.cursorRow == 5) | ||
| 24 | - #expect(screen.cursorColumn == 6) | ||
| 25 | - } | ||
| 26 | - | ||
| 27 | - @Test func conversationFollowsTheBottomUnlessScrolled() { | ||
| 28 | - var state = makeState() | ||
| 29 | - for number in 1 ... 5 { | ||
| 30 | - state.begin("q\(number)") | ||
| 31 | - state.end() | ||
| 32 | - } | ||
| 33 | - // 5 prompts separated by blank lines: 9 lines, 3 visible. | ||
| 34 | - #expect( | ||
| 35 | - Array(renderer.render(state, rows: 6, columns: 20).lines[1 ... 3]) == [ | ||
| 36 | - "› q4", "", "› q5", | ||
| 37 | - ]) | ||
| 38 | - | ||
| 39 | - _ = state.handle(.arrowUp) | ||
| 40 | - _ = state.handle(.arrowUp) | ||
| 41 | - let scrolled = renderer.render(state, rows: 6, columns: 40) | ||
| 42 | - #expect(Array(scrolled.lines[1 ... 3]) == ["› q3", "", "› q4"]) | ||
| 43 | - #expect(scrolled.lines[0].contains("↑ scrolled")) | ||
| 44 | - } | ||
| 45 | - | ||
| 46 | - @Test func thinkingIsHiddenUntilToggled() { | ||
| 47 | - var state = makeState() | ||
| 48 | - state.apply(.thinking("secret")) | ||
| 49 | - #expect(!renderer.render(state, rows: 5, columns: 20).lines.contains("secret")) | ||
| 50 | - _ = state.handle(.control("t")) | ||
| 51 | - #expect(renderer.render(state, rows: 5, columns: 20).lines.contains("secret")) | ||
| 52 | - } | ||
| 53 | - | ||
| 54 | - @Test func pendingConfirmationReplacesTheHelpLine() { | ||
| 55 | - var state = makeState() | ||
| 56 | - state.ask("bash wants to run: ls") | ||
| 57 | - #expect( | ||
| 58 | - renderer.render(state, rows: 5, columns: 60).lines[3] | ||
| 59 | - == "bash wants to run: ls Allow? (y/n)") | ||
| 60 | - } | ||
| 61 | - | ||
| 62 | - @Test func longInputKeepsTheCursorVisible() { | ||
| 63 | - var state = makeState() | ||
| 64 | - _ = type(String(repeating: "x", count: 50), then: .end, into: &state) | ||
| 65 | - let screen = renderer.render(state, rows: 5, columns: 20) | ||
| 66 | - #expect(screen.lines[4].count <= 20) | ||
| 67 | - #expect(screen.cursorColumn < 20) | ||
| 68 | - } | ||
| 69 | - | ||
| 70 | - @Test func colorsWrapStyledLinesInEscapeCodes() { | ||
| 71 | - var state = makeState() | ||
| 72 | - state.begin("hi") | ||
| 73 | - let line = ScreenRenderer(colors: true).render(state, rows: 5, columns: 20).lines[1] | ||
| 74 | - #expect(line == "\u{1B}[1m› hi\u{1B}[0m") | ||
| 75 | - } | ||
| 76 | -} | ||
deleted
Tests/RazorbillTUITests/TUIAppTests.swift +0 -127 | deleted file mode 100644 | ||
| @@ -1,127 +0,0 @@ | ||
| 1 | -import Foundation | |
| 2 | -import RazorbillCore | |
| 3 | -import RazorbillTUI | |
| 4 | -import Testing | |
| 5 | - | |
| 6 | -/// A terminal driven by the test: keys are pushed, screens are recorded. | |
| 7 | -final class FakeTerminal: Terminal, @unchecked Sendable { | |
| 8 | - private let lock = NSLock() | |
| 9 | - private var drawn: [ScreenRenderer.Screen] = [] | |
| 10 | - private var entered = 0 | |
| 11 | - private var left = 0 | |
| 12 | - private let stream: AsyncStream<Key> | |
| 13 | - private let continuation: AsyncStream<Key>.Continuation | |
| 14 | - let size = (rows: 12, columns: 60) | |
| 15 | - | |
| 16 | - init() { | |
| 17 | - (stream, continuation) = AsyncStream<Key>.makeStream() | |
| 18 | - } | |
| 19 | - | |
| 20 | - func enter() { lock.withLock { entered += 1 } } | |
| 21 | - func leave() { lock.withLock { left += 1 } } | |
| 22 | - func keys() -> AsyncStream<Key> { stream } | |
| 23 | - func draw(_ screen: ScreenRenderer.Screen) { lock.withLock { drawn.append(screen) } } | |
| 24 | - | |
| 25 | - func press(_ keys: Key...) { | |
| 26 | - for key in keys { continuation.yield(key) } | |
| 27 | - } | |
| 28 | - | |
| 29 | - func type(_ text: String) { | |
| 30 | - for character in text { continuation.yield(.character(character)) } | |
| 31 | - continuation.yield(.enter) | |
| 32 | - } | |
| 33 | - | |
| 34 | - func close() { continuation.finish() } | |
| 35 | - | |
| 36 | - var lastScreen: [String] { lock.withLock { drawn.last?.lines ?? [] } } | |
| 37 | - var enteredAndLeft: (Int, Int) { lock.withLock { (entered, left) } } | |
| 38 | -} | |
| 39 | - | |
| 40 | -/// Waits (up to 5 s) until `condition` holds for the app's state. | |
| 41 | -func waitFor(_ app: TUIApp, _ condition: @Sendable (ChatState) -> Bool) async throws { | |
| 42 | - for _ in 0 ..< 500 { | |
| 43 | - if condition(await app.currentState) { return } | |
| 44 | - try await Task.sleep(for: .milliseconds(10)) | |
| 45 | - } | |
| 46 | - Issue.record("condition not reached") | |
| 47 | -} | |
| 48 | - | |
| 49 | -let tuiConfig = AgentConfig(name: "helper", model: .huggingFace(id: "org/m", revision: "main")) | |
| 50 | - | |
| 51 | -@Suite struct TUIAppRuns { | |
| 52 | - @Test func sendsPromptsShowsAnswersAndRestoresTheTerminal() async throws { | |
| 53 | - let terminal = FakeTerminal() | |
| 54 | - let bridge = ConfirmationBridge() | |
| 55 | - let agent = Agent(config: tuiConfig, engine: FakeEngine(), toolContext: bridge.toolContext) | |
| 56 | - let app = TUIApp(agent: agent, terminal: terminal, bridge: bridge, colors: false) | |
| 57 | - let running = Task { await app.run() } | |
| 58 | - | |
| 59 | - terminal.type("hello") | |
| 60 | - try await waitFor(app) { state in | |
| 61 | - !state.isBusy && state.blocks.contains { $0.text == "echo: hello" } | |
| 62 | - } | |
| 63 | - terminal.press(.control("d")) | |
| 64 | - await running.value | |
| 65 | - | |
| 66 | - #expect(terminal.lastScreen.contains("echo: hello")) | |
| 67 | - #expect(terminal.enteredAndLeft == (1, 1)) | |
| 68 | - } | |
| 69 | - | |
| 70 | - @Test func toolConfirmationsAreAnsweredInTheScreen() async throws { | |
| 71 | - let call = ToolCall(name: "bash", arguments: ["command": .string("echo from-tui")]) | |
| 72 | - let engine = FakeEngine(script: [[.toolCall(call)], [.text("done")]]) | |
| 73 | - let terminal = FakeTerminal() | |
| 74 | - let bridge = ConfirmationBridge() | |
| 75 | - let directory = FileManager.default.temporaryDirectory.path | |
| 76 | - let agent = Agent( | |
| 77 | - config: tuiConfig, engine: engine, tools: [BashTool(workingDirectory: directory)], | |
| 78 | - toolContext: bridge.toolContext) | |
| 79 | - let app = TUIApp(agent: agent, terminal: terminal, bridge: bridge, colors: false) | |
| 80 | - let running = Task { await app.run() } | |
| 81 | - | |
| 82 | - terminal.type("run it") | |
| 83 | - try await waitFor(app) { | |
| 84 | - $0.pendingConfirmation?.hasPrefix("bash wants to run: echo from-tui") == true | |
| 85 | - } | |
| 86 | - terminal.press(.character("y")) | |
| 87 | - try await waitFor(app) { state in | |
| 88 | - !state.isBusy && state.blocks.contains { $0.text == "done" } | |
| 89 | - } | |
| 90 | - terminal.close() | |
| 91 | - await running.value | |
| 92 | - | |
| 93 | - #expect(engine.receivedMessages.last?.first?.content == "exit code: 0\nstdout:\nfrom-tui\n") | |
| 94 | - } | |
| 95 | - | |
| 96 | - @Test func resetStartsANewConversation() async throws { | |
| 97 | - let terminal = FakeTerminal() | |
| 98 | - let bridge = ConfirmationBridge() | |
| 99 | - let engine = FakeEngine() | |
| 100 | - let app = TUIApp( | |
| 101 | - agent: Agent(config: tuiConfig, engine: engine, toolContext: bridge.toolContext), | |
| 102 | - terminal: terminal, bridge: bridge, colors: false) | |
| 103 | - let running = Task { await app.run() } | |
| 104 | - | |
| 105 | - terminal.type("one") | |
| 106 | - try await waitFor(app) { !$0.isBusy && $0.blocks.count >= 2 } | |
| 107 | - terminal.press(.control("n")) | |
| 108 | - try await waitFor(app) { $0.blocks.map(\.text) == ["(new conversation)"] } | |
| 109 | - terminal.type("two") | |
| 110 | - try await waitFor(app) { !$0.isBusy && $0.blocks.count >= 3 } | |
| 111 | - terminal.close() | |
| 112 | - await running.value | |
| 113 | - | |
| 114 | - #expect(engine.sessionSetups.count == 2) | |
| 115 | - } | |
| 116 | -} | |
| 117 | - | |
| 118 | -@Test func theFileDecidesWhetherThinkingStartsShown() async { | |
| 119 | - var hidden = tuiConfig | |
| 120 | - hidden.userInterface.showThinking = false | |
| 121 | - for (config, expected) in [(tuiConfig, true), (hidden, false)] { | |
| 122 | - let bridge = ConfirmationBridge() | |
| 123 | - let agent = Agent(config: config, engine: FakeEngine(), toolContext: bridge.toolContext) | |
| 124 | - let app = TUIApp(agent: agent, terminal: FakeTerminal(), bridge: bridge, colors: false) | |
| 125 | - #expect(await app.currentState.showThinking == expected) | |
| 126 | - } | |
| 127 | -} | |
| deleted file mode 100644 | |||
| @@ -1,127 +0,0 @@ | |||
| 1 | -import Foundation | ||
| 2 | -import RazorbillCore | ||
| 3 | -import RazorbillTUI | ||
| 4 | -import Testing | ||
| 5 | - | ||
| 6 | -/// A terminal driven by the test: keys are pushed, screens are recorded. | ||
| 7 | -final class FakeTerminal: Terminal, @unchecked Sendable { | ||
| 8 | - private let lock = NSLock() | ||
| 9 | - private var drawn: [ScreenRenderer.Screen] = [] | ||
| 10 | - private var entered = 0 | ||
| 11 | - private var left = 0 | ||
| 12 | - private let stream: AsyncStream<Key> | ||
| 13 | - private let continuation: AsyncStream<Key>.Continuation | ||
| 14 | - let size = (rows: 12, columns: 60) | ||
| 15 | - | ||
| 16 | - init() { | ||
| 17 | - (stream, continuation) = AsyncStream<Key>.makeStream() | ||
| 18 | - } | ||
| 19 | - | ||
| 20 | - func enter() { lock.withLock { entered += 1 } } | ||
| 21 | - func leave() { lock.withLock { left += 1 } } | ||
| 22 | - func keys() -> AsyncStream<Key> { stream } | ||
| 23 | - func draw(_ screen: ScreenRenderer.Screen) { lock.withLock { drawn.append(screen) } } | ||
| 24 | - | ||
| 25 | - func press(_ keys: Key...) { | ||
| 26 | - for key in keys { continuation.yield(key) } | ||
| 27 | - } | ||
| 28 | - | ||
| 29 | - func type(_ text: String) { | ||
| 30 | - for character in text { continuation.yield(.character(character)) } | ||
| 31 | - continuation.yield(.enter) | ||
| 32 | - } | ||
| 33 | - | ||
| 34 | - func close() { continuation.finish() } | ||
| 35 | - | ||
| 36 | - var lastScreen: [String] { lock.withLock { drawn.last?.lines ?? [] } } | ||
| 37 | - var enteredAndLeft: (Int, Int) { lock.withLock { (entered, left) } } | ||
| 38 | -} | ||
| 39 | - | ||
| 40 | -/// Waits (up to 5 s) until `condition` holds for the app's state. | ||
| 41 | -func waitFor(_ app: TUIApp, _ condition: @Sendable (ChatState) -> Bool) async throws { | ||
| 42 | - for _ in 0 ..< 500 { | ||
| 43 | - if condition(await app.currentState) { return } | ||
| 44 | - try await Task.sleep(for: .milliseconds(10)) | ||
| 45 | - } | ||
| 46 | - Issue.record("condition not reached") | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -let tuiConfig = AgentConfig(name: "helper", model: .huggingFace(id: "org/m", revision: "main")) | ||
| 50 | - | ||
| 51 | -@Suite struct TUIAppRuns { | ||
| 52 | - @Test func sendsPromptsShowsAnswersAndRestoresTheTerminal() async throws { | ||
| 53 | - let terminal = FakeTerminal() | ||
| 54 | - let bridge = ConfirmationBridge() | ||
| 55 | - let agent = Agent(config: tuiConfig, engine: FakeEngine(), toolContext: bridge.toolContext) | ||
| 56 | - let app = TUIApp(agent: agent, terminal: terminal, bridge: bridge, colors: false) | ||
| 57 | - let running = Task { await app.run() } | ||
| 58 | - | ||
| 59 | - terminal.type("hello") | ||
| 60 | - try await waitFor(app) { state in | ||
| 61 | - !state.isBusy && state.blocks.contains { $0.text == "echo: hello" } | ||
| 62 | - } | ||
| 63 | - terminal.press(.control("d")) | ||
| 64 | - await running.value | ||
| 65 | - | ||
| 66 | - #expect(terminal.lastScreen.contains("echo: hello")) | ||
| 67 | - #expect(terminal.enteredAndLeft == (1, 1)) | ||
| 68 | - } | ||
| 69 | - | ||
| 70 | - @Test func toolConfirmationsAreAnsweredInTheScreen() async throws { | ||
| 71 | - let call = ToolCall(name: "bash", arguments: ["command": .string("echo from-tui")]) | ||
| 72 | - let engine = FakeEngine(script: [[.toolCall(call)], [.text("done")]]) | ||
| 73 | - let terminal = FakeTerminal() | ||
| 74 | - let bridge = ConfirmationBridge() | ||
| 75 | - let directory = FileManager.default.temporaryDirectory.path | ||
| 76 | - let agent = Agent( | ||
| 77 | - config: tuiConfig, engine: engine, tools: [BashTool(workingDirectory: directory)], | ||
| 78 | - toolContext: bridge.toolContext) | ||
| 79 | - let app = TUIApp(agent: agent, terminal: terminal, bridge: bridge, colors: false) | ||
| 80 | - let running = Task { await app.run() } | ||
| 81 | - | ||
| 82 | - terminal.type("run it") | ||
| 83 | - try await waitFor(app) { | ||
| 84 | - $0.pendingConfirmation?.hasPrefix("bash wants to run: echo from-tui") == true | ||
| 85 | - } | ||
| 86 | - terminal.press(.character("y")) | ||
| 87 | - try await waitFor(app) { state in | ||
| 88 | - !state.isBusy && state.blocks.contains { $0.text == "done" } | ||
| 89 | - } | ||
| 90 | - terminal.close() | ||
| 91 | - await running.value | ||
| 92 | - | ||
| 93 | - #expect(engine.receivedMessages.last?.first?.content == "exit code: 0\nstdout:\nfrom-tui\n") | ||
| 94 | - } | ||
| 95 | - | ||
| 96 | - @Test func resetStartsANewConversation() async throws { | ||
| 97 | - let terminal = FakeTerminal() | ||
| 98 | - let bridge = ConfirmationBridge() | ||
| 99 | - let engine = FakeEngine() | ||
| 100 | - let app = TUIApp( | ||
| 101 | - agent: Agent(config: tuiConfig, engine: engine, toolContext: bridge.toolContext), | ||
| 102 | - terminal: terminal, bridge: bridge, colors: false) | ||
| 103 | - let running = Task { await app.run() } | ||
| 104 | - | ||
| 105 | - terminal.type("one") | ||
| 106 | - try await waitFor(app) { !$0.isBusy && $0.blocks.count >= 2 } | ||
| 107 | - terminal.press(.control("n")) | ||
| 108 | - try await waitFor(app) { $0.blocks.map(\.text) == ["(new conversation)"] } | ||
| 109 | - terminal.type("two") | ||
| 110 | - try await waitFor(app) { !$0.isBusy && $0.blocks.count >= 3 } | ||
| 111 | - terminal.close() | ||
| 112 | - await running.value | ||
| 113 | - | ||
| 114 | - #expect(engine.sessionSetups.count == 2) | ||
| 115 | - } | ||
| 116 | -} | ||
| 117 | - | ||
| 118 | -@Test func theFileDecidesWhetherThinkingStartsShown() async { | ||
| 119 | - var hidden = tuiConfig | ||
| 120 | - hidden.userInterface.showThinking = false | ||
| 121 | - for (config, expected) in [(tuiConfig, true), (hidden, false)] { | ||
| 122 | - let bridge = ConfirmationBridge() | ||
| 123 | - let agent = Agent(config: config, engine: FakeEngine(), toolContext: bridge.toolContext) | ||
| 124 | - let app = TUIApp(agent: agent, terminal: FakeTerminal(), bridge: bridge, colors: false) | ||
| 125 | - #expect(await app.currentState.showThinking == expected) | ||
| 126 | - } | ||
| 127 | -} | ||
deleted
examples/agent.yaml +0 -35 | deleted file mode 100644 | ||
| @@ -1,35 +0,0 @@ | ||
| 1 | -# A razorbill agent. Use it with: rzb chat --config examples/agent.yaml | |
| 2 | -# Every key except `name` and `model` is optional; the values below are the defaults | |
| 3 | -# unless a comment says otherwise. | |
| 4 | - | |
| 5 | -name: swift-helper # required, shown in the UI | |
| 6 | -description: Helps with Swift questions | |
| 7 | - | |
| 8 | -# The model: a Hugging Face id (MLX format, usually from mlx-community) ... | |
| 9 | -model: | |
| 10 | - id: mlx-community/Qwen3-1.7B-4bit | |
| 11 | - revision: main | |
| 12 | -# ... or a local MLX model directory (relative paths start at this file's folder): | |
| 13 | -# model: | |
| 14 | -# path: ~/models/my-model | |
| 15 | - | |
| 16 | -generation: | |
| 17 | - temperature: 0.6 # 0 = deterministic | |
| 18 | - top_p: 1.0 # (0, 1] | |
| 19 | - max_tokens: 1024 # per answer | |
| 20 | - thinking: false # let reasoning models (Qwen3...) think first | |
| 21 | - # thinking_budget: 512 # most thinking tokens before answering (default: no limit) | |
| 22 | - | |
| 23 | -# System prompt. Variables: {{date}} (YYYY-MM-DD), {{cwd}}, {{env.NAME}}. | |
| 24 | -system: | | |
| 25 | - You are a concise Swift expert. Today is {{date}}. | |
| 26 | - The user works in {{cwd}}. | |
| 27 | - | |
| 28 | -# Built-in tools, enabled by being listed. Not set = no tools. | |
| 29 | -tools: | |
| 30 | - bash: | |
| 31 | - confirm: true # ask before running each command | |
| 32 | - | |
| 33 | -ui: | |
| 34 | - show_stats: true # print tokens and speed after each answer | |
| 35 | - show_thinking: true # show the reasoning when the model thinks (TUI: Ctrl-T) | |
| deleted file mode 100644 | |||
| @@ -1,35 +0,0 @@ | |||
| 1 | -# A razorbill agent. Use it with: rzb chat --config examples/agent.yaml | ||
| 2 | -# Every key except `name` and `model` is optional; the values below are the defaults | ||
| 3 | -# unless a comment says otherwise. | ||
| 4 | - | ||
| 5 | -name: swift-helper # required, shown in the UI | ||
| 6 | -description: Helps with Swift questions | ||
| 7 | - | ||
| 8 | -# The model: a Hugging Face id (MLX format, usually from mlx-community) ... | ||
| 9 | -model: | ||
| 10 | - id: mlx-community/Qwen3-1.7B-4bit | ||
| 11 | - revision: main | ||
| 12 | -# ... or a local MLX model directory (relative paths start at this file's folder): | ||
| 13 | -# model: | ||
| 14 | -# path: ~/models/my-model | ||
| 15 | - | ||
| 16 | -generation: | ||
| 17 | - temperature: 0.6 # 0 = deterministic | ||
| 18 | - top_p: 1.0 # (0, 1] | ||
| 19 | - max_tokens: 1024 # per answer | ||
| 20 | - thinking: false # let reasoning models (Qwen3...) think first | ||
| 21 | - # thinking_budget: 512 # most thinking tokens before answering (default: no limit) | ||
| 22 | - | ||
| 23 | -# System prompt. Variables: {{date}} (YYYY-MM-DD), {{cwd}}, {{env.NAME}}. | ||
| 24 | -system: | | ||
| 25 | - You are a concise Swift expert. Today is {{date}}. | ||
| 26 | - The user works in {{cwd}}. | ||
| 27 | - | ||
| 28 | -# Built-in tools, enabled by being listed. Not set = no tools. | ||
| 29 | -tools: | ||
| 30 | - bash: | ||
| 31 | - confirm: true # ask before running each command | ||
| 32 | - | ||
| 33 | -ui: | ||
| 34 | - show_stats: true # print tokens and speed after each answer | ||
| 35 | - show_thinking: true # show the reasoning when the model thinks (TUI: Ctrl-T) | ||
deleted
razorbill.yaml +0 -28 | deleted file mode 100644 | ||
| @@ -1,28 +0,0 @@ | ||
| 1 | -# razorbill agent — created by `rzb init`. Use it with: rzb chat --config <this file> | |
| 2 | - | |
| 3 | -name: "Bob" | |
| 4 | -description: "I'm Bob" | |
| 5 | - | |
| 6 | -# Hugging Face id (MLX format) or local directory (path: ...). | |
| 7 | -model: | |
| 8 | - id: "mlx-community/Qwen3.5-9B-MLX-4bit" | |
| 9 | - revision: "main" | |
| 10 | - | |
| 11 | -generation: | |
| 12 | - temperature: 0.6 # 0 = deterministic | |
| 13 | - top_p: 1.0 # (0, 1] | |
| 14 | - max_tokens: 1024 # per answer | |
| 15 | - thinking: true # let reasoning models think first | |
| 16 | - | |
| 17 | -# Variables: {{date}}, {{cwd}}, {{env.NAME}}. | |
| 18 | -system: | | |
| 19 | - You are a helpful assistant. Today is {{date}}. | |
| 20 | - | |
| 21 | -# Built-in tools, enabled by being listed. | |
| 22 | -tools: | |
| 23 | - bash: | |
| 24 | - confirm: true # ask before running each command | |
| 25 | - | |
| 26 | -ui: | |
| 27 | - show_stats: true # tokens and speed after each answer | |
| 28 | - show_thinking: true | |
| deleted file mode 100644 | |||
| @@ -1,28 +0,0 @@ | |||
| 1 | -# razorbill agent — created by `rzb init`. Use it with: rzb chat --config <this file> | ||
| 2 | - | ||
| 3 | -name: "Bob" | ||
| 4 | -description: "I'm Bob" | ||
| 5 | - | ||
| 6 | -# Hugging Face id (MLX format) or local directory (path: ...). | ||
| 7 | -model: | ||
| 8 | - id: "mlx-community/Qwen3.5-9B-MLX-4bit" | ||
| 9 | - revision: "main" | ||
| 10 | - | ||
| 11 | -generation: | ||
| 12 | - temperature: 0.6 # 0 = deterministic | ||
| 13 | - top_p: 1.0 # (0, 1] | ||
| 14 | - max_tokens: 1024 # per answer | ||
| 15 | - thinking: true # let reasoning models think first | ||
| 16 | - | ||
| 17 | -# Variables: {{date}}, {{cwd}}, {{env.NAME}}. | ||
| 18 | -system: | | ||
| 19 | - You are a helpful assistant. Today is {{date}}. | ||
| 20 | - | ||
| 21 | -# Built-in tools, enabled by being listed. | ||
| 22 | -tools: | ||
| 23 | - bash: | ||
| 24 | - confirm: true # ask before running each command | ||
| 25 | - | ||
| 26 | -ui: | ||
| 27 | - show_stats: true # tokens and speed after each answer | ||
| 28 | - show_thinking: true | ||