@narumitw/pi-plan-mode 0.58.0 → 0.58.1

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 (39) hide show
  1. package/dist/chunks/{chunk-QHHHBTDO.js → chunk-HF7ZEYIC.js} +29 -111
  2. package/dist/chunks/chunk-HF7ZEYIC.js.map +7 -0
  3. package/dist/chunks/{interactive-ui-UNJGC2RQ.js → interactive-ui-UK7IGPOE.js} +13 -41
  4. package/dist/chunks/interactive-ui-UK7IGPOE.js.map +7 -0
  5. package/dist/index.ts +25 -82
  6. package/dist/index.ts.map +2 -2
  7. package/package.json +50 -51
  8. package/src/active-implementation-menu.ts +57 -60
  9. package/src/command.ts +22 -22
  10. package/src/completion-tool.ts +53 -56
  11. package/src/extension-runtime.ts +5 -5
  12. package/src/finalization-request.ts +40 -44
  13. package/src/fresh-handoff-coordinator.ts +38 -41
  14. package/src/fresh-implementation.ts +293 -310
  15. package/src/implementation-models.ts +25 -30
  16. package/src/implementation-retention.ts +109 -123
  17. package/src/message-transform.ts +218 -252
  18. package/src/mode-contract.ts +46 -49
  19. package/src/plan-action-controller.ts +134 -155
  20. package/src/plan-action-menus.ts +390 -408
  21. package/src/plan-export-controller.ts +23 -28
  22. package/src/plan-export-screen.ts +13 -13
  23. package/src/plan-export.ts +85 -102
  24. package/src/plan-launch-menu.ts +119 -119
  25. package/src/plan-mode.ts +2017 -2098
  26. package/src/presentation.ts +84 -108
  27. package/src/prompt.ts +1 -1
  28. package/src/question-tool.ts +239 -267
  29. package/src/required-tools.ts +15 -19
  30. package/src/saved-plan-menu.ts +82 -84
  31. package/src/saved-plan-preflight.ts +29 -33
  32. package/src/settings-menu.ts +470 -513
  33. package/src/settings.ts +393 -452
  34. package/src/state.ts +167 -198
  35. package/src/tool-policy.ts +634 -699
  36. package/src/tool-selection.ts +39 -44
  37. package/src/workflow-mutex.ts +66 -66
  38. package/dist/chunks/chunk-QHHHBTDO.js.map +0 -7
  39. package/dist/chunks/interactive-ui-UNJGC2RQ.js.map +0 -7
@@ -2,27 +2,24 @@ import { isAbsolute, normalize } from "node:path";
2
2
  import type { ToolInfo } from "@earendil-works/pi-coding-agent";
3
3
 
4
4
  export const BUILTIN_SAFE_GIT_SUBCOMMANDS = [
5
- "status",
6
- "log",
7
- "diff",
8
- "show",
9
- "branch",
10
- "remote",
11
- "ls-files",
12
- "grep",
5
+ "status",
6
+ "log",
7
+ "diff",
8
+ "show",
9
+ "branch",
10
+ "remote",
11
+ "ls-files",
12
+ "grep",
13
13
  ] as const;
14
14
  export const CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [
15
- "rev-parse",
16
- "blame",
17
- "describe",
18
- "merge-base",
19
- "ls-tree",
20
- "cat-file",
21
- ] as const;
22
- export const SAFE_GIT_SUBCOMMANDS = [
23
- ...BUILTIN_SAFE_GIT_SUBCOMMANDS,
24
- ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS,
15
+ "rev-parse",
16
+ "blame",
17
+ "describe",
18
+ "merge-base",
19
+ "ls-tree",
20
+ "cat-file",
25
21
  ] as const;
22
+ export const SAFE_GIT_SUBCOMMANDS = [...BUILTIN_SAFE_GIT_SUBCOMMANDS, ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS] as const;
26
23
  export const SAFE_GH_SUBCOMMAND_PATHS = ["pr view", "pr list", "issue view", "issue list"] as const;
27
24
 
28
25
  export type BuiltinSafeGitSubcommand = (typeof BUILTIN_SAFE_GIT_SUBCOMMANDS)[number];
