@ours.network/tg-connector 0.3.3-nightly.4 → 0.4.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 (96) hide show
  1. package/README.md +114 -27
  2. package/dist/cli.js +98 -68
  3. package/dist/connector.js +24758 -68938
  4. package/dist/mufl_code/ED9CAFA60E1A0884E2CBC8E71BA8A137488A14763C57587D25AEC4BAD7F58C81.muflo +0 -0
  5. package/dist/mufl_code/actor.mu +1937 -0
  6. package/dist/mufl_code/config.mufl +27 -0
  7. package/dist/mufl_code/core/COMMERCIAL-LICENCE.md +25 -0
  8. package/dist/mufl_code/core/COMPATIBILITY.md +221 -0
  9. package/dist/mufl_code/core/CONTRIBUTING.md +37 -0
  10. package/dist/mufl_code/core/LICENSE +98 -0
  11. package/dist/mufl_code/core/NOTIFICATIONS_CONTRACT.md +290 -0
  12. package/dist/mufl_code/core/README.md +91 -0
  13. package/dist/mufl_code/core/SECURITY.md +40 -0
  14. package/dist/mufl_code/core/TRADEMARKS.md +24 -0
  15. package/dist/mufl_code/core/a2a_capabilities.mm +449 -0
  16. package/dist/mufl_code/core/a2a_cluster.mm +601 -0
  17. package/dist/mufl_code/core/a2a_control.mm +90 -0
  18. package/dist/mufl_code/core/a2a_messaging.mm +4817 -0
  19. package/dist/mufl_code/core/a2a_monitoring.mm +94 -0
  20. package/dist/mufl_code/core/a2a_notification_integration.mm +144 -0
  21. package/dist/mufl_code/core/a2a_notifications.mm +1127 -0
  22. package/dist/mufl_code/core/a2a_protocol.mm +246 -0
  23. package/dist/mufl_code/core/a2a_versions.mm +801 -0
  24. package/dist/mufl_code/core/config.mufl +29 -0
  25. package/dist/mufl_code/core/docs/.vitepress/config.mts +58 -0
  26. package/dist/mufl_code/core/docs/citations.json +688 -0
  27. package/dist/mufl_code/core/docs/guide/01-vendor-the-core.md +50 -0
  28. package/dist/mufl_code/core/docs/guide/02-configure-and-compile.md +100 -0
  29. package/dist/mufl_code/core/docs/guide/03-wire-the-host.md +154 -0
  30. package/dist/mufl_code/core/docs/guide/04-connect-and-message.md +156 -0
  31. package/dist/mufl_code/core/docs/guide/05-test-your-app.md +75 -0
  32. package/dist/mufl_code/core/docs/guide/index.md +63 -0
  33. package/dist/mufl_code/core/docs/how-it-works/capabilities-and-control.md +77 -0
  34. package/dist/mufl_code/core/docs/how-it-works/cluster.md +65 -0
  35. package/dist/mufl_code/core/docs/how-it-works/identity.md +56 -0
  36. package/dist/mufl_code/core/docs/how-it-works/invites-and-contacts.md +76 -0
  37. package/dist/mufl_code/core/docs/how-it-works/messaging.md +55 -0
  38. package/dist/mufl_code/core/docs/how-it-works/monitoring-and-config.md +72 -0
  39. package/dist/mufl_code/core/docs/how-it-works/overview.md +45 -0
  40. package/dist/mufl_code/core/docs/how-it-works/versioning.md +116 -0
  41. package/dist/mufl_code/core/docs/index.md +27 -0
  42. package/dist/mufl_code/core/docs/package-lock.json +3467 -0
  43. package/dist/mufl_code/core/docs/package.json +15 -0
  44. package/dist/mufl_code/core/docs/reference/contributing.md +26 -0
  45. package/dist/mufl_code/core/docs/reference/glossary.md +108 -0
  46. package/dist/mufl_code/core/docs/reference/implementations.md +23 -0
  47. package/dist/mufl_code/core/docs/reference/modules.md +19 -0
  48. package/dist/mufl_code/core/docs/scripts/check-citations.mjs +36 -0
  49. package/dist/mufl_code/core/docs/scripts/check-denylist.mjs +30 -0
  50. package/dist/mufl_code/core/docs/scripts/gen-llms.mjs +32 -0
  51. package/dist/mufl_code/core/docs/workflows/cluster.md +89 -0
  52. package/dist/mufl_code/core/docs/workflows/contact-exchange.md +60 -0
  53. package/dist/mufl_code/core/docs/workflows/contact-restore.md +60 -0
  54. package/dist/mufl_code/core/docs/workflows/control-verbs.md +70 -0
  55. package/dist/mufl_code/core/docs/workflows/index.md +57 -0
  56. package/dist/mufl_code/core/docs/workflows/introductions.md +60 -0
  57. package/dist/mufl_code/core/docs/workflows/messaging.md +75 -0
  58. package/dist/mufl_code/core/docs/workflows/monitoring.md +84 -0
  59. package/dist/mufl_code/core/docs/workflows/notifications.md +109 -0
  60. package/dist/mufl_code/core/release-notes/0.1.md +60 -0
  61. package/dist/mufl_code/core/release-notes/0.3.md +22 -0
  62. package/dist/mufl_code/core/release-notes/0.4.md +97 -0
  63. package/dist/mufl_code/core/tests/README.md +83 -0
  64. package/dist/mufl_code/core/tests/compat/README.md +82 -0
  65. package/dist/mufl_code/core/tests/compat/compat.mjs +245 -0
  66. package/dist/mufl_code/core/tests/compat/compat_peer.mjs +146 -0
  67. package/dist/mufl_code/core/tests/compat/run_compat.sh +96 -0
  68. package/dist/mufl_code/core/tests/corpus.mjs +139 -0
  69. package/dist/mufl_code/core/tests/corpus_actor.mu +242 -0
  70. package/dist/mufl_code/core/tests/fatcompile_actor.mu +52 -0
  71. package/dist/mufl_code/core/tests/mig.mjs +805 -0
  72. package/dist/mufl_code/core/tests/mig_actor.mu +518 -0
  73. package/dist/mufl_code/core/tests/migapp.mjs +431 -0
  74. package/dist/mufl_code/core/tests/migapp_actor.mu +294 -0
  75. package/dist/mufl_code/core/tests/mufl_semantics/run.sh +69 -0
  76. package/dist/mufl_code/core/tests/mufl_semantics/t11_three_version.mufl +47 -0
  77. package/dist/mufl_code/core/tests/mufl_semantics/t2_extra_fields.mufl +11 -0
  78. package/dist/mufl_code/core/tests/mufl_semantics/t7_runtime.mufl +30 -0
  79. package/dist/mufl_code/core/tests/mufl_semantics/t9_passthrough.mufl +19 -0
  80. package/dist/mufl_code/core/tests/mufl_semantics/t_str_order.mufl +19 -0
  81. package/dist/mufl_code/core/tests/notif.mjs +755 -0
  82. package/dist/mufl_code/core/tests/notif_actor.mu +450 -0
  83. package/dist/mufl_code/core/tests/protocol_container.mm +18 -0
  84. package/dist/mufl_code/core/tests/run.sh +65 -0
  85. package/dist/mufl_code/core/tests/run_corpus.sh +51 -0
  86. package/dist/mufl_code/core/tests/run_fatcompile.sh +40 -0
  87. package/dist/mufl_code/core/tests/run_mig.sh +51 -0
  88. package/dist/mufl_code/core/tests/run_migapp.sh +51 -0
  89. package/dist/mufl_code/core/tests/run_notif.sh +57 -0
  90. package/dist/mufl_code/core/tests/test.mjs +750 -0
  91. package/dist/mufl_code/core/tests/test_actor.mu +564 -0
  92. package/dist/mufl_code/core/tests/test_common.mjs +93 -0
  93. package/dist/mufl_code/core/version.mm +24 -0
  94. package/dist/mufl_code/protocol_container.mm +18 -0
  95. package/docs/voice-message-contract.md +2 -8
  96. package/package.json +5 -3
