omp-superagent 0.1.8 → 0.1.10

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 (116) hide show
  1. package/DESIGN.md +16 -8
  2. package/README.ko.md +28 -374
  3. package/README.md +30 -421
  4. package/THIRD_PARTY_NOTICES.md +8 -8
  5. package/config.example.json +7 -0
  6. package/docs/OPERATIONS.en.md +2223 -0
  7. package/docs/OPERATIONS.md +164 -23
  8. package/docs/design/execution.md +164 -18
  9. package/docs/design/messaging.md +78 -17
  10. package/docs/kakao-bridge-protocol.md +193 -0
  11. package/docs/releases/0.1.10.md +17 -0
  12. package/docs/releases/0.1.9.md +18 -0
  13. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  14. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  16. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  24. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  32. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  44. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  48. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  52. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  56. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  57. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  58. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  60. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  61. package/package.json +10 -8
  62. package/skills/head/SKILL.md +28 -14
  63. package/skills/head/references/routing.md +23 -17
  64. package/skills/head/references/supervision.md +22 -1
  65. package/skills/lane/SKILL.md +11 -0
  66. package/skills/lane/references/workflow.md +17 -8
  67. package/src/cli.ts +6 -4
  68. package/src/config.ts +44 -3
  69. package/src/contracts.ts +101 -8
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +44 -6
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-recovery.ts +226 -17
  75. package/src/host-extension.ts +132 -17
  76. package/src/host-protocol.ts +6 -9
  77. package/src/host-reply-voice.ts +181 -0
  78. package/src/lane-extension.ts +46 -8
  79. package/src/lane-models.ts +8 -0
  80. package/src/lane-report.ts +22 -0
  81. package/src/managed-ulw-probe.ts +22 -20
  82. package/src/message-order.ts +2 -1
  83. package/src/messenger-command-catalog.json +6 -3
  84. package/src/messenger-commands.ts +9 -2
  85. package/src/operator.ts +77 -0
  86. package/src/pr-github-schema.ts +2 -0
  87. package/src/pr-intake-automation.ts +1 -2
  88. package/src/pr-intake-comment.ts +1 -2
  89. package/src/pr-intake-fix.ts +1 -2
  90. package/src/pr-intake-github.ts +1 -2
  91. package/src/pr-intake-material.ts +1 -2
  92. package/src/pr-intake-tree.ts +1 -2
  93. package/src/pr-review-models.ts +28 -0
  94. package/src/result-attachment.ts +60 -79
  95. package/src/runtime.ts +1862 -298
  96. package/src/setup-profiles.ts +26 -65
  97. package/src/setup.ts +2 -1
  98. package/src/slack-command-registration.ts +48 -197
  99. package/src/soul.ts +214 -0
  100. package/src/store.ts +643 -55
  101. package/src/superkit-skills.ts +22 -0
  102. package/src/telegram-command-languages.json +17 -0
  103. package/src/telegram-command-registration.ts +32 -134
  104. package/src/worker-bridge.ts +21 -0
  105. package/src/worker-enrollment.ts +2 -1
  106. package/src/worker-host.ts +0 -24
  107. package/src/worker-serve-prepare.ts +19 -0
  108. package/src/worker-service.ts +51 -47
  109. package/scripts/ci.ts +0 -44
  110. package/scripts/release.ts +0 -112
  111. package/scripts/test-omp.sh +0 -44
  112. package/src/discord-commands.ts +0 -29
  113. package/src/discord-markdown.ts +0 -399
  114. package/src/slack-commands.ts +0 -18
  115. package/src/telegram-signal.ts +0 -14
  116. 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;
package/src/setup.ts CHANGED
@@ -125,7 +125,8 @@ async function newConfig(terminal: Terminal, path: string): Promise<{ config: Co
125
125
  if (!selected.length || selected.some(p => !["discord", "telegram", "slack"].includes(p)))
126
126
  throw new Error("Select at least one supported messenger");
127
127
  const raw: Record<string, unknown> = { ...template, command };
128
- for (const platform of ["discord", "telegram", "slack"]) delete raw[platform];
128
+ // Kakao needs an operator-run bridge; add its block manually (docs/kakao-bridge-protocol.md).
129
+ for (const platform of ["discord", "telegram", "slack", "kakao"]) delete raw[platform];
129
130
  const list = async (label: string) => (await terminal.ask(`${label} (comma-separated; empty = deny groups / DM only): `))
130
131
  .split(",").map(s => s.trim()).filter(Boolean);
131
132
  for (const platform of selected) {
@@ -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
  }
package/src/soul.ts ADDED
@@ -0,0 +1,214 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { Inbound, StorePort } from "./contracts";
3
+ import { ownerRoutingProse, transportRoutingProse } from "./topic-history";
4
+
5
+ const dimensions = {
6
+ concept: {
7
+ plain: "",
8
+ editorial: "Use an editorial presentation: distill the relevant points and make distinctions precise within the requested format.",
9
+ mentoring: "Use a mentoring presentation: make the reasoning easy to follow and use a concrete example when it fits the requested format.",
10
+ },
11
+ tone: {
12
+ direct: "Be candid and matter-of-fact without being curt.",
13
+ warm: "Sound warm and approachable without adding filler.",
14
+ neutral: "Use a calm, neutral tone.",
15
+ },
16
+ register: {
17
+ natural: "Match the operator's register.",
18
+ formal: "Use a respectful, formal register (존댓말 in Korean).",
19
+ casual: "Use a relaxed, conversational register.",
20
+ },
21
+ detail: {
22
+ balanced: "Give the context needed to use the answer.",
23
+ brief: "Keep the answer brief unless the operator asks for depth.",
24
+ detailed: "Include relevant context and explanation.",
25
+ },
26
+ structure: {
27
+ "answer-first": "Lead with the answer, result, or blocker.",
28
+ "evidence-first": "Present the key evidence before the conclusion.",
29
+ natural: "Organize the answer naturally for the question.",
30
+ },
31
+ emoji: {
32
+ none: "Do not add decorative emoji.",
33
+ light: "Use an occasional emoji only where it reads naturally.",
34
+ },
35
+ } as const;
36
+
37
+ type Voice = { [D in keyof typeof dimensions]: keyof typeof dimensions[D] };
38
+ const requests = {
39
+ concept: {
40
+ plain: /\b(?:plain|no particular) (?:concept|persona|style)\b|컨셉\s*(?:없이|빼고)|기본\s*컨셉/u,
41
+ editorial: /\b(?:like an? editor|editorial (?:voice|style|approach|concept)|editor(?:-like)? (?:voice|style|approach|concept))\b|(?:편집장|편집자|에디터)\s*(?:처럼|같이|같은|스타일|컨셉|콘셉트?|느낌|말투)/u,
42
+ mentoring: /\b(?:like (?:a|my) (?:mentor|coach)|(?:mentor|coach)(?:-like|ing)? (?:voice|style|approach|concept))\b|(?:멘토|코치|(?:옆자리|옆에 있는|일 잘하는)\s*선배|선배)\s*(?:처럼|같이|같은|스타일|컨셉|콘셉트?|느낌|말투)/u,
43
+ },
44
+ tone: {
45
+ direct: /\b(?:candid|straightforward|matter-of-fact|direct(?:ly)?|blunt(?:ly)?)\b|단도직입|직설적|담백/u,
46
+ warm: /\b(?:warm(?:er|ly)?|friendl(?:y|ier)|approachable)\b|따뜻|친근|다정/u,
47
+ neutral: /\b(?:neutral(?:ly)?|calm(?:ly)?)\b|중립적|차분/u,
48
+ },
49
+ register: {
50
+ natural: /\b(?:my|match my|mirror my) register\b|내 말투에 맞/u,
51
+ formal: /\b(?:formally|respectfully|politely|(?:formal|respectful|polite)(?=\s*(?:[,!.]|$)|\s+(?:tone|language|voice|register|style|replies|and)\b))\b|존댓말|격식\s*있게|예의\s*있게|공손(?:하게|히)/u,
52
+ casual: /\b(?:casual(?:ly)?|informal(?:ly)?|conversational)\b|반말|격식 없이/u,
53
+ },
54
+ detail: {
55
+ balanced: /\bbalanced (?:detail|length)\b|적당한 분량/u,
56
+ brief: /\b(?:brief(?:ly)?|concis(?:e|ely)|shorter|short replies)\b|짧(?:게|고)|간결하게|간단하게/u,
57
+ detailed: /\b(?:detailed|in detail|more detail|thorough(?:ly)?)\b|자세하게|상세하게/u,
58
+ },
59
+ structure: {
60
+ "answer-first": /\b(?:answer|conclusion|result) first\b|(?:결론|결과|답|핵심|요점)\s*(?:부터|을\s*먼저)/u,
61
+ "evidence-first": /\b(?:evidence|reasoning) first\b|근거부터/u,
62
+ natural: /\bnatural (?:structure|order)\b|자연스러운 순서/u,
63
+ },
64
+ emoji: {
65
+ none: /\b(?:no|without) emoji(?:s)?\b|(?:이모지|이모티콘)\s*(?:없이|빼고|금지|쓰지\s*말)/u,
66
+ light: /\b(?:occasional|light|use some) emoji(?:s)?\b|(?:가끔|가벼운)\s*(?:이모지|이모티콘)/u,
67
+ },
68
+ } satisfies { [D in keyof Voice]: Record<Voice[D], RegExp> };
69
+ const defaultVoice = {
70
+ concept: "plain", tone: "direct", register: "natural", detail: "balanced", structure: "answer-first", emoji: "none",
71
+ } satisfies Voice;
72
+ const setting = "soul:reply-voice";
73
+
74
+ export const soulUpdateSchema = Type.Object({
75
+ sourceId: Type.String({ minLength: 1, pattern: "\\S" }),
76
+ }, { additionalProperties: false });
77
+ type SoulUpdate = Partial<Voice> | "reset";
78
+ type Ledger = Pick<StorePort, "getMeta" | "setMeta">;
79
+
80
+ function object(value: unknown): value is Record<string, unknown> {
81
+ return typeof value === "object" && value !== null && !Array.isArray(value);
82
+ }
83
+
84
+ function voicePatch(value: unknown): value is Partial<Voice> {
85
+ return object(value) && Object.keys(value).length > 0 && Object.entries(value).every(([key, choice]) =>
86
+ Object.hasOwn(dimensions, key) && typeof choice === "string" && Object.hasOwn(dimensions[key as keyof Voice], choice));
87
+ }
88
+
89
+ function completeVoice(value: unknown) {
90
+ // Both persisted pre-concept profiles and the first native wire version
91
+ // have all the original fields but no concept.
92
+ if (!voicePatch(value) || Object.keys(defaultVoice).some(key => key !== "concept" && !Object.hasOwn(value, key)))
93
+ throw new Error("Invalid reply voice profile");
94
+ return { ...defaultVoice, ...value };
95
+ }
96
+
97
+ function savedVoice(store: Ledger) {
98
+ const raw = store.getMeta(setting);
99
+ if (raw === null) return { revision: 0, sourceId: null, style: defaultVoice };
100
+ const saved: unknown = JSON.parse(raw);
101
+ if (!object(saved) || Object.keys(saved).length !== 3 || typeof saved.revision !== "number"
102
+ || !Number.isSafeInteger(saved.revision) || saved.revision < 1 || typeof saved.sourceId !== "string" || !saved.sourceId)
103
+ throw new Error("Stored reply voice is invalid");
104
+ return { revision: saved.revision, sourceId: saved.sourceId, style: completeVoice(saved.style) };
105
+ }
106
+
107
+ function startsWithPresentation(text: string): boolean {
108
+ return Object.values(requests).some(choices => Object.values(choices).some(pattern => pattern.exec(text)?.index === 0));
109
+ }
110
+
111
+ function onlyPresentationGrammar(text: string): boolean {
112
+ // Every non-choice word must be reply syntax, not a task, exception, example
113
+ // or time/channel qualifier. This also prevents a negated choice from
114
+ // becoming affirmative just because its vocabulary matched a dimension.
115
+ const english = /\b(?:please|answer|answers|reply|replies|respond|response|responses|explain|use|keep|make|be|your|my|our|the|a|an|it|in|with|and|to|as|more|tone|register|length|style|voice|approach|concept|format)\b/gu;
116
+ const korean = /(?:답변|응답|말투|톤|분량|방식|스타일|컨셉|콘셉트?)(?:으로|은|는|을|를|이|가)?|(?:으로|하게|있게|해서|하고|이며|이고|면서|그리고|또|좀|더|늘|항상|기본적으로|답해|말해|설명해|알려|써|해|바꿔|변경해|설정해|정해|부탁해|부탁드려요|줘|주세요|주라|서|로|게)/gu;
117
+ return !text.replace(english, " ").replace(korean, " ").replace(/[\s,.!,。、]+/gu, "");
118
+ }
119
+
120
+ /** Only unambiguous, supported choices in the original author's own prose are saved. */
121
+ export function soulUpdateIntent(source: Inbound): SoulUpdate | null {
122
+ const headPrefix = /^ {0,3}\/head[ \t]/u;
123
+ const raw = source.text.replace(headPrefix, "");
124
+ const body = raw.trim();
125
+ const prose = transportRoutingProse(source).replace(headPrefix, "").trim();
126
+ const indented = /^[ \t]{4}|^\t/u;
127
+ const addressedText = source.discordOriginalText;
128
+ if (!body || indented.test(raw) || body !== prose || body !== ownerRoutingProse(raw) || /[\r\n??]/u.test(raw)) return null;
129
+ if (addressedText !== undefined) {
130
+ // An addressed message can be normalized by removing only the bot
131
+ // mention, but a voice draft or quoted physical line is not that prose.
132
+ const original = addressedText.replace(/<@!?(\d+)>/gu, (mention, id) => id === source.route.accountId ? " " : mention);
133
+ if (indented.test(addressedText) || /[\r\n]/u.test(addressedText)
134
+ || original.trim().replace(/\s+/gu, " ") !== source.text.trim().replace(/\s+/gu, " ")) return null;
135
+ }
136
+ const labeled = /^(?:soul|말투)\s*:\s*(\S.*)$/iu.exec(body)?.[1];
137
+ const request = labeled ?? body;
138
+ if (/^(?:please\s+)?reset(?:\s+(?:(?:the|your|our)\s+)?(?:soul|reply style|writing style))?(?:\s+to\s+(?:the\s+)?default(?:s)?)?[.!]?$/iu.test(request)
139
+ && (labeled !== undefined || /(?:soul|reply style|writing style)\b/iu.test(request))) return "reset";
140
+ if (/^(?:(?:소울|말투|응답\s*스타일)(?:을|를)?\s+)?(?:기본(?:값|값으로|으로)?\s*(?:초기화해|되돌려|돌려)|초기화(?:해)?)\s*(?:줘|주세요)?[.!]?$/u.test(request)
141
+ && (labeled !== undefined || /^(?:소울|말투|응답\s*스타일)/u.test(request))) return "reset";
142
+ const styleText = request.toLowerCase().replace(/[‘’]/gu, "'");
143
+ // A persistent change must be a direct instruction about this agent's
144
+ // replies. Questions, alternatives, scoped exceptions and examples are
145
+ // not configuration even when they contain a supported phrase.
146
+ if (/\b(?:not|don't|never|instead of|or|could|would|should|can you|if|unless|suppose|imagine|pretend|for example|example of|quote|forwarded|only when|only for|just this|(?:this|the next) (?:thread|task|reply|answer)|(?:he|she|they) (?:said|asked))\b|말고|아니[라면]|않|하지\s*마|말아|만약|가정|상상|척해|예를\s*들|예시|인용|전달받|라고\s*(?:했|하던|쓰|적)|라는\s*(?:요청|문구|말|지시)|라면|해\s*줄래|할\s*수\s*있|어떨까|어때|(?:이번|이|다음)\s*(?:한\s*번|한번|답변|작업|스레드|메시지)(?:에(?:서)?)?만|이번만/u.test(styleText)) return null;
147
+ const englishSetting = /^(?:please\s+)?(?:change|set|update)\s+(?:(?:the|your|our)\s+)?(?:soul|reply style|writing style)\b(?:\s+to)?\s+/u;
148
+ const englishReply = /^(?:please\s+)?(?:(?:answer|reply|respond|explain)\s+(?:(?:in|with|using)\s+(?:(?:a|an|the)\s+)?|(?=like\s|[a-z]+ly\b))|(?:answer|reply|respond)\s+(?=(?:answer|conclusion|result|evidence|reasoning) first\b)|use\s+(?=.*\b(?:tone|register|voice|style|length|format)\b)(?:(?:a|an|the)\s+)?)/u;
149
+ const englishFuture = /^(?:from now on|going forward|from your next reply(?: onward)?|henceforth),?\s+/u;
150
+ const koreanFuture = /^(?:(?:답변은|응답은|말투는)\s+)?(?:앞으로(?:는|도)?|이제부터(?:는)?|지금부터(?:는)?|다음(?:\s*답변)?부터(?:는)?|앞으론|항상|매번)\s+/u;
151
+ const koreanSetting = /^(?:기본\s*)?(?:소울|말투|(?:답변|응답)\s*(?:방식|스타일|말투)|답변\s*컨셉)(?:을|를|은|는)?\s+/u;
152
+ const koreanSetRequest = /(?:바꿔|변경해|설정해|정해)\s*(?:줘|주세요|주라)?[.!]?$/u;
153
+ const koreanReply = /(?:해\s*(?:줘|주세요|주라)?|알려\s*(?:줘|주세요|주라)|부탁(?:해|드려요)?)[.!]?$/u;
154
+ const koreanLead = /^(?:(?:제게|저한테|나한테|뭐든|기본적으로|답변은|응답은|말투는|답변을|응답을|말투를|답변할\s*때(?:는|마다)?|응답할\s*때(?:는|마다)?|유능한|능숙한|좋은|친절한|믿음직한)\s+)*/u;
155
+ const persistentEnglish = styleText.replace(englishFuture, "");
156
+ const persistentKorean = styleText.replace(koreanFuture, "");
157
+ let presentation: string;
158
+ if (labeled !== undefined) presentation = styleText.replace(koreanLead, "");
159
+ else if (englishSetting.test(styleText)) presentation = styleText.replace(englishSetting, "");
160
+ else if (koreanSetting.test(styleText) && koreanSetRequest.test(styleText)) presentation = styleText.replace(koreanSetting, "").replace(koreanLead, "");
161
+ else if (persistentEnglish !== styleText && englishReply.test(persistentEnglish)) presentation = persistentEnglish.replace(englishReply, "");
162
+ else if (persistentKorean !== styleText && koreanReply.test(persistentKorean)) presentation = persistentKorean.replace(koreanLead, "");
163
+ else return null;
164
+ if (labeled === undefined && !startsWithPresentation(presentation)) return null;
165
+ const patch: Record<string, string> = {};
166
+ let remainder = presentation;
167
+ for (const [dimension, choices] of Object.entries(requests)) {
168
+ const matches = Object.entries(choices).filter(([, pattern]) => pattern.test(presentation));
169
+ if (matches.length > 1) return null;
170
+ if (matches[0]) {
171
+ const [choice, pattern] = matches[0];
172
+ patch[dimension] = choice;
173
+ remainder = remainder.replace(new RegExp(pattern.source, "gu"), " ");
174
+ }
175
+ }
176
+ // Do not silently apply only the familiar half of a concept plus style
177
+ // request when the owner named an unsupported concept.
178
+ if (!patch.concept && /\b(?:concept|persona|like an?)\b|컨셉|콘셉트?|처럼|같은\s*느낌/u.test(presentation)) return null;
179
+ return onlyPresentationGrammar(remainder) && voicePatch(patch) ? patch : null;
180
+ }
181
+
182
+ export function soulSourceId(value: unknown): string {
183
+ if (object(value) && Object.keys(value).length === 1 && typeof value.sourceId === "string" && value.sourceId.trim())
184
+ return value.sourceId;
185
+ throw new Error("A reply voice update takes only its original sourceId");
186
+ }
187
+
188
+ export function applySoulUpdate(store: Ledger, sourceId: string, update: SoulUpdate) {
189
+ const current = savedVoice(store);
190
+ if (current.sourceId !== sourceId) {
191
+ const style = update === "reset" ? defaultVoice : { ...current.style, ...update };
192
+ const next = { revision: current.revision + 1, sourceId, style };
193
+ if (!Number.isSafeInteger(next.revision)) throw new Error("Reply voice revision is unavailable");
194
+ store.setMeta(setting, JSON.stringify(next));
195
+ }
196
+ const applied = savedVoice(store);
197
+ return { revision: applied.revision, style: applied.style };
198
+ }
199
+
200
+ export function replyVoiceProfile(store: Ledger, version: 1 | 2 = 2) {
201
+ const { concept, ...base } = savedVoice(store).style;
202
+ return version === 2 ? { ...base, concept } : base;
203
+ }
204
+
205
+ export function renderReplyVoice(value: unknown): string {
206
+ const style = completeVoice(value);
207
+ return [
208
+ "<superagent-reply-voice>",
209
+ "Apply this voice only to prose addressed to the operator. Use their language. Separate verified facts from inference. Task formats, role instructions, permissions and workflows are unchanged.",
210
+ dimensions.concept[style.concept], dimensions.tone[style.tone], dimensions.register[style.register], dimensions.detail[style.detail],
211
+ dimensions.structure[style.structure], dimensions.emoji[style.emoji],
212
+ "</superagent-reply-voice>",
213
+ ].filter(Boolean).join("\n");
214
+ }