@zanii/blackbox 0.3.0 → 0.4.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.
Files changed (82) hide show
  1. package/README.md +26 -1
  2. package/dist/a2a/index.d.ts +27 -0
  3. package/dist/a2a/index.js +104 -1
  4. package/dist/agents/index.d.ts +8 -0
  5. package/dist/analysis/accuracy.d.ts +24 -0
  6. package/dist/analysis/accuracy.js +45 -0
  7. package/dist/analysis/credential.d.ts +101 -0
  8. package/dist/analysis/credential.js +142 -0
  9. package/dist/analysis/faults.js +115 -0
  10. package/dist/analysis/grounding.d.ts +122 -0
  11. package/dist/analysis/grounding.js +445 -0
  12. package/dist/analysis/hallucination.d.ts +32 -0
  13. package/dist/analysis/hallucination.js +357 -0
  14. package/dist/analysis/index.d.ts +23 -0
  15. package/dist/analysis/index.js +93 -0
  16. package/dist/analysis/memory.d.ts +8 -0
  17. package/dist/analysis/memory.js +35 -8
  18. package/dist/analysis/reference.d.ts +49 -0
  19. package/dist/analysis/reference.js +164 -0
  20. package/dist/analysis/taxonomy.js +1 -0
  21. package/dist/approvals/index.d.ts +23 -0
  22. package/dist/approvals/index.js +48 -0
  23. package/dist/archive/parquet.d.ts +2 -0
  24. package/dist/archive/parquet.js +185 -0
  25. package/dist/badge/index.d.ts +16 -0
  26. package/dist/badge/index.js +48 -0
  27. package/dist/bom/index.js +20 -0
  28. package/dist/cli.js +114 -10
  29. package/dist/compliance/art12.js +36 -9
  30. package/dist/compliance/index.d.ts +36 -2
  31. package/dist/compliance/index.js +78 -11
  32. package/dist/compliance/zanii.d.ts +29 -0
  33. package/dist/compliance/zanii.js +84 -0
  34. package/dist/constitution/index.d.ts +57 -0
  35. package/dist/constitution/index.js +131 -0
  36. package/dist/cv/index.d.ts +39 -0
  37. package/dist/cv/index.js +108 -0
  38. package/dist/disclosure/index.d.ts +31 -0
  39. package/dist/disclosure/index.js +113 -0
  40. package/dist/encryption/index.d.ts +9 -0
  41. package/dist/encryption/index.js +31 -0
  42. package/dist/evidence/index.d.ts +60 -0
  43. package/dist/evidence/index.js +151 -0
  44. package/dist/federation/index.d.ts +35 -0
  45. package/dist/federation/index.js +102 -0
  46. package/dist/finance/index.d.ts +126 -0
  47. package/dist/finance/index.js +320 -0
  48. package/dist/fleet/index.js +9 -0
  49. package/dist/gov/index.d.ts +108 -0
  50. package/dist/gov/index.js +225 -0
  51. package/dist/health/index.d.ts +120 -0
  52. package/dist/health/index.js +233 -0
  53. package/dist/index.d.ts +28 -6
  54. package/dist/index.js +28 -6
  55. package/dist/memory/index.d.ts +36 -0
  56. package/dist/memory/index.js +85 -0
  57. package/dist/occurrence/index.d.ts +11 -0
  58. package/dist/occurrence/index.js +18 -0
  59. package/dist/otlp/index.js +28 -1
  60. package/dist/packs/index.js +44 -4
  61. package/dist/policy/delta.js +7 -1
  62. package/dist/policy/index.d.ts +23 -6
  63. package/dist/policy/index.js +151 -8
  64. package/dist/policy/zanii.d.ts +31 -0
  65. package/dist/policy/zanii.js +87 -0
  66. package/dist/pq/index.d.ts +23 -0
  67. package/dist/pq/index.js +104 -0
  68. package/dist/search/index.d.ts +23 -0
  69. package/dist/search/index.js +69 -0
  70. package/dist/session/index.d.ts +89 -1
  71. package/dist/session/index.js +143 -11
  72. package/dist/sla/index.d.ts +61 -0
  73. package/dist/sla/index.js +197 -0
  74. package/dist/succession/index.d.ts +50 -0
  75. package/dist/succession/index.js +123 -0
  76. package/dist/tokens/index.d.ts +6 -0
  77. package/dist/tokens/index.js +46 -0
  78. package/dist/version.d.ts +1 -1
  79. package/dist/version.js +1 -1
  80. package/dist/walls/index.d.ts +31 -0
  81. package/dist/walls/index.js +119 -0
  82. package/package.json +1 -1
