@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,2882 @@
1
+ // The owner's node: keys, conversations and recovery. Durable state decides everything.
2
+ // After any restart, the same catch-up path runs: resend what's pending, then read from position.
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { openSessionContent, sealSessionContent } from "../protocol/aead.js";
5
+ import { ChainVerifier, provesTwoAcks, verifyTranscript, witnessed } from "../protocol/chain.js";
6
+ import { ZERO_HASH, equalBytes, toHex } from "../protocol/encode.js";
7
+ import { generateIdentitySeeds, identityId, signerFromSeeds, verifySignature } from "../protocol/identity.js";
8
+ import { deriveSessionSecrets, destroySessionEphemeral, generateSessionEphemeral } from "../protocol/key-agreement.js";
9
+ import { verifyConsistency } from "../protocol/merkle.js";
10
+ import { mlKemDecapsulate, mlKemEncapsulate } from "../protocol/ml-kem.js";
11
+ import { deriveSessionSalt, generateSaltContribution, saltedContentHash } from "../protocol/salt.js";
12
+ import { checkSealRecord, decodeSealRecord, describeSeal, sealId, sealSummary } from "../protocol/seal.js";
13
+ import { STATUS_DOMAIN, checkStatusLog } from "../protocol/status.js";
14
+ import { buildTranscript } from "../protocol/transcript.js";
15
+ import { AgentStatus, StatusIssuer, StatusReason, statusStatementBytes, EntryKind, EntryMode, acceptBytes, refuseBytes, agentAuthBytes, ciphertextHash, confirmBytes, deliveryAckBytes, entryBytes, entryHash, greetingBytes, offerBytes, registerBytes, sealRequestBytes, structureHash, MAX_REFUSED_POSITIONS, bodyBytes, refusedList, readBodyBytes, } from "../protocol/structures.js";
16
+ import { LONG_CIPHERTEXT_BYTES, MAX_CIPHERTEXT_BYTES, MAX_GREETING_BYTES, fromB64, identityCodec, signatureCodec, signedAccept, signedAck, signedAssignment, signedConfirm, signedDeliveryAck, signedEntry, signedGreeting, signedOffer, signedRefuse, signedSealRequest, signedStatusStatement, toB64, } from "../protocol/wire.js";
17
+ import { Away, ONE_MESSAGE_LINE } from "./away.js";
18
+ import { LocalError, requirePerson } from "./errors.js";
19
+ import { Governance, REFUSAL_SENTENCES } from "./governance.js";
20
+ import { validateMoniker } from "./who-label.js";
21
+ import { productionRootKeys } from "../protocol/issuer-roots.js";
22
+ import { SHIPPED_ISSUER_LIST } from "../shipped-issuer-list.js";
23
+ import { HOW_TO_GET_A_CODE, Wallet } from "./wallet.js";
24
+ import { EncryptionKeys, PresentedStore, ensurePresentedSchema } from "./presented.js";
25
+ import { MAX_PRESENTED_SIGNALS, PresentedTooMany, checkEncryptionKey, openFromKey, openUnderSession, sealToKey, sealUnderSession } from "../protocol/presented-signals.js";
26
+ import { PlainTextServer, formatAddress, parseAddress, serverUrlFrom } from "./address.js";
27
+ import { ServerLink, ServerRefused, ServerUnreachable } from "./link.js";
28
+ import { logEvent } from "./log.js";
29
+ import { OutboundRateLimiter } from "./rate-limit.js";
30
+ import { OutboundScreen, ScreeningQueue } from "./screening.js";
31
+ import { loadSettings } from "./settings.js";
32
+ import { TIER, tierName } from "./tiers.js";
33
+ import { evaluate, isNoRule } from "./signal-rules.js";
34
+ import { compareTranscripts, LOST_MESSAGE_GUIDANCE, NO_SESSION_GUIDANCE, OTHER_AGENTS_SESSION_GUIDANCE, SEAL_NOTE, SESSION_CLOSED_GUIDANCE, SIGNAL_ERROR, TRUNCATED_SESSION_GUIDANCE, noAgentGuidance, refusedGuidance, sealMismatchMessage, sessionGuidance, tooLargeMessage, unreadWarning } from "../guidance.js";
35
+ const SEND_WINDOW_MS = 10 * 60 * 1000;
36
+ const INITIATE_WAIT_MS = 20_000;
37
+ const POSITION_CHECK_MS = 30_000;
38
+ const AUTH_RETRY_MS = 5_000;
39
+ // How long a person waits for each server to hear of a status change before being told which it hasn't reached. It keeps trying.
40
+ const STATUS_TELL_MS = 5_000;
41
+ // How long a send waits for its long upload before saying "not sent yet" and leaving it to carry on.
42
+ const LONG_SEND_PATIENCE_MS = 20_000;
43
+ // As long as a signed entry stays valid. A dead connection shows sooner, as silence.
44
+ const LONG_CALL_TIMEOUT_MS = SEND_WINDOW_MS;
45
+ const STILL_UPLOADING = Symbol("still uploading");
46
+ // One reply's message text. Replies are built whole on the one thread every agent shares, and a string can't pass about 512 MB.
47
+ const MAX_REPLY_BYTES = 8_000_000;
48
+ export const CONFIG_SERVER_URL = "server_url";
49
+ const DEFAULT_AGENT_NAME = "agent";
50
+ const CONFIG_SERVER_IDENTITY = "server_identity";
51
+ const CONFIG_SEAL_KEY = "seal_key";
52
+ const CONFIG_SEAL_LOG_HEAD = "seal_log_head";
53
+ const SEAL_EVERYTHING_HELD = 0;
54
+ // Not refusals of the seal itself: the first means this agent's login hasn't finished, the second that the server failed.
55
+ const SEAL_RETRY_CODES = ["not_authenticated", "internal_error"];
56
+ // A timer can stop counting while a machine sleeps, so no wait outlasts this before the clock is read again.
57
+ const STANDBY_CHECK_MAX_MS = 60_000;
58
+ const LATEST_DATE_MS = 8.64e15;
59
+ // How long a run of verdicts is left to settle before the sender is told how far screening has got.
60
+ const SCREENED_ACK_DELAY_MS = 1_000;
61
+ const SENDER_BACKLOG_CHECK_MS = 250;
62
+ const CONFIG_MODEL_EVER_RAN = "screener_model_ever_ran";
63
+ const MODEL_MISSING = "This agent's database used the screening model, and the model isn't installed on this machine, so only the deterministic rules are running. To add it, a person runs: cello screener install";
64
+ const WORKER_CRASH_TELL_EVERY_MS = 60_000;
65
+ const SIGNAL_VALUES = ["over", "standby", "wrap"];
66
+ const BYTE_LIMIT_REASON = "this conversation is past its byte limit";
67
+ const greetingKey = (contentKey) => new Uint8Array(createHash("sha256").update("cello-session-greeting").update(contentKey).digest());
68
+ const refusalKey = (sharedSecret) => new Uint8Array(createHash("sha256").update("cello-session-refusal").update(sharedSecret).digest());
69
+ // Only these words ever come out of a refusal, whatever the other side put in it.
70
+ function refusalSentence(opened) {
71
+ const fallback = "This agent refused the call.";
72
+ if (!opened)
73
+ return fallback;
74
+ let parsed;
75
+ try {
76
+ parsed = JSON.parse(new TextDecoder().decode(opened));
77
+ }
78
+ catch {
79
+ return fallback;
80
+ }
81
+ if (typeof parsed.code !== "string" || !Object.hasOwn(REFUSAL_SENTENCES, parsed.code))
82
+ return fallback;
83
+ const sentence = REFUSAL_SENTENCES[parsed.code];
84
+ return Number.isSafeInteger(parsed.limit) ? `${sentence} The limit is ${parsed.limit}.` : sentence;
85
+ }
86
+ export { LocalError };
87
+ export const SIGNALS = ["over", "standby", "wrap"];
88
+ // Everything an agent is shown of a message. A signal or a number is only passed on if it's a value CELLO itself writes,
89
+ // because the text is the only part that's screened, and a hostile sender could put words in any other field.
90
+ function shownMessage(row, closing) {
91
+ const body = parseBody(row.body);
92
+ const estMinutes = typeof body?.est_minutes === "number" && body.est_minutes > 0 ? { est_minutes: body.est_minutes } : {};
93
+ if (row.own === 1) {
94
+ return closing ? { closed_their_side: true } : { text: body?.text ?? null, signal: body?.signal ?? null, ...estMinutes };
95
+ }
96
+ if (row.verdict === null)
97
+ return { screening: { verdict: "not_screened_yet" } };
98
+ const detail = JSON.parse(row.verdict_detail);
99
+ const screening = { verdict: row.verdict, findings: detail.findings, ...(detail.score === null ? {} : { score: detail.score }), ...(detail.reason ? { reason: detail.reason } : {}), ran: detail.ran };
100
+ if (row.verdict === "blocked")
101
+ return { blocked: true, screening };
102
+ if (closing)
103
+ return { closed_their_side: true };
104
+ const signal = SIGNAL_VALUES.includes(body?.signal) ? body?.signal : null;
105
+ return { text: body ? (detail.delivered ?? body.text) : null, signal, ...estMinutes, ...(body ? {} : { unreadable: true }), screening };
106
+ }
107
+ function parseHex(value, bytes, name) {
108
+ if (typeof value !== "string" || value.length !== bytes * 2 || !/^[0-9a-fA-F]+$/.test(value)) {
109
+ throw new LocalError("bad_argument", `${name} must be ${bytes * 2} hex characters`);
110
+ }
111
+ return new Uint8Array(Buffer.from(value, "hex"));
112
+ }
113
+ const parseBody = readBodyBytes;
114
+ const UNVERIFIABLE_REASON = "its text isn't what its author signed";
115
+ // Both daemons start from the server's ack time, so they agree on the due time. Each compares it with its own clock,
116
+ // so a clock that's wrong by a minute tells a minute early or late, and changes nothing else.
117
+ // The minutes can come from the other party, so anything that isn't a usable time counts as no time.
118
+ function standbyDue(estMinutes, ackTime) {
119
+ if (typeof estMinutes !== "number" || !(estMinutes > 0))
120
+ return undefined;
121
+ const due = Math.ceil(ackTime + estMinutes * 60_000);
122
+ return due <= LATEST_DATE_MS ? due : undefined;
123
+ }
124
+ function concat(a, b) {
125
+ const out = new Uint8Array(a.length + b.length);
126
+ out.set(a, 0);
127
+ out.set(b, a.length);
128
+ return out;
129
+ }
130
+ function notSealedYet(reason) {
131
+ return { sealed: false, status: "not_sealed_yet", message: `This isn't sealed yet: ${reason}. The request is saved and retried by itself, and you'll get a notice.` };
132
+ }
133
+ export class Engine {
134
+ #store;
135
+ #events;
136
+ #link;
137
+ // Long uploads under way, by entry row. Each outlives the send that started it, so a retry never sends it twice.
138
+ #uploads = new Map();
139
+ #url;
140
+ #home;
141
+ #visiting = new Map();
142
+ #agents = new Map();
143
+ #lanes = new Map();
144
+ #verifiers = new Map();
145
+ #activation = new Map();
146
+ #server;
147
+ #positionCheck;
148
+ #standbyCheck;
149
+ #standbyCheckAt = 0;
150
+ #settings;
151
+ #screening;
152
+ #outbound = new OutboundScreen();
153
+ // Below zero, so a channel's job can't share an id with an entry's.
154
+ #nextChannelJob = 0;
155
+ #ackTimers = new Map();
156
+ #rates = new Map();
157
+ #refusals = new Map();
158
+ governance;
159
+ wallet;
160
+ #keys;
161
+ #presented;
162
+ #keyBusy = new Set();
163
+ #away;
164
+ #lastCrashTold = 0;
165
+ #modelMissingTold = false;
166
+ constructor(store, url, events) {
167
+ this.#store = store;
168
+ this.#events = events;
169
+ this.#url = url;
170
+ this.#settings = loadSettings(store);
171
+ ensurePresentedSchema(store);
172
+ this.#keys = new EncryptionKeys(store);
173
+ this.#presented = new PresentedStore(store);
174
+ this.wallet = new Wallet(store, {
175
+ keys: (agentHex) => {
176
+ const row = store.agents().find((candidate) => toHex(candidate.agent_id) === agentHex);
177
+ if (!row)
178
+ throw new LocalError("unknown_agent", noAgentGuidance(agentHex));
179
+ return { identity: this.#requireAgent(agentHex).signer.publicIdentity, seeds: { ed: new Uint8Array(row.ed_seed), pq: new Uint8Array(row.pq_seed) } };
180
+ },
181
+ screen: (agentHex, issuerHex, text) => this.channelHost().screen(agentHex, `signal:${issuerHex}`, 0, issuerHex, text),
182
+ notify: (agentId, text) => {
183
+ const agent = this.#agents.get(toHex(agentId));
184
+ if (agent)
185
+ this.#notify(agent, null, text);
186
+ },
187
+ roots: productionRootKeys,
188
+ shippedList: SHIPPED_ISSUER_LIST,
189
+ publishToServer: (agentHex, file) => this.#publicSignalCall(agentHex, undefined, "signal.publish", (agent) => ({ agent: toB64(agent.signer.id), signal: toB64(file) })).then(() => undefined),
190
+ unpublishFromServer: (agentHex, signalId) => this.#publicSignalCall(agentHex, undefined, "signal.unpublish", (agent) => ({ agent: toB64(agent.signer.id), signalId: toB64(signalId) })).then(() => undefined),
191
+ readPublic: async (agentHex, address) => {
192
+ let parsed;
193
+ try {
194
+ parsed = parseAddress(address);
195
+ }
196
+ catch (err) {
197
+ throw new LocalError(err instanceof PlainTextServer ? err.code : "bad_argument", err instanceof Error ? err.message : String(err));
198
+ }
199
+ const targetId = parseHex(parsed.id, 32, "address");
200
+ const target = toHex(targetId);
201
+ const answer = await this.#publicSignalCall(agentHex, parsed.server, "signal.public", (agent) => ({ agent: toB64(agent.signer.id), target: toB64(targetId) }));
202
+ if (!Array.isArray(answer.signals) || answer.signals.some((entry) => typeof entry !== "string"))
203
+ throw new LocalError("bad_server_answer", "That server's answer wasn't a list of signals, so nothing was read.");
204
+ return { target, files: answer.signals.map((entry) => new Uint8Array(Buffer.from(entry, "base64url"))) };
205
+ },
206
+ });
207
+ this.governance = new Governance(store, {
208
+ notify: (agentId, text) => {
209
+ const agent = this.#agents.get(toHex(agentId));
210
+ if (agent)
211
+ this.#notify(agent, null, text);
212
+ },
213
+ isLocalAgent: (id) => this.#agents.has(toHex(id)),
214
+ });
215
+ this.#away = new Away(store);
216
+ this.#screening = new ScreeningQueue({
217
+ load: (job) => this.#loadForScreen(job),
218
+ verdict: (job, verdict) => this.#onVerdict(job, verdict),
219
+ delayed: (job, aboutSeconds) => this.#onScreenDelayed(job, aboutSeconds),
220
+ workerCrashed: (message, waiting) => this.#onWorkerCrashed(message, waiting),
221
+ modelChecked: (model) => this.#onModelChecked(model),
222
+ }, this.#settings);
223
+ this.#link = new ServerLink(url, {
224
+ checkIdentity: (identity) => this.#checkServerIdentity(identity, url),
225
+ connected: async (server) => {
226
+ this.#server = server;
227
+ for (const agent of this.#agents.values())
228
+ void this.#bringOnline(agent, server);
229
+ },
230
+ disconnected: () => {
231
+ this.#server = undefined;
232
+ for (const agent of this.#agents.values())
233
+ agent.online = false;
234
+ },
235
+ push: (frame) => this.#onPush(frame, this.#home),
236
+ });
237
+ this.#home = { url, home: true, link: this.#link, longLink: this.#longLinkTo(url, () => this.#home), longServer: undefined, longProved: new Set(), server: undefined, wanted: new Set(), online: new Set(), visits: new Map(), opening: 0 };
238
+ }
239
+ async start() {
240
+ const pinned = this.#store.getConfig(CONFIG_SERVER_URL);
241
+ if (pinned && pinned !== this.#url)
242
+ throw new LocalError("server_changed", `this data belongs to ${pinned}, not ${this.#url}. Use a separate CELLO_HOME.`);
243
+ this.#store.setConfig(CONFIG_SERVER_URL, this.#url);
244
+ for (const row of this.#store.agents()) {
245
+ const signer = await signerFromSeeds({ ed: row.ed_seed, pq: row.pq_seed });
246
+ const statuses = new Map(this.#store.statusRows(signer.id).map((status) => [status.server_url, status]));
247
+ this.#agents.set(toHex(signer.id), { signer, hex: toHex(signer.id), name: row.name, registered: row.registered === 1, awaitingSignal: row.awaiting_signal === 1, online: false, statuses });
248
+ this.governance.writeDefaults(signer.id);
249
+ }
250
+ this.#checkStandbys();
251
+ this.#screening.start();
252
+ this.#outbound.start();
253
+ // A restart repeats no finished work: whatever had no verdict is simply still in the table.
254
+ for (const row of this.#store.unscreened()) {
255
+ this.#screening.add({ entryId: row.id, agentHex: toHex(row.agent_id), sessionHex: toHex(row.session_id), position: row.position, senderHex: toHex(row.sender), bytes: row.size, arrived: Date.now() });
256
+ }
257
+ this.#link.start();
258
+ this.#retryOutbox();
259
+ this.#home.longLink.start();
260
+ for (const row of this.#away.unscreened())
261
+ this.#screenGreeting(row);
262
+ // Back to every conversation hosted elsewhere, because a restart doesn't end one.
263
+ for (const agent of this.#agents.values()) {
264
+ for (const local of this.#store.sessionsOf(agent.signer.id)) {
265
+ if (local.server_url && !this.#visitFinished(agent, local))
266
+ this.#routeFor(agent, local);
267
+ }
268
+ }
269
+ // Pushes are hints. This catches a lost one, so it costs seconds rather than a conversation.
270
+ this.#positionCheck = setInterval(() => {
271
+ this.#catchUpEverywhere();
272
+ this.#retryOutbox();
273
+ this.#retireIdleVisits();
274
+ // A replaced public signal that the server hasn't yet been told to drop. The wallet limits this to one try a minute.
275
+ for (const agent of this.#agents.values())
276
+ if (agent.online)
277
+ this.#background("encryption key", this.#publishKey(agent));
278
+ for (const agent of this.#agents.values())
279
+ this.wallet.settlePublic(agent.hex).catch((err) => logEvent("signal.public.settle_failed", { agent: agent.hex, message: err instanceof Error ? err.message : String(err) }));
280
+ }, POSITION_CHECK_MS);
281
+ }
282
+ stop() {
283
+ clearInterval(this.#positionCheck);
284
+ clearTimeout(this.#standbyCheck);
285
+ for (const timer of this.#ackTimers.values())
286
+ clearTimeout(timer);
287
+ this.#screening.stop();
288
+ this.#outbound.stop();
289
+ this.#link.stop();
290
+ this.#home.longLink.stop();
291
+ for (const route of this.#visiting.values()) {
292
+ route.link.stop();
293
+ route.longLink.stop();
294
+ }
295
+ }
296
+ #longLinkTo(url, route) {
297
+ return new ServerLink(url, {
298
+ checkIdentity: (identity) => this.#checkServerIdentity(identity, url),
299
+ connected: async (server) => {
300
+ route().longServer = server;
301
+ route().longProved.clear();
302
+ },
303
+ disconnected: () => { route().longServer = undefined; },
304
+ // The server only ever pushes on the connection an agent came online on.
305
+ push: () => undefined,
306
+ }, "server_long");
307
+ }
308
+ // Each call still names its agent. Proof is per agent and per connection, so an agent proves itself here the first time it needs to.
309
+ // It goes to the server hosting the conversation, which on a visit isn't this daemon's own.
310
+ async #longCall(agent, route, method, params) {
311
+ const server = route.longServer;
312
+ if (!server)
313
+ throw new ServerUnreachable(route.longLink.problem ?? "the connection for long messages isn't up");
314
+ if (!route.longProved.has(agent.hex)) {
315
+ if (route.home) {
316
+ const clientNonce = new Uint8Array(randomBytes(32));
317
+ const proof = agentAuthBytes({ serverId: server.id, agentId: agent.signer.id, serverNonce: server.nonce, clientNonce });
318
+ const signature = await agent.signer.sign("cello-agent-auth", proof);
319
+ await route.longLink.call("auth", { agentId: toB64(agent.signer.id), clientNonce: toB64(clientNonce), signature: signatureCodec.encode(signature), long: true }, LONG_CALL_TIMEOUT_MS);
320
+ }
321
+ else {
322
+ await route.longLink.call("visit", { ...await this.#visitProof(agent, server), long: true }, LONG_CALL_TIMEOUT_MS);
323
+ }
324
+ if (route.longServer === server)
325
+ route.longProved.add(agent.hex);
326
+ }
327
+ return route.longLink.call(method, params, LONG_CALL_TIMEOUT_MS);
328
+ }
329
+ // ---- Screening. A verdict goes on the entry, and it's the only thing that makes a message deliverable. ----
330
+ #loadForScreen(job) {
331
+ if (job.channelText) {
332
+ const reader = this.#agents.get(job.agentHex);
333
+ if (!reader)
334
+ return null;
335
+ const guards = this.governance.guards;
336
+ return { body: job.channelText.bytes, level: this.governance.screeningRule(reader.signer.id, job.senderHex).level, language: { enforce: guards.value(reader.signer.id, "language_enforce"), allow: guards.value(reader.signer.id, "language_allow") } };
337
+ }
338
+ const body = this.#store.bodyOf(job.entryId);
339
+ const agent = this.#agents.get(job.agentHex);
340
+ if (!body || !agent)
341
+ return null;
342
+ const language = { enforce: this.governance.guards.value(agent.signer.id, "language_enforce"), allow: this.governance.guards.value(agent.signer.id, "language_allow") };
343
+ return { body, level: this.governance.screeningRule(agent.signer.id, job.senderHex).level, language };
344
+ }
345
+ // The doorbell comes after the write, so anyone it wakes finds the message there.
346
+ #onVerdict(job, verdict) {
347
+ if (job.channelText) {
348
+ job.channelText.done(verdict);
349
+ return;
350
+ }
351
+ const agent = this.#agents.get(job.agentHex);
352
+ if (!agent)
353
+ return;
354
+ const sessionId = parseHex(job.sessionHex, 16, "session id");
355
+ const detail = { delivered: verdict.delivered, findings: verdict.findings, reason: verdict.reason, score: verdict.score, ran: verdict.ran };
356
+ const row = this.#store.entryAt(agent.signer.id, sessionId, job.position);
357
+ if (!row)
358
+ return;
359
+ const closing = signedEntry.decode(JSON.parse(row.entry)).fields.kind === EntryKind.close;
360
+ this.#store.transaction(() => {
361
+ this.#store.setVerdict(job.entryId, verdict.verdict, JSON.stringify(detail));
362
+ if (verdict.verdict === "blocked")
363
+ this.#store.addNotice(agent.signer.id, sessionId, `The message at position ${job.position} was not delivered: ${verdict.reason}.`);
364
+ });
365
+ logEvent("screening.verdict", { agent: job.agentHex, session: job.sessionHex, position: job.position, verdict: verdict.verdict, findings: verdict.findings.map((f) => f.what), score: verdict.score, ms: Date.now() - job.arrived });
366
+ this.#events.ring(agent.hex, { type: closing ? "peer_closed" : "message", agent: agent.name, session_id: job.sessionHex, from_id: job.senderHex });
367
+ this.#ackSoon(agent, job.sessionHex);
368
+ }
369
+ #onScreenDelayed(job, aboutSeconds) {
370
+ // A channel has no sender waiting on this reader, and its reader is told by channel_read.
371
+ if (job.channelText)
372
+ return;
373
+ const agent = this.#agents.get(job.agentHex);
374
+ if (!agent)
375
+ return;
376
+ logEvent("screening.delayed", { agent: job.agentHex, session: job.sessionHex, position: job.position, about_seconds: aboutSeconds });
377
+ this.#events.ring(agent.hex, { type: "screening_delayed", agent: agent.name, session_id: job.sessionHex, position: job.position, about_seconds: aboutSeconds });
378
+ const sessionId = parseHex(job.sessionHex, 16, "session id");
379
+ this.#background("screening delay ack", this.#lane(agent.hex, job.sessionHex, async () => {
380
+ const local = this.#store.session(agent.signer.id, sessionId);
381
+ if (local)
382
+ await this.#deliver(agent, local, aboutSeconds);
383
+ }));
384
+ }
385
+ // A database can move to a machine without the model. That's said plainly, once per start, rather than quietly running less.
386
+ #onModelChecked(model) {
387
+ if (model.running) {
388
+ this.#store.setConfig(CONFIG_MODEL_EVER_RAN, "1");
389
+ return;
390
+ }
391
+ if (this.#store.getConfig(CONFIG_MODEL_EVER_RAN) !== "1" || this.#modelMissingTold)
392
+ return;
393
+ this.#modelMissingTold = true;
394
+ logEvent("screening.model_missing", { state: model.state, reason: model.reason });
395
+ for (const agent of this.#agents.values())
396
+ this.#notify(agent, null, MODEL_MISSING);
397
+ }
398
+ #onWorkerCrashed(message, waiting) {
399
+ const now = Date.now();
400
+ if (now - this.#lastCrashTold < WORKER_CRASH_TELL_EVERY_MS)
401
+ return;
402
+ this.#lastCrashTold = now;
403
+ const text = `The screening thread crashed and is restarting (${message}). Nothing unscreened was delivered, and ${waiting} message(s) are waiting for it.`;
404
+ for (const agent of this.#agents.values()) {
405
+ this.#store.addNotice(agent.signer.id, null, text);
406
+ this.#events.ring(agent.hex, { type: "notice", agent: agent.name });
407
+ }
408
+ }
409
+ // Sent when a run of verdicts settles, so a burst costs one signature, and it's retried by the next catch-up if it fails.
410
+ #ackSoon(agent, sessionHex) {
411
+ const key = agent.hex + sessionHex;
412
+ if (this.#ackTimers.has(key))
413
+ return;
414
+ this.#ackTimers.set(key, setTimeout(() => {
415
+ this.#ackTimers.delete(key);
416
+ const sessionId = parseHex(sessionHex, 16, "session id");
417
+ this.#background("screened ack", this.#lane(agent.hex, sessionHex, async () => {
418
+ const local = this.#store.session(agent.signer.id, sessionId);
419
+ if (local)
420
+ await this.#deliver(agent, local);
421
+ }));
422
+ }, SCREENED_ACK_DELAY_MS));
423
+ }
424
+ // The highest position with nothing unscreened at or before it.
425
+ #screenedThrough(agent, local) {
426
+ const first = this.#store.firstUnscreened(agent.signer.id, local.session_id);
427
+ return first === undefined ? local.verified_position : first - 1;
428
+ }
429
+ screeningFacts() {
430
+ const model = this.#screening.model;
431
+ const missing = model !== null && !model.running && this.#store.getConfig(CONFIG_MODEL_EVER_RAN) === "1";
432
+ return {
433
+ deterministic: { running: model !== null, rules: model ? "sanitizing, variants and patterns" : "starting" },
434
+ model: { ...(model ?? { state: "starting", running: false, backend: null, reason: null }), ...(missing ? { needs_installing: MODEL_MISSING } : {}) },
435
+ worker: { restarts: this.#screening.restarts, last_crash: this.#screening.lastCrash },
436
+ queue: this.#screening.pending(),
437
+ };
438
+ }
439
+ reloadScreener() {
440
+ this.#screening.reload();
441
+ return { reloaded: true };
442
+ }
443
+ // Which screeners really run on what this sender writes, right now.
444
+ #sessionScreening(agent, local) {
445
+ const rule = this.governance.screeningRule(agent.signer.id, toHex(local.counterparty_id));
446
+ const modelRunning = this.#screening.model?.running === true;
447
+ const screeners = rule.level === "off" ? [] : rule.level === "full" && modelRunning ? ["deterministic", "model"] : ["deterministic"];
448
+ const waiting = this.#screening.waiting(agent.hex, toHex(local.session_id));
449
+ return { level: rule.level, from: rule.from, screeners, ...(waiting ? { waiting_on: waiting } : {}) };
450
+ }
451
+ async #visitProof(agent, server) {
452
+ const identity = agent.signer.publicIdentity;
453
+ const clientNonce = new Uint8Array(randomBytes(32));
454
+ return {
455
+ identity: identityCodec.encode(identity),
456
+ clientNonce: toB64(clientNonce),
457
+ nameSignature: signatureCodec.encode(await agent.signer.sign("cello-visit", registerBytes({ serverId: server.id, identity }))),
458
+ signature: signatureCodec.encode(await agent.signer.sign("cello-agent-auth", agentAuthBytes({ serverId: server.id, agentId: agent.signer.id, serverNonce: server.nonce, clientNonce }))),
459
+ };
460
+ }
461
+ // ---- Servers other than this daemon's own ----
462
+ #pinKey(key, url) {
463
+ return url === this.#url ? key : `${key}:${url}`;
464
+ }
465
+ #urlOf(local) {
466
+ return local.server_url ?? this.#url;
467
+ }
468
+ #visitRoute(url) {
469
+ const existing = this.#visiting.get(url);
470
+ if (existing)
471
+ return existing;
472
+ const route = {
473
+ url,
474
+ home: false,
475
+ server: undefined,
476
+ wanted: new Set(),
477
+ online: new Set(),
478
+ visits: new Map(),
479
+ opening: 0,
480
+ longLink: this.#longLinkTo(url, () => route),
481
+ longServer: undefined,
482
+ longProved: new Set(),
483
+ link: new ServerLink(url, {
484
+ checkIdentity: (identity) => this.#checkServerIdentity(identity, url),
485
+ connected: async (server) => {
486
+ route.server = server;
487
+ this.#flushOutbox(route);
488
+ for (const hex of route.wanted)
489
+ this.#wantVisit(route, this.#requireAgent(hex));
490
+ },
491
+ disconnected: () => {
492
+ route.server = undefined;
493
+ route.online.clear();
494
+ },
495
+ push: (frame) => this.#onPush(frame, route),
496
+ }),
497
+ };
498
+ this.#visiting.set(url, route);
499
+ route.link.start();
500
+ route.longLink.start();
501
+ return route;
502
+ }
503
+ #routeFor(agent, local) {
504
+ if (!local.server_url)
505
+ return this.#home;
506
+ const route = this.#visitRoute(local.server_url);
507
+ this.#wantVisit(route, agent);
508
+ return route;
509
+ }
510
+ #wantVisit(route, agent) {
511
+ if (this.#stopAt(agent, route.url)?.status === "retired")
512
+ return;
513
+ route.wanted.add(agent.hex);
514
+ if (route.server && !route.online.has(agent.hex))
515
+ this.#background("visit", this.#visit(route, agent));
516
+ }
517
+ #visit(route, agent) {
518
+ const running = route.visits.get(agent.hex);
519
+ if (running)
520
+ return running;
521
+ const started = this.#visitOnce(route, agent).finally(() => route.visits.delete(agent.hex));
522
+ route.visits.set(agent.hex, started);
523
+ return started;
524
+ }
525
+ // Keys alone are enough: the other server needs no enrolment and doesn't ask anyone about this agent.
526
+ async #visitOnce(route, agent) {
527
+ const server = route.server;
528
+ while (server && route.server === server) {
529
+ try {
530
+ const answer = await route.link.call("visit", await this.#visitProof(agent, server));
531
+ route.online.add(agent.hex);
532
+ logEvent("agent.visiting", { agent: agent.hex, server: toHex(server.id) });
533
+ this.#noteStanding(agent, route, answer.standing);
534
+ await this.#catchUpAgent(agent, route);
535
+ return;
536
+ }
537
+ catch (err) {
538
+ if (err instanceof ServerRefused && err.code === "agent_retired") {
539
+ this.#noteStanding(agent, route, { status: "retired", reason: "none", record: null });
540
+ return;
541
+ }
542
+ // After an unclean drop, the server holds the old connection until its heartbeat ends it.
543
+ if (!(err instanceof ServerRefused) || err.code !== "agent_already_connected")
544
+ throw err;
545
+ await new Promise((resolve) => setTimeout(resolve, AUTH_RETRY_MS));
546
+ }
547
+ }
548
+ }
549
+ #isOnline(agent, route) {
550
+ return route.home ? agent.online : route.online.has(agent.hex);
551
+ }
552
+ #doneOpening(route) {
553
+ route.opening--;
554
+ this.#retireIdleVisits();
555
+ }
556
+ // The way to the server a new call goes to, ready to use, or a failure naming why not.
557
+ // The caller of this holds the route open, and lets go with #doneOpening.
558
+ async #reach(agent, url) {
559
+ const home = () => {
560
+ this.#home.opening++;
561
+ return this.#home;
562
+ };
563
+ if (!url || url === serverUrlFrom(this.#url))
564
+ return home();
565
+ const route = this.#visitRoute(url);
566
+ route.opening++;
567
+ route.wanted.add(agent.hex);
568
+ try {
569
+ const deadline = Date.now() + INITIATE_WAIT_MS;
570
+ while (!route.server && Date.now() < deadline)
571
+ await new Promise((resolve) => setTimeout(resolve, 100));
572
+ if (!route.server)
573
+ throw new LocalError("server_unreachable", `can't reach ${url}: ${route.link.problem ?? "it didn't answer"}`);
574
+ // This daemon's own server under another address. It's where these agents already live.
575
+ if (this.#store.getConfig(CONFIG_SERVER_IDENTITY) && equalBytes(route.server.id, this.#serverId())) {
576
+ route.wanted.delete(agent.hex);
577
+ this.#doneOpening(route);
578
+ return home();
579
+ }
580
+ let timer;
581
+ const late = new Promise((_, reject) => { timer = setTimeout(() => reject(new LocalError("server_unreachable", `${url} didn't take this agent's proof of identity in time`)), INITIATE_WAIT_MS); });
582
+ try {
583
+ await Promise.race([this.#call(() => this.#visit(route, agent)), late]);
584
+ }
585
+ finally {
586
+ clearTimeout(timer);
587
+ }
588
+ return route;
589
+ }
590
+ catch (err) {
591
+ this.#doneOpening(route);
592
+ throw err;
593
+ }
594
+ }
595
+ #visitFinished(agent, local) {
596
+ if (this.#stopAt(agent, this.#urlOf(local))?.status === "retired")
597
+ return true;
598
+ if (local.state === "offered")
599
+ return signedOffer.decode(JSON.parse(local.offer)).fields.expiresAt <= Date.now() && this.#store.pendingEntries(agent.signer.id, local.session_id).length === 0;
600
+ return local.state === "closed"
601
+ && this.#store.sealWants(agent.signer.id, local.session_id).length === 0
602
+ && this.#store.pendingEntries(agent.signer.id, local.session_id).length === 0
603
+ && local.delivered_through >= this.#latestFromPeer(agent, local);
604
+ }
605
+ // A visit is for its conversations, so the connection goes once they have nothing left to do. A later seal reopens it.
606
+ #retireIdleVisits() {
607
+ for (const route of this.#visiting.values()) {
608
+ if (route.opening > 0)
609
+ continue;
610
+ const busy = [...this.#agents.values()].some((agent) => this.#store.sessionsOf(agent.signer.id).some((local) => local.server_url === route.url && !this.#visitFinished(agent, local)));
611
+ if (busy || this.#store.outbox(route.url).length > 0)
612
+ continue;
613
+ route.link.stop();
614
+ route.longLink.stop();
615
+ this.#visiting.delete(route.url);
616
+ logEvent("server.visit_ended", { server: route.server ? toHex(route.server.id) : null });
617
+ }
618
+ }
619
+ #catchUpEverywhere(only) {
620
+ for (const agent of this.#agents.values()) {
621
+ if (only && agent !== only)
622
+ continue;
623
+ if (agent.online)
624
+ void this.#catchUpAgent(agent, this.#home);
625
+ for (const route of this.#visiting.values())
626
+ if (route.online.has(agent.hex))
627
+ void this.#catchUpAgent(agent, route);
628
+ }
629
+ }
630
+ #checkServerIdentity(identity, url) {
631
+ const encoded = JSON.stringify(identityCodec.encode(identity));
632
+ const pinned = this.#store.getConfig(this.#pinKey(CONFIG_SERVER_IDENTITY, url));
633
+ if (!pinned) {
634
+ this.#store.setConfig(this.#pinKey(CONFIG_SERVER_IDENTITY, url), encoded);
635
+ return null;
636
+ }
637
+ return pinned === encoded ? null : "this server's identity keys have changed since first contact, so its signatures can't be trusted";
638
+ }
639
+ #serverIdentity(url = this.#url) {
640
+ const pinned = this.#store.getConfig(this.#pinKey(CONFIG_SERVER_IDENTITY, url));
641
+ if (!pinned)
642
+ throw new LocalError("server_unreachable", "this daemon hasn't reached that server yet");
643
+ return identityCodec.decode(JSON.parse(pinned), "pinned server identity");
644
+ }
645
+ #serverId(url = this.#url) {
646
+ return identityId(this.#serverIdentity(url));
647
+ }
648
+ // Runs work for one session one at a time, so order on disk matches order of arrival.
649
+ #lane(agentHex, sessionHex, work) {
650
+ const key = agentHex + sessionHex;
651
+ const previous = this.#lanes.get(key) ?? Promise.resolve();
652
+ const run = previous.then(work, work);
653
+ this.#lanes.set(key, run.catch(() => undefined));
654
+ return run;
655
+ }
656
+ // Hands this agent's server the key callers seal signals to, until the server has it. Tried again from the timer if this fails.
657
+ async #publishKey(agent) {
658
+ if (this.#keyBusy.has(agent.hex))
659
+ return;
660
+ this.#keyBusy.add(agent.hex);
661
+ try {
662
+ const pending = await this.#keys.unpublished(agent);
663
+ if (!pending)
664
+ return;
665
+ await this.#call(() => this.#home.link.call("key.publish", { agent: toB64(agent.signer.id), key: pending.wire }));
666
+ this.#keys.markPublished(agent.signer.id, pending.revision);
667
+ logEvent("encryption_key.published", { agent: agent.hex, revision: pending.revision });
668
+ }
669
+ finally {
670
+ this.#keyBusy.delete(agent.hex);
671
+ }
672
+ }
673
+ #background(what, work) {
674
+ work.catch((err) => {
675
+ if (err instanceof ServerUnreachable) {
676
+ logEvent("server.unreachable_during", { what, message: err.message });
677
+ return;
678
+ }
679
+ logEvent("background.failed", { what, message: err instanceof Error ? err.message : String(err) });
680
+ });
681
+ }
682
+ async #bringOnline(agent, server) {
683
+ if (agent.awaitingSignal)
684
+ return;
685
+ try {
686
+ agent.problem = undefined;
687
+ if (!agent.registered)
688
+ await this.#register(agent);
689
+ while (this.#server === server) {
690
+ try {
691
+ const clientNonce = new Uint8Array(randomBytes(32));
692
+ const proof = agentAuthBytes({ serverId: server.id, agentId: agent.signer.id, serverNonce: server.nonce, clientNonce });
693
+ const signature = await agent.signer.sign("cello-agent-auth", proof);
694
+ const answer = await this.#link.call("auth", { agentId: toB64(agent.signer.id), clientNonce: toB64(clientNonce), signature: signatureCodec.encode(signature) });
695
+ agent.online = true;
696
+ logEvent("agent.online", { agent: agent.hex });
697
+ this.#noteStanding(agent, this.#home, answer.standing);
698
+ this.#flushOutbox(this.#home);
699
+ this.#background("encryption key", this.#publishKey(agent));
700
+ await this.#catchUpAgent(agent);
701
+ return;
702
+ }
703
+ catch (err) {
704
+ if (err instanceof ServerRefused && err.code === "agent_retired") {
705
+ this.#noteStanding(agent, this.#home, { status: "retired", reason: "none", record: null });
706
+ this.#flushOutbox(this.#home);
707
+ return;
708
+ }
709
+ // After an unclean drop, the server holds the old connection until its heartbeat ends it.
710
+ if (!(err instanceof ServerRefused) || err.code !== "agent_already_connected")
711
+ throw err;
712
+ await new Promise((resolve) => setTimeout(resolve, AUTH_RETRY_MS));
713
+ }
714
+ }
715
+ }
716
+ catch (err) {
717
+ agent.problem = err instanceof Error ? err.message : String(err);
718
+ logEvent("agent.bring_online_failed", { agent: agent.hex, message: agent.problem });
719
+ }
720
+ }
721
+ async #register(agent) {
722
+ const identity = agent.signer.publicIdentity;
723
+ const signature = await agent.signer.sign("cello-register", registerBytes({ serverId: this.#serverId(), identity }));
724
+ // The verified email a server asks for. A server that doesn't require one leaves it unread.
725
+ const email = this.wallet.emailFile(agent.hex);
726
+ await this.#link.call("register", { identity: identityCodec.encode(identity), signature: signatureCodec.encode(signature), ...(email ? { signal: toB64(email) } : {}) });
727
+ this.#store.markRegistered(agent.signer.id);
728
+ agent.registered = true;
729
+ logEvent("agent.registered", { agent: agent.hex });
730
+ }
731
+ async #catchUpAgent(agent, route = this.#home) {
732
+ try {
733
+ const stop = this.#stopAt(agent, route.url);
734
+ if (stop) {
735
+ // Stopped, it can't read or send, and the server won't list anything. What it may still do is finish a seal it asked for.
736
+ if (stop.status === "suspended") {
737
+ for (const local of this.#store.sessionsOf(agent.signer.id)) {
738
+ if (this.#urlOf(local) !== route.url || this.#store.sealWants(agent.signer.id, local.session_id).length === 0)
739
+ continue;
740
+ this.#background("seal while suspended", this.#lane(agent.hex, toHex(local.session_id), () => this.#retrySeals(agent, local.session_id)));
741
+ }
742
+ }
743
+ return;
744
+ }
745
+ const listedAt = Date.now();
746
+ const listed = await route.link.call("session.list", { agent: toB64(agent.signer.id) });
747
+ const seen = new Set();
748
+ for (const wire of listed.sessions) {
749
+ const sessionId = signedOffer.decode(wire.offer).fields.sessionId;
750
+ const sessionHex = toHex(sessionId);
751
+ seen.add(sessionHex);
752
+ this.#background("session update", this.#lane(agent.hex, sessionHex, async () => {
753
+ await this.#onSessionWire(agent, wire, route);
754
+ this.#tellLatePeer(agent, sessionId, listedAt, wire.tip);
755
+ }));
756
+ }
757
+ // An offer written to disk just before a crash may never have reached the server.
758
+ for (const row of this.#store.sessionsOf(agent.signer.id)) {
759
+ const sessionHex = toHex(row.session_id);
760
+ if (seen.has(sessionHex) || row.state !== "offered" || this.#urlOf(row) !== route.url)
761
+ continue;
762
+ this.#background("offer resend", route.link.call("session.offer", { agent: toB64(agent.signer.id), offer: JSON.parse(row.offer) }));
763
+ }
764
+ }
765
+ catch (err) {
766
+ logEvent("agent.catch_up_failed", { agent: agent.hex, message: err instanceof Error ? err.message : String(err) });
767
+ }
768
+ }
769
+ // Frames come from outside, and one bad frame mustn't take down every agent on this daemon.
770
+ #onPush(frame, route) {
771
+ try {
772
+ const agent = this.#agents.get(frame.agent);
773
+ if (!agent)
774
+ return;
775
+ if (frame.push === "status") {
776
+ this.#noteStanding(agent, route, frame.data);
777
+ return;
778
+ }
779
+ if (frame.push === "channel") {
780
+ this.#events.channelPush(frame);
781
+ return;
782
+ }
783
+ if (frame.push === "session") {
784
+ const wire = frame.data;
785
+ const sessionHex = toHex(signedOffer.decode(wire.offer).fields.sessionId);
786
+ this.#background("session push", this.#lane(agent.hex, sessionHex, () => this.#onSessionWire(agent, wire, route)));
787
+ return;
788
+ }
789
+ if (frame.push === "delivery") {
790
+ const { deliveryAck: wire, screeningEtaSeconds } = frame.data;
791
+ const sessionHex = toHex(signedDeliveryAck.decode(wire, "deliveryAck").fields.sessionId);
792
+ this.#background("delivery push", this.#lane(agent.hex, sessionHex, () => this.#onPeerDeliveryAck(agent, wire, screeningEtaSeconds)));
793
+ return;
794
+ }
795
+ const item = frame.data;
796
+ const sessionHex = toHex(signedEntry.decode(item.entry).fields.sessionId);
797
+ this.#background("entry push", this.#lane(agent.hex, sessionHex, () => this.#onEntryPush(agent, item, route)));
798
+ }
799
+ catch (err) {
800
+ logEvent("server.bad_push", { kind: frame.push, message: err instanceof Error ? err.message : String(err) });
801
+ }
802
+ }
803
+ // ---- Session setup ----
804
+ async #onSessionWire(agent, wire, route) {
805
+ const offer = signedOffer.decode(wire.offer, "offer");
806
+ const sessionId = offer.fields.sessionId;
807
+ let local = this.#store.session(agent.signer.id, sessionId);
808
+ if (!local) {
809
+ if (!equalBytes(offer.fields.calleeId, agent.signer.id)) {
810
+ logEvent("session.unknown_as_caller", { agent: agent.hex, session: toHex(sessionId) });
811
+ return;
812
+ }
813
+ // An agent is called only at its own server. Any other server claiming a call for it is making it up.
814
+ if (!route.home) {
815
+ logEvent("session.offer_from_wrong_server", { agent: agent.hex, session: toHex(sessionId) });
816
+ return;
817
+ }
818
+ await this.#acceptOffer(agent, wire);
819
+ return;
820
+ }
821
+ // One server can't speak for a conversation another one hosts.
822
+ if (this.#urlOf(local) !== route.url) {
823
+ logEvent("session.frame_from_wrong_server", { agent: agent.hex, session: toHex(sessionId) });
824
+ return;
825
+ }
826
+ const stopped = wire.stopped === true;
827
+ if (stopped !== this.#store.isStopped(agent.signer.id, sessionId)) {
828
+ this.#store.setStopped(agent.signer.id, sessionId, stopped);
829
+ this.#notify(agent, sessionId, stopped ? "This conversation has stopped. What you hold is safe, and you can still seal it." : "This conversation can carry on.");
830
+ }
831
+ if (local.role === "caller") {
832
+ if (local.state === "offered" && wire.refusal) {
833
+ await this.#onRefused(agent, local, wire.refusal);
834
+ return;
835
+ }
836
+ if (local.state === "offered" && wire.accept) {
837
+ await this.#answerAccept(agent, local, wire.accept);
838
+ local = this.#store.session(agent.signer.id, sessionId);
839
+ }
840
+ if (local.state === "accepted")
841
+ await this.#finishAsCaller(agent, local, wire.assignment);
842
+ }
843
+ else if (local.state === "accepted") {
844
+ if (!wire.accept) {
845
+ await this.#link.call("session.accept", { agent: toB64(agent.signer.id), sessionId: toB64(sessionId), accept: JSON.parse(local.accept) });
846
+ }
847
+ else if (wire.confirm && wire.assignment) {
848
+ await this.#finishAsCallee(agent, local, wire.confirm, wire.assignment);
849
+ }
850
+ }
851
+ local = this.#store.session(agent.signer.id, sessionId);
852
+ if (local.role === "caller" && wire.greeting && local.session_key)
853
+ await this.#onGreeting(agent, local, wire.greeting);
854
+ if (local.role === "callee" && local.state === "active")
855
+ await this.#greetIfDue(agent, local);
856
+ if (local.state === "active" || local.state === "closed") {
857
+ const hasWork = wire.tip > local.verified_position || this.#store.pendingEntries(agent.signer.id, sessionId).length > 0 || local.fault !== null || local.delivered_through < this.#latestFromPeer(agent, local) || (local.delivered_through > 0 && Math.min(this.#screenedThrough(agent, local), local.delivered_through) > local.acked_screened);
858
+ if (hasWork)
859
+ await this.#settle(agent, local);
860
+ if (this.#store.sealWants(agent.signer.id, sessionId).length > 0)
861
+ await this.#retrySeals(agent, sessionId);
862
+ }
863
+ }
864
+ // Tiers and policy aren't in this iteration, so a daemon takes every validly signed call.
865
+ // A definite no: the caller never waits out the offer. No session row is kept here, and the server takes it off this agent's
866
+ // list, so a restart doesn't count it twice. The reason goes to the caller's own key, so the server can't read it.
867
+ async #refuseOffer(agent, offer, refusal) {
868
+ const { fields } = offer;
869
+ const { ciphertext, sharedSecret } = await mlKemEncapsulate(fields.mlKemPublic);
870
+ const refuseFields = {
871
+ offerHash: structureHash(offer.bytes),
872
+ mlKemCiphertext: ciphertext,
873
+ sealedReason: sealSessionContent(refusalKey(sharedSecret), new TextEncoder().encode(JSON.stringify(refusal))),
874
+ };
875
+ sharedSecret.fill(0);
876
+ const signature = await agent.signer.sign("cello-session-refuse", refuseBytes(refuseFields));
877
+ await this.#link.call("session.refuse", { agent: toB64(agent.signer.id), sessionId: toB64(fields.sessionId), refusal: signedRefuse.encode({ fields: refuseFields, signature }) });
878
+ this.governance.noteRefusal(agent.signer.id, agent.hex, toHex(fields.callerId), refusal.code);
879
+ }
880
+ // What the caller's daemon says it heard. Only a callee's signature can make this happen, and only fixed sentences come out.
881
+ async #onRefused(agent, local, wire) {
882
+ const refusal = signedRefuse.decode(wire, "refusal");
883
+ if (!equalBytes(refusal.fields.offerHash, structureHash(signedOffer.decode(JSON.parse(local.offer)).bytes)))
884
+ throw new Error("this refusal answers a different offer");
885
+ if (!(await verifySignature(this.#counterpartyKeys(local), "cello-session-refuse", refusal.bytes, refusal.signature)))
886
+ throw new Error("this refusal isn't signed by the agent called");
887
+ const sharedSecret = await mlKemDecapsulate(local.mlkem_seed, refusal.fields.mlKemCiphertext);
888
+ const opened = openSessionContent(refusalKey(sharedSecret), refusal.fields.sealedReason);
889
+ sharedSecret.fill(0);
890
+ const sentence = refusalSentence(opened);
891
+ this.#store.updateSession(agent.signer.id, local.session_id, { state: "closed", fault: "refused", x25519_secret: null, mlkem_seed: null });
892
+ const sessionHex = toHex(local.session_id);
893
+ this.#refusals.set(agent.hex + sessionHex, sentence);
894
+ logEvent("session.was_refused", { agent: agent.hex, session: sessionHex });
895
+ this.#notify(agent, local.session_id, `${toHex(local.counterparty_id)} refused this call: ${sentence}`);
896
+ this.#activation.get(agent.hex + sessionHex)?.();
897
+ }
898
+ // One at a time per agent, so a burst of calls can't all pass the count before any of them is on disk.
899
+ async #acceptOffer(agent, wire) {
900
+ const offer = signedOffer.decode(wire.offer, "offer");
901
+ const fields = offer.fields;
902
+ const callerKeys = identityCodec.decode(wire.callerIdentity, "callerIdentity");
903
+ if (!equalBytes(identityId(callerKeys), fields.callerId))
904
+ throw new Error("the caller's keys don't match the caller's id");
905
+ if (!equalBytes(fields.serverId, this.#serverId()))
906
+ throw new Error("this offer names a different server");
907
+ if (!(await verifySignature(callerKeys, "cello-session-offer", offer.bytes, offer.signature)))
908
+ throw new Error("this offer isn't signed by its caller");
909
+ if (fields.expiresAt <= Date.now()) {
910
+ logEvent("session.offer_expired", { session: toHex(fields.sessionId) });
911
+ return;
912
+ }
913
+ // The caller's signals are opened before anything is decided, so a decision can look at them. A set that won't open is noted as that, not as none.
914
+ const theirs = await openFromKey(this.#keys.seeds(agent.signer.id), fields.signalsCiphertext, fields.sealedSignals);
915
+ const accept = await this.#lane(agent.hex, "gate", () => this.#admitOffer(agent, wire, offer, theirs));
916
+ if (!accept)
917
+ return;
918
+ await this.#link.call("session.accept", { agent: toB64(agent.signer.id), sessionId: toB64(fields.sessionId), accept });
919
+ logEvent("session.accepted", { agent: agent.hex, session: toHex(fields.sessionId) });
920
+ }
921
+ // Tier first, before any key material exists. The new session is on disk when this returns, so the next call counts it.
922
+ async #admitOffer(agent, wire, offer, theirs) {
923
+ const { fields } = offer;
924
+ // A stopped agent's tiers don't get a say, and a refused knock isn't counted against the caller.
925
+ this.#refuseIfStopped(agent, this.#url);
926
+ const refusal = this.governance.admit(agent.signer.id, fields.callerId);
927
+ if (refusal) {
928
+ await this.#refuseOffer(agent, offer, refusal);
929
+ return undefined;
930
+ }
931
+ // Then the signals they showed. The refusal is the same sentence whatever the rule, so it tells the caller nothing about the rule or its tier.
932
+ const judged = await this.#judge(agent, "inbound", fields.callerId, theirs);
933
+ if (!judged.pass) {
934
+ await this.#refuseOffer(agent, offer, { code: "signals_required" });
935
+ return undefined;
936
+ }
937
+ const own = await generateSessionEphemeral();
938
+ const { ciphertext, sharedSecret } = await mlKemEncapsulate(fields.mlKemPublic);
939
+ const { contentKey } = deriveSessionSecrets({
940
+ ownEphemeralSecret: own.secretKey,
941
+ peerEphemeralPublic: fields.x25519Public,
942
+ sessionId: fields.sessionId,
943
+ extraSharedSecret: sharedSecret,
944
+ pqTranscript: concat(ciphertext, fields.mlKemPublic),
945
+ });
946
+ const salt = generateSaltContribution();
947
+ const ours = this.#acceptSet(agent, contentKey);
948
+ const acceptFields = {
949
+ offerHash: structureHash(offer.bytes),
950
+ x25519Public: own.publicKey,
951
+ mlKemCiphertext: ciphertext,
952
+ sealedSalt: sealSessionContent(contentKey, salt),
953
+ sealedName: sealSessionContent(contentKey, new TextEncoder().encode(this.governance.offeredName(agent.signer.id, agent.name))),
954
+ sealedSignals: ours.sealed,
955
+ };
956
+ const signature = await agent.signer.sign("cello-session-accept", acceptBytes(acceptFields));
957
+ const accept = signedAccept.encode({ fields: acceptFields, signature });
958
+ this.#store.insertSession({
959
+ agent_id: agent.signer.id,
960
+ session_id: fields.sessionId,
961
+ role: "callee",
962
+ counterparty_id: fields.callerId,
963
+ counterparty_name: "",
964
+ counterparty_keys: JSON.stringify(wire.callerIdentity),
965
+ state: "accepted",
966
+ offer: JSON.stringify(wire.offer),
967
+ accept: JSON.stringify(accept),
968
+ session_key: contentKey,
969
+ own_salt: salt,
970
+ });
971
+ this.#presented.put(agent.signer.id, fields.sessionId, "caller", theirs);
972
+ this.#presented.put(agent.signer.id, fields.sessionId, "callee", ours.files);
973
+ destroySessionEphemeral(own);
974
+ sharedSecret.fill(0);
975
+ return accept;
976
+ }
977
+ // The agent called answered, and what it showed fell short of this agent's outbound rule. Nothing is confirmed, and the caller is told in its own words.
978
+ #declineAfterAccept(agent, local, evaluation) {
979
+ const sessionHex = toHex(local.session_id);
980
+ const lacking = [
981
+ evaluation.missing_types ? `types it didn't show: ${evaluation.missing_types.join(", ")}` : "",
982
+ evaluation.missing_issuer_kind ? "no signal from the kind of issuer required" : "",
983
+ evaluation.counted !== undefined && evaluation.missing_types === undefined && !evaluation.missing_issuer_kind ? `it showed ${evaluation.counted} that count` : "",
984
+ evaluation.not_counted_unrecognised ? `${evaluation.not_counted_unrecognised} from issuers this machine doesn't recognise didn't count` : "",
985
+ evaluation.not_counted_same_operator ? `${evaluation.not_counted_same_operator} from its own operator didn't count` : "",
986
+ ].filter(Boolean).join("; ");
987
+ const sentence = `${toHex(local.counterparty_id)} answered, but didn't show the signals your outbound rule asks for (${lacking}). The call was not confirmed. See the rule with: cello signal-rules`;
988
+ this.#store.updateSession(agent.signer.id, local.session_id, { state: "closed", fault: "signals_refused", x25519_secret: null, mlkem_seed: null });
989
+ this.#refusals.set(agent.hex + sessionHex, sentence);
990
+ logEvent("session.outbound_rule_declined", { agent: agent.hex, session: sessionHex });
991
+ this.#notify(agent, local.session_id, sentence);
992
+ this.#activation.get(agent.hex + sessionHex)?.();
993
+ }
994
+ // Judges a call by the signals the other side showed, against the rule that applies: this contact's, else its tier's, else the default. No rule passes.
995
+ // Only signals from an issuer that counts here are counted, so an issuer nobody recognises can't satisfy a rule. A set that wouldn't open counts as none.
996
+ async #judge(agent, direction, counterpartyId, shown) {
997
+ const tier = tierName(this.governance.contacts.tierOf(agent.signer.id, counterpartyId));
998
+ const { rule, level } = this.governance.rules.resolve(agent.signer.id, direction, tier, toHex(counterpartyId));
999
+ if (isNoRule(rule))
1000
+ return { pass: true };
1001
+ const evaluation = evaluate(rule, await this.wallet.standings(toHex(counterpartyId), shown === "unreadable" ? [] : shown));
1002
+ logEvent("signal.rule.judged", { agent: agent.hex, direction, level, pass: evaluation.pass, ...(shown === "unreadable" ? { unreadable: true } : {}) });
1003
+ return evaluation.pass ? { pass: true } : { pass: false, evaluation };
1004
+ }
1005
+ // The callee's own default set, sealed under the session key like its name. An accept can't be refused for a big set, so what doesn't fit is left off and the agent is told.
1006
+ #acceptSet(agent, sessionKey) {
1007
+ let { files } = this.wallet.presentable(agent.hex);
1008
+ if (files.length > MAX_PRESENTED_SIGNALS) {
1009
+ this.#notify(agent, null, `Your default set holds ${files.length} signals, and only ${MAX_PRESENTED_SIGNALS} can go with a call, so the newest ${MAX_PRESENTED_SIGNALS} were sent. Turn some off with: cello signals disable <hash>`);
1010
+ files = files.slice(0, MAX_PRESENTED_SIGNALS);
1011
+ }
1012
+ for (;;) {
1013
+ try {
1014
+ return { sealed: sealUnderSession(sessionKey, files), files };
1015
+ }
1016
+ catch (err) {
1017
+ if (!(err instanceof PresentedTooMany) || files.length === 0)
1018
+ throw err;
1019
+ this.#notify(agent, null, `Your default signals are too big to send together, so one was left off this call. Turn some off with: cello signals disable <hash>`);
1020
+ files = files.slice(0, -1);
1021
+ }
1022
+ }
1023
+ }
1024
+ // A name it gave itself, opened only by the party it's for. One that doesn't fit the rule is no name at all.
1025
+ #takeOfferedName(agent, local, key, sealed) {
1026
+ const opened = openSessionContent(key, sealed);
1027
+ const name = opened ? validateMoniker(new TextDecoder().decode(opened)) : null;
1028
+ if (!name)
1029
+ return;
1030
+ this.#store.updateSession(agent.signer.id, local.session_id, { counterparty_name: name });
1031
+ const renamed = this.governance.contacts.noteOfferedName(agent.signer.id, local.counterparty_id, name);
1032
+ if (renamed)
1033
+ this.#notify(agent, local.session_id, renamed);
1034
+ }
1035
+ async #answerAccept(agent, local, wireAccept) {
1036
+ const accept = signedAccept.decode(wireAccept, "accept");
1037
+ const keys = this.#counterpartyKeys(local);
1038
+ const offerFields = signedOffer.decode(JSON.parse(local.offer)).fields;
1039
+ if (!equalBytes(accept.fields.offerHash, structureHash(signedOffer.decode(JSON.parse(local.offer)).bytes)))
1040
+ throw new Error("this accept answers a different offer");
1041
+ if (!(await verifySignature(keys, "cello-session-accept", accept.bytes, accept.signature)))
1042
+ throw new Error("this accept isn't signed by the agent called");
1043
+ const seed = local.mlkem_seed;
1044
+ const secret = local.x25519_secret;
1045
+ if (!seed || !secret)
1046
+ throw new Error("this session's own key halves are missing");
1047
+ const sharedSecret = await mlKemDecapsulate(seed, accept.fields.mlKemCiphertext);
1048
+ const { contentKey } = deriveSessionSecrets({
1049
+ ownEphemeralSecret: secret,
1050
+ peerEphemeralPublic: accept.fields.x25519Public,
1051
+ sessionId: local.session_id,
1052
+ extraSharedSecret: sharedSecret,
1053
+ pqTranscript: concat(accept.fields.mlKemCiphertext, offerFields.mlKemPublic),
1054
+ });
1055
+ const peerSalt = openSessionContent(contentKey, accept.fields.sealedSalt);
1056
+ if (!peerSalt)
1057
+ throw new Error("the counterparty's salt didn't decrypt, so the two sides hold different keys");
1058
+ const ownSalt = generateSaltContribution();
1059
+ this.#takeOfferedName(agent, local, contentKey, accept.fields.sealedName);
1060
+ // What the callee showed, kept as the signed files it came as. A box that won't open is noted as that.
1061
+ const theirs = openUnderSession(contentKey, accept.fields.sealedSignals);
1062
+ this.#presented.put(agent.signer.id, local.session_id, "callee", theirs);
1063
+ // Who was called, judged by what came back. If it doesn't meet the rule, the call isn't confirmed: the other side's pending row expires, and no conversation starts.
1064
+ const judged = await this.#judge(agent, "outbound", local.counterparty_id, theirs);
1065
+ if (!judged.pass) {
1066
+ sharedSecret.fill(0);
1067
+ this.#declineAfterAccept(agent, local, judged.evaluation);
1068
+ return;
1069
+ }
1070
+ const confirmFields = { acceptHash: structureHash(accept.bytes), sealedSalt: sealSessionContent(contentKey, ownSalt), sealedName: sealSessionContent(contentKey, new TextEncoder().encode(this.governance.offeredName(agent.signer.id, agent.name))) };
1071
+ const signature = await agent.signer.sign("cello-session-confirm", confirmBytes(confirmFields));
1072
+ this.#store.updateSession(agent.signer.id, local.session_id, {
1073
+ state: "accepted",
1074
+ accept: JSON.stringify(wireAccept),
1075
+ confirm: JSON.stringify(signedConfirm.encode({ fields: confirmFields, signature })),
1076
+ session_key: contentKey,
1077
+ own_salt: ownSalt,
1078
+ salt: deriveSessionSalt(ownSalt, peerSalt),
1079
+ x25519_secret: null,
1080
+ mlkem_seed: null,
1081
+ });
1082
+ sharedSecret.fill(0);
1083
+ }
1084
+ async #finishAsCaller(agent, local, wireAssignment) {
1085
+ let assignment = wireAssignment;
1086
+ if (!assignment) {
1087
+ const result = await this.#routeFor(agent, local).link.call("session.confirm", { agent: toB64(agent.signer.id), sessionId: toB64(local.session_id), confirm: JSON.parse(local.confirm) });
1088
+ assignment = result.assignment;
1089
+ }
1090
+ await this.#activate(agent, local, JSON.parse(local.confirm), assignment, local.salt);
1091
+ }
1092
+ async #finishAsCallee(agent, local, wireConfirm, wireAssignment) {
1093
+ const confirm = signedConfirm.decode(wireConfirm, "confirm");
1094
+ const keys = this.#counterpartyKeys(local);
1095
+ if (!equalBytes(confirm.fields.acceptHash, structureHash(signedAccept.decode(JSON.parse(local.accept)).bytes)))
1096
+ throw new Error("this confirm answers a different accept");
1097
+ if (!(await verifySignature(keys, "cello-session-confirm", confirm.bytes, confirm.signature)))
1098
+ throw new Error("this confirm isn't signed by the caller");
1099
+ const peerSalt = openSessionContent(local.session_key, confirm.fields.sealedSalt);
1100
+ if (!peerSalt)
1101
+ throw new Error("the counterparty's salt didn't decrypt, so the two sides hold different keys");
1102
+ this.#takeOfferedName(agent, local, local.session_key, confirm.fields.sealedName);
1103
+ await this.#activate(agent, local, wireConfirm, wireAssignment, deriveSessionSalt(local.own_salt, peerSalt));
1104
+ if (!this.#events.reachable(agent.hex) && this.governance.reach.setting(agent.signer.id, "away.answering") === "true")
1105
+ this.#away.startVisit(agent.signer.id, local.session_id);
1106
+ }
1107
+ // ---- Away. A greeting goes beside the chain, signed by its sender and sealed to the caller, and the caller screens it like any text. ----
1108
+ async #greetIfDue(agent, local) {
1109
+ const visit = this.#away.visit(agent.signer.id, local.session_id);
1110
+ if (visit?.state !== "due")
1111
+ return;
1112
+ // Someone came back while this waited to go, or the agent has been stopped: either way it no longer speaks for anyone.
1113
+ if (this.#events.reachable(agent.hex) || this.#stopAt(agent, this.#urlOf(local))) {
1114
+ this.#away.setVisit(agent.signer.id, local.session_id, "not_sent");
1115
+ return;
1116
+ }
1117
+ let wire = visit.greeting;
1118
+ if (!wire) {
1119
+ const text = this.governance.awayText(agent.signer.id, local.counterparty_id, agent.name);
1120
+ if (!text) {
1121
+ this.#away.setVisit(agent.signer.id, local.session_id, "not_sent");
1122
+ return;
1123
+ }
1124
+ let screened;
1125
+ try {
1126
+ screened = (await this.#screenOutbound(agent, text, {}, `cello settings --agent ${agent.hex}`)).text;
1127
+ }
1128
+ catch (err) {
1129
+ // A worker that's restarting says nothing about the text, so that one tries again at the next catch-up.
1130
+ if (err instanceof LocalError && err.code === "screener_unavailable")
1131
+ return;
1132
+ if (!(err instanceof LocalError))
1133
+ throw err;
1134
+ this.#away.setVisit(agent.signer.id, local.session_id, "not_sent");
1135
+ logEvent("away.greeting_screened_out", { agent: agent.hex, session: toHex(local.session_id), code: err.code });
1136
+ this.#notify(agent, local.session_id, `Your away text wasn't sent to ${this.#who(agent, local)}, because your own outbound screen stopped it: ${err.message}`);
1137
+ return;
1138
+ }
1139
+ const fields = {
1140
+ offerHash: structureHash(signedOffer.decode(JSON.parse(local.offer)).bytes),
1141
+ sealedText: sealSessionContent(greetingKey(local.session_key), new TextEncoder().encode(screened)),
1142
+ };
1143
+ const signature = await agent.signer.sign("cello-session-greeting", greetingBytes(fields));
1144
+ wire = JSON.stringify(signedGreeting.encode({ fields, signature }));
1145
+ this.#away.setVisit(agent.signer.id, local.session_id, "due", wire);
1146
+ }
1147
+ try {
1148
+ await this.#link.call("session.greet", { agent: toB64(agent.signer.id), sessionId: toB64(local.session_id), greeting: JSON.parse(wire) });
1149
+ }
1150
+ catch (err) {
1151
+ if (err instanceof ServerUnreachable)
1152
+ return;
1153
+ throw err;
1154
+ }
1155
+ this.#away.setVisit(agent.signer.id, local.session_id, "sent");
1156
+ logEvent("away.greeted", { agent: agent.hex, session: toHex(local.session_id) });
1157
+ }
1158
+ // The server carries this frame and can't be trusted about it, so nothing is kept unless the agent called signed it for this very call.
1159
+ async #onGreeting(agent, local, wire) {
1160
+ if (this.#away.greeting(agent.signer.id, local.session_id))
1161
+ return;
1162
+ const reject = (why) => {
1163
+ this.#away.rejectGreeting(agent.signer.id, local.session_id, local.counterparty_id, why);
1164
+ logEvent("away.greeting_rejected", { agent: agent.hex, session: toHex(local.session_id), why });
1165
+ };
1166
+ let greeting;
1167
+ try {
1168
+ greeting = signedGreeting.decode(wire, "greeting");
1169
+ }
1170
+ catch {
1171
+ reject("malformed");
1172
+ return;
1173
+ }
1174
+ if (greeting.fields.sealedText.length > MAX_GREETING_BYTES) {
1175
+ reject("too_large");
1176
+ return;
1177
+ }
1178
+ const offerHash = structureHash(signedOffer.decode(JSON.parse(local.offer)).bytes);
1179
+ if (!equalBytes(greeting.fields.offerHash, offerHash)) {
1180
+ reject("answers_a_different_offer");
1181
+ return;
1182
+ }
1183
+ if (!(await verifySignature(this.#counterpartyKeys(local), "cello-session-greeting", greeting.bytes, greeting.signature))) {
1184
+ reject("bad_signature");
1185
+ return;
1186
+ }
1187
+ const opened = openSessionContent(greetingKey(local.session_key), greeting.fields.sealedText);
1188
+ if (!opened) {
1189
+ reject("does_not_decrypt");
1190
+ return;
1191
+ }
1192
+ this.#away.addGreeting(agent.signer.id, local.session_id, local.counterparty_id, opened);
1193
+ this.#screenGreeting(this.#away.greeting(agent.signer.id, local.session_id));
1194
+ }
1195
+ // The same queue, screeners and rules as a message from this sender. What it holds is durable, so a restart screens it again.
1196
+ #screenGreeting(row) {
1197
+ const agentHex = toHex(row.agent_id);
1198
+ const agent = this.#agents.get(agentHex);
1199
+ if (!agent)
1200
+ return;
1201
+ this.#nextChannelJob -= 1;
1202
+ const bytes = bodyBytes({ n: new Uint8Array(0), text: new TextDecoder().decode(row.body), signal: null, est_minutes: null });
1203
+ const sessionHex = toHex(row.session_id);
1204
+ this.#screening.add({
1205
+ entryId: this.#nextChannelJob, agentHex, sessionHex: `greeting:${sessionHex}`, position: 0, senderHex: toHex(row.sender_id), bytes: bytes.length, arrived: Date.now(),
1206
+ channelText: {
1207
+ bytes,
1208
+ done: (verdict) => {
1209
+ const detail = { delivered: verdict.delivered, findings: verdict.findings, reason: verdict.reason, score: verdict.score, ran: verdict.ran };
1210
+ this.#away.setVerdict(row.agent_id, row.session_id, verdict.verdict, JSON.stringify(detail));
1211
+ logEvent("screening.greeting_verdict", { agent: agentHex, session: sessionHex, verdict: verdict.verdict, findings: verdict.findings.map((f) => f.what) });
1212
+ this.#events.ring(agentHex, { type: "away_greeting", agent: agent.name, session_id: sessionHex, from_id: toHex(row.sender_id) });
1213
+ },
1214
+ },
1215
+ });
1216
+ }
1217
+ #shownGreeting(agent, row) {
1218
+ const detail = JSON.parse(row.verdict_detail);
1219
+ const screening = { verdict: row.verdict, findings: detail.findings, ...(detail.score === null ? {} : { score: detail.score }), ...(detail.reason ? { reason: detail.reason } : {}), ran: detail.ran };
1220
+ const local = this.#store.session(agent.signer.id, row.session_id);
1221
+ const about = { session_id: toHex(row.session_id), from: this.#who(agent, local), from_id: toHex(row.sender_id), automatic: true, in_the_record: false };
1222
+ if (row.verdict === "blocked")
1223
+ return { ...about, blocked: true, screening };
1224
+ return { ...about, text: detail.delivered ?? new TextDecoder().decode(row.body), screening };
1225
+ }
1226
+ greetings(agentHex) {
1227
+ const agent = this.#requireAgent(agentHex);
1228
+ return { greetings: this.#away.all(agent.signer.id).map((row) => this.#shownGreeting(agent, row)) };
1229
+ }
1230
+ // Their one message has landed, nobody here has said a word, and nobody has come back. Runs in the session's lane.
1231
+ async #closeVisit(agent, sessionId) {
1232
+ const local = this.#store.session(agent.signer.id, sessionId);
1233
+ if (this.#away.visit(agent.signer.id, sessionId)?.state !== "sent")
1234
+ return;
1235
+ if (this.#store.lastOwnEntry(agent.signer.id, sessionId)) {
1236
+ this.#away.setVisit(agent.signer.id, sessionId, "answered");
1237
+ return;
1238
+ }
1239
+ if (this.#events.reachable(agent.hex) || local.state !== "active")
1240
+ return;
1241
+ this.#away.setVisit(agent.signer.id, sessionId, "closed");
1242
+ logEvent("away.visit_closed", { agent: agent.hex, session: toHex(sessionId) });
1243
+ await this.#closeInLane(agent, toHex(sessionId), true);
1244
+ this.#notify(agent, sessionId, `${this.#who(agent, local)} left one message while nobody was reachable as this agent, and the visit was closed and sealed. Call receive to read it.`);
1245
+ }
1246
+ async #activate(agent, local, wireConfirm, wireAssignment, salt) {
1247
+ const assignment = signedAssignment.decode(wireAssignment, "assignment");
1248
+ const expected = {
1249
+ serverId: this.#serverId(this.#urlOf(local)),
1250
+ sessionId: local.session_id,
1251
+ callerId: local.role === "caller" ? agent.signer.id : local.counterparty_id,
1252
+ calleeId: local.role === "caller" ? local.counterparty_id : agent.signer.id,
1253
+ confirmHash: structureHash(signedConfirm.decode(wireConfirm).bytes),
1254
+ };
1255
+ const matches = Object.keys(expected).every((key) => equalBytes(assignment.fields[key], expected[key]));
1256
+ if (!matches || !(await verifySignature(this.#serverIdentity(this.#urlOf(local)), "cello-session-assignment", assignment.bytes, assignment.signature))) {
1257
+ throw new Error("the server's assignment doesn't match this session's setup");
1258
+ }
1259
+ this.#store.updateSession(agent.signer.id, local.session_id, {
1260
+ state: "active",
1261
+ confirm: JSON.stringify(wireConfirm),
1262
+ assignment: JSON.stringify(wireAssignment),
1263
+ salt,
1264
+ last_activity_at: assignment.fields.time,
1265
+ });
1266
+ const sessionHex = toHex(local.session_id);
1267
+ const peerHex = toHex(local.counterparty_id);
1268
+ logEvent("session.active", { agent: agent.hex, session: sessionHex });
1269
+ const admission = local.role === "callee" ? this.governance.admissionFor(agent.signer.id, peerHex, this.governance.contacts.tierOf(agent.signer.id, local.counterparty_id)) : {};
1270
+ this.#events.ring(agent.hex, { type: "session_started", agent: agent.name, session_id: sessionHex, from_id: peerHex, ...admission });
1271
+ this.#activation.get(agent.hex + sessionHex)?.();
1272
+ }
1273
+ #counterpartyKeys(local) {
1274
+ const keys = identityCodec.decode(JSON.parse(local.counterparty_keys), "counterparty keys");
1275
+ if (!equalBytes(identityId(keys), local.counterparty_id))
1276
+ throw new Error("the stored counterparty keys don't match its id");
1277
+ return keys;
1278
+ }
1279
+ // ---- Reading from position ----
1280
+ #verifier(agent, local) {
1281
+ const key = agent.hex + toHex(local.session_id);
1282
+ const cached = this.#verifiers.get(key);
1283
+ if (cached)
1284
+ return cached;
1285
+ const verifier = new ChainVerifier({
1286
+ sessionId: local.session_id,
1287
+ server: this.#serverIdentity(this.#urlOf(local)),
1288
+ participants: [agent.signer.publicIdentity, this.#counterpartyKeys(local)],
1289
+ });
1290
+ for (const row of this.#store.signedRecord(agent.signer.id, local.session_id, local.verified_position)) {
1291
+ const entry = signedEntry.decode(JSON.parse(row.entry));
1292
+ verifier.adopt(entry.fields, structureHash(entry.bytes), signedAck.decode(JSON.parse(row.ack)).fields.time);
1293
+ }
1294
+ this.#verifiers.set(key, verifier);
1295
+ return verifier;
1296
+ }
1297
+ async #onEntryPush(agent, item, route) {
1298
+ const sessionId = signedEntry.decode(item.entry).fields.sessionId;
1299
+ const local = this.#store.session(agent.signer.id, sessionId);
1300
+ if (!local || (local.state !== "active" && local.state !== "closed") || this.#urlOf(local) !== route.url)
1301
+ return;
1302
+ const position = signedAck.decode(item.ack).fields.position;
1303
+ const verifier = this.#verifier(agent, local);
1304
+ if (position <= verifier.position) {
1305
+ await this.#checkRepeat(agent, local, item);
1306
+ return;
1307
+ }
1308
+ // A long message's push carries no text, so #settle fetches it.
1309
+ if (item.ciphertext !== null && position === verifier.position + 1 && (await this.#ingest(agent, local, item))) {
1310
+ await this.#deliver(agent, this.#store.session(agent.signer.id, sessionId));
1311
+ return;
1312
+ }
1313
+ if (position > verifier.position)
1314
+ await this.#settle(agent, local);
1315
+ }
1316
+ // Resend what's pending, read everything new in order, then confirm what's stored.
1317
+ async #settle(agent, start) {
1318
+ const sessionId = start.session_id;
1319
+ await this.#resendPending(agent, start);
1320
+ let local = this.#store.session(agent.signer.id, sessionId);
1321
+ let long = false;
1322
+ for (;;) {
1323
+ const before = this.#verifier(agent, local).position;
1324
+ const params = { agent: toB64(agent.signer.id), sessionId: toB64(sessionId), after: before };
1325
+ const route = this.#routeFor(agent, local);
1326
+ const result = await (long ? this.#longCall(agent, route, "entry.fetch", { ...params, long }) : route.link.call("entry.fetch", params));
1327
+ long = result.longNext;
1328
+ for (const item of result.items) {
1329
+ local = this.#store.session(agent.signer.id, sessionId);
1330
+ if (!(await this.#ingest(agent, local, item)))
1331
+ return;
1332
+ }
1333
+ local = this.#store.session(agent.signer.id, sessionId);
1334
+ const after = this.#verifier(agent, local).position;
1335
+ if (after >= result.tip)
1336
+ break;
1337
+ if (long)
1338
+ continue;
1339
+ // A server that claims more but gives nothing new would otherwise keep this lane fetching forever.
1340
+ if (after === before) {
1341
+ this.#hold(agent, local, "server_sent_nothing_new", before + 1);
1342
+ return;
1343
+ }
1344
+ }
1345
+ local = this.#store.session(agent.signer.id, sessionId);
1346
+ if (local.fault) {
1347
+ this.#store.updateSession(agent.signer.id, sessionId, { fault: null });
1348
+ logEvent("session.fault_cleared", { session: toHex(sessionId) });
1349
+ }
1350
+ await this.#deliver(agent, this.#store.session(agent.signer.id, sessionId));
1351
+ }
1352
+ async #resendPending(agent, local) {
1353
+ for (const row of this.#store.pendingEntries(agent.signer.id, local.session_id)) {
1354
+ const outcome = await this.#attempt(agent, local, row);
1355
+ const preview = parseBody(row.body)?.text.slice(0, 120) ?? "";
1356
+ if (outcome.status === "landed") {
1357
+ this.#notify(agent, local.session_id, `Your message "${preview}" has now landed at position ${outcome.position}.`);
1358
+ }
1359
+ else if (outcome.status === "refused") {
1360
+ this.#notify(agent, local.session_id, `Your message "${preview}" was not sent: ${outcome.code}, ${outcome.message}. ${LOST_MESSAGE_GUIDANCE}`);
1361
+ }
1362
+ else {
1363
+ return;
1364
+ }
1365
+ }
1366
+ }
1367
+ #notify(agent, sessionId, text) {
1368
+ this.#store.addNotice(agent.signer.id, sessionId, text);
1369
+ this.#events.ring(agent.hex, { type: "notice", agent: agent.name, ...(sessionId ? { session_id: toHex(sessionId) } : {}) });
1370
+ }
1371
+ // Doesn't stop the conversation for good: it's rechecked at every catch-up, so a bad deploy thaws by itself.
1372
+ #hold(agent, local, reason, position) {
1373
+ this.#verifiers.delete(agent.hex + toHex(local.session_id));
1374
+ if (local.fault === reason)
1375
+ return;
1376
+ this.#store.updateSession(agent.signer.id, local.session_id, { fault: reason });
1377
+ logEvent("session.holding", { agent: agent.hex, session: toHex(local.session_id), reason, position });
1378
+ this.#notify(agent, local.session_id, `This session is holding at position ${position}, because something from the server didn't check out (${reason}). Nothing is lost, and it rechecks by itself.`);
1379
+ }
1380
+ // The running total for one conversation, read against whatever tier the sender is at now, so blocking stops it at once.
1381
+ // Known and above start again after a quiet spell, so a long conversation doesn't simply stop. A stranger's never does.
1382
+ #countBytes(agent, local, size, at) {
1383
+ const limits = this.governance.reach.limitsFor(agent.signer.id, this.governance.contacts.tierOf(agent.signer.id, local.counterparty_id));
1384
+ const resets = limits.bytes_reset_minutes > 0;
1385
+ const restart = resets && local.last_activity_at > 0 && at - local.last_activity_at >= limits.bytes_reset_minutes * 60_000;
1386
+ const total = (restart ? 0 : local.bytes_received) + size;
1387
+ const withheld = total > limits.max_bytes;
1388
+ const alreadyTold = !restart && local.bytes_told === 1;
1389
+ return { total, told: alreadyTold || withheld ? 1 : 0, withheld, tellNow: withheld && !alreadyTold, limit: limits.max_bytes, resets };
1390
+ }
1391
+ // Your own name for it wins, and a name it gave itself says so.
1392
+ #who(agent, local) {
1393
+ return this.governance.contacts.who(agent.signer.id, local.counterparty_id, toHex(local.counterparty_id), local.counterparty_name || null).who;
1394
+ }
1395
+ async #ingest(agent, local, item) {
1396
+ let landing;
1397
+ let entry;
1398
+ try {
1399
+ entry = signedEntry.decode(item.entry, "entry");
1400
+ const ack = signedAck.decode(item.ack, "ack");
1401
+ landing = witnessed(entry, ack);
1402
+ }
1403
+ catch (err) {
1404
+ this.#hold(agent, local, `malformed_frame: ${err instanceof Error ? err.message : String(err)}`, local.verified_position + 1);
1405
+ return false;
1406
+ }
1407
+ const verifier = this.#verifier(agent, local);
1408
+ const position = landing.ack.position;
1409
+ if (position <= verifier.position) {
1410
+ await this.#checkRepeat(agent, local, item);
1411
+ return true;
1412
+ }
1413
+ const fault = await verifier.check(landing);
1414
+ if (fault) {
1415
+ this.#hold(agent, local, fault, position);
1416
+ return false;
1417
+ }
1418
+ const closing = entry.fields.kind === EntryKind.close;
1419
+ const fromMe = equalBytes(entry.fields.authorId, agent.signer.id);
1420
+ const hash = structureHash(entry.bytes);
1421
+ let body;
1422
+ let unverifiable;
1423
+ if (fromMe) {
1424
+ const own = this.#store.ownEntryByHash(agent.signer.id, local.session_id, hash);
1425
+ if (!own) {
1426
+ this.#hold(agent, local, "own_entry_unknown", position);
1427
+ return false;
1428
+ }
1429
+ // Your daemon told you this was refused, and the server landed it anyway. It stays out of your record, and you're told.
1430
+ if (own.state === "not_sent") {
1431
+ this.#store.addEvidence({ agent_id: agent.signer.id, session_id: local.session_id, kind: "refused_entry_landed", position, entry: JSON.stringify(item.entry), ack: JSON.stringify(item.ack), other_ack: null, ciphertext: null });
1432
+ logEvent("session.refused_entry_landed", { agent: agent.hex, session: toHex(local.session_id), position });
1433
+ this.#notify(agent, local.session_id, `The server is claiming position ${position} for a message you were told was refused: "${parseBody(own.body)?.text.slice(0, 120) ?? ""}". This agent doesn't accept that, the proof is kept (see evidence), and the session stops here. Don't rely on this server for this conversation.`);
1434
+ this.#hold(agent, local, "refused_entry_landed", position);
1435
+ return false;
1436
+ }
1437
+ body = own.body;
1438
+ }
1439
+ else {
1440
+ if (!item.ciphertext) {
1441
+ this.#hold(agent, local, "encrypted_text_missing", position);
1442
+ return false;
1443
+ }
1444
+ const ciphertext = fromB64(item.ciphertext, "ciphertext");
1445
+ // Text that isn't what the author signed a hash of came from the server, which can send the right text next time.
1446
+ if (!equalBytes(ciphertextHash(ciphertext), entry.fields.ciphertextHash)) {
1447
+ this.#hold(agent, local, "text_does_not_match_signature", position);
1448
+ return false;
1449
+ }
1450
+ const opened = openSessionContent(local.session_key, ciphertext);
1451
+ if (opened && equalBytes(saltedContentHash(local.salt, opened), entry.fields.contentHash))
1452
+ body = opened;
1453
+ else {
1454
+ // The author signed text that can't be what it says, and those same bytes fail every time. Holding here would let one bad
1455
+ // message stop the reader for good, so the bytes are kept as evidence, the words aren't shown, and reading carries on.
1456
+ unverifiable = ciphertext;
1457
+ body = new Uint8Array(0);
1458
+ }
1459
+ }
1460
+ const ownClosed = local.own_closed === 1 || (closing && fromMe);
1461
+ const peerClosed = local.peer_closed === 1 || (closing && !fromMe);
1462
+ const nowClosed = ownClosed && peerClosed;
1463
+ // The words are this daemon's, not the other side's. A close by hand doesn't carry the mark, so it doesn't get them.
1464
+ const closedOnGreeting = closing && !fromMe && local.role === "caller" && parseBody(body)?.one_message === true && !this.#store.lastPeerEntry(agent.signer.id, local.session_id) && (this.#away.greeting(agent.signer.id, local.session_id)?.verdict ?? "rejected") !== "rejected";
1465
+ const counted = !fromMe && !closing && !unverifiable ? this.#countBytes(agent, local, body.length, landing.ack.time) : undefined;
1466
+ try {
1467
+ this.#store.transaction(() => {
1468
+ if (fromMe) {
1469
+ const own = this.#store.ownEntryByHash(agent.signer.id, local.session_id, hash);
1470
+ this.#store.markLanded(own.id, position, JSON.stringify(item.ack));
1471
+ }
1472
+ else {
1473
+ this.#store.insertEntry({
1474
+ agent_id: agent.signer.id,
1475
+ session_id: local.session_id,
1476
+ entry_hash: hash,
1477
+ position,
1478
+ state: "received",
1479
+ own: 0,
1480
+ entry: JSON.stringify(item.entry),
1481
+ ack: JSON.stringify(item.ack),
1482
+ // Nobody will read it, and the signed hashes are what the chain and a seal rest on, so past the limit a flood costs no disk for its words.
1483
+ body: counted?.withheld ? new Uint8Array(0) : body,
1484
+ });
1485
+ if (unverifiable) {
1486
+ this.#store.markWithheld(this.#store.entryIdAt(agent.signer.id, local.session_id, position), JSON.stringify({ delivered: null, findings: [], reason: UNVERIFIABLE_REASON, score: null, ran: { deterministic: false, model: false } }));
1487
+ this.#store.addEvidence({ agent_id: agent.signer.id, session_id: local.session_id, kind: "unverifiable_text", position, entry: JSON.stringify(item.entry), ack: JSON.stringify(item.ack), other_ack: null, ciphertext: unverifiable });
1488
+ }
1489
+ if (counted?.withheld)
1490
+ this.#store.markWithheld(this.#store.entryIdAt(agent.signer.id, local.session_id, position), JSON.stringify({ delivered: null, findings: [], reason: BYTE_LIMIT_REASON, score: null, ran: { deterministic: false, model: false, model_failed_copies: 0 } }));
1491
+ }
1492
+ this.#store.updateSession(agent.signer.id, local.session_id, {
1493
+ ...(counted ? { bytes_received: counted.total, bytes_told: counted.told } : {}),
1494
+ last_activity_at: landing.ack.time,
1495
+ verified_position: position,
1496
+ own_closed: ownClosed ? 1 : 0,
1497
+ peer_closed: peerClosed ? 1 : 0,
1498
+ ...(nowClosed ? { state: "closed", session_key: null } : {}),
1499
+ });
1500
+ });
1501
+ }
1502
+ catch (err) {
1503
+ // The check above already advanced the cached chain, so rebuild it from what's on disk.
1504
+ this.#verifiers.delete(agent.hex + toHex(local.session_id));
1505
+ throw err;
1506
+ }
1507
+ const sessionHex = toHex(local.session_id);
1508
+ const bell = { agent: agent.name, session_id: sessionHex, from_id: toHex(local.counterparty_id) };
1509
+ // Told once, and it rings no doorbell per message, so a flood past the limit can't keep waking anyone or cost a screen.
1510
+ if (counted?.tellNow)
1511
+ this.#notify(agent, local.session_id, `This conversation has passed its limit of ${counted.limit} bytes, so what it sends from now on isn't delivered. ${counted.resets ? "The count starts again after a quiet spell." : "The count doesn't reset at this tier."} The other side isn't told. Either side can start a new conversation.`);
1512
+ // Stored, but not deliverable until it has a verdict. Its doorbell rings then, from #onVerdict.
1513
+ if (unverifiable) {
1514
+ logEvent("session.unverifiable_text", { agent: agent.hex, session: sessionHex, position });
1515
+ this.#notify(agent, local.session_id, `The message at position ${position} from ${this.#who(agent, local)} isn't what its author signed, so it wasn't delivered. The bytes are kept (see evidence), and this agent's signed delivery ack lists it as refused. Later messages can still be read.`);
1516
+ }
1517
+ if (!fromMe && !counted?.withheld && !unverifiable) {
1518
+ const entryId = this.#store.entryIdAt(agent.signer.id, local.session_id, position);
1519
+ this.#screening.add({ entryId, agentHex: agent.hex, sessionHex, position, senderHex: toHex(local.counterparty_id), bytes: body.length, arrived: Date.now() });
1520
+ }
1521
+ if (closedOnGreeting)
1522
+ this.#notify(agent, local.session_id, ONE_MESSAGE_LINE);
1523
+ // Queued, not awaited: this lane is the one running now.
1524
+ if (!fromMe && !closing && local.role === "callee" && this.#away.visit(agent.signer.id, local.session_id)?.state === "sent") {
1525
+ this.#background("one-message close", this.#lane(agent.hex, sessionHex, () => this.#closeVisit(agent, local.session_id)));
1526
+ }
1527
+ if (nowClosed && local.state !== "closed") {
1528
+ logEvent("session.closed", { agent: agent.hex, session: sessionHex });
1529
+ this.#events.ring(agent.hex, { ...bell, type: "session_closed" });
1530
+ }
1531
+ const written = counted?.withheld || unverifiable ? null : parseBody(body);
1532
+ const due = !closing && written?.signal === "standby" ? standbyDue(written.est_minutes, landing.ack.time) : undefined;
1533
+ if (due !== undefined)
1534
+ this.#armStandbyCheck(due);
1535
+ return true;
1536
+ }
1537
+ // A different signed ack at a position already held. An ack the server didn't sign is dropped, because anyone can send junk.
1538
+ // Two it did sign is proof of misbehaviour: it's kept, the operator is told, and the session takes no more messages from this side.
1539
+ async #checkRepeat(agent, local, item) {
1540
+ const position = signedAck.decode(item.ack, "ack").fields.position;
1541
+ const held = this.#store.ackAt(agent.signer.id, local.session_id, position);
1542
+ if (!held)
1543
+ return;
1544
+ const proved = await provesTwoAcks(this.#serverIdentity(this.#urlOf(local)), signedAck.decode(JSON.parse(held)), signedAck.decode(item.ack, "ack"));
1545
+ if (!proved)
1546
+ return;
1547
+ this.#store.addEvidence({ agent_id: agent.signer.id, session_id: local.session_id, kind: "two_acks", position, entry: JSON.stringify(item.entry), ack: held, other_ack: JSON.stringify(item.ack), ciphertext: null });
1548
+ if (local.frozen === 1)
1549
+ return;
1550
+ this.#store.updateSession(agent.signer.id, local.session_id, { frozen: 1 });
1551
+ logEvent("session.frozen", { agent: agent.hex, session: toHex(local.session_id), position });
1552
+ this.#notify(agent, local.session_id, `The server signed two different things at position ${position}, which it must never do. This session is frozen: you can still read and seal, and you can't send. The proof is kept (see evidence). Tell whoever runs this server.`);
1553
+ }
1554
+ evidence(agentHex, sessionHex) {
1555
+ const agent = this.#requireAgent(agentHex);
1556
+ const local = this.#requireSession(agent, sessionHex);
1557
+ return {
1558
+ frozen: local.frozen === 1,
1559
+ evidence: this.#store.evidence(agent.signer.id, local.session_id).map((row) => ({
1560
+ kind: row.kind,
1561
+ position: row.position,
1562
+ entry: row.entry === null ? null : JSON.parse(row.entry),
1563
+ ack: JSON.parse(row.ack),
1564
+ other_ack: row.other_ack === null ? null : JSON.parse(row.other_ack),
1565
+ ciphertext: row.ciphertext === null ? null : toB64(row.ciphertext),
1566
+ })),
1567
+ };
1568
+ }
1569
+ // ---- Standbys past their time. Only the two daemons can see these, so all of this is local, and it only tells. ----
1570
+ #standbyIn(row, by, local) {
1571
+ if (!row || row.position === null || row.ack === null || row.position > local.verified_position)
1572
+ return undefined;
1573
+ if (signedEntry.decode(JSON.parse(row.entry)).fields.kind !== EntryKind.message)
1574
+ return undefined;
1575
+ const body = parseBody(row.body);
1576
+ if (body?.signal !== "standby")
1577
+ return undefined;
1578
+ const due = standbyDue(body.est_minutes, signedAck.decode(JSON.parse(row.ack)).fields.time);
1579
+ return due === undefined ? undefined : { by, position: row.position, due };
1580
+ }
1581
+ // A promise is open while it's its author's latest word. A follow-up still on its way to the server has no position
1582
+ // yet, so it counts as following up. If it's refused it leaves the chain, and the promise before it is open again.
1583
+ #openStandbys(agent, local) {
1584
+ if (local.state !== "active")
1585
+ return [];
1586
+ const own = this.#standbyIn(this.#store.lastOwnEntry(agent.signer.id, local.session_id), "you", local);
1587
+ const peer = this.#standbyIn(this.#store.lastPeerEntry(agent.signer.id, local.session_id), "other_side", local);
1588
+ return [own, peer].filter((standby) => standby !== undefined);
1589
+ }
1590
+ #standbyView(agent, local) {
1591
+ const now = Date.now();
1592
+ return this.#openStandbys(agent, local).map((s) => ({ by: s.by, position: s.position, due_at: new Date(s.due).toISOString(), overdue: s.due <= now }));
1593
+ }
1594
+ // One timer, set only while a promise is open. Every wait ends at the due time or the limit, and then reads the clock.
1595
+ #armStandbyCheck(due) {
1596
+ if (this.#standbyCheck && due >= this.#standbyCheckAt)
1597
+ return;
1598
+ clearTimeout(this.#standbyCheck);
1599
+ const now = Date.now();
1600
+ this.#standbyCheckAt = Math.min(due, now + STANDBY_CHECK_MAX_MS);
1601
+ this.#standbyCheck = setTimeout(() => this.#checkStandbys(), Math.max(0, this.#standbyCheckAt - now));
1602
+ }
1603
+ // Your own promise is settled by what's on this disk, so it can be told right now, even with no server.
1604
+ // The other side's may have been kept on the server, unread, so it's left for a catch-up to confirm.
1605
+ #checkStandbys() {
1606
+ this.#standbyCheck = undefined;
1607
+ const now = Date.now();
1608
+ let next = Infinity;
1609
+ for (const agent of this.#agents.values()) {
1610
+ let confirm = false;
1611
+ for (const local of this.#store.sessionsOf(agent.signer.id)) {
1612
+ try {
1613
+ for (const standby of this.#openStandbys(agent, local)) {
1614
+ if (this.#store.standbyTold(agent.signer.id, local.session_id, standby.position))
1615
+ continue;
1616
+ if (standby.due > now)
1617
+ next = Math.min(next, standby.due);
1618
+ else if (standby.by === "you")
1619
+ this.#tellLate(agent, local, standby);
1620
+ else
1621
+ confirm = true;
1622
+ }
1623
+ }
1624
+ catch (err) {
1625
+ logEvent("standby.check_failed", { agent: agent.hex, session: toHex(local.session_id), message: err instanceof Error ? err.message : String(err) });
1626
+ }
1627
+ }
1628
+ // Offline, the catch-up comes with the reconnect. A failed one comes round again with the position check.
1629
+ if (confirm)
1630
+ this.#catchUpEverywhere(agent);
1631
+ }
1632
+ if (next !== Infinity)
1633
+ this.#armStandbyCheck(next);
1634
+ }
1635
+ // The list was asked for after the promise fell due and this daemon holds all of it, so nothing kept the promise by then.
1636
+ #tellLatePeer(agent, sessionId, listedAt, tip) {
1637
+ const local = this.#store.session(agent.signer.id, sessionId);
1638
+ if (!local || local.verified_position < tip)
1639
+ return;
1640
+ for (const standby of this.#openStandbys(agent, local)) {
1641
+ if (standby.by === "other_side" && standby.due <= listedAt)
1642
+ this.#tellLate(agent, local, standby);
1643
+ }
1644
+ }
1645
+ // The mark and the notice commit together. A crash before the doorbell still leaves the notice for the next receive or wait.
1646
+ #tellLate(agent, local, standby) {
1647
+ const due = new Date(standby.due).toISOString();
1648
+ const text = standby.by === "you"
1649
+ ? `You said you'd follow up by now, in your message at position ${standby.position}, due ${due}.`
1650
+ : `The other side said it would follow up by now, in its message at position ${standby.position}, due ${due}, and it hasn't.`;
1651
+ const told = this.#store.transaction(() => {
1652
+ if (this.#store.standbyTold(agent.signer.id, local.session_id, standby.position))
1653
+ return false;
1654
+ this.#store.markStandbyTold(agent.signer.id, local.session_id, standby.position);
1655
+ this.#store.addNotice(agent.signer.id, local.session_id, text);
1656
+ return true;
1657
+ });
1658
+ if (!told)
1659
+ return;
1660
+ const sessionHex = toHex(local.session_id);
1661
+ logEvent("standby.overdue", { agent: agent.hex, session: sessionHex, by: standby.by, position: standby.position });
1662
+ this.#events.ring(agent.hex, { type: "standby_overdue", agent: agent.name, session_id: sessionHex });
1663
+ }
1664
+ #latestFromPeer(agent, local) {
1665
+ return this.#store.unreadBounds(agent.signer.id, local.session_id, local.delivered_through)?.last ?? 0;
1666
+ }
1667
+ // Runs only after the text is stored and decrypted. This signature is what lets the server remove it.
1668
+ // It also says how far screening has got, so it goes again when that moves, or when the screen is held up.
1669
+ async #deliver(agent, local, etaSeconds = 0) {
1670
+ const refused = this.#store.unverifiablePositions(agent.signer.id, local.session_id);
1671
+ const latest = Math.max(this.#latestFromPeer(agent, local), local.delivered_through);
1672
+ // The signed list has a limit, so a flood of bad messages stops the ack there rather than growing it without end.
1673
+ const past = refused[MAX_REFUSED_POSITIONS];
1674
+ const through = past === undefined ? latest : Math.min(latest, past - 1);
1675
+ if (through === 0)
1676
+ return;
1677
+ const screened = Math.min(this.#screenedThrough(agent, local), through);
1678
+ if (through === local.delivered_through && screened <= local.acked_screened && etaSeconds === 0)
1679
+ return;
1680
+ const ack = signedAck.decode(JSON.parse(this.#store.ackAt(agent.signer.id, local.session_id, through))).fields;
1681
+ const fields = { serverId: this.#serverId(this.#urlOf(local)), sessionId: local.session_id, readerId: agent.signer.id, throughPosition: through, entryHash: ack.entryHash, root: ack.root, screenedThrough: screened, refused: refusedList(refused.filter((position) => position <= through)) };
1682
+ const signature = await agent.signer.sign("cello-delivery-ack", deliveryAckBytes(fields));
1683
+ // The rough time goes beside the ack, unsigned: a seal may keep the ack, and this number means nothing an hour later.
1684
+ await this.#routeFor(agent, local).link.call("delivery.ack", { agent: toB64(agent.signer.id), deliveryAck: signedDeliveryAck.encode({ fields, signature }), screeningEtaSeconds: etaSeconds });
1685
+ this.#store.updateSession(agent.signer.id, local.session_id, { delivered_through: through, acked_screened: screened });
1686
+ }
1687
+ // How far the reader has screened what it holds. This is only ever used to tell and to pace, so a false one costs a delay.
1688
+ async #onPeerDeliveryAck(agent, wire, etaSeconds) {
1689
+ const signed = signedDeliveryAck.decode(wire, "deliveryAck");
1690
+ const { fields } = signed;
1691
+ const local = this.#store.session(agent.signer.id, fields.sessionId);
1692
+ if (!local || !equalBytes(fields.readerId, local.counterparty_id))
1693
+ return;
1694
+ if (!(await verifySignature(this.#counterpartyKeys(local), "cello-delivery-ack", signed.bytes, signed.signature)))
1695
+ return;
1696
+ if (fields.screenedThrough > local.peer_screened_through)
1697
+ this.#store.updateSession(agent.signer.id, local.session_id, { peer_screened_through: fields.screenedThrough });
1698
+ const position = fields.screenedThrough + 1;
1699
+ // Nothing signs the time, so it's only ever a number in a notice, and only a whole one gets that far.
1700
+ if (Number.isSafeInteger(etaSeconds) && etaSeconds > 0 && position > local.peer_eta_told) {
1701
+ this.#store.updateSession(agent.signer.id, local.session_id, { peer_eta_told: position });
1702
+ this.#notify(agent, local.session_id, `The other side is still screening position ${position}, for about ${etaSeconds} more seconds. Its machine has the message, and its agent hasn't been shown it yet.`);
1703
+ }
1704
+ }
1705
+ // A bot can outrun its reader. This waits a bounded time for the gap to close, then sends anyway, and says so.
1706
+ async #paceForReader(agent, sessionId) {
1707
+ const gap = () => {
1708
+ const local = this.#store.session(agent.signer.id, sessionId);
1709
+ return local ? this.#store.countOwnAfter(agent.signer.id, sessionId, local.peer_screened_through) : 0;
1710
+ };
1711
+ const { sender_backlog_gap: allowed, sender_backlog_wait_ms: limit } = this.#settings;
1712
+ if (gap() <= allowed)
1713
+ return {};
1714
+ const started = Date.now();
1715
+ while (gap() > allowed && Date.now() - started < limit) {
1716
+ await new Promise((resolve) => setTimeout(resolve, SENDER_BACKLOG_CHECK_MS));
1717
+ }
1718
+ const behind = gap();
1719
+ const waited = Date.now() - started;
1720
+ return { slowed: { waited_ms: waited, reader_behind_by: behind, message: `The other side's screening is ${behind} of your messages behind, so this send waited ${Math.round(waited / 1000)} seconds. Your messages are safe, and they're delivered in order as it catches up.` } };
1721
+ }
1722
+ // Credentials and hijack artifacts stop here, before anything is signed, on a thread that never runs the model.
1723
+ async #screenOutbound(agent, text, params, retry) {
1724
+ const keys = [...this.#agents.keys(), ...this.#store.sessionsOf(agent.signer.id).map((s) => toHex(s.counterparty_id))];
1725
+ const guards = this.governance.guards;
1726
+ const pii = { whitelist: guards.value(agent.signer.id, "pii_whitelist"), email: guards.value(agent.signer.id, "pii_check_email"), phone: guards.value(agent.signer.id, "pii_check_phone") };
1727
+ let verdict;
1728
+ try {
1729
+ verdict = await this.#outbound.screen(text, keys, pii);
1730
+ }
1731
+ catch (err) {
1732
+ throw new LocalError("screener_unavailable", `The outbound screen didn't run, so nothing was sent: ${err instanceof Error ? err.message : String(err)}. It restarts by itself, so try again.`);
1733
+ }
1734
+ if (verdict.disposition === "block")
1735
+ throw new LocalError("blocked_by_screening", `Nothing was sent: ${verdict.reason}. Categories: ${verdict.categories.join(", ")}.`);
1736
+ if (verdict.disposition === "hold") {
1737
+ const held = (verdict.held ?? []).map((h) => `${h.category.replace("pii:", "")} ${h.value}`).join(", ");
1738
+ if (params["allow_flagged"] !== true) {
1739
+ throw new LocalError("held_by_guard", `Nothing was sent, because it looks like personal data: ${held}. Say it without that, or have it let through with allow_flagged, which needs a person unless autonomous_override is on.`);
1740
+ }
1741
+ if (!guards.value(agent.signer.id, "autonomous_override")) {
1742
+ requirePerson(params, `This sends personal data from ${agent.hex}: ${held}.`, retry);
1743
+ }
1744
+ logEvent("guard.held_value_sent", { agent: agent.hex, categories: (verdict.held ?? []).map((h) => h.category), by_a_person: params["person_confirmed"] === true });
1745
+ return { text: verdict.text, report: { let_through: (verdict.held ?? []).map((h) => h.category) } };
1746
+ }
1747
+ if (verdict.disposition === "redact")
1748
+ return { text: verdict.text, report: { redacted: verdict.categories, message: "Parts of your message were replaced before sending: the text that went out isn't exactly what you wrote." } };
1749
+ return { text, report: {} };
1750
+ }
1751
+ // ---- This agent's own status ----
1752
+ // An agent's own server, or its own keys, stop it everywhere on this daemon. Any other server's word holds only for that server,
1753
+ // because a server it merely visited shouldn't be able to switch it off for everyone.
1754
+ #stopAt(agent, url) {
1755
+ for (const row of agent.statuses.values()) {
1756
+ if (row.status !== "active" && (row.everywhere === 1 || row.server_url === url))
1757
+ return row;
1758
+ }
1759
+ return undefined;
1760
+ }
1761
+ #refuseIfStopped(agent, url) {
1762
+ const stop = this.#stopAt(agent, url);
1763
+ if (stop?.status === "retired")
1764
+ throw new LocalError("agent_retired", `${agent.name} is retired, for good. Its record stays readable.`);
1765
+ if (stop)
1766
+ throw new LocalError("agent_suspended", `${agent.name} is suspended (reason: ${stop.reason}). Nothing was sent or read. It can still seal what's already witnessed, and only its operator or the portal can lift this.`);
1767
+ }
1768
+ assertCanAct(agentHex) {
1769
+ const agent = this.#requireAgent(agentHex);
1770
+ this.#refuseIfStopped(agent, this.#url);
1771
+ }
1772
+ #setStatus(agent, url, status, reason, everywhere) {
1773
+ const row = { server_url: url, status, reason, everywhere: everywhere ? 1 : 0 };
1774
+ this.#store.setStatus(agent.signer.id, row);
1775
+ agent.statuses.set(url, row);
1776
+ }
1777
+ // What a server has just said about this agent, whether it pushed that or answered a proof with it.
1778
+ #noteStanding(agent, route, standing) {
1779
+ const known = agent.statuses.get(route.url);
1780
+ // Retired is final here too, whatever a server says later.
1781
+ if (known?.status === "retired")
1782
+ return;
1783
+ if ((known?.status ?? "active") === standing.status && known?.reason === standing.reason)
1784
+ return;
1785
+ if (!known && standing.status === "active")
1786
+ return;
1787
+ // This agent's own stop hasn't reached that server yet, so that server's "active" is out of date, not a lifting.
1788
+ if (standing.status === "active" && this.#store.outbox(route.url).some((row) => equalBytes(row.agent_id, agent.signer.id)))
1789
+ return;
1790
+ this.#setStatus(agent, route.url, standing.status, standing.reason, route.home);
1791
+ route.longProved.delete(agent.hex);
1792
+ logEvent("agent.status_changed", { agent: agent.hex, status: standing.status, reason: standing.reason, server: route.url });
1793
+ if (standing.status === "retired") {
1794
+ if (route.home)
1795
+ agent.online = false;
1796
+ route.online.delete(agent.hex);
1797
+ route.wanted.delete(agent.hex);
1798
+ }
1799
+ this.#events.ring(agent.hex, { type: "agent_status", agent: agent.name });
1800
+ // A signed word from anyone but the server itself holds elsewhere too, so it's carried to every other server this agent uses.
1801
+ if (standing.record && signedStatusStatement.decode(standing.record.statement).fields.issuer !== StatusIssuer.server) {
1802
+ for (const url of this.#serversOf(agent)) {
1803
+ if (url !== route.url)
1804
+ this.#store.addToOutbox(agent.signer.id, url, JSON.stringify(standing.record.statement));
1805
+ }
1806
+ this.#retryOutbox();
1807
+ }
1808
+ if (standing.status === "active")
1809
+ this.#catchUpEverywhere(agent);
1810
+ }
1811
+ #serversOf(agent) {
1812
+ return [...new Set([this.#url, ...this.#store.sessionsOf(agent.signer.id).map((local) => this.#urlOf(local))])];
1813
+ }
1814
+ #routeAt(url) {
1815
+ return url === this.#url ? this.#home : this.#visitRoute(url);
1816
+ }
1817
+ #retryOutbox() {
1818
+ for (const url of new Set(this.#store.outbox().map((row) => row.server_url)))
1819
+ this.#flushOutbox(this.#routeAt(url));
1820
+ }
1821
+ // A statement carries its own authority, so it goes on any connection, and needs nothing proved first.
1822
+ #flushOutbox(route) {
1823
+ for (const row of this.#store.outbox(route.url)) {
1824
+ this.#background("status statement", route.link.call("agent.status", { statement: JSON.parse(row.statement) }).then(() => this.#store.removeFromOutbox(row), (err) => {
1825
+ if (err instanceof ServerUnreachable)
1826
+ return;
1827
+ // A final answer: it's stale, retired already, or that server has never seen this agent.
1828
+ this.#store.removeFromOutbox(row);
1829
+ logEvent("agent.status_refused", { agent: toHex(row.agent_id), server: route.url, code: err instanceof ServerRefused ? err.code : "failed" });
1830
+ }));
1831
+ }
1832
+ }
1833
+ async #whenReady(route, ms) {
1834
+ const deadline = Date.now() + ms;
1835
+ while (!route.link.ready && Date.now() < deadline)
1836
+ await new Promise((resolve) => setTimeout(resolve, 100));
1837
+ return route.link.ready;
1838
+ }
1839
+ // Durable before anything goes out: this daemon stops at once, and the servers are told as soon as each can be reached.
1840
+ async #stopOwn(agent, status, reason) {
1841
+ const fields = { agentId: agent.signer.id, status: AgentStatus[status], reason: StatusReason[reason], issuer: StatusIssuer.agent, issuerId: agent.signer.id, issuedAt: Date.now() };
1842
+ const statement = signedStatusStatement.encode({ fields, signature: await agent.signer.sign(STATUS_DOMAIN, statusStatementBytes(fields)) });
1843
+ const servers = this.#serversOf(agent);
1844
+ this.#store.transaction(() => {
1845
+ this.#setStatus(agent, this.#url, status, reason, true);
1846
+ for (const url of servers)
1847
+ this.#store.addToOutbox(agent.signer.id, url, JSON.stringify(statement));
1848
+ });
1849
+ logEvent("agent.status_signed", { agent: agent.hex, status, reason });
1850
+ this.#events.ring(agent.hex, { type: "agent_status", agent: agent.name });
1851
+ const answers = await Promise.all(servers.map(async (url) => {
1852
+ const route = this.#routeAt(url);
1853
+ route.longProved.delete(agent.hex);
1854
+ if (!(await this.#whenReady(route, STATUS_TELL_MS)))
1855
+ return { url, told: false };
1856
+ try {
1857
+ await route.link.call("agent.status", { statement });
1858
+ }
1859
+ catch (err) {
1860
+ if (err instanceof ServerUnreachable)
1861
+ return { url, told: false };
1862
+ logEvent("agent.status_refused", { agent: agent.hex, server: url, code: err instanceof ServerRefused ? err.code : "failed" });
1863
+ }
1864
+ for (const row of this.#store.outbox(url))
1865
+ if (equalBytes(row.agent_id, agent.signer.id))
1866
+ this.#store.removeFromOutbox(row);
1867
+ return { url, told: true };
1868
+ }));
1869
+ return { told: answers.filter((a) => a.told).map((a) => a.url), not_yet: answers.filter((a) => !a.told).map((a) => a.url) };
1870
+ }
1871
+ async suspend(agentHex, reason) {
1872
+ const agent = this.#requireAgent(agentHex);
1873
+ this.#refuseIfRetired(agent);
1874
+ const chosen = reason === undefined ? "owner_request" : reason;
1875
+ if (chosen !== "owner_request" && chosen !== "lost_machine" && chosen !== "compromise")
1876
+ throw new LocalError("bad_argument", "reason must be owner_request, lost_machine or compromise");
1877
+ const { told, not_yet } = await this.#stopOwn(agent, "suspended", chosen);
1878
+ return { agent_id: agent.hex, status: "suspended", reason: chosen, told, not_yet, note: "Only its server's operator, or the portal, can lift this. Sealing what's already witnessed still works." };
1879
+ }
1880
+ async retire(agentHex, reason) {
1881
+ const agent = this.#requireAgent(agentHex);
1882
+ const chosen = reason === undefined ? "owner_request" : reason;
1883
+ if (chosen !== "owner_request" && chosen !== "compromise")
1884
+ throw new LocalError("bad_argument", "reason must be owner_request or compromise");
1885
+ const { told, not_yet } = await this.#stopOwn(agent, "retired", chosen);
1886
+ agent.online = false;
1887
+ return { agent_id: agent.hex, status: "retired", reason: chosen, told, not_yet, deferred: not_yet.length > 0 };
1888
+ }
1889
+ #refuseIfRetired(agent) {
1890
+ for (const row of agent.statuses.values()) {
1891
+ if (row.status === "retired")
1892
+ throw new LocalError("agent_retired", `${agent.name} is retired already, for good.`);
1893
+ }
1894
+ }
1895
+ // Retires it, then takes it off this machine's lists and frees its name. Its keys and history stay in the database, as a record.
1896
+ async removeAgent(agentHex) {
1897
+ const agent = this.#requireAgent(agentHex);
1898
+ const answer = await this.retire(agentHex, undefined);
1899
+ this.#store.markRemoved(agent.signer.id);
1900
+ this.#agents.delete(agent.hex);
1901
+ for (const route of [this.#home, ...this.#visiting.values()])
1902
+ route.wanted.delete(agent.hex);
1903
+ return { removed: true, name: agent.name, ...answer };
1904
+ }
1905
+ // Asks each server this agent uses, and checks what comes back with public keys. Only this agent's keys can ask.
1906
+ async agentStatus(agentHex) {
1907
+ const agent = this.#requireAgent(agentHex);
1908
+ const servers = await Promise.all(this.#serversOf(agent).map(async (url) => {
1909
+ const route = this.#routeAt(url);
1910
+ if (!(await this.#whenReady(route, STATUS_TELL_MS)))
1911
+ return { server: url, reachable: false, problem: route.link.problem };
1912
+ const server = route.home ? this.#server : route.server;
1913
+ if (!server)
1914
+ return { server: url, reachable: false, problem: "still connecting" };
1915
+ const clientNonce = new Uint8Array(randomBytes(32));
1916
+ const signature = await agent.signer.sign("cello-agent-auth", agentAuthBytes({ serverId: server.id, agentId: agent.signer.id, serverNonce: server.nonce, clientNonce }));
1917
+ const answer = await this.#call(() => route.link.call("agent.status.read", { identity: identityCodec.encode(agent.signer.publicIdentity), clientNonce: toB64(clientNonce), signature: signatureCodec.encode(signature) }));
1918
+ const checked = await checkStatusLog(answer.records, agent.signer.id, this.#serverIdentity(url));
1919
+ if (!checked.ok)
1920
+ throw new LocalError("status_log_bad", `${url}: ${checked.message}`);
1921
+ return { server: url, reachable: true, status: answer.status, reason: answer.reason, verified: true, log: checked.log };
1922
+ }));
1923
+ const stop = this.#stopAt(agent, this.#url);
1924
+ return { agent_id: agent.hex, status_here: stop?.status ?? "active", servers };
1925
+ }
1926
+ // ---- Sending ----
1927
+ // Waits a while for a long upload. If it's still going, the agent hears so and the upload carries on.
1928
+ // When it finishes, the ordinary resend picks up its answer and sends whatever waited behind it.
1929
+ #upload(agent, route, local, row, params) {
1930
+ const upload = { finished: this.#longCall(agent, route, "entry.append", params), done: false };
1931
+ this.#uploads.set(row.id, upload);
1932
+ const sessionHex = toHex(local.session_id);
1933
+ upload.finished.then(() => {
1934
+ upload.done = true;
1935
+ this.#background("long upload finished", this.#lane(agent.hex, sessionHex, async () => {
1936
+ if (this.#uploads.has(row.id))
1937
+ await this.#settle(agent, this.#store.session(agent.signer.id, local.session_id));
1938
+ }));
1939
+ }, () => { this.#uploads.delete(row.id); });
1940
+ return this.#withinPatience(upload.finished);
1941
+ }
1942
+ async #withinPatience(finished) {
1943
+ let timer;
1944
+ const patience = new Promise((resolve) => { timer = setTimeout(() => resolve(STILL_UPLOADING), LONG_SEND_PATIENCE_MS); });
1945
+ try {
1946
+ return await Promise.race([finished, patience]);
1947
+ }
1948
+ finally {
1949
+ clearTimeout(timer);
1950
+ }
1951
+ }
1952
+ async #attempt(agent, local, row) {
1953
+ const route = this.#routeFor(agent, local);
1954
+ // Connected but not yet proved would be refused, and a refusal means this entry never goes.
1955
+ if (!this.#isOnline(agent, route))
1956
+ return { status: "pending" };
1957
+ // Whatever is signed after a long message waits for it: it would be refused for arriving first, as the connections don't keep order between them.
1958
+ if (this.#uploads.size > 0) {
1959
+ const first = this.#store.pendingEntries(agent.signer.id, local.session_id)[0];
1960
+ const earlier = first && first.id !== row.id ? this.#uploads.get(first.id) : undefined;
1961
+ if (earlier)
1962
+ return { status: "pending", uploading: true };
1963
+ }
1964
+ let result;
1965
+ try {
1966
+ const params = { agent: toB64(agent.signer.id), entry: JSON.parse(row.entry), ciphertext: toB64(row.ciphertext) };
1967
+ const underWay = this.#uploads.get(row.id);
1968
+ if (underWay && !underWay.done)
1969
+ return { status: "pending", uploading: true };
1970
+ let answer;
1971
+ if (underWay)
1972
+ answer = await underWay.finished;
1973
+ else if (row.ciphertext.length > LONG_CIPHERTEXT_BYTES)
1974
+ answer = await this.#upload(agent, route, local, row, params);
1975
+ else
1976
+ answer = await route.link.call("entry.append", params);
1977
+ if (answer === STILL_UPLOADING)
1978
+ return { status: "pending", uploading: true };
1979
+ this.#uploads.delete(row.id);
1980
+ result = answer;
1981
+ }
1982
+ catch (err) {
1983
+ if (err instanceof ServerUnreachable)
1984
+ return { status: "pending" };
1985
+ if (err instanceof ServerRefused) {
1986
+ if (err.code === "agent_suspended" || err.code === "agent_retired")
1987
+ this.#noteStanding(agent, route, { status: err.code === "agent_retired" ? "retired" : "suspended", reason: "none", record: null });
1988
+ // A repeat of a landed entry always returns its ack, so a refusal means this entry never landed.
1989
+ this.#store.markNotSent(row.id);
1990
+ this.#armStandbyCheck(Date.now());
1991
+ return { status: "refused", code: err.code, message: err.message };
1992
+ }
1993
+ throw err;
1994
+ }
1995
+ const ack = signedAck.decode(result.ack, "ack").fields;
1996
+ if (!equalBytes(ack.entryHash, row.entry_hash))
1997
+ throw new Error("the server acknowledged a different entry");
1998
+ this.#store.markLanded(row.id, ack.position, JSON.stringify(result.ack));
1999
+ const verifier = this.#verifier(agent, local);
2000
+ if (ack.position === verifier.position + 1) {
2001
+ const fresh = this.#store.session(agent.signer.id, local.session_id);
2002
+ await this.#ingest(agent, fresh, { entry: JSON.parse(row.entry), ack: result.ack, ciphertext: null });
2003
+ }
2004
+ return { status: "landed", position: ack.position };
2005
+ }
2006
+ async #append(agent, local, kind, mode, body) {
2007
+ const encodedBody = bodyBytes(body);
2008
+ const ciphertext = sealSessionContent(local.session_key, encodedBody);
2009
+ if (ciphertext.length > MAX_CIPHERTEXT_BYTES)
2010
+ throw new LocalError("too_large", tooLargeMessage(encodedBody.length));
2011
+ const verifier = this.#verifier(agent, local);
2012
+ const firstUnread = this.#store.firstUnreadToAnswer(agent.signer.id, local.session_id, local.read_position);
2013
+ const readPosition = firstUnread !== undefined ? firstUnread - 1 : verifier.position;
2014
+ const readRoot = verifier.rootAt(readPosition);
2015
+ if (!readRoot)
2016
+ throw new Error(`no root is held for position ${readPosition}`);
2017
+ const last = this.#store.lastOwnEntry(agent.signer.id, local.session_id);
2018
+ const lastFields = last ? signedEntry.decode(JSON.parse(last.entry)).fields : undefined;
2019
+ const fields = {
2020
+ serverId: this.#serverId(this.#urlOf(local)),
2021
+ sessionId: local.session_id,
2022
+ authorId: agent.signer.id,
2023
+ authorSeq: (lastFields?.authorSeq ?? 0) + 1,
2024
+ prevOwnHash: last ? last.entry_hash : ZERO_HASH,
2025
+ readPosition,
2026
+ readRoot,
2027
+ kind,
2028
+ mode,
2029
+ contentHash: saltedContentHash(local.salt, encodedBody),
2030
+ ciphertextHash: ciphertextHash(ciphertext),
2031
+ notAfter: Date.now() + SEND_WINDOW_MS,
2032
+ };
2033
+ const signature = await agent.signer.sign("cello-entry", entryBytes(fields));
2034
+ // On disk before it goes anywhere, so a crash after this point can only resend identical bytes.
2035
+ this.#store.insertEntry({
2036
+ agent_id: agent.signer.id,
2037
+ session_id: local.session_id,
2038
+ entry_hash: entryHash(fields),
2039
+ state: "pending",
2040
+ own: 1,
2041
+ entry: JSON.stringify(signedEntry.encode({ fields, signature })),
2042
+ ciphertext,
2043
+ body: encodedBody,
2044
+ });
2045
+ const row = this.#store.lastOwnEntry(agent.signer.id, local.session_id);
2046
+ return this.#attempt(agent, local, row);
2047
+ }
2048
+ #requireAgent(agentHex) {
2049
+ const agent = this.#agents.get(agentHex);
2050
+ if (!agent)
2051
+ throw new LocalError("unknown_agent", "no such agent on this machine");
2052
+ return agent;
2053
+ }
2054
+ // The signals each side showed with this call, checked again now. The other side's come with their standing and notes, and never a payload.
2055
+ async presentedSignals(agentHex, sessionHex) {
2056
+ const agent = this.#requireAgent(agentHex);
2057
+ const local = this.#requireSession(agent, sessionHex);
2058
+ const theirSide = local.role === "caller" ? "callee" : "caller";
2059
+ const ownSide = local.role;
2060
+ const theirs = await this.wallet.examine(agent.hex, toHex(local.counterparty_id), this.#presented.files(agent.signer.id, local.session_id, theirSide), "signal.presented.refused");
2061
+ return {
2062
+ session_id: toHex(local.session_id),
2063
+ from: toHex(local.counterparty_id),
2064
+ theirs: theirs.signals,
2065
+ refused: theirs.refused,
2066
+ theirs_unreadable: this.#presented.unreadable(agent.signer.id, local.session_id, theirSide),
2067
+ yours_sent: this.#presented.files(agent.signer.id, local.session_id, ownSide).length,
2068
+ };
2069
+ }
2070
+ #requireSession(agent, sessionHex) {
2071
+ // A short id isn't an id at all, but a piece of a real one is a paste that got cut.
2072
+ if (typeof sessionHex === "string" && /^[0-9a-fA-F]+$/.test(sessionHex) && sessionHex.length < 32 && this.#store.sessionsOf(agent.signer.id).some((row) => toHex(row.session_id).startsWith(sessionHex.toLowerCase()))) {
2073
+ throw new LocalError("unknown_session", TRUNCATED_SESSION_GUIDANCE);
2074
+ }
2075
+ const id = parseHex(sessionHex, 16, "session id");
2076
+ const local = this.#store.session(agent.signer.id, id);
2077
+ if (local)
2078
+ return local;
2079
+ const another = [...this.#agents.values()].some((other) => this.#store.session(other.signer.id, id) !== undefined);
2080
+ throw new LocalError("unknown_session", another ? OTHER_AGENTS_SESSION_GUIDANCE : NO_SESSION_GUIDANCE);
2081
+ }
2082
+ // Returns an outcome rather than throwing for anything the agent can act on.
2083
+ // The outbound cap, read fresh each send so a change holds from the next message. A slot is only used by a send that goes.
2084
+ #rateFor(agent) {
2085
+ const max = this.governance.guards.value(agent.signer.id, "rate_max_per_window");
2086
+ const window = this.governance.guards.value(agent.signer.id, "rate_window_ms");
2087
+ if (max === 0)
2088
+ return undefined;
2089
+ const held = this.#rates.get(agent.hex);
2090
+ if (held?.max === max && held.window === window)
2091
+ return held.limiter;
2092
+ const limiter = new OutboundRateLimiter({ maxPerWindow: max, windowMs: window });
2093
+ this.#rates.set(agent.hex, { max, window, limiter });
2094
+ return limiter;
2095
+ }
2096
+ async send(agentHex, sessionHex, text, signal, estMinutes, notice, params = {}) {
2097
+ const agent = this.#requireAgent(agentHex);
2098
+ // First, so a stopped agent hears that, and not a rate limit or a screening hold. The lane checks again, after the waits.
2099
+ this.#refuseIfStopped(agent, this.#urlOf(this.#requireSession(agent, sessionHex)));
2100
+ const rate = this.#rateFor(agent);
2101
+ const limited = rate?.peek(agent.hex);
2102
+ if (limited?.limited)
2103
+ throw new LocalError("rate_limited", limited.guidance);
2104
+ if (!SIGNALS.includes(signal))
2105
+ throw new LocalError("missing_signal", SIGNAL_ERROR);
2106
+ if (signal === "standby" && standbyDue(estMinutes, Date.now()) === undefined)
2107
+ throw new LocalError("missing_est_minutes", "standby needs est_minutes, a positive number of minutes until your follow-up");
2108
+ const screened = await this.#screenOutbound(agent, text, params, `cello send ${sessionHex} - --allow-flagged --over --agent ${agent.hex}`);
2109
+ // A notice is how "stop" gets through, so it never waits. These waits are outside the lane, so what arrives meanwhile isn't held up.
2110
+ const paced = notice ? {} : await this.#paceForReader(agent, this.#requireSession(agent, sessionHex).session_id);
2111
+ return this.#lane(agentHex, sessionHex, async () => {
2112
+ let local = this.#requireSession(agent, sessionHex);
2113
+ this.#refuseIfStopped(agent, this.#urlOf(local));
2114
+ if (local.state !== "active")
2115
+ throw new LocalError(local.state === "closed" ? "session_closed" : "session_not_active", local.state === "closed" ? SESSION_CLOSED_GUIDANCE : `this session is ${local.state}`);
2116
+ if (local.own_closed)
2117
+ throw new LocalError("session_closed", `you've already closed this session. ${SESSION_CLOSED_GUIDANCE}`);
2118
+ if (local.frozen === 1)
2119
+ throw new LocalError("session_frozen", "the server signed two different things at one position, so this session takes nothing more from you. You can still read and seal it. The proof is kept: see evidence.");
2120
+ if (local.fault)
2121
+ throw new LocalError("session_holding", `this session is holding: ${local.fault}. It rechecks by itself.`);
2122
+ if (!notice && this.#store.unreadCount(agent.signer.id, local.session_id, local.read_position) > 0) {
2123
+ const deliverable = this.#store.deliverableCount(agent.signer.id, local.session_id, local.read_position);
2124
+ const waiting = this.#screening.waiting(agent.hex, sessionHex);
2125
+ if (deliverable === 0 && waiting) {
2126
+ throw new LocalError("session_not_current", `A message has arrived that's still being screened: position ${waiting.position}, for about ${waiting.about_seconds} more seconds. Nothing was sent. A doorbell rings when it's ready. To say something now, such as stop, send it as a notice.`);
2127
+ }
2128
+ throw new LocalError("session_not_current", "a message has arrived that you haven't read. Nothing was sent. Call receive, then decide what to say.");
2129
+ }
2130
+ if (this.#store.pendingEntries(agent.signer.id, local.session_id).length > 0) {
2131
+ await this.#resendPending(agent, local);
2132
+ local = this.#store.session(agent.signer.id, local.session_id);
2133
+ if (this.#store.pendingEntries(agent.signer.id, local.session_id).length > 0) {
2134
+ throw new LocalError("previous_send_pending", "your previous message hasn't reached the server yet, so this one wasn't queued. Try again once it has.");
2135
+ }
2136
+ }
2137
+ const body = { n: new Uint8Array(randomBytes(16)), text: screened.text, signal, est_minutes: estMinutes ?? null };
2138
+ const outcome = await this.#append(agent, local, EntryKind.message, notice ? EntryMode.notice : EntryMode.reply, body);
2139
+ if (outcome.status === "landed") {
2140
+ rate?.record(agent.hex);
2141
+ // Answering a call is a reply. Talking in a session you called only becomes one once they've spoken.
2142
+ if (local.role === "callee" || this.#store.lastPeerEntry(agent.signer.id, local.session_id))
2143
+ this.governance.engaged(agent.signer.id, local.counterparty_id, "replied");
2144
+ }
2145
+ return { ...await this.#reportSend(agent, local, outcome), ...screened.report, ...paced };
2146
+ });
2147
+ }
2148
+ async #reportSend(agent, local, outcome) {
2149
+ if (outcome.status === "landed") {
2150
+ const fresh = this.#store.session(agent.signer.id, local.session_id);
2151
+ if (outcome.position > this.#verifier(agent, fresh).position)
2152
+ await this.#settle(agent, fresh);
2153
+ return { sent: true, position: outcome.position };
2154
+ }
2155
+ if (outcome.status === "pending" && outcome.uploading)
2156
+ return { sent: false, status: "not_sent_yet", message: "A long message is still uploading on a slow connection. Your message is saved, and it goes by itself. You'll get a notice." };
2157
+ if (outcome.status === "pending")
2158
+ return { sent: false, status: "not_sent_yet", message: "The server can't be reached. Your message is saved, and it goes when the server is back. You'll get a notice." };
2159
+ if (outcome.code === "not_current") {
2160
+ await this.#settle(agent, this.#store.session(agent.signer.id, local.session_id));
2161
+ throw new LocalError("session_not_current", "a message arrived just before yours. Nothing was sent. Call receive, then decide what to say.");
2162
+ }
2163
+ throw new LocalError(outcome.code, outcome.message);
2164
+ }
2165
+ async close(agentHex, sessionHex) {
2166
+ const agent = this.#requireAgent(agentHex);
2167
+ return this.#lane(agentHex, sessionHex, () => this.#closeInLane(agent, sessionHex));
2168
+ }
2169
+ async #closeInLane(agent, sessionHex, oneMessage = false) {
2170
+ const local = this.#requireSession(agent, sessionHex);
2171
+ if (local.own_closed || local.state === "closed")
2172
+ return { closed: true, state: local.state };
2173
+ this.#refuseIfStopped(agent, this.#urlOf(local));
2174
+ if (local.state !== "active")
2175
+ throw new LocalError("session_not_active", `this session is ${local.state}`);
2176
+ await this.#resendPending(agent, local);
2177
+ // Their close is an entry too, and it isn't a message anyone could have read.
2178
+ const lastPeer = this.#store.lastPeerEntry(agent.signer.id, local.session_id);
2179
+ const theirCloseUnread = local.peer_closed === 1 && lastPeer !== undefined && lastPeer.position > local.read_position;
2180
+ const neverRead = this.#store.unreadCount(agent.signer.id, local.session_id, local.read_position) - (theirCloseUnread ? 1 : 0);
2181
+ // Durable before the close goes, so a crash anywhere after this still ends in a seal.
2182
+ this.#store.addSealWant(agent.signer.id, local.session_id, SEAL_EVERYTHING_HELD);
2183
+ const body = { n: new Uint8Array(randomBytes(16)), text: "", signal: null, est_minutes: null, ...(oneMessage ? { one_message: true } : {}) };
2184
+ const outcome = await this.#append(agent, this.#store.session(agent.signer.id, local.session_id), EntryKind.close, EntryMode.notice, body);
2185
+ const report = await this.#reportSend(agent, local, outcome);
2186
+ const seal = report.sent ? await this.#sealAfterClose(agent, local.session_id) : notSealedYet("the close hasn't reached the server");
2187
+ const fresh = this.#store.session(agent.signer.id, local.session_id);
2188
+ return { closed: report.sent, state: fresh.state, peer_closed: fresh.peer_closed === 1, seal, ...report, ...(report.sent && neverRead > 0 ? { unread_count: neverRead, unread_warning: unreadWarning(neverRead, sessionHex) } : {}) };
2189
+ }
2190
+ // ---- Sealing ----
2191
+ async seal(agentHex, sessionHex, through) {
2192
+ const agent = this.#requireAgent(agentHex);
2193
+ if (through !== undefined && (!Number.isSafeInteger(through) || through < 1))
2194
+ throw new LocalError("bad_argument", "through must be a position, a whole number from 1 up");
2195
+ return this.#lane(agentHex, sessionHex, async () => {
2196
+ const local = this.#requireSession(agent, sessionHex);
2197
+ if (this.#stopAt(agent, this.#urlOf(local))?.status === "retired")
2198
+ this.#refuseIfStopped(agent, this.#urlOf(local));
2199
+ if (local.verified_position < 1)
2200
+ throw new LocalError("nothing_to_seal", "this session has no witnessed messages yet");
2201
+ if (through !== undefined && through > local.verified_position)
2202
+ throw new LocalError("seal_beyond_held", `you hold this session through position ${local.verified_position}, so ${through} can't be sealed`);
2203
+ const wanted = through ?? local.verified_position;
2204
+ this.#store.addSealWant(agent.signer.id, local.session_id, wanted);
2205
+ return this.#attemptSeal(agent, local.session_id, wanted);
2206
+ });
2207
+ }
2208
+ // A want is removed only by a stored seal or a final refusal. Anything else leaves it to retry at the next catch-up.
2209
+ async #attemptSeal(agent, sessionId, wanted) {
2210
+ const local = this.#store.session(agent.signer.id, sessionId);
2211
+ const through = wanted === SEAL_EVERYTHING_HELD ? local.verified_position : wanted;
2212
+ if (through < 1) {
2213
+ this.#store.removeSealWant(agent.signer.id, sessionId, wanted);
2214
+ throw new LocalError("nothing_to_seal", "this session has no witnessed messages yet");
2215
+ }
2216
+ const route = this.#routeFor(agent, local);
2217
+ if (!this.#isOnline(agent, route))
2218
+ return notSealedYet(route.link.problem ?? "this agent isn't online yet");
2219
+ const root = this.#verifier(agent, local).rootAt(through);
2220
+ if (!root)
2221
+ throw new Error(`no root is held for position ${through}`);
2222
+ const fields = { serverId: this.#serverId(route.url), sessionId, sealerId: agent.signer.id, counterpartyId: local.counterparty_id, throughPosition: through, root };
2223
+ const signature = await agent.signer.sign("cello-seal-request", sealRequestBytes(fields));
2224
+ let answer;
2225
+ try {
2226
+ answer = await route.link.call("seal.request", {
2227
+ agent: toB64(agent.signer.id),
2228
+ request: signedSealRequest.encode({ fields, signature }),
2229
+ knownLogSize: this.#knownSealLogHead(route.url)?.size ?? 0,
2230
+ });
2231
+ }
2232
+ catch (err) {
2233
+ if (err instanceof ServerUnreachable)
2234
+ return notSealedYet(err.message);
2235
+ if (err instanceof ServerRefused && SEAL_RETRY_CODES.includes(err.code))
2236
+ return notSealedYet(`${err.code}: ${err.message}`);
2237
+ if (err instanceof ServerRefused) {
2238
+ this.#store.removeSealWant(agent.signer.id, sessionId, wanted);
2239
+ throw new LocalError(err.code, err.code === "seal_root_mismatch" ? `${err.message}. ${compareTranscripts(toHex(sessionId))}` : err.message);
2240
+ }
2241
+ throw err;
2242
+ }
2243
+ let record;
2244
+ try {
2245
+ record = await this.#checkSealAnswer(agent, local, through, root, answer.record, answer.logProof);
2246
+ }
2247
+ catch (err) {
2248
+ this.#store.removeSealWant(agent.signer.id, sessionId, wanted);
2249
+ logEvent("seal.refused", { agent: agent.hex, session: toHex(sessionId), code: err instanceof LocalError ? err.code : "failed" });
2250
+ throw err;
2251
+ }
2252
+ const head = record.log.head.fields;
2253
+ this.#store.transaction(() => {
2254
+ this.#store.addSeal(agent.signer.id, sealId(record.certificate.bytes), sessionId, JSON.stringify(answer.record));
2255
+ this.#store.removeSealWant(agent.signer.id, sessionId, wanted);
2256
+ this.#store.setConfig(this.#pinKey(CONFIG_SEAL_KEY, route.url), toHex(head.sealKeyId));
2257
+ if (head.size > (this.#knownSealLogHead(route.url)?.size ?? 0))
2258
+ this.#store.setConfig(this.#pinKey(CONFIG_SEAL_LOG_HEAD, route.url), JSON.stringify({ size: head.size, root: toB64(head.root) }));
2259
+ });
2260
+ logEvent("seal.stored", { agent: agent.hex, session: toHex(sessionId), through });
2261
+ return { sealed: true, ...sealSummary(record), statement: describeSeal(record), note: SEAL_NOTE };
2262
+ }
2263
+ #knownSealLogHead(url) {
2264
+ const stored = this.#store.getConfig(this.#pinKey(CONFIG_SEAL_LOG_HEAD, url));
2265
+ if (!stored)
2266
+ return undefined;
2267
+ const parsed = JSON.parse(stored);
2268
+ return { size: parsed.size, root: fromB64(parsed.root, "stored seal log root") };
2269
+ }
2270
+ // The server can send anything, so nothing is stored or reported as sealed until it all checks out against this record.
2271
+ async #checkSealAnswer(agent, local, through, root, raw, logProof) {
2272
+ let decoded;
2273
+ try {
2274
+ decoded = decodeSealRecord(raw);
2275
+ }
2276
+ catch (err) {
2277
+ throw new LocalError("malformed_record", `the server's seal record can't be read: ${err instanceof Error ? err.message : String(err)}`);
2278
+ }
2279
+ const url = this.#urlOf(local);
2280
+ if (!equalBytes(identityId(decoded.server), this.#serverId(url)))
2281
+ throw new LocalError("seal_wrong_server", "this seal names a server other than the one this daemon pinned");
2282
+ const sealKeyId = identityId(decoded.sealKey);
2283
+ const pinned = this.#store.getConfig(this.#pinKey(CONFIG_SEAL_KEY, url));
2284
+ if (pinned && pinned !== toHex(sealKeyId))
2285
+ throw new LocalError("seal_key_changed", `this server's seal key has changed since your first seal: it was ${pinned}, and it's now ${toHex(sealKeyId)}`);
2286
+ const check = await checkSealRecord(raw, sealKeyId);
2287
+ if (!check.ok)
2288
+ throw new LocalError(check.fault, check.message);
2289
+ const cert = check.record.certificate.fields;
2290
+ if (!equalBytes(cert.root, root))
2291
+ throw new LocalError("seal_root_mismatch", sealMismatchMessage(through, toHex(local.session_id)));
2292
+ const subject = equalBytes(cert.sessionId, local.session_id) && equalBytes(cert.sealerId, agent.signer.id) && equalBytes(cert.counterpartyId, local.counterparty_id) && cert.throughPosition === through;
2293
+ if (!subject)
2294
+ throw new LocalError("seal_wrong_subject", "the server's certificate isn't for this seal: its session, parties or position differ");
2295
+ if (cert.tip < local.verified_position || (local.state === "closed" && cert.closed !== 1)) {
2296
+ throw new LocalError("seal_misreports_session", `the certificate says ${cert.tip} positions and closed=${cert.closed}, and you hold ${local.verified_position} in a session that is ${local.state}`);
2297
+ }
2298
+ this.#checkSealLogHistory(check.record, logProof, url);
2299
+ return check.record;
2300
+ }
2301
+ // Catches a log rewritten since this daemon last saw it. It can't catch two readers being shown different logs: only an outside witness can.
2302
+ #checkSealLogHistory(record, logProof, url) {
2303
+ const known = this.#knownSealLogHead(url);
2304
+ if (!known)
2305
+ return;
2306
+ const head = record.log.head.fields;
2307
+ const rewritten = new LocalError("seal_log_rewritten", `this server's seal log no longer contains what it showed you when it had ${known.size} seals. Nothing was stored.`);
2308
+ if (!logProof)
2309
+ throw rewritten;
2310
+ const path = logProof.map((hash) => fromB64(hash, "logProof"));
2311
+ const consistent = known.size <= head.size
2312
+ ? verifyConsistency(known.size, head.size, known.root, head.root, path)
2313
+ : verifyConsistency(head.size, known.size, head.root, known.root, path);
2314
+ if (!consistent)
2315
+ throw rewritten;
2316
+ }
2317
+ async #sealAfterClose(agent, sessionId) {
2318
+ try {
2319
+ return await this.#attemptSeal(agent, sessionId, SEAL_EVERYTHING_HELD);
2320
+ }
2321
+ catch (err) {
2322
+ if (!(err instanceof LocalError))
2323
+ throw err;
2324
+ return { sealed: false, status: "refused", error: err.code, message: err.message };
2325
+ }
2326
+ }
2327
+ async #retrySeals(agent, sessionId) {
2328
+ for (const want of this.#store.sealWants(agent.signer.id, sessionId)) {
2329
+ const label = want.through === SEAL_EVERYTHING_HELD ? "The seal after your close" : `Your seal through position ${want.through}`;
2330
+ try {
2331
+ const result = await this.#attemptSeal(agent, sessionId, want.through);
2332
+ // One still waiting mustn't hold up a different one that could finish.
2333
+ if (!result.sealed)
2334
+ continue;
2335
+ this.#notify(agent, sessionId, `${label} is done. Its id is ${result.seal_id}.`);
2336
+ }
2337
+ catch (err) {
2338
+ if (!(err instanceof LocalError))
2339
+ throw err;
2340
+ this.#notify(agent, sessionId, `${label} wasn't made: ${err.code}, ${err.message}.`);
2341
+ }
2342
+ }
2343
+ }
2344
+ seals(agentHex, sessionHex) {
2345
+ const agent = this.#requireAgent(agentHex);
2346
+ const sessionId = sessionHex === undefined ? undefined : this.#requireSession(agent, sessionHex).session_id;
2347
+ return {
2348
+ seals: this.#store.seals(agent.signer.id, sessionId).map((row) => sealSummary(decodeSealRecord(JSON.parse(row.record)))),
2349
+ waiting: this.#store.sealWants(agent.signer.id, sessionId).map((want) => ({ session_id: toHex(want.session_id), through: want.through === SEAL_EVERYTHING_HELD ? "everything held" : want.through })),
2350
+ };
2351
+ }
2352
+ exportSeal(agentHex, sealHex) {
2353
+ const agent = this.#requireAgent(agentHex);
2354
+ const row = this.#store.seal(agent.signer.id, parseHex(sealHex, 32, "seal id"));
2355
+ if (!row)
2356
+ throw new LocalError("unknown_seal", "this agent holds no seal with that id");
2357
+ return JSON.parse(row.record);
2358
+ }
2359
+ // Reads this agent's own record, so it needs no server and moves no read position.
2360
+ async exportTranscript(agentHex, sessionHex, choice) {
2361
+ const agent = this.#requireAgent(agentHex);
2362
+ const local = this.#requireSession(agent, sessionHex);
2363
+ const unscreened = this.#store.firstUnscreened(agent.signer.id, local.session_id);
2364
+ if (unscreened !== undefined && (choice.all || choice.reveal !== undefined)) {
2365
+ throw new LocalError("not_screened_yet", `Position ${unscreened} is still being screened, so nothing can be revealed yet. Try again once it's done.`);
2366
+ }
2367
+ const built = await buildTranscript({
2368
+ ...choice,
2369
+ session: toHex(local.session_id),
2370
+ sealCommand: `cello seal ${toHex(local.session_id)} --agent ${agent.name}`,
2371
+ entries: this.#store.verifiedEntries(agent.signer.id, local.session_id, local.verified_position).map((row) => ({
2372
+ position: row.position,
2373
+ entry: JSON.parse(row.entry),
2374
+ ack: row.ack ? JSON.parse(row.ack) : null,
2375
+ body: row.withheld === 1 ? null : row.body,
2376
+ })),
2377
+ seals: this.#store.seals(agent.signer.id, local.session_id).map((row) => JSON.parse(row.record)),
2378
+ salt: local.salt,
2379
+ });
2380
+ if (!built.ok)
2381
+ throw new LocalError(built.fault, built.message);
2382
+ return { file: built.file, summary: built.summary };
2383
+ }
2384
+ // ---- What agents and people ask for ----
2385
+ #newAgent(name, seeds, signer, awaitingSignal) {
2386
+ this.#store.insertAgent(signer.id, name, seeds.ed, seeds.pq);
2387
+ if (awaitingSignal)
2388
+ this.#store.setAwaitingSignal(signer.id, true);
2389
+ const agent = { signer, hex: toHex(signer.id), name, registered: false, awaitingSignal, online: false, statuses: new Map() };
2390
+ this.#agents.set(agent.hex, agent);
2391
+ this.governance.writeDefaults(signer.id);
2392
+ return agent;
2393
+ }
2394
+ #describeNew(agent) {
2395
+ const note = agent.online ? {} : { note: `saved, but not online yet: ${agent.problem ?? this.#link.problem ?? "the server didn't take it"}. It registers by itself once the server is reachable.` };
2396
+ return { name: agent.name, agent_id: agent.hex, address: formatAddress(agent.hex, this.#url), registered: agent.registered, online: agent.online, ...note };
2397
+ }
2398
+ #checkNewName(name) {
2399
+ if (validateMoniker(name) === null)
2400
+ throw new LocalError("bad_argument", "an agent name is 1 to 64 letters, digits, underscores or dashes");
2401
+ }
2402
+ async #signalThenOnline(agent, get) {
2403
+ const got = await get();
2404
+ if (!this.wallet.hasEmail(agent.hex)) {
2405
+ const why = got.refused.map((r) => r.message).join("; ") || "it sent none";
2406
+ throw new LocalError("no_email_signal", `The issuer didn't give this agent a verified email signal it could keep: ${why}. Nothing was registered. Run the same command again, and if it says the same, write to support@celloprotocol.com.`);
2407
+ }
2408
+ agent.awaitingSignal = false;
2409
+ this.#store.setAwaitingSignal(agent.signer.id, false);
2410
+ if (this.#server)
2411
+ await this.#bringOnline(agent, this.#server);
2412
+ return got;
2413
+ }
2414
+ // A second agent gets copies from the one already enrolled. With nothing to vouch for it, it registers bare, and a server that requires a signal refuses it by name.
2415
+ async createAgent(name) {
2416
+ this.#checkNewName(name);
2417
+ const existing = [...this.#agents.values()].find((a) => a.name === name);
2418
+ if (existing && !existing.awaitingSignal)
2419
+ throw new LocalError("agent_name_taken", `this machine already has an agent named ${name}`);
2420
+ if (existing)
2421
+ return this.#enrollExisting(existing, undefined);
2422
+ const holder = this.wallet.holderAmong([...this.#agents.keys()]);
2423
+ const seeds = generateIdentitySeeds();
2424
+ const signer = await signerFromSeeds(seeds);
2425
+ const agent = this.#newAgent(name, seeds, signer, holder !== undefined);
2426
+ if (holder)
2427
+ return this.#enrollExisting(agent, undefined);
2428
+ if (this.#server)
2429
+ await this.#bringOnline(agent, this.#server);
2430
+ return this.#describeNew(agent);
2431
+ }
2432
+ async #enrollExisting(agent, code) {
2433
+ const holder = this.wallet.holderAmong([...this.#agents.keys()].filter((hex) => hex !== agent.hex));
2434
+ const got = await this.#signalThenOnline(agent, async () => {
2435
+ if (holder)
2436
+ return this.wallet.copyFromHolder(agent.hex, holder);
2437
+ // A first answer that was lost, or a signal that has lapsed: the issuer may already know this agent, which spends no code.
2438
+ try {
2439
+ const collected = await this.wallet.collect(agent.hex);
2440
+ if (this.wallet.hasEmail(agent.hex))
2441
+ return collected;
2442
+ }
2443
+ catch (err) {
2444
+ if (!(err instanceof LocalError) || err.code !== "unknown_agent")
2445
+ throw err;
2446
+ }
2447
+ if (!code)
2448
+ throw new LocalError("code_required", HOW_TO_GET_A_CODE);
2449
+ return this.wallet.redeem(agent.hex, code);
2450
+ });
2451
+ return { ...this.#describeNew(agent), signals_held: got.held, signals_refused: got.refused };
2452
+ }
2453
+ // What setup does for an agent. Run again, it changes nothing: a code isn't spent on an agent that already has its signal.
2454
+ async enrollAgent(name, code) {
2455
+ const agents = [...this.#agents.values()];
2456
+ const chosen = name === undefined ? agents[0] : agents.find((a) => a.name === name);
2457
+ if (chosen && this.wallet.hasEmail(chosen.hex)) {
2458
+ if (!chosen.online && this.#server)
2459
+ await this.#bringOnline(chosen, this.#server);
2460
+ return { ...this.#describeNew(chosen), already_set_up: true };
2461
+ }
2462
+ if (chosen)
2463
+ return this.#enrollExisting(chosen, code);
2464
+ const newName = name ?? DEFAULT_AGENT_NAME;
2465
+ this.#checkNewName(newName);
2466
+ const holder = this.wallet.holderAmong(agents.map((a) => a.hex));
2467
+ if (!holder && !code)
2468
+ throw new LocalError("code_required", HOW_TO_GET_A_CODE);
2469
+ const seeds = generateIdentitySeeds();
2470
+ const signer = await signerFromSeeds(seeds);
2471
+ return this.#enrollExisting(this.#newAgent(newName, seeds, signer, true), code);
2472
+ }
2473
+ // What channels.ts needs from here. It shares an agent's keys and the server link, and nothing about any conversation.
2474
+ channelHost() {
2475
+ return {
2476
+ signer: (agentHex) => this.#requireAgent(agentHex).signer,
2477
+ agents: () => [...this.#agents.keys()],
2478
+ online: (agentHex) => this.#agents.get(agentHex)?.online === true,
2479
+ call: (method, params) => this.#link.call(method, params),
2480
+ callLong: (agentHex, method, params) => this.#longCall(this.#requireAgent(agentHex), this.#home, method, params),
2481
+ serverIdentity: () => this.#serverIdentity(),
2482
+ ring: (agentHex, bell) => this.#events.ring(agentHex, bell),
2483
+ // Channels share the one screening queue, so a channel takes turns with conversations by sender.
2484
+ screen: (agentHex, scope, position, senderHex, text) => new Promise((resolve) => {
2485
+ this.#nextChannelJob -= 1;
2486
+ // The worker reads the shape a message body has. Anything else, it takes as text nobody can read and passes unscanned.
2487
+ const bytes = bodyBytes({ n: new Uint8Array(0), text, signal: null, est_minutes: null });
2488
+ this.#screening.add({ entryId: this.#nextChannelJob, agentHex, sessionHex: scope, position, senderHex, bytes: bytes.length, arrived: Date.now(), channelText: { bytes, done: resolve } });
2489
+ }),
2490
+ screenOutbound: async (agentHex, text, params, retry) => {
2491
+ const screened = await this.#screenOutbound(this.#requireAgent(agentHex), text, params, retry);
2492
+ return screened;
2493
+ },
2494
+ };
2495
+ }
2496
+ // Everything else keys on agent_id, so only the name and a self-offered name equal to it change. Callers holding it hold its id.
2497
+ renameAgent(agentHex, name) {
2498
+ const agent = this.#requireAgent(agentHex);
2499
+ this.#checkNewName(name);
2500
+ const taken = [...this.#agents.values()].find((a) => a.name === name && a.hex !== agent.hex);
2501
+ if (taken)
2502
+ throw new LocalError("agent_name_taken", `this machine already has an agent named ${name}`);
2503
+ const previous = agent.name;
2504
+ this.#store.transaction(() => {
2505
+ this.#store.renameAgent(agent.signer.id, name);
2506
+ if (this.governance.reach.offeredName(agent.signer.id) === previous)
2507
+ this.governance.reach.setOfferedName(agent.signer.id, name);
2508
+ });
2509
+ agent.name = name;
2510
+ return { agent_id: agent.hex, name, previous_name: previous, offers_name: this.governance.offeredName(agent.signer.id, name) || null };
2511
+ }
2512
+ resolveAgent(nameOrId) {
2513
+ const byId = this.#agents.get(nameOrId);
2514
+ if (byId)
2515
+ return byId.hex;
2516
+ for (const agent of this.#agents.values())
2517
+ if (agent.name === nameOrId)
2518
+ return agent.hex;
2519
+ throw new LocalError("unknown_agent", noAgentGuidance(nameOrId));
2520
+ }
2521
+ agentName(agentHex) {
2522
+ return this.#requireAgent(agentHex).name;
2523
+ }
2524
+ async initiate(agentHex, target, params = {}) {
2525
+ const agent = this.#requireAgent(agentHex);
2526
+ // First, so a stopped agent is never offered the person's way past a block.
2527
+ this.#refuseIfStopped(agent, this.#url);
2528
+ // You blocked them, so calling them is a stop sign. A person can drive through it, once.
2529
+ const dialled = /^[0-9a-fA-F]{64}/.exec(target)?.[0];
2530
+ if (dialled && this.governance.contacts.tierOf(agent.signer.id, parseHex(dialled, 32, "target")) === TIER.BLOCKED) {
2531
+ requirePerson(params, `${agent.name} has blocked this agent, and this would call it anyway.`, `cello initiate-session ${target} --agent ${agent.hex}`);
2532
+ }
2533
+ let address;
2534
+ try {
2535
+ address = parseAddress(target);
2536
+ }
2537
+ catch (err) {
2538
+ throw new LocalError(err instanceof PlainTextServer ? err.code : "bad_argument", err instanceof Error ? err.message : String(err));
2539
+ }
2540
+ const targetId = parseHex(address.id, 32, "target");
2541
+ if (equalBytes(targetId, agent.signer.id))
2542
+ throw new LocalError("bad_argument", "an agent can't start a session with itself");
2543
+ const warning = this.#strangerWarning(agent, targetId);
2544
+ const route = await this.#reach(agent, address.server);
2545
+ try {
2546
+ const started = await this.#initiateOn(agent, route, targetId, typeof params["signals"] === "string" ? params["signals"] : undefined);
2547
+ return warning ? { ...started, warning } : started;
2548
+ }
2549
+ finally {
2550
+ this.#doneOpening(route);
2551
+ }
2552
+ }
2553
+ // A call always goes ahead. One to an agent outside your contacts carries a warning for the agent to pass on to its owner.
2554
+ #strangerWarning(agent, targetId) {
2555
+ if (this.governance.contacts.tierOf(agent.signer.id, targetId) >= TIER.KNOWN)
2556
+ return undefined;
2557
+ return `Unknown agent: not in your contacts. Be careful what you share. Know them? Add them to your contacts: cello contact-add ${toHex(targetId)} --agent ${agent.hex}`;
2558
+ }
2559
+ // The callee's server hosts, and each side connects to it directly. No server relays for another.
2560
+ async #initiateOn(agent, route, targetId, signalsSpec) {
2561
+ const agentHex = agent.hex;
2562
+ // The set is chosen first, so a bad choice stops here, before anything is looked up or sent.
2563
+ const presented = this.wallet.presentable(agentHex, signalsSpec);
2564
+ if (presented.files.length > MAX_PRESENTED_SIGNALS)
2565
+ throw new LocalError("too_many_signals", `At most ${MAX_PRESENTED_SIGNALS} signals go with a call, and this set has ${presented.files.length}. Turn some off with cello signals disable <hash>, or choose with --signals <hash>,<hash>, or send none with --signals none.`);
2566
+ const lookup = await this.#call(() => route.link.call("lookup", { agent: toB64(agent.signer.id), target: toB64(targetId) }));
2567
+ const identity = identityCodec.decode(lookup.identity, "identity");
2568
+ // The id you typed is the check: a server can't substitute other keys under it.
2569
+ if (!equalBytes(identityId(identity), targetId))
2570
+ throw new LocalError("wrong_identity", "the server returned keys that don't match the id you asked for");
2571
+ // Signals go sealed to the key the callee published. Without a good one nothing is sent, and the caller is told so rather than left to think they went.
2572
+ let sealedSignals = { signalsCiphertext: new Uint8Array(0), sealedSignals: new Uint8Array(0) };
2573
+ let signalsNote;
2574
+ if (presented.files.length > 0) {
2575
+ let key = null;
2576
+ if (lookup.encryptionKey === undefined || lookup.encryptionKey === null)
2577
+ signalsNote = "That agent hasn't published an encryption key, so your signals weren't sent with this call.";
2578
+ else {
2579
+ try {
2580
+ key = await checkEncryptionKey(lookup.encryptionKey, identity, targetId);
2581
+ }
2582
+ catch (err) {
2583
+ logEvent("encryption_key.bad", { agent: agentHex, message: err instanceof Error ? err.message : String(err) });
2584
+ signalsNote = "The encryption key that agent's server gave didn't check out, so your signals weren't sent with this call.";
2585
+ }
2586
+ }
2587
+ if (key) {
2588
+ try {
2589
+ sealedSignals = await sealToKey(key.mlKemPublic, presented.files);
2590
+ }
2591
+ catch (err) {
2592
+ if (err instanceof PresentedTooMany)
2593
+ throw new LocalError("signals_too_big", `${err.message}. Choose fewer with --signals <hash>,<hash>, or send none with --signals none.`);
2594
+ throw err;
2595
+ }
2596
+ }
2597
+ }
2598
+ const sessionId = new Uint8Array(randomBytes(16));
2599
+ const sessionHex = toHex(sessionId);
2600
+ const own = await generateSessionEphemeral();
2601
+ const fields = {
2602
+ serverId: this.#serverId(route.url),
2603
+ sessionId,
2604
+ callerId: agent.signer.id,
2605
+ calleeId: targetId,
2606
+ x25519Public: own.publicKey,
2607
+ mlKemPublic: own.mlKemPublic,
2608
+ expiresAt: Date.now() + this.#settings.offer_lifetime_minutes * 60_000,
2609
+ ...sealedSignals,
2610
+ };
2611
+ const signature = await agent.signer.sign("cello-session-offer", offerBytes(fields));
2612
+ const offer = signedOffer.encode({ fields, signature });
2613
+ const activated = new Promise((resolve) => this.#activation.set(agent.hex + sessionHex, resolve));
2614
+ await this.#lane(agentHex, sessionHex, async () => {
2615
+ this.#store.insertSession({
2616
+ agent_id: agent.signer.id,
2617
+ session_id: sessionId,
2618
+ role: "caller",
2619
+ counterparty_id: targetId,
2620
+ counterparty_name: "",
2621
+ counterparty_keys: JSON.stringify(lookup.identity),
2622
+ state: "offered",
2623
+ offer: JSON.stringify(offer),
2624
+ x25519_secret: own.secretKey,
2625
+ mlkem_seed: own.mlKemSeed,
2626
+ server_url: route.home ? null : route.url,
2627
+ });
2628
+ this.#presented.put(agent.signer.id, sessionId, "caller", sealedSignals.sealedSignals.length > 0 ? presented.files : []);
2629
+ await this.#call(() => route.link.call("session.offer", { agent: toB64(agent.signer.id), offer }));
2630
+ });
2631
+ const signalsInfo = { signals_sent: sealedSignals.sealedSignals.length > 0 ? presented.files.length : 0, ...(signalsNote ? { signals_note: signalsNote } : {}) };
2632
+ this.governance.engaged(agent.signer.id, targetId, "initiated");
2633
+ let timer;
2634
+ await Promise.race([activated, new Promise((resolve) => { timer = setTimeout(resolve, INITIATE_WAIT_MS); })]);
2635
+ clearTimeout(timer);
2636
+ this.#activation.delete(agent.hex + sessionHex);
2637
+ const state = this.#store.session(agent.signer.id, sessionId).state;
2638
+ const refused = this.#refusals.get(agent.hex + sessionHex);
2639
+ if (refused) {
2640
+ this.#refusals.delete(agent.hex + sessionHex);
2641
+ return { session_id: sessionHex, state: "refused", message: refused, ...signalsInfo };
2642
+ }
2643
+ if (state === "active")
2644
+ return { session_id: sessionHex, state, ...signalsInfo };
2645
+ return { session_id: sessionHex, state: "waiting", ...signalsInfo, message: `Nothing has answered yet, so that agent's daemon may be offline. An offline daemon can't send an away greeting, so silence here says nothing about whether anyone will read this. The call stands until ${new Date(fields.expiresAt).toISOString()}, and it connects by itself if that daemon comes back.` };
2646
+ }
2647
+ // One call about public signals, as the agent, to its own server or to the one an address names. A stopped agent does nothing.
2648
+ async #publicSignalCall(agentHex, serverUrl, method, params) {
2649
+ const agent = this.#requireAgent(agentHex);
2650
+ this.#refuseIfStopped(agent, serverUrl ?? this.#url);
2651
+ const route = await this.#reach(agent, serverUrl);
2652
+ try {
2653
+ return await this.#call(() => route.link.call(method, params(agent)));
2654
+ }
2655
+ finally {
2656
+ this.#doneOpening(route);
2657
+ }
2658
+ }
2659
+ async #call(work) {
2660
+ try {
2661
+ return await work();
2662
+ }
2663
+ catch (err) {
2664
+ if (err instanceof ServerRefused)
2665
+ throw new LocalError(err.code, err.message);
2666
+ if (err instanceof ServerUnreachable)
2667
+ throw new LocalError("server_unreachable", err.message);
2668
+ throw err;
2669
+ }
2670
+ }
2671
+ // Reading changes nothing. Only commit() moves the position, and the daemon calls it after the reply is written,
2672
+ // so a caller that hangs up first leaves the messages unread. An operator's look at a record never moves it either.
2673
+ receive(agentHex, sessionHex) {
2674
+ const agent = this.#requireAgent(agentHex);
2675
+ this.#refuseIfStopped(agent, this.#url);
2676
+ if (sessionHex)
2677
+ this.#refuseIfStopped(agent, this.#urlOf(this.#requireSession(agent, sessionHex)));
2678
+ // Stopped by one other server only: what's held from that server waits, and the rest reads as usual.
2679
+ const sessions = (sessionHex ? [this.#requireSession(agent, sessionHex)] : this.#store.sessionsOf(agent.signer.id)).filter((local) => !this.#stopAt(agent, this.#urlOf(local)));
2680
+ const messages = [];
2681
+ const reads = [];
2682
+ const screening = [];
2683
+ const policies = [];
2684
+ const guidance = [];
2685
+ let room = MAX_REPLY_BYTES;
2686
+ let more = false;
2687
+ for (const local of sessions) {
2688
+ if (room <= 0) {
2689
+ more ||= this.#store.deliverableCount(agent.signer.id, local.session_id, local.read_position) > 0;
2690
+ continue;
2691
+ }
2692
+ const page = this.#store.unreadPage(agent.signer.id, local.session_id, local.read_position, room);
2693
+ const unread = page.rows;
2694
+ more ||= page.more;
2695
+ // The newest signal says whose move it is. A close after it only leaves wrap standing: they've gone, so nobody expects a reply.
2696
+ let lastSignal = null;
2697
+ let blocked = 0;
2698
+ const lag = this.#replyLag(agent, local, unread);
2699
+ for (const row of unread) {
2700
+ room -= row.body.length;
2701
+ const closing = signedEntry.decode(JSON.parse(row.entry)).fields.kind === EntryKind.close;
2702
+ const shown = shownMessage(row, closing);
2703
+ lastSignal = closing ? (lastSignal === "wrap" ? "wrap" : null) : shown["signal"] ?? null;
2704
+ if (shown["blocked"] === true)
2705
+ blocked += 1;
2706
+ messages.push({
2707
+ session_id: toHex(local.session_id),
2708
+ from: this.#who(agent, local),
2709
+ from_id: toHex(local.counterparty_id),
2710
+ position: row.position,
2711
+ ...shown,
2712
+ });
2713
+ }
2714
+ let hasPolicy = false;
2715
+ if (unread.length > 0) {
2716
+ reads.push({ sessionId: local.session_id, through: unread.at(-1).position });
2717
+ const conduct = this.governance.conductFor(agent.signer.id, toHex(local.session_id), toHex(local.counterparty_id), this.governance.contacts.tierOf(agent.signer.id, local.counterparty_id), unread.length);
2718
+ if (Object.keys(conduct).length > 0) {
2719
+ policies.push({ session_id: toHex(local.session_id), ...conduct });
2720
+ hasPolicy = true;
2721
+ }
2722
+ }
2723
+ const held = this.#screening.waiting(agent.hex, toHex(local.session_id));
2724
+ if (held)
2725
+ screening.push({ session_id: toHex(local.session_id), ...held });
2726
+ if (unread.length > 0) {
2727
+ for (const text of sessionGuidance({ lastSignal, laterToCome: page.more || Boolean(held), finished: local.state !== "active" || local.own_closed === 1, hasPolicy, blocked, lag })) {
2728
+ guidance.push({ session_id: toHex(local.session_id), text });
2729
+ }
2730
+ }
2731
+ }
2732
+ const notices = this.#store.notices(agent.signer.id);
2733
+ const wantedSession = sessionHex ? sessions[0]?.session_id : undefined;
2734
+ const greetings = this.#away.unread(agent.signer.id).filter((row) => !wantedSession || equalBytes(row.session_id, wantedSession));
2735
+ return {
2736
+ result: { messages, ...(greetings.length > 0 ? { greetings: greetings.map((row) => this.#shownGreeting(agent, row)) } : {}), notices: notices.map((n) => ({ session_id: n.session_id ? toHex(n.session_id) : null, text: n.text })), ...(screening.length > 0 ? { still_screening: screening } : {}), ...(policies.length > 0 ? { policies } : {}), ...(guidance.length > 0 ? { guidance } : {}), ...(more ? { more: true } : {}) },
2737
+ commit: () => {
2738
+ this.#store.transaction(() => {
2739
+ for (const read of reads) {
2740
+ // Two reads can overlap, so a position only ever moves forward.
2741
+ const current = this.#store.session(agent.signer.id, read.sessionId);
2742
+ if (read.through > current.read_position)
2743
+ this.#store.updateSession(agent.signer.id, read.sessionId, { read_position: read.through });
2744
+ }
2745
+ for (const row of greetings)
2746
+ this.#away.markRead(agent.signer.id, row.session_id);
2747
+ if (notices.length > 0)
2748
+ this.#store.clearNotices(agent.signer.id, notices.at(-1).id);
2749
+ });
2750
+ },
2751
+ };
2752
+ }
2753
+ // Their newest replies, counted back from the end, that were signed without having seen a message of yours.
2754
+ #replyLag(agent, local, rows) {
2755
+ let replies = 0;
2756
+ let unseenPosition;
2757
+ for (const row of [...rows].reverse()) {
2758
+ const fields = signedEntry.decode(JSON.parse(row.entry)).fields;
2759
+ if (fields.kind === EntryKind.close)
2760
+ continue;
2761
+ const unseen = this.#store.firstOwnBetween(agent.signer.id, local.session_id, fields.readPosition, row.position);
2762
+ if (unseen === undefined)
2763
+ break;
2764
+ replies += 1;
2765
+ unseenPosition ??= unseen;
2766
+ }
2767
+ return unseenPosition === undefined ? undefined : { replies, unseenPosition };
2768
+ }
2769
+ // These four only read. None moves a read position, so looking never counts as reading.
2770
+ agents() {
2771
+ return {
2772
+ agents: [...this.#agents.values()].map((agent) => ({ name: agent.name, agent_id: agent.hex, address: formatAddress(agent.hex, this.#url), registered: agent.registered, online: agent.online, status: this.#stopAt(agent, this.#url)?.status ?? "active", unread: this.unreadCount(agent.hex) })),
2773
+ };
2774
+ }
2775
+ sessions(agentHex, includeClosed) {
2776
+ const agent = this.#requireAgent(agentHex);
2777
+ const rows = this.#store.sessionsOf(agent.signer.id).filter((s) => includeClosed || s.state !== "closed");
2778
+ return {
2779
+ sessions: rows.map((s) => ({
2780
+ session_id: toHex(s.session_id),
2781
+ with: this.#who(agent, s),
2782
+ with_id: toHex(s.counterparty_id),
2783
+ tier: tierName(this.governance.contacts.tierOf(agent.signer.id, s.counterparty_id)),
2784
+ ...(this.#agents.has(toHex(s.counterparty_id)) ? { same_daemon: true } : {}),
2785
+ bytes_received: s.bytes_received,
2786
+ byte_limit: this.governance.reach.limitsFor(agent.signer.id, this.governance.contacts.tierOf(agent.signer.id, s.counterparty_id)).max_bytes,
2787
+ ...(s.role === "callee" ? this.governance.admissionFor(agent.signer.id, toHex(s.counterparty_id), this.governance.contacts.tierOf(agent.signer.id, s.counterparty_id)) : {}),
2788
+ ...(s.role === "callee" && this.#away.visit(agent.signer.id, s.session_id) ? { away_visit: this.#away.visit(agent.signer.id, s.session_id)?.state } : {}),
2789
+ hosted_on: this.#urlOf(s),
2790
+ state: s.state,
2791
+ position: s.verified_position,
2792
+ unread: this.#store.unreadCount(agent.signer.id, s.session_id, s.read_position),
2793
+ own_closed: s.own_closed === 1,
2794
+ peer_closed: s.peer_closed === 1,
2795
+ fault: s.fault,
2796
+ stopped: this.#store.isStopped(agent.signer.id, s.session_id),
2797
+ standbys: this.#standbyView(agent, s),
2798
+ screening: this.#sessionScreening(agent, s),
2799
+ })),
2800
+ };
2801
+ }
2802
+ // Who has written and how much, with none of the text.
2803
+ inbox(agentHex) {
2804
+ const agent = this.#requireAgent(agentHex);
2805
+ const waiting = this.#store.sessionsOf(agent.signer.id).flatMap((s) => {
2806
+ const unread = this.#store.unreadCount(agent.signer.id, s.session_id, s.read_position);
2807
+ const held = this.#screening.waiting(agent.hex, toHex(s.session_id));
2808
+ return unread > 0 ? [{ session_id: toHex(s.session_id), from: this.#who(agent, s), from_id: toHex(s.counterparty_id), unread, ready: this.#store.deliverableCount(agent.signer.id, s.session_id, s.read_position), ...(held ? { still_screening: held } : {}) }] : [];
2809
+ });
2810
+ return { waiting, notices: this.#store.notices(agent.signer.id).length, refused_callers: this.governance.knocks(agent.signer.id, agent.hex) };
2811
+ }
2812
+ // Everything this agent holds of a conversation, its own messages included, in the order the server set.
2813
+ transcript(agentHex, sessionHex, after = 0) {
2814
+ const agent = this.#requireAgent(agentHex);
2815
+ const local = this.#requireSession(agent, sessionHex);
2816
+ const page = this.#store.recordPage(agent.signer.id, local.session_id, after, local.verified_position, MAX_REPLY_BYTES);
2817
+ // An agent can call this, so it's a way of reading: nothing unscreened or blocked comes through it either.
2818
+ const entries = page.rows.map((row) => {
2819
+ const closing = signedEntry.decode(JSON.parse(row.entry)).fields.kind === EntryKind.close;
2820
+ return {
2821
+ position: row.position,
2822
+ from: row.own === 1 ? agent.name : this.#who(agent, local),
2823
+ from_id: toHex(row.own === 1 ? agent.signer.id : local.counterparty_id),
2824
+ own: row.own === 1,
2825
+ ...shownMessage(row, closing),
2826
+ };
2827
+ });
2828
+ const refused = entries.filter((entry) => entry.blocked === true).length;
2829
+ return { session_id: toHex(local.session_id), with: this.#who(agent, local), with_id: toHex(local.counterparty_id), state: local.state, read_position: local.read_position, entries, ...(refused > 0 ? { quarantined_count: refused, quarantined_guidance: refusedGuidance(refused) } : {}), ...(page.more ? { more: true } : {}) };
2830
+ }
2831
+ // What can be read right now. A message still being screened isn't in it, or a caller would be told to read and find nothing.
2832
+ unreadCount(agentHex) {
2833
+ const agent = this.#requireAgent(agentHex);
2834
+ const messages = this.#store.sessionsOf(agent.signer.id).reduce((sum, s) => sum + this.#store.deliverableCount(agent.signer.id, s.session_id, s.read_position), 0);
2835
+ return messages + this.#store.notices(agent.signer.id).length + this.#away.unread(agent.signer.id).length;
2836
+ }
2837
+ // Checks this agent's own record, using only public keys.
2838
+ async verifySession(agentHex, sessionHex) {
2839
+ const agent = this.#requireAgent(agentHex);
2840
+ const local = this.#requireSession(agent, sessionHex);
2841
+ const items = this.#store.signedRecord(agent.signer.id, local.session_id, local.verified_position).map((row) => {
2842
+ const entry = signedEntry.decode(JSON.parse(row.entry));
2843
+ const ack = signedAck.decode(JSON.parse(row.ack));
2844
+ return witnessed(entry, ack);
2845
+ });
2846
+ const report = await verifyTranscript({ sessionId: local.session_id, server: this.#serverIdentity(this.#urlOf(local)), participants: [agent.signer.publicIdentity, this.#counterpartyKeys(local)] }, items);
2847
+ return { ok: report.ok, position: report.position, root: toHex(report.root), fault: report.fault ?? null, fault_at: report.faultAt ?? null };
2848
+ }
2849
+ status() {
2850
+ return {
2851
+ server: this.#url,
2852
+ connected: this.#link.ready,
2853
+ problem: this.#link.problem,
2854
+ screening: this.screeningFacts(),
2855
+ visiting: [...this.#visiting.values()].map((route) => ({ server: route.url, connected: route.link.ready, problem: route.link.problem, agents: [...route.online].length })),
2856
+ agents: [...this.#agents.values()].map((agent) => ({
2857
+ name: agent.name,
2858
+ agent_id: agent.hex,
2859
+ address: formatAddress(agent.hex, this.#url),
2860
+ registered: agent.registered,
2861
+ online: agent.online,
2862
+ // Callers seal their signals to this key, so until the server has it, calls to this agent carry none.
2863
+ encryption_key: this.#keys.latest(agent.signer.id)?.published === 1 ? "published" : "not published yet",
2864
+ status: this.#stopAt(agent, this.#url)?.status ?? "active",
2865
+ unread: this.unreadCount(agent.hex),
2866
+ sessions: this.#store.sessionsOf(agent.signer.id).map((s) => ({
2867
+ session_id: toHex(s.session_id),
2868
+ with: this.#who(agent, s),
2869
+ with_id: toHex(s.counterparty_id),
2870
+ state: s.state,
2871
+ position: s.verified_position,
2872
+ read_position: s.read_position,
2873
+ own_closed: s.own_closed === 1,
2874
+ peer_closed: s.peer_closed === 1,
2875
+ fault: s.fault,
2876
+ standbys: this.#standbyView(agent, s),
2877
+ screening: this.#sessionScreening(agent, s),
2878
+ })),
2879
+ })),
2880
+ };
2881
+ }
2882
+ }