@@ -30,811 +27,749 @@ export type ConfigurableSafeGitSubcommand = (typeof CONFIGURABLE_SAFE_GIT_SUBCOM
30
27
  export type SafeGitSubcommand = (typeof SAFE_GIT_SUBCOMMANDS)[number];
31
28
  export type SafeGhSubcommandPath = (typeof SAFE_GH_SUBCOMMAND_PATHS)[number];
32
29
  export interface SafeSubcommands {
33
- [command: string]: string[] | undefined;
30
+ [command: string]: string[] | undefined;
34
31
  }
35
32
 
36
- export const SAFE_BUILTIN_PLAN_TOOLS = new Set([
37
- "read",
38
- "bash",
39
- "powershell",
40
- "grep",
41
- "find",
42
- "ls",
43
- ]);
33
+ export const SAFE_BUILTIN_PLAN_TOOLS = new Set(["read", "bash", "powershell", "grep", "find", "ls"]);
44
34
  export type PlanModeToolPolicy = "read-only" | "limited" | "user-opt-in" | "blocked";
45
35
 
46
36
  const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
47
37
  const MUTATING_COMMANDS = new Set([
48
- "rm",
49
- "rmdir",
50
- "mv",
51
- "cp",
52
- "mkdir",
53
- "touch",
54
- "chmod",
55
- "chown",
56
- "chgrp",
57
- "ln",
58
- "tee",
59
- "truncate",
60
- "dd",
61
- "sudo",
62
- "su",
63
- "kill",
64
- "pkill",
65
- "killall",
66
- "reboot",
67
- "shutdown",
68
- "vim",
69
- "vi",
70
- "nano",
71
- "emacs",
72
- "code",
73
- "subl",
38
+ "rm",
39
+ "rmdir",
40
+ "mv",
41
+ "cp",
42
+ "mkdir",
43
+ "touch",
44
+ "chmod",
45
+ "chown",
46
+ "chgrp",
47
+ "ln",
48
+ "tee",
49
+ "truncate",
50
+ "dd",
51
+ "sudo",
52
+ "su",
53
+ "kill",
54
+ "pkill",
55
+ "killall",
56
+ "reboot",
57
+ "shutdown",
58
+ "vim",
59
+ "vi",
60
+ "nano",
61
+ "emacs",
62
+ "code",
63
+ "subl",
74
64
  ]);
75
65
  const READ_ONLY_POWERSHELL_COMMANDS = new Set([
76
- "format-list",
77
- "format-table",
78
- "get-childitem",
79
- "get-content",
80
- "get-item",
81
- "get-location",
82
- "measure-object",
83
- "out-string",
84
- "resolve-path",
85
- "select-string",
86
- "sort-object",
87
- "test-path",
88
- "write-output",
66
+ "format-list",
67
+ "format-table",
68
+ "get-childitem",
69
+ "get-content",
70
+ "get-item",
71
+ "get-location",
72
+ "measure-object",
73
+ "out-string",
74
+ "resolve-path",
75
+ "select-string",
76
+ "sort-object",
77
+ "test-path",
78
+ "write-output",
89
79
  ]);
90
80
  const READ_ONLY_COMMANDS = new Set([
91
- "cat",
92
- "head",
93
- "tail",
94
- "grep",
95
- "find",
96
- "ls",
97
- "pwd",
98
- "echo",
99
- "printf",
100
- "wc",
101
- "sort",
102
- "uniq",
103
- "diff",
104
- "file",
105
- "stat",
106
- "du",
107
- "df",
108
- "tree",
109
- "which",
110
- "whereis",
111
- "type",
112
- "printenv",
113
- "uname",
114
- "whoami",
115
- "id",
116
- "date",
117
- "uptime",
118
- "ps",
119
- "jq",
120
- "rg",
121
- "fd",
122
- "bat",
123
- "eza",
81
+ "cat",
82
+ "head",
83
+ "tail",
84
+ "grep",
85
+ "find",
86
+ "ls",
87
+ "pwd",
88
+ "echo",
89
+ "printf",
90
+ "wc",
91
+ "sort",
92
+ "uniq",
93
+ "diff",
94
+ "file",
95
+ "stat",
96
+ "du",
97
+ "df",
98
+ "tree",
99
+ "which",
100
+ "whereis",
101
+ "type",
102
+ "printenv",
103
+ "uname",
104
+ "whoami",
105
+ "id",
106
+ "date",
107
+ "uptime",
108
+ "ps",
109
+ "jq",
110
+ "rg",
111
+ "fd",
112
+ "bat",
113
+ "eza",
124
114
  ]);
125
115
 
126
116
  export function isBuiltinTool(tool: ToolInfo) {
127
- return tool.sourceInfo.source === "builtin";
117
+ return tool.sourceInfo.source === "builtin";
128
118
  }
129
119
 
130
120
  export function classifyPlanModeTool(tool: ToolInfo): PlanModeToolPolicy {
131
- if (!isBuiltinTool(tool)) return "user-opt-in";
132
- if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
133
- if (tool.name === "bash" || tool.name === "powershell") return "limited";
134
- return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
121
+ if (!isBuiltinTool(tool)) return "user-opt-in";
122
+ if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
123
+ if (tool.name === "bash" || tool.name === "powershell") return "limited";
124
+ return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
135
125
  }
136
126
 
137
127
  export function canSelectToolInPlanMode(tool: ToolInfo) {
138
- return classifyPlanModeTool(tool) !== "blocked";
128
+ return classifyPlanModeTool(tool) !== "blocked";
139
129
  }
140
130
 
141
131
  export function readCommand(input: unknown) {
142
- const command = input as { command?: unknown } | undefined;
143
- return typeof command?.command === "string" ? command.command : "";
132
+ const command = input as { command?: unknown } | undefined;
133
+ return typeof command?.command === "string" ? command.command : "";
144
134
  }
145
135
 
146
136
  export function findBlockedCommandSegment(
147
- command: string,
148
- safeSubcommands: SafeSubcommands = {},
149
- workingDirectory?: string,
150
- platform: NodeJS.Platform = process.platform,
137
+ command: string,
138
+ safeSubcommands: SafeSubcommands = {},
139
+ workingDirectory?: string,
140
+ platform: NodeJS.Platform = process.platform,
151
141
  ): string | undefined {
152
- if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return undefined;
153
- const segments = splitShellSegments(command);
154
- if (!segments || segments.length === 0) return command.trim() || "(empty command)";
155
- return segments.find(
156
- (segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory, platform),
157
- );
142
+ if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return undefined;
143
+ const segments = splitShellSegments(command);
144
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
145
+ return segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory, platform));
158
146
  }
159
147
 
160
148
  export function isSafeCommand(
161
- command: string,
162
- safeSubcommands: SafeSubcommands = {},
163
- workingDirectory?: string,
164
- platform: NodeJS.Platform = process.platform,
149
+ command: string,
150
+ safeSubcommands: SafeSubcommands = {},
151
+ workingDirectory?: string,
152
+ platform: NodeJS.Platform = process.platform,
165
153
  ) {
166
- return (
167
- findBlockedCommandSegment(command, safeSubcommands, workingDirectory, platform) === undefined
168
- );
154
+ return findBlockedCommandSegment(command, safeSubcommands, workingDirectory, platform) === undefined;
169
155
  }
170
156
 
171
157
  export function findBlockedPowerShellCommandSegment(
172
- command: string,
173
- safeSubcommands: SafeSubcommands = {},
174
- workingDirectory?: string,
158
+ command: string,
159
+ safeSubcommands: SafeSubcommands = {},
160
+ workingDirectory?: string,
175
161
  ): string | undefined {
176
- if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return undefined;
177
- const segments = splitPowerShellSegments(command);
178
- if (!segments || segments.length === 0) return command.trim() || "(empty command)";
179
- return segments.find(
180
- (segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory),
181
- );
162
+ if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return undefined;
163
+ const segments = splitPowerShellSegments(command);
164
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
165
+ return segments.find((segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory));
182
166
  }
183
167
 
184
168
  export function isSafePowerShellCommand(
185
- command: string,
186
- safeSubcommands: SafeSubcommands = {},
187
- workingDirectory?: string,
169
+ command: string,
170
+ safeSubcommands: SafeSubcommands = {},
171
+ workingDirectory?: string,
188
172
  ) {
189
- return (
190
- findBlockedPowerShellCommandSegment(command, safeSubcommands, workingDirectory) === undefined
191
- );
173
+ return findBlockedPowerShellCommandSegment(command, safeSubcommands, workingDirectory) === undefined;
192
174
  }
193
175
 
194
176
  function matchesConfiguredSafeSubcommand(command: string, safeSubcommands: SafeSubcommands) {
195
- const candidate = command.trimStart();
196
- return Object.entries(safeSubcommands).some(([configuredCommand, subcommands]) =>
197
- subcommands?.some((subcommand) => {
198
- const prefix = `${configuredCommand.trim()} ${subcommand.trim()}`;
199
- if (!configuredCommand.trim() || !subcommand.trim() || !candidate.startsWith(prefix)) {
200
- return false;
201
- }
202
- const boundary = candidate[prefix.length];
203
- return boundary === undefined || /[\s;&|<>()]/.test(boundary);
204
- }),
205
- );
177
+ const candidate = command.trimStart();
178
+ return Object.entries(safeSubcommands).some(([configuredCommand, subcommands]) =>
179
+ subcommands?.some((subcommand) => {
180
+ const prefix = `${configuredCommand.trim()} ${subcommand.trim()}`;
181
+ if (!configuredCommand.trim() || !subcommand.trim() || !candidate.startsWith(prefix)) {
182
+ return false;
183
+ }
184
+ const boundary = candidate[prefix.length];
185
+ return boundary === undefined || /[\s;&|<>()]/.test(boundary);
186
+ }),
187
+ );
206
188
  }
207
189
 
