@atbash/sdk 0.10.9-dev.0 → 0.10.11-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.
package/README.md CHANGED
@@ -111,8 +111,8 @@ Read-only methods that read from the Chromia blockchain and dashboard.
111
111
  | `getToolCallCount()` | Total number of tool calls on-chain |
112
112
  | `getToolCallFull(toolCallId)` | Full details of a single tool call |
113
113
  | `getOrgTierInfo(orgName)` | Check an org's tier and whether verdicts are enabled |
114
- | `getAgentDetail(pubkey)` | Get agent metadata (org, status, creation date) |
115
- | `getAgentPolicy(pubkey)` | Check the agent's policy pack and jail status |
114
+ | `getAgentDetail(pubkey, options?)` | Get agent metadata (org, status, creation date) |
115
+ | `getAgentPolicy(pubkey, options?)` | Check the agent's policy pack and jail status |
116
116
  | `getPendingHeldActions(orgName, maxCount)` | List actions waiting for operator approval |
117
117
  | `getHeldActionReviews(orgName, maxCount)` | List completed operator reviews |
118
118
  | `getSafetyStats()` | Chain-wide safety statistics |
@@ -148,6 +148,16 @@ const atbash = Atbash.fromConfig(); // reads env + config file
148
148
 
149
149
  Persistent config helpers: `saveUserConfig(config)`, `loadUserConfig()`, `resolve(key, flagValue?)`, `getConfigPath()`.
150
150
 
151
+ Agent policy and detail reads can resolve the organization's active network, or
152
+ accept an explicit network override:
153
+
154
+ ```ts
155
+ await atbash.getAgentPolicy(atbash.pubkey, { orgName: "acme" });
156
+ await atbash.getAgentDetail(atbash.pubkey, {
157
+ chainOpts: { network: "private" },
158
+ });
159
+ ```
160
+
151
161
  ## Error handling
152
162
 
153
163
  The SDK throws standard `Error` objects. Known failure modes are enriched with a pointer to the dashboard page that fixes them:
@@ -274,6 +274,13 @@ interface AgentPolicy {
274
274
  isCustom: boolean;
275
275
  defaultPolicy: string;
276
276
  }
277
+ /** Options for agent metadata and policy lookups. */
278
+ interface AgentLookupOptions {
279
+ /** Resolve the agent's network from this organization's active network. */
280
+ orgName?: string;
281
+ /** Explicit per-call chain override. `network` selects the dashboard chain. */
282
+ chainOpts?: ChainOpts;
283
+ }
277
284
  /** Optional structured logger. */
