heartcode 0.1.41 → 0.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  What changed in each version of HeartCode, newest first.
4
4
 
5
+ ## 0.1.42 (2026-11-03)
6
+
7
+ - **Your "no, do this instead" reaches the model as you**: what you type when you decline a command,
8
+ an edit or a call goes to the model as your own message, not inside the tool's result (where small
9
+ models read it as the tool failing and tried again).
10
+ - **The conversation's size counted honestly**: tokens estimated the way tokenizers split text, so
11
+ code, CSS, JSON and SVG count for what they are (a flat estimate was up to 2× low on them: a request
12
+ thought to fit was refused, and compacting never started); a ratio learned on prose never makes it
13
+ smaller than characters ÷ 4, and what's new since the server's last count is never discounted.
14
+ - **The provider's prompt cache kept**: a file read again no longer rewrites its older copy in the
15
+ middle of the conversation at once (every such change makes the provider process everything after
16
+ it again: minutes on a local model, full price on a paid one); older copies go together with the
17
+ old results, or when it's nearly full.
18
+ - **Checks what uses a change**: before saying done, the model reads its whole change and updates
19
+ what uses it (the callers of a function, what reads a renamed value). In our test a 14B model
20
+ updated both callers 2 of 2 times, against 0 of 2 before. The new `changes` tool shows the model
21
+ its own diff for the message (or the conversation), with or without git.
22
+ - **Tool messages that can't be misread**: search tells a path that doesn't exist, a pattern no file
23
+ fits and an invalid regular expression apart from "no matches" (with how many files it searched),
24
+ and takes a pattern as its path (`src/*.css`); shortened output says it's shortened to fit, not an
25
+ error.
26
+ - **Findings saved before compacting**: the model working on the task writes down what it has found
27
+ just before the conversation is summarized, and the summary starts with it, so it doesn't read the
28
+ same files again after every compaction.
29
+ - **`--temp` keeps nothing**: besides `~/.heart`, the project's `.heartcode/` (research pages, notes)
30
+ is untouched (read from a copy), logs go with the throwaway folder, and skills or MCP servers saved
31
+ in a `--temp` run don't reach the project.
32
+ - **The update check at every start**, not once a day: a new version shows on the next launch.
33
+ - **Thanks** in the README to Reika, OpenCode, Cline, OpenClaw and Pi.
34
+
5
35
  ## 0.1.41 (2026-11-03)
6
36
 
7
37
  - **Model scores on Your models**: Coding, Web apps and Vision show each model's LMArena score with
package/README.md CHANGED
@@ -56,7 +56,7 @@ tried did what I needed:
56
56
  default): requests, tools & commands, model choices, the agent's decisions, errors, the
57
57
  conversation, debug. Read them on the settings page, searched and live.
58
58
  - **Takes skills, MCP servers and hooks** in Claude Code's formats; `/import` brings yours over.
59
- - **Tells you when a newer version is out** (a check with npm at most once a day, in the status bar):
59
+ - **Tells you when a newer version is out** (a check with npm each time it starts, in the status bar):
60
60
  `/update` shows what changed and installs it the way you installed HeartCode. Switch it off in
61
61
  `/settings` → General.
62
62
  - **Best fit by public rankings**: with "Pick" set to "the best for each task", each message's
@@ -189,6 +189,16 @@ ones that change it (`/compact`, `/rewind`, `/resume`…) wait until it's done.
189
189
  commands show (`/help`, `/context`, `/diff`…) open in a dialog over the conversation; `Esc`
190
190
  closes it.
191
191
 
