@akasecurity/ai-tc-codex 0.9.16 → 0.9.17

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.
@@ -1,885 +1,8 @@
1
- var __create = Object.create;
2
1
  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
- try {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- } catch (e) {
11
- throw mod = 0, e;
12
- }
13
- };
14
2
  var __export = (target, all) => {
15
3
  for (var name in all)
16
4
  __defProp(target, name, { get: all[name], enumerable: true });
17
5
  };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
-
35
- // ../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js
36
- var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.11/node_modules/ignore/index.js"(exports, module) {
38
- "use strict";
39
- function makeArray(subject) {
40
- return Array.isArray(subject) ? subject : [subject];
41
- }
42
- var UNDEFINED = void 0;
43
- var EMPTY = "";
44
- var SPACE = " ";
45
- var ESCAPE = "\\";
46
- var REGEX_LITERAL_SPECIAL = /[.*+?()[\]{}^$|\\/]/;
47
- var REGEX_TEST_BLANK_LINE = /^\uFEFF? *$/;
48
- var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
49
- var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
50
- var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
51
- var REGEX_SPLITALL_CRLF = /\r?\n/g;
52
- var DOUBLE_SLASH = "//";
53
- var SLASH_CODE = 47;
54
- var DOT_CODE = 46;
55
- var SLASH3 = "/";
56
- var TMP_KEY_IGNORE = "node-ignore";
57
- if (typeof Symbol !== "undefined") {
58
- TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
59
- }
60
- var KEY_IGNORE = TMP_KEY_IGNORE;
61
- var define = (object2, key, value) => {
62
- Object.defineProperty(object2, key, { value });
63
- return value;
64
- };
65
- var RETURN_FALSE = () => false;
66
- var cleanRangeBackSlash = (slashes) => {
67
- const { length } = slashes;
68
- return slashes.slice(0, length - length % 2);
69
- };
70
- var POSIX_CLASSES = {
71
- alnum: "0-9A-Za-z",
72
- alpha: "A-Za-z",
73
- blank: " \\t",
74
- cntrl: "\\x00-\\x1f\\x7f",
75
- digit: "0-9",
76
- graph: "!-.0-~",
77
- lower: "a-z",
78
- print: " -.0-~",
79
- punct: "!-.:-@\\[-`{-~",
80
- // git's `sane-ctype.h` classifies \v and \f as control, not space,
81
- // unlike C's `isspace`
82
- space: " \\t\\n\\r",
83
- upper: "A-Z",
84
- xdigit: "0-9A-Fa-f"
85
- };
86
- var CLASS_MEMBERS_TO_ESCAPE = "\\]^-[";
87
- var escapeMember = (char) => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0 ? char : ESCAPE + char;
88
- var NON_SLASH = "(?!\\/)";
89
- var classSource = (negated, body) => {
90
- if (negated) {
91
- return `[^\\/${body}]`;
92
- }
93
- const source = `[${body}]`;
94
- return new RegExp(source).test("/") ? NON_SLASH + source : source;
95
- };
96
- var scanBracket = (pattern, start) => {
97
- const { length } = pattern;
98
- let index = start + 1;
99
- let negated = EMPTY;
100
- const lead = pattern[index];
101
- if (lead === "!" || lead === "^") {
102
- negated = "^";
103
- index++;
104
- }
105
- let body = EMPTY;
106
- let prev = EMPTY;
107
- for (; ; ) {
108
- const char = pattern[index];
109
- if (char === UNDEFINED) {
110
- return null;
111
- }
112
- if (char === ESCAPE) {
113
- const escaped = pattern[index + 1];
114
- if (escaped === UNDEFINED) {
115
- return null;
116
- }
117
- body += escapeMember(escaped);
118
- prev = escaped;
119
- index++;
120
- } else if (char === "-" && prev && index + 1 < length && pattern[index + 1] !== "]") {
121
- index++;
122
- let to = pattern[index];
123
- if (to === ESCAPE) {
124
- to = pattern[index += 1];
125
- }
126
- if (prev <= to) {
127
- body += `-${escapeMember(to)}`;
128
- }
129
- prev = EMPTY;
130
- } else if (char === "[" && pattern[index + 1] === ":") {
131
- const nameStart = index + 2;
132
- let end = nameStart;
133
- while (end < length && pattern[end] !== "]") {
134
- end++;
135
- }
136
- if (end === length) {
137
- return null;
138
- }
139
- if (end > nameStart && pattern[end - 1] === ":") {
140
- const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)];
141
- if (expanded === UNDEFINED) {
142
- return null;
143
- }
144
- body += expanded;
145
- prev = EMPTY;
146
- index = end;
147
- } else {
148
- body += escapeMember("[");
149
- prev = "[";
150
- index = nameStart - 2;
151
- }
152
- } else {
153
- body += escapeMember(char);
154
- prev = char;
155
- }
156
- index++;
157
- if (pattern[index] === "]") {
158
- return {
159
- end: index,
160
- source: classSource(negated, body)
161
- };
162
- }
163
- }
164
- };
165
- var NEVER_MATCH = "[]";
166
- var PLACEHOLDER = "\0";
167
- var REGEX_RESTORE_PLACEHOLDER = new RegExp(
168
- `${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,
169
- "g"
170
- );
171
- var TRAILING_WILDCARD = "\uE000";
172
- var TRAILING_DOUBLESTAR = "\uE001";
173
- var extractBrackets = (pattern) => {
174
- const sources = [];
175
- const hold = (source) => `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`;
176
- const { length } = pattern;
177
- let out = EMPTY;
178
- let index = 0;
179
- while (index < length) {
180
- const char = pattern[index];
181
- if (char === ESCAPE) {
182
- const escaped = pattern[index + 1];
183
- if (escaped === "*" || escaped === "[" || escaped === SPACE || escaped === ESCAPE) {
184
- out += pattern.slice(index, index + 2);
185
- } else {
186
- out += hold(
187
- REGEX_LITERAL_SPECIAL.test(escaped) ? ESCAPE + escaped : escaped
188
- );
189
- }
190
- index += 2;
191
- } else if (char === PLACEHOLDER) {
192
- out += hold(`[${PLACEHOLDER}]`);
193
- index++;
194
- } else if (char === "[") {
195
- const scanned = scanBracket(pattern, index);
196
- if (scanned === null) {
197
- out += hold(NEVER_MATCH);
198
- index = length;
199
- } else {
200
- out += hold(scanned.source);
201
- index = scanned.end + 1;
202
- }
203
- } else {
204
- out += char;
205
- index++;
206
- }
207
- }
208
- return {
209
- source: out,
210
- sources
211
- };
212
- };
213
- var DIRECT = null;
214
- var REGEX_INNER_SLASH = /\/(?!$)/;
215
- var REPLACERS = [
216
- [
217
- // Remove BOM
218
- // TODO:
219
- // Other similar zero-width characters?
220
- /^\uFEFF/,
221
- () => EMPTY,
222
- "\uFEFF"
223
- ],
224
- [
225
- // A trailing line terminator, left on when a whole file's contents are
226
- // added as one pattern rather than split into lines. git never sees one
227
- // -- it reads a `.gitignore` line by line -- so it is not part of the
228
- // pattern and is dropped here, apart from the trailing-space trimming,
229
- // which follows git in touching spaces and nothing else.
230
- /[\r\n]+$/,
231
- () => EMPTY
232
- ],
233
- // > Trailing spaces are ignored unless they are quoted with backslash ("\")
234
- [
235
- // Only spaces, never tabs or other whitespace: git trims a trailing run
236
- // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single
237
- // `case ' '`), so a pattern ending in a tab keeps it as a literal.
238
- // (a\ ) -> (a )
239
- // (a ) -> (a)
240
- // (a ) -> (a)
241
- // (a \ ) -> (a )
242
- /((?:\\\\)*?)(\\? +)$/,
243
- (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
244
- ],
245
- // Replace (\ ) with ' '
246
- // Only a space: an escaped tab or other whitespace is already a literal by
247
- // the time it reaches here, and a bare tab must be left as one, not turned
248
- // into a space.
249
- // (\ ) -> ' '
250
- // (\\ ) -> '\\ '
251
- // (\\\ ) -> '\\ '
252
- [
253
- /(\\+?) /g,
254
- (_, m1) => {
255
- const { length } = m1;
256
- return m1.slice(0, length - length % 2) + SPACE;
257
- }
258
- ],
259
- // Escape metacharacters
260
- // which is written down by users but means special for regular expressions.
261
- // > There are 12 characters with special meanings:
262
- // > - the backslash \,
263
- // > - the caret ^,
264
- // > - the dollar sign $,
265
- // > - the period or dot .,
266
- // > - the vertical bar or pipe symbol |,
267
- // > - the question mark ?,
268
- // > - the asterisk or star *,
269
- // > - the plus sign +,
270
- // > - the opening parenthesis (,
271
- // > - the closing parenthesis ),
272
- // > - and the opening square bracket [,
273
- // > - the opening curly brace {,
274
- // > These special characters are often called "metacharacters".
275
- [
276
- /[\\$.|*+(){^]/g,
277
- (match) => `\\${match}`
278
- ],
279
- [
280
- // > a question mark (?) matches a single character
281
- /(?!\\)\?/g,
282
- () => "[^/]",
283
- "?"
284
- ],
285
- // leading slash
286
- [
287
- // > A leading slash matches the beginning of the pathname.
288
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
289
- // A leading slash matches the beginning of the pathname
290
- /^\//,
291
- () => "^",
292
- SLASH3
293
- ],
294
- // replace special metacharacter slash after the leading slash
295
- [
296
- /\//g,
297
- () => "\\/",
298
- SLASH3
299
- ],
300
- [
301
- // > A leading "**" followed by a slash means match in all directories.
302
- // > For example, "**/foo" matches file or directory "foo" anywhere,
303
- // > the same as pattern "foo".
304
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
305
- // > under directory "foo".
306
- // Notice that the '*'s have been replaced as '\\*'
307
- /^\^*(?:\\\*\\\*\\\/)+/,
308
- // '**/foo' <-> 'foo'
309
- () => "^(?:.*\\/)?",
310
- "*"
311
- ],
312
- // starting
313
- [
314
- // there will be no leading '/'
315
- // (which has been replaced by section "leading slash")
316
- // If starts with '**', adding a '^' to the regular expression also works
317
- DIRECT,
318
- (source, pattern) => {
319
- if (!source || source[0] === "^") {
320
- return source;
321
- }
322
- const anchor2 = !REGEX_INNER_SLASH.test(pattern) ? "(?:^|\\/)" : "^";
323
- return anchor2 + source;
324
- }
325
- ],
326
- // two globstars
327
- [
328
- // Use lookahead assertions so that we could match more than one `'/**'`
329
- /\\\/\\\*\\\*(?=\\\/|$)/g,
330
- // Zero, one or several directories
331
- // should not use '*', or it will be replaced by the next replacer
332
- // Check if it is not the last `'/**'`
333
- (_, index, str2) => index + 6 < str2.length ? str2.slice(index + 6) === "\\/" ? "(?:\\/[^\\/]+)+" : "(?:\\/[^\\/]+)*" : `\\/${TRAILING_DOUBLESTAR}`,
334
- "*"
335
- ],
336
- // normal intermediate wildcards
337
- [
338
- // Never replace escaped '*'
339
- // ignore rule '\*' will match the path '*'
340
- // 'abc.*/' -> go
341
- // 'abc.*' -> skip this rule,
342
- // coz trailing single wildcard will be handed by [trailing wildcard]
343
- /(^|[^\\]+)(\\\*)+(?=.+)/g,
344
- // '*.js' matches '.js'
345
- // '*.js' doesn't match 'abc'
346
- (_, p1, p2) => {
347
- const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
348
- return p1 + unescaped;
349
- },
350
- "*"
351
- ],
352
- // trailing wildcard, held apart from a literal star
353
- [
354
- // The step above leaves a trailing `*` alone, so a single `\*` is all that
355
- // can be left at the end here. Whether it is a wildcard or a literal
356
- // turns on the backslashes the user put in front of it: the escaper has
357
- // since doubled every one, so what stands here is those `2N` doubled
358
- // backslashes and then the star's own escape. An even number of the
359
- // original `N` leaves the star unescaped -- a wildcard -- and an odd
360
- // number escapes it -- a literal. This runs while the two are still
361
- // distinct, before the unescape steps below collapse the literal onto
362
- // the very `\*` a wildcard leaves behind.
363
- /(^|[^\\])((?:\\\\)*)\\\*$/,
364
- (match, p1, p2) => (
365
- // `p2` holds the doubled user backslashes; half of them is `N`.
366
- p2.length / 2 % 2 === 0 ? p1 + p2 + TRAILING_WILDCARD : match
367
- ),
368
- "*"
369
- ],
370
- [
371
- // unescape, revert step 3 except for back slash
372
- // For example, if a user escape a '\\*',
373
- // after step 3, the result will be '\\\\\\*'
374
- /\\\\\\(?=[$.|*+(){^])/g,
375
- () => ESCAPE,
376
- ESCAPE + ESCAPE
377
- ],
378
- [
379
- // '\\\\' -> '\\'
380
- /\\\\/g,
381
- () => ESCAPE,
382
- ESCAPE + ESCAPE
383
- ],
384
- [
385
- // Every real bracket expression -- POSIX classes included -- has already
386
- // been held aside by `extractBrackets`, so the only `[` left in the
387
- // pattern is an escaped, literal one.
388
- // `\` is escaped by step 3
389
- /\\\[([^\]/]*?)(\\*)($|\])/g,
390
- // '\\[bar]' -> '\\\\[bar\\]'
391
- (match, range, endEscape, close) => `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,
392
- "["
393
- ],
394
- // ending
395
- [
396
- // 'js' will not match 'js.'
397
- // 'ab' will not match 'abc'
398
- DIRECT,
399
- // WTF!
400
- // https://git-scm.com/docs/gitignore
401
- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
402
- // which re-fixes #24, #38
403
- // > If there is a separator at the end of the pattern then the pattern
404
- // > will only match directories, otherwise the pattern can match both
405
- // > files and directories.
406
- // 'js*' will not match 'a.js'
407
- // 'js/' will not match 'a.js'
408
- // 'js' will match 'a.js' and 'a.js/'
409
- (source) => {
410
- const last = source[source.length - 1];
411
- if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
412
- return source;
413
- }
414
- return last === SLASH3 ? `${source}$` : `${source}(?=$|\\/$)`;
415
- }
416
- ]
417
- ];
418
- var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\uE000$/;
419
- var MODE_IGNORE = "regex";
420
- var MODE_CHECK_IGNORE = "checkRegex";
421
- var UNDERSCORE = "_";
422
- var replaceTrailingWildcard = (_, p1) => {
423
- const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
424
- return `${prefix}(?=$|\\/$)`;
425
- };
426
- var REGEX_REPLACE_TRAILING_DOUBLESTAR = /\uE001$/;
427
- var replaceTrailingDoublestar = () => ".+(?=$|\\/$)";
428
- var WILDCARD = "[^\\/]*";
429
- var separatorAfter = (run, at) => {
430
- let separator = EMPTY;
431
- for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
432
- separator += run[index].single;
433
- }
434
- return separator;
435
- };
436
- var pinWildcards = (source) => {
437
- if (source.indexOf(WILDCARD) < 0) {
438
- return source;
439
- }
440
- const tokens = [];
441
- const { length } = source;
442
- let index = 0;
443
- while (index < length) {
444
- const char = source[index];
445
- if (source.startsWith(WILDCARD, index)) {
446
- tokens.push({ wildcard: true });
447
- index += WILDCARD.length;
448
- } else if (char === "[") {
449
- let end = index + 1;
450
- if (source[end] === "^") {
451
- end++;
452
- }
453
- if (source[end] === "]") {
454
- end++;
455
- }
456
- while (end < length && source[end] !== "]") {
457
- end += source[end] === ESCAPE ? 2 : 1;
458
- }
459
- end++;
460
- tokens.push({ single: source.slice(index, end) });
461
- index = end;
462
- } else if (char === ESCAPE) {
463
- tokens.push({ single: source.slice(index, index + 2) });
464
- index += 2;
465
- } else if (char === "(") {
466
- let depth = 0;
467
- let end = index;
468
- do {
469
- if (source[end] === ESCAPE) {
470
- end++;
471
- } else if (source[end] === "(") {
472
- depth++;
473
- } else if (source[end] === ")") {
474
- depth--;
475
- }
476
- end++;
477
- } while (end < length && depth > 0);
478
- if ("*+?".indexOf(source[end]) >= 0) {
479
- end++;
480
- }
481
- tokens.push({ boundary: source.slice(index, end) });
482
- index = end;
483
- } else if (char === "^" || char === "$") {
484
- tokens.push({ boundary: char });
485
- index++;
486
- } else {
487
- tokens.push({ single: char });
488
- index++;
489
- }
490
- }
491
- let out = EMPTY;
492
- let run = [];
493
- const flush = () => {
494
- let lastWildcard;
495
- run.forEach((token, at) => {
496
- if (token.wildcard) {
497
- lastWildcard = at;
498
- }
499
- });
500
- run.forEach((token, at) => {
501
- if (!token.wildcard) {
502
- out += token.single;
503
- return;
504
- }
505
- out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
506
- });
507
- run = [];
508
- };
509
- tokens.forEach((token) => {
510
- if (token.boundary === void 0) {
511
- run.push(token);
512
- return;
513
- }
514
- flush();
515
- out += token.boundary;
516
- });
517
- flush();
518
- return out;
519
- };
520
- var makeRegexPrefix = (pattern) => {
521
- const { source, sources } = extractBrackets(pattern);
522
- const replaced = REPLACERS.reduce(
523
- // A pass whose matcher finds nothing hands back the very string it was
524
- // given, so asking first costs a search and saves a rewrite. Ten of the
525
- // fifteen passes never fire for a typical .gitignore line, and between
526
- // them they were 45% of this chain.
527
- (prev, [matcher, replacer, required2]) => {
528
- if (matcher === DIRECT) {
529
- return replacer(prev, pattern);
530
- }
531
- if (required2 !== UNDEFINED && prev.indexOf(required2) < 0) {
532
- return prev;
533
- }
534
- return matcher.test(prev) ? prev.replace(matcher, replacer.bind(pattern)) : prev;
535
- },
536
- source
537
- );
538
- return sources.length ? replaced.replace(
539
- REGEX_RESTORE_PLACEHOLDER,
540
- (match, index) => sources[index]
541
- ) : replaced;
542
- };
543
- var checkSourceOf = (body, prefix) => {
544
- if (body[body.length - 1] === SLASH3) {
545
- prefix = makeRegexPrefix(body.slice(0, -1));
546
- }
547
- const head = prefix.slice(0, -1);
548
- const last = prefix[prefix.length - 1];
549
- return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
550
- };
551
- var matchesBasename = (body) => {
552
- const index = body.indexOf(SLASH3);
553
- return index < 0 || index === body.length - 1;
554
- };
555
- var basenameOf = (path) => {
556
- const end = path.length - 1;
557
- const index = path.lastIndexOf(
558
- SLASH3,
559
- path[end] === SLASH3 ? end - 1 : end
560
- );
561
- return index < 0 ? path : path.slice(index + 1);
562
- };
563
- var parentOf = (path) => {
564
- if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
565
- const slices = path.split(SLASH3).filter(Boolean);
566
- slices.pop();
567
- return slices.length ? slices.join(SLASH3) + SLASH3 : EMPTY;
568
- }
569
- const end = path.length - 1;
570
- const cut = path.lastIndexOf(
571
- SLASH3,
572
- path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
573
- );
574
- return cut < 0 ? EMPTY : path.slice(0, cut + 1);
575
- };
576
- var isString = (subject) => typeof subject === "string";
577
- var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
578
- var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
579
- var IgnoreRule = class {
580
- constructor(pattern, mark, body, ignoreCase, negative, prefix) {
581
- this.pattern = pattern;
582
- this.mark = mark;
583
- this.negative = negative;
584
- define(this, "body", body);
585
- define(this, "ignoreCase", ignoreCase);
586
- define(this, "regexPrefix", prefix);
587
- }
588
- // Worked out on first use and kept behind an own property, the way `regex`
589
- // caches itself in `_regex`. Deciding it in the constructor instead would
590
- // add a fourth `defineProperty` to every rule ever built, which cost 4% of
591
- // every compile -- including the compiles of rules that are never matched
592
- // against anything.
593
- get _basenameOnly() {
594
- return define(this, "_basenameOnly", matchesBasename(this.body));
595
- }
596
- get regex() {
597
- const key = UNDERSCORE + MODE_IGNORE;
598
- if (this[key]) {
599
- return this[key];
600
- }
601
- return this._make(MODE_IGNORE, key);
602
- }
603
- get checkRegex() {
604
- const key = UNDERSCORE + MODE_CHECK_IGNORE;
605
- if (this[key]) {
606
- return this[key];
607
- }
608
- return this._make(MODE_CHECK_IGNORE, key);
609
- }
610
- _make(mode, key) {
611
- const str2 = pinWildcards(
612
- mode === MODE_IGNORE ? this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD, replaceTrailingWildcard).replace(REGEX_REPLACE_TRAILING_DOUBLESTAR, replaceTrailingDoublestar) : checkSourceOf(this.body, this.regexPrefix)
613
- );
614
- const regex = this.ignoreCase ? new RegExp(str2, "i") : new RegExp(str2);
615
- return define(this, key, regex);
616
- }
617
- };
618
- var createRule = ({
619
- pattern,
620
- mark
621
- }, ignoreCase) => {
622
- let negative = false;
623
- let body = pattern;
624
- if (body.indexOf("!") === 0) {
625
- negative = true;
626
- body = body.substr(1);
627
- }
628
- body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
629
- const regexPrefix = makeRegexPrefix(body);
630
- return new IgnoreRule(
631
- pattern,
632
- mark,
633
- body,
634
- ignoreCase,
635
- negative,
636
- regexPrefix
637
- );
638
- };
639
- var RuleManager = class {
640
- constructor(ignoreCase) {
641
- this._ignoreCase = ignoreCase;
642
- this._rules = [];
643
- this._basenameCount = 0;
644
- }
645
- _add(pattern) {
646
- if (pattern && pattern[KEY_IGNORE]) {
647
- this._rules = this._rules.concat(pattern._rules._rules);
648
- this._basenameCount += pattern._rules._basenameCount;
649
- this._added = true;
650
- return;
651
- }
652
- if (isString(pattern)) {
653
- pattern = {
654
- pattern
655
- };
656
- }
657
- if (checkPattern(pattern.pattern)) {
658
- const rule = createRule(pattern, this._ignoreCase);
659
- this._added = true;
660
- this._rules.push(rule);
661
- if (matchesBasename(rule.body)) {
662
- this._basenameCount++;
663
- }
664
- }
665
- }
666
- // @param {Array<string> | string | Ignore} pattern
667
- add(pattern) {
668
- this._added = false;
669
- makeArray(
670
- isString(pattern) ? splitPattern(pattern) : pattern
671
- ).forEach(this._add, this);
672
- if (this._added) {
673
- this._literalRules = UNDEFINED;
674
- }
675
- return this._added;
676
- }
677
- // Match the literal 'abc/' for `checkIgnore`, last rule wins. Only a rule
678
- // ending in a wildcard can match it (see `checkSourceOf`), so the rest
679
- // are left out once, rather than tested or compiled for every path.
680
- testLiteral(path) {
681
- const rules = this._literalRules || (this._literalRules = this._rules.filter(
682
- ({ body }) => body[body.length - (body[body.length - 1] === SLASH3 ? 2 : 1)] === "*"
683
- ));
684
- let ignored = false;
685
- let unignored = false;
686
- let matchedRule;
687
- for (let index = rules.length - 1; index >= 0; index--) {
688
- const rule = rules[index];
689
- if (rule.checkRegex.test(path)) {
690
- ignored = !rule.negative;
691
- unignored = rule.negative;
692
- matchedRule = rule.negative ? UNDEFINED : rule;
693
- break;
694
- }
695
- }
696
- const ret = {
697
- ignored,
698
- unignored
699
- };
700
- if (matchedRule) {
701
- ret.rule = matchedRule;
702
- }
703
- return ret;
704
- }
705
- // Test one single path without recursively checking parent directories
706
- //
707
- // - checkUnignored `boolean` whether should check if the path is unignored,
708
- // setting `checkUnignored` to `false` could reduce additional
709
- // path matching.
710
- // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
711
- // @returns {TestResult} true if a file is ignored
712
- test(path, checkUnignored, mode) {
713
- let ignored = false;
714
- let unignored = false;
715
- let matchedRule;
716
- const rules = this._rules;
717
- const { length } = rules;
718
- const shortcut = this._basenameCount * 2 >= length;
719
- const basename7 = shortcut ? basenameOf(path) : path;
720
- for (let index = 0; index < length; index++) {
721
- const rule = rules[index];
722
- const { negative } = rule;
723
- const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
724
- if (!skip && rule[mode].test(
725
- shortcut && rule._basenameOnly ? basename7 : path
726
- )) {
727
- ignored = !negative;
728
- unignored = negative;
729
- matchedRule = negative ? UNDEFINED : rule;
730
- }
731
- }
732
- const ret = {
733
- ignored,
734
- unignored
735
- };
736
- if (matchedRule) {
737
- ret.rule = matchedRule;
738
- }
739
- return ret;
740
- }
741
- };
742
- var throwError = (message, Ctor) => {
743
- throw new Ctor(message);
744
- };
745
- var checkPath = (path, originalPath, doThrow) => {
746
- if (!isString(path)) {
747
- return doThrow(
748
- `path must be a string, but got \`${originalPath}\``,
749
- TypeError
750
- );
751
- }
752
- if (!path) {
753
- return doThrow(`path must not be empty`, TypeError);
754
- }
755
- if (checkPath.isNotRelative(path)) {
756
- const r = "`path.relative()`d";
757
- return doThrow(
758
- `path should be a ${r} string, but got "${originalPath}"`,
759
- RangeError
760
- );
761
- }
762
- return true;
763
- };
764
- var isNotRelative = (path) => {
765
- const first = path.charCodeAt(0);
766
- if (first === SLASH_CODE) {
767
- return true;
768
- }
769
- if (first !== DOT_CODE) {
770
- return false;
771
- }
772
- if (path.length === 1) {
773
- return true;
774
- }
775
- const second = path.charCodeAt(1);
776
- if (second === SLASH_CODE) {
777
- return true;
778
- }
779
- if (second !== DOT_CODE) {
780
- return false;
781
- }
782
- return path.length === 2 || path.charCodeAt(2) === SLASH_CODE;
783
- };
784
- checkPath.isNotRelative = isNotRelative;
785
- checkPath.convert = (p) => p;
786
- var Ignore = class {
787
- constructor({
788
- ignorecase = true,
789
- ignoreCase = ignorecase,
790
- allowRelativePaths = false
791
- } = {}) {
792
- define(this, KEY_IGNORE, true);
793
- this._rules = new RuleManager(ignoreCase);
794
- this._strictPathCheck = !allowRelativePaths;
795
- this._initCache();
796
- }
797
- _initCache() {
798
- this._ignoreCache = /* @__PURE__ */ Object.create(null);
799
- this._testCache = /* @__PURE__ */ Object.create(null);
800
- }
801
- add(pattern) {
802
- if (this._rules.add(pattern)) {
803
- this._initCache();
804
- }
805
- return this;
806
- }
807
- // legacy
808
- addPattern(pattern) {
809
- return this.add(pattern);
810
- }
811
- // @returns {TestResult}
812
- _test(originalPath, cache, checkUnignored) {
813
- const path = originalPath && checkPath.convert(originalPath);
814
- checkPath(
815
- path,
816
- originalPath,
817
- this._strictPathCheck ? throwError : RETURN_FALSE
818
- );
819
- return this._t(path, cache, checkUnignored);
820
- }
821
- checkIgnore(path) {
822
- if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {
823
- return this.test(path);
824
- }
825
- const dir = this._t(path, this._testCache, true);
826
- if (dir.ignored) {
827
- return dir;
828
- }
829
- const literal2 = this._rules.testLiteral(path);
830
- return literal2.ignored || literal2.unignored ? literal2 : dir;
831
- }
832
- _t(path, cache, checkUnignored) {
833
- if (path in cache) {
834
- return cache[path];
835
- }
836
- const parentPath = parentOf(path);
837
- const parent = parentPath ? this._t(parentPath, cache, checkUnignored) : UNDEFINED;
838
- return cache[path] = parent && parent.ignored ? parent : this._rules.test(path, checkUnignored, MODE_IGNORE);
839
- }
840
- ignores(path) {
841
- return this._test(path, this._ignoreCache, false).ignored;
842
- }
843
- createFilter() {
844
- return (path) => !this.ignores(path);
845
- }
846
- filter(paths) {
847
- return makeArray(paths).filter(this.createFilter());
848
- }
849
- // @returns {TestResult}
850
- test(path) {
851
- return this._test(path, this._testCache, true);
852
- }
853
- };
854
- var factory = (options) => new Ignore(options);
855
- var isPathValid = (path) => checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
856
- var setupWindows = () => {
857
- const makePosix = (str2) => /^\\\\\?\\/.test(str2) || /["<>|\u0000-\u001F]+/u.test(str2) ? str2 : str2.replace(/\\/g, "/");
858
- checkPath.convert = makePosix;
859
- const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
860
- checkPath.isNotRelative = (path) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
861
- };
862
- if (
863
- // Detect `process` so that it can run in browsers.
864
- typeof process !== "undefined" && process.platform === "win32"
865
- ) {
866
- setupWindows();
867
- }
868
- module.exports = factory;
869
- factory.default = factory;
870
- module.exports.isPathValid = isPathValid;
871
- define(module.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
872
- }
873
- });
874
-
875
- // ../../packages/persistence/src/attached-derived.ts
876
- import { rmSync } from "fs";
877
- import { join } from "path";
878
- var POLICY_CACHE_FILENAME = "policy-cache.json";
879
-
880
- // ../../packages/persistence/src/control-plane-credential.ts
881
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
882
- import { join as join2 } from "path";
883
6
 
