@atbash/sdk 0.5.8 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -68,6 +68,38 @@ interface MemoryDiffResult {
68
68
  modified: ModifiedEntry[];
69
69
  anomalies: MemoryAnomaly[];
70
70
  }
71
+ /** AES-256-GCM output from `encryptMemoryContent`. */
72
+ interface EncryptedMemory {
73
+ ciphertext: Buffer;
74
+ nonce: Buffer;
75
+ }
76
+ /** Memory scanner verdict — matches the judge-response colour taxonomy. */
77
+ type MemoryScanVerdict = "green" | "yellow" | "red";
78
+ /** Result of `scanMemory` (regex pre-filter and/or LLM judge). */
79
+ interface MemoryScanResult {
80
+ safe: boolean;
81
+ verdict: MemoryScanVerdict;
82
+ reason: string;
83
+ confidence: number;
84
+ /** Severity 1 (poisonous) → 10 (benign). LLM sets it; falls back to red=2/yellow=5/green=8 when the LLM omits the SCORE prefix or the regex pre-filter short-circuits. */
85
+ score: number;
86
+ toolCallId?: string;
87
+ }
88
+ /** Options for `scanMemory`. Passed through to `judgeAction`. */
89
+ interface MemoryScanOptions {
90
+ /** Threshold for LLM confidence to escalate a green verdict to yellow. Default: 0.6 */
91
+ threshold?: number;
92
+ /** Judge endpoint override. Same shape as ClientOpts.endpoint. */
93
+ endpoint?: string;
94
+ /** Self-hosted judge response-signing pubkey. */
95
+ verifyPubKey?: string;
96
+ /** Org name for chain resolution. */
97
+ orgName?: string;
98
+ /** Tool name for on-chain audit log. */
99
+ toolName?: string;
100
+ /** JSON-serialized tool args for on-chain audit log. */
101
+ toolArgsJson?: string;
102
+ }
71
103
  /**
72
104
  * Which Atbash chain an action runs against. `public` is the shared
73
105
  * testnet (Free plan); `private` is reserved for Private / Swarm /
@@ -118,6 +150,8 @@ interface JudgeResult {
118
150
  latencyMs: number;
119
151
  toolCallId: string;
120
152
  onChain: boolean;
153
+ /** Severity 1 (poisonous) → 10 (benign). Present on memory-scan responses; absent for regular tool-call judgments. */
154
+ score?: number;
121
155
  /**
122
156
  * Whether the org's protection mode actually acts on a HOLD/BLOCK verdict.
123
157
  * `false` in Monitor mode (verdict is logged for observation, agent is NOT
@@ -310,6 +344,8 @@ interface JudgeOptions {
310
344
  * use `judgeAction` directly without going through `auditToolCall`.
311
345
  */
312
346
  resolved?: Record<string, unknown>;
347
+ /** Alternate flow: "memory-scan" tells the dashboard to use `context` as trusted policy and skip AGT/OPA/chain writes. Set by `scanMemory`; usually not needed at the call site. */
348
+ mode?: "memory-scan";
313
349
  }
314
350
  /** Options accepted by `logToolCall`. */
