@akasecurity/ai-tc-claude-code 0.9.12 → 0.9.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/query.js CHANGED
@@ -20572,7 +20572,17 @@ var UNPRICEABLE_PROVIDERS = Object.freeze([
20572
20572
  "gateway",
20573
20573
  "unknown",
20574
20574
  "cli",
20575
- "api"
20575
+ "api",
20576
+ // The browser extension's native host records these as `llm_call.provider`
20577
+ // for a web-chat turn — the web tool id, deliberately never the vendor id
20578
+ // (`openai`/`anthropic`) the session root carries. Subscription traffic
20579
+ // burns rate-limit budget, not dollar credits, and listing them here is
20580
+ // what keeps that true structurally: a later maintainer who wants to price
20581
+ // web-chat traffic at API rates has to delete this entry first, and meet
20582
+ // the reason on the way, rather than quietly adding one to
20583
+ // PROVIDER_PLATFORM.
20584
+ "chatgpt",
20585
+ "claude-ai"
20576
20586
  ]);
20577
20587
  function platformForProvider(provider) {
20578
20588
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
@@ -20775,7 +20785,12 @@ var HARNESS = {
20775
20785
  ClaudeDesktop: "claudedesktop",
20776
20786
  ChatGpt: "chatgpt",
20777
20787
  ClaudeAi: "claudeai",
20778
- Api: "api"
20788
+ Api: "api",
20789
+ // Not a coding assistant a person drives — an in-process SDK embedded in an
20790
+ // application, so it has no IDE/CLI/desktop/web surface of its own. Carries
20791
+ // the same id as its SOURCE_TOOL counterpart, unlike every capture-side tool
20792
+ // whose wire spelling differs from its display spelling.
20793
+ AiTcSdk: "ai-tc-sdk"
20779
20794
  };
20780
20795
  var Harness = external_exports.enum(HARNESS).meta({ id: "Harness" });
20781
20796
  var SOURCE_TOOL = {
@@ -20791,9 +20806,15 @@ var SOURCE_TOOL = {
20791
20806
  // whose tool could not be identified both render through the read side's
20792
20807
  // miss path rather than as a harness of their own.
20793
20808
  Cli: "cli",
20794
- Unknown: "unknown"
20809
+ Unknown: "unknown",
20810
+ // The wire id an in-process, request-path SDK stamps on its own structural
20811
+ // rows (`request_decision`) — never a capture of prompt/response/tool text,
20812
+ // since the SDK sits in front of a model call rather than inside a coding
20813
+ // assistant's own hook contract.
20814
+ AiTcSdk: "ai-tc-sdk"
20795
20815
  };
20796
20816
  var SourceTool = external_exports.enum(SOURCE_TOOL).meta({ id: "SourceTool" });
20817
+ var WebSourceTool = SourceTool.extract(["ChatGpt", "ClaudeAi"]);
20797
20818
  var TOOL_TO_HARNESS = {
20798
20819
  [SOURCE_TOOL.ClaudeCode]: HARNESS.ClaudeCode,
20799
20820
  [SOURCE_TOOL.ClaudeDesktop]: HARNESS.ClaudeDesktop,
@@ -20802,7 +20823,12 @@ var TOOL_TO_HARNESS = {
20802
20823
  [SOURCE_TOOL.ChatGpt]: HARNESS.ChatGpt,
20803
20824
  [SOURCE_TOOL.Codex]: HARNESS.Codex,
20804
20825
  [SOURCE_TOOL.Antigravity]: HARNESS.Antigravity,
20805
- [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20826
+ [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi,
20827
+ // Wire and display id are the same string here, but the row still belongs:
20828
+ // both vocabularies carry the `AiTcSdk` member, and the join is exactly
20829
+ // their intersection — leaving a shared member out would read as an
20830
+ // uninstrumented tool on both surfaces, which this one is not.
20831
+ [SOURCE_TOOL.AiTcSdk]: HARNESS.AiTcSdk
20806
20832
  };
20807
20833
 
20808
20834
  // ../../packages/schema/src/zod/finding.ts
@@ -20836,7 +20862,8 @@ var FindingProvider = Harness.extract([
20836
20862
  "ClaudeAi",
20837
20863
  "Codex",
20838
20864
  "Antigravity",
20839
- "Api"
20865
+ "Api",
20866
+ "AiTcSdk"
20840
20867
  ]).meta({ id: "FindingProvider" });
20841
20868
  var FindingCategory = external_exports.enum([
20842
20869
  "secret",
@@ -21213,18 +21240,41 @@ var AuditEventType = external_exports.enum([
21213
21240
  // 'tool_call' is the reconciler's structural row for every call, while
21214
21241
  // 'tool_use' exists only where a hook enforced against the arguments.
21215
21242
  "tool_use",
21216
- // One row per model REFUSAL: a switch onto a prohibited model that was
21217
- // denied, or a turn refused because the session was already running on one.
21218
- // A structural row like the ones above rather than a capture — it carries
21219
- // the model that was refused and nothing the user typed, because what is
21220
- // worth recording about a governance decision is the decision, and prompt
21221
- // text is the thing this product exists to keep from travelling.
21243
+ // One row per model REFUSAL, across all four seams a prohibited model can be
21244
+ // stopped at: a switch onto it, a turn already running on it, a subagent
21245
+ // spawn asking for it, or a request-path refusal an embedded request-path
21246
+ // SDK makes in-process before the call leaves the application. Which seam
21247
+ // rides `attributes.refusal_seam`, never this member name. A structural row
21248
+ // like the ones above rather than a capture — it carries the model that was
21249
+ // refused and nothing the user typed, because what is worth recording about
21250
+ // a governance decision is the decision, and prompt text is the thing this
21251
+ // product exists to keep from travelling.
21222
21252
  "model_refusal",
21253
+ // One row per request-path DECISION: a policy check an embedded request-path
21254
+ // SDK performs in-process before a model call leaves the application, or
21255
+ // against that call's non-streamed response. A structural row like
21256
+ // 'model_refusal' rather than a capture — content-free in the same way:
21257
+ // which side, which seam, what action and which field are decided rides
21258
+ // `attributes`, never this member name, and the matched text itself never
21259
+ // travels.
21260
+ //
21261
+ // A prohibited-model refusal on the request path is deliberately NOT this
21262
+ // member: it stays 'model_refusal' with `refusal_seam: 'request'`, so it
21263
+ // shares one bucket with the plugin's switch/turn/spawn refusals rather
21264
+ // than splitting one governance concept across two event types. This
21265
+ // member carries every OTHER request-path decision.
21266
+ "request_decision",
21223
21267
  // One row per config-inventory scan, hung off the session root. It is the
21224
21268
  // fact the posture inspection findings reference (findings require an
21225
21269
  // audit_event_id), and its started_at is the "scanned Nm ago" the read
21226
21270
  // surface renders.
21227
- "config_scan"
21271
+ "config_scan",
21272
+ // One row per reported browser-extension capture status, hung off the web
21273
+ // session root. The durable home of what one tab's network interception
21274
+ // is doing — a write-through of the native host's in-memory tracker, so a
21275
+ // second process (aka extension status) and a restarted host both have
21276
+ // somewhere to read it back from.
21277
+ "capture_status"
21228
21278
  ]).meta({ id: "AuditEventType" });
21229
21279
  var AttributeBag = external_exports.record(external_exports.string(), external_exports.unknown());
21230
21280
  var HostAttributes = external_exports.object({
@@ -21384,6 +21434,20 @@ var CaptureAttributes = external_exports.object({
21384
21434
  // repeated rather than referenced because a store reader opens this file.
21385
21435
  redact_degraded_to: ActionTaken.optional()
21386
21436
  }).catchall(external_exports.unknown());
21437
+ var CaptureStatusAttributes = external_exports.object({
21438
+ source_tool: external_exports.string().optional(),
21439
+ patched: external_exports.boolean().optional(),
21440
+ live: external_exports.boolean().optional(),
21441
+ blind: external_exports.boolean().optional(),
21442
+ sends_seen_dom: external_exports.number().int().nonnegative().optional(),
21443
+ exchanges_seen_net: external_exports.number().int().nonnegative().optional(),
21444
+ parse_failures: external_exports.number().int().nonnegative().optional(),
21445
+ unparsed_bodies: external_exports.number().int().nonnegative().optional(),
21446
+ shape_misses: external_exports.array(external_exports.string()).optional(),
21447
+ conversation_endpoints: external_exports.number().int().nonnegative().optional(),
21448
+ closed: external_exports.boolean().optional(),
21449
+ enforcement: external_exports.string().optional()
21450
+ }).catchall(external_exports.unknown());
21387
21451
  var ToolCallInspection = external_exports.object({
21388
21452
  ruleId: external_exports.string().min(1),
21389
21453
  ruleName: external_exports.string(),
@@ -22243,6 +22307,30 @@ var AttachedCredential = external_exports.object({
22243
22307
  keyPrefix: external_exports.string().min(1).max(16).optional(),
22244
22308
  mintedAt: external_exports.iso.datetime().optional()
22245
22309
  });
22310
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
22311
+ function unsafeEndpointReason(endpoint) {
22312
+ let parsed2;
22313
+ try {
22314
+ parsed2 = new URL(endpoint);
22315
+ } catch {
22316
+ return "unparseable";
22317
+ }
22318
+ if (parsed2.username !== "" || parsed2.password !== "") return "userinfo";
22319
+ if (parsed2.search !== "" || parsed2.hash !== "") return "query-or-fragment";
22320
+ if (parsed2.protocol === "https:") return null;
22321
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname) ? null : "insecure";
22322
+ }
22323
+ function isSafeEndpoint(endpoint) {
22324
+ return unsafeEndpointReason(endpoint) === null;
22325
+ }
22326
+ function originOnly(endpoint) {
22327
+ try {
22328
+ const parsed2 = new URL(endpoint);
22329
+ return `${parsed2.protocol}//${parsed2.host}`;
22330
+ } catch {
22331
+ return "(unparseable endpoint)";
22332
+ }
22333
+ }
22246
22334
  var MAX_DATE_MS = 253402300799999;
22247
22335
  var MAX_INT4 = 2147483647;
22248
22336
  var StorePosturePack = external_exports.object({
@@ -22397,6 +22485,11 @@ var RemoteFailureKind = external_exports.enum([
22397
22485
  "rejected",
22398
22486
  "unreachable"
22399
22487
  ]);
22488
+ var ControlPlaneFailure = RemoteFailureKind.extract([
22489
+ "unauthorized",
22490
+ "forbidden",
22491
+ "unreachable"
22492
+ ]);
22400
22493
  var AttachDeviceRequest = external_exports.object({
22401
22494
  // This machine's own continuity id, so re-attaching ROTATES the credential
22402
22495
  // on one machine record instead of producing a second one. Client-minted
@@ -22936,7 +23029,12 @@ var EventMetadata = external_exports.object({
22936
23029
  // in — set by the browser extension's network capture so a stored `response`
22937
23030
  // row can be joined to the `llm_call` leaf describing the same turn. Absent
22938
23031
  // on every other capture path, which has no such id.
22939
- messageId: external_exports.string().optional(),
23032
+ //
23033
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
23034
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
23035
+ // places an event is PARSED; the local write path types the event and parses
23036
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
23037
+ messageId: external_exports.string().min(1).optional(),
22940
23038
  conversationId: external_exports.string().optional(),
22941
23039
  // How long THIS capture's inspection blocked its caller, in whole
22942
23040
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
@@ -23778,6 +23876,85 @@ function policyIdIsReversible(policyId) {
23778
23876
  var DEFAULT_ACTIONS = Object.fromEntries(
23779
23877
  DetectionCategory.options.map((c) => [c, builtinPolicyToAction(severityFloorPolicy(c))])
23780
23878
  );
23879
+ function ruleCategoryMap(wireRules, localRules, compiledRules) {
23880
+ const map2 = /* @__PURE__ */ new Map();
23881
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
23882
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
23883
+ for (const rule of compiledRules) map2.set(rule.id, rule.category);
23884
+ return map2;
23885
+ }
23886
+ function policyKey(policy) {
23887
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
23888
+ }
23889
+ function floorFor(policy, categoryByRuleId) {
23890
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
23891
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
23892
+ }
23893
+ function strongerOf(a, b) {
23894
+ if (a === null) return b;
23895
+ if (b === null) return a;
23896
+ return strongerAction(a, b);
23897
+ }
23898
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
23899
+ const merged = /* @__PURE__ */ new Map();
23900
+ const disabled = [];
23901
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
23902
+ for (const policy of remotePolicies) {
23903
+ if (!policy.enabled) continue;
23904
+ if (!("category" in policy.target)) continue;
23905
+ if (remoteCategoryAction.has(policy.target.category)) continue;
23906
+ const floor = floorFor(policy, categoryByRuleId);
23907
+ remoteCategoryAction.set(
23908
+ policy.target.category,
23909
+ floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
23910
+ );
23911
+ }
23912
+ for (const policy of localPolicies) {
23913
+ if (!policy.enabled) {
23914
+ disabled.push(policy);
23915
+ continue;
23916
+ }
23917
+ const key = policyKey(policy);
23918
+ if (merged.has(key)) continue;
23919
+ let remoteFloor = null;
23920
+ if ("ruleId" in policy.target) {
23921
+ const category = categoryByRuleId.get(policy.target.ruleId);
23922
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
23923
+ }
23924
+ merged.set(
23925
+ key,
23926
+ remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
23927
+ );
23928
+ }
23929
+ const localCategoryAction = /* @__PURE__ */ new Map();
23930
+ for (const policy of merged.values()) {
23931
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
23932
+ }
23933
+ for (const policy of remotePolicies) {
23934
+ if (!policy.enabled) {
23935
+ disabled.push(policy);
23936
+ continue;
23937
+ }
23938
+ const key = policyKey(policy);
23939
+ const floor = floorFor(policy, categoryByRuleId);
23940
+ let localFloor = null;
23941
+ if ("ruleId" in policy.target) {
23942
+ const category = categoryByRuleId.get(policy.target.ruleId);
23943
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
23944
+ }
23945
+ const effectiveFloor = strongerOf(floor, localFloor);
23946
+ const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
23947
+ const existing = merged.get(key);
23948
+ if (existing === void 0) {
23949
+ merged.set(key, clamped);
23950
+ continue;
23951
+ }
23952
+ if (actionRank(clamped.action) > actionRank(existing.action)) {
23953
+ merged.set(key, clamped);
23954
+ }
23955
+ }
23956
+ return [...merged.values(), ...disabled];
23957
+ }
23781
23958
  var BUILTIN_POLICIES = Object.fromEntries(
23782
23959
  KNOWN_BUILTIN_IDS.map((id) => [id, { id, ...BUILTIN_POLICY_SPECS[id] }])
23783
23960
  );
@@ -24005,6 +24182,22 @@ var HistorySyncConsent = external_exports.object({
24005
24182
  payloadVersion: external_exports.number().int().positive(),
24006
24183
  endpoint: external_exports.string()
24007
24184
  });
24185
+ var WEB_CHAT_CAPTURE_CONSENT_VERSION = 1;
24186
+ var WebChatCaptureConsent = external_exports.object({
24187
+ acknowledgedAt: external_exports.iso.datetime(),
24188
+ version: external_exports.number().int().positive()
24189
+ });
24190
+ var WebChatResponseCapture = external_exports.enum(["with-findings", "always", "never"]);
24191
+ var WebChatCapture = external_exports.object({
24192
+ responses: WebChatResponseCapture.default("with-findings"),
24193
+ account: external_exports.boolean().default(false),
24194
+ // Absent until granted. Presence alone does not authorize anything — see
24195
+ // isWebChatCaptureConsentValid.
24196
+ consent: WebChatCaptureConsent.optional()
24197
+ });
24198
+ function isWebChatCaptureConsentValid(consent) {
24199
+ return consent?.version === WEB_CHAT_CAPTURE_CONSENT_VERSION;
24200
+ }
24008
24201
  var BODY_RETENTION_DEFAULT_DAYS = 30;
24009
24202
  var BodyRetention = external_exports.object({
24010
24203
  enabled: external_exports.boolean().default(false),
@@ -24063,6 +24256,16 @@ var WorkspaceSettings = external_exports.object({
24063
24256
  // both widenings. Absent until granted, and a grant for a different endpoint
24064
24257
  // or an older payload no longer counts.
24065
24258
  historySyncConsent: HistorySyncConsent.optional(),
24259
+ // What the browser extension may record from a web chat, and the grant that
24260
+ // authorizes it. Absent until the user answers: recording something that was
24261
+ // never recorded before is never an assumed grant on upgrade, so the whole
24262
+ // block is optional rather than defaulted in. What an absent block means is
24263
+ // webChatCaptureOf's answer, in one place.
24264
+ //
24265
+ // Enforcement is NOT gated on this. A machine that has never answered still
24266
+ // blocks, redacts and warns on what a user sends; the grant covers what is
24267
+ // written down.
24268
+ webChatCapture: WebChatCapture.optional(),
24066
24269
  // Local body expiry (see BodyRetention). Off until switched on; expiring a
24067
24270
  // body never removes the row or its findings.
24068
24271
  bodyRetention: BodyRetention.default({
@@ -24073,6 +24276,9 @@ var WorkspaceSettings = external_exports.object({
24073
24276
  function defaultWorkspaceSettings() {
24074
24277
  return WorkspaceSettings.parse({});
24075
24278
  }
24279
+ function webChatCaptureOf(settings) {
24280
+ return settings.webChatCapture ?? WebChatCapture.parse({});
24281
+ }
24076
24282
  function isAttached(settings) {
24077
24283
  return settings.runMode === "attached" && settings.controlPlane !== void 0;
24078
24284
  }
@@ -24170,7 +24376,10 @@ function toCaptureAttributes(event) {
24170
24376
  // `.catchall(z.unknown())` carries the long tail.
24171
24377
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
24172
24378
  ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24173
- ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24379
+ // A blank id is omitted rather than stored: it is a join key and `''` joins
24380
+ // nothing. This runs on the local write path, which types the event but
24381
+ // never parses it, so EventMetadata's own `.min(1)` does not reach here.
24382
+ ...metadata?.messageId !== void 0 && metadata.messageId !== "" ? { message_id: metadata.messageId } : {},
24174
24383
  ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
24175
24384
  };
24176
24385
  }
@@ -24544,12 +24753,14 @@ var RecommendedActionIdParam = external_exports.object({ id: external_exports.st
24544
24753
  // ../../packages/schema/src/zod/settings-action.ts
24545
24754
  var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24546
24755
  var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
24756
+ var WebChatCaptureConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "WebChatCaptureConsentChoice" });
24547
24757
  var SaveSettingsInput = external_exports.object({
24548
24758
  historicalAccess: external_exports.string(),
24549
24759
  modelJudgeConsent: ModelJudgeConsentChoice,
24550
24760
  historySyncConsent: HistorySyncConsentChoice,
24551
24761
  vaultConsent: external_exports.string(),
24552
24762
  vaultInlineReveal: external_exports.string(),
24763
+ webChatCaptureConsent: WebChatCaptureConsentChoice,
24553
24764
  // Widened to `string` like its neighbours rather than typed as
24554
24765
  // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24555
24766
  // the call site, so the domain check receives the type it was written for.
@@ -24764,11 +24975,24 @@ var WebExchange = external_exports.object({
24764
24975
  turnIndex: external_exports.number().int().nonnegative().optional(),
24765
24976
  toolCalls: external_exports.array(WebToolCall).default([]),
24766
24977
  // Absent when the adapter recovered no text. Capped by the caller at
24767
- // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24768
- // short capture is never mistaken for a short reply.
24978
+ // RESPONSE_TEXT_MAX_BYTES, so a short capture is never mistaken for a short
24979
+ // reply.
24769
24980
  responseText: external_exports.string().optional(),
24981
+ // The stored text is short of the reply. It does NOT say which of the two
24982
+ // ceilings on this path cut it: the caller applies its own cap on the raw
24983
+ // bytes it reads off the wire, which can be reached by a stream whose
24984
+ // recovered text stays well under RESPONSE_TEXT_MAX_BYTES, and applies that
24985
+ // one to the text. A reader cannot tell them apart, and nothing downstream
24986
+ // should branch as though it could.
24770
24987
  truncated: external_exports.boolean().default(false)
24771
24988
  });
24989
+ var WebEnforcementState = external_exports.enum([
24990
+ "watching",
24991
+ "composer-only",
24992
+ "button-only",
24993
+ "unattached",
24994
+ "unknown"
24995
+ ]);
24772
24996
  var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24773
24997
  var WebCaptureStatus = external_exports.object({
24774
24998
  patched: external_exports.boolean(),
@@ -24780,8 +25004,66 @@ var WebCaptureStatus = external_exports.object({
24780
25004
  unparsedBodies: external_exports.number().int().nonnegative(),
24781
25005
  // The adapter-declared JSON key paths that were absent from a real payload —
24782
25006
  // the earliest signal that a site's contract moved.
24783
- shapeMisses: external_exports.array(external_exports.string()).default([])
24784
- });
25007
+ shapeMisses: external_exports.array(external_exports.string()).default([]),
25008
+ // How many `kind: 'conversation'` endpoints the reporting tab's adapter
25009
+ // compiled. Zero means this build declares none for the site, so observing
25010
+ // nothing is the design rather than a fault — the one fact that separates a
25011
+ // site nobody has surveyed yet from one whose contract moved. Defaulted so a
25012
+ // build predating the field is read as declaring nothing rather than refused.
25013
+ conversationEndpoints: external_exports.number().int().nonnegative().default(0),
25014
+ // The document that sent this report is going away. The bridge sets it on
25015
+ // its `pagehide` report and nowhere else.
25016
+ //
25017
+ // A property of the REPORT rather than of capture health, which is why
25018
+ // nothing in `deriveWebCaptureState` reads it and why it stays out of the
25019
+ // bridge's own report signature — a closing tab's last word must not be
25020
+ // suppressed for carrying the same health as the report before it. What
25021
+ // reads it is the per-site fold: a document that said it was unloading stops
25022
+ // voting on the site's state, so the reload the `blind` remediation asks for
25023
+ // can actually clear the verdict it was shown. A document that dies without
25024
+ // sending one is covered by CAPTURE_STATUS_DOCUMENT_QUIET_MS instead.
25025
+ //
25026
+ // Defaulted so a build predating the field reads as a document that never
25027
+ // said it was closing — which keeps it voting, the same as every report that
25028
+ // is not a final one.
25029
+ closed: external_exports.boolean().default(false),
25030
+ // What the DOM enforcement path is doing, which none of the counters above
25031
+ // can say: `sendsSeenDom` rises only once a send has COMPLETED, so a tab
25032
+ // whose watcher never bound reports zero exactly like a tab nobody typed in.
25033
+ // Defaulted to 'unknown' rather than 'watching' so a status from a build
25034
+ // predating the field is not read as reporting a healthy one.
25035
+ enforcement: WebEnforcementState.default("unknown")
25036
+ });
25037
+ function webCaptureStatusObservedTurnPath(status) {
25038
+ if (!status.patched) return true;
25039
+ if (status.conversationEndpoints === 0) return true;
25040
+ return status.blind || status.shapeMisses.length > 0 || status.parseFailures > 0 || status.unparsedBodies > 0 || status.exchangesSeenNet > 0;
25041
+ }
25042
+ function pickReportedCaptureStatus(candidates) {
25043
+ return candidates.find((c) => webCaptureStatusObservedTurnPath(c.status)) ?? candidates[0];
25044
+ }
25045
+ var CAPTURE_STATUS_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
25046
+ var CAPTURE_STATUS_RECENCY_DAYS = CAPTURE_STATUS_RECENCY_MS / (24 * 60 * 60 * 1e3);
25047
+ var CAPTURE_STATUS_DOCUMENT_QUIET_MS = 12 * 60 * 60 * 1e3;
25048
+ function fromCaptureStatusAttributes(bag) {
25049
+ const parsedBag = CaptureStatusAttributes.safeParse(bag);
25050
+ if (!parsedBag.success) return null;
25051
+ const b = parsedBag.data;
25052
+ const parsedStatus = WebCaptureStatus.safeParse({
25053
+ patched: b.patched,
25054
+ live: b.live,
25055
+ blind: b.blind,
25056
+ sendsSeenDom: b.sends_seen_dom,
25057
+ exchangesSeenNet: b.exchanges_seen_net,
25058
+ parseFailures: b.parse_failures,
25059
+ unparsedBodies: b.unparsed_bodies,
25060
+ shapeMisses: b.shape_misses,
25061
+ conversationEndpoints: b.conversation_endpoints,
25062
+ closed: b.closed,
25063
+ enforcement: b.enforcement
25064
+ });
25065
+ return parsedStatus.success ? parsedStatus.data : null;
25066
+ }
24785
25067
 
24786
25068
  // ../../packages/persistence/src/paths.ts
24787
25069
  import {
@@ -24892,17 +25174,6 @@ function publishByLink(tmp, file2, data) {
24892
25174
  function controlPlaneCredentialPath(settingsDir2) {
24893
25175
  return join2(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
24894
25176
  }
24895
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
24896
- function isSafeEndpoint(endpoint) {
24897
- let parsed2;
24898
- try {
24899
- parsed2 = new URL(endpoint);
24900
- } catch {
24901
- return false;
24902
- }
24903
- if (parsed2.protocol === "https:") return true;
24904
- return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
24905
- }
24906
25177
  function repairOrRefuseMode(file2) {
24907
25178
  const link = lstatSync2(file2, { throwIfNoEntry: false });
24908
25179
  if (link === void 0) return "absent";
@@ -26685,7 +26956,7 @@ var SESSION_ROOT = `event_type = 'session'`;
26685
26956
  var HAS_ACTIVITY = `EXISTS (
26686
26957
  SELECT 1 FROM audit_events c
26687
26958
  WHERE c.root_session_id = audit_events.id
26688
- AND c.event_type NOT IN ('hook', 'config_scan'))`;
26959
+ AND c.event_type NOT IN ('hook', 'config_scan', 'capture_status'))`;
26689
26960
  var SqliteActivityRepository = class {
26690
26961
  constructor(db, now = () => Date.now()) {
26691
26962
  this.db = db;
@@ -26712,10 +26983,10 @@ var SqliteActivityRepository = class {
26712
26983
  SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
26713
26984
  UNION
26714
26985
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
26715
- WHERE started_at >= ?
26986
+ WHERE started_at >= ? AND event_type <> 'capture_status'
26716
26987
  UNION
26717
26988
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
26718
- WHERE ended_at >= ?)`,
26989
+ WHERE ended_at >= ? AND event_type <> 'capture_status')`,
26719
26990
  [liveThreshold, liveThreshold, liveThreshold]
26720
26991
  );
26721
26992
  const toolCallsToday = countScalar(
@@ -27122,7 +27393,10 @@ var SqliteAuditEventsRepository = class {
27122
27393
  attributes = excluded.attributes,
27123
27394
  ended_at = excluded.ended_at
27124
27395
  WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
27125
- > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`
27396
+ > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)
27397
+ OR (json_extract(excluded.attributes, '$.usage_source') IS NOT NULL
27398
+ AND json_extract(excluded.attributes, '$.output_tokens') IS NULL
27399
+ AND excluded.attributes <> audit_events.attributes)`
27126
27400
  );
27127
27401
  this.upsertSessionRootStmt = db.prepare(
27128
27402
  `INSERT OR IGNORE INTO audit_events
@@ -27390,6 +27664,87 @@ var SqliteBodyRetentionRepository = class {
27390
27664
  }
27391
27665
  };
27392
27666
 
27667
+ // ../../packages/persistence/src/repositories/capture-status.ts
27668
+ var STATUS_LOOKBACK_ROWS = 128;
27669
+ var SqliteCaptureStatusRepository = class {
27670
+ constructor(db) {
27671
+ this.db = db;
27672
+ this.recentStmt = db.prepare(
27673
+ `SELECT a.started_at AS startedAt,
27674
+ a.attributes AS attributes,
27675
+ a.root_session_id AS rootSessionId
27676
+ FROM audit_events a
27677
+ WHERE a.event_type = 'capture_status'
27678
+ AND a.source_tool = ?
27679
+ AND a.started_at >= ?
27680
+ ORDER BY a.started_at DESC, a.id DESC
27681
+ LIMIT ?`
27682
+ );
27683
+ }
27684
+ db;
27685
+ recentStmt;
27686
+ /**
27687
+ * Every document that reported for a site, in registry order by site, from
27688
+ * the last `CAPTURE_STATUS_RECENCY_MS`.
27689
+ *
27690
+ * SEVERAL per site, not one: a browser is many documents and each reports
27691
+ * for itself, so one row per site is a choice about which of them a user
27692
+ * sees — and the newest is the wrong one, since a healthy tab writing a
27693
+ * fresh report would hide a drifting tab's verdict, which is the whole
27694
+ * reason these rows exist. The pick WITHIN a document is made here (the
27695
+ * unchanged `pickReportedCaptureStatus`, over that document's own rows);
27696
+ * choosing between documents belongs where the state semantics live, and
27697
+ * that is `reportedCaptureDocumentForSite` in `@akasecurity/detections` —
27698
+ * this package may not import it.
27699
+ *
27700
+ * `now` is a required argument rather than a `Date.now()` read, so a caller
27701
+ * that already holds a render instant passes THAT one and a test can drive
27702
+ * the window without moving the wall clock.
27703
+ *
27704
+ * A site whose reports have all aged out contributes nothing, so it derives
27705
+ * to `unreported`. That is the point: nothing but the browser extension ever
27706
+ * writes these rows, so an uninstalled extension's last verdict would
27707
+ * otherwise stand as a live claim for ever with no later report able to
27708
+ * clear it.
27709
+ */
27710
+ latest(now) {
27711
+ const since = now - CAPTURE_STATUS_RECENCY_MS;
27712
+ const documents = [];
27713
+ for (const tool of WebSourceTool.options) {
27714
+ const rows = /* @__PURE__ */ new Map();
27715
+ const lastWord = /* @__PURE__ */ new Map();
27716
+ for (const row of allRows(this.recentStmt, [
27717
+ tool,
27718
+ since,
27719
+ STATUS_LOOKBACK_ROWS
27720
+ ])) {
27721
+ const status = fromCaptureStatusAttributes(parseJsonObject(row.attributes));
27722
+ if (status === null) continue;
27723
+ const record2 = { tool, observedAt: epochMillisToIso(row.startedAt), status };
27724
+ const group = rows.get(row.rootSessionId);
27725
+ if (group === void 0) {
27726
+ rows.set(row.rootSessionId, [record2]);
27727
+ lastWord.set(row.rootSessionId, { at: record2.observedAt, closed: status.closed });
27728
+ } else {
27729
+ group.push(record2);
27730
+ }
27731
+ }
27732
+ for (const [root, candidates] of rows) {
27733
+ const picked = pickReportedCaptureStatus(candidates);
27734
+ const last = lastWord.get(root);
27735
+ if (picked === void 0 || last === void 0) continue;
27736
+ documents.push({
27737
+ ...picked,
27738
+ ...root === null ? {} : { rootSessionId: root },
27739
+ lastReportAt: last.at,
27740
+ closed: last.closed
27741
+ });
27742
+ }
27743
+ }
27744
+ return documents;
27745
+ }
27746
+ };
27747
+
27393
27748
  // ../../packages/persistence/src/repositories/classified-data.ts
27394
27749
  var SqliteClassifiedDataRepository = class {
27395
27750
  constructor(db) {
@@ -32967,6 +33322,7 @@ function openAndInitialize(file2, base, skipTags) {
32967
33322
  activity: new SqliteActivityRepository(db),
32968
33323
  sourceProject: new SqliteSourceProjectRepository(db),
32969
33324
  auditEvents: new SqliteAuditEventsRepository(db),
33325
+ captureStatus: new SqliteCaptureStatusRepository(db),
32970
33326
  classifiedData: new SqliteClassifiedDataRepository(db),
32971
33327
  inspectionDefinitions: new SqliteInspectionDefinitionsRepository(db),
32972
33328
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
@@ -33007,6 +33363,7 @@ function openLocalDatabase(dir, options = {}) {
33007
33363
  activity,
33008
33364
  sourceProject,
33009
33365
  auditEvents,
33366
+ captureStatus,
33010
33367
  classifiedData,
33011
33368
  inspectionDefinitions,
33012
33369
  inspectionFindings,
@@ -33224,6 +33581,7 @@ function openLocalDatabase(dir, options = {}) {
33224
33581
  activity,
33225
33582
  sourceProject,
33226
33583
  auditEvents,
33584
+ captureStatus,
33227
33585
  classifiedData,
33228
33586
  inspectionDefinitions,
33229
33587
  inspectionFindings,
@@ -33358,11 +33716,6 @@ function readFingerprintKey(dataDir2) {
33358
33716
  // ../../packages/persistence/src/forward-health.ts
33359
33717
  import { readFileSync as readFileSync7 } from "fs";
33360
33718
  import { join as join9 } from "path";
33361
- var FAILURES = /* @__PURE__ */ new Set([
33362
- "unauthorized",
33363
- "forbidden",
33364
- "unreachable"
33365
- ]);
33366
33719
  var BREAKER_COOLDOWN_MS = 3e4;
33367
33720
  function parseForwardHealth(raw, nowMs) {
33368
33721
  try {
@@ -33371,7 +33724,8 @@ function parseForwardHealth(raw, nowMs) {
33371
33724
  const record2 = parsed2;
33372
33725
  const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33373
33726
  const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33374
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33727
+ const parsedFailure = ControlPlaneFailure.safeParse(record2.lastFailure);
33728
+ const lastFailure = parsedFailure.success ? parsedFailure.data : null;
33375
33729
  return { consecutiveFailures: failures, openedAtMs, lastFailure };
33376
33730
  } catch {
33377
33731
  return null;
@@ -33461,6 +33815,12 @@ var RemoteRequestInvalid = class extends Error {
33461
33815
  }
33462
33816
  cause;
33463
33817
  };
33818
+ var RemoteEndpointRefused = class extends Error {
33819
+ constructor(endpoint) {
33820
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
33821
+ this.name = "RemoteEndpointRefused";
33822
+ }
33823
+ };
33464
33824
  var RemoteResponseInvalid = class extends Error {
33465
33825
  constructor(route, detail) {
33466
33826
  super(`control plane answered ${route} with ${detail}`);
@@ -33613,14 +33973,15 @@ function parsed(schema, body, route) {
33613
33973
  }
33614
33974
  return result.data;
33615
33975
  }
33616
- function withoutTrailingSlashes(endpoint) {
33976
+ function resolveBaseUrl(endpoint) {
33977
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
33617
33978
  let end = endpoint.length;
33618
33979
  while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
33619
33980
  return endpoint.slice(0, end);
33620
33981
  }
33621
33982
  var SLASH2 = "/".charCodeAt(0);
33622
33983
  function createRemoteClient(options) {
33623
- const base = withoutTrailingSlashes(options.endpoint);
33984
+ const base = resolveBaseUrl(options.endpoint);
33624
33985
  const url2 = (route) => `${base}${route}`;
33625
33986
  const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
33626
33987
  const sendOne = async (event) => {
@@ -33750,6 +34111,7 @@ function classifyRemoteFailure(err) {
33750
34111
  case "RemoteRouteAbsent":
33751
34112
  return "route-absent";
33752
34113
  case "RemoteRequestInvalid":
34114
+ case "RemoteEndpointRefused":
33753
34115
  return "invalid-request";
33754
34116
  case "RemoteResponseInvalid":
33755
34117
  return "rejected";
@@ -34654,6 +35016,114 @@ var CONFIG_POSTURE_RULES = [
34654
35016
  }
34655
35017
  ];
34656
35018
 
35019
+ // ../../packages/detections/src/posture/web-capture-posture.ts
35020
+ var RULE_VERSION2 = "1";
35021
+ var DRIFT_MIN_PARSE_FAILURES = 2;
35022
+ var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
35023
+ "blind",
35024
+ "degraded"
35025
+ ]);
35026
+ var WEB_CAPTURE_DRIFT_RULE = {
35027
+ ruleId: "web-capture-drift",
35028
+ version: RULE_VERSION2,
35029
+ name: "Web chat capture is not reading the site",
35030
+ category: "config",
35031
+ severity: "medium",
35032
+ definition: JSON.stringify({
35033
+ kind: "web-capture-drift",
35034
+ states: [...WEB_CAPTURE_DRIFT_STATES],
35035
+ minParseFailures: DRIFT_MIN_PARSE_FAILURES
35036
+ })
35037
+ };
35038
+ function deriveWebCaptureState(status) {
35039
+ if (status === void 0) return "unreported";
35040
+ if (status.conversationEndpoints === 0) return "standby";
35041
+ if (!status.patched) return "unpatched";
35042
+ if (status.blind) return "blind";
35043
+ if (status.shapeMisses.length > 0) return "degraded";
35044
+ if (status.parseFailures >= DRIFT_MIN_PARSE_FAILURES) return "degraded";
35045
+ return status.live ? "active" : "idle";
35046
+ }
35047
+ var STATE_SEVERITY = {
35048
+ blind: 0,
35049
+ degraded: 1,
35050
+ unpatched: 2,
35051
+ idle: 3,
35052
+ standby: 4,
35053
+ active: 5,
35054
+ unreported: 6
35055
+ };
35056
+ function worseThan(a, b) {
35057
+ const sa = STATE_SEVERITY[deriveWebCaptureState(a.status)];
35058
+ const sb = STATE_SEVERITY[deriveWebCaptureState(b.status)];
35059
+ if (sa !== sb) return sa < sb;
35060
+ if (a.observedAt !== b.observedAt) return a.observedAt > b.observedAt;
35061
+ return (a.rootSessionId ?? "") > (b.rootSessionId ?? "");
35062
+ }
35063
+ function reportedCaptureDocumentForSite(documents) {
35064
+ let newestReport = "";
35065
+ for (const d of documents) if (d.lastReportAt > newestReport) newestReport = d.lastReportAt;
35066
+ const retired = (d) => {
35067
+ if (d.closed) return true;
35068
+ const behind = Date.parse(newestReport) - Date.parse(d.lastReportAt);
35069
+ return Number.isFinite(behind) && behind > CAPTURE_STATUS_DOCUMENT_QUIET_MS;
35070
+ };
35071
+ const voting = documents.filter((d) => !retired(d));
35072
+ const tested = voting.some((d) => webCaptureStatusObservedTurnPath(d.status));
35073
+ const pool = tested ? voting : documents;
35074
+ let worst;
35075
+ for (const d of pool) if (worst === void 0 || worseThan(d, worst)) worst = d;
35076
+ return worst;
35077
+ }
35078
+ var STATIC_COPY = {
35079
+ active: { headline: "turns are being observed on this site" },
35080
+ unreported: {
35081
+ // Says "recently" rather than "yet": the store read is bounded to
35082
+ // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
35083
+ // reported for AND one whose last report has aged out. The two are the
35084
+ // same fact to a reader — nobody has confirmed anything lately — and the
35085
+ // copy may not claim the stronger of them.
35086
+ headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
35087
+ },
35088
+ standby: {
35089
+ headline: "this build declares no endpoints for the site, so nothing is observed yet"
35090
+ },
35091
+ unpatched: {
35092
+ // Says what the flags say and no more. `patched` is false both for a tap
35093
+ // that installed and hooked neither transport and for one that never ran
35094
+ // at all — a page reports the same status either way, so the copy may not
35095
+ // assert one of them.
35096
+ headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
35097
+ },
35098
+ idle: { headline: "watching; no turn has been observed yet" },
35099
+ blind: {
35100
+ headline: "messages were sent in the page that the network capture never saw",
35101
+ remediation: "reload the tab. If it persists after `aka update` and reloading the extension at chrome://extensions, the site's send path has changed and needs a new extension build."
35102
+ },
35103
+ degraded: {
35104
+ headline: "the site's payloads no longer carry the fields the extension reads",
35105
+ remediation: "run `aka update`, then reload the extension at chrome://extensions. If it stays degraded after an update, the site's contract has changed and needs a new extension build."
35106
+ }
35107
+ };
35108
+ function webCaptureStateCopy(state) {
35109
+ return STATIC_COPY[state];
35110
+ }
35111
+ function webCaptureReport(documents) {
35112
+ return WebSourceTool.options.map((tool) => {
35113
+ const record2 = reportedCaptureDocumentForSite(documents.filter((d) => d.tool === tool));
35114
+ const state = deriveWebCaptureState(record2?.status);
35115
+ const copy = webCaptureStateCopy(state);
35116
+ return {
35117
+ tool,
35118
+ state,
35119
+ headline: copy.headline,
35120
+ ...copy.remediation !== void 0 ? { remediation: copy.remediation } : {},
35121
+ drift: WEB_CAPTURE_DRIFT_STATES.has(state),
35122
+ ...record2 !== void 0 ? { observedAt: record2.observedAt } : {}
35123
+ };
35124
+ });
35125
+ }
35126
+
34657
35127
  // ../../packages/detections/src/security/redos-probe.ts
34658
35128
  var BUDGET_MS = 100;
34659
35129
  var EXPONENTIAL_UNITS = [
@@ -36711,6 +37181,11 @@ function bundledDetections() {
36711
37181
  import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36712
37182
  import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
36713
37183
 
37184
+ // ../../packages/plugin-sdk/src/data-gateway.ts
37185
+ function offersCaptureStatusReader(gateway) {
37186
+ return typeof gateway.readCaptureStatuses === "function";
37187
+ }
37188
+
36714
37189
  // ../../packages/plugin-sdk/src/events.ts
36715
37190
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
36716
37191
 
@@ -36971,86 +37446,10 @@ function createForwardPolicy(deps) {
36971
37446
  }
36972
37447
 
36973
37448
  // ../../packages/plugin-runtime/src/attached/gateway.ts
36974
- function strongerOf(a, b) {
36975
- if (a === null) return b;
36976
- if (b === null) return a;
36977
- return strongerAction(a, b);
36978
- }
36979
- function ruleCategoryMap(wireRules, localRules) {
36980
- const map2 = /* @__PURE__ */ new Map();
36981
- for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
36982
- for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
36983
- for (const pack of bundledDetections()) {
36984
- for (const rule of pack.rules) map2.set(rule.id, rule.category);
36985
- }
36986
- return map2;
36987
- }
36988
- function policyKey(policy) {
36989
- return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
36990
- }
36991
- function floorFor(policy, categoryByRuleId) {
36992
- const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
36993
- return category === void 0 ? null : DEFAULT_ACTIONS[category];
36994
- }
36995
- function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
36996
- const merged = /* @__PURE__ */ new Map();
36997
- const disabled = [];
36998
- const remoteCategoryAction = /* @__PURE__ */ new Map();
36999
- for (const policy of remotePolicies) {
37000
- if (!policy.enabled) continue;
37001
- if (!("category" in policy.target)) continue;
37002
- if (remoteCategoryAction.has(policy.target.category)) continue;
37003
- const floor = floorFor(policy, categoryByRuleId);
37004
- remoteCategoryAction.set(
37005
- policy.target.category,
37006
- floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
37007
- );
37008
- }
37009
- for (const policy of localPolicies) {
37010
- if (!policy.enabled) {
37011
- disabled.push(policy);
37012
- continue;
37013
- }
37014
- const key = policyKey(policy);
37015
- if (merged.has(key)) continue;
37016
- let remoteFloor = null;
37017
- if ("ruleId" in policy.target) {
37018
- const category = categoryByRuleId.get(policy.target.ruleId);
37019
- if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
37020
- }
37021
- merged.set(
37022
- key,
37023
- remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
37024
- );
37025
- }
37026
- const localCategoryAction = /* @__PURE__ */ new Map();
37027
- for (const policy of merged.values()) {
37028
- if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
37029
- }
37030
- for (const policy of remotePolicies) {
37031
- if (!policy.enabled) {
37032
- disabled.push(policy);
37033
- continue;
37034
- }
37035
- const key = policyKey(policy);
37036
- const floor = floorFor(policy, categoryByRuleId);
37037
- let localFloor = null;
37038
- if ("ruleId" in policy.target) {
37039
- const category = categoryByRuleId.get(policy.target.ruleId);
37040
- if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
37041
- }
37042
- const effectiveFloor = strongerOf(floor, localFloor);
37043
- const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
37044
- const existing = merged.get(key);
37045
- if (existing === void 0) {
37046
- merged.set(key, clamped);
37047
- continue;
37048
- }
37049
- if (actionRank(clamped.action) > actionRank(existing.action)) {
37050
- merged.set(key, clamped);
37051
- }
37052
- }
37053
- return [...merged.values(), ...disabled];
37449
+ var bundledRulesFlatCache;
37450
+ function bundledRulesFlat() {
37451
+ bundledRulesFlatCache ??= bundledDetections().flatMap((pack) => pack.rules);
37452
+ return bundledRulesFlatCache;
37054
37453
  }
37055
37454
  var AttachedDataGateway = class {
37056
37455
  constructor(deps) {
@@ -37370,6 +37769,9 @@ var AttachedDataGateway = class {
37370
37769
  async readSessionProvider(sessionId) {
37371
37770
  return this.deps.local.readSessionProvider(sessionId);
37372
37771
  }
37772
+ async readCaptureStatuses() {
37773
+ return this.deps.local.readCaptureStatuses();
37774
+ }
37373
37775
  async facets() {
37374
37776
  return this.deps.local.facets();
37375
37777
  }
@@ -37452,7 +37854,7 @@ var AttachedDataGateway = class {
37452
37854
  policies: mergeRaiseOnly(
37453
37855
  local.policies,
37454
37856
  cached2.policies,
37455
- ruleCategoryMap(cached2.rules, local.rules)
37857
+ ruleCategoryMap(cached2.rules, local.rules, bundledRulesFlat())
37456
37858
  ),
37457
37859
  customKeywords: [...local.customKeywords, ...cached2.customKeywords],
37458
37860
  // TAKEN FROM THE CACHE, unlike the two fields below — and the asymmetry
@@ -37653,10 +38055,15 @@ import { join as join27 } from "path";
37653
38055
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37654
38056
  import { rename as rename2 } from "fs/promises";
37655
38057
  var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
37656
- var ATTEMPTS = 5;
38058
+ var IMMEDIATE_RETRIES = 8;
38059
+ var TIMED_RETRIES = 4;
38060
+ var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
37657
38061
  var delay = (ms) => new Promise((resolve2) => {
37658
38062
  setTimeout(resolve2, ms);
37659
38063
  });
38064
+ var yieldToLoop = () => new Promise((resolve2) => {
38065
+ setImmediate(resolve2);
38066
+ });
37660
38067
  async function publishByRename(tmp, file2, move = rename2) {
37661
38068
  for (let attempt = 1; ; attempt += 1) {
37662
38069
  try {
@@ -37665,7 +38072,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37665
38072
  } catch (err) {
37666
38073
  const code = err.code;
37667
38074
  if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
37668
- await delay(attempt * 10);
38075
+ await (attempt <= IMMEDIATE_RETRIES ? yieldToLoop() : delay((attempt - IMMEDIATE_RETRIES) * 10));
37669
38076
  }
37670
38077
  }
37671
38078
  }
@@ -38129,6 +38536,9 @@ var StandaloneDataGateway = class {
38129
38536
  readSessionProvider(sessionId) {
38130
38537
  return Promise.resolve(this.db.auditEvents.sessionProvider(sessionId));
38131
38538
  }
38539
+ readCaptureStatuses() {
38540
+ return Promise.resolve(this.db.captureStatus.latest(Date.now()));
38541
+ }
38132
38542
  facets() {
38133
38543
  return Promise.resolve(this.db.facets());
38134
38544
  }
@@ -38676,6 +39086,24 @@ function renderFindings(findings, status, severity) {
38676
39086
  indent(renderStatusBar(status))
38677
39087
  ].join("\n");
38678
39088
  }
39089
+ function renderWebCaptureDrift(sites) {
39090
+ const drifting = sites.filter((s) => s.drift);
39091
+ if (drifting.length === 0) return "";
39092
+ const rows = drifting.map((s) => [s.tool, s.state, s.headline]);
39093
+ return [
39094
+ `\u25CF Web chat capture (${String(drifting.length)})`,
39095
+ "",
39096
+ indent(table(["Site", "State", "What happened"], rows, { gap: 4 })),
39097
+ "",
39098
+ ...drifting.flatMap(
39099
+ (s) => s.remediation === void 0 ? [] : [
39100
+ indent(
39101
+ `${s.tool} \u2014 ${WEB_CAPTURE_DRIFT_RULE.ruleId} (${WEB_CAPTURE_DRIFT_RULE.severity}) \u2014 ${s.remediation}`
39102
+ )
39103
+ ]
39104
+ )
39105
+ ].join("\n");
39106
+ }
38679
39107
  var GAUGE_LABEL_W = 14;
38680
39108
  var GAUGE_BAR_W = 18;
38681
39109
  var WEEK_LABEL_W = 5;
@@ -38956,6 +39384,15 @@ function renderDetections(items) {
38956
39384
  }
38957
39385
  var SEVERITIES2 = ["critical", "high", "medium", "low"];
38958
39386
  var USAGE = "Usage: query <findings|health|recommend|audit|tokens|exceptions|detections>";
39387
+ async function webCaptureSites(gateway, consent) {
39388
+ if (!consent) return [];
39389
+ if (!offersCaptureStatusReader(gateway)) return [];
39390
+ try {
39391
+ return webCaptureReport(await gateway.readCaptureStatuses());
39392
+ } catch {
39393
+ return [];
39394
+ }
39395
+ }
38959
39396
  async function runQuery(sub2, gateway, opts = {}) {
38960
39397
  switch (sub2) {
38961
39398
  case "findings": {
@@ -38965,7 +39402,12 @@ async function runQuery(sub2, gateway, opts = {}) {
38965
39402
  gateway.healthSummary()
38966
39403
  ]);
38967
39404
  const rows = opts.severity !== void 0 ? findings.filter((f) => f.severity === opts.severity) : findings;
38968
- return renderFindings(rows, findingStatus(summary), opts.severity);
39405
+ const body = renderFindings(rows, findingStatus(summary), opts.severity);
39406
+ const showBlock2 = opts.severity === void 0 || opts.severity === WEB_CAPTURE_DRIFT_RULE.severity;
39407
+ const block = showBlock2 ? renderWebCaptureDrift(await webCaptureSites(gateway, opts.webCaptureConsent ?? false)) : "";
39408
+ return block === "" ? body : `${body}
39409
+
39410
+ ${block}`;
38969
39411
  }
38970
39412
  case "health": {
38971
39413
  const [summary, findings, activity] = await Promise.all([
@@ -39032,6 +39474,14 @@ try {
39032
39474
  `${fenced(
39033
39475
  await runQuery(sub, gateway, {
39034
39476
  ...severity !== void 0 ? { severity } : {},
39477
+ // Resolved here rather than inside render.ts, which reads no
39478
+ // files: this is the settings-holding boundary, and it is the
39479
+ // same predicate `aka extension status` and the native host
39480
+ // apply, so the three surfaces cannot disagree about whether
39481
+ // web-chat capture is on.
39482
+ webCaptureConsent: isWebChatCaptureConsentValid(
39483
+ webChatCaptureOf(config2.settings).consent
39484
+ ),
39035
39485
  // Resolved here rather than inside runQuery, which holds a gateway
39036
39486
  // and not the data dir. Read from the cache a hook wrote: probing
39037
39487
  // `claude --version` would answer for the install on PATH, which