heartcode 0.1.57 → 0.1.59
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 +46 -0
- package/README.md +17 -7
- package/SKILL.md +58 -17
- package/bin/heart.js +1 -1
- package/bin/heartcode.js +47 -24
- package/package.json +1 -1
- package/prompts/agent.md +24 -13
- package/src/agent.js +71 -29
- package/src/client.js +12 -3
- package/src/config.js +14 -2
- package/src/guided.js +26 -17
- package/src/headless.js +61 -14
- package/src/log.js +1 -1
- package/src/rankings.js +4 -3
- package/src/settings.html +218 -14
- package/src/settings.js +78 -3
- package/src/tabs.js +4 -1
- package/src/tools.js +41 -26
- package/src/ui.js +104 -20
package/src/agent.js
CHANGED
|
@@ -8,11 +8,11 @@ import path from 'node:path'
|
|
|
8
8
|
import { est, estMessages, Client, tokensOf, COMPACT_SHARE } from './client.js'
|
|
9
9
|
import { runGuided } from './guided.js'
|
|
10
10
|
import { markUsed, removeResearch, findResearch } from './research.js'
|
|
11
|
-
import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths } from './tools.js'
|
|
11
|
+
import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, searchesOutside, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, refusal, noteNamedPaths, sendTodos } from './tools.js'
|
|
12
12
|
import { serversNote } from './lsp.js'
|
|
13
13
|
import { newlyEnded, jobLine } from './background.js'
|
|
14
14
|
import { loadHooks, runHooks } from './hooks.js'
|
|
15
|
-
import { takeConfigErrors } from './config.js'
|
|
15
|
+
import { takeConfigErrors, HELPER_JOBS } from './config.js'
|
|
16
16
|
import { c, duration, Block, Markdown, color, diffLines, renderDiff } from './ui.js'
|
|
17
17
|
|
|
18
18
|
// Images for a helper (the agent tool's "images"), as data: URLs: image URLs (fetched), data: URLs,
|
|
@@ -247,19 +247,12 @@ export class Session {
|
|
|
247
247
|
return `error: ${e.message}`
|
|
248
248
|
}
|
|
249
249
|
const name = (t) => `${t.provider} ${t.model}`
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
const want = String(args.model ?? '').trim()
|
|
253
|
-
// only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
|
|
254
|
-
const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want || `${t.provider}/${t.model}` === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`) || t.model.endsWith(`/${want}`)))
|
|
255
|
-
if (!first) return `error: no model "${want}". Yours: ${all.map(name).join(', ')}`
|
|
256
|
-
// the one asked for first, then the others in your list's order: only those that can do the job
|
|
257
|
-
// (images need a model that sees them)
|
|
258
|
-
const able = (t) => !images.length || t.images
|
|
259
|
-
const order = [first, ...all.filter((t) => t !== first)].filter(able)
|
|
250
|
+
const { order, first, all, helpers } = this.helperModels(args, images.length > 0)
|
|
251
|
+
if (!first) return `error: no model "${String(args.model).trim()}". ${helpers ? 'Your helpers' : 'Yours'}: ${all.map(name).join(', ')}`
|
|
260
252
|
if (!order.length) return 'error: none of your models can see images'
|
|
261
253
|
const failed = []
|
|
262
254
|
for (const [i, t] of order.entries()) {
|
|
255
|
+
if (args.part) (args.part.by = t.model), (args.part.byProvider = t.provider ?? this.client.provider), sendTodos(this) // a part of the plan: the model doing it, shown beside it
|
|
263
256
|
let answer = ''
|
|
264
257
|
try {
|
|
265
258
|
answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
|
|
@@ -275,6 +268,24 @@ export class Session {
|
|
|
275
268
|
return `error: none of your models that can do it managed: ${failed.join('; ')}`
|
|
276
269
|
}
|
|
277
270
|
|
|
271
|
+
// The models a helper's job goes to, in order: the one asked for (args.model), then the helpers you
|
|
272
|
+
// ticked (then this model), else this model and your others, in your list's order; only those that
|
|
273
|
+
// see images when it comes with some. first: the one asked for (undefined: no such model).
|
|
274
|
+
helperModels(args, withImages) {
|
|
275
|
+
const name = (t) => `${t.provider} ${t.model}`
|
|
276
|
+
const self = { provider: this.client.provider, model: this.client.model, images: this.strat.vision, tools: this.strat.actions === 'tools', self: true }
|
|
277
|
+
const team = this.team?.() ?? []
|
|
278
|
+
const helpers = helpersOf(team)
|
|
279
|
+
const all = helpers ? [...helpers, self] : [self, ...team]
|
|
280
|
+
const want = String(args.model ?? '').trim()
|
|
281
|
+
// only one model available (a pinned model, or you have just one): helpers use it, whatever was asked
|
|
282
|
+
const first = !want || all.length === 1 ? all[0] : (all.find((t) => name(t) === want || `${t.provider}/${t.model}` === want) ?? all.find((t) => t.model === want || want.endsWith(` ${t.model}`) || t.model.endsWith(`/${want}`)))
|
|
283
|
+
const able = (t) => !withImages || t.images
|
|
284
|
+
let order = first ? [first, ...all.filter((t) => t !== first)].filter(able) : []
|
|
285
|
+
if (first && !order.length && helpers) order = [self, ...team].filter(able) // no helper sees images: any of yours that does
|
|
286
|
+
return { order, first, all, helpers }
|
|
287
|
+
}
|
|
288
|
+
|
|
278
289
|
// One helper on one model (t: this one, or another of yours), with its own connection (a helper's
|
|
279
290
|
// failure moves no one else on to another model) that gives up after a few tries (then the next
|
|
280
291
|
// model gets the job).
|
|
@@ -286,7 +297,7 @@ export class Session {
|
|
|
286
297
|
client.retryIf = (e, attempt) => attempt < 3 && e.name !== 'TimeoutError' && e.status !== 429 && e.status !== 413 && (!was || was(e, attempt)) // silent (not starting, or stopping midway: each try would wait as long again), rate-limited or too large: the next model, not another try
|
|
287
298
|
}
|
|
288
299
|
const label = clip(String(description ?? '').trim() || task.split('\n')[0], 60) // its model is named on the agent line
|
|
289
|
-
const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
|
|
300
|
+
const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label, client.model), chat: newChat(this.root) })
|
|
290
301
|
helper.chat.turns = this.chat.turns.slice(-1) // this message's turn: its file changes go there (track), the changes tool reads them
|
|
291
302
|
if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
|
|
292
303
|
Object.assign(helper, { isSub: true, research: this.research, ran: this.ran, noResearch: this.noResearch, mcp: this.mcp, skills: this.skills, hooks: this.hooks, allowTools: this.allowTools, denyTools: this.denyTools, maxTurns: this.maxTurns, autoCompact: this.autoCompact, appendSystem: this.appendSystem, fileCache: this.fileCache, noFormat: this.noFormat, noLsp: this.noLsp })
|
|
@@ -294,7 +305,7 @@ export class Session {
|
|
|
294
305
|
helper.mcpGate = async () => (await this.#gate(helper), () => {})
|
|
295
306
|
if (this.onEvent) helper.onEvent = (e) => this.onEvent({ ...e, parent: id, helper: label })
|
|
296
307
|
log('agent', `helper "${label}" (${images.length} image(s)): ${task}`)
|
|
297
|
-
this.ui.helpers?.set(label, 'starting') // a line under the spinner while it works (helperUI keeps it up to date)
|
|
308
|
+
this.ui.helpers?.set(label, { id, model: `${t.provider ?? client.provider}/${t.model ?? client.model}`, what: 'starting' }) // a line under the spinner while it works (helperUI keeps it up to date)
|
|
298
309
|
try {
|
|
299
310
|
const answer = await (strat.actions === 'tools' ? runNative : runGuided)(helper, task, images, signal)
|
|
300
311
|
log('agent', `helper "${label}" done`, answer)
|
|
@@ -568,7 +579,7 @@ const alwaysSkill = (k) => {
|
|
|
568
579
|
const SYSTEM = (s) => {
|
|
569
580
|
const instructions = userInstructions(s.root)
|
|
570
581
|
return [
|
|
571
|
-
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), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub) }), // models that can see often say they can't: told they can
|
|
582
|
+
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), see: Boolean(s.strat.vision), noUser: Boolean(s.ui.noUser || s.isSub), memory: Boolean(s.memory) && !s.isSub }), // models that can see often say they can't: told they can
|
|
572
583
|
instructions && prompt('agent/instructions', { instructions }),
|
|
573
584
|
...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map(alwaysSkill), // skills that say how to work (use: always), with the files they bring
|
|
574
585
|
!s.isSub && teamPrompt(s),
|
|
@@ -579,14 +590,19 @@ const SYSTEM = (s) => {
|
|
|
579
590
|
.join('\n\n')
|
|
580
591
|
}
|
|
581
592
|
|
|
593
|
+
// The helpers you ticked on Your models (jobs: what for), in your order; null when none are.
|
|
594
|
+
export const helpersOf = (team) => (team.some((t) => t.jobs) ? team.filter((t) => t.jobs) : null)
|
|
595
|
+
|
|
582
596
|
// Your other models and what each can do, for the agent tool's model (only when there are any): a
|
|
583
|
-
// short line each, in your list's order.
|
|
597
|
+
// short line each, in your list's order. With helpers ticked: only them, and what each is good at.
|
|
584
598
|
const teamPrompt = (s) => {
|
|
585
599
|
const team = s.team?.() ?? []
|
|
586
600
|
if (!team.length) return ''
|
|
587
|
-
const
|
|
588
|
-
const
|
|
589
|
-
|
|
601
|
+
const helpers = helpersOf(team)
|
|
602
|
+
const can = (t) => [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', t.context && `${kTokens(t.context)} context`].filter(Boolean)
|
|
603
|
+
const good = (t) => (t.jobs?.length ? ` · good at: ${t.jobs.map((j) => HELPER_JOBS[j]?.[1]).filter(Boolean).join('; ')}` : '')
|
|
604
|
+
const line = (t) => `- ${t.provider} ${t.model}${can(t).length ? `: ${can(t).join(', ')}` : ''}${good(t)}`
|
|
605
|
+
return prompt('agent/team', { helpers: Boolean(helpers), models: (helpers ?? team).map(line).join('\n'), you: [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking'].filter(Boolean).join(', ') })
|
|
590
606
|
}
|
|
591
607
|
|
|
592
608
|
const sizeOf = (m) =>
|
|
@@ -878,6 +894,8 @@ async function runNative(s, task, images, signal) {
|
|
|
878
894
|
}
|
|
879
895
|
let garbled = 0 // replies with a tool call written as text (template markup), this message
|
|
880
896
|
let movedOn = 0 // models given up on for that, in this message
|
|
897
|
+
let cut = '' // a reply cut off (its provider's output limit, or the connection ended early): what came of it so far
|
|
898
|
+
let cuts = 0 // cut off in a row: asked to go on, up to 3 times
|
|
881
899
|
let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
|
|
882
900
|
// No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
|
|
883
901
|
for (let step = 0; ; step++) {
|
|
@@ -922,7 +940,11 @@ async function runNative(s, task, images, signal) {
|
|
|
922
940
|
}
|
|
923
941
|
const stream = strat.stream
|
|
924
942
|
// A long tool call (a whole file) streams in silently: say what's being written.
|
|
925
|
-
const onToolDelta = (name, args) =>
|
|
943
|
+
const onToolDelta = (name, args) => {
|
|
944
|
+
const file = /"path"\s*:\s*"([^"]+)"/.exec(args)?.[1]
|
|
945
|
+
const what = name === 'run_command' ? 'preparing a command' : EDITS.has(name) && file ? `writing ${file}` : `preparing ${name}${file ? ` ${file}` : ''}` // only an edit is "writing" a file
|
|
946
|
+
ui.spinner(`${what} · ${args.length >= 1000 ? `${(args.length / 1000).toFixed(1)}k` : args.length} chars`)
|
|
947
|
+
}
|
|
926
948
|
// the prompts or HEARTCODE.md changed meanwhile (applySettings): the system prompt again, now
|
|
927
949
|
if (s.refreshSystem && s.messages[0]?.role === 'system') s.messages[0] = { ...s.messages[0], content: SYSTEM(s) }
|
|
928
950
|
s.refreshSystem = false
|
|
@@ -1005,7 +1027,20 @@ async function runNative(s, task, images, signal) {
|
|
|
1005
1027
|
showHeld(res.content) // not the answer: shown now, before its calls
|
|
1006
1028
|
s.acted = sinceNudge = true // did real work this message, for the premature-stop check
|
|
1007
1029
|
}
|
|
1008
|
-
s.
|
|
1030
|
+
s.lastStop = res.finishReason // why the last reply ended (headless: its stop_reason)
|
|
1031
|
+
s.onEvent?.({ type: 'assistant', model: `${client.provider}/${client.model}`, content: res.content, reasoning: res.reasoning, toolCalls: res.toolCalls, stop: res.finishReason }) // headless output
|
|
1032
|
+
// An answer cut off (its provider's output limit: no max_tokens is sent, so each has its own; or a
|
|
1033
|
+
// connection that ended early): the model goes on where it stopped (3 times in a row at most); the
|
|
1034
|
+
// answer is the pieces together. Still cut after that: it stays cut, and says so (stop_reason).
|
|
1035
|
+
if (!res.toolCalls.length && res.content?.trim() && (res.finishReason === 'length' || res.finishReason === 'incomplete') && cuts < 3) {
|
|
1036
|
+
cuts++
|
|
1037
|
+
cut += res.content
|
|
1038
|
+
log('task', `${client.model}: reply cut off (${res.finishReason}); asking it to go on`)
|
|
1039
|
+
s.messages.push({ role: 'user', content: prompt('agent/cut-off') })
|
|
1040
|
+
continue
|
|
1041
|
+
}
|
|
1042
|
+
if (cut && !res.toolCalls.length) res.content = cut + res.content
|
|
1043
|
+
if (!res.toolCalls.length || res.finishReason !== 'length') [cut, cuts] = ['', 0]
|
|
1009
1044
|
if (!res.toolCalls.length && !res.content?.trim()) {
|
|
1010
1045
|
// Nothing at all (seen after a failed tool call): not an answer. The same request again
|
|
1011
1046
|
// first (often fine the second time), then asked to go on; three in a row ends the task.
|
|
@@ -1049,7 +1084,7 @@ async function runNative(s, task, images, signal) {
|
|
|
1049
1084
|
}
|
|
1050
1085
|
}
|
|
1051
1086
|
// a helper's line: its job, and the model doing it (named once here; its steps go by its job)
|
|
1052
|
-
const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${a.model || client.model}`)}`
|
|
1087
|
+
const helperLine = (a) => `${clip(String(a.description ?? '').trim() || 'helper', 70)} ${c.faint(`· ${s.helperModels?.(a, [a.images ?? []].flat().length > 0).order[0]?.model ?? (a.model || client.model)}`)}` // the model that will do it
|
|
1053
1088
|
const together = new Map()
|
|
1054
1089
|
for (const call of res.toolCalls) {
|
|
1055
1090
|
const args = argsOf(call)
|
|
@@ -1096,7 +1131,7 @@ async function runNative(s, task, images, signal) {
|
|
|
1096
1131
|
: name === 'todo' || name === 'ask_user'
|
|
1097
1132
|
? ''
|
|
1098
1133
|
: (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
|
|
1099
|
-
if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80)) // asked together: shown once, with the first
|
|
1134
|
+
if (name !== 'run_command' && !together.has(call.id) && !askedWith.has(call.id)) ui.step(name, name === 'agent' && args ? helperLine(args) : clip(detail, 80), name === 'agent' ? '' : client.model) // asked together: shown once, with the first; named by the model that made the call (an agent line names the helper's)
|
|
1100
1135
|
const pre = early.get(call.id)
|
|
1101
1136
|
// the first changes to the files with no plan yet (this message, or still open from an earlier one):
|
|
1102
1137
|
// not made — the plan first, then the changes again. Every change in that reply (one made beside a
|
|
@@ -1128,7 +1163,9 @@ async function runNative(s, task, images, signal) {
|
|
|
1128
1163
|
if (++s.checksSince === 5 && (s.changed.size || s.isSub)) out += `\n\n${prompt('agent/enough-checks', { n: s.checksSince, choices: (s.chat?.choices ?? []).join('; ') })}`
|
|
1129
1164
|
}
|
|
1130
1165
|
}
|
|
1131
|
-
|
|
1166
|
+
// what was run or checked, for the review and the wrap-up: commands, MCP tools (a browser), helpers, the language server
|
|
1167
|
+
const checked = !args || refused ? null : name === 'run_command' ? String(args.command ?? '') : name === 'mcp' ? `${args.server} · ${args.tool}` : name === 'agent' ? `helper: ${args.description ?? clip(String(args.prompt ?? ''), 60)}` : name === 'lsp' ? `language server: ${args.action} ${args.file ?? ''}` : null
|
|
1168
|
+
if (checked) s.ran?.push({ command: checked, result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
|
|
1132
1169
|
if (!s.isSub && s.memory && !refused && args) await noteRun(s, name, args, out, signal).catch((e) => log('learn', `run note: ${e.message}`)) // learn from any run that failed then passed
|
|
1133
1170
|
// the same call again and again in a row (a weak model going round): told at the third, stopped at the fifth
|
|
1134
1171
|
const sig = `${name} ${call.function.arguments}`
|
|
@@ -1153,7 +1190,7 @@ async function runNative(s, task, images, signal) {
|
|
|
1153
1190
|
const msg = { role: 'tool', tool_call_id: call.id, content: fitResult(s, name, out, s.chat.outputs?.[call.id]) }
|
|
1154
1191
|
if (name === 'read_file' && args && !args.start_line && !args.end_line && !failed(out)) replaceCopy(s, args.path, msg)
|
|
1155
1192
|
s.messages.push(msg)
|
|
1156
|
-
s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
|
|
1193
|
+
s.onEvent?.({ type: 'tool', id: call.id, name, output: out, model: `${client.provider}/${client.model}` })
|
|
1157
1194
|
}
|
|
1158
1195
|
if (s.userSaid.length) s.messages.push({ role: 'user', content: s.userSaid.splice(0).join('\n\n') }) // their own words, as they typed them
|
|
1159
1196
|
trimOldResults(s)
|
|
@@ -1433,7 +1470,9 @@ export async function review(s, task, answer, signal) {
|
|
|
1433
1470
|
const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
|
|
1434
1471
|
const ask = prompt('agent/review', { request: requestsOf(s.chat, 1200), emphasis: (s.chat?.choices ?? []).join('; '), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)' })
|
|
1435
1472
|
const self = { provider: s.client.provider, model: s.client.model, self: true }
|
|
1436
|
-
const
|
|
1473
|
+
const others = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model))
|
|
1474
|
+
const reviewers = others.filter((t) => t.jobs?.includes('code')).sort((a, b) => Boolean(b.thinking) - Boolean(a.thinking)) // ticked for Code & logic on Your models, the thinking ones first
|
|
1475
|
+
const team = [...reviewers, ...others.filter((t) => !reviewers.includes(t))] // then your others, in your order (two at most, then this one)
|
|
1437
1476
|
for (const t of [...team.slice(0, 2), self]) {
|
|
1438
1477
|
s.ui.spinner(`${t.model} is reviewing the work`)
|
|
1439
1478
|
try {
|
|
@@ -1450,11 +1489,13 @@ export async function review(s, task, answer, signal) {
|
|
|
1450
1489
|
s.ui.stopSpin()
|
|
1451
1490
|
log('review', `${t.model}: ${said}`)
|
|
1452
1491
|
if (/^\W*yes\b/i.test(said)) {
|
|
1492
|
+
s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'yes', issues: '' })
|
|
1453
1493
|
s.ui.step('review', `${t.model}: looks right`)
|
|
1454
1494
|
return null
|
|
1455
1495
|
}
|
|
1456
1496
|
if (/^\W*no\b/i.test(said)) {
|
|
1457
1497
|
const issues = said.replace(/^\W*no\b[\s.:—-]*/i, '').trim()
|
|
1498
|
+
s.ui.event?.({ subtype: 'review', model: `${t.provider}/${t.model}`, verdict: 'no', issues })
|
|
1458
1499
|
s.ui.step('review', `${t.model}: ${clip(issues.split('\n').find((l) => l.trim()) ?? 'problems found', 90)}`)
|
|
1459
1500
|
return prompt('agent/review-failed', { model: t.model, issues: issues || '(no details given)' })
|
|
1460
1501
|
}
|
|
@@ -1480,7 +1521,8 @@ const lineCount = (out) => {
|
|
|
1480
1521
|
// Questions to the user (confirm, pick, ask) wait their turn: helpers working at once ask one by one.
|
|
1481
1522
|
const asking = new WeakMap() // ui → the question being asked
|
|
1482
1523
|
const streaming = new WeakMap() // ui → helper replies coming in now (only one: its thinking is shown as it comes)
|
|
1483
|
-
|
|
1524
|
+
// model: the helper's, named on each of its steps
|
|
1525
|
+
function helperUI(ui, label, model) {
|
|
1484
1526
|
// What the helper says is shown in full under its name. Its thinking is shown as it comes, like the
|
|
1485
1527
|
// conversation's; with other helpers replying at the
|
|
1486
1528
|
// same time, held until its reply ends, then printed at once (two streams would interleave).
|
|
@@ -1515,7 +1557,7 @@ function helperUI(ui, label) {
|
|
|
1515
1557
|
// what it's doing, for the line per helper under the spinner (ui.helpers: full screen only)
|
|
1516
1558
|
const status = (text) => {
|
|
1517
1559
|
if (!ui.helpers?.has(label)) return
|
|
1518
|
-
ui.helpers.set(label, clip(String(text), 60))
|
|
1560
|
+
ui.helpers.set(label, { ...ui.helpers.get(label), what: clip(String(text), 60) })
|
|
1519
1561
|
ui.render?.()
|
|
1520
1562
|
}
|
|
1521
1563
|
const own = {
|
|
@@ -1523,7 +1565,7 @@ function helperUI(ui, label) {
|
|
|
1523
1565
|
step: (name, detail = '') => {
|
|
1524
1566
|
if (ui.afterBlock) ui.gap()
|
|
1525
1567
|
ui.afterBlock = false
|
|
1526
|
-
ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}`)
|
|
1568
|
+
ui.print(` ${c.accent('●')} ${c.accent(c.bold(`${label} › ${name}`))} ${c.info(detail)}${model ? c.faint(` · ${model}`) : ''}`)
|
|
1527
1569
|
status(`${name} ${detail}`)
|
|
1528
1570
|
},
|
|
1529
1571
|
result: (text) => ui.print(` ${c.ghost('⎿')} ${c.faint(text)}`),
|
package/src/client.js
CHANGED
|
@@ -654,6 +654,7 @@ export class Client {
|
|
|
654
654
|
let thought = ''
|
|
655
655
|
let usage
|
|
656
656
|
let finishReason
|
|
657
|
+
let sawDone = false
|
|
657
658
|
const calls = []
|
|
658
659
|
let raw = '' // the stream as it came (its start), kept for a reply that turns out empty
|
|
659
660
|
// A reply going round (a small model repeating itself, which could fill the window): checked
|
|
@@ -682,8 +683,7 @@ export class Client {
|
|
|
682
683
|
}
|
|
683
684
|
poke()
|
|
684
685
|
firstAt ??= Date.now()
|
|
685
|
-
|
|
686
|
-
buf += dec.decode(value, { stream: true })
|
|
686
|
+
buf += end ? dec.decode() + '\n' : dec.decode(value, { stream: true }) // the end: its last line too, even without a line break after it
|
|
687
687
|
let nl
|
|
688
688
|
while ((nl = buf.indexOf('\n')) !== -1) {
|
|
689
689
|
const line = buf.slice(0, nl).trim()
|
|
@@ -691,7 +691,10 @@ export class Client {
|
|
|
691
691
|
if (raw.length < 100_000 && line) raw += line + '\n'
|
|
692
692
|
if (!line.startsWith('data:')) continue
|
|
693
693
|
const payload = line.slice(5).trim()
|
|
694
|
-
if (payload === '[DONE]')
|
|
694
|
+
if (payload === '[DONE]') {
|
|
695
|
+
sawDone = true
|
|
696
|
+
continue
|
|
697
|
+
}
|
|
695
698
|
let chunk
|
|
696
699
|
try {
|
|
697
700
|
chunk = JSON.parse(payload)
|
|
@@ -749,6 +752,12 @@ export class Client {
|
|
|
749
752
|
await reader.cancel().catch(() => {}) // the server stops generating
|
|
750
753
|
break
|
|
751
754
|
}
|
|
755
|
+
if (end) break
|
|
756
|
+
}
|
|
757
|
+
// closed with neither [DONE] nor a reason it ended: the connection ended early, the reply may be cut
|
|
758
|
+
if (!looped && !sawDone && !finishReason) {
|
|
759
|
+
finishReason = 'incomplete'
|
|
760
|
+
log('reply', `${this.model}: the stream ended without [DONE] or a finish reason: the reply may be cut off`)
|
|
752
761
|
}
|
|
753
762
|
clearTimeout(timer), started()
|
|
754
763
|
if (looped) {
|
package/src/config.js
CHANGED
|
@@ -19,7 +19,7 @@ export function projectDir(root, what) {
|
|
|
19
19
|
return dir
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'logs', 'replyStart', 'replyIdle', 'mouse']
|
|
22
|
+
const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search', 'testTimeout', 'updateCheck', 'logs', 'replyStart', 'replyIdle', 'mouse', 'helpers', 'helpersAuto', 'helperOrder', 'providerRank']
|
|
23
23
|
// How long a reply may take (the settings page's Your models), in seconds, with the defaults:
|
|
24
24
|
// replyStart: a reply must start within it, else that model failed; replyIdle: a reply that stops
|
|
25
25
|
// sending for it is stalled.
|
|
@@ -27,6 +27,18 @@ export function speedOf(cfg) {
|
|
|
27
27
|
const sec = (v, d, min, max) => (Number.isInteger(Number(v)) && Number(v) >= min && Number(v) <= max ? Number(v) : d)
|
|
28
28
|
return { replyStart: sec(cfg.replyStart, 60, 5, 600), replyIdle: sec(cfg.replyIdle, 150, 10, 1800) }
|
|
29
29
|
}
|
|
30
|
+
// What a helper can be picked for (Your models' pills): [its label there, what #1 is told it's good at,
|
|
31
|
+
// what the pill covers (its tooltip)]
|
|
32
|
+
export const HELPER_JOBS = {
|
|
33
|
+
ui: ['UI & visuals', 'websites, app screens, games, animation, 3D, charts', 'Websites and landing pages, app screens, games and animation, 3D, charts and SVG: anything people look at.'],
|
|
34
|
+
code: ['Code & logic', 'backend, APIs, scripts, automation, fixing bugs, tests, reviewing changes', 'Backend and APIs, scripts and automation, fixing bugs, tests and refactoring. Reviews of the work go to these first, then to your other models.'],
|
|
35
|
+
hard: ['Big & hard', 'hard thinking, planning, long tasks with many steps, huge files', 'Planning and architecture, tricky logic, long tasks with many steps, huge files or whole folders.'],
|
|
36
|
+
quick: ['Quick & cheap', 'small jobs: searching and reading code, lookups, small edits', 'Searching and reading code, looking things up, small edits: simple jobs, on a model that answered fast.'],
|
|
37
|
+
}
|
|
38
|
+
// a helper's jobs as saved, in today's names (picks from before the four: search, research → quick, review → code)
|
|
39
|
+
const WAS = { search: 'quick', research: 'quick', review: 'code' }
|
|
40
|
+
export const jobsOf = (jobs) => (Array.isArray(jobs) ? [...new Set(jobs.map((j) => WAS[j] ?? j).filter((j) => HELPER_JOBS[j]))] : undefined)
|
|
41
|
+
export const helpersOf = (map) => Object.fromEntries(Object.entries(map ?? {}).map(([k, jobs]) => [k, jobsOf(jobs)]).filter(([, jobs]) => jobs))
|
|
30
42
|
export const SPEED_LIMITS = { replyStart: [5, 600], replyIdle: [10, 1800] }
|
|
31
43
|
|
|
32
44
|
const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
|
|
@@ -134,7 +146,7 @@ export function loadConfig(flags = {}) {
|
|
|
134
146
|
const model = flags.model || process.env.HEART_MODEL
|
|
135
147
|
if (model && !isAuto(model)) Object.assign(cfg, parseModel(model, cfg.providers, cfg.provider))
|
|
136
148
|
// -m / an ad-hoc URL pins the chosen model for this run (a session of one): cfg.session, below
|
|
137
|
-
if ((baseUrl || (model && !isAuto(model))) && cfg.providers[cfg.provider] && cfg.model) cfg
|
|
149
|
+
if ((baseUrl || (model && !isAuto(model))) && cfg.providers[cfg.provider] && cfg.model) Object.assign(cfg, { session: [{ provider: cfg.provider, model: cfg.model }], pinned: true }) // pinned: asked for by name, so it runs even if its provider is switched off
|
|
138
150
|
synced(cfg, readJson(CONFIG_FILE, {}))
|
|
139
151
|
return cfg
|
|
140
152
|
}
|
package/src/guided.js
CHANGED
|
@@ -13,12 +13,13 @@ import { runHooks } from './hooks.js'
|
|
|
13
13
|
import { foldersOf } from './agent.js'
|
|
14
14
|
import { c } from './ui.js'
|
|
15
15
|
|
|
16
|
-
// The steps, as "name: description" lines in prompts/guided/actions.md
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
16
|
+
// The steps, as "name: description" lines in prompts/guided/actions.md (read each time: a project's
|
|
17
|
+
// own prompts and the settings page's edits apply at once)
|
|
18
|
+
const actions = () =>
|
|
19
|
+
prompt('guided/actions')
|
|
20
|
+
.split('\n')
|
|
21
|
+
.map((l) => l.split(/:\s*/, 2))
|
|
22
|
+
.filter(([n, d]) => n && d)
|
|
22
23
|
const TEST_FILE = /(^|[/._-])(tests?|spec|__tests__)([/._-]|$)/i
|
|
23
24
|
|
|
24
25
|
// Obvious next steps are taken without asking: a weak model's effort goes into
|
|
@@ -39,7 +40,7 @@ export function nextActions(st) {
|
|
|
39
40
|
if (!st.reads && st.hasFiles) first = ['read', 'search']
|
|
40
41
|
else if (st.wantsChange && !st.edits) first = st.hasFiles ? ['edit', 'create', 'read'] : ['create']
|
|
41
42
|
else first = ['finish', 'edit', 'run']
|
|
42
|
-
return [...new Set([...first, ...
|
|
43
|
+
return [...new Set([...first, ...actions().map(([n]) => n)])].filter((n) => (n !== 'delegate' || st.canDelegate) && (n !== 'ask' || !st.noAsk) && n !== st.avoid) // a step that just repeated with nothing new isn't offered again (a small model picks it over and over)
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
// A reply may be plain text or JSON like {"path": "a.js"}.
|
|
@@ -264,7 +265,8 @@ class Guided {
|
|
|
264
265
|
|
|
265
266
|
async start(images) {
|
|
266
267
|
this.images = images.length > 0
|
|
267
|
-
|
|
268
|
+
const team = this.s.team?.() ?? []
|
|
269
|
+
this.st.canDelegate = Boolean((team.some((t) => t.jobs) ? team.filter((t) => t.jobs) : team).some((t) => t.tools && (!this.images || t.images))) // one that sees them, with images; your helpers when you ticked some
|
|
268
270
|
if (!this.s.isSub) Object.assign(this.s, { research: [], ran: [], dirsBefore: foldersOf(this.s.root) }) // this message's, for the wrap-up (a helper adds to its main agent's)
|
|
269
271
|
if (images.length) await this.describeImages(images)
|
|
270
272
|
this.autoRead()
|
|
@@ -273,7 +275,8 @@ class Guided {
|
|
|
273
275
|
let last = ''
|
|
274
276
|
let repeats = 0
|
|
275
277
|
// No step limit (Esc stops it); a model doing the same thing three times in a row is stopped.
|
|
276
|
-
|
|
278
|
+
let step = 0
|
|
279
|
+
for (; !this.s.maxTurns || step < this.s.maxTurns; step++) {
|
|
277
280
|
this.ui.spinner('deciding next step')
|
|
278
281
|
const auto = autoAction(this.st)
|
|
279
282
|
const action = auto ?? (await this.pickAction())
|
|
@@ -310,6 +313,10 @@ class Guided {
|
|
|
310
313
|
}
|
|
311
314
|
if (repeats === 1) this.note(null, 'warning', prompt('guided/note-repeated'))
|
|
312
315
|
}
|
|
316
|
+
if (this.s.maxTurns && step >= this.s.maxTurns) {
|
|
317
|
+
if (!this.s.isSub) this.ui.warn(`stopped after ${this.s.maxTurns} steps (--max-turns); say "continue" to go on`)
|
|
318
|
+
throw Object.assign(new Error(`stopped after ${this.s.maxTurns} steps (--max-turns)`), { maxTurns: true })
|
|
319
|
+
}
|
|
313
320
|
const answer = await this.finish()
|
|
314
321
|
this.s.wrapUpLater?.(this.task, answer) // after the answer, beside what comes next (skipped for helpers and without memory)
|
|
315
322
|
return answer
|
|
@@ -320,7 +327,7 @@ class Guided {
|
|
|
320
327
|
async tool(name, args, run) {
|
|
321
328
|
const { s } = this
|
|
322
329
|
const id = `guided_${++this.calls}`
|
|
323
|
-
s.onEvent?.({ type: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: '', toolCalls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }] })
|
|
330
|
+
s.onEvent?.({ type: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: '', toolCalls: [{ id, type: 'function', function: { name, arguments: JSON.stringify(args) } }], stop: 'tool_calls' })
|
|
324
331
|
let out
|
|
325
332
|
const pre = allowed(s, name) && (await runHooks(s, 'PreToolUse', { tool_name: name, tool_input: args }, this.signal))
|
|
326
333
|
const notMine = name === 'write_file' && s.ownFiles && !s.ownFiles.includes(path.resolve(s.root, args.path))
|
|
@@ -333,7 +340,7 @@ class Guided {
|
|
|
333
340
|
if (post.block) out += `\n\n${prompt('agent/hook', { reason: post.block, after: true })}`
|
|
334
341
|
}
|
|
335
342
|
if (!pre || pre.block || notMine) this.ui.result(c.red(clip(out, 120)))
|
|
336
|
-
s.onEvent?.({ type: 'tool', id, name, output: out })
|
|
343
|
+
s.onEvent?.({ type: 'tool', id, name, output: out, model: `${s.client.provider}/${s.client.model}` })
|
|
337
344
|
return out
|
|
338
345
|
}
|
|
339
346
|
|
|
@@ -358,14 +365,15 @@ class Guided {
|
|
|
358
365
|
readNote(f, quiet = false) {
|
|
359
366
|
const body = readFileTool(this.s.root, f, 1, undefined, 2000)
|
|
360
367
|
this.note(`read:${f}`, `contents of ${f}`, clip(body, Math.floor(this.s.strat.context * 3.5 * 0.4)))
|
|
361
|
-
if (!quiet) this.ui.step('read', f)
|
|
368
|
+
if (!quiet) this.ui.step('read', f, this.s.client.model)
|
|
362
369
|
this.st.reads++
|
|
363
370
|
return body
|
|
364
371
|
}
|
|
365
372
|
|
|
366
373
|
async pickAction() {
|
|
367
374
|
const names = nextActions(this.st)
|
|
368
|
-
const
|
|
375
|
+
const desc = Object.fromEntries(actions())
|
|
376
|
+
const menu = names.map((n, i) => `${i + 1}. ${n} - ${desc[n]}`).join('\n')
|
|
369
377
|
let q = prompt('guided/next-action', { menu, reply: '', count: names.length })
|
|
370
378
|
for (let i = 0; i < 2; i++) {
|
|
371
379
|
const res = await this.query(q, { room: 16, oneLine: true })
|
|
@@ -408,7 +416,7 @@ class Guided {
|
|
|
408
416
|
const res = await this.query(prompt('guided/search'), { room: 40, oneLine: true })
|
|
409
417
|
const q = unquote(answerText(res.content).split('\n')[0].trim())
|
|
410
418
|
if (!q) return 'search:'
|
|
411
|
-
this.ui.step('search', q)
|
|
419
|
+
this.ui.step('search', q, this.s.client.model)
|
|
412
420
|
const out = await this.tool('search', { query: q }, () => searchFiles(this.s.root, q))
|
|
413
421
|
this.ui.result(out.startsWith('no matches') ? 'no matches' : `${out.split('\n').length} matches`)
|
|
414
422
|
this.note(`search:${q}`, `search results for "${q}"`, out)
|
|
@@ -424,7 +432,7 @@ class Guided {
|
|
|
424
432
|
let f = await this.pickFile(true, files)
|
|
425
433
|
if (!f) return 'edit:'
|
|
426
434
|
const old = fs.readFileSync(resolveIn(this.s.root, f), 'utf8')
|
|
427
|
-
this.ui.step('edit', f)
|
|
435
|
+
this.ui.step('edit', f, this.s.client.model)
|
|
428
436
|
let next = null
|
|
429
437
|
next = await this.editBlocks(f, old)
|
|
430
438
|
if (next === null) next = await this.editRewrite(f, old)
|
|
@@ -546,7 +554,7 @@ class Guided {
|
|
|
546
554
|
if (!rel) return 'create:'
|
|
547
555
|
const abs = resolveIn(this.s.root, rel)
|
|
548
556
|
const f = path.relative(this.s.root, abs)
|
|
549
|
-
this.ui.step('create', f)
|
|
557
|
+
this.ui.step('create', f, this.s.client.model)
|
|
550
558
|
if (fs.existsSync(abs)) {
|
|
551
559
|
const old = fs.readFileSync(abs, 'utf8')
|
|
552
560
|
const next = await this.editRewrite(f, old)
|
|
@@ -600,7 +608,8 @@ class Guided {
|
|
|
600
608
|
// Another of your models, one with tool calls, does the whole task; what it did goes in the notes.
|
|
601
609
|
async delegate() {
|
|
602
610
|
// the first of yours with tool calls (that sees images, if the task came with some)
|
|
603
|
-
const
|
|
611
|
+
const all = this.s.team()
|
|
612
|
+
const team = (all.some((t) => t.jobs) ? all.filter((t) => t.jobs) : all).filter((t) => t.tools && (!this.images || t.images)) // your helpers, when you ticked some
|
|
604
613
|
const t = team[0]
|
|
605
614
|
const args = { description: 'the task', prompt: this.task, model: `${t.provider} ${t.model}` }
|
|
606
615
|
const done = await this.tool('agent', args, (id) => this.s.subagent(args, this.signal, id))
|
package/src/headless.js
CHANGED
|
@@ -7,16 +7,24 @@
|
|
|
7
7
|
// stdin: {"type":"user","message":{"role":"user","content":"…"}} one per line, any number
|
|
8
8
|
// {"type":"control_request","request_id":"1","request":{"subtype":"interrupt"}}
|
|
9
9
|
// stdout: {"type":"system","subtype":"init",…}, {"type":"assistant",…}, {"type":"user",…}
|
|
10
|
-
// (tool results), {"type":"result",…} after each message
|
|
10
|
+
// (tool results), {"type":"result",…} after each message; and what the full screen
|
|
11
|
+
// shows besides, as {"type":"system","subtype":…}: "todos" (the plan: content, status,
|
|
12
|
+
// by: the model a part went to), "helper" (one at work: tool_use_id, label, model, status;
|
|
13
|
+
// "done" at its end), "review" (model, verdict yes/no, issues), "model_switch" (from, to,
|
|
14
|
+
// reason), "warning" (message), "retry" (attempt, delay_ms, error), "status" (what it's
|
|
15
|
+
// doing now, as the spinner says it: a running command's latest output line too)
|
|
11
16
|
// Nothing asks anything: what the permission mode would ask about is declined, with the reason
|
|
12
|
-
// told to the model. Logs
|
|
17
|
+
// told to the model. Logs go to their files (or HEART_LOG), never stdout; warnings and retries go to
|
|
18
|
+
// stderr with --verbose (and, in stream-json, as system lines).
|
|
13
19
|
import readline from 'node:readline'
|
|
14
20
|
import { log } from './log.js'
|
|
15
21
|
import { clip, TOOL_DEFS, extraTools, loadMcpTools, mcpName, failed as toolFailed } from './tools.js'
|
|
16
22
|
import { allowed } from './agent.js'
|
|
17
23
|
|
|
24
|
+
const plain = (t) => String(t ?? '').replace(/\x1b\[[0-9;]*m/g, '')
|
|
25
|
+
|
|
18
26
|
// Claude Code's tool names → HeartCode's (for --allowedTools / --disallowedTools).
|
|
19
|
-
const CLAUDE_TOOLS = { Read: 'read_file', Grep: 'search', Glob: 'list_files', LS: 'list_files', Edit: 'edit_file', MultiEdit: 'edit_file', Write: 'write_file', NotebookEdit: 'edit_file', Bash: 'run_command', BashOutput: 'background', KillShell: 'background', KillBash: 'background' }
|
|
27
|
+
const CLAUDE_TOOLS = { Read: 'read_file', Grep: 'search', Glob: 'list_files', LS: 'list_files', Edit: 'edit_file', MultiEdit: 'edit_file', Write: 'write_file', NotebookEdit: 'edit_file', Bash: 'run_command', BashOutput: 'background', KillShell: 'background', KillBash: 'background', WebFetch: 'web_fetch', WebSearch: 'web_search', TodoWrite: 'todo', Task: 'agent' }
|
|
20
28
|
export function toolNames(list) {
|
|
21
29
|
const names = list.flatMap((x) => String(x).split(/[,\s]+/)).filter(Boolean).map((t) => t.replace(/\(.*$/, '')) // ponytail: "Bash(git:*)" allows every command, not just git
|
|
22
30
|
return new Set(names.map((t) => CLAUDE_TOOLS[t] ?? t)) // mcp__server__tool and mcp__server as they are (tools.js allowed)
|
|
@@ -25,10 +33,24 @@ export function toolNames(list) {
|
|
|
25
33
|
// --permission-mode, in HeartCode's terms or Claude Code's.
|
|
26
34
|
export const PERMISSION_MODES = { all: 'all', commands: 'commands', ask: 'ask', bypassPermissions: 'all', acceptEdits: 'commands', default: 'ask', plan: 'plan', dontAsk: 'ask' }
|
|
27
35
|
|
|
28
|
-
// A UI that shows nothing and asks nobody.
|
|
36
|
+
// A UI that shows nothing and asks nobody; what the full screen would show goes to this.event (set
|
|
37
|
+
// by stream-json: a system message each) as data.
|
|
29
38
|
export class HeadlessUI {
|
|
30
39
|
constructor({ permission = 'all', verbose = false } = {}) {
|
|
31
|
-
Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true })
|
|
40
|
+
Object.assign(this, { permission, verbose, log: [], showThinking: true, full: false, noUser: true, event: null })
|
|
41
|
+
// helpers at work (agent.js: label → { id, model, what }): each change sent as a "helper" event
|
|
42
|
+
const ui = this
|
|
43
|
+
this.helpers = new (class extends Map {
|
|
44
|
+
set(label, v) {
|
|
45
|
+
ui.event?.({ subtype: 'helper', tool_use_id: v?.id ?? null, label, model: v?.model ?? null, status: v?.what ?? null })
|
|
46
|
+
return super.set(label, v)
|
|
47
|
+
}
|
|
48
|
+
delete(label) {
|
|
49
|
+
const v = this.get(label)
|
|
50
|
+
if (v) ui.event?.({ subtype: 'helper', tool_use_id: v.id ?? null, label, model: v.model ?? null, status: 'done' })
|
|
51
|
+
return super.delete(label)
|
|
52
|
+
}
|
|
53
|
+
})()
|
|
32
54
|
}
|
|
33
55
|
#err(text) {
|
|
34
56
|
if (this.verbose) process.stderr.write(`${text}\n`)
|
|
@@ -36,9 +58,28 @@ export class HeadlessUI {
|
|
|
36
58
|
warn(text) {
|
|
37
59
|
log('warn', text)
|
|
38
60
|
this.#err(`heartcode: ${text}`)
|
|
61
|
+
this.event?.({ subtype: 'warning', message: plain(text) })
|
|
39
62
|
}
|
|
40
63
|
retrying(err, ms, attempt) {
|
|
41
64
|
if (err) this.#err(`heartcode: retrying in ${Math.ceil(ms / 1000)}s (attempt ${attempt}): ${err.message}`)
|
|
65
|
+
if (err) this.event?.({ subtype: 'retry', attempt, delay_ms: ms, error: plain(err.message) })
|
|
66
|
+
}
|
|
67
|
+
// What it's doing now, as the spinner would say it: sent when it changes (a label that's a function,
|
|
68
|
+
// a running command's latest line: read once a second)
|
|
69
|
+
spinner(label) {
|
|
70
|
+
clearInterval(this.spinTimer)
|
|
71
|
+
const say = () => {
|
|
72
|
+
const text = plain(typeof label === 'function' ? label() : label)
|
|
73
|
+
// model: a helper's when it's that helper's ("<its job> · …"), else the main conversation's
|
|
74
|
+
const helper = [...this.helpers].find(([job]) => text.startsWith(`${job} · `))?.[1]
|
|
75
|
+
if (text && text !== this.said) this.event?.({ subtype: 'status', status: (this.said = text), model: helper?.model ?? this.waitingFor?.() ?? null })
|
|
76
|
+
}
|
|
77
|
+
say()
|
|
78
|
+
if (typeof label === 'function') this.spinTimer = setInterval(say, 1000).unref() // never what keeps a finished run going
|
|
79
|
+
}
|
|
80
|
+
stopSpin() {
|
|
81
|
+
clearInterval(this.spinTimer)
|
|
82
|
+
this.said = null
|
|
42
83
|
}
|
|
43
84
|
async confirm(question, kind = 'edit') {
|
|
44
85
|
if (this.permission === 'all' || (this.permission === 'commands' && kind === 'edit') || (this.permission === 'plan' && kind === 'read')) return true // plan: only reading
|
|
@@ -82,8 +123,6 @@ export class HeadlessUI {
|
|
|
82
123
|
async pick() {
|
|
83
124
|
return null
|
|
84
125
|
}
|
|
85
|
-
spinner() {}
|
|
86
|
-
stopSpin() {}
|
|
87
126
|
print() {}
|
|
88
127
|
write() {}
|
|
89
128
|
gap() {}
|
|
@@ -150,9 +189,14 @@ export async function runHeadless(app, opts) {
|
|
|
150
189
|
// its own arguments, not HeartCode's one mcp tool around them (a program reading it, Nibedita,
|
|
151
190
|
// knows its tools by those names).
|
|
152
191
|
const asClaude = (name, input) => (name === 'mcp' && input?.server && input?.tool ? { name: mcpName(String(input.server), String(input.tool)), input: input.arguments ?? {} } : { name, input })
|
|
153
|
-
let said =
|
|
192
|
+
let said = '' // the main conversation's last text sent as an assistant message
|
|
193
|
+
// why a reply ended, in Claude's words (stop_reason)
|
|
194
|
+
const STOP = { stop: 'end_turn', tool_calls: 'tool_use', function_call: 'tool_use', length: 'max_tokens', incomplete: 'max_tokens', content_filter: 'refusal', loop: 'end_turn' }
|
|
195
|
+
const stopOf = (r) => (r ? (STOP[r] ?? r) : null)
|
|
154
196
|
if (out === 'stream-json') {
|
|
155
197
|
if (opts.partial) app.ui.partial = (event) => emit({ type: 'stream_event', event, session_id, parent_tool_use_id: null }) // the replies as they come (--include-partial-messages)
|
|
198
|
+
app.ui.event = (e) => emit({ type: 'system', ...e, session_id })
|
|
199
|
+
app.ui.waitingFor = () => `${s.client.provider}/${s.client.model}` // the model at work now, on status events // the plan, helpers, reviews, model switches, warnings, retries, status
|
|
156
200
|
s.onEvent = (e) => {
|
|
157
201
|
if (e.type === 'assistant') {
|
|
158
202
|
const content = [
|
|
@@ -160,11 +204,11 @@ export async function runHeadless(app, opts) {
|
|
|
160
204
|
...(e.content ? [{ type: 'text', text: e.content }] : []),
|
|
161
205
|
...e.toolCalls.map((t) => ({ type: 'tool_use', id: t.id, ...asClaude(t.function.name, parseArgs(t.function.arguments)) })),
|
|
162
206
|
]
|
|
163
|
-
if (e.content && !e.parent) said =
|
|
207
|
+
if (e.content && !e.parent) said = e.content
|
|
164
208
|
// a helper's (agent) steps too, as Claude Code sends a subagent's: parent_tool_use_id is its agent call
|
|
165
|
-
if (content.length) emit({ type: 'assistant', message: { role: 'assistant', model: e.model ?? model, content }, parent_tool_use_id: e.parent ?? null, session_id })
|
|
209
|
+
if (content.length) emit({ type: 'assistant', message: { role: 'assistant', model: e.model ?? model, content, stop_reason: stopOf(e.stop) }, parent_tool_use_id: e.parent ?? null, session_id })
|
|
166
210
|
} else if (e.type === 'tool') {
|
|
167
|
-
emit({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: e.id, content: e.output, is_error: toolFailed(e.output) }] }, parent_tool_use_id: e.parent ?? null, session_id })
|
|
211
|
+
emit({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: e.id, content: e.output, is_error: toolFailed(e.output) }] }, model: e.model ?? null, parent_tool_use_id: e.parent ?? null, session_id }) // model: the one that made the call
|
|
168
212
|
}
|
|
169
213
|
}
|
|
170
214
|
if (s.strat.actions === 'tools' && s.mcp?.names.length) await loadMcpTools(s) // their tools are in the list, as in Claude Code's
|
|
@@ -180,7 +224,8 @@ export async function runHeadless(app, opts) {
|
|
|
180
224
|
usage = { input_tokens: 0, output_tokens: 0 }
|
|
181
225
|
byModel = {}
|
|
182
226
|
requests = 0
|
|
183
|
-
said =
|
|
227
|
+
said = ''
|
|
228
|
+
s.lastStop = null
|
|
184
229
|
current = { ctl: new AbortController() }
|
|
185
230
|
app.signal = current.ctl.signal
|
|
186
231
|
app.working = true // settings changed meanwhile: MCP servers and skills wait for the end of it
|
|
@@ -201,9 +246,11 @@ export async function runHeadless(app, opts) {
|
|
|
201
246
|
}
|
|
202
247
|
const subtype = current.maxTurns ? 'error_max_turns' : error ? 'error_during_execution' : 'success' // as Claude Code names them
|
|
203
248
|
current = null
|
|
204
|
-
const result = { type: 'result', subtype, is_error: Boolean(error), result: error ?? answer, num_turns: Math.max(1, requests), duration_ms: Date.now() - t0, total_cost_usd: (app.chat.usage?.cost ?? 0) - spent, usage, modelUsage: Object.keys(byModel).length ? byModel : { [model]: { inputTokens: 0, outputTokens: 0 } }, session_id }
|
|
249
|
+
const result = { type: 'result', subtype, is_error: Boolean(error), result: error ?? answer, stop_reason: error ? null : stopOf(s.lastStop ?? 'stop'), num_turns: Math.max(1, requests), duration_ms: Date.now() - t0, total_cost_usd: (app.chat.usage?.cost ?? 0) - spent, usage, modelUsage: Object.keys(byModel).length ? byModel : { [model]: { inputTokens: 0, outputTokens: 0 } }, session_id }
|
|
205
250
|
if (out === 'stream-json') {
|
|
206
|
-
|
|
251
|
+
// the answer as a reply of its own, unless it just went out as one (as it was: a cut-off answer is
|
|
252
|
+
// its pieces together; guided mode, an answer made after empty replies: never sent)
|
|
253
|
+
if (!error && answer && said.trim() !== answer.trim()) emit({ type: 'assistant', message: { role: 'assistant', model: `${s.client.provider}/${s.client.model}`, content: [{ type: 'text', text: answer }], stop_reason: stopOf(s.lastStop ?? 'stop') }, parent_tool_use_id: null, session_id })
|
|
207
254
|
emit(result)
|
|
208
255
|
} else if (out === 'json') emit(result)
|
|
209
256
|
else if (error) process.stderr.write(`heartcode: ${error}\n`)
|
package/src/log.js
CHANGED
|
@@ -147,7 +147,7 @@ const safe = (s) => String(s ?? '').replace(/[^\w.-]+/g, '_').slice(0, 60) || 'n
|
|
|
147
147
|
// firstTokenMs, usage, request, reply }. "full" keeps what was sent and what came back; "summary"
|
|
148
148
|
// only their sizes. API keys are never in it (they're headers, not the body).
|
|
149
149
|
export function logRequest(rec) {
|
|
150
|
-
if (!requestLog.on) return
|
|
150
|
+
if (!requestLog.on || process.env.HEART_LOG === 'off') return // HEART_LOG=off: no logs of any kind
|
|
151
151
|
try {
|
|
152
152
|
if (!requestLog.dir) {
|
|
153
153
|
let dir = path.join(REQUESTS, STAMP)
|