208
190
  function splitPowerShellSegments(command: string): string[] | undefined {
209
- const trimmed = command.trim();
210
- if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return undefined;
211
-
212
- const segments: string[] = [];
213
- let quote: "'" | '"' | undefined;
214
- let start = 0;
215
- for (let index = 0; index < trimmed.length; index += 1) {
216
- const character = trimmed[index];
217
- if (quote === "'") {
218
- if (character !== "'") continue;
219
- if (trimmed[index + 1] === "'") {
220
- index += 1;
221
- continue;
222
- }
223
- quote = undefined;
224
- continue;
225
- }
226
- if (quote === '"') {
227
- if (character === "$" || character === "`") return undefined;
228
- if (character === '"') quote = undefined;
229
- continue;
230
- }
231
- if (character === "'" || character === '"') {
232
- quote = character;
233
- continue;
234
- }
235
- if (["$", "@", "#", "!", "?", "{", "}", "(", ")", "[", "]", ">", "<"].includes(character)) {
236
- return undefined;
237
- }
238
- const next = trimmed[index + 1];
239
- if (character === "&" || (character === "|" && next === "|")) return undefined;
240
- const separatorLength = character === ";" || character === "|" ? 1 : 0;
241
- if (separatorLength === 0) continue;
242
- const segment = trimmed.slice(start, index).trim();
243
- if (!segment) return undefined;
244
- segments.push(segment);
245
- index += separatorLength - 1;
246
- start = index + 1;
247
- }
248
- if (quote) return undefined;
249
- const finalSegment = trimmed.slice(start).trim();
250
- if (!finalSegment) return undefined;
251
- segments.push(finalSegment);
252
- return segments;
253
- }
254
-
255
- function isSafePowerShellSegment(
256
- segment: string,
257
- safeSubcommands: SafeSubcommands,
258
- workingDirectory?: string,
259
- ) {
260
- const tokens = powerShellWords(segment);
261
- if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
262
- const command = tokens[0]?.toLowerCase();
263
- if (!command) return false;
264
- const args = tokens.slice(1);
265
- if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
266
- if (command === "get-process") return isSafeGetProcessArguments(args);
267
- if (command === "get-service") return isSafeGetServiceArguments(args);
268
- if (command !== "git" && command !== "gh") return false;
269
- return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
191
+ const trimmed = command.trim();
192
+ if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return undefined;
193
+
194
+ const segments: string[] = [];
195
+ let quote: "'" | '"' | undefined;
196
+ let start = 0;
197
+ for (let index = 0; index < trimmed.length; index += 1) {
198
+ const character = trimmed[index];
199
+ if (quote === "'") {
200
+ if (character !== "'") continue;
201
+ if (trimmed[index + 1] === "'") {
202
+ index += 1;
203
+ continue;
204
+ }
205
+ quote = undefined;
206
+ continue;
207
+ }
208
+ if (quote === '"') {
209
+ if (character === "$" || character === "`") return undefined;
210
+ if (character === '"') quote = undefined;
211
+ continue;
212
+ }
213
+ if (character === "'" || character === '"') {
214
+ quote = character;
215
+ continue;
216
+ }
217
+ if (["$", "@", "#", "!", "?", "{", "}", "(", ")", "[", "]", ">", "<"].includes(character)) {
218
+ return undefined;
219
+ }
220
+ const next = trimmed[index + 1];
221
+ if (character === "&" || (character === "|" && next === "|")) return undefined;
222
+ const separatorLength = character === ";" || character === "|" ? 1 : 0;
223
+ if (separatorLength === 0) continue;
224
+ const segment = trimmed.slice(start, index).trim();
225
+ if (!segment) return undefined;
226
+ segments.push(segment);
227
+ index += separatorLength - 1;
228
+ start = index + 1;
229
+ }
230
+ if (quote) return undefined;
231
+ const finalSegment = trimmed.slice(start).trim();
232
+ if (!finalSegment) return undefined;
233
+ segments.push(finalSegment);
234
+ return segments;
235
+ }
236
+
237
+ function isSafePowerShellSegment(segment: string, safeSubcommands: SafeSubcommands, workingDirectory?: string) {
238
+ const tokens = powerShellWords(segment);
239
+ if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
240
+ const command = tokens[0]?.toLowerCase();
241
+ if (!command) return false;
242
+ const args = tokens.slice(1);
243
+ if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
244
+ if (command === "get-process") return isSafeGetProcessArguments(args);
245
+ if (command === "get-service") return isSafeGetServiceArguments(args);
246
+ if (command !== "git" && command !== "gh") return false;
247
+ return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
270
248
  }
271
249
 
272
250
  function powerShellWords(segment: string): string[] | undefined {
273
- const words: string[] = [];
274
- let word = "";
275
- let hasWord = false;
276
- let quote: "'" | '"' | undefined;
277
- for (let index = 0; index < segment.length; index += 1) {
278
- const character = segment[index];
279
- if (quote === "'") {
280
- if (character !== "'") {
281
- word += character;
282
- continue;
283
- }
284
- if (segment[index + 1] === "'") {
285
- word += "'";
286
- index += 1;
287
- continue;
288
- }
289
- quote = undefined;
290
- continue;
291
- }
292
- if (quote === '"') {
293
- if (character === '"') quote = undefined;
294
- else word += character;
295
- continue;
296
- }
297
- if (character === "'" || character === '"') {
298
- quote = character;
299
- hasWord = true;
300
- } else if (/\s/.test(character)) {
301
- if (hasWord) words.push(word);
302
- word = "";
303
- hasWord = false;
304
- } else {
305
- word += character;
306
- hasWord = true;
307
- }
308
- }
309
- if (quote) return undefined;
310
- if (hasWord) words.push(word);
311
- return words;
251
+ const words: string[] = [];
252
+ let word = "";
253
+ let hasWord = false;
254
+ let quote: "'" | '"' | undefined;
255
+ for (let index = 0; index < segment.length; index += 1) {
256
+ const character = segment[index];
257
+ if (quote === "'") {
258
+ if (character !== "'") {
259
+ word += character;
260
+ continue;
261
+ }
262
+ if (segment[index + 1] === "'") {
263
+ word += "'";
264
+ index += 1;
265
+ continue;
266
+ }
267
+ quote = undefined;
268
+ continue;
269
+ }
270
+ if (quote === '"') {
271
+ if (character === '"') quote = undefined;
272
+ else word += character;
273
+ continue;
274
+ }
275
+ if (character === "'" || character === '"') {
276
+ quote = character;
277
+ hasWord = true;
278
+ } else if (/\s/.test(character)) {
279
+ if (hasWord) words.push(word);
280
+ word = "";
281
+ hasWord = false;
282
+ } else {
283
+ word += character;
284
+ hasWord = true;
285
+ }
286
+ }
287
+ if (quote) return undefined;
288
+ if (hasWord) words.push(word);
289
+ return words;
312
290
  }
313
291
 