@@ -0,0 +1,1937 @@
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
+ // core 0.7.0 receipts. A peer confirmed delivery ("delivered") or
439
+ // reading ("read") of messages WE sent; the daemon turns each wire_id
440
+ // into a reaction on the Telegram message that produced it. Nothing is
441
+ // stored packet-side: receipts are best-effort UX by core's own
442
+ // contract, never load-bearing, so a lost notify costs one reaction and
443
+ // nothing else — hence no _save_state here either (core adds its own
444
+ // when the receipt retires an unacked-redrive entry).
445
+ //
446
+ // $wire_ids is rebuilt element by element rather than cast wholesale:
447
+ // core already validated the shape, and this keeps the notify payload
448
+ // a plain str[] the host decodes with the same loop it uses for an inbox.
449
+ $on_receipt_received -> fn (arg: any) -> transaction::action::type[]
450
+ {
451
+ ids is str[] = [].
452
+ sc (arg $wire_ids) -- ( -> w)
453
+ {
454
+ ids (_count ids|) -> (w safe str).
455
+ }
456
+ if (_count ids|) == 0 { return []. }
457
+ return [ _notify_agent (
458
+ $event -> $receipt_received,
459
+ $sender_id -> (arg $sender_id) safe global_id,
460
+ $kind -> (arg $kind) safe str,
461
+ $wire_ids -> ids
462
+ ) ].
463
+ }
464
+ ).
465
+
466
+ // Wire the control plane (see MONITORING-AND-SHARED-LIBRARY-DESIGN.md
467
+ // Part 4): control requests from the bound browser proxy queue in
468
+ // control_inbox — NEVER the message inbox, so agent sessions don't see
469
+ // them — and the notify event wakes the daemon's dispatcher. The
470
+ // payload stays opaque here; sender authorization happens in the
471
+ // daemon against the packet's monitoring_proxy / proxy_pending state.
472
+ a2a_control::init (
473
+ $app_id -> "network.ours.telegram-connector",
474
+ $on_control_received -> fn (arg: any) -> transaction::action::type[]
475
+ {
476
+ abort "Control queue is full." when (_count control_inbox|) >= control_inbox_cap.
477
+ sender_name = (arg $sender_name) safe str.
478
+ control_inbox (_count control_inbox|) -> (
479
+ $sender_cid -> (arg $sender_id) safe global_id,
480
+ $sender_name -> sender_name,
481
+ $payload -> (arg $payload) safe str,
482
+ $date -> (arg $date) safe time
483
+ ).
484
+ return [
485
+ _notify_agent ($event -> $control_request, $sender_name -> sender_name, $queued -> _count control_inbox|),
486
+ _save_state NIL
487
+ ].
488
+ }
489
+ ).
490
+
491
+ // ---- capabilities manifest (core.connect) -----------------------------
492
+ // THE SINGLE ENABLEMENT BOOLEAN. Flipping this to FALSE removes core.connect
493
+ // from the live manifest, which (a) hides the Connect surface in any bound
494
+ // control plane and (b) makes the core node-side gate in
495
+ // ::a2a_messaging::ingest_connect_descriptor reject every introduction
496
+ // (it reads a2a_capabilities::self_supports("core.connect"), i.e. this
497
+ // manifest). There is NO other connect code in this app: the ingest
498
+ // transaction lives entirely in the shared core, so enabling/disabling the
499
+ // feature is exactly this flag — zero application logic.
500
+ supports_connect is bool = TRUE.
501
+
502
+ // The node's live self-description (a2a_capabilities::app_manifest_t),
503
+ // served on ::a2a_capabilities::get_manifest and read by self_supports.
504
+ // core.configuration is always present (the daemon renders its config
505
+ // schema); core.connect is present iff supports_connect. Neither has a
506
+ // packet-side verb handler — configuration is daemon-mediated and connect
507
+ // is the dedicated core ingest tx — so $supported (below) stays empty.
508
+ fn build_manifest (_: any) -> a2a_capabilities::app_manifest_t
509
+ {
510
+ caps is (str ->> a2a_capabilities::capability_t) = (,).
511
+ caps a2a_capabilities::cap_configuration -> (
512
+ $cap -> a2a_capabilities::cap_configuration,
513
+ $version -> 1,
514
+ $params -> "",
515
+ $secrets -> (,)
516
+ ).
517
+ if supports_connect
518
+ {
519
+ caps a2a_capabilities::cap_connect -> (
520
+ $cap -> a2a_capabilities::cap_connect,
521
+ $version -> 1,
522
+ $params -> "",
523
+ $secrets -> (,)
524
+ ).
525
+ }
526
+ // core 0.8.0/0.9.0 — end-to-end double-ratchet + its migration FSM. The
527
+ // connector runs the DR-routing core unconditionally, so it always speaks
528
+ // the e2e_signed_message envelope (core.e2e) and participates in the
529
+ // per-connection migration handshake (core.e2e.migrate). Advertised here so
530
+ // a controller's get_manifest / self_supports sees them; the peer-facing
531
+ // auto-migration trigger is driven by the $advertise wire piggyback below
532
+ // (self_advertises reads init's $advertise, not this describe() map).
533
+ caps a2a_capabilities::cap_e2e -> (
534
+ $cap -> a2a_capabilities::cap_e2e,
535
+ $version -> 1,
536
+ $params -> "",
537
+ $secrets -> (,)
538
+ ).
539
+ caps a2a_capabilities::cap_e2e_migrate -> (
540
+ $cap -> a2a_capabilities::cap_e2e_migrate,
541
+ $version -> 1,
542
+ $params -> "",
543
+ $secrets -> (,)
544
+ ).
545
+ // core 0.7.0 receipts. BOTH halves, and both are load-bearing here:
546
+ // `receive` is what makes a peer's receipt_gate let its confirmations
547
+ // through to us (that is what becomes a Telegram reaction), and `emit`
548
+ // is required by our OWN gate before we may send any — including the
549
+ // read receipts get_messages / get_files emit on the consumer path.
550
+ // Advertised in describe() for a bound control plane; the wire-level
551
+ // half that peers actually learn is the $advertise list below.
552
+ caps a2a_capabilities::cap_receipts_emit -> (
553
+ $cap -> a2a_capabilities::cap_receipts_emit,
554
+ $version -> 1,
555
+ $params -> "",
556
+ $secrets -> (,)
557
+ ).
558
+ caps a2a_capabilities::cap_receipts_receive -> (
559
+ $cap -> a2a_capabilities::cap_receipts_receive,
560
+ $version -> 1,
561
+ $params -> "",
562
+ $secrets -> (,)
563
+ ).
564
+ return (
565
+ $version -> 1,
566
+ $app_id -> "network.ours.telegram-connector",
567
+ $name -> a2a_messaging::my_name,
568
+ $description -> a2a_messaging::my_bio,
569
+ $monitoring_status -> "unbound",
570
+ $capabilities -> caps
571
+ ).
572
+ }
573
+
574
+ // Wire the capabilities library. $supported lists only caps with a packet
575
+ // VERB handler (init fail-fasts if any lacks one) — this app has none, so
576
+ // it is empty. core.connect MUST NOT appear here: it has no verb handler
577
+ // and would abort init; "supports introductions" is core.connect living in
578
+ // describe()'s live $capabilities map (above), per RELEASE_NOTES §B2.
579
+ a2a_capabilities::init (
580
+ $describe -> build_manifest,
581
+ $supported -> [],
582
+ // $advertise (core 0.9.0): PROTOCOL-surface capability ids carried on the
583
+ // wire piggyback ($caps in invite/restore/migration legs) -> self_caps, so
584
+ // self_advertises(cap_e2e_migrate)=TRUE (which gates mig_should_trigger) AND
585
+ // peers LEARN these into contact_caps. This — not the $describe manifest — is
586
+ // what makes an existing contact auto-migrate to the double ratchet once both
587
+ // sides advertise (§5.4). No handler needed (unlike $supported): these ids
588
+ // gate traffic shaping only and never route through dispatch.
589
+ //
590
+ // cap_e2e_rekey (core 0.11): lets a peer REPAIR a diverged DR session with
591
+ // us instead of waiting for one to re-establish by accident. A peer that
592
+ // detects divergence checks peer_supports_rekey (a2a_messaging.mm:1100 at
593
+ // core pin edbb11ad) on US before it will send anything at all — so while
594
+ // this id was absent, three separate paths were hard-stopped against us:
595
+ // maybe_init_rekey (:1211, never mints), redrive_unacked_actions (:1114,
596
+ // returns []) and rekey_ping_actions (:1143, returns []). The responder is
597
+ // core-side and library-routed (e2e_rekey_request_tx, :100 -> trn :3827 ->
598
+ // handle_e2e_rekey_request :3751), inherited by any actor loading
599
+ // a2a_messaging, so this advertisement is all that was missing.
600
+ //
601
+ // SAFETY — this id is a VERSION CLAIM, not just "I answer rekey": both
602
+ // cap-gates above exist because a pre-0.11 peer would deposit unrecognized
603
+ // duplicates on redrive and would render a $rekey_ping bootstrap AS AN APP
604
+ // MESSAGE. Advertising it from a pre-0.11 core would therefore be a harmful
605
+ // false yes. Checked before adding: the deployed connector packet carries
606
+ // core.e2e.rekey, rekey_ping, delivered_wire, unacked_e2e and
607
+ // e2e_rekey_request — i.e. its core already has receive-side wire_id dedup
608
+ // and understands the ping. The npm version string (0.1.8-nightly.4 on the
609
+ // running bridge) is NOT a proxy for the compiled core version; they are
610
+ // different objects and only the packet answers this question.
611
+ //
612
+ // cap_receipts_emit / cap_receipts_receive (core 0.7.0): the pair that
613
+ // opens receipt_gate (a2a_messaging.mm:1408). The gate is asymmetric —
614
+ // a SENDER emits only when it advertises `emit` AND the peer's learned
615
+ // caps carry `receive`. So `receive` here is what lets an agent's node
616
+ // send us the delivered/read confirmations we render as reactions, and
617
+ // `emit` is what lets US answer with the read receipts get_messages /
618
+ // get_files raise on their consumer path. Safe to claim: the receipt
619
+ // ingest transaction and the emit builders are core-side and inherited
620
+ // by any actor loading a2a_messaging (pin edbb11ad, core 0.9.0 > 0.7.0),
621
+ // and the receive side is a real consumer here, not a stub — the
622
+ // $on_receipt_received hook above forwards every event to the daemon.
623
+ $advertise -> [ a2a_capabilities::cap_e2e, a2a_capabilities::cap_e2e_migrate,
624
+ a2a_capabilities::cap_e2e_rekey,
625
+ a2a_capabilities::cap_receipts_emit,
626
+ a2a_capabilities::cap_receipts_receive ],
627
+ $handlers -> (,),
628
+ $on_unknown -> fn (_: any) -> transaction::action::type[] { return []. }
629
+ ).
630
+ }
631
+
632
+ // On recreation the host injects the persisted SIGN secret as init_arg: the
633
+ // hex string of the Serialize()'d secretkey_sign. Deserialize it back
634
+ // (_hex_string_to_binary -> _read_or_abort) and reseed to restore the
635
+ // container address (adapt #77). Fresh-create passes no arg and the
636
+ // bootstrapped identity stands.
637
+ trn __init arg
638
+ {
639
+ // Fresh create passes no init_arg — the wrapper hands __init an empty
640
+ // dict (not nil), so guard on the actual string type before deserializing
641
+ // the persisted SIGN secret (Serialize()-hex) and reseeding (adapt #77).
642
+ if _typeof arg == "STRING" {
643
+ key_storage::reseed_identity_from_secret
644
+ ((_read_or_abort (_hex_string_to_binary (arg SAFE(str)))) SAFE(secretkey_sign)).
645
+ }
646
+ return ::transaction::success[].
647
+ }
648
+
649
+ // ---- message store --------------------------------------------------------
650
+
651
+ trn readonly list_incoming_messages _
652
+ {
653
+ return inbox.
654
+ }
655
+
656
+ trn readonly list_incoming_files _
657
+ {
658
+ return file_inbox.
659
+ }
660
+
661
+ // Hand the agent every message it has not seen yet (status "unread") and flip
662
+ // those to "processed" — the ONLY place message bodies leave the packet, and
663
+ // the sole dedup point: a message is returned exactly once, so an agent that
664
+ // reads and acts immediately never double-processes. CRASH WINDOW: a
665
+ // "processed" body has already left; an agent that crashes after get_messages
666
+ // but before acting must defer_messages to recover it (-> "unread") before gc
667
+ // promotes it through "ready_to_delete" and deletes it (>= 1 gc cycle).
668
+ trn get_messages _
669
+ {
670
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
671
+
672
+ fresh is message_t[] = [].
673
+ new_inbox is message_t[] = [].
674
+ // core 0.7.0 READ receipts ride exactly this transition. A readonly trn
675
+ // cannot emit sends, so the unread->processed MARK *is* the read event: we
676
+ // collect the wire_ids we just flipped, grouped by sender (one receipt per
677
+ // peer covers many ids), and emit below. Because the ids come from the
678
+ // transition and not from the inbox, emission is exact-once for free — a
679
+ // second get_messages finds nothing unread and sends nothing.
680
+ read_ids is (global_id ->> str[]) = (,).
681
+ sc inbox -- ( -> m)
682
+ {
683
+ if (m $status) == "unread"
684
+ {
685
+ processed_m is message_t = (
686
+ $msg_id -> m $msg_id,
687
+ $sender_id -> m $sender_id,
688
+ $sender_name -> m $sender_name,
689
+ $text -> m $text,
690
+ $date -> m $date,
691
+ $status -> "processed",
692
+ $wire_id -> m $wire_id,
693
+ $reply_to -> m $reply_to
694
+ ).
695
+ fresh (_count fresh|) -> m.
696
+ new_inbox (_count new_inbox|) -> processed_m.
697
+ // "" = a pre-wire-id sender or an introduction first-message:
698
+ // nothing to confirm, so it is left out rather than guessed at.
699
+ if (m $wire_id) != ""
700
+ {
701
+ wids is str[] = [].
702
+ prev = read_ids (m $sender_id).
703
+ if prev != NIL { wids -> prev?. }
704
+ wids (_count wids|) -> m $wire_id.
705
+ read_ids (m $sender_id) -> wids.
706
+ }
707
+ }
708
+ else
709
+ {
710
+ new_inbox (_count new_inbox|) -> m.
711
+ }
712
+ }
713
+ inbox -> new_inbox.
714
+
715
+ actions is transaction::action::type[] = [].
716
+ actions (_count actions|) -> _return_data ($messages -> fresh).
717
+ // read_receipt_actions returns [] when the gate is shut (we don't advertise
718
+ // emit, or the peer never said it consumes receipts), so this is appended
719
+ // blindly and costs nothing when receipts are not in play.
720
+ sc read_ids -- (peer -> wids)
721
+ {
722
+ sc a2a_messaging::read_receipt_actions peer wids -- ( -> a)
723
+ {
724
+ actions (_count actions|) -> a.
725
+ }
726
+ }
727
+ actions (_count actions|) -> _save_state NIL.
728
+ return transaction::success actions.
729
+ }
730
+
731
+ // Hand the agent every file it has not seen (status "unread") and flip those to
732
+ // "processed" — the file analogue of get_messages, and the only place file bytes
733
+ // leave the packet. Same crash-window contract: a "processed" file already left;
734
+ // recover with defer_files before gc reclaims it.
735
+ trn get_files _
736
+ {
737
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
738
+
739
+ fresh is file_t[] = [].
740
+ new_inbox is file_t[] = [].
741
+ // Files share the wire_id namespace with messages, so the read receipt is
742
+ // raised on this transition exactly as in get_messages.
743
+ read_ids is (global_id ->> str[]) = (,).
744
+ sc file_inbox -- ( -> f)
745
+ {
746
+ if (f $status) == "unread"
747
+ {
748
+ processed_f is file_t = (
749
+ $file_id -> f $file_id,
750
+ $sender_id -> f $sender_id,
751
+ $sender_name -> f $sender_name,
752
+ $filename -> f $filename,
753
+ $mime -> f $mime,
754
+ $data -> f $data,
755
+ $date -> f $date,
756
+ $status -> "processed",
757
+ $wire_id -> f $wire_id,
758
+ $reply_to -> f $reply_to
759
+ ).
760
+ fresh (_count fresh|) -> f.
761
+ new_inbox (_count new_inbox|) -> processed_f.
762
+ if (f $wire_id) != ""
763
+ {
764
+ wids is str[] = [].
765
+ prev = read_ids (f $sender_id).
766
+ if prev != NIL { wids -> prev?. }
767
+ wids (_count wids|) -> f $wire_id.
768
+ read_ids (f $sender_id) -> wids.
769
+ }
770
+ }
771
+ else
772
+ {
773
+ new_inbox (_count new_inbox|) -> f.
774
+ }
775
+ }
776
+ file_inbox -> new_inbox.
777
+
778
+ actions is transaction::action::type[] = [].
779
+ actions (_count actions|) -> _return_data ($files -> fresh).
780
+ sc read_ids -- (peer -> wids)
781
+ {
782
+ sc a2a_messaging::read_receipt_actions peer wids -- ( -> a)
783
+ {
784
+ actions (_count actions|) -> a.
785
+ }
786
+ }
787
+ actions (_count actions|) -> _save_state NIL.
788
+ return transaction::success actions.
789
+ }
790
+
791
+ // Two-generation garbage collection of handled messages, fired by the host on
792
+ // a timer (NOT piggybacked on other transactions — that would collapse the
793
+ // window under traffic). Order matters: (A) delete everything already marked
794
+ // "ready_to_delete", THEN (B) promote "processed" -> "ready_to_delete". A
795
+ // single pass keyed on the current status gives exactly that — a message is in
796
+ // one status, so a freshly-processed message is promoted (not dropped) this
797
+ // tick and only deleted on the NEXT tick, guaranteeing it survives a full
798
+ // cycle (>= 1 interval) as a deferrable "ready_to_delete".
799
+ trn gc _
800
+ {
801
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
802
+
803
+ kept is message_t[] = [].
804
+ deleted is int = 0.
805
+ promoted is int = 0.
806
+ sc inbox -- ( -> m)
807
+ {
808
+ if (m $status) == "ready_to_delete"
809
+ {
810
+ deleted -> deleted + 1.
811
+ }
812
+ elif (m $status) == "processed"
813
+ {
814
+ kept (_count kept|) -> (
815
+ $msg_id -> m $msg_id,
816
+ $sender_id -> m $sender_id,
817
+ $sender_name -> m $sender_name,
818
+ $text -> m $text,
819
+ $date -> m $date,
820
+ $status -> "ready_to_delete",
821
+ $wire_id -> m $wire_id,
822
+ $reply_to -> m $reply_to
823
+ ).
824
+ promoted -> promoted + 1.
825
+ }
826
+ else
827
+ {
828
+ kept (_count kept|) -> m.
829
+ }
830
+ }
831
+ inbox -> kept.
832
+
833
+ // Same two-generation sweep over the file store: a delivered file's bytes are
834
+ // reclaimed a full gc cycle after delivery, exactly like message bodies.
835
+ fkept is file_t[] = [].
836
+ sc file_inbox -- ( -> f)
837
+ {
838
+ if (f $status) == "ready_to_delete"
839
+ {
840
+ deleted -> deleted + 1.
841
+ }
842
+ elif (f $status) == "processed"
843
+ {
844
+ fkept (_count fkept|) -> (
845
+ $file_id -> f $file_id,
846
+ $sender_id -> f $sender_id,
847
+ $sender_name -> f $sender_name,
848
+ $filename -> f $filename,
849
+ $mime -> f $mime,
850
+ $data -> f $data,
851
+ $date -> f $date,
852
+ $status -> "ready_to_delete",
853
+ $wire_id -> f $wire_id,
854
+ $reply_to -> f $reply_to
855
+ ).
856
+ promoted -> promoted + 1.
857
+ }
858
+ else
859
+ {
860
+ fkept (_count fkept|) -> f.
861
+ }
862
+ }
863
+ file_inbox -> fkept.
864
+
865
+ return transaction::success [
866
+ _return_data ($deleted -> deleted, $promoted -> promoted),
867
+ _save_state NIL
868
+ ].
869
+ }
870
+
871
+ // Put handled messages back into the queue (status -> "unread") so a different
872
+ // session picks them up on its next get_messages. Restores from EITHER post-
873
+ // read generation — "processed" or "ready_to_delete" — so a message stays
874
+ // recoverable across a full gc cycle. The opt-in counterpart to the safe
875
+ // default: forgetting to defer just means the message stays handled by you.
876
+ trn defer_messages _:($msg_ids -> ids: int[])
877
+ {
878
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
879
+
880
+ wanted is (int ->> bool) = (,).
881
+ sc ids -- ( -> id) { wanted id -> TRUE. }
882
+
883
+ new_inbox is message_t[] = [].
884
+ deferred is int = 0.
885
+ sc inbox -- ( -> m)
886
+ {
887
+ if (wanted (m $msg_id)) && (((m $status) == "processed") || ((m $status) == "ready_to_delete"))
888
+ {
889
+ new_inbox (_count new_inbox|) -> (
890
+ $msg_id -> m $msg_id,
891
+ $sender_id -> m $sender_id,
892
+ $sender_name -> m $sender_name,
893
+ $text -> m $text,
894
+ $date -> m $date,
895
+ $status -> "unread",
896
+ $wire_id -> m $wire_id,
897
+ $reply_to -> m $reply_to
898
+ ).
899
+ deferred -> deferred + 1.
900
+ }
901
+ else
902
+ {
903
+ new_inbox (_count new_inbox|) -> m.
904
+ }
905
+ }
906
+ inbox -> new_inbox.
907
+
908
+ return transaction::success [
909
+ _return_data ($deferred -> deferred),
910
+ _save_state NIL
911
+ ].
912
+ }
913
+
914
+ // Put handled files back into the queue (status -> "unread"), restoring from
915
+ // either post-read generation. The file analogue of defer_messages.
916
+ trn defer_files _:($file_ids -> ids: int[])
917
+ {
918
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
919
+
920
+ wanted is (int ->> bool) = (,).
921
+ sc ids -- ( -> id) { wanted id -> TRUE. }
922
+
923
+ new_inbox is file_t[] = [].
924
+ deferred is int = 0.
925
+ sc file_inbox -- ( -> f)
926
+ {
927
+ if (wanted (f $file_id)) && (((f $status) == "processed") || ((f $status) == "ready_to_delete"))
928
+ {
929
+ new_inbox (_count new_inbox|) -> (
930
+ $file_id -> f $file_id,
931
+ $sender_id -> f $sender_id,
932
+ $sender_name -> f $sender_name,
933
+ $filename -> f $filename,
934
+ $mime -> f $mime,
935
+ $data -> f $data,
936
+ $date -> f $date,
937
+ $status -> "unread",
938
+ $wire_id -> f $wire_id,
939
+ $reply_to -> f $reply_to
940
+ ).
941
+ deferred -> deferred + 1.
942
+ }
943
+ else
944
+ {
945
+ new_inbox (_count new_inbox|) -> f.
946
+ }
947
+ }
948
+ file_inbox -> new_inbox.
949
+
950
+ return transaction::success [
951
+ _return_data ($deferred -> deferred),
952
+ _save_state NIL
953
+ ].
954
+ }
955
+
956
+ // ---- local contact book ---------------------------------------------------
957
+ // The book itself lives HOST-SIDE (wrapper-local file, remote peers have no
958
+ // path to it) and stores only public address material — essentially a stored
959
+ // multi-use invite. It bypasses invite generation/delivery, NOT the key
960
+ // exchange: connecting still runs the normal encrypted_channel handshake.
961
+ // Authorization is per attempt: the host's registrar packet mints a fresh,
962
+ // short-lived, registrar-signed introduction credential for each connect, and
963
+ // the target verifies it against its pinned registrar keys. An external peer
964
+ // can never produce one, so the local boundary holds cryptographically.
965
+
966
+ trn readonly export_address_document _
967
+ {
968
+ return (_write address_document::get_my_address_document()).
969
+ }
970
+
971
+ // Export the root SIGN secret so the host can persist it (identity.key) and
972
+ // reseed a recreated packet to the same address across upgrades (adapt #77).
973
+ trn readonly export_signing_secret _
974
+ {
975
+ return key_storage::export_identity_signing_secret().
976
+ }
977
+
978
+ trn pin_registrar _:($registrar_ad -> registrar_ad_blob: bin, $replace -> replace: bool+)
979
+ {
980
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
981
+
982
+ ad = (_read_or_abort registrar_ad_blob) safe address_document_types::t_address_document.
983
+ if registrar_ad != NIL
984
+ {
985
+ // Idempotent re-pin of the same keys is a no-op; CHANGING the pinned
986
+ // keys is a deliberate act and must be requested explicitly, so no
987
+ // future internal-path code can substitute a registrar silently.
988
+ if (_value_id (registrar_ad? $identity $key_list)) == (_value_id (ad $identity $key_list))
989
+ {
990
+ return transaction::success [
991
+ _return_data ($pinned -> TRUE, $changed -> FALSE)
992
+ ].
993
+ }
994
+ abort "A different registrar key list is already pinned; pass $replace -> TRUE to overwrite." when replace == NIL || replace? != TRUE.
995
+ }
996
+ registrar_ad -> ad.
997
+ return transaction::success [
998
+ _return_data ($pinned -> TRUE, $changed -> TRUE),
999
+ _save_state NIL
1000
+ ].
1001
+ }
1002
+
1003
+ trn set_local_policy _:($auto_accept -> auto_accept: bool)
1004
+ {
1005
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1006
+ local_auto_accept -> auto_accept.
1007
+ return transaction::success [
1008
+ _return_data ($auto_accept -> auto_accept),
1009
+ _save_state NIL
1010
+ ].
1011
+ }
1012
+
1013
+ // Mint an introduction credential. Only meaningful on the host's REGISTRAR
1014
+ // packet: targets verify the signature against their pinned registrar keys,
1015
+ // so a credential minted by any other packet simply fails verification.
1016
+ // Stateless — nothing to save. iat is stamped with transaction time so mint
1017
+ // and verify use the same clock domain.
1018
+ trn mint_introduction _:($joiner_ad -> joiner_ad_blob: bin, $target_ad -> target_ad_blob: bin)
1019
+ {
1020
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1021
+
1022
+ joiner_ad = (_read_or_abort joiner_ad_blob) safe address_document_types::t_address_document.
1023
+ target_ad = (_read_or_abort target_ad_blob) safe address_document_types::t_address_document.
1024
+ intro is a2a_protocol::intro_t = (
1025
+ $version -> 1,
1026
+ $joiner_cid -> joiner_ad $identity $container_id,
1027
+ $joiner_ad_hash -> _value_id joiner_ad,
1028
+ $target_cid -> target_ad $identity $container_id,
1029
+ $iat -> (current_transaction_info::get_transaction_time())?,
1030
+ $nonce -> _new_id "ours local introduction"
1031
+ ).
1032
+ signed is a2a_protocol::signed_intro_t = ($i -> intro, $s -> key_storage::default_sign (_value_id intro)).
1033
+ return transaction::success [
1034
+ _return_data ($intro -> (_write signed))
1035
+ ].
1036
+ }
1037
+
1038
+ // Sign a contact-book entry (registrar packet only, same caveat as above).
1039
+ // Makes the host-side book file tamper-evident: senders re-derive this record
1040
+ // from the entry they read and verify the signature before connecting.
1041
+ trn sign_book_entry _:($name -> name: str, $ad -> ad_blob: bin)
1042
+ {
1043
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1044
+
1045
+ ad = (_read_or_abort ad_blob) safe address_document_types::t_address_document.
1046
+ entry is a2a_protocol::book_entry_t = ($version -> 1, $name -> name, $ad_hash -> _value_id ad).
1047
+ return transaction::success [
1048
+ _return_data ($sig -> (_write (key_storage::default_sign (_value_id entry))))
1049
+ ].
1050
+ }
1051
+
1052
+ // Connect to a same-host peer found in the local contact book: verify the
1053
+ // book entry's registrar signature, register the peer as a contact, then
1054
+ // introduce myself over the encrypted channel — carrying the credential the
1055
+ // host just minted for this attempt, plus (optionally) the first message so
1056
+ // introduction + first delivery are one atomic transaction on the target
1057
+ // (no introduce-vs-message ordering race).
1058
+ 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+)
1059
+ {
1060
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1061
+ abort "No registrar pinned — the local contact book is unavailable for this identity." when registrar_ad == NIL.
1062
+
1063
+ target_ad = (_read_or_abort target_ad_blob) safe address_document_types::t_address_document.
1064
+ target_id = target_ad $identity $container_id.
1065
+ abort "This contact-book entry is your own identity." when target_id == _get_container_id().
1066
+
1067
+ entry is a2a_protocol::book_entry_t = ($version -> 1, $name -> name, $ad_hash -> _value_id target_ad).
1068
+ entry_sig = (_read_or_abort entry_sig_blob) safe crypto_signature.
1069
+ 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.
1070
+
1071
+ a2a_messaging::contacts target_id -> ($name -> name, $container_id -> target_id).
1072
+ a2a_messaging::peer_ads target_id -> target_ad.
1073
+
1074
+ my_self_name = a2a_messaging::my_name.
1075
+ my_ad = address_document::get_my_address_document().
1076
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
1077
+ return transaction::success [
1078
+ encrypted_channel::send_encrypted_tx target_id (
1079
+ $name -> "::actor::local_introduce",
1080
+ $targ -> ($joiner_name -> my_self_name, $joiner_ad -> my_ad, $intro -> intro_blob, $text -> text)
1081
+ ),
1082
+ _return_data ($connected -> name, $container_id -> target_id),
1083
+ _save_state NIL
1084
+ ].
1085
+ }).
1086
+ }
1087
+
1088
+ trn approve_introduction _:($contact -> ref: str)
1089
+ {
1090
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1091
+
1092
+ pid = resolve_pending ref.
1093
+ entry = (pending_introductions pid)?.
1094
+ a2a_messaging::contacts pid -> ($name -> entry $name, $container_id -> pid).
1095
+ a2a_messaging::peer_ads pid -> entry $ad.
1096
+
1097
+ queued = entry $messages.
1098
+ flushed is int = 0.
1099
+ sc queued -- ( -> m)
1100
+ {
1101
+ deposit_message pid (entry $name) (m $text) (m $date) "" no_reply.
1102
+ flushed -> flushed + 1.
1103
+ }
1104
+ delete pending_introductions pid.
1105
+
1106
+ return transaction::success [
1107
+ _return_data ($approved -> entry $name, $container_id -> pid, $flushed -> flushed),
1108
+ _save_state NIL
1109
+ ].
1110
+ }
1111
+
1112
+ trn reject_introduction _:($contact -> ref: str)
1113
+ {
1114
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1115
+
1116
+ pid = resolve_pending ref.
1117
+ entry = (pending_introductions pid)?.
1118
+ dropped = _count (entry $messages)|.
1119
+ delete pending_introductions pid.
1120
+
1121
+ return transaction::success [
1122
+ _return_data ($rejected -> entry $name, $container_id -> pid, $dropped_messages -> dropped),
1123
+ _save_state NIL
1124
+ ].
1125
+ }
1126
+
1127
+ trn readonly list_pending_introductions _
1128
+ {
1129
+ out is (global_id ->> pending_view_t) = (,).
1130
+ sc pending_introductions -- (cid -> p)
1131
+ {
1132
+ out cid -> ($name -> p $name, $queued -> _count (p $messages)|).
1133
+ }
1134
+ return out.
1135
+ }
1136
+
1137
+ // ---- identity hierarchy ---------------------------------------------------
1138
+ // Two layers (see IDENTITY-HIERARCHY-DESIGN.md): one ROOT identity per host
1139
+ // (represents the person; structurally just a packet with no delegation
1140
+ // cert) and ROLE identities under it, each carrying a cert signed by the
1141
+ // root. The host drives issuance: it asks the root packet to sign a cert
1142
+ // (sign_delegation) and export its profile (export_root_profile), then
1143
+ // stores both into the role packet (set_delegation). Intra-root peers
1144
+ // (Ring 1) connect via connect_sibling/sibling_introduce with cert-based
1145
+ // auto-accept — no registrar credential, no approval queue, and it works
1146
+ // for roles that are not published in the local contact book.
1147
+
1148
+ // Sign a delegation certificate for a role (meaningful on the ROOT packet:
1149
+ // verifiers check the signature against the root's keys, so a cert minted
1150
+ // by any other packet fails verification). Stateless — nothing to save.
1151
+ trn sign_delegation _:($role_ad -> role_ad_blob: bin, $role_id -> role_id: str)
1152
+ {
1153
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1154
+ abort "Only a root identity can sign delegation certificates." when a2a_messaging::delegation_cert != NIL.
1155
+
1156
+ role_ad = (_read_or_abort role_ad_blob) safe address_document_types::t_address_document.
1157
+ role_cid = role_ad $identity $container_id.
1158
+ abort "Cannot issue a delegation certificate to myself." when role_cid == _get_container_id().
1159
+
1160
+ core is a2a_protocol::delegation_core_t = (
1161
+ $version -> 1,
1162
+ $role_cid -> role_cid,
1163
+ $role_ad_hash -> _value_id role_ad,
1164
+ $role_id -> role_id,
1165
+ $root_cid -> _get_container_id(),
1166
+ $issued_at -> (current_transaction_info::get_transaction_time())?
1167
+ ).
1168
+ cert is a2a_protocol::delegation_cert_t = ($c -> core, $s -> key_storage::default_sign (_value_id core)).
1169
+ return transaction::success [
1170
+ _return_data ($cert -> (_write cert))
1171
+ ].
1172
+ }
1173
+
1174
+ // Export my self-signed root profile (root packet only). Roles embed this
1175
+ // in the invites they generate, so external peers learn who is behind the
1176
+ // role; it carries my key list so the whole chain verifies standalone.
1177
+ trn export_root_profile _
1178
+ {
1179
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1180
+ abort "Only a root identity can export a root profile." when a2a_messaging::delegation_cert != NIL.
1181
+
1182
+ my_ad = address_document::get_my_address_document().
1183
+ core is a2a_protocol::root_profile_core_t = (
1184
+ $version -> 1,
1185
+ $root_cid -> _get_container_id(),
1186
+ $name -> a2a_messaging::my_name,
1187
+ $bio -> a2a_messaging::my_bio,
1188
+ $keys -> my_ad $identity $key_list
1189
+ ).
1190
+ profile is a2a_protocol::root_profile_t = ($p -> core, $s -> key_storage::default_sign (_value_id core)).
1191
+ return transaction::success [
1192
+ _return_data ($profile -> (_write profile))
1193
+ ].
1194
+ }
1195
+
1196
+ // Store my delegation cert + root material (role packet, host-fired after
1197
+ // the root signed the cert). Everything is verified before it is stored:
1198
+ // a cert that does not name me, does not match my keys, or was not signed
1199
+ // by the carried root is rejected. Re-running with fresh material is the
1200
+ // refresh path (e.g. the root's bio changed -> new profile, same root).
1201
+ trn set_delegation _:($cert -> cert_blob: bin, $root_ad -> root_ad_blob: bin, $root_profile -> rp_blob: bin)
1202
+ {
1203
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1204
+
1205
+ cert = (_read_or_abort cert_blob) safe a2a_protocol::delegation_cert_t.
1206
+ new_root_ad = (_read_or_abort root_ad_blob) safe address_document_types::t_address_document.
1207
+ rp = (_read_or_abort rp_blob) safe a2a_protocol::root_profile_t.
1208
+
1209
+ abort "Unsupported delegation certificate version." when (cert $c $version) != 1.
1210
+ abort "This delegation certificate was issued to a different identity." when (cert $c $role_cid) != _get_container_id().
1211
+ my_ad = address_document::get_my_address_document().
1212
+ abort "This delegation certificate does not match my address document." when (cert $c $role_ad_hash) != (_value_id my_ad).
1213
+ abort "The root address document does not match the certificate's root." when (new_root_ad $identity $container_id) != (cert $c $root_cid).
1214
+ 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.
1215
+ abort "Unsupported root profile version." when (rp $p $version) != 1.
1216
+ abort "The root profile does not match the certificate's root." when (rp $p $root_cid) != (cert $c $root_cid).
1217
+ 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)).
1218
+ 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.
1219
+
1220
+ a2a_messaging::delegation_cert -> cert.
1221
+ a2a_messaging::root_ad -> new_root_ad.
1222
+ a2a_messaging::root_profile -> rp.
1223
+
1224
+ return transaction::success [
1225
+ _return_data ($delegated -> TRUE, $root_cid -> (_str (cert $c $root_cid)), $role_id -> cert $c $role_id),
1226
+ _save_state NIL
1227
+ ].
1228
+ }
1229
+
1230
+ trn readonly describe_identity _
1231
+ {
1232
+ if a2a_messaging::delegation_cert == NIL
1233
+ {
1234
+ return ($name -> a2a_messaging::my_name, $bio -> a2a_messaging::my_bio, $has_cert -> FALSE, $role_id -> "", $root_cid -> "", $root_name -> "", $monitoring_enabled -> monitoring_enabled).
1235
+ }
1236
+ cert = a2a_messaging::delegation_cert?.
1237
+ rname is str = "".
1238
+ if a2a_messaging::root_profile != NIL { rname -> a2a_messaging::root_profile? $p $name. }
1239
+ return (
1240
+ $name -> a2a_messaging::my_name,
1241
+ $bio -> a2a_messaging::my_bio,
1242
+ $has_cert -> TRUE,
1243
+ $role_id -> cert $c $role_id,
1244
+ $root_cid -> (_str (cert $c $root_cid)),
1245
+ $root_name -> rname,
1246
+ $monitoring_enabled -> monitoring_enabled
1247
+ ).
1248
+ }
1249
+
1250
+ // Connect to an intra-root sibling (Ring 1): register it as a contact and
1251
+ // introduce myself over the encrypted channel, presenting my delegation
1252
+ // cert (NIL when I am the root itself — the channel proves I control the
1253
+ // root's keys, which is all a role needs to recognize its root). Like
1254
+ // connect_local, the optional first message rides the introduction so
1255
+ // introduce + first delivery are one atomic transaction on the target.
1256
+ trn connect_sibling _:($name -> name: str, $target_ad -> target_ad_blob: bin, $text -> text: str+)
1257
+ {
1258
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1259
+
1260
+ target_ad = (_read_or_abort target_ad_blob) safe address_document_types::t_address_document.
1261
+ target_id = target_ad $identity $container_id.
1262
+ abort "This sibling is your own identity." when target_id == _get_container_id().
1263
+
1264
+ cert_blob is bin+ = NIL.
1265
+ if a2a_messaging::delegation_cert != NIL { cert_blob -> (_write a2a_messaging::delegation_cert?). }
1266
+
1267
+ a2a_messaging::contacts target_id -> ($name -> name, $container_id -> target_id).
1268
+ a2a_messaging::peer_ads target_id -> target_ad.
1269
+ // Record the target's root linkage: a sibling shares my root by
1270
+ // definition (the receiving side verifies the converse independently).
1271
+ if a2a_messaging::delegation_cert != NIL && a2a_messaging::root_profile != NIL
1272
+ {
1273
+ 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).
1274
+ }
1275
+ else
1276
+ {
1277
+ a2a_messaging::contact_roots target_id -> ($root_cid -> _get_container_id(), $root_name -> a2a_messaging::my_name, $role_id -> name).
1278
+ }
1279
+
1280
+ my_self_name = a2a_messaging::my_name.
1281
+ my_ad = address_document::get_my_address_document().
1282
+ return encrypted_channel::execute_transaction target_id (fn (_) -> transaction::results::type {
1283
+ return transaction::success [
1284
+ encrypted_channel::send_encrypted_tx target_id (
1285
+ $name -> "::actor::sibling_introduce",
1286
+ $targ -> ($joiner_name -> my_self_name, $joiner_ad -> my_ad, $cert -> cert_blob, $text -> text)
1287
+ ),
1288
+ _return_data ($connected -> name, $container_id -> target_id),
1289
+ _save_state NIL
1290
+ ].
1291
+ }).
1292
+ }
1293
+
1294
+ // ---- monitoring + control plane -------------------------------------------
1295
+ // (see MONITORING-AND-SHARED-LIBRARY-DESIGN.md). A monitored ROLE reports
1296
+ // every message it sends/receives to its ROOT (the monitor_copy_actions
1297
+ // branches in the storage hooks above); the root queues the copies and the
1298
+ // host forwards them to a human proxy bound via 6-digit-code verification.
1299
+ // The proxy's control requests (create agent, update role, …) queue in
1300
+ // control_inbox and are executed by the host daemon.
1301
+
1302
+ trn readonly get_monitoring_status _
1303
+ {
1304
+ pending is bool = FALSE.
1305
+ if proxy_pending != NIL { pending -> TRUE. }
1306
+ proxy_out is str = "".
1307
+ if monitoring_proxy != NIL { proxy_out -> _str (monitoring_proxy? $proxy_cid). }
1308
+ return (
1309
+ $monitoring_enabled -> monitoring_enabled,
1310
+ $proxy_cid -> proxy_out,
1311
+ $proxy_pending -> pending,
1312
+ $copies_queued -> _count monitoring_inbox|,
1313
+ $control_queued -> _count control_inbox|
1314
+ ).
1315
+ }
1316
+
1317
+ // Sign a monitoring authorization for a role (ROOT packet only — the role
1318
+ // verifies the signature against its pinned root keys, so an auth minted
1319
+ // by any other packet fails). Stateless, mirrors sign_delegation.
1320
+ trn sign_monitoring_auth _:($role_ad -> role_ad_blob: bin, $enabled -> enabled: bool)
1321
+ {
1322
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1323
+ abort "Only a root identity can sign monitoring authorizations." when a2a_messaging::delegation_cert != NIL.
1324
+
1325
+ role_ad = (_read_or_abort role_ad_blob) safe address_document_types::t_address_document.
1326
+ core is monitoring_auth_core_t = (
1327
+ $version -> 1,
1328
+ $role_cid -> role_ad $identity $container_id,
1329
+ $enabled -> enabled,
1330
+ $issued_at -> (current_transaction_info::get_transaction_time())?
1331
+ ).
1332
+ auth is monitoring_auth_t = ($c -> core, $s -> key_storage::default_sign (_value_id core)).
1333
+ return transaction::success [
1334
+ _return_data ($auth -> (_write auth))
1335
+ ].
1336
+ }
1337
+
1338
+ // Store a verified monitoring flag (ROLE packet, host-fired after the root
1339
+ // signed the auth). An auth that does not name me or was not signed by my
1340
+ // root is rejected — so even a compromised host process cannot silently
1341
+ // flip monitoring without the root packet's keys.
1342
+ trn set_monitoring _:($auth -> auth_blob: bin)
1343
+ {
1344
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1345
+ abort "Only a delegated role can be monitored." when a2a_messaging::delegation_cert == NIL || a2a_messaging::root_ad == NIL.
1346
+
1347
+ auth = (_read_or_abort auth_blob) safe monitoring_auth_t.
1348
+ abort "Unsupported monitoring authorization version." when (auth $c $version) != 1.
1349
+ abort "This monitoring authorization was issued to a different identity." when (auth $c $role_cid) != _get_container_id().
1350
+ 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.
1351
+
1352
+ monitoring_enabled -> auth $c $enabled.
1353
+ return transaction::success [
1354
+ _return_data ($monitoring_enabled -> monitoring_enabled),
1355
+ _save_state NIL
1356
+ ].
1357
+ }
1358
+
1359
+ // A monitored role reports one message copy (ROOT packet, inbound). Only
1360
+ // accepted from a verified role of THIS root (the contact_roots linkage
1361
+ // recorded by sibling_introduce), and the copy must name its actual sender
1362
+ // — a role cannot forge copies on another role's behalf.
1363
+ trn receive_monitoring_copy _:($copy -> copy: monitoring_copy_t)
1364
+ {
1365
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1366
+ encrypted_channel::check_encrypted_or_abort().
1367
+
1368
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1369
+ link = a2a_messaging::contact_roots sender_id.
1370
+ abort "Monitoring copies are only accepted from my own roles." when link == NIL || (link? $root_cid) != _get_container_id().
1371
+ abort "Monitoring copy does not name its sender as the source." when (copy $source_cid) != sender_id.
1372
+ abort "Unsupported monitoring copy version." when (copy $version) != 1.
1373
+
1374
+ // Capped queue, oldest first out: if no proxy drains the root, recent
1375
+ // traffic wins over old.
1376
+ if (_count monitoring_inbox|) >= monitoring_inbox_cap
1377
+ {
1378
+ trimmed is monitoring_copy_t[] = [].
1379
+ i is int = 0.
1380
+ sc monitoring_inbox -- ( -> m)
1381
+ {
1382
+ if i > 0 { trimmed (_count trimmed|) -> m. }
1383
+ i -> i + 1.
1384
+ }
1385
+ monitoring_inbox -> trimmed.
1386
+ }
1387
+ monitoring_inbox (_count monitoring_inbox|) -> copy.
1388
+
1389
+ return transaction::success [
1390
+ _notify_agent ($event -> $monitoring_copy, $source_name -> copy $source_name, $queued -> _count monitoring_inbox|),
1391
+ _save_state NIL
1392
+ ].
1393
+ }
1394
+
1395
+ // Drain the queued monitoring copies (ROOT packet, host-fired before
1396
+ // forwarding to the bound proxy). Cleared on read, like get_messages.
1397
+ trn get_monitoring_copies _
1398
+ {
1399
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1400
+
1401
+ copies = monitoring_inbox.
1402
+ monitoring_inbox -> [].
1403
+ return transaction::success [
1404
+ _return_data ($copies -> copies),
1405
+ _save_state NIL
1406
+ ].
1407
+ }
1408
+
1409
+ // Drain the queued control requests (ROOT packet, host-fired by the
1410
+ // control dispatcher). Cleared on read.
1411
+ trn get_control_requests _
1412
+ {
1413
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1414
+
1415
+ reqs = control_inbox.
1416
+ control_inbox -> [].
1417
+ return transaction::success [
1418
+ _return_data ($requests -> reqs),
1419
+ _save_state NIL
1420
+ ].
1421
+ }
1422
+
1423
+ // Start a proxy binding (ROOT packet, host-fired): remember the code the
1424
+ // host generated (MUFL has no random source) for one specific contact.
1425
+ // Restarting overwrites any previous pending binding.
1426
+ trn set_proxy_pending _:($code -> code: str, $proxy -> proxy_ref: str)
1427
+ {
1428
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1429
+ abort "Only a root identity can bind a monitoring proxy." when a2a_messaging::delegation_cert != NIL.
1430
+
1431
+ pid = a2a_messaging::resolve_contact proxy_ref.
1432
+ proxy_pending -> (
1433
+ $code -> code,
1434
+ $proxy_cid -> pid,
1435
+ $created_at -> (current_transaction_info::get_transaction_time())?,
1436
+ $attempts -> 0
1437
+ ).
1438
+ return transaction::success [
1439
+ _return_data ($pending -> TRUE, $proxy_cid -> (_str pid)),
1440
+ _save_state NIL
1441
+ ].
1442
+ }
1443
+
1444
+ // Verify a proxy's code attempt (ROOT packet, host-fired when a `bind`
1445
+ // control request arrives). Failures are returned as DATA — not aborts —
1446
+ // so the attempt counter and expiry clearing persist atomically; an abort
1447
+ // would roll them back and reopen the brute-force window.
1448
+ trn verify_proxy_code _:($code -> code: str, $sender -> sender_ref: str)
1449
+ {
1450
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1451
+
1452
+ if proxy_pending == NIL
1453
+ {
1454
+ return transaction::success [ _return_data ($verified -> FALSE, $reason -> "no_pending") ].
1455
+ }
1456
+ p = proxy_pending?.
1457
+ now = (current_transaction_info::get_transaction_time())?.
1458
+
1459
+ if (_substract_seconds now (p $created_at)) > proxy_code_max_age_seconds
1460
+ {
1461
+ proxy_pending -> NIL.
1462
+ return transaction::success [
1463
+ _return_data ($verified -> FALSE, $reason -> "expired"),
1464
+ _save_state NIL
1465
+ ].
1466
+ }
1467
+
1468
+ sid = a2a_messaging::resolve_contact sender_ref.
1469
+ if sid != (p $proxy_cid)
1470
+ {
1471
+ // Not the contact this binding was started for: reject without
1472
+ // burning an attempt (the code was never compared).
1473
+ return transaction::success [ _return_data ($verified -> FALSE, $reason -> "wrong_sender") ].
1474
+ }
1475
+
1476
+ if code != (p $code)
1477
+ {
1478
+ attempts = (p $attempts) + 1.
1479
+ if attempts >= proxy_max_attempts
1480
+ {
1481
+ proxy_pending -> NIL.
1482
+ return transaction::success [
1483
+ _return_data ($verified -> FALSE, $reason -> "too_many_attempts"),
1484
+ _save_state NIL
1485
+ ].
1486
+ }
1487
+ proxy_pending -> (
1488
+ $code -> p $code,
1489
+ $proxy_cid -> p $proxy_cid,
1490
+ $created_at -> p $created_at,
1491
+ $attempts -> attempts
1492
+ ).
1493
+ return transaction::success [
1494
+ _return_data ($verified -> FALSE, $reason -> "wrong_code", $attempts_left -> proxy_max_attempts - attempts),
1495
+ _save_state NIL
1496
+ ].
1497
+ }
1498
+
1499
+ monitoring_proxy -> ($proxy_cid -> sid, $bound_at -> now).
1500
+ proxy_pending -> NIL.
1501
+ return transaction::success [
1502
+ _return_data ($verified -> TRUE, $proxy_cid -> (_str sid)),
1503
+ _save_state NIL
1504
+ ].
1505
+ }
1506
+
1507
+ // Drop the proxy binding (and any in-flight code verification).
1508
+ trn clear_monitoring_proxy _
1509
+ {
1510
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1511
+
1512
+ monitoring_proxy -> NIL.
1513
+ proxy_pending -> NIL.
1514
+ return transaction::success [
1515
+ _return_data ($cleared -> TRUE),
1516
+ _save_state NIL
1517
+ ].
1518
+ }
1519
+
1520
+ // ---- upgrade: state export / import -------------------------------------
1521
+ // The host persists state by calling export_state (readonly) and serializing
1522
+ // the returned value to a code-independent blob. On a code upgrade it also
1523
+ // persists the root SIGN secret (export_signing_secret) and recreates the
1524
+ // packet with that secret injected as init_arg; __init reseeds the identity
1525
+ // from it (reseed_identity_from_secret), which preserves the container
1526
+ // address regardless of the seed phrase or key-derivation used to recreate
1527
+ // the packet. The blob is then replayed through import_state.
1528
+ //
1529
+ // The packet-level snapshot is NOT used for upgrades: it is bound to the unit
1530
+ // code hash, so a new .muflo cannot load an old snapshot. This data blob is.
1531
+ //
1532
+ // Core (contact / profile / hierarchy / DR-session) state is carried WHOLE under
1533
+ // $core: export_core_state owns its OWN field set, so any field the shared core
1534
+ // adds — most importantly $e2e_sessions (the DR ratchet pickles that a manual
1535
+ // per-field projection silently DROPPED, losing messages across a reload) — rides
1536
+ // forward automatically, and the core's monitoring keys never collide with the
1537
+ // APP-level monitoring keys we still own below (they share both names AND shapes).
1538
+ // The blob stays code-independent; import_state migrates the pre-namespacing FLAT
1539
+ // shape forward (see there). Mirrors ours-mcp's actor exactly.
1540
+
1541
+ trn readonly export_state _
1542
+ {
1543
+ return (
1544
+ $app_format_version -> 1,
1545
+ $core -> a2a_messaging::export_core_state NIL,
1546
+ // ---- app-owned state (route inbox + files + local book + monitoring) ----
1547
+ $inbox -> inbox,
1548
+ $next_msg_seq -> next_msg_seq,
1549
+ $file_inbox -> file_inbox,
1550
+ $next_file_seq -> next_file_seq,
1551
+ $registrar_ad -> registrar_ad,
1552
+ $local_auto_accept -> local_auto_accept,
1553
+ // Nonces are exported so a restart does not reopen the replay window
1554
+ // for still-fresh credentials; stale ones are purged lazily anyway.
1555
+ $seen_nonces -> seen_nonces,
1556
+ $pending_introductions -> pending_introductions,
1557
+ // App-level (role->root) monitoring — a DISTINCT mechanism from core's
1558
+ // forced monitoring. Stays app-owned and top-level; it must NEVER be fed
1559
+ // into import_core_state (that would arm core's hidden monitoring_proxy,
1560
+ // which the app cannot disarm). See import_state's legacy branch.
1561
+ $monitoring_enabled -> monitoring_enabled,
1562
+ $monitoring_inbox -> monitoring_inbox,
1563
+ $proxy_pending -> proxy_pending,
1564
+ $monitoring_proxy -> monitoring_proxy,
1565
+ $control_inbox -> control_inbox
1566
+ ).
1567
+ }
1568
+
1569
+ trn import_state data: any
1570
+ {
1571
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::user,).
1572
+
1573
+ // App-level format stamp (absent == 0, every pre-stamp blob). Same contract
1574
+ // as the core stamp (see a2a_messaging::import_core_state): additive fields
1575
+ // stay optional reads; a future BREAKING app-blob change dispatches here.
1576
+ app_fmt is int = 0.
1577
+ if (data $app_format_version) != NIL { app_fmt -> (data $app_format_version) safe int. }
1578
+ 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.
1579
+
1580
+ // Core fields (contacts/profile/hierarchy/DR-sessions) — validated and restored
1581
+ // by the shared library, which also replays every peer's address document
1582
+ // through process_address_document so encrypted channels keep working after the
1583
+ // upgrade with no re-handshake, and parks $e2e_sessions for the staged commit
1584
+ // below. The current export namespaces core under $core, so the core owns its
1585
+ // own field set and its monitoring keys never collide with the app's. A
1586
+ // PRE-namespacing FLAT blob carries the core fields at the top level — migrate it
1587
+ // by feeding import_core_state ONLY the genuine shared fields. We deliberately
1588
+ // OMIT proxy_pending / monitoring_proxy on the legacy path: in a flat blob those
1589
+ // keys hold the APP-level monitoring state (same names AND shapes as core's), and
1590
+ // feeding them to import_core_state would arm core's hidden forced-monitoring
1591
+ // proxy — which the app can NEVER disarm. Mirrors ours-mcp's actor exactly.
1592
+ if (data $core) != NIL
1593
+ {
1594
+ a2a_messaging::import_core_state (data $core).
1595
+ }
1596
+ else
1597
+ {
1598
+ a2a_messaging::import_core_state (
1599
+ $my_name -> data $my_name,
1600
+ $contacts -> data $contacts,
1601
+ $pending_invites -> data $pending_invites,
1602
+ $peer_ads -> data $peer_ads,
1603
+ $my_bio -> data $my_bio,
1604
+ $delegation_cert -> data $delegation_cert,
1605
+ $root_ad -> data $root_ad,
1606
+ $root_profile -> data $root_profile,
1607
+ $contact_roots -> data $contact_roots
1608
+ ).
1609
+ }
1610
+
1611
+ // The inbox + next_msg_seq are the only parts the message-lifecycle changes
1612
+ // touched. A pre-lifecycle blob has no $next_msg_seq and inbox entries with
1613
+ // no id/status — MIGRATE it forward (the whole point of code-independent
1614
+ // state is that an old export upgrades, never resets): assign each legacy
1615
+ // message a sequential id and status "unread", and seed next_msg_seq past
1616
+ // them. A current-shape blob is loaded as-is except the gc vocabulary bump
1617
+ // ("read" -> "processed", see below).
1618
+ if (data $next_msg_seq) == NIL
1619
+ {
1620
+ legacy_inbox = (data $inbox) safe (legacy_message_t[]).
1621
+ migrated is message_t[] = [].
1622
+ seq is int = 1.
1623
+ sc legacy_inbox -- ( -> m)
1624
+ {
1625
+ migrated (_count migrated|) -> (
1626
+ $msg_id -> seq,
1627
+ $sender_id -> m $sender_id,
1628
+ $sender_name -> m $sender_name,
1629
+ $text -> m $text,
1630
+ $date -> m $date,
1631
+ $status -> "unread",
1632
+ $wire_id -> "",
1633
+ $reply_to -> NIL
1634
+ ).
1635
+ seq -> seq + 1.
1636
+ }
1637
+ inbox -> migrated.
1638
+ next_msg_seq -> seq.
1639
+ }
1640
+ else
1641
+ {
1642
+ // Current-shape blob, read field-by-field (NOT a strict message_t[]
1643
+ // cast) so a pre-1.4 blob — whose messages have no $wire_id/$reply_to
1644
+ // — imports without aborting on the now-required $wire_id. Two
1645
+ // forward-migrations: the old "read" status -> "processed" (else the
1646
+ // message is stuck: never returned, gc'd, or deferred), and absent
1647
+ // wire_id/reply_to default to "" / NIL.
1648
+ upgraded is message_t[] = [].
1649
+ sc (data $inbox) -- ( -> m)
1650
+ {
1651
+ mstatus = (((m $status) safe str) == "read" ?? "processed" ; (m $status) safe str).
1652
+ mwire is str = "".
1653
+ if (m $wire_id) != NIL { mwire -> (m $wire_id) safe str. }
1654
+ mreply is a2a_protocol::reply_ref_t+ = NIL.
1655
+ if (m $reply_to) != NIL { mreply -> (m $reply_to) safe a2a_protocol::reply_ref_t. }
1656
+ upgraded (_count upgraded|) -> (
1657
+ $msg_id -> (m $msg_id) safe int,
1658
+ $sender_id -> (m $sender_id) safe global_id,
1659
+ $sender_name -> (m $sender_name) safe str,
1660
+ $text -> (m $text) safe str,
1661
+ $date -> (m $date) safe time,
1662
+ $status -> mstatus,
1663
+ $wire_id -> mwire,
1664
+ $reply_to -> mreply
1665
+ ).
1666
+ }
1667
+ inbox -> upgraded.
1668
+ next_msg_seq -> (data $next_msg_seq) safe int.
1669
+ }
1670
+
1671
+ // Local-contact-book state arrived after the original schema — every
1672
+ // field is optional in old blobs and defaults stay in place when absent.
1673
+ if (data $registrar_ad) != NIL
1674
+ {
1675
+ registrar_ad -> (data $registrar_ad) safe address_document_types::t_address_document.
1676
+ }
1677
+ if (data $local_auto_accept) != NIL
1678
+ {
1679
+ local_auto_accept -> (data $local_auto_accept) safe bool.
1680
+ }
1681
+ if (data $seen_nonces) != NIL
1682
+ {
1683
+ seen_nonces -> (data $seen_nonces) safe (global_id ->> time).
1684
+ }
1685
+ if (data $pending_introductions) != NIL
1686
+ {
1687
+ pending_introductions -> (data $pending_introductions) safe (global_id ->> pending_intro_t).
1688
+ }
1689
+
1690
+ // Monitoring + control state arrived after the local-book schema —
1691
+ // optional in old blobs the same way.
1692
+ if (data $monitoring_enabled) != NIL
1693
+ {
1694
+ monitoring_enabled -> (data $monitoring_enabled) safe bool.
1695
+ }
1696
+ if (data $monitoring_inbox) != NIL
1697
+ {
1698
+ monitoring_inbox -> (data $monitoring_inbox) safe (monitoring_copy_t[]).
1699
+ }
1700
+ if (data $proxy_pending) != NIL
1701
+ {
1702
+ proxy_pending -> (data $proxy_pending) safe proxy_pending_t.
1703
+ }
1704
+ if (data $monitoring_proxy) != NIL
1705
+ {
1706
+ monitoring_proxy -> (data $monitoring_proxy) safe proxy_binding_t.
1707
+ }
1708
+ if (data $control_inbox) != NIL
1709
+ {
1710
+ control_inbox -> (data $control_inbox) safe (control_req_t[]).
1711
+ }
1712
+
1713
+ // File store arrived with core 3.1 — optional in pre-3.1 blobs; defaults
1714
+ // ([] / 1) stay in place when absent, so an old export imports unchanged.
1715
+ if (data $next_file_seq) != NIL
1716
+ {
1717
+ next_file_seq -> (data $next_file_seq) safe int.
1718
+ }
1719
+ if (data $file_inbox) != NIL
1720
+ {
1721
+ file_inbox -> (data $file_inbox) safe (file_t[]).
1722
+ }
1723
+
1724
+ // Pending introducers' keys too: their channel to me predates approval,
1725
+ // so it must survive an upgrade exactly like an approved contact's.
1726
+ sc pending_introductions -- ( -> p)
1727
+ {
1728
+ address_document::process_address_document (p $ad) TRUE.
1729
+ }
1730
+
1731
+ return transaction::success [
1732
+ _return_data ($imported -> TRUE, $contacts -> _count a2a_messaging::contacts|, $peers -> _count a2a_messaging::peer_ads|),
1733
+ _save_state NIL
1734
+ ].
1735
+ }
1736
+
1737
+ // ---- external (inbound) transactions ------------------------------------
1738
+
1739
+ // Compat shims (Option A): pre-migration peers address these as ::actor::*,
1740
+ // and the core keeps SENDING to the ::actor:: names too. Each delegates to
1741
+ // the shared handler — remove only when no old clients remain.
1742
+ trn accept_contact args: any
1743
+ {
1744
+ return a2a_messaging::handle_accept_contact args.
1745
+ }
1746
+
1747
+ trn receive_message args: any
1748
+ {
1749
+ return a2a_messaging::handle_receive_message args.
1750
+ }
1751
+
1752
+ // A same-host peer connects via the local contact book. The credential must
1753
+ // have been minted by THIS HOST's registrar for THIS sender and THIS target,
1754
+ // recently, and never seen before — five checks that together make the book
1755
+ // path unusable from outside the host:
1756
+ // 1. registrar signature over the credential (pinned key list)
1757
+ // 2. envelope $from == credential.joiner_cid (no splicing someone
1758
+ // else's credential onto your own channel)
1759
+ // 3. hash(joiner_ad) == credential.joiner_ad_hash (no AD substitution)
1760
+ // 4. credential.target_cid == me (no cross-target reuse)
1761
+ // 5. freshness window + unseen nonce (no replay)
1762
+ // The encrypted channel itself authenticates that the sender controls its
1763
+ // keys, so no extra challenge-response is needed.
1764
+ 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+)
1765
+ {
1766
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1767
+ encrypted_channel::check_encrypted_or_abort().
1768
+
1769
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1770
+ abort "This identity does not accept local-contact-book introductions." when registrar_ad == NIL.
1771
+
1772
+ signed = (_read_or_abort intro_blob) safe a2a_protocol::signed_intro_t.
1773
+ intro = signed $i.
1774
+ abort "Unsupported introduction credential version." when (intro $version) != 1.
1775
+ 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.
1776
+ abort "Introduction credential was minted for a different sender." when (intro $joiner_cid) != sender_id.
1777
+ abort "Introduction credential does not match the sender's address document." when (intro $joiner_ad_hash) != _value_id joiner_ad.
1778
+ abort "Introduction credential targets a different identity." when (intro $target_cid) != _get_container_id().
1779
+
1780
+ now = (current_transaction_info::get_transaction_time())?.
1781
+ age = _substract_seconds now (intro $iat).
1782
+ abort "Introduction credential is outside its freshness window." when age > intro_max_age_seconds || age < (0 - intro_max_skew_seconds).
1783
+
1784
+ // Lazy nonce GC (drop everything past the retention horizon), then the
1785
+ // replay check, then a hard cap so a misbehaving local peer cannot bloat
1786
+ // packet state inside the window.
1787
+ horizon = intro_max_age_seconds + intro_max_skew_seconds.
1788
+ fresh_nonces is (global_id ->> time) = (,).
1789
+ sc seen_nonces -- (n -> t)
1790
+ {
1791
+ if (_substract_seconds now t) <= horizon { fresh_nonces n -> t. }
1792
+ }
1793
+ seen_nonces -> fresh_nonces.
1794
+ abort "Replayed introduction credential." when seen_nonces (intro $nonce) != NIL.
1795
+ abort "Too many concurrent introductions; try again shortly." when (_count seen_nonces|) >= seen_nonce_cap.
1796
+ seen_nonces (intro $nonce) -> now.
1797
+
1798
+ existing = a2a_messaging::contacts sender_id.
1799
+ if existing != NIL
1800
+ {
1801
+ // Already a contact (idempotent re-introduction): keep my assigned
1802
+ // name, refresh the stored address document, deliver any payload.
1803
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1804
+ if text != NIL
1805
+ {
1806
+ mid = deposit_message sender_id (existing? $name) text? now "" no_reply.
1807
+ return transaction::success [
1808
+ _notify_agent ($event -> $message_received, $sender_name -> existing? $name, $msg_id -> mid, $date -> now),
1809
+ _save_state NIL
1810
+ ].
1811
+ }
1812
+ return transaction::success [ _save_state NIL ].
1813
+ }
1814
+
1815
+ if local_auto_accept
1816
+ {
1817
+ a2a_messaging::contacts sender_id -> ($name -> joiner_name, $container_id -> sender_id).
1818
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1819
+ if text != NIL
1820
+ {
1821
+ mid = deposit_message sender_id joiner_name text? now "" no_reply.
1822
+ return transaction::success [
1823
+ _notify_agent ($event -> $local_contact_added, $name -> joiner_name, $container_id -> sender_id),
1824
+ _notify_agent ($event -> $message_received, $sender_name -> joiner_name, $msg_id -> mid, $date -> now),
1825
+ _save_state NIL
1826
+ ].
1827
+ }
1828
+ return transaction::success [
1829
+ _notify_agent ($event -> $local_contact_added, $name -> joiner_name, $container_id -> sender_id),
1830
+ _save_state NIL
1831
+ ].
1832
+ }
1833
+
1834
+ // Pending-approval policy: park the introduction (with its optional
1835
+ // first message) until approve_introduction / reject_introduction.
1836
+ queued is pending_msg_t[] = [].
1837
+ if text != NIL { queued 0 -> ($text -> text?, $date -> now). }
1838
+ pending_introductions sender_id -> ($name -> joiner_name, $ad -> joiner_ad, $messages -> queued).
1839
+ return transaction::success [
1840
+ _notify_agent ($event -> $local_contact_request, $name -> joiner_name, $container_id -> sender_id, $queued -> _count queued|),
1841
+ _save_state NIL
1842
+ ].
1843
+ }
1844
+
1845
+ // An intra-root peer connects (Ring 1 of the identity hierarchy). Trust is
1846
+ // the delegation cert, not a registrar credential: the sender presents a
1847
+ // cert that must (a) name MY root, (b) verify against my root's keys,
1848
+ // (c) name the sender as the role, and (d) match the sender's address
1849
+ // document. The encrypted channel authenticates that the sender controls
1850
+ // its keys, and a cert is useless on anyone else's channel because of (c) —
1851
+ // so no nonce/freshness machinery is needed; the cert is a standing
1852
+ // credential, revoked by deleting the role (the root simply stops vouching).
1853
+ // A cert-less introduction is accepted ONLY from my root itself (the root
1854
+ // has no cert; the channel proves it controls the root's keys).
1855
+ // Intra-root introductions auto-accept regardless of local_auto_accept —
1856
+ // implicit trust inside the root is the point of Ring 1.
1857
+ 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+)
1858
+ {
1859
+ current_transaction_info::validate_origin_or_abort (transaction::envelope::origin::external,).
1860
+ encrypted_channel::check_encrypted_or_abort().
1861
+
1862
+ sender_id = current_transaction_info::get_external_envelope_or_abort() $from.
1863
+ now = (current_transaction_info::get_transaction_time())?.
1864
+
1865
+ link is a2a_protocol::contact_root_t+ = NIL.
1866
+ if cert_blob == NIL
1867
+ {
1868
+ // Sender claims to be my root.
1869
+ abort "A certificate-less sibling introduction is only accepted from my root." when a2a_messaging::delegation_cert == NIL.
1870
+ abort "Sender is not my root." when sender_id != (a2a_messaging::delegation_cert? $c $root_cid).
1871
+ link -> ($root_cid -> sender_id, $root_name -> joiner_name, $role_id -> "").
1872
+ }
1873
+ else
1874
+ {
1875
+ cert = (_read_or_abort cert_blob?) safe a2a_protocol::delegation_cert_t.
1876
+ abort "Unsupported delegation certificate version." when (cert $c $version) != 1.
1877
+ abort "Sibling certificate was issued for a different sender." when (cert $c $role_cid) != sender_id.
1878
+ abort "Sibling certificate does not match the sender's address document." when (cert $c $role_ad_hash) != (_value_id joiner_ad).
1879
+
1880
+ root_name_known is str = "".
1881
+ if a2a_messaging::delegation_cert != NIL
1882
+ {
1883
+ // I am a role: the cert must name MY root and verify against the
1884
+ // root key material pinned at delegation time.
1885
+ abort "My root material is missing — cannot verify sibling certificates." when a2a_messaging::root_ad == NIL.
1886
+ abort "Sibling certificate names a different root." when (cert $c $root_cid) != (a2a_messaging::delegation_cert? $c $root_cid).
1887
+ 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.
1888
+ if a2a_messaging::root_profile != NIL { root_name_known -> a2a_messaging::root_profile? $p $name. }
1889
+ }
1890
+ else
1891
+ {
1892
+ // I have no cert: I only accept certs that *I* issued, i.e. I am
1893
+ // the root. A legacy flat identity fails this check by design.
1894
+ abort "Sibling certificate names a different root." when (cert $c $root_cid) != _get_container_id().
1895
+ my_ad = address_document::get_my_address_document().
1896
+ 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.
1897
+ root_name_known -> a2a_messaging::my_name.
1898
+ }
1899
+ link -> ($root_cid -> cert $c $root_cid, $root_name -> root_name_known, $role_id -> cert $c $role_id).
1900
+ }
1901
+
1902
+ existing = a2a_messaging::contacts sender_id.
1903
+ if existing != NIL
1904
+ {
1905
+ // Already a contact (idempotent re-introduction): keep my assigned
1906
+ // name, refresh the stored material, deliver any payload.
1907
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1908
+ a2a_messaging::contact_roots sender_id -> link?.
1909
+ if text != NIL
1910
+ {
1911
+ mid = deposit_message sender_id (existing? $name) text? now "" no_reply.
1912
+ return transaction::success [
1913
+ _notify_agent ($event -> $message_received, $sender_name -> existing? $name, $msg_id -> mid, $date -> now),
1914
+ _save_state NIL
1915
+ ].
1916
+ }
1917
+ return transaction::success [ _save_state NIL ].
1918
+ }
1919
+
1920
+ a2a_messaging::contacts sender_id -> ($name -> joiner_name, $container_id -> sender_id).
1921
+ a2a_messaging::peer_ads sender_id -> joiner_ad.
1922
+ a2a_messaging::contact_roots sender_id -> link?.
1923
+ if text != NIL
1924
+ {
1925
+ mid = deposit_message sender_id joiner_name text? now "" no_reply.
1926
+ return transaction::success [
1927
+ _notify_agent ($event -> $sibling_contact_added, $name -> joiner_name, $container_id -> sender_id),
1928
+ _notify_agent ($event -> $message_received, $sender_name -> joiner_name, $msg_id -> mid, $date -> now),
1929
+ _save_state NIL
1930
+ ].
1931
+ }
1932
+ return transaction::success [
1933
+ _notify_agent ($event -> $sibling_contact_added, $name -> joiner_name, $container_id -> sender_id),
1934
+ _save_state NIL
1935
+ ].
1936
+ }
1937
+ }