omp-superagent 0.1.9 → 0.1.11

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 (151) hide show
  1. package/DESIGN.md +68 -21
  2. package/README.ko.md +30 -372
  3. package/README.md +31 -419
  4. package/THIRD_PARTY_NOTICES.md +35 -436
  5. package/assets/architecture-dark.svg +7 -12
  6. package/assets/architecture.ko-dark.svg +7 -12
  7. package/assets/architecture.ko.svg +7 -12
  8. package/assets/architecture.mmd +5 -13
  9. package/assets/architecture.svg +7 -12
  10. package/config.example.json +8 -0
  11. package/docs/OPERATIONS.en.md +2277 -0
  12. package/docs/OPERATIONS.md +198 -45
  13. package/docs/design/execution.md +163 -54
  14. package/docs/design/messaging.md +125 -34
  15. package/docs/kakao-bridge-protocol.md +193 -0
  16. package/docs/releases/0.1.10.md +17 -0
  17. package/docs/releases/0.1.11.md +18 -0
  18. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  21. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  25. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  26. package/package.json +10 -11
  27. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  28. package/skills/head/SKILL.md +36 -5
  29. package/skills/head/references/routing.md +1 -1
  30. package/skills/head/references/supervision.md +32 -26
  31. package/skills/lane/SKILL.md +39 -21
  32. package/skills/lane/references/workflow.md +23 -16
  33. package/src/cli.ts +35 -33
  34. package/src/{config.ts → config/config.ts} +51 -6
  35. package/src/config/wake-config.ts +36 -0
  36. package/src/contracts.ts +91 -13
  37. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  38. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  39. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  40. package/src/extension.ts +64 -28
  41. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  42. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  43. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  44. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  45. package/src/gateway-config.ts +1 -1
  46. package/src/gateway-restart-env.ts +3 -3
  47. package/src/{group-access.ts → group/group-access.ts} +8 -3
  48. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  49. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  50. package/src/host-extension.ts +213 -43
  51. package/src/host-sdk-helper.ts +62 -65
  52. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  53. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  54. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  55. package/src/{lane-report.ts → lane/lane-report.ts} +22 -0
  56. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  57. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  58. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  59. package/src/lane-extension.ts +69 -13
  60. package/src/managed-memory-helper.ts +2 -2
  61. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  62. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  63. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  64. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  65. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  66. package/src/messaging/messenger-commands.ts +55 -0
  67. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  68. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  69. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  70. package/src/omp/head-resume.ts +123 -0
  71. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  72. package/src/{host-protocol.ts → omp/host-protocol.ts} +11 -2
  73. package/src/omp/host-reply-voice.ts +181 -0
  74. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  75. package/src/{host.ts → omp/host.ts} +26 -17
  76. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  77. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  78. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  79. package/src/omp/native-journal.ts +124 -0
  80. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  81. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  82. package/src/omp/native-sessions.ts +124 -0
  83. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  84. package/src/omp/soul.ts +214 -0
  85. package/src/omp/stock-head-launch.ts +31 -0
  86. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  87. package/src/{operator.ts → operator/operator.ts} +2 -2
  88. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  89. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  90. package/src/{setup.ts → operator/setup.ts} +7 -6
  91. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  92. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  93. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  94. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  95. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  96. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  97. package/src/{message-order.ts → routing/message-order.ts} +3 -2
  98. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  99. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  100. package/src/{runtime.ts → runtime/controller.ts} +1278 -1267
  101. package/src/runtime/deferred-routing.ts +106 -0
  102. package/src/runtime/dm-timeline.ts +194 -0
  103. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  104. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  105. package/src/runtime/model-journal.ts +119 -0
  106. package/src/runtime/native-frames.ts +131 -0
  107. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  108. package/src/runtime/preset-sync.ts +232 -0
  109. package/src/runtime/preset-watch-paths.ts +137 -0
  110. package/src/runtime/result-attachments.ts +146 -0
  111. package/src/storage/deferred-routing.ts +149 -0
  112. package/src/{store.ts → storage/store.ts} +450 -49
  113. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  114. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  115. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  116. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  117. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  118. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  119. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  120. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  121. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  122. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  123. package/src/worker-serve-prepare.ts +4 -4
  124. package/src/board-extension.ts +0 -217
  125. package/src/board.ts +0 -467
  126. package/src/gateway-host-helper.ts +0 -13
  127. package/src/messenger-commands.ts +0 -15
  128. package/src/native-sessions.ts +0 -34
  129. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  130. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  131. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  132. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  133. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  134. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  135. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  136. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  137. /package/src/{repository.ts → operator/repository.ts} +0 -0
  138. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  139. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  140. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  141. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  142. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  143. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  144. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  145. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  146. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  147. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  148. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  149. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  150. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  151. /package/upstream/{ulw.json → super.json} +0 -0
