heartcode 0.1.45 → 0.1.56
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 +286 -0
- package/README.md +147 -126
- package/SKILL.md +16 -18
- package/bin/heartcode.js +146 -93
- package/package.json +2 -2
- package/prompts/README.md +1 -1
- package/prompts/agent.md +252 -352
- package/prompts/compact.md +24 -45
- package/prompts/guided.md +43 -67
- package/prompts/tests.md +15 -0
- package/src/acp.js +10 -5
- package/src/agent.js +211 -113
- package/src/check.js +411 -0
- package/src/client.js +25 -42
- package/src/config.js +10 -1
- package/src/guided.js +77 -26
- package/src/headless.js +31 -3
- package/src/log.js +1 -1
- package/src/lsp.js +10 -0
- package/src/mcp.js +30 -21
- package/src/prompts.js +1 -0
- package/src/reset.js +1 -1
- package/src/sessions.js +56 -17
- package/src/settings.html +296 -154
- package/src/settings.js +108 -43
- package/src/skills.js +42 -7
- package/src/tabs.js +6 -2
- package/src/tools.js +185 -56
- package/src/ui.js +449 -110
package/bin/heartcode.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { parseArgs } from 'node:util'
|
|
4
|
-
import { Client } from '../src/client.js'
|
|
5
|
-
import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION } from '../src/config.js'
|
|
4
|
+
import { Client, limitSaid, estMessages } from '../src/client.js'
|
|
5
|
+
import { loadConfig, saveConfig, readJson, writeJson, providerName, CONFIG_FILE, HOME, TEMP, AUTO_MODEL, isAuto, parseModel, takeIn, whatOf, VERSION, speedOf } from '../src/config.js'
|
|
6
6
|
import { loadProfile, strategy, describe, profilePath, profileFrom } from '../src/probe.js'
|
|
7
|
-
import { learnFromUsage, LIMIT_MS } from '../src/context.js'
|
|
7
|
+
import { learnFromUsage, LIMIT_MS, RATE_CAP_MS } from '../src/context.js'
|
|
8
8
|
import { Session, transcript, contextReport } from '../src/agent.js'
|
|
9
9
|
import { listJobs, getJob, stopJob, removeJob, runningJobs, tailLines, ago as ranFor } from '../src/background.js'
|
|
10
10
|
import { checkUpdate, installKind, UPDATE_COMMANDS, packageDir, whatsNew } from '../src/update.js'
|
|
11
11
|
import { treeItems, codePlan, move, leaving, leftText, leftFiles } from '../src/tree.js'
|
|
12
|
-
import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width } from '../src/ui.js'
|
|
12
|
+
import { UI, c, PERMISSIONS, duration, copyText, rank, setTheme, themeCodes, renderDiff, diffLines, DEFAULT_KEYS, loadKeys, width, shortError, wrapWords } from '../src/ui.js'
|
|
13
13
|
import { listFiles, runCommand, clip } from '../src/tools.js'
|
|
14
14
|
import { notify } from '../src/telegram.js'
|
|
15
15
|
import { log, LOG_FILE, LOG_DIR, requestLog, useRequestLog, useLogs, pruneLogs, logDays } from '../src/log.js'
|
|
@@ -57,7 +57,7 @@ ${c.bold('options')}
|
|
|
57
57
|
--api-key <key> API key for --base-url
|
|
58
58
|
-y, --yes do everything without asking (the default)
|
|
59
59
|
--ask ask before every edit and command, this run
|
|
60
|
-
--hide-thinking
|
|
60
|
+
--hide-thinking the model's thinking: only its last two lines while it thinks (the default; Alt+O shows all of it)
|
|
61
61
|
-C, --cwd <dir> project folder (default: current folder)
|
|
62
62
|
--temp keep nothing: a throwaway settings folder (your providers, model info,
|
|
63
63
|
prices and notes copied in), shared by the --temp runs going on at once
|
|
@@ -80,7 +80,6 @@ ${c.bold('headless')} (for other programs; flags and output as in Claude Code's
|
|
|
80
80
|
--skills-dir <dir> more skills (repeatable)
|
|
81
81
|
--allowedTools <list> only these tools (HeartCode's or Claude Code's names: Read, Edit, Bash…)
|
|
82
82
|
--disallowedTools <list> never these tools
|
|
83
|
-
--model-choice <order|fit> your models' order (#1, then the next), or fit: an orchestrator hands each task out
|
|
84
83
|
--permission-mode <m> all, commands, ask, plan (or bypassPermissions, acceptEdits, default);
|
|
85
84
|
--dangerously-skip-permissions = all. Nothing is asked: the rest is declined
|
|
86
85
|
--session-id <id> start (or continue) the session with this id
|
|
@@ -104,7 +103,7 @@ const SECTIONS = [
|
|
|
104
103
|
['/select_model', 'pick the model(s) for this session: one pins it, several rotate among them, auto = your whole list', true],
|
|
105
104
|
]],
|
|
106
105
|
['settings', [
|
|
107
|
-
['/toggle_thinking', "
|
|
106
|
+
['/toggle_thinking', "the model's thinking: its last two lines, or all of it (Alt+O)"],
|
|
108
107
|
['/voice', 'say your message (or Space in an empty box): it shows in the box as you speak, Enter sends it, Esc cancels'],
|
|
109
108
|
]],
|
|
110
109
|
['session', [
|
|
@@ -145,7 +144,7 @@ const COMMANDS = SECTIONS.flatMap(([, list]) => list).sort(byName)
|
|
|
145
144
|
// Typed while a task works, these run at once, beside it: they leave the conversation alone. The
|
|
146
145
|
// others (/compact, /rewind, /resume, /init…) wait in the queue until it's done.
|
|
147
146
|
const RIGHT_AWAY = new Set(['help', 'cost', 'context', 'background', 'model_info', 'diff', 'copy', 'mcp', 'doctor', 'toggle_thinking', 'btw', 'rename', 'export', 'tab', 'close_tab', 'exit', 'quit', 'settings', 'login_mcp', 'install_skill', 'import', 'voice', 'select_model'])
|
|
148
|
-
const helpText = (sections) => sections.map(([title, list]) => ` ${c.bold(title)}\n` + list.map(([n, d]) => ` ${c.cyan(n.padEnd(
|
|
147
|
+
const helpText = (sections) => sections.map(([title, list]) => ` ${c.bold(title)}\n` + list.map(([n, d]) => ` ${c.cyan(n.padEnd(17))} ${d}`).join('\n')).join('\n\n')
|
|
149
148
|
const SLASH = helpText(SECTIONS)
|
|
150
149
|
|
|
151
150
|
// The keyboard shortcuts, as [keys, what] rows, read from the effective keybindings (keybindings.json
|
|
@@ -158,7 +157,7 @@ function keysHelp(keys = {}, mouse = false) {
|
|
|
158
157
|
const rows = [
|
|
159
158
|
['Space', 'voice: listens at once, Enter sends what you said (in an empty box)'],
|
|
160
159
|
['Enter', 'send · while it works, queue the message (commands like /help, /cost, /select_model run at once)'],
|
|
161
|
-
['Option
|
|
160
|
+
['Option+Enter or Shift+Enter', 'new line in the box'],
|
|
162
161
|
['Esc', 'stop the task (press twice to confirm)'],
|
|
163
162
|
['Esc Esc', 'rewind to an earlier message (at the prompt)'],
|
|
164
163
|
['Shift+Tab', 'change what runs without asking (permissions)'],
|
|
@@ -178,7 +177,7 @@ function keysHelp(keys = {}, mouse = false) {
|
|
|
178
177
|
[mouse ? 'Drag' : '', 'select and copy: the conversation, a dialog, the folder, the input, the status bar'],
|
|
179
178
|
[mouse ? 'Double-click' : '', 'copy the word under it (an address, a path, a model)'],
|
|
180
179
|
[mouse ? (process.platform === 'darwin' ? 'Option+drag' : 'Shift+drag') : '', "the terminal's own selection, past HeartCode's"],
|
|
181
|
-
[mouse ? '' : 'Mouse', 'the terminal\'s own: select and copy as usual (HeartCode takes the mouse
|
|
180
|
+
[mouse ? '' : 'Mouse', 'the terminal\'s own: select and copy as usual (switch "HeartCode takes the mouse" on in /settings → General for the wheel to scroll only the conversation)'],
|
|
182
181
|
].filter(([k]) => k)
|
|
183
182
|
return rows
|
|
184
183
|
}
|
|
@@ -194,7 +193,7 @@ const ALL_OFF = `${c.yellow('The providers of all your models are switched off.'
|
|
|
194
193
|
// Choices for commands that take one (also offered in the "/" menu).
|
|
195
194
|
const ARGS = {
|
|
196
195
|
export: [['md', 'Markdown'], ['html', 'a web page'], ['json', 'the whole session file']],
|
|
197
|
-
set_effort: [['default',
|
|
196
|
+
set_effort: [['default', 'low: a little thinking, shown as it comes'], ['low', 'quick, less thinking'], ['medium', 'balanced'], ['high', 'thinks the longest']],
|
|
198
197
|
}
|
|
199
198
|
|
|
200
199
|
|
|
@@ -224,8 +223,6 @@ class App {
|
|
|
224
223
|
this.memory = new Memory(root) // .heartcode/memory: notes linked with [[name]]
|
|
225
224
|
this.director = new Director(this) // the manage tool: skills, MCP servers and settings by asking
|
|
226
225
|
this.later = [] // setting changes that wait until the current message is done
|
|
227
|
-
this.failures = {} // "provider model" → failed requests this session (engine: onFail)
|
|
228
|
-
this.resting = {} // "provider model" → until when it's out of quota (the server said so: engine: onFail)
|
|
229
226
|
this.loadProjectModels() // the model(s) you last chose for this folder (.heartcode/models.json)
|
|
230
227
|
}
|
|
231
228
|
|
|
@@ -306,7 +303,7 @@ class App {
|
|
|
306
303
|
case 'effort':
|
|
307
304
|
if (!ARGS.set_effort.some(([o]) => o === v)) return bad('default, low, medium or high')
|
|
308
305
|
cfg.effort = v === 'default' ? undefined : v
|
|
309
|
-
if (this.s?.strat.thinking) this.s.client.effort = cfg
|
|
306
|
+
if (this.s?.strat.thinking) this.s.client.effort = effortOf(cfg)
|
|
310
307
|
return save(`effort: ${v}`)
|
|
311
308
|
case 'auto_compact':
|
|
312
309
|
case 'director':
|
|
@@ -328,27 +325,52 @@ class App {
|
|
|
328
325
|
}
|
|
329
326
|
|
|
330
327
|
// The model, its probe and strategy for a provider and model (probed once, then cached).
|
|
331
|
-
// quiet: for a helper
|
|
328
|
+
// quiet: for a helper: nothing printed about the model, the settings left alone.
|
|
332
329
|
async engine(provider, model, ui, signal, { quiet = false } = {}) {
|
|
333
330
|
const { cfg } = this
|
|
334
331
|
const client = this.client(provider, model)
|
|
335
332
|
let price = null
|
|
336
333
|
// tokens and cost, into the chat (also a helper's, the probe's, compaction's)
|
|
337
334
|
client.price = () => price
|
|
338
|
-
|
|
335
|
+
let failed = null // { t, e }: the failure that made the model list move on (said with the model that answered)
|
|
336
|
+
let ok = false // a reply came since it
|
|
337
|
+
const spend = (u) => addUsage((this.chat.usage ??= {}), u, price)
|
|
338
|
+
// serverCount: the conversation's last request size (lastTokens) is the server's, not HeartCode's estimate (/context)
|
|
339
|
+
client.onSpend = function (u) {
|
|
340
|
+
if ((this.purpose ?? 'chat') === 'chat') this.serverCount = Boolean(u.total_tokens)
|
|
341
|
+
ok = true
|
|
342
|
+
spend(u)
|
|
343
|
+
}
|
|
339
344
|
client.onRetry = (err, ms, attempt, next) => ui.retrying(err, ms, attempt, next) // keep trying until Esc (also while probing)
|
|
340
|
-
//
|
|
341
|
-
// are tried in that order
|
|
345
|
+
// a failed request: what it says about the model's limits is learned
|
|
342
346
|
client.onFail = (e, t) => {
|
|
343
347
|
if (e.name === 'AbortError') return
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
348
|
+
if (ok) [failed, ok] = [null, false] // the first failure since a reply: why the list moves on (onSwitch)
|
|
349
|
+
failed ??= { t, e }
|
|
350
|
+
// "too large" with the limit stated (Groq: "Limit 2000 … tokens per minute"): kept in its profile,
|
|
351
|
+
// so it isn't sent what it can't take
|
|
352
|
+
const said = limitSaid(e)
|
|
353
|
+
if (said) {
|
|
354
|
+
const cl = this.client(t.provider, t.model)
|
|
355
|
+
const p = loadProfile(cl) || profileFrom(cl, limitsOf(t.provider, cl.baseUrl, t.model))
|
|
356
|
+
if (said.rate) p.rateCap = { tokens: said.tokens, until: Date.now() + RATE_CAP_MS }
|
|
357
|
+
else Object.assign(p, { inputLimit: said.tokens, inputLimitAt: Date.now() })
|
|
358
|
+
writeJson(profilePath(cl), p)
|
|
359
|
+
log('context', `${t.provider}/${t.model}: ${said.rate ? 'a per-minute cap' : 'a request limit'} of ${said.tokens} tokens, from its provider`)
|
|
360
|
+
}
|
|
347
361
|
}
|
|
348
362
|
// the model list (settings page): another model answered
|
|
363
|
+
// told once the reply that came is closed (it's known before the reply's last line ends: it'd go on
|
|
364
|
+
// that line): the agent says it then (announceSwitch), else right after
|
|
365
|
+
let switched = null
|
|
366
|
+
client.announceSwitch = () => switched && (ui.print(switched), (switched = null))
|
|
349
367
|
client.onSwitch = (t) => {
|
|
350
368
|
const i = client.rotation.list.indexOf(t)
|
|
351
|
-
|
|
369
|
+
const f = failed?.e
|
|
370
|
+
const why = f ? `${failed.t.model} ${f.status === 429 ? 'rate-limited (429)' : `failed (${clip(shortError(f), 50)})`} → ` : ''
|
|
371
|
+
failed = null
|
|
372
|
+
switched = c.dim(`↻ ${why}${t.provider} · ${t.model} answered${i ? ` (#${i + 1} in your model list)` : ' (#1 again)'}`)
|
|
373
|
+
setImmediate(client.announceSwitch)
|
|
352
374
|
}
|
|
353
375
|
if (cfg.maxRetries !== undefined) client.retryIf = (e, attempt) => attempt < cfg.maxRetries // headless: then give up
|
|
354
376
|
let profile = await getProfile(client, ui, quiet)
|
|
@@ -359,7 +381,7 @@ class App {
|
|
|
359
381
|
const apply = () => {
|
|
360
382
|
for (const k of Object.keys(strat)) delete strat[k]
|
|
361
383
|
Object.assign(strat, strategy(profile, cfg))
|
|
362
|
-
Object.assign(client, { tokenRatio: profile.tokenRatio ?? 1, knownGood: profile.largestAccepted ?? 0, can: strat, effort: strat.thinking ? cfg
|
|
384
|
+
Object.assign(client, { tokenRatio: profile.tokenRatio ?? 1, knownGood: profile.largestAccepted ?? 0, can: strat, effort: strat.thinking ? effortOf(cfg) : undefined })
|
|
363
385
|
for (const [q, at] of Object.entries(profile.quirks ?? {})) if (Date.now() - at < LIMIT_MS) client.quirks[q] = true
|
|
364
386
|
price = priceOf(client.provider, client.baseUrl, client.model)
|
|
365
387
|
if (this.s?.client === client) this.s.profile = profile // /model_info, the settings page
|
|
@@ -379,7 +401,9 @@ class App {
|
|
|
379
401
|
// to the window (a command can run for minutes). Nothing goes on with an old copy.
|
|
380
402
|
client.refresh = () => {
|
|
381
403
|
syncSettings()
|
|
382
|
-
|
|
404
|
+
const speed = speedOf(this.cfg) // the settings page's seconds (config.js)
|
|
405
|
+
client.startMs = 1000 * speed.replyStart // a reply must start within this, else the next model
|
|
406
|
+
client.idleMs = 1000 * speed.replyIdle // a reply that stops sending for this long: stalled
|
|
383
407
|
if (stampOf(profilePath(client)) !== stamp) client.onUse({ provider: client.provider, model: client.model })
|
|
384
408
|
}
|
|
385
409
|
// What this run learned about the model, onto its file as it is now: the rest (what you set up for
|
|
@@ -435,7 +459,7 @@ class App {
|
|
|
435
459
|
|
|
436
460
|
setChat(chat) {
|
|
437
461
|
this.chat = chat
|
|
438
|
-
if (this.s) this.s
|
|
462
|
+
if (this.s) Object.assign(this.s, { chat, counted: null, compactFailedAt: 0 }) // the last chat's token count and failed compaction aren't this one's
|
|
439
463
|
}
|
|
440
464
|
|
|
441
465
|
save() {
|
|
@@ -609,7 +633,7 @@ class App {
|
|
|
609
633
|
const mine = this.commands().slice(COMMANDS.length)
|
|
610
634
|
const sections = [...SECTIONS]
|
|
611
635
|
if (mine.length) sections.push(['your skills (type /skill:name)', mine])
|
|
612
|
-
sections.push(['keyboard', keysHelp(this.ui.keys, this.cfg?.mouse
|
|
636
|
+
sections.push(['keyboard', keysHelp(this.ui.keys, this.cfg?.mouse !== false)])
|
|
613
637
|
return helpText(sections)
|
|
614
638
|
}
|
|
615
639
|
|
|
@@ -674,23 +698,22 @@ class App {
|
|
|
674
698
|
const rot = this.s?.client.rotation
|
|
675
699
|
const now = this.inUse() // the model list's one in use; never one of a provider that's off
|
|
676
700
|
if (!now) return c.dim('the providers of all your models are off · /settings to switch one on')
|
|
677
|
-
const on = Object.values(cfg.providers).filter((p) => !p.off).length
|
|
678
701
|
const count = this.sessionModels().length
|
|
679
702
|
// the model answering now; a yellow "↻" before it when it's a fallback (rotated to after one failed)
|
|
680
703
|
const rotated = rot && rot.at > 0
|
|
681
704
|
const name = rotated ? c.yellow('↻ ' + now.model) : c.info(now.model)
|
|
682
705
|
const model =
|
|
683
|
-
count === 1 ? name : cfg.session ? `${name} ${c.faint(`(${count} chosen)`)}` : `${c.muted(
|
|
706
|
+
count === 1 ? name : cfg.session ? `${name} ${c.faint(`(${count} chosen)`)}` : `${c.muted('auto')} ${c.faint('(')}${name}${c.faint(')')} ${c.faint(`(${count} models)`)}`
|
|
684
707
|
const key = `${now.provider}/${now.model}`
|
|
685
708
|
if (this.profileKey !== key) [this.profileKey, this.profile] = [key, this.s?.profile ?? loadProfile(this.client(now.provider, now.model))]
|
|
686
709
|
const profile = this.s?.profile ?? this.profile
|
|
687
710
|
const strat = profile && (this.s?.strat ?? strategy(profile, cfg))
|
|
688
711
|
// each item, rendered (or null when it doesn't apply)
|
|
689
712
|
const parts = {
|
|
690
|
-
provider: `${c.brand('●')} ${c.muted(now.provider)}
|
|
713
|
+
provider: `${c.brand('●')} ${c.muted(now.provider)}`,
|
|
691
714
|
model,
|
|
692
|
-
mode: strat ?
|
|
693
|
-
thinking: strat?.thinking ? c.think(`thinking
|
|
715
|
+
mode: strat ? (strat.actions === 'tools' ? null : c.muted('no tool calls (guided)')) : c.faint('checked at your first message'), // what it can do: known once it's been asked
|
|
716
|
+
thinking: strat?.thinking ? c.think(`thinking · ${effortOf(cfg)}`) + (ui.showThinking ? c.faint(' (all)') : '') : null,
|
|
694
717
|
images: strat?.vision ? c.muted('images') : null,
|
|
695
718
|
ctx: null,
|
|
696
719
|
tps: null,
|
|
@@ -702,7 +725,7 @@ class App {
|
|
|
702
725
|
permissions: { all: c.green('⏵⏵ all allowed'), commands: c.yellow('ask before commands'), ask: c.yellow('ask before changes'), plan: c.info('⏸ plan mode') }[ui.permission],
|
|
703
726
|
}
|
|
704
727
|
if (strat) {
|
|
705
|
-
const used = this.s?.client.lastTokens ??
|
|
728
|
+
const used = this.s?.client.lastTokens || Math.round(estMessages(this.chat?.messages ?? []) * (strat.ratio ?? 1)) // a resumed chat before its first request: estimated
|
|
706
729
|
const pct = Math.round((used / strat.context) * 100)
|
|
707
730
|
const paint = pct >= 80 ? c.red : pct >= 50 ? c.yellow : c.green
|
|
708
731
|
const guess = strat.contextSure ? '' : '~' // not said by the server: assumed, and growing as bigger requests work
|
|
@@ -779,8 +802,6 @@ class App {
|
|
|
779
802
|
Object.assign(this.s, { noFormat: cfg.format === false, noLsp: cfg.lsp === false })
|
|
780
803
|
Object.assign(this.s, { mcp: this.mcp, memory: this.memory, skills: this.skills, director: this.director })
|
|
781
804
|
this.s.team = () => this.team() // your other models: a job this one can't do goes to one of them
|
|
782
|
-
this.s.fitMode = () => fitMode(this.cfg) // an orchestrator hands each message's work out, not your list's order
|
|
783
|
-
this.s.orchestrators = () => this.orchestrators()
|
|
784
805
|
this.s.engineFor = (t) => this.engine(t.provider, t.model, ui, undefined, { quiet: true })
|
|
785
806
|
// A model's context window, read from its saved profile (no probe, no network): so the agent can
|
|
786
807
|
// see, before compacting, whether another model in the list has room for the whole conversation.
|
|
@@ -793,8 +814,6 @@ class App {
|
|
|
793
814
|
return 0
|
|
794
815
|
}
|
|
795
816
|
}
|
|
796
|
-
this.s.failures = this.failures
|
|
797
|
-
this.s.resting = this.resting
|
|
798
817
|
if (this.allowTools?.length) this.s.allowTools = toolNames(this.allowTools) // headless --allowedTools
|
|
799
818
|
if (this.denyTools?.length) this.s.denyTools = toolNames(this.denyTools)
|
|
800
819
|
if (this.cfg.maxTurns) this.s.maxTurns = this.cfg.maxTurns
|
|
@@ -811,7 +830,6 @@ class App {
|
|
|
811
830
|
.filter((t) => cfg.providers[t.provider] && t.model && !seen.has(`${t.provider}/${t.model}`) && seen.add(`${t.provider}/${t.model}`))
|
|
812
831
|
.map((t) => ({ ...t, baseUrl: cfg.providers[t.provider].baseUrl, apiKey: cfg.providers[t.provider].apiKey }))
|
|
813
832
|
this.s?.client.setRotation(list, cfg.rotation ?? {})
|
|
814
|
-
if (fitMode(cfg)) this.s?.client.orderBy(this.orchestrators().map((t) => `${t.provider} ${t.model}`)) // the first orchestrator answers first (and the status bar shows it)
|
|
815
833
|
}
|
|
816
834
|
|
|
817
835
|
async use(name, model) {
|
|
@@ -822,27 +840,17 @@ class App {
|
|
|
822
840
|
await this.session()
|
|
823
841
|
}
|
|
824
842
|
|
|
825
|
-
// Your other models (not the one in use) and what each can do, from its saved
|
|
826
|
-
// models.dev: nothing is sent to them to find out.
|
|
843
|
+
// Your other models (not the one in use), in your order, and what each can do, from its saved
|
|
844
|
+
// profile or models.dev: nothing is sent to them to find out.
|
|
827
845
|
team() {
|
|
828
846
|
// helpers use this session's models (the set you chose, else your list), minus the one in use —
|
|
829
|
-
// so a pinned single model gives no team, and a chosen set keeps helpers within it
|
|
830
|
-
// orchestrates: minus the orchestrators too (they only hand work out)
|
|
847
|
+
// so a pinned single model gives no team, and a chosen set keeps helpers within it
|
|
831
848
|
const now = this.s?.client.rotation?.list[this.s.client.rotation.at] ?? this.sessionModels()[0]
|
|
832
|
-
const lead = this.s?.orchestrating ? this.orchestrators() : []
|
|
833
849
|
return this.sessionModels()
|
|
834
|
-
.filter((t) => !
|
|
850
|
+
.filter((t) => !(t.provider === now?.provider && t.model === now?.model))
|
|
835
851
|
.map((t) => ({ ...t, ...this.abilities(t) }))
|
|
836
852
|
}
|
|
837
853
|
|
|
838
|
-
// The models that orchestrate (Pick: "an orchestrator hands it out"): those picked on Your models
|
|
839
|
-
// that are in this session's set and call tools; none picked: your first that calls tools.
|
|
840
|
-
orchestrators() {
|
|
841
|
-
const mine = this.sessionModels().filter((t) => this.abilities(t).tools)
|
|
842
|
-
const picked = mine.filter((t) => (this.cfg.orchestrators ?? []).some((o) => o.provider === t.provider && o.model === t.model))
|
|
843
|
-
return picked.length ? picked : mine.slice(0, 1)
|
|
844
|
-
}
|
|
845
|
-
|
|
846
854
|
// What a model can do, from its saved profile or models.dev (guessed: neither knows it).
|
|
847
855
|
abilities(t) {
|
|
848
856
|
const cl = this.client(t.provider, t.model)
|
|
@@ -859,7 +867,7 @@ class App {
|
|
|
859
867
|
// "tools · images · thinking · 1M", for the model lists.
|
|
860
868
|
canText(t) {
|
|
861
869
|
const a = this.abilities(t)
|
|
862
|
-
return [a.tools ? 'tools' : 'no tools', a.images && 'images', a.thinking && 'thinking',
|
|
870
|
+
return [a.tools ? 'tools' : 'no tools', a.images && 'images', a.thinking && 'thinking', (a.guessed ? '~' : '') + kTokens(a.context)].filter(Boolean).join(' · ')
|
|
863
871
|
}
|
|
864
872
|
|
|
865
873
|
// Your models, in order: this one (#1), then the fallbacks (chosen on /settings, where every
|
|
@@ -872,7 +880,7 @@ class App {
|
|
|
872
880
|
const rot = this.s?.client.rotation
|
|
873
881
|
if (rot) return rot.list[rot.at]
|
|
874
882
|
if (this.s) return { provider: this.s.client.provider, model: this.s.client.model }
|
|
875
|
-
return
|
|
883
|
+
return this.sessionModels()[0] ?? null
|
|
876
884
|
}
|
|
877
885
|
|
|
878
886
|
// your list has models, but the providers of all of them are switched off
|
|
@@ -950,7 +958,7 @@ class App {
|
|
|
950
958
|
},
|
|
951
959
|
draw: (w, h) => {
|
|
952
960
|
const all = jobs()
|
|
953
|
-
if (!all.length) return ['',
|
|
961
|
+
if (!all.length) return ['', ...wrapWords('Nothing runs in the background. The model starts servers and watchers there.', w - 2).map((l) => ` ${c.faint(l.trim())}`), '', ` ${c.faint('Esc close')}`]
|
|
954
962
|
const job = current()
|
|
955
963
|
this.jobTab = job.id
|
|
956
964
|
// the tabs, scrolled so the one shown is on screen
|
|
@@ -978,7 +986,7 @@ class App {
|
|
|
978
986
|
return [
|
|
979
987
|
bar + (hidden ? c.faint(` +${hidden} more`) : ''),
|
|
980
988
|
c.ghost('─'.repeat(w)),
|
|
981
|
-
` ${c.bold(clip(job.command, w -
|
|
989
|
+
` ${c.bold(clip(job.command, Math.max(10, w - 2 - width(` · ${state} · ${ranFor(job)}${where}`.replace(/\x1b\[[0-9;]*m/g, '')))))} ${c.faint('·')} ${state} ${c.faint(`· ${ranFor(job)}`)}${where}`, // the command, as much as the rest leaves room for
|
|
982
990
|
...Array.from({ length: n }, (_, i) => (shown.length ? (shown[i] === undefined ? '' : ` ${ERROR.test(shown[i]) ? c.red(shown[i]) : c.muted(shown[i])}`) : i ? '' : ` ${c.faint('(no output yet)')}`)),
|
|
983
991
|
c.ghost('─'.repeat(w)),
|
|
984
992
|
` ${said ? c.yellow(said) : c.faint(`${all.length > 1 ? '←/→ another one · ' : ''}↑/↓ PgUp/PgDn scroll · K ${job.exited ? 'close' : 'stop'} it · Esc close`)}`,
|
|
@@ -1013,7 +1021,8 @@ class App {
|
|
|
1013
1021
|
this.saveProjectModels()
|
|
1014
1022
|
this.s = null
|
|
1015
1023
|
}
|
|
1016
|
-
const
|
|
1024
|
+
const n = this.myModels().length
|
|
1025
|
+
const msg = `${c.green('using')} ${c.dim('auto')} ${c.cyan(`(${n} model${n === 1 ? '' : 's'})`)}`
|
|
1017
1026
|
if (later) return this.later.push(apply), this.ui.print(`${msg} ${c.dim('· from your next message')}`)
|
|
1018
1027
|
apply()
|
|
1019
1028
|
this.ui.print(msg)
|
|
@@ -1033,8 +1042,9 @@ class App {
|
|
|
1033
1042
|
const chosen = new Set((cfg.session ?? mine).map(key)) // pre-ticked: this session's set, or all (auto)
|
|
1034
1043
|
const items = mine.map((t) => ({ label: t.model, t, checked: chosen.has(key(t)), desc: this.modelDesc(t, mine.indexOf(t)) }))
|
|
1035
1044
|
// first, standing alone: back to auto (Enter on it, whatever is ticked)
|
|
1036
|
-
const auto = { label: 'auto', only: true, auto: true, desc: `your whole list, in its order (${mine.length}
|
|
1037
|
-
const
|
|
1045
|
+
const auto = { label: 'auto', only: true, auto: true, desc: `your whole list, in its order (${mine.length} model${mine.length === 1 ? '' : 's'})${cfg.session ? ' · forgets what this folder picked' : ' · in use'}` }
|
|
1046
|
+
const guessed = mine.some((t) => this.abilities(t).guessed) ? "\n~128k and the like: the window's size is a guess (models.dev doesn't list the model)" : ''
|
|
1047
|
+
const picked = await ui.pick('Models for this session', [auto, ...items], { filter, multi: true, body: `Tick several to rotate among them, one to pin it, or choose auto.${guessed}` })
|
|
1038
1048
|
if (!picked) return
|
|
1039
1049
|
if (picked.some((it) => it.auto)) return cfg.session ? this.auto(later) : ui.print(c.dim('already on auto'))
|
|
1040
1050
|
const list = picked.map((it) => it.t)
|
|
@@ -1148,7 +1158,7 @@ function saveTabs(tabs) {
|
|
|
1148
1158
|
// last session here.
|
|
1149
1159
|
async function continueTabs(app, saved) {
|
|
1150
1160
|
const { ui, tabs } = app
|
|
1151
|
-
let open = (saved?.tabs ?? []).map((t, i) => ({ ...t, i, chat: loadChat(t.chat) })).filter((t) => t.chat?.turns?.length && (!t.worktree || fs.existsSync(t.chat.root)))
|
|
1161
|
+
let open = (saved?.tabs ?? []).map((t, i) => ({ ...t, i, chat: loadChat(t.chat, app.root) })).filter((t) => t.chat?.turns?.length && (!t.worktree || fs.existsSync(t.chat.root)))
|
|
1152
1162
|
if (!saved) open = listChats(app.root).filter((c) => c.turns?.length).slice(0, 1).map((chat) => ({ chat, worktree: null }))
|
|
1153
1163
|
if (!open.length) return
|
|
1154
1164
|
const many = open.length > 1
|
|
@@ -1156,7 +1166,7 @@ async function continueTabs(app, saved) {
|
|
|
1156
1166
|
const go = await ui.pick(many ? `Continue where you left off? ${open.length} tabs` : 'Continue your last session here?', [
|
|
1157
1167
|
{ label: many ? `Yes, with its ${open.length} tabs` : 'Yes', desc: `${open.map((t) => `"${t.chat.title}"`).join(', ')} · ${ago(newest)}`, yes: true },
|
|
1158
1168
|
{ label: 'No, start a new session', desc: '/resume finds it later' },
|
|
1159
|
-
], { quiet: true })
|
|
1169
|
+
], { quiet: true, fixed: true })
|
|
1160
1170
|
if (!go?.yes) return
|
|
1161
1171
|
// this tab takes the first one in this folder; the rest (and worktree ones) open as tabs
|
|
1162
1172
|
const here = open.find((t) => !t.worktree) ?? null
|
|
@@ -1190,9 +1200,9 @@ let settingsPage = null
|
|
|
1190
1200
|
|
|
1191
1201
|
// The browser, with a page. Windows: its URL handler (cmd's start mangles a URL whose arguments
|
|
1192
1202
|
// it reads as its own, and wants a quoted empty title first).
|
|
1193
|
-
//
|
|
1194
|
-
|
|
1195
|
-
const
|
|
1203
|
+
// The thinking effort asked of a model that thinks: yours, or low when you haven't chosen (many think
|
|
1204
|
+
// only when asked: then they think a little, and you see it)
|
|
1205
|
+
const effortOf = (cfg) => cfg.effort ?? 'low'
|
|
1196
1206
|
|
|
1197
1207
|
function openBrowser(url) {
|
|
1198
1208
|
if (process.env.HEART_NO_BROWSER) return
|
|
@@ -1214,7 +1224,7 @@ function applySettings(apps, cfg, what) {
|
|
|
1214
1224
|
const { ui } = app
|
|
1215
1225
|
const busy = Boolean(ui.busySince || app.working)
|
|
1216
1226
|
const now = (fn) => (busy ? app.later.push(fn) : fn())
|
|
1217
|
-
if (app.cfg !== cfg) for (const k of ['providers', 'provider', 'model', 'effort', 'theme', 'context', 'autoCompact', 'director', 'format', 'lsp', 'voice', 'rotation', 'statusBar'
|
|
1227
|
+
if (app.cfg !== cfg) for (const k of ['providers', 'provider', 'model', 'effort', 'theme', 'context', 'autoCompact', 'director', 'format', 'lsp', 'voice', 'rotation', 'statusBar']) app.cfg[k] = cfg[k]
|
|
1218
1228
|
// a model pinned in this CLI (/select_model) is a session choice: a model/order change on the
|
|
1219
1229
|
// settings page leaves it alone (only /select_model auto here returns it to the list)
|
|
1220
1230
|
if (what === 'model' && !app.cfg.session) {
|
|
@@ -1222,17 +1232,18 @@ function applySettings(apps, cfg, what) {
|
|
|
1222
1232
|
if (app.s && !(cfg.providers[cfg.provider] && cfg.model)) now(() => ((app.s = null), ui.print(c.dim('settings: no model chosen'))))
|
|
1223
1233
|
else if (app.s && !app.myModels().length) now(() => ((app.s = null), ui.print(c.dim('settings: the providers of all your models are switched off'))))
|
|
1224
1234
|
}
|
|
1225
|
-
// your model list: into the running session now, its next request goes to the new #1
|
|
1226
|
-
if (['model', 'setting:rotation'
|
|
1235
|
+
// your model list: into the running session now, its next request goes to the new #1
|
|
1236
|
+
if (['model', 'setting:rotation'].includes(what) && !app.cfg.session && app.s && cfg.providers[cfg.provider] && cfg.model) {
|
|
1227
1237
|
const was = `${app.s.client.provider} · ${app.s.client.model}`
|
|
1228
1238
|
app.useRotation()
|
|
1229
1239
|
const is = `${app.s.client.provider} · ${app.s.client.model}`
|
|
1230
1240
|
if (is !== was) ui.print(c.dim(`settings: ${is} now`))
|
|
1231
1241
|
}
|
|
1232
1242
|
if (what === 'provider') app.lists = {} // its list switched on or off, a model added by name
|
|
1233
|
-
if (what === 'setting:permissions') ui.setPermission(cfg.permissions)
|
|
1243
|
+
if (what === 'setting:permissions' && !ui.noUser) ui.setPermission(cfg.permissions) // -p and ACP keep the mode they were given (--permission-mode, the editor's)
|
|
1244
|
+
if (what === 'setting:mouse') ui.setMouse(cfg.mouse !== false)
|
|
1234
1245
|
if (what === 'setting:statusBar') ui.render?.() // the status bar's layout changed: redraw it now
|
|
1235
|
-
if (what === 'setting:effort' && app.s?.strat.thinking) app.s.client.effort = cfg
|
|
1246
|
+
if (what === 'setting:effort' && app.s?.strat.thinking) app.s.client.effort = effortOf(cfg)
|
|
1236
1247
|
if (what === 'setting:autoCompact' && app.s) app.s.autoCompact = cfg.autoCompact !== false
|
|
1237
1248
|
if (what === 'setting:format' && app.s) app.s.noFormat = cfg.format === false
|
|
1238
1249
|
if (what === 'setting:lsp' && app.s) app.s.noLsp = cfg.lsp === false
|
|
@@ -1568,7 +1579,7 @@ async function slash(app, line, working = false) {
|
|
|
1568
1579
|
ui.showText(
|
|
1569
1580
|
'Context',
|
|
1570
1581
|
[
|
|
1571
|
-
`${c.muted(`~${kTokens(r.total)} of ${kTokens(r.window)} (${share(r.total)}) · ${s.client.model}`)}${r.counted ? c.faint(` · the last request, as the server counted it: ${kTokens(r.counted)}`) : ''}`,
|
|
1582
|
+
`${c.muted(`~${kTokens(r.total)} of ${kTokens(r.window)} (${share(r.total)}) · ${s.client.model}`)}${r.counted ? c.faint(` · the last request, ${s.client.serverCount ? 'as the server counted it' : 'estimated (the server sent no count)'}: ${kTokens(r.counted)}`) : ''}`,
|
|
1572
1583
|
...r.parts.filter((p) => p.tokens).map((p) => row(p.name, p.tokens, p.note)),
|
|
1573
1584
|
` ${'room left'.padEnd(20)} ${kTokens(free).padStart(6)} ${c.faint(share(free).padStart(4))} ${c.faint(`before it summarizes, at 85% (${kTokens(r.compactAt)}) — or moves to a model with more room`)}`,
|
|
1574
1585
|
'',
|
|
@@ -1594,7 +1605,7 @@ async function slash(app, line, working = false) {
|
|
|
1594
1605
|
case 'clear_chat': // a new session; the old one stays in /resume
|
|
1595
1606
|
ui.clear()
|
|
1596
1607
|
app.setChat(newChat(app.root))
|
|
1597
|
-
if (app.s) app.s.client
|
|
1608
|
+
if (app.s) Object.assign(app.s.client, { lastTokens: 0, speed: { tokens: 0, ms: 0 } }) // the status bar starts over too
|
|
1598
1609
|
return
|
|
1599
1610
|
case 'resume':
|
|
1600
1611
|
return app.resume()
|
|
@@ -1696,7 +1707,9 @@ async function slash(app, line, working = false) {
|
|
|
1696
1707
|
}
|
|
1697
1708
|
case 'toggle_thinking':
|
|
1698
1709
|
ui.showThinking = !ui.showThinking
|
|
1699
|
-
|
|
1710
|
+
ui.print(c.dim(ui.showThinking ? 'thinking shown: all of it (Alt+O: last two lines)' : 'thinking shown: its last two lines (Alt+O: all of it)'))
|
|
1711
|
+
if (ui.showThinking && !ui.thinkTail) ui.showLastThought() // the one just over: all of it now
|
|
1712
|
+
return
|
|
1700
1713
|
}
|
|
1701
1714
|
if (!['model_info', 'compact'].includes(cmd)) {
|
|
1702
1715
|
app.skills = loadSkills(app.root) // edits to skill files apply right away
|
|
@@ -1724,11 +1737,12 @@ async function slash(app, line, working = false) {
|
|
|
1724
1737
|
}
|
|
1725
1738
|
}
|
|
1726
1739
|
|
|
1740
|
+
// true: done; false: stopped or failed; null: no model to run it
|
|
1727
1741
|
async function runTask(app, task, ctl) {
|
|
1728
1742
|
const { ui } = app
|
|
1729
1743
|
try {
|
|
1730
1744
|
const s = await app.session()
|
|
1731
|
-
if (!s) return
|
|
1745
|
+
if (!s) return null
|
|
1732
1746
|
let answer
|
|
1733
1747
|
try {
|
|
1734
1748
|
answer = await s.run(task, ctl?.signal)
|
|
@@ -1751,10 +1765,18 @@ async function runTask(app, task, ctl) {
|
|
|
1751
1765
|
|
|
1752
1766
|
async function repl(app, f = {}) {
|
|
1753
1767
|
const { ui, cfg } = app
|
|
1754
|
-
ui.fullscreen({ mouse: cfg.mouse
|
|
1768
|
+
ui.fullscreen({ mouse: cfg.mouse !== false }) // HeartCode's wheel and selection ("mouse": false: the terminal's own: then its wheel scrolls the whole screen)
|
|
1755
1769
|
ui.onDoubleEscape = () => '/rewind'
|
|
1756
1770
|
let ctl = null
|
|
1757
|
-
|
|
1771
|
+
// stopped by you (Esc, Ctrl+C; not Alt+S/Alt+A, which stop to send it): the queue isn't sent, it's
|
|
1772
|
+
// back in the input (with what's typed there), to edit or drop
|
|
1773
|
+
const stop = () => {
|
|
1774
|
+
if (!ctl) return
|
|
1775
|
+
ui.notice('') // "Press Esc again to stop" is done with
|
|
1776
|
+
if (!ui.sendNow && ui.ahead.length) app.nextInput = [...ui.ahead.splice(0), ui.rl?.line].filter(Boolean).join('\n')
|
|
1777
|
+
ctl.abort()
|
|
1778
|
+
}
|
|
1779
|
+
ui.onEscape = stop
|
|
1758
1780
|
// a command typed while it works: run now, beside the task, if it leaves the conversation alone
|
|
1759
1781
|
ui.onPanel = () => app.toggleJobs() // Alt+B: the background commands' logs, side by side, live
|
|
1760
1782
|
ui.onNow = (line) => {
|
|
@@ -1810,7 +1832,7 @@ async function repl(app, f = {}) {
|
|
|
1810
1832
|
lastInterrupt = Date.now()
|
|
1811
1833
|
if (ctl) {
|
|
1812
1834
|
if (again) return quit()
|
|
1813
|
-
|
|
1835
|
+
stop()
|
|
1814
1836
|
ui.cancelAsk()
|
|
1815
1837
|
return ui.warn(`stopping… (Ctrl+C again to quit${others() ? ` HeartCode, all ${others() + 1} tabs` : ''})`)
|
|
1816
1838
|
}
|
|
@@ -1819,25 +1841,39 @@ async function repl(app, f = {}) {
|
|
|
1819
1841
|
return ui.clearInput()
|
|
1820
1842
|
}
|
|
1821
1843
|
if (again) return quit() // the second within 2s (also when the first stopped the work)
|
|
1822
|
-
ui.notice(others() ? `Press Ctrl+C again to quit HeartCode (all ${others() + 1} tabs;
|
|
1844
|
+
ui.notice(others() ? `Press Ctrl+C again to quit HeartCode (all ${others() + 1} tabs; Alt+W closes just this one)` : 'Press Ctrl+C again to quit', 2000)
|
|
1823
1845
|
}
|
|
1824
1846
|
// Pinned to the top of the screen; /clear_chat and scrolling leave it alone.
|
|
1825
1847
|
const home = process.env.HOME
|
|
1826
1848
|
const where = home && app.root.startsWith(home) ? '~' + app.root.slice(home.length) : app.root
|
|
1827
1849
|
ui.folder = app.root // what a double click on the header's folder copies
|
|
1828
|
-
ui.header = (cols = 100) =>
|
|
1829
|
-
|
|
1830
|
-
[['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']]
|
|
1831
|
-
'
|
|
1832
|
-
|
|
1850
|
+
ui.header = (cols = 100) => {
|
|
1851
|
+
const room = cols - 2 - width(`♥ HeartCode ${VERSION} `) // the folder's own name (its end) stays in sight
|
|
1852
|
+
const keys = [['/', 'run a command'], ['@', 'attach a file'], ...(ui.voiceReady?.() ? [['Space', 'talk (voice)']] : []), [NEWLINE_KEY, 'add a new line'], ['Esc', 'stop'], ['Shift+Tab', 'change permissions']]
|
|
1853
|
+
// the keys: on a second line when they don't fit one, broken between keys (never inside one)
|
|
1854
|
+
const rows = []
|
|
1855
|
+
for (const kd of keys) {
|
|
1856
|
+
const row = rows.at(-1)
|
|
1857
|
+
if (row && width([...row, kd].map((x) => x.join(' ')).join(' · ')) <= cols - 2) row.push(kd)
|
|
1858
|
+
else rows.push([kd])
|
|
1859
|
+
}
|
|
1860
|
+
return [
|
|
1861
|
+
`${c.brand('♥')} ${c.bright(c.bold('HeartCode'))} ${c.faint(VERSION)} ${c.muted(width(where) > room ? '…' + where.slice(-(room - 1)) : where)}`,
|
|
1862
|
+
...rows.map((row) => row.map(([k, d]) => `${c.muted(k)} ${c.faint(d)}`).join(c.ghost(' · '))),
|
|
1863
|
+
'',
|
|
1864
|
+
]
|
|
1865
|
+
}
|
|
1833
1866
|
if (!ui.full) ui.print(ui.header().join('\n'))
|
|
1867
|
+
// nothing set up yet: how to, at once (not only after a first message); a local server is looked for first
|
|
1868
|
+
if (!Object.keys(cfg.providers).length) app.detectLocal().then((found) => (found ? ui.render?.() : ui.print(HOWTO)))
|
|
1869
|
+
else if (!cfg.providers[cfg.provider] || !cfg.model) ui.print(NO_MODELS)
|
|
1834
1870
|
if (f.onStart) await f.onStart(app)
|
|
1835
1871
|
if (f.continue) {
|
|
1836
1872
|
const last = listChats(app.root)[0]
|
|
1837
1873
|
if (last) await app.resume(last)
|
|
1838
1874
|
else ui.print(c.dim('No earlier session in this folder to continue.'))
|
|
1839
1875
|
}
|
|
1840
|
-
if (f['resume-id']) await app.resume(loadChat(f['resume-id']))
|
|
1876
|
+
if (f['resume-id']) await app.resume(loadChat(f['resume-id'], app.root))
|
|
1841
1877
|
else if (f.resume) await app.resume()
|
|
1842
1878
|
if (f.model) useModel(app, f.model) // a continued tab's own model
|
|
1843
1879
|
// models this folder picked earlier (/select_model): said, with the way back to your whole list
|
|
@@ -1878,6 +1914,7 @@ async function repl(app, f = {}) {
|
|
|
1878
1914
|
}
|
|
1879
1915
|
if (mark) ui.unmark(mark, /^\S+/.exec(t)[0])
|
|
1880
1916
|
} else {
|
|
1917
|
+
if (process.stdout.isTTY) process.stdout.write(`\x1b]0;● ${path.basename(app.root)} · HeartCode\x07`)
|
|
1881
1918
|
let ok = await runTask(app, t, ctl)
|
|
1882
1919
|
// plan mode: the plan is done; go ahead with it?
|
|
1883
1920
|
while (ok && ui.permission === 'plan' && !ctl.signal.aborted) {
|
|
@@ -1891,7 +1928,9 @@ async function repl(app, f = {}) {
|
|
|
1891
1928
|
ui.setPermission(go.mode)
|
|
1892
1929
|
ok = await runTask(app, prompt('agent/plan-approved'), ctl)
|
|
1893
1930
|
}
|
|
1894
|
-
if (ui.busySince) ui.print(c.faint(c.italic(`✻ took ${duration(ui.worked())}`))) // fixed once the reply is in
|
|
1931
|
+
if (ui.busySince && ok !== null) ui.print(c.faint(c.italic(`✻ took ${duration(ui.worked())}`))) // fixed once the reply is in (not when no model ran)
|
|
1932
|
+
// done, said by the terminal too: its title, and after a long task a bell and a notification (OSC 9)
|
|
1933
|
+
if (process.stdout.isTTY) process.stdout.write(`\x1b]0;${ok === null ? '♥' : '✓'} ${path.basename(app.root)} · HeartCode\x07` + (ok !== null && !ctl.signal.aborted && ui.worked() > 10_000 ? '\x07\x1b]9;HeartCode: done\x07' : ''))
|
|
1895
1934
|
}
|
|
1896
1935
|
ui.idle()
|
|
1897
1936
|
ctl = null
|
|
@@ -1903,6 +1942,10 @@ async function repl(app, f = {}) {
|
|
|
1903
1942
|
}
|
|
1904
1943
|
|
|
1905
1944
|
async function main() {
|
|
1945
|
+
// "heartcode page <file|url>": a web page checked in a browser (src/check.js). Only that: a prompt
|
|
1946
|
+
// that starts with "page" ("page fix the footer") is a prompt
|
|
1947
|
+
const target = process.argv[3]
|
|
1948
|
+
if (process.argv[2] === 'page' && process.argv.length === 4 && (/^https?:\/\//.test(target) || fs.existsSync(target))) return (process.exitCode = await (await import('../src/check.js')).pageCommand(target))
|
|
1906
1949
|
// "--resume <id>" (as in Claude Code) vs a bare "--resume" (pick one): an id follows it
|
|
1907
1950
|
const argv = process.argv.slice(2)
|
|
1908
1951
|
const print = argv.includes('-p') || argv.includes('--print') // headless: an id after --resume is always an id
|
|
@@ -1942,7 +1985,6 @@ async function main() {
|
|
|
1942
1985
|
disallowedTools: { type: 'string', multiple: true },
|
|
1943
1986
|
'disallowed-tools': { type: 'string', multiple: true },
|
|
1944
1987
|
'permission-mode': { type: 'string' },
|
|
1945
|
-
'model-choice': { type: 'string' },
|
|
1946
1988
|
'dangerously-skip-permissions': { type: 'boolean' },
|
|
1947
1989
|
'session-id': { type: 'string' },
|
|
1948
1990
|
effort: { type: 'string' },
|
|
@@ -1952,10 +1994,10 @@ async function main() {
|
|
|
1952
1994
|
'max-turns': { type: 'string' },
|
|
1953
1995
|
all: { type: 'boolean' }, // heart models --all
|
|
1954
1996
|
json: { type: 'boolean' }, // heart models --json
|
|
1997
|
+
'include-partial-messages': { type: 'boolean' }, // stream-json: the replies as they come (thinking too)
|
|
1955
1998
|
// accepted for drop-in use where Claude Code is expected; nothing to do in HeartCode
|
|
1956
1999
|
autocompact: { type: 'string' },
|
|
1957
2000
|
'exclude-dynamic-system-prompt-sections': { type: 'boolean' },
|
|
1958
|
-
'include-partial-messages': { type: 'boolean' },
|
|
1959
2001
|
help: { type: 'boolean', short: 'h' },
|
|
1960
2002
|
version: { type: 'boolean', short: 'v' },
|
|
1961
2003
|
},
|
|
@@ -1965,8 +2007,6 @@ async function main() {
|
|
|
1965
2007
|
if (f.context && !(Number(f.context) > 0)) throw new Error('--context must be a number of tokens')
|
|
1966
2008
|
for (const k of ['output-format', 'input-format']) if (f[k] && !['text', 'json', 'stream-json'].includes(f[k])) throw new Error(`--${k} must be text, json or stream-json`)
|
|
1967
2009
|
if (f['permission-mode'] && !PERMISSION_MODES[f['permission-mode']]) throw new Error(`--permission-mode must be one of ${Object.keys(PERMISSION_MODES).join(', ')}`)
|
|
1968
|
-
if (f['model-choice'] && !['order', 'fit'].includes(f['model-choice'])) throw new Error('--model-choice must be order or fit')
|
|
1969
|
-
modelChoiceFlag = f['model-choice']
|
|
1970
2010
|
|
|
1971
2011
|
const cfg = loadConfig({ baseUrl: f['base-url'], model: f.model, apiKey: f['api-key'], context: f.context })
|
|
1972
2012
|
setTheme(cfg.theme)
|
|
@@ -2011,7 +2051,11 @@ async function main() {
|
|
|
2011
2051
|
cfg.maxRetries ??= 10
|
|
2012
2052
|
// each editor session its own settings (one choosing a model doesn't change the others')
|
|
2013
2053
|
const apps = []
|
|
2014
|
-
const makeApp = (root, ui, mcp) =>
|
|
2054
|
+
const makeApp = (root, ui, mcp) => {
|
|
2055
|
+
const app = new App({ ...structuredClone(cfg), ...(mcp && { mcp: { extra: [mcp] } }) }, ui, root)
|
|
2056
|
+
usePromptsFrom(app.root) // its .heartcode/prompts override the built-in sections (as newApp's)
|
|
2057
|
+
return apps[apps.push(app) - 1]
|
|
2058
|
+
}
|
|
2015
2059
|
watchSettings(() => apps, cfg) // the settings page's changes, into every editor session
|
|
2016
2060
|
process.exit(await runAcp({ makeApp, version: VERSION, permission: f['permission-mode'] ? PERMISSION_MODES[f['permission-mode']] : (cfg.permissions ?? 'ask') }))
|
|
2017
2061
|
}
|
|
@@ -2035,15 +2079,24 @@ async function main() {
|
|
|
2035
2079
|
saveConfig(cfg)
|
|
2036
2080
|
}
|
|
2037
2081
|
}
|
|
2038
|
-
ui.showThinking =
|
|
2082
|
+
ui.showThinking = false // the thinking's last two lines while it thinks; Alt+O shows all of it (--hide-thinking: the same)
|
|
2039
2083
|
const app = new App(cfg, ui, root)
|
|
2040
2084
|
usePromptsFrom(app.root) // its .heartcode/prompts override the built-in sections
|
|
2041
2085
|
ui.suggest = (line, cursor) => app.suggest(line, cursor)
|
|
2042
2086
|
ui.status = (cols) => app.status(cols)
|
|
2087
|
+
ui.todos = () => app.chat?.todos // the plan, kept in sight while it works
|
|
2043
2088
|
ui.requestSince = () => app.s?.client.inFlight // the spinner shows how long the model has been answering
|
|
2089
|
+
ui.waitingFor = () => app.s?.client.model // the spinner: "waiting for <model>"
|
|
2044
2090
|
return app
|
|
2045
2091
|
}
|
|
2046
2092
|
let root = path.resolve(f.cwd ?? process.cwd())
|
|
2093
|
+
// a session of another folder (--resume <id> from anywhere): run in its project, where its files
|
|
2094
|
+
// are (what it changed is kept relative to it, and /rewind puts files back there)
|
|
2095
|
+
const other = (f['resume-id'] || f['session-id']) && loadChat(f['resume-id'] || f['session-id'], root)
|
|
2096
|
+
if (other?.root && path.resolve(other.root) !== root) {
|
|
2097
|
+
if (!fs.existsSync(other.root)) throw new Error(`session ${other.id} was in ${other.root}, which is gone`)
|
|
2098
|
+
root = path.resolve(other.root)
|
|
2099
|
+
}
|
|
2047
2100
|
const wt = f.worktree !== undefined ? createWorktree(root, f.worktree) : null
|
|
2048
2101
|
if (wt) {
|
|
2049
2102
|
root = wt.cwd
|
|
@@ -2052,7 +2105,7 @@ async function main() {
|
|
|
2052
2105
|
}
|
|
2053
2106
|
// The full screen: in tabs (the first one is this folder; /tab and Alt+T open more).
|
|
2054
2107
|
if (!headless && !sub && !positionals.length && process.stdin.isTTY && process.stdout.isTTY) {
|
|
2055
|
-
if (f['resume-id'] && !loadChat(f['resume-id'])) throw new Error(`no session ${f['resume-id']}`)
|
|
2108
|
+
if (f['resume-id'] && !loadChat(f['resume-id'], root)) throw new Error(`no session ${f['resume-id']}`)
|
|
2056
2109
|
const saved = readJson(TABS_FILE, {})[root] // before this run's first tab replaces it
|
|
2057
2110
|
const asked = f.continue || f.resume || f['resume-id'] || f['session-id'] // a session was chosen already
|
|
2058
2111
|
const tabs = new Tabs((tab, o) => {
|
|
@@ -2062,7 +2115,7 @@ async function main() {
|
|
|
2062
2115
|
Object.assign(app, { tabs, tab, worktree: o.wt ?? null })
|
|
2063
2116
|
if (o.first) {
|
|
2064
2117
|
if (f['no-memory']) app.memory = null
|
|
2065
|
-
if (f['session-id']) app.setChat(loadChat(f['session-id']) ?? { ...newChat(app.root), id: f['session-id'] })
|
|
2118
|
+
if (f['session-id']) app.setChat(loadChat(f['session-id'], app.root) ?? { ...newChat(app.root), id: f['session-id'] })
|
|
2066
2119
|
}
|
|
2067
2120
|
return (async () => {
|
|
2068
2121
|
await repl(app, o.first ? { ...f, onStart: !asked && ((a) => continueTabs(a, saved)) } : o.chat ? { 'resume-id': o.chat.id, model: o.model } : {})
|
|
@@ -2090,14 +2143,14 @@ async function main() {
|
|
|
2090
2143
|
if (sub === 'providers') return app.listProviders(), ui.close()
|
|
2091
2144
|
if (sub === 'models') return await app.listModels(positionals[1] ?? '', { all: f.all, json: f.json }), ui.close()
|
|
2092
2145
|
if (f['no-memory']) app.memory = null
|
|
2093
|
-
const chat = f['resume-id'] ? loadChat(f['resume-id']) : f.continue && headless ? listChats(app.root)[0] : f['session-id'] ? (loadChat(f['session-id']) ?? { ...newChat(app.root), id: f['session-id'] }) : null
|
|
2146
|
+
const chat = f['resume-id'] ? loadChat(f['resume-id'], app.root) : f.continue && headless ? listChats(app.root)[0] : f['session-id'] ? (loadChat(f['session-id'], app.root) ?? { ...newChat(app.root), id: f['session-id'] }) : null
|
|
2094
2147
|
if (f['resume-id'] && !chat) throw new Error(`no session ${f['resume-id']}`)
|
|
2095
2148
|
if (chat && (headless || !f['resume-id'])) app.setChat(chat) // interactive: resumed below, with its transcript
|
|
2096
2149
|
if (headless || positionals.length) watchSettings(() => [app], cfg) // an app's run takes the settings page's changes too
|
|
2097
2150
|
if (headless) {
|
|
2098
2151
|
app.allowTools = [...(f.allowedTools ?? []), ...(f['allowed-tools'] ?? [])]
|
|
2099
2152
|
app.denyTools = [...(f.disallowedTools ?? []), ...(f['disallowed-tools'] ?? [])]
|
|
2100
|
-
const code = await runHeadless(app, { prompt: positionals.join(' '), input: f['input-format'], output: f['output-format'], appendSystem: f['append-system-prompt'] })
|
|
2153
|
+
const code = await runHeadless(app, { prompt: positionals.join(' '), input: f['input-format'], output: f['output-format'], appendSystem: f['append-system-prompt'], partial: f['include-partial-messages'] })
|
|
2101
2154
|
if (wt && worktreeState(wt).empty) removeWorktree(wt) // else kept, for the caller to merge (its path is in the log)
|
|
2102
2155
|
process.exit(code) // MCP servers are stopped by the exit hooks
|
|
2103
2156
|
}
|