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
package/src/config.ts ADDED
@@ -0,0 +1,266 @@
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
+ voice?: DiscordVoiceConfig;
12
+ }
13
+
14
+ type DiscordVoiceSessionConfig = {
15
+ readonly channelId: string;
16
+ readonly textChannelId: string;
17
+ readonly voice: string;
18
+ readonly maxSessionSeconds: number;
19
+ };
20
+
21
+ export type DiscordVoiceConfig = DiscordVoiceSessionConfig & (
22
+ | {
23
+ readonly auth?: "api";
24
+ readonly apiKeyEnv: string;
25
+ readonly model: string;
26
+ readonly backendModel: string;
27
+ }
28
+ | {
29
+ readonly auth: "subscription";
30
+ readonly apiKeyEnv?: never;
31
+ readonly model?: never;
32
+ readonly backendModel?: never;
33
+ }
34
+ );
35
+
36
+ export interface TelegramConfig {
37
+ tokenEnv: string;
38
+ ownerId: string;
39
+ allowedChatIds: string[];
40
+ }
41
+
42
+ export interface SlackConfig {
43
+ botTokenEnv: string;
44
+ appTokenEnv: string;
45
+ ownerId: string;
46
+ teamId: string;
47
+ allowedChannelIds: string[];
48
+ }
49
+
50
+ export interface Config {
51
+ path: string;
52
+ stateDir: string;
53
+ headCwd: string;
54
+ command: string[];
55
+ maxHosts: number;
56
+ maxSubagents: number;
57
+ idleMs: number;
58
+ model?: string;
59
+ discord?: DiscordConfig;
60
+ telegram?: TelegramConfig;
61
+ slack?: SlackConfig;
62
+ }
63
+
64
+ function record(value: unknown, name: string): Record<string, unknown> {
65
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${name} must be an object`);
66
+ return value as Record<string, unknown>;
67
+ }
68
+ function text(value: unknown, name: string): string {
69
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required`);
70
+ return value;
71
+ }
72
+ function integer(value: unknown, name: string, minimum: number): number {
73
+ if (!Number.isSafeInteger(value) || (value as number) < minimum) throw new Error(`${name} must be an integer >= ${minimum}`);
74
+ return value as number;
75
+ }
76
+ function ids(value: unknown, name: string, pattern = /^\d+$/): string[] {
77
+ if (!Array.isArray(value) || !value.every(v => typeof v === "string" && pattern.test(v)))
78
+ throw new Error(`${name} must be an array of valid platform IDs`);
79
+ return [...new Set(value)];
80
+ }
81
+
82
+ function id(value: unknown, name: string, pattern: RegExp): string {
83
+ const result = text(value, name);
84
+ if (!pattern.test(result)) throw new Error(`${name} is not a valid platform ID`);
85
+ return result;
86
+ }
87
+
88
+ function tokenEnv(value: unknown, name: string): string {
89
+ const result = text(value, name);
90
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(result)) throw new Error(`${name} must name an environment variable`);
91
+ return result;
92
+ }
93
+
94
+ export function configuredPlatforms(config: Config): Platform[] {
95
+ return (["discord", "telegram", "slack"] as const).filter(platform => config[platform] !== undefined);
96
+ }
97
+
98
+ export function voiceApiKeyEnv(config: Config): string | undefined {
99
+ const voice = config.discord?.voice;
100
+ switch (voice?.auth) {
101
+ case "api":
102
+ case undefined:
103
+ return voice?.apiKeyEnv;
104
+ case "subscription":
105
+ return undefined;
106
+ }
107
+ }
108
+
109
+ export function credentialEnvNames(config: Config): string[] {
110
+ const voiceKey = voiceApiKeyEnv(config);
111
+ return [...new Set([
112
+ ...(config.discord ? [config.discord.tokenEnv] : []),
113
+ ...(voiceKey === undefined ? [] : [voiceKey]),
114
+ ...(config.telegram ? [config.telegram.tokenEnv] : []),
115
+ ...(config.slack ? [config.slack.botTokenEnv, config.slack.appTokenEnv] : []),
116
+ ])];
117
+ }
118
+
119
+ export function requireMessengerCredentials(config: Config): void {
120
+ // Only an explicit API voice session needs its provider key, not text intake.
121
+ const voiceKey = voiceApiKeyEnv(config);
122
+ for (const name of credentialEnvNames(config)) {
123
+ if (name === voiceKey) continue;
124
+ if (!process.env[name]) throw new Error(`Missing messenger credential environment variable ${name}`);
125
+ }
126
+ }
127
+
128
+ /** Configuration policy; each adapter additionally checks authenticated account identity. */
129
+ export function authorizeRoute(config: Config, route: Route): boolean {
130
+ if (!route.accountId || !route.channelId || !route.authorityId) return false;
131
+ if (route.topicId !== undefined && (route.guildId !== null || route.threadId !== null || !route.topicId || route.topicId.length > 128)) return false;
132
+ switch (route.platform) {
133
+ case "discord": {
134
+ const policy = config.discord;
135
+ return !!policy && route.authorityId === policy.ownerId &&
136
+ (route.guildId === null ? route.threadId === null :
137
+ policy.allowedGuildIds.includes(route.guildId) && policy.allowedChannelIds.includes(route.channelId));
138
+ }
139
+ case "telegram": {
140
+ const policy = config.telegram;
141
+ return !!policy && route.authorityId === policy.ownerId &&
142
+ (route.guildId === null ? route.channelId === policy.ownerId :
143
+ route.guildId === route.channelId && policy.allowedChatIds.includes(route.channelId));
144
+ }
145
+ case "slack": {
146
+ const policy = config.slack;
147
+ return !!policy && route.authorityId === policy.ownerId &&
148
+ route.accountId.startsWith(`${policy.teamId}:`) &&
149
+ (route.guildId === null ? /^D[A-Z0-9]+$/.test(route.channelId) :
150
+ route.guildId === policy.teamId && policy.allowedChannelIds.includes(route.channelId));
151
+ }
152
+ }
153
+ }
154
+
155
+ export async function loadConfig(path: string): Promise<Config> {
156
+ const absolute = resolve(path);
157
+ return parseConfig(await Bun.file(absolute).json(), absolute);
158
+ }
159
+
160
+ /** Validate an in-memory setup candidate with exactly the same policy as a saved config. */
161
+ export function parseConfig(value: unknown, path: string): Config {
162
+ const absolute = resolve(path);
163
+ const raw = record(value, "config");
164
+ if (raw.modelPresets !== undefined)
165
+ throw new Error("modelPresets belong to native OMP settings; initialize them through the head, not this application config");
166
+ const discord = raw.discord === undefined ? undefined : record(raw.discord, "discord");
167
+ const telegram = raw.telegram === undefined ? undefined : record(raw.telegram, "telegram");
168
+ const slack = raw.slack === undefined ? undefined : record(raw.slack, "slack");
169
+ if (!discord && !telegram && !slack) throw new Error("Configure at least one messenger: discord, telegram, or slack");
170
+ const base = dirname(absolute);
171
+ const pathValue = (v: unknown, key: string) => resolve(base, text(v, key));
172
+ if (!Array.isArray(raw.command) || !raw.command.length ||
173
+ !raw.command.every(v => typeof v === "string" && v.length > 0))
174
+ throw new Error("command must be an argv array for an installed stock OMP executable");
175
+ if (raw.command.some(v => /^(?:--session-settings|--rpc-socket|--model-preset)(?:=|$)/.test(v)) || raw.command[1] === "attach")
176
+ throw new Error("command contains unsupported patched OMP arguments; configure an installed stock OMP executable");
177
+ const headCwd = realpathSync(pathValue(raw.headCwd, "headCwd"));
178
+ if (!lstatSync(headCwd).isDirectory()) throw new Error("headCwd must be a directory");
179
+ const command = resolveOmpCommand(raw.command as string[], process.env.PATH, base);
180
+ const maxHosts = integer(raw.maxHosts, "maxHosts", 2);
181
+ const maxSubagents = integer(raw.maxSubagents, "maxSubagents", maxHosts);
182
+ const discordChannels = discord ? ids(discord.allowedChannelIds, "discord.allowedChannelIds") : [];
183
+ const voice = discord?.voice === undefined ? undefined : record(discord.voice, "discord.voice");
184
+ let voiceConfig: DiscordVoiceConfig | undefined;
185
+ if (voice) {
186
+ const channelId = id(voice.channelId, "discord.voice.channelId", /^\d+$/);
187
+ const textChannelId = id(voice.textChannelId, "discord.voice.textChannelId", /^\d+$/);
188
+ if (textChannelId === channelId || !discordChannels.includes(textChannelId))
189
+ throw new Error("discord.voice.textChannelId must be a separate, allowed text channel");
190
+ const maxSessionSeconds = integer(voice.maxSessionSeconds, "discord.voice.maxSessionSeconds", 1);
191
+ if (maxSessionSeconds * 1000 > 2 ** 31 - 1) throw new Error("discord.voice.maxSessionSeconds exceeds timer range");
192
+ const session = { channelId, textChannelId, voice: text(voice.voice, "discord.voice.voice"), maxSessionSeconds };
193
+ const auth = voice.auth;
194
+ switch (auth) {
195
+ case "subscription": {
196
+ const unsupported = Object.keys(voice).find(key => key !== "auth" && !Object.hasOwn(session, key));
197
+ if (unsupported !== undefined) throw new Error(`discord.voice.${unsupported} is not supported with subscription auth`);
198
+ voiceConfig = { ...session, auth: "subscription" };
199
+ break;
200
+ }
201
+ case "api":
202
+ case undefined: {
203
+ const apiKeyEnv = tokenEnv(voice.apiKeyEnv, "discord.voice.apiKeyEnv");
204
+ if ([discord?.tokenEnv, telegram?.tokenEnv, slack?.appTokenEnv, slack?.botTokenEnv].includes(apiKeyEnv))
205
+ throw new Error("discord.voice.apiKeyEnv must not name a messenger token");
206
+ voiceConfig = {
207
+ ...session, ...(auth === undefined ? {} : { auth }), apiKeyEnv,
208
+ model: text(voice.model, "discord.voice.model"),
209
+ backendModel: text(voice.backendModel, "discord.voice.backendModel"),
210
+ };
211
+ break;
212
+ }
213
+ default:
214
+ throw new Error('discord.voice.auth must be "api" or "subscription"');
215
+ }
216
+ }
217
+ return {
218
+ path: absolute,
219
+ stateDir: pathValue(raw.stateDir, "stateDir"),
220
+ headCwd,
221
+ command,
222
+ maxHosts,
223
+ maxSubagents,
224
+ idleMs: integer(raw.idleMs, "idleMs", 0),
225
+ ...(raw.model === undefined ? {} : { model: text(raw.model, "model") }),
226
+ ...(discord ? { discord: {
227
+ tokenEnv: tokenEnv(discord.tokenEnv, "discord.tokenEnv"),
228
+ ownerId: id(discord.ownerId, "discord.ownerId", /^\d+$/),
229
+ allowedGuildIds: ids(discord.allowedGuildIds, "discord.allowedGuildIds"),
230
+ allowedChannelIds: discordChannels,
231
+ ...(voiceConfig ? { voice: voiceConfig } : {}),
232
+ } } : {}),
233
+ ...(telegram ? { telegram: {
234
+ tokenEnv: tokenEnv(telegram.tokenEnv, "telegram.tokenEnv"),
235
+ ownerId: id(telegram.ownerId, "telegram.ownerId", /^[1-9]\d*$/),
236
+ allowedChatIds: ids(telegram.allowedChatIds, "telegram.allowedChatIds", /^-\d+$/),
237
+ } } : {}),
238
+ ...(slack ? { slack: {
239
+ botTokenEnv: tokenEnv(slack.botTokenEnv, "slack.botTokenEnv"),
240
+ appTokenEnv: tokenEnv(slack.appTokenEnv, "slack.appTokenEnv"),
241
+ ownerId: id(slack.ownerId, "slack.ownerId", /^[UW][A-Z0-9]+$/),
242
+ teamId: id(slack.teamId, "slack.teamId", /^T[A-Z0-9]+$/),
243
+ allowedChannelIds: ids(slack.allowedChannelIds, "slack.allowedChannelIds", /^[CG][A-Z0-9]+$/),
244
+ } } : {}),
245
+ };
246
+ }
247
+
248
+ /** No caller can turn a shared/symlink directory into a trusted socket directory. */
249
+ export function privateDirectory(path: string): void {
250
+ mkdirSync(path, { recursive: true, mode: 0o700 });
251
+ const stat = lstatSync(path);
252
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid()))
253
+ throw new Error(`Not an owned directory: ${path}`);
254
+ chmodSync(path, 0o700);
255
+ }
256
+
257
+ export function hostPaths(config: Config, id: string) {
258
+ if (!/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error("Invalid host ID");
259
+ const socketPath = join(config.stateDir, "run", `${id}.sock`);
260
+ if (Buffer.byteLength(socketPath) > 100) throw new Error("stateDir is too long for local Unix sockets; use a shorter private path");
261
+ return {
262
+ socketPath,
263
+ sessionFile: join(config.stateDir, "sessions", id, "session.jsonl"),
264
+ logPath: join(config.stateDir, "logs", `${id}.log`),
265
+ };
266
+ }
@@ -0,0 +1,381 @@
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
+ /** Untrusted observations, never instructions, authority, or automatic routing policy.
58
+ * For threads, channel describes the parent and thread describes the destination.
59
+ * Missing optional properties mean unavailable; a null topic is an observed empty topic.
60
+ */
61
+ export interface DiscordContext {
62
+ readonly kind: "guild" | "dm";
63
+ readonly channel: {
64
+ readonly id: string;
65
+ readonly name?: string;
66
+ readonly topic?: string | null;
67
+ readonly purpose?: string;
68
+ };
69
+ readonly thread?: { readonly id: string; readonly parentId: string; readonly name?: string; readonly purpose?: string };
70
+ }
71
+
72
+ export type DiscordPurposeRequest = {
73
+ readonly sourceId: string;
74
+ readonly route: Route;
75
+ } & (
76
+ | { readonly action: "list" }
77
+ | { readonly action: "set"; readonly purpose: string }
78
+ | { readonly action: "clear" }
79
+ );
80
+ export interface DiscordPurposeNote { readonly route: Route; readonly purpose: string }
81
+
82
+ export interface Inbound {
83
+ id: string;
84
+ route: Route;
85
+ /** Actual platform message ID; application commands have no source message. */
86
+ messageId: string | null;
87
+ /** Discord's actual interaction snowflake, never its response token. */
88
+ interactionId?: string;
89
+ /** Slack's scoped SHA256 trigger fingerprint, never a message timestamp or capability. */
90
+ invocationId?: string;
91
+ text: string;
92
+ receivedAt: number;
93
+ attachments: Attachment[];
94
+ reply?: ReplyContext;
95
+ discordContext?: DiscordContext;
96
+ }
97
+
98
+ /** A real platform message that can be fetched, reacted to, or used as a thread source. */
99
+ export interface MessageReference {
100
+ route: Route;
101
+ messageId: string;
102
+ }
103
+
104
+ export type WorkState = "open" | "paused" | "completed" | "cancelled";
105
+ export type RuntimeState = "unloaded" | "starting" | "running" | "idle" | "interrupted";
106
+ export interface LaneModel {
107
+ provider: string;
108
+ id: string;
109
+ }
110
+ export const HEAD_MODEL_CONTROL = "head:model-control";
111
+ export interface HeadModelChange {
112
+ readonly sourceId: string;
113
+ readonly model: LaneModel;
114
+ }
115
+ export const MODEL_PRESET_NAMES = ["high", "middle", "low"] as const;
116
+ export type ModelPreset = string;
117
+ export type LanePresetSnapshot = NativeModelPreset;
118
+ export interface ResolvedLanePreset {
119
+ model: LaneModel;
120
+ preset: ModelPreset;
121
+ snapshot: LanePresetSnapshot;
122
+ }
123
+ export interface LaneModelChoice {
124
+ model?: LaneModel;
125
+ preset?: ModelPreset;
126
+ }
127
+ /** Observations, not verified acceptance, execution authority, or a live-state guarantee. */
128
+ export interface LaneObservation {
129
+ inputId: string;
130
+ requestId: string;
131
+ sessionId: string;
132
+ generation: number;
133
+ lastReportAt: number;
134
+ summary: string;
135
+ lastEvidenceAt: number | null;
136
+ lastEvidence: (LaneEvidence & { at: number }) | null;
137
+ waiting: { target: LaneWaitTarget; since: number } | null;
138
+ }
139
+ export interface Lane {
140
+ id: string;
141
+ title: string;
142
+ route: Route;
143
+ cwd: string;
144
+ repoRoot: string | null;
145
+ brief: string;
146
+ acceptance: string[];
147
+ /** Null only for pre-selection records awaiting native-state adoption. */
148
+ model: LaneModel | null;
149
+ modelReason: string | null;
150
+ /** Preset label at selection time, never a live link to mutable configuration. */
151
+ modelPreset: ModelPreset | null;
152
+ modelPresetSnapshot: LanePresetSnapshot | null;
153
+ workState: WorkState;
154
+ runtimeState: RuntimeState;
155
+ sessionFile: string;
156
+ sessionId: string | null;
157
+ socketPath: string;
158
+ generation: number;
159
+ pid: number | null;
160
+ createdAt: number;
161
+ lastActivityAt: number;
162
+ result: string | null;
163
+ observation?: LaneObservation;
164
+ }
165
+
166
+ export type InputState = "pending" | "submitted" | "done" | "uncertain" | "cancelled";
167
+ export const WORKFLOW_NAMES = ["ulw", "mass-ulw", "ulw-plan", "ulw-loop", "ulw-execute", "ulw-research", "jevify"] as const;
168
+ export type WorkflowName = typeof WORKFLOW_NAMES[number];
169
+ export interface WorkflowChoice {
170
+ name: WorkflowName;
171
+ reason: string;
172
+ }
173
+ /** An activation request, not proof of native arming or native goal creation. */
174
+ export interface WorkflowActivation extends WorkflowChoice {
175
+ sourceId: string;
176
+ provenance: "user" | "head";
177
+ }
178
+ export interface InputRecord extends Inbound {
179
+ workflow: WorkflowActivation | null;
180
+ target: string | null;
181
+ state: InputState;
182
+ requestId: string | null;
183
+ generation: number | null;
184
+ }
185
+
186
+ export type OutputState = "pending" | "sending" | "sent" | "uncertain" | "failed";
187
+ export interface OutputRecord {
188
+ id: string;
189
+ sourceId: string;
190
+ route: Route;
191
+ /** Durable original owner message, only in the same physical conversation. */
192
+ replyTo?: MessageReference;
193
+ text: string;
194
+ state: OutputState;
195
+ remoteId: string | null;
196
+ error: string | null;
197
+ }
198
+
199
+ export interface Approval {
200
+ id: string;
201
+ target: string;
202
+ generation: number;
203
+ requestId: string;
204
+ route: Route;
205
+ request: Record<string, unknown>;
206
+ state: "pending" | "answered" | "cancelled";
207
+ remoteId: string | null;
208
+ decision?: { id: string; sourceId: string | null; sessionId: string };
209
+ }
210
+
211
+ export interface ApprovalResolution {
212
+ response?: DialogResponse;
213
+ reason?: string;
214
+ sourceId?: string;
215
+ headSelection?: { readonly reviewId: string; readonly reason: string };
216
+ }
217
+
218
+ export interface HeadRecoveryDecision {
219
+ attemptId: string;
220
+ decision: "release" | "hold";
221
+ evidenceEntryIds: string[];
222
+ reason: string;
223
+ }
224
+
225
+ export interface HeadRecoveryAttempt {
226
+ attemptId: string;
227
+ inputId: string;
228
+ requestId: string;
229
+ generation: number;
230
+ sessionId: string;
231
+ sessionFile: string;
232
+ hostPid: number;
233
+ recoveryRequestId: string;
234
+ promptDigest: string;
235
+ stopBoundary: string | null;
236
+ cursor: string | null;
237
+ boundary: string;
238
+ evidenceEntryIds: string[];
239
+ evidenceFingerprint: string;
240
+ state: "prepared" | "submitted" | "decided" | "settled" | "held";
241
+ decision?: HeadRecoveryDecision;
242
+ outcome?: "done" | "cancelled";
243
+ blocked?: boolean;
244
+ abandonedByOwner?: true;
245
+ }
246
+
247
+ export interface HeadRecoveryEffect {
248
+ id: string;
249
+ kind: string;
250
+ state: string;
251
+ }
252
+
253
+ export interface StorePort {
254
+ receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
255
+ input(id: string): InputRecord | null;
256
+ ownerSource(id: string): InputRecord | null;
257
+ inputs(target?: string): InputRecord[];
258
+ /** The first authorized revision on the physical route, even after settlement. */
259
+ firstAdmittedMessage(route: Route, messageId: string): InputRecord | null;
260
+ /** Actual authorized message IDs in durable admission order; not invocation or edit IDs. */
261
+ admittedMessageIds(route: Route): Iterable<string>;
262
+ bindInput(id: string, target: string): void;
263
+ submit(id: string, requestId: string, generation: number): boolean;
264
+ /** Nonterminal native assistant observation; never settles or dispatches its owner. */
265
+ progress(id: string, generation: number, sessionId: string, eventId: string, text: string): boolean;
266
+ recordLaneReport(id: string, generation: number, sessionId: string, eventId: string, report: LaneReport, observedAt?: number): boolean;
267
+ resolveLaneWaiting(id: string, generation: number, sessionId: string, kind: "tool" | "approval", nativeId: string): boolean;
268
+ settle(id: string, state: "done" | "uncertain" | "cancelled", output?: { id: string; text: string }, headModel?: HeadModelChange): boolean;
269
+ headRecoveryEffects(inputId: string): HeadRecoveryEffect[];
270
+ prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
271
+ commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
272
+ queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error">): boolean;
273
+ output(id: string): OutputRecord | null;
274
+ outputs(): OutputRecord[];
275
+ claimOutput(id: string): boolean;
276
+ finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void;
277
+ createLane(lane: Lane & { model: LaneModel; modelReason: string }, sourceId: string): Lane;
278
+ lane(id: string): Lane | null;
279
+ laneForRoute(route: Route): Lane | null;
280
+ lanes(): Lane[];
281
+ updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
282
+ "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
283
+ >>): boolean;
284
+ nextGeneration(id: string): Lane;
285
+ adoptLaneModel(id: string, generation: number, model: LaneModel, reason: string): boolean;
286
+ changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: string,
287
+ preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata?: Readonly<Record<string, string>>): boolean;
288
+ putApproval(approval: Approval): void;
289
+ approval(id: string): Approval | null;
290
+ approvals(target?: string): Approval[];
291
+ resolveApproval(id: string, generation: number, state: "answered" | "cancelled", resolution?: ApprovalResolution): boolean;
292
+ setApprovalMessage(id: string, remoteId: string): void;
293
+ recoverDeliveries(): void;
294
+ getMeta(key: string): string | null;
295
+ setMeta(key: string, value: string): void;
296
+ close(): void;
297
+ }
298
+
299
+ export interface DialogResponse {
300
+ value?: string;
301
+ confirmed?: boolean;
302
+ cancelled?: boolean;
303
+ answers?: Array<{ id: string; selectedOptions: string[]; customInput?: string }>;
304
+ }
305
+
306
+ export type MessageActivity = "received" | "thinking" | "idle";
307
+
308
+ export interface GatewayRestartRequest {
309
+ /** Persisted UUID, shared by controller and authenticated Gateway protocol. */
310
+ requestId: string;
311
+ inputId: string;
312
+ ackOutputId: string;
313
+ }
314
+
315
+ /** Durable lifecycle receipt, bound to the original owner input and owned processes. */
316
+ export interface GatewayRestartRecord extends GatewayRestartRequest {
317
+ /** Original Gateway and native HEAD, never the one-shot runner. */
318
+ gatewayPid: number;
319
+ headPid: number;
320
+ sessionId: string;
321
+ sessionFile: string;
322
+ state: "accepted" | "head-stopped" | "started" | "refused" | "uncertain" | "failed";
323
+ /** Replacement Gateway PID. The detached runner has a separate private plan identity. */
324
+ successorPid?: number;
325
+ /** Replacement native HEAD PID. */
326
+ replacementPid?: number;
327
+ reason?: string;
328
+ }
329
+
330
+ export interface GatewayRestartNotice {
331
+ requestId: string;
332
+ outcome: "refused" | "uncertain";
333
+ reason: string;
334
+ }
335
+
336
+ export interface ThreadInfo {
337
+ readonly route: Route;
338
+ readonly title: string;
339
+ readonly archived: boolean | null;
340
+ readonly requiresTag: boolean;
341
+ readonly availableTags: readonly { readonly id: string; readonly name: string; readonly moderated: boolean }[];
342
+ readonly appliedTags: readonly string[];
343
+ }
344
+
345
+ export interface ThreadUpdate {
346
+ readonly title?: string;
347
+ readonly appliedTags?: readonly string[];
348
+ readonly archived?: boolean;
349
+ }
350
+
351
+ export interface Messenger {
352
+ start(handlers: {
353
+ /** Authenticate first; do not consume inbound events until native approvals are reconciled. */
354
+ ready?: Promise<void>;
355
+ message(input: Inbound): Promise<void>;
356
+ answer(approvalId: string, response: DialogResponse, route: Route): Promise<void>;
357
+ /** Reconcile a previously attempted answer before retrying its native effect. */
358
+ reconcileAnswer?(approvalId: string, route: Route): Promise<"retry" | "accepted" | "rejected" | "unresolved">;
359
+ reconnect?(): Promise<void>;
360
+ /** Owned Gateway lifecycle outcome; never a user instruction or model turn. */
361
+ restart?(notice: GatewayRestartNotice): Promise<void>;
362
+ }): Promise<void>;
363
+ send(output: OutputRecord): Promise<string>;
364
+ /** Cosmetic own reactions on the original message; never an admission or completion receipt. */
365
+ setActivity?(message: MessageReference, activity: MessageActivity): Promise<void>;
366
+ showApproval(approval: Approval): Promise<string>;
367
+ dismissApproval(approval: Approval): Promise<void>;
368
+ /** Read-only authenticated capability probe; false is unsupported, not a failed creation. */
369
+ canCreateThread?(route: Route, appliedTags?: readonly string[]): Promise<boolean>;
370
+ createThread(route: Route, title: string, sourceMessageId?: string, appliedTags?: readonly string[]): Promise<Route>;
371
+ /** Optional native thread management; unsupported transports must not simulate it. */
372
+ inspectThread?(route: Route): Promise<ThreadInfo>;
373
+ updateThread?(route: Route, update: ThreadUpdate): Promise<ThreadInfo>;
374
+ inspectDiscordContext?(route: Route): Promise<DiscordContext>;
375
+ discordPurpose?(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]>;
376
+ /** null explicitly means no history API; intake recovery belongs to the adapter. */
377
+ fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null>;
378
+ /** Validate platform/auth destination before fetching. Never follow redirects with credentials. */
379
+ openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response>;
380
+ stop(): Promise<void>;
381
+ }