pi-rtk-optimizer 0.3.3 → 0.5.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 (38) hide show
  1. package/CHANGELOG.md +102 -67
  2. package/README.md +292 -290
  3. package/config/config.example.json +36 -35
  4. package/package.json +4 -4
  5. package/src/additional-coverage-test.ts +278 -0
  6. package/src/boolean-format.ts +3 -0
  7. package/src/command-rewriter-test.ts +160 -120
  8. package/src/command-rewriter.ts +594 -585
  9. package/src/config-modal-test.ts +168 -0
  10. package/src/config-modal.ts +613 -600
  11. package/src/config-store.ts +224 -217
  12. package/src/index-test.ts +54 -0
  13. package/src/index.ts +410 -289
  14. package/src/output-compactor-test.ts +500 -158
  15. package/src/output-compactor.ts +432 -349
  16. package/src/record-utils.ts +6 -0
  17. package/src/rewrite-bypass.ts +332 -173
  18. package/src/rewrite-pipeline-safety.ts +154 -0
  19. package/src/rewrite-rules.ts +255 -255
  20. package/src/rtk-command-environment.ts +64 -0
  21. package/src/runtime-guard-test.ts +42 -50
  22. package/src/runtime-guard.ts +14 -14
  23. package/src/techniques/build.ts +155 -155
  24. package/src/techniques/emoji.ts +91 -0
  25. package/src/techniques/git.ts +231 -229
  26. package/src/techniques/index.ts +10 -16
  27. package/src/techniques/linter.ts +151 -161
  28. package/src/techniques/path-utils.ts +67 -0
  29. package/src/techniques/rtk.ts +136 -0
  30. package/src/techniques/search.ts +67 -76
  31. package/src/techniques/source.ts +253 -253
  32. package/src/techniques/test-output.ts +172 -172
  33. package/src/test-helpers.ts +10 -0
  34. package/src/tool-execution-sanitizer.ts +69 -0
  35. package/src/types-shims.d.ts +192 -183
  36. package/src/types.ts +103 -114
  37. package/src/zellij-modal.ts +1001 -1001
  38. package/src/compat-commands.ts +0 -207