315
351
  interface LogToolCallOptions {
@@ -361,8 +397,17 @@ declare class Atbash {
361
397
  static fromConfig(options?: FromConfigOptions): Atbash;
362
398
  get pubkey(): string;
363
399
  get privkey(): string;
364
- /** GET /api/ai/exists?pubkey=… — defaults to this client's pubkey. */
365
- checkAgentExists(pubkey?: string): Promise<boolean>;
400
+ /**
401
+ * `GET /api/ai/exists?pubkey=…[&network=…]` defaults to this client's
402
+ * pubkey. Pass `opts.network` when the caller already knows which
403
+ * network the agent lives on (e.g. after resolving via `orgName`) so
404
+ * the dashboard queries that chain directly instead of falling back
405
+ * across public → private, which double-round-trips and can return
406
+ * false negatives when the fallback chain client is misconfigured.
407
+ */
408
+ checkAgentExists(pubkey?: string, opts?: {
409
+ network?: Network;
410
+ }): Promise<boolean>;
366
411
  /**
367
412
  * Pre-flight `checkAgentExists`, then sign `log_tool_call` locally and
368
413
  * return the signed tx hex. The server broadcasts to chain.
@@ -526,6 +571,438 @@ declare function verifyJudgeResponseSignature(bodyBytes: Uint8Array, signatureHe
526
571
  reason?: string;
527
572
  };
528
573
 
574
+ /** Derive the 32-byte AES key from an agent's secp256k1 privkey (hex). Deterministic — same privkey always yields the same key. */
575
+ declare function deriveMemoryKey(privkey: string): Promise<Buffer>;
576
+ /** Encrypt UTF-8 plaintext. `ciphertext` has the 16-byte GCM auth tag appended, matching the SDK's on-chain byte layout. */
577
+ declare function encryptMemoryContent(plaintext: string, key: Buffer): Promise<{
578
+ ciphertext: Buffer;
579
+ nonce: Buffer;
580
+ }>;
581
+ /** Decrypt ciphertext produced by `encryptMemoryContent`. Throws on GCM tag mismatch — indicates tampered ciphertext or wrong key. */
582
+ declare function decryptMemoryContent(ciphertext: Buffer, nonce: Buffer, key: Buffer): Promise<string>;
583
+
584
+ /**
585
+ * Scan a single memory entry for poisoning.
586
+ *
587
+ * `auth` is the agent that signs the on-chain audit log for the
588
+ * LLM-judge call. If Layer 1 (regex pre-filter) returns red, Layer 2
589
+ * (LLM) is skipped.
590
+ */
591
+ declare function scanMemory(entry: MemoryEntry, auth: AgentAuth, opts?: MemoryScanOptions): Promise<MemoryScanResult>;
592
+ /**
593
+ * Scan multiple entries. Stops on the first red verdict by default —
594
+ * set `stopOnRed: false` to scan every entry regardless.
595
+ */
596
+ declare function scanMemoryBatch(entries: MemoryEntry[], auth: AgentAuth, opts?: MemoryScanOptions & {
597
+ stopOnRed?: boolean;
598
+ }): Promise<MemoryScanResult[]>;
599
+
600
+ interface CommitMemoryOptions {
601
+ /** Score in [1, 10]. Defaults to 5 (matches the Rell entity default). */
602
+ score?: number;
603
+ /** Org name — when set, the SDK resolves which chain the agent lives on. */
604
+ orgName?: string;
605
+ /** Atbash service endpoint for org→chain lookup. */
606
+ endpoint?: string;
607
+ chainOpts?: ChainOpts;
608
+ }
609
+ interface RollbackMemoryOptions {
610
+ orgName?: string;
611
+ endpoint?: string;
612
+ chainOpts?: ChainOpts;
613
+ }
614
+ /**
615
+ * Encrypt `plaintext` and commit it as a new memory version via
616
+ * `add_agent_memory`. The previous active version (if any) is
617
+ * deactivated on-chain.
618
+ *
619
+ * The caller is responsible for running `scanMemory` first when
620
+ * appropriate — this function does not gate on the verdict. The
621
+ * `score` parameter is the only metadata that flows in alongside
622
+ * the ciphertext.
623
+ */
624
+ declare function commitMemoryVersion(plaintext: string, auth: AgentAuth, opts?: CommitMemoryOptions): Promise<void>;
625
+ /**
626
+ * Decrypted memory entry returned by the read helpers.
627
+ *
628
+ * `content` is the plaintext recovered from on-chain ciphertext. If
629
+ * decryption fails (corrupted row, wrong key, etc.), `content` is
630
+ * empty and `decryptError` carries the reason — the SDK returns the
631
+ * row instead of throwing so one bad entry doesn't hide the rest.
632
+ */
633
+ interface AgentMemoryEntry {
634
+ id: number;
635
+ content: string;
636
+ decryptError?: string;
637
+ score: number;
638
+ isActive: boolean;
639
+ createdAt: number;
640
+ updatedAt: number;
641
+ }
642
+ /** Rollback event from `memory_rollback_log`. */
643
+ interface MemoryRollbackEvent {
644
+ fromId: number;
645
+ toId: number;
646
+ reason: string;
647
+ signer: string;
648
+ createdAt: number;
649
+ }
650
+ /**
651
+ * Cheap version-pointer probe. Returns just the id of the current
652
+ * active memory (or null if none). No ciphertext is transferred — the
653
+ * response is a single integer, so this is safe to call on every
654
+ * memory-read hot path. Callers that hold a decrypted local copy can
655
+ * compare against a stored pointer and only refetch the full row via
656
+ * `getActiveMemory` when the id has changed.
657
+ */
658
+ declare function getActiveMemoryId(auth: AgentAuth, chainOpts?: ChainOpts): Promise<number | null>;
659
+ /**
660
+ * Recent active memory entries — subset of active versions filtered
661
+ * by the chain's `MEMORY_RECENT_WINDOW_MS` (10 days at time of
662
+ * writing). Intended for prompt injection at agent runtime, where
663
+ * stale memory is worse than missing memory. For a time-unbounded
664
+ * view of every currently active version, use `getAllAgentMemory`.
665
+ */
666
+ declare function getActiveMemory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry[]>;
667
+ /**
668
+ * All currently-active memory entries with no time cutoff. Use this
669
+ * when you need every active version regardless of age — e.g., a
670
+ * dashboard listing, or a long-running agent whose oldest active
671
+ * versions may have fallen outside `getActiveMemory`'s recent window.
672
+ */
673
+ declare function getAllAgentMemory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry[]>;
674
+ /**
675
+ * Full version history — active + inactive, most recent first.
676
+ * Used by rollback UX to choose a target version.
677
+ */
678
+ declare function getMemoryHistory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry[]>;
679
+ /**
680
+ * Fetch a single memory entry by version id, including its current
681
+ * `is_active` state. Useful for inspecting a historical version
682
+ * before rolling back to it.
683
+ */
684
+ declare function getMemoryById(id: number, auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry>;
685
+ /**
686
+ * Audit trail of rollback events for this agent, most recent first.
687
+ */
688
+ declare function getRollbackHistory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<MemoryRollbackEvent[]>;
689
+ /**
690
+ * Roll back to a previously-committed memory version. The target
691
+ * `toId` must exist and be currently inactive. `reason` is required
692
+ * and is recorded on-chain in `memory_rollback_log`.
693
+ */
694
+ declare function rollbackMemory(toId: number, reason: string, auth: AgentAuth, opts?: RollbackMemoryOptions): Promise<void>;
695
+
696
+ /**
697
+ * Classify a plugin tool-call event as a memory write.
698
+ *
699
+ * Plugins receive `before_tool_call` events from their host runtime
700
+ * (openclaw, Claude API, MCP, etc.) with varying argument shapes. This
701
+ * module normalizes across shapes and returns a `MemoryEntry` when the
702
+ * call is writing to a memory-like path, or `null` when the SDK should
703
+ * skip the memory-scan path entirely.
704
+ *
705
+ * `event` and `ctx` are typed `unknown` so any plugin can pass its
706
+ * native hook payloads without adaptation — the classifier probes
707
+ * common key names at runtime.
708
+ */
709
+
710
+ /**
711
+ * Tool names that indicate a memory write. Lowercase — matched
712
+ * case-insensitively so both OpenClaw (lowercase) and Claude API
713
+ * family (TitleCase) hit.
714
+ */
715
+ declare const DEFAULT_MEMORY_WRITE_TOOL_NAMES: ReadonlyArray<string>;
716
+ /**
717
+ * File path substrings that indicate a memory-shaped target. Callers
718
+ * can extend or override this list via `classifyMemoryWrite` options.
719
+ */
720
+ declare const DEFAULT_MEMORY_PATH_PATTERNS: ReadonlyArray<string>;
721
+ /**
722
+ * Minimal shape of a `before_tool_call` context object across plugins.
723
+ * The classifier reads only these fields — anything else is ignored.
724
+ */
725
+ interface ClassifierToolContext {
726
+ tool?: {
727
+ name?: string;
728
+ };
729
+ toolName?: string;
730
+ name?: string;
731
+ params?: unknown;
732
+ args?: unknown;
733
+ arguments?: unknown;
734
+ }
735
+ /**
736
+ * Minimal shape of a `before_tool_call` event object across plugins.
737
+ */
738
+ interface ClassifierToolEvent {
739
+ toolName?: string;
740
+ params?: unknown;
741
+ args?: unknown;
742
+ arguments?: unknown;
743
+ }
744
+ interface ClassifyMemoryWriteOptions {
745
+ /** Override default memory-path patterns. */
746
+ patterns?: ReadonlyArray<string>;
747
+ /** Override default memory-write tool names. */
748
+ toolNames?: ReadonlyArray<string>;
749
+ }
750
+ /**
751
+ * If this tool call is writing to a memory-shaped path, return a
752
+ * `MemoryEntry` suitable for `scanMemory` / `guardMemoryWrite`.
753
+ * Otherwise return `null` — the SDK's memory path is skipped and the
754
+ * caller can fall through to a regular tool-call audit.
755
+ *
756
+ * Empty-content writes return `null`: they can't carry a poisoning
757
+ * payload, and the regular audit path still sees them.
758
+ */
759
+ declare function classifyMemoryWrite(event: unknown, ctx: unknown, opts?: ClassifyMemoryWriteOptions): MemoryEntry | null;
760
+
761
+ /**
762
+ * Plugin-agnostic memory-write guard.
763
+ *
764
+ * A single call that replaces the plugin's usual memory-write branch:
765
+ * classify → scan (Layer 1 regex + Layer 2 LLM) → gate on verdict →
766
+ * persist to chain (fire-and-forget when allowed) → return decision.
767
+ *
768
+ * Plugins call this from their `before_tool_call` hook. When it returns
769
+ * `{ handled: false }` the call wasn't a memory write and the plugin
770
+ * should fall through to its regular tool-call audit. When
771
+ * `{ handled: true }` the plugin returns `decision` directly.
772
+ */
773
+
774
+ /**
775
+ * Minimal logger accepted by `guardMemoryWrite`. Plugins pass their
776
+ * host runtime's logger (openclaw's `api.logger`, MCP's console, etc.).
777
+ * Only `info` and `warn` are used — omitted methods no-op.
778
+ */
779
+ interface GuardLogger {
780
+ info?: (message: string, meta?: unknown) => void;
781
+ warn?: (message: string, meta?: unknown) => void;
782
+ }
783
+ interface GuardMemoryWriteInput extends ClassifyMemoryWriteOptions {
784
+ /** The plugin's raw `before_tool_call` event. */
785
+ event: unknown;
786
+ /** The plugin's `before_tool_call` context. */
787
+ ctx: unknown;
788
+ /** Agent auth used to sign the scan's on-chain audit and the memory-commit tx. */
789
+ auth: AgentAuth;
790
+ /** Judge endpoint override (dev vs prod). */
791
+ endpoint?: string;
792
+ /** Self-hosted judge response-signing pubkey. */
793
+ verifyPubKey?: string;
794
+ /** Org name for chain resolution (public vs org-private chain). */
795
+ orgName?: string;
796
+ /** LLM confidence threshold for yellow escalation. Default 0.6. */
797
+ threshold?: number;
798
+ /** When false, red verdicts log but don't block. Default true. */
799
+ enforce?: boolean;
800
+ /** When true, emit a classifier-probe log line via `logger.info`. */
801
+ debug?: boolean;
802
+ /** Optional logger for debug probe + persist-failure warnings. */
803
+ logger?: GuardLogger;
804
+ }
805
+ /** Plugin-facing decision. Shape mirrors what plugins return from `before_tool_call`. */
806
+ interface GuardMemoryDecision {
807
+ allow: boolean;
808
+ block?: boolean;
809
+ reason?: string;
810
+ }
811
+ interface GuardMemoryWriteResult {
812
+ /** True when this call was a memory write and `decision` was set. False = plugin should run its regular audit. */
813
+ handled: boolean;
814
+ /** Present when handled. Plugin returns this from its hook. */
815
+ decision?: GuardMemoryDecision;
816
+ /** Present when handled and scan ran. Absent when scan threw. */
817
+ scanResult?: MemoryScanResult;
818
+ /** Present when handled. True when a chain-commit was dispatched (fire-and-forget). */
819
+ committed?: boolean;
820
+ }
821
+ /**
822
+ * Guarded memory-write flow. Returns `{ handled: false }` when the tool
823
+ * call isn't a memory write, otherwise returns a `decision` the plugin
824
+ * should return from its hook.
825
+ *
826
+ * Verdict handling:
827
+ * - `red` → not persisted to chain; decision blocks (unless `enforce: false`)
828
+ * - `yellow` → persisted with LLM score; decision allows
829
+ * - `green` → persisted with LLM score; decision allows
830
+ *
831
+ * Chain commit is fire-and-forget: network errors are logged via
832
+ * `logger.warn` but never surfaced to the caller. This mirrors the
833
+ * existing plugin behaviour — chain is for audit/recovery, not gating.
834
+ */
835
+ declare function guardMemoryWrite(input: GuardMemoryWriteInput): Promise<GuardMemoryWriteResult>;
836
+
837
+ /**
838
+ * Aligns a local `MemoryPointer` with chain's active memory version
839
+ * via a TTL-cached pointer check. Inside the TTL window: no-op.
840
+ * Past it: one cheap chain query for the current active id; only on
841
+ * mismatch does the full row get refetched and decrypted.
842
+ *
843
+ * Fail modes:
844
+ * - Chain unreachable → throws the network error verbatim; caller
845
+ * serves the local copy and retries on the next check.
846
+ * - Tampered ciphertext (GCM tag mismatch) → throws
847
+ * `MemoryIntegrityError`. Fail-closed — never silent.
848
+ */
849
+
850
+ /** Per-agent state the caller persists between sync calls. */
851
+ interface MemoryPointer {
852
+ /** Last known chain-active memory id, or null if the agent had no active memory at the last check. */
853
+ activeId: number | null;
854
+ /** Wall-clock ms of the last successful chain check. Use 0 to force a check on the next call. */
855
+ checkedAt: number;
856
+ }
857
+ interface SyncMemoryOptions {
858
+ /** Trust the pointer without touching chain for this many ms since `checkedAt`. Default 30_000. */
859
+ ttlMs?: number;
860
+ /** Skip the TTL gate and force a chain check this call. Default false. */
861
+ force?: boolean;
862
+ chainOpts?: ChainOpts;
863
+ }
864
+ /**
865
+ * `drifted: false` — pointer is still valid; caller can keep serving the local copy.
866
+ * `drifted: true` — active id changed on chain; `current` is the fresh decrypted row
867
+ * (or `null` if active memory was removed entirely).
868
+ */
869
+ type SyncMemoryResult = {
870
+ drifted: false;
871
+ pointer: MemoryPointer;
872
+ } | {
873
+ drifted: true;
874
+ current: AgentMemoryEntry | null;
875
+ pointer: MemoryPointer;
876
+ };
877
+ /** Thrown when a fetched active row fails its GCM integrity check. Poisoning signal — do not swallow. */
878
+ declare class MemoryIntegrityError extends Error {
879
+ readonly id: number;
880
+ constructor(id: number, reason: string);
881
+ }
882
+ declare function syncLocalMemory(auth: AgentAuth, pointer: MemoryPointer, opts?: SyncMemoryOptions): Promise<SyncMemoryResult>;
883
+
884
+ declare class PointerStore {
885
+ private readonly filePath;
886
+ private cache;
887
+ private loading;
888
+ constructor(filePath: string);
889
+ /** Resolves the pointer for `agentPubkeyHex`, or a zero-pointer that will force a sync on first use. */
890
+ get(agentPubkeyHex: string): Promise<MemoryPointer>;
891
+ /** Persists an updated pointer. Failures are swallowed to a logger callback (if provided) so sync never blocks the caller. */
892
+ set(agentPubkeyHex: string, pointer: MemoryPointer, onError?: (err: Error) => void): Promise<void>;
893
+ private ensureLoaded;
894
+ private loadOnce;
895
+ private persist;
896
+ }
897
+ /** Default pointer-file location — `<workspaceDir>/.atbash/memory-pointer.json`. */
898
+ declare function defaultPointerPath(workspaceDir?: string): string;
899
+
900
+ /** Small logger shape used across the memory-poisoning surface. */
901
+ interface WrappedLogger {
902
+ info(message: string, meta?: Record<string, unknown>): void;
903
+ warn(message: string, meta?: Record<string, unknown>): void;
904
+ }
905
+ interface UpstreamLogger {
906
+ info: (...args: unknown[]) => void;
907
+ warn: (...args: unknown[]) => void;
908
+ }
909
+ /** Writes are serialized via an internal promise queue so lines interleave in call-order under concurrency. */
910
+ declare function createFileLogger(filePath: string, upstream?: UpstreamLogger): WrappedLogger;
911
+ /** Default log-file location — `<workspaceDir>/.atbash/plugin.log`. */
912
+ declare function defaultPluginLogPath(workspaceDir?: string): string;
913
+
914
+ /** Dedicated memory-read tool names, matched case-insensitively. Extend via options. */
915
+ declare const DEFAULT_MEMORY_READ_TOOL_NAMES: ReadonlyArray<string>;
916
+ interface ClassifyMemoryReadOptions {
917
+ /** Tool names that always count as memory reads. Merged with defaults. */
918
+ readToolNames?: ReadonlyArray<string>;
919
+ /** Additional path substrings that mark a file as memory. Merged with defaults. */
920
+ patterns?: ReadonlyArray<string>;
921
+ /** Additional generic-read tool names whose path arg to inspect. Merged with defaults. */
922
+ genericReadToolNames?: ReadonlyArray<string>;
923
+ }
924
+ /**
925
+ * Returns `true` when this tool call is a memory read — either a
926
+ * dedicated memory-read tool from `readToolNames`, or a generic read
927
+ * tool (`read` / `read_file`) targeting a memory-shaped path.
928
+ */
929
+ declare function classifyMemoryRead(event: unknown, ctx: unknown, opts?: ClassifyMemoryReadOptions): boolean;
930
+
931
+ /** Decision the manager returns to the plugin's `before_tool_call` handler. */
932
+ interface HookDecision {
933
+ allow?: boolean;
934
+ block?: boolean;
935
+ blockReason?: string;
936
+ reason?: string;
937
+ }
938
+ interface MemoryGuardManagerOptions {
939
+ auth: AgentAuth;
940
+ /** Host workspace root (used to derive default file paths). */
941
+ workspaceDir: string;
942
+ /** Absolute MEMORY.md path. Default `<workspaceDir>/MEMORY.md`. */
943
+ memoryFilePath?: string;
944
+ /** Persistent pointer file. Default `<workspaceDir>/.atbash/memory-pointer.json`. */
945
+ pointerFilePath?: string;
946
+ /** File-backed log. Default `<workspaceDir>/.atbash/plugin.log`. */
947
+ logFilePath?: string;
948
+ /** Optional host-native logger — every event mirrors here as well. */
949
+ hostLogger?: {
950
+ info: (...args: unknown[]) => void;
951
+ warn: (...args: unknown[]) => void;
952
+ };
953
+ /** TTL for the local-sync pointer between chain checks. Default 30_000 ms. */
954
+ ttlMs?: number;
955
+ /** Block memory reads when the chain-active version's score is below this. Default 1 (never blocks). */
956
+ rollbackMinScore?: number;
957
+ /** True → return `{block:true}` on defense triggers. False → log and return `null` (audit-only). Default true. */
958
+ enforce?: boolean;
959
+ /** Host-specific tuning of what counts as a memory read. */
960
+ memoryReadClassifier?: ClassifyMemoryReadOptions;
961
+ /** Passed through to `guardMemoryWrite`. Host memory-write tool names override. */
962
+ memoryWriteToolNames?: ReadonlyArray<string>;
963
+ /** Passed through to `guardMemoryWrite` — extra memory path substrings. */
964
+ memoryPathPatterns?: ReadonlyArray<string>;
965
+ /** Passed through to `guardMemoryWrite` — judge endpoint override (defaults to userConfig / DEFAULT_ENDPOINT). */
966
+ judgeEndpoint?: string;
967
+ /** Passed through to `guardMemoryWrite` — self-hosted judge verify pubkey. */
968
+ judgeVerifyPubKey?: string;
969
+ /** Passed through — org name for chain resolution. */
970
+ orgName?: string;
971
+ /** Debug probe in `guardMemoryWrite`. */
972
+ debug?: boolean;
973
+ }
974
+ /**
975
+ * Wire-once, dispatch-many factory. Plugins call once at register(),
976
+ * then feed every `before_tool_call` through `handleBeforeToolCall`.
977
+ */
978
+ declare class MemoryGuardManager {
979
+ private readonly opts;
980
+ private readonly pointerStore;
981
+ private readonly logger;
982
+ private readonly memoryFilePath;
983
+ private readonly ttlMs;
984
+ private readonly rollbackMinScore;
985
+ private readonly enforce;
986
+ private readonly agentPubkeyHex;
987
+ constructor(opts: MemoryGuardManagerOptions);
988
+ /**
989
+ * One-shot chain probe at plugin registration. Refreshes MEMORY.md
990
+ * from chain when drifted and score passes threshold. Fire-and-forget
991
+ * — errors are logged, never thrown.
992
+ */
993
+ runBootProbe(): Promise<void>;
994
+ /**
995
+ * Returns a `HookDecision` when the event is a memory read or write
996
+ * (host returns it verbatim to its runtime). Returns `null` when the
997
+ * event isn't memory-related — host falls through to its own audit.
998
+ */
999
+ handleBeforeToolCall(event: unknown, ctx: unknown): Promise<HookDecision | null>;
1000
+ private mapGuardResult;
1001
+ private handleMemoryRead;
1002
+ private writeMemoryAtomic;
1003
+ }
1004
+ declare function createMemoryGuardManager(opts: MemoryGuardManagerOptions): MemoryGuardManager;
1005
+
529
1006
  /**
530
1007
  * Atbash SDK Telemetry — OpenTelemetry metrics for usage tracking.
531
1008
  *
@@ -581,4 +1058,4 @@ declare function containsSecret(text: string): boolean;
581
1058
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
582
1059
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
583
1060
 
584
- export { type ActionType, type AgentAuth, type AgentPolicy, type AnomalySeverity, type AnomalyType, Atbash, AtbashAPIError, type AtbashLogger, type AtbashOptions, type AtbashUserConfig, type ChainOpts, type ClientSource, DEFAULT_BLOCKCHAIN_RID, DEFAULT_CHROMIA_NODE_URLS, DEFAULT_ENDPOINT, type Decision, type DecisionVerdict, type FromConfigOptions, type HeldAction, type HeldActionReview, type JudgeEndpointConfig, type JudgeOptions, type JudgeResult, type JudgmentState, type JudgmentStatus, type KeyPair, type LogToolCallOptions, type LogToolCallResult, type MemoryAnomaly, type MemoryDiffResult, type MemoryEntry, type MemorySnapshot, type ModifiedEntry, type Network, type OrgSubscription, type Provider, type PubkeyValue, type RedactResult, type SecretKind, type SecretMatch, SignatureVerificationError, type Subscription, type TelemetryConfig, type TierInfo, type ToolCallFull, type ToolCallInput, type ToolCallRecord, type ValidatedEndpoint, type Verdict, containsEvasionCharacters, containsSecret, createMemorySnapshot, derivePublicKey, diffMemorySnapshots, flushTelemetry, generateKeypair, getConfigDir, getConfigPath, isValidPrivateKey, loadAgent, loadAgentFromFile, loadUserConfig, normalizeForMatching, normalizeStatus, normalizeVerdict, pubkeyToHex, recordCall, recordDuration, redactJsonStrings, redactSecrets, resolve, resolveKeyPath, saveUserConfig, setupTelemetry, shutdownTelemetry, signJudgeAction, signLogToolCall, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };
1061
+ export { type ActionType, type AgentAuth, type AgentMemoryEntry, type AgentPolicy, type AnomalySeverity, type AnomalyType, Atbash, AtbashAPIError, type AtbashLogger, type AtbashOptions, type AtbashUserConfig, type ChainOpts, type ClassifierToolContext, type ClassifierToolEvent, type ClassifyMemoryReadOptions, type ClassifyMemoryWriteOptions, type ClientSource, type CommitMemoryOptions, DEFAULT_BLOCKCHAIN_RID, DEFAULT_CHROMIA_NODE_URLS, DEFAULT_ENDPOINT, DEFAULT_MEMORY_PATH_PATTERNS, DEFAULT_MEMORY_READ_TOOL_NAMES, DEFAULT_MEMORY_WRITE_TOOL_NAMES, type Decision, type DecisionVerdict, type EncryptedMemory, type FromConfigOptions, type GuardLogger, type GuardMemoryDecision, type GuardMemoryWriteInput, type GuardMemoryWriteResult, type HeldAction, type HeldActionReview, type HookDecision, type JudgeEndpointConfig, type JudgeOptions, type JudgeResult, type JudgmentState, type JudgmentStatus, type KeyPair, type LogToolCallOptions, type LogToolCallResult, type MemoryAnomaly, type MemoryDiffResult, type MemoryEntry, MemoryGuardManager, type MemoryGuardManagerOptions, MemoryIntegrityError, type MemoryPointer, type MemoryRollbackEvent, type MemoryScanOptions, type MemoryScanResult, type MemoryScanVerdict, type MemorySnapshot, type ModifiedEntry, type Network, type OrgSubscription, PointerStore, type Provider, type PubkeyValue, type RedactResult, type RollbackMemoryOptions, type SecretKind, type SecretMatch, SignatureVerificationError, type Subscription, type SyncMemoryOptions, type SyncMemoryResult, type TelemetryConfig, type TierInfo, type ToolCallFull, type ToolCallInput, type ToolCallRecord, type ValidatedEndpoint, type Verdict, type WrappedLogger, classifyMemoryRead, classifyMemoryWrite, commitMemoryVersion, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptMemoryContent, flushTelemetry, generateKeypair, getActiveMemory, getActiveMemoryId, getAllAgentMemory, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRollbackHistory, guardMemoryWrite, isValidPrivateKey, loadAgent, loadAgentFromFile, loadUserConfig, normalizeForMatching, normalizeStatus, normalizeVerdict, pubkeyToHex, recordCall, recordDuration, redactJsonStrings, redactSecrets, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };