copperhead 0.6.0 → 0.8.0

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 (118) hide show
  1. package/README.md +36 -4
  2. package/dist/agent/animate.js +76 -0
  3. package/dist/agent/animate.js.map +1 -0
  4. package/dist/agent/box.js +89 -0
  5. package/dist/agent/box.js.map +1 -0
  6. package/dist/agent/dock-renderer.js +173 -0
  7. package/dist/agent/dock-renderer.js.map +1 -0
  8. package/dist/agent/logo.js +21 -0
  9. package/dist/agent/logo.js.map +1 -0
  10. package/dist/agent/loop.js +130 -18
  11. package/dist/agent/loop.js.map +1 -1
  12. package/dist/agent/prompts.js +2 -1
  13. package/dist/agent/prompts.js.map +1 -1
  14. package/dist/agent/providers/claude-code.js +85 -116
  15. package/dist/agent/providers/claude-code.js.map +1 -1
  16. package/dist/agent/providers/cursor.js +317 -0
  17. package/dist/agent/providers/cursor.js.map +1 -0
  18. package/dist/agent/providers/tool-protocol.js +205 -0
  19. package/dist/agent/providers/tool-protocol.js.map +1 -0
  20. package/dist/agent/recovery.js +148 -0
  21. package/dist/agent/recovery.js.map +1 -0
  22. package/dist/agent/render.js +44 -12
  23. package/dist/agent/render.js.map +1 -1
  24. package/dist/agent/response-cache.js +81 -0
  25. package/dist/agent/response-cache.js.map +1 -0
  26. package/dist/agent/runmeta.js +4 -5
  27. package/dist/agent/runmeta.js.map +1 -1
  28. package/dist/agent/theme.js +84 -0
  29. package/dist/agent/theme.js.map +1 -0
  30. package/dist/agent/tools.js +61 -4
  31. package/dist/agent/tools.js.map +1 -1
  32. package/dist/agent/transcript.js.map +1 -1
  33. package/dist/cli.js +134 -13
  34. package/dist/cli.js.map +1 -1
  35. package/dist/commands/create.js +482 -38
  36. package/dist/commands/create.js.map +1 -1
  37. package/dist/commands/demo.js +146 -0
  38. package/dist/commands/demo.js.map +1 -0
  39. package/dist/commands/doctor.js +240 -0
  40. package/dist/commands/doctor.js.map +1 -0
  41. package/dist/commands/repl-inspect.js +342 -0
  42. package/dist/commands/repl-inspect.js.map +1 -0
  43. package/dist/commands/repl.js +618 -0
  44. package/dist/commands/repl.js.map +1 -0
  45. package/dist/config.js +24 -2
  46. package/dist/config.js.map +1 -1
  47. package/dist/kicad/bootstrap.js +166 -0
  48. package/dist/kicad/bootstrap.js.map +1 -0
  49. package/dist/kicad/cli.js +126 -6
  50. package/dist/kicad/cli.js.map +1 -1
  51. package/dist/kicad/spice.js +306 -0
  52. package/dist/kicad/spice.js.map +1 -0
  53. package/dist/kicad/symlib.js +228 -0
  54. package/dist/kicad/symlib.js.map +1 -0
  55. package/dist/memory/bom-table.js +193 -22
  56. package/dist/memory/bom-table.js.map +1 -1
  57. package/dist/memory/drift.js +33 -11
  58. package/dist/memory/drift.js.map +1 -1
  59. package/dist/util/cli-args.js +35 -0
  60. package/dist/util/cli-args.js.map +1 -0
  61. package/dist/util/dock.js +155 -0
  62. package/dist/util/dock.js.map +1 -0
  63. package/dist/util/git.js +165 -4
  64. package/dist/util/git.js.map +1 -1
  65. package/dist/util/live-prompt.js +542 -0
  66. package/dist/util/live-prompt.js.map +1 -0
  67. package/dist/util/paths.js +9 -0
  68. package/dist/util/paths.js.map +1 -1
  69. package/dist/util/preflight.js +37 -0
  70. package/dist/util/preflight.js.map +1 -1
  71. package/dist/util/retry.js +23 -0
  72. package/dist/util/retry.js.map +1 -1
  73. package/dist/util/select.js +172 -0
  74. package/dist/util/select.js.map +1 -0
  75. package/dist/util/tmp.js +119 -0
  76. package/dist/util/tmp.js.map +1 -0
  77. package/package.json +3 -2
  78. package/src/agent/animate.ts +90 -0
  79. package/src/agent/box.ts +99 -0
  80. package/src/agent/dock-renderer.ts +181 -0
  81. package/src/agent/logo.ts +23 -0
  82. package/src/agent/loop.ts +148 -18
  83. package/src/agent/prompts.ts +2 -1
  84. package/src/agent/providers/claude-code.ts +91 -122
  85. package/src/agent/providers/cursor.ts +364 -0
  86. package/src/agent/providers/tool-protocol.ts +212 -0
  87. package/src/agent/recovery.ts +162 -0
  88. package/src/agent/render.ts +56 -12
  89. package/src/agent/response-cache.ts +80 -0
  90. package/src/agent/runmeta.ts +6 -7
  91. package/src/agent/theme.ts +91 -0
  92. package/src/agent/tools.ts +62 -4
  93. package/src/agent/transcript.ts +1 -0
  94. package/src/agent/types.ts +17 -0
  95. package/src/cli.ts +139 -15
  96. package/src/commands/create.ts +581 -40
  97. package/src/commands/demo.ts +184 -0
  98. package/src/commands/doctor.ts +289 -0
  99. package/src/commands/repl-inspect.ts +353 -0
  100. package/src/commands/repl.ts +685 -0
  101. package/src/config.ts +40 -3
  102. package/src/kicad/bootstrap.ts +181 -0
  103. package/src/kicad/cli.ts +132 -7
  104. package/src/kicad/spice.ts +399 -0
  105. package/src/kicad/symlib.ts +248 -0
  106. package/src/layout/claude-ui-layout.md +72 -0
  107. package/src/layout/repl-ui-layout.md +139 -0
  108. package/src/memory/bom-table.ts +191 -20
  109. package/src/memory/drift.ts +42 -11
  110. package/src/util/cli-args.ts +42 -0
  111. package/src/util/dock.ts +161 -0
  112. package/src/util/git.ts +176 -4
  113. package/src/util/live-prompt.ts +595 -0
  114. package/src/util/paths.ts +10 -0
  115. package/src/util/preflight.ts +44 -0
  116. package/src/util/retry.ts +29 -0
  117. package/src/util/select.ts +192 -0
  118. package/src/util/tmp.ts +113 -0
