@nanhara/hara 0.0.2 → 0.33.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +431 -0
  2. package/CLA.md +1 -1
  3. package/README.md +199 -10
  4. package/dist/activity.js +30 -0
  5. package/dist/agent/loop.js +184 -0
  6. package/dist/config.js +114 -0
  7. package/dist/context/agents-md.js +64 -0
  8. package/dist/context/mentions.js +90 -0
  9. package/dist/diff.js +103 -0
  10. package/dist/fs-walk.js +103 -0
  11. package/dist/fuzzy.js +62 -0
  12. package/dist/images.js +146 -0
  13. package/dist/index.js +1362 -0
  14. package/dist/mcp/client.js +54 -0
  15. package/dist/md.js +52 -0
  16. package/dist/memory/guard.js +51 -0
  17. package/dist/memory/store.js +93 -0
  18. package/dist/org/planner.js +155 -0
  19. package/dist/org/roles.js +140 -0
  20. package/dist/org/router.js +39 -0
  21. package/dist/plugins/plugins.js +124 -0
  22. package/dist/providers/anthropic.js +83 -0
  23. package/dist/providers/openai.js +125 -0
  24. package/dist/providers/qwen-oauth.js +139 -0
  25. package/dist/providers/types.js +2 -0
  26. package/dist/recall.js +76 -0
  27. package/dist/sandbox.js +78 -0
  28. package/dist/search/embed.js +42 -0
  29. package/dist/search/hybrid.js +38 -0
  30. package/dist/search/semindex.js +141 -0
  31. package/dist/session/store.js +95 -0
  32. package/dist/skills/skills.js +141 -0
  33. package/dist/statusbar.js +69 -0
  34. package/dist/tools/agent.js +26 -0
  35. package/dist/tools/apply-core.js +63 -0
  36. package/dist/tools/builtin.js +106 -0
  37. package/dist/tools/codebase.js +102 -0
  38. package/dist/tools/computer.js +236 -0
  39. package/dist/tools/edit.js +62 -0
  40. package/dist/tools/memory.js +147 -0
  41. package/dist/tools/patch.js +123 -0
  42. package/dist/tools/registry.js +18 -0
  43. package/dist/tools/search.js +176 -0
  44. package/dist/tools/skill.js +30 -0
  45. package/dist/tools/web.js +73 -0
  46. package/dist/tui/App.js +165 -0
  47. package/dist/tui/InputBox.js +208 -0
  48. package/dist/tui/run.js +10 -0
  49. package/dist/tui/theme.js +11 -0
  50. package/dist/ui.js +17 -0
  51. package/dist/undo.js +40 -0
  52. package/dist/vision.js +81 -0
  53. package/package.json +32 -8
  54. package/LICENSE-MIT +0 -21
  55. package/bin/hara.mjs +0 -25
  56. /package/{LICENSE-APACHE → LICENSE} +0 -0
package/README.md CHANGED
@@ -6,23 +6,212 @@
6
6
  > with routing boundaries, a dispatcher, a single source-of-truth data layer, human-in-the-loop
7
7
  > approvals, and cron autonomy.
8
8
 
9
- 🚧 **Early placeholder.** The real CLI is under active development. This package reserves
10
- `@nanhara/hara` on npm. Follow along:
9
+ 🚧 **v0.33** · TypeScript · local-first · Apache-2.0
11
10
 
12
- - Repo: https://github.com/hara-cli/hara
13
- - Site: https://hara.run
11
+ **Highlights**
12
+ - **An org, not just an agent** — `hara org "<task>"` routes work to the role that *owns* it; `hara plan "<task>"` decomposes a task into a verified DAG of atoms (frame → atomize → sequence → execute → **verify gate**).
13
+ - **Real terminal UX** — an **ink TUI**: bottom-pinned input box, **plan mode** (read-only → propose a plan → approve → execute), selectable approvals with "don't ask again", windowed reasoning, **paste images** (Ctrl+V) for vision models, light/dark theme.
14
+ - **Persistent memory + self-evolution** — `memory_*` tools over global/project `MEMORY.md`; the agent recalls before acting, **proactively saves** durable facts, and grows its own playbooks (a lexical guard screens what it writes).
15
+ - **Multi-provider, all streamed** — Anthropic (Claude) or any OpenAI-compatible endpoint (Qwen/DashScope, GLM, Kimi, OpenAI) with live Markdown + visible reasoning.
16
+ - **Solid coding core** — `edit_file` / `apply_patch` (atomic multi-file) with colored diffs · `grep`/`glob`/`ls`/`codebase_search` (lexical + optional semantic search over the repo) /`web_fetch` · fuzzy `@file` · `/undo` · `/compact` · **Esc-to-interrupt** · parallel sub-agents · MCP client · macOS sandbox.
17
+
18
+ Track it: https://github.com/hara-cli/hara · https://hara.run
19
+
20
+ ## Install
14
21
 
