@criogaid/pi-hashline-edit 0.3.0 → 0.4.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 (69) hide show
  1. package/README.md +59 -50
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1594 -694
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +219 -130
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -8,104 +8,239 @@ import { makeReplaceTool } from "./replace-tool.ts";
8
8
  import { renderDiffPreview, withMutationStatus } from "./render.ts";
9
9
  import { makeWriteOverride } from "./write-tool.ts";
10
10
  import { generateMutationDetails } from "./mutation-result.ts";
11
+ import type { ActionFusionDetails } from "./action-fusion.ts";
12
+
13
+ const versions = { publishedRevision: "r", observedRevision: "r" };
14
+ const mutationDetails = (actionFusion?: ActionFusionDetails) => ({
15
+ ...generateMutationDetails("a.txt", "same\n", "same\n", versions, "PUBLISHED"),
16
+ actionFusion,
17
+ });
11
18
 
12
19
  test("mutation headers refresh in place and retain isolated per-call counts", () => {
13
- initTheme("dark");
14
- for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
15
- const args = { path: "a.txt", edits: [{ op: "append", body: ["new"] }], find: "old", replace: "new" };
16
- const context: any = { args, state: {}, invalidate() { assert.fail("rendering must not invalidate the row"); } };
17
- const header = tool.renderCall(args, theme, context);
18
- const other = tool.renderCall({ ...args, path: "b.txt" }, theme, { state: {} });
19
- assert.equal(context.state.callText, header);
20
- tool.renderResult({ content: [{ type: "text", text: "Done" }], details: { diff: "-1 old\n+1 new" } }, { isPartial: false, expanded: false }, theme, context);
21
- assert.match(header.render(100).join("\n"), /\+1/);
22
- assert.match(header.render(100).join("\n"), /-1/);
23
- assert.doesNotMatch(other.render(100).join("\n"), /\+1|-1/);
24
- context.lastComponent = header;
25
- assert.equal(tool.renderCall(args, theme, context), header);
26
- assert.match(header.render(100).join("\n"), /\+1/);
27
- }
20
+ initTheme("dark");
21
+ for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
22
+ const args = {
23
+ path: "a.txt",
24
+ edits: [{ op: "append" as const, body: ["new"] }],
25
+ replacements: [{ find: "old", replace: "new" }],
26
+ };
27
+ const context: any = {
28
+ args,
29
+ state: {},
30
+ invalidate() {
31
+ assert.fail("rendering must not invalidate the row");
32
+ },
33
+ };
34
+ const header = tool.renderCall(args, theme, context);
35
+ const other = tool.renderCall({ ...args, path: "b.txt" }, theme, { ...context, state: {} });
36
+ assert.equal(context.state.callText, header);
37
+ tool.renderResult(
38
+ {
39
+ content: [{ type: "text", text: "Done" }],
40
+ details: generateMutationDetails("a.txt", "old\n", "new\n", versions, "PUBLISHED"),
41
+ },
42
+ { isPartial: false, expanded: false },
43
+ theme,
44
+ context,
45
+ );
46
+ assert.match(header.render(100).join("\n"), /\+1/);
47
+ assert.match(header.render(100).join("\n"), /-1/);
48
+ assert.doesNotMatch(other.render(100).join("\n"), /\+1|-1/);
49
+ context.lastComponent = header;
50
+ assert.equal(tool.renderCall(args, theme, context), header);
51
+ assert.match(header.render(100).join("\n"), /\+1/);
52
+ }
53
+ });
54
+
55
+ test("edit call titles show structured batches and tolerate invalid partial input", () => {
56
+ initTheme("dark");
57
+ const tool = makeEditOverride(process.cwd());
58
+ const edits = [
59
+ { op: "replace" as const, anchor: "1#AB", body: ["new"] },
60
+ { op: "append" as const, body: ["more"] },
61
+ ];
62
+ const render = (value: unknown) =>
63
+ tool
64
+ .renderCall({ path: "f.txt", edits: value } as Parameters<typeof tool.renderCall>[0], theme, {
65
+ state: {},
66
+ } as Parameters<typeof tool.renderCall>[2])
67
+ .render(120)
68
+ .join("\n");
69
+ assert.match(render(edits), /2 ops: replace/);
70
+ assert.doesNotMatch(render(JSON.stringify(edits)), /ops:/);
71
+ assert.doesNotMatch(render("[{bad"), /ops:/);
28
72
  });
