@wrongstack/tools 0.5.6 → 0.6.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.
- package/dist/bash.d.ts +2 -1
- package/dist/bash.js +361 -3
- package/dist/bash.js.map +1 -1
- package/dist/builtin.js +408 -12
- package/dist/builtin.js.map +1 -1
- package/dist/circuit-breaker.d.ts +111 -0
- package/dist/circuit-breaker.js +150 -0
- package/dist/circuit-breaker.js.map +1 -0
- package/dist/exec.js +355 -4
- package/dist/exec.js.map +1 -1
- package/dist/fetch.js.map +1 -1
- package/dist/grep.js +9 -4
- package/dist/grep.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +412 -13
- package/dist/index.js.map +1 -1
- package/dist/logs.js +9 -4
- package/dist/logs.js.map +1 -1
- package/dist/pack.js +408 -12
- package/dist/pack.js.map +1 -1
- package/dist/process-registry.d.ts +112 -0
- package/dist/process-registry.js +327 -0
- package/dist/process-registry.js.map +1 -0
- package/dist/replace.js +9 -4
- package/dist/replace.js.map +1 -1
- package/dist/scaffold.js +2 -1
- package/dist/scaffold.js.map +1 -1
- package/package.json +10 -2
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { ChildProcess } from 'node:child_process';
|
|
2
|
+
import { CircuitBreakerSnapshot, CircuitBreakerConfig } from './circuit-breaker.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ProcessRegistry — global singleton that tracks all spawned child processes
|
|
6
|
+
* from `bash` and `exec` tools. Enables:
|
|
7
|
+
*
|
|
8
|
+
* - Listing active processes (for TUI status bar)
|
|
9
|
+
* - Killing individual processes or all processes (for Ctrl+C and /kill)
|
|
10
|
+
* - Detecting runaway processes (hung, looping)
|
|
11
|
+
* - Circuit breaker integration to prevent recursive/repeated failures
|
|
12
|
+
*
|
|
13
|
+
* Thread-safety: Node.js is single-threaded, but async callbacks can fire
|
|
14
|
+
* in any order. All mutations go through synchronized Map methods.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
interface TrackedProcess {
|
|
18
|
+
pid: number;
|
|
19
|
+
name: string;
|
|
20
|
+
command: string;
|
|
21
|
+
startedAt: number;
|
|
22
|
+
sessionId?: string;
|
|
23
|
+
/** The raw ChildProcess handle. Never call .kill() directly on this —
|
|
24
|
+
* use `kill()` below which handles process groups correctly on POSIX
|
|
25
|
+
* and degrades gracefully on Windows. */
|
|
26
|
+
child: ChildProcess;
|
|
27
|
+
/** True once the process has been kill()ed but not yet exited.
|
|
28
|
+
* We keep it in the registry until 'close' fires so callers can
|
|
29
|
+
* distinguish "still running" from "just exited". */
|
|
30
|
+
killed: boolean;
|
|
31
|
+
}
|
|
32
|
+
interface KillOpts {
|
|
33
|
+
/** SIGKILL instead of SIGTERM. Default: false (SIGTERM first). */
|
|
34
|
+
force?: boolean;
|
|
35
|
+
/** MS to wait between SIGTERM and SIGKILL on POSIX. Default: 2000. */
|
|
36
|
+
graceMs?: number;
|
|
37
|
+
}
|
|
38
|
+
interface RegistryStats {
|
|
39
|
+
activeCount: number;
|
|
40
|
+
totalCount: number;
|
|
41
|
+
breaker: CircuitBreakerSnapshot;
|
|
42
|
+
}
|
|
43
|
+
declare class ProcessRegistryImpl {
|
|
44
|
+
private readonly processes;
|
|
45
|
+
private readonly breaker;
|
|
46
|
+
constructor(breakerConfig?: CircuitBreakerConfig);
|
|
47
|
+
register(info: Omit<TrackedProcess, 'killed'>): void;
|
|
48
|
+
/** Unregister a process by PID. Called on 'close' / 'exit' events. */
|
|
49
|
+
unregister(pid: number): void;
|
|
50
|
+
/** Get a single process by PID. */
|
|
51
|
+
get(pid: number): TrackedProcess | undefined;
|
|
52
|
+
/** Get all tracked processes. */
|
|
53
|
+
list(): TrackedProcess[];
|
|
54
|
+
/** Get processes filtered by name (e.g. 'bash', 'exec'). */
|
|
55
|
+
byName(name: string): TrackedProcess[];
|
|
56
|
+
/** Get processes filtered by session. */
|
|
57
|
+
bySession(sessionId: string): TrackedProcess[];
|
|
58
|
+
/** Count of active (non-killed) processes. */
|
|
59
|
+
get activeCount(): number;
|
|
60
|
+
/**
|
|
61
|
+
* Combined stats for observability — used by /ps and the TUI status bar.
|
|
62
|
+
*/
|
|
63
|
+
stats(): RegistryStats;
|
|
64
|
+
/**
|
|
65
|
+
* Returns true if the circuit allows a new bash/exec call to proceed.
|
|
66
|
+
* When false, callers MUST NOT spawn a process.
|
|
67
|
+
*/
|
|
68
|
+
get canProceed(): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Called before spawning a process. Returns true if allowed; false if
|
|
71
|
+
* the circuit breaker is open.
|
|
72
|
+
*/
|
|
73
|
+
beforeCall(): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Called after a process finishes. `durationMs` is wall-clock time;
|
|
76
|
+
* `failed` is true for non-zero exit codes.
|
|
77
|
+
*/
|
|
78
|
+
afterCall(durationMs: number, failed: boolean): void;
|
|
79
|
+
/** Force-open the circuit breaker (Ctrl+C, /kill force). */
|
|
80
|
+
forceBreakerOpen(): void;
|
|
81
|
+
/** Force-reset the circuit breaker to closed (/kill reset). */
|
|
82
|
+
forceBreakerReset(): void;
|
|
83
|
+
/** Kill a single process by PID.
|
|
84
|
+
*
|
|
85
|
+
* On POSIX: sends SIGTERM to the *process group* (-pid) so that
|
|
86
|
+
* runaway grandchild processes (`sleep 9999 & disown`) are also killed.
|
|
87
|
+
* After `graceMs` a SIGKILL is sent if the process hasn't exited.
|
|
88
|
+
*
|
|
89
|
+
* On Windows: `child.kill()` maps to TerminateProcess — process groups
|
|
90
|
+
* are not meaningfully supported. A second `force=true` call sends
|
|
91
|
+
* SIGKILL (which maps to TerminateProcess again — the distinction is
|
|
92
|
+
* in the exit code, not the signal).
|
|
93
|
+
*
|
|
94
|
+
* Returns true if the process was found and kill was attempted.
|
|
95
|
+
*/
|
|
96
|
+
kill(pid: number, opts?: KillOpts): boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Kill all tracked processes.
|
|
99
|
+
* Returns the PIDs that were kill()ed.
|
|
100
|
+
*/
|
|
101
|
+
killAll(opts?: KillOpts): number[];
|
|
102
|
+
/**
|
|
103
|
+
* Kill all processes for a specific session.
|
|
104
|
+
* Returns the PIDs that were kill()ed.
|
|
105
|
+
*/
|
|
106
|
+
killSession(sessionId: string, opts?: KillOpts): number[];
|
|
107
|
+
}
|
|
108
|
+
declare function getProcessRegistry(): ProcessRegistryImpl;
|
|
109
|
+
/** Reset for tests. */
|
|
110
|
+
declare function _resetProcessRegistry(): void;
|
|
111
|
+
|
|
112
|
+
export { CircuitBreakerConfig, CircuitBreakerSnapshot, type KillOpts, type RegistryStats, type TrackedProcess, _resetProcessRegistry, getProcessRegistry };
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import * as os from 'os';
|
|
2
|
+
|
|
3
|
+
// src/process-registry.ts
|
|
4
|
+
|
|
5
|
+
// src/circuit-breaker.ts
|
|
6
|
+
var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
|
|
7
|
+
var DEFAULT_SLOW_CALL_THRESHOLD_MS = 6e4;
|
|
8
|
+
var DEFAULT_MAX_SLOW_CALLS = 3;
|
|
9
|
+
var DEFAULT_WINDOW_MS = 6e4;
|
|
10
|
+
var DEFAULT_MAX_CALLS_PER_WINDOW = 30;
|
|
11
|
+
var DEFAULT_COOLDOWN_MS = 3e4;
|
|
12
|
+
var CircuitBreaker = class {
|
|
13
|
+
maxConsecutiveFailures;
|
|
14
|
+
slowCallThresholdMs;
|
|
15
|
+
maxSlowCalls;
|
|
16
|
+
windowMs;
|
|
17
|
+
maxCallsPerWindow;
|
|
18
|
+
cooldownMs;
|
|
19
|
+
state = "closed";
|
|
20
|
+
consecutiveFailures = 0;
|
|
21
|
+
window = [];
|
|
22
|
+
lastFailureAt = null;
|
|
23
|
+
lastSlowAt = null;
|
|
24
|
+
/** Timestamp when the breaker was opened (for cooldown calculation). */
|
|
25
|
+
openedAt = null;
|
|
26
|
+
/** Timestamp when the last call ran (for half-open gate). */
|
|
27
|
+
lastCallAt = null;
|
|
28
|
+
constructor(config = {}) {
|
|
29
|
+
this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
|
|
30
|
+
this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
|
|
31
|
+
this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
|
|
32
|
+
this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
|
|
33
|
+
this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
|
|
34
|
+
this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Returns true if the circuit allows a new call to proceed.
|
|
38
|
+
* When false, callers should abort the tool call and return a
|
|
39
|
+
* circuit-breaker error instead of spawning a process.
|
|
40
|
+
*/
|
|
41
|
+
get canProceed() {
|
|
42
|
+
this._checkStateTransition();
|
|
43
|
+
return this.state !== "open";
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Snapshot of the current breaker state for observability (`/kill`).
|
|
47
|
+
*/
|
|
48
|
+
snapshot() {
|
|
49
|
+
this._checkStateTransition();
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
let cooldownRemaining = null;
|
|
52
|
+
if (this.openedAt !== null && this.state === "open") {
|
|
53
|
+
const elapsed = now - this.openedAt;
|
|
54
|
+
cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
state: this.state,
|
|
58
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
59
|
+
slowCallsInWindow: this.window.filter((c) => c.slow).length,
|
|
60
|
+
callsInWindow: this.window.length,
|
|
61
|
+
windowMs: this.windowMs,
|
|
62
|
+
cooldownRemainingMs: cooldownRemaining,
|
|
63
|
+
lastFailureAt: this.lastFailureAt,
|
|
64
|
+
lastSlowAt: this.lastSlowAt
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Call this BEFORE spawning a bash/exec process.
|
|
69
|
+
* Returns true if the call is allowed; false if the breaker is open.
|
|
70
|
+
* When false, callers MUST NOT spawn a process.
|
|
71
|
+
*/
|
|
72
|
+
beforeCall() {
|
|
73
|
+
this._checkStateTransition();
|
|
74
|
+
if (this.state === "open") return false;
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Call this AFTER a bash/exec process finishes (success or failure).
|
|
79
|
+
* `durationMs` is the wall-clock time the process ran.
|
|
80
|
+
* `failed` is true when the process returned a non-zero exit code or
|
|
81
|
+
* threw an exception before spawning.
|
|
82
|
+
*/
|
|
83
|
+
afterCall(durationMs, failed) {
|
|
84
|
+
const now = Date.now();
|
|
85
|
+
this.lastCallAt = now;
|
|
86
|
+
if (this.state === "half-open") {
|
|
87
|
+
if (failed) {
|
|
88
|
+
this._trip();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
this._reset();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
this._pruneWindow(now);
|
|
95
|
+
const slow = durationMs >= this.slowCallThresholdMs;
|
|
96
|
+
this.window.push({ at: now, failed, slow });
|
|
97
|
+
if (failed) {
|
|
98
|
+
this.consecutiveFailures++;
|
|
99
|
+
this.lastFailureAt = now;
|
|
100
|
+
if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
|
|
101
|
+
this._trip();
|
|
102
|
+
}
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.consecutiveFailures = 0;
|
|
106
|
+
if (slow) {
|
|
107
|
+
this.lastSlowAt = now;
|
|
108
|
+
const slowCount = this.window.filter((c) => c.slow).length;
|
|
109
|
+
if (slowCount >= this.maxSlowCalls) {
|
|
110
|
+
this._trip();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const callCount = this.window.length;
|
|
114
|
+
if (callCount >= this.maxCallsPerWindow) {
|
|
115
|
+
this._trip();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Force the breaker open. Used by /kill force and Ctrl+C. */
|
|
119
|
+
forceOpen() {
|
|
120
|
+
this._trip();
|
|
121
|
+
}
|
|
122
|
+
/** Force a reset to closed. Used by tests and /kill reset. */
|
|
123
|
+
forceReset() {
|
|
124
|
+
this._reset();
|
|
125
|
+
}
|
|
126
|
+
_trip() {
|
|
127
|
+
if (this.state === "open") return;
|
|
128
|
+
this.state = "open";
|
|
129
|
+
this.openedAt = Date.now();
|
|
130
|
+
}
|
|
131
|
+
_reset() {
|
|
132
|
+
this.state = "closed";
|
|
133
|
+
this.consecutiveFailures = 0;
|
|
134
|
+
this.window = [];
|
|
135
|
+
this.openedAt = null;
|
|
136
|
+
}
|
|
137
|
+
/** Transition from open → half-open when cooldown elapses. */
|
|
138
|
+
_checkStateTransition() {
|
|
139
|
+
if (this.state !== "open" || this.openedAt === null) return;
|
|
140
|
+
const elapsed = Date.now() - this.openedAt;
|
|
141
|
+
if (elapsed >= this.cooldownMs) {
|
|
142
|
+
this.state = "half-open";
|
|
143
|
+
this.openedAt = null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
_pruneWindow(now) {
|
|
147
|
+
const cutoff = now - this.windowMs;
|
|
148
|
+
this.window = this.window.filter((c) => c.at >= cutoff);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/process-registry.ts
|
|
153
|
+
var DEFAULT_GRACE_MS = 2e3;
|
|
154
|
+
var ProcessRegistryImpl = class {
|
|
155
|
+
processes = /* @__PURE__ */ new Map();
|
|
156
|
+
breaker;
|
|
157
|
+
constructor(breakerConfig) {
|
|
158
|
+
this.breaker = new CircuitBreaker(breakerConfig);
|
|
159
|
+
}
|
|
160
|
+
register(info) {
|
|
161
|
+
this.processes.set(info.pid, { ...info, killed: false });
|
|
162
|
+
}
|
|
163
|
+
/** Unregister a process by PID. Called on 'close' / 'exit' events. */
|
|
164
|
+
unregister(pid) {
|
|
165
|
+
this.processes.delete(pid);
|
|
166
|
+
}
|
|
167
|
+
/** Get a single process by PID. */
|
|
168
|
+
get(pid) {
|
|
169
|
+
return this.processes.get(pid);
|
|
170
|
+
}
|
|
171
|
+
/** Get all tracked processes. */
|
|
172
|
+
list() {
|
|
173
|
+
return Array.from(this.processes.values());
|
|
174
|
+
}
|
|
175
|
+
/** Get processes filtered by name (e.g. 'bash', 'exec'). */
|
|
176
|
+
byName(name) {
|
|
177
|
+
return this.list().filter((p) => p.name === name);
|
|
178
|
+
}
|
|
179
|
+
/** Get processes filtered by session. */
|
|
180
|
+
bySession(sessionId) {
|
|
181
|
+
return this.list().filter((p) => p.sessionId === sessionId);
|
|
182
|
+
}
|
|
183
|
+
/** Count of active (non-killed) processes. */
|
|
184
|
+
get activeCount() {
|
|
185
|
+
let n = 0;
|
|
186
|
+
for (const p of this.processes.values()) {
|
|
187
|
+
if (!p.killed) n++;
|
|
188
|
+
}
|
|
189
|
+
return n;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Combined stats for observability — used by /ps and the TUI status bar.
|
|
193
|
+
*/
|
|
194
|
+
stats() {
|
|
195
|
+
return {
|
|
196
|
+
activeCount: this.activeCount,
|
|
197
|
+
totalCount: this.processes.size,
|
|
198
|
+
breaker: this.breaker.snapshot()
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Returns true if the circuit allows a new bash/exec call to proceed.
|
|
203
|
+
* When false, callers MUST NOT spawn a process.
|
|
204
|
+
*/
|
|
205
|
+
get canProceed() {
|
|
206
|
+
return this.breaker.canProceed;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Called before spawning a process. Returns true if allowed; false if
|
|
210
|
+
* the circuit breaker is open.
|
|
211
|
+
*/
|
|
212
|
+
beforeCall() {
|
|
213
|
+
return this.breaker.beforeCall();
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Called after a process finishes. `durationMs` is wall-clock time;
|
|
217
|
+
* `failed` is true for non-zero exit codes.
|
|
218
|
+
*/
|
|
219
|
+
afterCall(durationMs, failed) {
|
|
220
|
+
this.breaker.afterCall(durationMs, failed);
|
|
221
|
+
}
|
|
222
|
+
/** Force-open the circuit breaker (Ctrl+C, /kill force). */
|
|
223
|
+
forceBreakerOpen() {
|
|
224
|
+
this.breaker.forceOpen();
|
|
225
|
+
}
|
|
226
|
+
/** Force-reset the circuit breaker to closed (/kill reset). */
|
|
227
|
+
forceBreakerReset() {
|
|
228
|
+
this.breaker.forceReset();
|
|
229
|
+
}
|
|
230
|
+
/** Kill a single process by PID.
|
|
231
|
+
*
|
|
232
|
+
* On POSIX: sends SIGTERM to the *process group* (-pid) so that
|
|
233
|
+
* runaway grandchild processes (`sleep 9999 & disown`) are also killed.
|
|
234
|
+
* After `graceMs` a SIGKILL is sent if the process hasn't exited.
|
|
235
|
+
*
|
|
236
|
+
* On Windows: `child.kill()` maps to TerminateProcess — process groups
|
|
237
|
+
* are not meaningfully supported. A second `force=true` call sends
|
|
238
|
+
* SIGKILL (which maps to TerminateProcess again — the distinction is
|
|
239
|
+
* in the exit code, not the signal).
|
|
240
|
+
*
|
|
241
|
+
* Returns true if the process was found and kill was attempted.
|
|
242
|
+
*/
|
|
243
|
+
kill(pid, opts = {}) {
|
|
244
|
+
const p = this.processes.get(pid);
|
|
245
|
+
if (!p) return false;
|
|
246
|
+
if (p.killed) return true;
|
|
247
|
+
const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
|
|
248
|
+
const isWin = os.platform() === "win32";
|
|
249
|
+
if (isWin) {
|
|
250
|
+
try {
|
|
251
|
+
p.child.kill(force ? "SIGKILL" : "SIGTERM");
|
|
252
|
+
} catch {
|
|
253
|
+
}
|
|
254
|
+
p.killed = true;
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
if (force) {
|
|
259
|
+
try {
|
|
260
|
+
process.kill(-pid, "SIGKILL");
|
|
261
|
+
} catch {
|
|
262
|
+
p.child.kill("SIGKILL");
|
|
263
|
+
}
|
|
264
|
+
} else {
|
|
265
|
+
try {
|
|
266
|
+
process.kill(-pid, "SIGTERM");
|
|
267
|
+
} catch {
|
|
268
|
+
p.child.kill("SIGTERM");
|
|
269
|
+
}
|
|
270
|
+
const timer = setTimeout(() => {
|
|
271
|
+
if (this.processes.has(pid) && !p.child.killed) {
|
|
272
|
+
try {
|
|
273
|
+
process.kill(-pid, "SIGKILL");
|
|
274
|
+
} catch {
|
|
275
|
+
try {
|
|
276
|
+
p.child.kill("SIGKILL");
|
|
277
|
+
} catch {
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}, graceMs);
|
|
282
|
+
timer.unref?.();
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
}
|
|
286
|
+
p.killed = true;
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Kill all tracked processes.
|
|
291
|
+
* Returns the PIDs that were kill()ed.
|
|
292
|
+
*/
|
|
293
|
+
killAll(opts = {}) {
|
|
294
|
+
const pids = Array.from(this.processes.keys());
|
|
295
|
+
const killed = [];
|
|
296
|
+
for (const pid of pids) {
|
|
297
|
+
if (this.kill(pid, opts)) killed.push(pid);
|
|
298
|
+
}
|
|
299
|
+
return killed;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Kill all processes for a specific session.
|
|
303
|
+
* Returns the PIDs that were kill()ed.
|
|
304
|
+
*/
|
|
305
|
+
killSession(sessionId, opts = {}) {
|
|
306
|
+
const pids = this.bySession(sessionId).map((p) => p.pid);
|
|
307
|
+
const killed = [];
|
|
308
|
+
for (const pid of pids) {
|
|
309
|
+
if (this.kill(pid, opts)) killed.push(pid);
|
|
310
|
+
}
|
|
311
|
+
return killed;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
var _registry;
|
|
315
|
+
function getProcessRegistry() {
|
|
316
|
+
if (!_registry) {
|
|
317
|
+
_registry = new ProcessRegistryImpl();
|
|
318
|
+
}
|
|
319
|
+
return _registry;
|
|
320
|
+
}
|
|
321
|
+
function _resetProcessRegistry() {
|
|
322
|
+
_registry = void 0;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export { _resetProcessRegistry, getProcessRegistry };
|
|
326
|
+
//# sourceMappingURL=process-registry.js.map
|
|
327
|
+
//# sourceMappingURL=process-registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/circuit-breaker.ts","../src/process-registry.ts"],"names":[],"mappings":";;;;;AA6DA,IAAM,gCAAA,GAAmC,CAAA;AACzC,IAAM,8BAAA,GAAiC,GAAA;AACvC,IAAM,sBAAA,GAAyB,CAAA;AAC/B,IAAM,iBAAA,GAAoB,GAAA;AAC1B,IAAM,4BAAA,GAA+B,EAAA;AACrC,IAAM,mBAAA,GAAsB,GAAA;AAarB,IAAM,iBAAN,MAAqB;AAAA,EACT,sBAAA;AAAA,EACA,mBAAA;AAAA,EACA,YAAA;AAAA,EACA,QAAA;AAAA,EACA,iBAAA;AAAA,EACA,UAAA;AAAA,EAET,KAAA,GAAsB,QAAA;AAAA,EACtB,mBAAA,GAAsB,CAAA;AAAA,EACtB,SAAuB,EAAC;AAAA,EACxB,aAAA,GAA+B,IAAA;AAAA,EAC/B,UAAA,GAA4B,IAAA;AAAA;AAAA,EAE5B,QAAA,GAA0B,IAAA;AAAA;AAAA,EAE1B,UAAA,GAA4B,IAAA;AAAA,EAEpC,WAAA,CAAY,MAAA,GAA+B,EAAC,EAAG;AAC7C,IAAA,IAAA,CAAK,sBAAA,GAAyB,OAAO,sBAAA,IAA0B,gCAAA;AAC/D,IAAA,IAAA,CAAK,mBAAA,GAAsB,OAAO,mBAAA,IAAuB,8BAAA;AACzD,IAAA,IAAA,CAAK,YAAA,GAAe,OAAO,YAAA,IAAgB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,GAAY,MAAA;AACd","file":"process-registry.js","sourcesContent":["/**\n * CircuitBreaker — prevents runaway bash/exec tool chains by:\n *\n * - Tripping on consecutive failures (models that keep repeating the\n * same failing command, e.g. `npm install` with wrong args in a loop)\n * - Tripping on slow call ratio (too many long-running commands suggest\n * a hung subprocess that the model doesn't know how to kill)\n * - Rate-limiting bursts (rapid succession of commands without reading\n * output suggests the model isn't processing results)\n * - Auto-recovering after a cooldown period so a fixed model can resume\n *\n * The breaker is owned by the ProcessRegistry so any tool that registers\n * a process participates in the same circuit. \"Per-tool\" isolation is\n * intentionally NOT implemented — the model treats bash/exec as one\n * resource pool; isolating them would let the model route around the\n * breaker by alternating which tool it uses.\n */\n\nexport interface CircuitBreakerConfig {\n /**\n * Consecutive failures before trip. Default: 5.\n * A single success resets this counter to 0.\n */\n maxConsecutiveFailures?: number;\n /**\n * Slow-call threshold in ms. A call that runs longer than this is\n * counted as \"slow\". Default: 60_000 (1 minute).\n */\n slowCallThresholdMs?: number;\n /**\n * Max slow calls before trip (within the sliding window). Default: 3.\n */\n maxSlowCalls?: number;\n /**\n * Sliding window for rate-limit and slow-call counting, in ms.\n * Default: 60_000 (1 minute).\n */\n windowMs?: number;\n /**\n * Max calls within the sliding window. Default: 30.\n * Burst exceeding this trips the breaker immediately.\n */\n maxCallsPerWindow?: number;\n /**\n * Cooldown before auto-recovery attempt, in ms. Default: 30_000 (30s).\n * After this the breaker enters \"half-open\" state and allows one call\n * through to test whether the problem is resolved.\n */\n cooldownMs?: number;\n}\n\ninterface CallRecord {\n at: number;\n /** True if the call threw or returned an is_error result. */\n failed: boolean;\n /** True if elapsed time exceeded slowCallThresholdMs. */\n slow: boolean;\n}\n\ntype BreakerState = 'closed' | 'open' | 'half-open';\n\nconst DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;\nconst DEFAULT_SLOW_CALL_THRESHOLD_MS = 60_000;\nconst DEFAULT_MAX_SLOW_CALLS = 3;\nconst DEFAULT_WINDOW_MS = 60_000;\nconst DEFAULT_MAX_CALLS_PER_WINDOW = 30;\nconst DEFAULT_COOLDOWN_MS = 30_000;\n\nexport interface CircuitBreakerSnapshot {\n state: 'closed' | 'open' | 'half-open';\n consecutiveFailures: number;\n slowCallsInWindow: number;\n callsInWindow: number;\n windowMs: number;\n cooldownRemainingMs: number | null;\n lastFailureAt: number | null;\n lastSlowAt: number | null;\n}\n\nexport class CircuitBreaker {\n private readonly maxConsecutiveFailures: number;\n private readonly slowCallThresholdMs: number;\n private readonly maxSlowCalls: number;\n private readonly windowMs: number;\n private readonly maxCallsPerWindow: number;\n private readonly cooldownMs: number;\n\n private state: BreakerState = 'closed';\n private consecutiveFailures = 0;\n private window: CallRecord[] = [];\n private lastFailureAt: number | null = null;\n private lastSlowAt: number | null = null;\n /** Timestamp when the breaker was opened (for cooldown calculation). */\n private openedAt: number | null = null;\n /** Timestamp when the last call ran (for half-open gate). */\n private lastCallAt: number | null = null;\n\n constructor(config: CircuitBreakerConfig = {}) {\n this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;\n this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;\n this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;\n this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;\n this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;\n this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;\n }\n\n /**\n * Returns true if the circuit allows a new call to proceed.\n * When false, callers should abort the tool call and return a\n * circuit-breaker error instead of spawning a process.\n */\n get canProceed(): boolean {\n this._checkStateTransition();\n return this.state !== 'open';\n }\n\n /**\n * Snapshot of the current breaker state for observability (`/kill`).\n */\n snapshot(): CircuitBreakerSnapshot {\n this._checkStateTransition();\n const now = Date.now();\n let cooldownRemaining: number | null = null;\n if (this.openedAt !== null && this.state === 'open') {\n const elapsed = now - this.openedAt;\n cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);\n }\n return {\n state: this.state,\n consecutiveFailures: this.consecutiveFailures,\n slowCallsInWindow: this.window.filter((c) => c.slow).length,\n callsInWindow: this.window.length,\n windowMs: this.windowMs,\n cooldownRemainingMs: cooldownRemaining,\n lastFailureAt: this.lastFailureAt,\n lastSlowAt: this.lastSlowAt,\n };\n }\n\n /**\n * Call this BEFORE spawning a bash/exec process.\n * Returns true if the call is allowed; false if the breaker is open.\n * When false, callers MUST NOT spawn a process.\n */\n beforeCall(): boolean {\n this._checkStateTransition();\n if (this.state === 'open') return false;\n return true;\n }\n\n /**\n * Call this AFTER a bash/exec process finishes (success or failure).\n * `durationMs` is the wall-clock time the process ran.\n * `failed` is true when the process returned a non-zero exit code or\n * threw an exception before spawning.\n */\n afterCall(durationMs: number, failed: boolean): void {\n const now = Date.now();\n this.lastCallAt = now;\n\n if (this.state === 'half-open') {\n // First call through after cooldown — if it failed, go back to open.\n if (failed) {\n this._trip();\n return;\n }\n // Success in half-open → reset to closed.\n this._reset();\n return;\n }\n\n // Prune old records outside the sliding window.\n this._pruneWindow(now);\n\n const slow = durationMs >= this.slowCallThresholdMs;\n this.window.push({ at: now, failed, slow });\n\n if (failed) {\n this.consecutiveFailures++;\n this.lastFailureAt = now;\n if (this.consecutiveFailures >= this.maxConsecutiveFailures) {\n this._trip();\n }\n return;\n }\n\n // Success: reset consecutive failure counter.\n this.consecutiveFailures = 0;\n\n if (slow) {\n this.lastSlowAt = now;\n const slowCount = this.window.filter((c) => c.slow).length;\n if (slowCount >= this.maxSlowCalls) {\n this._trip();\n }\n }\n\n const callCount = this.window.length;\n if (callCount >= this.maxCallsPerWindow) {\n // Rate limit exceeded. This is a soft trip — we reset the window\n // and let the next call try immediately (the caller will still see\n // canProceed=false until the window drains naturally).\n this._trip();\n }\n }\n\n /** Force the breaker open. Used by /kill force and Ctrl+C. */\n forceOpen(): void {\n this._trip();\n }\n\n /** Force a reset to closed. Used by tests and /kill reset. */\n forceReset(): void {\n this._reset();\n }\n\n private _trip(): void {\n if (this.state === 'open') return; // already open\n this.state = 'open';\n this.openedAt = Date.now();\n }\n\n private _reset(): void {\n this.state = 'closed';\n this.consecutiveFailures = 0;\n this.window = [];\n this.openedAt = null;\n }\n\n /** Transition from open → half-open when cooldown elapses. */\n private _checkStateTransition(): void {\n if (this.state !== 'open' || this.openedAt === null) return;\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.cooldownMs) {\n this.state = 'half-open';\n this.openedAt = null;\n }\n }\n\n private _pruneWindow(now: number): void {\n const cutoff = now - this.windowMs;\n this.window = this.window.filter((c) => c.at >= cutoff);\n }\n}","/**\n * ProcessRegistry — global singleton that tracks all spawned child processes\n * from `bash` and `exec` tools. Enables:\n *\n * - Listing active processes (for TUI status bar)\n * - Killing individual processes or all processes (for Ctrl+C and /kill)\n * - Detecting runaway processes (hung, looping)\n * - Circuit breaker integration to prevent recursive/repeated failures\n *\n * Thread-safety: Node.js is single-threaded, but async callbacks can fire\n * in any order. All mutations go through synchronized Map methods.\n */\nimport type { ChildProcess } from 'node:child_process';\nimport * as os from 'node:os';\nimport { CircuitBreaker, type CircuitBreakerSnapshot, type CircuitBreakerConfig } from './circuit-breaker.js';\n\nexport { type CircuitBreakerSnapshot, type CircuitBreakerConfig } from './circuit-breaker.js';\n\nexport interface TrackedProcess {\n pid: number;\n name: string;\n command: string;\n startedAt: number;\n sessionId?: string;\n /** The raw ChildProcess handle. Never call .kill() directly on this —\n * use `kill()` below which handles process groups correctly on POSIX\n * and degrades gracefully on Windows. */\n child: ChildProcess;\n /** True once the process has been kill()ed but not yet exited.\n * We keep it in the registry until 'close' fires so callers can\n * distinguish \"still running\" from \"just exited\". */\n killed: boolean;\n}\n\ninterface KillOpts {\n /** SIGKILL instead of SIGTERM. Default: false (SIGTERM first). */\n force?: boolean;\n /** MS to wait between SIGTERM and SIGKILL on POSIX. Default: 2000. */\n graceMs?: number;\n}\n\nexport interface RegistryStats {\n activeCount: number;\n totalCount: number;\n breaker: CircuitBreakerSnapshot;\n}\n\nconst DEFAULT_GRACE_MS = 2000;\n\nclass ProcessRegistryImpl {\n private readonly processes = new Map<number, TrackedProcess>();\n private readonly breaker: CircuitBreaker;\n\n constructor(breakerConfig?: CircuitBreakerConfig) {\n this.breaker = new CircuitBreaker(breakerConfig);\n }\n\n register(info: Omit<TrackedProcess, 'killed'>): void {\n this.processes.set(info.pid, { ...info, killed: false });\n }\n\n /** Unregister a process by PID. Called on 'close' / 'exit' events. */\n unregister(pid: number): void {\n this.processes.delete(pid);\n }\n\n /** Get a single process by PID. */\n get(pid: number): TrackedProcess | undefined {\n return this.processes.get(pid);\n }\n\n /** Get all tracked processes. */\n list(): TrackedProcess[] {\n return Array.from(this.processes.values());\n }\n\n /** Get processes filtered by name (e.g. 'bash', 'exec'). */\n byName(name: string): TrackedProcess[] {\n return this.list().filter((p) => p.name === name);\n }\n\n /** Get processes filtered by session. */\n bySession(sessionId: string): TrackedProcess[] {\n return this.list().filter((p) => p.sessionId === sessionId);\n }\n\n /** Count of active (non-killed) processes. */\n get activeCount(): number {\n let n = 0;\n for (const p of this.processes.values()) {\n if (!p.killed) n++;\n }\n return n;\n }\n\n /**\n * Combined stats for observability — used by /ps and the TUI status bar.\n */\n stats(): RegistryStats {\n return {\n activeCount: this.activeCount,\n totalCount: this.processes.size,\n breaker: this.breaker.snapshot(),\n };\n }\n\n /**\n * Returns true if the circuit allows a new bash/exec call to proceed.\n * When false, callers MUST NOT spawn a process.\n */\n get canProceed(): boolean {\n return this.breaker.canProceed;\n }\n\n /**\n * Called before spawning a process. Returns true if allowed; false if\n * the circuit breaker is open.\n */\n beforeCall(): boolean {\n return this.breaker.beforeCall();\n }\n\n /**\n * Called after a process finishes. `durationMs` is wall-clock time;\n * `failed` is true for non-zero exit codes.\n */\n afterCall(durationMs: number, failed: boolean): void {\n this.breaker.afterCall(durationMs, failed);\n }\n\n /** Force-open the circuit breaker (Ctrl+C, /kill force). */\n forceBreakerOpen(): void {\n this.breaker.forceOpen();\n }\n\n /** Force-reset the circuit breaker to closed (/kill reset). */\n forceBreakerReset(): void {\n this.breaker.forceReset();\n }\n\n /** Kill a single process by PID.\n *\n * On POSIX: sends SIGTERM to the *process group* (-pid) so that\n * runaway grandchild processes (`sleep 9999 & disown`) are also killed.\n * After `graceMs` a SIGKILL is sent if the process hasn't exited.\n *\n * On Windows: `child.kill()` maps to TerminateProcess — process groups\n * are not meaningfully supported. A second `force=true` call sends\n * SIGKILL (which maps to TerminateProcess again — the distinction is\n * in the exit code, not the signal).\n *\n * Returns true if the process was found and kill was attempted.\n */\n kill(pid: number, opts: KillOpts = {}): boolean {\n const p = this.processes.get(pid);\n if (!p) return false;\n if (p.killed) return true; // already kill()ed, don't double-send\n\n const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;\n const isWin = os.platform() === 'win32';\n\n if (isWin) {\n // Windows: no process group semantics; just kill the process.\n try {\n p.child.kill(force ? 'SIGKILL' : 'SIGTERM');\n } catch {\n // Process may have already exited.\n }\n p.killed = true;\n return true;\n }\n\n // POSIX: kill the process group so grandchildren are cleaned up too.\n try {\n if (force) {\n try {\n process.kill(-pid, 'SIGKILL');\n } catch {\n p.child.kill('SIGKILL');\n }\n } else {\n try {\n process.kill(-pid, 'SIGTERM');\n } catch {\n p.child.kill('SIGTERM');\n }\n // Schedule SIGKILL as backup.\n const timer = setTimeout(() => {\n // Re-check: process may have exited on its own.\n if (this.processes.has(pid) && !p.child.killed) {\n try {\n process.kill(-pid, 'SIGKILL');\n } catch {\n try {\n p.child.kill('SIGKILL');\n } catch {\n /* already gone */\n }\n }\n }\n }, graceMs);\n timer.unref?.(); // Don't keep event loop alive.\n }\n } catch {\n // Process may have already exited.\n }\n p.killed = true;\n return true;\n }\n\n /**\n * Kill all tracked processes.\n * Returns the PIDs that were kill()ed.\n */\n killAll(opts: KillOpts = {}): number[] {\n const pids = Array.from(this.processes.keys());\n const killed: number[] = [];\n for (const pid of pids) {\n if (this.kill(pid, opts)) killed.push(pid);\n }\n return killed;\n }\n\n /**\n * Kill all processes for a specific session.\n * Returns the PIDs that were kill()ed.\n */\n killSession(sessionId: string, opts: KillOpts = {}): number[] {\n const pids = this.bySession(sessionId).map((p) => p.pid);\n const killed: number[] = [];\n for (const pid of pids) {\n if (this.kill(pid, opts)) killed.push(pid);\n }\n return killed;\n }\n}\n\n/** Module-level singleton. Initialized on first access. */\nlet _registry: ProcessRegistryImpl | undefined;\n\nexport function getProcessRegistry(): ProcessRegistryImpl {\n if (!_registry) {\n _registry = new ProcessRegistryImpl();\n }\n return _registry;\n}\n\n/** Reset for tests. */\nexport function _resetProcessRegistry(): void {\n _registry = undefined;\n}\n\n// ── Convenience re-exports ────────────────────────────────────────────────────\n\nexport type { KillOpts };"]}
|
package/dist/replace.js
CHANGED
|
@@ -6,12 +6,17 @@ import { compileGlob, detectNewlineStyle, normalizeToLf, toStyle, atomicWrite, u
|
|
|
6
6
|
// src/replace.ts
|
|
7
7
|
|
|
8
8
|
// src/_regex.ts
|
|
9
|
-
var MAX_PATTERN_LEN =
|
|
9
|
+
var MAX_PATTERN_LEN = 256;
|
|
10
10
|
var DANGEROUS_PATTERNS = [
|
|
11
|
-
/(\([^)]*[+*][^)]*\))[+*]/,
|
|
12
11
|
// (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier
|
|
13
|
-
/(\(
|
|
14
|
-
|
|
12
|
+
/(\([^)]*[+*][^)]*\))[+*]/,
|
|
13
|
+
/(\(\?:[^)]*[+*][^)]*\))[+*]/,
|
|
14
|
+
// Adjacent quantifiers: a++ a*+
|
|
15
|
+
/[+*]{2,}/,
|
|
16
|
+
// Quantifier on alternation with length 2+
|
|
17
|
+
/\([^|)]+\|[^)]+\)[+*][+*]/,
|
|
18
|
+
// Greedy quantifier inside lookahead/lookbehind — (?!.*a+)
|
|
19
|
+
/[\(\[][^)\]]*[+*][^)\]]*[\)\]][^)]*\?\??/
|
|
15
20
|
];
|
|
16
21
|
function compileUserRegex(pattern, flags) {
|
|
17
22
|
if (typeof pattern !== "string") {
|
package/dist/replace.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/_regex.ts","../src/_util.ts","../src/replace.ts"],"names":["lstat","path2","stat","spawn","resolve"],"mappings":";;;;;;;;AAuBA,IAAM,eAAA,GAAkB,GAAA;AAIxB,IAAM,kBAAA,GAA4C;AAAA,EAChD,0BAAA;AAAA;AAAA,EACA;AAAA;AACF,CAAA;AAYO,SAAS,gBAAA,CAAiB,SAAiB,KAAA,EAA4C;AAC5F,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,0BAAA,EAA2B;AAAA,EACzD;AACA,EAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,kBAAA,EAAmB;AAAA,EACjD;AACA,EAAA,IAAI,OAAA,CAAQ,SAAS,eAAA,EAAiB;AACpC,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,CAAA,gBAAA,EAAmB,eAAe,CAAA,WAAA,CAAA,EAAc;AAAA,EAC9E;AACA,EAAA,KAAA,MAAW,MAAM,kBAAA,EAAoB;AACnC,IAAA,IAAI,EAAA,CAAG,IAAA,CAAK,OAAO,CAAA,EAAG;AACpB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,MAAA,EACE;AAAA,OACJ;AAAA,IACF;AAAA,EACF;AACA,EAAA,IAAI;AACF,IAAA,OAAO,EAAE,IAAI,IAAA,EAAM,KAAA,EAAO,IAAI,MAAA,CAAO,OAAA,EAAS,KAAK,CAAA,EAAE;AAAA,EACvD,SAAS,GAAA,EAAK;AACZ,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,MAAA,EAAQ,G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A,CAAU,IAAA,CAAK,IAAI,KAAK,CAAC,SAAA,CAAU,IAAA,CAAK,IAAI,CAAA,EAAG;AACjE,UAAA,OAAA,CAAQ,KAAK,IAAI,CAAA;AAAA,QACnB;AACA,QAAA,MAAA,CAAO,SAAA,GAAY,CAAA;AACnB,QAAA,IAAI,SAAA,YAAqB,SAAA,GAAY,CAAA;AAAA,MACvC;AAAA,IACF;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,KAAK,IAAI,CAAA;AACf,EAAA,OAAO,OAAA;AACT","file":"replace.js","sourcesContent":["/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length — practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 512;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n /(\\([^)]*[+*][^)]*\\))[+*]/, // (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/, // same, with non-capturing group\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n","import * as path from 'node:path';\nimport type { Context } from '@wrongstack/core';\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n","import { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport {\n atomicWrite,\n buildChildEnv,\n compileGlob,\n detectNewlineStyle,\n normalizeToLf,\n toStyle,\n unifiedDiff,\n} from '@wrongstack/core';\nimport type { Context, Tool } from '@wrongstack/core';\nimport { compileUserRegex } from './_regex.js';\nimport { isBinaryBuffer, safeResolve } from './_util.js';\n\ninterface ReplaceInput {\n pattern: string;\n replacement: string;\n files: string | string[];\n glob?: string;\n replace_all?: boolean;\n dry_run?: boolean;\n}\n\ninterface ReplaceOutput {\n files_modified: number;\n total_replacements: number;\n results: { path: string; replacements: number; diff?: string }[];\n dry_run: boolean;\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage'];\n\nexport const replaceTool: Tool<ReplaceInput, ReplaceOutput> = {\n name: 'replace',\n category: 'Transform',\n description:\n 'Batch replace a pattern across multiple files matched by glob. Returns diff for each modified file.',\n usageHint:\n 'Use `glob` for broad patterns (e.g. \"**/*.ts\"). Set `dry_run: true` to preview without modifying. `files` can be a single path, comma-separated list, or glob pattern.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 30_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex pattern to match' },\n replacement: { type: 'string', description: 'Replacement string' },\n files: {\n type: 'string',\n description: 'File(s) to target: single path, comma-separated list, or glob pattern',\n },\n glob: { type: 'string', description: 'Additional glob filter (e.g. \"*.ts\")' },\n replace_all: {\n type: 'boolean',\n description: 'Replace all occurrences in each file (default: true)',\n },\n dry_run: { type: 'boolean', description: 'Preview changes without writing' },\n },\n required: ['pattern', 'replacement', 'files'],\n },\n async execute(input: ReplaceInput, ctx: Context) {\n if (!input?.pattern) throw new Error('replace: pattern is required');\n if (input.replacement === undefined) throw new Error('replace: replacement is required');\n if (!input?.files) throw new Error('replace: files is required');\n\n const replaceAll = input.replace_all ?? true;\n // Always compile with 'g' so matchAll() works — matchAll throws\n // TypeError on non-global regexes. The replaceAll flag controls\n // how many matches we act on, not whether the regex is global.\n const compiled = compileUserRegex(input.pattern, 'g');\n if (!compiled.ok) {\n throw new Error(`replace: ${compiled.reason}`);\n }\n const re = compiled.regex;\n const globRe = input.glob ? compileGlob(input.glob) : null;\n const dryRun = input.dry_run ?? false;\n\n const filesInput = Array.isArray(input.files) ? input.files.join(',') : input.files;\n const fileList = await resolveFiles(filesInput, ctx, globRe);\n\n const results: ReplaceOutput['results'] = [];\n let totalReplacements = 0;\n\n for (const absPath of fileList) {\n // Use lstat to detect symlinks. resolveFiles already applies\n // safeResolve, but a symlink with a target outside the project\n // root would still pass that string check — explicitly skip it\n // so we never read or write through a link.\n const lstat = await fs.lstat(absPath).catch((err) => {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n });\n if (!lstat || !lstat.isFile()) continue;\n if (lstat.isSymbolicLink()) continue;\n\n // Cross-check via realpath: if the resolved target lives outside the\n // project root (e.g. a bind mount or a parent-dir traversal we missed),\n // skip rather than rewrite through it.\n let realPath: string;\n try {\n realPath = await fs.realpath(absPath);\n } catch {\n continue;\n }\n const rel = path.relative(ctx.projectRoot, realPath);\n if (rel.startsWith('..') || path.isAbsolute(rel)) continue;\n\n // Now stat the real target so we use its mode for atomicWrite.\n const stat = await fs.stat(realPath).catch(() => null);\n if (!stat || !stat.isFile()) continue;\n\n let content: string;\n try {\n const buf = await fs.readFile(realPath);\n if (isBinaryBuffer(buf)) continue;\n content = buf.toString('utf8');\n } catch {\n continue;\n }\n\n const style = detectNewlineStyle(content);\n const contentLf = normalizeToLf(content);\n re.lastIndex = 0;\n const allMatches = [...contentLf.matchAll(re)];\n if (allMatches.length === 0) continue;\n\n // When replace_all is false, only act on the first match.\n const matches = replaceAll ? allMatches : allMatches.slice(0, 1);\n const count = matches.length;\n\n // Rebuild: splice the replacement into each match position from\n // right to left so earlier indices stay valid.\n let newContentLf = contentLf;\n for (let i = matches.length - 1; i >= 0; i--) {\n const m = matches[i]!;\n newContentLf =\n newContentLf.slice(0, m.index) +\n input.replacement +\n newContentLf.slice(m.index! + m[0].length);\n }\n re.lastIndex = 0;\n totalReplacements += count;\n\n if (!dryRun) {\n const newContent = toStyle(newContentLf, style);\n // Write to the real path (already validated inside project root)\n // so atomicWrite's temp-and-rename can't be redirected through a\n // freshly-planted symlink at absPath.\n await atomicWrite(realPath, newContent, { mode: stat.mode & 0o777 });\n }\n\n const diff =\n dryRun || matches.length > 0\n ? unifiedDiff(content, toStyle(newContentLf, style), {\n fromFile: absPath,\n toFile: absPath,\n })\n : undefined;\n\n results.push({\n path: absPath,\n replacements: matches.length,\n diff,\n });\n }\n\n return {\n files_modified: results.length,\n total_replacements: totalReplacements,\n results,\n dry_run: dryRun,\n };\n },\n};\n\nasync function resolveFiles(\n filesInput: string,\n ctx: Context,\n extraGlob?: RegExp | null,\n): Promise<string[]> {\n const base = ctx.cwd;\n const normalized = filesInput.trim();\n\n if (normalized.startsWith('**/') || normalized.startsWith('*') || normalized.includes('**')) {\n return await globFiles(normalized, base, extraGlob);\n }\n\n const parts = normalized\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n const resolved: string[] = [];\n\n for (const p of parts) {\n const absPath = safeResolve(p, ctx);\n const stat = await fs.stat(absPath).catch(() => null);\n if (stat?.isFile()) {\n resolved.push(absPath);\n }\n }\n\n return resolved;\n}\n\nasync function globFiles(\n pattern: string,\n base: string,\n extraGlob?: RegExp | null,\n): Promise<string[]> {\n const { spawn } = await import('node:child_process');\n const results: string[] = [];\n\n const rgAvailable = await checkRg();\n if (rgAvailable) {\n try {\n const { promise } = spawnRgFind(pattern, base);\n return await promise;\n } catch {\n // fall through\n }\n }\n\n return await globNative(pattern, base, extraGlob);\n}\n\nfunction checkRg(): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n const p = spawn('rg', ['--version'], { env: buildChildEnv(), stdio: 'ignore' });\n p.on('error', () => resolve(false));\n p.on('close', (code) => resolve(code === 0));\n } catch {\n resolve(false);\n }\n });\n}\n\nfunction spawnRgFind(pattern: string, base: string): { promise: Promise<string[]> } {\n const args = ['--files', '--glob', pattern, base];\n const child = spawn('rg', args, { env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] });\n let buf = '';\n child.stdout?.on('data', (chunk: Buffer) => {\n buf += chunk.toString();\n });\n return {\n promise: new Promise((resolve, reject) => {\n child.on('error', reject);\n child.on('close', () => {\n resolve(buf.split('\\n').filter(Boolean));\n });\n }),\n };\n}\n\nasync function globNative(\n pattern: string,\n base: string,\n extraGlob?: RegExp | null,\n): Promise<string[]> {\n const results: string[] = [];\n const globRe = compileGlob(pattern);\n\n const walk = async (dir: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (DEFAULT_IGNORE.includes(e.name)) continue;\n const full = path.join(dir, e.name);\n // Dirent.isSymbolicLink() uses readdir's d_type, which may not detect\n // directory symlinks on Windows (d_type = DT_UNKNOWN). Defensive stat\n // call: skip any entry whose lstat shows a symlink — file or directory.\n try {\n const stat = await fs.lstat(full);\n if (stat.isSymbolicLink()) continue;\n } catch {\n // lstat fails for very unusual entries (e.g. broken symlinks to deleted\n // files on NFS); skip safely rather than surfacing an error.\n continue;\n }\n if (e.isDirectory()) {\n await walk(full);\n } else if (e.isFile()) {\n const name = e.name;\n if (globRe.test(name) || globRe.test(full)) {\n if (extraGlob && !extraGlob.test(name) && !extraGlob.test(full)) continue;\n results.push(full);\n }\n globRe.lastIndex = 0;\n if (extraGlob) extraGlob.lastIndex = 0;\n }\n }\n };\n\n await walk(base);\n return results;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/_regex.ts","../src/_util.ts","../src/replace.ts"],"names":["lstat","path2","stat","spawn","resolve"],"mappings":";;;;;;;;AAuBA,IAAM,eAAA,GAAkB,GAAA;AAIxB,IAAM,kBAAA,G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AAA,IAAI,SAAA,YAAqB,SAAA,GAAY,CAAA;AAAA,MACvC;AAAA,IACF;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,KAAK,IAAI,CAAA;AACf,EAAA,OAAO,OAAA;AACT","file":"replace.js","sourcesContent":["/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length — practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind — (?!.*a+)\n /[\\(\\[][^)\\]]*[+*][^)\\]]*[\\)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n","import * as path from 'node:path';\nimport type { Context } from '@wrongstack/core';\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n","import { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport {\n atomicWrite,\n buildChildEnv,\n compileGlob,\n detectNewlineStyle,\n normalizeToLf,\n toStyle,\n unifiedDiff,\n} from '@wrongstack/core';\nimport type { Context, Tool } from '@wrongstack/core';\nimport { compileUserRegex } from './_regex.js';\nimport { isBinaryBuffer, safeResolve } from './_util.js';\n\ninterface ReplaceInput {\n pattern: string;\n replacement: string;\n files: string | string[];\n glob?: string;\n replace_all?: boolean;\n dry_run?: boolean;\n}\n\ninterface ReplaceOutput {\n files_modified: number;\n total_replacements: number;\n results: { path: string; replacements: number; diff?: string }[];\n dry_run: boolean;\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage'];\n\nexport const replaceTool: Tool<ReplaceInput, ReplaceOutput> = {\n name: 'replace',\n category: 'Transform',\n description:\n 'Batch replace a pattern across multiple files matched by glob. Returns diff for each modified file.',\n usageHint:\n 'Use `glob` for broad patterns (e.g. \"**/*.ts\"). Set `dry_run: true` to preview without modifying. `files` can be a single path, comma-separated list, or glob pattern.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 30_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Regex pattern to match' },\n replacement: { type: 'string', description: 'Replacement string' },\n files: {\n type: 'string',\n description: 'File(s) to target: single path, comma-separated list, or glob pattern',\n },\n glob: { type: 'string', description: 'Additional glob filter (e.g. \"*.ts\")' },\n replace_all: {\n type: 'boolean',\n description: 'Replace all occurrences in each file (default: true)',\n },\n dry_run: { type: 'boolean', description: 'Preview changes without writing' },\n },\n required: ['pattern', 'replacement', 'files'],\n },\n async execute(input: ReplaceInput, ctx: Context) {\n if (!input?.pattern) throw new Error('replace: pattern is required');\n if (input.replacement === undefined) throw new Error('replace: replacement is required');\n if (!input?.files) throw new Error('replace: files is required');\n\n const replaceAll = input.replace_all ?? true;\n // Always compile with 'g' so matchAll() works — matchAll throws\n // TypeError on non-global regexes. The replaceAll flag controls\n // how many matches we act on, not whether the regex is global.\n const compiled = compileUserRegex(input.pattern, 'g');\n if (!compiled.ok) {\n throw new Error(`replace: ${compiled.reason}`);\n }\n const re = compiled.regex;\n const globRe = input.glob ? compileGlob(input.glob) : null;\n const dryRun = input.dry_run ?? false;\n\n const filesInput = Array.isArray(input.files) ? input.files.join(',') : input.files;\n const fileList = await resolveFiles(filesInput, ctx, globRe);\n\n const results: ReplaceOutput['results'] = [];\n let totalReplacements = 0;\n\n for (const absPath of fileList) {\n // Use lstat to detect symlinks. resolveFiles already applies\n // safeResolve, but a symlink with a target outside the project\n // root would still pass that string check — explicitly skip it\n // so we never read or write through a link.\n const lstat = await fs.lstat(absPath).catch((err) => {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n });\n if (!lstat || !lstat.isFile()) continue;\n if (lstat.isSymbolicLink()) continue;\n\n // Cross-check via realpath: if the resolved target lives outside the\n // project root (e.g. a bind mount or a parent-dir traversal we missed),\n // skip rather than rewrite through it.\n let realPath: string;\n try {\n realPath = await fs.realpath(absPath);\n } catch {\n continue;\n }\n const rel = path.relative(ctx.projectRoot, realPath);\n if (rel.startsWith('..') || path.isAbsolute(rel)) continue;\n\n // Now stat the real target so we use its mode for atomicWrite.\n const stat = await fs.stat(realPath).catch(() => null);\n if (!stat || !stat.isFile()) continue;\n\n let content: string;\n try {\n const buf = await fs.readFile(realPath);\n if (isBinaryBuffer(buf)) continue;\n content = buf.toString('utf8');\n } catch {\n continue;\n }\n\n const style = detectNewlineStyle(content);\n const contentLf = normalizeToLf(content);\n re.lastIndex = 0;\n const allMatches = [...contentLf.matchAll(re)];\n if (allMatches.length === 0) continue;\n\n // When replace_all is false, only act on the first match.\n const matches = replaceAll ? allMatches : allMatches.slice(0, 1);\n const count = matches.length;\n\n // Rebuild: splice the replacement into each match position from\n // right to left so earlier indices stay valid.\n let newContentLf = contentLf;\n for (let i = matches.length - 1; i >= 0; i--) {\n const m = matches[i]!;\n newContentLf =\n newContentLf.slice(0, m.index) +\n input.replacement +\n newContentLf.slice(m.index! + m[0].length);\n }\n re.lastIndex = 0;\n totalReplacements += count;\n\n if (!dryRun) {\n const newContent = toStyle(newContentLf, style);\n // Write to the real path (already validated inside project root)\n // so atomicWrite's temp-and-rename can't be redirected through a\n // freshly-planted symlink at absPath.\n await atomicWrite(realPath, newContent, { mode: stat.mode & 0o777 });\n }\n\n const diff =\n dryRun || matches.length > 0\n ? unifiedDiff(content, toStyle(newContentLf, style), {\n fromFile: absPath,\n toFile: absPath,\n })\n : undefined;\n\n results.push({\n path: absPath,\n replacements: matches.length,\n diff,\n });\n }\n\n return {\n files_modified: results.length,\n total_replacements: totalReplacements,\n results,\n dry_run: dryRun,\n };\n },\n};\n\nasync function resolveFiles(\n filesInput: string,\n ctx: Context,\n extraGlob?: RegExp | null,\n): Promise<string[]> {\n const base = ctx.cwd;\n const normalized = filesInput.trim();\n\n if (normalized.startsWith('**/') || normalized.startsWith('*') || normalized.includes('**')) {\n return await globFiles(normalized, base, extraGlob);\n }\n\n const parts = normalized\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n const resolved: string[] = [];\n\n for (const p of parts) {\n const absPath = safeResolve(p, ctx);\n const stat = await fs.stat(absPath).catch(() => null);\n if (stat?.isFile()) {\n resolved.push(absPath);\n }\n }\n\n return resolved;\n}\n\nasync function globFiles(\n pattern: string,\n base: string,\n extraGlob?: RegExp | null,\n): Promise<string[]> {\n const { spawn } = await import('node:child_process');\n const results: string[] = [];\n\n const rgAvailable = await checkRg();\n if (rgAvailable) {\n try {\n const { promise } = spawnRgFind(pattern, base);\n return await promise;\n } catch {\n // fall through\n }\n }\n\n return await globNative(pattern, base, extraGlob);\n}\n\nfunction checkRg(): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n const p = spawn('rg', ['--version'], { env: buildChildEnv(), stdio: 'ignore' });\n p.on('error', () => resolve(false));\n p.on('close', (code) => resolve(code === 0));\n } catch {\n resolve(false);\n }\n });\n}\n\nfunction spawnRgFind(pattern: string, base: string): { promise: Promise<string[]> } {\n const args = ['--files', '--glob', pattern, base];\n const child = spawn('rg', args, { env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] });\n let buf = '';\n child.stdout?.on('data', (chunk: Buffer) => {\n buf += chunk.toString();\n });\n return {\n promise: new Promise((resolve, reject) => {\n child.on('error', reject);\n child.on('close', () => {\n resolve(buf.split('\\n').filter(Boolean));\n });\n }),\n };\n}\n\nasync function globNative(\n pattern: string,\n base: string,\n extraGlob?: RegExp | null,\n): Promise<string[]> {\n const results: string[] = [];\n const globRe = compileGlob(pattern);\n\n const walk = async (dir: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (DEFAULT_IGNORE.includes(e.name)) continue;\n const full = path.join(dir, e.name);\n // Dirent.isSymbolicLink() uses readdir's d_type, which may not detect\n // directory symlinks on Windows (d_type = DT_UNKNOWN). Defensive stat\n // call: skip any entry whose lstat shows a symlink — file or directory.\n try {\n const stat = await fs.lstat(full);\n if (stat.isSymbolicLink()) continue;\n } catch {\n // lstat fails for very unusual entries (e.g. broken symlinks to deleted\n // files on NFS); skip safely rather than surfacing an error.\n continue;\n }\n if (e.isDirectory()) {\n await walk(full);\n } else if (e.isFile()) {\n const name = e.name;\n if (globRe.test(name) || globRe.test(full)) {\n if (extraGlob && !extraGlob.test(name) && !extraGlob.test(full)) continue;\n results.push(full);\n }\n globRe.lastIndex = 0;\n if (extraGlob) extraGlob.lastIndex = 0;\n }\n }\n };\n\n await walk(base);\n return results;\n}\n"]}
|
package/dist/scaffold.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as fs from 'fs/promises';
|
|
2
2
|
import * as path from 'path';
|
|
3
|
+
import { atomicWrite } from '@wrongstack/core';
|
|
3
4
|
|
|
4
5
|
// src/scaffold.ts
|
|
5
6
|
function resolvePath(input, ctx) {
|
|
@@ -175,7 +176,7 @@ async function handleBuiltIn(name, templateFiles, cwd, ctx, dryRun, vars) {
|
|
|
175
176
|
const fullPath = target;
|
|
176
177
|
if (!dryRun) {
|
|
177
178
|
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
|
178
|
-
await
|
|
179
|
+
await atomicWrite(fullPath, substituteVars(content, name, vars));
|
|
179
180
|
}
|
|
180
181
|
files.push(resolvedPath);
|
|
181
182
|
filesCreated++;
|