heartcode 0.1.40 → 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/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,12 +114,13 @@ 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).
120
121
  const request = (extra) => prompt('compact/summarize', { conversation: cut(), focus }) + extra
121
122
  const send = (extra) =>
122
- client.chat({ messages: strat.mergeSystem ? [{ role: 'user', content: `${prompt('compact/summarizer')}\n\n${request(extra)}` }] : [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request(extra) }] }, { signal })
123
+ client.chat({ messages: [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request(extra) }] }, { signal })
123
124
  const ask = (extra = '') => send(extra)
124
125
  let summary = notSummary((await ask()).content)
125
126
  if (!summary) {
@@ -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)
@@ -358,7 +384,7 @@ export class Session {
358
384
  const room = Math.floor((strat.context * 0.6 * 3.5) / (strat.ratio ?? 1))
359
385
  const text = conversation.length > room ? `[… the earliest part is cut]\n${conversation.slice(-room)}` : conversation
360
386
  const request = prompt('compact/branch-summarize', { conversation: text, files: files.join(', ') })
361
- const messages = strat.mergeSystem ? [{ role: 'user', content: `${prompt('compact/summarizer')}\n\n${request}` }] : [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request }]
387
+ const messages = [{ role: 'system', content: prompt('compact/summarizer') }, { role: 'user', content: request }]
362
388
  const summary = notSummary((await client.chat({ messages }, { signal })).content)
363
389
  if (!summary) throw new Error('the model did not write a summary')
364
390
  return summary