29
73
 
30
74
  test("mutation card owns stale-anchor notices without internal status", () => {
31
- initTheme("dark");
32
- const tool = withMutationStatus(makeEditOverride(process.cwd()));
33
- const args = { path: "a.txt", edits: [{ op: "append", body: ["new"] }] };
34
- const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
35
- const card = tool.renderCall!(args, theme, context);
36
- tool.renderResult!({
37
- content: [{ type: "text", text: "Edit saved." }, { type: "text", text: "command diagnostic" }],
38
- details: { actionFusion: { publication: "PUBLISHED", freshness: "changed", command: "failed" } },
39
- }, { isPartial: false, expanded: false }, theme, context);
40
- const output = card.render(160).join("\n");
41
- assert.match(output, /Edit saved/);
42
- assert.doesNotMatch(output, /publication=|freshness=/);
43
- assert.match(output, /Anchors are stale: target changed/);
44
- assert.doesNotMatch(output, /command diagnostic/);
45
- assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
75
+ initTheme("dark");
76
+ const tool = withMutationStatus(makeEditOverride(process.cwd()));
77
+ const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
78
+ const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
79
+ const card = tool.renderCall!(args, theme, context);
80
+ tool.renderResult!(
81
+ {
82
+ content: [
83
+ { type: "text", text: "Edit saved." },
84
+ { type: "text", text: "command diagnostic" },
85
+ ],
86
+ details: mutationDetails({
87
+ publication: "PUBLISHED",
88
+ freshness: "changed",
89
+ command: "failed",
90
+ }),
91
+ },
92
+ { isPartial: false, expanded: false },
93
+ theme,
94
+ context,
95
+ );
96
+ const output = card.render(160).join("\n");
97
+ assert.match(output, /Edit saved/);
98
+ assert.doesNotMatch(output, /publication=|freshness=/);
99
+ assert.match(output, /Anchors are stale: target changed/);
100
+ assert.doesNotMatch(output, /command diagnostic/);
101
+ assert.ok(output.includes(theme.getBgAnsi("toolSuccessBg")));
46
102
  });
47
103
 
48
104
  test("mutation card omits status when then_run was not requested", () => {
49
- initTheme("dark");
50
- const tool = withMutationStatus(makeEditOverride(process.cwd()));
51
- const args = { path: "a.txt", edits: [{ op: "append", body: ["new"] }] };
52
- const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
53
- const card = tool.renderCall!(args, theme, context);
54
- tool.renderResult!({
55
- content: [{ type: "text", text: "Edited a.txt." }],
56
- details: { actionFusion: { publication: "PUBLISHED", freshness: "unchanged", command: "not_requested" } },
57
- }, { isPartial: false, expanded: false }, theme, context);
58
- const output = card.render(160).join("\n");
59
- assert.match(output, /Edited a\.txt/);
60
- assert.doesNotMatch(output, /publication=|freshness=/);
61
- tool.renderCall!(args, theme, context);
62
- tool.renderResult!({
63
- content: [{ type: "text", text: "Edited a.txt." }],
64
- details: { actionFusion: { publication: "PUBLISHED", freshness: "changed", command: "not_requested" } },
65
- }, { isPartial: false, expanded: false }, theme, context);
66
- const staleOutput = card.render(160).join("\n");
67
- assert.match(staleOutput, /Anchors are stale: target changed/);
68
- assert.doesNotMatch(staleOutput, /publication=|freshness=/);
105
+ initTheme("dark");
106
+ const tool = withMutationStatus(makeEditOverride(process.cwd()));
107
+ const args = { path: "a.txt", edits: [{ op: "append" as const, body: ["new"] }] };
108
+ const context: any = { args, state: {}, isPartial: false, isError: false, invalidate() {} };
109
+ const card = tool.renderCall!(args, theme, context);
110
+ tool.renderResult!(
111
+ {
112
+ content: [{ type: "text", text: "Edited a.txt." }],
113
+ details: mutationDetails({
114
+ publication: "PUBLISHED",
115
+ freshness: "unchanged",
116
+ command: "not_requested",
117
+ }),
118
+ },
119
+ { isPartial: false, expanded: false },
120
+ theme,
121
+ context,
122
+ );
123
+ const output = card.render(160).join("\n");
124
+ assert.match(output, /Edited a\.txt/);
125
+ assert.doesNotMatch(output, /publication=|freshness=/);
126
+ tool.renderCall!(args, theme, context);
127
+ tool.renderResult!(
128
+ {
129
+ content: [{ type: "text", text: "Edited a.txt." }],
130
+ details: mutationDetails({
131
+ publication: "PUBLISHED",
132
+ freshness: "changed",
133
+ command: "not_requested",
134
+ }),
135
+ },
136
+ { isPartial: false, expanded: false },
137
+ theme,
138
+ context,
139
+ );
140
+ const staleOutput = card.render(160).join("\n");
141
+ assert.match(staleOutput, /Anchors are stale: target changed/);
142
+ assert.doesNotMatch(staleOutput, /publication=|freshness=/);
69
143
  });