@@ -0,0 +1,120 @@
1
+ type Obj = Record<string, unknown>;
2
+ /** The patient's seed, for the patient's own app. It never leaves the patient. */
3
+ export declare function episodeSeed(secretHex?: string): {
4
+ v: 1;
5
+ secret: string;
6
+ };
7
+ /** Zanii's tag for encounter n, derived by the patient; two tags can't be linked without the seed. */
8
+ export declare function episodeTag(seed: {
9
+ secret: string;
10
+ }, n: number): string;
11
+ /** The tag, or an error: the patient supplies the tag, never the seed. */
12
+ export declare function checkEpisodeTag(tag: unknown): string;
13
+ /** A disclosed value and nonce match the commitment made at the time. */
14
+ export declare const verifyCommitment: (value: unknown, nonce: string, commitment: string) => boolean;
15
+ /** Zanii's health.access payload: who accessed the record, and why. */
16
+ export declare function accessPayload(input: {
17
+ actor: string;
18
+ purpose: string;
19
+ ts: string;
20
+ consentRef?: string;
21
+ details?: Obj;
22
+ nonce?: string;
23
+ }): {
24
+ payload: Obj;
25
+ nonce: string;
26
+ };
27
+ /** What the clinician signs: jcsHash of the recommendation payload. */
28
+ export declare const recommendationHash: (payload: Obj) => string;
29
+ /** Zanii's health.recommendation payload. No protocol, no recommendation; a deviation is recorded, never refused. */
30
+ export declare function recommendationPayload(input: {
31
+ modelId: string;
32
+ manifestHash: string;
33
+ outcome: Obj;
34
+ ts: string;
35
+ runtimeHash?: string;
36
+ deviation?: Obj;
37
+ nonce?: string;
38
+ }): {
39
+ payload: Obj;
40
+ nonce: string;
41
+ hash: string;
42
+ };
43
+ /** Zanii's health.confirmation payload, signed on the clinician's own device. */
44
+ export declare function clinicianConfirmation(input: {
45
+ episodeTag: string;
46
+ clinicianDid: string;
47
+ recommendationHash: string;
48
+ confirmedAt: string;
49
+ clinicianPrivateKey: Uint8Array;
50
+ }): Obj;
51
+ /** Zanii's health.break_glass payload: emergency access, signed personally. Kept open on purpose, and loud. */
52
+ export declare function breakGlass(input: {
53
+ episodeTag: string;
54
+ clinicianDid: string;
55
+ reason: string;
56
+ ts: string;
57
+ clinicianPrivateKey: Uint8Array;
58
+ }): Obj;
59
+ /** A confirmation or break-glass is signed by the clinician it names, over the action it names. */
60
+ export declare function verifyHealthSignature(payload: unknown, tag: string): boolean;
61
+ /** Zanii's protocol trail. No verdict on uniformity (individualised care is correct medicine). */
62
+ export declare function protocolTrail(payloads: readonly unknown[]): {
63
+ protocols: {
64
+ manifest_hash: unknown;
65
+ count: number;
66
+ first_ts: unknown;
67
+ last_ts: unknown;
68
+ }[];
69
+ deviations: number;
70
+ unprotocolled: number;
71
+ };
72
+ export interface EpisodeItem {
73
+ session_id: string;
74
+ seq: number;
75
+ line: string;
76
+ event_hash: string;
77
+ anchored: boolean;
78
+ payload: Obj;
79
+ tag: string;
80
+ }
81
+ /** spec/health.md §4: the patient's episodes; `reviewed` holds "<session_id>:<seq>" of reviewed break-glass. */
82
+ export declare function episodesPack(items: readonly EpisodeItem[], o: {
83
+ tags: readonly string[];
84
+ reviewed: readonly string[];
85
+ generated_at: string;
86
+ }): {
87
+ v: number;
88
+ episodes: {
89
+ tag: string;
90
+ items: {
91
+ session_id: string;
92
+ seq: number;
93
+ line: string;
94
+ event_hash: string;
95
+ anchored: boolean;
96
+ payload: Obj;
97
+ }[];
98
+ }[];
99
+ total: number;
100
+ pending_break_glass: number;
101
+ protocols: {
102
+ protocols: {
103
+ manifest_hash: unknown;
104
+ count: number;
105
+ first_ts: unknown;
106
+ last_ts: unknown;
107
+ }[];
108
+ deviations: number;
109
+ unprotocolled: number;
110
+ };
111
+ generated_at: string;
112
+ };
113
+ export declare function healthFindings(lines: readonly string[], bodies: (hash: string) => Uint8Array | undefined, closing?: boolean): {
114
+ code: string;
115
+ source: string;
116
+ severity: "warning" | "advisory";
117
+ ref: Record<string, string | number>;
118
+ detail: string;
119
+ }[];
120
+ export {};
@@ -0,0 +1,233 @@
1
+ // Health (spec/health.md): unlinkable per-episode patient tags, access and recommendation payloads,
2
+ // clinician confirmations, loud break-glass, the protocol trail and the patient's pack, on Zanii's
3
+ // health payloads (@zanii/health). Pure; mirrors sdks/python/src/zanii_blackbox/health.py; pinned
4
+ // by spec/vectors/health.json.
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { createConfirmation, jcsHash } from "@zanii/core";
7
+ import { verifyConfirmation } from "../approvals/index.js";
8
+ import { canonical } from "../reconcile/shared.js";
9
+ const TAG = /^sha256:[0-9a-f]{64}$/;
10
+ const HEX64 = /^[0-9a-f]{64}$/;
11
+ /** The patient's seed, for the patient's own app. It never leaves the patient. */
12
+ export function episodeSeed(secretHex) {
13
+ const secret = secretHex ?? randomBytes(32).toString("hex");
14
+ if (!HEX64.test(secret))
15
+ throw new Error("seed secret must be 32 bytes of hex");
16
+ return { v: 1, secret };
17
+ }
18
+ /** Zanii's tag for encounter n, derived by the patient; two tags can't be linked without the seed. */
19
+ export function episodeTag(seed, n) {
20
+ if (!Number.isSafeInteger(n) || n < 0)
21
+ throw new Error("n must be a non-negative integer");
22
+ return jcsHash({ v: 1, type: "episode_tag", secret: seed.secret, n });
23
+ }
24
+ /** The tag, or an error: the patient supplies the tag, never the seed. */
25
+ export function checkEpisodeTag(tag) {
26
+ if ((typeof tag === "object" && tag !== null) || (typeof tag === "string" && HEX64.test(tag)))
27
+ throw new Error("pass the patient's episode tag, never the seed: whoever holds the seed can link every encounter");
28
+ if (typeof tag !== "string" || !TAG.test(tag))
29
+ throw new Error("episode_tag must be sha256: and 64 hex characters");
30
+ return tag;
31
+ }
32
+ const validTs = (ts) => typeof ts === "string" && !Number.isNaN(Date.parse(ts));
33
+ const commit = (value, nonce) => `sha256:${createHash("sha256").update(Buffer.from(nonce, "hex")).update(canonical(value)).digest("hex")}`;
34
+ /** A disclosed value and nonce match the commitment made at the time. */
35
+ export const verifyCommitment = (value, nonce, commitment) => /^[0-9a-f]{32}$/.test(nonce) && commit(value, nonce) === commitment;
36
+ const base = (kind) => ({ _zr_kind: "health", _zr_domain: "health", v: 1, kind });
37
+ /** Zanii's health.access payload: who accessed the record, and why. */
38
+ export function accessPayload(input) {
39
+ if (!input.actor)
40
+ throw new Error("actor is required");
41
+ if (!input.purpose)
42
+ throw new Error("purpose is required: purpose limitation is not optional");
43
+ if (!validTs(input.ts))
44
+ throw new Error("ts must be an ISO timestamp");
45
+ const nonce = input.nonce ?? randomBytes(16).toString("hex");
46
+ return {
47
+ payload: {
48
+ ...base("access"),
49
+ actor: input.actor,
50
+ purpose: input.purpose,
51
+ consent_ref: input.consentRef ?? null,
52
+ details_commitment: commit(input.details ?? {}, nonce),
53
+ ts: input.ts,
54
+ },
55
+ nonce,
56
+ };
57
+ }
58
+ /** What the clinician signs: jcsHash of the recommendation payload. */
59
+ export const recommendationHash = (payload) => jcsHash(payload);
60
+ /** Zanii's health.recommendation payload. No protocol, no recommendation; a deviation is recorded, never refused. */
61
+ export function recommendationPayload(input) {
62
+ if (!input.modelId)
63
+ throw new Error("model_id is required");
64
+ if (!input.manifestHash)
65
+ throw new Error("manifest_hash is required: a clinical recommendation with no governing protocol on record is not auditable");
66
+ if (!validTs(input.ts))
67
+ throw new Error("ts must be an ISO timestamp");
68
+ const nonce = input.nonce ?? randomBytes(16).toString("hex");
69
+ const payload = {
70
+ ...base("recommendation"),
71
+ model_id: input.modelId,
72
+ runtime_hash: input.runtimeHash ?? null,
73
+ manifest_hash: input.manifestHash,
74
+ outcome_commitment: commit(input.outcome, nonce),
75
+ deviation: input.deviation ?? null,
76
+ ts: input.ts,
77
+ };
78
+ return { payload, nonce, hash: recommendationHash(payload) };
79
+ }
80
+ /** Zanii's health.confirmation payload, signed on the clinician's own device. */
81
+ export function clinicianConfirmation(input) {
82
+ checkEpisodeTag(input.episodeTag);
83
+ const confirmation = createConfirmation({
84
+ ownerId: input.clinicianDid,
85
+ actionHash: input.recommendationHash,
86
+ confirmedAt: input.confirmedAt,
87
+ }, input.clinicianPrivateKey);
88
+ return {
89
+ ...base("confirmation"),
90
+ clinician: input.clinicianDid,
91
+ recommendation_hash: input.recommendationHash,
92
+ confirmation,
93
+ ts: input.confirmedAt,
94
+ };
95
+ }
96
+ const breakGlassAction = (tag, ts) => jcsHash({ v: 1, type: "break_glass", tag, ts });
97
+ /** Zanii's health.break_glass payload: emergency access, signed personally. Kept open on purpose, and loud. */
98
+ export function breakGlass(input) {
99
+ checkEpisodeTag(input.episodeTag);
100
+ if (!input.reason)
101
+ throw new Error("reason is required: an unexplained break-glass is exactly the abuse this exists to catch");
102
+ const confirmation = createConfirmation({
103
+ ownerId: input.clinicianDid,
104
+ actionHash: breakGlassAction(input.episodeTag, input.ts),
105
+ confirmedAt: input.ts,
106
+ }, input.clinicianPrivateKey);
107
+ return {
108
+ ...base("break_glass"),
109
+ clinician: input.clinicianDid,
110
+ reason: input.reason,
111
+ confirmation,
112
+ reviewed: false,
113
+ ts: input.ts,
114
+ };
115
+ }
116
+ /** A confirmation or break-glass is signed by the clinician it names, over the action it names. */
117
+ export function verifyHealthSignature(payload, tag) {
118
+ const p = (payload ?? {});
119
+ const c = p.confirmation;
120
+ if (!c || typeof c !== "object")
121
+ return false;
122
+ if (c.owner_id !== p.clinician || !verifyConfirmation(c))
123
+ return false;
124
+ if (p.kind === "confirmation")
125
+ return c.action_hash === p.recommendation_hash;
126
+ if (p.kind === "break_glass")
127
+ return c.action_hash === breakGlassAction(tag, p.ts);
128
+ return false;
129
+ }
130
+ /** Zanii's protocol trail. No verdict on uniformity (individualised care is correct medicine). */
131
+ export function protocolTrail(payloads) {
132
+ const recs = payloads
133
+ .filter((p) => typeof p === "object" && p !== null)
134
+ .filter((p) => p._zr_kind === "health" && p.kind === "recommendation")
135
+ .sort((a, b) => (String(a.ts) < String(b.ts) ? -1 : String(a.ts) > String(b.ts) ? 1 : 0));
136
+ const windows = new Map();
137
+ let deviations = 0;
138
+ let unprotocolled = 0;
139
+ for (const p of recs) {
140
+ if (p.deviation)
141
+ deviations++;
142
+ const h = p.manifest_hash;
143
+ if (!h) {
144
+ unprotocolled++;
145
+ continue;
146
+ }
147
+ const w = windows.get(String(h));
148
+ if (w) {
149
+ w.count++;
150
+ w.last_ts = p.ts;
151
+ }
152
+ else
153
+ windows.set(String(h), { manifest_hash: h, count: 1, first_ts: p.ts, last_ts: p.ts });
154
+ }
155
+ const protocols = [...windows.values()].sort((a, b) => String(a.first_ts) < String(b.first_ts) ? -1 : String(a.first_ts) > String(b.first_ts) ? 1 : 0);
156
+ return { protocols, deviations, unprotocolled };
157
+ }
158
+ /** spec/health.md §4: the patient's episodes; `reviewed` holds "<session_id>:<seq>" of reviewed break-glass. */
159
+ export function episodesPack(items, o) {
160
+ const done = new Set(o.reviewed);
161
+ const episodes = o.tags
162
+ .map((tag) => ({
163
+ tag,
164
+ items: items.filter((i) => i.tag === tag).map(({ tag: _t, ...rest }) => rest),
165
+ }))
166
+ .filter((e) => e.items.length > 0);
167
+ const pending = items.filter((i) => i.payload.kind === "break_glass" && !done.has(`${i.session_id}:${i.seq}`));
168
+ return {
169
+ v: 1,
170
+ episodes,
171
+ total: items.length,
172
+ pending_break_glass: pending.length,
173
+ protocols: protocolTrail(items.map((i) => i.payload)),
174
+ generated_at: o.generated_at,
175
+ };
176
+ }
177
+ const decoder = new TextDecoder();
178
+ export function healthFindings(lines, bodies, closing = false) {
179
+ const out = [];
180
+ const recommendations = [];
181
+ const confirmed = new Set();
182
+ let closed = closing;
183
+ for (const l of lines) {
184
+ const e = JSON.parse(l);
185
+ if (e.kind === "session.close")
186
+ closed = true;
187
+ if (e.kind !== "sdk.event" || !String(e.meta.type).startsWith("health."))
188
+ continue;
189
+ const body = bodies(e.body_hash);
190
+ let data = {};
191
+ try {
192
+ data = body ? JSON.parse(decoder.decode(body)) : {};
193
+ }
194
+ catch { }
195
+ const payload = data?.payload;
196
+ if (!payload || typeof payload !== "object")
197
+ continue;
198
+ const kind = payload.kind;
199
+ if (kind === "recommendation")
200
+ recommendations.push([e.seq, recommendationHash(payload)]);
201
+ else if (kind === "confirmation" || kind === "break_glass") {
202
+ if (!verifyHealthSignature(payload, String(data.episode_tag)))
203
+ out.push({
204
+ code: "HEALTH_SIGNATURE_INVALID",
205
+ source: "detectors",
206
+ severity: "warning",
207
+ ref: { seq: e.seq, kind },
208
+ detail: "A clinician signature that isn't theirs, or signs another action.",
209
+ });
210
+ else if (kind === "confirmation")
211
+ confirmed.add(String(payload.recommendation_hash));
212
+ else
213
+ out.push({
214
+ code: "BREAK_GLASS",
215
+ source: "detectors",
216
+ severity: "warning",
217
+ ref: { seq: e.seq, clinician: String(payload.clinician) },
218
+ detail: "Emergency access to a record, signed by the clinician.",
219
+ });
220
+ }
221
+ }
222
+ if (closed)
223
+ for (const [seq, h] of recommendations)
224
+ if (!confirmed.has(h))
225
+ out.push({
226
+ code: "UNCONFIRMED_RECOMMENDATION",
227
+ source: "detectors",
228
+ severity: "advisory",
229
+ ref: { seq, recommendation_hash: h },
230
+ detail: "A model's recommendation no clinician confirmed.",
231
+ });
232
+ return out;
233
+ }
package/dist/index.d.ts CHANGED
@@ -1,53 +1,75 @@
1
- export { A2A_STREAMING, type AgentCardReport, a2aMethod, a2aRequestMeta, a2aResponseMeta, agentCardDigest, agentCardPayload, verifyAgentCard, } from "./a2a/index.ts";
1
+ export { A2A_STREAMING, type AgentCardReport, a2aMethod, a2aRequestMeta, a2aResponseMeta, a2aRestMethod, a2aRestRequestMeta, a2aRestResponseMeta, agentCardDigest, agentCardPayload, gatewayCardKey, rewriteAgentCard, verifyAgentCard, } from "./a2a/index.ts";
2
2
  export { causality, memoryXray } from "./agents/index.ts";
