superagent-skill 0.4.2 → 0.5.1

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.
package/lib/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as reasonText, D as key, L as runningAssignment, N as latestReport, a as readSettings, b as directionAllowed, c as AGENT_NAMES, g as readState, h as FileRepositories, l as installed, m as runProcess, o as stringifyYaml, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor, v as RuleAssessmentSchema, x as Engine, z as threadKey } from "./settings-Dud0f9wo.mjs";
1
+ import { C as reasonText, D as key, L as runningAssignment, N as latestReport, a as readSettings, b as directionAllowed, c as AGENT_NAMES, g as readState, h as FileRepositories, l as installed, m as runProcess, o as stringifyYaml, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor, v as RuleAssessmentSchema, x as Engine, z as threadKey } from "./settings-BwRUbWkx.mjs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { access, appendFile, lstat, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
@@ -20,6 +20,7 @@ const MARKER = "# Written by superagent on every start; edits are lost.";
20
20
  /** Commands the shims provide, which a blocked list must never shadow. */
21
21
  const WORKER_COMMANDS = [
22
22
  "gh",
23
+ "glab",
23
24
  "git",
24
25
  "lark-cli"
25
26
  ];
@@ -71,9 +72,10 @@ async function writeEnvironment(accounts, blockedCommands) {
71
72
  ].join("\n");
72
73
  const run = (program) => `${withoutShims}\nexec ${shellQuote(program)} "$@"`;
73
74
  const fail = (message) => `echo ${shellQuote(message)} >&2\nexit 1`;
74
- await shim("gh", run(accounts.githubCli));
75
+ await shim("gh", accounts.githubCli ? run(accounts.githubCli) : fail("gh is unavailable: this installation has no GitHub Source."));
76
+ await shim("glab", accounts.gitlabCli ? run(accounts.gitlabCli) : fail("glab is unavailable: this installation has no GitLab Source."));
75
77
  await shim("lark-cli", accounts.feishuCli ? run(accounts.feishuCli) : fail("lark-cli is unavailable: this installation has no Feishu bot."));
76
- for (const name of new Set(blockedCommands.filter((name) => !WORKER_COMMANDS.includes(name)))) await shim(name, fail(`${name} is blocked in this installation; use gh, which acts as ${accounts.agentLogin}.`));
78
+ for (const name of new Set(blockedCommands.filter((name) => !WORKER_COMMANDS.includes(name)))) await shim(name, fail(`${name} is blocked in this installation${accounts.agentLogin ? `; work as ${accounts.agentLogin}` : ""}.`));
77
79
  for (const name of before) if (!kept.has(name)) await unlink(join(dir, name));