70
144
 
71
145
  test("unfused write errors retain the native full diagnostic", () => {
72
- initTheme("dark");
73
- const tool = withMutationStatus(makeWriteOverride(process.cwd()));
74
- const args = { path: "a.txt", content: "new" };
75
- const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
76
- const card = tool.renderCall!(args, theme, context);
77
- tool.renderResult!({ content: [{ type: "text", text: "write failed\nimportant detail" }], details: {} },
78
- { isPartial: false, expanded: false }, theme, context);
79
- assert.match(card.render(160).join("\n"), /write failed[\s\S]*important detail/);
146
+ initTheme("dark");
147
+ const tool = withMutationStatus(makeWriteOverride(process.cwd()));
148
+ const args = { path: "a.txt", content: "new" };
149
+ const context: any = { args, state: {}, isPartial: false, isError: true, invalidate() {} };
150
+ const card = tool.renderCall!(args, theme, context);
151
+ tool.renderResult!(
152
+ {
153
+ content: [{ type: "text", text: "write failed\nimportant detail" }],
154
+ details: {
155
+ path: "a.txt",
156
+ created: false,
157
+ publication: "NOT_PUBLISHED",
158
+ publishedRevision: "r",
159
+ observedRevision: "r",
160
+ },
161
+ },
162
+ { isPartial: false, expanded: false },
163
+ theme,
164
+ context,
165
+ );
166
+ assert.match(card.render(160).join("\n"), /write failed[\s\S]*important detail/);
80
167
  });
81
168
 
82
169
  test("mutation previews hide CRLF boundaries even with mixed endings or an unterminated last line", () => {
83
- initTheme("dark");
84
- for (const before of ["old\r\ncontext\r\n", "old\r\ncontext\nlast", "old\r\ncontext\r\nlast"]) {
85
- const after = before.replace("old", "new");
86
- const details = generateMutationDetails("a.txt", before, after, { publishedRevision: "r", observedRevision: "r" }, "PUBLISHED");
87
- assert.equal(details.diff, displayCarriageReturns(generateDiffString(before, after).diff));
88
- assert.match(details.diff, /␍/);
89
- assert.ok(details.patch.includes("-old\r\n"));
90
- for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
91
- for (const expanded of [false, true]) {
92
- const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
93
- const rendered = tool.renderResult({ content: [{ type: "text", text: "Done" }], details }, { isPartial: false, expanded }, theme, context);
94
- const output = rendered.render(160).join("\n");
95
- assert.doesNotMatch(output, /␍/);
96
- assert.match(output, /old[\s\S]*new[\s\S]*context/);
97
- }
98
- }
99
- }
170
+ initTheme("dark");
171
+ for (const before of ["old\r\ncontext\r\n", "old\r\ncontext\nlast", "old\r\ncontext\r\nlast"]) {
172
+ const after = before.replace("old", "new");
173
+ const details = generateMutationDetails(
174
+ "a.txt",
175
+ before,
176
+ after,
177
+ { publishedRevision: "r", observedRevision: "r" },
178
+ "PUBLISHED",
179
+ );
180
+ assert.equal(details.diff, displayCarriageReturns(generateDiffString(before, after).diff));
181
+ assert.match(details.diff, /␍/);
182
+ assert.ok(details.patch.includes("-old\r\n"));
183
+ for (const tool of [makeEditOverride(process.cwd()), makeReplaceTool(process.cwd())]) {
184
+ for (const expanded of [false, true]) {
185
+ const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
186
+ const rendered = tool.renderResult(
187
+ { content: [{ type: "text", text: "Done" }], details },
188
+ { isPartial: false, expanded },
189
+ theme,
190
+ context,
191
+ );
192
+ const output = rendered.render(160).join("\n");
193
+ assert.doesNotMatch(output, /␍/);
194
+ assert.match(output, /old[\s\S]*new[\s\S]*context/);
195
+ }
196
+ }
197
+ }
100
198
  });
