omp-superagent 0.1.7 → 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 (122) hide show
  1. package/DESIGN.md +27 -16
  2. package/README.ko.md +40 -19
  3. package/README.md +43 -18
  4. package/THIRD_PARTY_NOTICES.md +11 -11
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +285 -85
  7. package/docs/design/execution.md +133 -24
  8. package/docs/design/messaging.md +235 -50
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/docs/releases/0.1.9.md +18 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  24. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  32. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  44. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  56. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  57. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  58. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  60. package/package.json +17 -15
  61. package/skills/head/SKILL.md +3 -11
  62. package/skills/head/references/routing.md +23 -17
  63. package/skills/head/references/supervision.md +13 -1
  64. package/skills/lane/references/workflow.md +8 -8
  65. package/src/cli.ts +6 -3
  66. package/src/config.ts +5 -0
  67. package/src/contracts.ts +95 -10
  68. package/src/cron-jobs.ts +443 -19
  69. package/src/cron-pr-intake.ts +257 -0
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +31 -3
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-quota.ts +80 -0
  75. package/src/head-recovery.ts +249 -1
  76. package/src/host-extension.ts +194 -5
  77. package/src/host-protocol.ts +16 -9
  78. package/src/host-sdk-helper.ts +105 -10
  79. package/src/host.ts +111 -29
  80. package/src/installed-omp.ts +116 -4
  81. package/src/lane-models.ts +8 -0
  82. package/src/managed-ulw-probe.ts +22 -20
  83. package/src/managed-ulw.ts +137 -24
  84. package/src/messenger-command-catalog.json +6 -3
  85. package/src/messenger-commands.ts +9 -2
  86. package/src/native-presets.ts +32 -5
  87. package/src/omp-usage.ts +254 -36
  88. package/src/operator.ts +77 -0
  89. package/src/pr-github-schema.ts +2 -0
  90. package/src/pr-github.ts +4 -2
  91. package/src/pr-intake-automation.ts +315 -0
  92. package/src/pr-intake-comment.ts +225 -0
  93. package/src/pr-intake-fix.ts +232 -0
  94. package/src/pr-intake-github.ts +479 -0
  95. package/src/pr-intake-material.ts +229 -0
  96. package/src/pr-intake-mode.ts +59 -0
  97. package/src/pr-intake-review.ts +397 -0
  98. package/src/pr-intake-tree.ts +68 -0
  99. package/src/pr-intake-work.ts +29 -0
  100. package/src/pr-review-models.ts +28 -0
  101. package/src/result-attachment.ts +60 -79
  102. package/src/runtime.ts +2968 -449
  103. package/src/setup-profiles.ts +26 -65
  104. package/src/slack-command-registration.ts +48 -197
  105. package/src/store.ts +507 -87
  106. package/src/superkit-skills.ts +22 -0
  107. package/src/telegram-command-languages.json +17 -0
  108. package/src/telegram-command-registration.ts +32 -134
  109. package/src/topic-history.ts +30 -17
  110. package/src/worker-bridge.ts +21 -0
  111. package/src/worker-enrollment.ts +2 -1
  112. package/src/worker-host.ts +0 -24
  113. package/src/worker-serve-prepare.ts +19 -0
  114. package/src/worker-service.ts +51 -47
  115. package/scripts/ci.ts +0 -44
  116. package/scripts/release.ts +0 -112
  117. package/scripts/test-omp.sh +0 -43
  118. package/src/discord-commands.ts +0 -29
  119. package/src/discord-markdown.ts +0 -172
  120. package/src/slack-commands.ts +0 -18
  121. package/src/telegram-signal.ts +0 -14
  122. package/src/worker-stdio.ts +0 -61
