omp-superagent 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/DESIGN.md +16 -8
  2. package/README.ko.md +28 -374
  3. package/README.md +30 -421
  4. package/THIRD_PARTY_NOTICES.md +8 -8
  5. package/config.example.json +7 -0
  6. package/docs/OPERATIONS.en.md +2223 -0
  7. package/docs/OPERATIONS.md +164 -23
  8. package/docs/design/execution.md +164 -18
  9. package/docs/design/messaging.md +78 -17
  10. package/docs/kakao-bridge-protocol.md +193 -0
  11. package/docs/releases/0.1.10.md +17 -0
  12. package/docs/releases/0.1.9.md +18 -0
  13. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  14. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  16. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  24. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  32. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  44. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  48. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  52. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  56. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  57. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  58. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  60. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  61. package/package.json +10 -8
  62. package/skills/head/SKILL.md +28 -14
  63. package/skills/head/references/routing.md +23 -17
  64. package/skills/head/references/supervision.md +22 -1
  65. package/skills/lane/SKILL.md +11 -0
  66. package/skills/lane/references/workflow.md +17 -8
  67. package/src/cli.ts +6 -4
  68. package/src/config.ts +44 -3
  69. package/src/contracts.ts +101 -8
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +44 -6
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-recovery.ts +226 -17
  75. package/src/host-extension.ts +132 -17
  76. package/src/host-protocol.ts +6 -9
  77. package/src/host-reply-voice.ts +181 -0
  78. package/src/lane-extension.ts +46 -8
  79. package/src/lane-models.ts +8 -0
  80. package/src/lane-report.ts +22 -0
  81. package/src/managed-ulw-probe.ts +22 -20
  82. package/src/message-order.ts +2 -1
  83. package/src/messenger-command-catalog.json +6 -3
  84. package/src/messenger-commands.ts +9 -2
  85. package/src/operator.ts +77 -0
  86. package/src/pr-github-schema.ts +2 -0
  87. package/src/pr-intake-automation.ts +1 -2
  88. package/src/pr-intake-comment.ts +1 -2
  89. package/src/pr-intake-fix.ts +1 -2
  90. package/src/pr-intake-github.ts +1 -2
  91. package/src/pr-intake-material.ts +1 -2
  92. package/src/pr-intake-tree.ts +1 -2
  93. package/src/pr-review-models.ts +28 -0
  94. package/src/result-attachment.ts +60 -79
  95. package/src/runtime.ts +1862 -298
  96. package/src/setup-profiles.ts +26 -65
  97. package/src/setup.ts +2 -1
  98. package/src/slack-command-registration.ts +48 -197
  99. package/src/soul.ts +214 -0
  100. package/src/store.ts +643 -55
  101. package/src/superkit-skills.ts +22 -0
  102. package/src/telegram-command-languages.json +17 -0
  103. package/src/telegram-command-registration.ts +32 -134
  104. package/src/worker-bridge.ts +21 -0
  105. package/src/worker-enrollment.ts +2 -1
  106. package/src/worker-host.ts +0 -24
  107. package/src/worker-serve-prepare.ts +19 -0
  108. package/src/worker-service.ts +51 -47
  109. package/scripts/ci.ts +0 -44
  110. package/scripts/release.ts +0 -112
  111. package/scripts/test-omp.sh +0 -44
  112. package/src/discord-commands.ts +0 -29
  113. package/src/discord-markdown.ts +0 -399
  114. package/src/slack-commands.ts +0 -18
  115. package/src/telegram-signal.ts +0 -14
  116. package/src/worker-stdio.ts +0 -61
@@ -0,0 +1,22 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ // Canonical skill IDs match the commands. Legacy IDs remain wire tags and
5
+ // aliases (the plain SUPER command's legacy command name is "ulw").
6
+ export const superkitWorkflows = [
7
+ ["super-plan", "ulw-plan"],
8
+ ["super-run", "ulw-execute"],
9
+ ["super-loop", "ulw-loop"],
10
+ ["super-graph", "mass-ulw"],
11
+ ["super-research", "ulw-research"],
12
+ ] as const;
13
+
14
+ export const canonicalSuperkitSkills = ["super", ...superkitWorkflows.map(([command]) => command)] as const;
15
+ export const legacySuperkitSkills = ["ultrawork", ...superkitWorkflows.map(([, id]) => id)] as const;
16
+
17
+ // Select the layout for the whole revision: the probe rejects incomplete
18
+ // canonical packages rather than falling back to individual legacy aliases.
19
+ export function hasCanonicalSuperkitSkills(packagePath: string): boolean {
20
+ return canonicalSuperkitSkills.some(id =>
21
+ lstatSync(join(packagePath, "skills", id, "SKILL.md"), { throwIfNoEntry: false }) !== undefined);
22
+ }
@@ -0,0 +1,17 @@
1
+ [
2
+ "aa", "ab", "ae", "af", "ak", "am", "an", "ar", "as", "av", "ay", "az",
3
+ "ba", "be", "bg", "bi", "bm", "bn", "bo", "br", "bs",
4
+ "ca", "ce", "ch", "co", "cr", "cs", "cu", "cv", "cy",
5
+ "da", "de", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu",
6
+ "fa", "ff", "fi", "fj", "fo", "fr", "fy", "ga", "gd", "gl", "gn", "gu", "gv",
7
+ "ha", "he", "hi", "ho", "hr", "ht", "hu", "hy", "hz",
8
+ "ia", "id", "ie", "ig", "ii", "ik", "io", "is", "it", "iu",
9
+ "ja", "jv", "ka", "kg", "ki", "kj", "kk", "kl", "km", "kn", "ko", "kr", "ks", "ku", "kv", "kw", "ky",
10
+ "la", "lb", "lg", "li", "ln", "lo", "lt", "lu", "lv",
11
+ "mg", "mh", "mi", "mk", "ml", "mn", "mr", "ms", "mt", "my",
12
+ "na", "nb", "nd", "ne", "ng", "nl", "nn", "no", "nr", "nv", "ny",
13
+ "oc", "oj", "om", "or", "os", "pa", "pi", "pl", "ps", "pt", "qu",
14
+ "rm", "rn", "ro", "ru", "rw", "sa", "sc", "sd", "se", "sg", "si", "sk", "sl", "sm", "sn", "so", "sq", "sr", "ss", "st", "su", "sv", "sw",
15
+ "ta", "te", "tg", "th", "ti", "tk", "tl", "tn", "to", "tr", "ts", "tt", "tw", "ty",
16
+ "ug", "uk", "ur", "uz", "ve", "vi", "vo", "wa", "wo", "xh", "yi", "yo", "za", "zh", "zu"
17
+ ]
@@ -1,155 +1,53 @@
1
- import { Api } from "grammy";
2
- import type { BotCommand, BotCommandScopeChat, BotCommandScopeChatMember, LanguageCode } from "grammy/types";
3
1
  import type { Config } from "./config";
4
- import { loadCredentials, validateCredential } from "./credentials";
5
- import { MESSENGER_COMMANDS } from "./messenger-commands";
2
+ import { operatorBotToken, runOperator, type OperatorRun } from "./operator";
3
+ import languageCodes from "./telegram-command-languages.json";
6
4
 
7
- type CommandApi = Pick<Api, "getMe" | "getChat" | "getChatMember" | "getMyCommands" | "setMyCommands">;
8
- type OwnerScope = BotCommandScopeChat | BotCommandScopeChatMember;
9
-
10
- // The SDK exports its language mapping as declarations only, not runtime data.
11
- // Keep validation tied to its actual union rather than asserting any two letters.
12
- const LANGUAGE_CODES = [
13
- "aa", "ab", "ae", "af", "ak", "am", "an", "ar", "as", "av", "ay", "az",
14
- "ba", "be", "bg", "bi", "bm", "bn", "bo", "br", "bs",
15
- "ca", "ce", "ch", "co", "cr", "cs", "cu", "cv", "cy",
16
- "da", "de", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu",
17
- "fa", "ff", "fi", "fj", "fo", "fr", "fy", "ga", "gd", "gl", "gn", "gu", "gv",
18
- "ha", "he", "hi", "ho", "hr", "ht", "hu", "hy", "hz",
19
- "ia", "id", "ie", "ig", "ii", "ik", "io", "is", "it", "iu",
20
- "ja", "jv", "ka", "kg", "ki", "kj", "kk", "kl", "km", "kn", "ko", "kr", "ks", "ku", "kv", "kw", "ky",
21
- "la", "lb", "lg", "li", "ln", "lo", "lt", "lu", "lv",
22
- "mg", "mh", "mi", "mk", "ml", "mn", "mr", "ms", "mt", "my",
23
- "na", "nb", "nd", "ne", "ng", "nl", "nn", "no", "nr", "nv", "ny",
24
- "oc", "oj", "om", "or", "os", "pa", "pi", "pl", "ps", "pt", "qu",
25
- "rm", "rn", "ro", "ru", "rw", "sa", "sc", "sd", "se", "sg", "si", "sk", "sl", "sm", "sn", "so", "sq", "sr", "ss", "st", "su", "sv", "sw",
26
- "ta", "te", "tg", "th", "ti", "tk", "tl", "tn", "to", "tr", "ts", "tt", "tw", "ty",
27
- "ug", "uk", "ur", "uz", "ve", "vi", "vo", "wa", "wo", "xh", "yi", "yo", "za", "zh", "zu",
28
- ] as const satisfies readonly LanguageCode[];
29
-
30
- function normalizeLanguageCode(value: string | undefined): LanguageCode | undefined {
31
- // Omission and the API's empty-string selector both select the default list.
32
- // Omit both because the installed SDK does not include "" in LanguageCode.
33
- if (value === undefined || value === "") return undefined;
34
- const language = LANGUAGE_CODES.find(code => code === value);
35
- if (language === undefined) throw new Error("Telegram command language must be an empty string or a two-letter lowercase ISO 639-1 code");
36
- return language;
5
+ interface MenuCommand {
6
+ readonly command: string;
7
+ readonly description: string;
37
8
  }
38
9
 
10
+ type OwnerScope = { readonly type: "chat"; readonly chat_id: string }
11
+ | { readonly type: "chat_member"; readonly chat_id: string; readonly user_id: number };
12
+
39
13
  export interface TelegramCommandRegistrationOptions {
40
- apply?: boolean;
14
+ readonly apply?: boolean;
41
15
  /** Omit for the default language list; Telegram cannot enumerate language overrides. */
42
- languageCode?: string;
43
- createApi?: (token: string) => CommandApi;
16
+ readonly languageCode?: string;
17
+ readonly run?: OperatorRun;
44
18
  }
45
19
 
46
20
  export interface TelegramCommandRegistrationReport {
47
- status: "dry-run" | "applied";
48
- botId: string;
49
- languageCode: string | null;
50
- plannedCommands: BotCommand[];
51
- scopes: { scope: OwnerScope; current: BotCommand[]; changed: boolean }[];
52
- note: string;
21
+ readonly status: "dry-run" | "applied";
22
+ readonly botId: string;
23
+ readonly languageCode: string | null;
24
+ readonly plannedCommands: readonly MenuCommand[];
25
+ readonly scopes: readonly {
26
+ readonly scope: OwnerScope;
27
+ readonly current: readonly MenuCommand[];
28
+ readonly changed: boolean;
29
+ }[];
30
+ readonly note: string;
53
31
  }
54
32
 
55
- function commands(value: unknown): BotCommand[] {
56
- if (!Array.isArray(value) || value.length > 100) throw new Error("Invalid command list");
57
- return value.map(row => {
58
- if (!row || typeof row !== "object" || typeof row.command !== "string" ||
59
- !/^[a-z0-9_]{1,32}$/.test(row.command) || typeof row.description !== "string" ||
60
- row.description.length < 1 || row.description.length > 256) throw new Error("Invalid command definition");
61
- return { command: row.command, description: row.description };
62
- });
63
- }
64
-
65
- function exact(actual: BotCommand[], expected: BotCommand[]): boolean {
66
- // Order also defines the visible picker, so a reordered list is not exact.
67
- return JSON.stringify(actual) === JSON.stringify(expected);
68
- }
69
-
70
- /** API-only, opt-in menus. Never polls, manages webhooks, or imports the runtime. */
33
+ /** API-only, opt-in menus. Never polls, manages webhooks, or starts OMP. */
71
34
  export async function registerTelegramCommands(
72
35
  config: Config, options: TelegramCommandRegistrationOptions = {},
73
36
  ): Promise<TelegramCommandRegistrationReport> {
74
37
  const policy = config.telegram;
75
38
  if (!policy) throw new Error("telegram-commands requires configured Telegram credentials and policy");
39
+ // Keep bad operator input separate from failures reading private credentials.
76
40
  if (!/^[1-9][0-9]*$/.test(policy.ownerId) || !Number.isSafeInteger(Number(policy.ownerId)) ||
77
- policy.allowedChatIds.some(id => !/^-[1-9][0-9]*$/.test(id) || !Number.isSafeInteger(Number(id)))) {
41
+ policy.allowedChatIds.some(id => !/^-[1-9][0-9]*$/.test(id) || !Number.isSafeInteger(Number(id)))) {
78
42
  throw new Error("Telegram command menus require a positive owner ID and negative allowed group IDs");
79
43
  }
80
- const languageCode = normalizeLanguageCode(options.languageCode);
81
- try {
82
- // Preserve the existing explicit-environment/private-file precedence while
83
- // neither loading nor requiring any other platform's credentials.
84
- loadCredentials({ ...config, discord: undefined, slack: undefined });
85
- } catch { throw new Error("Cannot safely load the configured Telegram credential; details suppressed"); }
86
- const token = process.env[policy.tokenEnv];
87
- if (!token) throw new Error("Configured Telegram credential is missing");
88
- try { validateCredential(token); }
89
- catch { throw new Error("Configured Telegram credential is invalid; value suppressed"); }
90
-
91
- let api: CommandApi;
92
- try {
93
- // No retry transformer. Redirects must not forward the token-bearing URL.
94
- api = (options.createApi ?? (credential => new Api(credential, {
95
- sensitiveLogs: false, timeoutSeconds: 45, baseFetchConfig: { redirect: "error" },
96
- })))(token);
97
- } catch { throw new Error("Telegram API initialization failed; details suppressed"); }
98
-
99
- const plannedCommands = MESSENGER_COMMANDS.map(command => ({ command: command.name, description: command.description }));
100
- const language = languageCode === undefined ? {} : { language_code: languageCode };
101
- const scopes: TelegramCommandRegistrationReport["scopes"] = [];
102
- let botId: string;
103
- try {
104
- const bot = await api.getMe();
105
- if (!bot.is_bot || !Number.isSafeInteger(bot.id) || bot.id <= 0 || String(bot.id) === policy.ownerId) throw new Error("Invalid bot identity");
106
- botId = String(bot.id);
107
- const ownerChat = await api.getChat(policy.ownerId);
108
- if (String(ownerChat.id) !== policy.ownerId || ownerChat.type !== "private") throw new Error("Invalid owner DM");
109
- const targets: OwnerScope[] = [{ type: "chat", chat_id: policy.ownerId }];
110
- for (const chatId of new Set(policy.allowedChatIds)) {
111
- const chat = await api.getChat(chatId);
112
- if (String(chat.id) !== chatId || (chat.type !== "group" && chat.type !== "supergroup") ||
113
- ("is_direct_messages" in chat && chat.is_direct_messages === true)) throw new Error("Invalid allowed group");
114
- const member = await api.getChatMember(chatId, Number(policy.ownerId));
115
- if (String(member.user.id) !== policy.ownerId || member.user.is_bot ||
116
- !(member.status === "creator" || member.status === "administrator" || member.status === "member" ||
117
- (member.status === "restricted" && member.is_member))) throw new Error("Owner membership not verified");
118
- targets.push({ type: "chat_member", chat_id: chatId, user_id: Number(policy.ownerId) });
119
- }
120
- // Finish every ownership and menu read before attempting any mutation.
121
- for (const scope of targets) {
122
- const current = commands(await api.getMyCommands({ scope, ...language }));
123
- scopes.push({ scope, current, changed: !exact(current, plannedCommands) });
124
- }
125
- } catch {
126
- throw new Error("Telegram command inspection failed: bot identity, owner DM, allowed-group membership, or menu response could not be verified. No mutation was attempted; raw API details suppressed. No automatic retry was attempted.");
127
- }
128
-
129
- if (options.apply === true) {
130
- for (const target of scopes) {
131
- if (!target.changed) continue;
132
- try {
133
- const result = await api.setMyCommands(plannedCommands, { scope: target.scope, ...language });
134
- if (result !== true) throw new Error("Missing success receipt");
135
- } catch {
136
- throw new Error("Telegram command menu update is unresolved: the request failed and may have reached Telegram; earlier scopes may already have changed. No automatic retry was attempted; raw API details suppressed. Inspect with telegram-commands without --apply before deciding any further mutation.");
137
- }
138
- try {
139
- const actual = commands(await api.getMyCommands({ scope: target.scope, ...language }));
140
- if (!exact(actual, plannedCommands)) throw new Error("Menu readback differs");
141
- } catch {
142
- throw new Error("Telegram command menu update is unresolved: authoritative getMyCommands did not verify the exact supported names, descriptions, and order; earlier scopes may already have changed. No automatic retry was attempted; raw API details suppressed. Inspect with telegram-commands without --apply before deciding any further mutation.");
143
- }
144
- }
44
+ const { languageCode } = options;
45
+ if (languageCode !== undefined && languageCode !== "" && !languageCodes.includes(languageCode)) {
46
+ throw new Error("Telegram command language must be an empty string or a two-letter lowercase ISO 639-1 code");
145
47
  }
146
- const redact = (text: string) => text.replaceAll(token, "[redacted]").replace(/https?:\/\/\S+/gi, "[redacted-url]");
147
- return {
148
- status: options.apply === true ? "applied" : "dry-run", botId, languageCode: options.languageCode ?? null,
149
- plannedCommands,
150
- scopes: scopes.map(target => ({ ...target, current: target.current.map(command => ({
151
- command: command.command, description: redact(command.description),
152
- })) })),
153
- note: `${options.apply === true ? "Owner-scoped command menus verified by getMyCommands, including exact supported names, descriptions, and order." : "Read-only plan; no mutation was attempted. --apply replaces only these owner-scoped command lists."} Only the selected language list is inspected or changed. Other scopes and bot configuration are untouched. Language-specific menus not selected here are unknown and untouched: Telegram cannot enumerate them, and they may override the default-language menu. No polling, webhooks, or native runtime was started.`,
154
- };
48
+ const bot = operatorBotToken("Telegram", config.path, policy.tokenEnv);
49
+ return (options.run ?? runOperator)("telegram-commands", {
50
+ apply: options.apply === true, ownerId: policy.ownerId,
51
+ allowedChatIds: policy.allowedChatIds, languageCode,
52
+ }, { bot });
155
53
  }
@@ -0,0 +1,21 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { fileURLToPath } from "node:url";
3
+ import { hostOwnerExecutable } from "./host-owner-path";
4
+ import { WorkerRefusal } from "./worker-request";
5
+ import { trustedWorkerPath } from "./worker-trust";
6
+ import type { WorkerPolicy } from "./worker-wire";
7
+
8
+ export function workerBridgePaths(repos: WorkerPolicy["repos"]) {
9
+ return {
10
+ bin: trustedWorkerPath(hostOwnerExecutable, repos, "file"),
11
+ bun: trustedWorkerPath(realpathSync(process.execPath), repos, "file"),
12
+ helper: trustedWorkerPath(fileURLToPath(new URL("./worker-serve-prepare.ts", import.meta.url)), repos, "file"),
13
+ };
14
+ }
15
+
16
+ /** Preserve the PID sshd is waiting on, and transfer unread stdin without a JS pipe. */
17
+ export function execWorkerBridge(policy: WorkerPolicy, path: string): never {
18
+ const { bin, bun, helper } = workerBridgePaths(policy.repos);
19
+ if (!process.execve) throw new WorkerRefusal("Worker serve requires Bun execve support");
20
+ return process.execve(bin, [bin, "--worker-serve", bun, helper, path], process.env);
21
+ }
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { Type } from "@sinclair/typebox/type";
9
9
  import { Value } from "@sinclair/typebox/value";
10
10
  import { stagePrivateFile } from "./credentials";
11
+ import { workerBridgePaths } from "./worker-bridge";
11
12
  import {
12
13
  checkWorkerFile, readWorkerFile, shellWord, withWorkerWriteLock, workerDirectory,
13
14
  workerHash, workerPublicKey, WorkerRegistrationError,
@@ -48,7 +49,7 @@ function policyAt(path: string) {
48
49
  function enrollmentAuthorization(path: string, key: string, repos: WorkerPolicy["repos"]): string {
49
50
  trustedWorkerPath(workerInstallRoot, repos, "directory");
50
51
  const cli = trustedWorkerPath(fileURLToPath(new URL("./cli.ts", import.meta.url)), repos, "file");
51
- const bun = trustedWorkerPath(realpathSync(process.execPath), repos, "file");
52
+ const { bun } = workerBridgePaths(repos);
52
53
  const argv = [bun, "--no-env-file", cli, "worker", "serve", "--policy", path].map(shellWord);
53
54
  const command = `exec ${argv.join(" ")}`.replaceAll('"', '\\"');
54
55
  return `restrict,command="${command}" ${key} omp-sa-worker`;
@@ -1,5 +1,4 @@
1
1
  import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync, type Stats } from "node:fs";
2
- import { createConnection, type Socket } from "node:net";
3
2
  import { dirname, join } from "node:path";
4
3
  import { Value } from "@sinclair/typebox/value";
5
4
  import { HostConnection } from "./host";
@@ -10,7 +9,6 @@ import { remoteLanePaths, type WorkerPolicy, type WorkerProbe } from "./worker-w
10
9
 
11
10
  export const WORKER_ATTEMPT_ENV = "OMP_SUPERAGENT_WORKER_ATTEMPT";
12
11
  export const WORKER_SESSION_ENV = "OMP_SUPERAGENT_WORKER_EXPECTED_SESSION";
13
- const SOCKET_TIMEOUT_MS = 5_000;
14
12
 
15
13
  export function workerPaths(policy: WorkerPolicy, laneId: string) {
16
14
  const { socketPath, sessionFile } = remoteLanePaths(policy, laneId);
@@ -156,25 +154,3 @@ export async function inspectWorkerHost(ledger: WorkerLedger, paths: WorkerPaths
156
154
  return { socket: !!files.socket, sessionFile: !!files.session, sessionId: null,
157
155
  pid, pidAlive: nativeAlive, ownerAlive, uncertain: true };
158
156
  }
159
-
160
- export async function rawWorkerSocket(path: string, identity: WorkerIdentity): Promise<Socket> {
161
- if (!sameFile(identity, checkedSocket(path))) throw new WorkerRefusal("Worker socket changed before attach");
162
- const socket = createConnection(path);
163
- socket.pause();
164
- try {
165
- await new Promise<void>((resolve, reject) => {
166
- const timer = setTimeout(() => socket.destroy(new WorkerRefusal("Worker socket attach timed out")), SOCKET_TIMEOUT_MS);
167
- socket.once("error", reject);
168
- socket.once("connect", () => { clearTimeout(timer); resolve(); });
169
- socket.once("close", () => {
170
- clearTimeout(timer);
171
- reject(new WorkerRefusal("Worker socket closed during attach"));
172
- });
173
- });
174
- if (!sameFile(identity, checkedSocket(path))) throw new WorkerRefusal("Worker socket changed during attach");
175
- return socket;
176
- } catch (error) {
177
- socket.destroy();
178
- throw error;
179
- }
180
- }
@@ -0,0 +1,19 @@
1
+ // Private one-shot input from the Rust forced-command transport, not SSH stdio.
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { readWorkerPolicy } from "./worker-enrollment";
5
+ import { WorkerRefusal } from "./worker-request";
6
+ import { prepareWorker } from "./worker-service";
7
+ import { WORKER_HEADER_BYTES } from "./worker-wire";
8
+
9
+ const [path, ...extra] = process.argv.slice(2);
10
+ if (!path || extra.length || process.env.SSH_ORIGINAL_COMMAND !== "omp-sa-worker-v1")
11
+ throw new WorkerRefusal("Worker serve requires the enrolled SSH forced command");
12
+ const policy = readWorkerPolicy(homedir(), path);
13
+ const input = readFileSync(0); // The Rust parent writes one bounded header and closes this private pipe.
14
+ if (!input.length || input.length > WORKER_HEADER_BYTES || input.indexOf(10) !== input.length - 1)
15
+ throw new WorkerRefusal("Invalid private worker admission input");
16
+ const preparation = await prepareWorker(policy, input.subarray(0, -1));
17
+ await new Promise<void>((resolve, reject) => {
18
+ process.stdout.write(JSON.stringify(preparation), error => error ? reject(error) : resolve());
19
+ });
@@ -1,15 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { lstatSync, type Stats } from "node:fs";
2
3
  import { dirname } from "node:path";
3
- import type { Readable, Writable } from "node:stream";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { startHost } from "./host";
6
6
  import { boundWorkspace, enrolledRepo, privateWorkerDirectory, reserveCheckout } from "./worker-checkout";
7
- import { absentWorkerHost, attestWorkerHost, inspectWorkerHost, rawWorkerSocket, readWorkerFiles,
7
+ import { absentWorkerHost, attestWorkerHost, inspectWorkerHost, readWorkerFiles,
8
8
  WORKER_ATTEMPT_ENV, WORKER_SESSION_ENV, workerPaths } from "./worker-host";
9
9
  import { WorkerLedger, type WorkerReceipt } from "./worker-ledger";
10
10
  import { assertWorkerGitStartup, requireWorkerStartupFlags, workerLaunchProfile, workerManagedUlwPath } from "./worker-profile";
11
11
  import { parseWorkerPolicy, parseWorkerRequest, WorkerRefusal } from "./worker-request";
12
- import { bridgeWorker, workerHeader, workerReply } from "./worker-stdio";
13
12
  import type { WorkerDescription, WorkerLaneRef, WorkerLaunch, WorkerPolicy, WorkerProbe, WorkerRepo } from "./worker-wire";
14
13
 
15
14
  type WorkerLane = {
@@ -18,6 +17,23 @@ type WorkerLane = {
18
17
  readonly paths: ReturnType<typeof workerPaths>;
19
18
  };
20
19
  type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
20
+ type WorkerFileIdentity = Pick<Stats, "dev" | "ino">;
21
+ type AttachPermit = {
22
+ readonly generation: number; readonly workerAttempt: string;
23
+ readonly socketPath: string; readonly sessionFile: string; readonly sessionId: string;
24
+ readonly pid: number; readonly ownerPid: number;
25
+ readonly socket: { readonly dev: string; readonly ino: string };
26
+ readonly journal: { readonly dev: string; readonly ino: string };
27
+ };
28
+ type WorkerReply = { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly error: string };
29
+ type WorkerPreparation = { readonly kind: "reply"; readonly reply: WorkerReply } | ({ readonly kind: "attach" } & AttachPermit);
30
+
31
+ function exactInode(path: string, expected: WorkerFileIdentity) {
32
+ const { dev, ino } = lstatSync(path, { bigint: true });
33
+ if (Number(dev) !== expected.dev || Number(ino) !== expected.ino)
34
+ throw new WorkerRefusal("Worker socket or journal changed before attach");
35
+ return { dev: dev.toString(), ino: ino.toString() };
36
+ }
21
37
 
22
38
  function validateStorage(policy: WorkerPolicy): void {
23
39
  if (!privateWorkerDirectory(policy.stateDir)) throw new WorkerRefusal("Private worker storage is missing");
@@ -167,7 +183,7 @@ class WorkerService {
167
183
  }
168
184
  }
169
185
 
170
- async attach(ref: WorkerLaneRef) {
186
+ async attach(ref: WorkerLaneRef): Promise<AttachPermit> {
171
187
  const lane = this.#lane(ref);
172
188
  const observed = this.#receipt(lane);
173
189
  if (observed?.generation !== ref.generation) throw new WorkerRefusal("No worker launch receipt for this generation");
@@ -176,55 +192,43 @@ class WorkerService {
176
192
  if (receipt?.attempt !== observed.attempt || receipt.phase !== "live" ||
177
193
  !probe.socket || !probe.pidAlive || !probe.ownerAlive)
178
194
  throw new WorkerRefusal("Worker lane does not have an attachable native Host");
179
- const identity = await attestWorkerHost(lane.paths, await readWorkerFiles(lane.paths), receipt);
180
- const socket = await rawWorkerSocket(lane.paths.socketPath, identity);
195
+ const files = await readWorkerFiles(lane.paths);
196
+ if (!files.session) throw new WorkerRefusal("No owned worker socket/journal/checkout");
197
+ const { pid, ownerPid, sessionId, sessionFile, ...identity } = await attestWorkerHost(lane.paths, files, receipt);
198
+ const { socketPath } = lane.paths;
199
+ const socket = exactInode(socketPath, identity);
200
+ const journal = exactInode(sessionFile, files.session);
181
201
  const current = this.#receipt(lane);
182
- if (current?.phase !== "live" || current.attempt !== receipt.attempt) {
183
- socket.destroy();
202
+ if (current?.phase !== "live" || current.generation !== ref.generation || current.attempt !== receipt.attempt)
184
203
  throw new WorkerRefusal("Worker lane changed before attach");
185
- }
186
- return { socket, value: { pid: identity.pid, sessionId: identity.sessionId, sessionFile: identity.sessionFile } };
204
+ return { generation: receipt.generation, workerAttempt: receipt.attempt,
205
+ socketPath, sessionFile, sessionId, pid, ownerPid, socket, journal };
187
206
  }
188
207
  }
189
208
 
190
- /** One authorized forced-command invocation; never reads commands after the header except an attested native bridge. */
191
- export async function serveWorker(policy: WorkerPolicy, input: Readable = process.stdin, output: Writable = process.stdout): Promise<void> {
209
+ /** A bounded admission step; only the native worker transport receives post-header bytes. */
210
+ export async function prepareWorker(policy: WorkerPolicy, header: Buffer): Promise<WorkerPreparation> {
192
211
  let service: WorkerService | undefined;
193
- let attach: Awaited<ReturnType<WorkerService["attach"]>> | undefined;
194
- let reply: Parameters<typeof workerReply>[1];
195
- // Broken SSH output is handled by the write callback or the bridge. It is
196
- // never a death signal to the detached native processes.
197
- const outputLost = () => input.pause();
198
- input.on("error", outputLost);
199
- output.on("error", outputLost);
200
212
  try {
201
- try {
202
- const request = parseWorkerRequest(await workerHeader(input));
203
- const bound = parseWorkerPolicy(policy);
204
- if (request.op !== "describe" && request.workerId !== bound.workerId)
205
- throw new WorkerRefusal("Worker request names a different enrollment");
206
- validateStorage(bound);
207
- if (request.op === "describe") reply = { ok: true, value: await describeWorker(bound, request.workspace) };
208
- else {
209
- service = new WorkerService(bound);
210
- switch (request.op) {
211
- case "probe": reply = { ok: true, value: await service.probe(request.ref, request.reconcile) }; break;
212
- case "open": reply = { ok: true, value: await service.open(request.ref, request.launch) }; break;
213
- case "attach":
214
- attach = await service.attach(request.ref);
215
- reply = { ok: true, value: attach.value };
216
- break;
217
- }
213
+ const request = parseWorkerRequest(header);
214
+ const bound = parseWorkerPolicy(policy);
215
+ if (request.op !== "describe" && request.workerId !== bound.workerId)
216
+ throw new WorkerRefusal("Worker request names a different enrollment");
217
+ validateStorage(bound);
218
+ if (request.op === "describe")
219
+ return { kind: "reply", reply: { ok: true, value: await describeWorker(bound, request.workspace) } };
220
+ service = new WorkerService(bound);
221
+ switch (request.op) {
222
+ case "probe": return { kind: "reply", reply: { ok: true, value: await service.probe(request.ref, request.reconcile) } };
223
+ case "open": return { kind: "reply", reply: { ok: true, value: await service.open(request.ref, request.launch) } };
224
+ case "attach": return { kind: "attach", ...await service.attach(request.ref) };
225
+ default: {
226
+ request satisfies never;
227
+ throw new WorkerRefusal("Invalid worker request");
218
228
  }
219
- } catch (error) {
220
- reply = { ok: false, error: error instanceof WorkerRefusal ? error.message : "Worker could not verify the operation" };
221
- } finally { service?.close(); }
222
- await workerReply(output, reply);
223
- if (attach) await bridgeWorker(input, output, attach.socket);
224
- } finally {
225
- attach?.socket.destroy();
226
- input.pause();
227
- input.off("error", outputLost);
228
- output.off("error", outputLost);
229
- }
229
+ }
230
+ } catch (error) {
231
+ return { kind: "reply", reply: { ok: false,
232
+ error: error instanceof WorkerRefusal ? error.message : "Worker could not verify the operation" } };
233
+ } finally { service?.close(); }
230
234
  }
package/scripts/ci.ts DELETED
@@ -1,44 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { mkdtempDisposable } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { delimiter, dirname, join, resolve } from "node:path";
5
- import { activeManagedUlw } from "../src/managed-ulw";
6
- import { nativeTestCommand } from "../test/fixtures/native-command";
7
-
8
- const root = resolve(import.meta.dir, "..");
9
- const explicitCache = process.env.OMP_TEST_NATIVES_DIR;
10
- await using temporaryCache = explicitCache ? undefined : await mkdtempDisposable(join(tmpdir(), "omp-sa-natives-"));
11
- const nativesDir = explicitCache || temporaryCache!.path;
12
- const command = await nativeTestCommand({ ...process.env, OMP_TEST_NATIVES_DIR: nativesDir });
13
- const ulw = activeManagedUlw();
14
- const manifest = await Bun.file(join(ulw, "package.json")).json() as { omp: { extensions: string[] } };
15
- if (manifest.omp.extensions.length !== 1) throw new Error("Native composition tests require one managed ULW entrypoint");
16
- const env = {
17
- ...process.env,
18
- CI: "true",
19
- PATH: [dirname(process.execPath), process.env.PATH].filter(Boolean).join(delimiter),
20
- OMP_SUPERAGENT_NATIVE_TEST: "1",
21
- OMP_SUPERAGENT_SETUP_PTY_TEST: "1",
22
- OMP_SUPERAGENT_GATEWAY_DIFFERENTIAL: "1",
23
- OMP_TEST_COMMAND: JSON.stringify(command),
24
- OMP_TEST_NATIVES_DIR: nativesDir,
25
- OMP_TEST_ULW_EXTENSION: resolve(ulw, manifest.omp.extensions[0]!),
26
- };
27
- console.log(`CI: Bun ${Bun.version}; ULW ${ulw}`);
28
- const bun = [process.execPath, "--no-env-file"];
29
- const commands = [
30
- [...bun, "run", "check"],
31
- ["cargo", "test", "--locked", "--manifest-path", "host-owner/Cargo.toml"],
32
- // Cargo's default test targets build the Gateway examples used by the Bun fixtures.
33
- ["cargo", "test", "--locked", "--manifest-path", "gateway/Cargo.toml"],
34
- [...bun, "test", "--parallel=2", "test"],
35
- ];
36
- for (const command of commands) {
37
- const child = Bun.spawn(command, {
38
- cwd: root,
39
- env,
40
- stdin: "ignore", stdout: "inherit", stderr: "inherit",
41
- });
42
- const code = await child.exited;
43
- if (code !== 0) { process.exitCode = code; break; }
44
- }
@@ -1,112 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { constants } from "node:fs";
3
- import { access, mkdir, mkdtempDisposable } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join, resolve } from "node:path";
6
-
7
- const root = resolve(import.meta.dir, "..");
8
- const [mode, ...extra] = process.argv.slice(2);
9
- if (extra.length || mode !== undefined && mode !== "--publish" && mode !== "--replace")
10
- throw new Error("Usage: bun run release [--publish|--replace]");
11
-
12
- async function run(command: string[]): Promise<string> {
13
- const child = Bun.spawn(command, { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "inherit" });
14
- const text = await new Response(child.stdout).text();
15
- if (await child.exited !== 0) throw new Error(`Command failed: ${command.join(" ")}`);
16
- return text.trim();
17
- }
18
-
19
- if (await run(["git", "status", "--porcelain"]))
20
- throw new Error("Release packaging requires a clean checkout; commit the intended release changes first");
21
- const { name, version } = JSON.parse(await run(["git", "show", "HEAD:package.json"])) as { name: string; version: string };
22
- const tag = `v${version}`;
23
- const revision = await run(["git", "rev-parse", "HEAD"]);
24
- if (mode !== undefined) {
25
- if (process.env.GITHUB_REF_TYPE !== "tag" || process.env.GITHUB_REF_NAME !== tag)
26
- throw new Error(`Publishing requires the ${tag} tag workflow`);
27
- if (await run(["git", "rev-parse", `${tag}^{commit}`]) !== revision)
28
- throw new Error("Release tag does not identify the checked-out commit");
29
- }
30
- if (mode === "--replace" && process.env.GITHUB_EVENT_NAME !== "workflow_dispatch")
31
- throw new Error("Replacing a release requires the manual tag workflow");
32
- const notes = join(root, "docs/releases", `${version}.md`);
33
- if (!await Bun.file(notes).exists()) throw new Error(`Missing release notes: ${notes}`);
34
- const directory = join(root, "dist");
35
- await mkdir(directory, { recursive: true });
36
- const sourceFilename = `${name}-${version}.tar.gz`;
37
- const packageFilename = `${name}-${version}.tgz`;
38
- const nativePlatforms = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"] as const;
39
- const nativePackages = [
40
- { directory: "host-owner", binary: "omp-host-owner" },
41
- { directory: "gateway", binary: "omp-gateway" },
42
- ] as const;
43
-
44
- async function verifyNativePayload(directory: string): Promise<void> {
45
- for (const pkg of nativePackages) {
46
- const binDir = join(directory, pkg.directory, "bin");
47
- for (const platform of nativePlatforms) {
48
- await access(join(binDir, `${pkg.binary}-${platform}`), constants.X_OK);
49
- const notices = join(binDir, "notices", platform);
50
- await access(join(notices, "Cargo-LICENSES.txt"));
51
- await access(join(notices, "Cargo-SOURCES.txt"));
52
- await access(join(notices, "rust", "COPYRIGHT-library.html"));
53
- await access(join(notices, "rust", "licenses"));
54
- }
55
- }
56
- }
57
-
58
- if (mode === undefined) {
59
- // Each target's CI runner builds both packages with --locked; the archive
60
- // job assembles those same outputs instead of rebuilding any one target.
61
- await verifyNativePayload(root);
62
- const archive = join(directory, sourceFilename);
63
- const sourcePrefix = `${name}-${version}/`;
64
- await run(["git", "archive", "--format=tar.gz", `--prefix=${sourcePrefix}`, `--output=${archive}`, revision]);
65
- const sources = new Set((await run(["tar", "-tzf", archive])).split("\n"));
66
- if (!sources.has(`${sourcePrefix}.cargo/config.toml`)) throw new Error("Source archive lacks .cargo/config.toml");
67
- for (const pkg of nativePackages) {
68
- const prefix = `${sourcePrefix}${pkg.directory}/`;
69
- for (const file of ["Cargo.toml", "Cargo.lock", "src/main.rs"]) {
70
- if (!sources.has(`${prefix}${file}`)) throw new Error(`Source archive lacks ${pkg.directory}/${file}`);
71
- }
72
- if ([...sources].some(file => file.startsWith(`${prefix}target/`) || file.startsWith(`${prefix}bin/`))) {
73
- throw new Error(`The source archive contains generated ${pkg.directory} artifacts`);
74
- }
75
- }
76
- const npmArchive = join(directory, packageFilename);
77
- await run([process.execPath, "pm", "pack", "--ignore-scripts", "--filename", npmArchive]);
78
- const files = (await run(["tar", "-tzf", npmArchive])).split("\n");
79
- for (const pkg of nativePackages) {
80
- const prefix = `package/${pkg.directory}/`;
81
- if (files.some(file => file.startsWith(prefix) && file !== prefix && !file.startsWith(`${prefix}bin/`))) {
82
- throw new Error(`Unexpected ${pkg.directory} build or source data in the npm tarball`);
83
- }
84
- }
85
- // Packlist checks alone cannot detect a packer that strips executable bits.
86
- await using unpacked = await mkdtempDisposable(join(tmpdir(), "omp-sa-pack-"));
87
- await run(["tar", "-xzf", npmArchive, "-C", unpacked.path]);
88
- await verifyNativePayload(join(unpacked.path, "package"));
89
- }
90
-
91
- const assets: string[] = [];
92
- for (const filename of [sourceFilename, packageFilename]) {
93
- const path = join(directory, filename);
94
- const digest = new Bun.CryptoHasher("sha256").update(await Bun.file(path).arrayBuffer()).digest("hex");
95
- const checksum = `${path}.sha256`;
96
- const contents = `${digest} ${filename}\n`;
97
- if (mode === undefined) await Bun.write(checksum, contents);
98
- else if (await Bun.file(checksum).text() !== contents) throw new Error(`Packaged asset checksum mismatch: ${filename}`);
99
- assets.push(path, checksum);
100
- }
101
- console.log(`${mode === undefined ? "Packaged" : "Verified staged release for"} ${revision}\n${assets.join("\n")}`);
102
- if (mode === "--publish") {
103
- console.log(await run(["gh", "release", "create", tag, ...assets,
104
- "--verify-tag", "--title", `${name} ${version}`, "--notes-file", notes]));
105
- } else if (mode === "--replace") {
106
- // Check the live tag, not just the checkout used by earlier CI jobs.
107
- const remote = await run(["git", "ls-remote", "origin", `refs/tags/${tag}`, `refs/tags/${tag}^{}`]);
108
- if (remote.split("\n").at(-1)?.split("\t")[0] !== revision)
109
- throw new Error("Remote release tag no longer identifies the verified commit");
110
- console.log(await run(["gh", "release", "upload", tag, ...assets, "--clobber"]));
111
- console.log(await run(["gh", "release", "edit", tag, "--verify-tag", "--notes-file", notes]));
112
- }