@nanhara/hara 0.0.1 → 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 (55) hide show
  1. package/CHANGELOG.md +431 -0
  2. package/CLA.md +51 -0
  3. package/LICENSE +201 -21
  4. package/README.md +203 -7
  5. package/dist/activity.js +30 -0
  6. package/dist/agent/loop.js +184 -0
  7. package/dist/config.js +114 -0
  8. package/dist/context/agents-md.js +64 -0
  9. package/dist/context/mentions.js +90 -0
  10. package/dist/diff.js +103 -0
  11. package/dist/fs-walk.js +103 -0
  12. package/dist/fuzzy.js +62 -0
  13. package/dist/images.js +146 -0
  14. package/dist/index.js +1362 -0
  15. package/dist/mcp/client.js +54 -0
  16. package/dist/md.js +52 -0
  17. package/dist/memory/guard.js +51 -0
  18. package/dist/memory/store.js +93 -0
  19. package/dist/org/planner.js +155 -0
  20. package/dist/org/roles.js +140 -0
  21. package/dist/org/router.js +39 -0
  22. package/dist/plugins/plugins.js +124 -0
  23. package/dist/providers/anthropic.js +83 -0
  24. package/dist/providers/openai.js +125 -0
  25. package/dist/providers/qwen-oauth.js +139 -0
  26. package/dist/providers/types.js +2 -0
  27. package/dist/recall.js +76 -0
  28. package/dist/sandbox.js +78 -0
  29. package/dist/search/embed.js +42 -0
  30. package/dist/search/hybrid.js +38 -0
  31. package/dist/search/semindex.js +141 -0
  32. package/dist/session/store.js +95 -0
  33. package/dist/skills/skills.js +141 -0
  34. package/dist/statusbar.js +69 -0
  35. package/dist/tools/agent.js +26 -0
  36. package/dist/tools/apply-core.js +63 -0
  37. package/dist/tools/builtin.js +106 -0
  38. package/dist/tools/codebase.js +102 -0
  39. package/dist/tools/computer.js +236 -0
  40. package/dist/tools/edit.js +62 -0
  41. package/dist/tools/memory.js +147 -0
  42. package/dist/tools/patch.js +123 -0
  43. package/dist/tools/registry.js +18 -0
  44. package/dist/tools/search.js +176 -0
  45. package/dist/tools/skill.js +30 -0
  46. package/dist/tools/web.js +73 -0
  47. package/dist/tui/App.js +165 -0
  48. package/dist/tui/InputBox.js +208 -0
  49. package/dist/tui/run.js +10 -0
  50. package/dist/tui/theme.js +11 -0
  51. package/dist/ui.js +17 -0
  52. package/dist/undo.js +40 -0
  53. package/dist/vision.js +81 -0
  54. package/package.json +33 -7
  55. package/bin/hara.mjs +0 -25
package/LICENSE CHANGED
@@ -1,21 +1,201 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Nanhara
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.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Nanhara
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -6,16 +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
- MIT © Nanhara
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.
82
+
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
213
+
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).
216
+
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
+ }