@wheatley-ai/cli 0.2.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/README.md +37 -3
- 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 -157
- 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-DMljN0LW.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 +127 -114
- package/dist/ops/command-runner.js +1 -0
- package/dist/ops/install-method.js +189 -0
- package/dist/ops/registry.js +35 -0
- package/dist/ops/service.js +6 -1
- package/dist/ops/update.js +109 -88
- package/dist/triggers/delivery-codec.js +13 -0
- package/dist/triggers/webhook-ingress.js +89 -82
- package/package.json +11 -4
- package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
- package/dist/dashboard/assets/index-DXzGGAxQ.js +0 -11
|
@@ -5,6 +5,7 @@ import { MAX_FILES_PER_MESSAGE, stageInboundFiles, toUploadPayloads, } from "./a
|
|
|
5
5
|
import { loadDiscordRuntime, NO_MENTIONS } from "./discord-runtime.js";
|
|
6
6
|
import { discordErrorCode, errorText, toDeliveryError, UNKNOWN_MESSAGE_CODE, } from "./errors.js";
|
|
7
7
|
import { DISCORD_MESSAGE_MAX_LENGTH, LiveRuns } from "./live-runs.js";
|
|
8
|
+
import { initialView, modelRefText, parsePickerCustomId, pickerMessage, pickerStep, PickerStore, pickerToken, STALE_PICKER_TEXT, } from "./model-picker.js";
|
|
8
9
|
import { RecentIds } from "./recent-ids.js";
|
|
9
10
|
/** How many outbound `messageId` values the binding remembers to drop duplicate deliveries. */
|
|
10
11
|
const RECENT_DELIVERY_LIMIT = 1000;
|
|
@@ -96,6 +97,7 @@ export class DiscordBinding {
|
|
|
96
97
|
#loadDiscord;
|
|
97
98
|
#allowed;
|
|
98
99
|
#prompts;
|
|
100
|
+
#pickers;
|
|
99
101
|
#delivered = new RecentIds(RECENT_DELIVERY_LIMIT);
|
|
100
102
|
#live;
|
|
101
103
|
#client;
|
|
@@ -108,6 +110,7 @@ export class DiscordBinding {
|
|
|
108
110
|
this.#loadDiscord = options.loadDiscord ?? loadDiscordRuntime;
|
|
109
111
|
this.#allowed = new Set(config.allowedChatIds);
|
|
110
112
|
this.#prompts = new PromptStore(ctx.dataDir);
|
|
113
|
+
this.#pickers = new PickerStore(ctx.dataDir);
|
|
111
114
|
this.#live = new LiveRuns({
|
|
112
115
|
editIntervalMs: config.editIntervalMs,
|
|
113
116
|
log: ctx.log,
|
|
@@ -119,11 +122,12 @@ export class DiscordBinding {
|
|
|
119
122
|
* Loads `discord.js`, logs in, waits for the Gateway `clientReady` event, and registers the built-in commands as
|
|
120
123
|
* Slash Commands: in each `commandGuildIds` guild, or globally if the list is empty.
|
|
121
124
|
*
|
|
122
|
-
* Rejects if the stored Approval prompts cannot load or the login fails. A failed command
|
|
123
|
-
* error, because text commands still work.
|
|
125
|
+
* Rejects if the stored Approval prompts or model pickers cannot load or the login fails. A failed command
|
|
126
|
+
* registration only logs an error, because text commands still work.
|
|
124
127
|
*/
|
|
125
128
|
start = async (sink) => {
|
|
126
129
|
await this.#prompts.load();
|
|
130
|
+
await this.#pickers.load();
|
|
127
131
|
const discord = await this.#loadDiscord();
|
|
128
132
|
const client = discord.createClient({
|
|
129
133
|
intents: [
|
|
@@ -173,7 +177,8 @@ export class DiscordBinding {
|
|
|
173
177
|
/**
|
|
174
178
|
* Delivers durable outbound work. Drops a `messageId` that this binding delivered before.
|
|
175
179
|
*
|
|
176
|
-
* A `message` with a `runId` replaces the draft message of that Run with its first chunk.
|
|
180
|
+
* A `message` with a `runId` replaces the draft message of that Run with its first chunk. A `message` with a
|
|
181
|
+
* `modelPicker` that lists models becomes one picker message with select menus instead of its text. Rejects with a
|
|
177
182
|
* `DeliveryError`: `permanent` for an unknown, non-text, or not-allowed Chat, a file over the limit, or a Discord
|
|
178
183
|
* 4xx answer such as Missing Access; `retryable` before `start` finishes and for rate limits, 5xx, and network
|
|
179
184
|
* errors.
|
|
@@ -324,9 +329,11 @@ export class DiscordBinding {
|
|
|
324
329
|
if (connection === undefined) {
|
|
325
330
|
return;
|
|
326
331
|
}
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
332
|
+
const isComponent = interaction.isButton() || interaction.isStringSelectMenu();
|
|
333
|
+
const isOwnComponent = isComponent &&
|
|
334
|
+
(parseApprovalCustomId(interaction.customId) !== undefined ||
|
|
335
|
+
parsePickerCustomId(interaction.customId) !== undefined);
|
|
336
|
+
const isOwn = interaction.isChatInputCommand() || isOwnComponent;
|
|
330
337
|
if (!isOwn) {
|
|
331
338
|
return;
|
|
332
339
|
}
|
|
@@ -341,10 +348,56 @@ export class DiscordBinding {
|
|
|
341
348
|
if (interaction.isChatInputCommand()) {
|
|
342
349
|
await handleSlashCommand(interaction, channel.id, connection);
|
|
343
350
|
}
|
|
351
|
+
else if (interaction.isStringSelectMenu()) {
|
|
352
|
+
await this.#onModelPicker(interaction, interaction.values, channel.id, connection);
|
|
353
|
+
}
|
|
344
354
|
else if (interaction.isButton()) {
|
|
345
|
-
await
|
|
355
|
+
await (parseApprovalCustomId(interaction.customId) === undefined
|
|
356
|
+
? this.#onModelPicker(interaction, [], channel.id, connection)
|
|
357
|
+
: this.#onApprovalButton(interaction, channel.id, connection));
|
|
346
358
|
}
|
|
347
359
|
}
|
|
360
|
+
/** Shows another picker page, or switches the Chat to the chosen model and removes the picker components. */
|
|
361
|
+
async #onModelPicker(interaction, values, chatId, { discord, sink }) {
|
|
362
|
+
const press = parsePickerCustomId(interaction.customId);
|
|
363
|
+
const state = press === undefined ? undefined : this.#pickers.get(press.token);
|
|
364
|
+
const step = press !== undefined && state?.chatId === chatId
|
|
365
|
+
? pickerStep(state, press, values)
|
|
366
|
+
: undefined;
|
|
367
|
+
if (state === undefined || step === undefined) {
|
|
368
|
+
await interaction.reply({
|
|
369
|
+
content: STALE_PICKER_TEXT,
|
|
370
|
+
flags: discord.MessageFlags.Ephemeral,
|
|
371
|
+
});
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
if (step.kind === "show") {
|
|
375
|
+
await interaction.update(pickerMessage(discord, state, step.view));
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
await interaction.deferUpdate();
|
|
379
|
+
const args = modelRefText(step.model);
|
|
380
|
+
try {
|
|
381
|
+
await sink.command({
|
|
382
|
+
args,
|
|
383
|
+
chatId,
|
|
384
|
+
name: "model",
|
|
385
|
+
senderDisplayName: displayName(interaction.user.displayName),
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
await interaction.followUp({
|
|
390
|
+
content: "Wheatley could not run `/model`.",
|
|
391
|
+
flags: discord.MessageFlags.Ephemeral,
|
|
392
|
+
});
|
|
393
|
+
throw error;
|
|
394
|
+
}
|
|
395
|
+
await interaction.editReply({
|
|
396
|
+
components: [],
|
|
397
|
+
content: `Selected \`${args}\`.`,
|
|
398
|
+
});
|
|
399
|
+
await this.#pickers.delete(state.token);
|
|
400
|
+
}
|
|
348
401
|
async #onApprovalButton(interaction, chatId, { discord, sink }) {
|
|
349
402
|
const press = parseApprovalCustomId(interaction.customId);
|
|
350
403
|
if (press === undefined) {
|
|
@@ -403,7 +456,10 @@ export class DiscordBinding {
|
|
|
403
456
|
async #deliver(delivery) {
|
|
404
457
|
switch (delivery.kind) {
|
|
405
458
|
case "message": {
|
|
406
|
-
|
|
459
|
+
const picker = delivery.modelPicker;
|
|
460
|
+
await (picker !== undefined && picker.models.length > 0
|
|
461
|
+
? this.#deliverModelPicker(delivery, picker)
|
|
462
|
+
: this.#deliverMessage(delivery));
|
|
407
463
|
break;
|
|
408
464
|
}
|
|
409
465
|
case "approval_requested": {
|
|
@@ -441,6 +497,23 @@ export class DiscordBinding {
|
|
|
441
497
|
await channel.send(payload);
|
|
442
498
|
}
|
|
443
499
|
}
|
|
500
|
+
/** Sends one picker message per `messageId`, also across restarts, because the token derives from it. */
|
|
501
|
+
async #deliverModelPicker(delivery, picker) {
|
|
502
|
+
const { discord } = this.#requireConnection();
|
|
503
|
+
const channel = await this.#resolveChannel(delivery.chatId);
|
|
504
|
+
const token = pickerToken(delivery.messageId);
|
|
505
|
+
if (this.#pickers.get(token) !== undefined) {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const state = {
|
|
509
|
+
chatId: channel.id,
|
|
510
|
+
current: picker.current,
|
|
511
|
+
models: picker.models,
|
|
512
|
+
token,
|
|
513
|
+
};
|
|
514
|
+
await channel.send(pickerMessage(discord, state, initialView(state)));
|
|
515
|
+
await this.#pickers.put(state);
|
|
516
|
+
}
|
|
444
517
|
async #deliverApprovalRequest(delivery) {
|
|
445
518
|
const { discord } = this.#requireConnection();
|
|
446
519
|
const channel = await this.#resolveChannel(delivery.chatId);
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
const isMissingFile = (cause) => cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
|
4
|
+
/** One JSON file in the binding's `dataDir`. Writes replace the whole file atomically, one at a time. */
|
|
5
|
+
export class JsonFile {
|
|
6
|
+
#path;
|
|
7
|
+
#dataDir;
|
|
8
|
+
#isValid;
|
|
9
|
+
#writes = Promise.resolve();
|
|
10
|
+
constructor(dataDir, name, isValid) {
|
|
11
|
+
this.#dataDir = dataDir;
|
|
12
|
+
this.#path = path.join(dataDir, name);
|
|
13
|
+
this.#isValid = isValid;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Reads and parses the file. Resolves `undefined` for a missing file. Rejects for an unreadable file, invalid JSON,
|
|
17
|
+
* or JSON that `isValid` rejects.
|
|
18
|
+
*/
|
|
19
|
+
async read() {
|
|
20
|
+
let text;
|
|
21
|
+
try {
|
|
22
|
+
text = await readFile(this.#path, "utf-8");
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (isMissingFile(error)) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
const parsed = JSON.parse(text);
|
|
31
|
+
if (!this.#isValid(parsed)) {
|
|
32
|
+
throw new Error(`The file ${this.#path} has an unknown format`);
|
|
33
|
+
}
|
|
34
|
+
return parsed;
|
|
35
|
+
}
|
|
36
|
+
/** Replaces the file with `value` and resolves once the file holds it. */
|
|
37
|
+
async write(value) {
|
|
38
|
+
const snapshot = JSON.stringify(value);
|
|
39
|
+
const previous = this.#writes;
|
|
40
|
+
const write = async () => {
|
|
41
|
+
try {
|
|
42
|
+
await previous;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// The earlier write already rejected to its own caller. This write replaces the whole file anyway.
|
|
46
|
+
}
|
|
47
|
+
await mkdir(this.#dataDir, { recursive: true });
|
|
48
|
+
const temporary = `${this.#path}.tmp`;
|
|
49
|
+
await writeFile(temporary, snapshot);
|
|
50
|
+
await rename(temporary, this.#path);
|
|
51
|
+
};
|
|
52
|
+
// Writes run one at a time, so a slow earlier write cannot replace a newer snapshot.
|
|
53
|
+
const next = write();
|
|
54
|
+
this.#writes = next;
|
|
55
|
+
await next;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { Value } from "typebox/value";
|
|
4
|
+
import { NO_MENTIONS } from "./discord-runtime.js";
|
|
5
|
+
import { JsonFile } from "./json-file.js";
|
|
6
|
+
/** Discord limits a string select to this many options. */
|
|
7
|
+
const MAX_SELECT_OPTIONS = 25;
|
|
8
|
+
/** Discord limits an option label and description to this many characters. */
|
|
9
|
+
const MAX_OPTION_TEXT = 100;
|
|
10
|
+
/** Discord limits a select placeholder to this many characters. */
|
|
11
|
+
const MAX_PLACEHOLDER = 150;
|
|
12
|
+
const CUSTOM_ID_PREFIX = "wheatley-model";
|
|
13
|
+
const TOKEN_LENGTH = 16;
|
|
14
|
+
/** The store keeps the newest pickers only. An older picker answers as no longer available. */
|
|
15
|
+
const MAX_STORED_PICKERS = 20;
|
|
16
|
+
const STORE_FILE = "model-pickers.json";
|
|
17
|
+
const STORE_VERSION = 1;
|
|
18
|
+
const DIGITS = /^\d+$/u;
|
|
19
|
+
/**
|
|
20
|
+
* The text that tells the Sender that a picker is gone: unknown token, a token of another Chat, a finished choice,
|
|
21
|
+
* or an index that the stored models do not have.
|
|
22
|
+
*/
|
|
23
|
+
export const STALE_PICKER_TEXT = "This model picker is no longer available. Run `/model` again.";
|
|
24
|
+
const ModelRefSchema = Type.Object({
|
|
25
|
+
id: Type.String(),
|
|
26
|
+
provider: Type.String(),
|
|
27
|
+
});
|
|
28
|
+
const PickerStateSchema = Type.Object({
|
|
29
|
+
chatId: Type.String(),
|
|
30
|
+
current: Type.Optional(ModelRefSchema),
|
|
31
|
+
models: Type.Array(Type.Object({
|
|
32
|
+
id: Type.String(),
|
|
33
|
+
name: Type.String(),
|
|
34
|
+
provider: Type.String(),
|
|
35
|
+
})),
|
|
36
|
+
token: Type.String(),
|
|
37
|
+
});
|
|
38
|
+
const StoreFileSchema = Type.Object({
|
|
39
|
+
pickers: Type.Array(PickerStateSchema),
|
|
40
|
+
version: Type.Literal(STORE_VERSION),
|
|
41
|
+
});
|
|
42
|
+
const isStoreFile = (value) => Value.Check(StoreFileSchema, value);
|
|
43
|
+
/** The picker token of a delivery. The same `messageId` always gives the same token, so a retry finds its picker. */
|
|
44
|
+
export const pickerToken = (messageId) => createHash("sha256")
|
|
45
|
+
.update(messageId)
|
|
46
|
+
.digest("base64url")
|
|
47
|
+
.slice(0, TOKEN_LENGTH);
|
|
48
|
+
export const modelRefText = (model) => `${model.provider}/${model.id}`;
|
|
49
|
+
const isSameModel = (left, right) => left?.provider === right.provider && left.id === right.id;
|
|
50
|
+
const truncate = (text, max) => text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
51
|
+
const pageCount = (items) => Math.max(1, Math.ceil(items / MAX_SELECT_OPTIONS));
|
|
52
|
+
const pageOf = (position) => Math.floor(position / MAX_SELECT_OPTIONS);
|
|
53
|
+
const pageItems = (items, page) => items.slice(page * MAX_SELECT_OPTIONS, (page + 1) * MAX_SELECT_OPTIONS);
|
|
54
|
+
const providersOf = (state) => [
|
|
55
|
+
...new Set(state.models.map((model) => model.provider)),
|
|
56
|
+
];
|
|
57
|
+
const modelsOf = (state, provider) => state.models.flatMap((model, index) => model.provider === provider ? [{ index, model }] : []);
|
|
58
|
+
const isValidView = (state, view) => {
|
|
59
|
+
const providers = providersOf(state);
|
|
60
|
+
if (view.kind === "providers") {
|
|
61
|
+
return view.page < pageCount(providers.length);
|
|
62
|
+
}
|
|
63
|
+
const models = modelsOf(state, providers[view.provider]);
|
|
64
|
+
return models.length > 0 && view.page < pageCount(models.length);
|
|
65
|
+
};
|
|
66
|
+
/** The first view: the page of the current model, the models of the only provider, or the first provider page. */
|
|
67
|
+
export const initialView = (state) => {
|
|
68
|
+
const providers = providersOf(state);
|
|
69
|
+
const { current } = state;
|
|
70
|
+
const provider = providers.indexOf(current?.provider ?? "");
|
|
71
|
+
const position = modelsOf(state, current?.provider).findIndex(({ model }) => isSameModel(current, model));
|
|
72
|
+
if (provider !== -1 && position !== -1) {
|
|
73
|
+
return { kind: "models", page: pageOf(position), provider };
|
|
74
|
+
}
|
|
75
|
+
return providers.length === 1
|
|
76
|
+
? { kind: "models", page: 0, provider: 0 }
|
|
77
|
+
: { kind: "providers", page: 0 };
|
|
78
|
+
};
|
|
79
|
+
const customId = (token, action) => {
|
|
80
|
+
const prefix = `${CUSTOM_ID_PREFIX}:${token}`;
|
|
81
|
+
if (action.kind === "choose_provider") {
|
|
82
|
+
return `${prefix}:p`;
|
|
83
|
+
}
|
|
84
|
+
if (action.kind === "choose_model") {
|
|
85
|
+
return `${prefix}:m`;
|
|
86
|
+
}
|
|
87
|
+
const { view } = action;
|
|
88
|
+
return view.kind === "providers"
|
|
89
|
+
? `${prefix}:v:p:${view.page}`
|
|
90
|
+
: `${prefix}:v:m:${view.provider}:${view.page}`;
|
|
91
|
+
};
|
|
92
|
+
const parseIndex = (text) => text !== undefined && DIGITS.test(text) ? Number(text) : undefined;
|
|
93
|
+
const parseView = (parts) => {
|
|
94
|
+
const [kind, first, second, ...extra] = parts;
|
|
95
|
+
const firstIndex = parseIndex(first);
|
|
96
|
+
if (extra.length > 0 || firstIndex === undefined) {
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
if (kind === "p" && second === undefined) {
|
|
100
|
+
return { kind: "providers", page: firstIndex };
|
|
101
|
+
}
|
|
102
|
+
const page = parseIndex(second);
|
|
103
|
+
return kind === "m" && page !== undefined
|
|
104
|
+
? { kind: "models", page, provider: firstIndex }
|
|
105
|
+
: undefined;
|
|
106
|
+
};
|
|
107
|
+
const parseAction = (parts) => {
|
|
108
|
+
const [code, ...rest] = parts;
|
|
109
|
+
if (code === "p" && rest.length === 0) {
|
|
110
|
+
return { kind: "choose_provider" };
|
|
111
|
+
}
|
|
112
|
+
if (code === "m" && rest.length === 0) {
|
|
113
|
+
return { kind: "choose_model" };
|
|
114
|
+
}
|
|
115
|
+
const view = code === "v" ? parseView(rest) : undefined;
|
|
116
|
+
return view === undefined ? undefined : { kind: "show", view };
|
|
117
|
+
};
|
|
118
|
+
/** Parses the `custom_id` of a picker component, or returns `undefined` for other components. */
|
|
119
|
+
export const parsePickerCustomId = (value) => {
|
|
120
|
+
const [prefix, token, ...rest] = value.split(":");
|
|
121
|
+
const action = parseAction(rest);
|
|
122
|
+
if (prefix !== CUSTOM_ID_PREFIX ||
|
|
123
|
+
token === undefined ||
|
|
124
|
+
token === "" ||
|
|
125
|
+
action === undefined) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
return { action, token };
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Resolves a picker interaction against its state. `values` are the chosen option values of a select, empty for a
|
|
132
|
+
* button. Returns `undefined` if the interaction does not fit the state, for example an index past the models.
|
|
133
|
+
*/
|
|
134
|
+
export const pickerStep = (state, press, values) => {
|
|
135
|
+
const { action } = press;
|
|
136
|
+
if (action.kind === "show") {
|
|
137
|
+
return isValidView(state, action.view)
|
|
138
|
+
? { kind: "show", view: action.view }
|
|
139
|
+
: undefined;
|
|
140
|
+
}
|
|
141
|
+
const index = parseIndex(values[0]);
|
|
142
|
+
if (index === undefined) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
if (action.kind === "choose_provider") {
|
|
146
|
+
return index < providersOf(state).length
|
|
147
|
+
? { kind: "show", view: { kind: "models", page: 0, provider: index } }
|
|
148
|
+
: undefined;
|
|
149
|
+
}
|
|
150
|
+
const model = state.models[index];
|
|
151
|
+
return model === undefined ? undefined : { kind: "choose", model };
|
|
152
|
+
};
|
|
153
|
+
const placeholder = (noun, page, pages) => truncate(pages === 1
|
|
154
|
+
? `Choose a ${noun}`
|
|
155
|
+
: `Choose a ${noun} (page ${page + 1} of ${pages})`, MAX_PLACEHOLDER);
|
|
156
|
+
const selectRow = (discord, select) => ({
|
|
157
|
+
components: [{ ...select, type: discord.ComponentType.StringSelect }],
|
|
158
|
+
type: discord.ComponentType.ActionRow,
|
|
159
|
+
});
|
|
160
|
+
/** The Previous and Next buttons of one select, or none if it has one page. */
|
|
161
|
+
const pageButtons = (discord, token, noun, pages, viewAt, page) => {
|
|
162
|
+
if (pages === 1) {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
const button = (label, target, disabled) => ({
|
|
166
|
+
customId: customId(token, { kind: "show", view: viewAt(target) }),
|
|
167
|
+
disabled,
|
|
168
|
+
label,
|
|
169
|
+
style: discord.ButtonStyle.Secondary,
|
|
170
|
+
type: discord.ComponentType.Button,
|
|
171
|
+
});
|
|
172
|
+
// At an edge the disabled button targets a neighbor page, so the two `custom_id` values stay distinct.
|
|
173
|
+
return [
|
|
174
|
+
button(`Previous ${noun}s`, Math.max(0, page - 1), page === 0),
|
|
175
|
+
button(`Next ${noun}s`, Math.min(pages - 1, page + 1), page === pages - 1),
|
|
176
|
+
];
|
|
177
|
+
};
|
|
178
|
+
/**
|
|
179
|
+
* Builds the picker message for a view: a provider select, the model select of the shown provider, and a row of
|
|
180
|
+
* page buttons when a select has more than 25 options. At most three action rows.
|
|
181
|
+
*/
|
|
182
|
+
export const pickerMessage = (discord, state, view) => {
|
|
183
|
+
const { token, current } = state;
|
|
184
|
+
const providers = providersOf(state);
|
|
185
|
+
const providerPages = pageCount(providers.length);
|
|
186
|
+
const shown = view.kind === "models" ? view.provider : undefined;
|
|
187
|
+
const providerPage = view.kind === "models" ? pageOf(view.provider) : view.page;
|
|
188
|
+
const rows = [
|
|
189
|
+
selectRow(discord, {
|
|
190
|
+
customId: customId(token, { kind: "choose_provider" }),
|
|
191
|
+
options: pageItems(providers.map((name, index) => ({ index, name })), providerPage).map(({ index, name }) => ({
|
|
192
|
+
default: index === shown,
|
|
193
|
+
label: truncate(name, MAX_OPTION_TEXT),
|
|
194
|
+
value: String(index),
|
|
195
|
+
})),
|
|
196
|
+
placeholder: placeholder("provider", providerPage, providerPages),
|
|
197
|
+
}),
|
|
198
|
+
];
|
|
199
|
+
const buttons = pageButtons(discord, token, "provider", providerPages, (page) => ({ kind: "providers", page }), providerPage);
|
|
200
|
+
if (view.kind === "models") {
|
|
201
|
+
const models = modelsOf(state, providers[view.provider]);
|
|
202
|
+
const modelPages = pageCount(models.length);
|
|
203
|
+
rows.push(selectRow(discord, {
|
|
204
|
+
customId: customId(token, { kind: "choose_model" }),
|
|
205
|
+
options: pageItems(models, view.page).map(({ index, model }) => ({
|
|
206
|
+
default: isSameModel(current, model),
|
|
207
|
+
description: model.name === model.id
|
|
208
|
+
? undefined
|
|
209
|
+
: truncate(model.id, MAX_OPTION_TEXT),
|
|
210
|
+
label: truncate(model.name, MAX_OPTION_TEXT),
|
|
211
|
+
value: String(index),
|
|
212
|
+
})),
|
|
213
|
+
placeholder: placeholder("model", view.page, modelPages),
|
|
214
|
+
}));
|
|
215
|
+
buttons.push(...pageButtons(discord, token, "model", modelPages, (page) => ({ kind: "models", page, provider: view.provider }), view.page));
|
|
216
|
+
}
|
|
217
|
+
if (buttons.length > 0) {
|
|
218
|
+
rows.push({ components: buttons, type: discord.ComponentType.ActionRow });
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
allowedMentions: NO_MENTIONS,
|
|
222
|
+
components: rows,
|
|
223
|
+
content: current === undefined
|
|
224
|
+
? "Choose a model."
|
|
225
|
+
: `Current model: \`${modelRefText(current)}\``,
|
|
226
|
+
};
|
|
227
|
+
};
|
|
228
|
+
/**
|
|
229
|
+
* Keeps the newest picker states in the binding's `dataDir`, so that a picker still works after a daemon restart and
|
|
230
|
+
* a retried delivery finds the picker that it already sent.
|
|
231
|
+
*/
|
|
232
|
+
export class PickerStore {
|
|
233
|
+
#file;
|
|
234
|
+
/** In insertion order, oldest first. */
|
|
235
|
+
#pickers = new Map();
|
|
236
|
+
constructor(dataDir) {
|
|
237
|
+
this.#file = new JsonFile(dataDir, STORE_FILE, isStoreFile);
|
|
238
|
+
}
|
|
239
|
+
/** Reads the file. A missing file means no pickers. Throws for an unreadable or malformed file. */
|
|
240
|
+
async load() {
|
|
241
|
+
const parsed = await this.#file.read();
|
|
242
|
+
if (parsed === undefined) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
this.#pickers.clear();
|
|
246
|
+
for (const picker of parsed.pickers) {
|
|
247
|
+
this.#pickers.set(picker.token, picker);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
get(token) {
|
|
251
|
+
return this.#pickers.get(token);
|
|
252
|
+
}
|
|
253
|
+
/** Stores a picker, drops the oldest beyond the limit, and resolves once the file holds the result. */
|
|
254
|
+
async put(state) {
|
|
255
|
+
this.#pickers.set(state.token, state);
|
|
256
|
+
for (const token of this.#pickers.keys()) {
|
|
257
|
+
if (this.#pickers.size <= MAX_STORED_PICKERS) {
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
this.#pickers.delete(token);
|
|
261
|
+
}
|
|
262
|
+
await this.#persist();
|
|
263
|
+
}
|
|
264
|
+
/** Removes a picker and resolves once the file no longer holds it. */
|
|
265
|
+
async delete(token) {
|
|
266
|
+
if (this.#pickers.delete(token)) {
|
|
267
|
+
await this.#persist();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async #persist() {
|
|
271
|
+
await this.#file.write({
|
|
272
|
+
pickers: [...this.#pickers.values()],
|
|
273
|
+
version: STORE_VERSION,
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
@@ -8,6 +8,7 @@ import { toDeliveryError } from "./delivery-errors.js";
|
|
|
8
8
|
import { parseEventCallback, parseInteraction, parseSlashCommand, } from "./inbound.js";
|
|
9
9
|
import { LiveProgress } from "./live-progress.js";
|
|
10
10
|
import { WEBHOOK_PATH_SUFFIX } from "./manifest.js";
|
|
11
|
+
import { modelSelectedBlocks, modelSelectedText, } from "./model-picker-blocks.js";
|
|
11
12
|
import { SlackOutbound } from "./outbound.js";
|
|
12
13
|
import { decodeOptional, parseJsonText, UrlVerificationSchema, } from "./schemas.js";
|
|
13
14
|
import { verifySlackSignature } from "./signature.js";
|
|
@@ -54,7 +55,8 @@ const nameOf = async (web, user) => {
|
|
|
54
55
|
* calls for allowed Chats. The binding acknowledges each envelope or request before it processes it, so Slack does not
|
|
55
56
|
* retry while attachments download. `stop` waits for inbound work in progress.
|
|
56
57
|
*
|
|
57
|
-
* Outbound: `deliver` posts Markdown chunks, uploads attachments, and posts and updates
|
|
58
|
+
* Outbound: `deliver` posts Markdown chunks, uploads attachments, posts Block Kit model pickers, and posts and updates
|
|
59
|
+
* Block Kit Approval prompts.
|
|
58
60
|
*/
|
|
59
61
|
export class SlackBinding {
|
|
60
62
|
#config;
|
|
@@ -358,11 +360,39 @@ export class SlackBinding {
|
|
|
358
360
|
senderDisplayName: await this.#displayName(connection, command.user, command.userName),
|
|
359
361
|
});
|
|
360
362
|
};
|
|
361
|
-
#handleAction = async (
|
|
363
|
+
#handleAction = async (interaction) => {
|
|
362
364
|
const connection = this.#connection;
|
|
363
|
-
if (connection === undefined ||
|
|
365
|
+
if (connection === undefined || interaction === undefined) {
|
|
364
366
|
return;
|
|
365
367
|
}
|
|
368
|
+
await (interaction.kind === "approval"
|
|
369
|
+
? this.#handleApproval(connection, interaction)
|
|
370
|
+
: this.#handleModelSelection(connection, interaction));
|
|
371
|
+
};
|
|
372
|
+
/** Runs `/model <provider>/<id>` in the Chat of the picker, then replaces the picker with the selected model. */
|
|
373
|
+
#handleModelSelection = async (connection, selection) => {
|
|
374
|
+
const chatId = toChatId(selection.channel, selection.threadTs);
|
|
375
|
+
if (!this.#allowed(chatId)) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const senderDisplayName = await this.#displayName(connection, selection.user, selection.userName);
|
|
379
|
+
await connection.sink.command({
|
|
380
|
+
args: selection.model,
|
|
381
|
+
chatId,
|
|
382
|
+
name: "model",
|
|
383
|
+
senderDisplayName,
|
|
384
|
+
});
|
|
385
|
+
if (selection.messageTs === undefined) {
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
await connection.web.chat.update({
|
|
389
|
+
blocks: modelSelectedBlocks(selection.model, senderDisplayName),
|
|
390
|
+
channel: selection.channel,
|
|
391
|
+
text: modelSelectedText(selection.model),
|
|
392
|
+
ts: selection.messageTs,
|
|
393
|
+
});
|
|
394
|
+
};
|
|
395
|
+
#handleApproval = async (connection, action) => {
|
|
366
396
|
const chatId = connection.store.approval(action.approvalId)?.chatId ??
|
|
367
397
|
toChatId(action.channel, action.threadTs);
|
|
368
398
|
if (!this.#allowed(chatId)) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { decisionOfAction } from "./approval-blocks.js";
|
|
2
|
+
import { MODEL_ACTION_PREFIX } from "./model-picker-blocks.js";
|
|
2
3
|
import { BlockActionsSchema, decodeOptional, MessageEventCallbackSchema, SlashCommandSchema, } from "./schemas.js";
|
|
3
4
|
/** Message subtypes that carry a Sender message. Other subtypes are edits, joins, bot posts, and similar. */
|
|
4
5
|
const USER_SUBTYPES = new Set([
|
|
@@ -51,26 +52,34 @@ export const parseSlashCommand = (payload) => {
|
|
|
51
52
|
userName: decoded.user_name,
|
|
52
53
|
};
|
|
53
54
|
};
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
return undefined;
|
|
55
|
+
/** Returns the model selection or Approval click of one action, or `undefined` for another action. */
|
|
56
|
+
const interactionOf = (action, sender, messageTs) => {
|
|
57
|
+
const model = action.selected_option?.value;
|
|
58
|
+
if (action.action_id.startsWith(MODEL_ACTION_PREFIX) && model !== undefined) {
|
|
59
|
+
return { ...sender, kind: "model", messageTs, model };
|
|
60
60
|
}
|
|
61
61
|
const decision = decisionOfAction(action.action_id);
|
|
62
62
|
const approvalId = action.value;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
return decision === undefined || approvalId === undefined
|
|
64
|
+
? undefined
|
|
65
|
+
: { ...sender, approvalId, decision, kind: "approval" };
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Parses a `block_actions` payload. Returns `undefined` unless the first action is an Approval button or a model picker
|
|
69
|
+
* selection.
|
|
70
|
+
*/
|
|
71
|
+
export const parseInteraction = (payload) => {
|
|
72
|
+
const decoded = decodeOptional(BlockActionsSchema, payload);
|
|
73
|
+
const [action] = decoded?.actions ?? [];
|
|
74
|
+
const channel = decoded?.channel?.id ?? decoded?.container?.channel_id;
|
|
75
|
+
if (decoded === undefined || action === undefined || channel === undefined) {
|
|
66
76
|
return undefined;
|
|
67
77
|
}
|
|
68
|
-
|
|
69
|
-
approvalId,
|
|
78
|
+
const sender = {
|
|
70
79
|
channel,
|
|
71
|
-
decision,
|
|
72
80
|
threadTs: decoded.message?.thread_ts,
|
|
73
81
|
user: decoded.user.id,
|
|
74
82
|
userName: decoded.user.name ?? decoded.user.username,
|
|
75
83
|
};
|
|
84
|
+
return interactionOf(action, sender, decoded.message?.ts ?? decoded.container?.message_ts);
|
|
76
85
|
};
|