@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.
@@ -20478,7 +20478,17 @@ var UNPRICEABLE_PROVIDERS = Object.freeze([
20478
20478
  "gateway",
20479
20479
  "unknown",
20480
20480
  "cli",
20481
- "api"
20481
+ "api",
20482
+ // The browser extension's native host records these as `llm_call.provider`
20483
+ // for a web-chat turn — the web tool id, deliberately never the vendor id
20484
+ // (`openai`/`anthropic`) the session root carries. Subscription traffic
20485
+ // burns rate-limit budget, not dollar credits, and listing them here is
20486
+ // what keeps that true structurally: a later maintainer who wants to price
20487
+ // web-chat traffic at API rates has to delete this entry first, and meet
20488
+ // the reason on the way, rather than quietly adding one to
20489
+ // PROVIDER_PLATFORM.
20490
+ "chatgpt",
20491
+ "claude-ai"
20482
20492
  ]);
20483
20493
  function platformForProvider(provider) {
20484
20494
  return PROVIDER_PLATFORM.get(provider.trim().toLowerCase()) ?? null;
@@ -20621,7 +20631,12 @@ var HARNESS = {
20621
20631
  ClaudeDesktop: "claudedesktop",
20622
20632
  ChatGpt: "chatgpt",
20623
20633
  ClaudeAi: "claudeai",
20624
- Api: "api"
20634
+ Api: "api",
20635
+ // Not a coding assistant a person drives — an in-process SDK embedded in an
20636
+ // application, so it has no IDE/CLI/desktop/web surface of its own. Carries
20637
+ // the same id as its SOURCE_TOOL counterpart, unlike every capture-side tool
20638
+ // whose wire spelling differs from its display spelling.
20639
+ AiTcSdk: "ai-tc-sdk"
20625
20640
  };
20626
20641
  var Harness = external_exports.enum(HARNESS).meta({ id: "Harness" });
20627
20642
  var SOURCE_TOOL = {
@@ -20637,9 +20652,15 @@ var SOURCE_TOOL = {
20637
20652
  // whose tool could not be identified both render through the read side's
20638
20653
  // miss path rather than as a harness of their own.
20639
20654
  Cli: "cli",
20640
- Unknown: "unknown"
20655
+ Unknown: "unknown",
20656
+ // The wire id an in-process, request-path SDK stamps on its own structural
20657
+ // rows (`request_decision`) — never a capture of prompt/response/tool text,
20658
+ // since the SDK sits in front of a model call rather than inside a coding
20659
+ // assistant's own hook contract.
20660
+ AiTcSdk: "ai-tc-sdk"
20641
20661
  };
20642
20662
  var SourceTool = external_exports.enum(SOURCE_TOOL).meta({ id: "SourceTool" });
20663
+ var WebSourceTool = SourceTool.extract(["ChatGpt", "ClaudeAi"]);
20643
20664
  var TOOL_TO_HARNESS = {
20644
20665
  [SOURCE_TOOL.ClaudeCode]: HARNESS.ClaudeCode,
20645
20666
  [SOURCE_TOOL.ClaudeDesktop]: HARNESS.ClaudeDesktop,
@@ -20648,7 +20669,12 @@ var TOOL_TO_HARNESS = {
20648
20669
  [SOURCE_TOOL.ChatGpt]: HARNESS.ChatGpt,
20649
20670
  [SOURCE_TOOL.Codex]: HARNESS.Codex,
20650
20671
  [SOURCE_TOOL.Antigravity]: HARNESS.Antigravity,
20651
- [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20672
+ [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi,
20673
+ // Wire and display id are the same string here, but the row still belongs:
20674
+ // both vocabularies carry the `AiTcSdk` member, and the join is exactly
20675
+ // their intersection — leaving a shared member out would read as an
20676
+ // uninstrumented tool on both surfaces, which this one is not.
20677
+ [SOURCE_TOOL.AiTcSdk]: HARNESS.AiTcSdk
20652
20678
  };
20653
20679
 
20654
20680
  // ../../packages/schema/src/zod/finding.ts
@@ -20682,7 +20708,8 @@ var FindingProvider = Harness.extract([
20682
20708
  "ClaudeAi",
20683
20709
  "Codex",
20684
20710
  "Antigravity",
20685
- "Api"
20711
+ "Api",
20712
+ "AiTcSdk"
20686
20713
  ]).meta({ id: "FindingProvider" });
20687
20714
  var FindingCategory = external_exports.enum([
20688
20715
  "secret",
@@ -21059,18 +21086,41 @@ var AuditEventType = external_exports.enum([
21059
21086
  // 'tool_call' is the reconciler's structural row for every call, while
21060
21087
  // 'tool_use' exists only where a hook enforced against the arguments.
21061
21088
  "tool_use",
21062
- // One row per model REFUSAL: a switch onto a prohibited model that was
21063
- // denied, or a turn refused because the session was already running on one.
21064
- // A structural row like the ones above rather than a capture — it carries
21065
- // the model that was refused and nothing the user typed, because what is
21066
- // worth recording about a governance decision is the decision, and prompt
21067
- // text is the thing this product exists to keep from travelling.
21089
+ // One row per model REFUSAL, across all four seams a prohibited model can be
21090
+ // stopped at: a switch onto it, a turn already running on it, a subagent
21091
+ // spawn asking for it, or a request-path refusal an embedded request-path
21092
+ // SDK makes in-process before the call leaves the application. Which seam
21093
+ // rides `attributes.refusal_seam`, never this member name. A structural row
21094
+ // like the ones above rather than a capture — it carries the model that was
21095
+ // refused and nothing the user typed, because what is worth recording about
21096
+ // a governance decision is the decision, and prompt text is the thing this
21097
+ // product exists to keep from travelling.
21068
21098
  "model_refusal",
21099
+ // One row per request-path DECISION: a policy check an embedded request-path
21100
+ // SDK performs in-process before a model call leaves the application, or
21101
+ // against that call's non-streamed response. A structural row like
21102
+ // 'model_refusal' rather than a capture — content-free in the same way:
21103
+ // which side, which seam, what action and which field are decided rides
21104
+ // `attributes`, never this member name, and the matched text itself never
21105
+ // travels.
21106
+ //
21107
+ // A prohibited-model refusal on the request path is deliberately NOT this
21108
+ // member: it stays 'model_refusal' with `refusal_seam: 'request'`, so it
21109
+ // shares one bucket with the plugin's switch/turn/spawn refusals rather
21110
+ // than splitting one governance concept across two event types. This
21111
+ // member carries every OTHER request-path decision.
21112
+ "request_decision",
21069
21113
  // One row per config-inventory scan, hung off the session root. It is the
21070
21114
  // fact the posture inspection findings reference (findings require an
21071
21115
  // audit_event_id), and its started_at is the "scanned Nm ago" the read
21072
21116
  // surface renders.
21073
- "config_scan"
21117
+ "config_scan",
21118
+ // One row per reported browser-extension capture status, hung off the web
21119
+ // session root. The durable home of what one tab's network interception
21120
+ // is doing — a write-through of the native host's in-memory tracker, so a
21121
+ // second process (aka extension status) and a restarted host both have
21122
+ // somewhere to read it back from.
21123
+ "capture_status"
21074
21124
  ]).meta({ id: "AuditEventType" });
21075
21125
  var AttributeBag = external_exports.record(external_exports.string(), external_exports.unknown());
21076
21126
  var HostAttributes = external_exports.object({
@@ -21230,6 +21280,20 @@ var CaptureAttributes = external_exports.object({
21230
21280
  // repeated rather than referenced because a store reader opens this file.
21231
21281
  redact_degraded_to: ActionTaken.optional()
21232
21282
  }).catchall(external_exports.unknown());
21283
+ var CaptureStatusAttributes = external_exports.object({
21284
+ source_tool: external_exports.string().optional(),
21285
+ patched: external_exports.boolean().optional(),
21286
+ live: external_exports.boolean().optional(),
21287
+ blind: external_exports.boolean().optional(),
21288
+ sends_seen_dom: external_exports.number().int().nonnegative().optional(),
21289
+ exchanges_seen_net: external_exports.number().int().nonnegative().optional(),
21290
+ parse_failures: external_exports.number().int().nonnegative().optional(),
21291
+ unparsed_bodies: external_exports.number().int().nonnegative().optional(),
21292
+ shape_misses: external_exports.array(external_exports.string()).optional(),
21293
+ conversation_endpoints: external_exports.number().int().nonnegative().optional(),
21294
+ closed: external_exports.boolean().optional(),
21295
+ enforcement: external_exports.string().optional()
21296
+ }).catchall(external_exports.unknown());
21233
21297
  var ToolCallInspection = external_exports.object({
21234
21298
  ruleId: external_exports.string().min(1),
21235
21299
  ruleName: external_exports.string(),
@@ -22089,6 +22153,30 @@ var AttachedCredential = external_exports.object({
22089
22153
  keyPrefix: external_exports.string().min(1).max(16).optional(),
22090
22154
  mintedAt: external_exports.iso.datetime().optional()
22091
22155
  });
22156
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
22157
+ function unsafeEndpointReason(endpoint) {
22158
+ let parsed2;
22159
+ try {
22160
+ parsed2 = new URL(endpoint);
22161
+ } catch {
22162
+ return "unparseable";
22163
+ }
22164
+ if (parsed2.username !== "" || parsed2.password !== "") return "userinfo";
22165
+ if (parsed2.search !== "" || parsed2.hash !== "") return "query-or-fragment";
22166
+ if (parsed2.protocol === "https:") return null;
22167
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname) ? null : "insecure";
22168
+ }
22169
+ function isSafeEndpoint(endpoint) {
22170
+ return unsafeEndpointReason(endpoint) === null;
22171
+ }
22172
+ function originOnly(endpoint) {
22173
+ try {
22174
+ const parsed2 = new URL(endpoint);
22175
+ return `${parsed2.protocol}//${parsed2.host}`;
22176
+ } catch {
22177
+ return "(unparseable endpoint)";
22178
+ }
22179
+ }
22092
22180
  var MAX_DATE_MS = 253402300799999;
22093
22181
  var MAX_INT4 = 2147483647;
22094
22182
  var StorePosturePack = external_exports.object({
@@ -22243,6 +22331,11 @@ var RemoteFailureKind = external_exports.enum([
22243
22331
  "rejected",
22244
22332
  "unreachable"
22245
22333
  ]);
22334
+ var ControlPlaneFailure = RemoteFailureKind.extract([
22335
+ "unauthorized",
22336
+ "forbidden",
22337
+ "unreachable"
22338
+ ]);
22246
22339
  var AttachDeviceRequest = external_exports.object({
22247
22340
  // This machine's own continuity id, so re-attaching ROTATES the credential
22248
22341
  // on one machine record instead of producing a second one. Client-minted
@@ -22782,7 +22875,12 @@ var EventMetadata = external_exports.object({
22782
22875
  // in — set by the browser extension's network capture so a stored `response`
22783
22876
  // row can be joined to the `llm_call` leaf describing the same turn. Absent
22784
22877
  // on every other capture path, which has no such id.
22785
- messageId: external_exports.string().optional(),
22878
+ //
22879
+ // Non-empty for the reason WebExchange.messageId is: it is the join key, and
22880
+ // a blank one matches no `llm_call` leaf. That refusal reaches only the
22881
+ // places an event is PARSED; the local write path types the event and parses
22882
+ // nothing, which is why `toCaptureAttributes` omits a blank one separately.
22883
+ messageId: external_exports.string().min(1).optional(),
22786
22884
  conversationId: external_exports.string().optional(),
22787
22885
  // How long THIS capture's inspection blocked its caller, in whole
22788
22886
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
@@ -23851,6 +23949,18 @@ function isHistorySyncConsentValid(consent, endpoint) {
23851
23949
  if (consent === void 0 || endpoint === void 0) return false;
23852
23950
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23853
23951
  }
23952
+ var WebChatCaptureConsent = external_exports.object({
23953
+ acknowledgedAt: external_exports.iso.datetime(),
23954
+ version: external_exports.number().int().positive()
23955
+ });
23956
+ var WebChatResponseCapture = external_exports.enum(["with-findings", "always", "never"]);
23957
+ var WebChatCapture = external_exports.object({
23958
+ responses: WebChatResponseCapture.default("with-findings"),
23959
+ account: external_exports.boolean().default(false),
23960
+ // Absent until granted. Presence alone does not authorize anything — see
23961
+ // isWebChatCaptureConsentValid.
23962
+ consent: WebChatCaptureConsent.optional()
23963
+ });
23854
23964
  var BODY_RETENTION_DEFAULT_DAYS = 30;
23855
23965
  var BodyRetention = external_exports.object({
23856
23966
  enabled: external_exports.boolean().default(false),
@@ -23909,6 +24019,16 @@ var WorkspaceSettings = external_exports.object({
23909
24019
  // both widenings. Absent until granted, and a grant for a different endpoint
23910
24020
  // or an older payload no longer counts.
23911
24021
  historySyncConsent: HistorySyncConsent.optional(),
24022
+ // What the browser extension may record from a web chat, and the grant that
24023
+ // authorizes it. Absent until the user answers: recording something that was
24024
+ // never recorded before is never an assumed grant on upgrade, so the whole
24025
+ // block is optional rather than defaulted in. What an absent block means is
24026
+ // webChatCaptureOf's answer, in one place.
24027
+ //
24028
+ // Enforcement is NOT gated on this. A machine that has never answered still
24029
+ // blocks, redacts and warns on what a user sends; the grant covers what is
24030
+ // written down.
24031
+ webChatCapture: WebChatCapture.optional(),
23912
24032
  // Local body expiry (see BodyRetention). Off until switched on; expiring a
23913
24033
  // body never removes the row or its findings.
23914
24034
  bodyRetention: BodyRetention.default({
@@ -24016,7 +24136,10 @@ function toCaptureAttributes(event) {
24016
24136
  // `.catchall(z.unknown())` carries the long tail.
24017
24137
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
24018
24138
  ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24019
- ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24139
+ // A blank id is omitted rather than stored: it is a join key and `''` joins
24140
+ // nothing. This runs on the local write path, which types the event but
24141
+ // never parses it, so EventMetadata's own `.min(1)` does not reach here.
24142
+ ...metadata?.messageId !== void 0 && metadata.messageId !== "" ? { message_id: metadata.messageId } : {},
24020
24143
  ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
24021
24144
  };
24022
24145
  }
@@ -24390,12 +24513,14 @@ var RecommendedActionIdParam = external_exports.object({ id: external_exports.st
24390
24513
  // ../../packages/schema/src/zod/settings-action.ts
24391
24514
  var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
24392
24515
  var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
24516
+ var WebChatCaptureConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "WebChatCaptureConsentChoice" });
24393
24517
  var SaveSettingsInput = external_exports.object({
24394
24518
  historicalAccess: external_exports.string(),
24395
24519
  modelJudgeConsent: ModelJudgeConsentChoice,
24396
24520
  historySyncConsent: HistorySyncConsentChoice,
24397
24521
  vaultConsent: external_exports.string(),
24398
24522
  vaultInlineReveal: external_exports.string(),
24523
+ webChatCaptureConsent: WebChatCaptureConsentChoice,
24399
24524
  // Widened to `string` like its neighbours rather than typed as
24400
24525
  // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24401
24526
  // the call site, so the domain check receives the type it was written for.
@@ -24610,11 +24735,24 @@ var WebExchange = external_exports.object({
24610
24735
  turnIndex: external_exports.number().int().nonnegative().optional(),
24611
24736
  toolCalls: external_exports.array(WebToolCall).default([]),
24612
24737
  // Absent when the adapter recovered no text. Capped by the caller at
24613
- // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24614
- // short capture is never mistaken for a short reply.
24738
+ // RESPONSE_TEXT_MAX_BYTES, so a short capture is never mistaken for a short
24739
+ // reply.
24615
24740
  responseText: external_exports.string().optional(),
24741
+ // The stored text is short of the reply. It does NOT say which of the two
24742
+ // ceilings on this path cut it: the caller applies its own cap on the raw
24743
+ // bytes it reads off the wire, which can be reached by a stream whose
24744
+ // recovered text stays well under RESPONSE_TEXT_MAX_BYTES, and applies that
24745
+ // one to the text. A reader cannot tell them apart, and nothing downstream
24746
+ // should branch as though it could.
24616
24747
  truncated: external_exports.boolean().default(false)
24617
24748
  });
24749
+ var WebEnforcementState = external_exports.enum([
24750
+ "watching",
24751
+ "composer-only",
24752
+ "button-only",
24753
+ "unattached",
24754
+ "unknown"
24755
+ ]);
24618
24756
  var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24619
24757
  var WebCaptureStatus = external_exports.object({
24620
24758
  patched: external_exports.boolean(),
@@ -24626,8 +24764,66 @@ var WebCaptureStatus = external_exports.object({
24626
24764
  unparsedBodies: external_exports.number().int().nonnegative(),
24627
24765
  // The adapter-declared JSON key paths that were absent from a real payload —
24628
24766
  // the earliest signal that a site's contract moved.
24629
- shapeMisses: external_exports.array(external_exports.string()).default([])
24630
- });
24767
+ shapeMisses: external_exports.array(external_exports.string()).default([]),
24768
+ // How many `kind: 'conversation'` endpoints the reporting tab's adapter
24769
+ // compiled. Zero means this build declares none for the site, so observing
24770
+ // nothing is the design rather than a fault — the one fact that separates a
24771
+ // site nobody has surveyed yet from one whose contract moved. Defaulted so a
24772
+ // build predating the field is read as declaring nothing rather than refused.
24773
+ conversationEndpoints: external_exports.number().int().nonnegative().default(0),
24774
+ // The document that sent this report is going away. The bridge sets it on
24775
+ // its `pagehide` report and nowhere else.
24776
+ //
24777
+ // A property of the REPORT rather than of capture health, which is why
24778
+ // nothing in `deriveWebCaptureState` reads it and why it stays out of the
24779
+ // bridge's own report signature — a closing tab's last word must not be
24780
+ // suppressed for carrying the same health as the report before it. What
24781
+ // reads it is the per-site fold: a document that said it was unloading stops
24782
+ // voting on the site's state, so the reload the `blind` remediation asks for
24783
+ // can actually clear the verdict it was shown. A document that dies without
24784
+ // sending one is covered by CAPTURE_STATUS_DOCUMENT_QUIET_MS instead.
24785
+ //
24786
+ // Defaulted so a build predating the field reads as a document that never
24787
+ // said it was closing — which keeps it voting, the same as every report that
24788
+ // is not a final one.
24789
+ closed: external_exports.boolean().default(false),
24790
+ // What the DOM enforcement path is doing, which none of the counters above
24791
+ // can say: `sendsSeenDom` rises only once a send has COMPLETED, so a tab
24792
+ // whose watcher never bound reports zero exactly like a tab nobody typed in.
24793
+ // Defaulted to 'unknown' rather than 'watching' so a status from a build
24794
+ // predating the field is not read as reporting a healthy one.
24795
+ enforcement: WebEnforcementState.default("unknown")
24796
+ });
24797
+ function webCaptureStatusObservedTurnPath(status) {
24798
+ if (!status.patched) return true;
24799
+ if (status.conversationEndpoints === 0) return true;
24800
+ return status.blind || status.shapeMisses.length > 0 || status.parseFailures > 0 || status.unparsedBodies > 0 || status.exchangesSeenNet > 0;
24801
+ }
24802
+ function pickReportedCaptureStatus(candidates) {
24803
+ return candidates.find((c) => webCaptureStatusObservedTurnPath(c.status)) ?? candidates[0];
24804
+ }
24805
+ var CAPTURE_STATUS_RECENCY_MS = 30 * 24 * 60 * 60 * 1e3;
24806
+ var CAPTURE_STATUS_RECENCY_DAYS = CAPTURE_STATUS_RECENCY_MS / (24 * 60 * 60 * 1e3);
24807
+ var CAPTURE_STATUS_DOCUMENT_QUIET_MS = 12 * 60 * 60 * 1e3;
24808
+ function fromCaptureStatusAttributes(bag) {
24809
+ const parsedBag = CaptureStatusAttributes.safeParse(bag);
24810
+ if (!parsedBag.success) return null;
24811
+ const b = parsedBag.data;
24812
+ const parsedStatus = WebCaptureStatus.safeParse({
24813
+ patched: b.patched,
24814
+ live: b.live,
24815
+ blind: b.blind,
24816
+ sendsSeenDom: b.sends_seen_dom,
24817
+ exchangesSeenNet: b.exchanges_seen_net,
24818
+ parseFailures: b.parse_failures,
24819
+ unparsedBodies: b.unparsed_bodies,
24820
+ shapeMisses: b.shape_misses,
24821
+ conversationEndpoints: b.conversation_endpoints,
24822
+ closed: b.closed,
24823
+ enforcement: b.enforcement
24824
+ });
24825
+ return parsedStatus.success ? parsedStatus.data : null;
24826
+ }
24631
24827
 
24632
24828
  // ../../packages/persistence/src/paths.ts
24633
24829
  import {
@@ -24701,17 +24897,6 @@ function writeOwnerOnlyFileSync(file2, data) {
24701
24897
  function controlPlaneCredentialPath(settingsDir2) {
24702
24898
  return join2(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
24703
24899
  }
24704
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
24705
- function isSafeEndpoint(endpoint) {
24706
- let parsed2;
24707
- try {
24708
- parsed2 = new URL(endpoint);
24709
- } catch {
24710
- return false;
24711
- }
24712
- if (parsed2.protocol === "https:") return true;
24713
- return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
24714
- }
24715
24900
  function repairOrRefuseMode(file2) {
24716
24901
  const link = lstatSync2(file2, { throwIfNoEntry: false });
24717
24902
  if (link === void 0) return "absent";
@@ -26490,7 +26675,7 @@ var SESSION_ROOT = `event_type = 'session'`;
26490
26675
  var HAS_ACTIVITY = `EXISTS (
26491
26676
  SELECT 1 FROM audit_events c
26492
26677
  WHERE c.root_session_id = audit_events.id
26493
- AND c.event_type NOT IN ('hook', 'config_scan'))`;
26678
+ AND c.event_type NOT IN ('hook', 'config_scan', 'capture_status'))`;
26494
26679
  var SqliteActivityRepository = class {
26495
26680
  constructor(db, now = () => Date.now()) {
26496
26681
  this.db = db;
@@ -26517,10 +26702,10 @@ var SqliteActivityRepository = class {
26517
26702
  SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
26518
26703
  UNION
26519
26704
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
26520
- WHERE started_at >= ?
26705
+ WHERE started_at >= ? AND event_type <> 'capture_status'
26521
26706
  UNION
26522
26707
  SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
26523
- WHERE ended_at >= ?)`,
26708
+ WHERE ended_at >= ? AND event_type <> 'capture_status')`,
26524
26709
  [liveThreshold, liveThreshold, liveThreshold]
26525
26710
  );
26526
26711
  const toolCallsToday = countScalar(
@@ -26927,7 +27112,10 @@ var SqliteAuditEventsRepository = class {
26927
27112
  attributes = excluded.attributes,
26928
27113
  ended_at = excluded.ended_at
26929
27114
  WHERE COALESCE(json_extract(excluded.attributes, '$.output_tokens'), 0)
26930
- > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)`
27115
+ > COALESCE(json_extract(audit_events.attributes, '$.output_tokens'), 0)
27116
+ OR (json_extract(excluded.attributes, '$.usage_source') IS NOT NULL
27117
+ AND json_extract(excluded.attributes, '$.output_tokens') IS NULL
27118
+ AND excluded.attributes <> audit_events.attributes)`
26931
27119
  );
26932
27120
  this.upsertSessionRootStmt = db.prepare(
26933
27121
  `INSERT OR IGNORE INTO audit_events
@@ -27195,6 +27383,87 @@ var SqliteBodyRetentionRepository = class {
27195
27383
  }
27196
27384
  };
27197
27385
 
27386
+ // ../../packages/persistence/src/repositories/capture-status.ts
27387
+ var STATUS_LOOKBACK_ROWS = 128;
27388
+ var SqliteCaptureStatusRepository = class {
27389
+ constructor(db) {
27390
+ this.db = db;
27391
+ this.recentStmt = db.prepare(
27392
+ `SELECT a.started_at AS startedAt,
27393
+ a.attributes AS attributes,
27394
+ a.root_session_id AS rootSessionId
27395
+ FROM audit_events a
27396
+ WHERE a.event_type = 'capture_status'
27397
+ AND a.source_tool = ?
27398
+ AND a.started_at >= ?
27399
+ ORDER BY a.started_at DESC, a.id DESC
27400
+ LIMIT ?`
27401
+ );
27402
+ }
27403
+ db;
27404
+ recentStmt;
27405
+ /**
27406
+ * Every document that reported for a site, in registry order by site, from
27407
+ * the last `CAPTURE_STATUS_RECENCY_MS`.
27408
+ *
27409
+ * SEVERAL per site, not one: a browser is many documents and each reports
27410
+ * for itself, so one row per site is a choice about which of them a user
27411
+ * sees — and the newest is the wrong one, since a healthy tab writing a
27412
+ * fresh report would hide a drifting tab's verdict, which is the whole
27413
+ * reason these rows exist. The pick WITHIN a document is made here (the
27414
+ * unchanged `pickReportedCaptureStatus`, over that document's own rows);
27415
+ * choosing between documents belongs where the state semantics live, and
27416
+ * that is `reportedCaptureDocumentForSite` in `@akasecurity/detections` —
27417
+ * this package may not import it.
27418
+ *
27419
+ * `now` is a required argument rather than a `Date.now()` read, so a caller
27420
+ * that already holds a render instant passes THAT one and a test can drive
27421
+ * the window without moving the wall clock.
27422
+ *
27423
+ * A site whose reports have all aged out contributes nothing, so it derives
27424
+ * to `unreported`. That is the point: nothing but the browser extension ever
27425
+ * writes these rows, so an uninstalled extension's last verdict would
27426
+ * otherwise stand as a live claim for ever with no later report able to
27427
+ * clear it.
27428
+ */
27429
+ latest(now) {
27430
+ const since = now - CAPTURE_STATUS_RECENCY_MS;
27431
+ const documents = [];
27432
+ for (const tool of WebSourceTool.options) {
27433
+ const rows = /* @__PURE__ */ new Map();
27434
+ const lastWord = /* @__PURE__ */ new Map();
27435
+ for (const row of allRows(this.recentStmt, [
27436
+ tool,
27437
+ since,
27438
+ STATUS_LOOKBACK_ROWS
27439
+ ])) {
27440
+ const status = fromCaptureStatusAttributes(parseJsonObject(row.attributes));
27441
+ if (status === null) continue;
27442
+ const record2 = { tool, observedAt: epochMillisToIso(row.startedAt), status };
27443
+ const group = rows.get(row.rootSessionId);
27444
+ if (group === void 0) {
27445
+ rows.set(row.rootSessionId, [record2]);
27446
+ lastWord.set(row.rootSessionId, { at: record2.observedAt, closed: status.closed });
27447
+ } else {
27448
+ group.push(record2);
27449
+ }
27450
+ }
27451
+ for (const [root, candidates] of rows) {
27452
+ const picked = pickReportedCaptureStatus(candidates);
27453
+ const last = lastWord.get(root);
27454
+ if (picked === void 0 || last === void 0) continue;
27455
+ documents.push({
27456
+ ...picked,
27457
+ ...root === null ? {} : { rootSessionId: root },
27458
+ lastReportAt: last.at,
27459
+ closed: last.closed
27460
+ });
27461
+ }
27462
+ }
27463
+ return documents;
27464
+ }
27465
+ };
27466
+
27198
27467
  // ../../packages/persistence/src/repositories/classified-data.ts
27199
27468
  var SqliteClassifiedDataRepository = class {
27200
27469
  constructor(db) {
@@ -32747,6 +33016,7 @@ function openAndInitialize(file2, base, skipTags) {
32747
33016
  activity: new SqliteActivityRepository(db),
32748
33017
  sourceProject: new SqliteSourceProjectRepository(db),
32749
33018
  auditEvents: new SqliteAuditEventsRepository(db),
33019
+ captureStatus: new SqliteCaptureStatusRepository(db),
32750
33020
  classifiedData: new SqliteClassifiedDataRepository(db),
32751
33021
  inspectionDefinitions: new SqliteInspectionDefinitionsRepository(db),
32752
33022
  inspectionFindings: new SqliteInspectionFindingsRepository(db),
@@ -32787,6 +33057,7 @@ function openLocalDatabase(dir, options = {}) {
32787
33057
  activity,
32788
33058
  sourceProject,
32789
33059
  auditEvents,
33060
+ captureStatus,
32790
33061
  classifiedData,
32791
33062
  inspectionDefinitions,
32792
33063
  inspectionFindings,
@@ -33004,6 +33275,7 @@ function openLocalDatabase(dir, options = {}) {
33004
33275
  activity,
33005
33276
  sourceProject,
33006
33277
  auditEvents,
33278
+ captureStatus,
33007
33279
  classifiedData,
33008
33280
  inspectionDefinitions,
33009
33281
  inspectionFindings,
@@ -33045,11 +33317,6 @@ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
33045
33317
  // ../../packages/persistence/src/forward-health.ts
33046
33318
  import { readFileSync as readFileSync7 } from "fs";
33047
33319
  import { join as join9 } from "path";
33048
- var FAILURES = /* @__PURE__ */ new Set([
33049
- "unauthorized",
33050
- "forbidden",
33051
- "unreachable"
33052
- ]);
33053
33320
  var BREAKER_COOLDOWN_MS = 3e4;
33054
33321
  function parseForwardHealth(raw, nowMs) {
33055
33322
  try {
@@ -33058,7 +33325,8 @@ function parseForwardHealth(raw, nowMs) {
33058
33325
  const record2 = parsed2;
33059
33326
  const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33060
33327
  const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33061
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33328
+ const parsedFailure = ControlPlaneFailure.safeParse(record2.lastFailure);
33329
+ const lastFailure = parsedFailure.success ? parsedFailure.data : null;
33062
33330
  return { consecutiveFailures: failures, openedAtMs, lastFailure };
33063
33331
  } catch {
33064
33332
  return null;
@@ -33201,6 +33469,12 @@ var RemoteRequestInvalid = class extends Error {
33201
33469
  }
33202
33470
  cause;
33203
33471
  };
33472
+ var RemoteEndpointRefused = class extends Error {
33473
+ constructor(endpoint) {
33474
+ super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
33475
+ this.name = "RemoteEndpointRefused";
33476
+ }
33477
+ };
33204
33478
  var RemoteResponseInvalid = class extends Error {
33205
33479
  constructor(route, detail) {
33206
33480
  super(`control plane answered ${route} with ${detail}`);
@@ -33353,14 +33627,15 @@ function parsed(schema, body, route) {
33353
33627
  }
33354
33628
  return result.data;
33355
33629
  }
33356
- function withoutTrailingSlashes(endpoint) {
33630
+ function resolveBaseUrl(endpoint) {
33631
+ if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
33357
33632
  let end = endpoint.length;
33358
33633
  while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
33359
33634
  return endpoint.slice(0, end);
33360
33635
  }
33361
33636
  var SLASH2 = "/".charCodeAt(0);
33362
33637
  function createRemoteClient(options) {
33363
- const base = withoutTrailingSlashes(options.endpoint);
33638
+ const base = resolveBaseUrl(options.endpoint);
33364
33639
  const url2 = (route) => `${base}${route}`;
33365
33640
  const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
33366
33641
  const sendOne = async (event) => {
@@ -34237,6 +34512,56 @@ var CONFIG_POSTURE_RULES = [
34237
34512
  }
34238
34513
  ];
34239
34514
 
34515
+ // ../../packages/detections/src/posture/web-capture-posture.ts
34516
+ var RULE_VERSION2 = "1";
34517
+ var DRIFT_MIN_PARSE_FAILURES = 2;
34518
+ var WEB_CAPTURE_DRIFT_STATES = /* @__PURE__ */ new Set([
34519
+ "blind",
34520
+ "degraded"
34521
+ ]);
34522
+ var WEB_CAPTURE_DRIFT_RULE = {
34523
+ ruleId: "web-capture-drift",
34524
+ version: RULE_VERSION2,
34525
+ name: "Web chat capture is not reading the site",
34526
+ category: "config",
34527
+ severity: "medium",
34528
+ definition: JSON.stringify({
34529
+ kind: "web-capture-drift",
34530
+ states: [...WEB_CAPTURE_DRIFT_STATES],
34531
+ minParseFailures: DRIFT_MIN_PARSE_FAILURES
34532
+ })
34533
+ };
34534
+ var STATIC_COPY = {
34535
+ active: { headline: "turns are being observed on this site" },
34536
+ unreported: {
34537
+ // Says "recently" rather than "yet": the store read is bounded to
34538
+ // CAPTURE_STATUS_RECENCY_MS, so this state covers a site nothing has ever
34539
+ // reported for AND one whose last report has aged out. The two are the
34540
+ // same fact to a reader — nobody has confirmed anything lately — and the
34541
+ // copy may not claim the stronger of them.
34542
+ headline: `no report in the last ${String(CAPTURE_STATUS_RECENCY_DAYS)} days \u2014 open the site in Chrome with the extension loaded`
34543
+ },
34544
+ standby: {
34545
+ headline: "this build declares no endpoints for the site, so nothing is observed yet"
34546
+ },
34547
+ unpatched: {
34548
+ // Says what the flags say and no more. `patched` is false both for a tap
34549
+ // that installed and hooked neither transport and for one that never ran
34550
+ // at all — a page reports the same status either way, so the copy may not
34551
+ // assert one of them.
34552
+ headline: "the page tap captured neither fetch nor XHR \u2014 it may not have installed; reload the extension at chrome://extensions"
34553
+ },
34554
+ idle: { headline: "watching; no turn has been observed yet" },
34555
+ blind: {
34556
+ headline: "messages were sent in the page that the network capture never saw",
34557
+ 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."
34558
+ },
34559
+ degraded: {
34560
+ headline: "the site's payloads no longer carry the fields the extension reads",
34561
+ 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."
34562
+ }
34563
+ };
34564
+
34240
34565
  // ../../packages/detections/src/security/redos-probe.ts
34241
34566
  var BUDGET_MS = 100;
34242
34567
  var EXPONENTIAL_UNITS = [
@@ -34392,7 +34717,16 @@ function rebuildCapture(row) {
34392
34717
  const metadata = {
34393
34718
  ...rootSessionId === null ? {} : { sessionId: rootSessionId },
34394
34719
  ...filePath === void 0 ? {} : { filePath },
34395
- ...pick2(attributes, { repo: "repo", toolName: "tool_name", model: "model" }),
34720
+ ...pick2(attributes, {
34721
+ repo: "repo",
34722
+ toolName: "tool_name",
34723
+ model: "model",
34724
+ // The join back to the llm_call leaf for the same web-chat turn.
34725
+ // Stripping these would forward a response capture the deployment can
34726
+ // never correlate to the llm_call leaf describing the same turn.
34727
+ messageId: "message_id",
34728
+ conversationId: "conversation_id"
34729
+ }),
34396
34730
  // The two constrained strings, kept only if they satisfy the wire.
34397
34731
  ...withField("traceId", keep(stringOrUndefined(attributes.trace_id), TRACE_ID)),
34398
34732
  ...withField(
@@ -35039,6 +35373,9 @@ import { join as join27 } from "path";
35039
35373
 
35040
35374
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
35041
35375
  import { rename as rename2 } from "fs/promises";
35376
+ var IMMEDIATE_RETRIES = 8;
35377
+ var TIMED_RETRIES = 4;
35378
+ var ATTEMPTS = 1 + IMMEDIATE_RETRIES + TIMED_RETRIES;
35042
35379
 
35043
35380
  // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
35044
35381
  var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;