heartcode 0.1.41 → 0.1.44

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/agent.js CHANGED
@@ -7,8 +7,7 @@ import path from 'node:path'
7
7
  import { est, estMessages, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
8
8
  import { runGuided } from './guided.js'
9
9
  import { markUsed, removeResearch, findResearch } from './research.js'
10
- import { loadRankings, rankIn } from './rankings.js'
11
- import { pickModels, byPick } from './fit.js'
10
+ import { loadRankings, rankIn, rankings } from './rankings.js'
12
11
  import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, noteNamedPaths } from './tools.js'
13
12
  import { serversNote } from './lsp.js'
14
13
  import { newlyEnded, jobLine } from './background.js'
@@ -114,6 +113,7 @@ export class Session {
114
113
  const cut = () => (conversation.length > room ? `[… the earliest part is cut]\n${conversation.slice(-room)}` : conversation)
115
114
  const before = native ? size(body) : est(conversation)
116
115
  ui.spinner(why ? `${why}: compacting the conversation` : 'compacting the conversation')
116
+ const findings = native ? await this.findings(signal) : ''
117
117
  // A model shown its own work tends to carry on with it (calling tools, or writing tool calls
118
118
  // as text) instead of summarizing: so it's told what it is, and a reply that isn't a summary
119
119
  // is asked for again once; then the compaction fails (the conversation is trimmed instead).
@@ -131,7 +131,7 @@ export class Session {
131
131
  ;(chat.snapshots ??= [])[epoch] = { messages: chat.messages, history: [...chat.history] }
132
132
  chat.sentNotes = [] // the summary replaces the messages the notes came with
133
133
  chat.epoch = epoch + 1
134
- const recap = prompt('compact/summary', { summary, requests: requestsOf(chat) })
134
+ const recap = prompt('compact/summary', { summary, findings, requests: requestsOf(chat) })
135
135
  if (native) {
136
136
  chat.messages = midTask
137
137
  ? [...head, { role: 'user', content: `${recap}\n\n${prompt('compact/continue', { task })}` }]
@@ -147,6 +147,31 @@ export class Session {
147
147
  return summary
148
148
  }
149
149
 
150
+ // Before the conversation is summarized, the model working on it writes down what it has found:
151
+ // its conclusions live in its reasoning, which the summary (written from the transcript) never
152
+ // sees, and without them it reads the same files again after every compaction. Asked as the next
153
+ // message of its own conversation with the same tools, so the provider's cache of it still holds;
154
+ // tool calls in the reply aren't run. '' when there's nothing to ask or it fails (the summary alone).
155
+ async findings(signal) {
156
+ const { chat, client, strat } = this
157
+ if (!chat.messages?.length || !this.lastTools) return ''
158
+ // already past the model's window (one step can add a lot): the request would only be refused
159
+ if (strat.context > 0 && tokensOf(chat.messages, this.lastTools.map((t) => t.function), strat.ratio ?? 1) > strat.context * 0.95) {
160
+ log('compact', 'no findings note: the conversation is already past the window')
161
+ return ''
162
+ }
163
+ try {
164
+ const r = await client.chat({ messages: [...chat.messages, { role: 'user', content: prompt('compact/findings') }], tools: this.lastTools }, { signal })
165
+ const note = String(r.content ?? '').trim()
166
+ log('compact', note ? `findings note: ${note.length} characters` : 'no findings note (the reply had no text)', note)
167
+ return note
168
+ } catch (e) {
169
+ if (e.name === 'AbortError') throw e
170
+ log('compact', `no findings note: ${e.message}`)
171
+ return ''
172
+ }
173
+ }
174
+
150
175
  // images: data: URLs from the caller (headless input), besides @shot.png in the task.
151
176
  async run(task, signal, extra = []) {
152
177
  if (!this.isSub) this.client.newMessage?.() // the model list: from #1 again (unless set to stay)
@@ -183,12 +208,16 @@ export class Session {
183
208
  else this.ui.warn(`${this.client.model} can't read images (per its probe); ignoring ${images.length} image(s)`)
184
209
  images = []
185
210
  }
186
- // "best fit": the models that suit this message most, by their strengths (your order breaks ties)
187
- if (!this.isSub && this.fitMode?.()) {
188
- const fit = await pickModels(this, text, signal, { images: images.length, size: this.messages ? size(this.messages) : 0 })
189
- if (fit && this.client.orderBy?.(fit.work)) ui.step('models', `${this.client.model}${fit.why ? ` · picked for: ${fit.why}` : ''}`)
190
- } else if (!this.isSub) this.client.orderBy?.(null) // your order (best fit was switched off)
191
- if (!this.isSub) log('rotate', `this message starts on ${this.client.provider ?? ''} · ${this.client.model}${this.client.rotation ? ` (#${this.client.rotation.at + 1} of ${this.client.rotation.list.length}${this.fitMode?.() ? ', best fit' : ', your order'})` : ''}`)
211
+ // An orchestrator: the message starts on one of the models picked for it, which answers at once
212
+ // or hands the work to your other models (it decides) — only when there are others to hand to.
213
+ if (!this.isSub) {
214
+ const lead = this.fitMode?.() ? (this.orchestrators?.() ?? []) : []
215
+ this.client.orderBy?.(lead.length ? lead.map((t) => `${t.provider} ${t.model}`) : null)
216
+ this.orchestrating = lead.length > 0 // (then team() leaves the orchestrators out)
217
+ if (this.orchestrating && !this.team?.().length) this.orchestrating = false // no one to hand to: it does the work itself
218
+ if (this.orchestrating) rankings().catch(() => {}) // their places, for its list of models: fetched behind (once a week), never waited for
219
+ log('rotate', `this message starts on ${this.client.provider ?? ''} · ${this.client.model}${this.client.rotation ? ` (#${this.client.rotation.at + 1} of ${this.client.rotation.list.length}${this.orchestrating ? ', orchestrating' : ', your order'})` : ''}`)
220
+ }
192
221
  log('task', `${text} (${this.strat.actions} mode, ${images.length} image(s))`)
193
222
  const answer = this.strat.actions === 'tools' ? await runNative(this, text, images, signal) : await runGuided(this, text, images, signal)
194
223
  log('answer', answer) // the conversation's log
@@ -216,10 +245,10 @@ export class Session {
216
245
  }
217
246
  const name = (t) => `${t.provider} ${t.model}`
218
247
  const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
219
- const all = [self, ...(this.team?.() ?? [])]
248
+ const all = [...(this.orchestrating ? [] : [self]), ...(this.team?.() ?? [])] // an orchestrator hands work out, never to itself
220
249
  const want = String(args.model ?? '').trim()
221
250
  // only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
222
- const first = !want || all.length === 1 ? self : (all.find((t) => name(t) === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`)))
251
+ const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`)))
223
252
  if (!first) return `error: no model "${want}". Yours: ${all.map(name).join(', ')}`
224
253
  // the one asked for first (if it can do the job), then the others that can: those that call
225
254
  // tools first, then the ones that failed least this session, in your list's order
@@ -521,6 +550,7 @@ const rootList = (root) => {
521
550
  }
522
551
 
523
552
  const SYSTEM = (s) => {
553
+ if (s.orchestrating) return prompt('agent/orchestrator', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), ...teamOf(s) })
524
554
  const instructions = userInstructions(s.root)
525
555
  return [
526
556
  prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem) }),
@@ -539,11 +569,13 @@ const SYSTEM = (s) => {
539
569
  }
540
570
 
541
571
  // Your other models and what each can do, for the agent tool's model (only when there are any): a
542
- // short line each — in best fit, with its places in the public rankings (rankings.js).
543
- const RANKED_AS = { code: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
572
+ // short line each — with an orchestrator, with its places in the public rankings (rankings.js).
573
+ const RANKED_AS = { overall: 'text:overall', code: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
544
574
  const teamPrompt = (s) => {
545
575
  const team = s.team?.() ?? []
546
- if (!team.length) return ''
576
+ return team.length ? prompt('agent/team', teamOf(s, team)) : ''
577
+ }
578
+ const teamOf = (s, team = s.team?.() ?? []) => {
547
579
  const data = s.fitMode?.() ? loadRankings() : null
548
580
  const ranks = (t) => (data ? Object.entries(RANKED_AS).map(([k, list]) => ((r) => r && `${k} #${r.rank}`)(rankIn(t.model, list, data))).filter(Boolean).join(' ') : '')
549
581
  const line = (t) => {
@@ -552,7 +584,7 @@ const teamPrompt = (s) => {
552
584
  return `- ${t.provider} ${t.model}${facts.length ? `: ${facts.join(', ')}` : ''}`
553
585
  }
554
586
  const you = [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking', ranks(s.client) && `ranked ${ranks(s.client)}`].filter(Boolean).join(', ')
555
- return prompt('agent/team', { models: team.map(line).join('\n'), you, ranked: Boolean(data) })
587
+ return { models: team.map(line).join('\n'), you, ranked: Boolean(data) }
556
588
  }
557
589
 
558
590
  const sizeOf = (m) =>
@@ -743,14 +775,15 @@ async function runNative(s, task, images, signal) {
743
775
  // window as set up, measured or learned; also when that changes mid-task, or the model list moves
744
776
  // on to a model with a smaller one), so there's room left for the reply. Its size: what the server
745
777
  // 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%.
778
+ // (the tool results, never counted smaller than estimated: they're often code), or the estimate of
779
+ // all of it when that's more (no count yet: a resumed session, just compacted). After a failed try:
780
+ // again once it has grown by another 5%.
748
781
  const used = () => {
749
782
  const ratio = strat.ratio ?? 1
750
783
  const all = tokensOf(s.messages, [...TOOL_DEFS, ...extraTools(s)], ratio)
751
784
  const k = s.counted
752
785
  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))
786
+ return Math.max(all, k.tokens + tokensOf(s.messages.slice(k.upTo), null, Math.max(1, ratio)))
754
787
  }
755
788
  const nearlyFull = () => s.autoCompact && strat.context > 0 && used() >= strat.context * COMPACT_SHARE && used() >= (s.compactFailedAt ?? 0)
756
789
  const fullness = () => `context ${Math.round((used() / strat.context) * 100)}% full (~${kTokens(used())} of ${kTokens(strat.context)})`
@@ -779,6 +812,7 @@ async function runNative(s, task, images, signal) {
779
812
  }
780
813
  // Already that long from earlier messages: switch to a roomier model, or else compact first, so the
781
814
  // new message stays word for word.
815
+ if (nearlyFull() && dropStale(s)) log('compact', 'older copies of files read again shortened first')
782
816
  if (nearlyFull() && !roomier()) {
783
817
  await s.compact({ signal, why: fullness() }).then(afterCompact, (e) => (e.name === 'AbortError' ? Promise.reject(e) : ui.warn(`could not compact: ${e.message}`)))
784
818
  }
@@ -816,6 +850,7 @@ async function runNative(s, task, images, signal) {
816
850
  if (!s.isSub) s.choicesFresh = false // a question about how to do it, this message: replaces the earlier answers (s.chat.choices)
817
851
  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
852
  s.edits = 0 // successful file edits so far this message (to tell a real fix from a lucky rerun)
853
+ 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
854
  s.acted = false // used a tool this message (so a reply that only promises more is a premature stop)
820
855
  let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
821
856
  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 +876,13 @@ async function runNative(s, task, images, signal) {
841
876
  for (let step = 0; ; step++) {
842
877
  if (step && !s.isSub) s.onTurn?.() // saved after every step: a quit, crash or kill mid-task loses nothing done so far
843
878
  const tools = toolList()
879
+ s.lastTools = tools // what the requests carry: the findings note before compacting sends the same (compact)
844
880
  if (s.maxTurns && step >= s.maxTurns) {
845
881
  ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
846
882
  throw Object.assign(new Error(`stopped after ${s.maxTurns} steps (--max-turns)`), { maxTurns: true })
847
883
  }
848
884
  // after a failed compaction, the next try waits until the conversation has grown by 5% of the window
885
+ if (nearlyFull() && dropStale(s)) log('compact', 'older copies of files read again shortened first')
849
886
  if (nearlyFull() && step !== s.compactedAt && !roomier()) {
850
887
  s.compactedAt = step
851
888
  await s.compact({ signal, midTask: true, task, why: fullness() }).then(
@@ -1048,7 +1085,7 @@ async function runNative(s, task, images, signal) {
1048
1085
  lastCall = sig
1049
1086
  if (inRow >= 3) out += `\n\n${prompt('agent/repeating', { n: inRow })}`
1050
1087
  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`)
1088
+ 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
1089
  else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
1053
1090
  else if (failed(out)) ui.result(clip(out, 120))
1054
1091
  client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
@@ -1063,6 +1100,7 @@ async function runNative(s, task, images, signal) {
1063
1100
  s.messages.push(msg)
1064
1101
  s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
1065
1102
  }
1103
+ 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
1104
  trimOldResults(s)
1067
1105
  const ended = newlyEnded(s.root) // background commands that exited meanwhile: the model hears it now
1068
1106
  if (ended.length) {
@@ -1095,7 +1133,7 @@ const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
1095
1133
  // Files only read by people (a change there needs no run to check it).
1096
1134
  const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
1097
1135
  // 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'])
1136
+ const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'])
1099
1137
  export function newGuard() {
1100
1138
  const seen = new Map() // what a call is → { out, at }
1101
1139
  let epoch = 0 // goes up with each change (an edit, a command that can change things)
@@ -1111,7 +1149,7 @@ export function newGuard() {
1111
1149
  const keyOf = (name, a) => {
1112
1150
  if (name === 'web_search') return `search: ${words(a.query)}${a.fresh ? ' (fresh)' : ''}`
1113
1151
  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}`
1152
+ if (['run_command', 'read_file', 'search', 'list_files', 'find_command', 'lsp', 'changes'].includes(name)) return `${name} ${JSON.stringify(a)} @${epoch}`
1115
1153
  return null
1116
1154
  }
1117
1155
  g.before = (name, a) => {
@@ -1324,8 +1362,7 @@ export async function review(s, task, answer, signal) {
1324
1362
  const self = { provider: s.client.provider, model: s.client.model, self: true }
1325
1363
  const fails = (t) => s.failures?.[`${t.provider} ${t.model}`] ?? 0
1326
1364
  const team = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)).sort((a, b) => fails(a) - fails(b))
1327
- const others = s.fitMode?.() && s.chat.fit?.review?.length ? byPick(team, s.chat.fit.review) : team // best fit: the best at checking code first
1328
- for (const t of [...others.slice(0, 2), self]) {
1365
+ for (const t of [...team.slice(0, 2), ...(s.orchestrating ? [] : [self])]) { // an orchestrator doesn't check the work
1329
1366
  s.ui.spinner(`${t.model} is reviewing the work`)
1330
1367
  try {
1331
1368
  const { client } = t.self ? { client: s.client } : await s.engineFor(t)
@@ -1441,8 +1478,9 @@ function callOf(messages, id) {
1441
1478
  // provider's prompt cache (the conversation's unchanged start) is broken rarely, not every step.
1442
1479
  // An older conversation's results (no file yet) are saved now, before they're cut.
1443
1480
  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))
1481
+ 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
1482
  if (long.length <= most) return
1483
+ dropStale(s) // the conversation changes here anyway: the older copies of files read again go too
1446
1484
  for (const m of long.slice(0, -keep)) {
1447
1485
  const call = callOf(s.messages, m.tool_call_id)
1448
1486
  const read = /^read_file /.test(call) ? call.slice('read_file '.length) : '' // a project file: read it again
@@ -1454,16 +1492,23 @@ export function trimOldResults(s, keep = 4, most = 8) {
1454
1492
  log('tool', `older tool output cut: ${long.length - keep} results`)
1455
1493
  }
1456
1494
 
1457
- // A file read again: the older copy in the conversation becomes a one-line note.
1495
+ // A file read again: the older copy in the conversation becomes a one-line note, later. Changing a
1496
+ // message in the middle makes the provider process everything after it again (its prompt cache
1497
+ // keeps only the unchanged start: minutes on a local model, full price on a paid one), so the older
1498
+ // copies wait and go together with the old results (trimOldResults), or when it's nearly full.
1458
1499
  function replaceCopy(s, file, msg) {
1459
1500
  const key = path.normalize(String(file))
1460
1501
  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
- }
1502
+ if (older && !shortened.has(older)) (s.staleCopies ??= new Map()).set(older, file)
1465
1503
  s.copies.set(key, msg)
1466
1504
  }
1505
+ // the older copies waiting, replaced now: true when there were any
1506
+ function dropStale(s) {
1507
+ if (!s.staleCopies?.size) return false
1508
+ for (const [m, file] of s.staleCopies) if (!shortened.has(m)) (m.content = prompt('agent/older-copy', { file })), shortened.add(m)
1509
+ s.staleCopies.clear()
1510
+ return true
1511
+ }
1467
1512
 
1468
1513
  // Files the user's message names go in as if the model had already read them: one round trip less
1469
1514
  // 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
@@ -235,9 +263,9 @@ export class Client {
235
263
  }
236
264
  return i
237
265
  }
238
- // "Best fit": these models first ("provider model", best first), the others after in your list's
239
- // order; this message starts with the first, and a failure goes on to the next best. false: no list.
240
- // null: your order again (best fit switched off).
266
+ // An orchestrator: these models first ("provider model"), the others after in your list's order;
267
+ // this message starts with the first, and a failure goes on to the next. false: no list.
268
+ // null: your order again (switched off).
241
269
  orderBy(names) {
242
270
  const r = this.rotation
243
271
  if (!r) return false
@@ -247,12 +275,12 @@ export class Client {
247
275
  this.#use(r.list[0])
248
276
  return true
249
277
  }
250
- r.base ??= [...r.list] // your order, kept for when best fit is switched off
278
+ r.base ??= [...r.list] // your order, kept for when it's switched off
251
279
  const first = names.map((n) => r.list.find((t) => `${t.provider} ${t.model}` === n)).filter(Boolean)
252
280
  if (!first.length) return false
253
281
  r.list = [...new Set([...first, ...r.base])]
254
282
  r.at = 0
255
- log('rotate', `best fit: ${first.map((t) => t.model).join(', ')} first`)
283
+ log('rotate', `orchestrators: ${first.map((t) => t.model).join(', ')} first`)
256
284
  this.#use(r.list[0])
257
285
  return true
258
286
  }
package/src/config.js CHANGED
@@ -5,8 +5,21 @@ 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
- 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']
22
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'modelChoice', 'orchestrators', 'logs', 'replyStart', 'mouse']
10
23
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
11
24
 
12
25
  export function readJson(file, fallback) {
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/headless.js CHANGED
@@ -90,7 +90,7 @@ export async function runHeadless(app, opts) {
90
90
  }
91
91
  s.appendSystem = opts.appendSystem || undefined
92
92
  const session_id = app.chat.id
93
- const model = `${app.cfg.provider}/${s.client.model}`
93
+ const model = `${s.client.provider ?? app.cfg.provider}/${s.client.model}`
94
94
 
95
95
  // usage and request count, over everything this message sends (tool loop, compaction, memory)
96
96
  // (also your other models', when this one hands them a job: modelUsage has each)
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/rankings.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // What each model is good at, from public rankings (LMArena: people comparing two models' answers
2
- // to the same prompt, by skill): coding, web apps, images, long inputs… Fetched once a week into
3
- // ~/.heart/rankings.json (best fit only); a model is matched to its entry by name.
2
+ // to the same prompt, by skill): overall, coding, web apps, images. Fetched once a week into
3
+ // ~/.heart/rankings.json (with an orchestrator, or Update model info); a model is matched to its entry by name.
4
4
  import path from 'node:path'
5
5
  import { HOME, readJson, writeJson } from './config.js'
6
6
  import { log } from './log.js'
@@ -11,25 +11,8 @@ const WEEK = 7 * 24 * 3600_000
11
11
  const VERSION = 2 // 2: with each model's score; an older file is fetched again
12
12
  const FILES = 'https://huggingface.co/datasets/lmarena-ai/leaderboard-dataset/resolve/main' // one Parquet file per ranking: text, webdev, vision, agent
13
13
 
14
- // The skills a task can need: [ranking, its category, what it's for] (the pick names them).
15
- export const SKILLS = {
16
- coding: ['text', 'coding', 'writing and fixing code'],
17
- webdev: ['webdev', 'webdev', 'building web apps (any stack)'],
18
- 'webdev-html': ['webdev', 'webdev-html', 'plain HTML/CSS/JS pages, canvas and browser games'],
19
- 'webdev-react': ['webdev', 'webdev-react', 'React apps'],
20
- hard: ['text', 'hard_prompts', 'hard, multi-part problems'],
21
- instructions: ['text', 'instruction_following', 'following detailed instructions exactly'],
22
- 'long-input': ['text', 'longer_query', 'long inputs: big files, long specs'],
23
- 'multi-turn': ['text', 'multi_turn', 'long back-and-forth work'],
24
- math: ['text', 'math', 'math and algorithms'],
25
- writing: ['text', 'creative_writing', 'prose, docs, copy'],
26
- software: ['text', 'industry_software_and_it_services', 'software and IT know-how'],
27
- vision: ['vision', 'overall', 'understanding images and screenshots'],
28
- ocr: ['vision', 'ocr', 'reading text in images'],
29
- diagrams: ['vision', 'diagram', 'reading diagrams and charts'],
30
- agent: ['agent', 'overall', 'agent work: tool calls, commands, many steps'],
31
- }
32
- const OVERALL = 'text:overall' // a skill a model isn't ranked on: its overall place stands in
14
+ // The lists kept (ranking:category): shown on Your models and to the orchestrator
15
+ const LISTS = ['text:overall', 'text:coding', 'webdev:webdev', 'vision:overall']
33
16
 
34
17
  export const loadRankings = () => readJson(FILE, null)
35
18
 
@@ -49,7 +32,7 @@ export async function rankings({ signal, onWait, now = false } = {}) {
49
32
  const have = loadRankings()
50
33
  if (have && have.v === VERSION && Date.now() - have.fetched < WEEK && !now) return have
51
34
  refreshing ??= (async () => {
52
- const wanted = new Set([...Object.values(SKILLS).map(([c, k]) => `${c}:${k}`), OVERALL])
35
+ const wanted = new Set(LISTS)
53
36
  const all = Object.assign({}, ...(await Promise.all([...new Set([...wanted].map((p) => p.split(':')[0]))].map((c) => fetchRanking(c, have ? undefined : signal)))))
54
37
  const lists = Object.fromEntries(Object.entries(all).filter(([k]) => wanted.has(k)))
55
38
  const out = { v: VERSION, fetched: Date.now(), source: 'LMArena (huggingface.co/datasets/lmarena-ai/leaderboard-dataset)', lists }
@@ -104,14 +87,6 @@ export function place(model, list) {
104
87
  return at.length ? Math.min(...at.map((e) => e.rank)) / list.length : null
105
88
  }
106
89
 
107
- // A model's score for some skills, 0 (best) to 1: the average of its places; a skill it isn't
108
- // ranked on counts as its overall place. null: not ranked at all.
109
- export function score(model, skills, data) {
110
- const overall = place(model, data?.lists[OVERALL])
111
- const each = skills.map((k) => place(model, data?.lists[SKILLS[k] && `${SKILLS[k][0]}:${SKILLS[k][1]}`]) ?? overall)
112
- return each.every((x) => x == null) ? null : each.reduce((n, x) => n + (x ?? 1), 0) / each.length
113
- }
114
-
115
90
  // A model's place in one list ('text:coding'…), for showing: { rank, of, as, score, votes } (as: its name there); null when not in it
116
91
  export function rankIn(model, key, data) {
117
92
  const list = data?.lists[key]
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)