omp-superagent 0.0.0-stage → 0.1.1
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/DESIGN.md +1361 -0
- package/LICENSE +21 -0
- package/README.ko.md +184 -0
- package/README.md +205 -2
- package/THIRD_PARTY_NOTICES.md +313 -0
- package/assets/architecture.mmd +24 -0
- package/assets/architecture.svg +126 -0
- package/assets/superagent-avatar.jpg +0 -0
- package/assets/superagent-mascot.webp +0 -0
- package/config.example.json +26 -0
- package/docs/OPERATIONS.md +1030 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/package.json +59 -4
- package/scripts/check-omp.ts +4 -0
- package/scripts/ci.ts +28 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +50 -0
- package/scripts/setup.sh +25 -0
- package/skills/head/SKILL.md +259 -0
- package/skills/head/references/model-selection.md +263 -0
- package/skills/head/references/routing.md +356 -0
- package/skills/head/references/supervision.md +312 -0
- package/skills/lane/SKILL.md +188 -0
- package/skills/lane/references/workflow.md +349 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +167 -0
- package/src/config.ts +191 -0
- package/src/contracts.ts +317 -0
- package/src/credentials.ts +172 -0
- package/src/delivery.ts +7 -0
- package/src/dialog.ts +73 -0
- package/src/discord-command-registration.ts +201 -0
- package/src/discord-commands.ts +29 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord.ts +745 -0
- package/src/extension.ts +289 -0
- package/src/gateway-client.ts +222 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +392 -0
- package/src/gateway-store.ts +237 -0
- package/src/gateway.ts +638 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-extension.ts +449 -0
- package/src/host-owner.ts +350 -0
- package/src/host-protocol.ts +136 -0
- package/src/host.ts +414 -0
- package/src/installed-omp.ts +63 -0
- package/src/lane-extension.ts +179 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/managed-ulw-probe.ts +172 -0
- package/src/managed-ulw.ts +471 -0
- package/src/message-order.ts +21 -0
- package/src/messenger-commands.ts +16 -0
- package/src/messengers.ts +114 -0
- package/src/native-presets.ts +282 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +129 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +3864 -0
- package/src/setup-judge.ts +34 -0
- package/src/setup-memory.ts +39 -0
- package/src/setup-profiles.ts +84 -0
- package/src/setup.ts +300 -0
- package/src/slack-command-registration.ts +217 -0
- package/src/slack-commands.ts +18 -0
- package/src/slack.ts +776 -0
- package/src/store.ts +806 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +661 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import {
|
|
2
|
+
closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync,
|
|
3
|
+
renameSync, unlinkSync, writeFileSync, type Stats,
|
|
4
|
+
} from "node:fs";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { parseEnv } from "node:util";
|
|
8
|
+
import { credentialEnvNames, type Config } from "./config";
|
|
9
|
+
|
|
10
|
+
export interface CredentialFile {
|
|
11
|
+
path: string;
|
|
12
|
+
values: Record<string, string>;
|
|
13
|
+
/** Kept private in memory, never included in diagnostics. */
|
|
14
|
+
bytes: Buffer;
|
|
15
|
+
stat: Stats;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function missing(error: unknown): boolean {
|
|
19
|
+
return (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function privateFile(stat: Stats): void {
|
|
23
|
+
if (!stat.isFile() || (stat.mode & 0o177) !== 0 ||
|
|
24
|
+
(process.getuid && stat.uid !== process.getuid()))
|
|
25
|
+
throw new Error("Credential file must be an owned, non-symlink private file (mode 0600)");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function decode(bytes: Buffer): string {
|
|
29
|
+
const value = bytes.toString("utf8");
|
|
30
|
+
if (!Buffer.from(value, "utf8").equals(bytes) || value.includes("\0"))
|
|
31
|
+
throw new Error("Credential file must contain valid UTF-8 without NUL bytes");
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function parseCredentialValues(text: string): Record<string, string> {
|
|
36
|
+
const values: Record<string, string> = Object.create(null);
|
|
37
|
+
for (const [name, value] of Object.entries(parseEnv(text))) {
|
|
38
|
+
if (typeof value !== "string") throw new Error("Credential file is not valid dotenv");
|
|
39
|
+
values[name] = value;
|
|
40
|
+
}
|
|
41
|
+
return values;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** This is deliberately not dotenv autoloading: callers opt in for start/doctor only. */
|
|
45
|
+
export function readCredentialFile(configPath: string): CredentialFile | undefined {
|
|
46
|
+
const path = `${configPath}.env`;
|
|
47
|
+
let fd: number;
|
|
48
|
+
try {
|
|
49
|
+
const stat = lstatSync(path);
|
|
50
|
+
if (stat.isSymbolicLink()) throw new Error("Credential file must not be a symlink");
|
|
51
|
+
privateFile(stat);
|
|
52
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (missing(error)) return undefined;
|
|
55
|
+
if (error instanceof Error && error.message.startsWith("Credential file")) throw error;
|
|
56
|
+
throw new Error("Cannot safely open credential file");
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const stat = fstatSync(fd);
|
|
60
|
+
privateFile(stat);
|
|
61
|
+
const bytes = readFileSync(fd);
|
|
62
|
+
const text = decode(bytes);
|
|
63
|
+
let values: Record<string, string>;
|
|
64
|
+
try { values = parseCredentialValues(text); }
|
|
65
|
+
catch { throw new Error("Credential file is not valid dotenv"); }
|
|
66
|
+
return { path, values, bytes, stat };
|
|
67
|
+
} finally { closeSync(fd); }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function validateCredential(value: string): void {
|
|
71
|
+
if (!value || /[\r\n\0]/.test(value) || Buffer.from(value, "utf8").toString("utf8") !== value)
|
|
72
|
+
throw new Error("Credential must be a nonempty, single-line UTF-8 value without NUL bytes");
|
|
73
|
+
encodeValue(value);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function encodeValue(value: string): string {
|
|
77
|
+
// parseEnv, not shell syntax, is the authority. In particular, dollar signs and
|
|
78
|
+
// backslashes remain literal. Test the complete parse so quotes/comments cannot
|
|
79
|
+
// inject another assignment. No interpolation or shell evaluation is used.
|
|
80
|
+
const candidates = [value, `'${value}'`, `"${value}"`, `\`${value}\``];
|
|
81
|
+
for (const candidate of candidates) {
|
|
82
|
+
try {
|
|
83
|
+
const parsed = parseEnv(`VALUE=${candidate}\n`);
|
|
84
|
+
if (Object.keys(parsed).length === 1 && parsed.VALUE === value) return candidate;
|
|
85
|
+
} catch { /* Try another literal delimiter, never include the value in an error. */ }
|
|
86
|
+
}
|
|
87
|
+
throw new Error("Credential value cannot be stored losslessly in dotenv");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function serializeCredentials(values: Record<string, string>): string {
|
|
91
|
+
const entries = Object.entries(values);
|
|
92
|
+
const text = entries.map(([name, value]) => {
|
|
93
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Credential file has an invalid variable name");
|
|
94
|
+
return `${name}=${encodeValue(value)}\n`;
|
|
95
|
+
}).join("");
|
|
96
|
+
let parsed: Record<string, string>;
|
|
97
|
+
try { parsed = parseCredentialValues(text); }
|
|
98
|
+
catch { throw new Error("Credential file cannot be stored losslessly in dotenv"); }
|
|
99
|
+
if (Object.keys(parsed).length !== entries.length || entries.some(([name, value]) => parsed[name] !== value))
|
|
100
|
+
throw new Error("Credential file cannot be stored losslessly in dotenv");
|
|
101
|
+
return text;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function assertCredentialsUnchanged(configPath: string, previous: CredentialFile | undefined): void {
|
|
105
|
+
const current = readCredentialFile(configPath);
|
|
106
|
+
if (!!current !== !!previous || (current && previous &&
|
|
107
|
+
(current.stat.dev !== previous.stat.dev || current.stat.ino !== previous.stat.ino ||
|
|
108
|
+
current.stat.mtimeMs !== previous.stat.mtimeMs || current.stat.ctimeMs !== previous.stat.ctimeMs ||
|
|
109
|
+
!current.bytes.equals(previous.bytes))))
|
|
110
|
+
throw new Error("Credential file changed during setup; nothing was overwritten");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Stage privately beside the target. Caller must recheck snapshots before commit. */
|
|
114
|
+
export function stagePrivateFile(path: string, contents: string): string {
|
|
115
|
+
const temporary = join(dirname(path), `.setup-${randomUUID()}.tmp`);
|
|
116
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
117
|
+
try {
|
|
118
|
+
fchmodSync(fd, 0o600);
|
|
119
|
+
writeFileSync(fd, contents, "utf8");
|
|
120
|
+
fsyncSync(fd);
|
|
121
|
+
} catch {
|
|
122
|
+
unlinkSync(temporary);
|
|
123
|
+
throw new Error("Could not stage private setup file");
|
|
124
|
+
} finally { closeSync(fd); }
|
|
125
|
+
return temporary;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function writeCredentials(configPath: string, values: Record<string, string>, previous: CredentialFile | undefined): void {
|
|
129
|
+
const path = `${configPath}.env`;
|
|
130
|
+
// Serialize cooperating publishers, then recheck the caller's original snapshot.
|
|
131
|
+
// Never steal an existing lock: after an interrupted writer the operator must
|
|
132
|
+
// first ensure it is no longer running before explicitly removing this file.
|
|
133
|
+
const lockPath = `${path}.lock`;
|
|
134
|
+
let lock: number;
|
|
135
|
+
try { lock = openSync(lockPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
|
136
|
+
catch { throw new Error(`Credential write lock unavailable: ${lockPath}; no files were overwritten`); }
|
|
137
|
+
const lockStat = fstatSync(lock);
|
|
138
|
+
let temporary: string | undefined;
|
|
139
|
+
try {
|
|
140
|
+
fchmodSync(lock, 0o600);
|
|
141
|
+
writeFileSync(lock, `${process.pid}\n`, "utf8");
|
|
142
|
+
temporary = stagePrivateFile(path, serializeCredentials(values));
|
|
143
|
+
assertCredentialsUnchanged(configPath, previous);
|
|
144
|
+
if (previous) renameSync(temporary, path);
|
|
145
|
+
// The link is a complete private publication. A crash before stage cleanup may
|
|
146
|
+
// leave an extra private link, which is harmless and does not prevent reads.
|
|
147
|
+
else linkSync(temporary, path);
|
|
148
|
+
} finally {
|
|
149
|
+
try {
|
|
150
|
+
if (temporary) {
|
|
151
|
+
try { unlinkSync(temporary); } catch (error) { if (!missing(error)) throw error; }
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
closeSync(lock);
|
|
155
|
+
try {
|
|
156
|
+
const current = lstatSync(lockPath);
|
|
157
|
+
if (current.dev === lockStat.dev && current.ino === lockStat.ino) unlinkSync(lockPath);
|
|
158
|
+
} catch (error) { if (!missing(error)) throw error; }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Nonempty explicit environment wins; unrelated dotenv keys never enter a process. */
|
|
164
|
+
export function loadCredentials(config: Config): void {
|
|
165
|
+
const file = readCredentialFile(config.path);
|
|
166
|
+
if (!file) return;
|
|
167
|
+
for (const name of credentialEnvNames(config)) {
|
|
168
|
+
if (process.env[name]) continue;
|
|
169
|
+
const value = Object.hasOwn(file.values, name) ? file.values[name] : undefined;
|
|
170
|
+
if (value) { validateCredential(value); process.env[name] = value; }
|
|
171
|
+
}
|
|
172
|
+
}
|
package/src/delivery.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** An ambiguous transport mutation must never be retried as a known rejection. */
|
|
2
|
+
export class DeliveryError extends Error {
|
|
3
|
+
constructor(message: string, public readonly certainty: "rejected" | "uncertain" = "uncertain", public readonly retryAfterMs?: number, options?: ErrorOptions) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = "DeliveryError";
|
|
6
|
+
}
|
|
7
|
+
}
|
package/src/dialog.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Native OMP dialog semantics, independent of a transport's UI capacities. */
|
|
2
|
+
export interface Question {
|
|
3
|
+
id: string;
|
|
4
|
+
question: string;
|
|
5
|
+
header?: string;
|
|
6
|
+
options: { label: string; description?: string; preview?: string }[];
|
|
7
|
+
multi?: boolean;
|
|
8
|
+
recommended?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type Dialog =
|
|
12
|
+
| { method: "confirm"; title: string; message: string }
|
|
13
|
+
| { method: "select"; title: string; options: string[]; details: (string | undefined)[]; marker?: "radio" | "checkbox"; checked: number[]; markableCount: number; initialIndex?: number }
|
|
14
|
+
| { method: "input"; title: string; placeholder?: string; prefill?: string }
|
|
15
|
+
| { method: "editor"; title: string; placeholder?: string; prefill?: string }
|
|
16
|
+
| { method: "ask"; questions: Question[] };
|
|
17
|
+
|
|
18
|
+
function text(value: unknown): value is string { return typeof value === "string"; }
|
|
19
|
+
function object(value: unknown): value is Record<string, unknown> { return !!value && typeof value === "object" && !Array.isArray(value); }
|
|
20
|
+
function unsupported(reason: string): never { throw new Error(reason); }
|
|
21
|
+
|
|
22
|
+
/** Preserve native values and host-owned checked state; never collect secrets. */
|
|
23
|
+
export function parseDialog(request: Record<string, unknown>): Dialog {
|
|
24
|
+
if (request.secret === true) unsupported("Secret input cannot safely be collected through a messenger; use the local OMP interface.");
|
|
25
|
+
if (request.method === "ask") {
|
|
26
|
+
if (!Array.isArray(request.questions) || request.questions.length === 0) unsupported("Ask request has no questions.");
|
|
27
|
+
const questions: Question[] = request.questions.map((value: unknown) => {
|
|
28
|
+
if (!object(value) || !text(value.id) || !text(value.question) || !Array.isArray(value.options)) return unsupported("Malformed ask question.");
|
|
29
|
+
if (value.header !== undefined && !text(value.header)) unsupported("Malformed ask header.");
|
|
30
|
+
if (value.multi !== undefined && typeof value.multi !== "boolean") unsupported("Malformed ask selection mode.");
|
|
31
|
+
const options = value.options.map((option: unknown) => {
|
|
32
|
+
if (!object(option) || !text(option.label) || !option.label) return unsupported("Malformed ask option.");
|
|
33
|
+
if (option.description !== undefined && !text(option.description)) unsupported("Malformed ask description.");
|
|
34
|
+
if (option.preview !== undefined && !text(option.preview)) unsupported("Malformed ask preview.");
|
|
35
|
+
return { label: option.label, description: option.description as string | undefined, preview: option.preview as string | undefined };
|
|
36
|
+
});
|
|
37
|
+
if (new Set(options.map(option => option.label)).size !== options.length) unsupported("Ask option labels are not unique.");
|
|
38
|
+
if (value.recommended !== undefined && (!Number.isInteger(value.recommended) || (value.recommended as number) < 0 || (value.recommended as number) >= options.length)) unsupported("Malformed recommended option.");
|
|
39
|
+
return { id: value.id, question: value.question, header: value.header as string | undefined, multi: value.multi as boolean | undefined, recommended: value.recommended as number | undefined, options };
|
|
40
|
+
});
|
|
41
|
+
if (new Set(questions.map(question => question.id)).size !== questions.length) unsupported("Ask question IDs are not unique.");
|
|
42
|
+
return { method: "ask", questions };
|
|
43
|
+
}
|
|
44
|
+
if (!text(request.title)) unsupported("Dialog title is missing.");
|
|
45
|
+
if (request.method === "confirm") {
|
|
46
|
+
if (!text(request.message)) unsupported("Confirmation message is missing.");
|
|
47
|
+
return { method: "confirm", title: request.title, message: request.message };
|
|
48
|
+
}
|
|
49
|
+
if (request.method === "select") {
|
|
50
|
+
if (!Array.isArray(request.options) || request.options.length === 0 || !request.options.every(option => text(option) && option.length > 0) || new Set(request.options).size !== request.options.length) unsupported("Malformed or duplicate select options.");
|
|
51
|
+
if (request.selectionMarker !== undefined && request.selectionMarker !== "radio" && request.selectionMarker !== "checkbox") unsupported("Malformed select marker.");
|
|
52
|
+
const marker = request.selectionMarker as "radio" | "checkbox" | undefined;
|
|
53
|
+
const markableCount = request.markableCount ?? (marker ? request.options.length : 0);
|
|
54
|
+
if (!Number.isInteger(markableCount) || (markableCount as number) < 0 || (markableCount as number) > request.options.length) unsupported("Malformed marked-option count.");
|
|
55
|
+
const checked = request.checkedIndices ?? [];
|
|
56
|
+
if (!Array.isArray(checked) || checked.some(index => !Number.isInteger(index) || index < 0 || index >= (markableCount as number)) || new Set(checked).size !== checked.length) unsupported("Malformed checked-option state.");
|
|
57
|
+
if (request.initialIndex !== undefined && (!Number.isInteger(request.initialIndex) || (request.initialIndex as number) < 0 || (request.initialIndex as number) >= request.options.length)) unsupported("Malformed initial select index.");
|
|
58
|
+
if (request.optionDetails !== undefined && !Array.isArray(request.optionDetails)) unsupported("Malformed select details.");
|
|
59
|
+
const details = request.options.map((_, index) => {
|
|
60
|
+
const detail = Array.isArray(request.optionDetails) ? request.optionDetails[index] : undefined;
|
|
61
|
+
if (detail === undefined) return undefined;
|
|
62
|
+
if (!object(detail) || (detail.description !== undefined && !text(detail.description))) return unsupported("Malformed select description.");
|
|
63
|
+
return detail.description as string | undefined;
|
|
64
|
+
});
|
|
65
|
+
return { method: "select", title: request.title, options: request.options as string[], details, marker, checked, markableCount: markableCount as number, initialIndex: request.initialIndex as number | undefined };
|
|
66
|
+
}
|
|
67
|
+
if (request.method === "input" || request.method === "editor") {
|
|
68
|
+
if (request.placeholder !== undefined && !text(request.placeholder)) unsupported("Malformed input placeholder.");
|
|
69
|
+
if (request.prefill !== undefined && !text(request.prefill)) unsupported("Malformed editor content.");
|
|
70
|
+
return { method: request.method, title: request.title, placeholder: request.placeholder as string | undefined, prefill: request.prefill as string | undefined };
|
|
71
|
+
}
|
|
72
|
+
return unsupported(`Dialog method ${String(request.method)} cannot be represented safely in a messenger.`);
|
|
73
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { REST, Routes, type RESTOptions } from "discord.js";
|
|
2
|
+
import type { Config } from "./config";
|
|
3
|
+
import { loadCredentials, validateCredential } from "./credentials";
|
|
4
|
+
import { DISCORD_COMMANDS } from "./discord-commands";
|
|
5
|
+
|
|
6
|
+
type CommandRest = Pick<REST, "get" | "put">;
|
|
7
|
+
|
|
8
|
+
export interface DiscordCommandRegistrationOptions {
|
|
9
|
+
apply?: boolean;
|
|
10
|
+
createRest?: (options: Partial<RESTOptions>, token: string) => CommandRest;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface Registration {
|
|
14
|
+
id: string;
|
|
15
|
+
application_id: string;
|
|
16
|
+
type: number;
|
|
17
|
+
name: string;
|
|
18
|
+
description: string;
|
|
19
|
+
[key: string]: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DiscordCommandRegistrationReport {
|
|
23
|
+
status: "dry-run" | "blocked" | "applied";
|
|
24
|
+
applicationId: string;
|
|
25
|
+
botId: string;
|
|
26
|
+
plannedGlobal: typeof DISCORD_COMMANDS;
|
|
27
|
+
currentGlobal: { id: string; type: number; name: string }[];
|
|
28
|
+
obsoleteGlobal: { id: string; type: number; name: string }[];
|
|
29
|
+
guilds: {
|
|
30
|
+
guildId: string;
|
|
31
|
+
registrations: { id: string; type: number; name: string }[];
|
|
32
|
+
shadowing: { id: string; type: number; name: string }[];
|
|
33
|
+
}[];
|
|
34
|
+
note: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function object(value: unknown): Record<string, unknown> {
|
|
38
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed Discord response");
|
|
39
|
+
return value as Record<string, unknown>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function snowflake(value: unknown): string {
|
|
43
|
+
if (typeof value !== "string" || !/^\d+$/.test(value)) throw new Error("Malformed Discord identity");
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function registrations(value: unknown, applicationId: string, guildId?: string): Registration[] {
|
|
48
|
+
if (!Array.isArray(value)) throw new Error("Malformed Discord command list");
|
|
49
|
+
const ids = new Set<string>();
|
|
50
|
+
const keys = new Set<string>();
|
|
51
|
+
return value.map(item => {
|
|
52
|
+
const row = object(item);
|
|
53
|
+
const id = snowflake(row.id);
|
|
54
|
+
if (row.application_id !== applicationId ||
|
|
55
|
+
(guildId === undefined ? row.guild_id !== undefined : row.guild_id !== guildId) ||
|
|
56
|
+
!Number.isInteger(row.type) || ![1, 2, 3, 4].includes(row.type as number) ||
|
|
57
|
+
typeof row.name !== "string" || !row.name.length || row.name.length > 32 ||
|
|
58
|
+
typeof row.description !== "string" ||
|
|
59
|
+
(row.options !== undefined && !Array.isArray(row.options)))
|
|
60
|
+
throw new Error("Malformed Discord command list");
|
|
61
|
+
const key = `${row.type}:${row.name}`;
|
|
62
|
+
if (ids.has(id) || keys.has(key)) throw new Error("Duplicate Discord registration");
|
|
63
|
+
ids.add(id);
|
|
64
|
+
keys.add(key);
|
|
65
|
+
return row as Registration;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function sortedNumbers(value: unknown, fallback: number[]): number[] {
|
|
70
|
+
const values = value === undefined ? fallback : value;
|
|
71
|
+
if (!Array.isArray(values) || !values.every(item => Number.isInteger(item)) ||
|
|
72
|
+
new Set(values).size !== values.length) throw new Error("Malformed Discord command contexts");
|
|
73
|
+
return [...values].sort((a, b) => a - b);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function localizations(value: unknown): Record<string, string> {
|
|
77
|
+
if (value == null) return {};
|
|
78
|
+
const entries = Object.entries(object(value));
|
|
79
|
+
if (entries.some(([, text]) => typeof text !== "string")) throw new Error("Malformed Discord localization");
|
|
80
|
+
return Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b))) as Record<string, string>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Keep semantic option fields, omitting only Discord's documented empty defaults. */
|
|
84
|
+
function commandOption(value: unknown): Record<string, unknown> {
|
|
85
|
+
const row = object(value);
|
|
86
|
+
if (!Number.isInteger(row.type) || typeof row.name !== "string" || typeof row.description !== "string")
|
|
87
|
+
throw new Error("Malformed Discord command option");
|
|
88
|
+
const result: Record<string, unknown> = {};
|
|
89
|
+
for (const key of Object.keys(row).sort()) {
|
|
90
|
+
const item = row[key];
|
|
91
|
+
if (item === undefined) continue;
|
|
92
|
+
if ((key === "required" || key === "autocomplete") && item === false) continue;
|
|
93
|
+
if (key === "name_localizations" || key === "description_localizations") {
|
|
94
|
+
const values = localizations(item);
|
|
95
|
+
if (Object.keys(values).length) result[key] = values;
|
|
96
|
+
} else if (key === "options" || key === "choices" || key === "channel_types") {
|
|
97
|
+
if (!Array.isArray(item)) throw new Error("Malformed Discord command option");
|
|
98
|
+
if (item.length) result[key] = key === "options" ? item.map(commandOption) : item;
|
|
99
|
+
} else {
|
|
100
|
+
result[key] = item;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function definition(value: unknown): Record<string, unknown> {
|
|
107
|
+
const row = object(value);
|
|
108
|
+
if (typeof row.name !== "string" || typeof row.description !== "string" ||
|
|
109
|
+
(row.options !== undefined && !Array.isArray(row.options))) throw new Error("Malformed Discord definition");
|
|
110
|
+
return {
|
|
111
|
+
type: row.type ?? 1,
|
|
112
|
+
name: row.name,
|
|
113
|
+
description: row.description,
|
|
114
|
+
options: ((row.options ?? []) as unknown[]).map(commandOption),
|
|
115
|
+
contexts: sortedNumbers(row.contexts, [0, 1, 2]),
|
|
116
|
+
integration_types: sortedNumbers(row.integration_types, [0]),
|
|
117
|
+
name_localizations: localizations(row.name_localizations),
|
|
118
|
+
description_localizations: localizations(row.description_localizations),
|
|
119
|
+
default_member_permissions: row.default_member_permissions ?? null,
|
|
120
|
+
default_permission: row.default_permission ?? true,
|
|
121
|
+
nsfw: row.nsfw ?? false,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function exactDefinitions(actual: Registration[]): boolean {
|
|
126
|
+
const normalized = (commands: readonly unknown[]) => commands.map(definition)
|
|
127
|
+
.sort((a, b) => `${a.type}:${a.name}`.localeCompare(`${b.type}:${b.name}`));
|
|
128
|
+
return JSON.stringify(normalized(actual)) === JSON.stringify(normalized(DISCORD_COMMANDS));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** REST-only opt-in. Never opens a Gateway, imports native OMP, or retries a mutation. */
|
|
132
|
+
export async function registerDiscordCommands(
|
|
133
|
+
config: Config, options: DiscordCommandRegistrationOptions = {},
|
|
134
|
+
): Promise<DiscordCommandRegistrationReport> {
|
|
135
|
+
if (!config.discord) throw new Error("discord-commands requires configured Discord credentials and policy");
|
|
136
|
+
try {
|
|
137
|
+
// Reuse the existing private sibling-file/environment policy, selecting Discord only.
|
|
138
|
+
loadCredentials({ ...config, telegram: undefined, slack: undefined });
|
|
139
|
+
} catch { throw new Error("Cannot safely load the configured Discord credential; details suppressed"); }
|
|
140
|
+
const token = process.env[config.discord.tokenEnv];
|
|
141
|
+
if (!token) throw new Error("Configured Discord credential is missing");
|
|
142
|
+
try { validateCredential(token); }
|
|
143
|
+
catch { throw new Error("Configured Discord credential is invalid; value suppressed"); }
|
|
144
|
+
|
|
145
|
+
let rest: CommandRest;
|
|
146
|
+
try {
|
|
147
|
+
rest = (options.createRest ?? ((settings, credential) => new REST(settings).setToken(credential)))(
|
|
148
|
+
{ version: "10", retries: 0, rejectOnRateLimit: () => true }, token,
|
|
149
|
+
);
|
|
150
|
+
} catch { throw new Error("Discord REST initialization failed; details suppressed"); }
|
|
151
|
+
|
|
152
|
+
let report: DiscordCommandRegistrationReport;
|
|
153
|
+
let applicationId: string;
|
|
154
|
+
try {
|
|
155
|
+
const bot = object(await rest.get(Routes.user("@me")));
|
|
156
|
+
const botId = snowflake(bot.id);
|
|
157
|
+
if (bot.bot !== true) throw new Error("Discord identity is not a bot");
|
|
158
|
+
const application = object(await rest.get(Routes.oauth2CurrentApplication()));
|
|
159
|
+
applicationId = snowflake(application.id);
|
|
160
|
+
if (applicationId !== botId ||
|
|
161
|
+
(application.bot !== undefined && snowflake(object(application.bot).id) !== botId))
|
|
162
|
+
throw new Error("Discord bot/application identity mismatch");
|
|
163
|
+
const current = registrations(await rest.get(Routes.applicationCommands(applicationId)), applicationId);
|
|
164
|
+
const supported = new Set(DISCORD_COMMANDS.map(command => `${command.type ?? 1}:${command.name}`));
|
|
165
|
+
const summary = (rows: Registration[]) => rows.map(row => ({
|
|
166
|
+
id: row.id, type: row.type,
|
|
167
|
+
name: row.name.replaceAll(token, "[redacted]").replace(/https?:\/\/\S+/gi, "[redacted-url]"),
|
|
168
|
+
}));
|
|
169
|
+
const guilds: DiscordCommandRegistrationReport["guilds"] = [];
|
|
170
|
+
for (const guildId of config.discord.allowedGuildIds) {
|
|
171
|
+
const rows = registrations(await rest.get(Routes.applicationGuildCommands(applicationId, guildId)), applicationId, guildId);
|
|
172
|
+
guilds.push({ guildId, registrations: summary(rows), shadowing: summary(rows.filter(row => supported.has(`${row.type}:${row.name}`))) });
|
|
173
|
+
}
|
|
174
|
+
report = {
|
|
175
|
+
status: "dry-run", applicationId, botId, plannedGlobal: DISCORD_COMMANDS,
|
|
176
|
+
currentGlobal: summary(current),
|
|
177
|
+
obsoleteGlobal: summary(current.filter(row => !supported.has(`${row.type}:${row.name}`))),
|
|
178
|
+
guilds,
|
|
179
|
+
note: "Read-only plan. --apply takes exclusive ownership of this dedicated bot's GLOBAL command list, replacing it with supported Superagent definitions and deleting all other global registrations (including Hermes). Guild registrations are preserved; supported-name guild shadows block apply. No Gateway or native runtime was started.",
|
|
180
|
+
};
|
|
181
|
+
} catch {
|
|
182
|
+
throw new Error("Discord command inspection failed: identity, permissions, or response could not be verified. No mutation was attempted; raw SDK details suppressed. No automatic retry was attempted.");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (!options.apply) return report;
|
|
186
|
+
if (report.guilds.some(guild => guild.shadowing.length)) {
|
|
187
|
+
return { ...report, status: "blocked", note: "Apply refused: allowed-guild registrations shadow supported global commands. No mutation was attempted; all guild registrations are preserved. Resolve guild conflicts explicitly before applying." };
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
await rest.put(Routes.applicationCommands(applicationId), { body: DISCORD_COMMANDS });
|
|
191
|
+
} catch {
|
|
192
|
+
throw new Error("Discord global command overwrite is unresolved: the request failed and may have reached Discord. No automatic retry was attempted; raw SDK details suppressed. Inspect with discord-commands (without --apply) before deciding any further mutation.");
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
const actual = registrations(await rest.get(Routes.applicationCommands(applicationId)), applicationId);
|
|
196
|
+
if (!exactDefinitions(actual)) throw new Error("Discord readback differs");
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Error("Discord global command overwrite is unresolved: authoritative GET did not verify the exact supported definitions. No automatic retry was attempted; raw SDK details suppressed. Inspect with discord-commands (without --apply) before deciding any further mutation.");
|
|
199
|
+
}
|
|
200
|
+
return { ...report, status: "applied", note: "Global command overwrite verified by authoritative GET: exact supported Superagent names, types, descriptions, options, contexts, and guild-only installation. Obsolete global registrations were removed; guild registrations were not changed. No Gateway or native runtime was started." };
|
|
201
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ApplicationCommandOptionType, ApplicationCommandType, ApplicationIntegrationType, InteractionContextType,
|
|
3
|
+
type RESTPostAPIChatInputApplicationCommandsJSONBody,
|
|
4
|
+
} from "discord.js";
|
|
5
|
+
import { MESSENGER_COMMANDS } from "./messenger-commands";
|
|
6
|
+
|
|
7
|
+
/** The complete supported slash-command picker, also used for registration. */
|
|
8
|
+
export const DISCORD_COMMANDS: readonly RESTPostAPIChatInputApplicationCommandsJSONBody[] = MESSENGER_COMMANDS.map(
|
|
9
|
+
(command): RESTPostAPIChatInputApplicationCommandsJSONBody => ({
|
|
10
|
+
type: ApplicationCommandType.ChatInput, name: command.name, description: command.description,
|
|
11
|
+
contexts: [InteractionContextType.Guild, InteractionContextType.BotDM],
|
|
12
|
+
integration_types: [ApplicationIntegrationType.GuildInstall],
|
|
13
|
+
...("text" in command ? { options: [{ type: ApplicationCommandOptionType.String, name: "text", description: command.text, required: false }] } : {}),
|
|
14
|
+
}));
|
|
15
|
+
|
|
16
|
+
/** Reject stale registrations/options instead of silently executing a different command. */
|
|
17
|
+
export function parseDiscordCommand(name: string, options: unknown): string | null {
|
|
18
|
+
const command = DISCORD_COMMANDS.find(command => command.name === name);
|
|
19
|
+
if (!command || !Array.isArray(options)) return null;
|
|
20
|
+
if (options.length === 0) return `/${name}`;
|
|
21
|
+
if (!command.options?.length || options.length !== 1) return null;
|
|
22
|
+
const option: unknown = options[0];
|
|
23
|
+
if (!option || typeof option !== "object" || Array.isArray(option)) return null;
|
|
24
|
+
const value = option as Record<string, unknown>;
|
|
25
|
+
if (Object.keys(value).some(key => key !== "name" && key !== "type" && key !== "value") ||
|
|
26
|
+
value.name !== "text" || value.type !== ApplicationCommandOptionType.String || typeof value.value !== "string") return null;
|
|
27
|
+
const text = value.value.trim();
|
|
28
|
+
return `/${name}${text ? ` ${text}` : ""}`;
|
|
29
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown table rendering for the Discord transport.
|
|
3
|
+
*
|
|
4
|
+
* Discord has no pipe-table support: a table sent verbatim arrives as literal
|
|
5
|
+
* `| a | b |` rows. Discord does render fenced blocks in a monospaced font, so a
|
|
6
|
+
* table is converted into an aligned fenced block before it leaves this package.
|
|
7
|
+
*
|
|
8
|
+
* Column padding uses display width, not string length, so CJK and other wide
|
|
9
|
+
* characters line up. Bun.stringWidth supplies the display width directly;
|
|
10
|
+
* no OMP source checkout or private module is needed.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
type Align = "left" | "center" | "right";
|
|
14
|
+
|
|
15
|
+
const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
|
|
16
|
+
const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t\r]*$/;
|
|
17
|
+
const BLOCK_START = /^ {0,3}(?:>|#{1,6}(?:[ \t]|$)|(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$))/;
|
|
18
|
+
const DELIMITER_CELL = /^:?-+:?$/;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Split one table row into trimmed cells.
|
|
22
|
+
* Returns null when the line carries no unescaped pipe, so callers can end a
|
|
23
|
+
* table body. `\|` and pipes inside backtick spans never split a cell, matching
|
|
24
|
+
* how GFM reads a row.
|
|
25
|
+
*/
|
|
26
|
+
function splitRow(line: string): string[] | null {
|
|
27
|
+
const cells: string[] = [];
|
|
28
|
+
let cell = "";
|
|
29
|
+
let pipe = false;
|
|
30
|
+
let leading = false;
|
|
31
|
+
let tick = 0;
|
|
32
|
+
for (let index = 0; index < line.length; index++) {
|
|
33
|
+
const char = line[index]!;
|
|
34
|
+
if (char === "\\" && line[index + 1] === "|") {
|
|
35
|
+
// A GFM escaped pipe is cell content, not a separator: inside the fence
|
|
36
|
+
// it stays the literal `|` the author asked to display.
|
|
37
|
+
cell += "|";
|
|
38
|
+
index++;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (char === "`") {
|
|
42
|
+
let run = 1;
|
|
43
|
+
while (line[index + run] === "`") run++;
|
|
44
|
+
tick = tick === run ? 0 : tick === 0 ? run : tick;
|
|
45
|
+
cell += "`".repeat(run);
|
|
46
|
+
index += run - 1;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (char === "|" && tick === 0) {
|
|
50
|
+
if (!pipe) leading = cell.trim() === "";
|
|
51
|
+
pipe = true;
|
|
52
|
+
cells.push(cell);
|
|
53
|
+
cell = "";
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
cell += char;
|
|
57
|
+
}
|
|
58
|
+
if (!pipe) return null;
|
|
59
|
+
cells.push(cell);
|
|
60
|
+
if (leading) cells.shift();
|
|
61
|
+
if (cells.length > 0 && cells[cells.length - 1]!.trim() === "") cells.pop();
|
|
62
|
+
return cells.length > 0 ? cells.map(value => value.trim()) : null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The delimiter row must have the same cell count as the header, as in GFM. */
|
|
66
|
+
function parseDelimiter(line: string): Align[] | null {
|
|
67
|
+
const cells = splitRow(line);
|
|
68
|
+
if (!cells) return null;
|
|
69
|
+
const aligns: Align[] = [];
|
|
70
|
+
for (const cell of cells) {
|
|
71
|
+
if (!DELIMITER_CELL.test(cell)) return null;
|
|
72
|
+
const left = cell.startsWith(":");
|
|
73
|
+
const right = cell.endsWith(":");
|
|
74
|
+
aligns.push(left && right ? "center" : right ? "right" : "left");
|
|
75
|
+
}
|
|
76
|
+
return aligns;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function pad(value: string, width: number, align: Align): string {
|
|
80
|
+
const missing = width - Bun.stringWidth(value);
|
|
81
|
+
if (missing <= 0) return value;
|
|
82
|
+
if (align === "right") return " ".repeat(missing) + value;
|
|
83
|
+
if (align === "center") {
|
|
84
|
+
const left = Math.floor(missing / 2);
|
|
85
|
+
return " ".repeat(left) + value + " ".repeat(missing - left);
|
|
86
|
+
}
|
|
87
|
+
return value + " ".repeat(missing);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Check the byte budget before allocating any padded cells or separators. */
|
|
91
|
+
function formatTable(rows: string[][], aligns: Align[], maxBytes: number): { lines: string[]; bytes: number } | null {
|
|
92
|
+
const widths = aligns.map(() => 3);
|
|
93
|
+
for (const row of rows) {
|
|
94
|
+
for (let column = 0; column < row.length; column++) {
|
|
95
|
+
widths[column] = Math.max(widths[column] ?? 3, Bun.stringWidth(row[column]!));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const alignOf = (column: number): Align => aligns[column] ?? "left";
|
|
99
|
+
const fence = "```";
|
|
100
|
+
// Each row has a frame, display-width cells, and one newline. UTF-8 cell
|
|
101
|
+
// bytes may exceed their display width; the separator contains only ASCII.
|
|
102
|
+
const rowWidth = 3 * widths.length + 1 + widths.reduce((sum, width) => sum + width, 0);
|
|
103
|
+
let bytes = 2 * fence.length + rows.length + 2 + (rows.length + 1) * rowWidth;
|
|
104
|
+
for (const row of rows) {
|
|
105
|
+
for (const cell of row) bytes += Buffer.byteLength(cell, "utf8") - Bun.stringWidth(cell);
|
|
106
|
+
}
|
|
107
|
+
if (bytes > maxBytes) return null;
|
|
108
|
+
const line = (cells: string[]) =>
|
|
109
|
+
`| ${widths.map((width, column) => pad(cells[column] ?? "", width, alignOf(column))).join(" | ")} |`;
|
|
110
|
+
// Pure dashes keep the grid exact; alignment is already visible in the padded
|
|
111
|
+
// cells, and `:` markers would only shift every following column by one.
|
|
112
|
+
const separator = `| ${widths.map(width => "-".repeat(width)).join(" | ")} |`;
|
|
113
|
+
const lines = [fence, line(rows[0]!), separator];
|
|
114
|
+
for (let index = 1; index < rows.length; index++) lines.push(line(rows[index]!));
|
|
115
|
+
lines.push(fence);
|
|
116
|
+
return { lines, bytes };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Rewrite markdown pipe tables as aligned fenced blocks.
|
|
121
|
+
*
|
|
122
|
+
* Everything else passes through byte for byte: prose, lists, headings, links,
|
|
123
|
+
* blockquotes, inline code, and existing fenced blocks. Pipes inside a fence are
|
|
124
|
+
* never treated as a table, and an already-converted table stays inside its own
|
|
125
|
+
* fence, so the transform is idempotent. If alignment would exceed the complete
|
|
126
|
+
* message's byte budget, return the original text for the existing delivery path.
|
|
127
|
+
*/
|
|
128
|
+
export function renderDiscordMarkdown(text: string, maxBytes: number): string {
|
|
129
|
+
if (!text.includes("|")) return text;
|
|
130
|
+
let bytes = Buffer.byteLength(text, "utf8");
|
|
131
|
+
if (bytes > maxBytes) return text;
|
|
132
|
+
const lines = text.split("\n");
|
|
133
|
+
const out: string[] = [];
|
|
134
|
+
let fence: { char: string; length: number } | null = null;
|
|
135
|
+
for (let index = 0; index < lines.length; index++) {
|
|
136
|
+
const line = lines[index]!;
|
|
137
|
+
const marker = FENCE_OPEN.exec(line)?.[1];
|
|
138
|
+
if (fence) {
|
|
139
|
+
out.push(line);
|
|
140
|
+
const close = FENCE_CLOSE.exec(line)?.[1];
|
|
141
|
+
if (close && close[0] === fence.char && close.length >= fence.length) fence = null;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (marker) {
|
|
145
|
+
fence = { char: marker[0]!, length: marker.length };
|
|
146
|
+
out.push(line);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const delimiter = !BLOCK_START.test(line) && index + 1 < lines.length ? parseDelimiter(lines[index + 1]!) : null;
|
|
150
|
+
const header = delimiter ? splitRow(line) : null;
|
|
151
|
+
if (!delimiter || !header || header.length !== delimiter.length) {
|
|
152
|
+
out.push(line);
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const rows = [header];
|
|
156
|
+
let sourceBytes = Buffer.byteLength(line, "utf8") + 1 + Buffer.byteLength(lines[index + 1]!, "utf8");
|
|
157
|
+
let next = index + 2;
|
|
158
|
+
for (; next < lines.length; next++) {
|
|
159
|
+
if (FENCE_OPEN.test(lines[next]!) || BLOCK_START.test(lines[next]!)) break;
|
|
160
|
+
const row = splitRow(lines[next]!);
|
|
161
|
+
if (!row) break;
|
|
162
|
+
rows.push(row);
|
|
163
|
+
sourceBytes += 1 + Buffer.byteLength(lines[next]!, "utf8");
|
|
164
|
+
}
|
|
165
|
+
const table = formatTable(rows, delimiter, maxBytes - bytes + sourceBytes);
|
|
166
|
+
if (!table) return text;
|
|
167
|
+
bytes += table.bytes - sourceBytes;
|
|
168
|
+
for (const rendered of table.lines) out.push(rendered);
|
|
169
|
+
index = next - 1;
|
|
170
|
+
}
|
|
171
|
+
return out.join("\n");
|
|
172
|
+
}
|