heartcode 0.1.27 → 0.1.32

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.
@@ -0,0 +1,105 @@
1
+ // Commands that keep running (a dev server, a watcher, a long build): run_command with background
2
+ // true starts one and answers after a few seconds with what it printed so far; the background tool
3
+ // (and /background) reads what it printed since, lists them, stops one. Each runs in its own process
4
+ // group, its output going to a file; all of them are stopped when HeartCode exits.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { spawn } from 'node:child_process'
8
+ import { HOME } from './config.js'
9
+ import { log } from './log.js'
10
+
11
+ const DIR = path.join(HOME, 'outputs', 'background')
12
+ const jobs = new Map() // id → { id, command, root, pid, file, started, code, read, exited }
13
+ let made = 0
14
+
15
+ const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r(?!\n)/g, '\n')
16
+ const group = process.platform !== 'win32'
17
+ const kill = (job, sig) => {
18
+ try {
19
+ group ? process.kill(-job.pid, sig) : process.kill(job.pid, sig)
20
+ return true
21
+ } catch {
22
+ return false
23
+ }
24
+ }
25
+
26
+ // Started, and after `wait` ms: { job, output } (what it printed so far).
27
+ export async function startJob(root, command, { wait = 3000 } = {}) {
28
+ fs.mkdirSync(DIR, { recursive: true })
29
+ const id = ++made
30
+ const file = path.join(DIR, `${process.pid}-${id}.log`)
31
+ const fd = fs.openSync(file, 'w')
32
+ const child = spawn(command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' } })
33
+ fs.closeSync(fd)
34
+ const job = { id, command, root, pid: child.pid, file, started: Date.now(), code: null, read: 0, exited: false, told: false }
35
+ jobs.set(id, job)
36
+ child.on('error', (e) => fs.appendFileSync(file, `\n${e.message}\n`))
37
+ child.on('exit', (code, sig) => Object.assign(job, { code: code ?? sig, exited: true, ended: Date.now() }))
38
+ child.unref()
39
+ log('background', `#${id} started: ${command} (pid ${child.pid})`)
40
+ await new Promise((r) => setTimeout(r, wait))
41
+ return { job, output: newOutput(job) }
42
+ }
43
+
44
+ // What it printed since the last look (the last `most` characters of it).
45
+ export function newOutput(job, most = 4000) {
46
+ let text = ''
47
+ try {
48
+ const all = fs.readFileSync(job.file)
49
+ text = plain(all.subarray(job.read).toString('utf8'))
50
+ job.read = all.length
51
+ } catch {}
52
+ return text.length > most ? `…${text.slice(-most)}` : text
53
+ }
54
+
55
+ // Its last `n` lines, read from the end of its file (a long log isn't read whole).
56
+ export function tailLines(job, n) {
57
+ let text = ''
58
+ try {
59
+ const fd = fs.openSync(job.file, 'r')
60
+ const size = fs.fstatSync(fd).size
61
+ const len = Math.min(size, 64 * 1024)
62
+ const buf = Buffer.alloc(len)
63
+ fs.readSync(fd, buf, 0, len, size - len)
64
+ fs.closeSync(fd)
65
+ text = plain(buf.toString('utf8'))
66
+ } catch {}
67
+ return text.split('\n').filter((l, i, all) => l.trim() || i < all.length - 1).slice(-n)
68
+ }
69
+
70
+ export const listJobs = (root) => [...jobs.values()].filter((j) => !root || j.root === root)
71
+ export const getJob = (id) => jobs.get(Number(String(id).replace(/^#/, '')))
72
+ export const runningJobs = (root) => listJobs(root).filter((j) => !j.exited)
73
+
74
+ export function stopJob(job) {
75
+ if (job.exited) return false
76
+ kill(job, 'SIGTERM')
77
+ setTimeout(() => kill(job, 'SIGKILL'), 2000).unref()
78
+ log('background', `#${job.id} stopped: ${job.command}`)
79
+ return true
80
+ }
81
+
82
+ // Stopped (if it still runs) and taken off the list; its log file stays.
83
+ export function removeJob(job) {
84
+ stopJob(job)
85
+ jobs.delete(job.id)
86
+ log('background', `#${job.id} removed: ${job.command}`)
87
+ }
88
+
89
+ // The ones that ended since they were last told about (for the model's next step).
90
+ export function newlyEnded(root) {
91
+ const out = listJobs(root).filter((j) => j.exited && !j.told)
92
+ for (const j of out) j.told = true
93
+ return out
94
+ }
95
+
96
+ export const jobLine = (j) => `#${j.id} ${j.command} · ${j.exited ? `exited with ${j.code}` : 'running'} · ${ago(j)} · output: ${j.file}`
97
+ export const ago = (j) => {
98
+ const s = Math.round(((j.ended ?? Date.now()) - j.started) / 1000)
99
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : `${Math.round(s / 360) / 10}h`
100
+ }
101
+
102
+ // Nothing outlives HeartCode.
103
+ process.on('exit', () => {
104
+ for (const j of jobs.values()) if (!j.exited) kill(j, 'SIGTERM')
105
+ })
package/src/client.js CHANGED
@@ -198,6 +198,17 @@ export class Client {
198
198
  log('rotate', `${why} → ${r.list[r.at].provider} · ${r.list[r.at].model}`)
199
199
  this.#use(r.list[r.at])
200
200
  }
201
+ // Jump straight to a particular model in the list — the caller found it has room the current one
202
+ // doesn't (the conversation outgrew this model's window), so move there instead of compacting.
203
+ // No-op (false) without a list, or if it's not in the list or already the one in use.
204
+ switchTo(target, why) {
205
+ const r = this.rotation
206
+ if (!r) return false
207
+ const i = r.list.indexOf(target)
208
+ if (i < 0 || i === r.at) return false
209
+ this.#next(why, () => i)
210
+ return true
211
+ }
201
212
  // Which model of the list to go on to after this one failed, for one request (tried: the places
202
213
  // tried, down: the providers that answered with an error, 400 or above). A provider that answered
203
214
  // with an error isn't asked again through its next model: the next one is from another provider.
@@ -455,8 +466,8 @@ export class Client {
455
466
  } else this.onRetry(e, 0, attempt + 1, this.target)
456
467
  continue
457
468
  }
458
- // a server error or no connection, again and again (not a rate limit, which is waited out)
459
- if (e.status !== 429 && tries >= 8) throw e
469
+ // a server error or no connection, again and again: waited out like a rate limit (the wait
470
+ // grows to a minute), until it comes back or Esc — never given up on
460
471
  const wait = Math.min(Number(e.retryAfter) * 1000 || this.retryBase * 2 ** (tries - 1), 60_000)
461
472
  log('retry', `attempt ${attempt + 1} failed, waiting ${wait}ms: ${e.message}`)
462
473
  this.onRetry(e, wait, attempt + 1)
@@ -567,7 +578,7 @@ export class Client {
567
578
  // Speed counts from the first streamed token (or the request, if not streaming) to the end.
568
579
  const count = (r) => {
569
580
  if (r.usage?.prompt_tokens) this.onUsage?.(r.usage.prompt_tokens, estMessages(req.messages) + est(JSON.stringify(req.tools ?? '')))
570
- this.lastTokens = r.usage?.total_tokens || estMessages(req.messages) + est(r.content + r.reasoning)
581
+ if ((this.purpose ?? 'chat') === 'chat') this.lastTokens = r.usage?.total_tokens || estMessages(req.messages) + est(r.content + r.reasoning) // the conversation's size: not a side request's (a review, the wrap-up, a lesson)
571
582
  const out = r.usage?.completion_tokens || est(r.content + r.reasoning + r.toolCalls.map((t) => t.function.arguments).join(''))
572
583
  this.onSpend?.(r.usage?.prompt_tokens || r.usage?.completion_tokens ? r.usage : { prompt_tokens: estMessages(req.messages), completion_tokens: out, estimated: true }) // usage and cost (usage.js)
573
584
  const ms = Date.now() - (firstAt ?? sent)
package/src/config.js CHANGED
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'
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
8
 
9
- const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays']
9
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search']
10
10
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
11
11
 
12
12
  export function readJson(file, fallback) {
package/src/guided.js CHANGED
@@ -289,8 +289,13 @@ class Guided {
289
289
  repeats = sig === last ? repeats + 1 : 0
290
290
  last = sig
291
291
  if (repeats >= 2) {
292
- this.ui.warn(`stopped: ${this.s.client.model} did the same thing three times in a row`)
293
- break
292
+ // the next of your models carries on; with none, it goes on being told (only Esc stops it)
293
+ const was = this.s.client.model
294
+ if (this.s.client.moveOn?.(`${was} did the same thing three times in a row`)) this.ui.warn(`${was} did the same thing three times in a row; handing over to ${this.s.client.model}`)
295
+ else this.ui.warn(`${was} did the same thing three times in a row — it carries on, told so; Esc stops it`)
296
+ this.note(null, 'warning', prompt('guided/note-repeated'))
297
+ repeats = 0
298
+ continue
294
299
  }
295
300
  if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
296
301
  }
package/src/headless.js CHANGED
@@ -12,11 +12,11 @@
12
12
  // told to the model. Logs and warnings go to stderr (and HEART_LOG), never stdout.
13
13
  import readline from 'node:readline'
14
14
  import { log } from './log.js'
15
- import { clip, TOOL_DEFS, extraTools, loadMcpTools, failed as toolFailed } from './tools.js'
15
+ import { clip, TOOL_DEFS, extraTools, loadMcpTools, mcpName, failed as toolFailed } from './tools.js'
16
16
  import { allowed } from './agent.js'
17
17
 
18
18
  // Claude Code's tool names → HeartCode's (for --allowedTools / --disallowedTools).
19
- const CLAUDE_TOOLS = { Read: 'read_file', Grep: 'search', Glob: 'list_files', LS: 'list_files', Edit: 'edit_file', MultiEdit: 'edit_file', Write: 'write_file', NotebookEdit: 'edit_file', Bash: 'run_command' }
19
+ const CLAUDE_TOOLS = { Read: 'read_file', Grep: 'search', Glob: 'list_files', LS: 'list_files', Edit: 'edit_file', MultiEdit: 'edit_file', Write: 'write_file', NotebookEdit: 'edit_file', Bash: 'run_command', BashOutput: 'background', KillShell: 'background', KillBash: 'background' }
20
20
  export function toolNames(list) {
21
21
  const names = list.flatMap((x) => String(x).split(/[,\s]+/)).filter(Boolean).map((t) => t.replace(/\(.*$/, '')) // ponytail: "Bash(git:*)" allows every command, not just git
22
22
  return new Set(names.map((t) => CLAUDE_TOOLS[t] ?? t)) // mcp__server__tool and mcp__server as they are (tools.js allowed)
@@ -119,6 +119,10 @@ export async function runHeadless(app, opts) {
119
119
  return e
120
120
  }
121
121
 
122
+ // An MCP call goes out as Claude Code sends one: the tool by its own name (mcp__server__tool) with
123
+ // its own arguments, not HeartCode's one mcp tool around them (a program reading it, Nibedita,
124
+ // knows its tools by those names).
125
+ const asClaude = (name, input) => (name === 'mcp' && input?.server && input?.tool ? { name: mcpName(String(input.server), String(input.tool)), input: input.arguments ?? {} } : { name, input })
122
126
  let said = false // the model's text was already sent as an assistant message
123
127
  if (out === 'stream-json') {
124
128
  s.onEvent = (e) => {
@@ -126,7 +130,7 @@ export async function runHeadless(app, opts) {
126
130
  const content = [
127
131
  ...(e.reasoning ? [{ type: 'thinking', thinking: e.reasoning }] : []),
128
132
  ...(e.content ? [{ type: 'text', text: e.content }] : []),
129
- ...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, name: t.function.name, input: parseArgs(t.function.arguments) })),
133
+ ...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, ...asClaude(t.function.name, parseArgs(t.function.arguments)) })),
130
134
  ]
131
135
  if (e.content && !e.parent) said = true
132
136
  // a helper's (agent) steps too, as Claude Code sends a subagent's: parent_tool_use_id is its agent call
@@ -136,7 +140,8 @@ export async function runHeadless(app, opts) {
136
140
  }
137
141
  }
138
142
  if (s.strat.actions === 'tools' && s.mcp?.names.length) await loadMcpTools(s) // their tools are in the list, as in Claude Code's
139
- const tools = s.strat.actions === 'tools' ? [...TOOL_DEFS, ...extraTools(s)].map((f) => f.name).filter((n) => allowed(s, n)) : []
143
+ // each MCP tool by its own name (mcp__server__tool), as Claude Code lists them; the model reaches them through its one mcp tool
144
+ const tools = s.strat.actions === 'tools' ? [...[...TOOL_DEFS, ...extraTools(s)].map((f) => f.name), ...(s.mcpDirect?.keys() ?? [])].filter((n) => allowed(s, n)) : []
140
145
  emit({ type: 'system', subtype: 'init', session_id, model, cwd: app.root, tools, mcp_servers: app.mcp.names.map((name) => ({ name, status: s.mcpCatalog?.has(name) ? 'connected' : 'pending' })), permissionMode: app.ui.permission, apiKeySource: 'none' })
141
146
  }
142
147
 
@@ -175,6 +180,7 @@ export async function runHeadless(app, opts) {
175
180
  } else if (out === 'json') emit(result)
176
181
  else if (error) process.stderr.write(`heartcode: ${error}\n`)
177
182
  else process.stdout.write(answer.trim() + '\n')
183
+ await s.wrapping // the wrap-up (notes, research, cleanup) after the result is out, before it exits
178
184
  return !error
179
185
  }
180
186
 
package/src/memory.js CHANGED
@@ -26,7 +26,11 @@ export const fullSlug = (s) =>
26
26
  .replace(/\.md$/, '')
27
27
  .replace(/[^a-z0-9]+/g, '-')
28
28
  .replace(/^-+|-+$/g, '')
29
- export const slug = (s) => fullSlug(s).slice(0, 60) || 'note'
29
+ // cut at a word's end, not in the middle of one ("…-and-use-an-abso")
30
+ export const slug = (s) => {
31
+ const f = fullSlug(s)
32
+ return (f.length <= 60 ? f : f.slice(0, 61).replace(/-[^-]*$/, '').slice(0, 60)) || 'note'
33
+ }
30
34
 
31
35
  // One folder of notes.
32
36
  class Notes {
@@ -215,7 +219,7 @@ const tagList = (v) => (Array.isArray(v) ? v : String(v ?? '').split(/[,\s#]+/))
215
219
 
216
220
  // Words worth matching on: lowercased, without short or very common words, plural/-ing cut off.
217
221
  const STOP = new Set('the and for with this that from have what when where which into your you our are was were can will should could would about there their them then than just also only some more most very please make like want need does doing done how why who its it\'s use using'.split(' '))
218
- function keywords(text) {
222
+ export function keywords(text) {
219
223
  return String(text)
220
224
  .toLowerCase()
221
225
  .split(/[^a-z0-9]+/)
@@ -0,0 +1,142 @@
1
+ // Research: every web page and search HeartCode reads for a project, kept in
2
+ // <project>/.heartcode/research/ as Markdown (one file per page, the whole page), so nothing it looked
3
+ // up is lost: helpers' pages too. The same URL always maps to the same file (fetched again: replaced).
4
+ // ---
5
+ // url: https://…
6
+ // title: …
7
+ // fetched: 2026-10-31
8
+ // query: what it was looking for
9
+ // used_for: what it turned out to be used for (set when the task wraps up)
10
+ // ---
11
+ // # Title
12
+ // the page as Markdown
13
+ // INDEX.md lists them for people (and Obsidian); the model is given matching titles with each message
14
+ // and reads a file when it needs the detail. The folder ignores itself in git (raw pages can be big;
15
+ // the notes they lead to in .heartcode/memory are what's worth committing).
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { createHash } from 'node:crypto'
19
+ import { keywords } from './memory.js'
20
+
21
+ export const researchDir = (root) => path.join(root, '.heartcode', 'research')
22
+ const slugOf = (s, n) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, n).replace(/-+$/, '')
23
+ const hash = (s) => createHash('sha256').update(String(s)).digest('hex').slice(0, 8)
24
+ const today = () => new Date().toISOString().slice(0, 10)
25
+ const oneLine = (s) => String(s ?? '').replace(/\s+/g, ' ').trim()
26
+
27
+ // The file a page is kept in: its address, readable ("react.dev--learn-start-a-new-react-project.md").
28
+ export function pageFile(url) {
29
+ let host = 'page'
30
+ let rest = String(url)
31
+ try {
32
+ const u = new URL(url)
33
+ host = u.hostname.replace(/^www\./, '')
34
+ rest = u.pathname + u.search
35
+ } catch {}
36
+ const name = `${host.toLowerCase().replace(/[^a-z0-9.]+/g, '-').slice(0, 60) || 'page'}--${slugOf(rest, 200) || 'index'}`
37
+ return `${name.length > 110 ? `${name.slice(0, 100).replace(/-+$/, '')}-${hash(url)}` : name}.md`
38
+ }
39
+ const searchFile = (query) => `search--${slugOf(query, 90) || hash(query)}.md`
40
+
41
+ function write(root, file, meta, body) {
42
+ const dir = researchDir(root)
43
+ fs.mkdirSync(dir, { recursive: true })
44
+ const ignore = path.join(dir, '.gitignore')
45
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, '# HeartCode research: raw pages, kept out of git (the notes in ../memory are what to commit)\n*\n')
46
+ const head = Object.entries(meta)
47
+ .filter(([, v]) => v !== undefined && v !== '')
48
+ .map(([k, v]) => `${k}: ${oneLine(v)}`)
49
+ fs.writeFileSync(path.join(dir, file), `---\n${head.join('\n')}\n---\n\n${String(body).trim()}\n`)
50
+ rebuildIndex(root)
51
+ return { file: path.relative(root, path.join(dir, file)), bodyLine: head.length + 4 } // bodyLine: the page's first line in the file
52
+ }
53
+
54
+ // A fetched page (text: as Markdown). Returns { file (relative to the project), bodyLine }.
55
+ export function savePage(root, { url, title, text, query }) {
56
+ const file = pageFile(url)
57
+ const was = read(root, file)
58
+ return write(root, file, { url, title: title || url, fetched: today(), query: query || was?.query, used_for: was?.used_for }, text)
59
+ }
60
+
61
+ // A search's results (text: as the model was given them).
62
+ export function saveSearch(root, query, text) {
63
+ return write(root, searchFile(query), { kind: 'search', title: `Search: ${query}`, query, fetched: today() }, text)
64
+ }
65
+
66
+ function parse(root, name) {
67
+ const abs = path.join(researchDir(root), name)
68
+ let text
69
+ try {
70
+ text = fs.readFileSync(abs, 'utf8')
71
+ } catch {
72
+ return null
73
+ }
74
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text)
75
+ const meta = Object.fromEntries((m?.[1] ?? '').split('\n').map((l) => /^(\w+):\s*(.*)$/.exec(l.trim())).filter(Boolean).map(([, k, v]) => [k, v.trim()]))
76
+ return { ...meta, name, file: path.relative(root, abs), kind: meta.kind || 'page', size: text.length }
77
+ }
78
+ const read = (root, name) => parse(root, name)
79
+
80
+ // Every saved page and search: { name, file, url, title, fetched, query, used_for, kind, size }, newest first.
81
+ export function listResearch(root) {
82
+ let names = []
83
+ try {
84
+ names = fs.readdirSync(researchDir(root)).filter((f) => f.endsWith('.md') && f !== 'INDEX.md')
85
+ } catch {}
86
+ return names
87
+ .map((n) => parse(root, n))
88
+ .filter(Boolean)
89
+ .sort((a, b) => String(b.fetched).localeCompare(String(a.fetched)) || a.name.localeCompare(b.name))
90
+ }
91
+
92
+ // Saved research that matches a text (a task, a search query): pages first, the best matches first.
93
+ // A word in the title, the query that found it or what it was used for counts most; in the address, less.
94
+ export function findResearch(root, text, max = 6) {
95
+ const words = new Set(keywords(text))
96
+ if (!words.size) return []
97
+ return listResearch(root)
98
+ .map((r) => {
99
+ let score = 0
100
+ for (const w of new Set([...keywords(r.title), ...keywords(r.query), ...keywords(r.used_for)])) if (words.has(w)) score += 2
101
+ for (const w of new Set(keywords(r.url))) if (words.has(w)) score += 1
102
+ return { r, score: score - (r.kind === 'search' ? 1 : 0) }
103
+ })
104
+ .filter((x) => x.score >= 3)
105
+ .sort((a, b) => b.score - a.score)
106
+ .slice(0, max)
107
+ .map((x) => x.r)
108
+ }
109
+
110
+ // The file a model names: its name, or its path in the project ("…/research/x.md").
111
+ const nameOf = (file) => path.basename(String(file ?? '').trim())
112
+
113
+ // Kept: what it was used for goes in its header (and the index).
114
+ export function markUsed(root, file, usedFor) {
115
+ const r = read(root, nameOf(file))
116
+ if (!r) return false
117
+ const abs = path.join(researchDir(root), r.name)
118
+ const text = fs.readFileSync(abs, 'utf8')
119
+ const body = text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '')
120
+ const { name, file: _f, size, ...meta } = r
121
+ write(root, r.name, { ...meta, used_for: usedFor || meta.used_for || 'yes' }, body)
122
+ return true
123
+ }
124
+
125
+ export function removeResearch(root, file) {
126
+ const r = read(root, nameOf(file))
127
+ if (!r) return false
128
+ fs.rmSync(path.join(researchDir(root), r.name), { force: true })
129
+ rebuildIndex(root)
130
+ return true
131
+ }
132
+
133
+ function rebuildIndex(root) {
134
+ const all = listResearch(root)
135
+ const line = (r) => `- ${r.fetched ?? ''} · [${r.title || r.name}](${r.name})${r.url ? ` · ${r.url}` : ''}${r.used_for ? ` · used for: ${r.used_for}` : ''}`
136
+ const pages = all.filter((r) => r.kind !== 'search')
137
+ const searches = all.filter((r) => r.kind === 'search')
138
+ fs.writeFileSync(
139
+ path.join(researchDir(root), 'INDEX.md'),
140
+ `# Research\n\nWhat HeartCode read on the web for this project, newest first. Each page is kept whole in its file; the notes it led to are in ../memory.\n\n## Pages\n\n${pages.map(line).join('\n') || '(none yet)'}\n\n## Searches\n\n${searches.map(line).join('\n') || '(none yet)'}\n`,
141
+ )
142
+ }
package/src/sessions.js CHANGED
@@ -18,7 +18,10 @@ export function newChat(root) {
18
18
  export function saveChat(chat) {
19
19
  const file = path.join(DIR, `${chat.id}.json`)
20
20
  const first = chat.turns[0] ?? chat.branches?.[0]?.state.turns[0] // gone back to the start: its branches remain
21
- if (!first) return fs.rmSync(file, { force: true }) // nothing (left) worth keeping
21
+ if (!first) {
22
+ fs.rmSync(path.join(HOME, 'outputs', chat.id), { recursive: true, force: true }) // its saved tool output goes with it
23
+ return fs.rmSync(file, { force: true }) // nothing (left) worth keeping
24
+ }
22
25
  chat.updated = new Date().toISOString()
23
26
  chat.title = chat.name || first.task.split('\n')[0].slice(0, 80) // its name (/rename), else the first message, even after a rewind
24
27
  writeJson(file, chat)