@puzzmo/cli 1.0.57 → 1.0.59

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 (40) hide show
  1. package/lib/agents/claude.d.ts +3 -1
  2. package/lib/agents/claude.js +1 -1
  3. package/lib/agents/claude.js.map +1 -1
  4. package/lib/agents/codex.d.ts +6 -1
  5. package/lib/agents/codex.js +1 -1
  6. package/lib/agents/codex.js.map +1 -1
  7. package/lib/agents/copilot.d.ts +6 -1
  8. package/lib/agents/copilot.js +1 -1
  9. package/lib/agents/copilot.js.map +1 -1
  10. package/lib/agents/gemini.d.ts +7 -1
  11. package/lib/agents/gemini.js +1 -1
  12. package/lib/agents/gemini.js.map +1 -1
  13. package/lib/agents/opencode.d.ts +2 -1
  14. package/lib/agents/opencode.js +1 -1
  15. package/lib/agents/opencode.js.map +1 -1
  16. package/lib/commands/game/create.js +48 -27
  17. package/lib/commands/game/create.js.map +1 -1
  18. package/lib/skills/registry.d.ts +4 -0
  19. package/lib/skills/registry.js +6 -0
  20. package/lib/skills/registry.js.map +1 -1
  21. package/lib/skills/runner.d.ts +4 -1
  22. package/lib/skills/runner.js +102 -27
  23. package/lib/skills/runner.js.map +1 -1
  24. package/package.json +3 -2
  25. package/src/agents/__fixtures__/README.md +33 -0
  26. package/src/agents/__fixtures__/claude.jsonl +12 -0
  27. package/src/agents/__fixtures__/codex.jsonl +8 -0
  28. package/src/agents/__fixtures__/copilot.jsonl +6 -0
  29. package/src/agents/__fixtures__/gemini.jsonl +6 -0
  30. package/src/agents/claude.ts +1 -1
  31. package/src/agents/codex.ts +1 -1
  32. package/src/agents/copilot.ts +1 -1
  33. package/src/agents/gemini.ts +1 -1
  34. package/src/agents/opencode.ts +1 -1
  35. package/src/agents/parse-line.test.ts +113 -0
  36. package/src/commands/game/create.ts +57 -31
  37. package/src/skills/registry.ts +9 -0
  38. package/src/skills/runner.ts +107 -30
  39. package/tsconfig.json +1 -1
  40. package/vitest.config.mts +7 -0
@@ -1,29 +1,65 @@
1
- import { spawnSync } from "node:child_process";
1
+ import { getAgent } from "../agents/index.js";
2
2
  import { skillsPipeline } from "./registry.js";
3
3
  import { verifyBuild, runCommand, gitCommit } from "../util/exec.js";
4
4
  import { fetchSkillPrompt } from "./mcp-client.js";
5
5
  import { runPipelineTUI } from "../tui/pipeline.js";
6
+ const agentTimeoutMs = 300000; // 5 minute timeout per agent invocation
6
7
  /** Fetches step instructions from the MCP server and wraps them as an agent prompt */
7
8
  const buildPrompt = async (stepName, gameDir, repoContext) => {
8
9
  const instructions = await fetchSkillPrompt(stepName, gameDir);
9
10
  return `Follow these instructions. The game source is in the current directory.\n\n${repoContext}\n\n${instructions}`;
10
11
  };
