@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -0,0 +1,214 @@
1
+ /** Independent argument checks for the file operation and its optional Bash command. */
2
+ import { isProxy } from "node:util/types";
3
+ import { Type, type Static, type TObject, type TProperties } from "typebox";
4
+ import { errorMessage } from "../core/errors.ts";
5
+ import {
6
+ cloneArguments,
7
+ createArgumentBoundary,
8
+ noArgumentProduct,
9
+ type CheckArguments,
10
+ } from "./argument-validation.ts";
11
+ import { reportOf } from "./report.ts";
12
+ import type { OutputBudgetProvider } from "./budgets.ts";
13
+ import type { MutationToolName } from "./report-schema.ts";
14
+
15
+ export const MILLISECONDS_PER_SECOND = 1_000;
16
+ // Pi's built-in Bash rejects timeouts above the setTimeout millisecond limit.
17
+ export const MAX_BASH_TIMEOUT_SECONDS = 2_147_483_647 / MILLISECONDS_PER_SECOND;
18
+
19
+ const command = Type.String({ description: "Bash command to run." });
20
+ const timeout = Type.Optional(
21
+ Type.Number({
22
+ exclusiveMinimum: 0,
23
+ maximum: MAX_BASH_TIMEOUT_SECONDS,
24
+ description: "Timeout in seconds; none when omitted.",
25
+ }),
26
+ );
27
+ const commandArguments = Type.Object(
28
+ {
29
+ then_run: Type.Optional(
30
+ Type.Object(
31
+ {
32
+ command: Type.String({ ...command, pattern: "\\S" }),
33
+ timeout,
34
+ },
35
+ { additionalProperties: false },
36
+ ),
37
+ ),
38
+ },
39
+ { additionalProperties: false },
40
+ );
41
+ export type ThenRunInput = NonNullable<Static<typeof commandArguments>["then_run"]>;
42
+ export type ThenRunRequest =
43
+ | ThenRunInput
44
+ | { readonly commandText: string; readonly error: string };
45
+
46
+ // Pi clones and validates prepared arguments before hooks. Keep a rejected request present so a
47
+ // hook supplying defaults for an absent command cannot start Bash. Its empty command also fails
48
+ // the execution schema on its own. The diagnostic is never a shell argument.
49
+ const REJECTED = "__hashlineThenRunError";
50
+
51
+ function rawCommandText(value: unknown): string {
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "";
53
+ const text: unknown = Reflect.get(value, "command");
54
+ return typeof text === "string" ? text : "";
55
+ }
56
+
57
+ /** Let structuredClone observe fields in their original order and with the original receiver. */
58
+ function mapFollowUp(
59
+ input: unknown,
60
+ visit: (read: () => { then_run: unknown }) => unknown,
61
+ budgets: OutputBudgetProvider,
62
+ ): unknown {
63
+ if (
64
+ !input ||
65
+ typeof input !== "object" ||
66
+ Array.isArray(input) ||
67
+ isProxy(input) ||
68
+ !Object.prototype.propertyIsEnumerable.call(input, "then_run")
69
+ )
70
+ return input;
71
+ const proto: unknown = Object.getPrototypeOf(input);
72
+ if (proto !== null && proto !== Object.prototype) {
73
+ // Built-ins such as Date drop custom properties when cloned. Class instances become records.
74
+ return mapFollowUp(cloneArguments(input, budgets), visit, budgets);
75
+ }
76
+ const view = {};
77
+ for (const key of Object.keys(input)) {
78
+ Object.defineProperty(view, key, {
79
+ enumerable: true,
80
+ get:
81
+ key === "then_run"
82
+ ? () =>
83
+ visit(() =>
84
+ cloneArguments(
85
+ {
86
+ get then_run() {
87
+ return Reflect.get(input, key);
88
+ },
89
+ },
90
+ budgets,
91
+ "then_run",
92
+ ),
93
+ )
94
+ : () => Reflect.get(input, key),
95
+ });
96
+ }
97
+ return view;
98
+ }
99
+
100
+ export function createMutationArgumentBoundary<P extends TProperties, Parsed>(
101
+ schema: TObject<P>,
102
+ tool: MutationToolName,
103
+ actionFusion: boolean,
104
+ cwd: string,
105
+ budgets: OutputBudgetProvider,
106
+ check: CheckArguments<Parsed>,
107
+ ) {
108
+ if (!actionFusion) {
109
+ const file = createArgumentBoundary(schema, cwd, budgets, check);
110
+ return {
111
+ parameters: schema,
112
+ prepareArguments: file.prepareArguments,
113
+ afterHooks: (input: unknown) => ({ ...file.afterHooks(input), thenRun: undefined }),
114
+ };
115
+ }
116
+ const parameters = Type.Object(
117
+ {
118
+ ...schema.properties,
119
+ then_run: Type.Optional(
120
+ Type.Object(
121
+ { command, timeout },
122
+ {
123
+ description: `Command to run once after ${tool} succeeds; failure does not roll back the file.`,
124
+ },
125
+ ),
126
+ ),
127
+ },
128
+ { additionalProperties: false },
129
+ );
130
+ const file = createArgumentBoundary(
131
+ Type.Object(
132
+ { ...schema.properties, then_run: Type.Optional(Type.Unknown()) },
133
+ { additionalProperties: false },
134
+ ),
135
+ cwd,
136
+ budgets,
137
+ check,
138
+ );
139
+ const bash = createArgumentBoundary(commandArguments, cwd, budgets, () => noArgumentProduct);
140
+ return {
141
+ parameters,
142
+ prepareArguments(input: unknown): Static<typeof parameters> {
143
+ const prepared = file.prepareArguments(
144
+ mapFollowUp(
145
+ input,
146
+ (read) => {
147
+ let commandText = "";
148
+ try {
149
+ const snapshot = read();
150
+ commandText = rawCommandText(snapshot.then_run);
151
+ return bash.prepareArguments(snapshot).then_run;
152
+ } catch (error) {
153
+ return {
154
+ command: "",
155
+ [REJECTED]: { commandText, error: errorMessage(error) },
156
+ };
157
+ }
158
+ },
159
+ budgets,
160
+ ),
161
+ );
162
+ // Pi applies the registered schema's coercion to the same raw fields after preparation.
163
+ return prepared as Static<typeof parameters>;
164
+ },
165
+ afterHooks(input: unknown) {
166
+ let thenRun: ThenRunRequest | undefined;
167
+ const mutation = file.afterHooks(
168
+ mapFollowUp(
169
+ input,
170
+ (read) => {
171
+ let commandText = "";
172
+ try {
173
+ const snapshot = read();
174
+ const value = snapshot.then_run;
175
+ commandText = rawCommandText(value);
176
+ if (value && typeof value === "object" && Object.hasOwn(value, REJECTED)) {
177
+ const marker: unknown = Reflect.get(value, REJECTED);
178
+ const diagnostic: unknown =
179
+ marker && typeof marker === "object" ? Reflect.get(marker, "error") : undefined;
180
+ const rejectedCommand: unknown =
181
+ marker && typeof marker === "object"
182
+ ? Reflect.get(marker, "commandText")
183
+ : undefined;
184
+ const rejected =
185
+ typeof rejectedCommand === "string" &&
186
+ typeof diagnostic === "string" &&
187
+ Buffer.byteLength(diagnostic) <= budgets().blockBytes &&
188
+ reportOf({ content: [{ type: "text", text: diagnostic }] }, tool)?.error ===
189
+ "INVALID_ARGUMENTS";
190
+ if (
191
+ rejected &&
192
+ Object.keys(value).length === 2 &&
193
+ Reflect.get(value, "command") === ""
194
+ ) {
195
+ thenRun = { commandText: rejectedCommand, error: diagnostic };
196
+ return undefined;
197
+ }
198
+ if (rejected) Reflect.deleteProperty(value, REJECTED);
199
+ }
200
+ thenRun = bash.afterHooks(snapshot).args.then_run;
201
+ } catch (error) {
202
+ thenRun = { commandText, error: errorMessage(error) };
203
+ }
204
+ return undefined;
205
+ },
206
+ budgets,
207
+ ),
208
+ );
209
+ // TypeBox cannot infer the base mapped type after removing the independently checked field.
210
+ Reflect.deleteProperty(mutation.args, "then_run");
211
+ return { ...mutation, args: mutation.args as Static<typeof schema>, thenRun };
212
+ },
213
+ };
214
+ }
@@ -8,14 +8,12 @@
8
8
  import type {
9
9
  ExtensionAPI,
10
10
  ExtensionContext,
11
+ ThemeBg,
12
+ ThemeColor,
11
13
  ToolDefinition,
12
14
  ToolRenderers,
13
15
  } from "@earendil-works/pi-coding-agent";
