superagent-skill 0.2.0 → 0.4.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,10 +1,108 @@
1
- import { C as escapeRegExp, D as reasonText, L as latestReport, S as writeEnvironment, T as Engine, U as threadKey, V as runningAssignment, a as readSettings, b as directionAllowed, c as AGENT_NAMES, g as readState, h as FileRepositories, j as key, l as installed, m as runProcess, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor, v as RuleAssessmentSchema, w as sameName, x as runEnvironment } from "./settings-D0qG6Mo8.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-Dud0f9wo.mjs";
2
+ import { createHash } from "node:crypto";
2
3
  import { z } from "zod";
3
- import { access, appendFile, mkdir, readFile, readdir, stat } from "node:fs/promises";
4
- import { dirname, join, resolve } from "node:path";
4
+ import { access, appendFile, lstat, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { delimiter, dirname, join, resolve } from "node:path";
5
6
  import { execFile, spawn } from "node:child_process";
6
7
  import { homedir } from "node:os";
7
8
  import { fileURLToPath } from "node:url";
9
+ // src/infra/environment.ts
10
+ /**
11
+ * Writes the CLI shims and the isolated git configuration that bind a run to the agent's accounts.
12
+ *
13
+ * Each shim strips its own directory from PATH before it execs, so a wrapper script that resolves `gh` by name reaches the
14
+ * real binary instead of looping. The git configuration replaces the operator's global configuration for the run, so a
15
+ * worker cannot push with the operator's credentials.
16
+ *
17
+ * These are guardrails, not an OS boundary: a run shares the operator's OS user and can read their home directory.
18
+ */
19
+ const MARKER = "# Written by superagent on every start; edits are lost.";
20
+ /** Commands the shims provide, which a blocked list must never shadow. */
21
+ const WORKER_COMMANDS = [
22
+ "gh",
23
+ "git",
24
+ "lark-cli"
25
+ ];
26
+ const workerBin = (stateDir) => join(stateDir, "worker-bin");
27
+ const workerGitConfig = (stateDir) => join(stateDir, "worker-gitconfig");
28
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
29
+ const gitQuote = (value) => `"${value.replace(/[\\"]/g, (char) => `\\${char}`)}"`;
30
+ const credentialHelper = (cli) => `!${shellQuote(cli)} auth git-credential`;
31
+ async function written(file) {
32
+ try {
33
+ const stat = await lstat(file);
34
+ if (!stat.isFile() || stat.size > 4096) return false;
35
+ return (await readFile(file, "utf8")).includes(MARKER);
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+ async function own(file, content) {
41
+ const temporary = `${file}.${process.pid}.tmp`;
42
+ await writeFile(temporary, content, { mode: 384 });
43
+ await rename(temporary, file);
44
+ }
45
+ /**
46
+ * Writes the shims and git configuration, refusing to overwrite files it did not write.
47
+ * @throws when a file in the shim directory or at the git configuration path was written by something else.
48
+ */
49
+ async function writeEnvironment(accounts, blockedCommands) {
50
+ const dir = workerBin(accounts.stateDir);
51
+ await mkdir(dir, { recursive: true });
52
+ const before = await readdir(dir);
53
+ for (const name of before) if (!await written(join(dir, name))) throw new Error(`The file ${join(dir, name)} was not written by superagent; move it away or choose another state directory.`);
54
+ const kept = /* @__PURE__ */ new Set();
55
+ const shim = async (name, body) => {
56
+ const temporary = join(dir, `.${name}.${process.pid}.tmp`);
57
+ await writeFile(temporary, `#!/bin/sh\n${MARKER}\n${body}\n`, { mode: 493 });
58
+ await rename(temporary, join(dir, name));
59
+ kept.add(name);
60
+ };
61
+ const withoutShims = [
62
+ `self=${shellQuote(dir)}`,
63
+ "rest=",
64
+ "IFS=:",
65
+ "set -f",
66
+ "for entry in $PATH; do [ \"$entry\" = \"$self\" ] || rest=\"${rest:+$rest:}$entry\"; done",
67
+ "set +f",
68
+ "unset IFS",
69
+ "PATH=$rest",
70
+ "export PATH"
71
+ ].join("\n");
72
+ const run = (program) => `${withoutShims}\nexec ${shellQuote(program)} "$@"`;
73
+ const fail = (message) => `echo ${shellQuote(message)} >&2\nexit 1`;
74
+ await shim("gh", run(accounts.githubCli));
75
+ 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}.`));
77
+ for (const name of before) if (!kept.has(name)) await unlink(join(dir, name));
78
+ await own(workerGitConfig(accounts.stateDir), [
79
+ MARKER,
80
+ "[user]",
81
+ " useConfigOnly = true",
82
+ "[credential]",
83
+ " 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:",
89
+ "[filter \"lfs\"]",
90
+ " clean = git-lfs clean -- %f",
91
+ " smudge = git-lfs smudge -- %f",
92
+ " process = git-lfs filter-process",
93
+ " required = true"
94
+ ].join("\n") + "\n");
95
+ }
96
+ /** Environment variables a run receives, with the shim directory first on PATH. */
97
+ function runEnvironment(accounts, variables) {
98
+ return {
99
+ ...variables,
100
+ PATH: [workerBin(accounts.stateDir), process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"].join(delimiter),
101
+ GIT_CONFIG_GLOBAL: workerGitConfig(accounts.stateDir),
102
+ GIT_CONFIG_SYSTEM: "/dev/null",
103
+ GIT_TERMINAL_PROMPT: "0"
104
+ };
105
+ }
8
106
  // src/infra/commands.ts
9
107
  /** Runs the Source CLIs (`gh`, `lark-cli`) and reads their JSON. Every call is bounded and never prompts. */
10
108
  var CliError = class extends Error {
@@ -50,7 +148,7 @@ async function runJson(program, argv, options = {}) {
50
148
  const error = parsed.error;
51
149
  throw new CliError(program, `${program} ${argv.join(" ")}: ${error?.message ?? "failed"}`, text, "");
52
150
  }
53
- if (parsed && typeof parsed === "object" && "code" in parsed && "data" in parsed) return parsed.data;
151
+ if (parsed && typeof parsed === "object" && ("code" in parsed || "ok" in parsed) && "data" in parsed) return parsed.data;
54
152
  return parsed;
55
153
  }
56
154
  // src/prompts.ts
@@ -71,8 +169,54 @@ const STANDING_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "prompt
71
169
  async function standingRules() {
72
170
  return Promise.all(STANDING_FILES.map(async (name) => (await readFile(join(STANDING_DIR, name), "utf8")).trim()));
73
171
  }
172
+ /** Composes the prompt for reviewing and verifying a pull request. */
173
+ function composePrReviewPrompt(input) {
174
+ 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)}`;
176
+ return [
177
+ `# Ticket ${ticket.id} — Pull Request #${prNumber} Review & Verification`,
178
+ "",
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}\`.`,
182
+ "",
183
+ "## The Pull Request",
184
+ "",
185
+ asked,
186
+ ...notes.filter(Boolean).flatMap((note) => [
187
+ "",
188
+ "## Notes since the start",
189
+ "",
190
+ quote(note)
191
+ ]),
192
+ "",
193
+ "## Automated Local Verification Report",
194
+ "",
195
+ prVerification ? prVerification.markdown : "No automated verification commands were configured.",
196
+ "",
197
+ "## Review Instructions & Standards",
198
+ "",
199
+ "- **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."] : [],
202
+ "- **Decision Standards**:",
203
+ 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
+ " - 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.",
206
+ "",
207
+ ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
208
+ ...instructions.trim() ? [
209
+ "",
210
+ "## Team instructions",
211
+ "",
212
+ instructions.trim()
213
+ ] : [],
214
+ reportInstructions()
215
+ ].join("\n");
216
+ }
74
217
  /** Composes the prompt for one ticket: who asked, what they asked, and what the agent must not assume. */
75
218
  function composePrompt(input) {
219
+ if (input.isPrReview && input.prNumber) return composePrReviewPrompt(input);
76
220
  const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch, standing = [], notes = [] } = input;
