omp-superagent 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
@@ -0,0 +1,34 @@
1
+ import type { SettingProvenance } from "@oh-my-pi/pi-coding-agent/config/settings";
2
+
3
+ type JudgeConfiguration =
4
+ | { status: "configured" | "missing"; source: SettingProvenance }
5
+ | { status: "unknown" };
6
+
7
+ /** Read configuration only, after a new setup has successfully published. */
8
+ export async function inspectNativeJudge(cwd: string): Promise<JudgeConfiguration> {
9
+ try {
10
+ // Like setup-memory, keep even native dotenv/config imports behind setup's
11
+ // credential acquisition and publication. Never resolve a model or open auth.
12
+ const { Settings } = await import("@oh-my-pi/pi-coding-agent/config/settings");
13
+ const settings = await Settings.loadReadOnly({ cwd });
14
+ const source = settings.getModelRoleProvenance("judge");
15
+ if (source === "default") {
16
+ // Read-only settings intentionally skip legacy global migration. Only an
17
+ // effective higher-layer assignment can settle the role without it; in
18
+ // particular native project null falls through, unlike overlay null.
19
+ const { hasUnresolvedNativeLegacy } = await import("./native-settings");
20
+ if (await hasUnresolvedNativeLegacy(settings.getAgentDir())) return { status: "unknown" };
21
+ }
22
+ // Native modelRoles defaults to an empty record. This accessor normalizes
23
+ // string/array selectors, but does not resolve aliases or automatic fallbacks.
24
+ // Read the effective value, not a hidden global/project assignment: an
25
+ // overlay null or empty value can hide a configured lower-layer judge.
26
+ return {
27
+ status: settings.getModelRole("judge")?.split(",").some(selector => selector.trim()) ? "configured" : "missing",
28
+ source,
29
+ };
30
+ } catch {
31
+ // Native parse/read diagnostics can contain private settings or selectors.
32
+ return { status: "unknown" };
33
+ }
34
+ }
@@ -0,0 +1,39 @@
1
+ type MemoryPreferenceResult =
2
+ | { status: "enabled" | "shadowed" | "not-saved"; agentDir: string; source: string }
3
+ | { status: "failed" };
4
+
5
+ /** Called only after setup's configuration and credentials have been published. */
6
+ export async function saveMnemopiPreference(cwd: string): Promise<MemoryPreferenceResult> {
7
+ try {
8
+ // Do not import the package entry point, a memory backend, or a model runtime.
9
+ // Native settings transitively load native dotenv, so even these config-only
10
+ // imports must stay behind credential acquisition and final publication.
11
+ const [{ Settings }, { cfgMemoryBackend }, { editNativeGlobalConfig }] = await Promise.all([
12
+ import("@oh-my-pi/pi-coding-agent/config/settings"),
13
+ import("@oh-my-pi/pi-coding-agent/memory-backend/settings"),
14
+ import("./native-settings"),
15
+ ]);
16
+ // Config-only persistence must not open agent.db, migrate authentication,
17
+ // quarantine malformed startup config, or initialize the global singleton.
18
+ const settings = await Settings.loadReadOnly({ cwd });
19
+ await editNativeGlobalConfig(settings, [{ path: "memory.backend", value: "mnemopi" }]);
20
+
21
+ // A concurrent edit may be preserved instead of applying our stale write.
22
+ // A fresh, read-only instance is authoritative, not the writer's staged value.
23
+ const actual = await Settings.loadReadOnly({ cwd, agentDir: settings.getAgentDir() });
24
+ let persisted: unknown = actual.getGlobalSettings();
25
+ for (const segment of cfgMemoryBackend.segments) {
26
+ persisted = persisted && typeof persisted === "object" && Object.hasOwn(persisted, segment)
27
+ ? (persisted as Record<string, unknown>)[segment] : undefined;
28
+ }
29
+ const source = actual.getProvenance(cfgMemoryBackend);
30
+ return {
31
+ status: persisted !== "mnemopi" ? "not-saved" : cfgMemoryBackend.get(actual) === "mnemopi" ? "enabled" : "shadowed",
32
+ agentDir: actual.getAgentDir(), source,
33
+ };
34
+ } catch {
35
+ // Native diagnostics can contain config values. Never echo a caught error or
36
+ // undo setup publication / unrelated native writes to compensate for failure.
37
+ return { status: "failed" };
38
+ }
39
+ }
@@ -0,0 +1,84 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { REST, Routes, type RESTOptions } from "discord.js";
3
+ import { Api, InputFile } from "grammy";
4
+ import type { Config } from "./config";
5
+ import { validateCredential } from "./credentials";
6
+ import { withTelegramSignal } from "./telegram";
7
+
8
+ const avatar = new URL("../assets/superagent-avatar.jpg", import.meta.url);
9
+
10
+ interface ProfileOptions {
11
+ signal?: AbortSignal;
12
+ createRest?: (options: Partial<RESTOptions>, token: string) => Pick<REST, "get" | "patch">;
13
+ createApi?: (token: string) => Pick<Api, "getMe" | "setMyProfilePhoto" | "getUserProfilePhotos">;
14
+ }
15
+
16
+ interface ProfileResult {
17
+ platform: "discord" | "telegram";
18
+ status: "applied" | "failed";
19
+ message: string;
20
+ }
21
+
22
+ /** One-shot profile REST calls only; never starts a messenger or native session. */
23
+ export async function setupBotProfiles(
24
+ config: Config, credentials: Readonly<Record<string, string>>, options: ProfileOptions = {},
25
+ ): Promise<ProfileResult[]> {
26
+ const results: ProfileResult[] = [];
27
+ if (!config.discord && !config.telegram) return results;
28
+ const image = readFileSync(avatar);
29
+ if (config.discord) {
30
+ options.signal?.throwIfAborted();
31
+ let attempted = false;
32
+ try {
33
+ const token = credentials[config.discord.tokenEnv]!;
34
+ validateCredential(token);
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." });
51
+ } 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." });
55
+ }
56
+ }
57
+ if (config.telegram) {
58
+ if (options.signal?.aborted) return results;
59
+ let attempted = false;
60
+ try {
61
+ const token = credentials[config.telegram.tokenEnv]!;
62
+ validateCredential(token);
63
+ const api = (options.createApi ?? (credential => new Api(credential, {
64
+ sensitiveLogs: false, timeoutSeconds: 45, baseFetchConfig: { redirect: "error" },
65
+ })))(token);
66
+ const bot = await withTelegramSignal(options.signal, signal => api.getMe(signal));
67
+ if (!bot.is_bot || !Number.isSafeInteger(bot.id) || bot.id <= 0 || String(bot.id) === config.telegram.ownerId)
68
+ throw new Error("Invalid bot identity");
69
+ attempted = true;
70
+ if (await withTelegramSignal(options.signal, signal =>
71
+ api.setMyProfilePhoto({ type: "static", photo: new InputFile(image, "superagent-avatar.jpg") }, signal)) !== true)
72
+ throw new Error("Missing profile receipt");
73
+ const current = await withTelegramSignal(options.signal, signal => api.getUserProfilePhotos(bot.id, { limit: 1 }, signal));
74
+ if (current.total_count < 1 || !current.photos[0]?.some(photo => photo.file_id && photo.file_unique_id))
75
+ throw new Error("Missing profile readback");
76
+ results.push({ platform: "telegram", status: "applied", message: "Mascot upload accepted by Telegram; current profile photo confirmed by getUserProfilePhotos." });
77
+ } catch {
78
+ results.push({ platform: "telegram", status: "failed", message: attempted
79
+ ? "Profile update is unresolved; it may have reached Telegram. No automatic retry was attempted; API details suppressed."
80
+ : "Profile inspection failed; no Telegram profile update was attempted. Credential/API details suppressed." });
81
+ }
82
+ }
83
+ return results;
84
+ }
package/src/setup.ts ADDED
@@ -0,0 +1,300 @@
1
+ import {
2
+ closeSync, constants, existsSync, fstatSync, linkSync, lstatSync,
3
+ openSync, readFileSync, realpathSync, unlinkSync, writeSync,
4
+ } from "node:fs";
5
+ import { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { isatty } from "node:tty";
8
+ import { setImmediate as yieldToSignals } from "node:timers/promises";
9
+ import { credentialEnvNames, hostPaths, parseConfig, type Config } from "./config";
10
+ import { discoverInstalledOmp, inspectInstalledOmp } from "./installed-omp";
11
+ import {
12
+ assertCredentialsUnchanged, readCredentialFile, serializeCredentials, stagePrivateFile,
13
+ validateCredential, writeCredentials,
14
+ } from "./credentials";
15
+ import { saveMnemopiPreference } from "./setup-memory";
16
+ import { inspectNativeJudge } from "./setup-judge";
17
+
18
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
19
+
20
+ class SetupCancelled extends Error {
21
+ constructor(saved = false) {
22
+ super(saved ? "Setup cancelled after saving; local files and any completed profile changes were preserved"
23
+ : "Setup cancelled; no files were written");
24
+ }
25
+ }
26
+
27
+ // Bash owns the standard terminal password read and restoration, not a custom raw
28
+ // editor. Only this static program is passed in argv; input goes to private stdout.
29
+ const READ = `set +x
30
+ trap 'printf "\\n" >&2; exit 130' INT TERM HUP
31
+ IFS= builtin read -r value
32
+ status=$?
33
+ [ "$status" -eq 0 ] || exit 1
34
+ printf '%s' "$value"
35
+ `;
36
+ const READ_SECRET = READ.replace("read -r value", "read -r -s value").replace("status=$?", "status=$?\nprintf '\\n' >&2");
37
+
38
+ class Terminal {
39
+ private fd: number;
40
+ private cancelled = false;
41
+ saved = false;
42
+ readonly abort = new AbortController();
43
+ private reader?: { kill(signal: NodeJS.Signals): void; exited: Promise<number> };
44
+ private interrupt = () => {
45
+ this.cancelled = true;
46
+ this.abort.abort();
47
+ // A signal addressed to the setup PID does not automatically reach its child.
48
+ // Always use the trapped signal so Bash restores its own silent-read state.
49
+ try { this.reader?.kill("SIGINT"); } catch { /* The reader may already have exited. */ }
50
+ };
51
+
52
+ constructor() {
53
+ try {
54
+ this.fd = openSync("/dev/tty", constants.O_RDWR | constants.O_NOCTTY);
55
+ if (!fstatSync(this.fd).isCharacterDevice() || !isatty(this.fd)) {
56
+ closeSync(this.fd);
57
+ throw new Error("Not a terminal");
58
+ }
59
+ } catch { throw new Error("Setup requires a controlling terminal; piped or echoed secret input is not supported"); }
60
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, this.interrupt);
61
+ }
62
+
63
+ async ask(label: string, secret = false): Promise<string> {
64
+ if (this.cancelled) throw new SetupCancelled();
65
+ writeSync(this.fd, label);
66
+ const child = Bun.spawn(["/bin/bash", "--noprofile", "--norc", "-p", "+x", "-c", secret ? READ_SECRET : READ], {
67
+ stdin: this.fd, stdout: "pipe", stderr: this.fd,
68
+ env: { ...process.env, BASH_ENV: "/dev/null", ENV: "/dev/null", SHELLOPTS: "", BASHOPTS: "" },
69
+ });
70
+ this.reader = child;
71
+ try {
72
+ const [buffer, code] = await Promise.all([new Response(child.stdout).arrayBuffer(), child.exited]);
73
+ if (code !== 0 || this.cancelled) throw new SetupCancelled();
74
+ const bytes = Buffer.from(buffer);
75
+ const value = bytes.toString("utf8");
76
+ if (!Buffer.from(value, "utf8").equals(bytes)) throw new Error("Input must be valid UTF-8");
77
+ return value;
78
+ } catch (error) {
79
+ this.interrupt();
80
+ throw error;
81
+ } finally {
82
+ await child.exited;
83
+ this.reader = undefined;
84
+ }
85
+ }
86
+
87
+ async confirm(label: string): Promise<void> {
88
+ if (!/^y(es)?$/i.test((await this.ask(`${label} [y/N]: `)).trim())) throw new SetupCancelled();
89
+ }
90
+
91
+ check(): void { if (this.cancelled) throw new SetupCancelled(this.saved); }
92
+ async close(): Promise<void> {
93
+ if (this.reader) { this.interrupt(); await this.reader.exited; }
94
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.off(signal, this.interrupt);
95
+ closeSync(this.fd);
96
+ }
97
+ }
98
+
99
+ function currentConfig(path: string): Buffer | undefined {
100
+ try {
101
+ lstatSync(path); // A dangling symlink is not an absent configuration.
102
+ return readFileSync(path);
103
+ } catch (error) {
104
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
105
+ if (existsSync(dirname(path))) {
106
+ try { lstatSync(path); } catch { return undefined; }
107
+ }
108
+ }
109
+ throw new Error("Cannot read configuration; its parent directory must already exist");
110
+ }
111
+ }
112
+
113
+ function unchanged(path: string, previous: Buffer | undefined): void {
114
+ const current = currentConfig(path);
115
+ if (!!current !== !!previous || (current && previous && !current.equals(previous)))
116
+ throw new Error("Configuration changed during setup; nothing was overwritten");
117
+ }
118
+
119
+ async function newConfig(terminal: Terminal, path: string): Promise<{ config: Config; text: string }> {
120
+ const template = await Bun.file(join(root, "config.example.json")).json() as Record<string, any>;
121
+ const command = [discoverInstalledOmp()];
122
+ console.log(`Installed OMP command: ${command.map(shellQuote).join(" ")}`);
123
+ const selected = [...new Set((await terminal.ask("Messengers (comma-separated discord,telegram,slack): "))
124
+ .split(",").map(s => s.trim().toLowerCase()).filter(Boolean))];
125
+ if (!selected.length || selected.some(p => !["discord", "telegram", "slack"].includes(p)))
126
+ throw new Error("Select at least one supported messenger");
127
+ const raw: Record<string, unknown> = { ...template, command };
128
+ for (const platform of ["discord", "telegram", "slack"]) delete raw[platform];
129
+ const list = async (label: string) => (await terminal.ask(`${label} (comma-separated; empty = deny groups / DM only): `))
130
+ .split(",").map(s => s.trim()).filter(Boolean);
131
+ for (const platform of selected) {
132
+ const policy = { ...template[platform] };
133
+ policy.ownerId = (await terminal.ask(`${platform} owner user ID (required): `)).trim();
134
+ if (platform === "discord") {
135
+ policy.allowedGuildIds = await list("Discord allowed guild IDs");
136
+ policy.allowedChannelIds = await list("Discord allowed parent channel IDs");
137
+ } else if (platform === "telegram") {
138
+ policy.allowedChatIds = await list("Telegram allowed group chat IDs");
139
+ } else {
140
+ policy.teamId = (await terminal.ask("Slack workspace/team ID (required): ")).trim();
141
+ policy.allowedChannelIds = await list("Slack allowed channel IDs");
142
+ }
143
+ raw[platform] = policy;
144
+ }
145
+ const headCwd = (await terminal.ask(`Head workspace absolute directory [${process.cwd()}]: `)).trim() || process.cwd();
146
+ if (!isAbsolute(headCwd)) throw new Error("Head workspace must be an absolute existing directory");
147
+ const head = realpathSync(headCwd);
148
+ if (!lstatSync(head).isDirectory()) throw new Error("Head workspace must be an existing directory");
149
+ raw.headCwd = head;
150
+ await terminal.confirm(`Use head workspace ${head}?`);
151
+ const stateDir = (await terminal.ask("State directory (absolute path, required): ")).trim();
152
+ if (!isAbsolute(stateDir)) throw new Error("State directory must be an explicit absolute path");
153
+ raw.stateDir = stateDir;
154
+ for (const key of ["maxHosts", "maxSubagents", "idleMs"] as const) {
155
+ const answer = (await terminal.ask(`${key} [template default ${template[key]}]: `)).trim();
156
+ raw[key] = answer ? Number(answer) : template[key];
157
+ }
158
+ const config = parseConfig(raw, path);
159
+ return { config, text: `${JSON.stringify(raw, null, 2)}\n` };
160
+ }
161
+
162
+ function shellQuote(value: string): string { return `'${value.replaceAll("'", "'\\''")}'`; }
163
+
164
+ /** Interactive configuration and profile REST setup; no messenger or service activation. */
165
+ export async function setup(configPath: string): Promise<void> {
166
+ const path = resolve(configPath);
167
+ const terminal = new Terminal();
168
+ let configTemporary: string | undefined;
169
+ let createdConfig = false;
170
+ try {
171
+ const previousConfig = currentConfig(path);
172
+ const previousCredentials = readCredentialFile(path);
173
+ let config: Config;
174
+ let text: string | undefined;
175
+ let recommendMemory = false;
176
+ if (previousConfig) {
177
+ let value: unknown;
178
+ try { value = JSON.parse(previousConfig.toString("utf8")); }
179
+ catch { throw new Error("Existing configuration is not valid JSON; it was not modified"); }
180
+ config = parseConfig(value, path);
181
+ console.log("Existing configuration preserved; only its configured credentials will be prompted.");
182
+ } else {
183
+ ({ config, text } = await newConfig(terminal, path));
184
+ }
185
+ hostPaths(config, "main");
186
+ await inspectInstalledOmp(config.command, credentialEnvNames(config));
187
+ const values = Object.assign(Object.create(null) as Record<string, string>, previousCredentials?.values);
188
+ let replacing = false;
189
+ for (const name of credentialEnvNames(config)) {
190
+ const old = Object.hasOwn(values, name) ? values[name] : undefined;
191
+ const explicit = process.env[name];
192
+ const configured = !!(explicit || old);
193
+ const answer = await terminal.ask(`${name} (${configured ? "configured; Enter keeps existing" : "not configured; required"}): `, true);
194
+ if (answer) {
195
+ validateCredential(answer);
196
+ if (Object.hasOwn(values, name) && old !== answer) replacing = true;
197
+ values[name] = answer;
198
+ } else if (!configured) {
199
+ throw new Error(`A credential is required for ${name}`);
200
+ } else if (old) {
201
+ validateCredential(old);
202
+ } else if (explicit) {
203
+ // Enter keeps an env-only installation env-only, without copying its secret.
204
+ validateCredential(explicit);
205
+ }
206
+ console.log(`${name}: configured${explicit ? " (nonempty shell environment takes precedence)" : ""}`);
207
+ }
208
+ serializeCredentials(values); // Prove lossless encoding before any persistent write.
209
+ if (replacing) await terminal.confirm("Replace existing credential values?");
210
+ if (!previousConfig) {
211
+ console.log("Recommended: native OMP Mnemopi memory persists across conversations (project-scoped by default).");
212
+ console.log("This saves OMP's global memory.backend preference only; existing memory options stay unchanged.");
213
+ console.log("Depending on existing native settings, later memory use may process conversations with models and download models.");
214
+ console.log("Setup does not start memory or OMP; it activates on later OMP startup. Running OMP instances may apply native settings reloads.");
215
+ recommendMemory = /^y(es)?$/i.test((await terminal.ask("Enable native Mnemopi memory after saving setup? [y/N]: ")).trim());
216
+ if (!recommendMemory) console.log("Native memory settings will not be changed.");
217
+ }
218
+ console.log(`Configuration: ${path}\nPrivate credentials: ${path}.env`);
219
+ const profilePlatforms = (["discord", "telegram"] as const).filter(platform => config[platform]);
220
+ if (profilePlatforms.length) {
221
+ console.log(`After saving, replace the configured ${profilePlatforms.join("/")} bot profile pictures with the repository mascot: ${join(root, "assets", "superagent-avatar.jpg")}`);
222
+ console.log("This uses profile REST APIs only; no Gateway, polling, messages, or native model session is started.");
223
+ }
224
+ await terminal.confirm("Write configuration/credentials?");
225
+ // Snapshot the same environment-over-file precedence used by start before
226
+ // native settings imports can populate unrelated dotenv values.
227
+ const profileCredentials = Object.fromEntries(credentialEnvNames(config).map(name => [name, process.env[name] || values[name]!]));
228
+ // Deliver pending cancellation before entering the synchronous commit section.
229
+ await yieldToSignals();
230
+ terminal.check();
231
+ if (text !== undefined) configTemporary = stagePrivateFile(path, text);
232
+ unchanged(path, previousConfig);
233
+ assertCredentialsUnchanged(path, previousCredentials);
234
+ terminal.check();
235
+ if (configTemporary) {
236
+ linkSync(configTemporary, path); // Exclusive creation: never overwrite another config.
237
+ createdConfig = true;
238
+ }
239
+ try { writeCredentials(path, values, previousCredentials); }
240
+ catch (error) {
241
+ if (createdConfig && configTemporary) {
242
+ const staged = lstatSync(configTemporary);
243
+ const current = lstatSync(path);
244
+ if (staged.dev === current.dev && staged.ino === current.ino) unlinkSync(path);
245
+ createdConfig = false;
246
+ }
247
+ throw error;
248
+ }
249
+ terminal.saved = true;
250
+ console.log(`Saved configuration: ${path}\nPrivate credentials: ${path}.env (0600)`);
251
+ if (recommendMemory) {
252
+ const memory = await saveMnemopiPreference(config.headCwd);
253
+ if (memory.status === "failed") {
254
+ console.log("Setup saved, but native Mnemopi could not be saved or verified; memory activation is not confirmed. No service was started by setup.");
255
+ } else if (memory.status === "not-saved") {
256
+ console.log("Setup saved, but native persistence did not retain memory.backend=mnemopi; Mnemopi was not enabled by setup. Concurrent native settings were preserved.");
257
+ } else if (memory.status === "shadowed") {
258
+ console.log(`Saved native memory.backend=mnemopi in OMP agent settings: ${memory.agentDir}`);
259
+ console.log(`Mnemopi is not effective for the head workspace (${memory.source} settings take precedence); those settings were preserved. No service was started by setup.`);
260
+ } else {
261
+ console.log(`Saved native memory.backend=mnemopi in OMP agent settings: ${memory.agentDir}`);
262
+ console.log("Mnemopi is configured for the head workspace on later OMP startup; no service was started by setup.");
263
+ }
264
+ }
265
+ if (createdConfig) {
266
+ const judge = await inspectNativeJudge(config.headCwd);
267
+ if (judge.status === "unknown") {
268
+ console.log("Setup saved, but native OMP judge configuration could not be verified; judge configuration is unknown, not confirmed missing. Native model settings were not changed by this check.");
269
+ } else if (judge.status === "missing") {
270
+ console.log("Recommended: configure a native judge model for OMP's judge role; no effective judge selector is configured for the head workspace.");
271
+ if (judge.source !== "default") {
272
+ console.log(`The effective judge value is empty or unset in ${judge.source} settings; a hidden lower-layer assignment does not make it effective.`);
273
+ }
274
+ console.log("In an ordinary native OMP terminal opened in the head workspace, open /models, choose Roles -> Judge, and assign a native judgment model. Use the intended global/project storage scope and review any overriding native config overlay; do not use a messenger-managed session to persist this setting.");
275
+ console.log("This is configuration-only advice: selector presence does not prove model or authentication availability. Setup did not select a model, open account storage, or call a model/provider.");
276
+ }
277
+ }
278
+ if (profilePlatforms.length) {
279
+ terminal.check();
280
+ const { setupBotProfiles } = await import("./setup-profiles");
281
+ const profiles = await setupBotProfiles(config, profileCredentials, { signal: terminal.abort.signal });
282
+ for (const profile of profiles) {
283
+ console.log(`${profile.platform}: ${profile.message}`);
284
+ if (profile.status === "failed") process.exitCode = 1;
285
+ }
286
+ if (profiles.some(profile => profile.status === "failed"))
287
+ console.log("Local configuration/credentials remain saved; profile setup is incomplete. Inspect the bot profile before running setup again.");
288
+ terminal.check();
289
+ }
290
+ if (config.slack) {
291
+ console.log("slack: Bot/app tokens cannot upload the app icon automatically. Set it manually at https://api.slack.com/apps -> your app -> Basic Information -> Display Information -> App icon.");
292
+ console.log(`Slack app icon file: ${join(root, "assets", "superagent-avatar.jpg")}`);
293
+ }
294
+ const cli = `${shellQuote(process.execPath)} --no-env-file ${shellQuote(join(root, "src", "cli.ts"))}`;
295
+ console.log(`Next: ${cli} doctor --config ${shellQuote(path)}\nStart explicitly: ${cli} start --config ${shellQuote(path)}`);
296
+ } finally {
297
+ try { if (configTemporary) unlinkSync(configTemporary); }
298
+ finally { await terminal.close(); }
299
+ }
300
+ }