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
package/src/config.ts CHANGED
@@ -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;
@@ -62,6 +74,7 @@ export interface Config {
62
74
  discord?: DiscordConfig;
63
75
  telegram?: TelegramConfig;
64
76
  slack?: SlackConfig;
77
+ kakao?: KakaoConfig;
65
78
  groupRooms?: readonly GroupRoom[];
66
79
  }
67
80
 
@@ -96,7 +109,7 @@ function tokenEnv(value: unknown, name: string): string {
96
109
  }
97
110
 
98
111
  export function configuredPlatforms(config: Config): Platform[] {
99
- return (["discord", "telegram", "slack"] as const).filter(platform => config[platform] !== undefined);
112
+ return (["discord", "telegram", "slack", "kakao"] as const).filter(platform => config[platform] !== undefined);
100
113
  }
101
114
 
102
115
  export function voiceApiKeyEnv(config: Config): string | undefined {
@@ -117,6 +130,7 @@ export function credentialEnvNames(config: Config): string[] {
117
130
  ...(voiceKey === undefined ? [] : [voiceKey]),
118
131
  ...(config.telegram ? [config.telegram.tokenEnv] : []),
119
132
  ...(config.slack ? [config.slack.botTokenEnv, config.slack.appTokenEnv] : []),
133
+ ...(config.kakao ? [config.kakao.tokenEnv] : []),
120
134
  ])];
121
135
  }
122
136
 
@@ -164,6 +178,11 @@ export function isConfiguredRoute(config: Config, route: Route): boolean {
164
178
  (route.guildId === null ? /^D[A-Z0-9]+$/.test(route.channelId) :
165
179
  route.guildId === policy.teamId && policy.allowedChannelIds.includes(route.channelId));
166
180
  }
181
+ case "kakao": {
182
+ const policy = config.kakao;
183
+ return !!policy && route.authorityId === policy.ownerId && route.accountId === policy.botUserId
184
+ && route.guildId === null && route.threadId === null && route.channelId === policy.chatId;
185
+ }
167
186
  }
168
187
  }
169
188
 