3
3
  export { type DetectorOptions, detectors, fingerprint } from "./analysis/detectors.ts";
4
4
  export { FAULTS, type Fault, faultOf } from "./analysis/faults.ts";
5
- export { type AnalyzeOptions, analyze, type ClaimVerdict, type CriterionResult, checkFlightPlan, checkpointReplay, dualWitness, eventsOf, type Finding as AnalysisFinding, findingKey, type Landing, landing, OUTCOMES, type Outcome, type OutcomeRollup, rollup, type Severity, type WasteReason, type WasteReport, waste, } from "./analysis/index.ts";
5
+ export { type Accuracy, type AnalyzeOptions, type AnswerClaims, analyze, answerClaims, answerCredential, answerRisk, answersOf, answerText, type ClaimEntry, type ClaimVerdict, type CriterionResult, canonicalNumber, checkAgainstPacks, checkFlightPlan, checkpointReplay, detectorAccuracy, dualWitness, Evidence, eventsOf, type Fact, type Finding as AnalysisFinding, factsIn, findingKey, type GroundedClaim, groundingFindings, groundingRequest, HOLD_TRIGGERS, identifiersIn, judgeFindings, judgeRequest, type Label as AccuracyLabel, type Landing, landing, loadReferencePacks, modelGroundingFindings, normaliseValue, OUTCOMES, type Outcome, type OutcomeRollup, packsFor, parseGroundingAnswer, parseJudgeAnswer, type ReferenceFact, type ReferencePack, type ReferenceVerdict, referenceContext, rollup, type Severity, schemaProblem, toolHallucinations, verifyAnswerCredential, type WasteReason, type WasteReport, waste, wilsonLow, } from "./analysis/index.ts";
6
6
  export { MITRE_ATLAS, OWASP_ASI, TAXONOMY, type Taxonomy, taxonomyOf, } from "./analysis/taxonomy.ts";
