@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
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+
4
+ const ignoredDirs = new Set(["node_modules", "dist", ".git", ".puzzmo", ".yarn", ".DS_Store"])
5
+ const maxDepth = 3
6
+ const maxEntriesPerDir = 12
7
+ const maxLines = 90
8
+
9
+ /**
10
+ * A short description of what's already on disk, handed to the agent with every step.
11
+ * Without it each step opens by globbing and reading its way back to the same picture,
12
+ * which is several tool round trips before any work starts.
13
+ */
14
+ export const describeProject = (gameDir: string): string => {
15
+ const sections = [`Project layout (${path.basename(gameDir)}/):`, ...treeLines(gameDir, "", 0, { count: 0 })]
16
+
17
+ const puzzmoJSON = readIfPresent(path.join(gameDir, "puzzmo.json"))
18
+ if (puzzmoJSON) sections.push("", "puzzmo.json:", puzzmoJSON.trim())
19
+
20
+ const scripts = readScripts(path.join(gameDir, "package.json"))
21
+ if (scripts) sections.push("", `package.json scripts: ${scripts}`)
22
+
23
+ return sections.join("\n")
24
+ }
25
+
26
+ /** Renders an indented tree, skipping build output and collapsing large directories */
27
+ const treeLines = (dir: string, prefix: string, depth: number, budget: { count: number }): string[] => {
28
+ if (depth > maxDepth || budget.count >= maxLines) return []
29
+
30
+ let entries: fs.Dirent[]
31
+ try {
32
+ entries = fs.readdirSync(dir, { withFileTypes: true })
33
+ } catch {
34
+ return []
35
+ }
36
+
37
+ const visible = entries.filter((e) => !ignoredDirs.has(e.name)).sort((a, b) => a.name.localeCompare(b.name))
38
+ const shown = visible.slice(0, maxEntriesPerDir)
39
+ const lines: string[] = []
40
+
41
+ for (const entry of shown) {
42
+ if (budget.count >= maxLines) break
43
+ budget.count++
44
+ if (entry.isDirectory()) {
45
+ lines.push(`${prefix} ${entry.name}/`)
46
+ lines.push(...treeLines(path.join(dir, entry.name), `${prefix} `, depth + 1, budget))
47
+ } else {
48
+ lines.push(`${prefix} ${entry.name}`)
49
+ }
50
+ }
51
+
52
+ if (visible.length > shown.length) lines.push(`${prefix} ... ${visible.length - shown.length} more`)
53
+ return lines
54
+ }
55
+
56
+ /** Reads a file, returning undefined when it's missing or unreadable */
57
+ const readIfPresent = (file: string): string | undefined => {
58
+ try {
59
+ return fs.readFileSync(file, "utf-8")
60
+ } catch {
61
+ return undefined
62
+ }
63
+ }
64
+
65
+ /** Comma-separated script names from a package.json, or undefined when there isn't one */
66
+ const readScripts = (pkgPath: string): string | undefined => {
67
+ const raw = readIfPresent(pkgPath)
68
+ if (!raw) return undefined
69
+ try {
70
+ const names = Object.keys(JSON.parse(raw).scripts ?? {})
71
+ return names.length > 0 ? names.join(", ") : undefined
72
+ } catch {
73
+ return undefined
74
+ }
75
+ }
@@ -77,6 +77,17 @@ export const listMcpPrompts = async (gameDir: string): Promise<{ name: string; d
77
77
  }
78
78
  }
79
79
 
80
+ /** Skill docs are immutable for the length of a run, so a retry never refetches one */
81
+ const promptCache = new Map<string, Promise<string>>()
82
+
83
+ /**
84
+ * Warms the cache for every skill a pipeline will need, in parallel, so steps don't
85
+ * each pay a round trip mid-run. Failures are left for the step itself to report.
86
+ */
87
+ export const prefetchSkillPrompts = async (stepNames: string[], gameDir: string): Promise<void> => {
88
+ await Promise.all([...new Set(stepNames)].map((name) => fetchSkillPrompt(name, gameDir).catch(() => undefined)))
89
+ }
90
+
80
91
  /** Fetches a step's instructions from the MCP server configured in .mcp.json */
