omp-superagent 0.1.8 → 0.1.9

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 (104) hide show
  1. package/DESIGN.md +6 -2
  2. package/README.ko.md +12 -9
  3. package/README.md +13 -9
  4. package/THIRD_PARTY_NOTICES.md +8 -8
  5. package/docs/OPERATIONS.md +62 -20
  6. package/docs/design/execution.md +79 -14
  7. package/docs/design/messaging.md +66 -15
  8. package/docs/releases/0.1.9.md +18 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  14. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  15. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  16. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  17. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  21. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  22. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  23. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  24. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  25. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  29. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  30. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  31. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  32. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  33. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  41. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  42. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  43. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  44. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  45. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  46. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  49. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  50. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  51. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  53. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  54. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  55. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  56. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  57. package/package.json +10 -8
  58. package/skills/head/SKILL.md +3 -11
  59. package/skills/head/references/routing.md +23 -17
  60. package/skills/head/references/supervision.md +13 -1
  61. package/skills/lane/references/workflow.md +8 -8
  62. package/src/cli.ts +4 -4
  63. package/src/contracts.ts +71 -7
  64. package/src/discord-command-registration.ts +34 -186
  65. package/src/extension.ts +22 -2
  66. package/src/gateway-client.ts +11 -59
  67. package/src/gateway-protocol.ts +35 -1
  68. package/src/head-recovery.ts +226 -17
  69. package/src/host-extension.ts +82 -9
  70. package/src/host-protocol.ts +5 -9
  71. package/src/lane-models.ts +8 -0
  72. package/src/managed-ulw-probe.ts +22 -20
  73. package/src/messenger-command-catalog.json +6 -3
  74. package/src/messenger-commands.ts +9 -2
  75. package/src/operator.ts +77 -0
  76. package/src/pr-github-schema.ts +2 -0
  77. package/src/pr-intake-automation.ts +1 -2
  78. package/src/pr-intake-comment.ts +1 -2
  79. package/src/pr-intake-fix.ts +1 -2
  80. package/src/pr-intake-github.ts +1 -2
  81. package/src/pr-intake-material.ts +1 -2
  82. package/src/pr-intake-tree.ts +1 -2
  83. package/src/pr-review-models.ts +28 -0
  84. package/src/result-attachment.ts +60 -79
  85. package/src/runtime.ts +1461 -254
  86. package/src/setup-profiles.ts +26 -65
  87. package/src/slack-command-registration.ts +48 -197
  88. package/src/store.ts +265 -45
  89. package/src/superkit-skills.ts +22 -0
  90. package/src/telegram-command-languages.json +17 -0
  91. package/src/telegram-command-registration.ts +32 -134
  92. package/src/worker-bridge.ts +21 -0
  93. package/src/worker-enrollment.ts +2 -1
  94. package/src/worker-host.ts +0 -24
  95. package/src/worker-serve-prepare.ts +19 -0
  96. package/src/worker-service.ts +51 -47
  97. package/scripts/ci.ts +0 -44
  98. package/scripts/release.ts +0 -112
  99. package/scripts/test-omp.sh +0 -44
  100. package/src/discord-commands.ts +0 -29
  101. package/src/discord-markdown.ts +0 -399
  102. package/src/slack-commands.ts +0 -18
  103. package/src/telegram-signal.ts +0 -14
  104. package/src/worker-stdio.ts +0 -61
package/src/cli.ts CHANGED
@@ -87,7 +87,8 @@ Owner controls in chat (not shell commands):
87
87
  Send /help in Discord or Telegram. In Slack messages replace / with ! (e.g. !help, !status);
88
88
  registered Slack commands use /superagent-* (e.g. /superagent-status).
89
89
  /status, /context, /usage Inspect HEAD state, context or usage without starting a model turn.
90
- /usage reset List saved reset tickets; choose an account then confirm to spend one.
90
+ /usage-reset (Discord) List saved reset tickets; choose an account then confirm to spend one.
91
+ Telegram: /usage reset. Slack: !usage reset or /superagent-usage reset.
91
92
  /model [list|provider/id] Inspect or select the shared HEAD model; changes require an idle HEAD.
92
93
  /model preset [list|NAME] Inspect or select a preset. Only NAME --global also saves future defaults.
93
94
  /effort [LEVEL] Inspect or change HEAD thinking effort; existing lanes keep their settings.