@@ -200,7 +219,8 @@ export function parseConfig(value: unknown, path: string): Config {
200
219
  const discord = raw.discord === undefined ? undefined : record(raw.discord, "discord");
201
220
  const telegram = raw.telegram === undefined ? undefined : record(raw.telegram, "telegram");
202
221
  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");
222
+ const kakao = raw.kakao === undefined ? undefined : record(raw.kakao, "kakao");
223
+ if (!discord && !telegram && !slack && !kakao) throw new Error("Configure at least one messenger: discord, telegram, slack, or kakao");
204
224
  const base = dirname(absolute);
205
225
  const pathValue = (v: unknown, key: string) => resolve(base, text(v, key));
206
226
  if (!Array.isArray(raw.command) || !raw.command.length ||
@@ -241,7 +261,7 @@ export function parseConfig(value: unknown, path: string): Config {
241
261
  case "api":
242
262
  case undefined: {
243
263
  const apiKeyEnv = tokenEnv(voice.apiKeyEnv, "discord.voice.apiKeyEnv");
244
- if ([discord?.tokenEnv, telegram?.tokenEnv, slack?.appTokenEnv, slack?.botTokenEnv].includes(apiKeyEnv))
264
+ if ([discord?.tokenEnv, telegram?.tokenEnv, slack?.appTokenEnv, slack?.botTokenEnv, kakao?.tokenEnv].includes(apiKeyEnv))
245
265
  throw new Error("discord.voice.apiKeyEnv must not name a messenger token");
246
266
  voiceConfig = {
247
267
  ...session, ...(auth === undefined ? {} : { auth }), apiKeyEnv,
@@ -284,10 +304,31 @@ export function parseConfig(value: unknown, path: string): Config {
284
304
  teamId: id(slack.teamId, "slack.teamId", /^T[A-Z0-9]+$/),
285
305
  allowedChannelIds: ids(slack.allowedChannelIds, "slack.allowedChannelIds", /^[CG][A-Z0-9]+$/),
286
306
  } } : {}),
307
+ ...(kakao ? { kakao: parseKakao(kakao) } : {}),
287
308
  };
288
309
  return raw.groupRooms === undefined ? config : { ...config, groupRooms: parseGroupRooms(raw.groupRooms, config, base) };
289
310
  }
290
311
 
312
+ function parseKakao(kakao: Record<string, unknown>): KakaoConfig {
313
+ const kakaoId = /^[1-9]\d{0,19}$/;
314
+ const bridgeUrl = text(kakao.bridgeUrl, "kakao.bridgeUrl");
315
+ let url: URL;
316
+ try { url = new URL(bridgeUrl); } catch { throw new Error("kakao.bridgeUrl must be a URL"); }
317
+ // Literal loopback only: a host name could later resolve elsewhere.
318
+ if (url.protocol !== "http:" || !["127.0.0.1", "[::1]"].includes(url.hostname)
319
+ || url.username || url.password || url.search || url.hash)
320
+ throw new Error("kakao.bridgeUrl must be a plain http://127.0.0.1:PORT or http://[::1]:PORT URL");
321
+ const result: KakaoConfig = {
322
+ bridgeUrl,
323
+ tokenEnv: tokenEnv(kakao.tokenEnv, "kakao.tokenEnv"),
324
+ botUserId: id(kakao.botUserId, "kakao.botUserId", kakaoId),
325
+ ownerId: id(kakao.ownerId, "kakao.ownerId", kakaoId),
326
+ chatId: id(kakao.chatId, "kakao.chatId", kakaoId),
327
+ };
328
+ if (result.botUserId === result.ownerId) throw new Error("kakao.botUserId and kakao.ownerId must differ");
329
+ return result;
330
+ }
331
+
291
332
  /** No caller can turn a shared/symlink directory into a trusted socket directory. */
292
333
  export function privateDirectory(path: string): void {
293
334
  mkdirSync(path, { recursive: true, mode: 0o700 });
package/src/contracts.ts CHANGED
@@ -8,7 +8,7 @@ import type { RemotePlacement } from "./worker-wire";
8
8
  import type { OmpResetAccount } from "./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
12
 
13
13
  export interface Route {
14
14
  platform: Platform;
@@ -42,6 +42,11 @@ export function physicalRouteKey(route: Route): string {
42
42
 
43
43
  /** Store meta key: owner inputs acknowledged to Gateway whose topic routing is still pending, in delivery order. */
44
44
  export const DEFERRED_ROUTING_META = "intake:deferred-routing";
45
+ /** Internal HEAD review ID prefix; authority lives in the current store binding. */
46
+ export const SCOPE_REVIEW_PREFIX = "scope-review:";
47
+
48
+ /** Exact successor generation reserved when a submitted card is authorized to restore its original lane session. */
49
+ export const laneModelPickerRestoreKey = (sourceId: string) => `lane-model:picker-restore:${sourceId}`;
45
50
 
46
51
  export interface Attachment {
47
52
  id: string;
@@ -118,6 +123,8 @@ export interface Inbound {
118
123
  readonly cardId: string;
119
124
  readonly group: number;
120
125
  readonly option: number;
126
+ /** Emitted only when the final model choice is made on a scoped Discord card. */
127
+ readonly target?: "head" | "lane";
121
128
  /** Emitted only by the reset picker's separate Confirm action. */
122
129
  readonly confirmed?: true;
123
130
  };
@@ -129,6 +136,8 @@ export interface Inbound {
129
136
  receivedAt: number;
130
137
  attachments: Attachment[];
131
138
  reply?: ReplyContext;
139
+ /** The adapter observed a reply or shared message without an in-route reply snapshot. */
140
+ readonly unresolvedReply?: true;
132
141
  discordContext?: DiscordContext;
133
142
  }
134
143
 
@@ -144,6 +153,13 @@ export interface LaneModel {
144
153
  provider: string;
145
154
  id: string;
146
155
  }
156
+ export const laneFallbackKey = (id: string) => `lane-model:${id}:fallback`;
157
+ export interface LaneFallbackReceipt {
158
+ readonly sessionId: string;
159
+ readonly generation: number;
160
+ readonly hostPid: number;
161
+ readonly entryId: string;
162
+ }
147
163
  export const HEAD_MODEL_CONTROL = "head:model-control";
148
164
  export interface HeadModelChange {
149
165
  readonly sourceId: string;
@@ -231,11 +247,34 @@ export type HeadPicker = {
231
247
  readonly current?: string;
232
248
  readonly groups: readonly { readonly label: string; readonly options: readonly string[] }[];
233
249
  } & (
234
- | { readonly kind: "model"; readonly currentProvider?: string }
250
+ | { readonly kind: "model"; readonly currentProvider?: string; readonly modelTargets?: {
251
+ readonly lane?: {
252
+ readonly id: string;
253
+ readonly generation: number;
254
+ readonly sessionId: string | null;
255
+ readonly current?: string;
256
+ readonly currentProvider?: string;
257
+ /** If present, the canonical option indices allowed in each HEAD group. Empty means no lane choices. */
258
+ readonly allowedOptions?: readonly (readonly number[])[];
259
+ };
260
+ } }
235
261
  | { readonly kind: "effort"; readonly forModel: LaneModel }
236
262
  | { readonly kind: "usage-reset"; readonly accounts: readonly Pick<OmpResetAccount, "target" | "label" | "identity" | "offer">[] }
237
263
  );
238
264
 
265
+ /** Both admission and durable lane writes resolve the same original card coordinates. */
266
+ export function resolvePickerOption(picker: HeadPicker, selection: NonNullable<Inbound["pickerSelection"]>) {
267
+ if (!Number.isSafeInteger(selection.group) || selection.group < 0
268
+ || !Number.isSafeInteger(selection.option) || selection.option < 0) return null;
269
+ if (selection.target === "lane") {
270
+ const lane = picker.kind === "model" ? picker.modelTargets?.lane : undefined;
271
+ if (!lane || lane.allowedOptions !== undefined && !lane.allowedOptions?.[selection.group]?.includes(selection.option)) return null;
272
+ }
273
+ const group = picker.groups[selection.group];
274
+ const option = group?.options[selection.option];
275
+ return group && option ? { group, option } : null;
276
+ }
277
+
239
278
  export interface KickoffHold {
240
279
  readonly outputId: string;
241
280
  readonly state: OutputState | "missing";
@@ -258,6 +297,31 @@ export interface OutputRecord {
258
297
  error: string | null;
259
298
  }
260
299
 
300
+ export type SettlementOutput = Pick<OutputRecord, "id" | "text" | "picker"> & {
301
+ /** Controller-only lane failure routing, never derived from output text. */
302
+ readonly laneFailure?: "quota" | "recover";
303
+ /** Controller-verified clean native settlement of a solo scope-review admission. */
304
+ readonly scopeReviewEligible?: boolean;
305
+ };
306
+
307
+ export interface ScopeReview {
308
+ readonly lane: Lane;
309
+ readonly original: InputRecord;
310
+ readonly handoff: InputRecord;
311
+ }
312
+
313
+ /** Controller-proven successful native report, with its exact own approval if one was required. */
314
+ export interface ScopeReviewNativeProof {
315
+ readonly toolCallId: string;
316
+ readonly approvalId?: string;
317
+ }
318
+
319
+ export interface LaneRecoveryScope {
320
+ readonly lane: Lane;
321
+ readonly failed: InputRecord;
322
+ readonly original: InputRecord;
323
+ }
324
+
261
325
  export interface Approval {
262
326
  id: string;
263
327
  target: string;
@@ -320,7 +384,17 @@ export interface StorePort {
320
384
  receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
321
385
  input(id: string): InputRecord | null;
322
386
  ownerSource(id: string): InputRecord | null;
323
- /** Manager handoff's verified reply route, pinned if a bound reply joined its run. */
387
+ /** Revalidate a report's exact failed admission, actionable owner and operator selection. */
388
+ laneRecoveryScope(reportId: string): LaneRecoveryScope | null;
389
+ /** Stage a verified direct native scope-review signal; does not enqueue a HEAD input. */
390
+ recordScopeReview(inputId: string, generation: number, sessionId: string, sourceId: string, proof: ScopeReviewNativeProof): boolean;
391
+ /** Verify the current owner request, solo admission, and lane binding for review or granted dispatch. */
392
+ scopeReview(reviewId: string): ScopeReview | null;
393
+ /** Record one HEAD intent; only eligible native settlement can admit corrective work. */
394
+ requestScopeCorrection(reviewId: string): string;
395
+ /** Original parent route for a redirected report or a handoff derived from that report. */
396
+ reportApprovalSource(id: string): InputRecord | null;
397
+ /** Manager handoff's verified reply route, pinned for a parent-origin thread follow-up or a joined bound reply. */
324
398
  laneReplyRoute(input: InputRecord, source: InputRecord): Route;
325
399
  /** Exact original owner and authorized delivery route for a topic-owned lane input. */
326
400
  topicDelivery(id: string): { readonly source: InputRecord; readonly route: Route; readonly outputSourceId: string } | null;
@@ -336,6 +410,8 @@ export interface StorePort {
336
410
  latestLaneRun(target: string): InputRecord | null;
337
411
  /** A successful lane run still has an unresolved final report or delivery. */
338
412
  hasPendingLaneResult(target: string): boolean;
413
+ /** A current scope review or granted correction still needs this lane generation. */
414
+ hasPendingScopeReview(target: string): boolean;
339
415
  hasPendingLanePlacement(target: string): boolean;
340
416
  /** An uncertain HEAD input with a nonempty original native-owner record. */
341
417
  hasHeadRecoveryInput(): boolean;
@@ -366,13 +442,16 @@ export interface StorePort {
366
442
  progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace?: boolean): boolean;
367
443
  recordLaneReport(id: string, generation: number, sessionId: string, eventId: string, report: LaneReport, observedAt?: number): boolean;
368
444
  resolveLaneWaiting(id: string, generation: number, sessionId: string, kind: "tool" | "approval", nativeId: string): boolean;
369
- settle(id: string, state: "done" | "uncertain" | "cancelled", output?: Pick<OutputRecord, "id" | "text" | "picker">, headModel?: HeadModelChange, editInPlace?: boolean): boolean;
445
+ settle(id: string, state: "done" | "uncertain" | "cancelled", output?: SettlementOutput, headModel?: HeadModelChange, editInPlace?: boolean): boolean;
370
446
  settleCronControl(inputId: string, update: CronUpdate): boolean;
371
447
  resolveLaneInput(controlId: string, laneId: string, inputId: string, output: { readonly id: string; readonly text: string }): boolean;
372
448
  headRecoveryEffects(inputId: string): HeadRecoveryEffect[];
373
449
  prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
374
450
  commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
375
451
  queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
452
+ recordRestartCheckpointFailure(expectedFence: string, stopBoundary: string | null, failedFence: string,
453
+ output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
454
+ recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
376
455
  output(id: string): OutputRecord | null;
377
456
  outputs(physicalRoute?: string): OutputRecord[];
378
457
  claimOutput(id: string, editInPlace?: boolean): boolean;
@@ -384,10 +463,13 @@ export interface StorePort {
384
463
  updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
385
464
  "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
386
465
  >>): boolean;
387
- nextGeneration(id: string): Lane;
466
+ retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath">): boolean;
467
+ nextGeneration(id: string, pickerRestoreSourceId?: string): Lane;
388
468
  adoptLaneModel(id: string, generation: number, model: LaneModel, reason: string): boolean;
389
469
  changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: string,
390
- preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata?: Readonly<Record<string, string>>): boolean;
470
+ preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata?: Readonly<Record<string, string>>, operatorSourceId?: string): boolean;
471
+ recordLaneFallback(id: string, configured: LaneModel, previous: string | null, receipt: LaneFallbackReceipt,
472
+ notice: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
391
473
  putApproval(approval: Approval, ownerInputId?: string): void;
392
474
  approval(id: string): Approval | null;
393
475
  approvals(target?: string): Approval[];
@@ -451,6 +533,17 @@ export interface ThreadUpdate {
451
533
  readonly archived?: boolean;
452
534
  }
453
535
 
536
+ export interface InboundAttachmentBatch {
537
+ readonly inputId: string;
538
+ readonly route: Route;
539
+ readonly attachments: readonly Attachment[];
540
+ }
541
+
542
+ export interface InboundAttachmentReceipt {
543
+ readonly receipt: string;
544
+ readonly files: readonly { readonly path: string; readonly size: number; readonly mimeType: string; readonly sha256: string }[];
545
+ }
546
+
454
547
  export interface Messenger {
455
548
  start(handlers: {
456
549
  /** Authenticate first; do not consume inbound events until native approvals are reconciled. */
@@ -483,7 +576,7 @@ export interface Messenger {
483
576
  messengerPresence?(request: MessengerPresenceRequest): Promise<DiscordPresenceStatus>;
484
577
  /** null explicitly means no history API; intake recovery belongs to the adapter. */
485
578
  fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null>;
486
- /** Validate platform/auth destination before fetching. Never follow redirects with credentials. */
487
- openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response>;
579
+ /** Validate the source before fetching; receipt only a complete, private batch. */
580
+ openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt>;
488
581
  stop(): Promise<void>;
489
582
  }
@@ -1,201 +1,49 @@
1
- import { REST, Routes, type RESTOptions } from "discord.js";
2
1
  import type { Config } from "./config";
3
- import { loadCredentials, validateCredential } from "./credentials";
4
- import { DISCORD_COMMANDS } from "./discord-commands";
5
-
6
- type CommandRest = Pick<REST, "get" | "put">;
2
+ import { operatorBotToken, runOperator, type OperatorRun } from "./operator";
7
3
 
8
4
  export interface DiscordCommandRegistrationOptions {
9
- apply?: boolean;
10
- createRest?: (options: Partial<RESTOptions>, token: string) => CommandRest;
11
- }
12
-
13
- interface Registration {
14
- id: string;
15
- application_id: string;
16
- type: number;
17
- name: string;
18
- description: string;
19
- [key: string]: unknown;
20
- }
21
-
22
- export interface DiscordCommandRegistrationReport {
23
- status: "dry-run" | "blocked" | "applied";
24
- applicationId: string;
25
- botId: string;
26
- plannedGlobal: typeof DISCORD_COMMANDS;
27
- currentGlobal: { id: string; type: number; name: string }[];
28
- obsoleteGlobal: { id: string; type: number; name: string }[];
29
- guilds: {
30
- guildId: string;
31
- registrations: { id: string; type: number; name: string }[];
32
- shadowing: { id: string; type: number; name: string }[];
33
- }[];
34
- note: string;
35
- }
36
-
37
- function object(value: unknown): Record<string, unknown> {
38
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed Discord response");
39
- return value as Record<string, unknown>;
40
- }
41
-
42
- function snowflake(value: unknown): string {
43
- if (typeof value !== "string" || !/^\d+$/.test(value)) throw new Error("Malformed Discord identity");
44
- return value;
5
+ readonly apply?: boolean;
6
+ readonly run?: OperatorRun;
45
7
  }
46
8
 
47
- function registrations(value: unknown, applicationId: string, guildId?: string): Registration[] {
48
- if (!Array.isArray(value)) throw new Error("Malformed Discord command list");
49
- const ids = new Set<string>();
50
- const keys = new Set<string>();
51
- return value.map(item => {
52
- const row = object(item);
53
- const id = snowflake(row.id);
54
- if (row.application_id !== applicationId ||
55
- (guildId === undefined ? row.guild_id !== undefined : row.guild_id !== guildId) ||
56
- !Number.isInteger(row.type) || ![1, 2, 3, 4].includes(row.type as number) ||
57
- typeof row.name !== "string" || !row.name.length || row.name.length > 32 ||
58
- typeof row.description !== "string" ||
59
- (row.options !== undefined && !Array.isArray(row.options)))
60
- throw new Error("Malformed Discord command list");
61
- const key = `${row.type}:${row.name}`;
62
- if (ids.has(id) || keys.has(key)) throw new Error("Duplicate Discord registration");
63
- ids.add(id);
64
- keys.add(key);
65
- return row as Registration;
66
- });
9
+ interface DiscordDefinition {
10
+ readonly type: 1;
11
+ readonly name: string;
12
+ readonly description: string;
13
+ readonly contexts: readonly [0, 1];
14
+ readonly integration_types: readonly [0];
15
+ readonly options?: readonly [{ readonly type: 3; readonly name: "text"; readonly description: string; readonly required: false }];
67
16
  }
68
17
 
69
- function sortedNumbers(value: unknown, fallback: number[]): number[] {
70
- const values = value === undefined ? fallback : value;
71
- if (!Array.isArray(values) || !values.every(item => Number.isInteger(item)) ||
72
- new Set(values).size !== values.length) throw new Error("Malformed Discord command contexts");
73
- return [...values].sort((a, b) => a - b);
18
+ interface RegistrationSummary {
19
+ readonly id: string;
20
+ readonly type: number;
21
+ readonly name: string;
74
22
  }
75
23
 
76
- function localizations(value: unknown): Record<string, string> {
77
- if (value == null) return {};
78
- const entries = Object.entries(object(value));
79
- if (entries.some(([, text]) => typeof text !== "string")) throw new Error("Malformed Discord localization");
80
- return Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b))) as Record<string, string>;
81
- }
82
-
83
- /** Keep semantic option fields, omitting only Discord's documented empty defaults. */
84
- function commandOption(value: unknown): Record<string, unknown> {
85
- const row = object(value);
86
- if (!Number.isInteger(row.type) || typeof row.name !== "string" || typeof row.description !== "string")
87
- throw new Error("Malformed Discord command option");
88
- const result: Record<string, unknown> = {};
89
- for (const key of Object.keys(row).sort()) {
90
- const item = row[key];
91
- if (item === undefined) continue;
92
- if ((key === "required" || key === "autocomplete") && item === false) continue;
93
- if (key === "name_localizations" || key === "description_localizations") {
94
- const values = localizations(item);
95
- if (Object.keys(values).length) result[key] = values;
96
- } else if (key === "options" || key === "choices" || key === "channel_types") {
97
- if (!Array.isArray(item)) throw new Error("Malformed Discord command option");
98
- if (item.length) result[key] = key === "options" ? item.map(commandOption) : item;
99
- } else {
100
- result[key] = item;
101
- }
102
- }
103
- return result;
104
- }
105
-
106
- function definition(value: unknown): Record<string, unknown> {
107
- const row = object(value);
108
- if (typeof row.name !== "string" || typeof row.description !== "string" ||
109
- (row.options !== undefined && !Array.isArray(row.options))) throw new Error("Malformed Discord definition");
110
- return {
111
- type: row.type ?? 1,
112
- name: row.name,
113
- description: row.description,
114
- options: ((row.options ?? []) as unknown[]).map(commandOption),
115
- contexts: sortedNumbers(row.contexts, [0, 1, 2]),
116
- integration_types: sortedNumbers(row.integration_types, [0]),
117
- name_localizations: localizations(row.name_localizations),
118
- description_localizations: localizations(row.description_localizations),
119
- default_member_permissions: row.default_member_permissions ?? null,
120
- default_permission: row.default_permission ?? true,
121
- nsfw: row.nsfw ?? false,
122
- };
123
- }
124
-
125
- function exactDefinitions(actual: Registration[]): boolean {
126
- const normalized = (commands: readonly unknown[]) => commands.map(definition)
127
- .sort((a, b) => `${a.type}:${a.name}`.localeCompare(`${b.type}:${b.name}`));
128
- return JSON.stringify(normalized(actual)) === JSON.stringify(normalized(DISCORD_COMMANDS));
24
+ export interface DiscordCommandRegistrationReport {
25
+ readonly status: "dry-run" | "blocked" | "applied";
26
+ readonly applicationId: string;
27
+ readonly botId: string;
28
+ readonly plannedGlobal: readonly DiscordDefinition[];
29
+ readonly currentGlobal: readonly RegistrationSummary[];
30
+ readonly obsoleteGlobal: readonly RegistrationSummary[];
31
+ readonly guilds: readonly {
32
+ readonly guildId: string;
33
+ readonly registrations: readonly RegistrationSummary[];
34
+ readonly shadowing: readonly RegistrationSummary[];
35
+ }[];
36
+ readonly note: string;
129
37
  }
130
38
 
131
- /** REST-only opt-in. Never opens a Gateway, imports native OMP, or retries a mutation. */
39
+ /** REST-only opt-in. Never opens a Gateway or starts OMP. */
132
40
  export async function registerDiscordCommands(
133
41
  config: Config, options: DiscordCommandRegistrationOptions = {},
134
42
  ): Promise<DiscordCommandRegistrationReport> {
135
- if (!config.discord) throw new Error("discord-commands requires configured Discord credentials and policy");
136
- try {
137
- // Reuse the existing private sibling-file/environment policy, selecting Discord only.
138
- loadCredentials({ ...config, telegram: undefined, slack: undefined });
139
- } catch { throw new Error("Cannot safely load the configured Discord credential; details suppressed"); }
140
- const token = process.env[config.discord.tokenEnv];
141
- if (!token) throw new Error("Configured Discord credential is missing");
142
- try { validateCredential(token); }
143
- catch { throw new Error("Configured Discord credential is invalid; value suppressed"); }
144
-
145
- let rest: CommandRest;
146
- try {
147
- rest = (options.createRest ?? ((settings, credential) => new REST(settings).setToken(credential)))(
148
- { version: "10", retries: 0, rejectOnRateLimit: () => true }, token,
149
- );
150
- } catch { throw new Error("Discord REST initialization failed; details suppressed"); }
151
-
152
- let report: DiscordCommandRegistrationReport;
153
- let applicationId: string;
154
- try {
155
- const bot = object(await rest.get(Routes.user("@me")));
156
- const botId = snowflake(bot.id);
157
- if (bot.bot !== true) throw new Error("Discord identity is not a bot");
158
- const application = object(await rest.get(Routes.oauth2CurrentApplication()));
159
- applicationId = snowflake(application.id);
160
- if (applicationId !== botId ||
161
- (application.bot !== undefined && snowflake(object(application.bot).id) !== botId))
162
- throw new Error("Discord bot/application identity mismatch");
163
- const current = registrations(await rest.get(Routes.applicationCommands(applicationId)), applicationId);
164
- const supported = new Set(DISCORD_COMMANDS.map(command => `${command.type ?? 1}:${command.name}`));
165
- const summary = (rows: Registration[]) => rows.map(row => ({
166
- id: row.id, type: row.type,
167
- name: row.name.replaceAll(token, "[redacted]").replace(/https?:\/\/\S+/gi, "[redacted-url]"),
168
- }));
169
- const guilds: DiscordCommandRegistrationReport["guilds"] = [];
170
- for (const guildId of config.discord.allowedGuildIds) {
171
- const rows = registrations(await rest.get(Routes.applicationGuildCommands(applicationId, guildId)), applicationId, guildId);
172
- guilds.push({ guildId, registrations: summary(rows), shadowing: summary(rows.filter(row => supported.has(`${row.type}:${row.name}`))) });
173
- }
174
- report = {
175
- status: "dry-run", applicationId, botId, plannedGlobal: DISCORD_COMMANDS,
176
- currentGlobal: summary(current),
177
- obsoleteGlobal: summary(current.filter(row => !supported.has(`${row.type}:${row.name}`))),
178
- guilds,
179
- note: "Read-only plan. --apply takes exclusive ownership of this dedicated bot's GLOBAL command list, replacing it with supported Superagent definitions and deleting all other global registrations (including Hermes). Guild registrations are preserved; supported-name guild shadows block apply. No Gateway or native runtime was started.",
180
- };
181
- } catch {
182
- throw new Error("Discord command inspection failed: identity, permissions, or response could not be verified. No mutation was attempted; raw SDK details suppressed. No automatic retry was attempted.");
183
- }
184
-
185
- if (!options.apply) return report;
186
- if (report.guilds.some(guild => guild.shadowing.length)) {
187
- return { ...report, status: "blocked", note: "Apply refused: allowed-guild registrations shadow supported global commands. No mutation was attempted; all guild registrations are preserved. Resolve guild conflicts explicitly before applying." };
188
- }
189
- try {
190
- await rest.put(Routes.applicationCommands(applicationId), { body: DISCORD_COMMANDS });
191
- } catch {
192
- throw new Error("Discord global command overwrite is unresolved: the request failed and may have reached Discord. No automatic retry was attempted; raw SDK details suppressed. Inspect with discord-commands (without --apply) before deciding any further mutation.");
193
- }
194
- try {
195
- const actual = registrations(await rest.get(Routes.applicationCommands(applicationId)), applicationId);
196
- if (!exactDefinitions(actual)) throw new Error("Discord readback differs");
197
- } catch {
198
- throw new Error("Discord global command overwrite is unresolved: authoritative GET did not verify the exact supported definitions. No automatic retry was attempted; raw SDK details suppressed. Inspect with discord-commands (without --apply) before deciding any further mutation.");
199
- }
200
- return { ...report, status: "applied", note: "Global command overwrite verified by authoritative GET: exact supported Superagent names, types, descriptions, options, contexts, and guild-only installation. Obsolete global registrations were removed; guild registrations were not changed. No Gateway or native runtime was started." };
43
+ const policy = config.discord;
44
+ if (!policy) throw new Error("discord-commands requires configured Discord credentials and policy");
45
+ const bot = operatorBotToken("Discord", config.path, policy.tokenEnv);
46
+ return (options.run ?? runOperator)("discord-commands", {
47
+ apply: options.apply === true, allowedGuildIds: policy.allowedGuildIds,
48
+ }, { bot });
201
49
  }