heartcode 0.1.63 → 0.1.95

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/clis.js ADDED
@@ -0,0 +1,601 @@
1
+ // Coding CLIs on this machine as providers: Claude Code, Codex, opencode, Junie and the ones that speak
2
+ // the Agent Client Protocol (Kilo, Cline, Copilot, Cursor, Qwen…). One is added on /settings like any
3
+ // provider, with the address cli://<its name> and no key: its models are the CLI's own, tested and put
4
+ // in your list the same way. A CLI is an agent itself, so a message answered by one is worked on by it,
5
+ // in this folder, with its own tools, signed in its own way; HeartCode shows its thinking, its steps
6
+ // and its answer, and keeps its session for the next message (one it didn't see, from another of your
7
+ // models, is passed on to it first). Anything else asked of it (a summary, a test) is one plain
8
+ // question, in a scratch folder, with nothing it may change.
9
+ // Install routes, logins and invocations: from Nibedita (its internal/clis and internal/cli), checked
10
+ // against each CLI's --help and real runs.
11
+ // ponytail: no images and no effort levels passed to a CLI; Windows' argv limit (~32k) can cut a long
12
+ // first message to opencode, Junie and Kiro (the others read it on stdin or over ACP).
13
+ import fs from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+ import { execFileSync } from 'node:child_process'
17
+ import { spawnCmd, onPath, killTree } from './spawn.js'
18
+ import { guarded } from './guard.js'
19
+ import { log } from './log.js'
20
+
21
+ const WIN = process.platform === 'win32'
22
+ const ACP_MODE = 'https://agentclientprotocol.com/protocol/session-modes#' // Copilot names its modes so
23
+ const npm = (pkg) => ({ cmd: ['npm', 'install', '-g', pkg] })
24
+ const script = (unix, win) => [unix && { os: 'unix', cmd: ['bash', '-c', `curl -fsSL '${unix}' | bash`], also: ['curl'] }, win && { os: 'win32', cmd: ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', `irm '${win}' | iex`] }].filter(Boolean)
25
+
26
+ // id → { title, bin, kind, login (signs in, run in a terminal), page, install routes, … }. ACP ones:
27
+ // args (run it as an ACP server), modes (HeartCode's permission mode → the session settings that make
28
+ // it ask where HeartCode would: [option or 'mode', value]; what it asks, you answer, plan mode only
29
+ // reads), modeEnv (the same in its environment), bypassArgs (no asking, on its command line), modelArgs (a model on the command line, for one whose
30
+ // sessions offer none to pick), models (lists them, for one whose sessions don't).
31
+ export const CLIS = {
32
+ claude: { title: 'Claude Code', bin: 'claude', kind: 'claude', login: 'claude', page: 'https://docs.anthropic.com/en/docs/claude-code/setup', install: [...script('https://claude.ai/install.sh', 'https://claude.ai/install.ps1'), npm('@anthropic-ai/claude-code')] },
33
+ codex: { title: 'Codex', bin: 'codex', kind: 'codex', login: 'codex login', page: 'https://developers.openai.com/codex/cli', install: [npm('@openai/codex')] },
34
+ opencode: { title: 'opencode', bin: 'opencode', kind: 'opencode', login: 'opencode auth login', page: 'https://opencode.ai/docs', install: script('https://opencode.ai/install') },
35
+ junie: { title: 'Junie', bin: 'junie', kind: 'junie', login: 'junie', page: 'https://junie.jetbrains.com/docs/junie-cli.html', install: [...script('https://junie.jetbrains.com/install.sh', 'https://junie.jetbrains.com/install.ps1'), npm('@jetbrains/junie')] },
36
+ kilo: { title: 'Kilo Code', bin: 'kilo', kind: 'acp', args: ['acp'], login: 'kilo auth login', page: 'https://kilo.ai/docs/cli', install: [npm('@kilocode/cli')], modes: { all: [['mode', 'code']], commands: [['mode', 'code']], ask: [['mode', 'code']], plan: [['mode', 'plan']] }, modeEnv: { commands: { KILO_CONFIG_CONTENT: JSON.stringify({ permission: { bash: 'ask' } }) }, ask: { KILO_CONFIG_CONTENT: JSON.stringify({ permission: { edit: 'ask', bash: 'ask', webfetch: 'ask' } }) } } },
37
+ cline: { title: 'Cline', bin: 'cline', kind: 'acp', args: ['--acp'], login: 'cline auth', page: 'https://docs.cline.bot/cline-cli/overview', install: [npm('cline')], modes: { all: [['auto_approve', 'true'], ['mode', 'act']], commands: [['auto_approve', 'false'], ['mode', 'act']], ask: [['auto_approve', 'false'], ['mode', 'act']], plan: [['mode', 'plan']] } },
38
+ agy: { title: 'Antigravity', bin: 'agy', kind: 'acp', args: ['acp'], login: 'agy acp --login', page: 'https://antigravity.google/docs/cli/install', install: script('https://antigravity.google/cli/install.sh', 'https://antigravity.google/cli/install.ps1'), bypassArgs: ['--dangerously-skip-permissions'], modes: { all: [['mode', 'auto']], commands: [['mode', 'accept-edits']], ask: [['mode', 'default']], plan: [['mode', 'plan']] } },
39
+ 'kiro-cli': { title: 'Kiro', bin: 'kiro-cli', kind: 'acp', args: ['acp'], login: 'kiro-cli login', page: 'https://kiro.dev/docs/cli/installation/', install: script('https://cli.kiro.dev/install', 'https://cli.kiro.dev/install.ps1'), modes: { all: [['autopilot', 'on'], ['mode', 'vibe']], commands: [['autopilot', 'off'], ['mode', 'vibe']], ask: [['autopilot', 'off'], ['mode', 'vibe']], plan: [['autopilot', 'off'], ['mode', 'plan']] }, modelArgs: (m) => (m && m !== 'auto' ? ['--model', m] : []), models: kiroModels },
40
+ copilot: { title: 'GitHub Copilot', bin: 'copilot', kind: 'acp', args: ['--acp', '--no-auto-update'], login: 'copilot login', page: 'https://docs.github.com/copilot/how-tos/copilot-cli', install: [npm('@github/copilot')], bypassArgs: ['--allow-all'], modes: { all: [['allow_all', 'on'], ['mode', `${ACP_MODE}autopilot`]], commands: [['mode', `${ACP_MODE}agent`]], ask: [['mode', `${ACP_MODE}agent`]], plan: [['mode', `${ACP_MODE}plan`]] }, modelArgs: (m) => (m ? ['--model', m] : []), models: copilotModels },
41
+ 'cursor-agent': { title: 'Cursor', bin: 'cursor-agent', kind: 'acp', args: ['acp'], login: 'cursor-agent login', page: 'https://cursor.com/docs/cli/installation', install: script('https://cursor.com/install', 'https://cursor.com/install?win32=true'), modes: { all: [['mode', 'agent']], commands: [['mode', 'agent']], ask: [['mode', 'agent']], plan: [['mode', 'plan']] } },
42
+ codebuddy: { title: 'CodeBuddy', bin: 'codebuddy', kind: 'acp', args: ['--acp'], login: 'codebuddy', page: 'https://www.codebuddy.ai/cli', install: [npm('@tencent-ai/codebuddy-code')], modes: { all: [['mode', 'bypassPermissions']], commands: [['mode', 'acceptEdits']], ask: [['mode', 'default']], plan: [['mode', 'plan']] } },
43
+ qwen: { title: 'Qwen Code', bin: 'qwen', kind: 'acp', args: ['--acp'], login: 'qwen', page: 'https://github.com/QwenLM/qwen-code', install: [npm('@qwen-code/qwen-code')], modes: { all: [['mode', 'yolo']], commands: [['mode', 'auto-edit']], ask: [['mode', 'default']], plan: [['mode', 'plan']] } },
44
+ qodercli: { title: 'Qoder', bin: 'qodercli', kind: 'acp', args: ['--acp'], login: 'qodercli login', page: 'https://www.npmjs.com/package/@qoder-ai/qodercli', install: [npm('@qoder-ai/qodercli')], modes: { all: [['mode', 'yolo']], commands: [['mode', 'acceptEdits']], ask: [['mode', 'default']], plan: [['mode', 'default']] } },
45
+ vibe: { title: 'Mistral Vibe', bin: 'vibe-acp', kind: 'acp', args: [], login: 'vibe-acp --setup', page: 'https://github.com/mistralai/mistral-vibe', install: [{ cmd: ['uv', 'tool', 'install', 'mistral-vibe'] }, { cmd: ['pipx', 'install', 'mistral-vibe'] }], modes: { all: [['mode', 'auto-approve']], commands: [['mode', 'accept-edits']], ask: [['mode', 'ask']], plan: [['mode', 'ask']] } },
46
+ alphacode: { title: 'AlphaCode', bin: 'alphacode', kind: 'acp', args: ['acp', '--quiet', '--no-update'], login: 'alphacode', page: 'https://github.com/dragonked2/alphacode#install-in-30-seconds', install: script('https://raw.githubusercontent.com/dragonked2/alphacode/main/scripts/install.sh', 'https://raw.githubusercontent.com/dragonked2/alphacode/main/scripts/install.ps1'), modelArgs: (m) => (m ? ['--model', m] : []), models: alphacodeModels },
47
+ }
48
+
49
+ // The CLI a provider's address names (cli://claude), or null
50
+ export const cliOf = (baseUrl) => {
51
+ const m = /^cli:\/\/([^/]+)/i.exec(String(baseUrl ?? ''))
52
+ return m && CLIS[m[1]] ? m[1] : null
53
+ }
54
+ export const cliUrl = (id) => `cli://${id}`
55
+
56
+ // --- installed? installing ---
57
+ const fits = (r) => !r.os || (r.os === 'unix' ? !WIN : r.os === process.platform)
58
+ const ready = (r) => [r.cmd[0], ...(r.also ?? [])].every((p) => onPath(p))
59
+ const shown = (r) => (r.cmd[0] === 'bash' || r.cmd[0] === 'powershell' ? r.cmd.at(-1) : r.cmd.join(' '))
60
+ const versions = new Map() // id → its --version, once asked
61
+ const installs = new Map() // id → { running, log, error }
62
+
63
+ const run = (bin, args, { cwd = os.tmpdir(), timeout = 60_000, input } = {}) =>
64
+ new Promise((resolve) => {
65
+ let out = ''
66
+ let err = ''
67
+ const p = spawnCmd(bin, args, { cwd, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], detached: !WIN, env: { ...process.env, NO_COLOR: '1' } })
68
+ const t = setTimeout(() => killTree(p.pid, 'SIGKILL'), timeout)
69
+ p.stdout.on('data', (d) => (out += d))
70
+ p.stderr.on('data', (d) => (err += d))
71
+ if (input !== undefined) p.stdin.end(input)
72
+ p.on('error', (e) => (clearTimeout(t), resolve({ code: -1, out, err: err || e.message })))
73
+ p.on('close', (code) => (clearTimeout(t), resolve({ code, out, err })))
74
+ })
75
+
76
+ // its --version, asked once in the background: { v } once it answered (a slow one doesn't hold the list up)
77
+ function versionOf(id) {
78
+ if (!versions.has(id)) {
79
+ const got = {}
80
+ versions.set(id, got)
81
+ run(CLIS[id].bin, ['--version'], { timeout: 15_000 }).then(({ out, err }) => (got.v = (/\d+\.\d+[\w.+-]*/.exec(out || err)?.[0] ?? '').replace(/\.$/, '')))
82
+ }
83
+ return versions.get(id).v
84
+ }
85
+
86
+ // Every CLI, for the settings page: installed (its version, pending: not known yet), or how to install it
87
+ export function clisInfo() {
88
+ return Object.entries(CLIS).map(([id, k]) => {
89
+ const where = onPath(k.bin)
90
+ const routes = k.install.filter(fits)
91
+ const pick = routes.find(ready)
92
+ const inst = installs.get(id)
93
+ return {
94
+ id, title: k.title, login: k.login, page: k.page, installed: Boolean(where), version: where ? (versionOf(id) ?? '') : '', ...(where && versionOf(id) === undefined && { pending: true }),
95
+ ...(!where && { install: pick ? shown(pick) : '', commands: routes.map(shown), needs: pick ? '' : [...new Set(routes.map((r) => ({ npm: 'Node.js (npm)', bash: 'curl', uv: 'uv or pipx', pipx: 'uv or pipx' })[r.cmd[0]] ?? r.cmd[0]))].join(' or ') }),
96
+ ...(inst && { installing: inst.running, log: inst.log.slice(-3000), error: inst.error }),
97
+ }
98
+ })
99
+ }
100
+
101
+ // Installs one in the background, by the first way that fits this machine; one at a time (npm's global
102
+ // folder doesn't take two at once). done(): finished, either way.
103
+ let queue = Promise.resolve()
104
+ export function installCli(id, done = () => {}) {
105
+ const k = CLIS[id]
106
+ if (!k) throw new Error(`no CLI "${id}"`)
107
+ const r = k.install.filter(fits).find(ready)
108
+ if (!r) throw new Error(`nothing here can install ${k.title}: see ${k.page}`)
109
+ if (installs.get(id)?.running) return
110
+ const st = { running: true, log: '', error: '' }
111
+ installs.set(id, st)
112
+ queue = queue.then(() => new Promise((resolve) => {
113
+ const args = [...r.cmd.slice(1), ...(r.cmd[0] === 'npm' ? ['--loglevel=http'] : [])] // npm says nothing until it's done otherwise: looked stuck
114
+ const p = spawnCmd(r.cmd[0], args, { cwd: os.homedir(), stdio: ['ignore', 'pipe', 'pipe'], detached: !WIN, env: { ...process.env, CI: '1', NONINTERACTIVE: '1' } })
115
+ const t = setTimeout(() => killTree(p.pid, 'SIGKILL'), 15 * 60_000) // an installer waiting for something that never comes
116
+ const add = (d) => (st.log = (st.log + d).slice(-256_000))
117
+ p.stdout.on('data', add)
118
+ p.stderr.on('data', add)
119
+ const end = (code, e) => {
120
+ clearTimeout(t)
121
+ widenPath()
122
+ versions.delete(id)
123
+ st.running = false
124
+ if (code !== 0) st.error = `${shown(r)} failed (${e ?? `exit ${code}`}): ${st.log.trim().slice(-600)}`
125
+ else if (!onPath(k.bin)) st.error = `installed, but "${k.bin}" isn't on HeartCode's PATH yet: restart HeartCode`
126
+ log('cli', `install ${id}: ${st.error || 'done'}`)
127
+ resolve()
128
+ done()
129
+ }
130
+ p.on('error', (e) => end(-1, e.message))
131
+ p.on('close', (code) => end(code))
132
+ }))
133
+ }
134
+
135
+ // Where installers leave programs, on PATH for this run: npm's global bin, ~/.local/bin, ~/.opencode/bin…
136
+ function widenPath() {
137
+ const add = [path.join(os.homedir(), '.local', 'bin'), path.join(os.homedir(), '.opencode', 'bin'), path.join(os.homedir(), '.claude', 'local')]
138
+ const npmBin = onPath('npm')
139
+ if (npmBin) add.push(path.dirname(npmBin))
140
+ if (process.env.npm_config_prefix) add.push(WIN ? process.env.npm_config_prefix : path.join(process.env.npm_config_prefix, 'bin'))
141
+ const have = new Set((process.env.PATH ?? '').split(path.delimiter))
142
+ for (const d of add) if (!have.has(d) && fs.existsSync(d)) process.env.PATH += path.delimiter + d
143
+ }
144
+
145
+ // --- models ---
146
+ const json = (text) => JSON.parse(text.slice(text.indexOf('{'))) // some print a log line first (Junie)
147
+ // [{ id, name, description }], asked of the CLI (a process start, no message sent)
148
+ export async function cliModels(id) {
149
+ const k = CLIS[id]
150
+ if (!onPath(k.bin)) throw new Error(`${k.title} isn't installed ("${k.bin}" isn't on PATH)`)
151
+ if (k.models) return k.models()
152
+ if (k.kind === 'claude') return claudeModels(k)
153
+ if (k.kind === 'acp') return acpModels(id)
154
+ const { code, out, err } = await run(k.bin, { codex: ['debug', 'models'], opencode: ['models'], junie: ['list-models'] }[k.kind])
155
+ if (code !== 0) throw new Error(signedIn(id, err || out || `${k.bin} exited ${code}`))
156
+ if (k.kind === 'opencode') return out.split('\n').map((l) => l.trim()).filter((l) => /^\S+\/\S+$/.test(l)).map((m) => ({ id: m, description: m.split('/')[0] }))
157
+ if (k.kind === 'codex') return json(out).models.filter((m) => m.visibility !== 'hide').map((m) => ({ id: m.slug, name: m.display_name, description: m.description }))
158
+ return json(out).models.map((m) => ({ id: m.id, name: m.displayName }))
159
+ }
160
+
161
+ // Claude Code's own model menu: the initialize control request, answered before anything is sent
162
+ async function claudeModels(k) {
163
+ const p = spawnCmd(k.bin, ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose'], { cwd: os.tmpdir(), stdio: ['pipe', 'pipe', 'pipe'], detached: !WIN })
164
+ try {
165
+ p.stdin.write(JSON.stringify({ type: 'control_request', request_id: 'heart-models', request: { subtype: 'initialize' } }) + '\n')
166
+ return await new Promise((resolve, reject) => {
167
+ const t = setTimeout(() => reject(new Error(`${k.title} didn't list its models in 45s`)), 45_000)
168
+ lines(p.stdout, (l) => {
169
+ const r = l.type === 'control_response' && l.response?.request_id === 'heart-models' && l.response
170
+ if (!r) return
171
+ clearTimeout(t)
172
+ if (r.subtype === 'error') return reject(new Error(r.error))
173
+ resolve((r.response?.models ?? []).filter((m) => m.value).map((m) => ({ id: m.value, name: m.displayName, description: m.description })))
174
+ })
175
+ p.on('close', () => reject(new Error(`${k.title} ended without listing its models`)))
176
+ p.on('error', reject)
177
+ })
178
+ } finally {
179
+ killTree(p.pid, 'SIGKILL')
180
+ }
181
+ }
182
+
183
+ async function kiroModels() {
184
+ const { out } = await run('kiro-cli', ['chat', '--list-models', '--format', 'json'])
185
+ return json(out).models.map((m) => ({ id: m.model_id, name: m.model_name, description: `${m.description ?? ''}${m.rate_multiplier ? ` (${m.rate_multiplier}x credits)` : ''}`.trim() }))
186
+ }
187
+ // the choices for "model" in `copilot help config`, and auto
188
+ async function copilotModels() {
189
+ const { out } = await run('copilot', ['help', 'config'])
190
+ const ms = [{ id: 'auto', name: 'Auto', description: 'Copilot picks the model' }]
191
+ let inside = false
192
+ for (const l of out.split('\n').map((x) => x.trim())) {
193
+ if (l.startsWith('`model`:')) inside = true
194
+ else if (inside && l.startsWith('- "')) ms.push({ id: l.slice(3, -1) })
195
+ else if (inside && l) break
196
+ }
197
+ return ms
198
+ }
199
+ async function alphacodeModels() {
200
+ const { out } = await run('alphacode', ['model', 'list', '--no-update'])
201
+ return out.split('\n').map((l) => l.trim()).filter((l) => l && !l.includes(' ')).map((id) => ({ id }))
202
+ }
203
+
204
+ // One JSON object per line from a stream: each(obj)
205
+ function lines(stream, each) {
206
+ let buf = ''
207
+ stream.on('data', (d) => {
208
+ buf += d
209
+ let i
210
+ while ((i = buf.indexOf('\n')) >= 0) {
211
+ const l = buf.slice(0, i).trim()
212
+ buf = buf.slice(i + 1)
213
+ if (!l.startsWith('{')) continue
214
+ try {
215
+ each(JSON.parse(l))
216
+ } catch {}
217
+ }
218
+ })
219
+ }
220
+
221
+ // "not signed in" said as how to sign in
222
+ function signedIn(id, said) {
223
+ const k = CLIS[id]
224
+ said = String(said).trim().slice(-500)
225
+ return /auth|log ?in|sign ?in|credential|api key|unauthori[sz]ed|not logged/i.test(said) ? `${k.title} isn't signed in: run \`${k.login}\` in a terminal (${said})` : said
226
+ }
227
+
228
+ // --- a message ---
229
+ // HeartCode's step names for what the CLIs call their tools (and ACP's kinds), so their steps read like
230
+ // HeartCode's own
231
+ const STEP_OF = { bash: 'run_command', shell: 'run_command', execute: 'run_command', commandexecution: 'run_command', runshellcommand: 'run_command', read: 'read_file', readfile: 'read_file', view: 'read_file', write: 'write_file', writefile: 'write_file', create: 'write_file', edit: 'edit_file', multiedit: 'edit_file', strreplace: 'edit_file', applypatch: 'edit_file', patch: 'edit_file', delete: 'edit_file', move: 'edit_file', grep: 'search', glob: 'search', search: 'search', find: 'search', ls: 'list_files', list: 'list_files', webfetch: 'web_fetch', fetch: 'web_fetch', websearch: 'web_search', todowrite: 'todo', task: 'agent', agent: 'agent', subagent: 'agent' }
232
+ const KEYS = ['command', 'file_path', 'filePath', 'path', 'pattern', 'url', 'query', 'prompt', 'description']
233
+ function stepOf(name, input, cwd) {
234
+ const n = String(name ?? '').toLowerCase().replace(/[^a-z]/g, '')
235
+ let detail = ''
236
+ for (const k of KEYS) if (typeof input?.[k] === 'string' && input[k]) (detail ||= input[k])
237
+ if (detail && path.isAbsolute(detail) && detail.startsWith(cwd + path.sep)) detail = path.relative(cwd, detail)
238
+ return [STEP_OF[n] ?? (String(name ?? 'tool').replace(/^mcp__/, '') || 'tool'), detail.replace(/\s+/g, ' ').slice(0, 200)]
239
+ }
240
+
241
+ // The words of a message (images left out: see the top)
242
+ const words = (c) => (Array.isArray(c) ? c.map((p) => (typeof p === 'string' ? p : (p?.text ?? ''))).join('') : String(c ?? ''))
243
+ // Messages as one text, for a CLI that didn't see them
244
+ function transcript(msgs) {
245
+ return msgs.map((m) => {
246
+ if (m.role === 'tool') return `[a tool's result]: ${words(m.content).slice(0, 2000)}`
247
+ const calls = (m.tool_calls ?? []).map((t) => `[called ${t.function?.name}(${String(t.function?.arguments ?? '').slice(0, 300)})]`).join('\n')
248
+ return `[${m.role}]: ${[words(m.content), calls].filter(Boolean).join('\n')}`
249
+ }).join('\n\n')
250
+ }
251
+
252
+ // A request to a CLI provider (client.js sends it here): { content, reasoning, toolCalls: [], cli: true }.
253
+ // opts.agent: a message of the conversation (worked on by the CLI, in opts.cwd: steps through
254
+ // opts.onStep(name, detail) / opts.onStepFailed(), asked through opts.confirm(question, kind), allowed
255
+ // what opts.permission says); else one plain question.
256
+ export async function cliChat(client, body, opts = {}) {
257
+ const id = cliOf(client.baseUrl)
258
+ const k = CLIS[id]
259
+ if (!onPath(k.bin)) throw Object.assign(new Error(`${k.title} isn't installed ("${k.bin}" isn't on PATH): install it on /settings → Providers`), { status: 404 })
260
+ const msgs = body.messages.filter((m) => m.role !== 'system')
261
+ const agent = Boolean(opts.agent)
262
+ const runs = (client.cliRuns ??= new Map()) // provider → { session, last: the last message it saw }
263
+ const key = `${client.provider}/${client.model}`
264
+ const was = agent ? runs.get(key) : null
265
+ const at = was ? msgs.indexOf(was.last) : -1
266
+ let session = at >= 0 ? was.session : null // a rewind (Esc Esc) or another conversation: a new session, told all of it
267
+ let delta = session ? msgs.slice(at + 1) : msgs
268
+ if (session && delta[0]?.role === 'assistant') delta = delta.slice(1) // its own answer
269
+ // the message: the latest of yours; what came before it that it didn't see, as background
270
+ const at2 = delta.findLastIndex((m) => m.role === 'user')
271
+ const latest = delta[at2] ?? delta.at(-1)
272
+ const earlier = delta.slice(0, Math.max(0, at2))
273
+ const text = !agent
274
+ ? (body.messages[0]?.role === 'system' ? `${words(body.messages[0].content)}\n\n---\n\n` : '') + (msgs.length === 1 ? words(msgs[0].content) : transcript(msgs))
275
+ : earlier.length ? `Background: ${session ? 'what was said in this conversation since your last answer, while another assistant answered' : 'this conversation so far, from before you joined it'} (HeartCode, the app you run in, kept it):\n\n${transcript(earlier)}\n\n---\n\nMy message now:\n\n${words(latest?.content)}` : words(latest?.content)
276
+ const said = { text: '', last: '', think: '' }
277
+ const on = {
278
+ text: (t) => t && ((said.text += t), (said.last += t), opts.onToken?.(t)),
279
+ think: (t) => t && ((said.think += t), opts.onReasoning?.(t)),
280
+ step: (name, input, detail) => {
281
+ said.last = '' // the answer is what it says after its last step
282
+ if (!agent) return
283
+ const [n, d] = stepOf(name, input, opts.cwd ?? process.cwd())
284
+ opts.onStep?.(n, detail ?? d)
285
+ },
286
+ fail: () => agent && opts.onStepFailed?.(),
287
+ }
288
+ const mode = agent ? (opts.permission ?? 'all') : 'plan'
289
+ const cwd = agent ? (opts.cwd ?? process.cwd()) : os.tmpdir()
290
+ const t0 = Date.now()
291
+ const r = await DRIVERS[k.kind]({ id, k, model: client.model, text, session, mode, cwd, signal: opts.signal, on, confirm: opts.confirm, fresh: !agent })
292
+ log('cli', `${id} · ${client.model}: ${agent ? 'a message' : 'a question'} in ${Date.now() - t0}ms${r.session ? ` (session ${r.session})` : ''}`)
293
+ if (agent && r.session) runs.set(key, { session: r.session, last: latest })
294
+ const content = (said.last.trim() ? said.last : r.answer || said.last || said.text).trim()
295
+ return { content, reasoning: said.think.trim(), toolCalls: [], usage: null, finishReason: 'stop', cli: true }
296
+ }
297
+
298
+ // Stops a CLI and everything under it: some start their commands in groups of their own (opencode),
299
+ // which stopping its group leaves running (Windows: taskkill /T takes the tree)
300
+ function stopAll(pid) {
301
+ if (!pid) return
302
+ if (!WIN) {
303
+ try {
304
+ const kids = new Map()
305
+ for (const l of execFileSync('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8' }).split('\n')) {
306
+ const [c, p] = l.trim().split(/\s+/).map(Number)
307
+ if (c) kids.set(p, [...(kids.get(p) ?? []), c])
308
+ }
309
+ const all = []
310
+ for (let q = [pid]; q.length; ) for (const c of kids.get(q.shift()) ?? []) all.push(c), q.push(c)
311
+ for (const c of all) killTree(c, 'SIGTERM', false)
312
+ } catch {}
313
+ }
314
+ killTree(pid, 'SIGTERM')
315
+ }
316
+
317
+ // A CLI run for one message: started in its own process group (Esc stops all of it), its output read
318
+ // line by line (each(obj)), its environment guarded (guard.js: its commands can't stop HeartCode).
319
+ // { code, err } at the end.
320
+ function start(k, args, { cwd, signal, input, env = {} }, each) {
321
+ return new Promise((resolve, reject) => {
322
+ const p = spawnCmd(k.bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: !WIN, env: { ...guarded('', process.env).env, ...env } })
323
+ let err = ''
324
+ p.stderr.on('data', (d) => (err = (err + d).slice(-4000)))
325
+ lines(p.stdout, each)
326
+ if (input !== undefined) p.stdin.end(input)
327
+ else p.stdin.end()
328
+ const stop = () => stopAll(p.pid)
329
+ signal?.addEventListener('abort', stop, { once: true })
330
+ p.on('error', (e) => reject(Object.assign(new Error(`couldn't start ${k.bin}: ${e.message}`), { status: 404 })))
331
+ p.on('close', (code) => {
332
+ signal?.removeEventListener('abort', stop)
333
+ if (signal?.aborted) return reject(Object.assign(new Error('stopped'), { name: 'AbortError' }))
334
+ resolve({ code, err: err.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').trim() })
335
+ })
336
+ })
337
+ }
338
+
339
+ // A failed run as an error: a sign-in its words name (401), a limit (429), anything else (400: not
340
+ // waited out; your list moves on, if you have one)
341
+ const failure = (id, said) => {
342
+ const why = signedIn(id, said || 'it ended with an error')
343
+ return Object.assign(new Error(`${CLIS[id].title}: ${why}`), { status: /isn't signed in/.test(why) ? 401 : /rate.?limit|429|quota|usage limit|too many requests/i.test(why) ? 429 : 400 })
344
+ }
345
+
346
+ const DRIVERS = {
347
+ // claude -p, its stream-json; the message on stdin
348
+ async claude({ id, k, model, text, session, mode, cwd, signal, on, fresh }) {
349
+ const args = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages']
350
+ if (model && model !== 'default') args.push('--model', model)
351
+ if (fresh) args.push('--no-session-persistence', '--tools', '')
352
+ else args.push(...({ all: ['--dangerously-skip-permissions'], commands: ['--permission-mode', 'acceptEdits'], plan: ['--permission-mode', 'plan'] }[mode] ?? []))
353
+ if (session) args.push('--resume', session)
354
+ let sid = null
355
+ let result = null
356
+ let streamed = false
357
+ const { code, err } = await start(k, args, { cwd, signal, input: text, env: { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } }, (l) => {
358
+ if (l.session_id) sid = l.session_id
359
+ if (l.parent_tool_use_id) return // a subagent's: its work is its parent's step
360
+ if (l.type === 'stream_event') {
361
+ const d = l.event?.delta
362
+ if (d?.type === 'text_delta') (streamed = true), on.text(d.text)
363
+ if (d?.type === 'thinking_delta') on.think(d.thinking)
364
+ } else if (l.type === 'assistant') {
365
+ for (const c of l.message?.content ?? []) {
366
+ if (c.type === 'tool_use') on.step(c.name, c.input)
367
+ if (c.type === 'text' && !streamed) on.text(c.text)
368
+ }
369
+ streamed = false
370
+ } else if (l.type === 'user') {
371
+ for (const c of l.message?.content ?? []) if (c.type === 'tool_result' && c.is_error) on.fail()
372
+ } else if (l.type === 'result') result = l
373
+ })
374
+ if (result?.is_error || (!result && code !== 0)) throw failure(id, result?.result || result?.error || err)
375
+ return { session: sid, answer: result?.result }
376
+ },
377
+ // codex exec --json (exec resume <id> after the first); the message on stdin
378
+ async codex({ id, k, model, text, session, mode, cwd, signal, on, fresh }) {
379
+ const args = ['exec', ...(session ? ['resume'] : []), '--json', '--skip-git-repo-check']
380
+ if (mode === 'all') args.push('--dangerously-bypass-approvals-and-sandbox')
381
+ else args.push('-c', `sandbox_mode="${mode === 'commands' ? 'workspace-write' : 'read-only'}"`)
382
+ if (fresh) args.push('--ephemeral')
383
+ if (model) args.push('-m', model)
384
+ if (session) args.push(session)
385
+ args.push('-')
386
+ let sid = null
387
+ let error = ''
388
+ const { code, err } = await start(k, args, { cwd, signal, input: text }, (l) => {
389
+ const it = l.item ?? {}
390
+ if (l.type === 'thread.started') sid = l.thread_id
391
+ else if (l.type === 'item.started') {
392
+ if (it.type === 'command_execution') on.step('bash', { command: it.command })
393
+ else if (it.type === 'mcp_tool_call') on.step(`${it.server}.${it.tool}`, {})
394
+ else if (it.type === 'web_search') on.step('websearch', { query: it.query })
395
+ } else if (l.type === 'item.completed') {
396
+ if (it.type === 'agent_message') on.text(it.text)
397
+ else if (it.type === 'reasoning') on.think(it.text)
398
+ else if (it.type === 'file_change') for (const c of it.changes ?? []) on.step('edit', { path: c.path })
399
+ else if ((it.type === 'command_execution' && it.exit_code) || (it.type === 'mcp_tool_call' && it.status === 'failed')) on.fail()
400
+ } else if (l.type === 'turn.failed') error = l.error?.message ?? 'the turn failed'
401
+ else if (l.type === 'error') error = l.message
402
+ })
403
+ if (error || code !== 0) throw failure(id, error || err)
404
+ return { session: sid }
405
+ },
406
+ // opencode run --format json; the message as its argument (a leading dash would read as a flag).
407
+ // --standalone: its own server, under this run (the background service would go on with the work
408
+ // after Esc, and its commands wouldn't be guarded)
409
+ async opencode({ id, k, model, text, session, mode, cwd, signal, on }) {
410
+ const args = ['run', '--standalone', '--format', 'json', '--thinking']
411
+ if (model) args.push('-m', model)
412
+ if (session) args.push('-s', session)
413
+ if (mode === 'all') args.push('--auto')
414
+ else args.push('--agent', 'plan') // its read-only agent: it can't ask here
415
+ args.push(text.startsWith('-') ? ` ${text}` : text)
416
+ let sid = null
417
+ let error = ''
418
+ const { code, err } = await start(k, args, { cwd, signal, env: { OPENCODE_DISABLE_AUTOUPDATE: '1', PWD: cwd } }, (l) => {
419
+ sid ??= l.sessionID
420
+ const p = l.part ?? {}
421
+ if (l.type === 'text') on.text(p.text)
422
+ else if (l.type === 'reasoning') on.think(p.text)
423
+ else if (l.type === 'tool_use') {
424
+ on.step(p.tool, p.state?.input)
425
+ if (p.state?.status === 'error') on.fail()
426
+ } else if (l.type === 'error') error = l.error?.data?.message ?? l.error?.message ?? 'opencode reported an error'
427
+ })
428
+ if (error || (code !== 0 && !sid)) throw failure(id, error || err)
429
+ return { session: sid }
430
+ },
431
+ // junie --output-format=json-stream; it can't be held back, so only with "do everything"
432
+ async junie({ id, k, model, text, session, mode, cwd, signal, on, fresh }) {
433
+ if (mode !== 'all' && !fresh) throw Object.assign(new Error(`Junie can't be limited to asking first or reading: it works only with "do everything without asking" (Shift+Tab)`), { status: 400 })
434
+ const args = ['--output-format=json-stream', ...(session ? [`--session-id=${session}`] : []), ...(model ? [`--model=${model}`] : []), text]
435
+ let sid = null
436
+ let error = ''
437
+ let answer = ''
438
+ const { code, err } = await start(k, args, { cwd, signal }, (l) => {
439
+ if (l.type === 'session') sid = l.sessionId
440
+ else if (l.type === 'step' && l.name !== 'TASK RESULT') on.step(l.name, null, String(l.details ?? '').split('\n')[0])
441
+ else if (l.type === 'result' && l.status === 'failed') error ||= [l.errors].flat().filter(Boolean).join('; ')
442
+ else if (l.type === 'result') (answer = l.result), on.text(l.result)
443
+ else if (l.type === 'error') error = l.error || l.message || l.details || 'Junie reported an error'
444
+ })
445
+ if (error || (code !== 0 && !answer)) throw failure(id, error || err)
446
+ return { session: sid, answer }
447
+ },
448
+ acp: acpRun,
449
+ }
450
+
451
+ // --- ACP: JSON-RPC over the CLI's stdin and stdout ---
452
+ function acpConnect(id, { cwd, args = [], env = {}, onNote = () => {}, onAsk = async () => null }) {
453
+ const k = CLIS[id]
454
+ const p = spawnCmd(k.bin, [...k.args, ...args], { cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: !WIN, env: { ...guarded('', process.env).env, ...env } })
455
+ let next = 0
456
+ const waiting = new Map()
457
+ let err = ''
458
+ let dead = null
459
+ p.stderr.on('data', (d) => (err = (err + d).slice(-4000)))
460
+ const send = (m) => !dead && p.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...m }) + '\n')
461
+ lines(p.stdout, async (m) => {
462
+ if (m.method && m.id !== undefined) {
463
+ try {
464
+ send({ id: m.id, result: await onAsk(m.method, m.params ?? {}) })
465
+ } catch (e) {
466
+ send({ id: m.id, error: { code: -32601, message: e.message } })
467
+ }
468
+ } else if (m.method) onNote(m.method, m.params ?? {})
469
+ else if (waiting.has(m.id)) {
470
+ const w = waiting.get(m.id)
471
+ waiting.delete(m.id)
472
+ m.error ? w.reject(Object.assign(new Error(m.error.message + (m.error.data ? ` (${JSON.stringify(m.error.data).slice(0, 300)})` : '')), { rpc: true })) : w.resolve(m.result ?? {})
473
+ }
474
+ })
475
+ const gone = new Promise((resolve) => p.on('close', resolve))
476
+ p.on('error', (e) => (err ||= e.message))
477
+ gone.then(() => {
478
+ dead = new Error(`${k.title} stopped${err ? `: ${err.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').trim().slice(-500)}` : ''}`)
479
+ for (const w of waiting.values()) w.reject(dead)
480
+ waiting.clear()
481
+ })
482
+ const call = (method, params) => (dead ? Promise.reject(dead) : new Promise((resolve, reject) => {
483
+ const id = ++next
484
+ waiting.set(id, { resolve, reject })
485
+ send({ id, method, params })
486
+ }))
487
+ const hello = () => call('initialize', { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: 'heartcode', title: 'HeartCode', version: '1' } })
488
+ return { call, notify: (method, params) => send({ method, params }), hello, close: () => (p.stdin.end(), stopAll(p.pid)), pid: p.pid }
489
+ }
490
+ // a session's choices for one kind of setting ("model", "mode"), from its configOptions
491
+ const optionOf = (s, category) => s.configOptions?.find((o) => o.category === category || o.id === category)
492
+ const valuesOf = (o) => (o?.options ?? []).flatMap((c) => c.options ?? [c])
493
+
494
+ async function acpModels(id) {
495
+ const dir = path.join(os.tmpdir(), 'heartcode-models')
496
+ fs.mkdirSync(dir, { recursive: true })
497
+ const c = acpConnect(id, { cwd: dir })
498
+ try {
499
+ const caps = (await c.hello()).agentCapabilities ?? {}
500
+ const s = await c.call('session/new', { cwd: dir, mcpServers: [] }).catch((e) => Promise.reject(new Error(signedIn(id, e.message))))
501
+ if (caps.sessionCapabilities?.delete) await c.call('session/delete', { sessionId: s.sessionId }).catch(() => {})
502
+ else if (caps.sessionCapabilities?.close) await c.call('session/close', { sessionId: s.sessionId }).catch(() => {})
503
+ const o = optionOf(s, 'model')
504
+ if (o) return valuesOf(o).map((v) => ({ id: v.value, name: v.name, description: v.description }))
505
+ return (s.models?.availableModels ?? []).map((m) => ({ id: m.modelId, name: m.name, description: m.description }))
506
+ } finally {
507
+ c.close()
508
+ }
509
+ }
510
+
511
+ async function acpRun({ id, k, model, text, session, mode, cwd, signal, on, confirm, fresh }) {
512
+ const all = mode === 'all'
513
+ const calls = new Map() // its tool calls, shown once they say what they do
514
+ const show = (u, c) => {
515
+ if (c.shown || !(c.input || u.status === 'completed' || u.status === 'failed')) return
516
+ c.shown = true
517
+ on.step(c.tool || (c.title && !c.title.includes(' ') ? c.title : c.kind) || c.title, c.input ?? {}, c.input ? undefined : (c.path ?? (c.title?.includes(' ') ? c.title : '')))
518
+ }
519
+ let loading = false // a session reopened replays itself: not news
520
+ const conn = acpConnect(id, {
521
+ cwd,
522
+ args: [...(all ? (k.bypassArgs ?? []) : []), ...(k.modelArgs?.(model) ?? [])],
523
+ env: k.modeEnv?.[mode],
524
+ onNote: (method, { update: u }) => {
525
+ if (method !== 'session/update' || !u || loading) return
526
+ if (u.sessionUpdate === 'agent_message_chunk') on.text(u.content?.text)
527
+ else if (u.sessionUpdate === 'agent_thought_chunk') on.think(u.content?.text)
528
+ else if (u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update') {
529
+ const c = calls.get(u.toolCallId) ?? {}
530
+ calls.set(u.toolCallId, c)
531
+ c.title = u.title || c.title
532
+ c.kind = u.kind || c.kind
533
+ c.tool = u._meta?.toolName || u._meta?.claudeCode?.toolName || c.tool
534
+ if (u.rawInput && typeof u.rawInput === 'object' && Object.keys(u.rawInput).length) c.input = u.rawInput
535
+ c.path = u.locations?.[0]?.path || c.path
536
+ show(u, c)
537
+ if (u.status === 'failed') on.fail()
538
+ }
539
+ },
540
+ // its permission questions: yours to answer, as HeartCode's own (the mode you're in decides)
541
+ onAsk: async (method, r) => {
542
+ if (method !== 'session/request_permission') throw new Error(`${method} isn't something HeartCode does`)
543
+ const kind = r.toolCall?.kind
544
+ const reading = ['read', 'search', 'fetch', 'think'].includes(kind)
545
+ const title = String(r.toolCall?.title ?? kind ?? 'a step').split(cwd + path.sep).join('')
546
+ const verb = { edit: 'change', delete: 'delete', move: 'move', execute: 'run', fetch: 'fetch', read: 'read', search: 'search' }[kind]
547
+ const question = !title.includes(' ') && verb ? `${k.title} wants to ${verb} ${title}` : `${k.title}: ${title}?`
548
+ const yes = fresh ? reading : all || (mode === 'plan' && reading) || (mode !== 'plan' && (await confirm?.(question, kind === 'execute' ? 'command' : reading ? 'read' : 'edit')) === true)
549
+ const want = yes ? ['allow_once', 'allow_always'] : ['reject_once', 'reject_always']
550
+ const pick = want.map((w) => r.options?.find((o) => o.kind === w)).find(Boolean)
551
+ return pick ? { outcome: { outcome: 'selected', optionId: pick.optionId } } : { outcome: { outcome: 'cancelled' } }
552
+ },
553
+ })
554
+ const stop = () => sid && conn.notify('session/cancel', { sessionId: sid })
555
+ let sid = null
556
+ signal?.addEventListener('abort', stop, { once: true })
557
+ try {
558
+ const caps = (await conn.hello()).agentCapabilities ?? {}
559
+ let s = null
560
+ if (session && (caps.sessionCapabilities?.resume || caps.loadSession)) {
561
+ loading = true
562
+ s = await conn.call(caps.sessionCapabilities?.resume ? 'session/resume' : 'session/load', { sessionId: session, cwd, mcpServers: [] }).catch(() => null)
563
+ loading = false
564
+ if (s) s.sessionId ??= session
565
+ }
566
+ if (!s && session) text = `(You don't remember this conversation's start: ${k.title} couldn't reopen its session.)\n\n${text}`
567
+ s ??= await conn.call('session/new', { cwd, mcpServers: [] })
568
+ sid = s.sessionId
569
+ for (const [opt, value] of k.modes?.[mode] ?? []) await acpSet(conn, s, opt, value)
570
+ if (model && !k.modelArgs) {
571
+ const o = optionOf(s, 'model')
572
+ await (o ? conn.call('session/set_config_option', { sessionId: sid, configId: o.id, value: model }) : conn.call('session/set_model', { sessionId: sid, modelId: model })).catch((e) => log('cli', `${id}: model ${model}: ${e.message}`))
573
+ }
574
+ const res = await conn.call('session/prompt', { sessionId: sid, prompt: [{ type: 'text', text }] })
575
+ if (res.stopReason === 'cancelled' || signal?.aborted) throw Object.assign(new Error('stopped'), { name: 'AbortError' })
576
+ for (const [, c] of calls) show({ status: 'completed' }, c)
577
+ if (fresh && (caps.sessionCapabilities?.delete || caps.sessionCapabilities?.close)) await conn.call(caps.sessionCapabilities.delete ? 'session/delete' : 'session/close', { sessionId: sid }).catch(() => {})
578
+ return { session: caps.loadSession || caps.sessionCapabilities?.resume ? sid : null }
579
+ } catch (e) {
580
+ if (e.name === 'AbortError' || signal?.aborted) throw Object.assign(new Error('stopped'), { name: 'AbortError' })
581
+ throw failure(id, e.message)
582
+ } finally {
583
+ signal?.removeEventListener('abort', stop)
584
+ conn.close()
585
+ }
586
+ }
587
+ // one of a session's settings, or its mode; only what it offers
588
+ async function acpSet(conn, s, opt, value) {
589
+ try {
590
+ if (opt === 'mode') {
591
+ const o = optionOf(s, 'mode')
592
+ if (o) await conn.call('session/set_config_option', { sessionId: s.sessionId, configId: o.id, value })
593
+ else if (s.modes) await conn.call('session/set_mode', { sessionId: s.sessionId, modeId: value })
594
+ } else {
595
+ const o = s.configOptions?.find((x) => x.id === opt)
596
+ if (o) await conn.call('session/set_config_option', { sessionId: s.sessionId, configId: opt, value: o.type === 'boolean' ? value === 'true' : value })
597
+ }
598
+ } catch (e) {
599
+ log('cli', `set ${opt}=${value}: ${e.message}`)
600
+ }
601
+ }