superagent-skill 0.5.1 → 0.5.3

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/README.md CHANGED
@@ -119,6 +119,26 @@ One installation serves one forge: `github.enabled` and `gitlab.enabled` cannot
119
119
  credentials and CLI shim bind to one account. A merge request triggers the same review prompt as a pull request, with
120
120
  GitLab's words and its `refs/merge-requests/<iid>/head` checkout.
121
121
 
122
+ ## The issue workflow
123
+
124
+ `workflow` works through labeled GitLab issues one at a time, with the operator in the loop:
125
+
126
+ ```yaml
127
+ workflow:
128
+ enabled: true
129
+ label: superagent # open issues with this label are the queue
130
+ user: ou_... # asked in a Feishu direct message
131
+ mergeInto: release/test # what the ticket's request merges into
132
+ verifyCommands: ["./gradlew test"]
133
+ executor:
134
+ worktree: false # run in checkout on its long-lived branch, not a per-ticket worktree
135
+ ```
136
+
137
+ The bot proposes the next labeled issue — a `[Phase 0]` title first, then the lowest iid — and asks. `做 #2585` starts
138
+ the turn, `不做 #2585` drops it. When the turn ends the bot sends the summary and the output of `verifyCommands`, then asks
139
+ `关闭 #2585` or `保留 #2585`; only `关闭` closes the issue. The next issue is proposed after that answer. Answers are read
140
+ from the live Feishu stream, so run `superagent poll` continuously rather than one round at a time.
141
+
122
142
  ## Compare with dsh-superagent
123
143
 
124
144
  [`docs/dsh-superagent-comparison.md`](docs/dsh-superagent-comparison.md)([中文版](docs/dsh-superagent-comparison.zh.md))
@@ -154,8 +174,8 @@ pnpm install && pnpm build
154
174
  ln -sf "$PWD/bin/superagent.js" ~/.local/bin/superagent # a directory on PATH
155
175
  ```
156
176
 
157
- Start the loop from that directory: `superagent poll` keeps running, and `superagent poll --once` runs one round, which
158
- is what a cron entry calls each minute.
177
+ Start the loop from that directory: `superagent poll` keeps running, and `superagent poll . --once` runs one round,
178
+ waits for the turns it started, posts their reports, and exits — which is what a cron entry calls each minute.
159
179
 
160
180
  `checkout` names the repository the tickets change, and `executor.agent` names the coding agent. The Sources are
161
181
  optional, but at least one must be on; `github` and `gitlab` cannot both be, because one installation serves one forge.
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-BwRUbWkx.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-BPxaqC93.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";
@@ -261,10 +261,10 @@ function composePrompt(input) {
261
261
  "",
262
262
  "## How to work",
263
263
  "",
264
- `- Work only in this directory. It is a worktree of the repository on a new branch.`,
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.`,
264
+ input.shared ? "- Work only in this directory. It is the installation checkout on its long-lived development branch." : "- Work only in this directory. It is a worktree of the repository on a new branch.",
265
+ input.shared ? `- Commit on the branch this checkout is already on, and open a ${words.request} from it when done; do not create a per-ticket branch.` : 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.`,
266
266
  "- Run the tests the repository has. Do not claim a check passed unless you ran it.",
267
- `- Do not merge the ${words.request}. A person merges it.`,
267
+ input.mergeInto ? `- Merge the ${words.request} into \`${input.mergeInto}\` once your checks pass, so the test environment picks it up. Merge nothing into another branch.` : `- Do not merge the ${words.request}. A person merges it.`,
268
268
  "- If the request needs a decision you cannot make, stop and ask one concrete question.",
269
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."] : [],
270
270
  ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
@@ -1390,6 +1390,64 @@ async function closeMergeRequest(input) {
1390
1390
  "state_event=close"
1391
1391
  ]), { signal: input.signal });
1392
1392
  }
