heartcode 0.1.36 → 0.1.40
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/.claude/scheduled_tasks.lock +1 -0
- package/CHANGELOG.md +93 -0
- package/README.md +20 -7
- package/SKILL.md +5 -3
- package/bin/heart.js +7 -20
- package/bin/heartcode.js +61 -13
- package/package.json +1 -1
- package/prompts/agent.md +114 -115
- package/src/agent.js +63 -252
- package/src/background.js +39 -12
- package/src/client.js +41 -6
- package/src/config.js +1 -1
- package/src/fit.js +65 -0
- package/src/log.js +69 -18
- package/src/parquet.js +209 -0
- package/src/rankings.js +115 -0
- package/src/settings.html +173 -52
- package/src/settings.js +45 -13
- package/src/skills.js +7 -3
- package/src/tools.js +189 -50
- package/src/ui.js +37 -10
- package/src/update.js +59 -0
package/src/agent.js
CHANGED
|
@@ -4,11 +4,12 @@ import { log } from './log.js'
|
|
|
4
4
|
import { prompt, userInstructions } from './prompts.js'
|
|
5
5
|
import { newChat } from './sessions.js'
|
|
6
6
|
import path from 'node:path'
|
|
7
|
-
import { pathToFileURL } from 'node:url'
|
|
8
7
|
import { est, estMessages, Client, writtenBy, tokensOf, COMPACT_SHARE } from './client.js'
|
|
9
8
|
import { runGuided } from './guided.js'
|
|
10
9
|
import { markUsed, removeResearch, findResearch } from './research.js'
|
|
11
|
-
import {
|
|
10
|
+
import { loadRankings, rankIn } from './rankings.js'
|
|
11
|
+
import { pickModels, byPick } from './fit.js'
|
|
12
|
+
import { TOOL_DEFS, PLAN_HIDDEN, folderView, readOnlyCommand, extraTools, runTool, listFiles, namedFiles, readFileTool, clip, allowed, loadMcpTools, saveOutput, isSavedOutput, runningCall, imageUrl, MAX_IMAGE, failed, noteNamedPaths } from './tools.js'
|
|
12
13
|
import { serversNote } from './lsp.js'
|
|
13
14
|
import { newlyEnded, jobLine } from './background.js'
|
|
14
15
|
import { loadHooks, runHooks } from './hooks.js'
|
|
@@ -182,9 +183,16 @@ export class Session {
|
|
|
182
183
|
else this.ui.warn(`${this.client.model} can't read images (per its probe); ignoring ${images.length} image(s)`)
|
|
183
184
|
images = []
|
|
184
185
|
}
|
|
186
|
+
// "best fit": the models that suit this message most, by their strengths (your order breaks ties)
|
|
187
|
+
if (!this.isSub && this.fitMode?.()) {
|
|
188
|
+
const fit = await pickModels(this, text, signal, { images: images.length, size: this.messages ? size(this.messages) : 0 })
|
|
189
|
+
if (fit && this.client.orderBy?.(fit.work)) ui.step('models', `${this.client.model}${fit.why ? ` · picked for: ${fit.why}` : ''}`)
|
|
190
|
+
} else if (!this.isSub) this.client.orderBy?.(null) // your order (best fit was switched off)
|
|
191
|
+
if (!this.isSub) log('rotate', `this message starts on ${this.client.provider ?? ''} · ${this.client.model}${this.client.rotation ? ` (#${this.client.rotation.at + 1} of ${this.client.rotation.list.length}${this.fitMode?.() ? ', best fit' : ', your order'})` : ''}`)
|
|
185
192
|
log('task', `${text} (${this.strat.actions} mode, ${images.length} image(s))`)
|
|
186
193
|
const answer = this.strat.actions === 'tools' ? await runNative(this, text, images, signal) : await runGuided(this, text, images, signal)
|
|
187
|
-
log('
|
|
194
|
+
log('answer', answer) // the conversation's log
|
|
195
|
+
log('task', `answered (${String(answer ?? '').length} characters)`)
|
|
188
196
|
this.history.push({ task: text, answer })
|
|
189
197
|
return answer
|
|
190
198
|
}
|
|
@@ -223,7 +231,7 @@ export class Session {
|
|
|
223
231
|
for (const [i, t] of order.entries()) {
|
|
224
232
|
let answer = ''
|
|
225
233
|
try {
|
|
226
|
-
answer = (await this.#helper(t, task, images, args.description, id, signal))?.trim()
|
|
234
|
+
answer = (await this.#helper(t, task, images, args.description, id, signal, args.ownFiles))?.trim()
|
|
227
235
|
} catch (e) {
|
|
228
236
|
if (e.name === 'AbortError' || signal?.aborted) throw e
|
|
229
237
|
failed.push(`${t.model}: ${clip(e.message, 150)}`)
|
|
@@ -241,15 +249,16 @@ export class Session {
|
|
|
241
249
|
// One helper on one model (t: this one, or another of yours), with its own connection (a helper's
|
|
242
250
|
// failure moves no one else on to another model) that gives up after a few tries (then the next
|
|
243
251
|
// model gets the job).
|
|
244
|
-
async #helper(t, task, images, description, id, signal) {
|
|
252
|
+
async #helper(t, task, images, description, id, signal, ownFiles) {
|
|
245
253
|
let { client, profile, strat } = this
|
|
246
254
|
if (this.engineFor) {
|
|
247
255
|
;({ client, profile, strat } = await this.engineFor(t))
|
|
248
256
|
const was = client.retryIf
|
|
249
|
-
client.retryIf = (e, attempt) => attempt < 3 && (!was || was(e, attempt))
|
|
257
|
+
client.retryIf = (e, attempt) => attempt < 3 && !e.notStarted && (!was || was(e, attempt)) // not answering in time: the next model, not another wait
|
|
250
258
|
}
|
|
251
259
|
const label = clip(`${client.model}: ${String(description ?? '').trim() || task.split('\n')[0]}`, 60)
|
|
252
260
|
const helper = new Session({ client, profile, strat, root: this.root, ui: helperUI(this.ui, label), chat: newChat(this.root) })
|
|
261
|
+
if (ownFiles?.length) helper.ownFiles = ownFiles.map((f) => path.resolve(this.root, f)) // a part of the plan: changes only its own files
|
|
253
262
|
Object.assign(helper, { isSub: true, research: this.research, ran: this.ran, noResearch: this.noResearch, mcp: this.mcp, skills: this.skills, hooks: this.hooks, allowTools: this.allowTools, denyTools: this.denyTools, maxTurns: this.maxTurns, autoCompact: this.autoCompact, appendSystem: this.appendSystem, fileCache: this.fileCache, noFormat: this.noFormat, noLsp: this.noLsp })
|
|
254
263
|
helper.track = (rel, before) => this.track(rel, before)
|
|
255
264
|
helper.mcpGate = async () => (await this.#gate(helper), () => {})
|
|
@@ -301,7 +310,7 @@ export class Session {
|
|
|
301
310
|
this.ui.spinner(`${seer.model} is looking at image ${i + 1}`)
|
|
302
311
|
try {
|
|
303
312
|
const { client } = await this.engineFor(seer)
|
|
304
|
-
client.retryIf = (e, attempt) => attempt < 3
|
|
313
|
+
client.retryIf = (e, attempt) => attempt < 3 && !e.notStarted
|
|
305
314
|
said = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: prompt('guided/describe-image', { task }) }, { type: 'image_url', image_url: { url } }] }] }, { signal })).content.trim()
|
|
306
315
|
} catch (e) {
|
|
307
316
|
if (e.name === 'AbortError' || signal?.aborted) throw e
|
|
@@ -516,9 +525,9 @@ const SYSTEM = (s) => {
|
|
|
516
525
|
return [
|
|
517
526
|
prompt('agent/system', { root: s.root, env: envLine(), today: new Date().toISOString().slice(0, 10), rootList: rootList(s.root), servers: serversNote(s.root), files: '', more: '', caller: Boolean(s.appendSystem) }),
|
|
518
527
|
instructions && prompt('agent/instructions', { instructions }),
|
|
528
|
+
...[...(s.skills?.values() ?? [])].filter((k) => k.use === 'always').map((k) => k.body), // skills that say how to work (use: always)
|
|
519
529
|
s.memory && prompt('agent/memory', { tags: s.memory.tagSummary() || '(none yet)' }),
|
|
520
530
|
s.strat.vision && prompt('agent/you-see'), // models that can see often say they can't
|
|
521
|
-
s.mcpInstructions && prompt('agent/mcp-instructions', { instructions: s.mcpInstructions }), // what the MCP servers say about their tools
|
|
522
531
|
s.director && !s.appendSystem && s.director.app.cfg.director !== false && prompt('agent/director'),
|
|
523
532
|
!s.isSub && teamPrompt(s),
|
|
524
533
|
s.isSub && prompt('agent/subagent'),
|
|
@@ -529,14 +538,21 @@ const SYSTEM = (s) => {
|
|
|
529
538
|
.join('\n\n')
|
|
530
539
|
}
|
|
531
540
|
|
|
532
|
-
// Your other models and what each can do, for the agent tool's model (only when there are any)
|
|
541
|
+
// Your other models and what each can do, for the agent tool's model (only when there are any): a
|
|
542
|
+
// short line each — in best fit, with its places in the public rankings (rankings.js).
|
|
543
|
+
const RANKED_AS = { code: 'text:coding', web: 'webdev:webdev', vision: 'vision:overall' }
|
|
533
544
|
const teamPrompt = (s) => {
|
|
534
545
|
const team = s.team?.() ?? []
|
|
535
546
|
if (!team.length) return ''
|
|
536
|
-
const
|
|
537
|
-
const
|
|
538
|
-
const
|
|
539
|
-
|
|
547
|
+
const data = s.fitMode?.() ? loadRankings() : null
|
|
548
|
+
const ranks = (t) => (data ? Object.entries(RANKED_AS).map(([k, list]) => ((r) => r && `${k} #${r.rank}`)(rankIn(t.model, list, data))).filter(Boolean).join(' ') : '')
|
|
549
|
+
const line = (t) => {
|
|
550
|
+
const failed = s.failures?.[`${t.provider} ${t.model}`]
|
|
551
|
+
const facts = [t.tools === false && 'no tool calls', t.images && 'images', t.thinking && 'thinking', ranks(t) && `ranked ${ranks(t)}`, failed && `failed ${failed}× this session`].filter(Boolean)
|
|
552
|
+
return `- ${t.provider} ${t.model}${facts.length ? `: ${facts.join(', ')}` : ''}`
|
|
553
|
+
}
|
|
554
|
+
const you = [s.strat.vision ? 'images' : 'no images', s.strat.thinking && 'thinking', ranks(s.client) && `ranked ${ranks(s.client)}`].filter(Boolean).join(', ')
|
|
555
|
+
return prompt('agent/team', { models: team.map(line).join('\n'), you, ranked: Boolean(data) })
|
|
540
556
|
}
|
|
541
557
|
|
|
542
558
|
const sizeOf = (m) =>
|
|
@@ -774,22 +790,14 @@ async function runNative(s, task, images, signal) {
|
|
|
774
790
|
// pages already read for this project that match: titles only (the model opens one when needed)
|
|
775
791
|
const pages = s.isSub || !s.memory ? [] : findResearch(s.root, task, 6).filter((r) => r.kind !== 'search' && !sent.has(`research:${r.name}:${r.fetched}`))
|
|
776
792
|
s.chat.sentNotes = [...sent, ...notes.map(key), ...pages.map((r) => `research:${r.name}:${r.fetched}`)]
|
|
777
|
-
const guideSent = () => (s.chat.sentNotes ?? []).includes('guide:ui')
|
|
778
|
-
// the UI guide: once per conversation, with a message about a UI (else with the first UI file written)
|
|
779
|
-
const uiGuide = !sent.has('guide:ui') && UI_TASK.test(task)
|
|
780
|
-
if (uiGuide) s.chat.sentNotes = [...(s.chat.sentNotes ?? []), 'guide:ui']
|
|
781
793
|
const known = [
|
|
782
|
-
uiGuide && prompt('agent/ui-guide'),
|
|
783
794
|
notes.length && prompt('agent/memory-relevant', { notes: notes.map((n) => `[[${n.name}]] — ${n.description}`).join('\n') }),
|
|
784
795
|
pages.length && prompt('agent/research-known', { pages: pages.map((r) => `- ${r.title} — ${r.url} (read ${r.fetched}) → ${r.file}`).join('\n') }),
|
|
785
796
|
].filter(Boolean)
|
|
786
797
|
const text = known.length ? `${task}\n\n${known.join('\n\n')}` : task
|
|
787
798
|
if (!s.isSub) Object.assign(s, { research: [], ran: [], lastQuery: '', dirsBefore: foldersOf(s.root), noResearch: !s.memory }) // this message's pages and commands (helpers add theirs), and the folders there were, for the wrap-up
|
|
788
799
|
const planning = ui.permission === 'plan'
|
|
789
|
-
|
|
790
|
-
// prompt (not a helper's job, nor a program's own task with its own instructions)
|
|
791
|
-
const noted = !s.isSub && !s.appendSystem ? `${text}\n\n${prompt('agent/research-first', { today: new Date().toISOString().slice(0, 10) })}` : text
|
|
792
|
-
const said = planning && !s.isSub ? `${noted}\n\n${prompt('agent/plan-mode')}` : noted
|
|
800
|
+
const said = planning && !s.isSub ? `${text}\n\n${prompt('agent/plan-mode')}` : text
|
|
793
801
|
const content = images.length ? [{ type: 'text', text: said }, ...images.map((url) => ({ type: 'image_url', image_url: { url } }))] : said
|
|
794
802
|
s.messages.push({ role: 'user', content })
|
|
795
803
|
attachNamed(s, task) // files the message names: as if already read (saves a round trip each)
|
|
@@ -802,18 +810,19 @@ async function runNative(s, task, images, signal) {
|
|
|
802
810
|
// A todo list left done from an earlier message is cleared; an unfinished one stays.
|
|
803
811
|
if (!s.isSub && s.chat.todos?.every((t) => t.status === 'completed')) s.chat.todos = []
|
|
804
812
|
s.todoTouched = false
|
|
805
|
-
s.task = task // the user's message, for the
|
|
806
|
-
s.
|
|
807
|
-
|
|
808
|
-
s.
|
|
813
|
+
s.task = task // the user's message, for the review
|
|
814
|
+
for (const turn of s.chat.turns ?? []) noteNamedPaths(turn.task) // folders outside the project any message here names (a resumed chat's too): readable, and cd there is no wrong turn
|
|
815
|
+
noteNamedPaths(task)
|
|
816
|
+
if (!s.isSub) s.choicesFresh = false // a question about how to do it, this message: replaces the earlier answers (s.chat.choices)
|
|
809
817
|
s.runFails = new Map() // a command that failed (by its tool) → its error; when the same tool runs clean after an edit, that's a verified fix to learn from (any language, not just web)
|
|
810
818
|
s.edits = 0 // successful file edits so far this message (to tell a real fix from a lucky rerun)
|
|
811
819
|
s.acted = false // used a tool this message (so a reply that only promises more is a premature stop)
|
|
812
820
|
let nudged = 0 // reminders sent this message about open todo items, a premature stop, or a Stop hook
|
|
813
821
|
let sinceNudge = true // a tool call made since the last reminder: one that changed nothing isn't sent again (no count: it goes on while the model gets on)
|
|
814
822
|
s.planAsked = false // asked for a plan before its first change, this message
|
|
823
|
+
s.splitAsked = false // asked whether a plan's parts could run side by side, this message
|
|
815
824
|
// what changed and when it was last checked, this message: a change not run/tested since isn't done
|
|
816
|
-
Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1 })
|
|
825
|
+
Object.assign(s, { changed: new Set(), seq: 0, lastChangeAt: -1, lastCheckAt: -1, reviewedAt: -1, checksSince: 0, spots: new Map() })
|
|
817
826
|
|
|
818
827
|
let empty = 0 // replies in a row with neither text nor tool calls
|
|
819
828
|
let looping = 0 // replies cut for going into a loop, this message
|
|
@@ -830,6 +839,7 @@ async function runNative(s, task, images, signal) {
|
|
|
830
839
|
let refitted = false // this step's conversation was just compacted for a smaller model the list moved on to
|
|
831
840
|
// No step limit (helpers too): a long fix takes many steps, and Esc stops it. A caller can set one (--max-turns).
|
|
832
841
|
for (let step = 0; ; step++) {
|
|
842
|
+
if (step && !s.isSub) s.onTurn?.() // saved after every step: a quit, crash or kill mid-task loses nothing done so far
|
|
833
843
|
const tools = toolList()
|
|
834
844
|
if (s.maxTurns && step >= s.maxTurns) {
|
|
835
845
|
ui.warn(`stopped after ${s.maxTurns} steps (--max-turns); say "continue" to go on`)
|
|
@@ -943,12 +953,6 @@ async function runNative(s, task, images, signal) {
|
|
|
943
953
|
}
|
|
944
954
|
empty = 0
|
|
945
955
|
if (!res.toolCalls.length) {
|
|
946
|
-
// a page it built or restyled: HeartCode opens it and shows it the result, to check and fix
|
|
947
|
-
const look = !s.isSub && (await lookAtUi(s, signal))
|
|
948
|
-
if (look) {
|
|
949
|
-
s.messages.push({ role: 'user', content: look })
|
|
950
|
-
continue
|
|
951
|
-
}
|
|
952
956
|
const more = sinceNudge && !s.isSub && ((await notDone(s, signal, nudged > 0, res.content)) ?? (await review(s, task, res.content, signal)))
|
|
953
957
|
if (!more) {
|
|
954
958
|
s.wrapUpLater?.(task, res.content) // after the answer, beside what comes next
|
|
@@ -1006,10 +1010,11 @@ async function runNative(s, task, images, signal) {
|
|
|
1006
1010
|
: (args.path ?? args.url ?? args.query ?? args.filter ?? args.name ?? '')
|
|
1007
1011
|
if (name !== 'run_command' && !together.has(call.id)) ui.step(name, clip(detail, 80))
|
|
1008
1012
|
const pre = early.get(call.id)
|
|
1009
|
-
// the first
|
|
1010
|
-
// not made — the plan first, then the
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
+
// the first changes to the files with no plan yet (this message, or still open from an earlier one):
|
|
1014
|
+
// not made — the plan first, then the changes again. Every change in that reply (one made beside a
|
|
1015
|
+
// refused one is easily taken for refused too), once a message; not a helper's (its job is its plan)
|
|
1016
|
+
const planFirst = !s.isSub && (!s.planAsked || s.planHeldIn === res) && EDITS.has(name) && args && allowed(s, name) && ui.permission !== 'plan' && !s.todoTouched && !(s.chat.todos ?? []).some((t) => t.status !== 'completed')
|
|
1017
|
+
if (planFirst) Object.assign(s, { planAsked: true, planHeldIn: res })
|
|
1013
1018
|
const refused = planFirst ? prompt('agent/plan-first') : pre ? (pre.refused ?? null) : !together.has(call.id) && args && allowed(s, name) ? guard.before(name, args) : null
|
|
1014
1019
|
let out = refused ?? (pre ? await pre.running : together.has(call.id) ? await together.get(call.id) : !allowed(s, name) ? `error: the tool ${name} is not allowed here` : args ? await runTool(name, args, s, signal, call.id) : 'error: the tool arguments were not valid JSON')
|
|
1015
1020
|
if (!refused && args) out += guard.after(name, args, out)
|
|
@@ -1018,8 +1023,22 @@ async function runNative(s, task, images, signal) {
|
|
|
1018
1023
|
s.seq++
|
|
1019
1024
|
if (EDITS.has(name) && !failed(out)) {
|
|
1020
1025
|
s.lastChangeAt = s.seq
|
|
1026
|
+
s.checksSince = 0
|
|
1027
|
+
// the same spot changed again and again (and what it checks still comes out the same): told
|
|
1028
|
+
// at the third time that the cause is likely elsewhere
|
|
1029
|
+
const at = Number(/\nNow:\n\s*(\d+)\|/.exec(out)?.[1])
|
|
1030
|
+
if (args.path && at) {
|
|
1031
|
+
const spot = `${args.path}:${Math.round(at / 10)}`
|
|
1032
|
+
const n = (s.spots ??= new Map()).set(spot, (s.spots.get(spot) ?? 0) + 1).get(spot)
|
|
1033
|
+
if (n === 3) out += `\n\n${prompt('agent/same-spot', { file: String(args.path), line: at })}`
|
|
1034
|
+
}
|
|
1021
1035
|
if (args.path) s.changed.add(String(args.path))
|
|
1022
|
-
} else if (CHECKS.has(name))
|
|
1036
|
+
} else if (CHECKS.has(name)) {
|
|
1037
|
+
s.lastCheckAt = s.seq // ran something: a check of what changed (the model judges its result)
|
|
1038
|
+
// checking on and on with nothing changed (sleeps, screenshots, play-throughs): told once per
|
|
1039
|
+
// change that it's proven or not by now — stop, or fix what's broken
|
|
1040
|
+
if (++s.checksSince === 5 && (s.changed.size || s.isSub)) out += `\n\n${prompt('agent/enough-checks', { n: s.checksSince, choices: (s.chat?.choices ?? []).join('; ') })}`
|
|
1041
|
+
}
|
|
1023
1042
|
}
|
|
1024
1043
|
if (name === 'run_command' && args && !refused) s.ran?.push({ command: String(args.command ?? ''), result: clip(String(out).split('\n').filter((l) => l.trim()).slice(0, 2).join(' · '), 160) })
|
|
1025
1044
|
if (!s.isSub && s.memory && !refused && args) await noteRun(s, name, args, out, signal).catch((e) => log('learn', `run note: ${e.message}`)) // learn from any run that failed then passed
|
|
@@ -1033,11 +1052,6 @@ async function runNative(s, task, images, signal) {
|
|
|
1033
1052
|
else if (name === 'agent' && !failed(out)) ui.result(`${s.ui.permission === 'plan' ? 'planned' : 'done'}: ${clip(out.split('\n').find((l) => l.trim()) ?? '', 100)}`)
|
|
1034
1053
|
else if (failed(out)) ui.result(clip(out, 120))
|
|
1035
1054
|
client.refresh?.() // a setting changed while the tool ran (the window): its result is cut by the new one
|
|
1036
|
-
// the first UI file written in a conversation that hasn't had the UI guide: it comes with the result
|
|
1037
|
-
if (EDITS.has(name) && args && UI_FILE.test(String(args.path ?? '')) && !failed(out) && !guideSent()) {
|
|
1038
|
-
s.chat.sentNotes = [...(s.chat.sentNotes ?? []), 'guide:ui']
|
|
1039
|
-
out += `\n\n${prompt('agent/ui-guide')}`
|
|
1040
|
-
}
|
|
1041
1055
|
// every sizable result is saved as it comes (a web page already is, in research): later it can
|
|
1042
1056
|
// become a pointer to its file in the conversation without anything being lost
|
|
1043
1057
|
if (out.length > SAVE_AT && name !== 'read_file' && !s.chat.outputs?.[call.id]) {
|
|
@@ -1080,9 +1094,6 @@ const EDITS = new Set(['edit_file', 'write_file', 'append_file', 'apply_patch'])
|
|
|
1080
1094
|
const CHECKS = new Set(['run_command', 'mcp', 'agent', 'lsp'])
|
|
1081
1095
|
// Files only read by people (a change there needs no run to check it).
|
|
1082
1096
|
const DOC_FILE = /\.(md|mdx|txt|rst|adoc)$/i
|
|
1083
|
-
// A message about something people look at (gets the UI guide), and a file that is one.
|
|
1084
|
-
const UI_TASK = /\b(ui|ux|web ?page|page|website|web ?site|landing|dashboard|screen|component|front-?end|layout|redesign|design|css|html|styles?|styling|theme|tailwind|navbar|modal|button)s?\b/i
|
|
1085
|
-
const UI_FILE = /\.(html?|css|scss|sass|less|jsx|tsx|vue|svelte|astro)$/i
|
|
1086
1097
|
// Tools that only look (nothing changes): several in one reply run at the same time.
|
|
1087
1098
|
const LOOKUPS = new Set(['web_search', 'web_fetch', 'read_file', 'search', 'list_files', 'find_command', 'lsp'])
|
|
1088
1099
|
export function newGuard() {
|
|
@@ -1129,67 +1140,6 @@ export function newGuard() {
|
|
|
1129
1140
|
return g
|
|
1130
1141
|
}
|
|
1131
1142
|
|
|
1132
|
-
// The pages this message wrote or restyled (an .html written, or one using a .css written),
|
|
1133
|
-
// opened in the built-in browser (chrome-devtools): a screenshot at desktop width (the whole page)
|
|
1134
|
-
// and at phone width, given to the model to check against its brief and fix. Again whenever pages
|
|
1135
|
-
// changed since the last look; nothing when there's no browser. A model that can't see gets them
|
|
1136
|
-
// described by one of yours that can.
|
|
1137
|
-
// Problems found in a built page without a browser: JavaScript that doesn't parse, and the Tailwind
|
|
1138
|
-
// CDN used with @apply/@layer (it throws "Cannot apply unknown utility class" at runtime and the
|
|
1139
|
-
// styling breaks). These are caught even when the browser can't be opened.
|
|
1140
|
-
function staticChecks(root, rel) {
|
|
1141
|
-
const out = []
|
|
1142
|
-
let html
|
|
1143
|
-
try {
|
|
1144
|
-
html = fs.readFileSync(path.join(root, rel), 'utf8')
|
|
1145
|
-
} catch {
|
|
1146
|
-
return out
|
|
1147
|
-
}
|
|
1148
|
-
for (const m of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
|
|
1149
|
-
const attrs = m[1]
|
|
1150
|
-
if (/\bsrc\s*=/.test(attrs) || /\btype\s*=\s*["']?module/.test(attrs) || !m[2].trim()) continue // external or ESM: can't check this way
|
|
1151
|
-
try {
|
|
1152
|
-
new Function(m[2]) // compiles without running: throws on a syntax error (unclosed brace, typo)
|
|
1153
|
-
} catch (e) {
|
|
1154
|
-
out.push(`${rel}: the <script> doesn't parse — ${e.message}. The page's JavaScript won't run at all. Find and fix it (often an unclosed brace or bracket).`)
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1157
|
-
const tailwindCdn = /cdn\.tailwindcss\.com|@tailwindcss\/browser|type\s*=\s*["']text\/tailwindcss/.test(html)
|
|
1158
|
-
if (tailwindCdn) {
|
|
1159
|
-
const css = [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]).join('\n')
|
|
1160
|
-
const defined = new Set([...css.matchAll(/(?:^|\})\s*\.([a-zA-Z][\w-]*)\s*\{/g)].map((m) => m[1])) // classes defined with a rule
|
|
1161
|
-
const applied = new Set([...css.matchAll(/@apply\b([^;}{]*)/g)].flatMap((m) => m[1].split(/\s+/).map((t) => t.replace(/[^\w-].*$/, '')).filter(Boolean)))
|
|
1162
|
-
const bad = [...applied].filter((c) => defined.has(c))
|
|
1163
|
-
if (bad.length) out.push(`${rel}: the Tailwind browser build (CDN) throws "Cannot apply unknown utility class" here — you @apply a class you defined yourself (${bad.join(', ')}), which only a real build step allows. Put those utility classes directly in the HTML (class="…"), not behind @apply; or drop the @apply and write the rules in plain CSS.`)
|
|
1164
|
-
}
|
|
1165
|
-
return out
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
// The tech a mistake is about, for tagging a lesson so it's recalled on later tasks of the same
|
|
1169
|
-
// kind. Reads both the error and the command/file it came from; works for any language, not just web.
|
|
1170
|
-
function techOf(context) {
|
|
1171
|
-
const t = String(context).toLowerCase()
|
|
1172
|
-
const tags = []
|
|
1173
|
-
const add = (re, tag) => re.test(t) && tags.push(tag)
|
|
1174
|
-
add(/tailwind/, 'tailwind')
|
|
1175
|
-
add(/\btsc?\b|\.tsx?\b|typescript|ts-node/, 'typescript')
|
|
1176
|
-
add(/\bnode\b|\.c?js\b|\.mjs\b|javascript|npm|pnpm|yarn|\bbun\b|vite|webpack|eslint|referenceerror|is not defined/, 'javascript')
|
|
1177
|
-
add(/\breact\b|usestate|useeffect|\bjsx\b|next\.?js/, 'react')
|
|
1178
|
-
add(/\bpython3?\b|\bpip3?\b|\bpytest\b|\buv\b|\.py\b|traceback|modulenotfound|indentationerror/, 'python')
|
|
1179
|
-
add(/\bgo\b|\.go\b|golang|go\.mod/, 'go')
|
|
1180
|
-
add(/\bcargo\b|\brustc\b|\.rs\b|rust/, 'rust')
|
|
1181
|
-
add(/\bjava\b|\bmvn\b|gradle|\.java\b/, 'java')
|
|
1182
|
-
add(/\bruby\b|\bgem\b|bundle|\.rb\b|rails/, 'ruby')
|
|
1183
|
-
add(/\bphp\b|composer|\.php\b|laravel/, 'php')
|
|
1184
|
-
add(/\bmake\b|cmake|\bgcc\b|clang|\.c\b|\.cpp\b/, 'c')
|
|
1185
|
-
add(/\bdocker\b|dockerfile|kubectl|\bk8s\b/, 'docker')
|
|
1186
|
-
add(/\bcurl\b|\bwget\b|http|endpoint|\bapi\b|\bfetch\b/, 'api')
|
|
1187
|
-
add(/\.html\b|<script|<style|\bdom\b/, 'html')
|
|
1188
|
-
add(/\.css\b|@apply|@layer|utility class|stylesheet/, 'css')
|
|
1189
|
-
add(/\bsql\b|postgres|sqlite|mysql|database/, 'sql')
|
|
1190
|
-
return tags.length ? [...new Set(tags)].slice(0, 4) : ['general']
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
1143
|
// A command's tool: its first word (npm, python3, go, cargo, make, curl…), paths and flags dropped,
|
|
1194
1144
|
// so the same kind of command failing then passing is recognised across runs.
|
|
1195
1145
|
const runTool_ = (cmd) => (String(cmd).trim().match(/^[\w./-]+/)?.[0] ?? '').split('/').pop()
|
|
@@ -1220,12 +1170,12 @@ async function noteRun(s, name, args, out, signal) {
|
|
|
1220
1170
|
}
|
|
1221
1171
|
}
|
|
1222
1172
|
|
|
1223
|
-
// Turn each fixed mistake into one reusable rule and save it (global memory, tagged by
|
|
1173
|
+
// Turn each fixed mistake into one reusable rule and save it (global memory, tagged by the tool it came from). The
|
|
1224
1174
|
// model writes the rule from the error; a near-duplicate lesson is skipped. Recall is automatic
|
|
1225
1175
|
// (memory.relevant attaches matching notes to a later message).
|
|
1226
1176
|
async function learnFromFixes(s, fixed, signal) {
|
|
1227
1177
|
for (const { error, context } of fixed.slice(0, 5)) {
|
|
1228
|
-
const tags =
|
|
1178
|
+
const tags = [runTool_(context ?? error) || 'general'] // the tool it came from (npm, python3, cargo…)
|
|
1229
1179
|
const near = s.memory.search(`tag:lesson ${tags.join(' ')}`).find((n) => n.body.toLowerCase().includes(error.replace(/^[^:]*:\s*/, '').toLowerCase().slice(0, 30)))
|
|
1230
1180
|
if (near) continue // already learned
|
|
1231
1181
|
let rule = ''
|
|
@@ -1252,146 +1202,6 @@ async function learnFromFixes(s, fixed, signal) {
|
|
|
1252
1202
|
}
|
|
1253
1203
|
}
|
|
1254
1204
|
|
|
1255
|
-
// Injected into the page (evaluate_script): fills inputs, clicks buttons, toggles checkboxes, and
|
|
1256
|
-
// returns the errors any of them threw. Navigation is blocked so one click can't end the test.
|
|
1257
|
-
const SMOKE_TEST = `async () => {
|
|
1258
|
-
const errs = []
|
|
1259
|
-
const push = (m) => { const s = String(m && m.message ? m.message : m).slice(0, 180); if (s && !errs.includes(s)) errs.push(s) }
|
|
1260
|
-
addEventListener('error', (e) => push(e.message || (e.error && e.error.message) || e), true)
|
|
1261
|
-
addEventListener('unhandledrejection', (e) => push('unhandled: ' + ((e.reason && e.reason.message) || e.reason)), true)
|
|
1262
|
-
const ce = console.error; console.error = (...a) => { push(a.map(String).join(' ')); ce.apply(console, a) }
|
|
1263
|
-
document.addEventListener('submit', (e) => e.preventDefault(), true)
|
|
1264
|
-
document.addEventListener('click', (e) => { const a = e.target.closest && e.target.closest('a'); const h = a && a.getAttribute('href'); if (h && h[0] !== '#') e.preventDefault() }, true)
|
|
1265
|
-
for (const inp of document.querySelectorAll('input:not([type=button]):not([type=submit]):not([type=checkbox]):not([type=radio]):not([type=file]), textarea')) {
|
|
1266
|
-
try { inp.focus(); inp.value = 'Test 123'; inp.dispatchEvent(new Event('input', { bubbles: true })); inp.dispatchEvent(new Event('change', { bubbles: true })); for (const t of ['keydown','keypress','keyup']) inp.dispatchEvent(new KeyboardEvent(t, { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true })) } catch (e) { push('typing: ' + e.message) }
|
|
1267
|
-
}
|
|
1268
|
-
const btns = [...document.querySelectorAll('button, [role=button], input[type=button], input[type=submit], a[href^="#"], a:not([href]), [onclick]')]
|
|
1269
|
-
let controls = btns.length
|
|
1270
|
-
for (const el of btns) { try { el.click() } catch (e) { push('click "' + ((el.textContent || el.getAttribute('aria-label') || el.value || '').trim().slice(0, 30)) + '": ' + e.message) } ; await new Promise((r) => setTimeout(r, 10)) }
|
|
1271
|
-
for (const cb of document.querySelectorAll('input[type=checkbox], input[type=radio]')) { controls++; try { cb.click() } catch (e) { push('toggle: ' + e.message) } }
|
|
1272
|
-
await new Promise((r) => setTimeout(r, 200))
|
|
1273
|
-
return JSON.stringify({ errors: errs, controls })
|
|
1274
|
-
}`
|
|
1275
|
-
|
|
1276
|
-
async function lookAtUi(s, signal) {
|
|
1277
|
-
if (!s.uiTouched?.size || s.ui.permission === 'plan') return null // again whenever pages changed since the last look
|
|
1278
|
-
const touched = [...s.uiTouched]
|
|
1279
|
-
s.uiTouched.clear()
|
|
1280
|
-
const styles = touched.filter((f) => /\.css$/i.test(f)).map((f) => path.basename(f))
|
|
1281
|
-
const pages = touched.filter((f) => /\.html?$/i.test(f))
|
|
1282
|
-
if (styles.length) {
|
|
1283
|
-
for (const f of listFiles(s.root).filter((f) => /\.html?$/i.test(f))) {
|
|
1284
|
-
try {
|
|
1285
|
-
if (styles.some((c) => fs.readFileSync(path.join(s.root, f), 'utf8').includes(c))) pages.push(f)
|
|
1286
|
-
} catch {}
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
const shown = [...new Set(pages)].filter((f) => fs.existsSync(path.join(s.root, f)))
|
|
1290
|
-
if (!shown.length) return null
|
|
1291
|
-
s.uiLooks++
|
|
1292
|
-
const browser = s.mcp?.get?.('chrome-devtools')
|
|
1293
|
-
const errors = shown.flatMap((rel) => staticChecks(s.root, rel)) // works with no browser
|
|
1294
|
-
const shots = []
|
|
1295
|
-
let opened = 0 // pages actually opened in the browser (0: couldn't verify it runs)
|
|
1296
|
-
const text = (r) => (r.content ?? []).map((p) => p.text ?? '').join('\n')
|
|
1297
|
-
const done = browser ? await s.mcpGate?.() : null
|
|
1298
|
-
try {
|
|
1299
|
-
if (!browser) throw new Error('no browser')
|
|
1300
|
-
for (const rel of shown) {
|
|
1301
|
-
s.ui.spinner(`opening ${rel} in the browser`)
|
|
1302
|
-
const openedText = text(await browser.call('new_page', { url: pathToFileURL(path.join(s.root, rel)).href }, signal))
|
|
1303
|
-
opened++
|
|
1304
|
-
const id = Number(/(\d+):[^\n]*\[selected\]/.exec(openedText)?.[1]) || undefined // newer versions number the pages
|
|
1305
|
-
const page = id ? { pageId: id } : {}
|
|
1306
|
-
await new Promise((r) => setTimeout(r, 600)) // the scripts run before we read the console
|
|
1307
|
-
const con = await browser.call('list_console_messages', page, signal).catch(() => null)
|
|
1308
|
-
for (const line of (con ? text(con) : '').split('\n')) {
|
|
1309
|
-
if (!/\[error\]/i.test(line) || /favicon\.ico/i.test(line)) continue // a missing favicon isn't a real problem
|
|
1310
|
-
errors.push(`${rel}: ${line.replace(/^\s*msgid=\d+\s*\[error\]\s*/i, '').replace(/\s*\(\d+ args?\)\s*$/, '').trim()}`)
|
|
1311
|
-
}
|
|
1312
|
-
// Drive it like a user: fill the inputs, click every button, toggle every checkbox. An error a
|
|
1313
|
-
// control throws means it doesn't work (a dead button, a popup that fails) — caught here, not on a plain load.
|
|
1314
|
-
s.ui.spinner(`testing ${rel} (clicking through it)`)
|
|
1315
|
-
const ran = await browser.call('evaluate_script', { ...page, function: SMOKE_TEST }, signal).catch((e) => (log('look', `smoke test failed on ${rel}: ${e.message}`), null))
|
|
1316
|
-
const blob = ran && /\{"errors":\s*\[[\s\S]*?\],\s*"controls":\s*\d+\}/.exec(text(ran).replace(/\\n/g, ' ').replace(/\\"/g, '"').replace(/\\\\/g, '\\'))
|
|
1317
|
-
if (blob) {
|
|
1318
|
-
try {
|
|
1319
|
-
const r = JSON.parse(blob[0])
|
|
1320
|
-
for (const err of r.errors) errors.push(`${rel}: a control is broken — ${err}`)
|
|
1321
|
-
log('look', `${rel}: exercised ${r.controls} control(s), ${r.errors.length} broke`)
|
|
1322
|
-
} catch (e) {
|
|
1323
|
-
log('look', `smoke parse: ${e.message}`)
|
|
1324
|
-
}
|
|
1325
|
-
}
|
|
1326
|
-
for (const [width, height, fullPage] of [[1280, 900, true], [390, 844, false]]) {
|
|
1327
|
-
await browser.call('resize_page', { ...page, width, height }, signal)
|
|
1328
|
-
const r = await browser.call('take_screenshot', { ...page, ...(fullPage && { fullPage }) }, signal)
|
|
1329
|
-
const img = r.content?.find((p) => p.type === 'image' && p.data)
|
|
1330
|
-
if (img) shots.push({ label: `${rel} at ${width} px wide${fullPage ? ' (the whole page)' : ''}`, url: `data:${img.mimeType ?? 'image/png'};base64,${img.data}` })
|
|
1331
|
-
}
|
|
1332
|
-
if (id) await browser.call('close_page', page, signal).catch(() => {})
|
|
1333
|
-
}
|
|
1334
|
-
} catch (e) {
|
|
1335
|
-
if (signal?.aborted) throw e
|
|
1336
|
-
log('look', `couldn't open ${shown.join(', ')} in the browser: ${e.message}`)
|
|
1337
|
-
} finally {
|
|
1338
|
-
done?.()
|
|
1339
|
-
s.ui.stopSpin()
|
|
1340
|
-
}
|
|
1341
|
-
if (opened) s.lastCheckAt = s.seq ?? 0 // it ran in a browser: what changed was checked
|
|
1342
|
-
if (errors.length) log('look', `problems found: ${errors.join(' | ')}`)
|
|
1343
|
-
// Learn: a hard error that was there last look and is gone now was fixed — save the lesson so it
|
|
1344
|
-
// isn't made again (recalled on later tasks about the same tech). Only in the main agent.
|
|
1345
|
-
if (!s.isSub && s.memory) {
|
|
1346
|
-
const key = (e) => e.replace(/^[^:]*:\s*/, '').toLowerCase().replace(/["'`]/g, '').replace(/\d+/g, '#').replace(/\s+/g, ' ').trim().slice(0, 120)
|
|
1347
|
-
const nowKeys = new Set(errors.map(key))
|
|
1348
|
-
const fixed = (s.uiErrorsPrev ?? []).filter((p) => !nowKeys.has(p.key))
|
|
1349
|
-
if (fixed.length) await learnFromFixes(s, fixed, signal).catch((e) => log('learn', `failed: ${e.message}`))
|
|
1350
|
-
s.uiErrorsPrev = errors.map((e) => ({ key: key(e), error: e }))
|
|
1351
|
-
}
|
|
1352
|
-
// Couldn't open it in a browser (none configured, or it failed): don't pass silently — the model
|
|
1353
|
-
// must verify it itself. Static checks still apply.
|
|
1354
|
-
const unverified = opened === 0 ? `${shown.join(', ')} could not be opened in a browser here, so HeartCode could not confirm it works. Before you finish, verify it yourself: open it and check it actually works — no errors in the console, every button and interaction does what it should.` : ''
|
|
1355
|
-
// JavaScript errors mean the page is broken however good it looks: fed back on their own (text,
|
|
1356
|
-
// no model that sees needed), and the visual review added when there is one.
|
|
1357
|
-
const brokenList = errors.length ? errors.map((e, i) => `${i + 1}. ${e}`).join('\n') : ''
|
|
1358
|
-
let found = ''
|
|
1359
|
-
if (shots.length) {
|
|
1360
|
-
log('look', shots.map((x) => x.label))
|
|
1361
|
-
// reviewed in a request of its own (the screenshots and the user's request, nothing else): a
|
|
1362
|
-
// model checking its own work in its own conversation tends to call it fine
|
|
1363
|
-
const self = { provider: s.client.provider, model: s.client.model, images: s.strat.vision }
|
|
1364
|
-
const reviewers = [...(self.images ? [self] : []), ...(s.team?.() ?? []).filter((t) => t.images && !(t.provider === self.provider && t.model === self.model))]
|
|
1365
|
-
const ask = prompt('agent/ui-review', { task: s.task ?? '', shots: shots.map((x, i) => `${i + 1}. ${x.label}`).join('\n') })
|
|
1366
|
-
for (const t of reviewers) {
|
|
1367
|
-
s.ui.spinner(`${t.model} is reviewing ${shown.join(', ')}`)
|
|
1368
|
-
try {
|
|
1369
|
-
const { client } = t === self ? { client: s.client } : await s.engineFor(t)
|
|
1370
|
-
const was = client.purpose
|
|
1371
|
-
client.purpose = 'ui-review'
|
|
1372
|
-
try {
|
|
1373
|
-
found = (await client.chat({ messages: [{ role: 'user', content: [{ type: 'text', text: ask }, ...shots.map((x) => ({ type: 'image_url', image_url: { url: x.url } }))] }] }, { signal })).content.trim()
|
|
1374
|
-
} finally {
|
|
1375
|
-
client.purpose = was
|
|
1376
|
-
}
|
|
1377
|
-
if (found) break
|
|
1378
|
-
} catch (e) {
|
|
1379
|
-
if (signal?.aborted) throw e
|
|
1380
|
-
log('look', `${t.model} couldn't review: ${e.message}`)
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
s.ui.stopSpin()
|
|
1384
|
-
}
|
|
1385
|
-
const visual = found && !(/^\W*none\W*$/i.test(found) || !/\d+[.)]\s/.test(found)) ? found : ''
|
|
1386
|
-
if (!brokenList && !visual && !unverified) {
|
|
1387
|
-
if (shots.length) s.ui.step('look', `${shown.join(', ')}: works, nothing to fix`)
|
|
1388
|
-
return null
|
|
1389
|
-
}
|
|
1390
|
-
s.ui.step('look', `${shown.join(', ')}: ${[errors.length && `${errors.length} problem${errors.length > 1 ? 's' : ''}`, visual && 'review notes', unverified && 'verify it yourself'].filter(Boolean).join(', ')}`)
|
|
1391
|
-
const problems = [brokenList, visual, unverified].filter(Boolean).join('\n')
|
|
1392
|
-
return prompt('agent/look-at-ui', { files: shown.join(', '), problems })
|
|
1393
|
-
}
|
|
1394
|
-
|
|
1395
1205
|
// The model says it's done: is it? Not while its todo list (from this message) has open items, or
|
|
1396
1206
|
// while a Stop hook says otherwise. Returns what to tell it, or null. Each is asked a few times at
|
|
1397
1207
|
// most (the caller counts), so a model that can't finish still ends.
|
|
@@ -1510,15 +1320,16 @@ export async function review(s, task, answer, signal) {
|
|
|
1510
1320
|
if (!diffs.length) return null
|
|
1511
1321
|
const plan = (s.chat.todos ?? []).map((t) => `- [${t.status === 'completed' ? 'x' : ' '}] ${t.content}`).join('\n')
|
|
1512
1322
|
const ran = (s.ran ?? []).slice(-15).map((r) => `- ${clip(r.command.replace(/\s+/g, ' '), 160)} → ${r.result}`).join('\n')
|
|
1513
|
-
const ask = prompt('agent/review', { request: requestsOf(s.chat, 1200), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)' })
|
|
1323
|
+
const ask = prompt('agent/review', { request: requestsOf(s.chat, 1200), emphasis: (s.chat?.choices ?? []).join('; '), plan: plan || '(none)', answer: clip(String(answer ?? ''), 3000), changes: diffs.join('\n\n'), ran: ran || '(nothing)' })
|
|
1514
1324
|
const self = { provider: s.client.provider, model: s.client.model, self: true }
|
|
1515
1325
|
const fails = (t) => s.failures?.[`${t.provider} ${t.model}`] ?? 0
|
|
1516
|
-
const
|
|
1326
|
+
const team = (s.team?.() ?? []).filter((t) => t.tools !== false && !(t.provider === self.provider && t.model === self.model)).sort((a, b) => fails(a) - fails(b))
|
|
1327
|
+
const others = s.fitMode?.() && s.chat.fit?.review?.length ? byPick(team, s.chat.fit.review) : team // best fit: the best at checking code first
|
|
1517
1328
|
for (const t of [...others.slice(0, 2), self]) {
|
|
1518
1329
|
s.ui.spinner(`${t.model} is reviewing the work`)
|
|
1519
1330
|
try {
|
|
1520
1331
|
const { client } = t.self ? { client: s.client } : await s.engineFor(t)
|
|
1521
|
-
if (!t.self) client.retryIf = (e, attempt) => attempt < 2
|
|
1332
|
+
if (!t.self) client.retryIf = (e, attempt) => attempt < 2 && !e.notStarted
|
|
1522
1333
|
const was = client.purpose
|
|
1523
1334
|
client.purpose = 'review'
|
|
1524
1335
|
let said
|
package/src/background.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
// (and /background) reads what it printed since, lists them, stops
|
|
4
|
-
// group, its output going to a file; all of them are stopped when
|
|
1
|
+
// Every command run_command runs: started here, waited on for as long as the model chose, and if
|
|
2
|
+
// it's still running then, it carries on in the background (nothing ever blocks HeartCode); the
|
|
3
|
+
// background tool (and /background) reads what it printed since, waits on it, lists them, stops
|
|
4
|
+
// one. Each runs in its own process group, its output going to a file; all of them are stopped when
|
|
5
|
+
// HeartCode exits.
|
|
5
6
|
import fs from 'node:fs'
|
|
6
7
|
import path from 'node:path'
|
|
7
8
|
import { spawn } from 'node:child_process'
|
|
@@ -23,22 +24,35 @@ const kill = (job, sig) => {
|
|
|
23
24
|
}
|
|
24
25
|
}
|
|
25
26
|
|
|
26
|
-
// Started
|
|
27
|
-
export
|
|
27
|
+
// Started (it runs on; waitFor waits on it).
|
|
28
|
+
export function startJob(root, command) {
|
|
28
29
|
fs.mkdirSync(DIR, { recursive: true })
|
|
29
30
|
const id = ++made
|
|
30
31
|
const file = path.join(DIR, `${process.pid}-${id}.log`)
|
|
31
32
|
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
|
+
const child = spawn(command, { cwd: root, shell: true, detached: group, stdio: ['ignore', fd, fd], env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' } })
|
|
33
34
|
fs.closeSync(fd)
|
|
34
35
|
const job = { id, command, root, pid: child.pid, file, started: Date.now(), code: null, read: 0, exited: false, told: false }
|
|
35
36
|
jobs.set(id, job)
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
job.over = new Promise((r) => {
|
|
38
|
+
const end = (code) => r(Object.assign(job, { code, exited: true, ended: Date.now() }))
|
|
39
|
+
child.on('error', (e) => (fs.appendFileSync(file, `\n${e.message}\n`), end('error')))
|
|
40
|
+
child.on('exit', (code, sig) => end(code ?? sig))
|
|
41
|
+
})
|
|
38
42
|
child.unref()
|
|
39
43
|
log('background', `#${id} started: ${command} (pid ${child.pid})`)
|
|
40
|
-
|
|
41
|
-
|
|
44
|
+
return job
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Until it exits, `ms` pass or `signal` aborts, whichever comes first.
|
|
48
|
+
export function waitFor(job, ms, signal) {
|
|
49
|
+
if (job.exited || signal?.aborted) return Promise.resolve()
|
|
50
|
+
return new Promise((r) => {
|
|
51
|
+
const done = () => (clearTimeout(t), signal?.removeEventListener('abort', done), r())
|
|
52
|
+
const t = setTimeout(done, ms)
|
|
53
|
+
job.over.then(done)
|
|
54
|
+
signal?.addEventListener('abort', done, { once: true })
|
|
55
|
+
})
|
|
42
56
|
}
|
|
43
57
|
|
|
44
58
|
// What it printed since the last look (the last `most` characters of it).
|
|
@@ -69,16 +83,29 @@ export function tailLines(job, n) {
|
|
|
69
83
|
|
|
70
84
|
export const listJobs = (root) => [...jobs.values()].filter((j) => !root || j.root === root)
|
|
71
85
|
export const getJob = (id) => jobs.get(Number(String(id).replace(/^#/, '')))
|
|
72
|
-
|
|
86
|
+
// what a command left running has no exit to wait for: it's looked at (gone: marked so)
|
|
87
|
+
const settle = (j) => j.left && !j.exited && !kill(j, 0) && Object.assign(j, { exited: true, code: 'gone', ended: Date.now() })
|
|
88
|
+
export const runningJobs = (root) => listJobs(root).filter((j) => (settle(j), !j.exited))
|
|
73
89
|
|
|
74
90
|
export function stopJob(job) {
|
|
75
91
|
if (job.exited) return false
|
|
76
92
|
kill(job, 'SIGTERM')
|
|
77
93
|
setTimeout(() => kill(job, 'SIGKILL'), 2000).unref()
|
|
94
|
+
if (job.left) Object.assign(job, { exited: true, code: 'SIGTERM', ended: Date.now() }) // what a command left running: its shell's exit was long ago, so marked here
|
|
78
95
|
log('background', `#${job.id} stopped: ${job.command}`)
|
|
79
96
|
return true
|
|
80
97
|
}
|
|
81
98
|
|
|
99
|
+
// A command that ended but left processes running (`server &`, `nohup … &`): they're kept, as this
|
|
100
|
+
// background command (listed, stoppable, stopped when HeartCode exits), not killed — killing them
|
|
101
|
+
// left a model starting server after server. True when there were some.
|
|
102
|
+
export function keepLeftovers(job) {
|
|
103
|
+
if (!job.exited || !group || !kill(job, 0)) return false
|
|
104
|
+
Object.assign(job, { exited: false, code: null, left: true })
|
|
105
|
+
log('background', `#${job.id} left processes running: kept (${job.command})`)
|
|
106
|
+
return true
|
|
107
|
+
}
|
|
108
|
+
|
|
82
109
|
// Stopped (if it still runs) and taken off the list; its log file stays.
|
|
83
110
|
export function removeJob(job) {
|
|
84
111
|
stopJob(job)
|