@ours.network/tg-connector 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +98 -0
  2. package/README.md +318 -0
  3. package/dist/cli.js +726 -0
  4. package/dist/connector.js +1578 -0
  5. package/dist/mufl_code/2DA1D5F860E42C605D92F1E24E2466C70EFDDBF057BBCBA52F0ECC639EFCA387.muflo +0 -0
  6. package/dist/mufl_code/actor.mu +1757 -0
  7. package/dist/mufl_code/config.mufl +27 -0
  8. package/dist/mufl_code/core/CLUSTER_API.md +640 -0
  9. package/dist/mufl_code/core/CLUSTER_CONTRACT.md +121 -0
  10. package/dist/mufl_code/core/CLUSTER_INTRODUCTION_PLAN.md +200 -0
  11. package/dist/mufl_code/core/CONFIGURATION_DESIGN.md +35 -0
  12. package/dist/mufl_code/core/CONFIGURATION_PLAN.md +394 -0
  13. package/dist/mufl_code/core/DEVELOPMENT.md +168 -0
  14. package/dist/mufl_code/core/EPHEMERAL_INVITE_PLAN.md +465 -0
  15. package/dist/mufl_code/core/GROUP_CHAT_DESIGN.md +520 -0
  16. package/dist/mufl_code/core/LICENSE +98 -0
  17. package/dist/mufl_code/core/README.md +76 -0
  18. package/dist/mufl_code/core/a2a_capabilities.mm +350 -0
  19. package/dist/mufl_code/core/a2a_cluster.mm +601 -0
  20. package/dist/mufl_code/core/a2a_control.mm +89 -0
  21. package/dist/mufl_code/core/a2a_messaging.mm +2103 -0
  22. package/dist/mufl_code/core/a2a_monitoring.mm +94 -0
  23. package/dist/mufl_code/core/a2a_protocol.mm +231 -0
  24. package/dist/mufl_code/core/config.mufl +26 -0
  25. package/dist/mufl_code/core/release-notes/2.0.md +268 -0
  26. package/dist/mufl_code/core/release-notes/2.1.md +92 -0
  27. package/dist/mufl_code/core/release-notes/2.2.md +94 -0
  28. package/dist/mufl_code/core/release-notes/3.0.md +162 -0
  29. package/dist/mufl_code/core/release-notes/3.1.md +43 -0
  30. package/dist/mufl_code/core/release-notes/README.md +32 -0
  31. package/dist/mufl_code/core/tests/README.md +66 -0
  32. package/dist/mufl_code/core/tests/run.sh +67 -0
  33. package/dist/mufl_code/core/tests/test.mjs +467 -0
  34. package/dist/mufl_code/core/tests/test_actor.mu +287 -0
  35. package/dist/mufl_code/core/version.mm +24 -0
  36. package/dist/mufl_code/protocol_container.mm +18 -0
  37. package/package.json +46 -0
