@sean.holung/minicode 0.1.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 (54) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +241 -0
  3. package/dist/src/agent/agent.js +209 -0
  4. package/dist/src/agent/config.js +151 -0
  5. package/dist/src/agent/types.js +1 -0
  6. package/dist/src/index.js +138 -0
  7. package/dist/src/indexer/cache.js +121 -0
  8. package/dist/src/indexer/code-map.js +92 -0
  9. package/dist/src/indexer/plugin-loader.js +78 -0
  10. package/dist/src/indexer/plugins/typescript.js +327 -0
  11. package/dist/src/indexer/project-index.js +145 -0
  12. package/dist/src/indexer/types.js +1 -0
  13. package/dist/src/model/client.js +374 -0
  14. package/dist/src/prompt/system-prompt.js +91 -0
  15. package/dist/src/safety/guardrails.js +55 -0
  16. package/dist/src/session/session.js +95 -0
  17. package/dist/src/tools/edit-file.js +73 -0
  18. package/dist/src/tools/find-references.js +52 -0
  19. package/dist/src/tools/get-dependencies.js +56 -0
  20. package/dist/src/tools/helpers.js +42 -0
  21. package/dist/src/tools/list-files.js +63 -0
  22. package/dist/src/tools/read-file.js +79 -0
  23. package/dist/src/tools/read-symbol.js +96 -0
  24. package/dist/src/tools/registry.js +68 -0
  25. package/dist/src/tools/run-command.js +92 -0
  26. package/dist/src/tools/search-code-map.js +72 -0
  27. package/dist/src/tools/search.js +153 -0
  28. package/dist/src/tools/write-file.js +44 -0
  29. package/dist/src/ui/app.js +31 -0
  30. package/dist/src/ui/cli-ink.js +168 -0
  31. package/dist/src/ui/components/activity-pane.js +35 -0
  32. package/dist/src/ui/components/header-bar.js +6 -0
  33. package/dist/src/ui/components/input-composer.js +46 -0
  34. package/dist/src/ui/components/tool-timeline-item.js +37 -0
  35. package/dist/src/ui/events.js +1 -0
  36. package/dist/src/ui/state/ui-store.js +89 -0
  37. package/dist/src/ui/theme.js +23 -0
  38. package/dist/tests/agent.test.js +130 -0
  39. package/dist/tests/cache.test.js +37 -0
  40. package/dist/tests/config.test.js +37 -0
  41. package/dist/tests/dependency-graph.test.js +27 -0
  42. package/dist/tests/file-tools.test.js +73 -0
  43. package/dist/tests/find-references.test.js +30 -0
  44. package/dist/tests/get-dependencies.test.js +35 -0
  45. package/dist/tests/guardrails.test.js +18 -0
  46. package/dist/tests/indexer.test.js +201 -0
  47. package/dist/tests/model-client-openai.test.js +84 -0
  48. package/dist/tests/read-symbol.test.js +83 -0
  49. package/dist/tests/search-code-map.test.js +30 -0
  50. package/dist/tests/session.test.js +37 -0
  51. package/dist/tests/system-prompt.test.js +82 -0
  52. package/dist/tests/test-utils.js +18 -0
  53. package/dist/tests/tool-registry.test.js +41 -0
  54. package/package.json +43 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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 the 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 Sean Holung
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 ADDED
@@ -0,0 +1,241 @@
1
+ # minicode
2
+
3
+ A lightweight CLI coding agent optimized for **local models** by providing AST-based intelligent context for smaller models running on consumer hardware.
4
+
5
+ Read operations dominate token usage in typical agent sessions; minicode addresses this by optimizing for **specific languages** — indexing your project at startup with language plugins (TypeScript/JavaScript built-in) and injecting a compact **code map** (signatures only) into the system prompt, plus symbol-level tools (`read_symbol`, `find_references`, `get_dependencies`) so the model reads only what it needs instead of entire files. This keeps prompts lean enough for smaller models in the 20B range, with faster inference and better attention over the relevant code.
6
+
7
+ ## Quick Start (LM Studio)
8
+
9
+ ```bash
10
+ # 1. Start LM Studio, load a model (e.g. [GLM 4.7 Flash](https://lmstudio.ai/models/zai-org/glm-4.7-flash)), and start the local server. May need to increase context length settings for the model loaded.
11
+
12
+ # 2. Install
13
+ npm install -g @sean.holung/minicode
14
+
15
+ # 3. Configure for local (no API key needed)
16
+ mkdir -p ~/.minicode
17
+ cat > ~/.minicode/.env << 'EOF'
18
+ MODEL_PROVIDER=openai-compatible
19
+ MODEL=zai-org/glm-4.7-flash
20
+ OPENAI_BASE_URL=http://localhost:1234/v1
21
+ OPENAI_API_KEY=
22
+ MAX_STEPS=50
23
+ MAX_TOKENS=4096
24
+ MAX_CONTEXT_TOKENS=120000
25
+ WORKSPACE_ROOT=.
26
+ COMMAND_TIMEOUT_MS=30000
27
+ MAX_FILE_SIZE_BYTES=1000000
28
+ CONFIRM_DESTRUCTIVE=false
29
+ KEEP_RECENT_MESSAGES=12
30
+ LOOP_DETECTION_WINDOW=6
31
+ EOF
32
+ ```
33
+
34
+ ### How to run
35
+
36
+ `cd` to your working directory and run `minicode`.
37
+
38
+ ```
39
+ cd /path/to/your/project
40
+ minicode
41
+ ```
42
+
43
+ or you can also pass it an intial prompt from the start:
44
+
45
+ ```bash
46
+ minicode "Add error handling to src/api.ts"
47
+ ```
48
+
49
+ **Requirements:** Node.js 22+, LM Studio (or any OpenAI-compatible local server), `rg` in PATH (recommended). Set `MODEL` to match the model name in LM Studio.
50
+
51
+ ### Install from source
52
+
53
+ To build and install from the repository:
54
+
55
+ ```bash
56
+ git clone https://github.com/sean1588/minicode.git
57
+ cd minicode
58
+ npm install
59
+ npm run install:global
60
+ ```
61
+
62
+ ## Features
63
+
64
+ - Interactive multi-turn CLI session
65
+ - Agent loop with model tool-use support
66
+ - In-memory session history with trimming
67
+ - Safety guardrails for file paths and shell commands
68
+ - Built-in tools:
69
+ - `read_file`
70
+ - `write_file`
71
+ - `edit_file`
72
+ - `search` (ripgrep, grep fallback)
73
+ - `list_files`
74
+ - `run_command`
75
+ - **Context optimization:** Code map in system prompt, `read_symbol`, `find_references`, `get_dependencies`
76
+ - **Plugin system:** Extensible language support (TypeScript built-in)
77
+
78
+ ## Context Optimization
79
+
80
+ For a deep technical walkthrough of AST parsing, dependency graph construction, code-map ranking, and tool-call orchestration, see [docs/AST_DEP_GRAPH_TOOLING.md](docs/AST_DEP_GRAPH_TOOLING.md).
81
+
82
+ For agent-loop internals (session lifecycle, tool execution, streaming, loop detection, and model client behavior), see [docs/AGENT_RUNTIME.md](docs/AGENT_RUNTIME.md).
83
+
84
+ minicode reduces token usage by indexing your project and providing targeted tools:
85
+
86
+ - **Code map** — A compact project skeleton (signatures only) is injected into the system prompt so the model can orient itself without reading full files.
87
+ - `**read_symbol`** — Read a specific function or class by name, with referenced types.
88
+ - `**find_references**` — Find all symbols that reference a given symbol.
89
+ - `**get_dependencies**` — Get the dependency cone of a symbol.
90
+
91
+ The index is cached in `~/.minicode/cache/<workspace-hash>/` for faster startup on subsequent runs. Caches are global and keyed by workspace path, so nothing is stored inside your project directories.
92
+
93
+ ### Indexing and dependency graph
94
+
95
+ Indexing uses the **TypeScript compiler API** (`ts.createSourceFile`) to parse each file into an AST. It does not run `tsc` — no type-checking, no project config, just lightweight in-memory parsing.
96
+
97
+ From the AST, minicode builds a **dependency graph** of symbol relationships:
98
+
99
+ | Edge kind | How it's inferred from the AST |
100
+ | ----------- | ------------------------------------------------------- |
101
+ | `calls` | `foo()` or `new Bar()` → function/class being invoked |
102
+ | `references`| Type annotations like `: ModelResponse` |
103
+ | `extends` | `class X extends Y` |
104
+ | `implements`| `class X implements Y` |
105
+
106
+ The graph powers:
107
+
108
+ - **Code map ranking** — When the map is truncated, symbols with higher reference counts and entry-point files appear first.
109
+ - **`get_dependencies`** — Returns the transitive closure of what a symbol calls or references.
110
+ - **`find_references`** — Returns symbols that call or reference a given symbol.
111
+ - **`read_symbol`** — Shows "Used by", "Calls", and "Referenced Types" derived from the graph.
112
+
113
+ ## Plugin System
114
+
115
+ ### Supported Languages
116
+
117
+
118
+ | Language | Extensions | Plugin |
119
+ | --------------------- | ---------------------------- | -------- |
120
+ | TypeScript/JavaScript | `.ts`, `.tsx`, `.js`, `.jsx` | Built-in |
121
+
122
+
123
+ ### Installing Plugins
124
+
125
+ **npm:** Add a package matching `minicode-plugin-`* to your dependencies:
126
+
127
+ ```bash
128
+ npm install minicode-plugin-go # example
129
+ ```
130
+
131
+ **Local:** Place a `.js` file in `<workspace>/.minicode/plugins/`. It must export a `LanguagePlugin` (default or named `plugin`).
132
+
133
+ ### Creating Plugins
134
+
135
+ See [docs/PLUGIN_SPEC.md](docs/PLUGIN_SPEC.md) for the full specification. Quick start: copy `templates/plugin-template/` and implement `indexFile()`.
136
+
137
+ ## Configuration
138
+
139
+ Configuration can come from (later sources override earlier):
140
+
141
+ 1. `**~/.minicode/.env`** — User-level defaults (API keys, model, etc.)
142
+ 2. `**~/.minicode/agent.config.json**` — User-level JSON config
143
+ 3. **Project `.env`** and `**agent.config.json**` in workspace root
144
+ 4. Environment variables (highest precedence)
145
+
146
+ Nothing is written inside your workspace; config and cache live under `~/.minicode/`.
147
+
148
+ ### Environment variables
149
+
150
+
151
+ | Variable | Required | Default | Notes |
152
+ | ----------------------- | --------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
153
+ | `MODEL_PROVIDER` | No | `openai-compatible` | `anthropic` or `openai-compatible` (aliases: `openai`, `lmstudio`, `lm-studio`) |
154
+ | `MODEL` | No | `zai-org/glm-4.7-flash` | Model name for selected provider |
155
+ | `ANTHROPIC_API_KEY` | Yes (Anthropic) | none | Required when `MODEL_PROVIDER=anthropic` |
156
+ | `OPENAI_BASE_URL` | No | `http://localhost:1234/v1` | Base URL for OpenAI-compatible API (LM Studio, etc.) |
157
+ | `OPENAI_API_KEY` | No | none | Optional for local servers; required if your endpoint enforces auth |
158
+ | `MAX_STEPS` | No | `50` | Max agent loop iterations per user turn |
159
+ | `MAX_TOKENS` | No | `4096` | Max model output tokens per model call |
160
+ | `MAX_CONTEXT_TOKENS` | No | `120000` | Approximate session history trimming target. For small models (e.g. 8k context), set lower (e.g. `6000`) to leave room for responses. |
161
+ | `MAX_TOOL_OUTPUT_CHARS` | No | `15000` | Max chars per tool result before truncation. Set to `0` to disable. |
162
+ | `WORKSPACE_ROOT` | No | current working directory | Root directory tools are allowed to access |
163
+ | `COMMAND_TIMEOUT_MS` | No | `30000` | Timeout for shell/search commands |
164
+ | `MAX_FILE_SIZE_BYTES` | No | `1000000` | Read limit for `read_file` |
165
+ | `CONFIRM_DESTRUCTIVE` | No | `false` | If `true`, blocks destructive shell commands unless confirmed |
166
+ | `KEEP_RECENT_MESSAGES` | No | `12` | Minimum number of latest messages kept during trimming |
167
+ | `LOOP_DETECTION_WINDOW` | No | `6` | Window for repeated tool-call loop detection |
168
+
169
+
170
+ ### `agent.config.json`
171
+
172
+ Create `agent.config.json` in `~/.minicode/` for user-level defaults, or in the project root for workspace-specific overrides:
173
+
174
+ ```json
175
+ {
176
+ "modelProvider": "openai-compatible",
177
+ "model": "zai-org/glm-4.7-flash",
178
+ "maxSteps": 50,
179
+ "maxTokens": 4096,
180
+ "maxContextTokens": 120000,
181
+ "workspaceRoot": ".",
182
+ "commandTimeout": 30000,
183
+ "commandDenylist": [],
184
+ "confirmDestructive": false,
185
+ "maxFileSizeBytes": 1000000,
186
+ "keepRecentMessages": 12,
187
+ "loopDetectionWindow": 6,
188
+ "openAiBaseUrl": "http://localhost:1234/v1",
189
+ "openAiApiKey": ""
190
+ }
191
+ ```
192
+
193
+ Field mapping:
194
+
195
+ - `modelProvider` ↔ `MODEL_PROVIDER`
196
+ - `model` ↔ `MODEL`
197
+ - `maxSteps` ↔ `MAX_STEPS`
198
+ - `workspaceRoot` ↔ `WORKSPACE_ROOT`
199
+ - `maxTokens` ↔ `MAX_TOKENS`
200
+ - `maxContextTokens` ↔ `MAX_CONTEXT_TOKENS`
201
+ - `commandTimeout` ↔ `COMMAND_TIMEOUT_MS`
202
+ - `commandDenylist` ↔ no env equivalent (config-only)
203
+ - `confirmDestructive` ↔ `CONFIRM_DESTRUCTIVE`
204
+ - `maxFileSizeBytes` ↔ `MAX_FILE_SIZE_BYTES`
205
+ - `keepRecentMessages` ↔ `KEEP_RECENT_MESSAGES`
206
+ - `loopDetectionWindow` ↔ `LOOP_DETECTION_WINDOW`
207
+ - `openAiBaseUrl` ↔ `OPENAI_BASE_URL`
208
+ - `openAiApiKey` ↔ `OPENAI_API_KEY`
209
+
210
+ ## Usage
211
+
212
+ Interactive mode:
213
+
214
+ ```bash
215
+ npm run dev
216
+ ```
217
+
218
+ With an initial task (runs the task as the first message, then stays interactive for follow-up):
219
+
220
+ ```bash
221
+ npm run dev -- "Add error handling to src/api.ts and run tests"
222
+ ```
223
+
224
+ Verbose mode (log prompts, model responses, and tool invocations to stderr):
225
+
226
+ ```bash
227
+ npm run dev -- --verbose "Fix the bug"
228
+ npm run dev -- -v
229
+ ```
230
+
231
+ ## Scripts
232
+
233
+ - `npm run dev` - start the CLI in TypeScript mode
234
+ - `npm run dev:ink` - start with Ink UI (same as `dev` when in a TTY; use to override `CLI_UI_MODE=legacy`)
235
+ - `npm run build` - compile TypeScript to `dist/`
236
+ - `npm start` - run compiled CLI
237
+ - `npm run lint` - run ESLint on TypeScript source and tests
238
+ - `npm test` - run Node test suite
239
+
240
+
241
+
@@ -0,0 +1,209 @@
1
+ import { buildSystemPrompt } from "../prompt/system-prompt.js";
2
+ import { ensureStepWithinLimit } from "../safety/guardrails.js";
3
+ import { Session } from "../session/session.js";
4
+ function stableSerialize(value) {
5
+ if (Array.isArray(value)) {
6
+ return `[${value.map((item) => stableSerialize(item)).join(",")}]`;
7
+ }
8
+ if (value && typeof value === "object") {
9
+ const entries = Object.entries(value)
10
+ .sort(([a], [b]) => a.localeCompare(b))
11
+ .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableSerialize(entryValue)}`);
12
+ return `{${entries.join(",")}}`;
13
+ }
14
+ return JSON.stringify(value);
15
+ }
16
+ function signatureForToolCall(toolCall) {
17
+ return `${toolCall.name}:${stableSerialize(toolCall.input)}`;
18
+ }
19
+ function formatToolCallForProgress(toolCall, maxArgsLen = 100) {
20
+ const argsStr = JSON.stringify(toolCall.input);
21
+ const truncated = argsStr.length > maxArgsLen
22
+ ? argsStr.slice(0, maxArgsLen) + "..."
23
+ : argsStr;
24
+ return `${toolCall.name}(${truncated})`;
25
+ }
26
+ const VERBOSE_SEP = "─".repeat(60);
27
+ const PROGRESS_THINKING_MAX = 200;
28
+ export class CodingAgent {
29
+ session;
30
+ config;
31
+ modelClient;
32
+ toolRegistry;
33
+ projectIndex;
34
+ verbose;
35
+ onProgress;
36
+ onUiUpdate;
37
+ constructor(params) {
38
+ this.config = params.config;
39
+ this.modelClient = params.modelClient;
40
+ this.toolRegistry = params.toolRegistry;
41
+ this.session = params.session ?? new Session();
42
+ this.projectIndex = params.projectIndex;
43
+ this.verbose = params.verbose ?? false;
44
+ this.onProgress = params.onProgress;
45
+ this.onUiUpdate = params.onUiUpdate;
46
+ }
47
+ getSession() {
48
+ return this.session;
49
+ }
50
+ async runTurn(userMessage, options) {
51
+ this.session.addMessage({
52
+ role: "user",
53
+ content: userMessage,
54
+ });
55
+ const toolSchemas = this.toolRegistry.getToolSchemas();
56
+ const codeMapResult = this.projectIndex?.getCodeMap();
57
+ const systemPrompt = buildSystemPrompt(this.config, toolSchemas, codeMapResult);
58
+ const recentToolCallFingerprints = [];
59
+ let totalInputTokens = 0;
60
+ let totalOutputTokens = 0;
61
+ for (let step = 0; step < this.config.maxSteps; step += 1) {
62
+ ensureStepWithinLimit(step, this.config.maxSteps);
63
+ if (this.onUiUpdate) {
64
+ this.onUiUpdate({ type: "step", step });
65
+ }
66
+ this.session.trim(this.config.maxContextTokens, this.config.keepRecentMessages);
67
+ const messages = this.session.getMessages();
68
+ if (this.verbose) {
69
+ console.error(`\n${VERBOSE_SEP}`);
70
+ console.error(`[verbose] Request (step ${step})`);
71
+ console.error(`${VERBOSE_SEP}`);
72
+ console.error("\n[System Prompt]\n", systemPrompt);
73
+ console.error("\n[Messages]\n", JSON.stringify(messages, null, 2));
74
+ console.error(VERBOSE_SEP);
75
+ }
76
+ const response = await this.modelClient.chat({
77
+ model: this.config.model,
78
+ system: systemPrompt,
79
+ messages,
80
+ tools: toolSchemas,
81
+ maxTokens: this.config.maxTokens,
82
+ ...(this.onUiUpdate
83
+ ? {
84
+ onStream: (chunk) => {
85
+ this.onUiUpdate({ type: "streaming_chunk", content: chunk });
86
+ },
87
+ }
88
+ : {}),
89
+ ...(options?.signal && { signal: options.signal }),
90
+ });
91
+ totalInputTokens += response.usage.inputTokens;
92
+ totalOutputTokens += response.usage.outputTokens;
93
+ if (this.verbose) {
94
+ console.error(`\n${VERBOSE_SEP}`);
95
+ console.error("[verbose] Response");
96
+ console.error(`${VERBOSE_SEP}`);
97
+ console.error("Text:", response.text);
98
+ console.error("Tool calls:", response.toolCalls.length);
99
+ if (response.toolCalls.length > 0) {
100
+ console.error("Tools:", response.toolCalls.map((t) => `${t.name}(${JSON.stringify(t.input)})`).join(", "));
101
+ }
102
+ console.error("Usage:", response.usage);
103
+ console.error(VERBOSE_SEP);
104
+ }
105
+ if (response.toolCalls.length === 0) {
106
+ const finalText = response.text.length > 0
107
+ ? response.text
108
+ : "The model returned no response or tool calls. If you asked for code changes or other work, try rephrasing your request or using a model with stronger tool-use support.";
109
+ this.session.addMessage({
110
+ role: "assistant",
111
+ content: finalText,
112
+ });
113
+ const streamed = this.config.modelProvider === "openai-compatible" && !!this.onUiUpdate;
114
+ return {
115
+ text: finalText,
116
+ usage: { inputTokens: totalInputTokens, outputTokens: totalOutputTokens },
117
+ streamed,
118
+ };
119
+ }
120
+ if (response.text.length > 0) {
121
+ const truncated = response.text.length > PROGRESS_THINKING_MAX
122
+ ? response.text.slice(0, PROGRESS_THINKING_MAX) + "..."
123
+ : response.text;
124
+ if (this.onProgress) {
125
+ this.onProgress(`thinking: ${truncated}`);
126
+ }
127
+ if (this.onUiUpdate) {
128
+ this.onUiUpdate({ type: "thinking", content: truncated });
129
+ }
130
+ }
131
+ this.session.addMessage({
132
+ role: "assistant",
133
+ content: response.text,
134
+ toolCalls: response.toolCalls,
135
+ });
136
+ for (const toolCall of response.toolCalls) {
137
+ const fingerprint = signatureForToolCall(toolCall);
138
+ recentToolCallFingerprints.push(fingerprint);
139
+ if (recentToolCallFingerprints.length >
140
+ this.config.loopDetectionWindow) {
141
+ recentToolCallFingerprints.shift();
142
+ }
143
+ const repeatedCalls = recentToolCallFingerprints.filter((value) => value === fingerprint).length;
144
+ if (repeatedCalls >= 3) {
145
+ const loopMessage = "Stopped due to repeated identical tool calls. Please refine the prompt or provide additional constraints.";
146
+ this.session.addMessage({
147
+ role: "assistant",
148
+ content: loopMessage,
149
+ });
150
+ return {
151
+ text: loopMessage,
152
+ usage: { inputTokens: totalInputTokens, outputTokens: totalOutputTokens },
153
+ streamed: false,
154
+ };
155
+ }
156
+ if (this.onProgress) {
157
+ this.onProgress(`tool_call: ${formatToolCallForProgress(toolCall)}`);
158
+ }
159
+ if (this.onUiUpdate) {
160
+ this.onUiUpdate({
161
+ type: "tool_call_start",
162
+ name: toolCall.name,
163
+ input: toolCall.input,
164
+ });
165
+ }
166
+ if (this.verbose) {
167
+ console.error(`\n${VERBOSE_SEP}`);
168
+ console.error(`[verbose] Tool: ${toolCall.name}`);
169
+ console.error("Arguments:", JSON.stringify(toolCall.input, null, 2));
170
+ }
171
+ const toolStartMs = Date.now();
172
+ let toolResult = await this.toolRegistry.execute(toolCall.name, toolCall.input);
173
+ const maxChars = this.config.maxToolOutputChars;
174
+ if (maxChars > 0 && toolResult.length > maxChars) {
175
+ toolResult = `${toolResult.slice(0, maxChars)}\n\n[... truncated, ${toolResult.length - maxChars} more chars ...]`;
176
+ }
177
+ if (this.onUiUpdate) {
178
+ this.onUiUpdate({
179
+ type: "tool_call_end",
180
+ name: toolCall.name,
181
+ input: toolCall.input,
182
+ result: toolResult,
183
+ elapsedMs: Date.now() - toolStartMs,
184
+ });
185
+ }
186
+ if (this.verbose) {
187
+ console.error("Output:", toolResult);
188
+ console.error(VERBOSE_SEP);
189
+ }
190
+ this.session.addMessage({
191
+ role: "tool",
192
+ toolCallId: toolCall.id,
193
+ toolName: toolCall.name,
194
+ content: toolResult,
195
+ });
196
+ }
197
+ }
198
+ const stepLimitMessage = "Reached the maximum number of steps for this turn. I stopped to avoid an infinite loop.";
199
+ this.session.addMessage({
200
+ role: "assistant",
201
+ content: stepLimitMessage,
202
+ });
203
+ return {
204
+ text: stepLimitMessage,
205
+ usage: { inputTokens: totalInputTokens, outputTokens: totalOutputTokens },
206
+ streamed: false,
207
+ };
208
+ }
209
+ }