11
- /** Invokes an LLM agent with a prompt (plain mode, stdio inherited) */
12
- const invokeAgent = (agent, prompt, cwd) => {
13
- const env = { ...process.env };
14
- delete env.CLAUDECODE;
15
- const result = spawnSync(agent, [prompt], {
16
- cwd,
17
- env,
18
- stdio: ["inherit", "pipe", "pipe"],
19
- encoding: "utf-8",
20
- timeout: 300000, // 5 minute timeout per skill
21
- });
22
- const output = (result.stdout ?? "") + (result.stderr ?? "");
23
- return {
24
- success: result.status === 0,
25
- output,
12
+ /** Invokes an LLM agent with a prompt, streaming its text and tool activity to the console */
13
+ const invokeAgent = async (agentName, prompt, cwd) => {
14
+ const agent = getAgent(agentName);
15
+ if (!agent) {
16
+ console.error(` Unknown agent: ${agentName}`);
17
+ return false;
18
+ }
19
+ let resultOk = null;
20
+ let sawError = false;
21
+ let midLine = false;
22
+ // Text arrives as token deltas; track whether we are mid-line so discrete
23
+ // events (tool calls, results) always start on a fresh line.
24
+ const endLine = () => {
25
+ if (!midLine)
26
+ return;
27
+ process.stdout.write("\n");
28
+ midLine = false;
29
+ };
30
+ const printLine = (line) => {
31
+ endLine();
32
+ console.log(line);
26
33
  };
34
+ try {
35
+ for await (const event of agent.run({ prompt, cwd, signal: AbortSignal.timeout(agentTimeoutMs) })) {
36
+ if (event.type === "text") {
37
+ process.stdout.write(dim(event.text));
38
+ midLine = !event.text.endsWith("\n");
39
+ }
40
+ else if (event.type === "tool_result") {
41
+ printLine(` ${event.ok ? green("✓") : red("✗")} ${dim(event.summary)}`);
42
+ }
43
+ else if (event.type === "system") {
44
+ printLine(` ${dim(event.text)}`);
45
+ }
46
+ else if (event.type === "result") {
47
+ resultOk = event.ok;
48
+ const cost = event.costUSD != null ? ` ($${event.costUSD.toFixed(4)})` : "";
49
+ printLine((event.ok ? green : red)(` Agent finished${cost}`));
50
+ }
51
+ else if (event.type === "error") {
52
+ sawError = true;
53
+ printLine(red(` ${event.message}`));
54
+ }
55
+ }
56
+ }
57
+ catch (e) {
58
+ printLine(red(` Agent error: ${e?.message ?? e}`));
59
+ return false;
60
+ }
61
+ endLine();
62
+ return resultOk ?? !sawError;
27
63
  };
28
64
  /** Runs the skills pipeline with plain console output (no TUI) */
29
65
  export const runSkillsPipeline = async (agent, gameDir, repoContext) => {
@@ -33,11 +69,11 @@ export const runSkillsPipeline = async (agent, gameDir, repoContext) => {
33
69
  const step = i + 1;
34
70
  console.log(`[${step}/${total}] Running step: ${skill.name}`);
35
71
  const prompt = await buildPrompt(skill.name, gameDir, repoContext);
36
- let result = invokeAgent(agent, prompt, gameDir);
37
- if (!result.success) {
72
+ let success = await invokeAgent(agent, prompt, gameDir);
73
+ if (!success) {
38
74
  console.log(` Agent failed, retrying...`);
39
- result = invokeAgent(agent, prompt, gameDir);
40
- if (!result.success) {
75
+ success = await invokeAgent(agent, prompt, gameDir);
76
+ if (!success) {
41
77
  console.error(` Step ${skill.name} failed after retry. Stopping pipeline.`);
42
78
  process.exit(1);
43
79
  }
@@ -47,7 +83,7 @@ export const runSkillsPipeline = async (agent, gameDir, repoContext) => {
47
83
  if (!buildResult.success) {
48
84
  console.log(` Build failed after ${skill.name}, asking agent to fix...`);
49
85
  const fixPrompt = `The vite build failed after the "${skill.name}" step. Fix the build errors:\n\n${buildResult.error}`;
50
- invokeAgent(agent, fixPrompt, gameDir);
86
+ await invokeAgent(agent, fixPrompt, gameDir);
51
87
  const retryBuild = verifyBuild(gameDir);
52
88
  if (!retryBuild.success) {
53
89
  console.error(` Build still failing after fix attempt. Stopping.`);
@@ -70,14 +106,47 @@ export const runSkillsPipeline = async (agent, gameDir, repoContext) => {
70
106
  export const runSkillsPipelineTUI = async (agent, gameDir, repoContext) => {
71
107
  await runPipelineTUI(agent, gameDir, repoContext);
72
108
  };
109
+ /** Runs a chosen subset of skills (the optional add-ons after the prompt flow); warns but never exits on failure */
110
+ export const runSelectedSkills = async (agent, gameDir, repoContext, skills) => {
111
+ const total = skills.length;
112
+ for (let i = 0; i < total; i++) {
113
+ const skill = skills[i];
114
+ console.log(`[${i + 1}/${total}] Running step: ${skill.name}`);
115
+ const prompt = await buildPrompt(skill.name, gameDir, repoContext);
116
+ let success = await invokeAgent(agent, prompt, gameDir);
117
+ if (!success) {
118
+ console.log(` Agent failed, retrying...`);
119
+ success = await invokeAgent(agent, prompt, gameDir);
120
+ }
121
+ if (!success) {
122
+ console.error(` Step ${skill.name} did not complete cleanly, skipping.`);
123
+ continue;
124
+ }
125
+ // Verify build; ask the agent to fix but keep going regardless
126
+ const buildResult = verifyBuild(gameDir);
127
+ if (!buildResult.success) {
128
+ console.log(` Build failed after ${skill.name}, asking agent to fix...`);
129
+ const fixPrompt = `The vite build failed after the "${skill.name}" step. Fix the build errors:\n\n${buildResult.error}`;
130
+ await invokeAgent(agent, fixPrompt, gameDir);
131
+ }
132
+ try {
133
+ runCommand("git add -A", { cwd: gameDir });
134
+ gitCommit(`step: ${skill.name}`, { cwd: gameDir });
135
+ console.log(` Committed.`);
136
+ }
137
+ catch {
138
+ console.log(` No changes to commit.`);
139
+ }
140
+ }
141
+ };
73
142
  /** Runs a single agent invocation, verifies the build, and commits. Used by one-shot prompt-driven flows. */
74
- export const runAgentWithBuildLoop = (agent, prompt, gameDir, label) => {
143
+ export const runAgentWithBuildLoop = async (agent, prompt, gameDir, label) => {
75
144
  console.log(`Running agent: ${label}`);
76
- let result = invokeAgent(agent, prompt, gameDir);
77
- if (!result.success) {
145
+ let success = await invokeAgent(agent, prompt, gameDir);
146
+ if (!success) {
78
147
  console.log(` Agent failed, retrying...`);
79
- result = invokeAgent(agent, prompt, gameDir);
80
- if (!result.success) {
148
+ success = await invokeAgent(agent, prompt, gameDir);
149
+ if (!success) {
81
150
  console.error(` Agent failed after retry. Stopping.`);
82
151
  return false;
83
152
  }
@@ -86,7 +155,7 @@ export const runAgentWithBuildLoop = (agent, prompt, gameDir, label) => {
86
155
  if (!buildResult.success) {
87
156
  console.log(` Build failed, asking agent to fix...`);
88
157
  const fixPrompt = `The vite build failed after the "${label}" step. Fix the build errors:\n\n${buildResult.error}`;
89
- invokeAgent(agent, fixPrompt, gameDir);
158
+ await invokeAgent(agent, fixPrompt, gameDir);
90
159
  const retry = verifyBuild(gameDir);
91
160
  if (!retry.success) {
92
161
  console.error(` Build still failing after fix attempt.`);
@@ -103,4 +172,10 @@ export const runAgentWithBuildLoop = (agent, prompt, gameDir, label) => {
103
172
  }
104
173
  return true;
105
174
  };
175
+ /** Wraps a string in ANSI dim codes */
176
+ const dim = (s) => `\x1b[2m${s}\x1b[0m`;
177
+ /** Wraps a string in ANSI green codes */
178
+ const green = (s) => `\x1b[32m${s}\x1b[0m`;
179
+ /** Wraps a string in ANSI red codes */
180
+ const red = (s) => `\x1b[31m${s}\x1b[0m`;
106
181
  //# sourceMappingURL=runner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/skills/runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAE9C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAC9C,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAClD,OAAO,E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CAAC,CAAA;QAC5C,MAAM,KAAK,GAAG,WAAW,CAAC,OAAO,CAAC,CAAA;QAClC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;YACnB,OAAO,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAA;YACzD,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;IAED,IAAI,CAAC;QACH,UAAU,CAAC,YAAY,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAA;QAC1C,SAAS,CAAC,SAAS,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAA;QAC7C,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAA;IAC7B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAA;IACxC,CAAC;IACD,OAAO,IAAI,CAAA;AAAA,CACZ,CAAA;AAED,uCAAuC;AACvC,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,UAAU,CAAC,SAAS,CAAA;AAC/C,yCAAyC;AACzC,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,WAAW,CAAC,SAAS,CAAA;AAClD,uCAAuC;AACvC,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,WAAW,CAAC,SAAS,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@puzzmo/cli",
3
- "version": "1.0.57",
3
+ "version": "1.0.59",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "puzzmo": "./lib/index.js"
@@ -18,7 +18,8 @@
18
18
  },
19
19
  "scripts": {
20
20
  "build": "tsgo",
21
- "type-check": "tsgo --noEmit"
21
+ "type-check": "tsgo --noEmit",
22
+ "test": "vitest run"
22
23
  },
23
24
  "dependencies": {
24
25
  "@cfworker/json-schema": "^4.1.1",
@@ -0,0 +1,33 @@
1
+ # Agent output fixtures
2
+
3
+ Captured/derived samples of each CLI's headless event stream, used by
4
+ `parse-line.test.ts` to lock down the `parseLine` mappers without needing the
5
+ CLIs installed. Provenance matters — only `claude` is a first-party capture;
6
+ the rest are transcribed from public docs/schemas and should be re-captured
7
+ against a real run when someone has that subscription.
8
+
9
+ | Fixture | Source | Trust |
10
+ | --- | --- | --- |
11
+ | `claude.jsonl` | Real capture: `claude -p --output-format stream-json --include-partial-messages --verbose` (2026-07-18). IDs/paths trimmed; event shapes verbatim. | High — real |
12
+ | `codex.jsonl` | Transcribed from the `codex exec --json` event cheatsheet (takopi.dev) matching `@openai/codex-sdk`'s `ThreadEvent` union. | Medium — docs |
13
+ | `gemini.jsonl` | Transcribed from the `gemini --output-format stream-json` cheatsheet (littlebearapps.com) / `@google/gemini-cli-core` `JsonStreamEvent`. | Medium — docs |
14
+ | `copilot.jsonl` | Transcribed from GitHub's Copilot SDK "Streaming events" docs (session-events schema). | Medium — docs |
15
+
16
+ ## Re-capturing a real transcript
17
+
18
+ ```sh
19
+ # claude (already captured)
20
+ claude -p --output-format stream-json --include-partial-messages --verbose "…" > claude.jsonl
21
+
22
+ # codex
23
+ codex exec --json --skip-git-repo-check "…" > codex.jsonl
24
+
25
+ # gemini
26
+ gemini -p "…" --output-format stream-json > gemini.jsonl
27
+
28
+ # copilot
29
+ copilot -p "…" --output-format json --stream on --allow-all-tools > copilot.jsonl
30
+ ```
31
+
32
+ opencode is not line-based (it streams SSE objects via `@opencode-ai/sdk`), so its
33
+ mapper `mapOpencodeEvent` is tested with inline object fixtures in the test file.
@@ -0,0 +1,12 @@
1
+ {"type":"system","subtype":"init","cwd":"/tmp/game","session_id":"d90bdbde","tools":["Write","Bash"],"model":"claude-opus-4-8","permissionMode":"bypassPermissions","apiKeySource":"none"}
2
+ {"type":"system","subtype":"status","status":"requesting","session_id":"d90bdbde"}
3
+ {"type":"stream_event","event":{"type":"message_start","message":{"role":"assistant","content":[]}},"session_id":"d90bdbde"}
4
+ {"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}},"session_id":"d90bdbde"}
5
+ {"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"p"}},"session_id":"d90bdbde"}
6
+ {"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ong"}},"session_id":"d90bdbde"}
7
+ {"type":"stream_event","event":{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01SAm7","name":"Write","input":{},"caller":{"type":"direct"}}},"session_id":"d90bdbde"}
8
+ {"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01SAm7","name":"Write","input":{"file_path":"/tmp/game/ping.txt","content":"pong"}}]},"session_id":"d90bdbde"}
9
+ {"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01SAm7","type":"tool_result","content":"File created successfully at: /tmp/game/ping.txt"}]},"session_id":"d90bdbde","tool_use_result":{"type":"create","filePath":"/tmp/game/ping.txt","content":"pong","structuredPatch":[],"originalFile":null,"userModified":false}}
10
+ {"type":"stream_event","event":{"type":"message_stop"},"session_id":"d90bdbde"}
11
+ {"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"session_id":"d90bdbde"}
12
+ {"type":"result","subtype":"success","is_error":false,"duration_ms":1567,"num_turns":1,"result":"pong","session_id":"d90bdbde","total_cost_usd":0.061597}
@@ -0,0 +1,8 @@
1
+ {"type":"thread.started","thread_id":"0199a213-81c0-7800-8aa1-bbab2a035a53"}
2
+ {"type":"turn.started"}
3
+ {"type":"item.completed","item":{"id":"item_0","type":"reasoning","text":"**Scanning docs for exec JSON schema**"}}
4
+ {"type":"item.updated","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","status":"in_progress"}}
5
+ {"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"bash -lc ls","aggregated_output":"docs\nsrc\n","exit_code":0,"status":"completed"}}
6
+ {"type":"item.completed","item":{"id":"item_4","type":"file_change","changes":[{"path":"docs/exec-json-cheatsheet.md","kind":"add"},{"path":"docs/exec.md","kind":"update"}],"status":"completed"}}
7
+ {"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"Done. I updated the docs and added examples."}}
8
+ {"type":"turn.completed","usage":{"input_tokens":24763,"cached_input_tokens":24448,"output_tokens":122}}
@@ -0,0 +1,6 @@
1
+ {"type":"assistant.reasoning_delta","ephemeral":true,"data":{"reasoningId":"reasoning-456","deltaContent":"thinking chunk text"}}
2
+ {"type":"assistant.message_delta","ephemeral":true,"data":{"messageId":"msg-123","deltaContent":"Here are "}}
3
+ {"type":"assistant.message_delta","ephemeral":true,"data":{"messageId":"msg-123","deltaContent":"the files."}}
4
+ {"type":"tool.execution_start","data":{"toolCallId":"call-789","toolName":"bash","arguments":{"command":"ls -la"}}}
5
+ {"type":"tool.execution_complete","data":{"toolCallId":"call-789","success":true,"result":{"content":"total 0\ndrwxr-xr-x 2 user staff","detailedContent":"full result with diffs","contents":[]},"error":null}}
6
+ {"type":"assistant.turn_end","data":{"turnId":"turn-001"}}
@@ -0,0 +1,6 @@
1
+ {"type":"init","session_id":"abc123def","model":"gemini-2.5-pro","timestamp":"2026-01-15T10:00:00Z"}
2
+ {"type":"message","role":"thinking","delta":"Let me list the files","timestamp":"2026-01-15T10:00:01Z"}
3
+ {"type":"tool_use","tool_name":"Bash","tool_id":"tool_1","parameters":{"command":"echo hello"},"timestamp":"2026-01-15T10:00:01Z"}
4
+ {"type":"tool_result","tool_id":"tool_1","status":"success","output":"hello","timestamp":"2026-01-15T10:00:02Z"}
5
+ {"type":"message","role":"assistant","content":"The command output `hello`.","timestamp":"2026-01-15T10:00:05Z"}
6
+ {"type":"result","status":"success","stats":{"input_tokens":100,"output_tokens":50,"cost_usd":0.0025},"timestamp":"2026-01-15T10:00:06Z"}
@@ -24,7 +24,7 @@ export const claudeAgent: Agent = {
24
24
  }
25
25
 
26
26
  /** Map one stream-json line from claude to an AgentEvent (or null to skip). */
27
- const parseClaudeLine = (line: string): AgentEvent | null => {
27
+ export const parseClaudeLine = (line: string): AgentEvent | null => {
28
28
  let obj: any
29
29
  try {
30
30
  obj = JSON.parse(line)
@@ -22,7 +22,7 @@ export const codexAgent: Agent = {
22
22
  * Map one JSONL event from `codex exec --json` to an AgentEvent. Schema matches
23
23
  * the `ThreadEvent` union in `@openai/codex-sdk`.
24
24
  */
25
- const parseCodexLine = (line: string): AgentEvent | null => {
25
+ export const parseCodexLine = (line: string): AgentEvent | null => {
26
26
  let event: any
27
27
  try {
28
28
  event = JSON.parse(line)
@@ -23,7 +23,7 @@ export const copilotAgent: Agent = {
23
23
  * Map one JSONL event from `copilot --output-format json` to an AgentEvent.
24
24
  * Schema: `node_modules/@github/copilot/schemas/session-events.schema.json`.
25
25
  */
26
- const parseCopilotLine = (line: string): AgentEvent | null => {
26
+ export const parseCopilotLine = (line: string): AgentEvent | null => {
27
27
  let event: any
28
28
  try {
29
29
  event = JSON.parse(line)
@@ -24,7 +24,7 @@ export const geminiAgent: Agent = {
24
24
  * Event union per `@google/gemini-cli-core`'s `JsonStreamEvent`:
25
25
  * init / message / tool_use / tool_result / error / result.
26
26
  */
27
- const parseGeminiLine = (line: string): AgentEvent | null => {
27
+ export const parseGeminiLine = (line: string): AgentEvent | null => {
28
28
  let obj: any
29
29
  try {
30
30
  obj = JSON.parse(line)
@@ -112,7 +112,7 @@ const runOpencode = async function* (input: RunInput): AsyncIterable<AgentEvent>
112
112
  }
113
113
  }
114
114
 
115
- const mapOpencodeEvent = (event: any, sessionID: string | null): AgentEvent[] => {
115
+ export const mapOpencodeEvent = (event: any, sessionID: string | null): AgentEvent[] => {
116
116
  if (event.type === "message.part.updated") {
117
117
  const part = event.properties?.part
118
118
  const delta = event.properties?.delta as string | undefined
@@ -0,0 +1,113 @@
1
+ import fs from "node:fs"
2
+ import { describe, expect, it } from "vitest"
3
+
4
+ import { parseClaudeLine } from "./claude.js"
5
+ import { parseCodexLine } from "./codex.js"
6
+ import { parseCopilotLine } from "./copilot.js"
7
+ import { parseGeminiLine } from "./gemini.js"
8
+ import { mapOpencodeEvent } from "./opencode.js"
9
+ import type { AgentEvent } from "./types.js"
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[] => {
13
+ const raw = fs.readFileSync(new URL(`./__fixtures__/${name}`, import.meta.url), "utf-8")
14
+ return raw
15
+ .split("\n")
16
+ .filter((l) => l.trim())
17
+ .map(parser)
18
+ .filter((e): e is AgentEvent => e !== null)
19
+ }
20
+
21
+ describe("parseClaudeLine (real capture)", () => {
22
+ it("maps a text + tool-use transcript", () => {
23
+ expect(parseFixture("claude.jsonl", parseClaudeLine)).toEqual([
24
+ { type: "system", text: "Session started" },
25
+ { type: "text", text: "p" },
26
+ { type: "text", text: "ong" },
27
+ { type: "tool_use", name: "Write", summary: "" },
28
+ { type: "tool_result", ok: true, summary: "Created /tmp/game/ping.txt" },
29
+ { type: "result", ok: true, costUSD: 0.061597 },
30
+ ])
31
+ })
32
+ })
33
+
34
+ describe("parseCodexLine", () => {
35
+ it("maps reasoning, commands, file changes and completion", () => {
36
+ expect(parseFixture("codex.jsonl", parseCodexLine)).toEqual([
37
+ { type: "system", text: "Thread started" },
38
+ { type: "thinking", text: "**Scanning docs for exec JSON schema**\n" },
39
+ { type: "tool_result", ok: true, summary: "bash -lc ls" },
40
+ { type: "tool_result", ok: true, summary: "add docs/exec-json-cheatsheet.md, update docs/exec.md" },
41
+ { type: "text", text: "Done. I updated the docs and added examples.\n" },
42
+ { type: "result", ok: true },
43
+ ])
44
+ })
45
+ })
46
+
47
+ describe("parseGeminiLine", () => {
48
+ it("maps thinking delta, tool call, text and a costed result", () => {
49
+ expect(parseFixture("gemini.jsonl", parseGeminiLine)).toEqual([
50
+ { type: "system", text: "Session started" },
51
+ { type: "thinking", text: "Let me list the files" },
52
+ { type: "tool_use", name: "Bash", summary: "echo hello" },
53
+ { type: "tool_result", ok: true, summary: "hello" },
54
+ { type: "text", text: "The command output `hello`.\n" },
55
+ { type: "result", ok: true, costUSD: 0.0025 },
56
+ ])
57
+ })
58
+ })
59
+
60
+ describe("parseCopilotLine", () => {
61
+ it("maps reasoning/message deltas, a tool call and turn end", () => {
62
+ expect(parseFixture("copilot.jsonl", parseCopilotLine)).toEqual([
63
+ { type: "thinking", text: "thinking chunk text" },
64
+ { type: "text", text: "Here are " },
65
+ { type: "text", text: "the files." },
66
+ { type: "tool_use", name: "bash", summary: "ls -la" },
67
+ { type: "tool_result", ok: true, summary: "total 0\ndrwxr-xr-x 2 user staff" },
68
+ { type: "result", ok: true },
69
+ ])
70
+ })
71
+ })
72
+
73
+ describe("mapOpencodeEvent (SSE objects, not JSONL)", () => {
74
+ const sid = "ses_1"
75
+ it("maps a text delta", () => {
76
+ const ev = { type: "message.part.updated", properties: { part: { type: "text" }, delta: "hi" } }
77
+ expect(mapOpencodeEvent(ev, sid)).toEqual([{ type: "text", text: "hi" }])
78
+ })
79
+ it("maps a completed tool part", () => {
80
+ const ev = {
81
+ type: "message.part.updated",
82
+ properties: { part: { type: "tool", tool: "bash", state: { status: "completed", input: { command: "ls" } } } },
83
+ }
84
+ expect(mapOpencodeEvent(ev, sid)).toEqual([{ type: "tool_result", ok: true, summary: "ls" }])
85
+ })
86
+ it("maps a session error scoped to our session", () => {
87
+ const ev = { type: "session.error", properties: { sessionID: sid, error: { message: "boom" } } }
88
+ expect(mapOpencodeEvent(ev, sid)).toEqual([{ type: "error", message: "boom" }])
89
+ })
90
+ })
91
+
92
+ // Contract shared by every line-based adapter: parsing never throws, unknown
93
+ // lines are dropped (not crashed on), and a transcript ends in exactly one result.
94
+ describe("parser contract", () => {
95
+ const cases: [string, string, (line: string) => AgentEvent | null][] = [
96
+ ["claude", "claude.jsonl", parseClaudeLine],
97
+ ["codex", "codex.jsonl", parseCodexLine],
98
+ ["gemini", "gemini.jsonl", parseGeminiLine],
99
+ ["copilot", "copilot.jsonl", parseCopilotLine],
100
+ ]
101
+
102
+ it.each(cases)("%s: emits exactly one terminal result event", (_name, fixture, parser) => {
103
+ const events = parseFixture(fixture, parser)
104
+ expect(events.filter((e) => e.type === "result")).toHaveLength(1)
105
+ expect(events.at(-1)?.type).toBe("result")
106
+ })
107
+
108
+ it.each(cases)("%s: tolerates malformed JSON without throwing", (_name, _fixture, parser) => {
109
+ expect(() => parser("this is not json")).not.toThrow()
110
+ // Unparseable lines surface as a system event rather than crashing the stream.
111
+ expect(parser("this is not json")).toEqual({ type: "system", text: "this is not json" })
112
+ })
113
+ })
@@ -8,11 +8,12 @@ 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
10
  import { runCommand, gitCommit } from "../../util/exec.js"
11
- import { runSkillsPipelineTUI, runAgentWithBuildLoop } from "../../skills/runner.js"
11
+ import { runSkillsPipelineTUI, runAgentWithBuildLoop, runSelectedSkills } from "../../skills/runner.js"
12
+ import { optionalPromptSkills, type SkillDefinition } from "../../skills/registry.js"
12
13
  import { login } from "../login.js"
13
14
  import { getDefaultToken } from "../../util/config.js"
14
15
  import { slugify } from "../../util/slugify.js"
15
- import { detectRepoContext, type RepoType } from "./detectRepo.js"
16
+ import { detectRepoContext, type RepoContext, type RepoType } from "./detectRepo.js"
16
17
 
17
18
  export type Strategy = "import" | "blank" | "prompt"
18
19
 
@@ -35,8 +36,7 @@ const writeMcpConfig = (dir: string) => {
35
36
  mcpServers: {
36
37
  "dev.puzzmo.com": {
37
38
  type: "http",
38
- // url: "https://dev.puzzmo.com/api/mcp",
39
- url: "https://dev-dj9e.onrender.com/api/mcp",
39
+ url: "https://dev.puzzmo.com/api/mcp",
40
40
  headers: token ? { Authorization: `Bearer ${token}` } : undefined,
41
41
  },
42
42
  },
@@ -178,21 +178,49 @@ const pickAgent = async (preselected?: string): Promise<string> => {
178
178
  return result
179
179
  }
180
180
 
181
+ /** Presents the recommended optional skills as pre-checked tick boxes, returning the ones left on */
182
+ const pickOptionalSkills = async (): Promise<SkillDefinition[]> => {
183
+ const result = await p.multiselect({
184
+ message: "Apply these recommended extras? (space to toggle, enter to confirm)",
185
+ options: optionalPromptSkills.map((s) => ({ value: s.name, label: s.label ?? s.name })),
186
+ initialValues: optionalPromptSkills.map((s) => s.name),
187
+ required: false,
188
+ })
189
+ if (p.isCancel(result)) process.exit(0)
190
+ const chosen = result as string[]
191
+ return optionalPromptSkills.filter((s) => chosen.includes(s.name))
192
+ }
193
+
194
+ /** Builds the repo-context lines passed to skill agents so they respect the repo layout */
195
+ const buildRepoContext = (repo: RepoContext, repoType: RepoType): string => {
196
+ const lines = [
197
+ `Repo type: ${repoType}`,
198
+ `Package manager: ${repo.packageManager} (use this instead of npm/npx when running commands or adding dependencies)`,
199
+ ]
200
+ if (repoType === "multi-game")
201
+ lines.push("This is a multi-game repo with a shared root package.json. Do not create a per-game package.json or vite config.")
202
+ if (repoType === "workspace-monorepo") lines.push("This is a workspace monorepo. The game has its own package.json.")
203
+ return lines.join("\n")
204
+ }
205
+
206
+ type PromptStrategyArgs = {
207
+ userPrompt: string
208
+ displayName: string
209
+ }
210
+
181
211
  /** Composes the prompt sent to the agent for the "from prompt" strategy */
182
- const buildPromptStrategyMessage = (userPrompt: string, displayName: string): string =>
183
- [
184
- `You are scaffolding a Puzzmo game called "${displayName}" in the current directory.`,
185
- `The starter is a working Vite + Puzzmo SDK Minesweeper. Replace the gameplay with the game described below.`,
186
- ``,
187
- `Game description:`,
188
- userPrompt,
189
- ``,
190
- `Constraints:`,
191
- `- Keep puzzmo.json valid (do not remove the slug or displayName fields).`,
192
- `- Use the Puzzmo SDK lifecycle: gameReady → gameLoaded → on("start"|"retry") → updateGameState → gameCompleted.`,
193
- `- Replace fixtures in fixtures/puzzles/ with puzzles for the new game.`,
194
- `- Keep the build green (\`npx vite build\` should succeed).`,
195
- ].join("\n")
212
+ const buildPromptStrategyMessage = ({ userPrompt, displayName }: PromptStrategyArgs): string =>
213
+ `You are scaffolding a Puzzmo game called "${displayName}" in the current directory.
214
+ The starter is a working Vite + Puzzmo SDK Minesweeper. Replace the gameplay with the game described below.
215
+
216
+ Game description:
217
+ ${userPrompt}
218
+
219
+ Constraints:
220
+ - Keep puzzmo.json valid (do not remove the slug or displayName fields).
221
+ - Use the Puzzmo SDK lifecycle: gameReady → gameLoaded → on("start"|"retry") → updateGameState → gameCompleted.
222
+ - Replace fixtures in fixtures/puzzles/ with puzzles for the new game.
223
+ - Keep the build green (\`npx vite build\` should succeed).`
196
224
 
197
225
  /** Main game create wizard */
198
226
  export const gameCreate = async (opts: CreateOptions) => {
@@ -347,29 +375,27 @@ export const gameCreate = async (opts: CreateOptions) => {
347
375
  if (strategy === "import") {
348
376
  const selectedAgent = await pickAgent(opts.agent)
349
377
  if (selectedAgent !== "none") {
350
- const repoContextLines = [
351
- `Repo type: ${repoType}`,
352
- `Package manager: ${repo.packageManager} (use this instead of npm/npx when running commands or adding dependencies)`,
353
- ]
354
- if (repoType === "multi-game")
355
- repoContextLines.push(
356
- "This is a multi-game repo with a shared root package.json. Do not create a per-game package.json or vite config.",
357
- )
358
- if (repoType === "workspace-monorepo") repoContextLines.push("This is a workspace monorepo. The game has its own package.json.")
359
-
360
378
  p.log.step("Running Puzzmo migration pipeline...")
361
- await runSkillsPipelineTUI(selectedAgent, gameDir, repoContextLines.join("\n"))
379
+ await runSkillsPipelineTUI(selectedAgent, gameDir, buildRepoContext(repo, repoType))
362
380
  }
363
381
  } else if (strategy === "prompt") {
364
382
  const selectedAgent = await pickAgent(opts.agent)
365
- const message = buildPromptStrategyMessage(userPrompt!, name)
383
+ const message = buildPromptStrategyMessage({ userPrompt: userPrompt!, displayName: name })
366
384
  if (selectedAgent === "none") {
367
385
  p.log.warn("No agent selected; skipping LLM customization.")
368
386
  p.note(message, "Paste this prompt into your LLM agent:")
369
387
  } else {
388
+ // Ask which optional extras to apply up front, then run everything unattended
389
+ const extras = await pickOptionalSkills()
390
+
370
391
  p.log.step("Running agent with your prompt...")
371
- const ok = runAgentWithBuildLoop(selectedAgent, message, gameDir, "from-prompt")
392
+ const ok = await runAgentWithBuildLoop(selectedAgent, message, gameDir, "from-prompt")
372
393
  if (!ok) p.log.warn("Agent step did not complete cleanly. The Minesweeper starter is still in place.")
394
+
395
+ if (extras.length > 0) {
396
+ p.log.step(`Applying optional skills: ${extras.map((s) => s.name).join(", ")}`)
397
+ await runSelectedSkills(selectedAgent, gameDir, buildRepoContext(repo, repoType), extras)
398
+ }
373
399
  }
374
400
  }
375
401
 
@@ -1,5 +1,7 @@
1
1
  export type SkillDefinition = {
2
2
  name: string
3
+ /** Human-readable label shown in interactive pickers */
4
+ label?: string
3
5
  }
4
6
 
5
7
  /** Ordered list of skills for the migration pipeline */
@@ -12,3 +14,10 @@ export const skillsPipeline: SkillDefinition[] = [
12
14
  { name: "create-app-bundle" },
13
15
  { name: "setup-deploy" },
14
16
  ]
17
+
18
+ /** Recommended optional skills offered as pre-checked tick boxes after the "from a prompt" flow */
19
+ export const optionalPromptSkills: SkillDefinition[] = [
20
+ { name: "add-deeds", label: "Add deeds (in-game achievements)" },
21
+ { name: "setup-augmentations", label: "Set up augmentations" },
22
+ { name: "setup-deploy", label: "Set up deployment" },
23
+ ]