@cello-protocol/cli 0.0.317 → 0.0.319

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.
@@ -1,4 +1,8 @@
1
- export const TELEGRAM = { apiUrl: "https://api.telegram.org", timeoutMs: 15_000, pollSeconds: 25 };
1
+ // Telegram's Bot API: the calls a notifier needs. Every call has a time limit, and a refusal carries Telegram's own words.
2
+ // The bot token is part of the address, so nothing here ever puts an address in an error.
3
+ import { request as httpRequest } from "node:http";
4
+ import { request as httpsRequest } from "node:https";
5
+ export const TELEGRAM = { apiUrl: "https://api.telegram.org", timeoutMs: 6_000, pollSeconds: 25 };
2
6
  export class TelegramError extends Error {
3
7
  // Telegram's own error number, when it gave one: 401 is a token it doesn't know, 409 is another reader on the same bot.
4
8
  code;
@@ -7,38 +11,82 @@ export class TelegramError extends Error {
7
11
  this.code = code;
8
12
  }
9
13
  }
10
- async function call(at, token, method, body, limitMs = at.timeoutMs, stop) {
14
+ class TimedOut extends Error {
15
+ }
16
+ // Why a connection failed, in the system's own codes. Telegram has an IPv4 and an IPv6 address, and a failure to reach it
17
+ // is one error per address with an empty message of its own, so each address's code is listed.
18
+ function reason(err) {
19
+ if (!(err instanceof Error))
20
+ return String(err);
21
+ const each = err.errors;
22
+ if (Array.isArray(each) && each.length > 0)
23
+ return each.map((e) => { const one = e; return `${one.code ?? one.message ?? "failed"}${one.address ? ` at ${one.address}` : ""}`; }).join(", ");
24
+ const code = err.code;
25
+ return [code, err.message].filter((part) => typeof part === "string" && part.length > 0).join(": ") || err.name;
26
+ }
27
+ // One POST. Not fetch, for one reason: fetch gives each of a host's addresses a quarter of a second to connect before it
28
+ // moves to the next, and can't be told otherwise. On a slow link, or a machine with no IPv6 route, that fails a call Telegram
29
+ // would have answered. Here each address gets the call's whole limit.
30
+ function post(url, body, limitMs, stop) {
31
+ return new Promise((resolve, reject) => {
32
+ const send = url.protocol === "http:" ? httpRequest : httpsRequest;
33
+ // The connection option is passed through to the socket. The request's own types don't list it.
34
+ const options = { method: "POST", headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }, autoSelectFamilyAttemptTimeout: limitMs };
35
+ const request = send(url, options, (response) => {
36
+ const parts = [];
37
+ response.on("data", (part) => { parts.push(part); });
38
+ response.on("end", () => { done(); resolve({ status: response.statusCode ?? 0, text: Buffer.concat(parts).toString("utf8") }); });
39
+ response.on("error", (err) => { done(); reject(err); });
40
+ });
41
+ const timer = setTimeout(() => { request.destroy(new TimedOut()); }, limitMs);
42
+ const stopped = () => { request.destroy(new Error("stopped")); };
43
+ function done() {
44
+ clearTimeout(timer);
45
+ stop?.removeEventListener("abort", stopped);
46
+ }
47
+ stop?.addEventListener("abort", stopped);
48
+ request.on("error", (err) => { done(); reject(err); });
49
+ request.end(body);
50
+ });
51
+ }
52
+ // How many times one call is tried. Telegram sometimes doesn't answer a new connection at all: measured on 17 November from
53
+ // two networks, one try in six sat silent for its whole limit while the next was answered in under a second. So a silent
54
+ // try is given up on quickly and made again. A person not being told matters more than their being told twice.
55
+ const TRIES = 3;
56
+ async function call(at, token, method, body, limitMs = at.timeoutMs, stop, tries = TRIES) {
57
+ let url;
58
+ try {
59
+ url = new URL(`${at.apiUrl}/bot${token}/${method}`);
60
+ }
61
+ catch {
62
+ throw new TelegramError("Telegram couldn't be reached: its address isn't one.");
63
+ }
11
64
  let response;
12
- // A dropped connection is tried once more, because a person not being told matters more than their being told twice.
13
- // A timeout isn't: the limit is the promise.
14
65
  for (let attempt = 1; response === undefined; attempt++) {
15
66
  try {
16
- response = await fetch(`${at.apiUrl}/bot${token}/${method}`, {
17
- method: "POST",
18
- headers: { "Content-Type": "application/json" },
19
- body: JSON.stringify(body),
20
- signal: stop ? AbortSignal.any([AbortSignal.timeout(limitMs), stop]) : AbortSignal.timeout(limitMs),
21
- });
67
+ response = await post(url, JSON.stringify(body), limitMs, stop);
22
68
  }
23
69
  catch (err) {
24
70
  if (stop?.aborted)
25
71
  throw new TelegramError("Stopped.");
26
- if (err instanceof Error && err.name === "TimeoutError")
27
- throw new TelegramError(`Telegram didn't answer within ${limitMs / 1000} seconds.`);
28
- if (attempt < 2)
72
+ if (attempt < tries)
29
73
  continue;
30
- const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : err instanceof Error ? err.message : String(err);
31
- throw new TelegramError(`Telegram couldn't be reached, twice: ${cause.replaceAll(token, "<bot token>")}.`);
74
+ const times = tries === 1 ? "" : `, in ${tries} tries`;
75
+ if (err instanceof TimedOut)
76
+ throw new TelegramError(`Telegram didn't answer within ${limitMs / 1000} seconds${times}.`);
77
+ throw new TelegramError(`Telegram couldn't be reached${times}: ${reason(err).replaceAll(token, "<bot token>")}.`);
32
78
  }
33
79
  }
34
80
  let answer;
35
81
  try {
36
- answer = await response.json();
82
+ answer = JSON.parse(response.text);
37
83
  }
38
84
  catch {
39
85
  // No number: a page from a proxy or a hotel network isn't Telegram refusing the token.
40
86
  throw new TelegramError(`Telegram answered with something unreadable (HTTP ${response.status}).`);
41
87
  }
88
+ if (answer === null || typeof answer !== "object")
89
+ throw new TelegramError(`Telegram answered with something unreadable (HTTP ${response.status}).`);
42
90
  if (answer.ok !== true)
43
91
  throw new TelegramError(`Telegram refused: ${answer.description ?? `HTTP ${response.status}`}.`, answer.error_code);
44
92
  return answer.result;
@@ -60,7 +108,8 @@ export async function newestUpdate(at, token) {
60
108
  }
61
109
  // Everything sent to the bot from this update on, waiting up to pollSeconds for the first. Stopping it ends the wait at once.
62
110
  export async function updatesFrom(at, token, offset, stop) {
63
- return await call(at, token, "getUpdates", { offset, timeout: at.pollSeconds, allowed_updates: ["message"] }, at.pollSeconds * 1000 + at.timeoutMs, stop);
111
+ // One try: the reader calls again by itself, with a growing wait.
112
+ return await call(at, token, "getUpdates", { offset, timeout: at.pollSeconds, allowed_updates: ["message"] }, at.pollSeconds * 1000 + at.timeoutMs, stop, 1);
64
113
  }
65
114
  // Answers only once Telegram has accepted the message, with the ids Telegram gave: the chat's own number, which is what a
66
115
  // reply will carry even if the chat was named as @something, and the message's.
@@ -998,7 +998,9 @@ class CelloAdapter(BasePlatformAdapter):
998
998
  line = "[CELLO notice] " + text
999
999
  sid = _safe_scalar(notice.get("session_id"))
1000
1000
  logger.info("[cello] Notice for session %s: %s", sid, text)
1001
- if sid == current_session or (sid is None and self._session_scope == "agent" and current_session is not None):
1001
+ # Only a read of a session has a turn to put these in. A read of none has no turn, so nothing counts as "here":
1002
+ # with both ids empty they once matched, went into a list nobody used, and were never shown.
1003
+ if current_session is not None and (sid == current_session or (sid is None and self._session_scope == "agent")):
1002
1004
  here.append(line)
1003
1005
  continue
1004
1006
  if sid is None:
@@ -1017,7 +1019,9 @@ class CelloAdapter(BasePlatformAdapter):
1017
1019
  line = OPERATOR_HEADING + "\n" + reply["text"]
1018
1020
  sid = _safe_scalar(reply.get("session_id"))
1019
1021
  logger.info("[cello] The operator answered through %s, about session %s", reply.get("via"), sid)
1020
- if sid == current_session or (sid is None and self._session_scope == "agent" and current_session is not None):
1022
+ # Only a read of a session has a turn to put these in. A read of none has no turn, so nothing counts as "here":
1023
+ # with both ids empty they once matched, went into a list nobody used, and were never shown.
1024
+ if current_session is not None and (sid == current_session or (sid is None and self._session_scope == "agent")):
1021
1025
  here.append(line)
1022
1026
  continue
1023
1027
  if sid is None:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cello-protocol/cli",
3
- "version": "0.0.317",
3
+ "version": "0.0.319",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.7"