@@ -1,8 +1,8 @@
1
1
  import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
- import { physicalRoute, type Platform, type Route } from "./contracts";
4
- import { resolveOmpCommand } from "./installed-omp";
5
- import { groupRoom, parseGroupRooms, type GroupRoom } from "./group-policy";
3
+ import { physicalRoute, type Platform, type Route } from "../contracts";
4
+ import { resolveOmpCommand } from "../omp/installed-omp";
5
+ import { groupRoom, parseGroupRooms, type GroupRoom } from "../group/group-policy";
6
6
 
7
7
  export interface DiscordConfig {
8
8
  tokenEnv: string;
@@ -42,6 +42,18 @@ export interface TelegramConfig {
42
42
  allowedChatIds: string[];
43
43
  }
44
44
 
45
+ /**
46
+ * KakaoTalk through an operator-run loopback bridge that owns the logged-in Kakao
47
+ * session (docs/kakao-bridge-protocol.md). Owner one-to-one chat only.
48
+ */
49
+ export interface KakaoConfig {
50
+ bridgeUrl: string;
51
+ tokenEnv: string;
52
+ botUserId: string;
53
+ ownerId: string;
54
+ chatId: string;
55
+ }
56
+
45
57
  export interface SlackConfig {
46
58
  botTokenEnv: string;
47
59
  appTokenEnv: string;
@@ -50,6 +62,8 @@ export interface SlackConfig {
50
62
  allowedChannelIds: string[];
51
63
  }
52
64
 
65
+ export const DEFAULT_HEAD_IDLE_MS = 30 * 60 * 1000;
66
+
53
67
  export interface Config {
54
68
  path: string;
55
69
  stateDir: string;
@@ -58,10 +72,12 @@ export interface Config {
58
72
  maxHosts: number;
59
73
  maxSubagents: number;
60
74
  idleMs: number;
75
+ readonly headIdleMs?: number;
61
76
  model?: string;
62
77
  discord?: DiscordConfig;
63
78
  telegram?: TelegramConfig;
64
79
  slack?: SlackConfig;
80
+ kakao?: KakaoConfig;
65
81
  groupRooms?: readonly GroupRoom[];
66
82
  }
67
83
 
@@ -96,7 +112,7 @@ function tokenEnv(value: unknown, name: string): string {
96
112
  }
97
113
 
98
114
  export function configuredPlatforms(config: Config): Platform[] {
99
- return (["discord", "telegram", "slack"] as const).filter(platform => config[platform] !== undefined);
115
+ return (["discord", "telegram", "slack", "kakao"] as const).filter(platform => config[platform] !== undefined);
100
116
  }
101
117
 
102
118
  export function voiceApiKeyEnv(config: Config): string | undefined {
@@ -117,6 +133,7 @@ export function credentialEnvNames(config: Config): string[] {
117
133
  ...(voiceKey === undefined ? [] : [voiceKey]),
118
134
  ...(config.telegram ? [config.telegram.tokenEnv] : []),
119
135
  ...(config.slack ? [config.slack.botTokenEnv, config.slack.appTokenEnv] : []),
136
+ ...(config.kakao ? [config.kakao.tokenEnv] : []),
120
137
  ])];
121
138
  }
122
139
 
@@ -164,6 +181,11 @@ export function isConfiguredRoute(config: Config, route: Route): boolean {
164
181
  (route.guildId === null ? /^D[A-Z0-9]+$/.test(route.channelId) :
165
182
  route.guildId === policy.teamId && policy.allowedChannelIds.includes(route.channelId));
166
183
  }
184
+ case "kakao": {
185
+ const policy = config.kakao;
186
+ return !!policy && route.authorityId === policy.ownerId && route.accountId === policy.botUserId
187
+ && route.guildId === null && route.threadId === null && route.channelId === policy.chatId;
188
+ }
167
189
  }
168
190
  }
169
191
 