314
292
  function splitShellSegments(command: string): string[] | undefined {
315
- const trimmed = command.trim();
316
- if (!trimmed || /[\n\r`]/.test(trimmed)) return undefined;
317
-
318
- const segments: string[] = [];
319
- let quote: "'" | '"' | undefined;
320
- let escaped = false;
321
- let start = 0;
322
- for (let index = 0; index < trimmed.length; index += 1) {
323
- const character = trimmed[index];
324
- if (escaped) {
325
- escaped = false;
326
- continue;
327
- }
328
- if (character === "\\" && quote !== "'") {
329
- escaped = true;
330
- continue;
331
- }
332
- if (quote) {
333
- if (character === quote) quote = undefined;
334
- continue;
335
- }
336
- if (character === "'" || character === '"') {
337
- quote = character;
338
- continue;
339
- }
340
- if (character === ">" || character === "<" || character === "(" || character === ")") {
341
- return undefined;
342
- }
343
- const next = trimmed[index + 1];
344
- if (character === "&" && next !== "&") return undefined;
345
- const separatorLength =
346
- character === ";" || character === "|"
347
- ? next === character
348
- ? 2
349
- : 1
350
- : character === "&" && next === "&"
351
- ? 2
352
- : 0;
353
- if (separatorLength === 0) continue;
354
- const segment = trimmed.slice(start, index).trim();
355
- if (!segment) return undefined;
356
- segments.push(segment);
357
- index += separatorLength - 1;
358
- start = index + 1;
359
- }
360
- if (quote || escaped) return undefined;
361
- const finalSegment = trimmed.slice(start).trim();
362
- if (!finalSegment) return undefined;
363
- segments.push(finalSegment);
364
- return segments;
293
+ const trimmed = command.trim();
294
+ if (!trimmed || /[\n\r`]/.test(trimmed)) return undefined;
295
+
296
+ const segments: string[] = [];
297
+ let quote: "'" | '"' | undefined;
298
+ let escaped = false;
299
+ let start = 0;
300
+ for (let index = 0; index < trimmed.length; index += 1) {
301
+ const character = trimmed[index];
302
+ if (escaped) {
303
+ escaped = false;
304
+ continue;
305
+ }
306
+ if (character === "\\" && quote !== "'") {
307
+ escaped = true;
308
+ continue;
309
+ }
310
+ if (quote) {
311
+ if (character === quote) quote = undefined;
312
+ continue;
313
+ }
314
+ if (character === "'" || character === '"') {
315
+ quote = character;
316
+ continue;
317
+ }
318
+ if (character === ">" || character === "<" || character === "(" || character === ")") {
319
+ return undefined;
320
+ }
321
+ const next = trimmed[index + 1];
322
+ if (character === "&" && next !== "&") return undefined;
323
+ const separatorLength =
324
+ character === ";" || character === "|" ? (next === character ? 2 : 1) : character === "&" && next === "&" ? 2 : 0;
325
+ if (separatorLength === 0) continue;
326
+ const segment = trimmed.slice(start, index).trim();
327
+ if (!segment) return undefined;
328
+ segments.push(segment);
329
+ index += separatorLength - 1;
330
+ start = index + 1;
331
+ }
332
+ if (quote || escaped) return undefined;
333
+ const finalSegment = trimmed.slice(start).trim();
334
+ if (!finalSegment) return undefined;
335
+ segments.push(finalSegment);
336
+ return segments;
365
337
  }
366
338
 
367
339
  function isSafeSegment(
368
- segment: string,
369
- safeSubcommands: SafeSubcommands,
370
- workingDirectory: string | undefined,
371
- platform: NodeJS.Platform,
340
+ segment: string,
341
+ safeSubcommands: SafeSubcommands,
342
+ workingDirectory: string | undefined,
343
+ platform: NodeJS.Platform,
372
344
  ) {
373
- if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
374
- return false;
375
- }
376
- const tokens = shellWords(segment);
377
- if (!tokens || tokens.length === 0) return false;
378
- const command = tokens[0]?.toLowerCase();
379
- if (!command || MUTATING_COMMANDS.has(command)) return false;
380
- const args = tokens.slice(1);
381
- if (!hasSafeArguments(command, args)) return false;
382
- if (command === "hostname") return args.length === 0;
383
- if (command === "tasklist") return platform === "win32" && isSafeTasklistArguments(args);
384
- if (READ_ONLY_COMMANDS.has(command)) return true;
385
- return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
345
+ if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
346
+ return false;
347
+ }
348
+ const tokens = shellWords(segment);
349
+ if (!tokens || tokens.length === 0) return false;
350
+ const command = tokens[0]?.toLowerCase();
351
+ if (!command || MUTATING_COMMANDS.has(command)) return false;
352
+ const args = tokens.slice(1);
353
+ if (!hasSafeArguments(command, args)) return false;
354
+ if (command === "hostname") return args.length === 0;
355
+ if (command === "tasklist") return platform === "win32" && isSafeTasklistArguments(args);
356
+ if (READ_ONLY_COMMANDS.has(command)) return true;
357
+ return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
386
358
  }
387
359
 
388
360
  function hasShellExpansion(segment: string) {
389
- let quote: "'" | '"' | undefined;
390
- let escaped = false;
391
- for (const character of segment) {
392
- if (escaped) {
393
- escaped = false;
394
- continue;
395
- }
396
- if (character === "\\" && quote !== "'") {
397
- escaped = true;
398
- continue;
399
- }
400
- if (quote) {
401
- if (character === quote) quote = undefined;
402
- else if (character === "$" && quote === '"') return true;
403
- continue;
404
- }
405
- if (character === "'" || character === '"') {
406
- quote = character;
407
- continue;
408
- }
409
- if (["$", "*", "?", "[", "{"].includes(character)) return true;
410
- }
411
- return false;
361
+ let quote: "'" | '"' | undefined;
362
+ let escaped = false;
363
+ for (const character of segment) {
364
+ if (escaped) {
365
+ escaped = false;
366
+ continue;
367
+ }
368
+ if (character === "\\" && quote !== "'") {
369
+ escaped = true;
370
+ continue;
371
+ }
372
+ if (quote) {
373
+ if (character === quote) quote = undefined;
374
+ else if (character === "$" && quote === '"') return true;
375
+ continue;
376
+ }
377
+ if (character === "'" || character === '"') {
378
+ quote = character;
379
+ continue;
380
+ }
381
+ if (["$", "*", "?", "[", "{"].includes(character)) return true;
382
+ }
383
+ return false;
412
384
  }
413
385
 
414
386
  function shellWords(segment: string): string[] | undefined {
415
- const words: string[] = [];
416
- let word = "";
417
- let quote: "'" | '"' | undefined;
418
- let escaped = false;
419
- for (const character of segment) {
420
- if (escaped) {
421
- word += character;
422
- escaped = false;
423
- continue;
424
- }
425
- if (character === "\\" && quote !== "'") {
426
- escaped = true;
427
- continue;
428
- }
429
- if (quote) {
430
- if (character === quote) quote = undefined;
431
- else word += character;
432
- continue;
433
- }
434
- if (character === "'" || character === '"') quote = character;
435
- else if (/\s/.test(character)) {
436
- if (word) words.push(word);
437
- word = "";
438
- } else word += character;
439
- }
440
- if (quote || escaped) return undefined;
441
- if (word) words.push(word);
442
- return words;
387
+ const words: string[] = [];
388
+ let word = "";
389
+ let quote: "'" | '"' | undefined;
390
+ let escaped = false;
391
+ for (const character of segment) {
392
+ if (escaped) {
393
+ word += character;
394
+ escaped = false;
395
+ continue;
396
+ }
397
+ if (character === "\\" && quote !== "'") {
398
+ escaped = true;
399
+ continue;
400
+ }
401
+ if (quote) {
402
+ if (character === quote) quote = undefined;
403
+ else word += character;
404
+ continue;
405
+ }
406
+ if (character === "'" || character === '"') quote = character;
407
+ else if (/\s/.test(character)) {
408
+ if (word) words.push(word);
409
+ word = "";
410
+ } else word += character;
411
+ }
412
+ if (quote || escaped) return undefined;
413
+ if (word) words.push(word);
414
+ return words;
443
415
  }
444
416
 