1393
+ z.looseObject({
1394
+ iid: z.number(),
1395
+ title: z.string(),
1396
+ description: z.string().nullish(),
1397
+ state: z.string().nullish(),
1398
+ web_url: z.string().nullish(),
1399
+ updated_at: z.string().nullish(),
1400
+ author: PersonSchema,
1401
+ labels: z.array(z.string()).nullish()
1402
+ });
1403
+ /** The open issues carrying `label`, which is the workflow's queue. */
1404
+ async function listOpenIssues(input) {
1405
+ return runJson(input.cli, apiArgs(input.host, `projects/${projectPath(input.project)}/issues?state=opened&labels=${encodeURIComponent(input.label)}&per_page=100`), { signal: input.signal });
1406
+ }
1407
+ /**
1408
+ * Builds the Trigger the workflow proposes for one issue.
1409
+ *
1410
+ * It is `addressed: 'direct'`: the issue was chosen by the queue, not mentioned by someone, so the policy admits it as a
1411
+ * direct request from its author.
1412
+ */
1413
+ function issueTrigger(input) {
1414
+ const { issue, host, project, agent } = input;
1415
+ const username = issue.author?.username ?? "";
1416
+ const url = issue.web_url ?? gitlabPage(host, project, issue.iid);
1417
+ return {
1418
+ id: key("gitlab-issue", project, String(issue.iid)),
1419
+ source: SOURCE$2,
1420
+ threads: [gitlabThread(project, issue.iid)],
1421
+ actor: {
1422
+ source: SOURCE$2,
1423
+ id: username
1424
+ },
1425
+ human: !isBot(issue.author) && !sameName(username, agent),
1426
+ addressed: "direct",
1427
+ at: issue.updated_at ?? (/* @__PURE__ */ new Date()).toISOString(),
1428
+ text: `${issue.title}\n\n${issue.description ?? ""}`,
1429
+ url,
1430
+ channel: gitlabChannel(host, project, issue.iid, "issue", url),
1431
+ meta: {
1432
+ number: issue.iid,
1433
+ isPr: false,
1434
+ kind: "issue",
1435
+ repository: project,
1436
+ host,
1437
+ author: username,
1438
+ workflow: true
1439
+ }
1440
+ };
1441
+ }
1442
+ /** Closes an issue, which the operator confirmed in Feishu. */
1443
+ async function closeIssue(input) {
1444
+ await run(input.cli, apiArgs(input.host, `projects/${projectPath(input.project)}/issues/${input.iid}`, [
1445
+ "--method",
1446
+ "PUT",
1447
+ "--field",
1448
+ "state_event=close"
1449
+ ]), { signal: input.signal });
1450
+ }
1393
1451
  // src/sources/feishu.ts
1394
1452
  /**
1395
1453
  * The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
@@ -1545,6 +1603,27 @@ async function reply(cli, messageId, text, idempotencyKey, signal) {
1545
1603
  idempotencyKey
1546
1604
  ], { signal });
1547
1605
  }
1606
+ /**
1607
+ * Sends a new message as the bot: a direct message to `userId`, or into a chat. The idempotency key keeps a retried
1608
+ * round from sending the same question twice.
1609
+ */
1610
+ async function sendMessage(cli, to, text, idempotencyKey, signal) {
1611
+ const result = await runJson(cli, [
1612
+ "im",
1613
+ "+messages-send",
1614
+ "--as",
1615
+ "bot",
1616
+ ...to.chatId ? ["--chat-id", to.chatId] : ["--user-id", to.userId ?? ""],
1617
+ "--markdown",
1618
+ text,
1619
+ "--idempotency-key",
1620
+ idempotencyKey
1621
+ ], { signal });
1622
+ return {
1623
+ ...result.chat_id ? { chatId: result.chat_id } : {},
1624
+ ...result.message_id ? { messageId: result.message_id } : {}
1625
+ };
1626
+ }
1548
1627
  /** A small JSON reader for the event stream, which tolerates what other commands print before or between events. */
1549
1628
  var EventReader = class {
1550
1629
  rest = "";
@@ -1697,6 +1776,99 @@ function consumeEvents(options) {
1697
1776
  ended
1698
1777
  };
1699
1778
  }
