heartcode 0.1.30 → 0.1.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heartcode",
3
- "version": "0.1.30",
3
+ "version": "0.1.32",
4
4
  "description": "A coding CLI for any local or OpenAI-compatible model, including small models without tool calling.",
5
5
  "keywords": [
6
6
  "ai",
package/prompts/agent.md CHANGED
@@ -156,7 +156,7 @@ Instructions from the user (follow them):
156
156
  ## command-timeout
157
157
 
158
158
  <!-- Added to a command's result when it ran too long and was stopped. {{root}}: the project folder. -->
159
- (It ran for more than 2 minutes and was stopped. Searching the whole disk or home folder is the usual cause: the project is {{root}}; search inside it, with the search tool. If it's a server or a watcher, run it in the background with its output to a file.)
159
+ (It ran for more than 2 minutes and was stopped. Searching the whole disk or home folder is the usual cause: the project is {{root}}; search inside it, with the search tool. If it's a server or a watcher, run it again with background: true.)
160
160
 
161
161
  ## command-too-wide
162
162
 
@@ -196,7 +196,26 @@ Create a file, or overwrite one with its full content. With append: true, add to
196
196
 
197
197
  ## tool-run_command
198
198
 
199
- Run a shell command in the project folder; returns the exit code and output.
199
+ Run a shell command in the project folder; returns the exit code and output. A command that keeps running (a dev server, a watcher, a long build): set background true; it answers after a few seconds with its id and first output, and keeps running (the background tool reads it later).
200
+
201
+ ## tool-background
202
+
203
+ <!-- The background tool: commands started with run_command background true. -->
204
+ Commands started with run_command background true. action "output": what one printed since you last looked (id; the newest if left out). "list": all of them, running or exited. "stop": stop one (id). Stop what you started once you no longer need it.
205
+
206
+ ## background-started
207
+
208
+ <!-- run_command's result for a command started in the background. {{id}}, {{running}}, {{code}} (when it exited), {{output}}: what it printed so far, {{file}}: its whole output. -->
209
+ {{#if running}}Started in the background as #{{id}}; it is still running.{{else}}Started as #{{id}}, but it has already exited with {{code}}.{{/if}} Its output so far:
210
+ {{output}}
211
+ (All of it goes to {{file}}. background action "output" shows what's new, "stop" stops it.)
212
+
213
+ ## background-ended
214
+
215
+ <!-- Told to the model at its next step when commands it started in the background have ended. {{jobs}}: one line each. -->
216
+ (Background commands that have ended since your last step:
217
+ {{jobs}}
218
+ background action "output" shows what each printed last.)
200
219
 
201
220
  ## tool-mcp
202
221
 
package/src/agent.js CHANGED
@@ -5,11 +5,12 @@ import { prompt, userInstructions } from './prompts.js'
5
5
  import { newChat } from './sessions.js'
6
6
  import path from 'node:path'
7
7
  import { pathToFileURL } from 'node:url'
8
- import { est, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
8
+ import { est, estMessages, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
9
9
  import { runGuided } from './guided.js'
10
10
  import { markUsed, removeResearch, findResearch } from './research.js'
11
11
  import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed } from './tools.js'
12
12
  import { serversNote } from './lsp.js'
13
+ import { newlyEnded, jobLine } from './background.js'
13
14
  import { loadHooks, runHooks } from './hooks.js'
14
15
  import { takeConfigErrors } from './config.js'
15
16
  import { c, duration, Block, Markdown, color, diffLines, renderDiff } from './ui.js'
@@ -148,6 +149,7 @@ export class Session {
148
149
  // images: data: URLs from the caller (headless input), besides @shot.png in the task.
149
150
  async run(task, signal, extra = []) {
150
151
  if (!this.isSub) this.client.newMessage?.() // the model list: from #1 again (unless set to stay)
152
+ this.runs = (this.runs ?? 0) + 1
151
153
  const { chat, ui } = this
152
154
  repairSummary(chat)
153
155
  if (this.hooks !== false) this.hooks = loadHooks(this.root) // edits to hooks.json apply right away
@@ -365,14 +367,15 @@ export class Session {
365
367
  const tools = [...extraTools({ memory: this.memory }), ...(extra?.defs ?? [])].map((f) => ({ type: 'function', function: f }))
366
368
  const messages = [{ role: 'system', content: system }, { role: 'user', content: user }]
367
369
  let last = ''
370
+ const client = extra?.client ?? this.client
368
371
  for (;;) {
369
- const was = this.client.purpose
370
- this.client.purpose = 'memory' // in the requests log
372
+ const was = client.purpose
373
+ client.purpose = extra?.purpose ?? 'memory' // in the requests log
371
374
  let res
372
375
  try {
373
- res = await this.client.chat({ messages, tools }, { signal })
376
+ res = await client.chat({ messages, tools }, { signal })
374
377
  } finally {
375
- this.client.purpose = was
378
+ client.purpose = was
376
379
  }
377
380
  messages.push({ role: 'assistant', content: res.content || '', ...(res.toolCalls.length && { tool_calls: res.toolCalls }) })
378
381
  if (!res.toolCalls.length) return res.content.trim()
@@ -396,14 +399,26 @@ export class Session {
396
399
  // or deleted as junk, and throwaway files it made are removed. Done by code after every such task,
397
400
  // not left to the model to remember: a fresh, small request (the task, its answer, the lists), on
398
401
  // the model that did the task. Helpers' pages are in the same list (they share it).
399
- async wrapUp(task, answer, signal) {
402
+ // It runs after the answer is back (wrapUpLater), beside whatever you do next: its own connection,
403
+ // one wrap-up at a time; what it needs is taken from the task first, before the next one changes it.
404
+ wrapUpLater(task, answer) {
405
+ const at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }
406
+ const job = (this.wrapping ?? Promise.resolve())
407
+ .then(() => this.wrapUp(task, answer, undefined, at))
408
+ .catch((e) => log('wrapup', `failed: ${e.message}`))
409
+ .finally(() => this.wrapping === job && (this.wrapping = null))
410
+ this.wrapping = job
411
+ }
412
+
413
+ // at: the task's own state (wrapUpLater), else this message's
414
+ async wrapUp(task, answer, signal, at = { research: this.research, turn: this.chat.turns.at(-1), dirsBefore: this.dirsBefore, ran: this.ran, runs: this.runs }) {
400
415
  if (this.isSub || !this.memory || this.ui.permission === 'plan') return
401
- const pages = this.research ?? []
402
- const turn = this.chat.turns.at(-1)
416
+ const pages = at.research ?? []
417
+ const turn = at.turn
403
418
  const made = Object.entries(turn?.files ?? {}).filter(([rel, before]) => before === null && fs.existsSync(path.join(this.root, rel))).map(([rel]) => rel)
404
419
  // folders the task made that are still empty (a test folder): offered for cleanup too
405
- if (this.dirsBefore) for (const d of foldersOf(this.root)) if (!this.dirsBefore.has(d) && isEmptyDir(path.join(this.root, d))) made.push(`${d}/`)
406
- const ran = this.ran ?? []
420
+ if (at.dirsBefore) for (const d of foldersOf(this.root)) if (!at.dirsBefore.has(d) && isEmptyDir(path.join(this.root, d))) made.push(`${d}/`)
421
+ const ran = at.ran ?? []
407
422
  if (!pages.length && !made.length && !ran.length) return
408
423
  const commands = ran.map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 200)} → ${r.result}`).join('\n')
409
424
  const known = this.memory.relevant(`${task}\n${answer}\n${pages.map((p) => p.title).join('\n')}`, 12)
@@ -416,6 +431,7 @@ export class Session {
416
431
  })
417
432
  const files = new Set(pages.map((p) => p.file))
418
433
  const scratch = new Set(made)
434
+ const mine = at.runs // a message sent since: its task may use these files, so none are deleted
419
435
  const kept = []
420
436
  const dropped = []
421
437
  const removed = []
@@ -435,6 +451,7 @@ export class Session {
435
451
  if (!scratch.has(rel) && scratch.has(`${rel}/`)) rel = `${rel}/` // a folder named without its slash
436
452
  if (!scratch.has(rel)) return `error: "${rel}" isn't one of the new files this task made: ${[...scratch].join(', ')}`
437
453
  if (a.verdict !== 'delete') return `Kept ${rel}.`
454
+ if (this.runs !== mine) return `Kept ${rel}: the user has gone on to another task, which may use it.`
438
455
  if (rel.endsWith('/')) {
439
456
  if (!isEmptyDir(path.join(this.root, rel))) return `error: ${rel} isn't empty: delete the files in it first, or keep it`
440
457
  fs.rmSync(path.join(this.root, rel, '.DS_Store'), { force: true })
@@ -446,19 +463,15 @@ export class Session {
446
463
  return `Deleted ${rel}.`
447
464
  }
448
465
  }
449
- this.ui.spinner('keeping what this task learned')
450
- const was = this.client.purpose
466
+ const own = { provider: this.client.provider, model: this.client.model }
451
467
  try {
452
- this.client.purpose = 'wrapup'
453
- const said = await this.memoryTask(prompt('agent/wrapup'), request, signal, { defs, run })
468
+ const { client } = this.engineFor ? await this.engineFor(own) : { client: this.client }
469
+ const said = await this.memoryTask(prompt('agent/wrapup'), request, signal, { defs, run, client, purpose: 'wrapup' })
454
470
  log('wrapup', `${said} | pages kept ${kept.length}, deleted ${dropped.length}; files removed ${removed.length}`)
455
471
  if (kept.length || dropped.length) this.ui.step('research', `kept ${kept.length} page${kept.length === 1 ? '' : 's'}${dropped.length ? `, deleted ${dropped.length} as junk` : ''}`)
456
472
  } catch (e) {
457
473
  if (e.name === 'AbortError' || signal?.aborted) throw e
458
474
  log('wrapup', `failed: ${e.message}`)
459
- } finally {
460
- this.client.purpose = was
461
- this.ui.stopSpin()
462
475
  }
463
476
  }
464
477
 
@@ -938,7 +951,7 @@ async function runNative(s, task, images, signal) {
938
951
  }
939
952
  const more = sinceNudge && !s.isSub && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
940
953
  if (!more) {
941
- await s.wrapUp?.(task, res.content, signal)
954
+ s.wrapUpLater?.(task, res.content) // after the answer, beside what comes next
942
955
  return res.content
943
956
  }
944
957
  nudged++
@@ -984,8 +997,8 @@ async function runNative(s, task, images, signal) {
984
997
  ? `${args.server} · ${args.tool ?? ''}`
985
998
  : name === 'memory'
986
999
  ? `${args.action} ${args.name ? `[[${args.name}]]` : (args.query ?? '')}`
987
- : name === 'manage'
988
- ? [args.action, args.kind, args.name].filter(Boolean).join(' ')
1000
+ : name === 'manage' || name === 'background'
1001
+ ? [args.action, args.kind, args.name, args.id && `#${args.id}`].filter(Boolean).join(' ')
989
1002
  : name === 'agent'
990
1003
  ? [args.model && `${args.model}:`, args.description].filter(Boolean).join(' ')
991
1004
  : name === 'todo' || name === 'ask_user'
@@ -1037,6 +1050,11 @@ async function runNative(s, task, images, signal) {
1037
1050
  s.onEvent?.({ type: 'tool', id: call.id, name, output: out })
1038
1051
  }
1039
1052
  trimOldResults(s)
1053
+ const ended = newlyEnded(s.root) // background commands that exited meanwhile: the model hears it now
1054
+ if (ended.length) {
1055
+ for (const j of ended) ui.step('background', `#${j.id} ${clip(j.command, 60)} exited with ${j.code}`)
1056
+ s.messages.push({ role: 'user', content: prompt('agent/background-ended', { jobs: ended.map(jobLine).join('\n') }) })
1057
+ }
1040
1058
  if (stuck) {
1041
1059
  handOver(stuck)
1042
1060
  stuck = null
@@ -1661,3 +1679,50 @@ function attachNamed(s, task) {
1661
1679
  }
1662
1680
  if (calls.length) s.messages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results)
1663
1681
  }
1682
+
1683
+ // /context: what the next request carries, part by part, in tokens (estimated, by this model's
1684
+ // ratio of counted to estimated; the server's count of the last request beside it), and the
1685
+ // biggest single pieces. Returns { total, window, compactAt, counted, parts: [{ name, tokens, note }], biggest: [{ tokens, what, ago }] }.
1686
+ export function contextReport(s) {
1687
+ const ratio = s.strat?.ratio ?? 1
1688
+ const tok = (x) => Math.round(est(typeof x === 'string' ? x : JSON.stringify(x ?? '')) * ratio)
1689
+ const msgs = s.messages ?? []
1690
+ const tasks = (s.chat.turns ?? []).map((t) => String(t.task ?? '').slice(0, 60)).filter(Boolean)
1691
+ const tools = [...TOOL_DEFS, ...extraTools(s)].filter((f) => allowed(s, f.name))
1692
+ const parts = { system: 0, you: 0, notes: 0, replies: 0, results: 0, pointers: 0 }
1693
+ let whole = 0
1694
+ let cut = 0
1695
+ const pieces = []
1696
+ msgs.forEach((m, i) => {
1697
+ const n = Math.round(estMessages([m]) * ratio)
1698
+ const ago = msgs.length - 1 - i
1699
+ if (i === 0 && (m.role === 'system' || s.strat?.mergeSystem)) return void (parts.system += n)
1700
+ if (i === 1 && s.strat?.mergeSystem && m.role === 'assistant') return void (parts.system += n)
1701
+ if (m.role === 'tool') {
1702
+ const old = typeof m.content === 'string' && /^\[older output/.test(m.content)
1703
+ old ? (parts.pointers += n, cut++) : (parts.results += n, whole++)
1704
+ pieces.push({ tokens: n, what: `${callOf(msgs, m.tool_call_id)} (result${old ? ', a pointer' : ''})`, ago })
1705
+ } else if (m.role === 'assistant') {
1706
+ parts.replies += n
1707
+ pieces.push({ tokens: n, what: 'a model reply', ago })
1708
+ } else {
1709
+ const text = typeof m.content === 'string' ? m.content : (m.content ?? []).map((p) => p.text ?? '').join(' ')
1710
+ const yours = tasks.some((t) => text.startsWith(t))
1711
+ yours ? (parts.you += n) : (parts.notes += n)
1712
+ pieces.push({ tokens: n, what: yours ? `your message "${clip(text.split('\n')[0], 50)}"` : `a note to the model "${clip(text.split('\n')[0], 50)}"`, ago })
1713
+ }
1714
+ })
1715
+ const toolTokens = tok(tools.map((f) => ({ type: 'function', function: f })))
1716
+ const list = [
1717
+ { name: 'system prompt', tokens: parts.system },
1718
+ { name: `tools (${tools.length})`, tokens: toolTokens },
1719
+ { name: 'your messages', tokens: parts.you },
1720
+ { name: 'notes to the model', tokens: parts.notes, note: 'summaries, guides, reminders, saved notes found' },
1721
+ { name: 'model replies', tokens: parts.replies },
1722
+ { name: 'tool results', tokens: parts.results, note: `${whole} whole` },
1723
+ { name: 'older results', tokens: parts.pointers, note: `${cut} shortened to pointers to their files` },
1724
+ ]
1725
+ const total = list.reduce((a, p) => a + p.tokens, 0)
1726
+ const window = s.strat?.context ?? 0
1727
+ return { total, window, compactAt: Math.round(window * COMPACT_SHARE), counted: s.counted?.tokens ?? 0, parts: list, biggest: pieces.sort((a, b) => b.tokens - a.tokens).slice(0, 5) }
1728
+ }
@@ -0,0 +1,105 @@
1
+ // Commands that keep running (a dev server, a watcher, a long build): run_command with background
2
+ // true starts one and answers after a few seconds with what it printed so far; the background tool
3
+ // (and /background) reads what it printed since, lists them, stops one. Each runs in its own process
4
+ // group, its output going to a file; all of them are stopped when HeartCode exits.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { spawn } from 'node:child_process'
8
+ import { HOME } from './config.js'
9
+ import { log } from './log.js'
10
+
11
+ const DIR = path.join(HOME, 'outputs', 'background')
12
+ const jobs = new Map() // id → { id, command, root, pid, file, started, code, read, exited }
13
+ let made = 0
14
+
15
+ const plain = (t) => t.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').replace(/\r(?!\n)/g, '\n')
16
+ const group = process.platform !== 'win32'
17
+ const kill = (job, sig) => {
18
+ try {
19
+ group ? process.kill(-job.pid, sig) : process.kill(job.pid, sig)
20
+ return true
21
+ } catch {
22
+ return false
23
+ }
24
+ }
25
+
26
+ // Started, and after `wait` ms: { job, output } (what it printed so far).
27
+ export async function startJob(root, command, { wait = 3000 } = {}) {
28
+ fs.mkdirSync(DIR, { recursive: true })
29
+ const id = ++made
30
+ const file = path.join(DIR, `${process.pid}-${id}.log`)
31
+ const fd = fs.openSync(file, 'w')
32
+ const child = spawn(command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' } })
33
+ fs.closeSync(fd)
34
+ const job = { id, command, root, pid: child.pid, file, started: Date.now(), code: null, read: 0, exited: false, told: false }
35
+ jobs.set(id, job)
36
+ child.on('error', (e) => fs.appendFileSync(file, `\n${e.message}\n`))
37
+ child.on('exit', (code, sig) => Object.assign(job, { code: code ?? sig, exited: true, ended: Date.now() }))
38
+ child.unref()
39
+ log('background', `#${id} started: ${command} (pid ${child.pid})`)
40
+ await new Promise((r) => setTimeout(r, wait))
41
+ return { job, output: newOutput(job) }
42
+ }
43
+
44
+ // What it printed since the last look (the last `most` characters of it).
45
+ export function newOutput(job, most = 4000) {
46
+ let text = ''
47
+ try {
48
+ const all = fs.readFileSync(job.file)
49
+ text = plain(all.subarray(job.read).toString('utf8'))
50
+ job.read = all.length
51
+ } catch {}
52
+ return text.length > most ? `…${text.slice(-most)}` : text
53
+ }
54
+
55
+ // Its last `n` lines, read from the end of its file (a long log isn't read whole).
56
+ export function tailLines(job, n) {
57
+ let text = ''
58
+ try {
59
+ const fd = fs.openSync(job.file, 'r')
60
+ const size = fs.fstatSync(fd).size
61
+ const len = Math.min(size, 64 * 1024)
62
+ const buf = Buffer.alloc(len)
63
+ fs.readSync(fd, buf, 0, len, size - len)
64
+ fs.closeSync(fd)
65
+ text = plain(buf.toString('utf8'))
66
+ } catch {}
67
+ return text.split('\n').filter((l, i, all) => l.trim() || i < all.length - 1).slice(-n)
68
+ }
69
+
70
+ export const listJobs = (root) => [...jobs.values()].filter((j) => !root || j.root === root)
71
+ export const getJob = (id) => jobs.get(Number(String(id).replace(/^#/, '')))
72
+ export const runningJobs = (root) => listJobs(root).filter((j) => !j.exited)
73
+
74
+ export function stopJob(job) {
75
+ if (job.exited) return false
76
+ kill(job, 'SIGTERM')
77
+ setTimeout(() => kill(job, 'SIGKILL'), 2000).unref()
78
+ log('background', `#${job.id} stopped: ${job.command}`)
79
+ return true
80
+ }
81
+
82
+ // Stopped (if it still runs) and taken off the list; its log file stays.
83
+ export function removeJob(job) {
84
+ stopJob(job)
85
+ jobs.delete(job.id)
86
+ log('background', `#${job.id} removed: ${job.command}`)
87
+ }
88
+
89
+ // The ones that ended since they were last told about (for the model's next step).
90
+ export function newlyEnded(root) {
91
+ const out = listJobs(root).filter((j) => j.exited && !j.told)
92
+ for (const j of out) j.told = true
93
+ return out
94
+ }
95
+
96
+ export const jobLine = (j) => `#${j.id} ${j.command} · ${j.exited ? `exited with ${j.code}` : 'running'} · ${ago(j)} · output: ${j.file}`
97
+ export const ago = (j) => {
98
+ const s = Math.round(((j.ended ?? Date.now()) - j.started) / 1000)
99
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : `${Math.round(s / 360) / 10}h`
100
+ }
101
+
102
+ // Nothing outlives HeartCode.
103
+ process.on('exit', () => {
104
+ for (const j of jobs.values()) if (!j.exited) kill(j, 'SIGTERM')
105
+ })
package/src/config.js CHANGED
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'
6
6
  export const HOME = process.env.HEART_HOME || path.join(os.homedir(), '.heart')
7
7
  export const CONFIG_FILE = path.join(HOME, 'config.json')
8
8
 
9
- const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram']
9
+ const SETTINGS = ['context', 'effort', 'permissions', 'autoCompact', 'director', 'theme', 'format', 'lsp', 'voice', 'queue', 'rotation', 'statusBar', 'log', 'logRequests', 'logDetail', 'logDays', 'telegram', 'search']
10
10
  const LOCAL_NAMES = { 11434: 'ollama', 1234: 'lmstudio', 8080: 'llamacpp' }
11
11
 
12
12
  export function readJson(file, fallback) {
package/src/headless.js CHANGED
@@ -16,7 +16,7 @@ import { clip, TOOL_DEFS, extraTools, loadMcpTools, mcpName, failed as toolFaile
16
16
  import { allowed } from './agent.js'
17
17
 
18
18
  // 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' }
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' }
20
20
  export function toolNames(list) {
21
21
  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
22
  return new Set(names.map((t) => CLAUDE_TOOLS[t] ?? t)) // mcp__server__tool and mcp__server as they are (tools.js allowed)
@@ -180,6 +180,7 @@ export async function runHeadless(app, opts) {
180
180
  } else if (out === 'json') emit(result)
181
181
  else if (error) process.stderr.write(`heartcode: ${error}\n`)
182
182
  else process.stdout.write(answer.trim() + '\n')
183
+ await s.wrapping // the wrap-up (notes, research, cleanup) after the result is out, before it exits
183
184
  return !error
184
185
  }
185
186
 
package/src/settings.html CHANGED
@@ -86,9 +86,10 @@
86
86
  .using .k { color: var(--faint); display: block; }
87
87
  .using b { display: block; font-family: var(--mono); font-size: 12.5px; font-weight: 600; word-break: break-all; margin: 3px 0 2px; color: var(--text); }
88
88
  .using a { font-weight: 600; }
89
- .theme-pick { display: flex; margin-top: 10px; height: 34px; }
90
- .theme-pick label { flex: 1; justify-content: center; font-size: 12.5px; }
91
- .using:empty + .theme-pick { margin-top: auto; }
89
+ /* light or dark: one button at the top right of the page */
90
+ .theme-btn { position: absolute; top: 18px; right: 22px; z-index: 5; width: 38px; height: 38px; padding: 0; display: grid; place-items: center; border-radius: 50%; color: var(--muted); }
91
+ .theme-btn:hover { color: var(--text); }
92
+ .theme-btn svg { width: 18px; height: 18px; }
92
93
  main { padding: 36px 44px 72px; width: 100%; max-width: 1640px; min-width: 0; }
93
94
  .page { display: none; }
94
95
  .page.on { display: block; animation: page-in .22s ease-out; }
@@ -471,6 +472,24 @@
471
472
  .setting .t b { display: block; font-weight: 600; }
472
473
  .setting .t span { display: block; margin-top: 2px; color: var(--muted); font-size: 13px; line-height: 1.45; text-wrap: pretty; }
473
474
  .setting select, .setting input { flex: none; width: 240px; }
475
+ .settings-col .card.wide { grid-column: 1 / -1; }
476
+ .ws-url { display: flex; gap: 8px; margin-top: 10px; }
477
+ .ws-url input { flex: 1; min-width: 0; }
478
+ .ws-addr { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 6px; }
479
+ .ws-addr code { font: 12.5px/1.4 var(--mono, ui-monospace, Menlo, monospace); color: var(--text); background: var(--panel-2, color-mix(in srgb, var(--muted) 12%, transparent)); padding: 3px 8px; border-radius: 6px; word-break: break-all; }
480
+ .ws-row.mine { align-items: flex-start; }
481
+ .ws-row.mine .n, .ws-row.mine .mv, .ws-row.mine > .sw { margin-top: 2px; }
482
+ .ws-list { margin-top: 6px; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
483
+ .ws-row { display: flex; align-items: center; gap: 14px; padding: 10px 14px; border-bottom: 1px solid var(--line); }
484
+ .ws-row:last-child { border-bottom: 0; }
485
+ .ws-row .n { width: 22px; color: var(--muted); font-variant-numeric: tabular-nums; text-align: right; }
486
+ .ws-row .t { flex: 1; min-width: 0; }
487
+ .ws-row .t b { font-weight: 600; }
488
+ .ws-row .t span { display: block; color: var(--muted); font-size: 12.5px; line-height: 1.4; }
489
+ .ws-row.off .t > b, .ws-row.off .t > span, .ws-row.off .n { opacity: .5; } /* not the address box in it */
490
+ .ws-row .mv { display: flex; gap: 4px; }
491
+ .ws-row .mv button { width: 30px; padding: 4px 0; }
492
+ @media (max-width: 640px) { .ws-url { flex-wrap: wrap; } .ws-url input { flex-basis: 100%; } }
474
493
  .choice { position: relative; border: 1px solid var(--line-strong); border-radius: 12px; padding: 13px 15px; cursor: pointer; background: var(--panel); transition: border-color .15s, box-shadow .15s, background .15s; }
475
494
  .choice:hover { border-color: color-mix(in srgb, var(--accent) 45%, var(--line-strong)); }
476
495
  .choice.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent-soft) 60%, var(--panel)); }
@@ -522,14 +541,14 @@
522
541
  .md { grid-template-columns: 280px minmax(0, 1fr); }
523
542
  }
524
543
  @media (max-width: 860px) {
525
- .app { grid-template-columns: minmax(0, 1fr); }
544
+ .app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; } /* the bar on top keeps its height; the page gets the rest */
526
545
  aside { position: static; height: auto; border-right: 0; border-bottom: 1px solid var(--line); padding: 12px 16px 8px; }
527
546
  .brand { padding: 0 0 8px; }
528
547
  nav { display: flex; overflow-x: auto; gap: 4px; padding-bottom: 4px; }
529
548
  nav a { flex: none; margin: 0; }
530
549
  nav a.on::before { display: none; } /* a strip of tabs: the highlighted one is enough */
531
550
  nav a .count, .using, .nav-group { display: none; }
532
- .theme-pick { margin: 6px 0 4px; max-width: 280px; }
551
+ .theme-btn { top: 10px; right: 12px; }
533
552
  main { padding: 20px 16px 60px; }
534
553
  .steps { grid-template-columns: 1fr; }
535
554
  .choices, .choices.three { grid-template-columns: 1fr; }
@@ -610,9 +629,6 @@
610
629
  <a href="#logging" data-page="logging" data-tabs="logging files"><span class="ic">▤</span> Advanced <span class="count" id="n-failed"></span></a>
611
630
  </nav>
612
631
  <div class="using" id="using"></div>
613
- <div class="seg theme-pick" id="theme-pick" role="radiogroup" aria-label="Light or dark">
614
- <label><input type="radio" name="theme-pick" value="system">System</label><label><input type="radio" name="theme-pick" value="light">Light</label><label><input type="radio" name="theme-pick" value="dark">Dark</label>
615
- </div>
616
632
  </aside>
617
633
 
618
634
  <main>
@@ -764,6 +780,11 @@
764
780
  <p class="sub">Some features need a tool on your machine. Ready ones are ticked; the rest say what to install.</p>
765
781
  <div id="g-caps"></div>
766
782
  </div>
783
+ <div class="card wide">
784
+ <h2>Web search</h2>
785
+ <p class="sub">The engines HeartCode searches with, in this order: it asks the first one, and the next only when that one hasn't found enough, fails, or takes over 3 seconds. None needs a key.</p>
786
+ <div class="ws-list" id="ws-order"></div>
787
+ </div>
767
788
  </div>
768
789
  </section>
769
790
 
@@ -919,22 +940,32 @@
919
940
  <div class="actions"><button id="pr-cancel" type="button">Cancel</button><button class="primary" id="pr-save" type="button">Save</button></div>
920
941
  </form>
921
942
  </dialog>
943
+ <button type="button" class="theme-btn" id="theme-btn"></button>
922
944
  <div id="toast" role="status"></div>
923
945
  <div id="tip" role="tooltip"></div>
924
946
  <script>
925
947
  const token = new URLSearchParams(location.search).get('t')
926
- // Light, dark, or as the system is set: kept in this browser (the one thing the page keeps itself)
948
+ // Light or dark: the button at the top right switches; as the system is set until it's pressed. Kept in
949
+ // this browser (the one thing the page keeps itself).
927
950
  {
928
- const pick = document.getElementById('theme-pick')
929
- const now = () => document.documentElement.dataset.theme || 'system'
930
- const show = () => pick.querySelectorAll('label').forEach((l) => { const i = l.querySelector('input'); i.checked = i.value === now(); l.classList.toggle('on', i.checked) })
931
- pick.addEventListener('change', (e) => {
932
- const v = e.target.value
933
- if (v === 'system') delete document.documentElement.dataset.theme
934
- else document.documentElement.dataset.theme = v
935
- try { v === 'system' ? localStorage.removeItem('heart-theme') : localStorage.setItem('heart-theme', v) } catch {}
951
+ const btn = document.getElementById('theme-btn')
952
+ const system = matchMedia('(prefers-color-scheme: dark)')
953
+ const now = () => document.documentElement.dataset.theme || (system.matches ? 'dark' : 'light')
954
+ const SUN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="12" cy="12" r="4.2"/><path d="M12 2.5v2.2M12 19.3v2.2M4.6 4.6l1.6 1.6M17.8 17.8l1.6 1.6M2.5 12h2.2M19.3 12h2.2M4.6 19.4l1.6-1.6M17.8 6.2l1.6-1.6"/></svg>'
955
+ const MOON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"><path d="M20.5 14.2A8.5 8.5 0 0 1 9.8 3.5a8.5 8.5 0 1 0 10.7 10.7Z"/></svg>'
956
+ const show = () => {
957
+ const dark = now() === 'dark'
958
+ btn.innerHTML = dark ? SUN : MOON
959
+ btn.title = dark ? 'Light theme' : 'Dark theme'
960
+ btn.setAttribute('aria-label', btn.title)
961
+ }
962
+ btn.addEventListener('click', () => {
963
+ const v = now() === 'dark' ? 'light' : 'dark'
964
+ document.documentElement.dataset.theme = v
965
+ try { localStorage.setItem('heart-theme', v) } catch {}
936
966
  show()
937
967
  })
968
+ system.addEventListener('change', show)
938
969
  show()
939
970
  }
940
971
  const $ = (id) => document.getElementById(id)
@@ -1022,6 +1053,7 @@ const DOING = {
1022
1053
  '/api/mcp/login': 'Signing in — your browser will open',
1023
1054
  '/api/telegram/connect': 'Checking the token with Telegram',
1024
1055
  '/api/telegram/test': 'Sending a test message',
1056
+ '/api/search/test': 'Trying a search on your SearXNG',
1025
1057
  '/api/models-dev': null, // its own strip
1026
1058
  }
1027
1059
  let acting = 0
@@ -2132,6 +2164,7 @@ function drawGeneral(s) {
2132
2164
  h('div', { className: 't' }, h('b', { textContent: TOGGLE_INFO[k] ?? k }), h('span', { textContent: d[0].toUpperCase() + d.slice(1) })),
2133
2165
  sw({ checked: s.settings[k], onchange: (e) => act('/api/setting', { name: k, value: e.target.checked }, `${TOGGLE_INFO[k] ?? k}: ${e.target.checked ? 'on' : 'off'}`) }))))
2134
2166
  drawVoice(s)
2167
+ drawSearch(s)
2135
2168
  put($('g-caps'), ...(s.capabilities || []).map((c) =>
2136
2169
  h('div', { className: 'cap' + (c.ok ? '' : ' cap-off') },
2137
2170
  h('div', { className: 'cap-h' }, h('span', { className: 'cap-mark', textContent: c.ok ? '✓' : '✗' }), h('b', { textContent: c.name }), h('span', { className: c.ok ? 'tag ok' : 'tag need', textContent: c.ok ? 'ready' : 'needs setup' })),
@@ -2174,6 +2207,71 @@ $('v-src').onchange = (e) => {
2174
2207
  $('v-model').onchange = () => saveVoice('voice model saved')
2175
2208
  $('v-lang').onchange = () => saveVoice('voice language saved')
2176
2209
 
2210
+ // Web search: the engines in the order they're asked (↑↓), each switchable. Your own SearXNG's address
2211
+ // is typed in its own row: a box with Test and Add while there's none (or Change was pressed), else the
2212
+ // address with Change, Test and Remove.
2213
+ const ENGINE_INFO = {
2214
+ searxng: 'Your own instance: private, and no other site\'s limits. Its JSON API is used when it has it on.',
2215
+ searx: 'Many engines at once, through public instances from searx.space. Broad; some instances are busy.',
2216
+ duckduckgo: 'Broad results from its HTML page. Blocked on some networks.',
2217
+ mwmbl: 'An open, non-profit index of its own. Fast; smaller than the big engines.',
2218
+ stackoverflow: 'Questions and answers: for errors and how-to. Up to 3 results.',
2219
+ npm: 'Packages: for libraries and tools. Up to 3 results.',
2220
+ github: 'Repositories: for projects and examples. Up to 3 results.',
2221
+ }
2222
+ const wsInput = h('input', { type: 'text', placeholder: 'http://192.168.1.10:8888 or https://search.example.com', spellcheck: false, autocomplete: 'off', 'aria-label': 'Your SearXNG address' })
2223
+ let wsEditing = false
2224
+ const wsCancel = () => ((wsEditing = false), wsInput.blur(), drawSearch(S))
2225
+ const wsSave = async (url) => {
2226
+ const r = await act('/api/search', { searxng: url }, url.trim() ? 'your SearXNG saved: it is asked first' : 'your SearXNG removed')
2227
+ if (r) (wsEditing = false), wsInput.blur(), S && drawSearch(S)
2228
+ }
2229
+ const wsTest = async (url) => {
2230
+ const r = await act('/api/search/test', { searxng: url })
2231
+ if (r) toast(`it works: ${r.results} results for a test search`)
2232
+ }
2233
+ wsInput.onkeydown = (e) => {
2234
+ if (e.key === 'Enter') wsSave(wsInput.value) // a block: an on… handler returning false would cancel every other key (typing, pasting)
2235
+ if (e.key === 'Escape' && S?.search?.searxng) wsCancel()
2236
+ }
2237
+ function drawSearch(s) {
2238
+ if (document.activeElement === wsInput) return // typing there: left alone (a redraw would take the box away)
2239
+ const w = s.search ?? { order: [], off: [], names: {} }
2240
+ const save = (order, off, what) => act('/api/search', { order, off }, what)
2241
+ const btn = (text, onclick, cls = 'small') => h('button', { className: cls, type: 'button', textContent: text, onclick })
2242
+ put($('ws-order'), ...w.order.map((n, i) => {
2243
+ const mine = n === 'searxng'
2244
+ const none = mine && !w.searxng
2245
+ const on = !w.off.includes(n) && !none
2246
+ const move = (d) => {
2247
+ const o = [...w.order]
2248
+ ;[o[i], o[i + d]] = [o[i + d], o[i]]
2249
+ save(o, w.off, `${w.names[n]}: moved ${d < 0 ? 'up' : 'down'}`)
2250
+ }
2251
+ let extra = null
2252
+ if (mine && (none || wsEditing)) {
2253
+ if (!wsEditing) wsInput.value = ''
2254
+ extra = h('div', { className: 'ws-url' }, wsInput, btn('Test', () => wsTest(wsInput.value), ''), btn(none ? 'Add' : 'Save', () => wsSave(wsInput.value), 'primary'), none ? null : btn('Cancel', wsCancel, ''))
2255
+ } else if (mine) {
2256
+ extra = h('div', { className: 'ws-addr' }, h('code', { textContent: w.searxng }),
2257
+ btn('Change', () => ((wsEditing = true), (wsInput.value = w.searxng), drawSearch(S), wsInput.focus())),
2258
+ btn('Test', () => wsTest(w.searxng)),
2259
+ btn('Remove', () => wsSave('')))
2260
+ }
2261
+ return h('div', { className: 'ws-row' + (on ? '' : ' off') + (mine ? ' mine' : '') },
2262
+ h('span', { className: 'n', textContent: on ? `${w.order.filter((x, j) => j <= i && !w.off.includes(x) && !(x === 'searxng' && !w.searxng)).length}` : '–' }),
2263
+ h('div', { className: 't' }, h('b', { textContent: w.names[n] ?? n }), h('span', { textContent: ENGINE_INFO[n] ?? '' }), extra),
2264
+ h('div', { className: 'mv' },
2265
+ btn('↑', () => move(-1)),
2266
+ btn('↓', () => move(1))),
2267
+ sw({ checked: on, disabled: none, 'aria-label': `Use ${w.names[n]}`, onchange: (e) => save(w.order, e.target.checked ? w.off.filter((x) => x !== n) : [...w.off, n], `${w.names[n]}: ${e.target.checked ? 'on' : 'off'}`) }))
2268
+ }))
2269
+ // ↑ on the first and ↓ on the last can't move
2270
+ const rows = [...$('ws-order').children]
2271
+ rows[0]?.querySelector('.mv button').setAttribute('disabled', '')
2272
+ rows.at(-1)?.querySelectorAll('.mv button')[1]?.setAttribute('disabled', '')
2273
+ }
2274
+
2177
2275
  // --- Notifications: Telegram set up in three steps (a bot from @BotFather, its token, Start in the
2178
2276
  // bot), then on/off, a test, and which events send one ---
2179
2277
  function drawNotify(s) {
@@ -2501,7 +2599,9 @@ function drawSkills(s) {
2501
2599
  }
2502
2600
  }
2503
2601
  $('k-install').onclick = install
2504
- $('k-url').onkeydown = (e) => e.key === 'Enter' && install()
2602
+ $('k-url').onkeydown = (e) => {
2603
+ if (e.key === 'Enter') install()
2604
+ }
2505
2605
  $('k-import').onclick = openImport
2506
2606
  masterDetail('skills', $('k-items'), $('k-detail'), [{ title: mine.length && theirs.length ? 'Yours' : '', items: mine.map(item) }, { title: 'From projects', items: theirs.map(item) }], (x) => {
2507
2607
  if (!x) return h('div', { className: 'card' }, h('h2', { textContent: 'No skills yet' }), h('p', { className: 'sub', textContent: 'A skill is a prompt you use again and again, like "review this" or "write the release notes". Make one with + New skill, install one from GitHub above, or bring them from Claude Code and others with /import in HeartCode.' }))
@@ -2543,7 +2643,7 @@ let sbDrag = null // the chip being dragged: { id, from: 'palette' | { line, sid
2543
2643
  let sbSaveTimer = null
2544
2644
  const SB_DEFAULT = () => [
2545
2645
  { left: ['provider', 'model'], right: ['mode', 'thinking', 'images'] },
2546
- { left: ['ctx', 'tps', 'autocompact'], right: ['permissions', 'worktree', 'cost'] },
2646
+ { left: ['ctx', 'tps', 'autocompact'], right: ['background', 'permissions', 'worktree', 'cost'] },
2547
2647
  ]
2548
2648
  const sbLabel = (id) => (SB_ITEMS.find((i) => i.id === id) || {}).label || id
2549
2649
  const sbSample = (id) => (SB_ITEMS.find((i) => i.id === id) || {}).sample || id