14
- import {
15
- createBashToolDefinition,
16
- SettingsManager,
17
- ToolExecutionComponent,
18
- } from "@earendil-works/pi-coding-agent";
16
+ import { SettingsManager, ToolExecutionComponent } from "@earendil-works/pi-coding-agent";
19
17
  import {
20
18
  Box,
21
19
  Container,
@@ -27,21 +25,85 @@ import {
27
25
  import type { TSchema } from "typebox";
28
26
  import { Value } from "typebox/value";
29
27
  import { ACTION_FUSION_PROGRESS_SCHEMA, type ActionFusionProgress } from "./report-schema.ts";
30
- import { commandText } from "./mutation-result.ts";
28
+ import { nativeBash } from "./native-bash.ts";
31
29
  import type { MutationRenderState } from "./render.ts";
30
+ import type { ToolGuidelines } from "./schema.ts";
32
31
 
33
32
  const CARD_TYPE = "hashline-then-run";
34
33
  const RESULT_TYPE = "hashline-then-run-result";
35
34
 
36
- /** A command card persists its progress as is; restored entries are checked against the same schema. */
37
- const COMMAND_CARD_SCHEMA = ACTION_FUSION_PROGRESS_SCHEMA;
38
35
  type CommandCardData = ActionFusionProgress;
39
36
 
37
+ function isRecord(value: unknown): value is Record<string, unknown> {
38
+ return value !== null && typeof value === "object" && !Array.isArray(value);
39
+ }
40
+
41
+ /** Snapshot the JSON representation of the fields Pi's Bash renderer reads. */
42
+ export function projectBashDetails(details: unknown): unknown {
43
+ if (!isRecord(details)) return undefined;
44
+ const { fullOutputPath, truncation } = details;
45
+ return JSON.parse(
46
+ JSON.stringify({
47
+ fullOutputPath,
48
+ truncation: isRecord(truncation)
49
+ ? {
50
+ truncated: truncation.truncated,
51
+ truncatedBy: truncation.truncatedBy,
52
+ outputLines: truncation.outputLines,
53
+ totalLines: truncation.totalLines,
54
+ maxBytes: truncation.maxBytes,
55
+ }
56
+ : undefined,
57
+ }),
58
+ );
59
+ }
60
+
61
+ function decodeCard(read: () => unknown): CommandCardData | undefined {
62
+ try {
63
+ const source = read();
64
+ if (!isRecord(source)) return undefined;
65
+ const card = { ...source };
66
+ if (isRecord(card.result)) {
67
+ const result = { ...card.result };
68
+ const details = projectBashDetails(result.details);
69
+ if (details === undefined) delete result.details;
70
+ else result.details = details;
71
+ card.result = result;
72
+ }
73
+ const data: unknown = structuredClone(card);
74
+ if (!Value.Check(ACTION_FUSION_PROGRESS_SCHEMA, data)) return undefined;
75
+ const content = data.result?.content;
76
+ // Pi calls array methods outside its renderer guard. Accept only dense, indexed content.
77
+ if (content) {
78
+ const keys = Object.keys(content);
79
+ if (keys.length !== content.length || keys.some((key, i) => key !== String(i)))
80
+ return undefined;
81
+ }
82
+ return data;
83
+ } catch {
84
+ // Foreign entries may throw during access, cloning, or schema inspection.
85
+ return undefined;
86
+ }
87
+ }
88
+
40
89
  const commandPending = ({ command }: CommandCardData) =>
41
90
  command === "waiting" || command === "running";
42
91
  const commandFailed = ({ command }: CommandCardData) =>
43
92
  command === "failed" || command === "timeout";
44
93
 
94
+ const INTERRUPTED = "interrupted (final status unknown)";
95
+ type DisplayState = CommandCardData["command"] | typeof INTERRUPTED;
96
+ const CARD_COLORS = {
97
+ waiting: ["warning", "toolPendingBg"],
98
+ running: ["warning", "toolPendingBg"],
99
+ [INTERRUPTED]: ["warning", "customMessageBg"],
100
+ cancelled: ["warning", "customMessageBg"],
101
+ failed: ["error", "toolErrorBg"],
102
+ timeout: ["error", "toolErrorBg"],
103
+ succeeded: ["success", "toolSuccessBg"],
104
+ skipped: ["dim", "customMessageBg"],
105
+ } satisfies Record<DisplayState, [ThemeColor, ThemeBg]>;
106
+
45
107
  const TARGET_STATE = {
46
108
  changed: "the target changed after the mutation",
47
109
  missing: "the target is missing after the mutation",
@@ -53,8 +115,8 @@ const TARGET_STATE = {
53
115
  * states: whether the mutation completed and the target's freshness.
54
116
  */
55
117
  function notRunReason(card: CommandCardData): string | undefined {
56
- if (card.command === "cancelled" && !(card.result && commandText(card.result.content)))
57
- return "Not run: cancelled.";
118
+ // A cancelled command that started has a result, even an empty one.
119
+ if (card.command === "cancelled" && card.result === undefined) return "Not run: cancelled.";
58
120
  if (card.command !== "skipped") return undefined;
59
121
  const { mutationCompleted, freshness } = card;
60
122
  if (!mutationCompleted) return "Not run: the mutation did not complete.";
@@ -93,7 +155,6 @@ class CommandEntryComponent extends ToolExecutionComponent {
93
155
  /** Render one durable transcript card per fused command without adding model context. */
94
156
  export function registerFusionCards(pi: ExtensionAPI) {
95
157
  let currentCwd = process.cwd();
96
- const bash = createBashToolDefinition(process.cwd());
97
158
  const states = new Map<string, CommandCardData>();
98
159
  const active = new Set<string>();
99
160
  const cards = new Map<string, CommandEntryComponent>();
@@ -105,13 +166,13 @@ export function registerFusionCards(pi: ExtensionAPI) {
105
166
  active.clear();
106
167
  cards.clear();
107
168
  for (const entry of ctx.sessionManager.getBranch()) {
108
- if (
109
- entry.type !== "custom" ||
110
- (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)
111
- )
112
- continue;
113
- const data = entry.data;
114
- if (Value.Check(COMMAND_CARD_SCHEMA, data)) states.set(data.toolCallId, data);
169
+ const data = decodeCard(() =>
170
+ entry.type === "custom" &&
171
+ (entry.customType === CARD_TYPE || entry.customType === RESULT_TYPE)
172
+ ? entry.data
173
+ : undefined,
174
+ );
175
+ if (data) states.set(data.toolCallId, data);
115
176
  }
116
177
  };
117
178
  pi.on("session_start", (_event, ctx) => {
@@ -132,16 +193,11 @@ export function registerFusionCards(pi: ExtensionAPI) {
132
193
  });
133
194
  pi.on("session_tree", (_event, ctx) => restore(ctx));
134
195
 
135
- pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, options):
136
- | Component
137
- | undefined {
138
- const { expanded } = options;
139
- const initial = entry.data;
140
- if (!Value.Check(COMMAND_CARD_SCHEMA, initial)) return undefined;
196
+ function renderCard(initial: CommandCardData, expanded: boolean): Component {
141
197
  if (!tui) {
142
198
  // Pi may rebuild history before session_start supplies its UI context.
143
199
  let component: Component | undefined;
144
- const ready = () => (component ??= tui ? renderCard(entry, options) : undefined);
200
+ const ready = () => (component ??= tui ? renderCard(initial, expanded) : undefined);
145
201
  return {
146
202
  render: (width) => ready()?.render(width) ?? [],
147
203
  invalidate: () => component?.invalidate(),
@@ -153,49 +209,27 @@ export function registerFusionCards(pi: ExtensionAPI) {
153
209
  if (!card) {
154
210
  const current = () => states.get(initial.toolCallId) ?? initial;
155
211
  const statusText = new Text("", 0, 0);
156
- let outputPadding = settings.getOutputPad();
157
- let box = new Box(outputPadding, 1);
212
+ const box = new Box(0, 1);
158
213
  let call: Component | undefined;
159
214
  let result: Component | undefined;
160
215
  const renderers: ToolRenderers = {
161
216
  renderShell: "self",
162
217
  renderCall(_args, theme, context) {
163
- const padding = SettingsManager.inMemory(pi.getSettings()).getOutputPad();
164
- if (padding !== outputPadding) {
165
- outputPadding = padding;
166
- box = new Box(outputPadding, 1);
167
- }
218
+ box.setPaddingX(context.outputPad);
168
219
  const value = current();
169
220
  const args = { command: value.commandText, timeout: value.timing?.timeoutSeconds };
170
- const pending = commandPending(value);
171
- const interrupted = pending && !active.has(value.toolCallId);
172
- const status = interrupted ? "interrupted (final status unknown)" : value.command;
221
+ const status =
222
+ commandPending(value) && !active.has(value.toolCallId) ? INTERRUPTED : value.command;
173
223
  const countdown =
174
- value.command === "running" && !interrupted && value.timing
224
+ status === "running" && value.timing
175
225
  ? ` · ${value.timing.remainingSeconds}s remaining`
176
226
  : "";
177
- const failed = commandFailed(value);
178
- const color =
179
- pending || value.command === "cancelled"
180
- ? "warning"
181
- : failed
182
- ? "error"
183
- : value.command === "succeeded"
184
- ? "success"
185
- : "dim";
186
- const background =
187
- pending && !interrupted
188
- ? "toolPendingBg"
189
- : failed
190
- ? "toolErrorBg"
191
- : value.command === "succeeded"
192
- ? "toolSuccessBg"
193
- : "customMessageBg";
227
+ const [color, background] = CARD_COLORS[status];
194
228
  box.setBgFn((line) => theme.bg(background, line));
195
229
  statusText.setText(
196
230
  `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
197
231
  );
198
- call = bash.renderCall!(args, theme, { ...context, args, lastComponent: call });
232
+ call = nativeBash.renderCall!(args, theme, { ...context, args, lastComponent: call });
199
233
  box.clear();
200
234
  box.addChild(statusText);
201
235
  box.addChild(call);
@@ -206,7 +240,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
206
240
  renderResult(value, options, theme, context) {
207
241
  // Every command that ran or failed to start has a result; waiting and skipped ones do not.
208
242
  if (current().result) {
209
- result = bash.renderResult!(value, options, theme, {
243
+ result = nativeBash.renderResult!(value, options, theme, {
210
244
  ...context,
211
245
  args: { command: current().commandText, timeout: current().timing?.timeoutSeconds },
212
246
  lastComponent: result,
@@ -248,21 +282,29 @@ export function registerFusionCards(pi: ExtensionAPI) {
248
282
  card.setArgsComplete();
249
283
  cards.set(initial.toolCallId, card);
250
284
  }
285
+ card.setOutputPad(settings.getOutputPad());
251
286
  card.setShowImages(settings.getShowImages());
252
287
  card.setImageWidthCells(settings.getImageWidthCells());
253
288
  card.setGlobalExpanded(expanded);
254
289
  return card;
290
+ }
291
+
292
+ pi.registerEntryRenderer(CARD_TYPE, (entry, { expanded }) => {
293
+ const data = decodeCard(() => entry.data);
294
+ return data && renderCard(data, expanded);
255
295
  });
256
296
 
257
- return (progress: ActionFusionProgress) => {
297
+ return (input: ActionFusionProgress) => {
298
+ const progress = decodeCard(() => input);
299
+ if (!progress) throw new Error("Invalid then_run card progress.");
258
300
  const first = !states.has(progress.toolCallId);
259
301
  states.set(progress.toolCallId, progress);
260
302
  const pending = commandPending(progress);
261
303
  if (pending) active.add(progress.toolCallId);
262
304
  else active.delete(progress.toolCallId);
263
305
  // Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
264
- if (first) pi.appendEntry(CARD_TYPE, progress);
265
- if (!pending) pi.appendEntry(RESULT_TYPE, progress);
306
+ if (first) pi.appendEntry(CARD_TYPE, structuredClone(progress));
307
+ if (!pending) pi.appendEntry(RESULT_TYPE, structuredClone(progress));
266
308
  };
267
309
  }
268
310
 
@@ -284,8 +326,8 @@ interface FusedMutationRenderState extends MutationRenderState {
284
326
 
285
327
  /** Finish the mutation card independently while the fused command remains active. */
286
328
  export function withMutationStatus<TParams extends TSchema, TDetails>(
287
- tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
288
- ): ToolDefinition<TParams, TDetails, FusedMutationRenderState> {
329
+ tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState> & ToolGuidelines,
330
+ ): ToolDefinition<TParams, TDetails, FusedMutationRenderState> & ToolGuidelines {
289
331
  return {
290
332
  ...tool,
291
333
  renderShell: "self",
@@ -21,9 +21,12 @@ import {
21
21
  rgRejectsPatterns,
22
22
  runRgLines,
23
23
  runRgPaths,
24
+ searchDiagnostic,
25
+ type CandidateLines,
24
26
  type RgRunResult,
25
27
  } from "./rg-process.ts";
26
28
  import { lineCandidatePatterns, rgCodePoint } from "./rg-regex.ts";
29
+ import type { SearchWarning } from "./error-text.ts";
27
30
 
28
31
  /** Beyond this many candidate lines, a file's every line is checked instead. */
29
32
  const MAX_CANDIDATE_LINES = 64 * 1024;
@@ -35,10 +38,10 @@ export const MAX_UNNARROWED_SCAN_BYTES = 256 * 1024 * 1024;
35
38
  /** Candidate patterns match original bytes exactly as written; JavaScript decides case and encoding. */
36
39
  const BYTE_PATTERN_ARGS = ["--engine=default", "--case-sensitive", "--encoding=none"];
37
40
 
38
- /** An absolute file path to check: only its ascending candidate lines, or every line when absent. */
41
+ /** An absolute file path to check and its candidate lines. */
39
42
  export interface Candidate {
40
43
  readonly filePath: string;
41
- readonly lines?: readonly number[];
44
+ readonly lines: CandidateLines;
42
45
  }
43
46
 
44
47
  /** A literal's characters as one rg pattern. */
@@ -58,11 +61,6 @@ interface PatternStage {
58
61
  readonly list: () => Promise<RgRunResult>;
59
62
  }
60
63
 
61
- function widenOnArgumentLimit(error: unknown): undefined {
62
- if (isRgArgumentLimit(error)) return undefined;
63
- throw error;
64
- }
65
-
66
64
  /**
67
65
  * Await each consumer for backpressure; false stops listing. The caller owns worker cleanup.
68
66
  * An empty scope lists nothing, because rg would search the working directory instead.
@@ -74,20 +72,22 @@ export async function listCandidates(options: {
74
72
  readonly stopped: () => boolean;
75
73
  readonly onCandidate: (candidate: Candidate) => Promise<boolean>;
76
74
  }): Promise<{
77
- readonly listing?: RgRunResult;
75
+ /** The listing's own diagnostic, if any. */
76
+ readonly warnings: readonly SearchWarning[];
78
77
  readonly scanLimitReached: boolean;
79
78
  }> {
80
79
  const { scope, query, signal, stopped, onCandidate } = options;
81
- if (scope.searchPaths.length === 0) return { scanLimitReached: false };
80
+ if (scope.searchPaths.length === 0) return { warnings: [], scanLimitReached: false };
81
+ const { cwd } = scope;
82
82
  let scanAll = false;
83
83
  let listedAny = false;
84
84
  let scanned = 0;
85
85
  let scanLimitReached = false;
86
86
  const seen = new ListedFiles();
87
- const offer = async (path: string, lines?: readonly number[]) => {
87
+ const offer = async (path: string, lines: CandidateLines) => {
88
88
  listedAny = true;
89
89
  if (stopped()) return false;
90
- const filePath = resolve(path);
90
+ const filePath = resolve(cwd, path);
91
91
  if (await seen.has(filePath)) return true;
92
92
  seen.add(filePath);
93
93
  if (scanAll) {
@@ -103,7 +103,7 @@ export async function listCandidates(options: {
103
103
  }
104
104
  return onCandidate({ filePath, lines });
105
105
  };
106
- const scoped = [...scopeArgs(scope), "--", ...scope.searchPaths];
106
+ const scoped = scopeArgs(scope);
107
107
 
108
108
  /** Narrowing listings, most selective first; each is derived only when the one before gives way. */
109
109
  function* patternStages(): Generator<PatternStage> {
@@ -121,6 +121,7 @@ export async function listCandidates(options: {
121
121
  ...patternArgs,
122
122
  ...scoped,
123
123
  ],
124
+ cwd,
124
125
  signal,
125
126
  MAX_CANDIDATE_LINES,
126
127
  offer,
@@ -144,8 +145,9 @@ export async function listCandidates(options: {
144
145
  "--null",
145
146
  ...scoped,
146
147
  ],
148
+ cwd,
147
149
  signal,
148
- offer,
150
+ (path) => offer(path, "all"),
149
151
  ),
150
152
  };
151
153
  }
@@ -154,19 +156,30 @@ export async function listCandidates(options: {
154
156
  // before offering any candidate because it rejects the patterns. A completed listing that only
155
157
  // hit unreadable paths also exits with 2, and stands.
156
158
  for (const { patternArgs, list } of patternStages()) {
157
- const listing = await list().catch(widenOnArgumentLimit);
158
- const givesWay =
159
- !listing ||
160
- (listing.code === 2 &&
161
- !listedAny &&
162
- (await rgRejectsPatterns([...BYTE_PATTERN_ARGS, ...patternArgs], signal)));
163
- if (!givesWay) return { listing, scanLimitReached };
159
+ let listing: RgRunResult;
160
+ try {
161
+ listing = await list();
162
+ } catch (error) {
163
+ if (isRgArgumentLimit(error)) continue;
164
+ throw error;
165
+ }
166
+ const rejected =
167
+ listing.code === 2 &&
168
+ !listedAny &&
169
+ (await rgRejectsPatterns([...BYTE_PATTERN_ARGS, ...patternArgs], cwd, signal));
170
+ if (!rejected) return { warnings: listingWarnings(listing), scanLimitReached };
164
171
  }
165
172
  scanAll = true;
166
173
  const listing = await runRgPaths(
167
174
  [...COMMON_RG_ARGS, "--files", "--null", ...scoped],
175
+ cwd,
168
176
  signal,
169
- offer,
177
+ (path) => offer(path, "all"),
170
178
  );
171
- return { listing, scanLimitReached };
179
+ return { warnings: listingWarnings(listing), scanLimitReached };
180
+ }
181
+
182
+ function listingWarnings(listing: RgRunResult): readonly SearchWarning[] {
183
+ const diagnostic = searchDiagnostic(listing);
184
+ return diagnostic ? [diagnostic] : [];
172
185
  }