@ours.network/tg-connector 0.3.3-nightly.4 → 0.5.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 +131 -27
  2. package/dist/cli.js +98 -68
  3. package/dist/connector.js +24884 -68992
  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
package/README.md CHANGED
@@ -109,6 +109,102 @@ In a **privacy-mode** group only the `/id@<bot_username>` form is delivered (see
109
109
  note above); in DMs and privacy-off groups bare `/id` works too. In a group with
110
110
  several bots, only the one named in `/id@<bot_username>` answers.
111
111
 
112
+ ### Reply threading
113
+
114
+ An agent's answer can arrive in Telegram **as a reply to the message that prompted
115
+ it**, so a busy group chat stays readable. The mechanism is one mapping:
116
+
117
+ 1. an inbound Telegram message is sent to the agent as ours `wire_id` **W**, and the
118
+ route records `W → (chat id, message id)` in `messages.json` in its state dir;
119
+ 2. the agent answers with `reply_to_wire_id = W` (the `send_message` tool already
120
+ supports it);
121
+ 3. the connector resolves **W** back to that Telegram message and sends with
122
+ `reply_parameters.message_id`.
123
+
124
+ **It only works when the agent fills `reply_to_wire_id`.** An agent that does not
125
+ gets ordinary un-threaded messages — that is a property of the sender, not a
126
+ connector fault, so it is worth putting in the persona of any role that writes to
127
+ Telegram. If a pointer resolves to nothing (never mapped, or older than the 30-day
128
+ retention below) the message is delivered **plain**; a "similar" or most-recent
129
+ message is never substituted.
130
+
131
+ The map is persistent (it survives a daemon restart), holds **no message content** —
132
+ only chat/message ids, the contact id and the receipt state — and is pruned at
133
+ **30 days** / 2000 rows per route, oldest first.
134
+
135
+ ### Delivery & read receipts as reactions
136
+
137
+ When the agent's node confirms a message, the connector puts a **reaction** on the
138
+ originating Telegram message: 👀 when it was **delivered**, then 👌 once the agent
139
+ has **read** it (its `get` path). Because a bot may hold **at most one reaction per
140
+ message**, read *replaces* delivered rather than sitting beside it.
141
+
142
+ The confirmations themselves are core 0.7.0 receipts, not something the connector
143
+ invents: emission is gated on both sides' `core.receipts.*` capabilities (the
144
+ connector declares `emit` and `receive`), and application is **monotonic** per
145
+ (peer, message) over `unknown < sent < delivered < read` — a duplicate or
146
+ out-of-order receipt changes nothing. Receipts are **best-effort UX**: a missing
147
+ reaction does **not** mean the message failed to arrive, and a Telegram refusal on a
148
+ reaction (reactions disabled in the chat, message deleted) is logged and never
149
+ affects message delivery.
150
+
151
+ > **The agent side has to emit them.** A peer only sends receipts if *it* advertises
152
+ > `core.receipts.emit`. Against an agent node that does not, the reactions simply
153
+ > never appear — everything else keeps working.
154
+
155
+ Per **connection** (not per bot — `/receipts off` on one route leaves the others
156
+ alone), in the route's own chat:
157
+
158
+ ```
159
+ /receipts on # turn delivery/read reactions on for this connection
160
+ /receipts off # …and off
161
+ /receipts status # show the current setting and emoji
162
+ /emoji delivered <e> # set the "delivered" reaction
163
+ /emoji read <e> # set the "read" reaction
164
+ /emoji reset # back to 👀 / 👌
165
+ ```
166
+
167
+ Commands are parsed **in connector code**, never passed to the agent, and are
168
+ answered in the chat. An emoji is validated against Telegram's fixed
169
+ bot-reaction list **before** it is saved, with the valid set in the error —
170
+ note that ✅ is *not* on that list, which is why the `read` default is 👌.
171
+
172
+ ### `/help` and the slash menu
173
+
174
+ **`/help`** is answered by the connector itself: it lists the commands the
175
+ connector owns (`/help`, `/id`, `/receipts`, `/emoji`) and the current receipt
176
+ settings for that connection. It works in a chat with no route yet too — you get
177
+ the command list and a pointer to `/id`.
178
+
179
+ The same list is registered with Telegram via `setMyCommands` at **default
180
+ scope** when a bot starts polling, so a client offers the commands in its slash
181
+ menu as you type. Registration is cosmetic and best-effort: if it fails it is
182
+ logged, and every command still works when typed by hand.
183
+
184
+ > **Only these four commands are intercepted.** Everything else you send is
185
+ > relayed to the agent exactly as typed, *including* text that starts with a
186
+ > slash — `/deploy prod` reaches the agent, and so does `/help me write the
187
+ > release note`, because only a **bare** `/help` is treated as the command.
188
+
189
+ ### Message formatting
190
+
191
+ Formatting is preserved **in both directions**.
192
+
193
+ - **Telegram → agent.** A message's `entities` / `caption_entities` (bold, italic,
194
+ underline, strikethrough, spoiler, code, `pre` with its language, blockquote,
195
+ links and mentions) are folded into **Markdown** in the message text, so the
196
+ agent reads the formatting instead of losing it. Offsets are UTF-16 code units
197
+ and are treated as such. A `custom_emoji` is premium-only and degrades to the
198
+ stand-in glyph Telegram already put in the text. A message with no entities is
199
+ passed through byte-for-byte.
200
+ - **Agent → Telegram.** The agent's Markdown is rendered as `MarkdownV2`, escaping
201
+ the **text leaves only** (all 18 reserved characters — one unescaped `.` would
202
+ fail the whole send). Emphasis is deliberately conservative: `foo_bar_baz` and
203
+ `2*3*4` stay literal. The 4096-character limit is applied to the **escaped**
204
+ text. **If Telegram rejects the markup, the same text is resent with no
205
+ `parse_mode`** and the original refusal is logged — the message always wins over
206
+ its styling.
207
+
112
208
  ### Message envelope
