omp-superagent 0.1.7 → 0.1.9

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 (122) hide show
  1. package/DESIGN.md +27 -16
  2. package/README.ko.md +40 -19
  3. package/README.md +43 -18
  4. package/THIRD_PARTY_NOTICES.md +11 -11
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +285 -85
  7. package/docs/design/execution.md +133 -24
  8. package/docs/design/messaging.md +235 -50
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/docs/releases/0.1.9.md +18 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  24. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  32. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  44. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  56. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  57. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  58. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  60. package/package.json +17 -15
  61. package/skills/head/SKILL.md +3 -11
  62. package/skills/head/references/routing.md +23 -17
  63. package/skills/head/references/supervision.md +13 -1
  64. package/skills/lane/references/workflow.md +8 -8
  65. package/src/cli.ts +6 -3
  66. package/src/config.ts +5 -0
  67. package/src/contracts.ts +95 -10
  68. package/src/cron-jobs.ts +443 -19
  69. package/src/cron-pr-intake.ts +257 -0
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +31 -3
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-quota.ts +80 -0
  75. package/src/head-recovery.ts +249 -1
  76. package/src/host-extension.ts +194 -5
  77. package/src/host-protocol.ts +16 -9
  78. package/src/host-sdk-helper.ts +105 -10
  79. package/src/host.ts +111 -29
  80. package/src/installed-omp.ts +116 -4
  81. package/src/lane-models.ts +8 -0
  82. package/src/managed-ulw-probe.ts +22 -20
  83. package/src/managed-ulw.ts +137 -24
  84. package/src/messenger-command-catalog.json +6 -3
  85. package/src/messenger-commands.ts +9 -2
  86. package/src/native-presets.ts +32 -5
  87. package/src/omp-usage.ts +254 -36
  88. package/src/operator.ts +77 -0
  89. package/src/pr-github-schema.ts +2 -0
  90. package/src/pr-github.ts +4 -2
  91. package/src/pr-intake-automation.ts +315 -0
  92. package/src/pr-intake-comment.ts +225 -0
  93. package/src/pr-intake-fix.ts +232 -0
  94. package/src/pr-intake-github.ts +479 -0
  95. package/src/pr-intake-material.ts +229 -0
  96. package/src/pr-intake-mode.ts +59 -0
  97. package/src/pr-intake-review.ts +397 -0
  98. package/src/pr-intake-tree.ts +68 -0
  99. package/src/pr-intake-work.ts +29 -0
  100. package/src/pr-review-models.ts +28 -0
  101. package/src/result-attachment.ts +60 -79
  102. package/src/runtime.ts +2968 -449
  103. package/src/setup-profiles.ts +26 -65
  104. package/src/slack-command-registration.ts +48 -197
  105. package/src/store.ts +507 -87
  106. package/src/superkit-skills.ts +22 -0
  107. package/src/telegram-command-languages.json +17 -0
  108. package/src/telegram-command-registration.ts +32 -134
  109. package/src/topic-history.ts +30 -17
  110. package/src/worker-bridge.ts +21 -0
  111. package/src/worker-enrollment.ts +2 -1
  112. package/src/worker-host.ts +0 -24
  113. package/src/worker-serve-prepare.ts +19 -0
  114. package/src/worker-service.ts +51 -47
  115. package/scripts/ci.ts +0 -44
  116. package/scripts/release.ts +0 -112
  117. package/scripts/test-omp.sh +0 -43
  118. package/src/discord-commands.ts +0 -29
  119. package/src/discord-markdown.ts +0 -172
  120. package/src/slack-commands.ts +0 -18
  121. package/src/telegram-signal.ts +0 -14
  122. package/src/worker-stdio.ts +0 -61
@@ -1,85 +1,46 @@
1
- import { readFileSync } from "node:fs";
2
- import type { REST, RESTOptions } from "discord.js";
3
- import type { Api } from "grammy";
4
1
  import type { Config } from "./config";
5
2
  import { validateCredential } from "./credentials";
6
-
7
- const avatar = new URL("../assets/superagent-avatar.jpg", import.meta.url);
3
+ import { OperatorStartError, runOperator, type OperatorRun } from "./operator";
8
4
 
9
5
  interface ProfileOptions {
10
- signal?: AbortSignal;
11
- createRest?: (options: Partial<RESTOptions>, token: string) => Pick<REST, "get" | "patch">;
12
- createApi?: (token: string) => Pick<Api, "getMe" | "setMyProfilePhoto" | "getUserProfilePhotos">;
6
+ readonly signal?: AbortSignal;
7
+ readonly run?: OperatorRun;
13
8
  }
14
9
 
