@wheatley-ai/cli 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 +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +180 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +204 -0
- package/dist/cli/session.js +87 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1020 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +61 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon.js +88 -0
- package/dist/core/deployment.js +347 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +95 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +206 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
- package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +195 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +104 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +207 -0
- package/dist/triggers/webhook-ingress.js +216 -0
- package/dist/wiring/agent-services.js +144 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
import { Value } from "typebox/value";
|
|
3
|
+
import { ALLOWLIST_ENTRY } from "./chat-key.js";
|
|
4
|
+
/** The default interval between two draft edits (ADR 0012). */
|
|
5
|
+
export const DEFAULT_DRAFT_INTERVAL_MS = 1200;
|
|
6
|
+
/** Telegram rate limits make shorter draft intervals fail with HTTP 429. */
|
|
7
|
+
const MIN_DRAFT_INTERVAL_MS = 500;
|
|
8
|
+
const HTTPS_URL = "^https://\\S+$";
|
|
9
|
+
const strict = { additionalProperties: false };
|
|
10
|
+
/** The `config` of one Telegram Frontend Binding in `config.yaml`, before defaults. */
|
|
11
|
+
export const TelegramConfigSchema = Type.Object({
|
|
12
|
+
/** The Telegram Chats that the binding serves: a user, group, or supergroup ID, or a `<chat_id>:topic:<thread_id>` key. */
|
|
13
|
+
allowedChatIds: Type.Array(Type.Union([
|
|
14
|
+
Type.Integer(),
|
|
15
|
+
Type.String({ pattern: ALLOWLIST_ENTRY.source }),
|
|
16
|
+
]), { minItems: 1 }),
|
|
17
|
+
/** The secret in `secrets.yaml` that holds the bot token from BotFather. */
|
|
18
|
+
botToken: Type.Object({ secret: Type.String({ minLength: 1 }) }, strict),
|
|
19
|
+
/** The interval between two draft edits in milliseconds. The default is 1200. */
|
|
20
|
+
draftIntervalMs: Type.Optional(Type.Integer({ minimum: MIN_DRAFT_INTERVAL_MS })),
|
|
21
|
+
/** `mention` (default): in groups, answer only messages that mention the bot or reply to it. */
|
|
22
|
+
groupActivation: Type.Optional(Type.Union([Type.Literal("mention"), Type.Literal("always")])),
|
|
23
|
+
/** `polling` (default) uses outbound long polling. `webhook` mounts a route on the Webhook Ingress. */
|
|
24
|
+
mode: Type.Optional(Type.Union([Type.Literal("polling"), Type.Literal("webhook")])),
|
|
25
|
+
/** `draft` (default) streams the reply into an edited message. `typing` shows only the typing indicator. */
|
|
26
|
+
streaming: Type.Optional(Type.Union([Type.Literal("draft"), Type.Literal("typing")])),
|
|
27
|
+
/**
|
|
28
|
+
* The public HTTPS URL that Telegram calls in webhook mode. The reverse proxy must forward it to the route
|
|
29
|
+
* `/frontends/<agent>/<binding-id>/updates` of the Webhook Ingress.
|
|
30
|
+
*/
|
|
31
|
+
webhookUrl: Type.Optional(Type.String({ pattern: HTTPS_URL })),
|
|
32
|
+
}, strict);
|
|
33
|
+
const issuesOf = (value) => Value.Errors(TelegramConfigSchema, value).map((error) => ({
|
|
34
|
+
message: error.message,
|
|
35
|
+
path: error.instancePath.split("/").filter((part) => part !== ""),
|
|
36
|
+
}));
|
|
37
|
+
const normalize = (raw) => {
|
|
38
|
+
const mode = raw.mode ?? "polling";
|
|
39
|
+
if (mode === "webhook" && raw.webhookUrl === undefined) {
|
|
40
|
+
return {
|
|
41
|
+
issues: [
|
|
42
|
+
{
|
|
43
|
+
message: "webhookUrl is required when mode is webhook",
|
|
44
|
+
path: ["webhookUrl"],
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
value: {
|
|
51
|
+
allowedChatIds: raw.allowedChatIds.map(String),
|
|
52
|
+
botTokenSecret: raw.botToken.secret,
|
|
53
|
+
draftIntervalMs: raw.draftIntervalMs ?? DEFAULT_DRAFT_INTERVAL_MS,
|
|
54
|
+
groupActivation: raw.groupActivation ?? "mention",
|
|
55
|
+
streaming: raw.streaming ?? "draft",
|
|
56
|
+
transport: mode === "webhook" && raw.webhookUrl !== undefined
|
|
57
|
+
? { mode, url: raw.webhookUrl }
|
|
58
|
+
: { mode: "polling" },
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Validates and normalizes a Telegram binding config.
|
|
64
|
+
*
|
|
65
|
+
* Returns the issues for a value that breaks `TelegramConfigSchema`, or for webhook mode without `webhookUrl`.
|
|
66
|
+
*/
|
|
67
|
+
export const validateTelegramConfig = (value) => Value.Check(TelegramConfigSchema, value)
|
|
68
|
+
? normalize(value)
|
|
69
|
+
: { issues: issuesOf(value) };
|
|
70
|
+
const jsonSchemaDocument = () => ({
|
|
71
|
+
...structuredClone(TelegramConfigSchema),
|
|
72
|
+
});
|
|
73
|
+
/** Formats validation issues for an error message. */
|
|
74
|
+
export const formatIssues = (issues) => issues
|
|
75
|
+
.map((issue) => `/${issue.path.join("/")}: ${issue.message}`)
|
|
76
|
+
.join("; ");
|
|
77
|
+
/**
|
|
78
|
+
* The `configSchema` of the Telegram Frontend, as Standard JSON Schema V1 with a validator. The validator accepts the
|
|
79
|
+
* input unchanged, because `Frontend.createBinding` takes JSON config and normalizes it with `validateTelegramConfig`.
|
|
80
|
+
*/
|
|
81
|
+
export const telegramConfigSchema = {
|
|
82
|
+
"~standard": {
|
|
83
|
+
jsonSchema: { input: jsonSchemaDocument, output: jsonSchemaDocument },
|
|
84
|
+
validate: (value) => {
|
|
85
|
+
const result = validateTelegramConfig(value);
|
|
86
|
+
return result.issues === undefined
|
|
87
|
+
? { value }
|
|
88
|
+
: { issues: result.issues };
|
|
89
|
+
},
|
|
90
|
+
vendor: "wheatley",
|
|
91
|
+
version: 1,
|
|
92
|
+
},
|
|
93
|
+
};
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { chunkMarkdown, DeliveryError, isDeliveryError, } from "@wheatley-ai/sdk";
|
|
2
|
+
import { approvalKeyboard, approvalRequestText, approvalResolvedText, } from "./approvals.js";
|
|
3
|
+
import { attachmentSize, skippedFilesText, toUpload } from "./attachments.js";
|
|
4
|
+
import { parseChatKey } from "./chat-key.js";
|
|
5
|
+
import { TelegramApiError } from "./client.js";
|
|
6
|
+
import { HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_TOO_MANY_REQUESTS, } from "./http-status.js";
|
|
7
|
+
import { markdownToTelegramHtml } from "./markdown.js";
|
|
8
|
+
import { RecentSet } from "./recent-set.js";
|
|
9
|
+
/** Chunks stay below the 4096-character message limit of the Bot API. */
|
|
10
|
+
const MAX_CHUNK_LENGTH = 4000;
|
|
11
|
+
const MS_PER_SECOND = 1000;
|
|
12
|
+
/** How many delivered message IDs a binding remembers to drop duplicates. */
|
|
13
|
+
const DEDUP_CAPACITY = 1000;
|
|
14
|
+
const PARSE_ERROR = /can't parse entities/iu;
|
|
15
|
+
const NOT_MODIFIED = /message is not modified/iu;
|
|
16
|
+
/** Converts a client error to the `DeliveryError` that the outbox expects. */
|
|
17
|
+
const toDeliveryError = (cause) => {
|
|
18
|
+
if (isDeliveryError(cause)) {
|
|
19
|
+
return cause;
|
|
20
|
+
}
|
|
21
|
+
if (!(cause instanceof TelegramApiError)) {
|
|
22
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
23
|
+
return new DeliveryError(message, { cause, kind: "retryable" });
|
|
24
|
+
}
|
|
25
|
+
if (cause.code === HTTP_TOO_MANY_REQUESTS) {
|
|
26
|
+
return new DeliveryError(cause.message, {
|
|
27
|
+
cause,
|
|
28
|
+
kind: "retryable",
|
|
29
|
+
retryAfterMs: cause.retryAfterSeconds === undefined
|
|
30
|
+
? undefined
|
|
31
|
+
: cause.retryAfterSeconds * MS_PER_SECOND,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
// 400 means a deleted Chat, a deleted topic, or a request that Telegram never accepts. 403 means a removed bot.
|
|
35
|
+
const isPermanent = cause.code === HTTP_BAD_REQUEST || cause.code === HTTP_FORBIDDEN;
|
|
36
|
+
return new DeliveryError(cause.message, {
|
|
37
|
+
cause,
|
|
38
|
+
kind: isPermanent ? "permanent" : "retryable",
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
const isBadRequest = (cause) => cause instanceof TelegramApiError && cause.code === HTTP_BAD_REQUEST;
|
|
42
|
+
const isApiError = (cause, pattern) => isBadRequest(cause) && pattern.test(cause.message);
|
|
43
|
+
/**
|
|
44
|
+
* Creates the `FrontendBinding.deliver` of a Telegram binding.
|
|
45
|
+
*
|
|
46
|
+
* A `message` delivery sends its text chunks in order, then its attachments, then one notice that names the
|
|
47
|
+
* attachments over `maxAttachmentBytes`. A retry resumes after the parts that Telegram already confirmed, and a
|
|
48
|
+
* delivery that already succeeded is dropped. Rejects with a `DeliveryError`: permanent for an invalid or unlisted
|
|
49
|
+
* Chat and for Bot API codes 400 and 403, retryable for other failures.
|
|
50
|
+
*/
|
|
51
|
+
export const createDeliverer = (deps) => {
|
|
52
|
+
const { approvals, client, isAllowed, live, log, maxAttachmentBytes } = deps;
|
|
53
|
+
const progress = new Map();
|
|
54
|
+
const delivered = new RecentSet(DEDUP_CAPACITY);
|
|
55
|
+
const sendFormatted = async (target, markdown) => {
|
|
56
|
+
try {
|
|
57
|
+
return await client.sendMessage(target, markdownToTelegramHtml(markdown), { parseMode: "HTML" });
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (!isApiError(error, PARSE_ERROR)) {
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
return await client.sendMessage(target, markdown);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
/** Edits a message. Resolves `false` if Telegram cannot edit it any more, for example because it was deleted. */
|
|
67
|
+
const editFormatted = async (chatId, messageId, html, plain, options = {}) => {
|
|
68
|
+
try {
|
|
69
|
+
await client.editMessageText(chatId, messageId, html, {
|
|
70
|
+
...options,
|
|
71
|
+
parseMode: "HTML",
|
|
72
|
+
});
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (isApiError(error, NOT_MODIFIED)) {
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
if (isApiError(error, PARSE_ERROR)) {
|
|
80
|
+
await client.editMessageText(chatId, messageId, plain, options);
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
if (isBadRequest(error)) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/** Sends one chunk of a reply, into the Run's draft message if there is one that Telegram can still edit. */
|
|
90
|
+
const sendChunk = async (target, chunk, draft) => {
|
|
91
|
+
const edited = draft !== undefined &&
|
|
92
|
+
(await editFormatted(draft.target.chatId, draft.messageId, markdownToTelegramHtml(chunk), chunk));
|
|
93
|
+
if (!edited) {
|
|
94
|
+
await sendFormatted(target, chunk);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const progressOf = async (delivery, target) => {
|
|
98
|
+
const existing = progress.get(delivery.messageId);
|
|
99
|
+
if (existing !== undefined) {
|
|
100
|
+
return existing;
|
|
101
|
+
}
|
|
102
|
+
const draft = delivery.runId === undefined
|
|
103
|
+
? undefined
|
|
104
|
+
: await live.takeDraft(delivery.runId);
|
|
105
|
+
const sameChat = draft?.target.chatId === target.chatId &&
|
|
106
|
+
draft.target.threadId === target.threadId;
|
|
107
|
+
const state = { draft: sameChat ? draft : undefined, sentParts: 0 };
|
|
108
|
+
progress.set(delivery.messageId, state);
|
|
109
|
+
return state;
|
|
110
|
+
};
|
|
111
|
+
const deliverMessage = async (delivery, target) => {
|
|
112
|
+
const attachments = delivery.attachments ?? [];
|
|
113
|
+
const uploads = attachments.filter((attachment) => attachmentSize(attachment) <= maxAttachmentBytes);
|
|
114
|
+
const skipped = attachments
|
|
115
|
+
.filter((attachment) => attachmentSize(attachment) > maxAttachmentBytes)
|
|
116
|
+
.map((attachment) => attachment.filename);
|
|
117
|
+
if (skipped.length > 0) {
|
|
118
|
+
log.warn("Skipped outbound Telegram attachments over the limit", {
|
|
119
|
+
chatId: delivery.chatId,
|
|
120
|
+
filenames: skipped,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
const chunks = chunkMarkdown(delivery.text, MAX_CHUNK_LENGTH).filter((chunk) => chunk.trim() !== "");
|
|
124
|
+
const state = await progressOf(delivery, target);
|
|
125
|
+
const parts = [
|
|
126
|
+
...chunks.map((chunk, index) => async () => {
|
|
127
|
+
await sendChunk(target, chunk, index === 0 ? state.draft : undefined);
|
|
128
|
+
}),
|
|
129
|
+
...uploads.map((attachment) => async () => {
|
|
130
|
+
const upload = toUpload(attachment);
|
|
131
|
+
await client.sendFile(target, upload.kind, upload.file);
|
|
132
|
+
}),
|
|
133
|
+
...(skipped.length === 0
|
|
134
|
+
? []
|
|
135
|
+
: [
|
|
136
|
+
async () => {
|
|
137
|
+
await client.sendMessage(target, skippedFilesText(skipped, maxAttachmentBytes));
|
|
138
|
+
},
|
|
139
|
+
]),
|
|
140
|
+
];
|
|
141
|
+
for (const [index, part] of parts.entries()) {
|
|
142
|
+
if (index < state.sentParts) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
// oxlint-disable-next-line no-await-in-loop -- Parts must arrive in order.
|
|
146
|
+
await part();
|
|
147
|
+
state.sentParts = index + 1;
|
|
148
|
+
}
|
|
149
|
+
progress.delete(delivery.messageId);
|
|
150
|
+
delivered.add(delivery.messageId);
|
|
151
|
+
};
|
|
152
|
+
const deliverApprovalRequest = async (delivery, target) => {
|
|
153
|
+
if (approvals.get(delivery.approvalId) !== undefined) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const messageId = await client.sendMessage(target, approvalRequestText(delivery), { keyboard: approvalKeyboard(delivery.approvalId), parseMode: "HTML" });
|
|
157
|
+
await approvals.put({
|
|
158
|
+
approvalId: delivery.approvalId,
|
|
159
|
+
chatId: delivery.chatId,
|
|
160
|
+
inputPreview: delivery.inputPreview,
|
|
161
|
+
messageId,
|
|
162
|
+
telegramChatId: target.chatId,
|
|
163
|
+
toolName: delivery.toolName,
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
const deliverApprovalResolved = async (delivery, target) => {
|
|
167
|
+
const prompt = approvals.get(delivery.approvalId);
|
|
168
|
+
const html = approvalResolvedText(delivery, prompt);
|
|
169
|
+
const edited = prompt !== undefined &&
|
|
170
|
+
(await editFormatted(prompt.telegramChatId, prompt.messageId, html, html, {
|
|
171
|
+
keyboard: [],
|
|
172
|
+
}));
|
|
173
|
+
if (!edited) {
|
|
174
|
+
await client.sendMessage(target, html, { parseMode: "HTML" });
|
|
175
|
+
}
|
|
176
|
+
await approvals.delete(delivery.approvalId);
|
|
177
|
+
delivered.add(delivery.messageId);
|
|
178
|
+
};
|
|
179
|
+
return async (delivery) => {
|
|
180
|
+
const target = parseChatKey(delivery.chatId);
|
|
181
|
+
if (target === undefined) {
|
|
182
|
+
throw new DeliveryError(`Invalid Telegram chat ID: ${delivery.chatId}`, {
|
|
183
|
+
kind: "permanent",
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if (!isAllowed(delivery.chatId)) {
|
|
187
|
+
throw new DeliveryError(`Telegram chat ${delivery.chatId} is not in allowedChatIds`, { kind: "permanent" });
|
|
188
|
+
}
|
|
189
|
+
if (delivered.has(delivery.messageId)) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
switch (delivery.kind) {
|
|
194
|
+
case "message": {
|
|
195
|
+
await deliverMessage(delivery, target);
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "approval_requested": {
|
|
199
|
+
await deliverApprovalRequest(delivery, target);
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
case "approval_resolved": {
|
|
203
|
+
await deliverApprovalResolved(delivery, target);
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
default: {
|
|
207
|
+
break;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
throw toDeliveryError(error);
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createTelegramBinding } from "./binding.js";
|
|
2
|
+
import { formatIssues, telegramConfigSchema, validateTelegramConfig, } from "./config.js";
|
|
3
|
+
/** The `type` of Telegram Frontend Bindings in `config.yaml`. */
|
|
4
|
+
export const TELEGRAM_FRONTEND_TYPE = "telegram";
|
|
5
|
+
/**
|
|
6
|
+
* The `agent.sqlite` migrations of the Telegram Frontend. It has none: it keeps its Approval prompts in the binding's
|
|
7
|
+
* `FrontendContext.dataDir`.
|
|
8
|
+
*/
|
|
9
|
+
export const telegramMigrations = [];
|
|
10
|
+
/** The JSON-RPC handlers of the Telegram Frontend. It has none: Frontend Bindings report through `agent.status`. */
|
|
11
|
+
export const telegramRpcHandlers = {};
|
|
12
|
+
const loadGrammyClient = async (token) => {
|
|
13
|
+
const { createGrammyClient } = await import("./grammy-client.js");
|
|
14
|
+
return await createGrammyClient(token);
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Creates the built-in Telegram Frontend.
|
|
18
|
+
*
|
|
19
|
+
* `createBinding` throws if the config is invalid, if the bot token secret is missing, or if webhook mode is configured
|
|
20
|
+
* while the Webhook Ingress is disabled.
|
|
21
|
+
*/
|
|
22
|
+
export const createTelegramFrontend = (options = {}) => {
|
|
23
|
+
const createClient = options.createClient ?? loadGrammyClient;
|
|
24
|
+
return {
|
|
25
|
+
configSchema: telegramConfigSchema,
|
|
26
|
+
createBinding: async (rawConfig, ctx) => {
|
|
27
|
+
const validated = validateTelegramConfig(rawConfig);
|
|
28
|
+
if (validated.issues !== undefined) {
|
|
29
|
+
throw new Error(`Invalid config for Telegram binding ${ctx.bindingId}: ${formatIssues(validated.issues)}`);
|
|
30
|
+
}
|
|
31
|
+
const config = validated.value;
|
|
32
|
+
const token = ctx.secrets.get(config.botTokenSecret);
|
|
33
|
+
if (token === undefined || token === "") {
|
|
34
|
+
throw new Error(`Telegram binding ${ctx.bindingId} needs the secret ${config.botTokenSecret} in secrets.yaml`);
|
|
35
|
+
}
|
|
36
|
+
return createTelegramBinding(config, ctx, await createClient(token));
|
|
37
|
+
},
|
|
38
|
+
type: TELEGRAM_FRONTEND_TYPE,
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
/** The built-in Telegram Frontend, for the built-in Frontends of `ExtensionCatalog`. */
|
|
42
|
+
export const telegramFrontend = createTelegramFrontend();
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { TelegramApiError } from "./client.js";
|
|
2
|
+
import { HTTP_BAD_REQUEST } from "./http-status.js";
|
|
3
|
+
const ALLOWED_UPDATES = ["message", "callback_query"];
|
|
4
|
+
const DEFAULT_API_ROOT = "https://api.telegram.org";
|
|
5
|
+
const markupOf = (options) => options?.keyboard === undefined
|
|
6
|
+
? undefined
|
|
7
|
+
: {
|
|
8
|
+
inline_keyboard: options.keyboard.map((row) => row.map((button) => ({
|
|
9
|
+
callback_data: button.callbackData,
|
|
10
|
+
text: button.text,
|
|
11
|
+
}))),
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Creates a `TelegramClient` backed by grammY. It imports `grammy` on the first call, so Deployments without a Telegram
|
|
15
|
+
* binding never load it (ADR 0012).
|
|
16
|
+
*/
|
|
17
|
+
export const createGrammyClient = async (token, clientOptions = {}) => {
|
|
18
|
+
const { Bot, GrammyError, InputFile } = await import("grammy");
|
|
19
|
+
const apiRoot = clientOptions.apiRoot ?? DEFAULT_API_ROOT;
|
|
20
|
+
const bot = new Bot(token, { client: { apiRoot } });
|
|
21
|
+
const { api } = bot;
|
|
22
|
+
const toApiError = (cause) => {
|
|
23
|
+
if (cause instanceof GrammyError) {
|
|
24
|
+
return new TelegramApiError(cause.description, {
|
|
25
|
+
cause,
|
|
26
|
+
code: cause.error_code,
|
|
27
|
+
retryAfterSeconds: cause.parameters.retry_after,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
31
|
+
return new TelegramApiError(message, { cause });
|
|
32
|
+
};
|
|
33
|
+
const call = async (request) => {
|
|
34
|
+
try {
|
|
35
|
+
return await request();
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
throw toApiError(error);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const inputFile = (file) => "data" in file
|
|
42
|
+
? new InputFile(file.data, file.filename)
|
|
43
|
+
: new InputFile(file.path, file.filename);
|
|
44
|
+
return {
|
|
45
|
+
answerCallbackQuery: async (callbackQueryId, text) => {
|
|
46
|
+
await call(async () => await api.answerCallbackQuery(callbackQueryId, text === undefined ? undefined : { text }));
|
|
47
|
+
},
|
|
48
|
+
downloadFile: async (fileId) => {
|
|
49
|
+
const file = await call(async () => await api.getFile(fileId));
|
|
50
|
+
if (file.file_path === undefined) {
|
|
51
|
+
throw new TelegramApiError("Telegram returned no file path", {
|
|
52
|
+
code: HTTP_BAD_REQUEST,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
const filePath = file.file_path;
|
|
56
|
+
const response = await call(async () => await fetch(`${apiRoot}/file/bot${token}/${filePath}`));
|
|
57
|
+
if (!response.ok || response.body === null) {
|
|
58
|
+
throw new TelegramApiError(`File download failed with HTTP ${response.status}`, { code: response.status });
|
|
59
|
+
}
|
|
60
|
+
return response.body;
|
|
61
|
+
},
|
|
62
|
+
editMessageText: async (chatId, messageId, text, options) => {
|
|
63
|
+
await call(async () => await api.editMessageText(chatId, messageId, text, {
|
|
64
|
+
parse_mode: options?.parseMode,
|
|
65
|
+
reply_markup: markupOf(options),
|
|
66
|
+
}));
|
|
67
|
+
},
|
|
68
|
+
getMe: async () => {
|
|
69
|
+
const me = await call(async () => await api.getMe());
|
|
70
|
+
return { id: me.id, username: me.username };
|
|
71
|
+
},
|
|
72
|
+
sendFile: async ({ chatId, threadId }, kind, file) => {
|
|
73
|
+
const other = { message_thread_id: threadId };
|
|
74
|
+
if (kind === "photo") {
|
|
75
|
+
const photo = await call(async () => await api.sendPhoto(chatId, inputFile(file), other));
|
|
76
|
+
return photo.message_id;
|
|
77
|
+
}
|
|
78
|
+
const document = await call(async () => await api.sendDocument(chatId, inputFile(file), other));
|
|
79
|
+
return document.message_id;
|
|
80
|
+
},
|
|
81
|
+
sendMessage: async ({ chatId, threadId }, text, options) => {
|
|
82
|
+
const sent = await call(async () => await api.sendMessage(chatId, text, {
|
|
83
|
+
message_thread_id: threadId,
|
|
84
|
+
parse_mode: options?.parseMode,
|
|
85
|
+
reply_markup: markupOf(options),
|
|
86
|
+
}));
|
|
87
|
+
return sent.message_id;
|
|
88
|
+
},
|
|
89
|
+
sendTyping: async ({ chatId, threadId }) => {
|
|
90
|
+
await call(async () => await api.sendChatAction(chatId, "typing", {
|
|
91
|
+
message_thread_id: threadId,
|
|
92
|
+
}));
|
|
93
|
+
},
|
|
94
|
+
setMyCommands: async (commands) => {
|
|
95
|
+
await call(async () => await api.setMyCommands(commands));
|
|
96
|
+
},
|
|
97
|
+
startPolling: async (onUpdate) => {
|
|
98
|
+
bot.use(async (ctx) => {
|
|
99
|
+
await onUpdate(ctx.update);
|
|
100
|
+
});
|
|
101
|
+
await call(async () => {
|
|
102
|
+
await bot.start({
|
|
103
|
+
allowed_updates: [...ALLOWED_UPDATES],
|
|
104
|
+
drop_pending_updates: false,
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
stopPolling: async () => {
|
|
109
|
+
if (bot.isRunning()) {
|
|
110
|
+
await call(async () => {
|
|
111
|
+
await bot.stop();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
setWebhook: async (url, secretToken) => {
|
|
116
|
+
await call(async () => await api.setWebhook(url, {
|
|
117
|
+
allowed_updates: [...ALLOWED_UPDATES],
|
|
118
|
+
secret_token: secretToken,
|
|
119
|
+
}));
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** HTTP status codes that the webhook route returns and that the Bot API reports as `error_code`. */
|
|
2
|
+
export const HTTP_OK = 200;
|
|
3
|
+
export const HTTP_BAD_REQUEST = 400;
|
|
4
|
+
export const HTTP_UNAUTHORIZED = 401;
|
|
5
|
+
export const HTTP_FORBIDDEN = 403;
|
|
6
|
+
export const HTTP_TOO_MANY_REQUESTS = 429;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { DISPLAY_NAME_MAX_LENGTH } from "@wheatley-ai/protocol";
|
|
2
|
+
import { parseCommandText } from "@wheatley-ai/sdk";
|
|
3
|
+
import { parseApprovalCallback } from "./approvals.js";
|
|
4
|
+
import { incomingFiles, skippedFilesText, stageIncomingFiles, } from "./attachments.js";
|
|
5
|
+
import { chatKeyOf, targetOf } from "./chat-key.js";
|
|
6
|
+
const COMMAND_SUFFIX = /^\/[a-z]+@(?<bot>\w+)/iu;
|
|
7
|
+
const GROUP_TYPES = new Set(["group", "supergroup"]);
|
|
8
|
+
const displayName = (user) => {
|
|
9
|
+
if (user === undefined) {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
const fullName = [user.first_name, user.last_name ?? ""].join(" ").trim();
|
|
13
|
+
const name = fullName === "" ? user.username : fullName;
|
|
14
|
+
return name?.slice(0, DISPLAY_NAME_MAX_LENGTH);
|
|
15
|
+
};
|
|
16
|
+
const entityText = (text, entity) => text.slice(entity.offset, entity.offset + entity.length);
|
|
17
|
+
/** Returns true if a group message mentions the bot, runs its command, or replies to it. */
|
|
18
|
+
const isAddressedToBot = (message, text, entities, me) => {
|
|
19
|
+
const mention = me.username === undefined ? undefined : `@${me.username}`.toLowerCase();
|
|
20
|
+
const mentioned = entities.some((entity) => {
|
|
21
|
+
const value = entityText(text, entity).toLowerCase();
|
|
22
|
+
return ((mention !== undefined &&
|
|
23
|
+
((entity.type === "mention" && value === mention) ||
|
|
24
|
+
(entity.type === "bot_command" && value.endsWith(mention)))) ||
|
|
25
|
+
(entity.type === "text_mention" && entity.user?.id === me.id));
|
|
26
|
+
});
|
|
27
|
+
const reply = message.reply_to_message;
|
|
28
|
+
// In a forum topic, Telegram sets `reply_to_message` to the topic's first message on every message.
|
|
29
|
+
const isTopicRoot = message.is_topic_message === true &&
|
|
30
|
+
reply?.message_id === message.message_thread_id;
|
|
31
|
+
const repliesToBot = !isTopicRoot && reply?.from?.id === me.id;
|
|
32
|
+
return mentioned || repliesToBot;
|
|
33
|
+
};
|
|
34
|
+
/** Removes `@<bot>` mentions from message text. */
|
|
35
|
+
const stripMention = (text, me) => (me.username === undefined
|
|
36
|
+
? text
|
|
37
|
+
: text.replaceAll(new RegExp(`@${me.username}\\b`, "giu"), ""))
|
|
38
|
+
.replaceAll(/[ \t]{2,}/gu, " ")
|
|
39
|
+
.trim();
|
|
40
|
+
/** Returns true if the text is a command for another bot, for example `/new@other_bot`. */
|
|
41
|
+
const isCommandForOtherBot = (text, me) => {
|
|
42
|
+
const commandBot = COMMAND_SUFFIX.exec(text.trim())?.groups?.bot;
|
|
43
|
+
return (commandBot !== undefined &&
|
|
44
|
+
commandBot.toLowerCase() !== me.username?.toLowerCase());
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Creates the inbound side of a Telegram binding: messages, commands, and Approval button presses.
|
|
48
|
+
*
|
|
49
|
+
* It drops updates from Chats outside `allowedChatIds` with an `info` log, and it logs any other failure at `error`
|
|
50
|
+
* instead of rejecting, so one bad update does not stop the updates after it.
|
|
51
|
+
*/
|
|
52
|
+
export const createUpdateHandler = (deps) => {
|
|
53
|
+
const { approvals, client, config, ctx, isAllowed } = deps;
|
|
54
|
+
const { log } = ctx;
|
|
55
|
+
/** Stages the files of a message and tells the Chat about files over the limit. */
|
|
56
|
+
const stageFiles = async (message) => {
|
|
57
|
+
const staged = await stageIncomingFiles(client, incomingFiles(message), ctx.stagingDir, ctx.maxAttachmentBytes);
|
|
58
|
+
if (staged.tooLarge.length > 0) {
|
|
59
|
+
await client.sendMessage(targetOf(message), skippedFilesText(staged.tooLarge, ctx.maxAttachmentBytes));
|
|
60
|
+
}
|
|
61
|
+
return staged;
|
|
62
|
+
};
|
|
63
|
+
const handleMessage = async (message, sink, me) => {
|
|
64
|
+
if (message.from?.is_bot === true) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const chatId = chatKeyOf(message);
|
|
68
|
+
if (!isAllowed(chatId)) {
|
|
69
|
+
log.info("Dropped a message from a Telegram chat that is not in allowedChatIds", { chatId });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const text = message.text ?? message.caption ?? "";
|
|
73
|
+
const entities = message.entities ?? message.caption_entities ?? [];
|
|
74
|
+
const senderDisplayName = displayName(message.from);
|
|
75
|
+
const isGroup = GROUP_TYPES.has(message.chat.type);
|
|
76
|
+
if (isCommandForOtherBot(text, me)) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
// Commands skip mention gating: a command addresses bots by itself, and Telegram delivers bare commands to bots in
|
|
80
|
+
// privacy mode. A command for another bot returned above.
|
|
81
|
+
const command = parseCommandText(text);
|
|
82
|
+
if (command !== undefined) {
|
|
83
|
+
await sink.command({
|
|
84
|
+
args: command.args,
|
|
85
|
+
chatId,
|
|
86
|
+
name: command.name,
|
|
87
|
+
senderDisplayName,
|
|
88
|
+
});
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const needsMention = isGroup && config.groupActivation === "mention";
|
|
92
|
+
if (needsMention && !isAddressedToBot(message, text, entities, me)) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const staged = await stageFiles(message);
|
|
96
|
+
const body = isGroup ? stripMention(text, me) : text.trim();
|
|
97
|
+
if (body === "" && staged.attachments.length === 0) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
await sink.send({
|
|
101
|
+
attachments: staged.attachments.length === 0 ? undefined : staged.attachments,
|
|
102
|
+
chatId,
|
|
103
|
+
senderDisplayName,
|
|
104
|
+
text: body,
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
const handleCallback = async (query, sink) => {
|
|
108
|
+
const parsed = parseApprovalCallback(query.data ?? "");
|
|
109
|
+
const { message } = query;
|
|
110
|
+
const chatId = message === undefined ? undefined : chatKeyOf(message);
|
|
111
|
+
if (chatId !== undefined && !isAllowed(chatId)) {
|
|
112
|
+
log.info("Dropped a button press from a Telegram chat that is not in allowedChatIds", { chatId });
|
|
113
|
+
await client.answerCallbackQuery(query.id);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const prompt = parsed === undefined ? undefined : approvals.byToken(parsed.token);
|
|
117
|
+
if (parsed === undefined ||
|
|
118
|
+
prompt === undefined ||
|
|
119
|
+
prompt.chatId !== chatId) {
|
|
120
|
+
await client.answerCallbackQuery(query.id, "This approval has already ended.");
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const won = await sink.decide({
|
|
124
|
+
approvalId: prompt.approvalId,
|
|
125
|
+
chatId: prompt.chatId,
|
|
126
|
+
resolution: {
|
|
127
|
+
decision: parsed.decision,
|
|
128
|
+
resolvedBy: displayName(query.from),
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
await client.answerCallbackQuery(query.id, won ? "Decision recorded." : "This approval has already ended.");
|
|
132
|
+
};
|
|
133
|
+
return async (update, sink, me) => {
|
|
134
|
+
try {
|
|
135
|
+
if (update.message !== undefined) {
|
|
136
|
+
await handleMessage(update.message, sink, me);
|
|
137
|
+
}
|
|
138
|
+
else if (update.callback_query !== undefined) {
|
|
139
|
+
await handleCallback(update.callback_query, sink);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
log.error("Failed to handle a Telegram update", {
|
|
144
|
+
error: String(error),
|
|
145
|
+
updateId: update.update_id,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
};
|