15
22
  ```bash
16
23
  npm i -g @nanhara/hara
17
- hara # prints status
18
- hara --version
19
24
  ```
20
25
 
21
- ## License
26
+ Or from source:
27
+
28
+ ```bash
29
+ git clone https://github.com/hara-cli/hara && cd hara
30
+ npm install # builds via the prepare script
31
+ npm install -g . # or: npm link
32
+ ```
33
+
34
+ ## Quickstart
35
+
36
+ ```bash
37
+ npm i -g @nanhara/hara
38
+ hara login qwen # free Qwen OAuth (or: export ANTHROPIC_API_KEY=…)
39
+ cd your-project
40
+ hara # offers to write AGENTS.md, then drops you into the TUI
41
+ ```
42
+
43
+ Then just type a task — e.g. `fix the null check in @src/login.ts and run the tests`.
44
+ **shift+tab** cycles approvals (incl. **plan mode**) · **Esc** interrupts · `@`+Tab attaches a file · `/exit` quits.
45
+
46
+ One-shot, no REPL:
47
+
48
+ ```bash
49
+ hara -p "summarize @README.md and list any TODOs"
50
+ ```
51
+
52
+ ## Setup
53
+
54
+ hara is **multi-provider** — pick a provider + key.
55
+
56
+ **Anthropic (default)**
57
+ ```bash
58
+ export ANTHROPIC_API_KEY=sk-ant-...
59
+ ```
60
+
61
+ **Qwen — free OAuth** ("Qwen Code" tier, no API key — same flow as OpenClaw)
62
+ ```bash
63
+ hara login qwen # device login: open the printed URL, approve — token auto-refreshes
64
+ ```
65
+
66
+ **Qwen — DashScope API key** (Alibaba Model Studio, OpenAI-compatible)
67
+ ```bash
68
+ hara config set provider qwen
69
+ hara config set apiKey sk-... # your DashScope model-studio key
70
+ hara config set model qwen-plus # or qwen-max, qwen3-coder-plus, …
71
+ # endpoint defaults to dashscope compatible-mode/v1
72
+ #
73
+ # coding-plan keys (sk-sp-…) use the coding endpoint instead:
74
+ # hara config set baseURL https://coding.dashscope.aliyuncs.com/v1
75
+ # hara config set model qwen3.7-plus
76
+ # plan models: qwen3.7-plus, qwen3.6-plus, qwen3-coder-plus, qwen3-coder-next,
77
+ # qwen3-max-2026-01-23, glm-5, glm-4.7 (switch with -m or /model)
78
+ ```
79
+
80
+ > Plan keys (Coding Plan / Token Plan) are licensed **only** for use inside AI coding agents /
81
+ > OpenClaw-type tools like hara — not Dify/n8n, API-testing tools, or direct script/backend calls.
22
82
 