15
10
  interface ProfileResult {
16
- platform: "discord" | "telegram";
17
- status: "applied" | "failed";
18
- message: string;
11
+ readonly platform: "discord" | "telegram";
12
+ readonly status: "applied" | "failed";
13
+ readonly message: string;
19
14
  }
20
15
 
21
- /** One-shot profile REST calls only; never starts a messenger or native session. */
16
+ /** One-shot native API workflows only; never starts a messenger or OMP session. */
22
17
  export async function setupBotProfiles(
23
18
  config: Config, credentials: Readonly<Record<string, string>>, options: ProfileOptions = {},
24
19
  ): Promise<ProfileResult[]> {
25
20
  const results: ProfileResult[] = [];
26
- if (!config.discord && !config.telegram) return results;
27
- const image = readFileSync(avatar);
28
- if (config.discord) {
29
- options.signal?.throwIfAborted();
30
- let attempted = false;
21
+ if (config.discord) options.signal?.throwIfAborted();
22
+ for (const [platform, service] of [["discord", config.discord], ["telegram", config.telegram]] as const) {
23
+ if (options.signal?.aborted) break;
24
+ if (!service) continue;
25
+ const name = platform === "discord" ? "Discord" : "Telegram";
26
+ const inspection = `Profile inspection failed; no ${name} profile update was attempted. Credential/API details suppressed.`;
27
+ const unresolved = `Profile update is unresolved; it may have reached ${name}. No automatic retry was attempted; API details suppressed.`;
28
+ const bot = credentials[service.tokenEnv] ?? "";
31
29
  try {
32
- const token = credentials[config.discord.tokenEnv]!;
33
- validateCredential(token);
34
- const { REST, Routes } = await import("discord.js");
35
- const rest = (options.createRest ?? ((settings, credential) => new REST(settings).setToken(credential)))(
36
- { version: "10", retries: 0, rejectOnRateLimit: () => true }, token,
37
- );
38
- const bot = await rest.get(Routes.user("@me"), { signal: options.signal }) as { id: string; bot?: boolean };
39
- if (bot.bot !== true || typeof bot.id !== "string" || !/^\d+$/.test(bot.id) || bot.id === config.discord.ownerId)
40
- throw new Error("Invalid bot identity");
41
- attempted = true;
42
- const updated = await rest.patch(Routes.user("@me"), {
43
- signal: options.signal,
44
- body: { avatar: `data:image/jpeg;base64,${image.toString("base64")}` },
45
- }) as { id: string; avatar?: string | null };
46
- if (updated.id !== bot.id || !updated.avatar) throw new Error("Missing profile receipt");
47
- const current = await rest.get(Routes.user("@me"), { signal: options.signal }) as { id: string; bot?: boolean; avatar?: string | null };
48
- if (current.id !== bot.id || current.bot !== true || current.avatar !== updated.avatar)
49
- throw new Error("Profile readback differs");
50
- results.push({ platform: "discord", status: "applied", message: "Mascot profile picture applied and verified by Discord profile readback." });
30
+ validateCredential(bot);
51
31
  } catch {
52
- results.push({ platform: "discord", status: "failed", message: attempted
53
- ? "Profile update is unresolved; it may have reached Discord. No automatic retry was attempted; API details suppressed."
54
- : "Profile inspection failed; no Discord profile update was attempted. Credential/API details suppressed." });
32
+ results.push({ platform, status: "failed", message: inspection });
33
+ continue;
55
34
  }
56
- }
57
- if (config.telegram) {
58
- if (options.signal?.aborted) return results;
59
- let attempted = false;
60
35
  try {
61
- const token = credentials[config.telegram.tokenEnv]!;
62
- validateCredential(token);
63
- const { Api, InputFile } = await import("grammy");
64
- const { withTelegramSignal } = await import("./telegram-signal");
65
- const api = (options.createApi ?? (credential => new Api(credential, {
66
- sensitiveLogs: false, timeoutSeconds: 45, baseFetchConfig: { redirect: "error" },
67
- })))(token);
68
- const bot = await withTelegramSignal(options.signal, signal => api.getMe(signal));
69
- if (!bot.is_bot || !Number.isSafeInteger(bot.id) || bot.id <= 0 || String(bot.id) === config.telegram.ownerId)
70
- throw new Error("Invalid bot identity");
71
- attempted = true;
72
- if (await withTelegramSignal(options.signal, signal =>
73
- api.setMyProfilePhoto({ type: "static", photo: new InputFile(image, "superagent-avatar.jpg") }, signal)) !== true)
74
- throw new Error("Missing profile receipt");
75
- const current = await withTelegramSignal(options.signal, signal => api.getUserProfilePhotos(bot.id, { limit: 1 }, signal));
76
- if (current.total_count < 1 || !current.photos[0]?.some(photo => photo.file_id && photo.file_unique_id))
77
- throw new Error("Missing profile readback");
78
- results.push({ platform: "telegram", status: "applied", message: "Mascot upload accepted by Telegram; current profile photo confirmed by getUserProfilePhotos." });
79
- } catch {
80
- results.push({ platform: "telegram", status: "failed", message: attempted
81
- ? "Profile update is unresolved; it may have reached Telegram. No automatic retry was attempted; API details suppressed."
82
- : "Profile inspection failed; no Telegram profile update was attempted. Credential/API details suppressed." });
36
+ const run = options.run ?? runOperator;
37
+ results.push(await run<ProfileResult>(`${platform}-avatar`, { ownerId: service.ownerId }, { bot }, options.signal));
38
+ } catch (error) {
39
+ // Cancellation after dispatch can interrupt a write; no retry or next platform.
40
+ const beforeWrite = error instanceof OperatorStartError ||
41
+ (error instanceof Error && error.message === inspection);
42
+ const message = beforeWrite ? inspection : unresolved;
43
+ results.push({ platform, status: "failed", message });
83
44
  }
84
45
  }
85
46
  return results;
@@ -1,217 +1,68 @@
1
- import { LogLevel, WebClient, type WebClientOptions } from "@slack/web-api";
2
1
  import type { Config } from "./config";
3
2
  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
- }
3
+ import { runOperator, type OperatorRun } from "./operator";
11
4
 
12
5
  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;
6
+ readonly apply?: boolean;
7
+ /** Explicit app-configuration credential from an environment name or the sibling private file. */
8
+ readonly manifestTokenEnv: string;
9
+ readonly run?: OperatorRun;
17
10
  }
18
11
 
19
12
  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;
13
+ readonly status: "dry-run" | "applied";
14
+ readonly teamId: string;
15
+ readonly botId: string;
16
+ readonly botUserId: string;
17
+ readonly appId: string;
18
+ readonly currentCommands: readonly string[];
19
+ readonly obsoleteCommands: readonly string[];
20
+ readonly plannedCommands: readonly {
21
+ readonly command: string;
22
+ readonly description: string;
23
+ readonly usage_hint?: string;
24
+ readonly should_escape: boolean;
25
+ }[];
26
+ readonly changed: boolean;
27
+ readonly updated: boolean;
28
+ readonly manifestReadbackMatched: boolean;
29
+ readonly commandsGrant: "granted" | "missing" | "unknown";
30
+ readonly requiresReinstall: boolean | null;
31
+ readonly permissionsUpdated: boolean | null;
32
+ readonly note: string;
56
33
  }
57
34
 
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
- }
35
+ const envName = /^[A-Za-z_][A-Za-z0-9_]*$/;
96
36
 
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. */
37
+ /** Resolve only the bot and explicitly selected configuration credential. */
110
38
  export async function registerSlackCommands(
111
39
  config: Config, options: SlackCommandRegistrationOptions,
112
40
  ): Promise<SlackCommandRegistrationReport> {
113
41
  const policy = config.slack;
114
42
  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;
43
+ const name = options.manifestTokenEnv;
44
+ if (typeof name !== "string" || !envName.test(name))
45
+ throw new Error("slack-commands requires --manifest-token-env NAME naming an app configuration credential");
46
+ if (typeof policy.botTokenEnv !== "string" || !envName.test(policy.botTokenEnv) ||
47
+ typeof policy.teamId !== "string" || !/^T[A-Z0-9]+$/.test(policy.teamId))
48
+ throw new Error("Invalid Slack bot credential name or workspace policy");
49
+ if (name === policy.appTokenEnv || name === policy.botTokenEnv)
50
+ throw new Error("A distinct explicit Slack app configuration credential is required");
51
+ let bot: string;
52
+ let manifest: string;
119
53
  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] || "";
54
+ const botEnv = process.env[policy.botTokenEnv];
55
+ const manifestEnv = process.env[name];
56
+ const file = !botEnv || !manifestEnv ? readCredentialFile(config.path) : undefined;
57
+ bot = botEnv || file?.values[policy.botTokenEnv] || "";
58
+ manifest = manifestEnv || file?.values[name] || "";
125
59
  } 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); }
60
+ if (!bot) throw new Error("Configured Slack bot credential is missing");
61
+ if (!manifest) throw new Error("Explicit Slack app configuration credential is missing; set the named environment variable or its private sibling credential entry");
62
+ try { validateCredential(bot); validateCredential(manifest); }
129
63
  catch { throw new Error("Configured Slack credential is invalid; values suppressed"); }
130
64
 
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]);
65
+ return (options.run ?? runOperator)<SlackCommandRegistrationReport>(
66
+ "slack-commands", { teamId: policy.teamId, apply: options.apply === true }, { bot, manifest },
67
+ );
217
68
  }