@puzzmo/cli 1.0.71 → 1.0.73

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.
Files changed (83) hide show
  1. package/lib/agents/claude.d.ts +2 -2
  2. package/lib/agents/claude.js +67 -16
  3. package/lib/agents/claude.js.map +1 -1
  4. package/lib/agents/codex.js +12 -1
  5. package/lib/agents/codex.js.map +1 -1
  6. package/lib/agents/copilot.js +10 -1
  7. package/lib/agents/copilot.js.map +1 -1
  8. package/lib/agents/gemini.js +9 -1
  9. package/lib/agents/gemini.js.map +1 -1
  10. package/lib/agents/index.d.ts +1 -1
  11. package/lib/agents/stream-json-cli.d.ts +5 -4
  12. package/lib/agents/stream-json-cli.js +29 -4
  13. package/lib/agents/stream-json-cli.js.map +1 -1
  14. package/lib/agents/types.d.ts +15 -0
  15. package/lib/commands/game/create.js +46 -18
  16. package/lib/commands/game/create.js.map +1 -1
  17. package/lib/commands/game/seedImport.d.ts +13 -0
  18. package/lib/commands/game/seedImport.js +25 -0
  19. package/lib/commands/game/seedImport.js.map +1 -0
  20. package/lib/commands/upload.js +8 -19
  21. package/lib/commands/upload.js.map +1 -1
  22. package/lib/download/page-downloader.js +20 -7
  23. package/lib/download/page-downloader.js.map +1 -1
  24. package/lib/skills/context.d.ts +6 -0
  25. package/lib/skills/context.js +74 -0
  26. package/lib/skills/context.js.map +1 -0
  27. package/lib/skills/mcp-client.d.ts +5 -0
  28. package/lib/skills/mcp-client.js +21 -0
  29. package/lib/skills/mcp-client.js.map +1 -1
  30. package/lib/skills/registry.d.ts +24 -3
  31. package/lib/skills/registry.js +47 -11
  32. package/lib/skills/registry.js.map +1 -1
  33. package/lib/skills/runner.d.ts +3 -6
  34. package/lib/skills/runner.js +45 -94
  35. package/lib/skills/runner.js.map +1 -1
  36. package/lib/skills/step.d.ts +25 -0
  37. package/lib/skills/step.js +29 -0
  38. package/lib/skills/step.js.map +1 -0
  39. package/lib/tui/pipeline.d.ts +3 -1
  40. package/lib/tui/pipeline.js +195 -75
  41. package/lib/tui/pipeline.js.map +1 -1
  42. package/lib/util/collapseRepeats.d.ts +20 -0
  43. package/lib/util/collapseRepeats.js +80 -0
  44. package/lib/util/collapseRepeats.js.map +1 -0
  45. package/lib/util/duration.d.ts +7 -0
  46. package/lib/util/duration.js +25 -0
  47. package/lib/util/duration.js.map +1 -0
  48. package/lib/util/exec.d.ts +15 -3
  49. package/lib/util/exec.js +37 -7
  50. package/lib/util/exec.js.map +1 -1
  51. package/lib/util/mascot.d.ts +18 -0
  52. package/lib/util/mascot.js +42 -0
  53. package/lib/util/mascot.js.map +1 -0
  54. package/package.json +3 -2
  55. package/scripts/demo-tui.mjs +108 -0
  56. package/src/agents/__fixtures__/README.md +1 -0
  57. package/src/agents/__fixtures__/claude-bash.jsonl +114 -0
  58. package/src/agents/claude.ts +64 -16
  59. package/src/agents/codex.ts +12 -1
  60. package/src/agents/copilot.ts +10 -1
  61. package/src/agents/gemini.ts +9 -1
  62. package/src/agents/index.ts +1 -1
  63. package/src/agents/parse-line.test.ts +40 -6
  64. package/src/agents/stream-json-cli.ts +32 -8
  65. package/src/agents/types.ts +16 -0
  66. package/src/commands/game/create.ts +47 -18
  67. package/src/commands/game/seedImport.ts +30 -0
  68. package/src/commands/upload.ts +7 -21
  69. package/src/download/page-downloader.ts +22 -7
  70. package/src/skills/context.ts +75 -0
  71. package/src/skills/mcp-client.ts +24 -0
  72. package/src/skills/registry.ts +66 -11
  73. package/src/skills/runner.ts +52 -103
  74. package/src/skills/step.ts +47 -0
  75. package/src/tui/pipeline.ts +200 -72
  76. package/src/util/collapseRepeats.test.ts +78 -0
  77. package/src/util/collapseRepeats.ts +77 -0
  78. package/src/util/duration.test.ts +37 -0
  79. package/src/util/duration.ts +25 -0
  80. package/src/util/exec.ts +40 -7
  81. package/src/util/mascot.ts +55 -0
  82. package/templates/minesweeper/README.md +3 -1
  83. package/templates/minesweeper/package.json +3 -1
