superagent-skill 0.2.0 → 0.4.0

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,6 +1,7 @@
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 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, o as stringifyYaml, 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-D8KZBXO7.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 { access, appendFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
5
  import { dirname, join, resolve } from "node:path";
5
6
  import { execFile, spawn } from "node:child_process";
6
7
  import { homedir } from "node:os";
@@ -50,7 +51,7 @@ async function runJson(program, argv, options = {}) {
50
51
  const error = parsed.error;
51
52
  throw new CliError(program, `${program} ${argv.join(" ")}: ${error?.message ?? "failed"}`, text, "");
52
53
  }
53
- if (parsed && typeof parsed === "object" && "code" in parsed && "data" in parsed) return parsed.data;
54
+ if (parsed && typeof parsed === "object" && ("code" in parsed || "ok" in parsed) && "data" in parsed) return parsed.data;
54
55
  return parsed;
55
56
  }
56
57
  // src/prompts.ts
@@ -71,8 +72,54 @@ const STANDING_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "prompt
71
72
  async function standingRules() {
72
73
  return Promise.all(STANDING_FILES.map(async (name) => (await readFile(join(STANDING_DIR, name), "utf8")).trim()));
73
74
  }
75
+ /** Composes the prompt for reviewing and verifying a pull request. */
76
+ function composePrReviewPrompt(input) {
77
+ const { ticket, trigger, repository, agentLogin, instructions, standing = [], notes = [], prNumber, prVerification, autoMergeAllowed } = input;
78
+ const asked = trigger ? `Pull Request #${prNumber} details:\n\n${quote(trigger.text)}` : `Pull Request #${prNumber} review:\n\n${quote(ticket.title)}`;
79
+ return [
80
+ `# Ticket ${ticket.id} — Pull Request #${prNumber} Review & Verification`,
81
+ "",
82
+ `You are reviewing Pull Request #${prNumber} on repository \`${repository}\`.`,
83
+ `The PR's code has been checked out directly into this working directory.`,
84
+ `Your GitHub account is \`${agentLogin}\`.`,
85
+ "",
86
+ "## The Pull Request",
87
+ "",
88
+ asked,
89
+ ...notes.filter(Boolean).flatMap((note) => [
90
+ "",
91
+ "## Notes since the start",
92
+ "",
93
+ quote(note)
94
+ ]),
95
+ "",
96
+ "## Automated Local Verification Report",
97
+ "",
98
+ prVerification ? prVerification.markdown : "No automated verification commands were configured.",
99
+ "",
100
+ "## Review Instructions & Standards",
101
+ "",
102
+ "- **Inspect Every Line**: Scrutinize the git diff and logic changes. Do not blindly trust community submissions.",
103
+ "- **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.",
104
+ ...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."] : [],
105
+ "- **Decision Standards**:",
106
+ 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).",
107
+ " - Conclude your report with `DECISION: REQUEST_CHANGES` if tests failed, or if you found bugs, flaws, or missing tests.",
108
+ " - Conclude your report with `DECISION: CLOSE` if the PR is spam, malicious, completely misguided, or unfixable.",
109
+ "",
110
+ ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
111
+ ...instructions.trim() ? [
112
+ "",
113
+ "## Team instructions",
114
+ "",
115
+ instructions.trim()
116
+ ] : [],
117
+ reportInstructions()
118
+ ].join("\n");
119
+ }
74
120
  /** Composes the prompt for one ticket: who asked, what they asked, and what the agent must not assume. */
75
121
  function composePrompt(input) {
122
+ if (input.isPrReview && input.prNumber) return composePrReviewPrompt(input);
76
123
  const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch, standing = [], notes = [] } = input;
77
124
  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