77
221
  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)}`;
78
222
  return [
@@ -97,6 +241,7 @@ function composePrompt(input) {
97
241
  "- Run the tests the repository has. Do not claim a check passed unless you ran it.",
98
242
  "- Do not merge the pull request. A person merges it.",
99
243
  "- If the request needs a decision you cannot make, stop and ask one concrete question.",
244
+ ...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."] : [],
100
245
  ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
101
246
  ...instructions.trim() ? [
102
247
  "",
@@ -124,6 +269,20 @@ function quote(text) {
124
269
  /** Which sources this installation's Sources read, and whether they read every message in that scope. */
125
270
  function sourceScope(settings) {
126
271
  return { scope: (input) => {
272
+ if (input.source === "timer" || input.source === "watcher") return {
273
+ listened: true,
274
+ observed: true
275
+ };
276
+ if (input.source === "twitter") {
277
+ if (!settings.twitter?.enabled) return {
278
+ listened: false,
279
+ reason: "sourceOff"
280
+ };
281
+ return {
282
+ listened: true,
283
+ observed: true
284
+ };
285
+ }
127
286
  if (input.source === "feishu") {
128
287
  if (!settings.feishu?.enabled) return {
129
288
  listened: false,
@@ -153,7 +312,7 @@ function sourceScope(settings) {
153
312
  };
154
313
  return {
155
314
  listened: true,
156
- observed: false
315
+ observed: Boolean(input.meta.isPr) && Boolean(settings.github.prReview?.enabled)
157
316
  };
158
317
  } };
159
318
  }
@@ -161,17 +320,40 @@ function sourceScope(settings) {
161
320
  const UNASKED_RULE = "unasked";
162
321
  /** The Policy of one settings file, rebuilt whenever the round reads it. */
163
322
  function buildPolicy(settings, scope) {
164
- const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
323
+ const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : source === "twitter" ? settings.twitter?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
165
324
  return {
166
325
  version: `${settings.policy.mode}:${settings.policy.rules.filter((rule) => rule.enabled).map((rule) => rule.id).join(",")}`,
167
326
  paused: false,
168
327
  evalTimeoutMs: 12e4,
169
328
  gate: (trigger, _thread, _tickets, received) => {
329
+ if (trigger.source === "timer" || trigger.source === "watcher") return {
330
+ admissible: true,
331
+ strength: "inferred",
332
+ basis: {
333
+ via: "admission",
334
+ cell: "listedUnaddressed"
335
+ }
336
+ };
337
+ if (trigger.source === "github" && Boolean(trigger.meta?.isPr) && Boolean(settings.github?.prReview?.enabled) && settings.github?.prReview?.allowCommunityPrs !== false) {
338
+ const addressed = !!trigger.addressed;
339
+ const basis = addressed ? {
340
+ via: "listed",
341
+ addressed: trigger.addressed
342
+ } : {
343
+ via: "admission",
344
+ cell: "listedUnaddressed"
345
+ };
346
+ return {
347
+ admissible: true,
348
+ strength: addressed ? "explicit" : "inferred",
349
+ basis
350
+ };
351
+ }
170
352
  if (!trigger.human) return {
171
353
  admissible: false,
172
354
  reason: "bot"
173
355
  };
174
- const allowed = people(trigger.source).has(trigger.actor.id.toLowerCase());
356
+ const allowed = trigger.source === "twitter" && settings.twitter?.allowed.length === 0 ? true : people(trigger.source).has(trigger.actor.id.toLowerCase());
175
357
  const seen = received ?? scope.scope(trigger);
176
358
  const observed = seen.listened && seen.observed;
177
359
  const addressed = !!trigger.addressed;
@@ -257,6 +439,256 @@ function assessmentOutcome(assessment, settings, strength) {
257
439
  };
258
440
  return accept;
259
441
  }
442
+ // src/infra/presence.ts
443
+ /**
444
+ * Human presence detection and attention management.
445
+ *
446
+ * Implements the "Don't let the agent guess your presence" and "Start quiet" principles from Anthropic's
447
+ * "Building always-on agents" and FanBox practice: detect system-level input idle time, route notifications
448
+ * to local terminal/desktop when user is at their machine, and dispatch to mobile (Feishu/etc.) only when
449
+ * user is away or during active attention requests, respecting quiet hours.
450
+ */
451
+ /**
452
+ * Determines whether a given time falls within configured quiet hours.
453
+ * Supports intervals that cross midnight (e.g. 23:00 to 08:00).
454
+ */
455
+ function isQuietHours(now = /* @__PURE__ */ new Date(), config) {
456
+ if (!config || !config.enabled) return false;
457
+ const [startH = 23, startM = 0] = (config.start || "23:00").split(":").map(Number);
458
+ const [endH = 8, endM = 0] = (config.end || "08:00").split(":").map(Number);
459
+ const currentMinutes = now.getHours() * 60 + now.getMinutes();
460
+ const startMinutes = startH * 60 + startM;
461
+ const endMinutes = endH * 60 + endM;
462
+ if (startMinutes <= endMinutes) return currentMinutes >= startMinutes && currentMinutes < endMinutes;
463
+ return currentMinutes >= startMinutes || currentMinutes < endMinutes;
464
+ }
465
+ /**
466
+ * Returns estimated system idle seconds (time since last user keyboard/mouse/console input).
467
+ * Uses macOS /dev/console mtime or ioreg, falls back to 0.
468
+ */
469
+ async function getSystemIdleSeconds() {
470
+ try {
471
+ const s = await stat("/dev/console");
472
+ const idleSeconds = Math.max(0, Math.floor((Date.now() - s.mtimeMs) / 1e3));
473
+ if (Number.isFinite(idleSeconds)) return idleSeconds;
474
+ } catch {}
475
+ try {
476
+ const out = await run("/bin/sh", ["-c", "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print int($NF/1000000000); exit}'"], { timeoutMs: 2e3 });
477
+ const idle = parseInt(out.trim(), 10);
478
+ if (!Number.isNaN(idle) && idle >= 0) return idle;
479
+ } catch {}
480
+ return 0;
481
+ }
482
+ /**
483
+ * Determines whether a human user is currently active at the local machine.
484
+ * When idle time is below thresholdSeconds (default 300s = 5m), the user is considered present.
485
+ */
486
+ async function isUserPresent(thresholdSeconds = 300, idleProvider = getSystemIdleSeconds) {
487
+ try {
488
+ return await idleProvider() < thresholdSeconds;
489
+ } catch {
490
+ return false;
491
+ }
492
+ }
493
+ // src/infra/budget.ts
494
+ var BudgetGuard = class {
495
+ config;
496
+ storage;
497
+ constructor(config, storage) {
498
+ this.config = config;
499
+ this.storage = storage;
500
+ }
501
+ /** Checks if an autonomous wakeup is currently permitted under budget rules. */
502
+ async check(now = /* @__PURE__ */ new Date()) {
503
+ const today = now.toISOString().slice(0, 10);
504
+ const current = await this.storage.get() ?? {
505
+ date: today,
506
+ autonomousWakes: 0
507
+ };
508
+ const state = current.date === today ? current : {
509
+ date: today,
510
+ autonomousWakes: 0
511
+ };
512
+ if (state.autonomousWakes >= this.config.maxAutonomousWakesPerDay) return {
513
+ allowed: false,
514
+ reason: `Daily autonomous limit reached (${state.autonomousWakes}/${this.config.maxAutonomousWakesPerDay})`
515
+ };
516
+ if (state.lastWakeAt && this.config.autonomousCooldownSeconds > 0) {
517
+ const elapsedSeconds = Math.floor((now.getTime() - new Date(state.lastWakeAt).getTime()) / 1e3);
518
+ if (elapsedSeconds < this.config.autonomousCooldownSeconds) return {
519
+ allowed: false,
520
+ reason: `Autonomous cooldown active (${this.config.autonomousCooldownSeconds - elapsedSeconds}s remaining of ${this.config.autonomousCooldownSeconds}s)`
521
+ };
522
+ }
523
+ return { allowed: true };
524
+ }
525
+ /** Records that an autonomous wakeup has occurred, incrementing counter and recording timestamp. */
526
+ async record(now = /* @__PURE__ */ new Date()) {
527
+ const today = now.toISOString().slice(0, 10);
528
+ const current = await this.storage.get() ?? {
529
+ date: today,
530
+ autonomousWakes: 0
531
+ };
532
+ const state = current.date === today ? { ...current } : {
533
+ date: today,
534
+ autonomousWakes: 0
535
+ };
536
+ state.autonomousWakes += 1;
537
+ state.lastWakeAt = now.toISOString();
538
+ await this.storage.set(state);
539
+ return state;
540
+ }
541
+ };
542
+ // src/infra/timers.ts
543
+ /**
544
+ * Durable timers engine for proactive and autonomous agent runs.
545
+ *
546
+ * Implements the "Timers" primitive from Anthropic's "Building always-on agents":
547
+ * 1) Follow-ups: Short-term checkpoints scheduled by the agent or tickets (e.g. check CI in 15m).
548
+ * 2) Schedules: Recurring cron/interval-based jobs (e.g. daily standup, repo hygiene).
549
+ *
550
+ * Expired timers generate synthetic events for the Event Inbox, allowing the agent to sleep between runs.
551
+ */
552
+ var TimerStore = class {
553
+ dir;
554
+ constructor(dir) {
555
+ this.dir = dir;
556
+ }
557
+ timersDir() {
558
+ return join(this.dir, "timers");
559
+ }
560
+ async init() {
561
+ await mkdir(this.timersDir(), { recursive: true });
562
+ }
563
+ async list() {
564
+ await this.init();
565
+ const entries = await readdir(this.timersDir()).catch(() => []);
566
+ const timers = [];
567
+ for (const entry of entries) {
568
+ if (!entry.endsWith(".json")) continue;
569
+ try {
570
+ const raw = await readFile(join(this.timersDir(), entry), "utf8");
571
+ timers.push(JSON.parse(raw));
572
+ } catch {}
573
+ }
574
+ return timers.sort((a, b) => a.dueAt.localeCompare(b.dueAt));
575
+ }
576
+ async save(timer) {
577
+ await this.init();
578
+ const path = join(this.timersDir(), `${timer.id}.json`);
579
+ await writeFile(path, JSON.stringify(timer, null, 2), "utf8");
580
+ }
581
+ async remove(id) {
582
+ await this.init();
583
+ await rm(join(this.timersDir(), `${id}.json`), { force: true });
584
+ }
585
+ async getDue(now = /* @__PURE__ */ new Date()) {
586
+ const all = await this.list();
587
+ const nowIso = now.toISOString();
588
+ return all.filter((timer) => timer.dueAt <= nowIso);
589
+ }
590
+ /**
591
+ * Advances a recurring schedule timer or removes a one-shot follow-up timer.
592
+ */
593
+ async processDue(timer, now = /* @__PURE__ */ new Date()) {
594
+ if (timer.kind === "schedule" && timer.intervalMinutes && timer.intervalMinutes > 0) {
595
+ const nextDue = new Date(now.getTime() + timer.intervalMinutes * 6e4).toISOString();
596
+ const updated = {
597
+ ...timer,
598
+ dueAt: nextDue,
599
+ lastRunAt: now.toISOString()
600
+ };
601
+ await this.save(updated);
602
+ } else await this.remove(timer.id);
603
+ }
604
+ };
605
+ // src/infra/watchers.ts
606
+ /**
607
+ * Active watchers ("盯梢") for pull-based external sources without webhooks.
608
+ *
609
+ * Implements the "Not all events push themselves" lesson from FanBox and Anthropic:
610
+ * Periodically executes a lightweight command (e.g. `gh pr list`, `git fetch`), compares the output fingerprint,
611
+ * and produces a synthetic trigger only when new lines or status changes occur.
612
+ */
613
+ var WatcherEngine = class {
614
+ dir;
615
+ constructor(dir) {
616
+ this.dir = dir;
617
+ }
618
+ watchersDir() {
619
+ return join(this.dir, "watchers");
620
+ }
621
+ async init() {
622
+ await mkdir(this.watchersDir(), { recursive: true });
623
+ }
624
+ async getState(id) {
625
+ await this.init();
626
+ try {
627
+ const raw = await readFile(join(this.watchersDir(), `${id}.json`), "utf8");
628
+ return JSON.parse(raw);
629
+ } catch {
630
+ return;
631
+ }
632
+ }
633
+ async saveState(state) {
634
+ await this.init();
635
+ await writeFile(join(this.watchersDir(), `${state.id}.json`), JSON.stringify(state, null, 2), "utf8");
636
+ }
637
+ /**
638
+ * Checks whether the watcher is due for execution.
639
+ */
640
+ isDue(watcher, state, now = /* @__PURE__ */ new Date()) {
641
+ if (!state?.lastRunAt) return true;
642
+ return (now.getTime() - new Date(state.lastRunAt).getTime()) / 6e4 >= watcher.intervalMinutes;
643
+ }
644
+ /**
645
+ * Runs the watcher command, checks for output changes, and updates persistent state.
646
+ */
647
+ async check(watcher, options = {}) {
648
+ const now = options.now ?? /* @__PURE__ */ new Date();
649
+ const runner = options.runner ?? (async (cmd) => run("/bin/sh", ["-c", cmd], { timeoutMs: 3e4 }));
650
+ const state = await this.getState(watcher.id);
651
+ if (!this.isDue(watcher, state, now)) return { triggered: false };
652
+ let output = "";
653
+ try {
654
+ output = await runner(watcher.command);
655
+ } catch (error) {
656
+ return {
657
+ triggered: false,
658
+ error: error.message
659
+ };
660
+ }
661
+ const trimmed = output.trim();
662
+ const hash = createHash("sha256").update(trimmed).digest("hex");
663
+ if (!state) {
664
+ await this.saveState({
665
+ id: watcher.id,
666
+ lastRunAt: now.toISOString(),
667
+ lastOutputHash: hash,
668
+ lastOutputPreview: trimmed.slice(0, 500)
669
+ });
670
+ return { triggered: false };
671
+ }
672
+ if (state.lastOutputHash === hash) {
673
+ await this.saveState({
674
+ ...state,
675
+ lastRunAt: now.toISOString()
676
+ });
677
+ return { triggered: false };
678
+ }
679
+ const diff = `Watcher "${watcher.id}" detected change in command output:\n\n${trimmed.slice(0, 2e3)}\n\nInstruction: ${watcher.instruction}`;
680
+ await this.saveState({
681
+ id: watcher.id,
682
+ lastRunAt: now.toISOString(),
683
+ lastOutputHash: hash,
684
+ lastOutputPreview: trimmed.slice(0, 500)
685
+ });
686
+ return {
687
+ triggered: true,
688
+ diffText: diff
689
+ };
690
+ }
691
+ };
260
692
  // src/assess.ts
261
693
  /**
262
694
  * The assessment of a candidate a person did not address to the agent.
@@ -387,16 +819,36 @@ function assessing(options) {
387
819
  let outcome;
388
820
  try {
389
821
  const settings = options.settings();
390
- outcome = explicit ? {
822
+ const trigger = candidate.triggers[0];
823
+ const isAutonomousTrigger = trigger?.source === "timer" || trigger?.source === "watcher";
824
+ const isPrReview = trigger?.source === "github" && Boolean(trigger?.meta?.isPr) && Boolean(settings.github?.prReview?.enabled);
825
+ if (isAutonomousTrigger) outcome = {
826
+ kind: "accept",
827
+ title: trigger?.text.split("\n")[0]?.slice(0, 60) || "Autonomous Task",
828
+ scope: "autonomous",
829
+ reason: `Autonomous trigger from ${trigger?.source}`
830
+ };
831
+ else if (isPrReview) {
832
+ const prNum = trigger?.meta?.number;
833
+ outcome = {
834
+ kind: "accept",
835
+ title: `Review PR #${prNum}: ${trigger?.text.split("\n")[0]?.replace(/^#\s*Pull Request Review:\s*/i, "").trim() || `PR #${prNum}`}`.slice(0, 60),
836
+ scope: "pr_review",
837
+ reason: `Pull request review for #${prNum}`
838
+ };
839
+ } else if (explicit) outcome = {
391
840
  kind: "accept",
392
841
  ...named(candidate),
393
842
  scope: "",
394
843
  reason: "A person addressed the agent"
395
- } : assessmentOutcome(await options.next(candidate), settings, candidate.strength);
396
- if (!explicit && outcome.kind === "accept" && !settings.policy.rules.some((rule) => rule.id === "unasked")) outcome = {
397
- kind: "ignore",
398
- reason: "The assessment accepts, but no `unasked` rule is enabled"
399
844
  };