7
- export { type ApprovalFinding, approvalFindings } from "./approvals/index.ts";
7
+ export { type ApprovalFinding, approvalConfirmation, approvalFindings, argsHash, verifyConfirmation, } from "./approvals/index.ts";
8
8
  export { textWarnings } from "./approvals/warnings.ts";
9
9
  export { type ArchiveFile, type ArchiveManifest, type ArchiveReport, archiveDigest, archiveEntry, archiveManifest, verifyArchive, } from "./archive/index.ts";
10
+ export { archiveParquet } from "./archive/parquet.ts";
10
11
  export { type Attestation, attest, isReadOnly, normalise, parseCommand } from "./attest/index.ts";
11
12
  export { type AuthorityFinding, authorityAt, authorityTimeline, automationSurprise, type Mode as AuthorityMode, type Span as AuthoritySpan, } from "./authority/index.ts";
13
+ export { badgeSvg, RECORD_STATES, type RecordState, recordBadge, recordState, } from "./badge/index.ts";
12
14
  export { type Invoice, type InvoiceLine, invoice, loadPlans, type Plan, type Plans, renderTaxInvoice, stripeSignatureOk, type TaxInvoice, type TaxInvoiceInput, taxInvoice, } from "./billing/index.ts";
13
15
  export { type AgentIdentity, checkAgent, sessionBom } from "./bom/index.ts";
