heartcode 0.1.27 → 0.1.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +78 -0
- package/README.md +73 -29
- package/SKILL.md +31 -11
- package/bin/heartcode.js +20 -2
- package/package.json +1 -1
- package/prompts/agent.md +110 -20
- package/src/agent.js +426 -70
- package/src/client.js +14 -3
- package/src/config.js +1 -1
- package/src/guided.js +7 -2
- package/src/headless.js +8 -3
- package/src/memory.js +6 -2
- package/src/research.js +142 -0
- package/src/sessions.js +4 -1
- package/src/settings.html +212 -57
- package/src/settings.js +38 -0
- package/src/telegram.js +81 -0
- package/src/tools.js +133 -48
- package/src/ui.js +2 -1
- package/src/web.js +81 -10
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
|
|
459
|
-
|
|
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']
|
|
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
|
-
|
|
293
|
-
|
|
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,7 +12,7 @@
|
|
|
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).
|
|
@@ -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,
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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]+/)
|
package/src/research.js
ADDED
|
@@ -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)
|
|
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)
|