@@ -200,7 +222,8 @@ export function parseConfig(value: unknown, path: string): Config {
200
222
  const discord = raw.discord === undefined ? undefined : record(raw.discord, "discord");
201
223
  const telegram = raw.telegram === undefined ? undefined : record(raw.telegram, "telegram");
202
224
  const slack = raw.slack === undefined ? undefined : record(raw.slack, "slack");
203
- if (!discord && !telegram && !slack) throw new Error("Configure at least one messenger: discord, telegram, or slack");
225
+ const kakao = raw.kakao === undefined ? undefined : record(raw.kakao, "kakao");
226
+ if (!discord && !telegram && !slack && !kakao) throw new Error("Configure at least one messenger: discord, telegram, slack, or kakao");
204
227
  const base = dirname(absolute);
205
228
  const pathValue = (v: unknown, key: string) => resolve(base, text(v, key));
206
229
  if (!Array.isArray(raw.command) || !raw.command.length ||
@@ -241,7 +264,7 @@ export function parseConfig(value: unknown, path: string): Config {
241
264
  case "api":
242
265
  case undefined: {
243
266
  const apiKeyEnv = tokenEnv(voice.apiKeyEnv, "discord.voice.apiKeyEnv");
244
- if ([discord?.tokenEnv, telegram?.tokenEnv, slack?.appTokenEnv, slack?.botTokenEnv].includes(apiKeyEnv))
267
+ if ([discord?.tokenEnv, telegram?.tokenEnv, slack?.appTokenEnv, slack?.botTokenEnv, kakao?.tokenEnv].includes(apiKeyEnv))
245
268
  throw new Error("discord.voice.apiKeyEnv must not name a messenger token");
246
269
  voiceConfig = {
247
270
  ...session, ...(auth === undefined ? {} : { auth }), apiKeyEnv,
@@ -262,6 +285,7 @@ export function parseConfig(value: unknown, path: string): Config {
262
285
  maxHosts,
263
286
  maxSubagents,
264
287
  idleMs: integer(raw.idleMs, "idleMs", 0),
288
+ headIdleMs: raw.headIdleMs === undefined ? DEFAULT_HEAD_IDLE_MS : integer(raw.headIdleMs, "headIdleMs", 0),
265
289
  ...(raw.model === undefined ? {} : { model: text(raw.model, "model") }),
266
290
  ...(discord ? { discord: {
267
291
  tokenEnv: tokenEnv(discord.tokenEnv, "discord.tokenEnv"),
@@ -284,10 +308,31 @@ export function parseConfig(value: unknown, path: string): Config {
284
308
  teamId: id(slack.teamId, "slack.teamId", /^T[A-Z0-9]+$/),
285
309
  allowedChannelIds: ids(slack.allowedChannelIds, "slack.allowedChannelIds", /^[CG][A-Z0-9]+$/),
286
310
  } } : {}),
311
+ ...(kakao ? { kakao: parseKakao(kakao) } : {}),
287
312
  };
288
313
  return raw.groupRooms === undefined ? config : { ...config, groupRooms: parseGroupRooms(raw.groupRooms, config, base) };
289
314
  }
290
315
 
316
+ function parseKakao(kakao: Record<string, unknown>): KakaoConfig {
317
+ const kakaoId = /^[1-9]\d{0,19}$/;
318
+ const bridgeUrl = text(kakao.bridgeUrl, "kakao.bridgeUrl");
319
+ let url: URL;
320
+ try { url = new URL(bridgeUrl); } catch { throw new Error("kakao.bridgeUrl must be a URL"); }
321
+ // Literal loopback only: a host name could later resolve elsewhere.
322
+ if (url.protocol !== "http:" || !["127.0.0.1", "[::1]"].includes(url.hostname)
323
+ || url.username || url.password || url.search || url.hash)
324
+ throw new Error("kakao.bridgeUrl must be a plain http://127.0.0.1:PORT or http://[::1]:PORT URL");
325
+ const result: KakaoConfig = {
326
+ bridgeUrl,
327
+ tokenEnv: tokenEnv(kakao.tokenEnv, "kakao.tokenEnv"),
328
+ botUserId: id(kakao.botUserId, "kakao.botUserId", kakaoId),
329
+ ownerId: id(kakao.ownerId, "kakao.ownerId", kakaoId),
330
+ chatId: id(kakao.chatId, "kakao.chatId", kakaoId),
331
+ };
332
+ if (result.botUserId === result.ownerId) throw new Error("kakao.botUserId and kakao.ownerId must differ");
333
+ return result;
334
+ }
335
+
291
336
  /** No caller can turn a shared/symlink directory into a trusted socket directory. */
292
337
  export function privateDirectory(path: string): void {
293
338
  mkdirSync(path, { recursive: true, mode: 0o700 });
@@ -0,0 +1,36 @@
1
+ import { on } from "node:events";
2
+ import { watch } from "node:fs";
3
+ import { basename, dirname } from "node:path";
4
+ import { parseConfig } from "./config";
5
+
6
+ /** No controller, store or messenger is opened on unapproved bytes. The
7
+ * directory watch survives atomic replacement and is closed on Host stop. */
8
+ export async function loadWakeConfig(path: string, expectedHash: string, signal: AbortSignal) {
9
+ signal.throwIfAborted();
10
+ const watcher = watch(dirname(path), { persistent: false });
11
+ const changes = on(watcher, "change", { signal });
12
+ try {
13
+ for (;;) {
14
+ signal.throwIfAborted();
15
+ let bytes: ArrayBuffer | undefined;
16
+ try { bytes = await Bun.file(path).arrayBuffer(); }
17
+ catch (error) {
18
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
19
+ }
20
+ if (bytes && Bun.CryptoHasher.hash("sha256", bytes, "hex") === expectedHash) {
21
+ return parseConfig(await new Blob([bytes]).json(), path);
22
+ }
23
+ // The config may live beside the live Gateway database. Its journal
24
+ // writes are not a reason to reread the configuration.
25
+ let filename: unknown;
26
+ do {
27
+ const event = await changes.next();
28
+ if (event.done) throw new Error("Configuration watch closed before HEAD wake");
29
+ [, filename] = event.value;
30
+ } while (filename != null && filename !== basename(path));
31
+ }
32
+ } finally {
33
+ watcher.close();
34
+ await changes.return?.();
35
+ }
36
+ }
package/src/contracts.ts CHANGED
@@ -1,14 +1,15 @@
1
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
- import type { CronUpdate } from "./cron-jobs";
4
- import type { ReviewRound } from "./pr-intake-review";
5
- import type { GroupReply, GroupRequest } from "./group-policy";
6
- import type { StagedResultAttachment } from "./result-attachment";
7
- import type { RemotePlacement } from "./worker-wire";
8
- import type { OmpResetAccount } from "./omp-usage";
2
+ import type { LaneEvidence, LaneReport, LaneWaitTarget } from "./lane/lane-report";
3
+ import type { CronUpdate } from "./cron/cron-jobs";
4
+ import type { ReviewRound } from "./pr/pr-intake-review";
5
+ import type { GroupReply, GroupRequest } from "./group/group-policy";
6
+ import type { StagedResultAttachment } from "./messaging/result-attachment";
7
+ import type { RemotePlacement } from "./worker/worker-wire";
8
+ import type { OmpResetAccount } from "./omp/omp-usage";
9
9
 
10
10
  /** Coordination records only. OMP owns transcripts and execution state. */
11
- export type Platform = "discord" | "telegram" | "slack";
11
+ export type Platform = "discord" | "telegram" | "slack" | "kakao";
12
+ export type HistoryPlatform = Extract<Platform, "discord" | "slack">;
12
13
 
13
14
  export interface Route {
14
15
  platform: Platform;
@@ -40,8 +41,24 @@ export function physicalRouteKey(route: Route): string {
40
41
  return routeKey(physicalRoute(route));
41
42
  }
42
43
 
43
- /** Store meta key: owner inputs acknowledged to Gateway whose topic routing is still pending, in delivery order. */
44
- export const DEFERRED_ROUTING_META = "intake:deferred-routing";
44
+ /** Deferred intake shares order across threads and logical topics of a channel or DM. */
45
+ export function routingConversation(route: Route): string {
46
+ return routeKey({ ...physicalRoute(route), threadId: null });
47
+ }
48
+
49
+ /** Syntax only: these candidates still require current receipt and route authority. */
50
+ export function deferredRecoveryCandidate(text: string) {
51
+ const match = /^\/(restart|stop)(?:\s+(\S+))?$/u.exec(text.trim());
52
+ if (!match) return null;
53
+ const [, name, argument] = match;
54
+ if (name === "restart") return argument ? null : { kind: "restart" } as const;
55
+ if (!argument) return { kind: "bare-stop" } as const;
56
+ if (argument === "head") return { kind: "head-stop" } as const;
57
+ return { kind: "lane-stop", laneId: argument } as const;
58
+ }
59
+
60
+ /** Internal HEAD review ID prefix; authority lives in the current store binding. */
61
+ export const SCOPE_REVIEW_PREFIX = "scope-review:";
45
62
 
46
63
  /** Exact successor generation reserved when a submitted card is authorized to restore its original lane session. */
47
64
  export const laneModelPickerRestoreKey = (sourceId: string) => `lane-model:picker-restore:${sourceId}`;
@@ -131,9 +148,15 @@ export interface Inbound {
131
148
  readonly discordOriginalText?: string;
132
149
  /** Adapter-verified routing-only view; an empty string excludes the entire message. */
133
150
  readonly routingText?: string;
151
+ /** Telegram's authenticated formatting verdict; absent on pre-upgrade receipts. */
152
+ readonly telegramProtectedCommand?: boolean;
153
+ /** Original Telegram text or caption when an addressed bot suffix was removed. */
154
+ readonly telegramOriginalText?: string;
134
155
  receivedAt: number;
135
156
  attachments: Attachment[];
136
157
  reply?: ReplyContext;
158
+ /** The adapter observed a reply or shared message without an in-route reply snapshot. */
159
+ readonly unresolvedReply?: true;
137
160
  discordContext?: DiscordContext;
138
161
  }
139
162
 
@@ -255,6 +278,7 @@ export type HeadPicker = {
255
278
  };
256
279
  } }
257
280
  | { readonly kind: "effort"; readonly forModel: LaneModel }
281
+ | { readonly kind: "fast"; readonly forModel: LaneModel }
258
282
  | { readonly kind: "usage-reset"; readonly accounts: readonly Pick<OmpResetAccount, "target" | "label" | "identity" | "offer">[] }
259
283
  );
260
284
 
@@ -296,8 +320,22 @@ export interface OutputRecord {
296
320
  export type SettlementOutput = Pick<OutputRecord, "id" | "text" | "picker"> & {
297
321
  /** Controller-only lane failure routing, never derived from output text. */
298
322
  readonly laneFailure?: "quota" | "recover";
323
+ /** Controller-verified clean native settlement of a solo scope-review admission. */
324
+ readonly scopeReviewEligible?: boolean;
299
325
  };
300
326
 
327
+ export interface ScopeReview {
328
+ readonly lane: Lane;
329
+ readonly original: InputRecord;
330
+ readonly handoff: InputRecord;
331
+ }
332
+
333
+ /** Controller-proven successful native report, with its exact own approval if one was required. */
334
+ export interface ScopeReviewNativeProof {
335
+ readonly toolCallId: string;
336
+ readonly approvalId?: string;
337
+ }
338
+
301
339
  export interface LaneRecoveryScope {
302
340
  readonly lane: Lane;
303
341
  readonly failed: InputRecord;
@@ -360,7 +398,25 @@ export interface HeadRecoveryEffect {
360
398
  state: string;
361
399
  }
362
400
 
401
+ /** Ordered HEAD receipts for owner inputs still waiting for topic routing. */
402
+ export interface DeferredRoutingPort {
403
+ enqueue(input: Inbound): void;
404
+ /** Verify an existing deferred receipt and refresh eligible attachment URLs without changing order. */
405
+ reconcile(input: Inbound): boolean;
406
+ input(id: string): Inbound | null;
407
+ has(id: string): boolean;
408
+ head(conversation: string): string | null;
409
+ conversations(): readonly string[];
410
+ priority(conversation: string, includeBare: boolean): Iterable<Inbound>;
411
+ earlierLaneStops(lane: Pick<Lane, "id" | "route">, beforeId: string): Iterable<Inbound>;
412
+ hasEarlierMessage(input: Pick<Inbound, "id" | "route">, messageId: string): boolean;
413
+ /** IDs before this queued receipt, or all currently queued IDs for fresh direct admission. */
414
+ idsBefore(id: string): readonly string[];
415
+ remove(id: string): void;
416
+ }
417
+
363
418
  export interface StorePort {
419
+ readonly deferredRouting: DeferredRoutingPort;
364
420
  /** Typed, noninteractive work on the confirmed bot offer; never valid for ordinary owner intake. */
365
421
  receivePrWork(input: Inbound, target: string | null, round: ReviewRound): boolean;
366
422
  receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
@@ -368,6 +424,12 @@ export interface StorePort {
368
424
  ownerSource(id: string): InputRecord | null;
369
425
  /** Revalidate a report's exact failed admission, actionable owner and operator selection. */
370
426
  laneRecoveryScope(reportId: string): LaneRecoveryScope | null;
427
+ /** Stage a verified direct native scope-review signal; does not enqueue a HEAD input. */
428
+ recordScopeReview(inputId: string, generation: number, sessionId: string, sourceId: string, proof: ScopeReviewNativeProof): boolean;
429
+ /** Verify the current owner request, solo admission, and lane binding for review or granted dispatch. */
430
+ scopeReview(reviewId: string): ScopeReview | null;
431
+ /** Record one HEAD intent; only eligible native settlement can admit corrective work. */
432
+ requestScopeCorrection(reviewId: string): string;
371
433
  /** Original parent route for a redirected report or a handoff derived from that report. */
372
434
  reportApprovalSource(id: string): InputRecord | null;
373
435
  /** Manager handoff's verified reply route, pinned for a parent-origin thread follow-up or a joined bound reply. */
@@ -386,11 +448,15 @@ export interface StorePort {
386
448
  latestLaneRun(target: string): InputRecord | null;
387
449
  /** A successful lane run still has an unresolved final report or delivery. */
388
450
  hasPendingLaneResult(target: string): boolean;
451
+ /** A current scope review or granted correction still needs this lane generation. */
452
+ hasPendingScopeReview(target: string): boolean;
389
453
  hasPendingLanePlacement(target: string): boolean;
390
454
  /** An uncertain HEAD input with a nonempty original native-owner record. */
391
455
  hasHeadRecoveryInput(): boolean;
392
456
  /** No automatic head replacement while an original HEAD delivery is unresolved. */
393
457
  hasUnresolvedHeadDelivery(): boolean;
458
+ /** Any queued or held coordination work makes hibernating the controller unsafe. */
459
+ hasHeadSleepWork(): boolean;
394
460
  kickoffHold(target: string): KickoffHold | null;
395
461
  /** The first authorized revision on the physical route, even after settlement. */
396
462
  firstAdmittedMessage(route: Route, messageId: string): InputRecord | null;
@@ -423,6 +489,11 @@ export interface StorePort {
423
489
  prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
424
490
  commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
425
491
  queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
492
+ /** Atomically replace this native Host's outstanding job bindings and enqueue observed results. */
493
+ saveHeadJobs(bindingKey: string, owners: readonly (readonly [string, string, string])[],
494
+ outputs?: readonly Pick<OutputRecord, "id" | "sourceId" | "route" | "text">[]): void;
495
+ recordRestartCheckpointFailure(expectedFence: string, stopBoundary: string | null, failedFence: string,
496
+ output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
426
497
  recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
427
498
  output(id: string): OutputRecord | null;
428
499
  outputs(physicalRoute?: string): OutputRecord[];
@@ -435,6 +506,7 @@ export interface StorePort {
435
506
  updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
436
507
  "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
437
508
  >>): boolean;
509
+ retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath">): boolean;
438
510
  nextGeneration(id: string, pickerRestoreSourceId?: string): Lane;
439
511
  adoptLaneModel(id: string, generation: number, model: LaneModel, reason: string): boolean;
440
512
  changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: string,
@@ -449,6 +521,7 @@ export interface StorePort {
449
521
  recoverDeliveries(): void;
450
522
  getMeta(key: string): string | null;
451
523
  setMeta(key: string, value: string): void;
524
+ completeHistoryBoundary(key: string, cursor: string, sequence: string | null): void;
452
525
  close(): void;
453
526
  }
454
527
 
@@ -516,6 +589,8 @@ export interface InboundAttachmentReceipt {
516
589
  }
517
590
 
518
591
  export interface Messenger {
592
+ /** Startup history, when needed, is ordered by the authenticated transport. */
593
+ readonly managesStartupHistory?: true;
519
594
  start(handlers: {
520
595
  /** Authenticate first; do not consume inbound events until native approvals are reconciled. */
521
596
  ready?: Promise<void>;
@@ -524,7 +599,10 @@ export interface Messenger {
524
599
  answer(approvalId: string, response: DialogResponse, route: Route): Promise<void>;
525
600
  /** Reconcile a previously attempted answer before retrying its native effect. */
526
601
  reconcileAnswer?(approvalId: string, route: Route): Promise<"retry" | "accepted" | "rejected" | "unresolved">;
527
- reconnect?(): Promise<void>;
602
+ /** Pin existing cursors before a fresh Gateway opens ordered intake. */
603
+ reserveStartupHistory?(): void;
604
+ /** A sequence identifies an ordered Gateway gap; false reconciles approvals only. */
605
+ reconnect?(history?: number | false, platform?: HistoryPlatform): Promise<void>;
528
606
  /** Owned Gateway lifecycle outcome; never a user instruction or model turn. */
529
607
  restart?(notice: GatewayRestartNotice): Promise<void>;
530
608
  }): Promise<void>;
@@ -545,8 +623,8 @@ export interface Messenger {
545
623
  inspectDiscordContext?(route: Route): Promise<DiscordContext>;
546
624
  discordPurpose?(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]>;
547
625
  messengerPresence?(request: MessengerPresenceRequest): Promise<DiscordPresenceStatus>;
548
- /** null explicitly means no history API; intake recovery belongs to the adapter. */
549
- fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null>;
626
+ /** null means adapter-owned recovery. An ordered read uses the Gateway's saved gap cutoff. */
627
+ fetchAfter(route: Route, messageId: string, historySequence?: number): Promise<Inbound[] | null>;
550
628
  /** Validate the source before fetching; receipt only a complete, private batch. */
551
629
  openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt>;
552
630
  stop(): Promise<void>;
@@ -1,11 +1,12 @@
1
1
  // allow: SIZE_OK — prompt and PR intake jobs share one atomic schedule/control ledger.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { authorizeRoute, type Config } from "./config";
4
- import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "./contracts";
3
+ import { authorizeRoute, type Config } from "../config/config";
4
+ import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "../contracts";
5
5
  import { describePrIntake, normalizeIntakeRepository } from "./cron-pr-intake";
6
6
  import { describeCronSchedule, nextCronTime, parseCronSchedule, type CronSchedule } from "./cron-schedule";
7
- import { compareMessageIds } from "./message-order";
8
- import { parsePrModeControl, prModeArgument, prModeEffects, type PrIntakeMode } from "./pr-intake-mode";
7
+ import { compareMessageIds } from "../routing/message-order";
8
+ import { matchesWrittenCommand } from "../messaging/messenger-commands";
9
+ import { parsePrModeControl, prModeArgument, prModeEffects, type PrIntakeMode } from "../pr/pr-intake-mode";
9
10
 
10
11
  const jobsKey = "cron:jobs";
11
12
  export const CRON_RUN_PREFIX = "cron-run:";
@@ -121,14 +122,14 @@ function prModeReceipt(job: CronPrJob, mode: PrIntakeMode): string {
121
122
  }
122
123
 
123
124
  function prAddRequest(tail: string) {
124
- const pair = /^"([^"\r\n]+)"[ \t]+([^ \t\r\n]+)$/u.exec(tail);
125
+ const pair = /^"([^"\r\n]+)"[^\S\r\n\u2028\u2029]+(\S+)$/u.exec(tail);
125
126
  if (!pair?.[1] || !pair[2]) return null;
126
127
  const repository = normalizeIntakeRepository(pair[2]);
127
128
  return repository ? { schedule: pair[1].trim(), repository } : null;
128
129
  }
129
130
 
130
131
  function originalPrAdd(text: string) {
131
- const tail = /^\/cron[ \t]+pr-add[ \t]+(.+)$/u.exec(text.trim())?.[1];
132
+ const tail = /^\/cron[^\S\r\n\u2028\u2029]+pr-add[^\S\r\n\u2028\u2029]+(.+)$/u.exec(text.trim())?.[1];
132
133
  return tail ? prAddRequest(tail) : null;
133
134
  }
134
135
 
@@ -216,10 +217,8 @@ export class CronJobs {
216
217
  const stored = this.store.input(input.id);
217
218
  // A voice confirmation can have projected draft text in `text`. It is
218
219
  // not a physical owner instruction to open a lane or publish to GitHub.
219
- const written = stored?.discordOriginalText?.trim().replace(/^<@!?(\d+)>\s*/, (mention, id) =>
220
- id === route.accountId ? "" : mention).trim();
221
220
  return stored !== null && (stored.state === "pending" || stored.state === "done")
222
- && (written === undefined || written === stored.text.trim())
221
+ && matchesWrittenCommand(stored)
223
222
  && routeKey(stored.route) === routeKey(route) && stored.messageId === input.messageId
224
223
  && stored.interactionId === input.interactionId && !stored.pickerSelection
225
224
  && (stored.messageId === null ? stored.interactionId !== undefined
@@ -606,14 +605,23 @@ export class CronJobs {
606
605
  return id.startsWith(CRON_RUN_PREFIX) && this.store.getMeta(`cron-shell:${id}`) !== null;
607
606
  }
608
607
 
608
+ private scheduled(job: CronJob, boundary: string | null): job is CronJob & { nextAt: number } {
609
+ return job.nextAt !== null && !job.paused && job.stopBoundary === boundary
610
+ && (job.kind === "pr-intake" ? !job.removed : job.shell !== true);
611
+ }
612
+
613
+ hasScheduledWork(): boolean {
614
+ const boundary = this.store.getMeta("head:stop-boundary");
615
+ return this.state().jobs.some(job => this.scheduled(job, boundary) && this.source(job) !== null);
616
+ }
617
+
609
618
  poll(now: number): void {
610
619
  if (this.store.getMeta("head:restart-fence")) return;
611
620
  let state = this.state();
612
621
  const boundary = this.store.getMeta("head:stop-boundary");
613
- for (const job of state.jobs.filter(job => job.nextAt !== null && job.nextAt <= now)
614
- .sort((left, right) => (left.nextAt ?? 0) - (right.nextAt ?? 0))) {
615
- if (job.nextAt === null || job.paused || job.stopBoundary !== boundary || job.kind === "pr-intake" && job.removed) continue;
616
- if (job.kind !== "pr-intake" && job.shell === true) continue;
622
+ const scheduled = state.jobs.filter((job): job is CronJob & { nextAt: number } =>
623
+ this.scheduled(job, boundary) && job.nextAt <= now);
624
+ for (const job of scheduled.sort((left, right) => left.nextAt - right.nextAt)) {
617
625
  const source = this.source(job);
618
626
  if (!source) continue;
619
627
  const last = job.lastRunId ? this.store.input(job.lastRunId) : null;
@@ -1,10 +1,10 @@
1
1
  import { Type, type Static } from "@sinclair/typebox/type";
2
2
  import { Value } from "@sinclair/typebox/value";
3
- import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "./contracts";
3
+ import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "../contracts";
4
4
  import type { CronJobs, CronPrJob } from "./cron-jobs";
5
- import { parsePrRef } from "./pr-github";
6
- import { PrReadError } from "./pr-github-schema";
7
- import { intakeStatusKey } from "./pr-intake-work";
5
+ import { parsePrRef } from "../pr/pr-github";
6
+ import { PrReadError } from "../pr/pr-github-schema";
7
+ import { intakeStatusKey } from "../pr/pr-intake-work";
8
8
 
9
9
  const offerPrefix = "cron-pr:offer:";
10
10
  const githubId = Type.Readonly(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }));
@@ -6,7 +6,7 @@ export type CronSchedule =
6
6
  | { readonly kind: "calendar"; readonly expression: string; readonly timezone: string };
7
7
 
8
8
  export function parseCronSchedule(text: string, now: number): CronSchedule | null {
9
- const relative = /^(in|every) ([1-9]\d*)([smhd])$/.exec(text);
9
+ const relative = /^(in|every)[^\S\r\n\u2028\u2029]+([1-9]\d*)([smhd])$/u.exec(text);
10
10
  if (relative) {
11
11
  const [, mode, amount, unit] = relative;
12
12
  const seconds = Number(amount) * (unit === "s" ? 1 : unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
@@ -14,8 +14,8 @@ export function parseCronSchedule(text: string, now: number): CronSchedule | nul
14
14
  if (!Number.isFinite(new Date(now + milliseconds).getTime()) || mode === "every" && seconds < 60) return null;
15
15
  return mode === "every" ? { kind: "interval", milliseconds } : { kind: "once", at: now + milliseconds };
16
16
  }
17
- if (text.startsWith("at ")) {
18
- const date = text.slice(3);
17
+ const date = /^at[^\S\r\n\u2028\u2029]+(\S+)$/u.exec(text)?.[1];
18
+ if (date) {
19
19
  if (!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?(?:Z|[+-]\d{2}:\d{2})$/.test(date)) return null;
20
20
  const day = date.slice(0, 10);
21
21
  const midnight = new Date(`${day}T00:00:00Z`);