14
16
  export { BlackboxApiError, type Client, type ClientOptions, client, type SessionQuery, } from "./client/index.ts";
15
17
  export { ART12_MIN_RETENTION_DAYS, type Art12Check, type Art12Report, art12Check, } from "./compliance/art12.ts";
16
- export { complianceFacts, complianceReport, type Facts, type Framework, type Report as ComplianceReport, renderReport, } from "./compliance/index.ts";
18
+ export { accuracyFact, complianceFacts, complianceReport, controlsFact, type Facts, type Framework, hallucinationFacts, type Report as ComplianceReport, renderReport, } from "./compliance/index.ts";
19
+ export { renderZaniiCompliance, type ZaniiComplianceReport, zaniiCompliance, } from "./compliance/zanii.ts";
20
+ export { type Constitution, type ConstitutionRule, constitutionHash, createConstitution, evaluateConstitution, governanceOf, verifyConstitution, } from "./constitution/index.ts";
17
21
  export { type CallCost, type CostReport, callMicroUsd, effectivePrice, formatAed, type LoadedPrices, loadPrices, type ModelPrice, type PriceTable, priceCall, priceFor, promptTokens, requestsOf, sessionCost, type Tokens, toAedFils, tokensOf, } from "./cost/index.ts";
22
+ export { agentCv, buildCv, cvHash, verifyCv } from "./cv/index.ts";
18
23
  export { type AuditRow, CORE_EVIDENCE, CORE_IDENTIFIERS, type Connector as AuditConnector, canaryIdentifier, checkAuditConnector, type DataFinding, type DataRules, dataClasses, dataFindings, dataFingerprint, dataMeta, dataScan, dataTopology, hasEvidence, type Identifier, type Lineage, lineage, luhn, normalizeValue, parseAuditLog, parseCsv, reconcileSystem, type SystemReport, type Topology, toolWitness, unevidenced, verifyToolWitness, witnessOf, } from "./data/index.ts";
19
24
  export { type Directive, type DirectiveItem, type DirectiveOptions, directives, fleetDirectives, } from "./directives/index.ts";
25
+ export { argumentLeaves, type Disclosure, type DisclosureEnvelope, discloseFields, disclosureEnvelope, verifyDisclosure, verifyEventDisclosure, } from "./disclosure/index.ts";
20
26
  export { checkDrill, drillReport, type Fault as DrillFault } from "./drills/index.ts";
21
27
  export { checkDuty, type DutyFinding, type DutyLimits, dutyFindings } from "./duty/index.ts";
28
+ export { openSegments, type SealedSegment } from "./encryption/index.ts";
29
+ export { type EvidencePack, type EvidencePackOptions, evidencePack, renderEvidencePack, } from "./evidence/index.ts";
30
+ export { buildEquivocationProof, compareViews, cosignLedgerSth, verifyEquivocationProof, verifyLedgerCosignature, } from "./federation/index.ts";
31
+ export { buildOwnerAttestation, buildPayment, CURRENCIES, FTA_WALL_ID, financeFindings, formatMoney, ftaPayload, parseMoney, paymentsOf, screenCounterparty, screeningPayload, verifyOwnerAttestation, verifyOwnerBinding, } from "./finance/index.ts";
22
32
  export { aggregateFindings, airworthiness, type Collision, collisions, didFromSeed, type FindingGroup, incidentReport, logbook, type Summary, sessionSummary, signatureOf, signatures, signCertificate, verifyCertificate, } from "./fleet/index.ts";
33
+ export { type AppealItem, type AppealPack, appealPack, decisionPayload, GOV_DECISION_KINDS, renderAppealPack, ruleConsistency, signSubjectClaim, subjectTag, verifyDecision, verifyFactors, verifySubjectClaim, } from "./gov/index.ts";
34
+ export { accessPayload, breakGlass, checkEpisodeTag, clinicianConfirmation, type EpisodeItem, episodeSeed, episodesPack, episodeTag, healthFindings, protocolTrail, recommendationHash, recommendationPayload, verifyCommitment, verifyHealthSignature, } from "./health/index.ts";
23
35
  export { attachBlackbox, BlackboxAgentHooks, BlackboxCallbackHandler, type BlackboxCallbacks, blackboxAgentHooks, blackboxCallbacks, blackboxMiddleware, type EventSink, llmIds, llmIdsOf, trackMemory, wrapAnthropic, wrapBedrock, wrapGemini, wrapOpenAI, } from "./hooks/index.ts";
24
36
  export { type AgentSink, BlackboxStoppedError, blackboxAgentMiddleware, blackboxHitl, type HitlRequest, } from "./hooks/langchain-agent.ts";
25
37
  export { blackboxCheckpointer } from "./hooks/langgraph-checkpoint.ts";
26
38
  export { MANAGED_END, MANAGED_START, managedBlock, protectedEdit } from "./hooks/protect.ts";
27
39
  export { type Investigation, investigation, renderInvestigation, } from "./investigate/index.ts";
28
40
  export { type McpWrapOptions, mcpWrap } from "./mcp-wrap/index.ts";
41
+ export { commitContent, memoryChain, memoryEntry, verifyMemoryContent, verifyMemoryEntry, } from "./memory/index.ts";
29
42
  export { type AmountUnit, anthropicStatement, type Baseline, baselines, type Connector, checkConnector, checkStatement, csvStatement, customStatement, decimalToMicroUsd, fuel, modelSpend, openaiStatement, pageParams, parseXml, reconcileBilling, requestFor, resolvePath, type Statement, } from "./money/index.ts";