@@ -0,0 +1,257 @@
1
+ import { Type, type Static } from "@sinclair/typebox/type";
2
+ import { Value } from "@sinclair/typebox/value";
3
+ import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "./contracts";
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";
8
+
9
+ const offerPrefix = "cron-pr:offer:";
10
+ const githubId = Type.Readonly(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }));
11
+ const identitySchema = Type.Object({ repositoryId: githubId, ownerId: githubId });
12
+ const pullSchema = Type.Object({
13
+ number: Type.Readonly(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER })),
14
+ head: Type.Readonly(Type.String({ pattern: "^[0-9a-fA-F]{40}$" })),
15
+ author: Type.Readonly(Type.String({ minLength: 1 })),
16
+ createdAt: Type.Readonly(Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })),
17
+ });
18
+ const candidateSchema = Type.Object({
19
+ ...pullSchema.properties,
20
+ ...identitySchema.properties,
21
+ jobId: Type.Readonly(Type.String()),
22
+ outputId: Type.Readonly(Type.String()),
23
+ epoch: Type.Readonly(Type.String()),
24
+ policyRevision: Type.Optional(Type.Readonly(Type.String())),
25
+ });
26
+ const offerSchema = Type.Object({
27
+ ...candidateSchema.properties,
28
+ claimedBy: Type.Readonly(Type.Union([Type.String(), Type.Null()])),
29
+ });
30
+ const ledgerSchema = Type.Object({ identity: identitySchema, candidates: Type.Array(offerSchema) });
31
+ const resultSchema = Type.Object({
32
+ ...identitySchema.properties, self: Type.String({ minLength: 1 }), pulls: Type.Array(pullSchema),
33
+ });
34
+
35
+ type RepositoryIdentity = Static<typeof identitySchema>;
36
+ type Offer = Static<typeof offerSchema>;
37
+ export type CronPrCandidate = Static<typeof candidateSchema>;
38
+ export interface IntakeScan {
39
+ readonly job: CronPrJob;
40
+ readonly entries: readonly { candidate: CronPrCandidate; head: string | null }[];
41
+ }
42
+ export type ReadIntakePulls = (repository: string, signal: AbortSignal) => Promise<RepositoryIdentity & {
43
+ readonly self: string;
44
+ readonly pulls: readonly Static<typeof pullSchema>[];
45
+ }>;
46
+
47
+ class CronPrIntakeError extends Error {}
48
+
49
+ export function normalizeIntakeRepository(input: string): string | null {
50
+ try {
51
+ const { owner, repo } = parsePrRef(`${input}#1`);
52
+ return `${owner}/${repo}`;
53
+ } catch (error) {
54
+ if (error instanceof PrReadError && error.reason === "reference") return null;
55
+ throw error;
56
+ }
57
+ }
58
+
59
+ export function isPrIntakeOffer(outputId: string): boolean {
60
+ return outputId.startsWith(offerPrefix);
61
+ }
62
+
63
+ function ledgerKey(repository: string): string { return `cron-pr:ledger:${repository}`; }
64
+ function outcomeKey(runId: string): string { return `cron-pr:outcome:${runId}`; }
65
+
66
+ function ledger(store: StorePort, repository: string): Static<typeof ledgerSchema> | null {
67
+ const raw = store.getMeta(ledgerKey(repository));
68
+ if (raw === null) return null;
69
+ const parsed: unknown = JSON.parse(raw);
70
+ if (!Value.Check(ledgerSchema, parsed)) throw new CronPrIntakeError("Damaged PR intake offer ledger.");
71
+ return parsed;
72
+ }
73
+
74
+ function sameIdentity(left: RepositoryIdentity, right: RepositoryIdentity): boolean {
75
+ return left.repositoryId === right.repositoryId && left.ownerId === right.ownerId;
76
+ }
77
+
78
+ function action(candidate: CronPrCandidate): string {
79
+ return `/cron pr-review ${candidate.jobId} ${candidate.number} ${candidate.head}`;
80
+ }
81
+
82
+ function offerText(repository: string, candidate: CronPrCandidate): string {
83
+ if (candidate.policyRevision) return `${repository}#${candidate.number} — 새 외부 PR (${candidate.head}). 등록한 단계에 따라 이 메시지에 전용 검토 스레드를 엽니다. 상태: /cron show ${candidate.jobId} ${candidate.number}\n수동 검토:\n${action(candidate)}`;
84
+ return `New external pull request: ${repository}#${candidate.number}. `
85
+ + `The following owner command starts a read-only review; it does not merge or change the pull request.\n\n${action(candidate)}`;
86
+ }
87
+
88
+ export function describePrIntake(store: StorePort, job: CronPrJob, number: number | null): string {
89
+ const candidates = ledger(store, job.repository)?.candidates.filter(candidate => candidate.jobId === job.id) ?? [];
90
+ const summary = job.lastRunId ? store.getMeta(outcomeKey(job.lastRunId)) : null;
91
+ const newest = [...candidates].reverse();
92
+ const selected = number === null ? newest.slice(0, 10) : newest.filter(candidate => candidate.number === number);
93
+ const open = !job.paused && !job.removed && job.stopBoundary === store.getMeta("head:stop-boundary");
94
+ const lines = selected.map(candidate => {
95
+ const status = candidate.claimedBy !== null
96
+ ? store.output(candidate.outputId)?.state ?? "not queued; no automatic replay"
97
+ : candidate.epoch === job.epoch && open
98
+ ? "deferred; up to one offer per scan" : "deferred offer suppressed; manual review only";
99
+ const progress = store.getMeta(intakeStatusKey(job.id, candidate.number));
100
+ return `${action(candidate)} (${status})${progress ? ` — ${progress}` : ""}`;
101
+ });
102
+ return [
103
+ summary,
104
+ lines.length ? `Recorded PR offers:\n${lines.join("\n")}` : "No matching PR offers recorded.",
105
+ number === null && newest.length > selected.length ? `Showing the latest ${selected.length} of ${newest.length}; use /cron show ${job.id} PR_NUMBER for an older offer.` : null,
106
+ ].filter(Boolean).join("\n");
107
+ }
108
+
109
+ /** Read-only controller: no native prompts, synthetic owner inputs, or PR actions. */
110
+ export class CronPrIntake {
111
+ private readonly fetching = new Map<string, { readonly input: InputRecord; readonly abort: AbortController }>();
112
+
113
+ constructor(
114
+ private readonly store: StorePort,
115
+ private readonly jobs: CronJobs,
116
+ private readonly readIntakePulls: ReadIntakePulls,
117
+ ) {}
118
+
119
+ cancelInactive(): void {
120
+ for (const { input, abort } of this.fetching.values()) {
121
+ if (!this.jobs.pendingPrRun(input)) abort.abort();
122
+ }
123
+ }
124
+
125
+ candidate(job: CronPrJob, number: number): CronPrCandidate | null {
126
+ const saved = ledger(this.store, job.repository);
127
+ if (!saved) return null;
128
+ return saved.candidates.find(candidate => candidate.jobId === job.id && candidate.number === number
129
+ && sameIdentity(saved.identity, candidate)) ?? null;
130
+ }
131
+
132
+ canDeliver(output: OutputRecord): boolean {
133
+ if (!isPrIntakeOffer(output.id)) return false;
134
+ const [repository, number, extra] = output.id.slice(offerPrefix.length).split(":");
135
+ if (!repository || normalizeIntakeRepository(repository) !== repository || !number || extra !== undefined) return false;
136
+ const saved = ledger(this.store, repository);
137
+ if (!saved) return false;
138
+ const candidate = saved.candidates.find(item => item.outputId === output.id && item.claimedBy !== null && sameIdentity(saved.identity, item));
139
+ if (!candidate) return false;
140
+ const active = this.jobs.activePrEnrollment(candidate.jobId);
141
+ return active !== null && active.job.repository === repository && candidate.epoch === active.job.epoch
142
+ && output.sourceId === active.source.id && routeKey(output.route) === routeKey(active.source.route)
143
+ && output.text === offerText(repository, candidate);
144
+ }
145
+
146
+ async consume(input: InputRecord, signal: AbortSignal): Promise<IntakeScan | undefined> {
147
+ if (signal.aborted || this.fetching.has(input.id) || input.state !== "pending" || !this.jobs.isPrIntakeRun(input)) return;
148
+ const enrollment = this.jobs.pendingPrRun(input);
149
+ if (!enrollment) {
150
+ if (!this.store.getMeta("head:restart-fence")) this.store.settle(input.id, "cancelled");
151
+ return;
152
+ }
153
+ const abort = new AbortController();
154
+ const workSignal = AbortSignal.any([signal, abort.signal]);
155
+ this.fetching.set(input.id, { input, abort });
156
+ try {
157
+ const result = await this.read(enrollment.job.repository, workSignal);
158
+ // In-flight work is not authority: pause/removal, stop, replacement, or
159
+ // the loss of the original authenticated source can all revoke this receipt.
160
+ if (workSignal.aborted) return;
161
+ const current = this.jobs.pendingPrRun(input);
162
+ if (!current || current.job.epoch !== enrollment.job.epoch) {
163
+ if (!this.store.getMeta("head:restart-fence")) this.store.settle(input.id, "cancelled");
164
+ return;
165
+ }
166
+ if (result === null) {
167
+ this.finish(input.id, "GitHub lookup failed; no new offers were made.", "cancelled");
168
+ return;
169
+ }
170
+ const self = result.self.toLowerCase();
171
+ if (!current.job.repository.startsWith(`${self}/`)) {
172
+ this.finish(input.id, "Authenticated GitHub account does not match the repository owner; no new offers were made.", "cancelled");
173
+ return;
174
+ }
175
+ const saved = ledger(this.store, current.job.repository);
176
+ if (saved && !sameIdentity(saved.identity, result)) {
177
+ this.finish(input.id, "GitHub repository or owner identity changed; no new offers were made.", "cancelled");
178
+ return;
179
+ }
180
+ const identity = { repositoryId: result.repositoryId, ownerId: result.ownerId };
181
+ const policy = this.jobs.prPolicy(current.job.id);
182
+ const prior = saved?.candidates ?? [];
183
+ const seen = new Set(prior.map(candidate => candidate.number));
184
+ const observed = new Map<number, string>();
185
+ const added: Offer[] = [];
186
+ for (const pull of result.pulls) {
187
+ if (pull.author.toLowerCase() === self || pull.createdAt <= current.job.eligibleAfter || observed.has(pull.number)) continue;
188
+ const head = pull.head.toLowerCase();
189
+ observed.set(pull.number, head);
190
+ if (seen.has(pull.number)) continue;
191
+ added.push({
192
+ number: pull.number, head, author: pull.author, createdAt: pull.createdAt, claimedBy: null,
193
+ ...identity, jobId: current.job.id, epoch: current.job.epoch,
194
+ ...(policy ? { policyRevision: policy.revision } : {}),
195
+ outputId: `${offerPrefix}${current.job.repository}:${pull.number}`,
196
+ });
197
+ }
198
+ const candidates = [...prior, ...added];
199
+ let chosen: Offer | undefined;
200
+ let chosenIndex = -1;
201
+ // The run's claim consumes its one slot even if the process died before
202
+ // queueing. Old-epoch/closed candidates remain inspectable. An unclaimed
203
+ // offer gets its currently observed SHA, so pushes during the backlog
204
+ // do not make an otherwise eligible PR permanently unannouncable.
205
+ if (!prior.some(candidate => candidate.claimedBy === input.id)) {
206
+ for (const [index, candidate] of candidates.entries()) {
207
+ const head = observed.get(candidate.number);
208
+ if (candidate.claimedBy !== null || candidate.jobId !== current.job.id || candidate.epoch !== current.job.epoch
209
+ || head === undefined) continue;
210
+ if (!chosen || candidate.createdAt < chosen.createdAt
211
+ || candidate.createdAt === chosen.createdAt && candidate.number < chosen.number) {
212
+ chosenIndex = index;
213
+ chosen = { ...candidate, head };
214
+ }
215
+ }
216
+ }
217
+ if (chosen) candidates[chosenIndex] = { ...chosen, claimedBy: input.id };
218
+ if (!saved || added.length || chosen) {
219
+ // Commit discovery and claim together before touching the outbox. A
220
+ // non-retryable claim is distinct from deferred discovery.
221
+ this.store.setMeta(ledgerKey(current.job.repository), JSON.stringify({ identity, candidates }));
222
+ }
223
+ if (chosen) {
224
+ try {
225
+ this.store.queueOutput({
226
+ id: chosen.outputId, sourceId: current.source.id, route: current.source.route,
227
+ text: offerText(current.job.repository, chosen),
228
+ });
229
+ } catch (error) {
230
+ this.finish(input.id, "The PR offer was claimed but outbox creation was interrupted; inspect the recorded status.", "cancelled");
231
+ throw error;
232
+ }
233
+ }
234
+ this.finish(input.id, `GitHub lookup recorded ${added.length} new PR candidates; ${chosen ? "one offer queued" : "no offer queued"}.`, "done");
235
+ return { job: current.job, entries: candidates.flatMap(candidate =>
236
+ candidate.jobId === current.job.id && candidate.epoch === current.job.epoch && candidate.claimedBy !== null
237
+ && candidate.policyRevision ? [{ candidate, head: observed.get(candidate.number) ?? null }] : []) };
238
+ } finally {
239
+ this.fetching.delete(input.id);
240
+ }
241
+ }
242
+
243
+ private async read(repository: string, signal: AbortSignal) {
244
+ try {
245
+ const snapshot: unknown = await this.readIntakePulls(repository, signal);
246
+ return Value.Check(resultSchema, snapshot) ? snapshot : null;
247
+ } catch (error) {
248
+ if (error instanceof Error) return null;
249
+ throw error;
250
+ }
251
+ }
252
+
253
+ private finish(runId: string, note: string, state: "done" | "cancelled"): void {
254
+ this.store.setMeta(outcomeKey(runId), note);
255
+ this.store.settle(runId, state);
256
+ }
257
+ }
@@ -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
@@ -12,12 +12,14 @@ import { lanePlacement } from "./lane-rows";
12
12
  import { sameLaneModel } from "./lane-models";
