@niwa-labs/telegram 0.0.0-stage → 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/telegram
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Telegram surface: messages, owner requests and agent commands.
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@niwa-labs/telegram",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts"
8
+ },
9
+ "dependencies": {
10
+ "@niwa-labs/agent": "0.0.0",
11
+ "@niwa-labs/core": "0.0.0",
12
+ "@niwa-labs/plugin": "0.0.0",
13
+ "@niwa-labs/requests": "0.0.0",
14
+ "zod": "^4.6.7"
15
+ },
16
+ "devDependencies": {
17
+ "@niwa-labs/messages": "0.0.0",
18
+ "@niwa-labs/testing": "0.0.0"
19
+ }
20
+ }
package/src/bot.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * bot.ts — a tiny client of the Telegram Bot API.
3
+ *
4
+ * Only `fetch` and the Telegram API itself: no SDK, no dependency, nothing that decides what a
5
+ * message means. This file knows how to ask Telegram to do something and how to read what it
6
+ * says back; everything else — who the owner is, what a message means — belongs to index.ts.
7
+ *
8
+ * The API base is a parameter, so a test can point the client at a fake server and watch
9
+ * exactly what it would have sent to the real one.
10
+ */
11
+
12
+ import { NotSent } from "@niwa-labs/core";
13
+ import { z } from "zod";
14
+
15
+ /** Domain identifiers of Telegram. Branded: a bare number is not accepted where one is expected. */
16
+ export const chatSchema = z.number().brand<"ChatId">();
17
+ export const userSchema = z.number().brand<"UserId">();
18
+ export const updateSchema = z.number().brand<"UpdateId">();
19
+ export const messageSchema = z.number().brand<"MessageId">();
20
+ export type ChatId = z.infer<typeof chatSchema>;
21
+ export type UserId = z.infer<typeof userSchema>;
22
+ export type UpdateId = z.infer<typeof updateSchema>;
23
+ export type MessageId = z.infer<typeof messageSchema>;
24
+
25
+ /** A chat id, as Telegram gave it. */
26
+ export const chatId = (n: number): ChatId => chatSchema.parse(n);
27
+
28
+ /** The default base of the Telegram Bot API. */
29
+ export const API_BASE = "https://api.telegram.org";
30
+
31
+ /** One keyboard button. */
32
+ export interface InlineButton {
33
+ /** The text on the button. */
34
+ readonly text: string;
35
+ /**
36
+ * The data the button carries back when it is pressed.
37
+ *
38
+ * It is the callback of the button: Telegram hands it back with the press, and that is how
39
+ * the press is matched with the thing it answers.
40
+ */
41
+ readonly callback_data: string;
42
+ }
43
+
44
+ /** The keyboard under a message. */
45
+ export interface InlineKeyboard {
46
+ readonly inline_keyboard: ReadonlyArray<ReadonlyArray<InlineButton>>;
47
+ }
48
+
49
+ /** One update from Telegram: something happened in a chat. */
50
+ export interface Update {
51
+ readonly update_id: UpdateId;
52
+ readonly message?: {
53
+ readonly message_id: MessageId;
54
+ readonly chat: { readonly id: ChatId; readonly type: string };
55
+ readonly date: number;
56
+ readonly text?: string;
57
+ readonly from?: { readonly id: UserId; readonly username?: string };
58
+ /** The message this one answers, when the sender replied to one. */
59
+ readonly reply_to_message?: { readonly message_id: MessageId };
60
+ };
61
+ readonly callback_query?: {
62
+ readonly id: string;
63
+ readonly data?: string;
64
+ readonly message?: {
65
+ readonly message_id: MessageId;
66
+ readonly chat: { readonly id: ChatId; readonly type: string };
67
+ };
68
+ readonly from?: { readonly id: UserId; readonly username?: string };
69
+ };
70
+ }
71
+
72
+ /** What the Bot API says about a call. */
73
+ export interface BotResult<T> {
74
+ readonly ok: boolean;
75
+ readonly result?: T;
76
+ readonly description?: string;
77
+ readonly error_code?: number;
78
+ }
79
+
80
+ /** A message the client sent. */
81
+ export interface SentMessage {
82
+ readonly message_id: MessageId;
83
+ readonly chat: { readonly id: number };
84
+ readonly text?: string;
85
+ }
86
+
87
+ /** The client of the Bot API of one bot. */
88
+ export interface Bot {
89
+ /** The updates from the offset on. Telegram forgets the updates below the offset. */
90
+ getUpdates(offset: number, timeoutSeconds: number, signal?: AbortSignal): Promise<Update[]>;
91
+
92
+ /** Send a text message to a chat. */
93
+ sendMessage(chat: ChatId, text: string, keyboard?: InlineKeyboard, replyTo?: MessageId): Promise<SentMessage>;
94
+
95
+ /**
96
+ * Tell Telegram a press of a button was seen, with a short word to show the one who pressed it.
97
+ * Until then the button shows that it is waiting.
98
+ */
99
+ answerCallbackQuery(query: string, text?: string): Promise<void>;
100
+ }
101
+
102
+ /** The options of the client. */
103
+ export interface BotOptions {
104
+ /** The token of the bot: what Telegram gave it. */
105
+ readonly token: string;
106
+ /** The base of the API. The real one, unless a test says otherwise. */
107
+ readonly apiBase?: string;
108
+ }
109
+
110
+ /**
111
+ * The client of the Bot API.
112
+ *
113
+ * Every call goes through one place: the URL is built here, the body is JSON, and the answer
114
+ * is checked here. A failure of Telegram is an error with Telegram's own words.
115
+ */
116
+ export function createBot(opts: BotOptions): Bot {
117
+ const apiBase = (opts.apiBase ?? API_BASE).replace(/\/$/, "");
118
+ const token = opts.token;
119
+
120
+ /**
121
+ * The URL carries the token, and anything that came back may quote the URL: the token is never
122
+ * let out in an error, in either of the forms it can be written in a path.
123
+ */
124
+ const redact = (text: string): string =>
125
+ [token, encodeURIComponent(token)].reduce(
126
+ (kept, secret) => (secret === "" ? kept : kept.replaceAll(secret, "<token>")),
127
+ text,
128
+ );
129
+
130
+ function failedBeforeConnect(error: unknown): boolean {
131
+ const codes = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ConnectionRefused", "DNSLookupFailed"];
132
+ return [error, error instanceof Error ? error.cause : undefined].some((candidate) =>
133
+ typeof candidate === "object" && candidate !== null && "code" in candidate &&
134
+ typeof candidate.code === "string" && codes.includes(candidate.code));
135
+ }
136
+
137
+ /** One call to the Bot API. */
138
+ async function call<T>(
139
+ method: string,
140
+ body: Record<string, unknown>,
141
+ signal?: AbortSignal,
142
+ ): Promise<T> {
143
+ const url = `${apiBase}/bot${token}/${method}`;
144
+ let response: Response;
145
+ try {
146
+ response = await fetch(url, {
147
+ method: "POST",
148
+ redirect: "error",
149
+ headers: { "content-type": "application/json" },
150
+ body: JSON.stringify(body),
151
+ ...(signal === undefined ? {} : { signal }),
152
+ });
153
+ } catch (error) {
154
+ const message = `telegram ${method} failed: ${redact(error instanceof Error ? error.message : String(error))}`;
155
+ if (failedBeforeConnect(error)) throw new NotSent(message);
156
+ throw new Error(message);
157
+ }
158
+ let text: string;
159
+ try {
160
+ text = await response.text();
161
+ } catch (error) {
162
+ throw new Error(
163
+ `telegram ${method} answered ${String(response.status)} and its body could not be read: ${redact(error instanceof Error ? error.message : String(error))}`,
164
+ );
165
+ }
166
+ let parsed: BotResult<T>;
167
+ try {
168
+ parsed = JSON.parse(text) as BotResult<T>;
169
+ } catch {
170
+ // The body of something that is not the Bot API is never quoted: it may echo the request.
171
+ throw new Error(`telegram answered ${method} with ${String(response.status)} and a body that is not JSON`);
172
+ }
173
+ if (!parsed.ok) {
174
+ const reason = parsed.description === undefined ? `code ${String(parsed.error_code)}` : redact(parsed.description).slice(0, 200);
175
+ const message = `telegram refused ${method} (${String(response.status)}): ${reason}`;
176
+ if (parsed.ok === false && parsed.error_code !== undefined && parsed.error_code >= 400 && parsed.error_code < 500 && response.status < 500) {
177
+ throw new NotSent(message);
178
+ }
179
+ throw new Error(message);
180
+ }
181
+ if (parsed.result === undefined) {
182
+ throw new Error(`telegram answered ${method} without a result`);
183
+ }
184
+ return parsed.result;
185
+ }
186
+
187
+ return {
188
+ async getUpdates(offset, timeoutSeconds, signal) {
189
+ return call<Update[]>(
190
+ "getUpdates",
191
+ { offset, timeout: timeoutSeconds, allowed_updates: ["message", "callback_query"] },
192
+ signal,
193
+ );
194
+ },
195
+
196
+ async sendMessage(chat, text, keyboard, replyTo) {
197
+ return call<SentMessage>("sendMessage", {
198
+ chat_id: chat,
199
+ ...(replyTo === undefined ? {} : { reply_parameters: { message_id: replyTo } }),
200
+ text,
201
+ ...(keyboard === undefined ? {} : { reply_markup: keyboard }),
202
+ });
203
+ },
204
+
205
+ async answerCallbackQuery(query, text) {
206
+ await call<boolean>("answerCallbackQuery", {
207
+ callback_query_id: query,
208
+ ...(text === undefined ? {} : { text }),
209
+ });
210
+ },
211
+ };
212
+ }