113
209
 
114
210
  Each inbound Telegram message is forwarded to the agent as a single **JSON
@@ -200,15 +296,8 @@ added for provenance:
200
296
  }
201
297
  ```
202
298
 
203
- - **Opt-in, and it covers THIS PROCESS ONLY.** Off by default
204
- (`sttEnabled:false`), which means *the connector* sends no audio to a
205
- speech-to-text provider. It does **not** mean the audio is never transcribed:
206
- the connector is a client of an ours daemon, and **the daemon runs its own
207
- speech-to-text** when the receiving side pulls a voice note — under
208
- configuration this connector's operator does not control and may not know
209
- exists. When the connector was its own host, `sttEnabled:false` did cover the
210
- whole path; attached, it no longer can. Turn it on and supply a key to
211
- transcribe here as well (see [Configuration](#configuration)).
299
+ - **Opt-in.** Off by default (`sttEnabled:false`) — behaviour is then byte-identical
300
+ to today. Turn it on and supply a key (see [Configuration](#configuration)).
212
301
  - **No transcoding.** Telegram voice is **OGG/Opus**, which OpenAI-compatible
213
302
  transcription endpoints accept directly — the connector adds **no ffmpeg** and no
214
303
  new dependency (just built-in `fetch`).
@@ -262,11 +351,9 @@ npm install
262
351
  npm run build
263
352
  ```
264
353
 
