heartcode 0.1.44 → 0.1.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/settings.js CHANGED
@@ -8,29 +8,29 @@ import fs from 'node:fs'
8
8
  import path from 'node:path'
9
9
  import crypto from 'node:crypto'
10
10
  import os from 'node:os'
11
- import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf, VERSION } from './config.js'
11
+ import { HOME, saveConfig, readJson, writeJson, byName, takeIn, whatOf, VERSION, speedOf, SPEED_LIMITS } from './config.js'
12
12
  import { newer } from './update.js'
13
- import { DEFAULT_SERVERS, mcpAuth } from './mcp.js'
14
- import { sections, BUILTIN_PROMPTS } from './prompts.js'
13
+ import { DEFAULT_SERVERS, mcpAuth, serverName } from './mcp.js'
14
+ import { sections, BUILTIN_PROMPTS, prompt, reloadPrompts } from './prompts.js'
15
15
  import { Client } from './client.js'
16
- import { clip } from './tools.js'
16
+ import { clip, TOOL_DEFS } from './tools.js'
17
17
  import { loadProfile, strategy, profilePath, profileFrom } from './probe.js'
18
18
  import { loadPrices, priceOf, limitsOf } from './usage.js'
19
19
  import { THEMES, PERMISSIONS } from './ui.js'