13
13
  import { NativePresetManager } from "./native-presets";
14
14
  import { publishNativeSession } from "./native-sessions";
15
+ import { isPrReviewLane } from "./pr-intake-review";
15
16
  import { MODEL_PRESET_NAMES, WORKFLOW_NAMES } from "./contracts";
16
17
  import type { PrWatchCommand } from "./pr-watch";
17
18
  import type { LaneWatchCommand } from "./lane-watch";
18
19
  import { registerDecisionAsk } from "./decision-tool";
19
20
  import { registerResultAttach, RESULT_ATTACH_TOOL } from "./result-attachment";
20
21
  import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, type RotationGuardEvent, type RotationProbeEvent } from "./head-rotation";
22
+ import { readHeadQuota } from "./head-quota";
21
23
 
22
24
  // Inject the role contract, not the references. Resolve the reference directory
23
25
  // from this package so a same-name workspace skill cannot change the procedure.
@@ -125,6 +127,22 @@ export default function superagentExtension(pi: ExtensionAPI): void {
125
127
  pi.on("tool_call", (event, ctx) => {
126
128
  if (runtime?.prObservationActive())
127
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
+ }
128
146
  if (event.toolName === "lane_watch" && ctx.agent.kind !== "main")
129
147
  return { block: true, reason: "Lane watches are restricted to the main superagent head" };
130
148
  if (event.toolName === "head_recovery" && ctx.agent.kind !== "main")
@@ -266,7 +284,11 @@ export default function superagentExtension(pi: ExtensionAPI): void {
266
284
  }))])), { minProperties: 1, additionalProperties: false }),