@@ -1,10 +1,14 @@
1
- import { execSync } from "node:child_process"
2
1
  import fs from "node:fs"
3
2
  import path from "node:path"
4
3
 
5
4
  import { getAgent, type Agent, type AgentEvent } from "../agents/index.js"
6
- import { skillsPipeline } from "../skills/registry.js"
7
- import { fetchSkillPrompt } from "../skills/mcp-client.js"
5
+ import type { PipelineStep } from "../skills/registry.js"
6
+ import { prefetchSkillPrompts } from "../skills/mcp-client.js"
7
+ import { agentIdleTimeoutMs, buildStepPrompt, commitStep, resetSession, type PipelineContext } from "../skills/step.js"
8
+ import { collapseRepeats, foldTailRepeat, type RepeatableLine } from "../util/collapseRepeats.js"
9
+ import { verifyBuild } from "../util/exec.js"
10
+ import { formatDuration, formatElapsed } from "../util/duration.js"
11
+ import { mascotLarge, mascotSmall, pickMascot, type Mascot } from "../util/mascot.js"
8
12
 
9
13
  type StepState = "pending" | "running" | "success" | "failed" | "skipped"
10
14
  type Phase = "agent" | "build" | "commit" | "idle"
@@ -54,11 +58,6 @@ const phaseColor: Record<Phase, (s: string) => string> = {
54
58
  const ansiRe = /\x1b\[[0-9;]*[A-Za-z]/g
55
59
  const stripAnsi = (s: string) => s.replace(ansiRe, "")
56
60
 
57
- const buildPrompt = async (stepName: string, gameDir: string, repoContext: string): Promise<string> => {
58
- const instructions = await fetchSkillPrompt(stepName, gameDir)
59
- return `Follow these instructions. The game source is in the current directory.\n\n${repoContext}\n\n${instructions}`
60
- }
61
-
62
61
  /**
63
62
  * Format a non-streaming event into discrete lines. text/thinking are handled
64
63
  * separately by appendText so token deltas merge into one in-progress line.
@@ -75,26 +74,35 @@ const formatDiscreteEvent = (e: AgentEvent): string[] => {
75
74
  return []
76
75
  }
77
76
 
77
+ /** Where a step's wall-clock went, so it's clear whether a slow run is the agent or the build */
78
+ type StepTiming = { name: string; state: StepState; agentMs: number; buildMs: number; totalMs: number }
79
+
78
80
  class PipelineTUI {
79
81
  private states: StepState[]
80
82
  private currentStep = 0
81
83
  private phase: Phase = "idle"
82
84
  private done = false
83
- private outputLines: string[] = []
85
+ private outputLines: RepeatableLine[] = []
84
86
  private currentLine = ""
85
87
  private chatLines: string[] = []
86
88
  private renderScheduled = false
87
89
  private sidebarWidth = 30
88
90
  private logsDir: string
89
91
  private abortController: AbortController | null = null
92
+ private timings: StepTiming[] = []
93
+ /** Accumulated inside the running step, folded into `timings` when it finishes */
94
+ private agentMs = 0
95
+ private buildMs = 0
96
+ private stepStartedAt: number | null = null
97
+ private ticker: NodeJS.Timeout | null = null
90
98
 
91
99
  constructor(
92
100
  private agent: Agent,
93
- private gameDir: string,
94
- private repoContext: string,
101
+ private ctx: PipelineContext,
102
+ private steps: PipelineStep[],
95
103
  ) {
96
- this.states = skillsPipeline.map(() => "pending")
97
- this.logsDir = path.join(gameDir, ".puzzmo", "logs")
104
+ this.states = steps.map(() => "pending")
105
+ this.logsDir = path.join(ctx.gameDir, ".puzzmo", "logs")
98
106
  fs.mkdirSync(this.logsDir, { recursive: true })
99
107
  }
100
108
 
@@ -130,11 +138,20 @@ class PipelineTUI {
130
138
  /** Lock the in-progress streaming line as a complete entry. */
131
139
  private lockCurrent() {
132
140
  if (this.currentLine.length === 0) return
133
- this.outputLines.push(this.currentLine)
134
- this.chatLines.push(stripAnsi(this.currentLine))
141
+ this.pushLine(this.currentLine)
135
142
  this.currentLine = ""
136
143
  }
137
144
 
145
+ /**
146
+ * Appends one finished line to the pane, folding it into the block above when it
147
+ * repeats. The log keeps every line — `writeSkillLog` folds its own copy.
148
+ */
149
+ private pushLine(text: string) {
150
+ this.outputLines.push({ text, reps: 1 })
151
+ this.chatLines.push(stripAnsi(text))
152
+ foldTailRepeat(this.outputLines)
153
+ }
154
+
138
155
  /**
139
156
  * Append streaming text. Newlines lock the in-progress line; the trailing
140
157
  * fragment continues as the in-progress line. Optional styler wraps each
@@ -160,10 +177,7 @@ class PipelineTUI {
160
177
  private appendLines(lines: string[]) {
161
178
  if (lines.length === 0) return
162
179
  this.lockCurrent()
163
- for (const line of lines) {
164
- this.outputLines.push(line)
165
- this.chatLines.push(stripAnsi(line))
166
- }
180
+ for (const line of lines) this.pushLine(line)
167
181
  if (this.outputLines.length > 1000) this.outputLines = this.outputLines.slice(-this.contentRows * 4)
168
182
  this.scheduleRender()
169
183
  }
@@ -180,7 +194,7 @@ class PipelineTUI {
180
194
  buf += moveTo(2, 1)
181
195
  buf += "│ " + bold("Migration Steps") + " ".repeat(Math.max(0, sidebarWidth - 18)) + "│"
182
196
 
183
- const headerLabel = this.done ? "Done" : `${skillsPipeline[this.currentStep]?.name ?? ""} ${dim(`(${this.phase})`)}`
197
+ const headerLabel = this.done ? "Done" : `${this.steps[this.currentStep]?.name ?? ""} ${dim(`(${this.phase})`)}`
184
198
  const styledHeader = phaseColor[this.phase](bold(headerLabel))
185
199
  const headerVisible = stripAnsi(headerLabel).length
186
200
  buf += " " + styledHeader + " ".repeat(Math.max(0, outputWidth - headerVisible - 1)) + "│"
@@ -188,40 +202,59 @@ class PipelineTUI {
188
202
  buf += moveTo(3, 1)
189
203
  buf += "├" + "─".repeat(sidebarWidth - 2) + "┼" + "─".repeat(outputWidth) + "┤"
190
204
 
205
+ const mascot = this.sidebarMascot()
206
+ const mascotTop = mascot ? contentRows - mascot.height : -1
207
+
191
208
  for (let row = 0; row < contentRows; row++) {
192
209
  buf += moveTo(row + 4, 1)
193
210
 
194
211
  const skillIndex = row
195
- if (skillIndex < skillsPipeline.length) {
196
- const skill = skillsPipeline[skillIndex]
212
+ if (skillIndex < this.steps.length) {
213
+ const skill = this.steps[skillIndex]
197
214
  const state = this.states[skillIndex]
198
215
  const isActive = skillIndex === this.currentStep && !this.done
199
- const icon = stateIcon[state]
200
216
  const colorFn = stateColor[state]
201
- const label = `${icon} ${skill.name}`
217
+ // The elapsed time sits right-aligned in the sidebar; the step name gives way to it.
218
+ const elapsed = this.stepDuration(skillIndex)
219
+ const tail = elapsed ? `${elapsed} ` : ""
220
+ const room = sidebarWidth - 3
221
+ const label = `${stateIcon[state]} ${skill.name}`.slice(0, room - tail.length - 1)
202
222
  const styled = isActive ? bold(colorFn(label)) : colorFn(label)
203
- const rawLen = stripAnsi(styled).length
204
- buf += "│ " + styled + " ".repeat(Math.max(0, sidebarWidth - rawLen - 3)) + "│"
205
- } else if (skillIndex === skillsPipeline.length + 1) {
223
+ const gap = Math.max(1, room - label.length - tail.length)
224
+ buf += "│ " + styled + " ".repeat(gap) + dim(tail) + "│"
225
+ } else if (skillIndex === this.steps.length + 1) {
206
226
  const completedCount = this.states.filter((s) => s === "success").length
207
227
  const failedCount = this.states.filter((s) => s === "failed").length
208
228
  const status = this.done
209
229
  ? failedCount > 0
210
230
  ? red(`${failedCount} failure(s)`)
211
231
  : green("All complete!")
212
- : dim(`${completedCount}/${skillsPipeline.length} done`)
232
+ : dim(`${completedCount}/${this.steps.length} done`)
213
233
  const rawLen = stripAnsi(status).length
214
234
  buf += "│ " + status + " ".repeat(Math.max(0, sidebarWidth - rawLen - 3)) + "│"
235
+ } else if (mascot && row >= mascotTop) {
236
+ // Art rows are exactly mascot.width columns wide, so only the right pad varies.
237
+ buf += "│ " + mascot.lines[row - mascotTop] + " ".repeat(Math.max(0, sidebarWidth - mascot.width - 3)) + "│"
215
238
  } else {
216
239
  buf += "│" + " ".repeat(sidebarWidth - 2) + "│"
217
240
  }
218
241
 
219
242
  const visibleCount = this.outputLines.length + (this.currentLine.length > 0 ? 1 : 0)
220
243
  const lineIndex = visibleCount - contentRows + row
221
- const rawLine = lineIndex < 0 ? "" : lineIndex < this.outputLines.length ? (this.outputLines[lineIndex] ?? "") : this.currentLine
222
- const truncated = truncateVisible(rawLine, outputWidth - 2)
223
- const visibleLen = stripAnsi(truncated).length
224
- buf += " " + truncated + " ".repeat(Math.max(0, outputWidth - visibleLen - 1)) + "│"
244
+ const entry = this.outputLines[lineIndex]
245
+ const width = outputWidth - 2
246
+ const rendered =
247
+ lineIndex < 0
248
+ ? ""
249
+ : lineIndex < this.outputLines.length
250
+ ? entry
251
+ ? displayLine(entry, width)
252
+ : ""
253
+ : truncateVisible(this.currentLine, width)
254
+ const visibleLen = stripAnsi(rendered).length
255
+ // Truncation can land before a line's own reset, so close the row explicitly —
256
+ // otherwise the style bleeds through the border into the next row's sidebar.
257
+ buf += " " + rendered + reset() + " ".repeat(Math.max(0, outputWidth - visibleLen - 1)) + "│"
225
258
  }
226
259
 
227
260
  buf += moveTo(rows, 1)
@@ -230,12 +263,36 @@ class PipelineTUI {
230
263
  this.write(buf)
231
264
  }
232
265
 
233
- private async runAgent(prompt: string): Promise<boolean> {
266
+ /**
267
+ * The biggest mascot that fits in the sidebar below the step list, or null when
268
+ * there is no room. Reserves a blank row above it so it never abuts the status line.
269
+ */
270
+ private sidebarMascot(): Mascot | null {
271
+ const free = this.contentRows - (this.steps.length + 2)
272
+ const room = this.sidebarWidth - 3
273
+ for (const candidate of [mascotLarge, mascotSmall]) {
274
+ const art = pickMascot(candidate)
275
+ if (art && art.height + 1 <= free && art.width <= room) return art
276
+ }
277
+ return null
278
+ }
279
+
280
+ /** Runs the agent, continuing the pipeline's conversation unless `cold` asks for a fresh one. */
281
+ private async runAgent(prompt: string, cold = false): Promise<boolean> {
234
282
  this.abortController = new AbortController()
283
+ if (cold) resetSession(this.ctx.session)
284
+ const started = Date.now()
235
285
  let sawError = false
236
286
  let resultOk: boolean | null = null
237
287
  try {
238
- for await (const event of this.agent.run({ prompt, cwd: this.gameDir, signal: this.abortController.signal })) {
288
+ const run = this.agent.run({
289
+ prompt,
290
+ cwd: this.ctx.gameDir,
291
+ signal: this.abortController.signal,
292
+ session: this.ctx.session,
293
+ idleTimeoutMs: agentIdleTimeoutMs,
294
+ })
295
+ for await (const event of run) {
239
296
  if (event.type === "error") sawError = true
240
297
  if (event.type === "result") resultOk = event.ok
241
298
  if (event.type === "text") {
@@ -254,26 +311,54 @@ class PipelineTUI {
254
311
  return false
255
312
  } finally {
256
313
  this.abortController = null
314
+ this.agentMs += Date.now() - started
257
315
  }
258
316
  this.lockCurrent()
317
+ this.appendLines([dim(`Agent run took ${formatDuration(Date.now() - started)}`)])
259
318
  if (resultOk != null) return resultOk
260
319
  return !sawError
261
320
  }
262
321
 
263
- private runCmd(cmd: string): { success: boolean; output: string } {
322
+ /** Elapsed so far for the step in flight, final wall-clock for the ones that have finished */
323
+ private stepDuration(index: number): string {
324
+ const finished = this.timings[index]
325
+ if (finished) return formatDuration(finished.totalMs)
326
+ if (this.states[index] === "running" && this.stepStartedAt != null) return formatElapsed(Date.now() - this.stepStartedAt)
327
+ return ""
328
+ }
329
+
330
+ /** Times a step and files the result under its index, however the step exits */
331
+ private async runStep(stepIndex: number): Promise<boolean> {
332
+ this.agentMs = 0
333
+ this.buildMs = 0
334
+ const started = Date.now()
335
+ this.stepStartedAt = started
264
336
  try {
265
- const output = execSync(cmd, { cwd: this.gameDir, encoding: "utf-8", stdio: "pipe" })
266
- if (output.trim()) this.appendLines(output.trim().split("\n"))
267
- return { success: true, output }
268
- } catch (e: any) {
269
- const output = (e.stdout || "") + (e.stderr || "") || e.message
270
- if (output.trim()) this.appendLines(output.trim().split("\n"))
271
- return { success: false, output }
337
+ return await this.executeStep(stepIndex)
338
+ } finally {
339
+ this.timings[stepIndex] = {
340
+ name: this.steps[stepIndex].name,
341
+ state: this.states[stepIndex],
342
+ agentMs: this.agentMs,
343
+ buildMs: this.buildMs,
344
+ totalMs: Date.now() - started,
345
+ }
346
+ this.stepStartedAt = null
347
+ this.render() // repaint so the row swaps its live counter for the final time
272
348
  }
273
349
  }
274
350
 
275
- private async runStep(stepIndex: number): Promise<boolean> {
276
- const skill = skillsPipeline[stepIndex]
351
+ /** Runs the project's build, echoing its output into the pane */
352
+ private async verify(): Promise<{ success: boolean; error?: string }> {
353
+ const started = Date.now()
354
+ const result = await verifyBuild(this.ctx.gameDir, this.ctx.buildCmd)
355
+ this.buildMs += Date.now() - started
356
+ if (result.error?.trim()) this.appendLines(result.error.trim().split("\n"))
357
+ return result
358
+ }
359
+
360
+ private async executeStep(stepIndex: number): Promise<boolean> {
361
+ const step = this.steps[stepIndex]
277
362
  this.states[stepIndex] = "running"
278
363
  this.currentStep = stepIndex
279
364
  this.outputLines = []
@@ -284,48 +369,51 @@ class PipelineTUI {
284
369
 
285
370
  let prompt: string
286
371
  try {
287
- prompt = await buildPrompt(skill.name, this.gameDir, this.repoContext)
372
+ prompt = await buildStepPrompt(step, this.ctx)
288
373
  } catch (e: any) {
289
374
  this.appendLines([red(`Failed to fetch instructions: ${e.message}`)])
290
- this.writeSkillLog(skill.name)
375
+ this.writeSkillLog(step.name)
291
376
  this.states[stepIndex] = "failed"
292
377
  return false
293
378
  }
294
379
 
295
380
  let success = await this.runAgent(prompt)
296
381
  if (!success) {
297
- this.appendLines(["", dim("--- Retrying ---")])
298
- success = await this.runAgent(prompt)
382
+ // Retry cold: whatever went wrong may have been the resumed conversation itself
383
+ // (an agent that can't resume, or one that wedged partway through).
384
+ this.appendLines(["", dim("--- Retrying in a fresh session ---")])
385
+ success = await this.runAgent(prompt, true)
299
386
  if (!success) {
300
- this.writeSkillLog(skill.name)
387
+ this.writeSkillLog(step.name)
301
388
  this.states[stepIndex] = "failed"
302
389
  return false
303
390
  }
304
391
  }
305
392
 
306
- this.phase = "build"
307
- this.render()
308
- this.appendLines([dim("Verifying build...")])
309
- const buildResult = this.runCmd("npx vite build")
310
- if (!buildResult.success) {
311
- this.appendLines([dim("Asking agent to fix...")])
312
- const fixPrompt = `The vite build failed after the "${skill.name}" step. Fix the build errors:\n\n${buildResult.output}`
313
- await this.runAgent(fixPrompt)
314
- const retry = this.runCmd("npx vite build")
315
- if (!retry.success) {
316
- this.writeSkillLog(skill.name)
317
- this.states[stepIndex] = "failed"
318
- return false
393
+ if (!step.skipBuild) {
394
+ this.phase = "build"
395
+ this.render()
396
+ this.appendLines([dim(`Verifying build (${this.ctx.buildCmd})...`)])
397
+ const buildResult = await this.verify()
398
+ if (!buildResult.success) {
399
+ this.appendLines([dim("Asking agent to fix...")])
400
+ const fixPrompt = `The build (${this.ctx.buildCmd}) failed after the "${step.name}" step. Fix the build errors:\n\n${buildResult.error}`
401
+ await this.runAgent(fixPrompt)
402
+ const retry = await this.verify()
403
+ if (!retry.success) {
404
+ this.writeSkillLog(step.name)
405
+ this.states[stepIndex] = "failed"
406
+ return false
407
+ }
319
408
  }
320
409
  }
321
410
 
322
411
  this.phase = "commit"
323
412
  this.render()
324
- this.runCmd("git add -A")
325
- const commitResult = this.runCmd(`git commit -m "step: ${skill.name}"`)
326
- this.appendLines([dim(commitResult.success ? "Committed." : "No changes to commit.")])
413
+ const committed = await commitStep(this.ctx.gameDir, step.name)
414
+ this.appendLines([dim(committed ? "Committed." : "No changes to commit.")])
327
415
 
328
- this.writeSkillLog(skill.name)
416
+ this.writeSkillLog(step.name)
329
417
 
330
418
  this.states[stepIndex] = "success"
331
419
  this.render()
@@ -334,7 +422,22 @@ class PipelineTUI {
334
422
 
335
423
  private writeSkillLog(skillName: string) {
336
424
  const logPath = path.join(this.logsDir, `${skillName}.txt`)
337
- fs.writeFileSync(logPath, this.chatLines.join("\n") + "\n")
425
+ const timing = `Timing: agent ${formatDuration(this.agentMs)}, build ${formatDuration(this.buildMs)}`
426
+ fs.writeFileSync(logPath, [...collapseRepeats(this.chatLines), "", timing].join("\n") + "\n")
427
+ }
428
+
429
+ /** Prints where the run's time went, once the full-screen view has been torn down */
430
+ private printSummary(totalMs: number) {
431
+ if (this.timings.length === 0) return
432
+ const width = Math.max(...this.timings.map((t) => t.name.length))
433
+ const lines = [``, bold(`Migration finished in ${formatDuration(totalMs)}`)]
434
+ for (const t of this.timings) {
435
+ const icon = stateColor[t.state](stateIcon[t.state])
436
+ const spent = dim(`(agent ${formatDuration(t.agentMs)}, build ${formatDuration(t.buildMs)})`)
437
+ lines.push(` ${icon} ${t.name.padEnd(width)} ${formatDuration(t.totalMs).padStart(7)} ${spent}`)
438
+ }
439
+ lines.push(dim(` logs: ${this.logsDir}`))
440
+ console.log(lines.join("\n"))
338
441
  }
339
442
 
340
443
  private setupInput() {
@@ -351,19 +454,33 @@ class PipelineTUI {
351
454
  }
352
455
 
353
456
  private cleanup() {
457
+ if (this.ticker) clearInterval(this.ticker)
458
+ this.ticker = null
354
459
  this.write(showCursor())
355
460
  if (process.stdin.isTTY) process.stdin.setRawMode(false)
356
461
  process.stdin.pause()
357
462
  }
358
463
 
359
464
  async run() {
465
+ const startedAll = Date.now()
360
466
  this.write(hideCursor())
361
467
  this.setupInput()
362
468
  this.render()
363
469
 
364
470
  process.stdout.on("resize", () => this.render())
365
471
 
366
- for (let i = 0; i < skillsPipeline.length; i++) {
472
+ // Steps run for minutes at a time, so repaint on a timer to keep the elapsed column moving
473
+ // even while the agent is silent.
474
+ this.ticker = setInterval(() => this.scheduleRender(), 1000)
475
+ this.ticker.unref()
476
+
477
+ // Warm every skill doc up front, in parallel, so no step waits on the network mid-run.
478
+ await prefetchSkillPrompts(
479
+ this.steps.flatMap((s) => s.skills),
480
+ this.ctx.gameDir,
481
+ )
482
+
483
+ for (let i = 0; i < this.steps.length; i++) {
367
484
  const ok = await this.runStep(i)
368
485
  if (!ok) {
369
486
  this.appendLines(["", red("Pipeline stopped due to failure.")])
@@ -375,9 +492,20 @@ class PipelineTUI {
375
492
  this.done = true
376
493
  this.render()
377
494
  this.cleanup()
495
+ this.printSummary(Date.now() - startedAll)
378
496
  }
379
497
  }
380
498
 
499
+ /**
500
+ * Renders a pane line inside `width` columns, tagging it with its repeat count once it
501
+ * has folded. The tag is appended after truncation so a long line can't push it off the edge.
502
+ */
503
+ const displayLine = (line: RepeatableLine, width: number): string => {
504
+ if (line.reps < 2) return truncateVisible(line.text, width)
505
+ const tag = ` (x ${line.reps})`
506
+ return truncateVisible(line.text, Math.max(0, width - tag.length)) + dim(tag)
507
+ }
508
+
381
509
  /** Truncate a string to a visible width, preserving ANSI codes. */
382
510
  const truncateVisible = (s: string, maxWidth: number): string => {
383
511
  let visible = 0
@@ -401,9 +529,9 @@ const truncateVisible = (s: string, maxWidth: number): string => {
401
529
  return s.slice(0, i)
402
530
  }
403
531
 
404
- export const runPipelineTUI = async (agentName: string, gameDir: string, repoContext: string): Promise<void> => {
405
- const agent = getAgent(agentName)
406
- if (!agent) throw new Error(`Unknown agent: ${agentName}`)
407
- const tui = new PipelineTUI(agent, gameDir, repoContext)
532
+ export const runPipelineTUI = async (ctx: PipelineContext, steps: PipelineStep[]): Promise<void> => {
533
+ const agent = getAgent(ctx.agent)
534
+ if (!agent) throw new Error(`Unknown agent: ${ctx.agent}`)
535
+ const tui = new PipelineTUI(agent, ctx, steps)
408
536
  await tui.run()
409
537
  }
@@ -0,0 +1,78 @@
1
+ import { describe, expect, it } from "vitest"
2
+
3
+ import { collapseRepeats, foldTailRepeat, type RepeatableLine } from "./collapseRepeats.js"
4
+
5
+ /** Feeds lines in one at a time the way the pane does, then flattens for comparison. */
6
+ const appendAll = (texts: string[]): string[] => {
7
+ const lines: RepeatableLine[] = []
8
+ for (const text of texts) {
9
+ lines.push({ text, reps: 1 })
10
+ foldTailRepeat(lines)
11
+ }
12
+ return lines.map((l) => (l.reps > 1 ? `${l.text} (x ${l.reps})` : l.text))
13
+ }
14
+
15
+ describe("foldTailRepeat", () => {
16
+ it("folds identical lines as they arrive", () => {
17
+ expect(appendAll(["a", "a", "a", "b"])).toEqual(["a (x 3)", "b"])
18
+ })
19
+
20
+ it("folds a repeating call/result pair, which is what retried edits look like", () => {
21
+ const stream = ["Edit main.ts", " ✓ updated", "Edit main.ts", " ✓ updated", "Edit main.ts", " ✓ updated", "Done"]
22
+ expect(appendAll(stream)).toEqual(["Edit main.ts (x 3)", " ✓ updated", "Done"])
23
+ })
24
+
25
+ it("leaves non-adjacent repeats alone", () => {
26
+ expect(appendAll(["a", "b", "a"])).toEqual(["a", "b", "a"])
27
+ })
28
+
29
+ it("keeps a half-finished repeat visible until it completes", () => {
30
+ expect(appendAll(["Edit x", " ✓ ok", "Edit x"])).toEqual(["Edit x", " ✓ ok", "Edit x"])
31
+ expect(appendAll(["Edit x", " ✓ ok", "Edit x", " ✓ ok"])).toEqual(["Edit x (x 2)", " ✓ ok"])
32
+ })
33
+
34
+ it("never buries an existing count inside a folded block", () => {
35
+ // The second "a (x 2)" cannot merge into the first without losing a tally.
36
+ expect(appendAll(["a", "a", "b", "a", "a", "b"])).toEqual(["a (x 2)", "b", "a (x 2)", "b"])
37
+ })
38
+
39
+ it("reports whether it folded", () => {
40
+ const lines: RepeatableLine[] = [{ text: "a", reps: 1 }]
41
+ expect(foldTailRepeat(lines)).toBe(false)
42
+ lines.push({ text: "a", reps: 1 })
43
+ expect(foldTailRepeat(lines)).toBe(true)
44
+ expect(lines).toEqual([{ text: "a", reps: 2 }])
45
+ })
46
+ })
47
+
48
+ describe("collapseRepeats", () => {
49
+ it("leaves lines with no repeats alone", () => {
50
+ expect(collapseRepeats(["a", "b", "c"])).toEqual(["a", "b", "c"])
51
+ })
52
+
53
+ it("folds consecutive identical lines", () => {
54
+ expect(collapseRepeats(["a", "a", "a", "b"])).toEqual(["a (x 3)", "b"])
55
+ })
56
+
57
+ it("folds a repeating call/result pair, which is what retried edits look like", () => {
58
+ const lines = ["Edit main.ts", " ✓ updated", "Edit main.ts", " ✓ updated", "Edit main.ts", " ✓ updated", "Done"]
59
+ expect(collapseRepeats(lines)).toEqual(["Edit main.ts (x 3)", " ✓ updated", "Done"])
60
+ })
61
+
62
+ it("does not fold repeats that are not adjacent", () => {
63
+ expect(collapseRepeats(["a", "b", "a"])).toEqual(["a", "b", "a"])
64
+ })
65
+
66
+ it("keeps a trailing partial block rather than swallowing it", () => {
67
+ expect(collapseRepeats(["a", "b", "a", "b", "a"])).toEqual(["a (x 2)", "b", "a"])
68
+ })
69
+
70
+ it("prefers the block length that folds the most lines", () => {
71
+ // Folding the pair covers six lines; folding just the leading "a" would cover two.
72
+ expect(collapseRepeats(["a", "a", "b", "a", "a", "b", "a", "a", "b"])).toEqual(["a", "a", "b"].map((l, i) => (i === 0 ? "a (x 3)" : l)))
73
+ })
74
+
75
+ it("handles an empty input", () => {
76
+ expect(collapseRepeats([])).toEqual([])
77
+ })
78
+ })
@@ -0,0 +1,77 @@
1
+ /** Longest run of lines considered as a repeating unit — a tool call plus its result is two. */
2
+ const maxBlockLines = 10
3
+
4
+ /** A line of output, plus how many times it repeated in place. */
5
+ export type RepeatableLine = { text: string; reps: number }
6
+
7
+ /**
8
+ * Folds the just-appended tail into an identical block directly above it, bumping that
9
+ * block's count. Agents retry the same edit over and over, and each attempt logs its call
10
+ * and its result on separate lines, so this matches repeating *blocks*, not just lines.
11
+ *
12
+ * Mutates `lines` and runs in the append path, so a live pane can fold without re-scanning
13
+ * its whole buffer on every render. Returns true when a fold happened.
14
+ */
15
+ export const foldTailRepeat = (lines: RepeatableLine[]): boolean => {
16
+ for (let size = 1; size <= maxBlockLines; size++) {
17
+ const tail = lines.length - size
18
+ const prev = tail - size
19
+ if (prev < 0) return false
20
+ if (!foldable(lines, prev, tail, size)) continue
21
+ // The earlier copy carries the count for the whole block, so the new one just goes.
22
+ lines[prev].reps++
23
+ lines.length = tail
24
+ return true
25
+ }
26
+ return false
27
+ }
28
+
29
+ /**
30
+ * Folds consecutive repeats across a finished array in one pass, preferring whichever
31
+ * block length swallows the most lines. Use this for a written log; use `foldTailRepeat`
32
+ * for anything appended incrementally.
33
+ */
34
+ export const collapseRepeats = (lines: string[]): string[] => {
35
+ const out: string[] = []
36
+ let index = 0
37
+ while (index < lines.length) {
38
+ let bestSize = 1
39
+ let bestReps = 1
40
+ for (let size = 1; size <= maxBlockLines && index + size * 2 <= lines.length; size++) {
41
+ let reps = 1
42
+ while (blockRepeats(lines, index, size, reps)) reps++
43
+ if (reps > 1 && size * reps > bestSize * bestReps) {
44
+ bestSize = size
45
+ bestReps = reps
46
+ }
47
+ }
48
+
49
+ const block = lines.slice(index, index + bestSize)
50
+ if (bestReps > 1) block[0] = `${block[0]} (x ${bestReps})`
51
+ out.push(...block)
52
+ index += bestSize * bestReps
53
+ }
54
+ return out
55
+ }
56
+
57
+ /**
58
+ * True when the block at `b` is an unfolded repeat of the block at `a`. Both blocks must
59
+ * be free of existing counts (bar the first line of `a`, which is where a count lives),
60
+ * so folding can never bury a tally inside a block and lose it.
61
+ */
62
+ const foldable = (lines: RepeatableLine[], a: number, b: number, size: number): boolean => {
63
+ for (let i = 0; i < size; i++) {
64
+ if (lines[b + i].reps !== 1) return false
65
+ if (i > 0 && lines[a + i].reps !== 1) return false
66
+ if (lines[a + i].text !== lines[b + i].text) return false
67
+ }
68
+ return true
69
+ }
70
+
71
+ /** True when copy number `reps` of the block at `start` is still an exact match. */
72
+ const blockRepeats = (lines: string[], start: number, size: number, reps: number): boolean => {
73
+ const offset = start + reps * size
74
+ if (offset + size > lines.length) return false
75
+ for (let i = 0; i < size; i++) if (lines[offset + i] !== lines[start + i]) return false
76
+ return true
77
+ }
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from "vitest"
2
+
3
+ import { formatDuration, formatElapsed } from "./duration.js"
4
+
5
+ describe("formatDuration", () => {
6
+ it("uses milliseconds under a second", () => {
7
+ expect(formatDuration(0)).toBe("0ms")
8
+ expect(formatDuration(283)).toBe("283ms")
9
+ expect(formatDuration(999)).toBe("999ms")
10
+ })
11
+
12
+ it("uses one decimal of seconds under a minute", () => {
13
+ expect(formatDuration(1000)).toBe("1.0s")
14
+ expect(formatDuration(12_400)).toBe("12.4s")
15
+ })
16
+
17
+ it("uses zero-padded minutes and seconds above a minute", () => {
18
+ expect(formatDuration(60_000)).toBe("1m00s")
19
+ expect(formatDuration(362_000)).toBe("6m02s")
20
+ })
21
+
22
+ it("carries seconds that round up to a full minute", () => {
23
+ expect(formatDuration(119_700)).toBe("2m00s")
24
+ })
25
+ })
26
+
27
+ describe("formatElapsed", () => {
28
+ it("drops sub-second precision so a live counter doesn't flicker", () => {
29
+ expect(formatElapsed(9)).toBe("0s")
30
+ expect(formatElapsed(999)).toBe("0s")
31
+ expect(formatElapsed(12_400)).toBe("12s")
32
+ })
33
+
34
+ it("matches formatDuration above a minute", () => {
35
+ expect(formatElapsed(65_400)).toBe("1m05s")
36
+ })
37
+ })