445
417
  function hasSafeArguments(command: string, args: string[]) {
446
- const forbidden = new Set(["-i", "--in-place", "--fix", "--write", "-delete", "--delete"]);
447
- if (args.some((argument) => forbidden.has(argument))) return false;
448
- if (
449
- command === "sed" &&
450
- args.some(
451
- (argument) =>
452
- argument.startsWith("--in-place=") ||
453
- (/^-[^-]+/.test(argument) && argument.slice(1).includes("i")),
454
- )
455
- ) {
456
- return false;
457
- }
458
- if (
459
- command === "find" &&
460
- args.some((argument) =>
461
- ["-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"].includes(
462
- argument,
463
- ),
464
- )
465
- ) {
466
- return false;
467
- }
468
- if (
469
- command === "date" &&
470
- args.some((argument) => argument === "-s" || argument.startsWith("--set"))
471
- ) {
472
- return false;
473
- }
474
- if (
475
- (command === "sort" || command === "tree") &&
476
- args.some(
477
- (argument) =>
478
- argument === "-o" ||
479
- (argument.startsWith("-o") && !argument.startsWith("--")) ||
480
- argument.startsWith("--output"),
481
- )
482
- ) {
483
- return false;
484
- }
485
- if (
486
- command === "sort" &&
487
- args.some(
488
- (argument) =>
489
- argument === "-T" ||
490
- (argument.startsWith("-T") && argument.length > 2) ||
491
- argument.startsWith("--temporary-directory") ||
492
- argument.startsWith("--compress-program"),
493
- )
494
- ) {
495
- return false;
496
- }
497
- if (
498
- command === "diff" &&
499
- args.some((argument) => argument === "--output" || argument.startsWith("--output="))
500
- ) {
501
- return false;
502
- }
503
- if (command === "uniq" && args.filter((argument) => !argument.startsWith("-")).length > 1) {
504
- return false;
505
- }
506
- if (
507
- command === "fd" &&
508
- args.some((argument) =>
509
- ["-x", "-X", "--exec", "--exec-batch"].some(
510
- (flag) => argument === flag || argument.startsWith(`${flag}=`),
511
- ),
512
- )
513
- ) {
514
- return false;
515
- }
516
- if (
517
- command === "rg" &&
518
- args.some((argument) => argument === "--pre" || argument.startsWith("--pre="))
519
- ) {
520
- return false;
521
- }
522
- if (
523
- command === "bat" &&
524
- args.some((argument) => argument === "--pager" || argument.startsWith("--pager="))
525
- ) {
526
- return false;
527
- }
528
- return true;
418
+ const forbidden = new Set(["-i", "--in-place", "--fix", "--write", "-delete", "--delete"]);
419
+ if (args.some((argument) => forbidden.has(argument))) return false;
420
+ if (
421
+ command === "sed" &&
422
+ args.some(
423
+ (argument) => argument.startsWith("--in-place=") || (/^-[^-]+/.test(argument) && argument.slice(1).includes("i")),
424
+ )
425
+ ) {
426
+ return false;
427
+ }
428
+ if (
429
+ command === "find" &&
430
+ args.some((argument) =>
431
+ ["-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"].includes(argument),
432
+ )
433
+ ) {
434
+ return false;
435
+ }
436
+ if (command === "date" && args.some((argument) => argument === "-s" || argument.startsWith("--set"))) {
437
+ return false;
438
+ }
439
+ if (
440
+ (command === "sort" || command === "tree") &&
441
+ args.some(
442
+ (argument) =>
443
+ argument === "-o" ||
444
+ (argument.startsWith("-o") && !argument.startsWith("--")) ||
445
+ argument.startsWith("--output"),
446
+ )
447
+ ) {
448
+ return false;
449
+ }
450
+ if (
451
+ command === "sort" &&
452
+ args.some(
453
+ (argument) =>
454
+ argument === "-T" ||
455
+ (argument.startsWith("-T") && argument.length > 2) ||
456
+ argument.startsWith("--temporary-directory") ||
457
+ argument.startsWith("--compress-program"),
458
+ )
459
+ ) {
460
+ return false;
461
+ }
462
+ if (command === "diff" && args.some((argument) => argument === "--output" || argument.startsWith("--output="))) {
463
+ return false;
464
+ }
465
+ if (command === "uniq" && args.filter((argument) => !argument.startsWith("-")).length > 1) {
466
+ return false;
467
+ }
468
+ if (
469
+ command === "fd" &&
470
+ args.some((argument) =>
471
+ ["-x", "-X", "--exec", "--exec-batch"].some((flag) => argument === flag || argument.startsWith(`${flag}=`)),
472
+ )
473
+ ) {
474
+ return false;
475
+ }
476
+ if (command === "rg" && args.some((argument) => argument === "--pre" || argument.startsWith("--pre="))) {
477
+ return false;
478
+ }
479
+ if (command === "bat" && args.some((argument) => argument === "--pager" || argument.startsWith("--pager="))) {
480
+ return false;
481
+ }
482
+ return true;
529
483
  }
530
484
 
531
485
  type ArgumentValidator = (args: string[]) => boolean;
532
486
  const allowReadOnlyArguments: ArgumentValidator = () => true;
533
487
  const BUILTIN_GIT_VALIDATORS: Record<BuiltinSafeGitSubcommand, ArgumentValidator> = {
534
- status: allowReadOnlyArguments,
535
- log: allowReadOnlyArguments,
536
- diff: allowReadOnlyArguments,
537
- show: allowReadOnlyArguments,
538
- branch: isSafeGitBranchArguments,
539
- remote: isSafeGitRemoteArguments,
540
- "ls-files": allowReadOnlyArguments,
541
- grep: isSafeGitGrepArguments,
488
+ status: allowReadOnlyArguments,
489
+ log: allowReadOnlyArguments,
490
+ diff: allowReadOnlyArguments,
491
+ show: allowReadOnlyArguments,
492
+ branch: isSafeGitBranchArguments,
493
+ remote: isSafeGitRemoteArguments,
494
+ "ls-files": allowReadOnlyArguments,
495
+ grep: isSafeGitGrepArguments,
542
496
  };
543
497
  const CONFIGURABLE_GIT_VALIDATORS: Record<ConfigurableSafeGitSubcommand, ArgumentValidator> = {
544
- "rev-parse": allowReadOnlyArguments,
545
- blame: allowReadOnlyArguments,
546
- describe: allowReadOnlyArguments,
547
- "merge-base": allowReadOnlyArguments,
548
- "ls-tree": allowReadOnlyArguments,
549
- "cat-file": isSafeGitCatFileArguments,
498
+ "rev-parse": allowReadOnlyArguments,
499
+ blame: allowReadOnlyArguments,
500
+ describe: allowReadOnlyArguments,
501
+ "merge-base": allowReadOnlyArguments,
502
+ "ls-tree": allowReadOnlyArguments,
503
+ "cat-file": isSafeGitCatFileArguments,
550
504
  };
551
505
  const GH_VALIDATORS: Record<SafeGhSubcommandPath, ArgumentValidator> = {
552
- "pr view": isSafeGhReadArguments,
553
- "pr list": isSafeGhReadArguments,
554
- "issue view": isSafeGhReadArguments,
555
- "issue list": isSafeGhReadArguments,
506
+ "pr view": isSafeGhReadArguments,
507
+ "pr list": isSafeGhReadArguments,
508
+ "issue view": isSafeGhReadArguments,
509
+ "issue list": isSafeGhReadArguments,
556
510
  };