101
199
 
102
200
  test("diff previews retain standalone CR and literal control-picture characters", () => {
103
- initTheme("dark");
104
- for (const before of ["old\r", "old␍", "old\rcontent\r\n"]) {
105
- const details = generateMutationDetails("a.txt", before, before.replace("old", "new"), { publishedRevision: "r", observedRevision: "r" }, "PUBLISHED");
106
- const tool = makeEditOverride(process.cwd());
107
- const result = tool.renderResult({ content: [], details }, { expanded: true }, theme, { args: { path: "a.txt" }, state: {}, isError: false });
108
- assert.match(result.render(160).join("\n"), /␍/);
109
- }
110
- assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
201
+ initTheme("dark");
202
+ for (const before of ["old\r", "old␍", "old\rcontent\r\n"]) {
203
+ const details = generateMutationDetails(
204
+ "a.txt",
205
+ before,
206
+ before.replace("old", "new"),
207
+ { publishedRevision: "r", observedRevision: "r" },
208
+ "PUBLISHED",
209
+ );
210
+ const tool = makeEditOverride(process.cwd());
211
+ const result = tool.renderResult(
212
+ { content: [], details },
213
+ { expanded: true, isPartial: false },
214
+ theme,
215
+ {
216
+ args: { path: "a.txt", edits: [{ op: "append", body: ["new"] }] },
217
+ state: {},
218
+ isError: false,
219
+ } as Parameters<typeof tool.renderResult>[3],
220
+ );
221
+ assert.match(result.render(160).join("\n"), /␍/);
222
+ }
223
+ assert.match(renderDiffPreview("-1 old␍\n+1 new␍", true, theme), /␍/);
224
+ });
225
+
226
+ test("withMutationStatus renderResult initializes mutationShell defensively", () => {
227
+ initTheme("dark");
228
+ const tool = withMutationStatus(makeEditOverride(process.cwd()));
229
+ const context: any = { args: { path: "a.txt" }, state: {}, isError: false };
230
+ const container = tool.renderResult!(
231
+ {
232
+ content: [{ type: "text", text: "Edited a.txt." }],
233
+ details: mutationDetails({
234
+ publication: "PUBLISHED",
235
+ freshness: "unchanged",
236
+ command: "not_requested",
237
+ }),
238
+ },
239
+ { isPartial: false, expanded: false },
240
+ theme,
241
+ context,
242
+ );
243
+ assert.ok(container);
244
+ assert.ok(context.state.mutationShell);
245
+ assert.ok(context.state.mutationShell.box);
111
246
  });
package/src/pi/render.ts CHANGED
@@ -9,16 +9,23 @@
9
9
  * @module pi-hashline-edit/pi
10
10
  */
11
11
 
12
- import { renderDiff, type ToolDefinition } from "@earendil-works/pi-coding-agent";
13
- import { Box, Container, Text } from "@earendil-works/pi-tui";
12
+ import {
13
+ renderDiff,
14
+ type Theme,
15
+ type ToolDefinition,
16
+ type ToolRenderResultOptions,
17
+ } from "@earendil-works/pi-coding-agent";
18
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
19
+ import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
20
+ import type { TSchema } from "typebox";
14
21
 
15
22
  const HASHLINE_RE = /^(\d+)#[A-Za-z0-9]+│(.*)$/;