845
+ else {
846
+ outcome = assessmentOutcome(await options.next(candidate), settings, candidate.strength);
847
+ if (outcome.kind === "accept" && !settings.policy.rules.some((rule) => rule.id === "unasked")) outcome = {
848
+ kind: "ignore",
849
+ reason: "The assessment accepts, but no `unasked` rule is enabled"
850
+ };
851
+ }
400
852
  } catch (error) {
401
853
  outcome = {
402
854
  kind: "unavailable",
@@ -422,6 +874,10 @@ function assessing(options) {
422
874
  }
423
875
  };
424
876
  }
877
+ new Intl.Segmenter("zh", { granularity: "word" });
878
+ /** Case-insensitive comparison for GitHub logins and repository names. */
879
+ const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
880
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
425
881
  // src/sources/github.ts
426
882
  /**
427
883
  * The GitHub Source: turns new mentions and new Issues in one repository into Triggers.
@@ -433,15 +889,15 @@ function assessing(options) {
433
889
  * A notification only says that something mentioned the account. The comment itself is read afterwards, so the Trigger
434
890
  * carries what the person wrote, not the notification's summary.
435
891
  */
436
- const SOURCE$1 = "github";
892
+ const SOURCE$2 = "github";
437
893
  /** A thread identifier for an Issue or pull request number; both share one sequence in GitHub. */
438
894
  const githubThread = (number) => ({
439
- source: SOURCE$1,
895
+ source: SOURCE$2,
440
896
  id: String(number)
441
897
  });
442
898
  /** Where a reply to this number goes. */