@@ -0,0 +1,212 @@
1
+ import type { Msg, ToolCall, ToolSchema } from '../types.js';
2
+
3
+ export function renderToolProtocol(tools: ToolSchema[]): string {
4
+ if (!tools.length) return '';
5
+ const lines = [
6
+ '# Tool protocol',
7
+ '',
8
+ 'You are the reasoning half of a tool-driven workflow; you cannot run anything yourself.',
9
+ 'To take an action, reply with EXACTLY ONE JSON object and nothing else, wrapped in a',
10
+ '```json fenced code block:',
11
+ '',
12
+ '```json',
13
+ '{"tool": "<tool_name>", "args": { ... }}',
14
+ '```',
15
+ '',
16
+ 'Use only the tools listed below, with `args` matching the tool\'s JSON Schema. If you have',
17
+ 'no tool to call and only want to say something, reply with plain prose and no JSON block.',
18
+ '',
19
+ '## Available tools',
20
+ ];
21
+ for (const t of tools) {
22
+ lines.push(
23
+ '',
24
+ `### ${t.name}`,
25
+ t.description,
26
+ `Parameters (JSON Schema): ${JSON.stringify(t.parameters)}`,
27
+ );
28
+ }
29
+ return lines.join('\n');
30
+ }
31
+
32
+ /** Delta prompt for a resumed CLI session: new user lines and tool results only. */
33
+ export function renderDelta(messages: Msg[], from: number): string {
34
+ const idToName = new Map<string, string>();
35
+ for (const m of messages) {
36
+ if (m.role === 'assistant') for (const call of m.toolCalls ?? []) idToName.set(call.id, call.name);
37
+ }
38
+ const parts: string[] = [];
39
+ for (const m of messages.slice(Math.max(0, from))) {
40
+ if (m.role === 'user') {
41
+ parts.push(`[user]\n${m.content}`);
42
+ } else if (m.role === 'tool') {
43
+ const name = idToName.get(m.toolCallId) ?? m.toolCallId;
44
+ parts.push(`[result of ${name}]\n${m.content}`);
45
+ }
46
+ }
47
+ return parts.join('\n\n');
48
+ }
49
+
50
+ export function renderConversation(messages: Msg[]): string {
51
+ const idToName = new Map<string, string>();
52
+ const parts: string[] = [];
53
+ for (const m of messages) {
54
+ if (m.role === 'system') continue;
55
+ if (m.role === 'user') {
56
+ parts.push(`[user]\n${m.content}`);
57
+ } else if (m.role === 'assistant') {
58
+ if (m.content) parts.push(`[assistant]\n${m.content}`);
59
+ for (const call of m.toolCalls ?? []) {
60
+ idToName.set(call.id, call.name);
61
+ parts.push(
62
+ `[assistant tool call]\n\`\`\`json\n${JSON.stringify({ tool: call.name, args: call.args })}\n\`\`\``,
63
+ );
64
+ }
65
+ } else {
66
+ const name = idToName.get(m.toolCallId) ?? m.toolCallId;
67
+ parts.push(`[result of ${name}]\n${m.content}`);
68
+ }
69
+ }
70
+ return parts.join('\n\n');
71
+ }
72
+
73
+ export interface ParsedToolTurn {
74
+ text: string | null;
75
+ toolCalls: ToolCall[];
76
+ nudge?: string;
77
+ }
78
+
79
+ /**
80
+ * Detect a malformed-but-intended tool call in a turn that dispatched none
81
+ * (#I10). The signature is machine-recognizable: the text contains
82
+ * `"tool":"<name>"` naming a tool in the current catalog, yet nothing parsed.
83
+ * That is the exact case where the tolerant extractor's silence misleads the
84
+ * model — the JSON was near-miss malformed (a brace short, or the outer object
85
+ * split so only an inner `{args}` with no `tool` key balanced), not the tool
86
+ * being broken. Returns a one-line steer to re-emit it, or undefined when the
87
+ * absence of a call is genuine (plain prose, no tool named).
88
+ */
89
+ function detectMalformedCall(text: string, catalog: Set<string>): string | undefined {
90
+ const re = /"tool"\s*:\s*"([^"]+)"/g;
91
+ let m: RegExpExecArray | null;
92
+ while ((m = re.exec(text)) !== null) {
93
+ const name = m[1]!;
94
+ if (catalog.has(name)) {
95
+ return (
96
+ `A tool call for "${name}" looks malformed — it named the tool but did not parse as ` +
97
+ 'valid JSON (likely unbalanced braces or a missing closing brace), so no call ran. ' +
98
+ 'Re-emit it as exactly one complete JSON object: {"tool": "...", "args": { ... }}.'
99
+ );
100
+ }
101
+ }
102
+ return undefined;
103
+ }
104
+
105
+ /**
106
+ * Extract tool-call JSON from the model's reply. Tolerant by design (D1):
107
+ * unparseable output is returned as plain text with no tool calls rather than
108
+ * throwing, so a non-conforming turn degrades to the loop's stall/nudge path.
109
+ * A parsed block only counts as a tool call when its name is in the current
110
+ * turn's catalog (`availableTools(ctx)`): a hallucinated or locked tool name is
111
+ * left as prose so the loop nudges, rather than dispatching a bogus call.
112
+ */
113
+ export function parseToolCalls(
114
+ text: string | null,
115
+ nextId: () => string,
116
+ catalog: Set<string>,
117
+ ): ParsedToolTurn {
118
+ if (!text) return { text: null, toolCalls: [] };
119
+ const toolCalls: ToolCall[] = [];
120
+ const matched: Array<[number, number]> = [];
121
+
122
+ // Extract tool calls by scanning for complete JSON objects, NOT by matching
123
+ // ``` fences. A tool call's `content`/`args` can hold a full markdown doc that
124
+ // itself contains ``` code fences; a fence regex truncates the JSON at the
125
+ // first inner fence, JSON.parse fails, and the call is silently dropped (the
126
+ // model then assumes it wrote a file it never did). The brace scan is
127
+ // string-aware, so braces and backticks inside JSON string values are ignored.
128
+ let searchFrom = 0;
129
+ while (searchFrom < text.length) {
130
+ const braceAt = text.indexOf('{', searchFrom);
131
+ if (braceAt < 0) break;
132
+ const span = scanJsonObject(text, braceAt);
133
+ if (!span) {
134
+ // Unbalanced '{' (stray brace in prose): retry from the next candidate so
135
+ // one bad brace can't hide a well-formed call later in the reply.
136
+ searchFrom = braceAt + 1;
137
+ continue;
138
+ }
139
+ const call = toToolCall(text.slice(span.start, span.end), nextId, catalog);
140
+ if (call) {
141
+ toolCalls.push(call);
142
+ matched.push([span.start, span.end]);
143
+ }
144
+ searchFrom = span.end;
145
+ }
146
+
147
+ if (!toolCalls.length) {
148
+ // No call dispatched — but did the model clearly *intend* one? A fenced
149
+ // ```json block that names a catalog tool yet produced zero calls is a
150
+ // malformed near-miss (unbalanced braces, a missing `}`, or an inner object
151
+ // with no `tool` key). Silently dropping it gives the model no signal, so it
152
+ // misreads "no result" as "this tool is broken" and can bake that false
153
+ // conclusion into a committed summary (#I10). Surface a nudge instead.
154
+ return { text: text.trim() ? text : null, toolCalls, nudge: detectMalformedCall(text, catalog) };
155
+ }
156
+
157
+ // Prose is whatever survives once the tool-call objects (and any now-empty
158
+ // ```json fences around them) are removed.
159
+ let prose = '';
160
+ let cursor = 0;
161
+ for (const [start, end] of matched) {
162
+ prose += text.slice(cursor, start);
163
+ cursor = end;
164
+ }
165
+ prose += text.slice(cursor);
166
+ prose = prose.replace(/```(?:json)?\s*```/gi, '').replace(/```(?:json)?\s*$/gi, '').trim();
167
+ return { text: prose.length ? prose : null, toolCalls };
168
+ }
169
+
170
+ /**
171
+ * Find the first complete, brace-balanced JSON object at or after `from`,
172
+ * respecting JSON string quoting/escaping so braces or backticks inside string
173
+ * values do not end the scan. Returns its `[start, end)` bounds or null.
174
+ */
175
+ function scanJsonObject(text: string, from: number): { start: number; end: number } | null {
176
+ const start = text.indexOf('{', from);
177
+ if (start < 0) return null;
178
+ let depth = 0;
179
+ let inStr = false;
180
+ let esc = false;
181
+ for (let i = start; i < text.length; i++) {
182
+ const ch = text[i];
183
+ if (inStr) {
184
+ if (esc) esc = false;
185
+ else if (ch === '\\') esc = true;
186
+ else if (ch === '"') inStr = false;
187
+ continue;
188
+ }
189
+ if (ch === '"') inStr = true;
190
+ else if (ch === '{') depth++;
191
+ else if (ch === '}' && --depth === 0) return { start, end: i + 1 };
192
+ }
193
+ return null;
194
+ }
195
+
196
+ function toToolCall(raw: string | undefined, nextId: () => string, catalog: Set<string>): ToolCall | null {
197
+ if (!raw) return null;
198
+ let obj: unknown;
199
+ try {
200
+ obj = JSON.parse(raw.trim());
201
+ } catch {
202
+ return null;
203
+ }
204
+ if (!obj || typeof obj !== 'object') return null;
205
+ const rec = obj as Record<string, unknown>;
206
+ if (typeof rec.tool !== 'string') return null;
207
+ // Only accept names the turn actually advertised. An empty catalog means the
208
+ // turn offered no tools, so nothing parses as a call.
209
+ if (!catalog.has(rec.tool)) return null;
210
+ const args = rec.args && typeof rec.args === 'object' ? (rec.args as Record<string, unknown>) : {};
211
+ return { id: nextId(), name: rec.tool, args };
212
+ }
@@ -0,0 +1,162 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import type { Msg, Provider } from './types.js';
5
+
6
+ /** Thrown when a single provider turn blows past its watchdog deadline. */
7
+ export class TurnTimeoutError extends Error {
8
+ constructor(public readonly ms: number) {
9
+ super(`turn exceeded ${ms}ms without responding`);
10
+ this.name = 'TurnTimeoutError';
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Race `fn()` against a deadline so a hung provider call cannot stall the run
16
+ * forever. On timeout, `onTimeout` runs (tear down the in-flight call, e.g.
17
+ * provider.close()) and the returned promise rejects with TurnTimeoutError; the
18
+ * caller decides whether to retry or fail. `ms <= 0` (or non-finite) disables the
19
+ * watchdog and just awaits `fn()`.
20
+ */
21
+ export async function withTimeout<T>(
22
+ fn: () => Promise<T>,
23
+ ms: number,
24
+ onTimeout?: () => void | Promise<void>,
25
+ ): Promise<T> {
26
+ if (!Number.isFinite(ms) || ms <= 0) return fn();
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ const timeout = new Promise<never>((_, reject) => {
29
+ timer = setTimeout(() => {
30
+ void Promise.resolve(onTimeout?.()).catch(() => {});
31
+ reject(new TurnTimeoutError(ms));
32
+ }, ms);
33
+ });
34
+ try {
35
+ return await Promise.race([fn(), timeout]);
36
+ } finally {
37
+ if (timer) clearTimeout(timer);
38
+ }
39
+ }
40
+
41
+ export interface StageDiagnosis {
42
+ verdict: 'retry' | 'abort';
43
+ reason: string;
44
+ /** When retrying: concrete instructions to prepend to the next attempt. */
45
+ guidance?: string;
46
+ /** Tokens the diagnosis call itself spent, so the pipeline can fold them into
47
+ * the stage's cost total (F6). Absent when the call threw before a response. */
48
+ usage?: { inputTokens: number; outputTokens: number };
49
+ }
50
+
51
+ /** Extract the first brace-balanced JSON object from text, tolerating quoting and
52
+ * escaping, and interpret it as a StageDiagnosis. Anything unparseable is treated
53
+ * as "abort" so an ambiguous diagnosis never loops the pipeline forever. */
54
+ export function parseDiagnosis(text: string | null): StageDiagnosis {
55
+ if (!text) return { verdict: 'abort', reason: 'no diagnosis produced' };
56
+ const start = text.indexOf('{');
57
+ if (start >= 0) {
58
+ let depth = 0;
59
+ let inStr = false;
60
+ let esc = false;
61
+ for (let i = start; i < text.length; i++) {
62
+ const ch = text[i];
63
+ if (inStr) {
64
+ if (esc) esc = false;
65
+ else if (ch === '\\') esc = true;
66
+ else if (ch === '"') inStr = false;
67
+ continue;
68
+ }
69
+ if (ch === '"') inStr = true;
70
+ else if (ch === '{') depth++;
71
+ else if (ch === '}' && --depth === 0) {
72
+ try {
73
+ const o = JSON.parse(text.slice(start, i + 1)) as Partial<StageDiagnosis>;
74
+ const verdict = o.verdict === 'retry' ? 'retry' : 'abort';
75
+ return {
76
+ verdict,
77
+ reason: typeof o.reason === 'string' ? o.reason : 'no reason given',
78
+ ...(verdict === 'retry' && typeof o.guidance === 'string' && o.guidance.trim()
79
+ ? { guidance: o.guidance.trim() }
80
+ : {}),
81
+ };
82
+ } catch {
83
+ break;
84
+ }
85
+ }
86
+ }
87
+ }
88
+ return { verdict: 'abort', reason: 'diagnosis was not valid JSON' };
89
+ }
90
+
91
+ /** Compact, most-recent-last excerpt of a run's transcript for the diagnostician:
92
+ * the last assistant message and the last few tool results, truncated. */
93
+ export async function transcriptExcerpt(transcriptDir: string, maxChars = 4000): Promise<string> {
94
+ const p = path.join(transcriptDir, 'transcript.jsonl');
95
+ if (!existsSync(p)) return '(no transcript)';
96
+ let lines: string[];
97
+ try {
98
+ lines = (await readFile(p, 'utf8')).trim().split('\n');
99
+ } catch {
100
+ return '(transcript unreadable)';
101
+ }
102
+ const parts: string[] = [];
103
+ for (const line of lines.slice(-12)) {
104
+ try {
105
+ const e = JSON.parse(line) as { type: string; data?: Record<string, unknown> };
106
+ if (e.type === 'assistant' && typeof e.data?.text === 'string' && e.data.text) {
107
+ parts.push(`[assistant] ${e.data.text}`);
108
+ } else if (e.type === 'tool') {
109
+ parts.push(`[${String(e.data?.name)}] ${String(e.data?.result ?? '').split('\n')[0]}`);
110
+ }
111
+ } catch {
112
+ /* skip */
113
+ }
114
+ }
115
+ const joined = parts.join('\n');
116
+ return joined.length > maxChars ? joined.slice(joined.length - maxChars) : joined;
117
+ }
118
+
119
+ /**
120
+ * Ask the model whether a failed/incomplete stage is worth retrying, and if so
121
+ * how. Uses a fresh, tool-less provider turn (the same saved-login backend the
122
+ * pipeline runs on), so no extra credentials or config are needed. Any error or
123
+ * ambiguity resolves to "abort" — recovery must fail safe toward reporting to the
124
+ * human rather than looping.
125
+ */
126
+ export async function diagnoseStageFailure(
127
+ provider: Provider,
128
+ input: {
129
+ stageName: string;
130
+ stageGoal: string;
131
+ failure: string;
132
+ excerpt: string;
133
+ attempt: number;
134
+ maxAttempts: number;
135
+ },
136
+ ): Promise<StageDiagnosis> {
137
+ const system =
138
+ 'You are the recovery supervisor for an automated KiCad PCB-design pipeline. ' +
139
+ 'A stage just failed or ended without meeting its completion contract. Judge whether ' +
140
+ 'another automated attempt is likely to succeed, or whether a human should intervene. ' +
141
+ 'Be decisive and terse.';
142
+ const user =
143
+ `Stage: ${input.stageName}\n` +
144
+ `Stage goal: ${input.stageGoal}\n` +
145
+ `Failure: ${input.failure}\n` +
146
+ `This was attempt ${input.attempt} of ${input.maxAttempts}.\n\n` +
147
+ `Recent transcript (most recent last):\n${input.excerpt}\n\n` +
148
+ 'Reply with ONLY a JSON object, no prose:\n' +
149
+ '{"verdict":"retry"|"abort","reason":"<one sentence>","guidance":"<if retry: concrete, specific instructions to prepend to the next attempt so it avoids this failure; otherwise empty>"}\n' +
150
+ '- "retry" if the failure looks transient or fixable with clearer instructions (a dropped or locked tool call, an empty/no-op edit, a skipped step, a timeout, a formatting slip).\n' +
151
+ '- "abort" if repeating the same attempt will not help and a human should look (missing inputs, a genuine dead-end, or the same failure already seen on a prior attempt).';
152
+ const messages: Msg[] = [
153
+ { role: 'system', content: system },
154
+ { role: 'user', content: user },
155
+ ];
156
+ try {
157
+ const turn = await provider.chat(messages, []);
158
+ return { ...parseDiagnosis(turn.text), usage: turn.usage };
159
+ } catch (e) {
160
+ return { verdict: 'abort', reason: `diagnosis call failed: ${(e as Error).message}` };
161
+ }
162
+ }
@@ -3,8 +3,13 @@
3
3
  * once at startup: interactive (TTY, no --json/--plain) pins a status line to
4
4
  * the bottom of the terminal and redraws it in place; plain emits line-oriented
5
5
  * output with zero ANSI escapes — the mode CI, pipes, and tests see.
6
+ *
7
+ * Interactive mode adds subtle SGR chrome (copper accent, dim secondary text).
8
+ * Plain mode never emits color (AC-8.9).
6
9
  */
7
10
 
11
+ import { copper, dim, setColorEnabled, styleOutcome, toolLine, warn } from './theme.js';
12
+
8
13
  export interface ProgressRenderer {
9
14
  log(line: string): void;
10
15
  /** Called at the start of each turn with cumulative token totals so far. */
@@ -12,6 +17,14 @@ export interface ProgressRenderer {
12
17
  toolResult(name: string, firstLine: string): void;
13
18
  /** Busy text while a provider call is in flight; null when idle. */
14
19
  status(text: string | null): void;
20
+ /**
21
+ * Liveness signal emitted periodically while a provider turn is in flight
22
+ * (5.1): distinguishes a slow turn from a hung one. `elapsedMs` is time since
23
+ * this turn's provider call began; `streamedChars` is cumulative streamed
24
+ * output (0 when the provider doesn't stream — the elapsed time still tells
25
+ * the operator the turn is alive).
26
+ */
27
+ heartbeat(info: { elapsedMs: number; streamedChars: number }): void;
15
28
  /** Final outcome line; replaces the status line in interactive mode. */
16
29
  finish(line: string): void;
17
30
  }
@@ -41,6 +54,11 @@ export function plainRenderer(log: (line: string) => void): ProgressRenderer {
41
54
  turnStart: (turn, maxTurns, tokensIn, tokensOut) => log(turnMarker(turn, maxTurns, tokensIn, tokensOut)),
42
55
  toolResult: (name, firstLine) => log(` [${name}] ${firstLine}`),
43
56
  status: () => {},
57
+ heartbeat: ({ elapsedMs, streamedChars }) =>
58
+ log(
59
+ ` … still working — ${fmtDuration(elapsedMs)} elapsed` +
60
+ (streamedChars ? `, ~${fmtTokens(streamedChars)} chars streamed` : ' (no output yet)'),
61
+ ),
44
62
  finish: (line) => log(line),
45
63
  };
46
64
  }
@@ -68,6 +86,7 @@ export class InteractiveRenderer implements ProgressRenderer {
68
86
  private maxTurns = 0;
69
87
  private tokensIn = 0;
70
88
  private tokensOut = 0;
89
+ private streamedChars = 0;
71
90
  private busy: string | null = null;
72
91
  private frame = 0;
73
92
  private timer: ReturnType<typeof setInterval> | null = null;
@@ -92,16 +111,29 @@ export class InteractiveRenderer implements ProgressRenderer {
92
111
  }
93
112
 
94
113
  private statusText(): string {
95
- const parts = [
96
- `turn ${this.turn}/${this.maxTurns}`,
97
- `${fmtTokens(this.tokensIn)} in / ${fmtTokens(this.tokensOut)} out`,
98
- fmtDuration(Date.now() - this.startMs),
99
- ];
100
- if (this.busy) parts.push(this.busy);
101
- const spinner = this.busy ? FRAMES[this.frame % FRAMES.length] : '·';
102
- const line = `${spinner} ${parts.join(' · ')}`;
114
+ // Raw (uncolored) segments once; both the colored line and the
115
+ // narrow-terminal fallback are assembled from these.
116
+ const spinner = this.busy ? FRAMES[this.frame % FRAMES.length]! : '·';
117
+ const turn = `turn ${this.turn}/${this.maxTurns}`;
118
+ const tokens = `${fmtTokens(this.tokensIn)} in / ${fmtTokens(this.tokensOut)} out`;
119
+ const elapsed = fmtDuration(Date.now() - this.startMs);
120
+ // Fold streamed-output volume into the busy segment so a large turn's
121
+ // status line visibly grows a hung one stays frozen (5.1).
122
+ const busy = this.busy
123
+ ? this.streamedChars
124
+ ? `${this.busy} ~${fmtTokens(this.streamedChars)} ch`
125
+ : this.busy
126
+ : undefined;
127
+ const parts = [turn, dim(tokens), dim(elapsed), ...(busy ? [warn(busy)] : [])];
128
+ const line = `${this.busy ? copper(spinner) : dim(spinner)} ${parts.join(dim(' · '))}`;
129
+ // Truncate by visible length roughly: strip SGR when measuring so color
130
+ // codes don't eat the column budget and clip the readable text early.
103
131
  const width = this.out.columns ?? 80;
104
- return line.length > width ? line.slice(0, width - 1) : line;
132
+ const visible = line.replace(/\x1b\[[0-9;]*m/g, '');
133
+ if (visible.length <= width) return line;
134
+ // Fall back to an uncolored truncated line when the terminal is too narrow.
135
+ const plain = [spinner, turn, tokens, elapsed, ...(busy ? [busy] : [])].join(' · ');
136
+ return plain.length > width ? plain.slice(0, width - 1) : plain;
105
137
  }
106
138
 
107
139
  private redraw(): void {
@@ -138,23 +170,32 @@ export class InteractiveRenderer implements ProgressRenderer {
138
170
  this.maxTurns = maxTurns;
139
171
  this.tokensIn = tokensIn;
140
172
  this.tokensOut = tokensOut;
173
+ this.streamedChars = 0; // per-turn: reset so last turn's volume doesn't linger
141
174
  this.ensureTimer();
142
175
  this.redraw();
143
176
  }
144
177
 
145
178
  toolResult(name: string, firstLine: string): void {
146
- this.log(` [${name}] ${firstLine}`);
179
+ this.log(toolLine(name, firstLine));
147
180
  }
148
181
 
149
182
  status(text: string | null): void {
150
183
  this.busy = text;
184
+ if (!text) this.streamedChars = 0; // turn's provider call ended
151
185
  if (text && !this.idle) this.ensureTimer();
152
186
  this.redraw();
153
187
  }
154
188
 
189
+ heartbeat({ streamedChars }: { elapsedMs: number; streamedChars: number }): void {
190
+ // The spinner timer already advances elapsed time in place; the heartbeat's
191
+ // job here is to fold in the latest streamed-output volume and redraw.
192
+ this.streamedChars = streamedChars;
193
+ this.redraw();
194
+ }
195
+
155
196
  finish(line: string): void {
156
197
  if (this.statusShown) this.out.write(CLEAR_LINE);
157
- this.out.write(line + '\n');
198
+ this.out.write(styleOutcome(line) + '\n');
158
199
  this.suspend();
159
200
  }
160
201
 
@@ -188,7 +229,10 @@ export class InteractiveRenderer implements ProgressRenderer {
188
229
  * (AC-2.4): the only thing a --json invocation writes to stdout is its JSON.
189
230
  */
190
231
  export function makeRenderer(opts: { json: boolean; plain: boolean }): ProgressRenderer {
232
+ const interactive = !opts.json && !opts.plain && Boolean(process.stdout.isTTY);
233
+ // Color tracks the interactive path so --plain / pipes stay zero-ANSI (AC-8.9).
234
+ setColorEnabled(interactive && !process.env.NO_COLOR);
191
235
  if (opts.json) return plainRenderer((line) => console.error(line));
192
- if (!opts.plain && process.stdout.isTTY) return new InteractiveRenderer();
236
+ if (interactive) return new InteractiveRenderer();
193
237
  return plainRenderer((line) => console.log(line));
194
238
  }
@@ -0,0 +1,80 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import type { ChatOpts, Msg, Provider, ToolSchema, Turn } from './types.js';
6
+
7
+ /**
8
+ * Wraps a provider so each turn's `(messages, tools) -> Turn` is written to disk
9
+ * and replayed on an identical later call. This makes the pipeline cheap and
10
+ * fast to recover: a stage that is retried after a transient failure (a timed-out
11
+ * turn, a crash, an auto-retry) replays the responses it already paid for, from
12
+ * turn 1 up to the point where the inputs first diverge, instead of re-calling
13
+ * the model. When a retry deliberately changes the prompt (e.g. diagnosis
14
+ * guidance is appended), the input hash changes and the model is called fresh —
15
+ * so caching never pins a run to a stale, failing response.
16
+ *
17
+ * Best-effort by construction: a cache miss or any I/O error falls through to the
18
+ * live provider, and a hit reports zero token usage (the real spend was zero).
19
+ * The key is a content hash of the full message history and the advertised tool
20
+ * names, so any change to the conversation or available tools is a fresh call.
21
+ */
22
+ export class CachingProvider implements Provider {
23
+ readonly name: string;
24
+ private hits = 0;
25
+
26
+ /** Turns served from the on-disk cache so far (5.2: per-stage cache-hit%). */
27
+ get cacheHits(): number {
28
+ return this.hits;
29
+ }
30
+
31
+ constructor(
32
+ private readonly inner: Provider,
33
+ private readonly dir: string,
34
+ private readonly log?: (s: string) => void,
35
+ /** The concrete model id this run resolved to (e.g. `claude-code:opus`), used
36
+ * in the cache key so switching model on the same repo does not replay the
37
+ * other model's cached turns (F6). Falls back to the provider family name. */
38
+ private readonly modelId?: string,
39
+ ) {
40
+ this.name = inner.name;
41
+ }
42
+
43
+ private keyFor(messages: Msg[], tools: ToolSchema[]): string {
44
+ return createHash('sha256')
45
+ .update(JSON.stringify({ model: this.modelId ?? this.name, messages, tools: tools.map((t) => t.name) }))
46
+ .digest('hex');
47
+ }
48
+
49
+ async chat(messages: Msg[], tools: ToolSchema[], opts?: ChatOpts): Promise<Turn> {
50
+ const file = path.join(this.dir, `${this.keyFor(messages, tools)}.json`);
51
+ if (existsSync(file)) {
52
+ try {
53
+ const cached = JSON.parse(await readFile(file, 'utf8')) as Turn;
54
+ this.hits++;
55
+ this.log?.(`llm-cache: replayed a cached response (hit #${this.hits}, no tokens spent)`);
56
+ // Report zero usage: replaying a cached turn costs nothing.
57
+ return { ...cached, usage: { inputTokens: 0, outputTokens: 0 } };
58
+ } catch {
59
+ // corrupt/partial cache file — fall through and regenerate
60
+ }
61
+ }
62
+ const turn = await this.inner.chat(messages, tools, opts);
63
+ try {
64
+ await mkdir(this.dir, { recursive: true });
65
+ // Keep the cache out of git entirely (and out of failed-run stashes): a
66
+ // `*` .gitignore in the cache dir hides every entry, so the cache persists
67
+ // across runs without ever dirtying the tree.
68
+ const ignore = path.join(this.dir, '.gitignore');
69
+ if (!existsSync(ignore)) await writeFile(ignore, '*\n', 'utf8');
70
+ await writeFile(file, JSON.stringify(turn), 'utf8');
71
+ } catch {
72
+ // best-effort: caching must never break a run
73
+ }
74
+ return turn;
75
+ }
76
+
77
+ async close(): Promise<void> {
78
+ await this.inner.close?.();
79
+ }
80
+ }
@@ -9,7 +9,7 @@ import type { CopperheadConfig, ModelSource } from '../config.js';
9
9
 