278
285
  interface AtbashLogger {
279
286
  info?(...args: unknown[]): void;
@@ -430,6 +437,16 @@ declare class Atbash {
430
437
  * calls don't re-hit the dashboard. Cleared by `clearChainCache()`.
431
438
  */
432
439
  private readonly _chainCache;
440
+ /**
441
+ * Short-TTL cache for `/api/ai/exists`. The `registered` field is
442
+ * monotonic (once true, stays true), so most calls in a burst re-fetch
443
+ * data that hasn't changed. The `org_encryption_pubkey` field CAN change
444
+ * — an org toggling encryption mid-session — so the TTL is deliberately
445
+ * short (see `AGENT_EXISTS_TTL_MS`). Keyed by (pubkey, network) so
446
+ * cross-agent / cross-network calls don't collide.
447
+ */
448
+ private _agentExistsCache;
449
+ private static readonly AGENT_EXISTS_TTL_MS;
433
450
  /**
434
451
  * Cached bearer token for risk-engine / insurance read calls. Built
435
452
  * lazily as a signed `log_tool_call` tx and refreshed every 4 min so
@@ -511,8 +528,8 @@ declare class Atbash {
511
528
  getOrgTierInfo(orgName: string): Promise<TierInfo | null>;
512
529
  getPendingHeldActions(orgName: string, maxCount: number): Promise<HeldAction[]>;
513
530
  getHeldActionReviews(orgName: string, maxCount: number): Promise<HeldActionReview[]>;
514
- getAgentDetail(agentPubkey: string): Promise<Record<string, unknown>>;
515
- getAgentPolicy(agentPubkey: string): Promise<AgentPolicy>;
531
+ getAgentDetail(agentPubkey: string, options?: AgentLookupOptions): Promise<Record<string, unknown>>;
532
+ getAgentPolicy(agentPubkey: string, options?: AgentLookupOptions): Promise<AgentPolicy>;
516
533
  getSafetyStats(): Promise<Record<string, unknown>>;
517
534
  /**
518
535
  * Org's subscription on a specific chain. The `network` arg selects
@@ -547,6 +564,8 @@ declare class Atbash {
547
564
  private resolveChainFromMap;
548
565
  /** Drop any cached chain resolutions. Useful in tests. */
549
566
  clearChainCache(): void;
567
+ /** Drop the short-TTL `/api/ai/exists` cache. Useful in tests. */
568
+ clearAgentExistsCache(): void;
550
569
  /**
551
570
  * Wrap an SDK method body in telemetry — records the call at start
552
571
  * and a success/error duration at end. Re-throws on failure so the
@@ -561,6 +580,14 @@ declare class Atbash {
561
580
  * chains; otherwise the client's default.
562
581
  */
563
582
  private bridFromChainOpts;
583
+ /**
584
+ * Resolve the dashboard chain used by agent metadata/policy reads.
585
+ * Explicit per-call network overrides win; otherwise use the supplied org
586
+ * or the client's configured default org. A custom BRID is intentionally
587
+ * left untouched because it cannot be represented by the dashboard's
588
+ * public/private query selector.
589
+ */
590
+ private resolveAgentLookupNetwork;
564
591
  /**
565
592
  * Get-or-create a Bearer token for dashboard reads. The token is a
566
593
  * signed `log_tool_call` op (locally signed, never submitted) — the
@@ -893,19 +920,6 @@ interface ClassifyMemoryWriteOptions {
893
920
  */
894
921
  declare function classifyMemoryWrite(event: unknown, ctx: unknown, opts?: ClassifyMemoryWriteOptions): MemoryEntry | null;
895
922
 
896
- /**
897
- * Plugin-agnostic memory-write guard.
898
- *
899
- * A single call that replaces the plugin's usual memory-write branch:
900
- * classify → scan (Layer 1 regex + Layer 2 LLM) → gate on verdict →
901
- * persist to chain (fire-and-forget when allowed) → return decision.
902
- *
903
- * Plugins call this from their `before_tool_call` hook. When it returns
904
- * `{ handled: false }` the call wasn't a memory write and the plugin
905
- * should fall through to its regular tool-call audit. When
906
- * `{ handled: true }` the plugin returns `decision` directly.
907
- */
908
-
909
923
  /**
910
924
  * Minimal logger accepted by `guardMemoryWrite`. Plugins pass their
911
925
  * host runtime's logger (openclaw's `api.logger`, MCP's console, etc.).
@@ -936,6 +950,8 @@ interface GuardMemoryWriteInput extends ClassifyMemoryWriteOptions {
936
950
  debug?: boolean;
937
951
  /** Optional logger for debug probe + persist-failure warnings. */
938
952
  logger?: GuardLogger;
953
+ /** Absolute path of the agent's managed memory file. Required for chain commits — omitted skips them. */
954
+ memoryFilePath?: string;
939
955
  }
940
956
  /** Plugin-facing decision. Shape mirrors what plugins return from `before_tool_call`. */
941
957
  interface GuardMemoryDecision {
@@ -1000,12 +1016,19 @@ interface SyncMemoryOptions {
1000
1016
  * `drifted: false` — pointer is still valid; caller can keep serving the local copy.
1001
1017
  * `drifted: true` — active id changed on chain; `current` is the fresh decrypted row
1002
1018
  * (or `null` if active memory was removed entirely).
1019
+ *
1020
+ * `checked` — whether this call actually queried chain. `false` means the TTL
1021
+ * window was still open and the pointer was trusted without contacting chain, so
1022
+ * `drifted: false` carries no evidence about the current state. Callers that
1023
+ * vouch for content to a third party must not treat an unchecked result as proof.
1003
1024
  */
1004
1025
  type SyncMemoryResult = {
1005
1026
  drifted: false;
1027
+ checked: boolean;
1006
1028
  pointer: MemoryPointer;
1007
1029
  } | {
1008
1030
  drifted: true;
1031
+ checked: true;
1009
1032
  current: AgentMemoryEntry | null;
1010
1033
  pointer: MemoryPointer;
1011
1034
  };
@@ -1067,12 +1090,42 @@ interface ClassifyMemoryReadOptions {
1067
1090
  */
1068
1091
  declare function classifyMemoryRead(event: unknown, ctx: unknown, opts?: ClassifyMemoryReadOptions): boolean;
1069
1092
 
1070
- /** Decision the manager returns to the plugin's `before_tool_call` handler. */
1093
+ /**
1094
+ * Decision the manager returns to the plugin's `before_tool_call` handler.
1095
+ *
1096
+ * `allow: true` alone is NOT evidence that anything was checked. Read `audited`
1097
+ * to tell the two apart, and route un-audited calls to your own judge — see the
1098
+ * field docs below.
1099
+ */
1071
1100
  interface HookDecision {
1072
1101
  allow?: boolean;
1073
1102
  block?: boolean;
1074
1103
  blockReason?: string;
1075
1104
  reason?: string;
1105
+ /**
1106
+ * Whether the guard reached an enforcement decision about *this* call.
1107
+ *
1108
+ * Note this describes whether the guard **decided**, not whether it allowed.
1109
+ * Every `block` is `audited: true` — a blocked call is the most thoroughly
1110
+ * checked outcome the guard produces (a red scan, a ciphertext integrity
1111
+ * failure, a rolled-back version), and a host must never re-judge its way past
1112
+ * one.
1113
+ *
1114
+ * Absent or false means the guard reached no decision — it was inside its cache
1115
+ * window, chain was unreachable, the scan never ran, the file it can vouch for
1116
+ * is not the file being read, or it is in observe mode. Those calls are
1117
+ * unaudited: fall through to your own judge exactly as for a `null` return.
1118
+ *
1119
+ * So the host rule is:
1120
+ * `if (d.block) deny; else if (d.audited) allow; else judge it yourself;`
1121
+ *
1122
+ * Treating a bare `allow: true` as a completed audit is what this field exists
1123
+ * to prevent. A host that ignores it and returns the decision verbatim will
1124
+ * execute unaudited tool calls.
1125
+ */
1126
+ audited?: boolean;
1127
+ /** Scan verdict when one was produced (`green` | `yellow` | `red`). Absent when no scan ran. */
1128
+ verdict?: string;
1076
1129
  }
1077
1130
  interface MemoryGuardManagerOptions {
1078
1131
  auth: AgentAuth;
@@ -1095,6 +1148,13 @@ interface MemoryGuardManagerOptions {
1095
1148
  rollbackMinScore?: number;
1096
1149
  /** True → return `{block:true}` on defense triggers. False → log and return `null` (audit-only). Default true. */
1097
1150
  enforce?: boolean;
1151
+ /**
1152
+ * Chain targeting for the pointer sync (network, blockchainRid, nodeUrls).
1153
+ * Defaults to the SDK's configured chain. Without this the manager could only
1154
+ * ever talk to the default chain, which left the whole memory-read path
1155
+ * untestable — `syncLocalMemory` already accepted these options.
1156
+ */
1157
+ chainOpts?: ChainOpts;
1098
1158
  /** Host-specific tuning of what counts as a memory read. */
1099
1159
  memoryReadClassifier?: ClassifyMemoryReadOptions;
1100
1160
  /** Passed through to `guardMemoryWrite`. Host memory-write tool names override. */
@@ -1131,12 +1191,33 @@ declare class MemoryGuardManager {
1131
1191
  */
1132
1192
  runBootProbe(): Promise<void>;
1133
1193
  /**
1134
- * Returns a `HookDecision` when the event is a memory read or write
1135
- * (host returns it verbatim to its runtime). Returns `null` when the
1136
- * event isn't memory-related — host falls through to its own audit.
1194
+ * Returns a `HookDecision` when the guard reached a decision about this event.
1195
+ * Returns `null` when it did not — either the event isn't memory-related, or it
1196
+ * is but the guard could not check it. In both cases the host falls through to
1197
+ * its own audit.
1198
+ *
1199
+ * A returned decision carries `audited` (see `HookDecision`). Only
1200
+ * `{ allow: true, audited: true }` means "checked and cleared"; anything else
1201
+ * that allows is a call the host still needs to judge.
1137
1202
  */
1138
1203
  handleBeforeToolCall(event: unknown, ctx: unknown): Promise<HookDecision | null>;
1139
1204
  private mapGuardResult;
1205
+ /**
1206
+ * Whether the pointer state this manager tracks actually describes the file
1207
+ * this call is about to read.
1208
+ *
1209
+ * The classifier fires on nine patterns — including the bare tokens
1210
+ * `"memory/"`, `"CLAUDE.md"` and `"AGENTS.md"` — but the sync path only ever
1211
+ * reads, refreshes, or vouches for `this.memoryFilePath`. Without this check a
1212
+ * read of `/repo/CLAUDE.md` (or any path merely containing `memory/`) would
1213
+ * receive an `audited: true` for a file the guard never opened.
1214
+ *
1215
+ * Conservative on purpose: every path-shaped value found must resolve to the
1216
+ * managed file. If none is found, or any one differs, the answer is no. That
1217
+ * also covers events carrying two different path keys, where the classifier
1218
+ * and the host could otherwise disagree about which one is authoritative.
1219
+ */
1220
+ private vouchesForTarget;
1140
1221
  private handleMemoryRead;
1141
1222
  private writeMemoryAtomic;
1142
1223
  }
@@ -1145,13 +1226,17 @@ declare function createMemoryGuardManager(opts: MemoryGuardManagerOptions): Memo
1145
1226
  /**
1146
1227
  * Atbash SDK Telemetry — OpenTelemetry metrics for usage tracking.
1147
1228
  *
1148
- * Tracks: function call counts, latency, source (CLI/plugin/SDK),
1149
- * and agent identity. ON by default.
1229
+ * Metrics are POSTed to the Atbash-owned `/api/telemetry` proxy, which
1230
+ * verifies the bearer, injects the Honeycomb ingest key server-side, and
1231
+ * forwards to Honeycomb. The ingest credential never enters the SDK.
1232
+ *
1233
+ * Environment opt-out (recommended for air-gapped deployments):
1234
+ * ATBASH_TELEMETRY_DISABLED=1
1150
1235
  *
1151
1236
  * Opt-out: create ~/.config/atbash/telemetry.json with { "enabled": false }
1152
1237
  * The file must be readable by the SDK process. If missing, corrupted, or
1153
- * unreadable → telemetry stays ON. Environment variables cannot disable
1154
- * telemetry (prevents agent bypass via env-var injection).
1238
+ * unreadable, telemetry remains eligible to start unless the environment
1239
+ * opt-out is set.
1155
1240
  */
1156
1241
  type ClientSource = "cli" | "sdk" | "plugin:openclaw" | "plugin:langchain" | "plugin:langgraph" | "plugin:hermes" | "plugin:eliza" | "plugin:crewai" | "plugin:mcp" | "plugin:autogen" | "plugin:jeenai" | (string & {});
1157
1242
  interface TelemetryConfig {
@@ -1161,6 +1246,13 @@ interface TelemetryConfig {
1161
1246
  source?: ClientSource;
1162
1247
  /** Flush interval in ms. Default: 60000 */
1163
1248
  exportIntervalMs?: number;
1249
+ /** Atbash endpoint that hosts /api/telemetry. Required to actually export. */
1250
+ endpoint?: string;
1251
+ /**
1252
+ * Called on every export to obtain fresh auth headers (typically
1253
+ * `{ Authorization: "Bearer <hex>" }`). Required to actually export.
1254
+ */
1255
+ getAuthHeaders?: () => Record<string, string>;
1164
1256
  }
1165
1257
  declare function setupTelemetry(config: TelemetryConfig): void;
1166
1258
  /**
@@ -1280,4 +1372,4 @@ declare function containsSecret(text: string): boolean;
1280
1372
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
1281
1373
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
1282
1374
 
1283
- 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 };
1375
+ export { type ActionType, type AgentAuth, type AgentLookupOptions, 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 };