23
- Licensed under either of **MIT** ([LICENSE-MIT](LICENSE-MIT)) or **Apache-2.0**
24
- ([LICENSE-APACHE](LICENSE-APACHE)) at your option.
83
+ **Any OpenAI-compatible endpoint** (GLM, Kimi, OpenAI, local servers)
84
+ ```bash
85
+ hara config set provider openai
86
+ hara config set baseURL https://your-endpoint/v1
87
+ hara config set apiKey ...
88
+ hara config set model ...
89
+ ```
90
+
91
+ **Vision** — hara **auto-detects** whether your main model can see images. A vision model (Claude, gpt-4o,
92
+ qwen-vl, glm-4v…) gets pasted images **inline**. For a **text-only** model (DeepSeek, coding models), set a
93
+ describer — the "eyes" — and hara OCRs/describes each pasted image into text first:
94
+ ```bash
95
+ hara config set visionModel qwen-vl-max # a vision model on the same plan/key
96
+ # point it elsewhere if your endpoint doesn't serve vision:
97
+ # hara config set visionBaseURL https://dashscope.aliyuncs.com/compatible-mode/v1
98
+ # hara config set visionApiKey sk-...
99
+ ```
100
+ If a model's capability is unknown, hara **asks once and remembers**. In the TUI, `/vision <model>` sets the
101
+ describer and `/vision main yes|no|auto` corrects a model's detected capability.
102
+
103
+ Config lives in `~/.hara/config.json`. Env vars override it: `HARA_PROVIDER`, `HARA_MODEL`,
104
+ `HARA_BASE_URL`, `HARA_API_KEY`, or the provider key (`ANTHROPIC_API_KEY` / `DASHSCOPE_API_KEY`).
105
+
106
+ ## Use
107
+
108
+ ```bash
109
+ hara # interactive REPL (offers to create AGENTS.md on first run)
110
+ hara init # analyze the project & (re)generate AGENTS.md
111
+ hara doctor # check your setup (auth / model / node / assets / roles)
112
+ hara roles init # scaffold role-agents (implementer / reviewer / docs)
113
+ hara org "review src/ for bugs" # dispatch a task to the role that owns it (or --role <id>)
114
+ hara plan "add a /health endpoint with a test" # decompose → sequence (DAG) → run each step + verify
115
+ hara -p "summarize @README.md and fix the lint errors in src/" # one-shot; @path attaches a file
116
+ hara --approval auto-edit # suggest (default) | auto-edit | full-auto (-y = full-auto)
117
+ hara --sandbox workspace-write # confine shell writes to the project (macOS Seatbelt)
118
+ hara -c # resume the most recent session in this directory
119
+ hara --profile work # use a named profile from ~/.hara/config.json
120
+ hara -m glm-5 # pick a model
121
+ ```
122
+
123
+ Inside the REPL: `/help` `/init` `/tools` `/model` `/approval` `/org` `/plan` `/roles` `/usage` `/doctor` `/sessions` `/undo` `/compact` `/recall` `/reset` `/exit` (type `/`+Tab to complete). Type `@` + Tab to attach a file (fuzzy, walks subdirectories).
124
+
125
+ The interactive REPL is an **ink TUI**: a bordered **input box pinned at the bottom** — session name in
126
+ the top-right corner, approval modes + token usage + concurrency in the bottom border — with the
127
+ conversation scrolling above it. Streaming text, reasoning, tool calls, and colored diffs render as live
128
+ blocks; a spinner runs during a turn. **shift+tab** cycles the approval mode, **Esc** interrupts a running
129
+ turn, and tool approvals appear inline (y/N). **Ctrl+V** pastes an image from your clipboard (a screenshot,
130
+ or a copied image) — or drag an image file into the terminal — and it appears as a highlighted `[Image #N]`
131
+ token inline where your cursor is (backspace over it to remove it). hara auto-detects the model's capability —
132
+ a vision model sees the image directly; a text-only model routes it through a `visionModel` describer (see
133
+ Setup), shown in the header at startup. Set `HARA_TUI=0` for the classic readline REPL.
134
+
135
+ Each session gets a **UUID** and an **auto-summarized name** from your first message (kept verbatim, CJK
136
+ included); `hara sessions` lists them by short id, and `--resume <prefix>` accepts the short id.
137
+
138
+ Assistant output is **rendered as Markdown** (headers, bold, inline code, lists; code fences verbatim),
139
+ and a model's **reasoning** shows dimmed before the answer when available. Both are interactive-terminal
140
+ only; `HARA_MD=0` disables Markdown rendering.
141
+
142
+ **Skills** — reusable capabilities on the **agentskills.io standard** (`SKILL.md`, interoperable with Claude
143
+ Code / codex / openclaw). Drop a `~/.hara/skills/<name>/SKILL.md` (or project `.hara/skills/`) with `name` +
144
+ `description` frontmatter and Markdown instructions; the agent sees the list and calls the `skill` tool to load
145
+ a skill's full body only when it's relevant (progressive disclosure). `hara skills init` scaffolds one, `hara
146
+ skills` lists them, `/skill <id>` loads one into your next message, and the agent saves its own with
147
+ `skill_create` (`scope: project|personal`). Optional frontmatter: `when_to_use`, `allowed-tools`, `context: fork` (run as a sub-agent), `paths`.
148
+ When the agent saves a skill, secrets are **redacted** and local paths/emails **generalized** (`<project>` / `~` / `<email>`),
149
+ and a near-duplicate is flagged so it updates instead of piling up. `assetCapture: off|ask|auto` controls proactive end-of-session capture.
150
+
151
+ **Plugins** — bundle skills + roles + MCP servers in one installable unit (Claude-Code-compatible
152
+ `plugin.json` / `.claude-plugin/`). `hara plugin add file:<path> | github:<owner/repo> | git:<url>` installs it;
153
+ `hara plugin` lists; `enable`/`disable`/`remove`. A plugin's skills/roles/MCP auto-contribute (your project &
154
+ global override them). `.claude/agents/*.md` subagents load as roles too.
155
+
156
+ **Recall** — `hara recall --init` creates a personal `~/.hara/code-assets` library (snippets as `*.md`);
157
+ `hara recall "<query>"` searches it **plus your skills** (one corpus), and `/recall <query>` pulls the best
158
+ matches into your next message. A git-versionable library of code/patterns you want to reuse (`HARA_ASSETS` overrides the path).
159
+
160
+ **Semantic search** (opt-in) — `codebase_search`, `recall`, and `memory_search` can find things by *meaning*,
161
+ not just keywords. By default they're lexical (zero setup). Configure an embedding provider, then build an index:
162
+ `hara config set embedProvider ollama` (local & offline, e.g. `bge-m3`/`nomic-embed-text`) or `qwen` (DashScope),
163
+ then `hara index` (repo, for `codebase_search`) / `hara index --assets` (code-assets, skills & memory) / `hara
164
+ index --all`. A query like "read an image pasted from the clipboard" then surfaces `src/images.ts` even with no
165
+ shared words. Indexes are rebuildable `.hara/index/` artifacts (self-`.gitignore`d, never committed); no native
166
+ vector DB needed, and lexical still works when there's no index.
167
+
168
+ **Approval modes**: `suggest` confirms edits & shell · `auto-edit` auto-applies file edits but confirms shell · `full-auto` runs everything.
169
+ **Sandbox** (macOS): `--sandbox workspace-write|read-only` runs the `bash` tool under Seatbelt (writes confined to the project / blocked).
170
+ **Screen control** (opt-in): the `computer` tool drives desktop software (screenshot → click/type), native per OS
171
+ (mac `screencapture`+`cliclick` · Windows PowerShell · Linux `scrot`+`xdotool`). Off by default — enable a tier with
172
+ `hara config set computerUse read|click|full` and allowlist apps with `hara config set computerApps "App, …"`. Guarded
173
+ by the tier, the frontmost-app allowlist, a dangerous-key blocklist, and a once-per-session grant; screenshots are read via your vision model.
174
+ **Sessions**: conversations are saved automatically — `-c` / `--resume <id>` to continue, `hara sessions` to list.
175
+ **MCP**: add an `mcpServers` map to config (global or project `.hara/config.json`); their tools appear to the agent as `mcp__<server>__<tool>`.
176
+ **Profiles**: add a `profiles` map to `~/.hara/config.json` (`--profile <name>`), or drop a project-level `.hara/config.json` that overrides the global config.
177
+
178
+ ### The org — what makes hara different
179
+
180
+ Define role-agents in `.hara/roles/*.md` — each is a persona (the file body) plus frontmatter: `owns`
181
+ (keywords that route a task here), optional `rejects`, `model`, and `allowTools`/`denyTools`. `hara org
182
+ "<task>"` routes the task to the role that **owns** it (keyword match, LLM fallback) and runs that role's
183
+ agent — e.g. a read-only `reviewer` that reports issues vs an `implementer` that edits code. `hara roles`
184
+ lists them, `hara roles init` scaffolds a starter set, and `--role <id>` forces a specific role. The
185
+ **`agent`** tool spawns **parallel read-only sub-agents** for fan-out — analyze / review / search
186
+ several things at once (each can take a `role`).
187
+
188
+ Beyond routing, **`hara plan "<task>"`** makes the org *plan*: it decomposes the task into atoms,
189
+ sequences them as a DAG, and executes each step (optionally routed to a role) behind a per-step
190
+ **verify gate** — frame → atomize → sequence → execute → verify. Each atom may carry a `check` shell
191
+ command, so verification is **objective** (e.g. `npm test`, `tsc --noEmit`) rather than a
192
+ self-assessment. Plan state is the SSOT at `.hara/org/plan.json` (inspectable; execution stops on the
193
+ first failed verification).
194
+
195
+ ### What it can do
196
+
197
+ A streaming agentic loop with built-in tools — `read_file`, `write_file`, **`edit_file`** /
198
+ **`apply_patch`** (surgical edits — single file, or **atomic multi-file** changes), `bash`, and
199
+ read-only **`grep`** / **`glob`** / **`ls`** / **`web_fetch`** — behind a human-in-the-loop confirmation gate on the
200
+ dangerous ones unless `-y`. Read-only tools run in parallel within a turn, and edits print a
201
+ **colored diff** of what changed. Shell output streams live; press **Esc** to interrupt a running
202
+ turn, or **`/undo`** to revert the last edit.
203
+ - **Project context**: auto-loads `AGENTS.md` (the cross-tool standard) walking up to the repo root; `hara init` writes one by analyzing the repo.
204
+ - **`@file` mentions**: attach file contents to a message (`@path`); Tab-completes with a **fuzzy** matcher over the project (subdirs, git-tracked + untracked) — `@idx` → `src/index.ts`. `@<dir>` loads a directory listing, `@src/`+Tab drills into a folder, and mistyped tool/file paths get a "did you mean" suggestion.
205
+ - **Multi-provider**: Anthropic (Claude) or any OpenAI-compatible endpoint (Qwen/DashScope, GLM, Kimi, OpenAI) — **all streamed live**.
206
+
207
+ ### Roadmap
208
+
209
+ **Shipped:** ink TUI · plan mode · persistent memory + self-evolution · atomization planner · parallel sub-agents · `/compact` context management.
210
+ **Next:** parallel plan atoms · multi-role review chains · cron autonomy for the org · single-binary distribution · an enterprise control-plane (fleet + central token management).
211
+
212
+ ## License
25
213
 
