@puzzmo/cli 1.0.71 → 1.0.72
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/lib/agents/claude.d.ts +2 -2
- package/lib/agents/claude.js +67 -16
- package/lib/agents/claude.js.map +1 -1
- package/lib/agents/codex.js +12 -1
- package/lib/agents/codex.js.map +1 -1
- package/lib/agents/copilot.js +10 -1
- package/lib/agents/copilot.js.map +1 -1
- package/lib/agents/gemini.js +9 -1
- package/lib/agents/gemini.js.map +1 -1
- package/lib/agents/index.d.ts +1 -1
- package/lib/agents/stream-json-cli.d.ts +5 -4
- package/lib/agents/stream-json-cli.js +29 -4
- package/lib/agents/stream-json-cli.js.map +1 -1
- package/lib/agents/types.d.ts +15 -0
- package/lib/commands/game/create.js +46 -18
- package/lib/commands/game/create.js.map +1 -1
- package/lib/commands/game/seedImport.d.ts +13 -0
- package/lib/commands/game/seedImport.js +25 -0
- package/lib/commands/game/seedImport.js.map +1 -0
- package/lib/download/page-downloader.js +20 -7
- package/lib/download/page-downloader.js.map +1 -1
- package/lib/skills/context.d.ts +6 -0
- package/lib/skills/context.js +74 -0
- package/lib/skills/context.js.map +1 -0
- package/lib/skills/mcp-client.d.ts +5 -0
- package/lib/skills/mcp-client.js +21 -0
- package/lib/skills/mcp-client.js.map +1 -1
- package/lib/skills/registry.d.ts +24 -3
- package/lib/skills/registry.js +47 -11
- package/lib/skills/registry.js.map +1 -1
- package/lib/skills/runner.d.ts +3 -6
- package/lib/skills/runner.js +45 -94
- package/lib/skills/runner.js.map +1 -1
- package/lib/skills/step.d.ts +25 -0
- package/lib/skills/step.js +29 -0
- package/lib/skills/step.js.map +1 -0
- package/lib/tui/pipeline.d.ts +3 -1
- package/lib/tui/pipeline.js +138 -65
- package/lib/tui/pipeline.js.map +1 -1
- package/lib/util/duration.d.ts +7 -0
- package/lib/util/duration.js +25 -0
- package/lib/util/duration.js.map +1 -0
- package/lib/util/exec.d.ts +15 -3
- package/lib/util/exec.js +37 -7
- package/lib/util/exec.js.map +1 -1
- package/package.json +1 -1
- package/src/agents/__fixtures__/README.md +1 -0
- package/src/agents/__fixtures__/claude-bash.jsonl +114 -0
- package/src/agents/claude.ts +64 -16
- package/src/agents/codex.ts +12 -1
- package/src/agents/copilot.ts +10 -1
- package/src/agents/gemini.ts +9 -1
- package/src/agents/index.ts +1 -1
- package/src/agents/parse-line.test.ts +40 -6
- package/src/agents/stream-json-cli.ts +32 -8
- package/src/agents/types.ts +16 -0
- package/src/commands/game/create.ts +47 -18
- package/src/commands/game/seedImport.ts +30 -0
- package/src/download/page-downloader.ts +22 -7
- package/src/skills/context.ts +75 -0
- package/src/skills/mcp-client.ts +24 -0
- package/src/skills/registry.ts +66 -11
- package/src/skills/runner.ts +52 -103
- package/src/skills/step.ts +47 -0
- package/src/tui/pipeline.ts +141 -61
- package/src/util/duration.test.ts +37 -0
- package/src/util/duration.ts +25 -0
- package/src/util/exec.ts +40 -7
- package/templates/minesweeper/README.md +3 -1
- package/templates/minesweeper/package.json +3 -1
package/src/skills/runner.ts
CHANGED
|
@@ -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 {
|
|
6
|
-
import { verifyBuild
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
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 (
|
|
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,
|
|
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 ?
|
|
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
|
-
|
|
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 (
|
|
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
|
|
153
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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 (
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
+
}
|
package/src/tui/pipeline.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
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 {
|
|
7
|
-
import {
|
|
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 { verifyBuild } from "../util/exec.js"
|
|
9
|
+
import { formatDuration, formatElapsed } from "../util/duration.js"
|
|
8
10
|
|
|
9
11
|
type StepState = "pending" | "running" | "success" | "failed" | "skipped"
|
|
10
12
|
type Phase = "agent" | "build" | "commit" | "idle"
|
|
@@ -54,11 +56,6 @@ const phaseColor: Record<Phase, (s: string) => string> = {
|
|
|
54
56
|
const ansiRe = /\x1b\[[0-9;]*[A-Za-z]/g
|
|
55
57
|
const stripAnsi = (s: string) => s.replace(ansiRe, "")
|
|
56
58
|
|
|
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
59
|
/**
|
|
63
60
|
* Format a non-streaming event into discrete lines. text/thinking are handled
|
|
64
61
|
* separately by appendText so token deltas merge into one in-progress line.
|
|
@@ -75,6 +72,9 @@ const formatDiscreteEvent = (e: AgentEvent): string[] => {
|
|
|
75
72
|
return []
|
|
76
73
|
}
|
|
77
74
|
|
|
75
|
+
/** Where a step's wall-clock went, so it's clear whether a slow run is the agent or the build */
|
|
76
|
+
type StepTiming = { name: string; state: StepState; agentMs: number; buildMs: number; totalMs: number }
|
|
77
|
+
|
|
78
78
|
class PipelineTUI {
|
|
79
79
|
private states: StepState[]
|
|
80
80
|
private currentStep = 0
|
|
@@ -87,14 +87,20 @@ class PipelineTUI {
|
|
|
87
87
|
private sidebarWidth = 30
|
|
88
88
|
private logsDir: string
|
|
89
89
|
private abortController: AbortController | null = null
|
|
90
|
+
private timings: StepTiming[] = []
|
|
91
|
+
/** Accumulated inside the running step, folded into `timings` when it finishes */
|
|
92
|
+
private agentMs = 0
|
|
93
|
+
private buildMs = 0
|
|
94
|
+
private stepStartedAt: number | null = null
|
|
95
|
+
private ticker: NodeJS.Timeout | null = null
|
|
90
96
|
|
|
91
97
|
constructor(
|
|
92
98
|
private agent: Agent,
|
|
93
|
-
private
|
|
94
|
-
private
|
|
99
|
+
private ctx: PipelineContext,
|
|
100
|
+
private steps: PipelineStep[],
|
|
95
101
|
) {
|
|
96
|
-
this.states =
|
|
97
|
-
this.logsDir = path.join(gameDir, ".puzzmo", "logs")
|
|
102
|
+
this.states = steps.map(() => "pending")
|
|
103
|
+
this.logsDir = path.join(ctx.gameDir, ".puzzmo", "logs")
|
|
98
104
|
fs.mkdirSync(this.logsDir, { recursive: true })
|
|
99
105
|
}
|
|
100
106
|
|
|
@@ -180,7 +186,7 @@ class PipelineTUI {
|
|
|
180
186
|
buf += moveTo(2, 1)
|
|
181
187
|
buf += "│ " + bold("Migration Steps") + " ".repeat(Math.max(0, sidebarWidth - 18)) + "│"
|
|
182
188
|
|
|
183
|
-
const headerLabel = this.done ? "Done" : `${
|
|
189
|
+
const headerLabel = this.done ? "Done" : `${this.steps[this.currentStep]?.name ?? ""} ${dim(`(${this.phase})`)}`
|
|
184
190
|
const styledHeader = phaseColor[this.phase](bold(headerLabel))
|
|
185
191
|
const headerVisible = stripAnsi(headerLabel).length
|
|
186
192
|
buf += " " + styledHeader + " ".repeat(Math.max(0, outputWidth - headerVisible - 1)) + "│"
|
|
@@ -192,24 +198,27 @@ class PipelineTUI {
|
|
|
192
198
|
buf += moveTo(row + 4, 1)
|
|
193
199
|
|
|
194
200
|
const skillIndex = row
|
|
195
|
-
if (skillIndex <
|
|
196
|
-
const skill =
|
|
201
|
+
if (skillIndex < this.steps.length) {
|
|
202
|
+
const skill = this.steps[skillIndex]
|
|
197
203
|
const state = this.states[skillIndex]
|
|
198
204
|
const isActive = skillIndex === this.currentStep && !this.done
|
|
199
|
-
const icon = stateIcon[state]
|
|
200
205
|
const colorFn = stateColor[state]
|
|
201
|
-
|
|
206
|
+
// The elapsed time sits right-aligned in the sidebar; the step name gives way to it.
|
|
207
|
+
const elapsed = this.stepDuration(skillIndex)
|
|
208
|
+
const tail = elapsed ? `${elapsed} ` : ""
|
|
209
|
+
const room = sidebarWidth - 3
|
|
210
|
+
const label = `${stateIcon[state]} ${skill.name}`.slice(0, room - tail.length - 1)
|
|
202
211
|
const styled = isActive ? bold(colorFn(label)) : colorFn(label)
|
|
203
|
-
const
|
|
204
|
-
buf += "│ " + styled + " ".repeat(
|
|
205
|
-
} else if (skillIndex ===
|
|
212
|
+
const gap = Math.max(1, room - label.length - tail.length)
|
|
213
|
+
buf += "│ " + styled + " ".repeat(gap) + dim(tail) + "│"
|
|
214
|
+
} else if (skillIndex === this.steps.length + 1) {
|
|
206
215
|
const completedCount = this.states.filter((s) => s === "success").length
|
|
207
216
|
const failedCount = this.states.filter((s) => s === "failed").length
|
|
208
217
|
const status = this.done
|
|
209
218
|
? failedCount > 0
|
|
210
219
|
? red(`${failedCount} failure(s)`)
|
|
211
220
|
: green("All complete!")
|
|
212
|
-
: dim(`${completedCount}/${
|
|
221
|
+
: dim(`${completedCount}/${this.steps.length} done`)
|
|
213
222
|
const rawLen = stripAnsi(status).length
|
|
214
223
|
buf += "│ " + status + " ".repeat(Math.max(0, sidebarWidth - rawLen - 3)) + "│"
|
|
215
224
|
} else {
|
|
@@ -230,12 +239,22 @@ class PipelineTUI {
|
|
|
230
239
|
this.write(buf)
|
|
231
240
|
}
|
|
232
241
|
|
|
233
|
-
|
|
242
|
+
/** Runs the agent, continuing the pipeline's conversation unless `cold` asks for a fresh one. */
|
|
243
|
+
private async runAgent(prompt: string, cold = false): Promise<boolean> {
|
|
234
244
|
this.abortController = new AbortController()
|
|
245
|
+
if (cold) resetSession(this.ctx.session)
|
|
246
|
+
const started = Date.now()
|
|
235
247
|
let sawError = false
|
|
236
248
|
let resultOk: boolean | null = null
|
|
237
249
|
try {
|
|
238
|
-
|
|
250
|
+
const run = this.agent.run({
|
|
251
|
+
prompt,
|
|
252
|
+
cwd: this.ctx.gameDir,
|
|
253
|
+
signal: this.abortController.signal,
|
|
254
|
+
session: this.ctx.session,
|
|
255
|
+
idleTimeoutMs: agentIdleTimeoutMs,
|
|
256
|
+
})
|
|
257
|
+
for await (const event of run) {
|
|
239
258
|
if (event.type === "error") sawError = true
|
|
240
259
|
if (event.type === "result") resultOk = event.ok
|
|
241
260
|
if (event.type === "text") {
|
|
@@ -254,26 +273,54 @@ class PipelineTUI {
|
|
|
254
273
|
return false
|
|
255
274
|
} finally {
|
|
256
275
|
this.abortController = null
|
|
276
|
+
this.agentMs += Date.now() - started
|
|
257
277
|
}
|
|
258
278
|
this.lockCurrent()
|
|
279
|
+
this.appendLines([dim(`Agent run took ${formatDuration(Date.now() - started)}`)])
|
|
259
280
|
if (resultOk != null) return resultOk
|
|
260
281
|
return !sawError
|
|
261
282
|
}
|
|
262
283
|
|
|
263
|
-
|
|
284
|
+
/** Elapsed so far for the step in flight, final wall-clock for the ones that have finished */
|
|
285
|
+
private stepDuration(index: number): string {
|
|
286
|
+
const finished = this.timings[index]
|
|
287
|
+
if (finished) return formatDuration(finished.totalMs)
|
|
288
|
+
if (this.states[index] === "running" && this.stepStartedAt != null) return formatElapsed(Date.now() - this.stepStartedAt)
|
|
289
|
+
return ""
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Times a step and files the result under its index, however the step exits */
|
|
293
|
+
private async runStep(stepIndex: number): Promise<boolean> {
|
|
294
|
+
this.agentMs = 0
|
|
295
|
+
this.buildMs = 0
|
|
296
|
+
const started = Date.now()
|
|
297
|
+
this.stepStartedAt = started
|
|
264
298
|
try {
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
299
|
+
return await this.executeStep(stepIndex)
|
|
300
|
+
} finally {
|
|
301
|
+
this.timings[stepIndex] = {
|
|
302
|
+
name: this.steps[stepIndex].name,
|
|
303
|
+
state: this.states[stepIndex],
|
|
304
|
+
agentMs: this.agentMs,
|
|
305
|
+
buildMs: this.buildMs,
|
|
306
|
+
totalMs: Date.now() - started,
|
|
307
|
+
}
|
|
308
|
+
this.stepStartedAt = null
|
|
309
|
+
this.render() // repaint so the row swaps its live counter for the final time
|
|
272
310
|
}
|
|
273
311
|
}
|
|
274
312
|
|
|
275
|
-
|
|
276
|
-
|
|
313
|
+
/** Runs the project's build, echoing its output into the pane */
|
|
314
|
+
private async verify(): Promise<{ success: boolean; error?: string }> {
|
|
315
|
+
const started = Date.now()
|
|
316
|
+
const result = await verifyBuild(this.ctx.gameDir, this.ctx.buildCmd)
|
|
317
|
+
this.buildMs += Date.now() - started
|
|
318
|
+
if (result.error?.trim()) this.appendLines(result.error.trim().split("\n"))
|
|
319
|
+
return result
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
private async executeStep(stepIndex: number): Promise<boolean> {
|
|
323
|
+
const step = this.steps[stepIndex]
|
|
277
324
|
this.states[stepIndex] = "running"
|
|
278
325
|
this.currentStep = stepIndex
|
|
279
326
|
this.outputLines = []
|
|
@@ -284,48 +331,51 @@ class PipelineTUI {
|
|
|
284
331
|
|
|
285
332
|
let prompt: string
|
|
286
333
|
try {
|
|
287
|
-
prompt = await
|
|
334
|
+
prompt = await buildStepPrompt(step, this.ctx)
|
|
288
335
|
} catch (e: any) {
|
|
289
336
|
this.appendLines([red(`Failed to fetch instructions: ${e.message}`)])
|
|
290
|
-
this.writeSkillLog(
|
|
337
|
+
this.writeSkillLog(step.name)
|
|
291
338
|
this.states[stepIndex] = "failed"
|
|
292
339
|
return false
|
|
293
340
|
}
|
|
294
341
|
|
|
295
342
|
let success = await this.runAgent(prompt)
|
|
296
343
|
if (!success) {
|
|
297
|
-
|
|
298
|
-
|
|
344
|
+
// Retry cold: whatever went wrong may have been the resumed conversation itself
|
|
345
|
+
// (an agent that can't resume, or one that wedged partway through).
|
|
346
|
+
this.appendLines(["", dim("--- Retrying in a fresh session ---")])
|
|
347
|
+
success = await this.runAgent(prompt, true)
|
|
299
348
|
if (!success) {
|
|
300
|
-
this.writeSkillLog(
|
|
349
|
+
this.writeSkillLog(step.name)
|
|
301
350
|
this.states[stepIndex] = "failed"
|
|
302
351
|
return false
|
|
303
352
|
}
|
|
304
353
|
}
|
|
305
354
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
355
|
+
if (!step.skipBuild) {
|
|
356
|
+
this.phase = "build"
|
|
357
|
+
this.render()
|
|
358
|
+
this.appendLines([dim(`Verifying build (${this.ctx.buildCmd})...`)])
|
|
359
|
+
const buildResult = await this.verify()
|
|
360
|
+
if (!buildResult.success) {
|
|
361
|
+
this.appendLines([dim("Asking agent to fix...")])
|
|
362
|
+
const fixPrompt = `The build (${this.ctx.buildCmd}) failed after the "${step.name}" step. Fix the build errors:\n\n${buildResult.error}`
|
|
363
|
+
await this.runAgent(fixPrompt)
|
|
364
|
+
const retry = await this.verify()
|
|
365
|
+
if (!retry.success) {
|
|
366
|
+
this.writeSkillLog(step.name)
|
|
367
|
+
this.states[stepIndex] = "failed"
|
|
368
|
+
return false
|
|
369
|
+
}
|
|
319
370
|
}
|
|
320
371
|
}
|
|
321
372
|
|
|
322
373
|
this.phase = "commit"
|
|
323
374
|
this.render()
|
|
324
|
-
this.
|
|
325
|
-
|
|
326
|
-
this.appendLines([dim(commitResult.success ? "Committed." : "No changes to commit.")])
|
|
375
|
+
const committed = await commitStep(this.ctx.gameDir, step.name)
|
|
376
|
+
this.appendLines([dim(committed ? "Committed." : "No changes to commit.")])
|
|
327
377
|
|
|
328
|
-
this.writeSkillLog(
|
|
378
|
+
this.writeSkillLog(step.name)
|
|
329
379
|
|
|
330
380
|
this.states[stepIndex] = "success"
|
|
331
381
|
this.render()
|
|
@@ -334,7 +384,22 @@ class PipelineTUI {
|
|
|
334
384
|
|
|
335
385
|
private writeSkillLog(skillName: string) {
|
|
336
386
|
const logPath = path.join(this.logsDir, `${skillName}.txt`)
|
|
337
|
-
|
|
387
|
+
const timing = `Timing: agent ${formatDuration(this.agentMs)}, build ${formatDuration(this.buildMs)}`
|
|
388
|
+
fs.writeFileSync(logPath, [...this.chatLines, "", timing].join("\n") + "\n")
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Prints where the run's time went, once the full-screen view has been torn down */
|
|
392
|
+
private printSummary(totalMs: number) {
|
|
393
|
+
if (this.timings.length === 0) return
|
|
394
|
+
const width = Math.max(...this.timings.map((t) => t.name.length))
|
|
395
|
+
const lines = [``, bold(`Migration finished in ${formatDuration(totalMs)}`)]
|
|
396
|
+
for (const t of this.timings) {
|
|
397
|
+
const icon = stateColor[t.state](stateIcon[t.state])
|
|
398
|
+
const spent = dim(`(agent ${formatDuration(t.agentMs)}, build ${formatDuration(t.buildMs)})`)
|
|
399
|
+
lines.push(` ${icon} ${t.name.padEnd(width)} ${formatDuration(t.totalMs).padStart(7)} ${spent}`)
|
|
400
|
+
}
|
|
401
|
+
lines.push(dim(` logs: ${this.logsDir}`))
|
|
402
|
+
console.log(lines.join("\n"))
|
|
338
403
|
}
|
|
339
404
|
|
|
340
405
|
private setupInput() {
|
|
@@ -351,19 +416,33 @@ class PipelineTUI {
|
|
|
351
416
|
}
|
|
352
417
|
|
|
353
418
|
private cleanup() {
|
|
419
|
+
if (this.ticker) clearInterval(this.ticker)
|
|
420
|
+
this.ticker = null
|
|
354
421
|
this.write(showCursor())
|
|
355
422
|
if (process.stdin.isTTY) process.stdin.setRawMode(false)
|
|
356
423
|
process.stdin.pause()
|
|
357
424
|
}
|
|
358
425
|
|
|
359
426
|
async run() {
|
|
427
|
+
const startedAll = Date.now()
|
|
360
428
|
this.write(hideCursor())
|
|
361
429
|
this.setupInput()
|
|
362
430
|
this.render()
|
|
363
431
|
|
|
364
432
|
process.stdout.on("resize", () => this.render())
|
|
365
433
|
|
|
366
|
-
for
|
|
434
|
+
// Steps run for minutes at a time, so repaint on a timer to keep the elapsed column moving
|
|
435
|
+
// even while the agent is silent.
|
|
436
|
+
this.ticker = setInterval(() => this.scheduleRender(), 1000)
|
|
437
|
+
this.ticker.unref()
|
|
438
|
+
|
|
439
|
+
// Warm every skill doc up front, in parallel, so no step waits on the network mid-run.
|
|
440
|
+
await prefetchSkillPrompts(
|
|
441
|
+
this.steps.flatMap((s) => s.skills),
|
|
442
|
+
this.ctx.gameDir,
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
for (let i = 0; i < this.steps.length; i++) {
|
|
367
446
|
const ok = await this.runStep(i)
|
|
368
447
|
if (!ok) {
|
|
369
448
|
this.appendLines(["", red("Pipeline stopped due to failure.")])
|
|
@@ -375,6 +454,7 @@ class PipelineTUI {
|
|
|
375
454
|
this.done = true
|
|
376
455
|
this.render()
|
|
377
456
|
this.cleanup()
|
|
457
|
+
this.printSummary(Date.now() - startedAll)
|
|
378
458
|
}
|
|
379
459
|
}
|
|
380
460
|
|
|
@@ -401,9 +481,9 @@ const truncateVisible = (s: string, maxWidth: number): string => {
|
|
|
401
481
|
return s.slice(0, i)
|
|
402
482
|
}
|
|
403
483
|
|
|
404
|
-
export const runPipelineTUI = async (
|
|
405
|
-
const agent = getAgent(
|
|
406
|
-
if (!agent) throw new Error(`Unknown agent: ${
|
|
407
|
-
const tui = new PipelineTUI(agent,
|
|
484
|
+
export const runPipelineTUI = async (ctx: PipelineContext, steps: PipelineStep[]): Promise<void> => {
|
|
485
|
+
const agent = getAgent(ctx.agent)
|
|
486
|
+
if (!agent) throw new Error(`Unknown agent: ${ctx.agent}`)
|
|
487
|
+
const tui = new PipelineTUI(agent, ctx, steps)
|
|
408
488
|
await tui.run()
|
|
409
489
|
}
|