@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,112 @@
|
|
|
1
|
+
import { readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { dropOldest } from "./bounded.js";
|
|
4
|
+
import { decodeOptional, parseJsonText, StateFileSchema } from "./schemas.js";
|
|
5
|
+
/** The file in `FrontendContext.dataDir` that keeps the binding state across daemon restarts. */
|
|
6
|
+
export const STATE_FILE = "slack-state.json";
|
|
7
|
+
/** The number of engaged threads that the binding remembers. It forgets the oldest thread first. */
|
|
8
|
+
const MAX_THREADS = 1000;
|
|
9
|
+
/** The number of ended Approvals that the binding remembers to drop duplicate `approval_resolved` deliveries. */
|
|
10
|
+
const MAX_RESOLVED_APPROVALS = 500;
|
|
11
|
+
const readState = async (file) => {
|
|
12
|
+
try {
|
|
13
|
+
return await readFile(file, "utf-8");
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
throw error;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The persistent state of one Slack binding: the message of each Approval prompt, and the threads where the bot takes
|
|
24
|
+
* part. Map insertion order is age order, so the store drops the oldest entries first.
|
|
25
|
+
*/
|
|
26
|
+
export class SlackStateStore {
|
|
27
|
+
#file;
|
|
28
|
+
#log;
|
|
29
|
+
#approvals = new Map();
|
|
30
|
+
#threads = new Set();
|
|
31
|
+
#writes = Promise.resolve();
|
|
32
|
+
constructor(dataDir, log) {
|
|
33
|
+
this.#file = path.join(dataDir, STATE_FILE);
|
|
34
|
+
this.#log = log;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Reads the state file of a binding. A missing file gives an empty state. A corrupt file also gives an empty state
|
|
38
|
+
* and logs a warning, so a bad file never stops the binding. Rejects only if the file exists but cannot be read.
|
|
39
|
+
*/
|
|
40
|
+
static load = async (dataDir, log) => {
|
|
41
|
+
const store = new SlackStateStore(dataDir, log);
|
|
42
|
+
const text = await readState(store.#file);
|
|
43
|
+
if (text === undefined) {
|
|
44
|
+
return store;
|
|
45
|
+
}
|
|
46
|
+
const state = decodeOptional(StateFileSchema, parseJsonText(text));
|
|
47
|
+
if (state === undefined) {
|
|
48
|
+
log.warn("Ignored a corrupt Slack state file", { path: store.#file });
|
|
49
|
+
return store;
|
|
50
|
+
}
|
|
51
|
+
for (const [approvalId, record] of Object.entries(state.approvals)) {
|
|
52
|
+
store.#approvals.set(approvalId, record);
|
|
53
|
+
}
|
|
54
|
+
for (const chatId of state.threads) {
|
|
55
|
+
store.#threads.add(chatId);
|
|
56
|
+
}
|
|
57
|
+
return store;
|
|
58
|
+
};
|
|
59
|
+
approval = (approvalId) => this.#approvals.get(approvalId);
|
|
60
|
+
/** Stores the prompt message of an Approval and persists the state. Never rejects. */
|
|
61
|
+
putApproval = async (approvalId, record) => {
|
|
62
|
+
this.#approvals.delete(approvalId);
|
|
63
|
+
this.#approvals.set(approvalId, record);
|
|
64
|
+
this.#pruneResolved();
|
|
65
|
+
await this.#persist();
|
|
66
|
+
};
|
|
67
|
+
isEngaged = (chatId) => this.#threads.has(chatId);
|
|
68
|
+
/** Remembers that the bot takes part in a thread Chat, so replies in it need no mention. Never rejects. */
|
|
69
|
+
engage = async (chatId) => {
|
|
70
|
+
if (this.#threads.has(chatId)) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
this.#threads.add(chatId);
|
|
74
|
+
dropOldest(this.#threads, MAX_THREADS);
|
|
75
|
+
await this.#persist();
|
|
76
|
+
};
|
|
77
|
+
/** Resolves after every started write finished. */
|
|
78
|
+
flush = async () => {
|
|
79
|
+
await this.#writes;
|
|
80
|
+
};
|
|
81
|
+
#pruneResolved = () => {
|
|
82
|
+
const resolved = [...this.#approvals].filter(([, record]) => record.resolved);
|
|
83
|
+
const excess = Math.max(0, resolved.length - MAX_RESOLVED_APPROVALS);
|
|
84
|
+
for (const [approvalId] of resolved.slice(0, excess)) {
|
|
85
|
+
this.#approvals.delete(approvalId);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/** Queues a snapshot write after the previous write. Never rejects. */
|
|
89
|
+
#persist = async () => {
|
|
90
|
+
const snapshot = JSON.stringify({
|
|
91
|
+
approvals: Object.fromEntries(this.#approvals),
|
|
92
|
+
threads: [...this.#threads],
|
|
93
|
+
});
|
|
94
|
+
this.#writes = this.#write(this.#writes, snapshot);
|
|
95
|
+
await this.#writes;
|
|
96
|
+
};
|
|
97
|
+
/** Writes to a temporary file and renames it, so a crash never leaves a partial file. */
|
|
98
|
+
#write = async (previous, snapshot) => {
|
|
99
|
+
await previous;
|
|
100
|
+
const temporary = `${this.#file}.tmp`;
|
|
101
|
+
try {
|
|
102
|
+
await writeFile(temporary, snapshot, "utf-8");
|
|
103
|
+
await rename(temporary, this.#file);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
this.#log.error("Could not write the Slack state file", {
|
|
107
|
+
error: String(error),
|
|
108
|
+
path: this.#file,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Type } from "typebox";
|
|
5
|
+
import { Value } from "typebox/value";
|
|
6
|
+
import { escapeHtml } from "./markdown.js";
|
|
7
|
+
import { SerialQueue } from "./serial-queue.js";
|
|
8
|
+
const STORE_FILE = "approvals.json";
|
|
9
|
+
const CALLBACK_PREFIX = "ap";
|
|
10
|
+
const TOKEN_LENGTH = 16;
|
|
11
|
+
const CALLBACK_DATA = /^ap:(?<token>[\w-]+):(?<code>[ocad])$/u;
|
|
12
|
+
/** The four buttons of an Approval prompt, in display order, with their callback codes. */
|
|
13
|
+
const BUTTONS = [
|
|
14
|
+
{ code: "o", decision: "allow_once", label: "Allow once" },
|
|
15
|
+
{ code: "c", decision: "allow_conversation", label: "Allow for chat" },
|
|
16
|
+
{ code: "a", decision: "allow_always", label: "Always allow" },
|
|
17
|
+
{ code: "d", decision: "deny", label: "Deny" },
|
|
18
|
+
];
|
|
19
|
+
const OUTCOME_TEXT = {
|
|
20
|
+
allow_always: "Always allowed",
|
|
21
|
+
allow_conversation: "Allowed for this conversation",
|
|
22
|
+
allow_once: "Allowed once",
|
|
23
|
+
cancelled: "Cancelled",
|
|
24
|
+
deny: "Denied",
|
|
25
|
+
timeout: "Timed out",
|
|
26
|
+
};
|
|
27
|
+
const PromptSchema = Type.Object({
|
|
28
|
+
approvalId: Type.String(),
|
|
29
|
+
chatId: Type.String(),
|
|
30
|
+
inputPreview: Type.String(),
|
|
31
|
+
messageId: Type.Number(),
|
|
32
|
+
telegramChatId: Type.Number(),
|
|
33
|
+
toolName: Type.String(),
|
|
34
|
+
});
|
|
35
|
+
const StoreSchema = Type.Record(Type.String(), PromptSchema);
|
|
36
|
+
/** Returns the short key of an Approval for callback data, which Telegram limits to 64 bytes. */
|
|
37
|
+
export const approvalToken = (approvalId) => createHash("sha256")
|
|
38
|
+
.update(approvalId)
|
|
39
|
+
.digest("base64url")
|
|
40
|
+
.slice(0, TOKEN_LENGTH);
|
|
41
|
+
/** The inline keyboard of an Approval prompt: two rows of two buttons. */
|
|
42
|
+
export const approvalKeyboard = (approvalId) => {
|
|
43
|
+
const token = approvalToken(approvalId);
|
|
44
|
+
const buttons = BUTTONS.map((button) => ({
|
|
45
|
+
callbackData: `${CALLBACK_PREFIX}:${token}:${button.code}`,
|
|
46
|
+
text: button.label,
|
|
47
|
+
}));
|
|
48
|
+
return [buttons.slice(0, 2), buttons.slice(2)];
|
|
49
|
+
};
|
|
50
|
+
/** Parses the callback data of an Approval button. Returns `undefined` for other callback data. */
|
|
51
|
+
export const parseApprovalCallback = (data) => {
|
|
52
|
+
const groups = CALLBACK_DATA.exec(data)?.groups;
|
|
53
|
+
const button = BUTTONS.find((entry) => entry.code === groups?.code);
|
|
54
|
+
return groups?.token === undefined || button === undefined
|
|
55
|
+
? undefined
|
|
56
|
+
: { decision: button.decision, token: groups.token };
|
|
57
|
+
};
|
|
58
|
+
const describeTool = (toolName, inputPreview) => `Tool: <code>${escapeHtml(toolName)}</code>\n<pre>${escapeHtml(inputPreview)}</pre>`;
|
|
59
|
+
/** The HTML text of an Approval prompt. */
|
|
60
|
+
export const approvalRequestText = (delivery) => {
|
|
61
|
+
const expiry = delivery.expiresAt === null
|
|
62
|
+
? ""
|
|
63
|
+
: `\nExpires: ${escapeHtml(delivery.expiresAt)}`;
|
|
64
|
+
return `<b>Approval needed</b>\n${describeTool(delivery.toolName, delivery.inputPreview)}${expiry}`;
|
|
65
|
+
};
|
|
66
|
+
/** The HTML text that replaces an Approval prompt when the Approval ends. */
|
|
67
|
+
export const approvalResolvedText = (delivery, prompt) => {
|
|
68
|
+
const by = delivery.resolvedBy === undefined
|
|
69
|
+
? ""
|
|
70
|
+
: ` by ${escapeHtml(delivery.resolvedBy)}`;
|
|
71
|
+
const reason = delivery.reason === undefined
|
|
72
|
+
? ""
|
|
73
|
+
: `\nReason: ${escapeHtml(delivery.reason)}`;
|
|
74
|
+
const tool = prompt === undefined
|
|
75
|
+
? ""
|
|
76
|
+
: `\n${describeTool(prompt.toolName, prompt.inputPreview)}`;
|
|
77
|
+
return `<b>${OUTCOME_TEXT[delivery.decision]}</b>${by}${tool}${reason}`;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* The Approval prompts of one binding, kept in `approvals.json` of the binding's data directory so that an Approval
|
|
81
|
+
* that ends after a restart still edits its prompt.
|
|
82
|
+
*
|
|
83
|
+
* Invariant: every write replaces the file atomically, and writes run one at a time.
|
|
84
|
+
*/
|
|
85
|
+
export class ApprovalPromptStore {
|
|
86
|
+
#path;
|
|
87
|
+
#prompts = new Map();
|
|
88
|
+
#writes = new SerialQueue();
|
|
89
|
+
constructor(dataDir) {
|
|
90
|
+
this.#path = path.join(dataDir, STORE_FILE);
|
|
91
|
+
}
|
|
92
|
+
/** Reads the file. A missing file is an empty store. Rejects if the file is not a valid store. */
|
|
93
|
+
load = async () => {
|
|
94
|
+
let text;
|
|
95
|
+
try {
|
|
96
|
+
text = await readFile(this.#path, "utf-8");
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error instanceof Error &&
|
|
100
|
+
"code" in error &&
|
|
101
|
+
error.code === "ENOENT") {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
const parsed = JSON.parse(text);
|
|
107
|
+
if (!Value.Check(StoreSchema, parsed)) {
|
|
108
|
+
throw new Error(`Invalid Telegram approval store: ${this.#path}`);
|
|
109
|
+
}
|
|
110
|
+
this.#prompts = new Map(Object.entries(parsed));
|
|
111
|
+
};
|
|
112
|
+
/** Returns the prompt of an Approval by its callback token. */
|
|
113
|
+
byToken = (token) => this.#prompts.get(token);
|
|
114
|
+
/** Returns the prompt of an Approval. */
|
|
115
|
+
get = (approvalId) => this.#prompts.get(approvalToken(approvalId));
|
|
116
|
+
/** Stores a prompt. Resolves once the file is written. */
|
|
117
|
+
put = async (prompt) => {
|
|
118
|
+
this.#prompts.set(approvalToken(prompt.approvalId), prompt);
|
|
119
|
+
await this.#persist();
|
|
120
|
+
};
|
|
121
|
+
/** Removes a prompt. Resolves once the file is written. */
|
|
122
|
+
delete = async (approvalId) => {
|
|
123
|
+
if (this.#prompts.delete(approvalToken(approvalId))) {
|
|
124
|
+
await this.#persist();
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
#persist = async () => {
|
|
128
|
+
await this.#writes.run(async () => {
|
|
129
|
+
const temporary = `${this.#path}.tmp`;
|
|
130
|
+
await writeFile(temporary, JSON.stringify(Object.fromEntries(this.#prompts)), "utf-8");
|
|
131
|
+
await rename(temporary, this.#path);
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { open, unlink } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
/** Telegram sends photos larger than this as documents only. */
|
|
5
|
+
const MAX_PHOTO_BYTES = 10_000_000;
|
|
6
|
+
const BYTES_PER_MIB = 1_048_576;
|
|
7
|
+
const PHOTO_TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);
|
|
8
|
+
const UNSAFE_FILENAME = /[^\w.-]+/gu;
|
|
9
|
+
const fromFile = (file, fallbackName, fallbackType) => file === undefined
|
|
10
|
+
? []
|
|
11
|
+
: [
|
|
12
|
+
{
|
|
13
|
+
fileId: file.file_id,
|
|
14
|
+
filename: file.file_name ?? fallbackName,
|
|
15
|
+
mimeType: file.mime_type ?? fallbackType,
|
|
16
|
+
sizeBytes: file.file_size,
|
|
17
|
+
},
|
|
18
|
+
];
|
|
19
|
+
/** Lists the files of a message. A photo contributes its largest size only. */
|
|
20
|
+
export const incomingFiles = (message) => {
|
|
21
|
+
const id = message.message_id;
|
|
22
|
+
const photo = message.photo?.at(-1);
|
|
23
|
+
// Telegram also sets `document` on an animation message, with the same file.
|
|
24
|
+
const document = message.animation === undefined ? message.document : undefined;
|
|
25
|
+
return [
|
|
26
|
+
...(photo === undefined
|
|
27
|
+
? []
|
|
28
|
+
: [
|
|
29
|
+
{
|
|
30
|
+
fileId: photo.file_id,
|
|
31
|
+
filename: `photo-${id}.jpg`,
|
|
32
|
+
mimeType: "image/jpeg",
|
|
33
|
+
sizeBytes: photo.file_size,
|
|
34
|
+
},
|
|
35
|
+
]),
|
|
36
|
+
...fromFile(document, `document-${id}`, "application/octet-stream"),
|
|
37
|
+
...fromFile(message.animation, `animation-${id}.mp4`, "video/mp4"),
|
|
38
|
+
...fromFile(message.audio, `audio-${id}.mp3`, "audio/mpeg"),
|
|
39
|
+
...fromFile(message.voice, `voice-${id}.ogg`, "audio/ogg"),
|
|
40
|
+
...fromFile(message.video, `video-${id}.mp4`, "video/mp4"),
|
|
41
|
+
...fromFile(message.video_note, `video-note-${id}.mp4`, "video/mp4"),
|
|
42
|
+
];
|
|
43
|
+
};
|
|
44
|
+
class AttachmentTooLargeError extends Error {
|
|
45
|
+
name = "AttachmentTooLargeError";
|
|
46
|
+
}
|
|
47
|
+
const writeCapped = async (chunks, filePath, maxBytes) => {
|
|
48
|
+
const handle = await open(filePath, "wx");
|
|
49
|
+
let size = 0;
|
|
50
|
+
try {
|
|
51
|
+
for await (const chunk of chunks) {
|
|
52
|
+
size += chunk.byteLength;
|
|
53
|
+
if (size > maxBytes) {
|
|
54
|
+
throw new AttachmentTooLargeError(`File exceeds ${maxBytes} bytes`);
|
|
55
|
+
}
|
|
56
|
+
await handle.write(chunk);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
await handle.close();
|
|
61
|
+
await unlink(filePath);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
await handle.close();
|
|
65
|
+
return size;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Downloads the files of a message into `stagingDir`, at most `maxBytes` each.
|
|
69
|
+
*
|
|
70
|
+
* A file over the limit, by its declared size or by its downloaded bytes, goes to `tooLarge` and leaves no file
|
|
71
|
+
* behind. Rejects with the client error if a download fails for another reason.
|
|
72
|
+
*/
|
|
73
|
+
export const stageIncomingFiles = async (client, files, stagingDir, maxBytes) => {
|
|
74
|
+
const attachments = [];
|
|
75
|
+
const tooLarge = [];
|
|
76
|
+
for (const file of files) {
|
|
77
|
+
if (file.sizeBytes !== undefined && file.sizeBytes > maxBytes) {
|
|
78
|
+
tooLarge.push(file.filename);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
const safeName = path
|
|
82
|
+
.basename(file.filename)
|
|
83
|
+
.replaceAll(UNSAFE_FILENAME, "_");
|
|
84
|
+
const stagedPath = path.join(stagingDir, `${randomUUID()}-${safeName}`);
|
|
85
|
+
try {
|
|
86
|
+
// oxlint-disable-next-line no-await-in-loop -- Files download one at a time to bound memory and disk use.
|
|
87
|
+
const chunks = await client.downloadFile(file.fileId);
|
|
88
|
+
// oxlint-disable-next-line no-await-in-loop -- See above.
|
|
89
|
+
const sizeBytes = await writeCapped(chunks, stagedPath, maxBytes);
|
|
90
|
+
attachments.push({
|
|
91
|
+
filename: file.filename,
|
|
92
|
+
kind: "file",
|
|
93
|
+
mimeType: file.mimeType,
|
|
94
|
+
path: stagedPath,
|
|
95
|
+
sizeBytes,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (!(error instanceof AttachmentTooLargeError)) {
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
tooLarge.push(file.filename);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { attachments, tooLarge };
|
|
106
|
+
};
|
|
107
|
+
/** The notice for files that exceed the attachment limit, for example `Skipped a.bin: files over 10 MiB are not supported.` */
|
|
108
|
+
export const skippedFilesText = (filenames, maxBytes) => {
|
|
109
|
+
const limit = maxBytes >= BYTES_PER_MIB
|
|
110
|
+
? `${Math.floor(maxBytes / BYTES_PER_MIB)} MiB`
|
|
111
|
+
: `${maxBytes} bytes`;
|
|
112
|
+
return `Skipped ${filenames.join(", ")}: files over ${limit} are not supported.`;
|
|
113
|
+
};
|
|
114
|
+
/** The size of an outbound attachment in bytes. */
|
|
115
|
+
export const attachmentSize = (attachment) => attachment.kind === "bytes"
|
|
116
|
+
? attachment.data.byteLength
|
|
117
|
+
: attachment.sizeBytes;
|
|
118
|
+
/** Converts an outbound attachment to an upload: a photo for small JPEG, PNG, and WebP images, else a document. */
|
|
119
|
+
export const toUpload = (attachment) => {
|
|
120
|
+
const isPhoto = PHOTO_TYPES.has(attachment.mimeType) &&
|
|
121
|
+
attachmentSize(attachment) <= MAX_PHOTO_BYTES;
|
|
122
|
+
const file = attachment.kind === "bytes"
|
|
123
|
+
? { data: attachment.data, filename: attachment.filename }
|
|
124
|
+
: { filename: attachment.filename, path: attachment.path };
|
|
125
|
+
return { file, kind: isPhoto ? "photo" : "document" };
|
|
126
|
+
};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { Value } from "typebox/value";
|
|
3
|
+
import { ApprovalPromptStore } from "./approvals.js";
|
|
4
|
+
import { createAllowlist, parseChatKey } from "./chat-key.js";
|
|
5
|
+
import { TelegramUpdateSchema } from "./client.js";
|
|
6
|
+
import { createDeliverer } from "./delivery.js";
|
|
7
|
+
import { HTTP_BAD_REQUEST, HTTP_OK, HTTP_UNAUTHORIZED } from "./http-status.js";
|
|
8
|
+
import { createUpdateHandler } from "./inbound.js";
|
|
9
|
+
import { LiveRuns } from "./live.js";
|
|
10
|
+
import { RecentSet } from "./recent-set.js";
|
|
11
|
+
import { SerialQueue } from "./serial-queue.js";
|
|
12
|
+
/** The path suffix of the webhook route: `/frontends/<agent>/<binding-id>/updates`. */
|
|
13
|
+
export const WEBHOOK_PATH_SUFFIX = "updates";
|
|
14
|
+
/** The header that carries the secret token of `setWebhook`. */
|
|
15
|
+
export const SECRET_TOKEN_HEADER = "x-telegram-bot-api-secret-token";
|
|
16
|
+
/** How many webhook update IDs a binding remembers to drop duplicates. */
|
|
17
|
+
const DEDUP_CAPACITY = 1000;
|
|
18
|
+
const SECRET_TOKEN_BYTES = 32;
|
|
19
|
+
const tokensMatch = (given, expected) => {
|
|
20
|
+
const left = Buffer.from(given);
|
|
21
|
+
const right = Buffer.from(expected);
|
|
22
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Creates one Telegram Frontend Binding (ADRs 0007 and 0012).
|
|
26
|
+
*
|
|
27
|
+
* Throws if webhook mode is configured while the Webhook Ingress is disabled.
|
|
28
|
+
*/
|
|
29
|
+
export const createTelegramBinding = (config, ctx, client) => {
|
|
30
|
+
const { log, registerWebhookRoute } = ctx;
|
|
31
|
+
if (config.transport.mode === "webhook" &&
|
|
32
|
+
registerWebhookRoute === undefined) {
|
|
33
|
+
throw new Error(`Telegram binding ${ctx.bindingId} uses webhook mode, but the Webhook Ingress is disabled`);
|
|
34
|
+
}
|
|
35
|
+
const isAllowed = createAllowlist(config.allowedChatIds);
|
|
36
|
+
const approvals = new ApprovalPromptStore(ctx.dataDir);
|
|
37
|
+
const live = new LiveRuns(client, log, {
|
|
38
|
+
draftIntervalMs: config.draftIntervalMs,
|
|
39
|
+
streaming: config.streaming,
|
|
40
|
+
});
|
|
41
|
+
const deliver = createDeliverer({
|
|
42
|
+
approvals,
|
|
43
|
+
client,
|
|
44
|
+
isAllowed,
|
|
45
|
+
live,
|
|
46
|
+
log,
|
|
47
|
+
maxAttachmentBytes: ctx.maxAttachmentBytes,
|
|
48
|
+
});
|
|
49
|
+
const handle = createUpdateHandler({
|
|
50
|
+
approvals,
|
|
51
|
+
client,
|
|
52
|
+
config,
|
|
53
|
+
ctx,
|
|
54
|
+
isAllowed,
|
|
55
|
+
});
|
|
56
|
+
const seenUpdates = new RecentSet(DEDUP_CAPACITY);
|
|
57
|
+
const webhookUpdates = new SerialQueue();
|
|
58
|
+
const secretToken = randomBytes(SECRET_TOKEN_BYTES).toString("base64url");
|
|
59
|
+
let sink;
|
|
60
|
+
let bot;
|
|
61
|
+
let polling;
|
|
62
|
+
let route;
|
|
63
|
+
const handleUpdate = async (update) => {
|
|
64
|
+
if (sink !== undefined && bot !== undefined) {
|
|
65
|
+
await handle(update, sink, bot);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const onWebhook = async (request) => {
|
|
69
|
+
const given = request.headers[SECRET_TOKEN_HEADER];
|
|
70
|
+
if (given === undefined || !tokensMatch(given, secretToken)) {
|
|
71
|
+
return { status: HTTP_UNAUTHORIZED };
|
|
72
|
+
}
|
|
73
|
+
let update;
|
|
74
|
+
try {
|
|
75
|
+
update = JSON.parse(Buffer.from(request.body).toString("utf-8"));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return { status: HTTP_BAD_REQUEST };
|
|
79
|
+
}
|
|
80
|
+
if (!Value.Check(TelegramUpdateSchema, update)) {
|
|
81
|
+
return { status: HTTP_BAD_REQUEST };
|
|
82
|
+
}
|
|
83
|
+
if (!seenUpdates.has(update.update_id)) {
|
|
84
|
+
seenUpdates.add(update.update_id);
|
|
85
|
+
await webhookUpdates.run(async () => {
|
|
86
|
+
await handleUpdate(update);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return { status: HTTP_OK };
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
deliver,
|
|
93
|
+
onEvent: (event) => {
|
|
94
|
+
const target = parseChatKey(event.chatId);
|
|
95
|
+
if (target !== undefined && isAllowed(event.chatId)) {
|
|
96
|
+
live.onEvent(event, target);
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
start: async (activeSink) => {
|
|
100
|
+
await approvals.load();
|
|
101
|
+
bot = await client.getMe();
|
|
102
|
+
sink = activeSink;
|
|
103
|
+
try {
|
|
104
|
+
await client.setMyCommands(activeSink.commands.map((command) => ({
|
|
105
|
+
command: command.name,
|
|
106
|
+
description: command.argument === undefined
|
|
107
|
+
? command.description
|
|
108
|
+
: `${command.description} ${command.argument}`,
|
|
109
|
+
})));
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
log.warn("Failed to register Telegram bot commands", {
|
|
113
|
+
error: String(error),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
if (config.transport.mode === "polling" ||
|
|
117
|
+
registerWebhookRoute === undefined) {
|
|
118
|
+
polling = (async () => {
|
|
119
|
+
try {
|
|
120
|
+
await client.startPolling(handleUpdate);
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
log.error("Telegram polling stopped", { error: String(error) });
|
|
124
|
+
}
|
|
125
|
+
})();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
route = registerWebhookRoute(WEBHOOK_PATH_SUFFIX, onWebhook);
|
|
129
|
+
await client.setWebhook(config.transport.url, secretToken);
|
|
130
|
+
log.info("Telegram webhook registered", {
|
|
131
|
+
route: route.path,
|
|
132
|
+
url: config.transport.url,
|
|
133
|
+
});
|
|
134
|
+
},
|
|
135
|
+
stop: async () => {
|
|
136
|
+
route?.unregister();
|
|
137
|
+
route = undefined;
|
|
138
|
+
live.stop();
|
|
139
|
+
await client.stopPolling();
|
|
140
|
+
await polling;
|
|
141
|
+
await webhookUpdates.idle();
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** A Telegram Chat ID or a forum topic key, as `allowedChatIds` accepts it. */
|
|
2
|
+
export const ALLOWLIST_ENTRY = /^-?\d+(?::topic:\d+)?$/u;
|
|
3
|
+
const CHAT_KEY = /^(?<chat>-?\d+)(?::topic:(?<thread>\d+))?$/u;
|
|
4
|
+
/** Returns where a message lives: its chat, plus its forum topic for a forum topic message. */
|
|
5
|
+
export const targetOf = (location) => {
|
|
6
|
+
const thread = location.message_thread_id;
|
|
7
|
+
return location.is_topic_message === true && thread !== undefined
|
|
8
|
+
? { chatId: location.chat.id, threadId: thread }
|
|
9
|
+
: { chatId: location.chat.id };
|
|
10
|
+
};
|
|
11
|
+
/** Returns the Wheatley Chat ID: `<chat_id>`, or `<chat_id>:topic:<thread_id>` for a forum topic message. */
|
|
12
|
+
export const chatKeyOf = (location) => {
|
|
13
|
+
const { chatId, threadId } = targetOf(location);
|
|
14
|
+
return threadId === undefined
|
|
15
|
+
? String(chatId)
|
|
16
|
+
: `${chatId}:topic:${threadId}`;
|
|
17
|
+
};
|
|
18
|
+
/** Parses a Wheatley Chat ID of this Frontend. Returns `undefined` for an ID in another format. */
|
|
19
|
+
export const parseChatKey = (chatKey) => {
|
|
20
|
+
const groups = CHAT_KEY.exec(chatKey)?.groups;
|
|
21
|
+
const chat = groups?.chat;
|
|
22
|
+
if (chat === undefined) {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
const chatId = Number(chat);
|
|
26
|
+
const thread = groups?.thread;
|
|
27
|
+
if (!Number.isSafeInteger(chatId)) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
return thread === undefined
|
|
31
|
+
? { chatId }
|
|
32
|
+
: { chatId, threadId: Number(thread) };
|
|
33
|
+
};
|
|
34
|
+
/** The parent Chat ID of a Chat key: the group of a forum topic, or the key itself. */
|
|
35
|
+
const parentOf = (chatKey) => chatKey.split(":topic:")[0] ?? chatKey;
|
|
36
|
+
/**
|
|
37
|
+
* Creates the allowlist check of a binding. A key passes if `allowedChatIds` lists the key itself or its parent group,
|
|
38
|
+
* so one entry for a forum supergroup allows all of its topics.
|
|
39
|
+
*/
|
|
40
|
+
export const createAllowlist = (allowedChatIds) => {
|
|
41
|
+
const allowed = new Set(allowedChatIds);
|
|
42
|
+
return (chatKey) => allowed.has(chatKey) || allowed.has(parentOf(chatKey));
|
|
43
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
/*
|
|
3
|
+
* The Telegram Bot API subset that the Telegram Frontend uses. `grammy-client.ts` implements it with grammY, and
|
|
4
|
+
* tests replace it with a fake. The update schemas list only the fields that the Frontend reads and accept any other
|
|
5
|
+
* field, so a Telegram API update is assignable to them.
|
|
6
|
+
*/
|
|
7
|
+
const UserSchema = Type.Object({
|
|
8
|
+
first_name: Type.String(),
|
|
9
|
+
id: Type.Number(),
|
|
10
|
+
is_bot: Type.Boolean(),
|
|
11
|
+
last_name: Type.Optional(Type.String()),
|
|
12
|
+
username: Type.Optional(Type.String()),
|
|
13
|
+
});
|
|
14
|
+
const ChatSchema = Type.Object({
|
|
15
|
+
id: Type.Number(),
|
|
16
|
+
is_forum: Type.Optional(Type.Boolean()),
|
|
17
|
+
type: Type.String(),
|
|
18
|
+
});
|
|
19
|
+
const EntitySchema = Type.Object({
|
|
20
|
+
length: Type.Number(),
|
|
21
|
+
offset: Type.Number(),
|
|
22
|
+
type: Type.String(),
|
|
23
|
+
user: Type.Optional(UserSchema),
|
|
24
|
+
});
|
|
25
|
+
const FileSchema = Type.Object({
|
|
26
|
+
file_id: Type.String(),
|
|
27
|
+
file_name: Type.Optional(Type.String()),
|
|
28
|
+
file_size: Type.Optional(Type.Number()),
|
|
29
|
+
mime_type: Type.Optional(Type.String()),
|
|
30
|
+
});
|
|
31
|
+
const PhotoSizeSchema = Type.Object({
|
|
32
|
+
file_id: Type.String(),
|
|
33
|
+
file_size: Type.Optional(Type.Number()),
|
|
34
|
+
height: Type.Number(),
|
|
35
|
+
width: Type.Number(),
|
|
36
|
+
});
|
|
37
|
+
const MessageSchema = Type.Object({
|
|
38
|
+
animation: Type.Optional(FileSchema),
|
|
39
|
+
audio: Type.Optional(FileSchema),
|
|
40
|
+
caption: Type.Optional(Type.String()),
|
|
41
|
+
caption_entities: Type.Optional(Type.Array(EntitySchema)),
|
|
42
|
+
chat: ChatSchema,
|
|
43
|
+
document: Type.Optional(FileSchema),
|
|
44
|
+
entities: Type.Optional(Type.Array(EntitySchema)),
|
|
45
|
+
from: Type.Optional(UserSchema),
|
|
46
|
+
is_topic_message: Type.Optional(Type.Boolean()),
|
|
47
|
+
message_id: Type.Number(),
|
|
48
|
+
message_thread_id: Type.Optional(Type.Number()),
|
|
49
|
+
photo: Type.Optional(Type.Array(PhotoSizeSchema)),
|
|
50
|
+
reply_to_message: Type.Optional(Type.Object({
|
|
51
|
+
from: Type.Optional(UserSchema),
|
|
52
|
+
message_id: Type.Number(),
|
|
53
|
+
})),
|
|
54
|
+
text: Type.Optional(Type.String()),
|
|
55
|
+
video: Type.Optional(FileSchema),
|
|
56
|
+
video_note: Type.Optional(FileSchema),
|
|
57
|
+
voice: Type.Optional(FileSchema),
|
|
58
|
+
});
|
|
59
|
+
const CallbackQuerySchema = Type.Object({
|
|
60
|
+
data: Type.Optional(Type.String()),
|
|
61
|
+
from: UserSchema,
|
|
62
|
+
id: Type.String(),
|
|
63
|
+
message: Type.Optional(Type.Object({
|
|
64
|
+
chat: ChatSchema,
|
|
65
|
+
is_topic_message: Type.Optional(Type.Boolean()),
|
|
66
|
+
message_id: Type.Number(),
|
|
67
|
+
message_thread_id: Type.Optional(Type.Number()),
|
|
68
|
+
})),
|
|
69
|
+
});
|
|
70
|
+
/** The parts of a Telegram `Update` that the Frontend handles. */
|
|
71
|
+
export const TelegramUpdateSchema = Type.Object({
|
|
72
|
+
callback_query: Type.Optional(CallbackQuerySchema),
|
|
73
|
+
message: Type.Optional(MessageSchema),
|
|
74
|
+
update_id: Type.Number(),
|
|
75
|
+
});
|
|
76
|
+
/** A failed Bot API call. */
|
|
77
|
+
export class TelegramApiError extends Error {
|
|
78
|
+
name = "TelegramApiError";
|
|
79
|
+
/** The Bot API `error_code`, for example 403 or 429. Absent for a network error. */
|
|
80
|
+
code;
|
|
81
|
+
/** The Bot API `parameters.retry_after`, in seconds. */
|
|
82
|
+
retryAfterSeconds;
|
|
83
|
+
constructor(message, options = {}) {
|
|
84
|
+
super(message, { cause: options.cause });
|
|
85
|
+
this.code = options.code;
|
|
86
|
+
this.retryAfterSeconds = options.retryAfterSeconds;
|
|
87
|
+
}
|
|
88
|
+
}
|