1779
+ // src/workflow.ts
1780
+ /**
1781
+ * The issue-by-issue workflow: one labeled GitLab issue is proposed at a time, the operator is asked in a Feishu direct
1782
+ * message, the work runs only after a yes, and the issue is closed only after a second yes.
1783
+ *
1784
+ * The record of each issue lives in the state directory, so a restart re-asks nothing and a process that exits between
1785
+ * the question and the answer does not lose it.
1786
+ */
1787
+ /** One file per issue under `state/workflow`, so a person can read the queue with `ls` and `cat`. */
1788
+ var WorkflowStore = class {
1789
+ stateDir;
1790
+ constructor(stateDir) {
1791
+ this.stateDir = stateDir;
1792
+ }
1793
+ dir() {
1794
+ return join(this.stateDir, "workflow");
1795
+ }
1796
+ path(iid) {
1797
+ return join(this.dir(), `${iid}.json`);
1798
+ }
1799
+ async init() {
1800
+ await mkdir(this.dir(), { recursive: true });
1801
+ }
1802
+ async get(iid) {
1803
+ try {
1804
+ return JSON.parse(await readFile(this.path(iid), "utf8"));
1805
+ } catch {
1806
+ return;
1807
+ }
1808
+ }
1809
+ async save(record) {
1810
+ await this.init();
1811
+ await writeFile(this.path(record.iid), `${JSON.stringify(record, null, 2)}\n`, "utf8");
1812
+ }
1813
+ async all() {
1814
+ const names = await readdir(this.dir()).catch(() => []);
1815
+ const records = [];
1816
+ for (const name of names) {
1817
+ if (!name.endsWith(".json")) continue;
1818
+ try {
1819
+ records.push(JSON.parse(await readFile(join(this.dir(), name), "utf8")));
1820
+ } catch {}
1821
+ }
1822
+ return records;
1823
+ }
1824
+ /** The issue the workflow is on: waiting for a yes, running, or waiting for a close. */
1825
+ async active() {
1826
+ return (await this.all()).find((record) => record.phase === "waiting" || record.phase === "working" || record.phase === "closing");
1827
+ }
1828
+ };
1829
+ const VERBS = {
1830
+ "做": "do",
1831
+ "不做": "skip",
1832
+ "关闭": "close",
1833
+ "保留": "keep"
1834
+ };
1835
+ /** Reads `做 #2585`, `不做 #2585`, `关闭 #2585` or `保留 #2585`; anything else is a person's message as usual. */
1836
+ function workflowCommand(text) {
1837
+ const match = /^\s*(做|不做|关闭|保留)\s*#?\s*(\d+)\s*$/.exec(text);
1838
+ if (!match) return void 0;
1839
+ const verb = VERBS[match[1]];
1840
+ const iid = Number(match[2]);
1841
+ return verb && Number.isInteger(iid) && iid > 0 ? {
1842
+ verb,
1843
+ iid
1844
+ } : void 0;
1845
+ }
1846
+ /** The next issue to propose: the Phase 0 issue first, then the lowest iid not yet proposed. */
1847
+ function nextIssue(issues, seen) {
1848
+ const rank = (issue) => /^\[Phase 0\]/.test(issue.title) ? 0 : 1;
1849
+ return [...issues].filter((issue) => !seen.has(issue.iid)).sort((a, b) => rank(a) - rank(b) || a.iid - b.iid)[0];
1850
+ }
1851
+ /**
1852
+ * Runs the configured checks in the ticket's worktree and returns a short markdown record.
1853
+ *
1854
+ * A failing command is recorded, not thrown: the report still reaches the operator, and the summary says what failed.
1855
+ */
1856
+ async function runChecks(commands, cwd, signal) {
1857
+ const lines = [];
1858
+ for (const command of commands) try {
1859
+ const output = await run("/bin/sh", ["-c", command], {
1860
+ cwd,
1861
+ signal,
1862
+ timeoutMs: 18e5
1863
+ });
1864
+ lines.push(`- \`${command}\`: ok`);
1865
+ const tail = output.trim().split("\n").slice(-6).join("\n");
1866
+ if (tail) lines.push("", "```", tail, "```");
1867
+ } catch (error) {
1868
+ lines.push(`- \`${command}\`: FAILED — ${error.message.split("\n")[0].slice(0, 300)}`);
1869
+ }
1870
+ return lines.join("\n");
1871
+ }
1700
1872
  // src/sources/twitter.ts
1701
1873
  /**
1702
1874
  * The Twitter/X Source: searches keywords using `opencli twitter search` and turns feedback into Triggers,
@@ -2206,19 +2378,52 @@ var AgentExecutor = class {
2206
2378
  active = /* @__PURE__ */ new Map();
2207
2379
  /** Tickets whose turn waits for a free slot, oldest first. */
2208
2380
  pending = [];
2381
+ /** Workflow tickets whose turn waits for the operator's yes. */
2382
+ held = /* @__PURE__ */ new Map();
2383
+ /** The questions being sent, which a finishing run waits for so a DM is not cut off by its own exit. */
2384
+ asks = /* @__PURE__ */ new Set();
2209
2385
  pumping = false;
2210
2386
  constructor(options) {
2211
2387
  this.options = options;
2212
2388
  }
2213
2389
  start(ticket, assignment) {
2214
- const { site } = this.options;
2215
- site.started(ticket.id, assignment.id);
2390
+ this.options.site.started(ticket.id, assignment.id);
2391
+ this.dispatch(ticket, assignment);
2392
+ }
2393
+ /** Holds a workflow ticket for the operator's yes, or queues the turn in the free slots. */
2394
+ dispatch(ticket, assignment) {
2395
+ const trigger = this.options.repo?.triggers.get(ticket.origin.triggerId);
2396
+ if (this.options.workflow && trigger?.meta?.workflow === true) {
2397
+ this.held.set(ticket.id, {
2398
+ ticket,
2399
+ assignment
2400
+ });
2401
+ const ask = this.options.workflow.ask(ticket, trigger).catch((error) => this.options.log?.(`Could not ask about ${ticket.id}: ${error.message}`));
2402
+ this.asks.add(ask);
2403
+ ask.finally(() => {
2404
+ this.asks.delete(ask);
2405
+ });
2406
+ return;
2407
+ }
2216
2408
  this.pending.push({
2217
2409
  ticket,
2218
2410
  assignment
2219
2411
  });
2220
2412
  this.pump();
2221
2413
  }
