@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 = [
@@ -16202,6 +16201,125 @@ var ConfigScanRecord = external_exports.object({
16202
16201
  findings: external_exports.array(ConfigPostureFindingInput).optional()
16203
16202
  });
16204
16203
 
16204
+ // ../../packages/schema/src/zod/control-plane.ts
16205
+ var ATTACHED_CREDENTIAL_FILENAME = "control-plane-credential.json";
16206
+ var ATTACHED_CREDENTIAL_SPEC_VERSION = 1;
16207
+ var AttachedCredential = external_exports.object({
16208
+ specVersion: external_exports.literal(ATTACHED_CREDENTIAL_SPEC_VERSION),
16209
+ // The control-plane endpoint this credential was minted against.
16210
+ endpoint: external_exports.string().min(1),
16211
+ // The bearer credential itself. Never logged, never rendered — status
16212
+ // surfaces show `keyPrefix` and nothing else.
16213
+ apiKey: external_exports.string().min(1),
16214
+ // First few characters of the key, safe to display so a user can match the
16215
+ // credential against their organization's key list.
16216
+ keyPrefix: external_exports.string().min(1).max(16).optional(),
16217
+ mintedAt: external_exports.iso.datetime().optional()
16218
+ });
16219
+ var MAX_DATE_MS = 253402300799999;
16220
+ var MAX_INT4 = 2147483647;
16221
+ var StorePosturePack = external_exports.object({
16222
+ packId: external_exports.string().min(1),
16223
+ // 'namespace/packId'
16224
+ version: external_exports.string().min(1),
16225
+ enabled: external_exports.boolean(),
16226
+ // Stringified pass-through of the local store's `installed_packs.updated_at`
16227
+ // — the column format is store-version-dependent (epoch millis vs ISO), so
16228
+ // the wire shape assumes neither.
16229
+ updatedAt: external_exports.string().nullable()
16230
+ }).meta({ id: "StorePosturePack" });
16231
+ var StorePosturePolicyCounts = external_exports.object({
16232
+ total: external_exports.number().int().min(0),
16233
+ disabled: external_exports.number().int().min(0),
16234
+ // Exhaustive per-action map; the builder pre-fills every action with 0.
16235
+ //
16236
+ // Spelled out member-by-member rather than `z.record(ActionTaken, …)`. Zod
16237
+ // enforces exhaustiveness either way, but z.record emits `propertyNames` +
16238
+ // `additionalProperties` into a generated schema document, and a type
16239
+ // generator renders THAT with every key optional — a sender built against
16240
+ // the generated type would typecheck and still be rejected at runtime. An
16241
+ // explicit object emits `properties` + `required`, so generated types
16242
+ // demand all five.
16243
+ //
16244
+ // `satisfies Record<ActionTaken, …>` keeps the link to the enum: adding an
16245
+ // ActionTaken member is a COMPILE error here instead of silent drift.
16246
+ // `.strict()` is load-bearing — it rejects an unknown action key, which a
16247
+ // bare object would silently STRIP, accepting a miscounted map as valid.
16248
+ byAction: external_exports.object({
16249
+ warn: external_exports.number().int().min(0),
16250
+ redact: external_exports.number().int().min(0),
16251
+ block: external_exports.number().int().min(0),
16252
+ allow: external_exports.number().int().min(0),
16253
+ log: external_exports.number().int().min(0)
16254
+ }).strict()
16255
+ }).meta({ id: "StorePosturePolicyCounts" });
16256
+ var StorePosturePlugin = external_exports.object({
16257
+ /** Package name of the reporting plugin. */
16258
+ package: external_exports.string().min(1).max(200),
16259
+ version: external_exports.string().min(1).max(64),
16260
+ /** Version of the bundled core, when the build records one separately. */
16261
+ ossVersion: external_exports.string().max(64).nullable(),
16262
+ /**
16263
+ * `version` of the policy bundle this machine last fetched. Bounded at 200
16264
+ * rather than the 64 a bare sha256 hex digest needs today, so a later
16265
+ * format with an algorithm prefix does not start rejecting the channel.
16266
+ */
16267
+ policyBundleVersion: external_exports.string().max(200).nullable(),
16268
+ /** Epoch millis, on the CLIENT clock, of that fetch. */
16269
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
16270
+ }).meta({ id: "StorePosturePlugin" });
16271
+ var StorePostureSnapshot = external_exports.object({
16272
+ deviceId: external_exports.guid(),
16273
+ hostname: external_exports.string().min(1).max(253),
16274
+ // Epoch millis on the CLIENT clock. Bounded by what a receiving store
16275
+ // accepts (see MAX_DATE_MS), not by what a JavaScript Date can hold.
16276
+ capturedAt: external_exports.number().int().min(0).max(MAX_DATE_MS),
16277
+ // False is a measurement, not an error state: "no local store exists on
16278
+ // this machine".
16279
+ storePresent: external_exports.boolean(),
16280
+ schemaVersion: external_exports.number().int().min(0).max(MAX_INT4).nullable(),
16281
+ // PRAGMA user_version
16282
+ findingsTotal: external_exports.number().int().min(0).max(MAX_INT4),
16283
+ // Epoch millis, bounded like `capturedAt` — see MAX_DATE_MS on what that
16284
+ // bound does and does not do. Worth stating for these two specifically:
16285
+ // they are read from the local store's own ROWS rather than from this
16286
+ // machine's clock, so a damaged or hand-edited store is enough to produce
16287
+ // an out-of-range value with no clock skew involved.
16288
+ findingsFirstAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16289
+ findingsLastAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
16290
+ packs: external_exports.array(StorePosturePack).max(500),
16291
+ policyCounts: StorePosturePolicyCounts,
16292
+ // OPTIONAL, not nullable: a reporter that predates this member keeps
16293
+ // getting its 200 without a payload change.
16294
+ plugin: StorePosturePlugin.optional()
16295
+ }).meta({ id: "StorePostureSnapshot" });
16296
+ var CAPTURE_VERSION_PREFIX = "capture/";
16297
+ var RecordAuditEventRequest = AuditEventInput.extend({
16298
+ inspections: external_exports.array(ToolCallInspection).default([])
16299
+ }).refine((v) => v.inspections.every((i) => !i.ruleVersion.startsWith(CAPTURE_VERSION_PREFIX)), {
16300
+ message: `inspections[].ruleVersion must not start with \`${CAPTURE_VERSION_PREFIX}\` \u2014 that namespace is reserved for capture definitions the control plane mints itself`,
16301
+ path: ["inspections"]
16302
+ }).meta({ id: "RecordAuditEventRequest" });
16303
+ var IngestAck = external_exports.object({
16304
+ accepted: external_exports.number().int().nonnegative(),
16305
+ duplicates: external_exports.number().int().nonnegative()
16306
+ });
16307
+ var PRINTABLE = /^[^\p{Cc}\p{Cf}]*$/u;
16308
+ var printable = (max) => external_exports.string().max(max).regex(PRINTABLE, "must not contain control characters");
16309
+ var PluginWhoami = external_exports.object({
16310
+ tenantName: printable(200),
16311
+ userEmail: printable(320),
16312
+ role: printable(64),
16313
+ keyKind: printable(64),
16314
+ serverTime: printable(64)
16315
+ });
16316
+ var ControlPlaneErrorBody = external_exports.object({
16317
+ error: external_exports.object({
16318
+ code: external_exports.string().optional(),
16319
+ message: external_exports.string().optional()
16320
+ }).optional()
16321
+ });
16322
+
16205
16323
  // ../../packages/schema/src/zod/registry.ts
16206
16324
  var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
16207
16325
  var PackId = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
@@ -16504,15 +16622,15 @@ function summaryToDetectionListItem(s) {
16504
16622
  }
16505
16623
  function rowToDetectionDetail(row, findingsLast30d, update) {
16506
16624
  const rules = row.rules.flatMap((r) => {
16507
- const parsed = Matcher.safeParse(r.matcher);
16508
- if (!parsed.success) return [];
16625
+ const parsed2 = Matcher.safeParse(r.matcher);
16626
+ if (!parsed2.success) return [];
16509
16627
  return [
16510
16628
  {
16511
16629
  id: r.id,
16512
16630
  name: r.name,
16513
16631
  category: r.category,
16514
16632
  severity: r.severity,
16515
- matcher: parsed.data
16633
+ matcher: parsed2.data
16516
16634
  }
16517
16635
  ];
16518
16636
  });
@@ -17158,8 +17276,8 @@ function toApiAction(dbVal) {
17158
17276
  }
17159
17277
  function toApiCategory(dbVal) {
17160
17278
  if (dbVal === "code_context") return "source_code";
17161
- const parsed = FindingCategory.safeParse(dbVal);
17162
- return parsed.success ? parsed.data : "custom";
17279
+ const parsed2 = FindingCategory.safeParse(dbVal);
17280
+ return parsed2.success ? parsed2.data : "custom";
17163
17281
  }
17164
17282
  function toApiProvider(sourceTool) {
17165
17283
  return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
@@ -17789,6 +17907,9 @@ var WorkspaceSettings = external_exports.object({
17789
17907
  function defaultWorkspaceSettings() {
17790
17908
  return WorkspaceSettings.parse({});
17791
17909
  }
17910
+ function isAttached(settings) {
17911
+ return settings.runMode === "attached" && settings.controlPlane !== void 0;
17912
+ }
17792
17913
  function toInventoryRow(input, id, now) {
17793
17914
  return {
17794
17915
  id,
@@ -18056,8 +18177,8 @@ function builtinPolicyIsReversible(id) {
18056
18177
  return BUILTIN_POLICY_SPECS[id].reversible;
18057
18178
  }
18058
18179
  function policyIdIsReversible(policyId) {
18059
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18060
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18180
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18181
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18061
18182
  return builtinPolicyIsReversible(id);
18062
18183
  }
18063
18184
  var DEFAULT_ACTIONS = Object.fromEntries(
@@ -18068,8 +18189,8 @@ var BUILTIN_POLICIES = Object.fromEntries(
18068
18189
  );
18069
18190
  var DEFAULT_PACK_POLICY_ID = "monitor";
18070
18191
  function policyIdToAction(policyId) {
18071
- const parsed = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18072
- const id = parsed.success ? parsed.data : DEFAULT_PACK_POLICY_ID;
18192
+ const parsed2 = BuiltinPolicyId.safeParse(policyId ?? DEFAULT_PACK_POLICY_ID);
18193
+ const id = parsed2.success ? parsed2.data : DEFAULT_PACK_POLICY_ID;
18073
18194
  return BUILTIN_POLICIES[id].action;
18074
18195
  }
18075
18196
  var UsedByItem = external_exports.object({
@@ -18512,53 +18633,6 @@ function reviewSeverityRank(reasons) {
18512
18633
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
18513
18634
  }
18514
18635
 
18515
- // ../../packages/persistence/src/ids.ts
18516
- import { createHash } from "crypto";
18517
- function sha256Hex(input) {
18518
- return createHash("sha256").update(input).digest("hex");
18519
- }
18520
- function inventoryId(objectType, identityKey) {
18521
- return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18522
- }
18523
- function sourceProjectId(url2) {
18524
- return sha256Hex(canonicalIdentity(["source_project", url2]));
18525
- }
18526
- function classifiedDataId(cls) {
18527
- return sha256Hex(canonicalIdentity(["classified_data", cls]));
18528
- }
18529
- function inspectionDefinitionId(ruleId, version2) {
18530
- return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18531
- }
18532
- function llmCallId(sessionId, messageId) {
18533
- return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18534
- }
18535
- function toolCallId(sessionId, toolUseId) {
18536
- return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18537
- }
18538
- function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18539
- return sha256Hex(
18540
- canonicalIdentity([
18541
- "inspection_finding",
18542
- auditEventId,
18543
- ruleId,
18544
- String(spanStart),
18545
- String(spanEnd)
18546
- ])
18547
- );
18548
- }
18549
- var NO_SESSION = "no_session";
18550
- var NO_PATH = "no_path";
18551
- function captureId(sessionId, contentHash, filePath = null) {
18552
- return sha256Hex(
18553
- canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18554
- );
18555
- }
18556
-
18557
- // ../../packages/persistence/src/internal/snapshot.ts
18558
- import { randomUUID } from "crypto";
18559
- import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
18560
- import { basename, dirname, join } from "path";
18561
-
18562
18636
  // ../../packages/persistence/src/paths.ts
18563
18637
  import {
18564
18638
  chmodSync,
@@ -18609,6 +18683,23 @@ function tightenPerms(file2) {
18609
18683
  function writeExclusiveOwnerOnlySync(file2, data) {
18610
18684
  writeFileSync(file2, data, { mode: DATA_FILE_MODE, flag: "wx" });
18611
18685
  }
18686
+ function writeOwnerOnlyFileSync(file2, data) {
18687
+ const tmp = `${file2}.${String(process.pid)}.tmp`;
18688
+ try {
18689
+ rmSync(tmp, { force: true });
18690
+ } catch {
18691
+ }
18692
+ try {
18693
+ writeExclusiveOwnerOnlySync(tmp, data);
18694
+ renameSync(tmp, file2);
18695
+ } finally {
18696
+ try {
18697
+ rmSync(tmp, { force: true });
18698
+ } catch {
18699
+ }
18700
+ }
18701
+ tightenFile(file2);
18702
+ }
18612
18703
  function classifyOccupant(file2) {
18613
18704
  try {
18614
18705
  if (lstatSync(file2).isSymbolicLink()) return { kind: "symlink" };
@@ -18667,7 +18758,123 @@ function publishByLink(tmp, file2, data) {
18667
18758
  }
18668
18759
  }
18669
18760
 
18761
+ // ../../packages/persistence/src/control-plane-credential.ts
18762
+ function controlPlaneCredentialPath(settingsDir2) {
18763
+ return join(settingsDir2, ATTACHED_CREDENTIAL_FILENAME);
18764
+ }
18765
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
18766
+ function isSafeEndpoint(endpoint) {
18767
+ let parsed2;
18768
+ try {
18769
+ parsed2 = new URL(endpoint);
18770
+ } catch {
18771
+ return false;
18772
+ }
18773
+ if (parsed2.protocol === "https:") return true;
18774
+ return parsed2.protocol === "http:" && LOOPBACK_HOSTS.has(parsed2.hostname);
18775
+ }
18776
+ function repairOrRefuseMode(file2) {
18777
+ const link = lstatSync2(file2, { throwIfNoEntry: false });
18778
+ if (link === void 0) return "absent";
18779
+ if (link.isSymbolicLink()) return "untrusted";
18780
+ const stat = statSync(file2, { throwIfNoEntry: false });
18781
+ if (stat === void 0) return "absent";
18782
+ const uid = process.getuid?.();
18783
+ if (uid !== void 0 && stat.uid !== uid) return "untrusted";
18784
+ if (process.platform !== "win32" && (stat.mode & 511) !== DATA_FILE_MODE) {
18785
+ try {
18786
+ chmodSync2(file2, DATA_FILE_MODE);
18787
+ } catch {
18788
+ return "untrusted";
18789
+ }
18790
+ }
18791
+ return "ok";
18792
+ }
18793
+ function readControlPlaneCredentialState(settingsDir2, connection) {
18794
+ const file2 = controlPlaneCredentialPath(settingsDir2);
18795
+ let raw;
18796
+ const gate = repairOrRefuseMode(file2);
18797
+ if (gate === "absent") return { usable: false, reason: "absent" };
18798
+ if (gate === "untrusted") return { usable: false, reason: "untrusted-file" };
18799
+ try {
18800
+ raw = readFileSync(file2, "utf8");
18801
+ } catch (err) {
18802
+ const code = err.code;
18803
+ return { usable: false, reason: code === "ENOENT" ? "absent" : "unreadable" };
18804
+ }
18805
+ let parsed2;
18806
+ try {
18807
+ parsed2 = JSON.parse(raw);
18808
+ } catch {
18809
+ return { usable: false, reason: "malformed" };
18810
+ }
18811
+ const result = AttachedCredential.safeParse(parsed2);
18812
+ if (!result.success) return { usable: false, reason: "malformed" };
18813
+ if (!isSafeEndpoint(result.data.endpoint)) {
18814
+ return { usable: false, reason: "unsafe-endpoint" };
18815
+ }
18816
+ if (connection !== void 0 && connection.endpoint !== result.data.endpoint) {
18817
+ return {
18818
+ usable: false,
18819
+ reason: "endpoint-mismatch",
18820
+ credentialEndpoint: result.data.endpoint,
18821
+ settingsEndpoint: connection.endpoint
18822
+ };
18823
+ }
18824
+ return { usable: true, credential: result.data };
18825
+ }
18826
+
18827
+ // ../../packages/persistence/src/database.ts
18828
+ import { randomUUID as randomUUID10 } from "crypto";
18829
+ import { join as join3, sep } from "path";
18830
+ import { DatabaseSync } from "node:sqlite";
18831
+
18832
+ // ../../packages/persistence/src/ids.ts
18833
+ import { createHash } from "crypto";
18834
+ function sha256Hex(input) {
18835
+ return createHash("sha256").update(input).digest("hex");
18836
+ }
18837
+ function inventoryId(objectType, identityKey) {
18838
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18839
+ }
18840
+ function sourceProjectId(url2) {
18841
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
18842
+ }
18843
+ function classifiedDataId(cls) {
18844
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
18845
+ }
18846
+ function inspectionDefinitionId(ruleId, version2) {
18847
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18848
+ }
18849
+ function llmCallId(sessionId, messageId) {
18850
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18851
+ }
18852
+ function toolCallId(sessionId, toolUseId) {
18853
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18854
+ }
18855
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
18856
+ return sha256Hex(
18857
+ canonicalIdentity([
18858
+ "inspection_finding",
18859
+ auditEventId,
18860
+ ruleId,
18861
+ String(spanStart),
18862
+ String(spanEnd)
18863
+ ])
18864
+ );
18865
+ }
18866
+ var NO_SESSION = "no_session";
18867
+ var NO_PATH = "no_path";
18868
+ function captureId(sessionId, contentHash, filePath = null) {
18869
+ return sha256Hex(
18870
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
18871
+ );
18872
+ }
18873
+
18670
18874
  // ../../packages/persistence/src/internal/snapshot.ts
18875
+ import { randomUUID } from "crypto";
18876
+ import { existsSync, readdirSync, renameSync as renameSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
18877
+ import { basename, dirname, join as join2 } from "path";
18671
18878
  function backupPath(file2, tag) {
18672
18879
  return `${file2}.${tag}.${String(Date.now())}.${randomUUID().slice(0, 8)}.bak`;
18673
18880
  }
@@ -18677,15 +18884,15 @@ var STAGED_NAME_SUFFIX = `.bak${SNAPSHOT_STAGING_SUFFIX}`;
18677
18884
  var SNAPSHOT_STAGING_COPY = "copy";
18678
18885
  function createSnapshotStaging(backup) {
18679
18886
  const stage = `${backup}${SNAPSHOT_STAGING_SUFFIX}`;
18680
- rmSync2(stage, { recursive: true, force: true });
18887
+ rmSync3(stage, { recursive: true, force: true });
18681
18888
  mkdirOwnerOnlySync(stage);
18682
18889
  tightenDir(stage);
18683
- return { stage, copy: join(stage, SNAPSHOT_STAGING_COPY) };
18890
+ return { stage, copy: join2(stage, SNAPSHOT_STAGING_COPY) };
18684
18891
  }
18685
18892
  function idleMs(entry) {
18686
- for (const candidate of [join(entry, SNAPSHOT_STAGING_COPY), entry]) {
18893
+ for (const candidate of [join2(entry, SNAPSHOT_STAGING_COPY), entry]) {
18687
18894
  try {
18688
- return Date.now() - statSync(candidate).mtimeMs;
18895
+ return Date.now() - statSync2(candidate).mtimeMs;
18689
18896
  } catch {
18690
18897
  }
18691
18898
  }
@@ -18702,11 +18909,11 @@ function reapStalePartials(file2) {
18702
18909
  }
18703
18910
  for (const name of entries) {
18704
18911
  if (!name.startsWith(prefix) || !name.endsWith(STAGED_NAME_SUFFIX)) continue;
18705
- const staging = join(dir, name);
18912
+ const staging = join2(dir, name);
18706
18913
  try {
18707
18914
  const idle = idleMs(staging);
18708
18915
  if (idle !== null && idle > STALE_PARTIAL_MS) {
18709
- rmSync2(staging, { recursive: true, force: true });
18916
+ rmSync3(staging, { recursive: true, force: true });
18710
18917
  }
18711
18918
  } catch {
18712
18919
  }
@@ -18720,13 +18927,13 @@ function snapshotStore(db, backup) {
18720
18927
  renameSync2(copy, backup);
18721
18928
  } catch (error51) {
18722
18929
  try {
18723
- rmSync2(stage, { recursive: true, force: true });
18930
+ rmSync3(stage, { recursive: true, force: true });
18724
18931
  } catch {
18725
18932
  }
18726
18933
  throw error51;
18727
18934
  }
18728
18935
  try {
18729
- rmSync2(stage, { recursive: true, force: true });
18936
+ rmSync3(stage, { recursive: true, force: true });
18730
18937
  } catch {
18731
18938
  }
18732
18939
  }
@@ -18741,7 +18948,7 @@ function moveStoreAside(file2, backup) {
18741
18948
  renameSync2(sidecar, moved);
18742
18949
  undo.push([moved, sidecar]);
18743
18950
  } catch {
18744
- rmSync2(sidecar, { force: true });
18951
+ rmSync3(sidecar, { force: true });
18745
18952
  }
18746
18953
  }
18747
18954
  } catch (error51) {
@@ -18757,14 +18964,14 @@ function moveStoreAside(file2, backup) {
18757
18964
  }
18758
18965
  function discardStore(file2, backup) {
18759
18966
  try {
18760
- rmSync2(file2, { force: true });
18967
+ rmSync3(file2, { force: true });
18761
18968
  for (const sidecar of dbSidecars(file2)) {
18762
- rmSync2(sidecar, { force: true });
18969
+ rmSync3(sidecar, { force: true });
18763
18970
  }
18764
18971
  } catch (error51) {
18765
18972
  if (existsSync(file2)) {
18766
18973
  try {
18767
- rmSync2(backup, { force: true });
18974
+ rmSync3(backup, { force: true });
18768
18975
  } catch {
18769
18976
  }
18770
18977
  }
@@ -18996,10 +19203,31 @@ function applyMigrations(db, file2) {
18996
19203
  if (drained) applyLegacyDropMigration(db, file2);
18997
19204
  }
18998
19205
  }
19206
+ function readLegacyTables(db) {
19207
+ let holdsRows = false;
19208
+ const marks = [];
19209
+ for (const table of ["events", "findings"]) {
19210
+ try {
19211
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
19212
+ if (row === void 0) {
19213
+ holdsRows = true;
19214
+ marks.push(`${table}:unreadable`);
19215
+ continue;
19216
+ }
19217
+ if (row.n > 0) holdsRows = true;
19218
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
19219
+ } catch {
19220
+ holdsRows = true;
19221
+ marks.push(`${table}:unreadable`);
19222
+ }
19223
+ }
19224
+ return { holdsRows, mark: marks.join("|") };
19225
+ }
18999
19226
  function applyLegacyDropMigration(db, file2) {
19000
19227
  const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
19001
19228
  if (!migration) return;
19002
- if (file2) {
19229
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
19230
+ if (file2 !== void 0 && before?.holdsRows === true) {
19003
19231
  try {
19004
19232
  backupBeforeLegacyDrop(db, file2);
19005
19233
  } catch (error51) {
@@ -19013,6 +19241,12 @@ function applyLegacyDropMigration(db, file2) {
19013
19241
  () => {
19014
19242
  const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
19015
19243
  if (alreadyDropped) return;
19244
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
19245
+ akaWarn(
19246
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
19247
+ );
19248
+ return;
19249
+ }
19016
19250
  for (const statement of splitStatements(migration.sql)) {
19017
19251
  db.exec(statement);
19018
19252
  }
@@ -19367,8 +19601,8 @@ function safeJson(s, fallback) {
19367
19601
  function parseJsonObject(s) {
19368
19602
  if (s == null) return void 0;
19369
19603
  try {
19370
- const parsed = JSON.parse(s);
19371
- if (typeof parsed === "object" && parsed !== null) return parsed;
19604
+ const parsed2 = JSON.parse(s);
19605
+ if (typeof parsed2 === "object" && parsed2 !== null) return parsed2;
19372
19606
  } catch {
19373
19607
  }
19374
19608
  return void 0;
@@ -19379,16 +19613,16 @@ function encodeKeysetCursor(payload) {
19379
19613
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
19380
19614
  }
19381
19615
  function decodeKeysetCursor(cursor) {
19382
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19383
- if (parsed !== void 0 && "startedAtMs" in parsed && "id" in parsed && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19616
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
19617
+ if (parsed2 !== void 0 && "startedAtMs" in parsed2 && "id" in parsed2 && // `Number.isInteger`, not `typeof === 'number'`. Every timestamp this
19384
19618
  // resumes from is epoch millis, and a payload carrying ±Infinity or a
19385
19619
  // fraction binds cleanly rather than failing — returning an EMPTY page with
19386
19620
  // a null cursor, which a caller reads as "end of list". That is the one
19387
19621
  // outcome a cursor that does not decode must never produce, since the
19388
19622
  // documented behaviour above is to restart from the top. (`1e999` is valid
19389
19623
  // JSON and parses to Infinity; a bare `NaN` is not, so it cannot arrive.)
19390
- Number.isInteger(parsed.startedAtMs) && typeof parsed.id === "string") {
19391
- return parsed;
19624
+ Number.isInteger(parsed2.startedAtMs) && typeof parsed2.id === "string") {
19625
+ return parsed2;
19392
19626
  }
19393
19627
  return null;
19394
19628
  }
@@ -19453,18 +19687,18 @@ var DB_EVENT_TYPE_TO_KIND = {
19453
19687
  };
19454
19688
  function safeParseStringArray(raw) {
19455
19689
  if (!raw) return [];
19456
- const parsed = safeJson(raw, null);
19457
- return Array.isArray(parsed) ? parsed : [];
19690
+ const parsed2 = safeJson(raw, null);
19691
+ return Array.isArray(parsed2) ? parsed2 : [];
19458
19692
  }
19459
19693
  var DEFAULT_HARNESS = HARNESS.ClaudeCode;
19460
19694
  function toHarness(raw) {
19461
- const parsed = Harness.safeParse(raw);
19462
- return parsed.success ? parsed.data : DEFAULT_HARNESS;
19695
+ const parsed2 = Harness.safeParse(raw);
19696
+ return parsed2.success ? parsed2.data : DEFAULT_HARNESS;
19463
19697
  }
19464
19698
  function resolveLifecycle(row, lastActivityMs, nowMs) {
19465
19699
  if (row.status) {
19466
- const parsed = SessionStatus.safeParse(row.status);
19467
- if (parsed.success) return { status: parsed.data, endedAtMs: row.ended_at };
19700
+ const parsed2 = SessionStatus.safeParse(row.status);
19701
+ if (parsed2.success) return { status: parsed2.data, endedAtMs: row.ended_at };
19468
19702
  }
19469
19703
  if (row.ended_at !== null) return { status: "completed", endedAtMs: row.ended_at };
19470
19704
  if (lastActivityMs >= nowMs - LIVE_ACTIVITY_WINDOW_MS) {
@@ -20423,9 +20657,9 @@ var SqliteDetectionsRepository = class {
20423
20657
  const ruleIds = /* @__PURE__ */ new Set();
20424
20658
  for (const r of rows) {
20425
20659
  if (intToBool(r.enabled)) active += 1;
20426
- const parsed = parseRules(r.rulesJson);
20427
- rules += parsed.length;
20428
- for (const rule of parsed) {
20660
+ const parsed2 = parseRules(r.rulesJson);
20661
+ rules += parsed2.length;
20662
+ for (const rule of parsed2) {
20429
20663
  if (typeof rule.id === "string") ruleIds.add(rule.id);
20430
20664
  }
20431
20665
  }
@@ -20959,12 +21193,12 @@ function encodeGroupCursor(group) {
20959
21193
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
20960
21194
  }
20961
21195
  function decodeGroupCursor(cursor) {
20962
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
20963
- if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.id === "string") {
21196
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
21197
+ if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.id === "string") {
20964
21198
  return {
20965
- severity: parsed.sev,
20966
- latestDetectedAt: parsed.t,
20967
- id: parsed.id
21199
+ severity: parsed2.sev,
21200
+ latestDetectedAt: parsed2.t,
21201
+ id: parsed2.id
20968
21202
  };
20969
21203
  }
20970
21204
  return null;
@@ -22098,16 +22332,16 @@ var SqliteInstalledPacksRepository = class {
22098
22332
  continue;
22099
22333
  }
22100
22334
  for (const entry of raw) {
22101
- const parsed = Rule.safeParse(entry);
22102
- if (parsed.success) {
22103
- out.rules.push(parsed.data);
22104
- out.ruleActions.set(parsed.data.id, action);
22105
- out.ruleVersions.set(parsed.data.id, row.version);
22106
- if (reversible) out.reversibleRules.add(parsed.data.id);
22107
- else out.reversibleRules.delete(parsed.data.id);
22335
+ const parsed2 = Rule.safeParse(entry);
22336
+ if (parsed2.success) {
22337
+ out.rules.push(parsed2.data);
22338
+ out.ruleActions.set(parsed2.data.id, action);
22339
+ out.ruleVersions.set(parsed2.data.id, row.version);
22340
+ if (reversible) out.reversibleRules.add(parsed2.data.id);
22341
+ else out.reversibleRules.delete(parsed2.data.id);
22108
22342
  } else {
22109
22343
  out.invalidRules += 1;
22110
- reject(pack, printableRuleId(entry), firstIssueReason(parsed.error));
22344
+ reject(pack, printableRuleId(entry), firstIssueReason(parsed2.error));
22111
22345
  }
22112
22346
  }
22113
22347
  }
@@ -23497,15 +23731,15 @@ function encodeReuseCursor(payload) {
23497
23731
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
23498
23732
  }
23499
23733
  function decodeReuseCursor(cursor) {
23500
- const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23501
- if (parsed !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23734
+ const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
23735
+ if (parsed2 !== void 0 && // `Number.isInteger`, not `typeof === 'number'`: a payload carrying
23502
23736
  // ±Infinity or a fraction binds cleanly and returns an EMPTY page with a
23503
23737
  // null cursor, which the caller reads as "end of list" — the one outcome a
23504
23738
  // malformed cursor must never produce, since restarting from the top is the
23505
23739
  // documented behaviour and the only recoverable one. (`1e999` is valid JSON
23506
23740
  // and parses to Infinity; a bare `NaN` is not, so it cannot arrive here.)
23507
- Number.isInteger(parsed.occurrences) && typeof parsed.pointerId === "string") {
23508
- return { occurrences: parsed.occurrences, pointerId: parsed.pointerId };
23741
+ Number.isInteger(parsed2.occurrences) && typeof parsed2.pointerId === "string") {
23742
+ return { occurrences: parsed2.occurrences, pointerId: parsed2.pointerId };
23509
23743
  }
23510
23744
  return null;
23511
23745
  }
@@ -25234,7 +25468,7 @@ function openAndInitialize(file2) {
25234
25468
  }
25235
25469
  function openLocalDatabase(dir) {
25236
25470
  ensureDataDirSync(dir);
25237
- const file2 = join2(dir, DB_FILENAME);
25471
+ const file2 = join3(dir, DB_FILENAME);
25238
25472
  reapStalePartials(file2);
25239
25473
  const {
25240
25474
  db,
@@ -25470,9 +25704,9 @@ import {
25470
25704
  closeSync,
25471
25705
  existsSync as existsSync2,
25472
25706
  openSync,
25473
- readFileSync,
25474
- rmSync as rmSync3,
25475
- statSync as statSync2,
25707
+ readFileSync as readFileSync2,
25708
+ rmSync as rmSync4,
25709
+ statSync as statSync3,
25476
25710
  writeFileSync as writeFileSync2
25477
25711
  } from "fs";
25478
25712
  import { hostname as hostname3 } from "os";
@@ -25490,20 +25724,20 @@ function computeFindingKey(input) {
25490
25724
 
25491
25725
  // ../../packages/persistence/src/fingerprint.ts
25492
25726
  import { createHmac, randomBytes } from "crypto";
25493
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
25494
- import { join as join3 } from "path";
25727
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
25728
+ import { join as join4 } from "path";
25495
25729
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
25496
25730
  var EXCEPTION_KEY_FILENAME = "exception.key";
25497
25731
  var KEY_MATERIAL_BYTES = 32;
25498
25732
  function keyFilePath(dataDir2) {
25499
- return join3(dataDir2, EXCEPTION_KEY_FILENAME);
25733
+ return join4(dataDir2, EXCEPTION_KEY_FILENAME);
25500
25734
  }
25501
25735
  function parseKeyFile(raw) {
25502
- const parsed = JSON.parse(raw);
25503
- if (typeof parsed !== "object" || parsed === null) {
25736
+ const parsed2 = JSON.parse(raw);
25737
+ if (typeof parsed2 !== "object" || parsed2 === null) {
25504
25738
  throw new Error("exception key file is corrupt: not a JSON object");
25505
25739
  }
25506
- const { version: version2, material } = parsed;
25740
+ const { version: version2, material } = parsed2;
25507
25741
  if (typeof version2 !== "number" || !Number.isInteger(version2) || version2 < 1) {
25508
25742
  throw new Error("exception key file is corrupt: bad version");
25509
25743
  }
@@ -25534,7 +25768,7 @@ var FloorUnreadableError = class extends Error {
25534
25768
  }
25535
25769
  };
25536
25770
  function storedKeyVersionFloor(dataDir2) {
25537
- const file2 = join3(dataDir2, DB_FILENAME);
25771
+ const file2 = join4(dataDir2, DB_FILENAME);
25538
25772
  if (!existsSync3(file2)) return 0;
25539
25773
  let db;
25540
25774
  try {
@@ -25589,7 +25823,7 @@ function occupantMessage(file2, kind) {
25589
25823
  function readFingerprintKey(dataDir2) {
25590
25824
  let raw;
25591
25825
  try {
25592
- raw = readFileSync2(keyFilePath(dataDir2), "utf8");
25826
+ raw = readFileSync3(keyFilePath(dataDir2), "utf8");
25593
25827
  } catch (err) {
25594
25828
  if (err.code === "ENOENT") return null;
25595
25829
  throw err instanceof Error ? err : new Error(String(err));
@@ -25615,18 +25849,25 @@ function fingerprintValue(key, raw) {
25615
25849
  import { renameSync as renameSync3 } from "fs";
25616
25850
  import { mkdir } from "fs/promises";
25617
25851
  import { homedir } from "os";
25618
- import { join as join4 } from "path";
25852
+ import { join as join5 } from "path";
25619
25853
  function defaultDataDir() {
25620
- return join4(homedir(), ".aka");
25854
+ return join5(homedir(), ".aka");
25621
25855
  }
25622
25856
  function settingsDir(base = defaultDataDir()) {
25623
- return join4(base, "settings");
25857
+ return join5(base, "settings");
25624
25858
  }
25625
25859
  function dataDir(base = defaultDataDir()) {
25626
- return join4(base, "data");
25860
+ return join5(base, "data");
25627
25861
  }
25628
25862
  function dbPath(base = defaultDataDir()) {
25629
- return join4(dataDir(base), "aka.db");
25863
+ return join5(dataDir(base), "aka.db");
25864
+ }
25865
+ function keysDir(base = defaultDataDir()) {
25866
+ return join5(base, "keys");
25867
+ }
25868
+ async function ensureDataDir(dir = defaultDataDir()) {
25869
+ await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
25870
+ tightenDir(dir);
25630
25871
  }
25631
25872
  function ensureLayoutDirSync(dir = defaultDataDir()) {
25632
25873
  ensureDataDirSync(dir);
@@ -25639,8 +25880,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25639
25880
  for (const { name, dest } of moves) {
25640
25881
  try {
25641
25882
  ensureDataDirSync(dest);
25642
- const moved = join4(dest, name);
25643
- renameSync3(join4(base, name), moved);
25883
+ const moved = join5(dest, name);
25884
+ renameSync3(join5(base, name), moved);
25644
25885
  tightenFile(moved);
25645
25886
  } catch {
25646
25887
  }
@@ -25648,7 +25889,7 @@ function migrateLegacyLayout(base = defaultDataDir()) {
25648
25889
  }
25649
25890
 
25650
25891
  // ../../packages/persistence/src/managed-settings.ts
25651
- import { readFileSync as readFileSync3 } from "fs";
25892
+ import { readFileSync as readFileSync4 } from "fs";
25652
25893
  import { posix, win32 } from "path";
25653
25894
  function managedSettingsPaths(platform2 = process.platform) {
25654
25895
  if (platform2 === "darwin") {
@@ -25666,14 +25907,14 @@ function readManagedSettings(paths = managedSettingsPaths()) {
25666
25907
  for (const path of paths) {
25667
25908
  let text;
25668
25909
  try {
25669
- text = readFileSync3(path, "utf8");
25910
+ text = readFileSync4(path, "utf8");
25670
25911
  } catch {
25671
25912
  continue;
25672
25913
  }
25673
25914
  const record2 = parseJsonObject(text);
25674
25915
  if (!record2) continue;
25675
- const parsed = ManagedSettings.safeParse(record2);
25676
- if (parsed.success) return parsed.data;
25916
+ const parsed2 = ManagedSettings.safeParse(record2);
25917
+ if (parsed2.success) return parsed2.data;
25677
25918
  }
25678
25919
  return null;
25679
25920
  }
@@ -25713,14 +25954,14 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
25713
25954
  }
25714
25955
 
25715
25956
  // ../../packages/persistence/src/settings.ts
25716
- import { readFileSync as readFileSync4 } from "fs";
25717
- import { join as join5 } from "path";
25957
+ import { readFileSync as readFileSync5 } from "fs";
25958
+ import { join as join6 } from "path";
25718
25959
  var SETTINGS_FILENAME = "settings.json";
25719
25960
  function readWorkspaceSettings(base = defaultDataDir()) {
25720
25961
  return overlayManagedSettings(readUserSettings(base), readManagedSettings());
25721
25962
  }
25722
25963
  function readUserSettings(base) {
25723
- const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
25964
+ const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
25724
25965
  if (!record2) return defaultWorkspaceSettings();
25725
25966
  try {
25726
25967
  return WorkspaceSettings.parse(record2);
@@ -25731,13 +25972,64 @@ function readUserSettings(base) {
25731
25972
  function readJson(file2) {
25732
25973
  let text;
25733
25974
  try {
25734
- text = readFileSync4(file2, "utf8");
25975
+ text = readFileSync5(file2, "utf8");
25735
25976
  } catch {
25736
25977
  return null;
25737
25978
  }
25738
25979
  return parseJsonObject(text) ?? null;
25739
25980
  }
25740
25981
 
25982
+ // ../../packages/persistence/src/store-symlinks.ts
25983
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
25984
+ import { dirname as dirname2, join as join7, resolve } from "path";
25985
+ var STORE_DB = "the store database (including the prompt corpus)";
25986
+ var STORE_SETTINGS = "your settings file";
25987
+ function storeContents(home) {
25988
+ return /* @__PURE__ */ new Map([
25989
+ [home, "the store (including the prompt corpus in aka.db)"],
25990
+ [settingsDir(home), STORE_SETTINGS],
25991
+ [dataDir(home), STORE_DB],
25992
+ [keysDir(home), "the vault key"],
25993
+ [join7(settingsDir(home), "settings.json"), STORE_SETTINGS],
25994
+ [dbPath(home), STORE_DB]
25995
+ ]);
25996
+ }
25997
+ function symlinkedStorePaths(home, platform2 = process.platform) {
25998
+ return [...storeContents(home)].flatMap(([path, holds]) => {
25999
+ try {
26000
+ if (!lstatSync3(path).isSymbolicLink()) return [];
26001
+ return [
26002
+ {
26003
+ path,
26004
+ target: linkTarget(path),
26005
+ holds,
26006
+ // existsSync follows the link, so a target that is gone reads as
26007
+ // absent here while lstat above still sees the link itself.
26008
+ missing: !existsSync4(path),
26009
+ mode: targetMode(path, platform2)
26010
+ }
26011
+ ];
26012
+ } catch {
26013
+ return [];
26014
+ }
26015
+ });
26016
+ }
26017
+ function linkTarget(path) {
26018
+ try {
26019
+ return realpathSync(path);
26020
+ } catch {
26021
+ return resolve(dirname2(path), readlinkSync(path));
26022
+ }
26023
+ }
26024
+ function targetMode(path, platform2) {
26025
+ if (platform2 === "win32") return void 0;
26026
+ try {
26027
+ return statSync4(path).mode & 511;
26028
+ } catch {
26029
+ return void 0;
26030
+ }
26031
+ }
26032
+
25741
26033
  // ../../packages/persistence/src/vault/crypto.ts
25742
26034
  import {
25743
26035
  createCipheriv,
@@ -25750,20 +26042,20 @@ import {
25750
26042
  // ../../packages/persistence/src/vault/key-provider.ts
25751
26043
  import { execFileSync } from "child_process";
25752
26044
  import { randomBytes as randomBytes2 } from "crypto";
25753
- import { chmodSync as chmodSync2, readFileSync as readFileSync5, renameSync as renameSync4, rmSync as rmSync4, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs";
25754
- import { join as join6 } from "path";
26045
+ import { chmodSync as chmodSync3, readFileSync as readFileSync6, renameSync as renameSync4, rmSync as rmSync5, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
26046
+ import { join as join8 } from "path";
25755
26047
 
25756
26048
  // ../../packages/persistence/src/vault/vault.ts
25757
26049
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
25758
26050
 
25759
26051
  // ../../packages/persistence/src/warn-era-cap.ts
25760
- import { existsSync as existsSync4, writeFileSync as writeFileSync4 } from "fs";
25761
- import { join as join7 } from "path";
26052
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
26053
+ import { join as join9 } from "path";
25762
26054
  var MARKER = "warn-era-capped";
25763
26055
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25764
26056
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
25765
- const marker = join7(dataDir2, MARKER);
25766
- if (existsSync4(marker)) return { capped: 0, skipped: "already-run" };
26057
+ const marker = join9(dataDir2, MARKER);
26058
+ if (existsSync5(marker)) return { capped: 0, skipped: "already-run" };
25767
26059
  const capped = db.policies.capCategoryActions();
25768
26060
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
25769
26061
  `, { mode: DATA_FILE_MODE });
@@ -25804,8 +26096,8 @@ function hostOf(url2) {
25804
26096
  }
25805
26097
  }
25806
26098
  function resolveProvider() {
25807
- const parsed = ProviderEnvSchema.safeParse(process.env);
25808
- const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
26099
+ const parsed2 = ProviderEnvSchema.safeParse(process.env);
26100
+ const env = parsed2.success ? parsed2.data : ProviderEnvSchema.parse({});
25809
26101
  if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
25810
26102
  if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
25811
26103
  const baseUrl = env.ANTHROPIC_BASE_URL;
@@ -25822,8 +26114,8 @@ function resolveProvider() {
25822
26114
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
25823
26115
  try {
25824
26116
  ensureLayoutDirSync(base);
25825
- const settingsFile = join8(settingsDir(base), "settings.json");
25826
- if (existsSync5(settingsFile)) tightenFile(settingsFile);
26117
+ const settingsFile = join10(settingsDir(base), "settings.json");
26118
+ if (existsSync6(settingsFile)) tightenFile(settingsFile);
25827
26119
  } catch {
25828
26120
  }
25829
26121
  migrateLegacyLayout(base);
@@ -25846,9 +26138,9 @@ function resolveProviderSafe(resolveProviderFn) {
25846
26138
  }
25847
26139
 
25848
26140
  // ../../packages/plugin-sdk/src/config-inventory.ts
25849
- import { readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync, statSync as statSync5 } from "fs";
26141
+ import { readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
25850
26142
  import { homedir as homedir2 } from "os";
25851
- import { basename as basename3, join as join10 } from "path";
26143
+ import { basename as basename3, join as join12 } from "path";
25852
26144
 
25853
26145
  // ../../packages/detections/src/egress/registry.ts
25854
26146
  var EXTRACTOR_VERSION = "1";
@@ -27625,10 +27917,10 @@ var localhost_ref_default = {
27625
27917
  severity: "low",
27626
27918
  matcher: {
27627
27919
  type: "regex",
27628
- pattern: "\\b(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|::1)\\b",
27920
+ 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_])",
27629
27921
  flags: "g"
27630
27922
  },
27631
- examples: ["localhost", "127.0.0.1"]
27923
+ examples: ["localhost", "127.0.0.1", "0.0.0.0", "::1"]
27632
27924
  };
27633
27925
 
27634
27926
  // ../../rules/core-code-context/stack-trace.json
@@ -28937,8 +29229,8 @@ function bundledDetections() {
28937
29229
  }
28938
29230
 
28939
29231
  // ../../packages/plugin-sdk/src/repo.ts
28940
- import { existsSync as existsSync6, readFileSync as readFileSync6, statSync as statSync4 } from "fs";
28941
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join9, sep as sep2 } from "path";
29232
+ import { existsSync as existsSync7, readFileSync as readFileSync7, statSync as statSync6 } from "fs";
29233
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join11, sep as sep2 } from "path";
28942
29234
  function resolveRepo(cwd) {
28943
29235
  try {
28944
29236
  const root = findGitRoot(cwd);
@@ -28953,36 +29245,36 @@ function resolveRepo(cwd) {
28953
29245
  function findGitRoot(start) {
28954
29246
  let dir = start;
28955
29247
  for (; ; ) {
28956
- if (existsSync6(join9(dir, ".git"))) return dir;
28957
- const parent = dirname2(dir);
29248
+ if (existsSync7(join11(dir, ".git"))) return dir;
29249
+ const parent = dirname3(dir);
28958
29250
  if (parent === dir) return void 0;
28959
29251
  dir = parent;
28960
29252
  }
28961
29253
  }
28962
29254
  function resolveGitContext(root) {
28963
- const dotGit = join9(root, ".git");
29255
+ const dotGit = join11(root, ".git");
28964
29256
  try {
28965
- if (statSync4(dotGit).isDirectory()) {
28966
- return { configPath: join9(dotGit, "config"), headRoot: root };
29257
+ if (statSync6(dotGit).isDirectory()) {
29258
+ return { configPath: join11(dotGit, "config"), headRoot: root };
28967
29259
  }
28968
29260
  } catch {
28969
29261
  return void 0;
28970
29262
  }
28971
29263
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
28972
29264
  if (!target) return void 0;
28973
- const gitdir = isAbsolute(target) ? target : join9(root, target);
28974
- if (existsSync6(join9(gitdir, "config"))) {
28975
- return { configPath: join9(gitdir, "config"), headRoot: root };
29265
+ const gitdir = isAbsolute(target) ? target : join11(root, target);
29266
+ if (existsSync7(join11(gitdir, "config"))) {
29267
+ return { configPath: join11(gitdir, "config"), headRoot: root };
28976
29268
  }
28977
- const commonRaw = safeRead(join9(gitdir, "commondir"))?.trim();
29269
+ const commonRaw = safeRead(join11(gitdir, "commondir"))?.trim();
28978
29270
  if (!commonRaw) return void 0;
28979
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join9(gitdir, commonRaw);
28980
- const headRoot = basename2(commonGitDir) === ".git" ? dirname2(commonGitDir) : root;
28981
- return { configPath: join9(commonGitDir, "config"), headRoot };
29271
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join11(gitdir, commonRaw);
29272
+ const headRoot = basename2(commonGitDir) === ".git" ? dirname3(commonGitDir) : root;
29273
+ return { configPath: join11(commonGitDir, "config"), headRoot };
28982
29274
  }
28983
29275
  function safeRead(path) {
28984
29276
  try {
28985
- return readFileSync6(path, "utf8");
29277
+ return readFileSync7(path, "utf8");
28986
29278
  } catch {
28987
29279
  return void 0;
28988
29280
  }
@@ -29043,7 +29335,7 @@ function buildIngestEvent(input) {
29043
29335
  }
29044
29336
 
29045
29337
  // ../../packages/plugin-sdk/src/isolated-scan.ts
29046
- import { existsSync as existsSync7 } from "fs";
29338
+ import { existsSync as existsSync8 } from "fs";
29047
29339
  import { fileURLToPath } from "url";
29048
29340
  import { Worker } from "worker_threads";
29049
29341
  var ISOLATED_SCAN_BUDGET_MS = 2e3;
@@ -29057,7 +29349,7 @@ function resolveWorkerUrl() {
29057
29349
  for (const name of ["scan-worker.js", "scan-worker.ts"]) {
29058
29350
  const candidate = new URL(name, import.meta.url);
29059
29351
  try {
29060
- if (existsSync7(fileURLToPath(candidate))) {
29352
+ if (existsSync8(fileURLToPath(candidate))) {
29061
29353
  resolvedWorkerUrl = candidate;
29062
29354
  return candidate;
29063
29355
  }
@@ -29242,8 +29534,8 @@ function createIsolatedScanner(data, opts = {}) {
29242
29534
  }
29243
29535
  function enqueue(spec) {
29244
29536
  const next = chain.then(
29245
- () => new Promise((resolve) => {
29246
- spec(resolve);
29537
+ () => new Promise((resolve2) => {
29538
+ spec(resolve2);
29247
29539
  })
29248
29540
  );
29249
29541
  chain = next.then(
@@ -29254,7 +29546,7 @@ function createIsolatedScanner(data, opts = {}) {
29254
29546
  }
29255
29547
  return {
29256
29548
  scan(text, context, scanOpts) {
29257
- return enqueue((resolve) => {
29549
+ return enqueue((resolve2) => {
29258
29550
  runOne(
29259
29551
  {
29260
29552
  budgetMs,
@@ -29267,23 +29559,23 @@ function createIsolatedScanner(data, opts = {}) {
29267
29559
  }),
29268
29560
  reply: (message) => {
29269
29561
  if (message.kind !== "result") return false;
29270
- resolve({ status: "ok", findings: message.findings });
29562
+ resolve2({ status: "ok", findings: message.findings });
29271
29563
  return true;
29272
29564
  }
29273
29565
  },
29274
- resolve
29566
+ resolve2
29275
29567
  );
29276
29568
  });
29277
29569
  },
29278
29570
  probe(rule) {
29279
- return enqueue((resolve) => {
29571
+ return enqueue((resolve2) => {
29280
29572
  runOne(
29281
29573
  {
29282
29574
  budgetMs: probeBudgetMs,
29283
29575
  build: (id) => ({ kind: "probe", id, rule }),
29284
29576
  reply: (message) => {
29285
29577
  if (message.kind !== "probed") return false;
29286
- resolve({
29578
+ resolve2({
29287
29579
  status: "ok",
29288
29580
  verdict: message.verdict,
29289
29581
  worstMs: message.worstMs,
@@ -29292,7 +29584,7 @@ function createIsolatedScanner(data, opts = {}) {
29292
29584
  return true;
29293
29585
  }
29294
29586
  },
29295
- resolve
29587
+ resolve2
29296
29588
  );
29297
29589
  });
29298
29590
  },
@@ -29522,23 +29814,23 @@ function createGuardedScanner(partition, gateway, opts) {
29522
29814
 
29523
29815
  // ../../packages/plugin-sdk/src/ignore-layers.ts
29524
29816
  var import_ignore = __toESM(require_ignore(), 1);
29525
- import { readFileSync as readFileSync8 } from "fs";
29526
- import { join as join11 } from "path";
29817
+ import { readFileSync as readFileSync9 } from "fs";
29818
+ import { join as join13 } from "path";
29527
29819
 
29528
29820
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
29529
29821
  import { arch, hostname as hostname4, platform, release } from "os";
29530
29822
 
29531
29823
  // ../../packages/plugin-sdk/src/nudge.ts
29532
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
29533
- import { join as join12 } from "path";
29824
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
29825
+ import { join as join14 } from "path";
29534
29826
 
29535
29827
  // ../../packages/plugin-sdk/src/paths.ts
29536
- import { readdirSync as readdirSync3, realpathSync as realpathSync2 } from "fs";
29537
- import { basename as basename4, dirname as dirname3, sep as sep3 } from "path";
29828
+ import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
29829
+ import { basename as basename4, dirname as dirname4, sep as sep3 } from "path";
29538
29830
 
29539
29831
  // ../../packages/plugin-sdk/src/project-files.ts
29540
- import { existsSync as existsSync8, readdirSync as readdirSync4 } from "fs";
29541
- import { basename as basename5, join as join13 } from "path";
29832
+ import { existsSync as existsSync9, readdirSync as readdirSync4 } from "fs";
29833
+ import { basename as basename5, join as join15 } from "path";
29542
29834
 
29543
29835
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
29544
29836
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -29909,8 +30201,8 @@ function createPluginRuntime(gateway, settings, opts) {
29909
30201
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
29910
30202
 
29911
30203
  // ../../packages/plugin-sdk/src/throttle.ts
29912
- import { mkdirSync as mkdirSync3, statSync as statSync6, writeFileSync as writeFileSync6 } from "fs";
29913
- import { join as join14 } from "path";
30204
+ import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
30205
+ import { join as join16 } from "path";
29914
30206
 
29915
30207
  // src/present.ts
29916
30208
  var fg = (hex3) => (text) => {
@@ -30046,7 +30338,7 @@ function decidePreToolUse(toolName, toolInput, scanned) {
30046
30338
 
30047
30339
  // src/hooks/shared.ts
30048
30340
  async function readStdin() {
30049
- return new Promise((resolve) => {
30341
+ return new Promise((resolve2) => {
30050
30342
  let data = "";
30051
30343
  let settled = false;
30052
30344
  const finish = () => {
@@ -30055,7 +30347,7 @@ async function readStdin() {
30055
30347
  clearTimeout(timer);
30056
30348
  process.stdin.removeListener("data", onData);
30057
30349
  process.stdin.removeListener("end", finish);
30058
- resolve(data);
30350
+ resolve2(data);
30059
30351
  };
30060
30352
  const onData = (chunk) => {
30061
30353
  data += chunk;
@@ -30069,8 +30361,8 @@ async function readStdin() {
30069
30361
  }
30070
30362
  function parseJson(raw) {
30071
30363
  try {
30072
- const parsed = JSON.parse(raw);
30073
- return typeof parsed === "object" && parsed !== null ? parsed : null;
30364
+ const parsed2 = JSON.parse(raw);
30365
+ return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
30074
30366
  } catch {
30075
30367
  return null;
30076
30368
  }
@@ -30080,12 +30372,12 @@ function getString(record2, key) {
30080
30372
  return typeof value === "string" ? value : void 0;
30081
30373
  }
30082
30374
  function emit(output) {
30083
- return new Promise((resolve) => {
30375
+ return new Promise((resolve2) => {
30084
30376
  let settled = false;
30085
30377
  const finish = () => {
30086
30378
  if (settled) return;
30087
30379
  settled = true;
30088
- resolve();
30380
+ resolve2();
30089
30381
  };
30090
30382
  process.stdout.on("error", finish);
30091
30383
  process.stdout.write(JSON.stringify(output), finish);
@@ -30101,57 +30393,1247 @@ function baseMetadata(input) {
30101
30393
  }
30102
30394
 
30103
30395
  // src/hooks/store-health.ts
30104
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync7 } from "fs";
30105
- import { join as join15 } from "path";
30396
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync14, writeFileSync as writeFileSync7 } from "fs";
30397
+ import { dirname as dirname5, join as join22 } from "path";
30398
+
30399
+ // ../../packages/plugin-runtime/src/attached/failure.ts
30400
+ function statusOf(err) {
30401
+ if (typeof err !== "object" || err === null || !("status" in err)) return null;
30402
+ const { status } = err;
30403
+ if (typeof status !== "number" || !Number.isInteger(status)) return null;
30404
+ return status >= 100 && status <= 599 ? status : null;
30405
+ }
30406
+ function classifyFailure(err) {
30407
+ switch (statusOf(err)) {
30408
+ case 401:
30409
+ return "unauthorized";
30410
+ case 403:
30411
+ return "forbidden";
30412
+ default:
30413
+ return "unreachable";
30414
+ }
30415
+ }
30106
30416
 
30107
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
30108
- import { randomUUID as randomUUID15 } from "crypto";
30417
+ // ../../packages/plugin-runtime/src/attached/forward-drops.ts
30418
+ import { readFileSync as readFileSync11 } from "fs";
30419
+ import { join as join17 } from "path";
30420
+ var FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
30421
+ function forwardDropsPath(dataDir2) {
30422
+ return join17(dataDir2, FORWARD_DROPS_FILENAME);
30423
+ }
30424
+ function recordForwardDrops(dataDir2, count, nowMs) {
30425
+ if (count <= 0) return;
30426
+ try {
30427
+ ensureDataDirSync(dataDir2);
30428
+ const previous = readForwardDrops(dataDir2);
30429
+ const next = {
30430
+ droppedForwards: (previous?.droppedForwards ?? 0) + count,
30431
+ lastDropAtMs: nowMs
30432
+ };
30433
+ writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
30434
+ `);
30435
+ } catch {
30436
+ }
30437
+ }
30438
+ function readForwardDrops(dataDir2) {
30439
+ try {
30440
+ const parsed2 = JSON.parse(readFileSync11(forwardDropsPath(dataDir2), "utf8"));
30441
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30442
+ const record2 = parsed2;
30443
+ if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
30444
+ return null;
30445
+ }
30446
+ if (record2.droppedForwards <= 0) return null;
30447
+ if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
30448
+ return null;
30449
+ }
30450
+ return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
30451
+ } catch {
30452
+ return null;
30453
+ }
30454
+ }
30109
30455
 
30110
- // ../../packages/plugin-runtime/src/recorder.ts
30111
- var PLUGIN_RECORDER_BINARY = "plugin";
30456
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30457
+ import { randomUUID as randomUUID15 } from "crypto";
30458
+ import { readFileSync as readFileSync12 } from "fs";
30459
+ import { readFile, rename, writeFile } from "fs/promises";
30460
+ import { join as join18 } from "path";
30461
+
30462
+ // ../../packages/plugin-runtime/src/attached/with-timeout.ts
30463
+ var REQUEST_TIMEOUT_MS = 2e3;
30464
+ function withTimeout(promise2, ms) {
30465
+ let timer;
30466
+ const timeout = new Promise((_, reject) => {
30467
+ timer = setTimeout(() => {
30468
+ reject(new Error("attached gateway request timed out"));
30469
+ }, ms);
30470
+ });
30471
+ promise2.catch(() => void 0);
30472
+ return Promise.race([promise2, timeout]).finally(() => {
30473
+ clearTimeout(timer);
30474
+ });
30475
+ }
30112
30476
 
30113
- // ../../packages/plugin-runtime/src/standalone-gateway.ts
30114
- var StandaloneDataGateway = class {
30115
- db;
30116
- // Kept for the fingerprint key lookup (exception.key lives beside the store).
30117
- dataDir;
30118
- // One notice per gateway — see warnRulesetDiscarded.
30119
- warnedRulesetDiscarded = false;
30120
- constructor(dataDir2, detections = [], meta3) {
30121
- this.db = openLocalDatabase(dataDir2);
30122
- this.dataDir = dataDir2;
30123
- this.db.installedPacks.recordInventory(detections, meta3);
30124
- }
30125
- recordCapture(record2) {
30126
- this.db.recordCapture(record2.event, record2.findings);
30127
- return Promise.resolve();
30477
+ // ../../packages/plugin-runtime/src/attached/forward-policy.ts
30478
+ function isInvalidRequest(err) {
30479
+ return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
30480
+ }
30481
+ var FORWARD_BUDGET_MS = 1500;
30482
+ var DECISION_PATH_BUDGET_MS = 800;
30483
+ var BREAKER_FAILURE_THRESHOLD = 3;
30484
+ var BREAKER_COOLDOWN_MS = 3e4;
30485
+ var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
30486
+ var FAILURES = /* @__PURE__ */ new Set([
30487
+ "unauthorized",
30488
+ "forbidden",
30489
+ "unreachable"
30490
+ ]);
30491
+ var FORWARD_STATE_FILENAME = "attached-state.json";
30492
+ var STATE_FILENAME = FORWARD_STATE_FILENAME;
30493
+ function parseBreakerState(raw, nowMs) {
30494
+ try {
30495
+ const parsed2 = JSON.parse(raw);
30496
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
30497
+ const record2 = parsed2;
30498
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
30499
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
30500
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
30501
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
30502
+ } catch {
30503
+ return null;
30128
30504
  }
30129
- ensureInventory(ctx) {
30130
- return Promise.resolve(this.db.ensureInventory(ctx));
30505
+ }
30506
+ function createForwardPolicy(deps) {
30507
+ const now = deps.now ?? (() => Date.now());
30508
+ const file2 = join18(deps.dir, STATE_FILENAME);
30509
+ let state = null;
30510
+ let loading = null;
30511
+ async function readState() {
30512
+ let raw;
30513
+ try {
30514
+ raw = await readFile(file2, "utf8");
30515
+ } catch {
30516
+ return { ...CLOSED };
30517
+ }
30518
+ return parseBreakerState(raw, now()) ?? { ...CLOSED };
30131
30519
  }
30132
- recordAuditEvent(event) {
30133
- this.db.auditEvents.insertAuditEvent(event);
30134
- return Promise.resolve();
30520
+ async function load() {
30521
+ if (state !== null) return state;
30522
+ loading ??= readState().then((loaded) => {
30523
+ state = loaded;
30524
+ loading = null;
30525
+ return loaded;
30526
+ });
30527
+ return loading;
30135
30528
  }
30136
- // The id is minted inside the repository from the natural key — the plugin can't
30137
- // import @akasecurity/persistence to compute it, so the gateway is the boundary that
30138
- // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
30139
- // converge a streaming partial/final split (see insertLlmCall).
30140
- recordLlmCall(input) {
30141
- this.db.auditEvents.insertLlmCall(input);
30142
- return Promise.resolve();
30529
+ async function persist(next) {
30530
+ state = next;
30531
+ try {
30532
+ await ensureDataDir(deps.dir);
30533
+ const tmp = `${file2}.${randomUUID15()}.tmp`;
30534
+ await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
30535
+ await rename(tmp, file2);
30536
+ } catch {
30537
+ }
30143
30538
  }
30144
- // One reconcile pass = one transaction. All leaves commit together
30145
- // (single lock + WAL fsync); a contended SQLITE_BUSY rolls back and rejects so the
30539
+ return {
30540
+ async run(op, opts) {
30541
+ const budget = opts?.decisionPath === true ? DECISION_PATH_BUDGET_MS : FORWARD_BUDGET_MS;
30542
+ let current;
30543
+ try {
30544
+ current = await load();
30545
+ } catch {
30546
+ current = { ...CLOSED };
30547
+ }
30548
+ const at = now();
30549
+ if (current.openedAtMs !== null) {
30550
+ if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
30551
+ return { ok: false, reason: "breaker-open" };
30552
+ }
30553
+ await persist({
30554
+ consecutiveFailures: current.consecutiveFailures,
30555
+ openedAtMs: at,
30556
+ lastFailure: current.lastFailure
30557
+ });
30558
+ }
30559
+ try {
30560
+ const value = await withTimeout(op(), budget);
30561
+ if (current.openedAtMs !== null || current.consecutiveFailures > 0) {
30562
+ await persist({ ...CLOSED });
30563
+ }
30564
+ return { ok: true, value };
30565
+ } catch (err) {
30566
+ if (isInvalidRequest(err)) return { ok: false, reason: "invalid-request" };
30567
+ const reason = classifyFailure(err);
30568
+ const failures = current.consecutiveFailures + 1;
30569
+ const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
30570
+ await persist({
30571
+ consecutiveFailures: failures,
30572
+ openedAtMs: shouldOpen ? now() : null,
30573
+ lastFailure: reason
30574
+ });
30575
+ return { ok: false, reason };
30576
+ }
30577
+ }
30578
+ };
30579
+ }
30580
+
30581
+ // ../../packages/plugin-runtime/src/attached/gateway.ts
30582
+ var ACTION_STRENGTH = {
30583
+ allow: 0,
30584
+ log: 1,
30585
+ warn: 2,
30586
+ redact: 3,
30587
+ block: 4
30588
+ };
30589
+ function ruleCategoryMap(wireRules, localRules) {
30590
+ const map2 = /* @__PURE__ */ new Map();
30591
+ for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
30592
+ for (const rule of localRules ?? []) map2.set(rule.id, rule.category);
30593
+ for (const pack of bundledDetections()) {
30594
+ for (const rule of pack.rules) map2.set(rule.id, rule.category);
30595
+ }
30596
+ return map2;
30597
+ }
30598
+ function strongerOf(a, b) {
30599
+ if (a === null) return b;
30600
+ if (b === null) return a;
30601
+ return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
30602
+ }
30603
+ function policyKey(policy) {
30604
+ return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
30605
+ }
30606
+ function floorFor(policy, categoryByRuleId) {
30607
+ const category = "category" in policy.target ? policy.target.category : categoryByRuleId.get(policy.target.ruleId);
30608
+ return category === void 0 ? null : DEFAULT_ACTIONS[category];
30609
+ }
30610
+ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
30611
+ const merged = /* @__PURE__ */ new Map();
30612
+ const disabled = [];
30613
+ const remoteCategoryAction = /* @__PURE__ */ new Map();
30614
+ for (const policy of remotePolicies) {
30615
+ if (!policy.enabled) continue;
30616
+ if (!("category" in policy.target)) continue;
30617
+ if (remoteCategoryAction.has(policy.target.category)) continue;
30618
+ const floor = floorFor(policy, categoryByRuleId);
30619
+ remoteCategoryAction.set(
30620
+ policy.target.category,
30621
+ floor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[floor] ? floor : policy.action
30622
+ );
30623
+ }
30624
+ for (const policy of localPolicies) {
30625
+ if (!policy.enabled) {
30626
+ disabled.push(policy);
30627
+ continue;
30628
+ }
30629
+ const key = policyKey(policy);
30630
+ if (merged.has(key)) continue;
30631
+ let remoteFloor = null;
30632
+ if ("ruleId" in policy.target) {
30633
+ const category = categoryByRuleId.get(policy.target.ruleId);
30634
+ if (category !== void 0) remoteFloor = remoteCategoryAction.get(category) ?? null;
30635
+ }
30636
+ merged.set(
30637
+ key,
30638
+ remoteFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[remoteFloor] ? { ...policy, action: remoteFloor } : policy
30639
+ );
30640
+ }
30641
+ const localCategoryAction = /* @__PURE__ */ new Map();
30642
+ for (const policy of merged.values()) {
30643
+ if ("category" in policy.target) localCategoryAction.set(policy.target.category, policy.action);
30644
+ }
30645
+ for (const policy of remotePolicies) {
30646
+ if (!policy.enabled) {
30647
+ disabled.push(policy);
30648
+ continue;
30649
+ }
30650
+ const key = policyKey(policy);
30651
+ const floor = floorFor(policy, categoryByRuleId);
30652
+ let localFloor = null;
30653
+ if ("ruleId" in policy.target) {
30654
+ const category = categoryByRuleId.get(policy.target.ruleId);
30655
+ if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
30656
+ }
30657
+ const effectiveFloor = strongerOf(floor, localFloor);
30658
+ const clamped = effectiveFloor !== null && ACTION_STRENGTH[policy.action] < ACTION_STRENGTH[effectiveFloor] ? { ...policy, action: effectiveFloor } : policy;
30659
+ const existing = merged.get(key);
30660
+ if (existing === void 0) {
30661
+ merged.set(key, clamped);
30662
+ continue;
30663
+ }
30664
+ if (ACTION_STRENGTH[clamped.action] > ACTION_STRENGTH[existing.action]) {
30665
+ merged.set(key, clamped);
30666
+ }
30667
+ }
30668
+ return [...merged.values(), ...disabled];
30669
+ }
30670
+ var AttachedDataGateway = class {
30671
+ constructor(deps) {
30672
+ this.deps = deps;
30673
+ }
30674
+ deps;
30675
+ /**
30676
+ * The control plane's OWN resolution of this session's inventory, captured by
30677
+ * ensureInventory. Null until the first successful forward — and it stays
30678
+ * null for the whole session when the control plane is unreachable, which is fine:
30679
+ * reKeyForForward then leaves the event's ids alone and the control plane resolves
30680
+ * what it can from the descriptors it already has.
30681
+ */
30682
+ remoteInventory = null;
30683
+ // ---------------------------------------------------------------------
30684
+ // Writes: local first, then forward.
30685
+ // ---------------------------------------------------------------------
30686
+ async recordCapture(record2) {
30687
+ await this.deps.local.recordCapture(record2);
30688
+ await this.deps.forward.run(
30689
+ () => this.deps.client.ingestEvents({
30690
+ events: [record2.event],
30691
+ ...record2.dedupe ? { dedupe: record2.dedupe } : {}
30692
+ }),
30693
+ { decisionPath: true }
30694
+ );
30695
+ }
30696
+ async ensureInventory(ctx) {
30697
+ const resolved = await this.deps.local.ensureInventory(ctx);
30698
+ const remote = await this.deps.forward.run(() => this.deps.client.ingestInventory(ctx));
30699
+ this.remoteInventory = remote.ok ? remote.value : null;
30700
+ const snapshot = await (async () => {
30701
+ try {
30702
+ return await this.deps.posture?.prepare() ?? null;
30703
+ } catch {
30704
+ return null;
30705
+ }
30706
+ })();
30707
+ if (snapshot) {
30708
+ try {
30709
+ await withTimeout(
30710
+ this.deps.posture?.send(snapshot) ?? Promise.resolve(),
30711
+ REQUEST_TIMEOUT_MS
30712
+ );
30713
+ } catch {
30714
+ }
30715
+ }
30716
+ return resolved;
30717
+ }
30718
+ // The id is minted CLIENT-side and stored verbatim: the control plane does NOT
30719
+ // re-key it. `pgAuditValues` writes `id: event.id` and carries tenancy in
30720
+ // its own scoping columns, so the device and the forwarded copy
30721
+ // share one id space — which is what makes a re-post idempotent at all.
30722
+ //
30723
+ // Re-posts collapse via `onConflictDoUpdate` on the `id` PK, guarded by
30724
+ // `setWhere eventType = 'session'` (NOT onConflictDoNothing). That guard is
30725
+ // what makes an attached retry safe: a capture-stubbed session row can still
30726
+ // be HEALED by the authoritative root, while a duplicate non-session event —
30727
+ // a retried tool_call, exactly this path — can never stomp a populated row.
30728
+ async recordAuditEvent(event) {
30729
+ await this.deps.local.recordAuditEvent(event);
30730
+ await this.deps.forward.run(
30731
+ () => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
30732
+ );
30733
+ }
30734
+ // Attached `llm_call` is written locally by the inner gateway, then routed to
30735
+ // the control plane through the existing `recordAuditEvent` ingest (no dedicated
30736
+ // client method yet) by pre-building the audit event from the natural key.
30737
+ // The forward goes DIRECTLY to the client rather than through this.recordAuditEvent,
30738
+ // which would write the event to the local store a second time.
30739
+ async recordLlmCall(input) {
30740
+ await this.deps.local.recordLlmCall(input);
30741
+ await this.deps.forward.run(
30742
+ () => this.deps.client.recordAuditEvent(
30743
+ reKeyForForward(llmAuditEvent(input), this.remoteInventory)
30744
+ )
30745
+ );
30746
+ }
30747
+ /**
30748
+ * Forward one batch, item by item, under ONE aggregate deadline.
30749
+ *
30750
+ * Per-item budgets bound each request and nothing bounded their sum — see
30751
+ * BATCH_FORWARD_BUDGET_MS. When the deadline passes the remainder is dropped
30752
+ * rather than sent: the local write has already succeeded, so every caller
30753
+ * has a correct result to return, and a drop is the outcome this path is
30754
+ * built to accept (G8) where a blown hook timeout is not.
30755
+ *
30756
+ * Serial rather than concurrent on purpose. Firing N requests at once would
30757
+ * trade a latency problem for a burst the plane's own per-key rate limiting
30758
+ * would answer with the refusals the breaker then counts.
30759
+ *
30760
+ * WHAT IS DROPPED IS COUNTED. Every other forward failure ends in
30761
+ * `ForwardPolicy.run`'s catch and moves the breaker's file, which is what
30762
+ * lets status call the forward unhealthy; this path returns BEFORE `run` is
30763
+ * reached, so without the tally in `forward-drops.ts` a slow-but-answering
30764
+ * plane produces no failures, keeps the breaker closed, renders a healthy
30765
+ * block, and discards the tail of every batch indefinitely.
30766
+ */
30767
+ async forwardBatch(inputs, toEvent) {
30768
+ const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
30769
+ for (let i = 0; i < inputs.length; i += 1) {
30770
+ const now = Date.now();
30771
+ if (now >= deadline) {
30772
+ recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
30773
+ return;
30774
+ }
30775
+ const input = inputs[i];
30776
+ await this.deps.forward.run(
30777
+ () => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input), this.remoteInventory))
30778
+ );
30779
+ }
30780
+ }
30781
+ // Delegated as a BATCH rather than looped over recordLlmCall: the inner
30782
+ // gateway may write the whole batch in one local transaction, and looping
30783
+ // here would replace that with N separate local writes.
30784
+ async recordLlmCalls(inputs) {
30785
+ await this.deps.local.recordLlmCalls(inputs);
30786
+ await this.forwardBatch(inputs, (input) => llmAuditEvent(input));
30787
+ }
30788
+ // `input.inspections` (secrets detected client-side in the tool's masked
30789
+ // target) ride along on the request's `inspections` field — the control plane
30790
+ // persists each as an inspection_findings row linked to this audit event
30791
+ // (see RecordAuditEventRequest in @akasecurity/schema). The masked
30792
+ // `target` already rides `input.attributes`, so no raw secret leaks either
30793
+ // way — this only stops the FINDING row itself from being dropped.
30794
+ async recordToolCalls(inputs) {
30795
+ await this.deps.local.recordToolCalls(inputs);
30796
+ await this.forwardBatch(inputs, (input) => toolAuditEvent(input));
30797
+ }
30798
+ // Forwarded as a `config_scan` audit event: there is no dedicated
30799
+ // config-scan ingest endpoint, and the audit-event door is the one the
30800
+ // control plane already opens for client-minted, idempotent records.
30801
+ //
30802
+ // ONLY `scanEvent` CROSSES, and unlike `recordCapture` the plane cannot
30803
+ // re-derive the rest. A `ConfigScanRecord` is four things committed together
30804
+ // locally — the inventory `items`, this audit event, and the posture
30805
+ // `definitions`/`findings` that reference it — and three of them stay on the
30806
+ // device. Say that plainly rather than let the asymmetry with `recordCapture`
30807
+ // read as the same argument: there, findings are omitted BECAUSE the plane
30808
+ // re-derives them from `Event.content`; here there is no content to re-derive
30809
+ // from, so what is omitted is simply not sent.
30810
+ //
30811
+ // That is the wire contract as it stands rather than an oversight to patch
30812
+ // here. `items` has no route at all, and `RecordAuditEventRequest.inspections`
30813
+ // is documented as tool-call findings — widening it to carry config-scan
30814
+ // findings is an egress change (a posture finding's `maskedMatch` holds the
30815
+ // matched command) and a decision about what an attached deployment is
30816
+ // entitled to, not a bug fix. An attached machine's config posture therefore
30817
+ // reaches the plane as the event only; the dashboard's own view of it is the
30818
+ // local store.
30819
+ async recordConfigScan(record2) {
30820
+ await this.deps.local.recordConfigScan(record2);
30821
+ await this.deps.forward.run(
30822
+ () => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
30823
+ );
30824
+ }
30825
+ async recordBlockedDetection(entry) {
30826
+ return this.deps.local.recordBlockedDetection(entry);
30827
+ }
30828
+ /**
30829
+ * LOCAL-ONLY, deliberately. The shares API is read-plus-decision-override
30830
+ * with no egress ingest endpoint, so there is nothing to forward to; adding a
30831
+ * forward here would be inventing a wire contract that does not exist. The
30832
+ * local write is the whole operation, and its summary is the real one — the
30833
+ * scanner reads a throw as a FAILED WRITE and skips its ledger commit, so
30834
+ * returning the inner gateway's result keeps the retry semantics honest.
30835
+ */
30836
+ async recordProjectEgress(input) {
30837
+ return this.deps.local.recordProjectEgress(input);
30838
+ }
30839
+ // ---------------------------------------------------------------------
30840
+ // Reads and device-local ledgers: pure delegation.
30841
+ // ---------------------------------------------------------------------
30842
+ async configInventoryReport() {
30843
+ return this.deps.local.configInventoryReport();
30844
+ }
30845
+ async readSessionProvider(sessionId) {
30846
+ return this.deps.local.readSessionProvider(sessionId);
30847
+ }
30848
+ async facets() {
30849
+ return this.deps.local.facets();
30850
+ }
30851
+ /**
30852
+ * Delegated UNMODIFIED — including its refusals.
30853
+ *
30854
+ * This is a fail-secure boundary: it decides whether an approved exception
30855
+ * lets a blocked action through. Under local-first the local store owns the
30856
+ * exception ledger, so the honest answer is whatever it says; wrapping this
30857
+ * in a fallback (`catch { return true }`, or defaulting on a timeout) would
30858
+ * turn a store error into a granted bypass. If the inner gateway rejects,
30859
+ * this rejects, and the runtime's own handling decides — which is asserted
30860
+ * end-to-end through runtime.capture rather than here.
30861
+ */
30862
+ async consumeException(id) {
30863
+ return this.deps.local.consumeException(id);
30864
+ }
30865
+ async recentFindings(opts) {
30866
+ return this.deps.local.recentFindings(opts);
30867
+ }
30868
+ async healthSummary() {
30869
+ return this.deps.local.healthSummary();
30870
+ }
30871
+ async activityByDay(days) {
30872
+ return this.deps.local.activityByDay(days);
30873
+ }
30874
+ async tokenReports() {
30875
+ return this.deps.local.tokenReports();
30876
+ }
30877
+ async knownContentHashes() {
30878
+ return this.deps.local.knownContentHashes();
30879
+ }
30880
+ async scanLedger(rulesetHash) {
30881
+ return this.deps.local.scanLedger(rulesetHash);
30882
+ }
30883
+ async recordScanned(entries) {
30884
+ return this.deps.local.recordScanned(entries);
30885
+ }
30886
+ async getRuleProbeVerdict(ruleKey) {
30887
+ return this.deps.local.getRuleProbeVerdict(ruleKey);
30888
+ }
30889
+ async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
30890
+ return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
30891
+ }
30892
+ async openAtRestKeysForPath(path) {
30893
+ return this.deps.local.openAtRestKeysForPath(path);
30894
+ }
30895
+ async resolvedAtRestKeysForPath(path) {
30896
+ return this.deps.local.resolvedAtRestKeysForPath(path);
30897
+ }
30898
+ async insertResolution(input) {
30899
+ return this.deps.local.insertResolution(input);
30900
+ }
30901
+ async close() {
30902
+ return this.deps.local.close();
30903
+ }
30904
+ // ---------------------------------------------------------------------
30905
+ // Policy
30906
+ // ---------------------------------------------------------------------
30907
+ async getPolicyBundle() {
30908
+ const local = await this.deps.local.getPolicyBundle();
30909
+ const cached2 = await (async () => {
30910
+ try {
30911
+ return await this.deps.readCachedBundle();
30912
+ } catch {
30913
+ return null;
30914
+ }
30915
+ })();
30916
+ if (cached2 === null) return local;
30917
+ const byRuleId = /* @__PURE__ */ new Map();
30918
+ for (const rule of [...local.rules ?? [], ...cached2.rules ?? []]) {
30919
+ if (!byRuleId.has(rule.id)) byRuleId.set(rule.id, rule);
30920
+ }
30921
+ const rules = [...byRuleId.values()];
30922
+ return {
30923
+ ...local,
30924
+ // The remote version identifies the composed bundle for the poller.
30925
+ version: cached2.version,
30926
+ rules,
30927
+ policies: mergeRaiseOnly(
30928
+ local.policies,
30929
+ cached2.policies,
30930
+ ruleCategoryMap(cached2.rules, local.rules)
30931
+ ),
30932
+ customKeywords: [...local.customKeywords, ...cached2.customKeywords]
30933
+ // `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
30934
+ // snapshot) and is taken from the LOCAL bundle only — never from the wire
30935
+ // or the on-disk cache. Honoring a cached one would hand the control plane, or
30936
+ // anything able to write policy-cache.json, a kill-switch over the
30937
+ // compiled-in bundled packs: `{ rulesComplete: true, rules: [] }` would
30938
+ // zero local detection. Spread from `local` above, and deliberately not
30939
+ // re-read from `cached` here.
30940
+ //
30941
+ // THREE MORE OF THE CACHED BUNDLE'S FIELDS ARE DROPPED, each on purpose,
30942
+ // and each named here so a reader can tell a decision from an omission:
30943
+ //
30944
+ // `exceptions` — an exception SUPPRESSES a detection, so honoring
30945
+ // one from an unsigned on-disk cache would let
30946
+ // anything able to write that file turn rules off.
30947
+ // Every other field this merge accepts can only
30948
+ // RAISE enforcement; this is the one that cannot,
30949
+ // so it stays local-only until the bundle is
30950
+ // signed. Exceptions remain a device-local ledger.
30951
+ // `reversibleRuleIds` — the Redact & Vault archetype makes a redaction
30952
+ // recoverable, which is a CUSTODY change: it puts
30953
+ // the detected value in the local vault instead of
30954
+ // destroying it. Taking that instruction from the
30955
+ // cache would let a remote party turn one-way
30956
+ // redaction into retention. Dropping it keeps the
30957
+ // one-way behaviour, which the schema itself calls
30958
+ // "the safe direction to default".
30959
+ // `ruleVersions` — remote rules fall back to their own spec version.
30960
+ // Cosmetic rather than protective: it only affects
30961
+ // how a finding is version-attributed, and the two
30962
+ // sides may therefore attribute org rules
30963
+ // differently. Worth carrying once there is a
30964
+ // reader that needs it; nothing reads it today.
30965
+ };
30966
+ }
30967
+ // ---------------------------------------------------------------------
30968
+ // LocalStoreMaintenance — by delegation (D3).
30969
+ //
30970
+ // Implementing these is what actually closes the skipped-local-maintenance
30971
+ // gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
30972
+ // any object carrying all five, so the composite qualifies and SessionStart
30973
+ // runs maintenance on the device's real store.
30974
+ //
30975
+ // ⚠ Two of the five are SYNCHRONOUS and must stay that way. `handle-session-start`
30976
+ // calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
30977
+ // return value directly; declaring them `async` here would hand those call
30978
+ // sites a Promise and silently break both.
30979
+ // ---------------------------------------------------------------------
30980
+ async sweepTerminalExceptions(retentionMs) {
30981
+ return this.deps.local.sweepTerminalExceptions(retentionMs);
30982
+ }
30983
+ capWarnEraEnforcement(policyMode) {
30984
+ return this.deps.local.capWarnEraEnforcement(policyMode);
30985
+ }
30986
+ async recordProjectFiles(projectId, scan2) {
30987
+ return this.deps.local.recordProjectFiles(projectId, scan2);
30988
+ }
30989
+ async reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot) {
30990
+ return this.deps.local.reconcileWorktreeProjects(canonicalId, headRoot, worktreeRoot);
30991
+ }
30992
+ staleBinaryNotice(currentVersion) {
30993
+ return this.deps.local.staleBinaryNotice(currentVersion);
30994
+ }
30995
+ };
30996
+ function reKeyForForward(event, remote) {
30997
+ if (remote === null) {
30998
+ const stripped = { ...event };
30999
+ delete stripped.hostId;
31000
+ delete stripped.harnessId;
31001
+ delete stripped.sourceProjectId;
31002
+ return stripped;
31003
+ }
31004
+ const rekeyed = { ...event };
31005
+ delete rekeyed.hostId;
31006
+ delete rekeyed.harnessId;
31007
+ delete rekeyed.sourceProjectId;
31008
+ if (remote.hostId !== void 0) rekeyed.hostId = remote.hostId;
31009
+ if (remote.harnessId !== void 0) rekeyed.harnessId = remote.harnessId;
31010
+ if (remote.sourceProjectId !== void 0) rekeyed.sourceProjectId = remote.sourceProjectId;
31011
+ return rekeyed;
31012
+ }
31013
+ var BATCH_FORWARD_BUDGET_MS = 3e3;
31014
+ function llmAuditEvent(input) {
31015
+ return {
31016
+ id: llmCallId(input.sessionId, input.messageId),
31017
+ eventType: "llm_call",
31018
+ startedAt: input.startedAt,
31019
+ parentId: input.parentId,
31020
+ rootSessionId: input.rootSessionId,
31021
+ attributes: input.attributes
31022
+ };
31023
+ }
31024
+ function toolAuditEvent(input) {
31025
+ return {
31026
+ id: toolCallId(input.sessionId, input.toolUseId),
31027
+ eventType: "tool_call",
31028
+ startedAt: input.startedAt,
31029
+ parentId: input.parentId,
31030
+ rootSessionId: input.rootSessionId,
31031
+ attributes: input.attributes,
31032
+ inspections: input.inspections
31033
+ };
31034
+ }
31035
+
31036
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
31037
+ import { randomUUID as randomUUID16 } from "crypto";
31038
+ import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
31039
+ import { join as join19 } from "path";
31040
+
31041
+ // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
31042
+ import { rename as rename2 } from "fs/promises";
31043
+ var RETRYABLE = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
31044
+ var ATTEMPTS = 5;
31045
+ var delay = (ms) => new Promise((resolve2) => {
31046
+ setTimeout(resolve2, ms);
31047
+ });
31048
+ async function publishByRename(tmp, file2, move = rename2) {
31049
+ for (let attempt = 1; ; attempt += 1) {
31050
+ try {
31051
+ await move(tmp, file2);
31052
+ return;
31053
+ } catch (err) {
31054
+ const code = err.code;
31055
+ if (attempt >= ATTEMPTS || code === void 0 || !RETRYABLE.has(code)) throw err;
31056
+ await delay(attempt * 10);
31057
+ }
31058
+ }
31059
+ }
31060
+
31061
+ // ../../packages/plugin-runtime/src/attached/policy-store.ts
31062
+ function createPolicyStore(dir = dataDir()) {
31063
+ const file2 = join19(dir, "policy-cache.json");
31064
+ async function read() {
31065
+ try {
31066
+ const raw = await readFile2(file2, "utf8");
31067
+ const parsed2 = JSON.parse(raw);
31068
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
31069
+ const record2 = parsed2;
31070
+ const bundle = PolicyBundle.parse(record2.bundle);
31071
+ const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
31072
+ const etag = typeof record2.etag === "string" ? record2.etag : void 0;
31073
+ return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
31074
+ } catch {
31075
+ return null;
31076
+ }
31077
+ }
31078
+ async function write(bundle, etag) {
31079
+ await ensureDataDir(dir);
31080
+ const stored = {
31081
+ bundle,
31082
+ fetchedAtMs: Date.now(),
31083
+ ...etag === void 0 ? {} : { etag }
31084
+ };
31085
+ const tmp = `${file2}.${randomUUID16()}.tmp`;
31086
+ try {
31087
+ await writeFile2(tmp, JSON.stringify(stored), {
31088
+ encoding: "utf8",
31089
+ mode: DATA_FILE_MODE,
31090
+ flag: "wx"
31091
+ });
31092
+ await publishByRename(tmp, file2);
31093
+ } catch (err) {
31094
+ await rm(tmp, { force: true }).catch(() => void 0);
31095
+ throw err;
31096
+ }
31097
+ }
31098
+ return { read, write, file: file2 };
31099
+ }
31100
+
31101
+ // ../../packages/remote/src/http.ts
31102
+ import { request as httpRequest } from "http";
31103
+ import { request as httpsRequest } from "https";
31104
+ var DEFAULT_TIMEOUT_MS = 1e4;
31105
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
31106
+ var RemoteRequestError = class extends Error {
31107
+ constructor(status) {
31108
+ super(`control-plane request failed with status ${String(status)}`);
31109
+ this.status = status;
31110
+ this.name = "RemoteRequestError";
31111
+ }
31112
+ status;
31113
+ };
31114
+ var RemoteRequestInvalid = class extends Error {
31115
+ constructor(route, cause) {
31116
+ super(`refusing to send a malformed body to ${route}`);
31117
+ this.cause = cause;
31118
+ this.name = "RemoteRequestInvalid";
31119
+ }
31120
+ cause;
31121
+ };
31122
+ var RemoteResponseInvalid = class extends Error {
31123
+ constructor(route, detail) {
31124
+ super(`control plane answered ${route} with ${detail}`);
31125
+ this.name = "RemoteResponseInvalid";
31126
+ }
31127
+ };
31128
+ var RemoteTransportError = class extends Error {
31129
+ /**
31130
+ * The status the peer sent, when headers arrived and only the BODY was
31131
+ * refused.
31132
+ *
31133
+ * Undefined for the ordinary case this class was written for — no answer at
31134
+ * all. It exists because two paths reject after a status has already been
31135
+ * delivered: an oversized body and an aborted response. Discarding it there
31136
+ * reported a deployment answering 401 with a verbose body as a network
31137
+ * outage, which sends the reader to look at their network instead of their
31138
+ * credential.
31139
+ */
31140
+ constructor(reason, status) {
31141
+ super(`control-plane request did not complete: ${reason}`);
31142
+ this.status = status;
31143
+ this.name = "RemoteTransportError";
31144
+ }
31145
+ status;
31146
+ };
31147
+ async function send(options) {
31148
+ const url2 = new URL(options.url);
31149
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
31150
+ const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
31151
+ const requestOptions = {
31152
+ method: options.method,
31153
+ headers: {
31154
+ // CALLER HEADERS FIRST, so this module's own are not overridable. Spread
31155
+ // last they win, and two of the values below are ones no caller may
31156
+ // replace: `x-api-key` is the credential, and `content-length` is the
31157
+ // byte count that stops a multi-byte body being truncated by the
31158
+ // receiver. `SendOptions.headers` is a free-form record on an exported
31159
+ // function, so "no caller does that today" is not the guarantee to rely
31160
+ // on. The one header any caller actually passes — `if-none-match` on the
31161
+ // conditional GET — is untouched by this order.
31162
+ ...options.headers,
31163
+ // The credential. One header, matching what the deployment authenticates
31164
+ // on; a second copy in an `Authorization` header would be one more place
31165
+ // it can be logged by an intermediary for no gain.
31166
+ "x-api-key": options.apiKey,
31167
+ accept: "application/json",
31168
+ ...options.body === void 0 ? {} : {
31169
+ "content-type": "application/json",
31170
+ // Byte length, not string length: a multi-byte body sent with a
31171
+ // character count is truncated by the receiver.
31172
+ "content-length": String(Buffer.byteLength(options.body))
31173
+ }
31174
+ }
31175
+ };
31176
+ return new Promise((resolve2, reject) => {
31177
+ let settled = false;
31178
+ const fail = (reason, status) => {
31179
+ if (settled) return;
31180
+ settled = true;
31181
+ reject(new RemoteTransportError(reason, status));
31182
+ };
31183
+ const req = send_(url2, requestOptions, (res) => {
31184
+ const chunks = [];
31185
+ let size = 0;
31186
+ res.on("data", (chunk) => {
31187
+ size += chunk.length;
31188
+ if (size > MAX_RESPONSE_BYTES) {
31189
+ fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
31190
+ res.destroy();
31191
+ req.destroy();
31192
+ return;
31193
+ }
31194
+ chunks.push(chunk);
31195
+ });
31196
+ res.on("aborted", () => {
31197
+ fail("the response was aborted", res.statusCode);
31198
+ });
31199
+ res.on("end", () => {
31200
+ if (settled) return;
31201
+ settled = true;
31202
+ resolve2({
31203
+ status: res.statusCode ?? 0,
31204
+ headers: res.headers,
31205
+ body: Buffer.concat(chunks).toString("utf8")
31206
+ });
31207
+ });
31208
+ });
31209
+ const deadline = setTimeout(() => {
31210
+ fail(`no response within ${String(timeoutMs)}ms`);
31211
+ req.destroy();
31212
+ }, timeoutMs);
31213
+ deadline.unref();
31214
+ req.on("upgrade", (_res, socket) => {
31215
+ fail("the deployment answered with a protocol upgrade");
31216
+ socket.destroy();
31217
+ });
31218
+ req.on("close", () => {
31219
+ fail("the connection closed before a response was read");
31220
+ clearTimeout(deadline);
31221
+ });
31222
+ req.on("error", (err) => {
31223
+ fail(err.message);
31224
+ });
31225
+ if (options.body !== void 0) req.write(options.body);
31226
+ req.end();
31227
+ });
31228
+ }
31229
+
31230
+ // ../../packages/remote/src/client.ts
31231
+ var ROUTES = {
31232
+ events: "/v1/events",
31233
+ auditEvents: "/v1/audit-events",
31234
+ inventory: "/v1/inventory",
31235
+ storePosture: "/v1/store-posture",
31236
+ policyBundle: "/v1/policy-bundle",
31237
+ whoami: "/v1/plugin/whoami"
31238
+ };
31239
+ function headerValue(response, name) {
31240
+ const raw = response.headers[name];
31241
+ if (raw === void 0) return void 0;
31242
+ return Array.isArray(raw) ? raw[0] : raw;
31243
+ }
31244
+ function okBody(response) {
31245
+ if (response.status < 200 || response.status >= 300) {
31246
+ throw new RemoteRequestError(response.status);
31247
+ }
31248
+ return response.body;
31249
+ }
31250
+ function parsed(schema, body, route) {
31251
+ let json2;
31252
+ try {
31253
+ json2 = JSON.parse(body);
31254
+ } catch {
31255
+ throw new RemoteResponseInvalid(route, "a body that is not JSON");
31256
+ }
31257
+ const result = schema.safeParse(json2);
31258
+ if (!result.success) {
31259
+ throw new RemoteResponseInvalid(route, "a body this client cannot read");
31260
+ }
31261
+ return result.data;
31262
+ }
31263
+ function withoutTrailingSlashes(endpoint) {
31264
+ let end = endpoint.length;
31265
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
31266
+ return endpoint.slice(0, end);
31267
+ }
31268
+ var SLASH = "/".charCodeAt(0);
31269
+ function createRemoteClient(options) {
31270
+ const base = withoutTrailingSlashes(options.endpoint);
31271
+ const url2 = (route) => `${base}${route}`;
31272
+ const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
31273
+ return {
31274
+ async ingestEvents(batch) {
31275
+ const response = await send({
31276
+ ...common,
31277
+ method: "POST",
31278
+ url: url2(ROUTES.events),
31279
+ body: JSON.stringify(batch)
31280
+ });
31281
+ return parsed(IngestAck, okBody(response), ROUTES.events);
31282
+ },
31283
+ async ingestInventory(context) {
31284
+ const response = await send({
31285
+ ...common,
31286
+ method: "POST",
31287
+ url: url2(ROUTES.inventory),
31288
+ body: JSON.stringify(context)
31289
+ });
31290
+ return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
31291
+ },
31292
+ async recordAuditEvent(event) {
31293
+ const validated = RecordAuditEventRequest.safeParse(event);
31294
+ if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
31295
+ const submission = validated.data;
31296
+ const response = await send({
31297
+ ...common,
31298
+ method: "POST",
31299
+ url: url2(ROUTES.auditEvents),
31300
+ body: JSON.stringify(submission)
31301
+ });
31302
+ okBody(response);
31303
+ },
31304
+ async reportStorePosture(snapshot) {
31305
+ const response = await send({
31306
+ ...common,
31307
+ method: "POST",
31308
+ url: url2(ROUTES.storePosture),
31309
+ body: JSON.stringify(snapshot)
31310
+ });
31311
+ okBody(response);
31312
+ },
31313
+ async getPolicyBundle(etag) {
31314
+ const response = await send({
31315
+ ...common,
31316
+ method: "GET",
31317
+ url: url2(ROUTES.policyBundle),
31318
+ ...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
31319
+ });
31320
+ if (response.status === 304) {
31321
+ return { changed: false, etag: headerValue(response, "etag") ?? etag };
31322
+ }
31323
+ const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
31324
+ return { changed: true, bundle, etag: headerValue(response, "etag") };
31325
+ },
31326
+ async whoami() {
31327
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
31328
+ return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
31329
+ }
31330
+ };
31331
+ }
31332
+
31333
+ // ../../packages/plugin-runtime/src/attached/posture-reporter.ts
31334
+ var POSTURE_REPORT_INTERVAL_MS = 60 * 60 * 1e3;
31335
+ function createPostureReporter(deps) {
31336
+ async function prepare() {
31337
+ try {
31338
+ const state = await withTimeout(deps.store.read(), REQUEST_TIMEOUT_MS);
31339
+ if (state === null) return null;
31340
+ const nowMs = deps.now();
31341
+ const elapsed = nowMs - state.lastAttemptedAtMs;
31342
+ if (elapsed >= 0 && elapsed < POSTURE_REPORT_INTERVAL_MS) return null;
31343
+ try {
31344
+ await withTimeout(deps.store.markAttempted(state.deviceId, nowMs), REQUEST_TIMEOUT_MS);
31345
+ } catch {
31346
+ }
31347
+ const { readError, ...measurement } = deps.readStore();
31348
+ if (readError) return null;
31349
+ let plugin;
31350
+ try {
31351
+ plugin = await deps.pluginBlock?.();
31352
+ } catch {
31353
+ plugin = void 0;
31354
+ }
31355
+ return {
31356
+ deviceId: state.deviceId,
31357
+ hostname: deps.hostname(),
31358
+ capturedAt: nowMs,
31359
+ ...measurement,
31360
+ // Omit the key rather than spread an explicit `undefined` —
31361
+ // exactOptionalPropertyTypes distinguishes the two, and the bridge in
31362
+ // factory.ts keys on presence.
31363
+ ...plugin === void 0 ? {} : { plugin }
31364
+ };
31365
+ } catch {
31366
+ return null;
31367
+ }
31368
+ }
31369
+ async function send2(snapshot) {
31370
+ try {
31371
+ await deps.report(snapshot);
31372
+ } catch {
31373
+ }
31374
+ }
31375
+ return { prepare, send: send2 };
31376
+ }
31377
+
31378
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31379
+ import { statSync as statSync9 } from "fs";
31380
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
31381
+
31382
+ // ../../packages/plugin-runtime/src/attached/action-counts.ts
31383
+ function emptyActionCounts() {
31384
+ return Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
31385
+ }
31386
+ function isActionTaken(value) {
31387
+ return ACTION_TAKEN_KEYS.includes(value);
31388
+ }
31389
+
31390
+ // ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
31391
+ var CAPTURE_EVENT_TYPES_SQL2 = `('prompt','response','code_change','tool_use')`;
31392
+ function isSchemaAbsent(err) {
31393
+ return err instanceof Error && /no such table/i.test(err.message);
31394
+ }
31395
+ function emptyReadout(readError = false) {
31396
+ const byAction = emptyActionCounts();
31397
+ return {
31398
+ storePresent: false,
31399
+ schemaVersion: null,
31400
+ findingsTotal: 0,
31401
+ findingsFirstAt: null,
31402
+ findingsLastAt: null,
31403
+ packs: [],
31404
+ policyCounts: { total: 0, disabled: 0, byAction },
31405
+ readError
31406
+ };
31407
+ }
31408
+ function readStorePosture(dbPath2) {
31409
+ try {
31410
+ statSync9(dbPath2);
31411
+ } catch (err) {
31412
+ const code = err.code;
31413
+ if (code === "ENOENT" || code === "ENOTDIR") return emptyReadout();
31414
+ return emptyReadout(true);
31415
+ }
31416
+ let db = null;
31417
+ let version2 = null;
31418
+ let packs2 = [];
31419
+ let policyCounts = {
31420
+ total: 0,
31421
+ disabled: 0,
31422
+ byAction: emptyActionCounts()
31423
+ };
31424
+ let findingsTotal = 0;
31425
+ let findingsFirstAt = null;
31426
+ let findingsLastAt = null;
31427
+ const currentReadout = () => ({
31428
+ storePresent: true,
31429
+ schemaVersion: version2,
31430
+ findingsTotal,
31431
+ findingsFirstAt,
31432
+ findingsLastAt,
31433
+ packs: packs2,
31434
+ policyCounts,
31435
+ readError: false
31436
+ });
31437
+ try {
31438
+ db = new DatabaseSync3(dbPath2, { readOnly: true });
31439
+ db.exec("PRAGMA busy_timeout = 2000");
31440
+ version2 = db.prepare("PRAGMA user_version").get().user_version;
31441
+ try {
31442
+ const packRows = db.prepare(
31443
+ `SELECT namespace, pack_id, version, enabled, updated_at FROM installed_packs ORDER BY namespace, pack_id`
31444
+ ).all();
31445
+ packs2 = packRows.map((r) => ({
31446
+ packId: `${r.namespace}/${r.pack_id}`,
31447
+ version: r.version,
31448
+ enabled: r.enabled !== 0,
31449
+ updatedAt: r.updated_at == null ? null : String(r.updated_at)
31450
+ }));
31451
+ } catch (err) {
31452
+ if (!isSchemaAbsent(err)) throw err;
31453
+ }
31454
+ try {
31455
+ const policyRows = db.prepare(`SELECT action, enabled FROM policies`).all();
31456
+ const byAction = emptyActionCounts();
31457
+ let disabled = 0;
31458
+ for (const row of policyRows) {
31459
+ if (row.enabled === 0) disabled += 1;
31460
+ if (isActionTaken(row.action)) byAction[row.action] += 1;
31461
+ }
31462
+ policyCounts = { total: policyRows.length, disabled, byAction };
31463
+ } catch (err) {
31464
+ if (!isSchemaAbsent(err)) throw err;
31465
+ }
31466
+ try {
31467
+ const agg = db.prepare(
31468
+ `SELECT count(*) AS n, min(f.first_detected_at) AS firstAt, max(f.first_detected_at) AS lastAt
31469
+ FROM inspection_findings f JOIN audit_events e ON e.id = f.audit_event_id
31470
+ WHERE e.event_type IN ${CAPTURE_EVENT_TYPES_SQL2}`
31471
+ ).get();
31472
+ findingsTotal = agg.n;
31473
+ findingsFirstAt = agg.firstAt;
31474
+ findingsLastAt = agg.lastAt;
31475
+ } catch (err) {
31476
+ if (!isSchemaAbsent(err)) throw err;
31477
+ }
31478
+ return currentReadout();
31479
+ } catch {
31480
+ return emptyReadout(true);
31481
+ } finally {
31482
+ try {
31483
+ db?.close();
31484
+ } catch {
31485
+ }
31486
+ }
31487
+ }
31488
+
31489
+ // ../../packages/plugin-runtime/src/attached/posture-store.ts
31490
+ import { randomUUID as randomUUID17 } from "crypto";
31491
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
31492
+ import { join as join20 } from "path";
31493
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31494
+ function createPostureStore(dir = settingsDir(), legacyDir) {
31495
+ const file2 = join20(dir, "posture-state.json");
31496
+ const legacyFile = legacyDir === void 0 ? null : join20(legacyDir, "posture-state.json");
31497
+ async function persist(state) {
31498
+ await ensureDataDir(dir);
31499
+ const tmp = `${file2}.${randomUUID17()}.tmp`;
31500
+ try {
31501
+ await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
31502
+ await publishByRename(tmp, file2);
31503
+ } catch (err) {
31504
+ await rm2(tmp, { force: true }).catch(() => void 0);
31505
+ throw err;
31506
+ }
31507
+ }
31508
+ async function readFrom(path) {
31509
+ let raw;
31510
+ try {
31511
+ raw = await readFile3(path, "utf8");
31512
+ } catch (err) {
31513
+ const code = err.code;
31514
+ if (code === "ENOENT" || code === "ENOTDIR") return null;
31515
+ throw err;
31516
+ }
31517
+ try {
31518
+ const parsed2 = JSON.parse(raw);
31519
+ if (typeof parsed2 === "object" && parsed2 !== null) {
31520
+ const record2 = parsed2;
31521
+ if (typeof record2.deviceId === "string" && UUID_RE.test(record2.deviceId)) {
31522
+ const stamp = typeof record2.lastAttemptedAtMs === "number" ? record2.lastAttemptedAtMs : typeof record2.lastReportedAtMs === "number" ? record2.lastReportedAtMs : 0;
31523
+ return { deviceId: record2.deviceId, lastAttemptedAtMs: stamp };
31524
+ }
31525
+ }
31526
+ } catch {
31527
+ }
31528
+ return null;
31529
+ }
31530
+ async function read() {
31531
+ const current = await readFrom(file2);
31532
+ if (current) return current;
31533
+ const legacy = legacyFile === null || legacyFile === file2 ? null : await readFrom(legacyFile).catch(() => null);
31534
+ if (legacy) {
31535
+ try {
31536
+ await persist(legacy);
31537
+ } catch {
31538
+ }
31539
+ return legacy;
31540
+ }
31541
+ const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
31542
+ try {
31543
+ await ensureDataDir(dir);
31544
+ if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
31545
+ } catch {
31546
+ return null;
31547
+ }
31548
+ const winner = await readFrom(file2).catch(() => null);
31549
+ if (winner) return winner;
31550
+ try {
31551
+ await persist(fresh);
31552
+ } catch {
31553
+ return null;
31554
+ }
31555
+ return fresh;
31556
+ }
31557
+ async function markAttempted(deviceId, atMs) {
31558
+ await persist({ deviceId, lastAttemptedAtMs: atMs });
31559
+ }
31560
+ return { read, markAttempted, file: file2 };
31561
+ }
31562
+
31563
+ // ../../packages/plugin-runtime/src/attached/sync-state.ts
31564
+ import { readFileSync as readFileSync13 } from "fs";
31565
+ import { join as join21 } from "path";
31566
+
31567
+ // ../../packages/plugin-runtime/src/attached/status.ts
31568
+ var REFUSAL_LINES = {
31569
+ unauthorized: "KEY REJECTED \u2014 re-attach with a valid plugin key",
31570
+ forbidden: "ACCESS REFUSED \u2014 key is valid but not permitted; ask your org admin"
31571
+ };
31572
+ var OUTCOME_LINES = {
31573
+ ok: "policy synced",
31574
+ "not-modified": "policy up to date",
31575
+ unauthorized: REFUSAL_LINES.unauthorized,
31576
+ forbidden: REFUSAL_LINES.forbidden,
31577
+ unreachable: "control plane unreachable at last attempt",
31578
+ "invalid-bundle": "control plane sent a policy bundle this build cannot read"
31579
+ };
31580
+
31581
+ // ../../packages/plugin-runtime/src/attached/sync-trigger.ts
31582
+ import { spawn } from "child_process";
31583
+ import { fileURLToPath as fileURLToPath2 } from "url";
31584
+ var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
31585
+
31586
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31587
+ import { hostname as hostname5 } from "os";
31588
+
31589
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31590
+ import { randomUUID as randomUUID18 } from "crypto";
31591
+
31592
+ // ../../packages/plugin-runtime/src/recorder.ts
31593
+ var PLUGIN_RECORDER_BINARY = "plugin";
31594
+
31595
+ // ../../packages/plugin-runtime/src/standalone-gateway.ts
31596
+ var StandaloneDataGateway = class {
31597
+ db;
31598
+ // Kept for the fingerprint key lookup (exception.key lives beside the store).
31599
+ dataDir;
31600
+ // One notice per gateway — see warnRulesetDiscarded.
31601
+ warnedRulesetDiscarded = false;
31602
+ constructor(dataDir2, detections = [], meta3) {
31603
+ this.db = openLocalDatabase(dataDir2);
31604
+ this.dataDir = dataDir2;
31605
+ this.db.installedPacks.recordInventory(detections, meta3);
31606
+ }
31607
+ recordCapture(record2) {
31608
+ this.db.recordCapture(record2.event, record2.findings);
31609
+ return Promise.resolve();
31610
+ }
31611
+ ensureInventory(ctx) {
31612
+ return Promise.resolve(this.db.ensureInventory(ctx));
31613
+ }
31614
+ recordAuditEvent(event) {
31615
+ this.db.auditEvents.insertAuditEvent(event);
31616
+ return Promise.resolve();
31617
+ }
31618
+ // The id is minted inside the repository from the natural key — the plugin can't
31619
+ // import @akasecurity/persistence to compute it, so the gateway is the boundary that
31620
+ // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
31621
+ // converge a streaming partial/final split (see insertLlmCall).
31622
+ recordLlmCall(input) {
31623
+ this.db.auditEvents.insertLlmCall(input);
31624
+ return Promise.resolve();
31625
+ }
31626
+ // One reconcile pass = one transaction. All leaves commit together
31627
+ // (single lock + WAL fsync); a contended SQLITE_BUSY rolls back and rejects so the
30146
31628
  // reconciler drops the whole pass and recovers it idempotently on the next read.
30147
31629
  recordLlmCalls(inputs) {
30148
31630
  if (inputs.length === 0) return Promise.resolve();
30149
- return new Promise((resolve, reject) => {
31631
+ return new Promise((resolve2, reject) => {
30150
31632
  try {
30151
31633
  this.db.auditEvents.runInTransaction(() => {
30152
31634
  for (const input of inputs) this.db.auditEvents.insertLlmCall(input);
30153
31635
  });
30154
- resolve();
31636
+ resolve2();
30155
31637
  } catch (err) {
30156
31638
  reject(err instanceof Error ? err : new Error(String(err)));
30157
31639
  }
@@ -30163,12 +31645,12 @@ var StandaloneDataGateway = class {
30163
31645
  // drops the whole pass and recovers it idempotently next time.
30164
31646
  recordToolCalls(inputs) {
30165
31647
  if (inputs.length === 0) return Promise.resolve();
30166
- return new Promise((resolve, reject) => {
31648
+ return new Promise((resolve2, reject) => {
30167
31649
  try {
30168
31650
  this.db.auditEvents.runInTransaction(() => {
30169
31651
  for (const input of inputs) this.writeToolCall(input);
30170
31652
  });
30171
- resolve();
31653
+ resolve2();
30172
31654
  } catch (err) {
30173
31655
  reject(err instanceof Error ? err : new Error(String(err)));
30174
31656
  }
@@ -30310,7 +31792,7 @@ var StandaloneDataGateway = class {
30310
31792
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
30311
31793
  const installed = this.installedScanRules();
30312
31794
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
30313
- id: randomUUID15(),
31795
+ id: randomUUID18(),
30314
31796
  scope: "global",
30315
31797
  target: { ruleId },
30316
31798
  action,
@@ -30464,19 +31946,66 @@ var StandaloneDataGateway = class {
30464
31946
  }
30465
31947
  };
30466
31948
 
31949
+ // ../../packages/plugin-runtime/src/attached/factory.ts
31950
+ function resolveGatewayForConfig(config2, meta3) {
31951
+ const local = new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
31952
+ try {
31953
+ if (!isAttached(config2.settings)) return local;
31954
+ const connection = config2.settings.controlPlane;
31955
+ if (connection === void 0) return local;
31956
+ const state = readControlPlaneCredentialState(config2.settingsDir, connection);
31957
+ if (!state.usable) return local;
31958
+ const client = createRemoteClient({
31959
+ endpoint: connection.endpoint,
31960
+ apiKey: state.credential.apiKey
31961
+ });
31962
+ const store = createPolicyStore(config2.dataDir);
31963
+ const postureStore = createPostureStore(config2.settingsDir, config2.dataDir);
31964
+ const forward = createForwardPolicy({ dir: config2.dataDir });
31965
+ return new AttachedDataGateway({
31966
+ local,
31967
+ client,
31968
+ dataDir: config2.dataDir,
31969
+ readCachedBundle: () => store.read().then((cached2) => cached2?.bundle ?? null),
31970
+ forward,
31971
+ posture: createPostureReporter({
31972
+ // THROUGH THE BREAKER, and wrapped HERE rather than around
31973
+ // `PostureReporter.send`. The reporter swallows every error by
31974
+ // contract, so a wrap outside it would hand `forward.run` a resolved
31975
+ // promise for a send that failed — recording a SUCCESS, clearing
31976
+ // `consecutiveFailures` and `lastFailure`, and telling `aka status` the
31977
+ // forward recovered when nothing did. Wrapping the raw client call puts
31978
+ // the breaker above the swallow, where it can see the truth.
31979
+ //
31980
+ // What it buys: once the breaker is open — the plane already confirmed
31981
+ // down by the gateway's own writes — this stops paying a request
31982
+ // timeout per throttle interval to re-learn it.
31983
+ report: (snapshot) => forward.run(() => client.reportStorePosture(snapshot)).then(() => void 0),
31984
+ store: postureStore,
31985
+ readStore: () => readStorePosture(config2.dbPath),
31986
+ hostname: () => hostname5(),
31987
+ now: () => Date.now()
31988
+ })
31989
+ });
31990
+ } catch {
31991
+ return local;
31992
+ }
31993
+ }
31994
+
30467
31995
  // ../../packages/plugin-runtime/src/resolve.ts
30468
- var standaloneGatewayFactory = (config2, meta3) => new StandaloneDataGateway(config2.dataDir, bundledDetections(), meta3);
30469
- var defaultGatewayFactory = standaloneGatewayFactory;
31996
+ var configuredGatewayFactory = (config2, meta3) => resolveGatewayForConfig(config2, meta3);
31997
+ var defaultGatewayFactory = configuredGatewayFactory;
30470
31998
  function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFactory) {
30471
31999
  return gatewayFactory(config2, meta3);
30472
32000
  }
30473
32001
 
30474
32002
  // ../../packages/plugin-runtime/src/handle-session-start.ts
30475
- import { randomUUID as randomUUID16 } from "crypto";
32003
+ import { randomUUID as randomUUID19 } from "crypto";
30476
32004
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
30477
32005
 
30478
32006
  // src/hooks/store-health.ts
30479
32007
  var STORE_WARNING_MARKER = "store-warning-last-session";
32008
+ var STORE_REDIRECT_MARKER = "store-redirect-last-session";
30480
32009
  function openGatewayOrNull(config2) {
30481
32010
  try {
30482
32011
  return resolveDataGateway(config2);
@@ -30489,17 +32018,64 @@ function storeUnavailableMessage(dbPath2) {
30489
32018
  }
30490
32019
  function claimStoreUnavailableWarning(dataDir2, sessionId) {
30491
32020
  if (!sessionId) return true;
30492
- const path = join15(dataDir2, STORE_WARNING_MARKER);
30493
- try {
30494
- if (readFileSync10(path, "utf8") === sessionId) return false;
30495
- } catch {
32021
+ const dirs = markerDirs(dataDir2);
32022
+ if (alreadyClaimed(dirs, STORE_WARNING_MARKER, sessionId)) return false;
32023
+ recordClaim(dirs, STORE_WARNING_MARKER, sessionId);
32024
+ return true;
32025
+ }
32026
+ function markerDirs(dataDir2) {
32027
+ return [dataDir2, dirname5(dataDir2)];
32028
+ }
32029
+ function alreadyClaimed(dirs, marker, sessionId) {
32030
+ return dirs.some((dir) => {
32031
+ try {
32032
+ return readFileSync14(join22(dir, marker), "utf8") === sessionId;
32033
+ } catch {
32034
+ return false;
32035
+ }
32036
+ });
32037
+ }
32038
+ function recordClaim(dirs, marker, sessionId) {
32039
+ for (const dir of dirs) {
32040
+ try {
32041
+ mkdirSync4(dir, { recursive: true, mode: DATA_DIR_MODE });
32042
+ writeFileSync7(join22(dir, marker), sessionId, { mode: DATA_FILE_MODE });
32043
+ return;
32044
+ } catch {
32045
+ }
30496
32046
  }
32047
+ }
32048
+ function storeRedirectedMessage(paths, platform2 = process.platform) {
32049
+ const where = paths.map(({ path, target, holds, missing, mode }) => {
32050
+ if (missing) return `${path} -> ${target} (which does not exist; ${holds} cannot land there)`;
32051
+ const loose = mode !== void 0 && (mode & 63) !== 0 ? ", NOT owner-only" : "";
32052
+ const inherited = mode === void 0 ? "" : ` (${formatMode(mode)}${loose})`;
32053
+ return `${path} -> ${target}${inherited}, holding ${holds}`;
32054
+ }).join("; ");
32055
+ const subject = paths.length === 1 ? "a store path is a symlink" : `${String(paths.length)} store paths are symlinks`;
32056
+ const anyResolves = paths.some(({ missing }) => !missing);
32057
+ const lead = anyResolves ? `${subject}, so AKA is writing into the target instead: ${where}. ` : `${subject} resolving nowhere, so AKA cannot write there: ${where}. `;
32058
+ const kept = anyResolves && platform2 !== "win32" ? "Permissions are never changed through a symlink, so the store keeps whatever the target already had. " : "";
32059
+ return `[aka] ${lead}${kept}If you did not create that link, treat it as untrusted and run \`aka init\` for the full report.
32060
+ `;
32061
+ }
32062
+ function formatMode(mode) {
32063
+ return `0${mode.toString(8).padStart(3, "0")}`;
32064
+ }
32065
+ function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
30497
32066
  try {
30498
- mkdirSync4(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
30499
- writeFileSync7(path, sessionId, { mode: DATA_FILE_MODE });
32067
+ const paths = symlinkedStorePaths(dirname5(config2.dataDir));
32068
+ if (paths.length === 0) return;
32069
+ if (!sessionId) {
32070
+ write(storeRedirectedMessage(paths));
32071
+ return;
32072
+ }
32073
+ const dirs = markerDirs(config2.dataDir);
32074
+ if (alreadyClaimed(dirs, STORE_REDIRECT_MARKER, sessionId)) return;
32075
+ write(storeRedirectedMessage(paths));
32076
+ recordClaim(dirs, STORE_REDIRECT_MARKER, sessionId);
30500
32077
  } catch {
30501
32078
  }
30502
- return true;
30503
32079
  }
30504
32080
 
30505
32081
  // src/hooks/pre-tool-use.ts
@@ -30520,6 +32096,7 @@ async function main() {
30520
32096
  return;
30521
32097
  }
30522
32098
  const config2 = loadConfig();
32099
+ warnIfStoreRedirected(config2, getString(input, "session_id"));
30523
32100
  const gateway = openGatewayOrNull(config2);
30524
32101
  if (gateway === null) {
30525
32102
  if (claimStoreUnavailableWarning(config2.dataDir, getString(input, "session_id"))) {