@narumitw/pi-notify 0.0.0-stage → 0.2.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/src/notify.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { join } from "node:path";
2
+ import {
3
+ CONFIG_DIR_NAME,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ getAgentDir,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { Coordinator } from "./coordinator.js";
9
+ import { displayPath } from "./metadata.js";
10
+ import { defaults, SettingsStore } from "./settings.js";
11
+ import { providers } from "./telegram.js";
12
+
13
+ interface Owner {
14
+ controller: AbortController;
15
+ store: SettingsStore;
16
+ coordinator: Coordinator;
17
+ unsubscribe?: () => void;
18
+ menu?: Promise<unknown>;
19
+ }
20
+
21
+ export default function notify(pi: ExtensionAPI): void {
22
+ const owners = new Map<ExtensionContext["sessionManager"], Owner>();
23
+ const current = (ctx: ExtensionContext) => owners.get(ctx.sessionManager);
24
+ const stop = async (owner: Owner) => {
25
+ owner.controller.abort();
26
+ owner.unsubscribe?.();
27
+ owner.unsubscribe = undefined;
28
+ await Promise.allSettled([owner.coordinator.close(), owner.store.flush(), owner.menu]);
29
+ };
30
+ pi.on("session_start", async (_event, ctx) => {
31
+ const previous = current(ctx);
32
+ const controller = new AbortController();
33
+ const store = new SettingsStore(
34
+ join(getAgentDir(), "pi-notify.json"),
35
+ ctx.isProjectTrusted() ? join(ctx.cwd, CONFIG_DIR_NAME, "pi-notify.json") : undefined,
36
+ providers,
37
+ );
38
+ const ui = ctx.ui;
39
+ const hasUI = ctx.hasUI;
40
+ const manager = ctx.sessionManager;
41
+ const owner: Owner = {
42
+ controller,
43
+ store,
44
+ coordinator: new Coordinator(defaults(), providers, ctx.mode === "tui", undefined, () => {
45
+ if (owners.get(manager) === owner && !controller.signal.aborted && hasUI)
46
+ ui.notify("Telegram notification failed. Open /notify → Status for a safe error code.", "warning");
47
+ }),
48
+ };
49
+ owners.set(manager, owner);
50
+ if (previous) await stop(previous);
51
+ if (controller.signal.aborted || owners.get(manager) !== owner) return;
52
+ const snapshot = await store.load();
53
+ if (controller.signal.aborted || owners.get(manager) !== owner) return;
54
+ owner.coordinator.apply(snapshot.effective);
55
+ if (ctx.mode === "tui") {
56
+ // Public listeners run after Pi viewport input handling. Focus, mouse, and
57
+ // viewport/search keys can be consumed first; this observes forwarded input only.
58
+ owner.unsubscribe = ui.onTerminalInput((data) => {
59
+ owner.coordinator.input(data);
60
+ });
61
+ owner.coordinator.observeActivity();
62
+ }
63
+ if (snapshot.diagnostics.length && hasUI) ui.notify(snapshot.diagnostics.join(" "), "warning");
64
+ });
65
+ pi.on("before_agent_start", (_event, ctx) => {
66
+ current(ctx)?.coordinator.begin(true);
67
+ });
68
+ pi.on("agent_start", (_event, ctx) => {
69
+ current(ctx)?.coordinator.begin();
70
+ });
71
+ pi.on("message_end", (event, ctx) => {
72
+ if (event.message.role === "assistant") current(ctx)?.coordinator.assistant(event.message.stopReason === "error");
73
+ });
74
+ pi.on("agent_settled", (event, ctx) => {
75
+ current(ctx)?.coordinator.settle(event.aborted, {
76
+ sessionId: ctx.sessionManager.getSessionId(),
77
+ sessionName: ctx.sessionManager.getSessionName(),
78
+ cwd: ctx.cwd,
79
+ });
80
+ });
81
+ pi.on("session_shutdown", async (_event, ctx) => {
82
+ const owner = current(ctx);
83
+ if (!owner) return;
84
+ owners.delete(ctx.sessionManager);
85
+ await stop(owner);
86
+ });
87
+ pi.registerCommand("notify", {
88
+ description: "Configure Telegram notifications and inactivity reminders",
89
+ handler: async (args, ctx) => {
90
+ if (args.trim()) throw new Error("Usage: /notify (no arguments).");
91
+ const owner = current(ctx);
92
+ const path = owner?.store.userPath ?? join(getAgentDir(), "pi-notify.json");
93
+ if (ctx.mode !== "tui") {
94
+ if (ctx.hasUI) {
95
+ ctx.ui.notify(
96
+ `Notify setup requires TUI. Edit ${displayPath(path)} manually; inactivity mode delivers at settlement outside TUI.`,
97
+ "info",
98
+ );
99
+ return;
100
+ }
101
+ throw new Error(
102
+ "/notify setup requires TUI. Edit the user pi-notify.json file and reload; automatic delivery is independent of the menu.",
103
+ );
104
+ }
105
+ if (!owner || owner.controller.signal.aborted) throw new Error("Notify session is unavailable. Reload Pi.");
106
+ if (owner.menu) {
107
+ ctx.ui.notify("Notify menu is already open.", "info");
108
+ return;
109
+ }
110
+ const isCurrent = () => owners.get(ctx.sessionManager) === owner && !owner.controller.signal.aborted;
111
+ const { showNotifyMenu } = await import("./menu.js");
112
+ if (!isCurrent()) return;
113
+ // Dynamic import can race a second invocation of this command.
114
+ if (owner.menu) {
115
+ ctx.ui.notify("Notify menu is already open.", "info");
116
+ return;
117
+ }
118
+ const running = showNotifyMenu(ctx, {
119
+ store: owner.store,
120
+ coordinator: owner.coordinator,
121
+ providers,
122
+ signal: owner.controller.signal,
123
+ isCurrent,
124
+ });
125
+ owner.menu = running;
126
+ try {
127
+ await running;
128
+ } finally {
129
+ if (owner.menu === running) owner.menu = undefined;
130
+ }
131
+ },
132
+ });
133
+ }
@@ -0,0 +1,68 @@
1
+ export interface TelegramDestination {
2
+ provider: "telegram";
3
+ label: string;
4
+ botToken: string;
5
+ chatId: string;
6
+ messageThreadId?: number;
7
+ }
8
+
9
+ export type Destination = TelegramDestination;
10
+
11
+ export interface Notification {
12
+ id: string;
13
+ title: string;
14
+ body: string;
15
+ settledAt: number;
16
+ }
17
+
18
+ export type DeliveryCode =
19
+ | "invalid-destination"
20
+ | "unsupported-provider"
21
+ | "network"
22
+ | "timeout"
23
+ | "http"
24
+ | "api"
25
+ | "rate-limit"
26
+ | "response"
27
+ | "cancelled";
28
+ export type DeliveryResult =
29
+ | { state: "accepted" }
30
+ | { state: "failed"; code: DeliveryCode; retryAfterSeconds?: number }
31
+ | { state: "cancelled"; code: "cancelled" };
32
+
33
+ export interface NotificationProvider {
34
+ readonly id: string;
35
+ readonly label: string;
36
+ /** Return all owned fields, using undefined for absent optional fields, or reject. */
37
+ validate(value: unknown): Destination | undefined;
38
+ send(destination: Destination, notification: Notification, signal: AbortSignal): Promise<DeliveryResult>;
39
+ }
40
+
41
+ export type Providers = ReadonlyMap<string, NotificationProvider>;
42
+
43
+ export function isObject(value: unknown): value is Record<string, unknown> {
44
+ return value !== null && typeof value === "object" && !Array.isArray(value);
45
+ }
46
+
47
+ /** Unknown providers never fall back to Telegram. Raw settings remain storage-owned. */
48
+ export function validateDestination(value: unknown, providers: Providers): Destination | undefined {
49
+ if (!isObject(value) || typeof value.provider !== "string") return undefined;
50
+ return providers.get(value.provider)?.validate(value);
51
+ }
52
+
53
+ export async function deliver(
54
+ providers: Providers,
55
+ destination: Destination,
56
+ notification: Notification,
57
+ signal: AbortSignal,
58
+ ): Promise<DeliveryResult> {
59
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
60
+ const provider = providers.get(destination.provider);
61
+ if (!provider) return { state: "failed", code: "unsupported-provider" };
62
+ if (!provider.validate(destination)) return { state: "failed", code: "invalid-destination" };
63
+ try {
64
+ return await provider.send(destination, notification, signal);
65
+ } catch {
66
+ return signal.aborted ? { state: "cancelled", code: "cancelled" } : { state: "failed", code: "network" };
67
+ }
68
+ }
@@ -0,0 +1,261 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
+ import { type Destination, isObject, type Providers, validateDestination } from "./provider.js";
6
+
7
+ export type Mode = "immediate" | "after-inactivity";
8
+ export type Scope = "user" | "project";
9
+ export interface Settings {
10
+ enabled: boolean;
11
+ mode: Mode;
12
+ inactivitySeconds: number;
13
+ targetIds: string[];
14
+ destinations: Record<string, Destination>;
15
+ }
16
+ export interface Snapshot {
17
+ user: Record<string, unknown>;
18
+ project: Record<string, unknown>;
19
+ effective: Settings;
20
+ diagnostics: string[];
21
+ }
22
+ export const MAX_INACTIVITY_SECONDS = 86_400;
23
+ export const MAX_DESTINATIONS = 32;
24
+ export const policyKeys = ["enabled", "mode", "inactivitySeconds", "targetIds"] as const;
25
+ export const defaults = (): Settings => ({
26
+ enabled: true,
27
+ mode: "immediate",
28
+ inactivitySeconds: 30,
29
+ targetIds: [],
30
+ destinations: {},
31
+ });
32
+ export const validId = (id: string) =>
33
+ /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(id) && !["constructor", "prototype", "__proto__"].includes(id);
34
+ export const validSeconds = (value: unknown): value is number =>
35
+ Number.isInteger(value) && Number(value) >= 1 && Number(value) <= MAX_INACTIVITY_SECONDS;
36
+
37
+ function policy(document: Record<string, unknown>, diagnostics: string[]): Partial<Settings> {
38
+ const result: Partial<Settings> = {};
39
+ for (const key of policyKeys) {
40
+ if (!Object.hasOwn(document, key)) continue;
41
+ const value = document[key];
42
+ if (key === "enabled" && typeof value === "boolean") result.enabled = value;
43
+ else if (key === "mode" && (value === "immediate" || value === "after-inactivity")) result.mode = value;
44
+ else if (key === "inactivitySeconds" && validSeconds(value)) result.inactivitySeconds = value;
45
+ else if (
46
+ key === "targetIds" &&
47
+ Array.isArray(value) &&
48
+ value.length <= MAX_DESTINATIONS &&
49
+ value.every((id) => typeof id === "string" && validId(id)) &&
50
+ new Set(value).size === value.length
51
+ )
52
+ result.targetIds = [...value];
53
+ else diagnostics.push(`Invalid ${key} setting.`);
54
+ }
55
+ return result;
56
+ }
57
+
58
+ export function resolveSettings(
59
+ user: Record<string, unknown>,
60
+ project: Record<string, unknown>,
61
+ providers: Providers,
62
+ diagnostics: string[] = [],
63
+ ): Snapshot {
64
+ const effective = { ...defaults(), ...policy(user, diagnostics), ...policy(project, diagnostics) };
65
+ if (Object.hasOwn(project, "destinations"))
66
+ diagnostics.push("Project destinations are forbidden; use User settings.");
67
+ if (user.destinations !== undefined) {
68
+ if (!isObject(user.destinations) || Object.keys(user.destinations).length > MAX_DESTINATIONS)
69
+ diagnostics.push("Invalid destinations setting.");
70
+ else
71
+ for (const [id, raw] of Object.entries(user.destinations)) {
72
+ const destination = validId(id) ? validateDestination(raw, providers) : undefined;
73
+ if (destination) effective.destinations[id] = destination;
74
+ else diagnostics.push("Invalid destination or unsupported provider; edit User settings.");
75
+ }
76
+ }
77
+ if (effective.targetIds.some((id) => !Object.hasOwn(effective.destinations, id)))
78
+ diagnostics.push("Selected destination is missing or unsupported; update targetIds.");
79
+ // Fail closed rather than sending with partial or invalid routing settings.
80
+ if (diagnostics.length) effective.enabled = false;
81
+ return { user, project, effective, diagnostics };
82
+ }
83
+
84
+ async function readDocument(path: string): Promise<Record<string, unknown>> {
85
+ try {
86
+ const value: unknown = JSON.parse(await fs.readFile(path, "utf8"));
87
+ if (!isObject(value)) throw new Error("invalid");
88
+ return value;
89
+ } catch (error) {
90
+ if (isObject(error) && error.code === "ENOENT") return {};
91
+ throw new Error("Settings cannot be read as a JSON object. Repair the file before saving.");
92
+ }
93
+ }
94
+
95
+ /** Per-instance transactions plus Pi's process-wide path queue; no cross-process lock. */
96
+ export class SettingsStore {
97
+ snapshot: Snapshot;
98
+ private tail: Promise<unknown> = Promise.resolve();
99
+ readonly projectPath: string | undefined;
100
+ constructor(
101
+ readonly userPath: string,
102
+ projectPath: string | undefined,
103
+ private readonly providers: Providers,
104
+ ) {
105
+ // A customized agent directory can coincide with the project's settings directory.
106
+ // One physical path cannot be both credential storage and a project overlay.
107
+ this.projectPath = projectPath && resolve(projectPath) !== resolve(userPath) ? projectPath : undefined;
108
+ this.snapshot = resolveSettings({}, {}, providers);
109
+ }
110
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
111
+ // Always lock User before Project across instances to avoid lock-order deadlocks.
112
+ const task = this.tail.catch(() => {}).then(() => withFileMutationQueue(this.userPath, operation));
113
+ this.tail = task.catch(() => {});
114
+ return task;
115
+ }
116
+ validate(value: unknown): Destination | undefined {
117
+ return validateDestination(value, this.providers);
118
+ }
119
+ async flush(): Promise<void> {
120
+ await this.tail;
121
+ }
122
+ load(): Promise<Snapshot> {
123
+ return this.enqueue(async () => {
124
+ const diagnostics: string[] = [];
125
+ const read = async (path: string | undefined, scope: Scope) => {
126
+ if (!path) return {};
127
+ try {
128
+ return await (path === this.userPath
129
+ ? readDocument(path)
130
+ : withFileMutationQueue(path, () => readDocument(path)));
131
+ } catch {
132
+ diagnostics.push(`${scope} settings cannot be read. Repair the JSON file before saving.`);
133
+ return {};
134
+ }
135
+ };
136
+ const user = await read(this.userPath, "user");
137
+ const project = await read(this.projectPath, "project");
138
+ this.snapshot = resolveSettings(user, project, this.providers, diagnostics);
139
+ return this.snapshot;
140
+ });
141
+ }
142
+ change(
143
+ scope: Scope,
144
+ mutate: (
145
+ document: Record<string, unknown>,
146
+ project: Record<string, unknown>,
147
+ user: Record<string, unknown>,
148
+ ) => void,
149
+ signal: AbortSignal,
150
+ ): Promise<Snapshot> {
151
+ return this.enqueue(async () => {
152
+ const path = scope === "user" ? this.userPath : this.projectPath;
153
+ if (!path) throw new Error("Project settings require a trusted project.");
154
+ const operation = async () => {
155
+ signal.throwIfAborted();
156
+ const document = await readDocument(path);
157
+ signal.throwIfAborted();
158
+ const user = scope === "user" ? document : await readDocument(this.userPath);
159
+ const projectPath = this.projectPath;
160
+ const project =
161
+ scope === "project"
162
+ ? document
163
+ : projectPath
164
+ ? await withFileMutationQueue(projectPath, () => readDocument(projectPath))
165
+ : {};
166
+ signal.throwIfAborted();
167
+ const previousEnabled = document.enabled;
168
+ mutate(document, project, user);
169
+ const next = resolveSettings(user, project, this.providers);
170
+ if (next.effective.targetIds.some((id) => !Object.hasOwn(next.effective.destinations, id)))
171
+ throw new Error("Selected destination is missing or unsupported. Repair targetIds before saving.");
172
+ // Preserve unrecognized destinations on unrelated saves, but never enable invalid routing.
173
+ if (next.diagnostics.length && document.enabled === true && previousEnabled !== true)
174
+ throw new Error(
175
+ "Settings contain invalid fields or destinations. Repair them before enabling notifications.",
176
+ );
177
+ const temporary = join(dirname(path), `.pi-notify-${randomUUID()}.tmp`);
178
+ try {
179
+ await fs.mkdir(dirname(path), { recursive: true });
180
+ signal.throwIfAborted();
181
+ await fs.writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, { mode: 0o600, flag: "wx" });
182
+ signal.throwIfAborted();
183
+ await fs.rename(temporary, path);
184
+ } catch {
185
+ throw new Error("Settings were not saved. Check file permissions and available disk space.");
186
+ } finally {
187
+ await fs.rm(temporary, { force: true }).catch(() => {});
188
+ }
189
+ this.snapshot = next;
190
+ return next;
191
+ };
192
+ return path === this.userPath ? operation() : withFileMutationQueue(path, operation);
193
+ });
194
+ }
195
+ }
196
+
197
+ export function savePolicy(
198
+ store: SettingsStore,
199
+ scope: Scope,
200
+ key: (typeof policyKeys)[number],
201
+ value: unknown,
202
+ signal: AbortSignal,
203
+ ) {
204
+ const diagnostics: string[] = [];
205
+ if (value !== undefined) policy({ [key]: value }, diagnostics);
206
+ if (diagnostics.length) return Promise.reject(new Error("Invalid notification policy value."));
207
+ return store.change(
208
+ scope,
209
+ (document) => {
210
+ if (value === undefined) delete document[key];
211
+ else document[key] = value;
212
+ },
213
+ signal,
214
+ );
215
+ }
216
+
217
+ export function saveDestination(
218
+ store: SettingsStore,
219
+ id: string,
220
+ destination: Destination | undefined,
221
+ signal: AbortSignal,
222
+ selectNew = true,
223
+ ) {
224
+ if (!validId(id)) throw new Error("Invalid destination ID.");
225
+ const normalized = destination ? store.validate(destination) : undefined;
226
+ if (destination && !normalized) throw new Error("Invalid destination settings.");
227
+ return store.change(
228
+ "user",
229
+ (document, project) => {
230
+ if (document.destinations !== undefined && !isObject(document.destinations))
231
+ throw new Error("Invalid destinations setting. Repair the file before changing destinations.");
232
+ const destinations = isObject(document.destinations) ? { ...document.destinations } : {};
233
+ if (normalized) {
234
+ if (selectNew && !Object.hasOwn(destinations, id)) {
235
+ const diagnostics: string[] = [];
236
+ const selection = policy(
237
+ Object.hasOwn(document, "targetIds") ? { targetIds: document.targetIds } : {},
238
+ diagnostics,
239
+ );
240
+ if (diagnostics.length)
241
+ throw new Error("Invalid selected destinations. Repair targetIds before adding a destination.");
242
+ document.targetIds = [...new Set([...(selection.targetIds ?? []), id])];
243
+ }
244
+ if (Object.hasOwn(destinations, id) && !isObject(destinations[id]))
245
+ throw new Error("Invalid stored destination. Repair the file before replacing this entry.");
246
+ // Validators return owned optional keys as undefined so JSON publication removes them.
247
+ destinations[id] = { ...(isObject(destinations[id]) ? destinations[id] : {}), ...normalized };
248
+ if (Object.keys(destinations).length > MAX_DESTINATIONS)
249
+ throw new Error("At most 32 destinations are supported.");
250
+ } else {
251
+ if (Array.isArray(project.targetIds) && project.targetIds.includes(id))
252
+ throw new Error("Remove this destination from Project selections first.");
253
+ delete destinations[id];
254
+ if (Array.isArray(document.targetIds))
255
+ document.targetIds = document.targetIds.filter((target) => target !== id);
256
+ }
257
+ document.destinations = destinations;
258
+ },
259
+ signal,
260
+ );
261
+ }
@@ -0,0 +1,94 @@
1
+ import { type DeliveryResult, isObject, type NotificationProvider } from "./provider.js";
2
+ import { clipText } from "./text.js";
3
+
4
+ const TIMEOUT_MS = 10_000;
5
+ const MAX_RESPONSE_BYTES = 65_536;
6
+
7
+ /** No user-configurable origin, redirects, paid broadcasts, formatting, or retries. */
8
+ export function createTelegramProvider(fetcher: typeof fetch = fetch): NotificationProvider {
9
+ return {
10
+ id: "telegram",
11
+ label: "Telegram",
12
+ validate(value) {
13
+ if (!isObject(value) || value.provider !== "telegram") return undefined;
14
+ if (typeof value.label !== "string" || !value.label.trim() || value.label.length > 128) return undefined;
15
+ if (typeof value.botToken !== "string" || !/^\d{1,20}:[A-Za-z0-9_-]{20,200}$/.test(value.botToken))
16
+ return undefined;
17
+ if (typeof value.chatId !== "string" || !/^-?[1-9]\d{0,30}$/.test(value.chatId)) return undefined;
18
+ if (
19
+ value.messageThreadId !== undefined &&
20
+ (!Number.isSafeInteger(value.messageThreadId) || Number(value.messageThreadId) <= 0)
21
+ )
22
+ return undefined;
23
+ return {
24
+ provider: "telegram",
25
+ label: value.label,
26
+ botToken: value.botToken,
27
+ chatId: value.chatId,
28
+ messageThreadId: value.messageThreadId === undefined ? undefined : Number(value.messageThreadId),
29
+ };
30
+ },
31
+ async send(destination, notification, signal): Promise<DeliveryResult> {
32
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
33
+ const timeout = new AbortController();
34
+ const timer = setTimeout(() => timeout.abort(), TIMEOUT_MS);
35
+ const combined = AbortSignal.any([signal, timeout.signal]);
36
+ try {
37
+ const response = await fetcher(`https://api.telegram.org/bot${destination.botToken}/sendMessage`, {
38
+ method: "POST",
39
+ redirect: "error",
40
+ signal: combined,
41
+ headers: { "content-type": "application/json" },
42
+ body: JSON.stringify({
43
+ chat_id: destination.chatId,
44
+ ...(destination.messageThreadId === undefined ? {} : { message_thread_id: destination.messageThreadId }),
45
+ text: clipText(`${notification.title}\n${notification.body}`, 4096),
46
+ link_preview_options: { is_disabled: true },
47
+ }),
48
+ });
49
+ const reader = response.body?.getReader();
50
+ if (!reader) return { state: "failed", code: "response" };
51
+ let length = 0;
52
+ const chunks: Uint8Array[] = [];
53
+ try {
54
+ while (true) {
55
+ combined.throwIfAborted();
56
+ const part = await reader.read();
57
+ if (part.done) break;
58
+ length += part.value.byteLength;
59
+ if (length > MAX_RESPONSE_BYTES) return { state: "failed", code: "response" };
60
+ chunks.push(part.value);
61
+ }
62
+ } finally {
63
+ await reader.cancel().catch(() => {});
64
+ reader.releaseLock();
65
+ }
66
+ combined.throwIfAborted();
67
+ let body: unknown;
68
+ try {
69
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
70
+ } catch {
71
+ return { state: "failed", code: "response" };
72
+ }
73
+ if (!isObject(body)) return { state: "failed", code: "response" };
74
+ if (response.status === 429 || body.error_code === 429) {
75
+ const retry = isObject(body.parameters) ? body.parameters.retry_after : undefined;
76
+ return {
77
+ state: "failed",
78
+ code: "rate-limit",
79
+ ...(Number.isSafeInteger(retry) && Number(retry) > 0 ? { retryAfterSeconds: Number(retry) } : {}),
80
+ };
81
+ }
82
+ if (!response.ok) return { state: "failed", code: "http" };
83
+ return body.ok === true && isObject(body.result) ? { state: "accepted" } : { state: "failed", code: "api" };
84
+ } catch {
85
+ if (signal.aborted) return { state: "cancelled", code: "cancelled" };
86
+ return { state: "failed", code: timeout.signal.aborted ? "timeout" : "network" };
87
+ } finally {
88
+ clearTimeout(timer);
89
+ }
90
+ },
91
+ };
92
+ }
93
+
94
+ export const providers = new Map([["telegram", createTelegramProvider()]]);
package/src/text.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** Limit UTF-16 length conservatively without splitting a Unicode code point. */
2
+ export function clipText(text: string, limit: number): string {
3
+ if (text.length <= limit) return text;
4
+ let result = "";
5
+ for (const character of text) {
6
+ if (result.length + character.length > limit - 1) break;
7
+ result += character;
8
+ }
9
+ return `${result}…`;
10
+ }