557
511
 
558
512
  function isSafeStructuredCommand(
559
- command: string,
560
- args: string[],
561
- safeSubcommands: SafeSubcommands,
562
- workingDirectory?: string,
513
+ command: string,
514
+ args: string[],
515
+ safeSubcommands: SafeSubcommands,
516
+ workingDirectory?: string,
563
517
  ) {
564
- if (command === "git") return isSafeGitCommand(args, safeSubcommands, workingDirectory);
565
- if (command === "gh") return isSafeGhCommand(args, safeSubcommands);
566
-
567
- const subcommandIndex = args.findIndex((argument) => !argument.startsWith("-"));
568
- const subcommand = args[subcommandIndex]?.toLowerCase();
569
- const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];
570
- if (command === "sed") {
571
- const script = args.find((argument) => !argument.startsWith("-"));
572
- return (
573
- Boolean(script) &&
574
- (args.includes("-n") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) &&
575
- /^\d+(,\d+)?p$/.test(script ?? "")
576
- );
577
- }
578
- if (["node", "python", "python3", "tsc", "biome", "ruff", "ty"].includes(command)) {
579
- if (args.includes("--version")) return true;
580
- return (
581
- command === "tsc" &&
582
- args.includes("--noEmit") &&
583
- !args.some(
584
- (argument) =>
585
- argument === "--incremental" ||
586
- argument.startsWith("--incremental=") ||
587
- argument === "--tsBuildInfoFile" ||
588
- argument.startsWith("--tsBuildInfoFile=") ||
589
- argument === "--generateTrace" ||
590
- argument.startsWith("--generateTrace="),
591
- )
592
- );
593
- }
594
- if (command === "npm") {
595
- if (subcommand === "audit" && subcommandArgs.includes("fix")) return false;
596
- if (
597
- ["list", "ls", "view", "info", "search", "outdated", "audit", "test"].includes(
598
- subcommand ?? "",
599
- )
600
- ) {
601
- return true;
602
- }
603
- return subcommand === "run" && ["test", "check", "typecheck", "lint"].includes(args[1] ?? "");
604
- }
605
- if (["cargo", "go", "pytest", "vitest", "jest"].includes(command)) {
606
- return (
607
- ["test", "check"].includes(subcommand ?? "") || ["pytest", "vitest", "jest"].includes(command)
608
- );
609
- }
610
- return false;
518
+ if (command === "git") return isSafeGitCommand(args, safeSubcommands, workingDirectory);
519
+ if (command === "gh") return isSafeGhCommand(args, safeSubcommands);
520
+
521
+ const subcommandIndex = args.findIndex((argument) => !argument.startsWith("-"));
522
+ const subcommand = args[subcommandIndex]?.toLowerCase();
523
+ const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];
524
+ if (command === "sed") {
525
+ const script = args.find((argument) => !argument.startsWith("-"));
526
+ return (
527
+ Boolean(script) &&
528
+ (args.includes("-n") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) &&
529
+ /^\d+(,\d+)?p$/.test(script ?? "")
530
+ );
531
+ }
532
+ if (["node", "python", "python3", "tsc", "biome", "ruff", "ty"].includes(command)) {
533
+ if (args.includes("--version")) return true;
534
+ return (
535
+ command === "tsc" &&
536
+ args.includes("--noEmit") &&
537
+ !args.some(
538
+ (argument) =>
539
+ argument === "--incremental" ||
540
+ argument.startsWith("--incremental=") ||
541
+ argument === "--tsBuildInfoFile" ||
542
+ argument.startsWith("--tsBuildInfoFile=") ||
543
+ argument === "--generateTrace" ||
544
+ argument.startsWith("--generateTrace="),
545
+ )
546
+ );
547
+ }
548
+ if (command === "npm") {
549
+ if (subcommand === "audit" && subcommandArgs.includes("fix")) return false;
550
+ if (["list", "ls", "view", "info", "search", "outdated", "audit", "test"].includes(subcommand ?? "")) {
551
+ return true;
552
+ }
553
+ return subcommand === "run" && ["test", "check", "typecheck", "lint"].includes(args[1] ?? "");
554
+ }
555
+ if (["cargo", "go", "pytest", "vitest", "jest"].includes(command)) {
556
+ return ["test", "check"].includes(subcommand ?? "") || ["pytest", "vitest", "jest"].includes(command);
557
+ }
558
+ return false;
611
559
  }
612
560
 
613
561
  function isSafeTasklistArguments(args: string[]) {
614
- for (let index = 0; index < args.length; index += 1) {
615
- const argument = args[index]?.toLowerCase();
616
- if (["/v", "/nh", "/svc"].includes(argument ?? "")) continue;
617
- if (argument === "/fo") {
618
- const format = args[index + 1]?.toLowerCase();
619
- if (!format || !["table", "list", "csv"].includes(format)) return false;
620
- index += 1;
621
- continue;
622
- }
623
- if (argument === "/fi") {
624
- const filter = args[index + 1];
625
- if (!filter || filter.startsWith("/")) return false;
626
- index += 1;
627
- continue;
628
- }
629
- if (argument === "/m") {
630
- const module = args[index + 1];
631
- if (module && !module.startsWith("/")) index += 1;
632
- continue;
633
- }
634
- return false;
635
- }
636
- return true;
562
+ for (let index = 0; index < args.length; index += 1) {
563
+ const argument = args[index]?.toLowerCase();
564
+ if (["/v", "/nh", "/svc"].includes(argument ?? "")) continue;
565
+ if (argument === "/fo") {
566
+ const format = args[index + 1]?.toLowerCase();
567
+ if (!format || !["table", "list", "csv"].includes(format)) return false;
568
+ index += 1;
569
+ continue;
570
+ }
571
+ if (argument === "/fi") {
572
+ const filter = args[index + 1];
573
+ if (!filter || filter.startsWith("/")) return false;
574
+ index += 1;
575
+ continue;
576
+ }
577
+ if (argument === "/m") {
578
+ const module = args[index + 1];
579
+ if (module && !module.startsWith("/")) index += 1;
580
+ continue;
581
+ }
582
+ return false;
583
+ }
584
+ return true;
637
585
  }
638
586
 
639
587
  function isSafeGetProcessArguments(args: string[]) {
640
- return hasSafePowerShellQueryArguments(
641
- args,
642
- new Set(["-module", "-fileversioninfo", "-includeusername"]),
643
- new Set(["-name", "-id"]),
644
- );
588
+ return hasSafePowerShellQueryArguments(
589
+ args,
590
+ new Set(["-module", "-fileversioninfo", "-includeusername"]),
591
+ new Set(["-name", "-id"]),
592
+ );
645
593
  }
646
594
 
647
595
  function isSafeGetServiceArguments(args: string[]) {
648
- return hasSafePowerShellQueryArguments(
649
- args,
650
- new Set(["-dependentservices", "-requiredservices"]),
651
- new Set(["-name", "-displayname", "-include", "-exclude"]),
652
- );
596
+ return hasSafePowerShellQueryArguments(
597
+ args,
598
+ new Set(["-dependentservices", "-requiredservices"]),
599
+ new Set(["-name", "-displayname", "-include", "-exclude"]),
600
+ );
653
601
  }
