@wheatley-ai/cli 0.3.0 → 0.4.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/dist/cli/ask.js +8 -4
- package/dist/cli/chat.js +8 -4
- package/dist/cli/daemon.js +45 -0
- package/dist/cli/io.js +1 -0
- package/dist/cli/main.js +145 -163
- package/dist/cli/session.js +59 -3
- package/dist/cli/status.js +4 -4
- package/dist/cli/tui/app.js +14 -2
- package/dist/cli/tui/controller.js +80 -19
- package/dist/cli/tui/markdown.js +229 -104
- package/dist/cli/tui/model-picker.js +76 -0
- package/dist/cli/tui/picker-panel.js +39 -0
- package/dist/core/agent/agent.js +23 -12
- package/dist/core/config/config-store.js +11 -6
- package/dist/core/config/diagnostics.js +116 -0
- package/dist/core/config/secret-store.js +13 -9
- package/dist/core/deployment.js +19 -1
- package/dist/core/markdown-tokens.js +60 -0
- package/dist/core/model-catalog.js +54 -0
- package/dist/core/rpc/deployment-handlers.js +2 -1
- package/dist/core/server/control-server.js +19 -21
- package/dist/core/server/http-server.js +17 -0
- package/dist/core/server/static-files.js +40 -66
- package/dist/dashboard/assets/index-DGa2Ps9u.js +12 -0
- package/dist/dashboard/assets/index-DeERxJOJ.css +2 -0
- package/dist/dashboard/assets/{sheet-presentation-CkgiDsTg.js → sheet-presentation-CZ1dO2kr.js} +1 -1
- package/dist/dashboard/index.html +2 -2
- package/dist/frontends/discord/approvals.js +8 -43
- package/dist/frontends/discord/binding.js +81 -8
- package/dist/frontends/discord/json-file.js +57 -0
- package/dist/frontends/discord/model-picker.js +276 -0
- package/dist/frontends/slack/binding.js +33 -3
- package/dist/frontends/slack/inbound.js +21 -12
- package/dist/frontends/slack/model-picker-blocks.js +147 -0
- package/dist/frontends/slack/outbound.js +27 -2
- package/dist/frontends/slack/schemas.js +9 -2
- package/dist/frontends/telegram/approvals.js +13 -48
- package/dist/frontends/telegram/binding.js +5 -0
- package/dist/frontends/telegram/client.js +7 -0
- package/dist/frontends/telegram/delivery.js +19 -6
- package/dist/frontends/telegram/inbound.js +64 -8
- package/dist/frontends/telegram/markdown.js +120 -83
- package/dist/frontends/telegram/model-picker.js +160 -0
- package/dist/frontends/telegram/token-store.js +73 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +13 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +9 -1
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +2 -2
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +2 -2
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +23 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +1 -1
- package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
- package/dist/ops/cli.js +92 -98
- package/dist/ops/service.js +6 -1
- package/dist/ops/update.js +14 -27
- package/dist/triggers/delivery-codec.js +13 -0
- package/dist/triggers/webhook-ingress.js +89 -82
- package/package.json +9 -2
- package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
- package/dist/dashboard/assets/index-DThc2x_d.js +0 -11
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { escapeMrkdwn } from "./approval-blocks.js";
|
|
2
|
+
/** The `action_id` prefix of the model select menus. The selected option value is `<provider>/<id>`. */
|
|
3
|
+
export const MODEL_ACTION_PREFIX = "wheatley_model:";
|
|
4
|
+
/** Block Kit limits of a `static_select` menu and its option objects. */
|
|
5
|
+
const MAX_OPTIONS_PER_SELECT = 100;
|
|
6
|
+
const MAX_OPTION_TEXT_LENGTH = 75;
|
|
7
|
+
const MAX_OPTION_VALUE_LENGTH = 150;
|
|
8
|
+
const MAX_PLACEHOLDER_LENGTH = 150;
|
|
9
|
+
/** Block Kit limits of an `actions` block and of one message. */
|
|
10
|
+
const MAX_ELEMENTS_PER_ACTIONS = 25;
|
|
11
|
+
const MAX_MESSAGE_BLOCKS = 50;
|
|
12
|
+
const ELLIPSIS = "…";
|
|
13
|
+
/** The value of a model option, which is also the `/model` argument. */
|
|
14
|
+
export const modelValue = (model) => `${model.provider}/${model.id}`;
|
|
15
|
+
/**
|
|
16
|
+
* Shortens `text` to at most `max` UTF-16 code units, with an ellipsis at the end. It never splits a surrogate pair,
|
|
17
|
+
* so the result is within the limit whether Slack counts code units or code points.
|
|
18
|
+
*/
|
|
19
|
+
const truncate = (text, max) => {
|
|
20
|
+
if (text.length <= max) {
|
|
21
|
+
return text;
|
|
22
|
+
}
|
|
23
|
+
let result = "";
|
|
24
|
+
for (const char of text) {
|
|
25
|
+
if (result.length + char.length + ELLIPSIS.length > max) {
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
result += char;
|
|
29
|
+
}
|
|
30
|
+
return `${result}${ELLIPSIS}`;
|
|
31
|
+
};
|
|
32
|
+
const pagesOf = (models) => {
|
|
33
|
+
const pages = [];
|
|
34
|
+
for (let start = 0; start < models.length; start += MAX_OPTIONS_PER_SELECT) {
|
|
35
|
+
pages.push(models.slice(start, start + MAX_OPTIONS_PER_SELECT));
|
|
36
|
+
}
|
|
37
|
+
return pages;
|
|
38
|
+
};
|
|
39
|
+
/** Groups the models by provider, in the order of the picker. */
|
|
40
|
+
const providerMenus = (models) => {
|
|
41
|
+
const byProvider = new Map();
|
|
42
|
+
for (const model of models) {
|
|
43
|
+
const group = byProvider.get(model.provider) ?? [];
|
|
44
|
+
group.push(model);
|
|
45
|
+
byProvider.set(model.provider, group);
|
|
46
|
+
}
|
|
47
|
+
return [...byProvider].map(([provider, group]) => ({
|
|
48
|
+
pages: pagesOf(group),
|
|
49
|
+
provider,
|
|
50
|
+
}));
|
|
51
|
+
};
|
|
52
|
+
const optionOf = (model) => {
|
|
53
|
+
const text = {
|
|
54
|
+
text: truncate(model.name, MAX_OPTION_TEXT_LENGTH),
|
|
55
|
+
type: "plain_text",
|
|
56
|
+
};
|
|
57
|
+
return model.name === model.id
|
|
58
|
+
? { text, value: modelValue(model) }
|
|
59
|
+
: {
|
|
60
|
+
description: {
|
|
61
|
+
text: truncate(model.id, MAX_OPTION_TEXT_LENGTH),
|
|
62
|
+
type: "plain_text",
|
|
63
|
+
},
|
|
64
|
+
text,
|
|
65
|
+
value: modelValue(model),
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
const isCurrent = (model, current) => current !== undefined &&
|
|
69
|
+
model.provider === current.provider &&
|
|
70
|
+
model.id === current.id;
|
|
71
|
+
const placeholderOf = (menus, page) => menus.pages.length === 1
|
|
72
|
+
? truncate(menus.provider, MAX_PLACEHOLDER_LENGTH)
|
|
73
|
+
: truncate(`${menus.provider} (${page + 1}/${menus.pages.length})`, MAX_PLACEHOLDER_LENGTH);
|
|
74
|
+
const actionsBlock = (menus, index, current) => ({
|
|
75
|
+
block_id: `model_picker:${index}`,
|
|
76
|
+
elements: menus.pages.map((page, pageIndex) => {
|
|
77
|
+
const selected = page.find((model) => isCurrent(model, current));
|
|
78
|
+
return {
|
|
79
|
+
action_id: `${MODEL_ACTION_PREFIX}${index}:${pageIndex}`,
|
|
80
|
+
// JSON serialization drops an undefined initial option, which gives a menu with no selection.
|
|
81
|
+
initial_option: selected === undefined ? undefined : optionOf(selected),
|
|
82
|
+
options: page.map(optionOf),
|
|
83
|
+
placeholder: {
|
|
84
|
+
text: placeholderOf(menus, pageIndex),
|
|
85
|
+
type: "plain_text",
|
|
86
|
+
},
|
|
87
|
+
type: "static_select",
|
|
88
|
+
};
|
|
89
|
+
}),
|
|
90
|
+
type: "actions",
|
|
91
|
+
});
|
|
92
|
+
const headerText = (current) => current === undefined
|
|
93
|
+
? "*Choose a model*"
|
|
94
|
+
: `*Choose a model*\nCurrent model: \`${escapeMrkdwn(modelValue(current))}\``;
|
|
95
|
+
/** The fallback text of a model picker, for notifications and clients without Block Kit. */
|
|
96
|
+
export const MODEL_PICKER_TEXT = "Choose a model";
|
|
97
|
+
/**
|
|
98
|
+
* Builds the Block Kit model picker: a section with the current model, then one `actions` block per provider with one
|
|
99
|
+
* `static_select` menu per 100 models. It skips a model whose value is longer than Slack allows and adds a note that
|
|
100
|
+
* names the count. Returns `undefined` if no model fits or the picker needs more blocks or menus than Slack allows,
|
|
101
|
+
* so the caller can post the plain text instead.
|
|
102
|
+
*/
|
|
103
|
+
export const modelPickerBlocks = (picker) => {
|
|
104
|
+
const fitting = picker.models.filter((model) => modelValue(model).length <= MAX_OPTION_VALUE_LENGTH);
|
|
105
|
+
const skipped = picker.models.length - fitting.length;
|
|
106
|
+
const menus = providerMenus(fitting);
|
|
107
|
+
const noteBlocks = skipped === 0 ? 0 : 1;
|
|
108
|
+
const fits = fitting.length > 0 &&
|
|
109
|
+
1 + menus.length + noteBlocks <= MAX_MESSAGE_BLOCKS &&
|
|
110
|
+
menus.every((menu) => menu.pages.length <= MAX_ELEMENTS_PER_ACTIONS);
|
|
111
|
+
if (!fits) {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
const note = skipped === 0
|
|
115
|
+
? []
|
|
116
|
+
: [
|
|
117
|
+
{
|
|
118
|
+
elements: [
|
|
119
|
+
{
|
|
120
|
+
text: `${skipped} ${skipped === 1 ? "model has an ID" : "models have IDs"} too long for this menu. Send \`/model <provider>/<id>\` to choose one.`,
|
|
121
|
+
type: "mrkdwn",
|
|
122
|
+
},
|
|
123
|
+
],
|
|
124
|
+
type: "context",
|
|
125
|
+
},
|
|
126
|
+
];
|
|
127
|
+
return [
|
|
128
|
+
{
|
|
129
|
+
text: { text: headerText(picker.current), type: "mrkdwn" },
|
|
130
|
+
type: "section",
|
|
131
|
+
},
|
|
132
|
+
...menus.map((menu, index) => actionsBlock(menu, index, picker.current)),
|
|
133
|
+
...note,
|
|
134
|
+
];
|
|
135
|
+
};
|
|
136
|
+
/** The fallback text of a picker after a selection. */
|
|
137
|
+
export const modelSelectedText = (model) => `Model selected: ${model}`;
|
|
138
|
+
/** Builds the message that replaces the picker after a selection. It has no menus. */
|
|
139
|
+
export const modelSelectedBlocks = (model, selectedBy) => [
|
|
140
|
+
{
|
|
141
|
+
text: {
|
|
142
|
+
text: `:white_check_mark: *Model selected:* \`${escapeMrkdwn(model)}\` by ${escapeMrkdwn(selectedBy)}`,
|
|
143
|
+
type: "mrkdwn",
|
|
144
|
+
},
|
|
145
|
+
type: "section",
|
|
146
|
+
},
|
|
147
|
+
];
|
|
@@ -4,6 +4,7 @@ import { assertAttachmentSizes, uploadAttachment } from "./attachments.js";
|
|
|
4
4
|
import { dropOldest } from "./bounded.js";
|
|
5
5
|
import { parseChatId } from "./chat-id.js";
|
|
6
6
|
import { MAX_MARKDOWN_LENGTH } from "./live-progress.js";
|
|
7
|
+
import { MODEL_PICKER_TEXT, modelPickerBlocks } from "./model-picker-blocks.js";
|
|
7
8
|
import { postToChat } from "./slack-client.js";
|
|
8
9
|
/** The number of delivered outbox IDs that the binding remembers to drop duplicate deliveries. */
|
|
9
10
|
const MAX_DELIVERED_MESSAGES = 1000;
|
|
@@ -18,6 +19,18 @@ const postChunk = async (web, target, chunk, replaceTs) => {
|
|
|
18
19
|
ts: replaceTs,
|
|
19
20
|
});
|
|
20
21
|
};
|
|
22
|
+
const postBlocks = async (web, target, blocks, replaceTs) => {
|
|
23
|
+
if (replaceTs === undefined) {
|
|
24
|
+
await postToChat(web, target, { blocks, text: MODEL_PICKER_TEXT });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
await web.chat.update({
|
|
28
|
+
blocks,
|
|
29
|
+
channel: target.channel,
|
|
30
|
+
text: MODEL_PICKER_TEXT,
|
|
31
|
+
ts: replaceTs,
|
|
32
|
+
});
|
|
33
|
+
};
|
|
21
34
|
/** Posts the Block Kit prompt once per `approvalId`, and stores its message for the update on resolve. */
|
|
22
35
|
const deliverApprovalRequested = async (deps, delivery) => {
|
|
23
36
|
if (deps.store.approval(delivery.approvalId) !== undefined) {
|
|
@@ -112,7 +125,8 @@ export class SlackOutbound {
|
|
|
112
125
|
}
|
|
113
126
|
};
|
|
114
127
|
/**
|
|
115
|
-
* Posts the Markdown chunks,
|
|
128
|
+
* Posts the Markdown chunks, or the Block Kit model picker instead of the text if the message has one that fits,
|
|
129
|
+
* then uploads the attachments. If the message finishes a streamed Run, the first chunk
|
|
116
130
|
* replaces the draft reply. A retry resumes after the last part that Slack confirmed, and a repeated `messageId`
|
|
117
131
|
* after success does nothing.
|
|
118
132
|
*/
|
|
@@ -124,11 +138,22 @@ export class SlackOutbound {
|
|
|
124
138
|
const attachments = delivery.attachments ?? [];
|
|
125
139
|
assertAttachmentSizes(attachments, this.#deps.maxAttachmentBytes);
|
|
126
140
|
const target = parseChatId(delivery.chatId);
|
|
127
|
-
const
|
|
141
|
+
const pickerBlocks = delivery.modelPicker === undefined
|
|
142
|
+
? undefined
|
|
143
|
+
: modelPickerBlocks(delivery.modelPicker);
|
|
144
|
+
const chunks = delivery.text.trim() === "" || pickerBlocks !== undefined
|
|
128
145
|
? []
|
|
129
146
|
: chunkMarkdown(delivery.text, MAX_MARKDOWN_LENGTH);
|
|
130
147
|
const progress = await this.#messageProgress(delivery);
|
|
148
|
+
const pickerSteps = pickerBlocks === undefined
|
|
149
|
+
? []
|
|
150
|
+
: [
|
|
151
|
+
async () => {
|
|
152
|
+
await postBlocks(web, target, pickerBlocks, progress.draftTs);
|
|
153
|
+
},
|
|
154
|
+
];
|
|
131
155
|
const steps = [
|
|
156
|
+
...pickerSteps,
|
|
132
157
|
...chunks.map((chunk, index) => async () => {
|
|
133
158
|
await postChunk(web, target, chunk, index === 0 ? progress.draftTs : undefined);
|
|
134
159
|
}),
|
|
@@ -69,9 +69,16 @@ export const SlashCommandSchema = Type.Object({
|
|
|
69
69
|
});
|
|
70
70
|
/** A `block_actions` interactivity payload. */
|
|
71
71
|
export const BlockActionsSchema = Type.Object({
|
|
72
|
-
actions: Type.Array(Type.Object({
|
|
72
|
+
actions: Type.Array(Type.Object({
|
|
73
|
+
action_id: NonEmpty,
|
|
74
|
+
selected_option: Type.Optional(Type.Object({ value: NonEmpty })),
|
|
75
|
+
value: Type.Optional(NonEmpty),
|
|
76
|
+
}), { minItems: 1 }),
|
|
73
77
|
channel: Type.Optional(Type.Object({ id: NonEmpty })),
|
|
74
|
-
container: Type.Optional(Type.Object({
|
|
78
|
+
container: Type.Optional(Type.Object({
|
|
79
|
+
channel_id: Type.Optional(NonEmpty),
|
|
80
|
+
message_ts: Type.Optional(NonEmpty),
|
|
81
|
+
})),
|
|
75
82
|
message: Type.Optional(Type.Object({
|
|
76
83
|
thread_ts: Type.Optional(NonEmpty),
|
|
77
84
|
ts: Type.Optional(NonEmpty),
|
|
@@ -1,13 +1,8 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import { readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
-
import path from "node:path";
|
|
4
1
|
import { Type } from "typebox";
|
|
5
|
-
import { Value } from "typebox/value";
|
|
6
2
|
import { escapeHtml } from "./markdown.js";
|
|
7
|
-
import {
|
|
3
|
+
import { shortToken, TokenStore } from "./token-store.js";
|
|
8
4
|
const STORE_FILE = "approvals.json";
|
|
9
5
|
const CALLBACK_PREFIX = "ap";
|
|
10
|
-
const TOKEN_LENGTH = 16;
|
|
11
6
|
const CALLBACK_DATA = /^ap:(?<token>[\w-]+):(?<code>[ocad])$/u;
|
|
12
7
|
/** The four buttons of an Approval prompt, in display order, with their callback codes. */
|
|
13
8
|
const BUTTONS = [
|
|
@@ -32,12 +27,8 @@ const PromptSchema = Type.Object({
|
|
|
32
27
|
telegramChatId: Type.Number(),
|
|
33
28
|
toolName: Type.String(),
|
|
34
29
|
});
|
|
35
|
-
const StoreSchema = Type.Record(Type.String(), PromptSchema);
|
|
36
30
|
/** Returns the short key of an Approval for callback data, which Telegram limits to 64 bytes. */
|
|
37
|
-
export const approvalToken = (approvalId) =>
|
|
38
|
-
.update(approvalId)
|
|
39
|
-
.digest("base64url")
|
|
40
|
-
.slice(0, TOKEN_LENGTH);
|
|
31
|
+
export const approvalToken = (approvalId) => shortToken(approvalId);
|
|
41
32
|
/** The inline keyboard of an Approval prompt: two rows of two buttons. */
|
|
42
33
|
export const approvalKeyboard = (approvalId) => {
|
|
43
34
|
const token = approvalToken(approvalId);
|
|
@@ -79,56 +70,30 @@ export const approvalResolvedText = (delivery, prompt) => {
|
|
|
79
70
|
/**
|
|
80
71
|
* The Approval prompts of one binding, kept in `approvals.json` of the binding's data directory so that an Approval
|
|
81
72
|
* 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
73
|
*/
|
|
85
74
|
export class ApprovalPromptStore {
|
|
86
|
-
#
|
|
87
|
-
#prompts = new Map();
|
|
88
|
-
#writes = new SerialQueue();
|
|
75
|
+
#store;
|
|
89
76
|
constructor(dataDir) {
|
|
90
|
-
this.#
|
|
77
|
+
this.#store = new TokenStore({
|
|
78
|
+
dataDir,
|
|
79
|
+
file: STORE_FILE,
|
|
80
|
+
schema: PromptSchema,
|
|
81
|
+
});
|
|
91
82
|
}
|
|
92
83
|
/** Reads the file. A missing file is an empty store. Rejects if the file is not a valid store. */
|
|
93
84
|
load = async () => {
|
|
94
|
-
|
|
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));
|
|
85
|
+
await this.#store.load();
|
|
111
86
|
};
|
|
112
87
|
/** Returns the prompt of an Approval by its callback token. */
|
|
113
|
-
byToken = (token) => this.#
|
|
88
|
+
byToken = (token) => this.#store.get(token);
|
|
114
89
|
/** Returns the prompt of an Approval. */
|
|
115
|
-
get = (approvalId) => this.#
|
|
90
|
+
get = (approvalId) => this.#store.get(approvalToken(approvalId));
|
|
116
91
|
/** Stores a prompt. Resolves once the file is written. */
|
|
117
92
|
put = async (prompt) => {
|
|
118
|
-
this.#
|
|
119
|
-
await this.#persist();
|
|
93
|
+
await this.#store.put(approvalToken(prompt.approvalId), prompt);
|
|
120
94
|
};
|
|
121
95
|
/** Removes a prompt. Resolves once the file is written. */
|
|
122
96
|
delete = async (approvalId) => {
|
|
123
|
-
|
|
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
|
-
});
|
|
97
|
+
await this.#store.delete(approvalToken(approvalId));
|
|
133
98
|
};
|
|
134
99
|
}
|
|
@@ -7,6 +7,7 @@ import { createDeliverer } from "./delivery.js";
|
|
|
7
7
|
import { HTTP_BAD_REQUEST, HTTP_OK, HTTP_UNAUTHORIZED } from "./http-status.js";
|
|
8
8
|
import { createUpdateHandler } from "./inbound.js";
|
|
9
9
|
import { LiveRuns } from "./live.js";
|
|
10
|
+
import { createPickerStore } from "./model-picker.js";
|
|
10
11
|
import { RecentSet } from "./recent-set.js";
|
|
11
12
|
import { SerialQueue } from "./serial-queue.js";
|
|
12
13
|
/** The path suffix of the webhook route: `/frontends/<agent>/<binding-id>/updates`. */
|
|
@@ -34,6 +35,7 @@ export const createTelegramBinding = (config, ctx, client) => {
|
|
|
34
35
|
}
|
|
35
36
|
const isAllowed = createAllowlist(config.allowedChatIds);
|
|
36
37
|
const approvals = new ApprovalPromptStore(ctx.dataDir);
|
|
38
|
+
const pickers = createPickerStore(ctx.dataDir);
|
|
37
39
|
const live = new LiveRuns(client, log, {
|
|
38
40
|
draftIntervalMs: config.draftIntervalMs,
|
|
39
41
|
streaming: config.streaming,
|
|
@@ -45,6 +47,7 @@ export const createTelegramBinding = (config, ctx, client) => {
|
|
|
45
47
|
live,
|
|
46
48
|
log,
|
|
47
49
|
maxAttachmentBytes: ctx.maxAttachmentBytes,
|
|
50
|
+
pickers,
|
|
48
51
|
});
|
|
49
52
|
const handle = createUpdateHandler({
|
|
50
53
|
approvals,
|
|
@@ -52,6 +55,7 @@ export const createTelegramBinding = (config, ctx, client) => {
|
|
|
52
55
|
config,
|
|
53
56
|
ctx,
|
|
54
57
|
isAllowed,
|
|
58
|
+
pickers,
|
|
55
59
|
});
|
|
56
60
|
const seenUpdates = new RecentSet(DEDUP_CAPACITY);
|
|
57
61
|
const webhookUpdates = new SerialQueue();
|
|
@@ -98,6 +102,7 @@ export const createTelegramBinding = (config, ctx, client) => {
|
|
|
98
102
|
},
|
|
99
103
|
start: async (activeSink) => {
|
|
100
104
|
await approvals.load();
|
|
105
|
+
await pickers.load();
|
|
101
106
|
bot = await client.getMe();
|
|
102
107
|
sink = activeSink;
|
|
103
108
|
try {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
+
import { HTTP_BAD_REQUEST } from "./http-status.js";
|
|
2
3
|
/*
|
|
3
4
|
* The Telegram Bot API subset that the Telegram Frontend uses. `grammy-client.ts` implements it with grammY, and
|
|
4
5
|
* tests replace it with a fake. The update schemas list only the fields that the Frontend reads and accept any other
|
|
@@ -86,3 +87,9 @@ export class TelegramApiError extends Error {
|
|
|
86
87
|
this.retryAfterSeconds = options.retryAfterSeconds;
|
|
87
88
|
}
|
|
88
89
|
}
|
|
90
|
+
/** The Bot API error of an edit to the same text and keyboard. */
|
|
91
|
+
export const NOT_MODIFIED = /message is not modified/iu;
|
|
92
|
+
/** Returns true if `cause` is a Bot API 400 error whose description matches `pattern`. */
|
|
93
|
+
export const isApiError = (cause, pattern) => cause instanceof TelegramApiError &&
|
|
94
|
+
cause.code === HTTP_BAD_REQUEST &&
|
|
95
|
+
pattern.test(cause.message);
|
|
@@ -2,9 +2,10 @@ import { chunkMarkdown, DeliveryError, isDeliveryError, } from "@wheatley-ai/sdk
|
|
|
2
2
|
import { approvalKeyboard, approvalRequestText, approvalResolvedText, } from "./approvals.js";
|
|
3
3
|
import { attachmentSize, skippedFilesText, toUpload } from "./attachments.js";
|
|
4
4
|
import { parseChatKey } from "./chat-key.js";
|
|
5
|
-
import { TelegramApiError } from "./client.js";
|
|
5
|
+
import { isApiError, NOT_MODIFIED, TelegramApiError } from "./client.js";
|
|
6
6
|
import { HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_TOO_MANY_REQUESTS, } from "./http-status.js";
|
|
7
7
|
import { markdownToTelegramHtml } from "./markdown.js";
|
|
8
|
+
import { openingScreen, pickerToken, toStoredPicker } from "./model-picker.js";
|
|
8
9
|
import { RecentSet } from "./recent-set.js";
|
|
9
10
|
/** Chunks stay below the 4096-character message limit of the Bot API. */
|
|
10
11
|
const MAX_CHUNK_LENGTH = 4000;
|
|
@@ -12,7 +13,6 @@ const MS_PER_SECOND = 1000;
|
|
|
12
13
|
/** How many delivered message IDs a binding remembers to drop duplicates. */
|
|
13
14
|
const DEDUP_CAPACITY = 1000;
|
|
14
15
|
const PARSE_ERROR = /can't parse entities/iu;
|
|
15
|
-
const NOT_MODIFIED = /message is not modified/iu;
|
|
16
16
|
/** Converts a client error to the `DeliveryError` that the outbox expects. */
|
|
17
17
|
const toDeliveryError = (cause) => {
|
|
18
18
|
if (isDeliveryError(cause)) {
|
|
@@ -39,17 +39,17 @@ const toDeliveryError = (cause) => {
|
|
|
39
39
|
});
|
|
40
40
|
};
|
|
41
41
|
const isBadRequest = (cause) => cause instanceof TelegramApiError && cause.code === HTTP_BAD_REQUEST;
|
|
42
|
-
const isApiError = (cause, pattern) => isBadRequest(cause) && pattern.test(cause.message);
|
|
43
42
|
/**
|
|
44
43
|
* Creates the `FrontendBinding.deliver` of a Telegram binding.
|
|
45
44
|
*
|
|
46
45
|
* A `message` delivery sends its text chunks in order, then its attachments, then one notice that names the
|
|
47
|
-
* attachments over `maxAttachmentBytes`. A
|
|
46
|
+
* attachments over `maxAttachmentBytes`. A `message` with a `modelPicker` that lists models sends one picker message
|
|
47
|
+
* with an inline keyboard instead of its text. A retry resumes after the parts that Telegram already confirmed, and a
|
|
48
48
|
* delivery that already succeeded is dropped. Rejects with a `DeliveryError`: permanent for an invalid or unlisted
|
|
49
49
|
* Chat and for Bot API codes 400 and 403, retryable for other failures.
|
|
50
50
|
*/
|
|
51
51
|
export const createDeliverer = (deps) => {
|
|
52
|
-
const { approvals, client, isAllowed, live, log, maxAttachmentBytes } = deps;
|
|
52
|
+
const { approvals, client, isAllowed, live, log, maxAttachmentBytes, pickers, } = deps;
|
|
53
53
|
const progress = new Map();
|
|
54
54
|
const delivered = new RecentSet(DEDUP_CAPACITY);
|
|
55
55
|
const sendFormatted = async (target, markdown) => {
|
|
@@ -149,6 +149,16 @@ export const createDeliverer = (deps) => {
|
|
|
149
149
|
progress.delete(delivery.messageId);
|
|
150
150
|
delivered.add(delivery.messageId);
|
|
151
151
|
};
|
|
152
|
+
const deliverModelPicker = async (delivery, picker, target) => {
|
|
153
|
+
const token = pickerToken(delivery.messageId);
|
|
154
|
+
if (pickers.get(token) === undefined) {
|
|
155
|
+
const stored = toStoredPicker(delivery.chatId, picker);
|
|
156
|
+
const { keyboard, text } = openingScreen(token, stored);
|
|
157
|
+
await client.sendMessage(target, text, { keyboard, parseMode: "HTML" });
|
|
158
|
+
await pickers.put(token, stored);
|
|
159
|
+
}
|
|
160
|
+
delivered.add(delivery.messageId);
|
|
161
|
+
};
|
|
152
162
|
const deliverApprovalRequest = async (delivery, target) => {
|
|
153
163
|
if (approvals.get(delivery.approvalId) !== undefined) {
|
|
154
164
|
return;
|
|
@@ -192,7 +202,10 @@ export const createDeliverer = (deps) => {
|
|
|
192
202
|
try {
|
|
193
203
|
switch (delivery.kind) {
|
|
194
204
|
case "message": {
|
|
195
|
-
|
|
205
|
+
const picker = delivery.modelPicker;
|
|
206
|
+
await (picker === undefined || picker.models.length === 0
|
|
207
|
+
? deliverMessage(delivery, target)
|
|
208
|
+
: deliverModelPicker(delivery, picker, target));
|
|
196
209
|
break;
|
|
197
210
|
}
|
|
198
211
|
case "approval_requested": {
|
|
@@ -3,8 +3,11 @@ import { parseCommandText } from "@wheatley-ai/sdk";
|
|
|
3
3
|
import { parseApprovalCallback } from "./approvals.js";
|
|
4
4
|
import { incomingFiles, skippedFilesText, stageIncomingFiles, } from "./attachments.js";
|
|
5
5
|
import { chatKeyOf, targetOf } from "./chat-key.js";
|
|
6
|
+
import { isApiError, NOT_MODIFIED } from "./client.js";
|
|
7
|
+
import { parsePickerCallback, pickerScreen, pickerSelectedText, } from "./model-picker.js";
|
|
6
8
|
const COMMAND_SUFFIX = /^\/[a-z]+@(?<bot>\w+)/iu;
|
|
7
9
|
const GROUP_TYPES = new Set(["group", "supergroup"]);
|
|
10
|
+
const STALE_PICKER_TEXT = "This model picker has expired. Send /model again.";
|
|
8
11
|
const displayName = (user) => {
|
|
9
12
|
if (user === undefined) {
|
|
10
13
|
return undefined;
|
|
@@ -44,13 +47,13 @@ const isCommandForOtherBot = (text, me) => {
|
|
|
44
47
|
commandBot.toLowerCase() !== me.username?.toLowerCase());
|
|
45
48
|
};
|
|
46
49
|
/**
|
|
47
|
-
* Creates the inbound side of a Telegram binding: messages, commands, and Approval button presses.
|
|
50
|
+
* Creates the inbound side of a Telegram binding: messages, commands, and Approval and model picker button presses.
|
|
48
51
|
*
|
|
49
52
|
* It drops updates from Chats outside `allowedChatIds` with an `info` log, and it logs any other failure at `error`
|
|
50
53
|
* instead of rejecting, so one bad update does not stop the updates after it.
|
|
51
54
|
*/
|
|
52
55
|
export const createUpdateHandler = (deps) => {
|
|
53
|
-
const { approvals, client, config, ctx, isAllowed } = deps;
|
|
56
|
+
const { approvals, client, config, ctx, isAllowed, pickers } = deps;
|
|
54
57
|
const { log } = ctx;
|
|
55
58
|
/** Stages the files of a message and tells the Chat about files over the limit. */
|
|
56
59
|
const stageFiles = async (message) => {
|
|
@@ -104,15 +107,55 @@ export const createUpdateHandler = (deps) => {
|
|
|
104
107
|
text: body,
|
|
105
108
|
});
|
|
106
109
|
};
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
110
|
+
/** Edits a picker message. Ignores a repeated press that leaves the message as it is. */
|
|
111
|
+
const editPicker = async (query, text, keyboard) => {
|
|
112
|
+
if (query.message === undefined) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
await client.editMessageText(query.message.chat.id, query.message.message_id, text, { keyboard, parseMode: "HTML" });
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (!isApiError(error, NOT_MODIFIED)) {
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const handlePickerPress = async (query, press, chatId, sink) => {
|
|
125
|
+
const { action, token } = press;
|
|
126
|
+
const picker = pickers.get(token);
|
|
127
|
+
if (picker === undefined || picker.chatId !== chatId) {
|
|
128
|
+
await client.answerCallbackQuery(query.id, STALE_PICKER_TEXT);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (action.kind === "show") {
|
|
132
|
+
const screen = pickerScreen(token, picker, action.view);
|
|
133
|
+
if (screen === undefined) {
|
|
134
|
+
await client.answerCallbackQuery(query.id, STALE_PICKER_TEXT);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
113
137
|
await client.answerCallbackQuery(query.id);
|
|
138
|
+
await editPicker(query, screen.text, screen.keyboard);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const model = picker.models[action.model];
|
|
142
|
+
if (model === undefined) {
|
|
143
|
+
await client.answerCallbackQuery(query.id, STALE_PICKER_TEXT);
|
|
114
144
|
return;
|
|
115
145
|
}
|
|
146
|
+
// Removing the picker first turns a second press into a stale press instead of a second command.
|
|
147
|
+
await pickers.delete(token);
|
|
148
|
+
await sink.command({
|
|
149
|
+
args: `${model.provider}/${model.id}`,
|
|
150
|
+
chatId: picker.chatId,
|
|
151
|
+
name: "model",
|
|
152
|
+
senderDisplayName: displayName(query.from),
|
|
153
|
+
});
|
|
154
|
+
await client.answerCallbackQuery(query.id);
|
|
155
|
+
await editPicker(query, pickerSelectedText(model), []);
|
|
156
|
+
};
|
|
157
|
+
const handleApprovalPress = async (query, chatId, sink) => {
|
|
158
|
+
const parsed = parseApprovalCallback(query.data ?? "");
|
|
116
159
|
const prompt = parsed === undefined ? undefined : approvals.byToken(parsed.token);
|
|
117
160
|
if (parsed === undefined ||
|
|
118
161
|
prompt === undefined ||
|
|
@@ -130,6 +173,19 @@ export const createUpdateHandler = (deps) => {
|
|
|
130
173
|
});
|
|
131
174
|
await client.answerCallbackQuery(query.id, won ? "Decision recorded." : "This approval has already ended.");
|
|
132
175
|
};
|
|
176
|
+
const handleCallback = async (query, sink) => {
|
|
177
|
+
const { message } = query;
|
|
178
|
+
const chatId = message === undefined ? undefined : chatKeyOf(message);
|
|
179
|
+
if (chatId !== undefined && !isAllowed(chatId)) {
|
|
180
|
+
log.info("Dropped a button press from a Telegram chat that is not in allowedChatIds", { chatId });
|
|
181
|
+
await client.answerCallbackQuery(query.id);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const press = parsePickerCallback(query.data ?? "");
|
|
185
|
+
await (press === undefined
|
|
186
|
+
? handleApprovalPress(query, chatId, sink)
|
|
187
|
+
: handlePickerPress(query, press, chatId, sink));
|
|
188
|
+
};
|
|
133
189
|
return async (update, sink, me) => {
|
|
134
190
|
try {
|
|
135
191
|
if (update.message !== undefined) {
|