@kinqs/brainrouter-cli 0.3.4

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.
Files changed (87) hide show
  1. package/.env.example +109 -0
  2. package/README.md +185 -0
  3. package/dist/agent/agent.d.ts +765 -0
  4. package/dist/agent/agent.js +1977 -0
  5. package/dist/cli/cliPrompt.d.ts +15 -0
  6. package/dist/cli/cliPrompt.js +62 -0
  7. package/dist/cli/commands/_context.d.ts +53 -0
  8. package/dist/cli/commands/_context.js +14 -0
  9. package/dist/cli/commands/_helpers.d.ts +45 -0
  10. package/dist/cli/commands/_helpers.js +140 -0
  11. package/dist/cli/commands/guard.d.ts +6 -0
  12. package/dist/cli/commands/guard.js +292 -0
  13. package/dist/cli/commands/memory.d.ts +12 -0
  14. package/dist/cli/commands/memory.js +263 -0
  15. package/dist/cli/commands/obs.d.ts +6 -0
  16. package/dist/cli/commands/obs.js +208 -0
  17. package/dist/cli/commands/orchestration.d.ts +6 -0
  18. package/dist/cli/commands/orchestration.js +218 -0
  19. package/dist/cli/commands/session.d.ts +6 -0
  20. package/dist/cli/commands/session.js +191 -0
  21. package/dist/cli/commands/ui.d.ts +6 -0
  22. package/dist/cli/commands/ui.js +477 -0
  23. package/dist/cli/commands/workflow.d.ts +6 -0
  24. package/dist/cli/commands/workflow.js +691 -0
  25. package/dist/cli/repl.d.ts +12 -0
  26. package/dist/cli/repl.js +894 -0
  27. package/dist/config/config.d.ts +22 -0
  28. package/dist/config/config.js +105 -0
  29. package/dist/config/workspace.d.ts +7 -0
  30. package/dist/config/workspace.js +62 -0
  31. package/dist/index.d.ts +2 -0
  32. package/dist/index.js +610 -0
  33. package/dist/memory/briefing.d.ts +46 -0
  34. package/dist/memory/briefing.js +152 -0
  35. package/dist/memory/consolidation.d.ts +60 -0
  36. package/dist/memory/consolidation.js +208 -0
  37. package/dist/memory/formatters.d.ts +38 -0
  38. package/dist/memory/formatters.js +102 -0
  39. package/dist/memory/mentions.d.ts +10 -0
  40. package/dist/memory/mentions.js +72 -0
  41. package/dist/orchestration/orchestrator.d.ts +36 -0
  42. package/dist/orchestration/orchestrator.js +71 -0
  43. package/dist/orchestration/roles.d.ts +11 -0
  44. package/dist/orchestration/roles.js +117 -0
  45. package/dist/orchestration/tools.d.ts +244 -0
  46. package/dist/orchestration/tools.js +528 -0
  47. package/dist/prompt/breadthHint.d.ts +48 -0
  48. package/dist/prompt/breadthHint.js +93 -0
  49. package/dist/prompt/compactor.d.ts +31 -0
  50. package/dist/prompt/compactor.js +112 -0
  51. package/dist/prompt/initAgentMd.d.ts +13 -0
  52. package/dist/prompt/initAgentMd.js +194 -0
  53. package/dist/prompt/skillRunner.d.ts +34 -0
  54. package/dist/prompt/skillRunner.js +146 -0
  55. package/dist/prompt/systemPrompt.d.ts +10 -0
  56. package/dist/prompt/systemPrompt.js +171 -0
  57. package/dist/runtime/clipboard.d.ts +17 -0
  58. package/dist/runtime/clipboard.js +52 -0
  59. package/dist/runtime/llmSemaphore.d.ts +30 -0
  60. package/dist/runtime/llmSemaphore.js +67 -0
  61. package/dist/runtime/loopRunner.d.ts +25 -0
  62. package/dist/runtime/loopRunner.js +79 -0
  63. package/dist/runtime/mcpClient.d.ts +156 -0
  64. package/dist/runtime/mcpClient.js +234 -0
  65. package/dist/runtime/mcpUtils.d.ts +36 -0
  66. package/dist/runtime/mcpUtils.js +64 -0
  67. package/dist/runtime/sandbox.d.ts +48 -0
  68. package/dist/runtime/sandbox.js +156 -0
  69. package/dist/runtime/tracing.d.ts +25 -0
  70. package/dist/runtime/tracing.js +91 -0
  71. package/dist/state/cliState.d.ts +59 -0
  72. package/dist/state/cliState.js +311 -0
  73. package/dist/state/goalStore.d.ts +174 -0
  74. package/dist/state/goalStore.js +410 -0
  75. package/dist/state/hookifyStore.d.ts +80 -0
  76. package/dist/state/hookifyStore.js +237 -0
  77. package/dist/state/hooksStore.d.ts +42 -0
  78. package/dist/state/hooksStore.js +71 -0
  79. package/dist/state/preferencesStore.d.ts +41 -0
  80. package/dist/state/preferencesStore.js +25 -0
  81. package/dist/state/sessionStore.d.ts +42 -0
  82. package/dist/state/sessionStore.js +193 -0
  83. package/dist/state/taskStore.d.ts +23 -0
  84. package/dist/state/taskStore.js +80 -0
  85. package/dist/state/workflowArtifacts.d.ts +33 -0
  86. package/dist/state/workflowArtifacts.js +139 -0
  87. package/package.json +71 -0