654
602
 
655
603
  function hasSafePowerShellQueryArguments(
656
- args: string[],
657
- switches: ReadonlySet<string>,
658
- valueOptions: ReadonlySet<string>,
659
- ) {
660
- let positionalValues = 0;
661
- for (let index = 0; index < args.length; index += 1) {
662
- const argument = args[index];
663
- const normalized = argument?.toLowerCase();
664
- if (!argument || !normalized) return false;
665
- if (!argument.startsWith("-")) {
666
- positionalValues += 1;
667
- if (positionalValues > 1) return false;
668
- continue;
669
- }
670
- if (switches.has(normalized)) continue;
671
- if (!valueOptions.has(normalized)) return false;
672
- const value = args[index + 1];
673
- if (!value || value.startsWith("-")) return false;
674
- index += 1;
675
- }
676
- return true;
677
- }
678
-
679
- function isSafeGitCommand(
680
- args: string[],
681
- safeSubcommands: SafeSubcommands,
682
- workingDirectory?: string,
604
+ args: string[],
605
+ switches: ReadonlySet<string>,
606
+ valueOptions: ReadonlySet<string>,
683
607
  ) {
684
- const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);
685
- if (subcommandIndex === undefined) return false;
686
- const subcommand = args[subcommandIndex]?.toLowerCase();
687
- if (!subcommand || subcommand.startsWith("-")) return false;
688
- const subcommandArgs = args.slice(subcommandIndex + 1);
689
- const builtinValidator = (BUILTIN_GIT_VALIDATORS as Record<string, ArgumentValidator>)[
690
- subcommand
691
- ];
692
- const configuredValidator = (CONFIGURABLE_GIT_VALIDATORS as Record<string, ArgumentValidator>)[
693
- subcommand
694
- ];
695
- const configured = safeSubcommands.git?.includes(subcommand as SafeGitSubcommand) === true;
696
- const validator = builtinValidator ?? (configured ? configuredValidator : undefined);
697
- return (
698
- validator !== undefined &&
699
- hasSafeGitArguments(subcommand, subcommandArgs) &&
700
- validator(subcommandArgs)
701
- );
608
+ let positionalValues = 0;
609
+ for (let index = 0; index < args.length; index += 1) {
610
+ const argument = args[index];
611
+ const normalized = argument?.toLowerCase();
612
+ if (!argument || !normalized) return false;
613
+ if (!argument.startsWith("-")) {
614
+ positionalValues += 1;
615
+ if (positionalValues > 1) return false;
616
+ continue;
617
+ }
618
+ if (switches.has(normalized)) continue;
619
+ if (!valueOptions.has(normalized)) return false;
620
+ const value = args[index + 1];
621
+ if (!value || value.startsWith("-")) return false;
622
+ index += 1;
623
+ }
624
+ return true;
625
+ }
626
+
627
+ function isSafeGitCommand(args: string[], safeSubcommands: SafeSubcommands, workingDirectory?: string) {
628
+ const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);
629
+ if (subcommandIndex === undefined) return false;
630
+ const subcommand = args[subcommandIndex]?.toLowerCase();
631
+ if (!subcommand || subcommand.startsWith("-")) return false;
632
+ const subcommandArgs = args.slice(subcommandIndex + 1);
633
+ const builtinValidator = (BUILTIN_GIT_VALIDATORS as Record<string, ArgumentValidator>)[subcommand];
634
+ const configuredValidator = (CONFIGURABLE_GIT_VALIDATORS as Record<string, ArgumentValidator>)[subcommand];
635
+ const configured = safeSubcommands.git?.includes(subcommand as SafeGitSubcommand) === true;
636
+ const validator = builtinValidator ?? (configured ? configuredValidator : undefined);
637
+ return validator !== undefined && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);
702
638
  }
703
639
 
704
640
  function parseGitGlobalOptions(args: string[], workingDirectory?: string) {
705
- let index = 0;
706
- while (index < args.length) {
707
- const argument = args[index];
708
- if (argument === "--no-pager") {
709
- index += 1;
710
- continue;
711
- }
712
- if (argument !== "-C") break;
713
- const directory = args[index + 1];
714
- if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return undefined;
715
- index += 2;
716
- }
717
- return index;
641
+ let index = 0;
642
+ while (index < args.length) {
643
+ const argument = args[index];
644
+ if (argument === "--no-pager") {
645
+ index += 1;
646
+ continue;
647
+ }
648
+ if (argument !== "-C") break;
649
+ const directory = args[index + 1];
650
+ if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return undefined;
651
+ index += 2;
652
+ }
653
+ return index;
718
654
  }
719
655
 
720
656
  function isCurrentWorkingDirectory(directory: string, workingDirectory?: string) {
721
- if (!workingDirectory || directory.split(/[\\/]+/u).includes("..")) return false;
722
- if (normalize(directory) === ".") return true;
723
- return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);
657
+ if (!workingDirectory || directory.split(/[\\/]+/u).includes("..")) return false;
658
+ if (normalize(directory) === ".") return true;
659
+ return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);
724
660
  }
725
661
 
726
662
  function hasSafeGitArguments(subcommand: string, args: string[]) {
727
- return !args.some(
728
- (argument) =>
729
- argument === "--help" ||
730
- argument === "--show-signature" ||
731
- argument.startsWith("--show-signature=") ||
732
- argument.includes("%G") ||
733
- argument === "--output" ||
734
- argument.startsWith("--output=") ||
735
- argument === "--ext-diff" ||
736
- argument.startsWith("--ext-diff=") ||
737
- argument === "--textconv" ||
738
- argument.startsWith("--textconv=") ||
739
- argument === "--paginate" ||
740
- argument === "--open-files-in-pager" ||
741
- argument.startsWith("--open-files-in-pager=") ||
742
- (subcommand === "grep" && (argument === "-O" || argument.startsWith("-O"))),
743
- );
663
+ return !args.some(
664
+ (argument) =>
665
+ argument === "--help" ||
666
+ argument === "--show-signature" ||
667
+ argument.startsWith("--show-signature=") ||
668
+ argument.includes("%G") ||
669
+ argument === "--output" ||
670
+ argument.startsWith("--output=") ||
671
+ argument === "--ext-diff" ||
672
+ argument.startsWith("--ext-diff=") ||
673
+ argument === "--textconv" ||
674
+ argument.startsWith("--textconv=") ||
675
+ argument === "--paginate" ||
676
+ argument === "--open-files-in-pager" ||
677
+ argument.startsWith("--open-files-in-pager=") ||
678
+ (subcommand === "grep" && (argument === "-O" || argument.startsWith("-O"))),
679
+ );
744
680
  }
745
681
 
746
682
  function isSafeGitCatFileArguments(args: string[]) {
747
- return !args.some(
748
- (argument) =>
749
- matchesLongOptionPrefix(argument, "--filters", "--fi") ||
750
- matchesLongOptionPrefix(argument, "--textconv", "--t"),
751
- );
683
+ return !args.some(
684
+ (argument) =>
685
+ matchesLongOptionPrefix(argument, "--filters", "--fi") || matchesLongOptionPrefix(argument, "--textconv", "--t"),
686
+ );
752
687
  }
753
688
 