@@ -247,9 +248,8 @@ async function workerCommand(args: string[]): Promise<void> {
247
248
  throw new Error("Worker serve requires the enrolled SSH forced command");
248
249
  const { readWorkerPolicy } = await import("./worker-enrollment");
249
250
  const policy = readWorkerPolicy(homedir(), path);
250
- const { serveWorker } = await import("./worker-service");
251
- await serveWorker(policy);
252
- return;
251
+ const { execWorkerBridge } = await import("./worker-bridge");
252
+ return execWorkerBridge(policy, path);
253
253
  }
254
254
  default:
255
255
  throw new Error("Usage: omp-sa worker add|init|list|doctor (see omp-sa worker --help)");
package/src/contracts.ts CHANGED
@@ -43,6 +43,9 @@ export function physicalRouteKey(route: Route): string {
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
45
 
46
+ /** Exact successor generation reserved when a submitted card is authorized to restore its original lane session. */
47
+ export const laneModelPickerRestoreKey = (sourceId: string) => `lane-model:picker-restore:${sourceId}`;
48
+
46
49
  export interface Attachment {
47
50
  id: string;
48
51
  name: string;
@@ -118,6 +121,8 @@ export interface Inbound {
118
121
  readonly cardId: string;
119
122
  readonly group: number;
120
123
  readonly option: number;
124
+ /** Emitted only when the final model choice is made on a scoped Discord card. */
125
+ readonly target?: "head" | "lane";
121
126
  /** Emitted only by the reset picker's separate Confirm action. */
122
127
  readonly confirmed?: true;
123
128
  };
@@ -144,6 +149,13 @@ export interface LaneModel {
144
149
  provider: string;
145
150
  id: string;
146
151
  }
152
+ export const laneFallbackKey = (id: string) => `lane-model:${id}:fallback`;
153
+ export interface LaneFallbackReceipt {
154
+ readonly sessionId: string;
155
+ readonly generation: number;
156
+ readonly hostPid: number;
157
+ readonly entryId: string;
158
+ }
147
159
  export const HEAD_MODEL_CONTROL = "head:model-control";
148
160
  export interface HeadModelChange {
149
161
  readonly sourceId: string;
@@ -231,11 +243,34 @@ export type HeadPicker = {
231
243
  readonly current?: string;
232
244
  readonly groups: readonly { readonly label: string; readonly options: readonly string[] }[];
233
245
  } & (
234
- | { readonly kind: "model"; readonly currentProvider?: string }
246
+ | { readonly kind: "model"; readonly currentProvider?: string; readonly modelTargets?: {
247
+ readonly lane?: {
248
+ readonly id: string;
249
+ readonly generation: number;
250
+ readonly sessionId: string | null;
251
+ readonly current?: string;
252
+ readonly currentProvider?: string;
253
+ /** If present, the canonical option indices allowed in each HEAD group. Empty means no lane choices. */
254
+ readonly allowedOptions?: readonly (readonly number[])[];
255
+ };
256
+ } }
235
257
  | { readonly kind: "effort"; readonly forModel: LaneModel }
236
258
  | { readonly kind: "usage-reset"; readonly accounts: readonly Pick<OmpResetAccount, "target" | "label" | "identity" | "offer">[] }
237
259
  );
238
260
 
261
+ /** Both admission and durable lane writes resolve the same original card coordinates. */
262
+ export function resolvePickerOption(picker: HeadPicker, selection: NonNullable<Inbound["pickerSelection"]>) {
263
+ if (!Number.isSafeInteger(selection.group) || selection.group < 0
264
+ || !Number.isSafeInteger(selection.option) || selection.option < 0) return null;
265
+ if (selection.target === "lane") {
266
+ const lane = picker.kind === "model" ? picker.modelTargets?.lane : undefined;
267
+ if (!lane || lane.allowedOptions !== undefined && !lane.allowedOptions?.[selection.group]?.includes(selection.option)) return null;
268
+ }
269
+ const group = picker.groups[selection.group];
270
+ const option = group?.options[selection.option];
271
+ return group && option ? { group, option } : null;
272
+ }
273
+
239
274
  export interface KickoffHold {
240
275
  readonly outputId: string;
241
276
  readonly state: OutputState | "missing";
@@ -258,6 +293,17 @@ export interface OutputRecord {
258
293
  error: string | null;
259
294
  }
260
295
 
296
+ export type SettlementOutput = Pick<OutputRecord, "id" | "text" | "picker"> & {
297
+ /** Controller-only lane failure routing, never derived from output text. */
298
+ readonly laneFailure?: "quota" | "recover";
299
+ };
300
+
301
+ export interface LaneRecoveryScope {
302
+ readonly lane: Lane;
303
+ readonly failed: InputRecord;
304
+ readonly original: InputRecord;
305
+ }
306
+
261
307
  export interface Approval {
262
308
  id: string;
263
309
  target: string;
@@ -320,7 +366,11 @@ export interface StorePort {
320
366
  receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
321
367
  input(id: string): InputRecord | null;
322
368
  ownerSource(id: string): InputRecord | null;
323
- /** Manager handoff's verified reply route, pinned if a bound reply joined its run. */
369
+ /** Revalidate a report's exact failed admission, actionable owner and operator selection. */
370
+ laneRecoveryScope(reportId: string): LaneRecoveryScope | null;
371
+ /** Original parent route for a redirected report or a handoff derived from that report. */
372
+ reportApprovalSource(id: string): InputRecord | null;
373
+ /** Manager handoff's verified reply route, pinned for a parent-origin thread follow-up or a joined bound reply. */
324
374
  laneReplyRoute(input: InputRecord, source: InputRecord): Route;
325
375
  /** Exact original owner and authorized delivery route for a topic-owned lane input. */
326
376
  topicDelivery(id: string): { readonly source: InputRecord; readonly route: Route; readonly outputSourceId: string } | null;
@@ -366,13 +416,14 @@ export interface StorePort {
366
416
  progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace?: boolean): boolean;
367
417
  recordLaneReport(id: string, generation: number, sessionId: string, eventId: string, report: LaneReport, observedAt?: number): boolean;
368
418
  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;
419
+ settle(id: string, state: "done" | "uncertain" | "cancelled", output?: SettlementOutput, headModel?: HeadModelChange, editInPlace?: boolean): boolean;
370
420
  settleCronControl(inputId: string, update: CronUpdate): boolean;
371
421
  resolveLaneInput(controlId: string, laneId: string, inputId: string, output: { readonly id: string; readonly text: string }): boolean;
372
422
  headRecoveryEffects(inputId: string): HeadRecoveryEffect[];
373
423
  prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
374
424
  commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
375
425
  queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
426
+ recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
376
427
  output(id: string): OutputRecord | null;
377
428
  outputs(physicalRoute?: string): OutputRecord[];
378
429
  claimOutput(id: string, editInPlace?: boolean): boolean;
@@ -384,10 +435,12 @@ export interface StorePort {
384
435
  updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
385
436
  "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
386
437
  >>): boolean;
387
- nextGeneration(id: string): Lane;
438
+ nextGeneration(id: string, pickerRestoreSourceId?: string): Lane;
388
439
  adoptLaneModel(id: string, generation: number, model: LaneModel, reason: string): boolean;
389
440
  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;
441
+ preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata?: Readonly<Record<string, string>>, operatorSourceId?: string): boolean;
442
+ recordLaneFallback(id: string, configured: LaneModel, previous: string | null, receipt: LaneFallbackReceipt,
443
+ notice: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
391
444
  putApproval(approval: Approval, ownerInputId?: string): void;
392
445
  approval(id: string): Approval | null;
393
446
  approvals(target?: string): Approval[];
@@ -451,6 +504,17 @@ export interface ThreadUpdate {
451
504
  readonly archived?: boolean;
452
505
  }
453
506
 
507
+ export interface InboundAttachmentBatch {
508
+ readonly inputId: string;
509
+ readonly route: Route;
510
+ readonly attachments: readonly Attachment[];
511
+ }
512
+
513
+ export interface InboundAttachmentReceipt {
514
+ readonly receipt: string;
515
+ readonly files: readonly { readonly path: string; readonly size: number; readonly mimeType: string; readonly sha256: string }[];
516
+ }
517
+
454
518
  export interface Messenger {
455
519
  start(handlers: {
456
520
  /** Authenticate first; do not consume inbound events until native approvals are reconciled. */
@@ -483,7 +547,7 @@ export interface Messenger {
483
547
  messengerPresence?(request: MessengerPresenceRequest): Promise<DiscordPresenceStatus>;
484
548
  /** null explicitly means no history API; intake recovery belongs to the adapter. */
485
549
  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>;
550
+ /** Validate the source before fetching; receipt only a complete, private batch. */
551
+ openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt>;
488
552
  stop(): Promise<void>;
489
553
  }
@@ -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
  }
package/src/extension.ts CHANGED
@@ -127,6 +127,22 @@ export default function superagentExtension(pi: ExtensionAPI): void {
127
127
  pi.on("tool_call", (event, ctx) => {
128
128
  if (runtime?.prObservationActive())
129
129
  return { block: true, reason: "PR observation turns cannot use tools; summarize the observed evidence only" };
130
+ if (ctx.agent.kind === "main" && runtime?.laneRecoveryObservationOnly())
131
+ return { block: true, reason: "No current owner authority for this lane failure; report the observed result only" };
132
+ if (ctx.agent.kind === "main" && runtime?.laneRecoveryActive() && Object.hasOwn(managerTools, event.toolName)) {
133
+ switch (event.toolName) {
134
+ case "lane_models": case "lane_inspect": case "thread_inspect": case "discord_context": case "discord_purpose_list":
135
+ case "decision_list": case "decision_inspect": case "pr_watch_list":
136
+ // The runtime validates their exact report source, target and current authority.
137
+ case "lane_message": case "lane_set_model":
138
+ break;
139
+ case "lane_watch": case "messenger_presence":
140
+ if (event.input.action === "status") break;
141
+ return { block: true, reason: "Lane recovery cannot authorize this manager mutation" };
142
+ default:
143
+ return { block: true, reason: "Lane recovery cannot authorize this manager mutation" };
144
+ }
145
+ }
130
146
  if (event.toolName === "lane_watch" && ctx.agent.kind !== "main")
131
147
  return { block: true, reason: "Lane watches are restricted to the main superagent head" };
132
148
  if (event.toolName === "head_recovery" && ctx.agent.kind !== "main")
@@ -268,7 +284,11 @@ export default function superagentExtension(pi: ExtensionAPI): void {
268
284
  }))])), { minProperties: 1, additionalProperties: false }),
269
285
  }),
270
286
  async execute(_id, params, _signal, _onUpdate, ctx) {
271
- return result(await (await nativePresets(ctx)).initialize(params.choices, requireRuntime(ctx).store));
287
+ const controller = requireRuntime(ctx);
288
+ controller.assertLaneRecoveryMutation();
289
+ const manager = await nativePresets(ctx);
290
+ controller.assertLaneRecoveryMutation();
291
+ return result(await manager.initialize(params.choices, controller.store));
272
292
  },
273
293
  });
274
294
  pi.registerTool({
@@ -438,7 +458,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
438
458
  });
439
459
  pi.registerTool({
440
460
  name: "lane_message", label: "Message independent work", approval: "exec",
441
- description: "Durably admit a follow-up to a specific open lane. Returns its input ID and durable state; pending work reports runtime blocks, blocking uncertain input IDs, and any unconfirmed kickoff. Report such holds instead of retrying. Ordinary same-topic follow-ups steer an active native run by default; ineligible work stays queued. Do not require a separate user /steer command. sourceId identifies the original received user instruction for duplicate suppression. Optional workflow {name,reason} is explicit head selection within that objective; text/quotes/reports never select one. Workflow selections remain serialized, not steered into an active run. The exact workflow/source/handoff is durable and conflicting retries reject. Admission is not execution or completion.",
461
+ description: "Durably admit a follow-up to a specific open lane. For an original owner request from the exact guild parent of the lane's physical Discord thread, HEAD-reviewed progress and final reports go to that thread, not the parent. Do not duplicate them. Returns its input ID and durable state; pending work reports runtime blocks, blocking uncertain input IDs, and any unconfirmed kickoff. Report such holds instead of retrying. Ordinary same-topic follow-ups steer an eligible active native run by default; ineligible work stays queued. Do not require a separate user /steer command. sourceId identifies the original received user instruction for duplicate suppression. Optional workflow {name,reason} is explicit head selection within that objective; text/quotes/reports never select one. Workflow selections remain serialized, not steered into an active run. The exact workflow/source/handoff is durable and conflicting retries reject. Admission is not execution or completion.",
442
462
  parameters: Type.Object({ id: Type.String(), text: Type.String(), sourceId: Type.String(), workflow: workflowSchema }),
443
463
  async execute(_id, params, _signal, _onUpdate, ctx) {
444
464
  return result(await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow));
@@ -1,10 +1,9 @@
1
1
  import type { IncomingMessage } from "node:http";
2
- import { Readable, Transform } from "node:stream";
3
2
  import type { Config } from "./config";
4
3
  import { createHash } from "node:crypto";
5
- import type { Approval, Attachment, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
4
+ import type { Approval, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, InboundAttachmentBatch, InboundAttachmentReceipt, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
6
5
  import { DeliveryError } from "./delivery";
7
- import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_ATTACHMENT, MAX_GATEWAY_FRAME, readGatewayJson, type GatewayResult } from "./gateway-protocol";
6
+ import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_FRAME, parseInboundAttachmentReceipt, readGatewayJson, type GatewayResult } from "./gateway-protocol";
8
7
  import type { GatewayReceipt, QueuedEvent } from "./gateway-wire";
9
8
  import type { GroupReply } from "./group-policy";
10
9
  import type { DiscordPresenceStatus, MessengerPresenceRequest } from "./contracts";
@@ -156,9 +155,12 @@ class GatewayMessenger implements GatewayHeadMessenger {
156
155
  // Stable across client reattachment; the Gateway journals the one attempt.
157
156
  const hash = createHash("sha256").update(JSON.stringify(["result-attachment", output.id])).digest("hex");
158
157
  const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
159
- // The adapter needs bytes and filename, not filesystem paths or native IDs.
158
+ // Transfer only a receipt; the old persisted payload is read by the Gateway
159
+ // itself so its original attempt fingerprint can still be reconciled.
160
+ const { payload } = resultAttachment;
160
161
  return this.call<string>("/effect", { id, operation: "send", args: [{
161
- id: output.id, route: output.route, text: output.text, replyTo: output.replyTo, resultAttachment: resultAttachment.payload,
162
+ id: output.id, route: output.route, text: output.text, replyTo: output.replyTo,
163
+ resultAttachment: "data" in payload ? { name: payload.name, legacy: true } : payload,
162
164
  }] });
163
165
  }
164
166
  assertRoute(route: Route, purpose?: "history"): Promise<void> {
@@ -185,62 +187,12 @@ class GatewayMessenger implements GatewayHeadMessenger {
185
187
  discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> { return this.effect("discordPurpose", [request]); }
186
188
  fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> { return this.effect("fetchAfter", [route, messageId]); }
187
189
 
188
- async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
190
+ async openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt> {
189
191
  if (this.stopped) throw new DeliveryError("Gateway client is stopped", "rejected");
190
- if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_GATEWAY_ATTACHMENT))
191
- throw new DeliveryError("Invalid attachment size", "rejected");
192
- const incoming = await gatewayRequest(this.socketPath, "/attachment", { route, attachment }, { ...this.options(), signal });
193
- if (incoming.headers["x-gateway-attachment-protocol"] !== "1") {
194
- const result = await readGatewayJson(incoming) as GatewayResult;
195
- throw new DeliveryError(result.error ?? "Attachment rejected", result.certainty ?? "uncertain");
196
- }
197
- let bytes = 0;
198
- const header = Buffer.allocUnsafe(4);
199
- let headerBytes = 0;
200
- let remaining = 0;
201
- let complete = false;
202
- const bounded = new Transform({
203
- transform(chunk: Buffer, _encoding, callback) {
204
- let offset = 0;
205
- while (offset < chunk.length) {
206
- if (complete) { callback(new Error("Attachment data followed its completion frame")); return; }
207
- if (!remaining) {
208
- const count = Math.min(4 - headerBytes, chunk.length - offset);
209
- chunk.copy(header, headerBytes, offset, offset + count);
210
- headerBytes += count;
211
- offset += count;
212
- if (headerBytes < 4) continue;
213
- remaining = header.readUInt32BE();
214
- headerBytes = 0;
215
- if (!remaining) { complete = true; continue; }
216
- if (bytes + remaining > (attachment.size ?? MAX_GATEWAY_ATTACHMENT) || bytes + remaining > MAX_GATEWAY_ATTACHMENT) {
217
- callback(new Error("Attachment stream exceeds declared size"));
218
- return;
219
- }
220
- }
221
- const count = Math.min(remaining, chunk.length - offset);
222
- if (count) this.push(chunk.subarray(offset, offset + count));
223
- offset += count;
224
- remaining -= count;
225
- bytes += count;
226
- }
227
- callback();
228
- },
229
- flush(callback) {
230
- callback(!complete || remaining || headerBytes || attachment.size !== null && bytes !== attachment.size
231
- ? new Error("Attachment stream ended without a complete delivery receipt") : undefined);
232
- },
192
+ const result = await gatewayCall<unknown>(this.socketPath, "/attachment", batch, {
193
+ ...this.options(), signal, timeoutMs: 30_000 * Math.min(batch.attachments.length, 10) + 1000,
233
194
  });
234
- incoming.on("error", error => bounded.destroy(error));
235
- incoming.on("aborted", () => bounded.destroy(new Error("Attachment stream was interrupted")));
236
- bounded.on("close", () => incoming.destroy());
237
- incoming.pipe(bounded);
238
- const headers = new Headers();
239
- const contentType = incoming.headers["content-type"];
240
- const contentLength = incoming.headers["x-gateway-attachment-length"];
241
- if (typeof contentType === "string") headers.set("content-type", contentType);
242
- if (typeof contentLength === "string") headers.set("content-length", contentLength);
243
- return new Response(Readable.toWeb(bounded) as ReadableStream<Uint8Array>, { status: incoming.statusCode ?? 502, headers });
195
+ return parseInboundAttachmentReceipt(this.socketPath, batch, result);
244
196
  }
245
197
 
246
198
  async stop(): Promise<void> {
@@ -1,13 +1,16 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { request, type IncomingMessage } from "node:http";
2
3
  import { existsSync } from "node:fs";
3
- import { lstat } from "node:fs/promises";
4
+ import { lstat, realpath } from "node:fs/promises";
4
5
  import { dirname, join } from "node:path";
5
6
  import type { Config } from "./config";
7
+ import type { InboundAttachmentBatch, InboundAttachmentReceipt } from "./contracts";
6
8
  import { DeliveryError } from "./delivery";
7
9
  import type { GatewayStatus } from "./gateway-wire";
8
10
 
9
11
  export const MAX_GATEWAY_FRAME = 16 * 1024 * 1024;
10
12
  export const MAX_GATEWAY_ATTACHMENT = 20 * 1024 * 1024;
13
+ export const MAX_GATEWAY_ATTACHMENT_BATCH = 40 * 1024 * 1024;
11
14
  export interface GatewayResult { ok: boolean; value?: unknown; error?: string; certainty?: "rejected" | "uncertain"; retryAfterMs?: number }
12
15
 
13
16
  export function gatewayPaths(config: Pick<Config, "stateDir">) {
@@ -83,3 +86,34 @@ export async function gatewayCall<T>(socketPath: string, endpoint: string, body?
83
86
  if (!result.ok) throw new DeliveryError(result.error ?? "Gateway rejected operation", result.certainty ?? "uncertain", result.retryAfterMs);
84
87
  return result.value as T;
85
88
  }
89
+
90
+ /** A spool reply carries only correctly indexed local references, never attachment bytes. */
91
+ export async function parseInboundAttachmentReceipt(
92
+ socketPath: string, batch: InboundAttachmentBatch, value: unknown,
93
+ ): Promise<InboundAttachmentReceipt> {
94
+ const invalid = () => new DeliveryError("Invalid attachment spool receipt", "uncertain");
95
+ if (!value || typeof value !== "object" || !("receipt" in value) || !("files" in value)
96
+ || typeof value.receipt !== "string" || !/^[a-f0-9]{64}$/.test(value.receipt)
97
+ || !Array.isArray(value.files) || value.files.length !== batch.attachments.length) throw invalid();
98
+ const directory = join(await realpath(dirname(dirname(socketPath))), "attachments", value.receipt);
99
+ const digest = createHash("sha256").update(createHash("sha256").update(batch.inputId).digest());
100
+ let total = 0;
101
+ const files: InboundAttachmentReceipt["files"][number][] = [];
102
+ for (const [index, attachment] of batch.attachments.entries()) {
103
+ const file: unknown = value.files[index];
104
+ if (!file || typeof file !== "object" || !("path" in file) || !("size" in file) || !("mimeType" in file)
105
+ || file.path !== join(directory, String(index)) || typeof file.size !== "number"
106
+ || !Number.isSafeInteger(file.size) || file.size < 0 || file.size > MAX_GATEWAY_ATTACHMENT
107
+ || (attachment.size !== null && file.size !== attachment.size)
108
+ || !("sha256" in file) || typeof file.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(file.sha256)
109
+ || typeof file.mimeType !== "string"
110
+ || !["application/octet-stream", "image/png", "image/jpeg", "image/gif", "image/webp"].includes(file.mimeType))
111
+ throw invalid();
112
+ total += file.size;
113
+ if (total > MAX_GATEWAY_ATTACHMENT_BATCH) throw invalid();
114
+ digest.update(Buffer.from(file.sha256, "hex"));
115
+ files.push({ path: file.path, size: file.size, mimeType: file.mimeType, sha256: file.sha256 });
116
+ }
117
+ if (digest.digest("hex") !== value.receipt) throw invalid();
118
+ return { receipt: value.receipt, files };
119
+ }