@akasecurity/ai-tc-codex 0.9.7 → 0.9.8

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.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH = "/";
53
+ var SLASH2 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH).filter(Boolean);
425
+ const slices = path.split(SLASH2).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH) + SLASH,
429
+ slices.join(SLASH2) + SLASH2,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH).filter(Boolean);
445
+ slices = path.split(SLASH2).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH) + SLASH,
452
+ slices.join(SLASH2) + SLASH2,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,13 +492,12 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync5 } from "fs";
496
- import { join as join8 } from "path";
495
+ import { existsSync as existsSync6 } from "fs";
496
+ import { join as join10 } from "path";
497
497
 
498
- // ../../packages/persistence/src/database.ts
499
- import { randomUUID as randomUUID10 } from "crypto";
500
- import { join as join2, sep } from "path";
501
- import { DatabaseSync } from "node:sqlite";
498
+ // ../../packages/persistence/src/control-plane-credential.ts
499
+ import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync2, statSync } from "fs";
500
+ import { join } from "path";
502
501
 
503
502
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
504
503
  var SQLITE_MIGRATIONS = [
@@ -16205,6 +16204,125 @@ var ConfigScanRecord = external_exports.object({
16205
16204
  findings: external_exports.array(ConfigPostureFindingInput).optional()
16206
16205
  });
16207
16206
 
16207
+ // ../../packages/schema/src/zod/control-plane.ts
16208
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
16209
+ var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
16210
+ var AttachedCredential = external_exports.object({
16211
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
16212
+ // The control-plane endpoint this credential was minted against.
16213
+ endpoint: external_exports.string().min(1),
16214
+ // The bearer credential itself. Never logged, never rendered — status
16215
+ // surfaces show `keyPrefix` and nothing else.
16216
+ apiKey: external_exports.string().min(1),
16217
+ // First few characters of the key, safe to display so a user can match the
16218
+ // credential against their organization's key list.
16219
+ keyPrefix: external_exports.string().min(1).max(16).optional(),
16220
+ mintedAt: external_exports.iso.datetime().optional()
16221
+ });
16222
+ var MAX_DATE_MS = 253402300799999;
16223
+ var MAX_INT4 = 2147483647;
16224
+ var StorePosturePack = external_exports.object({
16225
+ packId: external_exports.string().min(1),
16226
+ // 'namespace/packId'
16227
+ version: external_exports.string().min(1),
16228
+ enabled: external_exports.boolean(),
16229
+ // Stringified pass-through of the local store's `installed_packs.updated_at`
16230
+ // — the column format is store-version-dependent (epoch millis vs ISO), so
16231
+ // the wire shape assumes neither.
16232
+ updatedAt: external_exports.string().nullable()
16233
+ }).meta({ id: "StorePosturePack" });
16234
+ var StorePosturePolicyCounts = external_exports.object({
16235
+ total: external_exports.number().int().min(0),
16236
+ disabled: external_exports.number().int().min(0),
16237
+ // Exhaustive per-action map; the builder pre-fills every action with 0.
16238
+ //
16239
+ // Spelled out member-by-member rather than `z.record(ActionTaken, …)`. Zod
16240
+ // enforces exhaustiveness either way, but z.record emits `propertyNames` +
16241
+ // `additionalProperties` into a generated schema document, and a type
16242
+ // generator renders THAT with every key optional — a sender built against
16243
+ // the generated type would typecheck and still be rejected at runtime. An
16244
+ // explicit object emits `properties` + `required`, so generated types
16245
+ // demand all five.
16246
+ //
16247
+ // `satisfies Record<ActionTaken, …>` keeps the link to the enum: adding an
16248
+ // ActionTaken member is a COMPILE error here instead of silent drift.
16249
+ // `.strict()` is load-bearing — it rejects an unknown action key, which a
16250
+ // bare object would silently STRIP, accepting a miscounted map as valid.
16251
+ byAction: external_exports.object({
16252
+ warn: external_exports.number().int().min(0),
16253
+ redact: external_exports.number().int().min(0),
16254
+ block: external_exports.number().int().min(0),
16255
+ allow: external_exports.number().int().min(0),
16256
+ log: external_exports.number().int().min(0)
16257
+ }).strict()
16258
+ }).meta({ id: "StorePosturePolicyCounts" });
16259
+ var StorePosturePlugin = external_exports.object({
16260
+ /** Package name of the reporting plugin. */
16261
+ package: external_exports.string().min(1).max(200),
16262
+ version: external_exports.string().min(1).max(64),
16263
+ /** Version of the bundled core, when the build records one separately. */
16264
+ ossVersion: external_exports.string().max(64).nullable(),
16265
+ /**
16266
+ * `version` of the policy bundle this machine last fetched. Bounded at 200
16267
+ * rather than the 64 a bare sha256 hex digest needs today, so a later
16268
+ * format with an algorithm prefix does not start rejecting the channel.
16269
+ */
16270
+ policyBundleVersion: external_exports.string().max(200).nullable(),
16271
+ /** Epoch millis, on the CLIENT clock, of that fetch. */
16272
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
16273
+ }).meta({ id: "StorePosturePlugin" });
16274
+ var StorePostureSnapshot = external_exports.object({
16275
+ deviceId: external_exports.guid(),
16276
+ hostname: external_exports.string().min(1).max(253),
16277
+ // Epoch millis on the CLIENT clock. Bounded by what a receiving store
16278
+ // accepts (see MAX_DATE_MS), not by what a JavaScript Date can hold.
16279
+ capturedAt: external_exports.number().int().min(0).max(MAX_DATE_MS),
16280
+ // False is a measurement, not an error state: "no local store exists on
16281
+ // this machine".
16282
+ storePresent: external_exports.boolean(),
16283
+ schemaVersion: external_exports.number().int().min(0).max(MAX_INT4).nullable(),
16284
+ // PRAGMA user_version
16285
+ findingsTotal: external_exports.number().int().min(0).max(MAX_INT4),
16286
+ // Epoch millis, bounded like `capturedAt` — see MAX_DATE_MS on what that
16287
+ // bound does and does not do. Worth stating for these two specifically:
16288
+ // they are read from the local store's own ROWS rather than from this
16289
+ // machine's clock, so a damaged or hand-edited store is enough to produce
16290
+ // an out-of-range value with no clock skew involved.
16291
+ findingsFirstAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16292
+ findingsLastAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16293
+ packs: external_exports.array(StorePosturePack).max(500),
16294
+ policyCounts: StorePosturePolicyCounts,
16295
+ // OPTIONAL, not nullable: a reporter that predates this member keeps
16296
+ // getting its 200 without a payload change.
16297
+ plugin: StorePosturePlugin.optional()
16298
+ }).meta({ id: "StorePostureSnapshot" });
16299
+ var CAPTURE_VERSION_PREFIX = "capture/";
16300
+ var RecordAuditEventRequest = AuditEventInput.extend({
16301
+ inspections: external_exports.array(ToolCallInspection).default([])
16302
+ }).refine((v) => v.inspections.every((i) => !i.ruleVersion.startsWith(CAPTURE_VERSION_PREFIX)), {
16303
+ message: `inspections[].ruleVersion must not start with \`${CAPTURE_VERSION_PREFIX}\` \u2014 that namespace is reserved for capture definitions the control plane mints itself`,
16304
+ path: ["inspections"]
16305
+ }).meta({ id: "RecordAuditEventRequest" });
16306
+ var IngestAck = external_exports.object({
16307
+ accepted: external_exports.number().int().nonnegative(),
16308
+ duplicates: external_exports.number().int().nonnegative()
16309
+ });
16310
+ var PRINTABLE = /^[^\p{Cc}\p{Cf}]*$/u;
16311
+ var printable = (max) => external_exports.string().max(max).regex(PRINTABLE, "must not contain control characters");
16312
+ var PluginWhoami = external_exports.object({
16313
+ tenantName: printable(200),
16314
+ userEmail: printable(320),
16315
+ role: printable(64),
16316
+ keyKind: printable(64),
16317
+ serverTime: printable(64)
16318
+ });
16319
+ var ControlPlaneErrorBody = external_exports.object({
16320
+ error: external_exports.object({
16321
+ code: external_exports.string().optional(),
16322
+ message: external_exports.string().optional()
16323
+ }).optional()
16324
+ });
16325
+
16208
16326
  // ../../packages/schema/src/zod/registry.ts
16209
16327
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
16210
16328
  var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -16507,15 +16625,15 @@ function summaryToDetectionListItem(s) {
16507
16625
  }
16508
16626
  function rowToDetectionDetail(row, findingsLast30d, update) {
16509
16627
  const rules = row.rules.flatMap((r) => {
16510
- const parsed = Matcher.safeParse(r.matcher);
16511
- if (!parsed.success) return [];
16628
+ const parsed2 = Matcher.safeParse(r.matcher);
16629
+ if (!parsed2.success) return [];
16512
16630
  return [
16513
16631
  {
16514
16632
  id: r.id,
16515
16633
  name: r.name,
16516
16634
  category: r.category,
16517
16635
  severity: r.severity,
16518
- matcher: parsed.data
16636
+ matcher: parsed2.data
16519
16637
  }
16520
16638
  ];
16521
16639
  });
@@ -17161,8 +17279,8 @@ function toApiAction(dbVal) {
17161
17279
  }
17162
17280
  function toApiCategory(dbVal) {
17163
17281
  if (dbVal === "code_context") return "source_code";
17164
- const parsed = FindingCategory.safeParse(dbVal);
17165
- return parsed.success ? parsed.data : "custom";
17282
+ const parsed2 = FindingCategory.safeParse(dbVal);
17283
+ return parsed2.success ? parsed2.data : "custom";
17166
17284
  }
17167
17285
  function toApiProvider(sourceTool) {
17168
17286
  return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
@@ -17792,6 +17910,9 @@ var WorkspaceSettings = external_exports.object({
17792
17910
  function defaultWorkspaceSettings() {
17793
17911
  return WorkspaceSettings.parse({});
17794
17912
  }
17913
+ function isAttached(settings) {
17914
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
17915
+ }
17795
17916
  function toInventoryRow(input, id, now) {
17796
17917
  return {
17797
17918
  id,
@@ -18059,8 +18180,8 @@ function builtinPolicyIsReversible(id) {
18059
18180
  return BUILTIN_POLICY_SPECS[id].reversible;
18060
18181
  }
18061
18182
  function policyIdIsReversible(policyId) {
18062
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18063
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18183
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18184
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18064
18185
  return builtinPolicyIsReversible(id);
18065
18186
  }
18066
18187
  var DEFAULT_ACTIONS = Object.fromEntries(
@@ -18071,8 +18192,8 @@ var BUILTIN_POLICIES = Object.fromEntries(
18071
18192
  );
18072
18193
  var DEFAULT_PACK_POLICY_ID = "monitor";
18073
18194
  function policyIdToAction(policyId) {
18074
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18075
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18195
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18196
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18076
18197
  return BUILTIN_POLICIES[id].action;
18077
18198
  }
18078
18199
  var UsedByItem = external_exports.object({
@@ -18515,53 +18636,6 @@ function reviewSeverityRank(reasons) {
18515
18636
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
18516
18637
  }
18517
18638
 
18518
- // ../../packages/persistence/src/ids.ts
18519
- import { createHash } from "crypto";
18520
- function sha256Hex(input) {
18521
- return createHash("sha256").update(input).digest("hex");
18522
- }
18523
- function inventoryId(objectType, identityKey) {
18524
- return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18525
- }
18526
- function sourceProjectId(url2) {
18527
- return sha256Hex(canonicalIdentity(["source_project", url2]));
18528
- }
18529
- function classifiedDataId(cls) {
18530
- return sha256Hex(canonicalIdentity(["classified_data", cls]));
18531
- }
18532
- function inspectionDefinitionId(ruleId, version2) {
18533
- return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18534
- }
18535
- function llmCallId(sessionId, messageId) {
18536
- return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18537
- }
18538
- function toolCallId(sessionId, toolUseId) {
18539
- return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18540
- }
18541
- function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18542
- return sha256Hex(
18543
- canonicalIdentity([
18544
- "inspection_finding",
18545
- auditEventId,
18546
- ruleId,
18547
- String(spanStart),
18548
- String(spanEnd)
18549
- ])
18550
- );
18551
- }
18552
- var NO_SESSION = "no_session";
18553
- var NO_PATH = "no_path";
18554
- function captureId(sessionId, contentHash, filePath = null) {
18555
- return sha256Hex(
18556
- canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18557
- );
18558
- }
18559
-
18560
- // ../../packages/persistence/src/internal/snapshot.ts
18561
- import { randomUUID } from "crypto";
18562
- import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
18563
- import { basename, dirname, join } from "path";
18564
-
18565
18639
  // ../../packages/persistence/src/paths.ts
18566
18640
  import {
18567
18641
  chmodSync,
@@ -18609,8 +18683,181 @@ function tightenFile(file2) {
18609
18683
  function tightenPerms(file2) {
18610
18684
  for (const path of [file2, ...dbSidecars(file2)]) chmodBestEffort(path, DATA_FILE_MODE);
18611
18685
  }
18686
+ function writeExclusiveOwnerOnlySync(file2, data) {
18687
+ writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
18688
+ }
18689
+ function writeOwnerOnlyFileSync(file2, data) {
18690
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
18691
+ try {
18692
+ rmSync(tmp, { force: true });
18693
+ } catch {
18694
+ }
18695
+ try {
18696
+ writeExclusiveOwnerOnlySync(tmp, data);
18697
+ renameSync(tmp, file2);
18698
+ } finally {
18699
+ try {
18700
+ rmSync(tmp, { force: true });
18701
+ } catch {
18702
+ }
18703
+ }
18704
+ tightenFile(file2);
18705
+ }
18706
+ function createOwnerOnlyFileSync(file2, data) {
18707
+ const tmp = `${file2}.${String(process.pid)}.${String(threadId)}.new`;
18708
+ try {
18709
+ rmSync(tmp, { force: true });
18710
+ } catch {
18711
+ }
18712
+ let created;
18713
+ try {
18714
+ writeExclusiveOwnerOnlySync(tmp, data);
18715
+ created = publishByLink(tmp, file2, data);
18716
+ } finally {
18717
+ try {
18718
+ rmSync(tmp, { force: true });
18719
+ } catch {
18720
+ }
18721
+ }
18722
+ if (created) tightenFile(file2);
18723
+ return created;
18724
+ }
18725
+ var LINK_UNSUPPORTED = /* @__PURE__ */ new Set(["EPERM", "ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EINVAL"]);
18726
+ function publishByLink(tmp, file2, data) {
18727
+ try {
18728
+ linkSync(tmp, file2);
18729
+ return true;
18730
+ } catch (err) {
18731
+ const code = err.code;
18732
+ if (code === "EEXIST") return false;
18733
+ if (!LINK_UNSUPPORTED.has(code ?? "")) throw err;
18734
+ }
18735
+ try {
18736
+ writeExclusiveOwnerOnlySync(file2, data);
18737
+ return true;
18738
+ } catch (err) {
18739
+ if (err.code === "EEXIST") return false;
18740
+ throw err;
18741
+ }
18742
+ }
18743
+
18744
+ // ../../packages/persistence/src/control-plane-credential.ts
18745
+ function controlPlaneCredentialPath(settingsDir2) {
18746
+ return join(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
18747
+ }
18748
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
18749
+ function isSafeEndpoint(endpoint) {
18750
+ let parsed2;
18751
+ try {
18752
+ parsed2 = new URL(endpoint);
18753
+ } catch {
18754
+ return false;
18755
+ }
18756
+ if (parsed2.protocol === "https:") return true;
18757
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
18758
+ }
18759
+ function repairOrRefuseMode(file2) {
18760
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
18761
+ if (link === void 0) return "absent";
18762
+ if (link.isSymbolicLink()) return "untrusted";
18763
+ const stat = statSync(file2, { throwIfNoEntry: false });
18764
+ if (stat === void 0) return "absent";
18765
+ const uid = process.getuid?.();
18766
+ if (uid !== void 0 && stat.uid !== uid) return "untrusted";
18767
+ if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
18768
+ try {
18769
+ chmodSync2(file2, DATA_FILE_MODE);
18770
+ } catch {
18771
+ return "untrusted";
18772
+ }
18773
+ }
18774
+ return "ok";
18775
+ }
18776
+ function readControlPlaneCredentialState(settingsDir2, connection) {
18777
+ const file2 = controlPlaneCredentialPath(settingsDir2);
18778
+ let raw;
18779
+ const gate = repairOrRefuseMode(file2);
18780
+ if (gate === "absent") return { usable: false, reason: "absent" };
18781
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
18782
+ try {
18783
+ raw = readFileSync(file2, "utf8");
18784
+ } catch (err) {
18785
+ const code = err.code;
18786
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
18787
+ }
18788
+ let parsed2;
18789
+ try {
18790
+ parsed2 = JSON.parse(raw);
18791
+ } catch {
18792
+ return { usable: false, reason: "malformed" };
18793
+ }
18794
+ const result = AttachedCredential.safeParse(parsed2);
18795
+ if (!result.success) return { usable: false, reason: "malformed" };
18796
+ if (!isSafeEndpoint(result.data.endpoint)) {
18797
+ return { usable: false, reason: "unsafe-endpoint" };
18798
+ }
18799
+ if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
18800
+ return {
18801
+ usable: false,
18802
+ reason: "endpoint-mismatch",
18803
+ credentialEndpoint: result.data.endpoint,
18804
+ settingsEndpoint: connection.endpoint
18805
+ };
18806
+ }
18807
+ return { usable: true, credential: result.data };
18808
+ }
18809
+
18810
+ // ../../packages/persistence/src/database.ts
18811
+ import { randomUUID as randomUUID10 } from "crypto";
18812
+ import { join as join3, sep } from "path";
18813
+ import { DatabaseSync } from "node:sqlite";
18814
+
18815
+ // ../../packages/persistence/src/ids.ts
18816
+ import { createHash } from "crypto";
18817
+ function sha256Hex(input) {
18818
+ return createHash("sha256").update(input).digest("hex");
18819
+ }
18820
+ function inventoryId(objectType, identityKey) {
18821
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18822
+ }
18823
+ function sourceProjectId(url2) {
18824
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
18825
+ }
18826
+ function classifiedDataId(cls) {
18827
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
18828
+ }
18829
+ function inspectionDefinitionId(ruleId, version2) {
18830
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18831
+ }
18832
+ function llmCallId(sessionId, messageId) {
18833
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18834
+ }
18835
+ function toolCallId(sessionId, toolUseId) {
18836
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18837
+ }
18838
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18839
+ return sha256Hex(
18840
+ canonicalIdentity([
18841
+ "inspection_finding",
18842
+ auditEventId,
18843
+ ruleId,
18844
+ String(spanStart),
18845
+ String(spanEnd)
18846
+ ])
18847
+ );
18848
+ }
18849
+ var NO_SESSION = "no_session";
18850
+ var NO_PATH = "no_path";
18851
+ function captureId(sessionId, contentHash, filePath = null) {
18852
+ return sha256Hex(
18853
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18854
+ );
18855
+ }
18612
18856
 
18613
18857
  // ../../packages/persistence/src/internal/snapshot.ts
18858
+ import { randomUUID } from "crypto";
18859
+ import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
18860
+ import { basename, dirname, join as join2 } from "path";
18614
18861
  function backupPath(file2, tag) {
18615
18862
  return `${file2}.${tag}.${String(Date.now())}.${randomUUID().slice(0, 8)}.bak`;
18616
18863
  }
@@ -18620,15 +18867,15 @@ var STAGED_NAME_SUFFIX = `.bak${SNAPSHOT_STAGING_SUFFIX}`;
18620
18867
  var SNAPSHOT_STAGING_COPY = "copy";
18621
18868
  function createSnapshotStaging(backup) {
18622
18869
  const stage = `${backup}${SNAPSHOT_STAGING_SUFFIX}`;
18623
- rmSync2(stage, { recursive: true, force: true });
18870
+ rmSync3(stage, { recursive: true, force: true });
18624
18871
  mkdirOwnerOnlySync(stage);
18625
18872
  tightenDir(stage);
18626
- return { stage, copy: join(stage, SNAPSHOT_STAGING_COPY) };
18873
+ return { stage, copy: join2(stage, SNAPSHOT_STAGING_COPY) };
18627
18874
  }
18628
18875
  function idleMs(entry) {
18629
- for (const candidate of [join(entry, SNAPSHOT_STAGING_COPY), entry]) {
18876
+ for (const candidate of [join2(entry, SNAPSHOT_STAGING_COPY), entry]) {
18630
18877
  try {
18631
- return Date.now() - statSync(candidate).mtimeMs;
18878
+ return Date.now() - statSync2(candidate).mtimeMs;
18632
18879
  } catch {
18633
18880
  }
18634
18881
  }
@@ -18645,11 +18892,11 @@ function reapStalePartials(file2) {
18645
18892
  }
18646
18893
  for (const name of entries) {
18647
18894
  if (!name.startsWith(prefix) || !name.endsWith(STAGED_NAME_SUFFIX)) continue;
18648
- const staging = join(dir, name);
18895
+ const staging = join2(dir, name);
18649
18896
  try {
18650
18897
  const idle = idleMs(staging);
18651
18898
  if (idle !== null && idle > STALE_PARTIAL_MS) {
18652
- rmSync2(staging, { recursive: true, force: true });
18899
+ rmSync3(staging, { recursive: true, force: true });
18653
18900
  }
18654
18901
  } catch {
18655
18902
  }
@@ -18663,13 +18910,13 @@ function snapshotStore(db, backup) {
18663
18910
  renameSync2(copy, backup);
18664
18911
  } catch (error51) {
18665
18912
  try {
18666
- rmSync2(stage, { recursive: true, force: true });
18913
+ rmSync3(stage, { recursive: true, force: true });
18667
18914
  } catch {
18668
18915
  }
18669
18916
  throw error51;
18670
18917
  }
18671
18918
  try {
18672
- rmSync2(stage, { recursive: true, force: true });
18919
+ rmSync3(stage, { recursive: true, force: true });
18673
18920
  } catch {
18674
18921
  }
18675
18922
  }
@@ -18684,7 +18931,7 @@ function moveStoreAside(file2, backup) {
18684
18931
  renameSync2(sidecar, moved);
18685
18932
  undo.push([moved, sidecar]);
18686
18933
  } catch {
18687
- rmSync2(sidecar, { force: true });
18934
+ rmSync3(sidecar, { force: true });
18688
18935
  }
18689
18936
  }
18690
18937
  } catch (error51) {
@@ -18700,14 +18947,14 @@ function moveStoreAside(file2, backup) {
18700
18947
  }
18701
18948
  function discardStore(file2, backup) {
18702
18949
  try {
18703
- rmSync2(file2, { force: true });
18950
+ rmSync3(file2, { force: true });
18704
18951
  for (const sidecar of dbSidecars(file2)) {
18705
- rmSync2(sidecar, { force: true });
18952
+ rmSync3(sidecar, { force: true });
18706
18953
  }
18707
18954
  } catch (error51) {
18708
18955
  if (existsSync(file2)) {
18709
18956
  try {
18710
- rmSync2(backup, { force: true });
18957
+ rmSync3(backup, { force: true });
18711
18958
  } catch {
18712
18959
  }
18713
18960
  }
@@ -18939,10 +19186,31 @@ function applyMigrations(db, file2) {
18939
19186
  if (drained) applyLegacyDropMigration(db, file2);
18940
19187
  }
18941
19188
  }
19189
+ function readLegacyTables(db) {
19190
+ let holdsRows = false;
19191
+ const marks = [];
19192
+ for (const table of ["events", "findings"]) {
19193
+ try {
19194
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
19195
+ if (row === void 0) {
19196
+ holdsRows = true;
19197
+ marks.push(`${table}:unreadable`);
19198
+ continue;
19199
+ }
19200
+ if (row.n > 0) holdsRows = true;
19201
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
19202
+ } catch {
19203
+ holdsRows = true;
19204
+ marks.push(`${table}:unreadable`);
19205
+ }
19206
+ }
19207
+ return { holdsRows, mark: marks.join("|") };
19208
+ }
18942
19209
  function applyLegacyDropMigration(db, file2) {
18943
19210
  const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
18944
19211
  if (!migration) return;
18945
- if (file2) {
19212
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
19213
+ if (file2 !== void 0 && before?.holdsRows === true) {
18946
19214
  try {
18947
19215
  backupBeforeLegacyDrop(db, file2);
18948
19216
  } catch (error51) {
@@ -18956,6 +19224,12 @@ function applyLegacyDropMigration(db, file2) {
18956
19224
  () => {
18957
19225
  const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
18958
19226
  if (alreadyDropped) return;
19227
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
19228
+ akaWarn(
19229
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
19230
+ );
19231
+ return;
19232
+ }
18959
19233
  for (const statement of splitStatements(migration.sql)) {
18960
19234
  db.exec(statement);
18961
19235
  }
@@ -19310,8 +19584,8 @@ function safeJson(s, fallback) {
19310
19584
  function parseJsonObject(s) {
19311
19585
  if (s == null) return void 0;
19312
19586
  try {
19313
- const parsed = JSON.parse(s);
19314
- if (typeof parsed === "object" && parsed !== null) return parsed;
19587
+ const parsed2 = JSON.parse(s);
19588
+ if (typeof parsed2 === "object" && parsed2 !== null) return parsed2;
19315
19589
  } catch {
19316
19590
  }
19317
19591
  return void 0;
@@ -19322,16 +19596,16 @@ function encodeKeysetCursor(payload) {
19322
19596
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
19323
19597
  }
19324
19598
  function decodeKeysetCursor(cursor) {
19325
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19326
- if (parsed !== void 0 && "startedAtMs" in parsed && "id" in parsed && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19599
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19600
+ if (parsed2 !== void 0 && "startedAtMs" in parsed2 && "id" in parsed2 && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19327
19601
  // resumes from is epoch millis, and a payload carrying ±Infinity or a
19328
19602
  // fraction binds cleanly rather than failing — returning an EMPTY page with
19329
19603
  // a null cursor, which a caller reads as "end of list". That is the one
19330
19604
  // outcome a cursor that does not decode must never produce, since the
19331
19605
  // documented behaviour above is to restart from the top. (`1e999` is valid
19332
19606
  // JSON and parses to Infinity; a bare `NaN` is not, so it cannot arrive.)
19333
- Number.isInteger(parsed.startedAtMs) && typeof parsed.id === "string") {
19334
- return parsed;
19607
+ Number.isInteger(parsed2.startedAtMs) && typeof parsed2.id === "string") {
19608
+ return parsed2;
19335
19609
  }
19336
19610
  return null;
19337
19611
  }
@@ -19396,18 +19670,18 @@ var DB_EVENT_TYPE_TO_KIND = {
19396
19670
  };
19397
19671
  function safeParseStringArray(raw) {
19398
19672
  if (!raw) return [];
19399
- const parsed = safeJson(raw, null);
19400
- return Array.isArray(parsed) ? parsed : [];
19673
+ const parsed2 = safeJson(raw, null);
19674
+ return Array.isArray(parsed2) ? parsed2 : [];
19401
19675
  }
19402
19676
  var DEFAULT_HARNESS = HARNESS.ClaudeCode;
19403
19677
  function toHarness(raw) {
19404
- const parsed = Harness.safeParse(raw);
19405
- return parsed.success ? parsed.data : DEFAULT_HARNESS;
19678
+ const parsed2 = Harness.safeParse(raw);
19679
+ return parsed2.success ? parsed2.data : DEFAULT_HARNESS;
19406
19680
  }
19407
19681
  function resolveLifecycle(row, lastActivityMs, nowMs) {
19408
19682
  if (row.status) {
19409
- const parsed = SessionStatus.safeParse(row.status);
19410
- if (parsed.success) return { status: parsed.data, endedAtMs: row.ended_at };
19683
+ const parsed2 = SessionStatus.safeParse(row.status);
19684
+ if (parsed2.success) return { status: parsed2.data, endedAtMs: row.ended_at };
19411
19685
  }
19412
19686
  if (row.ended_at !== null) return { status: "completed", endedAtMs: row.ended_at };
19413
19687
  if (lastActivityMs >= nowMs - LIVE_ACTIVITY_WINDOW_MS) {
@@ -20366,9 +20640,9 @@ var SqliteDetectionsRepository = class {
20366
20640
  const ruleIds = /* @__PURE__ */ new Set();
20367
20641
  for (const r of rows) {
20368
20642
  if (intToBool(r.enabled)) active += 1;
20369
- const parsed = parseRules(r.rulesJson);
20370
- rules += parsed.length;
20371
- for (const rule of parsed) {
20643
+ const parsed2 = parseRules(r.rulesJson);
20644
+ rules += parsed2.length;
20645
+ for (const rule of parsed2) {
20372
20646
  if (typeof rule.id === "string") ruleIds.add(rule.id);
20373
20647
  }
20374
20648
  }
@@ -20902,12 +21176,12 @@ function encodeGroupCursor(group) {
20902
21176
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
20903
21177
  }
20904
21178
  function decodeGroupCursor(cursor) {
20905
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
20906
- if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.id === "string") {
21179
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21180
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.id === "string") {
20907
21181
  return {
20908
- severity: parsed.sev,
20909
- latestDetectedAt: parsed.t,
20910
- id: parsed.id
21182
+ severity: parsed2.sev,
21183
+ latestDetectedAt: parsed2.t,
21184
+ id: parsed2.id
20911
21185
  };
20912
21186
  }
20913
21187
  return null;
@@ -22041,16 +22315,16 @@ var SqliteInstalledPacksRepository = class {
22041
22315
  continue;
22042
22316
  }
22043
22317
  for (const entry of raw) {
22044
- const parsed = Rule.safeParse(entry);
22045
- if (parsed.success) {
22046
- out.rules.push(parsed.data);
22047
- out.ruleActions.set(parsed.data.id, action);
22048
- out.ruleVersions.set(parsed.data.id, row.version);
22049
- if (reversible) out.reversibleRules.add(parsed.data.id);
22050
- else out.reversibleRules.delete(parsed.data.id);
22318
+ const parsed2 = Rule.safeParse(entry);
22319
+ if (parsed2.success) {
22320
+ out.rules.push(parsed2.data);
22321
+ out.ruleActions.set(parsed2.data.id, action);
22322
+ out.ruleVersions.set(parsed2.data.id, row.version);
22323
+ if (reversible) out.reversibleRules.add(parsed2.data.id);
22324
+ else out.reversibleRules.delete(parsed2.data.id);
22051
22325
  } else {
22052
22326
  out.invalidRules += 1;
22053
- reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
22327
+ reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
22054
22328
  }
22055
22329
  }
22056
22330
  }
@@ -23440,15 +23714,15 @@ function encodeReuseCursor(payload) {
23440
23714
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
23441
23715
  }
23442
23716
  function decodeReuseCursor(cursor) {
23443
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23444
- if (parsed !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23717
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23718
+ if (parsed2 !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23445
23719
  // ±Infinity or a fraction binds cleanly and returns an EMPTY page with a
23446
23720
  // null cursor, which the caller reads as "end of list" — the one outcome a
23447
23721
  // malformed cursor must never produce, since restarting from the top is the
23448
23722
  // documented behaviour and the only recoverable one. (`1e999` is valid JSON
23449
23723
  // and parses to Infinity; a bare `NaN` is not, so it cannot arrive here.)
23450
- Number.isInteger(parsed.occurrences) && typeof parsed.pointerId === "string") {
23451
- return { occurrences: parsed.occurrences, pointerId: parsed.pointerId };
23724
+ Number.isInteger(parsed2.occurrences) && typeof parsed2.pointerId === "string") {
23725
+ return { occurrences: parsed2.occurrences, pointerId: parsed2.pointerId };
23452
23726
  }
23453
23727
  return null;
23454
23728
  }
@@ -25177,7 +25451,7 @@ function openAndInitialize(file2) {
25177
25451
  }
25178
25452
  function openLocalDatabase(dir) {
25179
25453
  ensureDataDirSync(dir);
25180
- const file2 = join2(dir, DB_FILENAME);
25454
+ const file2 = join3(dir, DB_FILENAME);
25181
25455
  reapStalePartials(file2);
25182
25456
  const {
25183
25457
  db,
@@ -25413,9 +25687,9 @@ import {
25413
25687
  closeSync,
25414
25688
  existsSync as existsSync2,
25415
25689
  openSync,
25416
- readFileSync,
25417
- rmSync as rmSync3,
25418
- statSync as statSync2,
25690
+ readFileSync as readFileSync2,
25691
+ rmSync as rmSync4,
25692
+ statSync as statSync3,
25419
25693
  writeFileSync as writeFileSync2
25420
25694
  } from "fs";
25421
25695
  import { hostname as hostname3 } from "os";
@@ -25426,20 +25700,20 @@ import { createHash as createHash3 } from "crypto";
25426
25700
 
25427
25701
  // ../../packages/persistence/src/fingerprint.ts
25428
25702
  import { createHmac, randomBytes } from "crypto";
25429
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
25430
- import { join as join3 } from "path";
25703
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
25704
+ import { join as join4 } from "path";
25431
25705
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25432
25706
  var EXCEPTION_KEY_FILENAME = "exception.key";
25433
25707
  var KEY_MATERIAL_BYTES = 32;
25434
25708
  function keyFilePath(dataDir2) {
25435
- return join3(dataDir2, EXCEPTION_KEY_FILENAME);
25709
+ return join4(dataDir2, EXCEPTION_KEY_FILENAME);
25436
25710
  }
25437
25711
  function parseKeyFile(raw) {
25438
- const parsed = JSON.parse(raw);
25439
- if (typeof parsed !== "object" || parsed === null) {
25712
+ const parsed2 = JSON.parse(raw);
25713
+ if (typeof parsed2 !== "object" || parsed2 === null) {
25440
25714
  throw new Error("exception key file is corrupt: not a JSON object");
25441
25715
  }
25442
- const { version: version2, material } = parsed;
25716
+ const { version: version2, material } = parsed2;
25443
25717
  if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
25444
25718
  throw new Error("exception key file is corrupt: bad version");
25445
25719
  }
@@ -25455,7 +25729,7 @@ function parseKeyFile(raw) {
25455
25729
  function readFingerprintKey(dataDir2) {
25456
25730
  let raw;
25457
25731
  try {
25458
- raw = readFileSync2(keyFilePath(dataDir2), "utf8");
25732
+ raw = readFileSync3(keyFilePath(dataDir2), "utf8");
25459
25733
  } catch (err) {
25460
25734
  if (err.code === "ENOENT") return null;
25461
25735
  throw err instanceof Error ? err : new Error(String(err));
@@ -25467,18 +25741,22 @@ function readFingerprintKey(dataDir2) {
25467
25741
  import { renameSync as renameSync3 } from "fs";
25468
25742
  import { mkdir } from "fs/promises";
25469
25743
  import { homedir } from "os";
25470
- import { join as join4 } from "path";
25744
+ import { join as join5 } from "path";
25471
25745
  function defaultDataDir() {
25472
- return join4(homedir(), ".aka");
25746
+ return join5(homedir(), ".aka");
25473
25747
  }
25474
25748
  function settingsDir(base = defaultDataDir()) {
25475
- return join4(base, "settings");
25749
+ return join5(base, "settings");
25476
25750
  }
25477
25751
  function dataDir(base = defaultDataDir()) {
25478
- return join4(base, "data");
25752
+ return join5(base, "data");
25479
25753
  }
25480
25754
  function dbPath(base = defaultDataDir()) {
25481
- return join4(dataDir(base), "aka.db");
25755
+ return join5(dataDir(base), "aka.db");
25756
+ }
25757
+ async function ensureDataDir(dir = defaultDataDir()) {
25758
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25759
+ tightenDir(dir);
25482
25760
  }
25483
25761
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25484
25762
  ensureDataDirSync(dir);
@@ -25491,8 +25769,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25491
25769
  for (const { name, dest } of moves) {
25492
25770
  try {
25493
25771
  ensureDataDirSync(dest);
25494
- const moved = join4(dest, name);
25495
- renameSync3(join4(base, name), moved);
25772
+ const moved = join5(dest, name);
25773
+ renameSync3(join5(base, name), moved);
25496
25774
  tightenFile(moved);
25497
25775
  } catch {
25498
25776
  }
@@ -25500,7 +25778,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25500
25778
  }
25501
25779
 
25502
25780
  // ../../packages/persistence/src/managed-settings.ts
25503
- import { readFileSync as readFileSync3 } from "fs";
25781
+ import { readFileSync as readFileSync4 } from "fs";
25504
25782
  import { posix, win32 } from "path";
25505
25783
  function managedSettingsPaths(platform2 = process.platform) {
25506
25784
  if (platform2 === "darwin") {
@@ -25518,14 +25796,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25518
25796
  for (const path of paths) {
25519
25797
  let text;
25520
25798
  try {
25521
- text = readFileSync3(path, "utf8");
25799
+ text = readFileSync4(path, "utf8");
25522
25800
  } catch {
25523
25801
  continue;
25524
25802
  }
25525
25803
  const record2 = parseJsonObject(text);
25526
25804
  if (!record2) continue;
25527
- const parsed = ManagedSettings.safeParse(record2);
25528
- if (parsed.success) return parsed.data;
25805
+ const parsed2 = ManagedSettings.safeParse(record2);
25806
+ if (parsed2.success) return parsed2.data;
25529
25807
  }
25530
25808
  return null;
25531
25809
  }
@@ -25565,14 +25843,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25565
25843
  }
25566
25844
 
25567
25845
  // ../../packages/persistence/src/settings.ts
25568
- import { readFileSync as readFileSync4 } from "fs";
25569
- import { join as join5 } from "path";
25846
+ import { readFileSync as readFileSync5 } from "fs";
25847
+ import { join as join6 } from "path";
25570
25848
  var SETTINGS_FILENAME = "settings.json";
25571
25849
  function readWorkspaceSettings(base = defaultDataDir()) {
25572
25850
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25573
25851
  }
25574
25852
  function readUserSettings(base) {
25575
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25853
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25576
25854
  if (!record2) return defaultWorkspaceSettings();
25577
25855
  try {
25578
25856
  return WorkspaceSettings.parse(record2);
@@ -25583,13 +25861,17 @@ function readUserSettings(base) {
25583
25861
  function readJson(file2) {
25584
25862
  let text;
25585
25863
  try {
25586
- text = readFileSync4(file2, "utf8");
25864
+ text = readFileSync5(file2, "utf8");
25587
25865
  } catch {
25588
25866
  return null;
25589
25867
  }
25590
25868
  return parseJsonObject(text) ?? null;
25591
25869
  }
25592
25870
 
25871
+ // ../../packages/persistence/src/store-symlinks.ts
25872
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
25873
+ import { dirname as dirname2, join as join7, resolve } from "path";
25874
+
25593
25875
  // ../../packages/persistence/src/vault/crypto.ts
25594
25876
  import {
25595
25877
  createCipheriv,
@@ -25602,20 +25884,20 @@ import {
25602
25884
  // ../../packages/persistence/src/vault/key-provider.ts
25603
25885
  import { execFileSync } from "child_process";
25604
25886
  import { randomBytes as randomBytes2 } from "crypto";
25605
- import { chmodSync as chmodSync2, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
25606
- import { join as join6 } from "path";
25887
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
25888
+ import { join as join8 } from "path";
25607
25889
 
25608
25890
  // ../../packages/persistence/src/vault/vault.ts
25609
25891
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25610
25892
 
25611
25893
  // ../../packages/persistence/src/warn-era-cap.ts
25612
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25613
- import { join as join7 } from "path";
25894
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
25895
+ import { join as join9 } from "path";
25614
25896
  var MARKER = "warn-era-capped";
25615
25897
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25616
25898
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
25617
- const marker = join7(dataDir2, MARKER);
25618
- if (existsSync4(marker)) return { capped: 0, skipped: "already-run" };
25899
+ const marker = join9(dataDir2, MARKER);
25900
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25619
25901
  const capped = db.policies.capCategoryActions();
25620
25902
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25621
25903
  `, { mode: DATA_FILE_MODE });
@@ -25656,8 +25938,8 @@ function hostOf(url2) {
25656
25938
  }
25657
25939
  }
25658
25940
  function resolveProvider() {
25659
- const parsed = ProviderEnvSchema.safeParse(process.env);
25660
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
25941
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
25942
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25661
25943
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25662
25944
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25663
25945
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25674,8 +25956,8 @@ function resolveProvider() {
25674
25956
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25675
25957
  try {
25676
25958
  ensureLayoutDirSync(base);
25677
- const settingsFile = join8(settingsDir(base), "settings.json");
25678
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
25959
+ const settingsFile = join10(settingsDir(base), "settings.json");
25960
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25679
25961
  } catch {
25680
25962
  }
25681
25963
  migrateLegacyLayout(base);
@@ -25698,9 +25980,9 @@ function resolveProviderSafe(resolveProviderFn) {
25698
25980
  }
25699
25981
 
25700
25982
  // ../../packages/plugin-sdk/src/config-inventory.ts
25701
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
25983
+ import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25702
25984
  import { homedir as homedir2 } from "os";
25703
- import { basename as basename3, join as join10 } from "path";
25985
+ import { basename as basename3, join as join12 } from "path";
25704
25986
 
25705
25987
  // ../../packages/detections/src/egress/registry.ts
25706
25988
  var EXTRACTOR_VERSION = "1";
@@ -27390,10 +27672,10 @@ var localhost_ref_default = {
27390
27672
  severity: "low",
27391
27673
  matcher: {
27392
27674
  type: "regex",
27393
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27675
+ pattern: "(?<![A-Za-z0-9_])(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|(?<![A-Za-z0-9_]\\[)::1(?!:|\\.[0-9]))(?![A-Za-z0-9_])",
27394
27676
  flags: "g"
27395
27677
  },
27396
- examples: ["localhost", "127.0.0.1"]
27678
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27397
27679
  };
27398
27680
 
27399
27681
  // ../../rules/core-code-context/stack-trace.json
@@ -28744,8 +29026,8 @@ function scanText(text, ruleVersions) {
28744
29026
  }
28745
29027
 
28746
29028
  // ../../packages/plugin-sdk/src/repo.ts
28747
- import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
28748
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join9, sep as sep2 } from "path";
29029
+ import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
29030
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join11, sep as sep2 } from "path";
28749
29031
  function resolveRepoIdentity(cwd) {
28750
29032
  try {
28751
29033
  const root = findGitRoot(cwd);
@@ -28767,36 +29049,36 @@ function resolveRepoIdentity(cwd) {
28767
29049
  function findGitRoot(start) {
28768
29050
  let dir = start;
28769
29051
  for (; ; ) {
28770
- if (existsSync6(join9(dir, ".git"))) return dir;
28771
- const parent = dirname2(dir);
29052
+ if (existsSync7(join11(dir, ".git"))) return dir;
29053
+ const parent = dirname3(dir);
28772
29054
  if (parent === dir) return void 0;
28773
29055
  dir = parent;
28774
29056
  }
28775
29057
  }
28776
29058
  function resolveGitContext(root) {
28777
- const dotGit = join9(root, ".git");
29059
+ const dotGit = join11(root, ".git");
28778
29060
  try {
28779
- if (statSync4(dotGit).isDirectory()) {
28780
- return { configPath: join9(dotGit, "config"), headRoot: root };
29061
+ if (statSync6(dotGit).isDirectory()) {
29062
+ return { configPath: join11(dotGit, "config"), headRoot: root };
28781
29063
  }
28782
29064
  } catch {
28783
29065
  return void 0;
28784
29066
  }
28785
29067
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
28786
29068
  if (!target) return void 0;
28787
- const gitdir = isAbsolute(target) ? target : join9(root, target);
28788
- if (existsSync6(join9(gitdir, "config"))) {
28789
- return { configPath: join9(gitdir, "config"), headRoot: root };
29069
+ const gitdir = isAbsolute(target) ? target : join11(root, target);
29070
+ if (existsSync7(join11(gitdir, "config"))) {
29071
+ return { configPath: join11(gitdir, "config"), headRoot: root };
28790
29072
  }
28791
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29073
+ const commonRaw = safeRead(join11(gitdir, "commondir"))?.trim();
28792
29074
  if (!commonRaw) return void 0;
28793
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join9(gitdir, commonRaw);
28794
- const headRoot = basename2(commonGitDir) === ".git" ? dirname2(commonGitDir) : root;
28795
- return { configPath: join9(commonGitDir, "config"), headRoot };
29075
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join11(gitdir, commonRaw);
29076
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29077
+ return { configPath: join11(commonGitDir, "config"), headRoot };
28796
29078
  }
28797
29079
  function safeRead(path) {
28798
29080
  try {
28799
- return readFileSync6(path, "utf8");
29081
+ return readFileSync7(path, "utf8");
28800
29082
  } catch {
28801
29083
  return void 0;
28802
29084
  }
@@ -28837,14 +29119,14 @@ function slugFromUrl(url2) {
28837
29119
  import { createHash as createHash4, randomUUID as randomUUID13 } from "crypto";
28838
29120
 
28839
29121
  // ../../packages/plugin-sdk/src/isolated-scan.ts
28840
- import { existsSync as existsSync7 } from "fs";
29122
+ import { existsSync as existsSync8 } from "fs";
28841
29123
  import { fileURLToPath } from "url";
28842
29124
  import { Worker } from "worker_threads";
28843
29125
 
28844
29126
  // ../../packages/plugin-sdk/src/ignore-layers.ts
28845
29127
  var import_ignore = __toESM(require_ignore(), 1);
28846
- import { readFileSync as readFileSync8 } from "fs";
28847
- import { join as join11 } from "path";
29128
+ import { readFileSync as readFileSync9 } from "fs";
29129
+ import { join as join13 } from "path";
28848
29130
 
28849
29131
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
28850
29132
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -28876,16 +29158,16 @@ function resolveInventoryContext(input) {
28876
29158
  }
28877
29159
 
28878
29160
  // ../../packages/plugin-sdk/src/nudge.ts
28879
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
28880
- import { join as join12 } from "path";
29161
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
29162
+ import { join as join14 } from "path";
28881
29163
 
28882
29164
  // ../../packages/plugin-sdk/src/paths.ts
28883
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
28884
- import { basename as basename4, dirname as dirname3, sep as sep3 } from "path";
29165
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
29166
+ import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
28885
29167
 
28886
29168
  // ../../packages/plugin-sdk/src/project-files.ts
28887
- import { existsSync as existsSync8, readdirSync as readdirSync4 } from "fs";
28888
- import { basename as basename5, join as join13 } from "path";
29169
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
29170
+ import { basename as basename5, join as join15 } from "path";
28889
29171
 
28890
29172
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
28891
29173
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -28930,57 +29212,1247 @@ import { randomUUID as randomUUID14 } from "crypto";
28930
29212
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
28931
29213
 
28932
29214
  // ../../packages/plugin-sdk/src/throttle.ts
28933
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
28934
- import { join as join14 } from "path";
28935
-
28936
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
28937
- import { randomUUID as randomUUID15 } from "crypto";
29215
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
29216
+ import { join as join16 } from "path";
28938
29217
 
28939
- // ../../packages/plugin-runtime/src/recorder.ts
28940
- var PLUGIN_RECORDER_BINARY = "plugin";
29218
+ // ../../packages/plugin-runtime/src/attached/failure.ts
29219
+ function statusOf(err) {
29220
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
29221
+ const { status } = err;
29222
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
29223
+ return status >= 100 && status <= 599 ? status : null;
29224
+ }
29225
+ function classifyFailure(err) {
29226
+ switch (statusOf(err)) {
29227
+ case 401:
29228
+ return "unauthorized";
29229
+ case 403:
29230
+ return "forbidden";
29231
+ default:
29232
+ return "unreachable";
29233
+ }
29234
+ }
28941
29235
 
28942
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
28943
- var StandaloneDataGateway = class {
28944
- db;
28945
- // Kept for the fingerprint key lookup (exception.key lives beside the store).
28946
- dataDir;
28947
- // One notice per gateway — see warnRulesetDiscarded.
28948
- warnedRulesetDiscarded = false;
28949
- constructor(dataDir2, detections = [], meta3) {
28950
- this.db = openLocalDatabase(dataDir2);
28951
- this.dataDir = dataDir2;
28952
- this.db.installedPacks.recordInventory(detections, meta3);
29236
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
29237
+ import { readFileSync as readFileSync11 } from "fs";
29238
+ import { join as join17 } from "path";
29239
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
29240
+ function forwardDropsPath(dataDir2) {
29241
+ return join17(dataDir2, FORWARD_DROPS_FILENAME);
29242
+ }
29243
+ function recordForwardDrops(dataDir2, count, nowMs) {
29244
+ if (count <= 0) return;
29245
+ try {
29246
+ ensureDataDirSync(dataDir2);
29247
+ const previous = readForwardDrops(dataDir2);
29248
+ const next = {
29249
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
29250
+ lastDropAtMs: nowMs
29251
+ };
29252
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
29253
+ `);
29254
+ } catch {
28953
29255
  }
28954
- recordCapture(record2) {
28955
- this.db.recordCapture(record2.event, record2.findings);
28956
- return Promise.resolve();
29256
+ }
29257
+ function readForwardDrops(dataDir2) {
29258
+ try {
29259
+ const parsed2 = JSON.parse(readFileSync11(forwardDropsPath(dataDir2), "utf8"));
29260
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
29261
+ const record2 = parsed2;
29262
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
29263
+ return null;
29264
+ }
29265
+ if (record2.droppedForwards <= 0) return null;
29266
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
29267
+ return null;
29268
+ }
29269
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
29270
+ } catch {
29271
+ return null;
28957
29272
  }
28958
- ensureInventory(ctx) {
28959
- return Promise.resolve(this.db.ensureInventory(ctx));
29273
+ }
29274
+
29275
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
29276
+ import { randomUUID as randomUUID15 } from "crypto";
29277
+ import { readFileSync as readFileSync12 } from "fs";
29278
+ import { readFile, rename, writeFile } from "fs/promises";
29279
+ import { join as join18 } from "path";
29280
+
29281
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
29282
+ var REQUEST_TIMEOUT_MS = 2e3;
29283
+ function withTimeout(promise2, ms) {
29284
+ let timer;
29285
+ const timeout = new Promise((_, reject) => {
29286
+ timer = setTimeout(() => {
29287
+ reject(new Error("attached gateway request timed out"));
29288
+ }, ms);
29289
+ });
29290
+ promise2.catch(() => void 0);
29291
+ return Promise.race([promise2, timeout]).finally(() => {
29292
+ clearTimeout(timer);
29293
+ });
29294
+ }
29295
+
29296
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
29297
+ function isInvalidRequest(err) {
29298
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
29299
+ }
29300
+ var FORWARD_BUDGET_MS = 1500;
29301
+ var DECISION_PATH_BUDGET_MS = 800;
29302
+ var BREAKER_FAILURE_THRESHOLD = 3;
29303
+ var BREAKER_COOLDOWN_MS = 3e4;
29304
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
29305
+ var FAILURES = /* @__PURE__ */ new Set([
29306
+ "unauthorized",
29307
+ "forbidden",
29308
+ "unreachable"
29309
+ ]);
29310
+ var FORWARD_STATE_FILENAME = "attached-state.json";
29311
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
29312
+ function parseBreakerState(raw, nowMs) {
29313
+ try {
29314
+ const parsed2 = JSON.parse(raw);
29315
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
29316
+ const record2 = parsed2;
29317
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
29318
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
29319
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
29320
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
29321
+ } catch {
29322
+ return null;
28960
29323
  }
28961
- recordAuditEvent(event) {
28962
- this.db.auditEvents.insertAuditEvent(event);
28963
- return Promise.resolve();
29324
+ }
29325
+ function createForwardPolicy(deps) {
29326
+ const now = deps.now ?? (() => Date.now());
29327
+ const file2 = join18(deps.dir, STATE_FILENAME);
29328
+ let state = null;
29329
+ let loading = null;
29330
+ async function readState() {
29331
+ let raw;
29332
+ try {
29333
+ raw = await readFile(file2, "utf8");
29334
+ } catch {
29335
+ return { ...CLOSED };
29336
+ }
29337
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
28964
29338
  }
28965
- // The id is minted inside the repository from the natural key — the plugin can't
28966
- // import @akasecurity/persistence to compute it, so the gateway is the boundary that
28967
- // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
28968
- // converge a streaming partial/final split (see insertLlmCall).
28969
- recordLlmCall(input) {
28970
- this.db.auditEvents.insertLlmCall(input);
28971
- return Promise.resolve();
29339
+ async function load() {
29340
+ if (state !== null) return state;
29341
+ loading ??= readState().then((loaded) => {
29342
+ state = loaded;
29343
+ loading = null;
29344
+ return loaded;
29345
+ });
29346
+ return loading;
28972
29347
  }
28973
- // One reconcile pass = one transaction. All leaves commit together
28974
- // (single lock + WAL fsync); a contended SQLITE_BUSY rolls back and rejects so the
28975
- // reconciler drops the whole pass and recovers it idempotently on the next read.
28976
- recordLlmCalls(inputs) {
28977
- if (inputs.length === 0) return Promise.resolve();
28978
- return new Promise((resolve, reject) => {
28979
- try {
29348
+ async function persist(next) {
29349
+ state = next;
29350
+ try {
29351
+ await ensureDataDir(deps.dir);
29352
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
29353
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
29354
+ await rename(tmp, file2);
29355
+ } catch {
29356
+ }
29357
+ }
29358
+ return {
29359
+ async run(op, opts) {
29360
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
29361
+ let current;
29362
+ try {
29363
+ current = await load();
29364
+ } catch {
29365
+ current = { ...CLOSED };
29366
+ }
29367
+ const at = now();
29368
+ if (current.openedAtMs !== null) {
29369
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
29370
+ return { ok: false, reason: "breaker-open" };
29371
+ }
29372
+ await persist({
29373
+ consecutiveFailures: current.consecutiveFailures,
29374
+ openedAtMs: at,
29375
+ lastFailure: current.lastFailure
29376
+ });
29377
+ }
29378
+ try {
29379
+ const value = await withTimeout(op(), budget);
29380
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
29381
+ await persist({ ...CLOSED });
29382
+ }
29383
+ return { ok: true, value };
29384
+ } catch (err) {
29385
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
29386
+ const reason = classifyFailure(err);
29387
+ const failures = current.consecutiveFailures + 1;
29388
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
29389
+ await persist({
29390
+ consecutiveFailures: failures,
29391
+ openedAtMs: shouldOpen ? now() : null,
29392
+ lastFailure: reason
29393
+ });
29394
+ return { ok: false, reason };
29395
+ }
29396
+ }
29397
+ };
29398
+ }
29399
+
29400
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
29401
+ var ACTION_STRENGTH = {
29402
+ allow: 0,
29403
+ log: 1,
29404
+ warn: 2,
29405
+ redact: 3,
29406
+ block: 4
29407
+ };
29408
+ function ruleCategoryMap(wireRules, localRules) {
29409
+ const map2 = /* @__PURE__ */ new Map();
29410
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
29411
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
29412
+ for (const pack of bundledDetections()) {
29413
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
29414
+ }
29415
+ return map2;
29416
+ }
29417
+ function strongerOf(a, b) {
29418
+ if (a === null) return b;
29419
+ if (b === null) return a;
29420
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
29421
+ }
29422
+ function policyKey(policy) {
29423
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
29424
+ }
29425
+ function floorFor(policy, categoryByRuleId) {
29426
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
29427
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
29428
+ }
29429
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
29430
+ const merged = /* @__PURE__ */ new Map();
29431
+ const disabled = [];
29432
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
29433
+ for (const policy of remotePolicies) {
29434
+ if (!policy.enabled) continue;
29435
+ if (!("category" in policy.target)) continue;
29436
+ if (remoteCategoryAction.has(policy.target.category)) continue;
29437
+ const floor = floorFor(policy, categoryByRuleId);
29438
+ remoteCategoryAction.set(
29439
+ policy.target.category,
29440
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
29441
+ );
29442
+ }
29443
+ for (const policy of localPolicies) {
29444
+ if (!policy.enabled) {
29445
+ disabled.push(policy);
29446
+ continue;
29447
+ }
29448
+ const key = policyKey(policy);
29449
+ if (merged.has(key)) continue;
29450
+ let remoteFloor = null;
29451
+ if ("ruleId" in policy.target) {
29452
+ const category = categoryByRuleId.get(policy.target.ruleId);
29453
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
29454
+ }
29455
+ merged.set(
29456
+ key,
29457
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
29458
+ );
29459
+ }
29460
+ const localCategoryAction = /* @__PURE__ */ new Map();
29461
+ for (const policy of merged.values()) {
29462
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
29463
+ }
29464
+ for (const policy of remotePolicies) {
29465
+ if (!policy.enabled) {
29466
+ disabled.push(policy);
29467
+ continue;
29468
+ }
29469
+ const key = policyKey(policy);
29470
+ const floor = floorFor(policy, categoryByRuleId);
29471
+ let localFloor = null;
29472
+ if ("ruleId" in policy.target) {
29473
+ const category = categoryByRuleId.get(policy.target.ruleId);
29474
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
29475
+ }
29476
+ const effectiveFloor = strongerOf(floor, localFloor);
29477
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
29478
+ const existing = merged.get(key);
29479
+ if (existing === void 0) {
29480
+ merged.set(key, clamped);
29481
+ continue;
29482
+ }
29483
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
29484
+ merged.set(key, clamped);
29485
+ }
29486
+ }
29487
+ return [...merged.values(), ...disabled];
29488
+ }
29489
+ var AttachedDataGateway = class {
29490
+ constructor(deps) {
29491
+ this.deps = deps;
29492
+ }
29493
+ deps;
29494
+ /**
29495
+ * The control plane's OWN resolution of this session's inventory, captured by
29496
+ * ensureInventory. Null until the first successful forward — and it stays
29497
+ * null for the whole session when the control plane is unreachable, which is fine:
29498
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
29499
+ * what it can from the descriptors it already has.
29500
+ */
29501
+ remoteInventory = null;
29502
+ // ---------------------------------------------------------------------
29503
+ // Writes: local first, then forward.
29504
+ // ---------------------------------------------------------------------
29505
+ async recordCapture(record2) {
29506
+ await this.deps.local.recordCapture(record2);
29507
+ await this.deps.forward.run(
29508
+ () => this.deps.client.ingestEvents({
29509
+ events: [record2.event],
29510
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
29511
+ }),
29512
+ { decisionPath: true }
29513
+ );
29514
+ }
29515
+ async ensureInventory(ctx) {
29516
+ const resolved = await this.deps.local.ensureInventory(ctx);
29517
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
29518
+ this.remoteInventory = remote.ok ? remote.value : null;
29519
+ const snapshot = await (async () => {
29520
+ try {
29521
+ return await this.deps.posture?.prepare() ?? null;
29522
+ } catch {
29523
+ return null;
29524
+ }
29525
+ })();
29526
+ if (snapshot) {
29527
+ try {
29528
+ await withTimeout(
29529
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
29530
+ REQUEST_TIMEOUT_MS
29531
+ );
29532
+ } catch {
29533
+ }
29534
+ }
29535
+ return resolved;
29536
+ }
29537
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
29538
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
29539
+ // its own scoping columns, so the device and the forwarded copy
29540
+ // share one id space — which is what makes a re-post idempotent at all.
29541
+ //
29542
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
29543
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
29544
+ // what makes an attached retry safe: a capture-stubbed session row can still
29545
+ // be HEALED by the authoritative root, while a duplicate non-session event —
29546
+ // a retried tool_call, exactly this path — can never stomp a populated row.
29547
+ async recordAuditEvent(event) {
29548
+ await this.deps.local.recordAuditEvent(event);
29549
+ await this.deps.forward.run(
29550
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
29551
+ );
29552
+ }
29553
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
29554
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
29555
+ // client method yet) by pre-building the audit event from the natural key.
29556
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
29557
+ // which would write the event to the local store a second time.
29558
+ async recordLlmCall(input) {
29559
+ await this.deps.local.recordLlmCall(input);
29560
+ await this.deps.forward.run(
29561
+ () => this.deps.client.recordAuditEvent(
29562
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
29563
+ )
29564
+ );
29565
+ }
29566
+ /**
29567
+ * Forward one batch, item by item, under ONE aggregate deadline.
29568
+ *
29569
+ * Per-item budgets bound each request and nothing bounded their sum — see
29570
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
29571
+ * rather than sent: the local write has already succeeded, so every caller
29572
+ * has a correct result to return, and a drop is the outcome this path is
29573
+ * built to accept (G8) where a blown hook timeout is not.
29574
+ *
29575
+ * Serial rather than concurrent on purpose. Firing N requests at once would
29576
+ * trade a latency problem for a burst the plane's own per-key rate limiting
29577
+ * would answer with the refusals the breaker then counts.
29578
+ *
29579
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
29580
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
29581
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
29582
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
29583
+ * plane produces no failures, keeps the breaker closed, renders a healthy
29584
+ * block, and discards the tail of every batch indefinitely.
29585
+ */
29586
+ async forwardBatch(inputs, toEvent) {
29587
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
29588
+ for (let i = 0; i < inputs.length; i += 1) {
29589
+ const now = Date.now();
29590
+ if (now >= deadline) {
29591
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
29592
+ return;
29593
+ }
29594
+ const input = inputs[i];
29595
+ await this.deps.forward.run(
29596
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
29597
+ );
29598
+ }
29599
+ }
29600
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
29601
+ // gateway may write the whole batch in one local transaction, and looping
29602
+ // here would replace that with N separate local writes.
29603
+ async recordLlmCalls(inputs) {
29604
+ await this.deps.local.recordLlmCalls(inputs);
29605
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
29606
+ }
29607
+ // `input.inspections` (secrets detected client-side in the tool's masked
29608
+ // target) ride along on the request's `inspections` field — the control plane
29609
+ // persists each as an inspection_findings row linked to this audit event
29610
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
29611
+ // `target` already rides `input.attributes`, so no raw secret leaks either
29612
+ // way — this only stops the FINDING row itself from being dropped.
29613
+ async recordToolCalls(inputs) {
29614
+ await this.deps.local.recordToolCalls(inputs);
29615
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
29616
+ }
29617
+ // Forwarded as a `config_scan` audit event: there is no dedicated
29618
+ // config-scan ingest endpoint, and the audit-event door is the one the
29619
+ // control plane already opens for client-minted, idempotent records.
29620
+ //
29621
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
29622
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
29623
+ // locally — the inventory `items`, this audit event, and the posture
29624
+ // `definitions`/`findings` that reference it — and three of them stay on the
29625
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
29626
+ // read as the same argument: there, findings are omitted BECAUSE the plane
29627
+ // re-derives them from `Event.content`; here there is no content to re-derive
29628
+ // from, so what is omitted is simply not sent.
29629
+ //
29630
+ // That is the wire contract as it stands rather than an oversight to patch
29631
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
29632
+ // is documented as tool-call findings — widening it to carry config-scan
29633
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
29634
+ // matched command) and a decision about what an attached deployment is
29635
+ // entitled to, not a bug fix. An attached machine's config posture therefore
29636
+ // reaches the plane as the event only; the dashboard's own view of it is the
29637
+ // local store.
29638
+ async recordConfigScan(record2) {
29639
+ await this.deps.local.recordConfigScan(record2);
29640
+ await this.deps.forward.run(
29641
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
29642
+ );
29643
+ }
29644
+ async recordBlockedDetection(entry) {
29645
+ return this.deps.local.recordBlockedDetection(entry);
29646
+ }
29647
+ /**
29648
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
29649
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
29650
+ * forward here would be inventing a wire contract that does not exist. The
29651
+ * local write is the whole operation, and its summary is the real one — the
29652
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
29653
+ * returning the inner gateway's result keeps the retry semantics honest.
29654
+ */
29655
+ async recordProjectEgress(input) {
29656
+ return this.deps.local.recordProjectEgress(input);
29657
+ }
29658
+ // ---------------------------------------------------------------------
29659
+ // Reads and device-local ledgers: pure delegation.
29660
+ // ---------------------------------------------------------------------
29661
+ async configInventoryReport() {
29662
+ return this.deps.local.configInventoryReport();
29663
+ }
29664
+ async readSessionProvider(sessionId) {
29665
+ return this.deps.local.readSessionProvider(sessionId);
29666
+ }
29667
+ async facets() {
29668
+ return this.deps.local.facets();
29669
+ }
29670
+ /**
29671
+ * Delegated UNMODIFIED — including its refusals.
29672
+ *
29673
+ * This is a fail-secure boundary: it decides whether an approved exception
29674
+ * lets a blocked action through. Under local-first the local store owns the
29675
+ * exception ledger, so the honest answer is whatever it says; wrapping this
29676
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
29677
+ * turn a store error into a granted bypass. If the inner gateway rejects,
29678
+ * this rejects, and the runtime's own handling decides — which is asserted
29679
+ * end-to-end through runtime.capture rather than here.
29680
+ */
29681
+ async consumeException(id) {
29682
+ return this.deps.local.consumeException(id);
29683
+ }
29684
+ async recentFindings(opts) {
29685
+ return this.deps.local.recentFindings(opts);
29686
+ }
29687
+ async healthSummary() {
29688
+ return this.deps.local.healthSummary();
29689
+ }
29690
+ async activityByDay(days) {
29691
+ return this.deps.local.activityByDay(days);
29692
+ }
29693
+ async tokenReports() {
29694
+ return this.deps.local.tokenReports();
29695
+ }
29696
+ async knownContentHashes() {
29697
+ return this.deps.local.knownContentHashes();
29698
+ }
29699
+ async scanLedger(rulesetHash) {
29700
+ return this.deps.local.scanLedger(rulesetHash);
29701
+ }
29702
+ async recordScanned(entries) {
29703
+ return this.deps.local.recordScanned(entries);
29704
+ }
29705
+ async getRuleProbeVerdict(ruleKey) {
29706
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
29707
+ }
29708
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs) {
29709
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs);
29710
+ }
29711
+ async openAtRestKeysForPath(path) {
29712
+ return this.deps.local.openAtRestKeysForPath(path);
29713
+ }
29714
+ async resolvedAtRestKeysForPath(path) {
29715
+ return this.deps.local.resolvedAtRestKeysForPath(path);
29716
+ }
29717
+ async insertResolution(input) {
29718
+ return this.deps.local.insertResolution(input);
29719
+ }
29720
+ async close() {
29721
+ return this.deps.local.close();
29722
+ }
29723
+ // ---------------------------------------------------------------------
29724
+ // Policy
29725
+ // ---------------------------------------------------------------------
29726
+ async getPolicyBundle() {
29727
+ const local = await this.deps.local.getPolicyBundle();
29728
+ const cached2 = await (async () => {
29729
+ try {
29730
+ return await this.deps.readCachedBundle();
29731
+ } catch {
29732
+ return null;
29733
+ }
29734
+ })();
29735
+ if (cached2 === null) return local;
29736
+ const byRuleId = /* @__PURE__ */ new Map();
29737
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
29738
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
29739
+ }
29740
+ const rules = [...byRuleId.values()];
29741
+ return {
29742
+ ...local,
29743
+ // The remote version identifies the composed bundle for the poller.
29744
+ version: cached2.version,
29745
+ rules,
29746
+ policies: mergeRaiseOnly(
29747
+ local.policies,
29748
+ cached2.policies,
29749
+ ruleCategoryMap(cached2.rules, local.rules)
29750
+ ),
29751
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
29752
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
29753
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
29754
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
29755
+ // anything able to write policy-cache.json, a kill-switch over the
29756
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
29757
+ // zero local detection. Spread from `local` above, and deliberately not
29758
+ // re-read from `cached` here.
29759
+ //
29760
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
29761
+ // and each named here so a reader can tell a decision from an omission:
29762
+ //
29763
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
29764
+ // one from an unsigned on-disk cache would let
29765
+ // anything able to write that file turn rules off.
29766
+ // Every other field this merge accepts can only
29767
+ // RAISE enforcement; this is the one that cannot,
29768
+ // so it stays local-only until the bundle is
29769
+ // signed. Exceptions remain a device-local ledger.
29770
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
29771
+ // recoverable, which is a CUSTODY change: it puts
29772
+ // the detected value in the local vault instead of
29773
+ // destroying it. Taking that instruction from the
29774
+ // cache would let a remote party turn one-way
29775
+ // redaction into retention. Dropping it keeps the
29776
+ // one-way behaviour, which the schema itself calls
29777
+ // "the safe direction to default".
29778
+ // `ruleVersions` — remote rules fall back to their own spec version.
29779
+ // Cosmetic rather than protective: it only affects
29780
+ // how a finding is version-attributed, and the two
29781
+ // sides may therefore attribute org rules
29782
+ // differently. Worth carrying once there is a
29783
+ // reader that needs it; nothing reads it today.
29784
+ };
29785
+ }
29786
+ // ---------------------------------------------------------------------
29787
+ // LocalStoreMaintenance — by delegation (D3).
29788
+ //
29789
+ // Implementing these is what actually closes the skipped-local-maintenance
29790
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
29791
+ // any object carrying all five, so the composite qualifies and SessionStart
29792
+ // runs maintenance on the device's real store.
29793
+ //
29794
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
29795
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
29796
+ // return value directly; declaring them `async` here would hand those call
29797
+ // sites a Promise and silently break both.
29798
+ // ---------------------------------------------------------------------
29799
+ async sweepTerminalExceptions(retentionMs) {
29800
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
29801
+ }
29802
+ capWarnEraEnforcement(policyMode) {
29803
+ return this.deps.local.capWarnEraEnforcement(policyMode);
29804
+ }
29805
+ async recordProjectFiles(projectId, scan2) {
29806
+ return this.deps.local.recordProjectFiles(projectId, scan2);
29807
+ }
29808
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
29809
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
29810
+ }
29811
+ staleBinaryNotice(currentVersion) {
29812
+ return this.deps.local.staleBinaryNotice(currentVersion);
29813
+ }
29814
+ };
29815
+ function reKeyForForward(event, remote) {
29816
+ if (remote === null) {
29817
+ const stripped = { ...event };
29818
+ delete stripped.hostId;
29819
+ delete stripped.harnessId;
29820
+ delete stripped.sourceProjectId;
29821
+ return stripped;
29822
+ }
29823
+ const rekeyed = { ...event };
29824
+ delete rekeyed.hostId;
29825
+ delete rekeyed.harnessId;
29826
+ delete rekeyed.sourceProjectId;
29827
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
29828
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
29829
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
29830
+ return rekeyed;
29831
+ }
29832
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
29833
+ function llmAuditEvent(input) {
29834
+ return {
29835
+ id: llmCallId(input.sessionId, input.messageId),
29836
+ eventType: "llm_call",
29837
+ startedAt: input.startedAt,
29838
+ parentId: input.parentId,
29839
+ rootSessionId: input.rootSessionId,
29840
+ attributes: input.attributes
29841
+ };
29842
+ }
29843
+ function toolAuditEvent(input) {
29844
+ return {
29845
+ id: toolCallId(input.sessionId, input.toolUseId),
29846
+ eventType: "tool_call",
29847
+ startedAt: input.startedAt,
29848
+ parentId: input.parentId,
29849
+ rootSessionId: input.rootSessionId,
29850
+ attributes: input.attributes,
29851
+ inspections: input.inspections
29852
+ };
29853
+ }
29854
+
29855
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
29856
+ import { randomUUID as randomUUID16 } from "crypto";
29857
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
29858
+ import { join as join19 } from "path";
29859
+
29860
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
29861
+ import { rename as rename2 } from "fs/promises";
29862
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
29863
+ var ATTEMPTS = 5;
29864
+ var delay = (ms) => new Promise((resolve2) => {
29865
+ setTimeout(resolve2, ms);
29866
+ });
29867
+ async function publishByRename(tmp, file2, move = rename2) {
29868
+ for (let attempt = 1; ; attempt += 1) {
29869
+ try {
29870
+ await move(tmp, file2);
29871
+ return;
29872
+ } catch (err) {
29873
+ const code = err.code;
29874
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
29875
+ await delay(attempt * 10);
29876
+ }
29877
+ }
29878
+ }
29879
+
29880
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
29881
+ function createPolicyStore(dir = dataDir()) {
29882
+ const file2 = join19(dir, "policy-cache.json");
29883
+ async function read() {
29884
+ try {
29885
+ const raw = await readFile2(file2, "utf8");
29886
+ const parsed2 = JSON.parse(raw);
29887
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
29888
+ const record2 = parsed2;
29889
+ const bundle = PolicyBundle.parse(record2.bundle);
29890
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
29891
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
29892
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
29893
+ } catch {
29894
+ return null;
29895
+ }
29896
+ }
29897
+ async function write(bundle, etag) {
29898
+ await ensureDataDir(dir);
29899
+ const stored = {
29900
+ bundle,
29901
+ fetchedAtMs: Date.now(),
29902
+ ...etag === void 0 ? {} : { etag }
29903
+ };
29904
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
29905
+ try {
29906
+ await writeFile2(tmp, JSON.stringify(stored), {
29907
+ encoding: "utf8",
29908
+ mode: DATA_FILE_MODE,
29909
+ flag: "wx"
29910
+ });
29911
+ await publishByRename(tmp, file2);
29912
+ } catch (err) {
29913
+ await rm(tmp, { force: true }).catch(() => void 0);
29914
+ throw err;
29915
+ }
29916
+ }
29917
+ return { read, write, file: file2 };
29918
+ }
29919
+
29920
+ // ../../packages/remote/src/http.ts
29921
+ import { request as httpRequest } from "http";
29922
+ import { request as httpsRequest } from "https";
29923
+ var DEFAULT_TIMEOUT_MS = 1e4;
29924
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
29925
+ var RemoteRequestError = class extends Error {
29926
+ constructor(status) {
29927
+ super(`control-plane request failed with status ${String(status)}`);
29928
+ this.status = status;
29929
+ this.name = "RemoteRequestError";
29930
+ }
29931
+ status;
29932
+ };
29933
+ var RemoteRequestInvalid = class extends Error {
29934
+ constructor(route, cause) {
29935
+ super(`refusing to send a malformed body to ${route}`);
29936
+ this.cause = cause;
29937
+ this.name = "RemoteRequestInvalid";
29938
+ }
29939
+ cause;
29940
+ };
29941
+ var RemoteResponseInvalid = class extends Error {
29942
+ constructor(route, detail) {
29943
+ super(`control plane answered ${route} with ${detail}`);
29944
+ this.name = "RemoteResponseInvalid";
29945
+ }
29946
+ };
29947
+ var RemoteTransportError = class extends Error {
29948
+ /**
29949
+ * The status the peer sent, when headers arrived and only the BODY was
29950
+ * refused.
29951
+ *
29952
+ * Undefined for the ordinary case this class was written for — no answer at
29953
+ * all. It exists because two paths reject after a status has already been
29954
+ * delivered: an oversized body and an aborted response. Discarding it there
29955
+ * reported a deployment answering 401 with a verbose body as a network
29956
+ * outage, which sends the reader to look at their network instead of their
29957
+ * credential.
29958
+ */
29959
+ constructor(reason, status) {
29960
+ super(`control-plane request did not complete: ${reason}`);
29961
+ this.status = status;
29962
+ this.name = "RemoteTransportError";
29963
+ }
29964
+ status;
29965
+ };
29966
+ async function send(options) {
29967
+ const url2 = new URL(options.url);
29968
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
29969
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
29970
+ const requestOptions = {
29971
+ method: options.method,
29972
+ headers: {
29973
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
29974
+ // last they win, and two of the values below are ones no caller may
29975
+ // replace: `x-api-key` is the credential, and `content-length` is the
29976
+ // byte count that stops a multi-byte body being truncated by the
29977
+ // receiver. `SendOptions.headers` is a free-form record on an exported
29978
+ // function, so "no caller does that today" is not the guarantee to rely
29979
+ // on. The one header any caller actually passes — `if-none-match` on the
29980
+ // conditional GET — is untouched by this order.
29981
+ ...options.headers,
29982
+ // The credential. One header, matching what the deployment authenticates
29983
+ // on; a second copy in an `Authorization` header would be one more place
29984
+ // it can be logged by an intermediary for no gain.
29985
+ "x-api-key": options.apiKey,
29986
+ accept: "application/json",
29987
+ ...options.body === void 0 ? {} : {
29988
+ "content-type": "application/json",
29989
+ // Byte length, not string length: a multi-byte body sent with a
29990
+ // character count is truncated by the receiver.
29991
+ "content-length": String(Buffer.byteLength(options.body))
29992
+ }
29993
+ }
29994
+ };
29995
+ return new Promise((resolve2, reject) => {
29996
+ let settled = false;
29997
+ const fail = (reason, status) => {
29998
+ if (settled) return;
29999
+ settled = true;
30000
+ reject(new RemoteTransportError(reason, status));
30001
+ };
30002
+ const req = send_(url2, requestOptions, (res) => {
30003
+ const chunks = [];
30004
+ let size = 0;
30005
+ res.on("data", (chunk) => {
30006
+ size += chunk.length;
30007
+ if (size > MAX_RESPONSE_BYTES) {
30008
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
30009
+ res.destroy();
30010
+ req.destroy();
30011
+ return;
30012
+ }
30013
+ chunks.push(chunk);
30014
+ });
30015
+ res.on("aborted", () => {
30016
+ fail("the response was aborted", res.statusCode);
30017
+ });
30018
+ res.on("end", () => {
30019
+ if (settled) return;
30020
+ settled = true;
30021
+ resolve2({
30022
+ status: res.statusCode ?? 0,
30023
+ headers: res.headers,
30024
+ body: Buffer.concat(chunks).toString("utf8")
30025
+ });
30026
+ });
30027
+ });
30028
+ const deadline = setTimeout(() => {
30029
+ fail(`no response within ${String(timeoutMs)}ms`);
30030
+ req.destroy();
30031
+ }, timeoutMs);
30032
+ deadline.unref();
30033
+ req.on("upgrade", (_res, socket) => {
30034
+ fail("the deployment answered with a protocol upgrade");
30035
+ socket.destroy();
30036
+ });
30037
+ req.on("close", () => {
30038
+ fail("the connection closed before a response was read");
30039
+ clearTimeout(deadline);
30040
+ });
30041
+ req.on("error", (err) => {
30042
+ fail(err.message);
30043
+ });
30044
+ if (options.body !== void 0) req.write(options.body);
30045
+ req.end();
30046
+ });
30047
+ }
30048
+
30049
+ // ../../packages/remote/src/client.ts
30050
+ var ROUTES = {
30051
+ events: "/v1/events",
30052
+ auditEvents: "/v1/audit-events",
30053
+ inventory: "/v1/inventory",
30054
+ storePosture: "/v1/store-posture",
30055
+ policyBundle: "/v1/policy-bundle",
30056
+ whoami: "/v1/plugin/whoami"
30057
+ };
30058
+ function headerValue(response, name) {
30059
+ const raw = response.headers[name];
30060
+ if (raw === void 0) return void 0;
30061
+ return Array.isArray(raw) ? raw[0] : raw;
30062
+ }
30063
+ function okBody(response) {
30064
+ if (response.status < 200 || response.status >= 300) {
30065
+ throw new RemoteRequestError(response.status);
30066
+ }
30067
+ return response.body;
30068
+ }
30069
+ function parsed(schema, body, route) {
30070
+ let json2;
30071
+ try {
30072
+ json2 = JSON.parse(body);
30073
+ } catch {
30074
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
30075
+ }
30076
+ const result = schema.safeParse(json2);
30077
+ if (!result.success) {
30078
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
30079
+ }
30080
+ return result.data;
30081
+ }
30082
+ function withoutTrailingSlashes(endpoint) {
30083
+ let end = endpoint.length;
30084
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
30085
+ return endpoint.slice(0, end);
30086
+ }
30087
+ var SLASH = "/".charCodeAt(0);
30088
+ function createRemoteClient(options) {
30089
+ const base = withoutTrailingSlashes(options.endpoint);
30090
+ const url2 = (route) => `${base}${route}`;
30091
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
30092
+ return {
30093
+ async ingestEvents(batch) {
30094
+ const response = await send({
30095
+ ...common,
30096
+ method: "POST",
30097
+ url: url2(ROUTES.events),
30098
+ body: JSON.stringify(batch)
30099
+ });
30100
+ return parsed(IngestAck, okBody(response), ROUTES.events);
30101
+ },
30102
+ async ingestInventory(context) {
30103
+ const response = await send({
30104
+ ...common,
30105
+ method: "POST",
30106
+ url: url2(ROUTES.inventory),
30107
+ body: JSON.stringify(context)
30108
+ });
30109
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
30110
+ },
30111
+ async recordAuditEvent(event) {
30112
+ const validated = RecordAuditEventRequest.safeParse(event);
30113
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
30114
+ const submission = validated.data;
30115
+ const response = await send({
30116
+ ...common,
30117
+ method: "POST",
30118
+ url: url2(ROUTES.auditEvents),
30119
+ body: JSON.stringify(submission)
30120
+ });
30121
+ okBody(response);
30122
+ },
30123
+ async reportStorePosture(snapshot) {
30124
+ const response = await send({
30125
+ ...common,
30126
+ method: "POST",
30127
+ url: url2(ROUTES.storePosture),
30128
+ body: JSON.stringify(snapshot)
30129
+ });
30130
+ okBody(response);
30131
+ },
30132
+ async getPolicyBundle(etag) {
30133
+ const response = await send({
30134
+ ...common,
30135
+ method: "GET",
30136
+ url: url2(ROUTES.policyBundle),
30137
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
30138
+ });
30139
+ if (response.status === 304) {
30140
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
30141
+ }
30142
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
30143
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
30144
+ },
30145
+ async whoami() {
30146
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
30147
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
30148
+ }
30149
+ };
30150
+ }
30151
+
30152
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
30153
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
30154
+ function createPostureReporter(deps) {
30155
+ async function prepare() {
30156
+ try {
30157
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
30158
+ if (state === null) return null;
30159
+ const nowMs = deps.now();
30160
+ const elapsed = nowMs - state.lastAttemptedAtMs;
30161
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
30162
+ try {
30163
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
30164
+ } catch {
30165
+ }
30166
+ const { readError, ...measurement } = deps.readStore();
30167
+ if (readError) return null;
30168
+ let plugin;
30169
+ try {
30170
+ plugin = await deps.pluginBlock?.();
30171
+ } catch {
30172
+ plugin = void 0;
30173
+ }
30174
+ return {
30175
+ deviceId: state.deviceId,
30176
+ hostname: deps.hostname(),
30177
+ capturedAt: nowMs,
30178
+ ...measurement,
30179
+ // Omit the key rather than spread an explicit `undefined` —
30180
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
30181
+ // factory.ts keys on presence.
30182
+ ...plugin === void 0 ? {} : { plugin }
30183
+ };
30184
+ } catch {
30185
+ return null;
30186
+ }
30187
+ }
30188
+ async function send2(snapshot) {
30189
+ try {
30190
+ await deps.report(snapshot);
30191
+ } catch {
30192
+ }
30193
+ }
30194
+ return { prepare, send: send2 };
30195
+ }
30196
+
30197
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
30198
+ import { statSync as statSync9 } from "fs";
30199
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
30200
+
30201
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
30202
+ function emptyActionCounts() {
30203
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
30204
+ }
30205
+ function isActionTaken(value) {
30206
+ return ACTION_TAKEN_KEYS.includes(value);
30207
+ }
30208
+
30209
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
30210
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
30211
+ function isSchemaAbsent(err) {
30212
+ return err instanceof Error && /no such table/i.test(err.message);
30213
+ }
30214
+ function emptyReadout(readError = false) {
30215
+ const byAction = emptyActionCounts();
30216
+ return {
30217
+ storePresent: false,
30218
+ schemaVersion: null,
30219
+ findingsTotal: 0,
30220
+ findingsFirstAt: null,
30221
+ findingsLastAt: null,
30222
+ packs: [],
30223
+ policyCounts: { total: 0, disabled: 0, byAction },
30224
+ readError
30225
+ };
30226
+ }
30227
+ function readStorePosture(dbPath2) {
30228
+ try {
30229
+ statSync9(dbPath2);
30230
+ } catch (err) {
30231
+ const code = err.code;
30232
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
30233
+ return emptyReadout(true);
30234
+ }
30235
+ let db = null;
30236
+ let version2 = null;
30237
+ let packs2 = [];
30238
+ let policyCounts = {
30239
+ total: 0,
30240
+ disabled: 0,
30241
+ byAction: emptyActionCounts()
30242
+ };
30243
+ let findingsTotal = 0;
30244
+ let findingsFirstAt = null;
30245
+ let findingsLastAt = null;
30246
+ const currentReadout = () => ({
30247
+ storePresent: true,
30248
+ schemaVersion: version2,
30249
+ findingsTotal,
30250
+ findingsFirstAt,
30251
+ findingsLastAt,
30252
+ packs: packs2,
30253
+ policyCounts,
30254
+ readError: false
30255
+ });
30256
+ try {
30257
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
30258
+ db.exec("PRAGMA busy_timeout = 2000");
30259
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
30260
+ try {
30261
+ const packRows = db.prepare(
30262
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
30263
+ ).all();
30264
+ packs2 = packRows.map((r) => ({
30265
+ packId: `${r.namespace}/${r.pack_id}`,
30266
+ version: r.version,
30267
+ enabled: r.enabled !== 0,
30268
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
30269
+ }));
30270
+ } catch (err) {
30271
+ if (!isSchemaAbsent(err)) throw err;
30272
+ }
30273
+ try {
30274
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
30275
+ const byAction = emptyActionCounts();
30276
+ let disabled = 0;
30277
+ for (const row of policyRows) {
30278
+ if (row.enabled === 0) disabled += 1;
30279
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
30280
+ }
30281
+ policyCounts = { total: policyRows.length, disabled, byAction };
30282
+ } catch (err) {
30283
+ if (!isSchemaAbsent(err)) throw err;
30284
+ }
30285
+ try {
30286
+ const agg = db.prepare(
30287
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
30288
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
30289
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
30290
+ ).get();
30291
+ findingsTotal = agg.n;
30292
+ findingsFirstAt = agg.firstAt;
30293
+ findingsLastAt = agg.lastAt;
30294
+ } catch (err) {
30295
+ if (!isSchemaAbsent(err)) throw err;
30296
+ }
30297
+ return currentReadout();
30298
+ } catch {
30299
+ return emptyReadout(true);
30300
+ } finally {
30301
+ try {
30302
+ db?.close();
30303
+ } catch {
30304
+ }
30305
+ }
30306
+ }
30307
+
30308
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
30309
+ import { randomUUID as randomUUID17 } from "crypto";
30310
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
30311
+ import { join as join20 } from "path";
30312
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
30313
+ function createPostureStore(dir = settingsDir(), legacyDir) {
30314
+ const file2 = join20(dir, "posture-state.json");
30315
+ const legacyFile = legacyDir === void 0 ? null : join20(legacyDir, "posture-state.json");
30316
+ async function persist(state) {
30317
+ await ensureDataDir(dir);
30318
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
30319
+ try {
30320
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
30321
+ await publishByRename(tmp, file2);
30322
+ } catch (err) {
30323
+ await rm2(tmp, { force: true }).catch(() => void 0);
30324
+ throw err;
30325
+ }
30326
+ }
30327
+ async function readFrom(path) {
30328
+ let raw;
30329
+ try {
30330
+ raw = await readFile3(path, "utf8");
30331
+ } catch (err) {
30332
+ const code = err.code;
30333
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
30334
+ throw err;
30335
+ }
30336
+ try {
30337
+ const parsed2 = JSON.parse(raw);
30338
+ if (typeof parsed2 === "object" && parsed2 !== null) {
30339
+ const record2 = parsed2;
30340
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
30341
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
30342
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
30343
+ }
30344
+ }
30345
+ } catch {
30346
+ }
30347
+ return null;
30348
+ }
30349
+ async function read() {
30350
+ const current = await readFrom(file2);
30351
+ if (current) return current;
30352
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
30353
+ if (legacy) {
30354
+ try {
30355
+ await persist(legacy);
30356
+ } catch {
30357
+ }
30358
+ return legacy;
30359
+ }
30360
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
30361
+ try {
30362
+ await ensureDataDir(dir);
30363
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
30364
+ } catch {
30365
+ return null;
30366
+ }
30367
+ const winner = await readFrom(file2).catch(() => null);
30368
+ if (winner) return winner;
30369
+ try {
30370
+ await persist(fresh);
30371
+ } catch {
30372
+ return null;
30373
+ }
30374
+ return fresh;
30375
+ }
30376
+ async function markAttempted(deviceId, atMs) {
30377
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
30378
+ }
30379
+ return { read, markAttempted, file: file2 };
30380
+ }
30381
+
30382
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
30383
+ import { readFileSync as readFileSync13 } from "fs";
30384
+ import { join as join21 } from "path";
30385
+
30386
+ // ../../packages/plugin-runtime/src/attached/status.ts
30387
+ var REFUSAL_LINES = {
30388
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
30389
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
30390
+ };
30391
+ var OUTCOME_LINES = {
30392
+ ok: "policy synced",
30393
+ "not-modified": "policy up to date",
30394
+ unauthorized: REFUSAL_LINES.unauthorized,
30395
+ forbidden: REFUSAL_LINES.forbidden,
30396
+ unreachable: "control plane unreachable at last attempt",
30397
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
30398
+ };
30399
+
30400
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
30401
+ import { spawn } from "child_process";
30402
+ import { fileURLToPath as fileURLToPath2 } from "url";
30403
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
30404
+
30405
+ // ../../packages/plugin-runtime/src/attached/factory.ts
30406
+ import { hostname as hostname5 } from "os";
30407
+
30408
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
30409
+ import { randomUUID as randomUUID18 } from "crypto";
30410
+
30411
+ // ../../packages/plugin-runtime/src/recorder.ts
30412
+ var PLUGIN_RECORDER_BINARY = "plugin";
30413
+
30414
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
30415
+ var StandaloneDataGateway = class {
30416
+ db;
30417
+ // Kept for the fingerprint key lookup (exception.key lives beside the store).
30418
+ dataDir;
30419
+ // One notice per gateway — see warnRulesetDiscarded.
30420
+ warnedRulesetDiscarded = false;
30421
+ constructor(dataDir2, detections = [], meta3) {
30422
+ this.db = openLocalDatabase(dataDir2);
30423
+ this.dataDir = dataDir2;
30424
+ this.db.installedPacks.recordInventory(detections, meta3);
30425
+ }
30426
+ recordCapture(record2) {
30427
+ this.db.recordCapture(record2.event, record2.findings);
30428
+ return Promise.resolve();
30429
+ }
30430
+ ensureInventory(ctx) {
30431
+ return Promise.resolve(this.db.ensureInventory(ctx));
30432
+ }
30433
+ recordAuditEvent(event) {
30434
+ this.db.auditEvents.insertAuditEvent(event);
30435
+ return Promise.resolve();
30436
+ }
30437
+ // The id is minted inside the repository from the natural key — the plugin can't
30438
+ // import @akasecurity/persistence to compute it, so the gateway is the boundary that
30439
+ // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
30440
+ // converge a streaming partial/final split (see insertLlmCall).
30441
+ recordLlmCall(input) {
30442
+ this.db.auditEvents.insertLlmCall(input);
30443
+ return Promise.resolve();
30444
+ }
30445
+ // One reconcile pass = one transaction. All leaves commit together
30446
+ // (single lock + WAL fsync); a contended SQLITE_BUSY rolls back and rejects so the
30447
+ // reconciler drops the whole pass and recovers it idempotently on the next read.
30448
+ recordLlmCalls(inputs) {
30449
+ if (inputs.length === 0) return Promise.resolve();
30450
+ return new Promise((resolve2, reject) => {
30451
+ try {
28980
30452
  this.db.auditEvents.runInTransaction(() => {
28981
30453
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
28982
30454
  });
28983
- resolve();
30455
+ resolve2();
28984
30456
  } catch (err) {
28985
30457
  reject(err instanceof Error ? err : new Error(String(err)));
28986
30458
  }
@@ -28992,12 +30464,12 @@ var StandaloneDataGateway = class {
28992
30464
  // drops the whole pass and recovers it idempotently next time.
28993
30465
  recordToolCalls(inputs) {
28994
30466
  if (inputs.length === 0) return Promise.resolve();
28995
- return new Promise((resolve, reject) => {
30467
+ return new Promise((resolve2, reject) => {
28996
30468
  try {
28997
30469
  this.db.auditEvents.runInTransaction(() => {
28998
30470
  for (const input of inputs) this.writeToolCall(input);
28999
30471
  });
29000
- resolve();
30472
+ resolve2();
29001
30473
  } catch (err) {
29002
30474
  reject(err instanceof Error ? err : new Error(String(err)));
29003
30475
  }
@@ -29139,7 +30611,7 @@ var StandaloneDataGateway = class {
29139
30611
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
29140
30612
  const installed = this.installedScanRules();
29141
30613
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
29142
- id: randomUUID15(),
30614
+ id: randomUUID18(),
29143
30615
  scope: "global",
29144
30616
  target: { ruleId },
29145
30617
  action,
@@ -29293,15 +30765,61 @@ var StandaloneDataGateway = class {
29293
30765
  }
29294
30766
  };
29295
30767
 
30768
+ // ../../packages/plugin-runtime/src/attached/factory.ts
30769
+ function resolveGatewayForConfig(config2, meta3) {
30770
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30771
+ try {
30772
+ if (!isAttached(config2.settings)) return local;
30773
+ const connection = config2.settings.controlPlane;
30774
+ if (connection === void 0) return local;
30775
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
30776
+ if (!state.usable) return local;
30777
+ const client = createRemoteClient({
30778
+ endpoint: connection.endpoint,
30779
+ apiKey: state.credential.apiKey
30780
+ });
30781
+ const store = createPolicyStore(config2.dataDir);
30782
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
30783
+ const forward = createForwardPolicy({ dir: config2.dataDir });
30784
+ return new AttachedDataGateway({
30785
+ local,
30786
+ client,
30787
+ dataDir: config2.dataDir,
30788
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
30789
+ forward,
30790
+ posture: createPostureReporter({
30791
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
30792
+ // `PostureReporter.send`. The reporter swallows every error by
30793
+ // contract, so a wrap outside it would hand `forward.run` a resolved
30794
+ // promise for a send that failed — recording a SUCCESS, clearing
30795
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
30796
+ // forward recovered when nothing did. Wrapping the raw client call puts
30797
+ // the breaker above the swallow, where it can see the truth.
30798
+ //
30799
+ // What it buys: once the breaker is open — the plane already confirmed
30800
+ // down by the gateway's own writes — this stops paying a request
30801
+ // timeout per throttle interval to re-learn it.
30802
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
30803
+ store: postureStore,
30804
+ readStore: () => readStorePosture(config2.dbPath),
30805
+ hostname: () => hostname5(),
30806
+ now: () => Date.now()
30807
+ })
30808
+ });
30809
+ } catch {
30810
+ return local;
30811
+ }
30812
+ }
30813
+
29296
30814
  // ../../packages/plugin-runtime/src/resolve.ts
29297
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
29298
- var defaultGatewayFactory = standaloneGatewayFactory;
30815
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
30816
+ var defaultGatewayFactory = configuredGatewayFactory;
29299
30817
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
29300
30818
  return gatewayFactory(config2, meta3);
29301
30819
  }
29302
30820
 
29303
30821
  // ../../packages/plugin-runtime/src/handle-session-start.ts
29304
- import { randomUUID as randomUUID16 } from "crypto";
30822
+ import { randomUUID as randomUUID19 } from "crypto";
29305
30823
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
29306
30824
 
29307
30825
  // src/history/tail.ts
@@ -29311,13 +30829,13 @@ import {
29311
30829
  fstatSync,
29312
30830
  mkdirSync as mkdirSync4,
29313
30831
  openSync as openSync2,
29314
- readFileSync as readFileSync10,
30832
+ readFileSync as readFileSync14,
29315
30833
  readSync,
29316
30834
  writeFileSync as writeFileSync7
29317
30835
  } from "fs";
29318
- import { join as join15 } from "path";
30836
+ import { join as join22 } from "path";
29319
30837
  function offsetsDir(dataDir2) {
29320
- return join15(dataDir2, "usage-offsets");
30838
+ return join22(dataDir2, "usage-offsets");
29321
30839
  }
29322
30840
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
29323
30841
  function safeSessionId(sessionId) {
@@ -29327,14 +30845,14 @@ function safeSessionId(sessionId) {
29327
30845
  return createHash5("sha256").update(sessionId).digest("hex");
29328
30846
  }
29329
30847
  function offsetPath(dataDir2, sessionId) {
29330
- return join15(offsetsDir(dataDir2), safeSessionId(sessionId));
30848
+ return join22(offsetsDir(dataDir2), safeSessionId(sessionId));
29331
30849
  }
29332
30850
  function readOffset(dataDir2, sessionId) {
29333
30851
  try {
29334
- const raw = readFileSync10(offsetPath(dataDir2, sessionId), "utf8");
29335
- const parsed = JSON.parse(raw);
29336
- if (typeof parsed === "object" && parsed !== null) {
29337
- const rec = parsed;
30852
+ const raw = readFileSync14(offsetPath(dataDir2, sessionId), "utf8");
30853
+ const parsed2 = JSON.parse(raw);
30854
+ if (typeof parsed2 === "object" && parsed2 !== null) {
30855
+ const rec = parsed2;
29338
30856
  const offset = typeof rec.offset === "number" && Number.isFinite(rec.offset) && rec.offset >= 0 ? rec.offset : 0;
29339
30857
  const lastPromptId = typeof rec.lastPromptId === "string" ? rec.lastPromptId : void 0;
29340
30858
  return lastPromptId !== void 0 ? { offset, lastPromptId } : { offset };
@@ -29389,9 +30907,9 @@ function readTail(transcriptPath, startOffset) {
29389
30907
  }
29390
30908
 
29391
30909
  // src/history/transcripts.ts
29392
- import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync11, readSync as readSync2, statSync as statSync7 } from "fs";
30910
+ import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync5, readFileSync as readFileSync15, readSync as readSync2, statSync as statSync10 } from "fs";
29393
30911
  import { homedir as homedir3 } from "os";
29394
- import { join as join16 } from "path";
30912
+ import { join as join23 } from "path";
29395
30913
  function isRecord(value) {
29396
30914
  return typeof value === "object" && value !== null;
29397
30915
  }