@akasecurity/ai-tc-codex 0.9.16 → 0.9.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,888 +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_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
881
- var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
882
-
883
- // ../../packages/persistence/src/control-plane-credential.ts
884
- import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
885
- import { join as join2 } from "path";
886
6
 
887
7
  // ../../packages/schema/src/drizzle/deferred-migrations.ts
888
8
  var DEFERRED_MIGRATION_TAGS = [
@@ -1055,7 +175,7 @@ var MAX_TEMPORARY_MS = 24 * HOUR_MS;
1055
175
  var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
1056
176
 
1057
177
  // ../../packages/schema/src/invisible-padding.ts
1058
- var INVISIBLE_PADDING = /[\u00AD\u200B\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\u{E0001}\u{E0020}-\u{E007F}]/gu;
178
+ var INVISIBLE_PADDING = /[\u00AD\u061C\u180E\u200B\u200E\u200F\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\uFFF9-\uFFFB\u{E0001}\u{E0020}-\u{E007F}]/gu;
1059
179
  function stripInvisiblePadding(text) {
1060
180
  return text.replace(INVISIBLE_PADDING, "");
1061
181
  }
@@ -3873,9 +2993,9 @@ var asciiTabOrNewline = /[\t\n\r]/g;
3873
2993
  function stripTabAndNewline(value) {
3874
2994
  return value.replace(asciiTabOrNewline, "");
3875
2995
  }
3876
- function urlHostnameOk(url2, hostname7) {
3877
- hostname7.lastIndex = 0;
3878
- return hostname7.test(url2.hostname);
2996
+ function urlHostnameOk(url2, hostname6) {
2997
+ hostname6.lastIndex = 0;
2998
+ return hostname6.test(url2.hostname);
3879
2999
  }
3880
3000
  function urlProtocolOk(url2, protocol) {
3881
3001
  protocol.lastIndex = 0;
@@ -20795,13 +19915,16 @@ function serviceTierMultiplier(tier) {
20795
19915
  if (tier === void 0) return 1;
20796
19916
  return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
20797
19917
  }
19918
+ function promptTokensOf(usage) {
19919
+ return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
19920
+ }
20798
19921
  function costOf(price, usage) {
20799
19922
  const metered = [
20800
19923
  [usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
20801
19924
  [usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
20802
19925
  [usage.cacheReadTokens ?? 0, price.cacheRead]
20803
19926
  ];
20804
- const band = price.longContext !== null && (usage.inputTokens ?? 0) > price.longContext.thresholdInputTokens ? price.longContext : null;
19927
+ const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
20805
19928
  if (band !== null && (band.input === null || band.output === null)) return null;
20806
19929
  const inputRate = band?.input ?? price.input;
20807
19930
  const outputRate = band?.output ?? price.output;
@@ -20874,8 +19997,8 @@ var PLATFORM_HOSTING = /* @__PURE__ */ new Map([
20874
19997
  ["ollama", "local"],
20875
19998
  ["local", "local"]
20876
19999
  ]);
20877
- function hostingFor(platform2) {
20878
- return PLATFORM_HOSTING.get(platform2) ?? "api";
20000
+ function hostingFor(platform) {
20001
+ return PLATFORM_HOSTING.get(platform) ?? "api";
20879
20002
  }
20880
20003
  var FIRST_PARTY = /* @__PURE__ */ new Map([
20881
20004
  ["anthropic", "anthropic"],
@@ -20889,8 +20012,8 @@ var FIRST_PARTY = /* @__PURE__ */ new Map([
20889
20012
  function firstPartyPlatformFor(vendor2) {
20890
20013
  return FIRST_PARTY.get(vendor2) ?? null;
20891
20014
  }
20892
- function isFirstParty(vendor2, platform2) {
20893
- return FIRST_PARTY.get(vendor2) === platform2;
20015
+ function isFirstParty(vendor2, platform) {
20016
+ return FIRST_PARTY.get(vendor2) === platform;
20894
20017
  }
20895
20018
  var PLATFORM_NAMESPACES = Object.freeze([
20896
20019
  "anthropic",
@@ -20951,14 +20074,14 @@ var ModelVendorBuilder = class {
20951
20074
  );
20952
20075
  }
20953
20076
  for (const ref of spec.on ?? []) {
20954
- const { platform: platform2, price, retention, region } = normalizeRef(ref);
20955
- const firstParty = isFirstParty(this.vendor, platform2);
20956
- const hosting = hostingFor(platform2);
20077
+ const { platform, price, retention, region } = normalizeRef(ref);
20078
+ const firstParty = isFirstParty(this.vendor, platform);
20079
+ const hosting = hostingFor(platform);
20957
20080
  const isSelfHosted = hosting === "local";
20958
20081
  platforms.set(
20959
- platform2,
20082
+ platform,
20960
20083
  Object.freeze({
20961
- platform: platform2,
20084
+ platform,
20962
20085
  hosting,
20963
20086
  firstParty,
20964
20087
  price: price ?? (isSelfHosted ? ZERO_PRICE : firstParty ? spec.price ?? null : null),
@@ -21011,35 +20134,35 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
21011
20134
  var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
21012
20135
  var BEDROCK_REVISION_RE = /:\d+$/u;
21013
20136
  var VERTEX_VERSION_RE = /@[\w-]+$/u;
21014
- var DATED_SUFFIX_RE = /-\d{8}$/u;
20137
+ var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
21015
20138
  function stripPlatformDecorations(model) {
21016
20139
  let id = model.trim();
21017
- let platform2 = null;
20140
+ let platform = null;
21018
20141
  if (GEO_PREFIX_RE.test(id)) {
21019
20142
  id = id.replace(GEO_PREFIX_RE, "");
21020
- platform2 = "bedrock";
20143
+ platform = "bedrock";
21021
20144
  }
21022
20145
  if (NAMESPACE_DOT_RE.test(id)) {
21023
20146
  id = id.replace(NAMESPACE_DOT_RE, "");
21024
- platform2 ??= "bedrock";
20147
+ platform ??= "bedrock";
21025
20148
  }
21026
20149
  if (BEDROCK_VERSION_RE.test(id)) {
21027
20150
  id = id.replace(BEDROCK_VERSION_RE, "");
21028
- platform2 ??= "bedrock";
20151
+ platform ??= "bedrock";
21029
20152
  } else if (BEDROCK_REVISION_RE.test(id)) {
21030
20153
  id = id.replace(BEDROCK_REVISION_RE, "");
21031
- platform2 ??= "bedrock";
20154
+ platform ??= "bedrock";
21032
20155
  }
21033
20156
  if (VERTEX_VERSION_RE.test(id)) {
21034
20157
  id = id.replace(VERTEX_VERSION_RE, "");
21035
- platform2 ??= "vertex";
20158
+ platform ??= "vertex";
21036
20159
  }
21037
20160
  if (NAMESPACE_SLASH_RE.test(id)) {
21038
20161
  id = id.replace(NAMESPACE_SLASH_RE, "");
21039
20162
  } else if (GATEWAY_VENDOR_SLASH_RE.test(id)) {
21040
20163
  id = id.replace(GATEWAY_VENDOR_SLASH_RE, "");
21041
20164
  }
21042
- return { id, platform: platform2 };
20165
+ return { id, platform };
21043
20166
  }
21044
20167
  function buildModelIndex(entries) {
21045
20168
  const byId = /* @__PURE__ */ new Map();
@@ -21056,19 +20179,19 @@ function resolveModel(raw, index) {
21056
20179
  if (exact !== void 0) {
21057
20180
  return { entry: exact, canonicalId: raw, platform: null, raw };
21058
20181
  }
21059
- const { id, platform: platform2 } = stripPlatformDecorations(raw);
20182
+ const { id, platform } = stripPlatformDecorations(raw);
21060
20183
  const stripped = index.byId.get(id);
21061
20184
  if (stripped !== void 0) {
21062
- return { entry: stripped, canonicalId: id, platform: platform2, raw };
20185
+ return { entry: stripped, canonicalId: id, platform, raw };
21063
20186
  }
21064
20187
  if (DATED_SUFFIX_RE.test(id)) {
21065
20188
  const undated = id.replace(DATED_SUFFIX_RE, "");
21066
20189
  const byDate = index.byId.get(undated);
21067
20190
  if (byDate !== void 0) {
21068
- return { entry: byDate, canonicalId: undated, platform: platform2, raw };
20191
+ return { entry: byDate, canonicalId: undated, platform, raw };
21069
20192
  }
21070
20193
  }
21071
- return { entry: null, canonicalId: raw, platform: platform2, raw };
20194
+ return { entry: null, canonicalId: raw, platform, raw };
21072
20195
  }
21073
20196
 
21074
20197
  // ../../packages/schema/src/model/catalog.ts
@@ -21161,7 +20284,7 @@ anthropic.model("claude-haiku-4-5", {
21161
20284
  name: "Claude Haiku 4.5",
21162
20285
  ctx: 2e5,
21163
20286
  maxOut: 64e3,
21164
- // Reviewed: fast/cheap tier, no flagged reasoning or code specialisation.
20287
+ // Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
21165
20288
  capability: null,
21166
20289
  price: anthropicPrice(1, 5, 0.1),
21167
20290
  // The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
@@ -21292,6 +20415,11 @@ openai.model("gpt-4o", {
21292
20415
  price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
21293
20416
  on: [...OPENAI_RESELLERS]
21294
20417
  });
20418
+ openai.model("gpt-4o-2024-05-13", {
20419
+ name: "GPT-4o (2024-05-13)",
20420
+ price: tokenPrice(5, 15),
20421
+ on: [...OPENAI_RESELLERS]
20422
+ });
21295
20423
  openai.model("gpt-4o-mini", {
21296
20424
  name: "GPT-4o mini",
21297
20425
  price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
@@ -21311,6 +20439,24 @@ openai.model("o3", {
21311
20439
  price: tokenPrice(2, 8, { cacheRead: 0.5 }),
21312
20440
  on: [...OPENAI_RESELLERS]
21313
20441
  });
20442
+ openai.model("text-embedding-3-small", {
20443
+ name: "text-embedding-3-small",
20444
+ capability: "embedding",
20445
+ price: tokenPrice(0.02, 0),
20446
+ on: [...OPENAI_RESELLERS]
20447
+ });
20448
+ openai.model("text-embedding-3-large", {
20449
+ name: "text-embedding-3-large",
20450
+ capability: "embedding",
20451
+ price: tokenPrice(0.13, 0),
20452
+ on: [...OPENAI_RESELLERS]
20453
+ });
20454
+ openai.model("text-embedding-ada-002", {
20455
+ name: "text-embedding-ada-002",
20456
+ capability: "embedding",
20457
+ price: tokenPrice(0.1, 0),
20458
+ on: [...OPENAI_RESELLERS]
20459
+ });
21314
20460
  openai.model("gpt-oss-120b", {
21315
20461
  name: "GPT-OSS 120B",
21316
20462
  openWeights: true,
@@ -21597,10 +20743,21 @@ var MODEL_ENTRIES = Object.freeze([
21597
20743
  ...alibaba.models(),
21598
20744
  ...amazon.models()
21599
20745
  ]);
20746
+ var LONG_CONTEXT_THRESHOLDS = Object.freeze(
20747
+ [
20748
+ ...new Set(
20749
+ MODEL_ENTRIES.flatMap(
20750
+ (entry) => [...entry.platforms.values()].flatMap(
20751
+ (offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
20752
+ )
20753
+ )
20754
+ )
20755
+ ].sort((a, b) => a - b)
20756
+ );
21600
20757
  var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
21601
20758
 
21602
20759
  // ../../packages/schema/src/model/governance.ts
21603
- var ModelCapability = external_exports.enum(["reasoning", "code"]);
20760
+ var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
21604
20761
  var DataRetention = external_exports.enum([
21605
20762
  "zero_retention",
21606
20763
  "no_storage",
@@ -21696,16 +20853,16 @@ function platformForProvider(provider) {
21696
20853
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
21697
20854
  }
21698
20855
  function isLocalProvider(provider) {
21699
- const platform2 = platformForProvider(provider);
21700
- return platform2 !== null && hostingFor(platform2) === "local";
20856
+ const platform = platformForProvider(provider);
20857
+ return platform !== null && hostingFor(platform) === "local";
21701
20858
  }
21702
20859
  function priceFor(provider, model) {
21703
20860
  if (isLocalProvider(provider)) return ZERO_PRICE;
21704
20861
  const resolved = resolveModel(model, MODEL_INDEX);
21705
20862
  if (resolved.entry === null) return null;
21706
- const platform2 = resolved.platform ?? platformForProvider(provider);
21707
- if (platform2 === null) return null;
21708
- return resolved.entry.platforms.get(platform2)?.price ?? null;
20863
+ const platform = resolved.platform ?? platformForProvider(provider);
20864
+ if (platform === null) return null;
20865
+ return resolved.entry.platforms.get(platform)?.price ?? null;
21709
20866
  }
21710
20867
  var defaultCostModel = {
21711
20868
  normalizeModelId(provider, model) {
@@ -21731,7 +20888,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
21731
20888
 
21732
20889
  // ../../packages/schema/src/token/token-report.ts
21733
20890
  var num = (value) => value ?? 0;
21734
- function costUsageOf(a) {
20891
+ function costUsageOf(a, promptTokens) {
21735
20892
  const usage = {
21736
20893
  inputTokens: num(a.input_tokens),
21737
20894
  outputTokens: num(a.output_tokens),
@@ -21741,11 +20898,12 @@ function costUsageOf(a) {
21741
20898
  webSearchRequests: num(a.web_search_requests)
21742
20899
  };
21743
20900
  if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
20901
+ if (promptTokens !== void 0) usage.promptTokens = promptTokens;
21744
20902
  return usage;
21745
20903
  }
21746
20904
  function buildTokenReports(leaves, costModel) {
21747
20905
  const bySession = /* @__PURE__ */ new Map();
21748
- for (const { sessionId, attributes } of leaves) {
20906
+ for (const { sessionId, attributes, promptTokens } of leaves) {
21749
20907
  const provider = attributes.provider ?? "unknown";
21750
20908
  const model = attributes.model ?? "unknown";
21751
20909
  const key = `${provider} ${model}`;
@@ -21764,7 +20922,8 @@ function buildTokenReports(leaves, costModel) {
21764
20922
  cacheCreation: 0,
21765
20923
  cacheRead: 0,
21766
20924
  costUsd: 0,
21767
- priced: false
20925
+ priced: false,
20926
+ partial: false
21768
20927
  };
21769
20928
  rollups.set(key, acc);
21770
20929
  }
@@ -21772,8 +20931,14 @@ function buildTokenReports(leaves, costModel) {
21772
20931
  acc.output += num(attributes.output_tokens);
21773
20932
  acc.cacheCreation += num(attributes.cache_creation_input_tokens);
21774
20933
  acc.cacheRead += num(attributes.cache_read_input_tokens);
21775
- const leafCost = costModel.costFor({ provider, model, usage: costUsageOf(attributes) });
21776
- if (leafCost !== null) {
20934
+ const leafCost = costModel.costFor({
20935
+ provider,
20936
+ model,
20937
+ usage: costUsageOf(attributes, promptTokens)
20938
+ });
20939
+ if (leafCost === null) {
20940
+ acc.partial = true;
20941
+ } else {
21777
20942
  acc.costUsd += leafCost;
21778
20943
  acc.priced = true;
21779
20944
  }
@@ -21789,9 +20954,8 @@ function buildTokenReports(leaves, costModel) {
21789
20954
  const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
21790
20955
  totalTokens += rollupTotal;
21791
20956
  const estimatedCostUsd = acc.priced ? acc.costUsd : null;
21792
- if (estimatedCostUsd === null) {
21793
- anyUnpriced = true;
21794
- } else {
20957
+ if (acc.partial) anyUnpriced = true;
20958
+ if (estimatedCostUsd !== null) {
21795
20959
  anyPriced = true;
21796
20960
  costUsd += estimatedCostUsd;
21797
20961
  }
@@ -21814,7 +20978,7 @@ function buildTokenReports(leaves, costModel) {
21814
20978
  totalTokens,
21815
20979
  // Σ of the PRICED rollups; null when none had a known price.
21816
20980
  estimatedCostUsd: anyPriced ? costUsd : null,
21817
- // Any unknown (provider, model) means the total understates real spend.
20981
+ // Any call priced to null means the total understates real spend.
21818
20982
  costIsPartial: anyUnpriced
21819
20983
  });
21820
20984
  }
@@ -22516,6 +21680,11 @@ var CaptureAttributes = external_exports.object({
22516
21680
  // here too. The full statement is on EventMetadata.redactDegradedTo; it is
22517
21681
  // repeated rather than referenced because a store reader opens this file.
22518
21682
  redact_degraded_to: ActionTaken.optional(),
21683
+ // Why a capture has no content and no findings: its field was refused
21684
+ // because its bounded scan did not finish (see EventMetadata.scanIncomplete,
21685
+ // whose value this is). Absent on every capture that was scanned, so a
21686
+ // reader can tell a refused row from an empty clean one.
21687
+ scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
22519
21688
  // The scope key this capture was stamped with: the canonical repository
22520
21689
  // (`host/owner/repo`) of the path the capture names (a relative path is read
22521
21690
  // against its working directory), else of its own working directory, or a
@@ -22693,8 +21862,9 @@ var SessionTokenReport = external_exports.object({
22693
21862
  totalTokens: external_exports.number().int().nonnegative(),
22694
21863
  // Σ of the PRICED rollups only; null when no rollup had a known price.
22695
21864
  estimatedCostUsd: external_exports.number().nullable(),
22696
- // True whenever any rollup has a null cost (unknown provider/model), so the
22697
- // total understates real spend — the UI renders `≥ $X` instead of a falsely
21865
+ // True whenever any call priced to null (an unknown provider/model, or a call
21866
+ // over a long-context threshold whose rate is unpublished), so the total
21867
+ // understates real spend — the UI renders `≥ $X` instead of a falsely
22698
21868
  // precise figure rather than silently dropping the unpriced calls.
22699
21869
  costIsPartial: external_exports.boolean()
22700
21870
  });
@@ -23571,7 +22741,15 @@ var StorePostureSnapshot = external_exports.object({
23571
22741
  policyCounts: StorePosturePolicyCounts,
23572
22742
  // OPTIONAL, not nullable: a reporter that predates this member keeps
23573
22743
  // getting its 200 without a payload change.
23574
- plugin: StorePosturePlugin.optional()
22744
+ plugin: StorePosturePlugin.optional(),
22745
+ // OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
22746
+ // machine attachment omits it, so its body is byte for byte the one it
22747
+ // sent before this member existed. Absent therefore means machine-wide OR
22748
+ // a reporter older than this member, never "scoped". Both values parse, so
22749
+ // a sender that one day spells `machine` breaks no receiver; any other
22750
+ // value fails the whole snapshot, which is why the reporter sends a
22751
+ // constant and never the raw mode.
22752
+ attachmentMode: AttachmentMode.optional()
23575
22753
  }).meta({ id: "StorePostureSnapshot" });
23576
22754
  var CAPTURE_VERSION_PREFIX = "capture/";
23577
22755
  var RecordAuditEventRequest = AuditEventInput.extend({
@@ -23848,7 +23026,19 @@ var EventMetadata = external_exports.object({
23848
23026
  // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
23849
23027
  // Closing either means moving the reason onto the finding row, which
23850
23028
  // already carries its own action.
23851
- redactDegradedTo: ActionTaken.optional()
23029
+ redactDegradedTo: ActionTaken.optional(),
23030
+ // Set when this capture's field was REFUSED rather than scanned: a hook
23031
+ // bounds the scan of a large field (see `LargeInputScanOptions` in
23032
+ // @akasecurity/plugin-sdk), and a scan that did not finish blocks the
23033
+ // field instead of letting it through unscanned.
23034
+ //
23035
+ // - 'timeout': the bounded scan ran out of time.
23036
+ // - 'unavailable': no worker could run it.
23037
+ //
23038
+ // A refused row stores '' as its content and has no findings, which is
23039
+ // exactly what a clean, empty capture looks like — this marker is the only
23040
+ // thing that tells the two apart. Absent on every capture that was scanned.
23041
+ scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
23852
23042
  }).meta({ id: "EventMetadata" });
23853
23043
  var Event = external_exports.object({
23854
23044
  id: external_exports.guid(),
@@ -24018,7 +23208,7 @@ var Rule = external_exports.strictObject({
24018
23208
  postValidators: external_exports.array(PostValidatorRef).optional(),
24019
23209
  requiresNearby: RequiresNearby.optional(),
24020
23210
  examples: external_exports.array(external_exports.string()).optional(),
24021
- // Whether the matched text is itself sensitive. Absent means 'value'.
23211
+ // Whether the matched text is itself sensitive (see RuleEvidence).
24022
23212
  evidence: RuleEvidence.optional()
24023
23213
  }).meta({ id: "Rule" });
24024
23214
  var Author = external_exports.object({
@@ -24110,7 +23300,13 @@ var DetectionRule = external_exports.object({
24110
23300
  // Representative matching strings the rule author shipped with the rule. The
24111
23301
  // cheapest honest answer to "show me what this rule catches" — every bundled
24112
23302
  // rule has them, and they are already in the stored snapshot.
24113
- examples: external_exports.array(external_exports.string()).optional()
23303
+ examples: external_exports.array(external_exports.string()).optional(),
23304
+ // The rule's DECLARED evidence, as stored. Absent defers to the engine's
23305
+ // classification (ruleEvidence in @akasecurity/detections): a bundled
23306
+ // code-flaw rule reads as 'code' and anything else as 'value', and a rule
23307
+ // in a value category (secret/pii/financial/phi) is always 'value',
23308
+ // whatever it declares.
23309
+ evidence: RuleEvidence.optional()
24114
23310
  }).meta({ id: "DetectionRule" });
24115
23311
  var DetectionUpdate = external_exports.object({
24116
23312
  available: external_exports.boolean(),
@@ -24178,8 +23374,10 @@ var ImportDetectionRequest = external_exports.object({
24178
23374
  }).meta({ id: "ImportDetectionRequest" });
24179
23375
 
24180
23376
  // ../../packages/schema/src/zod/detection-build.ts
24181
- function optional2(key, parsed2, raw) {
24182
- if (raw === void 0 || !parsed2.success || parsed2.data === void 0) return {};
23377
+ function optional2(key, raw, parse4) {
23378
+ if (raw === void 0) return {};
23379
+ const parsed2 = parse4(raw);
23380
+ if (!parsed2.success || parsed2.data === void 0) return {};
24183
23381
  return { [key]: parsed2.data };
24184
23382
  }
24185
23383
  function isStringArray(value) {
@@ -24214,10 +23412,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24214
23412
  category: r.category,
24215
23413
  severity: r.severity,
24216
23414
  matcher: parsed2.data,
24217
- // The rest of what decides whether this rule fires. Carried so a consumer
24218
- // re-running the rule (a preview, a tester) evaluates what the engine
24219
- // evaluates rather than a matcher stripped of its guards — half the
24220
- // bundled catalog carries at least one of these.
23415
+ // `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
23416
+ // decides whether this rule fires. Carried so a consumer re-running the
23417
+ // rule (a preview, a tester) evaluates what the engine evaluates rather
23418
+ // than a matcher stripped of its guards — half the bundled catalog
23419
+ // carries at least one of these. `examples` and `evidence` describe the
23420
+ // rule and never gate a match.
24221
23421
  //
24222
23422
  // Enrichment is deliberately per-field and best-effort, NOT a whole-rule
24223
23423
  // `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
@@ -24227,18 +23427,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
24227
23427
  // test should stay exactly what it was, namely a renderable matcher. A
24228
23428
  // field that fails validation is omitted, which reads as "not set" and is
24229
23429
  // the same thing the consumer saw before this change.
24230
- ...optional2("appliesTo", AppliesTo.safeParse(r.appliesTo), r.appliesTo),
23430
+ ...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
24231
23431
  ...optional2(
24232
23432
  "postValidators",
24233
- PostValidatorRef.array().safeParse(r.postValidators),
24234
- r.postValidators
23433
+ r.postValidators,
23434
+ (v) => PostValidatorRef.array().safeParse(v)
24235
23435
  ),
24236
- ...optional2("requiresNearby", RequiresNearby.safeParse(r.requiresNearby), r.requiresNearby),
23436
+ ...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
24237
23437
  ...optional2(
24238
23438
  "examples",
24239
- { success: isStringArray(r.examples), data: r.examples },
24240
- r.examples
24241
- )
23439
+ r.examples,
23440
+ (v) => isStringArray(v) ? { success: true, data: v } : { success: false }
23441
+ ),
23442
+ ...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
24242
23443
  }
24243
23444
  ];
24244
23445
  });
@@ -24931,11 +24132,14 @@ var PolicyBundle = external_exports.object({
24931
24132
  ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
24932
24133
  // Model ids (the raw `model` string a harness reports, e.g.
24933
24134
  // `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
24934
- // a session onto one (PreModelSwitch) and refuses a turn that would run on
24935
- // one (UserPromptSubmit). Optional so an older backend — and an older
24936
- // on-disk cache — still parses; consumers read `?? []`, which is the
24937
- // unenforced behaviour that predates this field and the safe direction to
24938
- // default.
24135
+ // a session onto one (PreModelSwitch), refuses a turn that would run on one
24136
+ // (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
24137
+ // wherever the organization governs the event: everywhere on a
24138
+ // machine-wide attachment, and only in enrolled repositories on a scoped
24139
+ // one (the plugin runtime's `governanceApplies`).
24140
+ // Optional so an older backend — and an older on-disk cache — still
24141
+ // parses; consumers read `?? []`, which is the unenforced behaviour that
24142
+ // predates this field and the safe direction to default.
24939
24143
  //
24940
24144
  // Ids, not display names: the governance decision is keyed on the exact
24941
24145
  // string the harness reports (`model_status_override.versionId` in the
@@ -25394,6 +24598,8 @@ var AttachmentScopeEntry = external_exports.object({
25394
24598
  });
25395
24599
  var AttachmentScope = external_exports.object({
25396
24600
  endpoint: external_exports.string().min(1),
24601
+ tenantName: PluginWhoami.shape.tenantName.optional(),
24602
+ userEmail: PluginWhoami.shape.userEmail.optional(),
25397
24603
  entries: external_exports.array(AttachmentScopeEntry)
25398
24604
  });
25399
24605
  var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
@@ -25406,7 +24612,13 @@ function parseAttachmentScope(raw) {
25406
24612
  const entry = AttachmentScopeEntry.safeParse(candidate);
25407
24613
  if (entry.success) entries.push(entry.data);
25408
24614
  }
25409
- return { endpoint: envelope.data.endpoint, entries };
24615
+ const { endpoint, tenantName, userEmail } = envelope.data;
24616
+ return {
24617
+ endpoint,
24618
+ ...tenantName === void 0 ? {} : { tenantName },
24619
+ ...userEmail === void 0 ? {} : { userEmail },
24620
+ entries
24621
+ };
25410
24622
  } catch {
25411
24623
  return void 0;
25412
24624
  }
@@ -25643,6 +24855,7 @@ function toCaptureAttributes(event) {
25643
24855
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
25644
24856
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
25645
24857
  ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
24858
+ ...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
25646
24859
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
25647
24860
  // has ever populated either), but every legacy metadata key still rides
25648
24861
  // the bag rather than being silently dropped — CaptureAttributes'
@@ -25771,6 +24984,27 @@ var ManagedSettings = external_exports.object({
25771
24984
  };
25772
24985
  }).meta({ id: "ManagedSettings" });
25773
24986
 
24987
+ // ../../packages/schema/src/zod/mod-policy-snapshot.ts
24988
+ var MOD_POLICY_SNAPSHOT_VERSION = 1;
24989
+ var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
24990
+ var ModPolicySnapshot = external_exports.object({
24991
+ version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
24992
+ generatedAt: external_exports.iso.datetime(),
24993
+ // The complete effective ruleset, as the hook's runtime scans with it: the
24994
+ // user's enabled installed packs (user-modified and custom packs included).
24995
+ // Absent means the store holds no authoritative snapshot, and the reader
24996
+ // scans with the packs it ships — the hook's own fallback.
24997
+ rules: external_exports.array(Rule).optional(),
24998
+ // Rule-targeted actions (first enabled policy per rule wins).
24999
+ ruleActions: external_exports.record(external_exports.string(), ActionTaken),
25000
+ // The resolved action per detection category.
25001
+ categoryActions: external_exports.record(external_exports.string(), ActionTaken),
25002
+ // Rules with an active exception grant. Honouring a grant means matching a
25003
+ // keyed fingerprint of the value and consuming a use, which only the hook can
25004
+ // do, so the mod leaves a finding of one of these rules for the hook to decide.
25005
+ exceptionRuleIds: external_exports.array(external_exports.string())
25006
+ }).meta({ id: "ModPolicySnapshot" });
25007
+
25774
25008
  // ../../packages/schema/src/zod/project-files.ts
25775
25009
  var ProjectFileInput = external_exports.object({
25776
25010
  path: external_exports.string().min(1),
@@ -26091,7 +25325,16 @@ var AttachInput = external_exports.object({
26091
25325
  // 200 matches the tenantName bound beside it in control-plane.ts; nothing
26092
25326
  // renders a longer one usefully.
26093
25327
  label: printable(200).optional(),
26094
- accessKey: external_exports.string()
25328
+ accessKey: external_exports.string(),
25329
+ // How much of this machine the attachment is for: everything, or only the
25330
+ // repositories its user enrolls. Optional, so an input without it still
25331
+ // parses; what an absent mode means is for whatever reads it to decide, not
25332
+ // this shape. This member validates the VALUE rather than leaving that to the
25333
+ // call site, a deliberate exception to this module's shape-only rule: a shape
25334
+ // rejection names the field, so a value that is not a mode is refused as a bad
25335
+ // `mode` rather than stripped or passed on. The dashboard's attach action reads
25336
+ // it as the mode to attach in.
25337
+ mode: AttachmentMode.optional()
26095
25338
  });
26096
25339
 
26097
25340
  // ../../packages/schema/src/zod/triage.ts
@@ -26377,6 +25620,18 @@ function fromCaptureStatusAttributes(bag) {
26377
25620
  return parsedStatus.success ? parsedStatus.data : null;
26378
25621
  }
26379
25622
 
25623
+ // ../../packages/persistence/src/attached-derived.ts
25624
+ import { rmSync } from "fs";
25625
+ import { join } from "path";
25626
+ var POLICY_CACHE_FILENAME = "policy-cache.json";
25627
+ var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
25628
+ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
25629
+ var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
25630
+
25631
+ // ../../packages/persistence/src/control-plane-credential.ts
25632
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
25633
+ import { join as join2 } from "path";
25634
+
26380
25635
  // ../../packages/persistence/src/paths.ts
26381
25636
  import {
26382
25637
  chmodSync,
@@ -26523,6 +25778,14 @@ function repairOrRefuseMode(file2) {
26523
25778
  }
26524
25779
  return "ok";
26525
25780
  }
25781
+ function asReadableCredential(value) {
25782
+ const result = AttachedCredentialAny.safeParse(value);
25783
+ if (!result.success) return null;
25784
+ if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
25785
+ return null;
25786
+ }
25787
+ return result.data;
25788
+ }
26526
25789
  function readControlPlaneCredentialFile(settingsDir2, connection) {
26527
25790
  const file2 = controlPlaneCredentialPath(settingsDir2);
26528
25791
  let raw;
@@ -26541,20 +25804,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
26541
25804
  } catch {
26542
25805
  return { usable: false, reason: "malformed" };
26543
25806
  }
26544
- const result = AttachedCredential.safeParse(parsed2);
26545
- if (!result.success) return { usable: false, reason: "malformed" };
26546
- if (!isSafeEndpoint(result.data.endpoint)) {
25807
+ const credential = asReadableCredential(parsed2);
25808
+ if (credential === null) return { usable: false, reason: "malformed" };
25809
+ if (!isSafeEndpoint(credential.endpoint)) {
26547
25810
  return { usable: false, reason: "unsafe-endpoint" };
26548
25811
  }
26549
- if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
25812
+ if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
26550
25813
  return {
26551
25814
  usable: false,
26552
25815
  reason: "endpoint-mismatch",
26553
- credentialEndpoint: result.data.endpoint,
25816
+ credentialEndpoint: credential.endpoint,
26554
25817
  settingsEndpoint: connection.endpoint
26555
25818
  };
26556
25819
  }
26557
- return { usable: true, credential: result.data };
25820
+ return { usable: true, credential };
26558
25821
  }
26559
25822
  function readControlPlaneCredential(settingsDir2, connection) {
26560
25823
  const read = readControlPlaneCredentialFile(settingsDir2, connection);
@@ -26563,7 +25826,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
26563
25826
 
26564
25827
  // ../../packages/persistence/src/database.ts
26565
25828
  import { randomUUID as randomUUID11 } from "crypto";
26566
- import { dirname as dirname2, join as join7, sep } from "path";
25829
+ import { dirname as dirname2, join as join8, sep } from "path";
26567
25830
  import { DatabaseSync } from "node:sqlite";
26568
25831
 
26569
25832
  // ../../packages/persistence/src/ids.ts
@@ -26617,6 +25880,7 @@ function uuidFromDigest(digest) {
26617
25880
  function captureWireId(sessionId, contentHash, filePath = null) {
26618
25881
  return uuidFromDigest(captureId(sessionId, contentHash, filePath));
26619
25882
  }
25883
+ var DOT = ".".charCodeAt(0);
26620
25884
 
26621
25885
  // ../../packages/persistence/src/internal/snapshot.ts
26622
25886
  import { randomUUID } from "crypto";
@@ -26944,6 +26208,25 @@ function scopeKeysParam(scopeKeys) {
26944
26208
  var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
26945
26209
  FROM audit_events AS session_root
26946
26210
  WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
26211
+ var COUNTED_IN_SCOPE = `
26212
+ AND ${inScope("scope_key")}
26213
+ AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
26214
+ var DRAIN_TOTALS = `SELECT
26215
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
26216
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
26217
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26218
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
26219
+ THEN 1 ELSE 0 END) AS skipped,
26220
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26221
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
26222
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
26223
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
26224
+ FROM audit_events
26225
+ WHERE event_type IN (${TYPE_LIST})`;
26226
+ var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
26227
+ FROM audit_events
26228
+ WHERE synced_at = ${String(SKIPPED)}
26229
+ AND event_type IN (${CAPTURE_TYPE_LIST})`;
26947
26230
  var ROW_COLUMNS = `id,
26948
26231
  parent_id AS parentId,
26949
26232
  root_session_id AS rootSessionId,
@@ -27019,7 +26302,7 @@ var SqliteHistorySyncRepository = class {
27019
26302
  );
27020
26303
  this.scopedCaptureRowsStmt = db.prepare(
27021
26304
  `SELECT ${ROW_COLUMNS}
27022
- FROM audit_events
26305
+ FROM audit_events INDEXED BY idx_audit_scope_owed
27023
26306
  WHERE synced_at IS NULL
27024
26307
  AND sync_claimed_at IS NULL
27025
26308
  AND outbox_owed = 1
@@ -27072,40 +26355,28 @@ var SqliteHistorySyncRepository = class {
27072
26355
  );
27073
26356
  this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
27074
26357
  FROM audit_events${COUNTED_SCOPE}`);
26358
+ this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
26359
+ FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
27075
26360
  this.partitionByKindStmt = db.prepare(
27076
26361
  `SELECT event_type AS kind,${PARTITION_BUCKETS}
27077
26362
  FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
27078
26363
  GROUP BY event_type`
27079
26364
  );
27080
- this.countsStmt = db.prepare(
27081
- `SELECT
27082
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27083
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27084
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27085
- AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
27086
- THEN 1 ELSE 0 END) AS skipped,
27087
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27088
- AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
27089
- SUM(CASE WHEN synced_at = ${String(SKIPPED)}
27090
- AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
27091
- FROM audit_events
27092
- WHERE event_type IN (${TYPE_LIST})`
26365
+ this.scopedPartitionByKindStmt = db.prepare(
26366
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
26367
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
26368
+ GROUP BY event_type`
27093
26369
  );
27094
- this.captureSkipCountStmt = db.prepare(
27095
- // EVERY sentinel capture, whatever the reason — deliberately NOT split the
27096
- // way the structural totals are. The split exists because a refusal is
27097
- // terminal only against the deployment that gave it, and the structural
27098
- // re-arm frees it on a change of deployment. The capture lane has no such
27099
- // escape: re-arming a capture would offer one deployment's undelivered
27100
- // prompts, with their text, to a deployment that never saw them, which is
27101
- // exactly what disownCapturesStmt exists to prevent. So on this lane both
27102
- // reasons mean the same thing — this row will not be sent — and splitting
27103
- // them would put refused captures in a bucket nothing reads and nothing
27104
- // frees.
27105
- `SELECT COUNT(*) AS skipped
27106
- FROM audit_events
27107
- WHERE synced_at = ${String(SKIPPED)}
27108
- AND event_type IN (${CAPTURE_TYPE_LIST})`
26370
+ this.countsStmt = db.prepare(DRAIN_TOTALS);
26371
+ this.scopedCountsStmt = db.prepare(
26372
+ `${DRAIN_TOTALS}
26373
+ AND ${inScope("scope_key")}
26374
+ AND ${inScope(ROOT_SCOPE_KEY)}`
26375
+ );
26376
+ this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
26377
+ this.scopedCaptureSkipCountStmt = db.prepare(
26378
+ `${CAPTURE_SKIPS}
26379
+ AND ${inScope("scope_key")}`
27109
26380
  );
27110
26381
  this.fingerprintStmt = db.prepare(
27111
26382
  `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
@@ -27219,6 +26490,10 @@ var SqliteHistorySyncRepository = class {
27219
26490
  scopedCaptureRowsStmt;
27220
26491
  scopedCaptureBacklogOwedStmt;
27221
26492
  markScopeCapturesOwedStmt;
26493
+ scopedPartitionStmt;
26494
+ scopedPartitionByKindStmt;
26495
+ scopedCountsStmt;
26496
+ scopedCaptureSkipCountStmt;
27222
26497
  /**
27223
26498
  * The masked detections recorded against one tool call.
27224
26499
  *
@@ -27440,7 +26715,29 @@ var SqliteHistorySyncRepository = class {
27440
26715
  * in" — and a machine that has never attached has no boundary to pass, so
27441
26716
  * requiring one would force a caller to invent one and report the whole store
27442
26717
  * as queued.
26718
+ *
26719
+ * `scopeKeys` is a scoped attachment's filter: every bucket then counts only
26720
+ * the rows that pass the drain's reachability rule for that scope
26721
+ * (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
26722
+ * drain never offers), so a personal repository's rows are in none of them.
26723
+ * Omitted, this runs the machine statement, unchanged; an empty list counts
26724
+ * nothing.
27443
26725
  */
26726
+ partition(scopeKeys) {
26727
+ const row = getRow(
26728
+ scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
26729
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
26730
+ );
26731
+ return {
26732
+ queued: row?.queued ?? 0,
26733
+ inProgress: row?.inProgress ?? 0,
26734
+ synced: row?.synced ?? 0,
26735
+ failed: row?.failed ?? 0,
26736
+ refused: row?.refused ?? 0,
26737
+ detached: row?.detached ?? 0,
26738
+ total: row?.total ?? 0
26739
+ };
26740
+ }
27444
26741
  /**
27445
26742
  * The same partition, one row per kind that a lane carries.
27446
26743
  *
@@ -27450,11 +26747,14 @@ var SqliteHistorySyncRepository = class {
27450
26747
  * rendering a fixed list of kinds must therefore treat a missing one as "no
27451
26748
  * rows", never as "zero sent"; the two look identical in a bar and mean
27452
26749
  * different things.
26750
+ *
26751
+ * `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
26752
+ * still sum to the scoped aggregate. An empty list returns no rows.
27453
26753
  */
27454
- partitionByKind() {
26754
+ partitionByKind(scopeKeys) {
27455
26755
  return allRows(
27456
- this.partitionByKindStmt,
27457
- {}
26756
+ scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
26757
+ scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
27458
26758
  ).map((row) => ({
27459
26759
  kind: row.kind,
27460
26760
  queued: row.queued ?? 0,
@@ -27466,22 +26766,25 @@ var SqliteHistorySyncRepository = class {
27466
26766
  total: row.total ?? 0
27467
26767
  }));
27468
26768
  }
27469
- partition() {
27470
- const row = getRow(this.partitionStmt, {});
27471
- return {
27472
- queued: row?.queued ?? 0,
27473
- inProgress: row?.inProgress ?? 0,
27474
- synced: row?.synced ?? 0,
27475
- failed: row?.failed ?? 0,
27476
- refused: row?.refused ?? 0,
27477
- detached: row?.detached ?? 0,
27478
- total: row?.total ?? 0
27479
- };
27480
- }
27481
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27482
- counts(before) {
27483
- const row = getRow(this.countsStmt, { before });
27484
- const captures = getRow(this.captureSkipCountStmt);
26769
+ /**
26770
+ * The drain's totals. `pending` counts only what is inside the backlog; sent
26771
+ * and skipped are totals.
26772
+ *
26773
+ * `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
26774
+ * `capturesSkipped` included: a structural row is counted only when its own
26775
+ * key and its session root's key are among them, a capture when its own key
26776
+ * is. So `pending` is exactly what pendingSessions and pendingRows page out
26777
+ * under the same keys and boundary. Omitted, this runs the machine
26778
+ * statements, unchanged; an empty list counts nothing.
26779
+ */
26780
+ counts(before, scopeKeys) {
26781
+ const row = getRow(
26782
+ scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
26783
+ scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
26784
+ );
26785
+ const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
26786
+ scopeKeys: scopeKeysParam(scopeKeys)
26787
+ });
27485
26788
  return {
27486
26789
  pending: row?.pending ?? 0,
27487
26790
  sent: row?.sent ?? 0,
@@ -27733,6 +27036,7 @@ function applyMigrations(db, file2, options = {}) {
27733
27036
  }
27734
27037
  ensureSyncedAtColumn(db, "audit_events");
27735
27038
  ensureScopeKeyColumn(db);
27039
+ ensureScopeOwedIndex(db);
27736
27040
  ensureScanLedgerTable(db);
27737
27041
  ensureHistorySyncTable(db);
27738
27042
  ensureBlockedDetectionsTable(db);
@@ -28173,14 +27477,48 @@ function ensureScopeKeyColumn(db) {
28173
27477
  function hasScopeKeyColumn(db) {
28174
27478
  return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
28175
27479
  }
27480
+ 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";
27481
+ function ensureScopeOwedIndex(db) {
27482
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
27483
+ const columns = columnNames(db, "audit_events", { includeGenerated: true });
27484
+ const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
27485
+ if (!complete) return;
27486
+ db.exec(SCOPE_OWED_INDEX_DDL);
27487
+ }
28176
27488
  function ensureScanLedgerTable(db) {
28177
27489
  db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
28178
27490
  path TEXT PRIMARY KEY,
28179
27491
  mtime TEXT NOT NULL,
28180
27492
  content_hash TEXT NOT NULL,
28181
27493
  ruleset_hash TEXT NOT NULL,
28182
- scanned_at INTEGER NOT NULL
27494
+ scanned_at INTEGER NOT NULL,
27495
+ scope_key TEXT,
27496
+ scope_root TEXT
28183
27497
  )`);
27498
+ ensureScanLedgerScopeKeyColumn(db);
27499
+ ensureScanLedgerScopeRootColumn(db);
27500
+ }
27501
+ var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
27502
+ var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
27503
+ function ensureScanLedgerScopeKeyColumn(db) {
27504
+ ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
27505
+ }
27506
+ function ensureScanLedgerScopeRootColumn(db) {
27507
+ ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
27508
+ }
27509
+ function ensureScanLedgerColumn(db, column, ddl) {
27510
+ if (!schemaObjectExists(db, "table", "scan_ledger")) return;
27511
+ if (hasScanLedgerColumn(db, column)) return;
27512
+ withTransaction(
27513
+ db,
27514
+ () => {
27515
+ if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
27516
+ },
27517
+ "IMMEDIATE"
27518
+ );
27519
+ }
27520
+ function hasScanLedgerColumn(db, column) {
27521
+ return columnNames(db, "scan_ledger").includes(column);
28184
27522
  }
28185
27523
  function ensureHistorySyncTable(db) {
28186
27524
  db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
@@ -28231,6 +27569,106 @@ function ensureRuleProbeCacheTable(db) {
28231
27569
  )`);
28232
27570
  }
28233
27571
 
27572
+ // ../../packages/persistence/src/mod-policy-snapshot.ts
27573
+ import { createHash as createHash2 } from "crypto";
27574
+ import { readFileSync as readFileSync2 } from "fs";
27575
+ import { join as join4 } from "path";
27576
+ var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
27577
+ function modPolicySnapshotPath(dataDir2) {
27578
+ return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
27579
+ }
27580
+ function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
27581
+ const byRule = /* @__PURE__ */ new Map();
27582
+ const byCategory = /* @__PURE__ */ new Map();
27583
+ for (const policy of input2.policies) {
27584
+ if (!policy.enabled) continue;
27585
+ if ("ruleId" in policy.target) {
27586
+ if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
27587
+ } else if (!byCategory.has(policy.target.category)) {
27588
+ byCategory.set(policy.target.category, policy.action);
27589
+ }
27590
+ }
27591
+ const categoryActions = {};
27592
+ for (const category of DetectionCategory.options) {
27593
+ categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
27594
+ }
27595
+ return {
27596
+ version: MOD_POLICY_SNAPSHOT_VERSION,
27597
+ generatedAt: generatedAt.toISOString(),
27598
+ // `examples` is documentation the mod never reads, and a custom pack's are
27599
+ // whatever its author pasted in, so they stay behind.
27600
+ ...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
27601
+ ruleActions: Object.fromEntries(byRule),
27602
+ categoryActions,
27603
+ exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
27604
+ };
27605
+ }
27606
+ function assignedRuleActionPolicies(installed) {
27607
+ const out = [];
27608
+ for (const [ruleId, action] of installed.ruleActions) {
27609
+ if (installed.assignedRules.has(ruleId))
27610
+ out.push({ target: { ruleId }, action, enabled: true });
27611
+ }
27612
+ return out;
27613
+ }
27614
+ function withoutExamples(rule) {
27615
+ const copy = { ...rule };
27616
+ delete copy.examples;
27617
+ return copy;
27618
+ }
27619
+ function sameContent(a, b) {
27620
+ return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
27621
+ }
27622
+ function readModPolicySnapshot(dataDir2) {
27623
+ try {
27624
+ const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
27625
+ if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
27626
+ const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
27627
+ return parsed2.success ? parsed2.data : null;
27628
+ } catch {
27629
+ return null;
27630
+ }
27631
+ }
27632
+ function writeModPolicySnapshot(dataDir2, snapshot) {
27633
+ const text = JSON.stringify(snapshot);
27634
+ if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
27635
+ const existing = readModPolicySnapshot(dataDir2);
27636
+ if (existing !== null && sameContent(existing, snapshot)) return false;
27637
+ ensureDataDirSync(dataDir2);
27638
+ writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
27639
+ return true;
27640
+ }
27641
+ function regexProbeKey(matcher) {
27642
+ return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
27643
+ }
27644
+ function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27645
+ const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
27646
+ return rules.filter((rule) => {
27647
+ if (rule.matcher.type !== "regex") return true;
27648
+ const key = regexProbeKey(rule.matcher);
27649
+ const verdict = sources.probeVerdict(key);
27650
+ if (verdict === "quarantined") return false;
27651
+ return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
27652
+ });
27653
+ }
27654
+ function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
27655
+ const policies = sources.readPolicies();
27656
+ const snapshot = sources.installedRuleset();
27657
+ const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
27658
+ const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
27659
+ return {
27660
+ ...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
27661
+ policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
27662
+ exceptionRuleIds: sources.activeExceptionRuleIds()
27663
+ };
27664
+ }
27665
+ function refreshModPolicySnapshot(dataDir2, sources) {
27666
+ try {
27667
+ writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
27668
+ } catch {
27669
+ }
27670
+ }
27671
+
28234
27672
  // ../../packages/persistence/src/internal/json.ts
28235
27673
  function safeJson(s, fallback) {
28236
27674
  if (s == null) return fallback;
@@ -28405,6 +27843,11 @@ var TIMELINE_COLUMNS = `
28405
27843
  json_extract(attributes, '$.targetId') AS target_id,
28406
27844
  json_extract(attributes, '$.internal') AS internal,
28407
27845
  json_extract(attributes, '$.flagged') AS flagged`;
27846
+ var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
27847
+ + coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
27848
+ var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
27849
+ " + "
27850
+ );
28408
27851
  var LLM_USAGE_SELECT = `
28409
27852
  SELECT root_session_id AS sessionId,
28410
27853
  provider,
@@ -28416,9 +27859,10 @@ var LLM_USAGE_SELECT = `
28416
27859
  coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
28417
27860
  coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
28418
27861
  coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
28419
- coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
27862
+ coalesce(sum(web_search_requests), 0) AS webSearchRequests,
27863
+ coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
28420
27864
  var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
28421
- var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
27865
+ var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
28422
27866
  function usageLeaves(rows) {
28423
27867
  return rows.map((row) => {
28424
27868
  const attributes = {
@@ -28433,7 +27877,7 @@ function usageLeaves(rows) {
28433
27877
  if (row.provider !== null) attributes.provider = row.provider;
28434
27878
  if (row.model !== null) attributes.model = row.model;
28435
27879
  if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
28436
- return { sessionId: row.sessionId, attributes };
27880
+ return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
28437
27881
  });
28438
27882
  }
28439
27883
  var SESSION_ROOT = `event_type = 'session'`;
@@ -29767,9 +29211,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
29767
29211
  AND conditions IS NULL
29768
29212
  AND ${ACTIVE_PREDICATE}`;
29769
29213
  var SqliteExceptionsRepository = class {
29770
- constructor(db, now = () => Date.now()) {
29214
+ constructor(db, now = () => Date.now(), onChange = () => void 0) {
29771
29215
  this.db = db;
29772
29216
  this.now = now;
29217
+ this.onChange = onChange;
29773
29218
  this.consumeStmt = db.prepare(
29774
29219
  `UPDATE exceptions
29775
29220
  SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
@@ -29788,6 +29233,7 @@ var SqliteExceptionsRepository = class {
29788
29233
  }
29789
29234
  db;
29790
29235
  now;
29236
+ onChange;
29791
29237
  consumeStmt;
29792
29238
  insertBlockedStmt;
29793
29239
  sweepBlockedStmt;
@@ -29803,7 +29249,9 @@ var SqliteExceptionsRepository = class {
29803
29249
  */
29804
29250
  create(input2) {
29805
29251
  try {
29806
- return Promise.resolve(this.createSync(input2));
29252
+ const created = this.createSync(input2);
29253
+ this.onChange();
29254
+ return Promise.resolve(created);
29807
29255
  } catch (err) {
29808
29256
  return Promise.reject(err instanceof Error ? err : new Error(String(err)));
29809
29257
  }
@@ -29934,6 +29382,7 @@ var SqliteExceptionsRepository = class {
29934
29382
  SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
29935
29383
  WHERE id = :id AND revoked_at IS NULL`
29936
29384
  ).run({ id, revokedBy, reason: reason ?? null, now });
29385
+ if (Number(result.changes) === 1) this.onChange();
29937
29386
  return Promise.resolve(Number(result.changes) === 1);
29938
29387
  }
29939
29388
  /**
@@ -29946,6 +29395,15 @@ var SqliteExceptionsRepository = class {
29946
29395
  const result = this.consumeStmt.run({ id, now });
29947
29396
  return Promise.resolve(Number(result.changes) === 1);
29948
29397
  }
29398
+ /** The rule ids with at least one active grant, under any key version. */
29399
+ activeRuleIds(now = this.now()) {
29400
+ return allRows(
29401
+ this.db.prepare(
29402
+ `SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
29403
+ ),
29404
+ { now }
29405
+ ).map((row) => row.ruleId);
29406
+ }
29949
29407
  /**
29950
29408
  * The evaluation subset of every active grant under one fingerprint key
29951
29409
  * version — what rides the policy bundle to the hook. Grants written under
@@ -31069,31 +30527,31 @@ var SqliteInspectionFindingsRepository = class {
31069
30527
  };
31070
30528
 
31071
30529
  // ../../packages/persistence/src/repositories/installed-packs.ts
31072
- import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
30530
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
31073
30531
 
31074
30532
  // ../../packages/persistence/src/policy-floor.ts
31075
- import { readFileSync as readFileSync5 } from "fs";
31076
- import { join as join6 } from "path";
30533
+ import { readFileSync as readFileSync6 } from "fs";
30534
+ import { join as join7 } from "path";
31077
30535
 
31078
30536
  // ../../packages/persistence/src/local-layout.ts
31079
30537
  import { renameSync as renameSync3 } from "fs";
31080
30538
  import { mkdir } from "fs/promises";
31081
30539
  import { homedir } from "os";
31082
- import { join as join4 } from "path";
30540
+ import { join as join5 } from "path";
31083
30541
  function defaultDataDir() {
31084
- return join4(homedir(), ".aka");
30542
+ return join5(homedir(), ".aka");
31085
30543
  }
31086
30544
  function settingsDir(base = defaultDataDir()) {
31087
- return join4(base, "settings");
30545
+ return join5(base, "settings");
31088
30546
  }
31089
30547
  function dataDir(base = defaultDataDir()) {
31090
- return join4(base, "data");
30548
+ return join5(base, "data");
31091
30549
  }
31092
30550
  function dbPath(base = defaultDataDir()) {
31093
- return join4(dataDir(base), "aka.db");
30551
+ return join5(dataDir(base), "aka.db");
31094
30552
  }
31095
30553
  function keysDir(base = defaultDataDir()) {
31096
- return join4(base, "keys");
30554
+ return join5(base, "keys");
31097
30555
  }
31098
30556
  async function ensureDataDir(dir = defaultDataDir()) {
31099
30557
  await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
@@ -31110,8 +30568,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31110
30568
  for (const { name, dest } of moves) {
31111
30569
  try {
31112
30570
  ensureDataDirSync(dest);
31113
- const moved = join4(dest, name);
31114
- renameSync3(join4(base, name), moved);
30571
+ const moved = join5(dest, name);
30572
+ renameSync3(join5(base, name), moved);
31115
30573
  tightenFile(moved);
31116
30574
  } catch {
31117
30575
  }
@@ -31119,8 +30577,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
31119
30577
  }
31120
30578
 
31121
30579
  // ../../packages/persistence/src/settings.ts
31122
- import { readFileSync as readFileSync4 } from "fs";
31123
- import { join as join5 } from "path";
30580
+ import { readFileSync as readFileSync5 } from "fs";
30581
+ import { join as join6 } from "path";
31124
30582
 
31125
30583
  // ../../packages/persistence/src/file-lock.ts
31126
30584
  import { randomUUID as randomUUID3 } from "crypto";
@@ -31128,7 +30586,7 @@ import {
31128
30586
  closeSync,
31129
30587
  existsSync as existsSync2,
31130
30588
  openSync,
31131
- readFileSync as readFileSync2,
30589
+ readFileSync as readFileSync3,
31132
30590
  rmSync as rmSync5,
31133
30591
  statSync as statSync3,
31134
30592
  writeFileSync as writeFileSync2
@@ -31137,16 +30595,16 @@ import { hostname as hostname3 } from "os";
31137
30595
  var PARK = new Int32Array(new SharedArrayBuffer(4));
31138
30596
 
31139
30597
  // ../../packages/persistence/src/managed-settings.ts
31140
- import { readFileSync as readFileSync3 } from "fs";
30598
+ import { readFileSync as readFileSync4 } from "fs";
31141
30599
  import { posix, win32 } from "path";
31142
- function managedSettingsPaths(platform2 = process.platform) {
31143
- if (platform2 === "darwin") {
30600
+ function managedSettingsPaths(platform = process.platform) {
30601
+ if (platform === "darwin") {
31144
30602
  return [
31145
30603
  posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
31146
30604
  posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
31147
30605
  ];
31148
30606
  }
31149
- if (platform2 === "win32") {
30607
+ if (platform === "win32") {
31150
30608
  return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
31151
30609
  }
31152
30610
  return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
@@ -31156,7 +30614,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
31156
30614
  for (const path of paths) {
31157
30615
  let text;
31158
30616
  try {
31159
- text = readFileSync3(path, "utf8");
30617
+ text = readFileSync4(path, "utf8");
31160
30618
  } catch {
31161
30619
  continue;
31162
30620
  }
@@ -31210,7 +30668,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
31210
30668
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
31211
30669
  }
31212
30670
  function readUserSettings(base) {
31213
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
30671
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
31214
30672
  if (!record2) return defaultWorkspaceSettings();
31215
30673
  try {
31216
30674
  return WorkspaceSettings.parse(record2);
@@ -31221,7 +30679,7 @@ function readUserSettings(base) {
31221
30679
  function readJson(file2) {
31222
30680
  let text;
31223
30681
  try {
31224
- text = readFileSync4(file2, "utf8");
30682
+ text = readFileSync5(file2, "utf8");
31225
30683
  } catch {
31226
30684
  return null;
31227
30685
  }
@@ -31261,7 +30719,7 @@ var PolicyFloorError = class extends Error {
31261
30719
  };
31262
30720
  function readCachedPolicyBundle(base = defaultDataDir()) {
31263
30721
  try {
31264
- const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
30722
+ const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
31265
30723
  const parsed2 = JSON.parse(raw);
31266
30724
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
31267
30725
  return PolicyBundle.parse(parsed2.bundle);
@@ -31385,7 +30843,7 @@ function inventorySignature(packs2) {
31385
30843
  return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
31386
30844
  }
31387
30845
  function hashRules(rulesJson) {
31388
- return createHash2("sha256").update(rulesJson).digest("hex");
30846
+ return createHash3("sha256").update(rulesJson).digest("hex");
31389
30847
  }
31390
30848
  function parseVersion(v) {
31391
30849
  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
@@ -31427,9 +30885,10 @@ var SqliteInstalledPacksRepository = class {
31427
30885
  * from `openLocalDatabase`, which is the single construction site that owns a
31428
30886
  * real `~/.aka`.
31429
30887
  */
31430
- constructor(db, baseDir) {
30888
+ constructor(db, baseDir, onChange = () => void 0) {
31431
30889
  this.db = db;
31432
30890
  this.baseDir = baseDir;
30891
+ this.onChange = onChange;
31433
30892
  this.insertMissingStmt = db.prepare(
31434
30893
  `INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
31435
30894
  VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
@@ -31458,6 +30917,7 @@ var SqliteInstalledPacksRepository = class {
31458
30917
  }
31459
30918
  db;
31460
30919
  baseDir;
30920
+ onChange;
31461
30921
  insertMissingStmt;
31462
30922
  upsertAvailableStmt;
31463
30923
  signatureStmt;
@@ -31530,6 +30990,7 @@ var SqliteInstalledPacksRepository = class {
31530
30990
  },
31531
30991
  "IMMEDIATE"
31532
30992
  );
30993
+ this.onChange();
31533
30994
  } catch {
31534
30995
  }
31535
30996
  }
@@ -31604,6 +31065,7 @@ var SqliteInstalledPacksRepository = class {
31604
31065
  },
31605
31066
  "IMMEDIATE"
31606
31067
  );
31068
+ if (changed) this.onChange();
31607
31069
  return changed;
31608
31070
  }
31609
31071
  /**
@@ -31845,6 +31307,7 @@ var SqliteInstalledPacksRepository = class {
31845
31307
  `UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
31846
31308
  WHERE namespace = :namespace AND pack_id = :packId`
31847
31309
  ).run({ policyId, now: Date.now(), namespace, packId });
31310
+ if (Number(res.changes) > 0) this.onChange();
31848
31311
  return Number(res.changes) > 0;
31849
31312
  }
31850
31313
  /**
@@ -31869,6 +31332,7 @@ var SqliteInstalledPacksRepository = class {
31869
31332
  `UPDATE installed_packs SET enabled = :enabled, updated_at = :now
31870
31333
  WHERE namespace = :namespace AND pack_id = :packId`
31871
31334
  ).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
31335
+ if (Number(res.changes) > 0) this.onChange();
31872
31336
  return Number(res.changes) > 0;
31873
31337
  }
31874
31338
  // Fingerprint of the recorded available mirror — compared against the
@@ -32766,13 +32230,19 @@ var SqliteInventoryAssetsRepository = class {
32766
32230
  import { randomUUID as randomUUID6 } from "crypto";
32767
32231
  var SEED_BATCH_WINDOW_MS = 6e4;
32768
32232
  var SqlitePoliciesRepository = class {
32769
- constructor(db) {
32233
+ constructor(db, onChange = () => void 0) {
32770
32234
  this.db = db;
32235
+ this.onChange = onChange;
32771
32236
  }
32772
32237
  db;
32238
+ onChange;
32773
32239
  readPolicies() {
32240
+ return Promise.resolve(this.listPolicies());
32241
+ }
32242
+ /** The synchronous read behind {@link readPolicies}. */
32243
+ listPolicies() {
32774
32244
  const rows = allRows(this.db.prepare("SELECT * FROM policies"));
32775
- const policies = mapRowsTolerant(rows, (row) => {
32245
+ return mapRowsTolerant(rows, (row) => {
32776
32246
  const target = JSON.parse(row.target);
32777
32247
  const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
32778
32248
  return Policy.parse({
@@ -32784,7 +32254,6 @@ var SqlitePoliciesRepository = class {
32784
32254
  customKeywords
32785
32255
  });
32786
32256
  });
32787
- return Promise.resolve(policies);
32788
32257
  }
32789
32258
  // Seed one policy per bundled category at Monitor so the detection-type config
32790
32259
  // exists from first run. An unassigned pack's rules follow these rows, so
@@ -32795,7 +32264,7 @@ var SqlitePoliciesRepository = class {
32795
32264
  const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
32796
32265
  if (count > 0) {
32797
32266
  this.markEarlierChoices();
32798
- this.monitorUntouchedSeeds();
32267
+ if (this.monitorUntouchedSeeds()) this.onChange();
32799
32268
  return;
32800
32269
  }
32801
32270
  const stmt = this.db.prepare(
@@ -32812,6 +32281,7 @@ var SqlitePoliciesRepository = class {
32812
32281
  });
32813
32282
  }
32814
32283
  });
32284
+ this.onChange();
32815
32285
  }
32816
32286
  // Before this build, upsertCategoryAction INSERTed a new row with updated_at
32817
32287
  // equal to created_at, so a choice made for a category that had no row yet
@@ -32877,7 +32347,7 @@ var SqlitePoliciesRepository = class {
32877
32347
  ).filter(
32878
32348
  (row) => DEFAULT_ACTIONS[row.category] === row.action
32879
32349
  );
32880
- if (untouched.length === 0) return;
32350
+ if (untouched.length === 0) return false;
32881
32351
  const stmt = this.db.prepare(
32882
32352
  `UPDATE policies SET action = 'log'
32883
32353
  WHERE scope = 'global' AND json_extract(target, '$.category') = :category
@@ -32888,6 +32358,7 @@ var SqlitePoliciesRepository = class {
32888
32358
  stmt.run({ category: row.category, seeded: row.action });
32889
32359
  }
32890
32360
  });
32361
+ return true;
32891
32362
  }
32892
32363
  // Insert-or-update the single global per-category policy row, keyed on the
32893
32364
  // existing uq_policies_scope_target unique index (scope, target). `action`
@@ -32904,6 +32375,7 @@ var SqlitePoliciesRepository = class {
32904
32375
  ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
32905
32376
  updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
32906
32377
  ).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
32378
+ this.onChange();
32907
32379
  }
32908
32380
  // Caps every global per-category policy currently set to block/redact down
32909
32381
  // to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
@@ -32914,6 +32386,7 @@ var SqlitePoliciesRepository = class {
32914
32386
  WHERE scope='global' AND action IN ('block','redact')
32915
32387
  AND json_extract(target,'$.category') IS NOT NULL`
32916
32388
  ).run({ now: Date.now() });
32389
+ if (Number(info.changes) > 0) this.onChange();
32917
32390
  return Number(info.changes);
32918
32391
  }
32919
32392
  // Whether the category's row was ever written after it was created — by the
@@ -33233,31 +32706,45 @@ var SqliteScanLedgerRepository = class {
33233
32706
  constructor(db) {
33234
32707
  this.db = db;
33235
32708
  this.upsertStmt = db.prepare(
33236
- `INSERT INTO scan_ledger (path, mtime, content_hash, ruleset_hash, scanned_at)
33237
- VALUES (:path, :mtime, :contentHash, :rulesetHash, :scannedAt)
32709
+ `INSERT INTO scan_ledger
32710
+ (path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
32711
+ VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
33238
32712
  ON CONFLICT (path) DO UPDATE SET
33239
32713
  mtime = excluded.mtime,
33240
32714
  content_hash = excluded.content_hash,
33241
32715
  ruleset_hash = excluded.ruleset_hash,
32716
+ scope_key = excluded.scope_key,
32717
+ scope_root = excluded.scope_root,
33242
32718
  scanned_at = excluded.scanned_at`
33243
32719
  );
33244
32720
  this.readStmt = db.prepare(
33245
- `SELECT path, mtime, content_hash AS contentHash
32721
+ `SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
32722
+ scope_root AS scopeRoot
33246
32723
  FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
33247
32724
  );
33248
32725
  this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
32726
+ this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
33249
32727
  }
33250
32728
  db;
33251
32729
  upsertStmt;
33252
32730
  readStmt;
33253
32731
  pathsStmt;
32732
+ pathKeysStmt;
33254
32733
  // Previously scanned files under THIS ruleset, keyed by path. Rows from an
33255
32734
  // older ruleset are simply absent, which reads as "never scanned".
33256
32735
  entriesForRuleset(rulesetHash) {
33257
- const rows = allRows(this.readStmt, {
33258
- rulesetHash
33259
- });
33260
- return new Map(rows.map((r) => [r.path, { mtime: r.mtime, contentHash: r.contentHash }]));
32736
+ const rows = allRows(this.readStmt, { rulesetHash });
32737
+ return new Map(
32738
+ rows.map((r) => [
32739
+ r.path,
32740
+ {
32741
+ mtime: r.mtime,
32742
+ contentHash: r.contentHash,
32743
+ ...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
32744
+ ...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
32745
+ }
32746
+ ])
32747
+ );
33261
32748
  }
33262
32749
  // Every ledgered path, whatever ruleset it was scanned under — the set a
33263
32750
  // deletion sweep checks against disk. A file deleted before a ruleset change
@@ -33266,6 +32753,14 @@ var SqliteScanLedgerRepository = class {
33266
32753
  allPaths() {
33267
32754
  return allRows(this.pathsStmt).map((r) => r.path);
33268
32755
  }
32756
+ // Every ledgered path with the repository it was in when it was last read,
32757
+ // whatever ruleset it was scanned under: what a deletion sweep needs to say
32758
+ // which repository a vanished file belonged to. `undefined` for a row with no
32759
+ // key, which is every row written before the column existed.
32760
+ pathKeys() {
32761
+ const rows = allRows(this.pathKeysStmt);
32762
+ return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
32763
+ }
33269
32764
  upsertEntries(entries) {
33270
32765
  if (entries.length === 0) return;
33271
32766
  const scannedAt = Date.now();
@@ -33276,6 +32771,8 @@ var SqliteScanLedgerRepository = class {
33276
32771
  mtime: entry.mtime,
33277
32772
  contentHash: entry.contentHash,
33278
32773
  rulesetHash: entry.rulesetHash,
32774
+ scopeKey: entry.scopeKey ?? null,
32775
+ scopeRoot: entry.scopeRoot ?? null,
33279
32776
  scannedAt
33280
32777
  });
33281
32778
  }
@@ -34363,6 +33860,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
34363
33860
  deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
34364
33861
  };
34365
33862
  }
33863
+ function withoutTrailingSlashes(path) {
33864
+ let end = path.length;
33865
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
33866
+ return path.slice(0, end);
33867
+ }
34366
33868
  function toEndpointSummary(row) {
34367
33869
  return {
34368
33870
  id: row.id,
@@ -34650,7 +34152,7 @@ var SqliteSharesRepository = class {
34650
34152
  */
34651
34153
  reconcileCallSites(projectKey, reconcile) {
34652
34154
  if (reconcile.mode === "walk") {
34653
- const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
34155
+ const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
34654
34156
  this.db.prepare(
34655
34157
  `DELETE FROM share_call_site
34656
34158
  WHERE project_key = :key
@@ -35218,7 +34720,7 @@ function backupLegacyStore(db, file2) {
35218
34720
  discardStore(file2, backup);
35219
34721
  return backup;
35220
34722
  }
35221
- function openAndInitialize(file2, base, skipTags) {
34723
+ function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
35222
34724
  let db = openWithPragmas(file2);
35223
34725
  try {
35224
34726
  if (isForeignSqliteLineage(db)) {
@@ -35230,8 +34732,15 @@ function openAndInitialize(file2, base, skipTags) {
35230
34732
  }
35231
34733
  applyMigrations(db, file2, { skipTags });
35232
34734
  tightenPerms(file2);
35233
- const policies = new SqlitePoliciesRepository(db);
35234
- const installedPacks = new SqliteInstalledPacksRepository(db, base);
34735
+ const modPolicy = {};
34736
+ const onPolicyStateChange = () => {
34737
+ if (modPolicy.current !== void 0)
34738
+ refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
34739
+ };
34740
+ const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
34741
+ const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
34742
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
34743
+ const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
35235
34744
  const repositories = {
35236
34745
  events: new SqliteEventsRepository(db),
35237
34746
  findings: new SqliteFindingsRepository(db),
@@ -35240,9 +34749,9 @@ function openAndInitialize(file2, base, skipTags) {
35240
34749
  scanLedger: new SqliteScanLedgerRepository(db),
35241
34750
  historySync: new SqliteHistorySyncRepository(db),
35242
34751
  secretVault: new SqliteSecretVaultRepository(db),
35243
- exceptions: new SqliteExceptionsRepository(db),
34752
+ exceptions,
35244
34753
  resolutions: new SqliteResolutionsRepository(db),
35245
- ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
34754
+ ruleProbeCache,
35246
34755
  bodyRetention: new SqliteBodyRetentionRepository(db),
35247
34756
  security: new SqliteSecurityRepository(db),
35248
34757
  detections: new SqliteDetectionsRepository(db),
@@ -35260,6 +34769,13 @@ function openAndInitialize(file2, base, skipTags) {
35260
34769
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
35261
34770
  configInventory: new SqliteConfigInventoryRepository(db)
35262
34771
  };
34772
+ modPolicy.current = {
34773
+ installedRuleset: () => installedPacks.installedRuleset(),
34774
+ readPolicies: () => policies.listPolicies(),
34775
+ activeExceptionRuleIds: () => exceptions.activeRuleIds(),
34776
+ probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
34777
+ bundledRegexMatchers: () => shippedRegexMatchers2
34778
+ };
35263
34779
  policies.seedDefaults();
35264
34780
  return { db, ...repositories };
35265
34781
  } catch (err) {
@@ -35271,7 +34787,7 @@ function openAndInitialize(file2, base, skipTags) {
35271
34787
  var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
35272
34788
  function openLocalDatabase(dir, options = {}) {
35273
34789
  ensureDataDirSync(dir);
35274
- const file2 = join7(dir, DB_FILENAME);
34790
+ const file2 = join8(dir, DB_FILENAME);
35275
34791
  reapStalePartials(file2);
35276
34792
  const {
35277
34793
  db,
@@ -35307,7 +34823,8 @@ function openLocalDatabase(dir, options = {}) {
35307
34823
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
35308
34824
  // settings/ and data/, and the pack-policy floor needs both halves.
35309
34825
  dirname2(dir),
35310
- options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
34826
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
34827
+ options.shippedRegexMatchers ?? []
35311
34828
  );
35312
34829
  function captureRowId(event) {
35313
34830
  return captureId(
@@ -35572,7 +35089,7 @@ function openLocalDatabase(dir, options = {}) {
35572
35089
  }
35573
35090
 
35574
35091
  // ../../packages/persistence/src/egress-wire.ts
35575
- import { createHash as createHash3 } from "crypto";
35092
+ import { createHash as createHash4 } from "crypto";
35576
35093
  var PROJECT_KEY_DIGEST_VERSION = "v2";
35577
35094
  var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
35578
35095
  var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
@@ -35604,7 +35121,7 @@ function canonicalGitUrl(url2) {
35604
35121
  }
35605
35122
  function hashProjectKey(projectKey) {
35606
35123
  const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
35607
- return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35124
+ return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
35608
35125
  }
35609
35126
  var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
35610
35127
  var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
@@ -35669,24 +35186,23 @@ function toEgressIngestRequest(input2) {
35669
35186
  }
35670
35187
 
35671
35188
  // ../../packages/persistence/src/finding-key.ts
35672
- import { createHash as createHash4 } from "crypto";
35189
+ import { createHash as createHash5 } from "crypto";
35673
35190
  function normalizeFilePath(filePath) {
35674
35191
  return filePath.replaceAll("\\", "/");
35675
35192
  }
35676
35193
  function computeFindingKey(input2) {
35677
35194
  const normalizedPath = normalizeFilePath(input2.filePath);
35678
- return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35195
+ return createHash5("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
35679
35196
  }
35680
35197
 
35681
35198
  // ../../packages/persistence/src/fingerprint.ts
35682
35199
  import { createHmac, randomBytes } from "crypto";
35683
- import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
35684
- import { join as join8 } from "path";
35685
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35200
+ import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
35201
+ import { join as join9 } from "path";
35686
35202
  var EXCEPTION_KEY_FILENAME = "exception.key";
35687
35203
  var KEY_MATERIAL_BYTES = 32;
35688
35204
  function keyFilePath(dataDir2) {
35689
- return join8(dataDir2, EXCEPTION_KEY_FILENAME);
35205
+ return join9(dataDir2, EXCEPTION_KEY_FILENAME);
35690
35206
  }
35691
35207
  function parseKeyFile(raw) {
35692
35208
  const parsed2 = JSON.parse(raw);
@@ -35713,6 +35229,12 @@ var KEY_VERSION_COLUMNS = {
35713
35229
  };
35714
35230
  var SQLITE_ERROR2 = 1;
35715
35231
  var FLOOR_BUSY_TIMEOUT_MS = 250;
35232
+ function openReadOnly(file2) {
35233
+ const host = process;
35234
+ const sqlite = host.getBuiltinModule?.("node:sqlite");
35235
+ if (sqlite === void 0) throw new Error("this Node runtime cannot load node:sqlite");
35236
+ return new sqlite.DatabaseSync(file2, { readOnly: true });
35237
+ }
35716
35238
  var FloorUnreadableError = class extends Error {
35717
35239
  code = "floor-unreadable";
35718
35240
  constructor(cause) {
@@ -35724,11 +35246,11 @@ var FloorUnreadableError = class extends Error {
35724
35246
  }
35725
35247
  };
35726
35248
  function storedKeyVersionFloor(dataDir2) {
35727
- const file2 = join8(dataDir2, DB_FILENAME);
35249
+ const file2 = join9(dataDir2, DB_FILENAME);
35728
35250
  if (!existsSync3(file2)) return 0;
35729
35251
  let db;
35730
35252
  try {
35731
- db = new DatabaseSync2(file2, { readOnly: true });
35253
+ db = openReadOnly(file2);
35732
35254
  db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
35733
35255
  let floor = 0;
35734
35256
  for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
@@ -35779,7 +35301,7 @@ function occupantMessage(file2, kind) {
35779
35301
  function readFingerprintKey(dataDir2) {
35780
35302
  let raw;
35781
35303
  try {
35782
- raw = readFileSync6(keyFilePath(dataDir2), "utf8");
35304
+ raw = readFileSync7(keyFilePath(dataDir2), "utf8");
35783
35305
  } catch (err) {
35784
35306
  if (err.code === "ENOENT") return null;
35785
35307
  throw err instanceof Error ? err : new Error(String(err));
@@ -35805,8 +35327,8 @@ function exactFingerprintValue(key, raw) {
35805
35327
  }
35806
35328
 
35807
35329
  // ../../packages/persistence/src/forward-health.ts
35808
- import { readFileSync as readFileSync7 } from "fs";
35809
- import { join as join9 } from "path";
35330
+ import { readFileSync as readFileSync8 } from "fs";
35331
+ import { join as join10 } from "path";
35810
35332
  var BREAKER_COOLDOWN_MS = 3e4;
35811
35333
  function parseForwardHealth(raw, nowMs) {
35812
35334
  try {
@@ -35830,20 +35352,21 @@ function isForwardPaused(health, nowMs) {
35830
35352
 
35831
35353
  // ../../packages/persistence/src/history-backfill.ts
35832
35354
  import { existsSync as existsSync4 } from "fs";
35833
- import { join as join10 } from "path";
35355
+ import { join as join11 } from "path";
35834
35356
 
35835
35357
  // ../../packages/persistence/src/history-preview.ts
35836
35358
  import { existsSync as existsSync5 } from "fs";
35837
- import { join as join11 } from "path";
35838
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
35359
+ import { join as join12 } from "path";
35360
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
35839
35361
 
35840
35362
  // ../../packages/persistence/src/history-sync-state.ts
35841
- import { readFileSync as readFileSync8 } from "fs";
35842
- import { join as join12 } from "path";
35363
+ import { readFileSync as readFileSync9 } from "fs";
35364
+ import { join as join13 } from "path";
35365
+ var COUNTS_SCOPES = new Set(AttachmentMode.options);
35843
35366
 
35844
35367
  // ../../packages/persistence/src/store-symlinks.ts
35845
35368
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
35846
- import { dirname as dirname3, join as join13, resolve } from "path";
35369
+ import { dirname as dirname3, join as join14, resolve } from "path";
35847
35370
  var STORE_DB = "the store database (including the prompt corpus)";
35848
35371
  var STORE_SETTINGS = "your settings file";
35849
35372
  function storeContents(home) {
@@ -35852,11 +35375,11 @@ function storeContents(home) {
35852
35375
  [settingsDir(home), STORE_SETTINGS],
35853
35376
  [dataDir(home), STORE_DB],
35854
35377
  [keysDir(home), "the vault key"],
35855
- [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
35378
+ [join14(settingsDir(home), "settings.json"), STORE_SETTINGS],
35856
35379
  [dbPath(home), STORE_DB]
35857
35380
  ]);
35858
35381
  }
35859
- function symlinkedStorePaths(home, platform2 = process.platform) {
35382
+ function symlinkedStorePaths(home, platform = process.platform) {
35860
35383
  return [...storeContents(home)].flatMap(([path, holds]) => {
35861
35384
  try {
35862
35385
  if (!lstatSync3(path).isSymbolicLink()) return [];
@@ -35868,7 +35391,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
35868
35391
  // existsSync follows the link, so a target that is gone reads as
35869
35392
  // absent here while lstat above still sees the link itself.
35870
35393
  missing: !existsSync6(path),
35871
- mode: targetMode(path, platform2)
35394
+ mode: targetMode(path, platform)
35872
35395
  }
35873
35396
  ];
35874
35397
  } catch {
@@ -35883,8 +35406,8 @@ function linkTarget(path) {
35883
35406
  return resolve(dirname3(path), readlinkSync(path));
35884
35407
  }
35885
35408
  }
35886
- function targetMode(path, platform2) {
35887
- if (platform2 === "win32") return void 0;
35409
+ function targetMode(path, platform) {
35410
+ if (platform === "win32") return void 0;
35888
35411
  try {
35889
35412
  return statSync4(path).mode & 511;
35890
35413
  } catch {
@@ -35904,19 +35427,19 @@ import {
35904
35427
  // ../../packages/persistence/src/vault/key-provider.ts
35905
35428
  import { execFileSync } from "child_process";
35906
35429
  import { randomBytes as randomBytes2 } from "crypto";
35907
- import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35908
- import { join as join14 } from "path";
35430
+ import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
35431
+ import { join as join15 } from "path";
35909
35432
 
35910
35433
  // ../../packages/persistence/src/vault/vault.ts
35911
35434
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
35912
35435
 
35913
35436
  // ../../packages/persistence/src/warn-era-cap.ts
35914
35437
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
35915
- import { join as join15 } from "path";
35438
+ import { join as join16 } from "path";
35916
35439
  var MARKER = "warn-era-capped";
35917
35440
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35918
35441
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
35919
- const marker = join15(dataDir2, MARKER);
35442
+ const marker = join16(dataDir2, MARKER);
35920
35443
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
35921
35444
  const capped = db.policies.capCategoryActions();
35922
35445
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -35924,425 +35447,6 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
35924
35447
  return { capped };
35925
35448
  }
35926
35449
 
35927
- // ../../packages/remote/src/http.ts
35928
- import { request as httpRequest } from "http";
35929
- import { request as httpsRequest } from "https";
35930
- var DEFAULT_TIMEOUT_MS = 1e4;
35931
- var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35932
- var RemoteRequestError = class extends Error {
35933
- constructor(status) {
35934
- super(`control-plane request failed with status ${String(status)}`);
35935
- this.status = status;
35936
- this.name = "RemoteRequestError";
35937
- }
35938
- status;
35939
- };
35940
- var RemoteRouteAbsent = class extends Error {
35941
- constructor(route) {
35942
- super(`control plane does not serve ${route}`);
35943
- this.route = route;
35944
- this.name = "RemoteRouteAbsent";
35945
- }
35946
- route;
35947
- };
35948
- var RemoteRequestInvalid = class extends Error {
35949
- constructor(route, cause) {
35950
- super(`refusing to send a malformed body to ${route}`);
35951
- this.cause = cause;
35952
- this.name = "RemoteRequestInvalid";
35953
- }
35954
- cause;
35955
- };
35956
- var RemoteEndpointRefused = class extends Error {
35957
- constructor(endpoint) {
35958
- super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
35959
- this.name = "RemoteEndpointRefused";
35960
- }
35961
- };
35962
- var RemoteResponseInvalid = class extends Error {
35963
- constructor(route, detail) {
35964
- super(`control plane answered ${route} with ${detail}`);
35965
- this.name = "RemoteResponseInvalid";
35966
- }
35967
- };
35968
- var RemoteTransportError = class extends Error {
35969
- /**
35970
- * The status the peer sent, when headers arrived and only the BODY was
35971
- * refused.
35972
- *
35973
- * Undefined for the ordinary case this class was written for — no answer at
35974
- * all. It exists because two paths reject after a status has already been
35975
- * delivered: an oversized body and an aborted response. Discarding it there
35976
- * reported a deployment answering 401 with a verbose body as a network
35977
- * outage, which sends the reader to look at their network instead of their
35978
- * credential.
35979
- */
35980
- constructor(reason, status) {
35981
- super(`control-plane request did not complete: ${reason}`);
35982
- this.status = status;
35983
- this.name = "RemoteTransportError";
35984
- }
35985
- status;
35986
- };
35987
- async function send(options) {
35988
- const url2 = new URL(options.url);
35989
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35990
- const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
35991
- const requestOptions = {
35992
- method: options.method,
35993
- headers: {
35994
- // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
35995
- // last they win, and two of the values below are ones no caller may
35996
- // replace: `x-api-key` is the credential, and `content-length` is the
35997
- // byte count that stops a multi-byte body being truncated by the
35998
- // receiver. `SendOptions.headers` is a free-form record on an exported
35999
- // function, so "no caller does that today" is not the guarantee to rely
36000
- // on. The one header any caller actually passes — `if-none-match` on the
36001
- // conditional GET — is untouched by this order.
36002
- ...options.headers,
36003
- // The credential. One header, matching what the deployment authenticates
36004
- // on; a second copy in an `Authorization` header would be one more place
36005
- // it can be logged by an intermediary for no gain.
36006
- //
36007
- // Spread conditionally rather than assigned as `undefined`: Node's header
36008
- // handling and `content-length` bookkeeping treat a present-but-undefined
36009
- // key differently from an absent one, and "the header is not there" is
36010
- // the property the attach flow needs.
36011
- ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
36012
- accept: "application/json",
36013
- ...options.body === void 0 ? {} : {
36014
- "content-type": "application/json",
36015
- // Byte length, not string length: a multi-byte body sent with a
36016
- // character count is truncated by the receiver.
36017
- "content-length": String(Buffer.byteLength(options.body))
36018
- }
36019
- }
36020
- };
36021
- return new Promise((resolve3, reject) => {
36022
- let settled = false;
36023
- const fail = (reason, status) => {
36024
- if (settled) return;
36025
- settled = true;
36026
- reject(new RemoteTransportError(reason, status));
36027
- };
36028
- const req = send_(url2, requestOptions, (res) => {
36029
- const chunks = [];
36030
- let size = 0;
36031
- res.on("data", (chunk) => {
36032
- size += chunk.length;
36033
- if (size > MAX_RESPONSE_BYTES) {
36034
- fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
36035
- res.destroy();
36036
- req.destroy();
36037
- return;
36038
- }
36039
- chunks.push(chunk);
36040
- });
36041
- res.on("aborted", () => {
36042
- fail("the response was aborted", res.statusCode);
36043
- });
36044
- res.on("end", () => {
36045
- if (settled) return;
36046
- settled = true;
36047
- resolve3({
36048
- status: res.statusCode ?? 0,
36049
- headers: res.headers,
36050
- body: Buffer.concat(chunks).toString("utf8")
36051
- });
36052
- });
36053
- });
36054
- const deadline = setTimeout(() => {
36055
- fail(`no response within ${String(timeoutMs)}ms`);
36056
- req.destroy();
36057
- }, timeoutMs);
36058
- deadline.unref();
36059
- req.on("upgrade", (_res, socket) => {
36060
- fail("the deployment answered with a protocol upgrade");
36061
- socket.destroy();
36062
- });
36063
- req.on("close", () => {
36064
- fail("the connection closed before a response was read");
36065
- clearTimeout(deadline);
36066
- });
36067
- req.on("error", (err) => {
36068
- fail(err.message);
36069
- });
36070
- if (options.body !== void 0) req.write(options.body);
36071
- req.end();
36072
- });
36073
- }
36074
-
36075
- // ../../packages/remote/src/client.ts
36076
- var ROUTES = {
36077
- events: "/v1/events",
36078
- auditEvents: "/v1/audit-events",
36079
- auditEventsBatch: "/v1/audit-events/batch",
36080
- inventory: "/v1/inventory",
36081
- storePosture: "/v1/store-posture",
36082
- policyBundle: "/v1/policy-bundle",
36083
- whoami: "/v1/plugin/whoami",
36084
- shares: "/v1/shares",
36085
- commands: "/v1/plugin/commands"
36086
- };
36087
- function ackRoute(id) {
36088
- return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
36089
- }
36090
- function headerValue(response, name) {
36091
- const raw = response.headers[name];
36092
- if (raw === void 0) return void 0;
36093
- return Array.isArray(raw) ? raw[0] : raw;
36094
- }
36095
- function okBody(response) {
36096
- if (response.status < 200 || response.status >= 300) {
36097
- throw new RemoteRequestError(response.status);
36098
- }
36099
- return response.body;
36100
- }
36101
- function parsed(schema, body, route) {
36102
- let json2;
36103
- try {
36104
- json2 = JSON.parse(body);
36105
- } catch {
36106
- throw new RemoteResponseInvalid(route, "a body that is not JSON");
36107
- }
36108
- const result = schema.safeParse(json2);
36109
- if (!result.success) {
36110
- throw new RemoteResponseInvalid(route, "a body this client cannot read");
36111
- }
36112
- return result.data;
36113
- }
36114
- function resolveBaseUrl(endpoint) {
36115
- if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
36116
- let end = endpoint.length;
36117
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
36118
- return endpoint.slice(0, end);
36119
- }
36120
- var SLASH2 = "/".charCodeAt(0);
36121
- function createRemoteClient(options) {
36122
- const base = resolveBaseUrl(options.endpoint);
36123
- const url2 = (route) => `${base}${route}`;
36124
- const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
36125
- const sendOne = async (event) => {
36126
- const validated = RecordAuditEventRequest.safeParse(event);
36127
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
36128
- const response = await send({
36129
- ...common,
36130
- method: "POST",
36131
- url: url2(ROUTES.auditEvents),
36132
- body: JSON.stringify(validated.data)
36133
- });
36134
- okBody(response);
36135
- };
36136
- return {
36137
- async ingestEvents(batch) {
36138
- const response = await send({
36139
- ...common,
36140
- method: "POST",
36141
- url: url2(ROUTES.events),
36142
- body: JSON.stringify(batch)
36143
- });
36144
- return parsed(IngestAck, okBody(response), ROUTES.events);
36145
- },
36146
- async ingestInventory(context) {
36147
- const response = await send({
36148
- ...common,
36149
- method: "POST",
36150
- url: url2(ROUTES.inventory),
36151
- body: JSON.stringify(context)
36152
- });
36153
- return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
36154
- },
36155
- async recordAuditEvent(event) {
36156
- await sendOne(event);
36157
- },
36158
- async recordAuditEvents(events, opts) {
36159
- const validated = RecordAuditEventBatch.safeParse({ events });
36160
- if (!validated.success) {
36161
- throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
36162
- }
36163
- const response = await send({
36164
- ...common,
36165
- method: "POST",
36166
- url: url2(ROUTES.auditEventsBatch),
36167
- body: JSON.stringify(validated.data)
36168
- });
36169
- if (response.status === 404) {
36170
- if (opts?.fallbackToSingleEvents !== true) {
36171
- throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
36172
- }
36173
- for (const event of validated.data.events) await sendOne(event);
36174
- return { accepted: validated.data.events.length };
36175
- }
36176
- return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
36177
- },
36178
- async reportStorePosture(snapshot) {
36179
- const response = await send({
36180
- ...common,
36181
- method: "POST",
36182
- url: url2(ROUTES.storePosture),
36183
- body: JSON.stringify(snapshot)
36184
- });
36185
- okBody(response);
36186
- },
36187
- async getPolicyBundle(etag) {
36188
- const response = await send({
36189
- ...common,
36190
- method: "GET",
36191
- url: url2(ROUTES.policyBundle),
36192
- ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
36193
- });
36194
- if (response.status === 304) {
36195
- return { changed: false, etag: headerValue(response, "etag") ?? etag };
36196
- }
36197
- const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
36198
- return { changed: true, bundle, etag: headerValue(response, "etag") };
36199
- },
36200
- async whoami() {
36201
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
36202
- return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
36203
- },
36204
- async recordProjectEgress(request) {
36205
- const validated = EgressIngestRequest.safeParse(request);
36206
- if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
36207
- const response = await send({
36208
- ...common,
36209
- method: "POST",
36210
- url: url2(ROUTES.shares),
36211
- body: JSON.stringify(validated.data)
36212
- });
36213
- if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
36214
- okBody(response);
36215
- },
36216
- async pollCommand() {
36217
- const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
36218
- if (response.status === 404) return null;
36219
- return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
36220
- },
36221
- async ackCommand(id, body) {
36222
- const validated = DeviceCommandAckBody.safeParse(body);
36223
- const route = ackRoute(id);
36224
- if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
36225
- const response = await send({
36226
- ...common,
36227
- method: "POST",
36228
- url: url2(route),
36229
- body: JSON.stringify(validated.data)
36230
- });
36231
- okBody(response);
36232
- }
36233
- };
36234
- }
36235
-
36236
- // ../../packages/remote/src/failure-kind.ts
36237
- function statusOf(err) {
36238
- if (typeof err !== "object" || err === null || !("status" in err)) return null;
36239
- const { status } = err;
36240
- if (typeof status !== "number" || !Number.isInteger(status)) return null;
36241
- return status >= 100 && status <= 599 ? status : null;
36242
- }
36243
- function nameOf(err) {
36244
- if (typeof err !== "object" || err === null || !("name" in err)) return null;
36245
- return typeof err.name === "string" ? err.name : null;
36246
- }
36247
- function classifyRemoteFailure(err) {
36248
- switch (nameOf(err)) {
36249
- case "RemoteRouteAbsent":
36250
- return "route-absent";
36251
- case "RemoteRequestInvalid":
36252
- case "RemoteEndpointRefused":
36253
- return "invalid-request";
36254
- case "RemoteResponseInvalid":
36255
- return "rejected";
36256
- default:
36257
- break;
36258
- }
36259
- const status = statusOf(err);
36260
- if (status === null) return "unreachable";
36261
- switch (status) {
36262
- case 401:
36263
- return "unauthorized";
36264
- case 403:
36265
- return "forbidden";
36266
- case 429:
36267
- return "unreachable";
36268
- case 404:
36269
- return "unreachable";
36270
- default:
36271
- return status >= 400 && status <= 499 ? "rejected" : "unreachable";
36272
- }
36273
- }
36274
-
36275
- // ../../packages/plugin-runtime/src/attached/failure.ts
36276
- function classifyFailure(err) {
36277
- switch (classifyRemoteFailure(err)) {
36278
- case "unauthorized":
36279
- return "unauthorized";
36280
- case "forbidden":
36281
- return "forbidden";
36282
- default:
36283
- return "unreachable";
36284
- }
36285
- }
36286
-
36287
- // ../../packages/plugin-runtime/src/attached/with-timeout.ts
36288
- var REQUEST_TIMEOUT_MS = 2e3;
36289
- function withTimeout(promise2, ms) {
36290
- let timer;
36291
- const timeout = new Promise((_, reject) => {
36292
- timer = setTimeout(() => {
36293
- reject(new Error("attached gateway request timed out"));
36294
- }, ms);
36295
- });
36296
- promise2.catch(() => void 0);
36297
- return Promise.race([promise2, timeout]).finally(() => {
36298
- clearTimeout(timer);
36299
- });
36300
- }
36301
-
36302
- // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36303
- import { readFileSync as readFileSync10 } from "fs";
36304
- import { join as join16 } from "path";
36305
- var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36306
- function forwardDropsPath(dataDir2) {
36307
- return join16(dataDir2, FORWARD_DROPS_FILENAME);
36308
- }
36309
- function recordForwardDrops(dataDir2, count, nowMs) {
36310
- if (count <= 0) return;
36311
- try {
36312
- ensureDataDirSync(dataDir2);
36313
- const previous = readForwardDrops(dataDir2);
36314
- const next = {
36315
- droppedForwards: (previous?.droppedForwards ?? 0) + count,
36316
- lastDropAtMs: nowMs
36317
- };
36318
- writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
36319
- `);
36320
- } catch {
36321
- }
36322
- }
36323
- function readForwardDrops(dataDir2) {
36324
- try {
36325
- const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
36326
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36327
- const record2 = parsed2;
36328
- if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
36329
- return null;
36330
- }
36331
- if (record2.droppedForwards <= 0) return null;
36332
- if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
36333
- return null;
36334
- }
36335
- return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
36336
- } catch {
36337
- return null;
36338
- }
36339
- }
36340
-
36341
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36342
- import { randomUUID as randomUUID16 } from "crypto";
36343
- import { readFile, rename, writeFile } from "fs/promises";
36344
- import { join as join28 } from "path";
36345
-
36346
35450
  // ../../packages/plugin-sdk/src/config.ts
36347
35451
  import { existsSync as existsSync8 } from "fs";
36348
35452
  import { join as join17 } from "path";
@@ -36422,11 +35526,6 @@ function resolveProviderSafe(resolveProviderFn) {
36422
35526
  }
36423
35527
  }
36424
35528
 
36425
- // ../../packages/plugin-sdk/src/config-inventory.ts
36426
- import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
36427
- import { homedir as homedir2 } from "os";
36428
- import { basename as basename3, join as join19 } from "path";
36429
-
36430
35529
  // ../../packages/detections/src/egress/registry.ts
36431
35530
  var EXTRACTOR_VERSION = "3";
36432
35531
  var PROVIDER_REGISTRY = [
@@ -37190,12 +36289,12 @@ var RegexMatcher2 = class {
37190
36289
  rule.matcher,
37191
36290
  () => new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`)
37192
36291
  );
37193
- const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
36292
+ const scanText = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
37194
36293
  const spans = [];
37195
36294
  let m;
37196
- const maxIterations = scanText2.length + 1;
36295
+ const maxIterations = scanText.length + 1;
37197
36296
  let iterations = 0;
37198
- while ((m = re.exec(scanText2)) !== null) {
36297
+ while ((m = re.exec(scanText)) !== null) {
37199
36298
  if (++iterations > maxIterations) break;
37200
36299
  const group = captureGroup != null ? m[captureGroup] : m[0];
37201
36300
  if (m[0].length === 0) re.lastIndex++;
@@ -37537,17 +36636,18 @@ function ruleEvidence(rule) {
37537
36636
 
37538
36637
  // ../../packages/detections/src/mask.ts
37539
36638
  function maskMatch(raw) {
37540
- if (raw.length <= 5) return "***";
37541
- const atIndex = raw.indexOf("@");
37542
- if (atIndex > 0 && atIndex < raw.length - 1) {
37543
- const domain2 = raw.slice(atIndex + 1);
36639
+ const visible = stripInvisiblePadding(raw);
36640
+ if (visible.length <= 5) return "***";
36641
+ const atIndex = visible.indexOf("@");
36642
+ if (atIndex > 0 && atIndex < visible.length - 1) {
36643
+ const domain2 = visible.slice(atIndex + 1);
37544
36644
  if (domain2.includes(".")) {
37545
- const local = raw.slice(0, atIndex);
36645
+ const local = visible.slice(0, atIndex);
37546
36646
  const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
37547
36647
  return `${maskedLocal}@${domain2}`;
37548
36648
  }
37549
36649
  }
37550
- return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
36650
+ return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
37551
36651
  }
37552
36652
 
37553
36653
  // ../../packages/detections/src/pointer-shield.ts
@@ -37783,6 +36883,38 @@ function worstProbeMs(rule, now = wallClock, corroborate) {
37783
36883
  }
37784
36884
  var CPU_CORROBORATION_SHARE = 0.2;
37785
36885
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
36886
+ function repeatTo(unit, length) {
36887
+ return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
36888
+ }
36889
+ function joinTo(length, open3, close, item) {
36890
+ const parts = [];
36891
+ let size = open3.length;
36892
+ for (let i = 0; size < length; i++) {
36893
+ const next = (i === 0 ? "" : ",") + item(i);
36894
+ parts.push(next);
36895
+ size += next.length;
36896
+ }
36897
+ return (open3 + parts.join("") + close).slice(0, length);
36898
+ }
36899
+ var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
36900
+ var GROWTH_CORPORA = [
36901
+ {
36902
+ name: "one-line JSON dictionary",
36903
+ build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
36904
+ },
36905
+ {
36906
+ name: "JSON array of quoted SQL keywords",
36907
+ build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
36908
+ },
36909
+ { name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
36910
+ { name: "double-quote run", build: (length) => repeatTo('"', length) },
36911
+ { name: "space run", build: (length) => repeatTo(" ", length) },
36912
+ { name: "newline run", build: (length) => repeatTo("\n", length) },
36913
+ ...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
36914
+ name: `unit run ${JSON.stringify(unit)}`,
36915
+ build: (length) => repeatTo(unit, length)
36916
+ }))
36917
+ ];
37786
36918
  function checkRuleTiming(rule, corroborate) {
37787
36919
  const { ms, probe, corroboratedMs } = worstProbeMs(rule, wallClock, corroborate);
37788
36920
  const work = corroboratedMs ?? 0;
@@ -37809,7 +36941,12 @@ var MIN_RAW_LEN = 4;
37809
36941
  var RAW_RUN_LEN = 8;
37810
36942
  function carriesRawRun(text, rawValues) {
37811
36943
  let windows = null;
37812
- for (const raw of new Set(rawValues)) {
36944
+ const values = /* @__PURE__ */ new Set();
36945
+ for (const raw of rawValues) {
36946
+ values.add(raw);
36947
+ values.add(stripInvisiblePadding(raw));
36948
+ }
36949
+ for (const raw of values) {
37813
36950
  if (raw.length < MIN_RAW_LEN) continue;
37814
36951
  if (raw.length < RAW_RUN_LEN) {
37815
36952
  if (text.includes(raw)) return true;
@@ -37833,11 +36970,16 @@ function carriesRawRun(text, rawValues) {
37833
36970
  return false;
37834
36971
  }
37835
36972
  function safeMaskedMatch(rawMatch) {
37836
- const masked = maskMatch(rawMatch);
37837
- if (masked === rawMatch || rawMatch.length >= MIN_RAW_LEN && masked.includes(rawMatch)) {
37838
- return "***";
36973
+ const visible = stripInvisiblePadding(rawMatch);
36974
+ const masked = maskMatch(visible);
36975
+ const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
36976
+ if (!reveals(masked)) return masked;
36977
+ const atIndex = masked.indexOf("@");
36978
+ if (atIndex > 0 && atIndex < masked.length - 1) {
36979
+ const emailFallback = `*${masked.slice(atIndex)}`;
36980
+ if (!reveals(emailFallback)) return emailFallback;
37839
36981
  }
37840
- return masked;
36982
+ return "***";
37841
36983
  }
37842
36984
  function assertRawFree(text, rawValues) {
37843
36985
  if (carriesRawRun(text, rawValues)) {
@@ -38074,7 +37216,7 @@ var auth_jwt_no_verify_default = {
38074
37216
  severity: "critical",
38075
37217
  matcher: {
38076
37218
  type: "regex",
38077
- pattern: "(verify\\s*=\\s*false|verify_signature.*false|algorithms\\s*=\\s*\\[\\])",
37219
+ pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
38078
37220
  flags: "gi"
38079
37221
  },
38080
37222
  requiresNearby: {
@@ -38162,7 +37304,7 @@ var cmd_inject_shell_default = {
38162
37304
  severity: "critical",
38163
37305
  matcher: {
38164
37306
  type: "regex",
38165
- pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
37307
+ pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
38166
37308
  flags: "gi"
38167
37309
  },
38168
37310
  requiresNearby: {
@@ -38291,7 +37433,7 @@ var deser_yaml_unsafe_default = {
38291
37433
  severity: "high",
38292
37434
  matcher: {
38293
37435
  type: "regex",
38294
- pattern: "\\byaml\\.load\\s*\\((?![^)]*SafeLoader|[^)]*safe_load)",
37436
+ pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
38295
37437
  flags: "gi"
38296
37438
  },
38297
37439
  examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
@@ -38508,7 +37650,7 @@ var sql_inject_concat_dot_default = {
38508
37650
  severity: "high",
38509
37651
  matcher: {
38510
37652
  type: "regex",
38511
- pattern: `["'][^\\n]*?(select|insert|update|delete|drop|where)[^\\n]*?["']\\s*\\.`,
37653
+ pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
38512
37654
  flags: "gi"
38513
37655
  },
38514
37656
  appliesTo: {
@@ -38526,7 +37668,7 @@ var sql_inject_concat_default = {
38526
37668
  severity: "high",
38527
37669
  matcher: {
38528
37670
  type: "regex",
38529
- pattern: `["']\\s*(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?["']\\s*\\+`,
37671
+ pattern: `(["'])\\s*(?=(select\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?=))\\2(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?["']\\s*\\+`,
38530
37672
  flags: "gi"
38531
37673
  },
38532
37674
  examples: ['"SELECT * FROM users WHERE id = " + userId']
@@ -38541,7 +37683,7 @@ var sql_inject_format_default = {
38541
37683
  severity: "high",
38542
37684
  matcher: {
38543
37685
  type: "regex",
38544
- pattern: "\\b(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?(?:[%][sd]|\\{[^}]+\\})",
37686
+ pattern: "\\b(?=(select\\b(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))\\1(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})|\\b(?=(where\\b(?:(?!\\bwhere\\b)[^\\n])*?=))\\2(?:(?!\\bwhere\\b)[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})",
38545
37687
  flags: "gi"
38546
37688
  },
38547
37689
  examples: [
@@ -38559,7 +37701,7 @@ var sql_inject_interp_default = {
38559
37701
  severity: "high",
38560
37702
  matcher: {
38561
37703
  type: "regex",
38562
- pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
37704
+ pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
38563
37705
  flags: "gi"
38564
37706
  },
38565
37707
  examples: [
@@ -38934,7 +38076,7 @@ var stack_trace_default = {
38934
38076
  severity: "low",
38935
38077
  matcher: {
38936
38078
  type: "regex",
38937
- pattern: "(?:^|\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38079
+ pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
38938
38080
  flags: "g"
38939
38081
  },
38940
38082
  examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
@@ -40092,7 +39234,7 @@ var BUNDLED_PACKS = [
40092
39234
  {
40093
39235
  packId: "code-flaws",
40094
39236
  name: "Code Security Flaws",
40095
- version: "0.1.0",
39237
+ version: "0.1.1",
40096
39238
  rawRules: [
40097
39239
  sql_inject_concat_default,
40098
39240
  sql_inject_concat_dot_default,
@@ -40142,7 +39284,7 @@ var BUNDLED_PACKS = [
40142
39284
  {
40143
39285
  packId: "core-code-context",
40144
39286
  name: "Code Context",
40145
- version: "0.2.1",
39287
+ version: "0.2.2",
40146
39288
  rawRules: [
40147
39289
  internal_ip_default,
40148
39290
  localhost_ref_default,
@@ -40279,6 +39421,11 @@ function bundledDetections() {
40279
39421
  }));
40280
39422
  return cachedDetections;
40281
39423
  }
39424
+ function shippedRegexMatchers() {
39425
+ return bundledDetections().flatMap((pack) => pack.rules).flatMap(
39426
+ (rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
39427
+ );
39428
+ }
40282
39429
  function uniqueRuleIds(findings) {
40283
39430
  return [...new Set(findings.map((f) => f.ruleId))].join(", ");
40284
39431
  }
@@ -40308,8 +39455,9 @@ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18,
40308
39455
  var ATTRIBUTION_MEMO_LIMIT = 64;
40309
39456
  var attributionMemo = /* @__PURE__ */ new Map();
40310
39457
  var NO_ATTRIBUTION = Object.freeze({});
40311
- function resolveRepoAttribution(cwd) {
39458
+ function resolveRepoAttribution(cwd, options) {
40312
39459
  try {
39460
+ if (options?.cache === false) return attributeRepo(cwd);
40313
39461
  const remembered = attributionMemo.get(cwd);
40314
39462
  if (remembered !== void 0) return remembered;
40315
39463
  const attribution = attributeRepo(cwd);
@@ -40409,9 +39557,9 @@ function slugFromUrl(url2) {
40409
39557
  }
40410
39558
 
40411
39559
  // ../../packages/plugin-sdk/src/events.ts
40412
- import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
39560
+ import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
40413
39561
  function contentHashOf(text) {
40414
- return createHash5("sha256").update(text).digest("hex");
39562
+ return createHash6("sha256").update(text).digest("hex");
40415
39563
  }
40416
39564
  function buildIngestEvent(input2) {
40417
39565
  const contentHash = input2.contentHash ?? contentHashOf(input2.content);
@@ -40586,9 +39734,10 @@ function createIsolatedScanner(data, opts = {}) {
40586
39734
  if (job.timer !== void 0) return;
40587
39735
  job.startedAt = performance.now();
40588
39736
  job.progressAt = job.startedAt;
39737
+ const budget = job.deadlineAt === void 0 ? job.budgetMs : Math.max(0, Math.min(job.budgetMs, job.deadlineAt - job.startedAt));
40589
39738
  job.timer = setTimeout(() => {
40590
39739
  onDeadline(job);
40591
- }, job.budgetMs);
39740
+ }, budget);
40592
39741
  }
40593
39742
  function runOne(spec, fail) {
40594
39743
  if (closed) {
@@ -40599,6 +39748,12 @@ function createIsolatedScanner(data, opts = {}) {
40599
39748
  fail({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
40600
39749
  return;
40601
39750
  }
39751
+ const now = performance.now();
39752
+ const deadlineAt = spec.deadlineAt;
39753
+ if (deadlineAt !== void 0 && deadlineAt <= now) {
39754
+ fail({ status: "timeout", culpritIndex: void 0, elapsedMs: 0 });
39755
+ return;
39756
+ }
40602
39757
  const started = ensureWorker();
40603
39758
  if (!(started instanceof Worker)) {
40604
39759
  broken = started.error;
@@ -40606,11 +39761,11 @@ function createIsolatedScanner(data, opts = {}) {
40606
39761
  return;
40607
39762
  }
40608
39763
  const id = nextJobId++;
40609
- const now = performance.now();
40610
39764
  const job = {
40611
39765
  id,
40612
39766
  worker: started,
40613
39767
  budgetMs: spec.budgetMs,
39768
+ deadlineAt,
40614
39769
  startedAt: now,
40615
39770
  progressIndex: -1,
40616
39771
  progressAt: now,
@@ -40624,14 +39779,19 @@ function createIsolatedScanner(data, opts = {}) {
40624
39779
  if (readyWorker === started) {
40625
39780
  beginDeadline(job);
40626
39781
  } else {
39782
+ const startBudget = spec.startBudgetMs ?? startBudgetMs;
39783
+ const callerLimited = deadlineAt !== void 0 && deadlineAt - now < startBudget;
39784
+ const startWaitMs = callerLimited ? deadlineAt - now : startBudget;
40627
39785
  job.startupTimer = setTimeout(() => {
40628
39786
  if (pending !== job) return;
40629
39787
  kill(job.worker);
40630
- failPending({
40631
- status: "unavailable",
40632
- reason: `the scan worker did not start within ${String(startBudgetMs)}ms`
40633
- });
40634
- }, startBudgetMs);
39788
+ failPending(
39789
+ callerLimited ? { status: "timeout", culpritIndex: void 0, elapsedMs: performance.now() - now } : {
39790
+ status: "unavailable",
39791
+ reason: `the scan worker did not start within ${String(startBudget)}ms`
39792
+ }
39793
+ );
39794
+ }, startWaitMs);
40635
39795
  }
40636
39796
  try {
40637
39797
  started.postMessage(spec.build(id));
@@ -40660,7 +39820,9 @@ function createIsolatedScanner(data, opts = {}) {
40660
39820
  return enqueue((resolve3) => {
40661
39821
  runOne(
40662
39822
  {
40663
- budgetMs,
39823
+ budgetMs: scanOpts?.budgetMs ?? budgetMs,
39824
+ startBudgetMs: scanOpts?.startBudgetMs,
39825
+ deadlineAt: scanOpts?.deadlineAt,
40664
39826
  build: (id) => ({
40665
39827
  kind: "scan",
40666
39828
  id,
@@ -40854,6 +40016,9 @@ function createGuardedScanner(partition, gateway, opts) {
40854
40016
  let unverified = partition.unverified;
40855
40017
  let isolated = unverified.length > 0 ? createIsolatedScanner({ verified, unverified }, opts) : void 0;
40856
40018
  let retired = false;
40019
+ let bounded;
40020
+ let boundedWarned = false;
40021
+ let closed = false;
40857
40022
  function inProcess(text, context) {
40858
40023
  return scan(text, verified, context);
40859
40024
  }
@@ -40915,21 +40080,58 @@ function createGuardedScanner(partition, gateway, opts) {
40915
40080
  await degrade();
40916
40081
  return inProcess(text, context);
40917
40082
  }
40083
+ async function scanBounded(text, context, bound) {
40084
+ const remainingMs = bound.remainingMs;
40085
+ let outcome;
40086
+ if (closed) {
40087
+ outcome = { status: "unavailable", reason: "the scan worker is closed" };
40088
+ } else if (remainingMs !== void 0 && !(remainingMs > 0)) {
40089
+ outcome = { status: "timeout", culpritIndex: void 0, elapsedMs: 0 };
40090
+ } else {
40091
+ bounded ??= createIsolatedScanner({ verified, unverified }, opts);
40092
+ const deadlineAt = remainingMs === void 0 ? void 0 : performance.now() + remainingMs;
40093
+ try {
40094
+ outcome = await bounded.scan(text, context, {
40095
+ budgetMs: bound.budgetMs,
40096
+ startBudgetMs: bound.startBudgetMs,
40097
+ deadlineAt
40098
+ });
40099
+ } catch (error62) {
40100
+ outcome = {
40101
+ status: "unavailable",
40102
+ reason: error62 instanceof Error ? error62.message : "the scan worker failed unexpectedly"
40103
+ };
40104
+ }
40105
+ }
40106
+ if (outcome.status !== "ok" && !boundedWarned) {
40107
+ boundedWarned = true;
40108
+ process.stderr.write(
40109
+ outcome.status === "timeout" ? `[aka] a large input could not be scanned within its time limit and was refused.
40110
+ ` : `[aka] a large input could not be scanned and was refused: ${outcome.reason}.
40111
+ `
40112
+ );
40113
+ }
40114
+ return outcome;
40115
+ }
40918
40116
  return {
40919
40117
  scan: guardedScan,
40118
+ scanBounded,
40920
40119
  degraded: () => retired,
40921
40120
  async close() {
40922
- await retire();
40121
+ closed = true;
40122
+ const live = bounded;
40123
+ bounded = void 0;
40124
+ await Promise.all([retire(), live?.close()]);
40923
40125
  }
40924
40126
  };
40925
40127
  }
40926
40128
 
40927
40129
  // ../../packages/plugin-sdk/src/hook-fail-opens.ts
40928
- import { readFileSync as readFileSync13 } from "fs";
40929
- import { join as join20 } from "path";
40130
+ import { readFileSync as readFileSync12 } from "fs";
40131
+ import { join as join19 } from "path";
40930
40132
  var HOOK_FAIL_OPENS_FILENAME = "hook-fail-opens.json";
40931
40133
  function hookFailOpensPath(dataDir2) {
40932
- return join20(dataDir2, HOOK_FAIL_OPENS_FILENAME);
40134
+ return join19(dataDir2, HOOK_FAIL_OPENS_FILENAME);
40933
40135
  }
40934
40136
  function recordHookFailOpen(dataDir2, nowMs) {
40935
40137
  try {
@@ -40948,7 +40150,7 @@ function recordHookFailOpen(dataDir2, nowMs) {
40948
40150
  }
40949
40151
  function readHookFailOpens(dataDir2) {
40950
40152
  try {
40951
- const parsed2 = JSON.parse(readFileSync13(hookFailOpensPath(dataDir2), "utf8"));
40153
+ const parsed2 = JSON.parse(readFileSync12(hookFailOpensPath(dataDir2), "utf8"));
40952
40154
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
40953
40155
  const record2 = parsed2;
40954
40156
  if (!isPositiveSafeInteger(record2.failOpens)) return null;
@@ -40962,67 +40164,6 @@ function isPositiveSafeInteger(value) {
40962
40164
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
40963
40165
  }
40964
40166
 
40965
- // ../../packages/plugin-sdk/src/host-floor.ts
40966
- import { readFileSync as readFileSync15 } from "fs";
40967
- import { join as join22 } from "path";
40968
-
40969
- // ../../packages/plugin-sdk/src/model-governance.ts
40970
- import {
40971
- closeSync as closeSync2,
40972
- fstatSync,
40973
- mkdirSync as mkdirSync2,
40974
- openSync as openSync2,
40975
- readFileSync as readFileSync14,
40976
- readSync,
40977
- writeFileSync as writeFileSync5
40978
- } from "fs";
40979
- import { join as join21 } from "path";
40980
- var TAIL_BYTES = 256 * 1024;
40981
-
40982
- // ../../packages/plugin-sdk/src/host-floor.ts
40983
- var HOST_FEATURE = {
40984
- ModelSwitch: "model-switch",
40985
- VaultPointerDisplay: "vault-pointer-display"
40986
- };
40987
- var HOST_FLOORS = {
40988
- [HOST_FEATURE.ModelSwitch]: {
40989
- label: "model-switch protection",
40990
- hookEvents: ["PreModelSwitch", "PostModelSwitch"],
40991
- since: "2.1.251"
40992
- },
40993
- [HOST_FEATURE.VaultPointerDisplay]: {
40994
- label: "vault pointer display",
40995
- hookEvents: ["MessageDisplay"],
40996
- since: "2.1.152"
40997
- }
40998
- };
40999
- var ANTIGRAVITY_HOST_FEATURE = {
41000
- EndOfTurnCapture: "end-of-turn-capture"
41001
- };
41002
- var ANTIGRAVITY_HOST_FLOORS = {
41003
- [ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
41004
- label: "end-of-turn history capture",
41005
- hookEvents: ["Stop"],
41006
- since: "1.1.10"
41007
- }
41008
- };
41009
-
41010
- // ../../packages/plugin-sdk/src/ignore-layers.ts
41011
- var import_ignore = __toESM(require_ignore(), 1);
41012
- import { readFileSync as readFileSync16 } from "fs";
41013
- import { join as join23 } from "path";
41014
-
41015
- // ../../packages/plugin-sdk/src/inventory-resolver.ts
41016
- import { arch, hostname as hostname4, platform, release } from "os";
41017
-
41018
- // ../../packages/plugin-sdk/src/nudge.ts
41019
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync6 } from "fs";
41020
- import { join as join24 } from "path";
41021
-
41022
- // ../../packages/plugin-sdk/src/paths.ts
41023
- import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
41024
- import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
41025
-
41026
40167
  // ../../packages/plugin-sdk/src/policy-resolver.ts
41027
40168
  import { randomUUID as randomUUID14 } from "crypto";
41028
40169
  function createPolicyResolver(bundle) {
@@ -41067,36 +40208,6 @@ function assignedRulePolicies(installed) {
41067
40208
  return out;
41068
40209
  }
41069
40210
 
41070
- // ../../packages/plugin-sdk/src/project-files.ts
41071
- import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
41072
- import { basename as basename5, join as join25 } from "path";
41073
-
41074
- // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
41075
- var optionalBaseUrl2 = external_exports.preprocess((v) => {
41076
- if (typeof v === "string" && v.trim() === "") return void 0;
41077
- return v;
41078
- }, external_exports.string().optional()).catch(void 0);
41079
- var optionalFlag = external_exports.preprocess((v) => {
41080
- if (typeof v !== "string") return false;
41081
- const normalized = v.trim().toLowerCase();
41082
- return normalized !== "" && normalized !== "0" && normalized !== "false";
41083
- }, external_exports.boolean()).catch(false);
41084
- var antigravityProviderEnvShape = {
41085
- GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
41086
- GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
41087
- };
41088
- var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
41089
-
41090
- // ../../packages/plugin-sdk/src/provider-env-codex.ts
41091
- var optionalBaseUrl3 = external_exports.preprocess((v) => {
41092
- if (typeof v === "string" && v.trim() === "") return void 0;
41093
- return v;
41094
- }, external_exports.string().optional()).catch(void 0);
41095
- var codexProviderEnvShape = {
41096
- OPENAI_BASE_URL: optionalBaseUrl3
41097
- };
41098
- var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
41099
-
41100
40211
  // ../../packages/plugin-sdk/src/runtime.ts
41101
40212
  import { randomUUID as randomUUID15 } from "crypto";
41102
40213
  var ENFORCEMENT_CEILING_ENABLED = false;
@@ -41137,6 +40248,19 @@ function conditionsMatch(conditions, ctx) {
41137
40248
  if (conditions.provider !== void 0) return false;
41138
40249
  return true;
41139
40250
  }
40251
+ var LARGE_INPUT_THRESHOLD_CHARS = 32768;
40252
+ var LARGE_INPUT_SCAN_BUDGET_MS = 2e3;
40253
+ var LARGE_INPUT_START_BUDGET_MS = 1500;
40254
+ function readRemainingMs(largeInput) {
40255
+ const read = largeInput.remainingMs;
40256
+ if (read === void 0) return void 0;
40257
+ try {
40258
+ const remaining = read();
40259
+ return typeof remaining !== "number" || Number.isNaN(remaining) ? 0 : remaining;
40260
+ } catch {
40261
+ return 0;
40262
+ }
40263
+ }
41140
40264
  var bundlesPacked = false;
41141
40265
  function createPluginRuntime(gateway, settings, opts) {
41142
40266
  if (!bundlesPacked) {
@@ -41146,6 +40270,7 @@ function createPluginRuntime(gateway, settings, opts) {
41146
40270
  const policyMode = settings.policy;
41147
40271
  let redactFallback = settings.redactFallback;
41148
40272
  const dataDir2 = opts?.dataDir;
40273
+ const largeInput = opts?.largeInput;
41149
40274
  let rules = [];
41150
40275
  let evidenceOf = evidenceLookup(rules);
41151
40276
  let scanner;
@@ -41358,7 +40483,24 @@ function createPluginRuntime(gateway, settings, opts) {
41358
40483
  await ensureInitialized();
41359
40484
  if (!scanner) throw new Error("the runtime initialized without a scanner");
41360
40485
  const shielded = shieldPointers(text);
41361
- const matched = await scanner.scan(shielded.text, context);
40486
+ let matched;
40487
+ if (largeInput !== void 0 && shielded.text.length >= largeInput.thresholdChars) {
40488
+ const outcome = await scanner.scanBounded(shielded.text, context, {
40489
+ budgetMs: largeInput.budgetMs,
40490
+ startBudgetMs: largeInput.startBudgetMs,
40491
+ remainingMs: readRemainingMs(largeInput)
40492
+ });
40493
+ if (outcome.status !== "ok") {
40494
+ return {
40495
+ decision: { action: "block", text: null, findings: [], scanIncomplete: outcome.status },
40496
+ excepted: /* @__PURE__ */ new Set(),
40497
+ exceptionIds: []
40498
+ };
40499
+ }
40500
+ matched = outcome.findings;
40501
+ } else {
40502
+ matched = await scanner.scan(shielded.text, context);
40503
+ }
41362
40504
  const findings = dropShieldedFindings(matched, shielded.spans);
41363
40505
  const fpCache = /* @__PURE__ */ new Map();
41364
40506
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
@@ -41383,12 +40525,11 @@ function createPluginRuntime(gateway, settings, opts) {
41383
40525
  async function processText(text, context, opts2 = {}) {
41384
40526
  return (await evaluate(text, context, {}, opts2.rewritable)).decision;
41385
40527
  }
41386
- async function capture(input2, opts2 = {}) {
40528
+ async function evaluateCapture(input2, opts2) {
41387
40529
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
41388
- const filePath = input2.metadata?.filePath;
41389
40530
  const { decision, excepted, exceptionIds } = await evaluate(
41390
40531
  input2.text,
41391
- { filePath, eventKind: input2.kind },
40532
+ { filePath: input2.metadata?.filePath, eventKind: input2.kind },
41392
40533
  {
41393
40534
  sourceTool: input2.sourceTool,
41394
40535
  metadata: input2.metadata,
@@ -41396,20 +40537,28 @@ function createPluginRuntime(gateway, settings, opts) {
41396
40537
  },
41397
40538
  opts2.rewritable
41398
40539
  );
41399
- if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
40540
+ return { decision, excepted, exceptionIds, timingStartedAt };
40541
+ }
40542
+ async function persistCapture(input2, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
40543
+ const filePath = input2.metadata?.filePath;
40544
+ if (opts2.persist === "with-findings" && decision.findings.length === 0 && decision.scanIncomplete === void 0) {
40545
+ return;
40546
+ }
41400
40547
  try {
41401
40548
  const contentHash = contentHashOf(input2.text);
41402
40549
  const maskedFindings = decision.findings.filter(
41403
40550
  (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
41404
40551
  );
41405
- const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
40552
+ const storedContent = decision.scanIncomplete !== void 0 ? "" : maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
41406
40553
  const inspectionMs = elapsedMs(timingStartedAt);
41407
40554
  const redactDegradedTo = decision.redactDegradedTo;
41408
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
40555
+ const scanIncomplete = decision.scanIncomplete;
40556
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 || scanIncomplete !== void 0 ? {
41409
40557
  ...input2.metadata,
41410
40558
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
41411
40559
  ...inspectionMs !== void 0 ? { inspectionMs } : {},
41412
- ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
40560
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {},
40561
+ ...scanIncomplete !== void 0 ? { scanIncomplete } : {}
41413
40562
  } : input2.metadata;
41414
40563
  const event = buildIngestEvent({
41415
40564
  kind: input2.kind,
@@ -41439,6 +40588,8 @@ function createPluginRuntime(gateway, settings, opts) {
41439
40588
  // exceptions/blocked_detections when a key is available;
41440
40589
  // falls back to the masked match so at-rest findings still get
41441
40590
  // a stable (if weaker) identity on a workspace with no dataDir.
40591
+ // Both ignore the same invisible padding, so a clean and a
40592
+ // padded occurrence of one secret key alike on either path.
41442
40593
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
41443
40594
  }) : void 0;
41444
40595
  return {
@@ -41466,7 +40617,37 @@ function createPluginRuntime(gateway, settings, opts) {
41466
40617
  }
41467
40618
  } catch {
41468
40619
  }
41469
- return decision;
40620
+ }
40621
+ async function enforcedIn(text, context) {
40622
+ try {
40623
+ await ensureInitialized();
40624
+ if (!scanner) return [];
40625
+ const shielded = shieldPointers(text);
40626
+ const matched = await scanner.scan(shielded.text, context);
40627
+ return dropShieldedFindings(matched, shielded.spans).filter((finding) => {
40628
+ const action = resolveAction(finding.ruleId, finding.category);
40629
+ return action === "block" || action === "redact";
40630
+ });
40631
+ } catch {
40632
+ return [];
40633
+ }
40634
+ }
40635
+ async function capture(input2, opts2 = {}) {
40636
+ const evaluated = await evaluateCapture(input2, opts2);
40637
+ await persistCapture(input2, opts2, evaluated);
40638
+ return evaluated.decision;
40639
+ }
40640
+ async function captureDeferred(input2, opts2 = {}) {
40641
+ const evaluated = await evaluateCapture(input2, opts2);
40642
+ let recorded = false;
40643
+ return {
40644
+ result: evaluated.decision,
40645
+ record: async () => {
40646
+ if (recorded) return;
40647
+ recorded = true;
40648
+ await persistCapture(input2, opts2, evaluated);
40649
+ }
40650
+ };
41470
40651
  }
41471
40652
  async function rulesetFingerprint() {
41472
40653
  try {
@@ -41487,21 +40668,435 @@ function createPluginRuntime(gateway, settings, opts) {
41487
40668
  }
41488
40669
  await gateway.close();
41489
40670
  }
41490
- return { processText, capture, rulesetFingerprint, scanIsolationDegraded, close };
40671
+ return {
40672
+ processText,
40673
+ capture,
40674
+ captureDeferred,
40675
+ enforcedIn,
40676
+ rulesetFingerprint,
40677
+ scanIsolationDegraded,
40678
+ close
40679
+ };
41491
40680
  }
41492
40681
 
41493
- // ../../packages/plugin-sdk/src/scope-key.ts
41494
- import { existsSync as existsSync12 } from "fs";
41495
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join26, normalize } from "path";
40682
+ // ../../packages/remote/src/http.ts
40683
+ import { request as httpRequest } from "http";
40684
+ import { request as httpsRequest } from "https";
40685
+ var DEFAULT_TIMEOUT_MS = 1e4;
40686
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
40687
+ var RemoteRequestError = class extends Error {
40688
+ constructor(status) {
40689
+ super(`control-plane request failed with status ${String(status)}`);
40690
+ this.status = status;
40691
+ this.name = "RemoteRequestError";
40692
+ }
40693
+ status;
40694
+ };
40695
+ var RemoteRouteAbsent = class extends Error {
40696
+ constructor(route) {
40697
+ super(`control plane does not serve ${route}`);
40698
+ this.route = route;
40699
+ this.name = "RemoteRouteAbsent";
40700
+ }
40701
+ route;
40702
+ };
40703
+ var RemoteRequestInvalid = class extends Error {
40704
+ constructor(route, cause) {
40705
+ super(`refusing to send a malformed body to ${route}`);
40706
+ this.cause = cause;
40707
+ this.name = "RemoteRequestInvalid";
40708
+ }
40709
+ cause;
40710
+ };
40711
+ var RemoteEndpointRefused = class extends Error {
40712
+ constructor(endpoint) {
40713
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
40714
+ this.name = "RemoteEndpointRefused";
40715
+ }
40716
+ };
40717
+ var RemoteResponseInvalid = class extends Error {
40718
+ constructor(route, detail) {
40719
+ super(`control plane answered ${route} with ${detail}`);
40720
+ this.name = "RemoteResponseInvalid";
40721
+ }
40722
+ };
40723
+ var RemoteTransportError = class extends Error {
40724
+ /**
40725
+ * The status the peer sent, when headers arrived and only the BODY was
40726
+ * refused.
40727
+ *
40728
+ * Undefined for the ordinary case this class was written for — no answer at
40729
+ * all. It exists because two paths reject after a status has already been
40730
+ * delivered: an oversized body and an aborted response. Discarding it there
40731
+ * reported a deployment answering 401 with a verbose body as a network
40732
+ * outage, which sends the reader to look at their network instead of their
40733
+ * credential.
40734
+ */
40735
+ constructor(reason, status) {
40736
+ super(`control-plane request did not complete: ${reason}`);
40737
+ this.status = status;
40738
+ this.name = "RemoteTransportError";
40739
+ }
40740
+ status;
40741
+ };
40742
+ async function send(options) {
40743
+ const url2 = new URL(options.url);
40744
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
40745
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
40746
+ const requestOptions = {
40747
+ method: options.method,
40748
+ headers: {
40749
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
40750
+ // last they win, and two of the values below are ones no caller may
40751
+ // replace: `x-api-key` is the credential, and `content-length` is the
40752
+ // byte count that stops a multi-byte body being truncated by the
40753
+ // receiver. `SendOptions.headers` is a free-form record on an exported
40754
+ // function, so "no caller does that today" is not the guarantee to rely
40755
+ // on. The one header any caller actually passes — `if-none-match` on the
40756
+ // conditional GET — is untouched by this order.
40757
+ ...options.headers,
40758
+ // The credential. One header, matching what the deployment authenticates
40759
+ // on; a second copy in an `Authorization` header would be one more place
40760
+ // it can be logged by an intermediary for no gain.
40761
+ //
40762
+ // Spread conditionally rather than assigned as `undefined`: Node's header
40763
+ // handling and `content-length` bookkeeping treat a present-but-undefined
40764
+ // key differently from an absent one, and "the header is not there" is
40765
+ // the property the attach flow needs.
40766
+ ...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
40767
+ accept: "application/json",
40768
+ ...options.body === void 0 ? {} : {
40769
+ "content-type": "application/json",
40770
+ // Byte length, not string length: a multi-byte body sent with a
40771
+ // character count is truncated by the receiver.
40772
+ "content-length": String(Buffer.byteLength(options.body))
40773
+ }
40774
+ }
40775
+ };
40776
+ return new Promise((resolve3, reject) => {
40777
+ let settled = false;
40778
+ const fail = (reason, status) => {
40779
+ if (settled) return;
40780
+ settled = true;
40781
+ reject(new RemoteTransportError(reason, status));
40782
+ };
40783
+ const req = send_(url2, requestOptions, (res) => {
40784
+ const chunks = [];
40785
+ let size = 0;
40786
+ res.on("data", (chunk) => {
40787
+ size += chunk.length;
40788
+ if (size > MAX_RESPONSE_BYTES) {
40789
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
40790
+ res.destroy();
40791
+ req.destroy();
40792
+ return;
40793
+ }
40794
+ chunks.push(chunk);
40795
+ });
40796
+ res.on("aborted", () => {
40797
+ fail("the response was aborted", res.statusCode);
40798
+ });
40799
+ res.on("end", () => {
40800
+ if (settled) return;
40801
+ settled = true;
40802
+ resolve3({
40803
+ status: res.statusCode ?? 0,
40804
+ headers: res.headers,
40805
+ body: Buffer.concat(chunks).toString("utf8")
40806
+ });
40807
+ });
40808
+ });
40809
+ const deadline = setTimeout(() => {
40810
+ fail(`no response within ${String(timeoutMs)}ms`);
40811
+ req.destroy();
40812
+ }, timeoutMs);
40813
+ deadline.unref();
40814
+ req.on("upgrade", (_res, socket) => {
40815
+ fail("the deployment answered with a protocol upgrade");
40816
+ socket.destroy();
40817
+ });
40818
+ req.on("close", () => {
40819
+ fail("the connection closed before a response was read");
40820
+ clearTimeout(deadline);
40821
+ });
40822
+ req.on("error", (err) => {
40823
+ fail(err.message);
40824
+ });
40825
+ if (options.body !== void 0) req.write(options.body);
40826
+ req.end();
40827
+ });
40828
+ }
41496
40829
 
41497
- // ../../packages/plugin-sdk/src/suppressions.ts
41498
- var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
40830
+ // ../../packages/remote/src/client.ts
40831
+ var ROUTES = {
40832
+ events: "/v1/events",
40833
+ auditEvents: "/v1/audit-events",
40834
+ auditEventsBatch: "/v1/audit-events/batch",
40835
+ inventory: "/v1/inventory",
40836
+ storePosture: "/v1/store-posture",
40837
+ policyBundle: "/v1/policy-bundle",
40838
+ whoami: "/v1/plugin/whoami",
40839
+ shares: "/v1/shares",
40840
+ commands: "/v1/plugin/commands"
40841
+ };
40842
+ function ackRoute(id) {
40843
+ return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
40844
+ }
40845
+ function headerValue(response, name) {
40846
+ const raw = response.headers[name];
40847
+ if (raw === void 0) return void 0;
40848
+ return Array.isArray(raw) ? raw[0] : raw;
40849
+ }
40850
+ function okBody(response) {
40851
+ if (response.status < 200 || response.status >= 300) {
40852
+ throw new RemoteRequestError(response.status);
40853
+ }
40854
+ return response.body;
40855
+ }
40856
+ function parsed(schema, body, route) {
40857
+ let json2;
40858
+ try {
40859
+ json2 = JSON.parse(body);
40860
+ } catch {
40861
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
40862
+ }
40863
+ const result = schema.safeParse(json2);
40864
+ if (!result.success) {
40865
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
40866
+ }
40867
+ return result.data;
40868
+ }
40869
+ function resolveBaseUrl(endpoint) {
40870
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
40871
+ let end = endpoint.length;
40872
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
40873
+ return endpoint.slice(0, end);
40874
+ }
40875
+ var SLASH2 = "/".charCodeAt(0);
40876
+ function createRemoteClient(options) {
40877
+ const base = resolveBaseUrl(options.endpoint);
40878
+ const url2 = (route) => `${base}${route}`;
40879
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
40880
+ const sendOne = async (event) => {
40881
+ const validated = RecordAuditEventRequest.safeParse(event);
40882
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
40883
+ const response = await send({
40884
+ ...common,
40885
+ method: "POST",
40886
+ url: url2(ROUTES.auditEvents),
40887
+ body: JSON.stringify(validated.data)
40888
+ });
40889
+ okBody(response);
40890
+ };
40891
+ return {
40892
+ async ingestEvents(batch) {
40893
+ const response = await send({
40894
+ ...common,
40895
+ method: "POST",
40896
+ url: url2(ROUTES.events),
40897
+ body: JSON.stringify(batch)
40898
+ });
40899
+ return parsed(IngestAck, okBody(response), ROUTES.events);
40900
+ },
40901
+ async ingestInventory(context) {
40902
+ const response = await send({
40903
+ ...common,
40904
+ method: "POST",
40905
+ url: url2(ROUTES.inventory),
40906
+ body: JSON.stringify(context)
40907
+ });
40908
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
40909
+ },
40910
+ async recordAuditEvent(event) {
40911
+ await sendOne(event);
40912
+ },
40913
+ async recordAuditEvents(events, opts) {
40914
+ const validated = RecordAuditEventBatch.safeParse({ events });
40915
+ if (!validated.success) {
40916
+ throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
40917
+ }
40918
+ const response = await send({
40919
+ ...common,
40920
+ method: "POST",
40921
+ url: url2(ROUTES.auditEventsBatch),
40922
+ body: JSON.stringify(validated.data)
40923
+ });
40924
+ if (response.status === 404) {
40925
+ if (opts?.fallbackToSingleEvents !== true) {
40926
+ throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
40927
+ }
40928
+ for (const event of validated.data.events) await sendOne(event);
40929
+ return { accepted: validated.data.events.length };
40930
+ }
40931
+ return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
40932
+ },
40933
+ async reportStorePosture(snapshot) {
40934
+ const response = await send({
40935
+ ...common,
40936
+ method: "POST",
40937
+ url: url2(ROUTES.storePosture),
40938
+ body: JSON.stringify(snapshot)
40939
+ });
40940
+ okBody(response);
40941
+ },
40942
+ async getPolicyBundle(etag) {
40943
+ const response = await send({
40944
+ ...common,
40945
+ method: "GET",
40946
+ url: url2(ROUTES.policyBundle),
40947
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
40948
+ });
40949
+ if (response.status === 304) {
40950
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
40951
+ }
40952
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
40953
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
40954
+ },
40955
+ async whoami() {
40956
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
40957
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
40958
+ },
40959
+ async recordProjectEgress(request) {
40960
+ const validated = EgressIngestRequest.safeParse(request);
40961
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
40962
+ const response = await send({
40963
+ ...common,
40964
+ method: "POST",
40965
+ url: url2(ROUTES.shares),
40966
+ body: JSON.stringify(validated.data)
40967
+ });
40968
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
40969
+ okBody(response);
40970
+ },
40971
+ async pollCommand() {
40972
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
40973
+ if (response.status === 404) return null;
40974
+ return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
40975
+ },
40976
+ async ackCommand(id, body) {
40977
+ const validated = DeviceCommandAckBody.safeParse(body);
40978
+ const route = ackRoute(id);
40979
+ if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
40980
+ const response = await send({
40981
+ ...common,
40982
+ method: "POST",
40983
+ url: url2(route),
40984
+ body: JSON.stringify(validated.data)
40985
+ });
40986
+ okBody(response);
40987
+ }
40988
+ };
40989
+ }
40990
+
40991
+ // ../../packages/remote/src/failure-kind.ts
40992
+ function statusOf(err) {
40993
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
40994
+ const { status } = err;
40995
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
40996
+ return status >= 100 && status <= 599 ? status : null;
40997
+ }
40998
+ function nameOf(err) {
40999
+ if (typeof err !== "object" || err === null || !("name" in err)) return null;
41000
+ return typeof err.name === "string" ? err.name : null;
41001
+ }
41002
+ function classifyRemoteFailure(err) {
41003
+ switch (nameOf(err)) {
41004
+ case "RemoteRouteAbsent":
41005
+ return "route-absent";
41006
+ case "RemoteRequestInvalid":
41007
+ case "RemoteEndpointRefused":
41008
+ return "invalid-request";
41009
+ case "RemoteResponseInvalid":
41010
+ return "rejected";
41011
+ default:
41012
+ break;
41013
+ }
41014
+ const status = statusOf(err);
41015
+ if (status === null) return "unreachable";
41016
+ switch (status) {
41017
+ case 401:
41018
+ return "unauthorized";
41019
+ case 403:
41020
+ return "forbidden";
41021
+ case 429:
41022
+ return "unreachable";
41023
+ case 404:
41024
+ return "unreachable";
41025
+ default:
41026
+ return status >= 400 && status <= 499 ? "rejected" : "unreachable";
41027
+ }
41028
+ }
41029
+
41030
+ // ../../packages/plugin-runtime/src/attached/failure.ts
41031
+ function classifyFailure(err) {
41032
+ switch (classifyRemoteFailure(err)) {
41033
+ case "unauthorized":
41034
+ return "unauthorized";
41035
+ case "forbidden":
41036
+ return "forbidden";
41037
+ default:
41038
+ return "unreachable";
41039
+ }
41040
+ }
41499
41041
 
41500
- // ../../packages/plugin-sdk/src/throttle.ts
41501
- import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
41502
- import { join as join27 } from "path";
41042
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
41043
+ var REQUEST_TIMEOUT_MS = 2e3;
41044
+ function withTimeout(promise2, ms) {
41045
+ let timer;
41046
+ const timeout = new Promise((_, reject) => {
41047
+ timer = setTimeout(() => {
41048
+ reject(new Error("attached gateway request timed out"));
41049
+ }, ms);
41050
+ });
41051
+ promise2.catch(() => void 0);
41052
+ return Promise.race([promise2, timeout]).finally(() => {
41053
+ clearTimeout(timer);
41054
+ });
41055
+ }
41056
+
41057
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
41058
+ import { readFileSync as readFileSync13 } from "fs";
41059
+ import { join as join20 } from "path";
41060
+ var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
41061
+ function forwardDropsPath(dataDir2) {
41062
+ return join20(dataDir2, FORWARD_DROPS_FILENAME);
41063
+ }
41064
+ function recordForwardDrops(dataDir2, count, nowMs) {
41065
+ if (count <= 0) return;
41066
+ try {
41067
+ ensureDataDirSync(dataDir2);
41068
+ const previous = readForwardDrops(dataDir2);
41069
+ const next = {
41070
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
41071
+ lastDropAtMs: nowMs
41072
+ };
41073
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
41074
+ `);
41075
+ } catch {
41076
+ }
41077
+ }
41078
+ function readForwardDrops(dataDir2) {
41079
+ try {
41080
+ const parsed2 = JSON.parse(readFileSync13(forwardDropsPath(dataDir2), "utf8"));
41081
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
41082
+ const record2 = parsed2;
41083
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
41084
+ return null;
41085
+ }
41086
+ if (record2.droppedForwards <= 0) return null;
41087
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
41088
+ return null;
41089
+ }
41090
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
41091
+ } catch {
41092
+ return null;
41093
+ }
41094
+ }
41503
41095
 
41504
41096
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
41097
+ import { randomUUID as randomUUID16 } from "crypto";
41098
+ import { readFile, rename, writeFile } from "fs/promises";
41099
+ import { join as join21 } from "path";
41505
41100
  function isInvalidRequest(err) {
41506
41101
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
41507
41102
  }
@@ -41520,7 +41115,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
41520
41115
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
41521
41116
  function createForwardPolicy(deps) {
41522
41117
  const now = deps.now ?? (() => Date.now());
41523
- const file2 = join28(deps.dir, STATE_FILENAME);
41118
+ const file2 = join21(deps.dir, STATE_FILENAME);
41524
41119
  let state = null;
41525
41120
  let loading = null;
41526
41121
  async function readState() {
@@ -41686,6 +41281,9 @@ var AttachedDataGateway = class {
41686
41281
  *
41687
41282
  * Machine mode answers before any key is read, so a machine attachment pays
41688
41283
  * nothing for scoping and forwards exactly what it always has.
41284
+ *
41285
+ * `governanceAppliesTo` answers from this same verdict, so it agrees with
41286
+ * forwarding key for key.
41689
41287
  */
41690
41288
  verdictFor(keyOf) {
41691
41289
  try {
@@ -41702,24 +41300,27 @@ var AttachedDataGateway = class {
41702
41300
  * the key its row holds in the local store, recorded per root (see
41703
41301
  * `rootVerdict`), not the key on the root event just handed in: roots are
41704
41302
  * first-write-wins in the store, so when two producers record a root for one
41705
- * session (the session-start hook, then a reconcile pass) the second leaves
41706
- * the stored row as it was, and the history drain decides that row, not this
41707
- * event. Whether this root EVENT is itself sent takes both keys: the stored
41708
- * one AND its own. The event's attributes (cwd, project, repo) describe where
41709
- * it was recorded from, so a root event keyed to a personal directory is never
41710
- * sent under an enrolled stored root, though the enrolled leaves still forward
41711
- * under it: the instance that wrote the stored root is expected to have
41712
- * forwarded it. If it did not (the root was written while standalone or under
41713
- * another attachment, or its forward failed), the plane refuses those leaves
41714
- * and the history drain ships the root first. Any other row with a root
41715
- * reference (`rootSessionId`, else `parentId`) forwards only when its own key
41716
- * is in scope AND this instance recorded an in-scope verdict for that root.
41717
- * The audit-event route has real foreign keys on both columns and stubs no
41718
- * missing root, so a leaf sent after its root was kept local is refused
41719
- * there, and a refused forward counts toward the breaker that guards every
41720
- * other one. A root this instance never recorded is therefore `'local'`: the
41721
- * only answer that cannot orphan a row. A row with no root reference at all
41722
- * has nothing to orphan, and is decided by its own key.
41303
+ * session (the session-start hook, then a reconcile pass) the second leaves the
41304
+ * stored row as it was. That stored row, not this event, is what a history
41305
+ * drain pass would decide, if the root started before the attach; the drain
41306
+ * never offers one that started after it (`started_at < backlogBefore`).
41307
+ * Whether this root EVENT is itself sent takes both keys: the stored one AND
41308
+ * its own. The event's attributes (cwd, project, repo) describe where it was
41309
+ * recorded from, so a root event keyed to a personal directory is never sent
41310
+ * under an enrolled stored root, though the enrolled leaves still forward under
41311
+ * it: the instance that wrote the stored root is expected to have forwarded it.
41312
+ * If it did not (the root was written while standalone or under another
41313
+ * attachment, or its forward failed), the plane refuses those leaves. A root
41314
+ * that started before the attach is shipped, ahead of its leaves, by the
41315
+ * history drain; one that started after it is never offered by the drain. Any
41316
+ * other row with a root reference (`rootSessionId`, else `parentId`) forwards
41317
+ * only when its own key is in scope AND this instance recorded an in-scope
41318
+ * verdict for that root. The audit-event route has real foreign keys on both
41319
+ * columns and stubs no missing root, so a leaf sent after its root was kept
41320
+ * local is refused there, and a refused forward counts toward the breaker that
41321
+ * guards every other one. A root this instance never recorded is therefore
41322
+ * `'local'`: the only answer that cannot orphan a row. A row with no root
41323
+ * reference at all has nothing to orphan, and is decided by its own key.
41723
41324
  *
41724
41325
  * What this costs is stated rather than discovered. A session whose stored
41725
41326
  * root is not keyed to an enrolled repository keeps its token and tool
@@ -41790,6 +41391,87 @@ var AttachedDataGateway = class {
41790
41391
  return [];
41791
41392
  }
41792
41393
  }
41394
+ /**
41395
+ * The verdict for the repositories nested in a scanned project, answered
41396
+ * TOTALLY: `'forward'` or `'local'`, never a throw.
41397
+ *
41398
+ * A walk descends into a nested clone or submodule and folds its files into
41399
+ * the project it is walking, so one register can carry several
41400
+ * repositories' call sites under one project key. Each of them must be in
41401
+ * scope for it to forward. One key out of scope, or a nested repository with
41402
+ * no remote (an `undefined` key), keeps the whole register local.
41403
+ *
41404
+ * An ABSENT list is `'local'` too. Only the code that walked the tree can say
41405
+ * what is nested in it, and every scan passes the list, empty when nothing
41406
+ * is nested. A register nobody vouched for is not one a scoped attachment
41407
+ * may send.
41408
+ *
41409
+ * Machine mode answers before reading the context, so a machine attachment
41410
+ * forwards exactly what it always has.
41411
+ */
41412
+ nestedVerdict(context) {
41413
+ try {
41414
+ if (this.deps.attachment.mode === "machine") return "forward";
41415
+ const keys = context?.nestedScopeKeys;
41416
+ if (keys === void 0) return "local";
41417
+ for (const key of keys) {
41418
+ if (this.verdictFor(() => key) === "local") return "local";
41419
+ }
41420
+ return "forward";
41421
+ } catch {
41422
+ return "local";
41423
+ }
41424
+ }
41425
+ /**
41426
+ * The register a scoped attachment sends, once the project and the repositories
41427
+ * nested in it are in scope: the register itself, with `reconcile.deletedFiles`
41428
+ * cut to the deleted paths whose own repository is in scope. `undefined` sends
41429
+ * nothing. TOTAL, like `verdictFor`, and for its reasons.
41430
+ *
41431
+ * The deletion sweep takes its paths from the scan ledger, not from the walk,
41432
+ * and the ledger holds every file the scanner ever read under the root, nested
41433
+ * clones' included. So a clone that was removed, or one an ignore file now
41434
+ * hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
41435
+ * paths come back as deleted. The scan names the repository of each deleted
41436
+ * path (`context.deletedFileKeys`, one entry per path in the register's order)
41437
+ * and each is held to the same verdict as any other key. A path whose key is
41438
+ * absent, or out of scope, is not sent.
41439
+ *
41440
+ * The list is asked for here, and only here: it is an async read of the scan
41441
+ * ledger that the scan makes on being called, so a machine attachment, which
41442
+ * returns before this, and a register already kept local never cause it.
41443
+ *
41444
+ * Anything the scan did not vouch for sends no deleted path, and the register
41445
+ * itself still goes: no list, a list that throws or whose read is rejected, or a
41446
+ * list whose length is not the register's. Deleting is the only thing a dropped
41447
+ * path could have done on the server, so the cost of a refusal is a stored row
41448
+ * that stays, never a path that leaves.
41449
+ *
41450
+ * Machine mode returns `input` itself, the same object and unread, so a machine
41451
+ * attachment's request is exactly what it was. A register that lists no deleted
41452
+ * path, or that is not a ledger register, has nothing to cut and is returned
41453
+ * as it came, with the list unread.
41454
+ */
41455
+ async registerForWire(input2, context) {
41456
+ try {
41457
+ if (this.deps.attachment.mode === "machine") return input2;
41458
+ const { reconcile } = input2;
41459
+ if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
41460
+ const deleted = reconcile.deletedFiles;
41461
+ let kept = [];
41462
+ try {
41463
+ const keys = await context?.deletedFileKeys?.();
41464
+ if (keys?.length === deleted.length) {
41465
+ kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
41466
+ }
41467
+ } catch {
41468
+ kept = [];
41469
+ }
41470
+ return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
41471
+ } catch {
41472
+ return void 0;
41473
+ }
41474
+ }
41793
41475
  /**
41794
41476
  * The event `recordCapture` sends for a capture the verdict let through, or
41795
41477
  * `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
@@ -42115,12 +41797,24 @@ var AttachedDataGateway = class {
42115
41797
  * payload onto the wire-boundary-safe shape (no snippet, hashed
42116
41798
  * projectKey), and its result is discarded: `forward.run` never throws or
42117
41799
  * rejects, so there is nothing here to act on.
41800
+ *
41801
+ * `context.nestedScopeKeys` is what the scanner knows and the register does
41802
+ * not say: the key of every repository nested below the scan root, whose
41803
+ * files the walk folded into this register. On a scoped attachment the
41804
+ * register is forwarded only when the project's own key AND every one of
41805
+ * those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
41806
+ * ones whose own repository is in scope (`context.deletedFileKeys`, see
41807
+ * `registerForWire`). Machine mode never reads either, and the local write
41808
+ * never receives the context and gets the register whole.
42118
41809
  */
42119
- async recordProjectEgress(input2) {
41810
+ async recordProjectEgress(input2, context) {
42120
41811
  const summary = await this.deps.local.recordProjectEgress(input2);
42121
41812
  if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
41813
+ if (this.nestedVerdict(context) === "local") return summary;
41814
+ const register = await this.registerForWire(input2, context);
41815
+ if (register === void 0) return summary;
42122
41816
  await this.deps.forward.run(
42123
- () => this.deps.client.recordProjectEgress(toEgressIngestRequest(input2))
41817
+ () => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
42124
41818
  );
42125
41819
  return summary;
42126
41820
  }
@@ -42174,6 +41868,11 @@ var AttachedDataGateway = class {
42174
41868
  async scanLedgerPaths() {
42175
41869
  return this.deps.local.scanLedgerPaths();
42176
41870
  }
41871
+ // Delegated, like the path list. An inner gateway that cannot say answers an
41872
+ // empty map, which gives every deleted path no key.
41873
+ async scanLedgerPathKeys() {
41874
+ return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
41875
+ }
42177
41876
  async recordScanned(entries) {
42178
41877
  return this.deps.local.recordScanned(entries);
42179
41878
  }
@@ -42240,6 +41939,12 @@ var AttachedDataGateway = class {
42240
41939
  // and the spread above would otherwise drop the field silently — which is
42241
41940
  // exactly what it did, leaving the whole control inert on every device
42242
41941
  // while every test around it stayed green.
41942
+ //
41943
+ // WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
41944
+ // here: the port's `getPolicyBundle()` takes no event, and the runtime
41945
+ // reads this bundle once to build detection, so the detections it carries
41946
+ // apply to every event on the machine. Where a prohibition applies is
41947
+ // answered per event by `governanceAppliesTo` below.
42243
41948
  prohibitedModels: cached2.prohibitedModels,
42244
41949
  // NAMED for the same reason as the line above, and it is the same defect
42245
41950
  // if it is not: `...local` above spreads the DEVICE's bundle, so a field
@@ -42299,6 +42004,30 @@ var AttachedDataGateway = class {
42299
42004
  };
42300
42005
  }
42301
42006
  // ---------------------------------------------------------------------
42007
+ // GovernanceScope — where the organization's model policy applies
42008
+ // ---------------------------------------------------------------------
42009
+ /**
42010
+ * Whether the organization's governance applies to an event keyed `scopeKey`:
42011
+ * the question a model-guard site asks once it has decided to refuse.
42012
+ *
42013
+ * THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
42014
+ * with the same key would be forwarded. A machine-wide attachment governs
42015
+ * every event, keyless included, exactly as before. A scoped one governs an
42016
+ * event only when its key names an enrolled repository. An event in a
42017
+ * personal repository, in no repository, with an empty key, or met by a fault
42018
+ * is not governed.
42019
+ *
42020
+ * The event's OWN key, never its session root's. The root rule in
42021
+ * `auditVerdict` decides whether a row can be forwarded without orphaning it;
42022
+ * this decides whether a refusal applies, which is a question about where the
42023
+ * event happened.
42024
+ *
42025
+ * Answered from memory: no store read, no bundle read, nothing sent.
42026
+ */
42027
+ governanceAppliesTo(scopeKey) {
42028
+ return this.verdictFor(() => scopeKey) === "forward";
42029
+ }
42030
+ // ---------------------------------------------------------------------
42302
42031
  // LocalStoreMaintenance — by delegation (D3).
42303
42032
  //
42304
42033
  // Implementing these is what actually closes the skipped-local-maintenance
@@ -42407,14 +42136,15 @@ function toWireInspection(insp) {
42407
42136
  }
42408
42137
 
42409
42138
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42410
- import { createHash as createHash6 } from "crypto";
42411
- import { hostname as hostname5 } from "os";
42139
+ import { createHash as createHash7 } from "crypto";
42140
+ import { hostname as hostname4 } from "os";
42412
42141
 
42413
42142
  // ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
42414
42143
  var CORRELATION_ID = EventMetadata.shape.correlationId;
42415
42144
  var TRACE_ID = EventMetadata.shape.traceId;
42416
42145
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
42417
42146
  var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
42147
+ var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
42418
42148
 
42419
42149
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
42420
42150
  var CAPTURE_BATCH_BYTES = 1024 * 1024;
@@ -42426,17 +42156,17 @@ var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
42426
42156
 
42427
42157
  // ../../packages/plugin-runtime/src/attached/install-record.ts
42428
42158
  import { readFile as readFile2, stat } from "fs/promises";
42429
- import { basename as basename6, dirname as dirname7, join as join29, resolve as resolve2 } from "path";
42159
+ import { basename as basename3, dirname as dirname5, join as join22, resolve as resolve2 } from "path";
42430
42160
  async function readInstalledVersion(installRoot) {
42431
42161
  try {
42432
42162
  const versionDir = resolve2(installRoot);
42433
- const pluginDir = dirname7(versionDir);
42434
- const marketplaceDir = dirname7(pluginDir);
42435
- const cacheDir = dirname7(marketplaceDir);
42436
- if (basename6(cacheDir) !== "cache") return null;
42437
- const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
42163
+ const pluginDir = dirname5(versionDir);
42164
+ const marketplaceDir = dirname5(pluginDir);
42165
+ const cacheDir = dirname5(marketplaceDir);
42166
+ if (basename3(cacheDir) !== "cache") return null;
42167
+ const key = `${basename3(pluginDir)}@${basename3(marketplaceDir)}`;
42438
42168
  const record2 = JSON.parse(
42439
- await readFile2(join29(dirname7(cacheDir), "installed_plugins.json"), "utf8")
42169
+ await readFile2(join22(dirname5(cacheDir), "installed_plugins.json"), "utf8")
42440
42170
  );
42441
42171
  const plugins = record2?.plugins;
42442
42172
  if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
@@ -42468,7 +42198,7 @@ async function exists(path) {
42468
42198
  }
42469
42199
 
42470
42200
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
42471
- import { readFileSync as readFileSync18 } from "fs";
42201
+ import { readFileSync as readFileSync14 } from "fs";
42472
42202
  var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
42473
42203
  function createPluginBlock(build, policyStore) {
42474
42204
  return async () => {
@@ -42498,7 +42228,7 @@ async function readInstalledVersionBounded(installRoot) {
42498
42228
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42499
42229
  import { randomUUID as randomUUID17 } from "crypto";
42500
42230
  import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
42501
- import { join as join30 } from "path";
42231
+ import { join as join23 } from "path";
42502
42232
 
42503
42233
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
42504
42234
  import { rename as rename2 } from "fs/promises";
@@ -42527,7 +42257,7 @@ async function publishByRename(tmp, file2, move = rename2) {
42527
42257
 
42528
42258
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
42529
42259
  function createPolicyStore(dir = dataDir()) {
42530
- const file2 = join30(dir, "policy-cache.json");
42260
+ const file2 = join23(dir, "policy-cache.json");
42531
42261
  async function read() {
42532
42262
  try {
42533
42263
  const raw = await readFile3(file2, "utf8");
@@ -42597,8 +42327,8 @@ function createPolicyStore(dir = dataDir()) {
42597
42327
  }
42598
42328
 
42599
42329
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
42600
- import { readFileSync as readFileSync19 } from "fs";
42601
- import { join as join31 } from "path";
42330
+ import { readFileSync as readFileSync15 } from "fs";
42331
+ import { join as join24 } from "path";
42602
42332
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
42603
42333
  var OUTCOME_KEYS = {
42604
42334
  ok: true,
@@ -42612,7 +42342,7 @@ var OUTCOME_KEYS = {
42612
42342
  };
42613
42343
  var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
42614
42344
  function postureReportStatePath(dataDir2) {
42615
- return join31(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42345
+ return join24(dataDir2, POSTURE_REPORT_STATE_FILENAME);
42616
42346
  }
42617
42347
  function writePostureReportState(dataDir2, state) {
42618
42348
  try {
@@ -42653,10 +42383,19 @@ function createPostureReporter(deps) {
42653
42383
  hostname: deps.hostname(),
42654
42384
  capturedAt: nowMs,
42655
42385
  ...measurement,
42656
- // Omit the key rather than spread an explicit `undefined` —
42657
- // exactOptionalPropertyTypes distinguishes the two, and the bridge in
42658
- // factory.ts keys on presence.
42659
- ...plugin === void 0 ? {} : { plugin }
42386
+ // Omit the key rather than spread an explicit `undefined`. The type
42387
+ // admits `undefined` here (the schema's optional member), and
42388
+ // JSON.stringify sends the same bytes either way. Omitting keeps the
42389
+ // in-memory object free of an explicit `undefined` member, which the
42390
+ // tests pin by key presence.
42391
+ ...plugin === void 0 ? {} : { plugin },
42392
+ // LAST, and only for a scoped attachment. A machine attachment omits
42393
+ // the key the same way, so its body is byte for byte the one it sent
42394
+ // before the member existed. Anything but exactly `machine` reports the
42395
+ // constant `scoped`, never the raw value: that is resolveScope's own
42396
+ // fail direction, and a value outside the wire's vocabulary would fail
42397
+ // the whole snapshot at the receiver, the wipe signal with it.
42398
+ ...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
42660
42399
  };
42661
42400
  } catch {
42662
42401
  return null;
@@ -42679,8 +42418,8 @@ function createPostureReporter(deps) {
42679
42418
  }
42680
42419
 
42681
42420
  // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
42682
- import { statSync as statSync9 } from "fs";
42683
- import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
42421
+ import { statSync as statSync7 } from "fs";
42422
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42684
42423
 
42685
42424
  // ../../packages/plugin-runtime/src/attached/action-counts.ts
42686
42425
  function emptyActionCounts() {
@@ -42710,7 +42449,7 @@ function emptyReadout(readError = false) {
42710
42449
  }
42711
42450
  function readStorePosture(dbPath2) {
42712
42451
  try {
42713
- statSync9(dbPath2);
42452
+ statSync7(dbPath2);
42714
42453
  } catch (err) {
42715
42454
  const code = err.code;
42716
42455
  if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
@@ -42738,7 +42477,7 @@ function readStorePosture(dbPath2) {
42738
42477
  readError: false
42739
42478
  });
42740
42479
  try {
42741
- db = new DatabaseSync4(dbPath2, { readOnly: true });
42480
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
42742
42481
  db.exec("PRAGMA busy_timeout = 2000");
42743
42482
  version2 = db.prepare("PRAGMA user_version").get().user_version;
42744
42483
  try {
@@ -42792,11 +42531,11 @@ function readStorePosture(dbPath2) {
42792
42531
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
42793
42532
  import { randomUUID as randomUUID18 } from "crypto";
42794
42533
  import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
42795
- import { join as join32 } from "path";
42534
+ import { join as join25 } from "path";
42796
42535
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
42797
42536
  function createPostureStore(dir = settingsDir(), legacyDir) {
42798
- const file2 = join32(dir, "posture-state.json");
42799
- const legacyFile = legacyDir === void 0 ? null : join32(legacyDir, "posture-state.json");
42537
+ const file2 = join25(dir, "posture-state.json");
42538
+ const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
42800
42539
  async function persist(state) {
42801
42540
  await ensureDataDir(dir);
42802
42541
  const tmp = `${file2}.${randomUUID18()}.tmp`;
@@ -42864,8 +42603,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
42864
42603
  }
42865
42604
 
42866
42605
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
42867
- import { readFileSync as readFileSync20 } from "fs";
42868
- import { join as join33 } from "path";
42606
+ import { readFileSync as readFileSync16 } from "fs";
42607
+ import { join as join26 } from "path";
42869
42608
 
42870
42609
  // ../../packages/plugin-runtime/src/attached/status.ts
42871
42610
  var REFUSAL_LINES = {
@@ -42895,7 +42634,7 @@ import { fileURLToPath as fileURLToPath4 } from "url";
42895
42634
  var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
42896
42635
 
42897
42636
  // ../../packages/plugin-runtime/src/attached/factory.ts
42898
- import { hostname as hostname6 } from "os";
42637
+ import { hostname as hostname5 } from "os";
42899
42638
 
42900
42639
  // ../../packages/plugin-runtime/src/recorder.ts
42901
42640
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -42908,7 +42647,7 @@ var StandaloneDataGateway = class {
42908
42647
  // One notice per gateway — see warnRulesetDiscarded.
42909
42648
  warnedRulesetDiscarded = false;
42910
42649
  constructor(dataDir2, detections = [], meta4) {
42911
- this.db = openLocalDatabase(dataDir2);
42650
+ this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
42912
42651
  this.dataDir = dataDir2;
42913
42652
  this.db.installedPacks.recordInventory(detections, meta4);
42914
42653
  }
@@ -43257,6 +42996,9 @@ var StandaloneDataGateway = class {
43257
42996
  scanLedgerPaths() {
43258
42997
  return Promise.resolve(this.db.scanLedger.allPaths());
43259
42998
  }
42999
+ scanLedgerPathKeys() {
43000
+ return Promise.resolve(this.db.scanLedger.pathKeys());
43001
+ }
43260
43002
  recordScanned(entries) {
43261
43003
  this.db.scanLedger.upsertEntries(entries);
43262
43004
  return Promise.resolve();
@@ -43342,13 +43084,17 @@ function resolveGatewayForConfig(config2, meta4) {
43342
43084
  },
43343
43085
  store: postureStore,
43344
43086
  readStore: () => readStorePosture(config2.dbPath),
43345
- hostname: () => hostname6(),
43087
+ hostname: () => hostname5(),
43346
43088
  now: () => Date.now(),
43089
+ // The mode THIS gateway enforces, from the attachment resolved above,
43090
+ // so the report cannot name a mode the forward paths are not using.
43091
+ attachmentMode: attachment.mode,
43347
43092
  // The reporting build's identity, when the caller knows it (the plugin
43348
43093
  // adapters do; an embedder or a test may not). Composed with the SAME
43349
43094
  // policy store the sync child writes, so the block names the bundle
43350
- // actually in force. Key omitted rather than set undefined — the
43351
- // reporter keys on presence.
43095
+ // actually in force. The dependency key is omitted when no build is
43096
+ // known, and the reporter's optional call (`deps.pluginBlock?.()`)
43097
+ // then adds no block.
43352
43098
  ...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
43353
43099
  })
43354
43100
  });
@@ -43368,6 +43114,16 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
43368
43114
  import { randomUUID as randomUUID19 } from "crypto";
43369
43115
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
43370
43116
 
43117
+ // src/hooks/large-input.ts
43118
+ function largeInputBound(deadlineAt, now = () => performance.now()) {
43119
+ return {
43120
+ thresholdChars: LARGE_INPUT_THRESHOLD_CHARS,
43121
+ budgetMs: LARGE_INPUT_SCAN_BUDGET_MS,
43122
+ startBudgetMs: LARGE_INPUT_START_BUDGET_MS,
43123
+ remainingMs: () => deadlineAt - now()
43124
+ };
43125
+ }
43126
+
43371
43127
  // src/present.ts
43372
43128
  var SHADE = {
43373
43129
  light: "\u2591",
@@ -43405,16 +43161,26 @@ function withheldBanner(input2) {
43405
43161
  const header = `${SHADE.full}${SHADE.dark}${SHADE.medium}${SHADE.light} AKA ${SHADE.light}${SHADE.medium}${SHADE.dark}${SHADE.full}`;
43406
43162
  const subject = input2.action === "withheld" ? "The flagged value" : "Redacted spans";
43407
43163
  const approve = input2.blockedRef ? `Allow this exact value (${input2.blockedRef.maskedValue}) intentionally: aka exception approve ${input2.blockedRef.reference}` : "Allow intentionally: aka exception approve";
43164
+ const flagged = Boolean(input2.withheldRuleIds) || Boolean(input2.redactedRuleIds);
43408
43165
  return [
43409
43166
  `${header} ${input2.toolName} output ${input2.action}`,
43410
43167
  ...input2.withheldRuleIds ? [`${SHADE.full} Withheld: ${input2.withheldRuleIds}`] : [],
43411
43168
  ...input2.redactedRuleIds ? [`${SHADE.full} Redacted: ${input2.redactedRuleIds}`] : [],
43169
+ ...input2.tooLargeFields ? [
43170
+ `${SHADE.full} Too large to scan in time: ${input2.tooLargeFields} \u2014 withheld, never reached the model.`
43171
+ ] : [],
43412
43172
  ...input2.warnedRuleIds ? [`${SHADE.full} Also flagged (warn): ${input2.warnedRuleIds}`] : [],
43413
- `${SHADE.full} ${subject} never reached the model.`,
43414
- `${SHADE.full} ${approve}`,
43415
- `${SHADE.full} More: aka exception --help`
43173
+ ...flagged ? [
43174
+ `${SHADE.full} ${subject} never reached the model.`,
43175
+ `${SHADE.full} ${approve}`,
43176
+ `${SHADE.full} More: aka exception --help`
43177
+ ] : []
43416
43178
  ].join("\n");
43417
43179
  }
43180
+ function tooLargeToolText(toolName, field) {
43181
+ const part = field !== void 0 && field !== "" ? field : "output";
43182
+ return `[AKA SECURITY] ${toolName} ${part} withheld \u2014 too large to scan within the time limit. The content was not added to your context. This notice is a placeholder, not the real content: the underlying file or command output is unchanged, so never write this notice back to a file or treat it as data. Tell the user AKA withheld this output because it was too large to scan. If the task needs it, read it in smaller parts (for example a narrower range of lines).`;
43183
+ }
43418
43184
  function withheldToolText(toolName, ruleIds, field) {
43419
43185
  const part = field !== void 0 && field !== "" ? field : "output";
43420
43186
  return `[AKA SECURITY] ${toolName} ${part} withheld \u2014 flagged ${ruleIds}. The flagged content was not added to your context. This notice is a placeholder, not the real content: the underlying file or command output is unchanged, so never write this notice back to a file or treat it as data. Do not attempt to obtain the withheld content through other channels. Tell the user AKA withheld this output and why. If the user asks again \u2014 for example after granting an AKA exception \u2014 re-run this same tool call if it is safe to repeat: AKA re-evaluates every capture and passes values the user has excepted.`;
@@ -43430,7 +43196,8 @@ async function scanResponseFields(toolName, fields, capture, deadline) {
43430
43196
  blockedReferences: [],
43431
43197
  redactedReferences: [],
43432
43198
  toolName,
43433
- unscannedFields: 0
43199
+ unscannedFields: 0,
43200
+ tooLargeFields: []
43434
43201
  };
43435
43202
  for (const [index, field] of fields.entries()) {
43436
43203
  if (deadline !== void 0 && deadline.now() >= deadline.at) {
@@ -43438,6 +43205,11 @@ async function scanResponseFields(toolName, fields, capture, deadline) {
43438
43205
  break;
43439
43206
  }
43440
43207
  const result = await capture(field.text);
43208
+ if (result.scanIncomplete !== void 0) {
43209
+ const name = field.path.join(".");
43210
+ if (!outcome.tooLargeFields.includes(name)) outcome.tooLargeFields.push(name);
43211
+ continue;
43212
+ }
43441
43213
  if (result.findings.length === 0) continue;
43442
43214
  if (result.action === "block") {
43443
43215
  outcome.withheldFindings.push(...result.findings);
@@ -43452,21 +43224,30 @@ async function scanResponseFields(toolName, fields, capture, deadline) {
43452
43224
  return outcome;
43453
43225
  }
43454
43226
  function responseEmitPayload(outcome) {
43455
- const { toolName, withheldFindings, redactedButWithheldFindings, warnedFindings } = outcome;
43227
+ const {
43228
+ toolName,
43229
+ withheldFindings,
43230
+ redactedButWithheldFindings,
43231
+ warnedFindings,
43232
+ tooLargeFields
43233
+ } = outcome;
43456
43234
  const allWithheld = [...withheldFindings, ...redactedButWithheldFindings];
43457
- if (allWithheld.length > 0) {
43235
+ if (allWithheld.length > 0 || tooLargeFields.length > 0) {
43458
43236
  const withheldRuleIds = withheldFindings.length > 0 ? uniqueRuleIds(withheldFindings) : void 0;
43459
43237
  const redactedRuleIds = redactedButWithheldFindings.length > 0 ? uniqueRuleIds(redactedButWithheldFindings) : void 0;
43460
43238
  const ref = outcome.blockedReferences[0] ?? outcome.redactedReferences[0];
43461
43239
  return {
43462
43240
  decision: "block",
43463
- reason: withheldToolText(toolName, uniqueRuleIds(allWithheld)),
43241
+ // The whole result goes either way; a flagged rule is the more specific
43242
+ // reason when there is one.
43243
+ reason: allWithheld.length > 0 ? withheldToolText(toolName, uniqueRuleIds(allWithheld)) : tooLargeToolText(toolName),
43464
43244
  systemMessage: withheldBanner({
43465
43245
  toolName,
43466
43246
  action: "withheld",
43467
43247
  withheldRuleIds,
43468
43248
  redactedRuleIds,
43469
43249
  warnedRuleIds: warnedFindings.length > 0 ? uniqueRuleIds(warnedFindings) : void 0,
43250
+ tooLargeFields: tooLargeFields.length > 0 ? tooLargeFields.join(", ") : void 0,
43470
43251
  blockedRef: ref
43471
43252
  })
43472
43253
  };
@@ -43480,7 +43261,7 @@ function responseEmitPayload(outcome) {
43480
43261
  }
43481
43262
 
43482
43263
  // src/hooks/shared.ts
43483
- import { isAbsolute as isAbsolute3, normalize as normalize2, resolve as resolvePath } from "path";
43264
+ import { isAbsolute as isAbsolute2, normalize, resolve as resolvePath } from "path";
43484
43265
  async function readStdin() {
43485
43266
  return new Promise((resolve3) => {
43486
43267
  let data = "";
@@ -43540,9 +43321,9 @@ function captureScopeKey(input2, filePath) {
43540
43321
  if (filePath === void 0 || filePath === "") {
43541
43322
  return resolveRepoAttribution(getString(input2, "cwd") ?? process.cwd()).scopeKey;
43542
43323
  }
43543
- if (isAbsolute3(filePath)) return resolveRepoAttribution(normalize2(filePath)).scopeKey;
43324
+ if (isAbsolute2(filePath)) return resolveRepoAttribution(normalize(filePath)).scopeKey;
43544
43325
  const cwd = getString(input2, "cwd") ?? process.cwd();
43545
- if (!isAbsolute3(cwd)) return void 0;
43326
+ if (!isAbsolute2(cwd)) return void 0;
43546
43327
  return resolveRepoAttribution(resolvePath(cwd, filePath)).scopeKey;
43547
43328
  } catch {
43548
43329
  return void 0;
@@ -43556,16 +43337,16 @@ function countFailOpen(base) {
43556
43337
  }
43557
43338
 
43558
43339
  // src/hooks/store-health.ts
43559
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync21, writeFileSync as writeFileSync8 } from "fs";
43560
- import { dirname as dirname8, join as join34 } from "path";
43340
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync17, writeFileSync as writeFileSync5 } from "fs";
43341
+ import { dirname as dirname6, join as join27 } from "path";
43561
43342
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
43562
43343
  function markerDirs(dataDir2) {
43563
- return [dataDir2, dirname8(dataDir2)];
43344
+ return [dataDir2, dirname6(dataDir2)];
43564
43345
  }
43565
43346
  function alreadyClaimed(dirs, marker, sessionId) {
43566
43347
  return dirs.some((dir) => {
43567
43348
  try {
43568
- return readFileSync21(join34(dir, marker), "utf8") === sessionId;
43349
+ return readFileSync17(join27(dir, marker), "utf8") === sessionId;
43569
43350
  } catch {
43570
43351
  return false;
43571
43352
  }
@@ -43574,14 +43355,14 @@ function alreadyClaimed(dirs, marker, sessionId) {
43574
43355
  function recordClaim(dirs, marker, sessionId) {
43575
43356
  for (const dir of dirs) {
43576
43357
  try {
43577
- mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
43578
- writeFileSync8(join34(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43358
+ mkdirSync2(dir, { recursive: true, mode: DATA_DIR_MODE });
43359
+ writeFileSync5(join27(dir, marker), sessionId, { mode: DATA_FILE_MODE });
43579
43360
  return;
43580
43361
  } catch {
43581
43362
  }
43582
43363
  }
43583
43364
  }
43584
- function storeRedirectedMessage(paths, platform2 = process.platform) {
43365
+ function storeRedirectedMessage(paths, platform = process.platform) {
43585
43366
  const where = paths.map(({ path, target, holds, missing, mode }) => {
43586
43367
  if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
43587
43368
  const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
@@ -43591,7 +43372,7 @@ function storeRedirectedMessage(paths, platform2 = process.platform) {
43591
43372
  const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
43592
43373
  const anyResolves = paths.some(({ missing }) => !missing);
43593
43374
  const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
43594
- const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
43375
+ const kept = anyResolves && platform !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
43595
43376
  return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
43596
43377
  `;
43597
43378
  }
@@ -43600,7 +43381,7 @@ function formatMode(mode) {
43600
43381
  }
43601
43382
  function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
43602
43383
  try {
43603
- const paths = symlinkedStorePaths(dirname8(config2.dataDir));
43384
+ const paths = symlinkedStorePaths(dirname6(config2.dataDir));
43604
43385
  if (paths.length === 0) return;
43605
43386
  if (!sessionId) {
43606
43387
  write(storeRedirectedMessage(paths));
@@ -43740,7 +43521,10 @@ async function main() {
43740
43521
  const config2 = loadConfig();
43741
43522
  warnIfStoreRedirected(config2, getString(input2, "session_id"));
43742
43523
  const gateway = resolveDataGateway(config2);
43743
- const runtime = createPluginRuntime(gateway, config2.settings, { dataDir: config2.dataDir });
43524
+ const runtime = createPluginRuntime(gateway, config2.settings, {
43525
+ dataDir: config2.dataDir,
43526
+ largeInput: largeInputBound(RESPONSE_SCAN_DEADLINE_MS)
43527
+ });
43744
43528
  let outcome;
43745
43529
  try {
43746
43530
  outcome = await scanResponseFields(