@@ -0,0 +1,1757 @@
1
+ // ours messenger packet.
2
+ //
3
+ // One ADAPT node == one of these packets. Two nodes talk directly, peer to
4
+ // peer, through a relay broker (no central server). Messages are end-to-end
5
+ // encrypted; the key exchange is handled for us by the stdlib `encrypted_channel`
6
+ // library — we only ever address peers by their container id.
7
+ //
8
+ // The shared transaction logic lives in the ours-mufl-core repo (checked
9
+ // out as the core/ subfolder of this directory): `a2a_protocol` (wire shapes +
10
+ // verification), `a2a_messaging` (contact + message wire path, addressed
11
+ // ::a2a_messaging::<name> by the host), and `version`. They are shared with
12
+ // the web messenger — change them there, bump core_version, and recompile
13
+ // every consumer.
14
+ //
15
+ // This packet keeps only what is agent-specific:
16
+ // - the inbox message store with its lifecycle (unread -> processed ->
17
+ // ready_to_delete -> deleted; see get_messages / gc / defer_messages)
18
+ // - the local contact book + identity hierarchy transactions (host-fired)
19
+ // - export_state / import_state wrappers composing the core helpers with
20
+ // the app-side fields (including the legacy-blob migrations)
21
+ // - ::actor:: compat shims for the network-visible inbound transactions
22
+ // (accept_contact, receive_message) — pre-migration peers send to these
23
+ // names, and the core keeps SENDING to them too (Option A: zero network
24
+ // break; drop both only when no old clients remain)
25
+ //
26
+ // Storage is wired into the core via a2a_messaging::init hooks (see the
27
+ // hidden block): on_message_received deposits into the inbox (or the
28
+ // pending-introduction queue for unknown senders); send/remove hooks are
29
+ // agent no-ops.
30
+ //
31
+ // User transactions (each backs one MCP tool, except gc which the host fires):
32
+ // ::a2a_messaging::set_my_name — set the display name peers see for me
33
+ // ::a2a_messaging::set_my_bio — set my profile bio (free-text, self-asserted)
34
+ // ::a2a_messaging::generate_invite — make an invite blob for a named peer
35
+ // ::a2a_messaging::add_contact — join via an invite blob, reply to the inviter
36
+ // ::a2a_messaging::send_message — send an e2e-encrypted message to a contact
37
+ // ::a2a_messaging::remove_contact — forget a contact
38
+ // ::a2a_messaging::list_contacts — (readonly) my contacts
39
+ // ::a2a_messaging::list_contact_roots — (readonly) verified root linkage per contact
40
+ // ::a2a_messaging::get_version — (readonly) shared-core version
41
+ // list_incoming_messages — (readonly) my inbox, with per-message id + status
42
+ // get_messages — return unread messages + mark them processed (sole body egress)
43
+ // defer_messages — flip processed/ready_to_delete messages back to unread
44
+ // gc — two-generation GC of handled messages (host-fired, not a tool)
45
+ // ::a2a_messaging::flush_deferred — (host-fired) replay deferred queues once conditions clear
46
+ // restore_degraded_contacts — (host-fired) (re)issue restore requests for every degraded contact
47
+ // list_degraded_contacts — (readonly) contacts currently degraded (channel needs restore)
48
+ // list_deferred_queues — (readonly) per-contact deferred-message queue sizes
49
+ //
50
+ // Identity hierarchy (host-fired transactions; see IDENTITY-HIERARCHY-DESIGN.md):
51
+ // sign_delegation — root-only in practice: sign a delegation cert for a role
52
+ // export_root_profile — root-only in practice: my self-signed root profile blob
53
+ // set_delegation — role: store my verified delegation cert + root material
54
+ // describe_identity — (readonly) name/bio/hierarchy position
55
+ // connect_sibling — register an intra-root peer + send sibling_introduce
56
+ //
57
+ // Local contact book (host-fired transactions; see the design notes above
58
+ // local_introduce below):
59
+ // export_address_document — (readonly) my signed address document as a blob
60
+ // pin_registrar — pin the host registrar's signing keys (pin-once)
61
+ // set_local_policy — toggle auto-accept of local introductions
62
+ // mint_introduction — registrar-only in practice: sign an introduction credential
63
+ // sign_book_entry — registrar-only in practice: sign a contact-book entry
64
+ // connect_local — register a book contact + send local_introduce (+ first message)
65
+ // approve_introduction — accept a pending local introduction (flushes its queue)
66
+ // reject_introduction — drop a pending local introduction
67
+ // list_pending_introductions — (readonly) pending introductions (names + queue sizes)
68
+ //
69
+ // Monitoring + control plane (host-fired unless noted; see
70
+ // MONITORING-AND-SHARED-LIBRARY-DESIGN.md):
71
+ // get_monitoring_status — (readonly) enabled flag / proxy binding / queue sizes
72
+ // sign_monitoring_auth — root-only: sign an enable/disable auth for a role
73
+ // set_monitoring — role: verify the root-signed auth, set the flag
74
+ // get_monitoring_copies — root: drain queued copies for proxy forwarding
75
+ // get_control_requests — root: drain queued proxy control requests
76
+ // set_proxy_pending — root: store the host-generated 6-digit code
77
+ // verify_proxy_code — root: check a bind attempt (atomic attempts/expiry)
78
+ // clear_monitoring_proxy — root: drop the proxy binding
79
+ // ::a2a_control::send_control — send an opaque control payload to a contact
80
+ //
81
+ // External transactions (inbound, not exposed as tools):
82
+ // accept_contact — inviter learns the joiner's identity + name (core shim)
83
+ // receive_message — store a decrypted inbound message (core shim)
84
+ // receive_monitoring_copy — a monitored role of mine reports a message copy
85
+ // ::a2a_control::control_message — control payload from a contact (queued for the daemon)
86
+ // local_introduce — same-host peer connects via the local contact book
87
+ // sibling_introduce — intra-root peer connects, authorized by its delegation cert
88
+ // ::a2a_messaging::request_contact_restore / submit_restore_response / complete_restore
89
+ // — contact-restore handshake (signed re-key between known contacts)
90
+
91
+ application actor loads libraries
92
+ identity_proof_document,
93
+ attestation_document,
94
+ native_attestation_document,
95
+ transaction_message_decoder,
96
+ address_document,
97
+ address_document_types,
98
+ key_utils,
99
+ key_storage,
100
+ continuation,
101
+ encrypted_channel,
102
+ current_transaction_info,
103
+ a2a_protocol,
104
+ a2a_messaging,
105
+ a2a_control,
106
+ a2a_capabilities,
107
+ protocol_container,
108
+ registration_proof,
109
+ version
110
+ uses transactions
111
+ {
112
+ hidden
113
+ {
114
+ // A received message carries a stable per-packet id and a lifecycle status:
115
+ // "unread" (just arrived) -> "processed" (handed to the agent via
116
+ // get_messages) -> "ready_to_delete" (first gc tick) -> deleted (next gc
117
+ // tick). defer_messages flips "processed"/"ready_to_delete" back to "unread"
118
+ // so another session can pick it up — restorable from either generation,
119
+ // which is what makes the two-generation gc window race-free.
120
+ // $wire_id is the sender-stamped, cross-side handle ("" when the sender
121
+ // predates wire ids, or for introduction first-messages); $reply_to is
122
+ // the optional pointer at the message this one replies to (NIL = not a
123
+ // reply). Both are surfaced by get_messages so an agent can reference a
124
+ // message in a reply and recognize an incoming reply pointer.
125
+ metadef message_t: ($msg_id -> int, $sender_id -> global_id, $sender_name -> str, $text -> str, $date -> time, $status -> str, $wire_id -> str, $reply_to -> a2a_protocol::reply_ref_t+).
126
+ // The pre-lifecycle inbox shape (no per-message id/status). import_state
127
+ // migrates blobs in this shape forward — see below.
128
+ metadef legacy_message_t: ($sender_id -> global_id, $sender_name -> str, $text -> str, $date -> time).
129
+
130
+ // A received FILE, mirroring message_t's lifecycle so the receive path gets the
131
+ // same at-least-once / defer / two-generation-gc guarantees as messages. Unlike
132
+ // the QA reference (test_actor.mu) this store keeps the bytes ($data) — the
133
+ // connector must re-deliver them to Telegram. $wire_id is the sender-stamped
134
+ // cross-side handle (shared with messages); $reply_to is NIL unless a reply.
135
+ metadef file_t: (
136
+ $file_id -> int,
137
+ $sender_id -> global_id,
138
+ $sender_name -> str,
139
+ $filename -> str,
140
+ $mime -> str,
141
+ $data -> bin,
142
+ $date -> time,
143
+ $status -> str,
144
+ $wire_id -> str,
145
+ $reply_to -> a2a_protocol::reply_ref_t+
146
+ ).
147
+
148
+ // A not-yet-approved local introduction, with its bounded message queue.
149
+ // (The local-book WIRE shapes — intro_t, signed_intro_t, book_entry_t —
150
+ // live in a2a_protocol; these three are packet-local state/view shapes.)
151
+ metadef pending_msg_t: ($text -> str, $date -> time).
152
+ metadef pending_intro_t: ($name -> str, $ad -> address_document_types::t_address_document, $messages -> pending_msg_t[]).
153
+ metadef pending_view_t: ($name -> str, $queued -> int).
154
+
155
+ // Acceptance window for an introduction credential (seconds since mint;
156
+ // small negative slack for clock oddities) and the matching nonce-table
157
+ // retention horizon (window + slack, so a nonce outlives its credential).
158
+ intro_max_age_seconds is int = 300.
159
+ intro_max_skew_seconds is int = 30.
160
+ seen_nonce_cap is int = 1024.
161
+ pending_queue_cap is int = 50.
162
+
163
+ // ---- monitoring shapes + limits (see MONITORING-AND-SHARED-LIBRARY-DESIGN.md) ----
164
+ // Root-signed authorization for flipping a role's monitoring flag. Like
165
+ // a delegation cert, verified against the role's pinned root keys, so
166
+ // only this hierarchy's root can change what its roles report.
167
+ metadef monitoring_auth_core_t: ($version -> int, $role_cid -> global_id, $enabled -> bool, $issued_at -> time).
168
+ metadef monitoring_auth_t: ($c -> monitoring_auth_core_t, $s -> crypto_signature).
169
+ // One monitored message, as the role reports it to its root.
170
+ metadef monitoring_copy_t: (
171
+ $version -> int,
172
+ $source_cid -> global_id,
173
+ $source_name -> str,
174
+ $direction -> str,
175
+ $peer_cid -> global_id,
176
+ $peer_name -> str,
177
+ $date -> time,
178
+ $body -> str
179
+ ).
180
+ // Proxy binding (root only): a pending 6-digit-code verification and
181
+ // the verified binding that replaces it on success.
182
+ metadef proxy_pending_t: ($code -> str, $proxy_cid -> global_id, $created_at -> time, $attempts -> int).
183
+ metadef proxy_binding_t: ($proxy_cid -> global_id, $bound_at -> time).
184
+ // One queued control request from the bound browser proxy.
185
+ metadef control_req_t: ($sender_cid -> global_id, $sender_name -> str, $payload -> str, $date -> time).
186
+
187
+ proxy_code_max_age_seconds is int = 300.
188
+ proxy_max_attempts is int = 3.
189
+ monitoring_inbox_cap is int = 500.
190
+ control_inbox_cap is int = 200.
191
+
192
+ // Wire the deserialization primitive into the libraries that need it.
193
+ _read_or_abort = grab( _read_or_abort ).
194
+ key_storage::init ($_read_or_abort -> _read_or_abort).
195
+ encrypted_channel::init ($_read_or_abort -> _read_or_abort).
196
+
197
+ // ---- packet state ---------------------------------------------------
198
+ // (The shared contact/profile/hierarchy state — my_name, contacts,
199
+ // pending_invites, peer_ads, my_bio, delegation_cert, root_ad,
200
+ // root_profile, contact_roots — lives in a2a_messaging and is read /
201
+ // assigned as a2a_messaging::<field> below.)
202
+ //
203
+ // Received messages. Each carries its own lifecycle status (see
204
+ // message_t / get_messages / gc / defer_messages), so the
205
+ // packet is the single authority on what has been read or processed —
206
+ // no host-side cursor, safe across concurrent sessions.
207
+ inbox is message_t[] = [].
208
+ // Monotonic source of per-message ids (the stable handle the agent uses
209
+ // to mark a message processed or defer it).
210
+ next_msg_seq is int = 1.
211
+ // Received files (bytes included), same lifecycle as inbox. Drained by
212
+ // get_files, recovered by defer_files, reclaimed by gc.
213
+ file_inbox is file_t[] = [].
214
+ next_file_seq is int = 1.
215
+ // The host registrar's address document (pinned once at identity
216
+ // creation / injected on upgrade) — its $identity $key_list is what
217
+ // introduction credentials are verified against. NIL means this identity
218
+ // accepts no local-book introductions at all.
219
+ registrar_ad is address_document_types::t_address_document+ = NIL.
220
+ // Whether a verified local introduction registers the joiner immediately
221
+ // (TRUE) or parks it in pending_introductions for explicit approval.
222
+ local_auto_accept is bool = TRUE.
223
+ // Replay guard for introduction credentials: nonce -> when it was seen.
224
+ // Lazily purged past the freshness horizon, hard-capped at seen_nonce_cap.
225
+ seen_nonces is (global_id ->> time) = (,).
226
+ // Verified-but-unapproved local introductions (when auto-accept is off),
227
+ // each with a bounded queue of messages awaiting approval.
228
+ pending_introductions is (global_id ->> pending_intro_t) = (,).
229
+
230
+ // ---- monitoring state -------------------------------------------------
231
+ // Whether THIS packet (a role) reports its message traffic to its root.
232
+ // Only flipped by a root-signed authorization (set_monitoring).
233
+ monitoring_enabled is bool = FALSE.
234
+ // Root only: copies received from monitored roles, awaiting the host's
235
+ // get_monitoring_copies pull (forwarded to the bound proxy). Capped;
236
+ // oldest copies are dropped first when no proxy drains the queue.
237
+ monitoring_inbox is monitoring_copy_t[] = [].
238
+ // Root only: the in-flight proxy binding (6-digit code verification)
239
+ // and the verified proxy that monitoring traffic is forwarded to.
240
+ proxy_pending is proxy_pending_t+ = NIL.
241
+ monitoring_proxy is proxy_binding_t+ = NIL.
242
+ // Root only: control requests from the bound proxy, awaiting the
243
+ // host's get_control_requests pull. Kept out of the message inbox so
244
+ // agent sessions never see them.
245
+ control_inbox is control_req_t[] = [].
246
+
247
+ // Signal the host to persist the packet. Only emitted at the end of a
248
+ // complete procedure — intermediate states (e.g. channel handshake) are
249
+ // never saved, so a crash mid-handshake restores to the last stable point.
250
+ fn _save_state (_) = (transaction::action::return_data ($kind -> $save_state)).
251
+ fn _return_data (payload: any) = (transaction::action::return_data ($kind -> $data, $payload -> payload)).
252
+ fn _notify_agent (payload: any) = (transaction::action::return_data ($kind -> $notify_agent, $payload -> payload)).
253
+
254
+ // A typed NIL reply pointer, passed by the call sites that deposit a
255
+ // message with no reply context (introduction first-messages, approval
256
+ // flush). A bare NIL literal cannot infer the nullable reply_ref_t type
257
+ // at the call; this binding gives it one.
258
+ no_reply is a2a_protocol::reply_ref_t+ = NIL.
259
+
260
+ // Append a message to the inbox under a fresh id; returns the id.
261
+ // wire_id is "" for introduction first-messages and pre-1.4 senders;
262
+ // reply_to is NIL unless the sender marked this a reply.
263
+ fn deposit_message (sender_id: global_id, sender_name: str, text: str, msg_date: time, wire_id: str, reply_to: a2a_protocol::reply_ref_t+) -> int
264
+ {
265
+ mid = next_msg_seq.
266
+ next_msg_seq -> next_msg_seq + 1.
267
+ inbox (_count inbox|) -> (
268
+ $msg_id -> mid,
269
+ $sender_id -> sender_id,
270
+ $sender_name -> sender_name,
271
+ $text -> text,
272
+ $date -> msg_date,
273
+ $status -> "unread",
274
+ $wire_id -> wire_id,
275
+ $reply_to -> reply_to
276
+ ).
277
+ return mid.
278
+ }
279
+
280
+ // Append a file to file_inbox under a fresh id; returns the id. Mirrors
281
+ // deposit_message. wire_id is "" for a pre-wire sender; reply_to is NIL unless
282
+ // the sender marked this a reply.
283
+ fn deposit_file (sender_id: global_id, sender_name: str, filename: str, mime: str, data: bin, file_date: time, wire_id: str, reply_to: a2a_protocol::reply_ref_t+) -> int
284
+ {
285
+ fid = next_file_seq.
286
+ next_file_seq -> next_file_seq + 1.
287
+ file_inbox (_count file_inbox|) -> (
288
+ $file_id -> fid,
289
+ $sender_id -> sender_id,
290
+ $sender_name -> sender_name,
291
+ $filename -> filename,
292
+ $mime -> mime,
293
+ $data -> data,
294
+ $date -> file_date,
295
+ $status -> "unread",
296
+ $wire_id -> wire_id,
297
+ $reply_to -> reply_to
298
+ ).
299
+ return fid.
300
+ }
301
+
302
+ // Build the monitoring-copy action for one message IF this packet is a
303
+ // monitored role with a live encrypted channel to its root; [] otherwise.
304
+ // The is_container_registered guard makes a missing/lost root channel
305
+ // degrade to "no copy" instead of failing the user's message — the
306
+ // enable flow (host-side) establishes the channel via connect_sibling.
307
+ fn monitor_copy_actions (direction: str, peer_cid: global_id, text: str, msg_date: time) -> transaction::action::type[]
308
+ {
309
+ if monitoring_enabled == FALSE || a2a_messaging::delegation_cert == NIL { return []. }
310
+ root_cid = a2a_messaging::delegation_cert? $c $root_cid.
311
+ if key_storage::is_container_registered(root_cid) != TRUE { return []. }
312
+
313
+ peer_name is str = "".
314
+ p = a2a_messaging::contacts peer_cid.
315
+ if p != NIL { peer_name -> p? $name. }
316
+
317
+ copy is monitoring_copy_t = (
318
+ $version -> 1,
319
+ $source_cid -> _get_container_id(),
320
+ $source_name -> a2a_messaging::my_name,
321
+ $direction -> direction,
322
+ $peer_cid -> peer_cid,
323
+ $peer_name -> peer_name,
324
+ $date -> msg_date,
325
+ $body -> text
326
+ ).
327
+ return [
328
+ encrypted_channel::send_encrypted_tx root_cid (
329
+ $name -> "::actor::receive_monitoring_copy",
330
+ $targ -> ($copy -> copy)
331
+ )
332
+ ].
333
+ }
334
+
335
+ // Resolve a pending introduction by joiner name or stringified container
336
+ // id; aborts when nothing matches.
337
+ fn resolve_pending (ref: str) -> global_id
338
+ {
339
+ found is global_id+ = NIL.
340
+ sc pending_introductions -- (cid -> p) ?? found == NIL && ((p $name) == ref || (_str cid) == ref)
341
+ {
342
+ found -> cid.
343
+ }
344
+ abort "No pending introduction matches: " + ref when found == NIL.
345
+ return found?.
346
+ }
347
+
348
+ // Wire the agent's storage into the shared messaging core. The receive
349
+ // hook owns everything app-specific about an inbound message: known
350
+ // senders deposit into the inbox; an unknown sender may be a verified-
351
+ // but-unapproved local introduction messaging before approval — queue
352
+ // (bounded) inside its pending entry, approval flushes the queue into
353
+ // the inbox in order; anything else from an unknown sender is rejected.
354
+ // The notification deliberately carries NO message body — only that a
355
+ // message arrived, from whom, and its id. The body stays in the packet
356
+ // and only leaves through get_messages.
357
+ a2a_messaging::init (
358
+ $_read_or_abort -> _read_or_abort,
359
+ $on_message_received -> fn (arg: any) -> transaction::action::type[]
360
+ {
361
+ sender_id = (arg $sender_id) safe global_id.
362
+ text = (arg $text) safe str.
363
+ msg_date = (arg $date) safe time.
364
+ wire_id is str = "".
365
+ if (arg $wire_id) != NIL { wire_id -> (arg $wire_id) safe str. }
366
+ reply_to is a2a_protocol::reply_ref_t+ = NIL.
367
+ if (arg $reply_to) != NIL { reply_to -> (arg $reply_to) safe a2a_protocol::reply_ref_t. }
368
+
369
+ if (arg $sender_name) == NIL
370
+ {
371
+ p = pending_introductions sender_id.
372
+ abort "Message from an unknown sender was rejected." when p == NIL.
373
+ entry = p?.
374
+ queued = entry $messages.
375
+ abort "Pending-introduction message queue is full; awaiting approval." when (_count queued|) >= pending_queue_cap.
376
+ queued (_count queued|) -> ($text -> text, $date -> msg_date).
377
+ pending_introductions sender_id -> ($name -> entry $name, $ad -> entry $ad, $messages -> queued).
378
+ return [
379
+ _notify_agent ($event -> $pending_message, $sender_name -> entry $name, $queued -> _count queued|),
380
+ _save_state NIL
381
+ ].
382
+ }
383
+
384
+ sender_name = (arg $sender_name) safe str.
385
+ mid = deposit_message sender_id sender_name text msg_date wire_id reply_to.
386
+ actions is transaction::action::type[] = [].
387
+ sc monitor_copy_actions "in" sender_id text msg_date -- ( -> a)
388
+ {
389
+ actions (_count actions|) -> a.
390
+ }
391
+ actions (_count actions|) -> _notify_agent ($event -> $message_received, $sender_name -> sender_name, $msg_id -> mid, $date -> msg_date).
392
+ actions (_count actions|) -> _save_state NIL.
393
+ return actions.
394
+ },
395
+ $on_message_sent -> fn (arg: any) -> transaction::action::type[]
396
+ {
397
+ return monitor_copy_actions "out" ((arg $target_id) safe global_id) ((arg $text) safe str) ((arg $date) safe time).
398
+ },
399
+ $on_contact_removed -> fn (_: any) -> transaction::action::type[] { return []. },
400
+ $on_file_received -> fn (arg: any) -> transaction::action::type[]
401
+ {
402
+ sender_id = (arg $sender_id) safe global_id.
403
+ filename = (arg $filename) safe str.
404
+ mime is str = "".
405
+ if (arg $mime) != NIL { mime -> (arg $mime) safe str. }
406
+ data = (arg $data) safe bin.
407
+ file_date = (arg $date) safe time.
408
+ wire_id is str = "".
409
+ if (arg $wire_id) != NIL { wire_id -> (arg $wire_id) safe str. }
410
+ reply_to is a2a_protocol::reply_ref_t+ = NIL.
411
+ if (arg $reply_to) != NIL { reply_to -> (arg $reply_to) safe a2a_protocol::reply_ref_t. }
412
+
413
+ // The connector serves a single KNOWN proxy contact. A file from an
414
+ // unknown/unapproved sender (NIL name) is rejected — unlike messages
415
+ // there is deliberately no pending-introduction byte queue (design D7).
416
+ abort "File from an unknown sender was rejected." when (arg $sender_name) == NIL.
417
+ sender_name = (arg $sender_name) safe str.
418
+
419
+ fid = deposit_file sender_id sender_name filename mime data file_date wire_id reply_to.
420
+ actions is transaction::action::type[] = [].
421
+ // Metadata-only monitoring copy, same path as messages (design D5):
422
+ // never the bytes — file_monitor_summary uses _binlen.
423
+ sc monitor_copy_actions "in" sender_id (a2a_messaging::file_monitor_summary filename mime data) file_date -- ( -> a)
424
+ {
425
+ actions (_count actions|) -> a.
426
+ }
427
+ actions (_count actions|) -> _notify_agent ($event -> $file_received, $sender_name -> sender_name, $file_id -> fid, $date -> file_date).
428
+ actions (_count actions|) -> _save_state NIL.
429
+ return actions.
430
+ },
431
+ $on_file_sent -> fn (arg: any) -> transaction::action::type[]
432
+ {
433
+ // The connector is the sender here; Telegram already holds the
434
+ // original, so we persist nothing (design D6). We DO emit the
435
+ // metadata-only "out" monitoring copy, mirroring on_message_sent.
436
+ return monitor_copy_actions "out" ((arg $target_id) safe global_id) (a2a_messaging::file_monitor_summary ((arg $filename) safe str) ((arg $mime) safe str) ((arg $data) safe bin)) ((arg $date) safe time).
437
+ }
438
+ ).
439
+
440
+ // Wire the control plane (see MONITORING-AND-SHARED-LIBRARY-DESIGN.md
441
+ // Part 4): control requests from the bound browser proxy queue in
442
+ // control_inbox — NEVER the message inbox, so agent sessions don't see
443
+ // them — and the notify event wakes the daemon's dispatcher. The
444
+ // payload stays opaque here; sender authorization happens in the
445
+ // daemon against the packet's monitoring_proxy / proxy_pending state.
446
+ a2a_control::init (
447
+ $app_id -> "network.ours.telegram-connector",
448
+ $on_control_received -> fn (arg: any) -> transaction::action::type[]
449
+ {
450
+ abort "Control queue is full." when (_count control_inbox|) >= control_inbox_cap.
451
+ sender_name = (arg $sender_name) safe str.
452
+ control_inbox (_count control_inbox|) -> (
453
+ $sender_cid -> (arg $sender_id) safe global_id,
454
+ $sender_name -> sender_name,
455
+ $payload -> (arg $payload) safe str,
456
+ $date -> (arg $date) safe time
457
+ ).
458
+ return [
459
+ _notify_agent ($event -> $control_request, $sender_name -> sender_name, $queued -> _count control_inbox|),
460
+ _save_state NIL
461
+ ].
462
+ }
463
+ ).
464
+
465
+ // ---- capabilities manifest (core.connect) -----------------------------
466
+ // THE SINGLE ENABLEMENT BOOLEAN. Flipping this to FALSE removes core.connect
467
+ // from the live manifest, which (a) hides the Connect surface in any bound
468
+ // control plane and (b) makes the core node-side gate in
469
+ // ::a2a_messaging::ingest_connect_descriptor reject every introduction
470
+ // (it reads a2a_capabilities::self_supports("core.connect"), i.e. this
471
+ // manifest). There is NO other connect code in this app: the ingest
472
+ // transaction lives entirely in the shared core, so enabling/disabling the
473
+ // feature is exactly this flag — zero application logic.
474
+ supports_connect is bool = TRUE.
475
+
476
+ // The node's live self-description (a2a_capabilities::app_manifest_t),
477
+ // served on ::a2a_capabilities::get_manifest and read by self_supports.
478
+ // core.configuration is always present (the daemon renders its config
479
+ // schema); core.connect is present iff supports_connect. Neither has a
480
+ // packet-side verb handler — configuration is daemon-mediated and connect
481
+ // is the dedicated core ingest tx — so $supported (below) stays empty.
482
+ fn build_manifest (_: any) -> a2a_capabilities::app_manifest_t
483
+ {
484
+ caps is (str ->> a2a_capabilities::capability_t) = (,).
485
+ caps a2a_capabilities::cap_configuration -> (
486
+ $cap -> a2a_capabilities::cap_configuration,
487
+ $version -> 1,
488
+ $params -> "",
489
+ $secrets -> (,)
490
+ ).
491
+ if supports_connect
492
+ {
493
+ caps a2a_capabilities::cap_connect -> (
494
+ $cap -> a2a_capabilities::cap_connect,
495
+ $version -> 1,
496
+ $params -> "",
497
+ $secrets -> (,)
498
+ ).
499
+ }
500
+ return (
501
+ $version -> 1,
502
+ $app_id -> "network.ours.telegram-connector",
503
+ $name -> a2a_messaging::my_name,
504
+ $description -> a2a_messaging::my_bio,
505
+ $monitoring_status -> "unbound",
506
+ $capabilities -> caps
507
+ ).
508
+ }
509
+
510
+ // Wire the capabilities library. $supported lists only caps with a packet
511
+ // VERB handler (init fail-fasts if any lacks one) — this app has none, so
512
+ // it is empty. core.connect MUST NOT appear here: it has no verb handler
513
+ // and would abort init; "supports introductions" is core.connect living in
514
+ // describe()'s live $capabilities map (above), per RELEASE_NOTES §B2.
515
+ a2a_capabilities::init (
516
+ $describe -> build_manifest,
517
+ $supported -> [],
518
+ $handlers -> (,),
519
+ $on_unknown -> fn (_: any) -> transaction::action::type[] { return []. }
520
+ ).
521
+ }
522
+
523
+ // On recreation the host injects the persisted SIGN secret as init_arg: the
524
+ // hex string of the Serialize()'d secretkey_sign. Deserialize it back
525
+ // (_hex_string_to_binary -> _read_or_abort) and reseed to restore the
526
+ // container address (adapt #77). Fresh-create passes no arg and the
527
+ // bootstrapped identity stands.
528
+ trn __init arg
529
+ {
530
+ // Fresh create passes no init_arg — the wrapper hands __init an empty
531
+ // dict (not nil), so guard on the actual string type before deserializing
532
+ // the persisted SIGN secret (Serialize()-hex) and reseeding (adapt #77).
533
+ if _typeof arg == "STRING" {
534
+ key_storage::reseed_identity_from_secret
535
+ ((_read_or_abort (_hex_string_to_binary (arg SAFE(str)))) SAFE(secretkey_sign)).
536
+ }
537
+ return ::transaction::success[].
538
+ }
539
+
540
+ // ---- message store --------------------------------------------------------
541
+
542
+ trn readonly list_incoming_messages _
543
+ {
544
+ return inbox.
545
+ }
546
+
547
+ trn readonly list_incoming_files _
548
+ {
549
+ return file_inbox.
550
+ }
551
+
552
+ // Hand the agent every message it has not seen yet (status "unread") and flip
553
+ // those to "processed" — the ONLY place message bodies leave the packet, and
554
+ // the sole dedup point: a message is returned exactly once, so an agent that
555
+ // reads and acts immediately never double-processes. CRASH WINDOW: a
556
+ // "processed" body has already left; an agent that crashes after get_messages
557
+ // but before acting must defer_messages to recover it (-> "unread") before gc
558
+ // promotes it through "ready_to_delete" and deletes it (>= 1 gc cycle).
559
+ trn get_messages _
560
+ {
561
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
562
+
563
+ fresh is message_t[] = [].
564
+ new_inbox is message_t[] = [].
565
+ sc inbox -- ( -> m)
566
+ {
567
+ if (m $status) == "unread"
568
+ {
569
+ processed_m is message_t = (
570
+ $msg_id -> m $msg_id,
571
+ $sender_id -> m $sender_id,
572
+ $sender_name -> m $sender_name,
573
+ $text -> m $text,
574
+ $date -> m $date,
575
+ $status -> "processed",
576
+ $wire_id -> m $wire_id,
577
+ $reply_to -> m $reply_to
578
+ ).
579
+ fresh (_count fresh|) -> m.
580
+ new_inbox (_count new_inbox|) -> processed_m.
581
+ }
582
+ else
583
+ {
584
+ new_inbox (_count new_inbox|) -> m.
585
+ }
586
+ }
587
+ inbox -> new_inbox.
588
+
589
+ return transaction::success [
590
+ _return_data ($messages -> fresh),
591
+ _save_state NIL
592
+ ].
593
+ }
594
+
595
+ // Hand the agent every file it has not seen (status "unread") and flip those to
596
+ // "processed" — the file analogue of get_messages, and the only place file bytes
597
+ // leave the packet. Same crash-window contract: a "processed" file already left;
598
+ // recover with defer_files before gc reclaims it.
599
+ trn get_files _
600
+ {
601
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
602
+
603
+ fresh is file_t[] = [].
604
+ new_inbox is file_t[] = [].
605
+ sc file_inbox -- ( -> f)
606
+ {
607
+ if (f $status) == "unread"
608
+ {
609
+ processed_f is file_t = (
610
+ $file_id -> f $file_id,
611
+ $sender_id -> f $sender_id,
612
+ $sender_name -> f $sender_name,
613
+ $filename -> f $filename,
614
+ $mime -> f $mime,
615
+ $data -> f $data,
616
+ $date -> f $date,
617
+ $status -> "processed",
618
+ $wire_id -> f $wire_id,
619
+ $reply_to -> f $reply_to
620
+ ).
621
+ fresh (_count fresh|) -> f.
622
+ new_inbox (_count new_inbox|) -> processed_f.
623
+ }
624
+ else
625
+ {
626
+ new_inbox (_count new_inbox|) -> f.
627
+ }
628
+ }
629
+ file_inbox -> new_inbox.
630
+
631
+ return transaction::success [
632
+ _return_data ($files -> fresh),
633
+ _save_state NIL
634
+ ].
635
+ }
636
+
637
+ // Two-generation garbage collection of handled messages, fired by the host on
638
+ // a timer (NOT piggybacked on other transactions — that would collapse the
639
+ // window under traffic). Order matters: (A) delete everything already marked
640
+ // "ready_to_delete", THEN (B) promote "processed" -> "ready_to_delete". A
641
+ // single pass keyed on the current status gives exactly that — a message is in
642
+ // one status, so a freshly-processed message is promoted (not dropped) this
643
+ // tick and only deleted on the NEXT tick, guaranteeing it survives a full
644
+ // cycle (>= 1 interval) as a deferrable "ready_to_delete".
645
+ trn gc _
646
+ {
647
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
648
+
649
+ kept is message_t[] = [].
650
+ deleted is int = 0.
651
+ promoted is int = 0.
652
+ sc inbox -- ( -> m)
653
+ {
654
+ if (m $status) == "ready_to_delete"
655
+ {
656
+ deleted -> deleted + 1.
657
+ }
658
+ elif (m $status) == "processed"
659
+ {
660
+ kept (_count kept|) -> (
661
+ $msg_id -> m $msg_id,
662
+ $sender_id -> m $sender_id,
663
+ $sender_name -> m $sender_name,
664
+ $text -> m $text,
665
+ $date -> m $date,
666
+ $status -> "ready_to_delete",
667
+ $wire_id -> m $wire_id,
668
+ $reply_to -> m $reply_to
669
+ ).
670
+ promoted -> promoted + 1.
671
+ }
672
+ else
673
+ {
674
+ kept (_count kept|) -> m.
675
+ }
676
+ }
677
+ inbox -> kept.
678
+
679
+ // Same two-generation sweep over the file store: a delivered file's bytes are
680
+ // reclaimed a full gc cycle after delivery, exactly like message bodies.
681
+ fkept is file_t[] = [].
682
+ sc file_inbox -- ( -> f)
683
+ {
684
+ if (f $status) == "ready_to_delete"
685
+ {
686
+ deleted -> deleted + 1.
687
+ }
688
+ elif (f $status) == "processed"
689
+ {
690
+ fkept (_count fkept|) -> (
691
+ $file_id -> f $file_id,
692
+ $sender_id -> f $sender_id,
693
+ $sender_name -> f $sender_name,
694
+ $filename -> f $filename,
695
+ $mime -> f $mime,
696
+ $data -> f $data,
697
+ $date -> f $date,
698
+ $status -> "ready_to_delete",
699
+ $wire_id -> f $wire_id,
700
+ $reply_to -> f $reply_to
701
+ ).
702
+ promoted -> promoted + 1.
703
+ }
704
+ else
705
+ {
706
+ fkept (_count fkept|) -> f.
707
+ }
708
+ }
709
+ file_inbox -> fkept.
710
+
711
+ return transaction::success [
712
+ _return_data ($deleted -> deleted, $promoted -> promoted),
713
+ _save_state NIL
714
+ ].
715
+ }
716
+
717
+ // Put handled messages back into the queue (status -> "unread") so a different
718
+ // session picks them up on its next get_messages. Restores from EITHER post-
719
+ // read generation — "processed" or "ready_to_delete" — so a message stays
720
+ // recoverable across a full gc cycle. The opt-in counterpart to the safe
721
+ // default: forgetting to defer just means the message stays handled by you.
722
+ trn defer_messages _:($msg_ids -> ids: int[])
723
+ {
724
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
725
+
726
+ wanted is (int ->> bool) = (,).
727
+ sc ids -- ( -> id) { wanted id -> TRUE. }
728
+
729
+ new_inbox is message_t[] = [].
730
+ deferred is int = 0.
731
+ sc inbox -- ( -> m)
732
+ {
733
+ if (wanted (m $msg_id)) && (((m $status) == "processed") || ((m $status) == "ready_to_delete"))
734
+ {
735
+ new_inbox (_count new_inbox|) -> (
736
+ $msg_id -> m $msg_id,
737
+ $sender_id -> m $sender_id,
738
+ $sender_name -> m $sender_name,
739
+ $text -> m $text,
740
+ $date -> m $date,
741
+ $status -> "unread",
742
+ $wire_id -> m $wire_id,
743
+ $reply_to -> m $reply_to
744
+ ).
745
+ deferred -> deferred + 1.
746
+ }
747
+ else
748
+ {
749
+ new_inbox (_count new_inbox|) -> m.
750
+ }
751
+ }
752
+ inbox -> new_inbox.
753
+
754
+ return transaction::success [
755
+ _return_data ($deferred -> deferred),
756
+ _save_state NIL
757
+ ].
758
+ }
759
+
760
+ // Put handled files back into the queue (status -> "unread"), restoring from
761
+ // either post-read generation. The file analogue of defer_messages.
762
+ trn defer_files _:($file_ids -> ids: int[])
763
+ {
764
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
765
+
766
+ wanted is (int ->> bool) = (,).
767
+ sc ids -- ( -> id) { wanted id -> TRUE. }
768
+
769
+ new_inbox is file_t[] = [].
770
+ deferred is int = 0.
771
+ sc file_inbox -- ( -> f)
772
+ {
773
+ if (wanted (f $file_id)) && (((f $status) == "processed") || ((f $status) == "ready_to_delete"))
774
+ {
775
+ new_inbox (_count new_inbox|) -> (
776
+ $file_id -> f $file_id,
777
+ $sender_id -> f $sender_id,
778
+ $sender_name -> f $sender_name,
779
+ $filename -> f $filename,
780
+ $mime -> f $mime,
781
+ $data -> f $data,
782
+ $date -> f $date,
783
+ $status -> "unread",
784
+ $wire_id -> f $wire_id,
785
+ $reply_to -> f $reply_to
786
+ ).
787
+ deferred -> deferred + 1.
788
+ }
789
+ else
790
+ {
791
+ new_inbox (_count new_inbox|) -> f.
792
+ }
793
+ }
794
+ file_inbox -> new_inbox.
795
+
796
+ return transaction::success [
797
+ _return_data ($deferred -> deferred),
798
+ _save_state NIL
799
+ ].
800
+ }
801
+
802
+ // ---- local contact book ---------------------------------------------------
803
+ // The book itself lives HOST-SIDE (wrapper-local file, remote peers have no
804
+ // path to it) and stores only public address material — essentially a stored
805
+ // multi-use invite. It bypasses invite generation/delivery, NOT the key
806
+ // exchange: connecting still runs the normal encrypted_channel handshake.
807
+ // Authorization is per attempt: the host's registrar packet mints a fresh,
808
+ // short-lived, registrar-signed introduction credential for each connect, and
809
+ // the target verifies it against its pinned registrar keys. An external peer
810
+ // can never produce one, so the local boundary holds cryptographically.
811
+
812
+ trn readonly export_address_document _
813
+ {
814
+ return (_write address_document::get_my_address_document()).
815
+ }
816
+
817
+ // Export the root SIGN secret so the host can persist it (identity.key) and
818
+ // reseed a recreated packet to the same address across upgrades (adapt #77).
819
+ trn readonly export_signing_secret _
820
+ {
821
+ return key_storage::export_identity_signing_secret().
822
+ }
823
+
824
+ trn pin_registrar _:($registrar_ad -> registrar_ad_blob: bin, $replace -> replace: bool+)
825
+ {
826
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
827
+
828
+ ad = (_read_or_abort registrar_ad_blob) safe address_document_types::t_address_document.
829
+ if registrar_ad != NIL
830
+ {
831
+ // Idempotent re-pin of the same keys is a no-op; CHANGING the pinned
832
+ // keys is a deliberate act and must be requested explicitly, so no
833
+ // future internal-path code can substitute a registrar silently.
834
+ if (_value_id (registrar_ad? $identity $key_list)) == (_value_id (ad $identity $key_list))
835
+ {
836
+ return transaction::success [
837
+ _return_data ($pinned -> TRUE, $changed -> FALSE)
838
+ ].
839
+ }
840
+ abort "A different registrar key list is already pinned; pass $replace -> TRUE to overwrite." when replace == NIL || replace? != TRUE.
841
+ }
842
+ registrar_ad -> ad.
843
+ return transaction::success [
844
+ _return_data ($pinned -> TRUE, $changed -> TRUE),
845
+ _save_state NIL
846
+ ].
847
+ }
848
+
849
+ trn set_local_policy _:($auto_accept -> auto_accept: bool)
850
+ {
851
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
852
+ local_auto_accept -> auto_accept.
853
+ return transaction::success [
854
+ _return_data ($auto_accept -> auto_accept),
855
+ _save_state NIL
856
+ ].
857
+ }
858
+
859
+ // Mint an introduction credential. Only meaningful on the host's REGISTRAR
860
+ // packet: targets verify the signature against their pinned registrar keys,
861
+ // so a credential minted by any other packet simply fails verification.
862
+ // Stateless — nothing to save. iat is stamped with transaction time so mint
863
+ // and verify use the same clock domain.
864
+ trn mint_introduction _:($joiner_ad -> joiner_ad_blob: bin, $target_ad -> target_ad_blob: bin)
865
+ {
866
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
867
+
868
+ joiner_ad = (_read_or_abort joiner_ad_blob) safe address_document_types::t_address_document.
869
+ target_ad = (_read_or_abort target_ad_blob) safe address_document_types::t_address_document.
870
+ intro is a2a_protocol::intro_t = (
871
+ $version -> 1,
872
+ $joiner_cid -> joiner_ad $identity $container_id,
873
+ $joiner_ad_hash -> _value_id joiner_ad,
874
+ $target_cid -> target_ad $identity $container_id,
875
+ $iat -> (current_transaction_info::get_transaction_time())?,
876
+ $nonce -> _new_id "ours local introduction"
877
+ ).
878
+ signed is a2a_protocol::signed_intro_t = ($i -> intro, $s -> key_storage::default_sign (_value_id intro)).
879
+ return transaction::success [
880
+ _return_data ($intro -> (_write signed))
881
+ ].
882
+ }
883
+
884
+ // Sign a contact-book entry (registrar packet only, same caveat as above).
885
+ // Makes the host-side book file tamper-evident: senders re-derive this record
886
+ // from the entry they read and verify the signature before connecting.
887
+ trn sign_book_entry _:($name -> name: str, $ad -> ad_blob: bin)
888
+ {
889
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
890
+
891
+ ad = (_read_or_abort ad_blob) safe address_document_types::t_address_document.
892
+ entry is a2a_protocol::book_entry_t = ($version -> 1, $name -> name, $ad_hash -> _value_id ad).
893
+ return transaction::success [
894
+ _return_data ($sig -> (_write (key_storage::default_sign (_value_id entry))))
895
+ ].
896
+ }
897
+
898
+ // Connect to a same-host peer found in the local contact book: verify the
899
+ // book entry's registrar signature, register the peer as a contact, then
900
+ // introduce myself over the encrypted channel — carrying the credential the
901
+ // host just minted for this attempt, plus (optionally) the first message so
902
+ // introduction + first delivery are one atomic transaction on the target
903
+ // (no introduce-vs-message ordering race).
904
+ trn connect_local _:($name -> name: str, $target_ad -> target_ad_blob: bin, $intro -> intro_blob: bin, $entry_sig -> entry_sig_blob: bin, $text -> text: str+)
905
+ {
906
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
907
+ abort "No registrar pinned — the local contact book is unavailable for this identity." when registrar_ad == NIL.
908
+
909
+ target_ad = (_read_or_abort target_ad_blob) safe address_document_types::t_address_document.
910
+ target_id = target_ad $identity $container_id.
911
+ abort "This contact-book entry is your own identity." when target_id == _get_container_id().
912
+
913
+ entry is a2a_protocol::book_entry_t = ($version -> 1, $name -> name, $ad_hash -> _value_id target_ad).
914
+ entry_sig = (_read_or_abort entry_sig_blob) safe crypto_signature.
915
+ abort "Contact-book entry failed registrar verification." when key_storage::check_signature_new_container (_value_id entry) entry_sig (registrar_ad? $identity $key_list) != TRUE.
916
+
917
+ a2a_messaging::contacts target_id -> ($name -> name, $container_id -> target_id).
918
+ a2a_messaging::peer_ads target_id -> target_ad.
919
+
920
+ my_self_name = a2a_messaging::my_name.
921
+ my_ad = address_document::get_my_address_document().
922
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
923
+ return transaction::success [
924
+ encrypted_channel::send_encrypted_tx target_id (
925
+ $name -> "::actor::local_introduce",
926
+ $targ -> ($joiner_name -> my_self_name, $joiner_ad -> my_ad, $intro -> intro_blob, $text -> text)
927
+ ),
928
+ _return_data ($connected -> name, $container_id -> target_id),
929
+ _save_state NIL
930
+ ].
931
+ }).
932
+ }
933
+
934
+ trn approve_introduction _:($contact -> ref: str)
935
+ {
936
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
937
+
938
+ pid = resolve_pending ref.
939
+ entry = (pending_introductions pid)?.
940
+ a2a_messaging::contacts pid -> ($name -> entry $name, $container_id -> pid).
941
+ a2a_messaging::peer_ads pid -> entry $ad.
942
+
943
+ queued = entry $messages.
944
+ flushed is int = 0.
945
+ sc queued -- ( -> m)
946
+ {
947
+ deposit_message pid (entry $name) (m $text) (m $date) "" no_reply.
948
+ flushed -> flushed + 1.
949
+ }
950
+ delete pending_introductions pid.
951
+
952
+ return transaction::success [
953
+ _return_data ($approved -> entry $name, $container_id -> pid, $flushed -> flushed),
954
+ _save_state NIL
955
+ ].
956
+ }
957
+
958
+ trn reject_introduction _:($contact -> ref: str)
959
+ {
960
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
961
+
962
+ pid = resolve_pending ref.
963
+ entry = (pending_introductions pid)?.
964
+ dropped = _count (entry $messages)|.
965
+ delete pending_introductions pid.
966
+
967
+ return transaction::success [
968
+ _return_data ($rejected -> entry $name, $container_id -> pid, $dropped_messages -> dropped),
969
+ _save_state NIL
970
+ ].
971
+ }
972
+
973
+ trn readonly list_pending_introductions _
974
+ {
975
+ out is (global_id ->> pending_view_t) = (,).
976
+ sc pending_introductions -- (cid -> p)
977
+ {
978
+ out cid -> ($name -> p $name, $queued -> _count (p $messages)|).
979
+ }
980
+ return out.
981
+ }
982
+
983
+ // ---- identity hierarchy ---------------------------------------------------
984
+ // Two layers (see IDENTITY-HIERARCHY-DESIGN.md): one ROOT identity per host
985
+ // (represents the person; structurally just a packet with no delegation
986
+ // cert) and ROLE identities under it, each carrying a cert signed by the
987
+ // root. The host drives issuance: it asks the root packet to sign a cert
988
+ // (sign_delegation) and export its profile (export_root_profile), then
989
+ // stores both into the role packet (set_delegation). Intra-root peers
990
+ // (Ring 1) connect via connect_sibling/sibling_introduce with cert-based
991
+ // auto-accept — no registrar credential, no approval queue, and it works
992
+ // for roles that are not published in the local contact book.
993
+
994
+ // Sign a delegation certificate for a role (meaningful on the ROOT packet:
995
+ // verifiers check the signature against the root's keys, so a cert minted
996
+ // by any other packet fails verification). Stateless — nothing to save.
997
+ trn sign_delegation _:($role_ad -> role_ad_blob: bin, $role_id -> role_id: str)
998
+ {
999
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1000
+ abort "Only a root identity can sign delegation certificates." when a2a_messaging::delegation_cert != NIL.
1001
+
1002
+ role_ad = (_read_or_abort role_ad_blob) safe address_document_types::t_address_document.
1003
+ role_cid = role_ad $identity $container_id.
1004
+ abort "Cannot issue a delegation certificate to myself." when role_cid == _get_container_id().
1005
+
1006
+ core is a2a_protocol::delegation_core_t = (
1007
+ $version -> 1,
1008
+ $role_cid -> role_cid,
1009
+ $role_ad_hash -> _value_id role_ad,
1010
+ $role_id -> role_id,
1011
+ $root_cid -> _get_container_id(),
1012
+ $issued_at -> (current_transaction_info::get_transaction_time())?
1013
+ ).
1014
+ cert is a2a_protocol::delegation_cert_t = ($c -> core, $s -> key_storage::default_sign (_value_id core)).
1015
+ return transaction::success [
1016
+ _return_data ($cert -> (_write cert))
1017
+ ].
1018
+ }
1019
+
1020
+ // Export my self-signed root profile (root packet only). Roles embed this
1021
+ // in the invites they generate, so external peers learn who is behind the
1022
+ // role; it carries my key list so the whole chain verifies standalone.
1023
+ trn export_root_profile _
1024
+ {
1025
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1026
+ abort "Only a root identity can export a root profile." when a2a_messaging::delegation_cert != NIL.
1027
+
1028
+ my_ad = address_document::get_my_address_document().
1029
+ core is a2a_protocol::root_profile_core_t = (
1030
+ $version -> 1,
1031
+ $root_cid -> _get_container_id(),
1032
+ $name -> a2a_messaging::my_name,
1033
+ $bio -> a2a_messaging::my_bio,
1034
+ $keys -> my_ad $identity $key_list
1035
+ ).
1036
+ profile is a2a_protocol::root_profile_t = ($p -> core, $s -> key_storage::default_sign (_value_id core)).
1037
+ return transaction::success [
1038
+ _return_data ($profile -> (_write profile))
1039
+ ].
1040
+ }
1041
+
1042
+ // Store my delegation cert + root material (role packet, host-fired after
1043
+ // the root signed the cert). Everything is verified before it is stored:
1044
+ // a cert that does not name me, does not match my keys, or was not signed
1045
+ // by the carried root is rejected. Re-running with fresh material is the
1046
+ // refresh path (e.g. the root's bio changed -> new profile, same root).
1047
+ trn set_delegation _:($cert -> cert_blob: bin, $root_ad -> root_ad_blob: bin, $root_profile -> rp_blob: bin)
1048
+ {
1049
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1050
+
1051
+ cert = (_read_or_abort cert_blob) safe a2a_protocol::delegation_cert_t.
1052
+ new_root_ad = (_read_or_abort root_ad_blob) safe address_document_types::t_address_document.
1053
+ rp = (_read_or_abort rp_blob) safe a2a_protocol::root_profile_t.
1054
+
1055
+ abort "Unsupported delegation certificate version." when (cert $c $version) != 1.
1056
+ abort "This delegation certificate was issued to a different identity." when (cert $c $role_cid) != _get_container_id().
1057
+ my_ad = address_document::get_my_address_document().
1058
+ abort "This delegation certificate does not match my address document." when (cert $c $role_ad_hash) != (_value_id my_ad).
1059
+ abort "The root address document does not match the certificate's root." when (new_root_ad $identity $container_id) != (cert $c $root_cid).
1060
+ abort "The delegation certificate was not signed by the root." when key_storage::check_signature_new_container (_value_id (cert $c)) (cert $s) (new_root_ad $identity $key_list) != TRUE.
1061
+ abort "Unsupported root profile version." when (rp $p $version) != 1.
1062
+ abort "The root profile does not match the certificate's root." when (rp $p $root_cid) != (cert $c $root_cid).
1063
+ abort "The root profile's key list does not match the root's address document." when (_value_id (rp $p $keys)) != (_value_id (new_root_ad $identity $key_list)).
1064
+ abort "The root profile signature is invalid." when key_storage::check_signature_new_container (_value_id (rp $p)) (rp $s) (new_root_ad $identity $key_list) != TRUE.
1065
+
1066
+ a2a_messaging::delegation_cert -> cert.
1067
+ a2a_messaging::root_ad -> new_root_ad.
1068
+ a2a_messaging::root_profile -> rp.
1069
+
1070
+ return transaction::success [
1071
+ _return_data ($delegated -> TRUE, $root_cid -> (_str (cert $c $root_cid)), $role_id -> cert $c $role_id),
1072
+ _save_state NIL
1073
+ ].
1074
+ }
1075
+
1076
+ trn readonly describe_identity _
1077
+ {
1078
+ if a2a_messaging::delegation_cert == NIL
1079
+ {
1080
+ return ($name -> a2a_messaging::my_name, $bio -> a2a_messaging::my_bio, $has_cert -> FALSE, $role_id -> "", $root_cid -> "", $root_name -> "", $monitoring_enabled -> monitoring_enabled).
1081
+ }
1082
+ cert = a2a_messaging::delegation_cert?.
1083
+ rname is str = "".
1084
+ if a2a_messaging::root_profile != NIL { rname -> a2a_messaging::root_profile? $p $name. }
1085
+ return (
1086
+ $name -> a2a_messaging::my_name,
1087
+ $bio -> a2a_messaging::my_bio,
1088
+ $has_cert -> TRUE,
1089
+ $role_id -> cert $c $role_id,
1090
+ $root_cid -> (_str (cert $c $root_cid)),
1091
+ $root_name -> rname,
1092
+ $monitoring_enabled -> monitoring_enabled
1093
+ ).
1094
+ }
1095
+
1096
+ // Connect to an intra-root sibling (Ring 1): register it as a contact and
1097
+ // introduce myself over the encrypted channel, presenting my delegation
1098
+ // cert (NIL when I am the root itself — the channel proves I control the
1099
+ // root's keys, which is all a role needs to recognize its root). Like
1100
+ // connect_local, the optional first message rides the introduction so
1101
+ // introduce + first delivery are one atomic transaction on the target.
1102
+ trn connect_sibling _:($name -> name: str, $target_ad -> target_ad_blob: bin, $text -> text: str+)
1103
+ {
1104
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1105
+
1106
+ target_ad = (_read_or_abort target_ad_blob) safe address_document_types::t_address_document.
1107
+ target_id = target_ad $identity $container_id.
1108
+ abort "This sibling is your own identity." when target_id == _get_container_id().
1109
+
1110
+ cert_blob is bin+ = NIL.
1111
+ if a2a_messaging::delegation_cert != NIL { cert_blob -> (_write a2a_messaging::delegation_cert?). }
1112
+
1113
+ a2a_messaging::contacts target_id -> ($name -> name, $container_id -> target_id).
1114
+ a2a_messaging::peer_ads target_id -> target_ad.
1115
+ // Record the target's root linkage: a sibling shares my root by
1116
+ // definition (the receiving side verifies the converse independently).
1117
+ if a2a_messaging::delegation_cert != NIL && a2a_messaging::root_profile != NIL
1118
+ {
1119
+ a2a_messaging::contact_roots target_id -> ($root_cid -> a2a_messaging::delegation_cert? $c $root_cid, $root_name -> a2a_messaging::root_profile? $p $name, $role_id -> name).
1120
+ }
1121
+ else
1122
+ {
1123
+ a2a_messaging::contact_roots target_id -> ($root_cid -> _get_container_id(), $root_name -> a2a_messaging::my_name, $role_id -> name).
1124
+ }
1125
+
1126
+ my_self_name = a2a_messaging::my_name.
1127
+ my_ad = address_document::get_my_address_document().
1128
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
1129
+ return transaction::success [
1130
+ encrypted_channel::send_encrypted_tx target_id (
1131
+ $name -> "::actor::sibling_introduce",
1132
+ $targ -> ($joiner_name -> my_self_name, $joiner_ad -> my_ad, $cert -> cert_blob, $text -> text)
1133
+ ),
1134
+ _return_data ($connected -> name, $container_id -> target_id),
1135
+ _save_state NIL
1136
+ ].
1137
+ }).
1138
+ }
1139
+
1140
+ // ---- monitoring + control plane -------------------------------------------
1141
+ // (see MONITORING-AND-SHARED-LIBRARY-DESIGN.md). A monitored ROLE reports
1142
+ // every message it sends/receives to its ROOT (the monitor_copy_actions
1143
+ // branches in the storage hooks above); the root queues the copies and the
1144
+ // host forwards them to a human proxy bound via 6-digit-code verification.
1145
+ // The proxy's control requests (create agent, update role, …) queue in
1146
+ // control_inbox and are executed by the host daemon.
1147
+
1148
+ trn readonly get_monitoring_status _
1149
+ {
1150
+ pending is bool = FALSE.
1151
+ if proxy_pending != NIL { pending -> TRUE. }
1152
+ proxy_out is str = "".
1153
+ if monitoring_proxy != NIL { proxy_out -> _str (monitoring_proxy? $proxy_cid). }
1154
+ return (
1155
+ $monitoring_enabled -> monitoring_enabled,
1156
+ $proxy_cid -> proxy_out,
1157
+ $proxy_pending -> pending,
1158
+ $copies_queued -> _count monitoring_inbox|,
1159
+ $control_queued -> _count control_inbox|
1160
+ ).
1161
+ }
1162
+
1163
+ // Sign a monitoring authorization for a role (ROOT packet only — the role
1164
+ // verifies the signature against its pinned root keys, so an auth minted
1165
+ // by any other packet fails). Stateless, mirrors sign_delegation.
1166
+ trn sign_monitoring_auth _:($role_ad -> role_ad_blob: bin, $enabled -> enabled: bool)
1167
+ {
1168
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1169
+ abort "Only a root identity can sign monitoring authorizations." when a2a_messaging::delegation_cert != NIL.
1170
+
1171
+ role_ad = (_read_or_abort role_ad_blob) safe address_document_types::t_address_document.
1172
+ core is monitoring_auth_core_t = (
1173
+ $version -> 1,
1174
+ $role_cid -> role_ad $identity $container_id,
1175
+ $enabled -> enabled,
1176
+ $issued_at -> (current_transaction_info::get_transaction_time())?
1177
+ ).
1178
+ auth is monitoring_auth_t = ($c -> core, $s -> key_storage::default_sign (_value_id core)).
1179
+ return transaction::success [
1180
+ _return_data ($auth -> (_write auth))
1181
+ ].
1182
+ }
1183
+
1184
+ // Store a verified monitoring flag (ROLE packet, host-fired after the root
1185
+ // signed the auth). An auth that does not name me or was not signed by my
1186
+ // root is rejected — so even a compromised host process cannot silently
1187
+ // flip monitoring without the root packet's keys.
1188
+ trn set_monitoring _:($auth -> auth_blob: bin)
1189
+ {
1190
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1191
+ abort "Only a delegated role can be monitored." when a2a_messaging::delegation_cert == NIL || a2a_messaging::root_ad == NIL.
1192
+
1193
+ auth = (_read_or_abort auth_blob) safe monitoring_auth_t.
1194
+ abort "Unsupported monitoring authorization version." when (auth $c $version) != 1.
1195
+ abort "This monitoring authorization was issued to a different identity." when (auth $c $role_cid) != _get_container_id().
1196
+ abort "The monitoring authorization was not signed by my root." when key_storage::check_signature_new_container (_value_id (auth $c)) (auth $s) (a2a_messaging::root_ad? $identity $key_list) != TRUE.
1197
+
1198
+ monitoring_enabled -> auth $c $enabled.
1199
+ return transaction::success [
1200
+ _return_data ($monitoring_enabled -> monitoring_enabled),
1201
+ _save_state NIL
1202
+ ].
1203
+ }
1204
+
1205
+ // A monitored role reports one message copy (ROOT packet, inbound). Only
1206
+ // accepted from a verified role of THIS root (the contact_roots linkage
1207
+ // recorded by sibling_introduce), and the copy must name its actual sender
1208
+ // — a role cannot forge copies on another role's behalf.
1209
+ trn receive_monitoring_copy _:($copy -> copy: monitoring_copy_t)
1210
+ {
1211
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1212
+ encrypted_channel::check_encrypted_or_abort().
1213
+
1214
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1215
+ link = a2a_messaging::contact_roots sender_id.
1216
+ abort "Monitoring copies are only accepted from my own roles." when link == NIL || (link? $root_cid) != _get_container_id().
1217
+ abort "Monitoring copy does not name its sender as the source." when (copy $source_cid) != sender_id.
1218
+ abort "Unsupported monitoring copy version." when (copy $version) != 1.
1219
+
1220
+ // Capped queue, oldest first out: if no proxy drains the root, recent
1221
+ // traffic wins over old.
1222
+ if (_count monitoring_inbox|) >= monitoring_inbox_cap
1223
+ {
1224
+ trimmed is monitoring_copy_t[] = [].
1225
+ i is int = 0.
1226
+ sc monitoring_inbox -- ( -> m)
1227
+ {
1228
+ if i > 0 { trimmed (_count trimmed|) -> m. }
1229
+ i -> i + 1.
1230
+ }
1231
+ monitoring_inbox -> trimmed.
1232
+ }
1233
+ monitoring_inbox (_count monitoring_inbox|) -> copy.
1234
+
1235
+ return transaction::success [
1236
+ _notify_agent ($event -> $monitoring_copy, $source_name -> copy $source_name, $queued -> _count monitoring_inbox|),
1237
+ _save_state NIL
1238
+ ].
1239
+ }
1240
+
1241
+ // Drain the queued monitoring copies (ROOT packet, host-fired before
1242
+ // forwarding to the bound proxy). Cleared on read, like get_messages.
1243
+ trn get_monitoring_copies _
1244
+ {
1245
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1246
+
1247
+ copies = monitoring_inbox.
1248
+ monitoring_inbox -> [].
1249
+ return transaction::success [
1250
+ _return_data ($copies -> copies),
1251
+ _save_state NIL
1252
+ ].
1253
+ }
1254
+
1255
+ // Drain the queued control requests (ROOT packet, host-fired by the
1256
+ // control dispatcher). Cleared on read.
1257
+ trn get_control_requests _
1258
+ {
1259
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1260
+
1261
+ reqs = control_inbox.
1262
+ control_inbox -> [].
1263
+ return transaction::success [
1264
+ _return_data ($requests -> reqs),
1265
+ _save_state NIL
1266
+ ].
1267
+ }
1268
+
1269
+ // Start a proxy binding (ROOT packet, host-fired): remember the code the
1270
+ // host generated (MUFL has no random source) for one specific contact.
1271
+ // Restarting overwrites any previous pending binding.
1272
+ trn set_proxy_pending _:($code -> code: str, $proxy -> proxy_ref: str)
1273
+ {
1274
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1275
+ abort "Only a root identity can bind a monitoring proxy." when a2a_messaging::delegation_cert != NIL.
1276
+
1277
+ pid = a2a_messaging::resolve_contact proxy_ref.
1278
+ proxy_pending -> (
1279
+ $code -> code,
1280
+ $proxy_cid -> pid,
1281
+ $created_at -> (current_transaction_info::get_transaction_time())?,
1282
+ $attempts -> 0
1283
+ ).
1284
+ return transaction::success [
1285
+ _return_data ($pending -> TRUE, $proxy_cid -> (_str pid)),
1286
+ _save_state NIL
1287
+ ].
1288
+ }
1289
+
1290
+ // Verify a proxy's code attempt (ROOT packet, host-fired when a `bind`
1291
+ // control request arrives). Failures are returned as DATA — not aborts —
1292
+ // so the attempt counter and expiry clearing persist atomically; an abort
1293
+ // would roll them back and reopen the brute-force window.
1294
+ trn verify_proxy_code _:($code -> code: str, $sender -> sender_ref: str)
1295
+ {
1296
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1297
+
1298
+ if proxy_pending == NIL
1299
+ {
1300
+ return transaction::success [ _return_data ($verified -> FALSE, $reason -> "no_pending") ].
1301
+ }
1302
+ p = proxy_pending?.
1303
+ now = (current_transaction_info::get_transaction_time())?.
1304
+
1305
+ if (_substract_seconds now (p $created_at)) > proxy_code_max_age_seconds
1306
+ {
1307
+ proxy_pending -> NIL.
1308
+ return transaction::success [
1309
+ _return_data ($verified -> FALSE, $reason -> "expired"),
1310
+ _save_state NIL
1311
+ ].
1312
+ }
1313
+
1314
+ sid = a2a_messaging::resolve_contact sender_ref.
1315
+ if sid != (p $proxy_cid)
1316
+ {
1317
+ // Not the contact this binding was started for: reject without
1318
+ // burning an attempt (the code was never compared).
1319
+ return transaction::success [ _return_data ($verified -> FALSE, $reason -> "wrong_sender") ].
1320
+ }
1321
+
1322
+ if code != (p $code)
1323
+ {
1324
+ attempts = (p $attempts) + 1.
1325
+ if attempts >= proxy_max_attempts
1326
+ {
1327
+ proxy_pending -> NIL.
1328
+ return transaction::success [
1329
+ _return_data ($verified -> FALSE, $reason -> "too_many_attempts"),
1330
+ _save_state NIL
1331
+ ].
1332
+ }
1333
+ proxy_pending -> (
1334
+ $code -> p $code,
1335
+ $proxy_cid -> p $proxy_cid,
1336
+ $created_at -> p $created_at,
1337
+ $attempts -> attempts
1338
+ ).
1339
+ return transaction::success [
1340
+ _return_data ($verified -> FALSE, $reason -> "wrong_code", $attempts_left -> proxy_max_attempts - attempts),
1341
+ _save_state NIL
1342
+ ].
1343
+ }
1344
+
1345
+ monitoring_proxy -> ($proxy_cid -> sid, $bound_at -> now).
1346
+ proxy_pending -> NIL.
1347
+ return transaction::success [
1348
+ _return_data ($verified -> TRUE, $proxy_cid -> (_str sid)),
1349
+ _save_state NIL
1350
+ ].
1351
+ }
1352
+
1353
+ // Drop the proxy binding (and any in-flight code verification).
1354
+ trn clear_monitoring_proxy _
1355
+ {
1356
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1357
+
1358
+ monitoring_proxy -> NIL.
1359
+ proxy_pending -> NIL.
1360
+ return transaction::success [
1361
+ _return_data ($cleared -> TRUE),
1362
+ _save_state NIL
1363
+ ].
1364
+ }
1365
+
1366
+ // ---- upgrade: state export / import -------------------------------------
1367
+ // The host persists state by calling export_state (readonly) and serializing
1368
+ // the returned value to a code-independent blob. On a code upgrade it also
1369
+ // persists the root SIGN secret (export_signing_secret) and recreates the
1370
+ // packet with that secret injected as init_arg; __init reseeds the identity
1371
+ // from it (reseed_identity_from_secret), which preserves the container
1372
+ // address regardless of the seed phrase or key-derivation used to recreate
1373
+ // the packet. The blob is then replayed through import_state.
1374
+ //
1375
+ // The packet-level snapshot is NOT used for upgrades: it is bound to the unit
1376
+ // code hash, so a new .muflo cannot load an old snapshot. This data blob is.
1377
+ //
1378
+ // The blob stays FLAT with the historical field names — the core fields come
1379
+ // from a2a_messaging::export_core_state / import_core_state, the app fields
1380
+ // are composed in here — so a PRE-migration export imports unchanged.
1381
+
1382
+ trn readonly export_state _
1383
+ {
1384
+ core_state = a2a_messaging::export_core_state NIL.
1385
+ return (
1386
+ $app_format_version -> 1,
1387
+ $my_name -> core_state $my_name,
1388
+ $contacts -> core_state $contacts,
1389
+ $pending_invites -> core_state $pending_invites,
1390
+ $inbox -> inbox,
1391
+ $next_msg_seq -> next_msg_seq,
1392
+ $file_inbox -> file_inbox,
1393
+ $next_file_seq -> next_file_seq,
1394
+ $peer_ads -> core_state $peer_ads,
1395
+ $registrar_ad -> registrar_ad,
1396
+ $local_auto_accept -> local_auto_accept,
1397
+ // Nonces are exported so a restart does not reopen the replay window
1398
+ // for still-fresh credentials; stale ones are purged lazily anyway.
1399
+ $seen_nonces -> seen_nonces,
1400
+ $pending_introductions -> pending_introductions,
1401
+ $my_bio -> core_state $my_bio,
1402
+ $delegation_cert -> core_state $delegation_cert,
1403
+ $root_ad -> core_state $root_ad,
1404
+ $root_profile -> core_state $root_profile,
1405
+ $contact_roots -> core_state $contact_roots,
1406
+ $monitoring_enabled -> monitoring_enabled,
1407
+ $monitoring_inbox -> monitoring_inbox,
1408
+ $proxy_pending -> proxy_pending,
1409
+ $monitoring_proxy -> monitoring_proxy,
1410
+ $control_inbox -> control_inbox
1411
+ ).
1412
+ }
1413
+
1414
+ trn import_state data: any
1415
+ {
1416
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1417
+
1418
+ // App-level format stamp (absent == 0, every pre-stamp blob). Same contract
1419
+ // as the core stamp (see a2a_messaging::import_core_state): additive fields
1420
+ // stay optional reads; a future BREAKING app-blob change dispatches here.
1421
+ app_fmt is int = 0.
1422
+ if (data $app_format_version) != NIL { app_fmt -> (data $app_format_version) safe int. }
1423
+ abort "App state blob format_version " + (_str app_fmt) + " is newer than this code (supports up to 1) — upgrade ours-tg-connector before importing." when app_fmt > 1.
1424
+
1425
+ // Core fields (contacts/profile/hierarchy) — validated and restored by
1426
+ // the shared library, which also replays every peer's address document
1427
+ // through process_address_document so encrypted channels keep working
1428
+ // after the upgrade with no re-handshake.
1429
+ a2a_messaging::import_core_state data.
1430
+
1431
+ // The inbox + next_msg_seq are the only parts the message-lifecycle changes
1432
+ // touched. A pre-lifecycle blob has no $next_msg_seq and inbox entries with
1433
+ // no id/status — MIGRATE it forward (the whole point of code-independent
1434
+ // state is that an old export upgrades, never resets): assign each legacy
1435
+ // message a sequential id and status "unread", and seed next_msg_seq past
1436
+ // them. A current-shape blob is loaded as-is except the gc vocabulary bump
1437
+ // ("read" -> "processed", see below).
1438
+ if (data $next_msg_seq) == NIL
1439
+ {
1440
+ legacy_inbox = (data $inbox) safe (legacy_message_t[]).
1441
+ migrated is message_t[] = [].
1442
+ seq is int = 1.
1443
+ sc legacy_inbox -- ( -> m)
1444
+ {
1445
+ migrated (_count migrated|) -> (
1446
+ $msg_id -> seq,
1447
+ $sender_id -> m $sender_id,
1448
+ $sender_name -> m $sender_name,
1449
+ $text -> m $text,
1450
+ $date -> m $date,
1451
+ $status -> "unread",
1452
+ $wire_id -> "",
1453
+ $reply_to -> NIL
1454
+ ).
1455
+ seq -> seq + 1.
1456
+ }
1457
+ inbox -> migrated.
1458
+ next_msg_seq -> seq.
1459
+ }
1460
+ else
1461
+ {
1462
+ // Current-shape blob, read field-by-field (NOT a strict message_t[]
1463
+ // cast) so a pre-1.4 blob — whose messages have no $wire_id/$reply_to
1464
+ // — imports without aborting on the now-required $wire_id. Two
1465
+ // forward-migrations: the old "read" status -> "processed" (else the
1466
+ // message is stuck: never returned, gc'd, or deferred), and absent
1467
+ // wire_id/reply_to default to "" / NIL.
1468
+ upgraded is message_t[] = [].
1469
+ sc (data $inbox) -- ( -> m)
1470
+ {
1471
+ mstatus = (((m $status) safe str) == "read" ?? "processed" ; (m $status) safe str).
1472
+ mwire is str = "".
1473
+ if (m $wire_id) != NIL { mwire -> (m $wire_id) safe str. }
1474
+ mreply is a2a_protocol::reply_ref_t+ = NIL.
1475
+ if (m $reply_to) != NIL { mreply -> (m $reply_to) safe a2a_protocol::reply_ref_t. }
1476
+ upgraded (_count upgraded|) -> (
1477
+ $msg_id -> (m $msg_id) safe int,
1478
+ $sender_id -> (m $sender_id) safe global_id,
1479
+ $sender_name -> (m $sender_name) safe str,
1480
+ $text -> (m $text) safe str,
1481
+ $date -> (m $date) safe time,
1482
+ $status -> mstatus,
1483
+ $wire_id -> mwire,
1484
+ $reply_to -> mreply
1485
+ ).
1486
+ }
1487
+ inbox -> upgraded.
1488
+ next_msg_seq -> (data $next_msg_seq) safe int.
1489
+ }
1490
+
1491
+ // Local-contact-book state arrived after the original schema — every
1492
+ // field is optional in old blobs and defaults stay in place when absent.
1493
+ if (data $registrar_ad) != NIL
1494
+ {
1495
+ registrar_ad -> (data $registrar_ad) safe address_document_types::t_address_document.
1496
+ }
1497
+ if (data $local_auto_accept) != NIL
1498
+ {
1499
+ local_auto_accept -> (data $local_auto_accept) safe bool.
1500
+ }
1501
+ if (data $seen_nonces) != NIL
1502
+ {
1503
+ seen_nonces -> (data $seen_nonces) safe (global_id ->> time).
1504
+ }
1505
+ if (data $pending_introductions) != NIL
1506
+ {
1507
+ pending_introductions -> (data $pending_introductions) safe (global_id ->> pending_intro_t).
1508
+ }
1509
+
1510
+ // Monitoring + control state arrived after the local-book schema —
1511
+ // optional in old blobs the same way.
1512
+ if (data $monitoring_enabled) != NIL
1513
+ {
1514
+ monitoring_enabled -> (data $monitoring_enabled) safe bool.
1515
+ }
1516
+ if (data $monitoring_inbox) != NIL
1517
+ {
1518
+ monitoring_inbox -> (data $monitoring_inbox) safe (monitoring_copy_t[]).
1519
+ }
1520
+ if (data $proxy_pending) != NIL
1521
+ {
1522
+ proxy_pending -> (data $proxy_pending) safe proxy_pending_t.
1523
+ }
1524
+ if (data $monitoring_proxy) != NIL
1525
+ {
1526
+ monitoring_proxy -> (data $monitoring_proxy) safe proxy_binding_t.
1527
+ }
1528
+ if (data $control_inbox) != NIL
1529
+ {
1530
+ control_inbox -> (data $control_inbox) safe (control_req_t[]).
1531
+ }
1532
+
1533
+ // File store arrived with core 3.1 — optional in pre-3.1 blobs; defaults
1534
+ // ([] / 1) stay in place when absent, so an old export imports unchanged.
1535
+ if (data $next_file_seq) != NIL
1536
+ {
1537
+ next_file_seq -> (data $next_file_seq) safe int.
1538
+ }
1539
+ if (data $file_inbox) != NIL
1540
+ {
1541
+ file_inbox -> (data $file_inbox) safe (file_t[]).
1542
+ }
1543
+
1544
+ // Pending introducers' keys too: their channel to me predates approval,
1545
+ // so it must survive an upgrade exactly like an approved contact's.
1546
+ sc pending_introductions -- ( -> p)
1547
+ {
1548
+ address_document::process_address_document (p $ad) TRUE.
1549
+ }
1550
+
1551
+ return transaction::success [
1552
+ _return_data ($imported -> TRUE, $contacts -> _count a2a_messaging::contacts|, $peers -> _count a2a_messaging::peer_ads|),
1553
+ _save_state NIL
1554
+ ].
1555
+ }
1556
+
1557
+ // ---- external (inbound) transactions ------------------------------------
1558
+
1559
+ // Compat shims (Option A): pre-migration peers address these as ::actor::*,
1560
+ // and the core keeps SENDING to the ::actor:: names too. Each delegates to
1561
+ // the shared handler — remove only when no old clients remain.
1562
+ trn accept_contact args: any
1563
+ {
1564
+ return a2a_messaging::handle_accept_contact args.
1565
+ }
1566
+
1567
+ trn receive_message args: any
1568
+ {
1569
+ return a2a_messaging::handle_receive_message args.
1570
+ }
1571
+
1572
+ // A same-host peer connects via the local contact book. The credential must
1573
+ // have been minted by THIS HOST's registrar for THIS sender and THIS target,
1574
+ // recently, and never seen before — five checks that together make the book
1575
+ // path unusable from outside the host:
1576
+ // 1. registrar signature over the credential (pinned key list)
1577
+ // 2. envelope $from == credential.joiner_cid (no splicing someone
1578
+ // else's credential onto your own channel)
1579
+ // 3. hash(joiner_ad) == credential.joiner_ad_hash (no AD substitution)
1580
+ // 4. credential.target_cid == me (no cross-target reuse)
1581
+ // 5. freshness window + unseen nonce (no replay)
1582
+ // The encrypted channel itself authenticates that the sender controls its
1583
+ // keys, so no extra challenge-response is needed.
1584
+ trn local_introduce _:($joiner_name -> joiner_name: str, $joiner_ad -> joiner_ad: address_document_types::t_address_document, $intro -> intro_blob: bin, $text -> text: str+)
1585
+ {
1586
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1587
+ encrypted_channel::check_encrypted_or_abort().
1588
+
1589
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1590
+ abort "This identity does not accept local-contact-book introductions." when registrar_ad == NIL.
1591
+
1592
+ signed = (_read_or_abort intro_blob) safe a2a_protocol::signed_intro_t.
1593
+ intro = signed $i.
1594
+ abort "Unsupported introduction credential version." when (intro $version) != 1.
1595
+ abort "Introduction credential was not signed by this host's registrar." when key_storage::check_signature_new_container (_value_id intro) (signed $s) (registrar_ad? $identity $key_list) != TRUE.
1596
+ abort "Introduction credential was minted for a different sender." when (intro $joiner_cid) != sender_id.
1597
+ abort "Introduction credential does not match the sender's address document." when (intro $joiner_ad_hash) != _value_id joiner_ad.
1598
+ abort "Introduction credential targets a different identity." when (intro $target_cid) != _get_container_id().
1599
+
1600
+ now = (current_transaction_info::get_transaction_time())?.
1601
+ age = _substract_seconds now (intro $iat).
1602
+ abort "Introduction credential is outside its freshness window." when age > intro_max_age_seconds || age < (0 - intro_max_skew_seconds).
1603
+
1604
+ // Lazy nonce GC (drop everything past the retention horizon), then the
1605
+ // replay check, then a hard cap so a misbehaving local peer cannot bloat
1606
+ // packet state inside the window.
1607
+ horizon = intro_max_age_seconds + intro_max_skew_seconds.
1608
+ fresh_nonces is (global_id ->> time) = (,).
1609
+ sc seen_nonces -- (n -> t)
1610
+ {
1611
+ if (_substract_seconds now t) <= horizon { fresh_nonces n -> t. }
1612
+ }
1613
+ seen_nonces -> fresh_nonces.
1614
+ abort "Replayed introduction credential." when seen_nonces (intro $nonce) != NIL.
1615
+ abort "Too many concurrent introductions; try again shortly." when (_count seen_nonces|) >= seen_nonce_cap.
1616
+ seen_nonces (intro $nonce) -> now.
1617
+
1618
+ existing = a2a_messaging::contacts sender_id.
1619
+ if existing != NIL
1620
+ {
1621
+ // Already a contact (idempotent re-introduction): keep my assigned
1622
+ // name, refresh the stored address document, deliver any payload.
1623
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1624
+ if text != NIL
1625
+ {
1626
+ mid = deposit_message sender_id (existing? $name) text? now "" no_reply.
1627
+ return transaction::success [
1628
+ _notify_agent ($event -> $message_received, $sender_name -> existing? $name, $msg_id -> mid, $date -> now),
1629
+ _save_state NIL
1630
+ ].
1631
+ }
1632
+ return transaction::success [ _save_state NIL ].
1633
+ }
1634
+
1635
+ if local_auto_accept
1636
+ {
1637
+ a2a_messaging::contacts sender_id -> ($name -> joiner_name, $container_id -> sender_id).
1638
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1639
+ if text != NIL
1640
+ {
1641
+ mid = deposit_message sender_id joiner_name text? now "" no_reply.
1642
+ return transaction::success [
1643
+ _notify_agent ($event -> $local_contact_added, $name -> joiner_name, $container_id -> sender_id),
1644
+ _notify_agent ($event -> $message_received, $sender_name -> joiner_name, $msg_id -> mid, $date -> now),
1645
+ _save_state NIL
1646
+ ].
1647
+ }
1648
+ return transaction::success [
1649
+ _notify_agent ($event -> $local_contact_added, $name -> joiner_name, $container_id -> sender_id),
1650
+ _save_state NIL
1651
+ ].
1652
+ }
1653
+
1654
+ // Pending-approval policy: park the introduction (with its optional
1655
+ // first message) until approve_introduction / reject_introduction.
1656
+ queued is pending_msg_t[] = [].
1657
+ if text != NIL { queued 0 -> ($text -> text?, $date -> now). }
1658
+ pending_introductions sender_id -> ($name -> joiner_name, $ad -> joiner_ad, $messages -> queued).
1659
+ return transaction::success [
1660
+ _notify_agent ($event -> $local_contact_request, $name -> joiner_name, $container_id -> sender_id, $queued -> _count queued|),
1661
+ _save_state NIL
1662
+ ].
1663
+ }
1664
+
1665
+ // An intra-root peer connects (Ring 1 of the identity hierarchy). Trust is
1666
+ // the delegation cert, not a registrar credential: the sender presents a
1667
+ // cert that must (a) name MY root, (b) verify against my root's keys,
1668
+ // (c) name the sender as the role, and (d) match the sender's address
1669
+ // document. The encrypted channel authenticates that the sender controls
1670
+ // its keys, and a cert is useless on anyone else's channel because of (c) —
1671
+ // so no nonce/freshness machinery is needed; the cert is a standing
1672
+ // credential, revoked by deleting the role (the root simply stops vouching).
1673
+ // A cert-less introduction is accepted ONLY from my root itself (the root
1674
+ // has no cert; the channel proves it controls the root's keys).
1675
+ // Intra-root introductions auto-accept regardless of local_auto_accept —
1676
+ // implicit trust inside the root is the point of Ring 1.
1677
+ trn sibling_introduce _:($joiner_name -> joiner_name: str, $joiner_ad -> joiner_ad: address_document_types::t_address_document, $cert -> cert_blob: bin+, $text -> text: str+)
1678
+ {
1679
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1680
+ encrypted_channel::check_encrypted_or_abort().
1681
+
1682
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1683
+ now = (current_transaction_info::get_transaction_time())?.
1684
+
1685
+ link is a2a_protocol::contact_root_t+ = NIL.
1686
+ if cert_blob == NIL
1687
+ {
1688
+ // Sender claims to be my root.
1689
+ abort "A certificate-less sibling introduction is only accepted from my root." when a2a_messaging::delegation_cert == NIL.
1690
+ abort "Sender is not my root." when sender_id != (a2a_messaging::delegation_cert? $c $root_cid).
1691
+ link -> ($root_cid -> sender_id, $root_name -> joiner_name, $role_id -> "").
1692
+ }
1693
+ else
1694
+ {
1695
+ cert = (_read_or_abort cert_blob?) safe a2a_protocol::delegation_cert_t.
1696
+ abort "Unsupported delegation certificate version." when (cert $c $version) != 1.
1697
+ abort "Sibling certificate was issued for a different sender." when (cert $c $role_cid) != sender_id.
1698
+ abort "Sibling certificate does not match the sender's address document." when (cert $c $role_ad_hash) != (_value_id joiner_ad).
1699
+
1700
+ root_name_known is str = "".
1701
+ if a2a_messaging::delegation_cert != NIL
1702
+ {
1703
+ // I am a role: the cert must name MY root and verify against the
1704
+ // root key material pinned at delegation time.
1705
+ abort "My root material is missing — cannot verify sibling certificates." when a2a_messaging::root_ad == NIL.
1706
+ abort "Sibling certificate names a different root." when (cert $c $root_cid) != (a2a_messaging::delegation_cert? $c $root_cid).
1707
+ abort "Sibling certificate was not signed by my root." when key_storage::check_signature_new_container (_value_id (cert $c)) (cert $s) (a2a_messaging::root_ad? $identity $key_list) != TRUE.
1708
+ if a2a_messaging::root_profile != NIL { root_name_known -> a2a_messaging::root_profile? $p $name. }
1709
+ }
1710
+ else
1711
+ {
1712
+ // I have no cert: I only accept certs that *I* issued, i.e. I am
1713
+ // the root. A legacy flat identity fails this check by design.
1714
+ abort "Sibling certificate names a different root." when (cert $c $root_cid) != _get_container_id().
1715
+ my_ad = address_document::get_my_address_document().
1716
+ abort "Sibling certificate was not signed by me." when key_storage::check_signature_new_container (_value_id (cert $c)) (cert $s) (my_ad $identity $key_list) != TRUE.
1717
+ root_name_known -> a2a_messaging::my_name.
1718
+ }
1719
+ link -> ($root_cid -> cert $c $root_cid, $root_name -> root_name_known, $role_id -> cert $c $role_id).
1720
+ }
1721
+
1722
+ existing = a2a_messaging::contacts sender_id.
1723
+ if existing != NIL
1724
+ {
1725
+ // Already a contact (idempotent re-introduction): keep my assigned
1726
+ // name, refresh the stored material, deliver any payload.
1727
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1728
+ a2a_messaging::contact_roots sender_id -> link?.
1729
+ if text != NIL
1730
+ {
1731
+ mid = deposit_message sender_id (existing? $name) text? now "" no_reply.
1732
+ return transaction::success [
1733
+ _notify_agent ($event -> $message_received, $sender_name -> existing? $name, $msg_id -> mid, $date -> now),
1734
+ _save_state NIL
1735
+ ].
1736
+ }
1737
+ return transaction::success [ _save_state NIL ].
1738
+ }
1739
+
1740
+ a2a_messaging::contacts sender_id -> ($name -> joiner_name, $container_id -> sender_id).
1741
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1742
+ a2a_messaging::contact_roots sender_id -> link?.
1743
+ if text != NIL
1744
+ {
1745
+ mid = deposit_message sender_id joiner_name text? now "" no_reply.
1746
+ return transaction::success [
1747
+ _notify_agent ($event -> $sibling_contact_added, $name -> joiner_name, $container_id -> sender_id),
1748
+ _notify_agent ($event -> $message_received, $sender_name -> joiner_name, $msg_id -> mid, $date -> now),
1749
+ _save_state NIL
1750
+ ].
1751
+ }
1752
+ return transaction::success [
1753
+ _notify_agent ($event -> $sibling_contact_added, $name -> joiner_name, $container_id -> sender_id),
1754
+ _save_state NIL
1755
+ ].
1756
+ }
1757
+ }