267
285
  }),
268
286
  async execute(_id, params, _signal, _onUpdate, ctx) {
269
- 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));
270
292
  },
271
293
  });
272
294
  pi.registerTool({
@@ -436,7 +458,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
436
458
  });
437
459
  pi.registerTool({
438
460
  name: "lane_message", label: "Message independent work", approval: "exec",
439
- 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.",
440
462
  parameters: Type.Object({ id: Type.String(), text: Type.String(), sourceId: Type.String(), workflow: workflowSchema }),
441
463
  async execute(_id, params, _signal, _onUpdate, ctx) {
442
464
  return result(await requireRuntime(ctx).messageLane(params.id, params.text, params.sourceId, params.workflow));
@@ -486,7 +508,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
486
508
  let messenger: ReturnType<typeof createGatewayMessenger>;
487
509
  try {
488
510
  for (const lane of store.lanes()) {
489
- if (lane.remote || !lane.sessionId) continue;
511
+ if (lane.remote || !lane.sessionId || isPrReviewLane(store, lane.id)) continue;
490
512
  const { sessionFile } = hostPaths(config, lane.id);
491
513
  if (lane.sessionFile !== sessionFile) throw new Error("Refusing to publish a lane outside its managed session path");
492
514
  await publishNativeSession(sessionFile, lane.cwd, lane.sessionId);
@@ -500,9 +522,15 @@ export default function superagentExtension(pi: ExtensionAPI): void {
500
522
  pi.logger.error(`Superagent: ${error instanceof Error ? error.message : String(error)}`);
501
523
  }, {
502
524
  topicMemory: ctx.memory,
525
+ readHeadQuota: (failure, sessionId, signal) => {
526
+ const session = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID)?.session;
527
+ return session instanceof pi.pi.AgentSession && session.sessionId === sessionId
528
+ ? readHeadQuota(session, failure, signal) : Promise.resolve(false);
529
+ },
503
530
  resolvePreset: async (name, thinkingContext) => (await nativePresets(ctx)).resolve(name, thinkingContext),
504
531
  inspectPresets: async () => (await nativePresets(ctx)).inspect(),
505
532
  syncPresetRoles: async canWrite => (await nativePresets(ctx)).syncRoles(store, canWrite, () => ctx.modelRegistry.refresh("offline")),
533
+ presetRolePaths: async () => (await nativePresets(ctx)).watchedPaths(),
506
534
  persistPreset: async selection => (await nativePresets(ctx)).persistSelection(selection),
507
535
  reapHeadJobs: async ({ sessionId, sessionFile }) => {
508
536
  const root = pi.pi.AgentRegistry.global().get(pi.pi.MAIN_AGENT_ID);