125
  return [
@@ -97,6 +144,7 @@ function composePrompt(input) {
97
144
  "- Run the tests the repository has. Do not claim a check passed unless you ran it.",
98
145
  "- Do not merge the pull request. A person merges it.",
99
146
  "- If the request needs a decision you cannot make, stop and ask one concrete question.",
147
+ ...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
148
  ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
101
149
  ...instructions.trim() ? [
102
150
  "",
@@ -124,6 +172,20 @@ function quote(text) {
124
172
  /** Which sources this installation's Sources read, and whether they read every message in that scope. */
125
173
  function sourceScope(settings) {
126
174
  return { scope: (input) => {
175
+ if (input.source === "timer" || input.source === "watcher") return {
176
+ listened: true,
177
+ observed: true
178
+ };
179
+ if (input.source === "twitter") {
180
+ if (!settings.twitter?.enabled) return {
181
+ listened: false,
182
+ reason: "sourceOff"
183
+ };
184
+ return {
185
+ listened: true,
186
+ observed: true
187
+ };
188
+ }
127
189
  if (input.source === "feishu") {
128
190
  if (!settings.feishu?.enabled) return {
129
191
  listened: false,
@@ -153,7 +215,7 @@ function sourceScope(settings) {
153
215
  };
154
216
  return {
155
217
  listened: true,
156
- observed: false
218
+ observed: Boolean(input.meta.isPr) && Boolean(settings.github.prReview?.enabled)
157
219
  };
158
220
  } };
159
221
  }
@@ -161,17 +223,40 @@ function sourceScope(settings) {
161
223
  const UNASKED_RULE = "unasked";
162
224
  /** The Policy of one settings file, rebuilt whenever the round reads it. */
163
225
  function buildPolicy(settings, scope) {
164
- const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
226
+ const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : source === "twitter" ? settings.twitter?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
165
227
  return {
166
228
  version: `${settings.policy.mode}:${settings.policy.rules.filter((rule) => rule.enabled).map((rule) => rule.id).join(",")}`,
167
229
  paused: false,
168
230
  evalTimeoutMs: 12e4,
169
231
  gate: (trigger, _thread, _tickets, received) => {
232
+ if (trigger.source === "timer" || trigger.source === "watcher") return {
233
+ admissible: true,
234
+ strength: "inferred",
235
+ basis: {
236
+ via: "admission",
237
+ cell: "listedUnaddressed"
238
+ }
239
+ };
240
+ if (trigger.source === "github" && Boolean(trigger.meta?.isPr) && Boolean(settings.github?.prReview?.enabled) && settings.github?.prReview?.allowCommunityPrs !== false) {
241
+ const addressed = !!trigger.addressed;
242
+ const basis = addressed ? {
243
+ via: "listed",
244
+ addressed: trigger.addressed
245
+ } : {
246
+ via: "admission",
247
+ cell: "listedUnaddressed"
248
+ };
249
+ return {
250
+ admissible: true,
251
+ strength: addressed ? "explicit" : "inferred",
252
+ basis
253
+ };
254
+ }
170
255
  if (!trigger.human) return {
171
256
  admissible: false,
172
257
  reason: "bot"
173
258
  };
174
- const allowed = people(trigger.source).has(trigger.actor.id.toLowerCase());
259
+ const allowed = trigger.source === "twitter" && settings.twitter?.allowed.length === 0 ? true : people(trigger.source).has(trigger.actor.id.toLowerCase());
175
260
  const seen = received ?? scope.scope(trigger);
176
261
  const observed = seen.listened && seen.observed;
177
262
  const addressed = !!trigger.addressed;
@@ -257,6 +342,256 @@ function assessmentOutcome(assessment, settings, strength) {
257
342
  };
258
343
  return accept;
259
344
  }
345
+ // src/infra/presence.ts
346
+ /**
347
+ * Human presence detection and attention management.
348
+ *
349
+ * Implements the "Don't let the agent guess your presence" and "Start quiet" principles from Anthropic's
350
+ * "Building always-on agents" and FanBox practice: detect system-level input idle time, route notifications
351
+ * to local terminal/desktop when user is at their machine, and dispatch to mobile (Feishu/etc.) only when
352
+ * user is away or during active attention requests, respecting quiet hours.
353
+ */
354
+ /**
355
+ * Determines whether a given time falls within configured quiet hours.
356
+ * Supports intervals that cross midnight (e.g. 23:00 to 08:00).
357
+ */
358
+ function isQuietHours(now = /* @__PURE__ */ new Date(), config) {
359
+ if (!config || !config.enabled) return false;
360
+ const [startH = 23, startM = 0] = (config.start || "23:00").split(":").map(Number);
361
+ const [endH = 8, endM = 0] = (config.end || "08:00").split(":").map(Number);
362
+ const currentMinutes = now.getHours() * 60 + now.getMinutes();
363
+ const startMinutes = startH * 60 + startM;
364
+ const endMinutes = endH * 60 + endM;
365
+ if (startMinutes <= endMinutes) return currentMinutes >= startMinutes && currentMinutes < endMinutes;
366
+ return currentMinutes >= startMinutes || currentMinutes < endMinutes;
367
+ }
368
+ /**
369
+ * Returns estimated system idle seconds (time since last user keyboard/mouse/console input).
370
+ * Uses macOS /dev/console mtime or ioreg, falls back to 0.
371
+ */
372
+ async function getSystemIdleSeconds() {
373
+ try {
374
+ const s = await stat("/dev/console");
375
+ const idleSeconds = Math.max(0, Math.floor((Date.now() - s.mtimeMs) / 1e3));
376
+ if (Number.isFinite(idleSeconds)) return idleSeconds;
377
+ } catch {}
378
+ try {
379
+ const out = await run("/bin/sh", ["-c", "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print int($NF/1000000000); exit}'"], { timeoutMs: 2e3 });
380
+ const idle = parseInt(out.trim(), 10);
381
+ if (!Number.isNaN(idle) && idle >= 0) return idle;
382
+ } catch {}
383
+ return 0;
384
+ }
385
+ /**
386
+ * Determines whether a human user is currently active at the local machine.
387
+ * When idle time is below thresholdSeconds (default 300s = 5m), the user is considered present.
388
+ */
389
+ async function isUserPresent(thresholdSeconds = 300, idleProvider = getSystemIdleSeconds) {
390
+ try {
391
+ return await idleProvider() < thresholdSeconds;
392
+ } catch {
393
+ return false;
394
+ }
395
+ }
396
+ // src/infra/budget.ts
397
+ var BudgetGuard = class {
398
+ config;
399
+ storage;
400
+ constructor(config, storage) {
401
+ this.config = config;
402
+ this.storage = storage;
403
+ }
404
+ /** Checks if an autonomous wakeup is currently permitted under budget rules. */
405
+ async check(now = /* @__PURE__ */ new Date()) {
406
+ const today = now.toISOString().slice(0, 10);
407
+ const current = await this.storage.get() ?? {
408
+ date: today,
409
+ autonomousWakes: 0
410
+ };
411
+ const state = current.date === today ? current : {
412
+ date: today,
413
+ autonomousWakes: 0
414
+ };
415
+ if (state.autonomousWakes >= this.config.maxAutonomousWakesPerDay) return {
416
+ allowed: false,
417
+ reason: `Daily autonomous limit reached (${state.autonomousWakes}/${this.config.maxAutonomousWakesPerDay})`
418
+ };
419
+ if (state.lastWakeAt && this.config.autonomousCooldownSeconds > 0) {
420
+ const elapsedSeconds = Math.floor((now.getTime() - new Date(state.lastWakeAt).getTime()) / 1e3);
421
+ if (elapsedSeconds < this.config.autonomousCooldownSeconds) return {
422
+ allowed: false,
423
+ reason: `Autonomous cooldown active (${this.config.autonomousCooldownSeconds - elapsedSeconds}s remaining of ${this.config.autonomousCooldownSeconds}s)`
424
+ };
425
+ }
426
+ return { allowed: true };
427
+ }
428
+ /** Records that an autonomous wakeup has occurred, incrementing counter and recording timestamp. */
429
+ async record(now = /* @__PURE__ */ new Date()) {
430
+ const today = now.toISOString().slice(0, 10);
431
+ const current = await this.storage.get() ?? {
432
+ date: today,
433
+ autonomousWakes: 0
434
+ };
435
+ const state = current.date === today ? { ...current } : {
436
+ date: today,
437
+ autonomousWakes: 0
438
+ };
439
+ state.autonomousWakes += 1;
440
+ state.lastWakeAt = now.toISOString();
441
+ await this.storage.set(state);
442
+ return state;
443
+ }
444
+ };
445
+ // src/infra/timers.ts
446
+ /**
447
+ * Durable timers engine for proactive and autonomous agent runs.
448
+ *
449
+ * Implements the "Timers" primitive from Anthropic's "Building always-on agents":
450
+ * 1) Follow-ups: Short-term checkpoints scheduled by the agent or tickets (e.g. check CI in 15m).
451
+ * 2) Schedules: Recurring cron/interval-based jobs (e.g. daily standup, repo hygiene).
452
+ *
453
+ * Expired timers generate synthetic events for the Event Inbox, allowing the agent to sleep between runs.
454
+ */
455
+ var TimerStore = class {
456
+ dir;
457
+ constructor(dir) {
458
+ this.dir = dir;
459
+ }
460
+ timersDir() {
461
+ return join(this.dir, "timers");
462
+ }
463
+ async init() {
464
+ await mkdir(this.timersDir(), { recursive: true });
465
+ }
466
+ async list() {
467
+ await this.init();
468
+ const entries = await readdir(this.timersDir()).catch(() => []);
469
+ const timers = [];
470
+ for (const entry of entries) {
471
+ if (!entry.endsWith(".json")) continue;
472
+ try {
473
+ const raw = await readFile(join(this.timersDir(), entry), "utf8");
474
+ timers.push(JSON.parse(raw));
475
+ } catch {}
476
+ }
477
+ return timers.sort((a, b) => a.dueAt.localeCompare(b.dueAt));
478
+ }
479
+ async save(timer) {
480
+ await this.init();
481
+ const path = join(this.timersDir(), `${timer.id}.json`);
482
+ await writeFile(path, JSON.stringify(timer, null, 2), "utf8");
483
+ }
484
+ async remove(id) {
485
+ await this.init();
486
+ await rm(join(this.timersDir(), `${id}.json`), { force: true });
487
+ }
488
+ async getDue(now = /* @__PURE__ */ new Date()) {
489
+ const all = await this.list();
490
+ const nowIso = now.toISOString();
491
+ return all.filter((timer) => timer.dueAt <= nowIso);
492
+ }
493
+ /**
494
+ * Advances a recurring schedule timer or removes a one-shot follow-up timer.
495
+ */
496
+ async processDue(timer, now = /* @__PURE__ */ new Date()) {
497
+ if (timer.kind === "schedule" && timer.intervalMinutes && timer.intervalMinutes > 0) {
498
+ const nextDue = new Date(now.getTime() + timer.intervalMinutes * 6e4).toISOString();
499
+ const updated = {
500
+ ...timer,
501
+ dueAt: nextDue,
502
+ lastRunAt: now.toISOString()
503
+ };
504
+ await this.save(updated);
505
+ } else await this.remove(timer.id);
506
+ }
507
+ };
508
+ // src/infra/watchers.ts
509
+ /**
510
+ * Active watchers ("盯梢") for pull-based external sources without webhooks.
511
+ *
512
+ * Implements the "Not all events push themselves" lesson from FanBox and Anthropic:
513
+ * Periodically executes a lightweight command (e.g. `gh pr list`, `git fetch`), compares the output fingerprint,
514
+ * and produces a synthetic trigger only when new lines or status changes occur.
515
+ */
516
+ var WatcherEngine = class {
517
+ dir;
518
+ constructor(dir) {
519
+ this.dir = dir;
520
+ }
521
+ watchersDir() {
522
+ return join(this.dir, "watchers");
523
+ }
524
+ async init() {
525
+ await mkdir(this.watchersDir(), { recursive: true });
526
+ }
527
+ async getState(id) {
528
+ await this.init();
529
+ try {
530
+ const raw = await readFile(join(this.watchersDir(), `${id}.json`), "utf8");
531
+ return JSON.parse(raw);
532
+ } catch {
533
+ return;
534
+ }
535
+ }
536
+ async saveState(state) {
537
+ await this.init();
538
+ await writeFile(join(this.watchersDir(), `${state.id}.json`), JSON.stringify(state, null, 2), "utf8");
539
+ }
540
+ /**
541
+ * Checks whether the watcher is due for execution.
542
+ */
543
+ isDue(watcher, state, now = /* @__PURE__ */ new Date()) {
544
+ if (!state?.lastRunAt) return true;
545
+ return (now.getTime() - new Date(state.lastRunAt).getTime()) / 6e4 >= watcher.intervalMinutes;
546
+ }
547
+ /**
548
+ * Runs the watcher command, checks for output changes, and updates persistent state.
549
+ */
550
+ async check(watcher, options = {}) {
551
+ const now = options.now ?? /* @__PURE__ */ new Date();
552
+ const runner = options.runner ?? (async (cmd) => run("/bin/sh", ["-c", cmd], { timeoutMs: 3e4 }));
553
+ const state = await this.getState(watcher.id);
554
+ if (!this.isDue(watcher, state, now)) return { triggered: false };
555
+ let output = "";
556
+ try {
557
+ output = await runner(watcher.command);
558
+ } catch (error) {
559
+ return {
560
+ triggered: false,
561
+ error: error.message
562
+ };
563
+ }
564
+ const trimmed = output.trim();
565
+ const hash = createHash("sha256").update(trimmed).digest("hex");
566
+ if (!state) {
567
+ await this.saveState({
568
+ id: watcher.id,
569
+ lastRunAt: now.toISOString(),
570
+ lastOutputHash: hash,
571
+ lastOutputPreview: trimmed.slice(0, 500)
572
+ });
573
+ return { triggered: false };
574
+ }
575
+ if (state.lastOutputHash === hash) {
576
+ await this.saveState({
577
+ ...state,
578
+ lastRunAt: now.toISOString()
579
+ });
580
+ return { triggered: false };
581
+ }
582
+ const diff = `Watcher "${watcher.id}" detected change in command output:\n\n${trimmed.slice(0, 2e3)}\n\nInstruction: ${watcher.instruction}`;
583
+ await this.saveState({
584
+ id: watcher.id,
585
+ lastRunAt: now.toISOString(),
586
+ lastOutputHash: hash,
587
+ lastOutputPreview: trimmed.slice(0, 500)
588
+ });
589
+ return {
590
+ triggered: true,
591
+ diffText: diff
592
+ };
593
+ }
594
+ };
260
595
  // src/assess.ts
261
596
  /**
262
597
  * The assessment of a candidate a person did not address to the agent.
@@ -387,16 +722,36 @@ function assessing(options) {
387
722
  let outcome;
388
723
  try {
389
724
  const settings = options.settings();
390
- outcome = explicit ? {
725
+ const trigger = candidate.triggers[0];
726
+ const isAutonomousTrigger = trigger?.source === "timer" || trigger?.source === "watcher";
727
+ const isPrReview = trigger?.source === "github" && Boolean(trigger?.meta?.isPr) && Boolean(settings.github?.prReview?.enabled);
728
+ if (isAutonomousTrigger) outcome = {
729
+ kind: "accept",
730
+ title: trigger?.text.split("\n")[0]?.slice(0, 60) || "Autonomous Task",
731
+ scope: "autonomous",
732
+ reason: `Autonomous trigger from ${trigger?.source}`
733
+ };
734
+ else if (isPrReview) {
735
+ const prNum = trigger?.meta?.number;
736
+ outcome = {
737
+ kind: "accept",
738
+ title: `Review PR #${prNum}: ${trigger?.text.split("\n")[0]?.replace(/^#\s*Pull Request Review:\s*/i, "").trim() || `PR #${prNum}`}`.slice(0, 60),
739
+ scope: "pr_review",
740
+ reason: `Pull request review for #${prNum}`
741
+ };
742
+ } else if (explicit) outcome = {
391
743
  kind: "accept",
392
744
  ...named(candidate),
393
745
  scope: "",
394
746
  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
747
  };
748
+ else {
749
+ outcome = assessmentOutcome(await options.next(candidate), settings, candidate.strength);
750
+ if (outcome.kind === "accept" && !settings.policy.rules.some((rule) => rule.id === "unasked")) outcome = {
751
+ kind: "ignore",
752
+ reason: "The assessment accepts, but no `unasked` rule is enabled"
753
+ };
754
+ }
400
755
  } catch (error) {
401
756
  outcome = {
402
757
  kind: "unavailable",
@@ -433,15 +788,15 @@ function assessing(options) {
433
788
  * A notification only says that something mentioned the account. The comment itself is read afterwards, so the Trigger
434
789
  * carries what the person wrote, not the notification's summary.
435
790
  */
436
- const SOURCE$1 = "github";
791
+ const SOURCE$2 = "github";
437
792
  /** A thread identifier for an Issue or pull request number; both share one sequence in GitHub. */
438
793
  const githubThread = (number) => ({
439
- source: SOURCE$1,
794
+ source: SOURCE$2,
440
795
  id: String(number)
441
796
  });
442
797
  /** Where a reply to this number goes. */
443
798
  const githubChannel = (repository, number, url) => ({
444
- source: SOURCE$1,
799
+ source: SOURCE$2,
445
800
  thread: threadKey(githubThread(number)),
446
801
  address: {
447
802
  number: String(number),
@@ -516,10 +871,10 @@ function commentTrigger(input) {
516
871
  const login = comment.user.login;
517
872
  return {
518
873
  id: key("github-comment", url, String(comment.id ?? ""), at),
519
- source: SOURCE$1,
874
+ source: SOURCE$2,
520
875
  threads: [githubThread(number)],
521
876
  actor: {
522
- source: SOURCE$1,
877
+ source: SOURCE$2,
523
878
  id: login
524
879
  },
525
880
  human: isHumanLogin(comment.user) && !sameName(login, agent),
@@ -582,6 +937,69 @@ async function pollNotifications(input) {
582
937
  }
583
938
  return triggers;
584
939
  }
940
+ z.looseObject({
941
+ number: z.number(),
942
+ title: z.string(),
943
+ body: z.string().nullish(),
944
+ author: UserSchema,
945
+ updatedAt: z.string().nullish(),
946
+ url: z.string().nullish(),
947
+ headRefName: z.string().nullish(),
948
+ headRepositoryOwner: z.looseObject({ login: z.string() }).nullish()
949
+ });
950
+ /**
951
+ * Polls currently open pull requests for `repository` and returns Triggers for new or updated PRs.
952
+ */
953
+ async function pollOpenPullRequests(input) {
954
+ let prs = [];
955
+ try {
956
+ prs = await runJson(input.cli, [
957
+ "pr",
958
+ "list",
959
+ "--repo",
960
+ input.repository,
961
+ "--state",
962
+ "open",
963
+ "--json",
964
+ "number,title,body,author,updatedAt,url,headRefName,headRepositoryOwner"
965
+ ], { signal: input.signal });
966
+ } catch {
967
+ return [];
968
+ }
969
+ const triggers = [];
970
+ for (const pr of prs) {
971
+ if (sameName(pr.author.login, input.agent)) continue;
972
+ const at = pr.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
973
+ const prKey = key("github-pr-review", input.repository, String(pr.number), at);
974
+ if (input.seen(prKey)) continue;
975
+ const url = pr.url ?? githubPage(input.repository, pr.number, true);
976
+ triggers.push({
977
+ id: prKey,
978
+ source: SOURCE$2,
979
+ threads: [githubThread(pr.number)],
980
+ actor: {
981
+ source: SOURCE$2,
982
+ id: pr.author.login
983
+ },
984
+ human: isHumanLogin(pr.author) && !sameName(pr.author.login, input.agent),
985
+ addressed: "mention",
986
+ at,
987
+ text: `# Pull Request Review: #${pr.number} ${pr.title}\n\nAuthor: @${pr.author.login}\nURL: ${url}\n\n${pr.body ?? ""}`,
988
+ channel: githubChannel(input.repository, pr.number, url),
989
+ url,
990
+ meta: {
991
+ number: pr.number,
992
+ isPr: true,
993
+ kind: "pull_review",
994
+ repository: input.repository,
995
+ author: pr.author.login,
996
+ updatedAt: at
997
+ }
998
+ });
999
+ input.mark(prKey);
1000
+ }
1001
+ return triggers;
1002
+ }
585
1003
  // src/sources/feishu.ts
586
1004
  /**
587
1005
  * The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
@@ -592,17 +1010,17 @@ async function pollNotifications(input) {
592
1010
  * A chat is listened to only when `settings.feishu.chats` names it, because a bot in a busy chat sees everything and a
593
1011
  * Trigger per message would cost the team attention for nothing.
594
1012
  */
595
- const SOURCE = "feishu";
1013
+ const SOURCE$1 = "feishu";
596
1014
  /** 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
1015
  * the app's event subscription, so read it from `lark-cli event list` rather than assume it. */
598
1016
  const MESSAGE_EVENT = "im.message.receive_v1";
599
1017
  const feishuThread = (chatId, rootId, messageId) => ({
600
- source: SOURCE,
1018
+ source: SOURCE$1,
601
1019
  id: `${chatId}:${rootId ?? messageId}`
602
1020
  });
603
1021
  /** Where a reply to this message goes; `direct` is explicit because group and direct chat ids both start with `oc_`. */
604
1022
  const feishuChannel = (chatId, messageId, direct = false) => ({
605
- source: SOURCE,
1023
+ source: SOURCE$1,
606
1024
  thread: `feishu:${chatId}`,
607
1025
  address: {
608
1026
  chatId,
@@ -661,10 +1079,10 @@ function feishuTrigger(input, options) {
661
1079
  const url = event.message_app_link;
662
1080
  return {
663
1081
  id: key("feishu", event.message_id),
664
- source: SOURCE,
1082
+ source: SOURCE$1,
665
1083
  threads: [feishuThread(event.chat_id, event.root_id, event.message_id)],
666
1084
  actor: {
667
- source: SOURCE,
1085
+ source: SOURCE$1,
668
1086
  id: senderId
669
1087
  },
670
1088
  human: senderType === "user",
@@ -717,9 +1135,7 @@ async function chatMembers(cli, chatId, signal) {
717
1135
  chatId,
718
1136
  "--member-types",
719
1137
  "user",
720
- "--page-all",
721
- "--page-limit",
722
- "0"
1138
+ "--page-all"
723
1139
  ], { signal })).users ?? []).map((user) => ({
724
1140
  id: user.member_id,
725
1141
  name: user.name ?? user.member_id
@@ -891,6 +1307,97 @@ function consumeEvents(options) {
891
1307
  ended
892
1308
  };
893
1309
  }
1310
+ // src/sources/twitter.ts
1311
+ /**
1312
+ * The Twitter/X Source: searches keywords using `opencli twitter search` and turns feedback into Triggers,
1313
+ * and delivers responses back to the original tweet via `opencli twitter reply`.
1314
+ */
1315
+ const SOURCE = "twitter";
1316
+ z.looseObject({
1317
+ id: z.string(),
1318
+ author: z.string(),
1319
+ text: z.string(),
1320
+ created_at: z.string().nullish(),
1321
+ url: z.string()
1322
+ });
1323
+ const twitterThread = (id) => ({
1324
+ source: SOURCE,
1325
+ id
1326
+ });
1327
+ const twitterChannel = (url, id) => ({
1328
+ source: SOURCE,
1329
+ thread: threadKey(twitterThread(id)),
1330
+ address: {
1331
+ tweetUrl: url,
1332
+ tweetId: id
1333
+ }
1334
+ });
1335
+ function tweetTrigger(tweet, agentLogin) {
1336
+ const at = tweet.created_at ?? (/* @__PURE__ */ new Date()).toISOString();
1337
+ const addressed = agentLogin && tweet.text.toLowerCase().includes(`@${agentLogin.toLowerCase()}`);
1338
+ return {
1339
+ id: key("twitter-tweet", tweet.id),
1340
+ source: SOURCE,
1341
+ threads: [twitterThread(tweet.id)],
1342
+ actor: {
1343
+ source: SOURCE,
1344
+ id: tweet.author
1345
+ },
1346
+ human: true,
1347
+ ...addressed ? { addressed: "mention" } : {},
1348
+ at,
1349
+ text: tweet.text,
1350
+ url: tweet.url,
1351
+ channel: twitterChannel(tweet.url, tweet.id),
1352
+ meta: {
1353
+ tweetId: tweet.id,
1354
+ author: tweet.author
1355
+ }
1356
+ };
1357
+ }
1358
+ async function searchTweets(cli, query, options = {}) {
1359
+ const limit = options.limit ?? 15;
1360
+ const tweets = await runJson(cli, [
1361
+ "twitter",
1362
+ "search",
1363
+ query,
1364
+ "--product",
1365
+ "live",
1366
+ "--limit",
1367
+ String(limit),
1368
+ "-f",
1369
+ "json"
1370
+ ], { signal: options.signal });
1371
+ const list = Array.isArray(tweets) ? tweets : [];
1372
+ const triggers = [];
1373
+ for (const item of list) {
1374
+ if (!item.id || !item.text) continue;
1375
+ if (options.seen?.(item.id)) continue;
1376
+ options.mark?.(item.id);
1377
+ triggers.push(tweetTrigger(item, options.agentLogin));
1378
+ }
1379
+ return triggers;
1380
+ }
1381
+ async function replyTweet(cli, tweetUrl, text, options = {}) {
1382
+ await run(cli, [
1383
+ "twitter",
1384
+ "reply",
1385
+ tweetUrl,
1386
+ text
1387
+ ], { signal: options.signal });
1388
+ }
1389
+ async function twitterAccount(cli, signal) {
1390
+ try {
1391
+ return (await runJson(cli, [
1392
+ "twitter",
1393
+ "whoami",
1394
+ "-f",
1395
+ "json"
1396
+ ], { signal })).username ?? "";
1397
+ } catch {
1398
+ return "";
1399
+ }
1400
+ }
894
1401
  // src/infra/worktree.ts
895
1402
  /**
896
1403
  * Gives a ticket its own git worktree and branch, so two tickets can change one repository at once and neither sees the
@@ -926,15 +1433,63 @@ async function isGitRepository(directory) {
926
1433
  }
927
1434
  /**
928
1435
  * Creates the worktree for a ticket and returns its directory.
1436
+ * When `prNumber` is specified, fetches the PR branch/head and checks it out directly into the worktree.
929
1437
  *
930
1438
  * @throws when git cannot create the worktree, such as when the checkout has no commit yet; the caller then reports the
931
1439
  * ticket as failed instead of starting an agent in a directory that is not the repository.
932
1440
  */
933
1441
  async function prepareWorktree(options) {
934
- const { checkout, directory, branch, signal } = options;
1442
+ const { checkout, directory, branch, prNumber, repository, signal } = options;
935
1443
  await mkdir(directory, { recursive: true });
936
1444
  if ((await readdir(directory)).length) return directory;
937
1445
  if (!await isGitRepository(checkout)) return directory;
1446
+ if (prNumber) {
1447
+ let fetched = false;
1448
+ try {
1449
+ await run("git", [
1450
+ "-C",
1451
+ checkout,
1452
+ "fetch",
1453
+ "origin",
1454
+ `pull/${prNumber}/head:${branch}`
1455
+ ], {
1456
+ signal,
1457
+ timeoutMs: 6e4
1458
+ });
1459
+ fetched = true;
1460
+ } catch {
1461
+ if (repository) try {
1462
+ await run("git", [
1463
+ "-C",
1464
+ checkout,
1465
+ "fetch",
1466
+ `https://github.com/${repository}.git`,
1467
+ `pull/${prNumber}/head:${branch}`
1468
+ ], {
1469
+ signal,
1470
+ timeoutMs: 6e4
1471
+ });
1472
+ fetched = true;
1473
+ } catch {}
1474
+ }
1475
+ if (fetched) {
1476
+ await run("git", [
1477
+ "-C",
1478
+ checkout,
1479
+ "worktree",
1480
+ "add",
1481
+ directory,
1482
+ branch
1483
+ ], {
1484
+ signal,
1485
+ timeoutMs: 12e4
1486
+ }).catch(async (error) => {
1487
+ await removeWorktree(checkout, directory, signal, branch);
1488
+ throw new Error(`${directory} is not a branch point for PR #${prNumber}: ${error.message}`, { cause: error });
1489
+ });
1490
+ return directory;
1491
+ }
1492
+ }
938
1493
  await run("git", [
939
1494
  "-C",
940
1495
  checkout,
@@ -956,13 +1511,13 @@ async function prepareWorktree(options) {
956
1511
  signal,
957
1512
  timeoutMs: 12e4
958
1513
  }).catch(async (error) => {
959
- await removeWorktree(checkout, directory, signal);
1514
+ await removeWorktree(checkout, directory, signal, branch);
960
1515
  throw new Error(`${directory} is not a branch point: ${error.message}`, { cause: error });
961
1516
  });
962
1517
  return directory;
963
1518
  }
964
1519
  /** 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) {
1520
+ async function removeWorktree(checkout, directory, signal, branchToDelete) {
966
1521
  try {
967
1522
  await run("git", [
968
1523
  "-C",
@@ -976,6 +1531,76 @@ async function removeWorktree(checkout, directory, signal) {
976
1531
  timeoutMs: 12e4
977
1532
  });
978
1533
  } catch {}
1534
+ if (branchToDelete) try {
1535
+ await run("git", [
1536
+ "-C",
1537
+ checkout,
1538
+ "branch",
1539
+ "-D",
1540
+ branchToDelete
1541
+ ], {
1542
+ signal,
1543
+ timeoutMs: 1e4
1544
+ });
1545
+ } catch {}
1546
+ }
1547
+ // src/infra/pr-verifier.ts
1548
+ /**
1549
+ * Executes local automated verification commands (e.g. test suites, linters, build scripts)
1550
+ * inside a PR's checked-out worktree before code review.
1551
+ */
1552
+ async function runPrVerification(options) {
1553
+ const results = [];
1554
+ let allPassed = true;
1555
+ const timeoutMs = (options.timeoutSeconds ?? 300) * 1e3;
1556
+ for (const cmd of options.commands) {
1557
+ const start = Date.now();
1558
+ try {
1559
+ const output = await run("/bin/sh", ["-c", cmd], {
1560
+ cwd: options.cwd,
1561
+ env: options.env,
1562
+ timeoutMs,
1563
+ signal: options.signal
1564
+ });
1565
+ const durationMs = Date.now() - start;
1566
+ results.push({
1567
+ command: cmd,
1568
+ exitCode: 0,
1569
+ durationMs,
1570
+ stdout: output,
1571
+ stderr: "",
1572
+ passed: true
1573
+ });
1574
+ } catch (err) {
1575
+ const durationMs = Date.now() - start;
1576
+ allPassed = false;
1577
+ results.push({
1578
+ command: cmd,
1579
+ exitCode: err.exitCode ?? 1,
1580
+ durationMs,
1581
+ stdout: err.stdout ?? "",
1582
+ stderr: err.stderr ?? err.message ?? "",
1583
+ passed: false
1584
+ });
1585
+ break;
1586
+ }
1587
+ }
1588
+ const lines = [
1589
+ "### Automated Local Verification",
1590
+ "",
1591
+ allPassed ? "✅ **All local verification checks passed.**" : "❌ **Local verification failed.** The code in this PR failed one or more verification commands.",
1592
+ "",
1593
+ "| Command | Status | Duration |",
1594
+ "| :--- | :--- | :--- |"
1595
+ ];
1596
+ for (const r of results) lines.push(`| \`${r.command}\` | ${r.passed ? "✅ PASS" : "❌ FAIL (exit " + r.exitCode + ")"} | ${(r.durationMs / 1e3).toFixed(1)}s |`);
1597
+ for (const r of results) if (!r.passed) lines.push("", `#### Failure Log: \`${r.command}\``, "```text", (r.stderr || r.stdout || "Unknown error").trim().slice(-3e3), "```");
1598
+ return {
1599
+ passed: allPassed,
1600
+ totalCommands: options.commands.length,
1601
+ results,
1602
+ markdown: lines.join("\n")
1603
+ };
979
1604
  }
980
1605
  // src/runner.ts
981
1606
  /** 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 +1689,36 @@ function record(engine, repo, finished, log) {
1064
1689
  }
1065
1690
  }
1066
1691
  /** Posts the messages the Engine queued, one comment per message. */
1067
- async function send(channel, clis, log) {
1692
+ async function send(channel, clis, log, attentionConfig) {
1693
+ const quiet = isQuietHours(/* @__PURE__ */ new Date(), attentionConfig?.quietHours);
1694
+ const present = await isUserPresent(attentionConfig?.idleSecondsThreshold);
1068
1695
  for (const message of channel.drain()) {
1696
+ if (message.channel.source === "twitter") {
1697
+ const address = message.channel.address;
1698
+ if (!clis.twitter) {
1699
+ log(`Cannot answer on Twitter: the Twitter Source is off`);
1700
+ continue;
1701
+ }
1702
+ if (!address.tweetUrl) continue;
1703
+ try {
1704
+ await replyTweet(clis.twitter, address.tweetUrl, message.text);
1705
+ log(`Replied to tweet ${address.tweetUrl}`);
1706
+ } catch (error) {
1707
+ log(`Could not reply to tweet ${address.tweetUrl}: ${error.message}`);
1708
+ }
1709
+ continue;
1710
+ }
1069
1711
  if (message.channel.source === "feishu") {
1070
1712
  const address = message.channel.address;
1071
1713
  if (!clis.feishu) {
1072
1714
  log(`Cannot answer in ${address.chatId}: the Feishu Source is off`);
1073
1715
  continue;
1074
1716
  }
1717
+ if (quiet && message.kind !== "acknowledgement") log(`Quiet hours active (23:00-08:00); answered in ${address.chatId} quietly`);
1718
+ else if (present) log(`User is present at computer; answered in ${address.chatId}`);
1719
+ else log(`User is away; dispatched notification to mobile in ${address.chatId}`);
1075
1720
  try {
1076
1721
  await reply(clis.feishu, address.messageId, message.text, message.id);
1077
- log(`Answered in ${address.chatId}`);
1078
1722
  } catch (error) {
1079
1723
  log(`Could not answer in ${address.chatId}: ${error.message}`);
1080
1724
  }
@@ -1186,21 +1830,34 @@ var AgentExecutor = class {
1186
1830
  });
1187
1831
  }
1188
1832
  async execute(ticket, assignment, controller) {
1189
- const { settings, runner, stateDir, accounts, feishuCli, site } = this.options;
1833
+ const { settings, runner, stateDir, accounts, feishuCli, site, repo, log } = this.options;
1190
1834
  const directory = ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
1835
+ const trigger = repo?.triggers.get(ticket.origin.triggerId);
1836
+ const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
1837
+ const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
1191
1838
  try {
1192
1839
  const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
1193
1840
  await prepareWorktree({
1194
1841
  checkout: settings.checkout,
1195
1842
  directory,
1196
1843
  branch,
1844
+ prNumber: isPrReview ? prNumber : void 0,
1845
+ repository: settings.github?.repository,
1197
1846
  signal: controller.signal
1198
1847
  });
1199
1848
  if (settings.executor.prepare) await run("/bin/sh", ["-c", settings.executor.prepare], {
1200
1849
  env: this.variables(ticket, directory, branch),
1201
1850
  timeoutMs: 12e4
1202
1851
  });
1203
- const prompt = await this.options.prompt(ticket, directory, branch);
1852
+ let prVerification;
1853
+ if (isPrReview && settings.github?.prReview?.verifyCommands?.length) prVerification = await runPrVerification({
1854
+ cwd: directory,
1855
+ commands: settings.github.prReview.verifyCommands,
1856
+ timeoutSeconds: settings.github.prReview.verifyTimeoutSeconds,
1857
+ signal: controller.signal
1858
+ });
1859
+ const prompt = await this.options.prompt(ticket, directory, branch, prVerification);
1860
+ const isAutonomous = ticket.mandate.strength === "inferred" && !isPrReview;
1204
1861
  const result = await runner.run({
1205
1862
  prompt,
1206
1863
  cwd: directory,
@@ -1210,9 +1867,62 @@ var AgentExecutor = class {
1210
1867
  } : accounts, this.variables(ticket, directory, branch)),
1211
1868
  signal: controller.signal,
1212
1869
  timeoutMs: settings.executor.timeoutMinutes * 6e4,
1213
- model: settings.executor.model
1870
+ model: settings.executor.model,
1871
+ readOnly: isAutonomous
1214
1872
  });
1215
1873
  const report = result.report ?? inferReport(result.finalText, result.ok);
1874
+ if (isPrReview && prNumber && settings.github) {
1875
+ const textToAnalyze = `${result.finalText}\n${report.summary}`;
1876
+ const decisionMatch = /DECISION:\s*(MERGE|APPROVE|REQUEST_CHANGES|CLOSE)/i.exec(textToAnalyze);
1877
+ const decision = decisionMatch ? decisionMatch[1].toUpperCase() : report.state === "ready" ? "APPROVE" : "REQUEST_CHANGES";
1878
+ if (decision === "MERGE" && settings.github.prReview?.autoMerge && (!prVerification || prVerification.passed)) {
1879
+ const method = settings.github.prReview.mergeMethod ?? "squash";
1880
+ try {
1881
+ await run(settings.github.cli, [
1882
+ "pr",
1883
+ "merge",
1884
+ String(prNumber),
1885
+ `--${method}`,
1886
+ "--auto",
1887
+ "--repo",
1888
+ settings.github.repository
1889
+ ]);
1890
+ await run(settings.github.cli, [
1891
+ "pr",
1892
+ "comment",
1893
+ String(prNumber),
1894
+ "--repo",
1895
+ settings.github.repository,
1896
+ "-b",
1897
+ `🤖 **SuperAgent Review Verdict: MERGED**\n\n${deliverable(report.summary)}\n\nAutomated local verification passed and code review approved.`
1898
+ ]).catch(() => {});
1899
+ log?.(`Merged PR #${prNumber} on ${settings.github.repository}`);
1900
+ } catch (mergeErr) {
1901
+ log?.(`Could not merge PR #${prNumber}: ${mergeErr.message}`);
1902
+ }
1903
+ } else if (decision === "CLOSE") try {
1904
+ await run(settings.github.cli, [
1905
+ "pr",
1906
+ "close",
1907
+ String(prNumber),
1908
+ "--repo",
1909
+ settings.github.repository,
1910
+ "-c",
1911
+ `🤖 **SuperAgent Review Verdict: CLOSED**\n\n${deliverable(report.summary)}`
1912
+ ]);
1913
+ log?.(`Closed PR #${prNumber} on ${settings.github.repository}`);
1914
+ } catch (closeErr) {
1915
+ log?.(`Could not close PR #${prNumber}: ${closeErr.message}`);
1916
+ }
1917
+ }
1918
+ if (report.followupAfterSeconds && report.followupAfterSeconds > 0) await new TimerStore(stateDir).save({
1919
+ id: `followup-${ticket.id}-${Date.now()}`,
1920
+ kind: "followup",
1921
+ ticketId: ticket.id,
1922
+ dueAt: new Date(Date.now() + report.followupAfterSeconds * 1e3).toISOString(),
1923
+ prompt: `Follow-up checkpoint for ticket ${ticket.id}: ${report.summary}`,
1924
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1925
+ });
1216
1926
  await appendLog(directory, prompt, result.raw.slice(-2e4), report);
1217
1927
  site.reported(ticket.id, {
1218
1928
  state: report.state ?? (result.ok ? "ready" : "failed"),
@@ -1288,8 +1998,10 @@ async function runLoop(options) {
1288
1998
  const signal = stop.signal;
1289
1999
  const github = settings.github?.enabled ? settings.github : void 0;
1290
2000
  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.");
2001
+ const twitter = settings.twitter?.enabled ? settings.twitter : void 0;
2002
+ if (!github && !feishu && !twitter) throw new Error("No Source is on in settings.yaml; nothing to poll.");
1292
2003
  const login = github ? await agentLogin(github.cli, signal) : "";
2004
+ const twitterBot = twitter ? await twitterAccount(twitter.cli, signal) : "";
1293
2005
  const accounts = {
1294
2006
  stateDir: settings.stateDir,
1295
2007
  githubCli: github?.cli ?? "gh",
@@ -1350,10 +2062,15 @@ async function runLoop(options) {
1350
2062
  accounts,
1351
2063
  ...feishu ? { feishuCli: feishu.cli } : {},
1352
2064
  site,
1353
- prompt: async (ticket, directory, branch) => {
2065
+ repo,
2066
+ log,
2067
+ prompt: async (ticket, directory, branch, prVerification) => {
1354
2068
  const trigger = repo.triggers.get(ticket.origin.triggerId);
1355
2069
  const source = trigger?.source === "feishu" ? "feishu" : "github";
2070
+ const isPrReview = Boolean(trigger?.meta?.isPr) || ticket.mandate.scope === "pr_review";
2071
+ const prNumber = typeof trigger?.meta?.number === "number" ? trigger.meta.number : void 0;
1356
2072
  const notes = ticket.inputs.flatMap((input) => input.kind === "text" ? [input.text] : []);
2073
+ const readOnly = ticket.mandate.strength === "inferred" && !isPrReview;
1357
2074
  return composePrompt({
1358
2075
  ticket,
1359
2076
  trigger,
@@ -1364,7 +2081,12 @@ async function runLoop(options) {
1364
2081
  instructions: settings.prompts,
1365
2082
  branch,
1366
2083
  standing,
1367
- notes
2084
+ notes,
2085
+ readOnly,
2086
+ isPrReview,
2087
+ prNumber,
2088
+ prVerification,
2089
+ autoMergeAllowed: Boolean(github?.prReview?.autoMerge)
1368
2090
  });
1369
2091
  }
1370
2092
  });
@@ -1437,6 +2159,12 @@ async function runLoop(options) {
1437
2159
  const nextLine = () => handle ? handle.next(settings.executor.streamIdleMs) : Promise.resolve(false);
1438
2160
  const delivered = /* @__PURE__ */ new Set();
1439
2161
  engine.options.executor = executor;
2162
+ const timerStore = new TimerStore(settings.stateDir);
2163
+ const watcherEngine = new WatcherEngine(settings.stateDir);
2164
+ const budgetGuard = new BudgetGuard(settings.budget, {
2165
+ get: () => repo.getMeta("budget:state"),
2166
+ set: (s) => repo.setMeta("budget:state", s)
2167
+ });
1440
2168
  try {
1441
2169
  for (const ticket of repo.tickets.active()) engine.updateTicket(ticket);
1442
2170
  executor.recover(repo.tickets.active());
@@ -1477,9 +2205,98 @@ async function runLoop(options) {
1477
2205
  mark: (id) => repo.setMeta(seenKey(id), true)
1478
2206
  });
1479
2207
  for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
2208
+ if (github.prReview?.enabled && github.prReview?.pollOpenPrs !== false) try {
2209
+ const prTriggers = await pollOpenPullRequests({
2210
+ cli: github.cli,
2211
+ repository: github.repository,
2212
+ agent: login,
2213
+ signal,
2214
+ seen: (id) => repo.getMeta(id) === true,
2215
+ mark: (id) => repo.setMeta(id, true)
2216
+ });
2217
+ for (const trigger of prTriggers) if (engine.receive(trigger) !== "duplicate") log(`Received PR review trigger for #${trigger.meta?.number} from ${trigger.actor.id}`);
2218
+ } catch (prErr) {
2219
+ if (!signal.aborted) log(`PR poll failed: ${prErr.message}`);
2220
+ }
1480
2221
  since = round;
1481
2222
  repo.setMeta(pollKey, since);
1482
2223
  }
2224
+ if (twitter) try {
2225
+ const triggers = await searchTweets(twitter.cli, twitter.query, {
2226
+ seen: (id) => repo.getMeta(`twitter:seen:${id}`) === true,
2227
+ mark: (id) => repo.setMeta(`twitter:seen:${id}`, true),
2228
+ agentLogin: twitterBot,
2229
+ signal
2230
+ });
2231
+ for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received Twitter trigger ${trigger.id} from @${trigger.actor.id}`);
2232
+ } catch (error) {
2233
+ if (!signal.aborted) log(`Twitter poll failed: ${error.message}`);
2234
+ }
2235
+ if (settings.watchers && settings.watchers.length > 0) for (const watcher of settings.watchers) try {
2236
+ const check = await watcherEngine.check(watcher, { now: /* @__PURE__ */ new Date() });
2237
+ if (check.triggered && check.diffText) {
2238
+ const budgetCheck = await budgetGuard.check();
2239
+ if (!budgetCheck.allowed) {
2240
+ log(`Watcher ${watcher.id} triggered but postponed: ${budgetCheck.reason}`);
2241
+ continue;
2242
+ }
2243
+ await budgetGuard.record();
2244
+ log(`Watcher ${watcher.id} detected output changes; generating trigger`);
2245
+ const trigger = {
2246
+ id: `watcher:${watcher.id}:${Date.now()}`,
2247
+ source: "watcher",
2248
+ threads: [{
2249
+ source: "watcher",
2250
+ id: watcher.id
2251
+ }],
2252
+ actor: {
2253
+ source: "watcher",
2254
+ id: "system"
2255
+ },
2256
+ human: false,
2257
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2258
+ text: check.diffText,
2259
+ meta: { watcherId: watcher.id }
2260
+ };
2261
+ if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received watcher trigger ${trigger.id}`);
2262
+ }
2263
+ } catch (error) {
2264
+ log(`Watcher ${watcher.id} check error: ${error.message}`);
2265
+ }
2266
+ if (settings.timers?.enabled) {
2267
+ const dueTimers = await timerStore.getDue(/* @__PURE__ */ new Date());
2268
+ for (const timer of dueTimers) {
2269
+ const budgetCheck = await budgetGuard.check();
2270
+ if (!budgetCheck.allowed) {
2271
+ log(`Timer ${timer.id} postponed: ${budgetCheck.reason}`);
2272
+ break;
2273
+ }
2274
+ await budgetGuard.record();
2275
+ log(`Firing due timer ${timer.id} (${timer.kind})`);
2276
+ const trigger = {
2277
+ id: `timer:${timer.id}:${Date.now()}`,
2278
+ source: "timer",
2279
+ threads: [{
2280
+ source: "timer",
2281
+ id: timer.ticketId ?? timer.id
2282
+ }],
2283
+ actor: {
2284
+ source: "timer",
2285
+ id: "system"
2286
+ },
2287
+ human: false,
2288
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2289
+ text: timer.prompt,
2290
+ meta: {
2291
+ timerId: timer.id,
2292
+ kind: timer.kind,
2293
+ ticketId: timer.ticketId
2294
+ }
2295
+ };
2296
+ if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received timer trigger ${trigger.id}`);
2297
+ await timerStore.processDue(timer, /* @__PURE__ */ new Date());
2298
+ }
2299
+ }
1483
2300
  engine.evaluateDue();
1484
2301
  decide(engine, decided.drain(), log);
1485
2302
  record(engine, repo, finished.drain(), log);
@@ -1490,15 +2307,16 @@ async function runLoop(options) {
1490
2307
  await repo.flush();
1491
2308
  await send(channel, {
1492
2309
  ...github ? { github: github.cli } : {},
1493
- ...feishu ? { feishu: feishu.cli } : {}
1494
- }, log);
2310
+ ...feishu ? { feishu: feishu.cli } : {},
2311
+ ...twitter ? { twitter: twitter.cli } : {}
2312
+ }, log, settings.attention);
1495
2313
  await repo.flush();
1496
2314
  await sync();
1497
2315
  } catch (error) {
1498
2316
  if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
1499
2317
  }
1500
2318
  if (options.once) break;
1501
- const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity);
2319
+ const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity, twitter?.pollSeconds ?? Infinity);
1502
2320
  let left = options.once ? 0 : seconds * 1e3;
1503
2321
  while (left > 0 && !signal.aborted) {
1504
2322
  const began = Date.now();
@@ -1511,6 +2329,300 @@ async function runLoop(options) {
1511
2329
  stop.abort();
1512
2330
  if (options.once && !process.env.VITEST) setImmediate(() => process.exit(process.exitCode ?? 0));
1513
2331
  }
2332
+ // src/setup.ts
2333
+ /**
2334
+ * `superagent setup` fills the settings the Sources need from the CLIs that already know the answers.
2335
+ *
2336
+ * GitHub knows which account `gh` acts as; Feishu knows which chats the bot is in and who is in them. Asking those CLIs
2337
+ * 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
2338
+ * — so a setup is one command per Source.
2339
+ *
2340
+ * Nothing is written unless the CLI answered: a failing lookup leaves that section of `settings.yaml` as it was.
2341
+ */
2342
+ /** The login `gh` acts as, which is the account the agent reads notifications and opens pull requests under. */
2343
+ async function githubLogin(cli) {
2344
+ const user = await runJson(cli, ["api", "user"]);
2345
+ if (!user.login) throw new CliError(cli, `${cli} api user named no login`, "", "");
2346
+ return user.login;
2347
+ }
2348
+ /** The repository `github.repository` names, read through the agent's CLI so a private one is found too. */
2349
+ async function repositoryMeta(cli, repository) {
2350
+ return runJson(cli, [
2351
+ "api",
2352
+ `repos/${repository}`,
2353
+ "--jq",
2354
+ "{owner: .owner.login, name: .name, private: .private}"
2355
+ ]);
2356
+ }
2357
+ /** The owner of a checkout path, when that path is a GitHub repository the agent's account can read. */
2358
+ async function checkoutRepository(cli, origin) {
2359
+ if (!origin) return void 0;
2360
+ const match = /github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/.exec(origin.trim());
2361
+ if (!match) return void 0;
2362
+ try {
2363
+ const repo = await repositoryMeta(cli, `${match[1]}/${match[2]}`);
2364
+ return `${repo.owner}/${repo.name}`;
2365
+ } catch {
2366
+ return;
2367
+ }
2368
+ }
2369
+ /** The remote URL of the clone in `checkout`, as the worktree that `poll` starts from reads it. */
2370
+ async function originOf(checkout, stateDir) {
2371
+ return (await run("git", [
2372
+ "-C",
2373
+ checkout,
2374
+ "remote",
2375
+ "get-url",
2376
+ "origin"
2377
+ ], { cwd: stateDir }).catch(() => "")).trim() || void 0;
2378
+ }
2379
+ const ChatSchema = (value) => {
2380
+ const chat = value;
2381
+ return {
2382
+ chatId: String(chat.chat_id ?? ""),
2383
+ name: String(chat.name ?? chat.chat_id ?? "")
2384
+ };
2385
+ };
2386
+ /**
2387
+ * The group chats the bot can hear, which are the only ones it may listen to.
2388
+ *
2389
+ * `+chat-list` is user-only for direct chats, so this asks for groups only; a bot needs no user login for that.
2390
+ */
2391
+ async function botChats(cli) {
2392
+ const result = await runJson(cli, [
2393
+ "im",
2394
+ "+chat-list",
2395
+ "--as",
2396
+ "bot",
2397
+ "--types",
2398
+ "group",
2399
+ "--page-all"
2400
+ ]);
2401
+ const listing = result;
2402
+ return (Array.isArray(result) ? result : listing?.items ?? listing?.chats ?? []).map(ChatSchema).filter((chat) => chat.chatId);
2403
+ }
2404
+ /**
2405
+ * The people in a chat, found by their user name rather than by open id.
2406
+ *
2407
+ * The CLI cannot search users by name through the bot, so `names` is resolved against the members the bot can list: a
2408
+ * name matches a member's display name exactly, or, when no member matches, the part of a display name before `@` or
2409
+ * a space — which is how a person writes their GitHub name in Feishu. Ids the person typed are kept as they are.
2410
+ */
2411
+ async function resolveMembers(cli, chatId, names) {
2412
+ if (!names.length) return {
2413
+ found: [],
2414
+ missing: []
2415
+ };
2416
+ const found = names.filter((name) => name.startsWith("ou_"));
2417
+ const wanted = names.filter((name) => !name.startsWith("ou_"));
2418
+ const missing = [];
2419
+ if (!wanted.length) return {
2420
+ found,
2421
+ missing
2422
+ };
2423
+ const members = await chatMembers(cli, chatId);
2424
+ for (const name of wanted) {
2425
+ const match = members.find((member) => member.name === name) ?? members.find((member) => (member.name.split(/[@\s]/)[0] ?? "") === name);
2426
+ if (match) found.push(match.id);
2427
+ else missing.push(name);
2428
+ }
2429
+ return {
2430
+ found,
2431
+ missing
2432
+ };
2433
+ }
2434
+ /** Splits `a,b, c` and drops the blanks, so one flag can name several people. */
2435
+ const names = (value) => (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
2436
+ const MANAGED = ["github", "feishu"];
2437
+ /**
2438
+ * The settings file with only the Source sections replaced, so this command keeps the text an operator wrote.
2439
+ *
2440
+ * `writeSettings` writes a whole file and loses every comment; that is fine for `init`, which starts from nothing, but a
2441
+ * setup run should leave the rest of the file — the prompt, the rules, the executor — exactly as a person left it.
2442
+ */
2443
+ function mergeSections(text, settings) {
2444
+ const values = settings;
2445
+ const sections = MANAGED.filter((name) => values[name] !== void 0).map((name) => `${name}:\n${stringifyYaml(values[name], 2)}`);
2446
+ const kept = [];
2447
+ /** Sections the text did not have; they go after the settings the text does have. */
2448
+ const added = [];
2449
+ let dropping = false;
2450
+ let placed = false;
2451
+ const hold = (section) => {
2452
+ if (placed) added.push(section);
2453
+ else {
2454
+ kept.push(section);
2455
+ placed = true;
2456
+ }
2457
+ };
2458
+ for (const line of text.split("\n")) {
2459
+ if (line && !/^[\s-]/.test(line)) {
2460
+ const [name, ...rest] = line.split(":");
2461
+ dropping = MANAGED.includes(name) && rest.length === 1;
2462
+ if (dropping) hold(sections.shift() ?? "");
2463
+ }
2464
+ if (!dropping) kept.push(line);
2465
+ }
2466
+ return [
2467
+ kept.join("\n").replace(/\n+$/, ""),
2468
+ ...sections,
2469
+ ...added
2470
+ ].join("\n") + "\n";
2471
+ }
2472
+ /** Reads the settings, lets `edit` change them and writes them back when `edit` returns what it wrote. */
2473
+ async function update(dir, edit) {
2474
+ const path = join(dir, SETTINGS_FILE);
2475
+ const settings = await readSettings(path);
2476
+ if (!await edit(settings)) return void 0;
2477
+ await writeFile(path, mergeSections(await readFile(path, "utf8"), settings), "utf8");
2478
+ return settings;
2479
+ }
2480
+ async function setupGithub(options) {
2481
+ const lines = [];
2482
+ let failed = false;
2483
+ let login;
2484
+ await update(options.dir, async (settings) => {
2485
+ const cli = settings.github?.cli ?? "gh";
2486
+ try {
2487
+ login = await githubLogin(cli);
2488
+ } catch (error) {
2489
+ lines.push(`GitHub: ${error.message}`);
2490
+ failed = true;
2491
+ return false;
2492
+ }
2493
+ lines.push(`GitHub account: ${login} (${cli})`);
2494
+ const origin = options.stateDir ? await originOf(settings.checkout, options.stateDir) : void 0;
2495
+ const repository = settings.github?.repository ?? await checkoutRepository(cli, origin);
2496
+ try {
2497
+ const repo = repository ? await repositoryMeta(cli, repository) : void 0;
2498
+ const github = settings.github = {
2499
+ ...settings.github ?? {
2500
+ enabled: true,
2501
+ cli,
2502
+ repository: "",
2503
+ pollSeconds: 60,
2504
+ allowed: []
2505
+ },
2506
+ enabled: settings.github?.enabled ?? true,
2507
+ cli,
2508
+ repository: repo ? `${repo.owner}/${repo.name}` : settings.github?.repository ?? "",
2509
+ allowed: options.allow.length ? [...options.allow] : settings.github?.allowed ?? []
2510
+ };
2511
+ lines.push(repo ? `Repository: ${repo.owner}/${repo.name}${repo.private ? " (private)" : ""}` : "Repository: not found; set `github.repository`");
2512
+ if (!repo) failed = true;
2513
+ lines.push(`Allowed logins: ${github.allowed.join(", ") || "(none)"}`);
2514
+ 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.`);
2515
+ return true;
2516
+ } catch (error) {
2517
+ lines.push(`GitHub: ${error.message}`);
2518
+ failed = true;
2519
+ return false;
2520
+ }
2521
+ });
2522
+ return {
2523
+ lines,
2524
+ failed
2525
+ };
2526
+ }
2527
+ async function findChat(cli, wanted, current) {
2528
+ if (wanted?.startsWith("oc_")) return wanted;
2529
+ const chats = await botChats(cli);
2530
+ const known = current.feishu?.chats?.[0]?.chatId;
2531
+ if (!wanted && known) return known;
2532
+ if (!wanted) return chats.length === 1 ? chats[0].chatId : void 0;
2533
+ return (chats.find((chat) => chat.name === wanted) ?? chats.find((chat) => chat.name.includes(wanted)))?.chatId;
2534
+ }
2535
+ async function setupFeishu(options) {
2536
+ const lines = [];
2537
+ let failed = false;
2538
+ await update(options.dir, async (settings) => {
2539
+ const cli = settings.feishu?.cli ?? "lark-cli";
2540
+ const idsOnly = options.allow.length > 0 && options.allow.every((name) => name.startsWith("ou_"));
2541
+ let chatId;
2542
+ let chats = [];
2543
+ let listing = "";
2544
+ try {
2545
+ chats = await botChats(cli);
2546
+ } catch (error) {
2547
+ listing = error.message;
2548
+ }
2549
+ try {
2550
+ chatId = await findChat(cli, options.chat, settings);
2551
+ } catch (error) {
2552
+ listing ||= error.message;
2553
+ }
2554
+ const known = settings.feishu?.chats?.some((item) => item.chatId === chatId) ?? false;
2555
+ if (chatId && !idsOnly && !known && !chats.some((item) => item.chatId === chatId)) {
2556
+ 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}.`);
2557
+ failed = true;
2558
+ return false;
2559
+ }
2560
+ if (!chatId) {
2561
+ 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_…`.");
2562
+ failed = true;
2563
+ return false;
2564
+ }
2565
+ const chat = chats.find((item) => item.chatId === chatId);
2566
+ let allowed = settings.feishu?.allowed ?? [];
2567
+ if (options.allow.length) {
2568
+ const resolved = await resolveMembers(cli, chatId, options.allow).catch((error) => {
2569
+ lines.push(`Feishu: ${error.message}`);
2570
+ failed = true;
2571
+ return {
2572
+ found: [],
2573
+ missing: []
2574
+ };
2575
+ });
2576
+ allowed = [.../* @__PURE__ */ new Set([...allowed, ...resolved.found])];
2577
+ if (resolved.missing.length) {
2578
+ 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\`.`);
2579
+ failed = true;
2580
+ }
2581
+ }
2582
+ const feishu = settings.feishu = {
2583
+ ...settings.feishu ?? {
2584
+ enabled: true,
2585
+ cli,
2586
+ chats: [],
2587
+ directMessages: true,
2588
+ allowed: []
2589
+ },
2590
+ enabled: settings.feishu?.enabled ?? true,
2591
+ cli,
2592
+ chats: [{
2593
+ chatId,
2594
+ name: chat?.name ?? settings.feishu?.chats?.[0]?.name ?? chatId
2595
+ }],
2596
+ syncChat: chatId,
2597
+ allowed
2598
+ };
2599
+ lines.push(`Feishu chat: ${feishu.chats[0].name} (${chatId})`);
2600
+ lines.push(`Allowed: the chat's members (\`syncChat\`)${allowed.length ? `, and the ${allowed.length} open id(s) listed` : ""}`);
2601
+ return true;
2602
+ });
2603
+ return {
2604
+ lines,
2605
+ failed
2606
+ };
2607
+ }
2608
+ /** Runs the steps in order and prints what each found; a failed GitHub step still lets Feishu run. */
2609
+ async function setup(options) {
2610
+ const targets = options.targets.length ? options.targets : ["github", "feishu"];
2611
+ let failed = false;
2612
+ try {
2613
+ for (const target of targets) {
2614
+ const report = target === "github" ? await setupGithub(options) : await setupFeishu(options);
2615
+ for (const line of report.lines) options.log(line);
2616
+ failed ||= report.failed;
2617
+ }
2618
+ } catch (error) {
2619
+ options.log(error.message);
2620
+ return 1;
2621
+ }
2622
+ options.log("");
2623
+ options.log(`Wrote ${join(options.dir, SETTINGS_FILE)}. Next: \`superagent doctor\`, then \`superagent poll\`.`);
2624
+ return failed ? 1 : 0;
2625
+ }
1514
2626
  // src/cli.ts
1515
2627
  /**
1516
2628
  * `superagent` command line: create an installation, inspect it, and run one ticket by hand.
@@ -1521,12 +2633,20 @@ async function runLoop(options) {
1521
2633
  const USAGE = `superagent — an agent that turns GitHub and Feishu requests into tickets
1522
2634
 
1523
2635
  superagent init [dir] create ${SETTINGS_FILE} and the state directory in dir (default: .)
2636
+ superagent setup [dir] [what…] fill the GitHub and Feishu settings from the configured CLIs
1524
2637
  superagent status [dir] print open tickets and recent activity as Markdown
1525
2638
  superagent doctor [dir] show which coding agents are installed and which one is selected
1526
2639
  superagent agents list the coding agents a configuration may name
1527
2640
  superagent run <dir> -p <text> run one prompt on the configured agent, in a directory it names
1528
2641
  superagent poll [dir] [--once] poll the Sources and run the tickets they bring, once or until interrupted
1529
2642
 
2643
+ superagent setup asks the CLIs that already know the answers, so a person does not copy ids out of a web page:
2644
+
2645
+ --allow <names> logins or Feishu user names that may ask for work, comma separated
2646
+ (a name becomes the member's open id; the chat's members are added too)
2647
+ --chat <id|name> the Feishu chat the bot listens to
2648
+ github, feishu set up only one of them (the default is both)
2649
+
1530
2650
  Every command that reads an installation takes the directory that holds ${SETTINGS_FILE}.`;
1531
2651
  async function exists(path) {
1532
2652
  try {
@@ -1567,6 +2687,29 @@ async function init(dir) {
1567
2687
  ].join("\n"));
1568
2688
  return 0;
1569
2689
  }
2690
+ /** Fills the Source settings from GitHub and Feishu; the options are read here so the module stays about the CLIs. */
2691
+ async function setupSources(dir, rest) {
2692
+ const flag = (name) => {
2693
+ const index = rest.indexOf(name);
2694
+ return index < 0 ? void 0 : rest[index + 1];
2695
+ };
2696
+ const targets = rest.filter((item) => item === "github" || item === "feishu");
2697
+ let settings;
2698
+ try {
2699
+ settings = await readSettings(join(dir, SETTINGS_FILE));
2700
+ } catch (error) {
2701
+ process.stderr.write(`${error.message}\n`);
2702
+ return 1;
2703
+ }
2704
+ return setup({
2705
+ dir,
2706
+ targets: [...new Set(targets)],
2707
+ allow: names(flag("--allow")),
2708
+ chat: flag("--chat"),
2709
+ stateDir: await exists(settings.stateDir) ? settings.stateDir : void 0,
2710
+ log: (line) => process.stdout.write(`${line}\n`)
2711
+ });
2712
+ }
1570
2713
  async function status(dir) {
1571
2714
  const { tickets, threads, decisions, triggers: all, exists: found } = await readState(await stateDirOf(dir));
1572
2715
  const triggers = new Map(all.map((trigger) => [trigger.id, trigger]));
@@ -1689,6 +2832,7 @@ async function main(argv) {
1689
2832
  const dirOf = (index) => rest[index] && !rest[index].startsWith("-") ? resolve(rest[index]) : process.cwd();
1690
2833
  switch (command) {
1691
2834
  case "init": return init(rest[0] ? resolve(rest[0]) : process.cwd());
2835
+ case "setup": return setupSources(dirOf(0), rest);
1692
2836
  case "status": return status(dirOf(0));
1693
2837
  case "doctor": return doctor(dirOf(0));
1694
2838
  case "agents":