20
- import { loadSkills, frontMatter, BUNDLED } from './skills.js'
20
+ import { loadSkills, frontMatter, skillFiles } from './skills.js'
21
+ import { loadRankings, rankings, rankIn } from './rankings.js'
22
+ // a model's places in LMArena's public rankings, shown on Your models: { coding, web, vision } as { rank, of, score }
23
+ const RANKED_ON = { coding: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
24
+ const ranksOf = (model, data) => (data ? Object.fromEntries(Object.entries(RANKED_ON).map(([k, list]) => [k, rankIn(model, list, data)])) : null)
21
25
  import { installSkill, findImports } from './importer.js'
22
26
  import { capabilities } from './capabilities.js'
23
27
  import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
24
28
  import { searchSettings, testSearxng, ENGINE_NAMES } from './web.js'
25
- import { loadRankings, rankings, rankIn } from './rankings.js'
26
- // a model's places in the rankings shown on Your models: { coding, web, vision } as { rank, of, as }
27
- const RANKED_ON = { coding: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
28
- const ranksOf = (model, data) => (data ? Object.fromEntries(Object.entries(RANKED_ON).map(([k, list]) => [k, rankIn(model, list, data)])) : null)
29
29
  import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs, LOG_KINDS, kindsOn, listLogRuns, readLog } from './log.js'
30
30
 
31
31
  const PAGE = new URL('./settings.html', import.meta.url)
32
32
  const EFFORTS = ['default', 'low', 'medium', 'high']
33
- const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit", updateCheck: 'check at every start whether a newer HeartCode is out (shown in the status bar; /update installs it)' }
33
+ const TOGGLES = { autoCompact: 'compact the conversation when it fills 85% of the model\'s context window', director: 'let the model add skills, MCP servers and change settings when asked', format: "run the project's formatter on every file HeartCode writes", lsp: "show the model a language server's errors after each edit", updateCheck: 'check at every start whether a newer HeartCode is out (shown in the status bar; /update installs it)', mouse: "the wheel scrolls only the conversation (the tabs, the input and the status bar stay put) and dragging copies; Option+drag (Shift+drag elsewhere) is the terminal's own selection. Off: the terminal's own mouse, and its wheel scrolls the whole screen" }
34
34
  // The Logging page's: both off unless switched on; how much of each request ("full" or "summary")
35
35
  // The status-bar items the visual editor offers (id must match App.status in bin/heartcode.js).
36
36
  // `sample` is shown in the page's live preview.
@@ -55,13 +55,13 @@ const DETAILS = ['full', 'summary']
55
55
  const FILES = [
56
56
  ['mcp.json', 'MCP servers: programs that give the model more tools', true, '{\n "mcpServers": {\n "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"] },\n "docs": { "url": "https://mcp.example.com/mcp" }\n }\n}'],
57
57
  ['hooks.json', 'Your commands, run before or after the model uses a tool (one can block it)', true, '{\n "hooks": {\n "PreToolUse": [\n { "matcher": "run_command", "hooks": [{ "type": "command", "command": "./check-command.sh" }] }\n ]\n }\n}'],
58
- ['keybindings.json', 'Your own keys: an action, or a /command to send', true, '{\n "ctrl+o": "cycle_permissions",\n "ctrl+g": "/toggle_thinking"\n}'],
58
+ ['keybindings.json', 'Your own keys: an action, or a /command to send', true, '{\n "alt+o": "cycle_permissions",\n "alt+g": "/toggle_thinking"\n}'],
59
59
  ['theme.json', 'Your own colors, on top of the theme you chose', true, '{\n "brand": "#ff6b9d",\n "background": "#101014"\n}'],
60
60
  ['format.json', 'The formatter to run on each kind of file HeartCode writes', true, '{\n ".go": "gofmt -w {file}",\n ".py": "ruff format {file}"\n}'],
61
61
  ['HEARTCODE.md', 'Your instructions for every project (like AGENTS.md, for all of them)', false, '- Answer briefly.\n- Use pnpm, not npm.'],
62
62
  ]
63
63
  // The prompts the page edits: every section of these files (prompts/*.md); the system prompts first.
64
- const PROMPT_FILES = ['agent', 'guided', 'compact']
64
+ const PROMPT_FILES = ['agent', 'guided', 'compact', 'tests']
65
65
  const FIRST = { 'agent/system': 'System prompt (models with tool calls)', 'guided/system': 'System prompt (guided mode: models without tool calls)' }
66
66
  const ownPrompts = (file) => path.join(HOME, 'prompts', `${file}.md`)
67
67
  const tilde = (p) => (p.startsWith(os.homedir() + path.sep) ? '~' + p.slice(os.homedir().length) : p)
@@ -90,13 +90,30 @@ function setPrompt(file, name, text) {
90
90
  fs.writeFileSync(f, `# ${file}.md: your changes to HeartCode's prompts (the settings page; prompts/README.md in HeartCode)\n\n` + [...own].map(([n, t]) => `## ${n}\n\n${t}\n`).join('\n'))
91
91
  }
92
92
 
93
- // MCP servers: built in, yours (mcp.json); each on or off.
93
+ // MCP servers: yours (mcp.json), each on or off (an entry with neither command nor url only switched off a
94
+ // server HeartCode used to come with: not listed).
95
+ // A local server's flags, to tick on and off: what comes after the package or script it runs (npx's
96
+ // own -y isn't one), a value kept with its flag ("--port 3000"); the ones ticked off are kept in its
97
+ // offFlags, so they can come back.
98
+ const RUNNER_WORDS = new Set(['dlx', 'exec', 'run', 'x', 'tool'])
99
+ function flagsOf(c) {
100
+ const args = c.args ?? []
101
+ const at = args.findIndex((a, i) => !a.startsWith('-') && !RUNNER_WORDS.has(a) && !(i === 0 && c.command === 'docker'))
102
+ const on = []
103
+ for (let i = at + 1; at >= 0 && i < args.length; i++) {
104
+ if (!args[i].startsWith('-')) continue
105
+ const value = args[i + 1] !== undefined && !args[i + 1].startsWith('-') && !args[i].includes('=') ? args[++i] : null
106
+ on.push(value === null ? args[i] : `${args[i - 1]} ${value}`)
107
+ }
108
+ return [...on.map((flag) => ({ flag, on: true })), ...(c.offFlags ?? []).filter((f) => !on.includes(f)).map((flag) => ({ flag, on: false }))]
109
+ }
110
+
94
111
  function mcpServers() {
95
112
  const own = readJson(path.join(HOME, 'mcp.json'), {})?.mcpServers ?? {}
96
113
  const from = Object.fromEntries(Object.keys(DEFAULT_SERVERS).map((n) => [n, 'built in']))
97
114
  const all = structuredClone(DEFAULT_SERVERS)
98
115
  for (const [n, c] of Object.entries(own)) all[n] = { ...all[n], ...c }
99
- return Object.entries(all).map(([name, c]) => ({ name, from: from[name] ?? 'yours', on: !c.disabled, remote: Boolean(c.url), auth: mcpAuth(c), what: c.url ?? [c.command, ...(c.args ?? [])].filter(Boolean).join(' '), description: c.description ?? '' }))
116
+ return Object.entries(all).filter(([, c]) => c.command || c.url).map(([name, c]) => ({ name, from: from[name] ?? 'yours', on: !c.disabled, remote: Boolean(c.url), auth: mcpAuth(c), what: c.url ?? [c.command, ...(c.args ?? [])].filter(Boolean).join(' '), description: c.description ?? '' , flags: c.url ? [] : flagsOf(c) }))
100
117
  }
101
118
 
102
119
  // The model list: #1 is the model (cfg.provider/model), the rest cfg.rotation.then, in order.
@@ -144,6 +161,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
144
161
  let importCache = [] // the last /api/imports listing, so /api/imports/run can execute by id
145
162
  const token = crypto.randomBytes(24).toString('hex')
146
163
  const changed = (what) => {
164
+ if (what === 'prompts') reloadPrompts() // this page's own Tests use them too (heart settings has no HeartCode to apply them)
147
165
  try {
148
166
  apply(what)
149
167
  } catch (e) {
@@ -246,6 +264,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
246
264
  // How long a model test waits for its answer (cfg.testTimeout, seconds; the settings page sets it).
247
265
  const testWait = () => (Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10) * 1000
248
266
  const noAnswer = () => `no answer within ${testWait() / 1000} seconds`
267
+ // A provider's models tested a few at a time (more for a long list: startRun)
268
+ const AT_ONCE = 4
249
269
  // Never throws: { ok, ms, reply } or { ok: false, ms, status, error }; { stopped } when stop
250
270
  // (a run's Stop) cancels it.
251
271
  async function tryOne({ provider, model }, stop) {
@@ -255,15 +275,37 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
255
275
  const t0 = Date.now()
256
276
  try {
257
277
  const signal = stop ? AbortSignal.any([AbortSignal.timeout(testWait()), stop]) : AbortSignal.timeout(testWait())
258
- const r = await c.chat({ messages: [{ role: 'user', content: 'Reply with just the word OK.' }], stream: true }, { signal })
278
+ const r = await c.chat({ messages: [{ role: 'user', content: prompt('tests/hello') }], stream: true }, { signal })
259
279
  const reply = (r.content || '').trim()
260
280
  if (!reply && !r.toolCalls.length) return { ok: false, ms: Date.now() - t0, error: `it answered with nothing${r.usage?.completion_tokens ? ` (${r.usage.completion_tokens} tokens it said it wrote)` : ''}` }
261
- return { ok: true, ms: Date.now() - t0, reply: reply.slice(0, 80) }
281
+ const ms = Date.now() - t0
282
+ return { ok: true, ms, reply: reply.slice(0, 80), ...(testedOf({ provider, model })?.mode === 'tools' && (await toolTest(c, stop))) }
262
283
  } catch (e) {
263
284
  if (stop?.aborted) return { stopped: true }
264
285
  return { ok: false, ms: Date.now() - t0, status: e.status ?? null, error: e.name === 'TimeoutError' ? noAnswer() : whyFailed(e), ...(e.retryAfter > 0 && { retryAfter: Number(e.retryAfter) }) }
265
286
  }
266
287
  }
288
+ // A model that says it calls tools: can it do work with one? One of HeartCode's own tools and a
289
+ // small job; a call that does it passes. { toolsOk, toolsWhy }; nothing when it didn't answer in time.
290
+ async function toolTest(c, stop) {
291
+ const tools = TOOL_DEFS.filter((f) => f.name === 'write_file').map((f) => ({ type: 'function', function: f }))
292
+ try {
293
+ const signal = stop ? AbortSignal.any([AbortSignal.timeout(testWait()), stop]) : AbortSignal.timeout(testWait())
294
+ const r = await c.chat({ messages: [{ role: 'user', content: prompt('tests/tool-check') }], tools, stream: true }, { signal })
295
+ const call = r.toolCalls.find((x) => x.function.name === 'write_file')
296
+ if (!call) return { toolsOk: false, toolsWhy: r.toolCalls.length ? `it called ${r.toolCalls[0].function.name} instead of write_file` : `it answered in text instead of calling the tool: "${clip((r.content || '').trim(), 80)}"` }
297
+ let a
298
+ try {
299
+ a = JSON.parse(call.function.arguments || '{}')
300
+ } catch {
301
+ return { toolsOk: false, toolsWhy: `its tool call isn't valid JSON: ${clip(call.function.arguments, 80)}` }
302
+ }
303
+ return /notes\.txt$/.test(String(a.path ?? '')) && /hello/i.test(String(a.content ?? '')) ? { toolsOk: true } : { toolsOk: false, toolsWhy: `wrong arguments: ${clip(call.function.arguments, 100)}` }
304
+ } catch (e) {
305
+ if (stop?.aborted || e.name === 'TimeoutError') return {}
306
+ return { toolsOk: false, toolsWhy: `a request with tools failed: ${whyFailed(e)}` }
307
+ }
308
+ }
267
309
  // result: kept and sent to the page (given: a test already made, as a run decided to end it)
268
310
  async function testOne(t, given) {
269
311
  const key = `${t.provider}/${t.model}`
@@ -282,7 +324,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
282
324
  const RATE_TRIES = 4
283
325
  let run = null
284
326
  const runState = () => ({
285
- total: run.total, done: run.done, good: run.good, each: run.each, busy: [...run.busy.keys()], stopping: run.stopping, some: run.some, started: run.started,
327
+ total: run.total, done: run.done, good: run.good, each: run.each, busy: [...run.busy.keys()], now: [...run.now], stopping: run.stopping, some: run.some, started: run.started,
286
328
  paused: Object.fromEntries([...run.providers].filter(([, p]) => p.until > Date.now()).map(([name, p]) => [name, Math.ceil((p.until - Date.now()) / 1000)])),
287
329
  })
288
330
  // your models now ("provider/model"), to skip the ones taken off while a run goes
@@ -294,8 +336,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
294
336
  }
295
337
  const wait = (ms) => new Promise((r) => setTimeout(r, ms))
296
338
  async function startRun(list, some) {
297
- const each = Math.max(1, Math.ceil(list.length / 100))
298
- run = { total: list.length, done: 0, good: 0, each, busy: new Map(), pending: new Set(list.map((t) => `${t.provider}/${t.model}`)), stopping: false, some, started: Date.now(), providers: new Map(), cancel: new AbortController() }
339
+ const each = Math.max(AT_ONCE, Math.ceil(list.length / 100))
340
+ run = { total: list.length, done: 0, good: 0, each, busy: new Map(), now: new Set(), pending: new Set(list.map((t) => `${t.provider}/${t.model}`)), stopping: false, some, started: Date.now(), providers: new Map(), cancel: new AbortController() }
299
341
  emit('testrun', runState())
300
342
  for (const t of list) {
301
343
  if (!run.providers.has(t.provider)) run.providers.set(t.provider, { queue: [], cap: each, until: 0, pausedAt: 0, backoff: 15_000, refused: new Map() })
@@ -321,7 +363,10 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
321
363
  }
322
364
  run.busy.set(provider, (run.busy.get(provider) ?? 0) + 1)
323
365
  const sent = Date.now()
366
+ run.now.add(`${t.provider} ${t.model}`) // the models being tested this moment, for the page
367
+ emit('testrun', runState())
324
368
  const r = await tryOne(t, run.cancel.signal)
369
+ run.now.delete(`${t.provider} ${t.model}`)
325
370
  if (r.stopped) break // Stop: not a result (its last one stays)
326
371
  run.busy.get(provider) > 1 ? run.busy.set(provider, run.busy.get(provider) - 1) : run.busy.delete(provider)
327
372
  if (r.status === 429) {
@@ -372,9 +417,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
372
417
  update: (({ latest } = {}) => (cfg.updateCheck !== false && latest && newer(latest, VERSION) ? latest : null))(readJson(path.join(HOME, 'update-check.json'), {})), // the day's answer from npm: no request here
373
418
  order: [...(cfg.providers[cfg.provider] && cfg.model ? [{ provider: cfg.provider, model: cfg.model }] : []), ...rotationOf(cfg).then].map((t) => ({ ...t, tested: testedOf(t), known: knownOf(t), price: priceFor(t), ranks: ranksOf(t.model, ranked) })),
374
419
  rankings: ranked && { fetched: ranked.fetched, source: ranked.source },
375
- orchestrators: cfg.orchestrators ?? [],
376
420
  rotation: (({ then, ...opts }) => opts)(rotationOf(cfg)),
377
- settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), logs: kindsOn(cfg), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10, modelChoice: cfg.modelChoice === 'fit' ? 'fit' : 'order', replyStart: Number(cfg.replyStart) > 0 ? Number(cfg.replyStart) : 60 },
421
+ settings: { permissions: cfg.permissions ?? 'all', effort: cfg.effort ?? 'default', theme: cfg.theme ?? 'dark', context: cfg.context ?? null, ...Object.fromEntries(Object.keys(TOGGLES).map((k) => [k, cfg[k] !== false])), logs: kindsOn(cfg), logDetail: cfg.logDetail === 'summary' ? 'summary' : 'full', logDays: logDays(cfg), testTimeout: Number(cfg.testTimeout) > 0 ? Number(cfg.testTimeout) : 10, ...speedOf(cfg) },
378
422
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
379
423
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
380
424
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
@@ -384,7 +428,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
384
428
  capabilities: capabilities(cfg), // features that need outside tools, and whether they're here
385
429
  choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES, statusItems: STATUS_ITEMS, logKinds: Object.fromEntries(Object.entries(LOG_KINDS).map(([k, { label, about }]) => [k, { label, about }])) },
386
430
  files: FILES.map(([name, about, json, example]) => ({ name, about, json, example, text: fs.existsSync(path.join(HOME, name)) ? fs.readFileSync(path.join(HOME, name), 'utf8') : '' })),
387
- skills: [...loadSkills(null).values()].map((s) => ({ name: s.name, description: s.description, use: s.use, mine: s.file.startsWith(skillsDir() + path.sep), builtIn: s.file.startsWith(BUNDLED), text: fs.readFileSync(s.file, 'utf8') })),
431
+ skills: [...loadSkills(null).values()].map((s) => ({ name: s.name, description: s.description, use: s.use, mine: s.file.startsWith(skillsDir() + path.sep), text: fs.readFileSync(s.file, 'utf8'), path: tilde(path.basename(s.file) === 'SKILL.md' ? path.dirname(s.file) : s.file), files: skillFiles(s) })), // a folder skill: its other files (guides, assets)
388
432
  mcp: mcpServers(),
389
433
  prompts: prompts(),
390
434
  home: tilde(HOME),
@@ -393,7 +437,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
393
437
 
394
438
  const routes = {
395
439
  'GET /api/state': () => state(),
396
- // the public rankings, fetched now (with models.dev: Update model info on Your models)
440
+ // LMArena's public rankings, fetched now (with models.dev: Update model info on Your models)
397
441
  'POST /api/rankings': async () => {
398
442
  if (!(await rankings({ now: true }))) throw new Error("couldn't get the rankings (huggingface.co)")
399
443
  return state()
@@ -556,22 +600,12 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
556
600
  forgetTests()
557
601
  return state()
558
602
  },
559
- // The models that orchestrate when Pick is "an orchestrator hands it out": [{ provider, model }]
560
- // (none: your first that calls tools)
561
- 'POST /api/orchestrators': ({ list }) => {
562
- if (!Array.isArray(list)) throw new Error('a list of models is needed')
563
- const clean = list.map((t) => ({ provider: String(t?.provider ?? ''), model: String(t?.model ?? '').trim() })).filter((t) => cfg.providers[t.provider] && t.model)
564
- cfg.orchestrators = clean.length ? clean : undefined
565
- save('setting:orchestrators')
566
- return state()
567
- },
568
603
  // models.dev again (one model, or all of yours): its list fetched anew, and each model's profile
569
604
  // takes what it says now (one it didn't know before becomes "from models.dev"; your own settings
570
605
  // for it stay above). A running HeartCode takes it at once.
571
606
  // Test: one short message to the model, to see that it answers (key, access, name, the server
572
607
  // itself). In the requests log as a model test. Never throws: { ok, ms, reply } or { ok: false, error }.
573
608
  'POST /api/try': ({ provider, model } = {}) => testOne({ provider, model: String(model ?? '') }),
574
- // the tests' results, and the run going now (with the models it hasn't tested yet)
575
609
  // Test, on a model's row: one "Hello" to it, and exactly what was sent and what came back (the
576
610
  // key masked), for the page to show. Not streamed, so the answer is the provider's own JSON.
577
611
  'POST /api/hello': async ({ provider, model }) => {
@@ -594,6 +628,7 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
594
628
  return { sent, received: { error: e.name === 'TimeoutError' ? noAnswer() : `couldn't send it: ${e.cause?.code || e.cause?.message || e.message}`, ms: Date.now() - t0 } }
595
629
  }
596
630
  },
631
+ // the tests' results, and the run going now (with the models it hasn't tested yet)
597
632
  'POST /api/tests': () => ({ results: tests, run: run && { ...runState(), pending: [...run.pending] } }),
598
633
  // a run: all your models, or the ones given (only); one at a time if one is going already
599
634
  'POST /api/tests/start': ({ only } = {}) => {
@@ -671,9 +706,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
671
706
  if (name === 'logDays' && !(Number.isInteger(value) && value >= 1 && value <= 3650)) throw new Error('logDays: a whole number of days, 1 to 3650')
672
707
  if (name === 'logDetail' && !DETAILS.includes(value)) throw new Error(`logDetail: ${DETAILS.join(' or ')}`)
673
708
  if (name === 'testTimeout' && !(Number.isInteger(value) && value >= 1 && value <= 600)) throw new Error('test timeout: a whole number of seconds, 1 to 600')
674
- if (name === 'replyStart' && !(Number.isInteger(value) && value >= 5 && value <= 600)) throw new Error('a reply must start within: a whole number of seconds, 5 to 600')
675
- if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', 'modelChoice', 'replyStart', ...Object.keys(TOGGLES)].includes(name)) throw new Error(`no setting "${name}"`)
676
- if (name === 'modelChoice' && !['order', 'fit'].includes(value)) throw new Error('modelChoice: order or fit (an orchestrator)')
709
+ if (name in SPEED_LIMITS && !(Number.isInteger(value) && value >= SPEED_LIMITS[name][0] && value <= SPEED_LIMITS[name][1])) throw new Error(`${name}: a whole number, ${SPEED_LIMITS[name][0]} to ${SPEED_LIMITS[name][1]}`)
710
+ if (!['permissions', 'effort', 'theme', 'context', 'logDetail', 'logDays', 'testTimeout', ...Object.keys(SPEED_LIMITS), ...Object.keys(TOGGLES)].includes(name)) throw new Error(`no setting "${name}"`)
677
711
  cfg[name] = name === 'effort' && value === 'default' ? undefined : name === 'context' ? (value === null ? undefined : Number(value)) : value
678
712
  save(`setting:${name}`)
679
713
  if (name === 'logDetail') useRequestLog(cfg) // from the next request (a running HeartCode takes it in too: applySettings)
@@ -822,8 +856,6 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
822
856
  },
823
857
  // a server of yours, from the form: a command on this machine, or a remote URL
824
858
  'POST /api/mcp/add': ({ name, command, url }) => {
825
- name = safeName(name)
826
- if (!name) throw new Error('a name is needed')
827
859
  const words = String(command ?? '').match(/"[^"]*"|'[^']*'|\S+/g)?.map((w) => w.replace(/^(["'])(.*)\1$/, '$2')) ?? []
828
860
  url = String(url ?? '').trim()
829
861
  if (!words.length === !url) throw new Error('give a command, or a URL')
@@ -832,12 +864,36 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
832
864
  if (fs.existsSync(file) && !readJson(file, null)) throw new Error("mcp.json isn't valid JSON: fix it first")
833
865
  const data = readJson(file, null) ?? {}
834
866
  const servers = (data.mcpServers ??= {})
835
- if (servers[name] && !servers[name].disabled && (servers[name].command || servers[name].url)) throw new Error(`there's a server "${name}" already`)
867
+ // its name: as given, else from the command or URL; a name in use by a working server gets -2, -3…
868
+ const inUse = Object.entries(servers).filter(([, c]) => c.command || c.url).map(([n]) => n)
869
+ name = safeName(name) || serverName(url || String(command ?? ''), inUse)
870
+ if (inUse.includes(name)) throw new Error(`there's a server "${name}" already`)
836
871
  servers[name] = url ? { url } : { command: words[0], args: words.slice(1) }
837
872
  writeJson(file, data)
838
873
  changed('mcp')
839
874
  return state()
840
875
  },
876
+ // a flag of a local server ticked on (back into its command) or off (kept aside in offFlags)
877
+ 'POST /api/mcp/flag': ({ name, flag, on }) => {
878
+ const file = path.join(HOME, 'mcp.json')
879
+ if (fs.existsSync(file) && !readJson(file, null)) throw new Error("mcp.json isn't valid JSON: fix it first")
880
+ const data = readJson(file, null) ?? {}
881
+ const c = data.mcpServers?.[name]
882
+ if (!c?.command) throw new Error(`no local MCP server "${name}" of yours`)
883
+ flag = String(flag ?? '').trim().replace(/\s+/g, ' ')
884
+ const words = flag.split(' ')
885
+ if (!/^-/.test(words[0]) || words.length > 2) throw new Error('a flag starts with - (and may have one value: --port 3000)')
886
+ const args = c.args ?? []
887
+ const at = args.findIndex((a, i) => a === words[0] && (words.length === 1 || args[i + 1] === words[1]))
888
+ if (at >= 0) args.splice(at, words.length)
889
+ if (on) args.push(...words)
890
+ c.args = args
891
+ c.offFlags = on ? (c.offFlags ?? []).filter((f) => f !== flag) : [...new Set([...(c.offFlags ?? []), flag])]
892
+ if (!c.offFlags.length) delete c.offFlags
893
+ writeJson(file, data)
894
+ changed('mcp')
895
+ return state()
896
+ },
841
897
  'POST /api/mcp/remove': ({ name }) => {
842
898
  const file = path.join(HOME, 'mcp.json')
843
899
  const data = readJson(file, null)
@@ -875,10 +931,19 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
875
931
  if (!String(text ?? '').trim()) throw new Error('a skill needs its text')
876
932
  const { meta } = frontMatter(text)
877
933
  if (meta.name && safeName(meta.name) !== name) throw new Error(`the text says name: ${meta.name}, but the skill is called ${name}`)
878
- if (was && was !== name) removeSkill(was)
879
- const dir = path.join(skillsDir(), name)
880
- fs.mkdirSync(dir, { recursive: true })
881
- fs.writeFileSync(path.join(dir, 'SKILL.md'), text.endsWith('\n') ? text : text + '\n')
934
+ // where it lives: a one-file skill (<name>.md) stays one; a folder skill keeps its other files.
935
+ // Renamed: its file or folder moves (a folder's guides go with it). New: a folder.
936
+ const fileOf = (n) => (fs.existsSync(path.join(skillsDir(), `${n}.md`)) ? path.join(skillsDir(), `${n}.md`) : path.join(skillsDir(), n, 'SKILL.md'))
937
+ const old = was && safeName(was)
938
+ if (old && old !== name) {
939
+ const from = fileOf(old)
940
+ const to = path.basename(from) === 'SKILL.md' ? path.join(skillsDir(), name) : path.join(skillsDir(), `${name}.md`)
941
+ if (fs.existsSync(to) || fs.existsSync(fileOf(name))) throw new Error(`there's already a skill called ${name}`)
942
+ if (fs.existsSync(from)) fs.renameSync(path.basename(from) === 'SKILL.md' ? path.dirname(from) : from, to)
943
+ }
944
+ const file = fileOf(name)
945
+ fs.mkdirSync(path.dirname(file), { recursive: true })
946
+ fs.writeFileSync(file, text.endsWith('\n') ? text : text + '\n')
882
947
  changed('skill')
883
948
  return state()
884
949
  },
package/src/skills.js CHANGED
@@ -1,12 +1,16 @@
1
1
  // Skills: reusable prompts that you can type as /name and/or the model can load when a task
2
- // matches. One file (<name>.md) or a folder (<name>/SKILL.md, for extra files), in
3
- // skills/ in HeartCode the ones it comes with
4
- // ~/.heart/skills/ for every project (wins over those on the same name)
2
+ // matches. One file (<name>.md) or a folder (<name>/SKILL.md, for extra files), in (HeartCode comes
3
+ // with none: you add or install them)
4
+ // ~/.heart/skills/ for every project
5
5
  // .heartcode/skills/ for one project (wins on the same name)
6
6
  // ---
7
7
  // description: Review my changes before committing (what the model sees; also in the / menu)
8
8
  // use: both me (only typed: costs nothing until used) · model (only the model) · both
9
9
  // · always (in every system prompt: how to work, not a task)
10
+ // load: a.md, b.html (a folder skill) its files that come with it when the model loads it, so a
11
+ // model that doesn't go on to read them still has them
12
+ // A skill shared with other CLIs (the Agent Skills spec allows only name, description, license,
13
+ // compatibility, metadata, allowed-tools) puts these under metadata: heartcode-use, heartcode-load.
10
14
  // ---
11
15
  // Review the uncommitted changes, focusing on {{args}}.
12
16
  // !`git diff HEAD`
@@ -14,11 +18,9 @@
14
18
  // other CLIs), @path/to/file (its contents), !`command` (its output).
15
19
  import fs from 'node:fs'
16
20
  import path from 'node:path'
17
- import { fileURLToPath } from 'node:url'
18
21
  import { HOME } from './config.js'
19
22
 
20
23
  export const USES = ['me', 'model', 'both', 'always']
21
- export const BUNDLED = fileURLToPath(new URL('../skills/', import.meta.url))
22
24
 
23
25
  export function frontMatter(text) {
24
26
  const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text)
@@ -38,6 +40,13 @@ export function frontMatter(text) {
38
40
  let v = kept.map((l) => l.slice(Number.isFinite(minIndent) ? minIndent : 0)).join(block[1] === '>' ? ' ' : '\n')
39
41
  if (block[2] !== '+') v = v.replace(/\n+$/, '') // "-" strips trailing newlines; default keeps one at most
40
42
  meta[k] = v.trim()
43
+ } else if (!raw.trim() && /^\s+[\w-]+:/.test(lines[i + 1] ?? '')) {
44
+ // a map (the Agent Skills spec's "metadata:"): its indented "key: value" lines
45
+ meta[k] = {}
46
+ while (i + 1 < lines.length && (lines[i + 1].trim() === '' || indent(lines[i + 1]) > base)) {
47
+ const kv = /^\s+([\w-]+):\s*(.*)$/.exec(lines[++i])
48
+ if (kv) meta[k][kv[1]] = kv[2].replace(/^["']|["']$/g, '')
49
+ }
41
50
  } else {
42
51
  meta[k] = raw.replace(/^["']|["']$/g, '')
43
52
  }
@@ -48,6 +57,7 @@ export function frontMatter(text) {
48
57
  // Who can use a skill. Other CLIs' fields are understood too (disable-model-invocation, user-invocable).
49
58
  function useOf(meta, fallback = 'both') {
50
59
  if (USES.includes(meta.use)) return meta.use
60
+ if (USES.includes(meta.metadata?.['heartcode-use'])) return meta.metadata['heartcode-use'] // a skill shared with other CLIs keeps HeartCode's fields in metadata
51
61
  if (meta['disable-model-invocation'] === 'true') return 'me'
52
62
  if (meta['user-invocable'] === 'false') return 'model'
53
63
  return fallback
@@ -57,7 +67,7 @@ function useOf(meta, fallback = 'both') {
57
67
  export const extraSkillDirs = []
58
68
 
59
69
  export function skillDirs(root) {
60
- return [BUNDLED, path.join(HOME, 'skills'), root && path.join(root, '.heartcode', 'skills'), ...extraSkillDirs].filter(Boolean)
70
+ return [path.join(HOME, 'skills'), root && path.join(root, '.heartcode', 'skills'), ...extraSkillDirs].filter(Boolean)
61
71
  }
62
72
 
63
73
  export function loadSkills(root) {
@@ -78,12 +88,37 @@ export function loadSkills(root) {
78
88
  }
79
89
  const { meta, body } = frontMatter(text)
80
90
  const name = (meta.name || e.name.replace(/\.md$/, '')).toLowerCase().replace(/[^a-z0-9_:-]+/g, '-')
81
- skills.set(name, { name, description: meta.description || body.split('\n')[0].slice(0, 100) || '(no description)', use: useOf(meta), hint: meta['argument-hint'] ?? '', body, file })
91
+ skills.set(name, { name, description: meta.description || body.split('\n')[0].slice(0, 100) || '(no description)', use: useOf(meta), hint: meta['argument-hint'] ?? '', body, file, load: String(meta.load ?? meta.metadata?.['heartcode-load'] ?? '').split(',').map((f) => f.trim()).filter(Boolean) })
82
92
  }
83
93
  }
84
94
  return skills
85
95
  }
86
96
 
97
+ // A folder skill's other files (its guides, a stylesheet…), as paths in it: they're read with the
98
+ // skill tool's "file", since they sit outside the project. A one-file skill has none.
99
+ export function skillFiles(k) {
100
+ if (path.basename(k.file) !== 'SKILL.md') return []
101
+ const dir = path.dirname(k.file)
102
+ const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.name.startsWith('.') ? [] : e.isDirectory() ? walk(path.join(d, e.name)) : [path.relative(dir, path.join(d, e.name))]))
103
+ try {
104
+ return walk(dir).filter((f) => f !== 'SKILL.md').sort()
105
+ } catch {
106
+ return []
107
+ }
108
+ }
109
+
110
+ // One of them, or an error (only inside the skill's folder).
111
+ export function readSkillFile(k, file) {
112
+ const dir = path.dirname(k.file)
113
+ const abs = path.resolve(dir, file)
114
+ if (path.basename(k.file) !== 'SKILL.md' || !abs.startsWith(dir + path.sep)) return `error: the ${k.name} skill has no file "${file}"`
115
+ try {
116
+ return fs.readFileSync(abs, 'utf8')
117
+ } catch {
118
+ return `error: the ${k.name} skill has no file "${file}". Its files: ${skillFiles(k).join(', ') || 'none'}`
119
+ }
120
+ }
121
+
87
122
  // The skill's text with the arguments filled in ({{args}}, {{1}}…, or $ARGUMENTS, $1…).
88
123
  export function fillArgs(body, args) {
89
124
  const words = String(args ?? '').trim().split(/\s+/).filter(Boolean)
package/src/tabs.js CHANGED
@@ -137,7 +137,7 @@ export class Tabs {
137
137
  mid += line('│') + label + line('│') + ' '
138
138
  bottom += (on ? c.brand(`╯${' '.repeat(w)}╰`) : c.ghost(`┴${'─'.repeat(w)}┴`)) + c.ghost('─')
139
139
  })
140
- const hint = this.list.length > 1 ? 'Alt+T open a tab · Alt+W close this one · Alt+N/P (or Ctrl+PgUp/PgDn) switch tabs' : 'Alt+T open a new tab'
140
+ const hint = this.list.length > 1 ? 'Alt+T open a tab · Alt+W close this one · Alt+N/P switch tabs' : 'Alt+T open a new tab'
141
141
  mid += ` ${c.faint(hint)}`
142
142
  bottom += c.ghost('─'.repeat(Math.max(0, cols - width(bottom.replace(/\x1b\[[0-9;]*m/g, '')))))
143
143
  return [top, mid, bottom]