@akasecurity/ai-tc-claude-code 0.9.2 → 0.9.4

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.
@@ -492,11 +492,11 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
- import { existsSync as existsSync3 } from "fs";
496
- import { join as join6 } from "path";
495
+ import { existsSync as existsSync4 } from "fs";
496
+ import { join as join7 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/database.ts
499
- import { randomUUID as randomUUID8 } from "crypto";
499
+ import { randomUUID as randomUUID9 } from "crypto";
500
500
  import { existsSync, renameSync as renameSync2, rmSync as rmSync2 } from "fs";
501
501
  import { join, sep } from "path";
502
502
  import { DatabaseSync } from "node:sqlite";
@@ -562,6 +562,22 @@ var SQLITE_MIGRATIONS = [
562
562
  {
563
563
  tag: "0014_drop_legacy_events_findings",
564
564
  sql: "-- Custom migration: drops the frozen legacy `events`/`findings` tables\n-- (superseded by audit_events/inspection_definitions/inspection_findings) and\n-- replaces them with read-only views of the same name.\n--\n-- persistence's migrations.ts applies this migration ONLY once the batched\n-- history backfill (see runLegacyHistoryBackfill) has fully drained both\n-- tables, and only after copying the live file aside \u2014 see\n-- backupBeforeLegacyDrop in packages/persistence/src/migrations.ts. A store\n-- still mid-copy keeps its real tables and this migration stays pending.\n--\n-- The views exist for skew: the `aka` CLI and the Claude Code plugin update\n-- independently against one shared store, so an older, already-installed\n-- binary can open a store a newer binary already dropped these tables on.\n-- Every already-shipped repository constructor prepares its SQL eagerly at\n-- open time, so a bare \"table not found\" would fail the WHOLE open, not just\n-- a findings-specific read \u2014 these views keep `prepare()` succeeding so an\n-- old binary's unrelated features keep working; its own reads stay truthful,\n-- and its rare (already fail-open) writes fail at run time instead.\n--\n-- The 0009/0010 expression indexes existed only over the legacy `events`\n-- table; DROP TABLE below would remove them implicitly, but they are\n-- dropped explicitly first so the intent reads clearly. IF EXISTS so a store\n-- that reached here with an index missing out of band (an adopted-tag store\n-- whose physical index was never built) does not throw a deterministic \"no\n-- such index\" out of the fail-open drop path.\nDROP INDEX IF EXISTS `idx_events_code_change_path`;\n--> statement-breakpoint\nDROP INDEX IF EXISTS `idx_events_session_id`;\n--> statement-breakpoint\n-- `findings.event_id` references `events.id` \u2014 drop the child first.\nDROP TABLE `findings`;\n--> statement-breakpoint\nDROP TABLE `events`;\n--> statement-breakpoint\n-- Legacy `events` shape, projected from audit_events: `kind`/`occurred_at`/\n-- `source_tool` become real columns again (source_tool round-trips through\n-- the attributes bag, the only place a capture-typed audit row keeps it);\n-- `metadata` is reconstructed as the old camelCase JSON object from the new\n-- snake_case attributes bag, with `root_session_id` folded back in as\n-- `sessionId` (the one legacy metadata key that became a column, never an\n-- attribute, on the new table). Constrained to the four capture kinds so\n-- structural rows (session/run/tool_call/llm_call/source_lookup/config_scan)\n-- never leak into a legacy reader's result set \u2014 the old `events` table\n-- never held them either.\nCREATE VIEW `events` AS\nSELECT\n id,\n json_extract(attributes, '$.source_tool') AS source_tool,\n event_type AS kind,\n started_at AS occurred_at,\n content_hash,\n content,\n -- Plugin-local bookkeeping column that `ensureSyncedAtColumn` adds to the\n -- real `events` table at open time. A pre-cutover binary runs that probe on\n -- EVERY open; without this projection its `columnNames('events')` check\n -- misses `synced_at` and issues `ALTER TABLE events ADD COLUMN` against this\n -- view, which SQLite rejects (\"Cannot add a column to a view\") \u2014 a hard,\n -- non-fail-open crash of the whole open, the exact skew failure these views\n -- exist to prevent. Projecting it (always NULL; no reader consumes it)\n -- short-circuits that ALTER.\n NULL AS synced_at,\n json_object(\n 'sessionId', root_session_id,\n 'repo', json_extract(attributes, '$.repo'),\n 'filePath', json_extract(attributes, '$.file_path'),\n 'toolName', json_extract(attributes, '$.tool_name'),\n 'gitignored', json_extract(attributes, '$.gitignored'),\n 'wholeFile', json_extract(attributes, '$.whole_file'),\n 'model', json_extract(attributes, '$.model'),\n 'turnIndex', json_extract(attributes, '$.turn_index'),\n 'correlationId', json_extract(attributes, '$.correlation_id'),\n 'traceId', json_extract(attributes, '$.trace_id'),\n 'exceptionIds', json_extract(attributes, '$.exception_ids')\n ) AS metadata\nFROM audit_events\nWHERE event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--> statement-breakpoint\n-- A plain single-row INSERT (the old writer's shape \u2014 no ON CONFLICT) is\n-- accepted by prepare() against a view once an INSTEAD OF INSERT trigger\n-- exists, so it fails at run time instead of at open \u2014 landing in the same\n-- fail-open path the caller already wraps its write in.\nCREATE TRIGGER `trg_events_ro`\nINSTEAD OF INSERT ON `events`\nBEGIN SELECT RAISE(ABORT, 'events is read-only; write to audit_events instead'); END;\n--> statement-breakpoint\n-- Legacy `findings` shape: rule_id/category/severity come from the joined\n-- inspection_definitions row (the legacy table inlined them per-row; the\n-- generalized schema normalizes them out into the shared definition). A view\n-- has no rowid of its own, so the underlying table's rowid is re-exposed\n-- explicitly under that name \u2014 a legacy reader ordering by `f.rowid` would\n-- otherwise fail to resolve the column at all. Joined to audit_events for the\n-- same four-capture-kind constraint as the events view above (a finding\n-- attached to a tool_call/config_scan row never existed in the legacy table\n-- either \u2014 see the persistence findings repository's identical predicate).\nCREATE VIEW `findings` AS\nSELECT\n f.id AS id,\n f.rowid AS rowid,\n f.audit_event_id AS event_id,\n d.rule_id AS rule_id,\n d.category AS category,\n d.severity AS severity,\n f.span_start AS span_start,\n f.span_end AS span_end,\n f.masked_match AS masked_match,\n f.action_taken AS action_taken,\n f.confidence AS confidence,\n f.finding_key AS finding_key,\n f.first_detected_at AS first_detected_at\nFROM inspection_findings f\nJOIN audit_events e ON e.id = f.audit_event_id\nJOIN inspection_definitions d ON d.id = f.inspection_definition_id\nWHERE e.event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--> statement-breakpoint\n-- Defense in depth only: SQLite refuses to plan ANY upsert against a view\n-- (\"cannot UPSERT a view\") no matter what trigger exists, so this can never\n-- rescue the real legacy writer, which always used\n-- `ON CONFLICT (finding_key) DO UPDATE` \u2014 that statement still fails at\n-- prepare() on an old binary, same as it would with no trigger at all. This\n-- only covers a plain-INSERT shape, should one ever exist.\nCREATE TRIGGER `trg_findings_ro`\nINSTEAD OF INSERT ON `findings`\nBEGIN SELECT RAISE(ABORT, 'findings is read-only; write to inspection_findings instead'); END;\n"
565
+ },
566
+ {
567
+ tag: "0015_busy_vengeance",
568
+ sql: "CREATE TABLE `secret_vault` (\n `pointer_id` text PRIMARY KEY NOT NULL,\n `value_fingerprint` text NOT NULL,\n `fingerprint_key_version` integer NOT NULL,\n `key_version` integer NOT NULL,\n `category` text NOT NULL,\n `rule_id` text NOT NULL,\n `masked_match` text NOT NULL,\n `provider` text,\n `ciphertext` text NOT NULL,\n `nonce` text NOT NULL,\n `auth_tag` text NOT NULL,\n `occurrence_count` integer DEFAULT 1 NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_value` ON `secret_vault` (`value_fingerprint`);--> statement-breakpoint\nCREATE TABLE `secret_vault_deref` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `at` integer NOT NULL,\n `target` text NOT NULL,\n `reason` text NOT NULL,\n `outcome` text NOT NULL,\n `grant_id` text,\n `pointer_count` integer DEFAULT 1 NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_pointer` ON `secret_vault_deref` (`pointer_id`);--> statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_reason_at` ON `secret_vault_deref` (`reason`,`at`);"
569
+ },
570
+ {
571
+ tag: "0016_breezy_zodiak",
572
+ sql: "ALTER TABLE `exceptions` ADD `capability` text DEFAULT 'suppress' NOT NULL;"
573
+ },
574
+ {
575
+ tag: "0017_rainy_kat_farrell",
576
+ sql: "CREATE TABLE `secret_vault_sighting` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `location` text NOT NULL,\n `kind` text NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_sighting` ON `secret_vault_sighting` (`pointer_id`,`location`);"
577
+ },
578
+ {
579
+ tag: "0018_serious_tana_nile",
580
+ sql: "ALTER TABLE `secret_vault` ADD `format_version` integer DEFAULT 2 NOT NULL;"
565
581
  }
566
582
  ];
567
583
 
@@ -16218,6 +16234,7 @@ var ExceptionConditions = external_exports.object({
16218
16234
  sourceTool: external_exports.string().optional(),
16219
16235
  provider: external_exports.string().optional()
16220
16236
  }).strict();
16237
+ var ExceptionCapability = external_exports.enum(["suppress", "reveal_to_model"]);
16221
16238
  var DetectionException = external_exports.object({
16222
16239
  id: external_exports.guid(),
16223
16240
  ruleId: external_exports.string(),
@@ -16234,6 +16251,7 @@ var DetectionException = external_exports.object({
16234
16251
  keyVersion: external_exports.number().int().positive(),
16235
16252
  // maskMatch() preview of the approved value — never the raw value.
16236
16253
  maskedValue: external_exports.string(),
16254
+ capability: ExceptionCapability.default("suppress"),
16237
16255
  scope: ExceptionScope,
16238
16256
  expiresAt: external_exports.iso.datetime().nullable(),
16239
16257
  maxUses: external_exports.number().int().positive().nullable(),
@@ -16257,6 +16275,7 @@ var ExceptionBundleEntry = DetectionException.pick({
16257
16275
  ruleId: true,
16258
16276
  valueFingerprint: true,
16259
16277
  keyVersion: true,
16278
+ capability: true,
16260
16279
  expiresAt: true,
16261
16280
  maxUses: true,
16262
16281
  useCount: true,
@@ -17361,8 +17380,129 @@ var PatchInstalledPackRequest = external_exports.object({
17361
17380
  message: "At least one field must be provided"
17362
17381
  }).meta({ id: "PatchInstalledPackRequest" });
17363
17382
 
17383
+ // ../../packages/schema/src/zod/vault.ts
17384
+ var POINTER_FORMAT_VERSION = 2;
17385
+ var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
17386
+ var POINTER_TOKEN_PATTERN = new RegExp(
17387
+ `\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
17388
+ );
17389
+ var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
17390
+ function pointerTokenScanner() {
17391
+ return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
17392
+ }
17393
+ var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
17394
+ var ParsedPointer = external_exports.object({
17395
+ category: DetectionCategory,
17396
+ keyVersion: external_exports.number().int().positive(),
17397
+ pointerId: external_exports.string(),
17398
+ tag: external_exports.string()
17399
+ });
17400
+ var VaultEntry = external_exports.object({
17401
+ pointerId: external_exports.string(),
17402
+ // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
17403
+ // derived under. This is what a reveal-to-model grant matches on, and it rotates
17404
+ // independently of the vault encryption key below.
17405
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
17406
+ fingerprintKeyVersion: external_exports.number().int().positive(),
17407
+ // The vault-key epoch this row's ciphertext was sealed under.
17408
+ keyVersion: external_exports.number().int().positive(),
17409
+ // Fixed at first mint and never updated: the same value detected later under a
17410
+ // different rule's category keeps the category it was minted with, so one
17411
+ // value always produces exactly one wire token.
17412
+ category: DetectionCategory,
17413
+ ruleId: external_exports.string(),
17414
+ // Partial-reveal preview for badges and listings. Never the raw value.
17415
+ maskedMatch: external_exports.string(),
17416
+ provider: external_exports.string().optional(),
17417
+ ciphertext: external_exports.string(),
17418
+ nonce: external_exports.string(),
17419
+ authTag: external_exports.string(),
17420
+ // How many times this value has been detected on this machine — the reuse
17421
+ // signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
17422
+ occurrenceCount: external_exports.number().int().nonnegative(),
17423
+ firstSeen: external_exports.string(),
17424
+ lastSeen: external_exports.string()
17425
+ });
17426
+ var PointerDescriptor = external_exports.object({
17427
+ category: DetectionCategory,
17428
+ provider: external_exports.string().optional(),
17429
+ maskedMatch: external_exports.string(),
17430
+ occurrences: external_exports.number().int().nonnegative(),
17431
+ firstSeen: external_exports.string(),
17432
+ lastSeen: external_exports.string()
17433
+ });
17434
+ var PointerIdentity = external_exports.object({
17435
+ ruleId: external_exports.string(),
17436
+ valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
17437
+ fingerprintKeyVersion: external_exports.number().int().positive()
17438
+ });
17439
+ var DetokenizeTarget = external_exports.enum(["human", "model"]);
17440
+ var VaultDerefReason = external_exports.enum([
17441
+ "display",
17442
+ "explicit-reveal",
17443
+ "view-render",
17444
+ "model-input",
17445
+ "remediation",
17446
+ "purge"
17447
+ ]);
17448
+ var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
17449
+ var BATCHED_DEREF_REASONS = ["display", "view-render"];
17450
+ function isBatchedDerefReason(reason) {
17451
+ return BATCHED_DEREF_REASONS.includes(reason);
17452
+ }
17453
+ var VaultDeref = external_exports.object({
17454
+ id: external_exports.guid(),
17455
+ pointerId: external_exports.string(),
17456
+ at: external_exports.string(),
17457
+ target: DetokenizeTarget,
17458
+ reason: VaultDerefReason,
17459
+ outcome: VaultDerefOutcome,
17460
+ // Present only on a model-target crossing that a reveal grant authorized.
17461
+ grantId: external_exports.string().optional(),
17462
+ // How many pointers ONE batched render resolved. 1 for unbatched rows. Named
17463
+ // apart from VaultEntry.occurrenceCount, which counts detections of a value.
17464
+ pointerCount: external_exports.number().int().positive().default(1)
17465
+ });
17466
+ var VaultSightingKind = external_exports.enum([
17467
+ "prompt",
17468
+ "tool-input",
17469
+ "tool-output",
17470
+ "file",
17471
+ "transcript"
17472
+ ]);
17473
+ var VaultSighting = external_exports.object({
17474
+ location: external_exports.string(),
17475
+ kind: VaultSightingKind,
17476
+ firstSeen: external_exports.string(),
17477
+ lastSeen: external_exports.string()
17478
+ });
17479
+ var VaultInventoryEntry = external_exports.object({
17480
+ pointerId: external_exports.string(),
17481
+ category: DetectionCategory,
17482
+ provider: external_exports.string().optional(),
17483
+ maskedMatch: external_exports.string(),
17484
+ occurrences: external_exports.number().int().nonnegative(),
17485
+ firstSeen: external_exports.string(),
17486
+ lastSeen: external_exports.string(),
17487
+ // The active reveal-to-model grant covering this value, when one exists —
17488
+ // the inventory badges it, the row links to revocation.
17489
+ revealGrantId: external_exports.string().nullable(),
17490
+ sightings: external_exports.array(VaultSighting)
17491
+ });
17492
+ var VaultKeyCustody = external_exports.string();
17493
+ var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
17494
+ var VAULT_EVENT_NOTE_MAX_POINTERS = 8;
17495
+ var VAULT_CONSENT_VERSION = 1;
17496
+ var VaultConsent = external_exports.object({
17497
+ acknowledgedAt: external_exports.iso.datetime(),
17498
+ version: external_exports.number().int().positive()
17499
+ });
17500
+ function isVaultConsentValid(consent) {
17501
+ return consent?.version === VAULT_CONSENT_VERSION;
17502
+ }
17503
+
17364
17504
  // ../../packages/schema/src/zod/local.ts
17365
- var WORKSPACE_SETTINGS_SPEC_VERSION = 4;
17505
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 5;
17366
17506
  var RunMode = external_exports.enum(["standalone"]);
17367
17507
  var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
17368
17508
  var HistoricalAccess = external_exports.enum(["full", "session-only"]);
@@ -17384,6 +17524,16 @@ var WorkspaceSettings = external_exports.object({
17384
17524
  // In-place egress extraction on the scan paths; disable to stop all Data
17385
17525
  // Shares writes.
17386
17526
  dataSharesInPlace: external_exports.boolean().default(true),
17527
+ // Consent to keep a RECOVERABLE encrypted copy of detected values in the local
17528
+ // vault, instead of destroying them. Absent by default: this is a custody
17529
+ // change from one-way redaction, so it is never an assumed grant on upgrade.
17530
+ // Revoking stops future vaulting; it does not erase what is already stored —
17531
+ // purging the vault is the eraser.
17532
+ vaultConsent: VaultConsent.optional(),
17533
+ // Where the vault master key lives.
17534
+ vaultKeyCustody: VaultKeyCustody.default("file"),
17535
+ // How a pointer renders in assistant prose on screen (see VaultInlineReveal).
17536
+ vaultInlineReveal: VaultInlineReveal.default("masked"),
17387
17537
  // Absent until /aka:setup completes; its presence is what "onboarded" means.
17388
17538
  onboardedAt: external_exports.iso.datetime().optional(),
17389
17539
  // Records that the user consented to sending findings to the model API for
@@ -19798,6 +19948,9 @@ var AmbiguousExceptionIdError = class extends Error {
19798
19948
  var ACTIVE_PREDICATE = `revoked_at IS NULL
19799
19949
  AND (expires_at IS NULL OR expires_at > :now)
19800
19950
  AND (max_uses IS NULL OR use_count < max_uses)`;
19951
+ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
19952
+ AND conditions IS NULL
19953
+ AND ${ACTIVE_PREDICATE}`;
19801
19954
  var SqliteExceptionsRepository = class {
19802
19955
  constructor(db) {
19803
19956
  this.db = db;
@@ -19889,11 +20042,11 @@ var SqliteExceptionsRepository = class {
19889
20042
  this.db.prepare(
19890
20043
  `INSERT INTO exceptions (
19891
20044
  id, rule_id, category, value_fingerprint, key_version, masked_value,
19892
- scope, expires_at, max_uses, use_count, last_used_at, justification,
19893
- conditions, created_by, created_via, created_at, updated_at
20045
+ capability, scope, expires_at, max_uses, use_count, last_used_at,
20046
+ justification, conditions, created_by, created_via, created_at, updated_at
19894
20047
  ) VALUES (
19895
20048
  :id, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue,
19896
- :scope, :expiresAt, :maxUses, 0, NULL, :justification,
20049
+ :capability, :scope, :expiresAt, :maxUses, 0, NULL, :justification,
19897
20050
  :conditions, :createdBy, :createdVia, :now, :now
19898
20051
  )`
19899
20052
  ).run({
@@ -19903,6 +20056,7 @@ var SqliteExceptionsRepository = class {
19903
20056
  valueFingerprint: input.valueFingerprint,
19904
20057
  keyVersion: input.keyVersion,
19905
20058
  maskedValue: input.maskedValue,
20059
+ capability: input.capability ?? "suppress",
19906
20060
  scope: input.scope,
19907
20061
  expiresAt: input.expiresAt === null ? null : isoToEpochMillis(input.expiresAt),
19908
20062
  maxUses: input.maxUses,
@@ -19996,6 +20150,7 @@ var SqliteExceptionsRepository = class {
19996
20150
  ruleId: row.rule_id,
19997
20151
  valueFingerprint: row.value_fingerprint,
19998
20152
  keyVersion: row.key_version,
20153
+ capability: row.capability,
19999
20154
  expiresAt: row.expires_at === null ? null : epochMillisToIso(row.expires_at),
20000
20155
  maxUses: row.max_uses,
20001
20156
  useCount: row.use_count,
@@ -20050,6 +20205,35 @@ var SqliteExceptionsRepository = class {
20050
20205
  }))
20051
20206
  );
20052
20207
  }
20208
+ /**
20209
+ * The active reveal-to-model grant for a vaulted value's identity, or null.
20210
+ * Matching is exact on (ruleId, valueFingerprint, keyVersion) — the same key
20211
+ * suppression uses — plus the capability: a suppression grant must never
20212
+ * authorize a reveal. Read-only: the caller does NOT consume here, because a
20213
+ * revealed value re-enters the detection scan immediately afterward and the
20214
+ * suppression match there claims the use — one crossing, one use.
20215
+ *
20216
+ * A grant with `conditions` NEVER matches here: the reveal path does not yet
20217
+ * evaluate conditions, and a narrowing clause that is ignored would WIDEN the
20218
+ * grant instead. Fail closed until reveal-side condition evaluation exists.
20219
+ */
20220
+ activeRevealGrant(ruleId, valueFingerprint, keyVersion, now = Date.now()) {
20221
+ try {
20222
+ const row = getRow(
20223
+ this.db.prepare(
20224
+ `SELECT id FROM exceptions
20225
+ WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
20226
+ AND key_version = :keyVersion
20227
+ AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
20228
+ LIMIT 1`
20229
+ ),
20230
+ { ruleId, valueFingerprint, keyVersion, now }
20231
+ );
20232
+ return Promise.resolve(row ?? null);
20233
+ } catch (err) {
20234
+ return Promise.reject(err instanceof Error ? err : new Error(String(err)));
20235
+ }
20236
+ }
20053
20237
  /**
20054
20238
  * Retention sweep: delete TERMINAL rows (revoked, expired, or use-budget
20055
20239
  * exhausted) whose last transition is older than the retention window.
@@ -20077,6 +20261,7 @@ function parseExceptionRow(row) {
20077
20261
  valueFingerprint: row.value_fingerprint,
20078
20262
  keyVersion: row.key_version,
20079
20263
  maskedValue: row.masked_value,
20264
+ capability: row.capability,
20080
20265
  scope: row.scope,
20081
20266
  expiresAt: row.expires_at === null ? null : epochMillisToIso(row.expires_at),
20082
20267
  maxUses: row.max_uses,
@@ -22242,6 +22427,287 @@ var SqliteScanLedgerRepository = class {
22242
22427
  }
22243
22428
  };
22244
22429
 
22430
+ // ../../packages/persistence/src/repositories/secret-vault.ts
22431
+ import { randomUUID as randomUUID7 } from "crypto";
22432
+ var SELECT_COLUMNS = `
22433
+ pointer_id AS pointerId,
22434
+ value_fingerprint AS valueFingerprint,
22435
+ fingerprint_key_version AS fingerprintKeyVersion,
22436
+ key_version AS keyVersion,
22437
+ format_version AS formatVersion,
22438
+ category,
22439
+ rule_id AS ruleId,
22440
+ masked_match AS maskedMatch,
22441
+ provider,
22442
+ ciphertext,
22443
+ nonce,
22444
+ auth_tag AS authTag,
22445
+ occurrence_count AS occurrenceCount,
22446
+ first_seen AS firstSeen,
22447
+ last_seen AS lastSeen`;
22448
+ function toRow(raw) {
22449
+ const { provider, ...rest } = raw;
22450
+ return provider === null ? rest : { ...rest, provider };
22451
+ }
22452
+ var SqliteSecretVaultRepository = class {
22453
+ constructor(db) {
22454
+ this.db = db;
22455
+ this.insertStmt = db.prepare(
22456
+ `INSERT INTO secret_vault (
22457
+ pointer_id, value_fingerprint, fingerprint_key_version, key_version,
22458
+ format_version, category, rule_id, masked_match, provider,
22459
+ ciphertext, nonce, auth_tag,
22460
+ occurrence_count, first_seen, last_seen
22461
+ ) VALUES (
22462
+ :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
22463
+ :formatVersion, :category, :ruleId, :maskedMatch, :provider,
22464
+ :ciphertext, :nonce, :authTag,
22465
+ 1, :now, :now
22466
+ )`
22467
+ );
22468
+ this.bumpStmt = db.prepare(
22469
+ `UPDATE secret_vault
22470
+ SET occurrence_count = occurrence_count + 1, last_seen = :now
22471
+ WHERE value_fingerprint = :valueFingerprint`
22472
+ );
22473
+ this.byPointerStmt = db.prepare(
22474
+ `SELECT ${SELECT_COLUMNS} FROM secret_vault WHERE pointer_id = :pointerId`
22475
+ );
22476
+ this.byFingerprintStmt = db.prepare(
22477
+ `SELECT ${SELECT_COLUMNS} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`
22478
+ );
22479
+ this.listStmt = db.prepare(`SELECT ${SELECT_COLUMNS} FROM secret_vault ORDER BY first_seen`);
22480
+ this.replaceCiphertextStmt = db.prepare(
22481
+ `UPDATE secret_vault
22482
+ SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
22483
+ WHERE pointer_id = :pointerId`
22484
+ );
22485
+ this.refreshFingerprintStmt = db.prepare(
22486
+ `UPDATE secret_vault
22487
+ SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
22488
+ WHERE pointer_id = :pointerId`
22489
+ );
22490
+ this.derefStmt = db.prepare(
22491
+ `INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
22492
+ VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
22493
+ );
22494
+ }
22495
+ db;
22496
+ insertStmt;
22497
+ bumpStmt;
22498
+ byPointerStmt;
22499
+ byFingerprintStmt;
22500
+ listStmt;
22501
+ replaceCiphertextStmt;
22502
+ refreshFingerprintStmt;
22503
+ derefStmt;
22504
+ /**
22505
+ * Vault a value, or record another sighting of one already vaulted. Keyed on
22506
+ * `valueFingerprint`, never on the caller's pointer id: a value seen again
22507
+ * bumps `occurrence_count` and `last_seen` and comes back with its ORIGINAL
22508
+ * pointer, category and ciphertext, so the same secret always resolves to one
22509
+ * wire token. `minted` is true only when this call created the row.
22510
+ *
22511
+ * The read-then-write runs in one IMMEDIATE transaction so two concurrent
22512
+ * writers cannot both decide they are minting.
22513
+ */
22514
+ upsert(input, now) {
22515
+ let minted = false;
22516
+ withTransaction(
22517
+ this.db,
22518
+ () => {
22519
+ const existing = getRow(this.byFingerprintStmt, {
22520
+ valueFingerprint: input.valueFingerprint
22521
+ });
22522
+ if (existing === void 0) {
22523
+ this.insertStmt.run(
22524
+ bindParams({
22525
+ pointerId: input.pointerId,
22526
+ valueFingerprint: input.valueFingerprint,
22527
+ fingerprintKeyVersion: input.fingerprintKeyVersion,
22528
+ keyVersion: input.keyVersion,
22529
+ formatVersion: input.formatVersion ?? POINTER_FORMAT_VERSION,
22530
+ category: input.category,
22531
+ ruleId: input.ruleId,
22532
+ maskedMatch: input.maskedMatch,
22533
+ provider: input.provider,
22534
+ ciphertext: input.ciphertext,
22535
+ nonce: input.nonce,
22536
+ authTag: input.authTag,
22537
+ now
22538
+ })
22539
+ );
22540
+ minted = true;
22541
+ return;
22542
+ }
22543
+ this.bumpStmt.run({ valueFingerprint: input.valueFingerprint, now });
22544
+ },
22545
+ "IMMEDIATE"
22546
+ );
22547
+ const row = getRow(this.byFingerprintStmt, {
22548
+ valueFingerprint: input.valueFingerprint
22549
+ });
22550
+ if (row === void 0) throw new Error("vault: row vanished immediately after write");
22551
+ return { row: toRow(row), minted };
22552
+ }
22553
+ byPointerId(pointerId) {
22554
+ const raw = getRow(this.byPointerStmt, { pointerId });
22555
+ return raw === void 0 ? null : toRow(raw);
22556
+ }
22557
+ byValueFingerprint(fingerprint) {
22558
+ const raw = getRow(this.byFingerprintStmt, { valueFingerprint: fingerprint });
22559
+ return raw === void 0 ? null : toRow(raw);
22560
+ }
22561
+ /** Append one audit row. Carries no raw value and no ciphertext, by shape. */
22562
+ recordDeref(entry) {
22563
+ this.derefStmt.run(
22564
+ bindParams({
22565
+ id: entry.id,
22566
+ pointerId: entry.pointerId,
22567
+ at: entry.at,
22568
+ target: entry.target,
22569
+ reason: entry.reason,
22570
+ outcome: entry.outcome,
22571
+ grantId: entry.grantId,
22572
+ pointerCount: entry.pointerCount ?? 1
22573
+ })
22574
+ );
22575
+ }
22576
+ listAll() {
22577
+ return allRows(this.listStmt).map(toRow);
22578
+ }
22579
+ /** Re-seal an entry under a new key epoch, leaving its identity untouched. */
22580
+ replaceCiphertext(pointerId, next) {
22581
+ this.replaceCiphertextStmt.run({ pointerId, ...next });
22582
+ }
22583
+ /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
22584
+ refreshFingerprint(pointerId, next) {
22585
+ this.refreshFingerprintStmt.run({ pointerId, ...next });
22586
+ }
22587
+ /**
22588
+ * Destroy every vaulted value and report how many were destroyed. The deref
22589
+ * audit is left alone on purpose — see the table note above.
22590
+ */
22591
+ purgeAll() {
22592
+ let destroyed = 0;
22593
+ withTransaction(
22594
+ this.db,
22595
+ () => {
22596
+ destroyed = this.countEntries();
22597
+ this.db.exec("DELETE FROM secret_vault");
22598
+ },
22599
+ "IMMEDIATE"
22600
+ );
22601
+ return destroyed;
22602
+ }
22603
+ /**
22604
+ * Record (or re-stamp) one place a pointer has been written. One row per
22605
+ * (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
22606
+ * on hook paths — a failure must never affect the rewrite that triggered it,
22607
+ * so callers wrap this, not the other way around.
22608
+ */
22609
+ recordSighting(entry, now) {
22610
+ this.db.prepare(
22611
+ `INSERT INTO secret_vault_sighting (id, pointer_id, location, kind, first_seen, last_seen)
22612
+ VALUES (:id, :pointerId, :location, :kind, :now, :now)
22613
+ ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
22614
+ ).run({
22615
+ id: randomUUID7(),
22616
+ pointerId: entry.pointerId,
22617
+ location: entry.location,
22618
+ kind: entry.kind,
22619
+ now
22620
+ });
22621
+ }
22622
+ listSightings(pointerId) {
22623
+ const rows = allRows(
22624
+ this.db.prepare(
22625
+ `SELECT location, kind, first_seen, last_seen FROM secret_vault_sighting
22626
+ WHERE pointer_id = :pointerId ORDER BY last_seen DESC`
22627
+ ),
22628
+ { pointerId }
22629
+ );
22630
+ return rows.map((r) => ({
22631
+ location: r.location,
22632
+ kind: r.kind,
22633
+ firstSeen: new Date(r.first_seen).toISOString(),
22634
+ lastSeen: new Date(r.last_seen).toISOString()
22635
+ }));
22636
+ }
22637
+ /**
22638
+ * The dashboard inventory: every vaulted value's descriptor data joined with
22639
+ * its sightings and the active reveal-to-model grant when one exists.
22640
+ * Raw-free by construction — neither the fingerprint nor the ciphertext
22641
+ * columns are selected.
22642
+ */
22643
+ listInventory(now = Date.now()) {
22644
+ const rows = allRows(
22645
+ this.db.prepare(
22646
+ `SELECT v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
22647
+ v.occurrence_count, v.first_seen, v.last_seen,
22648
+ (SELECT e.id FROM exceptions e
22649
+ WHERE e.rule_id = v.rule_id
22650
+ AND e.value_fingerprint = v.value_fingerprint
22651
+ AND e.key_version = v.fingerprint_key_version
22652
+ AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
22653
+ LIMIT 1) AS grant_id
22654
+ FROM secret_vault v
22655
+ ORDER BY v.last_seen DESC`
22656
+ ),
22657
+ { now }
22658
+ );
22659
+ return rows.map((r) => ({
22660
+ pointerId: r.pointer_id,
22661
+ category: r.category,
22662
+ ...r.provider === null ? {} : { provider: r.provider },
22663
+ maskedMatch: r.masked_match,
22664
+ occurrences: r.occurrence_count,
22665
+ firstSeen: new Date(r.first_seen).toISOString(),
22666
+ lastSeen: new Date(r.last_seen).toISOString(),
22667
+ revealGrantId: r.grant_id,
22668
+ sightings: this.listSightings(r.pointer_id)
22669
+ }));
22670
+ }
22671
+ /**
22672
+ * The de-reference trail, newest first. By default the batched, high-volume
22673
+ * reasons (display, view-render) are hidden and counted instead — the rows
22674
+ * that matter as a signal are the model crossings, and burying them under
22675
+ * render noise would defeat the audit's purpose.
22676
+ */
22677
+ listDerefs(opts) {
22678
+ const limit = opts?.limit ?? 200;
22679
+ const where = opts?.includeBatched === true ? "" : `WHERE reason NOT IN ('display', 'view-render')`;
22680
+ const rows = allRows(
22681
+ this.db.prepare(
22682
+ `SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
22683
+ FROM secret_vault_deref ${where}
22684
+ ORDER BY at DESC, rowid DESC LIMIT :limit`
22685
+ ),
22686
+ { limit }
22687
+ );
22688
+ const hiddenBatched = opts?.includeBatched === true ? 0 : countScalar(
22689
+ this.db,
22690
+ `SELECT count(*) AS n FROM secret_vault_deref WHERE reason IN ('display', 'view-render')`
22691
+ );
22692
+ return {
22693
+ rows: rows.map((r) => ({
22694
+ id: r.id,
22695
+ pointerId: r.pointer_id,
22696
+ at: new Date(r.at).toISOString(),
22697
+ target: r.target,
22698
+ reason: r.reason,
22699
+ outcome: r.outcome,
22700
+ ...r.grant_id === null ? {} : { grantId: r.grant_id },
22701
+ pointerCount: r.pointer_count
22702
+ })),
22703
+ hiddenBatched
22704
+ };
22705
+ }
22706
+ countEntries() {
22707
+ return countScalar(this.db, "SELECT COUNT(*) AS n FROM secret_vault");
22708
+ }
22709
+ };
22710
+
22245
22711
  // ../../packages/persistence/src/repositories/security.ts
22246
22712
  var DAY_MS4 = 864e5;
22247
22713
  var SEVERITIES = ["critical", "high", "medium", "low"];
@@ -22587,7 +23053,7 @@ var SqliteSecurityRepository = class {
22587
23053
  };
22588
23054
 
22589
23055
  // ../../packages/persistence/src/repositories/shares.ts
22590
- import { randomUUID as randomUUID7 } from "crypto";
23056
+ import { randomUUID as randomUUID8 } from "crypto";
22591
23057
  var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
22592
23058
  var IN_CHUNK = 500;
22593
23059
  var KIND_ORDER = ["provider", "internal", "external", "ip"];
@@ -22843,7 +23309,7 @@ var SqliteSharesRepository = class {
22843
23309
  (id, destination_id, host, decision, created_at, updated_at)
22844
23310
  VALUES (:id, :destinationId, :host, :decision, :now, :now)`
22845
23311
  ).run({
22846
- id: randomUUID7(),
23312
+ id: randomUUID8(),
22847
23313
  destinationId,
22848
23314
  host: dest.host,
22849
23315
  decision,
@@ -22992,7 +23458,7 @@ var SqliteSharesRepository = class {
22992
23458
  let destinationId = destIds.get(hit.host);
22993
23459
  if (destinationId === void 0) {
22994
23460
  destStmt.run({
22995
- id: randomUUID7(),
23461
+ id: randomUUID8(),
22996
23462
  kind: hit.kind,
22997
23463
  name: hit.name,
22998
23464
  host: hit.host,
@@ -23008,7 +23474,7 @@ var SqliteSharesRepository = class {
23008
23474
  let endpointId = endpointIds.get(endpointKey);
23009
23475
  if (endpointId === void 0) {
23010
23476
  endpointStmt.run({
23011
- id: randomUUID7(),
23477
+ id: randomUUID8(),
23012
23478
  destinationId,
23013
23479
  method: hit.method,
23014
23480
  transport: hit.transport,
@@ -23021,7 +23487,7 @@ var SqliteSharesRepository = class {
23021
23487
  endpointIds.set(endpointKey, endpointId);
23022
23488
  }
23023
23489
  siteStmt.run({
23024
- id: randomUUID7(),
23490
+ id: randomUUID8(),
23025
23491
  endpointId,
23026
23492
  project: input.project,
23027
23493
  projectKey: input.projectKey,
@@ -23389,11 +23855,22 @@ function purgeSampleData(db) {
23389
23855
  function linkHost(input, hostId) {
23390
23856
  return hostId ? { ...input, hostId } : input;
23391
23857
  }
23858
+ function closeQuietly(db) {
23859
+ try {
23860
+ db.close();
23861
+ } catch {
23862
+ }
23863
+ }
23392
23864
  function openWithPragmas(file2) {
23393
23865
  const db = new DatabaseSync(file2);
23394
- db.exec("PRAGMA journal_mode = WAL");
23395
- db.exec("PRAGMA busy_timeout = 2000");
23396
- db.exec("PRAGMA foreign_keys = ON");
23866
+ try {
23867
+ db.exec("PRAGMA journal_mode = WAL");
23868
+ db.exec("PRAGMA busy_timeout = 2000");
23869
+ db.exec("PRAGMA foreign_keys = ON");
23870
+ } catch (err) {
23871
+ closeQuietly(db);
23872
+ throw err;
23873
+ }
23397
23874
  return db;
23398
23875
  }
23399
23876
  function backupLegacyStore(file2) {
@@ -23405,43 +23882,82 @@ function backupLegacyStore(file2) {
23405
23882
  }
23406
23883
  return backup;
23407
23884
  }
23885
+ function openAndInitialize(file2) {
23886
+ let db = openWithPragmas(file2);
23887
+ try {
23888
+ if (isForeignSqliteLineage(db)) {
23889
+ db.close();
23890
+ const backup = backupLegacyStore(file2);
23891
+ db = openWithPragmas(file2);
23892
+ akaWarn(
23893
+ `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
23894
+ );
23895
+ }
23896
+ applyMigrations(db, file2);
23897
+ tightenPerms(file2);
23898
+ const policies = new SqlitePoliciesRepository(db);
23899
+ const installedPacks = new SqliteInstalledPacksRepository(db);
23900
+ const repositories = {
23901
+ events: new SqliteEventsRepository(db),
23902
+ findings: new SqliteFindingsRepository(db),
23903
+ policies,
23904
+ installedPacks,
23905
+ scanLedger: new SqliteScanLedgerRepository(db),
23906
+ secretVault: new SqliteSecretVaultRepository(db),
23907
+ exceptions: new SqliteExceptionsRepository(db),
23908
+ resolutions: new SqliteResolutionsRepository(db),
23909
+ ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
23910
+ security: new SqliteSecurityRepository(db),
23911
+ detections: new SqliteDetectionsRepository(db),
23912
+ shares: new SqliteSharesRepository(db),
23913
+ policyCatalog: new SqlitePolicyCatalogRepository(installedPacks),
23914
+ inventory: new SqliteInventoryRepository(db),
23915
+ inventoryAssets: new SqliteInventoryAssetsRepository(db),
23916
+ projectFiles: new SqliteProjectFilesRepository(db),
23917
+ activity: new SqliteActivityRepository(db),
23918
+ sourceProject: new SqliteSourceProjectRepository(db),
23919
+ auditEvents: new SqliteAuditEventsRepository(db),
23920
+ classifiedData: new SqliteClassifiedDataRepository(db),
23921
+ inspectionDefinitions: new SqliteInspectionDefinitionsRepository(db),
23922
+ inspectionFindings: new SqliteInspectionFindingsRepository(db),
23923
+ configInventory: new SqliteConfigInventoryRepository(db)
23924
+ };
23925
+ policies.seedDefaults();
23926
+ return { db, ...repositories };
23927
+ } catch (err) {
23928
+ closeQuietly(db);
23929
+ throw err;
23930
+ }
23931
+ }
23408
23932
  function openLocalDatabase(dir) {
23409
23933
  ensureDataDirSync(dir);
23410
23934
  const file2 = join(dir, DB_FILENAME);
23411
- let db = openWithPragmas(file2);
23412
- if (isForeignSqliteLineage(db)) {
23413
- db.close();
23414
- const backup = backupLegacyStore(file2);
23415
- db = openWithPragmas(file2);
23416
- akaWarn(
23417
- `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
23418
- );
23419
- }
23420
- applyMigrations(db, file2);
23421
- tightenPerms(file2);
23422
- const events = new SqliteEventsRepository(db);
23423
- const findings = new SqliteFindingsRepository(db);
23424
- const policies = new SqlitePoliciesRepository(db);
23425
- const installedPacks = new SqliteInstalledPacksRepository(db);
23426
- const scanLedger = new SqliteScanLedgerRepository(db);
23427
- const exceptions = new SqliteExceptionsRepository(db);
23428
- const resolutions = new SqliteResolutionsRepository(db);
23429
- const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
23430
- const security = new SqliteSecurityRepository(db);
23431
- const detections = new SqliteDetectionsRepository(db);
23432
- const shares = new SqliteSharesRepository(db);
23433
- const policyCatalog = new SqlitePolicyCatalogRepository(installedPacks);
23434
- const inventory = new SqliteInventoryRepository(db);
23435
- const inventoryAssets = new SqliteInventoryAssetsRepository(db);
23436
- const projectFiles = new SqliteProjectFilesRepository(db);
23437
- const activity = new SqliteActivityRepository(db);
23438
- const sourceProject = new SqliteSourceProjectRepository(db);
23439
- const auditEvents = new SqliteAuditEventsRepository(db);
23440
- const classifiedData = new SqliteClassifiedDataRepository(db);
23441
- const inspectionDefinitions = new SqliteInspectionDefinitionsRepository(db);
23442
- const inspectionFindings = new SqliteInspectionFindingsRepository(db);
23443
- const configInventory = new SqliteConfigInventoryRepository(db);
23444
- policies.seedDefaults();
23935
+ const {
23936
+ db,
23937
+ events,
23938
+ findings,
23939
+ policies,
23940
+ installedPacks,
23941
+ scanLedger,
23942
+ secretVault,
23943
+ exceptions,
23944
+ resolutions,
23945
+ ruleProbeCache,
23946
+ security,
23947
+ detections,
23948
+ shares,
23949
+ policyCatalog,
23950
+ inventory,
23951
+ inventoryAssets,
23952
+ projectFiles,
23953
+ activity,
23954
+ sourceProject,
23955
+ auditEvents,
23956
+ classifiedData,
23957
+ inspectionDefinitions,
23958
+ inspectionFindings,
23959
+ configInventory
23960
+ } = openAndInitialize(file2);
23445
23961
  function recordCapture(event, detected) {
23446
23962
  failOpenTransaction(db, () => {
23447
23963
  const sessionId = event.metadata?.sessionId;
@@ -23532,7 +24048,7 @@ function openLocalDatabase(dir) {
23532
24048
  const definitionId = definitionIds.get(`${finding.ruleId}@${finding.version}`);
23533
24049
  if (!definitionId) continue;
23534
24050
  inspectionFindings.insertFinding({
23535
- id: randomUUID8(),
24051
+ id: randomUUID9(),
23536
24052
  auditEventId: record2.scanEvent.id,
23537
24053
  inspectionDefinitionId: definitionId,
23538
24054
  span: finding.span,
@@ -23609,6 +24125,7 @@ function openLocalDatabase(dir) {
23609
24125
  policies,
23610
24126
  installedPacks,
23611
24127
  scanLedger,
24128
+ secretVault,
23612
24129
  exceptions,
23613
24130
  resolutions,
23614
24131
  ruleProbeCache,
@@ -23641,6 +24158,26 @@ function openLocalDatabase(dir) {
23641
24158
  };
23642
24159
  }
23643
24160
 
24161
+ // ../../packages/persistence/src/exception-policy.ts
24162
+ var UserGrantPolicyProvider = class {
24163
+ #exceptions;
24164
+ constructor(exceptions) {
24165
+ this.#exceptions = exceptions;
24166
+ }
24167
+ async decideReveal(identity) {
24168
+ try {
24169
+ const grant = await this.#exceptions.activeRevealGrant(
24170
+ identity.ruleId,
24171
+ identity.valueFingerprint,
24172
+ identity.fingerprintKeyVersion
24173
+ );
24174
+ return grant === null ? { allow: false } : { allow: true, grantId: grant.id };
24175
+ } catch {
24176
+ return { allow: false };
24177
+ }
24178
+ }
24179
+ };
24180
+
23644
24181
  // ../../packages/persistence/src/finding-key.ts
23645
24182
  import { createHash as createHash3 } from "crypto";
23646
24183
  function normalizeFilePath(filePath) {
@@ -23653,8 +24190,9 @@ function computeFindingKey(input) {
23653
24190
 
23654
24191
  // ../../packages/persistence/src/fingerprint.ts
23655
24192
  import { createHmac, randomBytes } from "crypto";
23656
- import { readFileSync } from "fs";
24193
+ import { existsSync as existsSync2, readFileSync } from "fs";
23657
24194
  import { join as join2 } from "path";
24195
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
23658
24196
  var KEY_FILENAME = "exception.key";
23659
24197
  var KEY_MATERIAL_BYTES = 32;
23660
24198
  function keyFilePath(dataDir2) {
@@ -23678,6 +24216,50 @@ function parseKeyFile(raw) {
23678
24216
  }
23679
24217
  return { version: version2, material: bytes };
23680
24218
  }
24219
+ var KEY_VERSION_COLUMNS = {
24220
+ exceptions: "key_version",
24221
+ blocked_detections: "key_version",
24222
+ secret_vault: "fingerprint_key_version"
24223
+ };
24224
+ var SQLITE_ERROR = 1;
24225
+ var FLOOR_BUSY_TIMEOUT_MS = 250;
24226
+ var FloorUnreadableError = class extends Error {
24227
+ code = "floor-unreadable";
24228
+ constructor(cause) {
24229
+ super(
24230
+ `cannot read the stored fingerprint key versions: ${cause instanceof Error ? cause.message : String(cause)}`,
24231
+ { cause }
24232
+ );
24233
+ this.name = "FloorUnreadableError";
24234
+ }
24235
+ };
24236
+ function storedKeyVersionFloor(dataDir2) {
24237
+ const file2 = join2(dataDir2, DB_FILENAME);
24238
+ if (!existsSync2(file2)) return 0;
24239
+ let db;
24240
+ try {
24241
+ db = new DatabaseSync2(file2, { readOnly: true });
24242
+ db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
24243
+ let floor = 0;
24244
+ for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
24245
+ try {
24246
+ const row = getRow(
24247
+ db.prepare(`SELECT MAX(${column}) AS v FROM ${table}`)
24248
+ );
24249
+ floor = Math.max(floor, row?.v ?? 0);
24250
+ } catch (err) {
24251
+ if (err.errcode !== SQLITE_ERROR) {
24252
+ throw new FloorUnreadableError(err);
24253
+ }
24254
+ }
24255
+ }
24256
+ return floor;
24257
+ } catch (err) {
24258
+ throw err instanceof FloorUnreadableError ? err : new FloorUnreadableError(err);
24259
+ } finally {
24260
+ db?.close();
24261
+ }
24262
+ }
23681
24263
  function writeKeyFile(dataDir2, key) {
23682
24264
  ensureDataDirSync(dataDir2);
23683
24265
  const file2 = keyFilePath(dataDir2);
@@ -23702,7 +24284,10 @@ function loadOrCreateFingerprintKey(dataDir2) {
23702
24284
  tightenFile(keyFilePath(dataDir2));
23703
24285
  return existing;
23704
24286
  }
23705
- return writeKeyFile(dataDir2, { version: 1, material: randomBytes(KEY_MATERIAL_BYTES) });
24287
+ return writeKeyFile(dataDir2, {
24288
+ version: storedKeyVersionFloor(dataDir2) + 1,
24289
+ material: randomBytes(KEY_MATERIAL_BYTES)
24290
+ });
23706
24291
  }
23707
24292
  function fingerprintValue(key, raw) {
23708
24293
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
@@ -23725,6 +24310,9 @@ function dataDir(base = defaultDataDir()) {
23725
24310
  function dbPath(base = defaultDataDir()) {
23726
24311
  return join3(dataDir(base), "aka.db");
23727
24312
  }
24313
+ function keysDir(base = defaultDataDir()) {
24314
+ return join3(base, "keys");
24315
+ }
23728
24316
  function ensureLayoutDirSync(dir = defaultDataDir()) {
23729
24317
  ensureDataDirSync(dir);
23730
24318
  }
@@ -23766,44 +24354,905 @@ function readJson(file2) {
23766
24354
  return parseJsonObject(text) ?? null;
23767
24355
  }
23768
24356
 
23769
- // ../../packages/persistence/src/warn-era-cap.ts
23770
- import { existsSync as existsSync2, writeFileSync as writeFileSync2 } from "fs";
23771
- import { join as join5 } from "path";
23772
- var MARKER = "warn-era-capped";
23773
- function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
23774
- if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
23775
- const marker = join5(dataDir2, MARKER);
23776
- if (existsSync2(marker)) return { capped: 0, skipped: "already-run" };
23777
- const capped = db.policies.capCategoryActions();
23778
- writeFileSync2(marker, `${new Date(Date.now()).toISOString()}
23779
- `, { mode: DATA_FILE_MODE });
23780
- return { capped };
24357
+ // ../../packages/persistence/src/vault/crypto.ts
24358
+ import {
24359
+ createCipheriv,
24360
+ createDecipheriv,
24361
+ createHmac as createHmac2,
24362
+ hkdfSync,
24363
+ timingSafeEqual
24364
+ } from "crypto";
24365
+ var POINTER_ID_BYTES = 16;
24366
+ var NONCE_BYTES = 12;
24367
+ var TAG_BYTES = 10;
24368
+ var SUBKEY_BYTES = 32;
24369
+ var HKDF_INFO_ENC = "aka:vault:enc:v1";
24370
+ var HKDF_INFO_SIGN = "aka:vault:sign:v1";
24371
+ var HKDF_SALT = "aka:vault:v1";
24372
+ var B32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
24373
+ function base32Encode(bytes) {
24374
+ let out = "";
24375
+ let buffer = 0;
24376
+ let bits = 0;
24377
+ for (const byte of bytes) {
24378
+ buffer = buffer << 8 | byte;
24379
+ bits += 8;
24380
+ while (bits >= 5) {
24381
+ out += B32_ALPHABET.charAt(buffer >>> bits - 5 & 31);
24382
+ bits -= 5;
24383
+ }
24384
+ }
24385
+ if (bits > 0) out += B32_ALPHABET.charAt(buffer << 5 - bits & 31);
24386
+ return out;
23781
24387
  }
23782
-
23783
- // ../../packages/plugin-sdk/src/provider-env.ts
23784
- var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
23785
- var booleanish = external_exports.string().optional().transform((v) => {
23786
- if (v === void 0) return void 0;
23787
- const t = v.trim().toLowerCase();
23788
- if (t === "" || t === "false" || t === "0") return false;
23789
- return true;
23790
- }).catch(void 0);
23791
- var optionalBaseUrl = external_exports.preprocess((v) => {
23792
- if (typeof v === "string" && v.trim() === "") return void 0;
23793
- return v;
23794
- }, external_exports.string().optional()).catch(void 0);
23795
- var providerEnvShape = {
23796
- CLAUDE_CODE_USE_BEDROCK: booleanish,
23797
- CLAUDE_CODE_USE_VERTEX: booleanish,
23798
- ANTHROPIC_BASE_URL: optionalBaseUrl
23799
- };
23800
- var ProviderEnvSchema = external_exports.object(providerEnvShape);
23801
-
23802
- // ../../packages/plugin-sdk/src/provider.ts
23803
- function hostOf(url2) {
24388
+ function base32Decode(text) {
24389
+ const out = [];
24390
+ let buffer = 0;
24391
+ let bits = 0;
24392
+ for (const char of text) {
24393
+ const value = B32_ALPHABET.indexOf(char);
24394
+ if (value < 0) throw new Error("base32: character outside the alphabet");
24395
+ buffer = buffer << 5 | value;
24396
+ bits += 5;
24397
+ if (bits >= 8) {
24398
+ out.push(buffer >>> bits - 8 & 255);
24399
+ bits -= 8;
24400
+ }
24401
+ }
24402
+ return Buffer.from(out);
24403
+ }
24404
+ function encodeKeyVersion(version2) {
24405
+ if (!Number.isInteger(version2) || version2 < 1 || version2 > 4294967295) {
24406
+ throw new Error("vault: key version out of range");
24407
+ }
24408
+ const bytes = [];
24409
+ let remaining = version2;
24410
+ while (remaining > 0) {
24411
+ bytes.unshift(remaining & 255);
24412
+ remaining = Math.floor(remaining / 256);
24413
+ }
24414
+ return base32Encode(Uint8Array.from(bytes));
24415
+ }
24416
+ function decodeKeyVersion(encoded) {
24417
+ const bytes = base32Decode(encoded);
24418
+ if (bytes.length === 0 || bytes.length > 4) throw new Error("vault: bad key version encoding");
24419
+ let version2 = 0;
24420
+ for (const byte of bytes) version2 = version2 * 256 + byte;
24421
+ if (version2 < 1) throw new Error("vault: bad key version");
24422
+ return version2;
24423
+ }
24424
+ function deriveSubkeys(master) {
24425
+ const derive = (info) => Buffer.from(hkdfSync("sha256", master, HKDF_SALT, info, SUBKEY_BYTES));
24426
+ return { enc: derive(HKDF_INFO_ENC), sign: derive(HKDF_INFO_SIGN) };
24427
+ }
24428
+ function bindingInput(keyVersion, pointerId, category, formatVersion = POINTER_FORMAT_VERSION) {
24429
+ if (pointerId.length !== POINTER_ID_BYTES) {
24430
+ throw new Error("vault: pointer id must be 16 bytes");
24431
+ }
24432
+ const head = Buffer.alloc(6);
24433
+ head.writeUInt16BE(formatVersion, 0);
24434
+ head.writeUInt32BE(keyVersion, 2);
24435
+ return Buffer.concat([head, Buffer.from(pointerId), Buffer.from(category, "utf8")]);
24436
+ }
24437
+ function seal(encKey, plaintext, aad, nonce) {
24438
+ const cipher = createCipheriv("aes-256-gcm", encKey, nonce);
24439
+ cipher.setAAD(aad);
24440
+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
24441
+ return { ciphertext, nonce, authTag: cipher.getAuthTag() };
24442
+ }
24443
+ function open(encKey, sealed, aad) {
23804
24444
  try {
23805
- const host = new URL(url2).host;
23806
- if (host !== "") return host;
24445
+ const decipher = createDecipheriv("aes-256-gcm", encKey, sealed.nonce);
24446
+ decipher.setAAD(aad);
24447
+ decipher.setAuthTag(sealed.authTag);
24448
+ return Buffer.concat([decipher.update(sealed.ciphertext), decipher.final()]).toString("utf8");
24449
+ } catch {
24450
+ return null;
24451
+ }
24452
+ }
24453
+ function signPointer(signKey, keyVersion, pointerId, category) {
24454
+ return createHmac2("sha256", signKey).update(bindingInput(keyVersion, pointerId, category, POINTER_FORMAT_VERSION)).digest().subarray(0, TAG_BYTES);
24455
+ }
24456
+ function verifyPointerTag(signKey, keyVersion, pointerId, category, tag) {
24457
+ if (tag.length !== TAG_BYTES) return false;
24458
+ const expected = signPointer(signKey, keyVersion, pointerId, category);
24459
+ return timingSafeEqual(expected, Buffer.from(tag));
24460
+ }
24461
+ function formatPointer(category, keyVersion, pointerId, tag) {
24462
+ return `[[aka:${category}:${encodeKeyVersion(keyVersion)}.${base32Encode(pointerId)}.${base32Encode(tag)}]]`;
24463
+ }
24464
+
24465
+ // ../../packages/persistence/src/vault/key-provider.ts
24466
+ import { execFileSync } from "child_process";
24467
+ import { randomBytes as randomBytes2 } from "crypto";
24468
+ import {
24469
+ chmodSync as chmodSync2,
24470
+ mkdirSync as mkdirSync2,
24471
+ readFileSync as readFileSync3,
24472
+ renameSync as renameSync4,
24473
+ rmSync as rmSync3,
24474
+ statSync,
24475
+ writeFileSync as writeFileSync2
24476
+ } from "fs";
24477
+ import { join as join5 } from "path";
24478
+ var VaultKeyEpochMissingError = class extends Error {
24479
+ version;
24480
+ constructor(version2) {
24481
+ super(`vault: key epoch ${String(version2)} is not present in the keyring`);
24482
+ this.name = "VaultKeyEpochMissingError";
24483
+ this.version = version2;
24484
+ }
24485
+ };
24486
+ var VAULT_KEY_FILENAME = "vault.key";
24487
+ var KEY_MATERIAL_BYTES2 = 32;
24488
+ var KEYCHAIN_SERVICE = "aka-vault";
24489
+ var KEYCHAIN_ACCOUNT = "keyring";
24490
+ function parseKeyring(raw) {
24491
+ const parsed = JSON.parse(raw);
24492
+ if (typeof parsed !== "object" || parsed === null) {
24493
+ throw new Error("vault key file is corrupt: not a JSON object");
24494
+ }
24495
+ const { current, keys } = parsed;
24496
+ if (typeof current !== "number" || !Number.isInteger(current) || current < 1) {
24497
+ throw new Error("vault key file is corrupt: bad current version");
24498
+ }
24499
+ if (typeof keys !== "object" || keys === null || Array.isArray(keys)) {
24500
+ throw new Error("vault key file is corrupt: bad keys map");
24501
+ }
24502
+ const map2 = /* @__PURE__ */ new Map();
24503
+ for (const [rawVersion, rawMaterial] of Object.entries(keys)) {
24504
+ const version2 = Number(rawVersion);
24505
+ if (!Number.isInteger(version2) || version2 < 1) {
24506
+ throw new Error("vault key file is corrupt: bad key version");
24507
+ }
24508
+ if (typeof rawMaterial !== "string") {
24509
+ throw new Error("vault key file is corrupt: bad key material");
24510
+ }
24511
+ const bytes = Buffer.from(rawMaterial, "base64");
24512
+ if (bytes.length !== KEY_MATERIAL_BYTES2) {
24513
+ throw new Error("vault key file is corrupt: bad key material length");
24514
+ }
24515
+ map2.set(version2, bytes);
24516
+ }
24517
+ if (!map2.has(current)) {
24518
+ throw new Error("vault key file is corrupt: current version has no material");
24519
+ }
24520
+ return { current, keys: map2 };
24521
+ }
24522
+ function serializeKeyring(keyring) {
24523
+ const keys = {};
24524
+ for (const version2 of [...keyring.keys.keys()].sort((a, b) => a - b)) {
24525
+ const material = keyring.keys.get(version2);
24526
+ if (material) keys[String(version2)] = material.toString("base64");
24527
+ }
24528
+ return JSON.stringify({ current: keyring.current, keys });
24529
+ }
24530
+ function mintKeyring() {
24531
+ return { current: 1, keys: /* @__PURE__ */ new Map([[1, randomBytes2(KEY_MATERIAL_BYTES2)]]) };
24532
+ }
24533
+ function withNextEpoch(keyring) {
24534
+ const next = Math.max(...keyring.keys.keys()) + 1;
24535
+ const keys = new Map(keyring.keys);
24536
+ keys.set(next, randomBytes2(KEY_MATERIAL_BYTES2));
24537
+ return { current: next, keys };
24538
+ }
24539
+ function currentOf(keyring) {
24540
+ const material = keyring.keys.get(keyring.current);
24541
+ if (!material) throw new VaultKeyEpochMissingError(keyring.current);
24542
+ return { material, version: keyring.current };
24543
+ }
24544
+ function epochOf(keyring, version2) {
24545
+ const material = keyring.keys.get(version2);
24546
+ if (!material) throw new VaultKeyEpochMissingError(version2);
24547
+ return { material, version: version2 };
24548
+ }
24549
+ function asAsync(work) {
24550
+ try {
24551
+ return Promise.resolve(work());
24552
+ } catch (err) {
24553
+ return Promise.reject(err instanceof Error ? err : new Error(String(err)));
24554
+ }
24555
+ }
24556
+ function asError(err) {
24557
+ return err instanceof Error ? err : new Error(String(err));
24558
+ }
24559
+ var ROTATION_LOCK_STALE_MS = 6e4;
24560
+ var LOCK_OWNER_FILE = "owner";
24561
+ var ROTATION_IN_PROGRESS = "vault: a key rotation is already in progress";
24562
+ function claimRotationLock(lock, owner) {
24563
+ try {
24564
+ mkdirSync2(lock);
24565
+ } catch (err) {
24566
+ if (err.code === "EEXIST") return false;
24567
+ throw asError(err);
24568
+ }
24569
+ try {
24570
+ writeFileSync2(join5(lock, LOCK_OWNER_FILE), `${owner}
24571
+ `, { mode: DATA_FILE_MODE });
24572
+ return true;
24573
+ } catch (err) {
24574
+ rmSync3(lock, { recursive: true, force: true });
24575
+ throw asError(err);
24576
+ }
24577
+ }
24578
+ function acquireRotationLock(keysDir2) {
24579
+ const lock = join5(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
24580
+ const owner = randomBytes2(16).toString("hex");
24581
+ if (claimRotationLock(lock, owner)) return { lock, owner };
24582
+ let held;
24583
+ try {
24584
+ held = statSync(lock);
24585
+ } catch {
24586
+ throw new Error(ROTATION_IN_PROGRESS);
24587
+ }
24588
+ if (Date.now() - held.mtimeMs < ROTATION_LOCK_STALE_MS) throw new Error(ROTATION_IN_PROGRESS);
24589
+ const aside = `${lock}.stale.${owner}`;
24590
+ try {
24591
+ const now = statSync(lock);
24592
+ if (now.ino !== held.ino || now.mtimeMs !== held.mtimeMs) {
24593
+ throw new Error(ROTATION_IN_PROGRESS);
24594
+ }
24595
+ renameSync4(lock, aside);
24596
+ } catch (err) {
24597
+ if (err instanceof Error && err.message === ROTATION_IN_PROGRESS) throw err;
24598
+ throw new Error(ROTATION_IN_PROGRESS, { cause: err });
24599
+ }
24600
+ rmSync3(aside, { recursive: true, force: true });
24601
+ if (!claimRotationLock(lock, owner)) throw new Error(ROTATION_IN_PROGRESS);
24602
+ return { lock, owner };
24603
+ }
24604
+ function releaseRotationLock(lease) {
24605
+ try {
24606
+ if (readFileSync3(join5(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
24607
+ } catch {
24608
+ return;
24609
+ }
24610
+ rmSync3(lease.lock, { recursive: true, force: true });
24611
+ }
24612
+ function withRotationLock(keysDir2, work) {
24613
+ ensureDataDirSync(keysDir2);
24614
+ const lease = acquireRotationLock(keysDir2);
24615
+ try {
24616
+ return work();
24617
+ } finally {
24618
+ releaseRotationLock(lease);
24619
+ }
24620
+ }
24621
+ var FileKeyProvider = class {
24622
+ #keysDir;
24623
+ constructor(keysDir2) {
24624
+ this.#keysDir = keysDir2;
24625
+ }
24626
+ get filePath() {
24627
+ return join5(this.#keysDir, VAULT_KEY_FILENAME);
24628
+ }
24629
+ loadOrCreate() {
24630
+ return asAsync(() => {
24631
+ const existing = this.#read();
24632
+ if (!existing) return currentOf(this.#createExclusive());
24633
+ tightenFileMode(this.filePath);
24634
+ return currentOf(existing);
24635
+ });
24636
+ }
24637
+ rotate() {
24638
+ return asAsync(
24639
+ () => withRotationLock(this.#keysDir, () => {
24640
+ const existing = this.#read();
24641
+ if (!existing) return currentOf(this.#createExclusive());
24642
+ return currentOf(this.#write(withNextEpoch(existing)));
24643
+ })
24644
+ );
24645
+ }
24646
+ materialFor(version2) {
24647
+ return asAsync(() => {
24648
+ const existing = this.#read();
24649
+ if (!existing) throw new VaultKeyEpochMissingError(version2);
24650
+ return epochOf(existing, version2);
24651
+ });
24652
+ }
24653
+ /** The keyring, or null when the file is ABSENT. A corrupt file throws. */
24654
+ #read() {
24655
+ let raw;
24656
+ try {
24657
+ raw = readFileSync3(this.filePath, "utf8");
24658
+ } catch (err) {
24659
+ if (err.code === "ENOENT") return null;
24660
+ throw err instanceof Error ? err : new Error(String(err));
24661
+ }
24662
+ return parseKeyring(raw);
24663
+ }
24664
+ /**
24665
+ * First mint: the keyring is created at its FINAL path with a
24666
+ * creation-exclusive write, so two processes racing a fresh machine cannot
24667
+ * each mint a different epoch 1 — with tmp + rename the loser's replace
24668
+ * would orphan everything the winner had already sealed. On EEXIST the
24669
+ * loser re-reads and adopts the winner's keyring; it minted nothing.
24670
+ * Atomic replace is unnecessary here: nothing can be mid-read of a file
24671
+ * that did not exist, and a torn exclusive write parses as corrupt on the
24672
+ * next read and fails secure rather than being re-minted over.
24673
+ */
24674
+ #createExclusive() {
24675
+ ensureDataDirSync(this.#keysDir);
24676
+ const keyring = mintKeyring();
24677
+ try {
24678
+ writeFileSync2(this.filePath, `${serializeKeyring(keyring)}
24679
+ `, {
24680
+ flag: "wx",
24681
+ mode: DATA_FILE_MODE
24682
+ });
24683
+ } catch (err) {
24684
+ if (err.code !== "EEXIST") throw asError(err);
24685
+ const winner = this.#read();
24686
+ if (!winner) {
24687
+ throw new Error("vault: key file vanished during first mint", { cause: err });
24688
+ }
24689
+ return winner;
24690
+ }
24691
+ tightenFileMode(this.filePath);
24692
+ return keyring;
24693
+ }
24694
+ /**
24695
+ * Atomic tmp + rename so a crash mid-write cannot truncate the keyring.
24696
+ * Used only for rotation, under the rotation lock — first creation goes
24697
+ * through the creation-exclusive path instead.
24698
+ */
24699
+ #write(keyring) {
24700
+ ensureDataDirSync(this.#keysDir);
24701
+ const file2 = this.filePath;
24702
+ const tmp = `${file2}.tmp`;
24703
+ writeFileSync2(tmp, `${serializeKeyring(keyring)}
24704
+ `, { mode: DATA_FILE_MODE });
24705
+ renameSync4(tmp, file2);
24706
+ tightenFileMode(file2);
24707
+ return keyring;
24708
+ }
24709
+ };
24710
+ function tightenFileMode(file2) {
24711
+ try {
24712
+ chmodSync2(file2, DATA_FILE_MODE);
24713
+ } catch {
24714
+ }
24715
+ }
24716
+ var runSecurity = (args) => execFileSync("/usr/bin/security", args, {
24717
+ encoding: "utf8",
24718
+ stdio: ["ignore", "pipe", "ignore"]
24719
+ });
24720
+ var SECURITY_ITEM_NOT_FOUND = 44;
24721
+ var KeychainKeyProvider = class {
24722
+ #keysDir;
24723
+ #exec;
24724
+ constructor(keysDir2, exec = runSecurity) {
24725
+ if (exec === runSecurity && process.platform !== "darwin") {
24726
+ throw new Error(
24727
+ `keychain custody is not available on this platform (${process.platform}); use file custody`
24728
+ );
24729
+ }
24730
+ this.#keysDir = keysDir2;
24731
+ this.#exec = exec;
24732
+ }
24733
+ /** Where a fallback file provider for the same vault would keep its keyring. */
24734
+ get keysDir() {
24735
+ return this.#keysDir;
24736
+ }
24737
+ loadOrCreate() {
24738
+ return asAsync(() => {
24739
+ const existing = this.#read();
24740
+ if (existing) return currentOf(existing);
24741
+ return currentOf(this.#create(mintKeyring()));
24742
+ });
24743
+ }
24744
+ rotate() {
24745
+ return asAsync(
24746
+ () => withRotationLock(this.#keysDir, () => {
24747
+ const existing = this.#read();
24748
+ if (!existing) return currentOf(this.#create(mintKeyring()));
24749
+ return currentOf(this.#replace(withNextEpoch(existing)));
24750
+ })
24751
+ );
24752
+ }
24753
+ materialFor(version2) {
24754
+ return asAsync(() => {
24755
+ const existing = this.#read();
24756
+ if (!existing) throw new VaultKeyEpochMissingError(version2);
24757
+ return epochOf(existing, version2);
24758
+ });
24759
+ }
24760
+ /** The keyring, or null when no item exists yet. A corrupt item throws. */
24761
+ #read() {
24762
+ let raw;
24763
+ try {
24764
+ raw = this.#exec([
24765
+ "find-generic-password",
24766
+ "-s",
24767
+ KEYCHAIN_SERVICE,
24768
+ "-a",
24769
+ KEYCHAIN_ACCOUNT,
24770
+ "-w"
24771
+ ]);
24772
+ } catch (err) {
24773
+ if (err.status === SECURITY_ITEM_NOT_FOUND) return null;
24774
+ throw new Error(
24775
+ `vault: keychain read failed (${err instanceof Error ? err.message : String(err)}); refusing to treat the failure as an absent keyring`,
24776
+ { cause: err }
24777
+ );
24778
+ }
24779
+ const body = raw.trim();
24780
+ if (body.length === 0) return null;
24781
+ return parseKeyring(body);
24782
+ }
24783
+ /**
24784
+ * First mint: a plain `add-generic-password` (no `-U`) fails when an item
24785
+ * already exists, so a concurrent first mint cannot overwrite the winner's
24786
+ * keyring — the loser re-reads and adopts it instead.
24787
+ */
24788
+ #create(keyring) {
24789
+ const args = [
24790
+ "add-generic-password",
24791
+ "-s",
24792
+ KEYCHAIN_SERVICE,
24793
+ "-a",
24794
+ KEYCHAIN_ACCOUNT,
24795
+ "-w",
24796
+ serializeKeyring(keyring)
24797
+ ];
24798
+ try {
24799
+ this.#exec(args);
24800
+ } catch (err) {
24801
+ const winner = this.#read();
24802
+ if (winner) return winner;
24803
+ throw asError(err);
24804
+ }
24805
+ return keyring;
24806
+ }
24807
+ // `-U` updates the item in place, deliberately replacing the stored map with
24808
+ // one that contains it — used only for rotation, under the rotation lock.
24809
+ #replace(keyring) {
24810
+ this.#exec([
24811
+ "add-generic-password",
24812
+ "-U",
24813
+ "-s",
24814
+ KEYCHAIN_SERVICE,
24815
+ "-a",
24816
+ KEYCHAIN_ACCOUNT,
24817
+ "-w",
24818
+ serializeKeyring(keyring)
24819
+ ]);
24820
+ return keyring;
24821
+ }
24822
+ };
24823
+ function createKeyProvider(custody, keysDir2) {
24824
+ if (custody === "keychain") return new KeychainKeyProvider(keysDir2);
24825
+ return new FileKeyProvider(keysDir2);
24826
+ }
24827
+
24828
+ // ../../packages/persistence/src/vault/vault.ts
24829
+ import { randomBytes as randomBytes3, randomUUID as randomUUID10 } from "crypto";
24830
+ var CONSENT_ABSENT = /* @__PURE__ */ Symbol("aka.vault.consentAbsent");
24831
+ var UNAVAILABLE = /* @__PURE__ */ Symbol("aka.vault.unavailable");
24832
+ var VAULT_PURGE_POINTER_ID = "*";
24833
+ function parsePointer(token) {
24834
+ if (!POINTER_TOKEN_ANCHORED.test(token)) return null;
24835
+ const body = token.slice("[[aka:".length, -"]]".length);
24836
+ const colon = body.indexOf(":");
24837
+ if (colon < 0) return null;
24838
+ const category = body.slice(0, colon);
24839
+ const [kv, id, tag] = body.slice(colon + 1).split(".");
24840
+ if (kv === void 0 || id === void 0 || tag === void 0) return null;
24841
+ try {
24842
+ const keyVersion = decodeKeyVersion(kv);
24843
+ const pointerId = base32Decode(id);
24844
+ const tagBytes = base32Decode(tag);
24845
+ if (encodeKeyVersion(keyVersion) !== kv || base32Encode(pointerId) !== id || base32Encode(tagBytes) !== tag) {
24846
+ return null;
24847
+ }
24848
+ return { category, keyVersion, pointerId, tag: tagBytes };
24849
+ } catch {
24850
+ return null;
24851
+ }
24852
+ }
24853
+ var SecretVault = class {
24854
+ #repo;
24855
+ #keys;
24856
+ #fingerprintKey;
24857
+ #isConsented;
24858
+ #verifyGrant;
24859
+ #now;
24860
+ constructor(deps) {
24861
+ this.#repo = deps.repo;
24862
+ this.#keys = deps.keys;
24863
+ this.#fingerprintKey = deps.fingerprintKey;
24864
+ this.#isConsented = deps.isConsented;
24865
+ this.#verifyGrant = deps.verifyGrant;
24866
+ this.#now = deps.now ?? (() => Date.now());
24867
+ }
24868
+ /**
24869
+ * Store a value and return the pointer that stands for it. The same value
24870
+ * always yields the same pointer on this machine — one row, one pointer id,
24871
+ * one category — which is what makes dedup and reuse counting work.
24872
+ */
24873
+ async tokenize(raw, meta3) {
24874
+ if (!this.#isConsented()) return CONSENT_ABSENT;
24875
+ const valueFingerprint = fingerprintValue(this.#fingerprintKey, raw);
24876
+ const existing = this.#repo.byValueFingerprint(valueFingerprint);
24877
+ const now = this.#now();
24878
+ if (existing) {
24879
+ this.#repo.upsert({ ...existing, provider: existing.provider ?? void 0 }, now);
24880
+ return await this.#emitToken(existing.keyVersion, existing.pointerId, existing.category);
24881
+ }
24882
+ const { material, version: version2 } = await this.#keys.loadOrCreate();
24883
+ const subkeys = deriveSubkeys(material);
24884
+ const pointerId = randomBytes3(POINTER_ID_BYTES);
24885
+ const aad = bindingInput(version2, pointerId, meta3.category, POINTER_FORMAT_VERSION);
24886
+ const sealed = seal(subkeys.enc, raw, aad, randomBytes3(NONCE_BYTES));
24887
+ const { row } = this.#repo.upsert(
24888
+ {
24889
+ pointerId: base32Encode(pointerId),
24890
+ valueFingerprint,
24891
+ fingerprintKeyVersion: this.#fingerprintKey.version,
24892
+ keyVersion: version2,
24893
+ // Recorded so the row stays OPENABLE if the wire-format constant ever
24894
+ // moves: it is part of this row's AEAD AAD. It is not a tag input —
24895
+ // tags are pinned to the constant on both sides.
24896
+ formatVersion: POINTER_FORMAT_VERSION,
24897
+ category: meta3.category,
24898
+ ruleId: meta3.ruleId,
24899
+ maskedMatch: meta3.maskedMatch,
24900
+ provider: meta3.provider,
24901
+ ciphertext: sealed.ciphertext.toString("base64"),
24902
+ nonce: sealed.nonce.toString("base64"),
24903
+ authTag: sealed.authTag.toString("base64")
24904
+ },
24905
+ now
24906
+ );
24907
+ return await this.#emitToken(row.keyVersion, row.pointerId, row.category);
24908
+ }
24909
+ /**
24910
+ * Resolve a pointer back to its value, for a human or (with a grant) for the
24911
+ * model. Every call that gets as far as an identified row writes an audit row.
24912
+ */
24913
+ async detokenize(token, opts) {
24914
+ const parsed = parsePointer(token);
24915
+ if (!parsed) return UNAVAILABLE;
24916
+ let signKey;
24917
+ try {
24918
+ const epoch = await this.#keys.materialFor(parsed.keyVersion);
24919
+ signKey = deriveSubkeys(epoch.material).sign;
24920
+ } catch {
24921
+ return UNAVAILABLE;
24922
+ }
24923
+ if (!verifyPointerTag(signKey, parsed.keyVersion, parsed.pointerId, parsed.category, parsed.tag)) {
24924
+ return UNAVAILABLE;
24925
+ }
24926
+ const pointerId = base32Encode(parsed.pointerId);
24927
+ const row = this.#repo.byPointerId(pointerId);
24928
+ if (!row) {
24929
+ this.#audit(pointerId, opts, "unavailable");
24930
+ return UNAVAILABLE;
24931
+ }
24932
+ if (row.category !== parsed.category) return UNAVAILABLE;
24933
+ if (opts.target === "model") {
24934
+ const grantId = opts.grantId;
24935
+ const verify = this.#verifyGrant;
24936
+ if (verify === void 0 || grantId === void 0 || grantId === "") {
24937
+ this.#audit(pointerId, opts, "refused");
24938
+ return UNAVAILABLE;
24939
+ }
24940
+ let covered;
24941
+ try {
24942
+ covered = await verify(grantId, {
24943
+ ruleId: row.ruleId,
24944
+ valueFingerprint: row.valueFingerprint,
24945
+ fingerprintKeyVersion: row.fingerprintKeyVersion
24946
+ });
24947
+ } catch {
24948
+ covered = false;
24949
+ }
24950
+ if (!covered) {
24951
+ this.#audit(pointerId, opts, "refused");
24952
+ return UNAVAILABLE;
24953
+ }
24954
+ }
24955
+ let raw;
24956
+ try {
24957
+ const epoch = await this.#keys.materialFor(row.keyVersion);
24958
+ raw = open(
24959
+ deriveSubkeys(epoch.material).enc,
24960
+ {
24961
+ ciphertext: Buffer.from(row.ciphertext, "base64"),
24962
+ nonce: Buffer.from(row.nonce, "base64"),
24963
+ authTag: Buffer.from(row.authTag, "base64")
24964
+ },
24965
+ // Sealed under the ROW's epoch and format version. Rotation may have
24966
+ // moved the epoch past the one this token names, and a format bump may
24967
+ // have moved the constant past the generation this row was sealed
24968
+ // under — the AAD follows the row in both cases, never the token.
24969
+ bindingInput(row.keyVersion, parsed.pointerId, row.category, row.formatVersion)
24970
+ );
24971
+ } catch {
24972
+ raw = null;
24973
+ }
24974
+ if (raw === null) {
24975
+ this.#audit(pointerId, opts, "unavailable");
24976
+ return UNAVAILABLE;
24977
+ }
24978
+ this.#audit(pointerId, opts, "revealed");
24979
+ return raw;
24980
+ }
24981
+ /**
24982
+ * Owner-surface reveal by row id: the dashboard shows a row the owner can
24983
+ * already see and asks for its value. There is no wire token here to verify —
24984
+ * the tag exists to stop FORGED tokens arriving in untrusted text, and a row
24985
+ * id selected server-side from the owner's own store is not that — so this
24986
+ * loads the row directly, opens its ciphertext under the row's epoch, and
24987
+ * audits exactly like a human-target de-reference. Never callable with
24988
+ * target 'model': the wire-token path with its grant gate is the only road
24989
+ * raw travels toward the model.
24990
+ */
24991
+ async revealEntry(pointerId, opts) {
24992
+ const row = this.#repo.byPointerId(pointerId);
24993
+ if (!row) {
24994
+ this.#audit(pointerId, { target: "human", reason: opts.reason }, "unavailable");
24995
+ return UNAVAILABLE;
24996
+ }
24997
+ const raw = await this.#openRow(row);
24998
+ if (raw === null) {
24999
+ this.#audit(pointerId, { target: "human", reason: opts.reason }, "unavailable");
25000
+ return UNAVAILABLE;
25001
+ }
25002
+ this.#audit(pointerId, { target: "human", reason: opts.reason }, "revealed");
25003
+ return raw;
25004
+ }
25005
+ /** Badge and listing data. No raw value, no fingerprint, and no audit row. */
25006
+ async describePointer(token) {
25007
+ const row = await this.#rowFor(token);
25008
+ if (!row) return null;
25009
+ return {
25010
+ category: row.category,
25011
+ ...row.provider === void 0 ? {} : { provider: row.provider },
25012
+ maskedMatch: row.maskedMatch,
25013
+ occurrences: row.occurrenceCount,
25014
+ firstSeen: new Date(row.firstSeen).toISOString(),
25015
+ lastSeen: new Date(row.lastSeen).toISOString()
25016
+ };
25017
+ }
25018
+ /**
25019
+ * The raw-free row identity a reveal grant matches on. Deliberately not fed to
25020
+ * view surfaces: the keyed fingerprint is a correlation key and must not reach
25021
+ * a presentation layer.
25022
+ */
25023
+ async resolvePointerIdentity(token) {
25024
+ const row = await this.#rowFor(token);
25025
+ if (!row) return null;
25026
+ return {
25027
+ ruleId: row.ruleId,
25028
+ valueFingerprint: row.valueFingerprint,
25029
+ fingerprintKeyVersion: row.fingerprintKeyVersion
25030
+ };
25031
+ }
25032
+ /**
25033
+ * Mint the next vault key epoch and re-encrypt every entry under it. Pointers
25034
+ * already emitted keep verifying: their tag is checked against the historical
25035
+ * epoch they name, which the key provider retains.
25036
+ *
25037
+ * Safe to interrupt — each row carries the epoch its ciphertext is sealed
25038
+ * under, so a half-finished pass leaves every row openable.
25039
+ *
25040
+ * The rotation lock covers only the keyring mint inside `rotate()`; the
25041
+ * re-seal pass below runs unlocked. Two concurrent rotations therefore
25042
+ * serialize on the keyring but interleave over the rows, so a slower pass can
25043
+ * re-seal a row back to an epoch a faster one already moved past, and
25044
+ * `reEncrypted` can double-count. No value is lost either way — every epoch is
25045
+ * retained and every row stays openable — but "after rotation every row sits
25046
+ * at the newest epoch" does not hold under concurrency. Holding the lock
25047
+ * across the whole pass requires an async-aware lock, since a callback that
25048
+ * awaits would release the lock at its first suspension.
25049
+ */
25050
+ async rotateVaultKey() {
25051
+ const next = await this.#keys.rotate();
25052
+ const nextEnc = deriveSubkeys(next.material).enc;
25053
+ let reEncrypted = 0;
25054
+ for (const row of this.#repo.listAll()) {
25055
+ if (row.keyVersion === next.version) continue;
25056
+ const pointerId = base32Decode(row.pointerId);
25057
+ let raw;
25058
+ try {
25059
+ const epoch = await this.#keys.materialFor(row.keyVersion);
25060
+ raw = open(
25061
+ deriveSubkeys(epoch.material).enc,
25062
+ {
25063
+ ciphertext: Buffer.from(row.ciphertext, "base64"),
25064
+ nonce: Buffer.from(row.nonce, "base64"),
25065
+ authTag: Buffer.from(row.authTag, "base64")
25066
+ },
25067
+ bindingInput(row.keyVersion, pointerId, row.category, row.formatVersion)
25068
+ );
25069
+ } catch {
25070
+ raw = null;
25071
+ }
25072
+ if (raw === null) continue;
25073
+ const sealed = seal(
25074
+ nextEnc,
25075
+ raw,
25076
+ bindingInput(next.version, pointerId, row.category, row.formatVersion),
25077
+ randomBytes3(NONCE_BYTES)
25078
+ );
25079
+ this.#repo.replaceCiphertext(row.pointerId, {
25080
+ keyVersion: next.version,
25081
+ ciphertext: sealed.ciphertext.toString("base64"),
25082
+ nonce: sealed.nonce.toString("base64"),
25083
+ authTag: sealed.authTag.toString("base64")
25084
+ });
25085
+ reEncrypted += 1;
25086
+ }
25087
+ return { version: next.version, reEncrypted };
25088
+ }
25089
+ /**
25090
+ * Re-key every entry's value fingerprint after the exception key rotates,
25091
+ * PRESERVING each pointer id. Unlike grants — where rotation is invalidation,
25092
+ * because the raw values are gone — the vault still holds the values, so
25093
+ * determinism, dedup, and every outstanding pointer survive the rotation.
25094
+ *
25095
+ * Every fingerprint-key rotation must run this: a row left at the old epoch
25096
+ * still resolves, but the same value detected again fingerprints under the
25097
+ * NEW key, misses the dedup lookup, and mints a second row and a second
25098
+ * pointer — one value, two tokens in circulation.
25099
+ *
25100
+ * Per-row best-effort: a row that cannot open, or whose refreshed
25101
+ * fingerprint collides with a row already refreshed, is skipped rather than
25102
+ * aborting the pass — one damaged entry must not strand the re-key of every
25103
+ * other. A skipped row keeps resolving under its old fingerprint epoch.
25104
+ */
25105
+ async refreshFingerprints(next) {
25106
+ let refreshed = 0;
25107
+ for (const row of this.#repo.listAll()) {
25108
+ try {
25109
+ const raw = await this.#openRow(row);
25110
+ if (raw === null) continue;
25111
+ this.#repo.refreshFingerprint(row.pointerId, {
25112
+ valueFingerprint: fingerprintValue(next, raw),
25113
+ fingerprintKeyVersion: next.version
25114
+ });
25115
+ refreshed += 1;
25116
+ } catch {
25117
+ continue;
25118
+ }
25119
+ }
25120
+ return refreshed;
25121
+ }
25122
+ /**
25123
+ * Destroy every entry, making all outstanding pointers permanently
25124
+ * unresolvable.
25125
+ *
25126
+ * The count comes from `purgeAll` rather than a separate `countEntries` —
25127
+ * `purgeAll` counts inside the same transaction that deletes, so the audit row
25128
+ * reports what was actually destroyed. Counting beforehand would let a
25129
+ * concurrent write land between the two statements and put a number in the
25130
+ * durable record that never matched reality.
25131
+ */
25132
+ purgeVault() {
25133
+ const destroyed = this.#repo.purgeAll();
25134
+ this.#repo.recordDeref({
25135
+ id: randomUUID10(),
25136
+ pointerId: VAULT_PURGE_POINTER_ID,
25137
+ at: this.#now(),
25138
+ target: "human",
25139
+ reason: "purge",
25140
+ outcome: "unavailable",
25141
+ pointerCount: Math.max(destroyed, 1)
25142
+ });
25143
+ return destroyed;
25144
+ }
25145
+ // Sign under the epoch the token names — which for a re-detected value is the
25146
+ // epoch its row currently sits at rather than whatever is current.
25147
+ //
25148
+ // The row's format version is NOT a tag input. It binds the row's ciphertext
25149
+ // (it is part of the AEAD AAD, so an old row stays openable) but never the
25150
+ // wire tag, which verification checks against POINTER_FORMAT_VERSION without
25151
+ // knowing any row. Signing a token here under a row's own generation is what
25152
+ // would make the vault emit tokens it then refuses.
25153
+ async #emitToken(keyVersion, pointerIdB32, category) {
25154
+ const pointerId = base32Decode(pointerIdB32);
25155
+ const epoch = await this.#keys.materialFor(keyVersion);
25156
+ const signKey = deriveSubkeys(epoch.material).sign;
25157
+ return formatPointer(
25158
+ category,
25159
+ keyVersion,
25160
+ pointerId,
25161
+ signPointer(signKey, keyVersion, pointerId, category)
25162
+ );
25163
+ }
25164
+ async #openRow(row) {
25165
+ try {
25166
+ const epoch = await this.#keys.materialFor(row.keyVersion);
25167
+ return open(
25168
+ deriveSubkeys(epoch.material).enc,
25169
+ {
25170
+ ciphertext: Buffer.from(row.ciphertext, "base64"),
25171
+ nonce: Buffer.from(row.nonce, "base64"),
25172
+ authTag: Buffer.from(row.authTag, "base64")
25173
+ },
25174
+ bindingInput(row.keyVersion, base32Decode(row.pointerId), row.category, row.formatVersion)
25175
+ );
25176
+ } catch {
25177
+ return null;
25178
+ }
25179
+ }
25180
+ // Shared lookup for the read-only surfaces. It verifies the tag exactly as
25181
+ // detokenize does: a descriptor is not raw, but a token nobody can vouch for
25182
+ // should not resolve to anything at all — otherwise a fabricated pointer, or a
25183
+ // lookalike planted in a file, would still yield a category and a masked
25184
+ // preview. Verifying needs the historical epoch's key, which is why these
25185
+ // surfaces are async.
25186
+ async #rowFor(token) {
25187
+ const parsed = parsePointer(token);
25188
+ if (!parsed) return null;
25189
+ try {
25190
+ const epoch = await this.#keys.materialFor(parsed.keyVersion);
25191
+ const signKey = deriveSubkeys(epoch.material).sign;
25192
+ if (!verifyPointerTag(signKey, parsed.keyVersion, parsed.pointerId, parsed.category, parsed.tag)) {
25193
+ return null;
25194
+ }
25195
+ } catch {
25196
+ return null;
25197
+ }
25198
+ const row = this.#repo.byPointerId(base32Encode(parsed.pointerId));
25199
+ if (row?.category !== parsed.category) return null;
25200
+ return row;
25201
+ }
25202
+ #audit(pointerId, opts, outcome) {
25203
+ this.#repo.recordDeref({
25204
+ id: randomUUID10(),
25205
+ pointerId,
25206
+ at: this.#now(),
25207
+ target: opts.target,
25208
+ reason: opts.reason,
25209
+ outcome,
25210
+ ...opts.grantId === void 0 ? {} : { grantId: opts.grantId },
25211
+ // Only the batched reasons carry a count above one; a model crossing is
25212
+ // always its own row.
25213
+ pointerCount: isBatchedDerefReason(opts.reason) ? opts.pointerCount ?? 1 : 1
25214
+ });
25215
+ }
25216
+ };
25217
+
25218
+ // ../../packages/persistence/src/warn-era-cap.ts
25219
+ import { existsSync as existsSync3, writeFileSync as writeFileSync3 } from "fs";
25220
+ import { join as join6 } from "path";
25221
+ var MARKER = "warn-era-capped";
25222
+ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
25223
+ if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
25224
+ const marker = join6(dataDir2, MARKER);
25225
+ if (existsSync3(marker)) return { capped: 0, skipped: "already-run" };
25226
+ const capped = db.policies.capCategoryActions();
25227
+ writeFileSync3(marker, `${new Date(Date.now()).toISOString()}
25228
+ `, { mode: DATA_FILE_MODE });
25229
+ return { capped };
25230
+ }
25231
+
25232
+ // ../../packages/plugin-sdk/src/provider-env.ts
25233
+ var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
25234
+ var booleanish = external_exports.string().optional().transform((v) => {
25235
+ if (v === void 0) return void 0;
25236
+ const t = v.trim().toLowerCase();
25237
+ if (t === "" || t === "false" || t === "0") return false;
25238
+ return true;
25239
+ }).catch(void 0);
25240
+ var optionalBaseUrl = external_exports.preprocess((v) => {
25241
+ if (typeof v === "string" && v.trim() === "") return void 0;
25242
+ return v;
25243
+ }, external_exports.string().optional()).catch(void 0);
25244
+ var providerEnvShape = {
25245
+ CLAUDE_CODE_USE_BEDROCK: booleanish,
25246
+ CLAUDE_CODE_USE_VERTEX: booleanish,
25247
+ ANTHROPIC_BASE_URL: optionalBaseUrl
25248
+ };
25249
+ var ProviderEnvSchema = external_exports.object(providerEnvShape);
25250
+
25251
+ // ../../packages/plugin-sdk/src/provider.ts
25252
+ function hostOf(url2) {
25253
+ try {
25254
+ const host = new URL(url2).host;
25255
+ if (host !== "") return host;
23807
25256
  } catch {
23808
25257
  }
23809
25258
  try {
@@ -23832,8 +25281,8 @@ function resolveProvider() {
23832
25281
  function loadConfig(base = defaultDataDir()) {
23833
25282
  try {
23834
25283
  ensureLayoutDirSync(base);
23835
- const settingsFile = join6(settingsDir(base), "settings.json");
23836
- if (existsSync3(settingsFile)) tightenFile(settingsFile);
25284
+ const settingsFile = join7(settingsDir(base), "settings.json");
25285
+ if (existsSync4(settingsFile)) tightenFile(settingsFile);
23837
25286
  } catch {
23838
25287
  }
23839
25288
  migrateLegacyLayout(base);
@@ -23856,9 +25305,9 @@ function resolveProviderSafe() {
23856
25305
  }
23857
25306
 
23858
25307
  // ../../packages/plugin-sdk/src/config-inventory.ts
23859
- import { readdirSync, readFileSync as readFileSync4, realpathSync, statSync as statSync2 } from "fs";
25308
+ import { readdirSync, readFileSync as readFileSync5, realpathSync, statSync as statSync3 } from "fs";
23860
25309
  import { homedir as homedir2 } from "os";
23861
- import { basename as basename2, join as join8 } from "path";
25310
+ import { basename as basename2, join as join9 } from "path";
23862
25311
 
23863
25312
  // ../../packages/detections/src/egress/registry.ts
23864
25313
  var EXTRACTOR_VERSION = "1";
@@ -24646,12 +26095,12 @@ function redact(text, findings) {
24646
26095
  const regions = [];
24647
26096
  for (const f of sorted) {
24648
26097
  const rank = SEVERITY_RANK2[f.severity];
24649
- const open = regions[regions.length - 1];
24650
- if (open && f.span.start < open.end) {
24651
- open.end = Math.max(open.end, f.span.end);
24652
- if (rank > open.rank) {
24653
- open.rank = rank;
24654
- open.category = f.category;
26098
+ const open2 = regions[regions.length - 1];
26099
+ if (open2 && f.span.start < open2.end) {
26100
+ open2.end = Math.max(open2.end, f.span.end);
26101
+ if (rank > open2.rank) {
26102
+ open2.rank = rank;
26103
+ open2.category = f.category;
24655
26104
  }
24656
26105
  } else {
24657
26106
  regions.push({ start: f.span.start, end: f.span.end, category: f.category, rank });
@@ -24680,6 +26129,24 @@ function maskMatch(raw) {
24680
26129
  return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
24681
26130
  }
24682
26131
 
26132
+ // ../../packages/detections/src/pointer-shield.ts
26133
+ function shieldPointers(text) {
26134
+ const spans = [];
26135
+ let out = null;
26136
+ for (const match of text.matchAll(pointerTokenScanner())) {
26137
+ spans.push({ start: match.index, end: match.index + match[0].length });
26138
+ out ??= text;
26139
+ out = out.slice(0, match.index) + " ".repeat(match[0].length) + out.slice(match.index + match[0].length);
26140
+ }
26141
+ return { text: out ?? text, spans };
26142
+ }
26143
+ function dropShieldedFindings(findings, spans) {
26144
+ if (spans.length === 0) return findings;
26145
+ return findings.filter(
26146
+ (finding) => !spans.some((s) => finding.span.start < s.end && finding.span.end > s.start)
26147
+ );
26148
+ }
26149
+
24683
26150
  // ../../packages/detections/src/posture/config-posture.ts
24684
26151
  var RULE_VERSION = "1";
24685
26152
  var KNOWN_TOOLS = /* @__PURE__ */ new Set([
@@ -26876,8 +28343,8 @@ function bundledDetections() {
26876
28343
  }
26877
28344
 
26878
28345
  // ../../packages/plugin-sdk/src/repo.ts
26879
- import { existsSync as existsSync4, readFileSync as readFileSync3, statSync } from "fs";
26880
- import { basename, dirname, isAbsolute, join as join7, sep as sep2 } from "path";
28346
+ import { existsSync as existsSync5, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
28347
+ import { basename, dirname, isAbsolute, join as join8, sep as sep2 } from "path";
26881
28348
  function resolveRepo(cwd) {
26882
28349
  try {
26883
28350
  const root = findGitRoot(cwd);
@@ -26892,36 +28359,36 @@ function resolveRepo(cwd) {
26892
28359
  function findGitRoot(start) {
26893
28360
  let dir = start;
26894
28361
  for (; ; ) {
26895
- if (existsSync4(join7(dir, ".git"))) return dir;
28362
+ if (existsSync5(join8(dir, ".git"))) return dir;
26896
28363
  const parent = dirname(dir);
26897
28364
  if (parent === dir) return void 0;
26898
28365
  dir = parent;
26899
28366
  }
26900
28367
  }
26901
28368
  function resolveGitContext(root) {
26902
- const dotGit = join7(root, ".git");
28369
+ const dotGit = join8(root, ".git");
26903
28370
  try {
26904
- if (statSync(dotGit).isDirectory()) {
26905
- return { configPath: join7(dotGit, "config"), headRoot: root };
28371
+ if (statSync2(dotGit).isDirectory()) {
28372
+ return { configPath: join8(dotGit, "config"), headRoot: root };
26906
28373
  }
26907
28374
  } catch {
26908
28375
  return void 0;
26909
28376
  }
26910
28377
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
26911
28378
  if (!target) return void 0;
26912
- const gitdir = isAbsolute(target) ? target : join7(root, target);
26913
- if (existsSync4(join7(gitdir, "config"))) {
26914
- return { configPath: join7(gitdir, "config"), headRoot: root };
28379
+ const gitdir = isAbsolute(target) ? target : join8(root, target);
28380
+ if (existsSync5(join8(gitdir, "config"))) {
28381
+ return { configPath: join8(gitdir, "config"), headRoot: root };
26915
28382
  }
26916
- const commonRaw = safeRead(join7(gitdir, "commondir"))?.trim();
28383
+ const commonRaw = safeRead(join8(gitdir, "commondir"))?.trim();
26917
28384
  if (!commonRaw) return void 0;
26918
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join7(gitdir, commonRaw);
28385
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join8(gitdir, commonRaw);
26919
28386
  const headRoot = basename(commonGitDir) === ".git" ? dirname(commonGitDir) : root;
26920
- return { configPath: join7(commonGitDir, "config"), headRoot };
28387
+ return { configPath: join8(commonGitDir, "config"), headRoot };
26921
28388
  }
26922
28389
  function safeRead(path) {
26923
28390
  try {
26924
- return readFileSync3(path, "utf8");
28391
+ return readFileSync4(path, "utf8");
26925
28392
  } catch {
26926
28393
  return void 0;
26927
28394
  }
@@ -26959,13 +28426,13 @@ function slugFromUrl(url2) {
26959
28426
  }
26960
28427
 
26961
28428
  // ../../packages/plugin-sdk/src/events.ts
26962
- import { createHash as createHash4, randomUUID as randomUUID9 } from "crypto";
28429
+ import { createHash as createHash4, randomUUID as randomUUID11 } from "crypto";
26963
28430
  function contentHashOf(text) {
26964
28431
  return createHash4("sha256").update(text).digest("hex");
26965
28432
  }
26966
28433
  function buildIngestEvent(input) {
26967
28434
  return {
26968
- id: randomUUID9(),
28435
+ id: randomUUID11(),
26969
28436
  sourceTool: input.sourceTool,
26970
28437
  kind: input.kind,
26971
28438
  occurredAt: input.occurredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
@@ -26976,7 +28443,7 @@ function buildIngestEvent(input) {
26976
28443
  // SDK boot in the fail-open hook path). Preserve any id the caller already set.
26977
28444
  metadata: {
26978
28445
  ...input.metadata,
26979
- correlationId: input.metadata?.correlationId ?? randomUUID9()
28446
+ correlationId: input.metadata?.correlationId ?? randomUUID11()
26980
28447
  }
26981
28448
  };
26982
28449
  }
@@ -26985,8 +28452,8 @@ function buildIngestEvent(input) {
26985
28452
  import { arch, hostname as hostname3, platform, release } from "os";
26986
28453
 
26987
28454
  // ../../packages/plugin-sdk/src/nudge.ts
26988
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
26989
- import { join as join9 } from "path";
28455
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
28456
+ import { join as join10 } from "path";
26990
28457
 
26991
28458
  // ../../packages/plugin-sdk/src/paths.ts
26992
28459
  import { readdirSync as readdirSync2, realpathSync as realpathSync2 } from "fs";
@@ -26994,8 +28461,8 @@ import { basename as basename3, dirname as dirname2, sep as sep3 } from "path";
26994
28461
 
26995
28462
  // ../../packages/plugin-sdk/src/project-files.ts
26996
28463
  var import_ignore = __toESM(require_ignore(), 1);
26997
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync6 } from "fs";
26998
- import { basename as basename4, join as join10, relative, sep as sep4 } from "path";
28464
+ import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync7 } from "fs";
28465
+ import { basename as basename4, join as join11, relative, sep as sep4 } from "path";
26999
28466
 
27000
28467
  // ../../packages/plugin-sdk/src/rule-quarantine.ts
27001
28468
  var PASS_BUDGET_MS = 2e3;
@@ -27051,7 +28518,7 @@ async function filterUnsafeRules(rules, gateway, opts) {
27051
28518
  }
27052
28519
 
27053
28520
  // ../../packages/plugin-sdk/src/runtime.ts
27054
- import { randomUUID as randomUUID10 } from "crypto";
28521
+ import { randomUUID as randomUUID12 } from "crypto";
27055
28522
  var ENFORCEMENT_CEILING_ENABLED = false;
27056
28523
  var ACTION_PRIORITY = ["block", "redact", "warn", "log", "allow"];
27057
28524
  function entryIsActive(entry, now) {
@@ -27154,7 +28621,12 @@ function createPluginRuntime(gateway, settings, opts) {
27154
28621
  if (worst === "block") return { action: "block", text: null, findings };
27155
28622
  if (worst === "redact") {
27156
28623
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
27157
- return { action: "redact", text: redact(text, redactFindings), findings };
28624
+ return {
28625
+ action: "redact",
28626
+ text: redact(text, redactFindings),
28627
+ findings,
28628
+ enforcedFindings: redactFindings
28629
+ };
27158
28630
  }
27159
28631
  return { action: worst, text, findings };
27160
28632
  }
@@ -27195,9 +28667,17 @@ function createPluginRuntime(gateway, settings, opts) {
27195
28667
  else groups.set(pair, [finding]);
27196
28668
  }
27197
28669
  const now = Date.now();
28670
+ const preAuthorized = new Set(ctx.preAuthorizedGrantIds ?? []);
27198
28671
  for (const [pair, group] of groups) {
27199
28672
  const entry = entries.get(pair);
27200
- if (!entry || !entryIsActive(entry, now) || !conditionsMatch(entry.conditions, ctx)) {
28673
+ if (!entry) continue;
28674
+ if (preAuthorized.has(entry.id)) {
28675
+ if (!conditionsMatch(entry.conditions, ctx)) continue;
28676
+ for (const finding of group) excepted.add(finding);
28677
+ exceptionIds.push(entry.id);
28678
+ continue;
28679
+ }
28680
+ if (!entryIsActive(entry, now) || !conditionsMatch(entry.conditions, ctx)) {
27201
28681
  continue;
27202
28682
  }
27203
28683
  let consumed = false;
@@ -27229,7 +28709,7 @@ function createPluginRuntime(gateway, settings, opts) {
27229
28709
  const pair = `${finding.ruleId}:${fp}`;
27230
28710
  if (seen.has(pair)) continue;
27231
28711
  seen.add(pair);
27232
- const reference = randomUUID10().replaceAll("-", "").slice(0, 6);
28712
+ const reference = randomUUID12().replaceAll("-", "").slice(0, 6);
27233
28713
  const maskedValue = maskMatch(finding.rawMatch);
27234
28714
  try {
27235
28715
  await gateway.recordBlockedDetection({
@@ -27253,7 +28733,8 @@ function createPluginRuntime(gateway, settings, opts) {
27253
28733
  async function evaluate(text, context, ctx) {
27254
28734
  try {
27255
28735
  await ensureInitialized();
27256
- const findings = scan(text, rules, context);
28736
+ const shielded = shieldPointers(text);
28737
+ const findings = dropShieldedFindings(scan(shielded.text, rules, context), shielded.spans);
27257
28738
  const fpCache = /* @__PURE__ */ new Map();
27258
28739
  const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
27259
28740
  const decision = decide(findings, text, excepted);
@@ -27276,7 +28757,11 @@ function createPluginRuntime(gateway, settings, opts) {
27276
28757
  const { decision, excepted, exceptionIds } = await evaluate(
27277
28758
  input.text,
27278
28759
  filePath ? { filePath } : void 0,
27279
- { sourceTool: input.sourceTool, metadata: input.metadata }
28760
+ {
28761
+ sourceTool: input.sourceTool,
28762
+ metadata: input.metadata,
28763
+ preAuthorizedGrantIds: opts2.preAuthorizedGrantIds
28764
+ }
27280
28765
  );
27281
28766
  if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
27282
28767
  try {
@@ -27306,7 +28791,7 @@ function createPluginRuntime(gateway, settings, opts) {
27306
28791
  valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
27307
28792
  }) : void 0;
27308
28793
  return {
27309
- id: randomUUID10(),
28794
+ id: randomUUID12(),
27310
28795
  eventId: event.id,
27311
28796
  ruleId: match.ruleId,
27312
28797
  category: match.category,
@@ -27332,7 +28817,7 @@ function createPluginRuntime(gateway, settings, opts) {
27332
28817
  const sorted = [...rules].sort((a, b) => a.id.localeCompare(b.id));
27333
28818
  return contentHashOf(JSON.stringify(sorted));
27334
28819
  } catch {
27335
- return `unresolved-${randomUUID10()}`;
28820
+ return `unresolved-${randomUUID12()}`;
27336
28821
  }
27337
28822
  }
27338
28823
  async function close() {
@@ -27345,8 +28830,380 @@ function createPluginRuntime(gateway, settings, opts) {
27345
28830
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
27346
28831
 
27347
28832
  // ../../packages/plugin-sdk/src/throttle.ts
27348
- import { mkdirSync as mkdirSync3, statSync as statSync3, writeFileSync as writeFileSync4 } from "fs";
27349
- import { join as join11 } from "path";
28833
+ import { mkdirSync as mkdirSync4, statSync as statSync4, writeFileSync as writeFileSync5 } from "fs";
28834
+ import { join as join12 } from "path";
28835
+
28836
+ // ../../packages/plugin-sdk/src/tokenize.ts
28837
+ function redactedPlaceholder(category) {
28838
+ return `[REDACTED:${category.toUpperCase()}]`;
28839
+ }
28840
+ var POINTER_UNAVAILABLE_TEXT = "[unavailable]";
28841
+ var SEVERITY_RANK3 = { critical: 3, high: 2, medium: 1, low: 0 };
28842
+ function groupSpans(text, findings) {
28843
+ const sorted = [...findings].filter((f) => f.span.start >= 0 && f.span.end <= text.length && f.span.start < f.span.end).sort((a, b) => a.span.start - b.span.start || b.span.end - a.span.end);
28844
+ const groups = [];
28845
+ for (const finding of sorted) {
28846
+ const last = groups[groups.length - 1];
28847
+ if (last && finding.span.start < last.end) {
28848
+ last.end = Math.max(last.end, finding.span.end);
28849
+ if ((SEVERITY_RANK3[finding.severity] ?? 0) > (SEVERITY_RANK3[last.severity] ?? 0)) {
28850
+ last.category = finding.category;
28851
+ last.severity = finding.severity;
28852
+ }
28853
+ delete last.finding;
28854
+ continue;
28855
+ }
28856
+ groups.push({
28857
+ start: finding.span.start,
28858
+ end: finding.span.end,
28859
+ finding,
28860
+ category: finding.category,
28861
+ severity: finding.severity
28862
+ });
28863
+ }
28864
+ return groups;
28865
+ }
28866
+ var NULL_RESOLVER = () => Promise.resolve(null);
28867
+ var SecretVaultGlue = class {
28868
+ #vault;
28869
+ revealGrantResolver;
28870
+ // Set only when THIS glue opened the store, so a glue over an injected vault
28871
+ // never closes a handle it does not own.
28872
+ #release;
28873
+ constructor(vault, revealGrantResolver = NULL_RESOLVER, release2) {
28874
+ this.#vault = vault;
28875
+ this.revealGrantResolver = revealGrantResolver;
28876
+ this.#release = release2;
28877
+ }
28878
+ close() {
28879
+ const release2 = this.#release;
28880
+ this.#release = void 0;
28881
+ try {
28882
+ release2?.();
28883
+ } catch {
28884
+ }
28885
+ }
28886
+ async tokenizeValue(raw, meta3) {
28887
+ try {
28888
+ const result = await this.#vault.tokenize(raw, meta3);
28889
+ return typeof result === "string" ? result : redactedPlaceholder(meta3.category);
28890
+ } catch {
28891
+ return redactedPlaceholder(meta3.category);
28892
+ }
28893
+ }
28894
+ async tokenizeText(text, opts) {
28895
+ try {
28896
+ const findings = opts?.findings ?? this.#selfScan(text);
28897
+ if (findings === null) return { text: "[REDACTED]", pointers: [], degraded: [] };
28898
+ if (findings.length === 0) return { text, pointers: [], degraded: [] };
28899
+ const groups = groupSpans(text, findings);
28900
+ const pointers = [];
28901
+ const degraded = [];
28902
+ let out = text;
28903
+ for (const group of [...groups].reverse()) {
28904
+ const original = text.slice(group.start, group.end);
28905
+ const finding = group.finding;
28906
+ let replacement;
28907
+ if (finding === void 0) {
28908
+ replacement = redactedPlaceholder(group.category);
28909
+ degraded.unshift({ category: group.category });
28910
+ } else if (original !== finding.rawMatch) {
28911
+ replacement = redactedPlaceholder(group.category);
28912
+ degraded.unshift({ category: group.category });
28913
+ } else {
28914
+ replacement = await this.tokenizeValue(finding.rawMatch, {
28915
+ ruleId: finding.ruleId,
28916
+ category: finding.category,
28917
+ maskedMatch: maskMatch(finding.rawMatch)
28918
+ });
28919
+ if (replacement.startsWith("[[aka:")) pointers.unshift(replacement);
28920
+ else degraded.unshift({ category: finding.category });
28921
+ }
28922
+ out = out.slice(0, group.start) + replacement + out.slice(group.end);
28923
+ }
28924
+ if (opts?.sighting && pointers.length > 0) {
28925
+ for (const pointer of pointers) {
28926
+ try {
28927
+ const id = pointer.split(".")[1];
28928
+ if (id !== void 0) this.#vault.recordSighting?.(id, opts.sighting);
28929
+ } catch {
28930
+ }
28931
+ }
28932
+ }
28933
+ return { text: out, pointers, degraded };
28934
+ } catch {
28935
+ return { text: "[REDACTED]", pointers: [], degraded: [] };
28936
+ }
28937
+ }
28938
+ async detokenizeText(text, opts) {
28939
+ try {
28940
+ const matches = [...text.matchAll(pointerTokenScanner())];
28941
+ if (matches.length === 0) return { text, revealed: 0 };
28942
+ const occurrences = /* @__PURE__ */ new Map();
28943
+ for (const match of matches) {
28944
+ occurrences.set(match[0], (occurrences.get(match[0]) ?? 0) + 1);
28945
+ }
28946
+ const resolved = /* @__PURE__ */ new Map();
28947
+ for (const [pointer, count] of occurrences) {
28948
+ try {
28949
+ const value = await this.#vault.detokenize(pointer, {
28950
+ target: "human",
28951
+ reason: opts.reason,
28952
+ pointerCount: count
28953
+ });
28954
+ resolved.set(pointer, typeof value === "string" ? value : null);
28955
+ } catch {
28956
+ resolved.set(pointer, null);
28957
+ }
28958
+ }
28959
+ let out = text;
28960
+ let revealed = 0;
28961
+ for (const match of [...matches].reverse()) {
28962
+ const value = resolved.get(match[0]);
28963
+ const replacement = value ?? POINTER_UNAVAILABLE_TEXT;
28964
+ if (value !== null && value !== void 0) revealed += 1;
28965
+ out = out.slice(0, match.index) + replacement + out.slice(match.index + match[0].length);
28966
+ }
28967
+ return { text: out, revealed };
28968
+ } catch {
28969
+ return { text, revealed: 0 };
28970
+ }
28971
+ }
28972
+ // Scan with the bundled packs, as the mask path does. Pointers already in the
28973
+ // text are blanked first so a pointer is never re-tokenized. Returns null
28974
+ // when the registry or the scan itself failed — the caller must then treat
28975
+ // the whole text as unclassifiable.
28976
+ #selfScan(text) {
28977
+ try {
28978
+ registerBundledPacks();
28979
+ const shielded = shieldPointers(text);
28980
+ return dropShieldedFindings(scan(shielded.text, getLoadedRules()), shielded.spans);
28981
+ } catch {
28982
+ return null;
28983
+ }
28984
+ }
28985
+ async describePointerSafe(token) {
28986
+ try {
28987
+ return await this.#vault.describePointer(token);
28988
+ } catch {
28989
+ return null;
28990
+ }
28991
+ }
28992
+ async probeModelPointers(text, opts) {
28993
+ const granted = /* @__PURE__ */ new Map();
28994
+ const ungranted = [];
28995
+ try {
28996
+ for (const pointer of new Set([...text.matchAll(pointerTokenScanner())].map((m) => m[0]))) {
28997
+ try {
28998
+ const grantId = await opts.resolveGrant(pointer);
28999
+ if (grantId === null) ungranted.push(pointer);
29000
+ else granted.set(pointer, grantId);
29001
+ } catch {
29002
+ ungranted.push(pointer);
29003
+ }
29004
+ }
29005
+ return { granted, ungranted };
29006
+ } catch {
29007
+ return { granted: /* @__PURE__ */ new Map(), ungranted };
29008
+ }
29009
+ }
29010
+ async substituteModelPointers(text, opts) {
29011
+ try {
29012
+ const matches = [...text.matchAll(pointerTokenScanner())];
29013
+ if (matches.length === 0) return { text, revealed: [], unresolved: [], grantIds: [] };
29014
+ const resolved = /* @__PURE__ */ new Map();
29015
+ for (const pointer of new Set(matches.map((m) => m[0]))) {
29016
+ try {
29017
+ const grantId = await opts.resolveGrant(pointer);
29018
+ if (grantId === null) {
29019
+ await this.#vault.detokenize(pointer, { target: "model", reason: "model-input" });
29020
+ resolved.set(pointer, null);
29021
+ continue;
29022
+ }
29023
+ const value = await this.#vault.detokenize(pointer, {
29024
+ target: "model",
29025
+ reason: "model-input",
29026
+ grantId
29027
+ });
29028
+ resolved.set(pointer, typeof value === "string" ? { value, grantId } : null);
29029
+ } catch {
29030
+ resolved.set(pointer, null);
29031
+ }
29032
+ }
29033
+ const spentGrants = /* @__PURE__ */ new Set();
29034
+ for (const entry of resolved.values()) {
29035
+ if (entry === null || spentGrants.has(entry.grantId)) continue;
29036
+ spentGrants.add(entry.grantId);
29037
+ try {
29038
+ await this.#vault.consumeGrant?.(entry.grantId);
29039
+ } catch {
29040
+ }
29041
+ }
29042
+ let out = text;
29043
+ const revealed = /* @__PURE__ */ new Set();
29044
+ const unresolved = /* @__PURE__ */ new Set();
29045
+ for (const match of [...matches].reverse()) {
29046
+ const entry = resolved.get(match[0]);
29047
+ if (entry === null || entry === void 0) {
29048
+ unresolved.add(match[0]);
29049
+ continue;
29050
+ }
29051
+ revealed.add(match[0]);
29052
+ out = out.slice(0, match.index) + entry.value + out.slice(match.index + match[0].length);
29053
+ }
29054
+ return {
29055
+ text: out,
29056
+ revealed: [...revealed],
29057
+ unresolved: [...unresolved],
29058
+ grantIds: [...spentGrants]
29059
+ };
29060
+ } catch {
29061
+ return { text, revealed: [], unresolved: [], grantIds: [] };
29062
+ }
29063
+ }
29064
+ };
29065
+ function hasPointer(text) {
29066
+ return pointerTokenScanner().test(text);
29067
+ }
29068
+ function createVaultGlue(options) {
29069
+ if (options?.vault) return new SecretVaultGlue(options.vault, options.revealResolver);
29070
+ const base = options?.base ?? defaultDataDir();
29071
+ try {
29072
+ const dir = dataDir(base);
29073
+ const db = openLocalDatabase(dir);
29074
+ const settings = readWorkspaceSettings(base);
29075
+ const provider = options?.policyProvider ?? new UserGrantPolicyProvider(db.exceptions);
29076
+ const vault = new SecretVault({
29077
+ repo: db.secretVault,
29078
+ keys: createKeyProvider(settings.vaultKeyCustody, keysDir(base)),
29079
+ fingerprintKey: loadOrCreateFingerprintKey(dir),
29080
+ // Read live so a revocation applies to the very next call, not the next
29081
+ // process.
29082
+ isConsented: () => isVaultConsentValid(readWorkspaceSettings(base).vaultConsent),
29083
+ // This is the one construction site that reveals to the model, so it is
29084
+ // the one that supplies the last gate. The decision is re-taken from the
29085
+ // ROW's identity at the moment of crossing, which closes the window
29086
+ // between resolving a grant and spending it: a grant revoked in between
29087
+ // refuses here.
29088
+ //
29089
+ // The re-decision is on the identity alone, never on the grant id
29090
+ // matching the one the resolver returned. ExceptionPolicyProvider
29091
+ // promises no id stability across calls — a provider deciding from
29092
+ // external policy may well mint a fresh id each time — so comparing ids
29093
+ // would silently refuse every crossing for such a provider while looking
29094
+ // like a security check. `allow` for this row is the whole question.
29095
+ verifyGrant: async (_grantId, identity) => {
29096
+ const decision = await provider.decideReveal(identity);
29097
+ return decision.allow;
29098
+ }
29099
+ });
29100
+ const vaultWithSightings = {
29101
+ tokenize: (raw, meta3) => vault.tokenize(raw, meta3),
29102
+ detokenize: (token, opts) => vault.detokenize(token, opts),
29103
+ describePointer: (token) => vault.describePointer(token),
29104
+ resolvePointerIdentity: (token) => vault.resolvePointerIdentity(token),
29105
+ recordSighting: (pointerId, sighting) => {
29106
+ db.secretVault.recordSighting({ pointerId, ...sighting }, Date.now());
29107
+ },
29108
+ consumeGrant: (grantId) => db.exceptions.consume(grantId)
29109
+ };
29110
+ const revealGrantResolver = async (pointer) => {
29111
+ try {
29112
+ const identity = await vault.resolvePointerIdentity(pointer);
29113
+ if (identity === null) return null;
29114
+ const decision = await provider.decideReveal(identity);
29115
+ return decision.allow ? decision.grantId : null;
29116
+ } catch {
29117
+ return null;
29118
+ }
29119
+ };
29120
+ return new SecretVaultGlue(vaultWithSightings, revealGrantResolver, () => {
29121
+ db.close();
29122
+ });
29123
+ } catch {
29124
+ return new SecretVaultGlue(UNOPENABLE_VAULT);
29125
+ }
29126
+ }
29127
+ var UNOPENABLE_VAULT = {
29128
+ tokenize: () => Promise.resolve(/* @__PURE__ */ Symbol("aka.vault.unopenable")),
29129
+ detokenize: () => Promise.resolve(/* @__PURE__ */ Symbol("aka.vault.unopenable")),
29130
+ describePointer: () => Promise.resolve(null),
29131
+ resolvePointerIdentity: () => Promise.resolve(null)
29132
+ };
29133
+
29134
+ // src/protocol/marker.ts
29135
+ import { randomBytes as randomBytes4 } from "crypto";
29136
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, renameSync as renameSync5, writeFileSync as writeFileSync6 } from "fs";
29137
+ import { join as join13 } from "path";
29138
+ var MARKER_FILE = "protocol-marker";
29139
+ function mintMarker() {
29140
+ return randomBytes4(8).toString("hex");
29141
+ }
29142
+ function sessionProtocolMarker(dataDir2, sessionId) {
29143
+ if (!sessionId) return mintMarker();
29144
+ const path = join13(dataDir2, MARKER_FILE);
29145
+ try {
29146
+ const stored = JSON.parse(readFileSync8(path, "utf8"));
29147
+ if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
29148
+ return stored.marker;
29149
+ }
29150
+ } catch {
29151
+ }
29152
+ const marker = mintMarker();
29153
+ try {
29154
+ mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
29155
+ const tmp = join13(dataDir2, `${MARKER_FILE}.tmp`);
29156
+ writeFileSync6(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
29157
+ renameSync5(tmp, path);
29158
+ } catch {
29159
+ }
29160
+ return marker;
29161
+ }
29162
+
29163
+ // src/protocol/notes.ts
29164
+ function countOf(n, noun) {
29165
+ return `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
29166
+ }
29167
+ function uniqueCategories(items) {
29168
+ return [...new Set(items.map((item) => item.category))].join(", ");
29169
+ }
29170
+ function eventNote(opts) {
29171
+ const { pointers, degraded } = opts.realized;
29172
+ if (pointers.length === 0 && degraded.length === 0) return null;
29173
+ const parts = [];
29174
+ if (pointers.length > 0) {
29175
+ const shown = pointers.slice(0, VAULT_EVENT_NOTE_MAX_POINTERS);
29176
+ const listed = shown.map((p) => `${p.token} (${p.category}${p.provider ? `/${p.provider}` : ""})`).join(", ");
29177
+ const hidden = pointers.length - shown.length;
29178
+ const overflow = hidden > 0 ? ` \u2026 and ${String(hidden)} more` : "";
29179
+ parts.push(
29180
+ `AKA replaced ${countOf(pointers.length, "value")} before this ran \u2014 ${listed}${overflow}. Use each pointer verbatim; the raw values are not available to you. Never fabricate or alter a pointer.`
29181
+ );
29182
+ }
29183
+ if (degraded.length > 0) {
29184
+ const many = degraded.length > 1;
29185
+ parts.push(
29186
+ `AKA removed ${countOf(degraded.length, "value")} (${uniqueCategories(degraded)}) before this ran. The vault was unavailable so ${many ? "they were" : "it was"} redacted irreversibly \u2014 no pointer exists for ${many ? "them" : "it"}. Do not invent one, and do not ask the user for the ${many ? "values" : "value"}.`
29187
+ );
29188
+ }
29189
+ return `[AKA ${opts.marker}] ${opts.surface}: ${parts.join(" ")}`;
29190
+ }
29191
+ function userDisclosure(opts) {
29192
+ const { pointers, degraded } = opts.realized;
29193
+ if (pointers.length === 0 && degraded.length === 0) return null;
29194
+ const sentences = [];
29195
+ if (pointers.length > 0) {
29196
+ sentences.push(
29197
+ `AKA replaced ${countOf(pointers.length, "value")} (${uniqueCategories(pointers)}) in this ${opts.surface} \u2014 kept recoverable in your local vault \u2014 see the AKA dashboard or \`aka vault show\`.`
29198
+ );
29199
+ }
29200
+ if (degraded.length > 0) {
29201
+ sentences.push(
29202
+ `AKA removed ${countOf(degraded.length, "value")} (${uniqueCategories(degraded)}) from this ${opts.surface} \u2014 redacted irreversibly \u2014 the vault was unavailable.`
29203
+ );
29204
+ }
29205
+ return sentences.join(" ");
29206
+ }
27350
29207
 
27351
29208
  // src/hooks/paths.ts
27352
29209
  function stringAtPath(root, path) {
@@ -27381,6 +29238,41 @@ function replaceAtPath(root, path, value) {
27381
29238
  return { ...record2, [head]: replaceAtPath(record2[head], rest, value) };
27382
29239
  }
27383
29240
 
29241
+ // src/hooks/pointer-substitution.ts
29242
+ async function decideInputPointers(fields, substitute) {
29243
+ const outcomes = [];
29244
+ for (const field of fields) {
29245
+ if (!hasPointer(field.text)) continue;
29246
+ let text = field.text;
29247
+ let revealed = [];
29248
+ let unresolved = [];
29249
+ let failed = false;
29250
+ try {
29251
+ ({ text, revealed, unresolved } = await substitute(field.text));
29252
+ } catch {
29253
+ failed = true;
29254
+ }
29255
+ if (field.executable) {
29256
+ if (failed || unresolved.length > 0 || revealed.length === 0) {
29257
+ outcomes.push({ path: field.path, disposition: "deny" });
29258
+ } else {
29259
+ outcomes.push({ path: field.path, disposition: "deref", text });
29260
+ }
29261
+ } else if (!failed && revealed.length > 0) {
29262
+ outcomes.push({ path: field.path, disposition: "deref", text });
29263
+ } else {
29264
+ outcomes.push({ path: field.path, disposition: "keep" });
29265
+ }
29266
+ }
29267
+ return outcomes;
29268
+ }
29269
+ function denyPointerMessage(toolName) {
29270
+ return `A vault pointer in a ${toolName} command cannot execute as text, and AKA does not substitute the raw value without an active reveal exception. Ask the user to grant one (aka exception approve) or remove the pointer.`;
29271
+ }
29272
+ function denyUnresolvedPointerMessage(toolName) {
29273
+ return `A vault pointer in a ${toolName} command is covered by a reveal exception but its value could not be resolved, so the command was not run rather than executed with the pointer as literal text. The entry may have been purged; check the vault.`;
29274
+ }
29275
+
27384
29276
  // src/present.ts
27385
29277
  var fg = (hex3) => (text) => {
27386
29278
  const r = Number.parseInt(hex3.slice(1, 3), 16);
@@ -27430,7 +29322,11 @@ function exceptionPointer(references) {
27430
29322
 
27431
29323
  // src/hooks/pre-tool-use-decision.ts
27432
29324
  var EXECUTABLE_REDACT_NOTE = "Masking inside an executable command would silently change what runs, so a redact policy blocks it instead.";
27433
- function decidePreToolUse(toolName, toolInput, scanned) {
29325
+ function pointerCategory(token) {
29326
+ const match = /^\[\[aka:([a-z_]+):/.exec(token);
29327
+ return match?.[1] ?? "secret";
29328
+ }
29329
+ async function decidePreToolUse(toolName, toolInput, scanned, tokenizeField) {
27434
29330
  const blockedRules = /* @__PURE__ */ new Set();
27435
29331
  const warnedRules = /* @__PURE__ */ new Set();
27436
29332
  const redactedRules = /* @__PURE__ */ new Set();
@@ -27438,7 +29334,8 @@ function decidePreToolUse(toolName, toolInput, scanned) {
27438
29334
  const redactedReferences = [];
27439
29335
  let escalated = false;
27440
29336
  let updatedInput = null;
27441
- for (const { spec, result } of scanned) {
29337
+ const realized = { pointers: [], degraded: [] };
29338
+ for (const { spec, text, result } of scanned) {
27442
29339
  const escalate = result.action === "redact" && spec.executable;
27443
29340
  if (escalate) escalated = true;
27444
29341
  const action = escalate ? "block" : result.action;
@@ -27448,8 +29345,21 @@ function decidePreToolUse(toolName, toolInput, scanned) {
27448
29345
  } else if (action === "redact") {
27449
29346
  for (const finding of result.findings) redactedRules.add(finding.ruleId);
27450
29347
  if (result.blockedReferences) redactedReferences.push(...result.blockedReferences);
27451
- if (result.text !== null) {
27452
- updatedInput = replaceAtPath(updatedInput ?? toolInput, spec.path, result.text);
29348
+ let rewritten = result.text;
29349
+ const enforced = result.enforcedFindings ?? [];
29350
+ if (tokenizeField && enforced.length > 0) {
29351
+ try {
29352
+ const tokenized = await tokenizeField(text, enforced);
29353
+ rewritten = tokenized.text;
29354
+ for (const token of tokenized.pointers) {
29355
+ realized.pointers.push({ token, category: pointerCategory(token) });
29356
+ }
29357
+ realized.degraded.push(...tokenized.degraded);
29358
+ } catch {
29359
+ }
29360
+ }
29361
+ if (rewritten !== null) {
29362
+ updatedInput = replaceAtPath(updatedInput ?? toolInput, spec.path, rewritten);
27453
29363
  }
27454
29364
  } else if (action === "warn") {
27455
29365
  for (const finding of result.findings) warnedRules.add(finding.ruleId);
@@ -27457,31 +29367,41 @@ function decidePreToolUse(toolName, toolInput, scanned) {
27457
29367
  }
27458
29368
  if (blockedRules.size > 0) {
27459
29369
  return {
27460
- hookSpecificOutput: {
27461
- hookEventName: "PreToolUse",
27462
- permissionDecision: "deny",
27463
- permissionDecisionReason: blockMessage({
27464
- subject: `${toolName} call`,
27465
- ruleIds: [...blockedRules].join(", "),
27466
- blockedRef: blockedReferences[0],
27467
- note: escalated ? EXECUTABLE_REDACT_NOTE : void 0
27468
- })
27469
- }
29370
+ output: {
29371
+ hookSpecificOutput: {
29372
+ hookEventName: "PreToolUse",
29373
+ permissionDecision: "deny",
29374
+ permissionDecisionReason: blockMessage({
29375
+ subject: `${toolName} call`,
29376
+ ruleIds: [...blockedRules].join(", "),
29377
+ blockedRef: blockedReferences[0],
29378
+ note: escalated ? EXECUTABLE_REDACT_NOTE : void 0
29379
+ })
29380
+ }
29381
+ },
29382
+ realized: null
27470
29383
  };
27471
29384
  }
27472
29385
  if (redactedRules.size > 0) {
29386
+ const tokenized = realized.pointers.length > 0 || realized.degraded.length > 0;
27473
29387
  return {
27474
- hookSpecificOutput: {
27475
- hookEventName: "PreToolUse",
27476
- permissionDecision: "allow",
27477
- updatedInput: updatedInput ?? { ...toolInput }
29388
+ output: {
29389
+ hookSpecificOutput: {
29390
+ hookEventName: "PreToolUse",
29391
+ permissionDecision: "allow",
29392
+ updatedInput: updatedInput ?? { ...toolInput }
29393
+ },
29394
+ systemMessage: `AKA redacted sensitive content in ${toolName} input \u2014 flagged ${[...redactedRules].join(", ")}.${exceptionPointer(redactedReferences)}`
27478
29395
  },
27479
- systemMessage: `AKA redacted sensitive content in ${toolName} input \u2014 flagged ${[...redactedRules].join(", ")}.${exceptionPointer(redactedReferences)}`
29396
+ realized: tokenized ? realized : null
27480
29397
  };
27481
29398
  }
27482
29399
  if (warnedRules.size > 0) {
27483
29400
  return {
27484
- systemMessage: `AKA flagged sensitive content in ${toolName} input (${[...warnedRules].join(", ")}).`
29401
+ output: {
29402
+ systemMessage: `AKA flagged sensitive content in ${toolName} input (${[...warnedRules].join(", ")}).`
29403
+ },
29404
+ realized: null
27485
29405
  };
27486
29406
  }
27487
29407
  return null;
@@ -27621,11 +29541,11 @@ function baseMetadata(input) {
27621
29541
  }
27622
29542
 
27623
29543
  // src/hooks/store-health.ts
27624
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
27625
- import { join as join12 } from "path";
29544
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync9, writeFileSync as writeFileSync7 } from "fs";
29545
+ import { join as join14 } from "path";
27626
29546
 
27627
29547
  // ../../packages/plugin-runtime/src/standalone-gateway.ts
27628
- import { randomUUID as randomUUID11 } from "crypto";
29548
+ import { randomUUID as randomUUID13 } from "crypto";
27629
29549
 
27630
29550
  // ../../packages/plugin-runtime/src/recorder.ts
27631
29551
  var PLUGIN_RECORDER_BINARY = "plugin";
@@ -27787,7 +29707,7 @@ var StandaloneDataGateway = class {
27787
29707
  const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
27788
29708
  const installed = this.installedScanRules();
27789
29709
  const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
27790
- id: randomUUID11(),
29710
+ id: randomUUID13(),
27791
29711
  scope: "global",
27792
29712
  target: { ruleId },
27793
29713
  action,
@@ -27940,7 +29860,7 @@ function resolveDataGateway(config2, meta3, gatewayFactory = standaloneGatewayFa
27940
29860
  }
27941
29861
 
27942
29862
  // ../../packages/plugin-runtime/src/handle-session-start.ts
27943
- import { randomUUID as randomUUID12 } from "crypto";
29863
+ import { randomUUID as randomUUID14 } from "crypto";
27944
29864
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
27945
29865
 
27946
29866
  // src/hooks/store-health.ts
@@ -27957,14 +29877,14 @@ function storeUnavailableMessage(dbPath2) {
27957
29877
  }
27958
29878
  function claimStoreUnavailableWarning(dataDir2, sessionId) {
27959
29879
  if (!sessionId) return true;
27960
- const path = join12(dataDir2, STORE_WARNING_MARKER);
29880
+ const path = join14(dataDir2, STORE_WARNING_MARKER);
27961
29881
  try {
27962
- if (readFileSync7(path, "utf8") === sessionId) return false;
29882
+ if (readFileSync9(path, "utf8") === sessionId) return false;
27963
29883
  } catch {
27964
29884
  }
27965
29885
  try {
27966
- mkdirSync4(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
27967
- writeFileSync5(path, sessionId, { mode: DATA_FILE_MODE });
29886
+ mkdirSync6(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
29887
+ writeFileSync7(path, sessionId, { mode: DATA_FILE_MODE });
27968
29888
  } catch {
27969
29889
  }
27970
29890
  return true;
@@ -27981,9 +29901,64 @@ async function main() {
27981
29901
  const fields = scannableInputFields(toolName, toolInput);
27982
29902
  if (fields.length === 0) return;
27983
29903
  const config2 = loadConfig();
29904
+ const sessionId = getString(input, "session_id");
29905
+ const consented = isVaultConsentValid(config2.settings.vaultConsent);
29906
+ const vaultGlue = consented ? createVaultGlue() : null;
29907
+ const pointerFields = [];
29908
+ for (const spec of fields) {
29909
+ const text = stringAtPath(toolInput, spec.path);
29910
+ if (text !== void 0 && text !== "") {
29911
+ pointerFields.push({ path: spec.path, text, executable: spec.executable });
29912
+ }
29913
+ }
29914
+ const spentGrantIds = [];
29915
+ let denyForPointer = false;
29916
+ if (vaultGlue) {
29917
+ for (const field of pointerFields.filter((f) => f.executable)) {
29918
+ const probe = await vaultGlue.probeModelPointers(field.text, {
29919
+ resolveGrant: vaultGlue.revealGrantResolver
29920
+ });
29921
+ if (probe.ungranted.length > 0) denyForPointer = true;
29922
+ }
29923
+ } else {
29924
+ denyForPointer = pointerFields.some((f) => f.executable && pointerTokenScanner().test(f.text));
29925
+ }
29926
+ const pointerOutcomes = denyForPointer ? [] : await decideInputPointers(pointerFields, async (text) => {
29927
+ if (!vaultGlue) {
29928
+ return {
29929
+ text,
29930
+ revealed: [],
29931
+ unresolved: [...text.matchAll(pointerTokenScanner())].map((m) => m[0]),
29932
+ grantIds: []
29933
+ };
29934
+ }
29935
+ const result = await vaultGlue.substituteModelPointers(text, {
29936
+ resolveGrant: vaultGlue.revealGrantResolver
29937
+ });
29938
+ spentGrantIds.push(...result.grantIds);
29939
+ return result;
29940
+ });
29941
+ const unresolvedAfterGrant = pointerOutcomes.some((o) => o.disposition === "deny");
29942
+ if (denyForPointer || unresolvedAfterGrant) {
29943
+ await emit({
29944
+ hookSpecificOutput: {
29945
+ hookEventName: "PreToolUse",
29946
+ permissionDecision: "deny",
29947
+ permissionDecisionReason: denyForPointer ? denyPointerMessage(toolName) : denyUnresolvedPointerMessage(toolName)
29948
+ }
29949
+ });
29950
+ return;
29951
+ }
29952
+ let effectiveInput = toolInput;
29953
+ let derefHappened = false;
29954
+ for (const outcome of pointerOutcomes) {
29955
+ if (outcome.disposition !== "deref" || outcome.text === void 0) continue;
29956
+ effectiveInput = replaceAtPath(effectiveInput, outcome.path, outcome.text);
29957
+ derefHappened = true;
29958
+ }
27984
29959
  const gateway = openGatewayOrNull(config2);
27985
29960
  if (gateway === null) {
27986
- if (claimStoreUnavailableWarning(config2.dataDir, getString(input, "session_id"))) {
29961
+ if (claimStoreUnavailableWarning(config2.dataDir, sessionId)) {
27987
29962
  await emit({ systemMessage: storeUnavailableMessage(config2.dbPath) });
27988
29963
  }
27989
29964
  return;
@@ -27997,7 +29972,7 @@ async function main() {
27997
29972
  const scanned = [];
27998
29973
  try {
27999
29974
  for (const spec of fields) {
28000
- const text = stringAtPath(toolInput, spec.path);
29975
+ const text = stringAtPath(effectiveInput, spec.path);
28001
29976
  if (text === void 0 || text === "") continue;
28002
29977
  const result = await runtime.capture(
28003
29978
  { kind, sourceTool: "claude-code", text, metadata },
@@ -28007,15 +29982,83 @@ async function main() {
28007
29982
  // every Bash command and one call per string leaf of every MCP payload,
28008
29983
  // and 'always' would copy that whole stream into the store to trail the
28009
29984
  // enforcement decisions that are the point of the kind.
28010
- kind === "tool_use" ? { persist: "with-findings" } : {}
29985
+ {
29986
+ ...kind === "tool_use" ? { persist: "with-findings" } : {},
29987
+ // Grants this call's pointer crossing already spent: suppression
29988
+ // applies without charging a second use.
29989
+ ...spentGrantIds.length > 0 ? { preAuthorizedGrantIds: spentGrantIds } : {}
29990
+ }
28011
29991
  );
28012
- scanned.push({ spec, result });
29992
+ scanned.push({ spec, text, result });
28013
29993
  }
28014
29994
  } finally {
28015
29995
  await runtime.close();
28016
29996
  }
28017
- const output = decidePreToolUse(toolName, toolInput, scanned);
28018
- if (output) await emit(output);
29997
+ const decision = await decidePreToolUse(
29998
+ toolName,
29999
+ effectiveInput,
30000
+ scanned,
30001
+ vaultGlue ? (text, findings) => vaultGlue.tokenizeText(text, {
30002
+ findings,
30003
+ sighting: filePath ? { location: filePath, kind: "file" } : { location: `${toolName} input`, kind: "tool-input" }
30004
+ }) : void 0
30005
+ );
30006
+ const revealNote = `AKA revealed granted vault value(s) to this ${toolName} call \u2014 the reveal exception you approved authorized it.`;
30007
+ if (decision) {
30008
+ const output = withProtocolNotes(
30009
+ decision.output,
30010
+ decision.realized,
30011
+ toolName,
30012
+ config2,
30013
+ sessionId,
30014
+ vaultGlue
30015
+ );
30016
+ if (derefHappened && !("hookSpecificOutput" in output)) {
30017
+ await emit({
30018
+ hookSpecificOutput: {
30019
+ hookEventName: "PreToolUse",
30020
+ permissionDecision: "allow",
30021
+ updatedInput: effectiveInput
30022
+ },
30023
+ systemMessage: `${output.systemMessage} ${revealNote}`
30024
+ });
30025
+ return;
30026
+ }
30027
+ await emit(output);
30028
+ return;
30029
+ }
30030
+ if (derefHappened) {
30031
+ await emit({
30032
+ hookSpecificOutput: {
30033
+ hookEventName: "PreToolUse",
30034
+ permissionDecision: "allow",
30035
+ updatedInput: effectiveInput
30036
+ },
30037
+ systemMessage: revealNote
30038
+ });
30039
+ }
30040
+ }
30041
+ function withProtocolNotes(output, realized, toolName, config2, sessionId, vaultGlue) {
30042
+ if (!vaultGlue || realized === null || !("hookSpecificOutput" in output)) return output;
30043
+ if (!("updatedInput" in output.hookSpecificOutput) || !("systemMessage" in output)) {
30044
+ return output;
30045
+ }
30046
+ try {
30047
+ const surface = `${toolName} input`;
30048
+ const marker = sessionProtocolMarker(config2.dataDir, sessionId);
30049
+ const note = eventNote({ marker, surface, realized });
30050
+ const disclosure = userDisclosure({ surface, realized });
30051
+ return {
30052
+ ...output,
30053
+ hookSpecificOutput: {
30054
+ ...output.hookSpecificOutput,
30055
+ ...note === null ? {} : { additionalContext: note }
30056
+ },
30057
+ systemMessage: disclosure ?? output.systemMessage
30058
+ };
30059
+ } catch {
30060
+ return output;
30061
+ }
28019
30062
  }
28020
30063
  try {
28021
30064
  await main();