754
689
  function isSafeGitGrepArguments(args: string[]) {
755
- return !args.some(
756
- (argument) =>
757
- matchesLongOptionPrefix(argument, "--textconv", "--textc") ||
758
- matchesLongOptionPrefix(argument, "--open-files-in-pager", "--op") ||
759
- matchesLongOptionPrefix(argument, "--ext-grep", "--ext"),
760
- );
690
+ return !args.some(
691
+ (argument) =>
692
+ matchesLongOptionPrefix(argument, "--textconv", "--textc") ||
693
+ matchesLongOptionPrefix(argument, "--open-files-in-pager", "--op") ||
694
+ matchesLongOptionPrefix(argument, "--ext-grep", "--ext"),
695
+ );
761
696
  }
762
697
 
763
698
  function matchesLongOptionPrefix(argument: string, option: string, shortest: string) {
764
- const optionName = argument.split("=", 1)[0] ?? "";
765
- return optionName.length >= shortest.length && option.startsWith(optionName);
699
+ const optionName = argument.split("=", 1)[0] ?? "";
700
+ return optionName.length >= shortest.length && option.startsWith(optionName);
766
701
  }
767
702
 
768
703
  function isSafeGitBranchArguments(args: string[]) {
769
- if (args.some((argument) => !argument.startsWith("-"))) return false;
770
- return !args.some(
771
- (argument) =>
772
- /^-[^-]*[dDmMcCu]/.test(argument) ||
773
- matchesLongOptionPrefix(argument, "--delete", "--del") ||
774
- matchesLongOptionPrefix(argument, "--move", "--mov") ||
775
- matchesLongOptionPrefix(argument, "--copy", "--cop") ||
776
- matchesLongOptionPrefix(argument, "--edit-description", "--e") ||
777
- matchesLongOptionPrefix(argument, "--unset-upstream", "--u") ||
778
- matchesLongOptionPrefix(argument, "--set-upstream-to", "--set-u") ||
779
- matchesLongOptionPrefix(argument, "--create-reflog", "--creat"),
780
- );
704
+ if (args.some((argument) => !argument.startsWith("-"))) return false;
705
+ return !args.some(
706
+ (argument) =>
707
+ /^-[^-]*[dDmMcCu]/.test(argument) ||
708
+ matchesLongOptionPrefix(argument, "--delete", "--del") ||
709
+ matchesLongOptionPrefix(argument, "--move", "--mov") ||
710
+ matchesLongOptionPrefix(argument, "--copy", "--cop") ||
711
+ matchesLongOptionPrefix(argument, "--edit-description", "--e") ||
712
+ matchesLongOptionPrefix(argument, "--unset-upstream", "--u") ||
713
+ matchesLongOptionPrefix(argument, "--set-upstream-to", "--set-u") ||
714
+ matchesLongOptionPrefix(argument, "--create-reflog", "--creat"),
715
+ );
781
716
  }
782
717
 
783
718
  function isSafeGitRemoteArguments(args: string[]) {
784
- const actionIndex = args.findIndex((argument) => !argument.startsWith("-"));
785
- if (actionIndex < 0) return true;
786
- const action = args[actionIndex];
787
- if (action === "get-url") return true;
788
- if (action !== "show") return false;
719
+ const actionIndex = args.findIndex((argument) => !argument.startsWith("-"));
720
+ if (actionIndex < 0) return true;
721
+ const action = args[actionIndex];
722
+ if (action === "get-url") return true;
723
+ if (action !== "show") return false;
789
724
 
790
- const showArgs = args.slice(actionIndex + 1);
791
- if (showArgs.includes("--")) return false;
792
- const remotes = showArgs.filter((argument) => !argument.startsWith("-"));
793
- return remotes.length === 0 || (remotes.length === 1 && showArgs.includes("-n"));
725
+ const showArgs = args.slice(actionIndex + 1);
726
+ if (showArgs.includes("--")) return false;
727
+ const remotes = showArgs.filter((argument) => !argument.startsWith("-"));
728
+ return remotes.length === 0 || (remotes.length === 1 && showArgs.includes("-n"));
794
729
  }
795
730
 
796
731
  function isSafeGhCommand(args: string[], safeSubcommands: SafeSubcommands) {
797
- const group = args[0]?.toLowerCase();
798
- const action = args[1]?.toLowerCase();
799
- if (!group || !action || group.startsWith("-") || action.startsWith("-")) return false;
800
- const path = `${group} ${action}` as SafeGhSubcommandPath;
801
- if (!safeSubcommands.gh?.includes(path)) return false;
802
- const validator = (GH_VALIDATORS as Record<string, ArgumentValidator>)[path];
803
- return validator?.(args.slice(2)) ?? false;
732
+ const group = args[0]?.toLowerCase();
733
+ const action = args[1]?.toLowerCase();
734
+ if (!group || !action || group.startsWith("-") || action.startsWith("-")) return false;
735
+ const path = `${group} ${action}` as SafeGhSubcommandPath;
736
+ if (!safeSubcommands.gh?.includes(path)) return false;
737
+ const validator = (GH_VALIDATORS as Record<string, ArgumentValidator>)[path];
738
+ return validator?.(args.slice(2)) ?? false;
804
739
  }
805
740
 
806
741
  function isSafeGhReadArguments(args: string[]) {
807
- return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);
742
+ return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);
808
743
  }
809
744
 
810
745
  function isUnsafeGhReadArgument(argument: string) {
811
- return (
812
- argument.startsWith("-w") ||
813
- argument === "--web" ||
814
- argument.startsWith("--web=") ||
815
- argument === "--browser" ||
816
- argument.startsWith("--browser=") ||
817
- argument === "--paginate" ||
818
- argument === "--pager" ||
819
- argument.startsWith("--pager=") ||
820
- argument === "--output" ||
821
- argument.startsWith("--output=")
822
- );
746
+ return (
747
+ argument.startsWith("-w") ||
748
+ argument === "--web" ||
749
+ argument.startsWith("--web=") ||
750
+ argument === "--browser" ||
751
+ argument.startsWith("--browser=") ||
752
+ argument === "--paginate" ||
753
+ argument === "--pager" ||
754
+ argument.startsWith("--pager=") ||
755
+ argument === "--output" ||
756
+ argument.startsWith("--output=")
757
+ );
823
758
  }
824
759
 
825
760
  function hasGhJsonOutput(args: string[]) {
826
- let hasJson = false;
827
- for (let index = 0; index < args.length; index += 1) {
828
- const argument = args[index];
829
- if (argument === "--json") {
830
- const value = args[index + 1];
831
- if (!value || value.startsWith("-")) return false;
832
- hasJson = true;
833
- index += 1;
834
- } else if (argument.startsWith("--json=")) {
835
- if (argument === "--json=") return false;
836
- hasJson = true;
837
- }
838
- }
839
- return hasJson;
761
+ let hasJson = false;
762
+ for (let index = 0; index < args.length; index += 1) {
763
+ const argument = args[index];
764
+ if (argument === "--json") {
765
+ const value = args[index + 1];
766
+ if (!value || value.startsWith("-")) return false;
767
+ hasJson = true;
768
+ index += 1;
769
+ } else if (argument.startsWith("--json=")) {
770
+ if (argument === "--json=") return false;
771
+ hasJson = true;
772
+ }
773
+ }
774
+ return hasJson;
840
775
  }