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/headless.js CHANGED
@@ -48,8 +48,33 @@ export class HeadlessUI {
48
48
  setPermission(mode) {
49
49
  this.permission = mode
50
50
  }
51
- response() {
52
- return { text() {}, think() {}, end() {} }
51
+ // A model's reply as it comes, for --include-partial-messages (stream-json): Claude Code's events
52
+ // (message_start, a content block each for its thinking and its text with their deltas,
53
+ // message_stop) through this.partial. Without it, or a helper's reply (its steps come whole, with
54
+ // their parent): nothing.
55
+ response(who, { helper = false } = {}) {
56
+ const send = !helper && this.partial
57
+ if (!send) return { text() {}, think() {}, end() {} }
58
+ let started = false
59
+ let kind = null
60
+ let index = -1
61
+ const open = (k) => {
62
+ if (!started) (started = true), send({ type: 'message_start', message: { role: 'assistant', model: who, content: [] } })
63
+ if (kind === k) return
64
+ if (kind) send({ type: 'content_block_stop', index })
65
+ kind = k
66
+ send({ type: 'content_block_start', index: ++index, content_block: k === 'thinking' ? { type: 'thinking', thinking: '' } : { type: 'text', text: '' } })
67
+ }
68
+ return {
69
+ think: (t) => t && (open('thinking'), send({ type: 'content_block_delta', index, delta: { type: 'thinking_delta', thinking: t } })),
70
+ text: (t) => t && (open('text'), send({ type: 'content_block_delta', index, delta: { type: 'text_delta', text: t } })),
71
+ end: () => {
72
+ if (kind) send({ type: 'content_block_stop', index })
73
+ if (started) send({ type: 'message_stop' })
74
+ started = false
75
+ kind = null
76
+ },
77
+ }
53
78
  }
54
79
  async ask() {
55
80
  return null
@@ -125,6 +150,7 @@ export async function runHeadless(app, opts) {
125
150
  const asClaude = (name, input) => (name === 'mcp' && input?.server && input?.tool ? { name: mcpName(String(input.server), String(input.tool)), input: input.arguments ?? {} } : { name, input })
126
151
  let said = false // the model's text was already sent as an assistant message
127
152
  if (out === 'stream-json') {
153
+ if (opts.partial) app.ui.partial = (event) => emit({ type: 'stream_event', event, session_id, parent_tool_use_id: null }) // the replies as they come (--include-partial-messages)
128
154
  s.onEvent = (e) => {
129
155
  if (e.type === 'assistant') {
130
156
  const content = [
package/src/log.js CHANGED
@@ -25,7 +25,7 @@ export const LOG_DIR = process.env.HEART_LOG === 'off' ? null : path.resolve(pro
25
25
  // listed goes in debug.
26
26
  export const LOG_KINDS = {
27
27
  tools: { label: 'Tools & commands', about: 'what HeartCode did on your machine: each tool call and its result, commands and background commands, MCP calls, files written', topics: ['tool', 'command', 'mcp', 'background', 'lsp', 'format', 'write', 'web', 'research', 'worktree'] },
28
- models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries, best-fit picks and quirks found', topics: ['rotate', 'retry', 'fit', 'quirk'] },
28
+ models: { label: 'Model choices', about: 'why a model answered or didn\'t: fallbacks, retries and quirks found', topics: ['rotate', 'retry', 'quirk'] },
29
29
  agent: { label: "Agent's decisions", about: 'why it did what it did: each task and its answer, plan-first, reviews, page checks, helpers and parts, compacting, lessons, the wrap-up', topics: ['task', 'look', 'review', 'compact', 'wrapup', 'learn', 'agent', 'director', 'guided', 'rewind', 'btw', 'parts'] },
30
30
  errors: { label: 'Errors', about: 'what went wrong: errors, crashes and warnings, with where they came from', topics: ['error', 'crash', 'warn', 'exit'] },
31
31
  conversation: { label: 'Conversation', about: 'a plain transcript: what you typed, its answers, its questions and your answers', topics: ['input', 'ask', 'answer'] },
package/src/mcp.js CHANGED
@@ -19,27 +19,36 @@ import { HOME, readJson, readConfig, writeJson, VERSION } from './config.js'
19
19
  import { log } from './log.js'
20
20
  import { savedToken, signIn, hasToken } from './oauth.js'
21
21
 
22
- // Built in; a config entry with the same name changes it, "disabled": true turns it off.
23
- export const DEFAULT_SERVERS = {
24
- 'chrome-devtools': {
25
- command: 'npx',
26
- // headless: no window pops up (works over SSH too); isolated: its own throwaway profile, so
27
- // runs don't fight over one. Override args in ~/.heart/mcp.json for a visible browser.
28
- args: ['-y', 'chrome-devtools-mcp@latest', '--headless', '--isolated'],
29
- // a screenshot/snapshot saved by a relative path lands in the server's cwd: a scratch dir, not
30
- // the project, so the browser never litters it (pages are opened by absolute file:// URLs).
31
- scratchCwd: true,
32
- description: 'a Chrome browser: open pages, click, fill forms, read the console and network requests, take screenshots',
33
- },
34
- 'computer-use': {
35
- command: 'npx',
36
- args: ['-y', '@zavora-ai/computer-use-mcp@latest'],
37
- // Off until you switch it on (/settings → MCP servers, or /mcp): it controls your whole desktop.
38
- // Needs the OS's permission (macOS: Screen Recording + Accessibility for your terminal) and a
39
- // vision model that's good at computer use — a weak model won't drive it well.
40
- disabled: true,
41
- description: 'control your computer like a person — screenshots, mouse, keyboard, clipboard (off by default; needs screen/accessibility permission and a capable vision model)',
42
- },
22
+ // Built in: none. HeartCode comes with no MCP servers; you add the ones you want (/settings → MCP
23
+ // servers, /mcp, or ~/.heart/mcp.json). Kept as a map so a server could be built in again by name.
24
+ export const DEFAULT_SERVERS = {}
25
+
26
+ // A server's name from how it's started, so nobody has to make one up: the package or program it
27
+ // runs, without its scope, version and "mcp"/"server" words (npx -y chrome-devtools-mcp@latest →
28
+ // chrome-devtools; uvx mcp-server-fetch → fetch; docker run -i mcp/github → github), or a URL's site
29
+ // (https://mcp.notion.com/mcp → notion). taken: names in use (then -2, -3…). The settings page has a copy.
30
+ const RUNNERS = new Set(['npx', 'bunx', 'pnpx', 'uvx', 'pipx', 'node', 'python', 'python3', 'deno', 'bun', 'docker', 'pnpm', 'yarn', 'uv'])
31
+ const RUNNER_WORDS = new Set(['dlx', 'exec', 'run', 'x', 'tool'])
32
+ export function serverName(given, taken = []) {
33
+ const s = String(given ?? '').trim()
34
+ let base = ''
35
+ if (/^https?:\/\//i.test(s)) {
36
+ try {
37
+ const parts = new URL(s).hostname.replace(/^(www|api|mcp)\./, '').split('.')
38
+ base = parts.length > 1 ? parts.at(-2) : parts[0]
39
+ } catch {}
40
+ } else {
41
+ const words = s.match(/"[^"]*"|'[^']*'|\S+/g)?.map((w) => w.replace(/^(["'])(.*)\1$/, '$2')) ?? []
42
+ const what = words.find((w, i) => !(i === 0 && RUNNERS.has(path.basename(w))) && !w.startsWith('-') && !RUNNER_WORDS.has(w)) ?? words[0] ?? ''
43
+ const pkg = what.replace(/^(@?[^@]+)@.*$/, '$1')
44
+ base = pkg.split(/[\\/]/).pop().replace(/\.(m?js|ts|py)$/, '')
45
+ base = base.replace(/^(mcp[-_]server[-_]|server[-_]|mcp[-_])/, '').replace(/([-_]mcp[-_]server|[-_]mcp|[-_]server)$/, '')
46
+ if (/^(mcp|server|mcp-server)?$/.test(base) && pkg.startsWith('@')) base = pkg.slice(1).split('/')[0] // @playwright/mcp → playwright
47
+ }
48
+ base = base.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'server'
49
+ let name = base
50
+ for (let n = 2; taken.includes(name); n++) name = `${base}-${n}`
51
+ return name
43
52
  }
44
53
 
45
54
  // extra: more configs from the caller (--mcp-config: a file path or JSON text); strict: only those
package/src/prompts.js CHANGED
@@ -67,6 +67,7 @@ export function prompt(id, vars = {}) {
67
67
  if (!(k in vars)) throw new Error(`prompt "${id}" needs {{${k}}}`)
68
68
  return String(vars[k])
69
69
  })
70
+ .trim() // a part left out ({{#if}}) leaves no blank lines behind
70
71
  }
71
72
 
72
73
  // The user's standing instructions: ~/.heart/HEARTCODE.md, then the project's own file. The project's
package/src/reset.js CHANGED
@@ -21,7 +21,7 @@ export const RESETS = [
21
21
  {
22
22
  level: 'everything',
23
23
  label: 'Everything',
24
- desc: `the above, and your sessions, global memory, skills, instructions (HEARTCODE.md), history, logs: all of ${HOME}`,
24
+ desc: `the above, and global memory, skills, instructions (HEARTCODE.md), history, logs: all of ${HOME} (a project's sessions stay in its .heartcode/sessions)`,
25
25
  files: null, // the whole folder
26
26
  },
27
27
  ]
package/src/sessions.js CHANGED
@@ -1,10 +1,25 @@
1
- // Saved conversations: one file per chat in ~/.heart/sessions, written after every message, so a
2
- // chat can be resumed later and rewound to any earlier message (conversation, files, or both).
1
+ // Saved conversations: one file per chat in the project's .heartcode/sessions, written after every
2
+ // message, so a chat can be resumed later and rewound to any earlier message (conversation, files,
3
+ // or both). It stays with the project; the folder ignores itself in git (conversations can hold
4
+ // secrets). Sessions from before (~/.heart/sessions) still list, and move over when next saved.
3
5
  import fs from 'node:fs'
4
6
  import path from 'node:path'
5
- import { HOME, readJson, writeJson } from './config.js'
7
+ import { HOME, projectDir, readJson, writeJson } from './config.js'
6
8
 
7
- const DIR = path.join(HOME, 'sessions')
9
+ const LEGACY = path.join(HOME, 'sessions') // where they all were; also where one goes if its project folder can't be written
10
+ const INDEX = path.join(HOME, 'sessions.json') // id → its folder, so --resume <id> and an editor's session/load work from anywhere
11
+
12
+ // The project a chat belongs to: a worktree's (<top>/.heartcode/worktrees/<name>) is its top's,
13
+ // so removing the worktree doesn't take its sessions with it.
14
+ const projectOf = (root) => path.resolve(root).replace(/[\\/]\.heartcode[\\/]worktrees[\\/][^\\/]+$/, '')
15
+ function dirOf(root) {
16
+ const dir = projectDir(projectOf(root), 'sessions')
17
+ if (!fs.existsSync(path.join(dir, '.gitignore'))) {
18
+ fs.mkdirSync(dir, { recursive: true })
19
+ fs.writeFileSync(path.join(dir, '.gitignore'), '*\n')
20
+ }
21
+ return dir
22
+ }
8
23
 
9
24
  // A chat: what the model has seen (messages for tool mode, history for guided mode), what the
10
25
  // screen showed (log), and per message ("turn") where each of those stood and the files as they
@@ -16,15 +31,29 @@ export function newChat(root) {
16
31
  }
17
32
 
18
33
  export function saveChat(chat) {
19
- const file = path.join(DIR, `${chat.id}.json`)
34
+ const legacy = path.join(LEGACY, `${chat.id}.json`)
35
+ let dir = LEGACY
36
+ try {
37
+ dir = dirOf(chat.root)
38
+ } catch {} // a folder that can't be written (read-only, gone): the global one
39
+ const file = path.join(dir, `${chat.id}.json`)
20
40
  const first = chat.turns[0] ?? chat.branches?.[0]?.state.turns[0] // gone back to the start: its branches remain
21
41
  if (!first) {
22
42
  fs.rmSync(path.join(HOME, 'outputs', chat.id), { recursive: true, force: true }) // its saved tool output goes with it
43
+ fs.rmSync(legacy, { force: true })
23
44
  return fs.rmSync(file, { force: true }) // nothing (left) worth keeping
24
45
  }
25
46
  chat.updated = new Date().toISOString()
26
47
  chat.title = chat.name || first.task.split('\n')[0].slice(0, 80) // its name (/rename), else the first message, even after a rewind
27
- writeJson(file, chat)
48
+ try {
49
+ writeJson(file, chat)
50
+ } catch {
51
+ dir = LEGACY
52
+ writeJson(legacy, chat)
53
+ }
54
+ if (dir !== LEGACY) fs.rmSync(legacy, { force: true }) // an older session, now moved into its project
55
+ const index = readJson(INDEX, {})
56
+ if (index[chat.id] !== dir) writeJson(INDEX, { ...index, [chat.id]: dir })
28
57
  }
29
58
 
30
59
  // /fork: a copy of the chat to go on with (the original stays as it is, in /resume).
@@ -94,20 +123,30 @@ ${body.join('\n')}
94
123
  `
95
124
  }
96
125
 
97
- // One chat by its id (any folder), or null.
98
- export function loadChat(id) {
99
- return /^[\w.-]+$/.test(id) ? readJson(path.join(DIR, `${id}.json`), null) : null
126
+ // One chat by its id, or null: in this folder's project, wherever the index last saw it, or the old place.
127
+ export function loadChat(id, root = process.cwd()) {
128
+ if (!/^[\w.-]+$/.test(id)) return null
129
+ const here = projectDir(projectOf(root), 'sessions')
130
+ for (const dir of new Set([here, readJson(INDEX, {})[id], LEGACY].filter(Boolean))) {
131
+ const chat = readJson(path.join(dir, `${id}.json`), null)
132
+ if (chat) return chat
133
+ }
134
+ return null
100
135
  }
101
136
 
102
- // This folder's chats, newest first.
103
- export function listChats(root) {
104
- let files = []
137
+ const chatsIn = (dir) => {
105
138
  try {
106
- files = fs.readdirSync(DIR).filter((f) => f.endsWith('.json'))
107
- } catch {}
108
- return files
109
- .map((f) => readJson(path.join(DIR, f), null))
110
- .filter((c) => c && c.root === root && (c.turns?.length || c.branches?.length))
139
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => readJson(path.join(dir, f), null))
140
+ } catch {
141
+ return []
142
+ }
143
+ }
144
+
145
+ // This folder's chats, newest first: the project's own, and older ones still in the global place.
146
+ export function listChats(root) {
147
+ const seen = new Set()
148
+ return [...chatsIn(projectDir(projectOf(root), 'sessions')), ...chatsIn(LEGACY)]
149
+ .filter((c) => c && c.root === root && (c.turns?.length || c.branches?.length) && !seen.has(c.id) && seen.add(c.id))
111
150
  .sort((a, b) => b.updated.localeCompare(a.updated))
112
151
  }
113
152