16
23
 
17
24
  export interface HashlineRow {
18
- /** Line number as written in the anchor (string form). */
19
- lineNo: string;
20
- /** Line content with the `LINE#HASH│` prefix removed. */
21
- content: string;
25
+ /** Line number as written in the anchor (string form). */
26
+ lineNo: string;
27
+ /** Line content with the `LINE#HASH│` prefix removed. */
28
+ content: string;
22
29
  }
23
30
 
24
31
  /**
@@ -28,8 +35,8 @@ export interface HashlineRow {
28
35
  * text) so callers can fall through to their own formatting.
29
36
  */
30
37
  export function parseHashline(line: string): HashlineRow | null {
31
- const m = line.match(HASHLINE_RE);
32
- return m ? { lineNo: m[1], content: m[2] } : null;
38
+ const m = line.match(HASHLINE_RE);
39
+ return m ? { lineNo: m[1], content: m[2] } : null;
33
40
  }
34
41
 
35
42
  /** Max diff lines shown when a result is rendered collapsed. */
@@ -42,37 +49,48 @@ const MAX_COLLAPSED_DIFF_LINES = 24;
42
49
  * first 24 rendered lines with an overflow marker — truncating after rendering
43
50
  * keeps `-`/`+` pairs intact so the intra-line highlight never dangles.
44
51
  */