78
80
  await own(workerGitConfig(accounts.stateDir), [
79
81
  MARKER,
@@ -81,11 +83,20 @@ async function writeEnvironment(accounts, blockedCommands) {
81
83
  " useConfigOnly = true",
82
84
  "[credential]",
83
85
  " helper =",
84
- "[credential \"https://github.com\"]",
85
- `\thelper = ${gitQuote(credentialHelper(accounts.githubCli))}`,
86
- "[url \"https://github.com/\"]",
87
- " insteadOf = git@github.com:",
88
- " insteadOf = ssh://git@github.com:",
86
+ ...accounts.gitlabCli && accounts.gitlabHost ? [
87
+ `[credential "https://${accounts.gitlabHost}"]`,
88
+ `\thelper = ${gitQuote(credentialHelper(accounts.gitlabCli))}`,
89
+ `[url "https://${accounts.gitlabHost}/"]`,
90
+ `\tinsteadOf = git@${accounts.gitlabHost}:`,
91
+ `\tinsteadOf = ssh://git@${accounts.gitlabHost}:`
92
+ ] : [],
93
+ ...accounts.githubCli ? [
94
+ "[credential \"https://github.com\"]",
95
+ `\thelper = ${gitQuote(credentialHelper(accounts.githubCli))}`,
96
+ "[url \"https://github.com/\"]",
97
+ " insteadOf = git@github.com:",
98
+ " insteadOf = ssh://git@github.com:"
99
+ ] : [],
89
100
  "[filter \"lfs\"]",
90
101
  " clean = git-lfs clean -- %f",
91
102
  " smudge = git-lfs smudge -- %f",
@@ -169,18 +180,31 @@ const STANDING_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "prompt
169
180
  async function standingRules() {
170
181
  return Promise.all(STANDING_FILES.map(async (name) => (await readFile(join(STANDING_DIR, name), "utf8")).trim()));
171
182
  }
172
- /** Composes the prompt for reviewing and verifying a pull request. */
183
+ /** The forge's own words, so a GitLab ticket is not told to open a pull request. */
184
+ const forgeWords = (source) => source === "gitlab" ? {
185
+ name: "GitLab",
186
+ request: "merge request",
187
+ Request: "Merge Request",
188
+ short: "MR"
189
+ } : {
190
+ name: "GitHub",
191
+ request: "pull request",
192
+ Request: "Pull Request",
193
+ short: "PR"
194
+ };
195
+ /** Composes the prompt for reviewing and verifying a pull request or a merge request. */
173
196
  function composePrReviewPrompt(input) {
174
197
  const { ticket, trigger, repository, agentLogin, instructions, standing = [], notes = [], prNumber, prVerification, autoMergeAllowed } = input;
175
- const asked = trigger ? `Pull Request #${prNumber} details:\n\n${quote(trigger.text)}` : `Pull Request #${prNumber} review:\n\n${quote(ticket.title)}`;
198
+ const words = forgeWords(input.source);
199
+ const asked = trigger ? `${words.Request} #${prNumber} details:\n\n${quote(trigger.text)}` : `${words.Request} #${prNumber} review:\n\n${quote(ticket.title)}`;
176
200
  return [
177
- `# Ticket ${ticket.id} — Pull Request #${prNumber} Review & Verification`,
201
+ `# Ticket ${ticket.id} — ${words.Request} #${prNumber} Review & Verification`,
178
202
  "",
179
- `You are reviewing Pull Request #${prNumber} on repository \`${repository}\`.`,
180
- `The PR's code has been checked out directly into this working directory.`,
181
- `Your GitHub account is \`${agentLogin}\`.`,
203
+ `You are reviewing ${words.Request} #${prNumber} on repository \`${repository}\`.`,
204
+ `The ${words.short}'s code has been checked out directly into this working directory.`,
205
+ `Your ${words.name} account is \`${agentLogin}\`.`,
182
206
  "",
183
- "## The Pull Request",
207
+ `## The ${words.Request}`,
184
208
  "",
185
209
  asked,
186
210
  ...notes.filter(Boolean).flatMap((note) => [
@@ -197,12 +221,12 @@ function composePrReviewPrompt(input) {
197
221
  "## Review Instructions & Standards",
198
222
  "",
199
223
  "- **Inspect Every Line**: Scrutinize the git diff and logic changes. Do not blindly trust community submissions.",
200
- "- **Zero Tolerance for AI Slop**: Many PRs are generated hastily by coding agents without testing. Ensure logic is sound, error handling is thorough, and no regressions are introduced.",
201
- ...prVerification && !prVerification.passed ? ["- ⚠️ **CRITICAL: Local automated verification has FAILED.** You MUST NOT approve or merge this PR. Clearly point out the failure logs and what the author needs to fix."] : [],
224
+ "- **Zero Tolerance for AI Slop**: Many requests are generated hastily by coding agents without testing. Ensure logic is sound, error handling is thorough, and no regressions are introduced.",
225
+ ...prVerification && !prVerification.passed ? [`- ⚠️ **CRITICAL: Local automated verification has FAILED.** You MUST NOT approve or merge this ${words.request}. Clearly point out the failure logs and what the author needs to fix.`] : [],
202
226
  "- **Decision Standards**:",
203
227
  autoMergeAllowed && (!prVerification || prVerification.passed) ? " - Conclude your report with `DECISION: MERGE` ONLY if all automated checks passed AND your line-by-line review confirms the code is robust and bug-free." : " - Conclude your report with `DECISION: APPROVE` if all tests passed and the code is clean (human maintainer will merge).",
204
228
  " - Conclude your report with `DECISION: REQUEST_CHANGES` if tests failed, or if you found bugs, flaws, or missing tests.",
205
- " - Conclude your report with `DECISION: CLOSE` if the PR is spam, malicious, completely misguided, or unfixable.",
229
+ ` - Conclude your report with \`DECISION: CLOSE\` if the ${words.request} is spam, malicious, completely misguided, or unfixable.`,
206
230
  "",
207
231
  ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
208
232
  ...instructions.trim() ? [
@@ -218,11 +242,12 @@ function composePrReviewPrompt(input) {
218
242
  function composePrompt(input) {
219
243
  if (input.isPrReview && input.prNumber) return composePrReviewPrompt(input);
220
244
  const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch, standing = [], notes = [] } = input;
245
+ const words = forgeWords(source);
221
246
  const asked = trigger ? `A person wrote this in ${trigger.url ?? trigger.channel?.thread ?? "the source conversation"}:\n\n${quote(trigger.text)}` : `The ticket has no source message; work on the title alone:\n\n${quote(ticket.title)}`;
222
247
  return [
223
248
  `# Ticket ${ticket.id}`,
224
249
  "",
225
- ...source === "feishu" ? [`You work on the repository \`${repository}\`. The request came from a chat, which has no branch of its own, so open your`, "pull request from a new branch and say in your report where the person can find it."] : [`You work on the repository \`${repository}\`. Your GitHub account is \`${agentLogin}\`; every GitHub action you take is`, "visible to the team under that name."],
250
+ ...source === "feishu" ? [`You work on the repository \`${repository}\`. The request came from a chat, which has no branch of its own, so open your`, `${words.request} from a new branch and say in your report where the person can find it.`] : [`You work on the repository \`${repository}\`. Your ${words.name} account is \`${agentLogin}\`; every ${words.name} action you take is`, "visible to the team under that name."],
226
251
  "",
227
252
  "## The request",
228
253
  "",
@@ -237,9 +262,9 @@ function composePrompt(input) {
237
262
  "## How to work",
238
263
  "",
239
264
  `- Work only in this directory. It is a worktree of the repository on a new branch.`,
240
- branch ? `- Commit on the branch \`${branch}\`, which this directory is already on, and open a pull request from it when done.` : `- Put your branch under \`${branchPrefix}\` followed by a short name, and open a pull request from it when done.`,
265
+ branch ? `- Commit on the branch \`${branch}\`, which this directory is already on, and open a ${words.request} from it when done.` : `- Put your branch under \`${branchPrefix}\` followed by a short name, and open a ${words.request} from it when done.`,
241
266
  "- Run the tests the repository has. Do not claim a check passed unless you ran it.",
242
- "- Do not merge the pull request. A person merges it.",
267
+ `- Do not merge the ${words.request}. A person merges it.`,
243
268
  "- If the request needs a decision you cannot make, stop and ask one concrete question.",
244
269
  ...input.readOnly ? ["- Autonomous run mode: you may inspect, search, and run tests, but do NOT push commits or make permanent mutations.", "- If code changes or human decisions are required, report state as \"blocked\" and provide a \"question\" for human approval."] : [],
245
270
  ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
@@ -293,6 +318,26 @@ function sourceScope(settings) {
293
318
  observed: true
294
319
  };
295
320
  }
321
+ if (input.source === "gitlab") {
322
+ const gitlab = settings.gitlab;
323
+ if (!gitlab?.enabled) return {
324
+ listened: false,
325
+ reason: "sourceOff"
326
+ };
327
+ const project = input.meta.repository ?? gitlab.project;
328
+ if (!project) return {
329
+ listened: false,
330
+ reason: "unsupported"
331
+ };
332
+ if (project.toLowerCase() !== gitlab.project.toLowerCase()) return {
333
+ listened: false,
334
+ reason: "otherRepository"
335
+ };
336
+ return {
337
+ listened: true,
338
+ observed: Boolean(input.meta.isPr) && Boolean(gitlab.mrReview?.enabled)
339
+ };
340
+ }
296
341
  if (input.source !== "github") return {
297
342
  listened: false,
298
343
  reason: "unsupported"
@@ -320,7 +365,7 @@ function sourceScope(settings) {
320
365
  const UNASKED_RULE = "unasked";
321
366
  /** The Policy of one settings file, rebuilt whenever the round reads it. */
322
367
  function buildPolicy(settings, scope) {
323
- const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : source === "twitter" ? settings.twitter?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
368
+ const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : source === "twitter" ? settings.twitter?.allowed : source === "gitlab" ? settings.gitlab?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
324
369
  return {
325
370
  version: `${settings.policy.mode}:${settings.policy.rules.filter((rule) => rule.enabled).map((rule) => rule.id).join(",")}`,
326
371
  paused: false,
@@ -334,7 +379,10 @@ function buildPolicy(settings, scope) {
334
379
  cell: "listedUnaddressed"
335
380
  }
336
381
  };
337
- if (trigger.source === "github" && Boolean(trigger.meta?.isPr) && Boolean(settings.github?.prReview?.enabled) && settings.github?.prReview?.allowCommunityPrs !== false) {
382
+ const reviewEnabled = trigger.source === "gitlab" ? settings.gitlab?.mrReview?.enabled : trigger.source === "github" ? settings.github?.prReview?.enabled : false;
383
+ const isPrReview = Boolean(trigger.meta?.isPr) && Boolean(reviewEnabled);
384
+ const community = trigger.source === "gitlab" ? settings.gitlab?.mrReview?.allowCommunityMrs !== false : settings.github?.prReview?.allowCommunityPrs !== false;
385
+ if (isPrReview && community) {
338
386
  const addressed = !!trigger.addressed;
339
387
  const basis = addressed ? {
340
388
  via: "listed",
@@ -889,15 +937,15 @@ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
889
937
  * A notification only says that something mentioned the account. The comment itself is read afterwards, so the Trigger
890
938
  * carries what the person wrote, not the notification's summary.
891
939
  */
892
- const SOURCE$2 = "github";
940
+ const SOURCE$3 = "github";
893
941
  /** A thread identifier for an Issue or pull request number; both share one sequence in GitHub. */
894
942
  const githubThread = (number) => ({
895
- source: SOURCE$2,
943
+ source: SOURCE$3,
896
944
  id: String(number)
897
945
  });
898
946
  /** Where a reply to this number goes. */
899
947
  const githubChannel = (repository, number, url) => ({
900
- source: SOURCE$2,
948
+ source: SOURCE$3,
901
949
  thread: threadKey(githubThread(number)),
902
950
  address: {
903
951
  number: String(number),
@@ -972,10 +1020,10 @@ function commentTrigger(input) {
972
1020
  const login = comment.user.login;
973
1021
  return {
974
1022
  id: key("github-comment", url, String(comment.id ?? ""), at),
975
- source: SOURCE$2,
1023
+ source: SOURCE$3,
976
1024
  threads: [githubThread(number)],
977
1025
  actor: {
978
- source: SOURCE$2,
1026
+ source: SOURCE$3,
979
1027
  id: login
980
1028
  },
981
1029
  human: isHumanLogin(comment.user) && !sameName(login, agent),
@@ -1076,10 +1124,10 @@ async function pollOpenPullRequests(input) {
1076
1124
  const url = pr.url ?? githubPage(input.repository, pr.number, true);
1077
1125
  triggers.push({
1078
1126
  id: prKey,
1079
- source: SOURCE$2,
1127
+ source: SOURCE$3,
1080
1128
  threads: [githubThread(pr.number)],
1081
1129
  actor: {
1082
- source: SOURCE$2,
1130
+ source: SOURCE$3,
1083
1131
  id: pr.author.login
1084
1132
  },
1085
1133
  human: isHumanLogin(pr.author) && !sameName(pr.author.login, input.agent),
@@ -1101,6 +1149,247 @@ async function pollOpenPullRequests(input) {
1101
1149
  }
1102
1150
  return triggers;
1103
1151
  }
1152
+ // src/sources/gitlab.ts
1153
+ /**
1154
+ * The GitLab Source: turns to-do items addressed to the agent and open merge requests into Triggers.
1155
+ *
1156
+ * GitLab delivers a mention, a direct address or an assignment to the agent's account as a to-do item, so the poll reads
1157
+ * `/todos` rather than every note in the project. A to-do carries the note's text, its author and the issue or merge
1158
+ * request it sits on, so a second request is not needed to know what the person wrote.
1159
+ *
1160
+ * The same project path and host reach a self-managed GitLab: `glab --hostname` chooses the instance, and every URL this
1161
+ * module builds names that host rather than gitlab.com.
1162
+ */
1163
+ const SOURCE$2 = "gitlab";
1164
+ /** GitLab's API names a project by its URL-encoded namespace path, subgroups included. */
1165
+ const projectPath = (project) => encodeURIComponent(project);
1166
+ /** Web address of an issue or a merge request on the configured host. */
1167
+ const gitlabPage = (host, project, iid, mergeRequest = false) => `https://${host}/${project}/-/${mergeRequest ? "merge_requests" : "issues"}/${iid}`;
1168
+ /** A thread names its kind, because an issue and a merge request can share the same iid in one project. */
1169
+ const gitlabThread = (project, iid, mergeRequest = false) => ({
1170
+ source: SOURCE$2,
1171
+ id: `${project}${mergeRequest ? "!" : "#"}${iid}`
1172
+ });
1173
+ const gitlabChannel = (host, project, iid, kind, url) => ({
1174
+ source: SOURCE$2,
1175
+ thread: threadKey(gitlabThread(project, iid, kind === "merge_request")),
1176
+ address: {
1177
+ host,
1178
+ project,
1179
+ number: String(iid),
1180
+ kind,
1181
+ ...url ? { url } : {}
1182
+ }
1183
+ });
1184
+ /** True for an account GitLab reports as a bot rather than a person. */
1185
+ const isBot = (user) => user?.bot === true || /_bot(?:\b|_)/.test(user?.username ?? "") || /\[bot\]$/.test(user?.username ?? "");
1186
+ const PersonSchema = z.looseObject({
1187
+ username: z.string().nullish(),
1188
+ name: z.string().nullish(),
1189
+ bot: z.boolean().nullish()
1190
+ }).nullish().transform((user) => user ?? {
1191
+ username: "",
1192
+ name: null,
1193
+ bot: null
1194
+ });
1195
+ /** Actions that put a person's request in front of the agent. A build failure or an approval is not one. */
1196
+ const ADDRESSING = /* @__PURE__ */ new Set([
1197
+ "mentioned",
1198
+ "directly_addressed",
1199
+ "assigned",
1200
+ "review_requested"
1201
+ ]);
1202
+ z.looseObject({
1203
+ id: z.union([z.number(), z.string()]),
1204
+ action_name: z.string(),
1205
+ target_type: z.string(),
1206
+ author: PersonSchema,
1207
+ target: z.looseObject({
1208
+ iid: z.number().nullish(),
1209
+ title: z.string().nullish(),
1210
+ description: z.string().nullish(),
1211
+ web_url: z.string().nullish(),
1212
+ state: z.string().nullish()
1213
+ }).nullish(),
1214
+ project: z.looseObject({ path_with_namespace: z.string().nullish() }).nullish(),
1215
+ body: z.string().nullish(),
1216
+ target_url: z.string().nullish(),
1217
+ created_at: z.string().nullish(),
1218
+ updated_at: z.string().nullish()
1219
+ });
1220
+ /**
1221
+ * Builds a Trigger from one to-do item, or `undefined` when it names no issue or merge request.
1222
+ *
1223
+ * `mentioned` and `directly_addressed` mean the person wrote to the agent; `assigned` and `review_requested` mean the
1224
+ * agent was handed the item without a mention, which is still a request aimed at the agent and no one else.
1225
+ */
1226
+ function todoTrigger(input) {
1227
+ const { todo, host, project, agent } = input;
1228
+ const iid = todo.target?.iid;
1229
+ if (!iid) return void 0;
1230
+ const mergeRequest = todo.target_type === "MergeRequest";
1231
+ const kind = mergeRequest ? "merge_request" : "issue";
1232
+ const username = todo.author?.username ?? "";
1233
+ const text = [todo.target?.title?.trim() ?? "", todo.body?.trim() || todo.target?.description?.trim() || ""].filter(Boolean).join("\n\n") || "(the to-do carried no text)";
1234
+ const url = todo.target?.web_url ?? todo.target_url ?? gitlabPage(host, project, iid, mergeRequest);
1235
+ const at = todo.updated_at ?? todo.created_at ?? (/* @__PURE__ */ new Date()).toISOString();
1236
+ const addressing = ADDRESSING.has(todo.action_name);
1237
+ return {
1238
+ id: key("gitlab-todo", project, String(todo.id)),
1239
+ source: SOURCE$2,
1240
+ threads: [gitlabThread(project, iid, mergeRequest)],
1241
+ actor: {
1242
+ source: SOURCE$2,
1243
+ id: username
1244
+ },
1245
+ human: !isBot(todo.author) && !sameName(username, agent),
1246
+ ...addressing ? { addressed: /mentioned|directly_addressed/.test(todo.action_name) ? "mention" : "direct" } : {},
1247
+ at,
1248
+ text,
1249
+ url,
1250
+ channel: gitlabChannel(host, project, iid, kind, url),
1251
+ meta: {
1252
+ number: iid,
1253
+ isPr: mergeRequest,
1254
+ kind,
1255
+ repository: project,
1256
+ host,
1257
+ author: username,
1258
+ action: todo.action_name
1259
+ }
1260
+ };
1261
+ }
1262
+ z.looseObject({
1263
+ iid: z.number(),
1264
+ title: z.string(),
1265
+ description: z.string().nullish(),
1266
+ author: PersonSchema,
1267
+ updated_at: z.string().nullish(),
1268
+ web_url: z.string().nullish(),
1269
+ source_branch: z.string().nullish(),
1270
+ sha: z.string().nullish(),
1271
+ draft: z.boolean().nullish(),
1272
+ work_in_progress: z.boolean().nullish()
1273
+ });
1274
+ /** The username the CLI acts as on `host`, which the Trigger builder uses to tell the agent's own work apart. */
1275
+ async function gitlabLogin(cli, host, signal) {
1276
+ const user = await runJson(cli, apiArgs(host, "user"), { signal });
1277
+ if (!user.username) throw new Error(`${cli} api user named no username on ${host}`);
1278
+ return user.username;
1279
+ }
1280
+ /** One `glab api` call: the host is named every time, so a checkout cannot choose another GitLab by accident. */
1281
+ const apiArgs = (host, path, extra = []) => [
1282
+ "api",
1283
+ "--hostname",
1284
+ host,
1285
+ path,
1286
+ ...extra
1287
+ ];
1288
+ /**
1289
+ * Polls pending to-do items for the project and returns the Triggers not seen before.
1290
+ *
1291
+ * A to-do for another project is marked seen as well: the account may receive to-dos from everywhere, and only this
1292
+ * project's are this installation's work.
1293
+ */
1294
+ async function pollTodos(input) {
1295
+ const todos = await runJson(input.cli, apiArgs(input.host, "todos?state=pending&per_page=100"), { signal: input.signal });
1296
+ const triggers = [];
1297
+ for (const todo of todos) {
1298
+ const id = `gitlab:todo:${todo.id}`;
1299
+ if (input.seen(id)) continue;
1300
+ input.mark(id);
1301
+ if (!sameName(todo.project?.path_with_namespace ?? "", input.project)) continue;
1302
+ if (!ADDRESSING.has(todo.action_name)) continue;
1303
+ const username = todo.author?.username ?? "";
1304
+ if (isBot(todo.author) || sameName(username, input.agent)) continue;
1305
+ const trigger = todoTrigger({
1306
+ todo,
1307
+ host: input.host,
1308
+ project: input.project,
1309
+ agent: input.agent
1310
+ });
1311
+ if (trigger) triggers.push(trigger);
1312
+ }
1313
+ return triggers;
1314
+ }
1315
+ /**
1316
+ * Polls open merge requests and returns one Trigger per new or updated merge request.
1317
+ *
1318
+ * The key carries `updated_at`, so a push to the source branch asks for another review while an untouched merge request
1319
+ * is not reviewed twice.
1320
+ */
1321
+ async function pollOpenMergeRequests(input) {
1322
+ const mergeRequests = await runJson(input.cli, apiArgs(input.host, `projects/${projectPath(input.project)}/merge_requests?state=opened&per_page=100`), { signal: input.signal });
1323
+ const triggers = [];
1324
+ for (const mergeRequest of mergeRequests) {
1325
+ const author = mergeRequest.author?.username ?? "";
1326
+ if (isBot(mergeRequest.author) || sameName(author, input.agent)) continue;
1327
+ const at = mergeRequest.updated_at ?? (/* @__PURE__ */ new Date()).toISOString();
1328
+ const id = key("gitlab-mr-review", input.project, String(mergeRequest.iid), at);
1329
+ if (input.seen(id)) continue;
1330
+ input.mark(id);
1331
+ const url = mergeRequest.web_url ?? gitlabPage(input.host, input.project, mergeRequest.iid, true);
1332
+ triggers.push({
1333
+ id,
1334
+ source: SOURCE$2,
1335
+ threads: [gitlabThread(input.project, mergeRequest.iid, true)],
1336
+ actor: {
1337
+ source: SOURCE$2,
1338
+ id: author
1339
+ },
1340
+ human: true,
1341
+ addressed: "mention",
1342
+ at,
1343
+ text: `# Merge Request Review: !${mergeRequest.iid} ${mergeRequest.title}\n\nAuthor: @${author}\nURL: ${url}\n\n${mergeRequest.description ?? ""}`,
1344
+ channel: gitlabChannel(input.host, input.project, mergeRequest.iid, "merge_request", url),
1345
+ url,
1346
+ meta: {
1347
+ number: mergeRequest.iid,
1348
+ isPr: true,
1349
+ kind: "pull_review",
1350
+ repository: input.project,
1351
+ host: input.host,
1352
+ author,
1353
+ updatedAt: at
1354
+ }
1355
+ });
1356
+ }
1357
+ return triggers;
1358
+ }
1359
+ /** Posts a note on an issue or a merge request. */
1360
+ async function replyNote(input) {
1361
+ const kind = input.kind === "merge_request" ? "merge_requests" : "issues";
1362
+ await run(input.cli, apiArgs(input.host, `projects/${projectPath(input.project)}/${kind}/${input.iid}/notes`, [
1363
+ "--method",
1364
+ "POST",
1365
+ "--raw-field",
1366
+ `body=${input.body}`
1367
+ ]), { signal: input.signal });
1368
+ }
1369
+ /**
1370
+ * Merges a merge request, optionally only once its pipeline succeeds.
1371
+ *
1372
+ * GitLab decides whether a merge squashes by project settings, not per request, so `squash` asks for the project's
1373
+ * squash behaviour rather than naming a merge method.
1374
+ */
1375
+ async function mergeMergeRequest(input) {
1376
+ await run(input.cli, apiArgs(input.host, `projects/${projectPath(input.project)}/merge_requests/${input.iid}/merge`, [
1377
+ "--method",
1378
+ "PUT",
1379
+ "--field",
1380
+ `squash=${input.squash}`,
1381
+ ...input.autoMerge ? ["--field", "merge_when_pipeline_succeeds=true"] : []
1382
+ ]), { signal: input.signal });
1383
+ }
1384
+ /** Closes a merge request without merging it. */
1385
+ async function closeMergeRequest(input) {
1386
+ await run(input.cli, apiArgs(input.host, `projects/${projectPath(input.project)}/merge_requests/${input.iid}`, [
1387
+ "--method",
1388
+ "PUT",
1389
+ "--field",
1390
+ "state_event=close"
1391
+ ]), { signal: input.signal });
1392
+ }
1104
1393
  // src/sources/feishu.ts
1105
1394
  /**
1106
1395
  * The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
@@ -1534,7 +1823,7 @@ async function isGitRepository(directory) {
1534
1823
  }
1535
1824
  /**
1536
1825
  * Creates the worktree for a ticket and returns its directory.
1537
- * When `prNumber` is specified, fetches the PR branch/head and checks it out directly into the worktree.
1826
+ * When `prNumber` is specified, fetches the review's head and checks it out directly into the worktree.
1538
1827
  *
1539
1828
  * @throws when git cannot create the worktree, such as when the checkout has no commit yet; the caller then reports the
1540
1829
  * ticket as failed instead of starting an agent in a directory that is not the repository.
@@ -1545,6 +1834,8 @@ async function prepareWorktree(options) {
1545
1834
  if ((await readdir(directory)).length) return directory;
1546
1835
  if (!await isGitRepository(checkout)) return directory;
1547
1836
  if (prNumber) {
1837
+ const head = options.ref ?? `pull/${prNumber}/head`;
1838
+ const remote = options.remote ?? (repository ? `https://github.com/${repository}.git` : void 0);
1548
1839
  let fetched = false;
1549
1840
  try {
1550
1841
  await run("git", [
@@ -1552,20 +1843,20 @@ async function prepareWorktree(options) {
1552
1843
  checkout,
1553
1844
  "fetch",
1554
1845
  "origin",
1555
- `pull/${prNumber}/head:${branch}`
1846
+ `${head}:${branch}`
1556
1847
  ], {
1557
1848
  signal,
1558
1849
  timeoutMs: 6e4
1559
1850
  });
1560
1851
  fetched = true;
1561
1852
  } catch {
1562
- if (repository) try {
1853
+ if (remote) try {
1563
1854
  await run("git", [
1564
1855
  "-C",
1565
1856
  checkout,
1566
1857
  "fetch",
1567
- `https://github.com/${repository}.git`,
1568
- `pull/${prNumber}/head:${branch}`
1858
+ remote,
1859
+ `${head}:${branch}`
1569
1860
  ], {
1570
1861
  signal,
1571
1862
  timeoutMs: 6e4
@@ -1586,7 +1877,7 @@ async function prepareWorktree(options) {
1586
1877
  timeoutMs: 12e4
1587
1878
  }).catch(async (error) => {
1588
1879
  await removeWorktree(checkout, directory, signal, branch);
1589
- throw new Error(`${directory} is not a branch point for PR #${prNumber}: ${error.message}`, { cause: error });
1880
+ throw new Error(`${directory} is not a branch point for review #${prNumber}: ${error.message}`, { cause: error });
1590
1881
  });
1591
1882
  return directory;
1592
1883
  }
@@ -1719,12 +2010,11 @@ function deliver(engine, repo, delivered, log) {
1719
2010
  delivered.add(`${ticket.id}@${report.at}`);
1720
2011
  const text = deliverable(String(report.summary));
1721
2012
  try {
1722
- engine.reply({
2013
+ if (!engine.reply({
1723
2014
  purpose: "result",
1724
2015
  ticketId: ticket.id,
1725
2016
  text
1726
- });
1727
- log(`Answered ticket ${ticket.id} in its conversation`);
2017
+ }).reused) log(`Answered ticket ${ticket.id} in its conversation`);
1728
2018
  } catch (error) {
1729
2019
  log(`Could not answer ticket ${ticket.id}: ${error.message}`);
1730
2020
  }
@@ -1790,9 +2080,13 @@ function record(engine, repo, finished, log) {
1790
2080
  }
1791
2081
  }
1792
2082
  /** Posts the messages the Engine queued, one comment per message. */
1793
- async function send(channel, clis, log, attentionConfig) {
2083
+ async function send(channel, clis, log, attentionConfig, sent) {
1794
2084
  const quiet = isQuietHours(/* @__PURE__ */ new Date(), attentionConfig?.quietHours);
1795
2085
  const present = await isUserPresent(attentionConfig?.idleSecondsThreshold);
2086
+ const done = (message) => {
2087
+ channel.withdraw(message.id);
2088
+ sent?.(message.id);
2089
+ };
1796
2090
  for (const message of channel.drain()) {
1797
2091
  if (message.channel.source === "twitter") {
1798
2092
  const address = message.channel.address;
@@ -1804,6 +2098,7 @@ async function send(channel, clis, log, attentionConfig) {
1804
2098
  try {
1805
2099
  await replyTweet(clis.twitter, address.tweetUrl, message.text);
1806
2100
  log(`Replied to tweet ${address.tweetUrl}`);
2101
+ done(message);
1807
2102
  } catch (error) {
1808
2103
  log(`Could not reply to tweet ${address.tweetUrl}: ${error.message}`);
1809
2104
  }
@@ -1820,11 +2115,37 @@ async function send(channel, clis, log, attentionConfig) {
1820
2115
  else log(`User is away; dispatched notification to mobile in ${address.chatId}`);
1821
2116
  try {
1822
2117
  await reply(clis.feishu, address.messageId, message.text, message.id);
2118
+ done(message);
1823
2119
  } catch (error) {
1824
2120
  log(`Could not answer in ${address.chatId}: ${error.message}`);
1825
2121
  }
1826
2122
  continue;
1827
2123
  }
2124
+ if (message.channel.source === "gitlab") {
2125
+ const address = message.channel.address;
2126
+ if (!clis.gitlab) {
2127
+ log(`Cannot post on ${address.project}: the GitLab Source is off`);
2128
+ continue;
2129
+ }
2130
+ if (!address.project || !address.number) continue;
2131
+ const kind = address.kind === "merge_request" ? "merge_request" : "issue";
2132
+ const url = `${address.project}${kind === "merge_request" ? "!" : "#"}${address.number}`;
2133
+ try {
2134
+ await replyNote({
2135
+ cli: clis.gitlab.cli,
2136
+ host: address.host ?? clis.gitlab.host,
2137
+ project: address.project,
2138
+ iid: Number(address.number),
2139
+ kind,
2140
+ body: message.text
2141
+ });
2142
+ log(`Posted a note on ${url}`);
2143
+ done(message);
2144
+ } catch (error) {
2145
+ log(`Could not post on ${url}: ${error.message}`);
2146
+ }
2147
+ continue;
2148
+ }
1828
2149
  const address = message.channel.address;
1829
2150
  if (!address.number || !address.repository) continue;
1830
2151
  if (!clis.github) {
@@ -1839,6 +2160,7 @@ async function send(channel, clis, log, attentionConfig) {
1839
2160
  `body=${message.text}`
1840
2161
  ]);
1841
2162
  log(`Posted a message on ${address.repository}#${address.number}`);
2163
+ done(message);
1842
2164
  } catch (error) {
1843
2165
  log(`Could not post on ${address.repository}#${address.number}: ${error.message}`);
1844
2166
  }
@@ -1849,19 +2171,28 @@ const pollKey = "github:poll";
1849
2171
  const seenKey = (id) => `github:seen:${id}`;
1850
2172
  /** Lines one round reads from the stream at most, so a chat that keeps talking does not hold a round open. */
1851
2173
  const MAX_LINES = 500;
1852
- /** A failed save of the last round must not stop the next one. */
1853
- function outbox() {
2174
+ /**
2175
+ * The outbox of one run, plus the ids earlier runs already posted.
2176
+ *
2177
+ * A message goes out once, and a process that started later must know it: the id is deterministic
2178
+ * (`key('reply', triggerId, text)`), but the map alone forgets it at exit, so `poll --once` from cron re-posted every
2179
+ * ready report. The id of a posted message is kept in the state directory for the same reason the ticket is.
2180
+ */
2181
+ function outbox(repo) {
1854
2182
  const messages = /* @__PURE__ */ new Map();
2183
+ const sentKey = (id) => `outbox:${id}`;
2184
+ const sent = (id) => repo.getMeta(sentKey(id)) === true;
1855
2185
  return {
1856
2186
  send: (message) => {
1857
- if (!messages.has(message.id)) messages.set(message.id, message);
2187
+ if (!messages.has(message.id) && !sent(message.id)) messages.set(message.id, message);
1858
2188
  },
1859
- status: (id) => messages.has(id) ? "pending" : void 0,
2189
+ status: (id) => messages.has(id) ? "pending" : sent(id) ? "sent" : void 0,
1860
2190
  withdraw: (id) => {
1861
2191
  messages.delete(id);
1862
2192
  },
1863
- /** Everything queued so far, for the caller to deliver in order. */
1864
- drain: () => [...messages.values()].sort((a, b) => a.id.localeCompare(b.id))
2193
+ /** A caller posts what is waiting; the message stays until the post succeeds, so a failed one is retried next round. */
2194
+ drain: () => [...messages.values()].sort((a, b) => a.id.localeCompare(b.id)),
2195
+ sent
1865
2196
  };
1866
2197
  }
1867
2198
  /**
@@ -1931,11 +2262,13 @@ var AgentExecutor = class {
1931
2262
  });
1932
2263
  }
1933
2264
  async execute(ticket, assignment, controller) {
1934
- const { settings, runner, stateDir, accounts, feishuCli, site, repo, log } = this.options;
2265
+ const { settings, runner, stateDir, accounts, site, repo, log } = this.options;
1935
2266
  const directory = ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
1936
2267
  const trigger = repo?.triggers.get(ticket.origin.triggerId);
1937
2268
  const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
1938
2269
  const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
2270
+ const source = trigger?.source === "gitlab" ? "gitlab" : "github";
2271
+ const review = source === "gitlab" ? settings.gitlab?.mrReview : settings.github?.prReview;
1939
2272
  try {
1940
2273
  const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
1941
2274
  await prepareWorktree({
@@ -1943,7 +2276,11 @@ var AgentExecutor = class {
1943
2276
  directory,
1944
2277
  branch,
1945
2278
  prNumber: isPrReview ? prNumber : void 0,
1946
- repository: settings.github?.repository,
2279
+ repository: source === "gitlab" ? settings.gitlab?.project : settings.github?.repository,
2280
+ ...source === "gitlab" && settings.gitlab && prNumber !== void 0 ? {
2281
+ ref: `refs/merge-requests/${prNumber}/head`,
2282
+ remote: `https://${settings.gitlab.host}/${settings.gitlab.project}.git`
2283
+ } : {},
1947
2284
  signal: controller.signal
1948
2285
  });
1949
2286
  if (settings.executor.prepare) await run("/bin/sh", ["-c", settings.executor.prepare], {
@@ -1951,10 +2288,10 @@ var AgentExecutor = class {
1951
2288
  timeoutMs: 12e4
1952
2289
  });
1953
2290
  let prVerification;
1954
- if (isPrReview && settings.github?.prReview?.verifyCommands?.length) prVerification = await runPrVerification({
2291
+ if (isPrReview && review?.verifyCommands?.length) prVerification = await runPrVerification({
1955
2292
  cwd: directory,
1956
- commands: settings.github.prReview.verifyCommands,
1957
- timeoutSeconds: settings.github.prReview.verifyTimeoutSeconds,
2293
+ commands: review.verifyCommands,
2294
+ timeoutSeconds: review.verifyTimeoutSeconds,
1958
2295
  signal: controller.signal
1959
2296
  });
1960
2297
  const prompt = await this.options.prompt(ticket, directory, branch, prVerification);
@@ -1962,58 +2299,97 @@ var AgentExecutor = class {
1962
2299
  const result = await runner.run({
1963
2300
  prompt,
1964
2301
  cwd: directory,
1965
- env: runEnvironment(feishuCli ? {
1966
- ...accounts,
1967
- feishuCli
1968
- } : accounts, this.variables(ticket, directory, branch)),
2302
+ env: runEnvironment(accounts, this.variables(ticket, directory, branch)),
1969
2303
  signal: controller.signal,
1970
2304
  timeoutMs: settings.executor.timeoutMinutes * 6e4,
1971
2305
  model: settings.executor.model,
1972
2306
  readOnly: isAutonomous
1973
2307
  });
1974
2308
  const report = result.report ?? inferReport(result.finalText, result.ok);
1975
- if (isPrReview && prNumber && settings.github) {
2309
+ if (isPrReview && prNumber && review) {
1976
2310
  const textToAnalyze = `${result.finalText}\n${report.summary}`;
1977
2311
  const decisionMatch = /DECISION:\s*(MERGE|APPROVE|REQUEST_CHANGES|CLOSE)/i.exec(textToAnalyze);
1978
2312
  const decision = decisionMatch ? decisionMatch[1].toUpperCase() : report.state === "ready" ? "APPROVE" : "REQUEST_CHANGES";
1979
- if (decision === "MERGE" && settings.github.prReview?.autoMerge && (!prVerification || prVerification.passed)) {
1980
- const method = settings.github.prReview.mergeMethod ?? "squash";
1981
- try {
1982
- await run(settings.github.cli, [
2313
+ const request = source === "gitlab" ? `MR !${prNumber}` : `PR #${prNumber}`;
2314
+ const project = source === "gitlab" ? settings.gitlab?.project : settings.github?.repository;
2315
+ const verdict = (state) => `🤖 **SuperAgent Review Verdict: ${state}**\n\n${deliverable(report.summary)}`;
2316
+ if (decision === "MERGE" && review.autoMerge && (!prVerification || prVerification.passed)) try {
2317
+ if (source === "gitlab" && settings.gitlab) {
2318
+ const gitlab = settings.gitlab;
2319
+ await mergeMergeRequest({
2320
+ cli: gitlab.cli,
2321
+ host: gitlab.host,
2322
+ project: gitlab.project,
2323
+ iid: prNumber,
2324
+ squash: gitlab.mrReview?.squash ?? true,
2325
+ autoMerge: true
2326
+ });
2327
+ await replyNote({
2328
+ cli: gitlab.cli,
2329
+ host: gitlab.host,
2330
+ project: gitlab.project,
2331
+ iid: prNumber,
2332
+ kind: "merge_request",
2333
+ body: `${verdict("MERGED")}\n\nAutomated local verification passed and code review approved.`
2334
+ }).catch(() => {});
2335
+ } else if (settings.github) {
2336
+ const github = settings.github;
2337
+ const method = github.prReview?.mergeMethod ?? "squash";
2338
+ await run(github.cli, [
1983
2339
  "pr",
1984
2340
  "merge",
1985
2341
  String(prNumber),
1986
2342
  `--${method}`,
1987
2343
  "--auto",
1988
2344
  "--repo",
1989
- settings.github.repository
2345
+ github.repository
1990
2346
  ]);
1991
- await run(settings.github.cli, [
2347
+ await run(github.cli, [
1992
2348
  "pr",
1993
2349
  "comment",
1994
2350
  String(prNumber),
1995
2351
  "--repo",
1996
- settings.github.repository,
2352
+ github.repository,
1997
2353
  "-b",
1998
- `🤖 **SuperAgent Review Verdict: MERGED**\n\n${deliverable(report.summary)}\n\nAutomated local verification passed and code review approved.`
2354
+ `${verdict("MERGED")}\n\nAutomated local verification passed and code review approved.`
1999
2355
  ]).catch(() => {});
2000
- log?.(`Merged PR #${prNumber} on ${settings.github.repository}`);
2001
- } catch (mergeErr) {
2002
- log?.(`Could not merge PR #${prNumber}: ${mergeErr.message}`);
2003
2356
  }
2004
- } else if (decision === "CLOSE") try {
2005
- await run(settings.github.cli, [
2006
- "pr",
2007
- "close",
2008
- String(prNumber),
2009
- "--repo",
2010
- settings.github.repository,
2011
- "-c",
2012
- `🤖 **SuperAgent Review Verdict: CLOSED**\n\n${deliverable(report.summary)}`
2013
- ]);
2014
- log?.(`Closed PR #${prNumber} on ${settings.github.repository}`);
2357
+ log?.(`Merged ${request} on ${project}`);
2358
+ } catch (mergeErr) {
2359
+ log?.(`Could not merge ${request}: ${mergeErr.message}`);
2360
+ }
2361
+ else if (decision === "CLOSE") try {
2362
+ if (source === "gitlab" && settings.gitlab) {
2363
+ const gitlab = settings.gitlab;
2364
+ await closeMergeRequest({
2365
+ cli: gitlab.cli,
2366
+ host: gitlab.host,
2367
+ project: gitlab.project,
2368
+ iid: prNumber
2369
+ });
2370
+ await replyNote({
2371
+ cli: gitlab.cli,
2372
+ host: gitlab.host,
2373
+ project: gitlab.project,
2374
+ iid: prNumber,
2375
+ kind: "merge_request",
2376
+ body: verdict("CLOSED")
2377
+ }).catch(() => {});
2378
+ } else if (settings.github) {
2379
+ const github = settings.github;
2380
+ await run(github.cli, [
2381
+ "pr",
2382
+ "close",
2383
+ String(prNumber),
2384
+ "--repo",
2385
+ github.repository,
2386
+ "-c",
2387
+ verdict("CLOSED")
2388
+ ]);
2389
+ }
2390
+ log?.(`Closed ${request} on ${project}`);
2015
2391
  } catch (closeErr) {
2016
- log?.(`Could not close PR #${prNumber}: ${closeErr.message}`);
2392
+ log?.(`Could not close ${request}: ${closeErr.message}`);
2017
2393
  }
2018
2394
  }
2019
2395
  if (report.followupAfterSeconds && report.followupAfterSeconds > 0) await new TimerStore(stateDir).save({
@@ -2098,19 +2474,27 @@ async function runLoop(options) {
2098
2474
  if (!options.once) caller.addEventListener("abort", () => stop.abort(), { once: true });
2099
2475
  const signal = stop.signal;
2100
2476
  const github = settings.github?.enabled ? settings.github : void 0;
2477
+ const gitlab = settings.gitlab?.enabled ? settings.gitlab : void 0;
2101
2478
  const feishu = settings.feishu?.enabled ? settings.feishu : void 0;
2102
2479
  const twitter = settings.twitter?.enabled ? settings.twitter : void 0;
2103
- if (!github && !feishu && !twitter) throw new Error("No Source is on in settings.yaml; nothing to poll.");
2104
- const login = github ? await agentLogin(github.cli, signal) : "";
2480
+ if (!github && !gitlab && !feishu && !twitter) throw new Error("No Source is on in settings.yaml; nothing to poll.");
2481
+ const login = github ? await agentLogin(github.cli, signal) : gitlab ? await gitlabLogin(gitlab.cli, gitlab.host, signal) : "";
2105
2482
  const twitterBot = twitter ? await twitterAccount(twitter.cli, signal) : "";
2106
2483
  const accounts = {
2107
2484
  stateDir: settings.stateDir,
2108
- githubCli: github?.cli ?? "gh",
2485
+ ...github ? { githubCli: github.cli } : {},
2486
+ ...gitlab ? {
2487
+ gitlabCli: gitlab.cli,
2488
+ gitlabHost: gitlab.host
2489
+ } : {},
2490
+ ...feishu ? { feishuCli: feishu.cli } : {},
2109
2491
  agentLogin: login
2110
2492
  };
2493
+ /** The project the tickets change, in the forge's own naming. */
2494
+ const repository = github?.repository ?? gitlab?.project ?? settings.checkout;
2111
2495
  await writeEnvironment(accounts, settings.executor.blockedCommands);
2112
2496
  const standing = await standingRules();
2113
- const channel = outbox();
2497
+ const channel = outbox(repo);
2114
2498
  const scope = sourceScope(settings);
2115
2499
  const decided = new WorkQueue();
2116
2500
  const finished = new WorkQueue();
@@ -2127,55 +2511,54 @@ async function runLoop(options) {
2127
2511
  executor: void 0,
2128
2512
  outbox: channel
2129
2513
  });
2130
- const site = {
2131
- started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
2132
- reported: (ticketId, report) => {
2133
- record(engine, repo, [{
2134
- ticketId,
2135
- report
2136
- }], log);
2137
- },
2138
- failed: (ticketId, _assignmentId, summary) => {
2139
- record(engine, repo, [{
2140
- ticketId,
2141
- report: {
2142
- state: "failed",
2143
- summary
2144
- }
2145
- }], log);
2146
- },
2147
- interrupted: (ticketId, assignmentId) => {
2148
- try {
2149
- engine.assignmentInterrupted(ticketId, assignmentId);
2150
- } catch (error) {
2151
- log(`Could not recover ${ticketId}: ${error.message}`);
2152
- }
2153
- }
2154
- };
2155
2514
  const executor = new AgentExecutor({
2156
2515
  engine,
2157
2516
  settings,
2158
2517
  maxWorkers: settings.executor.maxWorkers,
2159
2518
  runner: runnerFor(settings.executor.agent, settings.executor.binary),
2160
2519
  stateDir: settings.stateDir,
2161
- repository: github?.repository ?? settings.checkout,
2520
+ repository,
2162
2521
  agent: login,
2163
2522
  accounts,
2164
- ...feishu ? { feishuCli: feishu.cli } : {},
2165
- site,
2523
+ site: {
2524
+ started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
2525
+ reported: (ticketId, report) => {
2526
+ record(engine, repo, [{
2527
+ ticketId,
2528
+ report
2529
+ }], log);
2530
+ },
2531
+ failed: (ticketId, _assignmentId, summary) => {
2532
+ record(engine, repo, [{
2533
+ ticketId,
2534
+ report: {
2535
+ state: "failed",
2536
+ summary
2537
+ }
2538
+ }], log);
2539
+ },
2540
+ interrupted: (ticketId, assignmentId) => {
2541
+ try {
2542
+ engine.assignmentInterrupted(ticketId, assignmentId);
2543
+ } catch (error) {
2544
+ log(`Could not recover ${ticketId}: ${error.message}`);
2545
+ }
2546
+ }
2547
+ },
2166
2548
  repo,
2167
2549
  log,
2168
2550
  prompt: async (ticket, directory, branch, prVerification) => {
2169
2551
  const trigger = repo.triggers.get(ticket.origin.triggerId);
2170
- const source = trigger?.source === "feishu" ? "feishu" : "github";
2552
+ const source = trigger?.source === "feishu" ? "feishu" : trigger?.source === "gitlab" ? "gitlab" : "github";
2171
2553
  const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
2172
2554
  const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
2173
2555
  const notes = ticket.inputs.flatMap((input) => input.kind === "text" ? [input.text] : []);
2174
2556
  const readOnly = ticket.mandate.strength === "inferred" && !isPrReview;
2557
+ const autoMerge = source === "gitlab" ? gitlab?.mrReview?.autoMerge : github?.prReview?.autoMerge;
2175
2558
  return composePrompt({
2176
2559
  ticket,
2177
2560
  trigger,
2178
- repository: github?.repository ?? settings.checkout,
2561
+ repository,
2179
2562
  agentLogin: login,
2180
2563
  branchPrefix: settings.branchPrefix,
2181
2564
  source,
@@ -2187,7 +2570,7 @@ async function runLoop(options) {
2187
2570
  isPrReview,
2188
2571
  prNumber,
2189
2572
  prVerification,
2190
- autoMergeAllowed: Boolean(github?.prReview?.autoMerge)
2573
+ autoMergeAllowed: Boolean(autoMerge)
2191
2574
  });
2192
2575
  }
2193
2576
  });
@@ -2322,6 +2705,36 @@ async function runLoop(options) {
2322
2705
  since = round;
2323
2706
  repo.setMeta(pollKey, since);
2324
2707
  }
2708
+ if (gitlab) {
2709
+ try {
2710
+ const triggers = await pollTodos({
2711
+ cli: gitlab.cli,
2712
+ host: gitlab.host,
2713
+ project: gitlab.project,
2714
+ agent: login,
2715
+ signal,
2716
+ seen: (id) => repo.getMeta(seenKey(id)) === true,
2717
+ mark: (id) => repo.setMeta(seenKey(id), true)
2718
+ });
2719
+ for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
2720
+ } catch (error) {
2721
+ if (!signal.aborted) log(`GitLab poll failed: ${error.message}`);
2722
+ }
2723
+ if (gitlab.mrReview?.enabled && gitlab.mrReview.pollOpenMrs !== false) try {
2724
+ const triggers = await pollOpenMergeRequests({
2725
+ cli: gitlab.cli,
2726
+ host: gitlab.host,
2727
+ project: gitlab.project,
2728
+ agent: login,
2729
+ signal,
2730
+ seen: (id) => repo.getMeta(`gitlab:seen:${id}`) === true,
2731
+ mark: (id) => repo.setMeta(`gitlab:seen:${id}`, true)
2732
+ });
2733
+ for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received MR review trigger for !${trigger.meta?.number} from ${trigger.actor.id}`);
2734
+ } catch (error) {
2735
+ if (!signal.aborted) log(`Merge request poll failed: ${error.message}`);
2736
+ }
2737
+ }
2325
2738
  if (twitter) try {
2326
2739
  const triggers = await searchTweets(twitter.cli, twitter.query, {
2327
2740
  seen: (id) => repo.getMeta(`twitter:seen:${id}`) === true,
@@ -2408,16 +2821,20 @@ async function runLoop(options) {
2408
2821
  await repo.flush();
2409
2822
  await send(channel, {
2410
2823
  ...github ? { github: github.cli } : {},
2824
+ ...gitlab ? { gitlab: {
2825
+ cli: gitlab.cli,
2826
+ host: gitlab.host
2827
+ } } : {},
2411
2828
  ...feishu ? { feishu: feishu.cli } : {},
2412
2829
  ...twitter ? { twitter: twitter.cli } : {}
2413
- }, log, settings.attention);
2830
+ }, log, settings.attention, (id) => repo.setMeta(`outbox:${id}`, true));
2414
2831
  await repo.flush();
2415
2832
  await sync();
2416
2833
  } catch (error) {
2417
2834
  if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
2418
2835
  }
2419
2836
  if (options.once) break;
2420
- const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity, twitter?.pollSeconds ?? Infinity);
2837
+ const seconds = Math.min(github?.pollSeconds ?? Infinity, gitlab?.pollSeconds ?? Infinity, feishu ? 15 : Infinity, twitter?.pollSeconds ?? Infinity);
2421
2838
  let left = options.once ? 0 : seconds * 1e3;
2422
2839
  while (left > 0 && !signal.aborted) {
2423
2840
  const began = Date.now();
@@ -2534,7 +2951,11 @@ async function resolveMembers(cli, chatId, names) {
2534
2951
  }
2535
2952
  /** Splits `a,b, c` and drops the blanks, so one flag can name several people. */
2536
2953
  const names = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
2537
- const MANAGED = ["github", "feishu"];
2954
+ const MANAGED = [
2955
+ "github",
2956
+ "feishu",
2957
+ "gitlab"
2958
+ ];
2538
2959
  /**
2539
2960
  * The settings file with only the Source sections replaced, so this command keeps the text an operator wrote.
2540
2961
  *
@@ -2584,6 +3005,11 @@ async function setupGithub(options) {
2584
3005
  let login;
2585
3006
  await update(options.dir, async (settings) => {
2586
3007
  const cli = settings.github?.cli ?? "gh";
3008
+ if (settings.gitlab?.enabled) {
3009
+ lines.push("GitHub: this installation already serves GitLab; set `gitlab.enabled` to false before adding GitHub");
3010
+ failed = true;
3011
+ return false;
3012
+ }
2587
3013
  try {
2588
3014
  login = await githubLogin(cli);
2589
3015
  } catch (error) {
@@ -2625,6 +3051,84 @@ async function setupGithub(options) {
2625
3051
  failed
2626
3052
  };
2627
3053
  }
3054
+ /** The host and project of a GitLab remote URL, in either the https or the ssh form. */
3055
+ function gitlabOrigin(origin) {
3056
+ const match = /^(?:https?:\/\/([^/]+)\/|ssh:\/\/git@([^/]+)\/|git@([^/]+):)(.+?)(?:\.git)?\/?$/.exec(origin.trim());
3057
+ if (!match) return void 0;
3058
+ const host = (match[1] ?? match[2] ?? match[3] ?? "").replace(/^[^@]+@/, "");
3059
+ const project = match[4];
3060
+ return host && project ? {
3061
+ host,
3062
+ project
3063
+ } : void 0;
3064
+ }
3065
+ /** Fills the GitLab Source from `glab` and the checkout's origin, so a self-managed instance is one field. */
3066
+ async function setupGitlab(options) {
3067
+ const lines = [];
3068
+ let failed = false;
3069
+ await update(options.dir, async (settings) => {
3070
+ const cli = settings.gitlab?.cli ?? "glab";
3071
+ if (settings.github?.enabled) {
3072
+ lines.push("GitLab: this installation already serves GitHub; set `github.enabled` to false before adding GitLab");
3073
+ failed = true;
3074
+ return false;
3075
+ }
3076
+ const origin = options.stateDir ? await originOf(settings.checkout, options.stateDir) : void 0;
3077
+ const parsed = origin ? gitlabOrigin(origin) : void 0;
3078
+ const configuredHost = settings.gitlab?.host;
3079
+ const host = configuredHost && configuredHost !== "gitlab.com" ? configuredHost : parsed?.host ?? configuredHost ?? "gitlab.com";
3080
+ const project = settings.gitlab?.project ?? parsed?.project;
3081
+ if (!project) {
3082
+ lines.push("GitLab: no `group/project` in settings and none in the checkout origin; set `gitlab.project`");
3083
+ failed = true;
3084
+ return false;
3085
+ }
3086
+ let login;
3087
+ try {
3088
+ login = await gitlabLogin(cli, host);
3089
+ } catch (error) {
3090
+ lines.push(`GitLab: ${error.message}`);
3091
+ failed = true;
3092
+ return false;
3093
+ }
3094
+ lines.push(`GitLab account: ${login} (${cli} on ${host})`);
3095
+ try {
3096
+ const meta = await runJson(cli, [
3097
+ "api",
3098
+ "--hostname",
3099
+ host,
3100
+ `projects/${encodeURIComponent(project)}`
3101
+ ]);
3102
+ const gitlab = settings.gitlab = {
3103
+ ...settings.gitlab ?? {
3104
+ enabled: true,
3105
+ host,
3106
+ project,
3107
+ cli,
3108
+ pollSeconds: 60,
3109
+ allowed: []
3110
+ },
3111
+ enabled: settings.gitlab?.enabled ?? true,
3112
+ host,
3113
+ cli,
3114
+ project: meta.path_with_namespace ?? project,
3115
+ allowed: options.allow.length ? [...options.allow] : settings.gitlab?.allowed ?? []
3116
+ };
3117
+ lines.push(`Project: ${gitlab.project}${meta.visibility ? ` (${meta.visibility})` : ""}`);
3118
+ lines.push(`Allowed users: ${gitlab.allowed.join(", ") || "(none)"}`);
3119
+ if (gitlab.allowed.every((item) => item.toLowerCase() !== login.toLowerCase())) lines.push(`Note: ${login} is not allowed to ask for work; add it with \`--allow ${login}\` if the agent should answer itself.`);
3120
+ return true;
3121
+ } catch (error) {
3122
+ lines.push(`GitLab: ${error.message}`);
3123
+ failed = true;
3124
+ return false;
3125
+ }
3126
+ });
3127
+ return {
3128
+ lines,
3129
+ failed
3130
+ };
3131
+ }
2628
3132
  async function findChat(cli, wanted, current) {
2629
3133
  if (wanted?.startsWith("oc_")) return wanted;
2630
3134
  const chats = await botChats(cli);
@@ -2708,11 +3212,12 @@ async function setupFeishu(options) {
2708
3212
  }
2709
3213
  /** Runs the steps in order and prints what each found; a failed GitHub step still lets Feishu run. */
2710
3214
  async function setup(options) {
2711
- const targets = options.targets.length ? options.targets : ["github", "feishu"];
3215
+ const forge = (await readSettings(join(options.dir, "settings.yaml")).catch(() => void 0))?.gitlab?.enabled ? "gitlab" : "github";
3216
+ const targets = options.targets.length ? options.targets : [forge, "feishu"];
2712
3217
  let failed = false;
2713
3218
  try {
2714
3219
  for (const target of targets) {
2715
- const report = target === "github" ? await setupGithub(options) : await setupFeishu(options);
3220
+ const report = target === "github" ? await setupGithub(options) : target === "feishu" ? await setupFeishu(options) : await setupGitlab(options);
2716
3221
  for (const line of report.lines) options.log(line);
2717
3222
  failed ||= report.failed;
2718
3223
  }
@@ -2731,10 +3236,10 @@ async function setup(options) {
2731
3236
  * The command prints Markdown because people and agents both read it: an agent that needs to know what is open runs
2732
3237
  * `superagent status` and gets an answer it can put straight into a prompt.
2733
3238
  */
2734
- const USAGE = `superagent — an agent that turns GitHub and Feishu requests into tickets
3239
+ const USAGE = `superagent — an agent that turns GitHub, GitLab and Feishu requests into tickets
2735
3240
 
2736
3241
  superagent init [dir] create ${SETTINGS_FILE} and the state directory in dir (default: .)
2737
- superagent setup [dir] [what…] fill the GitHub and Feishu settings from the configured CLIs
3242
+ superagent setup [dir] [what…] fill the Source settings from the configured CLIs
2738
3243
  superagent status [dir] print open tickets and recent activity as Markdown
2739
3244
  superagent doctor [dir] show which coding agents are installed and which one is selected
2740
3245
  superagent agents list the coding agents a configuration may name
@@ -2743,10 +3248,10 @@ const USAGE = `superagent — an agent that turns GitHub and Feishu requests int
2743
3248
 
2744
3249
  superagent setup asks the CLIs that already know the answers, so a person does not copy ids out of a web page:
2745
3250
 
2746
- --allow <names> logins or Feishu user names that may ask for work, comma separated
2747
- (a name becomes the member's open id; the chat's members are added too)
3251
+ --allow <names> logins, GitLab usernames or Feishu user names that may ask for work, comma separated
3252
+ (a Feishu name becomes the member's open id; the chat's members are added too)
2748
3253
  --chat <id|name> the Feishu chat the bot listens to
2749
- github, feishu set up only one of them (the default is both)
3254
+ github, feishu, gitlab set up only one of them (the default is GitHub and Feishu)
2750
3255
 
2751
3256
  Every command that reads an installation takes the directory that holds ${SETTINGS_FILE}.`;
2752
3257
  async function exists(path) {
@@ -2783,7 +3288,7 @@ async function init(dir) {
2783
3288
  "",
2784
3289
  `State lives in ${settings.stateDir}.`,
2785
3290
  "",
2786
- "Next: set `github.repository` and `github.allowed`, choose `executor.agent`, then run `superagent doctor`.",
3291
+ "Next: set `github.repository` or `gitlab.project`, fill its allowed list, choose `executor.agent`, then run `superagent doctor`.",
2787
3292
  ""
2788
3293
  ].join("\n"));
2789
3294
  return 0;
@@ -2794,7 +3299,7 @@ async function setupSources(dir, rest) {
2794
3299
  const index = rest.indexOf(name);
2795
3300
  return index < 0 ? void 0 : rest[index + 1];
2796
3301
  };
2797
- const targets = rest.filter((item) => item === "github" || item === "feishu");
3302
+ const targets = rest.filter((item) => item === "github" || item === "feishu" || item === "gitlab");
2798
3303
  let settings;
2799
3304
  try {
2800
3305
  settings = await readSettings(join(dir, SETTINGS_FILE));
@@ -2874,6 +3379,7 @@ async function doctor(dir) {
2874
3379
  const chosen = settings.executor.agent;
2875
3380
  lines.push("", `Selected: **${chosen}**${found[chosen] ? "" : " — not installed"}`, "");
2876
3381
  if (settings.github) lines.push(`Repository: \`${settings.github.repository}\`, allowed logins: ${settings.github.allowed.join(", ") || "(none)"}`, "");
3382
+ if (settings.gitlab) lines.push(`GitLab project: \`${settings.gitlab.project}\` on \`${settings.gitlab.host}\`, allowed users: ${settings.gitlab.allowed.join(", ") || "(none)"}`, "");
2877
3383
  const stateFound = await exists(settings.stateDir);
2878
3384
  lines.push(`State directory: \`${settings.stateDir}\`${stateFound ? "" : " — missing, run `superagent init`"}`, "");
2879
3385
  process.stdout.write(lines.join("\n"));