@atbash/sdk 0.5.8-dev.0 → 0.6.0

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.
@@ -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 /
@@ -310,6 +342,8 @@ interface JudgeOptions {
310
342
  * use `judgeAction` directly without going through `auditToolCall`.
311
343
  */
312
344
  resolved?: Record<string, unknown>;
345
+ /** 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. */
346
+ mode?: "memory-scan";
313
347
  }
314
348
  /** Options accepted by `logToolCall`. */
315
349
  interface LogToolCallOptions {
@@ -526,6 +560,271 @@ declare function verifyJudgeResponseSignature(bodyBytes: Uint8Array, signatureHe
526
560
  reason?: string;
527
561
  };
528
562
 
563
+ /**
564
+ * Derive a 32-byte AES key from the agent's secp256k1 privkey (hex).
565
+ * Deterministic — same privkey always produces the same key, so the
566
+ * SDK can encrypt now and decrypt later without storing the key.
567
+ */
568
+ declare function deriveMemoryKey(privkey: string): Buffer;
569
+ /**
570
+ * Encrypt UTF-8 plaintext. Returns `{ ciphertext, nonce }` — ciphertext
571
+ * has the 16-byte GCM auth tag appended, matching the TS SDK's on-chain
572
+ * byte layout for cross-language parity.
573
+ */
574
+ declare function encryptMemoryContent(plaintext: string, key: Buffer): {
575
+ ciphertext: Buffer;
576
+ nonce: Buffer;
577
+ };
578
+ /**
579
+ * Decrypt ciphertext produced by `encryptMemoryContent`. Throws when
580
+ * the GCM auth tag doesn't match (tamper detection / wrong key).
581
+ */
582
+ declare function decryptMemoryContent(ciphertext: Buffer, nonce: Buffer, key: Buffer): 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
+ * Recent active memory entries — subset of active versions filtered
652
+ * by the chain's `MEMORY_RECENT_WINDOW_MS` (10 days at time of
653
+ * writing). Intended for prompt injection at agent runtime, where
654
+ * stale memory is worse than missing memory. For a time-unbounded
655
+ * view of every currently active version, use `getAllAgentMemory`.
656
+ */
657
+ declare function getActiveMemory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry[]>;
658
+ /**
659
+ * All currently-active memory entries with no time cutoff. Use this
660
+ * when you need every active version regardless of age — e.g., a
661
+ * dashboard listing, or a long-running agent whose oldest active
662
+ * versions may have fallen outside `getActiveMemory`'s recent window.
663
+ */
664
+ declare function getAllAgentMemory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry[]>;
665
+ /**
666
+ * Full version history — active + inactive, most recent first.
667
+ * Used by rollback UX to choose a target version.
668
+ */
669
+ declare function getMemoryHistory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry[]>;
670
+ /**
671
+ * Fetch a single memory entry by version id, including its current
672
+ * `is_active` state. Useful for inspecting a historical version
673
+ * before rolling back to it.
674
+ */
675
+ declare function getMemoryById(id: number, auth: AgentAuth, chainOpts?: ChainOpts): Promise<AgentMemoryEntry>;
676
+ /**
677
+ * Audit trail of rollback events for this agent, most recent first.
678
+ */
679
+ declare function getRollbackHistory(auth: AgentAuth, chainOpts?: ChainOpts): Promise<MemoryRollbackEvent[]>;
680
+ /**
681
+ * Roll back to a previously-committed memory version. The target
682
+ * `toId` must exist and be currently inactive. `reason` is required
683
+ * and is recorded on-chain in `memory_rollback_log`.
684
+ */
685
+ declare function rollbackMemory(toId: number, reason: string, auth: AgentAuth, opts?: RollbackMemoryOptions): Promise<void>;
686
+
687
+ /**
688
+ * Classify a plugin tool-call event as a memory write.
689
+ *
690
+ * Plugins receive `before_tool_call` events from their host runtime
691
+ * (openclaw, Claude API, MCP, etc.) with varying argument shapes. This
692
+ * module normalizes across shapes and returns a `MemoryEntry` when the
693
+ * call is writing to a memory-like path, or `null` when the SDK should
694
+ * skip the memory-scan path entirely.
695
+ *
696
+ * `event` and `ctx` are typed `unknown` so any plugin can pass its
697
+ * native hook payloads without adaptation — the classifier probes
698
+ * common key names at runtime.
699
+ */
700
+
701
+ /**
702
+ * Tool names that indicate a memory write. Lowercase — matched
703
+ * case-insensitively so both OpenClaw (lowercase) and Claude API
704
+ * family (TitleCase) hit.
705
+ */
706
+ declare const DEFAULT_MEMORY_WRITE_TOOL_NAMES: ReadonlyArray<string>;
707
+ /**
708
+ * File path substrings that indicate a memory-shaped target. Callers
709
+ * can extend or override this list via `classifyMemoryWrite` options.
710
+ */
711
+ declare const DEFAULT_MEMORY_PATH_PATTERNS: ReadonlyArray<string>;
712
+ /**
713
+ * Minimal shape of a `before_tool_call` context object across plugins.
714
+ * The classifier reads only these fields — anything else is ignored.
715
+ */
716
+ interface ClassifierToolContext {
717
+ tool?: {
718
+ name?: string;
719
+ };
720
+ toolName?: string;
721
+ name?: string;
722
+ params?: unknown;
723
+ args?: unknown;
724
+ arguments?: unknown;
725
+ }
726
+ /**
727
+ * Minimal shape of a `before_tool_call` event object across plugins.
728
+ */
729
+ interface ClassifierToolEvent {
730
+ toolName?: string;
731
+ params?: unknown;
732
+ args?: unknown;
733
+ arguments?: unknown;
734
+ }
735
+ interface ClassifyMemoryWriteOptions {
736
+ /** Override default memory-path patterns. */
737
+ patterns?: ReadonlyArray<string>;
738
+ /** Override default memory-write tool names. */
739
+ toolNames?: ReadonlyArray<string>;
740
+ }
741
+ /**
742
+ * If this tool call is writing to a memory-shaped path, return a
743
+ * `MemoryEntry` suitable for `scanMemory` / `guardMemoryWrite`.
744
+ * Otherwise return `null` — the SDK's memory path is skipped and the
745
+ * caller can fall through to a regular tool-call audit.
746
+ *
747
+ * Empty-content writes return `null`: they can't carry a poisoning
748
+ * payload, and the regular audit path still sees them.
749
+ */
750
+ declare function classifyMemoryWrite(event: unknown, ctx: unknown, opts?: ClassifyMemoryWriteOptions): MemoryEntry | null;
751
+
752
+ /**
753
+ * Plugin-agnostic memory-write guard.
754
+ *
755
+ * A single call that replaces the plugin's usual memory-write branch:
756
+ * classify → scan (Layer 1 regex + Layer 2 LLM) → gate on verdict →
757
+ * persist to chain (fire-and-forget when allowed) → return decision.
758
+ *
759
+ * Plugins call this from their `before_tool_call` hook. When it returns
760
+ * `{ handled: false }` the call wasn't a memory write and the plugin
761
+ * should fall through to its regular tool-call audit. When
762
+ * `{ handled: true }` the plugin returns `decision` directly.
763
+ */
764
+
765
+ /**
766
+ * Minimal logger accepted by `guardMemoryWrite`. Plugins pass their
767
+ * host runtime's logger (openclaw's `api.logger`, MCP's console, etc.).
768
+ * Only `info` and `warn` are used — omitted methods no-op.
769
+ */
770
+ interface GuardLogger {
771
+ info?: (message: string, meta?: unknown) => void;
772
+ warn?: (message: string, meta?: unknown) => void;
773
+ }
774
+ interface GuardMemoryWriteInput extends ClassifyMemoryWriteOptions {
775
+ /** The plugin's raw `before_tool_call` event. */
776
+ event: unknown;
777
+ /** The plugin's `before_tool_call` context. */
778
+ ctx: unknown;
779
+ /** Agent auth used to sign the scan's on-chain audit and the memory-commit tx. */
780
+ auth: AgentAuth;
781
+ /** Judge endpoint override (dev vs prod). */
782
+ endpoint?: string;
783
+ /** Self-hosted judge response-signing pubkey. */
784
+ verifyPubKey?: string;
785
+ /** Org name for chain resolution (public vs org-private chain). */
786
+ orgName?: string;
787
+ /** LLM confidence threshold for yellow escalation. Default 0.6. */
788
+ threshold?: number;
789
+ /** When false, red verdicts log but don't block. Default true. */
790
+ enforce?: boolean;
791
+ /** When true, emit a classifier-probe log line via `logger.info`. */
792
+ debug?: boolean;
793
+ /** Optional logger for debug probe + persist-failure warnings. */
794
+ logger?: GuardLogger;
795
+ }
796
+ /** Plugin-facing decision. Shape mirrors what plugins return from `before_tool_call`. */
797
+ interface GuardMemoryDecision {
798
+ allow: boolean;
799
+ block?: boolean;
800
+ reason?: string;
801
+ }
802
+ interface GuardMemoryWriteResult {
803
+ /** True when this call was a memory write and `decision` was set. False = plugin should run its regular audit. */
804
+ handled: boolean;
805
+ /** Present when handled. Plugin returns this from its hook. */
806
+ decision?: GuardMemoryDecision;
807
+ /** Present when handled and scan ran. Absent when scan threw. */
808
+ scanResult?: MemoryScanResult;
809
+ /** Present when handled. True when a chain-commit was dispatched (fire-and-forget). */
810
+ committed?: boolean;
811
+ }
812
+ /**
813
+ * Guarded memory-write flow. Returns `{ handled: false }` when the tool
814
+ * call isn't a memory write, otherwise returns a `decision` the plugin
815
+ * should return from its hook.
816
+ *
817
+ * Verdict handling:
818
+ * - `red` → not persisted to chain; decision blocks (unless `enforce: false`)
819
+ * - `yellow` → persisted with LLM score; decision allows
820
+ * - `green` → persisted with LLM score; decision allows
821
+ *
822
+ * Chain commit is fire-and-forget: network errors are logged via
823
+ * `logger.warn` but never surfaced to the caller. This mirrors the
824
+ * existing plugin behaviour — chain is for audit/recovery, not gating.
825
+ */
826
+ declare function guardMemoryWrite(input: GuardMemoryWriteInput): Promise<GuardMemoryWriteResult>;
827
+
529
828
  /**
530
829
  * Atbash SDK Telemetry — OpenTelemetry metrics for usage tracking.
531
830
  *
@@ -581,4 +880,4 @@ declare function containsSecret(text: string): boolean;
581
880
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
582
881
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
583
882
 
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 };
883
+ 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 ClassifyMemoryWriteOptions, type ClientSource, type CommitMemoryOptions, DEFAULT_BLOCKCHAIN_RID, DEFAULT_CHROMIA_NODE_URLS, DEFAULT_ENDPOINT, DEFAULT_MEMORY_PATH_PATTERNS, 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 JudgeEndpointConfig, type JudgeOptions, type JudgeResult, type JudgmentState, type JudgmentStatus, type KeyPair, type LogToolCallOptions, type LogToolCallResult, type MemoryAnomaly, type MemoryDiffResult, type MemoryEntry, type MemoryRollbackEvent, type MemoryScanOptions, type MemoryScanResult, type MemoryScanVerdict, type MemorySnapshot, type ModifiedEntry, type Network, type OrgSubscription, type Provider, type PubkeyValue, type RedactResult, type RollbackMemoryOptions, type SecretKind, type SecretMatch, SignatureVerificationError, type Subscription, type TelemetryConfig, type TierInfo, type ToolCallFull, type ToolCallInput, type ToolCallRecord, type ValidatedEndpoint, type Verdict, classifyMemoryWrite, commitMemoryVersion, containsEvasionCharacters, containsSecret, createMemorySnapshot, decryptMemoryContent, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptMemoryContent, flushTelemetry, generateKeypair, getActiveMemory, 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, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };