@cello-protocol/cli 0.0.305 → 0.0.307

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 +564 -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 +80 -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 +511 -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 +146 -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 +63 -0
  50. package/dist/daemon/reach.js +207 -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 +188 -0
  60. package/dist/daemon/store.js +474 -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 +428 -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 +26 -0
  70. package/dist/hermes-bridge.js +180 -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 +835 -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 +155 -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 +252 -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 +1040 -0
  180. package/hermes/plugin/plugin.yaml +30 -0
  181. package/hermes/skills/cello-bridge-setup/SKILL.md +38 -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,5 @@
1
+ export declare class LocalError extends Error {
2
+ readonly code: string;
3
+ constructor(code: string, message: string);
4
+ }
5
+ export declare function requirePerson(params: Record<string, unknown>, what: string, command: string): void;
@@ -0,0 +1,16 @@
1
+ // A refusal with a name, which the caller gets as it is.
2
+ export class LocalError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "LocalError";
7
+ this.code = code;
8
+ }
9
+ }
10
+ // Anything that loosens is refused here unless a person agreed at a terminal, whoever asked. The command line alone asks,
11
+ // and re-sends with this set. A program running as this user could set it too: this is the speed bump the help describes.
12
+ export function requirePerson(params, what, command) {
13
+ if (params["person_confirmed"] === true && params["caller"] === "cli")
14
+ return;
15
+ throw new LocalError("person_required", `${what} Nothing changed. Only a person at a terminal can do this, so if you're an agent, relay it to your operator, to run in their own terminal: ${command}`);
16
+ }
@@ -0,0 +1,66 @@
1
+ import { Contacts } from "./contacts.ts";
2
+ import { Guards } from "./guards.ts";
3
+ import { SignalRules } from "./signal-rules.ts";
4
+ import { PolicyStore } from "./policy-store.ts";
5
+ import { Reach } from "./reach.ts";
6
+ import type { Store } from "./store.ts";
7
+ import { type Tier } from "./tiers.ts";
8
+ export type ScreeningLevel = "full" | "deterministic" | "off";
9
+ export interface GovernanceHooks {
10
+ notify(agentId: Uint8Array, text: string): void;
11
+ isLocalAgent(id: Uint8Array): boolean;
12
+ }
13
+ type Params = Record<string, unknown>;
14
+ export declare const REFUSAL_SENTENCES: {
15
+ readonly not_accepting: "This agent is not accepting connections. Retrying will not change this.";
16
+ readonly busy: "This agent can't take another conversation from you right now.";
17
+ readonly session_limit: "You have reached the number of conversations this agent allows you. Close one, and try again.";
18
+ readonly signals_required: "This agent asks for signals your call didn't show. Look up its public signals, then call again with the ones it needs.";
19
+ };
20
+ export type RefusalCode = keyof typeof REFUSAL_SENTENCES;
21
+ export declare class Governance {
22
+ #private;
23
+ readonly contacts: Contacts;
24
+ readonly reach: Reach;
25
+ readonly guards: Guards;
26
+ readonly policies: PolicyStore;
27
+ readonly rules: SignalRules;
28
+ constructor(store: Store, hooks: GovernanceHooks);
29
+ writeDefaults(agentId: Uint8Array): void;
30
+ admit(agentId: Uint8Array, callerId: Uint8Array): {
31
+ code: RefusalCode;
32
+ limit?: number;
33
+ } | null;
34
+ noteRefusal(agentId: Uint8Array, agentHex: string, callerHex: string, code: RefusalCode): void;
35
+ knocks(agentId: Uint8Array, agentHex: string): unknown[];
36
+ awayText(agentId: Uint8Array, callerId: Uint8Array, fallbackName: string): string;
37
+ offeredName(agentId: Uint8Array, fallback: string): string;
38
+ setOwnMoniker(agentId: Uint8Array, agentHex: string, params: Params): unknown;
39
+ engaged(agentId: Uint8Array, contactId: Uint8Array, how: "initiated" | "replied"): void;
40
+ listContacts(agentId: Uint8Array): unknown;
41
+ contactAdd(agentId: Uint8Array, agentHex: string, params: Params): unknown;
42
+ contactRemove(agentId: Uint8Array, agentHex: string, params: Params): unknown;
43
+ contactSetTier(agentId: Uint8Array, agentHex: string, params: Params): unknown;
44
+ signalRules(agentId: Uint8Array): unknown;
45
+ signalRuleSet(agentId: Uint8Array, agentHex: string, params: Params): unknown;
46
+ signalRuleClear(agentId: Uint8Array, agentHex: string, params: Params): unknown;
47
+ contactSetAway(agentId: Uint8Array, params: Params): unknown;
48
+ contactSetMoniker(agentId: Uint8Array, params: Params): unknown;
49
+ listSettings(agentId: Uint8Array | undefined): unknown;
50
+ settingsSet(agentId: Uint8Array | undefined, agentHex: string | undefined, params: Params): unknown;
51
+ listGuards(agentId: Uint8Array, key: string | undefined): unknown;
52
+ guardSet(agentId: Uint8Array, agentHex: string, params: Params): unknown;
53
+ screeningLog(agentId: Uint8Array, limit: number | undefined): unknown;
54
+ screeningRule(agentId: Uint8Array, senderHex: string): {
55
+ level: ScreeningLevel;
56
+ from: "agent_rule" | "tier_rule" | "default";
57
+ };
58
+ setScreening(agentId: Uint8Array, agentHex: string, params: Params): unknown;
59
+ policyList(agentId: Uint8Array): unknown;
60
+ policyPending(agentId: Uint8Array): unknown;
61
+ policyPropose(agentId: Uint8Array, agentHex: string, params: Params): unknown;
62
+ policyApprove(agentId: Uint8Array, agentHex: string, params: Params): unknown;
63
+ admissionFor(agentId: Uint8Array, peerHex: string, tier: Tier): Record<string, unknown>;
64
+ conductFor(agentId: Uint8Array, sessionHex: string, peerHex: string, tier: Tier, count: number): Record<string, unknown>;
65
+ }
66
+ export {};
@@ -0,0 +1,514 @@
1
+ // What a person decides about their agent: contacts, tiers, limits, guards, policies and screening rules.
2
+ // Each change is judged here by which way it goes, whoever asked. Loosening needs a person at a terminal, and it's logged,
3
+ // and the agent gets a notice. Nothing here reaches the server.
4
+ import { toHex } from "../protocol/encode.js";
5
+ import { Contacts } from "./contacts.js";
6
+ import { LocalError, requirePerson } from "./errors.js";
7
+ import { Guards } from "./guards.js";
8
+ import { logEvent } from "./log.js";
9
+ import { PolicyCadence, admissionPolicyField, attachConductPolicy } from "./policy-cadence.js";
10
+ import { PolicyProposals } from "./policy-proposals.js";
11
+ import { ISSUER_KINDS, RULE_DIRECTIONS, RULE_SCOPES, SignalRules, isNoRule } from "./signal-rules.js";
12
+ import { MAX_PRESENTED_SIGNALS } from "../protocol/structures.js";
13
+ import { PolicyStore, PolicyValidationError } from "./policy-store.js";
14
+ import { CALLING_RAISES_KEY, Reach } from "./reach.js";
15
+ import { SettingError, changeSetting, listSettings } from "./settings.js";
16
+ import { TIER, tierFromName, tierName } from "./tiers.js";
17
+ import { validateMoniker } from "./who-label.js";
18
+ const LEVEL_STRENGTH = { full: 2, deterministic: 1, off: 0 };
19
+ // Known can be reached by an agent's own call or reply, so only tiers a person alone can set may have less screening.
20
+ const WEAKENABLE_TIERS = ["whitelisted", "vip"];
21
+ const DEFAULT_LOG_LIMIT = 50;
22
+ const fromHex = (hex) => new Uint8Array(Buffer.from(hex, "hex"));
23
+ // The only reasons a refusal can carry. The caller's daemon writes the sentence, so a refuser's prose never reaches its model.
24
+ export const REFUSAL_SENTENCES = {
25
+ not_accepting: "This agent is not accepting connections. Retrying will not change this.",
26
+ busy: "This agent can't take another conversation from you right now.",
27
+ session_limit: "You have reached the number of conversations this agent allows you. Close one, and try again.",
28
+ // The same words whatever the rule, so a caller can't read the rule or the tier from the refusal. Its public signals are where to look.
29
+ signals_required: "This agent asks for signals your call didn't show. Look up its public signals, then call again with the ones it needs.",
30
+ };
31
+ function hexParam(params, name) {
32
+ const value = params[name];
33
+ if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value))
34
+ throw new LocalError("bad_argument", `${name} must be an agent_id, 64 hex characters`);
35
+ const hex = value.toLowerCase();
36
+ return { id: fromHex(hex), hex };
37
+ }
38
+ function optionalText(params, name) {
39
+ const value = params[name];
40
+ if (value === undefined)
41
+ return undefined;
42
+ if (typeof value !== "string")
43
+ throw new LocalError("bad_argument", `${name} must be text`);
44
+ return value;
45
+ }
46
+ export class Governance {
47
+ contacts;
48
+ reach;
49
+ guards;
50
+ policies;
51
+ rules;
52
+ #proposals;
53
+ #cadence = new PolicyCadence();
54
+ #store;
55
+ #hooks;
56
+ constructor(store, hooks) {
57
+ this.#store = store;
58
+ this.#hooks = hooks;
59
+ this.contacts = new Contacts(store);
60
+ this.reach = new Reach(store);
61
+ this.guards = new Guards(store);
62
+ this.policies = new PolicyStore(store, this.reach);
63
+ this.rules = new SignalRules(store);
64
+ this.#proposals = new PolicyProposals(store, this.reach, this.policies);
65
+ }
66
+ // At creation, and at each start, so an agent made before a setting existed gets it too.
67
+ writeDefaults(agentId) {
68
+ this.reach.writeDefaults(agentId);
69
+ this.guards.writeDefaults(agentId);
70
+ }
71
+ #weakened(agentId, key, from, to, direction, params, undo) {
72
+ const confirmed = params["person_confirmed"] === true;
73
+ this.guards.record(agentId, key, from, to, direction, confirmed);
74
+ logEvent("governance.changed", { agent: toHex(agentId), key, from, to, direction, confirmed });
75
+ if (direction === "loosen")
76
+ this.#hooks.notify(agentId, `${key} changed from ${JSON.stringify(from)} to ${JSON.stringify(to)}, by a person at this machine's terminal. If that wasn't you, run: ${undo}`);
77
+ }
78
+ // ---- The gate. Runs before any key material exists, and asks nobody: a call either fits what the owner set or it's refused. ----
79
+ admit(agentId, callerId) {
80
+ const tier = this.contacts.tierOf(agentId, callerId);
81
+ const limits = this.reach.limitsFor(agentId, tier);
82
+ if (limits.shut)
83
+ return { code: "not_accepting" };
84
+ const quietMs = this.reach.number(agentId, "limits.quiet_minutes") * 60_000;
85
+ const now = Date.now();
86
+ // A session stays open however long it's quiet, and only stops counting. Sessions this agent started aren't anyone's knock.
87
+ const counting = this.#store.sessionsOf(agentId).filter((s) => s.role === "callee" && (s.state === "accepted" || s.state === "active") && s.peer_closed === 0 && s.own_closed === 0 && now - s.last_activity_at < quietMs);
88
+ const fromCaller = counting.filter((s) => toHex(s.counterparty_id) === toHex(callerId)).length;
89
+ if (fromCaller >= limits.max_sessions)
90
+ return tier === TIER.UNKNOWN ? { code: "busy" } : { code: "session_limit", limit: limits.max_sessions };
91
+ if (tier === TIER.UNKNOWN) {
92
+ const strangers = counting.filter((s) => this.contacts.tierOf(agentId, s.counterparty_id) === TIER.UNKNOWN).length;
93
+ if (strangers >= this.reach.number(agentId, "limits.stranger_pool"))
94
+ return { code: "busy" };
95
+ }
96
+ return null;
97
+ }
98
+ // Every refusal goes on the ledger, one row per caller, so knocking a thousand times can push nobody else out. Bob hears
99
+ // about a limit, at most once in each cooldown. A block or a shut tier is his own choice, so it just sits in the inbox.
100
+ noteRefusal(agentId, agentHex, callerHex, code) {
101
+ const told = this.reach.addRefusal(agentId, fromHex(callerHex), code, code !== "not_accepting", this.reach.number(agentId, "limits.cap_alarm_minutes") * 60_000);
102
+ logEvent("session.refused", { agent: agentHex, caller: callerHex, reason: code });
103
+ if (told && code === "signals_required")
104
+ this.#hooks.notify(agentId, `${callerHex} tried to start a conversation and didn't show the signals your inbound rule asks for. See the rule with: cello signal-rules --agent ${agentHex}. To let it through anyway, a person can add it as a contact: cello contact-set-tier ${callerHex} --tier whitelisted --agent ${agentHex}`);
105
+ else if (told)
106
+ this.#hooks.notify(agentId, `${callerHex} tried to start a conversation and was over a limit (${code}). To give it more room, a person runs: cello contact-set-tier ${callerHex} --tier whitelisted --agent ${agentHex}`);
107
+ }
108
+ knocks(agentId, agentHex) {
109
+ return this.reach.refusals(agentId).map((row) => ({
110
+ contact_id: toHex(row.contact_id),
111
+ first_at: new Date(row.first_refused_at).toISOString(),
112
+ last_at: new Date(row.last_refused_at).toISOString(),
113
+ times: row.times,
114
+ reason: row.last_reason,
115
+ let_through: `cello contact-set-tier ${toHex(row.contact_id)} --tier known --agent ${agentHex}`,
116
+ }));
117
+ }
118
+ // The ladder, most specific first: for this caller, their tier, this agent's default, then the system's. Empty sends nothing.
119
+ awayText(agentId, callerId, fallbackName) {
120
+ const tier = this.contacts.tierOf(agentId, callerId);
121
+ const own = this.contacts.get(agentId, callerId)?.away_message;
122
+ if (own)
123
+ return own;
124
+ const forTier = this.reach.tiers(agentId).find((row) => row.tier === tierName(tier))?.away_text;
125
+ if (forTier)
126
+ return forTier;
127
+ const byDefault = this.reach.setting(agentId, "away.default");
128
+ if (byDefault)
129
+ return byDefault;
130
+ const system = this.reach.setting(agentId, tier === TIER.UNKNOWN ? "away.system.stranger" : "away.system.known");
131
+ return system.replaceAll("{name}", this.offeredName(agentId, fallbackName) || "This agent");
132
+ }
133
+ // What this agent calls itself, sealed to whoever it talks to. Empty offers no name.
134
+ offeredName(agentId, fallback) {
135
+ return this.reach.offeredName(agentId) ?? fallback;
136
+ }
137
+ setOwnMoniker(agentId, agentHex, params) {
138
+ const moniker = params["clear"] === true ? "" : this.#monikerOf(params);
139
+ if (moniker === undefined)
140
+ throw new LocalError("bad_argument", "give the name, or --clear to offer none");
141
+ this.reach.setOfferedName(agentId, moniker);
142
+ return { agent_id: agentHex, offers_name: moniker || null };
143
+ }
144
+ // ---- Contacts ----
145
+ // THE rule for when an agent's own action raises a stranger to known, and the only place it lives. It raises a stranger and
146
+ // nothing else: it never lifts a block, and accepting a call doesn't do it. Replying counts. Calling doesn't, unless a person
147
+ // turns on the setting, because persuading an agent to dial a lure is easy.
148
+ engaged(agentId, contactId, how) {
149
+ if (how === "initiated" && this.reach.setting(agentId, CALLING_RAISES_KEY) !== "true")
150
+ return;
151
+ if (this.contacts.tierOf(agentId, contactId) === TIER.UNKNOWN)
152
+ this.contacts.put(agentId, contactId, { tier: TIER.KNOWN, provenance: how });
153
+ }
154
+ #contactView(agentId, row) {
155
+ return {
156
+ contact_id: toHex(row.contact_id),
157
+ tier: tierName(row.tier),
158
+ ...this.contacts.who(agentId, row.contact_id, toHex(row.contact_id), row.last_offered_moniker),
159
+ moniker: row.moniker,
160
+ away_message: row.away_message,
161
+ provenance: row.provenance,
162
+ added_at: new Date(row.added_at).toISOString(),
163
+ ...(this.#hooks.isLocalAgent(row.contact_id) ? { same_daemon: true } : {}),
164
+ };
165
+ }
166
+ listContacts(agentId) {
167
+ return { contacts: this.contacts.list(agentId).map((row) => this.#contactView(agentId, row)) };
168
+ }
169
+ contactAdd(agentId, agentHex, params) {
170
+ const contact = hexParam(params, "contact");
171
+ const moniker = this.#monikerOf(params);
172
+ const tier = this.contacts.tierOf(agentId, contact.id);
173
+ if (tier === TIER.BLOCKED) {
174
+ requirePerson(params, `This would lift your block on ${contact.hex}.`, `cello contact-add ${contact.hex} --agent ${agentHex}`);
175
+ this.#weakened(agentId, `contact.${contact.hex}.tier`, "blocked", "known", "loosen", params, `cello contact-set-tier ${contact.hex} --tier blocked --agent ${agentHex}`);
176
+ }
177
+ const raises = tier === TIER.BLOCKED || tier === TIER.UNKNOWN;
178
+ this.contacts.put(agentId, contact.id, { ...(raises ? { tier: TIER.KNOWN, provenance: "added" } : {}), ...(moniker ? { moniker } : {}) });
179
+ return this.#contactView(agentId, this.contacts.get(agentId, contact.id));
180
+ }
181
+ #monikerOf(params) {
182
+ const raw = optionalText(params, "moniker");
183
+ if (raw === undefined)
184
+ return undefined;
185
+ if (validateMoniker(raw) === null)
186
+ throw new LocalError("invalid_moniker", "a name is 1 to 64 letters, digits, underscores or dashes");
187
+ return raw;
188
+ }
189
+ // Removing a blocked row unblocks it. Removing any other only moves it back to a stranger.
190
+ contactRemove(agentId, agentHex, params) {
191
+ const contact = hexParam(params, "contact");
192
+ const row = this.contacts.get(agentId, contact.id);
193
+ if (!row)
194
+ return { removed: false, contact_id: contact.hex };
195
+ if (row.tier === TIER.BLOCKED) {
196
+ requirePerson(params, `Removing ${contact.hex} would lift your block on it.`, `cello contact-remove ${contact.hex} --agent ${agentHex}`);
197
+ this.#weakened(agentId, `contact.${contact.hex}.tier`, "blocked", "unknown", "loosen", params, `cello contact-set-tier ${contact.hex} --tier blocked --agent ${agentHex}`);
198
+ }
199
+ this.contacts.remove(agentId, contact.id);
200
+ return { removed: true, contact_id: contact.hex };
201
+ }
202
+ contactSetTier(agentId, agentHex, params) {
203
+ const contact = hexParam(params, "contact");
204
+ const to = tierFromName(params["tier"]);
205
+ if (to === undefined)
206
+ throw new LocalError("invalid_tier", "tier must be blocked, unknown, known, whitelisted or vip");
207
+ const from = this.contacts.tierOf(agentId, contact.id);
208
+ const direction = to > from ? "loosen" : to < from ? "tighten" : "neutral";
209
+ if (direction === "loosen")
210
+ requirePerson(params, `This raises ${contact.hex} from ${tierName(from)} to ${tierName(to)}, which gives it more room with ${agentHex}.`, `cello contact-set-tier ${contact.hex} --tier ${tierName(to)} --agent ${agentHex}`);
211
+ this.contacts.put(agentId, contact.id, { tier: to });
212
+ if (direction === "loosen")
213
+ this.reach.forgetRefusal(agentId, contact.id);
214
+ if (direction !== "neutral")
215
+ this.#weakened(agentId, `contact.${contact.hex}.tier`, tierName(from), tierName(to), direction, params, `cello contact-set-tier ${contact.hex} --tier ${tierName(from)} --agent ${agentHex}`);
216
+ return this.#contactView(agentId, this.contacts.get(agentId, contact.id));
217
+ }
218
+ // ---- Signal rules: who may call this agent, and who it may call, by the signals shown with the call. ----
219
+ signalRules(agentId) {
220
+ return {
221
+ rules: this.rules.list(agentId).map((row) => ({ direction: row.direction, scope: row.scope, target: row.target || undefined, require_types: row.require_types, require_issuer_kind: row.require_issuer_kind, min_count: row.min_count, updated_at: new Date(row.updated_at).toISOString() })),
222
+ note: "With no rule, no signals are required. A rule counts only signals from an issuer that counts here, and never one from your own operator toward any demand (a type, a kind of issuer or a minimum). The most specific rule wins: contact, then tier, then default.",
223
+ };
224
+ }
225
+ #ruleKey(params) {
226
+ const direction = params["direction"];
227
+ const scope = params["scope"];
228
+ if (!RULE_DIRECTIONS.includes(direction))
229
+ throw new LocalError("bad_argument", "direction must be inbound (who calls you) or outbound (who you call).");
230
+ if (!RULE_SCOPES.includes(scope))
231
+ throw new LocalError("bad_argument", "scope must be default, tier or contact.");
232
+ try {
233
+ return { direction: direction, scope: scope, target: SignalRules.checkTarget(scope, optionalText(params, "target")) };
234
+ }
235
+ catch (err) {
236
+ throw new LocalError("bad_argument", err instanceof Error ? err.message : String(err));
237
+ }
238
+ }
239
+ #ruleFrom(params) {
240
+ const rawTypes = optionalText(params, "require_types");
241
+ const types = rawTypes === undefined || rawTypes.trim() === "" ? [] : rawTypes.split(",").map((t) => t.trim());
242
+ for (const type of types)
243
+ if (!/^[A-Za-z0-9_.:-]{1,64}$/.test(type))
244
+ throw new LocalError("bad_argument", `${JSON.stringify(type)} isn't a signal type: letters, digits and _ . : - up to 64.`);
245
+ const kind = params["require_issuer_kind"];
246
+ if (kind !== undefined && !ISSUER_KINDS.includes(kind))
247
+ throw new LocalError("bad_argument", "require_issuer_kind must be issuer or agent.");
248
+ const min = params["min_count"];
249
+ if (min !== undefined && (typeof min !== "number" || !Number.isInteger(min) || min < 0))
250
+ throw new LocalError("bad_argument", "min_count must be a whole number, 0 or more.");
251
+ const rule = { require_types: [...new Set(types)], require_issuer_kind: kind ?? null, min_count: min ?? 0 };
252
+ if (isNoRule(rule))
253
+ throw new LocalError("bad_argument", "A rule needs something in it: require_types, require_issuer_kind or min_count. To remove a rule, use signal-rule-clear.");
254
+ // A call carries at most this many signals, so a rule asking for more could never be met and would refuse everyone.
255
+ if (rule.min_count > MAX_PRESENTED_SIGNALS || rule.require_types.length > MAX_PRESENTED_SIGNALS)
256
+ throw new LocalError("bad_argument", `A call carries at most ${MAX_PRESENTED_SIGNALS} signals, so a rule can't ask for more than that.`);
257
+ return rule;
258
+ }
259
+ // The command that puts this rule in force, or removes the rule when there is none. What a refusal tells an agent to relay, and what an undo runs.
260
+ #ruleCommand(direction, scope, target, rule, agentHex) {
261
+ const where = `--direction ${direction} --scope ${scope}${target ? ` --target ${target}` : ""}`;
262
+ if (rule === null)
263
+ return `cello signal-rule-clear ${where} --agent ${agentHex}`;
264
+ const parts = [rule.require_types.length ? `--require-types ${rule.require_types.join(",")}` : "", rule.require_issuer_kind ? `--require-issuer-kind ${rule.require_issuer_kind}` : "", rule.min_count ? `--min-count ${rule.min_count}` : ""].filter(Boolean);
265
+ return `cello signal-rule-set ${where} ${parts.join(" ")} --agent ${agentHex}`;
266
+ }
267
+ // The rule in words a person can read in a prompt or a notice, from its three demands and nothing else. A stored row is trimmed to a bare rule first.
268
+ #describeRule(rule) {
269
+ if (rule === null || isNoRule(rule))
270
+ return "no rule";
271
+ const demands = [
272
+ rule.require_types.length ? `the types ${rule.require_types.join(", ")}` : "",
273
+ rule.require_issuer_kind ? `a signal from an issuer of kind ${rule.require_issuer_kind}` : "",
274
+ rule.min_count ? `at least ${rule.min_count} signal${rule.min_count === 1 ? "" : "s"}` : "",
275
+ ].filter(Boolean);
276
+ return `a rule asking for ${demands.join(", ")}`;
277
+ }
278
+ #bare(row) {
279
+ return row ? { require_types: [...row.require_types], require_issuer_kind: row.require_issuer_kind, min_count: row.min_count } : null;
280
+ }
281
+ // Asking for more is free, anyone may. Asking for less, or swapping one demand for another, lets a caller through who is stopped now, so it needs a person.
282
+ signalRuleSet(agentId, agentHex, params) {
283
+ const { direction, scope, target } = this.#ruleKey(params);
284
+ const next = this.#ruleFrom(params);
285
+ const contactTier = scope === "contact" ? tierName(this.contacts.tierOf(agentId, fromHex(target))) : "unknown";
286
+ const before = this.#bare(this.rules.get(agentId, direction, scope, target));
287
+ const weakens = this.rules.weakens(agentId, direction, scope, target, next, contactTier);
288
+ const label = `${direction} ${scope}${target ? ` ${target}` : ""}`;
289
+ const undo = this.#ruleCommand(direction, scope, target, before, agentHex);
290
+ if (weakens)
291
+ requirePerson(params, `This loosens the ${label} signal rule for ${agentHex}, from ${this.#describeRule(before)} to ${this.#describeRule(next)}, so a call is let through that is stopped now.`, this.#ruleCommand(direction, scope, target, next, agentHex));
292
+ this.rules.put(agentId, direction, scope, target, next);
293
+ this.#weakened(agentId, `signal_rule.${direction}.${scope}${target ? `.${target}` : ""}`, this.#describeRule(before), this.#describeRule(next), weakens ? "loosen" : "tighten", params, undo);
294
+ return { direction, scope, target: target || undefined, ...next, loosened: weakens };
295
+ }
296
+ signalRuleClear(agentId, agentHex, params) {
297
+ const { direction, scope, target } = this.#ruleKey(params);
298
+ const before = this.#bare(this.rules.get(agentId, direction, scope, target));
299
+ if (before === null)
300
+ return { direction, scope, target: target || undefined, cleared: false };
301
+ const contactTier = scope === "contact" ? tierName(this.contacts.tierOf(agentId, fromHex(target))) : "unknown";
302
+ const weakens = this.rules.weakens(agentId, direction, scope, target, null, contactTier);
303
+ const redo = this.#ruleCommand(direction, scope, target, before, agentHex);
304
+ if (weakens)
305
+ requirePerson(params, `Removing the ${direction} ${scope}${target ? ` ${target}` : ""} signal rule for ${agentHex} lets through calls it stops now.`, this.#ruleCommand(direction, scope, target, null, agentHex));
306
+ this.rules.clear(agentId, direction, scope, target);
307
+ this.#weakened(agentId, `signal_rule.${direction}.${scope}${target ? `.${target}` : ""}`, this.#describeRule(before), "no rule", weakens ? "loosen" : "tighten", params, redo);
308
+ return { direction, scope, target: target || undefined, cleared: true, loosened: weakens };
309
+ }
310
+ contactSetAway(agentId, params) {
311
+ const contact = hexParam(params, "contact");
312
+ const raw = optionalText(params, "text");
313
+ const text = raw === undefined || raw.trim() === "" ? null : raw;
314
+ const max = this.reach.number(agentId, "away.max_chars");
315
+ if (text && text.length > max)
316
+ throw new LocalError("invalid_message", `an away message must be ${max} characters or fewer`);
317
+ this.contacts.put(agentId, contact.id, { away_message: text });
318
+ return this.#contactView(agentId, this.contacts.get(agentId, contact.id));
319
+ }
320
+ contactSetMoniker(agentId, params) {
321
+ const contact = hexParam(params, "contact");
322
+ this.contacts.put(agentId, contact.id, { moniker: this.#monikerOf(params) ?? null });
323
+ return this.#contactView(agentId, this.contacts.get(agentId, contact.id));
324
+ }
325
+ // ---- Settings ----
326
+ listSettings(agentId) {
327
+ return { settings: listSettings(this.#store), ...(agentId ? { tiers: this.reach.tiers(agentId), agent_settings: this.reach.settings(agentId) } : {}) };
328
+ }
329
+ settingsSet(agentId, agentHex, params) {
330
+ const name = optionalText(params, "name");
331
+ if (!name)
332
+ throw new LocalError("bad_argument", "name the setting to change");
333
+ const value = optionalText(params, "value");
334
+ const clear = params["clear"] === true;
335
+ if (clear === (value !== undefined))
336
+ throw new LocalError("bad_argument", "give a value, or --clear to go back to the default, and not both");
337
+ const agentFlag = agentHex ? ` --agent ${agentHex}` : "";
338
+ const command = `cello settings-set ${name} ${clear ? "--clear" : JSON.stringify(value)}${agentFlag}`;
339
+ const isAgentKey = ["bounds.", "away.", "limits.", "policy.", "contacts.", "calling."].some((prefix) => name.startsWith(prefix));
340
+ if (!isAgentKey) {
341
+ if (clear)
342
+ throw new LocalError("bad_argument", "a daemon setting has no --clear: set the value you want");
343
+ // Tuning, not a guard, so any shell of the owner's can do it. It just isn't an agent's tool.
344
+ if (params["caller"] !== "cli")
345
+ throw new LocalError("person_required", `A daemon setting is changed from the owner's own shell. Nothing changed. Relay this to your operator: ${command}`);
346
+ try {
347
+ changeSetting(this.#store, name, value);
348
+ }
349
+ catch (err) {
350
+ if (err instanceof SettingError)
351
+ throw new LocalError("bad_setting", err.message);
352
+ throw err;
353
+ }
354
+ logEvent("settings.changed", { name, value });
355
+ return { settings: listSettings(this.#store), note: "This takes effect at the next login." };
356
+ }
357
+ if (!agentId || !agentHex)
358
+ throw new LocalError("bad_argument", `${name} belongs to one agent, so name it with --agent`);
359
+ const change = this.reach.plan(agentId, name, clear ? null : value);
360
+ if (change.direction === "loosen")
361
+ requirePerson(params, `This changes ${name} from ${change.from} to ${change.to} for ${agentHex}, which loosens it.`, command);
362
+ change.apply();
363
+ if (change.direction !== "neutral")
364
+ this.#weakened(agentId, name, change.from, change.to, change.direction, params, `cello settings-set ${name} ${JSON.stringify(change.from)} --agent ${agentHex}`);
365
+ return { name, value: change.to, was: change.from };
366
+ }
367
+ // ---- Guards ----
368
+ listGuards(agentId, key) {
369
+ const guards = this.guards.list(agentId);
370
+ if (key === undefined)
371
+ return { guards };
372
+ const found = guards.find((guard) => guard.key === key);
373
+ if (!found)
374
+ throw new LocalError("unknown_guard", `there's no guard named ${key}`);
375
+ return found;
376
+ }
377
+ guardSet(agentId, agentHex, params) {
378
+ const key = optionalText(params, "key");
379
+ const raw = optionalText(params, "value") ?? "";
380
+ const plan = this.guards.plan(agentId, key, raw);
381
+ const command = `cello config-set ${key} ${JSON.stringify(raw)} --agent ${agentHex}`;
382
+ if (plan.direction === "loosen")
383
+ requirePerson(params, `This loosens the guard ${key}, to ${JSON.stringify(plan.value)}, for ${agentHex}.`, command);
384
+ this.guards.apply(agentId, plan, params["person_confirmed"] === true);
385
+ logEvent("guard.changed", { agent: agentHex, key, direction: plan.direction, confirmed: params["person_confirmed"] === true });
386
+ if (plan.direction === "loosen")
387
+ this.#hooks.notify(agentId, `The guard ${key} changed to ${JSON.stringify(plan.value)}, by a person at this machine's terminal. If that wasn't you, a person can change it back with config-set.`);
388
+ return { key, value: plan.value, was: plan.was, direction: plan.direction };
389
+ }
390
+ // What the guards did: messages stopped or flagged, callers refused, and every change, newest first.
391
+ screeningLog(agentId, limit) {
392
+ const count = limit === undefined ? DEFAULT_LOG_LIMIT : limit;
393
+ if (!Number.isInteger(count) || count < 1)
394
+ throw new LocalError("bad_argument", "limit must be a whole number from 1 up");
395
+ const screened = this.#store.prepare("SELECT e.session_id, e.position, e.verdict, e.verdict_detail, s.counterparty_id FROM entries e JOIN sessions s ON s.agent_id = e.agent_id AND s.session_id = e.session_id WHERE e.agent_id = ? AND e.own = 0 AND e.verdict IN ('flagged', 'blocked') ORDER BY e.id DESC LIMIT ?").all(agentId, count);
396
+ return {
397
+ screened: screened.map((row) => {
398
+ const detail = JSON.parse(row.verdict_detail);
399
+ return { session_id: toHex(row.session_id), position: row.position, from_id: toHex(row.counterparty_id), verdict: row.verdict, findings: detail.findings.map((f) => f.what), reason: detail.reason };
400
+ }),
401
+ refused_callers: this.reach.refusals(agentId).map((row) => ({ contact_id: toHex(row.contact_id), first_at: new Date(row.first_refused_at).toISOString(), last_at: new Date(row.last_refused_at).toISOString(), times: row.times, last_reason: row.last_reason })),
402
+ changes: this.guards.changes(agentId, count).map((row) => ({ key: row.key, from: row.from_json === null ? null : JSON.parse(row.from_json), to: JSON.parse(row.to_json), direction: row.direction, by_a_person: row.confirmed === 1, at: new Date(row.at).toISOString() })),
403
+ };
404
+ }
405
+ // ---- Screening rules. One sender's rule outranks its tier's, which outranks the default of full. ----
406
+ screeningRule(agentId, senderHex) {
407
+ const own = this.#store.screeningRule(agentId, "sender", senderHex);
408
+ if (own)
409
+ return { level: own, from: "agent_rule" };
410
+ const tier = tierName(this.contacts.tierOf(agentId, fromHex(senderHex)));
411
+ const byTier = this.#store.screeningRule(agentId, "tier", tier);
412
+ return byTier ? { level: byTier, from: "tier_rule" } : { level: "full", from: "default" };
413
+ }
414
+ setScreening(agentId, agentHex, params) {
415
+ const level = params["level"];
416
+ if (!(level in LEVEL_STRENGTH))
417
+ throw new LocalError("bad_argument", "level must be full, deterministic or off");
418
+ const tier = optionalText(params, "tier");
419
+ if ((params["sender"] === undefined) === (tier === undefined))
420
+ throw new LocalError("bad_argument", "name one sender, or one tier with --tier");
421
+ if (tier !== undefined)
422
+ return this.#setTierScreening(agentId, agentHex, tier, level, params);
423
+ const sender = hexParam(params, "sender");
424
+ const before = this.screeningRule(agentId, sender.hex).level;
425
+ if (LEVEL_STRENGTH[level] < LEVEL_STRENGTH[before]) {
426
+ requirePerson(params, `This weakens screening of everything ${sender.hex} sends to ${agentHex}, to level ${level}.\nAn agent you control can still forward something hostile it picked up elsewhere.`, `cello screening ${sender.hex} --level ${level} --agent ${agentHex}`);
427
+ }
428
+ return this.#applyScreening(agentId, agentHex, "sender", sender.hex, before, level, params, { sender: sender.hex });
429
+ }
430
+ #setTierScreening(agentId, agentHex, tier, level, params) {
431
+ const rule = this.#store.screeningRule(agentId, "tier", tier);
432
+ const before = rule ?? "full";
433
+ if (tierFromName(tier) === undefined)
434
+ throw new LocalError("invalid_tier", "tier must be whitelisted or vip");
435
+ if (level !== "full" && !WEAKENABLE_TIERS.includes(tier))
436
+ throw new LocalError("tier_not_weakenable", `Screening can't be weakened for the whole ${tier} tier, by anyone: an agent's own call or reply can put a stranger in known. It can be weakened for whitelisted or vip, or for one named agent.`);
437
+ if (LEVEL_STRENGTH[level] < LEVEL_STRENGTH[before]) {
438
+ requirePerson(params, `This weakens screening of everything sent to ${agentHex} by anyone in the ${tier} tier, to level ${level}.\nEven a trusted agent can be compromised, and can forward something hostile it picked up elsewhere.`, `cello screening --tier ${tier} --level ${level} --agent ${agentHex}`);
439
+ }
440
+ return this.#applyScreening(agentId, agentHex, "tier", tier, before, level, params, { tier });
441
+ }
442
+ #applyScreening(agentId, agentHex, scope, subject, before, level, params, named) {
443
+ this.#store.setScreeningRule(agentId, scope, subject, level);
444
+ const direction = LEVEL_STRENGTH[level] < LEVEL_STRENGTH[before] ? "loosen" : LEVEL_STRENGTH[level] > LEVEL_STRENGTH[before] ? "tighten" : "neutral";
445
+ this.guards.record(agentId, `screening.${subject}`, before, level, direction, params["person_confirmed"] === true);
446
+ logEvent("screening.rule_changed", { agent: agentHex, scope, subject, from: before, to: level });
447
+ const flags = scope === "tier" ? `--tier ${subject}` : subject;
448
+ const whose = scope === "tier" ? `the ${subject} tier` : subject;
449
+ this.#hooks.notify(agentId, `The screening rule for messages from ${whose} changed from ${before} to ${level}, by a person at this machine's terminal. If that wasn't you, run: cello screening ${flags} --level full --agent ${agentHex}`);
450
+ return { agent_id: agentHex, ...named, level, was: before };
451
+ }
452
+ // ---- Policies ----
453
+ #policy(work) {
454
+ try {
455
+ return work();
456
+ }
457
+ catch (err) {
458
+ if (err instanceof PolicyValidationError)
459
+ throw new LocalError(err.reason, err.message);
460
+ throw err;
461
+ }
462
+ }
463
+ policyList(agentId) {
464
+ return { policies: this.policies.list(agentId) };
465
+ }
466
+ policyPending(agentId) {
467
+ return { pending: this.#proposals.pending(agentId) };
468
+ }
469
+ // Changes nothing: a person approves it, or it's dropped when its time runs out.
470
+ policyPropose(agentId, agentHex, params) {
471
+ const scope = params["scope"];
472
+ const type = params["type"];
473
+ const target = optionalText(params, "target") ?? "";
474
+ const text = optionalText(params, "text");
475
+ const none = params["none"] === true;
476
+ const clear = params["clear"] === true;
477
+ if ([text !== undefined, none, clear].filter(Boolean).length !== 1)
478
+ throw new LocalError("bad_argument", "give the policy's text, or --none to send nothing, or --clear to remove it");
479
+ const everyN = params["every_n"];
480
+ const proposal = this.#policy(() => this.#proposals.propose(agentId, {
481
+ scope,
482
+ target: scope === "contact" ? target.toLowerCase() : target,
483
+ type,
484
+ action: clear ? "clear" : "set",
485
+ ...(clear ? {} : { value: none ? { mode: "none" } : { mode: "text", text: text } }),
486
+ ...(everyN === undefined ? {} : { everyN }),
487
+ }, params["caller"] === "cli" ? "operator" : "agent"));
488
+ return { ...proposal, in_force: false, next: `Nothing has changed. A person approves it at a terminal: cello policy-approve ${proposal.proposal_id} --agent ${agentHex}` };
489
+ }
490
+ policyApprove(agentId, agentHex, params) {
491
+ const proposalId = optionalText(params, "proposal_id");
492
+ const pending = this.#proposals.pending(agentId).find((p) => p.proposal_id === proposalId);
493
+ if (!pending)
494
+ throw new LocalError("proposal_not_found", `no pending proposal ${proposalId}. They last ${this.reach.setting(agentId, "policy.proposal_hours")} hours: see policy-pending.`);
495
+ if (params["decline"] === true) {
496
+ this.#proposals.decline(agentId, proposalId);
497
+ return { declined: true, proposal_id: proposalId };
498
+ }
499
+ const was = pending.was ? (pending.was.mode === "none" ? "NONE" : pending.was.text) : "nothing";
500
+ const now = pending.action === "clear" ? "nothing" : pending.mode === "none" ? "NONE" : pending.text;
501
+ requirePerson(params, `This puts in force the ${pending.type} policy at ${pending.scope}${pending.target ? ` ${pending.target}` : ""}, proposed by ${pending.proposed_by}.\nIt was: ${was}\nIt becomes: ${now}`, `cello policy-approve ${proposalId} --agent ${agentHex}`);
502
+ const result = this.#proposals.approve(agentId, proposalId);
503
+ if (!result.ok)
504
+ throw new LocalError(result.reason, `no pending proposal ${proposalId}`);
505
+ this.guards.record(agentId, `policy.${pending.type}.${pending.scope}${pending.target ? `.${pending.target}` : ""}`, was, now, "neutral", true);
506
+ return { approved: true, proposal_id: proposalId, in_force: this.policies.list(agentId) };
507
+ }
508
+ admissionFor(agentId, peerHex, tier) {
509
+ return admissionPolicyField({ store: this.policies, agentId, peerHex, tierName: tierName(tier) });
510
+ }
511
+ conductFor(agentId, sessionHex, peerHex, tier, count) {
512
+ return attachConductPolicy({ store: this.policies, cadence: this.#cadence, agentId, sessionHex, peerHex, tierName: tierName(tier), count });
513
+ }
514
+ }
@@ -0,0 +1,36 @@
1
+ import type { Direction } from "./reach.ts";
2
+ import type { Store } from "./store.ts";
3
+ interface Guard {
4
+ default: unknown;
5
+ baseline: unknown;
6
+ describes: string;
7
+ classify(from: unknown, to: unknown): Direction;
8
+ coerce(raw: string): unknown;
9
+ }
10
+ export declare const GUARDS: Record<string, Guard>;
11
+ export interface GuardPlan {
12
+ key: string;
13
+ value: unknown;
14
+ was: unknown;
15
+ direction: Direction;
16
+ }
17
+ export interface ChangeRow {
18
+ key: string;
19
+ from_json: string | null;
20
+ to_json: string;
21
+ direction: string;
22
+ confirmed: number;
23
+ at: number;
24
+ }
25
+ export declare class Guards {
26
+ #private;
27
+ constructor(store: Store);
28
+ writeDefaults(agentId: Uint8Array): void;
29
+ value<T>(agentId: Uint8Array, key: string): T;
30
+ list(agentId: Uint8Array): unknown[];
31
+ plan(agentId: Uint8Array, key: string, raw: string): GuardPlan;
32
+ apply(agentId: Uint8Array, plan: GuardPlan, confirmed: boolean): void;
33
+ record(agentId: Uint8Array, key: string, from: unknown, to: unknown, direction: Direction, confirmed: boolean): void;
34
+ changes(agentId: Uint8Array, limit: number): ChangeRow[];
35
+ }
36
+ export {};