@atbash/sdk 0.20.0-dev.0 → 0.22.0-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
@@ -68,7 +68,7 @@ Two ways to create an agent:
68
68
 
69
69
  ## Secret storage
70
70
 
71
- - Load the private key from an environment variable (`ATBASH_AGENT_KEY`) or a secret manager — never hardcode it.
71
+ - Keep the private key in the key file (`~/.config/atbash/guard-client-key`, or a file named by `keyPath`), in `ATBASH_AGENT_KEY`, or in a secret manager — never hardcode it. See [Which key signs](#which-key-signs).
72
72
  - Never commit `.env` files containing the key.
73
73
  - If a key leaks, stop using it and create a new agent in the dashboard.
74
74
 
@@ -127,31 +127,71 @@ Standalone helpers for keypair handling.
127
127
  | `isValidPrivateKey(hex)` | Validate a private-key string |
128
128
  | `loadAgent(privkey)` | Validate the key + return `{ pubkey, privkey }` |
129
129
 
130
- ## Configuration
130
+ ## Configuration resolution
131
131
 
132
- Configuration is resolved with priority: **constructor arg > env var > config file** (`~/.config/atbash/config.json`).
132
+ `new Atbash(privkey, options)` takes everything explicitly. `Atbash.fromConfig(options)` fills in what you did not pass from the environment and then from `~/.config/atbash/config.json`, and finds the signing key for you.
133
133
 
134
134
  ```ts
135
135
  import { Atbash } from "@atbash/sdk";
136
- const atbash = Atbash.fromConfig(); // reads env + config file
136
+ const atbash = Atbash.fromConfig(); // key file + env + config.json
137
137
  ```
138
138
 
139
- | Config key | Env var |
140
- |---|---|
141
- | `agentKey` | `ATBASH_AGENT_KEY` |
142
- | `orgName` | `ATBASH_ORG_NAME` |
143
- | `judgeEndpoint` | `ATBASH_ENDPOINT` |
144
- | `judgeVerifyPubKey` | `ATBASH_JUDGE_VERIFY_PUBKEY` (self-hosted judge response-signing key; selects the self-hosted policy) |
145
- | `blockchainRid` | `ATBASH_BLOCKCHAIN_RID` |
139
+ ### Settings: option, then env, then `config.json`
140
+
141
+ Each setting is read from the first place that has it: the `fromConfig` option, then the environment variable, then the key in `config.json`.
142
+
143
+ `judge` is taken whole. Pass it complete, or leave it out and use the environment or `config.json`: a `judge` with only an `endpoint` ignores `ATBASH_JUDGE_VERIFY_PUBKEY`, so a self-hosted host then fails the allowlist.
144
+
145
+ | `fromConfig` option | Env var | `config.json` key | Notes |
146
+ |---|---|---|---|
147
+ | `judge.endpoint` | `ATBASH_ENDPOINT` | `judgeEndpoint` | Must pass the endpoint rules below. |
148
+ | `judge.verifyPubKey` | `ATBASH_JUDGE_VERIFY_PUBKEY` | `judgeVerifyPubKey` | 66-hex response-signing key of a self-hosted judge. Set through the environment or `config.json` without an endpoint, it throws; passed in `judge` without an endpoint, the default endpoint is used. |
149
+ | `network` | `ATBASH_DEFAULT_CHAIN_NETWORK` | `defaultChainNetwork` | Only `"private"` is accepted; anything else throws. A client that names no chain is pinned to it, even for an org the dashboard places on another chain. |
150
+ | `debug` | `ATBASH_DEBUG` | `debug` | `1`, `true` or `yes` turns diagnostics on. |
151
+ | `orgName` | `ATBASH_ORG_NAME` | `orgName` | `fromConfig` reads the option only. The env var and file key are read by `resolve("orgName")`, which the CLI and plugins use. |
152
+
153
+ `agentKey` is not in this table on purpose: the signing key is never read from `config.json` (next section).
154
+
155
+ Helpers: `saveUserConfig(config)`, `loadUserConfig()`, `resolve(key, flagValue?)`, `getConfigPath()`.
156
+
157
+ ### Which key signs
158
+
159
+ `fromConfig` picks the first of these that is set:
160
+
161
+ 1. `agentKey` option (hex private key in code).
162
+ 2. `keyPath` option. A path that does not exist throws; the SDK never falls through to another key when you named one.
163
+ 3. `ATBASH_AGENT_KEY` environment variable.
164
+ 4. `~/.config/atbash/guard-client-key`.
165
+ 5. `~/.config/atbash/atbash-client-key`.
166
+
167
+ If none exists `fromConfig` throws `atbash key file not found. Looked for: <both default paths>`. The bare constructor never reads a key file.
168
+
169
+ An `agentKey` inside `config.json` is ignored. A settings file is writable by anything on the machine and is shared by every Atbash integration, so it is not allowed to choose who you sign as. When you pass a `logger`, `fromConfig` warns:
170
+
171
+ ```
172
+ [atbash] "agentKey" in config.json is ignored — settings do not choose the signing key. It holds <pubkey>; this client signs as the key file or ATBASH_AGENT_KEY instead. ...
173
+ ```
174
+
175
+ and when no key file exists at all, the "not found" error names the pubkey stranded in `config.json` so you know where it went.
176
+
177
+ A key file is either `key=value` lines or JSON. Both fields must be present; the public key is re-derived from the private key, and a `0x` prefix is accepted.
178
+
179
+ ```
180
+ privkey=<64 hex>
181
+ pubkey=<66 hex>
182
+ ```
183
+
184
+ ```json
185
+ { "privKey": "<64 hex>", "pubKey": "<66 hex>" }
186
+ ```
146
187
 
147
- Persistent config helpers: `saveUserConfig(config)`, `loadUserConfig()`, `resolve(key, flagValue?)`, `getConfigPath()`.
188
+ For adapters and CI, keep the key in a file and point at it with `keyPath` (or let the default path be found). Passing the key on a command line puts it in shell history and process listings.
148
189
 
149
- ### Judge endpoint policy
190
+ ### What `orgName` does
150
191
 
151
- Both `Atbash.fromConfig()` and the direct constructor validate the judge endpoint before any request is made. `new Atbash(privkey, { endpoint })` accepts only an `https://` allowlisted judge host, or a self-hosted judge when `verifyPubKey` is also given (the 66-hex response-signing key, which then verifies every judge response). Plaintext `http://` is accepted only for loopback (`localhost`, `127.0.0.1`, `::1`) local development. Anything else throws at construction, so a misconfigured or injected endpoint can no longer receive the agent's signed actions or return unsigned verdicts. `validateJudgeEndpoint(...)` exposes the same check.
192
+ `orgName` tells the SDK which chain to sign the call for: the org's network is looked up once through the dashboard, cached per client, and every judge and log call is signed for that chain. The SDK does not check that the name matches the org the agent was registered under; which org's policy judges the action is decided by the agent's registration, not by this string. On a deployment with a single chain a missing or different `orgName` therefore does not change the verdict. Org-scoped reads such as `getOrgTierInfo(orgName)` send the name as given; the dashboard answers an agent-authenticated call for the agent's own org, whatever name was passed.
152
193
 
153
- Agent policy and detail reads can resolve the organization's active network, or
154
- accept an explicit network override:
194
+ Agent policy and detail reads can take the org, or an explicit chain:
155
195
 
156
196
  ```ts
157
197
  await atbash.getAgentPolicy(atbash.pubkey, { orgName: "acme" });
@@ -160,6 +200,41 @@ await atbash.getAgentDetail(atbash.pubkey, {
160
200
  });
161
201
  ```
162
202
 
203
+ ### Judge endpoint rules
204
+
205
+ Both `fromConfig` and the constructor validate the endpoint before any request. `validateJudgeEndpoint(...)` exposes the same check.
206
+
207
+ - With no endpoint configured the SDK talks to the endpoint compiled into the build (`https://atbash.ai` for a release build).
208
+ - An `https://` endpoint is accepted without further setup only on the trusted hosts: `atbash.ai`, `www.atbash.ai` and the build's own default host.
209
+ - Any other `https://` endpoint is a self-hosted judge. It needs `policy: "self-hosted"` plus `verifyPubKey` (the judge's 66-hex compressed response-signing key), or `ATBASH_ENDPOINT` plus `ATBASH_JUDGE_VERIFY_PUBKEY`. Every judge response is then signature-checked against that key. Without the key the constructor throws `judge endpoint hostname "<host>" is not in the trusted allowlist`.
210
+ - Plain `http://` is accepted only for loopback (`localhost`, `127.0.0.1`, `::1`), for a dashboard running on the same machine. Any other `http://` endpoint throws.
211
+ - A URL with embedded credentials (`user:pass@host`) throws.
212
+
213
+ ```ts
214
+ const atbash = Atbash.fromConfig({
215
+ judge: {
216
+ policy: "self-hosted",
217
+ endpoint: "https://judge.example.com",
218
+ verifyPubKey: "02…66 hex…",
219
+ },
220
+ });
221
+ ```
222
+
223
+ ### From a key file to a first ALLOW
224
+
225
+ 1. Download the key file the onboarding wizard offers at its Deploy step (it is in the `key=value` form above) and save it, for example as `./agent.key`.
226
+ 2. Build the client from that file and judge an action:
227
+
228
+ ```ts
229
+ import { Atbash } from "@atbash/sdk";
230
+
231
+ const atbash = Atbash.fromConfig({ keyPath: "./agent.key" });
232
+ const result = await atbash.judgeAction("read file", "list the files in ./src");
233
+ console.log(result.allow, result.enforced, result.reason);
234
+ ```
235
+
236
+ Dropping the same file at `~/.config/atbash/guard-client-key` lets `Atbash.fromConfig()` find it with no options at all.
237
+
163
238
  ## Error handling
164
239
 
165
240
  The SDK throws standard `Error` objects. Known failure modes are enriched with a pointer to the dashboard page that fixes them:
@@ -38,8 +38,12 @@ interface ChainConfig {
38
38
  readonly blockchainRid: string;
39
39
  readonly nodeUrls: readonly string[];
40
40
  }
41
- declare const PUBLIC_CHAIN: ChainConfig;
42
41
  declare const PRIVATE_CHAIN: ChainConfig;
42
+ /**
43
+ * The chain a network name selects. Only `"private"` exists; any other value,
44
+ * including `"public"` from an untyped caller, is refused with the same
45
+ * message the config switch gives, never routed to private in silence.
46
+ */
43
47
  declare function chainForNetwork(network: Network): ChainConfig;
44
48
 
45
49
  /**
@@ -130,13 +134,11 @@ interface MemoryScanOptions {
130
134
  toolArgsJson?: string;
131
135
  }
132
136
  /**
133
- * Which Atbash chain an action runs against. `public` is the shared
134
- * testnet (Free plan); `private` is reserved for Private / Swarm /
135
- * Enterprise tier subscribers. The SDK resolves which one to use from
136
- * the org's subscription via `orgName` — callers normally don't need
137
- * to pass this manually.
137
+ * Chain selector. Only `"private"` exists: the public testnet chains are
138
+ * retired. The SDK resolves an org's chain through the Dashboard via
139
+ * `orgName` — callers normally don't need to pass this manually.
138
140
  */
139
- type Network = "public" | "private";
141
+ type Network = "private";
140
142
  /**
141
143
  * Per-call chain overrides. Pass exactly what you need to override —
142
144
  * `network` selects between the SDK's known chains, `blockchainRid` pins a
@@ -340,7 +342,7 @@ interface AtbashOptions {
340
342
  */
341
343
  chain?: ChainConfig;
342
344
  /**
343
- * Preset chain selector — `"public"` or `"private"`. Resolves to the
345
+ * Preset chain selector — `"private"` is the only value. Resolves to the
344
346
  * matching `ChainConfig` via `chainForNetwork()`. Overridden by `chain`,
345
347
  * overrides env `ATBASH_DEFAULT_CHAIN_NETWORK` and the config file.
346
348
  */
@@ -748,12 +750,9 @@ declare class Atbash {
748
750
  * Resolve which chain an org's actions should run against. Cached
749
751
  * per-client by orgName. Resolution order:
750
752
  * 1. `org_networks` map (authoritative).
751
- * 2. Per-chain subscription fallback — public + private records
752
- * are fetched in parallel, with `is_private_blockchain` and
753
- * `assigned_at` reconciling mixed states.
754
- * A lookup that names exactly one chain wins outright. Where it names
755
- * neither (a brand-new org) or cannot choose between them, the client's
756
- * configured default decides.
753
+ * 2. Subscription fallback — the org's subscription row on the chain.
754
+ * A lookup that finds the org wins outright. Where it finds nothing (a
755
+ * brand-new org), the client's configured default decides.
757
756
  */
758
757
  resolveChainForOrg(orgName: string): Promise<ChainConfig>;
759
758
  /**
@@ -870,8 +869,6 @@ declare function releaseJailHolds(): void;
870
869
  declare function configureJailHold(next: Partial<typeof DEFAULTS>): void;
871
870
 
872
871
  declare const DEFAULT_ENDPOINT: string;
873
- declare const DEFAULT_CHROMIA_NODE_URLS: readonly string[];
874
- declare const DEFAULT_BLOCKCHAIN_RID: string;
875
872
 
876
873
  declare class AtbashAPIError extends Error {
877
874
  /** HTTP status code (or 0 if the request never completed). */
@@ -1157,11 +1154,18 @@ declare function getRecentAgentMemory(auth: AgentAuth, chainOpts?: ChainOpts, fi
1157
1154
  * when you need every active version regardless of age.
1158
1155
  */
1159
1156
  declare function getActiveAgentMemory(auth: AgentAuth, chainOpts?: ChainOpts, filePath?: string | null): Promise<AgentMemoryEntry[]>;
1157
+ interface MemoryHistoryPage {
1158
+ /** Most versions to return, at most 200. Omit for the full history. */
1159
+ maxCount?: number;
1160
+ /** Return only versions with a lower id: the last id of the previous page. */
1161
+ beforeId?: number;
1162
+ }
1160
1163
  /**
1161
1164
  * Full version history — active + inactive, most recent first. Used
1162
- * by rollback UX to choose a target version.
1165
+ * by rollback UX to choose a target version. Pass `page` to read it in
1166
+ * pages; this needs a Dashboard and chain that support paging.
1163
1167
  */
1164
- declare function getMemoryHistory(auth: AgentAuth, chainOpts?: ChainOpts, filePath?: string | null): Promise<AgentMemoryEntry[]>;
1168
+ declare function getMemoryHistory(auth: AgentAuth, chainOpts?: ChainOpts, filePath?: string | null, page?: MemoryHistoryPage): Promise<AgentMemoryEntry[]>;
1165
1169
  /**
1166
1170
  * Fetch a single memory entry by version id, including its current
1167
1171
  * `is_active` state. Version ids are agent-unique on chain (not
@@ -1991,4 +1995,4 @@ declare function containsSecret(text: string): boolean;
1991
1995
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
1992
1996
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
1993
1997
 
1994
- 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 ChainConfig, 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, JudgeRefusalError, 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 OperationEvent, type OrgSubscription, PRIVATE_CHAIN, PUBLIC_CHAIN, 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, canonicalAllow, chainForNetwork, chooseKeyPath, claimHashHex, classifyMemoryRead, classifyMemoryWrite, columnAad, commitMemoryVersion, configureEvents, configureJailHold, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, eventsAreOn, flushTelemetry, generateKeypair, getActiveAgentMemory, getActiveMemoryId, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRecentAgentMemory, getRollbackHistory, guardMemoryWrite, isEnvelope, isJailHeld, isValidPrivateKey, keyFingerprintOf, keyPathCandidates, loadAgent, loadAgentFromFile, loadUserConfig, memorySlotOf, normalizeActionForHash, normalizeActionType, normalizeForMatching, normalizeStatus, normalizeVerdict, packEnvelope, parseEnvelope, pubkeyToHex, recordCall, recordDuration, recordEvent, redactJsonStrings, redactSecrets, releaseJailHolds, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signEncryptedToolCall, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };
1998
+ 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 ChainConfig, type ChainOpts, type ClassifierToolContext, type ClassifierToolEvent, type ClassifyMemoryReadOptions, type ClassifyMemoryWriteOptions, type ClientSource, type CommitMemoryOptions, 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, JudgeRefusalError, type JudgeResult, type JudgmentState, type JudgmentStatus, KEY_FILENAMES, type KeyPair, type LogToolCallOptions, type LogToolCallResult, type MemoryAnomaly, type MemoryDiffResult, type MemoryEntry, MemoryGuardManager, type MemoryGuardManagerOptions, type MemoryHistoryPage, MemoryIntegrityError, type MemoryPointer, type MemoryRollbackEvent, type MemoryScanOptions, type MemoryScanResult, type MemoryScanVerdict, type MemorySnapshot, type ModifiedEntry, type Network, type OperationEvent, type OrgSubscription, PRIVATE_CHAIN, 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, canonicalAllow, chainForNetwork, chooseKeyPath, claimHashHex, classifyMemoryRead, classifyMemoryWrite, columnAad, commitMemoryVersion, configureEvents, configureJailHold, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, eventsAreOn, flushTelemetry, generateKeypair, getActiveAgentMemory, getActiveMemoryId, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRecentAgentMemory, getRollbackHistory, guardMemoryWrite, isEnvelope, isJailHeld, isValidPrivateKey, keyFingerprintOf, keyPathCandidates, loadAgent, loadAgentFromFile, loadUserConfig, memorySlotOf, normalizeActionForHash, normalizeActionType, normalizeForMatching, normalizeStatus, normalizeVerdict, packEnvelope, parseEnvelope, pubkeyToHex, recordCall, recordDuration, recordEvent, redactJsonStrings, redactSecrets, releaseJailHolds, resolve, resolveKeyPath, rollbackMemory, saveUserConfig, scanMemory, scanMemoryBatch, setupTelemetry, shutdownTelemetry, signEncryptedToolCall, signJudgeAction, signLogToolCall, syncLocalMemory, validateJudgeEndpoint, verifyJudgeResponseSignature, verifySignature };