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.
Files changed (76) hide show
  1. package/DESIGN.md +1361 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +184 -0
  4. package/README.md +205 -2
  5. package/THIRD_PARTY_NOTICES.md +313 -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 +1030 -0
  12. package/docs/releases/0.1.0.md +222 -0
  13. package/docs/releases/0.1.1.md +60 -0
  14. package/package.json +59 -4
  15. package/scripts/check-omp.ts +4 -0
  16. package/scripts/ci.ts +28 -0
  17. package/scripts/prepare-ulw.ts +18 -0
  18. package/scripts/release.ts +50 -0
  19. package/scripts/setup.sh +25 -0
  20. package/skills/head/SKILL.md +259 -0
  21. package/skills/head/references/model-selection.md +263 -0
  22. package/skills/head/references/routing.md +356 -0
  23. package/skills/head/references/supervision.md +312 -0
  24. package/skills/lane/SKILL.md +188 -0
  25. package/skills/lane/references/workflow.md +349 -0
  26. package/src/autostart.ts +295 -0
  27. package/src/board-extension.ts +217 -0
  28. package/src/board.ts +396 -0
  29. package/src/cli.ts +167 -0
  30. package/src/config.ts +191 -0
  31. package/src/contracts.ts +317 -0
  32. package/src/credentials.ts +172 -0
  33. package/src/delivery.ts +7 -0
  34. package/src/dialog.ts +73 -0
  35. package/src/discord-command-registration.ts +201 -0
  36. package/src/discord-commands.ts +29 -0
  37. package/src/discord-markdown.ts +172 -0
  38. package/src/discord.ts +745 -0
  39. package/src/extension.ts +289 -0
  40. package/src/gateway-client.ts +222 -0
  41. package/src/gateway-protocol.ts +85 -0
  42. package/src/gateway-restart.ts +151 -0
  43. package/src/gateway-server.ts +392 -0
  44. package/src/gateway-store.ts +237 -0
  45. package/src/gateway.ts +638 -0
  46. package/src/head-recovery.ts +61 -0
  47. package/src/host-extension.ts +449 -0
  48. package/src/host-owner.ts +350 -0
  49. package/src/host-protocol.ts +136 -0
  50. package/src/host.ts +414 -0
  51. package/src/installed-omp.ts +63 -0
  52. package/src/lane-extension.ts +179 -0
  53. package/src/lane-models.ts +75 -0
  54. package/src/lane-report.ts +70 -0
  55. package/src/managed-ulw-probe.ts +172 -0
  56. package/src/managed-ulw.ts +471 -0
  57. package/src/message-order.ts +21 -0
  58. package/src/messenger-commands.ts +16 -0
  59. package/src/messengers.ts +114 -0
  60. package/src/native-presets.ts +282 -0
  61. package/src/native-sessions.ts +32 -0
  62. package/src/native-settings.ts +129 -0
  63. package/src/repository.ts +12 -0
  64. package/src/runtime.ts +3864 -0
  65. package/src/setup-judge.ts +34 -0
  66. package/src/setup-memory.ts +39 -0
  67. package/src/setup-profiles.ts +84 -0
  68. package/src/setup.ts +300 -0
  69. package/src/slack-command-registration.ts +217 -0
  70. package/src/slack-commands.ts +18 -0
  71. package/src/slack.ts +776 -0
  72. package/src/store.ts +806 -0
  73. package/src/telegram-command-registration.ts +155 -0
  74. package/src/telegram.ts +661 -0
  75. package/src/workflow.ts +94 -0
  76. package/upstream/ulw.json +9 -0