443
899
  const githubChannel = (repository, number, url) => ({
444
- source: SOURCE$1,
900
+ source: SOURCE$2,
445
901
  thread: threadKey(githubThread(number)),
446
902
  address: {
447
903
  number: String(number),
@@ -516,10 +972,10 @@ function commentTrigger(input) {
516
972
  const login = comment.user.login;
517
973
  return {
518
974
  id: key("github-comment", url, String(comment.id ?? ""), at),
519
- source: SOURCE$1,
975
+ source: SOURCE$2,
520
976
  threads: [githubThread(number)],
521
977
  actor: {
522
- source: SOURCE$1,
978
+ source: SOURCE$2,
523
979
  id: login
524
980
  },
525
981
  human: isHumanLogin(comment.user) && !sameName(login, agent),
@@ -582,6 +1038,69 @@ async function pollNotifications(input) {
582
1038
  }
583
1039
  return triggers;
584
1040
  }
1041
+ z.looseObject({
1042
+ number: z.number(),
1043
+ title: z.string(),
1044
+ body: z.string().nullish(),
1045
+ author: UserSchema,
1046
+ updatedAt: z.string().nullish(),
1047
+ url: z.string().nullish(),
1048
+ headRefName: z.string().nullish(),
1049
+ headRepositoryOwner: z.looseObject({ login: z.string() }).nullish()
1050
+ });
1051
+ /**
1052
+ * Polls currently open pull requests for `repository` and returns Triggers for new or updated PRs.
1053
+ */
1054
+ async function pollOpenPullRequests(input) {
1055
+ let prs = [];
1056
+ try {
1057
+ prs = await runJson(input.cli, [
1058
+ "pr",
1059
+ "list",
1060
+ "--repo",
1061
+ input.repository,
1062
+ "--state",
1063
+ "open",
1064
+ "--json",
1065
+ "number,title,body,author,updatedAt,url,headRefName,headRepositoryOwner"
1066
+ ], { signal: input.signal });
1067
+ } catch {
1068
+ return [];
1069
+ }
1070
+ const triggers = [];
1071
+ for (const pr of prs) {
1072
+ if (sameName(pr.author.login, input.agent)) continue;
1073
+ const at = pr.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
1074
+ const prKey = key("github-pr-review", input.repository, String(pr.number), at);
1075
+ if (input.seen(prKey)) continue;
1076
+ const url = pr.url ?? githubPage(input.repository, pr.number, true);
1077
+ triggers.push({
1078
+ id: prKey,
1079
+ source: SOURCE$2,
1080
+ threads: [githubThread(pr.number)],
1081
+ actor: {
1082
+ source: SOURCE$2,
1083
+ id: pr.author.login
1084
+ },
1085
+ human: isHumanLogin(pr.author) && !sameName(pr.author.login, input.agent),
1086
+ addressed: "mention",
1087
+ at,
1088
+ text: `# Pull Request Review: #${pr.number} ${pr.title}\n\nAuthor: @${pr.author.login}\nURL: ${url}\n\n${pr.body ?? ""}`,
1089
+ channel: githubChannel(input.repository, pr.number, url),
1090
+ url,
1091
+ meta: {
1092
+ number: pr.number,
1093
+ isPr: true,
1094
+ kind: "pull_review",
1095
+ repository: input.repository,
1096
+ author: pr.author.login,
1097
+ updatedAt: at
1098
+ }
1099
+ });
1100
+ input.mark(prKey);
1101
+ }
1102
+ return triggers;
1103
+ }
585
1104
  // src/sources/feishu.ts
586
1105
  /**
587
1106
  * The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
@@ -592,17 +1111,17 @@ async function pollNotifications(input) {
592
1111
  * A chat is listened to only when `settings.feishu.chats` names it, because a bot in a busy chat sees everything and a
593
1112
  * Trigger per message would cost the team attention for nothing.
594
1113
  */
595
- const SOURCE = "feishu";
1114
+ const SOURCE$1 = "feishu";
596
1115
  /** The event the Feishu bot subscribes to: a message sent to it or in a chat it is in. The key is generated by Feishu for
597
1116
  * the app's event subscription, so read it from `lark-cli event list` rather than assume it. */
598
1117
  const MESSAGE_EVENT = "im.message.receive_v1";
599
1118
  const feishuThread = (chatId, rootId, messageId) => ({
600
- source: SOURCE,
1119
+ source: SOURCE$1,
601
1120
  id: `${chatId}:${rootId ?? messageId}`
602
1121
  });
603
1122
  /** Where a reply to this message goes; `direct` is explicit because group and direct chat ids both start with `oc_`. */
604
1123
  const feishuChannel = (chatId, messageId, direct = false) => ({
605
- source: SOURCE,
1124
+ source: SOURCE$1,
606
1125
  thread: `feishu:${chatId}`,
607
1126
  address: {
608
1127
  chatId,
@@ -661,10 +1180,10 @@ function feishuTrigger(input, options) {
661
1180
  const url = event.message_app_link;
662
1181
  return {
663
1182
  id: key("feishu", event.message_id),
664
- source: SOURCE,
1183
+ source: SOURCE$1,
665
1184
  threads: [feishuThread(event.chat_id, event.root_id, event.message_id)],
666
1185
  actor: {
667
- source: SOURCE,
1186
+ source: SOURCE$1,
668
1187
  id: senderId
669
1188
  },
670
1189
  human: senderType === "user",
@@ -717,9 +1236,7 @@ async function chatMembers(cli, chatId, signal) {
717
1236
  chatId,
718
1237
  "--member-types",
719
1238
  "user",
720
- "--page-all",
721
- "--page-limit",
722
- "0"
1239
+ "--page-all"
723
1240
  ], { signal })).users ?? []).map((user) => ({
724
1241
  id: user.member_id,
725
1242
  name: user.name ?? user.member_id
@@ -891,6 +1408,97 @@ function consumeEvents(options) {
891
1408
  ended
892
1409
  };
893
1410
  }
1411
+ // src/sources/twitter.ts
1412
+ /**
1413
+ * The Twitter/X Source: searches keywords using `opencli twitter search` and turns feedback into Triggers,
1414
+ * and delivers responses back to the original tweet via `opencli twitter reply`.
1415
+ */
1416
+ const SOURCE = "twitter";
1417
+ z.looseObject({
1418
+ id: z.string(),
1419
+ author: z.string(),
1420
+ text: z.string(),
1421
+ created_at: z.string().nullish(),
1422
+ url: z.string()
1423
+ });
1424
+ const twitterThread = (id) => ({
1425
+ source: SOURCE,
1426
+ id
1427
+ });
1428
+ const twitterChannel = (url, id) => ({
1429
+ source: SOURCE,
1430
+ thread: threadKey(twitterThread(id)),
1431
+ address: {
1432
+ tweetUrl: url,
1433
+ tweetId: id
1434
+ }
1435
+ });
1436
+ function tweetTrigger(tweet, agentLogin) {
1437
+ const at = tweet.created_at ?? (/* @__PURE__ */ new Date()).toISOString();
1438
+ const addressed = agentLogin && tweet.text.toLowerCase().includes(`@${agentLogin.toLowerCase()}`);
1439
+ return {
1440
+ id: key("twitter-tweet", tweet.id),
1441
+ source: SOURCE,
1442
+ threads: [twitterThread(tweet.id)],
1443
+ actor: {
1444
+ source: SOURCE,
1445
+ id: tweet.author
1446
+ },
1447
+ human: true,
1448
+ ...addressed ? { addressed: "mention" } : {},
1449
+ at,
1450
+ text: tweet.text,
1451
+ url: tweet.url,
1452
+ channel: twitterChannel(tweet.url, tweet.id),
1453
+ meta: {
1454
+ tweetId: tweet.id,
1455
+ author: tweet.author
1456
+ }
1457
+ };
1458
+ }
1459
+ async function searchTweets(cli, query, options = {}) {
1460
+ const limit = options.limit ?? 15;
1461
+ const tweets = await runJson(cli, [
1462
+ "twitter",
1463
+ "search",
1464
+ query,
1465
+ "--product",
1466
+ "live",
1467
+ "--limit",
1468
+ String(limit),
1469
+ "-f",
1470
+ "json"
1471
+ ], { signal: options.signal });
1472
+ const list = Array.isArray(tweets) ? tweets : [];
1473
+ const triggers = [];
1474
+ for (const item of list) {
1475
+ if (!item.id || !item.text) continue;
1476
+ if (options.seen?.(item.id)) continue;
1477
+ options.mark?.(item.id);
1478
+ triggers.push(tweetTrigger(item, options.agentLogin));
1479
+ }
1480
+ return triggers;
1481
+ }
1482
+ async function replyTweet(cli, tweetUrl, text, options = {}) {
1483
+ await run(cli, [
1484
+ "twitter",
1485
+ "reply",
1486
+ tweetUrl,
1487
+ text
1488
+ ], { signal: options.signal });
1489
+ }
1490
+ async function twitterAccount(cli, signal) {
1491
+ try {
1492
+ return (await runJson(cli, [
1493
+ "twitter",
1494
+ "whoami",
1495
+ "-f",
1496
+ "json"
1497
+ ], { signal })).username ?? "";
1498
+ } catch {
1499
+ return "";
1500
+ }
1501
+ }
894
1502
  // src/infra/worktree.ts
895
1503
  /**
896
1504
  * Gives a ticket its own git worktree and branch, so two tickets can change one repository at once and neither sees the
@@ -926,15 +1534,63 @@ async function isGitRepository(directory) {
926
1534
  }
927
1535
  /**
928
1536
  * 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.
929
1538
  *
930
1539
  * @throws when git cannot create the worktree, such as when the checkout has no commit yet; the caller then reports the
931
1540
  * ticket as failed instead of starting an agent in a directory that is not the repository.
932
1541
  */
933
1542
  async function prepareWorktree(options) {
934
- const { checkout, directory, branch, signal } = options;
1543
+ const { checkout, directory, branch, prNumber, repository, signal } = options;
935
1544
  await mkdir(directory, { recursive: true });
936
1545
  if ((await readdir(directory)).length) return directory;
937
1546
  if (!await isGitRepository(checkout)) return directory;
1547
+ if (prNumber) {
1548
+ let fetched = false;
1549
+ try {
1550
+ await run("git", [
1551
+ "-C",
1552
+ checkout,
1553
+ "fetch",
1554
+ "origin",
1555
+ `pull/${prNumber}/head:${branch}`
1556
+ ], {
1557
+ signal,
1558
+ timeoutMs: 6e4
1559
+ });
1560
+ fetched = true;
1561
+ } catch {
1562
+ if (repository) try {
1563
+ await run("git", [
1564
+ "-C",
1565
+ checkout,
1566
+ "fetch",
1567
+ `https://github.com/${repository}.git`,
1568
+ `pull/${prNumber}/head:${branch}`
1569
+ ], {
1570
+ signal,
1571
+ timeoutMs: 6e4
1572
+ });
1573
+ fetched = true;
1574
+ } catch {}
1575
+ }
1576
+ if (fetched) {
1577
+ await run("git", [
1578
+ "-C",
1579
+ checkout,
1580
+ "worktree",
1581
+ "add",
1582
+ directory,
1583
+ branch
1584
+ ], {
1585
+ signal,
1586
+ timeoutMs: 12e4
1587
+ }).catch(async (error) => {
1588
+ await removeWorktree(checkout, directory, signal, branch);
1589
+ throw new Error(`${directory} is not a branch point for PR #${prNumber}: ${error.message}`, { cause: error });
1590
+ });
1591
+ return directory;
1592
+ }
1593
+ }
938
1594
  await run("git", [
939
1595
  "-C",
940
1596
  checkout,
@@ -956,13 +1612,13 @@ async function prepareWorktree(options) {
956
1612
  signal,
957
1613
  timeoutMs: 12e4
958
1614
  }).catch(async (error) => {
959
- await removeWorktree(checkout, directory, signal);
1615
+ await removeWorktree(checkout, directory, signal, branch);
960
1616
  throw new Error(`${directory} is not a branch point: ${error.message}`, { cause: error });
961
1617
  });
962
1618
  return directory;
963
1619
  }
964
1620
  /** Removes a ticket's worktree once its ticket ended, so the state directory does not grow without bound. */
965
- async function removeWorktree(checkout, directory, signal) {
1621
+ async function removeWorktree(checkout, directory, signal, branchToDelete) {
966
1622
  try {
967
1623
  await run("git", [
968
1624
  "-C",
@@ -976,6 +1632,76 @@ async function removeWorktree(checkout, directory, signal) {
976
1632
  timeoutMs: 12e4
977
1633
  });
978
1634
  } catch {}
1635
+ if (branchToDelete) try {
1636
+ await run("git", [
1637
+ "-C",
1638
+ checkout,
1639
+ "branch",
1640
+ "-D",
1641
+ branchToDelete
1642
+ ], {
1643
+ signal,
1644
+ timeoutMs: 1e4
1645
+ });
1646
+ } catch {}
1647
+ }
1648
+ // src/infra/pr-verifier.ts
1649
+ /**
1650
+ * Executes local automated verification commands (e.g. test suites, linters, build scripts)
1651
+ * inside a PR's checked-out worktree before code review.
1652
+ */
1653
+ async function runPrVerification(options) {
1654
+ const results = [];
1655
+ let allPassed = true;
1656
+ const timeoutMs = (options.timeoutSeconds ?? 300) * 1e3;
1657
+ for (const cmd of options.commands) {
1658
+ const start = Date.now();
1659
+ try {
1660
+ const output = await run("/bin/sh", ["-c", cmd], {
1661
+ cwd: options.cwd,
1662
+ env: options.env,
1663
+ timeoutMs,
1664
+ signal: options.signal
1665
+ });
1666
+ const durationMs = Date.now() - start;
1667
+ results.push({
1668
+ command: cmd,
1669
+ exitCode: 0,
1670
+ durationMs,
1671
+ stdout: output,
1672
+ stderr: "",
1673
+ passed: true
1674
+ });
1675
+ } catch (err) {
1676
+ const durationMs = Date.now() - start;
1677
+ allPassed = false;
1678
+ results.push({
1679
+ command: cmd,
1680
+ exitCode: err.exitCode ?? 1,
1681
+ durationMs,
1682
+ stdout: err.stdout ?? "",
1683
+ stderr: err.stderr ?? err.message ?? "",
1684
+ passed: false
1685
+ });
1686
+ break;
1687
+ }
1688
+ }
1689
+ const lines = [
1690
+ "### Automated Local Verification",
1691
+ "",
1692
+ allPassed ? "✅ **All local verification checks passed.**" : "❌ **Local verification failed.** The code in this PR failed one or more verification commands.",
1693
+ "",
1694
+ "| Command | Status | Duration |",
1695
+ "| :--- | :--- | :--- |"
1696
+ ];
1697
+ for (const r of results) lines.push(`| \`${r.command}\` | ${r.passed ? "✅ PASS" : "❌ FAIL (exit " + r.exitCode + ")"} | ${(r.durationMs / 1e3).toFixed(1)}s |`);
1698
+ for (const r of results) if (!r.passed) lines.push("", `#### Failure Log: \`${r.command}\``, "```text", (r.stderr || r.stdout || "Unknown error").trim().slice(-3e3), "```");
1699
+ return {
1700
+ passed: allPassed,
1701
+ totalCommands: options.commands.length,
1702
+ results,
1703
+ markdown: lines.join("\n")
1704
+ };
979
1705
  }
980
1706
  // src/runner.ts
981
1707
  /** How long a reply in a conversation may be: a person reads it on a phone, and the evidence belongs in the pull request. */
@@ -1064,17 +1790,36 @@ function record(engine, repo, finished, log) {
1064
1790
  }
1065
1791
  }
1066
1792
  /** Posts the messages the Engine queued, one comment per message. */
1067
- async function send(channel, clis, log) {
1793
+ async function send(channel, clis, log, attentionConfig) {
1794
+ const quiet = isQuietHours(/* @__PURE__ */ new Date(), attentionConfig?.quietHours);
1795
+ const present = await isUserPresent(attentionConfig?.idleSecondsThreshold);
1068
1796
  for (const message of channel.drain()) {
1797
+ if (message.channel.source === "twitter") {
1798
+ const address = message.channel.address;
1799
+ if (!clis.twitter) {
1800
+ log(`Cannot answer on Twitter: the Twitter Source is off`);
1801
+ continue;
1802
+ }
1803
+ if (!address.tweetUrl) continue;
1804
+ try {
1805
+ await replyTweet(clis.twitter, address.tweetUrl, message.text);
1806
+ log(`Replied to tweet ${address.tweetUrl}`);
1807
+ } catch (error) {
1808
+ log(`Could not reply to tweet ${address.tweetUrl}: ${error.message}`);
1809
+ }
1810
+ continue;
1811
+ }
1069
1812
  if (message.channel.source === "feishu") {
1070
1813
  const address = message.channel.address;
1071
1814
  if (!clis.feishu) {
1072
1815
  log(`Cannot answer in ${address.chatId}: the Feishu Source is off`);
1073
1816
  continue;
1074
1817
  }
1818
+ if (quiet && message.kind !== "acknowledgement") log(`Quiet hours active (23:00-08:00); answered in ${address.chatId} quietly`);
1819
+ else if (present) log(`User is present at computer; answered in ${address.chatId}`);
1820
+ else log(`User is away; dispatched notification to mobile in ${address.chatId}`);
1075
1821
  try {
1076
1822
  await reply(clis.feishu, address.messageId, message.text, message.id);
1077
- log(`Answered in ${address.chatId}`);
1078
1823
  } catch (error) {
1079
1824
  log(`Could not answer in ${address.chatId}: ${error.message}`);
1080
1825
  }
@@ -1186,21 +1931,34 @@ var AgentExecutor = class {
1186
1931
  });
1187
1932
  }
1188
1933
  async execute(ticket, assignment, controller) {
1189
- const { settings, runner, stateDir, accounts, feishuCli, site } = this.options;
1934
+ const { settings, runner, stateDir, accounts, feishuCli, site, repo, log } = this.options;
1190
1935
  const directory = ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
1936
+ const trigger = repo?.triggers.get(ticket.origin.triggerId);
1937
+ const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
1938
+ const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
1191
1939
  try {
1192
1940
  const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
1193
1941
  await prepareWorktree({
1194
1942
  checkout: settings.checkout,
1195
1943
  directory,
1196
1944
  branch,
1945
+ prNumber: isPrReview ? prNumber : void 0,
1946
+ repository: settings.github?.repository,
1197
1947
  signal: controller.signal
1198
1948
  });
1199
1949
  if (settings.executor.prepare) await run("/bin/sh", ["-c", settings.executor.prepare], {
1200
1950
  env: this.variables(ticket, directory, branch),
1201
1951
  timeoutMs: 12e4
1202
1952
  });
1203
- const prompt = await this.options.prompt(ticket, directory, branch);
1953
+ let prVerification;
1954
+ if (isPrReview && settings.github?.prReview?.verifyCommands?.length) prVerification = await runPrVerification({
1955
+ cwd: directory,
1956
+ commands: settings.github.prReview.verifyCommands,
1957
+ timeoutSeconds: settings.github.prReview.verifyTimeoutSeconds,
1958
+ signal: controller.signal
1959
+ });
1960
+ const prompt = await this.options.prompt(ticket, directory, branch, prVerification);
1961
+ const isAutonomous = ticket.mandate.strength === "inferred" && !isPrReview;
1204
1962
  const result = await runner.run({
1205
1963
  prompt,
1206
1964
  cwd: directory,
@@ -1210,9 +1968,62 @@ var AgentExecutor = class {
1210
1968
  } : accounts, this.variables(ticket, directory, branch)),
1211
1969
  signal: controller.signal,
1212
1970
  timeoutMs: settings.executor.timeoutMinutes * 6e4,
1213
- model: settings.executor.model
1971
+ model: settings.executor.model,
1972
+ readOnly: isAutonomous
1214
1973
  });
1215
1974
  const report = result.report ?? inferReport(result.finalText, result.ok);
1975
+ if (isPrReview && prNumber && settings.github) {
1976
+ const textToAnalyze = `${result.finalText}\n${report.summary}`;
1977
+ const decisionMatch = /DECISION:\s*(MERGE|APPROVE|REQUEST_CHANGES|CLOSE)/i.exec(textToAnalyze);
1978
+ 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, [
1983
+ "pr",
1984
+ "merge",
1985
+ String(prNumber),
1986
+ `--${method}`,
1987
+ "--auto",
1988
+ "--repo",
1989
+ settings.github.repository
1990
+ ]);
1991
+ await run(settings.github.cli, [
1992
+ "pr",
1993
+ "comment",
1994
+ String(prNumber),
1995
+ "--repo",
1996
+ settings.github.repository,
1997
+ "-b",
1998
+ `🤖 **SuperAgent Review Verdict: MERGED**\n\n${deliverable(report.summary)}\n\nAutomated local verification passed and code review approved.`
1999
+ ]).catch(() => {});
2000
+ log?.(`Merged PR #${prNumber} on ${settings.github.repository}`);
2001
+ } catch (mergeErr) {
2002
+ log?.(`Could not merge PR #${prNumber}: ${mergeErr.message}`);
2003
+ }
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}`);
2015
+ } catch (closeErr) {
2016
+ log?.(`Could not close PR #${prNumber}: ${closeErr.message}`);
2017
+ }
2018
+ }
2019
+ if (report.followupAfterSeconds && report.followupAfterSeconds > 0) await new TimerStore(stateDir).save({
2020
+ id: `followup-${ticket.id}-${Date.now()}`,
2021
+ kind: "followup",
2022
+ ticketId: ticket.id,
2023
+ dueAt: new Date(Date.now() + report.followupAfterSeconds * 1e3).toISOString(),
2024
+ prompt: `Follow-up checkpoint for ticket ${ticket.id}: ${report.summary}`,
2025
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2026
+ });
1216
2027
  await appendLog(directory, prompt, result.raw.slice(-2e4), report);
1217
2028
  site.reported(ticket.id, {
1218
2029
  state: report.state ?? (result.ok ? "ready" : "failed"),
@@ -1288,8 +2099,10 @@ async function runLoop(options) {
1288
2099
  const signal = stop.signal;
1289
2100
  const github = settings.github?.enabled ? settings.github : void 0;
1290
2101
  const feishu = settings.feishu?.enabled ? settings.feishu : void 0;
1291
- if (!github && !feishu) throw new Error("No Source is on in settings.yaml; nothing to poll.");
2102
+ 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.");
1292
2104
  const login = github ? await agentLogin(github.cli, signal) : "";
2105
+ const twitterBot = twitter ? await twitterAccount(twitter.cli, signal) : "";
1293
2106
  const accounts = {
1294
2107
  stateDir: settings.stateDir,
1295
2108
  githubCli: github?.cli ?? "gh",
@@ -1350,10 +2163,15 @@ async function runLoop(options) {
1350
2163
  accounts,
1351
2164
  ...feishu ? { feishuCli: feishu.cli } : {},
1352
2165
  site,
1353
- prompt: async (ticket, directory, branch) => {
2166
+ repo,
2167
+ log,
2168
+ prompt: async (ticket, directory, branch, prVerification) => {
1354
2169
  const trigger = repo.triggers.get(ticket.origin.triggerId);
1355
2170
  const source = trigger?.source === "feishu" ? "feishu" : "github";
2171
+ const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
2172
+ const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
1356
2173
  const notes = ticket.inputs.flatMap((input) => input.kind === "text" ? [input.text] : []);
2174
+ const readOnly = ticket.mandate.strength === "inferred" && !isPrReview;
1357
2175
  return composePrompt({
1358
2176
  ticket,
1359
2177
  trigger,
@@ -1364,7 +2182,12 @@ async function runLoop(options) {
1364
2182
  instructions: settings.prompts,
1365
2183
  branch,
1366
2184
  standing,
1367
- notes
2185
+ notes,
2186
+ readOnly,
2187
+ isPrReview,
2188
+ prNumber,
2189
+ prVerification,
2190
+ autoMergeAllowed: Boolean(github?.prReview?.autoMerge)
1368
2191
  });
1369
2192
  }
1370
2193
  });
@@ -1437,6 +2260,12 @@ async function runLoop(options) {
1437
2260
  const nextLine = () => handle ? handle.next(settings.executor.streamIdleMs) : Promise.resolve(false);
1438
2261
  const delivered = /* @__PURE__ */ new Set();
1439
2262
  engine.options.executor = executor;
2263
+ const timerStore = new TimerStore(settings.stateDir);
2264
+ const watcherEngine = new WatcherEngine(settings.stateDir);
2265
+ const budgetGuard = new BudgetGuard(settings.budget, {
2266
+ get: () => repo.getMeta("budget:state"),
2267
+ set: (s) => repo.setMeta("budget:state", s)
2268
+ });
1440
2269
  try {
1441
2270
  for (const ticket of repo.tickets.active()) engine.updateTicket(ticket);
1442
2271
  executor.recover(repo.tickets.active());
@@ -1477,9 +2306,98 @@ async function runLoop(options) {
1477
2306
  mark: (id) => repo.setMeta(seenKey(id), true)
1478
2307
  });
1479
2308
  for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
2309
+ if (github.prReview?.enabled && github.prReview?.pollOpenPrs !== false) try {
2310
+ const prTriggers = await pollOpenPullRequests({
2311
+ cli: github.cli,
2312
+ repository: github.repository,
2313
+ agent: login,
2314
+ signal,
2315
+ seen: (id) => repo.getMeta(id) === true,
2316
+ mark: (id) => repo.setMeta(id, true)
2317
+ });
2318
+ for (const trigger of prTriggers) if (engine.receive(trigger) !== "duplicate") log(`Received PR review trigger for #${trigger.meta?.number} from ${trigger.actor.id}`);
2319
+ } catch (prErr) {
2320
+ if (!signal.aborted) log(`PR poll failed: ${prErr.message}`);
2321
+ }
1480
2322
  since = round;
1481
2323
  repo.setMeta(pollKey, since);
1482
2324
  }
2325
+ if (twitter) try {
2326
+ const triggers = await searchTweets(twitter.cli, twitter.query, {
2327
+ seen: (id) => repo.getMeta(`twitter:seen:${id}`) === true,
2328
+ mark: (id) => repo.setMeta(`twitter:seen:${id}`, true),
2329
+ agentLogin: twitterBot,
2330
+ signal
2331
+ });
2332
+ for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received Twitter trigger ${trigger.id} from @${trigger.actor.id}`);
2333
+ } catch (error) {
2334
+ if (!signal.aborted) log(`Twitter poll failed: ${error.message}`);
2335
+ }
2336
+ if (settings.watchers && settings.watchers.length > 0) for (const watcher of settings.watchers) try {
2337
+ const check = await watcherEngine.check(watcher, { now: /* @__PURE__ */ new Date() });
2338
+ if (check.triggered && check.diffText) {
2339
+ const budgetCheck = await budgetGuard.check();
2340
+ if (!budgetCheck.allowed) {
2341
+ log(`Watcher ${watcher.id} triggered but postponed: ${budgetCheck.reason}`);
2342
+ continue;
2343
+ }
2344
+ await budgetGuard.record();
2345
+ log(`Watcher ${watcher.id} detected output changes; generating trigger`);
2346
+ const trigger = {
2347
+ id: `watcher:${watcher.id}:${Date.now()}`,
2348
+ source: "watcher",
2349
+ threads: [{
2350
+ source: "watcher",
2351
+ id: watcher.id
2352
+ }],
2353
+ actor: {
2354
+ source: "watcher",
2355
+ id: "system"
2356
+ },
2357
+ human: false,
2358
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2359
+ text: check.diffText,
2360
+ meta: { watcherId: watcher.id }
2361
+ };
2362
+ if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received watcher trigger ${trigger.id}`);
2363
+ }
2364
+ } catch (error) {
2365
+ log(`Watcher ${watcher.id} check error: ${error.message}`);
2366
+ }
2367
+ if (settings.timers?.enabled) {
2368
+ const dueTimers = await timerStore.getDue(/* @__PURE__ */ new Date());
2369
+ for (const timer of dueTimers) {
2370
+ const budgetCheck = await budgetGuard.check();
2371
+ if (!budgetCheck.allowed) {
2372
+ log(`Timer ${timer.id} postponed: ${budgetCheck.reason}`);
2373
+ break;
2374
+ }
2375
+ await budgetGuard.record();
2376
+ log(`Firing due timer ${timer.id} (${timer.kind})`);
2377
+ const trigger = {
2378
+ id: `timer:${timer.id}:${Date.now()}`,
2379
+ source: "timer",
2380
+ threads: [{
2381
+ source: "timer",
2382
+ id: timer.ticketId ?? timer.id
2383
+ }],
2384
+ actor: {
2385
+ source: "timer",
2386
+ id: "system"
2387
+ },
2388
+ human: false,
2389
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2390
+ text: timer.prompt,
2391
+ meta: {
2392
+ timerId: timer.id,
2393
+ kind: timer.kind,
2394
+ ticketId: timer.ticketId
2395
+ }
2396
+ };
2397
+ if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received timer trigger ${trigger.id}`);
2398
+ await timerStore.processDue(timer, /* @__PURE__ */ new Date());
2399
+ }
2400
+ }
1483
2401
  engine.evaluateDue();
1484
2402
  decide(engine, decided.drain(), log);
1485
2403
  record(engine, repo, finished.drain(), log);
@@ -1490,15 +2408,16 @@ async function runLoop(options) {
1490
2408
  await repo.flush();
1491
2409
  await send(channel, {
1492
2410
  ...github ? { github: github.cli } : {},
1493
- ...feishu ? { feishu: feishu.cli } : {}
1494
- }, log);
2411
+ ...feishu ? { feishu: feishu.cli } : {},
2412
+ ...twitter ? { twitter: twitter.cli } : {}
2413
+ }, log, settings.attention);
1495
2414
  await repo.flush();
1496
2415
  await sync();
1497
2416
  } catch (error) {
1498
2417
  if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
1499
2418
  }
1500
2419
  if (options.once) break;
1501
- const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity);
2420
+ const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity, twitter?.pollSeconds ?? Infinity);
1502
2421
  let left = options.once ? 0 : seconds * 1e3;
1503
2422
  while (left > 0 && !signal.aborted) {
1504
2423
  const began = Date.now();
@@ -1511,6 +2430,300 @@ async function runLoop(options) {
1511
2430
  stop.abort();
1512
2431
  if (options.once && !process.env.VITEST) setImmediate(() => process.exit(process.exitCode ?? 0));
1513
2432
  }
2433
+ // src/setup.ts
2434
+ /**
2435
+ * `superagent setup` fills the settings the Sources need from the CLIs that already know the answers.
2436
+ *
2437
+ * GitHub knows which account `gh` acts as; Feishu knows which chats the bot is in and who is in them. Asking those CLIs
2438
+ * removes the step a person would otherwise do by hand — look up a chat id in the Feishu UI, copy every member's open id
2439
+ * — so a setup is one command per Source.
2440
+ *
2441
+ * Nothing is written unless the CLI answered: a failing lookup leaves that section of `settings.yaml` as it was.
2442
+ */
2443
+ /** The login `gh` acts as, which is the account the agent reads notifications and opens pull requests under. */
2444
+ async function githubLogin(cli) {
2445
+ const user = await runJson(cli, ["api", "user"]);
2446
+ if (!user.login) throw new CliError(cli, `${cli} api user named no login`, "", "");
2447
+ return user.login;
2448
+ }
2449
+ /** The repository `github.repository` names, read through the agent's CLI so a private one is found too. */
2450
+ async function repositoryMeta(cli, repository) {
2451
+ return runJson(cli, [
2452
+ "api",
2453
+ `repos/${repository}`,
2454
+ "--jq",
2455
+ "{owner: .owner.login, name: .name, private: .private}"
2456
+ ]);
2457
+ }
2458
+ /** The owner of a checkout path, when that path is a GitHub repository the agent's account can read. */
2459
+ async function checkoutRepository(cli, origin) {
2460
+ if (!origin) return void 0;
2461
+ const match = /github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/.exec(origin.trim());
2462
+ if (!match) return void 0;
2463
+ try {
2464
+ const repo = await repositoryMeta(cli, `${match[1]}/${match[2]}`);
2465
+ return `${repo.owner}/${repo.name}`;
2466
+ } catch {
2467
+ return;
2468
+ }
2469
+ }
2470
+ /** The remote URL of the clone in `checkout`, as the worktree that `poll` starts from reads it. */
2471
+ async function originOf(checkout, stateDir) {
2472
+ return (await run("git", [
2473
+ "-C",
2474
+ checkout,
2475
+ "remote",
2476
+ "get-url",
2477
+ "origin"
2478
+ ], { cwd: stateDir }).catch(() => "")).trim() || void 0;
2479
+ }
2480
+ const ChatSchema = (value) => {
2481
+ const chat = value;
2482
+ return {
2483
+ chatId: String(chat.chat_id ?? ""),
2484
+ name: String(chat.name ?? chat.chat_id ?? "")
2485
+ };
2486
+ };
2487
+ /**
2488
+ * The group chats the bot can hear, which are the only ones it may listen to.
2489
+ *
2490
+ * `+chat-list` is user-only for direct chats, so this asks for groups only; a bot needs no user login for that.
2491
+ */
2492
+ async function botChats(cli) {
2493
+ const result = await runJson(cli, [
2494
+ "im",
2495
+ "+chat-list",
2496
+ "--as",
2497
+ "bot",
2498
+ "--types",
2499
+ "group",
2500
+ "--page-all"
2501
+ ]);
2502
+ const listing = result;
2503
+ return (Array.isArray(result) ? result : listing?.items ?? listing?.chats ?? []).map(ChatSchema).filter((chat) => chat.chatId);
2504
+ }
2505
+ /**
2506
+ * The people in a chat, found by their user name rather than by open id.
2507
+ *
2508
+ * The CLI cannot search users by name through the bot, so `names` is resolved against the members the bot can list: a
2509
+ * name matches a member's display name exactly, or, when no member matches, the part of a display name before `@` or
2510
+ * a space — which is how a person writes their GitHub name in Feishu. Ids the person typed are kept as they are.
2511
+ */
2512
+ async function resolveMembers(cli, chatId, names) {
2513
+ if (!names.length) return {
2514
+ found: [],
2515
+ missing: []
2516
+ };
2517
+ const found = names.filter((name) => name.startsWith("ou_"));
2518
+ const wanted = names.filter((name) => !name.startsWith("ou_"));
2519
+ const missing = [];
2520
+ if (!wanted.length) return {
2521
+ found,
2522
+ missing
2523
+ };
2524
+ const members = await chatMembers(cli, chatId);
2525
+ for (const name of wanted) {
2526
+ const match = members.find((member) => member.name === name) ?? members.find((member) => (member.name.split(/[@\s]/)[0] ?? "") === name);
2527
+ if (match) found.push(match.id);
2528
+ else missing.push(name);
2529
+ }
2530
+ return {
2531
+ found,
2532
+ missing
2533
+ };
2534
+ }
2535
+ /** Splits `a,b, c` and drops the blanks, so one flag can name several people. */
2536
+ const names = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
2537
+ const MANAGED = ["github", "feishu"];
2538
+ /**
2539
+ * The settings file with only the Source sections replaced, so this command keeps the text an operator wrote.
2540
+ *
2541
+ * `writeSettings` writes a whole file and loses every comment; that is fine for `init`, which starts from nothing, but a
2542
+ * setup run should leave the rest of the file — the prompt, the rules, the executor — exactly as a person left it.
2543
+ */
2544
+ function mergeSections(text, settings) {
2545
+ const values = settings;
2546
+ const sections = MANAGED.filter((name) => values[name] !== void 0).map((name) => `${name}:\n${stringifyYaml(values[name], 2)}`);
2547
+ const kept = [];
2548
+ /** Sections the text did not have; they go after the settings the text does have. */
2549
+ const added = [];
2550
+ let dropping = false;
2551
+ let placed = false;
2552
+ const hold = (section) => {
2553
+ if (placed) added.push(section);
2554
+ else {
2555
+ kept.push(section);
2556
+ placed = true;
2557
+ }
2558
+ };
2559
+ for (const line of text.split("\n")) {
2560
+ if (line && !/^[\s-]/.test(line)) {
2561
+ const [name, ...rest] = line.split(":");
2562
+ dropping = MANAGED.includes(name) && rest.length === 1;
2563
+ if (dropping) hold(sections.shift() ?? "");
2564
+ }
2565
+ if (!dropping) kept.push(line);
2566
+ }
2567
+ return [
2568
+ kept.join("\n").replace(/\n+$/, ""),
2569
+ ...sections,
2570
+ ...added
2571
+ ].join("\n") + "\n";
2572
+ }
2573
+ /** Reads the settings, lets `edit` change them and writes them back when `edit` returns what it wrote. */
2574
+ async function update(dir, edit) {
2575
+ const path = join(dir, SETTINGS_FILE);
2576
+ const settings = await readSettings(path);
2577
+ if (!await edit(settings)) return void 0;
2578
+ await writeFile(path, mergeSections(await readFile(path, "utf8"), settings), "utf8");
2579
+ return settings;
2580
+ }
2581
+ async function setupGithub(options) {
2582
+ const lines = [];
2583
+ let failed = false;
2584
+ let login;
2585
+ await update(options.dir, async (settings) => {
2586
+ const cli = settings.github?.cli ?? "gh";
2587
+ try {
2588
+ login = await githubLogin(cli);
2589
+ } catch (error) {
2590
+ lines.push(`GitHub: ${error.message}`);
2591
+ failed = true;
2592
+ return false;
2593
+ }
2594
+ lines.push(`GitHub account: ${login} (${cli})`);
2595
+ const origin = options.stateDir ? await originOf(settings.checkout, options.stateDir) : void 0;
2596
+ const repository = settings.github?.repository ?? await checkoutRepository(cli, origin);
2597
+ try {
2598
+ const repo = repository ? await repositoryMeta(cli, repository) : void 0;
2599
+ const github = settings.github = {
2600
+ ...settings.github ?? {
2601
+ enabled: true,
2602
+ cli,
2603
+ repository: "",
2604
+ pollSeconds: 60,
2605
+ allowed: []
2606
+ },
2607
+ enabled: settings.github?.enabled ?? true,
2608
+ cli,
2609
+ repository: repo ? `${repo.owner}/${repo.name}` : settings.github?.repository ?? "",
2610
+ allowed: options.allow.length ? [...options.allow] : settings.github?.allowed ?? []
2611
+ };
2612
+ lines.push(repo ? `Repository: ${repo.owner}/${repo.name}${repo.private ? " (private)" : ""}` : "Repository: not found; set `github.repository`");
2613
+ if (!repo) failed = true;
2614
+ lines.push(`Allowed logins: ${github.allowed.join(", ") || "(none)"}`);
2615
+ if (github.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.`);
2616
+ return true;
2617
+ } catch (error) {
2618
+ lines.push(`GitHub: ${error.message}`);
2619
+ failed = true;
2620
+ return false;
2621
+ }
2622
+ });
2623
+ return {
2624
+ lines,
2625
+ failed
2626
+ };
2627
+ }
2628
+ async function findChat(cli, wanted, current) {
2629
+ if (wanted?.startsWith("oc_")) return wanted;
2630
+ const chats = await botChats(cli);
2631
+ const known = current.feishu?.chats?.[0]?.chatId;
2632
+ if (!wanted && known) return known;
2633
+ if (!wanted) return chats.length === 1 ? chats[0].chatId : void 0;
2634
+ return (chats.find((chat) => chat.name === wanted) ?? chats.find((chat) => chat.name.includes(wanted)))?.chatId;
2635
+ }
2636
+ async function setupFeishu(options) {
2637
+ const lines = [];
2638
+ let failed = false;
2639
+ await update(options.dir, async (settings) => {
2640
+ const cli = settings.feishu?.cli ?? "lark-cli";
2641
+ const idsOnly = options.allow.length > 0 && options.allow.every((name) => name.startsWith("ou_"));
2642
+ let chatId;
2643
+ let chats = [];
2644
+ let listing = "";
2645
+ try {
2646
+ chats = await botChats(cli);
2647
+ } catch (error) {
2648
+ listing = error.message;
2649
+ }
2650
+ try {
2651
+ chatId = await findChat(cli, options.chat, settings);
2652
+ } catch (error) {
2653
+ listing ||= error.message;
2654
+ }
2655
+ const known = settings.feishu?.chats?.some((item) => item.chatId === chatId) ?? false;
2656
+ if (chatId && !idsOnly && !known && !chats.some((item) => item.chatId === chatId)) {
2657
+ lines.push(listing ? `Feishu: ${listing}` : `Feishu: the bot is in ${chats.length ? chats.map((chat) => `${chat.name} (${chat.chatId})`).join(", ") : "no group chat"}; it cannot listen to ${chatId}.`);
2658
+ failed = true;
2659
+ return false;
2660
+ }
2661
+ if (!chatId) {
2662
+ lines.push(listing ? `Feishu: ${listing}` : chats.length ? `Feishu: the bot is in ${chats.map((chat) => `${chat.name} (${chat.chatId})`).join(", ")}; choose one with \`--chat\`.` : "Feishu: the bot is in no group chat; add it to one, or pass `--chat oc_…`.");
2663
+ failed = true;
2664
+ return false;
2665
+ }
2666
+ const chat = chats.find((item) => item.chatId === chatId);
2667
+ let allowed = settings.feishu?.allowed ?? [];
2668
+ if (options.allow.length) {
2669
+ const resolved = await resolveMembers(cli, chatId, options.allow).catch((error) => {
2670
+ lines.push(`Feishu: ${error.message}`);
2671
+ failed = true;
2672
+ return {
2673
+ found: [],
2674
+ missing: []
2675
+ };
2676
+ });
2677
+ allowed = [.../* @__PURE__ */ new Set([...allowed, ...resolved.found])];
2678
+ if (resolved.missing.length) {
2679
+ lines.push(`Feishu: no member of the chat is called ${resolved.missing.join(", ")}; pass their open id (ou_…) or leave the chat members to fill the list with \`syncChat\`.`);
2680
+ failed = true;
2681
+ }
2682
+ }
2683
+ const feishu = settings.feishu = {
2684
+ ...settings.feishu ?? {
2685
+ enabled: true,
2686
+ cli,
2687
+ chats: [],
2688
+ directMessages: true,
2689
+ allowed: []
2690
+ },
2691
+ enabled: settings.feishu?.enabled ?? true,
2692
+ cli,
2693
+ chats: [{
2694
+ chatId,
2695
+ name: chat?.name ?? settings.feishu?.chats?.[0]?.name ?? chatId
2696
+ }],
2697
+ syncChat: chatId,
2698
+ allowed
2699
+ };
2700
+ lines.push(`Feishu chat: ${feishu.chats[0].name} (${chatId})`);
2701
+ lines.push(`Allowed: the chat's members (\`syncChat\`)${allowed.length ? `, and the ${allowed.length} open id(s) listed` : ""}`);
2702
+ return true;
2703
+ });
2704
+ return {
2705
+ lines,
2706
+ failed
2707
+ };
2708
+ }
2709
+ /** Runs the steps in order and prints what each found; a failed GitHub step still lets Feishu run. */
2710
+ async function setup(options) {
2711
+ const targets = options.targets.length ? options.targets : ["github", "feishu"];
2712
+ let failed = false;
2713
+ try {
2714
+ for (const target of targets) {
2715
+ const report = target === "github" ? await setupGithub(options) : await setupFeishu(options);
2716
+ for (const line of report.lines) options.log(line);
2717
+ failed ||= report.failed;
2718
+ }
2719
+ } catch (error) {
2720
+ options.log(error.message);
2721
+ return 1;
2722
+ }
2723
+ options.log("");
2724
+ options.log(`Wrote ${join(options.dir, SETTINGS_FILE)}. Next: \`superagent doctor\`, then \`superagent poll\`.`);
2725
+ return failed ? 1 : 0;
2726
+ }
1514
2727
  // src/cli.ts
1515
2728
  /**
1516
2729
  * `superagent` command line: create an installation, inspect it, and run one ticket by hand.
@@ -1521,12 +2734,20 @@ async function runLoop(options) {
1521
2734
  const USAGE = `superagent — an agent that turns GitHub and Feishu requests into tickets
1522
2735
 
1523
2736
  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
1524
2738
  superagent status [dir] print open tickets and recent activity as Markdown
1525
2739
  superagent doctor [dir] show which coding agents are installed and which one is selected
1526
2740
  superagent agents list the coding agents a configuration may name
1527
2741
  superagent run <dir> -p <text> run one prompt on the configured agent, in a directory it names
1528
2742
  superagent poll [dir] [--once] poll the Sources and run the tickets they bring, once or until interrupted
1529
2743
 
2744
+ superagent setup asks the CLIs that already know the answers, so a person does not copy ids out of a web page:
2745
+
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)
2748
+ --chat <id|name> the Feishu chat the bot listens to
2749
+ github, feishu set up only one of them (the default is both)
2750
+
1530
2751
  Every command that reads an installation takes the directory that holds ${SETTINGS_FILE}.`;
1531
2752
  async function exists(path) {
1532
2753
  try {
@@ -1567,6 +2788,29 @@ async function init(dir) {
1567
2788
  ].join("\n"));
1568
2789
  return 0;
1569
2790
  }
2791
+ /** Fills the Source settings from GitHub and Feishu; the options are read here so the module stays about the CLIs. */
2792
+ async function setupSources(dir, rest) {
2793
+ const flag = (name) => {
2794
+ const index = rest.indexOf(name);
2795
+ return index < 0 ? void 0 : rest[index + 1];
2796
+ };
2797
+ const targets = rest.filter((item) => item === "github" || item === "feishu");
2798
+ let settings;
2799
+ try {
2800
+ settings = await readSettings(join(dir, SETTINGS_FILE));
2801
+ } catch (error) {
2802
+ process.stderr.write(`${error.message}\n`);
2803
+ return 1;
2804
+ }
2805
+ return setup({
2806
+ dir,
2807
+ targets: [...new Set(targets)],
2808
+ allow: names(flag("--allow")),
2809
+ chat: flag("--chat"),
2810
+ stateDir: await exists(settings.stateDir) ? settings.stateDir : void 0,
2811
+ log: (line) => process.stdout.write(`${line}\n`)
2812
+ });
2813
+ }
1570
2814
  async function status(dir) {
1571
2815
  const { tickets, threads, decisions, triggers: all, exists: found } = await readState(await stateDirOf(dir));
1572
2816
  const triggers = new Map(all.map((trigger) => [trigger.id, trigger]));
@@ -1689,6 +2933,7 @@ async function main(argv) {
1689
2933
  const dirOf = (index) => rest[index] && !rest[index].startsWith("-") ? resolve(rest[index]) : process.cwd();
1690
2934
  switch (command) {
1691
2935
  case "init": return init(rest[0] ? resolve(rest[0]) : process.cwd());
2936
+ case "setup": return setupSources(dirOf(0), rest);
1692
2937
  case "status": return status(dirOf(0));
1693
2938
  case "doctor": return doctor(dirOf(0));
1694
2939
  case "agents":