81
92
  export const fetchSkillPrompt = async (stepName: string, gameDir: string): Promise<string> => {
82
93
  const config = readMcpConfig(gameDir)
@@ -85,6 +96,19 @@ export const fetchSkillPrompt = async (stepName: string, gameDir: string): Promi
85
96
  const server = Object.values(config.mcpServers)[0]
86
97
  if (!server) throw new Error("No MCP server configured in .mcp.json")
87
98
 
99
+ const cacheKey = `${server.url}|${stepName}`
100
+ const cached = promptCache.get(cacheKey)
101
+ if (cached) return cached
102
+
103
+ const pending = requestSkillPrompt(server, stepName)
104
+ promptCache.set(cacheKey, pending)
105
+ // A failed fetch shouldn't be remembered — the next attempt should try the network again.
106
+ pending.catch(() => promptCache.delete(cacheKey))
107
+ return pending
108
+ }
109
+
110
+ /** Performs the uncached prompts/get round trip and flattens the response to text */
111
+ const requestSkillPrompt = async (server: { url: string; headers?: Record<string, string> }, stepName: string): Promise<string> => {
88
112
  const result = await mcpRequest(server.url, server.headers ?? {}, "prompts/get", { name: stepName })
89
113
  if (!result?.messages?.length) throw new Error(`MCP server returned no instructions for "${stepName}"`)
90
114
 
@@ -4,20 +4,75 @@ export type SkillDefinition = {
4
4
  label?: string
5
5
  }
6
6
 
7
- /** Ordered list of skills for the migration pipeline */
8
- export const skillsPipeline: SkillDefinition[] = [
9
- { name: "convert-to-vite" },
10
- { name: "introduce-puzzmo-sdk" },
11
- { name: "game-completion" },
12
- { name: "add-deeds" },
13
- { name: "setup-augmentations" },
14
- { name: "create-app-bundle" },
15
- { name: "setup-deploy" },
7
+ /**
8
+ * One step of the migration. A step is a single agent invocation: its prompt is the local
9
+ * `preamble` followed by the skill docs fetched from the MCP server, so several related
10
+ * skills can be handled in one pass instead of one cold agent run each.
11
+ */
12
+ export type PipelineStep = {
13
+ /** Short id — used for the sidebar label, the commit message and the log file name */
14
+ name: string
15
+ /** Skill docs to fetch from the MCP server and append to the prompt, in order */
16
+ skills: string[]
17
+ /** Local instructions leading the fetched docs */
18
+ preamble: string
19
+ /** Set for steps that can't affect the build, so the build check is skipped */
20
+ skipBuild?: boolean
21
+ }
22
+
23
+ const portSourcePreamble = `Port the imported game into this Puzzmo project.
24
+
25
+ \`original/\` holds the game exactly as it was downloaded from the web — its HTML entry point
26
+ plus the scripts, styles and assets it referenced. Everything else in this directory is the
27
+ Minesweeper starter: a complete, working Puzzmo game that already builds.
28
+
29
+ Replace the starter's gameplay with the game from \`original/\`:
30
+ - Move the game's logic into \`src/main.ts\`, adding modules under \`src/\` where that keeps things
31
+ readable. Keep the SDK lifecycle calls that are already there (gameReady, gameLoaded,
32
+ on("start"), on("retry"), updateGameState, gameCompleted) and point them at the ported game.
33
+ - Update \`index.html\` and \`src/style.css\` to match what the ported game renders.
34
+ - Replace the puzzles in \`fixtures/puzzles/\` with puzzles for this game, in whatever format the
35
+ ported code parses out of \`puzzleString\`. Two or three with different characteristics.
36
+ - Delete \`original/\` once its contents have been ported or deliberately dropped.
37
+
38
+ A pristine copy of the starter stays in \`.puzzmo/reference/\` — read it whenever you need to see
39
+ how a finished Puzzmo game is wired. Leave the \`game\` block in puzzmo.json alone, and keep the
40
+ build green.`
41
+
42
+ const lifecyclePreamble = `Audit and complete this game's Puzzmo integration.
43
+
44
+ The SDK is already installed and the starter already wired up the lifecycle, so most of what
45
+ follows may be done — check each point against the ported game and fill in what is missing or
46
+ still describes Minesweeper rather than re-scaffolding it. Deeds and the leaderboards built on
47
+ them are the part most likely to be absent.
48
+
49
+ Do all of it in this one pass, in the order the instructions appear.`
50
+
51
+ const thumbnailPreamble = `Give this game a real thumbnail.
52
+
53
+ \`vite.config.ts\` already registers \`appBundlePlugin()\` and \`src/appBundle.tsx\` already exists
54
+ from the starter, so skip the plugin wiring below — the work is rewriting \`renderThumbnail\` so
55
+ it renders this game rather than a Minesweeper board.`
56
+
57
+ /**
58
+ * Steps for a game imported from a URL. The project is scaffolded from the bundled starter
59
+ * before any of this runs, so these steps only cover work that genuinely needs judgement.
60
+ */
61
+ export const importPipeline: PipelineStep[] = [
62
+ { name: "port-source", skills: [], preamble: portSourcePreamble },
63
+ {
64
+ name: "puzzmo-lifecycle",
65
+ skills: ["introduce-puzzmo-sdk", "game-completion", "add-deeds", "setup-augmentations"],
66
+ preamble: lifecyclePreamble,
67
+ },
68
+ { name: "thumbnail", skills: ["create-app-bundle"], preamble: thumbnailPreamble },
16
69
  ]
17
70
 
18
- /** Recommended optional skills offered as pre-checked tick boxes after the "from a prompt" flow */
71
+ /**
72
+ * Recommended optional skills offered as pre-checked tick boxes after the "from a prompt" flow.
73
+ * Deploy setup isn't here because the starter ships it: deploy scripts, .gitignore and README.
74
+ */
19
75
  export const optionalPromptSkills: SkillDefinition[] = [
20
76
  { name: "add-deeds", label: "Add deeds (in-game achievements)" },
21
77
  { name: "setup-augmentations", label: "Set up augmentations" },
22
- { name: "setup-deploy", label: "Set up deployment" },
23
78
  ]
@@ -1,25 +1,23 @@
1
1
  import fs from "node:fs"
2
2
  import path from "node:path"
3
3
 
4
- import { getAgent } from "../agents/index.js"
5
- import { skillsPipeline, type SkillDefinition } from "./registry.js"
6
- import { verifyBuild, runCommand, gitCommit } from "../util/exec.js"
7
- import { fetchSkillPrompt } from "./mcp-client.js"
8
- import { runPipelineTUI } from "../tui/pipeline.js"
9
-
10
- const agentTimeoutMs = 300000 // 5 minute timeout per agent invocation
11
-
12
- /** Fetches step instructions from the MCP server and wraps them as an agent prompt */
13
- const buildPrompt = async (stepName: string, gameDir: string, repoContext: string): Promise<string> => {
14
- const instructions = await fetchSkillPrompt(stepName, gameDir)
15
- return `Follow these instructions. The game source is in the current directory.\n\n${repoContext}\n\n${instructions}`
16
- }
4
+ import { getAgent, type AgentSession } from "../agents/index.js"
5
+ import { type PipelineStep, type SkillDefinition } from "./registry.js"
6
+ import { verifyBuild } from "../util/exec.js"
7
+ import { formatDuration } from "../util/duration.js"
8
+ import { agentIdleTimeoutMs, buildStepPrompt, commitStep, resetSession, type PipelineContext } from "./step.js"
17
9
 
18
10
  /**
19
11
  * Invokes an LLM agent with a prompt, streaming its text and tool activity to the console.
20
12
  * When `transcript` is provided, an ANSI-stripped copy of everything printed is appended to it.
21
13
  */
22
- const invokeAgent = async (agentName: string, prompt: string, cwd: string, transcript?: string[]): Promise<boolean> => {
14
+ const invokeAgent = async (
15
+ agentName: string,
16
+ prompt: string,
17
+ cwd: string,
18
+ session?: AgentSession,
19
+ transcript?: string[],
20
+ ): Promise<boolean> => {
23
21
  const agent = getAgent(agentName)
24
22
  if (!agent) {
25
23
  const line = ` Unknown agent: ${agentName}`
@@ -28,6 +26,7 @@ const invokeAgent = async (agentName: string, prompt: string, cwd: string, trans
28
26
  return false
29
27
  }
30
28
 
29
+ const started = Date.now()
31
30
  let resultOk: boolean | null = null
32
31
  let sawError = false
33
32
  let midLine = false
@@ -55,7 +54,7 @@ const invokeAgent = async (agentName: string, prompt: string, cwd: string, trans
55
54
  }
56
55
 
57
56
  try {
58
- for await (const event of agent.run({ prompt, cwd, signal: AbortSignal.timeout(agentTimeoutMs) })) {
57
+ for await (const event of agent.run({ prompt, cwd, session, idleTimeoutMs: agentIdleTimeoutMs })) {
59
58
  if (event.type === "text") {
60
59
  process.stdout.write(dim(event.text))
61
60
  midLine = !event.text.endsWith("\n")
@@ -71,8 +70,8 @@ const invokeAgent = async (agentName: string, prompt: string, cwd: string, trans
71
70
  printLine(` ${dim(event.text)}`)
72
71
  } else if (event.type === "result") {
73
72
  resultOk = event.ok
74
- const cost = event.costUSD != null ? ` ($${event.costUSD.toFixed(4)})` : ""
75
- printLine((event.ok ? green : red)(` Agent finished${cost}`))
73
+ const cost = event.costUSD != null ? `, $${event.costUSD.toFixed(4)}` : ""
74
+ printLine((event.ok ? green : red)(` Agent finished in ${formatDuration(Date.now() - started)}${cost}`))
76
75
  } else if (event.type === "error") {
77
76
  sawError = true
78
77
  printLine(red(` ${event.message}`))
@@ -85,75 +84,28 @@ const invokeAgent = async (agentName: string, prompt: string, cwd: string, trans
85
84
  endLine()
86
85
  flushBuf()
87
86
 
88
- return resultOk ?? !sawError
89
- }
90
-
91
- /** Runs the skills pipeline with plain console output (no TUI) */
92
- export const runSkillsPipeline = async (agent: string, gameDir: string, repoContext: string) => {
93
- const total = skillsPipeline.length
94
-
95
- for (let i = 0; i < total; i++) {
96
- const skill = skillsPipeline[i]
97
- const step = i + 1
98
- console.log(`[${step}/${total}] Running step: ${skill.name}`)
99
-
100
- const prompt = await buildPrompt(skill.name, gameDir, repoContext)
101
- let success = await invokeAgent(agent, prompt, gameDir)
102
-
103
- if (!success) {
104
- console.log(` Agent failed, retrying...`)
105
- success = await invokeAgent(agent, prompt, gameDir)
106
- if (!success) {
107
- console.error(` Step ${skill.name} failed after retry. Stopping pipeline.`)
108
- process.exit(1)
109
- }
110
- }
111
-
112
- // Verify build
113
- const buildResult = verifyBuild(gameDir)
114
- if (!buildResult.success) {
115
- console.log(` Build failed after ${skill.name}, asking agent to fix...`)
116
- const fixPrompt = `The vite build failed after the "${skill.name}" step. Fix the build errors:\n\n${buildResult.error}`
117
- await invokeAgent(agent, fixPrompt, gameDir)
118
-
119
- const retryBuild = verifyBuild(gameDir)
120
- if (!retryBuild.success) {
121
- console.error(` Build still failing after fix attempt. Stopping.`)
122
- process.exit(1)
123
- }
124
- }
125
-
126
- // Commit
127
- try {
128
- runCommand("git add -A", { cwd: gameDir })
129
- gitCommit(`step: ${skill.name}`, { cwd: gameDir })
130
- console.log(` Committed.`)
131
- } catch {
132
- console.log(` No changes to commit.`)
133
- }
134
- }
135
-
136
- console.log(`\nAll skills completed!`)
137
- }
138
-
139
- /** Runs the skills pipeline with a split-pane TUI */
140
- export const runSkillsPipelineTUI = async (agent: string, gameDir: string, repoContext: string) => {
141
- await runPipelineTUI(agent, gameDir, repoContext)
87
+ const ok = resultOk ?? !sawError
88
+ if (ok && session) session.started = true
89
+ return ok
142
90
  }
143
91
 
144
92
  /** Runs a chosen subset of skills (the optional add-ons after the prompt flow); warns but never exits on failure */
145
- export const runSelectedSkills = async (agent: string, gameDir: string, repoContext: string, skills: SkillDefinition[]) => {
93
+ export const runSelectedSkills = async (ctx: PipelineContext, skills: SkillDefinition[]) => {
146
94
  const total = skills.length
95
+ const startedAll = Date.now()
147
96
 
148
97
  for (let i = 0; i < total; i++) {
149
98
  const skill = skills[i]
99
+ const startedStep = Date.now()
150
100
  console.log(`[${i + 1}/${total}] Running step: ${skill.name}`)
151
101
 
152
- const prompt = await buildPrompt(skill.name, gameDir, repoContext)
153
- let success = await invokeAgent(agent, prompt, gameDir)
102
+ const step: PipelineStep = { name: skill.name, skills: [skill.name], preamble: "Follow these instructions." }
103
+ const prompt = await buildStepPrompt(step, ctx)
104
+ let success = await invokeAgent(ctx.agent, prompt, ctx.gameDir, ctx.session)
154
105
  if (!success) {
155
106
  console.log(` Agent failed, retrying...`)
156
- success = await invokeAgent(agent, prompt, gameDir)
107
+ resetSession(ctx.session)
108
+ success = await invokeAgent(ctx.agent, prompt, ctx.gameDir, ctx.session)
157
109
  }
158
110
  if (!success) {
159
111
  console.error(` Step ${skill.name} did not complete cleanly, skipping.`)
@@ -161,21 +113,19 @@ export const runSelectedSkills = async (agent: string, gameDir: string, repoCont
161
113
  }
162
114
 
163
115
  // Verify build; ask the agent to fix but keep going regardless
164
- const buildResult = verifyBuild(gameDir)
116
+ const buildResult = await verifyBuild(ctx.gameDir, ctx.buildCmd)
165
117
  if (!buildResult.success) {
166
118
  console.log(` Build failed after ${skill.name}, asking agent to fix...`)
167
- const fixPrompt = `The vite build failed after the "${skill.name}" step. Fix the build errors:\n\n${buildResult.error}`
168
- await invokeAgent(agent, fixPrompt, gameDir)
119
+ const fixPrompt = `The build (${ctx.buildCmd}) failed after the "${skill.name}" step. Fix the build errors:\n\n${buildResult.error}`
120
+ await invokeAgent(ctx.agent, fixPrompt, ctx.gameDir, ctx.session)
169
121
  }
170
122
 
171
- try {
172
- runCommand("git add -A", { cwd: gameDir })
173
- gitCommit(`step: ${skill.name}`, { cwd: gameDir })
174
- console.log(` Committed.`)
175
- } catch {
176
- console.log(` No changes to commit.`)
177
- }
123
+ const committed = await commitStep(ctx.gameDir, skill.name)
124
+ console.log(committed ? " Committed." : " No changes to commit.")
125
+ console.log(` ${skill.name} took ${formatDuration(Date.now() - startedStep)}`)
178
126
  }
127
+
128
+ if (total > 0) console.log(`Optional skills finished in ${formatDuration(Date.now() - startedAll)}`)
179
129
  }
180
130
 
181
131
  /**
@@ -185,7 +135,8 @@ export const runSelectedSkills = async (agent: string, gameDir: string, repoCont
185
135
  export type BuildLoopResult = { ok: true; logPath: string } | { ok: false; reason: string; buildError?: string; logPath: string }
186
136
 
187
137
  /** Runs a single agent invocation, verifies the build, and commits. Used by one-shot prompt-driven flows. */
188
- export const runAgentWithBuildLoop = async (agent: string, prompt: string, gameDir: string, label: string): Promise<BuildLoopResult> => {
138
+ export const runAgentWithBuildLoop = async (ctx: PipelineContext, prompt: string, label: string): Promise<BuildLoopResult> => {
139
+ const started = Date.now()
189
140
  const transcript: string[] = []
190
141
  // Print to the console and record the same line to the run transcript.
191
142
  const say = (line: string) => {
@@ -194,40 +145,38 @@ export const runAgentWithBuildLoop = async (agent: string, prompt: string, gameD
194
145
  }
195
146
 
196
147
  say(`Running agent: ${label}`)
197
- let success = await invokeAgent(agent, prompt, gameDir, transcript)
148
+ let success = await invokeAgent(ctx.agent, prompt, ctx.gameDir, ctx.session, transcript)
198
149
  if (!success) {
199
150
  say(` Agent failed, retrying...`)
200
- success = await invokeAgent(agent, prompt, gameDir, transcript)
151
+ resetSession(ctx.session)
152
+ success = await invokeAgent(ctx.agent, prompt, ctx.gameDir, ctx.session, transcript)
201
153
  if (!success) {
202
154
  say(` Agent failed after retry. Stopping.`)
203
- const logPath = writeRunLog(gameDir, label, transcript)
155
+ const logPath = writeRunLog(ctx.gameDir, label, transcript)
204
156
  return { ok: false, reason: "the agent did not finish successfully after two attempts", logPath }
205
157
  }
206
158
  }
207
159
 
208
- const buildResult = verifyBuild(gameDir)
160
+ const buildStarted = Date.now()
161
+ const buildResult = await verifyBuild(ctx.gameDir, ctx.buildCmd)
162
+ say(dim(` Build took ${formatDuration(Date.now() - buildStarted)}`))
209
163
  if (!buildResult.success) {
210
164
  say(` Build failed, asking agent to fix...`)
211
165
  recordBuildError(say, buildResult.error)
212
- const fixPrompt = `The vite build failed after the "${label}" step. Fix the build errors:\n\n${buildResult.error}`
213
- await invokeAgent(agent, fixPrompt, gameDir, transcript)
214
- const retry = verifyBuild(gameDir)
166
+ const fixPrompt = `The build (${ctx.buildCmd}) failed after the "${label}" step. Fix the build errors:\n\n${buildResult.error}`
167
+ await invokeAgent(ctx.agent, fixPrompt, ctx.gameDir, ctx.session, transcript)
168
+ const retry = await verifyBuild(ctx.gameDir, ctx.buildCmd)
215
169
  if (!retry.success) {
216
170
  say(` Build still failing after fix attempt.`)
217
171
  recordBuildError(say, retry.error)
218
- const logPath = writeRunLog(gameDir, label, transcript)
219
- return { ok: false, reason: "the vite build is still failing after the agent's fix attempt", buildError: retry.error, logPath }
172
+ const logPath = writeRunLog(ctx.gameDir, label, transcript)
173
+ return { ok: false, reason: "the build is still failing after the agent's fix attempt", buildError: retry.error, logPath }
220
174
  }
221
175
  }
222
176
 
223
- try {
224
- runCommand("git add -A", { cwd: gameDir })
225
- gitCommit(`step: ${label}`, { cwd: gameDir })
226
- say(` Committed.`)
227
- } catch {
228
- say(` No changes to commit.`)
229
- }
230
- return { ok: true, logPath: writeRunLog(gameDir, label, transcript) }
177
+ say((await commitStep(ctx.gameDir, label)) ? " Committed." : " No changes to commit.")
178
+ say(` ${label} finished in ${formatDuration(Date.now() - started)}`)
179
+ return { ok: true, logPath: writeRunLog(ctx.gameDir, label, transcript) }
231
180
  }
232
181
 
233
182
  /** Emits captured build output via `say`, trimmed to the trailing lines that usually hold the actual error */
@@ -0,0 +1,47 @@
1
+ import { randomUUID } from "node:crypto"
2
+
3
+ import type { AgentSession } from "../agents/index.js"
4
+ import type { PipelineStep } from "./registry.js"
5
+ import { runCapture } from "../util/exec.js"
6
+ import { fetchSkillPrompt } from "./mcp-client.js"
7
+ import { describeProject } from "./context.js"
8
+
9
+ /** Stop an agent that has produced no output at all for this long — a wedged run, not a thinking one */
10
+ export const agentIdleTimeoutMs = 120000
11
+
12
+ /** Everything a step needs to run: which agent, where, how to build, and the conversation to continue */
13
+ export type PipelineContext = {
14
+ agent: string
15
+ gameDir: string
16
+ repoContext: string
17
+ /** Command that builds the game, resolved from the detected package manager */
18
+ buildCmd: string
19
+ /** Shared across steps so the agent keeps its picture of the project between them */
20
+ session: AgentSession
21
+ }
22
+
23
+ /** A fresh conversation. Steps share one of these; a retry rotates to a new one. */
24
+ export const newSession = (): AgentSession => ({ id: randomUUID(), started: false })
25
+
26
+ /** Points the context at a new conversation, so the next run starts cold */
27
+ export const resetSession = (session: AgentSession) => {
28
+ session.id = randomUUID()
29
+ session.started = false
30
+ }
31
+
32
+ /**
33
+ * Assembles a step's prompt: local instructions, the state of the project, then the skill
34
+ * docs from the MCP server. Several skills in one step become one agent invocation.
35
+ */
36
+ export const buildStepPrompt = async (step: PipelineStep, ctx: PipelineContext): Promise<string> => {
37
+ const docs = await Promise.all(step.skills.map((name) => fetchSkillPrompt(name, ctx.gameDir)))
38
+ const parts = [step.preamble, ctx.repoContext, describeProject(ctx.gameDir), ...docs]
39
+ return parts.filter(Boolean).join("\n\n---\n\n")
40
+ }
41
+
42
+ /** Stages and commits whatever the step changed. False when there was nothing to commit. */
43
+ export const commitStep = async (gameDir: string, label: string): Promise<boolean> => {
44
+ await runCapture("git add -A", { cwd: gameDir })
45
+ const result = await runCapture(`git commit -m "step: ${label}"`, { cwd: gameDir })
46
+ return result.success
47
+ }