2414
+ /** Starts the held turn of a ticket the operator approved; false when this executor holds none. */
2415
+ release(ticketId) {
2416
+ const held = this.held.get(ticketId);
2417
+ if (!held) return false;
2418
+ this.held.delete(ticketId);
2419
+ this.pending.push(held);
2420
+ this.pump();
2421
+ return true;
2422
+ }
2423
+ /** Drops a held turn, such as one the operator declined. */
2424
+ forget(ticketId) {
2425
+ this.held.delete(ticketId);
2426
+ }
2222
2427
  deliver() {}
2223
2428
  /**
2224
2429
  * Takes in the tickets a previous process left running. Their agents ended with that process, so a turn that had not
@@ -2230,10 +2435,7 @@ var AgentExecutor = class {
2230
2435
  const assignment = runningAssignment(ticket);
2231
2436
  if (assignment) this.options.site.interrupted(ticket.id, assignment.id);
2232
2437
  }
2233
- for (const ticket of open) for (const assignment of ticket.assignments) if (assignment.state === "pending") this.pending.push({
2234
- ticket,
2235
- assignment
2236
- });
2438
+ for (const ticket of open) for (const assignment of ticket.assignments) if (assignment.state === "pending") this.dispatch(ticket, assignment);
2237
2439
  this.pump();
2238
2440
  }
2239
2441
  /** The Engine's memory of the ticket, so the report lands on a ticket that already holds this round's changes to it. */
@@ -2243,6 +2445,7 @@ var AgentExecutor = class {
2243
2445
  stop(ticket) {
2244
2446
  this.active.get(ticket.id)?.abort();
2245
2447
  this.active.delete(ticket.id);
2448
+ this.held.delete(ticket.id);
2246
2449
  const waiting = this.pending.findIndex((item) => item.ticket.id === ticket.id);
2247
2450
  if (waiting >= 0) this.pending.splice(waiting, 1);
2248
2451
  this.pump();
@@ -2261,17 +2464,29 @@ var AgentExecutor = class {
2261
2464
  }
2262
2465
  });
2263
2466
  }