30
- export { filingPack, type OccurrenceFacts, type OccurrenceFramework, type OccurrenceReport, occurrenceFacts, occurrenceReport, renderOccurrence, } from "./occurrence/index.ts";
43
+ export { deadlinesDue, filingPack, type OccurrenceFacts, type OccurrenceFramework, type OccurrenceReport, occurrenceFacts, occurrenceReport, renderOccurrence, } from "./occurrence/index.ts";
31
44
  export { ingestOcsf, type OcsfEvent, type OcsfVersion, ocsfLine, toOcsf } from "./ocsf/index.ts";
32
45
  export { toOtlp } from "./otlp/index.ts";
33
46
  export { checkIdentifier, checkPack, corePack, type PackEntry, packData, packFrameworks, } from "./packs/index.ts";
34
47
  export { type PolicyChange, type PolicyDelta, policyDelta } from "./policy/delta.ts";
35
48
  export { type Draft, type DraftGroup, policyDrafts } from "./policy/drafts.ts";
36
- export { audited, type CompiledPolicy, compilePolicy, type Decision, decide, loadPolicy, mcpToolHints, type Policy, policyFindings, type Rule, type ToolHints, } from "./policy/index.ts";
49
+ export { audited, type CompiledPolicy, compilePolicy, type Decision, decide, ENVIRONMENT, environmentOf, loadPolicy, mcpToolHints, type Policy, policyFindings, type Rule, type ToolHints, toolDefinitionHash, } from "./policy/index.ts";
50
+ export { fromZaniiPolicy, toZaniiPolicy } from "./policy/zanii.ts";
51
+ export { bindPqKey, PQ_ALG, pqAvailable, pqPublicKey, pqSeedOf, pqTransitionPayload, verifyPqBinding, } from "./pq/index.ts";
37
52
  export { calibration, FEATURES, features, MIN_EACH, type PrecogModel, precogFindings, precogReport, predict, prefixOf, splitOf, TARGET, train, } from "./precog/index.ts";
38
53
  export { type InterventionEvidence, interventionEvidence, interventionGain, } from "./precog/intervention.ts";
39
54
  export { activities, buildNormal, type NormalModel, type NormalScore, normalScore, normalThreshold, } from "./precog/normal.ts";
40
55
  export { type PreflightFinding, preflightFindings } from "./preflight/index.ts";
41
56
  export { type Rating, type TypeUnratedFinding, typeRatings, typeUnrated, } from "./ratings/index.ts";
42
57
  export { type Finding, type FindingCode, type Harness, loadLocal, type ReconcileOptions, RecordNotVerified, type Report, reconcile, } from "./reconcile/index.ts";
58
+ /** Canonical JSON (keys sorted, no whitespace, JavaScript number formatting), as hashed. */
59
+ export { canonical } from "./reconcile/shared.ts";
43
60
  export { cassette, requestKey, type Take } from "./replay/index.ts";
44
61
  export { ORPHAN_TEXT, repairToolCalls } from "./replay/repair.ts";
62
+ export { checkSearch, type SearchMatch, type SearchQuery, searchEvents } from "./search/index.ts";
45
63
  export { type DrainResult, drainSpools } from "./session/drain.ts";
46
64
  export { BlackboxSession, checkEgress, type EgressCheck, type FlightPlan, type LlmCallIds, type SessionError, type SessionOptions, type SessionState, type SessionStats, session, stableEventId, } from "./session/index.ts";
65
+ export { assembleSla, assessCompliance, buildSlaBody, signSla, slaHash, verifySla, } from "./sla/index.ts";
66
+ export { assembleSuccession, buildSuccessionBody, type Succession, type SuccessionBody, type SuccessionReason, signSuccession, successionHash, verifyLineage, verifySuccession, } from "./succession/index.ts";
47
67
  export { type TimestampReport, timestampRequest, verifyTimestamp, } from "./timestamp/index.ts";
68
+ export { resolveToken, resolveTokens, tokenFor } from "./tokens/index.ts";
48
69
  export { addCheckpointBody, type Cbor, cborDecode, cborEncode, checkpointText, consistencyProof, cosign, cosignMldsa, ed25519PublicKey, inclusionProof, keyRotationNote, leafHash, logKid, makeReceipt, merkleRoot, mldsaAvailable, mldsaPublicKey, noteVkey, parseAddCheckpoint, parseCheckpoint, parseVkey, RECEIPT_SUB, SESSION_CONTENT_TYPE, sessionStatement, signNote, signStatement, splitNote, statementEntry, subtreeMessage, transparentStatement, verifyConsistency, verifyCoseSign1, verifyCosignature, verifyInclusion, verifyKeyRotation, verifyNote, verifyReceipt, verifyTransparency, } from "./transparency/index.ts";
49
70
  export { type Compensation, checkCompensations, runUndo, type UndoFinding, type UndoStatus, type UndoStep, undoFindings, undoPlan, } from "./undo/index.ts";
50
71
  export * from "./verify/index.ts";
51
72
  export { VERSION } from "./version.ts";
73
+ export { checkOutput, WALLS, type Wall, wallFindings, wallManifestHash, } from "./walls/index.ts";
52
74
  export { type Conditions, type Sample, weather } from "./weather/index.ts";
53
75
  export { postReceipt, receiptFor, type Tree, workspaceTree } from "./workspace-receipt/index.ts";
package/dist/index.js CHANGED
@@ -1,55 +1,77 @@
1
1
  // Public API of @zanii/blackbox. Everything customers can import is re-exported here.
2
2
  // Keep this file in step with sdks/python/src/zanii_blackbox/__init__.py (the SDKs mirror each other).
3
- export { A2A_STREAMING, a2aMethod, a2aRequestMeta, a2aResponseMeta, agentCardDigest, agentCardPayload, verifyAgentCard, } from "./a2a/index.js";
3
+ export { A2A_STREAMING, a2aMethod, a2aRequestMeta, a2aResponseMeta, a2aRestMethod, a2aRestRequestMeta, a2aRestResponseMeta, agentCardDigest, agentCardPayload, gatewayCardKey, rewriteAgentCard, verifyAgentCard, } from "./a2a/index.js";
4
4
  export { causality, memoryXray } from "./agents/index.js";
5
5
  export { detectors, fingerprint } from "./analysis/detectors.js";
6
6
  export { FAULTS, faultOf } from "./analysis/faults.js";
7
- export { analyze, checkFlightPlan, checkpointReplay, dualWitness, eventsOf, findingKey, landing, OUTCOMES, rollup, waste, } from "./analysis/index.js";
7
+ export { analyze, answerClaims, answerCredential, answerRisk, answersOf, answerText, canonicalNumber, checkAgainstPacks, checkFlightPlan, checkpointReplay, detectorAccuracy, dualWitness, Evidence, eventsOf, factsIn, findingKey, groundingFindings, groundingRequest, HOLD_TRIGGERS, identifiersIn, judgeFindings, judgeRequest, landing, loadReferencePacks, modelGroundingFindings, normaliseValue, OUTCOMES, packsFor, parseGroundingAnswer, parseJudgeAnswer, referenceContext, rollup, schemaProblem, toolHallucinations, verifyAnswerCredential, waste, wilsonLow, } from "./analysis/index.js";
8
8
  export { MITRE_ATLAS, OWASP_ASI, TAXONOMY, taxonomyOf, } from "./analysis/taxonomy.js";
9
- export { approvalFindings } from "./approvals/index.js";
9
+ export { approvalConfirmation, approvalFindings, argsHash, verifyConfirmation, } from "./approvals/index.js";
10
10
  export { textWarnings } from "./approvals/warnings.js";
11
11
  export { archiveDigest, archiveEntry, archiveManifest, verifyArchive, } from "./archive/index.js";
12
+ export { archiveParquet } from "./archive/parquet.js";
12
13
  export { attest, isReadOnly, normalise, parseCommand } from "./attest/index.js";
13
14
  export { authorityAt, authorityTimeline, automationSurprise, } from "./authority/index.js";
15
+ export { badgeSvg, RECORD_STATES, recordBadge, recordState, } from "./badge/index.js";
14
16
  export { invoice, loadPlans, renderTaxInvoice, stripeSignatureOk, taxInvoice, } from "./billing/index.js";
15
17
  export { checkAgent, sessionBom } from "./bom/index.js";
16
18
  export { BlackboxApiError, client, } from "./client/index.js";
17
19
  export { ART12_MIN_RETENTION_DAYS, art12Check, } from "./compliance/art12.js";
18
- export { complianceFacts, complianceReport, renderReport, } from "./compliance/index.js";
20
+ export { accuracyFact, complianceFacts, complianceReport, controlsFact, hallucinationFacts, renderReport, } from "./compliance/index.js";
21
+ export { renderZaniiCompliance, zaniiCompliance, } from "./compliance/zanii.js";
22
+ export { constitutionHash, createConstitution, evaluateConstitution, governanceOf, verifyConstitution, } from "./constitution/index.js";
19
23
  export { callMicroUsd, effectivePrice, formatAed, loadPrices, priceCall, priceFor, promptTokens, requestsOf, sessionCost, toAedFils, tokensOf, } from "./cost/index.js";
24
+ export { agentCv, buildCv, cvHash, verifyCv } from "./cv/index.js";
20
25
  export { CORE_EVIDENCE, CORE_IDENTIFIERS, canaryIdentifier, checkAuditConnector, dataClasses, dataFindings, dataFingerprint, dataMeta, dataScan, dataTopology, hasEvidence, lineage, luhn, normalizeValue, parseAuditLog, parseCsv, reconcileSystem, toolWitness, unevidenced, verifyToolWitness, witnessOf, } from "./data/index.js";
21
26
  export { directives, fleetDirectives, } from "./directives/index.js";
27
+ export { argumentLeaves, discloseFields, disclosureEnvelope, verifyDisclosure, verifyEventDisclosure, } from "./disclosure/index.js";
22
28
  export { checkDrill, drillReport } from "./drills/index.js";
23
29
  export { checkDuty, dutyFindings } from "./duty/index.js";
30
+ export { openSegments } from "./encryption/index.js";
31
+ export { evidencePack, renderEvidencePack, } from "./evidence/index.js";
32
+ export { buildEquivocationProof, compareViews, cosignLedgerSth, verifyEquivocationProof, verifyLedgerCosignature, } from "./federation/index.js";
33
+ export { buildOwnerAttestation, buildPayment, CURRENCIES, FTA_WALL_ID, financeFindings, formatMoney, ftaPayload, parseMoney, paymentsOf, screenCounterparty, screeningPayload, verifyOwnerAttestation, verifyOwnerBinding, } from "./finance/index.js";
24
34
  export { aggregateFindings, airworthiness, collisions, didFromSeed, incidentReport, logbook, sessionSummary, signatureOf, signatures, signCertificate, verifyCertificate, } from "./fleet/index.js";
35
+ export { appealPack, decisionPayload, GOV_DECISION_KINDS, renderAppealPack, ruleConsistency, signSubjectClaim, subjectTag, verifyDecision, verifyFactors, verifySubjectClaim, } from "./gov/index.js";
36
+ export { accessPayload, breakGlass, checkEpisodeTag, clinicianConfirmation, episodeSeed, episodesPack, episodeTag, healthFindings, protocolTrail, recommendationHash, recommendationPayload, verifyCommitment, verifyHealthSignature, } from "./health/index.js";
25
37
  export { attachBlackbox, BlackboxAgentHooks, BlackboxCallbackHandler, blackboxAgentHooks, blackboxCallbacks, blackboxMiddleware, llmIds, llmIdsOf, trackMemory, wrapAnthropic, wrapBedrock, wrapGemini, wrapOpenAI, } from "./hooks/index.js";
26
38
  export { BlackboxStoppedError, blackboxAgentMiddleware, blackboxHitl, } from "./hooks/langchain-agent.js";
27
39
  export { blackboxCheckpointer } from "./hooks/langgraph-checkpoint.js";
28
40
  export { MANAGED_END, MANAGED_START, managedBlock, protectedEdit } from "./hooks/protect.js";
29
41
  export { investigation, renderInvestigation, } from "./investigate/index.js";
30
42
  export { mcpWrap } from "./mcp-wrap/index.js";
43
+ export { commitContent, memoryChain, memoryEntry, verifyMemoryContent, verifyMemoryEntry, } from "./memory/index.js";
31
44
  export { anthropicStatement, baselines, checkConnector, checkStatement, csvStatement, customStatement, decimalToMicroUsd, fuel, modelSpend, openaiStatement, pageParams, parseXml, reconcileBilling, requestFor, resolvePath, } from "./money/index.js";
32
- export { filingPack, occurrenceFacts, occurrenceReport, renderOccurrence, } from "./occurrence/index.js";
45
+ export { deadlinesDue, filingPack, occurrenceFacts, occurrenceReport, renderOccurrence, } from "./occurrence/index.js";
33
46
  export { ingestOcsf, ocsfLine, toOcsf } from "./ocsf/index.js";
34
47
  export { toOtlp } from "./otlp/index.js";
35
48
  export { checkIdentifier, checkPack, corePack, packData, packFrameworks, } from "./packs/index.js";
36
49
  export { policyDelta } from "./policy/delta.js";
37
50
  export { policyDrafts } from "./policy/drafts.js";
38
- export { audited, compilePolicy, decide, loadPolicy, mcpToolHints, policyFindings, } from "./policy/index.js";
51
+ export { audited, compilePolicy, decide, ENVIRONMENT, environmentOf, loadPolicy, mcpToolHints, policyFindings, toolDefinitionHash, } from "./policy/index.js";
52
+ export { fromZaniiPolicy, toZaniiPolicy } from "./policy/zanii.js";
53
+ export { bindPqKey, PQ_ALG, pqAvailable, pqPublicKey, pqSeedOf, pqTransitionPayload, verifyPqBinding, } from "./pq/index.js";
39
54
  export { calibration, FEATURES, features, MIN_EACH, precogFindings, precogReport, predict, prefixOf, splitOf, TARGET, train, } from "./precog/index.js";
40
55
  export { interventionEvidence, interventionGain, } from "./precog/intervention.js";
41
56
  export { activities, buildNormal, normalScore, normalThreshold, } from "./precog/normal.js";
42
57
  export { preflightFindings } from "./preflight/index.js";
43
58
  export { typeRatings, typeUnrated, } from "./ratings/index.js";
44
59
  export { loadLocal, RecordNotVerified, reconcile, } from "./reconcile/index.js";
60
+ /** Canonical JSON (keys sorted, no whitespace, JavaScript number formatting), as hashed. */
61
+ export { canonical } from "./reconcile/shared.js";
45
62
  export { cassette, requestKey } from "./replay/index.js";
46
63
  export { ORPHAN_TEXT, repairToolCalls } from "./replay/repair.js";
64
+ export { checkSearch, searchEvents } from "./search/index.js";
47
65
  export { drainSpools } from "./session/drain.js";
48
66
  export { BlackboxSession, checkEgress, session, stableEventId, } from "./session/index.js";
67
+ export { assembleSla, assessCompliance, buildSlaBody, signSla, slaHash, verifySla, } from "./sla/index.js";
68
+ export { assembleSuccession, buildSuccessionBody, signSuccession, successionHash, verifyLineage, verifySuccession, } from "./succession/index.js";
49
69
  export { timestampRequest, verifyTimestamp, } from "./timestamp/index.js";
70
+ export { resolveToken, resolveTokens, tokenFor } from "./tokens/index.js";
50
71
  export { addCheckpointBody, cborDecode, cborEncode, checkpointText, consistencyProof, cosign, cosignMldsa, ed25519PublicKey, inclusionProof, keyRotationNote, leafHash, logKid, makeReceipt, merkleRoot, mldsaAvailable, mldsaPublicKey, noteVkey, parseAddCheckpoint, parseCheckpoint, parseVkey, RECEIPT_SUB, SESSION_CONTENT_TYPE, sessionStatement, signNote, signStatement, splitNote, statementEntry, subtreeMessage, transparentStatement, verifyConsistency, verifyCoseSign1, verifyCosignature, verifyInclusion, verifyKeyRotation, verifyNote, verifyReceipt, verifyTransparency, } from "./transparency/index.js";
51
72
  export { checkCompensations, runUndo, undoFindings, undoPlan, } from "./undo/index.js";
52
73
  export * from "./verify/index.js";
53
74
  export { VERSION } from "./version.js";
75
+ export { checkOutput, WALLS, wallFindings, wallManifestHash, } from "./walls/index.js";
54
76
  export { weather } from "./weather/index.js";
55
77
  export { postReceipt, receiptFor, workspaceTree } from "./workspace-receipt/index.js";
@@ -0,0 +1,36 @@
1
+ type Obj = Record<string, unknown>;
2
+ /** Zanii's salted commitment to memory content. */
3
+ export declare function commitContent(content: string, salt?: string): {
4
+ commitment: string;
5
+ salt: string;
6
+ };
7
+ /** The entry was about `content`, given the salt kept at write time. */
8
+ export declare const verifyMemoryContent: (content: string, salt: string, commitment: string) => boolean;
9
+ /** Zanii's memory.write payload, after `prev` (the previous entry; null starts a chain). Keep the salt. */
10
+ export declare function memoryEntry(input: {
11
+ content: string;
12
+ ts: string;
13
+ kind?: string;
14
+ prev?: Obj | null;
15
+ salt?: string;
16
+ agent?: string;
17
+ tags?: string[];
18
+ }): {
19
+ payload: Obj;
20
+ salt: string;
21
+ };
22
+ /** Zanii's check of one entry: well formed, and its entry_hash matches. */
23
+ export declare function verifyMemoryEntry(payload: unknown): {
24
+ ok: boolean;
25
+ reasons: string[];
26
+ };
27
+ /** Walks entries in order: each checks, links to the one before and counts up by one. The first may continue a chain from elsewhere. */
28
+ export declare function memoryChain(entries: readonly unknown[]): {
29
+ ok: boolean;
30
+ length: number;
31
+ broken: {
32
+ index: number;
33
+ reason: string;
34
+ }[];
35
+ };
36
+ export {};