package/.env.example ADDED
@@ -0,0 +1,109 @@
1
+ # BrainRouter CLI agent — environment
2
+ #
3
+ # Copy to brainrouter-cli/.env. Loaded by the CLI at startup.
4
+ #
5
+ # This file is for CLI-AGENT concerns only:
6
+ # - chat LLM the terminal agent talks to
7
+ # - tool runtime knobs (loop limit, result clamp, MCP timeout)
8
+ # - auto-compaction trigger
9
+ # - sandbox configuration for run_command
10
+ # - web search backend
11
+ # - trace logging
12
+ # - workspace override
13
+ #
14
+ # MCP-server concerns (cognitive extraction, embeddings, reranker, memory
15
+ # engine knobs, server auth) live in brainrouter/.env.example.
16
+ #
17
+ # Why split: the MCP and the CLI are separate processes with different
18
+ # concerns. The CLI's chat LLM can be a smart cloud model while the MCP's
19
+ # cognitive extractor is a cheap local one. Their concurrency caps differ
20
+ # too (CLI default 4, MCP default 2). Keep them independent.
21
+
22
+ # ==========================================
23
+ # Chat LLM (for the agent's own conversation)
24
+ # ==========================================
25
+ # Same var names as the MCP, but a separate process — set them here for the
26
+ # CLI's chat model. Falls back to OPENAI_API_KEY.
27
+ #
28
+ # If you don't set BRAINROUTER_LLM_API_KEY here, the CLI also reads it from
29
+ # brainrouter/.env as a transitional fallback. Setting it here makes the
30
+ # CLI's choice explicit and lets you use a different chat model than the
31
+ # MCP's extractor (e.g. gpt-4o for chat, gpt-4o-mini for extraction).
32
+ BRAINROUTER_LLM_API_KEY=your_api_key_here
33
+
34
+ # OpenAI-compatible chat-completions endpoint.
35
+ # Examples:
36
+ # OpenAI: https://api.openai.com/v1/chat/completions
37
+ # OpenRouter: https://openrouter.ai/api/v1/chat/completions
38
+ # Anthropic via OpenRouter: anthropic/claude-sonnet-4
39
+ # LM Studio: http://localhost:1234/v1/chat/completions
40
+ BRAINROUTER_LLM_ENDPOINT=https://api.openai.com/v1/chat/completions
41
+
42
+ BRAINROUTER_LLM_MODEL=gpt-4o-mini
43
+
44
+ # Per-call timeout for the CLI's chat LLM. Default: 120000.
45
+ # BRAINROUTER_LLM_TIMEOUT_MS=120000
46
+
47
+ # Cap on concurrent in-flight chat LLM calls FROM THE CLI PROCESS.
48
+ # Default: 4 (separate from the MCP's own cap). Set to 1 for consumer-grade
49
+ # local backends; crank to 16+ for cloud APIs.
50
+ # BRAINROUTER_LLM_MAX_CONCURRENT=4
51
+
52
+ # ==========================================
53
+ # Tool runtime
54
+ # ==========================================
55
+ # Per-tool timeout for CLI → MCP requests. Default: 60000.
56
+ # BRAINROUTER_MCP_TIMEOUT_MS=60000
57
+
58
+ # LLM-visible clamp on a single tool-result body (full text still recorded
59
+ # in the transcript on disk). Default: 8000.
60
+ # BRAINROUTER_MAX_TOOL_RESULT_CHARS=8000
61
+
62
+ # Hard ceiling on tool-call iterations per turn. Default: 60.
63
+ # BRAINROUTER_MAX_TOOL_LOOPS=60
64
+
65
+ # Estimated history-size trigger for auto-`/compact`. Default: 80000 tokens.
66
+ # BRAINROUTER_AUTO_COMPACT_TOKENS=80000
67
+
68
+ # ==========================================
69
+ # Sandbox (run_command)
70
+ # ==========================================
71
+ # Wrap shell commands in the platform sandbox:
72
+ # macOS: sandbox-exec
73
+ # Linux: bwrap (preferred) or firejail
74
+ # Set 'on' to enable. Off by default.
75
+ # BRAINROUTER_SANDBOX=on
76
+
77
+ # Allow outbound network from sandboxed commands. Off by default.
78
+ # BRAINROUTER_SANDBOX_NETWORK=off
79
+
80
+ # Colon-separated read/write path allowlists.
81
+ # BRAINROUTER_SANDBOX_READ_PATHS=/usr/local:/opt
82
+ # BRAINROUTER_SANDBOX_WRITE_PATHS=/tmp
83
+
84
+ # ==========================================
85
+ # Workspace
86
+ # ==========================================
87
+ # Override workspace root the CLI uses for file tools + session key.
88
+ # Most users let the CLI auto-detect via git/closest package.json.
89
+ # BRAINROUTER_WORKSPACE=/path/to/project
90
+
91
+ # Override per-user state root. Default: ~/.brainrouter.
92
+ # Both the CLI and MCP honor this — set it once and both processes use it.
93
+ # BRAINROUTER_HOME=/path/to/state
94
+
95
+ # ==========================================
96
+ # Web search
97
+ # ==========================================
98
+ # Custom search backend for the web_search tool. Must accept
99
+ # POST { query, maxResults } → { results: [{ title, url, snippet }] }.
100
+ # Falls back to DuckDuckGo's Instant Answer API when unset.
101
+ # Compatible with Brave Search API wrappers, Tavily, SerpAPI proxies.
102
+ # BRAINROUTER_WEB_SEARCH_ENDPOINT=https://your-search-proxy.example.com/search
103
+
104
+ # ==========================================
105
+ # Observability
106
+ # ==========================================
107
+ # Path for OTEL-style JSONL turn traces. One line per turn/tool span.
108
+ # Toggle at runtime with /trace on|off.
109
+ # BRAINROUTER_TRACE_LOG=/path/to/trace.jsonl
package/README.md ADDED
@@ -0,0 +1,185 @@
1
+ # 🧠 BrainRouter Terminal Agent CLI
2
+
3
+ A premium, autonomous terminal-based AI coding assistant and REPL that acts as your local agent. It leverages **BrainRouter's memory engine** for cognitive persistence (System 1/2 loops) and provides standard filesystem/terminal tools to solve complex coding tasks autonomously.
4
+
5
+ ---
6
+
7
+ ## Features
8
+ - **Dual-Tier Connection**: Connects to local MCP servers via standard I/O (stdio) or hosted multi-tenant servers over Streamable HTTP/SSE.
9
+ - **Double-Tier Memory Architecture**:
10
+ - **System 1 (Heuristic Recall)**: Automatically retrieves active focus scenes, codebase facts, and skills *before* each LLM reasoning cycle.
11
+ - **System 2 (Memory Consolidation)**: Autonomously extracts learning points, updates facts, and saves evidence via turn-by-turn memory capture.
12
+ - **Local Execution Harness**: Autonomous execution of files editing, directory listing, regex/string grep, and terminal command invocation (safely prompted for user verification).
13
+ - **Obsidian Dark / Midnight Ledger Aesthetics**: High-end command line styling, loader animations, and formatted terminal markdown output.
14
+
15
+ ---
16
+
17
+ ## Installation & Setup
18
+
19
+ 1. **Build the Monorepo**:
20
+ From the repository root:
21
+ ```bash
22
+ npm install
23
+ npm run build
24
+ ```
25
+
26
+ 2. **Configure Provider and Server Profiles**:
27
+ Run the interactive configurator to set up your LLM settings (OpenAI, local endpoints like Ollama/LM Studio) and active server profile.
28
+ From the repository root:
29
+ ```bash
30
+ npm run cli config
31
+ ```
32
+ Or from the `brainrouter` package subdirectory:
33
+ ```bash
34
+ node dist/index.js config
35
+ ```
36
+ This generates and modifies settings stored in `~/.config/brainrouter/config.json`.
37
+
38
+ ---
39
+
40
+ ## CLI Usage
41
+
42
+ ### Start Interactive Agent Session (REPL)
43
+ Starts the agent loop. It will automatically load the active server connection and prime the agent with active codebase memories.
44
+ From the repository root:
45
+ ```bash
46
+ npm run cli
47
+ ```
48
+ Or to run a specific command:
49
+ ```bash
50
+ npm run cli chat
51
+ ```
52
+ Or from the `brainrouter` package subdirectory:
53
+ ```bash
54
+ node dist/index.js chat
55
+ ```
56
+ *Tip: You can override the active LLM model via `--model <name>` or profile via `--profile <name>`.*
57
+
58
+ Workspace detection:
59
+ - By default, BrainRouter uses the nearest project root with `AGENT.md`, `AGENTS.md`, or `.git`.
60
+ - If you run from this package directory during BrainRouter development, the CLI promotes the workspace to the monorepo root so tools see the whole project, not only `brainrouter/`.
61
+ - Override manually with `--workspace /absolute/path/to/project` or `BRAINROUTER_WORKSPACE=/absolute/path/to/project`.
62
+ - In the REPL, run `/workspace` to confirm the active root and session key.
63
+
64
+ ### Host Login / Setup Connection
65
+ Interactively log in to a hosted HTTP/SSE BrainRouter deployment and test latency/connectivity:
66
+ From the repository root:
67
+ ```bash
68
+ npm run cli login
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Interactive REPL Slash Commands
74
+
75
+ Within the chat session, type `/` to access commands:
76
+ - `/help` — List all available directive commands.
77
+ - `/status` — Display active server profile details, LLM model, server latency check, and database size stats.
78
+ - `/workspace` — Show active workspace root, launch directory, and BrainRouter session key.
79
+ - `/tools` — Show local workspace tools and MCP tools exposed to the LLM.
80
+ - `/doctor` — Check active profile, MCP connectivity, plan + session store health, and orchestration tool availability.
81
+ - `/skills` — Visualize all loaded BrainRouter skills and categories.
82
+ - `/plan` — Show the durable CLI task plan persisted under `.brainrouter/cli/tasks.json`.
83
+ - `/transcript [main|sessionKey]` — Show recent persisted transcript entries.
84
+ - `/roles` — List built-in agent roles (`explorer`, `architect`, `reviewer`, `worker`, `verifier`) with default access modes.
85
+ - `/agents` — List child agent sessions with status, role, label, and elapsed time.
86
+ - `/agent <id>` — Show child detail, prompt, final output, and recent transcript.
87
+ - `/spawn <role> <prompt>` — Spawn a child agent (parent narrates via the LLM tool call).
88
+ - `/wait <id> [timeoutMs]` — Wait for a child agent to finish.
89
+ - `/spec <title>` — Runs the **spec-driven-skill** and writes a full `spec.md` to `<workspace>/.brainrouter/cli/workflows/<slug>/spec.md`. Stops for approval before generating tasks.
90
+ - `/approve [slug]` — Approves the current (or named) workflow and kicks off the worker + verifier implementation phase, one task at a time, appending to `walkthrough.md`.
91
+ - `/workflows` — List durable workflow folders with per-artifact status (`spec.md`, `tasks.md`, `walkthrough.md`).
92
+ - `/feature-dev <feature>` — Runs the catalogued **agentic-engineering-workflow** skill with explorer + architect orchestration. Writes `spec.md` and `tasks.md` to the workflow folder, then stops for user approval before worker implementation.
93
+ - `/review [scope]` — Runs the catalogued **code-review-and-quality** skill with 3 parallel reviewer agents (correctness, maintainability, conventions).
94
+ - `/implement-plan` — Runs the catalogued **incremental-skill** with a worker + verifier loop on the next pending plan item.
95
+ - `/skill <name> [input]` — Generic invoker for any skill in your `skills/` catalogue. The CLI fetches the skill body via the MCP `get_skill` tool, falls back to filesystem (`skills/**/SKILL.md`), and hands the agent a structured prompt that embeds the skill instructions plus orchestration affordances (`spawn_agent`, `update_plan`).
96
+
97
+ ### Skill-driven workflows
98
+
99
+ The CLI ships with a thin slash → skill mapping (see `brainrouter-cli/src/prompt/skillRunner.ts`). Slash commands do **not** carry monolithic hard-coded prompts; they delegate to the SKILL.md authored under `skills/`. This means improving a workflow is a documentation edit, not a code change. Add a new mapping in `SLASH_TO_SKILL` to expose a new slash command, or use `/skill <name>` to invoke any skill ad-hoc.
100
+
101
+ #### How the skill catalogue is discovered
102
+
103
+ The CLI resolves a skill body in this order:
104
+
105
+ 1. **MCP `get_skill` tool** — the connected MCP server merges *global* skills (the canonical BrainRouter catalogue) with *local* skills the user authored under `<workspace>/skills/` or `<workspace>/projects/*/skills/`. Local skills shadow global ones on name conflict. This is the path used in normal operation.
106
+ 2. **Filesystem fallback** (used only when MCP is unreachable) searches, in order:
107
+ - `<workspace>/skills/**/SKILL.md`
108
+ - `<workspace>/.brainrouter/skills/**/SKILL.md`
109
+ - The installed `@kinqs/brainrouter-mcp-server` package directory (resolved via `require.resolve`). This works because the MCP package bundles the canonical catalogue at publish time (see below).
110
+ 3. Otherwise the CLI hands the agent a benign placeholder and asks it to use general judgement.
111
+
112
+ #### Catalogue bundling at publish time
113
+
114
+ The `@kinqs/brainrouter-mcp-server` package ships with the full BrainRouter skill catalogue baked in, so a user who only runs `npm install @kinqs/brainrouter-mcp-server @kinqs/brainrouter-cli` in their own workspace gets all 70+ canonical skills out of the box — no monorepo checkout required.
115
+
116
+ This is done via two lifecycle scripts in `brainrouter/scripts/`:
117
+
118
+ - `prepack.mjs` — runs before `npm pack`/`npm publish`. Copies `skills/`, `agents/`, `references/`, and `docs/` from the monorepo root into the package directory and records what it copied in `.bundled-content.json`.
119
+ - `postpack.mjs` — runs after pack. Reads the marker and removes exactly what `prepack` added, leaving the working tree clean.
120
+
121
+ The MCP server's resolver ([brainrouter/src/resolver.ts](../brainrouter/src/resolver.ts)) prefers the package's own `skills/` when present (installed-package mode) and otherwise walks up to the monorepo root (development mode). Both layouts work identically from the CLI's point of view.
122
+
123
+ ### Durable workflow artifacts (one folder per workflow)
124
+
125
+ All multi-step commands (`/spec`, `/feature-dev`, `/review`, `/implement-plan`) anchor to a workflow slug and write their outputs to:
126
+
127
+ ```
128
+ <workspace>/.brainrouter/cli/workflows/<slug>/
129
+ meta.json # { slug, title, kind, createdAt, updatedAt, status }
130
+ spec.md # produced by /spec or /feature-dev phase 3
131
+ tasks.md # produced by /feature-dev phase 3
132
+ walkthrough.md # appended by /implement-plan as items ship
133
+ review.md # produced by /review
134
+ ```
135
+
136
+ The orchestration prompts for these commands **require** the agent to call `write_file` with the exact workspace-relative path — no chat-only plans. Use `/workflows` to inspect what's on disk. `getCurrentWorkflow` tracks the most recent one so `/implement-plan` appends to it automatically.
137
+
138
+ The system prompt also directs the agent to redirect free-form spec/plan requests to `/spec` or `/feature-dev` instead of producing inline monoliths, so the "one place" rule survives even when you don't type a slash command.
139
+
140
+ ### Memory-native flow
141
+
142
+ Each parent turn runs three memory queries in parallel before the LLM sees the user prompt:
143
+
144
+ 1. **`memory_recall`** — cognitive memory most relevant to the prompt.
145
+ 2. **`memory_working_context`** — current working canvas, so resumed sessions don't reset.
146
+ 3. **`memory_task_state`** — open tasks / handover notes for this workspace.
147
+
148
+ The merged briefing (secrets redacted via `redactText`) is injected as a system message and the recalled record IDs are tracked through the whole turn. At end-of-turn, `selectCitedRecordIds` heuristically picks the records that actually informed the answer (by ID mention or distinctive content match) and reports them via `memory_mark_cited` — replacing the previous always-empty citation list, so System-1 recall actually learns.
149
+
150
+ Child agents (`spawn_agent`) skip the full briefing for speed but accept a `seedRecordIds: string[]` parameter so the parent can hand over what it already recalled. Long child outputs (≥ 6,000 chars) are automatically offloaded to `memory_working_offload` and only a preview + ref handle is returned to the parent — the main context-saving win when synthesizing multiple child reports.
151
+
152
+ After every turn, the CLI also asks `memory_contradictions` and surfaces a one-line warning in the REPL when newly-captured beliefs disagree with prior ones, so drift gets caught instead of silently accumulating.
153
+
154
+ Inspection commands:
155
+
156
+ - `/memory <query>` — search long-term cognitive memory (`memory_search`).
157
+ - `/recall <query>` — explicit `memory_recall`, no LLM turn.
158
+ - `/briefing` — what was recalled before the most recent turn.
159
+ - `/scenes` — list active focus scenes.
160
+ - `/working` — current working-memory canvas.
161
+ - `/forget <recordId>` — archive an obsolete memory.
162
+
163
+ The workflow commands `/feature-dev`, `/review`, and `/implement-plan` are now required to open with `memory_search` (plus `memory_graph_query` / `memory_file_history` / `memory_task_state` depending on the workflow) and pass `seedRecordIds` to children, so no exploration is ever duplicated across sessions.
164
+
165
+ ### Child agent permissions
166
+
167
+ Child agents default to the safest mode for their role: `explorer`, `architect`, `reviewer` are `read`; `worker` is `write`; `verifier` is `shell`. Override with `access: "read" | "write" | "shell"` when calling `spawn_agent`. Shell execution from children runs unattended — only grant `shell` to trusted roles like `verifier`.
168
+ - `/config` — Output active configuration details (with security sanitization for API keys).
169
+ - `/compact` — Clear the active chat context while keeping the session identity.
170
+ - `/clear` — Wipe the chat history of the active session.
171
+ - `/exit` — Close connections and exit.
172
+
173
+ ---
174
+
175
+ ## Autonomous Tool Execution
176
+
177
+ The agent coordinates two scopes of tools:
178
+ 1. **BrainRouter Memory Tools** (loaded dynamically via the MCP connection): `memory_recall`, `memory_capture_turn`, `list_skills`, etc.
179
+ 2. **Local Workspace Tools**:
180
+ - `read_file` — Reads content of a workspace file.
181
+ - `write_file` — Overwrites or writes a new file.
182
+ - `edit_file` — Performs safe single-match string search-and-replace.
183
+ - `list_dir` — Lists directory paths.
184
+ - `grep_search` — Platform-independent recursive search of code patterns.
185
+ - `run_command` — Runs a shell command on your host (always requests manual confirmation first for safety).