@atbash/sdk 0.10.7-dev.0 → 0.10.10-dev.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.
@@ -430,6 +430,16 @@ declare class Atbash {
430
430
  * calls don't re-hit the dashboard. Cleared by `clearChainCache()`.
431
431
  */
432
432
  private readonly _chainCache;
433
+ /**
434
+ * Short-TTL cache for `/api/ai/exists`. The `registered` field is
435
+ * monotonic (once true, stays true), so most calls in a burst re-fetch
436
+ * data that hasn't changed. The `org_encryption_pubkey` field CAN change
437
+ * — an org toggling encryption mid-session — so the TTL is deliberately
438
+ * short (see `AGENT_EXISTS_TTL_MS`). Keyed by (pubkey, network) so
439
+ * cross-agent / cross-network calls don't collide.
440
+ */
441
+ private _agentExistsCache;
442
+ private static readonly AGENT_EXISTS_TTL_MS;
433
443
  /**
434
444
  * Cached bearer token for risk-engine / insurance read calls. Built
435
445
  * lazily as a signed `log_tool_call` tx and refreshed every 4 min so
@@ -547,6 +557,8 @@ declare class Atbash {
547
557
  private resolveChainFromMap;
548
558
  /** Drop any cached chain resolutions. Useful in tests. */
549
559
  clearChainCache(): void;
560
+ /** Drop the short-TTL `/api/ai/exists` cache. Useful in tests. */
561
+ clearAgentExistsCache(): void;
550
562
  /**
551
563
  * Wrap an SDK method body in telemetry — records the call at start
552
564
  * and a success/error duration at end. Re-throws on failure so the
@@ -576,7 +588,13 @@ declare class Atbash {
576
588
  private raiseIfError;
577
589
  /** Wrap a failed HTTP *response* (non-2xx / non-200) as an AtbashAPIError. */
578
590
  private httpError;
579
- /** Wrap a *transport* failure (fetch threw, no response) as an AtbashAPIError. */
591
+ /**
592
+ * Wrap a transport failure (fetch threw, no response) as an AtbashAPIError.
593
+ *
594
+ * `HttpTransportError.kind` names the cause; the message is already
595
+ * human-readable. `debug` echoes the original exception so operators can
596
+ * cross-reference with node / undici logs when a class doesn't match.
597
+ */
580
598
  private transportError;
581
599
  private json;
582
600
  static generateKeypair(): KeyPair;
@@ -602,6 +620,43 @@ declare class SignatureVerificationError extends Error {
602
620
  constructor(message: string);
603
621
  }
604
622
 
623
+ /**
624
+ * Thin typed fetch wrapper.
625
+ *
626
+ * openapi-typescript emits types only (no runtime client), so this is the
627
+ * single hand-written transport — generic `get`/`post` over global `fetch`
628
+ * with a per-request timeout. The endpoint-specific request/response *shapes*
629
+ * are pulled from the generated `schema.ts` at the call sites in client.ts, so
630
+ * the wire contract still lives in spec/openapi.yaml. Methods return the raw
631
+ * `Response` so the caller can read the exact bytes the server signed before
632
+ * any decode (judge signature verification) — mirroring the Python surface's
633
+ * use of raw httpx (DECISIONS 2026-05-22).
634
+ */
635
+ type QueryValue = string | number | boolean | undefined | null;
636
+ declare class HttpClient {
637
+ readonly baseUrl: string;
638
+ readonly timeoutMs: number;
639
+ constructor(baseUrl: string, timeoutMs: number);
640
+ buildUrl(path: string, query?: Record<string, QueryValue>): string;
641
+ get(path: string, query?: Record<string, QueryValue>, headers?: Record<string, string>): Promise<Response>;
642
+ post(path: string, body: unknown, headers?: Record<string, string>): Promise<Response>;
643
+ private fetch;
644
+ }
645
+ /**
646
+ * A transport failure the SDK can act on. Every real cause the platform surfaces
647
+ * lands as one of these — the message names the cause in plain language so a
648
+ * plugin can show it to a user without decoding httpx / fetch internals.
649
+ *
650
+ * `cause` preserves the original error for debug logging; consumers that want
651
+ * the raw exception (e.g. tests) read it there.
652
+ */
653
+ declare class HttpTransportError extends Error {
654
+ readonly kind: "timeout" | "aborted" | "dns" | "connect_refused" | "connection_reset" | "unknown";
655
+ constructor(kind: HttpTransportError["kind"], message: string, options?: {
656
+ cause?: unknown;
657
+ });
658
+ }
659
+
605
660
  /** Normalize wire shapes (verdict casing, status, pubkey) to canonical forms. */
606
661
 
607
662
  declare function normalizeVerdict(raw: unknown): Verdict;
@@ -850,19 +905,6 @@ interface ClassifyMemoryWriteOptions {
850
905
  */
851
906
  declare function classifyMemoryWrite(event: unknown, ctx: unknown, opts?: ClassifyMemoryWriteOptions): MemoryEntry | null;
852
907
 
853
- /**
854
- * Plugin-agnostic memory-write guard.
855
- *
856
- * A single call that replaces the plugin's usual memory-write branch:
857
- * classify → scan (Layer 1 regex + Layer 2 LLM) → gate on verdict →
858
- * persist to chain (fire-and-forget when allowed) → return decision.
859
- *
860
- * Plugins call this from their `before_tool_call` hook. When it returns
861
- * `{ handled: false }` the call wasn't a memory write and the plugin
862
- * should fall through to its regular tool-call audit. When
863
- * `{ handled: true }` the plugin returns `decision` directly.
864
- */
865
-
866
908
  /**
867
909
  * Minimal logger accepted by `guardMemoryWrite`. Plugins pass their
868
910
  * host runtime's logger (openclaw's `api.logger`, MCP's console, etc.).
@@ -893,6 +935,8 @@ interface GuardMemoryWriteInput extends ClassifyMemoryWriteOptions {
893
935
  debug?: boolean;
894
936
  /** Optional logger for debug probe + persist-failure warnings. */
895
937
  logger?: GuardLogger;
938
+ /** Absolute path of the agent's managed memory file. Required for chain commits — omitted skips them. */
939
+ memoryFilePath?: string;
896
940
  }
897
941
  /** Plugin-facing decision. Shape mirrors what plugins return from `before_tool_call`. */
898
942
  interface GuardMemoryDecision {
@@ -957,12 +1001,19 @@ interface SyncMemoryOptions {
957
1001
  * `drifted: false` — pointer is still valid; caller can keep serving the local copy.
958
1002
  * `drifted: true` — active id changed on chain; `current` is the fresh decrypted row
959
1003
  * (or `null` if active memory was removed entirely).
1004
+ *
1005
+ * `checked` — whether this call actually queried chain. `false` means the TTL
1006
+ * window was still open and the pointer was trusted without contacting chain, so
1007
+ * `drifted: false` carries no evidence about the current state. Callers that
1008
+ * vouch for content to a third party must not treat an unchecked result as proof.
960
1009
  */
961
1010
  type SyncMemoryResult = {
962
1011
  drifted: false;
1012
+ checked: boolean;
963
1013
  pointer: MemoryPointer;
964
1014
  } | {
965
1015
  drifted: true;
1016
+ checked: true;
966
1017
  current: AgentMemoryEntry | null;
967
1018
  pointer: MemoryPointer;
968
1019
  };
@@ -1024,12 +1075,42 @@ interface ClassifyMemoryReadOptions {
1024
1075
  */
1025
1076
  declare function classifyMemoryRead(event: unknown, ctx: unknown, opts?: ClassifyMemoryReadOptions): boolean;
1026
1077
 
1027
- /** Decision the manager returns to the plugin's `before_tool_call` handler. */
1078
+ /**
1079
+ * Decision the manager returns to the plugin's `before_tool_call` handler.
1080
+ *
1081
+ * `allow: true` alone is NOT evidence that anything was checked. Read `audited`
1082
+ * to tell the two apart, and route un-audited calls to your own judge — see the
1083
+ * field docs below.
1084
+ */
1028
1085
  interface HookDecision {
1029
1086
  allow?: boolean;
1030
1087
  block?: boolean;
1031
1088
  blockReason?: string;
1032
1089
  reason?: string;
1090
+ /**
1091
+ * Whether the guard reached an enforcement decision about *this* call.
1092
+ *
1093
+ * Note this describes whether the guard **decided**, not whether it allowed.
1094
+ * Every `block` is `audited: true` — a blocked call is the most thoroughly
1095
+ * checked outcome the guard produces (a red scan, a ciphertext integrity
1096
+ * failure, a rolled-back version), and a host must never re-judge its way past
1097
+ * one.
1098
+ *
1099
+ * Absent or false means the guard reached no decision — it was inside its cache
1100
+ * window, chain was unreachable, the scan never ran, the file it can vouch for
1101
+ * is not the file being read, or it is in observe mode. Those calls are
1102
+ * unaudited: fall through to your own judge exactly as for a `null` return.
1103
+ *
1104
+ * So the host rule is:
1105
+ * `if (d.block) deny; else if (d.audited) allow; else judge it yourself;`
1106
+ *
1107
+ * Treating a bare `allow: true` as a completed audit is what this field exists
1108
+ * to prevent. A host that ignores it and returns the decision verbatim will
1109
+ * execute unaudited tool calls.
1110
+ */
1111
+ audited?: boolean;
1112
+ /** Scan verdict when one was produced (`green` | `yellow` | `red`). Absent when no scan ran. */
1113
+ verdict?: string;
1033
1114
  }
1034
1115
  interface MemoryGuardManagerOptions {
1035
1116
  auth: AgentAuth;
@@ -1052,6 +1133,13 @@ interface MemoryGuardManagerOptions {
1052
1133
  rollbackMinScore?: number;
1053
1134
  /** True → return `{block:true}` on defense triggers. False → log and return `null` (audit-only). Default true. */
1054
1135
  enforce?: boolean;
1136
+ /**
1137
+ * Chain targeting for the pointer sync (network, blockchainRid, nodeUrls).
1138
+ * Defaults to the SDK's configured chain. Without this the manager could only
1139
+ * ever talk to the default chain, which left the whole memory-read path
1140
+ * untestable — `syncLocalMemory` already accepted these options.
1141
+ */
1142
+ chainOpts?: ChainOpts;
1055
1143
  /** Host-specific tuning of what counts as a memory read. */
1056
1144
  memoryReadClassifier?: ClassifyMemoryReadOptions;
1057
1145
  /** Passed through to `guardMemoryWrite`. Host memory-write tool names override. */
@@ -1088,12 +1176,33 @@ declare class MemoryGuardManager {
1088
1176
  */
1089
1177
  runBootProbe(): Promise<void>;
1090
1178
  /**
1091
- * Returns a `HookDecision` when the event is a memory read or write
1092
- * (host returns it verbatim to its runtime). Returns `null` when the
1093
- * event isn't memory-related — host falls through to its own audit.
1179
+ * Returns a `HookDecision` when the guard reached a decision about this event.
1180
+ * Returns `null` when it did not — either the event isn't memory-related, or it
1181
+ * is but the guard could not check it. In both cases the host falls through to
1182
+ * its own audit.
1183
+ *
1184
+ * A returned decision carries `audited` (see `HookDecision`). Only
1185
+ * `{ allow: true, audited: true }` means "checked and cleared"; anything else
1186
+ * that allows is a call the host still needs to judge.
1094
1187
  */
1095
1188
  handleBeforeToolCall(event: unknown, ctx: unknown): Promise<HookDecision | null>;
1096
1189
  private mapGuardResult;
1190
+ /**
1191
+ * Whether the pointer state this manager tracks actually describes the file
1192
+ * this call is about to read.
1193
+ *
1194
+ * The classifier fires on nine patterns — including the bare tokens
1195
+ * `"memory/"`, `"CLAUDE.md"` and `"AGENTS.md"` — but the sync path only ever
1196
+ * reads, refreshes, or vouches for `this.memoryFilePath`. Without this check a
1197
+ * read of `/repo/CLAUDE.md` (or any path merely containing `memory/`) would
1198
+ * receive an `audited: true` for a file the guard never opened.
1199
+ *
1200
+ * Conservative on purpose: every path-shaped value found must resolve to the
1201
+ * managed file. If none is found, or any one differs, the answer is no. That
1202
+ * also covers events carrying two different path keys, where the classifier
1203
+ * and the host could otherwise disagree about which one is authoritative.
1204
+ */
1205
+ private vouchesForTarget;
1097
1206
  private handleMemoryRead;
1098
1207
  private writeMemoryAtomic;
1099
1208
  }
@@ -1237,4 +1346,4 @@ declare function containsSecret(text: string): boolean;
1237
1346
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
1238
1347
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
1239
1348
 
1240
- export { type ActionType, type AgentAuth, type AgentMemoryEntry, type AgentPolicy, type AnomalySeverity, type AnomalyType, Atbash, AtbashAPIError, type AtbashLogger, type AtbashOptions, type AtbashUserConfig, BOOT_SYNC_HINT, 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, EciesDomain, type EncryptedMemory, type Envelope, 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, KEY_FILENAMES, 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, bootSyncFailureLine, buildAllowedJudgeHosts, chooseKeyPath, claimHashHex, classifyMemoryRead, classifyMemoryWrite, columnAad, commitMemoryVersion, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, flushTelemetry, generateKeypair, getActiveMemory, getActiveMemoryId, getAllAgentMemory, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRollbackHistory, guardMemoryWrite, isEnvelope, isValidPrivateKey, keyFingerprintOf, keyPathCandidates, loadAgent, loadAgentFromFile, loadUserConfig, normalizeActionForHash, normalizeForMatching, normalizeStatus, normalizeVerdict, packEnvelope, parseEnvelope, pubkeyToHex, recordCall, recordDuration, redactJsonStrings, redactSecrets, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signEncryptedToolCall, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };
1349
+ export { type ActionType, type AgentAuth, type AgentMemoryEntry, type AgentPolicy, type AnomalySeverity, type AnomalyType, Atbash, AtbashAPIError, type AtbashLogger, type AtbashOptions, type AtbashUserConfig, BOOT_SYNC_HINT, 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, EciesDomain, type EncryptedMemory, type Envelope, type FromConfigOptions, type GuardLogger, type GuardMemoryDecision, type GuardMemoryWriteInput, type GuardMemoryWriteResult, type HeldAction, type HeldActionReview, type HookDecision, HttpClient, HttpTransportError, type JudgeEndpointConfig, type JudgeOptions, type JudgeResult, type JudgmentState, type JudgmentStatus, KEY_FILENAMES, 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, bootSyncFailureLine, buildAllowedJudgeHosts, chooseKeyPath, claimHashHex, classifyMemoryRead, classifyMemoryWrite, columnAad, commitMemoryVersion, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, flushTelemetry, generateKeypair, getActiveMemory, getActiveMemoryId, getAllAgentMemory, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRollbackHistory, guardMemoryWrite, isEnvelope, isValidPrivateKey, keyFingerprintOf, keyPathCandidates, loadAgent, loadAgentFromFile, loadUserConfig, normalizeActionForHash, normalizeForMatching, normalizeStatus, normalizeVerdict, packEnvelope, parseEnvelope, pubkeyToHex, recordCall, recordDuration, redactJsonStrings, redactSecrets, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signEncryptedToolCall, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };