@atbash/sdk 0.13.3-dev.0 → 0.15.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
@@ -63,8 +63,8 @@ Two ways to create an agent:
63
63
 
64
64
  ```ts
65
65
  import { generateKeypair } from "@atbash/sdk";
66
- const { privKey, pubKey } = generateKeypair();
67
- console.log("Save this private key somewhere safe:", privKey);
66
+ const { priv_key, pub_key } = generateKeypair();
67
+ console.log("Save this private key somewhere safe:", priv_key);
68
68
  ```
69
69
 
70
70
  Paste the public key into the **Onboard agent** form on the dashboard, assign it to an org, and attach a policy pack before calling `judgeAction`.
@@ -169,6 +169,11 @@ interface LogToolCallResult {
169
169
  }
170
170
  interface JudgeResult {
171
171
  verdict: Verdict;
172
+ /**
173
+ * Canonical executable permission, computed by `canonicalAllow` — see that
174
+ * function for the rule. Never more permissive than `auditToolCall`.
175
+ */
176
+ allow: boolean;
172
177
  actionType: string;
173
178
  reason: string;
174
179
  confidence: number;
@@ -197,6 +202,8 @@ interface JudgeResult {
197
202
  interface JudgmentStatus {
198
203
  status: JudgmentState;
199
204
  verdict: Verdict;
205
+ /** Same canonical executable permission as {@link JudgeResult.allow}. */
206
+ allow: boolean;
200
207
  reason: string;
201
208
  judgmentId: string;
202
209
  onChain?: boolean;
@@ -564,7 +571,17 @@ declare class Atbash {
564
571
  */
565
572
  private failJudge;
566
573
  private fail;
567
- getJudgmentStatus(judgmentId: string, agentPubkey?: string): Promise<JudgmentStatus>;
574
+ /**
575
+ * Return the current status of a previously submitted judgment.
576
+ *
577
+ * `chainOpts` names which chain the judgment was signed against. The
578
+ * server's GET /api/v1/judge routes to that chain when the SDK sends
579
+ * a `brid` query param; without it, the server falls back to public.
580
+ * Callers on the private chain must pass a `chainOpts` (or configure
581
+ * the client on the private chain) — otherwise polling a POSTed
582
+ * judgment on the private chain 404s at the server.
583
+ */
584
+ getJudgmentStatus(judgmentId: string, agentPubkey?: string, chainOpts?: ChainOpts): Promise<JudgmentStatus>;
568
585
  getToolCalls(maxCount: number): Promise<ToolCallRecord[]>;
569
586
  getOrgToolCalls(orgName: string, maxCount: number): Promise<ToolCallRecord[]>;
570
587
  getAgentToolCalls(agentPubkey: string, maxCount: number): Promise<ToolCallRecord[]>;
@@ -749,9 +766,25 @@ declare class HttpTransportError extends Error {
749
766
  });
750
767
  }
751
768
 
769
+ declare function canonicalAllow(data: Record<string, unknown>): boolean;
770
+
752
771
  /** Normalize wire shapes (verdict casing, status, pubkey) to canonical forms. */
753
772
 
754
773
  declare function normalizeVerdict(raw: unknown): Verdict;
774
+ /**
775
+ * Canonicalize `action_type` at the wire boundary, the way
776
+ * {@link normalizeVerdict} already canonicalizes `verdict`.
777
+ *
778
+ * `verdict` has been normalized here since the beginning and has never
779
+ * drifted between consumers. `action_type` was passed through raw, so every
780
+ * reader invented its own folding policy — `auditToolCall` compared exactly
781
+ * while `memory/scan.ts` trimmed and case-folded, and the same `" ALLOW "`
782
+ * was therefore an error on one path and permission on the other.
783
+ *
784
+ * Trim and case-fold only. Zero-width and homoglyph variants survive
785
+ * untouched, stay outside the known set, and still fail closed.
786
+ */
787
+ declare function normalizeActionType(raw: unknown): string;
755
788
  declare function normalizeStatus(raw: unknown): JudgmentState;
756
789
  /** Wire pubkey may be a hex string, a Buffer/Uint8Array, or `{ data: [...] }`. */
757
790
  declare function pubkeyToHex(val: unknown): string;
@@ -1476,4 +1509,4 @@ declare function containsSecret(text: string): boolean;
1476
1509
  declare function createMemorySnapshot(entries: MemoryEntry[], takenAt: number): MemorySnapshot;
1477
1510
  declare function diffMemorySnapshots(before: MemorySnapshot, after: MemorySnapshot): MemoryDiffResult;
1478
1511
 
1479
- 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, 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, 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, chainForNetwork, chooseKeyPath, claimHashHex, classifyMemoryRead, classifyMemoryWrite, columnAad, commitMemoryVersion, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, flushTelemetry, generateKeypair, getActiveAgentMemory, getActiveMemoryId, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRecentAgentMemory, 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 };
1512
+ 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, 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, 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, containsEvasionCharacters, containsSecret, createFileLogger, createMemoryGuardManager, createMemorySnapshot, decryptForOrg, decryptMemoryContent, defaultPluginLogPath, defaultPointerPath, deriveMemoryKey, derivePublicKey, diffMemorySnapshots, encryptForOrg, encryptMemoryContent, encryptedLength, flushTelemetry, generateKeypair, getActiveAgentMemory, getActiveMemoryId, getConfigDir, getConfigPath, getMemoryById, getMemoryHistory, getRecentAgentMemory, getRollbackHistory, guardMemoryWrite, isEnvelope, isValidPrivateKey, keyFingerprintOf, keyPathCandidates, loadAgent, loadAgentFromFile, loadUserConfig, normalizeActionForHash, normalizeActionType, 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 };
package/dist/browser.mjs CHANGED
@@ -44555,6 +44555,10 @@ function loadAgentFromFile(_keyPath) {
44555
44555
  throw new Error(NOT_AVAILABLE);
44556
44556
  }
44557
44557
 
44558
+ // src-ts/decision.ts
44559
+ init_define_ATBASH_CHROMIA_NODE_URLS();
44560
+ init_define_ATBASH_PRIVATE_NODE_URLS();
44561
+
44558
44562
  // src-ts/normalize.ts
44559
44563
  init_define_ATBASH_CHROMIA_NODE_URLS();
44560
44564
  init_define_ATBASH_PRIVATE_NODE_URLS();
@@ -44566,6 +44570,9 @@ function normalizeVerdict(raw2) {
44566
44570
  if (v === "BLOCK" || v === "RED") return "BLOCK";
44567
44571
  return "HOLD";
44568
44572
  }
44573
+ function normalizeActionType(raw2) {
44574
+ return typeof raw2 === "string" ? raw2.trim().toLowerCase() : "";
44575
+ }
44569
44576
  function normalizeStatus(raw2) {
44570
44577
  const s2 = String(raw2 ?? "").toLowerCase();
44571
44578
  if (s2 === "pending" || s2 === "answered" || s2 === "error") return s2;
@@ -44582,6 +44589,37 @@ function pubkeyToHex(val) {
44582
44589
  return "";
44583
44590
  }
44584
44591
 
44592
+ // src-ts/decision.ts
44593
+ function isRecord(value) {
44594
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44595
+ }
44596
+ function allowSignalsPermit(data) {
44597
+ const signals = [];
44598
+ if (Object.hasOwn(data, "allow")) signals.push(data.allow);
44599
+ if (isRecord(data.decision) && Object.hasOwn(data.decision, "allow")) {
44600
+ signals.push(data.decision.allow);
44601
+ }
44602
+ return signals.length === 0 || signals.every((value) => value === true);
44603
+ }
44604
+ function wireActionType(data) {
44605
+ if (data.action_type !== void 0)
44606
+ return normalizeActionType(data.action_type);
44607
+ return normalizeActionType(data.actionType);
44608
+ }
44609
+ function isAuditTier(data) {
44610
+ const absentVerdict = data.verdict === null || data.verdict === void 0;
44611
+ return absentVerdict && data.status === "logged";
44612
+ }
44613
+ function canonicalAllow(data) {
44614
+ if (!allowSignalsPermit(data)) return false;
44615
+ const actionType = wireActionType(data);
44616
+ if (actionType && actionType !== "allow") return false;
44617
+ if (isAuditTier(data)) return true;
44618
+ if (typeof data.verdict !== "string") return false;
44619
+ const verdict = data.verdict.trim().toUpperCase();
44620
+ return verdict === "ALLOW" || verdict === "GREEN";
44621
+ }
44622
+
44585
44623
  // src-ts/browser/opentel/telemetry.ts
44586
44624
  init_define_ATBASH_CHROMIA_NODE_URLS();
44587
44625
  init_define_ATBASH_PRIVATE_NODE_URLS();
@@ -44750,7 +44788,10 @@ var Atbash = class _Atbash {
44750
44788
  getAuthHeaders: () => this.authHeaders()
44751
44789
  });
44752
44790
  } catch (err) {
44753
- this.logger.warn?.("[atbash] telemetry setup failed \u2014 continuing without metrics", { error: String(err) });
44791
+ this.logger.warn?.(
44792
+ "[atbash] telemetry setup failed \u2014 continuing without metrics",
44793
+ { error: String(err) }
44794
+ );
44754
44795
  }
44755
44796
  }
44756
44797
  /**
@@ -44965,7 +45006,10 @@ var Atbash = class _Atbash {
44965
45006
  this._chainCache.set(options.orgName, chain);
44966
45007
  chainOpts = { network: mapNetwork };
44967
45008
  } else if (!chainOpts?.blockchainRid) {
44968
- const resolved = await this.resolveChainFromMap(options.orgName, null);
45009
+ const resolved = await this.resolveChainFromMap(
45010
+ options.orgName,
45011
+ null
45012
+ );
44969
45013
  chainOpts = { ...chainOpts, network: resolved.network };
44970
45014
  }
44971
45015
  }
@@ -45040,7 +45084,8 @@ var Atbash = class _Atbash {
45040
45084
  const score = typeof rawScore === "number" && Number.isInteger(rawScore) && rawScore >= 1 && rawScore <= 10 ? rawScore : void 0;
45041
45085
  return {
45042
45086
  verdict: normalizeVerdict(data.verdict),
45043
- actionType: String(data.action_type ?? ""),
45087
+ allow: canonicalAllow(data),
45088
+ actionType: normalizeActionType(data.action_type),
45044
45089
  reason: String(data.reason ?? ""),
45045
45090
  confidence: Number(data.confidence ?? 0),
45046
45091
  provider: String(data.provider ?? ""),
@@ -45182,19 +45227,31 @@ var Atbash = class _Atbash {
45182
45227
  return { allow: !this.failClosed, verdict: "ERROR", reason, toolCallId };
45183
45228
  }
45184
45229
  /* ── judgment status ───────────────────────────────────────────────────── */
45185
- async getJudgmentStatus(judgmentId, agentPubkey) {
45230
+ /**
45231
+ * Return the current status of a previously submitted judgment.
45232
+ *
45233
+ * `chainOpts` names which chain the judgment was signed against. The
45234
+ * server's GET /api/v1/judge routes to that chain when the SDK sends
45235
+ * a `brid` query param; without it, the server falls back to public.
45236
+ * Callers on the private chain must pass a `chainOpts` (or configure
45237
+ * the client on the private chain) — otherwise polling a POSTed
45238
+ * judgment on the private chain 404s at the server.
45239
+ */
45240
+ async getJudgmentStatus(judgmentId, agentPubkey, chainOpts) {
45186
45241
  const pk = agentPubkey ?? this.auth.pubkey;
45242
+ const brid = this.bridFromChainOpts(chainOpts);
45187
45243
  return this.track("getJudgmentStatus", pk, async () => {
45188
45244
  const resp = await this.http.get(
45189
45245
  "/api/v1/judge",
45190
- { tool_call_id: judgmentId, agent_pubkey: pk },
45191
- this.authHeaders(await this.defaultOrgBrid())
45246
+ { tool_call_id: judgmentId, agent_pubkey: pk, brid },
45247
+ this.authHeaders(brid)
45192
45248
  );
45193
45249
  await this.raiseIfError(resp);
45194
45250
  const data = await this.json(resp) ?? {};
45195
45251
  return {
45196
45252
  status: normalizeStatus(data.status),
45197
45253
  verdict: normalizeVerdict(data.verdict),
45254
+ allow: canonicalAllow(data),
45198
45255
  reason: String(data.reason ?? ""),
45199
45256
  judgmentId: String(data.judgmentId ?? judgmentId),
45200
45257
  onChain: optBool(data.onChain),
@@ -45254,7 +45311,7 @@ var Atbash = class _Atbash {
45254
45311
  { tool_call_id: toolCallId },
45255
45312
  await this.defaultOrgBrid()
45256
45313
  );
45257
- if (!isRecord(raw2)) return null;
45314
+ if (!isRecord2(raw2)) return null;
45258
45315
  return toToolCallFull(raw2);
45259
45316
  });
45260
45317
  }
@@ -45266,7 +45323,7 @@ var Atbash = class _Atbash {
45266
45323
  { org: orgName },
45267
45324
  brid
45268
45325
  );
45269
- if (!isRecord(raw2)) return null;
45326
+ if (!isRecord2(raw2)) return null;
45270
45327
  return {
45271
45328
  orgName: String(raw2.org_name ?? ""),
45272
45329
  tier: String(raw2.tier ?? ""),
@@ -45343,7 +45400,7 @@ var Atbash = class _Atbash {
45343
45400
  );
45344
45401
  await this.raiseIfError(resp);
45345
45402
  const data = await this.json(resp) ?? {};
45346
- if (isRecord(data.data)) return data.data;
45403
+ if (isRecord2(data.data)) return data.data;
45347
45404
  return data;
45348
45405
  });
45349
45406
  }
@@ -45359,7 +45416,7 @@ var Atbash = class _Atbash {
45359
45416
  if (network) params.network = network;
45360
45417
  const brid = network ? this.bridFromChainOpts({ network }) : void 0;
45361
45418
  const raw2 = await this.riskEngineGet("org-subscription", params, brid);
45362
- if (!isRecord(raw2)) return null;
45419
+ if (!isRecord2(raw2)) return null;
45363
45420
  return coerceOrgSubscription(raw2, orgName);
45364
45421
  });
45365
45422
  }
@@ -45565,7 +45622,7 @@ var Atbash = class _Atbash {
45565
45622
  }
45566
45623
  if (resp.status !== 200) throw await this.httpError(resp);
45567
45624
  const data = await this.json(resp);
45568
- return isRecord(data) ? data : {};
45625
+ return isRecord2(data) ? data : {};
45569
45626
  }
45570
45627
  async riskEngineRecords(action, params, brid) {
45571
45628
  const raw2 = await this.riskEngineGet(action, params, brid);
@@ -45632,14 +45689,11 @@ var Atbash = class _Atbash {
45632
45689
  transportError(err) {
45633
45690
  if (err instanceof HttpTransportError) {
45634
45691
  if (this.debug) {
45635
- this.logger.warn?.(
45636
- `[atbash] transport failed \u2014 kind=${err.kind}`,
45637
- {
45638
- kind: err.kind,
45639
- cause: err.cause instanceof Error ? err.cause.message : String(err.cause ?? ""),
45640
- endpoint: this.endpoint
45641
- }
45642
- );
45692
+ this.logger.warn?.(`[atbash] transport failed \u2014 kind=${err.kind}`, {
45693
+ kind: err.kind,
45694
+ cause: err.cause instanceof Error ? err.cause.message : String(err.cause ?? ""),
45695
+ endpoint: this.endpoint
45696
+ });
45643
45697
  }
45644
45698
  return new AtbashAPIError(0, err.message, "", this.endpoint);
45645
45699
  }
@@ -45737,7 +45791,7 @@ function coerceOrgSubscription(raw2, orgName) {
45737
45791
  is_active: Boolean(raw2.is_active)
45738
45792
  };
45739
45793
  }
45740
- function isRecord(v) {
45794
+ function isRecord2(v) {
45741
45795
  return typeof v === "object" && v !== null && !Array.isArray(v);
45742
45796
  }
45743
45797
  function optString(v) {
@@ -46307,6 +46361,7 @@ export {
46307
46361
  SignatureVerificationError,
46308
46362
  bootSyncFailureLine,
46309
46363
  buildAllowedJudgeHosts,
46364
+ canonicalAllow,
46310
46365
  chainForNetwork,
46311
46366
  chooseKeyPath,
46312
46367
  claimHashHex,
@@ -46348,6 +46403,7 @@ export {
46348
46403
  loadAgentFromFile,
46349
46404
  loadUserConfig,
46350
46405
  normalizeActionForHash,
46406
+ normalizeActionType,
46351
46407
  normalizeForMatching2 as normalizeForMatching,
46352
46408
  normalizeStatus,
46353
46409
  normalizeVerdict,