2467
+ /** Resolves when no turn runs, none waits for a slot, and every question has gone out. */
2468
+ idle() {
2469
+ if (!this.active.size && !this.pending.length && !this.asks.size) return Promise.resolve();
2470
+ return new Promise((resolve) => {
2471
+ const timer = setInterval(() => {
2472
+ if (this.active.size || this.pending.length || this.asks.size) return;
2473
+ clearInterval(timer);
2474
+ resolve();
2475
+ }, 50);
2476
+ });
2477
+ }
2264
2478
  async execute(ticket, assignment, controller) {
2265
2479
  const { settings, runner, stateDir, accounts, site, repo, log } = this.options;
2266
- const directory = ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
2480
+ const shared = settings.executor.worktree === false;
2481
+ const directory = shared ? settings.checkout : ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
2267
2482
  const trigger = repo?.triggers.get(ticket.origin.triggerId);
2268
2483
  const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
2269
2484
  const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
2270
2485
  const source = trigger?.source === "gitlab" ? "gitlab" : "github";
2271
2486
  const review = source === "gitlab" ? settings.gitlab?.mrReview : settings.github?.prReview;
2272
2487
  try {
2273
- const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
2274
- await prepareWorktree({
2488
+ const branch = shared ? void 0 : ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
2489
+ if (!shared && branch) await prepareWorktree({
2275
2490
  checkout: settings.checkout,
2276
2491
  directory,
2277
2492
  branch,
@@ -2406,6 +2621,8 @@ var AgentExecutor = class {
2406
2621
  summary: report.summary,
2407
2622
  question: report.question ?? null
2408
2623
  });
2624
+ const workflowTrigger = repo?.triggers.get(ticket.origin.triggerId);
2625
+ if (this.options.workflow && workflowTrigger?.meta?.workflow === true) await this.options.workflow.done(ticket, workflowTrigger, report.summary).catch((error) => log?.(`Could not report on ${ticket.id}: ${error.message}`));
2409
2626
  } catch (error) {
2410
2627
  site.failed(ticket.id, assignment.id, `The agent could not run: ${error.message}`);
2411
2628
  } finally {
@@ -2418,7 +2635,7 @@ var AgentExecutor = class {
2418
2635
  return {
2419
2636
  SUPERAGENT_TICKET: ticket.id,
2420
2637
  SUPERAGENT_DIR: directory,
2421
- SUPERAGENT_BRANCH: branch,
2638
+ SUPERAGENT_BRANCH: branch ?? "",
2422
2639
  SUPERAGENT_REPOSITORY: this.options.repository,
2423
2640
  SUPERAGENT_TRIGGER: trigger.triggerId,
2424
2641
  DSH_SUPERAGENT_DIR: directory,
@@ -2477,6 +2694,10 @@ async function runLoop(options) {
2477
2694
  const gitlab = settings.gitlab?.enabled ? settings.gitlab : void 0;
2478
2695
  const feishu = settings.feishu?.enabled ? settings.feishu : void 0;
2479
2696
  const twitter = settings.twitter?.enabled ? settings.twitter : void 0;
2697
+ const workflow = settings.workflow?.enabled ? settings.workflow : void 0;
2698
+ if (workflow && (!gitlab || !feishu)) throw new Error("The issue workflow asks in Feishu about GitLab issues; turn both Sources on.");
2699
+ const workflowStore = workflow ? new WorkflowStore(settings.stateDir) : void 0;
2700
+ if (workflowStore) await workflowStore.init();
2480
2701
  if (!github && !gitlab && !feishu && !twitter) throw new Error("No Source is on in settings.yaml; nothing to poll.");
2481
2702
  const login = github ? await agentLogin(github.cli, signal) : gitlab ? await gitlabLogin(gitlab.cli, gitlab.host, signal) : "";
2482
2703
  const twitterBot = twitter ? await twitterAccount(twitter.cli, signal) : "";
@@ -2495,6 +2716,18 @@ async function runLoop(options) {
2495
2716
  await writeEnvironment(accounts, settings.executor.blockedCommands);
2496
2717
  const standing = await standingRules();
2497
2718
  const channel = outbox(repo);
2719
+ const destinations = {
2720
+ ...github ? { github: github.cli } : {},
2721
+ ...gitlab ? { gitlab: {
2722
+ cli: gitlab.cli,
2723
+ host: gitlab.host
2724
+ } } : {},
2725
+ ...feishu ? { feishu: feishu.cli } : {},
2726
+ ...twitter ? { twitter: twitter.cli } : {}
2727
+ };
2728
+ const markSent = (id) => {
2729
+ repo.setMeta(`outbox:${id}`, true);
2730
+ };
2498
2731
  const scope = sourceScope(settings);
2499
2732
  const decided = new WorkQueue();
2500
2733
  const finished = new WorkQueue();
@@ -2511,7 +2744,63 @@ async function runLoop(options) {
2511
2744
  executor: void 0,
2512
2745
  outbox: channel
2513
2746
  });
2514
- const executor = new AgentExecutor({
2747
+ const site = {
2748
+ started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
2749
+ reported: (ticketId, report) => {
2750
+ record(engine, repo, [{
2751
+ ticketId,
2752
+ report
2753
+ }], log);
2754
+ },
2755
+ failed: (ticketId, _assignmentId, summary) => {
2756
+ record(engine, repo, [{
2757
+ ticketId,
2758
+ report: {
2759
+ state: "failed",
2760
+ summary
2761
+ }
2762
+ }], log);
2763
+ },
2764
+ interrupted: (ticketId, assignmentId) => {
2765
+ try {
2766
+ engine.assignmentInterrupted(ticketId, assignmentId);
2767
+ } catch (error) {
2768
+ log(`Could not recover ${ticketId}: ${error.message}`);
2769
+ }
2770
+ }
2771
+ };
2772
+ let executor;
2773
+ const askAbout = async (ticket, trigger) => {
2774
+ const iid = Number(trigger.meta.number);
2775
+ if ((await workflowStore.get(iid))?.phase === "working") {
2776
+ executor.release(ticket.id);
2777
+ return;
2778
+ }
2779
+ await workflowStore.save({
2780
+ iid,
2781
+ ticketId: ticket.id,
2782
+ phase: "waiting",
2783
+ at: (/* @__PURE__ */ new Date()).toISOString()
2784
+ });
2785
+ const title = trigger.text.split("\n")[0].trim();
2786
+ if (!feishu || !workflow) return;
2787
+ await sendMessage(feishu.cli, { userId: workflow.user }, `**#${iid} ${title}**\n\n${trigger.url ?? ""}\n\n要做吗?回复 \`做 #${iid}\` 或 \`不做 #${iid}\`。`, `ask-${iid}`, signal);
2788
+ };
2789
+ const doneAbout = async (ticket, trigger, summary) => {
2790
+ if (!workflow || !feishu || !workflowStore) return;
2791
+ const iid = Number(trigger.meta.number);
2792
+ const directory = ticket.execution?.directory ?? join(settings.stateDir, "work", ticket.id);
2793
+ const checks = workflow.verifyCommands.length ? await runChecks(workflow.verifyCommands, directory, signal) : "";
2794
+ await workflowStore.save({
2795
+ iid,
2796
+ ticketId: ticket.id,
2797
+ phase: "closing",
2798
+ at: (/* @__PURE__ */ new Date()).toISOString()
2799
+ });
2800
+ const title = trigger.text.split("\n")[0].trim();
2801
+ await sendMessage(feishu.cli, { userId: workflow.user }, `**完成 #${iid}** ${title}\n\n${summary}\n\n${checks ? `**验证**\n${checks}\n\n` : ""}关闭吗?回复 \`关闭 #${iid}\` 或 \`保留 #${iid}\`。`, `summary-${iid}`, signal);
2802
+ };
2803
+ executor = new AgentExecutor({
2515
2804
  engine,
2516
2805
  settings,
2517
2806
  maxWorkers: settings.executor.maxWorkers,
@@ -2520,33 +2809,13 @@ async function runLoop(options) {
2520
2809
  repository,
2521
2810
  agent: login,
2522
2811
  accounts,
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
- },
2812
+ site,
2548
2813
  repo,
2549
2814
  log,
2815
+ ...workflow ? { workflow: {
2816
+ ask: askAbout,
2817
+ done: doneAbout
2818
+ } } : {},
2550
2819
  prompt: async (ticket, directory, branch, prVerification) => {
2551
2820
  const trigger = repo.triggers.get(ticket.origin.triggerId);
2552
2821
  const source = trigger?.source === "feishu" ? "feishu" : trigger?.source === "gitlab" ? "gitlab" : "github";
@@ -2570,10 +2839,115 @@ async function runLoop(options) {
2570
2839
  isPrReview,
2571
2840
  prNumber,
2572
2841
  prVerification,
2573
- autoMergeAllowed: Boolean(autoMerge)
2842
+ autoMergeAllowed: Boolean(autoMerge),
2843
+ mergeInto: workflow?.mergeInto,
2844
+ shared: settings.executor.worktree === false
2574
2845
  });
2575
2846
  }
2576
2847
  });
2848
+ /** The operator's answer in Feishu: start, skip, close or keep the issue the workflow is on. */
2849
+ const handleWorkflowCommand = async (command) => {
2850
+ if (!workflow || !feishu || !workflowStore || !gitlab) return;
2851
+ const record = await workflowStore.get(command.iid);
2852
+ const say = (text, key) => sendMessage(feishu.cli, { userId: workflow.user }, text, key, signal).then(() => void 0).catch((error) => {
2853
+ log(`Could not answer #${command.iid}: ${error.message}`);
2854
+ });
2855
+ if (!record) {
2856
+ await say(`没有在等 #${command.iid} 的决定。`, `noop-${command.iid}-${Date.now()}`);
2857
+ return;
2858
+ }
2859
+ if (command.verb === "do" && record.phase === "waiting") {
2860
+ await workflowStore.save({
2861
+ ...record,
2862
+ phase: "working",
2863
+ at: (/* @__PURE__ */ new Date()).toISOString()
2864
+ });
2865
+ if (!record.ticketId || !executor.release(record.ticketId)) log(`#${command.iid}: no held turn to start; the next round restarts it`);
2866
+ return;
2867
+ }
2868
+ if (command.verb === "skip" && (record.phase === "waiting" || record.phase === "working")) {
2869
+ await workflowStore.save({
2870
+ ...record,
2871
+ phase: "skipped",
2872
+ at: (/* @__PURE__ */ new Date()).toISOString()
2873
+ });
2874
+ if (record.ticketId) {
2875
+ executor.forget(record.ticketId);
2876
+ try {
2877
+ engine.stopTicket(record.ticketId, "declined");
2878
+ } catch {}
2879
+ }
2880
+ await say(`已跳过 #${command.iid}。`, `skip-${command.iid}`);
2881
+ return;
2882
+ }
2883
+ if (command.verb === "close" && record.phase === "closing") {
2884
+ try {
2885
+ await closeIssue({
2886
+ cli: gitlab.cli,
2887
+ host: gitlab.host,
2888
+ project: gitlab.project,
2889
+ iid: command.iid,
2890
+ signal
2891
+ });
2892
+ await workflowStore.save({
2893
+ ...record,
2894
+ phase: "done",
2895
+ at: (/* @__PURE__ */ new Date()).toISOString()
2896
+ });
2897
+ await say(`已关闭 #${command.iid}。`, `close-${command.iid}`);
2898
+ } catch (error) {
2899
+ await say(`关闭 #${command.iid} 失败:${error.message}`, `close-failed-${command.iid}-${Date.now()}`);
2900
+ }
2901
+ return;
2902
+ }
2903
+ if (command.verb === "keep" && record.phase === "closing") {
2904
+ await workflowStore.save({
2905
+ ...record,
2906
+ phase: "done",
2907
+ at: (/* @__PURE__ */ new Date()).toISOString()
2908
+ });
2909
+ await say(`保留 #${command.iid}。`, `keep-${command.iid}`);
2910
+ return;
2911
+ }
2912
+ await say(`#${command.iid} 现在不接受这个决定。`, `state-${command.iid}-${Date.now()}`);
2913
+ };
2914
+ /** Proposes the next labeled issue when nothing waits for a yes, a turn, or a close. */
2915
+ const proposeIssue = async () => {
2916
+ if (!workflow || !workflowStore || !gitlab) return;
2917
+ if (await workflowStore.active()) return;
2918
+ try {
2919
+ const next = nextIssue(await listOpenIssues({
2920
+ cli: gitlab.cli,
2921
+ host: gitlab.host,
2922
+ project: gitlab.project,
2923
+ label: workflow.label,
2924
+ signal
2925
+ }), new Set((await workflowStore.all()).map((record) => record.iid)));
2926
+ if (!next) return;
2927
+ await workflowStore.save({
2928
+ iid: next.iid,
2929
+ phase: "waiting",
2930
+ at: (/* @__PURE__ */ new Date()).toISOString()
2931
+ });
2932
+ if (engine.receive(issueTrigger({
2933
+ issue: next,
2934
+ host: gitlab.host,
2935
+ project: gitlab.project,
2936
+ agent: login
2937
+ })) !== "duplicate") log(`Proposed issue #${next.iid}: ${next.title}`);
2938
+ } catch (error) {
2939
+ if (!signal.aborted) log(`Could not read the issue queue: ${error.message}`);
2940
+ }
2941
+ };
2942
+ /** Commands being handled, which a finishing run waits for so their answer is not cut off by its own exit. */
2943
+ const commands = /* @__PURE__ */ new Set();
2944
+ const track = (work) => {
2945
+ const tracked = work.catch(() => void 0);
2946
+ commands.add(tracked);
2947
+ tracked.finally(() => {
2948
+ commands.delete(tracked);
2949
+ });
2950
+ };
2577
2951
  const admitted = /* @__PURE__ */ new Set();
2578
2952
  const sync = () => !feishu?.syncChat ? Promise.resolve() : chatMembers(feishu.cli, feishu.syncChat, signal).then((members) => {
2579
2953
  const listed = feishu.allowed.map((id) => id.toLowerCase());
@@ -2619,7 +2993,13 @@ async function runLoop(options) {
2619
2993
  directMessages: feishu?.directMessages ?? true,
2620
2994
  onInvalid: (error) => log(`Ignored an event: ${error}`)
2621
2995
  })).then((trigger) => {
2622
- if (trigger) store(trigger);
2996
+ if (!trigger) return;
2997
+ const command = workflow && trigger.meta?.direct === true && trigger.actor.id === workflow.user ? workflowCommand(trigger.text) : void 0;
2998
+ if (command) {
2999
+ track(handleWorkflowCommand(command));
3000
+ return;
3001
+ }
3002
+ store(trigger);
2623
3003
  }).catch((error) => {
2624
3004
  log(`Could not store an event: ${error.message}`);
2625
3005
  });
@@ -2735,6 +3115,7 @@ async function runLoop(options) {
2735
3115
  if (!signal.aborted) log(`Merge request poll failed: ${error.message}`);
2736
3116
  }
2737
3117
  }
3118
+ if (workflow) await proposeIssue();
2738
3119
  if (twitter) try {
2739
3120
  const triggers = await searchTweets(twitter.cli, twitter.query, {
2740
3121
  seen: (id) => repo.getMeta(`twitter:seen:${id}`) === true,
@@ -2819,15 +3200,7 @@ async function runLoop(options) {
2819
3200
  inRound.clear();
2820
3201
  deliver(engine, repo, delivered, log);
2821
3202
  await repo.flush();
2822
- await send(channel, {
2823
- ...github ? { github: github.cli } : {},
2824
- ...gitlab ? { gitlab: {
2825
- cli: gitlab.cli,
2826
- host: gitlab.host
2827
- } } : {},
2828
- ...feishu ? { feishu: feishu.cli } : {},
2829
- ...twitter ? { twitter: twitter.cli } : {}
2830
- }, log, settings.attention, (id) => repo.setMeta(`outbox:${id}`, true));
3203
+ await send(channel, destinations, log, settings.attention, markSent);
2831
3204
  await repo.flush();
2832
3205
  await sync();
2833
3206
  } catch (error) {
@@ -2844,6 +3217,14 @@ async function runLoop(options) {
2844
3217
  left -= Date.now() - began;
2845
3218
  }
2846
3219
  }
3220
+ if (options.once && options.finish) {
3221
+ await executor.idle();
3222
+ await Promise.allSettled([...commands]);
3223
+ deliver(engine, repo, delivered, log);
3224
+ await repo.flush();
3225
+ await send(channel, destinations, log, settings.attention, markSent);
3226
+ await repo.flush();
3227
+ }
2847
3228
  stop.abort();
2848
3229
  if (options.once && !process.env.VITEST) setImmediate(() => process.exit(process.exitCode ?? 0));
2849
3230
  }
@@ -3424,7 +3805,10 @@ async function poll(dir, once) {
3424
3805
  repo,
3425
3806
  signal: controller.signal,
3426
3807
  log,
3427
- ...once ? { once: true } : {}
3808
+ ...once ? {
3809
+ once: true,
3810
+ finish: true
3811
+ } : {}
3428
3812
  });
3429
3813
  return 0;
3430
3814
  } catch (error) {
package/lib/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as followupOwners, B as ticketOutcome, C as reasonText, D as key, E as ticketStage, F as reached, I as readUntil, L as runningAssignment, M as latestAssignment, N as latestReport, O as USER_ERRORS, P as liveTicket, R as settled, S as REASONS, T as canRetry, V as waitsForPerson, _ as AdmissionDirectionSchema, a as readSettings, b as directionAllowed, c as AGENT_NAMES, d as REPORT_FILE, f as readReport, g as readState, h as FileRepositories, i as parseYaml, j as isoTime, k as UserError, l as installed, n as SettingsSchema, o as stringifyYaml, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor, v as RuleAssessmentSchema, w as said, x as Engine, y as RuleMatchSchema, z as threadKey } from "./settings-BwRUbWkx.mjs";
1
+ import { A as followupOwners, B as ticketOutcome, C as reasonText, D as key, E as ticketStage, F as reached, I as readUntil, L as runningAssignment, M as latestAssignment, N as latestReport, O as USER_ERRORS, P as liveTicket, R as settled, S as REASONS, T as canRetry, V as waitsForPerson, _ as AdmissionDirectionSchema, a as readSettings, b as directionAllowed, c as AGENT_NAMES, d as REPORT_FILE, f as readReport, g as readState, h as FileRepositories, i as parseYaml, j as isoTime, k as UserError, l as installed, n as SettingsSchema, o as stringifyYaml, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor, v as RuleAssessmentSchema, w as said, x as Engine, y as RuleMatchSchema, z as threadKey } from "./settings-BPxaqC93.mjs";
2
2
  // src/core/memory.ts
3
3
  /** In-memory repository implementation for testing and ephemeral engine instances. */
4
4
  const clone = (value) => structuredClone(value);
@@ -2547,7 +2547,9 @@ const ExecutorSchema = z.object({
2547
2547
  /** Shell command that prepares a worktree; `$DSH_SUPERAGENT_*` variables are set before it runs. */
2548
2548
  prepare: z.string().default(""),
2549
2549
  /** Commands a ticket may not run. */
2550
- blockedCommands: z.array(z.string()).default([])
2550
+ blockedCommands: z.array(z.string()).default([]),
2551
+ /** Whether each ticket gets its own worktree and branch. False runs in `checkout`, on its current branch. */
2552
+ worktree: z.boolean().default(true)
2551
2553
  });
2552
2554
  const RuleSchema = z.object({
2553
2555
  /** The id an assessment names; `unasked` is reserved for the verdict that a message asks for work at all. */
@@ -2640,6 +2642,21 @@ const MrReviewSchema = z.object({
2640
2642
  /** Whether merge requests from authors not explicitly in the allowed list may be reviewed. */
2641
2643
  allowCommunityMrs: z.boolean().default(true)
2642
2644
  });
2645
+ /**
2646
+ * The issue-by-issue workflow: propose one labeled issue, ask the operator in Feishu, run it only after a yes, and
2647
+ * close it only after a second yes. The bot asks in a direct message to `user`.
2648
+ */
2649
+ const WorkflowSchema = z.object({
2650
+ enabled: z.boolean().default(false),
2651
+ /** Open issues with this label form the queue; the Phase 0 issue comes first, then iid ascending. */
2652
+ label: z.string().min(1).default("superagent"),
2653
+ /** The Feishu open id the bot asks, in a direct message. */
2654
+ user: z.string().min(1),
2655
+ /** The branch a ticket merges its request into, such as `release/test`; empty means a person merges it. */
2656
+ mergeInto: z.string().default("release/test"),
2657
+ /** Commands run in the ticket's worktree after the turn; their output joins the summary. */
2658
+ verifyCommands: z.array(z.string()).default([])
2659
+ });
2643
2660
  const SettingsSchema = z.object({
2644
2661
  /** Where tickets, triggers and logs live, as an absolute path. */
2645
2662
  stateDir: z.string().min(1),
@@ -2698,6 +2715,8 @@ const SettingsSchema = z.object({
2698
2715
  /** Merge request review, checkout, and verification settings. */
2699
2716
  mrReview: MrReviewSchema.optional()
2700
2717
  }).optional(),
2718
+ /** Issue-by-issue approval workflow, asked and confirmed in Feishu. */
2719
+ workflow: WorkflowSchema.optional(),
2701
2720
  executor: ExecutorSchema.optional().transform((value) => ExecutorSchema.parse(value ?? {})),
2702
2721
  policy: PolicySchema.optional().transform((value) => PolicySchema.parse(value ?? {})),
2703
2722
  /** Who assesses a candidate and with what: the `claude` CLI, or a runner named here. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "superagent-skill",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "type": "module",
5
5
  "description": "A headless, file-backed agent that turns requests from GitHub issues, Feishu chats, or Twitter mentions into tickets and runs each ticket on a configurable coding agent: Claude Code, Codex or opencode.",
6
6
  "bin": {