192
+ ## Thanks
193
+
194
+ A lot of what HeartCode handles, I learned from other coding agents and the problems they ran into
195
+ first. Thank you to [Reika](https://github.com/alexwkleung/reika) (its measured findings on small
196
+ models: sending a "no, do this instead" as your own message, counting code's tokens honestly,
197
+ keeping the provider's prompt cache, checking what uses a changed function, saving what the model
198
+ found before compacting), [OpenCode](https://github.com/anomalyco/opencode),
199
+ [Cline](https://github.com/cline/cline), [OpenClaw](https://github.com/openclaw/openclaw) and
200
+ [Pi](https://github.com/earendil-works/pi), for the many use cases like these they showed me.
201
+
192
202
  ## License
193
203
 
194
204
  [MIT](LICENSE)
package/SKILL.md CHANGED
@@ -123,7 +123,9 @@ goes to stderr. Logs never go to stdout.
123
123
 
124
124
  ## Continue the same conversation
125
125
 
126
- Pass the `session_id` from the last result:
126
+ Every run is saved as a session in `~/.heart/sessions/` (and logged, for the kinds of logs the user
127
+ switched on), as when the user works in HeartCode; `--temp` keeps nothing. Pass the `session_id`
128
+ from the last result:
127
129
 
128
130
  ```sh
129
131
  heart -p --output-format json --resume 20261027-… "now add a test for the empty case"
@@ -146,10 +148,10 @@ can't switch the model you chose.
146
148
  | Everything (edits and commands) | `--permission-mode all` (the default unless the user set another) |
147
149
  | Changes kept apart from the user's files | `--worktree=<name>` (in a git repo): it works in `.heartcode/worktrees/<name>` on the branch `heartcode/<name>`; kept if anything changed (merge it from there), removed if nothing did |
148
150
  | A cap on how long it works | `--max-turns 30` (model steps), `--max-retries 3` (a failing provider) |
149
- | Nothing written to the user's `~/.heart` (sessions, logs, settings) | `--temp` (a throwaway copy, shared by the `--temp` runs going on at once) |
151
+ | Nothing kept: no session, logs, settings or notes in `~/.heart`, nothing in the project's `.heartcode/` | `--temp` (a throwaway copy, shared by the `--temp` runs going on at once, deleted after the last; the project's notes and research are read, and what the run adds goes with the copy) |
150
152
 
151
153
  Tool names: HeartCode's own (`read_file`, `edit_file`, `write_file`, `run_command`, `search`,
152
- `list_files`, `web_fetch`, `web_search`…) or Claude Code's (`Read`, `Edit`, `Write`, `Bash`,
154
+ `list_files`, `changes`, `web_fetch`, `web_search`…) or Claude Code's (`Read`, `Edit`, `Write`, `Bash`,
153
155
  `Grep`, `Glob`, `WebFetch`, `WebSearch`). `--disallowedTools Bash` takes one away. MCP servers'
154
156
  tools are named as in Claude Code: `mcp__<server>__<tool>`; `mcp__<server>` means all of one
155
157
  server's tools, `mcp` all of them. (The model itself reaches them through one `mcp` tool that lists
@@ -178,6 +180,10 @@ the next capable model until one does the job. A helper works until its job is d
178
180
  limit; `--max-turns` applies to it too). Their tokens are in `usage`, and each model's in
179
181
  `modelUsage`.
180
182
 
183
+ A long run that fills the model's context window is compacted: the model first writes down what it
184
+ has found, then the conversation so far is replaced by a summary that starts with those notes. That
185
+ is two extra requests, counted in `usage`, and not in the stream.
186
+
181
187
  ## Setting up a model
182
188
 
183
189
  Ask the user which provider and model to use, and for the key. Never invent one. Then:
@@ -191,7 +197,8 @@ HEART_API_KEY=… heart -u https://api.groq.com/openai/v1 -m openai/gpt-oss-120b
191
197
  ```
192
198
 
193
199
  A model server on this machine (Ollama on :11434, LM Studio on :1234, llama.cpp on :8080) is
194
- found on its own. The user can also set everything up in a browser: `heart settings`, where
200
+ found on its own. The user can also set everything up in a browser: `heart settings` (its link has
201
+ the machine's network address, so it opens from another device too, for HeartCode on a server), where
195
202
  **Test** (or **Test all**) under *Your models* sends a model a short message to show it really
196
203
  answers. A run that fails with a wrong key or an unknown model: ask the user to test it there.
197
204
 
package/bin/heart.js CHANGED
@@ -52,10 +52,11 @@ if (temp) {
52
52
  fs.rmSync(dir, { recursive: true, force: true }) // left by a crashed run: from your settings again
53
53
  fs.mkdirSync(runs, { recursive: true })
54
54
  // your providers and keys; what HeartCode learned about each model and prices (or it tests them again)
55
- for (const f of ['config.json', 'models', 'prices.json']) if (fs.existsSync(path.join(realHome, f))) fs.cpSync(path.join(realHome, f), path.join(dir, f), { recursive: true })
55
+ for (const f of ['config.json', 'models', 'prices.json', 'memory']) if (fs.existsSync(path.join(realHome, f))) fs.cpSync(path.join(realHome, f), path.join(dir, f), { recursive: true })
56
56
  }
57
57
  fs.writeFileSync(path.join(runs, String(process.pid)), '')
58
58
  process.env.HEART_HOME = dir
59
+ process.env.HEART_TEMP = '1' // the project's .heartcode folders too: copies in here (config.js projectDir)
59
60
  process.on('exit', () => {
60
61
  fs.rmSync(path.join(runs, String(process.pid)), { force: true })
61
62
  if (!others().length) fs.rmSync(dir, { recursive: true, force: true })
@@ -77,7 +78,7 @@ if (first && !first.startsWith('-') && !SUBCOMMANDS.includes(first)) {
77
78
 
78
79
  // where the logs go, and this run's name for its folders (src/log.js: each kind of log is switched on
79
80
  // by itself in config.json's "logs", also while HeartCode runs)
80
- const logs = temp ? path.join(os.tmpdir(), 'heart-temp-logs') : path.join(realHome, 'logs')
81
+ const logs = temp ? path.join(process.env.HEART_HOME, 'logs') : path.join(realHome, 'logs') // --temp: deleted with its folder
81
82
  process.env.HEART_LOGS ??= logs
82
83
  let runStamp = stamp
83
84
  for (let n = 2; ['runs', 'requests'].some((d) => fs.existsSync(path.join(logs, d, runStamp))); n++) runStamp = `${stamp}-${n}` // two runs in the same second
package/bin/heartcode.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import path from 'node:path'
3
3
  import { parseArgs } from 'node:util'
4
4
  import { Client } from '../src/client.js'
5
- import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION } from '../src/config.js'
5
+ import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION } from '../src/config.js'
6
6
  import { loadProfile, strategy, describe, profilePath, profileFrom } from '../src/probe.js'
7
7
  import { learnFromUsage, LIMIT_MS } from '../src/context.js'
8
8
  import { Session, transcript, contextReport } from '../src/agent.js'
@@ -59,9 +59,10 @@ ${c.bold('options')}
59
59
  --ask ask before every edit and command, this run
60
60
  --hide-thinking collapse the model's thinking to one line
61
61
  -C, --cwd <dir> project folder (default: current folder)
62
- --temp a throwaway settings folder (your providers, model tests and prices
63
- copied in), shared by the --temp runs going on at once and deleted
64
- after the last; ~/.heart isn't touched
62
+ --temp keep nothing: a throwaway settings folder (your providers, model info,
63
+ prices and notes copied in), shared by the --temp runs going on at once
64
+ and deleted after the last, with its logs; ~/.heart and the project's
65
+ .heartcode/ aren't touched (their notes and research are read from a copy)
65
66
  --context <n> context window size in tokens
66
67
  --save keep the given -u/-m/--api-key/... in ${CONFIG_FILE}
67
68
  -w, --worktree work in a new git worktree and branch (--worktree=name to name it,
@@ -238,6 +239,7 @@ class App {
238
239
  }
239
240
 
240
241
  saveProjectModels() {
242
+ if (TEMP) return // --temp keeps nothing: the choice lasts for this run only
241
243
  const file = path.join(this.root, '.heartcode', 'models.json')
242
244
  if (this.cfg.session?.length) writeJson(file, { session: this.cfg.session.map((t) => ({ provider: t.provider, model: t.model })) })
243
245
  else fs.rmSync(file, { force: true }) // auto: forget the folder's choice
@@ -1443,7 +1445,7 @@ async function slash(app, line, working = false) {
1443
1445
  return ui.showText('Commands and keys', app.help())
1444
1446
  case 'update': {
1445
1447
  ui.spinner('asking npm for the newest HeartCode')
1446
- const u = await checkUpdate({ force: true })
1448
+ const u = await checkUpdate()
1447
1449
  ui.stopSpin()
1448
1450
  if (!u) return ui.warn("couldn't reach npm to check for a newer HeartCode")
1449
1451
  app.update = u
@@ -1827,7 +1829,7 @@ async function repl(app, f = {}) {
1827
1829
  // models this folder picked earlier (/select_model): said, with the way back to your whole list
1828
1830
  if (app.folderModels && cfg.session?.length) ui.print(`${c.muted('this folder uses')} ${c.cyan(cfg.session.map((t) => t.model).join(', '))} ${c.faint(`(picked earlier) · ${c.cyan('/select_model auto')} for your whole list again`)}`)
1829
1831
  app.tabs?.onChange?.() // the conversation it opened with
1830
- // a newer HeartCode: asked in the background (once a day at most), said once and kept in the status bar
1832
+ // a newer HeartCode: asked of npm in the background at every start, said once and kept in the status bar
1831
1833
  if (cfg.updateCheck !== false)
1832
1834
  checkUpdate()
1833
1835
  .then((u) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.41",
3
+ "version": "0.1.42",
4
4
  "description": "A coding CLI for any local or OpenAI-compatible model, including small models without tool calling.",
5
5
  "keywords": [
6
6
  "ai",
package/prompts/agent.md CHANGED
@@ -50,6 +50,7 @@ A tool or package the plan needs that isn't installed: find the right way for th
50
50
 
51
51
  ## Prove it works, then stop
52
52
  Never say done, fixed or working without having just run what proves it and read its output. "It should work" and "no syntax error" are not proof. Check it the way the person who asked will use it: run it, use it with real input and an edge case, look at what it shows, read its errors; stop what you started. Tests there: run them.
53
+ Before you say done, read your whole change (the changes tool) and find what uses what you changed: the callers of a function you changed, everything that reads a name, value or format you renamed or reshaped. Update them too.
53
54
  A real bug: fix the cause, run it again, until it works end to end. The proof passes: stop — no polish, cleanup or extra tests after. A review point (HeartCode's, a reviewer's, a helper's): check it against the code first; wrong: say why and don't do it.
54
55
  When you made something that runs, end with how to run it: the exact command(s) from the project folder and the URL to open.
55
56
 
@@ -81,12 +82,12 @@ How to use {{server}}, in its own words (said once):
81
82
  ## output-cut
82
83
 
83
84
  <!-- After the start of a tool result too long for the conversation. {{shown}}, {{total}}: characters; {{file}}: where all of it is (empty if it couldn't be saved). -->
84
- [Output cut: the first {{shown}} of {{total}} characters are above.{{#if file}} All of it is in {{file}}: read the rest with read_file (start_line, end_line) or find what you need in it with search (path: that file).{{else}} Ask for less of it at a time.{{/if}}]
85
+ [Shortened to fit the conversation, not an error: the tool ran normally and its result is complete; only the first {{shown}} of {{total}} characters are shown above.{{#if file}} All of it is in {{file}}: read the rest with read_file (start_line, end_line) or find what you need in it with search (path: that file).{{else}} Ask for less of it at a time.{{/if}}]
85
86
 
86
87
  ## output-old
87
88
 
88
89
  <!-- Replaces an older tool result (all but the newest few long ones) once there are many. {{call}}: what the call was ("run_command npm test"); {{total}}: its length; {{file}}: where all of it is (may be empty). The first lines follow it. -->
89
- [older output of {{call}}, {{total}} characters{{#if file}} — all of it is in {{file}}: read_file it (start_line/end_line) or search in it if you need it again{{/if}}. Its first lines:]
90
+ [older output of {{call}}, {{total}} characters, shortened to save room (it ran normally then){{#if file}} — all of it is in {{file}}: read_file it (start_line/end_line) or search in it if you need it again{{/if}}. Its first lines:]
90
91
 
91
92
  ## empty-reply
92
93
 
@@ -132,7 +133,11 @@ Read a file; returns numbered lines. For part of a big file, give start_line and
132
133
 
133
134
  ## tool-search
134
135
 
135
- Find text or a regex in the project's files (or only in `path`). Returns file:line: text.
136
+ Find text or a regex in the project's files (or only in `path`: a file, a folder, or a pattern like `src/*.css`). Returns file:line: text.
137
+
138
+ ## tool-changes
139
+
140
+ What you changed in files for this message, as a diff: each file from before your first change to now (with `all`: everything changed in this conversation; with `path`: that file only). Read it before you say done, to see your whole change at once.
136
141
 
137
142
  ## tool-list_files
138
143
 
@@ -10,6 +10,12 @@ its section into ~/.heart/prompts/compact.md (every project) or .heartcode/promp
10
10
  <!-- System prompt of the summary request. -->
11
11
  You write summaries of conversations between a user and a coding assistant. You don't continue the work and you can't use tools: you only write the summary, as plain text.
12
12
 
13
+ ## findings
14
+
15
+ <!-- Asked of the model doing the task, as the next message of its own conversation, just before the
16
+ conversation is compacted. Its reply leads the summary that replaces the conversation. -->
17
+ The earlier part of this conversation is about to be replaced by a summary, and your reasoning so far will be gone. Write down now what you'd need to carry on without reading everything again: what you found and concluded (causes, decisions, what works and what doesn't), where things are (files, lines, names), what's done, and what's next. Plain notes, only what matters. Don't call tools.
18
+
13
19
  ## summarize-again
14
20
 
15
21
  <!-- Added when the first reply wasn't a summary (empty, or a tool call). -->
@@ -37,9 +43,16 @@ Write it as compact notes. No preamble, no tool calls.
37
43
 
38
44
  ## summary
39
45
 
40
- <!-- Replaces the compacted part of the conversation. {{summary}}: the summary.
46
+ <!-- Replaces the compacted part of the conversation. {{summary}}: the summary; {{findings}}: the
47
+ model's own notes of what it had found, written just before (may be empty).
41
48
  {{requests}}: the user's messages so far, word for word ("- …" lines; may be empty). -->
42
- This conversation was compacted to save space. Summary of everything before this point:
49
+ This conversation was compacted to save space.{{#if findings}}
50
+
51
+ Your own notes, written just before, of what you had found:
52
+
53
+ {{findings}}{{/if}}
54
+
55
+ Summary of everything before this point:
43
56
 
44
57
  {{summary}}{{#if requests}}
45
58
 
package/src/acp.js CHANGED
@@ -14,7 +14,7 @@ import { HeadlessUI } from './headless.js'
14
14
  import { PERMISSIONS } from './ui.js'
15
15
  import { loadChat } from './sessions.js'
16
16
 
17
- const KIND = { read_file: 'read', list_files: 'search', search: 'search', edit_file: 'edit', write_file: 'edit', run_command: 'execute', web_fetch: 'fetch', web_search: 'fetch', todo: 'think', agent: 'think' }
17
+ const KIND = { read_file: 'read', changes: 'read', list_files: 'search', search: 'search', edit_file: 'edit', write_file: 'edit', run_command: 'execute', web_fetch: 'fetch', web_search: 'fetch', todo: 'think', agent: 'think' }
18
18
  const plain = (s) => String(s ?? '').replace(/\x1b\[[0-9;]*m/g, '')
19
19
 
20
20
  // The screen for one session: everything goes to the editor as session/update.
package/src/agent.js CHANGED
@@ -114,6 +114,7 @@ export class Session {
114
114
  const cut = () => (conversation.length > room ? `[… the earliest part is cut]\n${conversation.slice(-room)}` : conversation)
115
115
  const before = native ? size(body) : est(conversation)
116
116
  ui.spinner(why ? `${why}: compacting the conversation` : 'compacting the conversation')
117
+ const findings = native ? await this.findings(signal) : ''
117
118
  // A model shown its own work tends to carry on with it (calling tools, or writing tool calls
118
119
  // as text) instead of summarizing: so it's told what it is, and a reply that isn't a summary
119
120
  // is asked for again once; then the compaction fails (the conversation is trimmed instead).
@@ -131,7 +132,7 @@ export class Session {
131
132
  ;(chat.snapshots ??= [])[epoch] = { messages: chat.messages, history: [...chat.history] }
132
133
  chat.sentNotes = [] // the summary replaces the messages the notes came with
133
134
  chat.epoch = epoch + 1
134
- const recap = prompt('compact/summary', { summary, requests: requestsOf(chat) })
135
+ const recap = prompt('compact/summary', { summary, findings, requests: requestsOf(chat) })
135
136
  if (native) {
136
137
  chat.messages = midTask
137
138
  ? [...head, { role: 'user', content: `${recap}\n\n${prompt('compact/continue', { task })}` }]
@@ -147,6 +148,31 @@ export class Session {
147
148
  return summary
148
149
  }
149
150
 
151
+ // Before the conversation is summarized, the model working on it writes down what it has found:
152
+ // its conclusions live in its reasoning, which the summary (written from the transcript) never
153
+ // sees, and without them it reads the same files again after every compaction. Asked as the next
154
+ // message of its own conversation with the same tools, so the provider's cache of it still holds;
155
+ // tool calls in the reply aren't run. '' when there's nothing to ask or it fails (the summary alone).
156
+ async findings(signal) {
157
+ const { chat, client, strat } = this
158
+ if (!chat.messages?.length || !this.lastTools) return ''
159
+ // already past the model's window (one step can add a lot): the request would only be refused
160
+ if (strat.context > 0 && tokensOf(chat.messages, this.lastTools.map((t) => t.function), strat.ratio ?? 1) > strat.context * 0.95) {
161
+ log('compact', 'no findings note: the conversation is already past the window')
162
+ return ''
163
+ }
164
+ try {
165
+ const r = await client.chat({ messages: [...chat.messages, { role: 'user', content: prompt('compact/findings') }], tools: this.lastTools }, { signal })
166
+ const note = String(r.content ?? '').trim()
167
+ log('compact', note ? `findings note: ${note.length} characters` : 'no findings note (the reply had no text)', note)
168
+ return note
169
+ } catch (e) {
170
+ if (e.name === 'AbortError') throw e
171
+ log('compact', `no findings note: ${e.message}`)
172
+ return ''
173
+ }
174
+ }
175
+
150
176
  // images: data: URLs from the caller (headless input), besides @shot.png in the task.
151
177
  async run(task, signal, extra = []) {
152
178
  if (!this.isSub) this.client.newMessage?.() // the model list: from #1 again (unless set to stay)
@@ -743,14 +769,15 @@ async function runNative(s, task, images, signal) {
743
769
  // window as set up, measured or learned; also when that changes mid-task, or the model list moves
744
770
  // on to a model with a smaller one), so there's room left for the reply. Its size: what the server
745
771
  // counted for this conversation's last request (s.counted) plus the estimate of what came since
746
- // (the tool results), or the estimate of all of it when that's more (no count yet: a resumed
747
- // session, just compacted). After a failed try: again once it has grown by another 5%.
772
+ // (the tool results, never counted smaller than estimated: they're often code), or the estimate of
773
+ // all of it when that's more (no count yet: a resumed session, just compacted). After a failed try:
774
+ // again once it has grown by another 5%.
748
775
  const used = () => {
749
776
  const ratio = strat.ratio ?? 1
750
777
  const all = tokensOf(s.messages, [...TOOL_DEFS, ...extraTools(s)], ratio)
751
778
  const k = s.counted
752
779
  if (!k?.tokens || k.upTo > s.messages.length) return all
753
- return Math.max(all, k.tokens + tokensOf(s.messages.slice(k.upTo), null, ratio))
780
+ return Math.max(all, k.tokens + tokensOf(s.messages.slice(k.upTo), null, Math.max(1, ratio)))
754
781
  }
755
782
  const nearlyFull = () => s.autoCompact && strat.context > 0 && used() >= strat.context * COMPACT_SHARE && used() >= (s.compactFailedAt ?? 0)
756
783
  const fullness = () => `context ${Math.round((used() / strat.context) * 100)}% full (~${kTokens(used())} of ${kTokens(strat.context)})`
@@ -779,6 +806,7 @@ async function runNative(s, task, images, signal) {
779
806
  }
780
807
  // Already that long from earlier messages: switch to a roomier model, or else compact first, so the
781
808
  // new message stays word for word.
809
+ if (nearlyFull() && dropStale(s)) log('compact', 'older copies of files read again shortened first')
782
810
  if (nearlyFull() && !roomier()) {
783
811
  await s.compact({ signal, why: fullness() }).then(afterCompact, (e) => (e.name === 'AbortError' ? Promise.reject(e) : ui.warn(`could not compact: ${e.message}`)))
784
812
  }
@@ -816,6 +844,7 @@ async function runNative(s, task, images, signal) {
816
844
  if (!s.isSub) s.choicesFresh = false // a question about how to do it, this message: replaces the earlier answers (s.chat.choices)
817
845
  s.runFails = new Map() // a command that failed (by its tool) → its error; when the same tool runs clean after an edit, that's a verified fix to learn from (any language, not just web)
818
846
  s.edits = 0 // successful file edits so far this message (to tell a real fix from a lucky rerun)
847
+ s.userSaid = [] // what the user typed with a "no" to a tool call: sent as their message after the results (declined in tools.js)
819
848
  s.acted = false // used a tool this message (so a reply that only promises more is a premature stop)
820
849
  let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
821
850
  let sinceNudge = true // a tool call made since the last reminder: one that changed nothing isn't sent again (no count: it goes on while the model gets on)
@@ -841,11 +870,13 @@ async function runNative(s, task, images, signal) {
841
870
  for (let step = 0; ; step++) {
842
871
  if (step && !s.isSub) s.onTurn?.() // saved after every step: a quit, crash or kill mid-task loses nothing done so far
843
872
  const tools = toolList()
873
+ s.lastTools = tools // what the requests carry: the findings note before compacting sends the same (compact)
844
874
  if (s.maxTurns && step >= s.maxTurns) {
845
875
  ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
846
876
  throw Object.assign(new Error(`stopped after ${s.maxTurns} steps (--max-turns)`), { maxTurns: true })
847
877
  }
848
878
  // after a failed compaction, the next try waits until the conversation has grown by 5% of the window
879
+ if (nearlyFull() && dropStale(s)) log('compact', 'older copies of files read again shortened first')
849
880
  if (nearlyFull() && step !== s.compactedAt && !roomier()) {
850
881
  s.compactedAt = step
851
882
  await s.compact({ signal, midTask: true, task, why: fullness() }).then(
@@ -1048,7 +1079,7 @@ async function runNative(s, task, images, signal) {
1048
1079
  lastCall = sig
1049
1080
  if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow })}`
1050
1081
  if (inRow >= 5) stuck = `made the same ${name} call five times in a row`
1051
- if (name === 'read_file' || name === 'search' || name === 'list_files' || name === 'web_fetch' || name === 'web_search') ui.result(`${out.split('\n').length} lines`)
1082
+ if (name === 'read_file' || name === 'search' || name === 'list_files' || name === 'web_fetch' || name === 'web_search' || name === 'changes') ui.result(`${out.split('\n').length} lines`)
1052
1083
  else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
1053
1084
  else if (failed(out)) ui.result(clip(out, 120))
1054
1085
  client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
@@ -1063,6 +1094,7 @@ async function runNative(s, task, images, signal) {
1063
1094
  s.messages.push(msg)
1064
1095
  s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
1065
1096
  }
1097
+ if (s.userSaid.length) s.messages.push({ role: 'user', content: s.userSaid.splice(0).join('\n\n') }) // their own words, as they typed them
1066
1098
  trimOldResults(s)
1067
1099
  const ended = newlyEnded(s.root) // background commands that exited meanwhile: the model hears it now
1068
1100
  if (ended.length) {
@@ -1095,7 +1127,7 @@ const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1095
1127
  // Files only read by people (a change there needs no run to check it).
1096
1128
  const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
1097
1129
  // Tools that only look (nothing changes): several in one reply run at the same time.
1098
- const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp'])
1130
+ const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'])
1099
1131
  export function newGuard() {
1100
1132
  const seen = new Map() // what a call is → { out, at }
1101
1133
  let epoch = 0 // goes up with each change (an edit, a command that can change things)
@@ -1111,7 +1143,7 @@ export function newGuard() {
1111
1143
  const keyOf = (name, a) => {
1112
1144
  if (name === 'web_search') return `search: ${words(a.query)}${a.fresh ? ' (fresh)' : ''}`
1113
1145
  if (name === 'web_fetch') return `page: ${String(a.url ?? '').toLowerCase().replace(/^https?:\/\/(www\.)?/, '').replace(/\/+$/, '')} @${a.start ?? 0} ${words(a.look_for)}`
1114
- if (['run_command', 'read_file', 'search', 'list_files', 'find_command', 'lsp'].includes(name)) return `${name} ${JSON.stringify(a)} @${epoch}`
1146
+ if (['run_command', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'].includes(name)) return `${name} ${JSON.stringify(a)} @${epoch}`
1115
1147
  return null
1116
1148
  }
1117
1149
  g.before = (name, a) => {
@@ -1441,8 +1473,9 @@ function callOf(messages, id) {
1441
1473
  // provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
1442
1474
  // An older conversation's results (no file yet) are saved now, before they're cut.
1443
1475
  export function trimOldResults(s, keep = 4, most = 8) {
1444
- const long = s.messages.filter((m) => m.role === 'tool' && typeof m.content === 'string' && m.content.length > SAVE_AT && !shortened.has(m) && !/^\[older output/.test(m.content))
1476
+ const long = s.messages.filter((m) => m.role === 'tool' && typeof m.content === 'string' && m.content.length > SAVE_AT && !shortened.has(m) && !/^\[older output/.test(m.content) && !s.staleCopies?.has(m))
1445
1477
  if (long.length <= most) return
1478
+ dropStale(s) // the conversation changes here anyway: the older copies of files read again go too
1446
1479
  for (const m of long.slice(0, -keep)) {
1447
1480
  const call = callOf(s.messages, m.tool_call_id)
1448
1481
  const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
@@ -1454,16 +1487,23 @@ export function trimOldResults(s, keep = 4, most = 8) {
1454
1487
  log('tool', `older tool output cut: ${long.length - keep} results`)
1455
1488
  }
1456
1489
 
1457
- // A file read again: the older copy in the conversation becomes a one-line note.
1490
+ // A file read again: the older copy in the conversation becomes a one-line note, later. Changing a
1491
+ // message in the middle makes the provider process everything after it again (its prompt cache
1492
+ // keeps only the unchanged start: minutes on a local model, full price on a paid one), so the older
1493
+ // copies wait and go together with the old results (trimOldResults), or when it's nearly full.
1458
1494
  function replaceCopy(s, file, msg) {
1459
1495
  const key = path.normalize(String(file))
1460
1496
  const older = (s.copies ??= new Map()).get(key)
1461
- if (older && !shortened.has(older)) {
1462
- older.content = prompt('agent/older-copy', { file })
1463
- shortened.add(older)
1464
- }
1497
+ if (older && !shortened.has(older)) (s.staleCopies ??= new Map()).set(older, file)
1465
1498
  s.copies.set(key, msg)
1466
1499
  }
1500
+ // the older copies waiting, replaced now: true when there were any
1501
+ function dropStale(s) {
1502
+ if (!s.staleCopies?.size) return false
1503
+ for (const [m, file] of s.staleCopies) if (!shortened.has(m)) (m.content = prompt('agent/older-copy', { file })), shortened.add(m)
1504
+ s.staleCopies.clear()
1505
+ return true
1506
+ }
1467
1507
 
1468
1508
  // Files the user's message names go in as if the model had already read them: one round trip less
1469
1509
  // per file, and the model starts from the real content. Small text files only, at most 3.
package/src/client.js CHANGED
@@ -3,7 +3,17 @@ import { createHash } from 'node:crypto'
3
3
  import { setTimeout as sleep } from 'node:timers/promises'
4
4
  import { log, logRequest, requestLog } from './log.js'
5
5
 
6
- export const est = (text) => Math.ceil(String(text ?? '').length / 3.5)
6
+ // Tokens in a text, estimated the way tokenizers split it: a word or a number is about one, a long
7
+ // word more, every symbol one. Prose comes out near characters ÷ 4; code, CSS, JSON and SVG paths,
8
+ // dense with symbols and digits, far higher (a flat characters ÷ 3.5 was 2× low on them: a request
9
+ // estimated to fit was refused, and compacting never started).
10
+ const PIECE = /[A-Za-z]+|\d{1,3}|[^\sA-Za-z\d]/g
11
+ export const est = (text) => {
12
+ const t = String(text ?? '')
13
+ let n = 0
14
+ for (const [w] of t.matchAll(PIECE)) n += w.length > 7 && /[A-Za-z]/.test(w[0]) ? Math.ceil(w.length / 6) : 1
15
+ return Math.max(n, Math.ceil(t.length / 4))
16
+ }
7
17
  // An error that may go away by itself: a rate limit, a server error or overload, a timeout, no
8
18
  // connection (no status). Anything else (a wrong model name, key or request) won't.
9
19
  // A 403 that is a web page, not the API's own (JSON) answer, comes from a gateway or proxy in
@@ -13,15 +23,33 @@ export const outage = (e) => !e.status || [408, 409, 429].includes(e.status) ||
13
23
  // won't help, but the next one in the list may work.
14
24
  export const unusable = (e) => [401, 403, 404].includes(e.status) && !outage(e)
15
25
  // A request's messages, estimated: an image's data isn't text (about 800 tokens, not its base64)
16
- export function estMessages(messages) {
26
+ // Each message's count is kept while its content is the same (a long conversation is counted
27
+ // several times a step). chars: its length, for the floor below.
28
+ const counted = new WeakMap()
29
+ function estMessage(m) {
30
+ const had = counted.get(m)
31
+ if (had && had.content === m.content && had.calls === m.tool_calls) return had
17
32
  let images = 0
18
- const text = JSON.stringify(messages ?? [], (k, v) => (k === 'url' && typeof v === 'string' && v.startsWith('data:') ? (images++, '') : v))
19
- return est(text) + images * 800
33
+ const text = JSON.stringify(m, (k, v) => (k === 'url' && typeof v === 'string' && v.startsWith('data:') ? (images++, '') : v))
34
+ const got = { content: m.content, calls: m.tool_calls, tokens: est(text) + images * 800, chars: text.length }
35
+ if (m && typeof m === 'object') counted.set(m, got)
36
+ return got
37
+ }
38
+ export function estMessages(messages, chars = false) {
39
+ let n = 0
40
+ for (const m of messages ?? []) n += estMessage(m)[chars ? 'chars' : 'tokens']
41
+ return n
20
42
  }
21
43
  // A request's size in a model's tokens, estimated: its messages and tools, by that model's ratio of
22
44
  // counted to estimated tokens (context.js). The same measure decides when to compact (agent.js) and
23
45
  // whether a request fits the model the list moves on to.
24
- export const tokensOf = (messages, tools, ratio = 1) => Math.round((estMessages(messages) + (tools?.length ? est(JSON.stringify(tools)) : 0)) * ratio)
46
+ // The learned ratio never takes it below characters ÷ 4: a ratio learned on prose would otherwise
47
+ // make code look smaller than it is.
48
+ export const tokensOf = (messages, tools, ratio = 1) => {
49
+ const e = estMessages(messages) + (tools?.length ? est(JSON.stringify(tools)) : 0)
50
+ const floor = (estMessages(messages, true) + (tools?.length ? JSON.stringify(tools).length : 0)) / 4
51
+ return Math.round(Math.max(e * ratio, Math.min(e, floor)))
52
+ }
25
53
  // The share of a model's window a conversation may take: the rest is room for the reply. Past it,
26
54
  // the conversation is compacted first.
27
55
  export const COMPACT_SHARE = 0.85
package/src/config.js CHANGED
@@ -5,6 +5,19 @@ import { fileURLToPath } from 'node:url'
5
5
 
6
6
  export const HOME = process.env.HEART_HOME || path.join(os.homedir(), '.heart')
7
7
  export const CONFIG_FILE = path.join(HOME, 'config.json')
8
+ // --temp (bin/heart.js): HOME is a throwaway folder, deleted after the run, and nothing is kept
9
+ // anywhere else either: the project's own HeartCode folders are copies in it (projectDir)
10
+ export const TEMP = process.env.HEART_TEMP === '1'
11
+
12
+ // The project's .heartcode/<what> (research, memory). In a --temp run, a copy in the throwaway
13
+ // folder instead: what the project has is read, what the run adds goes with the folder.
14
+ export function projectDir(root, what) {
15
+ const real = path.join(root, '.heartcode', what)
16
+ if (!TEMP) return real
17
+ const dir = path.join(HOME, 'projects', path.resolve(root).replace(/[^\w.-]+/g, '_'), what)
18
+ if (!fs.existsSync(dir)) fs.existsSync(real) ? fs.cpSync(real, dir, { recursive: true }) : fs.mkdirSync(dir, { recursive: true })
19
+ return dir
20
+ }
8
21
 
9
22
  const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'modelChoice', 'logs', 'replyStart', 'mouse']
10
23
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
package/src/director.js CHANGED
@@ -2,11 +2,12 @@
2
2
  // asked in plain words, with one tool, manage. The settings page (General → Features) turns it off.
3
3
  import fs from 'node:fs'
4
4
  import path from 'node:path'
5
- import { HOME, readJson, writeJson } from './config.js'
5
+ import { HOME, TEMP, readJson, writeJson } from './config.js'
6
6
  import { log } from './log.js'
7
7
  import { DEFAULT_SERVERS } from './mcp.js'
8
8
  import { prompt } from './prompts.js'
9
9
  import { frontMatter, loadSkills, skillDirs } from './skills.js'
10
+ import { declined } from './tools.js'
10
11
  import { c, diffLines, renderDiff } from './ui.js'
11
12
 
12
13
  const KINDS = ['skill', 'mcp', 'setting']
@@ -41,7 +42,7 @@ export class Director {
41
42
  async manage(args, s) {
42
43
  const { app } = this
43
44
  const kind = args.kind
44
- const scope = args.scope === 'global' ? 'global' : 'project'
45
+ const scope = args.scope === 'global' || TEMP ? 'global' : 'project' // --temp: saved in the throwaway folder, never in the project
45
46
  const name = safeName(args.name)
46
47
  if (args.action === 'help') return prompt('agent/director-help', Object.fromEntries(['args', '1', '2'].map((k) => [k, `{{${k}}}`]))) // the formats show these holes as they are
47
48
  if (!KINDS.includes(kind)) return `error: kind must be one of ${KINDS.join(', ')}`
@@ -57,12 +58,13 @@ export class Director {
57
58
  const existing = loadSkills(app.root).get(name)
58
59
  const dir = dirs[scope === 'global' ? 0 : 1]
59
60
  // saving changes the existing file, unless a scope is given that it isn't in (then a new one there)
60
- const file = existing && (!args.scope || existing.file.startsWith(dir + path.sep)) ? existing.file : path.join(dir, `${name}.md`)
61
+ const file = existing && (!args.scope || existing.file.startsWith(dir + path.sep)) && !(TEMP && !existing.file.startsWith(HOME + path.sep)) ? existing.file : path.join(dir, `${name}.md`)
61
62
  if (args.action === 'show') return existing ? `${existing.file}\n\n${fs.readFileSync(existing.file, 'utf8')}` : `error: no ${kind} "${name}"`
62
63
  if (args.action === 'delete') {
63
64
  if (!existing) return `error: no ${kind} "${name}"`
65
+ if (TEMP && !existing.file.startsWith(HOME + path.sep)) return TEMP_REFUSED
64
66
  const ok = await s.ui.confirm(`Delete the ${kind} ${name} (${existing.file})?`, 'edit')
65
- if (ok !== true) return declined(ok)
67
+ if (ok !== true) return declined(s, ok, 'The user declined.')
66
68
  // a skill in its own folder (<name>/SKILL.md): that folder; never a skills folder itself
67
69
  const folder = path.dirname(existing.file)
68
70
  const isFolder = path.basename(existing.file) === 'SKILL.md' && !skillDirs(app.root).some((d) => path.resolve(d) === path.resolve(folder))
@@ -77,7 +79,7 @@ export class Director {
77
79
  const old = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : ''
78
80
  s.ui.print(renderDiff(diffLines(old, content + '\n'), tilde(file)))
79
81
  const ok = await s.ui.confirm(`${old ? 'Update' : 'Save'} the ${kind} ${name}?`, 'edit')
80
- if (ok !== true) return declined(ok)
82
+ if (ok !== true) return declined(s, ok, 'The user declined.')
81
83
  fs.mkdirSync(path.dirname(file), { recursive: true })
82
84
  fs.writeFileSync(file, content + '\n')
83
85
  app.reload(kind)
@@ -109,8 +111,9 @@ export class Director {
109
111
  data.mcpServers ??= {}
110
112
  if (action === 'delete') {
111
113
  if (!where && !DEFAULT_SERVERS[name]) return `error: no MCP server "${name}"`
114
+ if (TEMP && where?.scope === 'project') return TEMP_REFUSED
112
115
  const ok = await s.ui.confirm(`${DEFAULT_SERVERS[name] ? 'Turn off' : 'Delete'} the MCP server ${name}?`, 'edit')
113
- if (ok !== true) return declined(ok)
116
+ if (ok !== true) return declined(s, ok, 'The user declined.')
114
117
  if (DEFAULT_SERVERS[name]) data.mcpServers[name] = { disabled: true } // built in: turned off, not gone
115
118
  else delete data.mcpServers[name]
116
119
  writeJson(file, data)
@@ -133,7 +136,7 @@ export class Director {
133
136
  const clean = Object.fromEntries(['command', 'args', 'env', 'url', 'headers', 'description', 'disabled'].filter((k) => cfg[k] !== undefined).map((k) => [k, cfg[k]]))
134
137
  s.ui.print(`${c.bold(name)} ${c.faint(`→ ${tilde(file)}`)}\n ${c.muted(JSON.stringify(clean))}`)
135
138
  const ok = await s.ui.confirm(clean.url && !clean.command ? `Save the MCP server ${name}? HeartCode will connect to ${clean.url}` : `Save the MCP server ${name}? HeartCode will run: ${clean.command ?? ''} ${(clean.args ?? []).join(' ')}`, 'command')
136
- if (ok !== true) return declined(ok)
139
+ if (ok !== true) return declined(s, ok, 'The user declined.')
137
140
  data.mcpServers[name] = { ...data.mcpServers[name], ...clean }
138
141
  writeJson(file, data)
139
142
  this.app.reload('mcp')
@@ -141,6 +144,6 @@ export class Director {
141
144
  }
142
145
  }
143
146
 
144
- const declined = (ok) => `The user declined.${typeof ok === 'string' ? ` User feedback: ${ok}` : ''}`
147
+ const TEMP_REFUSED = "error: this is a --temp run, which keeps nothing, so it can't change the project's own files. Tell the user what to change instead."
145
148
  const tilde = (f) => (process.env.HOME && f.startsWith(process.env.HOME) ? '~' + f.slice(process.env.HOME.length) : f)
146
149
  const mcpFiles = (root) => [{ scope: 'global', file: path.join(HOME, 'mcp.json') }, { scope: 'project', file: path.join(root, '.heartcode', 'mcp.json') }]
package/src/importer.js CHANGED
@@ -7,7 +7,7 @@ import fs from 'node:fs'
7
7
  import os from 'node:os'
8
8
  import path from 'node:path'
9
9
  import { spawnSync } from 'node:child_process'
10
- import { HOME, readJson, writeJson } from './config.js'
10
+ import { HOME, TEMP, readJson, writeJson } from './config.js'
11
11
  import { frontMatter } from './skills.js'
12
12
  import { Memory } from './memory.js'
13
13
 
@@ -38,7 +38,8 @@ function filesIn(dir, exts) {
38
38
  }
39
39
 
40
40
  const safe = (n) => String(n).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
41
- const skillsDir = (root, scope) => (scope === 'global' ? path.join(HOME, 'skills') : path.join(root, '.heartcode', 'skills'))
41
+ // --temp: the throwaway folder, never the project (nothing is kept from a --temp run)
42
+ const skillsDir = (root, scope) => (scope === 'global' || TEMP ? path.join(HOME, 'skills') : path.join(root, '.heartcode', 'skills'))
42
43
  const taken = (root, scope, name) => exists(path.join(skillsDir(root, scope), `${name}.md`)) || exists(path.join(skillsDir(root, scope), name))
43
44
  // name, else name-2, name-3…: the first not taken
44
45
  const freeName = (isTaken, name) => {
@@ -101,7 +102,7 @@ function importSkillFolder(root, scope, name, dir) {
101
102
  return name
102
103
  }
103
104
 
104
- const mcpFile = (root, scope) => (scope === 'global' ? path.join(HOME, 'mcp.json') : path.join(root, '.heartcode', 'mcp.json'))
105
+ const mcpFile = (root, scope) => (scope === 'global' || TEMP ? path.join(HOME, 'mcp.json') : path.join(root, '.heartcode', 'mcp.json'))
105
106
  const serverKey = (cfg) => (cfg.command ? [cfg.command, ...(cfg.args ?? [])].join(' ') : (cfg.url ?? cfg.httpUrl ?? ''))
106
107
  // Why an MCP server would be a duplicate there, or ''
107
108
  function mcpDup(root, scope, name, cfg) {
package/src/memory.js CHANGED
@@ -14,7 +14,7 @@
14
14
  // less: the tag list in the system prompt, and with each message only the notes it matches.
15
15
  import fs from 'node:fs'
16
16
  import path from 'node:path'
17
- import { HOME } from './config.js'
17
+ import { HOME, projectDir } from './config.js'
18
18
 
19
19
  export const TYPES = ['user', 'project', 'feedback', 'reference']
20
20
  const LINK = /\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]/g
@@ -146,7 +146,7 @@ class Notes {
146
146
  // the same name); writing goes to the scope asked for, or where the note already is.
147
147
  export class Memory {
148
148
  constructor(root, globalDir = path.join(HOME, 'memory')) {
149
- this.project = new Notes(path.join(root, '.heartcode', 'memory'), 'project')
149
+ this.project = new Notes(projectDir(root, 'memory'), 'project')
150
150
  this.global = new Notes(globalDir, 'global')
151
151
  }
152
152
 
package/src/research.js CHANGED
@@ -17,8 +17,9 @@ import fs from 'node:fs'
17
17
  import path from 'node:path'
18
18
  import { createHash } from 'node:crypto'
19
19
  import { keywords } from './memory.js'
20
+ import { projectDir } from './config.js'
20
21
 
21
- export const researchDir = (root) => path.join(root, '.heartcode', 'research')
22
+ export const researchDir = (root) => projectDir(root, 'research')
22
23
  const slugOf = (s, n) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, n).replace(/-+$/, '')
23
24
  const hash = (s) => createHash('sha256').update(String(s)).digest('hex').slice(0, 8)
24
25
  const today = () => new Date().toISOString().slice(0, 10)
package/src/settings.js CHANGED
@@ -30,7 +30,7 @@ import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLog
30
30
 
31
31
  const PAGE = new URL('./settings.html', import.meta.url)
32
32
  const EFFORTS = ['default', 'low', 'medium', 'high']
33
- const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit", updateCheck: 'check once a day whether a newer HeartCode is out (shown in the status bar; /update installs it)' }
33
+ const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit", updateCheck: 'check at every start whether a newer HeartCode is out (shown in the status bar; /update installs it)' }
34
34
  // The Logging page's: both off unless switched on; how much of each request ("full" or "summary")
35
35
  // The status-bar items the visual editor offers (id must match App.status in bin/heartcode.js).
36
36
  // `sample` is shown in the page's live preview.
package/src/tools.js CHANGED
@@ -218,12 +218,25 @@ function readImage(s, p) {
218
218
  export function searchFiles(root, query, sub = '', limit = 50) {
219
219
  const ci = query === query.toLowerCase()
220
220
  let re
221
+ let literal = false // not a valid regular expression: searched as the text it is
221
222
  try {
222
223
  re = new RegExp(query, ci ? 'i' : '')
223
224
  } catch {
224
225
  re = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), ci ? 'i' : '')
226
+ literal = true
227
+ }
228
+ // a pattern given as the path ("src/*.css", "**/*.ts"): the folder before it, and its files that fit
229
+ let only = null
230
+ const pattern = sub
231
+ if (/[*?]/.test(sub)) {
232
+ const parts = String(sub).split(/[\\/]/)
233
+ const at = parts.findIndex((p) => /[*?]/.test(p))
234
+ const glob = parts.slice(at).filter((p) => p !== '**').join('/') || '*'
235
+ only = new RegExp(`(^|/)${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')}$`)
236
+ sub = parts.slice(0, at).join('/')
225
237
  }
226
238
  const abs = sub ? resolveIn(root, sub, true) : ''
239
+ if (abs && !fs.existsSync(abs)) return `error: ${sub} doesn't exist, so nothing was searched (this is not "no matches"). Give a file or folder that exists, or leave path out to search the whole project.`
227
240
  const away = abs && abs !== root && !abs.startsWith(root + path.sep) && !isSavedOutput(abs) // a folder the user named outside the project
228
241
  let single = false // one file named: searched whatever lists leave out (a saved page, a .gitignored file)
229
242
  try {
@@ -232,8 +245,11 @@ export function searchFiles(root, query, sub = '', limit = 50) {
232
245
  const saved = isSavedOutput(abs) || single
233
246
  const prefix = sub && !saved && !away ? path.relative(root, abs) : ''
234
247
  const hits = []
248
+ let searched = 0
235
249
  for (const f of saved ? [abs] : away ? listFiles(abs).map((f) => path.join(abs, f)) : listFiles(root)) {
236
250
  if (prefix && f !== prefix && !f.startsWith(prefix + '/')) continue
251
+ if (only && !only.test(f)) continue
252
+ searched++
237
253
  let buf
238
254
  try {
239
255
  buf = fs.readFileSync(path.resolve(root, f))
@@ -248,7 +264,8 @@ export function searchFiles(root, query, sub = '', limit = 50) {
248
264
  if (hits.length >= limit) return hits.join('\n') + `\n… (stopped at ${limit} matches)`
249
265
  }
250
266
  }
251
- return hits.join('\n') || `no matches for ${query}`
267
+ if (hits.length) return hits.join('\n')
268
+ return searched ? `no matches for ${query} in ${searched} file${searched === 1 ? '' : 's'} searched${literal ? ' (as plain text: it isn\'t a valid regular expression)' : ''}` : `nothing was searched: no files${only ? ` fit ${pattern}` : ''} in ${sub || 'the project'} (this is not "no matches")`
252
269
  }
253
270
 
254
271
  // Runs a shell command in its own process group. The command is over when its shell exits, even
@@ -295,11 +312,12 @@ export function runCommand(root, cmd, { signal, timeout = 120_000, stdin, env, s
295
312
  child.stdout.destroy()
296
313
  child.stderr.destroy()
297
314
  const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
298
- resolve({ code, output: plain(out) + note, ...(split && { stderr: plain(err) }) })
315
+ resolve({ code, output: (dropped ? '(the start of a very long output was left out: only its last 100,000 characters are here; the command itself was not affected)\n…' : '') + plain(out) + note, ...(split && { stderr: plain(err) }) })
299
316
  }
317
+ let dropped = false // a very long output's start, left out (said, so it isn't read as the command failing)
300
318
  const add = (d) => {
301
319
  out += d
302
- if (out.length > 200_000) out = out.slice(-100_000)
320
+ if (out.length > 200_000) (out = out.slice(-100_000)), (dropped = true)
303
321
  }
304
322
  const addErr = (d) => {
305
323
  err += d
@@ -332,6 +350,38 @@ export function suggestCommands(root) {
332
350
  return out.slice(0, 9)
333
351
  }
334
352
 
353
+ // What the model changed in files: this message's (or with all, the conversation's), each file from
354
+ // before its first change to now (the turns keep that first version for /rewind; /diff shows the same).
355
+ function changesTool(s, args) {
356
+ const turns = args.all ? (s.chat?.turns ?? []) : (s.chat?.turns ?? []).slice(-1)
357
+ const first = new Map()
358
+ for (const t of turns) for (const [rel, before] of Object.entries(t.files ?? {})) if (!first.has(rel)) first.set(rel, before)
359
+ const want = String(args.path ?? '').trim().replace(/^\.\//, '')
360
+ const out = []
361
+ for (const rel of [...first.keys()].filter((f) => !want || f === want || f.endsWith('/' + want)).sort()) {
362
+ const abs = path.join(s.root, rel)
363
+ const now = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null
364
+ const was = first.get(rel)
365
+ if (was === now) continue
366
+ out.push(was === null ? `${rel} (new)\n${renderDiff(diffLines('', now), rel, false, 3, 400)}` : now === null ? `${rel} (deleted)` : renderDiff(diffLines(was, now), rel, false, 3, 400))
367
+ }
368
+ const where = args.all ? 'in this conversation' : 'for this message'
369
+ return out.join('\n\n') || (want ? `No changes to ${want} ${where}.` : `No file changes ${where}${first.size ? ' (the files you changed are back as they were)' : ''}.`)
370
+ }
371
+
372
+ // A "no" from the user, with what they typed instead. Their words go to the model as their own message,
373
+ // after the tool results (s.userSaid, which the agent sends): inside a result a model reads them as the
374
+ // tool talking, and tries again. Where there's no queue (guided mode) or no user (headless: the "no" is
375
+ // HeartCode's), they stay in the result.
376
+ export function declined(s, ok, what) {
377
+ const said = typeof ok === 'string' ? ok.trim() : ''
378
+ if (said && s.userSaid && !s.ui.noUser) {
379
+ s.userSaid.push(said)
380
+ return `${what} What they want instead is in their message that follows.`
381
+ }
382
+ return `${what}${said ? ` ${s.ui.noUser ? said : `User feedback: ${said}`}` : ''}`
383
+ }
384
+
335
385
  const PLACEHOLDER = /(\.\.\.|…)\s*(rest|existing|remaining|unchanged|other)|rest of (the )?(code|file)|existing code (here|unchanged)/i
336
386
 
337
387
  // Shows the diff, asks the user, writes (next = null: deletes the file). Shared by both agent modes.
@@ -343,7 +393,7 @@ export async function proposeWrite(s, rel, old, next) {
343
393
  if (next !== null && PLACEHOLDER.test(next) && !PLACEHOLDER.test(old)) s.ui.warn('the new content seems to contain a placeholder like "rest of code unchanged"')
344
394
  const ok = await s.ui.confirm(next === null ? `Delete ${rel}?` : old ? `Apply this change to ${rel}?` : `Create ${rel}?`)
345
395
  log('write', rel, ok === true ? 'approved' : `rejected ${typeof ok === 'string' ? ok : ''}`)
346
- if (ok !== true) return { status: 'rejected', feedback: typeof ok === 'string' ? ok : '' }
396
+ if (ok !== true) return { status: 'rejected', said: declined(s, ok, '') }
347
397
  const abs = resolveIn(s.root, rel)
348
398
  s.track?.(rel, fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null) // for /rewind
349
399
  if (next === null) fs.rmSync(abs, { force: true })
@@ -426,7 +476,7 @@ export async function runConfirmed(s, cmd, signal, background = false, wait) {
426
476
  return prompt('agent/command-too-wide', { root: s.root })
427
477
  }
428
478
  const ok = s.ui.permission === 'plan' ? true : await s.ui.confirm(`Run ${c.bold(cmd)}?`, 'command') // plan mode: only read-only ones get here
429
- if (ok !== true) return `The user declined to run this command.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
479
+ if (ok !== true) return declined(s, ok, 'The user declined to run this command.')
430
480
  const secs = Number(wait) > 0 ? Number(wait) : background ? 3 : 30
431
481
  const before = snapshot(s)
432
482
  s.ui.spinner(`running ${cmd}`)
@@ -531,7 +581,7 @@ function changesSince(s, before) {
531
581
  export function writeResult(rel, r) {
532
582
  if (r.status === 'applied') return `${r.deleted ? 'Deleted' : 'Changed'} ${rel} (${r.summary}).${r.note ? `\n${r.note}` : ''}`
533
583
  if (r.status === 'unchanged') return `No change: the new content of ${rel} is identical to the old content.`
534
- return `The user rejected the change to ${rel}.${r.feedback ? ' User feedback: ' + r.feedback : ''}`
584
+ return r.feedback ? r.feedback : `The user rejected the change to ${rel}.${r.said ?? ''}`
535
585
  }
536
586
 
537
587
  // --- native tool calling ---
@@ -543,6 +593,7 @@ const obj = (properties, required = []) => ({ type: 'object', properties, requir
543
593
  export const TOOL_DEFS = [
544
594
  { name: 'read_file', description: prompt('agent/tool-read_file'), parameters: obj({ path: str, start_line: int, end_line: int }, ['path']) },
545
595
  { name: 'search', description: prompt('agent/tool-search'), parameters: obj({ query: str, path: str }, ['query']) },
596
+ { name: 'changes', description: prompt('agent/tool-changes'), parameters: obj({ path: str, all: { type: 'boolean' } }) },
546
597
  { name: 'list_files', description: prompt('agent/tool-list_files'), parameters: obj({ path: str, filter: str }) },
547
598
  { name: 'find_command', description: prompt('agent/tool-find_command'), parameters: obj({ names: { type: 'array', items: str } }, ['names']) },
548
599
  { name: 'lsp', description: prompt('agent/tool-lsp'), parameters: obj({ server: str, language: str, action: { type: 'string', enum: ['definition', 'references', 'hover', 'errors'] }, file: str, line: int, column: int, name: str }, ['server', 'language', 'action', 'file']) },
@@ -737,7 +788,7 @@ async function webTool(s, name, args, signal) {
737
788
  const what = name === 'web_search' ? String(args.query ?? '') : String(args.url ?? '')
738
789
  if (!what.trim()) return `error: ${name} needs ${name === 'web_search' ? '"query"' : '"url"'}`
739
790
  const ok = await s.ui.confirm(name === 'web_search' ? `Search the web for ${c.bold(what)}?` : `Fetch ${c.bold(what)}?`, 'read')
740
- if (ok !== true) return `The user declined this.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
791
+ if (ok !== true) return declined(s, ok, 'The user declined this.')
741
792
  // what this message's research is for: the page's look_for, else the last search, else the task
742
793
  const purpose = String(args.look_for ?? '').trim() || s.lastQuery || String(s.task ?? '').split('\n')[0].slice(0, 160)
743
794
  if (name === 'web_search') {
@@ -949,7 +1000,7 @@ async function callMcp(s, server, tool, a, signal) {
949
1000
  // declines what it would ask, so a browser's snapshot must not be); any other like a command
950
1001
  if (!def?.annotations?.readOnlyHint) {
951
1002
  const ok = await s.ui.confirm(`Use ${server.name} → ${tool}?`, 'command')
952
- if (ok !== true) return `The user declined this call.${typeof ok === 'string' ? ' User feedback: ' + ok : ''}`
1003
+ if (ok !== true) return declined(s, ok, 'The user declined this call.')
953
1004
  }
954
1005
  const done = await s.mcpGate?.() // a helper may be using the MCP servers (a browser): its turn first
955
1006
  s.ui.spinner(`${server.name} · ${tool}`)
@@ -1296,6 +1347,8 @@ async function tool(name, args, s, signal, id) {
1296
1347
  }
1297
1348
  case 'search':
1298
1349
  return searchFiles(root, String(args.query ?? ''), args.path)
1350
+ case 'changes':
1351
+ return changesTool(s, args)
1299
1352
  case 'find_command': {
1300
1353
  const names = (Array.isArray(args.names) ? args.names : String(args.names ?? args.name ?? '').split(/[\s,]+/)).map(String).filter(Boolean)
1301
1354
  if (!names.length) return 'error: find_command needs "names": the commands to look for, like ["rg", "pnpm"]'
package/src/update.js CHANGED
@@ -1,4 +1,4 @@
1
- // A newer HeartCode: asked of npm at most once a day (in the background, never waited on), shown in
1
+ // A newer HeartCode: asked of npm at every start (in the background, never waited on), shown in
2
2
  // the status bar, installed with /update the way HeartCode was installed. A git checkout (npm link)
3
3
  // isn't npm-installed over: it's told to git pull.
4
4
  import fs from 'node:fs'
@@ -7,7 +7,6 @@ import { fileURLToPath } from 'node:url'
7
7
  import { HOME, VERSION, readJson, writeJson } from './config.js'
8
8
 
9
9
  const FILE = path.join(HOME, 'update-check.json')
10
- const DAY = 24 * 60 * 60 * 1000
11
10
  const PKG = fileURLToPath(new URL('..', import.meta.url))
12
11
 
13
12
  // "0.1.38" > "0.1.37": numbers compared part by part (a pre-release tag isn't offered)
@@ -17,18 +16,16 @@ export const newer = (a, b) => {
17
16
  return false
18
17
  }
19
18
 
20
- // { current, latest, newer }, or null when npm can't be reached. force: ask now, not from the day's answer.
21
- export async function checkUpdate({ force = false } = {}) {
22
- const was = readJson(FILE, {})
23
- let latest = was.latest
24
- if (force || !latest || Date.now() - (was.checked ?? 0) > DAY) {
25
- try {
26
- const r = await fetch('https://registry.npmjs.org/heartcode/latest', { signal: AbortSignal.timeout(8000) })
27
- latest = (await r.json()).version
28
- writeJson(FILE, { checked: Date.now(), latest })
29
- } catch {
30
- if (!latest) return null
31
- }
19
+ // { current, latest, newer }: npm asked now (its answer kept for the settings page); npm out of
20
+ // reach, its last answer; null when there's none.
21
+ export async function checkUpdate() {
22
+ let latest = readJson(FILE, {}).latest
23
+ try {
24
+ const r = await fetch('https://registry.npmjs.org/heartcode/latest', { signal: AbortSignal.timeout(8000) })
25
+ latest = (await r.json()).version
26
+ writeJson(FILE, { checked: Date.now(), latest })
27
+ } catch {
28
+ if (!latest) return null
32
29
  }
33
30
  return { current: VERSION, latest, newer: Boolean(latest) && newer(latest, VERSION) }
34
31
  }