@@ -0,0 +1,6 @@
1
+ export function toRecord(value: unknown): Record<string, unknown> {
2
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
3
+ return {};
4
+ }
5
+ return value as Record<string, unknown>;
6
+ }
@@ -1,173 +1,332 @@
1
- import type { RtkRewriteRule } from "./rewrite-rules.js";
2
-
3
- const COMMAND_WORD_PATTERN = /"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|`(?:\\.|[^`])*`|[^\s]+/g;
4
- const BYPASSED_CARGO_SUBCOMMANDS = new Set(["help", "install", "publish"]);
5
- const GH_STRUCTURED_OUTPUT_FLAGS = ["--json", "--jq", "--template"] as const;
6
- const INTERACTIVE_CONTAINER_SHELLS = new Set([
7
- "ash",
8
- "bash",
9
- "cmd",
10
- "cmd.exe",
11
- "fish",
12
- "powershell",
13
- "powershell.exe",
14
- "pwsh",
15
- "pwsh.exe",
16
- "sh",
17
- "zsh",
18
- ]);
19
-
20
- function splitCommandWords(commandBody: string): string[] {
21
- return commandBody.match(COMMAND_WORD_PATTERN) ?? [];
22
- }
23
-
24
- function shouldBypassCargoRewrite(tokens: string[]): boolean {
25
- let index = 1;
26
-
27
- while (index < tokens.length && tokens[index].startsWith("+")) {
28
- index += 1;
29
- }
30
-
31
- while (index < tokens.length && tokens[index].startsWith("-")) {
32
- index += 1;
33
- }
34
-
35
- const subcommand = tokens[index]?.toLowerCase();
36
- if (!subcommand) {
37
- return true;
38
- }
39
-
40
- return BYPASSED_CARGO_SUBCOMMANDS.has(subcommand);
41
- }
42
-
43
- function normalizeCommandWord(token: string): string {
44
- const unwrapped = token.replace(/^(?:["'`])|(?:["'`])$/g, "");
45
- const lastPathSeparator = Math.max(unwrapped.lastIndexOf("/"), unwrapped.lastIndexOf("\\"));
46
- const basename = lastPathSeparator >= 0 ? unwrapped.slice(lastPathSeparator + 1) : unwrapped;
47
- return basename.toLowerCase();
48
- }
49
-
50
- function findInteractiveShellIndex(tokens: string[], startIndex: number, endIndex: number): number {
51
- for (let index = startIndex; index < endIndex; index += 1) {
52
- if (INTERACTIVE_CONTAINER_SHELLS.has(normalizeCommandWord(tokens[index] ?? ""))) {
53
- return index;
54
- }
55
- }
56
-
57
- return -1;
58
- }
59
-
60
- function hasTrailingArguments(tokens: string[], startIndex: number, endIndex: number): boolean {
61
- return startIndex >= 0 && startIndex < endIndex - 1;
62
- }
63
-
64
- function hasStructuredGhOutputFlag(tokens: string[]): boolean {
65
- return tokens.some((token) => {
66
- const normalized = token.toLowerCase();
67
- return GH_STRUCTURED_OUTPUT_FLAGS.some((flag) => normalized === flag || normalized.startsWith(`${flag}=`));
68
- });
69
- }
70
-
71
- function hasShortInteractiveFlag(token: string, flag: "i" | "t"): boolean {
72
- if (!token.startsWith("-") || token.startsWith("--")) {
73
- return false;
74
- }
75
-
76
- return token.slice(1).includes(flag);
77
- }
78
-
79
- function hasInteractiveFlagPair(tokens: string[], startIndex: number, endIndex: number): boolean {
80
- let interactive = false;
81
- let tty = false;
82
-
83
- for (let index = startIndex; index < endIndex; index += 1) {
84
- const token = tokens[index] ?? "";
85
- if (token === "--interactive") {
86
- interactive = true;
87
- continue;
88
- }
89
- if (token === "--tty") {
90
- tty = true;
91
- continue;
92
- }
93
- if (hasShortInteractiveFlag(token, "i")) {
94
- interactive = true;
95
- }
96
- if (hasShortInteractiveFlag(token, "t")) {
97
- tty = true;
98
- }
99
- }
100
-
101
- return interactive && tty;
102
- }
103
-
104
- function shouldBypassInteractiveContainerRewrite(tokens: string[]): boolean {
105
- const command = tokens[0]?.toLowerCase();
106
- if (!command) {
107
- return false;
108
- }
109
-
110
- if (command === "docker" || command === "podman") {
111
- const subcommand = tokens[1]?.toLowerCase();
112
- if (subcommand === "run" || subcommand === "exec") {
113
- const interactiveShellIndex = findInteractiveShellIndex(tokens, 2, tokens.length);
114
- return (
115
- interactiveShellIndex >= 0 &&
116
- !hasTrailingArguments(tokens, interactiveShellIndex, tokens.length) &&
117
- !hasInteractiveFlagPair(tokens, 2, interactiveShellIndex)
118
- );
119
- }
120
-
121
- if (subcommand === "compose") {
122
- const composeSubcommand = tokens[2]?.toLowerCase();
123
- if (composeSubcommand === "run" || composeSubcommand === "exec") {
124
- const interactiveShellIndex = findInteractiveShellIndex(tokens, 3, tokens.length);
125
- return (
126
- interactiveShellIndex >= 0 &&
127
- !hasTrailingArguments(tokens, interactiveShellIndex, tokens.length) &&
128
- !hasInteractiveFlagPair(tokens, 3, interactiveShellIndex)
129
- );
130
- }
131
- }
132
- }
133
-
134
- if (command === "kubectl" && tokens[1]?.toLowerCase() === "exec") {
135
- const separatorIndex = tokens.indexOf("--");
136
- if (separatorIndex === -1 || separatorIndex >= tokens.length - 1) {
137
- return false;
138
- }
139
-
140
- const interactiveShellIndex = findInteractiveShellIndex(tokens, separatorIndex + 1, tokens.length);
141
- if (interactiveShellIndex === -1) {
142
- return false;
143
- }
144
-
145
- return !hasTrailingArguments(tokens, interactiveShellIndex, tokens.length) && !hasInteractiveFlagPair(tokens, 2, separatorIndex);
146
- }
147
-
148
- return false;
149
- }
150
-
151
- /**
152
- * Skips RTK rewrites for command shapes that do not map cleanly to RTK wrappers.
153
- */
154
- export function shouldBypassRewriteForCommand(commandBody: string, rule: RtkRewriteRule): boolean {
155
- const tokens = splitCommandWords(commandBody.trim());
156
- if (tokens.length === 0) {
157
- return false;
158
- }
159
-
160
- if (tokens[0]?.toLowerCase() === "gh" && hasStructuredGhOutputFlag(tokens)) {
161
- return true;
162
- }
163
-
164
- if (rule.category === "rust" && tokens[0]?.toLowerCase() === "cargo") {
165
- return shouldBypassCargoRewrite(tokens);
166
- }
167
-
168
- if (rule.category === "containers") {
169
- return shouldBypassInteractiveContainerRewrite(tokens);
170
- }
171
-
172
- return false;
173
- }
1
+ import type { RtkRewriteRule } from "./rewrite-rules.js";
2
+
3
+ const COMMAND_WORD_PATTERN = /"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|`(?:\\.|[^`])*`|[^\s]+/g;
4
+ const BYPASSED_CARGO_SUBCOMMANDS = new Set(["help", "install", "publish"]);
5
+ const GH_STRUCTURED_OUTPUT_FLAGS = ["--json", "--jq", "--template"] as const;
6
+ const UNSAFE_COMPOUND_REWRITE_COMMANDS = new Set(["find", "grep", "rg", "ls"]);
7
+ const BYPASSED_FIND_ACTIONS = new Set([
8
+ "-delete",
9
+ "-exec",
10
+ "-execdir",
11
+ "-fprint",
12
+ "-fprint0",
13
+ "-fprintf",
14
+ "-fls",
15
+ "-ls",
16
+ "-ok",
17
+ "-okdir",
18
+ "-print0",
19
+ "-printf",
20
+ "-prune",
21
+ "-quit",
22
+ ]);
23
+ const BASH_INLINE_COMMAND_FLAGS = new Set(["-c", "-cl", "-lc", "--command"]);
24
+ const POWERSHELL_INLINE_COMMAND_FLAGS = new Set(["-c", "-command", "-encodedcommand"]);
25
+ const CMD_INLINE_COMMAND_FLAGS = new Set(["/c", "/k"]);
26
+ const INTERACTIVE_CONTAINER_SHELLS = new Set([
27
+ "ash",
28
+ "bash",
29
+ "cmd",
30
+ "cmd.exe",
31
+ "fish",
32
+ "powershell",
33
+ "powershell.exe",
34
+ "pwsh",
35
+ "pwsh.exe",
36
+ "sh",
37
+ "zsh",
38
+ ]);
39
+
40
+ function splitCommandWords(commandBody: string): string[] {
41
+ return commandBody.match(COMMAND_WORD_PATTERN) ?? [];
42
+ }
43
+
44
+ function splitTopLevelCompoundSegments(command: string): string[] {
45
+ const segments: string[] = [];
46
+ let segmentStart = 0;
47
+ let quote: "'" | '"' | "`" | null = null;
48
+ let escaped = false;
49
+
50
+ const pushSegment = (endIndex: number): void => {
51
+ const segment = command.slice(segmentStart, endIndex).trim();
52
+ if (segment) {
53
+ segments.push(segment);
54
+ }
55
+ };
56
+
57
+ for (let index = 0; index < command.length; index += 1) {
58
+ const char = command[index] ?? "";
59
+ const nextChar = command[index + 1] ?? "";
60
+ const prevChar = index > 0 ? command[index - 1] ?? "" : "";
61
+
62
+ if (escaped) {
63
+ escaped = false;
64
+ continue;
65
+ }
66
+
67
+ if (quote !== null) {
68
+ if (char === "\\" && quote !== "'") {
69
+ escaped = true;
70
+ continue;
71
+ }
72
+ if (char === quote) {
73
+ quote = null;
74
+ }
75
+ continue;
76
+ }
77
+
78
+ if (char === "\\") {
79
+ escaped = true;
80
+ continue;
81
+ }
82
+
83
+ if (char === "'" || char === '"' || char === "`") {
84
+ quote = char;
85
+ continue;
86
+ }
87
+
88
+ let separatorLength = 0;
89
+ if ((char === "&" && nextChar === "&") || (char === "|" && nextChar === "|") || (char === "|" && nextChar === "&")) {
90
+ separatorLength = 2;
91
+ } else if (char === "|" && prevChar !== ">") {
92
+ separatorLength = 1;
93
+ } else if (char === "&" && nextChar !== ">" && prevChar !== ">" && prevChar !== "<") {
94
+ separatorLength = 1;
95
+ }
96
+
97
+ // Intentionally ignore semicolons here so unquoted sed scripts remain eligible for
98
+ // segment-level rewriting instead of being treated as unsafe compound shells.
99
+ if (separatorLength === 0) {
100
+ continue;
101
+ }
102
+
103
+ pushSegment(index);
104
+ segmentStart = index + separatorLength;
105
+ if (separatorLength === 2) {
106
+ index += 1;
107
+ }
108
+ }
109
+
110
+ pushSegment(command.length);
111
+ return segments;
112
+ }
113
+
114
+ function shouldBypassCargoRewrite(tokens: string[]): boolean {
115
+ let index = 1;
116
+
117
+ while (index < tokens.length && tokens[index].startsWith("+")) {
118
+ index += 1;
119
+ }
120
+
121
+ while (index < tokens.length && tokens[index].startsWith("-")) {
122
+ index += 1;
123
+ }
124
+
125
+ const subcommand = tokens[index]?.toLowerCase();
126
+ if (!subcommand) {
127
+ return true;
128
+ }
129
+
130
+ return BYPASSED_CARGO_SUBCOMMANDS.has(subcommand);
131
+ }
132
+
133
+ function normalizeCommandWord(token: string): string {
134
+ const unwrapped = token.replace(/^(?:["'`])|(?:["'`])$/g, "");
135
+ const lastPathSeparator = Math.max(unwrapped.lastIndexOf("/"), unwrapped.lastIndexOf("\\"));
136
+ const basename = lastPathSeparator >= 0 ? unwrapped.slice(lastPathSeparator + 1) : unwrapped;
137
+ return basename.toLowerCase();
138
+ }
139
+
140
+ function findInteractiveShellIndex(tokens: string[], startIndex: number, endIndex: number): number {
141
+ for (let index = startIndex; index < endIndex; index += 1) {
142
+ if (INTERACTIVE_CONTAINER_SHELLS.has(normalizeCommandWord(tokens[index] ?? ""))) {
143
+ return index;
144
+ }
145
+ }
146
+
147
+ return -1;
148
+ }
149
+
150
+ function hasTrailingArguments(tokens: string[], startIndex: number, endIndex: number): boolean {
151
+ return startIndex >= 0 && startIndex < endIndex - 1;
152
+ }
153
+
154
+ function hasStructuredGhOutputFlag(tokens: string[]): boolean {
155
+ return tokens.some((token) => {
156
+ const normalized = token.toLowerCase();
157
+ return GH_STRUCTURED_OUTPUT_FLAGS.some((flag) => normalized === flag || normalized.startsWith(`${flag}=`));
158
+ });
159
+ }
160
+
161
+ function hasShortInteractiveFlag(token: string, flag: "i" | "t"): boolean {
162
+ if (!token.startsWith("-") || token.startsWith("--")) {
163
+ return false;
164
+ }
165
+
166
+ return token.slice(1).includes(flag);
167
+ }
168
+
169
+ function hasInteractiveFlagPair(tokens: string[], startIndex: number, endIndex: number): boolean {
170
+ let interactive = false;
171
+ let tty = false;
172
+
173
+ for (let index = startIndex; index < endIndex; index += 1) {
174
+ const token = tokens[index] ?? "";
175
+ if (token === "--interactive") {
176
+ interactive = true;
177
+ continue;
178
+ }
179
+ if (token === "--tty") {
180
+ tty = true;
181
+ continue;
182
+ }
183
+ if (hasShortInteractiveFlag(token, "i")) {
184
+ interactive = true;
185
+ }
186
+ if (hasShortInteractiveFlag(token, "t")) {
187
+ tty = true;
188
+ }
189
+ }
190
+
191
+ return interactive && tty;
192
+ }
193
+
194
+ function shouldBypassInteractiveContainerRewrite(tokens: string[]): boolean {
195
+ const command = tokens[0]?.toLowerCase();
196
+ if (!command) {
197
+ return false;
198
+ }
199
+
200
+ if (command === "docker" || command === "podman") {
201
+ const subcommand = tokens[1]?.toLowerCase();
202
+ if (subcommand === "run" || subcommand === "exec") {
203
+ const interactiveShellIndex = findInteractiveShellIndex(tokens, 2, tokens.length);
204
+ return (
205
+ interactiveShellIndex >= 0 &&
206
+ !hasTrailingArguments(tokens, interactiveShellIndex, tokens.length) &&
207
+ !hasInteractiveFlagPair(tokens, 2, interactiveShellIndex)
208
+ );
209
+ }
210
+
211
+ if (subcommand === "compose") {
212
+ const composeSubcommand = tokens[2]?.toLowerCase();
213
+ if (composeSubcommand === "run" || composeSubcommand === "exec") {
214
+ const interactiveShellIndex = findInteractiveShellIndex(tokens, 3, tokens.length);
215
+ return (
216
+ interactiveShellIndex >= 0 &&
217
+ !hasTrailingArguments(tokens, interactiveShellIndex, tokens.length) &&
218
+ !hasInteractiveFlagPair(tokens, 3, interactiveShellIndex)
219
+ );
220
+ }
221
+ }
222
+ }
223
+
224
+ if (command === "kubectl" && tokens[1]?.toLowerCase() === "exec") {
225
+ const separatorIndex = tokens.indexOf("--");
226
+ if (separatorIndex === -1 || separatorIndex >= tokens.length - 1) {
227
+ return false;
228
+ }
229
+
230
+ const interactiveShellIndex = findInteractiveShellIndex(tokens, separatorIndex + 1, tokens.length);
231
+ if (interactiveShellIndex === -1) {
232
+ return false;
233
+ }
234
+
235
+ return !hasTrailingArguments(tokens, interactiveShellIndex, tokens.length) && !hasInteractiveFlagPair(tokens, 2, separatorIndex);
236
+ }
237
+
238
+ return false;
239
+ }
240
+
241
+ function shouldBypassFindRewrite(tokens: string[]): boolean {
242
+ return tokens.slice(1).some((token) => {
243
+ const normalized = token.toLowerCase();
244
+ return (
245
+ BYPASSED_FIND_ACTIONS.has(normalized) ||
246
+ normalized.startsWith("-exec") ||
247
+ normalized.startsWith("-ok") ||
248
+ normalized.startsWith("-printf") ||
249
+ normalized.startsWith("-fprint") ||
250
+ normalized.startsWith("-fls")
251
+ );
252
+ });
253
+ }
254
+
255
+ function shouldBypassLsRewrite(tokens: string[]): boolean {
256
+ return tokens.slice(1).some((token) => token.startsWith("-"));
257
+ }
258
+
259
+ function shouldBypassNativeShellProxyRewrite(tokens: string[]): boolean {
260
+ const command = normalizeCommandWord(tokens[0] ?? "");
261
+ const firstArgument = tokens[1]?.toLowerCase();
262
+ if (!command || !firstArgument) {
263
+ return false;
264
+ }
265
+
266
+ if (command === "bash") {
267
+ return BASH_INLINE_COMMAND_FLAGS.has(firstArgument);
268
+ }
269
+
270
+ if (command === "powershell" || command === "powershell.exe") {
271
+ return POWERSHELL_INLINE_COMMAND_FLAGS.has(firstArgument);
272
+ }
273
+
274
+ if (command === "cmd" || command === "cmd.exe") {
275
+ return CMD_INLINE_COMMAND_FLAGS.has(firstArgument);
276
+ }
277
+
278
+ return false;
279
+ }
280
+
281
+ /**
282
+ * Skips entire compound commands when any segment depends on native shell piping or
283
+ * formatting-sensitive search/list output that RTK wrappers may not preserve exactly.
284
+ */
285
+ export function shouldBypassWholeCommandRewrite(command: string): boolean {
286
+ const segments = splitTopLevelCompoundSegments(command.trim());
287
+ if (segments.length <= 1) {
288
+ return false;
289
+ }
290
+
291
+ return segments.some((segment) => {
292
+ const tokens = splitCommandWords(segment);
293
+ const commandName = normalizeCommandWord(tokens[0] ?? "");
294
+ return UNSAFE_COMPOUND_REWRITE_COMMANDS.has(commandName) || shouldBypassNativeShellProxyRewrite(tokens);
295
+ });
296
+ }
297
+
298
+ /**
299
+ * Skips RTK rewrites for command shapes that do not map cleanly to RTK wrappers.
300
+ */
301
+ export function shouldBypassRewriteForCommand(commandBody: string, rule: RtkRewriteRule): boolean {
302
+ const tokens = splitCommandWords(commandBody.trim());
303
+ if (tokens.length === 0) {
304
+ return false;
305
+ }
306
+
307
+ if (tokens[0]?.toLowerCase() === "gh" && hasStructuredGhOutputFlag(tokens)) {
308
+ return true;
309
+ }
310
+
311
+ if (rule.category === "rust" && tokens[0]?.toLowerCase() === "cargo") {
312
+ return shouldBypassCargoRewrite(tokens);
313
+ }
314
+
315
+ if (rule.category === "containers") {
316
+ return shouldBypassInteractiveContainerRewrite(tokens);
317
+ }
318
+
319
+ if (rule.id === "find") {
320
+ return shouldBypassFindRewrite(tokens);
321
+ }
322
+
323
+ if (rule.id === "ls") {
324
+ return shouldBypassLsRewrite(tokens);
325
+ }
326
+
327
+ if (rule.id === "bash-proxy" || rule.id === "cmd-proxy" || rule.id === "powershell-proxy") {
328
+ return shouldBypassNativeShellProxyRewrite(tokens);
329
+ }
330
+
331
+ return false;
332
+ }
@@ -0,0 +1,154 @@
1
+ interface ParsedPipeline {
2
+ segments: string[];
3
+ separators: string[];
4
+ }
5
+
6
+ interface ProducerRewritePlan {
7
+ command: string;
8
+ captureStderr: boolean;
9
+ }
10
+
11
+ function isTopLevelQuoteCharacter(character: string): character is '"' | "'" | "`" {
12
+ return character === '"' || character === "'" || character === "`";
13
+ }
14
+
15
+ function parseSimpleTopLevelPipeline(command: string): ParsedPipeline | null {
16
+ const segments: string[] = [];
17
+ const separators: string[] = [];
18
+ let quote: '"' | "'" | "`" | null = null;
19
+ let escaped = false;
20
+ let segmentStart = 0;
21
+
22
+ for (let index = 0; index < command.length; index += 1) {
23
+ const character = command[index] ?? "";
24
+ const nextCharacter = command[index + 1] ?? "";
25
+ const previousCharacter = index > 0 ? (command[index - 1] ?? "") : "";
26
+
27
+ if (escaped) {
28
+ escaped = false;
29
+ continue;
30
+ }
31
+
32
+ if (quote !== null) {
33
+ if (character === "\\" && quote !== "'") {
34
+ escaped = true;
35
+ continue;
36
+ }
37
+ if (character === quote) {
38
+ quote = null;
39
+ }
40
+ continue;
41
+ }
42
+
43
+ if (character === "\\") {
44
+ escaped = true;
45
+ continue;
46
+ }
47
+
48
+ if (isTopLevelQuoteCharacter(character)) {
49
+ quote = character;
50
+ continue;
51
+ }
52
+
53
+ if (character === "|" && nextCharacter === "|") {
54
+ return null;
55
+ }
56
+
57
+ if (character === "|" && previousCharacter !== ">") {
58
+ const separatorLength = nextCharacter === "&" ? 2 : 1;
59
+ segments.push(command.slice(segmentStart, index));
60
+ separators.push(command.slice(index, index + separatorLength));
61
+ segmentStart = index + separatorLength;
62
+ if (separatorLength === 2) {
63
+ index += 1;
64
+ }
65
+ continue;
66
+ }
67
+
68
+ if (character === "&" && nextCharacter === "&") {
69
+ return null;
70
+ }
71
+
72
+ if (character === "&" && nextCharacter !== ">" && previousCharacter !== ">" && previousCharacter !== "<") {
73
+ return null;
74
+ }
75
+
76
+ if (character === ";") {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ if (separators.length === 0) {
82
+ return null;
83
+ }
84
+
85
+ segments.push(command.slice(segmentStart));
86
+ return { segments, separators };
87
+ }
88
+
89
+ function extractProducerRewritePlan(segment: string, firstSeparator: string): ProducerRewritePlan | null {
90
+ const trimmed = segment.trim();
91
+ if (!/^rtk\s+/i.test(trimmed)) {
92
+ return null;
93
+ }
94
+
95
+ const stderrMergeMatch = trimmed.match(/^(.*?)(?:\s+)?2>\s*&1\s*$/u);
96
+ if (stderrMergeMatch) {
97
+ const command = stderrMergeMatch[1]?.trimEnd() ?? "";
98
+ return command ? { command, captureStderr: true } : null;
99
+ }
100
+
101
+ return {
102
+ command: trimmed,
103
+ captureStderr: firstSeparator === "|&",
104
+ };
105
+ }
106
+
107
+ function buildBufferedPipelineCommand(
108
+ producer: ProducerRewritePlan,
109
+ remainder: string,
110
+ ): string {
111
+ const tempFileVariable = "__pi_rtk_pipe_tmp";
112
+ const statusVariable = "__pi_rtk_pipe_status";
113
+ const producerRedirect = producer.captureStderr ? `> "$${tempFileVariable}" 2>&1` : `> "$${tempFileVariable}"`;
114
+ const cleanupTrap = `rm -f "$${tempFileVariable}"`;
115
+
116
+ return [
117
+ "{",
118
+ `${tempFileVariable}="$(mktemp)" || exit $?;`,
119
+ `${statusVariable}=0;`,
120
+ `trap '${cleanupTrap}' EXIT HUP INT TERM;`,
121
+ `${producer.command} ${producerRedirect};`,
122
+ `${statusVariable}=$?;`,
123
+ `if [ $${statusVariable} -eq 0 ]; then (${remainder}) < "$${tempFileVariable}"; ${statusVariable}=$?; fi;`,
124
+ `exit $${statusVariable};`,
125
+ "}",
126
+ ].join(" ");
127
+ }
128
+
129
+ export function applyRewrittenCommandShellSafetyFixups(command: string): string {
130
+ if (process.platform !== "win32") {
131
+ return command;
132
+ }
133
+
134
+ const parsedPipeline = parseSimpleTopLevelPipeline(command);
135
+ if (!parsedPipeline) {
136
+ return command;
137
+ }
138
+
139
+ const producer = extractProducerRewritePlan(parsedPipeline.segments[0] ?? "", parsedPipeline.separators[0] ?? "");
140
+ if (!producer) {
141
+ return command;
142
+ }
143
+
144
+ const remainder = parsedPipeline.segments
145
+ .slice(1)
146
+ .map((segment, index) => `${index === 0 ? "" : (parsedPipeline.separators[index] ?? "")}${segment}`)
147
+ .join("")
148
+ .trim();
149
+ if (!remainder) {
150
+ return command;
151
+ }
152
+
153
+ return buildBufferedPipelineCommand(producer, remainder);
154
+ }