@cello-protocol/cli 0.0.306 → 0.0.308

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 (234) hide show
  1. package/.claude-plugin/marketplace.json +15 -0
  2. package/README.md +107 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +602 -0
  5. package/dist/daemon/account-page-assets.d.ts +4 -0
  6. package/dist/daemon/account-page-assets.js +160 -0
  7. package/dist/daemon/account-page.d.ts +14 -0
  8. package/dist/daemon/account-page.js +104 -0
  9. package/dist/daemon/address.d.ts +10 -0
  10. package/dist/daemon/address.js +34 -0
  11. package/dist/daemon/away.d.ts +31 -0
  12. package/dist/daemon/away.js +65 -0
  13. package/dist/daemon/channel-store.d.ts +112 -0
  14. package/dist/daemon/channel-store.js +284 -0
  15. package/dist/daemon/channels.d.ts +46 -0
  16. package/dist/daemon/channels.js +1049 -0
  17. package/dist/daemon/contacts.d.ts +26 -0
  18. package/dist/daemon/contacts.js +74 -0
  19. package/dist/daemon/engine.d.ts +82 -0
  20. package/dist/daemon/engine.js +2882 -0
  21. package/dist/daemon/errors.d.ts +5 -0
  22. package/dist/daemon/errors.js +16 -0
  23. package/dist/daemon/governance.d.ts +66 -0
  24. package/dist/daemon/governance.js +514 -0
  25. package/dist/daemon/guards.d.ts +36 -0
  26. package/dist/daemon/guards.js +140 -0
  27. package/dist/daemon/issuer-client.d.ts +56 -0
  28. package/dist/daemon/issuer-client.js +143 -0
  29. package/dist/daemon/link.d.ts +30 -0
  30. package/dist/daemon/link.js +191 -0
  31. package/dist/daemon/log.d.ts +1 -0
  32. package/dist/daemon/log.js +4 -0
  33. package/dist/daemon/main.d.ts +1 -0
  34. package/dist/daemon/main.js +513 -0
  35. package/dist/daemon/paths.d.ts +6 -0
  36. package/dist/daemon/paths.js +21 -0
  37. package/dist/daemon/pii.d.ts +24 -0
  38. package/dist/daemon/pii.js +147 -0
  39. package/dist/daemon/policy-cadence.d.ts +33 -0
  40. package/dist/daemon/policy-cadence.js +59 -0
  41. package/dist/daemon/policy-proposals.d.ts +41 -0
  42. package/dist/daemon/policy-proposals.js +83 -0
  43. package/dist/daemon/policy-store.d.ts +47 -0
  44. package/dist/daemon/policy-store.js +144 -0
  45. package/dist/daemon/presented.d.ts +36 -0
  46. package/dist/daemon/presented.js +94 -0
  47. package/dist/daemon/rate-limit.d.ts +17 -0
  48. package/dist/daemon/rate-limit.js +44 -0
  49. package/dist/daemon/reach.d.ts +62 -0
  50. package/dist/daemon/reach.js +204 -0
  51. package/dist/daemon/screening.d.ts +97 -0
  52. package/dist/daemon/screening.js +362 -0
  53. package/dist/daemon/settings.d.ts +125 -0
  54. package/dist/daemon/settings.js +73 -0
  55. package/dist/daemon/signal-rules.d.ts +55 -0
  56. package/dist/daemon/signal-rules.js +127 -0
  57. package/dist/daemon/signal-store.d.ts +53 -0
  58. package/dist/daemon/signal-store.js +114 -0
  59. package/dist/daemon/store.d.ts +189 -0
  60. package/dist/daemon/store.js +477 -0
  61. package/dist/daemon/tiers.d.ts +14 -0
  62. package/dist/daemon/tiers.js +9 -0
  63. package/dist/daemon/wallet.d.ts +73 -0
  64. package/dist/daemon/wallet.js +429 -0
  65. package/dist/daemon/who-label.d.ts +3 -0
  66. package/dist/daemon/who-label.js +11 -0
  67. package/dist/guidance.d.ts +39 -0
  68. package/dist/guidance.js +98 -0
  69. package/dist/hermes-bridge.d.ts +34 -0
  70. package/dist/hermes-bridge.js +223 -0
  71. package/dist/install-mcp.d.ts +6 -0
  72. package/dist/install-mcp.js +77 -0
  73. package/dist/ipc/client.d.ts +18 -0
  74. package/dist/ipc/client.js +107 -0
  75. package/dist/ipc/operations.d.ts +30 -0
  76. package/dist/ipc/operations.js +846 -0
  77. package/dist/ipc/protocol.d.ts +21 -0
  78. package/dist/ipc/protocol.js +1 -0
  79. package/dist/issuer-list-sign.d.ts +12 -0
  80. package/dist/issuer-list-sign.js +43 -0
  81. package/dist/local-operations.d.ts +2 -0
  82. package/dist/local-operations.js +73 -0
  83. package/dist/mcp-tools.d.ts +14 -0
  84. package/dist/mcp-tools.js +45 -0
  85. package/dist/mcp.d.ts +2 -0
  86. package/dist/mcp.js +160 -0
  87. package/dist/protocol/aead.d.ts +4 -0
  88. package/dist/protocol/aead.js +35 -0
  89. package/dist/protocol/cbor.d.ts +40 -0
  90. package/dist/protocol/cbor.js +106 -0
  91. package/dist/protocol/chain.d.ts +44 -0
  92. package/dist/protocol/chain.js +126 -0
  93. package/dist/protocol/channel.d.ts +153 -0
  94. package/dist/protocol/channel.js +298 -0
  95. package/dist/protocol/encode.d.ts +6 -0
  96. package/dist/protocol/encode.js +21 -0
  97. package/dist/protocol/identity.d.ts +27 -0
  98. package/dist/protocol/identity.js +94 -0
  99. package/dist/protocol/issuer-list.d.ts +56 -0
  100. package/dist/protocol/issuer-list.js +193 -0
  101. package/dist/protocol/issuer-roots.d.ts +6 -0
  102. package/dist/protocol/issuer-roots.js +10 -0
  103. package/dist/protocol/key-agreement.d.ts +20 -0
  104. package/dist/protocol/key-agreement.js +88 -0
  105. package/dist/protocol/merkle.d.ts +16 -0
  106. package/dist/protocol/merkle.js +166 -0
  107. package/dist/protocol/ml-dsa.d.ts +28 -0
  108. package/dist/protocol/ml-dsa.js +58 -0
  109. package/dist/protocol/ml-kem.d.ts +14 -0
  110. package/dist/protocol/ml-kem.js +57 -0
  111. package/dist/protocol/pq-errors.d.ts +9 -0
  112. package/dist/protocol/pq-errors.js +23 -0
  113. package/dist/protocol/pq-warnings.d.ts +1 -0
  114. package/dist/protocol/pq-warnings.js +18 -0
  115. package/dist/protocol/presented-signals.d.ts +17 -0
  116. package/dist/protocol/presented-signals.js +92 -0
  117. package/dist/protocol/salt.d.ts +5 -0
  118. package/dist/protocol/salt.js +47 -0
  119. package/dist/protocol/seal.d.ts +58 -0
  120. package/dist/protocol/seal.js +220 -0
  121. package/dist/protocol/signal.d.ts +54 -0
  122. package/dist/protocol/signal.js +266 -0
  123. package/dist/protocol/status.d.ts +41 -0
  124. package/dist/protocol/status.js +64 -0
  125. package/dist/protocol/structures.d.ts +359 -0
  126. package/dist/protocol/structures.js +296 -0
  127. package/dist/protocol/transcript.d.ts +61 -0
  128. package/dist/protocol/transcript.js +319 -0
  129. package/dist/protocol/wire.d.ts +212 -0
  130. package/dist/protocol/wire.js +161 -0
  131. package/dist/require-node.d.ts +1 -0
  132. package/dist/require-node.js +10 -0
  133. package/dist/screener/affordance.d.ts +1 -0
  134. package/dist/screener/affordance.js +2 -0
  135. package/dist/screener/classifier-selfcheck.d.ts +29 -0
  136. package/dist/screener/classifier-selfcheck.js +56 -0
  137. package/dist/screener/exfil.d.ts +11 -0
  138. package/dist/screener/exfil.js +45 -0
  139. package/dist/screener/gitleaks-rules.d.ts +9 -0
  140. package/dist/screener/gitleaks-rules.js +226 -0
  141. package/dist/screener/inbound.d.ts +25 -0
  142. package/dist/screener/inbound.js +102 -0
  143. package/dist/screener/injection-classifier-onnx.d.ts +20 -0
  144. package/dist/screener/injection-classifier-onnx.js +89 -0
  145. package/dist/screener/injection-classifier-wasm.d.ts +2 -0
  146. package/dist/screener/injection-classifier-wasm.js +97 -0
  147. package/dist/screener/injection-patterns.d.ts +8 -0
  148. package/dist/screener/injection-patterns.js +48 -0
  149. package/dist/screener/injection-windows.d.ts +9 -0
  150. package/dist/screener/injection-windows.js +37 -0
  151. package/dist/screener/language.d.ts +15 -0
  152. package/dist/screener/language.js +71 -0
  153. package/dist/screener/linear-regex.d.ts +8 -0
  154. package/dist/screener/linear-regex.js +27 -0
  155. package/dist/screener/model-installer.d.ts +14 -0
  156. package/dist/screener/model-installer.js +61 -0
  157. package/dist/screener/outbound.d.ts +19 -0
  158. package/dist/screener/outbound.js +62 -0
  159. package/dist/screener/sanitize.d.ts +44 -0
  160. package/dist/screener/sanitize.js +361 -0
  161. package/dist/screener/scan-variants.d.ts +5 -0
  162. package/dist/screener/scan-variants.js +146 -0
  163. package/dist/screener/screener-model-manifest.d.ts +16 -0
  164. package/dist/screener/screener-model-manifest.js +20 -0
  165. package/dist/screener/screener-state.d.ts +29 -0
  166. package/dist/screener/screener-state.js +119 -0
  167. package/dist/screener/secrets.d.ts +18 -0
  168. package/dist/screener/secrets.js +84 -0
  169. package/dist/screener/worker.d.ts +6 -0
  170. package/dist/screener/worker.js +83 -0
  171. package/dist/setup.d.ts +9 -0
  172. package/dist/setup.js +259 -0
  173. package/dist/shipped-issuer-list.d.ts +1 -0
  174. package/dist/shipped-issuer-list.js +3 -0
  175. package/dist/signals-text.d.ts +46 -0
  176. package/dist/signals-text.js +81 -0
  177. package/dist/verify-seal.d.ts +9 -0
  178. package/dist/verify-seal.js +30 -0
  179. package/hermes/plugin/__init__.py +1066 -0
  180. package/hermes/plugin/plugin.yaml +30 -0
  181. package/hermes/skills/cello-bridge-setup/SKILL.md +48 -0
  182. package/hermes/skills/cello-policy/SKILL.md +44 -0
  183. package/package.json +48 -16
  184. package/plugins/cello/.claude-plugin/plugin.json +19 -0
  185. package/plugins/cello/.mcp.json +7 -0
  186. package/plugins/cello/skills/cello/SKILL.md +117 -0
  187. package/dist/arg-parse.d.ts +0 -19
  188. package/dist/arg-parse.d.ts.map +0 -1
  189. package/dist/arg-parse.js +0 -29
  190. package/dist/arg-parse.js.map +0 -1
  191. package/dist/bin/cello.d.ts +0 -15
  192. package/dist/bin/cello.d.ts.map +0 -1
  193. package/dist/bin/cello.js +0 -110
  194. package/dist/bin/cello.js.map +0 -1
  195. package/dist/cli-args.d.ts +0 -62
  196. package/dist/cli-args.d.ts.map +0 -1
  197. package/dist/cli-args.js +0 -129
  198. package/dist/cli-args.js.map +0 -1
  199. package/dist/commands.d.ts +0 -196
  200. package/dist/commands.d.ts.map +0 -1
  201. package/dist/commands.js +0 -1544
  202. package/dist/commands.js.map +0 -1
  203. package/dist/hermes/assets.d.ts +0 -41
  204. package/dist/hermes/assets.d.ts.map +0 -1
  205. package/dist/hermes/assets.js +0 -2281
  206. package/dist/hermes/assets.js.map +0 -1
  207. package/dist/hermes/install-hermes.d.ts +0 -50
  208. package/dist/hermes/install-hermes.d.ts.map +0 -1
  209. package/dist/hermes/install-hermes.js +0 -232
  210. package/dist/hermes/install-hermes.js.map +0 -1
  211. package/dist/json-out.d.ts +0 -41
  212. package/dist/json-out.d.ts.map +0 -1
  213. package/dist/json-out.js +0 -59
  214. package/dist/json-out.js.map +0 -1
  215. package/dist/node-runtime-guard-init.d.ts +0 -6
  216. package/dist/node-runtime-guard-init.d.ts.map +0 -1
  217. package/dist/node-runtime-guard-init.js +0 -7
  218. package/dist/node-runtime-guard-init.js.map +0 -1
  219. package/dist/node-runtime-guard.d.ts +0 -48
  220. package/dist/node-runtime-guard.d.ts.map +0 -1
  221. package/dist/node-runtime-guard.js +0 -79
  222. package/dist/node-runtime-guard.js.map +0 -1
  223. package/dist/parity-commands.d.ts +0 -427
  224. package/dist/parity-commands.d.ts.map +0 -1
  225. package/dist/parity-commands.js +0 -953
  226. package/dist/parity-commands.js.map +0 -1
  227. package/dist/registry.d.ts +0 -120
  228. package/dist/registry.d.ts.map +0 -1
  229. package/dist/registry.js +0 -2169
  230. package/dist/registry.js.map +0 -1
  231. package/dist/screener-commands.d.ts +0 -85
  232. package/dist/screener-commands.d.ts.map +0 -1
  233. package/dist/screener-commands.js +0 -313
  234. package/dist/screener-commands.js.map +0 -1
@@ -0,0 +1,147 @@
1
+ import { createHash } from "node:crypto";
2
+ const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
3
+ const IP_RE = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
4
+ const SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
5
+ // A card number starts 2 to 6. A millisecond timestamp starts 1, and passes the checksum one time in ten.
6
+ const CC_RE = /\b[2-6](?:[ -]?\d){12,18}\b/g;
7
+ const PHONE_RE = /\+?\d[\d\s().-]{7,}\d/g;
8
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?)?/;
9
+ function isPlausiblePhone(value) {
10
+ const trimmed = value.trim();
11
+ const remainder = trimmed.replace(ISO_DATE_RE, "");
12
+ const digits = remainder.replace(/\D/g, "");
13
+ return digits.length >= 7;
14
+ }
15
+ const LONG_HEX_RE = /\b[0-9a-fA-F]{32,}\b/g;
16
+ const UUID_RE = /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g;
17
+ const HEX_LETTER_RE = /[a-fA-F]/;
18
+ function maskHashes(text) {
19
+ const mask = (m) => (HEX_LETTER_RE.test(m) ? "_".repeat(m.length) : m);
20
+ return text.replace(UUID_RE, mask).replace(LONG_HEX_RE, mask);
21
+ }
22
+ function flagIdFor(category, value) {
23
+ return createHash("sha256").update(`${category}:${value}`).digest("hex").slice(0, 12);
24
+ }
25
+ function luhnValid(digits) {
26
+ let sum = 0;
27
+ let alt = false;
28
+ for (let i = digits.length - 1; i >= 0; i--) {
29
+ let d = digits.charCodeAt(i) - 48;
30
+ if (d < 0 || d > 9)
31
+ return false;
32
+ if (alt) {
33
+ d *= 2;
34
+ if (d > 9)
35
+ d -= 9;
36
+ }
37
+ sum += d;
38
+ alt = !alt;
39
+ }
40
+ return digits.length > 0 && sum % 10 === 0;
41
+ }
42
+ function parseIpv4Octets(value) {
43
+ const parts = value.split(".");
44
+ if (parts.length !== 4)
45
+ return null;
46
+ const octets = [];
47
+ for (const p of parts) {
48
+ const n = Number(p);
49
+ if (p.length === 0 || n < 0 || n > 255)
50
+ return null;
51
+ octets.push(n);
52
+ }
53
+ return octets;
54
+ }
55
+ function isNonIdentifyingIpv4(value) {
56
+ const octets = parseIpv4Octets(value);
57
+ if (!octets)
58
+ return false;
59
+ if (octets[0] === 127)
60
+ return true;
61
+ if (octets[0] === 0 && octets[1] === 0 && octets[2] === 0 && octets[3] === 0)
62
+ return true;
63
+ if (octets[0] === 255 && octets[1] === 255 && octets[2] === 255 && octets[3] === 255)
64
+ return true;
65
+ return false;
66
+ }
67
+ function validIp(value) {
68
+ return parseIpv4Octets(value) !== null && !isNonIdentifyingIpv4(value);
69
+ }
70
+ function normalizeEmail(v) { return v.toLowerCase(); }
71
+ function normalizePhone(v) { return v.replace(/\D/g, ""); }
72
+ function normalizeForWhitelist(category, value) {
73
+ if (category === "pii:email")
74
+ return normalizeEmail(value);
75
+ if (category === "pii:phone")
76
+ return normalizePhone(value);
77
+ return value;
78
+ }
79
+ export class OutboundPIIScreener {
80
+ #whitelist;
81
+ #bulkThreshold;
82
+ #cumulativeThreshold;
83
+ #checkEmail;
84
+ #checkPhone;
85
+ #sessionDistinct = new Map();
86
+ constructor(opts) {
87
+ this.#whitelist = new Set([
88
+ ...opts.whitelist.map(normalizeEmail),
89
+ ...opts.whitelist.map(normalizePhone).filter((p) => p.length > 0),
90
+ ]);
91
+ this.#bulkThreshold = opts.bulkThreshold ?? 5;
92
+ this.#cumulativeThreshold = opts.cumulativeThreshold ?? 20;
93
+ this.#checkEmail = opts.checkEmail ?? true;
94
+ this.#checkPhone = opts.checkPhone ?? true;
95
+ }
96
+ screen(content, sessionId) {
97
+ const text = new TextDecoder("utf-8", { fatal: false }).decode(content);
98
+ const candidates = [];
99
+ const collect = (sourceText, re, category, priority, accept) => {
100
+ for (const m of sourceText.matchAll(re)) {
101
+ const value = m[0];
102
+ if (!accept(value))
103
+ continue;
104
+ candidates.push({ start: m.index ?? 0, end: (m.index ?? 0) + value.length, category, value, priority });
105
+ }
106
+ };
107
+ if (this.#checkEmail)
108
+ collect(text, EMAIL_RE, "pii:email", 0, () => true);
109
+ collect(text, IP_RE, "pii:ip", 1, validIp);
110
+ collect(text, SSN_RE, "pii:ssn", 2, () => true);
111
+ collect(text, CC_RE, "pii:credit_card", 3, (v) => luhnValid(v.replace(/[^0-9]/g, "")));
112
+ if (this.#checkPhone) {
113
+ const phoneText = maskHashes(text.replace(IP_RE, (m) => (parseIpv4Octets(m) !== null ? "_".repeat(m.length) : m)));
114
+ collect(phoneText, PHONE_RE, "pii:phone", 4, isPlausiblePhone);
115
+ }
116
+ candidates.sort((a, b) => a.priority - b.priority || a.start - b.start);
117
+ const taken = [];
118
+ const accepted = [];
119
+ for (const c of candidates) {
120
+ if (taken.some(([s, e]) => c.start < e && c.end > s))
121
+ continue;
122
+ taken.push([c.start, c.end]);
123
+ accepted.push(c);
124
+ }
125
+ const byKey = new Map();
126
+ for (const c of accepted) {
127
+ if (this.#whitelist.has(normalizeForWhitelist(c.category, c.value)))
128
+ continue;
129
+ const key = `${c.category}:${c.value}`;
130
+ if (!byKey.has(key))
131
+ byKey.set(key, { category: c.category, value: c.value, flagId: flagIdFor(c.category, c.value) });
132
+ }
133
+ const events = [...byKey.values()];
134
+ if (events.length === 0)
135
+ return { disposition: "allow", events: [], count: 0 };
136
+ let distinct = this.#sessionDistinct.get(sessionId);
137
+ if (!distinct) {
138
+ distinct = new Set();
139
+ this.#sessionDistinct.set(sessionId, distinct);
140
+ }
141
+ for (const e of events)
142
+ distinct.add(`${e.category}:${e.value}`);
143
+ const count = events.length;
144
+ const bulk = count >= this.#bulkThreshold || distinct.size >= this.#cumulativeThreshold;
145
+ return { disposition: "warn", severity: bulk ? "bulk" : "normal", events, count };
146
+ }
147
+ }
@@ -0,0 +1,33 @@
1
+ import type { PolicyStore, PolicyType, ResolvedPolicy } from "./policy-store.ts";
2
+ export type AttachReason = "first" | "changed" | "cadence";
3
+ export interface PolicyField {
4
+ type: PolicyType;
5
+ level: ResolvedPolicy["level"];
6
+ text: string;
7
+ }
8
+ export declare const POLICY_ERROR_TEXT: string;
9
+ export declare class PolicyCadence {
10
+ #private;
11
+ shouldAttach(key: string, resolved: ResolvedPolicy, deliveredCount: number): AttachReason | null;
12
+ }
13
+ export declare function admissionPolicyField(a: {
14
+ store: PolicyStore;
15
+ agentId: Uint8Array;
16
+ peerHex: string;
17
+ tierName: string;
18
+ }): {
19
+ policy?: PolicyField;
20
+ policy_error?: string;
21
+ };
22
+ export declare function attachConductPolicy(a: {
23
+ store: PolicyStore;
24
+ cadence: PolicyCadence;
25
+ agentId: Uint8Array;
26
+ sessionHex: string;
27
+ peerHex: string;
28
+ tierName: string;
29
+ count: number;
30
+ }): {
31
+ policy?: PolicyField;
32
+ policy_error?: string;
33
+ };
@@ -0,0 +1,59 @@
1
+ // When an operator's policy rides on a delivery: the first since the daemon started, whenever its text changes, and every
2
+ // every_n messages after. In memory on purpose: a restart attaches it again on the first delivery, the safe direction.
3
+ // A lookup that fails must never look like no policy, so it gives a line the agent reads.
4
+ import { toHex } from "../protocol/encode.js";
5
+ import { logEvent } from "./log.js";
6
+ export const POLICY_ERROR_TEXT = "Your operator's policy for this peer could not be read, so none is shown here. That is a fault " +
7
+ "on this machine, not a sign that no policy exists — act cautiously and tell your operator.";
8
+ export class PolicyCadence {
9
+ #state = new Map();
10
+ shouldAttach(key, resolved, deliveredCount) {
11
+ const s = this.#state.get(key);
12
+ let reason;
13
+ if (!s)
14
+ reason = "first";
15
+ else if (s.lastText !== resolved.text)
16
+ reason = "changed";
17
+ else if (s.sinceLast + deliveredCount >= resolved.everyN)
18
+ reason = "cadence";
19
+ else
20
+ reason = null;
21
+ if (reason === null) {
22
+ s.sinceLast += deliveredCount;
23
+ }
24
+ else {
25
+ this.#state.set(key, { sinceLast: 0, lastText: resolved.text });
26
+ }
27
+ return reason;
28
+ }
29
+ }
30
+ const field = (r) => ({ policy: { type: r.type, level: r.level, text: r.text } });
31
+ function failed(agentId, type, err) {
32
+ logEvent("policy.resolve.failed", { agent: toHex(agentId), type, reason: err instanceof Error ? err.message : String(err) });
33
+ return { policy_error: POLICY_ERROR_TEXT };
34
+ }
35
+ export function admissionPolicyField(a) {
36
+ try {
37
+ const r = a.store.resolveSession(a.agentId, "admission", a.peerHex, a.tierName);
38
+ return r ? field(r) : {};
39
+ }
40
+ catch (err) {
41
+ return failed(a.agentId, "admission", err);
42
+ }
43
+ }
44
+ export function attachConductPolicy(a) {
45
+ let r;
46
+ try {
47
+ r = a.store.resolveSession(a.agentId, "conduct", a.peerHex, a.tierName);
48
+ }
49
+ catch (err) {
50
+ return failed(a.agentId, "conduct", err);
51
+ }
52
+ if (!r || a.count <= 0)
53
+ return {};
54
+ const reason = a.cadence.shouldAttach(`${toHex(a.agentId)}:${a.sessionHex}`, r, a.count);
55
+ if (reason === null)
56
+ return {};
57
+ logEvent("policy.attached", { agent: toHex(a.agentId), session: a.sessionHex, type: r.type, level: r.level, reason });
58
+ return field(r);
59
+ }
@@ -0,0 +1,41 @@
1
+ import type { Reach } from "./reach.ts";
2
+ import type { Store } from "./store.ts";
3
+ import type { PolicyRow, PolicyScope, PolicyStore, PolicyType, PolicyValue } from "./policy-store.ts";
4
+ export type ProposedBy = "agent" | "operator";
5
+ export interface ProposalInput {
6
+ scope: PolicyScope;
7
+ target: string;
8
+ type: PolicyType;
9
+ action: "set" | "clear";
10
+ value?: PolicyValue;
11
+ everyN?: number;
12
+ }
13
+ export interface PolicyProposal {
14
+ proposal_id: string;
15
+ scope: PolicyScope;
16
+ target: string;
17
+ type: PolicyType;
18
+ action: "set" | "clear";
19
+ mode: "text" | "none" | null;
20
+ text: string | null;
21
+ every_n: number | null;
22
+ proposed_by: ProposedBy;
23
+ created_at: number;
24
+ }
25
+ export type ApproveResult = {
26
+ ok: true;
27
+ proposal: PolicyProposal;
28
+ } | {
29
+ ok: false;
30
+ reason: "proposal_not_found";
31
+ };
32
+ export declare class PolicyProposals {
33
+ #private;
34
+ constructor(db: Store, reach: Reach, policies: PolicyStore, now?: () => number);
35
+ propose(agentId: Uint8Array, p: ProposalInput, proposedBy: ProposedBy): PolicyProposal;
36
+ pending(agentId: Uint8Array): Array<PolicyProposal & {
37
+ was: PolicyRow | null;
38
+ }>;
39
+ approve(agentId: Uint8Array, proposalId: string): ApproveResult;
40
+ decline(agentId: Uint8Array, proposalId: string): boolean;
41
+ }
@@ -0,0 +1,83 @@
1
+ import { toHex } from "../protocol/encode.js";
2
+ import { logEvent } from "./log.js";
3
+ const HOUR_MS = 60 * 60 * 1000;
4
+ export class PolicyProposals {
5
+ #db;
6
+ #reach;
7
+ #policies;
8
+ #now;
9
+ constructor(db, reach, policies, now = Date.now) {
10
+ this.#db = db;
11
+ this.#reach = reach;
12
+ this.#policies = policies;
13
+ this.#now = now;
14
+ }
15
+ propose(agentId, p, proposedBy) {
16
+ const v = this.#policies.validate(agentId, p.scope, p.target, p.type, p.action === "set" ? (p.value ?? { mode: "text", text: "" }) : undefined, p.everyN);
17
+ const id = this.#nextId(agentId);
18
+ const row = {
19
+ proposal_id: id, scope: p.scope, target: v.target, type: p.type, action: p.action,
20
+ mode: p.action === "set" ? (p.value?.mode ?? "text") : null,
21
+ text: p.action === "set" ? v.text : null,
22
+ every_n: p.action === "set" ? v.everyN : null,
23
+ proposed_by: proposedBy, created_at: this.#now(),
24
+ };
25
+ this.#db.prepare("DELETE FROM agent_policy_proposals WHERE agent_id = ? AND scope = ? AND target = ? AND type = ?")
26
+ .run(agentId, row.scope, row.target, row.type);
27
+ this.#db.prepare(`INSERT INTO agent_policy_proposals (agent_id, proposal_id, scope, target, type, action, mode, text, every_n, proposed_by, created_at)
28
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(agentId, id, row.scope, row.target, row.type, row.action, row.mode, row.text, row.every_n, row.proposed_by, row.created_at);
29
+ logEvent("policy.proposed", { agent: toHex(agentId), proposalId: id, scope: row.scope, target: row.target, type: row.type, proposedBy });
30
+ return row;
31
+ }
32
+ pending(agentId) {
33
+ this.#expire(agentId);
34
+ const rows = this.#db.prepare(`SELECT proposal_id, scope, target, type, action, mode, text, every_n, proposed_by, created_at
35
+ FROM agent_policy_proposals WHERE agent_id = ? ORDER BY created_at, proposal_id`).all(agentId);
36
+ return rows.map((r) => ({ ...r, was: this.#policies.get(agentId, r.scope, r.target, r.type) }));
37
+ }
38
+ approve(agentId, proposalId) {
39
+ const p = this.#find(agentId, proposalId);
40
+ if (!p)
41
+ return { ok: false, reason: "proposal_not_found" };
42
+ if (p.action === "clear") {
43
+ this.#policies.clear(agentId, p.scope, p.target, p.type);
44
+ }
45
+ else {
46
+ const value = p.mode === "none" ? { mode: "none" } : { mode: "text", text: p.text ?? "" };
47
+ this.#policies.set(agentId, p.scope, p.target, p.type, value, p.every_n ?? undefined);
48
+ }
49
+ this.#delete(agentId, proposalId);
50
+ logEvent("policy.approved", { agent: toHex(agentId), proposalId });
51
+ return { ok: true, proposal: p };
52
+ }
53
+ decline(agentId, proposalId) {
54
+ if (!this.#find(agentId, proposalId))
55
+ return false;
56
+ this.#delete(agentId, proposalId);
57
+ logEvent("policy.declined", { agent: toHex(agentId), proposalId });
58
+ return true;
59
+ }
60
+ #find(agentId, proposalId) {
61
+ this.#expire(agentId);
62
+ return this.#db.prepare(`SELECT proposal_id, scope, target, type, action, mode, text, every_n, proposed_by, created_at
63
+ FROM agent_policy_proposals WHERE agent_id = ? AND proposal_id = ?`).get(agentId, proposalId) ?? null;
64
+ }
65
+ #delete(agentId, proposalId) {
66
+ this.#db.prepare("DELETE FROM agent_policy_proposals WHERE agent_id = ? AND proposal_id = ?").run(agentId, proposalId);
67
+ }
68
+ #expire(agentId) {
69
+ const cutoff = this.#now() - this.#reach.number(agentId, "policy.proposal_hours") * HOUR_MS;
70
+ const old = this.#db.prepare("SELECT proposal_id FROM agent_policy_proposals WHERE agent_id = ? AND created_at < ?")
71
+ .all(agentId, cutoff);
72
+ if (old.length === 0)
73
+ return;
74
+ this.#db.prepare("DELETE FROM agent_policy_proposals WHERE agent_id = ? AND created_at < ?").run(agentId, cutoff);
75
+ for (const o of old)
76
+ logEvent("policy.expired", { agent: toHex(agentId), proposalId: o.proposal_id });
77
+ }
78
+ #nextId(agentId) {
79
+ this.#db.prepare("INSERT INTO agent_policy_proposal_seq (agent_id, last) VALUES (?, 1) ON CONFLICT (agent_id) DO UPDATE SET last = last + 1").run(agentId);
80
+ const r = this.#db.prepare("SELECT last FROM agent_policy_proposal_seq WHERE agent_id = ?").get(agentId);
81
+ return `p${r.last}`;
82
+ }
83
+ }
@@ -0,0 +1,47 @@
1
+ import type { Reach } from "./reach.ts";
2
+ import type { Store } from "./store.ts";
3
+ export type PolicyType = "admission" | "conduct";
4
+ export type PolicyScope = "default" | "tier" | "contact";
5
+ export type PolicyLevel = "contact" | "tier" | "default";
6
+ export interface ResolvedPolicy {
7
+ type: PolicyType;
8
+ level: PolicyLevel;
9
+ text: string;
10
+ everyN: number;
11
+ }
12
+ export interface PolicyRow {
13
+ scope: PolicyScope;
14
+ target: string;
15
+ type: PolicyType;
16
+ mode: "text" | "none";
17
+ text: string | null;
18
+ every_n: number;
19
+ updated_at: number;
20
+ }
21
+ export type PolicyValue = {
22
+ mode: "text";
23
+ text: string;
24
+ } | {
25
+ mode: "none";
26
+ };
27
+ export declare const POLICY_SCOPES: readonly PolicyScope[];
28
+ export declare const POLICY_TYPES: readonly PolicyType[];
29
+ export declare class PolicyValidationError extends Error {
30
+ readonly reason: string;
31
+ constructor(reason: string, message: string);
32
+ }
33
+ export declare function ensurePolicySchema(db: Store): void;
34
+ export declare class PolicyStore {
35
+ #private;
36
+ constructor(db: Store, reach: Reach);
37
+ set(agentId: Uint8Array, scope: PolicyScope, target: string, type: PolicyType, value: PolicyValue, everyN?: number): void;
38
+ get(agentId: Uint8Array, scope: PolicyScope, target: string, type: PolicyType): PolicyRow | null;
39
+ validate(agentId: Uint8Array, scope: PolicyScope, target: string, type: PolicyType, value?: PolicyValue, everyN?: number): {
40
+ target: string;
41
+ text: string | null;
42
+ everyN: number;
43
+ };
44
+ clear(agentId: Uint8Array, scope: PolicyScope, target: string, type: PolicyType): boolean;
45
+ list(agentId: Uint8Array): PolicyRow[];
46
+ resolveSession(agentId: Uint8Array, type: PolicyType, peerPubkeyHex: string, tierName: string): ResolvedPolicy | null;
47
+ }
@@ -0,0 +1,144 @@
1
+ import { toHex } from "../protocol/encode.js";
2
+ import { logEvent } from "./log.js";
3
+ import { SETTABLE_TIERS as SETTABLE_TIER_NAMES } from "./tiers.js";
4
+ export const POLICY_SCOPES = ["default", "tier", "contact"];
5
+ export const POLICY_TYPES = ["admission", "conduct"];
6
+ export class PolicyValidationError extends Error {
7
+ reason;
8
+ constructor(reason, message) {
9
+ super(message);
10
+ this.reason = reason;
11
+ this.name = "PolicyValidationError";
12
+ }
13
+ }
14
+ export function ensurePolicySchema(db) {
15
+ db.exec(`
16
+ CREATE TABLE IF NOT EXISTS agent_policies (
17
+ agent_id BLOB NOT NULL,
18
+ scope TEXT NOT NULL CHECK (scope IN ('default','tier','contact','channel','channel_default')),
19
+ target TEXT NOT NULL DEFAULT '',
20
+ type TEXT NOT NULL CHECK (type IN ('admission','conduct')),
21
+ mode TEXT NOT NULL CHECK (mode IN ('text','none')),
22
+ text TEXT,
23
+ every_n INTEGER NOT NULL DEFAULT 10 CHECK (every_n >= 1),
24
+ updated_at INTEGER NOT NULL,
25
+ PRIMARY KEY (agent_id, scope, target, type)
26
+ )
27
+ `);
28
+ db.exec(`
29
+ CREATE TABLE IF NOT EXISTS agent_policy_proposals (
30
+ agent_id BLOB NOT NULL,
31
+ proposal_id TEXT NOT NULL,
32
+ scope TEXT NOT NULL, target TEXT NOT NULL DEFAULT '', type TEXT NOT NULL,
33
+ action TEXT NOT NULL CHECK (action IN ('set','clear')),
34
+ mode TEXT CHECK (mode IN ('text','none')),
35
+ text TEXT,
36
+ every_n INTEGER CHECK (every_n IS NULL OR every_n >= 1),
37
+ proposed_by TEXT NOT NULL CHECK (proposed_by IN ('agent','operator')),
38
+ created_at INTEGER NOT NULL,
39
+ PRIMARY KEY (agent_id, proposal_id),
40
+ UNIQUE (agent_id, scope, target, type)
41
+ )
42
+ `);
43
+ db.exec(`
44
+ CREATE TABLE IF NOT EXISTS agent_policy_proposal_seq (
45
+ agent_id BLOB PRIMARY KEY,
46
+ last INTEGER NOT NULL
47
+ )
48
+ `);
49
+ }
50
+ const HEX64 = /^[0-9a-f]{64}$/;
51
+ export class PolicyStore {
52
+ #db;
53
+ #reach;
54
+ constructor(db, reach) {
55
+ this.#db = db;
56
+ this.#reach = reach;
57
+ ensurePolicySchema(db);
58
+ }
59
+ set(agentId, scope, target, type, value, everyN) {
60
+ const { target: t, text, everyN: n } = this.validate(agentId, scope, target, type, value, everyN);
61
+ this.#db.prepare(`INSERT INTO agent_policies (agent_id, scope, target, type, mode, text, every_n, updated_at)
62
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
63
+ ON CONFLICT (agent_id, scope, target, type) DO UPDATE SET
64
+ mode = excluded.mode, text = excluded.text, every_n = excluded.every_n, updated_at = excluded.updated_at`).run(agentId, scope, t, type, value.mode, text, n, Date.now());
65
+ logEvent("policy.set", { agent: toHex(agentId), scope, target: t, type, mode: value.mode });
66
+ }
67
+ get(agentId, scope, target, type) {
68
+ return this.#db.prepare("SELECT scope, target, type, mode, text, every_n, updated_at FROM agent_policies WHERE agent_id = ? AND scope = ? AND target = ? AND type = ?").get(agentId, scope, target, type) ?? null;
69
+ }
70
+ validate(agentId, scope, target, type, value, everyN) {
71
+ const t = this.#validateKey(scope, target, type);
72
+ let text = null;
73
+ const defaultEveryN = this.#reach.number(agentId, "policy.every_n");
74
+ if (value === undefined)
75
+ return { target: t, text, everyN: defaultEveryN };
76
+ if (value.mode === "text") {
77
+ if (value.text.trim() === "") {
78
+ throw new PolicyValidationError("policy_text_empty", "The policy text is empty. Use NONE (--none) to send nothing.");
79
+ }
80
+ const max = this.#reach.number(agentId, "policy.text_max");
81
+ if (value.text.length > max) {
82
+ throw new PolicyValidationError("policy_text_too_long", `The policy text is ${value.text.length} characters; the limit is ${max}.`);
83
+ }
84
+ text = value.text;
85
+ }
86
+ else if (value.mode !== "none") {
87
+ throw new PolicyValidationError("policy_mode_unknown", "A policy is either text or NONE.");
88
+ }
89
+ const n = everyN ?? defaultEveryN;
90
+ if (!Number.isInteger(n) || n < 1) {
91
+ throw new PolicyValidationError("policy_every_n_invalid", `every_n must be an integer of at least 1, got ${String(everyN)}.`);
92
+ }
93
+ return { target: t, text, everyN: n };
94
+ }
95
+ clear(agentId, scope, target, type) {
96
+ const t = this.#validateKey(scope, target, type);
97
+ const removed = this.get(agentId, scope, t, type) !== null;
98
+ this.#db.prepare("DELETE FROM agent_policies WHERE agent_id = ? AND scope = ? AND target = ? AND type = ?").run(agentId, scope, t, type);
99
+ logEvent("policy.cleared", { agent: toHex(agentId), scope, target: t, type, mode: removed ? "removed" : "absent" });
100
+ return removed;
101
+ }
102
+ list(agentId) {
103
+ return this.#db.prepare("SELECT scope, target, type, mode, text, every_n, updated_at FROM agent_policies WHERE agent_id = ? ORDER BY scope, target, type").all(agentId);
104
+ }
105
+ resolveSession(agentId, type, peerPubkeyHex, tierName) {
106
+ const walk = [["contact", peerPubkeyHex.toLowerCase()], ["tier", tierName], ["default", ""]];
107
+ return this.#walk(agentId, type, walk);
108
+ }
109
+ #walk(agentId, type, walk) {
110
+ const stmt = this.#db.prepare("SELECT mode, text, every_n FROM agent_policies WHERE agent_id = ? AND scope = ? AND target = ? AND type = ?");
111
+ for (const [scope, target] of walk) {
112
+ const row = stmt.get(agentId, scope, target, type);
113
+ if (!row)
114
+ continue;
115
+ if (row.mode === "none")
116
+ return null;
117
+ return { type, level: scope, text: row.text ?? "", everyN: row.every_n };
118
+ }
119
+ return null;
120
+ }
121
+ #validateKey(scope, target, type) {
122
+ if (!POLICY_SCOPES.includes(scope)) {
123
+ throw new PolicyValidationError("policy_scope_unknown", `Unknown scope '${String(scope)}'. Use one of: ${POLICY_SCOPES.join(", ")}.`);
124
+ }
125
+ if (!POLICY_TYPES.includes(type)) {
126
+ throw new PolicyValidationError("policy_type_unknown", `Unknown type '${String(type)}'. Use admission or conduct.`);
127
+ }
128
+ if (scope === "default") {
129
+ if (target !== "")
130
+ throw new PolicyValidationError("policy_target_invalid", `Scope '${scope}' takes no target.`);
131
+ return "";
132
+ }
133
+ if (scope === "tier") {
134
+ if (!SETTABLE_TIER_NAMES.includes(target)) {
135
+ throw new PolicyValidationError("policy_target_invalid", `'${target}' is not a tier. Use one of: ${SETTABLE_TIER_NAMES.join(", ")}.`);
136
+ }
137
+ return target;
138
+ }
139
+ if (!HEX64.test(target)) {
140
+ throw new PolicyValidationError("policy_target_invalid", `A ${scope} target is a public key: 64 lowercase hex characters.`);
141
+ }
142
+ return target;
143
+ }
144
+ }
@@ -0,0 +1,36 @@
1
+ import { type WireSigned } from "../protocol/wire.ts";
2
+ import type { Signer } from "../protocol/identity.ts";
3
+ import type { Store } from "./store.ts";
4
+ export declare function ensurePresentedSchema(db: Store): void;
5
+ interface KeyRow {
6
+ agent_id: Uint8Array;
7
+ revision: number;
8
+ kem_seed: Uint8Array;
9
+ signed: string;
10
+ published: number;
11
+ created_at: number;
12
+ }
13
+ export declare class EncryptionKeys {
14
+ #private;
15
+ constructor(store: Store);
16
+ latest(agentId: Uint8Array): KeyRow | undefined;
17
+ seeds(agentId: Uint8Array): Uint8Array[];
18
+ make(agent: {
19
+ signer: Signer;
20
+ }): Promise<KeyRow>;
21
+ unpublished(agent: {
22
+ signer: Signer;
23
+ }): Promise<{
24
+ revision: number;
25
+ wire: WireSigned;
26
+ } | null>;
27
+ markPublished(agentId: Uint8Array, revision: number): void;
28
+ }
29
+ export declare class PresentedStore {
30
+ #private;
31
+ constructor(store: Store);
32
+ put(agentId: Uint8Array, sessionId: Uint8Array, side: "caller" | "callee", files: readonly Uint8Array[] | "unreadable"): void;
33
+ files(agentId: Uint8Array, sessionId: Uint8Array, side: "caller" | "callee"): Uint8Array[];
34
+ unreadable(agentId: Uint8Array, sessionId: Uint8Array, side: "caller" | "callee"): boolean;
35
+ }
36
+ export {};