@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,887 +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
- var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
880
- var ATTACHED_HISTORY_SYNC_STATE_FILENAME = "attached-history-sync.json";
881
-
882
- // ../../packages/persistence/src/control-plane-credential.ts
883
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
884
- import { join as join2 } from "path";
885
6
 
886
7
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
887
8
  var DEFERRED_MIGRATION_TAGS = [
@@ -3866,9 +2987,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3866
2987
  function stripTabAndNewline(value) {
3867
2988
  return value.replace(asciiTabOrNewline, "");
3868
2989
  }
3869
- function urlHostnameOk(url2, hostname7) {
3870
- hostname7.lastIndex = 0;
3871
- return hostname7.test(url2.hostname);
2990
+ function urlHostnameOk(url2, hostname6) {
2991
+ hostname6.lastIndex = 0;
2992
+ return hostname6.test(url2.hostname);
3872
2993
  }
3873
2994
  function urlProtocolOk(url2, protocol) {
3874
2995
  protocol.lastIndex = 0;
@@ -20788,13 +19909,16 @@ function serviceTierMultiplier(tier) {
20788
19909
  if (tier === void 0) return 1;
20789
19910
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20790
19911
  }
19912
+ function promptTokensOf(usage) {
19913
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19914
+ }
20791
19915
  function costOf(price, usage) {
20792
19916
  const metered = [
20793
19917
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20794
19918
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20795
19919
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20796
19920
  ];
20797
- 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;
20798
19922
  if (band !== null && (band.input === null || band.output === null)) return null;
20799
19923
  const inputRate = band?.input ?? price.input;
20800
19924
  const outputRate = band?.output ?? price.output;
@@ -20867,8 +19991,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20867
19991
  ["ollama", "local"],
20868
19992
  ["local", "local"]
20869
19993
  ]);
20870
- function hostingFor(platform2) {
20871
- return PLATFORM_HOSTING.get(platform2) ?? "api";
19994
+ function hostingFor(platform) {
19995
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20872
19996
  }
20873
19997
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20874
19998
  ["anthropic", "anthropic"],
@@ -20882,8 +20006,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20882
20006
  function firstPartyPlatformFor(vendor2) {
20883
20007
  return FIRST_PARTY.get(vendor2) ?? null;
20884
20008
  }
20885
- function isFirstParty(vendor2, platform2) {
20886
- return FIRST_PARTY.get(vendor2) === platform2;
20009
+ function isFirstParty(vendor2, platform) {
20010
+ return FIRST_PARTY.get(vendor2) === platform;
20887
20011
  }
20888
20012
  var PLATFORM_NAMESPACES = Object.freeze([
20889
20013
  "anthropic",
@@ -20944,14 +20068,14 @@ var ModelVendorBuilder = class {
20944
20068
  );
20945
20069
  }
20946
20070
  for (const ref of spec.on ?? []) {
20947
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20948
- const firstParty = isFirstParty(this.vendor, platform2);
20949
- const hosting = hostingFor(platform2);
20071
+ const { platform, price, retention, region } = normalizeRef(ref);
20072
+ const firstParty = isFirstParty(this.vendor, platform);
20073
+ const hosting = hostingFor(platform);
20950
20074
  const isSelfHosted = hosting === "local";
20951
20075
  platforms.set(
20952
- platform2,
20076
+ platform,
20953
20077
  Object.freeze({
20954
- platform: platform2,
20078
+ platform,
20955
20079
  hosting,
20956
20080
  firstParty,
20957
20081
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21004,35 +20128,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21004
20128
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21005
20129
  var BEDROCK_REVISION_RE = /:\d+$/u;
21006
20130
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21007
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20131
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21008
20132
  function stripPlatformDecorations(model) {
21009
20133
  let id = model.trim();
21010
- let platform2 = null;
20134
+ let platform = null;
21011
20135
  if (GEO_PREFIX_RE.test(id)) {
21012
20136
  id = id.replace(GEO_PREFIX_RE, "");
21013
- platform2 = "bedrock";
20137
+ platform = "bedrock";
21014
20138
  }
21015
20139
  if (NAMESPACE_DOT_RE.test(id)) {
21016
20140
  id = id.replace(NAMESPACE_DOT_RE, "");
21017
- platform2 ??= "bedrock";
20141
+ platform ??= "bedrock";
21018
20142
  }
21019
20143
  if (BEDROCK_VERSION_RE.test(id)) {
21020
20144
  id = id.replace(BEDROCK_VERSION_RE, "");
21021
- platform2 ??= "bedrock";
20145
+ platform ??= "bedrock";
21022
20146
  } else if (BEDROCK_REVISION_RE.test(id)) {
21023
20147
  id = id.replace(BEDROCK_REVISION_RE, "");
21024
- platform2 ??= "bedrock";
20148
+ platform ??= "bedrock";
21025
20149
  }
21026
20150
  if (VERTEX_VERSION_RE.test(id)) {
21027
20151
  id = id.replace(VERTEX_VERSION_RE, "");
21028
- platform2 ??= "vertex";
20152
+ platform ??= "vertex";
21029
20153
  }
21030
20154
  if (NAMESPACE_SLASH_RE.test(id)) {
21031
20155
  id = id.replace(NAMESPACE_SLASH_RE, "");
21032
20156
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21033
20157
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21034
20158
  }
21035
- return { id, platform: platform2 };
20159
+ return { id, platform };
21036
20160
  }
21037
20161
  function buildModelIndex(entries) {
21038
20162
  const byId = /* @__PURE__ */ new Map();
@@ -21049,19 +20173,19 @@ function resolveModel(raw, index) {
21049
20173
  if (exact !== void 0) {
21050
20174
  return { entry: exact, canonicalId: raw, platform: null, raw };
21051
20175
  }
21052
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20176
+ const { id, platform } = stripPlatformDecorations(raw);
21053
20177
  const stripped = index.byId.get(id);
21054
20178
  if (stripped !== void 0) {
21055
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20179
+ return { entry: stripped, canonicalId: id, platform, raw };
21056
20180
  }
21057
20181
  if (DATED_SUFFIX_RE.test(id)) {
21058
20182
  const undated = id.replace(DATED_SUFFIX_RE, "");
21059
20183
  const byDate = index.byId.get(undated);
21060
20184
  if (byDate !== void 0) {
21061
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20185
+ return { entry: byDate, canonicalId: undated, platform, raw };
21062
20186
  }
21063
20187
  }
21064
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20188
+ return { entry: null, canonicalId: raw, platform, raw };
21065
20189
  }
21066
20190
 
21067
20191
  // ../../packages/schema/src/model/catalog.ts
@@ -21154,7 +20278,7 @@ anthropic.model("claude-haiku-4-5", {
21154
20278
  name: "Claude Haiku 4.5",
21155
20279
  ctx: 2e5,
21156
20280
  maxOut: 64e3,
21157
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20281
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21158
20282
  capability: null,
21159
20283
  price: anthropicPrice(1, 5, 0.1),
21160
20284
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21285,6 +20409,11 @@ openai.model("gpt-4o", {
21285
20409
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21286
20410
  on: [...OPENAI_RESELLERS]
21287
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
+ });
21288
20417
  openai.model("gpt-4o-mini", {
21289
20418
  name: "GPT-4o mini",
21290
20419
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21304,6 +20433,24 @@ openai.model("o3", {
21304
20433
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21305
20434
  on: [...OPENAI_RESELLERS]
21306
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
+ });
21307
20454
  openai.model("gpt-oss-120b", {
21308
20455
  name: "GPT-OSS 120B",
21309
20456
  openWeights: true,
@@ -21590,10 +20737,21 @@ var MODEL_ENTRIES = Object.freeze([
21590
20737
  ...alibaba.models(),
21591
20738
  ...amazon.models()
21592
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
+ );
21593
20751
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21594
20752
 
21595
20753
  // ../../packages/schema/src/model/governance.ts
21596
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20754
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21597
20755
  var DataRetention = external_exports.enum([
21598
20756
  "zero_retention",
21599
20757
  "no_storage",
@@ -21689,16 +20847,16 @@ function platformForProvider(provider) {
21689
20847
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21690
20848
  }
21691
20849
  function isLocalProvider(provider) {
21692
- const platform2 = platformForProvider(provider);
21693
- return platform2 !== null && hostingFor(platform2) === "local";
20850
+ const platform = platformForProvider(provider);
20851
+ return platform !== null && hostingFor(platform) === "local";
21694
20852
  }
21695
20853
  function priceFor(provider, model) {
21696
20854
  if (isLocalProvider(provider)) return ZERO_PRICE;
21697
20855
  const resolved = resolveModel(model, MODEL_INDEX);
21698
20856
  if (resolved.entry === null) return null;
21699
- const platform2 = resolved.platform ?? platformForProvider(provider);
21700
- if (platform2 === null) return null;
21701
- 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;
21702
20860
  }
21703
20861
  var defaultCostModel = {
21704
20862
  normalizeModelId(provider, model) {
@@ -21724,7 +20882,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21724
20882
 
21725
20883
  // ../../packages/schema/src/token/token-report.ts
21726
20884
  var num = (value) => value ?? 0;
21727
- function costUsageOf(a) {
20885
+ function costUsageOf(a, promptTokens) {
21728
20886
  const usage = {
21729
20887
  inputTokens: num(a.input_tokens),
21730
20888
  outputTokens: num(a.output_tokens),
@@ -21734,11 +20892,12 @@ function costUsageOf(a) {
21734
20892
  webSearchRequests: num(a.web_search_requests)
21735
20893
  };
21736
20894
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20895
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21737
20896
  return usage;
21738
20897
  }
21739
20898
  function buildTokenReports(leaves, costModel) {
21740
20899
  const bySession = /* @__PURE__ */ new Map();
21741
- for (const { sessionId, attributes } of leaves) {
20900
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21742
20901
  const provider = attributes.provider ?? "unknown";
21743
20902
  const model = attributes.model ?? "unknown";
21744
20903
  const key = `${provider} ${model}`;
@@ -21757,7 +20916,8 @@ function buildTokenReports(leaves, costModel) {
21757
20916
  cacheCreation: 0,
21758
20917
  cacheRead: 0,
21759
20918
  costUsd: 0,
21760
- priced: false
20919
+ priced: false,
20920
+ partial: false
21761
20921
  };
21762
20922
  rollups.set(key, acc);
21763
20923
  }
@@ -21765,8 +20925,14 @@ function buildTokenReports(leaves, costModel) {
21765
20925
  acc.output += num(attributes.output_tokens);
21766
20926
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21767
20927
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21768
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21769
- 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 {
21770
20936
  acc.costUsd += leafCost;
21771
20937
  acc.priced = true;
21772
20938
  }
@@ -21782,9 +20948,8 @@ function buildTokenReports(leaves, costModel) {
21782
20948
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21783
20949
  totalTokens += rollupTotal;
21784
20950
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21785
- if (estimatedCostUsd === null) {
21786
- anyUnpriced = true;
21787
- } else {
20951
+ if (acc.partial) anyUnpriced = true;
20952
+ if (estimatedCostUsd !== null) {
21788
20953
  anyPriced = true;
21789
20954
  costUsd += estimatedCostUsd;
21790
20955
  }
@@ -21807,7 +20972,7 @@ function buildTokenReports(leaves, costModel) {
21807
20972
  totalTokens,
21808
20973
  // Σ of the PRICED rollups; null when none had a known price.
21809
20974
  estimatedCostUsd: anyPriced ? costUsd : null,
21810
- // Any unknown (provider, model) means the total understates real spend.
20975
+ // Any call priced to null means the total understates real spend.
21811
20976
  costIsPartial: anyUnpriced
21812
20977
  });
21813
20978
  }
@@ -22509,6 +21674,11 @@ var CaptureAttributes = external_exports.object({
22509
21674
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22510
21675
  // repeated rather than referenced because a store reader opens this file.
22511
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(),
22512
21682
  // The scope key this capture was stamped with: the canonical repository
22513
21683
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22514
21684
  // against its working directory), else of its own working directory, or a
@@ -22686,8 +21856,9 @@ var SessionTokenReport = external_exports.object({
22686
21856
  totalTokens: external_exports.number().int().nonnegative(),
22687
21857
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22688
21858
  estimatedCostUsd: external_exports.number().nullable(),
22689
- // True whenever any rollup has a null cost (unknown provider/model), so the
22690
- // 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
22691
21862
  // precise figure rather than silently dropping the unpriced calls.
22692
21863
  costIsPartial: external_exports.boolean()
22693
21864
  });
@@ -23434,6 +22605,9 @@ var AttachedCredentialAny = external_exports.discriminatedUnion("specVersion", [
23434
22605
  AttachedCredentialV1,
23435
22606
  AttachedCredentialV2
23436
22607
  ]);
22608
+ function attachmentModeOf(credential) {
22609
+ return credential.specVersion === ATTACHED_CREDENTIAL_SPEC_VERSION ? "machine" : "scoped";
22610
+ }
23437
22611
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
23438
22612
  function unsafeEndpointReason(endpoint) {
23439
22613
  let parsed2;
@@ -23561,7 +22735,15 @@ var StorePostureSnapshot = external_exports.object({
23561
22735
  policyCounts: StorePosturePolicyCounts,
23562
22736
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23563
22737
  // getting its 200 without a payload change.
23564
- plugin: StorePosturePlugin.optional()
22738
+ plugin: StorePosturePlugin.optional(),
22739
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22740
+ // machine attachment omits it, so its body is byte for byte the one it
22741
+ // sent before this member existed. Absent therefore means machine-wide OR
22742
+ // a reporter older than this member, never "scoped". Both values parse, so
22743
+ // a sender that one day spells `machine` breaks no receiver; any other
22744
+ // value fails the whole snapshot, which is why the reporter sends a
22745
+ // constant and never the raw mode.
22746
+ attachmentMode: AttachmentMode.optional()
23565
22747
  }).meta({ id: "StorePostureSnapshot" });
23566
22748
  var CAPTURE_VERSION_PREFIX = "capture/";
23567
22749
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23838,7 +23020,19 @@ var EventMetadata = external_exports.object({
23838
23020
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23839
23021
  // Closing either means moving the reason onto the finding row, which
23840
23022
  // already carries its own action.
23841
- redactDegradedTo: ActionTaken.optional()
23023
+ redactDegradedTo: ActionTaken.optional(),
23024
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23025
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23026
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23027
+ // field instead of letting it through unscanned.
23028
+ //
23029
+ // - 'timeout': the bounded scan ran out of time.
23030
+ // - 'unavailable': no worker could run it.
23031
+ //
23032
+ // A refused row stores '' as its content and has no findings, which is
23033
+ // exactly what a clean, empty capture looks like — this marker is the only
23034
+ // thing that tells the two apart. Absent on every capture that was scanned.
23035
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23842
23036
  }).meta({ id: "EventMetadata" });
23843
23037
  var Event = external_exports.object({
23844
23038
  id: external_exports.guid(),
@@ -24008,7 +23202,7 @@ var Rule = external_exports.strictObject({
24008
23202
  postValidators: external_exports.array(PostValidatorRef).optional(),
24009
23203
  requiresNearby: RequiresNearby.optional(),
24010
23204
  examples: external_exports.array(external_exports.string()).optional(),
24011
- // Whether the matched text is itself sensitive. Absent means 'value'.
23205
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24012
23206
  evidence: RuleEvidence.optional()
24013
23207
  }).meta({ id: "Rule" });
24014
23208
  var Author = external_exports.object({
@@ -24100,7 +23294,13 @@ var DetectionRule = external_exports.object({
24100
23294
  // Representative matching strings the rule author shipped with the rule. The
24101
23295
  // cheapest honest answer to "show me what this rule catches" — every bundled
24102
23296
  // rule has them, and they are already in the stored snapshot.
24103
- examples: external_exports.array(external_exports.string()).optional()
23297
+ examples: external_exports.array(external_exports.string()).optional(),
23298
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23299
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23300
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23301
+ // in a value category (secret/pii/financial/phi) is always 'value',
23302
+ // whatever it declares.
23303
+ evidence: RuleEvidence.optional()
24104
23304
  }).meta({ id: "DetectionRule" });
24105
23305
  var DetectionUpdate = external_exports.object({
24106
23306
  available: external_exports.boolean(),
@@ -24168,8 +23368,10 @@ var ImportDetectionRequest = external_exports.object({
24168
23368
  }).meta({ id: "ImportDetectionRequest" });
24169
23369
 
24170
23370
  // ../../packages/schema/src/zod/detection-build.ts
24171
- function optional2(key, parsed2, raw) {
24172
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23371
+ function optional2(key, raw, parse4) {
23372
+ if (raw === void 0) return {};
23373
+ const parsed2 = parse4(raw);
23374
+ if (!parsed2.success || parsed2.data === void 0) return {};
24173
23375
  return { [key]: parsed2.data };
24174
23376
  }
24175
23377
  function isStringArray(value) {
@@ -24204,10 +23406,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24204
23406
  category: r.category,
24205
23407
  severity: r.severity,
24206
23408
  matcher: parsed2.data,
24207
- // The rest of what decides whether this rule fires. Carried so a consumer
24208
- // re-running the rule (a preview, a tester) evaluates what the engine
24209
- // evaluates rather than a matcher stripped of its guards — half the
24210
- // bundled catalog carries at least one of these.
23409
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23410
+ // decides whether this rule fires. Carried so a consumer re-running the
23411
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23412
+ // than a matcher stripped of its guards — half the bundled catalog
23413
+ // carries at least one of these. `examples` and `evidence` describe the
23414
+ // rule and never gate a match.
24211
23415
  //
24212
23416
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24213
23417
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24217,18 +23421,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24217
23421
  // test should stay exactly what it was, namely a renderable matcher. A
24218
23422
  // field that fails validation is omitted, which reads as "not set" and is
24219
23423
  // the same thing the consumer saw before this change.
24220
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23424
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24221
23425
  ...optional2(
24222
23426
  "postValidators",
24223
- PostValidatorRef.array().safeParse(r.postValidators),
24224
- r.postValidators
23427
+ r.postValidators,
23428
+ (v) => PostValidatorRef.array().safeParse(v)
24225
23429
  ),
24226
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23430
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24227
23431
  ...optional2(
24228
23432
  "examples",
24229
- { success: isStringArray(r.examples), data: r.examples },
24230
- r.examples
24231
- )
23433
+ r.examples,
23434
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23435
+ ),
23436
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24232
23437
  }
24233
23438
  ];
24234
23439
  });
@@ -24921,11 +24126,14 @@ var PolicyBundle = external_exports.object({
24921
24126
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24922
24127
  // Model ids (the raw `model` string a harness reports, e.g.
24923
24128
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24924
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24925
- // one (UserPromptSubmit). Optional so an older backend — and an older
24926
- // on-disk cache — still parses; consumers read `?? []`, which is the
24927
- // unenforced behaviour that predates this field and the safe direction to
24928
- // default.
24129
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24130
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24131
+ // wherever the organization governs the event: everywhere on a
24132
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24133
+ // one (the plugin runtime's `governanceApplies`).
24134
+ // Optional so an older backend — and an older on-disk cache — still
24135
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24136
+ // predates this field and the safe direction to default.
24929
24137
  //
24930
24138
  // Ids, not display names: the governance decision is keyed on the exact
24931
24139
  // string the harness reports (`model_status_override.versionId` in the
@@ -25302,9 +24510,36 @@ var AttachmentScopeEntry = external_exports.object({
25302
24510
  });
25303
24511
  var AttachmentScope = external_exports.object({
25304
24512
  endpoint: external_exports.string().min(1),
24513
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24514
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25305
24515
  entries: external_exports.array(AttachmentScopeEntry)
25306
24516
  });
25307
24517
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
24518
+ function parseAttachmentScope(raw) {
24519
+ try {
24520
+ const envelope = AttachmentScopeEnvelope.safeParse(raw);
24521
+ if (!envelope.success) return void 0;
24522
+ const entries = [];
24523
+ for (const candidate of envelope.data.entries) {
24524
+ const entry = AttachmentScopeEntry.safeParse(candidate);
24525
+ if (entry.success) entries.push(entry.data);
24526
+ }
24527
+ const { endpoint, tenantName, userEmail } = envelope.data;
24528
+ return {
24529
+ endpoint,
24530
+ ...tenantName === void 0 ? {} : { tenantName },
24531
+ ...userEmail === void 0 ? {} : { userEmail },
24532
+ entries
24533
+ };
24534
+ } catch {
24535
+ return void 0;
24536
+ }
24537
+ }
24538
+ function scopeForEndpoint(raw, endpoint) {
24539
+ if (endpoint === void 0) return void 0;
24540
+ const scope = parseAttachmentScope(raw);
24541
+ return scope?.endpoint === endpoint ? scope : void 0;
24542
+ }
25308
24543
  var WebChatCaptureConsent = external_exports.object({
25309
24544
  acknowledgedAt: external_exports.iso.datetime(),
25310
24545
  version: external_exports.number().int().positive()
@@ -25415,6 +24650,40 @@ function defaultWorkspaceSettings() {
25415
24650
  function isAttached(settings) {
25416
24651
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
25417
24652
  }
24653
+ function resolveScope(input2, extraEntries) {
24654
+ try {
24655
+ if (input2.mode === "machine") return { mode: "machine", keys: /* @__PURE__ */ new Set() };
24656
+ const keys = /* @__PURE__ */ new Set();
24657
+ const stored = scopeForEndpoint(input2.scope, input2.endpoint);
24658
+ for (const entry of stored?.entries ?? []) {
24659
+ keys.add(entry.identity);
24660
+ }
24661
+ for (const candidate of extraEntries ?? []) {
24662
+ const entry = AttachmentScopeEntry.safeParse(candidate);
24663
+ if (entry.success) keys.add(entry.data.identity);
24664
+ }
24665
+ return { mode: "scoped", keys };
24666
+ } catch {
24667
+ return { mode: "scoped", keys: /* @__PURE__ */ new Set() };
24668
+ }
24669
+ }
24670
+ function scopeVerdict(resolved, key) {
24671
+ try {
24672
+ if (resolved.mode === "machine") return "forward";
24673
+ if (typeof key !== "string" || key === "") return "local";
24674
+ return resolved.keys.has(key) ? "forward" : "local";
24675
+ } catch {
24676
+ return "local";
24677
+ }
24678
+ }
24679
+ function scopeFilterOf(resolved) {
24680
+ try {
24681
+ if (resolved.mode === "machine") return void 0;
24682
+ return [...resolved.keys].sort();
24683
+ } catch {
24684
+ return [];
24685
+ }
24686
+ }
25418
24687
  function toInventoryRow(input2, id, now) {
25419
24688
  return {
25420
24689
  id,
@@ -25506,6 +24775,7 @@ function toCaptureAttributes(event) {
25506
24775
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25507
24776
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25508
24777
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24778
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25509
24779
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25510
24780
  // has ever populated either), but every legacy metadata key still rides
25511
24781
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25634,6 +24904,27 @@ var ManagedSettings = external_exports.object({
25634
24904
  };
25635
24905
  }).meta({ id: "ManagedSettings" });
25636
24906
 
24907
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24908
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24909
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24910
+ var ModPolicySnapshot = external_exports.object({
24911
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24912
+ generatedAt: external_exports.iso.datetime(),
24913
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24914
+ // user's enabled installed packs (user-modified and custom packs included).
24915
+ // Absent means the store holds no authoritative snapshot, and the reader
24916
+ // scans with the packs it ships — the hook's own fallback.
24917
+ rules: external_exports.array(Rule).optional(),
24918
+ // Rule-targeted actions (first enabled policy per rule wins).
24919
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
24920
+ // The resolved action per detection category.
24921
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
24922
+ // Rules with an active exception grant. Honouring a grant means matching a
24923
+ // keyed fingerprint of the value and consuming a use, which only the hook can
24924
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
24925
+ exceptionRuleIds: external_exports.array(external_exports.string())
24926
+ }).meta({ id: "ModPolicySnapshot" });
24927
+
25637
24928
  // ../../packages/schema/src/zod/project-files.ts
25638
24929
  var ProjectFileInput = external_exports.object({
25639
24930
  path: external_exports.string().min(1),
@@ -25954,7 +25245,16 @@ var AttachInput = external_exports.object({
25954
25245
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
25955
25246
  // renders a longer one usefully.
25956
25247
  label: printable(200).optional(),
25957
- accessKey: external_exports.string()
25248
+ accessKey: external_exports.string(),
25249
+ // How much of this machine the attachment is for: everything, or only the
25250
+ // repositories its user enrolls. Optional, so an input without it still
25251
+ // parses; what an absent mode means is for whatever reads it to decide, not
25252
+ // this shape. This member validates the VALUE rather than leaving that to the
25253
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25254
+ // rejection names the field, so a value that is not a mode is refused as a bad
25255
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25256
+ // it as the mode to attach in.
25257
+ mode: AttachmentMode.optional()
25958
25258
  });
25959
25259
 
25960
25260
  // ../../packages/schema/src/zod/triage.ts
@@ -26240,6 +25540,17 @@ function fromCaptureStatusAttributes(bag) {
26240
25540
  return parsedStatus.success ? parsedStatus.data : null;
26241
25541
  }
26242
25542
 
25543
+ // ../../packages/persistence/src/attached-derived.ts
25544
+ import { rmSync } from "fs";
25545
+ import { join } from "path";
25546
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25547
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25548
+ var ATTACHED_HISTORY_SYNC_STATE_FILENAME = "attached-history-sync.json";
25549
+
25550
+ // ../../packages/persistence/src/control-plane-credential.ts
25551
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25552
+ import { join as join2 } from "path";
25553
+
26243
25554
  // ../../packages/persistence/src/paths.ts
26244
25555
  import {
26245
25556
  chmodSync,
@@ -26329,6 +25640,14 @@ function repairOrRefuseMode(file2) {
26329
25640
  }
26330
25641
  return "ok";
26331
25642
  }
25643
+ function asReadableCredential(value) {
25644
+ const result = AttachedCredentialAny.safeParse(value);
25645
+ if (!result.success) return null;
25646
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25647
+ return null;
25648
+ }
25649
+ return result.data;
25650
+ }
26332
25651
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26333
25652
  const file2 = controlPlaneCredentialPath(settingsDir2);
26334
25653
  let raw;
@@ -26347,25 +25666,25 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26347
25666
  } catch {
26348
25667
  return { usable: false, reason: "malformed" };
26349
25668
  }
26350
- const result = AttachedCredential.safeParse(parsed2);
26351
- if (!result.success) return { usable: false, reason: "malformed" };
26352
- if (!isSafeEndpoint(result.data.endpoint)) {
25669
+ const credential = asReadableCredential(parsed2);
25670
+ if (credential === null) return { usable: false, reason: "malformed" };
25671
+ if (!isSafeEndpoint(credential.endpoint)) {
26353
25672
  return { usable: false, reason: "unsafe-endpoint" };
26354
25673
  }
26355
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25674
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26356
25675
  return {
26357
25676
  usable: false,
26358
25677
  reason: "endpoint-mismatch",
26359
- credentialEndpoint: result.data.endpoint,
25678
+ credentialEndpoint: credential.endpoint,
26360
25679
  settingsEndpoint: connection.endpoint
26361
25680
  };
26362
25681
  }
26363
- return { usable: true, credential: result.data };
25682
+ return { usable: true, credential };
26364
25683
  }
26365
25684
 
26366
25685
  // ../../packages/persistence/src/database.ts
26367
25686
  import { randomUUID as randomUUID11 } from "crypto";
26368
- import { dirname as dirname2, join as join7, sep } from "path";
25687
+ import { dirname as dirname2, join as join8, sep } from "path";
26369
25688
  import { DatabaseSync } from "node:sqlite";
26370
25689
 
26371
25690
  // ../../packages/persistence/src/ids.ts
@@ -26408,6 +25727,7 @@ function uuidFromDigest(digest) {
26408
25727
  function captureWireId(sessionId, contentHash, filePath = null) {
26409
25728
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26410
25729
  }
25730
+ var DOT = ".".charCodeAt(0);
26411
25731
 
26412
25732
  // ../../packages/persistence/src/internal/snapshot.ts
26413
25733
  import { randomUUID } from "crypto";
@@ -26735,6 +26055,25 @@ function scopeKeysParam(scopeKeys) {
26735
26055
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26736
26056
  FROM audit_events AS session_root
26737
26057
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26058
+ var COUNTED_IN_SCOPE = `
26059
+ AND ${inScope("scope_key")}
26060
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26061
+ var DRAIN_TOTALS = `SELECT
26062
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26063
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26064
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26065
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26066
+ THEN 1 ELSE 0 END) AS skipped,
26067
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26068
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26069
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26070
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26071
+ FROM audit_events
26072
+ WHERE event_type IN (${TYPE_LIST})`;
26073
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26074
+ FROM audit_events
26075
+ WHERE synced_at = ${String(SKIPPED)}
26076
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26738
26077
  var HISTORY_SYNC_LEASE_STALE_MS = 6e4;
26739
26078
  var ROW_COLUMNS = `id,
26740
26079
  parent_id AS parentId,
@@ -26811,7 +26150,7 @@ var SqliteHistorySyncRepository = class {
26811
26150
  );
26812
26151
  this.scopedCaptureRowsStmt = db.prepare(
26813
26152
  `SELECT ${ROW_COLUMNS}
26814
- FROM audit_events
26153
+ FROM audit_events INDEXED BY idx_audit_scope_owed
26815
26154
  WHERE synced_at IS NULL
26816
26155
  AND sync_claimed_at IS NULL
26817
26156
  AND outbox_owed = 1
@@ -26864,40 +26203,28 @@ var SqliteHistorySyncRepository = class {
26864
26203
  );
26865
26204
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26866
26205
  FROM audit_events${COUNTED_SCOPE}`);
26206
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26207
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
26867
26208
  this.partitionByKindStmt = db.prepare(
26868
26209
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
26869
26210
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
26870
26211
  GROUP BY event_type`
26871
26212
  );
26872
- this.countsStmt = db.prepare(
26873
- `SELECT
26874
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26875
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26876
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26877
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26878
- THEN 1 ELSE 0 END) AS skipped,
26879
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26880
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26881
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26882
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26883
- FROM audit_events
26884
- WHERE event_type IN (${TYPE_LIST})`
26213
+ this.scopedPartitionByKindStmt = db.prepare(
26214
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26215
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26216
+ GROUP BY event_type`
26885
26217
  );
26886
- this.captureSkipCountStmt = db.prepare(
26887
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
26888
- // way the structural totals are. The split exists because a refusal is
26889
- // terminal only against the deployment that gave it, and the structural
26890
- // re-arm frees it on a change of deployment. The capture lane has no such
26891
- // escape: re-arming a capture would offer one deployment's undelivered
26892
- // prompts, with their text, to a deployment that never saw them, which is
26893
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
26894
- // reasons mean the same thing — this row will not be sent — and splitting
26895
- // them would put refused captures in a bucket nothing reads and nothing
26896
- // frees.
26897
- `SELECT COUNT(*) AS skipped
26898
- FROM audit_events
26899
- WHERE synced_at = ${String(SKIPPED)}
26900
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26218
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26219
+ this.scopedCountsStmt = db.prepare(
26220
+ `${DRAIN_TOTALS}
26221
+ AND ${inScope("scope_key")}
26222
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26223
+ );
26224
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26225
+ this.scopedCaptureSkipCountStmt = db.prepare(
26226
+ `${CAPTURE_SKIPS}
26227
+ AND ${inScope("scope_key")}`
26901
26228
  );
26902
26229
  this.fingerprintStmt = db.prepare(
26903
26230
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27011,6 +26338,10 @@ var SqliteHistorySyncRepository = class {
27011
26338
  scopedCaptureRowsStmt;
27012
26339
  scopedCaptureBacklogOwedStmt;
27013
26340
  markScopeCapturesOwedStmt;
26341
+ scopedPartitionStmt;
26342
+ scopedPartitionByKindStmt;
26343
+ scopedCountsStmt;
26344
+ scopedCaptureSkipCountStmt;
27014
26345
  /**
27015
26346
  * The masked detections recorded against one tool call.
27016
26347
  *
@@ -27232,7 +26563,29 @@ var SqliteHistorySyncRepository = class {
27232
26563
  * in" — and a machine that has never attached has no boundary to pass, so
27233
26564
  * requiring one would force a caller to invent one and report the whole store
27234
26565
  * as queued.
26566
+ *
26567
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26568
+ * the rows that pass the drain's reachability rule for that scope
26569
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26570
+ * drain never offers), so a personal repository's rows are in none of them.
26571
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26572
+ * nothing.
27235
26573
  */
26574
+ partition(scopeKeys) {
26575
+ const row = getRow(
26576
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26577
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26578
+ );
26579
+ return {
26580
+ queued: row?.queued ?? 0,
26581
+ inProgress: row?.inProgress ?? 0,
26582
+ synced: row?.synced ?? 0,
26583
+ failed: row?.failed ?? 0,
26584
+ refused: row?.refused ?? 0,
26585
+ detached: row?.detached ?? 0,
26586
+ total: row?.total ?? 0
26587
+ };
26588
+ }
27236
26589
  /**
27237
26590
  * The same partition, one row per kind that a lane carries.
27238
26591
  *
@@ -27242,11 +26595,14 @@ var SqliteHistorySyncRepository = class {
27242
26595
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27243
26596
  * rows", never as "zero sent"; the two look identical in a bar and mean
27244
26597
  * different things.
26598
+ *
26599
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26600
+ * still sum to the scoped aggregate. An empty list returns no rows.
27245
26601
  */
27246
- partitionByKind() {
26602
+ partitionByKind(scopeKeys) {
27247
26603
  return allRows(
27248
- this.partitionByKindStmt,
27249
- {}
26604
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26605
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27250
26606
  ).map((row) => ({
27251
26607
  kind: row.kind,
27252
26608
  queued: row.queued ?? 0,
@@ -27258,22 +26614,25 @@ var SqliteHistorySyncRepository = class {
27258
26614
  total: row.total ?? 0
27259
26615
  }));
27260
26616
  }
27261
- partition() {
27262
- const row = getRow(this.partitionStmt, {});
27263
- return {
27264
- queued: row?.queued ?? 0,
27265
- inProgress: row?.inProgress ?? 0,
27266
- synced: row?.synced ?? 0,
27267
- failed: row?.failed ?? 0,
27268
- refused: row?.refused ?? 0,
27269
- detached: row?.detached ?? 0,
27270
- total: row?.total ?? 0
27271
- };
27272
- }
27273
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27274
- counts(before) {
27275
- const row = getRow(this.countsStmt, { before });
27276
- const captures = getRow(this.captureSkipCountStmt);
26617
+ /**
26618
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26619
+ * and skipped are totals.
26620
+ *
26621
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26622
+ * `capturesSkipped` included: a structural row is counted only when its own
26623
+ * key and its session root's key are among them, a capture when its own key
26624
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26625
+ * under the same keys and boundary. Omitted, this runs the machine
26626
+ * statements, unchanged; an empty list counts nothing.
26627
+ */
26628
+ counts(before, scopeKeys) {
26629
+ const row = getRow(
26630
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26631
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26632
+ );
26633
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26634
+ scopeKeys: scopeKeysParam(scopeKeys)
26635
+ });
27277
26636
  return {
27278
26637
  pending: row?.pending ?? 0,
27279
26638
  sent: row?.sent ?? 0,
@@ -27525,6 +26884,7 @@ function applyMigrations(db, file2, options = {}) {
27525
26884
  }
27526
26885
  ensureSyncedAtColumn(db, "audit_events");
27527
26886
  ensureScopeKeyColumn(db);
26887
+ ensureScopeOwedIndex(db);
27528
26888
  ensureScanLedgerTable(db);
27529
26889
  ensureHistorySyncTable(db);
27530
26890
  ensureBlockedDetectionsTable(db);
@@ -27965,14 +27325,48 @@ function ensureScopeKeyColumn(db) {
27965
27325
  function hasScopeKeyColumn(db) {
27966
27326
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
27967
27327
  }
27328
+ 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";
27329
+ function ensureScopeOwedIndex(db) {
27330
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27331
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27332
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27333
+ if (!complete) return;
27334
+ db.exec(SCOPE_OWED_INDEX_DDL);
27335
+ }
27968
27336
  function ensureScanLedgerTable(db) {
27969
27337
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27970
27338
  path TEXT PRIMARY KEY,
27971
27339
  mtime TEXT NOT NULL,
27972
27340
  content_hash TEXT NOT NULL,
27973
27341
  ruleset_hash TEXT NOT NULL,
27974
- scanned_at INTEGER NOT NULL
27342
+ scanned_at INTEGER NOT NULL,
27343
+ scope_key TEXT,
27344
+ scope_root TEXT
27975
27345
  )`);
27346
+ ensureScanLedgerScopeKeyColumn(db);
27347
+ ensureScanLedgerScopeRootColumn(db);
27348
+ }
27349
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27350
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27351
+ function ensureScanLedgerScopeKeyColumn(db) {
27352
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27353
+ }
27354
+ function ensureScanLedgerScopeRootColumn(db) {
27355
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27356
+ }
27357
+ function ensureScanLedgerColumn(db, column, ddl) {
27358
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27359
+ if (hasScanLedgerColumn(db, column)) return;
27360
+ withTransaction(
27361
+ db,
27362
+ () => {
27363
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27364
+ },
27365
+ "IMMEDIATE"
27366
+ );
27367
+ }
27368
+ function hasScanLedgerColumn(db, column) {
27369
+ return columnNames(db, "scan_ledger").includes(column);
27976
27370
  }
27977
27371
  function ensureHistorySyncTable(db) {
27978
27372
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28023,6 +27417,106 @@ function ensureRuleProbeCacheTable(db) {
28023
27417
  )`);
28024
27418
  }
28025
27419
 
27420
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27421
+ import { createHash as createHash2 } from "crypto";
27422
+ import { readFileSync as readFileSync2 } from "fs";
27423
+ import { join as join4 } from "path";
27424
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27425
+ function modPolicySnapshotPath(dataDir2) {
27426
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27427
+ }
27428
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27429
+ const byRule = /* @__PURE__ */ new Map();
27430
+ const byCategory = /* @__PURE__ */ new Map();
27431
+ for (const policy of input2.policies) {
27432
+ if (!policy.enabled) continue;
27433
+ if ("ruleId" in policy.target) {
27434
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27435
+ } else if (!byCategory.has(policy.target.category)) {
27436
+ byCategory.set(policy.target.category, policy.action);
27437
+ }
27438
+ }
27439
+ const categoryActions = {};
27440
+ for (const category of DetectionCategory.options) {
27441
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27442
+ }
27443
+ return {
27444
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27445
+ generatedAt: generatedAt.toISOString(),
27446
+ // `examples` is documentation the mod never reads, and a custom pack's are
27447
+ // whatever its author pasted in, so they stay behind.
27448
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27449
+ ruleActions: Object.fromEntries(byRule),
27450
+ categoryActions,
27451
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27452
+ };
27453
+ }
27454
+ function assignedRuleActionPolicies(installed) {
27455
+ const out = [];
27456
+ for (const [ruleId, action] of installed.ruleActions) {
27457
+ if (installed.assignedRules.has(ruleId))
27458
+ out.push({ target: { ruleId }, action, enabled: true });
27459
+ }
27460
+ return out;
27461
+ }
27462
+ function withoutExamples(rule) {
27463
+ const copy = { ...rule };
27464
+ delete copy.examples;
27465
+ return copy;
27466
+ }
27467
+ function sameContent(a, b) {
27468
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27469
+ }
27470
+ function readModPolicySnapshot(dataDir2) {
27471
+ try {
27472
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27473
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27474
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27475
+ return parsed2.success ? parsed2.data : null;
27476
+ } catch {
27477
+ return null;
27478
+ }
27479
+ }
27480
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27481
+ const text = JSON.stringify(snapshot);
27482
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27483
+ const existing = readModPolicySnapshot(dataDir2);
27484
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27485
+ ensureDataDirSync(dataDir2);
27486
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27487
+ return true;
27488
+ }
27489
+ function regexProbeKey(matcher) {
27490
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27491
+ }
27492
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27493
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27494
+ return rules.filter((rule) => {
27495
+ if (rule.matcher.type !== "regex") return true;
27496
+ const key = regexProbeKey(rule.matcher);
27497
+ const verdict = sources.probeVerdict(key);
27498
+ if (verdict === "quarantined") return false;
27499
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27500
+ });
27501
+ }
27502
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27503
+ const policies = sources.readPolicies();
27504
+ const snapshot = sources.installedRuleset();
27505
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27506
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27507
+ return {
27508
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27509
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27510
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27511
+ };
27512
+ }
27513
+ function refreshModPolicySnapshot(dataDir2, sources) {
27514
+ try {
27515
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27516
+ } catch {
27517
+ }
27518
+ }
27519
+
28026
27520
  // ../../packages/persistence/src/internal/json.ts
28027
27521
  function safeJson(s, fallback) {
28028
27522
  if (s == null) return fallback;
@@ -28197,6 +27691,11 @@ var TIMELINE_COLUMNS = `
28197
27691
  json_extract(attributes, '$.targetId') AS target_id,
28198
27692
  json_extract(attributes, '$.internal') AS internal,
28199
27693
  json_extract(attributes, '$.flagged') AS flagged`;
27694
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27695
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27696
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27697
+ " + "
27698
+ );
28200
27699
  var LLM_USAGE_SELECT = `
28201
27700
  SELECT root_session_id AS sessionId,
28202
27701
  provider,
@@ -28208,9 +27707,10 @@ var LLM_USAGE_SELECT = `
28208
27707
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28209
27708
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28210
27709
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28211
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27710
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27711
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28212
27712
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28213
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27713
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28214
27714
  function usageLeaves(rows) {
28215
27715
  return rows.map((row) => {
28216
27716
  const attributes = {
@@ -28225,7 +27725,7 @@ function usageLeaves(rows) {
28225
27725
  if (row.provider !== null) attributes.provider = row.provider;
28226
27726
  if (row.model !== null) attributes.model = row.model;
28227
27727
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28228
- return { sessionId: row.sessionId, attributes };
27728
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28229
27729
  });
28230
27730
  }
28231
27731
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29158,8 +28658,8 @@ var SqliteConfigInventoryRepository = class {
29158
28658
  }
29159
28659
  db;
29160
28660
  report() {
29161
- const scan2 = latestConfigScan(this.db);
29162
- if (!scan2) {
28661
+ const scan = latestConfigScan(this.db);
28662
+ if (!scan) {
29163
28663
  return {
29164
28664
  scannedAt: null,
29165
28665
  skills: [],
@@ -29175,7 +28675,7 @@ var SqliteConfigInventoryRepository = class {
29175
28675
  WHERE object_type IN ('skill', 'hook', 'mcp_server', 'config_file') AND last_seen >= :startedAt
29176
28676
  ORDER BY object_type, title`
29177
28677
  ),
29178
- { startedAt: scan2.started_at }
28678
+ { startedAt: scan.started_at }
29179
28679
  );
29180
28680
  const findings = allRows(
29181
28681
  this.db.prepare(
@@ -29184,7 +28684,7 @@ var SqliteConfigInventoryRepository = class {
29184
28684
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
29185
28685
  WHERE f.audit_event_id = :scanId`
29186
28686
  ),
29187
- { scanId: scan2.id }
28687
+ { scanId: scan.id }
29188
28688
  );
29189
28689
  const skills = [];
29190
28690
  const hooks = [];
@@ -29200,12 +28700,12 @@ var SqliteConfigInventoryRepository = class {
29200
28700
  else configFiles.push(toConfigFileItem(row, bag));
29201
28701
  }
29202
28702
  return {
29203
- scannedAt: new Date(scan2.started_at).toISOString(),
28703
+ scannedAt: new Date(scan.started_at).toISOString(),
29204
28704
  skills,
29205
28705
  hooks,
29206
28706
  mcpServers,
29207
28707
  configFiles,
29208
- topics: buildTopics(skills, hooks, mcpServers, configFiles, scan2.attributes)
28708
+ topics: buildTopics(skills, hooks, mcpServers, configFiles, scan.attributes)
29209
28709
  };
29210
28710
  }
29211
28711
  // asset_id → trust for every stored override. The id space is opaque on
@@ -29559,9 +29059,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29559
29059
  AND conditions IS NULL
29560
29060
  AND ${ACTIVE_PREDICATE}`;
29561
29061
  var SqliteExceptionsRepository = class {
29562
- constructor(db, now = () => Date.now()) {
29062
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29563
29063
  this.db = db;
29564
29064
  this.now = now;
29065
+ this.onChange = onChange;
29565
29066
  this.consumeStmt = db.prepare(
29566
29067
  `UPDATE exceptions
29567
29068
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29580,6 +29081,7 @@ var SqliteExceptionsRepository = class {
29580
29081
  }
29581
29082
  db;
29582
29083
  now;
29084
+ onChange;
29583
29085
  consumeStmt;
29584
29086
  insertBlockedStmt;
29585
29087
  sweepBlockedStmt;
@@ -29595,7 +29097,9 @@ var SqliteExceptionsRepository = class {
29595
29097
  */
29596
29098
  create(input2) {
29597
29099
  try {
29598
- return Promise.resolve(this.createSync(input2));
29100
+ const created = this.createSync(input2);
29101
+ this.onChange();
29102
+ return Promise.resolve(created);
29599
29103
  } catch (err) {
29600
29104
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29601
29105
  }
@@ -29726,6 +29230,7 @@ var SqliteExceptionsRepository = class {
29726
29230
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29727
29231
  WHERE id = :id AND revoked_at IS NULL`
29728
29232
  ).run({ id, revokedBy, reason: reason ?? null, now });
29233
+ if (Number(result.changes) === 1) this.onChange();
29729
29234
  return Promise.resolve(Number(result.changes) === 1);
29730
29235
  }
29731
29236
  /**
@@ -29738,6 +29243,15 @@ var SqliteExceptionsRepository = class {
29738
29243
  const result = this.consumeStmt.run({ id, now });
29739
29244
  return Promise.resolve(Number(result.changes) === 1);
29740
29245
  }
29246
+ /** The rule ids with at least one active grant, under any key version. */
29247
+ activeRuleIds(now = this.now()) {
29248
+ return allRows(
29249
+ this.db.prepare(
29250
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29251
+ ),
29252
+ { now }
29253
+ ).map((row) => row.ruleId);
29254
+ }
29741
29255
  /**
29742
29256
  * The evaluation subset of every active grant under one fingerprint key
29743
29257
  * version — what rides the policy bundle to the hook. Grants written under
@@ -30861,30 +30375,30 @@ var SqliteInspectionFindingsRepository = class {
30861
30375
  };
30862
30376
 
30863
30377
  // ../../packages/persistence/src/repositories/installed-packs.ts
30864
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30378
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
30865
30379
 
30866
30380
  // ../../packages/persistence/src/policy-floor.ts
30867
- import { readFileSync as readFileSync5 } from "fs";
30868
- import { join as join6 } from "path";
30381
+ import { readFileSync as readFileSync6 } from "fs";
30382
+ import { join as join7 } from "path";
30869
30383
 
30870
30384
  // ../../packages/persistence/src/local-layout.ts
30871
30385
  import { renameSync as renameSync3 } from "fs";
30872
30386
  import { mkdir } from "fs/promises";
30873
30387
  import { homedir } from "os";
30874
- import { join as join4 } from "path";
30388
+ import { join as join5 } from "path";
30875
30389
  function defaultDataDir() {
30876
- return join4(homedir(), ".aka");
30390
+ return join5(homedir(), ".aka");
30877
30391
  }
30878
30392
  function settingsDir(base = defaultDataDir()) {
30879
- return join4(base, "settings");
30393
+ return join5(base, "settings");
30880
30394
  }
30881
30395
  function dataDir(base = defaultDataDir()) {
30882
- return join4(base, "data");
30396
+ return join5(base, "data");
30883
30397
  }
30884
30398
 
30885
30399
  // ../../packages/persistence/src/settings.ts
30886
- import { readFileSync as readFileSync4 } from "fs";
30887
- import { join as join5 } from "path";
30400
+ import { readFileSync as readFileSync5 } from "fs";
30401
+ import { join as join6 } from "path";
30888
30402
 
30889
30403
  // ../../packages/persistence/src/file-lock.ts
30890
30404
  import { randomUUID as randomUUID3 } from "crypto";
@@ -30892,7 +30406,7 @@ import {
30892
30406
  closeSync,
30893
30407
  existsSync as existsSync2,
30894
30408
  openSync,
30895
- readFileSync as readFileSync2,
30409
+ readFileSync as readFileSync3,
30896
30410
  rmSync as rmSync5,
30897
30411
  statSync as statSync3,
30898
30412
  writeFileSync as writeFileSync2
@@ -30901,16 +30415,16 @@ import { hostname as hostname3 } from "os";
30901
30415
  var PARK = new Int32Array(new SharedArrayBuffer(4));
30902
30416
 
30903
30417
  // ../../packages/persistence/src/managed-settings.ts
30904
- import { readFileSync as readFileSync3 } from "fs";
30418
+ import { readFileSync as readFileSync4 } from "fs";
30905
30419
  import { posix, win32 } from "path";
30906
- function managedSettingsPaths(platform2 = process.platform) {
30907
- if (platform2 === "darwin") {
30420
+ function managedSettingsPaths(platform = process.platform) {
30421
+ if (platform === "darwin") {
30908
30422
  return [
30909
30423
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
30910
30424
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
30911
30425
  ];
30912
30426
  }
30913
- if (platform2 === "win32") {
30427
+ if (platform === "win32") {
30914
30428
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
30915
30429
  }
30916
30430
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -30920,7 +30434,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
30920
30434
  for (const path of paths) {
30921
30435
  let text;
30922
30436
  try {
30923
- text = readFileSync3(path, "utf8");
30437
+ text = readFileSync4(path, "utf8");
30924
30438
  } catch {
30925
30439
  continue;
30926
30440
  }
@@ -30974,7 +30488,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
30974
30488
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
30975
30489
  }
30976
30490
  function readUserSettings(base) {
30977
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30491
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
30978
30492
  if (!record2) return defaultWorkspaceSettings();
30979
30493
  try {
30980
30494
  return WorkspaceSettings.parse(record2);
@@ -30985,7 +30499,7 @@ function readUserSettings(base) {
30985
30499
  function readJson(file2) {
30986
30500
  let text;
30987
30501
  try {
30988
- text = readFileSync4(file2, "utf8");
30502
+ text = readFileSync5(file2, "utf8");
30989
30503
  } catch {
30990
30504
  return null;
30991
30505
  }
@@ -31025,7 +30539,7 @@ var PolicyFloorError = class extends Error {
31025
30539
  };
31026
30540
  function readCachedPolicyBundle(base = defaultDataDir()) {
31027
30541
  try {
31028
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30542
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31029
30543
  const parsed2 = JSON.parse(raw);
31030
30544
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31031
30545
  return PolicyBundle.parse(parsed2.bundle);
@@ -31149,7 +30663,7 @@ function inventorySignature(packs) {
31149
30663
  return packs.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31150
30664
  }
31151
30665
  function hashRules(rulesJson) {
31152
- return createHash2("sha256").update(rulesJson).digest("hex");
30666
+ return createHash3("sha256").update(rulesJson).digest("hex");
31153
30667
  }
31154
30668
  function parseVersion(v) {
31155
30669
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31191,9 +30705,10 @@ var SqliteInstalledPacksRepository = class {
31191
30705
  * from `openLocalDatabase`, which is the single construction site that owns a
31192
30706
  * real `~/.aka`.
31193
30707
  */
31194
- constructor(db, baseDir) {
30708
+ constructor(db, baseDir, onChange = () => void 0) {
31195
30709
  this.db = db;
31196
30710
  this.baseDir = baseDir;
30711
+ this.onChange = onChange;
31197
30712
  this.insertMissingStmt = db.prepare(
31198
30713
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31199
30714
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31222,6 +30737,7 @@ var SqliteInstalledPacksRepository = class {
31222
30737
  }
31223
30738
  db;
31224
30739
  baseDir;
30740
+ onChange;
31225
30741
  insertMissingStmt;
31226
30742
  upsertAvailableStmt;
31227
30743
  signatureStmt;
@@ -31294,6 +30810,7 @@ var SqliteInstalledPacksRepository = class {
31294
30810
  },
31295
30811
  "IMMEDIATE"
31296
30812
  );
30813
+ this.onChange();
31297
30814
  } catch {
31298
30815
  }
31299
30816
  }
@@ -31368,6 +30885,7 @@ var SqliteInstalledPacksRepository = class {
31368
30885
  },
31369
30886
  "IMMEDIATE"
31370
30887
  );
30888
+ if (changed) this.onChange();
31371
30889
  return changed;
31372
30890
  }
31373
30891
  /**
@@ -31609,6 +31127,7 @@ var SqliteInstalledPacksRepository = class {
31609
31127
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31610
31128
  WHERE namespace = :namespace AND pack_id = :packId`
31611
31129
  ).run({ policyId, now: Date.now(), namespace, packId });
31130
+ if (Number(res.changes) > 0) this.onChange();
31612
31131
  return Number(res.changes) > 0;
31613
31132
  }
31614
31133
  /**
@@ -31633,6 +31152,7 @@ var SqliteInstalledPacksRepository = class {
31633
31152
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31634
31153
  WHERE namespace = :namespace AND pack_id = :packId`
31635
31154
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31155
+ if (Number(res.changes) > 0) this.onChange();
31636
31156
  return Number(res.changes) > 0;
31637
31157
  }
31638
31158
  // Fingerprint of the recorded available mirror — compared against the
@@ -32530,13 +32050,19 @@ var SqliteInventoryAssetsRepository = class {
32530
32050
  import { randomUUID as randomUUID6 } from "crypto";
32531
32051
  var SEED_BATCH_WINDOW_MS = 6e4;
32532
32052
  var SqlitePoliciesRepository = class {
32533
- constructor(db) {
32053
+ constructor(db, onChange = () => void 0) {
32534
32054
  this.db = db;
32055
+ this.onChange = onChange;
32535
32056
  }
32536
32057
  db;
32058
+ onChange;
32537
32059
  readPolicies() {
32060
+ return Promise.resolve(this.listPolicies());
32061
+ }
32062
+ /** The synchronous read behind {@link readPolicies}. */
32063
+ listPolicies() {
32538
32064
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32539
- const policies = mapRowsTolerant(rows, (row) => {
32065
+ return mapRowsTolerant(rows, (row) => {
32540
32066
  const target = JSON.parse(row.target);
32541
32067
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32542
32068
  return Policy.parse({
@@ -32548,7 +32074,6 @@ var SqlitePoliciesRepository = class {
32548
32074
  customKeywords
32549
32075
  });
32550
32076
  });
32551
- return Promise.resolve(policies);
32552
32077
  }
32553
32078
  // Seed one policy per bundled category at Monitor so the detection-type config
32554
32079
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32559,7 +32084,7 @@ var SqlitePoliciesRepository = class {
32559
32084
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32560
32085
  if (count > 0) {
32561
32086
  this.markEarlierChoices();
32562
- this.monitorUntouchedSeeds();
32087
+ if (this.monitorUntouchedSeeds()) this.onChange();
32563
32088
  return;
32564
32089
  }
32565
32090
  const stmt = this.db.prepare(
@@ -32576,6 +32101,7 @@ var SqlitePoliciesRepository = class {
32576
32101
  });
32577
32102
  }
32578
32103
  });
32104
+ this.onChange();
32579
32105
  }
32580
32106
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32581
32107
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32641,7 +32167,7 @@ var SqlitePoliciesRepository = class {
32641
32167
  ).filter(
32642
32168
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32643
32169
  );
32644
- if (untouched.length === 0) return;
32170
+ if (untouched.length === 0) return false;
32645
32171
  const stmt = this.db.prepare(
32646
32172
  `UPDATE policies SET action = 'log'
32647
32173
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32652,6 +32178,7 @@ var SqlitePoliciesRepository = class {
32652
32178
  stmt.run({ category: row.category, seeded: row.action });
32653
32179
  }
32654
32180
  });
32181
+ return true;
32655
32182
  }
32656
32183
  // Insert-or-update the single global per-category policy row, keyed on the
32657
32184
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32668,6 +32195,7 @@ var SqlitePoliciesRepository = class {
32668
32195
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32669
32196
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32670
32197
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32198
+ this.onChange();
32671
32199
  }
32672
32200
  // Caps every global per-category policy currently set to block/redact down
32673
32201
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32678,6 +32206,7 @@ var SqlitePoliciesRepository = class {
32678
32206
  WHERE scope='global' AND action IN ('block','redact')
32679
32207
  AND json_extract(target,'$.category') IS NOT NULL`
32680
32208
  ).run({ now: Date.now() });
32209
+ if (Number(info.changes) > 0) this.onChange();
32681
32210
  return Number(info.changes);
32682
32211
  }
32683
32212
  // Whether the category's row was ever written after it was created — by the
@@ -32772,10 +32301,10 @@ var SqliteProjectFilesRepository = class {
32772
32301
  pruneStmt;
32773
32302
  maxStampStmt;
32774
32303
  /** Replace `projectId`'s tree with the scan's files. Caller wraps in a transaction. */
32775
- replaceForProject(projectId, scan2, now) {
32304
+ replaceForProject(projectId, scan, now) {
32776
32305
  const maxStamp = getRow(this.maxStampStmt, { projectId })?.maxStamp ?? 0;
32777
32306
  const stamp = Math.max(now, maxStamp + 1);
32778
- for (const file2 of scan2.files) {
32307
+ for (const file2 of scan.files) {
32779
32308
  this.upsertStmt.run({
32780
32309
  id: randomUUID7(),
32781
32310
  projectId,
@@ -32786,7 +32315,7 @@ var SqliteProjectFilesRepository = class {
32786
32315
  now: stamp
32787
32316
  });
32788
32317
  }
32789
- if (!scan2.truncated) this.pruneStmt.run({ projectId, now: stamp });
32318
+ if (!scan.truncated) this.pruneStmt.run({ projectId, now: stamp });
32790
32319
  }
32791
32320
  };
32792
32321
 
@@ -32997,31 +32526,45 @@ var SqliteScanLedgerRepository = class {
32997
32526
  constructor(db) {
32998
32527
  this.db = db;
32999
32528
  this.upsertStmt = db.prepare(
33000
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33001
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32529
+ `INSERT INTO scan_ledger
32530
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32531
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33002
32532
  ON CONFLICT (path) DO UPDATE SET
33003
32533
  mtime = excluded.mtime,
33004
32534
  content_hash = excluded.content_hash,
33005
32535
  ruleset_hash = excluded.ruleset_hash,
32536
+ scope_key = excluded.scope_key,
32537
+ scope_root = excluded.scope_root,
33006
32538
  scanned_at = excluded.scanned_at`
33007
32539
  );
33008
32540
  this.readStmt = db.prepare(
33009
- `SELECT path, mtime, content_hash AS contentHash
32541
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32542
+ scope_root AS scopeRoot
33010
32543
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33011
32544
  );
33012
32545
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32546
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33013
32547
  }
33014
32548
  db;
33015
32549
  upsertStmt;
33016
32550
  readStmt;
33017
32551
  pathsStmt;
32552
+ pathKeysStmt;
33018
32553
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33019
32554
  // older ruleset are simply absent, which reads as "never scanned".
33020
32555
  entriesForRuleset(rulesetHash) {
33021
- const rows = allRows(this.readStmt, {
33022
- rulesetHash
33023
- });
33024
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32556
+ const rows = allRows(this.readStmt, { rulesetHash });
32557
+ return new Map(
32558
+ rows.map((r) => [
32559
+ r.path,
32560
+ {
32561
+ mtime: r.mtime,
32562
+ contentHash: r.contentHash,
32563
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32564
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32565
+ }
32566
+ ])
32567
+ );
33025
32568
  }
33026
32569
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33027
32570
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33030,6 +32573,14 @@ var SqliteScanLedgerRepository = class {
33030
32573
  allPaths() {
33031
32574
  return allRows(this.pathsStmt).map((r) => r.path);
33032
32575
  }
32576
+ // Every ledgered path with the repository it was in when it was last read,
32577
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32578
+ // which repository a vanished file belonged to. `undefined` for a row with no
32579
+ // key, which is every row written before the column existed.
32580
+ pathKeys() {
32581
+ const rows = allRows(this.pathKeysStmt);
32582
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32583
+ }
33033
32584
  upsertEntries(entries) {
33034
32585
  if (entries.length === 0) return;
33035
32586
  const scannedAt = Date.now();
@@ -33040,6 +32591,8 @@ var SqliteScanLedgerRepository = class {
33040
32591
  mtime: entry.mtime,
33041
32592
  contentHash: entry.contentHash,
33042
32593
  rulesetHash: entry.rulesetHash,
32594
+ scopeKey: entry.scopeKey ?? null,
32595
+ scopeRoot: entry.scopeRoot ?? null,
33043
32596
  scannedAt
33044
32597
  });
33045
32598
  }
@@ -34127,6 +33680,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34127
33680
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34128
33681
  };
34129
33682
  }
33683
+ function withoutTrailingSlashes(path) {
33684
+ let end = path.length;
33685
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33686
+ return path.slice(0, end);
33687
+ }
34130
33688
  function toEndpointSummary(row) {
34131
33689
  return {
34132
33690
  id: row.id,
@@ -34414,7 +33972,7 @@ var SqliteSharesRepository = class {
34414
33972
  */
34415
33973
  reconcileCallSites(projectKey, reconcile) {
34416
33974
  if (reconcile.mode === "walk") {
34417
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
33975
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34418
33976
  this.db.prepare(
34419
33977
  `DELETE FROM share_call_site
34420
33978
  WHERE project_key = :key
@@ -34982,7 +34540,7 @@ function backupLegacyStore(db, file2) {
34982
34540
  discardStore(file2, backup);
34983
34541
  return backup;
34984
34542
  }
34985
- function openAndInitialize(file2, base, skipTags) {
34543
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers) {
34986
34544
  let db = openWithPragmas(file2);
34987
34545
  try {
34988
34546
  if (isForeignSqliteLineage(db)) {
@@ -34994,8 +34552,15 @@ function openAndInitialize(file2, base, skipTags) {
34994
34552
  }
34995
34553
  applyMigrations(db, file2, { skipTags });
34996
34554
  tightenPerms(file2);
34997
- const policies = new SqlitePoliciesRepository(db);
34998
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34555
+ const modPolicy = {};
34556
+ const onPolicyStateChange = () => {
34557
+ if (modPolicy.current !== void 0)
34558
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34559
+ };
34560
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34561
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34562
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34563
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
34999
34564
  const repositories = {
35000
34565
  events: new SqliteEventsRepository(db),
35001
34566
  findings: new SqliteFindingsRepository(db),
@@ -35004,9 +34569,9 @@ function openAndInitialize(file2, base, skipTags) {
35004
34569
  scanLedger: new SqliteScanLedgerRepository(db),
35005
34570
  historySync: new SqliteHistorySyncRepository(db),
35006
34571
  secretVault: new SqliteSecretVaultRepository(db),
35007
- exceptions: new SqliteExceptionsRepository(db),
34572
+ exceptions,
35008
34573
  resolutions: new SqliteResolutionsRepository(db),
35009
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34574
+ ruleProbeCache,
35010
34575
  bodyRetention: new SqliteBodyRetentionRepository(db),
35011
34576
  security: new SqliteSecurityRepository(db),
35012
34577
  detections: new SqliteDetectionsRepository(db),
@@ -35024,6 +34589,13 @@ function openAndInitialize(file2, base, skipTags) {
35024
34589
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35025
34590
  configInventory: new SqliteConfigInventoryRepository(db)
35026
34591
  };
34592
+ modPolicy.current = {
34593
+ installedRuleset: () => installedPacks.installedRuleset(),
34594
+ readPolicies: () => policies.listPolicies(),
34595
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34596
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34597
+ bundledRegexMatchers: () => shippedRegexMatchers
34598
+ };
35027
34599
  policies.seedDefaults();
35028
34600
  return { db, ...repositories };
35029
34601
  } catch (err) {
@@ -35035,7 +34607,7 @@ function openAndInitialize(file2, base, skipTags) {
35035
34607
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35036
34608
  function openLocalDatabase(dir, options = {}) {
35037
34609
  ensureDataDirSync(dir);
35038
- const file2 = join7(dir, DB_FILENAME);
34610
+ const file2 = join8(dir, DB_FILENAME);
35039
34611
  reapStalePartials(file2);
35040
34612
  const {
35041
34613
  db,
@@ -35071,7 +34643,8 @@ function openLocalDatabase(dir, options = {}) {
35071
34643
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35072
34644
  // settings/ and data/, and the pack-policy floor needs both halves.
35073
34645
  dirname2(dir),
35074
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34646
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34647
+ options.shippedRegexMatchers ?? []
35075
34648
  );
35076
34649
  function captureRowId(event) {
35077
34650
  return captureId(
@@ -35227,10 +34800,10 @@ function openLocalDatabase(dir, options = {}) {
35227
34800
  }
35228
34801
  });
35229
34802
  }
35230
- function recordProjectFiles(projectId, scan2) {
35231
- if (scan2.files.length === 0) return;
34803
+ function recordProjectFiles(projectId, scan) {
34804
+ if (scan.files.length === 0) return;
35232
34805
  failOpenTransaction(db, () => {
35233
- projectFiles.replaceForProject(projectId, scan2, Date.now());
34806
+ projectFiles.replaceForProject(projectId, scan, Date.now());
35234
34807
  });
35235
34808
  }
35236
34809
  async function transaction(fn) {
@@ -35336,22 +34909,21 @@ function openLocalDatabase(dir, options = {}) {
35336
34909
  }
35337
34910
 
35338
34911
  // ../../packages/persistence/src/egress-wire.ts
35339
- import { createHash as createHash3 } from "crypto";
34912
+ import { createHash as createHash4 } from "crypto";
35340
34913
  var SLASH = "/".charCodeAt(0);
35341
34914
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35342
34915
 
35343
34916
  // ../../packages/persistence/src/finding-key.ts
35344
- import { createHash as createHash4 } from "crypto";
34917
+ import { createHash as createHash5 } from "crypto";
35345
34918
 
35346
34919
  // ../../packages/persistence/src/fingerprint.ts
35347
34920
  import { createHmac, randomBytes } from "crypto";
35348
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35349
- import { join as join8 } from "path";
35350
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34921
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
34922
+ import { join as join9 } from "path";
35351
34923
 
35352
34924
  // ../../packages/persistence/src/forward-health.ts
35353
- import { readFileSync as readFileSync7 } from "fs";
35354
- import { join as join9 } from "path";
34925
+ import { readFileSync as readFileSync8 } from "fs";
34926
+ import { join as join10 } from "path";
35355
34927
  var BREAKER_COOLDOWN_MS = 3e4;
35356
34928
  function parseForwardHealth(raw, nowMs) {
35357
34929
  try {
@@ -35370,7 +34942,7 @@ function parseForwardHealth(raw, nowMs) {
35370
34942
  function readForwardHealth(dir, nowMs = Date.now()) {
35371
34943
  try {
35372
34944
  return parseForwardHealth(
35373
- readFileSync7(join9(dir, ATTACHED_FORWARD_STATE_FILENAME), "utf8"),
34945
+ readFileSync8(join10(dir, ATTACHED_FORWARD_STATE_FILENAME), "utf8"),
35374
34946
  nowMs
35375
34947
  );
35376
34948
  } catch {
@@ -35385,16 +34957,16 @@ function isForwardPaused(health, nowMs) {
35385
34957
 
35386
34958
  // ../../packages/persistence/src/history-backfill.ts
35387
34959
  import { existsSync as existsSync4 } from "fs";
35388
- import { join as join10 } from "path";
34960
+ import { join as join11 } from "path";
35389
34961
 
35390
34962
  // ../../packages/persistence/src/history-preview.ts
35391
34963
  import { existsSync as existsSync5 } from "fs";
35392
- import { join as join11 } from "path";
35393
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
34964
+ import { join as join12 } from "path";
34965
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35394
34966
 
35395
34967
  // ../../packages/persistence/src/history-sync-state.ts
35396
- import { readFileSync as readFileSync8 } from "fs";
35397
- import { join as join12 } from "path";
34968
+ import { readFileSync as readFileSync9 } from "fs";
34969
+ import { join as join13 } from "path";
35398
34970
  var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
35399
34971
  var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
35400
34972
  var OUTCOMES = /* @__PURE__ */ new Set([
@@ -35403,9 +34975,10 @@ var OUTCOMES = /* @__PURE__ */ new Set([
35403
34975
  "refused",
35404
34976
  "interrupted"
35405
34977
  ]);
34978
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35406
34979
  var SPEC_VERSION = 1;
35407
34980
  function historySyncStatePath(dataDir2) {
35408
- return join12(dataDir2, HISTORY_SYNC_STATE_FILENAME);
34981
+ return join13(dataDir2, HISTORY_SYNC_STATE_FILENAME);
35409
34982
  }
35410
34983
  function writeHistorySyncState(dataDir2, state) {
35411
34984
  try {
@@ -35418,7 +34991,7 @@ function writeHistorySyncState(dataDir2, state) {
35418
34991
  }
35419
34992
  function readHistorySyncState(dataDir2) {
35420
34993
  try {
35421
- const parsed2 = JSON.parse(readFileSync8(historySyncStatePath(dataDir2), "utf8"));
34994
+ const parsed2 = JSON.parse(readFileSync9(historySyncStatePath(dataDir2), "utf8"));
35422
34995
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
35423
34996
  const r = parsed2;
35424
34997
  if (r.specVersion !== SPEC_VERSION) return null;
@@ -35436,7 +35009,8 @@ function readHistorySyncState(dataDir2) {
35436
35009
  pendingTotal: r.pendingTotal,
35437
35010
  skippedTotal: r.skippedTotal,
35438
35011
  startedAtMs: r.startedAtMs,
35439
- completedAtMs: r.completedAtMs
35012
+ completedAtMs: r.completedAtMs,
35013
+ ...isCountsScope(r.countsScope) ? { countsScope: r.countsScope } : {}
35440
35014
  };
35441
35015
  } catch {
35442
35016
  return null;
@@ -35448,10 +35022,13 @@ function isCount(v) {
35448
35022
  function isNullableCount(v) {
35449
35023
  return v === null || isCount(v);
35450
35024
  }
35025
+ function isCountsScope(v) {
35026
+ return typeof v === "string" && COUNTS_SCOPES.has(v);
35027
+ }
35451
35028
 
35452
35029
  // ../../packages/persistence/src/store-symlinks.ts
35453
35030
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35454
- import { dirname as dirname3, join as join13, resolve } from "path";
35031
+ import { dirname as dirname3, join as join14, resolve } from "path";
35455
35032
 
35456
35033
  // ../../packages/persistence/src/vault/crypto.ts
35457
35034
  import {
@@ -35465,15 +35042,15 @@ import {
35465
35042
  // ../../packages/persistence/src/vault/key-provider.ts
35466
35043
  import { execFileSync } from "child_process";
35467
35044
  import { randomBytes as randomBytes2 } from "crypto";
35468
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35469
- import { join as join14 } from "path";
35045
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35046
+ import { join as join15 } from "path";
35470
35047
 
35471
35048
  // ../../packages/persistence/src/vault/vault.ts
35472
35049
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35473
35050
 
35474
35051
  // ../../packages/persistence/src/warn-era-cap.ts
35475
35052
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35476
- import { join as join15 } from "path";
35053
+ import { join as join16 } from "path";
35477
35054
 
35478
35055
  // ../../packages/remote/src/http.ts
35479
35056
  import { request as httpRequest } from "http";
@@ -35788,998 +35365,13 @@ function createRemoteClient(options) {
35788
35365
  var REQUEST_TIMEOUT_MS = 2e3;
35789
35366
 
35790
35367
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
35791
- import { readFileSync as readFileSync10 } from "fs";
35792
- import { join as join16 } from "path";
35368
+ import { readFileSync as readFileSync11 } from "fs";
35369
+ import { join as join17 } from "path";
35793
35370
 
35794
35371
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35795
- import { randomUUID as randomUUID16 } from "crypto";
35372
+ import { randomUUID as randomUUID13 } from "crypto";
35796
35373
  import { readFile, rename, writeFile } from "fs/promises";
35797
- import { join as join28 } from "path";
35798
-
35799
- // ../../packages/plugin-sdk/src/config.ts
35800
- import { existsSync as existsSync8 } from "fs";
35801
- import { join as join17 } from "path";
35802
-
35803
- // ../../packages/plugin-sdk/src/provider-env.ts
35804
- var booleanish = external_exports.string().optional().transform((v) => {
35805
- if (v === void 0) return void 0;
35806
- const t = v.trim().toLowerCase();
35807
- if (t === "" || t === "false" || t === "0") return false;
35808
- return true;
35809
- }).catch(void 0);
35810
- var optionalBaseUrl = external_exports.preprocess((v) => {
35811
- if (typeof v === "string" && v.trim() === "") return void 0;
35812
- return v;
35813
- }, external_exports.string().optional()).catch(void 0);
35814
- var providerEnvShape = {
35815
- CLAUDE_CODE_USE_BEDROCK: booleanish,
35816
- CLAUDE_CODE_USE_VERTEX: booleanish,
35817
- ANTHROPIC_BASE_URL: optionalBaseUrl
35818
- };
35819
- var ProviderEnvSchema = external_exports.object(providerEnvShape);
35820
-
35821
- // ../../packages/plugin-sdk/src/config-inventory.ts
35822
- import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
35823
- import { homedir as homedir2 } from "os";
35824
- import { basename as basename3, join as join19 } from "path";
35825
-
35826
- // ../../packages/detections/src/egress/registry.ts
35827
- var EXTRACTOR_VERSION = "3";
35828
- var PROVIDER_REGISTRY = [
35829
- {
35830
- id: "stripe",
35831
- name: "Stripe",
35832
- category: "Payments",
35833
- hostSuffixes: ["stripe.com"],
35834
- apiBase: "https://api.stripe.com",
35835
- defaultDataClasses: ["pii", "customer"],
35836
- sdks: {
35837
- npm: ["stripe"],
35838
- pypi: ["stripe"],
35839
- go: ["github.com/stripe/stripe-go"],
35840
- maven: ["com.stripe"],
35841
- rubygems: ["stripe"],
35842
- composer: ["stripe/stripe-php"],
35843
- nuget: ["Stripe.net"]
35844
- }
35845
- },
35846
- {
35847
- id: "datadog",
35848
- name: "Datadog",
35849
- category: "Observability",
35850
- hostSuffixes: ["datadoghq.com", "datadoghq.eu"],
35851
- apiBase: "https://api.datadoghq.com",
35852
- defaultDataClasses: ["telemetry", "logs", "metrics"],
35853
- sdks: {
35854
- npm: ["dd-trace", "@datadog/browser-logs"],
35855
- pypi: ["datadog", "ddtrace"],
35856
- go: ["github.com/DataDog/dd-trace-go"],
35857
- maven: ["com.datadoghq"],
35858
- rubygems: ["ddtrace", "dogapi"],
35859
- nuget: ["Datadog.Trace"]
35860
- }
35861
- },
35862
- {
35863
- id: "newrelic",
35864
- name: "New Relic",
35865
- category: "Observability",
35866
- hostSuffixes: ["newrelic.com", "nr-data.net"],
35867
- apiBase: "https://api.newrelic.com",
35868
- defaultDataClasses: ["telemetry", "logs", "metrics"],
35869
- sdks: {
35870
- npm: ["newrelic"],
35871
- pypi: ["newrelic"],
35872
- go: ["github.com/newrelic/go-agent"],
35873
- maven: ["com.newrelic.agent.java"],
35874
- rubygems: ["newrelic_rpm"],
35875
- nuget: ["NewRelic.Agent"]
35876
- }
35877
- },
35878
- {
35879
- id: "sentry",
35880
- name: "Sentry",
35881
- category: "Error tracking",
35882
- hostSuffixes: ["sentry.io"],
35883
- apiBase: "https://sentry.io",
35884
- defaultDataClasses: ["source", "telemetry"],
35885
- sdks: {
35886
- npm: ["@sentry/node", "@sentry/react", "@sentry/nextjs"],
35887
- pypi: ["sentry-sdk"],
35888
- go: ["github.com/getsentry/sentry-go"],
35889
- maven: ["io.sentry"],
35890
- rubygems: ["sentry-ruby"],
35891
- cargo: ["sentry"],
35892
- composer: ["sentry/sentry"],
35893
- nuget: ["Sentry"]
35894
- }
35895
- },
35896
- {
35897
- id: "openai",
35898
- name: "OpenAI",
35899
- category: "LLM provider",
35900
- hostSuffixes: ["openai.com"],
35901
- apiBase: "https://api.openai.com",
35902
- defaultDataClasses: ["pii", "source"],
35903
- sdks: {
35904
- npm: ["openai"],
35905
- pypi: ["openai"],
35906
- go: ["github.com/sashabaranov/go-openai"],
35907
- maven: ["com.openai"],
35908
- rubygems: ["ruby-openai"],
35909
- cargo: ["async-openai"],
35910
- composer: ["openai-php/client"],
35911
- nuget: ["OpenAI"]
35912
- }
35913
- },
35914
- {
35915
- id: "anthropic",
35916
- name: "Anthropic",
35917
- category: "LLM provider",
35918
- hostSuffixes: ["anthropic.com"],
35919
- apiBase: "https://api.anthropic.com",
35920
- defaultDataClasses: ["pii", "source"],
35921
- sdks: {
35922
- npm: ["@anthropic-ai/sdk"],
35923
- pypi: ["anthropic"],
35924
- go: ["github.com/anthropics/anthropic-sdk-go"],
35925
- nuget: ["Anthropic.SDK"]
35926
- }
35927
- },
35928
- {
35929
- id: "aws",
35930
- name: "Amazon Web Services",
35931
- category: "Cloud platform",
35932
- hostSuffixes: ["amazonaws.com"],
35933
- apiBase: "https://s3.amazonaws.com",
35934
- defaultDataClasses: ["secrets", "customer"],
35935
- sdks: {
35936
- npm: ["@aws-sdk/client-s3", "aws-sdk"],
35937
- pypi: ["boto3"],
35938
- go: ["github.com/aws/aws-sdk-go", "github.com/aws/aws-sdk-go-v2"],
35939
- maven: ["com.amazonaws", "software.amazon.awssdk"],
35940
- rubygems: ["aws-sdk-s3"],
35941
- cargo: ["aws-sdk-s3"],
35942
- nuget: ["AWSSDK.S3"]
35943
- }
35944
- },
35945
- {
35946
- id: "gcp",
35947
- name: "Google Cloud",
35948
- category: "Cloud platform",
35949
- hostSuffixes: ["googleapis.com"],
35950
- apiBase: "https://storage.googleapis.com",
35951
- defaultDataClasses: ["customer", "logs"],
35952
- sdks: {
35953
- npm: ["@google-cloud/storage"],
35954
- pypi: ["google-cloud-storage"],
35955
- go: ["cloud.google.com/go"],
35956
- maven: ["com.google.cloud"],
35957
- rubygems: ["google-cloud-storage"],
35958
- nuget: ["Google.Cloud.Storage.V1"]
35959
- }
35960
- },
35961
- {
35962
- id: "google-fonts",
35963
- name: "Google Fonts",
35964
- category: "CDN / edge",
35965
- hostSuffixes: ["fonts.googleapis.com", "fonts.gstatic.com"],
35966
- apiBase: "https://fonts.googleapis.com",
35967
- defaultDataClasses: ["none"],
35968
- sdks: {}
35969
- },
35970
- {
35971
- id: "azure",
35972
- name: "Microsoft Azure",
35973
- category: "Cloud platform",
35974
- hostSuffixes: ["azure.com", "windows.net"],
35975
- apiBase: "https://management.azure.com",
35976
- defaultDataClasses: ["customer", "logs"],
35977
- sdks: {
35978
- npm: ["@azure/storage-blob"],
35979
- pypi: ["azure-storage-blob"],
35980
- go: ["github.com/Azure/azure-sdk-for-go"],
35981
- maven: ["com.azure"],
35982
- rubygems: ["azure-storage-blob"],
35983
- nuget: ["Azure.Storage.Blobs"]
35984
- }
35985
- },
35986
- {
35987
- id: "slack",
35988
- name: "Slack",
35989
- category: "Notifications",
35990
- hostSuffixes: ["slack.com"],
35991
- apiBase: "https://slack.com/api",
35992
- defaultDataClasses: ["logs"],
35993
- sdks: {
35994
- npm: ["@slack/web-api"],
35995
- pypi: ["slack-sdk"],
35996
- go: ["github.com/slack-go/slack"],
35997
- maven: ["com.slack.api"],
35998
- rubygems: ["slack-ruby-client"],
35999
- composer: ["slack-php/slack-api"],
36000
- nuget: ["SlackNet"]
36001
- }
36002
- },
36003
- {
36004
- id: "segment",
36005
- name: "Segment",
36006
- category: "Analytics",
36007
- hostSuffixes: ["segment.io", "segment.com"],
36008
- apiBase: "https://api.segment.io",
36009
- defaultDataClasses: ["customer"],
36010
- sdks: {
36011
- npm: ["@segment/analytics-node", "analytics-node"],
36012
- pypi: ["segment-analytics-python"],
36013
- go: ["github.com/segmentio/analytics-go"],
36014
- maven: ["com.segment.analytics.java"],
36015
- rubygems: ["analytics-ruby"],
36016
- nuget: ["Analytics"]
36017
- }
36018
- },
36019
- {
36020
- id: "twilio",
36021
- name: "Twilio",
36022
- category: "Communications",
36023
- hostSuffixes: ["twilio.com"],
36024
- apiBase: "https://api.twilio.com",
36025
- defaultDataClasses: ["pii", "customer"],
36026
- sdks: {
36027
- npm: ["twilio"],
36028
- pypi: ["twilio"],
36029
- go: ["github.com/twilio/twilio-go"],
36030
- maven: ["com.twilio.sdk"],
36031
- rubygems: ["twilio-ruby"],
36032
- composer: ["twilio/sdk"],
36033
- nuget: ["Twilio"]
36034
- }
36035
- },
36036
- {
36037
- id: "sendgrid",
36038
- name: "SendGrid",
36039
- category: "Email",
36040
- hostSuffixes: ["sendgrid.com"],
36041
- apiBase: "https://api.sendgrid.com",
36042
- defaultDataClasses: ["pii"],
36043
- sdks: {
36044
- npm: ["@sendgrid/mail"],
36045
- pypi: ["sendgrid"],
36046
- go: ["github.com/sendgrid/sendgrid-go"],
36047
- maven: ["com.sendgrid"],
36048
- rubygems: ["sendgrid-ruby"],
36049
- composer: ["sendgrid/sendgrid"],
36050
- nuget: ["SendGrid"]
36051
- }
36052
- },
36053
- {
36054
- id: "mailgun",
36055
- name: "Mailgun",
36056
- category: "Email",
36057
- hostSuffixes: ["mailgun.net"],
36058
- apiBase: "https://api.mailgun.net",
36059
- defaultDataClasses: ["pii"],
36060
- sdks: {
36061
- npm: ["mailgun.js"],
36062
- pypi: ["mailgun"],
36063
- rubygems: ["mailgun-ruby"],
36064
- composer: ["mailgun/mailgun-php"],
36065
- nuget: ["Mailgun"]
36066
- }
36067
- },
36068
- {
36069
- id: "mixpanel",
36070
- name: "Mixpanel",
36071
- category: "Analytics",
36072
- hostSuffixes: ["mixpanel.com"],
36073
- apiBase: "https://api.mixpanel.com",
36074
- defaultDataClasses: ["customer", "telemetry"],
36075
- sdks: {
36076
- npm: ["mixpanel"],
36077
- pypi: ["mixpanel"],
36078
- rubygems: ["mixpanel-ruby"],
36079
- nuget: ["Mixpanel"]
36080
- }
36081
- },
36082
- {
36083
- id: "amplitude",
36084
- name: "Amplitude",
36085
- category: "Analytics",
36086
- hostSuffixes: ["amplitude.com"],
36087
- apiBase: "https://api2.amplitude.com",
36088
- defaultDataClasses: ["customer", "telemetry"],
36089
- sdks: {
36090
- npm: ["@amplitude/analytics-node"],
36091
- pypi: ["amplitude-analytics"],
36092
- nuget: ["Amplitude"]
36093
- }
36094
- },
36095
- {
36096
- id: "posthog",
36097
- name: "PostHog",
36098
- category: "Analytics",
36099
- hostSuffixes: ["posthog.com"],
36100
- apiBase: "https://us.i.posthog.com",
36101
- defaultDataClasses: ["customer", "telemetry"],
36102
- sdks: {
36103
- npm: ["posthog-node", "posthog-js"],
36104
- pypi: ["posthog"],
36105
- go: ["github.com/posthog/posthog-go"],
36106
- rubygems: ["posthog-ruby"],
36107
- composer: ["posthog/posthog-php"],
36108
- nuget: ["PostHog"]
36109
- }
36110
- },
36111
- {
36112
- id: "honeycomb",
36113
- name: "Honeycomb",
36114
- category: "Observability",
36115
- hostSuffixes: ["honeycomb.io"],
36116
- apiBase: "https://api.honeycomb.io",
36117
- defaultDataClasses: ["telemetry", "metrics"],
36118
- sdks: {
36119
- npm: ["libhoney"],
36120
- pypi: ["libhoney"],
36121
- go: ["github.com/honeycombio/libhoney-go"],
36122
- rubygems: ["libhoney"]
36123
- }
36124
- },
36125
- {
36126
- id: "grafana",
36127
- name: "Grafana Cloud",
36128
- category: "Observability",
36129
- hostSuffixes: ["grafana.net"],
36130
- apiBase: "https://grafana.net",
36131
- defaultDataClasses: ["logs", "metrics"],
36132
- sdks: {
36133
- npm: ["@grafana/faro-web-sdk"]
36134
- }
36135
- },
36136
- {
36137
- id: "splunk",
36138
- name: "Splunk",
36139
- category: "Observability",
36140
- hostSuffixes: ["splunkcloud.com", "splunk.com"],
36141
- apiBase: "https://http-inputs.splunkcloud.com",
36142
- defaultDataClasses: ["logs"],
36143
- sdks: {
36144
- npm: ["splunk-logging"],
36145
- pypi: ["splunk-sdk"],
36146
- maven: ["com.splunk"],
36147
- nuget: ["Splunk.Logging.Common"]
36148
- }
36149
- },
36150
- {
36151
- id: "pagerduty",
36152
- name: "PagerDuty",
36153
- category: "Incident response",
36154
- hostSuffixes: ["pagerduty.com"],
36155
- apiBase: "https://api.pagerduty.com",
36156
- defaultDataClasses: ["logs"],
36157
- sdks: {
36158
- npm: ["@pagerduty/pdjs"],
36159
- pypi: ["pdpyras"],
36160
- go: ["github.com/PagerDuty/go-pagerduty"],
36161
- rubygems: ["pagerduty"]
36162
- }
36163
- },
36164
- {
36165
- id: "github",
36166
- name: "GitHub",
36167
- category: "Developer platform",
36168
- hostSuffixes: ["github.com", "githubusercontent.com"],
36169
- apiBase: "https://api.github.com",
36170
- defaultDataClasses: ["source"],
36171
- sdks: {
36172
- npm: ["@octokit/rest", "octokit"],
36173
- pypi: ["pygithub"],
36174
- go: ["github.com/google/go-github"],
36175
- maven: ["org.kohsuke.github-api"],
36176
- rubygems: ["octokit"],
36177
- cargo: ["octocrab"],
36178
- composer: ["knplabs/github-api"],
36179
- nuget: ["Octokit"]
36180
- }
36181
- },
36182
- {
36183
- id: "gitlab",
36184
- name: "GitLab",
36185
- category: "Developer platform",
36186
- hostSuffixes: ["gitlab.com"],
36187
- apiBase: "https://gitlab.com/api",
36188
- defaultDataClasses: ["source"],
36189
- sdks: {
36190
- npm: ["@gitbeaker/rest"],
36191
- pypi: ["python-gitlab"],
36192
- go: ["gitlab.com/gitlab-org/api/client-go"],
36193
- rubygems: ["gitlab"],
36194
- nuget: ["GitLabApiClient"]
36195
- }
36196
- },
36197
- {
36198
- id: "auth0",
36199
- name: "Auth0",
36200
- category: "Identity",
36201
- hostSuffixes: ["auth0.com"],
36202
- apiBase: "https://login.auth0.com",
36203
- defaultDataClasses: ["pii"],
36204
- sdks: {
36205
- npm: ["auth0"],
36206
- pypi: ["auth0-python"],
36207
- go: ["github.com/auth0/go-auth0"],
36208
- maven: ["com.auth0"],
36209
- rubygems: ["auth0"],
36210
- composer: ["auth0/auth0-php"],
36211
- nuget: ["Auth0.ManagementApi"]
36212
- }
36213
- },
36214
- {
36215
- id: "okta",
36216
- name: "Okta",
36217
- category: "Identity",
36218
- hostSuffixes: ["okta.com", "oktapreview.com"],
36219
- apiBase: "https://login.okta.com",
36220
- defaultDataClasses: ["pii"],
36221
- sdks: {
36222
- npm: ["@okta/okta-sdk-nodejs"],
36223
- pypi: ["okta"],
36224
- go: ["github.com/okta/okta-sdk-golang"],
36225
- maven: ["com.okta.sdk"],
36226
- nuget: ["Okta.Sdk"]
36227
- }
36228
- },
36229
- {
36230
- id: "clerk",
36231
- name: "Clerk",
36232
- category: "Identity",
36233
- hostSuffixes: ["clerk.com", "clerk.dev"],
36234
- apiBase: "https://api.clerk.com",
36235
- defaultDataClasses: ["pii"],
36236
- sdks: {
36237
- npm: ["@clerk/backend", "@clerk/nextjs"],
36238
- pypi: ["clerk-backend-api"],
36239
- go: ["github.com/clerk/clerk-sdk-go"]
36240
- }
36241
- },
36242
- {
36243
- id: "supabase",
36244
- name: "Supabase",
36245
- category: "Backend platform",
36246
- hostSuffixes: ["supabase.co", "supabase.com"],
36247
- apiBase: "https://api.supabase.com",
36248
- defaultDataClasses: ["pii", "customer"],
36249
- sdks: {
36250
- npm: ["@supabase/supabase-js"],
36251
- pypi: ["supabase"],
36252
- cargo: ["postgrest"]
36253
- }
36254
- },
36255
- {
36256
- id: "firebase",
36257
- name: "Firebase",
36258
- category: "Backend platform",
36259
- hostSuffixes: ["firebaseio.com", "firebase.google.com"],
36260
- apiBase: "https://firebaseio.com",
36261
- defaultDataClasses: ["customer"],
36262
- sdks: {
36263
- npm: ["firebase", "firebase-admin"],
36264
- pypi: ["firebase-admin"],
36265
- go: ["firebase.google.com/go"],
36266
- maven: ["com.google.firebase"]
36267
- }
36268
- },
36269
- {
36270
- id: "mongodb-atlas",
36271
- name: "MongoDB Atlas",
36272
- category: "Database SaaS",
36273
- hostSuffixes: ["mongodb.net", "mongodb.com"],
36274
- apiBase: "https://cloud.mongodb.com",
36275
- defaultDataClasses: ["customer"],
36276
- sdks: {
36277
- npm: ["mongodb"],
36278
- pypi: ["pymongo"],
36279
- go: ["go.mongodb.org/mongo-driver"],
36280
- maven: ["org.mongodb"],
36281
- rubygems: ["mongo"],
36282
- cargo: ["mongodb"],
36283
- nuget: ["MongoDB.Driver"]
36284
- }
36285
- },
36286
- {
36287
- id: "planetscale",
36288
- name: "PlanetScale",
36289
- category: "Database SaaS",
36290
- hostSuffixes: ["psdb.cloud", "planetscale.com"],
36291
- apiBase: "https://api.planetscale.com",
36292
- defaultDataClasses: ["customer"],
36293
- sdks: {
36294
- npm: ["@planetscale/database"],
36295
- go: ["github.com/planetscale/planetscale-go"]
36296
- }
36297
- },
36298
- {
36299
- id: "algolia",
36300
- name: "Algolia",
36301
- category: "Search SaaS",
36302
- hostSuffixes: ["algolia.net", "algolianet.com"],
36303
- apiBase: "https://algolia.net",
36304
- defaultDataClasses: ["customer"],
36305
- sdks: {
36306
- npm: ["algoliasearch"],
36307
- pypi: ["algoliasearch"],
36308
- go: ["github.com/algolia/algoliasearch-client-go"],
36309
- maven: ["com.algolia"],
36310
- rubygems: ["algolia"],
36311
- composer: ["algolia/algoliasearch-client-php"],
36312
- nuget: ["Algolia.Search"]
36313
- }
36314
- },
36315
- {
36316
- id: "cloudflare",
36317
- name: "Cloudflare",
36318
- category: "CDN / edge",
36319
- hostSuffixes: ["cloudflare.com", "workers.dev"],
36320
- apiBase: "https://api.cloudflare.com",
36321
- defaultDataClasses: ["logs"],
36322
- sdks: {
36323
- npm: ["cloudflare"],
36324
- pypi: ["cloudflare"],
36325
- go: ["github.com/cloudflare/cloudflare-go"],
36326
- nuget: ["CloudFlare.Client"]
36327
- }
36328
- },
36329
- {
36330
- id: "huggingface",
36331
- name: "Hugging Face",
36332
- category: "LLM provider",
36333
- hostSuffixes: ["huggingface.co"],
36334
- apiBase: "https://api-inference.huggingface.co",
36335
- defaultDataClasses: ["source"],
36336
- sdks: {
36337
- npm: ["@huggingface/inference"],
36338
- pypi: ["huggingface-hub", "transformers"],
36339
- rubygems: ["hugging-face"]
36340
- }
36341
- },
36342
- {
36343
- id: "cohere",
36344
- name: "Cohere",
36345
- category: "LLM provider",
36346
- hostSuffixes: ["cohere.com", "cohere.ai"],
36347
- apiBase: "https://api.cohere.com",
36348
- defaultDataClasses: ["pii", "source"],
36349
- sdks: {
36350
- npm: ["cohere-ai"],
36351
- pypi: ["cohere"],
36352
- go: ["github.com/cohere-ai/cohere-go"]
36353
- }
36354
- },
36355
- {
36356
- id: "mistral",
36357
- name: "Mistral AI",
36358
- category: "LLM provider",
36359
- hostSuffixes: ["mistral.ai"],
36360
- apiBase: "https://api.mistral.ai",
36361
- defaultDataClasses: ["pii", "source"],
36362
- sdks: {
36363
- npm: ["@mistralai/mistralai"],
36364
- pypi: ["mistralai"],
36365
- go: ["github.com/gage-technologies/mistral-go"]
36366
- }
36367
- }
36368
- ];
36369
- var EXCLUDED_HOST_SUFFIXES = [
36370
- "localhost",
36371
- "test",
36372
- "example",
36373
- "invalid",
36374
- "example.com",
36375
- "example.org",
36376
- "example.net",
36377
- "w3.org",
36378
- "schemas.openxmlformats.org",
36379
- "schemas.microsoft.com",
36380
- "schemas.android.com",
36381
- "maven.apache.org"
36382
- ];
36383
- var EGRESS_VERSION_MATERIAL = `${EXTRACTOR_VERSION}
36384
- ${JSON.stringify(PROVIDER_REGISTRY)}
36385
- ${JSON.stringify(EXCLUDED_HOST_SUFFIXES)}`;
36386
-
36387
- // ../../packages/detections/src/egress/extract.ts
36388
- var SECRET_KEY_NAMES = "api[_-]?key|apikey|private[_-]?key|access[_-]?key|access[_-]?token|token|secret|credentials?|password|passwd|pwd|authorization|sig|signature|sas|assertion";
36389
- var AUTH_SCHEMES = "Bearer|Basic|Token|Digest|ApiKey|SSWS|AWS4-HMAC-SHA256";
36390
- var SECRET_VALUE = new RegExp(
36391
- `((?:${SECRET_KEY_NAMES})['"\`]?\\s*[:=]\\s*['"\`]?)(?!(?:${AUTH_SCHEMES})[\\s'"\`])[^\\s'"\`&]+`,
36392
- "gi"
36393
- );
36394
- var AUTH_SCHEME_VALUE = new RegExp(
36395
- `((?:${SECRET_KEY_NAMES})['"\`]?\\s*[:=]\\s*['"\`]?)(${AUTH_SCHEMES})\\s+[^\\s'"\`]+`,
36396
- "gi"
36397
- );
36398
- var WEBHOOK_SECRET_PATHS = [
36399
- { hosts: ["hooks.slack.com"], prefix: "/services/" },
36400
- {
36401
- hosts: ["discord.com", "discordapp.com", "ptb.discord.com", "canary.discord.com"],
36402
- prefix: "/api/webhooks/"
36403
- },
36404
- { hosts: ["hooks.zapier.com"], prefix: "/hooks/" },
36405
- { hosts: ["outlook.office.com", "outlook.office365.com"], prefix: "/webhook/" }
36406
- ];
36407
- function escapeRegExp(literal2) {
36408
- return literal2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36409
- }
36410
- var WEBHOOK_URL = new RegExp(
36411
- `(https?://(?:${WEBHOOK_SECRET_PATHS.flatMap(
36412
- (entry) => entry.hosts.map((host) => `${escapeRegExp(host)}${escapeRegExp(entry.prefix)}`)
36413
- ).join("|")}))[^\\s'"\`<>()[\\]{},;]+`,
36414
- "gi"
36415
- );
36416
-
36417
- // ../../packages/detections/src/escape-regexp.ts
36418
- function escapeRegExp2(value) {
36419
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36420
- }
36421
-
36422
- // ../../packages/detections/src/format-chars.ts
36423
- var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
36424
- var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
36425
-
36426
- // ../../packages/detections/src/regex-cache.ts
36427
- var singles = /* @__PURE__ */ new WeakMap();
36428
- var keywordLists = /* @__PURE__ */ new WeakMap();
36429
- var labelLists = /* @__PURE__ */ new WeakMap();
36430
- function listCache(kind) {
36431
- return kind === "keyword" ? keywordLists : labelLists;
36432
- }
36433
- function memoizedRegExp(owner, build) {
36434
- const cached2 = singles.get(owner);
36435
- if (cached2 !== void 0) {
36436
- cached2.lastIndex = 0;
36437
- return cached2;
36438
- }
36439
- const compiled = build();
36440
- singles.set(owner, compiled);
36441
- return compiled;
36442
- }
36443
- function memoizedRegExpList(kind, owner, build) {
36444
- const cache = listCache(kind);
36445
- const cached2 = cache.get(owner);
36446
- if (cached2 !== void 0) {
36447
- if (cached2.stateful) {
36448
- for (const re of cached2.entries) if (re !== void 0) re.lastIndex = 0;
36449
- }
36450
- return cached2.entries;
36451
- }
36452
- const entries = build();
36453
- cache.set(owner, {
36454
- entries,
36455
- stateful: entries.some((re) => re !== void 0 && (re.global || re.sticky))
36456
- });
36457
- return entries;
36458
- }
36459
-
36460
- // ../../packages/detections/src/matchers/limits.ts
36461
- var MAX_MATCHES_PER_RULE = 1e4;
36462
- var MAX_REGEX_INPUT_LENGTH = 2e5;
36463
-
36464
- // ../../packages/detections/src/matchers/keyword.ts
36465
- var KeywordMatcher2 = class {
36466
- match(text, rule) {
36467
- if (rule.matcher.type !== "keyword") return [];
36468
- const { keywords, caseSensitive } = rule.matcher;
36469
- const spans = [];
36470
- const compiled = memoizedRegExpList(
36471
- "keyword",
36472
- rule.matcher,
36473
- () => keywords.map((kw) => {
36474
- if (kw.length === 0) return void 0;
36475
- return new RegExp(escapeRegExp2(kw), caseSensitive ? "gu" : "giu");
36476
- })
36477
- );
36478
- for (const re of compiled) {
36479
- if (re === void 0) continue;
36480
- if (spans.length >= MAX_MATCHES_PER_RULE) break;
36481
- let m;
36482
- while ((m = re.exec(text)) !== null) {
36483
- spans.push({ start: m.index, end: m.index + m[0].length });
36484
- if (spans.length >= MAX_MATCHES_PER_RULE) break;
36485
- }
36486
- }
36487
- return spans;
36488
- }
36489
- };
36490
-
36491
- // ../../packages/detections/src/matchers/regex.ts
36492
- var RegexMatcher2 = class {
36493
- match(text, rule) {
36494
- if (rule.matcher.type !== "regex") return [];
36495
- const { pattern, flags, captureGroup } = rule.matcher;
36496
- const re = memoizedRegExp(
36497
- rule.matcher,
36498
- () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
36499
- );
36500
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36501
- const spans = [];
36502
- let m;
36503
- const maxIterations = scanText2.length + 1;
36504
- let iterations = 0;
36505
- while ((m = re.exec(scanText2)) !== null) {
36506
- if (++iterations > maxIterations) break;
36507
- const group = captureGroup != null ? m[captureGroup] : m[0];
36508
- if (m[0].length === 0) re.lastIndex++;
36509
- if (group && spans.length < MAX_MATCHES_PER_RULE) {
36510
- const groupIndices = captureGroup != null ? m.indices?.[captureGroup] : void 0;
36511
- const start = groupIndices ? groupIndices[0] : m.index;
36512
- spans.push({ start, end: start + group.length });
36513
- }
36514
- if (!flags.includes("g") || spans.length >= MAX_MATCHES_PER_RULE) break;
36515
- }
36516
- return spans;
36517
- }
36518
- };
36519
-
36520
- // ../../packages/detections/src/engine.ts
36521
- var keywordMatcher = new KeywordMatcher2();
36522
- var regexMatcher = new RegexMatcher2();
36523
-
36524
- // ../../packages/detections/src/posture/config-posture.ts
36525
- var RULE_VERSION = "1";
36526
- var KNOWN_TOOLS = /* @__PURE__ */ new Set([
36527
- "prettier",
36528
- "eslint",
36529
- "biome",
36530
- "black",
36531
- "ruff",
36532
- "gofmt",
36533
- "rustfmt",
36534
- "node",
36535
- "npx",
36536
- "npm",
36537
- "pnpm",
36538
- "yarn",
36539
- "make",
36540
- "git",
36541
- "jq",
36542
- "echo"
36543
- ]);
36544
- var EGRESS_RE = /\b(curl|wget|nc|ncat|netcat|ssh|scp|rsync)\b|https?:\/\//;
36545
- var MUTATION_RE = /(--write|--fix|\s-w\b|\s-i\b|(?<![\d&>])>\s?\S)/;
36546
- var CONFIG_POSTURE_RULES = [
36547
- {
36548
- ruleId: "hook-conflict",
36549
- version: RULE_VERSION,
36550
- name: "Overlapping hooks \u2014 run order is undefined",
36551
- category: "config",
36552
- severity: "medium",
36553
- definition: JSON.stringify({
36554
- kind: "hook-conflict",
36555
- mutation: MUTATION_RE.source,
36556
- note: "two hooks on the same event with overlapping matchers, both mutating the tool target"
36557
- })
36558
- },
36559
- {
36560
- ruleId: "hook-unknown",
36561
- version: RULE_VERSION,
36562
- name: "Unknown hook \u2014 not attributable to a plugin or known tool",
36563
- category: "config",
36564
- // medium, not high: with a deliberately tiny allowlist this v1 heuristic
36565
- // fires on ordinary interpreter hooks (python3 x.py) and compound commands
36566
- // (cd … && tool); 'high' is reserved for egress, which is genuinely
36567
- // dangerous. Revisit when the known-hooks registry replaces the allowlist.
36568
- severity: "medium",
36569
- definition: JSON.stringify({ kind: "hook-unknown", knownTools: [...KNOWN_TOOLS] })
36570
- },
36571
- {
36572
- ruleId: "hook-external-egress",
36573
- version: RULE_VERSION,
36574
- name: "Hook command can send data externally",
36575
- category: "config",
36576
- severity: "high",
36577
- definition: JSON.stringify({ kind: "hook-external-egress", pattern: EGRESS_RE.source })
36578
- }
36579
- ];
36580
-
36581
- // ../../packages/detections/src/posture/web-capture-posture.ts
36582
- var RULE_VERSION2 = "1";
36583
- var DRIFT_MIN_PARSE_FAILURES = 2;
36584
- var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
36585
- "blind",
36586
- "degraded"
36587
- ]);
36588
- var WEB_CAPTURE_DRIFT_RULE = {
36589
- ruleId: "web-capture-drift",
36590
- version: RULE_VERSION2,
36591
- name: "Web chat capture is not reading the site",
36592
- category: "config",
36593
- severity: "medium",
36594
- definition: JSON.stringify({
36595
- kind: "web-capture-drift",
36596
- states: [...WEB_CAPTURE_DRIFT_STATES],
36597
- minParseFailures: DRIFT_MIN_PARSE_FAILURES
36598
- })
36599
- };
36600
- var STATIC_COPY = {
36601
- active: { headline: "turns are being observed on this site" },
36602
- unreported: {
36603
- // Says "recently" rather than "yet": the store read is bounded to
36604
- // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
36605
- // reported for AND one whose last report has aged out. The two are the
36606
- // same fact to a reader — nobody has confirmed anything lately — and the
36607
- // copy may not claim the stronger of them.
36608
- headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
36609
- },
36610
- standby: {
36611
- headline: "this build declares no endpoints for the site, so nothing is observed yet"
36612
- },
36613
- unpatched: {
36614
- // Says what the flags say and no more. `patched` is false both for a tap
36615
- // that installed and hooked neither transport and for one that never ran
36616
- // at all — a page reports the same status either way, so the copy may not
36617
- // assert one of them.
36618
- headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
36619
- },
36620
- idle: { headline: "watching; no turn has been observed yet" },
36621
- blind: {
36622
- headline: "messages were sent in the page that the network capture never saw",
36623
- 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."
36624
- },
36625
- degraded: {
36626
- headline: "the site's payloads no longer carry the fields the extension reads",
36627
- 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."
36628
- }
36629
- };
36630
-
36631
- // ../../packages/detections/src/security/redos-probe.ts
36632
- var BUDGET_MS = 100;
36633
- var EXPONENTIAL_UNITS = [
36634
- "a",
36635
- "0",
36636
- " ",
36637
- "x",
36638
- "ab",
36639
- "a.",
36640
- "a-",
36641
- "a_",
36642
- "a@",
36643
- "a/",
36644
- "a:",
36645
- "a=",
36646
- "a;",
36647
- "aA0",
36648
- " "
36649
- ];
36650
- var EXPONENTIAL_PROBES = EXPONENTIAL_UNITS.flatMap(
36651
- (unit) => [23, 25].map((len) => unit.repeat(Math.ceil(len / unit.length)).slice(0, len) + "!")
36652
- );
36653
- var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map(
36654
- (unit) => unit.repeat(1e4).slice(0, 4e4) + "!"
36655
- );
36656
- var CPU_CORROBORATION_SHARE = 0.2;
36657
- var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36658
-
36659
- // ../../packages/plugin-sdk/src/repo.ts
36660
- import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36661
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36662
- var NO_ATTRIBUTION = Object.freeze({});
36663
-
36664
- // ../../packages/plugin-sdk/src/events.ts
36665
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36666
-
36667
- // ../../packages/plugin-sdk/src/isolated-scan.ts
36668
- import { existsSync as existsSync10 } from "fs";
36669
- import { fileURLToPath } from "url";
36670
- import { Worker } from "worker_threads";
36671
-
36672
- // ../../packages/plugin-sdk/src/hook-fail-opens.ts
36673
- import { readFileSync as readFileSync13 } from "fs";
36674
- import { join as join20 } from "path";
36675
-
36676
- // ../../packages/plugin-sdk/src/host-floor.ts
36677
- import { readFileSync as readFileSync15 } from "fs";
36678
- import { join as join22 } from "path";
36679
-
36680
- // ../../packages/plugin-sdk/src/model-governance.ts
36681
- import {
36682
- closeSync as closeSync2,
36683
- fstatSync,
36684
- mkdirSync as mkdirSync2,
36685
- openSync as openSync2,
36686
- readFileSync as readFileSync14,
36687
- readSync,
36688
- writeFileSync as writeFileSync5
36689
- } from "fs";
36690
- import { join as join21 } from "path";
36691
- var TAIL_BYTES = 256 * 1024;
36692
-
36693
- // ../../packages/plugin-sdk/src/host-floor.ts
36694
- var HOST_FEATURE = {
36695
- ModelSwitch: "model-switch",
36696
- VaultPointerDisplay: "vault-pointer-display"
36697
- };
36698
- var HOST_FLOORS = {
36699
- [HOST_FEATURE.ModelSwitch]: {
36700
- label: "model-switch protection",
36701
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
36702
- since: "2.1.251"
36703
- },
36704
- [HOST_FEATURE.VaultPointerDisplay]: {
36705
- label: "vault pointer display",
36706
- hookEvents: ["MessageDisplay"],
36707
- since: "2.1.152"
36708
- }
36709
- };
36710
- var ANTIGRAVITY_HOST_FEATURE = {
36711
- EndOfTurnCapture: "end-of-turn-capture"
36712
- };
36713
- var ANTIGRAVITY_HOST_FLOORS = {
36714
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
36715
- label: "end-of-turn history capture",
36716
- hookEvents: ["Stop"],
36717
- since: "1.1.10"
36718
- }
36719
- };
36720
-
36721
- // ../../packages/plugin-sdk/src/ignore-layers.ts
36722
- var import_ignore = __toESM(require_ignore(), 1);
36723
- import { readFileSync as readFileSync16 } from "fs";
36724
- import { join as join23 } from "path";
36725
-
36726
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
36727
- import { arch, hostname as hostname4, platform, release } from "os";
36728
-
36729
- // ../../packages/plugin-sdk/src/nudge.ts
36730
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
36731
- import { join as join24 } from "path";
36732
-
36733
- // ../../packages/plugin-sdk/src/paths.ts
36734
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
36735
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36736
-
36737
- // ../../packages/plugin-sdk/src/policy-resolver.ts
36738
- import { randomUUID as randomUUID14 } from "crypto";
36739
-
36740
- // ../../packages/plugin-sdk/src/project-files.ts
36741
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36742
- import { basename as basename5, join as join25 } from "path";
36743
-
36744
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36745
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
36746
- if (typeof v === "string" && v.trim() === "") return void 0;
36747
- return v;
36748
- }, external_exports.string().optional()).catch(void 0);
36749
- var optionalFlag = external_exports.preprocess((v) => {
36750
- if (typeof v !== "string") return false;
36751
- const normalized = v.trim().toLowerCase();
36752
- return normalized !== "" && normalized !== "0" && normalized !== "false";
36753
- }, external_exports.boolean()).catch(false);
36754
- var antigravityProviderEnvShape = {
36755
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
36756
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
36757
- };
36758
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
36759
-
36760
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
36761
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
36762
- if (typeof v === "string" && v.trim() === "") return void 0;
36763
- return v;
36764
- }, external_exports.string().optional()).catch(void 0);
36765
- var codexProviderEnvShape = {
36766
- OPENAI_BASE_URL: optionalBaseUrl3
36767
- };
36768
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
36769
-
36770
- // ../../packages/plugin-sdk/src/runtime.ts
36771
- import { randomUUID as randomUUID15 } from "crypto";
36772
-
36773
- // ../../packages/plugin-sdk/src/scope-key.ts
36774
- import { existsSync as existsSync12 } from "fs";
36775
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
36776
-
36777
- // ../../packages/plugin-sdk/src/suppressions.ts
36778
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36779
-
36780
- // ../../packages/plugin-sdk/src/throttle.ts
36781
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36782
- import { join as join27 } from "path";
35374
+ import { join as join18 } from "path";
36783
35375
 
36784
35376
  // ../../packages/plugin-runtime/src/attached/scope-strip.ts
36785
35377
  function withoutScopeKey(event) {
@@ -36793,9 +35385,19 @@ function withoutScopeKey(event) {
36793
35385
  return bare;
36794
35386
  }
36795
35387
 
35388
+ // ../../packages/plugin-runtime/src/attached/scoped-repo.ts
35389
+ function withScopedRepo(event, scopeKey) {
35390
+ const repo = scopeKey.split("/").filter((segment) => segment !== "").pop();
35391
+ if (repo !== void 0) return { ...event, metadata: { ...event.metadata, repo } };
35392
+ if (event.metadata?.repo === void 0) return event;
35393
+ const metadata = { ...event.metadata };
35394
+ delete metadata.repo;
35395
+ return { ...event, metadata };
35396
+ }
35397
+
36796
35398
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36797
35399
  import { createHash as createHash6 } from "crypto";
36798
- import { hostname as hostname5 } from "os";
35400
+ import { hostname as hostname4 } from "os";
36799
35401
 
36800
35402
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
36801
35403
  function rebuildCapture(row) {
@@ -36860,6 +35462,13 @@ function rebuildCapture(row) {
36860
35462
  ...withField(
36861
35463
  "redactDegradedTo",
36862
35464
  keep(stringOrUndefined(attributes.redact_degraded_to), REDACT_DEGRADED_TO)
35465
+ ),
35466
+ // Carried, for the same reason again: a refused row's content is '' and it
35467
+ // has no findings, so without the marker the deployment reads a refusal as
35468
+ // a clean empty capture. Parsed against the wire for the same reason too.
35469
+ ...withField(
35470
+ "scanIncomplete",
35471
+ keep(stringOrUndefined(attributes.scan_incomplete), SCAN_INCOMPLETE)
36863
35472
  )
36864
35473
  // inspectionMs is DELIBERATELY not carried. It measures latency a live host
36865
35474
  // session actually waited on, and a row being drained hours later is not
@@ -36890,6 +35499,7 @@ var CORRELATION_ID = EventMetadata.shape.correlationId;
36890
35499
  var TRACE_ID = EventMetadata.shape.traceId;
36891
35500
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
36892
35501
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
35502
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
36893
35503
  function isoOrUndefined(epochMs) {
36894
35504
  if (!Number.isFinite(epochMs)) return void 0;
36895
35505
  const iso = new Date(epochMs);
@@ -37025,6 +35635,11 @@ async function runHistorySync(deps) {
37025
35635
  if (!Number.isFinite(consentAcknowledgedAtMs)) return didNotRun("attachment-unreadable");
37026
35636
  const state = readControlPlaneCredentialFile(deps.settingsDir, connection);
37027
35637
  if (!state.usable) return didNotRun("credential-unusable");
35638
+ const mode = attachmentModeOf(state.credential);
35639
+ const scopeOf = (live) => resolveScope({ mode, scope: live.attachmentScope, endpoint: connection.endpoint });
35640
+ const passScope = scopeOf(settings);
35641
+ const passFilter = scopeFilterOf(passScope);
35642
+ const liveScope = () => mode === "machine" ? passScope : scopeOf(readWorkspaceSettings(deps.base));
37028
35643
  const nowMs = now();
37029
35644
  if (isForwardPaused(readForwardHealth(deps.dataDir, nowMs), nowMs)) {
37030
35645
  return didNotRun("breaker-open");
@@ -37037,7 +35652,7 @@ async function runHistorySync(deps) {
37037
35652
  const recorded = ledger.deployment();
37038
35653
  let backlogBefore;
37039
35654
  if (recorded.fingerprint !== fingerprint) {
37040
- ledger.rearmFor(fingerprint, attachedAtMs, consentAcknowledgedAtMs);
35655
+ ledger.rearmFor(fingerprint, attachedAtMs, consentAcknowledgedAtMs, passFilter);
37041
35656
  backlogBefore = attachedAtMs;
37042
35657
  } else if (recorded.backlogBefore === void 0) {
37043
35658
  ledger.freezeBoundary(attachedAtMs);
@@ -37046,7 +35661,7 @@ async function runHistorySync(deps) {
37046
35661
  backlogBefore = recorded.backlogBefore;
37047
35662
  }
37048
35663
  const pid = process.pid;
37049
- if (!ledger.claim(pid, hostname5(), now(), HISTORY_SYNC_LEASE_STALE_MS)) {
35664
+ if (!ledger.claim(pid, hostname4(), now(), HISTORY_SYNC_LEASE_STALE_MS)) {
37050
35665
  return didNotRun("already-running");
37051
35666
  }
37052
35667
  const client = deps.sendBatch !== void 0 && deps.sendCaptures !== void 0 && deps.sendOne !== void 0 ? void 0 : createRemoteClient({
@@ -37079,7 +35694,8 @@ async function runHistorySync(deps) {
37079
35694
  random,
37080
35695
  budgetMs,
37081
35696
  pid,
37082
- backlogBefore
35697
+ backlogBefore,
35698
+ liveScope
37083
35699
  });
37084
35700
  } finally {
37085
35701
  ledger.release(pid);
@@ -37107,13 +35723,23 @@ async function drain(d) {
37107
35723
  d.ledger.heartbeat(d.pid, at);
37108
35724
  lastHeartbeat = at;
37109
35725
  };
35726
+ const capturesOwed = (filter2) => d.ledger.pendingCaptureRows(1, d.now() - CAPTURE_GRACE_MS, filter2).length > 0;
37110
35727
  const drainStructural = async (until) => {
37111
35728
  let stopped = "ok";
37112
35729
  outer: while (d.now() < until) {
37113
- const sessions = d.ledger.pendingSessions(SESSION_PAGE, d.backlogBefore);
35730
+ const sessions = d.ledger.pendingSessions(
35731
+ SESSION_PAGE,
35732
+ d.backlogBefore,
35733
+ scopeFilterOf(d.liveScope())
35734
+ );
37114
35735
  if (sessions.length === 0) break;
37115
35736
  for (const sessionId of sessions) {
37116
- const rows = d.ledger.pendingRows(sessionId, ROW_PAGE, d.backlogBefore);
35737
+ const rows = d.ledger.pendingRows(
35738
+ sessionId,
35739
+ ROW_PAGE,
35740
+ d.backlogBefore,
35741
+ scopeFilterOf(d.liveScope())
35742
+ );
37117
35743
  if (rows.length === 0) continue;
37118
35744
  const ready = [];
37119
35745
  for (const row of rows) {
@@ -37160,10 +35786,13 @@ async function drain(d) {
37160
35786
  skipped += captures.skipped;
37161
35787
  if (captures.stopped !== void 0) outcome = captures.stopped;
37162
35788
  }
37163
- if (outcome === "ok" && d.now() < deadline && d.ledger.pendingCaptureRows(1, d.now() - CAPTURE_GRACE_MS).length === 0) {
35789
+ if (outcome === "ok" && d.now() < deadline && !capturesOwed(scopeFilterOf(d.liveScope()))) {
37164
35790
  outcome = await drainStructural(deadline);
37165
35791
  }
37166
- if (outcome === "ok" && d.now() >= deadline && d.ledger.counts(d.backlogBefore).pending > 0) {
35792
+ const filter = scopeFilterOf(d.liveScope());
35793
+ const counts = d.ledger.counts(d.backlogBefore, filter);
35794
+ const countsScope = filter === void 0 ? "machine" : "scoped";
35795
+ if (outcome === "ok" && d.now() >= deadline && counts.pending > 0) {
37167
35796
  outcome = "interrupted";
37168
35797
  }
37169
35798
  return {
@@ -37172,28 +35801,60 @@ async function drain(d) {
37172
35801
  sent,
37173
35802
  skipped,
37174
35803
  // LIMIT 1 — this asks "is anything owed", never "how much", so it must not
37175
- // pay for a count over the capture grain on every pass.
37176
- capturesPending: d.ledger.pendingCaptureRows(1, d.now() - CAPTURE_GRACE_MS).length > 0,
37177
- counts: d.ledger.counts(d.backlogBefore),
35804
+ // pay for a count over the capture grain on every pass. Through the same
35805
+ // filter as `counts`, so a marker on a capture outside the scope does not
35806
+ // hold `capturesPending` true, and both halves of `done` describe one scope.
35807
+ capturesPending: capturesOwed(filter),
35808
+ counts,
35809
+ countsScope,
37178
35810
  atMs: d.now()
37179
35811
  };
37180
35812
  }
35813
+ function scopeKeyOfRow(row) {
35814
+ const raw = row.attributes;
35815
+ if (typeof raw !== "string") return void 0;
35816
+ try {
35817
+ const bag = JSON.parse(raw);
35818
+ if (typeof bag !== "object" || bag === null || Array.isArray(bag)) return void 0;
35819
+ const key = bag.scope_key;
35820
+ return typeof key === "string" ? key : void 0;
35821
+ } catch {
35822
+ return void 0;
35823
+ }
35824
+ }
37181
35825
  async function drainCaptures(d, deadline, beat) {
37182
35826
  let sent = 0;
37183
35827
  let skipped = 0;
37184
35828
  for (; ; ) {
37185
35829
  if (d.now() >= deadline) return { sent, skipped, stopped: "interrupted" };
37186
- const rows = d.ledger.pendingCaptureRows(CAPTURE_BATCH_SIZE, d.now() - CAPTURE_GRACE_MS);
35830
+ const scope = d.liveScope();
35831
+ const rows = d.ledger.pendingCaptureRows(
35832
+ CAPTURE_BATCH_SIZE,
35833
+ d.now() - CAPTURE_GRACE_MS,
35834
+ scopeFilterOf(scope)
35835
+ );
37187
35836
  if (rows.length === 0) return { sent, skipped };
35837
+ const inScopeRows = [];
35838
+ for (const row of rows) {
35839
+ if (scope.mode === "machine") {
35840
+ inScopeRows.push({ row });
35841
+ continue;
35842
+ }
35843
+ const key = scopeKeyOfRow(row);
35844
+ if (key !== void 0 && scopeVerdict(scope, key) === "forward") {
35845
+ inScopeRows.push({ row, key });
35846
+ }
35847
+ }
35848
+ if (inScopeRows.length === 0) return { sent, skipped };
37188
35849
  const ready = [];
37189
35850
  const unbuildable = [];
37190
- for (const row of rows) {
35851
+ for (const { row, key } of inScopeRows) {
37191
35852
  const event = rebuildCapture(row);
37192
35853
  if (event === void 0) {
37193
35854
  unbuildable.push(row.id);
37194
35855
  continue;
37195
35856
  }
37196
- ready.push({ id: row.id, event });
35857
+ ready.push({ id: row.id, event: key === void 0 ? event : withScopedRepo(event, key) });
37197
35858
  }
37198
35859
  if (unbuildable.length > 0) {
37199
35860
  d.ledger.markSkipped(unbuildable, d.now());
@@ -37444,16 +36105,25 @@ async function runHistorySyncPass(base = defaultDataDir(), seams = {}) {
37444
36105
  // genuinely finishes. The capture lane does not: its subject grows with
37445
36106
  // every live session that fails to forward, so `phase` can go back to
37446
36107
  // 'filling' after reading 'complete'. This keeps its original meaning
37447
- // either way — the first moment this machine owed the deployment nothing —
37448
- // which is why it is pinned rather than recomputed.
36108
+ // either way — the first moment this machine owed the deployment nothing
36109
+ // its scope would send — which is why it is pinned rather than recomputed.
37449
36110
  // WRITTEN ONCE, on the false→true transition, and never cleared. Under v1
37450
- // this was monotone because the structural lane only ever drained; the
37451
- // capture lane is what makes `done` flap, and clearing on every flap would
37452
- // erase the pin and re-stamp it on the next catch-up — so a consumer
37453
- // reading "when this machine first caught up" would get the most recent
37454
- // one instead. Carrying the previous value through the false case is what
37455
- // keeps the original meaning.
37456
- completedAtMs: previous?.completedAtMs ?? (done ? result.atMs : null)
36111
+ // this was monotone because the structural lane only ever drained. The
36112
+ // capture lane makes `done` flap, and on a SCOPED attachment so does an
36113
+ // enroll: the counts cover only that scope's rows, so enrolling a
36114
+ // repository with unsent history can turn `done` false again, and an
36115
+ // unenroll can turn it true. Clearing on every flap would erase the pin and
36116
+ // re-stamp it on the next catch-up — so a consumer reading "when this
36117
+ // machine first caught up" would get the most recent one instead. Carrying
36118
+ // the previous value through the false case is what keeps the original
36119
+ // meaning.
36120
+ completedAtMs: previous?.completedAtMs ?? (done ? result.atMs : null),
36121
+ // Which population the totals above describe. Every pass from this build
36122
+ // on writes it, taken from THIS pass's own counts and never carried over
36123
+ // from the file read at the start of the pass, so `aka status` can tell a
36124
+ // scoped pass's numbers from those a build before it counted for
36125
+ // everything recorded on this machine, whose file has no such field.
36126
+ countsScope: result.countsScope
37457
36127
  });
37458
36128
  return result.outcome;
37459
36129
  } catch {
@@ -37463,21 +36133,21 @@ async function runHistorySyncPass(base = defaultDataDir(), seams = {}) {
37463
36133
 
37464
36134
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37465
36135
  import { spawn } from "child_process";
37466
- import { fileURLToPath as fileURLToPath2 } from "url";
36136
+ import { fileURLToPath } from "url";
37467
36137
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
37468
36138
 
37469
36139
  // ../../packages/plugin-runtime/src/attached/install-record.ts
37470
36140
  import { readFile as readFile2, stat } from "fs/promises";
37471
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
36141
+ import { basename as basename2, dirname as dirname4, join as join19, resolve as resolve2 } from "path";
37472
36142
 
37473
36143
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37474
- import { readFileSync as readFileSync18 } from "fs";
36144
+ import { readFileSync as readFileSync12 } from "fs";
37475
36145
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
37476
36146
 
37477
36147
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37478
- import { randomUUID as randomUUID17 } from "crypto";
36148
+ import { randomUUID as randomUUID14 } from "crypto";
37479
36149
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
37480
- import { join as join30 } from "path";
36150
+ import { join as join20 } from "path";
37481
36151
 
37482
36152
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37483
36153
  import { rename as rename2 } from "fs/promises";
@@ -37486,8 +36156,8 @@ var TIMED_RETRIES = 4;
37486
36156
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
37487
36157
 
37488
36158
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
37489
- import { readFileSync as readFileSync19 } from "fs";
37490
- import { join as join31 } from "path";
36159
+ import { readFileSync as readFileSync13 } from "fs";
36160
+ import { join as join21 } from "path";
37491
36161
  var OUTCOME_KEYS = {
37492
36162
  ok: true,
37493
36163
  unauthorized: true,
@@ -37504,17 +36174,17 @@ var OUTCOMES2 = new Set(Object.keys(OUTCOME_KEYS));
37504
36174
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
37505
36175
 
37506
36176
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
37507
- import { statSync as statSync9 } from "fs";
37508
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
36177
+ import { statSync as statSync6 } from "fs";
36178
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
37509
36179
 
37510
36180
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37511
- import { randomUUID as randomUUID18 } from "crypto";
36181
+ import { randomUUID as randomUUID15 } from "crypto";
37512
36182
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37513
- import { join as join32 } from "path";
36183
+ import { join as join22 } from "path";
37514
36184
 
37515
36185
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37516
- import { readFileSync as readFileSync20 } from "fs";
37517
- import { join as join33 } from "path";
36186
+ import { readFileSync as readFileSync14 } from "fs";
36187
+ import { join as join23 } from "path";
37518
36188
 
37519
36189
  // ../../packages/plugin-runtime/src/attached/status.ts
37520
36190
  var REFUSAL_LINES = {
@@ -37532,7 +36202,7 @@ var OUTCOME_LINES = {
37532
36202
 
37533
36203
  // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
37534
36204
  import { spawn as spawn2 } from "child_process";
37535
- import { fileURLToPath as fileURLToPath3 } from "url";
36205
+ import { fileURLToPath as fileURLToPath2 } from "url";
37536
36206
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37537
36207
 
37538
36208
  // ../../packages/plugin-runtime/src/content-retention-pass.ts
@@ -37540,14 +36210,14 @@ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
37540
36210
 
37541
36211
  // ../../packages/plugin-runtime/src/content-retention-trigger.ts
37542
36212
  import { spawn as spawn3 } from "child_process";
37543
- import { fileURLToPath as fileURLToPath4 } from "url";
36213
+ import { fileURLToPath as fileURLToPath3 } from "url";
37544
36214
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
37545
36215
 
37546
36216
  // ../../packages/plugin-runtime/src/attached/factory.ts
37547
- import { hostname as hostname6 } from "os";
36217
+ import { hostname as hostname5 } from "os";
37548
36218
 
37549
36219
  // ../../packages/plugin-runtime/src/handle-session-start.ts
37550
- import { randomUUID as randomUUID19 } from "crypto";
36220
+ import { randomUUID as randomUUID16 } from "crypto";
37551
36221
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
37552
36222
 
37553
36223
  // src/history-sync.ts