omp-superagent 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +1361 -0
- package/LICENSE +21 -0
- package/README.ko.md +184 -0
- package/README.md +205 -2
- package/THIRD_PARTY_NOTICES.md +313 -0
- package/assets/architecture.mmd +24 -0
- package/assets/architecture.svg +126 -0
- package/assets/superagent-avatar.jpg +0 -0
- package/assets/superagent-mascot.webp +0 -0
- package/config.example.json +26 -0
- package/docs/OPERATIONS.md +1030 -0
- package/docs/releases/0.1.0.md +222 -0
- package/docs/releases/0.1.1.md +60 -0
- package/package.json +59 -4
- package/scripts/check-omp.ts +4 -0
- package/scripts/ci.ts +28 -0
- package/scripts/prepare-ulw.ts +18 -0
- package/scripts/release.ts +50 -0
- package/scripts/setup.sh +25 -0
- package/skills/head/SKILL.md +259 -0
- package/skills/head/references/model-selection.md +263 -0
- package/skills/head/references/routing.md +356 -0
- package/skills/head/references/supervision.md +312 -0
- package/skills/lane/SKILL.md +188 -0
- package/skills/lane/references/workflow.md +349 -0
- package/src/autostart.ts +295 -0
- package/src/board-extension.ts +217 -0
- package/src/board.ts +396 -0
- package/src/cli.ts +167 -0
- package/src/config.ts +191 -0
- package/src/contracts.ts +317 -0
- package/src/credentials.ts +172 -0
- package/src/delivery.ts +7 -0
- package/src/dialog.ts +73 -0
- package/src/discord-command-registration.ts +201 -0
- package/src/discord-commands.ts +29 -0
- package/src/discord-markdown.ts +172 -0
- package/src/discord.ts +745 -0
- package/src/extension.ts +289 -0
- package/src/gateway-client.ts +222 -0
- package/src/gateway-protocol.ts +85 -0
- package/src/gateway-restart.ts +151 -0
- package/src/gateway-server.ts +392 -0
- package/src/gateway-store.ts +237 -0
- package/src/gateway.ts +638 -0
- package/src/head-recovery.ts +61 -0
- package/src/host-extension.ts +449 -0
- package/src/host-owner.ts +350 -0
- package/src/host-protocol.ts +136 -0
- package/src/host.ts +414 -0
- package/src/installed-omp.ts +63 -0
- package/src/lane-extension.ts +179 -0
- package/src/lane-models.ts +75 -0
- package/src/lane-report.ts +70 -0
- package/src/managed-ulw-probe.ts +172 -0
- package/src/managed-ulw.ts +471 -0
- package/src/message-order.ts +21 -0
- package/src/messenger-commands.ts +16 -0
- package/src/messengers.ts +114 -0
- package/src/native-presets.ts +282 -0
- package/src/native-sessions.ts +32 -0
- package/src/native-settings.ts +129 -0
- package/src/repository.ts +12 -0
- package/src/runtime.ts +3864 -0
- package/src/setup-judge.ts +34 -0
- package/src/setup-memory.ts +39 -0
- package/src/setup-profiles.ts +84 -0
- package/src/setup.ts +300 -0
- package/src/slack-command-registration.ts +217 -0
- package/src/slack-commands.ts +18 -0
- package/src/slack.ts +776 -0
- package/src/store.ts +806 -0
- package/src/telegram-command-registration.ts +155 -0
- package/src/telegram.ts +661 -0
- package/src/workflow.ts +94 -0
- package/upstream/ulw.json +9 -0
package/src/cli.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file
|
|
2
|
+
import { Database } from "bun:sqlite";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { configuredPlatforms, credentialEnvNames, hostPaths, loadConfig, requireMessengerCredentials } from "./config";
|
|
6
|
+
import { inspectInstalledOmp, supportedOmp } from "./installed-omp";
|
|
7
|
+
import { loadCredentials } from "./credentials";
|
|
8
|
+
import type { Lane } from "./contracts";
|
|
9
|
+
import { setup } from "./setup";
|
|
10
|
+
|
|
11
|
+
// Lifecycle imports below must stay lazy: static Gateway/Host imports execute
|
|
12
|
+
// OMP's dotenv loader before setup/doctor/command registration select credential sources.
|
|
13
|
+
const HELP = `omp-sa — messenger-connected OMP head and independent topic sessions
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
omp-sa setup --config FILE
|
|
17
|
+
omp-sa start --config FILE
|
|
18
|
+
omp-sa install --config FILE
|
|
19
|
+
omp-sa uninstall --config FILE
|
|
20
|
+
omp-sa status --config FILE
|
|
21
|
+
omp-sa stop [main|LANE_ID] --config FILE
|
|
22
|
+
omp-sa doctor --config FILE
|
|
23
|
+
omp-sa discord-commands --config FILE [--apply]
|
|
24
|
+
omp-sa telegram-commands --config FILE [--language CODE] [--apply]
|
|
25
|
+
omp-sa slack-commands --config FILE --manifest-token-env NAME [--apply]
|
|
26
|
+
|
|
27
|
+
setup interactively saves configuration and a private FILE.env, then sets Discord/Telegram bot profile pictures to the repository mascot through REST APIs; it never starts messenger connections or services.
|
|
28
|
+
start explicitly launches a detached Gateway and its native head, activating configured messenger connections. No install/autostart is performed.
|
|
29
|
+
install enables macOS per-user startup at future login only; requires configured messenger credentials in private FILE.env and native settings/authentication under the OS account home. No immediate start or shell environment capture.
|
|
30
|
+
uninstall removes only the owned login launcher; it does not stop an existing Gateway/head or remove credentials/state.
|
|
31
|
+
stop main stops the supervised Gateway/head service; busy native hosts refuse without being killed or resurrected.
|
|
32
|
+
discord-commands uses Discord REST only: dry-run by default, with no Gateway or native runtime activation.
|
|
33
|
+
--apply exclusively replaces this dedicated bot's GLOBAL commands with supported Superagent commands, deleting obsolete registrations (including Hermes). Guild commands are preserved; shadowing conflicts refuse apply.
|
|
34
|
+
telegram-commands configures owner-scoped Telegram command menus; --language selects an optional Telegram language code.
|
|
35
|
+
slack-commands configures /superagent-* commands through the app manifest; NAME identifies an app-configuration token environment variable, never a token argument.
|
|
36
|
+
All command registration is read-only by default and requires --apply to change remote configuration. No polling, Socket Mode, or native model session is started.
|
|
37
|
+
Requires an already installed stock OMP ${supportedOmp}. Same-process native TUI attach is not supported.
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
function laneRows(stateDir: string): Lane[] {
|
|
41
|
+
const path = join(stateDir, "coordination.sqlite");
|
|
42
|
+
if (!existsSync(path)) return [];
|
|
43
|
+
const db = new Database(path, { readonly: true });
|
|
44
|
+
try {
|
|
45
|
+
return (db.query("SELECT data FROM lanes ORDER BY rowid").all() as { data: string }[])
|
|
46
|
+
.map(row => JSON.parse(row.data) as Lane);
|
|
47
|
+
} finally { db.close(); }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function main(args = process.argv.slice(2)): Promise<void> {
|
|
51
|
+
if (!args.length || args.includes("--help") || args[0] === "help") { console.log(HELP); return; }
|
|
52
|
+
const [command] = args;
|
|
53
|
+
if (!["setup", "start", "install", "uninstall", "status", "stop", "doctor", "discord-commands", "telegram-commands", "slack-commands"].includes(command!)) throw new Error(`Unknown command: ${command}`);
|
|
54
|
+
const configAt = args.indexOf("--config");
|
|
55
|
+
if (configAt < 0 || !args[configAt + 1]) throw new Error("--config FILE is required");
|
|
56
|
+
if (command === "install" || command === "uninstall") {
|
|
57
|
+
if (args.length !== 3 || configAt !== 1 || args[2]!.startsWith("-"))
|
|
58
|
+
throw new Error(`Usage: ${command} --config FILE`);
|
|
59
|
+
const config = await loadConfig(args[2]!);
|
|
60
|
+
const { installAutostart, uninstallAutostart } = await import("./autostart");
|
|
61
|
+
console.log(JSON.stringify(await (command === "install" ? installAutostart(config) : uninstallAutostart(config)), null, 2));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (command === "setup") { await setup(args[configAt + 1]!); return; }
|
|
65
|
+
if (command === "discord-commands" || command === "telegram-commands" || command === "slack-commands") {
|
|
66
|
+
const extra = command === "telegram-commands" ? " [--language CODE]"
|
|
67
|
+
: command === "slack-commands" ? " --manifest-token-env NAME" : "";
|
|
68
|
+
const usage = `Usage: ${command} --config FILE${extra} [--apply]`;
|
|
69
|
+
const valueFlags = new Set(["--config", ...(command === "telegram-commands" ? ["--language"]
|
|
70
|
+
: command === "slack-commands" ? ["--manifest-token-env"] : [])]);
|
|
71
|
+
const values = new Map<string, string>();
|
|
72
|
+
let apply = false;
|
|
73
|
+
for (let index = 1; index < args.length; index++) {
|
|
74
|
+
const flag = args[index]!;
|
|
75
|
+
if (flag === "--apply" && !apply) { apply = true; continue; }
|
|
76
|
+
const value = args[index + 1];
|
|
77
|
+
if (!valueFlags.has(flag) || values.has(flag) || !value || value.startsWith("-")) throw new Error(usage);
|
|
78
|
+
values.set(flag, value);
|
|
79
|
+
index++;
|
|
80
|
+
}
|
|
81
|
+
const configPath = values.get("--config");
|
|
82
|
+
const manifestTokenEnv = values.get("--manifest-token-env");
|
|
83
|
+
if (!configPath || command === "slack-commands" && !manifestTokenEnv) throw new Error(usage);
|
|
84
|
+
const config = await loadConfig(configPath);
|
|
85
|
+
let report: unknown;
|
|
86
|
+
if (command === "discord-commands") {
|
|
87
|
+
const { registerDiscordCommands } = await import("./discord-command-registration");
|
|
88
|
+
report = await registerDiscordCommands(config, { apply });
|
|
89
|
+
} else if (command === "telegram-commands") {
|
|
90
|
+
const { registerTelegramCommands } = await import("./telegram-command-registration");
|
|
91
|
+
report = await registerTelegramCommands(config, { apply, languageCode: values.get("--language") });
|
|
92
|
+
} else {
|
|
93
|
+
const { registerSlackCommands } = await import("./slack-command-registration");
|
|
94
|
+
report = await registerSlackCommands(config, { apply, manifestTokenEnv: manifestTokenEnv! });
|
|
95
|
+
}
|
|
96
|
+
console.log(JSON.stringify(report, null, 2));
|
|
97
|
+
if (report && typeof report === "object" && "status" in report && report.status === "blocked") process.exitCode = 1;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const config = await loadConfig(args[configAt + 1]!);
|
|
101
|
+
const target = args[1] && !args[1]!.startsWith("-") ? args[1]! : "main";
|
|
102
|
+
const paths = hostPaths(config, target);
|
|
103
|
+
if (command === "doctor") {
|
|
104
|
+
loadCredentials(config);
|
|
105
|
+
const omp = await inspectInstalledOmp(config.command, credentialEnvNames(config));
|
|
106
|
+
console.log(JSON.stringify({
|
|
107
|
+
config: config.path, command: config.command, headCwd: config.headCwd,
|
|
108
|
+
omp, nativeTuiAttach: false,
|
|
109
|
+
maxHosts: config.maxHosts, maxSubagents: config.maxSubagents,
|
|
110
|
+
platforms: configuredPlatforms(config),
|
|
111
|
+
credentials: Object.fromEntries(credentialEnvNames(config).map(name => [name, Boolean(process.env[name])])),
|
|
112
|
+
messengersActivated: false,
|
|
113
|
+
}, null, 2));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (command === "status") {
|
|
117
|
+
const { gatewayStatus } = await import("./gateway-protocol");
|
|
118
|
+
const { autostartStatus } = await import("./autostart");
|
|
119
|
+
console.log(JSON.stringify({
|
|
120
|
+
gateway: await gatewayStatus(config),
|
|
121
|
+
autostart: await autostartStatus(config),
|
|
122
|
+
main: { socketPath: hostPaths(config, "main").socketPath },
|
|
123
|
+
lanes: laneRows(config.stateDir).map(l => ({
|
|
124
|
+
id: l.id, title: l.title, cwd: l.cwd, workState: l.workState,
|
|
125
|
+
model: l.model ?? null, modelReason: l.modelReason ?? null, modelPreset: l.modelPreset ?? null,
|
|
126
|
+
recordedRuntimeState: l.runtimeState, sessionId: l.sessionId, socketPath: l.socketPath,
|
|
127
|
+
})),
|
|
128
|
+
note: "Gateway/head readiness is live when the Gateway is reachable; lane records are not a completion guarantee.",
|
|
129
|
+
}, null, 2));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (target !== "main" && !laneRows(config.stateDir).some(l => l.id === target))
|
|
133
|
+
throw new Error("Unknown managed lane");
|
|
134
|
+
if (command === "stop") {
|
|
135
|
+
if (target === "main") {
|
|
136
|
+
const { stopGateway } = await import("./gateway");
|
|
137
|
+
await stopGateway(config);
|
|
138
|
+
console.log("Gateway and supervised main host accepted graceful shutdown.");
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const { connect } = await import("./host");
|
|
142
|
+
const host = await connect(paths.socketPath);
|
|
143
|
+
try {
|
|
144
|
+
const response = await host.request({ type: "shutdown_host" });
|
|
145
|
+
if (!response.success) throw new Error(response.error ?? "Host refused shutdown");
|
|
146
|
+
console.log(`Host ${target} accepted graceful shutdown.`);
|
|
147
|
+
} finally { await host.close(); }
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (target !== "main") throw new Error("start only activates the Gateway/main service; lanes remain head-owned");
|
|
151
|
+
loadCredentials(config);
|
|
152
|
+
// Resolve required messenger credentials before native imports can populate env
|
|
153
|
+
// from their own project/provider configuration. Other native settings stay native.
|
|
154
|
+
requireMessengerCredentials(config);
|
|
155
|
+
const { gatewayPaths, launchGateway } = await import("./gateway");
|
|
156
|
+
const status = await launchGateway(config);
|
|
157
|
+
console.log(JSON.stringify({ ...status, gatewaySocketPath: gatewayPaths(config).socketPath,
|
|
158
|
+
gatewayLogPath: gatewayPaths(config).logPath,
|
|
159
|
+
note: "Gateway owns messenger transports. Explicit start may return while initialization is checking/running or blocked. head.ready requires verified native high/middle/low presets; head.initialization reports setup/recovery state separately from approval-reconciled intake readiness. Ordinary input remains durably queued until initialization completes." }, null, 2));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (import.meta.main) {
|
|
163
|
+
await main().catch(error => {
|
|
164
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
165
|
+
process.exitCode = 1;
|
|
166
|
+
});
|
|
167
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import type { Platform, Route } from "./contracts";
|
|
4
|
+
import { resolveOmpCommand } from "./installed-omp";
|
|
5
|
+
|
|
6
|
+
export interface DiscordConfig {
|
|
7
|
+
tokenEnv: string;
|
|
8
|
+
ownerId: string;
|
|
9
|
+
allowedGuildIds: string[];
|
|
10
|
+
allowedChannelIds: string[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface TelegramConfig {
|
|
14
|
+
tokenEnv: string;
|
|
15
|
+
ownerId: string;
|
|
16
|
+
allowedChatIds: string[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface SlackConfig {
|
|
20
|
+
botTokenEnv: string;
|
|
21
|
+
appTokenEnv: string;
|
|
22
|
+
ownerId: string;
|
|
23
|
+
teamId: string;
|
|
24
|
+
allowedChannelIds: string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface Config {
|
|
28
|
+
path: string;
|
|
29
|
+
stateDir: string;
|
|
30
|
+
headCwd: string;
|
|
31
|
+
command: string[];
|
|
32
|
+
maxHosts: number;
|
|
33
|
+
maxSubagents: number;
|
|
34
|
+
idleMs: number;
|
|
35
|
+
model?: string;
|
|
36
|
+
discord?: DiscordConfig;
|
|
37
|
+
telegram?: TelegramConfig;
|
|
38
|
+
slack?: SlackConfig;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function record(value: unknown, name: string): Record<string, unknown> {
|
|
42
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${name} must be an object`);
|
|
43
|
+
return value as Record<string, unknown>;
|
|
44
|
+
}
|
|
45
|
+
function text(value: unknown, name: string): string {
|
|
46
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required`);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function integer(value: unknown, name: string, minimum: number): number {
|
|
50
|
+
if (!Number.isSafeInteger(value) || (value as number) < minimum) throw new Error(`${name} must be an integer >= ${minimum}`);
|
|
51
|
+
return value as number;
|
|
52
|
+
}
|
|
53
|
+
function ids(value: unknown, name: string, pattern = /^\d+$/): string[] {
|
|
54
|
+
if (!Array.isArray(value) || !value.every(v => typeof v === "string" && pattern.test(v)))
|
|
55
|
+
throw new Error(`${name} must be an array of valid platform IDs`);
|
|
56
|
+
return [...new Set(value)];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function id(value: unknown, name: string, pattern: RegExp): string {
|
|
60
|
+
const result = text(value, name);
|
|
61
|
+
if (!pattern.test(result)) throw new Error(`${name} is not a valid platform ID`);
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function tokenEnv(value: unknown, name: string): string {
|
|
66
|
+
const result = text(value, name);
|
|
67
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(result)) throw new Error(`${name} must name an environment variable`);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function configuredPlatforms(config: Config): Platform[] {
|
|
72
|
+
return (["discord", "telegram", "slack"] as const).filter(platform => config[platform] !== undefined);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function credentialEnvNames(config: Config): string[] {
|
|
76
|
+
return [...new Set([
|
|
77
|
+
...(config.discord ? [config.discord.tokenEnv] : []),
|
|
78
|
+
...(config.telegram ? [config.telegram.tokenEnv] : []),
|
|
79
|
+
...(config.slack ? [config.slack.botTokenEnv, config.slack.appTokenEnv] : []),
|
|
80
|
+
])];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function requireMessengerCredentials(config: Config): void {
|
|
84
|
+
for (const name of credentialEnvNames(config)) {
|
|
85
|
+
if (!process.env[name]) throw new Error(`Missing messenger credential environment variable ${name}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Configuration policy; each adapter additionally checks authenticated account identity. */
|
|
90
|
+
export function authorizeRoute(config: Config, route: Route): boolean {
|
|
91
|
+
if (!route.accountId || !route.channelId || !route.authorityId) return false;
|
|
92
|
+
if (route.topicId !== undefined && (route.guildId !== null || route.threadId !== null || !route.topicId || route.topicId.length > 128)) return false;
|
|
93
|
+
switch (route.platform) {
|
|
94
|
+
case "discord": {
|
|
95
|
+
const policy = config.discord;
|
|
96
|
+
return !!policy && route.authorityId === policy.ownerId &&
|
|
97
|
+
(route.guildId === null ? route.threadId === null :
|
|
98
|
+
policy.allowedGuildIds.includes(route.guildId) && policy.allowedChannelIds.includes(route.channelId));
|
|
99
|
+
}
|
|
100
|
+
case "telegram": {
|
|
101
|
+
const policy = config.telegram;
|
|
102
|
+
return !!policy && route.authorityId === policy.ownerId &&
|
|
103
|
+
(route.guildId === null ? route.channelId === policy.ownerId :
|
|
104
|
+
route.guildId === route.channelId && policy.allowedChatIds.includes(route.channelId));
|
|
105
|
+
}
|
|
106
|
+
case "slack": {
|
|
107
|
+
const policy = config.slack;
|
|
108
|
+
return !!policy && route.authorityId === policy.ownerId &&
|
|
109
|
+
route.accountId.startsWith(`${policy.teamId}:`) &&
|
|
110
|
+
(route.guildId === null ? /^D[A-Z0-9]+$/.test(route.channelId) :
|
|
111
|
+
route.guildId === policy.teamId && policy.allowedChannelIds.includes(route.channelId));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function loadConfig(path: string): Promise<Config> {
|
|
117
|
+
const absolute = resolve(path);
|
|
118
|
+
return parseConfig(await Bun.file(absolute).json(), absolute);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Validate an in-memory setup candidate with exactly the same policy as a saved config. */
|
|
122
|
+
export function parseConfig(value: unknown, path: string): Config {
|
|
123
|
+
const absolute = resolve(path);
|
|
124
|
+
const raw = record(value, "config");
|
|
125
|
+
if (raw.modelPresets !== undefined)
|
|
126
|
+
throw new Error("modelPresets belong to native OMP settings; initialize them through the head, not this application config");
|
|
127
|
+
const discord = raw.discord === undefined ? undefined : record(raw.discord, "discord");
|
|
128
|
+
const telegram = raw.telegram === undefined ? undefined : record(raw.telegram, "telegram");
|
|
129
|
+
const slack = raw.slack === undefined ? undefined : record(raw.slack, "slack");
|
|
130
|
+
if (!discord && !telegram && !slack) throw new Error("Configure at least one messenger: discord, telegram, or slack");
|
|
131
|
+
const base = dirname(absolute);
|
|
132
|
+
const pathValue = (v: unknown, key: string) => resolve(base, text(v, key));
|
|
133
|
+
if (!Array.isArray(raw.command) || !raw.command.length ||
|
|
134
|
+
!raw.command.every(v => typeof v === "string" && v.length > 0))
|
|
135
|
+
throw new Error("command must be an argv array for an installed stock OMP executable");
|
|
136
|
+
if (raw.command.some(v => /^(?:--session-settings|--rpc-socket|--model-preset)(?:=|$)/.test(v)) || raw.command[1] === "attach")
|
|
137
|
+
throw new Error("command contains unsupported patched OMP arguments; configure an installed stock OMP executable");
|
|
138
|
+
const headCwd = realpathSync(pathValue(raw.headCwd, "headCwd"));
|
|
139
|
+
if (!lstatSync(headCwd).isDirectory()) throw new Error("headCwd must be a directory");
|
|
140
|
+
const command = resolveOmpCommand(raw.command as string[]);
|
|
141
|
+
const maxHosts = integer(raw.maxHosts, "maxHosts", 2);
|
|
142
|
+
const maxSubagents = integer(raw.maxSubagents, "maxSubagents", maxHosts);
|
|
143
|
+
return {
|
|
144
|
+
path: absolute,
|
|
145
|
+
stateDir: pathValue(raw.stateDir, "stateDir"),
|
|
146
|
+
headCwd,
|
|
147
|
+
command,
|
|
148
|
+
maxHosts,
|
|
149
|
+
maxSubagents,
|
|
150
|
+
idleMs: integer(raw.idleMs, "idleMs", 0),
|
|
151
|
+
...(raw.model === undefined ? {} : { model: text(raw.model, "model") }),
|
|
152
|
+
...(discord ? { discord: {
|
|
153
|
+
tokenEnv: tokenEnv(discord.tokenEnv, "discord.tokenEnv"),
|
|
154
|
+
ownerId: id(discord.ownerId, "discord.ownerId", /^\d+$/),
|
|
155
|
+
allowedGuildIds: ids(discord.allowedGuildIds, "discord.allowedGuildIds"),
|
|
156
|
+
allowedChannelIds: ids(discord.allowedChannelIds, "discord.allowedChannelIds"),
|
|
157
|
+
} } : {}),
|
|
158
|
+
...(telegram ? { telegram: {
|
|
159
|
+
tokenEnv: tokenEnv(telegram.tokenEnv, "telegram.tokenEnv"),
|
|
160
|
+
ownerId: id(telegram.ownerId, "telegram.ownerId", /^[1-9]\d*$/),
|
|
161
|
+
allowedChatIds: ids(telegram.allowedChatIds, "telegram.allowedChatIds", /^-\d+$/),
|
|
162
|
+
} } : {}),
|
|
163
|
+
...(slack ? { slack: {
|
|
164
|
+
botTokenEnv: tokenEnv(slack.botTokenEnv, "slack.botTokenEnv"),
|
|
165
|
+
appTokenEnv: tokenEnv(slack.appTokenEnv, "slack.appTokenEnv"),
|
|
166
|
+
ownerId: id(slack.ownerId, "slack.ownerId", /^[UW][A-Z0-9]+$/),
|
|
167
|
+
teamId: id(slack.teamId, "slack.teamId", /^T[A-Z0-9]+$/),
|
|
168
|
+
allowedChannelIds: ids(slack.allowedChannelIds, "slack.allowedChannelIds", /^[CG][A-Z0-9]+$/),
|
|
169
|
+
} } : {}),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** No caller can turn a shared/symlink directory into a trusted socket directory. */
|
|
174
|
+
export function privateDirectory(path: string): void {
|
|
175
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
176
|
+
const stat = lstatSync(path);
|
|
177
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid()))
|
|
178
|
+
throw new Error(`Not an owned directory: ${path}`);
|
|
179
|
+
chmodSync(path, 0o700);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function hostPaths(config: Config, id: string) {
|
|
183
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error("Invalid host ID");
|
|
184
|
+
const socketPath = join(config.stateDir, "run", `${id}.sock`);
|
|
185
|
+
if (Buffer.byteLength(socketPath) > 100) throw new Error("stateDir is too long for local Unix sockets; use a shorter private path");
|
|
186
|
+
return {
|
|
187
|
+
socketPath,
|
|
188
|
+
sessionFile: join(config.stateDir, "sessions", id, "session.jsonl"),
|
|
189
|
+
logPath: join(config.stateDir, "logs", `${id}.log`),
|
|
190
|
+
};
|
|
191
|
+
}
|
package/src/contracts.ts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import type { ModelPreset as NativeModelPreset } from "@oh-my-pi/pi-coding-agent/config/model-settings";
|
|
2
|
+
import type { LaneEvidence, LaneReport, LaneWaitTarget } from "./lane-report";
|
|
3
|
+
|
|
4
|
+
/** Coordination records only. OMP owns transcripts and execution state. */
|
|
5
|
+
export type Platform = "discord" | "telegram" | "slack";
|
|
6
|
+
|
|
7
|
+
export interface Route {
|
|
8
|
+
platform: Platform;
|
|
9
|
+
accountId: string;
|
|
10
|
+
authorityId: string;
|
|
11
|
+
guildId: string | null;
|
|
12
|
+
channelId: string;
|
|
13
|
+
threadId: string | null;
|
|
14
|
+
/** Coordination-only DM topic; never a platform channel/thread identifier. */
|
|
15
|
+
topicId?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function routeKey(route: Route): string {
|
|
19
|
+
const identity = [
|
|
20
|
+
route.platform, route.accountId, route.authorityId,
|
|
21
|
+
route.guildId, route.channelId, route.threadId,
|
|
22
|
+
];
|
|
23
|
+
// Preserve all existing physical-route keys in already-created ledgers.
|
|
24
|
+
if (route.topicId !== undefined) identity.push(route.topicId);
|
|
25
|
+
return JSON.stringify(identity);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function physicalRoute(route: Route): Route {
|
|
29
|
+
const { topicId: _topic, ...physical } = route;
|
|
30
|
+
return physical;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function physicalRouteKey(route: Route): string {
|
|
34
|
+
return routeKey(physicalRoute(route));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface Attachment {
|
|
38
|
+
id: string;
|
|
39
|
+
name: string;
|
|
40
|
+
/** Token-free resource reference; only the owning adapter resolves it. */
|
|
41
|
+
url: string;
|
|
42
|
+
/** null means the platform did not declare a size; zero is a known empty file. */
|
|
43
|
+
size: number | null;
|
|
44
|
+
contentType?: string;
|
|
45
|
+
voice?: true;
|
|
46
|
+
durationSeconds?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Untrusted contextual snapshot, never sender authority, command text, or routing. */
|
|
50
|
+
export interface ReplyContext {
|
|
51
|
+
messageId: string;
|
|
52
|
+
authorId: string | null;
|
|
53
|
+
text: string | null;
|
|
54
|
+
quote?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface Inbound {
|
|
58
|
+
id: string;
|
|
59
|
+
route: Route;
|
|
60
|
+
/** Actual platform message ID; application commands have no source message. */
|
|
61
|
+
messageId: string | null;
|
|
62
|
+
/** Discord's actual interaction snowflake, never its response token. */
|
|
63
|
+
interactionId?: string;
|
|
64
|
+
/** Slack's scoped SHA256 trigger fingerprint, never a message timestamp or capability. */
|
|
65
|
+
invocationId?: string;
|
|
66
|
+
text: string;
|
|
67
|
+
receivedAt: number;
|
|
68
|
+
attachments: Attachment[];
|
|
69
|
+
reply?: ReplyContext;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A real platform message that can be fetched, reacted to, or used as a thread source. */
|
|
73
|
+
export interface MessageReference {
|
|
74
|
+
route: Route;
|
|
75
|
+
messageId: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type WorkState = "open" | "paused" | "completed" | "cancelled";
|
|
79
|
+
export type RuntimeState = "unloaded" | "starting" | "running" | "idle" | "interrupted";
|
|
80
|
+
export interface LaneModel {
|
|
81
|
+
provider: string;
|
|
82
|
+
id: string;
|
|
83
|
+
}
|
|
84
|
+
export const MODEL_PRESET_NAMES = ["high", "middle", "low"] as const;
|
|
85
|
+
export type ModelPreset = string;
|
|
86
|
+
export type LanePresetSnapshot = NativeModelPreset;
|
|
87
|
+
export interface ResolvedLanePreset {
|
|
88
|
+
model: LaneModel;
|
|
89
|
+
preset: ModelPreset;
|
|
90
|
+
snapshot: LanePresetSnapshot;
|
|
91
|
+
}
|
|
92
|
+
export interface LaneModelChoice {
|
|
93
|
+
model?: LaneModel;
|
|
94
|
+
preset?: ModelPreset;
|
|
95
|
+
}
|
|
96
|
+
/** Observations, not verified acceptance, execution authority, or a live-state guarantee. */
|
|
97
|
+
export interface LaneObservation {
|
|
98
|
+
inputId: string;
|
|
99
|
+
requestId: string;
|
|
100
|
+
sessionId: string;
|
|
101
|
+
generation: number;
|
|
102
|
+
lastReportAt: number;
|
|
103
|
+
summary: string;
|
|
104
|
+
lastEvidenceAt: number | null;
|
|
105
|
+
lastEvidence: (LaneEvidence & { at: number }) | null;
|
|
106
|
+
waiting: { target: LaneWaitTarget; since: number } | null;
|
|
107
|
+
}
|
|
108
|
+
export interface Lane {
|
|
109
|
+
id: string;
|
|
110
|
+
title: string;
|
|
111
|
+
route: Route;
|
|
112
|
+
cwd: string;
|
|
113
|
+
repoRoot: string | null;
|
|
114
|
+
brief: string;
|
|
115
|
+
acceptance: string[];
|
|
116
|
+
/** Null only for pre-selection records awaiting native-state adoption. */
|
|
117
|
+
model: LaneModel | null;
|
|
118
|
+
modelReason: string | null;
|
|
119
|
+
/** Preset label at selection time, never a live link to mutable configuration. */
|
|
120
|
+
modelPreset: ModelPreset | null;
|
|
121
|
+
modelPresetSnapshot: LanePresetSnapshot | null;
|
|
122
|
+
workState: WorkState;
|
|
123
|
+
runtimeState: RuntimeState;
|
|
124
|
+
sessionFile: string;
|
|
125
|
+
sessionId: string | null;
|
|
126
|
+
socketPath: string;
|
|
127
|
+
generation: number;
|
|
128
|
+
pid: number | null;
|
|
129
|
+
createdAt: number;
|
|
130
|
+
lastActivityAt: number;
|
|
131
|
+
result: string | null;
|
|
132
|
+
observation?: LaneObservation;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export type InputState = "pending" | "submitted" | "done" | "uncertain" | "cancelled";
|
|
136
|
+
export const WORKFLOW_NAMES = ["ulw", "mass-ulw", "ulw-plan", "ulw-loop", "ulw-execute", "ulw-research", "jevify"] as const;
|
|
137
|
+
export type WorkflowName = typeof WORKFLOW_NAMES[number];
|
|
138
|
+
export interface WorkflowChoice {
|
|
139
|
+
name: WorkflowName;
|
|
140
|
+
reason: string;
|
|
141
|
+
}
|
|
142
|
+
/** An activation request, not proof of native arming or native goal creation. */
|
|
143
|
+
export interface WorkflowActivation extends WorkflowChoice {
|
|
144
|
+
sourceId: string;
|
|
145
|
+
provenance: "user" | "head";
|
|
146
|
+
}
|
|
147
|
+
export interface InputRecord extends Inbound {
|
|
148
|
+
workflow: WorkflowActivation | null;
|
|
149
|
+
target: string | null;
|
|
150
|
+
state: InputState;
|
|
151
|
+
requestId: string | null;
|
|
152
|
+
generation: number | null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export type OutputState = "pending" | "sending" | "sent" | "uncertain" | "failed";
|
|
156
|
+
export interface OutputRecord {
|
|
157
|
+
id: string;
|
|
158
|
+
sourceId: string;
|
|
159
|
+
route: Route;
|
|
160
|
+
text: string;
|
|
161
|
+
state: OutputState;
|
|
162
|
+
remoteId: string | null;
|
|
163
|
+
error: string | null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface Approval {
|
|
167
|
+
id: string;
|
|
168
|
+
target: string;
|
|
169
|
+
generation: number;
|
|
170
|
+
requestId: string;
|
|
171
|
+
route: Route;
|
|
172
|
+
request: Record<string, unknown>;
|
|
173
|
+
state: "pending" | "answered" | "cancelled";
|
|
174
|
+
remoteId: string | null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface HeadRecoveryDecision {
|
|
178
|
+
attemptId: string;
|
|
179
|
+
decision: "release" | "hold";
|
|
180
|
+
evidenceEntryIds: string[];
|
|
181
|
+
reason: string;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface HeadRecoveryAttempt {
|
|
185
|
+
attemptId: string;
|
|
186
|
+
inputId: string;
|
|
187
|
+
requestId: string;
|
|
188
|
+
generation: number;
|
|
189
|
+
sessionId: string;
|
|
190
|
+
sessionFile: string;
|
|
191
|
+
hostPid: number;
|
|
192
|
+
recoveryRequestId: string;
|
|
193
|
+
promptDigest: string;
|
|
194
|
+
stopBoundary: string | null;
|
|
195
|
+
cursor: string | null;
|
|
196
|
+
boundary: string;
|
|
197
|
+
evidenceEntryIds: string[];
|
|
198
|
+
evidenceFingerprint: string;
|
|
199
|
+
state: "prepared" | "submitted" | "decided" | "settled" | "held";
|
|
200
|
+
decision?: HeadRecoveryDecision;
|
|
201
|
+
outcome?: "done" | "cancelled";
|
|
202
|
+
blocked?: boolean;
|
|
203
|
+
abandonedByOwner?: true;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface HeadRecoveryEffect {
|
|
207
|
+
id: string;
|
|
208
|
+
kind: string;
|
|
209
|
+
state: string;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export interface StorePort {
|
|
213
|
+
receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
|
|
214
|
+
input(id: string): InputRecord | null;
|
|
215
|
+
inputs(target?: string): InputRecord[];
|
|
216
|
+
/** Actual authorized user messages, including settled records, in durable admission order. */
|
|
217
|
+
admittedMessages(route: Route): InputRecord[];
|
|
218
|
+
bindInput(id: string, target: string): void;
|
|
219
|
+
submit(id: string, requestId: string, generation: number): boolean;
|
|
220
|
+
/** Nonterminal native assistant observation; never settles or dispatches its owner. */
|
|
221
|
+
progress(id: string, generation: number, sessionId: string, eventId: string, text: string): boolean;
|
|
222
|
+
recordLaneReport(id: string, generation: number, sessionId: string, eventId: string, report: LaneReport, observedAt?: number): boolean;
|
|
223
|
+
resolveLaneWaiting(id: string, generation: number, sessionId: string, kind: "tool" | "approval", nativeId: string): boolean;
|
|
224
|
+
settle(id: string, state: "done" | "uncertain" | "cancelled", output?: { id: string; text: string }): boolean;
|
|
225
|
+
headRecoveryEffects(inputId: string): HeadRecoveryEffect[];
|
|
226
|
+
prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
|
|
227
|
+
commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
|
|
228
|
+
queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error">): boolean;
|
|
229
|
+
output(id: string): OutputRecord | null;
|
|
230
|
+
outputs(): OutputRecord[];
|
|
231
|
+
claimOutput(id: string): boolean;
|
|
232
|
+
finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void;
|
|
233
|
+
createLane(lane: Lane & { model: LaneModel; modelReason: string }, sourceId: string): Lane;
|
|
234
|
+
lane(id: string): Lane | null;
|
|
235
|
+
laneForRoute(route: Route): Lane | null;
|
|
236
|
+
lanes(): Lane[];
|
|
237
|
+
updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
|
|
238
|
+
"workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
|
|
239
|
+
>>): boolean;
|
|
240
|
+
nextGeneration(id: string): Lane;
|
|
241
|
+
adoptLaneModel(id: string, generation: number, model: LaneModel, reason: string): boolean;
|
|
242
|
+
changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: string,
|
|
243
|
+
preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata?: Readonly<Record<string, string>>): boolean;
|
|
244
|
+
putApproval(approval: Approval): void;
|
|
245
|
+
approval(id: string): Approval | null;
|
|
246
|
+
approvals(target?: string): Approval[];
|
|
247
|
+
resolveApproval(id: string, generation: number, state: "answered" | "cancelled"): boolean;
|
|
248
|
+
setApprovalMessage(id: string, remoteId: string): void;
|
|
249
|
+
recoverDeliveries(): void;
|
|
250
|
+
getMeta(key: string): string | null;
|
|
251
|
+
setMeta(key: string, value: string): void;
|
|
252
|
+
close(): void;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export interface DialogResponse {
|
|
256
|
+
value?: string;
|
|
257
|
+
confirmed?: boolean;
|
|
258
|
+
cancelled?: boolean;
|
|
259
|
+
answers?: Array<{ id: string; selectedOptions: string[]; customInput?: string }>;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export type MessageActivity = "received" | "thinking" | "idle";
|
|
263
|
+
|
|
264
|
+
export interface GatewayRestartRequest {
|
|
265
|
+
/** Persisted UUID, shared by controller and authenticated Gateway protocol. */
|
|
266
|
+
requestId: string;
|
|
267
|
+
inputId: string;
|
|
268
|
+
ackOutputId: string;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Durable lifecycle receipt, bound to the original owner input and owned processes. */
|
|
272
|
+
export interface GatewayRestartRecord extends GatewayRestartRequest {
|
|
273
|
+
/** Original Gateway and native HEAD, never the one-shot runner. */
|
|
274
|
+
gatewayPid: number;
|
|
275
|
+
headPid: number;
|
|
276
|
+
sessionId: string;
|
|
277
|
+
sessionFile: string;
|
|
278
|
+
state: "accepted" | "head-stopped" | "started" | "refused" | "uncertain" | "failed";
|
|
279
|
+
/** Replacement Gateway PID. The detached runner has a separate private plan identity. */
|
|
280
|
+
successorPid?: number;
|
|
281
|
+
/** Replacement native HEAD PID. */
|
|
282
|
+
replacementPid?: number;
|
|
283
|
+
reason?: string;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export interface GatewayRestartNotice {
|
|
287
|
+
requestId: string;
|
|
288
|
+
outcome: "refused" | "uncertain";
|
|
289
|
+
reason: string;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface Messenger {
|
|
293
|
+
start(handlers: {
|
|
294
|
+
/** Authenticate first; do not consume inbound events until native approvals are reconciled. */
|
|
295
|
+
ready?: Promise<void>;
|
|
296
|
+
message(input: Inbound): Promise<void>;
|
|
297
|
+
answer(approvalId: string, response: DialogResponse, route: Route): Promise<void>;
|
|
298
|
+
/** Reconcile a previously attempted answer before retrying its native effect. */
|
|
299
|
+
reconcileAnswer?(approvalId: string, route: Route): Promise<"retry" | "accepted" | "rejected" | "unresolved">;
|
|
300
|
+
reconnect?(): Promise<void>;
|
|
301
|
+
/** Owned Gateway lifecycle outcome; never a user instruction or model turn. */
|
|
302
|
+
restart?(notice: GatewayRestartNotice): Promise<void>;
|
|
303
|
+
}): Promise<void>;
|
|
304
|
+
send(output: OutputRecord): Promise<string>;
|
|
305
|
+
/** Cosmetic own reactions on the original message; never an admission or completion receipt. */
|
|
306
|
+
setActivity?(message: MessageReference, activity: MessageActivity): Promise<void>;
|
|
307
|
+
showApproval(approval: Approval): Promise<string>;
|
|
308
|
+
dismissApproval(approval: Approval): Promise<void>;
|
|
309
|
+
/** Read-only authenticated capability probe; false is unsupported, not a failed creation. */
|
|
310
|
+
canCreateThread?(route: Route): Promise<boolean>;
|
|
311
|
+
createThread(route: Route, title: string, sourceMessageId?: string): Promise<Route>;
|
|
312
|
+
/** null explicitly means no history API; intake recovery belongs to the adapter. */
|
|
313
|
+
fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null>;
|
|
314
|
+
/** Validate platform/auth destination before fetching. Never follow redirects with credentials. */
|
|
315
|
+
openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response>;
|
|
316
|
+
stop(): Promise<void>;
|
|
317
|
+
}
|