26
- Contributions are accepted under these terms; see [CLA.md](CLA.md).
214
+ Licensed under the **Apache License 2.0** ([LICENSE](LICENSE)) — a permissive license with an
215
+ explicit patent grant. Contributions per [CLA.md](CLA.md).
27
216
 
28
217
  © 2026 Nanhara
@@ -0,0 +1,30 @@
1
+ // Live concurrency signal — how many tool/subagent operations are in flight right now.
2
+ // The status bar subscribes to render the "⛁ N" indicator; the agent loop inc/dec around
3
+ // parallel tool execution (and, later, spawned subagents).
4
+ let running = 0;
5
+ let peak = 0;
6
+ let listener = null;
7
+ export const activity = {
8
+ get running() {
9
+ return running;
10
+ },
11
+ get peak() {
12
+ return peak;
13
+ },
14
+ inc() {
15
+ running++;
16
+ if (running > peak)
17
+ peak = running;
18
+ listener?.();
19
+ },
20
+ dec() {
21
+ running = Math.max(0, running - 1);
22
+ listener?.();
23
+ },
24
+ resetPeak() {
25
+ peak = running;
26
+ },
27
+ onChange(fn) {
28
+ listener = fn;
29
+ },
30
+ };
@@ -0,0 +1,184 @@
1
+ import { getTool, toolSpecs } from "../tools/registry.js";
2
+ import { stdout } from "node:process";
3
+ import { c, out } from "../ui.js";
4
+ import { activity } from "../activity.js";
5
+ import { makeRenderer } from "../md.js";
6
+ import { skillsDigest } from "../skills/skills.js";
7
+ /** Whether a tool call needs user confirmation under the given approval mode. */
8
+ export function needsConfirm(kind, mode) {
9
+ if (kind === "read")
10
+ return false;
11
+ if (kind === "computer")
12
+ return true; // screen control always needs a session grant (even full-auto)
13
+ if (mode === "full-auto")
14
+ return false;
15
+ if (mode === "auto-edit")
16
+ return kind === "exec";
17
+ return true; // suggest: confirm edits and exec
18
+ }
19
+ const HARA_SYSTEM = (cwd) => `You are hara, a coding agent running in the user's terminal.
20
+ Working directory: ${cwd}
21
+ Be concise and direct. Use the provided tools to read files, edit/write files, and run shell
22
+ commands. Prefer small, verifiable steps; edit existing files with edit_file rather than rewriting
23
+ them whole. You have a persistent memory: use memory_search before answering about prior decisions,
24
+ conventions, or the user's preferences, and memory_write to proactively save durable facts you learn.
25
+ When a task matches one of the Skills listed below, call the \`skill\` tool to load its full instructions
26
+ before acting; save a reusable how-to as a new skill with skill_create. If you discover a durable project
27
+ convention, you may propose an edit to AGENTS.md via edit_file (the user reviews the diff). After completing
28
+ a task, give a one-line summary.`;
29
+ function composeSystem(cwd, projectContext, override, memory) {
30
+ const head = override ? `${override}\n\nWorking directory: ${cwd}` : HARA_SYSTEM(cwd);
31
+ const skills = skillsDigest(cwd);
32
+ return (head +
33
+ (projectContext ? `\n\n# Project context (AGENTS.md)\n${projectContext}` : "") +
34
+ (memory ? `\n\n# Memory (durable — facts/decisions/prefs you've saved; use memory_search/get for more)\n${memory}` : "") +
35
+ (skills ? `\n\n# Skills (capabilities you can load — call the \`skill\` tool with the id for full instructions before using one)\n${skills}` : ""));
36
+ }
37
+ /** Provider-agnostic agentic loop. Mutates `history` in place. */
38
+ export async function runAgent(history, opts) {
39
+ const { provider, ctx } = opts;
40
+ for (;;) {
41
+ const specs = opts.toolFilter ? toolSpecs().filter((t) => opts.toolFilter(t.name)) : toolSpecs();
42
+ const sink = ctx.ui; // TUI mode: route output to ink instead of stdout
43
+ const tty = stdout.isTTY && !opts.quiet && !sink;
44
+ const md = tty && process.env.HARA_MD !== "0" ? makeRenderer(out) : null;
45
+ let sawReasoning = false;
46
+ // "working Ns" spinner until the first output arrives (cleared on text/reasoning or turn end)
47
+ let spin = null;
48
+ const stopSpin = () => {
49
+ if (spin) {
50
+ clearInterval(spin);
51
+ spin = null;
52
+ out("\r\x1b[K");
53
+ }
54
+ };
55
+ if (tty) {
56
+ const frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏";
57
+ const t0 = Date.now();
58
+ let fi = 0;
59
+ spin = setInterval(() => out(`\r${c.dim(`${frames[fi++ % frames.length]} working ${Math.floor((Date.now() - t0) / 1000)}s`)}`), 100);
60
+ }
61
+ const r = await provider.turn({
62
+ system: composeSystem(ctx.cwd, opts.projectContext, opts.systemOverride, opts.memory),
63
+ history,
64
+ tools: specs,
65
+ onText: (d) => {
66
+ if (opts.quiet)
67
+ return;
68
+ if (sink) {
69
+ sink.text(d);
70
+ return;
71
+ }
72
+ stopSpin();
73
+ if (sawReasoning) {
74
+ out("\n");
75
+ sawReasoning = false;
76
+ }
77
+ if (md)
78
+ md.push(d);
79
+ else
80
+ out(d);
81
+ },
82
+ onReasoning: sink || tty
83
+ ? (d) => {
84
+ if (opts.quiet)
85
+ return;
86
+ if (sink) {
87
+ sink.reasoning(d);
88
+ return;
89
+ }
90
+ stopSpin();
91
+ sawReasoning = true;
92
+ out(c.dim(d));
93
+ }
94
+ : undefined,
95
+ signal: opts.signal,
96
+ });
97
+ stopSpin();
98
+ md?.end();
99
+ if (!opts.quiet && !sink)
100
+ out("\n");
101
+ if (r.usage && opts.stats) {
102
+ opts.stats.input += r.usage.input;
103
+ opts.stats.output += r.usage.output;
104
+ opts.stats.lastInput = r.usage.input;
105
+ }
106
+ history.push({ role: "assistant", text: r.text, toolUses: r.toolUses });
107
+ if (r.stop === "error") {
108
+ const msg = r.errorMsg === "interrupted" ? "(interrupted)" : `[${provider.id} error] ${r.errorMsg ?? "unknown"}`;
109
+ if (!opts.quiet) {
110
+ if (sink)
111
+ sink.notice(msg);
112
+ else
113
+ out(r.errorMsg === "interrupted" ? c.dim(`\n${msg}\n`) : c.red(`${msg}\n`));
114
+ }
115
+ return;
116
+ }
117
+ if (r.stop !== "tool_use")
118
+ return;
119
+ const plans = [];
120
+ for (const tu of r.toolUses) {
121
+ const tool = getTool(tu.name);
122
+ if (!tool) {
123
+ plans.push({ tu, tool: undefined, denied: `Unknown tool: ${tu.name}` });
124
+ continue;
125
+ }
126
+ const input = tu.input;
127
+ const preview = String(input.path ?? input.command ?? input.pattern ?? input.url ?? input.task ?? "")
128
+ .replace(/\s+/g, " ")
129
+ .trim();
130
+ if (needsConfirm(tool.kind, opts.approval) && !opts.autoApprove?.has(tu.name)) {
131
+ const reply = await opts.confirm(`${c.yellow("⚠")} ${c.bold(tu.name)} ${c.dim(preview)} — run?`);
132
+ if (reply === false) {
133
+ plans.push({ tu, tool, denied: "User denied this action." });
134
+ continue;
135
+ }
136
+ if (reply === "always")
137
+ opts.autoApprove?.add(tu.name);
138
+ }
139
+ plans.push({ tu, tool });
140
+ if (!opts.quiet) {
141
+ const pv = preview ? preview.slice(0, 80) : "";
142
+ if (sink)
143
+ sink.tool(tu.name, pv);
144
+ else
145
+ out(c.dim(` ↳ ${tu.name}${pv ? " " + pv : ""}\n`));
146
+ }
147
+ }
148
+ // Execute: read-only tools run concurrently; edit/exec run alone, in order.
149
+ const results = new Array(plans.length);
150
+ const runOne = async (idx, p) => {
151
+ if (p.denied !== undefined) {
152
+ results[idx] = { id: p.tu.id, name: p.tu.name, content: p.denied, isError: true };
153
+ return;
154
+ }
155
+ activity.inc();
156
+ try {
157
+ const res = await p.tool.run(p.tu.input, ctx);
158
+ results[idx] = { id: p.tu.id, name: p.tu.name, content: res };
159
+ }
160
+ catch (e) {
161
+ results[idx] = { id: p.tu.id, name: p.tu.name, content: `Error: ${e.message}`, isError: true };
162
+ }
163
+ finally {
164
+ activity.dec();
165
+ }
166
+ };
167
+ let batch = [];
168
+ for (let i = 0; i < plans.length; i++) {
169
+ const p = plans[i];
170
+ if (p.denied === undefined && p.tool?.kind === "read") {
171
+ batch.push(runOne(i, p)); // safe → accumulate to run concurrently
172
+ }
173
+ else {
174
+ if (batch.length) {
175
+ await Promise.all(batch); // flush pending reads before an edit/exec
176
+ batch = [];
177
+ }
178
+ await runOne(i, p);
179
+ }
180
+ }
181
+ await Promise.all(batch);
182
+ history.push({ role: "tool", results });
183
+ }
184
+ }
package/dist/config.js ADDED
@@ -0,0 +1,114 @@
1
+ import { homedir } from "node:os";
2
+ import { join, dirname, resolve } from "node:path";
3
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
4
+ const PROVIDER_DEFAULTS = {
5
+ anthropic: { model: "claude-opus-4-8", envKey: "ANTHROPIC_API_KEY" },
6
+ qwen: {
7
+ model: "qwen-plus",
8
+ baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
9
+ envKey: "DASHSCOPE_API_KEY",
10
+ },
11
+ "qwen-oauth": { model: "coder-model", envKey: "QWEN_OAUTH_TOKEN" },
12
+ openai: { model: "gpt-4o-mini", envKey: "OPENAI_API_KEY" },
13
+ };
14
+ export const CONFIG_KEYS = ["provider", "apiKey", "model", "baseURL", "approval", "sandbox", "theme", "evolve", "assetCapture", "computerUse", "computerApps", "visionModel", "visionBaseURL", "visionApiKey", "embedProvider", "embedModel", "embedBaseURL", "embedApiKey"];
15
+ export const APPROVAL_MODES = ["suggest", "auto-edit", "full-auto"];
16
+ export const SANDBOX_MODES = ["off", "workspace-write", "read-only"];
17
+ const PROJECT_ROOT_MARKERS = [".git", "package.json", "Cargo.toml", "go.mod", "pyproject.toml", ".hg"];
18
+ export function configPath() {
19
+ return join(homedir(), ".hara", "config.json");
20
+ }
21
+ export function readRawConfig() {
22
+ const p = configPath();
23
+ if (!existsSync(p))
24
+ return {};
25
+ try {
26
+ return JSON.parse(readFileSync(p, "utf8"));
27
+ }
28
+ catch {
29
+ return {};
30
+ }
31
+ }
32
+ /** Nearest project override `.hara/config.json`, searching cwd up to the repo root. */
33
+ function readProjectConfig(cwd) {
34
+ let dir = resolve(cwd);
35
+ for (;;) {
36
+ const p = join(dir, ".hara", "config.json");
37
+ if (existsSync(p)) {
38
+ try {
39
+ return JSON.parse(readFileSync(p, "utf8"));
40
+ }
41
+ catch {
42
+ return {};
43
+ }
44
+ }
45
+ if (PROJECT_ROOT_MARKERS.some((m) => existsSync(join(dir, m))))
46
+ break; // stop at repo root
47
+ const parent = dirname(dir);
48
+ if (parent === dir)
49
+ break;
50
+ dir = parent;
51
+ }
52
+ return {};
53
+ }
54
+ export function writeConfigValue(key, value) {
55
+ const p = configPath();
56
+ const cfg = readRawConfig();
57
+ cfg[key] = value;
58
+ mkdirSync(dirname(p), { recursive: true });
59
+ writeFileSync(p, JSON.stringify(cfg, null, 2) + "\n", "utf8");
60
+ }
61
+ /** Record (or clear, with cap=null) a confirmed per-model vision capability in `modelVision`. */
62
+ export function setModelVisionOverride(model, cap) {
63
+ const p = configPath();
64
+ const cfg = readRawConfig();
65
+ const map = cfg.modelVision && typeof cfg.modelVision === "object" ? cfg.modelVision : {};
66
+ if (cap === null)
67
+ delete map[model];
68
+ else
69
+ map[model] = cap;
70
+ cfg.modelVision = map;
71
+ mkdirSync(dirname(p), { recursive: true });
72
+ writeFileSync(p, JSON.stringify(cfg, null, 2) + "\n", "utf8");
73
+ }
74
+ /**
75
+ * Effective config. Precedence (high→low): env vars > selected profile >
76
+ * project `.hara/config.json` > global `~/.hara/config.json` > provider defaults.
77
+ */
78
+ export function loadConfig(opts = {}) {
79
+ const global = readRawConfig();
80
+ const { profiles, ...globalBase } = global;
81
+ const project = readProjectConfig(process.cwd());
82
+ const profileName = process.env.HARA_PROFILE ?? opts.profile;
83
+ const profile = profileName && profiles && profiles[profileName] ? profiles[profileName] : {};
84
+ const merged = { ...globalBase, ...project, ...profile };
85
+ const provider = (process.env.HARA_PROVIDER ?? merged.provider ?? "anthropic");
86
+ const d = PROVIDER_DEFAULTS[provider] ?? PROVIDER_DEFAULTS.anthropic;
87
+ const model = process.env.HARA_MODEL ?? merged.model ?? d.model;
88
+ const baseURL = process.env.HARA_BASE_URL ?? merged.baseURL ?? d.baseURL;
89
+ const apiKey = process.env.HARA_API_KEY ?? process.env[d.envKey] ?? merged.apiKey;
90
+ const approval = (process.env.HARA_APPROVAL ?? merged.approval ?? "suggest");
91
+ const sandbox = (process.env.HARA_SANDBOX ?? merged.sandbox ?? "off");
92
+ const theme = (process.env.HARA_THEME ?? merged.theme ?? "dark");
93
+ const evolve = (process.env.HARA_EVOLVE ?? merged.evolve ?? "proactive");
94
+ const assetCapture = (process.env.HARA_ASSET_CAPTURE ?? merged.assetCapture ?? "ask");
95
+ const computerUse = (process.env.HARA_COMPUTER_USE ?? merged.computerUse ?? "off");
96
+ const computerApps = String(process.env.HARA_COMPUTER_APPS ?? merged.computerApps ?? "").split(",").map((s) => s.trim()).filter(Boolean);
97
+ const visionModel = process.env.HARA_VISION_MODEL ?? merged.visionModel;
98
+ const visionBaseURL = process.env.HARA_VISION_BASE_URL ?? merged.visionBaseURL;
99
+ const visionApiKey = process.env.HARA_VISION_API_KEY ?? merged.visionApiKey;
100
+ const modelVision = merged.modelVision && typeof merged.modelVision === "object" ? merged.modelVision : {};
101
+ const embedProvider = (process.env.HARA_EMBED_PROVIDER ?? merged.embedProvider ?? "off");
102
+ const embedModel = process.env.HARA_EMBED_MODEL ?? merged.embedModel;
103
+ const embedBaseURL = process.env.HARA_EMBED_BASE_URL ?? merged.embedBaseURL;
104
+ const embedApiKey = process.env.HARA_EMBED_API_KEY ?? merged.embedApiKey;
105
+ const mcpServers = {
106
+ ...(globalBase.mcpServers ?? {}),
107
+ ...(project.mcpServers ?? {}),
108
+ ...(profile.mcpServers ?? {}),
109
+ };
110
+ return { provider, apiKey, model, baseURL, approval, sandbox, theme, evolve, assetCapture, computerUse, computerApps, visionModel, visionBaseURL, visionApiKey, modelVision, embedProvider, embedModel, embedBaseURL, embedApiKey, mcpServers, cwd: process.cwd() };
111
+ }
112
+ export function providerEnvKey(provider) {
113
+ return (PROVIDER_DEFAULTS[provider] ?? PROVIDER_DEFAULTS.anthropic).envKey;
114
+ }
@@ -0,0 +1,64 @@
1
+ // Project-context loading (AGENTS.md) — the cross-tool standard read by Codex/Claude Code/OpenClaw.
2
+ // Walks up from cwd to the project root, concatenates AGENTS.md files, caps total size.
3
+ import { readFileSync, existsSync } from "node:fs";
4
+ import { join, dirname, resolve } from "node:path";
5
+ const FILENAMES = ["AGENTS.override.md", "AGENTS.md"];
6
+ const ROOT_MARKERS = [".git", "package.json", "Cargo.toml", "go.mod", "pyproject.toml", ".hg"];
7
+ const MAX_BYTES = 32 * 1024;
8
+ export function findProjectRoot(cwd) {
9
+ let dir = resolve(cwd);
10
+ for (;;) {
11
+ if (ROOT_MARKERS.some((m) => existsSync(join(dir, m))))
12
+ return dir;
13
+ const parent = dirname(dir);
14
+ if (parent === dir)
15
+ return resolve(cwd); // no marker found → treat cwd as root
16
+ dir = parent;
17
+ }
18
+ }
19
+ /** Concatenate AGENTS.md files from project root down to cwd (root first), capped at 32 KiB. */
20
+ export function loadAgentsMd(cwd) {
21
+ const root = findProjectRoot(cwd);
22
+ const chain = [];
23
+ let dir = resolve(cwd);
24
+ for (;;) {
25
+ chain.unshift(dir);
26
+ if (dir === root)
27
+ break;
28
+ const parent = dirname(dir);
29
+ if (parent === dir)
30
+ break;
31
+ dir = parent;
32
+ }
33
+ const parts = [];
34
+ for (const d of chain) {
35
+ for (const name of FILENAMES) {
36
+ const p = join(d, name);
37
+ if (existsSync(p)) {
38
+ try {
39
+ const txt = readFileSync(p, "utf8").trim();
40
+ if (txt)
41
+ parts.push(`<!-- ${name} @ ${d} -->\n${txt}`);
42
+ }
43
+ catch {
44
+ /* ignore unreadable */
45
+ }
46
+ }
47
+ }
48
+ }
49
+ let combined = parts.join("\n\n--- project-doc ---\n\n");
50
+ if (Buffer.byteLength(combined, "utf8") > MAX_BYTES) {
51
+ combined = Buffer.from(combined, "utf8").subarray(0, MAX_BYTES).toString("utf8") + "\n…[truncated]";
52
+ }
53
+ return combined;
54
+ }
55
+ export function hasAgentsMd(cwd) {
56
+ const root = findProjectRoot(cwd);
57
+ return FILENAMES.some((n) => existsSync(join(root, n)));
58
+ }
59
+ /** Prompt hara runs against itself to analyze the repo and write AGENTS.md. */
60
+ export const INIT_PROMPT = "Explore this repository to understand it, then write a concise AGENTS.md at the project root.\n" +
61
+ "Use read_file, bash (e.g. `ls`, `git ls-files`, `cat`), and write_file.\n" +
62
+ "AGENTS.md should cover: what the project is (1-2 sentences), the directory structure, key commands " +
63
+ "(build / test / run / lint), and important conventions. Keep it under ~150 lines.\n" +
64
+ "Create it with write_file at path 'AGENTS.md', then reply with a one-line confirmation.";