@@ -0,0 +1,217 @@
1
+ import { LogLevel, WebClient, type WebClientOptions } from "@slack/web-api";
2
+ import type { Config } from "./config";
3
+ import { readCredentialFile, validateCredential } from "./credentials";
4
+ import { SLACK_COMMANDS } from "./slack-commands";
5
+
6
+ export interface SlackCommandClient {
7
+ auth: Pick<WebClient["auth"], "test">;
8
+ bots: Pick<WebClient["bots"], "info">;
9
+ apps: { manifest: Pick<WebClient["apps"]["manifest"], "export" | "validate" | "update"> };
10
+ }
11
+
12
+ export interface SlackCommandRegistrationOptions {
13
+ apply?: boolean;
14
+ /** Explicit app-configuration credential, from this environment name or the sibling private credential file. */
15
+ manifestTokenEnv: string;
16
+ createWebClient?: (token: string, options: WebClientOptions) => SlackCommandClient;
17
+ }
18
+
19
+ export interface SlackCommandRegistrationReport {
20
+ status: "dry-run" | "applied";
21
+ teamId: string;
22
+ botId: string;
23
+ botUserId: string;
24
+ appId: string;
25
+ currentCommands: string[];
26
+ obsoleteCommands: string[];
27
+ plannedCommands: typeof SLACK_COMMANDS;
28
+ changed: boolean;
29
+ updated: boolean;
30
+ manifestReadbackMatched: boolean;
31
+ commandsGrant: "granted" | "missing" | "unknown";
32
+ requiresReinstall: boolean | null;
33
+ permissionsUpdated: boolean | null;
34
+ note: string;
35
+ }
36
+
37
+ type ObjectValue = Record<string, unknown>;
38
+ type Manifest = Parameters<WebClient["apps"]["manifest"]["update"]>[0]["manifest"];
39
+ const object = (value: unknown): value is ObjectValue => !!value && typeof value === "object" && !Array.isArray(value);
40
+ const id = (value: unknown, prefix: string): value is string => typeof value === "string" && new RegExp(`^${prefix}[A-Z0-9]+$`).test(value);
41
+ const envName = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
42
+
43
+ function exportedManifest(value: unknown): Manifest {
44
+ if (!object(value) || !object(value.display_information) || typeof value.display_information.name !== "string" ||
45
+ !value.display_information.name || !object(value.settings) || value.settings.socket_mode_enabled !== true) throw new Error("Invalid Socket Mode manifest");
46
+ for (const key of ["features", "oauth_config"] as const) {
47
+ if (value[key] !== undefined && !object(value[key])) throw new Error("Invalid manifest object");
48
+ }
49
+ if (object(value.oauth_config) && value.oauth_config.scopes !== undefined && !object(value.oauth_config.scopes)) throw new Error("Invalid scopes");
50
+ const scopes = object(value.oauth_config) && object(value.oauth_config.scopes) ? value.oauth_config.scopes : {};
51
+ if (scopes.bot !== undefined && (!Array.isArray(scopes.bot) || !scopes.bot.every(scope => typeof scope === "string"))) throw new Error("Invalid bot scopes");
52
+ const commands = object(value.features) ? value.features.slash_commands : undefined;
53
+ if (commands !== undefined && (!Array.isArray(commands) || !commands.every(command => object(command) &&
54
+ typeof command.command === "string" && /^\/[a-z0-9_-]{1,31}$/.test(command.command) && typeof command.description === "string"))) throw new Error("Invalid command list");
55
+ return structuredClone(value) as Manifest;
56
+ }
57
+
58
+ // These are disabled/empty API defaults, not a blanket removal of false or empty
59
+ // values: unknown future fields and function/workflow definitions remain exact.
60
+ const emptyDefaults: Record<string, unknown> = {
61
+ "_metadata.major_version": 1,
62
+ "display_information.description": "", "display_information.long_description": "",
63
+ "features.app_home.home_tab_enabled": false, "features.app_home.messages_tab_enabled": false,
64
+ "features.app_home.messages_tab_read_only_enabled": false, "features.bot_user.always_online": false,
65
+ "features.slash_commands.*.should_escape": false, "features.slash_commands.*.usage_hint": "", "features.slash_commands.*.url": "",
66
+ "settings.org_deploy_enabled": false, "settings.token_rotation_enabled": false, "settings.is_hosted": false,
67
+ "settings.interactivity.is_enabled": false, "settings.incoming_webhooks.incoming_webhooks_enabled": false,
68
+ };
69
+ const unordered = new Set([
70
+ "oauth_config.redirect_urls", "oauth_config.scopes.bot", "oauth_config.scopes.user",
71
+ "oauth_config.scopes.bot_optional", "oauth_config.scopes.user_optional",
72
+ "settings.allowed_ip_address_ranges", "settings.event_subscriptions.bot_events", "settings.event_subscriptions.user_events",
73
+ "features.unfurl_domains",
74
+ ]);
75
+ const emptyContainers = new Set([
76
+ "_metadata", "features", "features.app_home", "features.slash_commands", "features.shortcuts", "features.workflow_steps",
77
+ "oauth_config", "oauth_config.scopes", "settings", "settings.event_subscriptions", "settings.interactivity", "settings.incoming_webhooks",
78
+ ]);
79
+
80
+ function normalized(value: unknown, path = ""): unknown {
81
+ if (Object.hasOwn(emptyDefaults, path) && value === emptyDefaults[path]) return undefined;
82
+ if (Array.isArray(value)) {
83
+ const result = value.map(item => normalized(item, `${path}.*`));
84
+ if (!result.length && (unordered.has(path) || emptyContainers.has(path))) return undefined;
85
+ if (unordered.has(path) || path === "features.slash_commands") result.sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
86
+ return result;
87
+ }
88
+ if (!object(value)) return value;
89
+ const result: ObjectValue = {};
90
+ for (const key of Object.keys(value).sort()) {
91
+ const item = normalized(value[key], path ? `${path}.${key}` : key);
92
+ if (item !== undefined) result[key] = item;
93
+ }
94
+ return !Object.keys(result).length && emptyContainers.has(path) ? undefined : result;
95
+ }
96
+
97
+ function exact(actual: Manifest, expected: Manifest): boolean {
98
+ return JSON.stringify(normalized(actual)) === JSON.stringify(normalized(expected));
99
+ }
100
+
101
+ function redact<T>(value: T, secrets: string[]): T {
102
+ if (typeof value === "string") return secrets.reduce((text, secret) => text.replaceAll(secret, "[redacted]"), value)
103
+ .replace(/(?:https?|wss?):\/\/\S+/gi, "[redacted-url]") as T;
104
+ if (Array.isArray(value)) return value.map(item => redact(item, secrets)) as T;
105
+ if (object(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redact(item, secrets)])) as T;
106
+ return value;
107
+ }
108
+
109
+ /** Official API only. No socket, runtime activation, token parsing, or automatic retries. */
110
+ export async function registerSlackCommands(
111
+ config: Config, options: SlackCommandRegistrationOptions,
112
+ ): Promise<SlackCommandRegistrationReport> {
113
+ const policy = config.slack;
114
+ if (!policy) throw new Error("slack-commands requires configured Slack credentials and policy");
115
+ if (!envName(options.manifestTokenEnv)) throw new Error("slack-commands requires --manifest-token-env NAME naming an app configuration credential");
116
+ if (!envName(policy.botTokenEnv) || !id(policy.teamId, "T")) throw new Error("Invalid Slack bot credential name or workspace policy");
117
+ let botToken: string;
118
+ let manifestToken: string;
119
+ try {
120
+ // Resolve only the bot and explicitly selected configuration credential. Never
121
+ // load Discord, Telegram, the Socket Mode app token, or unrelated dotenv keys.
122
+ const file = !process.env[policy.botTokenEnv] || !process.env[options.manifestTokenEnv] ? readCredentialFile(config.path) : undefined;
123
+ botToken = process.env[policy.botTokenEnv] || file?.values[policy.botTokenEnv] || "";
124
+ manifestToken = process.env[options.manifestTokenEnv] || file?.values[options.manifestTokenEnv] || "";
125
+ } catch { throw new Error("Cannot safely load configured Slack credentials; details suppressed"); }
126
+ if (!botToken) throw new Error("Configured Slack bot credential is missing");
127
+ if (!manifestToken) throw new Error("Explicit Slack app configuration credential is missing; set the named environment variable or its private sibling credential entry");
128
+ try { validateCredential(botToken); validateCredential(manifestToken); }
129
+ catch { throw new Error("Configured Slack credential is invalid; values suppressed"); }
130
+
131
+ let bot: SlackCommandClient;
132
+ let app: SlackCommandClient;
133
+ try {
134
+ const logger = { debug() {}, info() {}, warn() {}, error() {}, setLevel(_level: LogLevel) {}, getLevel: () => LogLevel.ERROR, setName(_name: string) {} };
135
+ const settings: WebClientOptions = { retryConfig: { retries: 0 }, rejectRateLimitedCalls: true, allowAbsoluteUrls: false, logger };
136
+ const create = options.createWebClient ?? ((token, settings) => new WebClient(token, settings));
137
+ bot = create(botToken, { ...settings, teamId: policy.teamId });
138
+ app = create(manifestToken, settings);
139
+ } catch { throw new Error("Slack API initialization failed; details suppressed"); }
140
+
141
+ let teamId: string;
142
+ let botId: string;
143
+ let botUserId: string;
144
+ let appId: string;
145
+ let current: Manifest;
146
+ let commandsGrant: SlackCommandRegistrationReport["commandsGrant"] = "unknown";
147
+ try {
148
+ const identity = await bot.auth.test();
149
+ if (identity.ok !== true || identity.team_id !== policy.teamId || !id(identity.bot_id, "B") || !id(identity.user_id, "[UW]")) throw new Error("Wrong bot identity");
150
+ const result = await bot.bots.info({ bot: identity.bot_id, team_id: policy.teamId });
151
+ if (result.ok !== true || !result.bot || result.bot.id !== identity.bot_id || result.bot.user_id !== identity.user_id ||
152
+ result.bot.deleted === true || !id(result.bot.app_id, "A") || (identity.app_id !== undefined && identity.app_id !== result.bot.app_id)) throw new Error("Wrong app identity");
153
+ teamId = identity.team_id;
154
+ botId = identity.bot_id;
155
+ botUserId = identity.user_id;
156
+ appId = result.bot.app_id;
157
+ // The SDK obtains this from Slack's x-oauth-scopes response header, not the
158
+ // manifest's requested scopes (which say nothing about installed grants).
159
+ const grants = identity.response_metadata?.scopes ?? result.response_metadata?.scopes;
160
+ if (Array.isArray(grants) && grants.every(scope => typeof scope === "string")) commandsGrant = grants.includes("commands") ? "granted" : "missing";
161
+ const response = await app.apps.manifest.export({ app_id: appId });
162
+ if (response.ok !== true) throw new Error("Export failed");
163
+ current = exportedManifest(response.manifest);
164
+ } catch {
165
+ throw new Error("Slack command inspection failed: configured workspace, bot/app identity, Socket Mode, or manifest export could not be verified. No mutation was attempted; raw API details suppressed. No automatic retry was attempted.");
166
+ }
167
+
168
+ const intended = structuredClone(current);
169
+ intended.features = { ...intended.features, slash_commands: structuredClone(SLACK_COMMANDS) };
170
+ intended.oauth_config = { ...intended.oauth_config, scopes: {
171
+ ...intended.oauth_config?.scopes,
172
+ bot: [...new Set([...(intended.oauth_config?.scopes?.bot ?? []), "commands" as const])],
173
+ } };
174
+ const currentCommands = current.features?.slash_commands?.map(command => command.command) ?? [];
175
+ const supported = new Set(SLACK_COMMANDS.map(command => command.command));
176
+ const changed = !exact(current, intended);
177
+ let updated = false;
178
+ let permissionsUpdated: boolean | null = null;
179
+ let manifestReadbackMatched = !changed;
180
+ if (options.apply === true && changed) {
181
+ try {
182
+ const validation = await app.apps.manifest.validate({ app_id: appId, manifest: intended });
183
+ if (validation.ok !== true || (validation.errors !== undefined && (!Array.isArray(validation.errors) || validation.errors.length))) throw new Error("Invalid manifest");
184
+ } catch {
185
+ throw new Error("Slack manifest validation failed. No mutation was attempted; raw API details suppressed. The explicit configuration credential needs app_configurations:write. No automatic retry was attempted.");
186
+ }
187
+ try {
188
+ const response = await app.apps.manifest.update({ app_id: appId, manifest: intended });
189
+ if (response.ok !== true || response.app_id !== appId || typeof response.permissions_updated !== "boolean") throw new Error("Uncertain update response");
190
+ permissionsUpdated = response.permissions_updated;
191
+ updated = true;
192
+ } catch {
193
+ throw new Error("Slack manifest update outcome is uncertain; the app may have changed. Inspect its authoritative manifest before another apply. Raw API details suppressed; no automatic retry was attempted.");
194
+ }
195
+ try {
196
+ const response = await app.apps.manifest.export({ app_id: appId });
197
+ if (response.ok !== true || !exact(exportedManifest(response.manifest), intended)) throw new Error("Readback differs");
198
+ manifestReadbackMatched = true;
199
+ } catch {
200
+ throw new Error("Slack manifest update may have succeeded, but authoritative readback failed or differed from the intended commands or unrelated configuration. Outcome uncertain; inspect the app before another apply. Raw API details suppressed; no automatic retry was attempted.");
201
+ }
202
+ }
203
+ const requiresReinstall = permissionsUpdated === true || commandsGrant === "missing" ? true : commandsGrant === "unknown" ? null : false;
204
+ return redact({
205
+ status: options.apply === true ? "applied" : "dry-run", teamId, botId, botUserId, appId,
206
+ currentCommands, obsoleteCommands: currentCommands.filter(command => !supported.has(command)),
207
+ plannedCommands: structuredClone(SLACK_COMMANDS), changed, updated, manifestReadbackMatched, commandsGrant, requiresReinstall, permissionsUpdated,
208
+ note: [
209
+ options.apply === true ? "The exported app configuration matches the supported commands." : "Dry-run: API reads and local comparison only; apply replaces this exact app's slash command list, including obsolete Hermes commands.",
210
+ "All unrelated manifest fields and existing scopes are preserved. Socket Mode must already be enabled; no HTTP request URLs are invented.",
211
+ requiresReinstall === true ? "Reinstall or reauthorize the app in the configured workspace to grant the required permissions; registration does not establish active command delivery." :
212
+ requiresReinstall === null ? "Installed commands scope could not be confirmed; check grants and reinstall or reauthorize if needed. Active command delivery is not verified." :
213
+ "The configured bot reports the commands grant; active Socket Mode command delivery is not verified.",
214
+ "Configuration credentials require app_configurations:read, plus app_configurations:write for apply. Bot identity inspection requires users:read. No socket or runtime was started.",
215
+ ].join(" "),
216
+ } satisfies SlackCommandRegistrationReport, [botToken, manifestToken]);
217
+ }
@@ -0,0 +1,18 @@
1
+ import { MESSENGER_COMMANDS } from "./messenger-commands";
2
+
3
+ /** Slack reserves /help and /status, so every supported picker entry is namespaced. */
4
+ export const SLACK_COMMANDS = MESSENGER_COMMANDS.map(command => ({
5
+ command: `/superagent-${command.name}`,
6
+ description: command.description,
7
+ ...("text" in command ? { usage_hint: command.text } : {}),
8
+ should_escape: false,
9
+ }));
10
+
11
+ /** Only registered names are accepted; invalid no-argument invocations are not commands. */
12
+ export function parseSlackCommand(name: string, text: string): string | null {
13
+ const command = MESSENGER_COMMANDS.find(command => name === `/superagent-${command.name}`);
14
+ if (!command) return null;
15
+ const argument = text.trim();
16
+ if (argument && !("text" in command)) return null;
17
+ return `/${command.name}${argument ? ` ${argument}` : ""}`;
18
+ }