delegate-connector-telegram 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: delegate-connector-telegram
3
+ Version: 0.1.0
4
+ Summary: OSS Telegram connector for the Terrene Delegate substrate (kailash.delegate).
5
+ Project-URL: Homepage, https://github.com/terrene-foundation/delegate-connectors
6
+ Project-URL: Changelog, https://github.com/terrene-foundation/delegate-connectors/blob/main/CHANGELOG.md
7
+ Author: Terrene Foundation
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: bot-api,connector,delegate,kailash,telegram
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Communications :: Chat
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: cryptography>=42.0
22
+ Requires-Dist: httpx>=0.27
23
+ Requires-Dist: kailash>=2.28.0
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
26
+ Requires-Dist: pytest>=8.0; extra == 'test'
27
+ Requires-Dist: python-dotenv>=1.0; extra == 'test'
28
+ Description-Content-Type: text/markdown
29
+
30
+ <!--
31
+ Copyright 2026 Terrene Foundation
32
+ SPDX-License-Identifier: Apache-2.0
33
+ -->
34
+
35
+ # delegate-connector-telegram
36
+
37
+ An OSS Python connector for the Terrene Delegate substrate. Implements the
38
+ shipped `kailash.delegate.Connector` ABC (kailash 2.26.2) for Telegram via the
39
+ Bot API. It mirrors the email connector's shape and differs only in transport
40
+ (HTTP-only Bot API) and identity model (integer `user_id` / `chat_id`).
41
+
42
+ The connector contract (the shipped ABC — `authenticate / read / write / invoke`
43
+ plus the `auth_verifier / ledger / revocation` trust properties) is:
44
+
45
+ - **`write`** — `action` is a thunk wrapping a Bot API `sendMessage` POST,
46
+ executed under audit, returning a real `SignedActionEnvelope`. The send is the
47
+ auditable external side-effect.
48
+ - **`read`** — `query` is a thunk wrapping a Bot API `getUpdates` long-poll fetch,
49
+ executed under audit, returning `(updates, AttestedReadReceipt)`.
50
+ - **`authenticate`** — resolves the dispatch identity's `delegate_id` to a
51
+ `Principal` against a dual-keyed resolver (by stringified integer `user_id`
52
+ and `chat_id`). An unknown identity resolves to `Reject` (fail-closed); a
53
+ `@username` handle is never a resolution key (ref-unsafe and mutable).
54
+ - **`invoke`** — single-method dispatch entry: authenticate FIRST (fail-closed,
55
+ before any Bot API call), then dispatch a send, returning a
56
+ `ConnectorInvocationResult(external_side_effect=True)`.
57
+ - Trust properties — `auth_verifier` returns the wired `Ed25519Verifier`;
58
+ `ledger` / `revocation` return shipped concretes (framework-first; no custom
59
+ trust primitives).
60
+
61
+ It subclasses `Connector` **directly** (ADR-1) — NOT `LegacyInvokeConnector`,
62
+ whose proxied `read` / `write` emit empty, unverifiable receipts. There is no
63
+ stale `connect() / identify() / normalize()` surface; those methods do not exist
64
+ in the shipped ABC.
65
+
66
+ ## Components
67
+
68
+ - **`transport.py`** — the `httpx`-backed Bot API transport (`sendMessage`
69
+ outbound + `getUpdates` inbound long-poll). A Bot API `429` raises a typed
70
+ `RateLimitedError` carrying `retry_after`; the caller decides backoff.
71
+ - **`connector.py`** — the `TelegramConnector` itself (the four ABC members + the
72
+ three trust properties) plus the `verify_action_envelope` /
73
+ `verify_read_receipt` helpers that re-derive identity-bound signing bytes.
74
+ - **`directory.py`** — the dual-keyed principal resolver + the closed-enum
75
+ `UnknownSenderDisposition` (unknown sender → `Reject`).
76
+ - **`validation.py`** — pure message-content validation (control-character
77
+ reject, `text` ≤ 4096 UTF-16 code units, `chat_id` shape), invoked at the
78
+ `OutboundMessage` construction boundary so every send route is covered.
79
+ - **`compose.py`** — `build_telegram_runtime`, which composes a real
80
+ `DelegateRuntime` around the connector with the shipped trust / audit /
81
+ verifier concretes (no mocks).
82
+
83
+ ## Install
84
+
85
+ ```bash
86
+ pip install -e connectors/telegram
87
+ ```
88
+
89
+ ## Configure
90
+
91
+ All credentials come from the environment (see `.env.example`):
92
+ `TELEGRAM_BOT_TOKEN` and `TELEGRAM_API_BASE`. Nothing is hardcoded; nothing is
93
+ logged. The token is part of the request URL, so the transport logs the method +
94
+ chat, never the URL.
95
+
96
+ ## Test
97
+
98
+ ```bash
99
+ pip install -e "connectors/telegram[test]"
100
+ # Tier 1 (unit)
101
+ python -m pytest connectors/telegram/tests/unit -q
102
+ # Tier 2/3 (integration — REAL TelegramTransport over a REAL httpx.AsyncClient
103
+ # whose byte stream terminates at an in-process protocol-faithful Bot API
104
+ # double; NO mock at the connector boundary, so these RUN in CI)
105
+ python -m pytest connectors/telegram/tests/integration -q
106
+ # Conformance (canonical conformance vector set)
107
+ python -m pytest connectors/telegram/tests/conformance -q
108
+ # Regression (behavioral security-property guards; NEVER deleted)
109
+ python -m pytest connectors/telegram/tests/regression -q
110
+ ```
111
+
112
+ The opt-in Tier-3 live test (`test_live_telegram`) skips with a clear "cannot
113
+ execute" reason unless real `TELEGRAM_*` credentials are present — it never falls
114
+ back to a mock. The end-to-end `runtime.execute()` outcome assertions are
115
+ strict-`xfail` gated on an SDK fix (kailash-py#1182); the connector's own
116
+ read / write receipts verify today.
117
+
118
+ ## License
119
+
120
+ Apache 2.0. All open-source IP is owned by the Terrene Foundation.
@@ -0,0 +1,10 @@
1
+ delegate_connectors/telegram/__init__.py,sha256=x4OL45mD-gWMZtQOWeucS7spIAhXpN6N6_gHeD3p9G0,2006
2
+ delegate_connectors/telegram/compose.py,sha256=2mawEoDhgqhAuaE8O9NRoYzHP_DaTT0zt7VD029dCUw,9341
3
+ delegate_connectors/telegram/connector.py,sha256=RP9s3VdAUyxOpI8KwNGyq7Nfni0iEES7AugTwvOG9mk,19905
4
+ delegate_connectors/telegram/directory.py,sha256=UhCRkKXx5Quz56emGwZfYDDeIj0Ea4qGlzjRQpuBJ0o,8154
5
+ delegate_connectors/telegram/transport.py,sha256=DiTv4JgBOT52AeCIemxqXFNmbgaNGPqPsJwrcgbbHAk,20671
6
+ delegate_connectors/telegram/validation.py,sha256=1MkqwYGeu1Zn9q8X0S7jpFXYM15xnrPe_NEwY_760Zg,7210
7
+ delegate_connector_telegram-0.1.0.dist-info/METADATA,sha256=TrNcSjPYcooSVwPJl9fLlYI99nJa1pzlBfmWx7LG5EA,5509
8
+ delegate_connector_telegram-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ delegate_connector_telegram-0.1.0.dist-info/licenses/LICENSE,sha256=DKFbIQY8niGx_We4B50lQtmpWkQ7i0aLU8vRC5MGkx0,11290
10
+ delegate_connector_telegram-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Terrene Foundation
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,52 @@
1
+ # Copyright 2026 Terrene Foundation
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Telegram connector for the Terrene Delegate substrate.
4
+
5
+ Implements the shipped ``kailash.delegate.Connector`` ABC (kailash 2.26.2) for
6
+ Telegram via the Bot API: ``sendMessage`` outbound (``write``) and ``getUpdates``
7
+ long-poll inbound (``read``), authenticated against a dual-keyed principal
8
+ resolver. See the package README + ``specs/`` in the monorepo root for the full
9
+ contract.
10
+
11
+ The full surface has shipped: the pure-logic foundation — principal resolution
12
+ (:mod:`delegate_connectors.telegram.directory`) and message-content validation
13
+ (:mod:`delegate_connectors.telegram.validation`) — alongside the ``httpx``-backed
14
+ Bot API transport (:mod:`delegate_connectors.telegram.transport`), the
15
+ ``TelegramConnector`` itself (:mod:`delegate_connectors.telegram.connector`), and
16
+ the runtime composition (:mod:`delegate_connectors.telegram.compose`).
17
+
18
+ ``__all__`` re-exports only the pure, always-importable primitives (directory +
19
+ validation) so importing the package root never forces an ``httpx`` import for
20
+ callers that only need the resolver / validators. The ``httpx``-dependent
21
+ modules are imported from their own submodules directly (e.g.
22
+ ``from delegate_connectors.telegram.transport import TelegramTransport``).
23
+ """
24
+
25
+ __version__ = "0.1.0"
26
+
27
+ from delegate_connectors.telegram.directory import (
28
+ ResolutionOutcome,
29
+ TelegramPrincipalResolver,
30
+ UnknownSenderDisposition,
31
+ )
32
+ from delegate_connectors.telegram.validation import (
33
+ MAX_TEXT_UTF16_UNITS,
34
+ MessageValidationError,
35
+ text_utf16_units,
36
+ validate_chat_id,
37
+ validate_text,
38
+ )
39
+
40
+ __all__ = [
41
+ "__version__",
42
+ # Principal resolution (directory.py).
43
+ "TelegramPrincipalResolver",
44
+ "UnknownSenderDisposition",
45
+ "ResolutionOutcome",
46
+ # Message-content validation (validation.py — pure, no transport).
47
+ "MessageValidationError",
48
+ "validate_text",
49
+ "validate_chat_id",
50
+ "text_utf16_units",
51
+ "MAX_TEXT_UTF16_UNITS",
52
+ ]
@@ -0,0 +1,249 @@
1
+ # Copyright 2026 Terrene Foundation
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Compose a runnable ``DelegateRuntime`` around a :class:`TelegramConnector`.
4
+
5
+ Builds the full shipped composition — ``PrincipalDirectory`` +
6
+ ``Ed25519Verifier``, in-memory ``AuditChainEngine`` over a ``TrustLineageChain``,
7
+ ``TenantScopedCascade`` (root grantee registered with a real Ed25519 grant
8
+ proof), ``Role``, ``DispatchSurface``, and ``DelegateRuntime`` — using the
9
+ spine-shipped concretes for everything except the connector. No mocks; no
10
+ Postgres; no PACT (the shipped runtime audit is in-memory).
11
+
12
+ The runtime is constructed with a real ``Ed25519Verifier`` (NOT ``NullVerifier``)
13
+ and a real Ed25519 ``signer``. All constructors succeed and the composition
14
+ passes the runtime's R2-composition gate.
15
+
16
+ ``runtime.execute()`` — end-to-end (fixed at kailash >= 2.28.0):
17
+ Previously gated on kailash-py#1182 — the runtime/dispatch audit-emit path
18
+ signed the event PAYLOAD bytes while ``AuditChainEngine.emit_event`` verified
19
+ the FULL audit-entry signing bytes, so ``execute()`` returned
20
+ ``taod_state.phase == "failed"`` under any real verifier at the first phase
21
+ transition. Fixed at kailash <= 2.28.1 (the connector floor is now
22
+ ``>=2.28.0``); ``runtime.execute()`` now completes end-to-end. See
23
+ ``workspaces/whatsapp/journal/0008`` for the fix verification.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import uuid
29
+ from dataclasses import dataclass
30
+ from datetime import datetime, timezone
31
+
32
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
33
+
34
+ from kailash.delegate import (
35
+ AuditChainEngine,
36
+ DelegateIdentity,
37
+ DelegateRuntime,
38
+ DispatchSurface,
39
+ Ed25519Verifier,
40
+ PrincipalDirectory,
41
+ )
42
+ from kailash.delegate.dispatch import Principal
43
+ from kailash.delegate.envelope import DelegateConstraintEnvelope
44
+ from kailash.delegate.trust import TenantScope, TenantScopedCascade
45
+ from kailash.delegate.types import (
46
+ CapabilitySet,
47
+ DelegateGenesisRecord,
48
+ Role,
49
+ RoleLifecycleState,
50
+ RoleScope,
51
+ )
52
+ from kailash.trust._json import canonical_json_dumps
53
+ from kailash.trust.chain import AuthorityType, GenesisRecord, TrustLineageChain
54
+ from kailash.trust.envelope import ConstraintEnvelope
55
+
56
+ from delegate_connectors.telegram.connector import TelegramConnector
57
+ from delegate_connectors.telegram.directory import TelegramPrincipalResolver
58
+ from delegate_connectors.telegram.transport import TelegramTransport
59
+
60
+ __all__ = [
61
+ "TelegramV0Signature",
62
+ "ComposedTelegramRuntime",
63
+ "build_telegram_runtime",
64
+ ]
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class TelegramV0Signature:
69
+ """Minimal application-supplied dispatch signature (v0 fixture).
70
+
71
+ Satisfies the shipped ``SignatureContract`` Protocol (``name`` +
72
+ ``input_schema`` + ``output_schema``). This is a DOCUMENTED v0 placeholder:
73
+ real applications supply their own structured signature. It is NOT a
74
+ stub-for-production — it is the genuine, minimal v0 dispatch contract for
75
+ a Telegram ``sendMessage``, and it is honored by the dispatch surface's
76
+ input validation.
77
+ """
78
+
79
+ name: str = "telegram-send"
80
+ input_schema: dict[str, type] | None = None
81
+ output_schema: dict[str, type] | None = None
82
+
83
+ def __post_init__(self) -> None:
84
+ if self.input_schema is None:
85
+ # chat_id can be int OR str (@channelusername); the dispatch surface
86
+ # accepts the first matching type from the tuple union (the SDK
87
+ # schema check is a basic isinstance, not a discriminated union),
88
+ # so list the most common (int) first.
89
+ object.__setattr__(
90
+ self,
91
+ "input_schema",
92
+ {"chat_id": int, "text": str},
93
+ )
94
+ if self.output_schema is None:
95
+ object.__setattr__(
96
+ self,
97
+ "output_schema",
98
+ {"message_id": int, "chat_id": int, "ok": bool},
99
+ )
100
+
101
+
102
+ @dataclass(frozen=True, slots=True)
103
+ class ComposedTelegramRuntime:
104
+ """The composed runtime plus the handles a caller needs to drive it.
105
+
106
+ ``runtime.execute(payload)`` is the dispatch entry (see the module-level
107
+ KNOWN SDK BLOCKER). ``connector`` is the bound :class:`TelegramConnector`;
108
+ ``verifier`` verifies every receipt the connector signs; ``identity`` is
109
+ the dispatch identity registered as the cascade root grantee.
110
+ """
111
+
112
+ runtime: DelegateRuntime
113
+ dispatch_surface: DispatchSurface
114
+ connector: TelegramConnector
115
+ verifier: Ed25519Verifier
116
+ identity: DelegateIdentity
117
+ audit_engine: AuditChainEngine
118
+
119
+
120
+ def build_telegram_runtime(
121
+ *,
122
+ transport: TelegramTransport,
123
+ sender_user_id: int,
124
+ sender_chat_id: int,
125
+ sender_principal_tenant: str = "tenant-telegram-v0",
126
+ signing_key: Ed25519PrivateKey | None = None,
127
+ ) -> ComposedTelegramRuntime:
128
+ """Compose a real ``DelegateRuntime`` around a :class:`TelegramConnector`.
129
+
130
+ All trust/audit/verifier concretes are the spine-shipped ones; only the
131
+ connector is connector-specific. The returned runtime is reusable and
132
+ holds no per-call global state.
133
+
134
+ Args:
135
+ transport: the connector's Bot API transport (point it at a local Bot
136
+ API service in integration tests, the real Telegram API in
137
+ production).
138
+ sender_user_id: the Telegram ``user_id`` the dispatch identity
139
+ authenticates as (the resolver's primary key).
140
+ sender_chat_id: the paired ``chat_id`` registered alongside the
141
+ ``user_id`` — both view the same Principal.
142
+ sender_principal_tenant: the tenant the connector operates under.
143
+ signing_key: optional Ed25519 key; generated if absent. The matching
144
+ public key is registered in the directory so the connector's
145
+ receipts verify under the composed verifier.
146
+ """
147
+ sk = signing_key or Ed25519PrivateKey.generate()
148
+ pk_bytes = sk.public_key().public_bytes_raw()
149
+
150
+ def signer(canonical_bytes: bytes) -> str:
151
+ # Ed25519 signature (64 bytes) -> 128-char lowercase hex, the
152
+ # audit-engine + dispatch-surface signer contract.
153
+ return sk.sign(canonical_bytes).hex()
154
+
155
+ delegate_id = uuid.uuid4()
156
+ identity = DelegateIdentity(
157
+ delegate_id=delegate_id,
158
+ sovereign_ref="telegram-connector-sovereign",
159
+ role_binding_ref="telegram-connector-role-binding",
160
+ genesis_ref="telegram-connector-genesis",
161
+ principal_kind="delegate",
162
+ )
163
+
164
+ directory = PrincipalDirectory(
165
+ identities=(identity,),
166
+ verification_keys={delegate_id: pk_bytes},
167
+ )
168
+ verifier = Ed25519Verifier(directory)
169
+
170
+ # In-memory audit chain (no Postgres) gated by the same verifier class.
171
+ genesis_block = GenesisRecord(
172
+ id="telegram-genesis-block",
173
+ agent_id=str(delegate_id),
174
+ authority_id="telegram-connector-authority",
175
+ authority_type=AuthorityType.SYSTEM,
176
+ created_at=datetime.now(timezone.utc),
177
+ signature="00" * 64,
178
+ )
179
+ chain = TrustLineageChain(genesis=genesis_block)
180
+ audit_engine = AuditChainEngine(chain=chain, verifier=verifier)
181
+
182
+ delegate_genesis = DelegateGenesisRecord(
183
+ block=genesis_block, spec_version="0", capabilities=("telegram.send",)
184
+ )
185
+ envelope = DelegateConstraintEnvelope.from_genesis(
186
+ ConstraintEnvelope(), delegate_genesis
187
+ )
188
+
189
+ # Tenant cascade; register the dispatch identity as root grantee with a
190
+ # real Ed25519 grant proof (a wired verifier refuses an unsigned seed).
191
+ tenant = TenantScope.for_tenant(sender_principal_tenant)
192
+ cascade = TenantScopedCascade(tenant=tenant, verifier=verifier)
193
+ grant_canonical = canonical_json_dumps(
194
+ {"delegate_id": str(delegate_id), "tenant": tenant.tenant_id}
195
+ ).encode("utf-8")
196
+ cascade.register_root_grantee(identity, grant_proof=sk.sign(grant_canonical).hex())
197
+
198
+ role = Role(
199
+ role_id=uuid.uuid4(),
200
+ display_name="telegram-connector-role",
201
+ scope=RoleScope(
202
+ domain="telegram",
203
+ capabilities=CapabilitySet(capabilities=("telegram.send",)),
204
+ ),
205
+ lifecycle=RoleLifecycleState.ACTIVE,
206
+ )
207
+
208
+ principal = Principal(
209
+ delegate_id=str(delegate_id),
210
+ tenant_id=tenant.tenant_id,
211
+ claims={"user_id": sender_user_id, "chat_id": sender_chat_id},
212
+ )
213
+ resolver = TelegramPrincipalResolver([(sender_user_id, sender_chat_id, principal)])
214
+
215
+ connector = TelegramConnector(
216
+ transport=transport,
217
+ resolver=resolver,
218
+ signing_key=sk,
219
+ verifier=verifier,
220
+ tenant_id=tenant.tenant_id,
221
+ )
222
+
223
+ dispatch_surface = DispatchSurface(
224
+ connector,
225
+ TelegramV0Signature(),
226
+ envelope,
227
+ identity,
228
+ audit_engine=audit_engine,
229
+ trust_cascade=cascade,
230
+ role=role,
231
+ signer=signer,
232
+ verifier=verifier,
233
+ )
234
+ runtime = DelegateRuntime(
235
+ dispatch_surface=dispatch_surface,
236
+ audit_engine=audit_engine,
237
+ cascade=cascade,
238
+ envelope=envelope,
239
+ identity=identity,
240
+ signer=signer,
241
+ )
242
+ return ComposedTelegramRuntime(
243
+ runtime=runtime,
244
+ dispatch_surface=dispatch_surface,
245
+ connector=connector,
246
+ verifier=verifier,
247
+ identity=identity,
248
+ audit_engine=audit_engine,
249
+ )