@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,5 +1,5 @@
1
1
  import { runStreamJsonCli } from "./stream-json-cli.js"
2
- import type { Agent, AgentEvent } from "./types.js"
2
+ import type { Agent, AgentEvent, AgentSession } from "./types.js"
3
3
 
4
4
  /**
5
5
  * Claude adapter — wraps the local `claude` CLI in subprocess + stream-json mode
@@ -12,7 +12,19 @@ export const claudeAgent: Agent = {
12
12
  runStreamJsonCli(
13
13
  {
14
14
  cmd: "claude",
15
- buildArgs: (prompt) => ["-p", "--output-format", "stream-json", "--include-partial-messages", "--verbose", prompt],
15
+ buildArgs: (prompt, session) => [
16
+ "-p",
17
+ "--output-format",
18
+ "stream-json",
19
+ "--include-partial-messages",
20
+ "--verbose",
21
+ // Nothing can answer a permission prompt in headless mode, so the default mode
22
+ // silently denies the installs and file writes the migration is made of.
23
+ "--permission-mode",
24
+ "bypassPermissions",
25
+ ...sessionArgs(session),
26
+ prompt,
27
+ ],
16
28
  parseLine: parseClaudeLine,
17
29
  env: (base) => {
18
30
  delete base.CLAUDECODE // claude refuses to start nested otherwise
@@ -23,8 +35,14 @@ export const claudeAgent: Agent = {
23
35
  ),
24
36
  }
25
37
 
26
- /** Map one stream-json line from claude to an AgentEvent (or null to skip). */
27
- export const parseClaudeLine = (line: string): AgentEvent | null => {
38
+ /** Names the session on the first run so later runs can resume it by id. */
39
+ const sessionArgs = (session?: AgentSession): string[] => {
40
+ if (!session) return []
41
+ return session.started ? ["--resume", session.id] : ["--session-id", session.id]
42
+ }
43
+
44
+ /** Map one stream-json line from claude to AgentEvents (or null to skip). */
45
+ export const parseClaudeLine = (line: string): AgentEvent | AgentEvent[] | null => {
28
46
  let obj: any
29
47
  try {
30
48
  obj = JSON.parse(line)
@@ -37,23 +55,24 @@ export const parseClaudeLine = (line: string): AgentEvent | null => {
37
55
  const ev = obj.event
38
56
  if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta") return { type: "text", text: ev.delta.text }
39
57
  if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta") return { type: "thinking", text: ev.delta.thinking ?? "" }
40
- if (ev.type === "content_block_start" && ev.content_block?.type === "tool_use")
41
- return {
42
- type: "tool_use",
43
- name: ev.content_block.name,
44
- summary: summarizeToolInput(ev.content_block.name, ev.content_block.input ?? {}),
45
- }
58
+ // A tool call is announced here with an empty `input` — its arguments only follow as
59
+ // input_json_delta fragments, so the call is reported from the assistant message instead.
46
60
  return null
47
61
  }
48
62
 
49
- // Per-turn full messages — suppress to avoid duplicating the deltas
50
- if (obj.type === "assistant" && obj.message?.content) return null
63
+ // Per-turn messages repeat text we already streamed, but they are the one place a tool
64
+ // call's arguments arrive assembled. A turn can open several tools, hence an array.
65
+ if (obj.type === "assistant" && Array.isArray(obj.message?.content))
66
+ return obj.message.content
67
+ .filter((block: any) => block?.type === "tool_use")
68
+ .map((block: any): AgentEvent => ({ type: "tool_use", name: block.name, summary: summarizeToolInput(block.name, block.input) }))
51
69
 
52
70
  if (obj.type === "user") {
53
71
  const r = obj.tool_use_result
54
72
  if (r?.type === "create") return { type: "tool_result", ok: true, summary: `Created ${r.filePath}` }
55
73
  if (r?.type === "update") return { type: "tool_result", ok: true, summary: `Updated ${r.filePath}` }
56
- return null
74
+ const blocks = Array.isArray(obj.message?.content) ? obj.message.content : []
75
+ return blocks.filter((block: any) => block?.type === "tool_result").map(toolResultEvent)
57
76
  }
58
77
 
59
78
  if (obj.type === "result") {
@@ -66,9 +85,38 @@ export const parseClaudeLine = (line: string): AgentEvent | null => {
66
85
  return null
67
86
  }
68
87
 
88
+ /** What the tool is actually doing, as one line — a bare "Bash" tells the reader nothing. */
69
89
  const summarizeToolInput = (name: string, input: any): string => {
70
- if (name === "Edit" || name === "Write" || name === "Read") return input.file_path ?? ""
71
- if (name === "Bash") return String(input.command ?? "").slice(0, 200)
72
- if (name === "Glob" || name === "Grep") return String(input.pattern ?? "")
90
+ if (!input || typeof input !== "object") return ""
91
+ if (name === "Bash" || name === "BashOutput") return oneLine(input.command ?? input.description)
92
+ if (name === "Edit" || name === "Write" || name === "Read") return oneLine(input.file_path)
93
+ if (name === "NotebookEdit") return oneLine(input.notebook_path)
94
+ if (name === "Glob" || name === "Grep") return oneLine([input.pattern, input.path].filter(Boolean).join(" in "))
95
+ if (name === "WebFetch") return oneLine(input.url)
96
+ if (name === "WebSearch") return oneLine(input.query)
97
+ if (name === "TodoWrite") return oneLine(`${input.todos?.length ?? 0} todos`)
98
+ // Task and any MCP tool: the description is the only human-readable field they share.
99
+ return oneLine(input.description)
100
+ }
101
+
102
+ /** Renders a tool result as one line, so a failed command isn't silent in the output */
103
+ const toolResultEvent = (block: any): AgentEvent => ({
104
+ type: "tool_result",
105
+ ok: block.is_error !== true,
106
+ summary: oneLine(blockText(block.content)),
107
+ })
108
+
109
+ /** Tool results are usually a string, but can be content blocks when a tool returns images */
110
+ const blockText = (content: unknown): string => {
111
+ if (typeof content === "string") return content
112
+ if (Array.isArray(content)) return content.map((part: any) => (typeof part?.text === "string" ? part.text : "")).join(" ")
73
113
  return ""
74
114
  }
115
+
116
+ /** Collapses whitespace and clips, so a heredoc or multi-line output can't break the TUI's rows */
117
+ const oneLine = (value: unknown, max = 160): string => {
118
+ const text = String(value ?? "")
119
+ .replace(/\s+/g, " ")
120
+ .trim()
121
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
122
+ }
@@ -11,7 +11,18 @@ export const codexAgent: Agent = {
11
11
  runStreamJsonCli(
12
12
  {
13
13
  cmd: "codex",
14
- buildArgs: (prompt) => ["exec", "--json", "--skip-git-repo-check", prompt],
14
+ buildArgs: (prompt, session) => [
15
+ "exec",
16
+ ...(session?.started ? ["resume", "--last"] : []),
17
+ "--json",
18
+ "--skip-git-repo-check",
19
+ // exec sandboxes to read-only with no network; the pipeline writes files and installs deps.
20
+ "-c",
21
+ 'sandbox_mode="workspace-write"',
22
+ "-c",
23
+ "sandbox_workspace_write.network_access=true",
24
+ prompt,
25
+ ],
15
26
  parseLine: parseCodexLine,
16
27
  },
17
28
  input,
@@ -12,7 +12,16 @@ export const copilotAgent: Agent = {
12
12
  runStreamJsonCli(
13
13
  {
14
14
  cmd: "copilot",
15
- buildArgs: (prompt) => ["-p", prompt, "--output-format", "json", "--stream", "on", "--allow-all-tools"],
15
+ buildArgs: (prompt, session) => [
16
+ "-p",
17
+ prompt,
18
+ "--output-format",
19
+ "json",
20
+ "--stream",
21
+ "on",
22
+ "--allow-all-tools",
23
+ ...(session?.started ? ["--continue"] : []),
24
+ ],
16
25
  parseLine: parseCopilotLine,
17
26
  },
18
27
  input,
@@ -12,7 +12,15 @@ export const geminiAgent: Agent = {
12
12
  runStreamJsonCli(
13
13
  {
14
14
  cmd: "gemini",
15
- buildArgs: (prompt) => ["-p", prompt, "--output-format", "stream-json"],
15
+ // --yolo auto-approves tool use; headless runs have no one to approve it.
16
+ buildArgs: (prompt, session) => [
17
+ "-p",
18
+ prompt,
19
+ "--output-format",
20
+ "stream-json",
21
+ "--yolo",
22
+ ...(session?.started ? ["--resume", "latest"] : []),
23
+ ],
16
24
  parseLine: parseGeminiLine,
17
25
  },
18
26
  input,
@@ -5,7 +5,7 @@ import { geminiAgent } from "./gemini.js"
5
5
  import { opencodeAgent } from "./opencode.js"
6
6
  import type { Agent } from "./types.js"
7
7
 
8
- export type { Agent, AgentEvent, RunInput } from "./types.js"
8
+ export type { Agent, AgentEvent, AgentSession, RunInput } from "./types.js"
9
9
 
10
10
  export const AGENTS: Record<string, Agent> = {
11
11
  claude: claudeAgent,
@@ -8,14 +8,19 @@ import { parseGeminiLine } from "./gemini.js"
8
8
  import { mapOpencodeEvent } from "./opencode.js"
9
9
  import type { AgentEvent } from "./types.js"
10
10
 
11
- /** Reads a fixture .jsonl, running `parser` over each line and keeping the non-null events. */
12
- const parseFixture = (name: string, parser: (line: string) => AgentEvent | null): AgentEvent[] => {
11
+ type LineParser = (line: string) => AgentEvent | AgentEvent[] | null
12
+
13
+ /** Reads a fixture .jsonl, running `parser` over each line and keeping the events it yields. */
14
+ const parseFixture = (name: string, parser: LineParser): AgentEvent[] => {
13
15
  const raw = fs.readFileSync(new URL(`./__fixtures__/${name}`, import.meta.url), "utf-8")
14
16
  return raw
15
17
  .split("\n")
16
18
  .filter((l) => l.trim())
17
- .map(parser)
18
- .filter((e): e is AgentEvent => e !== null)
19
+ .flatMap((line) => {
20
+ const parsed = parser(line)
21
+ if (!parsed) return []
22
+ return Array.isArray(parsed) ? parsed : [parsed]
23
+ })
19
24
  }
20
25
 
21
26
  describe("parseClaudeLine (real capture)", () => {
@@ -24,11 +29,39 @@ describe("parseClaudeLine (real capture)", () => {
24
29
  { type: "system", text: "Session started" },
25
30
  { type: "text", text: "p" },
26
31
  { type: "text", text: "ong" },
27
- { type: "tool_use", name: "Write", summary: "" },
32
+ { type: "tool_use", name: "Write", summary: "/tmp/game/ping.txt" },
28
33
  { type: "tool_result", ok: true, summary: "Created /tmp/game/ping.txt" },
29
34
  { type: "result", ok: true, costUSD: 0.061597 },
30
35
  ])
31
36
  })
37
+
38
+ // content_block_start announces each tool with an empty `input`, so a summary can only come
39
+ // from the assistant message. Two Bash calls in one turn also exercise the multi-event return.
40
+ it("summarizes bash commands and surfaces failed tools", () => {
41
+ const events = parseFixture("claude-bash.jsonl", parseClaudeLine)
42
+ expect(events.filter((e) => e.type !== "text" && e.type !== "thinking")).toEqual([
43
+ { type: "system", text: "Session started" },
44
+ { type: "tool_use", name: "Bash", summary: "ls -la" },
45
+ { type: "tool_use", name: "Bash", summary: "node --version" },
46
+ { type: "tool_result", ok: true, summary: "(Bash completed with no output)" },
47
+ { type: "tool_result", ok: true, summary: "v24.19.0" },
48
+ { type: "tool_use", name: "Write", summary: "/tmp/game/notes.txt" },
49
+ { type: "tool_result", ok: true, summary: "Created /tmp/game/notes.txt" },
50
+ { type: "tool_use", name: "Bash", summary: "cat /nope/missing.txt" },
51
+ { type: "tool_result", ok: false, summary: "Exit code 1 cat: /nope/missing.txt: No such file or directory" },
52
+ { type: "result", ok: true, costUSD: 0.072234 },
53
+ ])
54
+ })
55
+
56
+ it("keeps multi-line commands and output on one line", () => {
57
+ const toolUse = parseClaudeLine(
58
+ JSON.stringify({
59
+ type: "assistant",
60
+ message: { content: [{ type: "tool_use", name: "Bash", input: { command: "cat <<'EOF' > a.txt\nhello\nEOF" } }] },
61
+ }),
62
+ )
63
+ expect(toolUse).toEqual([{ type: "tool_use", name: "Bash", summary: "cat <<'EOF' > a.txt hello EOF" }])
64
+ })
32
65
  })
33
66
 
34
67
  describe("parseCodexLine", () => {
@@ -92,8 +125,9 @@ describe("mapOpencodeEvent (SSE objects, not JSONL)", () => {
92
125
  // Contract shared by every line-based adapter: parsing never throws, unknown
93
126
  // lines are dropped (not crashed on), and a transcript ends in exactly one result.
94
127
  describe("parser contract", () => {
95
- const cases: [string, string, (line: string) => AgentEvent | null][] = [
128
+ const cases: [string, string, LineParser][] = [
96
129
  ["claude", "claude.jsonl", parseClaudeLine],
130
+ ["claude (bash)", "claude-bash.jsonl", parseClaudeLine],
97
131
  ["codex", "codex.jsonl", parseCodexLine],
98
132
  ["gemini", "gemini.jsonl", parseGeminiLine],
99
133
  ["copilot", "copilot.jsonl", parseCopilotLine],
@@ -1,6 +1,6 @@
1
1
  import { spawn, type ChildProcess } from "node:child_process"
2
2
 
3
- import type { AgentEvent, RunInput } from "./types.js"
3
+ import type { AgentEvent, AgentSession, RunInput } from "./types.js"
4
4
 
5
5
  /**
6
6
  * Shared driver for any CLI that emits NDJSON over stdout when given a prompt
@@ -8,15 +8,16 @@ import type { AgentEvent, RunInput } from "./types.js"
8
8
  */
9
9
  export type StreamJsonCliConfig = {
10
10
  cmd: string
11
- buildArgs: (prompt: string) => string[]
12
- /** Map one parsed JSON line to an AgentEvent (or null to drop). */
13
- parseLine: (line: string) => AgentEvent | null
11
+ /** Build argv for a run. `session` is set when the caller wants this run to continue an earlier one. */
12
+ buildArgs: (prompt: string, session?: AgentSession) => string[]
13
+ /** Map one parsed JSON line to an AgentEvent, several (a turn can start multiple tools), or null to drop. */
14
+ parseLine: (line: string) => AgentEvent | AgentEvent[] | null
14
15
  /** Optional env mutator. Receives a copy of process.env. */
15
16
  env?: (base: NodeJS.ProcessEnv) => NodeJS.ProcessEnv
16
17
  }
17
18
 
18
19
  export const runStreamJsonCli = async function* (config: StreamJsonCliConfig, input: RunInput): AsyncIterable<AgentEvent> {
19
- const args = config.buildArgs(input.prompt)
20
+ const args = config.buildArgs(input.prompt, input.session)
20
21
  const env = config.env ? config.env({ ...process.env }) : { ...process.env }
21
22
 
22
23
  let proc: ChildProcess
@@ -40,17 +41,34 @@ export const runStreamJsonCli = async function* (config: StreamJsonCliConfig, in
40
41
  let buf = ""
41
42
  let sawResult = false
42
43
 
44
+ let idleTimer: NodeJS.Timeout | null = null
45
+ let idleFired = false
46
+
47
+ // Agents can think for minutes at a time, so cap silence rather than total runtime:
48
+ // a wedged run dies quickly while a productive long one is left alone.
49
+ const armIdleTimer = () => {
50
+ if (!input.idleTimeoutMs || idleFired || done) return
51
+ if (idleTimer) clearTimeout(idleTimer)
52
+ idleTimer = setTimeout(() => {
53
+ idleFired = true
54
+ push({ type: "error", message: `No output for ${Math.round(input.idleTimeoutMs! / 1000)}s, stopping the agent` })
55
+ proc.kill()
56
+ }, input.idleTimeoutMs)
57
+ }
58
+
43
59
  const push = (e: AgentEvent) => {
44
60
  if (e.type === "result") sawResult = true
45
61
  queue.push(e)
62
+ armIdleTimer()
46
63
  resolveWaiting?.()
47
64
  resolveWaiting = null
48
65
  }
49
66
 
50
67
  const flushLine = (line: string) => {
51
68
  if (!line.trim()) return
52
- const event = config.parseLine(line)
53
- if (event) push(event)
69
+ const parsed = config.parseLine(line)
70
+ if (!parsed) return
71
+ for (const event of Array.isArray(parsed) ? parsed : [parsed]) push(event)
54
72
  }
55
73
 
56
74
  proc.stdout?.on("data", (chunk: Buffer) => {
@@ -60,15 +78,18 @@ export const runStreamJsonCli = async function* (config: StreamJsonCliConfig, in
60
78
  for (const line of lines) flushLine(line)
61
79
  })
62
80
 
81
+ // Warnings on stderr are noise, not failure — a run is judged by its result event
82
+ // and exit code, so a deprecation notice can't trigger a spurious retry.
63
83
  proc.stderr?.on("data", (chunk: Buffer) => {
64
84
  const text = chunk.toString("utf8").trim()
65
- if (text) push({ type: "error", message: text })
85
+ if (text) push({ type: "system", text })
66
86
  })
67
87
 
68
88
  proc.on("close", (code) => {
69
89
  if (buf.trim()) flushLine(buf)
70
90
  if (code !== 0 && !sawResult) push({ type: "result", ok: false })
71
91
  done = true
92
+ if (idleTimer) clearTimeout(idleTimer)
72
93
  resolveWaiting?.()
73
94
  resolveWaiting = null
74
95
  })
@@ -76,10 +97,13 @@ export const runStreamJsonCli = async function* (config: StreamJsonCliConfig, in
76
97
  proc.on("error", (err) => {
77
98
  push({ type: "error", message: err.message })
78
99
  done = true
100
+ if (idleTimer) clearTimeout(idleTimer)
79
101
  resolveWaiting?.()
80
102
  resolveWaiting = null
81
103
  })
82
104
 
105
+ armIdleTimer()
106
+
83
107
  while (true) {
84
108
  if (queue.length > 0) yield queue.shift()!
85
109
  else if (done) return
@@ -11,10 +11,26 @@ export type AgentEvent =
11
11
  | { type: "result"; ok: boolean; costUSD?: number }
12
12
  | { type: "error"; message: string }
13
13
 
14
+ /**
15
+ * A conversation carried across several agent invocations. Reusing one keeps the
16
+ * agent's knowledge of the project (and its prompt cache) between pipeline steps
17
+ * instead of paying for a cold re-read of the codebase every time.
18
+ */
19
+ export type AgentSession = {
20
+ /** Stable id, for CLIs that let us name the session up front */
21
+ id: string
22
+ /** Set once a run has established the session; later runs resume rather than start cold */
23
+ started: boolean
24
+ }
25
+
14
26
  export type RunInput = {
15
27
  prompt: string
16
28
  cwd?: string
17
29
  signal?: AbortSignal
30
+ /** Continue this conversation instead of starting a fresh one, where the agent supports it */
31
+ session?: AgentSession
32
+ /** Abort the run when the agent has produced no output for this long */
33
+ idleTimeoutMs?: number
18
34
  }
19
35
 
20
36
  export interface Agent {
@@ -7,9 +7,12 @@ import * as p from "@clack/prompts"
7
7
  import { agentNames } from "../../agents/index.js"
8
8
  import { detectAgent } from "../../wizard/agent-detect.js"
9
9
  import { downloadPage } from "../../download/page-downloader.js"
10
- import { runCommand, gitCommit, isGitInstalled } from "../../util/exec.js"
11
- import { runSkillsPipelineTUI, runAgentWithBuildLoop, runSelectedSkills } from "../../skills/runner.js"
12
- import { optionalPromptSkills, type SkillDefinition } from "../../skills/registry.js"
10
+ import { runCommand, gitCommit, isGitInstalled, resolveBuildCommand, type PackageManagerName } from "../../util/exec.js"
11
+ import { runAgentWithBuildLoop, runSelectedSkills } from "../../skills/runner.js"
12
+ import { runPipelineTUI } from "../../tui/pipeline.js"
13
+ import { newSession, type PipelineContext } from "../../skills/step.js"
14
+ import { importPipeline, optionalPromptSkills, type SkillDefinition } from "../../skills/registry.js"
15
+ import { seedImportedGame, importedSourceDir, referenceDir } from "./seedImport.js"
13
16
  import { login } from "../login.js"
14
17
  import { getDefaultToken } from "../../util/config.js"
15
18
  import { slugify } from "../../util/slugify.js"
@@ -237,10 +240,11 @@ const buildRepoContext = (repo: RepoContext, repoType: RepoType): string => {
237
240
  type PromptStrategyArgs = {
238
241
  userPrompt: string
239
242
  displayName: string
243
+ buildCmd: string
240
244
  }
241
245
 
242
246
  /** Composes the prompt sent to the agent for the "from prompt" strategy */
243
- const buildPromptStrategyMessage = ({ userPrompt, displayName }: PromptStrategyArgs): string =>
247
+ const buildPromptStrategyMessage = ({ userPrompt, displayName, buildCmd }: PromptStrategyArgs): string =>
244
248
  `You are scaffolding a Puzzmo game called "${displayName}" in the current directory.
245
249
  The starter is a working Vite + Puzzmo SDK Minesweeper. Replace the gameplay with the game described below.
246
250
 
@@ -251,7 +255,7 @@ Constraints:
251
255
  - Keep puzzmo.json valid (do not remove the slug or displayName fields).
252
256
  - Use the Puzzmo SDK lifecycle: gameReady → gameLoaded → on("start"|"retry") → updateGameState → gameCompleted.
253
257
  - Replace fixtures in fixtures/puzzles/ with puzzles for the new game.
254
- - Keep the build green (\`npx vite build\` should succeed).`
258
+ - Keep the build green (\`${buildCmd}\` should succeed).`
255
259
 
256
260
  /** Main game create wizard */
257
261
  export const gameCreate = async (opts: CreateOptions) => {
@@ -348,15 +352,23 @@ export const gameCreate = async (opts: CreateOptions) => {
348
352
 
349
353
  const slug = opts.slug ?? slugify(name)
350
354
 
351
- // Materialize template content for blank/prompt strategies (after we know the slug/name)
352
- if (strategy !== "import") {
353
- const templateDir = resolveTemplateDir("minesweeper")
354
- if (!fs.existsSync(templateDir)) {
355
- p.log.error(`Bundled template not found at ${templateDir}`)
356
- process.exit(1)
357
- }
358
- copyTemplate(templateDir, tmpDir, { __SLUG__: slug, __DISPLAY_NAME__: name, __TEAM_ID__: opts.teamID ?? "REPLACE_ME" })
355
+ // Materialize the starter (after we know the slug/name). Imports get it too — porting a
356
+ // downloaded game into a project that already builds beats rebuilding the project by hand.
357
+ const templateDir = resolveTemplateDir("minesweeper")
358
+ if (!fs.existsSync(templateDir)) {
359
+ p.log.error(`Bundled template not found at ${templateDir}`)
360
+ process.exit(1)
361
+ }
362
+ const replacements = {
363
+ __SLUG__: slug,
364
+ __DISPLAY_NAME__: name,
365
+ __TEAM_ID__: opts.teamID ?? "REPLACE_ME",
366
+ // Prettier rewrites __DISPLAY_NAME__ to bold syntax in markdown, so match that form too.
367
+ "**DISPLAY_NAME**": name,
359
368
  }
369
+ const materialize = (from: string, to: string) => copyTemplate(from, to, replacements)
370
+ if (strategy === "import") seedImportedGame(tmpDir, templateDir, materialize)
371
+ else materialize(templateDir, tmpDir)
360
372
 
361
373
  // Step 5: Login if token provided
362
374
  if (opts.accessToken) {
@@ -410,24 +422,38 @@ export const gameCreate = async (opts: CreateOptions) => {
410
422
  }
411
423
 
412
424
  // Step 7: Strategy-specific agent work
425
+ const pm = packageManagerFrom(opts.pm, repo.packageManager)
426
+ const buildCmd = resolveBuildCommand(gameDir, pm)
427
+ // One context per run: the agent keeps the same conversation across every step.
428
+ const contextFor = (agent: string): PipelineContext => ({
429
+ agent,
430
+ gameDir,
431
+ repoContext: buildRepoContext(repo, repoType),
432
+ buildCmd,
433
+ session: newSession(),
434
+ })
435
+
413
436
  if (strategy === "import") {
414
437
  const selectedAgent = await pickAgent(opts.agent)
415
438
  if (selectedAgent !== "none") {
416
439
  p.log.step("Running Puzzmo migration pipeline...")
417
- await runSkillsPipelineTUI(selectedAgent, gameDir, buildRepoContext(repo, repoType))
440
+ await runPipelineTUI(contextFor(selectedAgent), importPipeline)
441
+ } else {
442
+ p.log.info(`The downloaded game is in ${importedSourceDir}/, and a reference game is in ${referenceDir}/.`)
418
443
  }
419
444
  } else if (strategy === "prompt") {
420
445
  const selectedAgent = await pickAgent(opts.agent)
421
- const message = buildPromptStrategyMessage({ userPrompt: userPrompt!, displayName: name })
446
+ const message = buildPromptStrategyMessage({ userPrompt: userPrompt!, displayName: name, buildCmd })
422
447
  if (selectedAgent === "none") {
423
448
  p.log.warn("No agent selected; skipping LLM customization.")
424
449
  p.note(message, "Paste this prompt into your LLM agent:")
425
450
  } else {
426
451
  // Ask which optional extras to apply up front, then run everything unattended
427
452
  const extras = await pickOptionalSkills()
453
+ const ctx = contextFor(selectedAgent)
428
454
 
429
455
  p.log.step("Running agent with your prompt...")
430
- const result = await runAgentWithBuildLoop(selectedAgent, message, gameDir, "from-prompt")
456
+ const result = await runAgentWithBuildLoop(ctx, message, "from-prompt")
431
457
  if (!result.ok) {
432
458
  p.log.warn(`Agent step did not complete cleanly: ${result.reason}. The Minesweeper starter is still in place.`)
433
459
  if (result.buildError) p.note(result.buildError.trimEnd().split("\n").slice(-40).join("\n"), "Last build error")
@@ -436,7 +462,7 @@ export const gameCreate = async (opts: CreateOptions) => {
436
462
 
437
463
  if (extras.length > 0) {
438
464
  p.log.step(`Applying optional skills: ${extras.map((s) => s.name).join(", ")}`)
439
- await runSelectedSkills(selectedAgent, gameDir, buildRepoContext(repo, repoType), extras)
465
+ await runSelectedSkills(ctx, extras)
440
466
  }
441
467
  }
442
468
  }
@@ -446,7 +472,6 @@ export const gameCreate = async (opts: CreateOptions) => {
446
472
  writeSchemaHint(gameDir, effectiveRepoRoot)
447
473
 
448
474
  // Done
449
- const pm = opts.pm || repo.packageManager
450
475
  const runCmd = pm === "npm" ? "npx" : pm === "yarn" ? "yarn dlx" : "pnpm dlx"
451
476
  const relativePath = path.relative(process.cwd(), gameDir)
452
477
 
@@ -457,3 +482,7 @@ export const gameCreate = async (opts: CreateOptions) => {
457
482
 
458
483
  p.outro(`Done! Your game is in ./${relativePath}/`)
459
484
  }
485
+
486
+ /** `--pm` arrives as a plain string; anything unexpected falls back to the repo's own manager */
487
+ const packageManagerFrom = (value: string | undefined, fallback: PackageManagerName): PackageManagerName =>
488
+ value === "npm" || value === "yarn" || value === "pnpm" ? value : fallback
@@ -0,0 +1,30 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+
4
+ /** Where the downloaded page is parked while the agent ports it */
5
+ export const importedSourceDir = "original"
6
+
7
+ /** Where an untouched copy of the starter lives, for the agent to read but not edit */
8
+ export const referenceDir = path.join(".puzzmo", "reference")
9
+
10
+ /**
11
+ * Turns a freshly downloaded page into a working Puzzmo project.
12
+ *
13
+ * The download moves to `original/`, the starter is unpacked over the top as the shell to port
14
+ * into, and a pristine copy is left in `.puzzmo/reference/`. This means the migration begins
15
+ * from a project that already builds and is already wired to the SDK, instead of asking an
16
+ * agent to reconstruct the whole layout a step at a time.
17
+ */
18
+ export const seedImportedGame = (
19
+ gameDir: string,
20
+ templateDir: string,
21
+ copyTemplate: (sourceDir: string, targetDir: string) => void,
22
+ ): void => {
23
+ const downloaded = path.join(gameDir, "src")
24
+ const target = path.join(gameDir, importedSourceDir)
25
+ if (fs.existsSync(target)) fs.rmSync(target, { recursive: true })
26
+ if (fs.existsSync(downloaded)) fs.renameSync(downloaded, target)
27
+
28
+ copyTemplate(templateDir, gameDir)
29
+ copyTemplate(templateDir, path.join(gameDir, referenceDir))
30
+ }
@@ -17,6 +17,7 @@ import {
17
17
  import { createUserGame } from "../util/createGame.js"
18
18
  import { discoverGames, type DiscoveredGame } from "../util/discoverGames.js"
19
19
  import { lintPuzzmoFile } from "../util/lintPuzzmoFile.js"
20
+ import { mascotSmall, pickMascot } from "../util/mascot.js"
20
21
  import { slugify } from "../util/slugify.js"
21
22
 
22
23
  type UploadOptions = {
@@ -235,29 +236,14 @@ const plural = (n: number, singular: string, pluralForm?: string): string => `${
235
236
  const isDefaultServer = (source: string): boolean => normalizeSource(source) === normalizeSource(defaultSource)
236
237
 
237
238
  const yellow = (s: string): string => (process.stdout.isTTY ? `\x1b[33m${s}\x1b[0m` : s)
238
- const blackOnYellow = (s: string): string => (process.stdout.isTTY ? `\x1b[30;43m${s}\x1b[0m` : s)
239
239
 
240
- const puzzmonautLines = [
241
- ` ${yellow("▟████▙")}`,
242
- ` ${yellow("██")}${blackOnYellow("▝ ▘ ")} ${yellow("██")}`,
243
- `${yellow(" ██")}${blackOnYellow(" ▄▖")}${yellow("██")}`,
244
- ` ${yellow("▝▀▀▀▀▘")}`,
245
- ]
246
-
247
- // oxlint-disable-next-line no-control-regex
248
- const visualWidth = (s: string): number => s.replace(/\u001b\[[0-9;]*m/g, "").length
249
-
250
- /** Renders the puzzmonaut with message lines vertically centered to its right. */
240
+ /** Renders the puzzmonaut with message lines vertically centered to its right, or bare text in a log. */
251
241
  const puzzmonautSays = (messages: string[]): string => {
252
- const iconWidth = Math.max(...puzzmonautLines.map(visualWidth))
253
- const startRow = Math.max(0, Math.floor((puzzmonautLines.length - messages.length) / 2))
254
- return puzzmonautLines
255
- .map((line, i) => {
256
- const pad = " ".repeat(iconWidth - visualWidth(line))
257
- const msg = messages[i - startRow] ?? ""
258
- return `${line}${pad} ${msg}`.trimEnd()
259
- })
260
- .join("\n")
242
+ const mascot = pickMascot(mascotSmall)
243
+ if (!mascot) return messages.join("\n")
244
+ const startRow = Math.max(0, Math.floor((mascot.height - messages.length) / 2))
245
+ // Every art row is exactly mascot.width columns, so the text aligns without padding.
246
+ return mascot.lines.map((line, i) => `${line} ${messages[i - startRow] ?? ""}`.trimEnd()).join("\n")
261
247
  }
262
248
 
263
249
  /** Collects all files in a directory recursively */
@@ -126,10 +126,10 @@ export const downloadPage = async (url: string, outputDir: string): Promise<{ ti
126
126
  // Find referenced assets (src, href, url())
127
127
  const assetRefs = extractAssetRefs(html)
128
128
 
129
- for (const ref of assetRefs) {
130
- const ok = await downloadAsset(ref, baseURL, srcDir, downloaded, assetContent, false)
131
- if (ok) html = html.replaceAll(ref, new URL(ref, baseURL).pathname.replace(/^\//, ""))
132
- }
129
+ const fetched = await mapWithConcurrency(assetRefs, (ref) => downloadAsset(ref, baseURL, srcDir, downloaded, assetContent, false))
130
+ assetRefs.forEach((ref, i) => {
131
+ if (fetched[i]) html = html.replaceAll(ref, new URL(ref, baseURL).pathname.replace(/^\//, ""))
132
+ })
133
133
 
134
134
  // Second pass: scan downloaded JS/CSS files for string literals referencing
135
135
  // paths with known asset extensions (images, fonts, audio, video).
@@ -143,9 +143,7 @@ export const downloadPage = async (url: string, outputDir: string): Promise<{ ti
143
143
 
144
144
  if (jsAssetRefs.size > 0) {
145
145
  console.log(` Found ${jsAssetRefs.size} additional asset reference${jsAssetRefs.size === 1 ? "" : "s"} in JS/CSS files`)
146
- for (const ref of jsAssetRefs) {
147
- await downloadAsset(ref, baseURL, srcDir, downloaded, assetContent, true)
148
- }
146
+ await mapWithConcurrency([...jsAssetRefs], (ref) => downloadAsset(ref, baseURL, srcDir, downloaded, assetContent, true))
149
147
  }
150
148
 
151
149
  // Write the HTML file
@@ -156,6 +154,23 @@ export const downloadPage = async (url: string, outputDir: string): Promise<{ ti
156
154
  return { title: extractTitle(html) }
157
155
  }
158
156
 
157
+ /** How many assets to fetch at once — a page's assets are otherwise one round trip each */
158
+ const downloadConcurrency = 8
159
+
160
+ /** Runs `task` over every item with a bounded number in flight, preserving input order in the results */
161
+ const mapWithConcurrency = async <T, R>(items: T[], task: (item: T) => Promise<R>): Promise<R[]> => {
162
+ const results = new Array<R>(items.length)
163
+ let next = 0
164
+ const worker = async () => {
165
+ while (next < items.length) {
166
+ const index = next++
167
+ results[index] = await task(items[index])
168
+ }
169
+ }
170
+ await Promise.all(Array.from({ length: Math.min(downloadConcurrency, items.length) }, worker))
171
+ return results
172
+ }
173
+
159
174
  /** Extracts asset references from HTML using regex */
160
175
  const extractAssetRefs = (html: string): string[] => {
161
176
  const refs: string[] = []