omp-superagent 0.0.0-stage → 0.1.2

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.
Files changed (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
@@ -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,118 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { Type } from "@sinclair/typebox/type";
3
+ import { Value } from "@sinclair/typebox/value";
4
+ import { physicalRoute, physicalRouteKey, type DiscordPurposeNote, type DiscordPurposeRequest, type Route, type StorePort } from "./contracts";
5
+ import { DeliveryError } from "./delivery";
6
+
7
+ const PURPOSES = "discord:purposes";
8
+ type Metadata = Pick<StorePort, "getMeta" | "setMeta">;
9
+ interface Purposes {
10
+ readonly notes: Readonly<Record<string, DiscordPurposeNote>>;
11
+ readonly receipts: Readonly<Record<string, { readonly request: DiscordPurposeRequest; readonly result: readonly DiscordPurposeNote[] }>>;
12
+ }
13
+ const routeSchema = Type.Object({
14
+ platform: Type.Literal("discord"), accountId: Type.String({ minLength: 1 }),
15
+ authorityId: Type.String({ minLength: 1 }), channelId: Type.String({ minLength: 1 }),
16
+ guildId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
17
+ threadId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
18
+ }, { additionalProperties: false });
19
+ const purposeSchema = Type.String({ minLength: 1, maxLength: 4000, pattern: "\\S" });
20
+ const noteSchema = Type.Object({ route: routeSchema, purpose: purposeSchema }, { additionalProperties: false });
21
+ const requestFields = { sourceId: Type.String({ minLength: 1, maxLength: 1000 }), route: routeSchema };
22
+ const stateSchema = Type.Object({
23
+ notes: Type.Record(Type.String(), noteSchema),
24
+ receipts: Type.Record(Type.String(), Type.Object({
25
+ request: Type.Union([
26
+ Type.Object({ ...requestFields, action: Type.Literal("set"), purpose: purposeSchema }, { additionalProperties: false }),
27
+ Type.Object({ ...requestFields, action: Type.Literal("clear") }, { additionalProperties: false }),
28
+ ]),
29
+ result: Type.Array(noteSchema),
30
+ }, { additionalProperties: false })),
31
+ }, { additionalProperties: false });
32
+
33
+ function record(value: unknown): value is Record<string, unknown> {
34
+ return !!value && typeof value === "object" && !Array.isArray(value);
35
+ }
36
+
37
+ /** Parse the local IPC/tool boundary without accepting extra route selectors. */
38
+ export function discordPurposeRequest(value: unknown): DiscordPurposeRequest {
39
+ const reject = () => new DeliveryError("Invalid Discord purpose request", "rejected");
40
+ if (!record(value)) throw reject();
41
+ const data = value;
42
+ if (typeof data.sourceId !== "string" || !data.sourceId.trim() || data.sourceId.length > 1000 ||
43
+ !record(data.route)) throw reject();
44
+ const route = data.route;
45
+ if (route.platform !== "discord" || typeof route.accountId !== "string" || !route.accountId ||
46
+ typeof route.authorityId !== "string" || !route.authorityId || typeof route.channelId !== "string" || !route.channelId ||
47
+ !(route.guildId === null || typeof route.guildId === "string" && route.guildId.length > 0) ||
48
+ !(route.threadId === null || typeof route.threadId === "string" && route.threadId.length > 0) ||
49
+ route.guildId === null && route.threadId !== null ||
50
+ Object.keys(route).some(key => !["platform", "accountId", "authorityId", "guildId", "channelId", "threadId"].includes(key)) ||
51
+ Object.keys(data).some(key => !["sourceId", "route", "action", "purpose"].includes(key))) throw reject();
52
+ const destination: Route = { platform: "discord", accountId: route.accountId, authorityId: route.authorityId,
53
+ channelId: route.channelId, guildId: route.guildId, threadId: route.threadId };
54
+ const common = { sourceId: data.sourceId, route: destination };
55
+ switch (data.action) {
56
+ case "list":
57
+ case "clear":
58
+ if (Object.hasOwn(data, "purpose")) throw reject();
59
+ return { ...common, action: data.action };
60
+ case "set":
61
+ if (typeof data.purpose !== "string" || !data.purpose.trim() || data.purpose.length > 4000) throw reject();
62
+ return { ...common, action: "set", purpose: data.purpose };
63
+ default: throw reject();
64
+ }
65
+ }
66
+
67
+ /** Only the original conversation or its exact parent; never another allowed channel/sibling. */
68
+ export function authorizeDiscordPurpose(source: Route, destination: Route): void {
69
+ const parent = { ...physicalRoute(source), threadId: null };
70
+ if (source.platform !== "discord" || destination.platform !== "discord" ||
71
+ physicalRouteKey(destination) !== physicalRouteKey(source) && physicalRouteKey(destination) !== physicalRouteKey(parent)) {
72
+ throw new DeliveryError("Discord purpose destination is unrelated to the original source", "rejected");
73
+ }
74
+ }
75
+
76
+ function state(store: Metadata): Purposes {
77
+ const saved = store.getMeta(PURPOSES);
78
+ if (saved === null) return { notes: {}, receipts: {} };
79
+ const reject = () => new DeliveryError("Discord purpose state is damaged; existing notes were preserved", "rejected");
80
+ let parsed: unknown;
81
+ try { parsed = JSON.parse(saved); }
82
+ catch (error) { if (error instanceof SyntaxError) throw reject(); throw error; }
83
+ if (!Value.Check(stateSchema, parsed)) throw reject();
84
+ for (const [key, note] of Object.entries(parsed.notes))
85
+ if (key !== physicalRouteKey(note.route) || note.route.guildId === null && note.route.threadId !== null) throw reject();
86
+ for (const [key, receipt] of Object.entries(parsed.receipts))
87
+ if (key !== JSON.stringify([receipt.request.sourceId, physicalRouteKey(receipt.request.route)])) throw reject();
88
+ return parsed;
89
+ }
90
+
91
+ export function discordPurposeNotes(store: Metadata, route: Route): readonly DiscordPurposeNote[] {
92
+ const notes = state(store).notes;
93
+ const parent = { ...physicalRoute(route), threadId: null };
94
+ const keys = [...new Set([physicalRouteKey(parent), physicalRouteKey(route)])];
95
+ return keys.flatMap(key => notes[key] ? [notes[key]] : []);
96
+ }
97
+
98
+ /** One synchronous metadata write atomically preserves the note and its source-bound receipt. */
99
+ export function changeDiscordPurpose(store: Metadata, request: DiscordPurposeRequest): readonly DiscordPurposeNote[] {
100
+ if (request.action === "list") return discordPurposeNotes(store, request.route);
101
+ const previous = state(store);
102
+ const receiptKey = JSON.stringify([request.sourceId, physicalRouteKey(request.route)]);
103
+ const saved = previous.receipts[receiptKey];
104
+ if (saved) {
105
+ if (!isDeepStrictEqual(saved.request, request)) throw new DeliveryError("Discord purpose source identity conflict", "rejected");
106
+ return saved.result;
107
+ }
108
+ const notes = { ...previous.notes };
109
+ const key = physicalRouteKey(request.route);
110
+ switch (request.action) {
111
+ case "set": notes[key] = { route: physicalRoute(request.route), purpose: request.purpose }; break;
112
+ case "clear": delete notes[key]; break;
113
+ }
114
+ const parent = { ...physicalRoute(request.route), threadId: null };
115
+ const result = [...new Set([physicalRouteKey(parent), key])].flatMap(id => notes[id] ? [notes[id]] : []);
116
+ store.setMeta(PURPOSES, JSON.stringify({ notes, receipts: { ...previous.receipts, [receiptKey]: { request, result } } }));
117
+ return result;
118
+ }
@@ -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
+ }
@@ -0,0 +1,124 @@
1
+ import { ChannelType, MessageFlags, MessageReferenceType, MessageType, type Message, type TextChannel } from "discord.js";
2
+ import { DeliveryError } from "./delivery.ts";
3
+
4
+ const CONFIRM = "/voice confirm";
5
+ export const VOICE_DRAFT_HEADER = "Proposed work from the live voice session (not yet submitted).\n";
6
+ const PROPOSAL_TTL_MS = 5 * 60 * 1000;
7
+ const MESSAGE_LIMIT = 2000;
8
+
9
+ type PostedDraft = {
10
+ readonly id: string;
11
+ readonly createdTimestamp: number;
12
+ readonly accountId: string;
13
+ readonly ownerId: string;
14
+ readonly guildId: string;
15
+ readonly channelId: string;
16
+ readonly work: string;
17
+ };
18
+
19
+ type Draft = {
20
+ readonly signal: AbortSignal;
21
+ readonly startedAt: number;
22
+ readonly posted?: PostedDraft;
23
+ };
24
+
25
+ export class VoiceDrafts {
26
+ private draft: Draft | null = null;
27
+ private sending = false;
28
+
29
+ /** The caller supplies the session's already allowlisted, bound guild text channel. */
30
+ async propose(channel: TextChannel, ownerId: string, text: string, signal: AbortSignal): Promise<void> {
31
+ signal.throwIfAborted();
32
+ if (this.sending || this.current()) {
33
+ throw new DeliveryError("A voice work proposal is already outstanding.", "rejected");
34
+ }
35
+ const accountId = channel.client.user?.id;
36
+ if (!accountId || !channel.guildId || channel.type !== ChannelType.GuildText) {
37
+ throw new DeliveryError("Voice work proposals require a bound Discord guild text channel.", "rejected");
38
+ }
39
+ if (text.length > MESSAGE_LIMIT) {
40
+ throw new DeliveryError("Voice work proposal is too long to review in one Discord message.", "rejected");
41
+ }
42
+ const work = text.trim();
43
+ if (!work) throw new DeliveryError("Voice work proposal is empty.", "rejected");
44
+
45
+ // A fenced literal cannot render links, custom emoji or Discord mentions.
46
+ // Escape backticks, controls (including bidi overrides), and the escape
47
+ // character itself so the displayed text cannot impersonate the instructions.
48
+ const literal = work.replace(/[\\`\p{Cc}\p{Cf}\p{Cs}\p{Default_Ignorable_Code_Point}]/gu, character => character === "\n"
49
+ ? character : `\\u{${character.codePointAt(0)!.toString(16)}}`);
50
+ const content = VOICE_DRAFT_HEADER +
51
+ `\`\`\`\n${literal}\n\`\`\`\n` +
52
+ `To submit this proposal to HEAD, reply to this message with exactly \`${CONFIRM}\` ` +
53
+ "while the voice session is active and within five minutes.\n" +
54
+ "HEAD replies in Discord text. OpenAI Live does not receive the reply content. " +
55
+ "Risky actions still require separate approval.";
56
+ if (content.length > MESSAGE_LIMIT) {
57
+ throw new DeliveryError("Voice work proposal is too long to review in one Discord message.", "rejected");
58
+ }
59
+
60
+ const draft = { signal, startedAt: Date.now() };
61
+ const { guildId, id: channelId } = channel;
62
+ this.draft = draft;
63
+ this.sending = true;
64
+ try {
65
+ const sent = await channel.send({
66
+ content, allowedMentions: { parse: [], repliedUser: false }, flags: MessageFlags.SuppressEmbeds,
67
+ }).catch(() => {
68
+ // Discord may have posted the card despite the failure. Keep the slot
69
+ // until expiry or session end; never bind a guess to an unknown message.
70
+ throw new DeliveryError("Voice work proposal delivery is uncertain; it cannot be confirmed.", "uncertain");
71
+ });
72
+ if (this.current() !== draft) {
73
+ throw new DeliveryError("The voice work proposal is no longer active and cannot be confirmed.", "rejected");
74
+ }
75
+ if (!/^[0-9]{1,20}$/.test(sent.id) || sent.author.id !== accountId || !sent.author.bot ||
76
+ sent.channelId !== channelId || sent.guildId !== guildId || sent.content !== content ||
77
+ !Number.isSafeInteger(sent.createdTimestamp)) {
78
+ throw new DeliveryError("Discord did not verify the voice work proposal; it cannot be confirmed.", "uncertain");
79
+ }
80
+ this.draft = {
81
+ signal, startedAt: Date.now(),
82
+ posted: { id: sent.id, createdTimestamp: sent.createdTimestamp, accountId, ownerId, guildId, channelId, work },
83
+ };
84
+ } finally {
85
+ this.sending = false;
86
+ }
87
+ }
88
+
89
+ /** Call only for fresh MessageCreate events, never for updates or fetched history. */
90
+ consume(message: Message): string | null {
91
+ const draft = this.current()?.posted;
92
+ if (!draft || message.content !== CONFIRM || message.type !== MessageType.Reply ||
93
+ message.editedTimestamp !== null || message.webhookId !== null ||
94
+ message.author.id !== draft.ownerId || message.author.bot || message.client.user?.id !== draft.accountId ||
95
+ message.channelId !== draft.channelId || message.guildId !== draft.guildId ||
96
+ message.id === draft.id || message.createdTimestamp < draft.createdTimestamp ||
97
+ message.attachments.size || message.stickers.size || message.messageSnapshots.size) return null;
98
+
99
+ const reference = message.reference;
100
+ if (!reference || reference.messageId !== draft.id || reference.channelId !== draft.channelId ||
101
+ (reference.guildId !== undefined && reference.guildId !== draft.guildId) ||
102
+ (reference.type !== undefined && reference.type !== MessageReferenceType.Default)) return null;
103
+
104
+ this.clear();
105
+ return "Work proposed in a live Discord voice session and confirmed by the owner in writing.\n" +
106
+ "This is an ordinary work request, not a slash command, native control, or approval. " +
107
+ "Apply the usual safety and approval checks.\n\n" + draft.work;
108
+ }
109
+
110
+ clear(): void {
111
+ this.draft = null;
112
+ }
113
+
114
+ private current(): Draft | null {
115
+ const draft = this.draft;
116
+ if (!draft) return null;
117
+ const elapsed = Date.now() - draft.startedAt;
118
+ if (draft.signal.aborted || elapsed < 0 || elapsed >= PROPOSAL_TTL_MS) {
119
+ this.clear();
120
+ return null;
121
+ }
122
+ return draft;
123
+ }
124
+ }