@zanii/blackbox 0.0.0-stage → 0.1.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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +109 -2
  3. package/dist/agents/index.d.ts +34 -0
  4. package/dist/agents/index.js +73 -0
  5. package/dist/analysis/detectors.d.ts +36 -0
  6. package/dist/analysis/detectors.js +339 -0
  7. package/dist/analysis/faults.d.ts +9 -0
  8. package/dist/analysis/faults.js +210 -0
  9. package/dist/analysis/index.d.ts +68 -0
  10. package/dist/analysis/index.js +388 -0
  11. package/dist/analysis/landing.d.ts +25 -0
  12. package/dist/analysis/landing.js +225 -0
  13. package/dist/analysis/memory.d.ts +13 -0
  14. package/dist/analysis/memory.js +33 -0
  15. package/dist/analysis/waste.d.ts +29 -0
  16. package/dist/analysis/waste.js +79 -0
  17. package/dist/approvals/index.d.ts +11 -0
  18. package/dist/approvals/index.js +27 -0
  19. package/dist/approvals/warnings.d.ts +2 -0
  20. package/dist/approvals/warnings.js +28 -0
  21. package/dist/attest/index.d.ts +17 -0
  22. package/dist/attest/index.js +106 -0
  23. package/dist/authority/index.d.ts +24 -0
  24. package/dist/authority/index.js +77 -0
  25. package/dist/billing/index.d.ts +99 -0
  26. package/dist/billing/index.js +174 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +1019 -0
  29. package/dist/client/index.d.ts +146 -0
  30. package/dist/client/index.js +210 -0
  31. package/dist/compliance/index.d.ts +41 -0
  32. package/dist/compliance/index.js +96 -0
  33. package/dist/cost/index.d.ts +133 -0
  34. package/dist/cost/index.js +293 -0
  35. package/dist/directives/index.d.ts +35 -0
  36. package/dist/directives/index.js +80 -0
  37. package/dist/drills/index.d.ts +43 -0
  38. package/dist/drills/index.js +101 -0
  39. package/dist/duty/index.d.ts +21 -0
  40. package/dist/duty/index.js +68 -0
  41. package/dist/fleet/index.d.ts +141 -0
  42. package/dist/fleet/index.js +454 -0
  43. package/dist/hooks/ai-sdk.d.ts +42 -0
  44. package/dist/hooks/ai-sdk.js +62 -0
  45. package/dist/hooks/claude-agent-sdk.d.ts +14 -0
  46. package/dist/hooks/claude-agent-sdk.js +70 -0
  47. package/dist/hooks/index.d.ts +7 -0
  48. package/dist/hooks/index.js +10 -0
  49. package/dist/hooks/langchain-agent.d.ts +69 -0
  50. package/dist/hooks/langchain-agent.js +163 -0
  51. package/dist/hooks/langchain.d.ts +41 -0
  52. package/dist/hooks/langchain.js +216 -0
  53. package/dist/hooks/langgraph-checkpoint.d.ts +12 -0
  54. package/dist/hooks/langgraph-checkpoint.js +73 -0
  55. package/dist/hooks/memory.d.ts +17 -0
  56. package/dist/hooks/memory.js +64 -0
  57. package/dist/hooks/openai-agents.d.ts +6 -0
  58. package/dist/hooks/openai-agents.js +40 -0
  59. package/dist/hooks/protect.d.ts +7 -0
  60. package/dist/hooks/protect.js +39 -0
  61. package/dist/hooks/providers.d.ts +16 -0
  62. package/dist/hooks/providers.js +149 -0
  63. package/dist/hooks/shared.d.ts +11 -0
  64. package/dist/hooks/shared.js +39 -0
  65. package/dist/index.d.ts +45 -0
  66. package/dist/index.js +47 -0
  67. package/dist/investigate/index.d.ts +66 -0
  68. package/dist/investigate/index.js +119 -0
  69. package/dist/mcp-server/index.d.ts +85 -0
  70. package/dist/mcp-server/index.js +216 -0
  71. package/dist/mcp-wrap/index.d.ts +17 -0
  72. package/dist/mcp-wrap/index.js +170 -0
  73. package/dist/money/index.d.ts +114 -0
  74. package/dist/money/index.js +622 -0
  75. package/dist/occurrence/index.d.ts +108 -0
  76. package/dist/occurrence/index.js +168 -0
  77. package/dist/ocsf/index.d.ts +22 -0
  78. package/dist/ocsf/index.js +168 -0
  79. package/dist/otlp/index.d.ts +24 -0
  80. package/dist/otlp/index.js +143 -0
  81. package/dist/packs/index.d.ts +40 -0
  82. package/dist/packs/index.js +217 -0
  83. package/dist/policy/delta.d.ts +11 -0
  84. package/dist/policy/delta.js +39 -0
  85. package/dist/policy/drafts.d.ts +34 -0
  86. package/dist/policy/drafts.js +129 -0
  87. package/dist/policy/index.d.ts +47 -0
  88. package/dist/policy/index.js +154 -0
  89. package/dist/precog/index.d.ts +96 -0
  90. package/dist/precog/index.js +167 -0
  91. package/dist/precog/intervention.d.ts +22 -0
  92. package/dist/precog/intervention.js +44 -0
  93. package/dist/precog/normal.d.ts +31 -0
  94. package/dist/precog/normal.js +89 -0
  95. package/dist/preflight/index.d.ts +11 -0
  96. package/dist/preflight/index.js +19 -0
  97. package/dist/ratings/index.d.ts +21 -0
  98. package/dist/ratings/index.js +48 -0
  99. package/dist/reconcile/claude-code.d.ts +19 -0
  100. package/dist/reconcile/claude-code.js +220 -0
  101. package/dist/reconcile/codex.d.ts +5 -0
  102. package/dist/reconcile/codex.js +191 -0
  103. package/dist/reconcile/index.d.ts +19 -0
  104. package/dist/reconcile/index.js +50 -0
  105. package/dist/reconcile/record.d.ts +49 -0
  106. package/dist/reconcile/record.js +225 -0
  107. package/dist/reconcile/shared.d.ts +65 -0
  108. package/dist/reconcile/shared.js +113 -0
  109. package/dist/replay/index.d.ts +11 -0
  110. package/dist/replay/index.js +64 -0
  111. package/dist/replay/repair.d.ts +10 -0
  112. package/dist/replay/repair.js +62 -0
  113. package/dist/session/drain.d.ts +13 -0
  114. package/dist/session/drain.js +35 -0
  115. package/dist/session/index.d.ts +256 -0
  116. package/dist/session/index.js +658 -0
  117. package/dist/undo/index.d.ts +45 -0
  118. package/dist/undo/index.js +212 -0
  119. package/dist/verify/anchor.d.ts +54 -0
  120. package/dist/verify/anchor.js +77 -0
  121. package/dist/verify/chain.d.ts +27 -0
  122. package/dist/verify/chain.js +105 -0
  123. package/dist/verify/envelope.d.ts +28 -0
  124. package/dist/verify/envelope.js +55 -0
  125. package/dist/verify/index.d.ts +3 -0
  126. package/dist/verify/index.js +3 -0
  127. package/dist/version.d.ts +1 -0
  128. package/dist/version.js +2 -0
  129. package/dist/weather/index.d.ts +24 -0
  130. package/dist/weather/index.js +45 -0
  131. package/dist/workspace-receipt/index.d.ts +15 -0
  132. package/dist/workspace-receipt/index.js +121 -0
  133. package/package.json +56 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,110 @@
1
- # Temporary Holding Version
1
+ # @zanii/blackbox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The TypeScript SDK for [Zanii Blackbox](https://zanii.agency), the flight recorder for AI agents.
4
+
5
+ Blackbox records every model call and tool call your agent makes, from a gateway that runs outside the agent's process. The records are hash-chained, so an edit or a deletion shows, and anchored as receipts that anyone can verify offline. This SDK is optional. It adds what only the agent knows (steps, its own tools, its checks, the outcome) as a second, independent record, and it reads and verifies what the gateway recorded.
6
+
7
+ ```sh
8
+ npm install @zanii/blackbox
9
+ ```
10
+
11
+ Node.js 24 or later. ESM only.
12
+
13
+ ## Before you start
14
+
15
+ You need a running Blackbox gateway, self-hosted with Docker, Kubernetes or from source. A hosted UAE region is planned; write to [info@zanii.agency](mailto:info@zanii.agency) for early access. The gateway holds your provider keys. Your agent gets a session token instead, and its model calls go through the gateway:
16
+
17
+ ```sh
18
+ export BLACKBOX_URL=https://blackbox.example.com
19
+ export BLACKBOX_ADMIN_KEY=... # or a tenant key (bbxt_...)
20
+ ```
21
+
22
+ ## Record a run
23
+
24
+ ```ts
25
+ import Anthropic from "@anthropic-ai/sdk";
26
+ import { session } from "@zanii/blackbox";
27
+
28
+ const s = await session({
29
+ url: process.env.BLACKBOX_URL!,
30
+ adminKey: process.env.BLACKBOX_ADMIN_KEY!,
31
+ label: "refund-agent",
32
+ budgetUsd: "2.00",
33
+ flightPlan: {
34
+ objective: "Process today's refund queue",
35
+ expected_tools: ["lookup_order", "issue_refund"],
36
+ },
37
+ });
38
+
39
+ // Model calls go through the gateway with the session's token, never your provider key.
40
+ const anthropic = new Anthropic({ baseURL: `${process.env.BLACKBOX_URL}/anthropic`, apiKey: s.token });
41
+
42
+ s.step("load queue");
43
+ s.toolCall("lookup_order", { order: 8812 });
44
+ s.toolResult("lookup_order", { ok: true });
45
+ s.verify("amount-matches-invoice", true); // your own check, recorded as evidence
46
+
47
+ // A risky tool waits for a person, who sees the arguments in the cockpit.
48
+ const answer = await s.requestApproval("issue_refund", {
49
+ args: { order: 8812, amount_aed: "1250.00" },
50
+ reason: "Damaged on delivery",
51
+ });
52
+ if (answer === "approved") {
53
+ // issue the refund
54
+ }
55
+
56
+ await s.close("success");
57
+ ```
58
+
59
+ `answer` is only `"approved"` when a person approved it. `"rejected"`, `"timeout"` and `"error"` all mean don't run the tool.
60
+
61
+ ## What the SDK guarantees
62
+
63
+ - **It never throws into your agent.** If the gateway is down, the session keeps recording to disk and reports the problem in `s.stats.lastError`.
64
+ - **It loses nothing it accepted.** Every event is written to a local spool before it is sent, numbered without gaps, and resent until the gateway confirms it. After a crash, `blackbox drain` sends what's left.
65
+ - **It stays out of the way.** Recording is non-blocking with bounded memory. A recorded call costs about 0.3 ms (measured over 20,000 calls on a laptop); shipping happens in the background.
66
+ - **It has no other runtime dependencies** besides the Zanii core libraries.
67
+
68
+ ## Frameworks
69
+
70
+ | Framework | Use |
71
+ |---|---|
72
+ | LangChain / LangGraph | `blackboxCallbacks(s)`, `blackboxAgentMiddleware(s)`, `blackboxCheckpointer(saver, s)`, and `blackboxHitl` for human-in-the-loop |
73
+ | OpenAI Agents SDK | `attachBlackbox(runner, s)` |
74
+ | Claude Agent SDK | `blackboxAgentHooks(s)` |
75
+ | Vercel AI SDK | `blackboxMiddleware(s)` |
76
+ | Provider clients | `wrapAnthropic`, `wrapOpenAI`, `wrapGemini`, `wrapBedrock` link each call to the gateway's record |
77
+
78
+ ## Command line
79
+
80
+ The package installs a `blackbox` command:
81
+
82
+ ```sh
83
+ blackbox sessions # the newest sessions, and whether each record verifies
84
+ blackbox tail ses_... # follow a session live
85
+ blackbox export ses_... --out run.json
86
+ blackbox verify run.json # verify an audit bundle offline, anywhere
87
+ blackbox reconcile ... # check an agent's own logs against the gateway's record
88
+ blackbox mcp-wrap --server files -- node server.js # record a local stdio MCP server
89
+ blackbox drain # send spooled events left by a stopped agent
90
+ ```
91
+
92
+ ## Verify a record offline
93
+
94
+ ```ts
95
+ import { verifyBundle } from "@zanii/blackbox";
96
+ ```
97
+
98
+ An audit bundle carries the events, the chain and the anchors. Checking it needs no account and no network, so an auditor or a regulator can check it independently.
99
+
100
+ ## Also in Python
101
+
102
+ [`zanii-blackbox`](https://pypi.org/project/zanii-blackbox/) has the same API in snake_case. Both SDKs must produce the same output on the same shared test vectors.
103
+
104
+ ## Support
105
+
106
+ - Website: [zanii.agency](https://zanii.agency)
107
+ - Email: [info@zanii.agency](mailto:info@zanii.agency)
108
+ - Security reports: [info@zanii.agency](mailto:info@zanii.agency), privately, not in a public issue
109
+
110
+ Licensed under [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0).
@@ -0,0 +1,34 @@
1
+ import type { Bodies } from "../reconcile/record.ts";
2
+ /** spec/agents.md §2: `revoked` = ids revoked elsewhere (other sessions of the tenant). */
3
+ export declare function memoryXray(lines: readonly string[], bodies: Bodies, revoked?: readonly string[]): {
4
+ writes: number;
5
+ reads: number;
6
+ revoked: string[];
7
+ stale_reads: {
8
+ seq: number;
9
+ memory_id: string;
10
+ }[];
11
+ };
12
+ /** spec/agents.md §3. */
13
+ export declare function causality(records: ReadonlyArray<readonly string[]>): {
14
+ root: string | null;
15
+ sessions: {
16
+ session_id: string;
17
+ parent: string | null;
18
+ depth: number;
19
+ started_at: string;
20
+ handoff: string | null;
21
+ findings: {
22
+ advisory: number;
23
+ caution: number;
24
+ warning: number;
25
+ };
26
+ }[];
27
+ root_cause: {
28
+ session_id: string;
29
+ seq: number;
30
+ ts: string;
31
+ code: string;
32
+ severity: string;
33
+ }[];
34
+ };
@@ -0,0 +1,73 @@
1
+ // Memory X-ray and multi-agent causality (spec/agents.md). Mirrors sdks/python/src/zanii_blackbox/agents.py.
2
+ import { eventsOf } from "../analysis/index.js";
3
+ import { memoryXrayOf } from "../analysis/memory.js";
4
+ /** spec/agents.md §2: `revoked` = ids revoked elsewhere (other sessions of the tenant). */
5
+ export function memoryXray(lines, bodies, revoked = []) {
6
+ return memoryXrayOf(eventsOf(lines, bodies), revoked);
7
+ }
8
+ const RANK = { warning: 0, caution: 1 };
9
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
10
+ /** spec/agents.md §3. */
11
+ export function causality(records) {
12
+ const info = records
13
+ .filter((r) => r.length > 0)
14
+ .map((lines) => {
15
+ const events = lines.map((l) => JSON.parse(l));
16
+ const open = events[0];
17
+ const findings = { advisory: 0, caution: 0, warning: 0 };
18
+ const found = [];
19
+ for (const e of events)
20
+ if (e.kind === "finding") {
21
+ const sev = String(e.meta.severity);
22
+ if (sev in findings)
23
+ findings[sev]++;
24
+ if (sev in RANK)
25
+ found.push({
26
+ session_id: open.session_id,
27
+ seq: e.seq,
28
+ ts: e.ts,
29
+ code: String(e.meta.code),
30
+ severity: sev,
31
+ });
32
+ }
33
+ return {
34
+ session_id: open.session_id,
35
+ parent: typeof open.meta.parent === "string" ? open.meta.parent : null,
36
+ started_at: open.ts,
37
+ handoff: typeof open.meta.handoff === "string" ? open.meta.handoff : null,
38
+ findings,
39
+ found,
40
+ };
41
+ });
42
+ const ids = new Set(info.map((i) => i.session_id));
43
+ const children = new Map();
44
+ for (const i of info) {
45
+ const p = i.parent !== null && ids.has(i.parent) ? i.parent : null;
46
+ children.set(p, [...(children.get(p) ?? []), i]);
47
+ }
48
+ const byStart = (a, b) => cmp(a.started_at, b.started_at) || cmp(a.session_id, b.session_id);
49
+ const roots = [...(children.get(null) ?? [])].sort(byStart);
50
+ const sessions = [];
51
+ const visit = (i, depth) => {
52
+ sessions.push({
53
+ session_id: i.session_id,
54
+ parent: i.parent,
55
+ depth,
56
+ started_at: i.started_at,
57
+ handoff: i.handoff,
58
+ findings: i.findings,
59
+ });
60
+ for (const c of [...(children.get(i.session_id) ?? [])].sort(byStart))
61
+ visit(c, depth + 1);
62
+ };
63
+ for (const r of roots)
64
+ visit(r, 0);
65
+ const rootCause = info
66
+ .flatMap((i) => i.found)
67
+ .sort((a, b) => cmp(a.ts, b.ts) ||
68
+ RANK[a.severity] - RANK[b.severity] ||
69
+ cmp(a.session_id, b.session_id) ||
70
+ a.seq - b.seq)
71
+ .slice(0, 10);
72
+ return { root: roots[0]?.session_id ?? null, sessions, root_cause: rootCause };
73
+ }
@@ -0,0 +1,36 @@
1
+ import { type LoadedPrices } from "../cost/index.ts";
2
+ import { type Bodies, type Call } from "../reconcile/record.ts";
3
+ import type { Finding } from "./index.ts";
4
+ export interface DetectorOptions {
5
+ bodies: Bodies;
6
+ now: number;
7
+ prices?: LoadedPrices;
8
+ budgetMicroUsd?: number;
9
+ }
10
+ /** T1.4: equivalent arguments give the same fingerprint (volatile keys dropped, paths normalised). */
11
+ export declare function fingerprint(args: unknown): string;
12
+ export interface ToolCall {
13
+ seq: number;
14
+ tool: string;
15
+ fp: string;
16
+ id?: string;
17
+ /** The call's arguments as the model sent them. */
18
+ args?: unknown;
19
+ }
20
+ export declare function toolCallsOf(calls: Call[]): ToolCall[];
21
+ /**
22
+ * Tool results the agent sent back: Anthropic tool_result blocks and Chat Completions `role: "tool"`
23
+ * messages (the first carrying each id), MCP tool.result. Chat Completions has no error flag, so its
24
+ * results count as not errors.
25
+ */
26
+ export declare function toolResultsOf(calls: Call[], lines: readonly string[]): Array<{
27
+ seq: number;
28
+ error: boolean;
29
+ id?: string;
30
+ }>;
31
+ export declare function detectors(lines: readonly string[], options: DetectorOptions): Finding[];
32
+ /** The latest budget and call limit a person granted (spec/approvals.md §4), if any. */
33
+ export declare function grantedLimits(lines: readonly string[]): {
34
+ budget?: number;
35
+ calls?: number;
36
+ };