10
10
  /** Caller-supplied run identity: facts the loop cannot probe for itself. */
11
11
  export interface RunMetaInput {
12
- command?: 'do' | 'create' | 'sync';
12
+ command?: 'do' | 'create' | 'sync' | 'repl';
13
13
  modelSource?: ModelSource;
14
14
  version?: string;
15
15
  kicadCliVersion?: string;
@@ -29,7 +29,7 @@ export interface RunMeta {
29
29
  modelSource: ModelSource | null;
30
30
  runId: string;
31
31
  startedAt: string;
32
- command: 'do' | 'create' | 'sync' | null;
32
+ command: 'do' | 'create' | 'sync' | 'repl' | null;
33
33
  interactive: boolean;
34
34
  stage: { name: string; index: number; total: number } | null;
35
35
  brief: { path: string; sha256: string } | null;
@@ -150,14 +150,14 @@ export async function collectRunMeta(opts: CollectRunMetaOptions): Promise<RunMe
150
150
 
151
151
  const unk = (v: string | null | undefined): string => v ?? 'unknown';
152
152
 
153
- /** ≤ 2 lines, printed before the first turn (AC-8.4). */
153
+ /** ≤ 2 lines, printed before the first turn (AC-8.4).
154
+ * Live header stays compact: install path / platform live in summary.md only. */
154
155
  export function renderCliHeader(meta: RunMeta): string[] {
155
156
  const v = meta.versions;
156
157
  const line1 = [
157
- `copperhead v${unk(v.copperhead)}${v.installPath ? ` (${v.installPath})` : ''}`,
158
+ `copperhead v${unk(v.copperhead)}`,
158
159
  `kicad-cli ${unk(v.kicadCli)}`,
159
160
  `node ${v.node}`,
160
- v.platform,
161
161
  ].join(' · ');
162
162
 
163
163
  const repoState =
@@ -167,12 +167,11 @@ export function renderCliHeader(meta: RunMeta): string[] {
167
167
  ? `dirty(${meta.git.uncommittedFiles})`
168
168
  : 'clean';
169
169
  const line2 = [
170
- `run ${meta.runId}`,
171
170
  unk(meta.command),
172
171
  ...(meta.stage ? [`stage ${meta.stage.name} (${meta.stage.index}/${meta.stage.total})`] : []),
173
172
  `model ${meta.model} (${meta.provider}, via ${unk(meta.modelSource)})`,
174
173
  `turns ≤${meta.config.maxTurns}`,
175
- `repo ${unk(meta.git.branch)}@${meta.git.commit?.slice(0, 7) ?? 'unknown'} ${repoState}`,
174
+ `${unk(meta.git.branch)}@${meta.git.commit?.slice(0, 7) ?? 'unknown'} ${repoState}`,
176
175
  ].join(' · ');
177
176
  return [line1, line2];
178
177
  }