884
7
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
885
8
  var DEFERRED_MIGRATION_TAGS = [
@@ -3864,9 +2987,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3864
2987
  function stripTabAndNewline(value) {
3865
2988
  return value.replace(asciiTabOrNewline, "");
3866
2989
  }
3867
- function urlHostnameOk(url2, hostname7) {
3868
- hostname7.lastIndex = 0;
3869
- return hostname7.test(url2.hostname);
2990
+ function urlHostnameOk(url2, hostname6) {
2991
+ hostname6.lastIndex = 0;
2992
+ return hostname6.test(url2.hostname);
3870
2993
  }
3871
2994
  function urlProtocolOk(url2, protocol) {
3872
2995
  protocol.lastIndex = 0;
@@ -20786,13 +19909,16 @@ function serviceTierMultiplier(tier) {
20786
19909
  if (tier === void 0) return 1;
20787
19910
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20788
19911
  }
19912
+ function promptTokensOf(usage) {
19913
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19914
+ }
20789
19915
  function costOf(price, usage) {
20790
19916
  const metered = [
20791
19917
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20792
19918
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20793
19919
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20794
19920
  ];
20795
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19921
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20796
19922
  if (band !== null && (band.input === null || band.output === null)) return null;
20797
19923
  const inputRate = band?.input ?? price.input;
20798
19924
  const outputRate = band?.output ?? price.output;
@@ -20865,8 +19991,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20865
19991
  ["ollama", "local"],
20866
19992
  ["local", "local"]
20867
19993
  ]);
20868
- function hostingFor(platform2) {
20869
- return PLATFORM_HOSTING.get(platform2) ?? "api";
19994
+ function hostingFor(platform) {
19995
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20870
19996
  }
20871
19997
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20872
19998
  ["anthropic", "anthropic"],
@@ -20880,8 +20006,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20880
20006
  function firstPartyPlatformFor(vendor2) {
20881
20007
  return FIRST_PARTY.get(vendor2) ?? null;
20882
20008
  }
20883
- function isFirstParty(vendor2, platform2) {
20884
- return FIRST_PARTY.get(vendor2) === platform2;
20009
+ function isFirstParty(vendor2, platform) {
20010
+ return FIRST_PARTY.get(vendor2) === platform;
20885
20011
  }
20886
20012
  var PLATFORM_NAMESPACES = Object.freeze([
20887
20013
  "anthropic",
@@ -20942,14 +20068,14 @@ var ModelVendorBuilder = class {
20942
20068
  );
20943
20069
  }
20944
20070
  for (const ref of spec.on ?? []) {
20945
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20946
- const firstParty = isFirstParty(this.vendor, platform2);
20947
- const hosting = hostingFor(platform2);
20071
+ const { platform, price, retention, region } = normalizeRef(ref);
20072
+ const firstParty = isFirstParty(this.vendor, platform);
20073
+ const hosting = hostingFor(platform);
20948
20074
  const isSelfHosted = hosting === "local";
20949
20075
  platforms.set(
20950
- platform2,
20076
+ platform,
20951
20077
  Object.freeze({
20952
- platform: platform2,
20078
+ platform,
20953
20079
  hosting,
20954
20080
  firstParty,
20955
20081
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21002,35 +20128,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21002
20128
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21003
20129
  var BEDROCK_REVISION_RE = /:\d+$/u;
21004
20130
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21005
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20131
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21006
20132
  function stripPlatformDecorations(model) {
21007
20133
  let id = model.trim();
21008
- let platform2 = null;
20134
+ let platform = null;
21009
20135
  if (GEO_PREFIX_RE.test(id)) {
21010
20136
  id = id.replace(GEO_PREFIX_RE, "");
21011
- platform2 = "bedrock";
20137
+ platform = "bedrock";
21012
20138
  }
21013
20139
  if (NAMESPACE_DOT_RE.test(id)) {
21014
20140
  id = id.replace(NAMESPACE_DOT_RE, "");
21015
- platform2 ??= "bedrock";
20141
+ platform ??= "bedrock";
21016
20142
  }
21017
20143
  if (BEDROCK_VERSION_RE.test(id)) {
21018
20144
  id = id.replace(BEDROCK_VERSION_RE, "");
21019
- platform2 ??= "bedrock";
20145
+ platform ??= "bedrock";
21020
20146
  } else if (BEDROCK_REVISION_RE.test(id)) {
21021
20147
  id = id.replace(BEDROCK_REVISION_RE, "");
21022
- platform2 ??= "bedrock";
20148
+ platform ??= "bedrock";
21023
20149
  }
21024
20150
  if (VERTEX_VERSION_RE.test(id)) {
21025
20151
  id = id.replace(VERTEX_VERSION_RE, "");
21026
- platform2 ??= "vertex";
20152
+ platform ??= "vertex";
21027
20153
  }
21028
20154
  if (NAMESPACE_SLASH_RE.test(id)) {
21029
20155
  id = id.replace(NAMESPACE_SLASH_RE, "");
21030
20156
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21031
20157
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21032
20158
  }
21033
- return { id, platform: platform2 };
20159
+ return { id, platform };
21034
20160
  }
21035
20161
  function buildModelIndex(entries) {
21036
20162
  const byId = /* @__PURE__ */ new Map();
@@ -21047,19 +20173,19 @@ function resolveModel(raw, index) {
21047
20173
  if (exact !== void 0) {
21048
20174
  return { entry: exact, canonicalId: raw, platform: null, raw };
21049
20175
  }
21050
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20176
+ const { id, platform } = stripPlatformDecorations(raw);
21051
20177
  const stripped = index.byId.get(id);
21052
20178
  if (stripped !== void 0) {
21053
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20179
+ return { entry: stripped, canonicalId: id, platform, raw };
21054
20180
  }
21055
20181
  if (DATED_SUFFIX_RE.test(id)) {
21056
20182
  const undated = id.replace(DATED_SUFFIX_RE, "");
21057
20183
  const byDate = index.byId.get(undated);
21058
20184
  if (byDate !== void 0) {
21059
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20185
+ return { entry: byDate, canonicalId: undated, platform, raw };
21060
20186
  }
21061
20187
  }
21062
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20188
+ return { entry: null, canonicalId: raw, platform, raw };
21063
20189
  }
21064
20190
 
21065
20191
  // ../../packages/schema/src/model/catalog.ts
@@ -21152,7 +20278,7 @@ anthropic.model("claude-haiku-4-5", {
21152
20278
  name: "Claude Haiku 4.5",
21153
20279
  ctx: 2e5,
21154
20280
  maxOut: 64e3,
21155
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20281
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21156
20282
  capability: null,
21157
20283
  price: anthropicPrice(1, 5, 0.1),
21158
20284
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21283,6 +20409,11 @@ openai.model("gpt-4o", {
21283
20409
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21284
20410
  on: [...OPENAI_RESELLERS]
21285
20411
  });
20412
+ openai.model("gpt-4o-2024-05-13", {
20413
+ name: "GPT-4o (2024-05-13)",
20414
+ price: tokenPrice(5, 15),
20415
+ on: [...OPENAI_RESELLERS]
20416
+ });
21286
20417
  openai.model("gpt-4o-mini", {
21287
20418
  name: "GPT-4o mini",
21288
20419
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21302,6 +20433,24 @@ openai.model("o3", {
21302
20433
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21303
20434
  on: [...OPENAI_RESELLERS]
21304
20435
  });
20436
+ openai.model("text-embedding-3-small", {
20437
+ name: "text-embedding-3-small",
20438
+ capability: "embedding",
20439
+ price: tokenPrice(0.02, 0),
20440
+ on: [...OPENAI_RESELLERS]
20441
+ });
20442
+ openai.model("text-embedding-3-large", {
20443
+ name: "text-embedding-3-large",
20444
+ capability: "embedding",
20445
+ price: tokenPrice(0.13, 0),
20446
+ on: [...OPENAI_RESELLERS]
20447
+ });
20448
+ openai.model("text-embedding-ada-002", {
20449
+ name: "text-embedding-ada-002",
20450
+ capability: "embedding",
20451
+ price: tokenPrice(0.1, 0),
20452
+ on: [...OPENAI_RESELLERS]
20453
+ });
21305
20454
  openai.model("gpt-oss-120b", {
21306
20455
  name: "GPT-OSS 120B",
21307
20456
  openWeights: true,
@@ -21588,10 +20737,21 @@ var MODEL_ENTRIES = Object.freeze([
21588
20737
  ...alibaba.models(),
21589
20738
  ...amazon.models()
21590
20739
  ]);
20740
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20741
+ [
20742
+ ...new Set(
20743
+ MODEL_ENTRIES.flatMap(
20744
+ (entry) => [...entry.platforms.values()].flatMap(
20745
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20746
+ )
20747
+ )
20748
+ )
20749
+ ].sort((a, b) => a - b)
20750
+ );
21591
20751
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21592
20752
 
21593
20753
  // ../../packages/schema/src/model/governance.ts
21594
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20754
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21595
20755
  var DataRetention = external_exports.enum([
21596
20756
  "zero_retention",
21597
20757
  "no_storage",
@@ -21687,16 +20847,16 @@ function platformForProvider(provider) {
21687
20847
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21688
20848
  }
21689
20849
  function isLocalProvider(provider) {
21690
- const platform2 = platformForProvider(provider);
21691
- return platform2 !== null && hostingFor(platform2) === "local";
20850
+ const platform = platformForProvider(provider);
20851
+ return platform !== null && hostingFor(platform) === "local";
21692
20852
  }
21693
20853
  function priceFor(provider, model) {
21694
20854
  if (isLocalProvider(provider)) return ZERO_PRICE;
21695
20855
  const resolved = resolveModel(model, MODEL_INDEX);
21696
20856
  if (resolved.entry === null) return null;
21697
- const platform2 = resolved.platform ?? platformForProvider(provider);
21698
- if (platform2 === null) return null;
21699
- return resolved.entry.platforms.get(platform2)?.price ?? null;
20857
+ const platform = resolved.platform ?? platformForProvider(provider);
20858
+ if (platform === null) return null;
20859
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21700
20860
  }
21701
20861
  var defaultCostModel = {
21702
20862
  normalizeModelId(provider, model) {
@@ -21722,7 +20882,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21722
20882
 
21723
20883
  // ../../packages/schema/src/token/token-report.ts
21724
20884
  var num = (value) => value ?? 0;
21725
- function costUsageOf(a) {
20885
+ function costUsageOf(a, promptTokens) {
21726
20886
  const usage = {
21727
20887
  inputTokens: num(a.input_tokens),
21728
20888
  outputTokens: num(a.output_tokens),
@@ -21732,11 +20892,12 @@ function costUsageOf(a) {
21732
20892
  webSearchRequests: num(a.web_search_requests)
21733
20893
  };
21734
20894
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20895
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21735
20896
  return usage;
21736
20897
  }
21737
20898
  function buildTokenReports(leaves, costModel) {
21738
20899
  const bySession = /* @__PURE__ */ new Map();
21739
- for (const { sessionId, attributes } of leaves) {
20900
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21740
20901
  const provider = attributes.provider ?? "unknown";
21741
20902
  const model = attributes.model ?? "unknown";
21742
20903
  const key = `${provider} ${model}`;
@@ -21755,7 +20916,8 @@ function buildTokenReports(leaves, costModel) {
21755
20916
  cacheCreation: 0,
21756
20917
  cacheRead: 0,
21757
20918
  costUsd: 0,
21758
- priced: false
20919
+ priced: false,
20920
+ partial: false
21759
20921
  };
21760
20922
  rollups.set(key, acc);
21761
20923
  }
@@ -21763,8 +20925,14 @@ function buildTokenReports(leaves, costModel) {
21763
20925
  acc.output += num(attributes.output_tokens);
21764
20926
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21765
20927
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21766
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21767
- if (leafCost !== null) {
20928
+ const leafCost = costModel.costFor({
20929
+ provider,
20930
+ model,
20931
+ usage: costUsageOf(attributes, promptTokens)
20932
+ });
20933
+ if (leafCost === null) {
20934
+ acc.partial = true;
20935
+ } else {
21768
20936
  acc.costUsd += leafCost;
21769
20937
  acc.priced = true;
21770
20938
  }
@@ -21780,9 +20948,8 @@ function buildTokenReports(leaves, costModel) {
21780
20948
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21781
20949
  totalTokens += rollupTotal;
21782
20950
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21783
- if (estimatedCostUsd === null) {
21784
- anyUnpriced = true;
21785
- } else {
20951
+ if (acc.partial) anyUnpriced = true;
20952
+ if (estimatedCostUsd !== null) {
21786
20953
  anyPriced = true;
21787
20954
  costUsd += estimatedCostUsd;
21788
20955
  }
@@ -21805,7 +20972,7 @@ function buildTokenReports(leaves, costModel) {
21805
20972
  totalTokens,
21806
20973
  // Σ of the PRICED rollups; null when none had a known price.
21807
20974
  estimatedCostUsd: anyPriced ? costUsd : null,
21808
- // Any unknown (provider, model) means the total understates real spend.
20975
+ // Any call priced to null means the total understates real spend.
21809
20976
  costIsPartial: anyUnpriced
21810
20977
  });
21811
20978
  }
@@ -22507,6 +21674,11 @@ var CaptureAttributes = external_exports.object({
22507
21674
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22508
21675
  // repeated rather than referenced because a store reader opens this file.
22509
21676
  redact_degraded_to: ActionTaken.optional(),
21677
+ // Why a capture has no content and no findings: its field was refused
21678
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21679
+ // whose value this is). Absent on every capture that was scanned, so a
21680
+ // reader can tell a refused row from an empty clean one.
21681
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22510
21682
  // The scope key this capture was stamped with: the canonical repository
22511
21683
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22512
21684
  // against its working directory), else of its own working directory, or a
@@ -22684,8 +21856,9 @@ var SessionTokenReport = external_exports.object({
22684
21856
  totalTokens: external_exports.number().int().nonnegative(),
22685
21857
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22686
21858
  estimatedCostUsd: external_exports.number().nullable(),
22687
- // True whenever any rollup has a null cost (unknown provider/model), so the
22688
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21859
+ // True whenever any call priced to null (an unknown provider/model, or a call
21860
+ // over a long-context threshold whose rate is unpublished), so the total
21861
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22689
21862
  // precise figure rather than silently dropping the unpriced calls.
22690
21863
  costIsPartial: external_exports.boolean()
22691
21864
  });
@@ -23407,6 +22580,7 @@ var EgressWriteSummary = external_exports.object({
23407
22580
  }).meta({ id: "EgressWriteSummary" });
23408
22581
 
23409
22582
  // ../../packages/schema/src/zod/control-plane.ts
22583
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
23410
22584
  var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
23411
22585
  var AttachedCredential = external_exports.object({
23412
22586
  specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
@@ -23431,6 +22605,25 @@ var AttachedCredentialAny = external_exports.discriminatedUnion("specVersion", [
23431
22605
  AttachedCredentialV1,
23432
22606
  AttachedCredentialV2
23433
22607
  ]);
22608
+ function attachmentModeOf(credential) {
22609
+ return credential.specVersion === ATTACHED_CREDENTIAL_SPEC_VERSION ? "machine" : "scoped";
22610
+ }
22611
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
22612
+ function unsafeEndpointReason(endpoint) {
22613
+ let parsed;
22614
+ try {
22615
+ parsed = new URL(endpoint);
22616
+ } catch {
22617
+ return "unparseable";
22618
+ }
22619
+ if (parsed.username !== "" || parsed.password !== "") return "userinfo";
22620
+ if (parsed.search !== "" || parsed.hash !== "") return "query-or-fragment";
22621
+ if (parsed.protocol === "https:") return null;
22622
+ return parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname) ? null : "insecure";
22623
+ }
22624
+ function isSafeEndpoint(endpoint) {
22625
+ return unsafeEndpointReason(endpoint) === null;
22626
+ }
23434
22627
  var MAX_DATE_MS = 253402300799999;
23435
22628
  var MAX_INT4 = 2147483647;
23436
22629
  var StorePosturePack = external_exports.object({
@@ -23534,7 +22727,15 @@ var StorePostureSnapshot = external_exports.object({
23534
22727
  policyCounts: StorePosturePolicyCounts,
23535
22728
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23536
22729
  // getting its 200 without a payload change.
23537
- plugin: StorePosturePlugin.optional()
22730
+ plugin: StorePosturePlugin.optional(),
22731
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22732
+ // machine attachment omits it, so its body is byte for byte the one it
22733
+ // sent before this member existed. Absent therefore means machine-wide OR
22734
+ // a reporter older than this member, never "scoped". Both values parse, so
22735
+ // a sender that one day spells `machine` breaks no receiver; any other
22736
+ // value fails the whole snapshot, which is why the reporter sends a
22737
+ // constant and never the raw mode.
22738
+ attachmentMode: AttachmentMode.optional()
23538
22739
  }).meta({ id: "StorePostureSnapshot" });
23539
22740
  var CAPTURE_VERSION_PREFIX = "capture/";
23540
22741
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23811,7 +23012,19 @@ var EventMetadata = external_exports.object({
23811
23012
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23812
23013
  // Closing either means moving the reason onto the finding row, which
23813
23014
  // already carries its own action.
23814
- redactDegradedTo: ActionTaken.optional()
23015
+ redactDegradedTo: ActionTaken.optional(),
23016
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23017
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23018
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23019
+ // field instead of letting it through unscanned.
23020
+ //
23021
+ // - 'timeout': the bounded scan ran out of time.
23022
+ // - 'unavailable': no worker could run it.
23023
+ //
23024
+ // A refused row stores '' as its content and has no findings, which is
23025
+ // exactly what a clean, empty capture looks like — this marker is the only
23026
+ // thing that tells the two apart. Absent on every capture that was scanned.
23027
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23815
23028
  }).meta({ id: "EventMetadata" });
23816
23029
  var Event = external_exports.object({
23817
23030
  id: external_exports.guid(),
@@ -23981,7 +23194,7 @@ var Rule = external_exports.strictObject({
23981
23194
  postValidators: external_exports.array(PostValidatorRef).optional(),
23982
23195
  requiresNearby: RequiresNearby.optional(),
23983
23196
  examples: external_exports.array(external_exports.string()).optional(),
23984
- // Whether the matched text is itself sensitive. Absent means 'value'.
23197
+ // Whether the matched text is itself sensitive (see RuleEvidence).
23985
23198
  evidence: RuleEvidence.optional()
23986
23199
  }).meta({ id: "Rule" });
23987
23200
  var Author = external_exports.object({
@@ -24073,7 +23286,13 @@ var DetectionRule = external_exports.object({
24073
23286
  // Representative matching strings the rule author shipped with the rule. The
24074
23287
  // cheapest honest answer to "show me what this rule catches" — every bundled
24075
23288
  // rule has them, and they are already in the stored snapshot.
24076
- examples: external_exports.array(external_exports.string()).optional()
23289
+ examples: external_exports.array(external_exports.string()).optional(),
23290
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23291
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23292
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23293
+ // in a value category (secret/pii/financial/phi) is always 'value',
23294
+ // whatever it declares.
23295
+ evidence: RuleEvidence.optional()
24077
23296
  }).meta({ id: "DetectionRule" });
24078
23297
  var DetectionUpdate = external_exports.object({
24079
23298
  available: external_exports.boolean(),
@@ -24141,8 +23360,10 @@ var ImportDetectionRequest = external_exports.object({
24141
23360
  }).meta({ id: "ImportDetectionRequest" });
24142
23361
 
24143
23362
  // ../../packages/schema/src/zod/detection-build.ts
24144
- function optional2(key, parsed, raw) {
24145
- if (raw === void 0 || !parsed.success || parsed.data === void 0) return {};
23363
+ function optional2(key, raw, parse4) {
23364
+ if (raw === void 0) return {};
23365
+ const parsed = parse4(raw);
23366
+ if (!parsed.success || parsed.data === void 0) return {};
24146
23367
  return { [key]: parsed.data };
24147
23368
  }
24148
23369
  function isStringArray(value) {
@@ -24177,10 +23398,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24177
23398
  category: r.category,
24178
23399
  severity: r.severity,
24179
23400
  matcher: parsed.data,
24180
- // The rest of what decides whether this rule fires. Carried so a consumer
24181
- // re-running the rule (a preview, a tester) evaluates what the engine
24182
- // evaluates rather than a matcher stripped of its guards — half the
24183
- // bundled catalog carries at least one of these.
23401
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23402
+ // decides whether this rule fires. Carried so a consumer re-running the
23403
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23404
+ // than a matcher stripped of its guards — half the bundled catalog
23405
+ // carries at least one of these. `examples` and `evidence` describe the
23406
+ // rule and never gate a match.
24184
23407
  //
24185
23408
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24186
23409
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24190,18 +23413,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24190
23413
  // test should stay exactly what it was, namely a renderable matcher. A
24191
23414
  // field that fails validation is omitted, which reads as "not set" and is
24192
23415
  // the same thing the consumer saw before this change.
24193
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23416
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24194
23417
  ...optional2(
24195
23418
  "postValidators",
24196
- PostValidatorRef.array().safeParse(r.postValidators),
24197
- r.postValidators
23419
+ r.postValidators,
23420
+ (v) => PostValidatorRef.array().safeParse(v)
24198
23421
  ),
24199
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23422
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24200
23423
  ...optional2(
24201
23424
  "examples",
24202
- { success: isStringArray(r.examples), data: r.examples },
24203
- r.examples
24204
- )
23425
+ r.examples,
23426
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23427
+ ),
23428
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24205
23429
  }
24206
23430
  ];
24207
23431
  });
@@ -24894,11 +24118,14 @@ var PolicyBundle = external_exports.object({
24894
24118
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24895
24119
  // Model ids (the raw `model` string a harness reports, e.g.
24896
24120
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24897
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24898
- // one (UserPromptSubmit). Optional so an older backend — and an older
24899
- // on-disk cache — still parses; consumers read `?? []`, which is the
24900
- // unenforced behaviour that predates this field and the safe direction to
24901
- // default.
24121
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24122
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24123
+ // wherever the organization governs the event: everywhere on a
24124
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24125
+ // one (the plugin runtime's `governanceApplies`).
24126
+ // Optional so an older backend — and an older on-disk cache — still
24127
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24128
+ // predates this field and the safe direction to default.
24902
24129
  //
24903
24130
  // Ids, not display names: the governance decision is keyed on the exact
24904
24131
  // string the harness reports (`model_status_override.versionId` in the
@@ -25270,9 +24497,39 @@ var AttachmentScopeEntry = external_exports.object({
25270
24497
  });
25271
24498
  var AttachmentScope = external_exports.object({
25272
24499
  endpoint: external_exports.string().min(1),
24500
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24501
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25273
24502
  entries: external_exports.array(AttachmentScopeEntry)
25274
24503
  });
25275
24504
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
24505
+ function parseAttachmentScope(raw) {
24506
+ try {
24507
+ const envelope = AttachmentScopeEnvelope.safeParse(raw);
24508
+ if (!envelope.success) return void 0;
24509
+ const entries = [];
24510
+ for (const candidate of envelope.data.entries) {
24511
+ const entry = AttachmentScopeEntry.safeParse(candidate);
24512
+ if (entry.success) entries.push(entry.data);
24513
+ }
24514
+ const { endpoint, tenantName, userEmail } = envelope.data;
24515
+ return {
24516
+ endpoint,
24517
+ ...tenantName === void 0 ? {} : { tenantName },
24518
+ ...userEmail === void 0 ? {} : { userEmail },
24519
+ entries
24520
+ };
24521
+ } catch {
24522
+ return void 0;
24523
+ }
24524
+ }
24525
+ function scopeForEndpoint(raw, endpoint) {
24526
+ if (endpoint === void 0) return void 0;
24527
+ const scope = parseAttachmentScope(raw);
24528
+ return scope?.endpoint === endpoint ? scope : void 0;
24529
+ }
24530
+ function isAttachmentScopeValid(raw, endpoint) {
24531
+ return scopeForEndpoint(raw, endpoint) !== void 0;
24532
+ }
25276
24533
  var WebChatCaptureConsent = external_exports.object({
25277
24534
  acknowledgedAt: external_exports.iso.datetime(),
25278
24535
  version: external_exports.number().int().positive()
@@ -25383,9 +24640,45 @@ function defaultWorkspaceSettings() {
25383
24640
  function isAttached(settings) {
25384
24641
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
25385
24642
  }
24643
+ function resolveScope(input2, extraEntries) {
24644
+ try {
24645
+ if (input2.mode === "machine") return { mode: "machine", keys: /* @__PURE__ */ new Set() };
24646
+ const keys = /* @__PURE__ */ new Set();
24647
+ const stored = scopeForEndpoint(input2.scope, input2.endpoint);
24648
+ for (const entry of stored?.entries ?? []) {
24649
+ keys.add(entry.identity);
24650
+ }
24651
+ for (const candidate of extraEntries ?? []) {
24652
+ const entry = AttachmentScopeEntry.safeParse(candidate);
24653
+ if (entry.success) keys.add(entry.data.identity);
24654
+ }
24655
+ return { mode: "scoped", keys };
24656
+ } catch {
24657
+ return { mode: "scoped", keys: /* @__PURE__ */ new Set() };
24658
+ }
24659
+ }
25386
24660
  function canSweepSyncLane(settings) {
25387
24661
  return settings.runMode !== "attached" && settings.controlPlane === void 0 && settings.historySyncConsent === void 0;
25388
24662
  }
24663
+ function syncLaneRetentionOf(settings, resolved) {
24664
+ try {
24665
+ if (canSweepSyncLane(settings)) return { kind: "sweep" };
24666
+ if (resolved?.mode !== "scoped") return { kind: "hold-all" };
24667
+ const raw = settings.attachmentScope;
24668
+ if (!isAttachmentScopeValid(raw, settings.controlPlane?.endpoint)) return { kind: "hold-all" };
24669
+ const persisted = parseAttachmentScope(raw);
24670
+ if (persisted === void 0 || !keptEveryEntry(raw, persisted)) return { kind: "hold-all" };
24671
+ if (persisted.entries.some((entry) => !resolved.keys.has(entry.identity))) {
24672
+ return { kind: "hold-all" };
24673
+ }
24674
+ return { kind: "hold-keys", keys: [...resolved.keys].sort() };
24675
+ } catch {
24676
+ return { kind: "hold-all" };
24677
+ }
24678
+ }
24679
+ function keptEveryEntry(raw, parsed) {
24680
+ return typeof raw === "object" && raw !== null && "entries" in raw && Array.isArray(raw.entries) && raw.entries.length === parsed.entries.length;
24681
+ }
25389
24682
  function toInventoryRow(input2, id, now) {
25390
24683
  return {
25391
24684
  id,
@@ -25477,6 +24770,7 @@ function toCaptureAttributes(event) {
25477
24770
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25478
24771
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25479
24772
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24773
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25480
24774
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25481
24775
  // has ever populated either), but every legacy metadata key still rides
25482
24776
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25605,6 +24899,27 @@ var ManagedSettings = external_exports.object({
25605
24899
  };
25606
24900
  }).meta({ id: "ManagedSettings" });
25607
24901
 
24902
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24903
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24904
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24905
+ var ModPolicySnapshot = external_exports.object({
24906
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24907
+ generatedAt: external_exports.iso.datetime(),
24908
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24909
+ // user's enabled installed packs (user-modified and custom packs included).
24910
+ // Absent means the store holds no authoritative snapshot, and the reader
24911
+ // scans with the packs it ships — the hook's own fallback.
24912
+ rules: external_exports.array(Rule).optional(),
24913
+ // Rule-targeted actions (first enabled policy per rule wins).
24914
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
24915
+ // The resolved action per detection category.
24916
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
24917
+ // Rules with an active exception grant. Honouring a grant means matching a
24918
+ // keyed fingerprint of the value and consuming a use, which only the hook can
24919
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
24920
+ exceptionRuleIds: external_exports.array(external_exports.string())
24921
+ }).meta({ id: "ModPolicySnapshot" });
24922
+
25608
24923
  // ../../packages/schema/src/zod/project-files.ts
25609
24924
  var ProjectFileInput = external_exports.object({
25610
24925
  path: external_exports.string().min(1),
@@ -25925,7 +25240,16 @@ var AttachInput = external_exports.object({
25925
25240
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
25926
25241
  // renders a longer one usefully.
25927
25242
  label: printable(200).optional(),
25928
- accessKey: external_exports.string()
25243
+ accessKey: external_exports.string(),
25244
+ // How much of this machine the attachment is for: everything, or only the
25245
+ // repositories its user enrolls. Optional, so an input without it still
25246
+ // parses; what an absent mode means is for whatever reads it to decide, not
25247
+ // this shape. This member validates the VALUE rather than leaving that to the
25248
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25249
+ // rejection names the field, so a value that is not a mode is refused as a bad
25250
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25251
+ // it as the mode to attach in.
25252
+ mode: AttachmentMode.optional()
25929
25253
  });
25930
25254
 
25931
25255
  // ../../packages/schema/src/zod/triage.ts
@@ -26211,6 +25535,15 @@ function fromCaptureStatusAttributes(bag) {
26211
25535
  return parsedStatus.success ? parsedStatus.data : null;
26212
25536
  }
26213
25537
 
25538
+ // ../../packages/persistence/src/attached-derived.ts
25539
+ import { rmSync } from "fs";
25540
+ import { join } from "path";
25541
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25542
+
25543
+ // ../../packages/persistence/src/control-plane-credential.ts
25544
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25545
+ import { join as join2 } from "path";
25546
+
26214
25547
  // ../../packages/persistence/src/paths.ts
26215
25548
  import {
26216
25549
  chmodSync,
@@ -26258,10 +25591,93 @@ function tightenFile(file2) {
26258
25591
  function tightenPerms(file2) {
26259
25592
  for (const path of [file2, ...dbSidecars(file2)]) chmodBestEffort(path, DATA_FILE_MODE);
26260
25593
  }
25594
+ function writeExclusiveOwnerOnlySync(file2, data) {
25595
+ writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
25596
+ }
25597
+ function writeOwnerOnlyFileSync(file2, data) {
25598
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
25599
+ try {
25600
+ rmSync2(tmp, { force: true });
25601
+ } catch {
25602
+ }
25603
+ try {
25604
+ writeExclusiveOwnerOnlySync(tmp, data);
25605
+ renameSync(tmp, file2);
25606
+ } finally {
25607
+ try {
25608
+ rmSync2(tmp, { force: true });
25609
+ } catch {
25610
+ }
25611
+ }
25612
+ tightenFile(file2);
25613
+ }
25614
+
25615
+ // ../../packages/persistence/src/control-plane-credential.ts
25616
+ function controlPlaneCredentialPath(settingsDir2) {
25617
+ return join2(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
25618
+ }
25619
+ function repairOrRefuseMode(file2) {
25620
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
25621
+ if (link === void 0) return "absent";
25622
+ if (link.isSymbolicLink()) return "untrusted";
25623
+ const stat2 = statSync(file2, { throwIfNoEntry: false });
25624
+ if (stat2 === void 0) return "absent";
25625
+ const uid = process.getuid?.();
25626
+ if (uid !== void 0 && stat2.uid !== uid) return "untrusted";
25627
+ if (process.platform !== "win32" && (stat2.mode & 511) !== DATA_FILE_MODE) {
25628
+ try {
25629
+ chmodSync2(file2, DATA_FILE_MODE);
25630
+ } catch {
25631
+ return "untrusted";
25632
+ }
25633
+ }
25634
+ return "ok";
25635
+ }
25636
+ function asReadableCredential(value) {
25637
+ const result = AttachedCredentialAny.safeParse(value);
25638
+ if (!result.success) return null;
25639
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25640
+ return null;
25641
+ }
25642
+ return result.data;
25643
+ }
25644
+ function readControlPlaneCredentialFile(settingsDir2, connection) {
25645
+ const file2 = controlPlaneCredentialPath(settingsDir2);
25646
+ let raw;
25647
+ const gate = repairOrRefuseMode(file2);
25648
+ if (gate === "absent") return { usable: false, reason: "absent" };
25649
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
25650
+ try {
25651
+ raw = readFileSync(file2, "utf8");
25652
+ } catch (err) {
25653
+ const code = err.code;
25654
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
25655
+ }
25656
+ let parsed;
25657
+ try {
25658
+ parsed = JSON.parse(raw);
25659
+ } catch {
25660
+ return { usable: false, reason: "malformed" };
25661
+ }
25662
+ const credential = asReadableCredential(parsed);
25663
+ if (credential === null) return { usable: false, reason: "malformed" };
25664
+ if (!isSafeEndpoint(credential.endpoint)) {
25665
+ return { usable: false, reason: "unsafe-endpoint" };
25666
+ }
25667
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
25668
+ return {
25669
+ usable: false,
25670
+ reason: "endpoint-mismatch",
25671
+ credentialEndpoint: credential.endpoint,
25672
+ settingsEndpoint: connection.endpoint
25673
+ };
25674
+ }
25675
+ return { usable: true, credential };
25676
+ }
26261
25677
 
26262
25678
  // ../../packages/persistence/src/database.ts
26263
25679
  import { randomUUID as randomUUID11 } from "crypto";
26264
- import { dirname as dirname2, join as join7, sep } from "path";
25680
+ import { dirname as dirname2, join as join8, sep } from "path";
26265
25681
  import { DatabaseSync } from "node:sqlite";
26266
25682
 
26267
25683
  // ../../packages/persistence/src/ids.ts
@@ -26294,6 +25710,7 @@ function captureId(sessionId, contentHash, filePath = null) {
26294
25710
  canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
26295
25711
  );
26296
25712
  }
25713
+ var DOT = ".".charCodeAt(0);
26297
25714
 
26298
25715
  // ../../packages/persistence/src/internal/snapshot.ts
26299
25716
  import { randomUUID } from "crypto";
@@ -26621,6 +26038,25 @@ function scopeKeysParam(scopeKeys) {
26621
26038
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26622
26039
  FROM audit_events AS session_root
26623
26040
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26041
+ var COUNTED_IN_SCOPE = `
26042
+ AND ${inScope("scope_key")}
26043
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26044
+ var DRAIN_TOTALS = `SELECT
26045
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26046
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26047
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26048
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26049
+ THEN 1 ELSE 0 END) AS skipped,
26050
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26051
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26052
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26053
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26054
+ FROM audit_events
26055
+ WHERE event_type IN (${TYPE_LIST})`;
26056
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26057
+ FROM audit_events
26058
+ WHERE synced_at = ${String(SKIPPED)}
26059
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26624
26060
  var ROW_COLUMNS = `id,
26625
26061
  parent_id AS parentId,
26626
26062
  root_session_id AS rootSessionId,
@@ -26696,7 +26132,7 @@ var SqliteHistorySyncRepository = class {
26696
26132
  );
26697
26133
  this.scopedCaptureRowsStmt = db.prepare(
26698
26134
  `SELECT ${ROW_COLUMNS}
26699
- FROM audit_events
26135
+ FROM audit_events INDEXED BY idx_audit_scope_owed
26700
26136
  WHERE synced_at IS NULL
26701
26137
  AND sync_claimed_at IS NULL
26702
26138
  AND outbox_owed = 1
@@ -26749,40 +26185,28 @@ var SqliteHistorySyncRepository = class {
26749
26185
  );
26750
26186
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26751
26187
  FROM audit_events${COUNTED_SCOPE}`);
26188
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26189
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
26752
26190
  this.partitionByKindStmt = db.prepare(
26753
26191
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
26754
26192
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
26755
26193
  GROUP BY event_type`
26756
26194
  );
26757
- this.countsStmt = db.prepare(
26758
- `SELECT
26759
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26760
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26761
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26762
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26763
- THEN 1 ELSE 0 END) AS skipped,
26764
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26765
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26766
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26767
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26768
- FROM audit_events
26769
- WHERE event_type IN (${TYPE_LIST})`
26195
+ this.scopedPartitionByKindStmt = db.prepare(
26196
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26197
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26198
+ GROUP BY event_type`
26770
26199
  );
26771
- this.captureSkipCountStmt = db.prepare(
26772
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
26773
- // way the structural totals are. The split exists because a refusal is
26774
- // terminal only against the deployment that gave it, and the structural
26775
- // re-arm frees it on a change of deployment. The capture lane has no such
26776
- // escape: re-arming a capture would offer one deployment's undelivered
26777
- // prompts, with their text, to a deployment that never saw them, which is
26778
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
26779
- // reasons mean the same thing — this row will not be sent — and splitting
26780
- // them would put refused captures in a bucket nothing reads and nothing
26781
- // frees.
26782
- `SELECT COUNT(*) AS skipped
26783
- FROM audit_events
26784
- WHERE synced_at = ${String(SKIPPED)}
26785
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26200
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26201
+ this.scopedCountsStmt = db.prepare(
26202
+ `${DRAIN_TOTALS}
26203
+ AND ${inScope("scope_key")}
26204
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26205
+ );
26206
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26207
+ this.scopedCaptureSkipCountStmt = db.prepare(
26208
+ `${CAPTURE_SKIPS}
26209
+ AND ${inScope("scope_key")}`
26786
26210
  );
26787
26211
  this.fingerprintStmt = db.prepare(
26788
26212
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -26896,6 +26320,10 @@ var SqliteHistorySyncRepository = class {
26896
26320
  scopedCaptureRowsStmt;
26897
26321
  scopedCaptureBacklogOwedStmt;
26898
26322
  markScopeCapturesOwedStmt;
26323
+ scopedPartitionStmt;
26324
+ scopedPartitionByKindStmt;
26325
+ scopedCountsStmt;
26326
+ scopedCaptureSkipCountStmt;
26899
26327
  /**
26900
26328
  * The masked detections recorded against one tool call.
26901
26329
  *
@@ -27117,7 +26545,29 @@ var SqliteHistorySyncRepository = class {
27117
26545
  * in" — and a machine that has never attached has no boundary to pass, so
27118
26546
  * requiring one would force a caller to invent one and report the whole store
27119
26547
  * as queued.
26548
+ *
26549
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26550
+ * the rows that pass the drain's reachability rule for that scope
26551
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26552
+ * drain never offers), so a personal repository's rows are in none of them.
26553
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26554
+ * nothing.
27120
26555
  */
26556
+ partition(scopeKeys) {
26557
+ const row = getRow(
26558
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26559
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26560
+ );
26561
+ return {
26562
+ queued: row?.queued ?? 0,
26563
+ inProgress: row?.inProgress ?? 0,
26564
+ synced: row?.synced ?? 0,
26565
+ failed: row?.failed ?? 0,
26566
+ refused: row?.refused ?? 0,
26567
+ detached: row?.detached ?? 0,
26568
+ total: row?.total ?? 0
26569
+ };
26570
+ }
27121
26571
  /**
27122
26572
  * The same partition, one row per kind that a lane carries.
27123
26573
  *
@@ -27127,11 +26577,14 @@ var SqliteHistorySyncRepository = class {
27127
26577
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27128
26578
  * rows", never as "zero sent"; the two look identical in a bar and mean
27129
26579
  * different things.
26580
+ *
26581
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26582
+ * still sum to the scoped aggregate. An empty list returns no rows.
27130
26583
  */
27131
- partitionByKind() {
26584
+ partitionByKind(scopeKeys) {
27132
26585
  return allRows(
27133
- this.partitionByKindStmt,
27134
- {}
26586
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26587
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27135
26588
  ).map((row) => ({
27136
26589
  kind: row.kind,
27137
26590
  queued: row.queued ?? 0,
@@ -27143,22 +26596,25 @@ var SqliteHistorySyncRepository = class {
27143
26596
  total: row.total ?? 0
27144
26597
  }));
27145
26598
  }
27146
- partition() {
27147
- const row = getRow(this.partitionStmt, {});
27148
- return {
27149
- queued: row?.queued ?? 0,
27150
- inProgress: row?.inProgress ?? 0,
27151
- synced: row?.synced ?? 0,
27152
- failed: row?.failed ?? 0,
27153
- refused: row?.refused ?? 0,
27154
- detached: row?.detached ?? 0,
27155
- total: row?.total ?? 0
27156
- };
27157
- }
27158
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27159
- counts(before) {
27160
- const row = getRow(this.countsStmt, { before });
27161
- const captures = getRow(this.captureSkipCountStmt);
26599
+ /**
26600
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26601
+ * and skipped are totals.
26602
+ *
26603
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26604
+ * `capturesSkipped` included: a structural row is counted only when its own
26605
+ * key and its session root's key are among them, a capture when its own key
26606
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26607
+ * under the same keys and boundary. Omitted, this runs the machine
26608
+ * statements, unchanged; an empty list counts nothing.
26609
+ */
26610
+ counts(before, scopeKeys) {
26611
+ const row = getRow(
26612
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26613
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26614
+ );
26615
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26616
+ scopeKeys: scopeKeysParam(scopeKeys)
26617
+ });
27162
26618
  return {
27163
26619
  pending: row?.pending ?? 0,
27164
26620
  sent: row?.sent ?? 0,
@@ -27410,6 +26866,7 @@ function applyMigrations(db, file2, options = {}) {
27410
26866
  }
27411
26867
  ensureSyncedAtColumn(db, "audit_events");
27412
26868
  ensureScopeKeyColumn(db);
26869
+ ensureScopeOwedIndex(db);
27413
26870
  ensureScanLedgerTable(db);
27414
26871
  ensureHistorySyncTable(db);
27415
26872
  ensureBlockedDetectionsTable(db);
@@ -27850,14 +27307,48 @@ function ensureScopeKeyColumn(db) {
27850
27307
  function hasScopeKeyColumn(db) {
27851
27308
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
27852
27309
  }
27310
+ var SCOPE_OWED_INDEX_DDL = "CREATE INDEX IF NOT EXISTS idx_audit_scope_owed ON audit_events (scope_key, event_type, started_at) WHERE outbox_owed = 1 AND synced_at IS NULL";
27311
+ function ensureScopeOwedIndex(db) {
27312
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27313
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27314
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27315
+ if (!complete) return;
27316
+ db.exec(SCOPE_OWED_INDEX_DDL);
27317
+ }
27853
27318
  function ensureScanLedgerTable(db) {
27854
27319
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27855
27320
  path TEXT PRIMARY KEY,
27856
27321
  mtime TEXT NOT NULL,
27857
27322
  content_hash TEXT NOT NULL,
27858
27323
  ruleset_hash TEXT NOT NULL,
27859
- scanned_at INTEGER NOT NULL
27324
+ scanned_at INTEGER NOT NULL,
27325
+ scope_key TEXT,
27326
+ scope_root TEXT
27860
27327
  )`);
27328
+ ensureScanLedgerScopeKeyColumn(db);
27329
+ ensureScanLedgerScopeRootColumn(db);
27330
+ }
27331
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27332
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27333
+ function ensureScanLedgerScopeKeyColumn(db) {
27334
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27335
+ }
27336
+ function ensureScanLedgerScopeRootColumn(db) {
27337
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27338
+ }
27339
+ function ensureScanLedgerColumn(db, column, ddl) {
27340
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27341
+ if (hasScanLedgerColumn(db, column)) return;
27342
+ withTransaction(
27343
+ db,
27344
+ () => {
27345
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27346
+ },
27347
+ "IMMEDIATE"
27348
+ );
27349
+ }
27350
+ function hasScanLedgerColumn(db, column) {
27351
+ return columnNames(db, "scan_ledger").includes(column);
27861
27352
  }
27862
27353
  function ensureHistorySyncTable(db) {
27863
27354
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -27908,6 +27399,106 @@ function ensureRuleProbeCacheTable(db) {
27908
27399
  )`);
27909
27400
  }
27910
27401
 
27402
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27403
+ import { createHash as createHash2 } from "crypto";
27404
+ import { readFileSync as readFileSync2 } from "fs";
27405
+ import { join as join4 } from "path";
27406
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27407
+ function modPolicySnapshotPath(dataDir2) {
27408
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27409
+ }
27410
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27411
+ const byRule = /* @__PURE__ */ new Map();
27412
+ const byCategory = /* @__PURE__ */ new Map();
27413
+ for (const policy of input2.policies) {
27414
+ if (!policy.enabled) continue;
27415
+ if ("ruleId" in policy.target) {
27416
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27417
+ } else if (!byCategory.has(policy.target.category)) {
27418
+ byCategory.set(policy.target.category, policy.action);
27419
+ }
27420
+ }
27421
+ const categoryActions = {};
27422
+ for (const category of DetectionCategory.options) {
27423
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27424
+ }
27425
+ return {
27426
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27427
+ generatedAt: generatedAt.toISOString(),
27428
+ // `examples` is documentation the mod never reads, and a custom pack's are
27429
+ // whatever its author pasted in, so they stay behind.
27430
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27431
+ ruleActions: Object.fromEntries(byRule),
27432
+ categoryActions,
27433
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27434
+ };
27435
+ }
27436
+ function assignedRuleActionPolicies(installed) {
27437
+ const out = [];
27438
+ for (const [ruleId, action] of installed.ruleActions) {
27439
+ if (installed.assignedRules.has(ruleId))
27440
+ out.push({ target: { ruleId }, action, enabled: true });
27441
+ }
27442
+ return out;
27443
+ }
27444
+ function withoutExamples(rule) {
27445
+ const copy = { ...rule };
27446
+ delete copy.examples;
27447
+ return copy;
27448
+ }
27449
+ function sameContent(a, b) {
27450
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27451
+ }
27452
+ function readModPolicySnapshot(dataDir2) {
27453
+ try {
27454
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27455
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27456
+ const parsed = ModPolicySnapshot.safeParse(JSON.parse(text));
27457
+ return parsed.success ? parsed.data : null;
27458
+ } catch {
27459
+ return null;
27460
+ }
27461
+ }
27462
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27463
+ const text = JSON.stringify(snapshot);
27464
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27465
+ const existing = readModPolicySnapshot(dataDir2);
27466
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27467
+ ensureDataDirSync(dataDir2);
27468
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27469
+ return true;
27470
+ }
27471
+ function regexProbeKey(matcher) {
27472
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27473
+ }
27474
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27475
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27476
+ return rules.filter((rule) => {
27477
+ if (rule.matcher.type !== "regex") return true;
27478
+ const key = regexProbeKey(rule.matcher);
27479
+ const verdict = sources.probeVerdict(key);
27480
+ if (verdict === "quarantined") return false;
27481
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27482
+ });
27483
+ }
27484
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27485
+ const policies = sources.readPolicies();
27486
+ const snapshot = sources.installedRuleset();
27487
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27488
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27489
+ return {
27490
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27491
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27492
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27493
+ };
27494
+ }
27495
+ function refreshModPolicySnapshot(dataDir2, sources) {
27496
+ try {
27497
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27498
+ } catch {
27499
+ }
27500
+ }
27501
+
27911
27502
  // ../../packages/persistence/src/internal/json.ts
27912
27503
  function safeJson(s, fallback) {
27913
27504
  if (s == null) return fallback;
@@ -28082,6 +27673,11 @@ var TIMELINE_COLUMNS = `
28082
27673
  json_extract(attributes, '$.targetId') AS target_id,
28083
27674
  json_extract(attributes, '$.internal') AS internal,
28084
27675
  json_extract(attributes, '$.flagged') AS flagged`;
27676
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27677
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27678
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27679
+ " + "
27680
+ );
28085
27681
  var LLM_USAGE_SELECT = `
28086
27682
  SELECT root_session_id AS sessionId,
28087
27683
  provider,
@@ -28093,9 +27689,10 @@ var LLM_USAGE_SELECT = `
28093
27689
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28094
27690
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28095
27691
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28096
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27692
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27693
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28097
27694
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28098
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27695
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28099
27696
  function usageLeaves(rows) {
28100
27697
  return rows.map((row) => {
28101
27698
  const attributes = {
@@ -28110,7 +27707,7 @@ function usageLeaves(rows) {
28110
27707
  if (row.provider !== null) attributes.provider = row.provider;
28111
27708
  if (row.model !== null) attributes.model = row.model;
28112
27709
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28113
- return { sessionId: row.sessionId, attributes };
27710
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28114
27711
  });
28115
27712
  }
28116
27713
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29043,8 +28640,8 @@ var SqliteConfigInventoryRepository = class {
29043
28640
  }
29044
28641
  db;
29045
28642
  report() {
29046
- const scan2 = latestConfigScan(this.db);
29047
- if (!scan2) {
28643
+ const scan = latestConfigScan(this.db);
28644
+ if (!scan) {
29048
28645
  return {
29049
28646
  scannedAt: null,
29050
28647
  skills: [],
@@ -29060,7 +28657,7 @@ var SqliteConfigInventoryRepository = class {
29060
28657
  WHERE object_type IN ('skill', 'hook', 'mcp_server', 'config_file') AND last_seen >= :startedAt
29061
28658
  ORDER BY object_type, title`
29062
28659
  ),
29063
- { startedAt: scan2.started_at }
28660
+ { startedAt: scan.started_at }
29064
28661
  );
29065
28662
  const findings = allRows(
29066
28663
  this.db.prepare(
@@ -29069,7 +28666,7 @@ var SqliteConfigInventoryRepository = class {
29069
28666
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
29070
28667
  WHERE f.audit_event_id = :scanId`
29071
28668
  ),
29072
- { scanId: scan2.id }
28669
+ { scanId: scan.id }
29073
28670
  );
29074
28671
  const skills = [];
29075
28672
  const hooks = [];
@@ -29085,12 +28682,12 @@ var SqliteConfigInventoryRepository = class {
29085
28682
  else configFiles.push(toConfigFileItem(row, bag));
29086
28683
  }
29087
28684
  return {
29088
- scannedAt: new Date(scan2.started_at).toISOString(),
28685
+ scannedAt: new Date(scan.started_at).toISOString(),
29089
28686
  skills,
29090
28687
  hooks,
29091
28688
  mcpServers,
29092
28689
  configFiles,
29093
- topics: buildTopics(skills, hooks, mcpServers, configFiles, scan2.attributes)
28690
+ topics: buildTopics(skills, hooks, mcpServers, configFiles, scan.attributes)
29094
28691
  };
29095
28692
  }
29096
28693
  // asset_id → trust for every stored override. The id space is opaque on
@@ -29444,9 +29041,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29444
29041
  AND conditions IS NULL
29445
29042
  AND ${ACTIVE_PREDICATE}`;
29446
29043
  var SqliteExceptionsRepository = class {
29447
- constructor(db, now = () => Date.now()) {
29044
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29448
29045
  this.db = db;
29449
29046
  this.now = now;
29047
+ this.onChange = onChange;
29450
29048
  this.consumeStmt = db.prepare(
29451
29049
  `UPDATE exceptions
29452
29050
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29465,6 +29063,7 @@ var SqliteExceptionsRepository = class {
29465
29063
  }
29466
29064
  db;
29467
29065
  now;
29066
+ onChange;
29468
29067
  consumeStmt;
29469
29068
  insertBlockedStmt;
29470
29069
  sweepBlockedStmt;
@@ -29480,7 +29079,9 @@ var SqliteExceptionsRepository = class {
29480
29079
  */
29481
29080
  create(input2) {
29482
29081
  try {
29483
- return Promise.resolve(this.createSync(input2));
29082
+ const created = this.createSync(input2);
29083
+ this.onChange();
29084
+ return Promise.resolve(created);
29484
29085
  } catch (err) {
29485
29086
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29486
29087
  }
@@ -29611,6 +29212,7 @@ var SqliteExceptionsRepository = class {
29611
29212
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29612
29213
  WHERE id = :id AND revoked_at IS NULL`
29613
29214
  ).run({ id, revokedBy, reason: reason ?? null, now });
29215
+ if (Number(result.changes) === 1) this.onChange();
29614
29216
  return Promise.resolve(Number(result.changes) === 1);
29615
29217
  }
29616
29218
  /**
@@ -29623,6 +29225,15 @@ var SqliteExceptionsRepository = class {
29623
29225
  const result = this.consumeStmt.run({ id, now });
29624
29226
  return Promise.resolve(Number(result.changes) === 1);
29625
29227
  }
29228
+ /** The rule ids with at least one active grant, under any key version. */
29229
+ activeRuleIds(now = this.now()) {
29230
+ return allRows(
29231
+ this.db.prepare(
29232
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29233
+ ),
29234
+ { now }
29235
+ ).map((row) => row.ruleId);
29236
+ }
29626
29237
  /**
29627
29238
  * The evaluation subset of every active grant under one fingerprint key
29628
29239
  * version — what rides the policy bundle to the hook. Grants written under
@@ -30746,30 +30357,30 @@ var SqliteInspectionFindingsRepository = class {
30746
30357
  };
30747
30358
 
30748
30359
  // ../../packages/persistence/src/repositories/installed-packs.ts
30749
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30360
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
30750
30361
 
30751
30362
  // ../../packages/persistence/src/policy-floor.ts
30752
- import { readFileSync as readFileSync5 } from "fs";
30753
- import { join as join6 } from "path";
30363
+ import { readFileSync as readFileSync6 } from "fs";
30364
+ import { join as join7 } from "path";
30754
30365
 
30755
30366
  // ../../packages/persistence/src/local-layout.ts
30756
30367
  import { renameSync as renameSync3 } from "fs";
30757
30368
  import { mkdir } from "fs/promises";
30758
30369
  import { homedir } from "os";
30759
- import { join as join4 } from "path";
30370
+ import { join as join5 } from "path";
30760
30371
  function defaultDataDir() {
30761
- return join4(homedir(), ".aka");
30372
+ return join5(homedir(), ".aka");
30762
30373
  }
30763
30374
  function settingsDir(base = defaultDataDir()) {
30764
- return join4(base, "settings");
30375
+ return join5(base, "settings");
30765
30376
  }
30766
30377
  function dataDir(base = defaultDataDir()) {
30767
- return join4(base, "data");
30378
+ return join5(base, "data");
30768
30379
  }
30769
30380
 
30770
30381
  // ../../packages/persistence/src/settings.ts
30771
- import { readFileSync as readFileSync4 } from "fs";
30772
- import { join as join5 } from "path";
30382
+ import { readFileSync as readFileSync5 } from "fs";
30383
+ import { join as join6 } from "path";
30773
30384
 
30774
30385
  // ../../packages/persistence/src/file-lock.ts
30775
30386
  import { randomUUID as randomUUID3 } from "crypto";
@@ -30777,7 +30388,7 @@ import {
30777
30388
  closeSync,
30778
30389
  existsSync as existsSync2,
30779
30390
  openSync,
30780
- readFileSync as readFileSync2,
30391
+ readFileSync as readFileSync3,
30781
30392
  rmSync as rmSync5,
30782
30393
  statSync as statSync3,
30783
30394
  writeFileSync as writeFileSync2
@@ -30786,16 +30397,16 @@ import { hostname as hostname3 } from "os";
30786
30397
  var PARK = new Int32Array(new SharedArrayBuffer(4));
30787
30398
 
30788
30399
  // ../../packages/persistence/src/managed-settings.ts
30789
- import { readFileSync as readFileSync3 } from "fs";
30400
+ import { readFileSync as readFileSync4 } from "fs";
30790
30401
  import { posix, win32 } from "path";
30791
- function managedSettingsPaths(platform2 = process.platform) {
30792
- if (platform2 === "darwin") {
30402
+ function managedSettingsPaths(platform = process.platform) {
30403
+ if (platform === "darwin") {
30793
30404
  return [
30794
30405
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
30795
30406
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
30796
30407
  ];
30797
30408
  }
30798
- if (platform2 === "win32") {
30409
+ if (platform === "win32") {
30799
30410
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
30800
30411
  }
30801
30412
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -30805,7 +30416,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
30805
30416
  for (const path of paths) {
30806
30417
  let text;
30807
30418
  try {
30808
- text = readFileSync3(path, "utf8");
30419
+ text = readFileSync4(path, "utf8");
30809
30420
  } catch {
30810
30421
  continue;
30811
30422
  }
@@ -30859,7 +30470,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
30859
30470
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
30860
30471
  }
30861
30472
  function readUserSettings(base) {
30862
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30473
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
30863
30474
  if (!record2) return defaultWorkspaceSettings();
30864
30475
  try {
30865
30476
  return WorkspaceSettings.parse(record2);
@@ -30870,7 +30481,7 @@ function readUserSettings(base) {
30870
30481
  function readJson(file2) {
30871
30482
  let text;
30872
30483
  try {
30873
- text = readFileSync4(file2, "utf8");
30484
+ text = readFileSync5(file2, "utf8");
30874
30485
  } catch {
30875
30486
  return null;
30876
30487
  }
@@ -30910,7 +30521,7 @@ var PolicyFloorError = class extends Error {
30910
30521
  };
30911
30522
  function readCachedPolicyBundle(base = defaultDataDir()) {
30912
30523
  try {
30913
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30524
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30914
30525
  const parsed = JSON.parse(raw);
30915
30526
  if (typeof parsed !== "object" || parsed === null) return null;
30916
30527
  return PolicyBundle.parse(parsed.bundle);
@@ -31034,7 +30645,7 @@ function inventorySignature(packs) {
31034
30645
  return packs.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31035
30646
  }
31036
30647
  function hashRules(rulesJson) {
31037
- return createHash2("sha256").update(rulesJson).digest("hex");
30648
+ return createHash3("sha256").update(rulesJson).digest("hex");
31038
30649
  }
31039
30650
  function parseVersion(v) {
31040
30651
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31076,9 +30687,10 @@ var SqliteInstalledPacksRepository = class {
31076
30687
  * from `openLocalDatabase`, which is the single construction site that owns a
31077
30688
  * real `~/.aka`.
31078
30689
  */
31079
- constructor(db, baseDir) {
30690
+ constructor(db, baseDir, onChange = () => void 0) {
31080
30691
  this.db = db;
31081
30692
  this.baseDir = baseDir;
30693
+ this.onChange = onChange;
31082
30694
  this.insertMissingStmt = db.prepare(
31083
30695
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31084
30696
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31107,6 +30719,7 @@ var SqliteInstalledPacksRepository = class {
31107
30719
  }
31108
30720
  db;
31109
30721
  baseDir;
30722
+ onChange;
31110
30723
  insertMissingStmt;
31111
30724
  upsertAvailableStmt;
31112
30725
  signatureStmt;
@@ -31179,6 +30792,7 @@ var SqliteInstalledPacksRepository = class {
31179
30792
  },
31180
30793
  "IMMEDIATE"
31181
30794
  );
30795
+ this.onChange();
31182
30796
  } catch {
31183
30797
  }
31184
30798
  }
@@ -31253,6 +30867,7 @@ var SqliteInstalledPacksRepository = class {
31253
30867
  },
31254
30868
  "IMMEDIATE"
31255
30869
  );
30870
+ if (changed) this.onChange();
31256
30871
  return changed;
31257
30872
  }
31258
30873
  /**
@@ -31494,6 +31109,7 @@ var SqliteInstalledPacksRepository = class {
31494
31109
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31495
31110
  WHERE namespace = :namespace AND pack_id = :packId`
31496
31111
  ).run({ policyId, now: Date.now(), namespace, packId });
31112
+ if (Number(res.changes) > 0) this.onChange();
31497
31113
  return Number(res.changes) > 0;
31498
31114
  }
31499
31115
  /**
@@ -31518,6 +31134,7 @@ var SqliteInstalledPacksRepository = class {
31518
31134
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31519
31135
  WHERE namespace = :namespace AND pack_id = :packId`
31520
31136
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31137
+ if (Number(res.changes) > 0) this.onChange();
31521
31138
  return Number(res.changes) > 0;
31522
31139
  }
31523
31140
  // Fingerprint of the recorded available mirror — compared against the
@@ -32415,13 +32032,19 @@ var SqliteInventoryAssetsRepository = class {
32415
32032
  import { randomUUID as randomUUID6 } from "crypto";
32416
32033
  var SEED_BATCH_WINDOW_MS = 6e4;
32417
32034
  var SqlitePoliciesRepository = class {
32418
- constructor(db) {
32035
+ constructor(db, onChange = () => void 0) {
32419
32036
  this.db = db;
32037
+ this.onChange = onChange;
32420
32038
  }
32421
32039
  db;
32040
+ onChange;
32422
32041
  readPolicies() {
32042
+ return Promise.resolve(this.listPolicies());
32043
+ }
32044
+ /** The synchronous read behind {@link readPolicies}. */
32045
+ listPolicies() {
32423
32046
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32424
- const policies = mapRowsTolerant(rows, (row) => {
32047
+ return mapRowsTolerant(rows, (row) => {
32425
32048
  const target = JSON.parse(row.target);
32426
32049
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32427
32050
  return Policy.parse({
@@ -32433,7 +32056,6 @@ var SqlitePoliciesRepository = class {
32433
32056
  customKeywords
32434
32057
  });
32435
32058
  });
32436
- return Promise.resolve(policies);
32437
32059
  }
32438
32060
  // Seed one policy per bundled category at Monitor so the detection-type config
32439
32061
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32444,7 +32066,7 @@ var SqlitePoliciesRepository = class {
32444
32066
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32445
32067
  if (count > 0) {
32446
32068
  this.markEarlierChoices();
32447
- this.monitorUntouchedSeeds();
32069
+ if (this.monitorUntouchedSeeds()) this.onChange();
32448
32070
  return;
32449
32071
  }
32450
32072
  const stmt = this.db.prepare(
@@ -32461,6 +32083,7 @@ var SqlitePoliciesRepository = class {
32461
32083
  });
32462
32084
  }
32463
32085
  });
32086
+ this.onChange();
32464
32087
  }
32465
32088
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32466
32089
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32526,7 +32149,7 @@ var SqlitePoliciesRepository = class {
32526
32149
  ).filter(
32527
32150
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32528
32151
  );
32529
- if (untouched.length === 0) return;
32152
+ if (untouched.length === 0) return false;
32530
32153
  const stmt = this.db.prepare(
32531
32154
  `UPDATE policies SET action = 'log'
32532
32155
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32537,6 +32160,7 @@ var SqlitePoliciesRepository = class {
32537
32160
  stmt.run({ category: row.category, seeded: row.action });
32538
32161
  }
32539
32162
  });
32163
+ return true;
32540
32164
  }
32541
32165
  // Insert-or-update the single global per-category policy row, keyed on the
32542
32166
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32553,6 +32177,7 @@ var SqlitePoliciesRepository = class {
32553
32177
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32554
32178
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32555
32179
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32180
+ this.onChange();
32556
32181
  }
32557
32182
  // Caps every global per-category policy currently set to block/redact down
32558
32183
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32563,6 +32188,7 @@ var SqlitePoliciesRepository = class {
32563
32188
  WHERE scope='global' AND action IN ('block','redact')
32564
32189
  AND json_extract(target,'$.category') IS NOT NULL`
32565
32190
  ).run({ now: Date.now() });
32191
+ if (Number(info.changes) > 0) this.onChange();
32566
32192
  return Number(info.changes);
32567
32193
  }
32568
32194
  // Whether the category's row was ever written after it was created — by the
@@ -32657,10 +32283,10 @@ var SqliteProjectFilesRepository = class {
32657
32283
  pruneStmt;
32658
32284
  maxStampStmt;
32659
32285
  /** Replace `projectId`'s tree with the scan's files. Caller wraps in a transaction. */
32660
- replaceForProject(projectId, scan2, now) {
32286
+ replaceForProject(projectId, scan, now) {
32661
32287
  const maxStamp = getRow(this.maxStampStmt, { projectId })?.maxStamp ?? 0;
32662
32288
  const stamp = Math.max(now, maxStamp + 1);
32663
- for (const file2 of scan2.files) {
32289
+ for (const file2 of scan.files) {
32664
32290
  this.upsertStmt.run({
32665
32291
  id: randomUUID7(),
32666
32292
  projectId,
@@ -32671,7 +32297,7 @@ var SqliteProjectFilesRepository = class {
32671
32297
  now: stamp
32672
32298
  });
32673
32299
  }
32674
- if (!scan2.truncated) this.pruneStmt.run({ projectId, now: stamp });
32300
+ if (!scan.truncated) this.pruneStmt.run({ projectId, now: stamp });
32675
32301
  }
32676
32302
  };
32677
32303
 
@@ -32882,31 +32508,45 @@ var SqliteScanLedgerRepository = class {
32882
32508
  constructor(db) {
32883
32509
  this.db = db;
32884
32510
  this.upsertStmt = db.prepare(
32885
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
32886
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32511
+ `INSERT INTO scan_ledger
32512
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32513
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
32887
32514
  ON CONFLICT (path) DO UPDATE SET
32888
32515
  mtime = excluded.mtime,
32889
32516
  content_hash = excluded.content_hash,
32890
32517
  ruleset_hash = excluded.ruleset_hash,
32518
+ scope_key = excluded.scope_key,
32519
+ scope_root = excluded.scope_root,
32891
32520
  scanned_at = excluded.scanned_at`
32892
32521
  );
32893
32522
  this.readStmt = db.prepare(
32894
- `SELECT path, mtime, content_hash AS contentHash
32523
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32524
+ scope_root AS scopeRoot
32895
32525
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
32896
32526
  );
32897
32527
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32528
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
32898
32529
  }
32899
32530
  db;
32900
32531
  upsertStmt;
32901
32532
  readStmt;
32902
32533
  pathsStmt;
32534
+ pathKeysStmt;
32903
32535
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
32904
32536
  // older ruleset are simply absent, which reads as "never scanned".
32905
32537
  entriesForRuleset(rulesetHash) {
32906
- const rows = allRows(this.readStmt, {
32907
- rulesetHash
32908
- });
32909
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32538
+ const rows = allRows(this.readStmt, { rulesetHash });
32539
+ return new Map(
32540
+ rows.map((r) => [
32541
+ r.path,
32542
+ {
32543
+ mtime: r.mtime,
32544
+ contentHash: r.contentHash,
32545
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32546
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32547
+ }
32548
+ ])
32549
+ );
32910
32550
  }
32911
32551
  // Every ledgered path, whatever ruleset it was scanned under — the set a
32912
32552
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -32915,6 +32555,14 @@ var SqliteScanLedgerRepository = class {
32915
32555
  allPaths() {
32916
32556
  return allRows(this.pathsStmt).map((r) => r.path);
32917
32557
  }
32558
+ // Every ledgered path with the repository it was in when it was last read,
32559
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32560
+ // which repository a vanished file belonged to. `undefined` for a row with no
32561
+ // key, which is every row written before the column existed.
32562
+ pathKeys() {
32563
+ const rows = allRows(this.pathKeysStmt);
32564
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32565
+ }
32918
32566
  upsertEntries(entries) {
32919
32567
  if (entries.length === 0) return;
32920
32568
  const scannedAt = Date.now();
@@ -32925,6 +32573,8 @@ var SqliteScanLedgerRepository = class {
32925
32573
  mtime: entry.mtime,
32926
32574
  contentHash: entry.contentHash,
32927
32575
  rulesetHash: entry.rulesetHash,
32576
+ scopeKey: entry.scopeKey ?? null,
32577
+ scopeRoot: entry.scopeRoot ?? null,
32928
32578
  scannedAt
32929
32579
  });
32930
32580
  }
@@ -34012,6 +33662,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34012
33662
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34013
33663
  };
34014
33664
  }
33665
+ function withoutTrailingSlashes(path) {
33666
+ let end = path.length;
33667
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33668
+ return path.slice(0, end);
33669
+ }
34015
33670
  function toEndpointSummary(row) {
34016
33671
  return {
34017
33672
  id: row.id,
@@ -34299,7 +33954,7 @@ var SqliteSharesRepository = class {
34299
33954
  */
34300
33955
  reconcileCallSites(projectKey, reconcile) {
34301
33956
  if (reconcile.mode === "walk") {
34302
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
33957
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34303
33958
  this.db.prepare(
34304
33959
  `DELETE FROM share_call_site
34305
33960
  WHERE project_key = :key
@@ -34867,7 +34522,7 @@ function backupLegacyStore(db, file2) {
34867
34522
  discardStore(file2, backup);
34868
34523
  return backup;
34869
34524
  }
34870
- function openAndInitialize(file2, base, skipTags) {
34525
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers) {
34871
34526
  let db = openWithPragmas(file2);
34872
34527
  try {
34873
34528
  if (isForeignSqliteLineage(db)) {
@@ -34879,8 +34534,15 @@ function openAndInitialize(file2, base, skipTags) {
34879
34534
  }
34880
34535
  applyMigrations(db, file2, { skipTags });
34881
34536
  tightenPerms(file2);
34882
- const policies = new SqlitePoliciesRepository(db);
34883
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34537
+ const modPolicy = {};
34538
+ const onPolicyStateChange = () => {
34539
+ if (modPolicy.current !== void 0)
34540
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34541
+ };
34542
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34543
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34544
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34545
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
34884
34546
  const repositories = {
34885
34547
  events: new SqliteEventsRepository(db),
34886
34548
  findings: new SqliteFindingsRepository(db),
@@ -34889,9 +34551,9 @@ function openAndInitialize(file2, base, skipTags) {
34889
34551
  scanLedger: new SqliteScanLedgerRepository(db),
34890
34552
  historySync: new SqliteHistorySyncRepository(db),
34891
34553
  secretVault: new SqliteSecretVaultRepository(db),
34892
- exceptions: new SqliteExceptionsRepository(db),
34554
+ exceptions,
34893
34555
  resolutions: new SqliteResolutionsRepository(db),
34894
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34556
+ ruleProbeCache,
34895
34557
  bodyRetention: new SqliteBodyRetentionRepository(db),
34896
34558
  security: new SqliteSecurityRepository(db),
34897
34559
  detections: new SqliteDetectionsRepository(db),
@@ -34909,6 +34571,13 @@ function openAndInitialize(file2, base, skipTags) {
34909
34571
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
34910
34572
  configInventory: new SqliteConfigInventoryRepository(db)
34911
34573
  };
34574
+ modPolicy.current = {
34575
+ installedRuleset: () => installedPacks.installedRuleset(),
34576
+ readPolicies: () => policies.listPolicies(),
34577
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34578
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34579
+ bundledRegexMatchers: () => shippedRegexMatchers
34580
+ };
34912
34581
  policies.seedDefaults();
34913
34582
  return { db, ...repositories };
34914
34583
  } catch (err) {
@@ -34920,7 +34589,7 @@ function openAndInitialize(file2, base, skipTags) {
34920
34589
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
34921
34590
  function openLocalDatabase(dir, options = {}) {
34922
34591
  ensureDataDirSync(dir);
34923
- const file2 = join7(dir, DB_FILENAME);
34592
+ const file2 = join8(dir, DB_FILENAME);
34924
34593
  reapStalePartials(file2);
34925
34594
  const {
34926
34595
  db,
@@ -34956,7 +34625,8 @@ function openLocalDatabase(dir, options = {}) {
34956
34625
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
34957
34626
  // settings/ and data/, and the pack-policy floor needs both halves.
34958
34627
  dirname2(dir),
34959
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34628
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34629
+ options.shippedRegexMatchers ?? []
34960
34630
  );
34961
34631
  function captureRowId(event) {
34962
34632
  return captureId(
@@ -35112,10 +34782,10 @@ function openLocalDatabase(dir, options = {}) {
35112
34782
  }
35113
34783
  });
35114
34784
  }
35115
- function recordProjectFiles(projectId, scan2) {
35116
- if (scan2.files.length === 0) return;
34785
+ function recordProjectFiles(projectId, scan) {
34786
+ if (scan.files.length === 0) return;
35117
34787
  failOpenTransaction(db, () => {
35118
- projectFiles.replaceForProject(projectId, scan2, Date.now());
34788
+ projectFiles.replaceForProject(projectId, scan, Date.now());
35119
34789
  });
35120
34790
  }
35121
34791
  async function transaction(fn) {
@@ -35221,39 +34891,39 @@ function openLocalDatabase(dir, options = {}) {
35221
34891
  }
35222
34892
 
35223
34893
  // ../../packages/persistence/src/egress-wire.ts
35224
- import { createHash as createHash3 } from "crypto";
34894
+ import { createHash as createHash4 } from "crypto";
35225
34895
  var SLASH = "/".charCodeAt(0);
35226
34896
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35227
34897
 
35228
34898
  // ../../packages/persistence/src/finding-key.ts
35229
- import { createHash as createHash4 } from "crypto";
34899
+ import { createHash as createHash5 } from "crypto";
35230
34900
 
35231
34901
  // ../../packages/persistence/src/fingerprint.ts
35232
34902
  import { createHmac, randomBytes } from "crypto";
35233
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35234
- import { join as join8 } from "path";
35235
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34903
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
34904
+ import { join as join9 } from "path";
35236
34905
 
35237
34906
  // ../../packages/persistence/src/forward-health.ts
35238
- import { readFileSync as readFileSync7 } from "fs";
35239
- import { join as join9 } from "path";
34907
+ import { readFileSync as readFileSync8 } from "fs";
34908
+ import { join as join10 } from "path";
35240
34909
 
35241
34910
  // ../../packages/persistence/src/history-backfill.ts
35242
34911
  import { existsSync as existsSync4 } from "fs";
35243
- import { join as join10 } from "path";
34912
+ import { join as join11 } from "path";
35244
34913
 
35245
34914
  // ../../packages/persistence/src/history-preview.ts
35246
34915
  import { existsSync as existsSync5 } from "fs";
35247
- import { join as join11 } from "path";
35248
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
34916
+ import { join as join12 } from "path";
34917
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35249
34918
 
35250
34919
  // ../../packages/persistence/src/history-sync-state.ts
35251
- import { readFileSync as readFileSync8 } from "fs";
35252
- import { join as join12 } from "path";
34920
+ import { readFileSync as readFileSync9 } from "fs";
34921
+ import { join as join13 } from "path";
34922
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35253
34923
 
35254
34924
  // ../../packages/persistence/src/store-symlinks.ts
35255
34925
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35256
- import { dirname as dirname3, join as join13, resolve } from "path";
34926
+ import { dirname as dirname3, join as join14, resolve } from "path";
35257
34927
 
35258
34928
  // ../../packages/persistence/src/vault/crypto.ts
35259
34929
  import {
@@ -35267,15 +34937,15 @@ import {
35267
34937
  // ../../packages/persistence/src/vault/key-provider.ts
35268
34938
  import { execFileSync } from "child_process";
35269
34939
  import { randomBytes as randomBytes2 } from "crypto";
35270
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35271
- import { join as join14 } from "path";
34940
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
34941
+ import { join as join15 } from "path";
35272
34942
 
35273
34943
  // ../../packages/persistence/src/vault/vault.ts
35274
34944
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35275
34945
 
35276
34946
  // ../../packages/persistence/src/warn-era-cap.ts
35277
34947
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35278
- import { join as join15 } from "path";
34948
+ import { join as join16 } from "path";
35279
34949
 
35280
34950
  // ../../packages/remote/src/http.ts
35281
34951
  import { request as httpRequest } from "http";
@@ -35289,1029 +34959,45 @@ var SLASH2 = "/".charCodeAt(0);
35289
34959
  var REQUEST_TIMEOUT_MS = 2e3;
35290
34960
 
35291
34961
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
35292
- import { readFileSync as readFileSync10 } from "fs";
35293
- import { join as join16 } from "path";
34962
+ import { readFileSync as readFileSync11 } from "fs";
34963
+ import { join as join17 } from "path";
35294
34964
 
35295
34965
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35296
- import { randomUUID as randomUUID16 } from "crypto";
34966
+ import { randomUUID as randomUUID13 } from "crypto";
35297
34967
  import { readFile, rename, writeFile } from "fs/promises";
35298
- import { join as join28 } from "path";
35299
-
35300
- // ../../packages/plugin-sdk/src/config.ts
35301
- import { existsSync as existsSync8 } from "fs";
35302
- import { join as join17 } from "path";
35303
-
35304
- // ../../packages/plugin-sdk/src/provider-env.ts
35305
- var booleanish = external_exports.string().optional().transform((v) => {
35306
- if (v === void 0) return void 0;
35307
- const t = v.trim().toLowerCase();
35308
- if (t === "" || t === "false" || t === "0") return false;
35309
- return true;
35310
- }).catch(void 0);
35311
- var optionalBaseUrl = external_exports.preprocess((v) => {
35312
- if (typeof v === "string" && v.trim() === "") return void 0;
35313
- return v;
35314
- }, external_exports.string().optional()).catch(void 0);
35315
- var providerEnvShape = {
35316
- CLAUDE_CODE_USE_BEDROCK: booleanish,
35317
- CLAUDE_CODE_USE_VERTEX: booleanish,
35318
- ANTHROPIC_BASE_URL: optionalBaseUrl
35319
- };
35320
- var ProviderEnvSchema = external_exports.object(providerEnvShape);
35321
-
35322
- // ../../packages/plugin-sdk/src/config-inventory.ts
35323
- import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
35324
- import { homedir as homedir2 } from "os";
35325
- import { basename as basename3, join as join19 } from "path";
35326
-
35327
- // ../../packages/detections/src/egress/registry.ts
35328
- var EXTRACTOR_VERSION = "3";
35329
- var PROVIDER_REGISTRY = [
35330
- {
35331
- id: "stripe",
35332
- name: "Stripe",
35333
- category: "Payments",
35334
- hostSuffixes: ["stripe.com"],
35335
- apiBase: "https://api.stripe.com",
35336
- defaultDataClasses: ["pii", "customer"],
35337
- sdks: {
35338
- npm: ["stripe"],
35339
- pypi: ["stripe"],
35340
- go: ["github.com/stripe/stripe-go"],
35341
- maven: ["com.stripe"],
35342
- rubygems: ["stripe"],
35343
- composer: ["stripe/stripe-php"],
35344
- nuget: ["Stripe.net"]
35345
- }
35346
- },
35347
- {
35348
- id: "datadog",
35349
- name: "Datadog",
35350
- category: "Observability",
35351
- hostSuffixes: ["datadoghq.com", "datadoghq.eu"],
35352
- apiBase: "https://api.datadoghq.com",
35353
- defaultDataClasses: ["telemetry", "logs", "metrics"],
35354
- sdks: {
35355
- npm: ["dd-trace", "@datadog/browser-logs"],
35356
- pypi: ["datadog", "ddtrace"],
35357
- go: ["github.com/DataDog/dd-trace-go"],
35358
- maven: ["com.datadoghq"],
35359
- rubygems: ["ddtrace", "dogapi"],
35360
- nuget: ["Datadog.Trace"]
35361
- }
35362
- },
35363
- {
35364
- id: "newrelic",
35365
- name: "New Relic",
35366
- category: "Observability",
35367
- hostSuffixes: ["newrelic.com", "nr-data.net"],
35368
- apiBase: "https://api.newrelic.com",
35369
- defaultDataClasses: ["telemetry", "logs", "metrics"],
35370
- sdks: {
35371
- npm: ["newrelic"],
35372
- pypi: ["newrelic"],
35373
- go: ["github.com/newrelic/go-agent"],
35374
- maven: ["com.newrelic.agent.java"],
35375
- rubygems: ["newrelic_rpm"],
35376
- nuget: ["NewRelic.Agent"]
35377
- }
35378
- },
35379
- {
35380
- id: "sentry",
35381
- name: "Sentry",
35382
- category: "Error tracking",
35383
- hostSuffixes: ["sentry.io"],
35384
- apiBase: "https://sentry.io",
35385
- defaultDataClasses: ["source", "telemetry"],
35386
- sdks: {
35387
- npm: ["@sentry/node", "@sentry/react", "@sentry/nextjs"],
35388
- pypi: ["sentry-sdk"],
35389
- go: ["github.com/getsentry/sentry-go"],
35390
- maven: ["io.sentry"],
35391
- rubygems: ["sentry-ruby"],
35392
- cargo: ["sentry"],
35393
- composer: ["sentry/sentry"],
35394
- nuget: ["Sentry"]
35395
- }
35396
- },
35397
- {
35398
- id: "openai",
35399
- name: "OpenAI",
35400
- category: "LLM provider",
35401
- hostSuffixes: ["openai.com"],
35402
- apiBase: "https://api.openai.com",
35403
- defaultDataClasses: ["pii", "source"],
35404
- sdks: {
35405
- npm: ["openai"],
35406
- pypi: ["openai"],
35407
- go: ["github.com/sashabaranov/go-openai"],
35408
- maven: ["com.openai"],
35409
- rubygems: ["ruby-openai"],
35410
- cargo: ["async-openai"],
35411
- composer: ["openai-php/client"],
35412
- nuget: ["OpenAI"]
35413
- }
35414
- },
35415
- {
35416
- id: "anthropic",
35417
- name: "Anthropic",
35418
- category: "LLM provider",
35419
- hostSuffixes: ["anthropic.com"],
35420
- apiBase: "https://api.anthropic.com",
35421
- defaultDataClasses: ["pii", "source"],
35422
- sdks: {
35423
- npm: ["@anthropic-ai/sdk"],
35424
- pypi: ["anthropic"],
35425
- go: ["github.com/anthropics/anthropic-sdk-go"],
35426
- nuget: ["Anthropic.SDK"]
35427
- }
35428
- },
35429
- {
35430
- id: "aws",
35431
- name: "Amazon Web Services",
35432
- category: "Cloud platform",
35433
- hostSuffixes: ["amazonaws.com"],
35434
- apiBase: "https://s3.amazonaws.com",
35435
- defaultDataClasses: ["secrets", "customer"],
35436
- sdks: {
35437
- npm: ["@aws-sdk/client-s3", "aws-sdk"],
35438
- pypi: ["boto3"],
35439
- go: ["github.com/aws/aws-sdk-go", "github.com/aws/aws-sdk-go-v2"],
35440
- maven: ["com.amazonaws", "software.amazon.awssdk"],
35441
- rubygems: ["aws-sdk-s3"],
35442
- cargo: ["aws-sdk-s3"],
35443
- nuget: ["AWSSDK.S3"]
35444
- }
35445
- },
35446
- {
35447
- id: "gcp",
35448
- name: "Google Cloud",
35449
- category: "Cloud platform",
35450
- hostSuffixes: ["googleapis.com"],
35451
- apiBase: "https://storage.googleapis.com",
35452
- defaultDataClasses: ["customer", "logs"],
35453
- sdks: {
35454
- npm: ["@google-cloud/storage"],
35455
- pypi: ["google-cloud-storage"],
35456
- go: ["cloud.google.com/go"],
35457
- maven: ["com.google.cloud"],
35458
- rubygems: ["google-cloud-storage"],
35459
- nuget: ["Google.Cloud.Storage.V1"]
35460
- }
35461
- },
35462
- {
35463
- id: "google-fonts",
35464
- name: "Google Fonts",
35465
- category: "CDN / edge",
35466
- hostSuffixes: ["fonts.googleapis.com", "fonts.gstatic.com"],
35467
- apiBase: "https://fonts.googleapis.com",
35468
- defaultDataClasses: ["none"],
35469
- sdks: {}
35470
- },
35471
- {
35472
- id: "azure",
35473
- name: "Microsoft Azure",
35474
- category: "Cloud platform",
35475
- hostSuffixes: ["azure.com", "windows.net"],
35476
- apiBase: "https://management.azure.com",
35477
- defaultDataClasses: ["customer", "logs"],
35478
- sdks: {
35479
- npm: ["@azure/storage-blob"],
35480
- pypi: ["azure-storage-blob"],
35481
- go: ["github.com/Azure/azure-sdk-for-go"],
35482
- maven: ["com.azure"],
35483
- rubygems: ["azure-storage-blob"],
35484
- nuget: ["Azure.Storage.Blobs"]
35485
- }
35486
- },
35487
- {
35488
- id: "slack",
35489
- name: "Slack",
35490
- category: "Notifications",
35491
- hostSuffixes: ["slack.com"],
35492
- apiBase: "https://slack.com/api",
35493
- defaultDataClasses: ["logs"],
35494
- sdks: {
35495
- npm: ["@slack/web-api"],
35496
- pypi: ["slack-sdk"],
35497
- go: ["github.com/slack-go/slack"],
35498
- maven: ["com.slack.api"],
35499
- rubygems: ["slack-ruby-client"],
35500
- composer: ["slack-php/slack-api"],
35501
- nuget: ["SlackNet"]
35502
- }
35503
- },
35504
- {
35505
- id: "segment",
35506
- name: "Segment",
35507
- category: "Analytics",
35508
- hostSuffixes: ["segment.io", "segment.com"],
35509
- apiBase: "https://api.segment.io",
35510
- defaultDataClasses: ["customer"],
35511
- sdks: {
35512
- npm: ["@segment/analytics-node", "analytics-node"],
35513
- pypi: ["segment-analytics-python"],
35514
- go: ["github.com/segmentio/analytics-go"],
35515
- maven: ["com.segment.analytics.java"],
35516
- rubygems: ["analytics-ruby"],
35517
- nuget: ["Analytics"]
35518
- }
35519
- },
35520
- {
35521
- id: "twilio",
35522
- name: "Twilio",
35523
- category: "Communications",
35524
- hostSuffixes: ["twilio.com"],
35525
- apiBase: "https://api.twilio.com",
35526
- defaultDataClasses: ["pii", "customer"],
35527
- sdks: {
35528
- npm: ["twilio"],
35529
- pypi: ["twilio"],
35530
- go: ["github.com/twilio/twilio-go"],
35531
- maven: ["com.twilio.sdk"],
35532
- rubygems: ["twilio-ruby"],
35533
- composer: ["twilio/sdk"],
35534
- nuget: ["Twilio"]
35535
- }
35536
- },
35537
- {
35538
- id: "sendgrid",
35539
- name: "SendGrid",
35540
- category: "Email",
35541
- hostSuffixes: ["sendgrid.com"],
35542
- apiBase: "https://api.sendgrid.com",
35543
- defaultDataClasses: ["pii"],
35544
- sdks: {
35545
- npm: ["@sendgrid/mail"],
35546
- pypi: ["sendgrid"],
35547
- go: ["github.com/sendgrid/sendgrid-go"],
35548
- maven: ["com.sendgrid"],
35549
- rubygems: ["sendgrid-ruby"],
35550
- composer: ["sendgrid/sendgrid"],
35551
- nuget: ["SendGrid"]
35552
- }
35553
- },
35554
- {
35555
- id: "mailgun",
35556
- name: "Mailgun",
35557
- category: "Email",
35558
- hostSuffixes: ["mailgun.net"],
35559
- apiBase: "https://api.mailgun.net",
35560
- defaultDataClasses: ["pii"],
35561
- sdks: {
35562
- npm: ["mailgun.js"],
35563
- pypi: ["mailgun"],
35564
- rubygems: ["mailgun-ruby"],
35565
- composer: ["mailgun/mailgun-php"],
35566
- nuget: ["Mailgun"]
35567
- }
35568
- },
35569
- {
35570
- id: "mixpanel",
35571
- name: "Mixpanel",
35572
- category: "Analytics",
35573
- hostSuffixes: ["mixpanel.com"],
35574
- apiBase: "https://api.mixpanel.com",
35575
- defaultDataClasses: ["customer", "telemetry"],
35576
- sdks: {
35577
- npm: ["mixpanel"],
35578
- pypi: ["mixpanel"],
35579
- rubygems: ["mixpanel-ruby"],
35580
- nuget: ["Mixpanel"]
35581
- }
35582
- },
35583
- {
35584
- id: "amplitude",
35585
- name: "Amplitude",
35586
- category: "Analytics",
35587
- hostSuffixes: ["amplitude.com"],
35588
- apiBase: "https://api2.amplitude.com",
35589
- defaultDataClasses: ["customer", "telemetry"],
35590
- sdks: {
35591
- npm: ["@amplitude/analytics-node"],
35592
- pypi: ["amplitude-analytics"],
35593
- nuget: ["Amplitude"]
35594
- }
35595
- },
35596
- {
35597
- id: "posthog",
35598
- name: "PostHog",
35599
- category: "Analytics",
35600
- hostSuffixes: ["posthog.com"],
35601
- apiBase: "https://us.i.posthog.com",
35602
- defaultDataClasses: ["customer", "telemetry"],
35603
- sdks: {
35604
- npm: ["posthog-node", "posthog-js"],
35605
- pypi: ["posthog"],
35606
- go: ["github.com/posthog/posthog-go"],
35607
- rubygems: ["posthog-ruby"],
35608
- composer: ["posthog/posthog-php"],
35609
- nuget: ["PostHog"]
35610
- }
35611
- },
35612
- {
35613
- id: "honeycomb",
35614
- name: "Honeycomb",
35615
- category: "Observability",
35616
- hostSuffixes: ["honeycomb.io"],
35617
- apiBase: "https://api.honeycomb.io",
35618
- defaultDataClasses: ["telemetry", "metrics"],
35619
- sdks: {
35620
- npm: ["libhoney"],
35621
- pypi: ["libhoney"],
35622
- go: ["github.com/honeycombio/libhoney-go"],
35623
- rubygems: ["libhoney"]
35624
- }
35625
- },
35626
- {
35627
- id: "grafana",
35628
- name: "Grafana Cloud",
35629
- category: "Observability",
35630
- hostSuffixes: ["grafana.net"],
35631
- apiBase: "https://grafana.net",
35632
- defaultDataClasses: ["logs", "metrics"],
35633
- sdks: {
35634
- npm: ["@grafana/faro-web-sdk"]
35635
- }
35636
- },
35637
- {
35638
- id: "splunk",
35639
- name: "Splunk",
35640
- category: "Observability",
35641
- hostSuffixes: ["splunkcloud.com", "splunk.com"],
35642
- apiBase: "https://http-inputs.splunkcloud.com",
35643
- defaultDataClasses: ["logs"],
35644
- sdks: {
35645
- npm: ["splunk-logging"],
35646
- pypi: ["splunk-sdk"],
35647
- maven: ["com.splunk"],
35648
- nuget: ["Splunk.Logging.Common"]
35649
- }
35650
- },
35651
- {
35652
- id: "pagerduty",
35653
- name: "PagerDuty",
35654
- category: "Incident response",
35655
- hostSuffixes: ["pagerduty.com"],
35656
- apiBase: "https://api.pagerduty.com",
35657
- defaultDataClasses: ["logs"],
35658
- sdks: {
35659
- npm: ["@pagerduty/pdjs"],
35660
- pypi: ["pdpyras"],
35661
- go: ["github.com/PagerDuty/go-pagerduty"],
35662
- rubygems: ["pagerduty"]
35663
- }
35664
- },
35665
- {
35666
- id: "github",
35667
- name: "GitHub",
35668
- category: "Developer platform",
35669
- hostSuffixes: ["github.com", "githubusercontent.com"],
35670
- apiBase: "https://api.github.com",
35671
- defaultDataClasses: ["source"],
35672
- sdks: {
35673
- npm: ["@octokit/rest", "octokit"],
35674
- pypi: ["pygithub"],
35675
- go: ["github.com/google/go-github"],
35676
- maven: ["org.kohsuke.github-api"],
35677
- rubygems: ["octokit"],
35678
- cargo: ["octocrab"],
35679
- composer: ["knplabs/github-api"],
35680
- nuget: ["Octokit"]
35681
- }
35682
- },
35683
- {
35684
- id: "gitlab",
35685
- name: "GitLab",
35686
- category: "Developer platform",
35687
- hostSuffixes: ["gitlab.com"],
35688
- apiBase: "https://gitlab.com/api",
35689
- defaultDataClasses: ["source"],
35690
- sdks: {
35691
- npm: ["@gitbeaker/rest"],
35692
- pypi: ["python-gitlab"],
35693
- go: ["gitlab.com/gitlab-org/api/client-go"],
35694
- rubygems: ["gitlab"],
35695
- nuget: ["GitLabApiClient"]
35696
- }
35697
- },
35698
- {
35699
- id: "auth0",
35700
- name: "Auth0",
35701
- category: "Identity",
35702
- hostSuffixes: ["auth0.com"],
35703
- apiBase: "https://login.auth0.com",
35704
- defaultDataClasses: ["pii"],
35705
- sdks: {
35706
- npm: ["auth0"],
35707
- pypi: ["auth0-python"],
35708
- go: ["github.com/auth0/go-auth0"],
35709
- maven: ["com.auth0"],
35710
- rubygems: ["auth0"],
35711
- composer: ["auth0/auth0-php"],
35712
- nuget: ["Auth0.ManagementApi"]
35713
- }
35714
- },
35715
- {
35716
- id: "okta",
35717
- name: "Okta",
35718
- category: "Identity",
35719
- hostSuffixes: ["okta.com", "oktapreview.com"],
35720
- apiBase: "https://login.okta.com",
35721
- defaultDataClasses: ["pii"],
35722
- sdks: {
35723
- npm: ["@okta/okta-sdk-nodejs"],
35724
- pypi: ["okta"],
35725
- go: ["github.com/okta/okta-sdk-golang"],
35726
- maven: ["com.okta.sdk"],
35727
- nuget: ["Okta.Sdk"]
35728
- }
35729
- },
35730
- {
35731
- id: "clerk",
35732
- name: "Clerk",
35733
- category: "Identity",
35734
- hostSuffixes: ["clerk.com", "clerk.dev"],
35735
- apiBase: "https://api.clerk.com",
35736
- defaultDataClasses: ["pii"],
35737
- sdks: {
35738
- npm: ["@clerk/backend", "@clerk/nextjs"],
35739
- pypi: ["clerk-backend-api"],
35740
- go: ["github.com/clerk/clerk-sdk-go"]
35741
- }
35742
- },
35743
- {
35744
- id: "supabase",
35745
- name: "Supabase",
35746
- category: "Backend platform",
35747
- hostSuffixes: ["supabase.co", "supabase.com"],
35748
- apiBase: "https://api.supabase.com",
35749
- defaultDataClasses: ["pii", "customer"],
35750
- sdks: {
35751
- npm: ["@supabase/supabase-js"],
35752
- pypi: ["supabase"],
35753
- cargo: ["postgrest"]
35754
- }
35755
- },
35756
- {
35757
- id: "firebase",
35758
- name: "Firebase",
35759
- category: "Backend platform",
35760
- hostSuffixes: ["firebaseio.com", "firebase.google.com"],
35761
- apiBase: "https://firebaseio.com",
35762
- defaultDataClasses: ["customer"],
35763
- sdks: {
35764
- npm: ["firebase", "firebase-admin"],
35765
- pypi: ["firebase-admin"],
35766
- go: ["firebase.google.com/go"],
35767
- maven: ["com.google.firebase"]
35768
- }
35769
- },
35770
- {
35771
- id: "mongodb-atlas",
35772
- name: "MongoDB Atlas",
35773
- category: "Database SaaS",
35774
- hostSuffixes: ["mongodb.net", "mongodb.com"],
35775
- apiBase: "https://cloud.mongodb.com",
35776
- defaultDataClasses: ["customer"],
35777
- sdks: {
35778
- npm: ["mongodb"],
35779
- pypi: ["pymongo"],
35780
- go: ["go.mongodb.org/mongo-driver"],
35781
- maven: ["org.mongodb"],
35782
- rubygems: ["mongo"],
35783
- cargo: ["mongodb"],
35784
- nuget: ["MongoDB.Driver"]
35785
- }
35786
- },
35787
- {
35788
- id: "planetscale",
35789
- name: "PlanetScale",
35790
- category: "Database SaaS",
35791
- hostSuffixes: ["psdb.cloud", "planetscale.com"],
35792
- apiBase: "https://api.planetscale.com",
35793
- defaultDataClasses: ["customer"],
35794
- sdks: {
35795
- npm: ["@planetscale/database"],
35796
- go: ["github.com/planetscale/planetscale-go"]
35797
- }
35798
- },
35799
- {
35800
- id: "algolia",
35801
- name: "Algolia",
35802
- category: "Search SaaS",
35803
- hostSuffixes: ["algolia.net", "algolianet.com"],
35804
- apiBase: "https://algolia.net",
35805
- defaultDataClasses: ["customer"],
35806
- sdks: {
35807
- npm: ["algoliasearch"],
35808
- pypi: ["algoliasearch"],
35809
- go: ["github.com/algolia/algoliasearch-client-go"],
35810
- maven: ["com.algolia"],
35811
- rubygems: ["algolia"],
35812
- composer: ["algolia/algoliasearch-client-php"],
35813
- nuget: ["Algolia.Search"]
35814
- }
35815
- },
35816
- {
35817
- id: "cloudflare",
35818
- name: "Cloudflare",
35819
- category: "CDN / edge",
35820
- hostSuffixes: ["cloudflare.com", "workers.dev"],
35821
- apiBase: "https://api.cloudflare.com",
35822
- defaultDataClasses: ["logs"],
35823
- sdks: {
35824
- npm: ["cloudflare"],
35825
- pypi: ["cloudflare"],
35826
- go: ["github.com/cloudflare/cloudflare-go"],
35827
- nuget: ["CloudFlare.Client"]
35828
- }
35829
- },
35830
- {
35831
- id: "huggingface",
35832
- name: "Hugging Face",
35833
- category: "LLM provider",
35834
- hostSuffixes: ["huggingface.co"],
35835
- apiBase: "https://api-inference.huggingface.co",
35836
- defaultDataClasses: ["source"],
35837
- sdks: {
35838
- npm: ["@huggingface/inference"],
35839
- pypi: ["huggingface-hub", "transformers"],
35840
- rubygems: ["hugging-face"]
35841
- }
35842
- },
35843
- {
35844
- id: "cohere",
35845
- name: "Cohere",
35846
- category: "LLM provider",
35847
- hostSuffixes: ["cohere.com", "cohere.ai"],
35848
- apiBase: "https://api.cohere.com",
35849
- defaultDataClasses: ["pii", "source"],
35850
- sdks: {
35851
- npm: ["cohere-ai"],
35852
- pypi: ["cohere"],
35853
- go: ["github.com/cohere-ai/cohere-go"]
35854
- }
35855
- },
35856
- {
35857
- id: "mistral",
35858
- name: "Mistral AI",
35859
- category: "LLM provider",
35860
- hostSuffixes: ["mistral.ai"],
35861
- apiBase: "https://api.mistral.ai",
35862
- defaultDataClasses: ["pii", "source"],
35863
- sdks: {
35864
- npm: ["@mistralai/mistralai"],
35865
- pypi: ["mistralai"],
35866
- go: ["github.com/gage-technologies/mistral-go"]
35867
- }
35868
- }
35869
- ];
35870
- var EXCLUDED_HOST_SUFFIXES = [
35871
- "localhost",
35872
- "test",
35873
- "example",
35874
- "invalid",
35875
- "example.com",
35876
- "example.org",
35877
- "example.net",
35878
- "w3.org",
35879
- "schemas.openxmlformats.org",
35880
- "schemas.microsoft.com",
35881
- "schemas.android.com",
35882
- "maven.apache.org"
35883
- ];
35884
- var EGRESS_VERSION_MATERIAL = `${EXTRACTOR_VERSION}
35885
- ${JSON.stringify(PROVIDER_REGISTRY)}
35886
- ${JSON.stringify(EXCLUDED_HOST_SUFFIXES)}`;
35887
-
35888
- // ../../packages/detections/src/egress/extract.ts
35889
- var SECRET_KEY_NAMES = "api[_-]?key|apikey|private[_-]?key|access[_-]?key|access[_-]?token|token|secret|credentials?|password|passwd|pwd|authorization|sig|signature|sas|assertion";
35890
- var AUTH_SCHEMES = "Bearer|Basic|Token|Digest|ApiKey|SSWS|AWS4-HMAC-SHA256";
35891
- var SECRET_VALUE = new RegExp(
35892
- `((?:${SECRET_KEY_NAMES})['"\`]?\\s*[:=]\\s*['"\`]?)(?!(?:${AUTH_SCHEMES})[\\s'"\`])[^\\s'"\`&]+`,
35893
- "gi"
35894
- );
35895
- var AUTH_SCHEME_VALUE = new RegExp(
35896
- `((?:${SECRET_KEY_NAMES})['"\`]?\\s*[:=]\\s*['"\`]?)(${AUTH_SCHEMES})\\s+[^\\s'"\`]+`,
35897
- "gi"
35898
- );
35899
- var WEBHOOK_SECRET_PATHS = [
35900
- { hosts: ["hooks.slack.com"], prefix: "/services/" },
35901
- {
35902
- hosts: ["discord.com", "discordapp.com", "ptb.discord.com", "canary.discord.com"],
35903
- prefix: "/api/webhooks/"
35904
- },
35905
- { hosts: ["hooks.zapier.com"], prefix: "/hooks/" },
35906
- { hosts: ["outlook.office.com", "outlook.office365.com"], prefix: "/webhook/" }
35907
- ];
35908
- function escapeRegExp(literal2) {
35909
- return literal2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35910
- }
35911
- var WEBHOOK_URL = new RegExp(
35912
- `(https?://(?:${WEBHOOK_SECRET_PATHS.flatMap(
35913
- (entry) => entry.hosts.map((host) => `${escapeRegExp(host)}${escapeRegExp(entry.prefix)}`)
35914
- ).join("|")}))[^\\s'"\`<>()[\\]{},;]+`,
35915
- "gi"
35916
- );
35917
-
35918
- // ../../packages/detections/src/escape-regexp.ts
35919
- function escapeRegExp2(value) {
35920
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35921
- }
35922
-
35923
- // ../../packages/detections/src/format-chars.ts
35924
- var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
35925
- var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
35926
-
35927
- // ../../packages/detections/src/regex-cache.ts
35928
- var singles = /* @__PURE__ */ new WeakMap();
35929
- var keywordLists = /* @__PURE__ */ new WeakMap();
35930
- var labelLists = /* @__PURE__ */ new WeakMap();
35931
- function listCache(kind) {
35932
- return kind === "keyword" ? keywordLists : labelLists;
35933
- }
35934
- function memoizedRegExp(owner, build) {
35935
- const cached2 = singles.get(owner);
35936
- if (cached2 !== void 0) {
35937
- cached2.lastIndex = 0;
35938
- return cached2;
35939
- }
35940
- const compiled = build();
35941
- singles.set(owner, compiled);
35942
- return compiled;
35943
- }
35944
- function memoizedRegExpList(kind, owner, build) {
35945
- const cache = listCache(kind);
35946
- const cached2 = cache.get(owner);
35947
- if (cached2 !== void 0) {
35948
- if (cached2.stateful) {
35949
- for (const re of cached2.entries) if (re !== void 0) re.lastIndex = 0;
35950
- }
35951
- return cached2.entries;
35952
- }
35953
- const entries = build();
35954
- cache.set(owner, {
35955
- entries,
35956
- stateful: entries.some((re) => re !== void 0 && (re.global || re.sticky))
35957
- });
35958
- return entries;
35959
- }
35960
-
35961
- // ../../packages/detections/src/matchers/limits.ts
35962
- var MAX_MATCHES_PER_RULE = 1e4;
35963
- var MAX_REGEX_INPUT_LENGTH = 2e5;
35964
-
35965
- // ../../packages/detections/src/matchers/keyword.ts
35966
- var KeywordMatcher2 = class {
35967
- match(text, rule) {
35968
- if (rule.matcher.type !== "keyword") return [];
35969
- const { keywords, caseSensitive } = rule.matcher;
35970
- const spans = [];
35971
- const compiled = memoizedRegExpList(
35972
- "keyword",
35973
- rule.matcher,
35974
- () => keywords.map((kw) => {
35975
- if (kw.length === 0) return void 0;
35976
- return new RegExp(escapeRegExp2(kw), caseSensitive ? "gu" : "giu");
35977
- })
35978
- );
35979
- for (const re of compiled) {
35980
- if (re === void 0) continue;
35981
- if (spans.length >= MAX_MATCHES_PER_RULE) break;
35982
- let m;
35983
- while ((m = re.exec(text)) !== null) {
35984
- spans.push({ start: m.index, end: m.index + m[0].length });
35985
- if (spans.length >= MAX_MATCHES_PER_RULE) break;
35986
- }
35987
- }
35988
- return spans;
35989
- }
35990
- };
35991
-
35992
- // ../../packages/detections/src/matchers/regex.ts
35993
- var RegexMatcher2 = class {
35994
- match(text, rule) {
35995
- if (rule.matcher.type !== "regex") return [];
35996
- const { pattern, flags, captureGroup } = rule.matcher;
35997
- const re = memoizedRegExp(
35998
- rule.matcher,
35999
- () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
36000
- );
36001
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36002
- const spans = [];
36003
- let m;
36004
- const maxIterations = scanText2.length + 1;
36005
- let iterations = 0;
36006
- while ((m = re.exec(scanText2)) !== null) {
36007
- if (++iterations > maxIterations) break;
36008
- const group = captureGroup != null ? m[captureGroup] : m[0];
36009
- if (m[0].length === 0) re.lastIndex++;
36010
- if (group && spans.length < MAX_MATCHES_PER_RULE) {
36011
- const groupIndices = captureGroup != null ? m.indices?.[captureGroup] : void 0;
36012
- const start = groupIndices ? groupIndices[0] : m.index;
36013
- spans.push({ start, end: start + group.length });
36014
- }
36015
- if (!flags.includes("g") || spans.length >= MAX_MATCHES_PER_RULE) break;
36016
- }
36017
- return spans;
36018
- }
36019
- };
36020
-
36021
- // ../../packages/detections/src/engine.ts
36022
- var keywordMatcher = new KeywordMatcher2();
36023
- var regexMatcher = new RegexMatcher2();
36024
-
36025
- // ../../packages/detections/src/posture/config-posture.ts
36026
- var RULE_VERSION = "1";
36027
- var KNOWN_TOOLS = /* @__PURE__ */ new Set([
36028
- "prettier",
36029
- "eslint",
36030
- "biome",
36031
- "black",
36032
- "ruff",
36033
- "gofmt",
36034
- "rustfmt",
36035
- "node",
36036
- "npx",
36037
- "npm",
36038
- "pnpm",
36039
- "yarn",
36040
- "make",
36041
- "git",
36042
- "jq",
36043
- "echo"
36044
- ]);
36045
- var EGRESS_RE = /\b(curl|wget|nc|ncat|netcat|ssh|scp|rsync)\b|https?:\/\//;
36046
- var MUTATION_RE = /(--write|--fix|\s-w\b|\s-i\b|(?<![\d&>])>\s?\S)/;
36047
- var CONFIG_POSTURE_RULES = [
36048
- {
36049
- ruleId: "hook-conflict",
36050
- version: RULE_VERSION,
36051
- name: "Overlapping hooks \u2014 run order is undefined",
36052
- category: "config",
36053
- severity: "medium",
36054
- definition: JSON.stringify({
36055
- kind: "hook-conflict",
36056
- mutation: MUTATION_RE.source,
36057
- note: "two hooks on the same event with overlapping matchers, both mutating the tool target"
36058
- })
36059
- },
36060
- {
36061
- ruleId: "hook-unknown",
36062
- version: RULE_VERSION,
36063
- name: "Unknown hook \u2014 not attributable to a plugin or known tool",
36064
- category: "config",
36065
- // medium, not high: with a deliberately tiny allowlist this v1 heuristic
36066
- // fires on ordinary interpreter hooks (python3 x.py) and compound commands
36067
- // (cd … && tool); 'high' is reserved for egress, which is genuinely
36068
- // dangerous. Revisit when the known-hooks registry replaces the allowlist.
36069
- severity: "medium",
36070
- definition: JSON.stringify({ kind: "hook-unknown", knownTools: [...KNOWN_TOOLS] })
36071
- },
36072
- {
36073
- ruleId: "hook-external-egress",
36074
- version: RULE_VERSION,
36075
- name: "Hook command can send data externally",
36076
- category: "config",
36077
- severity: "high",
36078
- definition: JSON.stringify({ kind: "hook-external-egress", pattern: EGRESS_RE.source })
36079
- }
36080
- ];
36081
-
36082
- // ../../packages/detections/src/posture/web-capture-posture.ts
36083
- var RULE_VERSION2 = "1";
36084
- var DRIFT_MIN_PARSE_FAILURES = 2;
36085
- var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
36086
- "blind",
36087
- "degraded"
36088
- ]);
36089
- var WEB_CAPTURE_DRIFT_RULE = {
36090
- ruleId: "web-capture-drift",
36091
- version: RULE_VERSION2,
36092
- name: "Web chat capture is not reading the site",
36093
- category: "config",
36094
- severity: "medium",
36095
- definition: JSON.stringify({
36096
- kind: "web-capture-drift",
36097
- states: [...WEB_CAPTURE_DRIFT_STATES],
36098
- minParseFailures: DRIFT_MIN_PARSE_FAILURES
36099
- })
36100
- };
36101
- var STATIC_COPY = {
36102
- active: { headline: "turns are being observed on this site" },
36103
- unreported: {
36104
- // Says "recently" rather than "yet": the store read is bounded to
36105
- // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
36106
- // reported for AND one whose last report has aged out. The two are the
36107
- // same fact to a reader — nobody has confirmed anything lately — and the
36108
- // copy may not claim the stronger of them.
36109
- headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
36110
- },
36111
- standby: {
36112
- headline: "this build declares no endpoints for the site, so nothing is observed yet"
36113
- },
36114
- unpatched: {
36115
- // Says what the flags say and no more. `patched` is false both for a tap
36116
- // that installed and hooked neither transport and for one that never ran
36117
- // at all — a page reports the same status either way, so the copy may not
36118
- // assert one of them.
36119
- headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
36120
- },
36121
- idle: { headline: "watching; no turn has been observed yet" },
36122
- blind: {
36123
- headline: "messages were sent in the page that the network capture never saw",
36124
- remediation: "reload the tab. If it persists after `aka update` and reloading the extension at chrome://extensions, the site's send path has changed and needs a new extension build."
36125
- },
36126
- degraded: {
36127
- headline: "the site's payloads no longer carry the fields the extension reads",
36128
- remediation: "run `aka update`, then reload the extension at chrome://extensions. If it stays degraded after an update, the site's contract has changed and needs a new extension build."
36129
- }
36130
- };
36131
-
36132
- // ../../packages/detections/src/security/redos-probe.ts
36133
- var BUDGET_MS = 100;
36134
- var EXPONENTIAL_UNITS = [
36135
- "a",
36136
- "0",
36137
- " ",
36138
- "x",
36139
- "ab",
36140
- "a.",
36141
- "a-",
36142
- "a_",
36143
- "a@",
36144
- "a/",
36145
- "a:",
36146
- "a=",
36147
- "a;",
36148
- "aA0",
36149
- " "
36150
- ];
36151
- var EXPONENTIAL_PROBES = EXPONENTIAL_UNITS.flatMap(
36152
- (unit) => [23, 25].map((len) => unit.repeat(Math.ceil(len / unit.length)).slice(0, len) + "!")
36153
- );
36154
- var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map(
36155
- (unit) => unit.repeat(1e4).slice(0, 4e4) + "!"
36156
- );
36157
- var CPU_CORROBORATION_SHARE = 0.2;
36158
- var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36159
-
36160
- // ../../packages/plugin-sdk/src/repo.ts
36161
- import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36162
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36163
- var NO_ATTRIBUTION = Object.freeze({});
36164
-
36165
- // ../../packages/plugin-sdk/src/events.ts
36166
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36167
-
36168
- // ../../packages/plugin-sdk/src/isolated-scan.ts
36169
- import { existsSync as existsSync10 } from "fs";
36170
- import { fileURLToPath } from "url";
36171
- import { Worker } from "worker_threads";
36172
-
36173
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
36174
- import { readFileSync as readFileSync13 } from "fs";
36175
- import { join as join20 } from "path";
36176
-
36177
- // ../../packages/plugin-sdk/src/host-floor.ts
36178
- import { readFileSync as readFileSync15 } from "fs";
36179
- import { join as join22 } from "path";
36180
-
36181
- // ../../packages/plugin-sdk/src/model-governance.ts
36182
- import {
36183
- closeSync as closeSync2,
36184
- fstatSync,
36185
- mkdirSync as mkdirSync2,
36186
- openSync as openSync2,
36187
- readFileSync as readFileSync14,
36188
- readSync,
36189
- writeFileSync as writeFileSync5
36190
- } from "fs";
36191
- import { join as join21 } from "path";
36192
- var TAIL_BYTES = 256 * 1024;
36193
-
36194
- // ../../packages/plugin-sdk/src/host-floor.ts
36195
- var HOST_FEATURE = {
36196
- ModelSwitch: "model-switch",
36197
- VaultPointerDisplay: "vault-pointer-display"
36198
- };
36199
- var HOST_FLOORS = {
36200
- [HOST_FEATURE.ModelSwitch]: {
36201
- label: "model-switch protection",
36202
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
36203
- since: "2.1.251"
36204
- },
36205
- [HOST_FEATURE.VaultPointerDisplay]: {
36206
- label: "vault pointer display",
36207
- hookEvents: ["MessageDisplay"],
36208
- since: "2.1.152"
36209
- }
36210
- };
36211
- var ANTIGRAVITY_HOST_FEATURE = {
36212
- EndOfTurnCapture: "end-of-turn-capture"
36213
- };
36214
- var ANTIGRAVITY_HOST_FLOORS = {
36215
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
36216
- label: "end-of-turn history capture",
36217
- hookEvents: ["Stop"],
36218
- since: "1.1.10"
36219
- }
36220
- };
36221
-
36222
- // ../../packages/plugin-sdk/src/ignore-layers.ts
36223
- var import_ignore = __toESM(require_ignore(), 1);
36224
- import { readFileSync as readFileSync16 } from "fs";
36225
- import { join as join23 } from "path";
36226
-
36227
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
36228
- import { arch, hostname as hostname4, platform, release } from "os";
36229
-
36230
- // ../../packages/plugin-sdk/src/nudge.ts
36231
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
36232
- import { join as join24 } from "path";
36233
-
36234
- // ../../packages/plugin-sdk/src/paths.ts
36235
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36236
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36237
-
36238
- // ../../packages/plugin-sdk/src/policy-resolver.ts
36239
- import { randomUUID as randomUUID14 } from "crypto";
36240
-
36241
- // ../../packages/plugin-sdk/src/project-files.ts
36242
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36243
- import { basename as basename5, join as join25 } from "path";
36244
-
36245
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36246
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
36247
- if (typeof v === "string" && v.trim() === "") return void 0;
36248
- return v;
36249
- }, external_exports.string().optional()).catch(void 0);
36250
- var optionalFlag = external_exports.preprocess((v) => {
36251
- if (typeof v !== "string") return false;
36252
- const normalized = v.trim().toLowerCase();
36253
- return normalized !== "" && normalized !== "0" && normalized !== "false";
36254
- }, external_exports.boolean()).catch(false);
36255
- var antigravityProviderEnvShape = {
36256
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
36257
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
36258
- };
36259
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
36260
-
36261
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
36262
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
36263
- if (typeof v === "string" && v.trim() === "") return void 0;
36264
- return v;
36265
- }, external_exports.string().optional()).catch(void 0);
36266
- var codexProviderEnvShape = {
36267
- OPENAI_BASE_URL: optionalBaseUrl3
36268
- };
36269
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
36270
-
36271
- // ../../packages/plugin-sdk/src/runtime.ts
36272
- import { randomUUID as randomUUID15 } from "crypto";
36273
-
36274
- // ../../packages/plugin-sdk/src/scope-key.ts
36275
- import { existsSync as existsSync12 } from "fs";
36276
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
36277
-
36278
- // ../../packages/plugin-sdk/src/suppressions.ts
36279
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36280
-
36281
- // ../../packages/plugin-sdk/src/throttle.ts
36282
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36283
- import { join as join27 } from "path";
34968
+ import { join as join18 } from "path";
36284
34969
 
36285
34970
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36286
34971
  import { createHash as createHash6 } from "crypto";
36287
- import { hostname as hostname5 } from "os";
34972
+ import { hostname as hostname4 } from "os";
36288
34973
 
36289
34974
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
36290
34975
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36291
34976
  var TRACE_ID = EventMetadata.shape.traceId;
36292
34977
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
36293
34978
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
34979
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
36294
34980
 
36295
34981
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36296
34982
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
36297
34983
 
36298
34984
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36299
34985
  import { spawn } from "child_process";
36300
- import { fileURLToPath as fileURLToPath2 } from "url";
34986
+ import { fileURLToPath } from "url";
36301
34987
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
36302
34988
 
36303
34989
  // ../../packages/plugin-runtime/src/attached/install-record.ts
36304
34990
  import { readFile as readFile2, stat } from "fs/promises";
36305
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
34991
+ import { basename as basename2, dirname as dirname4, join as join19, resolve as resolve2 } from "path";
36306
34992
 
36307
34993
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
36308
- import { readFileSync as readFileSync18 } from "fs";
34994
+ import { readFileSync as readFileSync12 } from "fs";
36309
34995
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
36310
34996
 
36311
34997
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36312
- import { randomUUID as randomUUID17 } from "crypto";
34998
+ import { randomUUID as randomUUID14 } from "crypto";
36313
34999
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
36314
- import { join as join30 } from "path";
35000
+ import { join as join20 } from "path";
36315
35001
 
36316
35002
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36317
35003
  import { rename as rename2 } from "fs/promises";
@@ -36320,8 +35006,8 @@ var TIMED_RETRIES = 4;
36320
35006
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
36321
35007
 
36322
35008
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
36323
- import { readFileSync as readFileSync19 } from "fs";
36324
- import { join as join31 } from "path";
35009
+ import { readFileSync as readFileSync13 } from "fs";
35010
+ import { join as join21 } from "path";
36325
35011
  var OUTCOME_KEYS = {
36326
35012
  ok: true,
36327
35013
  unauthorized: true,
@@ -36338,17 +35024,17 @@ var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
36338
35024
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
36339
35025
 
36340
35026
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
36341
- import { statSync as statSync9 } from "fs";
36342
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
35027
+ import { statSync as statSync6 } from "fs";
35028
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36343
35029
 
36344
35030
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
36345
- import { randomUUID as randomUUID18 } from "crypto";
35031
+ import { randomUUID as randomUUID15 } from "crypto";
36346
35032
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
36347
- import { join as join32 } from "path";
35033
+ import { join as join22 } from "path";
36348
35034
 
36349
35035
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
36350
- import { readFileSync as readFileSync20 } from "fs";
36351
- import { join as join33 } from "path";
35036
+ import { readFileSync as readFileSync14 } from "fs";
35037
+ import { join as join23 } from "path";
36352
35038
 
36353
35039
  // ../../packages/plugin-runtime/src/attached/status.ts
36354
35040
  var REFUSAL_LINES = {
@@ -36366,12 +35052,32 @@ var OUTCOME_LINES = {
36366
35052
 
36367
35053
  // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
36368
35054
  import { spawn as spawn2 } from "child_process";
36369
- import { fileURLToPath as fileURLToPath3 } from "url";
35055
+ import { fileURLToPath as fileURLToPath2 } from "url";
36370
35056
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
36371
35057
 
36372
35058
  // ../../packages/plugin-runtime/src/content-retention-pass.ts
36373
35059
  var MAX_ROWS_PER_SWEEP = 50 * 1e3;
36374
35060
  var DAY_MS5 = 864e5;
35061
+ function syncLaneRetentionFor(settings, base) {
35062
+ try {
35063
+ const connection = settings.controlPlane;
35064
+ if (!isAttached(settings) || connection === void 0) {
35065
+ return syncLaneRetentionOf(settings, void 0);
35066
+ }
35067
+ const read = readControlPlaneCredentialFile(settingsDir(base), connection);
35068
+ if (!read.usable) return syncLaneRetentionOf(settings, void 0);
35069
+ return syncLaneRetentionOf(
35070
+ settings,
35071
+ resolveScope({
35072
+ mode: attachmentModeOf(read.credential),
35073
+ scope: settings.attachmentScope,
35074
+ endpoint: connection.endpoint
35075
+ })
35076
+ );
35077
+ } catch {
35078
+ return { kind: "hold-all" };
35079
+ }
35080
+ }
36375
35081
  function runContentRetentionPass(seams = {}) {
36376
35082
  const base = seams.base ?? defaultDataDir();
36377
35083
  const now = (seams.now ?? Date.now)();
@@ -36379,10 +35085,11 @@ function runContentRetentionPass(seams = {}) {
36379
35085
  const settings = readWorkspaceSettings(base);
36380
35086
  const retention = settings.bodyRetention;
36381
35087
  if (!retention.enabled) return { ran: false, reason: "disabled" };
35088
+ const syncLane = syncLaneRetentionFor(settings, base);
36382
35089
  const db = openLocalDatabase(dataDir(base));
36383
35090
  const out = db.bodyRetention.expire({
36384
35091
  cutoff: now - retention.retainDays * DAY_MS5,
36385
- sweepSyncLane: canSweepSyncLane(settings),
35092
+ sweepSyncLane: syncLane,
36386
35093
  now,
36387
35094
  maxRows: MAX_ROWS_PER_SWEEP
36388
35095
  });
@@ -36394,14 +35101,14 @@ function runContentRetentionPass(seams = {}) {
36394
35101
 
36395
35102
  // ../../packages/plugin-runtime/src/content-retention-trigger.ts
36396
35103
  import { spawn as spawn3 } from "child_process";
36397
- import { fileURLToPath as fileURLToPath4 } from "url";
35104
+ import { fileURLToPath as fileURLToPath3 } from "url";
36398
35105
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
36399
35106
 
36400
35107
  // ../../packages/plugin-runtime/src/attached/factory.ts
36401
- import { hostname as hostname6 } from "os";
35108
+ import { hostname as hostname5 } from "os";
36402
35109
 
36403
35110
  // ../../packages/plugin-runtime/src/handle-session-start.ts
36404
- import { randomUUID as randomUUID19 } from "crypto";
35111
+ import { randomUUID as randomUUID16 } from "crypto";
36405
35112
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
36406
35113
 
36407
35114
  // src/content-retention.ts