45
- export function renderDiffPreview(diff: string, expanded: boolean, theme: any): string {
46
- const rendered = renderDiff(diff);
47
- if (expanded) return rendered;
48
- const allLines = rendered.split("\n");
49
- const more =
50
- allLines.length > MAX_COLLAPSED_DIFF_LINES
51
- ? `\n${theme.fg("dim", `… (${allLines.length - MAX_COLLAPSED_DIFF_LINES} more)`)}`
52
- : "";
53
- return allLines.slice(0, MAX_COLLAPSED_DIFF_LINES).join("\n") + more;
52
+ export function renderDiffPreview(diff: string, expanded: boolean, theme: Theme): string {
53
+ const rendered = renderDiff(diff);
54
+ if (expanded) return rendered;
55
+ const allLines = rendered.split("\n");
56
+ const more =
57
+ allLines.length > MAX_COLLAPSED_DIFF_LINES
58
+ ? `\n${theme.fg("dim", `… (${allLines.length - MAX_COLLAPSED_DIFF_LINES} more)`)}`
59
+ : "";
60
+ return allLines.slice(0, MAX_COLLAPSED_DIFF_LINES).join("\n") + more;
54
61
  }
55
62
 
56
63
  /** Added/removed line counts of a pi-format diff string (`+N`/`-N` leading char). */
57
64
  export interface DiffCounts {
58
- added: number;
59
- removed: number;
65
+ added: number;
66
+ removed: number;
67
+ }
68
+
69
+ interface MutationRenderState {
70
+ diffCounts?: DiffCounts;
71
+ callText?: Text;
72
+ mutationShell?: {
73
+ box: Box;
74
+ call?: Component;
75
+ result?: Component;
76
+ fileState?: { freshness?: string };
77
+ };
60
78
  }
61
79
 
62
80
  /** Count added/removed lines in a pi-format diff (`+N content` / `-N content` / ` N content`). */
63
81
  export function countDiffLines(diff: string): DiffCounts {
64
- let added = 0;
65
- let removed = 0;
66
- for (const line of diff.split("\n")) {
67
- if (line.startsWith("+")) added++;
68
- else if (line.startsWith("-")) removed++;
69
- }
70
- return { added, removed };
82
+ let added = 0;
83
+ let removed = 0;
84
+ for (const line of diff.split("\n")) {
85
+ if (line.startsWith("+")) added++;
86
+ else if (line.startsWith("-")) removed++;
87
+ }
88
+ return { added, removed };
71
89
  }
72
90
 
73
91
  /** Format `+N -N` with the theme's diff colors for the tool call header. */
74
- export function formatDiffCounts(counts: DiffCounts, theme: any): string {
75
- return ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`;
92
+ export function formatDiffCounts(counts: DiffCounts, theme: Theme): string {
93
+ return ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`;
76
94
  }
77
95
 
78
96
  /**
@@ -92,86 +110,125 @@ export function formatDiffCounts(counts: DiffCounts, theme: any): string {
92
110
  * component after the nested one — the diff renders twice.
93
111
  */
94
112
  export function publishDiffCounts(
95
- diff: string | undefined,
96
- context: any,
97
- refreshHeader: (counts: DiffCounts) => void,
113
+ diff: string | undefined,
114
+ context: { state?: MutationRenderState },
115
+ refreshHeader: (counts: DiffCounts) => void,
98
116
  ): void {
99
- if (!diff || !context?.state) return;
100
- const counts = countDiffLines(diff);
101
- const prev: DiffCounts | undefined = context.state.diffCounts;
102
- context.state.diffCounts = counts;
103
- if (!prev || prev.added !== counts.added || prev.removed !== counts.removed) refreshHeader(counts);
117
+ if (!diff || !context?.state) return;
118
+ const counts = countDiffLines(diff);
119
+ const prev: DiffCounts | undefined = context.state.diffCounts;
120
+ context.state.diffCounts = counts;
121
+ if (!prev || prev.added !== counts.added || prev.removed !== counts.removed)
122
+ refreshHeader(counts);
104
123
  }
105
124
 
106
125
  /** Reuse the call component and retain it for the result's in-place count refresh. */
107
- export function renderMutationCall(
108
- args: any, theme: any, context: any, header: (args: any, theme: any, counts?: DiffCounts) => string,
126
+ export function renderMutationCall<TArgs>(
127
+ args: TArgs,
128
+ theme: Theme,
129
+ context: { lastComponent?: Component; state?: MutationRenderState },
130
+ header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
109
131
  ): Text {
110
- const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
111
- if (context?.state) context.state.callText = text;
112
- text.setText(header(args, theme, context?.state?.diffCounts));
113
- return text;
132
+ const text = (context?.lastComponent as Text | undefined) ?? new Text("", 0, 0);
133
+ if (context?.state) context.state.callText = text;
134
+ text.setText(header(args, theme, context?.state?.diffCounts));
135
+ return text;
114
136
  }
115
137
 
116
138
  /** Keep model-facing diagnostic details out of the compact error row. */
117
- export function renderToolError(result: any, theme: any): Text {
118
- const content = result.content?.[0];
119
- const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
120
- return new Text(theme.fg("error", text), 0, 0);
139
+ export function renderToolError(
140
+ result: Pick<AgentToolResult<unknown>, "content">,
141
+ theme: Theme,
142
+ ): Text {
143
+ const content = result.content?.[0];
144
+ const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
145
+ return new Text(theme.fg("error", text), 0, 0);
121
146
  }
122
147
 
123
148
  /** Render mutation status or a diff, refreshing the call header's counts in place. */
124
- export function renderMutationResult(
125
- result: any, { isPartial, expanded }: any, theme: any, context: any,
126
- pending: string, fallback: string, header: (args: any, theme: any, counts?: DiffCounts) => string,
149
+ export function renderMutationResult<TArgs>(
150
+ result: AgentToolResult<{
151
+ displayDiff?: string;
152
+ diff?: string;
153
+ actionFusion?: { publication?: string };
154
+ }>,
155
+ { isPartial, expanded }: ToolRenderResultOptions,
156
+ theme: Theme,
157
+ context: { isError: boolean; args: TArgs; state?: MutationRenderState },
158
+ pending: string,
159
+ fallback: string,
160
+ header: (args: TArgs, theme: Theme, counts?: DiffCounts) => string,
127
161
  ): Text {
128
- if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
129
- const content = result.content?.[0];
130
- if (context.isError) return renderToolError(result, theme);
131
- const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
132
- // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
133
- publishDiffCounts(diff, context, (counts) => {
134
- context.state?.callText?.setText(header(context.args, theme, counts));
135
- });
136
- if (!diff) {
137
- // Only the summary is displayed; subsequent anchor rows are for the model.
138
- const summary = content?.type === "text" ? content.text.split("\n")[0] : fallback;
139
- return new Text(theme.fg("success", summary), 0, 0);
140
- }
141
- return new Text(renderDiffPreview(diff, expanded, theme), 0, 0);
162
+ if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED")
163
+ return new Text(theme.fg("warning", pending), 0, 0);
164
+ const content = result.content?.[0];
165
+ if (context.isError) return renderToolError(result, theme);
166
+ const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
167
+ // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
168
+ publishDiffCounts(diff, context, (counts) => {
169
+ context.state?.callText?.setText(header(context.args, theme, counts));
170
+ });
171
+ if (!diff) {
172
+ // Only the summary is displayed; subsequent anchor rows are for the model.
173
+ const summary = content?.type === "text" ? content.text.split("\n")[0] : fallback;
174
+ return new Text(theme.fg("success", summary), 0, 0);
175
+ }
176
+ return new Text(renderDiffPreview(diff, expanded, theme), 0, 0);
142
177
  }
143
178
 
144
179
  /** Keep the mutation card's background independent of the fused command's lifetime. */
145
- export function withMutationStatus(tool: ToolDefinition<any, any, any>): ToolDefinition<any, any, any> {
146
- return {
147
- ...tool,
148
- renderShell: "self",
149
- renderCall(args, theme, context) {
150
- const shell = context.state.mutationShell ??= { box: new Box(1, 1) };
151
- shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
152
- shell.box.clear();
153
- shell.box.addChild(shell.call);
154
- shell.box.setBgFn((line: string) => theme.bg(context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
155
- return shell.box;
156
- },
157
- renderResult(result, options, theme, context) {
158
- const shell = context.state.mutationShell;
159
- const isPartial = options.isPartial && result.details?.actionFusion?.mutationCompleted !== true;
160
- // Fused errors retain combined details for the model; show the mutation's summary here.
161
- const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
162
- shell.result = fusedError ? renderToolError(result, theme)
163
- : tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
164
- // Pi runs renderCall first; update its box in place without invalidating the tool row.
165
- shell.box.addChild(shell.result);
166
- const file = result.details?.actionFusion ?? shell.fileState;
167
- if (file) {
168
- shell.fileState = { freshness: file.freshness };
169
- if (file.freshness === "changed" || file.freshness === "missing") {
170
- shell.box.addChild(new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0));
171
- }
172
- }
173
- shell.box.setBgFn((line: string) => theme.bg(isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
174
- return new Container();
175
- },
176
- };
180
+ export function withMutationStatus<TParams extends TSchema, TDetails>(
181
+ tool: ToolDefinition<TParams, TDetails, MutationRenderState>,
182
+ ): ToolDefinition<TParams, TDetails, MutationRenderState> {
183
+ return {
184
+ ...tool,
185
+ renderShell: "self",
186
+ renderCall(args, theme, context) {
187
+ const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
188
+ shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
189
+ shell.box.clear();
190
+ shell.box.addChild(shell.call);
191
+ shell.box.setBgFn((line: string) =>
192
+ theme.bg(
193
+ context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
194
+ line,
195
+ ),
196
+ );
197
+ return shell.box;
198
+ },
199
+ renderResult(result, options, theme, context) {
200
+ const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
201
+ const details = result.details as
202
+ | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
203
+ | undefined;
204
+ const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
205
+ // Fused errors retain combined details for the model; show the mutation's summary here.
206
+ const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
207
+ shell.result = fusedError
208
+ ? renderToolError(result, theme)
209
+ : tool.renderResult!(result, { ...options, isPartial }, theme, {
210
+ ...context,
211
+ isPartial,
212
+ lastComponent: shell.result,
213
+ });
214
+ // Pi runs renderCall first; update its box in place without invalidating the tool row.
215
+ shell.box.addChild(shell.result);
216
+ const file = details?.actionFusion ?? shell.fileState;
217
+ if (file) {
218
+ shell.fileState = { freshness: file.freshness };
219
+ if (file.freshness === "changed" || file.freshness === "missing") {
220
+ shell.box.addChild(
221
+ new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
222
+ );
223
+ }
224
+ }
225
+ shell.box.setBgFn((line: string) =>
226
+ theme.bg(
227
+ isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
228
+ line,
229
+ ),
230
+ );
231
+ return new Container();
232
+ },
233
+ };
177
234
  }