@akasecurity/ai-tc-codex 0.9.16 → 0.9.17-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }
@@ -22686,8 +21851,9 @@ var SessionTokenReport = external_exports.object({
22686
21851
  totalTokens: external_exports.number().int().nonnegative(),
22687
21852
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22688
21853
  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
21854
+ // True whenever any call priced to null (an unknown provider/model, or a call
21855
+ // over a long-context threshold whose rate is unpublished), so the total
21856
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22691
21857
  // precise figure rather than silently dropping the unpriced calls.
22692
21858
  costIsPartial: external_exports.boolean()
22693
21859
  });
@@ -23434,6 +22600,9 @@ var AttachedCredentialAny = external_exports.discriminatedUnion("specVersion", [
23434
22600
  AttachedCredentialV1,
23435
22601
  AttachedCredentialV2
23436
22602
  ]);
22603
+ function attachmentModeOf(credential) {
22604
+ return credential.specVersion === ATTACHED_CREDENTIAL_SPEC_VERSION ? "machine" : "scoped";
22605
+ }
23437
22606
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
23438
22607
  function unsafeEndpointReason(endpoint) {
23439
22608
  let parsed2;
@@ -23561,7 +22730,15 @@ var StorePostureSnapshot = external_exports.object({
23561
22730
  policyCounts: StorePosturePolicyCounts,
23562
22731
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23563
22732
  // getting its 200 without a payload change.
23564
- plugin: StorePosturePlugin.optional()
22733
+ plugin: StorePosturePlugin.optional(),
22734
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22735
+ // machine attachment omits it, so its body is byte for byte the one it
22736
+ // sent before this member existed. Absent therefore means machine-wide OR
22737
+ // a reporter older than this member, never "scoped". Both values parse, so
22738
+ // a sender that one day spells `machine` breaks no receiver; any other
22739
+ // value fails the whole snapshot, which is why the reporter sends a
22740
+ // constant and never the raw mode.
22741
+ attachmentMode: AttachmentMode.optional()
23565
22742
  }).meta({ id: "StorePostureSnapshot" });
23566
22743
  var CAPTURE_VERSION_PREFIX = "capture/";
23567
22744
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -24008,7 +23185,7 @@ var Rule = external_exports.strictObject({
24008
23185
  postValidators: external_exports.array(PostValidatorRef).optional(),
24009
23186
  requiresNearby: RequiresNearby.optional(),
24010
23187
  examples: external_exports.array(external_exports.string()).optional(),
24011
- // Whether the matched text is itself sensitive. Absent means 'value'.
23188
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24012
23189
  evidence: RuleEvidence.optional()
24013
23190
  }).meta({ id: "Rule" });
24014
23191
  var Author = external_exports.object({
@@ -24100,7 +23277,13 @@ var DetectionRule = external_exports.object({
24100
23277
  // Representative matching strings the rule author shipped with the rule. The
24101
23278
  // cheapest honest answer to "show me what this rule catches" — every bundled
24102
23279
  // rule has them, and they are already in the stored snapshot.
24103
- examples: external_exports.array(external_exports.string()).optional()
23280
+ examples: external_exports.array(external_exports.string()).optional(),
23281
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23282
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23283
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23284
+ // in a value category (secret/pii/financial/phi) is always 'value',
23285
+ // whatever it declares.
23286
+ evidence: RuleEvidence.optional()
24104
23287
  }).meta({ id: "DetectionRule" });
24105
23288
  var DetectionUpdate = external_exports.object({
24106
23289
  available: external_exports.boolean(),
@@ -24168,8 +23351,10 @@ var ImportDetectionRequest = external_exports.object({
24168
23351
  }).meta({ id: "ImportDetectionRequest" });
24169
23352
 
24170
23353
  // ../../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 {};
23354
+ function optional2(key, raw, parse4) {
23355
+ if (raw === void 0) return {};
23356
+ const parsed2 = parse4(raw);
23357
+ if (!parsed2.success || parsed2.data === void 0) return {};
24173
23358
  return { [key]: parsed2.data };
24174
23359
  }
24175
23360
  function isStringArray(value) {
@@ -24204,10 +23389,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24204
23389
  category: r.category,
24205
23390
  severity: r.severity,
24206
23391
  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.
23392
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23393
+ // decides whether this rule fires. Carried so a consumer re-running the
23394
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23395
+ // than a matcher stripped of its guards — half the bundled catalog
23396
+ // carries at least one of these. `examples` and `evidence` describe the
23397
+ // rule and never gate a match.
24211
23398
  //
24212
23399
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24213
23400
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24217,18 +23404,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24217
23404
  // test should stay exactly what it was, namely a renderable matcher. A
24218
23405
  // field that fails validation is omitted, which reads as "not set" and is
24219
23406
  // the same thing the consumer saw before this change.
24220
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23407
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24221
23408
  ...optional2(
24222
23409
  "postValidators",
24223
- PostValidatorRef.array().safeParse(r.postValidators),
24224
- r.postValidators
23410
+ r.postValidators,
23411
+ (v) => PostValidatorRef.array().safeParse(v)
24225
23412
  ),
24226
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23413
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24227
23414
  ...optional2(
24228
23415
  "examples",
24229
- { success: isStringArray(r.examples), data: r.examples },
24230
- r.examples
24231
- )
23416
+ r.examples,
23417
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23418
+ ),
23419
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24232
23420
  }
24233
23421
  ];
24234
23422
  });
@@ -24921,11 +24109,14 @@ var PolicyBundle = external_exports.object({
24921
24109
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24922
24110
  // Model ids (the raw `model` string a harness reports, e.g.
24923
24111
  // `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.
24112
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24113
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24114
+ // wherever the organization governs the event: everywhere on a
24115
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24116
+ // one (the plugin runtime's `governanceApplies`).
24117
+ // Optional so an older backend — and an older on-disk cache — still
24118
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24119
+ // predates this field and the safe direction to default.
24929
24120
  //
24930
24121
  // Ids, not display names: the governance decision is keyed on the exact
24931
24122
  // string the harness reports (`model_status_override.versionId` in the
@@ -25302,9 +24493,36 @@ var AttachmentScopeEntry = external_exports.object({
25302
24493
  });
25303
24494
  var AttachmentScope = external_exports.object({
25304
24495
  endpoint: external_exports.string().min(1),
24496
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24497
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25305
24498
  entries: external_exports.array(AttachmentScopeEntry)
25306
24499
  });
25307
24500
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
24501
+ function parseAttachmentScope(raw) {
24502
+ try {
24503
+ const envelope = AttachmentScopeEnvelope.safeParse(raw);
24504
+ if (!envelope.success) return void 0;
24505
+ const entries = [];
24506
+ for (const candidate of envelope.data.entries) {
24507
+ const entry = AttachmentScopeEntry.safeParse(candidate);
24508
+ if (entry.success) entries.push(entry.data);
24509
+ }
24510
+ const { endpoint, tenantName, userEmail } = envelope.data;
24511
+ return {
24512
+ endpoint,
24513
+ ...tenantName === void 0 ? {} : { tenantName },
24514
+ ...userEmail === void 0 ? {} : { userEmail },
24515
+ entries
24516
+ };
24517
+ } catch {
24518
+ return void 0;
24519
+ }
24520
+ }
24521
+ function scopeForEndpoint(raw, endpoint) {
24522
+ if (endpoint === void 0) return void 0;
24523
+ const scope = parseAttachmentScope(raw);
24524
+ return scope?.endpoint === endpoint ? scope : void 0;
24525
+ }
25308
24526
  var WebChatCaptureConsent = external_exports.object({
25309
24527
  acknowledgedAt: external_exports.iso.datetime(),
25310
24528
  version: external_exports.number().int().positive()
@@ -25415,6 +24633,40 @@ function defaultWorkspaceSettings() {
25415
24633
  function isAttached(settings) {
25416
24634
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
25417
24635
  }
24636
+ function resolveScope(input2, extraEntries) {
24637
+ try {
24638
+ if (input2.mode === "machine") return { mode: "machine", keys: /* @__PURE__ */ new Set() };
24639
+ const keys = /* @__PURE__ */ new Set();
24640
+ const stored = scopeForEndpoint(input2.scope, input2.endpoint);
24641
+ for (const entry of stored?.entries ?? []) {
24642
+ keys.add(entry.identity);
24643
+ }
24644
+ for (const candidate of extraEntries ?? []) {
24645
+ const entry = AttachmentScopeEntry.safeParse(candidate);
24646
+ if (entry.success) keys.add(entry.data.identity);
24647
+ }
24648
+ return { mode: "scoped", keys };
24649
+ } catch {
24650
+ return { mode: "scoped", keys: /* @__PURE__ */ new Set() };
24651
+ }
24652
+ }
24653
+ function scopeVerdict(resolved, key) {
24654
+ try {
24655
+ if (resolved.mode === "machine") return "forward";
24656
+ if (typeof key !== "string" || key === "") return "local";
24657
+ return resolved.keys.has(key) ? "forward" : "local";
24658
+ } catch {
24659
+ return "local";
24660
+ }
24661
+ }
24662
+ function scopeFilterOf(resolved) {
24663
+ try {
24664
+ if (resolved.mode === "machine") return void 0;
24665
+ return [...resolved.keys].sort();
24666
+ } catch {
24667
+ return [];
24668
+ }
24669
+ }
25418
24670
  function toInventoryRow(input2, id, now) {
25419
24671
  return {
25420
24672
  id,
@@ -25634,6 +24886,27 @@ var ManagedSettings = external_exports.object({
25634
24886
  };
25635
24887
  }).meta({ id: "ManagedSettings" });
25636
24888
 
24889
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24890
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24891
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24892
+ var ModPolicySnapshot = external_exports.object({
24893
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24894
+ generatedAt: external_exports.iso.datetime(),
24895
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24896
+ // user's enabled installed packs (user-modified and custom packs included).
24897
+ // Absent means the store holds no authoritative snapshot, and the reader
24898
+ // scans with the packs it ships — the hook's own fallback.
24899
+ rules: external_exports.array(Rule).optional(),
24900
+ // Rule-targeted actions (first enabled policy per rule wins).
24901
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
24902
+ // The resolved action per detection category.
24903
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
24904
+ // Rules with an active exception grant. Honouring a grant means matching a
24905
+ // keyed fingerprint of the value and consuming a use, which only the hook can
24906
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
24907
+ exceptionRuleIds: external_exports.array(external_exports.string())
24908
+ }).meta({ id: "ModPolicySnapshot" });
24909
+
25637
24910
  // ../../packages/schema/src/zod/project-files.ts
25638
24911
  var ProjectFileInput = external_exports.object({
25639
24912
  path: external_exports.string().min(1),
@@ -25954,7 +25227,16 @@ var AttachInput = external_exports.object({
25954
25227
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
25955
25228
  // renders a longer one usefully.
25956
25229
  label: printable(200).optional(),
25957
- accessKey: external_exports.string()
25230
+ accessKey: external_exports.string(),
25231
+ // How much of this machine the attachment is for: everything, or only the
25232
+ // repositories its user enrolls. Optional, so an input without it still
25233
+ // parses; what an absent mode means is for whatever reads it to decide, not
25234
+ // this shape. This member validates the VALUE rather than leaving that to the
25235
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25236
+ // rejection names the field, so a value that is not a mode is refused as a bad
25237
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25238
+ // it as the mode to attach in.
25239
+ mode: AttachmentMode.optional()
25958
25240
  });
25959
25241
 
25960
25242
  // ../../packages/schema/src/zod/triage.ts
@@ -26240,6 +25522,17 @@ function fromCaptureStatusAttributes(bag) {
26240
25522
  return parsedStatus.success ? parsedStatus.data : null;
26241
25523
  }
26242
25524
 
25525
+ // ../../packages/persistence/src/attached-derived.ts
25526
+ import { rmSync } from "fs";
25527
+ import { join } from "path";
25528
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25529
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25530
+ var ATTACHED_HISTORY_SYNC_STATE_FILENAME = "attached-history-sync.json";
25531
+
25532
+ // ../../packages/persistence/src/control-plane-credential.ts
25533
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25534
+ import { join as join2 } from "path";
25535
+
26243
25536
  // ../../packages/persistence/src/paths.ts
26244
25537
  import {
26245
25538
  chmodSync,
@@ -26329,6 +25622,14 @@ function repairOrRefuseMode(file2) {
26329
25622
  }
26330
25623
  return "ok";
26331
25624
  }
25625
+ function asReadableCredential(value) {
25626
+ const result = AttachedCredentialAny.safeParse(value);
25627
+ if (!result.success) return null;
25628
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25629
+ return null;
25630
+ }
25631
+ return result.data;
25632
+ }
26332
25633
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26333
25634
  const file2 = controlPlaneCredentialPath(settingsDir2);
26334
25635
  let raw;
@@ -26347,25 +25648,25 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26347
25648
  } catch {
26348
25649
  return { usable: false, reason: "malformed" };
26349
25650
  }
26350
- const result = AttachedCredential.safeParse(parsed2);
26351
- if (!result.success) return { usable: false, reason: "malformed" };
26352
- if (!isSafeEndpoint(result.data.endpoint)) {
25651
+ const credential = asReadableCredential(parsed2);
25652
+ if (credential === null) return { usable: false, reason: "malformed" };
25653
+ if (!isSafeEndpoint(credential.endpoint)) {
26353
25654
  return { usable: false, reason: "unsafe-endpoint" };
26354
25655
  }
26355
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25656
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26356
25657
  return {
26357
25658
  usable: false,
26358
25659
  reason: "endpoint-mismatch",
26359
- credentialEndpoint: result.data.endpoint,
25660
+ credentialEndpoint: credential.endpoint,
26360
25661
  settingsEndpoint: connection.endpoint
26361
25662
  };
26362
25663
  }
26363
- return { usable: true, credential: result.data };
25664
+ return { usable: true, credential };
26364
25665
  }
26365
25666
 
26366
25667
  // ../../packages/persistence/src/database.ts
26367
25668
  import { randomUUID as randomUUID11 } from "crypto";
26368
- import { dirname as dirname2, join as join7, sep } from "path";
25669
+ import { dirname as dirname2, join as join8, sep } from "path";
26369
25670
  import { DatabaseSync } from "node:sqlite";
26370
25671
 
26371
25672
  // ../../packages/persistence/src/ids.ts
@@ -26408,6 +25709,7 @@ function uuidFromDigest(digest) {
26408
25709
  function captureWireId(sessionId, contentHash, filePath = null) {
26409
25710
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26410
25711
  }
25712
+ var DOT = ".".charCodeAt(0);
26411
25713
 
26412
25714
  // ../../packages/persistence/src/internal/snapshot.ts
26413
25715
  import { randomUUID } from "crypto";
@@ -26735,6 +26037,25 @@ function scopeKeysParam(scopeKeys) {
26735
26037
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26736
26038
  FROM audit_events AS session_root
26737
26039
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26040
+ var COUNTED_IN_SCOPE = `
26041
+ AND ${inScope("scope_key")}
26042
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26043
+ var DRAIN_TOTALS = `SELECT
26044
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26045
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26046
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26047
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26048
+ THEN 1 ELSE 0 END) AS skipped,
26049
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26050
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26051
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26052
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26053
+ FROM audit_events
26054
+ WHERE event_type IN (${TYPE_LIST})`;
26055
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26056
+ FROM audit_events
26057
+ WHERE synced_at = ${String(SKIPPED)}
26058
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26738
26059
  var HISTORY_SYNC_LEASE_STALE_MS = 6e4;
26739
26060
  var ROW_COLUMNS = `id,
26740
26061
  parent_id AS parentId,
@@ -26811,7 +26132,7 @@ var SqliteHistorySyncRepository = class {
26811
26132
  );
26812
26133
  this.scopedCaptureRowsStmt = db.prepare(
26813
26134
  `SELECT ${ROW_COLUMNS}
26814
- FROM audit_events
26135
+ FROM audit_events INDEXED BY idx_audit_scope_owed
26815
26136
  WHERE synced_at IS NULL
26816
26137
  AND sync_claimed_at IS NULL
26817
26138
  AND outbox_owed = 1
@@ -26864,40 +26185,28 @@ var SqliteHistorySyncRepository = class {
26864
26185
  );
26865
26186
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26866
26187
  FROM audit_events${COUNTED_SCOPE}`);
26188
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26189
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
26867
26190
  this.partitionByKindStmt = db.prepare(
26868
26191
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
26869
26192
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
26870
26193
  GROUP BY event_type`
26871
26194
  );
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})`
26195
+ this.scopedPartitionByKindStmt = db.prepare(
26196
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26197
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26198
+ GROUP BY event_type`
26885
26199
  );
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})`
26200
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26201
+ this.scopedCountsStmt = db.prepare(
26202
+ `${DRAIN_TOTALS}
26203
+ AND ${inScope("scope_key")}
26204
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26205
+ );
26206
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26207
+ this.scopedCaptureSkipCountStmt = db.prepare(
26208
+ `${CAPTURE_SKIPS}
26209
+ AND ${inScope("scope_key")}`
26901
26210
  );
26902
26211
  this.fingerprintStmt = db.prepare(
26903
26212
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27011,6 +26320,10 @@ var SqliteHistorySyncRepository = class {
27011
26320
  scopedCaptureRowsStmt;
27012
26321
  scopedCaptureBacklogOwedStmt;
27013
26322
  markScopeCapturesOwedStmt;
26323
+ scopedPartitionStmt;
26324
+ scopedPartitionByKindStmt;
26325
+ scopedCountsStmt;
26326
+ scopedCaptureSkipCountStmt;
27014
26327
  /**
27015
26328
  * The masked detections recorded against one tool call.
27016
26329
  *
@@ -27232,7 +26545,29 @@ var SqliteHistorySyncRepository = class {
27232
26545
  * in" — and a machine that has never attached has no boundary to pass, so
27233
26546
  * requiring one would force a caller to invent one and report the whole store
27234
26547
  * as queued.
26548
+ *
26549
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26550
+ * the rows that pass the drain's reachability rule for that scope
26551
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26552
+ * drain never offers), so a personal repository's rows are in none of them.
26553
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26554
+ * nothing.
27235
26555
  */
26556
+ partition(scopeKeys) {
26557
+ const row = getRow(
26558
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26559
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26560
+ );
26561
+ return {
26562
+ queued: row?.queued ?? 0,
26563
+ inProgress: row?.inProgress ?? 0,
26564
+ synced: row?.synced ?? 0,
26565
+ failed: row?.failed ?? 0,
26566
+ refused: row?.refused ?? 0,
26567
+ detached: row?.detached ?? 0,
26568
+ total: row?.total ?? 0
26569
+ };
26570
+ }
27236
26571
  /**
27237
26572
  * The same partition, one row per kind that a lane carries.
27238
26573
  *
@@ -27242,11 +26577,14 @@ var SqliteHistorySyncRepository = class {
27242
26577
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27243
26578
  * rows", never as "zero sent"; the two look identical in a bar and mean
27244
26579
  * different things.
26580
+ *
26581
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26582
+ * still sum to the scoped aggregate. An empty list returns no rows.
27245
26583
  */
27246
- partitionByKind() {
26584
+ partitionByKind(scopeKeys) {
27247
26585
  return allRows(
27248
- this.partitionByKindStmt,
27249
- {}
26586
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26587
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27250
26588
  ).map((row) => ({
27251
26589
  kind: row.kind,
27252
26590
  queued: row.queued ?? 0,
@@ -27258,22 +26596,25 @@ var SqliteHistorySyncRepository = class {
27258
26596
  total: row.total ?? 0
27259
26597
  }));
27260
26598
  }
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);
26599
+ /**
26600
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26601
+ * and skipped are totals.
26602
+ *
26603
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26604
+ * `capturesSkipped` included: a structural row is counted only when its own
26605
+ * key and its session root's key are among them, a capture when its own key
26606
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26607
+ * under the same keys and boundary. Omitted, this runs the machine
26608
+ * statements, unchanged; an empty list counts nothing.
26609
+ */
26610
+ counts(before, scopeKeys) {
26611
+ const row = getRow(
26612
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26613
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26614
+ );
26615
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26616
+ scopeKeys: scopeKeysParam(scopeKeys)
26617
+ });
27277
26618
  return {
27278
26619
  pending: row?.pending ?? 0,
27279
26620
  sent: row?.sent ?? 0,
@@ -27525,6 +26866,7 @@ function applyMigrations(db, file2, options = {}) {
27525
26866
  }
27526
26867
  ensureSyncedAtColumn(db, "audit_events");
27527
26868
  ensureScopeKeyColumn(db);
26869
+ ensureScopeOwedIndex(db);
27528
26870
  ensureScanLedgerTable(db);
27529
26871
  ensureHistorySyncTable(db);
27530
26872
  ensureBlockedDetectionsTable(db);
@@ -27965,14 +27307,48 @@ function ensureScopeKeyColumn(db) {
27965
27307
  function hasScopeKeyColumn(db) {
27966
27308
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
27967
27309
  }
27310
+ var SCOPE_OWED_INDEX_DDL = "CREATE INDEX IF NOT EXISTS idx_audit_scope_owed ON audit_events (scope_key, event_type, started_at) WHERE outbox_owed = 1 AND synced_at IS NULL";
27311
+ function ensureScopeOwedIndex(db) {
27312
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27313
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27314
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27315
+ if (!complete) return;
27316
+ db.exec(SCOPE_OWED_INDEX_DDL);
27317
+ }
27968
27318
  function ensureScanLedgerTable(db) {
27969
27319
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
27970
27320
  path TEXT PRIMARY KEY,
27971
27321
  mtime TEXT NOT NULL,
27972
27322
  content_hash TEXT NOT NULL,
27973
27323
  ruleset_hash TEXT NOT NULL,
27974
- scanned_at INTEGER NOT NULL
27324
+ scanned_at INTEGER NOT NULL,
27325
+ scope_key TEXT,
27326
+ scope_root TEXT
27975
27327
  )`);
27328
+ ensureScanLedgerScopeKeyColumn(db);
27329
+ ensureScanLedgerScopeRootColumn(db);
27330
+ }
27331
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27332
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27333
+ function ensureScanLedgerScopeKeyColumn(db) {
27334
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27335
+ }
27336
+ function ensureScanLedgerScopeRootColumn(db) {
27337
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27338
+ }
27339
+ function ensureScanLedgerColumn(db, column, ddl) {
27340
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27341
+ if (hasScanLedgerColumn(db, column)) return;
27342
+ withTransaction(
27343
+ db,
27344
+ () => {
27345
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27346
+ },
27347
+ "IMMEDIATE"
27348
+ );
27349
+ }
27350
+ function hasScanLedgerColumn(db, column) {
27351
+ return columnNames(db, "scan_ledger").includes(column);
27976
27352
  }
27977
27353
  function ensureHistorySyncTable(db) {
27978
27354
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28023,6 +27399,106 @@ function ensureRuleProbeCacheTable(db) {
28023
27399
  )`);
28024
27400
  }
28025
27401
 
27402
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27403
+ import { createHash as createHash2 } from "crypto";
27404
+ import { readFileSync as readFileSync2 } from "fs";
27405
+ import { join as join4 } from "path";
27406
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27407
+ function modPolicySnapshotPath(dataDir2) {
27408
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27409
+ }
27410
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27411
+ const byRule = /* @__PURE__ */ new Map();
27412
+ const byCategory = /* @__PURE__ */ new Map();
27413
+ for (const policy of input2.policies) {
27414
+ if (!policy.enabled) continue;
27415
+ if ("ruleId" in policy.target) {
27416
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27417
+ } else if (!byCategory.has(policy.target.category)) {
27418
+ byCategory.set(policy.target.category, policy.action);
27419
+ }
27420
+ }
27421
+ const categoryActions = {};
27422
+ for (const category of DetectionCategory.options) {
27423
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27424
+ }
27425
+ return {
27426
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27427
+ generatedAt: generatedAt.toISOString(),
27428
+ // `examples` is documentation the mod never reads, and a custom pack's are
27429
+ // whatever its author pasted in, so they stay behind.
27430
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27431
+ ruleActions: Object.fromEntries(byRule),
27432
+ categoryActions,
27433
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27434
+ };
27435
+ }
27436
+ function assignedRuleActionPolicies(installed) {
27437
+ const out = [];
27438
+ for (const [ruleId, action] of installed.ruleActions) {
27439
+ if (installed.assignedRules.has(ruleId))
27440
+ out.push({ target: { ruleId }, action, enabled: true });
27441
+ }
27442
+ return out;
27443
+ }
27444
+ function withoutExamples(rule) {
27445
+ const copy = { ...rule };
27446
+ delete copy.examples;
27447
+ return copy;
27448
+ }
27449
+ function sameContent(a, b) {
27450
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27451
+ }
27452
+ function readModPolicySnapshot(dataDir2) {
27453
+ try {
27454
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27455
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27456
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27457
+ return parsed2.success ? parsed2.data : null;
27458
+ } catch {
27459
+ return null;
27460
+ }
27461
+ }
27462
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27463
+ const text = JSON.stringify(snapshot);
27464
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27465
+ const existing = readModPolicySnapshot(dataDir2);
27466
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27467
+ ensureDataDirSync(dataDir2);
27468
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27469
+ return true;
27470
+ }
27471
+ function regexProbeKey(matcher) {
27472
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27473
+ }
27474
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27475
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27476
+ return rules.filter((rule) => {
27477
+ if (rule.matcher.type !== "regex") return true;
27478
+ const key = regexProbeKey(rule.matcher);
27479
+ const verdict = sources.probeVerdict(key);
27480
+ if (verdict === "quarantined") return false;
27481
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27482
+ });
27483
+ }
27484
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27485
+ const policies = sources.readPolicies();
27486
+ const snapshot = sources.installedRuleset();
27487
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27488
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27489
+ return {
27490
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27491
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27492
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27493
+ };
27494
+ }
27495
+ function refreshModPolicySnapshot(dataDir2, sources) {
27496
+ try {
27497
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27498
+ } catch {
27499
+ }
27500
+ }
27501
+
28026
27502
  // ../../packages/persistence/src/internal/json.ts
28027
27503
  function safeJson(s, fallback) {
28028
27504
  if (s == null) return fallback;
@@ -28197,6 +27673,11 @@ var TIMELINE_COLUMNS = `
28197
27673
  json_extract(attributes, '$.targetId') AS target_id,
28198
27674
  json_extract(attributes, '$.internal') AS internal,
28199
27675
  json_extract(attributes, '$.flagged') AS flagged`;
27676
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27677
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27678
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27679
+ " + "
27680
+ );
28200
27681
  var LLM_USAGE_SELECT = `
28201
27682
  SELECT root_session_id AS sessionId,
28202
27683
  provider,
@@ -28208,9 +27689,10 @@ var LLM_USAGE_SELECT = `
28208
27689
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28209
27690
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28210
27691
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28211
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27692
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27693
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28212
27694
  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`;
27695
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28214
27696
  function usageLeaves(rows) {
28215
27697
  return rows.map((row) => {
28216
27698
  const attributes = {
@@ -28225,7 +27707,7 @@ function usageLeaves(rows) {
28225
27707
  if (row.provider !== null) attributes.provider = row.provider;
28226
27708
  if (row.model !== null) attributes.model = row.model;
28227
27709
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28228
- return { sessionId: row.sessionId, attributes };
27710
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28229
27711
  });
28230
27712
  }
28231
27713
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29158,8 +28640,8 @@ var SqliteConfigInventoryRepository = class {
29158
28640
  }
29159
28641
  db;
29160
28642
  report() {
29161
- const scan2 = latestConfigScan(this.db);
29162
- if (!scan2) {
28643
+ const scan = latestConfigScan(this.db);
28644
+ if (!scan) {
29163
28645
  return {
29164
28646
  scannedAt: null,
29165
28647
  skills: [],
@@ -29175,7 +28657,7 @@ var SqliteConfigInventoryRepository = class {
29175
28657
  WHERE object_type IN ('skill', 'hook', 'mcp_server', 'config_file') AND last_seen >= :startedAt
29176
28658
  ORDER BY object_type, title`
29177
28659
  ),
29178
- { startedAt: scan2.started_at }
28660
+ { startedAt: scan.started_at }
29179
28661
  );
29180
28662
  const findings = allRows(
29181
28663
  this.db.prepare(
@@ -29184,7 +28666,7 @@ var SqliteConfigInventoryRepository = class {
29184
28666
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
29185
28667
  WHERE f.audit_event_id = :scanId`
29186
28668
  ),
29187
- { scanId: scan2.id }
28669
+ { scanId: scan.id }
29188
28670
  );
29189
28671
  const skills = [];
29190
28672
  const hooks = [];
@@ -29200,12 +28682,12 @@ var SqliteConfigInventoryRepository = class {
29200
28682
  else configFiles.push(toConfigFileItem(row, bag));
29201
28683
  }
29202
28684
  return {
29203
- scannedAt: new Date(scan2.started_at).toISOString(),
28685
+ scannedAt: new Date(scan.started_at).toISOString(),
29204
28686
  skills,
29205
28687
  hooks,
29206
28688
  mcpServers,
29207
28689
  configFiles,
29208
- topics: buildTopics(skills, hooks, mcpServers, configFiles, scan2.attributes)
28690
+ topics: buildTopics(skills, hooks, mcpServers, configFiles, scan.attributes)
29209
28691
  };
29210
28692
  }
29211
28693
  // asset_id → trust for every stored override. The id space is opaque on
@@ -29559,9 +29041,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29559
29041
  AND conditions IS NULL
29560
29042
  AND ${ACTIVE_PREDICATE}`;
29561
29043
  var SqliteExceptionsRepository = class {
29562
- constructor(db, now = () => Date.now()) {
29044
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29563
29045
  this.db = db;
29564
29046
  this.now = now;
29047
+ this.onChange = onChange;
29565
29048
  this.consumeStmt = db.prepare(
29566
29049
  `UPDATE exceptions
29567
29050
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29580,6 +29063,7 @@ var SqliteExceptionsRepository = class {
29580
29063
  }
29581
29064
  db;
29582
29065
  now;
29066
+ onChange;
29583
29067
  consumeStmt;
29584
29068
  insertBlockedStmt;
29585
29069
  sweepBlockedStmt;
@@ -29595,7 +29079,9 @@ var SqliteExceptionsRepository = class {
29595
29079
  */
29596
29080
  create(input2) {
29597
29081
  try {
29598
- return Promise.resolve(this.createSync(input2));
29082
+ const created = this.createSync(input2);
29083
+ this.onChange();
29084
+ return Promise.resolve(created);
29599
29085
  } catch (err) {
29600
29086
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29601
29087
  }
@@ -29726,6 +29212,7 @@ var SqliteExceptionsRepository = class {
29726
29212
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29727
29213
  WHERE id = :id AND revoked_at IS NULL`
29728
29214
  ).run({ id, revokedBy, reason: reason ?? null, now });
29215
+ if (Number(result.changes) === 1) this.onChange();
29729
29216
  return Promise.resolve(Number(result.changes) === 1);
29730
29217
  }
29731
29218
  /**
@@ -29738,6 +29225,15 @@ var SqliteExceptionsRepository = class {
29738
29225
  const result = this.consumeStmt.run({ id, now });
29739
29226
  return Promise.resolve(Number(result.changes) === 1);
29740
29227
  }
29228
+ /** The rule ids with at least one active grant, under any key version. */
29229
+ activeRuleIds(now = this.now()) {
29230
+ return allRows(
29231
+ this.db.prepare(
29232
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29233
+ ),
29234
+ { now }
29235
+ ).map((row) => row.ruleId);
29236
+ }
29741
29237
  /**
29742
29238
  * The evaluation subset of every active grant under one fingerprint key
29743
29239
  * version — what rides the policy bundle to the hook. Grants written under
@@ -30861,30 +30357,30 @@ var SqliteInspectionFindingsRepository = class {
30861
30357
  };
30862
30358
 
30863
30359
  // ../../packages/persistence/src/repositories/installed-packs.ts
30864
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30360
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
30865
30361
 
30866
30362
  // ../../packages/persistence/src/policy-floor.ts
30867
- import { readFileSync as readFileSync5 } from "fs";
30868
- import { join as join6 } from "path";
30363
+ import { readFileSync as readFileSync6 } from "fs";
30364
+ import { join as join7 } from "path";
30869
30365
 
30870
30366
  // ../../packages/persistence/src/local-layout.ts
30871
30367
  import { renameSync as renameSync3 } from "fs";
30872
30368
  import { mkdir } from "fs/promises";
30873
30369
  import { homedir } from "os";
30874
- import { join as join4 } from "path";
30370
+ import { join as join5 } from "path";
30875
30371
  function defaultDataDir() {
30876
- return join4(homedir(), ".aka");
30372
+ return join5(homedir(), ".aka");
30877
30373
  }
30878
30374
  function settingsDir(base = defaultDataDir()) {
30879
- return join4(base, "settings");
30375
+ return join5(base, "settings");
30880
30376
  }
30881
30377
  function dataDir(base = defaultDataDir()) {
30882
- return join4(base, "data");
30378
+ return join5(base, "data");
30883
30379
  }
30884
30380
 
30885
30381
  // ../../packages/persistence/src/settings.ts
30886
- import { readFileSync as readFileSync4 } from "fs";
30887
- import { join as join5 } from "path";
30382
+ import { readFileSync as readFileSync5 } from "fs";
30383
+ import { join as join6 } from "path";
30888
30384
 
30889
30385
  // ../../packages/persistence/src/file-lock.ts
30890
30386
  import { randomUUID as randomUUID3 } from "crypto";
@@ -30892,7 +30388,7 @@ import {
30892
30388
  closeSync,
30893
30389
  existsSync as existsSync2,
30894
30390
  openSync,
30895
- readFileSync as readFileSync2,
30391
+ readFileSync as readFileSync3,
30896
30392
  rmSync as rmSync5,
30897
30393
  statSync as statSync3,
30898
30394
  writeFileSync as writeFileSync2
@@ -30901,16 +30397,16 @@ import { hostname as hostname3 } from "os";
30901
30397
  var PARK = new Int32Array(new SharedArrayBuffer(4));
30902
30398
 
30903
30399
  // ../../packages/persistence/src/managed-settings.ts
30904
- import { readFileSync as readFileSync3 } from "fs";
30400
+ import { readFileSync as readFileSync4 } from "fs";
30905
30401
  import { posix, win32 } from "path";
30906
- function managedSettingsPaths(platform2 = process.platform) {
30907
- if (platform2 === "darwin") {
30402
+ function managedSettingsPaths(platform = process.platform) {
30403
+ if (platform === "darwin") {
30908
30404
  return [
30909
30405
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
30910
30406
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
30911
30407
  ];
30912
30408
  }
30913
- if (platform2 === "win32") {
30409
+ if (platform === "win32") {
30914
30410
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
30915
30411
  }
30916
30412
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -30920,7 +30416,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
30920
30416
  for (const path of paths) {
30921
30417
  let text;
30922
30418
  try {
30923
- text = readFileSync3(path, "utf8");
30419
+ text = readFileSync4(path, "utf8");
30924
30420
  } catch {
30925
30421
  continue;
30926
30422
  }
@@ -30974,7 +30470,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
30974
30470
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
30975
30471
  }
30976
30472
  function readUserSettings(base) {
30977
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30473
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
30978
30474
  if (!record2) return defaultWorkspaceSettings();
30979
30475
  try {
30980
30476
  return WorkspaceSettings.parse(record2);
@@ -30985,7 +30481,7 @@ function readUserSettings(base) {
30985
30481
  function readJson(file2) {
30986
30482
  let text;
30987
30483
  try {
30988
- text = readFileSync4(file2, "utf8");
30484
+ text = readFileSync5(file2, "utf8");
30989
30485
  } catch {
30990
30486
  return null;
30991
30487
  }
@@ -31025,7 +30521,7 @@ var PolicyFloorError = class extends Error {
31025
30521
  };
31026
30522
  function readCachedPolicyBundle(base = defaultDataDir()) {
31027
30523
  try {
31028
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30524
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31029
30525
  const parsed2 = JSON.parse(raw);
31030
30526
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31031
30527
  return PolicyBundle.parse(parsed2.bundle);
@@ -31149,7 +30645,7 @@ function inventorySignature(packs) {
31149
30645
  return packs.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31150
30646
  }
31151
30647
  function hashRules(rulesJson) {
31152
- return createHash2("sha256").update(rulesJson).digest("hex");
30648
+ return createHash3("sha256").update(rulesJson).digest("hex");
31153
30649
  }
31154
30650
  function parseVersion(v) {
31155
30651
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31191,9 +30687,10 @@ var SqliteInstalledPacksRepository = class {
31191
30687
  * from `openLocalDatabase`, which is the single construction site that owns a
31192
30688
  * real `~/.aka`.
31193
30689
  */
31194
- constructor(db, baseDir) {
30690
+ constructor(db, baseDir, onChange = () => void 0) {
31195
30691
  this.db = db;
31196
30692
  this.baseDir = baseDir;
30693
+ this.onChange = onChange;
31197
30694
  this.insertMissingStmt = db.prepare(
31198
30695
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31199
30696
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31222,6 +30719,7 @@ var SqliteInstalledPacksRepository = class {
31222
30719
  }
31223
30720
  db;
31224
30721
  baseDir;
30722
+ onChange;
31225
30723
  insertMissingStmt;
31226
30724
  upsertAvailableStmt;
31227
30725
  signatureStmt;
@@ -31294,6 +30792,7 @@ var SqliteInstalledPacksRepository = class {
31294
30792
  },
31295
30793
  "IMMEDIATE"
31296
30794
  );
30795
+ this.onChange();
31297
30796
  } catch {
31298
30797
  }
31299
30798
  }
@@ -31368,6 +30867,7 @@ var SqliteInstalledPacksRepository = class {
31368
30867
  },
31369
30868
  "IMMEDIATE"
31370
30869
  );
30870
+ if (changed) this.onChange();
31371
30871
  return changed;
31372
30872
  }
31373
30873
  /**
@@ -31609,6 +31109,7 @@ var SqliteInstalledPacksRepository = class {
31609
31109
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31610
31110
  WHERE namespace = :namespace AND pack_id = :packId`
31611
31111
  ).run({ policyId, now: Date.now(), namespace, packId });
31112
+ if (Number(res.changes) > 0) this.onChange();
31612
31113
  return Number(res.changes) > 0;
31613
31114
  }
31614
31115
  /**
@@ -31633,6 +31134,7 @@ var SqliteInstalledPacksRepository = class {
31633
31134
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31634
31135
  WHERE namespace = :namespace AND pack_id = :packId`
31635
31136
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31137
+ if (Number(res.changes) > 0) this.onChange();
31636
31138
  return Number(res.changes) > 0;
31637
31139
  }
31638
31140
  // Fingerprint of the recorded available mirror — compared against the
@@ -32530,13 +32032,19 @@ var SqliteInventoryAssetsRepository = class {
32530
32032
  import { randomUUID as randomUUID6 } from "crypto";
32531
32033
  var SEED_BATCH_WINDOW_MS = 6e4;
32532
32034
  var SqlitePoliciesRepository = class {
32533
- constructor(db) {
32035
+ constructor(db, onChange = () => void 0) {
32534
32036
  this.db = db;
32037
+ this.onChange = onChange;
32535
32038
  }
32536
32039
  db;
32040
+ onChange;
32537
32041
  readPolicies() {
32042
+ return Promise.resolve(this.listPolicies());
32043
+ }
32044
+ /** The synchronous read behind {@link readPolicies}. */
32045
+ listPolicies() {
32538
32046
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32539
- const policies = mapRowsTolerant(rows, (row) => {
32047
+ return mapRowsTolerant(rows, (row) => {
32540
32048
  const target = JSON.parse(row.target);
32541
32049
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32542
32050
  return Policy.parse({
@@ -32548,7 +32056,6 @@ var SqlitePoliciesRepository = class {
32548
32056
  customKeywords
32549
32057
  });
32550
32058
  });
32551
- return Promise.resolve(policies);
32552
32059
  }
32553
32060
  // Seed one policy per bundled category at Monitor so the detection-type config
32554
32061
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32559,7 +32066,7 @@ var SqlitePoliciesRepository = class {
32559
32066
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32560
32067
  if (count > 0) {
32561
32068
  this.markEarlierChoices();
32562
- this.monitorUntouchedSeeds();
32069
+ if (this.monitorUntouchedSeeds()) this.onChange();
32563
32070
  return;
32564
32071
  }
32565
32072
  const stmt = this.db.prepare(
@@ -32576,6 +32083,7 @@ var SqlitePoliciesRepository = class {
32576
32083
  });
32577
32084
  }
32578
32085
  });
32086
+ this.onChange();
32579
32087
  }
32580
32088
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32581
32089
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32641,7 +32149,7 @@ var SqlitePoliciesRepository = class {
32641
32149
  ).filter(
32642
32150
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32643
32151
  );
32644
- if (untouched.length === 0) return;
32152
+ if (untouched.length === 0) return false;
32645
32153
  const stmt = this.db.prepare(
32646
32154
  `UPDATE policies SET action = 'log'
32647
32155
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32652,6 +32160,7 @@ var SqlitePoliciesRepository = class {
32652
32160
  stmt.run({ category: row.category, seeded: row.action });
32653
32161
  }
32654
32162
  });
32163
+ return true;
32655
32164
  }
32656
32165
  // Insert-or-update the single global per-category policy row, keyed on the
32657
32166
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32668,6 +32177,7 @@ var SqlitePoliciesRepository = class {
32668
32177
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32669
32178
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32670
32179
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32180
+ this.onChange();
32671
32181
  }
32672
32182
  // Caps every global per-category policy currently set to block/redact down
32673
32183
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32678,6 +32188,7 @@ var SqlitePoliciesRepository = class {
32678
32188
  WHERE scope='global' AND action IN ('block','redact')
32679
32189
  AND json_extract(target,'$.category') IS NOT NULL`
32680
32190
  ).run({ now: Date.now() });
32191
+ if (Number(info.changes) > 0) this.onChange();
32681
32192
  return Number(info.changes);
32682
32193
  }
32683
32194
  // Whether the category's row was ever written after it was created — by the
@@ -32772,10 +32283,10 @@ var SqliteProjectFilesRepository = class {
32772
32283
  pruneStmt;
32773
32284
  maxStampStmt;
32774
32285
  /** Replace `projectId`'s tree with the scan's files. Caller wraps in a transaction. */
32775
- replaceForProject(projectId, scan2, now) {
32286
+ replaceForProject(projectId, scan, now) {
32776
32287
  const maxStamp = getRow(this.maxStampStmt, { projectId })?.maxStamp ?? 0;
32777
32288
  const stamp = Math.max(now, maxStamp + 1);
32778
- for (const file2 of scan2.files) {
32289
+ for (const file2 of scan.files) {
32779
32290
  this.upsertStmt.run({
32780
32291
  id: randomUUID7(),
32781
32292
  projectId,
@@ -32786,7 +32297,7 @@ var SqliteProjectFilesRepository = class {
32786
32297
  now: stamp
32787
32298
  });
32788
32299
  }
32789
- if (!scan2.truncated) this.pruneStmt.run({ projectId, now: stamp });
32300
+ if (!scan.truncated) this.pruneStmt.run({ projectId, now: stamp });
32790
32301
  }
32791
32302
  };
32792
32303
 
@@ -32997,31 +32508,45 @@ var SqliteScanLedgerRepository = class {
32997
32508
  constructor(db) {
32998
32509
  this.db = db;
32999
32510
  this.upsertStmt = db.prepare(
33000
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33001
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32511
+ `INSERT INTO scan_ledger
32512
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32513
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33002
32514
  ON CONFLICT (path) DO UPDATE SET
33003
32515
  mtime = excluded.mtime,
33004
32516
  content_hash = excluded.content_hash,
33005
32517
  ruleset_hash = excluded.ruleset_hash,
32518
+ scope_key = excluded.scope_key,
32519
+ scope_root = excluded.scope_root,
33006
32520
  scanned_at = excluded.scanned_at`
33007
32521
  );
33008
32522
  this.readStmt = db.prepare(
33009
- `SELECT path, mtime, content_hash AS contentHash
32523
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32524
+ scope_root AS scopeRoot
33010
32525
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33011
32526
  );
33012
32527
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32528
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33013
32529
  }
33014
32530
  db;
33015
32531
  upsertStmt;
33016
32532
  readStmt;
33017
32533
  pathsStmt;
32534
+ pathKeysStmt;
33018
32535
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33019
32536
  // older ruleset are simply absent, which reads as "never scanned".
33020
32537
  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 }]));
32538
+ const rows = allRows(this.readStmt, { rulesetHash });
32539
+ return new Map(
32540
+ rows.map((r) => [
32541
+ r.path,
32542
+ {
32543
+ mtime: r.mtime,
32544
+ contentHash: r.contentHash,
32545
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32546
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32547
+ }
32548
+ ])
32549
+ );
33025
32550
  }
33026
32551
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33027
32552
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33030,6 +32555,14 @@ var SqliteScanLedgerRepository = class {
33030
32555
  allPaths() {
33031
32556
  return allRows(this.pathsStmt).map((r) => r.path);
33032
32557
  }
32558
+ // Every ledgered path with the repository it was in when it was last read,
32559
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32560
+ // which repository a vanished file belonged to. `undefined` for a row with no
32561
+ // key, which is every row written before the column existed.
32562
+ pathKeys() {
32563
+ const rows = allRows(this.pathKeysStmt);
32564
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32565
+ }
33033
32566
  upsertEntries(entries) {
33034
32567
  if (entries.length === 0) return;
33035
32568
  const scannedAt = Date.now();
@@ -33040,6 +32573,8 @@ var SqliteScanLedgerRepository = class {
33040
32573
  mtime: entry.mtime,
33041
32574
  contentHash: entry.contentHash,
33042
32575
  rulesetHash: entry.rulesetHash,
32576
+ scopeKey: entry.scopeKey ?? null,
32577
+ scopeRoot: entry.scopeRoot ?? null,
33043
32578
  scannedAt
33044
32579
  });
33045
32580
  }
@@ -34127,6 +33662,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34127
33662
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34128
33663
  };
34129
33664
  }
33665
+ function withoutTrailingSlashes(path) {
33666
+ let end = path.length;
33667
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33668
+ return path.slice(0, end);
33669
+ }
34130
33670
  function toEndpointSummary(row) {
34131
33671
  return {
34132
33672
  id: row.id,
@@ -34414,7 +33954,7 @@ var SqliteSharesRepository = class {
34414
33954
  */
34415
33955
  reconcileCallSites(projectKey, reconcile) {
34416
33956
  if (reconcile.mode === "walk") {
34417
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
33957
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34418
33958
  this.db.prepare(
34419
33959
  `DELETE FROM share_call_site
34420
33960
  WHERE project_key = :key
@@ -34982,7 +34522,7 @@ function backupLegacyStore(db, file2) {
34982
34522
  discardStore(file2, backup);
34983
34523
  return backup;
34984
34524
  }
34985
- function openAndInitialize(file2, base, skipTags) {
34525
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers) {
34986
34526
  let db = openWithPragmas(file2);
34987
34527
  try {
34988
34528
  if (isForeignSqliteLineage(db)) {
@@ -34994,8 +34534,15 @@ function openAndInitialize(file2, base, skipTags) {
34994
34534
  }
34995
34535
  applyMigrations(db, file2, { skipTags });
34996
34536
  tightenPerms(file2);
34997
- const policies = new SqlitePoliciesRepository(db);
34998
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34537
+ const modPolicy = {};
34538
+ const onPolicyStateChange = () => {
34539
+ if (modPolicy.current !== void 0)
34540
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34541
+ };
34542
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34543
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34544
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34545
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
34999
34546
  const repositories = {
35000
34547
  events: new SqliteEventsRepository(db),
35001
34548
  findings: new SqliteFindingsRepository(db),
@@ -35004,9 +34551,9 @@ function openAndInitialize(file2, base, skipTags) {
35004
34551
  scanLedger: new SqliteScanLedgerRepository(db),
35005
34552
  historySync: new SqliteHistorySyncRepository(db),
35006
34553
  secretVault: new SqliteSecretVaultRepository(db),
35007
- exceptions: new SqliteExceptionsRepository(db),
34554
+ exceptions,
35008
34555
  resolutions: new SqliteResolutionsRepository(db),
35009
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34556
+ ruleProbeCache,
35010
34557
  bodyRetention: new SqliteBodyRetentionRepository(db),
35011
34558
  security: new SqliteSecurityRepository(db),
35012
34559
  detections: new SqliteDetectionsRepository(db),
@@ -35024,6 +34571,13 @@ function openAndInitialize(file2, base, skipTags) {
35024
34571
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35025
34572
  configInventory: new SqliteConfigInventoryRepository(db)
35026
34573
  };
34574
+ modPolicy.current = {
34575
+ installedRuleset: () => installedPacks.installedRuleset(),
34576
+ readPolicies: () => policies.listPolicies(),
34577
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34578
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34579
+ bundledRegexMatchers: () => shippedRegexMatchers
34580
+ };
35027
34581
  policies.seedDefaults();
35028
34582
  return { db, ...repositories };
35029
34583
  } catch (err) {
@@ -35035,7 +34589,7 @@ function openAndInitialize(file2, base, skipTags) {
35035
34589
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35036
34590
  function openLocalDatabase(dir, options = {}) {
35037
34591
  ensureDataDirSync(dir);
35038
- const file2 = join7(dir, DB_FILENAME);
34592
+ const file2 = join8(dir, DB_FILENAME);
35039
34593
  reapStalePartials(file2);
35040
34594
  const {
35041
34595
  db,
@@ -35071,7 +34625,8 @@ function openLocalDatabase(dir, options = {}) {
35071
34625
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35072
34626
  // settings/ and data/, and the pack-policy floor needs both halves.
35073
34627
  dirname2(dir),
35074
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34628
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34629
+ options.shippedRegexMatchers ?? []
35075
34630
  );
35076
34631
  function captureRowId(event) {
35077
34632
  return captureId(
@@ -35227,10 +34782,10 @@ function openLocalDatabase(dir, options = {}) {
35227
34782
  }
35228
34783
  });
35229
34784
  }
35230
- function recordProjectFiles(projectId, scan2) {
35231
- if (scan2.files.length === 0) return;
34785
+ function recordProjectFiles(projectId, scan) {
34786
+ if (scan.files.length === 0) return;
35232
34787
  failOpenTransaction(db, () => {
35233
- projectFiles.replaceForProject(projectId, scan2, Date.now());
34788
+ projectFiles.replaceForProject(projectId, scan, Date.now());
35234
34789
  });
35235
34790
  }
35236
34791
  async function transaction(fn) {
@@ -35336,22 +34891,21 @@ function openLocalDatabase(dir, options = {}) {
35336
34891
  }
35337
34892
 
35338
34893
  // ../../packages/persistence/src/egress-wire.ts
35339
- import { createHash as createHash3 } from "crypto";
34894
+ import { createHash as createHash4 } from "crypto";
35340
34895
  var SLASH = "/".charCodeAt(0);
35341
34896
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35342
34897
 
35343
34898
  // ../../packages/persistence/src/finding-key.ts
35344
- import { createHash as createHash4 } from "crypto";
34899
+ import { createHash as createHash5 } from "crypto";
35345
34900
 
35346
34901
  // ../../packages/persistence/src/fingerprint.ts
35347
34902
  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";
34903
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
34904
+ import { join as join9 } from "path";
35351
34905
 
35352
34906
  // ../../packages/persistence/src/forward-health.ts
35353
- import { readFileSync as readFileSync7 } from "fs";
35354
- import { join as join9 } from "path";
34907
+ import { readFileSync as readFileSync8 } from "fs";
34908
+ import { join as join10 } from "path";
35355
34909
  var BREAKER_COOLDOWN_MS = 3e4;
35356
34910
  function parseForwardHealth(raw, nowMs) {
35357
34911
  try {
@@ -35370,7 +34924,7 @@ function parseForwardHealth(raw, nowMs) {
35370
34924
  function readForwardHealth(dir, nowMs = Date.now()) {
35371
34925
  try {
35372
34926
  return parseForwardHealth(
35373
- readFileSync7(join9(dir, ATTACHED_FORWARD_STATE_FILENAME), "utf8"),
34927
+ readFileSync8(join10(dir, ATTACHED_FORWARD_STATE_FILENAME), "utf8"),
35374
34928
  nowMs
35375
34929
  );
35376
34930
  } catch {
@@ -35385,16 +34939,16 @@ function isForwardPaused(health, nowMs) {
35385
34939
 
35386
34940
  // ../../packages/persistence/src/history-backfill.ts
35387
34941
  import { existsSync as existsSync4 } from "fs";
35388
- import { join as join10 } from "path";
34942
+ import { join as join11 } from "path";
35389
34943
 
35390
34944
  // ../../packages/persistence/src/history-preview.ts
35391
34945
  import { existsSync as existsSync5 } from "fs";
35392
- import { join as join11 } from "path";
35393
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
34946
+ import { join as join12 } from "path";
34947
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35394
34948
 
35395
34949
  // ../../packages/persistence/src/history-sync-state.ts
35396
- import { readFileSync as readFileSync8 } from "fs";
35397
- import { join as join12 } from "path";
34950
+ import { readFileSync as readFileSync9 } from "fs";
34951
+ import { join as join13 } from "path";
35398
34952
  var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
35399
34953
  var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
35400
34954
  var OUTCOMES = /* @__PURE__ */ new Set([
@@ -35403,9 +34957,10 @@ var OUTCOMES = /* @__PURE__ */ new Set([
35403
34957
  "refused",
35404
34958
  "interrupted"
35405
34959
  ]);
34960
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35406
34961
  var SPEC_VERSION = 1;
35407
34962
  function historySyncStatePath(dataDir2) {
35408
- return join12(dataDir2, HISTORY_SYNC_STATE_FILENAME);
34963
+ return join13(dataDir2, HISTORY_SYNC_STATE_FILENAME);
35409
34964
  }
35410
34965
  function writeHistorySyncState(dataDir2, state) {
35411
34966
  try {
@@ -35418,7 +34973,7 @@ function writeHistorySyncState(dataDir2, state) {
35418
34973
  }
35419
34974
  function readHistorySyncState(dataDir2) {
35420
34975
  try {
35421
- const parsed2 = JSON.parse(readFileSync8(historySyncStatePath(dataDir2), "utf8"));
34976
+ const parsed2 = JSON.parse(readFileSync9(historySyncStatePath(dataDir2), "utf8"));
35422
34977
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
35423
34978
  const r = parsed2;
35424
34979
  if (r.specVersion !== SPEC_VERSION) return null;
@@ -35436,7 +34991,8 @@ function readHistorySyncState(dataDir2) {
35436
34991
  pendingTotal: r.pendingTotal,
35437
34992
  skippedTotal: r.skippedTotal,
35438
34993
  startedAtMs: r.startedAtMs,
35439
- completedAtMs: r.completedAtMs
34994
+ completedAtMs: r.completedAtMs,
34995
+ ...isCountsScope(r.countsScope) ? { countsScope: r.countsScope } : {}
35440
34996
  };
35441
34997
  } catch {
35442
34998
  return null;
@@ -35448,10 +35004,13 @@ function isCount(v) {
35448
35004
  function isNullableCount(v) {
35449
35005
  return v === null || isCount(v);
35450
35006
  }
35007
+ function isCountsScope(v) {
35008
+ return typeof v === "string" && COUNTS_SCOPES.has(v);
35009
+ }
35451
35010
 
35452
35011
  // ../../packages/persistence/src/store-symlinks.ts
35453
35012
  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";
35013
+ import { dirname as dirname3, join as join14, resolve } from "path";
35455
35014
 
35456
35015
  // ../../packages/persistence/src/vault/crypto.ts
35457
35016
  import {
@@ -35465,15 +35024,15 @@ import {
35465
35024
  // ../../packages/persistence/src/vault/key-provider.ts
35466
35025
  import { execFileSync } from "child_process";
35467
35026
  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";
35027
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35028
+ import { join as join15 } from "path";
35470
35029
 
35471
35030
  // ../../packages/persistence/src/vault/vault.ts
35472
35031
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35473
35032
 
35474
35033
  // ../../packages/persistence/src/warn-era-cap.ts
35475
35034
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35476
- import { join as join15 } from "path";
35035
+ import { join as join16 } from "path";
35477
35036
 
35478
35037
  // ../../packages/remote/src/http.ts
35479
35038
  import { request as httpRequest } from "http";
@@ -35788,998 +35347,13 @@ function createRemoteClient(options) {
35788
35347
  var REQUEST_TIMEOUT_MS = 2e3;
35789
35348
 
35790
35349
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
35791
- import { readFileSync as readFileSync10 } from "fs";
35792
- import { join as join16 } from "path";
35350
+ import { readFileSync as readFileSync11 } from "fs";
35351
+ import { join as join17 } from "path";
35793
35352
 
35794
35353
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
35795
- import { randomUUID as randomUUID16 } from "crypto";
35354
+ import { randomUUID as randomUUID13 } from "crypto";
35796
35355
  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";
35356
+ import { join as join18 } from "path";
36783
35357
 
36784
35358
  // ../../packages/plugin-runtime/src/attached/scope-strip.ts
36785
35359
  function withoutScopeKey(event) {
@@ -36793,9 +35367,19 @@ function withoutScopeKey(event) {
36793
35367
  return bare;
36794
35368
  }
36795
35369
 
35370
+ // ../../packages/plugin-runtime/src/attached/scoped-repo.ts
35371
+ function withScopedRepo(event, scopeKey) {
35372
+ const repo = scopeKey.split("/").filter((segment) => segment !== "").pop();
35373
+ if (repo !== void 0) return { ...event, metadata: { ...event.metadata, repo } };
35374
+ if (event.metadata?.repo === void 0) return event;
35375
+ const metadata = { ...event.metadata };
35376
+ delete metadata.repo;
35377
+ return { ...event, metadata };
35378
+ }
35379
+
36796
35380
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36797
35381
  import { createHash as createHash6 } from "crypto";
36798
- import { hostname as hostname5 } from "os";
35382
+ import { hostname as hostname4 } from "os";
36799
35383
 
36800
35384
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
36801
35385
  function rebuildCapture(row) {
@@ -37025,6 +35609,11 @@ async function runHistorySync(deps) {
37025
35609
  if (!Number.isFinite(consentAcknowledgedAtMs)) return didNotRun("attachment-unreadable");
37026
35610
  const state = readControlPlaneCredentialFile(deps.settingsDir, connection);
37027
35611
  if (!state.usable) return didNotRun("credential-unusable");
35612
+ const mode = attachmentModeOf(state.credential);
35613
+ const scopeOf = (live) => resolveScope({ mode, scope: live.attachmentScope, endpoint: connection.endpoint });
35614
+ const passScope = scopeOf(settings);
35615
+ const passFilter = scopeFilterOf(passScope);
35616
+ const liveScope = () => mode === "machine" ? passScope : scopeOf(readWorkspaceSettings(deps.base));
37028
35617
  const nowMs = now();
37029
35618
  if (isForwardPaused(readForwardHealth(deps.dataDir, nowMs), nowMs)) {
37030
35619
  return didNotRun("breaker-open");
@@ -37037,7 +35626,7 @@ async function runHistorySync(deps) {
37037
35626
  const recorded = ledger.deployment();
37038
35627
  let backlogBefore;
37039
35628
  if (recorded.fingerprint !== fingerprint) {
37040
- ledger.rearmFor(fingerprint, attachedAtMs, consentAcknowledgedAtMs);
35629
+ ledger.rearmFor(fingerprint, attachedAtMs, consentAcknowledgedAtMs, passFilter);
37041
35630
  backlogBefore = attachedAtMs;
37042
35631
  } else if (recorded.backlogBefore === void 0) {
37043
35632
  ledger.freezeBoundary(attachedAtMs);
@@ -37046,7 +35635,7 @@ async function runHistorySync(deps) {
37046
35635
  backlogBefore = recorded.backlogBefore;
37047
35636
  }
37048
35637
  const pid = process.pid;
37049
- if (!ledger.claim(pid, hostname5(), now(), HISTORY_SYNC_LEASE_STALE_MS)) {
35638
+ if (!ledger.claim(pid, hostname4(), now(), HISTORY_SYNC_LEASE_STALE_MS)) {
37050
35639
  return didNotRun("already-running");
37051
35640
  }
37052
35641
  const client = deps.sendBatch !== void 0 && deps.sendCaptures !== void 0 && deps.sendOne !== void 0 ? void 0 : createRemoteClient({
@@ -37079,7 +35668,8 @@ async function runHistorySync(deps) {
37079
35668
  random,
37080
35669
  budgetMs,
37081
35670
  pid,
37082
- backlogBefore
35671
+ backlogBefore,
35672
+ liveScope
37083
35673
  });
37084
35674
  } finally {
37085
35675
  ledger.release(pid);
@@ -37107,13 +35697,23 @@ async function drain(d) {
37107
35697
  d.ledger.heartbeat(d.pid, at);
37108
35698
  lastHeartbeat = at;
37109
35699
  };
35700
+ const capturesOwed = (filter2) => d.ledger.pendingCaptureRows(1, d.now() - CAPTURE_GRACE_MS, filter2).length > 0;
37110
35701
  const drainStructural = async (until) => {
37111
35702
  let stopped = "ok";
37112
35703
  outer: while (d.now() < until) {
37113
- const sessions = d.ledger.pendingSessions(SESSION_PAGE, d.backlogBefore);
35704
+ const sessions = d.ledger.pendingSessions(
35705
+ SESSION_PAGE,
35706
+ d.backlogBefore,
35707
+ scopeFilterOf(d.liveScope())
35708
+ );
37114
35709
  if (sessions.length === 0) break;
37115
35710
  for (const sessionId of sessions) {
37116
- const rows = d.ledger.pendingRows(sessionId, ROW_PAGE, d.backlogBefore);
35711
+ const rows = d.ledger.pendingRows(
35712
+ sessionId,
35713
+ ROW_PAGE,
35714
+ d.backlogBefore,
35715
+ scopeFilterOf(d.liveScope())
35716
+ );
37117
35717
  if (rows.length === 0) continue;
37118
35718
  const ready = [];
37119
35719
  for (const row of rows) {
@@ -37160,10 +35760,13 @@ async function drain(d) {
37160
35760
  skipped += captures.skipped;
37161
35761
  if (captures.stopped !== void 0) outcome = captures.stopped;
37162
35762
  }
37163
- if (outcome === "ok" && d.now() < deadline && d.ledger.pendingCaptureRows(1, d.now() - CAPTURE_GRACE_MS).length === 0) {
35763
+ if (outcome === "ok" && d.now() < deadline && !capturesOwed(scopeFilterOf(d.liveScope()))) {
37164
35764
  outcome = await drainStructural(deadline);
37165
35765
  }
37166
- if (outcome === "ok" && d.now() >= deadline && d.ledger.counts(d.backlogBefore).pending > 0) {
35766
+ const filter = scopeFilterOf(d.liveScope());
35767
+ const counts = d.ledger.counts(d.backlogBefore, filter);
35768
+ const countsScope = filter === void 0 ? "machine" : "scoped";
35769
+ if (outcome === "ok" && d.now() >= deadline && counts.pending > 0) {
37167
35770
  outcome = "interrupted";
37168
35771
  }
37169
35772
  return {
@@ -37172,28 +35775,60 @@ async function drain(d) {
37172
35775
  sent,
37173
35776
  skipped,
37174
35777
  // 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),
35778
+ // pay for a count over the capture grain on every pass. Through the same
35779
+ // filter as `counts`, so a marker on a capture outside the scope does not
35780
+ // hold `capturesPending` true, and both halves of `done` describe one scope.
35781
+ capturesPending: capturesOwed(filter),
35782
+ counts,
35783
+ countsScope,
37178
35784
  atMs: d.now()
37179
35785
  };
37180
35786
  }
35787
+ function scopeKeyOfRow(row) {
35788
+ const raw = row.attributes;
35789
+ if (typeof raw !== "string") return void 0;
35790
+ try {
35791
+ const bag = JSON.parse(raw);
35792
+ if (typeof bag !== "object" || bag === null || Array.isArray(bag)) return void 0;
35793
+ const key = bag.scope_key;
35794
+ return typeof key === "string" ? key : void 0;
35795
+ } catch {
35796
+ return void 0;
35797
+ }
35798
+ }
37181
35799
  async function drainCaptures(d, deadline, beat) {
37182
35800
  let sent = 0;
37183
35801
  let skipped = 0;
37184
35802
  for (; ; ) {
37185
35803
  if (d.now() >= deadline) return { sent, skipped, stopped: "interrupted" };
37186
- const rows = d.ledger.pendingCaptureRows(CAPTURE_BATCH_SIZE, d.now() - CAPTURE_GRACE_MS);
35804
+ const scope = d.liveScope();
35805
+ const rows = d.ledger.pendingCaptureRows(
35806
+ CAPTURE_BATCH_SIZE,
35807
+ d.now() - CAPTURE_GRACE_MS,
35808
+ scopeFilterOf(scope)
35809
+ );
37187
35810
  if (rows.length === 0) return { sent, skipped };
35811
+ const inScopeRows = [];
35812
+ for (const row of rows) {
35813
+ if (scope.mode === "machine") {
35814
+ inScopeRows.push({ row });
35815
+ continue;
35816
+ }
35817
+ const key = scopeKeyOfRow(row);
35818
+ if (key !== void 0 && scopeVerdict(scope, key) === "forward") {
35819
+ inScopeRows.push({ row, key });
35820
+ }
35821
+ }
35822
+ if (inScopeRows.length === 0) return { sent, skipped };
37188
35823
  const ready = [];
37189
35824
  const unbuildable = [];
37190
- for (const row of rows) {
35825
+ for (const { row, key } of inScopeRows) {
37191
35826
  const event = rebuildCapture(row);
37192
35827
  if (event === void 0) {
37193
35828
  unbuildable.push(row.id);
37194
35829
  continue;
37195
35830
  }
37196
- ready.push({ id: row.id, event });
35831
+ ready.push({ id: row.id, event: key === void 0 ? event : withScopedRepo(event, key) });
37197
35832
  }
37198
35833
  if (unbuildable.length > 0) {
37199
35834
  d.ledger.markSkipped(unbuildable, d.now());
@@ -37444,16 +36079,25 @@ async function runHistorySyncPass(base = defaultDataDir(), seams = {}) {
37444
36079
  // genuinely finishes. The capture lane does not: its subject grows with
37445
36080
  // every live session that fails to forward, so `phase` can go back to
37446
36081
  // '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.
36082
+ // either way — the first moment this machine owed the deployment nothing
36083
+ // its scope would send — which is why it is pinned rather than recomputed.
37449
36084
  // 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)
36085
+ // this was monotone because the structural lane only ever drained. The
36086
+ // capture lane makes `done` flap, and on a SCOPED attachment so does an
36087
+ // enroll: the counts cover only that scope's rows, so enrolling a
36088
+ // repository with unsent history can turn `done` false again, and an
36089
+ // unenroll can turn it true. Clearing on every flap would erase the pin and
36090
+ // re-stamp it on the next catch-up — so a consumer reading "when this
36091
+ // machine first caught up" would get the most recent one instead. Carrying
36092
+ // the previous value through the false case is what keeps the original
36093
+ // meaning.
36094
+ completedAtMs: previous?.completedAtMs ?? (done ? result.atMs : null),
36095
+ // Which population the totals above describe. Every pass from this build
36096
+ // on writes it, taken from THIS pass's own counts and never carried over
36097
+ // from the file read at the start of the pass, so `aka status` can tell a
36098
+ // scoped pass's numbers from those a build before it counted for
36099
+ // everything recorded on this machine, whose file has no such field.
36100
+ countsScope: result.countsScope
37457
36101
  });
37458
36102
  return result.outcome;
37459
36103
  } catch {
@@ -37463,21 +36107,21 @@ async function runHistorySyncPass(base = defaultDataDir(), seams = {}) {
37463
36107
 
37464
36108
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37465
36109
  import { spawn } from "child_process";
37466
- import { fileURLToPath as fileURLToPath2 } from "url";
36110
+ import { fileURLToPath } from "url";
37467
36111
  var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
37468
36112
 
37469
36113
  // ../../packages/plugin-runtime/src/attached/install-record.ts
37470
36114
  import { readFile as readFile2, stat } from "fs/promises";
37471
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
36115
+ import { basename as basename2, dirname as dirname4, join as join19, resolve as resolve2 } from "path";
37472
36116
 
37473
36117
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
37474
- import { readFileSync as readFileSync18 } from "fs";
36118
+ import { readFileSync as readFileSync12 } from "fs";
37475
36119
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
37476
36120
 
37477
36121
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37478
- import { randomUUID as randomUUID17 } from "crypto";
36122
+ import { randomUUID as randomUUID14 } from "crypto";
37479
36123
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
37480
- import { join as join30 } from "path";
36124
+ import { join as join20 } from "path";
37481
36125
 
37482
36126
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37483
36127
  import { rename as rename2 } from "fs/promises";
@@ -37486,8 +36130,8 @@ var TIMED_RETRIES = 4;
37486
36130
  var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
37487
36131
 
37488
36132
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
37489
- import { readFileSync as readFileSync19 } from "fs";
37490
- import { join as join31 } from "path";
36133
+ import { readFileSync as readFileSync13 } from "fs";
36134
+ import { join as join21 } from "path";
37491
36135
  var OUTCOME_KEYS = {
37492
36136
  ok: true,
37493
36137
  unauthorized: true,
@@ -37504,17 +36148,17 @@ var OUTCOMES2 = new Set(Object.keys(OUTCOME_KEYS));
37504
36148
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
37505
36149
 
37506
36150
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
37507
- import { statSync as statSync9 } from "fs";
37508
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
36151
+ import { statSync as statSync6 } from "fs";
36152
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
37509
36153
 
37510
36154
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37511
- import { randomUUID as randomUUID18 } from "crypto";
36155
+ import { randomUUID as randomUUID15 } from "crypto";
37512
36156
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37513
- import { join as join32 } from "path";
36157
+ import { join as join22 } from "path";
37514
36158
 
37515
36159
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37516
- import { readFileSync as readFileSync20 } from "fs";
37517
- import { join as join33 } from "path";
36160
+ import { readFileSync as readFileSync14 } from "fs";
36161
+ import { join as join23 } from "path";
37518
36162
 
37519
36163
  // ../../packages/plugin-runtime/src/attached/status.ts
37520
36164
  var REFUSAL_LINES = {
@@ -37532,7 +36176,7 @@ var OUTCOME_LINES = {
37532
36176
 
37533
36177
  // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
37534
36178
  import { spawn as spawn2 } from "child_process";
37535
- import { fileURLToPath as fileURLToPath3 } from "url";
36179
+ import { fileURLToPath as fileURLToPath2 } from "url";
37536
36180
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37537
36181
 
37538
36182
  // ../../packages/plugin-runtime/src/content-retention-pass.ts
@@ -37540,14 +36184,14 @@ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
37540
36184
 
37541
36185
  // ../../packages/plugin-runtime/src/content-retention-trigger.ts
37542
36186
  import { spawn as spawn3 } from "child_process";
37543
- import { fileURLToPath as fileURLToPath4 } from "url";
36187
+ import { fileURLToPath as fileURLToPath3 } from "url";
37544
36188
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
37545
36189
 
37546
36190
  // ../../packages/plugin-runtime/src/attached/factory.ts
37547
- import { hostname as hostname6 } from "os";
36191
+ import { hostname as hostname5 } from "os";
37548
36192
 
37549
36193
  // ../../packages/plugin-runtime/src/handle-session-start.ts
37550
- import { randomUUID as randomUUID19 } from "crypto";
36194
+ import { randomUUID as randomUUID16 } from "crypto";
37551
36195
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
37552
36196
 
37553
36197
  // src/history-sync.ts