265
- Requires Node ≥ 20, and **an ours daemon already running on this box** — the
266
- connector attaches to it over `/api/v1` and drives it through
267
- [`@ours.network/sdk`](https://www.npmjs.com/package/@ours.network/sdk). It runs
268
- no engine of its own: there is no native ADAPT SDK and no MUFL packet here, so
269
- nothing beyond `npm install` is resolved at runtime.
354
+ Requires Node ≥ 20. The native ADAPT SDK (`@adapt-toolkit/sdk` +
355
+ `@adapt-toolkit/sdk-native`, pinned to the version matching the shipped
356
+ `.muflo`) is resolved from `node_modules` at runtime.
270
357
 
271
358
  ## Usage
272
359
 
@@ -339,8 +426,7 @@ Precedence per field: **env var > `config.json` > default**. The config file is
339
426
 
340
427
  | field | env var | default |
341
428
  |----------------|---------------------------|-------------------------------------------------|
342
- | daemon URL | `OURS_TG_DAEMON_URL` | `''` (the SDK's own default selection) |
343
- | daemon state dir | `OURS_TG_DAEMON_STATE_DIR` | `''` (the SDK's own default selection) |
429
+ | broker URL | `OURS_TG_BROKER_URL` | `wss://broker1.ours.network` |
344
430
  | control port | `OURS_TG_CONTROL_PORT` | `3051` (localhost only) |
345
431
  | state dir | `OURS_TG_STATE_DIR` | `~/.ours-telegram` |
346
432
  | poll timeout | `OURS_TG_POLL_TIMEOUT` | `30` (seconds, Telegram long-poll) |
@@ -350,7 +436,7 @@ Precedence per field: **env var > `config.json` > default**. The config file is
350
436
  | retry backoff | `OURS_TG_FETCH_RETRY_BASE_MS` | `300` (base delay between those retries; grows exponentially with jitter) |
351
437
  | attachment cap | `OURS_TG_ATTACHMENT_MAX_BYTES` | `10485760` (10 MB; larger inbound media forwarded as a metadata-only stub) |
352
438
  | outbound file cap | `OURS_TG_OUTBOUND_FILE_MAX_BYTES` | `52428800` (50 MB; a larger file from a contact is skipped + logged — Telegram's `sendDocument` limit) |
353
- | STT enabled | `OURS_TG_STT_ENABLED` | `false` (whether **this connector** transcribes voice; the attached daemon runs its own STT regardless — see [Voice](#voice-messages--speech-to-text)) |
439
+ | STT enabled | `OURS_TG_STT_ENABLED` | `false` (master switch for voice transcription; off ⇒ byte-identical to today) |
354
440
  | STT API key | `OURS_TG_STT_API_KEY` | `''` (secret; env preferred — masked if placed in `config.json`, never logged) |
355
441
  | STT base URL | `OURS_TG_STT_BASE_URL` | `https://api.openai.com/v1` (OpenAI-compatible endpoint root; e.g. `https://api.groq.com/openai/v1` or a self-hosted whisper server) |
356
442
  | STT model | `OURS_TG_STT_MODEL` | `whisper-1` (e.g. `whisper-large-v3-turbo` on Groq) |
@@ -363,18 +449,36 @@ Precedence per field: **env var > `config.json` > default**. The config file is
363
449
  The control API is bound to `127.0.0.1` and unauthenticated — it manages bot
364
450
  tokens, so do not expose the control port off-host.
365
451
 
366
- ## Control plane (removed)
452
+ ## Control plane (ours messenger)
453
+
454
+ Each bridge is a self-sovereign ours node that can be **managed from the
455
+ ours messenger control plane** over the encrypted a2a_control
456
+ channel — no extra ports. The connector advertises an app manifest
457
+ (`network.ours.telegram-connector`) with a `core.configuration` capability, so the
458
+ messenger renders its generic config form for it. Two fields are configurable
459
+ live (no restart):
367
460
 
368
- The connector used to be a **managed node**: it advertised an app manifest
369
- (`network.ours.telegram-connector`) and the ours messenger could bind to it over
370
- the a2a_control channel and edit the allowed chat id and denial message live.
371
- That is gone — messenger manageability was removed by ruling, and with it the
372
- `cp_invite` and `bind_proxy` commands, the `get_manifest` / `get_config` /
373
- `set_config` verbs, and the bind ceremony.
461
+ - **Allowed chat ID** — only this chat is proxied to the agent.
462
+ - **Denial message** — what any other chat is told.
463
+
464
+ (The bot token is *not* CP-configurable: the messenger strips secret-field values
465
+ on save, so the token stays set at connection creation.)
466
+
467
+ Bind it once:
468
+
469
+ ```sh
470
+ # 1. add the messenger as a contact of the bridge node
471
+ ours-tg-connector cp_invite supportbot
472
+ # → paste the invite into the messenger (add contact / add node)
473
+
474
+ # 2. start the bind ceremony for that contact; read out the 6-digit code
475
+ ours-tg-connector bind_proxy supportbot <messenger-contact-name-or-cid>
476
+ # → enter the code in the messenger Control Panel (out-of-band, 5 min, 3 tries)
477
+ ```
374
478
 
375
- A route is configured when it is created (`add_new_connection`) and changed by
376
- removing it and adding it back. There is no live reconfiguration path, and
377
- nothing to bind.
479
+ Once bound, the messenger can pull the manifest, render the config form, and push
480
+ changes (`get_manifest` / `get_config` / `set_config`). Config verbs are gated:
481
+ only the bound control plane may read or write the configuration.
378
482
 
379
483
  ## Learn more
380
484
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire as __tgCreateRequire } from 'node:module'; const require = __tgCreateRequire(import.meta.url);
2
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
3
3
 
4
4
  // src/cli.ts
5
5
  import { spawn, spawnSync } from "node:child_process";
@@ -14,8 +14,7 @@ import * as fs from "node:fs";
14
14
  import { homedir } from "node:os";
15
15
  import { resolve, join, dirname } from "node:path";
16
16
  var DEFAULT_CONFIG = {
17
- daemonUrl: "",
18
- daemonStateDir: "",
17
+ brokerUrl: "wss://broker1.ours.network",
19
18
  controlPort: 3051,
20
19
  stateDir: resolve(homedir(), ".ours-telegram"),
21
20
  pollTimeoutSec: 30,
@@ -55,8 +54,7 @@ function readFileConfig() {
55
54
  return {};
56
55
  }
57
56
  const out2 = {};
58
- if (typeof parsed.daemonUrl === "string") out2.daemonUrl = parsed.daemonUrl;
59
- if (typeof parsed.daemonStateDir === "string") out2.daemonStateDir = resolve(parsed.daemonStateDir);
57
+ if (typeof parsed.brokerUrl === "string") out2.brokerUrl = parsed.brokerUrl;
60
58
  if (typeof parsed.controlPort === "number" && Number.isFinite(parsed.controlPort)) out2.controlPort = parsed.controlPort;
61
59
  if (typeof parsed.stateDir === "string") out2.stateDir = resolve(parsed.stateDir);
62
60
  if (typeof parsed.pollTimeoutSec === "number" && Number.isFinite(parsed.pollTimeoutSec)) {
@@ -103,11 +101,7 @@ function envBool(name) {
103
101
  function loadConfig() {
104
102
  const file = readFileConfig();
105
103
  return {
106
- // NOTE: no OURS_TG_BROKER_URL any more. The connector does not talk to a
107
- // broker — the daemon does. A stale one in a config file is now ignored
108
- // rather than half-honoured.
109
- daemonUrl: process.env.OURS_TG_DAEMON_URL ?? file.daemonUrl ?? DEFAULT_CONFIG.daemonUrl,
110
- daemonStateDir: process.env.OURS_TG_DAEMON_STATE_DIR ?? file.daemonStateDir ?? DEFAULT_CONFIG.daemonStateDir,
104
+ brokerUrl: process.env.OURS_TG_BROKER_URL ?? file.brokerUrl ?? DEFAULT_CONFIG.brokerUrl,
111
105
  controlPort: envInt("OURS_TG_CONTROL_PORT") ?? file.controlPort ?? DEFAULT_CONFIG.controlPort,
112
106
  stateDir: resolve(process.env.OURS_TG_STATE_DIR ?? file.stateDir ?? DEFAULT_CONFIG.stateDir),
113
107
  pollTimeoutSec: envInt("OURS_TG_POLL_TIMEOUT") ?? file.pollTimeoutSec ?? DEFAULT_CONFIG.pollTimeoutSec,
@@ -129,52 +123,6 @@ function loadConfig() {
129
123
  };
130
124
  }
131
125
 
132
- // src/service-definition.ts
133
- function serviceEnvironment(config, stateDir) {
134
- const env = {
135
- OURS_TG_CONTROL_PORT: String(config.controlPort),
136
- OURS_TG_STATE_DIR: stateDir,
137
- OURS_TG_POLL_TIMEOUT: String(config.pollTimeoutSec)
138
- };
139
- if (config.daemonUrl) env.OURS_TG_DAEMON_URL = config.daemonUrl;
140
- if (config.daemonStateDir) env.OURS_TG_DAEMON_STATE_DIR = config.daemonStateDir;
141
- return env;
142
- }
143
- function xmlText(value) {
144
- return String(value).replace(/[&<>"']/g, (character) => ({
145
- "&": "&amp;",
146
- "<": "&lt;",
147
- ">": "&gt;",
148
- '"': "&quot;",
149
- "'": "&apos;"
150
- })[character]);
151
- }
152
- function launchdPlist(input) {
153
- const envEntries = Object.entries(input.env).map(([key, value]) => ` <key>${xmlText(key)}</key><string>${xmlText(value)}</string>`).join("\n");
154
- return `<?xml version="1.0" encoding="UTF-8"?>
155
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
156
- <plist version="1.0">
157
- <dict>
158
- <key>Label</key><string>${xmlText(input.label)}</string>
159
- <key>ProgramArguments</key>
160
- <array>
161
- <string>${xmlText(input.execPath)}</string>
162
- <string>${xmlText(input.self)}</string>
163
- <string>serve</string>
164
- </array>
165
- <key>EnvironmentVariables</key>
166
- <dict>
167
- ${envEntries}
168
- </dict>
169
- <key>RunAtLoad</key><true/>
170
- <key>KeepAlive</key><true/>
171
- <key>StandardOutPath</key><string>${xmlText(input.logPath)}</string>
172
- <key>StandardErrorPath</key><string>${xmlText(input.logPath)}</string>
173
- </dict>
174
- </plist>
175
- `;
176
- }
177
-
178
126
  // src/routing.ts
179
127
  function looksLikeBotToken(s) {
180
128
  return /^\d+:[A-Za-z0-9_-]+$/.test(s);
@@ -264,7 +212,7 @@ async function cmdStart() {
264
212
  const ready = await waitForPort(PORT);
265
213
  if (ready) {
266
214
  out(`up on ${BASE}`);
267
- out(` daemon: ${CONFIG.daemonUrl || "(default selection)"}`);
215
+ out(` broker: ${CONFIG.brokerUrl}`);
268
216
  out(` state: ${STATE_DIR}`);
269
217
  out(` logs: ${LOG_PATH}`);
270
218
  } else {
@@ -309,7 +257,7 @@ async function cmdStatus() {
309
257
  out("ours-tg-connector: running");
310
258
  if (pid) out(` pid: ${pid}`);
311
259
  out(` url: ${BASE} ${up ? "(reachable)" : "(port not answering!)"}`);
312
- out(` daemon: ${CONFIG.daemonUrl || "(default selection)"}`);
260
+ out(` broker: ${CONFIG.brokerUrl}`);
313
261
  out(` state: ${STATE_DIR}`);
314
262
  out(` logs: ${LOG_PATH}`);
315
263
  if (up) {
@@ -510,6 +458,54 @@ async function cmdListConnections() {
510
458
  }
511
459
  }
512
460
  }
461
+ async function cmdCpInvite(name) {
462
+ if (!name) {
463
+ err("cp_invite requires a connection name.");
464
+ process.exit(1);
465
+ }
466
+ if (!await portOpen(PORT)) {
467
+ err("daemon not running \u2014 start it first.");
468
+ process.exit(1);
469
+ }
470
+ const res = await fetch(`${BASE}/connections/${encodeURIComponent(name)}/cp-invite`, { method: "POST" });
471
+ const body = await res.json();
472
+ if (!body.ok || !body.invite) {
473
+ err(`cp_invite failed: ${body.error ?? `HTTP ${res.status}`}`);
474
+ process.exit(1);
475
+ }
476
+ out("");
477
+ out(`Add the messenger control plane as a contact of "${name}".`);
478
+ out("Paste this invite into the messenger (add contact / add node):");
479
+ out("");
480
+ out(body.invite);
481
+ out("");
482
+ out(`Once it is a contact, bind it: ours-tg-connector bind_proxy ${name} <contact-name-or-cid>`);
483
+ }
484
+ async function cmdBindProxy(name, contact) {
485
+ if (!name || !contact) {
486
+ err("bind_proxy requires <connection-name> <contact-name-or-cid>.");
487
+ process.exit(1);
488
+ }
489
+ if (!await portOpen(PORT)) {
490
+ err("daemon not running \u2014 start it first.");
491
+ process.exit(1);
492
+ }
493
+ const res = await fetch(`${BASE}/connections/${encodeURIComponent(name)}/bind`, {
494
+ method: "POST",
495
+ headers: { "Content-Type": "application/json" },
496
+ body: JSON.stringify({ contact })
497
+ });
498
+ const body = await res.json();
499
+ if (!body.ok || !body.code) {
500
+ err(`bind_proxy failed: ${body.error ?? `HTTP ${res.status}`}`);
501
+ process.exit(1);
502
+ }
503
+ out("");
504
+ out(`Verification code: ${body.code}`);
505
+ out("");
506
+ out("Enter it in the messenger Control Panel within 5 minutes (3 attempts).");
507
+ out("Do NOT send it over ours \u2014 it must travel out-of-band (this terminal counts).");
508
+ }
513
509
  async function cmdRemoveConnection(name) {
514
510
  if (!name) {
515
511
  err("remove_connection requires a connection name.");
@@ -539,7 +535,14 @@ function run(cmd, args) {
539
535
  const r = spawnSync(cmd, args, { stdio: "inherit" });
540
536
  return r.status === 0;
541
537
  }
542
- var serviceEnv = () => serviceEnvironment(CONFIG, STATE_DIR);
538
+ function serviceEnv() {
539
+ return {
540
+ OURS_TG_BROKER_URL: CONFIG.brokerUrl,
541
+ OURS_TG_CONTROL_PORT: String(CONFIG.controlPort),
542
+ OURS_TG_STATE_DIR: STATE_DIR,
543
+ OURS_TG_POLL_TIMEOUT: String(CONFIG.pollTimeoutSec)
544
+ };
545
+ }
543
546
  function installSystemd() {
544
547
  const unitPath = systemdUnitPath();
545
548
  fs2.mkdirSync(dirname2(unitPath), { recursive: true });
@@ -593,13 +596,29 @@ function installLaunchd() {
593
596
  const plistPath = launchdPlistPath();
594
597
  fs2.mkdirSync(dirname2(plistPath), { recursive: true });
595
598
  const env = serviceEnv();
596
- const plist = launchdPlist({
597
- label: LAUNCHD_LABEL,
598
- execPath: process.execPath,
599
- self: SELF,
600
- logPath: LOG_PATH,
601
- env
602
- });
599
+ const envEntries = Object.entries(env).map(([k, v]) => ` <key>${k}</key><string>${v}</string>`).join("\n");
600
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
601
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
602
+ <plist version="1.0">
603
+ <dict>
604
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
605
+ <key>ProgramArguments</key>
606
+ <array>
607
+ <string>${process.execPath}</string>
608
+ <string>${SELF}</string>
609
+ <string>serve</string>
610
+ </array>
611
+ <key>EnvironmentVariables</key>
612
+ <dict>
613
+ ${envEntries}
614
+ </dict>
615
+ <key>RunAtLoad</key><true/>
616
+ <key>KeepAlive</key><true/>
617
+ <key>StandardOutPath</key><string>${LOG_PATH}</string>
618
+ <key>StandardErrorPath</key><string>${LOG_PATH}</string>
619
+ </dict>
620
+ </plist>
621
+ `;
603
622
  fs2.writeFileSync(plistPath, plist);
604
623
  out(`wrote ${plistPath}`);
605
624
  run("launchctl", ["unload", plistPath]);
@@ -656,6 +675,10 @@ function usage() {
656
675
  out(" list_connections list configured routes grouped by bot");
657
676
  out(" remove_connection <name> delete a route and its state");
658
677
  out("");
678
+ out(" control plane (ours messenger):");
679
+ out(" cp_invite <name> print an invite to add the messenger as a contact");
680
+ out(" bind_proxy <name> <contact> start binding the messenger as control plane (prints a 6-digit code)");
681
+ out("");
659
682
  out(" start start the daemon in the background");
660
683
  out(" stop stop the running daemon");
661
684
  out(" restart stop then start");
@@ -667,8 +690,7 @@ function usage() {
667
690
  out("");
668
691
  out("Config precedence (per field): env var > config.json > default.");
669
692
  out(" config.json: OURS_TG_CONFIG, else ~/.ours-telegram/config.json");
670
- out(" env: OURS_TG_DAEMON_URL + OURS_TG_DAEMON_STATE_DIR (both, or neither), OURS_TG_CONTROL_PORT (3051),");
671
- out(" OURS_TG_STATE_DIR, OURS_TG_POLL_TIMEOUT (30)");
693
+ out(" env: OURS_TG_BROKER_URL, OURS_TG_CONTROL_PORT (3051), OURS_TG_STATE_DIR, OURS_TG_POLL_TIMEOUT (30)");
672
694
  }
673
695
  async function main() {
674
696
  const cmd = process.argv[2] ?? "help";
@@ -719,6 +741,14 @@ async function main() {
719
741
  case "remove":
720
742
  await cmdRemoveConnection(process.argv[3]);
721
743
  break;
744
+ case "cp_invite":
745
+ case "cp-invite":
746
+ await cmdCpInvite(process.argv[3]);
747
+ break;
748
+ case "bind_proxy":
749
+ case "bind-proxy":
750
+ await cmdBindProxy(process.argv[3], process.argv[4]);
751
+ break;
722
752
  case "start":
723
753
  await cmdStart();
724
754
  break;