@@ -730,8 +756,8 @@ async function runNative(s, task, images, signal) {
730
756
  // Unchanged, it stays the same text, so a provider's prompt cache still holds.
731
757
  const sys = SYSTEM(s)
732
758
  if (!s.messages) {
733
- s.messages = strat.mergeSystem ? [{ role: 'user', content: sys }, { role: 'assistant', content: prompt('agent/system-acknowledged') }] : [{ role: 'system', content: sys }]
734
- } else if (s.messages[0]?.content !== sys && (s.messages[0]?.role === 'system' || strat.mergeSystem)) {
759
+ s.messages = [{ role: 'system', content: sys }]
760
+ } else if (s.messages[0]?.content !== sys && s.messages[0]?.role === 'system') {
735
761
  s.messages[0] = { ...s.messages[0], content: sys }
736
762
  }
737
763
  if (s.chat.branchNote && !s.isSub) {
@@ -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(
@@ -859,15 +890,15 @@ async function runNative(s, task, images, signal) {
859
890
  }
860
891
  // the model answering can change mid-message (your model list): the system prompt follows it
861
892
  const now = SYSTEM(s)
862
- if (s.messages[0]?.content !== now && (s.messages[0]?.role === 'system' || strat.mergeSystem)) s.messages[0] = { ...s.messages[0], content: now }
893
+ if (s.messages[0]?.content !== now && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: now }
863
894
  pairTools(s.messages)
864
895
  ui.spinner('thinking')
865
896
  const out = ui.response(client.model) // named: helpers think too (theirs are named in helperUI)
866
- const stream = strat.toolsStream
897
+ const stream = strat.stream
867
898
  // A long tool call (a whole file) streams in silently: say what's being written.
868
899
  const onToolDelta = (name, args) => ui.spinner(`${name === 'run_command' ? 'preparing a command' : `writing ${/"path"\s*:\s*"([^"]+)"/.exec(args)?.[1] ?? name}`} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
869
900
  // the prompts or HEARTCODE.md changed meanwhile (applySettings): the system prompt again, now
870
- if (s.refreshSystem && (s.messages[0]?.role === 'system' || strat.mergeSystem)) s.messages[0] = { ...s.messages[0], content: SYSTEM(s) }
901
+ if (s.refreshSystem && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: SYSTEM(s) }
871
902
  s.refreshSystem = false
872
903
  let res
873
904
  try {
@@ -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.
@@ -1507,8 +1547,7 @@ export function contextReport(s) {
1507
1547
  msgs.forEach((m, i) => {
1508
1548
  const n = Math.round(estMessages([m]) * ratio)
1509
1549
  const ago = msgs.length - 1 - i
1510
- if (i === 0 && (m.role === 'system' || s.strat?.mergeSystem)) return void (parts.system += n)
1511
- if (i === 1 && s.strat?.mergeSystem && m.role === 'assistant') return void (parts.system += n)
1550
+ if (i === 0 && m.role === 'system') return void (parts.system += n)
1512
1551
  if (m.role === 'tool') {
1513
1552
  const old = typeof m.content === 'string' && /^\[older output/.test(m.content)
1514
1553
  old ? (parts.pointers += n, cut++) : (parts.results += n, whole++)
@@ -38,8 +38,8 @@ export function capabilities(cfg = {}) {
38
38
  const npx = onPath('npx')
39
39
  caps.push({
40
40
  id: 'browser',
41
- name: 'Browser preview & UI review',
42
- what: 'HeartCode opens pages it builds in a real browser, reads the console and takes screenshots to check them.',
41
+ name: 'Browser',
42
+ what: 'The browser tools: the model opens a page in a real browser, uses it, reads the console and takes screenshots.',
43
43
  ok: chrome && npx,
44
44
  need: !npx ? 'Node.js' : !chrome ? 'Google Chrome' : '',
45
45
  })
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/guided.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Guided mode, for models without (reliable) tool calls. HeartCode drives the
2
2
  // task as a series of single questions; every answer has one trivial shape
3
3
  // (a number, a path, or "the whole reply is code") and is checked against
4
- // reality before use. With constrained output, the server enforces the shape.
4
+ // reality before use.
5
5
  import fs from 'node:fs'
6
6
  import { log } from './log.js'
7
7
  import { prompt, userInstructions } from './prompts.js'
@@ -39,7 +39,7 @@ export function nextActions(st) {
39
39
  return [...new Set([...first, ...ACTIONS.map(([n]) => n)])].filter((n) => n !== 'delegate' || st.canDelegate)
40
40
  }
41
41
 
42
- // A reply may be plain text or (when enforced) JSON like {"path": "a.js"}.
42
+ // A reply may be plain text or JSON like {"path": "a.js"}.
43
43
  export function answerText(reply) {
44
44
  const t = String(reply).trim()
45
45
  if (t.startsWith('{')) {
@@ -172,8 +172,7 @@ class Guided {
172
172
  }
173
173
 
174
174
  async yesNo(question, fallback) {
175
- const schema = { type: 'object', properties: { answer: { type: 'string', enum: ['yes', 'no'] } }, required: ['answer'], additionalProperties: false }
176
- const res = await this.query(prompt('guided/yes-no', { question }), { room: 20, schema, oneLine: true })
175
+ const res = await this.query(prompt('guided/yes-no', { question }), { room: 20, oneLine: true })
177
176
  const m = /\b(yes|no)\b/i.exec(answerText(res.content))
178
177
  return m ? m[1].toLowerCase() === 'yes' : fallback
179
178
  }
@@ -229,24 +228,21 @@ class Guided {
229
228
  return this.ask1(question, opts)
230
229
  }
231
230
 
232
- async ask1(question, { room = 32, schema, oneLine, onToken, answer, skipKey } = {}, tries = 0) {
231
+ async ask1(question, { room = 32, oneLine, onToken, answer, skipKey } = {}, tries = 0) {
233
232
  const { client, strat } = this.s
234
233
  const think = strat.thinking ? 4096 : 0
235
234
  const user = `${this.context(est(question) + room + think + tries * 600, skipKey)}\n\n${question}`
236
235
  this.instructions ??= userInstructions(this.s.root)
237
236
  const system = [prompt('guided/system'), this.instructions && prompt('agent/instructions', { instructions: this.instructions }), this.s.appendSystem].filter(Boolean).join('\n\n')
238
- const messages = strat.mergeSystem
239
- ? [{ role: 'user', content: `${system}\n\n${user}` }]
240
- : [
241
- { role: 'system', content: system },
242
- { role: 'user', content: user },
243
- ]
237
+ const messages = [
238
+ { role: 'system', content: system },
239
+ { role: 'user', content: user },
240
+ ]
244
241
  const out = this.ui.response()
245
242
  if (answer) onToken = out.text
246
243
  const stream = Boolean(strat.stream && (onToken || strat.thinking))
247
244
  const body = { messages, temperature: 0, stream } // no max_tokens: the model decides how long
248
- if (schema && strat.enforce) body.response_format = { type: 'json_schema', json_schema: { name: 'answer', strict: true, schema } }
249
- else if (oneLine && strat.stop) body.stop = ['\n\n']
245
+ if (oneLine && strat.stop) body.stop = ['\n\n']
250
246
  const res = await client.chat(body, { signal: this.signal, onToken, onReasoning: out.think })
251
247
  if (!stream) out.think(res.reasoning)
252
248
  if (answer && !stream) out.text(res.content)
@@ -331,9 +327,8 @@ class Guided {
331
327
  const names = nextActions(this.st)
332
328
  const menu = names.map((n, i) => `${i + 1}. ${n} - ${DESC[n]}`).join('\n')
333
329
  let q = prompt('guided/next-action', { menu })
334
- const schema = { type: 'object', properties: { choice: { type: 'integer', enum: names.map((_, i) => i + 1) } }, required: ['choice'], additionalProperties: false }
335
330
  for (let i = 0; i < 2; i++) {
336
- const res = await this.query(q, { room: 16, schema, oneLine: true })
331
+ const res = await this.query(q, { room: 16, oneLine: true })
337
332
  const a = parsePick(res.content, names)
338
333
  if (a) return a
339
334
  q += '\n\n' + prompt('guided/next-action-retry', { reply: clip(res.content, 40), count: names.length })
@@ -346,11 +341,9 @@ class Guided {
346
341
  this.note(null, 'note', prompt('guided/note-no-files'))
347
342
  return null
348
343
  }
349
- const schema =
350
- candidates.length <= 300 ? { type: 'object', properties: { path: { type: 'string', enum: candidates } }, required: ['path'], additionalProperties: false } : undefined
351
344
  let q = prompt('guided/pick-file', { question })
352
345
  for (let i = 0; i < 2; i++) {
353
- const res = await this.query(q, { room: 60, schema, oneLine: true })
346
+ const res = await this.query(q, { room: 60, oneLine: true })
354
347
  const said = answerText(res.content)
355
348
  const f = matchFile(candidates, said)
356
349
  if (f) return f
@@ -387,7 +380,7 @@ class Guided {
387
380
  const old = fs.readFileSync(resolveIn(this.s.root, f), 'utf8')
388
381
  this.ui.step('edit', f)
389
382
  let next = null
390
- if (this.s.strat.edits === 'search_replace') next = await this.editBlocks(f, old)
383
+ next = await this.editBlocks(f, old)
391
384
  if (next === null) next = await this.editRewrite(f, old)
392
385
  if (next === null) return `edit:${f}`
393
386
  const lost = lostNames(old, next, this.task)
@@ -443,11 +436,9 @@ class Guided {
443
436
  win = focusWindow(lines, answerText(res.content), room) ?? [0, lines.length]
444
437
  }
445
438
  const view = clip(numberLines(lines.slice(win[0], win[1]), win[0] + 1), room)
446
- const schema = { type: 'object', properties: { start: { type: 'integer' }, end: { type: 'integer' } }, required: ['start', 'end'], additionalProperties: false }
447
439
  const part = win[0] > 0 || win[1] < lines.length ? ` (lines ${win[0] + 1}-${win[1]} of ${lines.length})` : ''
448
440
  const rres = await this.query(prompt('guided/pick-range', { file: f, part, view: fence(view) }), {
449
441
  room: 20,
450
- schema,
451
442
  oneLine: true,
452
443
  skipKey,
453
444
  })