warden-agent 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yash Honap
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,167 @@
1
- # Temporary Holding Version
1
+ # Warden
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A coding agent that runs in your terminal and works with **any model**: Gemini (free tier), OpenRouter, Groq, Ollama and LM Studio (local, free), OpenAI, Anthropic, or any OpenAI-compatible server.
4
+
5
+ You chat with it in your project folder. It reads your code, edits files, runs commands and tests, and asks before it changes anything (unless you tell it not to).
6
+
7
+ It also includes the original Warden supervisor tools: record and review Claude Code sessions, and run the same task on several models to compare them.
8
+
9
+ > **Status: early (0.4.0).** Tested live with Gemini 2.5 Flash. Read [What is verified](#what-is-verified).
10
+
11
+ ## Install
12
+
13
+ Pick one. All three give you the same `warden` command.
14
+
15
+ **Windows, nothing installed yet** (paste into PowerShell; installs Node.js if needed, then Warden):
16
+ ```powershell
17
+ irm https://raw.githubusercontent.com/yashhonap/warden/main/install.ps1 | iex
18
+ ```
19
+
20
+ **macOS / Linux:**
21
+ ```bash
22
+ curl -fsSL https://raw.githubusercontent.com/yashhonap/warden/main/install.sh | sh
23
+ ```
24
+
25
+ **Already have Node.js 22.13+:**
26
+ ```bash
27
+ npm i -g warden-agent
28
+ ```
29
+
30
+ **Or download one file** (Node.js included): `warden-windows-x64.exe`, `warden-macos-arm64` or `warden-linux-x64` from [Releases](https://github.com/yashhonap/warden/releases/latest). Windows may warn that the publisher is unknown (the file is not code-signed); choose "More info", then "Run anyway".
31
+
32
+ Then open a **new** terminal, go to a project folder and type `warden`. The first time, it walks you through getting a free API key (about two minutes with Google Gemini).
33
+
34
+ Something not working? Run `warden doctor`: it checks your setup and tells you what to fix. See also [Troubleshooting](docs/TROUBLESHOOTING.md). Update with `warden update`.
35
+
36
+ From a source checkout, run `npm link` once in the folder, or use `node src/cli.mjs` wherever this README says `warden`.
37
+
38
+ ## Add models (free ones too)
39
+
40
+ Inside Warden, type `/add`:
41
+
42
+ ```
43
+ › /add
44
+ 1 ○ OpenRouter hundreds of models, some free (Nemotron, Qwen, Llama…)
45
+ 2 ○ Hugging Face open models (DeepSeek, Qwen, Nemotron…), free monthly credits
46
+ 3 ○ NVIDIA Nemotron, DeepSeek, Llama…, free credits
47
+ 4 ● Google Gemini free tier
48
+ … Groq · Cerebras · Mistral · DeepSeek · Ollama · LM Studio · OpenAI · Anthropic
49
+ c ○ Custom any OpenAI-compatible server (URL)
50
+ ```
51
+
52
+ Pick a source, paste its key (typed hidden), search its models (free ones are listed first and marked), pick one. Warden then sends the model one tiny test to check the key and to find out how it can use tools, and saves it under a short name. Switch any time with `/model`.
53
+
54
+ - Keys pasted into `/add` are saved in `~/.warden/credentials.json` on your PC (plain text, only your Windows user can read your profile folder). Environment variables, if set, are used first. `/remove <source>` deletes a saved key.
55
+ - **Models without tool calling:** many free models cannot call tools natively. Warden then uses its own text format for tool calls, so they can still read and edit files (with the same approvals). If a model cannot manage either, it is marked **chat only**.
56
+ - **Free means limited.** Free tiers have small daily quotas (Gemini 2.5 Flash's free tier allowed 20 requests a day when tested). When a quota runs out, Warden says so instead of retrying; switch to another model with `/model`.
57
+
58
+ You can also set keys yourself as environment variables (`setx GEMINI_API_KEY "your-key"` on Windows, then open a new terminal): `GEMINI_API_KEY`, `OPENROUTER_API_KEY`, `HF_TOKEN`, `NVIDIA_API_KEY`, `GROQ_API_KEY`, `CEREBRAS_API_KEY`, `MISTRAL_API_KEY`, `DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`. Ollama and LM Studio need none.
59
+
60
+ ## Use it
61
+
62
+ ```bash
63
+ cd your-project
64
+ warden
65
+ ```
66
+
67
+ Then type what you want, e.g. `the tests in calc_test.py fail, fix them`. Warden shows each step:
68
+
69
+ ```
70
+ ● Read calc.py
71
+ ⎿ 12 lines
72
+ ● Edit calc.py
73
+ - return a - b
74
+ + return a + b
75
+ ? Allow this change? [y] yes [a] always allow edit_file this session [n] no, or type what to do instead
76
+ ```
77
+
78
+ Inside the app:
79
+
80
+ | | |
81
+ |---|---|
82
+ | `/add` | add a model from any source (see above) |
83
+ | `/model` | pick from your saved models by number; `/model <name>` or `/model provider/model` switches directly (becomes your default) |
84
+ | `/models openrouter nemotron --free` | browse and search a source's models |
85
+ | `/providers` | which sources have a key |
86
+ | `/remove <name>` | remove a saved model; `/remove <source>` forgets that source's saved key |
87
+ | `/mode` | `ask` (approve edits and commands), `auto-edit` (edits in this folder run without asking), `yolo` (everything runs without asking). Shift+Tab cycles. |
88
+ | `/clear` | new conversation |
89
+ | `/resume` | continue an earlier conversation |
90
+ | `/init` | the model writes a `WARDEN.md` with notes about your project |
91
+ | `/usage` | tokens used |
92
+ | `!command` | run a shell command yourself; the model sees the output |
93
+ | Ctrl+C | interrupt the model; twice at an empty prompt quits |
94
+
95
+ Other ways to start:
96
+
97
+ ```bash
98
+ warden "fix the failing test" # start with a message
99
+ warden --model groq/llama-3.3-70b-versatile
100
+ warden --continue # pick up the last conversation in this folder
101
+ warden -p "summarise this repo" # answer once and exit (scripts); --json for JSON
102
+ ```
103
+
104
+ If a `WARDEN.md`, `AGENTS.md` or `CLAUDE.md` exists in the folder, its contents are given to the model as project instructions.
105
+
106
+ ## Tools the model can use
107
+
108
+ `read_file`, `write_file`, `edit_file` (exact text replacement), `list_dir`, `glob`, `grep`, and `bash`. On Windows, `bash` uses Git Bash if installed, otherwise PowerShell.
109
+
110
+ ## Safety
111
+
112
+ - **`ask` mode (default):** every file change and every command needs your approval. Reading files inside the project does not. Reading or writing outside the project always asks, except in `yolo`.
113
+ - **`yolo` runs commands without asking.** Use it only in a folder you are happy for the model to change, ideally a git repo with your work committed.
114
+ - `-p` mode never prompts: anything that would need approval is denied unless you pass `--mode auto-edit` or `--mode yolo`.
115
+ - Keys are read from environment variables only. Conversations are saved as plain text in `~/.warden/sessions/` on your machine.
116
+ - Free tiers rate-limit. Warden waits and retries on 429 errors and shows that it is waiting.
117
+
118
+ ## Privacy
119
+
120
+ - **No telemetry.** Warden does not report anything about you or your usage.
121
+ - Your prompts, and the files and command output the model asks for, go **only to the model provider you picked** (Google, OpenRouter, …), under that provider's terms. Free tiers often allow the provider to use your data to improve their models; use a paid tier or a local model (Ollama, LM Studio) for private code.
122
+ - Conversations are saved on your computer in `~/.warden/sessions/`. Keys you paste into `/add` are saved in `~/.warden/credentials.json`. Delete those folders to remove everything.
123
+ - Once a day Warden asks the npm registry for the latest version number (a plain request to a public URL, nothing about you is sent). Turn it off with the environment variable `WARDEN_NO_UPDATE_CHECK=1` or `"updateCheck": false` in the settings.
124
+
125
+ ## Settings
126
+
127
+ `~/.warden/config.json`, section `agent` (all optional):
128
+
129
+ ```json
130
+ {
131
+ "agent": {
132
+ "model": "gemini/gemini-2.5-flash",
133
+ "mode": "ask",
134
+ "maxSteps": 60,
135
+ "contextTokens": 120000,
136
+ "providers": {
137
+ "deepseek": { "api": "openai", "baseUrl": "https://api.deepseek.com/v1", "keyEnv": ["DEEPSEEK_API_KEY"] }
138
+ }
139
+ }
140
+ }
141
+ ```
142
+
143
+ Any OpenAI-compatible server can be added under `providers` and used as `name/model`.
144
+
145
+ ## Supervisor tools (from Warden 0.1)
146
+
147
+ Record Claude Code sessions, review them with other models, and compare models on the same task:
148
+
149
+ ```bash
150
+ warden daemon # record Claude Code via hooks; dashboard at http://127.0.0.1:7777/
151
+ warden review <session-id> # approval-gated reviewers on any model
152
+ warden arena run task.json # same task, several models or agents, ranked
153
+ ```
154
+
155
+ See [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) for setup, hook configuration and details.
156
+
157
+ ## What is verified
158
+
159
+ - `npm test` runs offline: a mock model server that streams tool calls, the real tools on a temp project, permissions, rate-limit retries, interrupts, saved sessions, the terminal app driven through a pipe, and the supervisor tests.
160
+ - **Live:** Gemini 2.5 Flash through Google's OpenAI-compatible endpoint. It found, read and fixed a bug, streamed its answer, asked for approval, and respected a denial. The `/add` tool test identified it as native tool calling. Its free daily quota (20 requests) ran out during testing, which is how the quota handling was found and fixed.
161
+ - **Live model lists:** OpenRouter (466 models, 16 free), Hugging Face (126, free monthly credits rather than free models) and NVIDIA (65 chat models) were listed through Warden's own code without keys.
162
+ - **Not tested live:** chatting through OpenRouter, Hugging Face, NVIDIA, Groq, Cerebras, Mistral, DeepSeek, Ollama, LM Studio, OpenAI and Anthropic (no keys or local servers were available). The text tool format was tested against a mock model only. They use the same code path as Gemini (except Anthropic, which has its own).
163
+ - The interactive app was tested through a pipe and on Gemini, but not in every terminal. Shift+Tab mode switching depends on your terminal sending the right key code.
164
+
165
+ ## License
166
+
167
+ MIT, see [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "warden-agent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "A terminal coding agent for any model (Gemini, OpenRouter, Groq, Ollama, OpenAI, Anthropic), plus tools to review and compare coding agents.",
5
+ "keywords": [
6
+ "ai",
7
+ "coding-agent",
8
+ "cli",
9
+ "terminal",
10
+ "llm",
11
+ "gemini",
12
+ "ollama",
13
+ "openrouter",
14
+ "agents",
15
+ "code-review"
16
+ ],
17
+ "license": "MIT",
18
+ "author": "Yash Honap",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/yashhonap/warden.git"
22
+ },
23
+ "homepage": "https://github.com/yashhonap/warden#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/yashhonap/warden/issues"
26
+ },
27
+ "type": "module",
28
+ "bin": {
29
+ "warden": "src/cli.mjs"
30
+ },
31
+ "files": [
32
+ "src",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "scripts": {
37
+ "daemon": "node src/cli.mjs daemon",
38
+ "watch": "node src/cli.mjs watch",
39
+ "test": "node test/meta.mock.mjs && node test/agent.mock.mjs && node test/models.mock.mjs && node test/providers.mock.mjs && node test/arena.mock.mjs && node test/harnesses.mock.mjs",
40
+ "build:standalone": "node scripts/build-standalone.mjs"
41
+ },
42
+ "engines": {
43
+ "node": ">=22.13"
44
+ },
45
+ "devDependencies": {
46
+ "esbuild": "^0.28.2",
47
+ "postject": "^1.0.0-alpha.6"
48
+ }
49
+ }
@@ -0,0 +1,85 @@
1
+ // Where models come from. Every source here speaks the OpenAI-compatible API except "anthropic".
2
+ // listModels() returns a normalised list: { id, ctx, free, tools } (null = the source does not say).
3
+ //
4
+ // Checked live on 2026-11-11: OpenRouter, Hugging Face and NVIDIA publish their model lists without a key;
5
+ // Groq, Cerebras, Mistral and DeepSeek need a key to list models.
6
+
7
+ const NON_CHAT = /embed|rerank|safety|guard|reward|whisper|tts|speech|transcri|moderation|ocr|parse|clip|retriever|detector|image-gen|flux|stable-diffusion/i;
8
+
9
+ export const CATALOG = {
10
+ openrouter: {
11
+ label: "OpenRouter", api: "openai", baseUrl: "https://openrouter.ai/api/v1", keyEnv: ["OPENROUTER_API_KEY"],
12
+ keyUrl: "https://openrouter.ai/keys", blurb: "hundreds of models, some free (Nemotron, Qwen, Llama…)", publicList: true,
13
+ async list(fetchJson) {
14
+ const j = await fetchJson("https://openrouter.ai/api/v1/models");
15
+ return (j.data || []).map((m) => ({
16
+ id: m.id, ctx: m.context_length ?? null,
17
+ free: m.pricing ? Number(m.pricing.prompt) === 0 && Number(m.pricing.completion) === 0 : null,
18
+ tools: Array.isArray(m.supported_parameters) ? m.supported_parameters.includes("tools") : null,
19
+ }));
20
+ },
21
+ },
22
+ huggingface: {
23
+ label: "Hugging Face", api: "openai", baseUrl: "https://router.huggingface.co/v1", keyEnv: ["HF_TOKEN", "HUGGINGFACE_API_KEY"],
24
+ keyUrl: "https://huggingface.co/settings/tokens", blurb: "open models (DeepSeek, Qwen, Nemotron…), free monthly credits", publicList: true,
25
+ async list(fetchJson) {
26
+ const j = await fetchJson("https://router.huggingface.co/v1/models");
27
+ return (j.data || []).map((m) => {
28
+ const live = (m.providers || []).filter((p) => p.status !== "error");
29
+ return {
30
+ id: m.id,
31
+ ctx: live.reduce((n, p) => Math.max(n, p.context_length || 0), 0) || null,
32
+ free: live.some((p) => p.is_free) || null,
33
+ tools: live.length ? live.some((p) => p.supports_tools) : null,
34
+ };
35
+ });
36
+ },
37
+ },
38
+ nvidia: {
39
+ label: "NVIDIA", api: "openai", baseUrl: "https://integrate.api.nvidia.com/v1", keyEnv: ["NVIDIA_API_KEY"],
40
+ keyUrl: "https://build.nvidia.com", blurb: "Nemotron, DeepSeek, Llama…, free credits", publicList: true,
41
+ async list(fetchJson) {
42
+ const j = await fetchJson("https://integrate.api.nvidia.com/v1/models");
43
+ return (j.data || []).filter((m) => !NON_CHAT.test(m.id)).map((m) => ({ id: m.id, ctx: null, free: null, tools: null }));
44
+ },
45
+ },
46
+ gemini: {
47
+ label: "Google Gemini", api: "openai", baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", keyEnv: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
48
+ keyUrl: "https://aistudio.google.com/apikey", blurb: "free tier",
49
+ },
50
+ groq: {
51
+ label: "Groq", api: "openai", baseUrl: "https://api.groq.com/openai/v1", keyEnv: ["GROQ_API_KEY"],
52
+ keyUrl: "https://console.groq.com/keys", blurb: "free tier, very fast",
53
+ },
54
+ cerebras: {
55
+ label: "Cerebras", api: "openai", baseUrl: "https://api.cerebras.ai/v1", keyEnv: ["CEREBRAS_API_KEY"],
56
+ keyUrl: "https://cloud.cerebras.ai", blurb: "free tier, very fast",
57
+ },
58
+ mistral: {
59
+ label: "Mistral", api: "openai", baseUrl: "https://api.mistral.ai/v1", keyEnv: ["MISTRAL_API_KEY"],
60
+ keyUrl: "https://console.mistral.ai/api-keys", blurb: "free tier (Experiment plan)",
61
+ },
62
+ deepseek: {
63
+ label: "DeepSeek", api: "openai", baseUrl: "https://api.deepseek.com", keyEnv: ["DEEPSEEK_API_KEY"],
64
+ keyUrl: "https://platform.deepseek.com/api_keys", blurb: "official API, cheap but not free",
65
+ },
66
+ ollama: {
67
+ label: "Ollama", api: "openai", baseUrl: "http://127.0.0.1:11434/v1", keyEnv: [], local: true,
68
+ keyUrl: "https://ollama.com/download", blurb: "models on your own PC, no key",
69
+ },
70
+ lmstudio: {
71
+ label: "LM Studio", api: "openai", baseUrl: "http://127.0.0.1:1234/v1", keyEnv: [], local: true,
72
+ keyUrl: "https://lmstudio.ai", blurb: "models on your own PC, no key",
73
+ },
74
+ openai: {
75
+ label: "OpenAI", api: "openai", baseUrl: "https://api.openai.com/v1", keyEnv: ["OPENAI_API_KEY"], maxTokensParam: "max_completion_tokens",
76
+ keyUrl: "https://platform.openai.com/api-keys", blurb: "paid",
77
+ },
78
+ anthropic: {
79
+ label: "Anthropic", api: "anthropic", baseUrl: "https://api.anthropic.com/v1", keyEnv: ["ANTHROPIC_API_KEY"],
80
+ keyUrl: "https://console.anthropic.com/settings/keys", blurb: "paid",
81
+ },
82
+ };
83
+
84
+ // Order shown by /add: the easiest free option first (Gemini: tested live, native tool calling), then other free sources.
85
+ export const ADD_ORDER = ["gemini", "openrouter", "huggingface", "nvidia", "groq", "cerebras", "mistral", "deepseek", "ollama", "lmstudio", "openai", "anthropic"];
@@ -0,0 +1,44 @@
1
+ // Agent settings live in ~/.warden/config.json under "agent" (the supervisor uses the rest of that file).
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ export const HOME = process.env.WARDEN_HOME || path.join(os.homedir(), ".warden");
7
+ export const CONFIG_FILE = path.join(HOME, "config.json");
8
+ export const SESSIONS_DIR = path.join(HOME, "sessions");
9
+
10
+ export const AGENT_DEFAULTS = {
11
+ model: null, // "provider/model"; null = pick from the API keys you have
12
+ mode: "ask", // ask | auto-edit | yolo
13
+ maxOutputTokens: 8192,
14
+ maxSteps: 60, // model calls per user message before Warden stops and asks you
15
+ contextTokens: 120000, // rough budget; old tool output is trimmed above this
16
+ providers: {}, // extra or overridden providers: { "name": { "api": "openai", "baseUrl": "...", "keyEnv": ["ENV"] } }
17
+ recentModels: [],
18
+ };
19
+
20
+ function readAll() {
21
+ try { return JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8")); } catch { return {}; }
22
+ }
23
+
24
+ export function loadAgentConfig() {
25
+ return { ...AGENT_DEFAULTS, ...(readAll().agent || {}) };
26
+ }
27
+
28
+ // Saves only the given keys, preserving everything else in the file (including supervisor settings).
29
+ export function saveAgentConfig(patch) {
30
+ const all = readAll();
31
+ all.agent = { ...(all.agent || {}), ...patch };
32
+ fs.mkdirSync(HOME, { recursive: true });
33
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(all, null, 2));
34
+ }
35
+
36
+ // First model we can actually use, based on which keys are set.
37
+ export function pickDefaultModel(env = process.env) {
38
+ if (env.GEMINI_API_KEY || env.GOOGLE_API_KEY) return "gemini/gemini-2.5-flash";
39
+ if (env.GROQ_API_KEY) return "groq/llama-3.3-70b-versatile";
40
+ if (env.OPENROUTER_API_KEY) return "openrouter/openrouter/auto";
41
+ if (env.ANTHROPIC_API_KEY) return "anthropic/claude-sonnet-5-5";
42
+ if (env.OPENAI_API_KEY) return "openai/gpt-4.1-mini";
43
+ return "gemini/gemini-2.5-flash";
44
+ }
@@ -0,0 +1,38 @@
1
+ // API keys pasted into /add are stored in ~/.warden/credentials.json (plain text, readable only by your user account
2
+ // where the OS allows). Environment variables always take priority over saved keys.
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { HOME } from "./config.mjs";
6
+
7
+ export const CREDENTIALS_FILE = path.join(HOME, "credentials.json");
8
+
9
+ function readAll() {
10
+ try { return JSON.parse(fs.readFileSync(CREDENTIALS_FILE, "utf8")) || {}; } catch { return {}; }
11
+ }
12
+
13
+ export function savedKey(provider) {
14
+ const v = readAll()[provider];
15
+ return typeof v === "string" && v ? v : null;
16
+ }
17
+
18
+ export function saveKey(provider, key) {
19
+ const all = readAll();
20
+ all[provider] = String(key).trim();
21
+ writeAll(all);
22
+ }
23
+
24
+ export function removeKey(provider) {
25
+ const all = readAll();
26
+ if (!(provider in all)) return false;
27
+ delete all[provider];
28
+ writeAll(all);
29
+ return true;
30
+ }
31
+
32
+ function writeAll(all) {
33
+ fs.mkdirSync(HOME, { recursive: true });
34
+ fs.writeFileSync(CREDENTIALS_FILE, JSON.stringify(all, null, 2), { mode: 0o600 });
35
+ try { fs.chmodSync(CREDENTIALS_FILE, 0o600); } catch {}
36
+ }
37
+
38
+ export const mask = (k) => (k && k.length > 8 ? `${k.slice(0, 4)}…${k.slice(-4)}` : "****");
@@ -0,0 +1,75 @@
1
+ // `warden doctor`: checks the things that usually go wrong and says how to fix each one in plain words.
2
+ // Safe to paste when asking for help: keys are never printed, only where they come from.
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import { execFileSync } from "node:child_process";
6
+ import { VERSION } from "../version.mjs";
7
+ import { HOME, loadAgentConfig, pickDefaultModel, CONFIG_FILE } from "./config.mjs";
8
+ import { CATALOG, ADD_ORDER } from "./catalog.mjs";
9
+ import { keyStatus, parseModelSpec, resolveProvider, chat } from "./providers.mjs";
10
+ import { savedModels } from "./models.mjs";
11
+ import { detectShell } from "./tools.mjs";
12
+ import { isStandalone, fetchLatest, newer } from "./update.mjs";
13
+
14
+ export async function runDoctor({ testChat = false } = {}) {
15
+ const cfg = loadAgentConfig();
16
+ let problems = 0;
17
+ const ok = (m) => console.log(` ok ${m}`);
18
+ const bad = (m, fix) => { problems++; console.log(` FIX ${m}\n -> ${fix}`); };
19
+ const info = (m) => console.log(` info ${m}`);
20
+
21
+ console.log(`\nWarden doctor (Warden ${VERSION}${isStandalone() ? ", standalone build" : ""})\n`);
22
+
23
+ // Node
24
+ const [maj, min] = process.versions.node.split(".").map(Number);
25
+ if (maj > 22 || (maj === 22 && min >= 13)) ok(`Node.js ${process.versions.node}`);
26
+ else bad(`Node.js ${process.versions.node} is too old (Warden needs 22.13 or newer)`, "install the LTS version from https://nodejs.org, then reinstall Warden");
27
+ info(`${os.platform()} ${os.release()} (${os.arch()}); shell for commands: ${detectShell().name}`);
28
+
29
+ // git (used for project info, diffs and the arena)
30
+ try { const v = execFileSync("git", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, windowsHide: true }).trim(); ok(v); }
31
+ catch { info("git not found. Warden works without it, but cannot show git status (install from https://git-scm.com)"); }
32
+
33
+ // settings folder
34
+ try { fs.mkdirSync(HOME, { recursive: true }); fs.accessSync(HOME, fs.constants.W_OK); ok(`settings folder ${HOME}`); }
35
+ catch (e) { bad(`cannot write to ${HOME} (${e.code || e.message})`, "set WARDEN_HOME to a folder you can write to"); }
36
+ if (fs.existsSync(CONFIG_FILE)) { try { JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8")); } catch { bad(`${CONFIG_FILE} is not valid JSON`, "fix or delete that file (Warden recreates it)"); } }
37
+
38
+ // model + keys
39
+ const model = cfg.model || pickDefaultModel();
40
+ let provider;
41
+ try { provider = parseModelSpec(model).provider; resolveProvider(provider, cfg); ok(`model ${model}`); }
42
+ catch (e) { bad(`model "${model}": ${e.message}`, "run warden, then /add to pick a model"); }
43
+ const withKey = ADD_ORDER.filter((n) => { try { return !/missing/.test(keyStatus(n, cfg)) && !CATALOG[n].local; } catch { return false; } });
44
+ if (provider) {
45
+ let st = ""; try { st = keyStatus(provider, cfg); } catch {}
46
+ if (/missing/.test(st)) bad(`no key for ${provider}`, "run warden and follow the setup, or /add (free: Google Gemini, https://aistudio.google.com/apikey)");
47
+ else ok(`${provider}: ${st}`);
48
+ }
49
+ info(`sources with a key: ${withKey.length ? withKey.join(", ") : "none"}; saved models: ${savedModels(cfg).length}`);
50
+
51
+ // internet + the provider
52
+ if (provider) {
53
+ const p = resolveProvider(provider, cfg);
54
+ try {
55
+ const r = await fetch(`${p.baseUrl}/models`, { signal: AbortSignal.timeout(8000) });
56
+ ok(`can reach ${new URL(p.baseUrl).host} (HTTP ${r.status})`);
57
+ } catch (e) {
58
+ if (p.local) bad(`cannot reach ${p.label} at ${p.baseUrl}`, `start ${p.label} and download a model, or pick another source with /add`);
59
+ else bad(`cannot reach ${new URL(p.baseUrl).host} (${e.cause?.code || e.message})`, "check your internet connection, VPN or company proxy (set HTTPS_PROXY if you use one)");
60
+ }
61
+ }
62
+ if (testChat && provider) {
63
+ try {
64
+ const r = await chat({ spec: model, cfg, system: "Reply with the single word: ready", messages: [{ role: "user", content: "ping" }], maxOutputTokens: 20 });
65
+ ok(`${model} answered: "${r.text.trim().slice(0, 40)}"`);
66
+ } catch (e) { bad(`${model} did not answer: ${e.message.slice(0, 200)}`, /401|403|key/i.test(e.message) ? "the key is wrong or expired: /add it again" : /429/.test(e.message) ? "quota used up: try another model with /model" : "try another model with /add"); }
67
+ } else info("add --chat to also send one tiny test message to the model (uses one request of your quota)");
68
+
69
+ // version
70
+ try { const latest = await fetchLatest(5000); if (newer(latest, VERSION)) info(`Warden ${latest} is available: warden update`); else ok("Warden is up to date"); }
71
+ catch { info("could not check for updates (offline, or not published yet)"); }
72
+
73
+ console.log(problems ? `\n${problems} thing${problems > 1 ? "s" : ""} to fix (see FIX above).\n` : "\nEverything looks fine.\n");
74
+ return problems ? 1 : 0;
75
+ }
@@ -0,0 +1,35 @@
1
+ // `warden -p "task"`: one message, no interface. The answer goes to stdout, tool activity to stderr.
2
+ // Tool calls that would need approval are denied unless --mode auto-edit or --mode yolo allows them.
3
+ import { runTurn } from "./loop.mjs";
4
+ import { Session } from "./session.mjs";
5
+ import { loadAgentConfig, pickDefaultModel } from "./config.mjs";
6
+ import { MODES } from "./tools.mjs";
7
+ import { resolveModelInput } from "./models.mjs";
8
+
9
+ export async function runHeadless({ prompt, cwd = process.cwd(), model, mode, json = false }) {
10
+ const cfg = loadAgentConfig();
11
+ if (model) model = resolveModelInput(cfg, model); // accepts a saved name too
12
+ const session = new Session({ cwd, model: model || cfg.model || pickDefaultModel() });
13
+ const perm = { mode: MODES.includes(mode) ? mode : "ask", allowed: new Set() };
14
+ const err = (s) => process.stderr.write(s + "\n");
15
+ const controller = new AbortController();
16
+ process.on("SIGINT", () => controller.abort());
17
+ let text = "";
18
+ const ui = {
19
+ onText: (d) => { text += d; if (!json) process.stdout.write(d); },
20
+ onAssistantEnd: (t) => { if (!json && t && !t.endsWith("\n")) process.stdout.write("\n"); },
21
+ onRetry: ({ status, waitMs }) => err(`[warden] rate limited (${status}), retrying in ${Math.round(waitMs / 1000)}s`),
22
+ onNotice: (m) => err(`[warden] ${m}`),
23
+ confirm: async (call, tool, desc) => { err(`[warden] denied (mode ${perm.mode}): ${desc}`); return "no"; },
24
+ onToolEnd: (call, tool, res) => err(`[warden] ${res?.denied ? "denied" : res?.error ? "error" : "ok"} ${res?.display?.title || call.name}${res?.error ? ": " + res.error : ""}`),
25
+ };
26
+ try {
27
+ const r = await runTurn({ session, userText: prompt, cfg, ui, perm, signal: controller.signal, cwd });
28
+ if (json) process.stdout.write(JSON.stringify({ ok: !r.interrupted, text, model: session.model, usage: session.usage, session: session.id }) + "\n");
29
+ return r.interrupted ? 130 : 0;
30
+ } catch (e) {
31
+ if (json) process.stdout.write(JSON.stringify({ ok: false, error: e.message, model: session.model }) + "\n");
32
+ else err(`[warden] error: ${e.message}`);
33
+ return 1;
34
+ }
35
+ }
@@ -0,0 +1,105 @@
1
+ // The agent loop: send the conversation to the model, run the tools it asks for (with permission), repeat until
2
+ // it answers without tool calls. The UI is injected so the same loop runs in the terminal app and in headless mode.
3
+ import { chat, toolsUnsupported } from "./providers.mjs";
4
+ import { findModel, toolModeFor, setToolMode } from "./models.mjs";
5
+ import { TOOLS, toolByName, needsApproval, describeCall } from "./tools.mjs";
6
+ import { systemPrompt } from "./prompt.mjs";
7
+
8
+ const isAbort = (e) => e?.name === "AbortError" || /aborted/i.test(e?.message || "");
9
+
10
+ // Keep the conversation under a rough token budget by blanking the oldest tool outputs first.
11
+ export function trimContext(messages, budgetTokens) {
12
+ const size = () => messages.reduce((n, m) => n + (m.content?.length || 0) + JSON.stringify(m.toolCalls || "").length, 0) / 4;
13
+ if (size() <= budgetTokens) return 0;
14
+ let trimmed = 0;
15
+ for (let i = 0; i < messages.length - 6 && size() > budgetTokens; i++) {
16
+ const m = messages[i];
17
+ if (m.role === "tool" && m.content.length > 200 && !m.trimmed) { m.content = "[old tool output removed to save context]"; m.trimmed = true; trimmed++; }
18
+ }
19
+ return trimmed;
20
+ }
21
+
22
+ /**
23
+ * Runs one user message to completion.
24
+ * ui: { onAssistantStart, onText, onAssistantEnd, onToolStart, onToolEnd, confirm, onRetry, onNotice }
25
+ * perm: { mode, allowed: Set<toolName> }
26
+ */
27
+ export async function runTurn({ session, userText, cfg, ui, perm, signal, cwd = session.cwd }) {
28
+ session.push({ role: "user", content: userText });
29
+ const tools = TOOLS.map(({ name, description, parameters }) => ({ name, description, parameters }));
30
+
31
+ for (let step = 1; ; step++) {
32
+ if (step > cfg.maxSteps) {
33
+ ui.onNotice?.(`Stopped after ${cfg.maxSteps} model calls for one message. Say "continue" to keep going.`);
34
+ return { stopped: "max_steps" };
35
+ }
36
+ // a saved model may have a smaller context window than the global budget
37
+ const saved = findModel(cfg, session.model);
38
+ const budget = saved?.ctx ? Math.min(cfg.contextTokens, Math.floor(saved.ctx * 0.7)) : cfg.contextTokens;
39
+ const cut = trimContext(session.messages, budget);
40
+ if (cut) ui.onNotice?.(`Trimmed ${cut} old tool output(s) to stay within the context budget.`);
41
+
42
+ let res, partial = "";
43
+ session.toolModes ||= {};
44
+ const toolMode = session.toolModes[session.model] || toolModeFor(cfg, session.model);
45
+ ui.onAssistantStart?.();
46
+ try {
47
+ res = await chat({
48
+ spec: session.model, system: systemPrompt({ cwd, mode: perm.mode }), messages: session.messages, tools,
49
+ cfg, signal, maxOutputTokens: cfg.maxOutputTokens, toolMode,
50
+ onText: (d) => { partial += d; ui.onText?.(d); }, onRetry: ui.onRetry,
51
+ });
52
+ } catch (e) {
53
+ ui.onAssistantEnd?.(partial);
54
+ if (isAbort(e) || signal?.aborted) {
55
+ session.push({ role: "assistant", content: (partial ? partial + "\n" : "") + "[interrupted by the user]" });
56
+ return { interrupted: true };
57
+ }
58
+ // This model rejects native tool calling: switch it to the text format and try the same step again.
59
+ if (toolMode === "native" && !partial && toolsUnsupported(e)) {
60
+ setToolMode(cfg, session.model, "text"); // remembered if it is a saved model
61
+ session.toolModes[session.model] = "text"; // and for the rest of this conversation either way
62
+ ui.onNotice?.(`${session.model} does not accept native tool calls; switching it to Warden's text tool format.`);
63
+ step--;
64
+ continue;
65
+ }
66
+ // keep the conversation valid for the next message: the user turn stays, no half assistant message
67
+ throw e;
68
+ }
69
+ ui.onAssistantEnd?.(res.text);
70
+ session.usage.calls++;
71
+ if (res.usage) { session.usage.input += res.usage.input; session.usage.output += res.usage.output; }
72
+ session.push({ role: "assistant", content: res.text, ...(res.toolCalls.length ? { toolCalls: res.toolCalls } : {}) });
73
+ if (!res.toolCalls.length) return { done: true, text: res.text, stopReason: res.stopReason };
74
+
75
+ // Every tool call must get a result, even when interrupted, or the next request is invalid.
76
+ for (const call of res.toolCalls) {
77
+ const tool = toolByName(call.name);
78
+ const result = (content, isError = true) => session.push({ role: "tool", toolCallId: call.id, name: call.name, content, ...(isError ? { isError: true } : {}) });
79
+ if (signal?.aborted) { result("Interrupted by the user before this ran."); continue; }
80
+ if (!tool) { result(`Unknown tool "${call.name}". Available: ${TOOLS.map((t) => t.name).join(", ")}`); ui.onToolEnd?.(call, null, { error: "unknown tool" }); continue; }
81
+ if (call.args?.__invalid_json !== undefined) { result("Your tool arguments were not valid JSON. Send them again as a JSON object."); ui.onToolEnd?.(call, tool, { error: "invalid arguments" }); continue; }
82
+
83
+ ui.onToolStart?.(call, tool);
84
+ if (needsApproval(tool, call.args, { cwd, mode: perm.mode, allowed: perm.allowed })) {
85
+ const answer = await ui.confirm(call, tool, describeCall(tool, call.args, cwd));
86
+ if (answer === "always") perm.allowed.add(tool.name);
87
+ else if (answer !== "yes") {
88
+ const why = typeof answer === "object" && answer.reason ? ` Reason: ${answer.reason}` : "";
89
+ result(`User denied this ${tool.name} call.${why}`);
90
+ ui.onToolEnd?.(call, tool, { denied: true });
91
+ continue;
92
+ }
93
+ }
94
+ try {
95
+ const out = await tool.run(call.args || {}, { cwd, signal });
96
+ result(out.content, !!out.isError);
97
+ ui.onToolEnd?.(call, tool, out);
98
+ } catch (e) {
99
+ result(`Error: ${e.message}`);
100
+ ui.onToolEnd?.(call, tool, { error: e.message });
101
+ }
102
+ }
103
+ if (signal?.aborted) return { interrupted: true };
104
+ }
105
+ }