@agenttrail/cli 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +252 -2
- package/dist/chunk-F6FLYISV.js +148 -0
- package/dist/cli/index.cjs +149 -0
- package/dist/cli/index.js +2 -0
- package/dist/cursor/capture-hook.mjs +2 -0
- package/dist/cursor/flush.mjs +6 -0
- package/dist/cursor/pep-hook.mjs +4690 -0
- package/dist/index.cjs +148 -0
- package/dist/index.d.cts +630 -0
- package/dist/index.d.ts +630 -0
- package/dist/index.js +1 -0
- package/package.json +48 -3
- package/plugin/.claude-plugin/marketplace.json +22 -0
- package/plugin/.claude-plugin/plugin.json +11 -0
- package/plugin/README.md +32 -0
- package/plugin/hooks/hooks.json +16 -0
- package/plugin/scripts/pep-hook.mjs +4690 -0
|
@@ -0,0 +1,4690 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
19
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
20
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
21
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
22
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
23
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
24
|
+
mod
|
|
25
|
+
));
|
|
26
|
+
|
|
27
|
+
// ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/constants.js
|
|
28
|
+
var require_constants = __commonJS({
|
|
29
|
+
"../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/constants.js"(exports, module) {
|
|
30
|
+
"use strict";
|
|
31
|
+
var WIN_SLASH = "\\\\/";
|
|
32
|
+
var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
|
|
33
|
+
var DEFAULT_MAX_EXTGLOB_RECURSION = 0;
|
|
34
|
+
var DOT_LITERAL = "\\.";
|
|
35
|
+
var PLUS_LITERAL = "\\+";
|
|
36
|
+
var QMARK_LITERAL = "\\?";
|
|
37
|
+
var SLASH_LITERAL = "\\/";
|
|
38
|
+
var ONE_CHAR = "(?=.)";
|
|
39
|
+
var QMARK = "[^/]";
|
|
40
|
+
var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
|
|
41
|
+
var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
|
|
42
|
+
var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
|
|
43
|
+
var NO_DOT = `(?!${DOT_LITERAL})`;
|
|
44
|
+
var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
|
|
45
|
+
var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
|
|
46
|
+
var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
|
|
47
|
+
var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
|
|
48
|
+
var STAR = `${QMARK}*?`;
|
|
49
|
+
var SEP = "/";
|
|
50
|
+
var POSIX_CHARS = {
|
|
51
|
+
DOT_LITERAL,
|
|
52
|
+
PLUS_LITERAL,
|
|
53
|
+
QMARK_LITERAL,
|
|
54
|
+
SLASH_LITERAL,
|
|
55
|
+
ONE_CHAR,
|
|
56
|
+
QMARK,
|
|
57
|
+
END_ANCHOR,
|
|
58
|
+
DOTS_SLASH,
|
|
59
|
+
NO_DOT,
|
|
60
|
+
NO_DOTS,
|
|
61
|
+
NO_DOT_SLASH,
|
|
62
|
+
NO_DOTS_SLASH,
|
|
63
|
+
QMARK_NO_DOT,
|
|
64
|
+
STAR,
|
|
65
|
+
START_ANCHOR,
|
|
66
|
+
SEP
|
|
67
|
+
};
|
|
68
|
+
var WINDOWS_CHARS = {
|
|
69
|
+
...POSIX_CHARS,
|
|
70
|
+
SLASH_LITERAL: `[${WIN_SLASH}]`,
|
|
71
|
+
QMARK: WIN_NO_SLASH,
|
|
72
|
+
STAR: `${WIN_NO_SLASH}*?`,
|
|
73
|
+
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
|
|
74
|
+
NO_DOT: `(?!${DOT_LITERAL})`,
|
|
75
|
+
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
|
|
76
|
+
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
|
|
77
|
+
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
|
|
78
|
+
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
|
|
79
|
+
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
|
|
80
|
+
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
|
|
81
|
+
SEP: "\\"
|
|
82
|
+
};
|
|
83
|
+
var POSIX_REGEX_SOURCE = {
|
|
84
|
+
__proto__: null,
|
|
85
|
+
alnum: "a-zA-Z0-9",
|
|
86
|
+
alpha: "a-zA-Z",
|
|
87
|
+
ascii: "\\x00-\\x7F",
|
|
88
|
+
blank: " \\t",
|
|
89
|
+
cntrl: "\\x00-\\x1F\\x7F",
|
|
90
|
+
digit: "0-9",
|
|
91
|
+
graph: "\\x21-\\x7E",
|
|
92
|
+
lower: "a-z",
|
|
93
|
+
print: "\\x20-\\x7E ",
|
|
94
|
+
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
|
|
95
|
+
space: " \\t\\r\\n\\v\\f",
|
|
96
|
+
upper: "A-Z",
|
|
97
|
+
word: "A-Za-z0-9_",
|
|
98
|
+
xdigit: "A-Fa-f0-9"
|
|
99
|
+
};
|
|
100
|
+
module.exports = {
|
|
101
|
+
DEFAULT_MAX_EXTGLOB_RECURSION,
|
|
102
|
+
MAX_LENGTH: 1024 * 64,
|
|
103
|
+
POSIX_REGEX_SOURCE,
|
|
104
|
+
// regular expressions
|
|
105
|
+
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
|
|
106
|
+
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
|
|
107
|
+
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
|
|
108
|
+
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
|
|
109
|
+
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
|
|
110
|
+
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
|
|
111
|
+
// Replace globs with equivalent patterns to reduce parsing time.
|
|
112
|
+
REPLACEMENTS: {
|
|
113
|
+
__proto__: null,
|
|
114
|
+
"***": "*",
|
|
115
|
+
"**/**": "**",
|
|
116
|
+
"**/**/**": "**"
|
|
117
|
+
},
|
|
118
|
+
// Digits
|
|
119
|
+
CHAR_0: 48,
|
|
120
|
+
/* 0 */
|
|
121
|
+
CHAR_9: 57,
|
|
122
|
+
/* 9 */
|
|
123
|
+
// Alphabet chars.
|
|
124
|
+
CHAR_UPPERCASE_A: 65,
|
|
125
|
+
/* A */
|
|
126
|
+
CHAR_LOWERCASE_A: 97,
|
|
127
|
+
/* a */
|
|
128
|
+
CHAR_UPPERCASE_Z: 90,
|
|
129
|
+
/* Z */
|
|
130
|
+
CHAR_LOWERCASE_Z: 122,
|
|
131
|
+
/* z */
|
|
132
|
+
CHAR_LEFT_PARENTHESES: 40,
|
|
133
|
+
/* ( */
|
|
134
|
+
CHAR_RIGHT_PARENTHESES: 41,
|
|
135
|
+
/* ) */
|
|
136
|
+
CHAR_ASTERISK: 42,
|
|
137
|
+
/* * */
|
|
138
|
+
// Non-alphabetic chars.
|
|
139
|
+
CHAR_AMPERSAND: 38,
|
|
140
|
+
/* & */
|
|
141
|
+
CHAR_AT: 64,
|
|
142
|
+
/* @ */
|
|
143
|
+
CHAR_BACKWARD_SLASH: 92,
|
|
144
|
+
/* \ */
|
|
145
|
+
CHAR_CARRIAGE_RETURN: 13,
|
|
146
|
+
/* \r */
|
|
147
|
+
CHAR_CIRCUMFLEX_ACCENT: 94,
|
|
148
|
+
/* ^ */
|
|
149
|
+
CHAR_COLON: 58,
|
|
150
|
+
/* : */
|
|
151
|
+
CHAR_COMMA: 44,
|
|
152
|
+
/* , */
|
|
153
|
+
CHAR_DOT: 46,
|
|
154
|
+
/* . */
|
|
155
|
+
CHAR_DOUBLE_QUOTE: 34,
|
|
156
|
+
/* " */
|
|
157
|
+
CHAR_EQUAL: 61,
|
|
158
|
+
/* = */
|
|
159
|
+
CHAR_EXCLAMATION_MARK: 33,
|
|
160
|
+
/* ! */
|
|
161
|
+
CHAR_FORM_FEED: 12,
|
|
162
|
+
/* \f */
|
|
163
|
+
CHAR_FORWARD_SLASH: 47,
|
|
164
|
+
/* / */
|
|
165
|
+
CHAR_GRAVE_ACCENT: 96,
|
|
166
|
+
/* ` */
|
|
167
|
+
CHAR_HASH: 35,
|
|
168
|
+
/* # */
|
|
169
|
+
CHAR_HYPHEN_MINUS: 45,
|
|
170
|
+
/* - */
|
|
171
|
+
CHAR_LEFT_ANGLE_BRACKET: 60,
|
|
172
|
+
/* < */
|
|
173
|
+
CHAR_LEFT_CURLY_BRACE: 123,
|
|
174
|
+
/* { */
|
|
175
|
+
CHAR_LEFT_SQUARE_BRACKET: 91,
|
|
176
|
+
/* [ */
|
|
177
|
+
CHAR_LINE_FEED: 10,
|
|
178
|
+
/* \n */
|
|
179
|
+
CHAR_NO_BREAK_SPACE: 160,
|
|
180
|
+
/* \u00A0 */
|
|
181
|
+
CHAR_PERCENT: 37,
|
|
182
|
+
/* % */
|
|
183
|
+
CHAR_PLUS: 43,
|
|
184
|
+
/* + */
|
|
185
|
+
CHAR_QUESTION_MARK: 63,
|
|
186
|
+
/* ? */
|
|
187
|
+
CHAR_RIGHT_ANGLE_BRACKET: 62,
|
|
188
|
+
/* > */
|
|
189
|
+
CHAR_RIGHT_CURLY_BRACE: 125,
|
|
190
|
+
/* } */
|
|
191
|
+
CHAR_RIGHT_SQUARE_BRACKET: 93,
|
|
192
|
+
/* ] */
|
|
193
|
+
CHAR_SEMICOLON: 59,
|
|
194
|
+
/* ; */
|
|
195
|
+
CHAR_SINGLE_QUOTE: 39,
|
|
196
|
+
/* ' */
|
|
197
|
+
CHAR_SPACE: 32,
|
|
198
|
+
/* */
|
|
199
|
+
CHAR_TAB: 9,
|
|
200
|
+
/* \t */
|
|
201
|
+
CHAR_UNDERSCORE: 95,
|
|
202
|
+
/* _ */
|
|
203
|
+
CHAR_VERTICAL_LINE: 124,
|
|
204
|
+
/* | */
|
|
205
|
+
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
|
|
206
|
+
/* \uFEFF */
|
|
207
|
+
/**
|
|
208
|
+
* Create EXTGLOB_CHARS
|
|
209
|
+
*/
|
|
210
|
+
extglobChars(chars) {
|
|
211
|
+
return {
|
|
212
|
+
"!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
|
|
213
|
+
"?": { type: "qmark", open: "(?:", close: ")?" },
|
|
214
|
+
"+": { type: "plus", open: "(?:", close: ")+" },
|
|
215
|
+
"*": { type: "star", open: "(?:", close: ")*" },
|
|
216
|
+
"@": { type: "at", open: "(?:", close: ")" }
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
/**
|
|
220
|
+
* Create GLOB_CHARS
|
|
221
|
+
*/
|
|
222
|
+
globChars(win32) {
|
|
223
|
+
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
// ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/utils.js
|
|
230
|
+
var require_utils = __commonJS({
|
|
231
|
+
"../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/utils.js"(exports) {
|
|
232
|
+
"use strict";
|
|
233
|
+
var {
|
|
234
|
+
REGEX_BACKSLASH,
|
|
235
|
+
REGEX_REMOVE_BACKSLASH,
|
|
236
|
+
REGEX_SPECIAL_CHARS,
|
|
237
|
+
REGEX_SPECIAL_CHARS_GLOBAL
|
|
238
|
+
} = require_constants();
|
|
239
|
+
exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
|
|
240
|
+
exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
|
|
241
|
+
exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
|
|
242
|
+
exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
|
|
243
|
+
exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
|
|
244
|
+
exports.isWindows = () => {
|
|
245
|
+
if (typeof navigator !== "undefined" && navigator.platform) {
|
|
246
|
+
const platform = navigator.platform.toLowerCase();
|
|
247
|
+
return platform === "win32" || platform === "windows";
|
|
248
|
+
}
|
|
249
|
+
if (typeof process !== "undefined" && process.platform) {
|
|
250
|
+
return process.platform === "win32";
|
|
251
|
+
}
|
|
252
|
+
return false;
|
|
253
|
+
};
|
|
254
|
+
exports.removeBackslashes = (str) => {
|
|
255
|
+
return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
|
|
256
|
+
return match === "\\" ? "" : match;
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
exports.escapeLast = (input, char, lastIdx) => {
|
|
260
|
+
const idx = input.lastIndexOf(char, lastIdx);
|
|
261
|
+
if (idx === -1) return input;
|
|
262
|
+
if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
|
|
263
|
+
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
|
|
264
|
+
};
|
|
265
|
+
exports.removePrefix = (input, state = {}) => {
|
|
266
|
+
let output = input;
|
|
267
|
+
if (output.startsWith("./")) {
|
|
268
|
+
output = output.slice(2);
|
|
269
|
+
state.prefix = "./";
|
|
270
|
+
}
|
|
271
|
+
return output;
|
|
272
|
+
};
|
|
273
|
+
exports.wrapOutput = (input, state = {}, options = {}) => {
|
|
274
|
+
const prepend = options.contains ? "" : "^";
|
|
275
|
+
const append = options.contains ? "" : "$";
|
|
276
|
+
let output = `${prepend}(?:${input})${append}`;
|
|
277
|
+
if (state.negated === true) {
|
|
278
|
+
output = `(?:^(?!${output}).*$)`;
|
|
279
|
+
}
|
|
280
|
+
return output;
|
|
281
|
+
};
|
|
282
|
+
exports.basename = (path, { windows } = {}) => {
|
|
283
|
+
const segs = path.split(windows ? /[\\/]/ : "/");
|
|
284
|
+
const last = segs[segs.length - 1];
|
|
285
|
+
if (last === "") {
|
|
286
|
+
return segs[segs.length - 2];
|
|
287
|
+
}
|
|
288
|
+
return last;
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/scan.js
|
|
294
|
+
var require_scan = __commonJS({
|
|
295
|
+
"../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/scan.js"(exports, module) {
|
|
296
|
+
"use strict";
|
|
297
|
+
var utils = require_utils();
|
|
298
|
+
var {
|
|
299
|
+
CHAR_ASTERISK,
|
|
300
|
+
/* * */
|
|
301
|
+
CHAR_AT,
|
|
302
|
+
/* @ */
|
|
303
|
+
CHAR_BACKWARD_SLASH,
|
|
304
|
+
/* \ */
|
|
305
|
+
CHAR_COMMA,
|
|
306
|
+
/* , */
|
|
307
|
+
CHAR_DOT,
|
|
308
|
+
/* . */
|
|
309
|
+
CHAR_EXCLAMATION_MARK,
|
|
310
|
+
/* ! */
|
|
311
|
+
CHAR_FORWARD_SLASH,
|
|
312
|
+
/* / */
|
|
313
|
+
CHAR_LEFT_CURLY_BRACE,
|
|
314
|
+
/* { */
|
|
315
|
+
CHAR_LEFT_PARENTHESES,
|
|
316
|
+
/* ( */
|
|
317
|
+
CHAR_LEFT_SQUARE_BRACKET,
|
|
318
|
+
/* [ */
|
|
319
|
+
CHAR_PLUS,
|
|
320
|
+
/* + */
|
|
321
|
+
CHAR_QUESTION_MARK,
|
|
322
|
+
/* ? */
|
|
323
|
+
CHAR_RIGHT_CURLY_BRACE,
|
|
324
|
+
/* } */
|
|
325
|
+
CHAR_RIGHT_PARENTHESES,
|
|
326
|
+
/* ) */
|
|
327
|
+
CHAR_RIGHT_SQUARE_BRACKET
|
|
328
|
+
/* ] */
|
|
329
|
+
} = require_constants();
|
|
330
|
+
var isPathSeparator = (code) => {
|
|
331
|
+
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
|
|
332
|
+
};
|
|
333
|
+
var depth = (token) => {
|
|
334
|
+
if (token.isPrefix !== true) {
|
|
335
|
+
token.depth = token.isGlobstar ? Infinity : 1;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
var scan = (input, options) => {
|
|
339
|
+
const opts = options || {};
|
|
340
|
+
const length = input.length - 1;
|
|
341
|
+
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
|
|
342
|
+
const slashes = [];
|
|
343
|
+
const tokens = [];
|
|
344
|
+
const parts = [];
|
|
345
|
+
let str = input;
|
|
346
|
+
let index = -1;
|
|
347
|
+
let start = 0;
|
|
348
|
+
let lastIndex = 0;
|
|
349
|
+
let isBrace = false;
|
|
350
|
+
let isBracket = false;
|
|
351
|
+
let isGlob = false;
|
|
352
|
+
let isExtglob = false;
|
|
353
|
+
let isGlobstar = false;
|
|
354
|
+
let braceEscaped = false;
|
|
355
|
+
let backslashes = false;
|
|
356
|
+
let negated = false;
|
|
357
|
+
let negatedExtglob = false;
|
|
358
|
+
let finished = false;
|
|
359
|
+
let braces = 0;
|
|
360
|
+
let prev;
|
|
361
|
+
let code;
|
|
362
|
+
let token = { value: "", depth: 0, isGlob: false };
|
|
363
|
+
const eos = () => index >= length;
|
|
364
|
+
const peek = () => str.charCodeAt(index + 1);
|
|
365
|
+
const advance = () => {
|
|
366
|
+
prev = code;
|
|
367
|
+
return str.charCodeAt(++index);
|
|
368
|
+
};
|
|
369
|
+
while (index < length) {
|
|
370
|
+
code = advance();
|
|
371
|
+
let next;
|
|
372
|
+
if (code === CHAR_BACKWARD_SLASH) {
|
|
373
|
+
backslashes = token.backslashes = true;
|
|
374
|
+
code = advance();
|
|
375
|
+
if (code === CHAR_LEFT_CURLY_BRACE) {
|
|
376
|
+
braceEscaped = true;
|
|
377
|
+
}
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
|
|
381
|
+
braces++;
|
|
382
|
+
while (eos() !== true && (code = advance())) {
|
|
383
|
+
if (code === CHAR_BACKWARD_SLASH) {
|
|
384
|
+
backslashes = token.backslashes = true;
|
|
385
|
+
advance();
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (code === CHAR_LEFT_CURLY_BRACE) {
|
|
389
|
+
braces++;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
|
|
393
|
+
isBrace = token.isBrace = true;
|
|
394
|
+
isGlob = token.isGlob = true;
|
|
395
|
+
finished = true;
|
|
396
|
+
if (scanToEnd === true) {
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
if (braceEscaped !== true && code === CHAR_COMMA) {
|
|
402
|
+
isBrace = token.isBrace = true;
|
|
403
|
+
isGlob = token.isGlob = true;
|
|
404
|
+
finished = true;
|
|
405
|
+
if (scanToEnd === true) {
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
if (code === CHAR_RIGHT_CURLY_BRACE) {
|
|
411
|
+
braces--;
|
|
412
|
+
if (braces === 0) {
|
|
413
|
+
braceEscaped = false;
|
|
414
|
+
isBrace = token.isBrace = true;
|
|
415
|
+
finished = true;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (scanToEnd === true) {
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
if (code === CHAR_FORWARD_SLASH) {
|
|
426
|
+
slashes.push(index);
|
|
427
|
+
tokens.push(token);
|
|
428
|
+
token = { value: "", depth: 0, isGlob: false };
|
|
429
|
+
if (finished === true) continue;
|
|
430
|
+
if (prev === CHAR_DOT && index === start + 1) {
|
|
431
|
+
start += 2;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
lastIndex = index + 1;
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
if (opts.noext !== true) {
|
|
438
|
+
const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
|
|
439
|
+
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
|
|
440
|
+
isGlob = token.isGlob = true;
|
|
441
|
+
isExtglob = token.isExtglob = true;
|
|
442
|
+
finished = true;
|
|
443
|
+
if (code === CHAR_EXCLAMATION_MARK && index === start) {
|
|
444
|
+
negatedExtglob = true;
|
|
445
|
+
}
|
|
446
|
+
if (scanToEnd === true) {
|
|
447
|
+
while (eos() !== true && (code = advance())) {
|
|
448
|
+
if (code === CHAR_BACKWARD_SLASH) {
|
|
449
|
+
backslashes = token.backslashes = true;
|
|
450
|
+
code = advance();
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (code === CHAR_RIGHT_PARENTHESES) {
|
|
454
|
+
isGlob = token.isGlob = true;
|
|
455
|
+
finished = true;
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (code === CHAR_ASTERISK) {
|
|
465
|
+
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
|
|
466
|
+
isGlob = token.isGlob = true;
|
|
467
|
+
finished = true;
|
|
468
|
+
if (scanToEnd === true) {
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
break;
|
|
472
|
+
}
|
|
473
|
+
if (code === CHAR_QUESTION_MARK) {
|
|
474
|
+
isGlob = token.isGlob = true;
|
|
475
|
+
finished = true;
|
|
476
|
+
if (scanToEnd === true) {
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
break;
|
|
480
|
+
}
|
|
481
|
+
if (code === CHAR_LEFT_SQUARE_BRACKET) {
|
|
482
|
+
while (eos() !== true && (next = advance())) {
|
|
483
|
+
if (next === CHAR_BACKWARD_SLASH) {
|
|
484
|
+
backslashes = token.backslashes = true;
|
|
485
|
+
advance();
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
|
|
489
|
+
isBracket = token.isBracket = true;
|
|
490
|
+
isGlob = token.isGlob = true;
|
|
491
|
+
finished = true;
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
if (scanToEnd === true) {
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
|
|
501
|
+
negated = token.negated = true;
|
|
502
|
+
start++;
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
|
|
506
|
+
isGlob = token.isGlob = true;
|
|
507
|
+
if (scanToEnd === true) {
|
|
508
|
+
while (eos() !== true && (code = advance())) {
|
|
509
|
+
if (code === CHAR_LEFT_PARENTHESES) {
|
|
510
|
+
backslashes = token.backslashes = true;
|
|
511
|
+
code = advance();
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (code === CHAR_RIGHT_PARENTHESES) {
|
|
515
|
+
finished = true;
|
|
516
|
+
break;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
if (isGlob === true) {
|
|
524
|
+
finished = true;
|
|
525
|
+
if (scanToEnd === true) {
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
break;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (opts.noext === true) {
|
|
532
|
+
isExtglob = false;
|
|
533
|
+
isGlob = false;
|
|
534
|
+
}
|
|
535
|
+
let base = str;
|
|
536
|
+
let prefix = "";
|
|
537
|
+
let glob = "";
|
|
538
|
+
if (start > 0) {
|
|
539
|
+
prefix = str.slice(0, start);
|
|
540
|
+
str = str.slice(start);
|
|
541
|
+
lastIndex -= start;
|
|
542
|
+
}
|
|
543
|
+
if (base && isGlob === true && lastIndex > 0) {
|
|
544
|
+
base = str.slice(0, lastIndex);
|
|
545
|
+
glob = str.slice(lastIndex);
|
|
546
|
+
} else if (isGlob === true) {
|
|
547
|
+
base = "";
|
|
548
|
+
glob = str;
|
|
549
|
+
} else {
|
|
550
|
+
base = str;
|
|
551
|
+
}
|
|
552
|
+
if (base && base !== "" && base !== "/" && base !== str) {
|
|
553
|
+
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
|
|
554
|
+
base = base.slice(0, -1);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (opts.unescape === true) {
|
|
558
|
+
if (glob) glob = utils.removeBackslashes(glob);
|
|
559
|
+
if (base && backslashes === true) {
|
|
560
|
+
base = utils.removeBackslashes(base);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
const state = {
|
|
564
|
+
prefix,
|
|
565
|
+
input,
|
|
566
|
+
start,
|
|
567
|
+
base,
|
|
568
|
+
glob,
|
|
569
|
+
isBrace,
|
|
570
|
+
isBracket,
|
|
571
|
+
isGlob,
|
|
572
|
+
isExtglob,
|
|
573
|
+
isGlobstar,
|
|
574
|
+
negated,
|
|
575
|
+
negatedExtglob
|
|
576
|
+
};
|
|
577
|
+
if (opts.tokens === true) {
|
|
578
|
+
state.maxDepth = 0;
|
|
579
|
+
if (!isPathSeparator(code)) {
|
|
580
|
+
tokens.push(token);
|
|
581
|
+
}
|
|
582
|
+
state.tokens = tokens;
|
|
583
|
+
}
|
|
584
|
+
if (opts.parts === true || opts.tokens === true) {
|
|
585
|
+
let prevIndex;
|
|
586
|
+
for (let idx = 0; idx < slashes.length; idx++) {
|
|
587
|
+
const n = prevIndex ? prevIndex + 1 : start;
|
|
588
|
+
const i = slashes[idx];
|
|
589
|
+
const value = input.slice(n, i);
|
|
590
|
+
if (opts.tokens) {
|
|
591
|
+
if (idx === 0 && start !== 0) {
|
|
592
|
+
tokens[idx].isPrefix = true;
|
|
593
|
+
tokens[idx].value = prefix;
|
|
594
|
+
} else {
|
|
595
|
+
tokens[idx].value = value;
|
|
596
|
+
}
|
|
597
|
+
depth(tokens[idx]);
|
|
598
|
+
state.maxDepth += tokens[idx].depth;
|
|
599
|
+
}
|
|
600
|
+
if (idx !== 0 || value !== "") {
|
|
601
|
+
parts.push(value);
|
|
602
|
+
}
|
|
603
|
+
prevIndex = i;
|
|
604
|
+
}
|
|
605
|
+
if (prevIndex && prevIndex + 1 < input.length) {
|
|
606
|
+
const value = input.slice(prevIndex + 1);
|
|
607
|
+
parts.push(value);
|
|
608
|
+
if (opts.tokens) {
|
|
609
|
+
tokens[tokens.length - 1].value = value;
|
|
610
|
+
depth(tokens[tokens.length - 1]);
|
|
611
|
+
state.maxDepth += tokens[tokens.length - 1].depth;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
state.slashes = slashes;
|
|
615
|
+
state.parts = parts;
|
|
616
|
+
}
|
|
617
|
+
return state;
|
|
618
|
+
};
|
|
619
|
+
module.exports = scan;
|
|
620
|
+
}
|
|
621
|
+
});
|
|
622
|
+
|
|
623
|
+
// ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/parse.js
|
|
624
|
+
var require_parse = __commonJS({
|
|
625
|
+
"../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/parse.js"(exports, module) {
|
|
626
|
+
"use strict";
|
|
627
|
+
var constants = require_constants();
|
|
628
|
+
var utils = require_utils();
|
|
629
|
+
var {
|
|
630
|
+
MAX_LENGTH,
|
|
631
|
+
POSIX_REGEX_SOURCE,
|
|
632
|
+
REGEX_NON_SPECIAL_CHARS,
|
|
633
|
+
REGEX_SPECIAL_CHARS_BACKREF,
|
|
634
|
+
REPLACEMENTS
|
|
635
|
+
} = constants;
|
|
636
|
+
var expandRange = (args, options) => {
|
|
637
|
+
if (typeof options.expandRange === "function") {
|
|
638
|
+
return options.expandRange(...args, options);
|
|
639
|
+
}
|
|
640
|
+
args.sort();
|
|
641
|
+
const value = `[${args.join("-")}]`;
|
|
642
|
+
try {
|
|
643
|
+
new RegExp(value);
|
|
644
|
+
} catch (ex) {
|
|
645
|
+
return args.map((v) => utils.escapeRegex(v)).join("..");
|
|
646
|
+
}
|
|
647
|
+
return value;
|
|
648
|
+
};
|
|
649
|
+
var syntaxError = (type, char) => {
|
|
650
|
+
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
|
|
651
|
+
};
|
|
652
|
+
var splitTopLevel = (input) => {
|
|
653
|
+
const parts = [];
|
|
654
|
+
let bracket = 0;
|
|
655
|
+
let paren = 0;
|
|
656
|
+
let quote = 0;
|
|
657
|
+
let value = "";
|
|
658
|
+
let escaped = false;
|
|
659
|
+
for (const ch of input) {
|
|
660
|
+
if (escaped === true) {
|
|
661
|
+
value += ch;
|
|
662
|
+
escaped = false;
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
if (ch === "\\") {
|
|
666
|
+
value += ch;
|
|
667
|
+
escaped = true;
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
if (ch === '"') {
|
|
671
|
+
quote = quote === 1 ? 0 : 1;
|
|
672
|
+
value += ch;
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
if (quote === 0) {
|
|
676
|
+
if (ch === "[") {
|
|
677
|
+
bracket++;
|
|
678
|
+
} else if (ch === "]" && bracket > 0) {
|
|
679
|
+
bracket--;
|
|
680
|
+
} else if (bracket === 0) {
|
|
681
|
+
if (ch === "(") {
|
|
682
|
+
paren++;
|
|
683
|
+
} else if (ch === ")" && paren > 0) {
|
|
684
|
+
paren--;
|
|
685
|
+
} else if (ch === "|" && paren === 0) {
|
|
686
|
+
parts.push(value);
|
|
687
|
+
value = "";
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
value += ch;
|
|
693
|
+
}
|
|
694
|
+
parts.push(value);
|
|
695
|
+
return parts;
|
|
696
|
+
};
|
|
697
|
+
var isPlainBranch = (branch) => {
|
|
698
|
+
let escaped = false;
|
|
699
|
+
for (const ch of branch) {
|
|
700
|
+
if (escaped === true) {
|
|
701
|
+
escaped = false;
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
if (ch === "\\") {
|
|
705
|
+
escaped = true;
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
if (/[?*+@!()[\]{}]/.test(ch)) {
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return true;
|
|
713
|
+
};
|
|
714
|
+
var normalizeSimpleBranch = (branch) => {
|
|
715
|
+
let value = branch.trim();
|
|
716
|
+
let changed = true;
|
|
717
|
+
while (changed === true) {
|
|
718
|
+
changed = false;
|
|
719
|
+
if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
|
|
720
|
+
value = value.slice(2, -1);
|
|
721
|
+
changed = true;
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
if (!isPlainBranch(value)) {
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
return value.replace(/\\(.)/g, "$1");
|
|
728
|
+
};
|
|
729
|
+
var hasRepeatedCharPrefixOverlap = (branches) => {
|
|
730
|
+
const values = branches.map(normalizeSimpleBranch).filter(Boolean);
|
|
731
|
+
for (let i = 0; i < values.length; i++) {
|
|
732
|
+
for (let j = i + 1; j < values.length; j++) {
|
|
733
|
+
const a = values[i];
|
|
734
|
+
const b = values[j];
|
|
735
|
+
const char = a[0];
|
|
736
|
+
if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
if (a === b || a.startsWith(b) || b.startsWith(a)) {
|
|
740
|
+
return true;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return false;
|
|
745
|
+
};
|
|
746
|
+
var parseRepeatedExtglob = (pattern, requireEnd = true) => {
|
|
747
|
+
if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") {
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
let bracket = 0;
|
|
751
|
+
let paren = 0;
|
|
752
|
+
let quote = 0;
|
|
753
|
+
let escaped = false;
|
|
754
|
+
for (let i = 1; i < pattern.length; i++) {
|
|
755
|
+
const ch = pattern[i];
|
|
756
|
+
if (escaped === true) {
|
|
757
|
+
escaped = false;
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
if (ch === "\\") {
|
|
761
|
+
escaped = true;
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
if (ch === '"') {
|
|
765
|
+
quote = quote === 1 ? 0 : 1;
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
if (quote === 1) {
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
if (ch === "[") {
|
|
772
|
+
bracket++;
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if (ch === "]" && bracket > 0) {
|
|
776
|
+
bracket--;
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
if (bracket > 0) {
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
if (ch === "(") {
|
|
783
|
+
paren++;
|
|
784
|
+
continue;
|
|
785
|
+
}
|
|
786
|
+
if (ch === ")") {
|
|
787
|
+
paren--;
|
|
788
|
+
if (paren === 0) {
|
|
789
|
+
if (requireEnd === true && i !== pattern.length - 1) {
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
return {
|
|
793
|
+
type: pattern[0],
|
|
794
|
+
body: pattern.slice(2, i),
|
|
795
|
+
end: i
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
var getStarExtglobSequenceOutput = (pattern) => {
|
|
802
|
+
let index = 0;
|
|
803
|
+
const chars = [];
|
|
804
|
+
while (index < pattern.length) {
|
|
805
|
+
const match = parseRepeatedExtglob(pattern.slice(index), false);
|
|
806
|
+
if (!match || match.type !== "*") {
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
const branches = splitTopLevel(match.body).map((branch2) => branch2.trim());
|
|
810
|
+
if (branches.length !== 1) {
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
const branch = normalizeSimpleBranch(branches[0]);
|
|
814
|
+
if (!branch || branch.length !== 1) {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
chars.push(branch);
|
|
818
|
+
index += match.end + 1;
|
|
819
|
+
}
|
|
820
|
+
if (chars.length < 1) {
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`;
|
|
824
|
+
return `${source}*`;
|
|
825
|
+
};
|
|
826
|
+
var repeatedExtglobRecursion = (pattern) => {
|
|
827
|
+
let depth = 0;
|
|
828
|
+
let value = pattern.trim();
|
|
829
|
+
let match = parseRepeatedExtglob(value);
|
|
830
|
+
while (match) {
|
|
831
|
+
depth++;
|
|
832
|
+
value = match.body.trim();
|
|
833
|
+
match = parseRepeatedExtglob(value);
|
|
834
|
+
}
|
|
835
|
+
return depth;
|
|
836
|
+
};
|
|
837
|
+
var analyzeRepeatedExtglob = (body, options) => {
|
|
838
|
+
if (options.maxExtglobRecursion === false) {
|
|
839
|
+
return { risky: false };
|
|
840
|
+
}
|
|
841
|
+
const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
|
|
842
|
+
const branches = splitTopLevel(body).map((branch) => branch.trim());
|
|
843
|
+
if (branches.length > 1) {
|
|
844
|
+
if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) {
|
|
845
|
+
return { risky: true };
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
for (const branch of branches) {
|
|
849
|
+
const safeOutput = getStarExtglobSequenceOutput(branch);
|
|
850
|
+
if (safeOutput) {
|
|
851
|
+
return { risky: true, safeOutput };
|
|
852
|
+
}
|
|
853
|
+
if (repeatedExtglobRecursion(branch) > max) {
|
|
854
|
+
return { risky: true };
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
return { risky: false };
|
|
858
|
+
};
|
|
859
|
+
var parse = (input, options) => {
|
|
860
|
+
if (typeof input !== "string") {
|
|
861
|
+
throw new TypeError("Expected a string");
|
|
862
|
+
}
|
|
863
|
+
input = REPLACEMENTS[input] || input;
|
|
864
|
+
const opts = { ...options };
|
|
865
|
+
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
|
|
866
|
+
let len = input.length;
|
|
867
|
+
if (len > max) {
|
|
868
|
+
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
|
|
869
|
+
}
|
|
870
|
+
const bos = { type: "bos", value: "", output: opts.prepend || "" };
|
|
871
|
+
const tokens = [bos];
|
|
872
|
+
const capture = opts.capture ? "" : "?:";
|
|
873
|
+
const PLATFORM_CHARS = constants.globChars(opts.windows);
|
|
874
|
+
const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
|
|
875
|
+
const {
|
|
876
|
+
DOT_LITERAL,
|
|
877
|
+
PLUS_LITERAL,
|
|
878
|
+
SLASH_LITERAL,
|
|
879
|
+
ONE_CHAR,
|
|
880
|
+
DOTS_SLASH,
|
|
881
|
+
NO_DOT,
|
|
882
|
+
NO_DOT_SLASH,
|
|
883
|
+
NO_DOTS_SLASH,
|
|
884
|
+
QMARK,
|
|
885
|
+
QMARK_NO_DOT,
|
|
886
|
+
STAR,
|
|
887
|
+
START_ANCHOR
|
|
888
|
+
} = PLATFORM_CHARS;
|
|
889
|
+
const globstar = (opts2) => {
|
|
890
|
+
return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
|
|
891
|
+
};
|
|
892
|
+
const nodot = opts.dot ? "" : NO_DOT;
|
|
893
|
+
const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
|
|
894
|
+
let star = opts.bash === true ? globstar(opts) : STAR;
|
|
895
|
+
if (opts.capture) {
|
|
896
|
+
star = `(${star})`;
|
|
897
|
+
}
|
|
898
|
+
if (typeof opts.noext === "boolean") {
|
|
899
|
+
opts.noextglob = opts.noext;
|
|
900
|
+
}
|
|
901
|
+
const state = {
|
|
902
|
+
input,
|
|
903
|
+
index: -1,
|
|
904
|
+
start: 0,
|
|
905
|
+
dot: opts.dot === true,
|
|
906
|
+
consumed: "",
|
|
907
|
+
output: "",
|
|
908
|
+
prefix: "",
|
|
909
|
+
backtrack: false,
|
|
910
|
+
negated: false,
|
|
911
|
+
brackets: 0,
|
|
912
|
+
braces: 0,
|
|
913
|
+
parens: 0,
|
|
914
|
+
quotes: 0,
|
|
915
|
+
globstar: false,
|
|
916
|
+
tokens
|
|
917
|
+
};
|
|
918
|
+
input = utils.removePrefix(input, state);
|
|
919
|
+
len = input.length;
|
|
920
|
+
const extglobs = [];
|
|
921
|
+
const braces = [];
|
|
922
|
+
const stack = [];
|
|
923
|
+
let prev = bos;
|
|
924
|
+
let value;
|
|
925
|
+
const eos = () => state.index === len - 1;
|
|
926
|
+
const peek = state.peek = (n = 1) => input[state.index + n];
|
|
927
|
+
const advance = state.advance = () => input[++state.index] || "";
|
|
928
|
+
const remaining = () => input.slice(state.index + 1);
|
|
929
|
+
const consume = (value2 = "", num = 0) => {
|
|
930
|
+
state.consumed += value2;
|
|
931
|
+
state.index += num;
|
|
932
|
+
};
|
|
933
|
+
const append = (token) => {
|
|
934
|
+
state.output += token.output != null ? token.output : token.value;
|
|
935
|
+
consume(token.value);
|
|
936
|
+
};
|
|
937
|
+
const negate = () => {
|
|
938
|
+
let count = 1;
|
|
939
|
+
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
|
|
940
|
+
advance();
|
|
941
|
+
state.start++;
|
|
942
|
+
count++;
|
|
943
|
+
}
|
|
944
|
+
if (count % 2 === 0) {
|
|
945
|
+
return false;
|
|
946
|
+
}
|
|
947
|
+
state.negated = true;
|
|
948
|
+
state.start++;
|
|
949
|
+
return true;
|
|
950
|
+
};
|
|
951
|
+
const increment = (type) => {
|
|
952
|
+
state[type]++;
|
|
953
|
+
stack.push(type);
|
|
954
|
+
};
|
|
955
|
+
const decrement = (type) => {
|
|
956
|
+
state[type]--;
|
|
957
|
+
stack.pop();
|
|
958
|
+
};
|
|
959
|
+
const push = (tok) => {
|
|
960
|
+
if (prev.type === "globstar") {
|
|
961
|
+
const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
|
|
962
|
+
const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
|
|
963
|
+
if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
|
|
964
|
+
state.output = state.output.slice(0, -prev.output.length);
|
|
965
|
+
prev.type = "star";
|
|
966
|
+
prev.value = "*";
|
|
967
|
+
prev.output = star;
|
|
968
|
+
state.output += prev.output;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
if (extglobs.length && tok.type !== "paren") {
|
|
972
|
+
extglobs[extglobs.length - 1].inner += tok.value;
|
|
973
|
+
}
|
|
974
|
+
if (tok.value || tok.output) append(tok);
|
|
975
|
+
if (prev && prev.type === "text" && tok.type === "text") {
|
|
976
|
+
prev.output = (prev.output || prev.value) + tok.value;
|
|
977
|
+
prev.value += tok.value;
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
tok.prev = prev;
|
|
981
|
+
tokens.push(tok);
|
|
982
|
+
prev = tok;
|
|
983
|
+
};
|
|
984
|
+
const extglobOpen = (type, value2) => {
|
|
985
|
+
const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
|
|
986
|
+
token.prev = prev;
|
|
987
|
+
token.parens = state.parens;
|
|
988
|
+
token.output = state.output;
|
|
989
|
+
token.startIndex = state.index;
|
|
990
|
+
token.tokensIndex = tokens.length;
|
|
991
|
+
const output = (opts.capture ? "(" : "") + token.open;
|
|
992
|
+
increment("parens");
|
|
993
|
+
push({ type, value: value2, output: state.output ? "" : ONE_CHAR });
|
|
994
|
+
push({ type: "paren", extglob: true, value: advance(), output });
|
|
995
|
+
extglobs.push(token);
|
|
996
|
+
};
|
|
997
|
+
const extglobClose = (token) => {
|
|
998
|
+
const literal = input.slice(token.startIndex, state.index + 1);
|
|
999
|
+
const body = input.slice(token.startIndex + 2, state.index);
|
|
1000
|
+
const analysis = analyzeRepeatedExtglob(body, opts);
|
|
1001
|
+
if ((token.type === "plus" || token.type === "star") && analysis.risky) {
|
|
1002
|
+
const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0;
|
|
1003
|
+
const open = tokens[token.tokensIndex];
|
|
1004
|
+
open.type = "text";
|
|
1005
|
+
open.value = literal;
|
|
1006
|
+
open.output = safeOutput || utils.escapeRegex(literal);
|
|
1007
|
+
for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
|
|
1008
|
+
tokens[i].value = "";
|
|
1009
|
+
tokens[i].output = "";
|
|
1010
|
+
delete tokens[i].suffix;
|
|
1011
|
+
}
|
|
1012
|
+
state.output = token.output + open.output;
|
|
1013
|
+
state.backtrack = true;
|
|
1014
|
+
push({ type: "paren", extglob: true, value, output: "" });
|
|
1015
|
+
decrement("parens");
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
let output = token.close + (opts.capture ? ")" : "");
|
|
1019
|
+
let rest;
|
|
1020
|
+
if (token.type === "negate") {
|
|
1021
|
+
let extglobStar = star;
|
|
1022
|
+
if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
|
|
1023
|
+
extglobStar = globstar(opts);
|
|
1024
|
+
}
|
|
1025
|
+
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
|
|
1026
|
+
output = token.close = `)$))${extglobStar}`;
|
|
1027
|
+
}
|
|
1028
|
+
if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
|
|
1029
|
+
const expression = parse(rest, { ...options, fastpaths: false }).output;
|
|
1030
|
+
output = token.close = `)${expression})${extglobStar})`;
|
|
1031
|
+
}
|
|
1032
|
+
if (token.prev.type === "bos") {
|
|
1033
|
+
state.negatedExtglob = true;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
push({ type: "paren", extglob: true, value, output });
|
|
1037
|
+
decrement("parens");
|
|
1038
|
+
};
|
|
1039
|
+
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
|
|
1040
|
+
let backslashes = false;
|
|
1041
|
+
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
|
|
1042
|
+
if (first === "\\") {
|
|
1043
|
+
backslashes = true;
|
|
1044
|
+
return m;
|
|
1045
|
+
}
|
|
1046
|
+
if (first === "?") {
|
|
1047
|
+
if (esc) {
|
|
1048
|
+
return esc + first + (rest ? QMARK.repeat(rest.length) : "");
|
|
1049
|
+
}
|
|
1050
|
+
if (index === 0) {
|
|
1051
|
+
return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
|
|
1052
|
+
}
|
|
1053
|
+
return QMARK.repeat(chars.length);
|
|
1054
|
+
}
|
|
1055
|
+
if (first === ".") {
|
|
1056
|
+
return DOT_LITERAL.repeat(chars.length);
|
|
1057
|
+
}
|
|
1058
|
+
if (first === "*") {
|
|
1059
|
+
if (esc) {
|
|
1060
|
+
return esc + first + (rest ? star : "");
|
|
1061
|
+
}
|
|
1062
|
+
return star;
|
|
1063
|
+
}
|
|
1064
|
+
return esc ? m : `\\${m}`;
|
|
1065
|
+
});
|
|
1066
|
+
if (backslashes === true) {
|
|
1067
|
+
if (opts.unescape === true) {
|
|
1068
|
+
output = output.replace(/\\/g, "");
|
|
1069
|
+
} else {
|
|
1070
|
+
output = output.replace(/\\+/g, (m) => {
|
|
1071
|
+
return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
if (output === input && opts.contains === true) {
|
|
1076
|
+
state.output = input;
|
|
1077
|
+
return state;
|
|
1078
|
+
}
|
|
1079
|
+
state.output = utils.wrapOutput(output, state, options);
|
|
1080
|
+
return state;
|
|
1081
|
+
}
|
|
1082
|
+
while (!eos()) {
|
|
1083
|
+
value = advance();
|
|
1084
|
+
if (value === "\0") {
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
if (value === "\\") {
|
|
1088
|
+
const next = peek();
|
|
1089
|
+
if (next === "/" && opts.bash !== true) {
|
|
1090
|
+
continue;
|
|
1091
|
+
}
|
|
1092
|
+
if (next === "." || next === ";") {
|
|
1093
|
+
continue;
|
|
1094
|
+
}
|
|
1095
|
+
if (!next) {
|
|
1096
|
+
value += "\\";
|
|
1097
|
+
push({ type: "text", value });
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
const match = /^\\+/.exec(remaining());
|
|
1101
|
+
let slashes = 0;
|
|
1102
|
+
if (match && match[0].length > 2) {
|
|
1103
|
+
slashes = match[0].length;
|
|
1104
|
+
state.index += slashes;
|
|
1105
|
+
if (slashes % 2 !== 0) {
|
|
1106
|
+
value += "\\";
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
if (opts.unescape === true) {
|
|
1110
|
+
value = advance();
|
|
1111
|
+
} else {
|
|
1112
|
+
value += advance();
|
|
1113
|
+
}
|
|
1114
|
+
if (state.brackets === 0) {
|
|
1115
|
+
push({ type: "text", value });
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
|
|
1120
|
+
if (opts.posix !== false && value === ":") {
|
|
1121
|
+
const inner = prev.value.slice(1);
|
|
1122
|
+
if (inner.includes("[")) {
|
|
1123
|
+
prev.posix = true;
|
|
1124
|
+
if (inner.includes(":")) {
|
|
1125
|
+
const idx = prev.value.lastIndexOf("[");
|
|
1126
|
+
const pre = prev.value.slice(0, idx);
|
|
1127
|
+
const rest2 = prev.value.slice(idx + 2);
|
|
1128
|
+
const posix = POSIX_REGEX_SOURCE[rest2];
|
|
1129
|
+
if (posix) {
|
|
1130
|
+
prev.value = pre + posix;
|
|
1131
|
+
state.backtrack = true;
|
|
1132
|
+
advance();
|
|
1133
|
+
if (!bos.output && tokens.indexOf(prev) === 1) {
|
|
1134
|
+
bos.output = ONE_CHAR;
|
|
1135
|
+
}
|
|
1136
|
+
continue;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
|
|
1142
|
+
value = `\\${value}`;
|
|
1143
|
+
}
|
|
1144
|
+
if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
|
|
1145
|
+
value = `\\${value}`;
|
|
1146
|
+
}
|
|
1147
|
+
if (opts.posix === true && value === "!" && prev.value === "[") {
|
|
1148
|
+
value = "^";
|
|
1149
|
+
}
|
|
1150
|
+
prev.value += value;
|
|
1151
|
+
append({ value });
|
|
1152
|
+
continue;
|
|
1153
|
+
}
|
|
1154
|
+
if (state.quotes === 1 && value !== '"') {
|
|
1155
|
+
value = utils.escapeRegex(value);
|
|
1156
|
+
prev.value += value;
|
|
1157
|
+
append({ value });
|
|
1158
|
+
continue;
|
|
1159
|
+
}
|
|
1160
|
+
if (value === '"') {
|
|
1161
|
+
state.quotes = state.quotes === 1 ? 0 : 1;
|
|
1162
|
+
if (opts.keepQuotes === true) {
|
|
1163
|
+
push({ type: "text", value });
|
|
1164
|
+
}
|
|
1165
|
+
continue;
|
|
1166
|
+
}
|
|
1167
|
+
if (value === "(") {
|
|
1168
|
+
increment("parens");
|
|
1169
|
+
push({ type: "paren", value });
|
|
1170
|
+
continue;
|
|
1171
|
+
}
|
|
1172
|
+
if (value === ")") {
|
|
1173
|
+
if (state.parens === 0 && opts.strictBrackets === true) {
|
|
1174
|
+
throw new SyntaxError(syntaxError("opening", "("));
|
|
1175
|
+
}
|
|
1176
|
+
const extglob = extglobs[extglobs.length - 1];
|
|
1177
|
+
if (extglob && state.parens === extglob.parens + 1) {
|
|
1178
|
+
extglobClose(extglobs.pop());
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
push({ type: "paren", value, output: state.parens ? ")" : "\\)" });
|
|
1182
|
+
decrement("parens");
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
if (value === "[") {
|
|
1186
|
+
if (opts.nobracket === true || !remaining().includes("]")) {
|
|
1187
|
+
if (opts.nobracket !== true && opts.strictBrackets === true) {
|
|
1188
|
+
throw new SyntaxError(syntaxError("closing", "]"));
|
|
1189
|
+
}
|
|
1190
|
+
value = `\\${value}`;
|
|
1191
|
+
} else {
|
|
1192
|
+
increment("brackets");
|
|
1193
|
+
}
|
|
1194
|
+
push({ type: "bracket", value });
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
if (value === "]") {
|
|
1198
|
+
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
|
|
1199
|
+
push({ type: "text", value, output: `\\${value}` });
|
|
1200
|
+
continue;
|
|
1201
|
+
}
|
|
1202
|
+
if (state.brackets === 0) {
|
|
1203
|
+
if (opts.strictBrackets === true) {
|
|
1204
|
+
throw new SyntaxError(syntaxError("opening", "["));
|
|
1205
|
+
}
|
|
1206
|
+
push({ type: "text", value, output: `\\${value}` });
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
decrement("brackets");
|
|
1210
|
+
const prevValue = prev.value.slice(1);
|
|
1211
|
+
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
|
|
1212
|
+
value = `/${value}`;
|
|
1213
|
+
}
|
|
1214
|
+
prev.value += value;
|
|
1215
|
+
append({ value });
|
|
1216
|
+
if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
const escaped = utils.escapeRegex(prev.value);
|
|
1220
|
+
state.output = state.output.slice(0, -prev.value.length);
|
|
1221
|
+
if (opts.literalBrackets === true) {
|
|
1222
|
+
state.output += escaped;
|
|
1223
|
+
prev.value = escaped;
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
prev.value = `(${capture}${escaped}|${prev.value})`;
|
|
1227
|
+
state.output += prev.value;
|
|
1228
|
+
continue;
|
|
1229
|
+
}
|
|
1230
|
+
if (value === "{" && opts.nobrace !== true) {
|
|
1231
|
+
increment("braces");
|
|
1232
|
+
const open = {
|
|
1233
|
+
type: "brace",
|
|
1234
|
+
value,
|
|
1235
|
+
output: "(",
|
|
1236
|
+
outputIndex: state.output.length,
|
|
1237
|
+
tokensIndex: state.tokens.length
|
|
1238
|
+
};
|
|
1239
|
+
braces.push(open);
|
|
1240
|
+
push(open);
|
|
1241
|
+
continue;
|
|
1242
|
+
}
|
|
1243
|
+
if (value === "}") {
|
|
1244
|
+
const brace = braces[braces.length - 1];
|
|
1245
|
+
if (opts.nobrace === true || !brace) {
|
|
1246
|
+
push({ type: "text", value, output: value });
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
let output = ")";
|
|
1250
|
+
if (brace.dots === true) {
|
|
1251
|
+
const arr = tokens.slice();
|
|
1252
|
+
const range = [];
|
|
1253
|
+
for (let i = arr.length - 1; i >= 0; i--) {
|
|
1254
|
+
tokens.pop();
|
|
1255
|
+
if (arr[i].type === "brace") {
|
|
1256
|
+
break;
|
|
1257
|
+
}
|
|
1258
|
+
if (arr[i].type !== "dots") {
|
|
1259
|
+
range.unshift(arr[i].value);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
output = expandRange(range, opts);
|
|
1263
|
+
state.backtrack = true;
|
|
1264
|
+
}
|
|
1265
|
+
if (brace.comma !== true && brace.dots !== true) {
|
|
1266
|
+
const out = state.output.slice(0, brace.outputIndex);
|
|
1267
|
+
const toks = state.tokens.slice(brace.tokensIndex);
|
|
1268
|
+
brace.value = brace.output = "\\{";
|
|
1269
|
+
value = output = "\\}";
|
|
1270
|
+
state.output = out;
|
|
1271
|
+
for (const t of toks) {
|
|
1272
|
+
state.output += t.output || t.value;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
push({ type: "brace", value, output });
|
|
1276
|
+
decrement("braces");
|
|
1277
|
+
braces.pop();
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
if (value === "|") {
|
|
1281
|
+
if (extglobs.length > 0) {
|
|
1282
|
+
extglobs[extglobs.length - 1].conditions++;
|
|
1283
|
+
}
|
|
1284
|
+
push({ type: "text", value });
|
|
1285
|
+
continue;
|
|
1286
|
+
}
|
|
1287
|
+
if (value === ",") {
|
|
1288
|
+
let output = value;
|
|
1289
|
+
const brace = braces[braces.length - 1];
|
|
1290
|
+
if (brace && stack[stack.length - 1] === "braces") {
|
|
1291
|
+
brace.comma = true;
|
|
1292
|
+
output = "|";
|
|
1293
|
+
}
|
|
1294
|
+
push({ type: "comma", value, output });
|
|
1295
|
+
continue;
|
|
1296
|
+
}
|
|
1297
|
+
if (value === "/") {
|
|
1298
|
+
if (prev.type === "dot" && state.index === state.start + 1) {
|
|
1299
|
+
state.start = state.index + 1;
|
|
1300
|
+
state.consumed = "";
|
|
1301
|
+
state.output = "";
|
|
1302
|
+
tokens.pop();
|
|
1303
|
+
prev = bos;
|
|
1304
|
+
continue;
|
|
1305
|
+
}
|
|
1306
|
+
push({ type: "slash", value, output: SLASH_LITERAL });
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
if (value === ".") {
|
|
1310
|
+
if (state.braces > 0 && prev.type === "dot") {
|
|
1311
|
+
if (prev.value === ".") prev.output = DOT_LITERAL;
|
|
1312
|
+
const brace = braces[braces.length - 1];
|
|
1313
|
+
prev.type = "dots";
|
|
1314
|
+
prev.output += value;
|
|
1315
|
+
prev.value += value;
|
|
1316
|
+
brace.dots = true;
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
|
|
1320
|
+
push({ type: "text", value, output: DOT_LITERAL });
|
|
1321
|
+
continue;
|
|
1322
|
+
}
|
|
1323
|
+
push({ type: "dot", value, output: DOT_LITERAL });
|
|
1324
|
+
continue;
|
|
1325
|
+
}
|
|
1326
|
+
if (value === "?") {
|
|
1327
|
+
const isGroup = prev && prev.value === "(";
|
|
1328
|
+
if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
|
|
1329
|
+
extglobOpen("qmark", value);
|
|
1330
|
+
continue;
|
|
1331
|
+
}
|
|
1332
|
+
if (prev && prev.type === "paren") {
|
|
1333
|
+
const next = peek();
|
|
1334
|
+
let output = value;
|
|
1335
|
+
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
|
|
1336
|
+
output = `\\${value}`;
|
|
1337
|
+
}
|
|
1338
|
+
push({ type: "text", value, output });
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1341
|
+
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
|
|
1342
|
+
push({ type: "qmark", value, output: QMARK_NO_DOT });
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
push({ type: "qmark", value, output: QMARK });
|
|
1346
|
+
continue;
|
|
1347
|
+
}
|
|
1348
|
+
if (value === "!") {
|
|
1349
|
+
if (opts.noextglob !== true && peek() === "(") {
|
|
1350
|
+
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
|
|
1351
|
+
extglobOpen("negate", value);
|
|
1352
|
+
continue;
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
if (opts.nonegate !== true && state.index === 0) {
|
|
1356
|
+
negate();
|
|
1357
|
+
continue;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
if (value === "+") {
|
|
1361
|
+
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
|
|
1362
|
+
extglobOpen("plus", value);
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
if (prev && prev.value === "(" || opts.regex === false) {
|
|
1366
|
+
push({ type: "plus", value, output: PLUS_LITERAL });
|
|
1367
|
+
continue;
|
|
1368
|
+
}
|
|
1369
|
+
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
|
|
1370
|
+
push({ type: "plus", value });
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
push({ type: "plus", value: PLUS_LITERAL });
|
|
1374
|
+
continue;
|
|
1375
|
+
}
|
|
1376
|
+
if (value === "@") {
|
|
1377
|
+
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
|
|
1378
|
+
push({ type: "at", extglob: true, value, output: "" });
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
push({ type: "text", value });
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
if (value !== "*") {
|
|
1385
|
+
if (value === "$" || value === "^") {
|
|
1386
|
+
value = `\\${value}`;
|
|
1387
|
+
}
|
|
1388
|
+
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
|
|
1389
|
+
if (match) {
|
|
1390
|
+
value += match[0];
|
|
1391
|
+
state.index += match[0].length;
|
|
1392
|
+
}
|
|
1393
|
+
push({ type: "text", value });
|
|
1394
|
+
continue;
|
|
1395
|
+
}
|
|
1396
|
+
if (prev && (prev.type === "globstar" || prev.star === true)) {
|
|
1397
|
+
prev.type = "star";
|
|
1398
|
+
prev.star = true;
|
|
1399
|
+
prev.value += value;
|
|
1400
|
+
prev.output = star;
|
|
1401
|
+
state.backtrack = true;
|
|
1402
|
+
state.globstar = true;
|
|
1403
|
+
consume(value);
|
|
1404
|
+
continue;
|
|
1405
|
+
}
|
|
1406
|
+
let rest = remaining();
|
|
1407
|
+
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
|
|
1408
|
+
extglobOpen("star", value);
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
if (prev.type === "star") {
|
|
1412
|
+
if (opts.noglobstar === true) {
|
|
1413
|
+
consume(value);
|
|
1414
|
+
continue;
|
|
1415
|
+
}
|
|
1416
|
+
const prior = prev.prev;
|
|
1417
|
+
const before = prior.prev;
|
|
1418
|
+
const isStart = prior.type === "slash" || prior.type === "bos";
|
|
1419
|
+
const afterStar = before && (before.type === "star" || before.type === "globstar");
|
|
1420
|
+
if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
|
|
1421
|
+
push({ type: "star", value, output: "" });
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
|
|
1425
|
+
const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
|
|
1426
|
+
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
|
|
1427
|
+
push({ type: "star", value, output: "" });
|
|
1428
|
+
continue;
|
|
1429
|
+
}
|
|
1430
|
+
while (rest.slice(0, 3) === "/**") {
|
|
1431
|
+
const after = input[state.index + 4];
|
|
1432
|
+
if (after && after !== "/") {
|
|
1433
|
+
break;
|
|
1434
|
+
}
|
|
1435
|
+
rest = rest.slice(3);
|
|
1436
|
+
consume("/**", 3);
|
|
1437
|
+
}
|
|
1438
|
+
if (prior.type === "bos" && eos()) {
|
|
1439
|
+
prev.type = "globstar";
|
|
1440
|
+
prev.value += value;
|
|
1441
|
+
prev.output = globstar(opts);
|
|
1442
|
+
state.output = prev.output;
|
|
1443
|
+
state.globstar = true;
|
|
1444
|
+
consume(value);
|
|
1445
|
+
continue;
|
|
1446
|
+
}
|
|
1447
|
+
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
|
|
1448
|
+
state.output = state.output.slice(0, -(prior.output + prev.output).length);
|
|
1449
|
+
prior.output = `(?:${prior.output}`;
|
|
1450
|
+
prev.type = "globstar";
|
|
1451
|
+
prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
|
|
1452
|
+
prev.value += value;
|
|
1453
|
+
state.globstar = true;
|
|
1454
|
+
state.output += prior.output + prev.output;
|
|
1455
|
+
consume(value);
|
|
1456
|
+
continue;
|
|
1457
|
+
}
|
|
1458
|
+
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
|
|
1459
|
+
const end = rest[1] !== void 0 ? "|$" : "";
|
|
1460
|
+
state.output = state.output.slice(0, -(prior.output + prev.output).length);
|
|
1461
|
+
prior.output = `(?:${prior.output}`;
|
|
1462
|
+
prev.type = "globstar";
|
|
1463
|
+
prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
|
|
1464
|
+
prev.value += value;
|
|
1465
|
+
state.output += prior.output + prev.output;
|
|
1466
|
+
state.globstar = true;
|
|
1467
|
+
consume(value + advance());
|
|
1468
|
+
push({ type: "slash", value: "/", output: "" });
|
|
1469
|
+
continue;
|
|
1470
|
+
}
|
|
1471
|
+
if (prior.type === "bos" && rest[0] === "/") {
|
|
1472
|
+
prev.type = "globstar";
|
|
1473
|
+
prev.value += value;
|
|
1474
|
+
prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
|
|
1475
|
+
state.output = prev.output;
|
|
1476
|
+
state.globstar = true;
|
|
1477
|
+
consume(value + advance());
|
|
1478
|
+
push({ type: "slash", value: "/", output: "" });
|
|
1479
|
+
continue;
|
|
1480
|
+
}
|
|
1481
|
+
state.output = state.output.slice(0, -prev.output.length);
|
|
1482
|
+
prev.type = "globstar";
|
|
1483
|
+
prev.output = globstar(opts);
|
|
1484
|
+
prev.value += value;
|
|
1485
|
+
state.output += prev.output;
|
|
1486
|
+
state.globstar = true;
|
|
1487
|
+
consume(value);
|
|
1488
|
+
continue;
|
|
1489
|
+
}
|
|
1490
|
+
const token = { type: "star", value, output: star };
|
|
1491
|
+
if (opts.bash === true) {
|
|
1492
|
+
token.output = ".*?";
|
|
1493
|
+
if (prev.type === "bos" || prev.type === "slash") {
|
|
1494
|
+
token.output = nodot + token.output;
|
|
1495
|
+
}
|
|
1496
|
+
push(token);
|
|
1497
|
+
continue;
|
|
1498
|
+
}
|
|
1499
|
+
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
|
|
1500
|
+
token.output = value;
|
|
1501
|
+
push(token);
|
|
1502
|
+
continue;
|
|
1503
|
+
}
|
|
1504
|
+
if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
|
|
1505
|
+
if (prev.type === "dot") {
|
|
1506
|
+
state.output += NO_DOT_SLASH;
|
|
1507
|
+
prev.output += NO_DOT_SLASH;
|
|
1508
|
+
} else if (opts.dot === true) {
|
|
1509
|
+
state.output += NO_DOTS_SLASH;
|
|
1510
|
+
prev.output += NO_DOTS_SLASH;
|
|
1511
|
+
} else {
|
|
1512
|
+
state.output += nodot;
|
|
1513
|
+
prev.output += nodot;
|
|
1514
|
+
}
|
|
1515
|
+
if (peek() !== "*") {
|
|
1516
|
+
state.output += ONE_CHAR;
|
|
1517
|
+
prev.output += ONE_CHAR;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
push(token);
|
|
1521
|
+
}
|
|
1522
|
+
while (state.brackets > 0) {
|
|
1523
|
+
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
|
|
1524
|
+
state.output = utils.escapeLast(state.output, "[");
|
|
1525
|
+
decrement("brackets");
|
|
1526
|
+
}
|
|
1527
|
+
while (state.parens > 0) {
|
|
1528
|
+
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
|
|
1529
|
+
state.output = utils.escapeLast(state.output, "(");
|
|
1530
|
+
decrement("parens");
|
|
1531
|
+
}
|
|
1532
|
+
while (state.braces > 0) {
|
|
1533
|
+
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
|
|
1534
|
+
state.output = utils.escapeLast(state.output, "{");
|
|
1535
|
+
decrement("braces");
|
|
1536
|
+
}
|
|
1537
|
+
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
|
|
1538
|
+
push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
|
|
1539
|
+
}
|
|
1540
|
+
if (state.backtrack === true) {
|
|
1541
|
+
state.output = "";
|
|
1542
|
+
for (const token of state.tokens) {
|
|
1543
|
+
state.output += token.output != null ? token.output : token.value;
|
|
1544
|
+
if (token.suffix) {
|
|
1545
|
+
state.output += token.suffix;
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
return state;
|
|
1550
|
+
};
|
|
1551
|
+
parse.fastpaths = (input, options) => {
|
|
1552
|
+
const opts = { ...options };
|
|
1553
|
+
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
|
|
1554
|
+
const len = input.length;
|
|
1555
|
+
if (len > max) {
|
|
1556
|
+
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
|
|
1557
|
+
}
|
|
1558
|
+
input = REPLACEMENTS[input] || input;
|
|
1559
|
+
const {
|
|
1560
|
+
DOT_LITERAL,
|
|
1561
|
+
SLASH_LITERAL,
|
|
1562
|
+
ONE_CHAR,
|
|
1563
|
+
DOTS_SLASH,
|
|
1564
|
+
NO_DOT,
|
|
1565
|
+
NO_DOTS,
|
|
1566
|
+
NO_DOTS_SLASH,
|
|
1567
|
+
STAR,
|
|
1568
|
+
START_ANCHOR
|
|
1569
|
+
} = constants.globChars(opts.windows);
|
|
1570
|
+
const nodot = opts.dot ? NO_DOTS : NO_DOT;
|
|
1571
|
+
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
|
|
1572
|
+
const capture = opts.capture ? "" : "?:";
|
|
1573
|
+
const state = { negated: false, prefix: "" };
|
|
1574
|
+
let star = opts.bash === true ? ".*?" : STAR;
|
|
1575
|
+
if (opts.capture) {
|
|
1576
|
+
star = `(${star})`;
|
|
1577
|
+
}
|
|
1578
|
+
const globstar = (opts2) => {
|
|
1579
|
+
if (opts2.noglobstar === true) return star;
|
|
1580
|
+
return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
|
|
1581
|
+
};
|
|
1582
|
+
const create = (str) => {
|
|
1583
|
+
switch (str) {
|
|
1584
|
+
case "*":
|
|
1585
|
+
return `${nodot}${ONE_CHAR}${star}`;
|
|
1586
|
+
case ".*":
|
|
1587
|
+
return `${DOT_LITERAL}${ONE_CHAR}${star}`;
|
|
1588
|
+
case "*.*":
|
|
1589
|
+
return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
|
|
1590
|
+
case "*/*":
|
|
1591
|
+
return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
|
|
1592
|
+
case "**":
|
|
1593
|
+
return nodot + globstar(opts);
|
|
1594
|
+
case "**/*":
|
|
1595
|
+
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
|
|
1596
|
+
case "**/*.*":
|
|
1597
|
+
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
|
|
1598
|
+
case "**/.*":
|
|
1599
|
+
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
|
|
1600
|
+
default: {
|
|
1601
|
+
const match = /^(.*?)\.(\w+)$/.exec(str);
|
|
1602
|
+
if (!match) return;
|
|
1603
|
+
const source2 = create(match[1]);
|
|
1604
|
+
if (!source2) return;
|
|
1605
|
+
return source2 + DOT_LITERAL + match[2];
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
const output = utils.removePrefix(input, state);
|
|
1610
|
+
let source = create(output);
|
|
1611
|
+
if (source && opts.strictSlashes !== true) {
|
|
1612
|
+
source += `${SLASH_LITERAL}?`;
|
|
1613
|
+
}
|
|
1614
|
+
return source;
|
|
1615
|
+
};
|
|
1616
|
+
module.exports = parse;
|
|
1617
|
+
}
|
|
1618
|
+
});
|
|
1619
|
+
|
|
1620
|
+
// ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/picomatch.js
|
|
1621
|
+
var require_picomatch = __commonJS({
|
|
1622
|
+
"../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/lib/picomatch.js"(exports, module) {
|
|
1623
|
+
"use strict";
|
|
1624
|
+
var scan = require_scan();
|
|
1625
|
+
var parse = require_parse();
|
|
1626
|
+
var utils = require_utils();
|
|
1627
|
+
var constants = require_constants();
|
|
1628
|
+
var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
|
|
1629
|
+
var picomatch2 = (glob, options, returnState = false) => {
|
|
1630
|
+
if (Array.isArray(glob)) {
|
|
1631
|
+
const fns = glob.map((input) => picomatch2(input, options, returnState));
|
|
1632
|
+
const arrayMatcher = (str) => {
|
|
1633
|
+
for (const isMatch of fns) {
|
|
1634
|
+
const state2 = isMatch(str);
|
|
1635
|
+
if (state2) return state2;
|
|
1636
|
+
}
|
|
1637
|
+
return false;
|
|
1638
|
+
};
|
|
1639
|
+
return arrayMatcher;
|
|
1640
|
+
}
|
|
1641
|
+
const isState = isObject(glob) && glob.tokens && glob.input;
|
|
1642
|
+
if (glob === "" || typeof glob !== "string" && !isState) {
|
|
1643
|
+
throw new TypeError("Expected pattern to be a non-empty string");
|
|
1644
|
+
}
|
|
1645
|
+
const opts = options || {};
|
|
1646
|
+
const posix = opts.windows;
|
|
1647
|
+
const regex = isState ? picomatch2.compileRe(glob, options) : picomatch2.makeRe(glob, options, false, true);
|
|
1648
|
+
const state = regex.state;
|
|
1649
|
+
delete regex.state;
|
|
1650
|
+
let isIgnored = () => false;
|
|
1651
|
+
if (opts.ignore) {
|
|
1652
|
+
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
|
|
1653
|
+
isIgnored = picomatch2(opts.ignore, ignoreOpts, returnState);
|
|
1654
|
+
}
|
|
1655
|
+
const matcher = (input, returnObject = false) => {
|
|
1656
|
+
const { isMatch, match, output } = picomatch2.test(input, regex, options, { glob, posix });
|
|
1657
|
+
const result = { glob, state, regex, posix, input, output, match, isMatch };
|
|
1658
|
+
if (typeof opts.onResult === "function") {
|
|
1659
|
+
opts.onResult(result);
|
|
1660
|
+
}
|
|
1661
|
+
if (isMatch === false) {
|
|
1662
|
+
result.isMatch = false;
|
|
1663
|
+
return returnObject ? result : false;
|
|
1664
|
+
}
|
|
1665
|
+
if (isIgnored(input)) {
|
|
1666
|
+
if (typeof opts.onIgnore === "function") {
|
|
1667
|
+
opts.onIgnore(result);
|
|
1668
|
+
}
|
|
1669
|
+
result.isMatch = false;
|
|
1670
|
+
return returnObject ? result : false;
|
|
1671
|
+
}
|
|
1672
|
+
if (typeof opts.onMatch === "function") {
|
|
1673
|
+
opts.onMatch(result);
|
|
1674
|
+
}
|
|
1675
|
+
return returnObject ? result : true;
|
|
1676
|
+
};
|
|
1677
|
+
if (returnState) {
|
|
1678
|
+
matcher.state = state;
|
|
1679
|
+
}
|
|
1680
|
+
return matcher;
|
|
1681
|
+
};
|
|
1682
|
+
picomatch2.test = (input, regex, options, { glob, posix } = {}) => {
|
|
1683
|
+
if (typeof input !== "string") {
|
|
1684
|
+
throw new TypeError("Expected input to be a string");
|
|
1685
|
+
}
|
|
1686
|
+
if (input === "") {
|
|
1687
|
+
return { isMatch: false, output: "" };
|
|
1688
|
+
}
|
|
1689
|
+
const opts = options || {};
|
|
1690
|
+
const format = opts.format || (posix ? utils.toPosixSlashes : null);
|
|
1691
|
+
let match = input === glob;
|
|
1692
|
+
let output = match && format ? format(input) : input;
|
|
1693
|
+
if (match === false) {
|
|
1694
|
+
output = format ? format(input) : input;
|
|
1695
|
+
match = output === glob;
|
|
1696
|
+
}
|
|
1697
|
+
if (match === false || opts.capture === true) {
|
|
1698
|
+
if (opts.matchBase === true || opts.basename === true) {
|
|
1699
|
+
match = picomatch2.matchBase(input, regex, options, posix);
|
|
1700
|
+
} else {
|
|
1701
|
+
match = regex.exec(output);
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
return { isMatch: Boolean(match), match, output };
|
|
1705
|
+
};
|
|
1706
|
+
picomatch2.matchBase = (input, glob, options) => {
|
|
1707
|
+
const regex = glob instanceof RegExp ? glob : picomatch2.makeRe(glob, options);
|
|
1708
|
+
return regex.test(utils.basename(input));
|
|
1709
|
+
};
|
|
1710
|
+
picomatch2.isMatch = (str, patterns, options) => picomatch2(patterns, options)(str);
|
|
1711
|
+
picomatch2.parse = (pattern, options) => {
|
|
1712
|
+
if (Array.isArray(pattern)) return pattern.map((p) => picomatch2.parse(p, options));
|
|
1713
|
+
return parse(pattern, { ...options, fastpaths: false });
|
|
1714
|
+
};
|
|
1715
|
+
picomatch2.scan = (input, options) => scan(input, options);
|
|
1716
|
+
picomatch2.compileRe = (state, options, returnOutput = false, returnState = false) => {
|
|
1717
|
+
if (returnOutput === true) {
|
|
1718
|
+
return state.output;
|
|
1719
|
+
}
|
|
1720
|
+
const opts = options || {};
|
|
1721
|
+
const prepend = opts.contains ? "" : "^";
|
|
1722
|
+
const append = opts.contains ? "" : "$";
|
|
1723
|
+
let source = `${prepend}(?:${state.output})${append}`;
|
|
1724
|
+
if (state && state.negated === true) {
|
|
1725
|
+
source = `^(?!${source}).*$`;
|
|
1726
|
+
}
|
|
1727
|
+
const regex = picomatch2.toRegex(source, options);
|
|
1728
|
+
if (returnState === true) {
|
|
1729
|
+
regex.state = state;
|
|
1730
|
+
}
|
|
1731
|
+
return regex;
|
|
1732
|
+
};
|
|
1733
|
+
picomatch2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
|
|
1734
|
+
if (!input || typeof input !== "string") {
|
|
1735
|
+
throw new TypeError("Expected a non-empty string");
|
|
1736
|
+
}
|
|
1737
|
+
let parsed = { negated: false, fastpaths: true };
|
|
1738
|
+
if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
|
|
1739
|
+
parsed.output = parse.fastpaths(input, options);
|
|
1740
|
+
}
|
|
1741
|
+
if (!parsed.output) {
|
|
1742
|
+
parsed = parse(input, options);
|
|
1743
|
+
}
|
|
1744
|
+
return picomatch2.compileRe(parsed, options, returnOutput, returnState);
|
|
1745
|
+
};
|
|
1746
|
+
picomatch2.toRegex = (source, options) => {
|
|
1747
|
+
try {
|
|
1748
|
+
const opts = options || {};
|
|
1749
|
+
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
|
|
1750
|
+
} catch (err) {
|
|
1751
|
+
if (options && options.debug === true) throw err;
|
|
1752
|
+
return /$^/;
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
picomatch2.constants = constants;
|
|
1756
|
+
module.exports = picomatch2;
|
|
1757
|
+
}
|
|
1758
|
+
});
|
|
1759
|
+
|
|
1760
|
+
// ../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/index.js
|
|
1761
|
+
var require_picomatch2 = __commonJS({
|
|
1762
|
+
"../../node_modules/.pnpm/picomatch@4.0.4/node_modules/picomatch/index.js"(exports, module) {
|
|
1763
|
+
"use strict";
|
|
1764
|
+
var pico = require_picomatch();
|
|
1765
|
+
var utils = require_utils();
|
|
1766
|
+
function picomatch2(glob, options, returnState = false) {
|
|
1767
|
+
if (options && (options.windows === null || options.windows === void 0)) {
|
|
1768
|
+
options = { ...options, windows: utils.isWindows() };
|
|
1769
|
+
}
|
|
1770
|
+
return pico(glob, options, returnState);
|
|
1771
|
+
}
|
|
1772
|
+
Object.assign(picomatch2, pico);
|
|
1773
|
+
module.exports = picomatch2;
|
|
1774
|
+
}
|
|
1775
|
+
});
|
|
1776
|
+
|
|
1777
|
+
// src/pep/hook-shim.ts
|
|
1778
|
+
import { homedir as homedir2 } from "os";
|
|
1779
|
+
|
|
1780
|
+
// ../shared/src/policy-evaluate.ts
|
|
1781
|
+
var POLICY_EVALUATE_DEFAULT_KIND = "execute_tool";
|
|
1782
|
+
var POLICY_HOLD_MAX_WINDOW_SECONDS = 590;
|
|
1783
|
+
|
|
1784
|
+
// ../policy-engine/src/context.ts
|
|
1785
|
+
var NIL_UUID = "00000000-0000-0000-0000-000000000000";
|
|
1786
|
+
var EPOCH = "1970-01-01T00:00:00.000Z";
|
|
1787
|
+
function normalizeSpanAttributes(attributes) {
|
|
1788
|
+
if (attributes.detail === void 0 && attributes.full_command !== void 0) {
|
|
1789
|
+
return { ...attributes, detail: attributes.full_command };
|
|
1790
|
+
}
|
|
1791
|
+
return attributes;
|
|
1792
|
+
}
|
|
1793
|
+
function buildEvaluationContext(request, orgId) {
|
|
1794
|
+
const span = {
|
|
1795
|
+
id: NIL_UUID,
|
|
1796
|
+
traceId: NIL_UUID,
|
|
1797
|
+
orgId,
|
|
1798
|
+
parentSpanId: null,
|
|
1799
|
+
kind: request.kind ?? POLICY_EVALUATE_DEFAULT_KIND,
|
|
1800
|
+
label: request.tool,
|
|
1801
|
+
startedAt: EPOCH,
|
|
1802
|
+
durationMs: 0,
|
|
1803
|
+
tokens: 0,
|
|
1804
|
+
cachedTokens: 0,
|
|
1805
|
+
failed: false,
|
|
1806
|
+
attributes: normalizeSpanAttributes(request.args)
|
|
1807
|
+
};
|
|
1808
|
+
return {
|
|
1809
|
+
span,
|
|
1810
|
+
agentId: request.scope?.agent_id ?? NIL_UUID,
|
|
1811
|
+
projectId: request.scope?.project_id ?? NIL_UUID,
|
|
1812
|
+
developerId: request.scope?.developer_id ?? null
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
// ../policy-engine/src/matchers.ts
|
|
1817
|
+
var import_picomatch = __toESM(require_picomatch2(), 1);
|
|
1818
|
+
var DETAIL_ATTR = "detail";
|
|
1819
|
+
var FILE_PATH_ATTR = "file_path";
|
|
1820
|
+
var FILE_GLOB_OPTIONS = { dot: true, nocase: true };
|
|
1821
|
+
var LABEL_GLOB_OPTIONS = { dot: true, nocase: true };
|
|
1822
|
+
function matchKind(conditionKind, span) {
|
|
1823
|
+
const matched = span.kind.toLowerCase() === conditionKind.toLowerCase();
|
|
1824
|
+
return {
|
|
1825
|
+
matched,
|
|
1826
|
+
reason: matched ? `kind: "${conditionKind}" matched` : `kind: expected "${conditionKind}", got "${span.kind}"`
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
function matchLabel(conditionLabel, span) {
|
|
1830
|
+
const matched = createCompiledLabelMatcher(conditionLabel)(span.label);
|
|
1831
|
+
return {
|
|
1832
|
+
matched,
|
|
1833
|
+
reason: matched ? `label: "${conditionLabel}" matched` : `label: expected "${conditionLabel}", got "${span.label}"`
|
|
1834
|
+
};
|
|
1835
|
+
}
|
|
1836
|
+
function matchDetailContains(requiredSubstrings, span) {
|
|
1837
|
+
const detail = span.attributes[DETAIL_ATTR];
|
|
1838
|
+
if (detail === void 0) {
|
|
1839
|
+
return { matched: false, reason: "detail_contains: detail attribute missing" };
|
|
1840
|
+
}
|
|
1841
|
+
const missing = [];
|
|
1842
|
+
for (const substring of requiredSubstrings) {
|
|
1843
|
+
if (!detail.includes(substring)) {
|
|
1844
|
+
missing.push(substring);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
if (missing.length > 0) {
|
|
1848
|
+
return {
|
|
1849
|
+
matched: false,
|
|
1850
|
+
reason: `detail_contains: missing substrings: ${JSON.stringify(missing)}`
|
|
1851
|
+
};
|
|
1852
|
+
}
|
|
1853
|
+
return {
|
|
1854
|
+
matched: true,
|
|
1855
|
+
reason: `detail_contains: all ${requiredSubstrings.length} substring(s) found`
|
|
1856
|
+
};
|
|
1857
|
+
}
|
|
1858
|
+
function matchDetailMatches(patterns, span) {
|
|
1859
|
+
const detail = span.attributes[DETAIL_ATTR];
|
|
1860
|
+
if (detail === void 0) {
|
|
1861
|
+
return { matched: false, reason: "detail_matches: detail attribute missing" };
|
|
1862
|
+
}
|
|
1863
|
+
for (const pattern of patterns) {
|
|
1864
|
+
if (createCompiledDetailMatcher(pattern)(detail)) {
|
|
1865
|
+
return { matched: true, reason: `detail_matches: "${pattern}" matched` };
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
return {
|
|
1869
|
+
matched: false,
|
|
1870
|
+
reason: `detail_matches: no pattern of ${patterns.length} matched`
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
function matchFileGlob(pattern, span) {
|
|
1874
|
+
const filePath = span.attributes[FILE_PATH_ATTR];
|
|
1875
|
+
if (filePath === void 0) {
|
|
1876
|
+
return { matched: false, reason: "file_glob: file_path attribute missing" };
|
|
1877
|
+
}
|
|
1878
|
+
try {
|
|
1879
|
+
const isMatch = (0, import_picomatch.default)(pattern, FILE_GLOB_OPTIONS);
|
|
1880
|
+
const matched = isMatch(filePath);
|
|
1881
|
+
return {
|
|
1882
|
+
matched,
|
|
1883
|
+
reason: matched ? `file_glob: "${pattern}" matched "${filePath}"` : `file_glob: "${pattern}" did not match "${filePath}"`
|
|
1884
|
+
};
|
|
1885
|
+
} catch {
|
|
1886
|
+
return {
|
|
1887
|
+
matched: false,
|
|
1888
|
+
reason: `file_glob: invalid pattern: "${pattern}"`
|
|
1889
|
+
};
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
function resolveNumericField(field, span) {
|
|
1893
|
+
switch (field) {
|
|
1894
|
+
case "tokens":
|
|
1895
|
+
return span.tokens;
|
|
1896
|
+
case "cached_tokens":
|
|
1897
|
+
return span.cachedTokens;
|
|
1898
|
+
case "duration_ms":
|
|
1899
|
+
return span.durationMs;
|
|
1900
|
+
default: {
|
|
1901
|
+
const _exhaustive = field;
|
|
1902
|
+
throw new Error(`unmapped numeric field: ${String(_exhaustive)}`);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
function matchNumeric(comparison, span) {
|
|
1907
|
+
const actual = resolveNumericField(comparison.field, span);
|
|
1908
|
+
const { op, value, field } = comparison;
|
|
1909
|
+
let matched;
|
|
1910
|
+
switch (op) {
|
|
1911
|
+
case "gt":
|
|
1912
|
+
matched = actual > value;
|
|
1913
|
+
break;
|
|
1914
|
+
case "gte":
|
|
1915
|
+
matched = actual >= value;
|
|
1916
|
+
break;
|
|
1917
|
+
case "lt":
|
|
1918
|
+
matched = actual < value;
|
|
1919
|
+
break;
|
|
1920
|
+
case "lte":
|
|
1921
|
+
matched = actual <= value;
|
|
1922
|
+
break;
|
|
1923
|
+
default: {
|
|
1924
|
+
const _exhaustive = op;
|
|
1925
|
+
throw new Error(`unmapped numeric op: ${String(_exhaustive)}`);
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
return {
|
|
1929
|
+
matched,
|
|
1930
|
+
reason: matched ? `numeric: ${field} (${actual}) ${op} ${value} matched` : `numeric: ${field} (${actual}) not ${op} ${value}`
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
var compiledGlobCache = /* @__PURE__ */ new Map();
|
|
1934
|
+
var compiledLabelCache = /* @__PURE__ */ new Map();
|
|
1935
|
+
var compiledDetailCache = /* @__PURE__ */ new Map();
|
|
1936
|
+
function createCompiledLabelMatcher(pattern) {
|
|
1937
|
+
let matcher = compiledLabelCache.get(pattern);
|
|
1938
|
+
if (matcher === void 0) {
|
|
1939
|
+
try {
|
|
1940
|
+
matcher = (0, import_picomatch.default)(pattern, LABEL_GLOB_OPTIONS);
|
|
1941
|
+
} catch {
|
|
1942
|
+
matcher = () => false;
|
|
1943
|
+
}
|
|
1944
|
+
compiledLabelCache.set(pattern, matcher);
|
|
1945
|
+
}
|
|
1946
|
+
const cached = matcher;
|
|
1947
|
+
return (label) => cached(label);
|
|
1948
|
+
}
|
|
1949
|
+
function createCompiledDetailMatcher(pattern) {
|
|
1950
|
+
let compiled = compiledDetailCache.get(pattern);
|
|
1951
|
+
if (compiled === void 0) {
|
|
1952
|
+
try {
|
|
1953
|
+
compiled = new RegExp(pattern, "i");
|
|
1954
|
+
} catch {
|
|
1955
|
+
compiled = null;
|
|
1956
|
+
}
|
|
1957
|
+
compiledDetailCache.set(pattern, compiled);
|
|
1958
|
+
}
|
|
1959
|
+
const cached = compiled;
|
|
1960
|
+
return cached === null ? () => false : (detail) => cached.test(detail);
|
|
1961
|
+
}
|
|
1962
|
+
function createCompiledFileGlobMatcher(pattern) {
|
|
1963
|
+
let matcher = compiledGlobCache.get(pattern);
|
|
1964
|
+
if (!matcher) {
|
|
1965
|
+
try {
|
|
1966
|
+
matcher = (0, import_picomatch.default)(pattern, FILE_GLOB_OPTIONS);
|
|
1967
|
+
compiledGlobCache.set(pattern, matcher);
|
|
1968
|
+
} catch {
|
|
1969
|
+
return (_span) => ({
|
|
1970
|
+
matched: false,
|
|
1971
|
+
reason: `file_glob: invalid pattern: "${pattern}"`
|
|
1972
|
+
});
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
const cachedMatcher = matcher;
|
|
1976
|
+
return (span) => {
|
|
1977
|
+
const filePath = span.attributes[FILE_PATH_ATTR];
|
|
1978
|
+
if (filePath === void 0) {
|
|
1979
|
+
return { matched: false, reason: "file_glob: file_path attribute missing" };
|
|
1980
|
+
}
|
|
1981
|
+
const matched = cachedMatcher(filePath);
|
|
1982
|
+
return {
|
|
1983
|
+
matched,
|
|
1984
|
+
reason: matched ? `file_glob: "${pattern}" matched "${filePath}"` : `file_glob: "${pattern}" did not match "${filePath}"`
|
|
1985
|
+
};
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
// ../policy-engine/src/scope.ts
|
|
1990
|
+
function isInScopeArray(scopeArray, value) {
|
|
1991
|
+
return scopeArray.includes("*") || scopeArray.includes(value);
|
|
1992
|
+
}
|
|
1993
|
+
function matchScope(scope, context) {
|
|
1994
|
+
if (scope === void 0) {
|
|
1995
|
+
return { matched: true, reason: "scope: no scope filter (applies globally)" };
|
|
1996
|
+
}
|
|
1997
|
+
const failures = [];
|
|
1998
|
+
if (scope.agent_in !== void 0) {
|
|
1999
|
+
if (!isInScopeArray(scope.agent_in, context.agentId)) {
|
|
2000
|
+
failures.push(`agent_in: "${context.agentId}" not in [${scope.agent_in.join(", ")}]`);
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
if (scope.project_in !== void 0) {
|
|
2004
|
+
if (!isInScopeArray(scope.project_in, context.projectId)) {
|
|
2005
|
+
failures.push(`project_in: "${context.projectId}" not in [${scope.project_in.join(", ")}]`);
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
if (failures.length > 0) {
|
|
2009
|
+
return {
|
|
2010
|
+
matched: false,
|
|
2011
|
+
reason: `scope: ${failures.join("; ")}`
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
return { matched: true, reason: "scope: all scope filters matched" };
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
// ../policy-engine/src/evaluator.ts
|
|
2018
|
+
function evaluateConditionCompiled(condition, span, compiledGlobMatcher) {
|
|
2019
|
+
const kindResult = matchKind(condition.kind, span);
|
|
2020
|
+
if (!kindResult.matched) {
|
|
2021
|
+
return kindResult;
|
|
2022
|
+
}
|
|
2023
|
+
const reasons = [kindResult.reason];
|
|
2024
|
+
if (condition.label !== void 0) {
|
|
2025
|
+
const labelResult = matchLabel(condition.label, span);
|
|
2026
|
+
if (!labelResult.matched) {
|
|
2027
|
+
return labelResult;
|
|
2028
|
+
}
|
|
2029
|
+
reasons.push(labelResult.reason);
|
|
2030
|
+
}
|
|
2031
|
+
if (condition.detail_contains !== void 0) {
|
|
2032
|
+
const detailResult = matchDetailContains(condition.detail_contains, span);
|
|
2033
|
+
if (!detailResult.matched) {
|
|
2034
|
+
return detailResult;
|
|
2035
|
+
}
|
|
2036
|
+
reasons.push(detailResult.reason);
|
|
2037
|
+
}
|
|
2038
|
+
if (condition.detail_matches !== void 0) {
|
|
2039
|
+
const regexResult = matchDetailMatches(condition.detail_matches, span);
|
|
2040
|
+
if (!regexResult.matched) {
|
|
2041
|
+
return regexResult;
|
|
2042
|
+
}
|
|
2043
|
+
reasons.push(regexResult.reason);
|
|
2044
|
+
}
|
|
2045
|
+
if (condition.file_glob !== void 0) {
|
|
2046
|
+
if (compiledGlobMatcher) {
|
|
2047
|
+
const globResult = compiledGlobMatcher(span);
|
|
2048
|
+
if (!globResult.matched) {
|
|
2049
|
+
return globResult;
|
|
2050
|
+
}
|
|
2051
|
+
reasons.push(globResult.reason);
|
|
2052
|
+
} else {
|
|
2053
|
+
const globResult = matchFileGlob(condition.file_glob, span);
|
|
2054
|
+
if (!globResult.matched) {
|
|
2055
|
+
return globResult;
|
|
2056
|
+
}
|
|
2057
|
+
reasons.push(globResult.reason);
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
if (condition.numeric !== void 0) {
|
|
2061
|
+
for (const comparison of condition.numeric) {
|
|
2062
|
+
const numericResult = matchNumeric(comparison, span);
|
|
2063
|
+
if (!numericResult.matched) {
|
|
2064
|
+
return numericResult;
|
|
2065
|
+
}
|
|
2066
|
+
reasons.push(numericResult.reason);
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
return {
|
|
2070
|
+
matched: true,
|
|
2071
|
+
reason: reasons.join("; ")
|
|
2072
|
+
};
|
|
2073
|
+
}
|
|
2074
|
+
function compilePolicy(predicate) {
|
|
2075
|
+
function compileConditions(conditions) {
|
|
2076
|
+
if (conditions === void 0) return void 0;
|
|
2077
|
+
return conditions.map((condition) => {
|
|
2078
|
+
const globMatcher = condition.file_glob ? createCompiledFileGlobMatcher(condition.file_glob) : void 0;
|
|
2079
|
+
return globMatcher ? { condition, globMatcher } : { condition };
|
|
2080
|
+
});
|
|
2081
|
+
}
|
|
2082
|
+
const compiledAnyOf = compileConditions(predicate.match.any_of);
|
|
2083
|
+
const compiledAllOf = compileConditions(predicate.match.all_of);
|
|
2084
|
+
const compiledNoneOf = compileConditions(predicate.match.none_of);
|
|
2085
|
+
const scope = predicate.scope;
|
|
2086
|
+
return (context) => {
|
|
2087
|
+
const scopeResult = matchScope(scope, context);
|
|
2088
|
+
if (!scopeResult.matched) {
|
|
2089
|
+
return { matched: false, reasons: [scopeResult.reason] };
|
|
2090
|
+
}
|
|
2091
|
+
const reasons = [];
|
|
2092
|
+
const span = context.span;
|
|
2093
|
+
if (compiledAllOf !== void 0) {
|
|
2094
|
+
for (const { condition, globMatcher } of compiledAllOf) {
|
|
2095
|
+
const result = evaluateConditionCompiled(condition, span, globMatcher);
|
|
2096
|
+
if (!result.matched) {
|
|
2097
|
+
return {
|
|
2098
|
+
matched: false,
|
|
2099
|
+
reasons: [`all_of: condition failed \u2014 ${result.reason}`]
|
|
2100
|
+
};
|
|
2101
|
+
}
|
|
2102
|
+
reasons.push(`all_of: ${result.reason}`);
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
if (compiledAnyOf !== void 0) {
|
|
2106
|
+
let anyMatched = false;
|
|
2107
|
+
const anyOfReasons = [];
|
|
2108
|
+
for (const { condition, globMatcher } of compiledAnyOf) {
|
|
2109
|
+
const result = evaluateConditionCompiled(condition, span, globMatcher);
|
|
2110
|
+
if (result.matched) {
|
|
2111
|
+
anyMatched = true;
|
|
2112
|
+
anyOfReasons.push(`any_of: ${result.reason}`);
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
if (!anyMatched) {
|
|
2116
|
+
return { matched: false, reasons: ["any_of: no conditions matched"] };
|
|
2117
|
+
}
|
|
2118
|
+
reasons.push(...anyOfReasons);
|
|
2119
|
+
}
|
|
2120
|
+
if (compiledNoneOf !== void 0) {
|
|
2121
|
+
for (const { condition, globMatcher } of compiledNoneOf) {
|
|
2122
|
+
const result = evaluateConditionCompiled(condition, span, globMatcher);
|
|
2123
|
+
if (result.matched) {
|
|
2124
|
+
return {
|
|
2125
|
+
matched: false,
|
|
2126
|
+
reasons: [`none_of: excluded condition matched \u2014 ${result.reason}`]
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
reasons.push(`none_of: no excluded condition matched (${compiledNoneOf.length} checked)`);
|
|
2131
|
+
}
|
|
2132
|
+
return { matched: true, reasons };
|
|
2133
|
+
};
|
|
2134
|
+
}
|
|
2135
|
+
|
|
2136
|
+
// ../policy-engine/src/verdict.ts
|
|
2137
|
+
function strongestVerdict(matches) {
|
|
2138
|
+
let denyId = null;
|
|
2139
|
+
let approvalId = null;
|
|
2140
|
+
for (const m of matches) {
|
|
2141
|
+
if (m.action === "block") {
|
|
2142
|
+
if (denyId === null) denyId = m.policyId;
|
|
2143
|
+
} else if (m.action === "require_approval") {
|
|
2144
|
+
if (approvalId === null) approvalId = m.policyId;
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
if (denyId !== null) return { verdict: "deny", policyId: denyId };
|
|
2148
|
+
if (approvalId !== null) return { verdict: "require_approval", policyId: approvalId };
|
|
2149
|
+
return { verdict: "allow", policyId: null };
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
// src/cursor/detect.ts
|
|
2153
|
+
var CURSOR_EVENT_NAMES = /* @__PURE__ */ new Set([
|
|
2154
|
+
// guard's list
|
|
2155
|
+
"preToolUse",
|
|
2156
|
+
"postToolUse",
|
|
2157
|
+
"postToolUseFailure",
|
|
2158
|
+
"beforeShellExecution",
|
|
2159
|
+
"afterShellExecution",
|
|
2160
|
+
"beforeMCPExecution",
|
|
2161
|
+
"afterMCPExecution",
|
|
2162
|
+
"beforeReadFile",
|
|
2163
|
+
"beforeTabFileRead",
|
|
2164
|
+
"afterFileEdit",
|
|
2165
|
+
"subagentStart",
|
|
2166
|
+
"beforeSubmitPrompt",
|
|
2167
|
+
"stop",
|
|
2168
|
+
// Cursor events guard's list lacks
|
|
2169
|
+
"afterAgentResponse",
|
|
2170
|
+
"subagentStop",
|
|
2171
|
+
"sessionEnd",
|
|
2172
|
+
// where Cursor runs a Claude Code SessionStart hook
|
|
2173
|
+
"sessionStart",
|
|
2174
|
+
// measured in L1 (Cursor 3.21.16)
|
|
2175
|
+
"afterAgentThought",
|
|
2176
|
+
"workspaceOpen"
|
|
2177
|
+
]);
|
|
2178
|
+
function isCursorHookPayload(payload) {
|
|
2179
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return false;
|
|
2180
|
+
const { cursor_version, hook_event_name } = payload;
|
|
2181
|
+
if (typeof cursor_version === "string") return true;
|
|
2182
|
+
return typeof hook_event_name === "string" && CURSOR_EVENT_NAMES.has(hook_event_name);
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
// src/capture/file-io.ts
|
|
2186
|
+
import {
|
|
2187
|
+
chmodSync,
|
|
2188
|
+
existsSync,
|
|
2189
|
+
mkdirSync,
|
|
2190
|
+
readdirSync,
|
|
2191
|
+
readFileSync,
|
|
2192
|
+
renameSync,
|
|
2193
|
+
rmSync,
|
|
2194
|
+
writeFileSync
|
|
2195
|
+
} from "fs";
|
|
2196
|
+
import { basename, dirname, join } from "path";
|
|
2197
|
+
var CAPTURE_DIR_MODE = 448;
|
|
2198
|
+
var CAPTURE_FILE_MODE = 384;
|
|
2199
|
+
var tempCounter = 0;
|
|
2200
|
+
function tempPathFor(path, pid = process.pid) {
|
|
2201
|
+
tempCounter += 1;
|
|
2202
|
+
return join(dirname(path), `.${basename(path)}.${pid}.${tempCounter}.tmp`);
|
|
2203
|
+
}
|
|
2204
|
+
var nodeCaptureFileIO = {
|
|
2205
|
+
readFile(path) {
|
|
2206
|
+
return readFileSync(path);
|
|
2207
|
+
},
|
|
2208
|
+
writeFileAtomic(path, data, mode) {
|
|
2209
|
+
mkdirSync(dirname(path), { recursive: true, mode: CAPTURE_DIR_MODE });
|
|
2210
|
+
const temp = tempPathFor(path);
|
|
2211
|
+
try {
|
|
2212
|
+
writeFileSync(temp, data, { mode });
|
|
2213
|
+
chmodSync(temp, mode);
|
|
2214
|
+
renameSync(temp, path);
|
|
2215
|
+
} catch (err) {
|
|
2216
|
+
rmSync(temp, { force: true });
|
|
2217
|
+
throw err;
|
|
2218
|
+
}
|
|
2219
|
+
},
|
|
2220
|
+
mkdirp(path, mode) {
|
|
2221
|
+
mkdirSync(path, { recursive: true, mode });
|
|
2222
|
+
},
|
|
2223
|
+
remove(path) {
|
|
2224
|
+
rmSync(path, { recursive: true, force: true });
|
|
2225
|
+
},
|
|
2226
|
+
exists(path) {
|
|
2227
|
+
return existsSync(path);
|
|
2228
|
+
},
|
|
2229
|
+
readdir(path) {
|
|
2230
|
+
return readdirSync(path).sort();
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
|
|
2234
|
+
// ../shared/src/agent-attributes.ts
|
|
2235
|
+
var TOOL_VENDOR_NAME_MAX_LENGTH = 255;
|
|
2236
|
+
|
|
2237
|
+
// src/capture/canonical.ts
|
|
2238
|
+
import { createHash } from "crypto";
|
|
2239
|
+
var PAID_DETAIL_CAP = 8192;
|
|
2240
|
+
var CORRELATION_ID_MAX = 255;
|
|
2241
|
+
function capToPaidDetail(s) {
|
|
2242
|
+
return s.length > PAID_DETAIL_CAP ? s.slice(0, PAID_DETAIL_CAP) : s;
|
|
2243
|
+
}
|
|
2244
|
+
function sortedJson(value) {
|
|
2245
|
+
const sort = (v) => {
|
|
2246
|
+
if (Array.isArray(v)) return v.map(sort);
|
|
2247
|
+
if (v !== null && typeof v === "object") {
|
|
2248
|
+
const record = v;
|
|
2249
|
+
return Object.fromEntries(
|
|
2250
|
+
Object.keys(record).sort().map((key) => [key, sort(record[key])])
|
|
2251
|
+
);
|
|
2252
|
+
}
|
|
2253
|
+
return v;
|
|
2254
|
+
};
|
|
2255
|
+
try {
|
|
2256
|
+
return JSON.stringify(sort(value)) ?? "";
|
|
2257
|
+
} catch {
|
|
2258
|
+
return "";
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
function safeStringify(value) {
|
|
2262
|
+
try {
|
|
2263
|
+
return JSON.stringify(value) ?? "";
|
|
2264
|
+
} catch {
|
|
2265
|
+
return "";
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
function mcpFullCommand(input) {
|
|
2269
|
+
return capToPaidDetail(mcpInputText(input));
|
|
2270
|
+
}
|
|
2271
|
+
function mcpInputText(input) {
|
|
2272
|
+
if (typeof input === "string") {
|
|
2273
|
+
let parsed;
|
|
2274
|
+
try {
|
|
2275
|
+
parsed = JSON.parse(input);
|
|
2276
|
+
} catch {
|
|
2277
|
+
return input;
|
|
2278
|
+
}
|
|
2279
|
+
return parsed !== null && typeof parsed === "object" ? safeStringify(parsed) : input;
|
|
2280
|
+
}
|
|
2281
|
+
if (input !== null && typeof input === "object") return safeStringify(input);
|
|
2282
|
+
return "{}";
|
|
2283
|
+
}
|
|
2284
|
+
function serializeMcpInput(input) {
|
|
2285
|
+
if (typeof input === "string") {
|
|
2286
|
+
let parsed;
|
|
2287
|
+
try {
|
|
2288
|
+
parsed = JSON.parse(input);
|
|
2289
|
+
} catch {
|
|
2290
|
+
return capToPaidDetail(input);
|
|
2291
|
+
}
|
|
2292
|
+
return capToPaidDetail(sortedJson(parsed));
|
|
2293
|
+
}
|
|
2294
|
+
if (input !== null && typeof input === "object") return capToPaidDetail(sortedJson(input));
|
|
2295
|
+
return "{}";
|
|
2296
|
+
}
|
|
2297
|
+
function correlationIdFor(raw) {
|
|
2298
|
+
if (typeof raw !== "string" || raw === "") return null;
|
|
2299
|
+
if (raw.length <= CORRELATION_ID_MAX && !hasControlCharacter(raw)) return raw;
|
|
2300
|
+
return `sha256:${createHash("sha256").update(raw, "utf8").digest("hex")}`;
|
|
2301
|
+
}
|
|
2302
|
+
function hasControlCharacter(s) {
|
|
2303
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
2304
|
+
const code = s.charCodeAt(i);
|
|
2305
|
+
if (code < 32 || code === 127) return true;
|
|
2306
|
+
}
|
|
2307
|
+
return false;
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
// src/cursor/normalize.ts
|
|
2311
|
+
var CURSOR_MCP_PREFIX = "MCP:";
|
|
2312
|
+
function isCursorMcpCall(vendorTool) {
|
|
2313
|
+
return vendorTool.startsWith(CURSOR_MCP_PREFIX);
|
|
2314
|
+
}
|
|
2315
|
+
function isRecord(value) {
|
|
2316
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2317
|
+
}
|
|
2318
|
+
function nonEmpty(value) {
|
|
2319
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
2320
|
+
}
|
|
2321
|
+
function capVendorTool(s) {
|
|
2322
|
+
return s.length > TOOL_VENDOR_NAME_MAX_LENGTH ? s.slice(0, TOOL_VENDOR_NAME_MAX_LENGTH) : s;
|
|
2323
|
+
}
|
|
2324
|
+
function isAbsoluteGlob(glob) {
|
|
2325
|
+
return /^(?:[\\/]|[A-Za-z]:[\\/])/.test(glob);
|
|
2326
|
+
}
|
|
2327
|
+
function joinSearchPath(dir, glob) {
|
|
2328
|
+
return `${dir.replace(/[\\/]+$/, "")}/${glob}`;
|
|
2329
|
+
}
|
|
2330
|
+
function grepCandidates(folder, glob, tool = "Grep") {
|
|
2331
|
+
const dir = nonEmpty(folder);
|
|
2332
|
+
const pattern = nonEmpty(glob);
|
|
2333
|
+
if (pattern !== void 0 && (dir === void 0 || isAbsoluteGlob(pattern))) {
|
|
2334
|
+
return [{ tool, args: { file_path: pattern } }];
|
|
2335
|
+
}
|
|
2336
|
+
if (dir === void 0) return [{ tool, args: {} }];
|
|
2337
|
+
if (pattern === void 0) return [{ tool, args: { file_path: dir } }];
|
|
2338
|
+
return [
|
|
2339
|
+
{ tool, args: { file_path: joinSearchPath(dir, pattern) } },
|
|
2340
|
+
{ tool, args: { file_path: dir } }
|
|
2341
|
+
];
|
|
2342
|
+
}
|
|
2343
|
+
function commandCall(tool, command) {
|
|
2344
|
+
return typeof command === "string" ? { tool, args: { full_command: capToPaidDetail(command) } } : { tool, args: {} };
|
|
2345
|
+
}
|
|
2346
|
+
function fileCall(tool, path) {
|
|
2347
|
+
return typeof path === "string" ? { tool, args: { file_path: path } } : { tool, args: {} };
|
|
2348
|
+
}
|
|
2349
|
+
function writeCandidates(path) {
|
|
2350
|
+
return [fileCall("Write", path), fileCall("Edit", path)];
|
|
2351
|
+
}
|
|
2352
|
+
var TOOL_EVENTS = /* @__PURE__ */ new Set([
|
|
2353
|
+
"preToolUse",
|
|
2354
|
+
"postToolUse",
|
|
2355
|
+
"postToolUseFailure"
|
|
2356
|
+
]);
|
|
2357
|
+
var SHELL_EVENTS = /* @__PURE__ */ new Set(["beforeShellExecution", "afterShellExecution"]);
|
|
2358
|
+
var FILE_EDIT_EVENTS = /* @__PURE__ */ new Set(["afterFileEdit"]);
|
|
2359
|
+
var MCP_EVENTS = /* @__PURE__ */ new Set(["beforeMCPExecution", "afterMCPExecution"]);
|
|
2360
|
+
function cursorVendorTool(payload) {
|
|
2361
|
+
if (!isRecord(payload)) return void 0;
|
|
2362
|
+
const event = payload.hook_event_name;
|
|
2363
|
+
if (typeof event !== "string") return void 0;
|
|
2364
|
+
const toolName = typeof payload.tool_name === "string" ? payload.tool_name : "";
|
|
2365
|
+
if (TOOL_EVENTS.has(event)) return capVendorTool(toolName);
|
|
2366
|
+
if (MCP_EVENTS.has(event)) return capVendorTool(`${CURSOR_MCP_PREFIX}${toolName}`);
|
|
2367
|
+
if (SHELL_EVENTS.has(event)) return "Shell";
|
|
2368
|
+
if (FILE_EDIT_EVENTS.has(event)) return "Write";
|
|
2369
|
+
return void 0;
|
|
2370
|
+
}
|
|
2371
|
+
function toolEventCandidates(toolName, input) {
|
|
2372
|
+
if (toolName.startsWith(CURSOR_MCP_PREFIX)) return void 0;
|
|
2373
|
+
switch (toolName) {
|
|
2374
|
+
case "Shell":
|
|
2375
|
+
return [commandCall("Bash", input.command)];
|
|
2376
|
+
case "Read":
|
|
2377
|
+
case "Delete":
|
|
2378
|
+
return [fileCall(toolName, input.file_path)];
|
|
2379
|
+
case "Write":
|
|
2380
|
+
return writeCandidates(input.file_path);
|
|
2381
|
+
case "Grep":
|
|
2382
|
+
return grepCandidates(input.file_path, input.glob);
|
|
2383
|
+
}
|
|
2384
|
+
const args = {};
|
|
2385
|
+
if (typeof input.command === "string") args.full_command = capToPaidDetail(input.command);
|
|
2386
|
+
if (typeof input.file_path === "string") args.file_path = input.file_path;
|
|
2387
|
+
return [{ tool: toolName, args }];
|
|
2388
|
+
}
|
|
2389
|
+
function normalizeCursorPayload(payload) {
|
|
2390
|
+
if (!isRecord(payload) || !isCursorHookPayload(payload)) return void 0;
|
|
2391
|
+
const event = payload.hook_event_name;
|
|
2392
|
+
if (typeof event !== "string") return void 0;
|
|
2393
|
+
const vendorTool = cursorVendorTool(payload);
|
|
2394
|
+
if (vendorTool === void 0) return void 0;
|
|
2395
|
+
const correlationId = correlationIdFor(payload.tool_use_id);
|
|
2396
|
+
if (SHELL_EVENTS.has(event)) {
|
|
2397
|
+
return {
|
|
2398
|
+
event,
|
|
2399
|
+
vendorTool,
|
|
2400
|
+
candidates: [commandCall("Bash", payload.command)],
|
|
2401
|
+
correlationId
|
|
2402
|
+
};
|
|
2403
|
+
}
|
|
2404
|
+
if (MCP_EVENTS.has(event)) {
|
|
2405
|
+
const server = nonEmpty(payload.mcp_server_name);
|
|
2406
|
+
const tool = nonEmpty(payload.tool_name);
|
|
2407
|
+
if (server === void 0 || tool === void 0) return void 0;
|
|
2408
|
+
return {
|
|
2409
|
+
event,
|
|
2410
|
+
vendorTool,
|
|
2411
|
+
candidates: [
|
|
2412
|
+
{
|
|
2413
|
+
tool: `mcp__${server}__${tool}`,
|
|
2414
|
+
args: { full_command: mcpFullCommand(payload.tool_input) }
|
|
2415
|
+
}
|
|
2416
|
+
],
|
|
2417
|
+
correlationId
|
|
2418
|
+
};
|
|
2419
|
+
}
|
|
2420
|
+
if (FILE_EDIT_EVENTS.has(event)) {
|
|
2421
|
+
return {
|
|
2422
|
+
event,
|
|
2423
|
+
vendorTool,
|
|
2424
|
+
candidates: writeCandidates(payload.file_path),
|
|
2425
|
+
correlationId
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
const input = isRecord(payload.tool_input) ? payload.tool_input : {};
|
|
2429
|
+
const toolName = typeof payload.tool_name === "string" ? payload.tool_name : "";
|
|
2430
|
+
const candidates = toolEventCandidates(toolName, input);
|
|
2431
|
+
if (candidates === void 0) return void 0;
|
|
2432
|
+
return { event, vendorTool, candidates, correlationId };
|
|
2433
|
+
}
|
|
2434
|
+
function cursorCommandText(payload) {
|
|
2435
|
+
if (!isRecord(payload)) return void 0;
|
|
2436
|
+
const event = payload.hook_event_name;
|
|
2437
|
+
if (typeof event !== "string") return void 0;
|
|
2438
|
+
if (SHELL_EVENTS.has(event)) {
|
|
2439
|
+
return typeof payload.command === "string" ? payload.command : void 0;
|
|
2440
|
+
}
|
|
2441
|
+
if (MCP_EVENTS.has(event)) return mcpInputText(payload.tool_input);
|
|
2442
|
+
if (!TOOL_EVENTS.has(event)) return void 0;
|
|
2443
|
+
const toolName = typeof payload.tool_name === "string" ? payload.tool_name : "";
|
|
2444
|
+
if (toolName.startsWith(CURSOR_MCP_PREFIX)) return mcpInputText(payload.tool_input);
|
|
2445
|
+
const input = isRecord(payload.tool_input) ? payload.tool_input : {};
|
|
2446
|
+
return typeof input.command === "string" ? input.command : void 0;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// src/cursor/version.ts
|
|
2450
|
+
var ENFORCEMENT_MIN_CURSOR = "3.21.16";
|
|
2451
|
+
var STRICT_VERSION = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
2452
|
+
function parseCursorVersion(value) {
|
|
2453
|
+
if (typeof value !== "string") return void 0;
|
|
2454
|
+
const match = STRICT_VERSION.exec(value);
|
|
2455
|
+
if (match === null) return void 0;
|
|
2456
|
+
const [major, minor, patch] = [match[1], match[2], match[3]].map(Number);
|
|
2457
|
+
if (major === void 0 || minor === void 0 || patch === void 0) return void 0;
|
|
2458
|
+
if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
|
|
2459
|
+
return void 0;
|
|
2460
|
+
}
|
|
2461
|
+
return { major, minor, patch };
|
|
2462
|
+
}
|
|
2463
|
+
function compareCursorVersions(a, b) {
|
|
2464
|
+
if (a.major !== b.major) return a.major - b.major;
|
|
2465
|
+
if (a.minor !== b.minor) return a.minor - b.minor;
|
|
2466
|
+
return a.patch - b.patch;
|
|
2467
|
+
}
|
|
2468
|
+
function enforcementSupport(rawVersion) {
|
|
2469
|
+
const version = parseCursorVersion(rawVersion);
|
|
2470
|
+
if (version === void 0) return "unknown";
|
|
2471
|
+
const floor = parseCursorVersion(ENFORCEMENT_MIN_CURSOR);
|
|
2472
|
+
if (floor === void 0) return "unknown";
|
|
2473
|
+
return compareCursorVersions(version, floor) >= 0 ? "supported" : "too-old";
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
// src/pep/agent.ts
|
|
2477
|
+
var APP_NAMES = {
|
|
2478
|
+
claude: true,
|
|
2479
|
+
cursor: true,
|
|
2480
|
+
codex: true
|
|
2481
|
+
};
|
|
2482
|
+
function agentNamed(value) {
|
|
2483
|
+
return value !== void 0 && Object.hasOwn(APP_NAMES, value) ? value : void 0;
|
|
2484
|
+
}
|
|
2485
|
+
function agentFromArgv(argv) {
|
|
2486
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
2487
|
+
const arg = argv[i];
|
|
2488
|
+
if (arg === "--agent") return agentNamed(argv[i + 1]);
|
|
2489
|
+
if (arg?.startsWith("--agent=")) return agentNamed(arg.slice("--agent=".length));
|
|
2490
|
+
}
|
|
2491
|
+
return void 0;
|
|
2492
|
+
}
|
|
2493
|
+
function scopeFromArgv(argv) {
|
|
2494
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
2495
|
+
const arg = argv[i];
|
|
2496
|
+
if (arg === "--scope") return scopeNamed(argv[i + 1]);
|
|
2497
|
+
if (arg?.startsWith("--scope=")) return scopeNamed(arg.slice("--scope=".length));
|
|
2498
|
+
}
|
|
2499
|
+
return void 0;
|
|
2500
|
+
}
|
|
2501
|
+
function scopeNamed(value) {
|
|
2502
|
+
return value === "project" || value === "user" ? value : void 0;
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
// src/pep/config.ts
|
|
2506
|
+
import { homedir } from "os";
|
|
2507
|
+
import { join as join2 } from "path";
|
|
2508
|
+
|
|
2509
|
+
// src/auth/device.ts
|
|
2510
|
+
var API_BASE_SUFFIX = "/api/v1";
|
|
2511
|
+
function normalizeApiBase(value) {
|
|
2512
|
+
let url;
|
|
2513
|
+
try {
|
|
2514
|
+
url = new URL(value);
|
|
2515
|
+
} catch {
|
|
2516
|
+
throw new Error(
|
|
2517
|
+
`invalid api endpoint '${value}': must be an absolute http(s) URL (e.g. https://api.agenttrail.sh or http://localhost:3000).`
|
|
2518
|
+
);
|
|
2519
|
+
}
|
|
2520
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
2521
|
+
throw new Error(
|
|
2522
|
+
`invalid api endpoint '${value}': protocol must be http: or https: (got '${url.protocol}').`
|
|
2523
|
+
);
|
|
2524
|
+
}
|
|
2525
|
+
const base = url.href.replace(/\/$/, "");
|
|
2526
|
+
return base.endsWith(API_BASE_SUFFIX) ? base : `${base}${API_BASE_SUFFIX}`;
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
// src/pep/config.ts
|
|
2530
|
+
var ENV_PEP_ENFORCE = "AGENTTRAIL_PEP_ENFORCE";
|
|
2531
|
+
var ENV_PEP_URL = "AGENTTRAIL_PEP_URL";
|
|
2532
|
+
var ENV_PEP_HOLD_URL = "AGENTTRAIL_PEP_HOLD_URL";
|
|
2533
|
+
var ENV_PEP_SNAPSHOT_URL = "AGENTTRAIL_PEP_SNAPSHOT_URL";
|
|
2534
|
+
var ENV_PEP_TOKEN = "AGENTTRAIL_PEP_TOKEN";
|
|
2535
|
+
var ENV_PEP_TIMEOUT_MS = "AGENTTRAIL_PEP_TIMEOUT_MS";
|
|
2536
|
+
var ENV_PEP_ORG_ID = "AGENTTRAIL_PEP_ORG_ID";
|
|
2537
|
+
var ENV_PEP_SNAPSHOT_PATH = "AGENTTRAIL_PEP_SNAPSHOT_PATH";
|
|
2538
|
+
var ENV_OTEL_RESOURCE_ATTRIBUTES = "OTEL_RESOURCE_ATTRIBUTES";
|
|
2539
|
+
var RESOURCE_KEY_AGENT_ID = "agenttrail.agent.id";
|
|
2540
|
+
var RESOURCE_KEY_PROJECT_ID = "agenttrail.project.id";
|
|
2541
|
+
var DEFAULT_PEP_TIMEOUT_MS = 3e3;
|
|
2542
|
+
var PEP_WATCHDOG_MS = 6e3;
|
|
2543
|
+
var PEP_HOLD_FETCH_TIMEOUT_MS = 595e3;
|
|
2544
|
+
var PEP_HOLD_WATCHDOG_MS = 598e3;
|
|
2545
|
+
var NIL_ORG_ID = "00000000-0000-0000-0000-000000000000";
|
|
2546
|
+
var UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2547
|
+
function scopeId(value) {
|
|
2548
|
+
return value !== void 0 && UUID_SHAPE.test(value) && value !== NIL_ORG_ID ? value : void 0;
|
|
2549
|
+
}
|
|
2550
|
+
function parseResourceScope(raw) {
|
|
2551
|
+
if (!raw) return void 0;
|
|
2552
|
+
const values = /* @__PURE__ */ new Map();
|
|
2553
|
+
for (const entry of raw.split(",")) {
|
|
2554
|
+
const eq = entry.indexOf("=");
|
|
2555
|
+
if (eq < 0) continue;
|
|
2556
|
+
const key = entry.slice(0, eq).trim();
|
|
2557
|
+
if (key === "") continue;
|
|
2558
|
+
try {
|
|
2559
|
+
values.set(key, decodeURIComponent(entry.slice(eq + 1).trim()));
|
|
2560
|
+
} catch {
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
const agentId = scopeId(values.get(RESOURCE_KEY_AGENT_ID));
|
|
2564
|
+
const projectId = scopeId(values.get(RESOURCE_KEY_PROJECT_ID));
|
|
2565
|
+
if (agentId === void 0 && projectId === void 0) return void 0;
|
|
2566
|
+
return {
|
|
2567
|
+
...agentId !== void 0 ? { agent_id: agentId } : {},
|
|
2568
|
+
...projectId !== void 0 ? { project_id: projectId } : {}
|
|
2569
|
+
};
|
|
2570
|
+
}
|
|
2571
|
+
function snapshotCachePath(home = homedir()) {
|
|
2572
|
+
return join2(home, ".agenttrail", "pep-snapshot.json");
|
|
2573
|
+
}
|
|
2574
|
+
function nonEmpty2(v) {
|
|
2575
|
+
const t = v?.trim();
|
|
2576
|
+
return t && t.length > 0 ? t : void 0;
|
|
2577
|
+
}
|
|
2578
|
+
function resolvePepConfig(env) {
|
|
2579
|
+
const timeoutRaw = nonEmpty2(env[ENV_PEP_TIMEOUT_MS]);
|
|
2580
|
+
const parsed = timeoutRaw ? Number(timeoutRaw) : Number.NaN;
|
|
2581
|
+
const timeoutMs = Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : DEFAULT_PEP_TIMEOUT_MS;
|
|
2582
|
+
return {
|
|
2583
|
+
enforce: nonEmpty2(env[ENV_PEP_ENFORCE]) === "1",
|
|
2584
|
+
url: nonEmpty2(env[ENV_PEP_URL]),
|
|
2585
|
+
holdUrl: nonEmpty2(env[ENV_PEP_HOLD_URL]),
|
|
2586
|
+
snapshotUrl: nonEmpty2(env[ENV_PEP_SNAPSHOT_URL]),
|
|
2587
|
+
token: nonEmpty2(env[ENV_PEP_TOKEN]),
|
|
2588
|
+
timeoutMs,
|
|
2589
|
+
orgId: nonEmpty2(env[ENV_PEP_ORG_ID]),
|
|
2590
|
+
snapshotPath: nonEmpty2(env[ENV_PEP_SNAPSHOT_PATH]) ?? snapshotCachePath(),
|
|
2591
|
+
scope: parseResourceScope(env[ENV_OTEL_RESOURCE_ATTRIBUTES])
|
|
2592
|
+
};
|
|
2593
|
+
}
|
|
2594
|
+
function pdpEvaluateUrl(apiBase) {
|
|
2595
|
+
return `${normalizeApiBase(apiBase)}/policies/evaluate`;
|
|
2596
|
+
}
|
|
2597
|
+
function pdpHoldUrl(apiBase) {
|
|
2598
|
+
return `${normalizeApiBase(apiBase)}/policies/hold`;
|
|
2599
|
+
}
|
|
2600
|
+
var PEP_ENFORCE_SENTINEL = { [ENV_PEP_ENFORCE]: "1" };
|
|
2601
|
+
|
|
2602
|
+
// src/pep/cursor-config.ts
|
|
2603
|
+
import { realpathSync as realpathSync2 } from "fs";
|
|
2604
|
+
|
|
2605
|
+
// src/auth/credentials.ts
|
|
2606
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, unlinkSync as unlinkSync2 } from "fs";
|
|
2607
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
2608
|
+
|
|
2609
|
+
// src/setup/wire.ts
|
|
2610
|
+
import { randomBytes } from "crypto";
|
|
2611
|
+
import {
|
|
2612
|
+
chmodSync as chmodSync2,
|
|
2613
|
+
lstatSync,
|
|
2614
|
+
mkdirSync as mkdirSync2,
|
|
2615
|
+
readFileSync as readFileSync2,
|
|
2616
|
+
readlinkSync,
|
|
2617
|
+
realpathSync,
|
|
2618
|
+
renameSync as renameSync2,
|
|
2619
|
+
statSync,
|
|
2620
|
+
unlinkSync,
|
|
2621
|
+
writeFileSync as writeFileSync2
|
|
2622
|
+
} from "fs";
|
|
2623
|
+
import { dirname as dirname2, join as join3, resolve } from "path";
|
|
2624
|
+
|
|
2625
|
+
// src/auth/credentials.ts
|
|
2626
|
+
function credentialsPath(homeDir, agent = "claude") {
|
|
2627
|
+
switch (agent) {
|
|
2628
|
+
case "claude":
|
|
2629
|
+
return join4(homeDir, ".agenttrail", "credentials.json");
|
|
2630
|
+
case "cursor":
|
|
2631
|
+
return join4(homeDir, ".agenttrail", "cursor", "credentials.json");
|
|
2632
|
+
case "codex":
|
|
2633
|
+
return join4(homeDir, ".agenttrail", "codex", "credentials.json");
|
|
2634
|
+
}
|
|
2635
|
+
return noCredentialFor(agent);
|
|
2636
|
+
}
|
|
2637
|
+
function noCredentialFor(agent) {
|
|
2638
|
+
throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(agent)}.`);
|
|
2639
|
+
}
|
|
2640
|
+
function readCredentials(homeDir, io = {}, agent = "claude") {
|
|
2641
|
+
const read = io.readFile ?? ((p) => readFileSync3(p, "utf8"));
|
|
2642
|
+
try {
|
|
2643
|
+
const parsed = JSON.parse(read(credentialsPath(homeDir, agent)));
|
|
2644
|
+
if (!isCredentials(parsed)) return null;
|
|
2645
|
+
return parsed;
|
|
2646
|
+
} catch {
|
|
2647
|
+
return null;
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
function isCredentials(v) {
|
|
2651
|
+
if (typeof v !== "object" || v === null) return false;
|
|
2652
|
+
const c = v;
|
|
2653
|
+
return typeof c.refresh_token === "string" && typeof c.ingest_token === "string" && typeof c.ingest_token_expires_at === "string" && typeof c.org_id === "string" && typeof c.host === "string" && typeof c.endpoint === "string" && (c.api_endpoint === void 0 || typeof c.api_endpoint === "string");
|
|
2654
|
+
}
|
|
2655
|
+
|
|
2656
|
+
// src/cursor/paths.ts
|
|
2657
|
+
import { join as join6 } from "path";
|
|
2658
|
+
|
|
2659
|
+
// src/capture/paths.ts
|
|
2660
|
+
import { createHash as createHash2 } from "crypto";
|
|
2661
|
+
import { join as join5 } from "path";
|
|
2662
|
+
function capturePaths(home, stateDir) {
|
|
2663
|
+
const root = join5(home, ".agenttrail", stateDir);
|
|
2664
|
+
const runtime = join5(root, "runtime");
|
|
2665
|
+
return {
|
|
2666
|
+
root,
|
|
2667
|
+
credentials: join5(root, "credentials.json"),
|
|
2668
|
+
install: join5(root, "install.json"),
|
|
2669
|
+
projects: join5(root, "projects.json"),
|
|
2670
|
+
runtime,
|
|
2671
|
+
captureHook: join5(runtime, "capture-hook.mjs"),
|
|
2672
|
+
flush: join5(runtime, "flush.mjs"),
|
|
2673
|
+
queueKey: join5(root, "queue.key"),
|
|
2674
|
+
enforcement: join5(root, "enforcement.json"),
|
|
2675
|
+
pepSnapshot: join5(root, "pep-snapshot.json"),
|
|
2676
|
+
queue: join5(root, "queue"),
|
|
2677
|
+
turns: join5(root, "turns"),
|
|
2678
|
+
senderLock: join5(root, "sender.lock"),
|
|
2679
|
+
senderState: join5(root, "sender-state.json"),
|
|
2680
|
+
backfillState: join5(root, "backfill-state.json")
|
|
2681
|
+
};
|
|
2682
|
+
}
|
|
2683
|
+
function captureQueueFolder(home, stateDir, projectKey) {
|
|
2684
|
+
return join5(capturePaths(home, stateDir).queue, projectKey);
|
|
2685
|
+
}
|
|
2686
|
+
|
|
2687
|
+
// src/cursor/identity.ts
|
|
2688
|
+
var CURSOR_STATE_DIR = "cursor";
|
|
2689
|
+
|
|
2690
|
+
// src/cursor/paths.ts
|
|
2691
|
+
function cursorPaths(home) {
|
|
2692
|
+
return capturePaths(home, CURSOR_STATE_DIR);
|
|
2693
|
+
}
|
|
2694
|
+
function queueFolderFor(home, projectKey) {
|
|
2695
|
+
return captureQueueFolder(home, CURSOR_STATE_DIR, projectKey);
|
|
2696
|
+
}
|
|
2697
|
+
|
|
2698
|
+
// src/cursor/enforcement-record.ts
|
|
2699
|
+
function readEnforcementRecord(home, io = nodeCaptureFileIO) {
|
|
2700
|
+
let value;
|
|
2701
|
+
try {
|
|
2702
|
+
const path = cursorPaths(home).enforcement;
|
|
2703
|
+
if (!io.exists(path)) return void 0;
|
|
2704
|
+
value = JSON.parse(io.readFile(path).toString("utf8"));
|
|
2705
|
+
} catch {
|
|
2706
|
+
return void 0;
|
|
2707
|
+
}
|
|
2708
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
2709
|
+
const record = value;
|
|
2710
|
+
if (record.v !== 1) return void 0;
|
|
2711
|
+
if (typeof record.enabled !== "boolean" || typeof record.apiBase !== "string" || typeof record.orgId !== "string" || typeof record.agentId !== "string" || typeof record.timeoutMs !== "number" || typeof record.userScopeHandoff !== "boolean") {
|
|
2712
|
+
return void 0;
|
|
2713
|
+
}
|
|
2714
|
+
return record;
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
// src/capture/registry.ts
|
|
2718
|
+
function isRecord2(value) {
|
|
2719
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2720
|
+
}
|
|
2721
|
+
function isString(value) {
|
|
2722
|
+
return typeof value === "string" && value !== "";
|
|
2723
|
+
}
|
|
2724
|
+
function skippedRecord(key, value) {
|
|
2725
|
+
if (!isRecord2(value)) return { key };
|
|
2726
|
+
const root = isString(value.root) ? value.root : void 0;
|
|
2727
|
+
const subfolders = Array.isArray(value.subfolders) ? value.subfolders.map((sub) => isRecord2(sub) && isString(sub.path) ? sub.path : void 0).filter((path) => path !== void 0) : [];
|
|
2728
|
+
return {
|
|
2729
|
+
key,
|
|
2730
|
+
...root !== void 0 ? { root } : {},
|
|
2731
|
+
...subfolders.length > 0 ? { subfolders } : {}
|
|
2732
|
+
};
|
|
2733
|
+
}
|
|
2734
|
+
function parseRegistryText(text, isProjectRecord2) {
|
|
2735
|
+
let value;
|
|
2736
|
+
try {
|
|
2737
|
+
value = JSON.parse(text);
|
|
2738
|
+
} catch {
|
|
2739
|
+
return void 0;
|
|
2740
|
+
}
|
|
2741
|
+
if (!isRecord2(value) || value.v !== 1 || !isRecord2(value.projects)) return void 0;
|
|
2742
|
+
const projects = {};
|
|
2743
|
+
const skipped = [];
|
|
2744
|
+
for (const [key, record] of Object.entries(value.projects)) {
|
|
2745
|
+
if (isProjectRecord2(key, record)) projects[key] = record;
|
|
2746
|
+
else skipped.push(skippedRecord(key, record));
|
|
2747
|
+
}
|
|
2748
|
+
return { registry: { v: 1, projects }, skipped };
|
|
2749
|
+
}
|
|
2750
|
+
var EMPTY_REGISTRY = Object.freeze({
|
|
2751
|
+
v: 1,
|
|
2752
|
+
projects: Object.freeze({})
|
|
2753
|
+
});
|
|
2754
|
+
function readRegistryAt(path, isProjectRecord2, io = nodeCaptureFileIO) {
|
|
2755
|
+
let text;
|
|
2756
|
+
try {
|
|
2757
|
+
if (!io.exists(path)) return { kind: "missing" };
|
|
2758
|
+
text = io.readFile(path).toString("utf8");
|
|
2759
|
+
} catch {
|
|
2760
|
+
return { kind: "unreadable" };
|
|
2761
|
+
}
|
|
2762
|
+
const parsed = parseRegistryText(text, isProjectRecord2);
|
|
2763
|
+
return parsed === void 0 ? { kind: "unreadable" } : { kind: "ok", registry: parsed.registry, skipped: parsed.skipped };
|
|
2764
|
+
}
|
|
2765
|
+
function trimmed(path) {
|
|
2766
|
+
return path.length > 1 ? path.replace(/\/+$/, "") : path;
|
|
2767
|
+
}
|
|
2768
|
+
function contains(folder, candidate) {
|
|
2769
|
+
const f = trimmed(folder);
|
|
2770
|
+
const c = trimmed(candidate);
|
|
2771
|
+
return c === f || c.startsWith(f.endsWith("/") ? f : `${f}/`);
|
|
2772
|
+
}
|
|
2773
|
+
function candidatesOf(workspaceRoots, projectDirEnv) {
|
|
2774
|
+
const all = [...workspaceRoots, ...projectDirEnv !== void 0 ? [projectDirEnv] : []];
|
|
2775
|
+
return all.filter((path) => typeof path === "string" && path !== "");
|
|
2776
|
+
}
|
|
2777
|
+
function findProjectForWorkspace(registry, workspaceRoots, projectDirEnv) {
|
|
2778
|
+
const candidates = candidatesOf(workspaceRoots, projectDirEnv);
|
|
2779
|
+
let best;
|
|
2780
|
+
for (const record of Object.values(registry.projects)) {
|
|
2781
|
+
if (!candidates.some((path) => contains(record.root, path))) continue;
|
|
2782
|
+
if (best === void 0 || record.root.length > best.root.length) best = record;
|
|
2783
|
+
}
|
|
2784
|
+
return best;
|
|
2785
|
+
}
|
|
2786
|
+
function skippedRecordsForWorkspace(skipped, workspaceRoots, projectDirEnv) {
|
|
2787
|
+
const candidates = candidatesOf(workspaceRoots, projectDirEnv);
|
|
2788
|
+
return skipped.filter((record) => {
|
|
2789
|
+
const folders = [
|
|
2790
|
+
...record.root === void 0 ? [] : [record.root],
|
|
2791
|
+
...record.subfolders ?? []
|
|
2792
|
+
];
|
|
2793
|
+
return folders.some((folder) => candidates.some((path) => contains(folder, path)));
|
|
2794
|
+
});
|
|
2795
|
+
}
|
|
2796
|
+
function mostSpecificFolder(folders, workspaceRoots, projectDirEnv) {
|
|
2797
|
+
const candidates = candidatesOf(workspaceRoots, projectDirEnv);
|
|
2798
|
+
let best;
|
|
2799
|
+
for (const folder of folders) {
|
|
2800
|
+
if (!candidates.some((path) => contains(folder.path, path))) continue;
|
|
2801
|
+
if (best === void 0 || folder.path.length > best.path.length) {
|
|
2802
|
+
best = { path: folder.path, install: folder.install };
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
return best;
|
|
2806
|
+
}
|
|
2807
|
+
|
|
2808
|
+
// src/cursor/registry.ts
|
|
2809
|
+
function isRecord3(value) {
|
|
2810
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2811
|
+
}
|
|
2812
|
+
function isString2(value) {
|
|
2813
|
+
return typeof value === "string" && value !== "";
|
|
2814
|
+
}
|
|
2815
|
+
function isInstall(value) {
|
|
2816
|
+
return value === "project" || value === "user";
|
|
2817
|
+
}
|
|
2818
|
+
var PROJECT_SOURCES = /* @__PURE__ */ new Set(["flag", "agenttrail-json", "derived"]);
|
|
2819
|
+
function isSubfolder(value) {
|
|
2820
|
+
return isRecord3(value) && isString2(value.path) && isString2(value.transcriptFolder) && isInstall(value.install) && isString2(value.registeredAt);
|
|
2821
|
+
}
|
|
2822
|
+
function isProjectRecord(key, value) {
|
|
2823
|
+
if (!isRecord3(value)) return false;
|
|
2824
|
+
return value.projectKey === key && isString2(value.root) && isString2(value.transcriptFolder) && isString2(value.orgId) && isString2(value.projectSlug) && isString2(value.projectId) && PROJECT_SOURCES.has(value.projectSource) && typeof value.projectLabel === "string" && (value.developerId === void 0 || typeof value.developerId === "string") && typeof value.captureContent === "boolean" && isInstall(value.install) && isString2(value.registeredAt) && (value.subfolders === void 0 || Array.isArray(value.subfolders) && value.subfolders.every(isSubfolder));
|
|
2825
|
+
}
|
|
2826
|
+
function readRegistry(home, io = nodeCaptureFileIO) {
|
|
2827
|
+
return readRegistryAt(cursorPaths(home).projects, isProjectRecord, io);
|
|
2828
|
+
}
|
|
2829
|
+
function findProjectForWorkspace2(registry, workspaceRoots, projectDirEnv) {
|
|
2830
|
+
return findProjectForWorkspace(registry, workspaceRoots, projectDirEnv);
|
|
2831
|
+
}
|
|
2832
|
+
function folderForWorkspace(record, workspaceRoots, projectDirEnv) {
|
|
2833
|
+
return mostSpecificFolder(
|
|
2834
|
+
[
|
|
2835
|
+
{ path: record.root, install: record.install },
|
|
2836
|
+
...(record.subfolders ?? []).map((sub) => ({ path: sub.path, install: sub.install }))
|
|
2837
|
+
],
|
|
2838
|
+
workspaceRoots,
|
|
2839
|
+
projectDirEnv
|
|
2840
|
+
);
|
|
2841
|
+
}
|
|
2842
|
+
|
|
2843
|
+
// src/pep/cursor-config.ts
|
|
2844
|
+
var CURSOR_VENDOR_SLUG = "cursor";
|
|
2845
|
+
function resolveWorkspacePath(path, realpath = realpathSync2.native) {
|
|
2846
|
+
try {
|
|
2847
|
+
return realpath(path);
|
|
2848
|
+
} catch {
|
|
2849
|
+
return path;
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
function lookupCursorWorkspace(query) {
|
|
2853
|
+
const read = readRegistry(query.home, query.io ?? nodeCaptureFileIO);
|
|
2854
|
+
if (read.kind !== "ok") return { kind: "registry-unreadable", reason: read.kind };
|
|
2855
|
+
const resolve2 = (path) => resolveWorkspacePath(path, query.realpath);
|
|
2856
|
+
const roots = query.workspaceRoots.filter((path) => path !== "").map(resolve2);
|
|
2857
|
+
const projectDir = query.projectDirEnv === void 0 ? void 0 : resolve2(query.projectDirEnv);
|
|
2858
|
+
const record = findProjectForWorkspace2(read.registry, roots, projectDir);
|
|
2859
|
+
if (record === void 0) {
|
|
2860
|
+
const damaged = skippedRecordsForWorkspace(read.skipped, roots, projectDir);
|
|
2861
|
+
if (damaged.length > 0) return { kind: "record-damaged", skipped: damaged };
|
|
2862
|
+
return { kind: "not-registered" };
|
|
2863
|
+
}
|
|
2864
|
+
const folder = folderForWorkspace(record, roots, projectDir);
|
|
2865
|
+
if (folder === void 0) {
|
|
2866
|
+
return {
|
|
2867
|
+
kind: "record-damaged",
|
|
2868
|
+
skipped: [{ key: record.projectKey, root: record.root }]
|
|
2869
|
+
};
|
|
2870
|
+
}
|
|
2871
|
+
return { kind: "ok", record, folder };
|
|
2872
|
+
}
|
|
2873
|
+
function entryOwnsFolder(folder, launchScope) {
|
|
2874
|
+
return folder.install === launchScope;
|
|
2875
|
+
}
|
|
2876
|
+
function cursorScopeFor(record, agentId) {
|
|
2877
|
+
return {
|
|
2878
|
+
agent_id: agentId,
|
|
2879
|
+
project_id: record.projectId,
|
|
2880
|
+
vendor: CURSOR_VENDOR_SLUG
|
|
2881
|
+
};
|
|
2882
|
+
}
|
|
2883
|
+
function resolveCursorPepConfig(home, io, credentialsIO) {
|
|
2884
|
+
const record = readEnforcementRecord(home, io ?? nodeCaptureFileIO);
|
|
2885
|
+
if (record === void 0 || !record.enabled) return void 0;
|
|
2886
|
+
const creds = readCredentials(home, credentialsIO, "cursor");
|
|
2887
|
+
const token = creds?.ingest_token;
|
|
2888
|
+
if (creds === void 0 || typeof token !== "string" || token === "") return void 0;
|
|
2889
|
+
const apiBase = record.apiBase;
|
|
2890
|
+
return {
|
|
2891
|
+
url: pdpEvaluateUrl(apiBase),
|
|
2892
|
+
holdUrl: pdpHoldUrl(apiBase),
|
|
2893
|
+
token,
|
|
2894
|
+
snapshotPath: cursorPaths(home).pepSnapshot,
|
|
2895
|
+
orgId: record.orgId,
|
|
2896
|
+
agentId: record.agentId,
|
|
2897
|
+
timeoutMs: record.timeoutMs,
|
|
2898
|
+
userScopeHandoff: record.userScopeHandoff
|
|
2899
|
+
};
|
|
2900
|
+
}
|
|
2901
|
+
|
|
2902
|
+
// src/pep/cursor-emit.ts
|
|
2903
|
+
var CURSOR_NO_OPINION = "{}";
|
|
2904
|
+
var CURSOR_CRASH_LINE = "AgentTrail enforcement failed; failing closed.";
|
|
2905
|
+
var CURSOR_SHELL_TOOL = "Shell";
|
|
2906
|
+
function permission(kind, message) {
|
|
2907
|
+
return JSON.stringify({ permission: kind, user_message: message, agent_message: message });
|
|
2908
|
+
}
|
|
2909
|
+
function cursorApprovalDeniedMessage(message) {
|
|
2910
|
+
return `${message} Cursor cannot ask for approval on this tool \u2014 ask a reviewer to approve it, then retry.`;
|
|
2911
|
+
}
|
|
2912
|
+
function buildCursorAnswer(input) {
|
|
2913
|
+
const { event, tool, outcome } = input;
|
|
2914
|
+
if (event === "beforeShellExecution") {
|
|
2915
|
+
if (outcome.kind === "none") return CURSOR_NO_OPINION;
|
|
2916
|
+
return permission("ask", outcome.message);
|
|
2917
|
+
}
|
|
2918
|
+
if (outcome.kind === "deny") return permission("deny", outcome.message);
|
|
2919
|
+
if (outcome.kind === "none") return CURSOR_NO_OPINION;
|
|
2920
|
+
if (tool === CURSOR_SHELL_TOOL && input.handoff === true) return CURSOR_NO_OPINION;
|
|
2921
|
+
return permission("deny", cursorApprovalDeniedMessage(outcome.message));
|
|
2922
|
+
}
|
|
2923
|
+
function answerBlocks(answer) {
|
|
2924
|
+
try {
|
|
2925
|
+
return JSON.parse(answer).permission === "deny";
|
|
2926
|
+
} catch {
|
|
2927
|
+
return false;
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
function combineCandidateVerdicts(perCandidate) {
|
|
2931
|
+
const union = perCandidate.flat();
|
|
2932
|
+
const { verdict, policyId } = strongestVerdict(union);
|
|
2933
|
+
if (policyId === null) return { verdict, policyId: null, candidateIndex: null };
|
|
2934
|
+
const candidateIndex = perCandidate.findIndex(
|
|
2935
|
+
(matches) => matches.some((match) => match.policyId === policyId)
|
|
2936
|
+
);
|
|
2937
|
+
return { verdict, policyId, candidateIndex: candidateIndex === -1 ? null : candidateIndex };
|
|
2938
|
+
}
|
|
2939
|
+
function createRealCursorEmitter() {
|
|
2940
|
+
let done = false;
|
|
2941
|
+
return {
|
|
2942
|
+
emitAnswer(answer) {
|
|
2943
|
+
if (done) return;
|
|
2944
|
+
done = true;
|
|
2945
|
+
process.stdout.write(answer, () => process.exit(0));
|
|
2946
|
+
const t = setTimeout(() => {
|
|
2947
|
+
process.stderr.write(`${CURSOR_CRASH_LINE}
|
|
2948
|
+
`);
|
|
2949
|
+
process.exit(2);
|
|
2950
|
+
}, 1e3);
|
|
2951
|
+
t.unref?.();
|
|
2952
|
+
},
|
|
2953
|
+
emitCrash() {
|
|
2954
|
+
if (done) return;
|
|
2955
|
+
done = true;
|
|
2956
|
+
process.stderr.write(`${CURSOR_CRASH_LINE}
|
|
2957
|
+
`);
|
|
2958
|
+
process.exit(2);
|
|
2959
|
+
}
|
|
2960
|
+
};
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
// src/pep/pdp-client.ts
|
|
2964
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
2965
|
+
var PdpUnreachableError = class extends Error {
|
|
2966
|
+
constructor(reason) {
|
|
2967
|
+
super(`PDP unreachable: ${reason}`);
|
|
2968
|
+
this.name = "PdpUnreachableError";
|
|
2969
|
+
}
|
|
2970
|
+
};
|
|
2971
|
+
var API_TIER_REFUSAL_MESSAGE = /^This feature requires the (Pro|Team|Business|Enterprise) plan or higher\.$/;
|
|
2972
|
+
async function isApiTierRefusal(res) {
|
|
2973
|
+
let body;
|
|
2974
|
+
try {
|
|
2975
|
+
body = JSON.parse(await res.text());
|
|
2976
|
+
} catch {
|
|
2977
|
+
return false;
|
|
2978
|
+
}
|
|
2979
|
+
if (typeof body !== "object" || body === null) return false;
|
|
2980
|
+
const error = body.error;
|
|
2981
|
+
if (typeof error !== "object" || error === null) return false;
|
|
2982
|
+
const { code, message } = error;
|
|
2983
|
+
return code === "forbidden" && typeof message === "string" && API_TIER_REFUSAL_MESSAGE.test(message);
|
|
2984
|
+
}
|
|
2985
|
+
function foreign403(what) {
|
|
2986
|
+
return new PdpUnreachableError(
|
|
2987
|
+
`${what} 403 did not come from the AgentTrail API (no tier-refusal body) \u2014 most likely a gateway/WAF block; failing closed`
|
|
2988
|
+
);
|
|
2989
|
+
}
|
|
2990
|
+
async function boundedFetch(fetchFn, url, init, timeoutMs) {
|
|
2991
|
+
const controller = new AbortController();
|
|
2992
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
2993
|
+
try {
|
|
2994
|
+
return await fetchFn(url, { ...init, signal: controller.signal });
|
|
2995
|
+
} catch (err) {
|
|
2996
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2997
|
+
throw new PdpUnreachableError(msg);
|
|
2998
|
+
} finally {
|
|
2999
|
+
clearTimeout(timer);
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
async function evaluateViaPdp(args, fetchFn) {
|
|
3003
|
+
const res = await boundedFetch(
|
|
3004
|
+
fetchFn,
|
|
3005
|
+
args.url,
|
|
3006
|
+
{
|
|
3007
|
+
method: "POST",
|
|
3008
|
+
headers: {
|
|
3009
|
+
"content-type": "application/json",
|
|
3010
|
+
authorization: `Bearer ${args.token}`
|
|
3011
|
+
},
|
|
3012
|
+
body: JSON.stringify(args.request)
|
|
3013
|
+
},
|
|
3014
|
+
args.timeoutMs
|
|
3015
|
+
);
|
|
3016
|
+
if (res.status === 200) {
|
|
3017
|
+
let parsed;
|
|
3018
|
+
try {
|
|
3019
|
+
parsed = await res.json();
|
|
3020
|
+
} catch {
|
|
3021
|
+
throw new PdpUnreachableError("200 with unparseable JSON body");
|
|
3022
|
+
}
|
|
3023
|
+
if (!isEvaluateResponse(parsed)) {
|
|
3024
|
+
throw new PdpUnreachableError("200 with malformed PolicyEvaluateResponse");
|
|
3025
|
+
}
|
|
3026
|
+
return { kind: "ok", response: parsed };
|
|
3027
|
+
}
|
|
3028
|
+
if (res.status === 403) {
|
|
3029
|
+
if (await isApiTierRefusal(res)) return { kind: "tier-disabled" };
|
|
3030
|
+
throw foreign403("evaluate");
|
|
3031
|
+
}
|
|
3032
|
+
if (res.status === 401) return { kind: "unauthorized" };
|
|
3033
|
+
throw new PdpUnreachableError(`unexpected status ${res.status}`);
|
|
3034
|
+
}
|
|
3035
|
+
async function holdForApproval(args, fetchFn) {
|
|
3036
|
+
const res = await boundedFetch(
|
|
3037
|
+
fetchFn,
|
|
3038
|
+
args.url,
|
|
3039
|
+
{
|
|
3040
|
+
method: "POST",
|
|
3041
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${args.token}` },
|
|
3042
|
+
body: JSON.stringify({
|
|
3043
|
+
...args.request,
|
|
3044
|
+
correlation_id: args.correlationId,
|
|
3045
|
+
// Omitted entirely when the caller sends none, so the Claude Code path's request
|
|
3046
|
+
// body is byte-identical to what it was before Cursor needed the field.
|
|
3047
|
+
...args.maxWindowSeconds === void 0 ? {} : { max_window_seconds: args.maxWindowSeconds }
|
|
3048
|
+
})
|
|
3049
|
+
},
|
|
3050
|
+
args.timeoutMs
|
|
3051
|
+
);
|
|
3052
|
+
if (res.status === 403) {
|
|
3053
|
+
if (await isApiTierRefusal(res)) return "tier-disabled";
|
|
3054
|
+
throw foreign403("hold");
|
|
3055
|
+
}
|
|
3056
|
+
if (res.status !== 200) throw new PdpUnreachableError(`hold status ${res.status}`);
|
|
3057
|
+
let parsed;
|
|
3058
|
+
try {
|
|
3059
|
+
parsed = JSON.parse(await res.text());
|
|
3060
|
+
} catch {
|
|
3061
|
+
throw new PdpUnreachableError("hold 200 with unparseable body");
|
|
3062
|
+
}
|
|
3063
|
+
const outcome = parsed.outcome;
|
|
3064
|
+
if (outcome === "approved" || outcome === "denied" || outcome === "unanswered") {
|
|
3065
|
+
return outcome;
|
|
3066
|
+
}
|
|
3067
|
+
throw new PdpUnreachableError("hold 200 with malformed outcome");
|
|
3068
|
+
}
|
|
3069
|
+
function readCachedSnapshot(path, io = {}) {
|
|
3070
|
+
const read = io.readFile ?? ((p) => readFileSync4(p, "utf8"));
|
|
3071
|
+
try {
|
|
3072
|
+
const parsed = JSON.parse(read(path));
|
|
3073
|
+
return isCompiledSnapshot(parsed) ? parsed : null;
|
|
3074
|
+
} catch {
|
|
3075
|
+
return null;
|
|
3076
|
+
}
|
|
3077
|
+
}
|
|
3078
|
+
function isEvaluateResponse(v) {
|
|
3079
|
+
if (typeof v !== "object" || v === null) return false;
|
|
3080
|
+
const o = v;
|
|
3081
|
+
return (o.verdict === "allow" || o.verdict === "deny" || o.verdict === "require_approval") && typeof o.reason === "string" && Array.isArray(o.matched_policies) && (o.fail_mode === "closed" || o.fail_mode === "open");
|
|
3082
|
+
}
|
|
3083
|
+
function isCompiledSnapshot(v) {
|
|
3084
|
+
if (typeof v !== "object" || v === null) return false;
|
|
3085
|
+
const o = v;
|
|
3086
|
+
return typeof o.version === "string" && (o.fail_mode === "closed" || o.fail_mode === "open") && Array.isArray(o.policies);
|
|
3087
|
+
}
|
|
3088
|
+
|
|
3089
|
+
// src/pep/cursor-hold.ts
|
|
3090
|
+
function holdWindowSeconds(elapsedMs) {
|
|
3091
|
+
const spent = Math.floor(Math.max(0, elapsedMs) / 1e3);
|
|
3092
|
+
return Math.min(
|
|
3093
|
+
POLICY_HOLD_MAX_WINDOW_SECONDS,
|
|
3094
|
+
Math.max(1, POLICY_HOLD_MAX_WINDOW_SECONDS - spent)
|
|
3095
|
+
);
|
|
3096
|
+
}
|
|
3097
|
+
function holdWatchdogDelayMs(elapsedMs) {
|
|
3098
|
+
return Math.max(1, PEP_HOLD_WATCHDOG_MS - Math.max(0, elapsedMs));
|
|
3099
|
+
}
|
|
3100
|
+
async function holdCursorApproval(input) {
|
|
3101
|
+
const { cfg, correlationId } = input;
|
|
3102
|
+
if (!cfg.holdUrl || !cfg.token || correlationId === null || correlationId === "") {
|
|
3103
|
+
return { outcome: "no-correlation", windowSeconds: null, correlationId: null };
|
|
3104
|
+
}
|
|
3105
|
+
const windowSeconds = holdWindowSeconds(input.elapsedMs);
|
|
3106
|
+
input.extendDeadline?.(holdWatchdogDelayMs(input.elapsedMs));
|
|
3107
|
+
try {
|
|
3108
|
+
const outcome = await holdForApproval(
|
|
3109
|
+
{
|
|
3110
|
+
url: cfg.holdUrl,
|
|
3111
|
+
token: cfg.token,
|
|
3112
|
+
request: input.request,
|
|
3113
|
+
correlationId,
|
|
3114
|
+
timeoutMs: PEP_HOLD_FETCH_TIMEOUT_MS,
|
|
3115
|
+
maxWindowSeconds: windowSeconds
|
|
3116
|
+
},
|
|
3117
|
+
input.fetchFn
|
|
3118
|
+
);
|
|
3119
|
+
if (outcome === "tier-disabled") {
|
|
3120
|
+
return { outcome: "forbidden", windowSeconds, correlationId };
|
|
3121
|
+
}
|
|
3122
|
+
return { outcome, windowSeconds, correlationId };
|
|
3123
|
+
} catch (err) {
|
|
3124
|
+
if (err instanceof PdpUnreachableError) {
|
|
3125
|
+
return { outcome: "unreachable", windowSeconds, correlationId };
|
|
3126
|
+
}
|
|
3127
|
+
throw err;
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
// src/capture/args-hash.ts
|
|
3132
|
+
import { createHmac, randomBytes as randomBytes2 } from "crypto";
|
|
3133
|
+
var ARGS_HASH_PREFIX = "h1:";
|
|
3134
|
+
var QUEUE_KEY_BYTES = 32;
|
|
3135
|
+
var ARGS_HASH_HEX = 32;
|
|
3136
|
+
function argsHashFor(args, key) {
|
|
3137
|
+
const digest = createHmac("sha256", key).update(sortedJson(args), "utf8").digest("hex");
|
|
3138
|
+
return `${ARGS_HASH_PREFIX}${digest.slice(0, ARGS_HASH_HEX)}`;
|
|
3139
|
+
}
|
|
3140
|
+
function readCaptureQueueKey(home, stateDir, io = nodeCaptureFileIO) {
|
|
3141
|
+
let bytes;
|
|
3142
|
+
try {
|
|
3143
|
+
bytes = io.readFile(capturePaths(home, stateDir).queueKey);
|
|
3144
|
+
} catch {
|
|
3145
|
+
return void 0;
|
|
3146
|
+
}
|
|
3147
|
+
return bytes.length === QUEUE_KEY_BYTES ? new Uint8Array(bytes) : void 0;
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
// src/cursor/args-hash.ts
|
|
3151
|
+
function argsHashForCall(vendorTool, firstCandidateArgs, toolInput, key) {
|
|
3152
|
+
const args = isCursorMcpCall(vendorTool) ? { full_command: serializeMcpInput(toolInput) } : firstCandidateArgs;
|
|
3153
|
+
return argsHashFor(args, key);
|
|
3154
|
+
}
|
|
3155
|
+
function readQueueKey(home, io = nodeCaptureFileIO) {
|
|
3156
|
+
return readCaptureQueueKey(home, CURSOR_STATE_DIR, io);
|
|
3157
|
+
}
|
|
3158
|
+
|
|
3159
|
+
// src/backfill/content.ts
|
|
3160
|
+
var CONTENT_KEY_USER_PROMPT = "user_prompt";
|
|
3161
|
+
var CONTENT_KEY_COMPLETION = "gen_ai.completion";
|
|
3162
|
+
var CONTENT_KEY_TOOL_COMMAND = "full_command";
|
|
3163
|
+
var CONTENT_KEY_TOOL_FILE = "file_path";
|
|
3164
|
+
var CONTENT_KEY_TOOL_RESULT = "gen_ai.tool.call.result";
|
|
3165
|
+
var CONTENT_KEYS = /* @__PURE__ */ new Set([
|
|
3166
|
+
CONTENT_KEY_USER_PROMPT,
|
|
3167
|
+
CONTENT_KEY_COMPLETION,
|
|
3168
|
+
CONTENT_KEY_TOOL_COMMAND,
|
|
3169
|
+
CONTENT_KEY_TOOL_FILE,
|
|
3170
|
+
CONTENT_KEY_TOOL_RESULT
|
|
3171
|
+
]);
|
|
3172
|
+
|
|
3173
|
+
// ../shared/src/scrubbing-patterns.ts
|
|
3174
|
+
function redacted(kind, hint) {
|
|
3175
|
+
return hint ? `[REDACTED:${kind}:${hint}]` : `[REDACTED:${kind}]`;
|
|
3176
|
+
}
|
|
3177
|
+
var LEAD = String.raw`(?:\b|(?<=\\[nrtfb])|(?<=\\u[0-9A-Fa-f]{4})|(?<=\x1b\[[0-9;:?]{0,32}[@-~])|(?<=\\(?:u001[bB]|x1[bB]|033)\[[0-9;:?]{0,32}[@-~])|(?<=\x1b\([0-9A-Za-z])|(?<=\\(?:u001[bB]|x1[bB]|033)\([0-9A-Za-z]))`;
|
|
3178
|
+
function led(source, flags) {
|
|
3179
|
+
return new RegExp(`${LEAD}${source}`, flags);
|
|
3180
|
+
}
|
|
3181
|
+
var AWS_ACCESS_KEY_ID = led(
|
|
3182
|
+
String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,
|
|
3183
|
+
"g"
|
|
3184
|
+
);
|
|
3185
|
+
var AWS_SECRET_ACCESS_KEY = new RegExp(
|
|
3186
|
+
`((?:aws[_-]?)?secret[_-]?access[_-]?key)(["']?\\s*[=:]\\s*["']?)((?![0-9a-f]{40}(?![A-Za-z0-9/+=]))[A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])`,
|
|
3187
|
+
"gi"
|
|
3188
|
+
);
|
|
3189
|
+
var OPENAI_KEY = led(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`, "g");
|
|
3190
|
+
var GITHUB_TOKEN = led(
|
|
3191
|
+
String.raw`(?:(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,255}\b|github_pat_[A-Za-z0-9_]{22,255}\b)`,
|
|
3192
|
+
"g"
|
|
3193
|
+
);
|
|
3194
|
+
var SLACK_TOKEN = led(String.raw`xox[baprs]-[A-Za-z0-9-]{10,255}\b`, "g");
|
|
3195
|
+
var BEARER_TOKEN = led(String.raw`Bearer\s+([A-Za-z0-9._~+/-]{8,})=*`, "gi");
|
|
3196
|
+
var CONNECTION_STRING = led(
|
|
3197
|
+
String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,
|
|
3198
|
+
"gi"
|
|
3199
|
+
);
|
|
3200
|
+
var JWT = led(String.raw`eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b`, "g");
|
|
3201
|
+
var PEM_PRIVATE_KEY = /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]{0,8192}?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g;
|
|
3202
|
+
var BASIC_AUTH_URL = led(String.raw`(https?|ftp|wss?):\/\/[^\s/@:]+:[^\s]*@(?=[^\s/:@])`, "gi");
|
|
3203
|
+
var ENV_SECRET_ASSIGNMENT = (() => {
|
|
3204
|
+
const sentinel2 = String.fromCharCode(57344);
|
|
3205
|
+
const key = "([A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API[_-]?KEY|APIKEY|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|CLIENT[_-]?SECRET|AUTH[_-]?TOKEN|CREDENTIALS?)[A-Z0-9_]*)";
|
|
3206
|
+
const value = `(?:(")([^"${sentinel2}]{4,})"|(')([^'${sentinel2}]{4,})'|([^\\s"',;${sentinel2}]{4,}))`;
|
|
3207
|
+
return new RegExp(`${LEAD}${key}(["']?\\s*[=:]\\s*)${value}`, "gi");
|
|
3208
|
+
})();
|
|
3209
|
+
var EMAIL = led(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`, "g");
|
|
3210
|
+
var SSN = led(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`, "g");
|
|
3211
|
+
var CREDIT_CARD = led(String.raw`(?:\d{13,19}\b|\d{3,6}([ -])\d{3,6}(?:\1\d{3,6}){1,3}\b)`, "g");
|
|
3212
|
+
var PHONE = led(
|
|
3213
|
+
String.raw`(?:\+?\d{1,3}[ .-]?)?(?:\(\d{2,4}\)[ .-]?)?\d{2,4}[ .-]\d{2,4}[ .-]\d{2,4}\b`,
|
|
3214
|
+
"g"
|
|
3215
|
+
);
|
|
3216
|
+
var SCRUB_PATTERNS = [
|
|
3217
|
+
{
|
|
3218
|
+
id: "aws-access-key-id",
|
|
3219
|
+
kind: "secret",
|
|
3220
|
+
category: "aws",
|
|
3221
|
+
severity: "high",
|
|
3222
|
+
tier: "permissive",
|
|
3223
|
+
regex: AWS_ACCESS_KEY_ID,
|
|
3224
|
+
// No hint: the last-4 of the id fingerprints the key, so nothing of it is disclosed.
|
|
3225
|
+
placeholder: () => redacted("secret:aws")
|
|
3226
|
+
},
|
|
3227
|
+
{
|
|
3228
|
+
id: "pem-private-key",
|
|
3229
|
+
kind: "secret",
|
|
3230
|
+
category: "private-key",
|
|
3231
|
+
severity: "high",
|
|
3232
|
+
tier: "permissive",
|
|
3233
|
+
regex: PEM_PRIVATE_KEY,
|
|
3234
|
+
placeholder: () => redacted("secret:private-key")
|
|
3235
|
+
},
|
|
3236
|
+
{
|
|
3237
|
+
id: "jwt",
|
|
3238
|
+
kind: "secret",
|
|
3239
|
+
category: "jwt",
|
|
3240
|
+
severity: "high",
|
|
3241
|
+
tier: "permissive",
|
|
3242
|
+
regex: JWT,
|
|
3243
|
+
placeholder: () => redacted("secret:jwt", "claims-not-stored")
|
|
3244
|
+
},
|
|
3245
|
+
{
|
|
3246
|
+
id: "github-token",
|
|
3247
|
+
kind: "secret",
|
|
3248
|
+
category: "token",
|
|
3249
|
+
severity: "high",
|
|
3250
|
+
tier: "permissive",
|
|
3251
|
+
regex: GITHUB_TOKEN,
|
|
3252
|
+
placeholder: () => redacted("secret:github")
|
|
3253
|
+
},
|
|
3254
|
+
{
|
|
3255
|
+
id: "slack-token",
|
|
3256
|
+
kind: "secret",
|
|
3257
|
+
category: "token",
|
|
3258
|
+
severity: "high",
|
|
3259
|
+
tier: "permissive",
|
|
3260
|
+
regex: SLACK_TOKEN,
|
|
3261
|
+
placeholder: () => redacted("secret:slack")
|
|
3262
|
+
},
|
|
3263
|
+
{
|
|
3264
|
+
id: "openai-key",
|
|
3265
|
+
kind: "secret",
|
|
3266
|
+
category: "token",
|
|
3267
|
+
severity: "high",
|
|
3268
|
+
tier: "permissive",
|
|
3269
|
+
regex: OPENAI_KEY,
|
|
3270
|
+
placeholder: () => redacted("secret:api-key")
|
|
3271
|
+
},
|
|
3272
|
+
{
|
|
3273
|
+
id: "connection-string",
|
|
3274
|
+
kind: "secret",
|
|
3275
|
+
category: "connection-string",
|
|
3276
|
+
severity: "high",
|
|
3277
|
+
tier: "permissive",
|
|
3278
|
+
regex: CONNECTION_STRING,
|
|
3279
|
+
// No hint: the host is captured (group 2) only to anchor the password class to the
|
|
3280
|
+
// last `@`; it is a real hostname and is not echoed into the placeholder.
|
|
3281
|
+
placeholder: () => redacted("secret:connection-string")
|
|
3282
|
+
},
|
|
3283
|
+
{
|
|
3284
|
+
id: "basic-auth-url",
|
|
3285
|
+
kind: "secret",
|
|
3286
|
+
category: "basic-auth",
|
|
3287
|
+
severity: "high",
|
|
3288
|
+
tier: "permissive",
|
|
3289
|
+
regex: BASIC_AUTH_URL,
|
|
3290
|
+
// Keep the scheme so the URL stays recognizable; redact user:pass@.
|
|
3291
|
+
placeholder: (g) => `${g[1].toLowerCase()}://${redacted("secret:basic-auth")}@`
|
|
3292
|
+
},
|
|
3293
|
+
{
|
|
3294
|
+
id: "bearer-token",
|
|
3295
|
+
kind: "secret",
|
|
3296
|
+
category: "token",
|
|
3297
|
+
severity: "medium",
|
|
3298
|
+
tier: "permissive",
|
|
3299
|
+
regex: BEARER_TOKEN,
|
|
3300
|
+
placeholder: () => `Bearer ${redacted("secret:bearer")}`
|
|
3301
|
+
},
|
|
3302
|
+
{
|
|
3303
|
+
id: "aws-secret-access-key",
|
|
3304
|
+
kind: "secret",
|
|
3305
|
+
category: "aws",
|
|
3306
|
+
severity: "medium",
|
|
3307
|
+
tier: "standard",
|
|
3308
|
+
regex: AWS_SECRET_ACCESS_KEY,
|
|
3309
|
+
// Preserve the key name (group 1) + the original separator (group 2, incl. the
|
|
3310
|
+
// value's opening quote); redact only the 40-char value (group 3). TEC-904:
|
|
3311
|
+
// emitting g[2] instead of a hard-coded `=` keeps `key: "val"` from being
|
|
3312
|
+
// rewritten to `key="val` (dangling quote) and preserves `=`-form output.
|
|
3313
|
+
placeholder: (g) => `${g[1]}${g[2]}${redacted("secret:aws-secret")}`
|
|
3314
|
+
},
|
|
3315
|
+
{
|
|
3316
|
+
id: "env-secret",
|
|
3317
|
+
kind: "secret",
|
|
3318
|
+
category: "env-secret",
|
|
3319
|
+
severity: "medium",
|
|
3320
|
+
tier: "standard",
|
|
3321
|
+
regex: ENV_SECRET_ASSIGNMENT,
|
|
3322
|
+
// Preserve the key name (group 1) + the original separator (group 2); redact
|
|
3323
|
+
// only the value (group 4/6/7). TEC-904: emitting g[2] instead of a hard-coded
|
|
3324
|
+
// `=` keeps `key: value` from being rewritten to `key=value`.
|
|
3325
|
+
// TEC-534: the match also consumes the value's quotes, so re-emit them around
|
|
3326
|
+
// the placeholder — g[3]/g[5] is the opening quote for the double-/single-
|
|
3327
|
+
// quoted branch, and empty for an unquoted value. Without this the output is
|
|
3328
|
+
// not valid JSON or YAML (see the exact-output tests).
|
|
3329
|
+
placeholder: (g) => {
|
|
3330
|
+
const quote = g[3] ?? g[5] ?? "";
|
|
3331
|
+
return `${g[1]}${g[2]}${quote}${redacted("secret:env")}${quote}`;
|
|
3332
|
+
}
|
|
3333
|
+
},
|
|
3334
|
+
{
|
|
3335
|
+
id: "email",
|
|
3336
|
+
kind: "pii",
|
|
3337
|
+
category: "email",
|
|
3338
|
+
severity: "low",
|
|
3339
|
+
tier: "standard",
|
|
3340
|
+
regex: EMAIL,
|
|
3341
|
+
placeholder: () => redacted("pii:email")
|
|
3342
|
+
},
|
|
3343
|
+
{
|
|
3344
|
+
id: "ssn",
|
|
3345
|
+
kind: "pii",
|
|
3346
|
+
category: "ssn",
|
|
3347
|
+
severity: "high",
|
|
3348
|
+
tier: "standard",
|
|
3349
|
+
regex: SSN,
|
|
3350
|
+
placeholder: () => redacted("pii:ssn")
|
|
3351
|
+
},
|
|
3352
|
+
{
|
|
3353
|
+
id: "credit-card",
|
|
3354
|
+
kind: "pii",
|
|
3355
|
+
category: "credit-card",
|
|
3356
|
+
severity: "high",
|
|
3357
|
+
tier: "standard",
|
|
3358
|
+
regex: CREDIT_CARD,
|
|
3359
|
+
placeholder: () => redacted("pii:credit-card")
|
|
3360
|
+
},
|
|
3361
|
+
{
|
|
3362
|
+
id: "phone",
|
|
3363
|
+
kind: "pii",
|
|
3364
|
+
category: "phone",
|
|
3365
|
+
severity: "low",
|
|
3366
|
+
tier: "strict",
|
|
3367
|
+
regex: PHONE,
|
|
3368
|
+
placeholder: () => redacted("pii:phone")
|
|
3369
|
+
}
|
|
3370
|
+
];
|
|
3371
|
+
var LUHN_VALIDATED_IDS = /* @__PURE__ */ new Set(["credit-card"]);
|
|
3372
|
+
function passesLuhn(candidate) {
|
|
3373
|
+
const digits = candidate.replace(/\D/g, "");
|
|
3374
|
+
if (digits.length < 13 || digits.length > 19) return false;
|
|
3375
|
+
let sum = 0;
|
|
3376
|
+
let double = false;
|
|
3377
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
3378
|
+
let d = digits.charCodeAt(i) - 48;
|
|
3379
|
+
if (double) {
|
|
3380
|
+
d *= 2;
|
|
3381
|
+
if (d > 9) d -= 9;
|
|
3382
|
+
}
|
|
3383
|
+
sum += d;
|
|
3384
|
+
double = !double;
|
|
3385
|
+
}
|
|
3386
|
+
return sum % 10 === 0;
|
|
3387
|
+
}
|
|
3388
|
+
|
|
3389
|
+
// ../shared/src/scrubber.ts
|
|
3390
|
+
var MODE_TIERS = {
|
|
3391
|
+
permissive: /* @__PURE__ */ new Set(["permissive"]),
|
|
3392
|
+
standard: /* @__PURE__ */ new Set(["permissive", "standard"]),
|
|
3393
|
+
strict: /* @__PURE__ */ new Set(["permissive", "standard", "strict"])
|
|
3394
|
+
};
|
|
3395
|
+
var SENTINEL_CHAR = String.fromCharCode(57344);
|
|
3396
|
+
var SENTINEL_RE = new RegExp(`${SENTINEL_CHAR}(\\d+)${SENTINEL_CHAR}`, "g");
|
|
3397
|
+
function sentinel(index) {
|
|
3398
|
+
return `${SENTINEL_CHAR}${index}${SENTINEL_CHAR}`;
|
|
3399
|
+
}
|
|
3400
|
+
function resolveMode(mode, enablePhone = false) {
|
|
3401
|
+
if (mode === "off") return [];
|
|
3402
|
+
const tiers = MODE_TIERS[mode];
|
|
3403
|
+
return SCRUB_PATTERNS.filter((p) => {
|
|
3404
|
+
if (p.id === "phone") return tiers.has("strict") || enablePhone;
|
|
3405
|
+
return tiers.has(p.tier);
|
|
3406
|
+
});
|
|
3407
|
+
}
|
|
3408
|
+
function compileDenylist(sources) {
|
|
3409
|
+
if (!sources || sources.length === 0) return [];
|
|
3410
|
+
const out = [];
|
|
3411
|
+
for (const src of sources) {
|
|
3412
|
+
try {
|
|
3413
|
+
out.push(new RegExp(src, "g"));
|
|
3414
|
+
} catch {
|
|
3415
|
+
}
|
|
3416
|
+
}
|
|
3417
|
+
return out;
|
|
3418
|
+
}
|
|
3419
|
+
function applyPattern(text, pattern, tally, slots) {
|
|
3420
|
+
const needsLuhn = LUHN_VALIDATED_IDS.has(pattern.id);
|
|
3421
|
+
return text.replace(pattern.regex, (...args) => {
|
|
3422
|
+
const match = args[0];
|
|
3423
|
+
if (needsLuhn && !passesLuhn(match)) return match;
|
|
3424
|
+
const groups = args.slice(0, args.length - 2);
|
|
3425
|
+
tally[pattern.id] = (tally[pattern.id] ?? 0) + 1;
|
|
3426
|
+
const slot = slots.length;
|
|
3427
|
+
slots.push(pattern.placeholder(groups));
|
|
3428
|
+
return sentinel(slot);
|
|
3429
|
+
});
|
|
3430
|
+
}
|
|
3431
|
+
function resolveScrubbers(config) {
|
|
3432
|
+
if (config.mode === "off") return null;
|
|
3433
|
+
return {
|
|
3434
|
+
patterns: resolveMode(config.mode, config.enablePhone),
|
|
3435
|
+
denylist: compileDenylist(config.denylistPatterns)
|
|
3436
|
+
};
|
|
3437
|
+
}
|
|
3438
|
+
function scrubTextWith(text, resolved) {
|
|
3439
|
+
if (text.length === 0) {
|
|
3440
|
+
return { text, redactions: {}, total: 0 };
|
|
3441
|
+
}
|
|
3442
|
+
const { patterns, denylist } = resolved;
|
|
3443
|
+
if (patterns.length === 0 && denylist.length === 0) {
|
|
3444
|
+
return { text, redactions: {}, total: 0 };
|
|
3445
|
+
}
|
|
3446
|
+
return scrubResolved(text, patterns, denylist);
|
|
3447
|
+
}
|
|
3448
|
+
function scrubResolved(text, patterns, denylist) {
|
|
3449
|
+
const tally = {};
|
|
3450
|
+
const slots = [];
|
|
3451
|
+
let out = text.includes(SENTINEL_CHAR) ? text.split(SENTINEL_CHAR).join("") : text;
|
|
3452
|
+
for (const pattern of patterns) {
|
|
3453
|
+
out = applyPattern(out, pattern, tally, slots);
|
|
3454
|
+
}
|
|
3455
|
+
for (let i = 0; i < denylist.length; i++) {
|
|
3456
|
+
out = out.replace(denylist[i], () => {
|
|
3457
|
+
tally.custom = (tally.custom ?? 0) + 1;
|
|
3458
|
+
const slot = slots.length;
|
|
3459
|
+
slots.push("[REDACTED:custom]");
|
|
3460
|
+
return sentinel(slot);
|
|
3461
|
+
});
|
|
3462
|
+
}
|
|
3463
|
+
if (slots.length === 0) {
|
|
3464
|
+
return { text, redactions: {}, total: 0 };
|
|
3465
|
+
}
|
|
3466
|
+
out = out.replace(SENTINEL_RE, (_m, idx) => slots[Number(idx)]);
|
|
3467
|
+
let total = 0;
|
|
3468
|
+
for (const k in tally) total += tally[k];
|
|
3469
|
+
return { text: out, redactions: tally, total };
|
|
3470
|
+
}
|
|
3471
|
+
|
|
3472
|
+
// ../shared/src/secret-manager-scrub.ts
|
|
3473
|
+
var SECRET_MANAGER_OUTPUT_ID = "secret-manager-output";
|
|
3474
|
+
var SECRET_MANAGER_PLACEHOLDER = `[REDACTED:secret:${SECRET_MANAGER_OUTPUT_ID}]`;
|
|
3475
|
+
var SECRET_MANAGER_COMMAND_RES = [
|
|
3476
|
+
/^op\s+read(\s|$)/,
|
|
3477
|
+
/^op\s+item\s+get(\s|$)/,
|
|
3478
|
+
/^aws\s+secretsmanager\s+get-secret-value(\s|$)/,
|
|
3479
|
+
/^gcloud\s+secrets\s+versions\s+access(\s|$)/,
|
|
3480
|
+
/^vault\s+read(\s|$)/,
|
|
3481
|
+
/^vault\s+kv\s+get(\s|$)/,
|
|
3482
|
+
/^az\s+keyvault\s+secret\s+show(\s|$)/
|
|
3483
|
+
];
|
|
3484
|
+
var SEGMENT_SPLIT_RE = /&&|\|\||;|\|/;
|
|
3485
|
+
var LEADING_ENV_ASSIGNMENTS_RE = /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;
|
|
3486
|
+
function segmentIsSecretManagerFetch(segment) {
|
|
3487
|
+
const normalized = segment.trimStart().replace(LEADING_ENV_ASSIGNMENTS_RE, "");
|
|
3488
|
+
return SECRET_MANAGER_COMMAND_RES.some((re) => re.test(normalized));
|
|
3489
|
+
}
|
|
3490
|
+
function isSecretManagerFetch(command) {
|
|
3491
|
+
if (command.length === 0) return false;
|
|
3492
|
+
for (const segment of command.split(SEGMENT_SPLIT_RE)) {
|
|
3493
|
+
if (segmentIsSecretManagerFetch(segment)) return true;
|
|
3494
|
+
}
|
|
3495
|
+
return false;
|
|
3496
|
+
}
|
|
3497
|
+
var EMPTY_KEY_SET = /* @__PURE__ */ new Set();
|
|
3498
|
+
function secretManagerResultKeys(attributes, config) {
|
|
3499
|
+
const command = attributes[config.commandKey];
|
|
3500
|
+
if (typeof command !== "string" || !isSecretManagerFetch(command)) {
|
|
3501
|
+
return EMPTY_KEY_SET;
|
|
3502
|
+
}
|
|
3503
|
+
const out = /* @__PURE__ */ new Set();
|
|
3504
|
+
for (const key of Object.keys(attributes)) {
|
|
3505
|
+
const value = attributes[key];
|
|
3506
|
+
if (typeof value !== "string" || value.length === 0) continue;
|
|
3507
|
+
if (config.resultKeys?.has(key)) {
|
|
3508
|
+
out.add(key);
|
|
3509
|
+
continue;
|
|
3510
|
+
}
|
|
3511
|
+
if (config.resultKeyPrefixes?.some((prefix) => key.startsWith(prefix))) {
|
|
3512
|
+
out.add(key);
|
|
3513
|
+
}
|
|
3514
|
+
}
|
|
3515
|
+
return out;
|
|
3516
|
+
}
|
|
3517
|
+
|
|
3518
|
+
// ../shared/src/types/messages.ts
|
|
3519
|
+
var SSE_CHANNEL_PREFIX = "pubsub:sse:org:";
|
|
3520
|
+
var SSE_CHANNEL_PATTERN = `${SSE_CHANNEL_PREFIX}*`;
|
|
3521
|
+
|
|
3522
|
+
// ../shared/src/types/scrubbing.ts
|
|
3523
|
+
var DEFAULT_SCRUBBING_CONFIG = {
|
|
3524
|
+
mode: "standard"
|
|
3525
|
+
};
|
|
3526
|
+
|
|
3527
|
+
// src/backfill/scrub.ts
|
|
3528
|
+
var EDGE_SECRET_MANAGER_CONFIG = {
|
|
3529
|
+
commandKey: CONTENT_KEY_TOOL_COMMAND,
|
|
3530
|
+
resultKeys: /* @__PURE__ */ new Set([CONTENT_KEY_TOOL_RESULT])
|
|
3531
|
+
};
|
|
3532
|
+
function scrubAttributes(attributes, resolved, options = {}) {
|
|
3533
|
+
const out = {};
|
|
3534
|
+
const byType = {};
|
|
3535
|
+
let redactedCount = 0;
|
|
3536
|
+
if (resolved === null) {
|
|
3537
|
+
for (const [key, value] of Object.entries(attributes)) out[key] = value;
|
|
3538
|
+
return { attributes: out, redactedCount: 0, byType: {} };
|
|
3539
|
+
}
|
|
3540
|
+
const secretManagerKeys = secretManagerResultKeys(
|
|
3541
|
+
options.correlationCommand === void 0 ? attributes : { ...attributes, [CONTENT_KEY_TOOL_COMMAND]: options.correlationCommand },
|
|
3542
|
+
EDGE_SECRET_MANAGER_CONFIG
|
|
3543
|
+
);
|
|
3544
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
3545
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
3546
|
+
out[key] = value;
|
|
3547
|
+
continue;
|
|
3548
|
+
}
|
|
3549
|
+
if (secretManagerKeys.has(key)) {
|
|
3550
|
+
out[key] = SECRET_MANAGER_PLACEHOLDER;
|
|
3551
|
+
byType[SECRET_MANAGER_OUTPUT_ID] = (byType[SECRET_MANAGER_OUTPUT_ID] ?? 0) + 1;
|
|
3552
|
+
redactedCount += 1;
|
|
3553
|
+
continue;
|
|
3554
|
+
}
|
|
3555
|
+
if (!CONTENT_KEYS.has(key)) {
|
|
3556
|
+
out[key] = value;
|
|
3557
|
+
continue;
|
|
3558
|
+
}
|
|
3559
|
+
const result = scrubTextWith(value, resolved);
|
|
3560
|
+
out[key] = result.text;
|
|
3561
|
+
if (result.total > 0) {
|
|
3562
|
+
redactedCount += result.total;
|
|
3563
|
+
for (const id in result.redactions) {
|
|
3564
|
+
byType[id] = (byType[id] ?? 0) + result.redactions[id];
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
}
|
|
3568
|
+
return { attributes: out, redactedCount, byType };
|
|
3569
|
+
}
|
|
3570
|
+
|
|
3571
|
+
// src/capture/queue-record.ts
|
|
3572
|
+
var CONTENT_VALUE_CAP = 8192;
|
|
3573
|
+
var QUEUE_ENTRY_CAP = 1e4;
|
|
3574
|
+
function queueEntryCount(io, folder) {
|
|
3575
|
+
try {
|
|
3576
|
+
return io.readdir(folder).filter((name) => name.endsWith(".json")).length;
|
|
3577
|
+
} catch {
|
|
3578
|
+
return 0;
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
var TAIL_MARGIN = 16 * 1024;
|
|
3582
|
+
var SCRUB_WINDOW = CONTENT_VALUE_CAP + TAIL_MARGIN;
|
|
3583
|
+
function isRecord4(value) {
|
|
3584
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3585
|
+
}
|
|
3586
|
+
function capContent(s) {
|
|
3587
|
+
return s.length > CONTENT_VALUE_CAP ? s.slice(0, CONTENT_VALUE_CAP) : s;
|
|
3588
|
+
}
|
|
3589
|
+
function unchangedTailLength(input, scrubbed) {
|
|
3590
|
+
let n = 0;
|
|
3591
|
+
const max = Math.min(input.length, scrubbed.length);
|
|
3592
|
+
while (n < max && input.charCodeAt(input.length - 1 - n) === scrubbed.charCodeAt(scrubbed.length - 1 - n)) {
|
|
3593
|
+
n += 1;
|
|
3594
|
+
}
|
|
3595
|
+
return n;
|
|
3596
|
+
}
|
|
3597
|
+
function scrubAndCap(attributes, resolved) {
|
|
3598
|
+
const windowed = {};
|
|
3599
|
+
const cut = /* @__PURE__ */ new Map();
|
|
3600
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
3601
|
+
if (CONTENT_KEYS.has(key) && value.length > SCRUB_WINDOW) {
|
|
3602
|
+
const head = value.slice(0, SCRUB_WINDOW);
|
|
3603
|
+
windowed[key] = head;
|
|
3604
|
+
cut.set(key, head);
|
|
3605
|
+
} else {
|
|
3606
|
+
windowed[key] = value;
|
|
3607
|
+
}
|
|
3608
|
+
}
|
|
3609
|
+
const command = attributes[CONTENT_KEY_TOOL_COMMAND];
|
|
3610
|
+
const scrubbed = scrubAttributes(
|
|
3611
|
+
windowed,
|
|
3612
|
+
resolved,
|
|
3613
|
+
command === void 0 ? {} : { correlationCommand: command }
|
|
3614
|
+
);
|
|
3615
|
+
const out = {};
|
|
3616
|
+
for (const [key, value] of Object.entries(scrubbed.attributes)) {
|
|
3617
|
+
if (!CONTENT_KEYS.has(key)) {
|
|
3618
|
+
out[key] = value;
|
|
3619
|
+
continue;
|
|
3620
|
+
}
|
|
3621
|
+
const head = cut.get(key);
|
|
3622
|
+
let text = value;
|
|
3623
|
+
if (head !== void 0 && text !== SECRET_MANAGER_PLACEHOLDER) {
|
|
3624
|
+
const tail = Math.min(TAIL_MARGIN, unchangedTailLength(head, text));
|
|
3625
|
+
text = text.slice(0, text.length - tail);
|
|
3626
|
+
}
|
|
3627
|
+
out[key] = capContent(text);
|
|
3628
|
+
}
|
|
3629
|
+
return { attributes: out, redactedCount: scrubbed.redactedCount, byType: scrubbed.byType };
|
|
3630
|
+
}
|
|
3631
|
+
function textForScrub(full, canonical) {
|
|
3632
|
+
if (canonical === void 0) return void 0;
|
|
3633
|
+
return full?.startsWith(canonical) ? full : canonical;
|
|
3634
|
+
}
|
|
3635
|
+
var edgeScrubbers;
|
|
3636
|
+
function scrubbers() {
|
|
3637
|
+
if (edgeScrubbers === void 0) edgeScrubbers = resolveScrubbers(DEFAULT_SCRUBBING_CONFIG);
|
|
3638
|
+
return edgeScrubbers;
|
|
3639
|
+
}
|
|
3640
|
+
function scrubContent(values) {
|
|
3641
|
+
const attrs = {};
|
|
3642
|
+
for (const [key, value] of Object.entries(values)) {
|
|
3643
|
+
if (value !== void 0) attrs[key] = value;
|
|
3644
|
+
}
|
|
3645
|
+
return scrubAndCap(attrs, scrubbers()).attributes;
|
|
3646
|
+
}
|
|
3647
|
+
function scrubCallArgs(args, commandText) {
|
|
3648
|
+
const scrubbed = scrubContent({
|
|
3649
|
+
[CONTENT_KEY_TOOL_COMMAND]: textForScrub(commandText, args.full_command),
|
|
3650
|
+
[CONTENT_KEY_TOOL_FILE]: args.file_path
|
|
3651
|
+
});
|
|
3652
|
+
const out = {};
|
|
3653
|
+
if (scrubbed[CONTENT_KEY_TOOL_COMMAND] !== void 0) {
|
|
3654
|
+
out.full_command = scrubbed[CONTENT_KEY_TOOL_COMMAND];
|
|
3655
|
+
}
|
|
3656
|
+
if (scrubbed[CONTENT_KEY_TOOL_FILE] !== void 0)
|
|
3657
|
+
out.file_path = scrubbed[CONTENT_KEY_TOOL_FILE];
|
|
3658
|
+
return out;
|
|
3659
|
+
}
|
|
3660
|
+
function queueEntryFileName(atMs, pid, seq) {
|
|
3661
|
+
return `${atMs}-${pid}-${seq}.json`;
|
|
3662
|
+
}
|
|
3663
|
+
function serializeQueueEntry(entry) {
|
|
3664
|
+
return `${JSON.stringify(entry)}
|
|
3665
|
+
`;
|
|
3666
|
+
}
|
|
3667
|
+
function isCaptureRecord(value, captureEvents) {
|
|
3668
|
+
if (typeof value.event !== "string" || !captureEvents.has(value.event)) return false;
|
|
3669
|
+
if (typeof value.capturedAtMs !== "number" || !Number.isFinite(value.capturedAtMs)) return false;
|
|
3670
|
+
const tool = value.tool;
|
|
3671
|
+
if (tool === void 0) return true;
|
|
3672
|
+
return isRecord4(tool) && typeof tool.vendorTool === "string" && typeof tool.argsHash === "string" && isRecord4(tool.call) && typeof tool.call.tool === "string";
|
|
3673
|
+
}
|
|
3674
|
+
function isDecisionRecord(value) {
|
|
3675
|
+
return typeof value.decidedAtMs === "number" && Number.isFinite(value.decidedAtMs) && typeof value.decisionMs === "number" && typeof value.hookEvent === "string" && typeof value.vendorTool === "string" && typeof value.argsHash === "string" && typeof value.verdict === "string" && typeof value.blocked === "boolean";
|
|
3676
|
+
}
|
|
3677
|
+
function parseQueueEntryWith(text, captureEvents) {
|
|
3678
|
+
let parsed;
|
|
3679
|
+
try {
|
|
3680
|
+
parsed = JSON.parse(text);
|
|
3681
|
+
} catch {
|
|
3682
|
+
return void 0;
|
|
3683
|
+
}
|
|
3684
|
+
if (!isRecord4(parsed)) return void 0;
|
|
3685
|
+
const value = parsed;
|
|
3686
|
+
const unknown = () => ({
|
|
3687
|
+
kind: "unknown",
|
|
3688
|
+
rawKind: typeof value.kind === "string" ? value.kind : String(value.kind),
|
|
3689
|
+
rawV: value.v
|
|
3690
|
+
});
|
|
3691
|
+
if (value.v !== 1) return unknown();
|
|
3692
|
+
if (value.kind === "capture" && isCaptureRecord(value, captureEvents)) {
|
|
3693
|
+
return value;
|
|
3694
|
+
}
|
|
3695
|
+
if (value.kind === "pep-decision" && isDecisionRecord(value)) {
|
|
3696
|
+
return value;
|
|
3697
|
+
}
|
|
3698
|
+
return unknown();
|
|
3699
|
+
}
|
|
3700
|
+
|
|
3701
|
+
// src/cursor/types.ts
|
|
3702
|
+
var CAPTURE_EVENTS = Object.freeze([
|
|
3703
|
+
"beforeSubmitPrompt",
|
|
3704
|
+
"postToolUse",
|
|
3705
|
+
"postToolUseFailure",
|
|
3706
|
+
"afterMCPExecution",
|
|
3707
|
+
"afterAgentResponse",
|
|
3708
|
+
"afterFileEdit",
|
|
3709
|
+
"subagentStart",
|
|
3710
|
+
"subagentStop",
|
|
3711
|
+
"stop"
|
|
3712
|
+
]);
|
|
3713
|
+
|
|
3714
|
+
// src/cursor/queue-record.ts
|
|
3715
|
+
var CAPTURE_SET = new Set(CAPTURE_EVENTS);
|
|
3716
|
+
function parseQueueEntry(text) {
|
|
3717
|
+
return parseQueueEntryWith(text, CAPTURE_SET);
|
|
3718
|
+
}
|
|
3719
|
+
|
|
3720
|
+
// src/pep/cursor-join.ts
|
|
3721
|
+
var SHELL_JOIN_WINDOW_MS = 3e4;
|
|
3722
|
+
var MCP_OBSERVED_WINDOW_MS = 6e4;
|
|
3723
|
+
function recentDecisions(query, windowMs) {
|
|
3724
|
+
const io = query.io ?? nodeCaptureFileIO;
|
|
3725
|
+
const folder = queueFolderFor(query.home, query.projectKey);
|
|
3726
|
+
let names;
|
|
3727
|
+
try {
|
|
3728
|
+
names = io.readdir(folder);
|
|
3729
|
+
} catch {
|
|
3730
|
+
return [];
|
|
3731
|
+
}
|
|
3732
|
+
const oldest = query.nowMs - windowMs;
|
|
3733
|
+
const inWindow = [];
|
|
3734
|
+
for (const name of names) {
|
|
3735
|
+
if (!name.endsWith(".json")) continue;
|
|
3736
|
+
const atMs = Number.parseInt(name.slice(0, name.indexOf("-")), 10);
|
|
3737
|
+
if (!Number.isFinite(atMs) || atMs < oldest || atMs > query.nowMs) continue;
|
|
3738
|
+
inWindow.push({ atMs, name });
|
|
3739
|
+
}
|
|
3740
|
+
inWindow.sort((a, b) => b.atMs - a.atMs || b.name.localeCompare(a.name));
|
|
3741
|
+
const out = [];
|
|
3742
|
+
for (const { name } of inWindow) {
|
|
3743
|
+
let text;
|
|
3744
|
+
try {
|
|
3745
|
+
text = io.readFile(`${folder}/${name}`).toString("utf8");
|
|
3746
|
+
} catch {
|
|
3747
|
+
continue;
|
|
3748
|
+
}
|
|
3749
|
+
const entry = parseQueueEntry(text);
|
|
3750
|
+
if (entry?.kind === "pep-decision") out.push(entry);
|
|
3751
|
+
}
|
|
3752
|
+
return out;
|
|
3753
|
+
}
|
|
3754
|
+
function sameGeneration(record, query) {
|
|
3755
|
+
if (query.conversationId === null || query.generationId === null) return false;
|
|
3756
|
+
return record.conversationId === query.conversationId && record.generationId === query.generationId;
|
|
3757
|
+
}
|
|
3758
|
+
function readShellJoin(query) {
|
|
3759
|
+
const records = recentDecisions(query, SHELL_JOIN_WINDOW_MS);
|
|
3760
|
+
let liveHandoff = false;
|
|
3761
|
+
let answer;
|
|
3762
|
+
for (const record of records) {
|
|
3763
|
+
if (!sameGeneration(record, query)) continue;
|
|
3764
|
+
if (record.handoff === "shell-card") liveHandoff = true;
|
|
3765
|
+
if (answer !== void 0) continue;
|
|
3766
|
+
if (query.argsHash === null || record.argsHash !== query.argsHash) continue;
|
|
3767
|
+
if (record.hookEvent !== "preToolUse") continue;
|
|
3768
|
+
answer = record.handoff === "shell-card" ? { kind: "handoff" } : { kind: "decided" };
|
|
3769
|
+
}
|
|
3770
|
+
return answer ?? { kind: "miss", liveHandoff };
|
|
3771
|
+
}
|
|
3772
|
+
function joinQueryFor(input) {
|
|
3773
|
+
const io = input.io ?? nodeCaptureFileIO;
|
|
3774
|
+
const key = readQueueKey(input.home, io);
|
|
3775
|
+
const label = input.vendorTool ?? input.normalized?.vendorTool;
|
|
3776
|
+
const first = input.normalized?.candidates[0];
|
|
3777
|
+
return {
|
|
3778
|
+
home: input.home,
|
|
3779
|
+
io,
|
|
3780
|
+
projectKey: input.projectKey,
|
|
3781
|
+
conversationId: input.conversationId,
|
|
3782
|
+
generationId: input.generationId,
|
|
3783
|
+
argsHash: key === void 0 || label === void 0 ? null : argsHashForCall(label, first?.args ?? {}, input.toolInput, key),
|
|
3784
|
+
nowMs: input.nowMs
|
|
3785
|
+
};
|
|
3786
|
+
}
|
|
3787
|
+
function readMcpCorrelationId(query) {
|
|
3788
|
+
if (query.argsHash === null) return null;
|
|
3789
|
+
for (const record of recentDecisions(query, MCP_OBSERVED_WINDOW_MS)) {
|
|
3790
|
+
if (!sameGeneration(record, query)) continue;
|
|
3791
|
+
if (record.verdict !== "observed" || record.argsHash !== query.argsHash) continue;
|
|
3792
|
+
if (record.toolUseId !== null) return record.toolUseId;
|
|
3793
|
+
}
|
|
3794
|
+
return null;
|
|
3795
|
+
}
|
|
3796
|
+
|
|
3797
|
+
// src/pep/cursor-record.ts
|
|
3798
|
+
var EVALUATED_VIA = /* @__PURE__ */ new Set(["pdp", "cached-rules"]);
|
|
3799
|
+
function writeDecisionRecord(input) {
|
|
3800
|
+
try {
|
|
3801
|
+
const key = readQueueKey(input.home, input.io);
|
|
3802
|
+
if (key === void 0) return false;
|
|
3803
|
+
const observed = input.verdict === "observed";
|
|
3804
|
+
const first = input.candidates[0];
|
|
3805
|
+
if (first === void 0 && !observed && EVALUATED_VIA.has(input.via)) return false;
|
|
3806
|
+
const record = {
|
|
3807
|
+
v: 1,
|
|
3808
|
+
kind: "pep-decision",
|
|
3809
|
+
decidedAtMs: input.decidedAtMs,
|
|
3810
|
+
decisionMs: input.decisionMs,
|
|
3811
|
+
hookEvent: input.hookEvent,
|
|
3812
|
+
conversationId: input.conversationId,
|
|
3813
|
+
generationId: input.generationId,
|
|
3814
|
+
toolUseId: input.toolUseId,
|
|
3815
|
+
toolUseIdFrom: input.toolUseIdFrom ?? (input.toolUseId === null ? "none" : "payload"),
|
|
3816
|
+
vendorTool: input.vendorTool,
|
|
3817
|
+
// An "observed" record stands for a call this hook did not decide, so it carries no
|
|
3818
|
+
// call — only the id and the hash the decision event needs to find it (R5 item 3).
|
|
3819
|
+
// Otherwise the command itself rides only where the project captures content, and
|
|
3820
|
+
// then edge-scrubbed through capture's own scrubber, because this file lands in the
|
|
3821
|
+
// same queue and is shipped by the same sender. Recording it raw would put a secret
|
|
3822
|
+
// an agent had just read into a queue file, which R5's never-contains list forbids.
|
|
3823
|
+
call: observed || first === void 0 ? null : input.captureContent ? { tool: first.tool, args: scrubCallArgs(first.args, input.commandText) } : { tool: first.tool, args: {} },
|
|
3824
|
+
candidateTools: input.candidates.map((candidate) => candidate.tool),
|
|
3825
|
+
argsHash: argsHashForCall(input.vendorTool, first?.args ?? {}, input.toolInput, key),
|
|
3826
|
+
verdict: input.verdict,
|
|
3827
|
+
policyId: input.policyId,
|
|
3828
|
+
candidateIndex: input.candidateIndex,
|
|
3829
|
+
via: input.via,
|
|
3830
|
+
...input.hold === void 0 ? {} : { hold: input.hold },
|
|
3831
|
+
...input.handoff === void 0 ? {} : { handoff: input.handoff },
|
|
3832
|
+
blocked: input.blocked
|
|
3833
|
+
};
|
|
3834
|
+
const folder = queueFolderFor(input.home, input.projectKey);
|
|
3835
|
+
if (queueEntryCount(input.io, folder) >= QUEUE_ENTRY_CAP) return false;
|
|
3836
|
+
input.io.mkdirp(folder, CAPTURE_DIR_MODE);
|
|
3837
|
+
input.io.writeFileAtomic(
|
|
3838
|
+
`${folder}/${queueEntryFileName(input.decidedAtMs, process.pid, 0)}`,
|
|
3839
|
+
serializeQueueEntry(record),
|
|
3840
|
+
CAPTURE_FILE_MODE
|
|
3841
|
+
);
|
|
3842
|
+
return true;
|
|
3843
|
+
} catch {
|
|
3844
|
+
return false;
|
|
3845
|
+
}
|
|
3846
|
+
}
|
|
3847
|
+
function writeHandoffRecord(input) {
|
|
3848
|
+
return writeDecisionRecord({
|
|
3849
|
+
...input,
|
|
3850
|
+
hookEvent: "preToolUse",
|
|
3851
|
+
verdict: "require_approval",
|
|
3852
|
+
via: "pdp",
|
|
3853
|
+
blocked: false,
|
|
3854
|
+
handoff: "shell-card"
|
|
3855
|
+
});
|
|
3856
|
+
}
|
|
3857
|
+
|
|
3858
|
+
// src/pep/cursor-request.ts
|
|
3859
|
+
var CURSOR_DECISION_EVENTS = /* @__PURE__ */ new Set([
|
|
3860
|
+
"preToolUse",
|
|
3861
|
+
"beforeMCPExecution"
|
|
3862
|
+
]);
|
|
3863
|
+
function toRequest(call) {
|
|
3864
|
+
const args = {};
|
|
3865
|
+
if (call.args.full_command !== void 0) args.full_command = call.args.full_command;
|
|
3866
|
+
if (call.args.file_path !== void 0) args.file_path = call.args.file_path;
|
|
3867
|
+
return { tool: call.tool, args };
|
|
3868
|
+
}
|
|
3869
|
+
function buildCursorPdpRequest(payload) {
|
|
3870
|
+
const call = normalizeCursorPayload(payload);
|
|
3871
|
+
if (call === void 0) return void 0;
|
|
3872
|
+
if (!CURSOR_DECISION_EVENTS.has(call.event)) return void 0;
|
|
3873
|
+
return call.candidates.map(toRequest);
|
|
3874
|
+
}
|
|
3875
|
+
function withScope(requests, scope) {
|
|
3876
|
+
return requests.map((request) => ({ ...request, scope }));
|
|
3877
|
+
}
|
|
3878
|
+
|
|
3879
|
+
// src/pep/hook-shim.ts
|
|
3880
|
+
var HOOK_OUTCOMES = Object.keys({
|
|
3881
|
+
deny: 0,
|
|
3882
|
+
ask: 0,
|
|
3883
|
+
warn: 0,
|
|
3884
|
+
none: 0
|
|
3885
|
+
});
|
|
3886
|
+
var NO_DECISION = { decision: "none", reason: "" };
|
|
3887
|
+
var MAX_DETAIL_LEN = 8192;
|
|
3888
|
+
var PEP_VENDOR = "claude-code";
|
|
3889
|
+
var SHELL_TOOLS = /* @__PURE__ */ new Set(["Bash", "PowerShell"]);
|
|
3890
|
+
var FILE_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write", "Read", "MultiEdit", "NotebookEdit"]);
|
|
3891
|
+
var SEARCH_GLOB_FIELD = /* @__PURE__ */ new Map([
|
|
3892
|
+
["Grep", "glob"],
|
|
3893
|
+
["Glob", "pattern"]
|
|
3894
|
+
]);
|
|
3895
|
+
function nonEmpty3(value) {
|
|
3896
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
3897
|
+
}
|
|
3898
|
+
function isAbsoluteGlob2(glob) {
|
|
3899
|
+
return /^(?:[\\/]|[A-Za-z]:[\\/])/.test(glob);
|
|
3900
|
+
}
|
|
3901
|
+
function searchPath(tool, input) {
|
|
3902
|
+
const field = SEARCH_GLOB_FIELD.get(tool);
|
|
3903
|
+
const dir = nonEmpty3(input.path);
|
|
3904
|
+
const glob = field === void 0 ? void 0 : nonEmpty3(input[field]);
|
|
3905
|
+
if (glob === void 0) return dir;
|
|
3906
|
+
if (dir === void 0 || isAbsoluteGlob2(glob)) return glob;
|
|
3907
|
+
return `${dir.replace(/[\\/]+$/, "")}/${glob}`;
|
|
3908
|
+
}
|
|
3909
|
+
var handleApproval = async (payload, verdict, ctx) => {
|
|
3910
|
+
const correlationId = typeof payload.tool_use_id === "string" ? payload.tool_use_id : "";
|
|
3911
|
+
if (!ctx.cfg.holdUrl || !ctx.cfg.token || !correlationId) {
|
|
3912
|
+
return {
|
|
3913
|
+
decision: "ask",
|
|
3914
|
+
reason: verdict.reason || "AgentTrail requires approval for this action."
|
|
3915
|
+
};
|
|
3916
|
+
}
|
|
3917
|
+
ctx.extendDeadline?.(PEP_HOLD_WATCHDOG_MS);
|
|
3918
|
+
try {
|
|
3919
|
+
const outcome = await holdForApproval(
|
|
3920
|
+
{
|
|
3921
|
+
url: ctx.cfg.holdUrl,
|
|
3922
|
+
token: ctx.cfg.token,
|
|
3923
|
+
// The same scope as the evaluate request: the server labels the held approval with it.
|
|
3924
|
+
request: buildPdpRequest(payload, ctx.cfg.scope),
|
|
3925
|
+
correlationId,
|
|
3926
|
+
timeoutMs: PEP_HOLD_FETCH_TIMEOUT_MS
|
|
3927
|
+
},
|
|
3928
|
+
ctx.fetchFn
|
|
3929
|
+
);
|
|
3930
|
+
if (outcome === "tier-disabled") {
|
|
3931
|
+
return NO_DECISION;
|
|
3932
|
+
}
|
|
3933
|
+
if (outcome === "approved") {
|
|
3934
|
+
return NO_DECISION;
|
|
3935
|
+
}
|
|
3936
|
+
if (outcome === "denied") {
|
|
3937
|
+
return { decision: "deny", reason: "Denied by an AgentTrail reviewer." };
|
|
3938
|
+
}
|
|
3939
|
+
return {
|
|
3940
|
+
decision: "ask",
|
|
3941
|
+
reason: "No AgentTrail reviewer answered in time; deferring the decision to you."
|
|
3942
|
+
};
|
|
3943
|
+
} catch {
|
|
3944
|
+
return {
|
|
3945
|
+
decision: "deny",
|
|
3946
|
+
reason: "AgentTrail approval hold was unreachable; failing closed."
|
|
3947
|
+
};
|
|
3948
|
+
}
|
|
3949
|
+
};
|
|
3950
|
+
function cap(s) {
|
|
3951
|
+
return s.length > MAX_DETAIL_LEN ? s.slice(0, MAX_DETAIL_LEN) : s;
|
|
3952
|
+
}
|
|
3953
|
+
var TRUNCATION_MARKER = "\u2026[truncated]\u2026";
|
|
3954
|
+
function capMiddle(s) {
|
|
3955
|
+
if (s.length <= MAX_DETAIL_LEN) return s;
|
|
3956
|
+
const budget = MAX_DETAIL_LEN - TRUNCATION_MARKER.length;
|
|
3957
|
+
const head = Math.ceil(budget / 2);
|
|
3958
|
+
const tail = budget - head;
|
|
3959
|
+
return `${s.slice(0, head)}${TRUNCATION_MARKER}${s.slice(s.length - tail)}`;
|
|
3960
|
+
}
|
|
3961
|
+
function safeStringify2(v) {
|
|
3962
|
+
try {
|
|
3963
|
+
return JSON.stringify(v) ?? "";
|
|
3964
|
+
} catch {
|
|
3965
|
+
return "";
|
|
3966
|
+
}
|
|
3967
|
+
}
|
|
3968
|
+
function buildPdpRequest(payload, scope) {
|
|
3969
|
+
const tool = typeof payload.tool_name === "string" ? payload.tool_name : "";
|
|
3970
|
+
const input = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : {};
|
|
3971
|
+
const args = {};
|
|
3972
|
+
if (SHELL_TOOLS.has(tool)) {
|
|
3973
|
+
if (typeof input.command === "string") args.full_command = cap(input.command);
|
|
3974
|
+
} else if (FILE_TOOLS.has(tool)) {
|
|
3975
|
+
const fp = input.file_path ?? input.notebook_path;
|
|
3976
|
+
if (typeof fp === "string") args.file_path = fp;
|
|
3977
|
+
} else if (SEARCH_GLOB_FIELD.has(tool)) {
|
|
3978
|
+
const fp = searchPath(tool, input);
|
|
3979
|
+
if (fp !== void 0) args.file_path = fp;
|
|
3980
|
+
} else if (tool === "WebSearch") {
|
|
3981
|
+
if (typeof input.query === "string") args.full_command = cap(input.query);
|
|
3982
|
+
} else if (tool.startsWith("mcp__")) {
|
|
3983
|
+
args.full_command = capMiddle(safeStringify2(input));
|
|
3984
|
+
} else {
|
|
3985
|
+
if (typeof input.command === "string") args.full_command = cap(input.command);
|
|
3986
|
+
if (typeof input.file_path === "string") args.file_path = input.file_path;
|
|
3987
|
+
}
|
|
3988
|
+
const agentId = scope?.agent_id;
|
|
3989
|
+
const projectId = scope?.project_id;
|
|
3990
|
+
return {
|
|
3991
|
+
tool,
|
|
3992
|
+
args,
|
|
3993
|
+
scope: {
|
|
3994
|
+
...agentId !== void 0 ? { agent_id: agentId } : {},
|
|
3995
|
+
...projectId !== void 0 ? { project_id: projectId } : {},
|
|
3996
|
+
vendor: PEP_VENDOR
|
|
3997
|
+
}
|
|
3998
|
+
};
|
|
3999
|
+
}
|
|
4000
|
+
async function mapVerdict(payload, response, cfg, deps) {
|
|
4001
|
+
switch (response.verdict) {
|
|
4002
|
+
case "allow": {
|
|
4003
|
+
const warned = (response.matched_policies ?? []).some((p) => p.action === "warn");
|
|
4004
|
+
return warned ? { decision: "warn", reason: response.reason || "Flagged by AgentTrail policy." } : NO_DECISION;
|
|
4005
|
+
}
|
|
4006
|
+
case "deny":
|
|
4007
|
+
return { decision: "deny", reason: response.reason || "Blocked by AgentTrail policy." };
|
|
4008
|
+
case "require_approval":
|
|
4009
|
+
return (deps.approve ?? handleApproval)(
|
|
4010
|
+
payload,
|
|
4011
|
+
{ reason: response.reason },
|
|
4012
|
+
{ cfg, fetchFn: deps.fetchFn, extendDeadline: deps.extendDeadline }
|
|
4013
|
+
);
|
|
4014
|
+
}
|
|
4015
|
+
}
|
|
4016
|
+
function failClosedViaSnapshot(_payload, request, cfg, deps) {
|
|
4017
|
+
const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
|
|
4018
|
+
if (!snapshot) {
|
|
4019
|
+
return {
|
|
4020
|
+
decision: "deny",
|
|
4021
|
+
reason: "AgentTrail PDP is unreachable and no local policy snapshot is cached; failing closed."
|
|
4022
|
+
};
|
|
4023
|
+
}
|
|
4024
|
+
const { verdict, decidingName } = evaluateLocally(snapshot, request, cfg.orgId);
|
|
4025
|
+
if (verdict === "deny") {
|
|
4026
|
+
return {
|
|
4027
|
+
decision: "deny",
|
|
4028
|
+
reason: `Blocked by local AgentTrail policy${quoted(decidingName)} (PDP unreachable; evaluated against the cached snapshot).`
|
|
4029
|
+
};
|
|
4030
|
+
}
|
|
4031
|
+
if (verdict === "require_approval") {
|
|
4032
|
+
return {
|
|
4033
|
+
decision: "ask",
|
|
4034
|
+
reason: `Approval required by local AgentTrail policy${quoted(decidingName)} (PDP unreachable; deferring to you).`
|
|
4035
|
+
};
|
|
4036
|
+
}
|
|
4037
|
+
return NO_DECISION;
|
|
4038
|
+
}
|
|
4039
|
+
function quoted(name) {
|
|
4040
|
+
return name ? ` "${name}"` : "";
|
|
4041
|
+
}
|
|
4042
|
+
function evaluateLocally(snapshot, request, orgId) {
|
|
4043
|
+
const ctx = buildEvaluationContext(request, orgId ?? NIL_ORG_ID);
|
|
4044
|
+
const matches = [];
|
|
4045
|
+
const byId = /* @__PURE__ */ new Map();
|
|
4046
|
+
for (const entry of snapshot.policies) {
|
|
4047
|
+
let matched = false;
|
|
4048
|
+
try {
|
|
4049
|
+
matched = compilePolicy(entry.predicate)(ctx).matched;
|
|
4050
|
+
} catch {
|
|
4051
|
+
continue;
|
|
4052
|
+
}
|
|
4053
|
+
if (matched) {
|
|
4054
|
+
matches.push({ policyId: entry.id, action: entry.action });
|
|
4055
|
+
byId.set(entry.id, entry);
|
|
4056
|
+
}
|
|
4057
|
+
}
|
|
4058
|
+
const { verdict, policyId } = strongestVerdict(matches);
|
|
4059
|
+
const names = {};
|
|
4060
|
+
for (const [id, entry] of byId) names[id] = entry.name;
|
|
4061
|
+
return {
|
|
4062
|
+
verdict,
|
|
4063
|
+
decidingName: policyId ? byId.get(policyId)?.name ?? null : null,
|
|
4064
|
+
matches,
|
|
4065
|
+
names
|
|
4066
|
+
};
|
|
4067
|
+
}
|
|
4068
|
+
async function decide(payload, cfg, deps) {
|
|
4069
|
+
if (!cfg.enforce) {
|
|
4070
|
+
return NO_DECISION;
|
|
4071
|
+
}
|
|
4072
|
+
if (!cfg.url || !cfg.token) {
|
|
4073
|
+
return {
|
|
4074
|
+
decision: "deny",
|
|
4075
|
+
reason: "AgentTrail enforcement is enabled but misconfigured (missing PDP URL or token); failing closed. Re-run `npx -y @agenttrail/cli@latest setup --agent claude`."
|
|
4076
|
+
};
|
|
4077
|
+
}
|
|
4078
|
+
const request = buildPdpRequest(payload, cfg.scope);
|
|
4079
|
+
try {
|
|
4080
|
+
const outcome = await evaluateViaPdp(
|
|
4081
|
+
{ url: cfg.url, token: cfg.token, request, timeoutMs: cfg.timeoutMs },
|
|
4082
|
+
deps.fetchFn
|
|
4083
|
+
);
|
|
4084
|
+
if (outcome.kind === "tier-disabled") {
|
|
4085
|
+
return NO_DECISION;
|
|
4086
|
+
}
|
|
4087
|
+
if (outcome.kind === "unauthorized") {
|
|
4088
|
+
return {
|
|
4089
|
+
decision: "deny",
|
|
4090
|
+
reason: "AgentTrail rejected the enforcement credential (401); failing closed. Re-run `npx -y @agenttrail/cli@latest setup --agent claude`."
|
|
4091
|
+
};
|
|
4092
|
+
}
|
|
4093
|
+
return await mapVerdict(payload, outcome.response, cfg, deps);
|
|
4094
|
+
} catch (err) {
|
|
4095
|
+
if (err instanceof PdpUnreachableError) {
|
|
4096
|
+
return failClosedViaSnapshot(payload, request, cfg, deps);
|
|
4097
|
+
}
|
|
4098
|
+
throw err;
|
|
4099
|
+
}
|
|
4100
|
+
}
|
|
4101
|
+
function buildHookOutput(outcome, reason) {
|
|
4102
|
+
if (outcome === "none") return "";
|
|
4103
|
+
if (outcome === "warn") return reason === "" ? "" : JSON.stringify({ systemMessage: reason });
|
|
4104
|
+
return JSON.stringify({
|
|
4105
|
+
hookSpecificOutput: {
|
|
4106
|
+
hookEventName: "PreToolUse",
|
|
4107
|
+
permissionDecision: outcome,
|
|
4108
|
+
permissionDecisionReason: reason
|
|
4109
|
+
}
|
|
4110
|
+
});
|
|
4111
|
+
}
|
|
4112
|
+
function createRealEmitter() {
|
|
4113
|
+
let done = false;
|
|
4114
|
+
return {
|
|
4115
|
+
emitVerdict(outcome, reason) {
|
|
4116
|
+
if (done) return;
|
|
4117
|
+
done = true;
|
|
4118
|
+
const out = buildHookOutput(outcome, reason);
|
|
4119
|
+
if (out === "") {
|
|
4120
|
+
process.exit(0);
|
|
4121
|
+
}
|
|
4122
|
+
process.stdout.write(out, () => process.exit(0));
|
|
4123
|
+
const t = setTimeout(() => {
|
|
4124
|
+
process.stderr.write("AgentTrail enforcement output stalled; failing closed.\n");
|
|
4125
|
+
process.exit(2);
|
|
4126
|
+
}, 1e3);
|
|
4127
|
+
t.unref?.();
|
|
4128
|
+
},
|
|
4129
|
+
emitCrashDeny(reason) {
|
|
4130
|
+
if (done) return;
|
|
4131
|
+
done = true;
|
|
4132
|
+
process.stderr.write(`${reason}
|
|
4133
|
+
`);
|
|
4134
|
+
process.exit(2);
|
|
4135
|
+
}
|
|
4136
|
+
};
|
|
4137
|
+
}
|
|
4138
|
+
function parsePayload(input) {
|
|
4139
|
+
const parsed = JSON.parse(input);
|
|
4140
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
4141
|
+
throw new Error("PreToolUse payload was not a JSON object");
|
|
4142
|
+
}
|
|
4143
|
+
return parsed;
|
|
4144
|
+
}
|
|
4145
|
+
var DEFAULT_AGENT = "claude";
|
|
4146
|
+
function defaultSchedule(fn, ms) {
|
|
4147
|
+
const t = setTimeout(fn, ms);
|
|
4148
|
+
t.unref?.();
|
|
4149
|
+
return () => clearTimeout(t);
|
|
4150
|
+
}
|
|
4151
|
+
async function runShim(deps) {
|
|
4152
|
+
const schedule = deps.schedule ?? defaultSchedule;
|
|
4153
|
+
const fire = () => deps.emitter.emitCrashDeny("AgentTrail enforcement timed out; failing closed.");
|
|
4154
|
+
let cancelWatchdog = schedule(fire, deps.watchdogMs ?? PEP_WATCHDOG_MS);
|
|
4155
|
+
const extendDeadline = (ms) => {
|
|
4156
|
+
cancelWatchdog();
|
|
4157
|
+
cancelWatchdog = schedule(fire, ms);
|
|
4158
|
+
};
|
|
4159
|
+
try {
|
|
4160
|
+
const agent = agentFromArgv(deps.argv ?? process.argv.slice(2)) ?? DEFAULT_AGENT;
|
|
4161
|
+
if (agent !== "claude") {
|
|
4162
|
+
cancelWatchdog();
|
|
4163
|
+
deps.emitter.emitCrashDeny(
|
|
4164
|
+
"AgentTrail enforcement for this agent is not available in this build; failing closed."
|
|
4165
|
+
);
|
|
4166
|
+
return;
|
|
4167
|
+
}
|
|
4168
|
+
const input = await deps.readStdin();
|
|
4169
|
+
const payload = parsePayload(input);
|
|
4170
|
+
if (isCursorHookPayload(payload)) {
|
|
4171
|
+
cancelWatchdog();
|
|
4172
|
+
(deps.cursorEmitter ?? createRealCursorEmitter()).emitAnswer(CURSOR_NO_OPINION);
|
|
4173
|
+
return;
|
|
4174
|
+
}
|
|
4175
|
+
const cfg = resolvePepConfig(deps.env);
|
|
4176
|
+
const decision = await decide(payload, cfg, {
|
|
4177
|
+
fetchFn: deps.fetchFn,
|
|
4178
|
+
snapshotIO: deps.snapshotIO,
|
|
4179
|
+
approve: deps.approve,
|
|
4180
|
+
extendDeadline
|
|
4181
|
+
});
|
|
4182
|
+
cancelWatchdog();
|
|
4183
|
+
deps.emitter.emitVerdict(decision.decision, decision.reason);
|
|
4184
|
+
} catch (err) {
|
|
4185
|
+
cancelWatchdog();
|
|
4186
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4187
|
+
deps.emitter.emitCrashDeny(`AgentTrail enforcement error; failing closed: ${msg}`);
|
|
4188
|
+
}
|
|
4189
|
+
}
|
|
4190
|
+
async function readRealStdin() {
|
|
4191
|
+
const chunks = [];
|
|
4192
|
+
for await (const chunk of process.stdin) {
|
|
4193
|
+
chunks.push(Buffer.from(chunk));
|
|
4194
|
+
}
|
|
4195
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
4196
|
+
}
|
|
4197
|
+
function isDirectRun() {
|
|
4198
|
+
const entry = process.argv[1] ?? "";
|
|
4199
|
+
return /pep-hook\.(mjs|cjs|js)$/.test(entry);
|
|
4200
|
+
}
|
|
4201
|
+
var CODEX_ENFORCEMENT_UNAVAILABLE = "AgentTrail enforcement for Codex is not available in this build; failing closed.";
|
|
4202
|
+
function runCodexShim(deps) {
|
|
4203
|
+
deps.writeStderr(`${CODEX_ENFORCEMENT_UNAVAILABLE}
|
|
4204
|
+
`);
|
|
4205
|
+
return 2;
|
|
4206
|
+
}
|
|
4207
|
+
function dispatchHookRun(argv, drivers) {
|
|
4208
|
+
const agent = agentFromArgv(argv) ?? DEFAULT_AGENT;
|
|
4209
|
+
switch (agent) {
|
|
4210
|
+
case "claude":
|
|
4211
|
+
drivers.claude();
|
|
4212
|
+
return;
|
|
4213
|
+
case "cursor":
|
|
4214
|
+
drivers.cursor();
|
|
4215
|
+
return;
|
|
4216
|
+
case "codex":
|
|
4217
|
+
drivers.codex();
|
|
4218
|
+
return;
|
|
4219
|
+
default:
|
|
4220
|
+
noDriverFor(agent);
|
|
4221
|
+
}
|
|
4222
|
+
}
|
|
4223
|
+
function noDriverFor(_agent) {
|
|
4224
|
+
process.stderr.write(
|
|
4225
|
+
"AgentTrail enforcement for this agent is not available in this build; failing closed.\n"
|
|
4226
|
+
);
|
|
4227
|
+
process.exitCode = 2;
|
|
4228
|
+
}
|
|
4229
|
+
if (isDirectRun()) {
|
|
4230
|
+
const argv = process.argv.slice(2);
|
|
4231
|
+
dispatchHookRun(argv, {
|
|
4232
|
+
cursor: () => {
|
|
4233
|
+
const emitter = createRealCursorEmitter();
|
|
4234
|
+
process.on("uncaughtException", () => emitter.emitCrash());
|
|
4235
|
+
process.on("unhandledRejection", () => emitter.emitCrash());
|
|
4236
|
+
const cursorHome = homedir2();
|
|
4237
|
+
void runCursorShim({
|
|
4238
|
+
env: process.env,
|
|
4239
|
+
readStdin: readRealStdin,
|
|
4240
|
+
fetchFn: fetch,
|
|
4241
|
+
emitter,
|
|
4242
|
+
entryScope: scopeFromArgv(argv) ?? "project",
|
|
4243
|
+
home: cursorHome,
|
|
4244
|
+
config: resolveCursorPepConfig(cursorHome)
|
|
4245
|
+
});
|
|
4246
|
+
},
|
|
4247
|
+
codex: () => {
|
|
4248
|
+
const writeStderr = (text) => process.stderr.write(text);
|
|
4249
|
+
process.on("uncaughtException", () => {
|
|
4250
|
+
process.exitCode = 2;
|
|
4251
|
+
writeStderr(`${CODEX_ENFORCEMENT_UNAVAILABLE}
|
|
4252
|
+
`);
|
|
4253
|
+
});
|
|
4254
|
+
process.stderr.on("error", () => {
|
|
4255
|
+
});
|
|
4256
|
+
process.exitCode = runCodexShim({ writeStderr });
|
|
4257
|
+
},
|
|
4258
|
+
claude: () => {
|
|
4259
|
+
const emitter = createRealEmitter();
|
|
4260
|
+
process.on(
|
|
4261
|
+
"uncaughtException",
|
|
4262
|
+
() => emitter.emitCrashDeny(
|
|
4263
|
+
"AgentTrail enforcement crashed (uncaughtException); failing closed."
|
|
4264
|
+
)
|
|
4265
|
+
);
|
|
4266
|
+
process.on(
|
|
4267
|
+
"unhandledRejection",
|
|
4268
|
+
() => emitter.emitCrashDeny(
|
|
4269
|
+
"AgentTrail enforcement crashed (unhandledRejection); failing closed."
|
|
4270
|
+
)
|
|
4271
|
+
);
|
|
4272
|
+
void runShim({
|
|
4273
|
+
env: process.env,
|
|
4274
|
+
readStdin: readRealStdin,
|
|
4275
|
+
fetchFn: fetch,
|
|
4276
|
+
emitter,
|
|
4277
|
+
argv
|
|
4278
|
+
});
|
|
4279
|
+
}
|
|
4280
|
+
});
|
|
4281
|
+
}
|
|
4282
|
+
var CURSOR_BROKEN_INSTALL = "AgentTrail cannot read its project registry. Run setup again for this project.";
|
|
4283
|
+
var CURSOR_MISCONFIGURED = "AgentTrail enforcement is enabled here but misconfigured. Run setup again for this project.";
|
|
4284
|
+
var CURSOR_UNAUTHORIZED = "AgentTrail rejected the enforcement credential (401). Run login again for Cursor.";
|
|
4285
|
+
var CURSOR_NO_CACHE = "AgentTrail is unreachable and no local policy snapshot is cached; failing closed.";
|
|
4286
|
+
var CURSOR_UNANSWERED = "No reviewer answered in time \u2014 ask a reviewer to approve, then retry.";
|
|
4287
|
+
var CURSOR_HOLD_UNREACHABLE = "AgentTrail could not reach a reviewer for this action; failing closed.";
|
|
4288
|
+
var CURSOR_NO_CORRELATION = "AgentTrail could not request approval for this action; failing closed.";
|
|
4289
|
+
function cursorAnswerEventOf(event) {
|
|
4290
|
+
if (event === "preToolUse" || event === "beforeMCPExecution" || event === "beforeShellExecution") {
|
|
4291
|
+
return event;
|
|
4292
|
+
}
|
|
4293
|
+
return void 0;
|
|
4294
|
+
}
|
|
4295
|
+
function refuse(event, message) {
|
|
4296
|
+
return buildCursorAnswer({
|
|
4297
|
+
event,
|
|
4298
|
+
tool: "",
|
|
4299
|
+
outcome: event === "beforeShellExecution" ? { kind: "approval", message } : { kind: "deny", message }
|
|
4300
|
+
});
|
|
4301
|
+
}
|
|
4302
|
+
function matchesOf(response) {
|
|
4303
|
+
const matches = [];
|
|
4304
|
+
const names = {};
|
|
4305
|
+
for (const policy of response.matched_policies ?? []) {
|
|
4306
|
+
matches.push({ policyId: policy.id, action: policy.action });
|
|
4307
|
+
names[policy.id] = policy.name;
|
|
4308
|
+
}
|
|
4309
|
+
return { matches, names };
|
|
4310
|
+
}
|
|
4311
|
+
function cursorReason(verdict, name) {
|
|
4312
|
+
const named = name === null ? "" : ` "${name}"`;
|
|
4313
|
+
return verdict === "deny" ? `Blocked by AgentTrail policy${named}.` : `Approval required by AgentTrail policy${named}.`;
|
|
4314
|
+
}
|
|
4315
|
+
async function decideCursorCandidates(requests, cfg, deps) {
|
|
4316
|
+
const settled = await Promise.all(
|
|
4317
|
+
requests.map(async (request) => {
|
|
4318
|
+
try {
|
|
4319
|
+
return {
|
|
4320
|
+
ok: true,
|
|
4321
|
+
outcome: await evaluateViaPdp(
|
|
4322
|
+
{ url: cfg.url, token: cfg.token, request, timeoutMs: cfg.timeoutMs },
|
|
4323
|
+
deps.fetchFn
|
|
4324
|
+
)
|
|
4325
|
+
};
|
|
4326
|
+
} catch (err) {
|
|
4327
|
+
if (err instanceof PdpUnreachableError) return { ok: false };
|
|
4328
|
+
throw err;
|
|
4329
|
+
}
|
|
4330
|
+
})
|
|
4331
|
+
);
|
|
4332
|
+
if (settled.some((result) => !result.ok)) {
|
|
4333
|
+
const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
|
|
4334
|
+
if (!snapshot) {
|
|
4335
|
+
return {
|
|
4336
|
+
outcome: { kind: "deny", message: CURSOR_NO_CACHE },
|
|
4337
|
+
holdCandidate: null,
|
|
4338
|
+
policyId: null,
|
|
4339
|
+
via: "no-cache"
|
|
4340
|
+
};
|
|
4341
|
+
}
|
|
4342
|
+
const local = requests.map((request) => evaluateLocally(snapshot, request, cfg.orgId));
|
|
4343
|
+
return outcomeOf(local, "cached-rules");
|
|
4344
|
+
}
|
|
4345
|
+
const perCandidate = [];
|
|
4346
|
+
let refused = 0;
|
|
4347
|
+
for (const result of settled) {
|
|
4348
|
+
if (!result.ok) continue;
|
|
4349
|
+
const { outcome } = result;
|
|
4350
|
+
if (outcome.kind === "unauthorized") {
|
|
4351
|
+
return {
|
|
4352
|
+
outcome: { kind: "deny", message: CURSOR_UNAUTHORIZED },
|
|
4353
|
+
holdCandidate: null,
|
|
4354
|
+
policyId: null,
|
|
4355
|
+
via: "unauthorized"
|
|
4356
|
+
};
|
|
4357
|
+
}
|
|
4358
|
+
if (outcome.kind === "tier-disabled") {
|
|
4359
|
+
refused += 1;
|
|
4360
|
+
perCandidate.push({ matches: [], names: {} });
|
|
4361
|
+
continue;
|
|
4362
|
+
}
|
|
4363
|
+
perCandidate.push(matchesOf(outcome.response));
|
|
4364
|
+
}
|
|
4365
|
+
return outcomeOf(
|
|
4366
|
+
perCandidate,
|
|
4367
|
+
refused === perCandidate.length && refused > 0 ? "forbidden" : "pdp"
|
|
4368
|
+
);
|
|
4369
|
+
}
|
|
4370
|
+
function outcomeOf(perCandidate, via) {
|
|
4371
|
+
const combined = combineCandidateVerdicts(perCandidate.map((result) => result.matches));
|
|
4372
|
+
if (combined.verdict === "allow") {
|
|
4373
|
+
return { outcome: { kind: "none" }, holdCandidate: null, policyId: null, via };
|
|
4374
|
+
}
|
|
4375
|
+
const names = Object.assign({}, ...perCandidate.map((result) => result.names));
|
|
4376
|
+
const name = combined.policyId === null ? null : names[combined.policyId] ?? null;
|
|
4377
|
+
const message = cursorReason(combined.verdict, name);
|
|
4378
|
+
if (combined.verdict === "deny") {
|
|
4379
|
+
return {
|
|
4380
|
+
outcome: { kind: "deny", message },
|
|
4381
|
+
holdCandidate: null,
|
|
4382
|
+
policyId: combined.policyId,
|
|
4383
|
+
via
|
|
4384
|
+
};
|
|
4385
|
+
}
|
|
4386
|
+
return {
|
|
4387
|
+
outcome: { kind: "approval", message },
|
|
4388
|
+
// The candidate that produced the deciding policy — the one the hold route
|
|
4389
|
+
// re-evaluates. Any other would re-evaluate as a call the policy does not cover.
|
|
4390
|
+
holdCandidate: combined.candidateIndex,
|
|
4391
|
+
policyId: combined.policyId,
|
|
4392
|
+
via
|
|
4393
|
+
};
|
|
4394
|
+
}
|
|
4395
|
+
function decideCursorShell(join7, cfg, deps, request) {
|
|
4396
|
+
if (join7.kind === "handoff") {
|
|
4397
|
+
return { kind: "approval", message: "AgentTrail is waiting for approval of this command." };
|
|
4398
|
+
}
|
|
4399
|
+
if (join7.kind === "decided") return { kind: "none" };
|
|
4400
|
+
if (join7.liveHandoff) {
|
|
4401
|
+
return { kind: "approval", message: "AgentTrail is waiting for approval in this turn." };
|
|
4402
|
+
}
|
|
4403
|
+
const snapshot = readCachedSnapshot(cfg.snapshotPath, deps.snapshotIO);
|
|
4404
|
+
if (!snapshot || request === void 0) {
|
|
4405
|
+
return { kind: "approval", message: "AgentTrail could not check this command." };
|
|
4406
|
+
}
|
|
4407
|
+
const local = evaluateLocally(snapshot, request, cfg.orgId);
|
|
4408
|
+
if (local.verdict === "allow") return { kind: "none" };
|
|
4409
|
+
return { kind: "approval", message: cursorReason(local.verdict, local.decidingName) };
|
|
4410
|
+
}
|
|
4411
|
+
function outcomeOfHold(result) {
|
|
4412
|
+
switch (result.outcome) {
|
|
4413
|
+
case "approved":
|
|
4414
|
+
return { kind: "none" };
|
|
4415
|
+
case "denied":
|
|
4416
|
+
return { kind: "deny", message: "Denied by an AgentTrail reviewer." };
|
|
4417
|
+
case "forbidden":
|
|
4418
|
+
return { kind: "none" };
|
|
4419
|
+
case "unreachable":
|
|
4420
|
+
return { kind: "deny", message: CURSOR_HOLD_UNREACHABLE };
|
|
4421
|
+
case "no-correlation":
|
|
4422
|
+
return { kind: "deny", message: CURSOR_NO_CORRELATION };
|
|
4423
|
+
case "unanswered":
|
|
4424
|
+
return "split";
|
|
4425
|
+
}
|
|
4426
|
+
return assertNever(result.outcome);
|
|
4427
|
+
}
|
|
4428
|
+
function assertNever(outcome) {
|
|
4429
|
+
throw new Error(`AgentTrail could not answer an unknown hold outcome: ${String(outcome)}`);
|
|
4430
|
+
}
|
|
4431
|
+
async function runCursorShim(deps) {
|
|
4432
|
+
const schedule = deps.schedule ?? defaultSchedule;
|
|
4433
|
+
const now = deps.now ?? Date.now;
|
|
4434
|
+
const startedAtMs = now();
|
|
4435
|
+
const fire = () => deps.emitter.emitCrash();
|
|
4436
|
+
let cancelWatchdog = schedule(fire, deps.watchdogMs ?? PEP_WATCHDOG_MS);
|
|
4437
|
+
const extendDeadline = (ms) => {
|
|
4438
|
+
cancelWatchdog();
|
|
4439
|
+
cancelWatchdog = schedule(fire, ms);
|
|
4440
|
+
};
|
|
4441
|
+
try {
|
|
4442
|
+
const answer = await answerCursor({ extendDeadline, ...deps }, startedAtMs);
|
|
4443
|
+
cancelWatchdog();
|
|
4444
|
+
deps.emitter.emitAnswer(answer);
|
|
4445
|
+
} catch {
|
|
4446
|
+
cancelWatchdog();
|
|
4447
|
+
deps.emitter.emitCrash();
|
|
4448
|
+
}
|
|
4449
|
+
}
|
|
4450
|
+
async function answerCursor(deps, startedAtMs) {
|
|
4451
|
+
const payload = parsePayload(await deps.readStdin());
|
|
4452
|
+
const event = cursorAnswerEventOf(payload.hook_event_name);
|
|
4453
|
+
if (event === void 0) return CURSOR_NO_OPINION;
|
|
4454
|
+
const normalized = normalizeCursorPayload(payload);
|
|
4455
|
+
const workspaceRoots = Array.isArray(payload.workspace_roots) ? payload.workspace_roots.filter((path) => typeof path === "string") : [];
|
|
4456
|
+
const lookup = lookupCursorWorkspace({
|
|
4457
|
+
home: deps.home,
|
|
4458
|
+
workspaceRoots,
|
|
4459
|
+
// From the ENVIRONMENT, which is where Cursor puts it (915 of 915 recorded hook runs),
|
|
4460
|
+
// and not from the payload, which never carries it (0 of 983). Capture's hook read the
|
|
4461
|
+
// env var from the start; this branch read a payload field that does not exist, so the
|
|
4462
|
+
// subfolder rule below it — a folder setup ran in wins over the workspace root, with
|
|
4463
|
+
// ITS install scope (Q4) — could not fire. An empty value is absence, not a path.
|
|
4464
|
+
projectDirEnv: deps.env.CURSOR_PROJECT_DIR || void 0,
|
|
4465
|
+
io: deps.io,
|
|
4466
|
+
realpath: deps.realpath
|
|
4467
|
+
});
|
|
4468
|
+
switch (lookup.kind) {
|
|
4469
|
+
case "registry-unreadable":
|
|
4470
|
+
case "record-damaged":
|
|
4471
|
+
return refuse(event, CURSOR_BROKEN_INSTALL);
|
|
4472
|
+
case "not-registered":
|
|
4473
|
+
return deps.entryScope === "user" ? refuse(event, CURSOR_BROKEN_INSTALL) : CURSOR_NO_OPINION;
|
|
4474
|
+
case "ok":
|
|
4475
|
+
break;
|
|
4476
|
+
}
|
|
4477
|
+
if (!entryOwnsFolder(lookup.folder, deps.entryScope)) return CURSOR_NO_OPINION;
|
|
4478
|
+
const record = (answer2, fields) => {
|
|
4479
|
+
const vendorTool = fields.vendorTool ?? normalized?.vendorTool ?? cursorVendorTool(payload);
|
|
4480
|
+
if (vendorTool === void 0) {
|
|
4481
|
+
throw new Error("AgentTrail could not label this call to record its decision");
|
|
4482
|
+
}
|
|
4483
|
+
writeDecisionRecord({
|
|
4484
|
+
home: deps.home,
|
|
4485
|
+
io: deps.io ?? nodeCaptureFileIO,
|
|
4486
|
+
projectKey: lookup.record.projectKey,
|
|
4487
|
+
hookEvent: event,
|
|
4488
|
+
vendorTool,
|
|
4489
|
+
candidates: normalized?.candidates ?? [],
|
|
4490
|
+
toolInput: payload.tool_input,
|
|
4491
|
+
commandText: cursorCommandText(payload),
|
|
4492
|
+
conversationId: nonEmptyString(payload.conversation_id),
|
|
4493
|
+
generationId: nonEmptyString(payload.generation_id),
|
|
4494
|
+
toolUseId: fields.toolUseId ?? normalized?.correlationId ?? null,
|
|
4495
|
+
...fields.toolUseIdFrom === void 0 ? {} : { toolUseIdFrom: fields.toolUseIdFrom },
|
|
4496
|
+
captureContent: lookup.record.captureContent,
|
|
4497
|
+
decidedAtMs: clock(),
|
|
4498
|
+
decisionMs: clock() - startedAtMs,
|
|
4499
|
+
verdict: fields.verdict,
|
|
4500
|
+
policyId: fields.policyId ?? null,
|
|
4501
|
+
candidateIndex: fields.candidateIndex ?? null,
|
|
4502
|
+
via: fields.via,
|
|
4503
|
+
blocked: answerBlocks(answer2),
|
|
4504
|
+
...fields.hold === void 0 ? {} : { hold: fields.hold }
|
|
4505
|
+
});
|
|
4506
|
+
return answer2;
|
|
4507
|
+
};
|
|
4508
|
+
const clock = deps.now ?? Date.now;
|
|
4509
|
+
const cfg = deps.config;
|
|
4510
|
+
if (cfg === void 0) {
|
|
4511
|
+
return record(refuse(event, CURSOR_MISCONFIGURED), {
|
|
4512
|
+
verdict: event === "beforeShellExecution" ? "require_approval" : "deny",
|
|
4513
|
+
via: "misconfigured"
|
|
4514
|
+
});
|
|
4515
|
+
}
|
|
4516
|
+
if (event === "beforeShellExecution") {
|
|
4517
|
+
const request = normalized?.candidates[0];
|
|
4518
|
+
const join7 = (deps.shellJoin ?? readShellJoin)(
|
|
4519
|
+
joinQueryFor({
|
|
4520
|
+
home: deps.home,
|
|
4521
|
+
io: deps.io,
|
|
4522
|
+
projectKey: lookup.record.projectKey,
|
|
4523
|
+
normalized,
|
|
4524
|
+
vendorTool: normalized?.vendorTool,
|
|
4525
|
+
toolInput: payload.tool_input,
|
|
4526
|
+
conversationId: nonEmptyString(payload.conversation_id),
|
|
4527
|
+
generationId: nonEmptyString(payload.generation_id),
|
|
4528
|
+
nowMs: clock()
|
|
4529
|
+
})
|
|
4530
|
+
);
|
|
4531
|
+
const outcome = decideCursorShell(
|
|
4532
|
+
join7,
|
|
4533
|
+
cfg,
|
|
4534
|
+
deps,
|
|
4535
|
+
request === void 0 ? void 0 : { tool: request.tool, args: { ...request.args } }
|
|
4536
|
+
);
|
|
4537
|
+
return record(buildCursorAnswer({ event, tool: "", outcome }), {
|
|
4538
|
+
verdict: verdictOf(outcome),
|
|
4539
|
+
// This checkpoint asks no one: it answers from the queue, or from the cached rules
|
|
4540
|
+
// when the queue has nothing to say.
|
|
4541
|
+
via: join7.kind === "miss" ? "cached-rules" : "pdp"
|
|
4542
|
+
});
|
|
4543
|
+
}
|
|
4544
|
+
const requests = buildCursorPdpRequest(payload);
|
|
4545
|
+
if (requests === void 0 || normalized === void 0) {
|
|
4546
|
+
const label = cursorVendorTool(payload);
|
|
4547
|
+
const mcp = label?.startsWith(CURSOR_MCP_PREFIX);
|
|
4548
|
+
return record(CURSOR_NO_OPINION, {
|
|
4549
|
+
verdict: "observed",
|
|
4550
|
+
via: "pdp",
|
|
4551
|
+
...mcp === true && label !== void 0 ? { vendorTool: label, toolUseId: correlationIdFor(payload.tool_use_id) } : (
|
|
4552
|
+
// Not an MCP call and not mappable: nothing to record it under, and nothing
|
|
4553
|
+
// will look for it.
|
|
4554
|
+
{}
|
|
4555
|
+
)
|
|
4556
|
+
});
|
|
4557
|
+
}
|
|
4558
|
+
const scoped = withScope(requests, cursorScopeFor(lookup.record, cfg.agentId));
|
|
4559
|
+
const decision = await decideCursorCandidates(scoped, cfg, deps);
|
|
4560
|
+
const tool = normalized.vendorTool;
|
|
4561
|
+
const decided = {
|
|
4562
|
+
verdict: verdictOf(decision.outcome),
|
|
4563
|
+
via: decision.via,
|
|
4564
|
+
policyId: decision.policyId,
|
|
4565
|
+
candidateIndex: decision.holdCandidate
|
|
4566
|
+
};
|
|
4567
|
+
if (decision.outcome.kind !== "approval") {
|
|
4568
|
+
return record(buildCursorAnswer({ event, tool, outcome: decision.outcome }), decided);
|
|
4569
|
+
}
|
|
4570
|
+
const now = deps.now ?? Date.now;
|
|
4571
|
+
const held = scoped[decision.holdCandidate ?? 0] ?? scoped[0];
|
|
4572
|
+
if (held === void 0) {
|
|
4573
|
+
return record(buildCursorAnswer({ event, tool, outcome: decision.outcome }), decided);
|
|
4574
|
+
}
|
|
4575
|
+
const correlationId = event === "beforeMCPExecution" ? (deps.recoverMcpCorrelationId ?? readMcpCorrelationId)(
|
|
4576
|
+
joinQueryFor({
|
|
4577
|
+
home: deps.home,
|
|
4578
|
+
io: deps.io,
|
|
4579
|
+
projectKey: lookup.record.projectKey,
|
|
4580
|
+
normalized,
|
|
4581
|
+
vendorTool: normalized.vendorTool,
|
|
4582
|
+
toolInput: payload.tool_input,
|
|
4583
|
+
conversationId: nonEmptyString(payload.conversation_id),
|
|
4584
|
+
generationId: nonEmptyString(payload.generation_id),
|
|
4585
|
+
nowMs: clock()
|
|
4586
|
+
})
|
|
4587
|
+
) : normalized.correlationId;
|
|
4588
|
+
const hold = await holdCursorApproval({
|
|
4589
|
+
cfg,
|
|
4590
|
+
fetchFn: deps.fetchFn,
|
|
4591
|
+
request: held,
|
|
4592
|
+
correlationId,
|
|
4593
|
+
elapsedMs: now() - startedAtMs,
|
|
4594
|
+
extendDeadline: deps.extendDeadline
|
|
4595
|
+
});
|
|
4596
|
+
const heldFields = {
|
|
4597
|
+
...decided,
|
|
4598
|
+
...hold.outcome === "forbidden" ? { via: "forbidden" } : {},
|
|
4599
|
+
toolUseId: correlationId,
|
|
4600
|
+
toolUseIdFrom: event === "beforeMCPExecution" ? "queue" : "payload",
|
|
4601
|
+
...hold.outcome === "forbidden" ? {} : {
|
|
4602
|
+
hold: {
|
|
4603
|
+
correlationId: hold.correlationId ?? "",
|
|
4604
|
+
windowSeconds: hold.windowSeconds ?? 0,
|
|
4605
|
+
outcome: hold.outcome
|
|
4606
|
+
}
|
|
4607
|
+
}
|
|
4608
|
+
};
|
|
4609
|
+
const mapped = outcomeOfHold(hold);
|
|
4610
|
+
if (mapped !== "split") {
|
|
4611
|
+
return record(buildCursorAnswer({ event, tool, outcome: mapped }), heldFields);
|
|
4612
|
+
}
|
|
4613
|
+
const unanswered = { kind: "approval", message: CURSOR_UNANSWERED };
|
|
4614
|
+
if (tool !== CURSOR_SHELL_TOOL) {
|
|
4615
|
+
return record(buildCursorAnswer({ event, tool, outcome: unanswered }), heldFields);
|
|
4616
|
+
}
|
|
4617
|
+
const handoff = offerHandoff({
|
|
4618
|
+
payload,
|
|
4619
|
+
normalized,
|
|
4620
|
+
lookup,
|
|
4621
|
+
cfg,
|
|
4622
|
+
deps,
|
|
4623
|
+
decision,
|
|
4624
|
+
hold,
|
|
4625
|
+
decidedAtMs: now(),
|
|
4626
|
+
decisionMs: now() - startedAtMs
|
|
4627
|
+
});
|
|
4628
|
+
const answer = buildCursorAnswer({ event, tool, outcome: unanswered, handoff });
|
|
4629
|
+
return handoff ? answer : record(answer, heldFields);
|
|
4630
|
+
}
|
|
4631
|
+
function verdictOf(outcome) {
|
|
4632
|
+
switch (outcome.kind) {
|
|
4633
|
+
case "none":
|
|
4634
|
+
return "allow";
|
|
4635
|
+
case "deny":
|
|
4636
|
+
return "deny";
|
|
4637
|
+
case "approval":
|
|
4638
|
+
return "require_approval";
|
|
4639
|
+
}
|
|
4640
|
+
}
|
|
4641
|
+
function offerHandoff(input) {
|
|
4642
|
+
if (enforcementSupport(input.payload.cursor_version) !== "supported") return false;
|
|
4643
|
+
const conversationId = nonEmptyString(input.payload.conversation_id);
|
|
4644
|
+
const generationId = nonEmptyString(input.payload.generation_id);
|
|
4645
|
+
if (conversationId === null || generationId === null) return false;
|
|
4646
|
+
if (input.deps.entryScope === "user" && input.cfg.userScopeHandoff !== true) return false;
|
|
4647
|
+
return writeHandoffRecord({
|
|
4648
|
+
home: input.deps.home,
|
|
4649
|
+
io: input.deps.io ?? nodeCaptureFileIO,
|
|
4650
|
+
projectKey: input.lookup.record.projectKey,
|
|
4651
|
+
vendorTool: input.normalized.vendorTool,
|
|
4652
|
+
candidates: input.normalized.candidates,
|
|
4653
|
+
toolInput: input.payload.tool_input,
|
|
4654
|
+
commandText: cursorCommandText(input.payload),
|
|
4655
|
+
conversationId,
|
|
4656
|
+
generationId,
|
|
4657
|
+
toolUseId: input.normalized.correlationId,
|
|
4658
|
+
captureContent: input.lookup.record.captureContent,
|
|
4659
|
+
decidedAtMs: input.decidedAtMs,
|
|
4660
|
+
decisionMs: input.decisionMs,
|
|
4661
|
+
policyId: input.decision.policyId,
|
|
4662
|
+
candidateIndex: input.decision.holdCandidate,
|
|
4663
|
+
hold: {
|
|
4664
|
+
correlationId: input.hold.correlationId ?? "",
|
|
4665
|
+
windowSeconds: input.hold.windowSeconds ?? 0,
|
|
4666
|
+
outcome: "unanswered"
|
|
4667
|
+
}
|
|
4668
|
+
});
|
|
4669
|
+
}
|
|
4670
|
+
function nonEmptyString(value) {
|
|
4671
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
4672
|
+
}
|
|
4673
|
+
export {
|
|
4674
|
+
CODEX_ENFORCEMENT_UNAVAILABLE,
|
|
4675
|
+
HOOK_OUTCOMES,
|
|
4676
|
+
MAX_DETAIL_LEN,
|
|
4677
|
+
PEP_VENDOR,
|
|
4678
|
+
TRUNCATION_MARKER,
|
|
4679
|
+
buildHookOutput,
|
|
4680
|
+
buildPdpRequest,
|
|
4681
|
+
createRealEmitter,
|
|
4682
|
+
decide,
|
|
4683
|
+
dispatchHookRun,
|
|
4684
|
+
evaluateLocally,
|
|
4685
|
+
handleApproval,
|
|
4686
|
+
parsePayload,
|
|
4687
|
+
runCodexShim,
|
|
4688
|
+
runCursorShim,
|
|
4689
|
+
runShim
|
|
4690
|
+
};
|