@ours.network/tg-connector 2.0.4-nightly.2 → 2.1.1
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.
- package/README.md +17 -0
- package/dist/connector.js +770 -68
- package/docs/telegram-widgets.md +238 -0
- package/examples/widget-choice.html +55 -0
- package/package.json +7 -6
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
# Telegram widgets for connected agents
|
|
2
|
+
|
|
3
|
+
An agent connected through a route can send a Telegram **widget** to the route's
|
|
4
|
+
private chat: a small, self-contained HTML/CSS/JS document that Telegram runs
|
|
5
|
+
inside the message. The agent receives the user's widget requests and changes
|
|
6
|
+
what the widget shows. Ordinary agent messages are never rendered as widgets.
|
|
7
|
+
Only the explicit `telegram_widget_send` command creates one.
|
|
8
|
+
|
|
9
|
+
## What Telegram provides
|
|
10
|
+
|
|
11
|
+
Sources: Bot API 10.4, dated 9 November 2026, checked 10 November 2026:
|
|
12
|
+
[changelog](https://core.telegram.org/bots/api-changelog#november-9-2026),
|
|
13
|
+
[sendWidget](https://core.telegram.org/bots/api#sendwidget),
|
|
14
|
+
[WidgetQuery](https://core.telegram.org/bots/api#widgetquery) and the
|
|
15
|
+
[widgets guide](https://core.telegram.org/bots/widgets).
|
|
16
|
+
|
|
17
|
+
- A widget is **fixed code plus changeable state**. Its HTML never changes after
|
|
18
|
+
sending. Only the bot can write its state: `chat_data` (this message) and
|
|
19
|
+
`public_data`.
|
|
20
|
+
- **Production:** widgets work only in the bot's private chat with a user, and are
|
|
21
|
+
automatically protected (no forwarding). Groups, inline mode and forwards are
|
|
22
|
+
test-server only. Shared widgets (`is_shared`) are a separate feature that this
|
|
23
|
+
connector does not use yet.
|
|
24
|
+
- **Sandbox:** the widget runs in QuickJS with no network, no external resources
|
|
25
|
+
and no keyboard input. Its one way out is `TelegramWidget.request(data)`.
|
|
26
|
+
- `request(data)` sends 1–64 UTF-8 bytes. The bot receives it as a `widget_query`
|
|
27
|
+
update and must call `answerWidgetQuery` **within 15 s** (answer data ≤1024
|
|
28
|
+
bytes). An answer does not change state. In the private chat, a widget may also
|
|
29
|
+
send requests **in the background**, without a tap.
|
|
30
|
+
- State changes go through `editMessageWidgetData`. The running widget gets
|
|
31
|
+
`chatDataChanged` / `publicDataChanged`.
|
|
32
|
+
|
|
33
|
+
| Limit | Value |
|
|
34
|
+
|---|---|
|
|
35
|
+
| HTML | ≤32768 UTF-8 bytes and ≤4096 bytes after zlib level 9; valid UTF-8 without NUL |
|
|
36
|
+
| `chat_data`, `public_data` | ≤1024 UTF-8 bytes each, no NUL |
|
|
37
|
+
| request `data` | 1–64 UTF-8 bytes |
|
|
38
|
+
| answer | within 15 s; ≤1024 bytes |
|
|
39
|
+
| requests | 5 per 5 s per user and bot |
|
|
40
|
+
|
|
41
|
+
The connector checks the HTML size locally with Node's zlib. Telegram notes that
|
|
42
|
+
zlib builds can differ by a few dozen bytes near 4096. Telegram's own
|
|
43
|
+
`INPUT_MEDIA_WIDGET_TOO_LARGE` is still reported back as `rejected`. Measure near
|
|
44
|
+
the cap with
|
|
45
|
+
`python3 -c 'import sys,zlib; print(len(zlib.compress(sys.stdin.buffer.read(), 9)))' < widget.html`.
|
|
46
|
+
|
|
47
|
+
## Which routes offer widgets
|
|
48
|
+
|
|
49
|
+
A route offers widgets only when it is pinned to **one private chat**: a positive
|
|
50
|
+
chat id with no topic. Catch-all, group and topic routes advertise no widget
|
|
51
|
+
commands, so `send_command` reports `unsupported_peer`.
|
|
52
|
+
|
|
53
|
+
Only the route's connected agent can use them. That is the route's recorded
|
|
54
|
+
proxy agent (`peerCid`), and the command's sender must be that agent as
|
|
55
|
+
authenticated by ours, never by a name or an argument.
|
|
56
|
+
|
|
57
|
+
A route records its agent once, from the daemon's authenticated contact list, and
|
|
58
|
+
only when the route has **exactly one** contact. It checks when the route starts,
|
|
59
|
+
when a contact is added, and when a widget command arrives while no agent is
|
|
60
|
+
recorded. This also covers routes created before the binding was recorded. A
|
|
61
|
+
recorded agent is never replaced by later contacts. If the route has no contact or
|
|
62
|
+
several, or the contact list cannot be read, or the binding cannot be saved, no
|
|
63
|
+
agent is recorded and widget commands answer `not_authorized`; ordinary messages
|
|
64
|
+
are unaffected. The connector log names the reason (`proxy agent not bound ...`).
|
|
65
|
+
|
|
66
|
+
## Agent usage
|
|
67
|
+
|
|
68
|
+
The route identity advertises two typed ours commands. With the ours MCP tools:
|
|
69
|
+
|
|
70
|
+
1. `list_contact_commands(contact: "<route contact>")` shows `telegram_widget_send`
|
|
71
|
+
and `telegram_widget_update` with their JSON Schemas.
|
|
72
|
+
2. `send_command(contact, "telegram_widget_send", {...})`, then `get_messages`.
|
|
73
|
+
The `command_result` whose `reply_to.wire_id` is the request's wire id carries
|
|
74
|
+
`{ok:true, result:{...}}`.
|
|
75
|
+
|
|
76
|
+
### `telegram_widget_send`
|
|
77
|
+
|
|
78
|
+
```json
|
|
79
|
+
{
|
|
80
|
+
"request_id": "choice-2026-11-10-1",
|
|
81
|
+
"html": "<…contents of examples/widget-choice.html…>",
|
|
82
|
+
"chat_data": "{\"q\":\"Ship it?\",\"opts\":[\"Yes\",\"Later\"],\"pick\":null,\"n\":0}",
|
|
83
|
+
"caption": "Ship it?"
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Optional fields: `public_data`, `width` and `height` (Telegram clamps them). The
|
|
88
|
+
chat is always the route's own chat. It cannot be given as an argument.
|
|
89
|
+
|
|
90
|
+
The `result.status` is one of:
|
|
91
|
+
|
|
92
|
+
| status | meaning |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `sent` | posted; includes `widget_ref` and `message_id` |
|
|
95
|
+
| `rejected` | not posted. `code` is `invalid_html`, `invalid_state`, `invalid_arguments`, `not_authorized`, `unsupported_route`, `ledger_full`, `ledger_unavailable`, `state_unwritable`, `request_id_conflict`, or `telegram_refused` (with `telegram_error_code` and a short, token-free `description`) |
|
|
96
|
+
| `unknown` | the request may have been posted (transport error, 5xx, unreadable reply, or a connector restart mid-send). It is **never re-sent**. |
|
|
97
|
+
|
|
98
|
+
If the connector cannot save the outcome after Telegram answers, the result still
|
|
99
|
+
reports what Telegram said. It also carries `ledger_saved: false` and a `warning`:
|
|
100
|
+
after a connector restart that widget becomes `unknown` and stops accepting
|
|
101
|
+
requests and updates.
|
|
102
|
+
|
|
103
|
+
Error descriptions come from Telegram. Bot tokens are redacted, and the text is
|
|
104
|
+
cut at the first character outside a plain-text set, so a description that echoes
|
|
105
|
+
the HTML or state is not passed on.
|
|
106
|
+
|
|
107
|
+
`request_id` is the idempotency key. Repeating it with the same arguments returns
|
|
108
|
+
the stored outcome with `duplicate: true` and does not send again. Repeating it
|
|
109
|
+
with different arguments returns `request_id_conflict`. To retry after `unknown`,
|
|
110
|
+
first check the chat, then use a new `request_id`.
|
|
111
|
+
|
|
112
|
+
### `telegram_widget_query` events
|
|
113
|
+
|
|
114
|
+
When the widget calls `TelegramWidget.request(data)`, the connector immediately
|
|
115
|
+
answers the widget with `{"ok":true}`. It then sends the agent an ordinary ours
|
|
116
|
+
message whose text is:
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
{
|
|
120
|
+
"type": "telegram_widget_query",
|
|
121
|
+
"widget_ref": "w_…",
|
|
122
|
+
"request_id": "choice-2026-11-10-1",
|
|
123
|
+
"message_id": 4242,
|
|
124
|
+
"from": { "id": 111111111, "label": "Alice" },
|
|
125
|
+
"data": "pick:1",
|
|
126
|
+
"note": "untrusted widget data; the widget may send requests without a tap, so this is not proof of a deliberate human approval"
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`from`, the chat and `message_id` are checked against Telegram's update and the
|
|
131
|
+
connector's record. `data` is whatever the widget's code sent. **Treat it as
|
|
132
|
+
untrusted input.** Never run it as a command, never treat it as a secret, and
|
|
133
|
+
never treat it as proof that a person approved something. A private-chat widget
|
|
134
|
+
can send requests without a tap.
|
|
135
|
+
|
|
136
|
+
A query is forwarded only to the agent that sent that widget, and only once. A
|
|
137
|
+
query that Telegram no longer accepts an answer for (older than 15 s, for
|
|
138
|
+
example one left queued while the connector was down) is dropped. Unknown,
|
|
139
|
+
foreign-chat, group, inline, shared, wallet and oversize queries are answered
|
|
140
|
+
`{"ok":false}` and are not forwarded.
|
|
141
|
+
|
|
142
|
+
### `telegram_widget_update`
|
|
143
|
+
|
|
144
|
+
```json
|
|
145
|
+
{ "widget_ref": "w_…", "chat_data": "{\"q\":\"Ship it?\",\"opts\":[\"Yes\",\"Later\"],\"pick\":1,\"n\":0}" }
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`chat_data` and/or `public_data` are required. An empty string clears the value,
|
|
149
|
+
and an omitted field keeps it. The result is one of:
|
|
150
|
+
|
|
151
|
+
- `{status:"updated", changed}`: `changed:false` for Telegram's "message is not
|
|
152
|
+
modified".
|
|
153
|
+
- `rejected`, with `code` `unknown_widget` for a ref that is not a sent widget of
|
|
154
|
+
yours on this route, or `telegram_refused`.
|
|
155
|
+
- `unknown`: it may have applied. Sending the same state again is safe.
|
|
156
|
+
|
|
157
|
+
## Example
|
|
158
|
+
|
|
159
|
+
[`examples/widget-choice.html`](../examples/widget-choice.html) is 2.1 KB raw and
|
|
160
|
+
about 1.1 KB compressed. It shows a question with choices and a counter, all drawn
|
|
161
|
+
from `chat_data`. A tap sends `pick:<n>` or `inc`, and the widget shows "sent —
|
|
162
|
+
waiting for the agent" until the agent's `telegram_widget_update` arrives. It uses
|
|
163
|
+
only the chat's theme variables and default buttons, and has no wallet or payment
|
|
164
|
+
features.
|
|
165
|
+
|
|
166
|
+
A minimal agent loop:
|
|
167
|
+
|
|
168
|
+
1. Send the widget with the initial `chat_data`.
|
|
169
|
+
2. On a `telegram_widget_query` with `data` `pick:1`, validate it against the
|
|
170
|
+
options it offered.
|
|
171
|
+
3. Call `telegram_widget_update` with the new state, for example `pick: 1`.
|
|
172
|
+
|
|
173
|
+
## Persistence and failure semantics
|
|
174
|
+
|
|
175
|
+
`<state>/<route>/widgets.json` (mode 0600) holds one record per send:
|
|
176
|
+
`widget_ref`, `request_id`, the argument hash, the owning agent, chat, message id
|
|
177
|
+
and outcome. It also holds the last 1000 answered query ids. It contains no HTML
|
|
178
|
+
and no state.
|
|
179
|
+
|
|
180
|
+
- The `sending` record is written **before** the single `sendWidget` request,
|
|
181
|
+
which is never retried by the transport. If it cannot be written, nothing is
|
|
182
|
+
sent. A record still `sending` at startup becomes `unknown`.
|
|
183
|
+
- Records are never evicted. At 2000 per route, new sends are refused with
|
|
184
|
+
`ledger_full`; existing widgets keep working.
|
|
185
|
+
- If `widgets.json` exists but is unreadable or invalid, the route's widgets are
|
|
186
|
+
disabled (`ledger_unavailable`, queries refused) rather than silently starting
|
|
187
|
+
over. To repair it, stop the connector, fix or move the file, and restart.
|
|
188
|
+
Moving it forfeits the history of earlier widgets: their queries are then
|
|
189
|
+
refused.
|
|
190
|
+
- Typed commands share the ours inbox with ordinary messages. The ordered
|
|
191
|
+
Telegram drain never posts a `command` or `command_result` row to Telegram. It
|
|
192
|
+
consumes the row, and the ours SDK runs the handler and returns its result. The
|
|
193
|
+
daemon marks a command read before its handler runs, so a command is never
|
|
194
|
+
replayed after a restart.
|
|
195
|
+
- A query id is saved before the query is acknowledged. If it cannot be saved,
|
|
196
|
+
the query is answered `{"ok":false}` and not forwarded, so a restart can never
|
|
197
|
+
deliver it twice.
|
|
198
|
+
- One `getUpdates` poller per bot serves both messages and `widget_query`
|
|
199
|
+
(`allowed_updates: ["message", "widget_query"]`). Messages are still handled
|
|
200
|
+
one at a time and in order, but on a queue the poller does not wait for. Each
|
|
201
|
+
widget query is handled as soon as it is fetched, concurrently with other
|
|
202
|
+
queries. A slow message (a media download or speech-to-text) or a slow forward
|
|
203
|
+
to one agent therefore does not hold back other queries. Forwarded query
|
|
204
|
+
events can arrive in a different order than the taps; use your own state (for
|
|
205
|
+
example a revision number in `chat_data`) if order matters.
|
|
206
|
+
- The `offset` the poller sends to Telegram, which confirms every earlier update,
|
|
207
|
+
never moves past the oldest message that has not finished. A message still
|
|
208
|
+
queued or running at a stop or crash is delivered again after the restart, as
|
|
209
|
+
it was before widgets. While such a message runs, later updates come back on
|
|
210
|
+
each poll and are skipped by `update_id`. During that time the poller polls
|
|
211
|
+
about once a second.
|
|
212
|
+
|
|
213
|
+
**Limit: acknowledgements are prompt, not guaranteed.** `getUpdates` returns at
|
|
214
|
+
most 100 updates per call. This window is per bot, across all its routes. While
|
|
215
|
+
an ordinary message is still being handled, the poller only sees the 99 updates
|
|
216
|
+
after it. The poller also pauses fetching when more than 200 messages are
|
|
217
|
+
unfinished or 64 queries are in flight. A widget query beyond the window, or one
|
|
218
|
+
that arrives during such a pause, waits until handling catches up. If that takes
|
|
219
|
+
longer than Telegram's 15 s, the widget's `request()` fails with `TIMEOUT`, the
|
|
220
|
+
connector's late answer is refused as stale, and **nothing is forwarded to the
|
|
221
|
+
agent**. Ordinary messages are not lost in either case. Removing this limit
|
|
222
|
+
would need a durable on-disk message queue, which is deferred.
|
|
223
|
+
|
|
224
|
+
## Not included
|
|
225
|
+
|
|
226
|
+
These are not used by this connector:
|
|
227
|
+
|
|
228
|
+
- groups, forum topics, inline mode and forwards, which are not available in
|
|
229
|
+
production;
|
|
230
|
+
- shared widgets (`is_shared`, `sendSharedWidget`, `editSharedWidgetData`,
|
|
231
|
+
`shared_widget_query`), which this connector does not use yet;
|
|
232
|
+
- agent-authored query answers, since the connector answers at once to meet the
|
|
233
|
+
15 s deadline;
|
|
234
|
+
- a durable on-disk queue for ordinary messages, which would remove the
|
|
235
|
+
100-update window limit described above;
|
|
236
|
+
- captions with formatting;
|
|
237
|
+
- reply keyboards under a widget;
|
|
238
|
+
- wallet and payment requests.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
<!-- A tiny agent-driven Telegram widget: a question with choices and a counter.
|
|
2
|
+
Everything it shows comes from chat_data, which only the agent writes
|
|
3
|
+
(telegram_widget_update). A tap sends "pick:<n>" or "inc" to the agent and
|
|
4
|
+
shows "sent…" until the agent's new state arrives. See docs/telegram-widgets.md.
|
|
5
|
+
chat_data: {"q":"Ship it?","opts":["Yes","Later"],"pick":null,"n":0,"note":""} -->
|
|
6
|
+
<style>
|
|
7
|
+
.opts{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}
|
|
8
|
+
.opts button.on{outline:2px solid var(--tg-theme-accent-text-color)}
|
|
9
|
+
.meta{color:var(--tg-theme-hint-color);font-size:.9em}
|
|
10
|
+
</style>
|
|
11
|
+
<h3 id="q">…</h3>
|
|
12
|
+
<div class="opts" id="opts"></div>
|
|
13
|
+
<p><button id="inc">+1</button> <span id="n"></span></p>
|
|
14
|
+
<p class="meta" id="note"></p>
|
|
15
|
+
<script>
|
|
16
|
+
const W = window.TelegramWidget;
|
|
17
|
+
const $ = (id) => document.getElementById(id);
|
|
18
|
+
let pending = false;
|
|
19
|
+
function state() {
|
|
20
|
+
try { return JSON.parse(W.chatData) || {}; } catch (e) { return {}; }
|
|
21
|
+
}
|
|
22
|
+
function ask(data) {
|
|
23
|
+
if (pending) return;
|
|
24
|
+
pending = true;
|
|
25
|
+
render();
|
|
26
|
+
W.request(data).then(
|
|
27
|
+
(a) => {
|
|
28
|
+
if (a.result === '{"ok":false}') { pending = false; render(); $('note').textContent = 'refused'; }
|
|
29
|
+
else if (pending) $('note').textContent = 'sent — waiting for the agent';
|
|
30
|
+
},
|
|
31
|
+
(e) => { pending = false; render(); $('note').textContent = 'not sent (' + e.code + ')'; },
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
function render() {
|
|
35
|
+
const s = state();
|
|
36
|
+
$('q').textContent = s.q || 'Waiting for the agent…';
|
|
37
|
+
const box = $('opts');
|
|
38
|
+
box.textContent = '';
|
|
39
|
+
(Array.isArray(s.opts) ? s.opts : []).slice(0, 6).forEach((label, i) => {
|
|
40
|
+
const b = document.createElement('button');
|
|
41
|
+
b.textContent = String(label);
|
|
42
|
+
if (s.pick === i) b.className = 'on';
|
|
43
|
+
b.disabled = pending;
|
|
44
|
+
b.addEventListener('click', () => ask('pick:' + i));
|
|
45
|
+
box.appendChild(b);
|
|
46
|
+
});
|
|
47
|
+
$('inc').disabled = pending;
|
|
48
|
+
$('n').textContent = 'count: ' + (Number(s.n) || 0);
|
|
49
|
+
$('note').textContent = s.note || '';
|
|
50
|
+
}
|
|
51
|
+
$('inc').addEventListener('click', () => ask('inc'));
|
|
52
|
+
W.onEvent('chatDataChanged', () => { pending = false; render(); });
|
|
53
|
+
render();
|
|
54
|
+
W.ready();
|
|
55
|
+
</script>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ours.network/tg-connector",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "Bridge Telegram bots to ours.network agents \u2014 attaches to an already-running ours daemon and bridges one Telegram chat/topic to one agent per route. Run `ours-tg-connector add_new_connection`.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "FSL-1.1-Apache-2.0",
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
"files": [
|
|
21
21
|
"dist",
|
|
22
22
|
"README.md",
|
|
23
|
-
"docs"
|
|
23
|
+
"docs",
|
|
24
|
+
"examples"
|
|
24
25
|
],
|
|
25
26
|
"engines": {
|
|
26
27
|
"node": ">=22"
|
|
@@ -37,15 +38,15 @@
|
|
|
37
38
|
"test:v1-lifecycle": "node tests/v1-lifecycle.integration.mjs cli"
|
|
38
39
|
},
|
|
39
40
|
"dependencies": {
|
|
40
|
-
"@ours.network/sdk": "5.2.
|
|
41
|
+
"@ours.network/sdk": "5.2.0",
|
|
41
42
|
"undici": "^7.28.0"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
44
|
-
"@ours.network/cli": "4.
|
|
45
|
-
"@ours.network/daemon": "5.2.1-nightly.1",
|
|
45
|
+
"@ours.network/cli": "4.0.1",
|
|
46
46
|
"@types/node": "^20.14.0",
|
|
47
47
|
"esbuild": "^0.24.2",
|
|
48
48
|
"tsx": "^4.19.0",
|
|
49
|
-
"typescript": "^5.5.4"
|
|
49
|
+
"typescript": "^5.5.4",
|
|
50
|
+
"@ours.network/daemon": "5.2.0"
|
|
50
51
|
}
|
|
51
52
|
}
|