superagent-skill 0.1.0 → 0.2.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,106 +1,10 @@
1
- import { O as latestReport, P as threadKey, S as key, a as readSettings, c as AGENT_NAMES, g as Engine, h as readState, l as installed, m as FileRepositories, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor } from "./settings-BewLFAqT.mjs";
2
- import { access, lstat, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
3
- import { delimiter, join, resolve } from "node:path";
4
- import { execFile, spawn } from "node:child_process";
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";
5
2
  import { z } from "zod";
3
+ import { access, appendFile, mkdir, readFile, readdir, stat } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { execFile, spawn } from "node:child_process";
6
6
  import { homedir } from "node:os";
7
- // src/infra/environment.ts
8
- /**
9
- * Writes the CLI shims and the isolated git configuration that bind a run to the agent's accounts.
10
- *
11
- * Each shim strips its own directory from PATH before it execs, so a wrapper script that resolves `gh` by name reaches the
12
- * real binary instead of looping. The git configuration replaces the operator's global configuration for the run, so a
13
- * worker cannot push with the operator's credentials.
14
- *
15
- * These are guardrails, not an OS boundary: a run shares the operator's OS user and can read their home directory.
16
- */
17
- const MARKER = "# Written by superagent on every start; edits are lost.";
18
- /** Commands the shims provide, which a blocked list must never shadow. */
19
- const WORKER_COMMANDS = [
20
- "gh",
21
- "git",
22
- "lark-cli"
23
- ];
24
- const workerBin = (stateDir) => join(stateDir, "worker-bin");
25
- const workerGitConfig = (stateDir) => join(stateDir, "worker-gitconfig");
26
- const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
27
- const gitQuote = (value) => `"${value.replace(/[\\"]/g, (char) => `\\${char}`)}"`;
28
- const credentialHelper = (cli) => `!${shellQuote(cli)} auth git-credential`;
29
- async function written(file) {
30
- try {
31
- const stat = await lstat(file);
32
- if (!stat.isFile() || stat.size > 4096) return false;
33
- return (await readFile(file, "utf8")).includes(MARKER);
34
- } catch {
35
- return false;
36
- }
37
- }
38
- async function own(file, content) {
39
- const temporary = `${file}.${process.pid}.tmp`;
40
- await writeFile(temporary, content, { mode: 384 });
41
- await rename(temporary, file);
42
- }
43
- /**
44
- * Writes the shims and git configuration, refusing to overwrite files it did not write.
45
- * @throws when a file in the shim directory or at the git configuration path was written by something else.
46
- */
47
- async function writeEnvironment(accounts, blockedCommands) {
48
- const dir = workerBin(accounts.stateDir);
49
- await mkdir(dir, { recursive: true });
50
- const before = await readdir(dir);
51
- 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.`);
52
- const kept = /* @__PURE__ */ new Set();
53
- const shim = async (name, body) => {
54
- const temporary = join(dir, `.${name}.${process.pid}.tmp`);
55
- await writeFile(temporary, `#!/bin/sh\n${MARKER}\n${body}\n`, { mode: 493 });
56
- await rename(temporary, join(dir, name));
57
- kept.add(name);
58
- };
59
- const withoutShims = [
60
- `self=${shellQuote(dir)}`,
61
- "rest=",
62
- "IFS=:",
63
- "set -f",
64
- "for entry in $PATH; do [ \"$entry\" = \"$self\" ] || rest=\"${rest:+$rest:}$entry\"; done",
65
- "set +f",
66
- "unset IFS",
67
- "PATH=$rest",
68
- "export PATH"
69
- ].join("\n");
70
- const run = (program) => `${withoutShims}\nexec ${shellQuote(program)} "$@"`;
71
- const fail = (message) => `echo ${shellQuote(message)} >&2\nexit 1`;
72
- await shim("gh", run(accounts.githubCli));
73
- await shim("lark-cli", accounts.feishuCli ? run(accounts.feishuCli) : fail("lark-cli is unavailable: this installation has no Feishu bot."));
74
- 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}.`));
75
- for (const name of before) if (!kept.has(name)) await unlink(join(dir, name));
76
- await own(workerGitConfig(accounts.stateDir), [
77
- MARKER,
78
- "[user]",
79
- " useConfigOnly = true",
80
- "[credential]",
81
- " helper =",
82
- "[credential \"https://github.com\"]",
83
- `\thelper = ${gitQuote(credentialHelper(accounts.githubCli))}`,
84
- "[url \"https://github.com/\"]",
85
- " insteadOf = git@github.com:",
86
- " insteadOf = ssh://git@github.com:",
87
- "[filter \"lfs\"]",
88
- " clean = git-lfs clean -- %f",
89
- " smudge = git-lfs smudge -- %f",
90
- " process = git-lfs filter-process",
91
- " required = true"
92
- ].join("\n") + "\n");
93
- }
94
- /** Environment variables a run receives, with the shim directory first on PATH. */
95
- function runEnvironment(accounts, variables) {
96
- return {
97
- ...variables,
98
- PATH: [workerBin(accounts.stateDir), process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"].join(delimiter),
99
- GIT_CONFIG_GLOBAL: workerGitConfig(accounts.stateDir),
100
- GIT_CONFIG_SYSTEM: "/dev/null",
101
- GIT_TERMINAL_PROMPT: "0"
102
- };
103
- }
7
+ import { fileURLToPath } from "node:url";
104
8
  // src/infra/commands.ts
105
9
  /** Runs the Source CLIs (`gh`, `lark-cli`) and reads their JSON. Every call is bounded and never prompts. */
106
10
  var CliError = class extends Error {
@@ -150,9 +54,26 @@ async function runJson(program, argv, options = {}) {
150
54
  return parsed;
151
55
  }
152
56
  // src/prompts.ts
57
+ /**
58
+ * The prompt a ticket's agent receives.
59
+ *
60
+ * It is assembled here rather than read from files so that an installation has one thing to read: `settings.yaml`. The
61
+ * team-editable part is `prompts.instructions`, which the operator writes in their own words.
62
+ */
63
+ /**
64
+ * The rules that hold for every ticket, one file each beside this one.
65
+ *
66
+ * They were files in the DSH bundle, where an operator edited them in the panel; here the text is part of the install,
67
+ * so it is read from the file next to the source rather than copied into this module.
68
+ */
69
+ const STANDING_FILES = ["scope.md", "delivery.md"];
70
+ const STANDING_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "prompts");
71
+ async function standingRules() {
72
+ return Promise.all(STANDING_FILES.map(async (name) => (await readFile(join(STANDING_DIR, name), "utf8")).trim()));
73
+ }
153
74
  /** Composes the prompt for one ticket: who asked, what they asked, and what the agent must not assume. */
154
75
  function composePrompt(input) {
155
- const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch } = input;
76
+ const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch, standing = [], notes = [] } = input;
156
77
  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)}`;
157
78
  return [
158
79
  `# Ticket ${ticket.id}`,
@@ -162,6 +83,12 @@ function composePrompt(input) {
162
83
  "## The request",
163
84
  "",
164
85
  asked,
86
+ ...notes.filter(Boolean).flatMap((note) => [
87
+ "",
88
+ "## Notes since the start",
89
+ "",
90
+ quote(note)
91
+ ]),
165
92
  "",
166
93
  "## How to work",
167
94
  "",
@@ -170,12 +97,12 @@ function composePrompt(input) {
170
97
  "- Run the tests the repository has. Do not claim a check passed unless you ran it.",
171
98
  "- Do not merge the pull request. A person merges it.",
172
99
  "- If the request needs a decision you cannot make, stop and ask one concrete question.",
173
- "",
100
+ ...standing.filter(Boolean).flatMap((rule) => ["", rule]),
174
101
  ...instructions.trim() ? [
102
+ "",
175
103
  "## Team instructions",
176
104
  "",
177
- instructions.trim(),
178
- ""
105
+ instructions.trim()
179
106
  ] : [],
180
107
  reportInstructions()
181
108
  ].join("\n");
@@ -184,10 +111,317 @@ function composePrompt(input) {
184
111
  function quote(text) {
185
112
  return (text.trim() || "(empty message)").split("\n").map((line) => `> ${line}`).join("\n");
186
113
  }
187
- new Intl.Segmenter("zh", { granularity: "word" });
188
- /** Case-insensitive comparison for GitHub logins and repository names. */
189
- const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
190
- const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
114
+ // src/policy.ts
115
+ /**
116
+ * How an installation decides who may start work: an explicit request from a listed person, or an owner's unaddressed
117
+ * message that an assessment matches to an enabled rule.
118
+ *
119
+ * The admission table is kept whole here rather than simplified to "listed and addressed": a message that carries no
120
+ * request is still worth assessing when the owner wrote it in a chat the Source reads, because many real requests are a
121
+ * suggestion, not an order. `policy.mode` decides whether such a candidate is accepted (`auto`), only recorded
122
+ * (`observe`), or dropped before an assessment (`off`).
123
+ */
124
+ /** Which sources this installation's Sources read, and whether they read every message in that scope. */
125
+ function sourceScope(settings) {
126
+ return { scope: (input) => {
127
+ if (input.source === "feishu") {
128
+ if (!settings.feishu?.enabled) return {
129
+ listened: false,
130
+ reason: "sourceOff"
131
+ };
132
+ return {
133
+ listened: true,
134
+ observed: true
135
+ };
136
+ }
137
+ if (input.source !== "github") return {
138
+ listened: false,
139
+ reason: "unsupported"
140
+ };
141
+ if (!settings.github?.enabled) return {
142
+ listened: false,
143
+ reason: "sourceOff"
144
+ };
145
+ const repository = input.meta.repository ?? settings.github.repository;
146
+ if (!repository) return {
147
+ listened: false,
148
+ reason: "unsupported"
149
+ };
150
+ if (repository.toLowerCase() !== settings.github.repository.toLowerCase()) return {
151
+ listened: false,
152
+ reason: "otherRepository"
153
+ };
154
+ return {
155
+ listened: true,
156
+ observed: false
157
+ };
158
+ } };
159
+ }
160
+ /** The rule a person's unaddressed chat message must match before its candidate may be accepted. */
161
+ const UNASKED_RULE = "unasked";
162
+ /** The Policy of one settings file, rebuilt whenever the round reads it. */
163
+ function buildPolicy(settings, scope) {
164
+ const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
165
+ return {
166
+ version: `${settings.policy.mode}:${settings.policy.rules.filter((rule) => rule.enabled).map((rule) => rule.id).join(",")}`,
167
+ paused: false,
168
+ evalTimeoutMs: 12e4,
169
+ gate: (trigger, _thread, _tickets, received) => {
170
+ if (!trigger.human) return {
171
+ admissible: false,
172
+ reason: "bot"
173
+ };
174
+ const allowed = people(trigger.source).has(trigger.actor.id.toLowerCase());
175
+ const seen = received ?? scope.scope(trigger);
176
+ const observed = seen.listened && seen.observed;
177
+ const addressed = !!trigger.addressed;
178
+ const basis = addressed ? {
179
+ via: "listed",
180
+ addressed: trigger.addressed
181
+ } : {
182
+ via: "admission",
183
+ cell: "listedUnaddressed"
184
+ };
185
+ if (allowed && addressed) return {
186
+ admissible: true,
187
+ strength: "explicit",
188
+ basis
189
+ };
190
+ if (allowed && observed && settings.policy.mode !== "off") return {
191
+ admissible: true,
192
+ strength: "inferred",
193
+ basis
194
+ };
195
+ return {
196
+ admissible: false,
197
+ reason: allowed ? "notAddressed" : "notAllowed"
198
+ };
199
+ },
200
+ revalidate: () => true,
201
+ admitsInferred: (rules) => settings.policy.mode === "auto" && rules.length > 0 && rules.every((id) => settings.policy.rules.some((rule) => rule.enabled && rule.id === id))
202
+ };
203
+ }
204
+ /**
205
+ * The decision an assessment reaches, as a Validation: an accepted candidate needs the `unasked` rule, then one verdict
206
+ * for every enabled rule. `observe` records what `auto` would accept as an ignored Decision, so a person can read the
207
+ * judgements before any of them starts work.
208
+ */
209
+ function assessmentOutcome(assessment, settings, strength) {
210
+ const enabled = settings.policy.rules.filter((rule) => rule.enabled);
211
+ const judged = new Map(assessment.rule_assessments.map((item) => [item.rule_id, item]));
212
+ const missing = enabled.filter((rule) => !judged.has(rule.id));
213
+ if (missing.length) throw new Error(`No verdict for the rule(s) ${missing.map((rule) => rule.id).join(", ")}`);
214
+ const matches = enabled.filter((rule) => judged.get(rule.id).matched).map((rule) => rule.id);
215
+ const audit = {
216
+ rule_assessments: assessment.rule_assessments,
217
+ direction: assessment.direction,
218
+ intent_evidence: assessment.intent_evidence
219
+ };
220
+ if (assessment.decision !== "accept") return {
221
+ kind: assessment.decision,
222
+ reason: assessment.reason,
223
+ audit
224
+ };
225
+ if (!matches.length) return {
226
+ kind: "ignore",
227
+ audit,
228
+ reason: "No enabled rule matches this message"
229
+ };
230
+ if (!directionAllowed(assessment.direction)) return {
231
+ kind: "ignore",
232
+ audit,
233
+ reason: assessment.intent_evidence ? "The direction is not settled" : "The assessment gives no evidence of intent"
234
+ };
235
+ if (strength === "inferred" && !matches.includes("unasked")) return {
236
+ kind: "ignore",
237
+ audit,
238
+ reason: "The message does not ask for work; only the unasked rule can accept one"
239
+ };
240
+ const accept = {
241
+ kind: "accept",
242
+ title: assessment.title,
243
+ scope: assessment.scope,
244
+ reason: assessment.reason,
245
+ rules: matches,
246
+ audit,
247
+ ...assessment.acknowledgement ? { acknowledgement: assessment.acknowledgement } : {}
248
+ };
249
+ if (strength === "inferred" && settings.policy.mode !== "auto") return {
250
+ kind: "ignore",
251
+ reason: `Observe mode: would accept "${assessment.title}"`,
252
+ audit: {
253
+ ...audit,
254
+ would_accept: true,
255
+ proposal: accept
256
+ }
257
+ };
258
+ return accept;
259
+ }
260
+ // src/assess.ts
261
+ /**
262
+ * The assessment of a candidate a person did not address to the agent.
263
+ *
264
+ * One model call reads the messages in a Thread and the enabled rules, and answers one verdict per rule plus a direction:
265
+ * whether a change was asked for, at a target or standard that already exists. The model never decides authority; the
266
+ * Policy and the engine's `admitsInferred` do. A failed or malformed answer ends the assessment as `unavailable`, which a
267
+ * person can see and re-run, rather than as a quiet ignore.
268
+ */
269
+ /** The JSON the assessor must print. */
270
+ const AssessmentSchema = z.object({
271
+ decision: z.enum([
272
+ "accept",
273
+ "ignore",
274
+ "unavailable"
275
+ ]),
276
+ rule_assessments: z.array(RuleAssessmentSchema),
277
+ direction: z.unknown(),
278
+ title: z.string().max(80).nullish().transform((value) => value ?? ""),
279
+ scope: z.string().max(500).nullish().transform((value) => value ?? ""),
280
+ reason: z.string().max(500).nullish().transform((value) => value ?? ""),
281
+ intent_evidence: z.string().max(700).nullable().default(null),
282
+ acknowledgement: z.string().max(200).nullable().default(null)
283
+ });
284
+ /** The talk in a Thread, oldest first, each message cut so the prompt stays bounded. */
285
+ function conversation(thread, triggers, limit = 12) {
286
+ return triggers.slice(-limit).map((trigger) => {
287
+ const text = trigger.text.replace(/\s+/g, " ").trim().slice(0, 1500);
288
+ const who = trigger.human ? trigger.actor.id : "a bot";
289
+ const mark = trigger.addressed ? " (addressed the agent)" : "";
290
+ return `- [${trigger.id}] ${who}${mark} at ${trigger.at}: ${text}`;
291
+ }).join("\n");
292
+ }
293
+ /** The prompt one assessment reads: the rules it must judge, then the discussion. */
294
+ function assessmentPrompt(candidate, settings) {
295
+ const enabled = settings.policy.rules.filter((rule) => rule.enabled);
296
+ return [
297
+ `# A message in a chat the agent reads, not addressed to it`,
298
+ "",
299
+ "Decide whether it asks for work. You do not do the work and you do not change anything.",
300
+ "",
301
+ "## Rules",
302
+ "",
303
+ ...[
304
+ `- \`${UNASKED_RULE}\` (The request): the discussion asks for a concrete change to this project, with a target or an`,
305
+ " existing standard to change it towards, and no open design decision. A preference, a hypothetical or a discussion of",
306
+ " another product does not match.",
307
+ ...enabled.map((rule) => `- \`${rule.id}\` (${rule.name}): ${rule.instruction}`)
308
+ ],
309
+ "",
310
+ "## The discussion",
311
+ "",
312
+ conversation(candidate.thread, candidate.triggers),
313
+ "",
314
+ "## Answer",
315
+ "",
316
+ "Print one JSON object and nothing else:",
317
+ "",
318
+ "```json",
319
+ "{\"decision\": \"accept\" | \"ignore\" | \"unavailable\",",
320
+ " \"rule_assessments\": [{\"rule_id\": \"<id>\", \"matched\": true, \"reason\": \"<one sentence, factual>\"}, ...],",
321
+ " \"direction\": {\"implementation_requested\": true, \"target_basis\": \"specified\" | \"existing-standard\" | \"undetermined\",",
322
+ " \"requires_design_decision\": false, \"evidence\": \"<the words that establish it>\"},",
323
+ " \"title\": \"<a short name for the work, when accepting>\",",
324
+ " \"scope\": \"<what changes, in one sentence>\",",
325
+ " \"reason\": \"<one sentence for a person reading the decision>\",",
326
+ " \"intent_evidence\": \"<the quotation that shows the request>\",",
327
+ " \"acknowledgement\": null}",
328
+ "```",
329
+ "",
330
+ "- Include exactly one `rule_assessments` entry for every rule above, matched or not.",
331
+ "- `accept` only when the discussion asks for a change the rules allow; otherwise `ignore`.",
332
+ "- `unavailable` only when the discussion is unreadable."
333
+ ].join("\n");
334
+ }
335
+ /** Reads the JSON object out of what the model printed, tolerating a fenced block or surrounding prose. */
336
+ function parseAssessment(text) {
337
+ const start = text.indexOf("{");
338
+ const end = text.lastIndexOf("}");
339
+ if (start < 0 || end <= start) throw new Error("The assessment printed no JSON object");
340
+ const parsed = AssessmentSchema.parse(JSON.parse(text.slice(start, end + 1)));
341
+ if (parsed.decision === "accept" && !directionAllowed(parsed.direction)) throw new Error("The assessment accepts without a settled direction");
342
+ return parsed;
343
+ }
344
+ /** A model call that judges one candidate, once per Eval: the engine asks once, and a replay of the same trigger comes as a new Eval. */
345
+ function claudeAssessor(settings) {
346
+ return async (candidate) => {
347
+ const { agent, binary, model } = settings.assess;
348
+ if (agent !== "claude") throw new Error(`The assessor runs on claude; settings.assess.agent is ${agent}`);
349
+ const env = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== void 0));
350
+ const result = await runProcess(binary ?? "claude", [
351
+ "-p",
352
+ "--output-format",
353
+ "json",
354
+ ...model ? ["--model", model] : []
355
+ ], {
356
+ cwd: settings.checkout,
357
+ env,
358
+ stdin: assessmentPrompt(candidate, settings),
359
+ signal: AbortSignal.timeout(12e4),
360
+ timeoutMs: 12e4
361
+ });
362
+ if (result.exitCode !== 0) throw new Error(`The assessor exited ${result.exitCode}: ${result.stderr.slice(-500)}`);
363
+ const envelope = JSON.parse(result.stdout);
364
+ if (envelope.is_error) throw new Error(`The assessor failed: ${envelope.result ?? ""}`.slice(0, 500));
365
+ return parseAssessment(envelope.result ?? "");
366
+ };
367
+ }
368
+ // src/assessing.ts
369
+ /** The name an addressed request gives its ticket: its first line without the mentions, short enough for a branch. */
370
+ function named(candidate) {
371
+ return { title: (candidate.triggers[0]?.text ?? "").split("\n")[0].replace(/@[\w-]+/g, "").trim().slice(0, 60) || "Request" };
372
+ }
373
+ /**
374
+ * The Assessor a loop installs: it judges each candidate in one model call, in flight beside the rounds.
375
+ *
376
+ * The call is asynchronous so a slow assessment never holds up a Source. Its outcome is a decision the loop makes: the
377
+ * loop keeps one Engine across rounds, and a command run from this callback would see a Thread the round in flight is in
378
+ * the middle of changing. A verdict for an Eval that ended meanwhile is dropped, and its requeued Triggers get a fresh one.
379
+ */
380
+ function assessing(options) {
381
+ const running = /* @__PURE__ */ new Map();
382
+ return {
383
+ request(candidate) {
384
+ running.set(candidate.evalId, candidate);
385
+ const explicit = candidate.strength === "explicit";
386
+ (async () => {
387
+ let outcome;
388
+ try {
389
+ const settings = options.settings();
390
+ outcome = explicit ? {
391
+ kind: "accept",
392
+ ...named(candidate),
393
+ scope: "",
394
+ 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
+ };
400
+ } catch (error) {
401
+ outcome = {
402
+ kind: "unavailable",
403
+ reason: `The assessment could not run: ${error.message}`
404
+ };
405
+ }
406
+ if (!running.has(candidate.evalId)) return;
407
+ running.delete(candidate.evalId);
408
+ const triggerId = candidate.triggers[0]?.id;
409
+ if (triggerId) options.decided.push({
410
+ triggerId,
411
+ outcome: {
412
+ ...outcome,
413
+ evalId: candidate.evalId
414
+ }
415
+ });
416
+ })().catch((error) => {
417
+ options.log(`The assessment of ${candidate.evalId} failed: ${error.message}`);
418
+ });
419
+ },
420
+ release(evalId) {
421
+ running.delete(evalId);
422
+ }
423
+ };
424
+ }
191
425
  // src/sources/github.ts
192
426
  /**
193
427
  * The GitHub Source: turns new mentions and new Issues in one repository into Triggers.
@@ -639,6 +873,7 @@ function consumeEvents(options) {
639
873
  settled();
640
874
  });
641
875
  child.on("close", (code) => {
876
+ options.onEnded?.();
642
877
  if (!finished) {
643
878
  reader.flush();
644
879
  if (code !== 0) options.onError(`The event consumer exited with code ${code}`);
@@ -743,12 +978,20 @@ async function removeWorktree(checkout, directory, signal) {
743
978
  } catch {}
744
979
  }
745
980
  // src/runner.ts
981
+ /** How long a reply in a conversation may be: a person reads it on a phone, and the evidence belongs in the pull request. */
982
+ const REPLY_MAX = 200;
983
+ /** The first sentence of a report summary, short enough to send; the record keeps every word. */
984
+ function deliverable(summary) {
985
+ const one = summary.replace(/\s+/g, " ").trim();
986
+ const text = ((one.split(/(?<=[.!?])\s|(?<=[\u3002\uff01\uff1f])/)[0] ?? "") || one).replace(/[\s.!?\u3002\uff01\uff1f]+$/, "");
987
+ return text.length > REPLY_MAX ? `${text.slice(0, 199).trimEnd()}…` : text || "The work is done.";
988
+ }
746
989
  function deliver(engine, repo, delivered, log) {
747
990
  for (const ticket of repo.tickets.list()) {
748
991
  const report = latestReport(ticket);
749
992
  if (!ticket.ended || report?.state !== "ready" || delivered.has(`${ticket.id}@${report.at}`)) continue;
750
993
  delivered.add(`${ticket.id}@${report.at}`);
751
- const text = String(report.summary).trim() || "The work is done.";
994
+ const text = deliverable(String(report.summary));
752
995
  try {
753
996
  engine.reply({
754
997
  purpose: "result",
@@ -761,45 +1004,24 @@ function deliver(engine, repo, delivered, log) {
761
1004
  }
762
1005
  }
763
1006
  }
764
- /** Decides the requests the assessor accepted, which starts their tickets. */
765
- function advance(engine, repo, log, candidates) {
766
- for (const candidate of candidates) {
767
- const trigger = repo.triggers.get(candidate.triggers[0].id);
768
- if (!trigger) continue;
769
- const name = trigger.text.split("\n")[0].replace(/@[\w-]+/g, "").trim().slice(0, 60) || "Request";
770
- try {
771
- const decision = engine.decide(trigger.id, {
772
- kind: "accept",
773
- title: name,
774
- scope: name,
775
- reason: "explicit"
776
- });
777
- log(`Accepted ${trigger.id} as ticket ${decision.ticketId ?? "(none)"}`);
778
- } catch (error) {
779
- log(`Could not accept ${trigger.id}: ${error.message}`);
780
- }
781
- }
782
- }
783
- /** Holds the turns' outcomes until a round records them, and wakes that round when one arrives. */
784
- var TurnQueue = class {
1007
+ /** Holds outcomes that arrive while no round is listening, and wakes a round to record them. */
1008
+ var WorkQueue = class {
785
1009
  items = [];
786
- handoff;
787
1010
  waiter;
788
- /** A turn that finished; it is kept even with no round waiting, so a turn that outlives its round is still recorded. */
1011
+ /** An outcome that arrived; it is kept even with no round waiting, so one that outlives its round is still recorded. */
789
1012
  push(item) {
790
1013
  this.items.push(item);
791
- this.handoff?.(item);
792
1014
  this.wake();
793
1015
  }
794
- /** The turns finished since the last drain. */
1016
+ /** What arrived since the last drain. */
795
1017
  drain() {
796
1018
  return this.items.splice(0);
797
1019
  }
798
- /** Whether a turn is waiting to be recorded. */
1020
+ /** Whether an outcome waits to be recorded. */
799
1021
  ready() {
800
1022
  return this.items.length > 0;
801
1023
  }
802
- /** Settles when a turn has finished, or when `ms` passes. */
1024
+ /** Settles when an outcome arrives, or when `ms` passes. */
803
1025
  wait(ms) {
804
1026
  if (this.items.length) return Promise.resolve();
805
1027
  return new Promise((resolve) => {
@@ -816,8 +1038,17 @@ var TurnQueue = class {
816
1038
  this.waiter?.();
817
1039
  }
818
1040
  };
819
- /** How long one round waits for a turn before the next round; a turn is recorded when it ends, not several rounds later. */
1041
+ /** How long one round waits for an outcome before the next round; one that arrives is recorded at once, not several rounds later. */
820
1042
  const TURN_WAIT_MS = 1e3;
1043
+ /** Records the assessments that finished as Decisions; one the Engine refuses is logged, not thrown. */
1044
+ function decide(engine, decided, log) {
1045
+ for (const { triggerId, outcome } of decided) try {
1046
+ const made = engine.decide(triggerId, outcome);
1047
+ log(`Decided ${triggerId}: ${made.kind}${made.ticketId ? `, ticket ${made.ticketId}` : ""}${made.reason?.length ? ` — ${JSON.stringify(made.reason)}` : ""}`);
1048
+ } catch (error) {
1049
+ log(`Could not decide ${triggerId}: ${error.message}`);
1050
+ }
1051
+ }
821
1052
  /** Records the turns that finished, so a ticket ends without the loop holding work in memory; a refused report is logged, not thrown. */
822
1053
  function record(engine, repo, finished, log) {
823
1054
  for (const item of finished) try {
@@ -871,81 +1102,6 @@ async function send(channel, clis, log) {
871
1102
  /** Where the loop keeps its own bookkeeping, beside the domain state. */
872
1103
  const pollKey = "github:poll";
873
1104
  const seenKey = (id) => `github:seen:${id}`;
874
- /** A Source Scope that listens to the configured repository's threads. */
875
- function sourceScope(settings) {
876
- return { scope: (input) => {
877
- if (input.source === "feishu") return settings.feishu?.enabled ? {
878
- listened: true,
879
- observed: false
880
- } : {
881
- listened: false,
882
- reason: "sourceOff"
883
- };
884
- if (input.source !== "github") return {
885
- listened: false,
886
- reason: "unsupported"
887
- };
888
- if (!settings.github?.enabled) return {
889
- listened: false,
890
- reason: "sourceOff"
891
- };
892
- const repository = input.meta.repository ?? settings.github.repository;
893
- if (!repository) return {
894
- listened: false,
895
- reason: "unsupported"
896
- };
897
- if (!sameName(repository, settings.github.repository)) return {
898
- listened: false,
899
- reason: "otherRepository"
900
- };
901
- return {
902
- listened: true,
903
- observed: false
904
- };
905
- } };
906
- }
907
- /** A Policy that admits a person on the allow list who addressed the agent, and nothing else. */
908
- function buildPolicy(settings) {
909
- const allowed = new Set((settings.github?.allowed ?? []).map((name) => name.toLowerCase()));
910
- const people = new Set((settings.feishu?.allowed ?? []).map((id) => id.toLowerCase()));
911
- return {
912
- version: `${allowed.size}.${people.size}`,
913
- paused: false,
914
- gate: (trigger) => {
915
- if (!trigger.human) return {
916
- admissible: false,
917
- reason: "bot"
918
- };
919
- if (!(trigger.source === "feishu" ? people : allowed).has(trigger.actor.id.toLowerCase())) return {
920
- admissible: false,
921
- reason: "notAllowed"
922
- };
923
- if (!trigger.addressed) return {
924
- admissible: false,
925
- reason: "notAddressed"
926
- };
927
- return {
928
- admissible: true,
929
- strength: "explicit",
930
- basis: {
931
- via: "listed",
932
- addressed: "mention"
933
- }
934
- };
935
- },
936
- revalidate: (mandate) => mandate.basis.via !== "bot" && (mandate.actor.source === "feishu" ? people : allowed).has(mandate.actor.id.toLowerCase()),
937
- admitsInferred: () => false,
938
- evalTimeoutMs: 12e4
939
- };
940
- }
941
- /** Marks a request accepted without a model call: an explicit mention by an allowed person is its own authorization. */
942
- const explicitAssessor = {
943
- request: (candidate) => {
944
- accepted.push(candidate);
945
- },
946
- release: () => {}
947
- };
948
- const accepted = [];
949
1105
  /** Lines one round reads from the stream at most, so a chat that keeps talking does not hold a round open. */
950
1106
  const MAX_LINES = 500;
951
1107
  /** A failed save of the last round must not stop the next one. */
@@ -972,17 +1128,38 @@ function outbox() {
972
1128
  var AgentExecutor = class {
973
1129
  options;
974
1130
  active = /* @__PURE__ */ new Map();
1131
+ /** Tickets whose turn waits for a free slot, oldest first. */
1132
+ pending = [];
1133
+ pumping = false;
975
1134
  constructor(options) {
976
1135
  this.options = options;
977
1136
  }
978
1137
  start(ticket, assignment) {
979
- const controller = new AbortController();
980
1138
  const { site } = this.options;
981
1139
  site.started(ticket.id, assignment.id);
982
- this.active.set(ticket.id, controller);
983
- this.execute(ticket, assignment, controller);
1140
+ this.pending.push({
1141
+ ticket,
1142
+ assignment
1143
+ });
1144
+ this.pump();
984
1145
  }
985
1146
  deliver() {}
1147
+ /**
1148
+ * Takes in the tickets a previous process left running. Their agents ended with that process, so a turn that had not
1149
+ * reported is restarted with a recovery note, and one whose report a person still has to act on goes back to the queue
1150
+ * with its inputs. A start from `interrupted` joins the same queue as a new ticket.
1151
+ */
1152
+ recover(open) {
1153
+ for (const ticket of open) {
1154
+ const assignment = runningAssignment(ticket);
1155
+ if (assignment) this.options.site.interrupted(ticket.id, assignment.id);
1156
+ }
1157
+ for (const ticket of open) for (const assignment of ticket.assignments) if (assignment.state === "pending") this.pending.push({
1158
+ ticket,
1159
+ assignment
1160
+ });
1161
+ this.pump();
1162
+ }
986
1163
  /** The Engine's memory of the ticket, so the report lands on a ticket that already holds this round's changes to it. */
987
1164
  refresh(ticket) {
988
1165
  this.options.engine.updateTicket(ticket);
@@ -990,6 +1167,23 @@ var AgentExecutor = class {
990
1167
  stop(ticket) {
991
1168
  this.active.get(ticket.id)?.abort();
992
1169
  this.active.delete(ticket.id);
1170
+ const waiting = this.pending.findIndex((item) => item.ticket.id === ticket.id);
1171
+ if (waiting >= 0) this.pending.splice(waiting, 1);
1172
+ this.pump();
1173
+ }
1174
+ /** Starts waiting tickets while a slot is free; the turns run beside the rounds, so this never blocks on one. */
1175
+ pump() {
1176
+ if (this.pumping) return;
1177
+ this.pumping = true;
1178
+ Promise.resolve().then(() => {
1179
+ this.pumping = false;
1180
+ while (this.active.size < this.options.maxWorkers && this.pending.length) {
1181
+ const item = this.pending.shift();
1182
+ const controller = new AbortController();
1183
+ this.active.set(item.ticket.id, controller);
1184
+ this.execute(item.ticket, item.assignment, controller);
1185
+ }
1186
+ });
993
1187
  }
994
1188
  async execute(ticket, assignment, controller) {
995
1189
  const { settings, runner, stateDir, accounts, feishuCli, site } = this.options;
@@ -1029,6 +1223,7 @@ var AgentExecutor = class {
1029
1223
  site.failed(ticket.id, assignment.id, `The agent could not run: ${error.message}`);
1030
1224
  } finally {
1031
1225
  this.active.delete(ticket.id);
1226
+ this.pump();
1032
1227
  }
1033
1228
  }
1034
1229
  variables(ticket, directory, branch) {
@@ -1058,6 +1253,12 @@ async function appendLog(directory, prompt, raw, report) {
1058
1253
  "",
1059
1254
  `## ${(/* @__PURE__ */ new Date()).toISOString()}`,
1060
1255
  "",
1256
+ "**Prompt**",
1257
+ "",
1258
+ "```",
1259
+ prompt,
1260
+ "```",
1261
+ "",
1061
1262
  "**Report**",
1062
1263
  "",
1063
1264
  "```json",
@@ -1070,8 +1271,7 @@ async function appendLog(directory, prompt, raw, report) {
1070
1271
  raw,
1071
1272
  "```"
1072
1273
  ].join("\n");
1073
- const previous = await readFile(path, "utf8").catch(() => "");
1074
- await mkdir(join(directory, ".superagent"), { recursive: true }).then(() => writeFile(path, `${previous}${entry}\n`));
1274
+ await mkdir(join(directory, ".superagent"), { recursive: true }).then(() => appendFile(path, `${entry}\n`));
1075
1275
  }
1076
1276
  /**
1077
1277
  * The loop that makes an installation run without a person: poll the Sources, assess what they bring, and run the tickets
@@ -1096,42 +1296,64 @@ async function runLoop(options) {
1096
1296
  agentLogin: login
1097
1297
  };
1098
1298
  await writeEnvironment(accounts, settings.executor.blockedCommands);
1299
+ const standing = await standingRules();
1099
1300
  const channel = outbox();
1100
- const finished = new TurnQueue();
1301
+ const scope = sourceScope(settings);
1302
+ const decided = new WorkQueue();
1303
+ const finished = new WorkQueue();
1101
1304
  const engine = new Engine({
1102
1305
  repo,
1103
- policy: () => buildPolicy(settings),
1104
- scope: sourceScope(settings),
1105
- assessor: explicitAssessor,
1306
+ policy: () => buildPolicy(settings, scope),
1307
+ scope,
1308
+ assessor: assessing({
1309
+ settings: () => settings,
1310
+ next: claudeAssessor(settings),
1311
+ decided,
1312
+ log
1313
+ }),
1106
1314
  executor: void 0,
1107
1315
  outbox: channel
1108
1316
  });
1317
+ const site = {
1318
+ started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
1319
+ reported: (ticketId, report) => {
1320
+ record(engine, repo, [{
1321
+ ticketId,
1322
+ report
1323
+ }], log);
1324
+ },
1325
+ failed: (ticketId, _assignmentId, summary) => {
1326
+ record(engine, repo, [{
1327
+ ticketId,
1328
+ report: {
1329
+ state: "failed",
1330
+ summary
1331
+ }
1332
+ }], log);
1333
+ },
1334
+ interrupted: (ticketId, assignmentId) => {
1335
+ try {
1336
+ engine.assignmentInterrupted(ticketId, assignmentId);
1337
+ } catch (error) {
1338
+ log(`Could not recover ${ticketId}: ${error.message}`);
1339
+ }
1340
+ }
1341
+ };
1109
1342
  const executor = new AgentExecutor({
1110
1343
  engine,
1111
1344
  settings,
1345
+ maxWorkers: settings.executor.maxWorkers,
1112
1346
  runner: runnerFor(settings.executor.agent, settings.executor.binary),
1113
1347
  stateDir: settings.stateDir,
1114
1348
  repository: github?.repository ?? settings.checkout,
1115
1349
  agent: login,
1116
1350
  accounts,
1117
1351
  ...feishu ? { feishuCli: feishu.cli } : {},
1118
- site: {
1119
- started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
1120
- reported: (ticketId, report) => finished.push({
1121
- ticketId,
1122
- report
1123
- }),
1124
- failed: (ticketId, _assignmentId, summary) => finished.push({
1125
- ticketId,
1126
- report: {
1127
- state: "failed",
1128
- summary
1129
- }
1130
- })
1131
- },
1352
+ site,
1132
1353
  prompt: async (ticket, directory, branch) => {
1133
1354
  const trigger = repo.triggers.get(ticket.origin.triggerId);
1134
1355
  const source = trigger?.source === "feishu" ? "feishu" : "github";
1356
+ const notes = ticket.inputs.flatMap((input) => input.kind === "text" ? [input.text] : []);
1135
1357
  return composePrompt({
1136
1358
  ticket,
1137
1359
  trigger,
@@ -1140,7 +1362,9 @@ async function runLoop(options) {
1140
1362
  branchPrefix: settings.branchPrefix,
1141
1363
  source,
1142
1364
  instructions: settings.prompts,
1143
- branch
1365
+ branch,
1366
+ standing,
1367
+ notes
1144
1368
  });
1145
1369
  }
1146
1370
  });
@@ -1176,7 +1400,6 @@ async function runLoop(options) {
1176
1400
  };
1177
1401
  const store = (trigger) => {
1178
1402
  try {
1179
- options.repo;
1180
1403
  if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
1181
1404
  } catch (error) {
1182
1405
  log(`Could not store ${trigger.id}: ${error.message}`);
@@ -1197,13 +1420,7 @@ async function runLoop(options) {
1197
1420
  };
1198
1421
  let handle;
1199
1422
  const stopListening = new AbortController();
1200
- const unlisten = () => {
1201
- stopListening.abort();
1202
- };
1203
- const endStream = async () => {
1204
- unlisten();
1205
- if (handle) await handle.ended;
1206
- };
1423
+ if (options.once) caller.addEventListener("abort", () => stopListening.abort(), { once: true });
1207
1424
  if (feishu) handle = consumeEvents({
1208
1425
  cli: feishu.cli,
1209
1426
  signal: stopListening.signal,
@@ -1211,6 +1428,7 @@ async function runLoop(options) {
1211
1428
  onListening: (started) => {
1212
1429
  handle = started;
1213
1430
  },
1431
+ ...options.once ? {} : { onEnded: () => stopListening.abort() },
1214
1432
  onError: (message) => {
1215
1433
  if (!signal.aborted) log(message);
1216
1434
  }
@@ -1219,13 +1437,12 @@ async function runLoop(options) {
1219
1437
  const nextLine = () => handle ? handle.next(settings.executor.streamIdleMs) : Promise.resolve(false);
1220
1438
  const delivered = /* @__PURE__ */ new Set();
1221
1439
  engine.options.executor = executor;
1222
- finished.handoff = (item) => {
1223
- try {
1224
- record(engine, repo, [item], log);
1225
- } catch (error) {
1226
- log(`Could not record the report for ${item.ticketId}: ${error.message}`);
1227
- }
1228
- };
1440
+ try {
1441
+ for (const ticket of repo.tickets.active()) engine.updateTicket(ticket);
1442
+ executor.recover(repo.tickets.active());
1443
+ } catch (error) {
1444
+ log(`Could not recover the tickets left running: ${error.message}`);
1445
+ }
1229
1446
  const inRound = /* @__PURE__ */ new Set();
1230
1447
  const ingest = () => {
1231
1448
  const waiting = repo.triggers.list().filter((trigger) => trigger.source === "feishu");
@@ -1264,7 +1481,7 @@ async function runLoop(options) {
1264
1481
  repo.setMeta(pollKey, since);
1265
1482
  }
1266
1483
  engine.evaluateDue();
1267
- advance(engine, repo, log, accepted.splice(0));
1484
+ decide(engine, decided.drain(), log);
1268
1485
  record(engine, repo, finished.drain(), log);
1269
1486
  await repo.flush();
1270
1487
  await pull();
@@ -1281,16 +1498,18 @@ async function runLoop(options) {
1281
1498
  if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
1282
1499
  }
1283
1500
  if (options.once) break;
1284
- let left = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity) * 1e3;
1501
+ const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity);
1502
+ let left = options.once ? 0 : seconds * 1e3;
1285
1503
  while (left > 0 && !signal.aborted) {
1286
1504
  const began = Date.now();
1287
- await Promise.race([finished.wait(Math.max(1, Math.min(TURN_WAIT_MS, left))), new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
1288
- if (finished.ready()) break;
1505
+ const wait = Math.max(1, Math.min(TURN_WAIT_MS, left));
1506
+ await Promise.race([Promise.race([finished.wait(wait), decided.wait(wait)]), new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
1507
+ if (finished.ready() || decided.ready()) break;
1289
1508
  left -= Date.now() - began;
1290
1509
  }
1291
1510
  }
1292
1511
  stop.abort();
1293
- if (feishu) await endStream();
1512
+ if (options.once && !process.env.VITEST) setImmediate(() => process.exit(process.exitCode ?? 0));
1294
1513
  }
1295
1514
  // src/cli.ts
1296
1515
  /**
@@ -1349,7 +1568,8 @@ async function init(dir) {
1349
1568
  return 0;
1350
1569
  }
1351
1570
  async function status(dir) {
1352
- const { tickets, threads, exists: found } = await readState(await stateDirOf(dir));
1571
+ const { tickets, threads, decisions, triggers: all, exists: found } = await readState(await stateDirOf(dir));
1572
+ const triggers = new Map(all.map((trigger) => [trigger.id, trigger]));
1353
1573
  if (!found) {
1354
1574
  process.stdout.write(`No state directory yet. Run \`superagent init\` first.\n`);
1355
1575
  return 1;
@@ -1378,6 +1598,16 @@ async function status(dir) {
1378
1598
  lines.push("");
1379
1599
  }
1380
1600
  if (!tickets.length) lines.push("No tickets yet.", "");
1601
+ const judged = decisions.filter((decision) => decision.strength === "inferred").sort((a, b) => a.at.localeCompare(b.at)).slice(-10);
1602
+ if (judged.length) {
1603
+ lines.push("## Unaddressed messages", "");
1604
+ for (const decision of judged) {
1605
+ const message = decision.triggerIds.map((id) => triggers.get(id)?.text ?? "").join(" ");
1606
+ const what = decision.ticketId ? `ticket \`${decision.ticketId}\`` : decision.kind;
1607
+ lines.push(`- ${decision.at} **${what}** — ${reasonText(decision.reason)}${message ? ` — “${message.replace(/\s+/g, " ").slice(0, 80)}”` : ""}`);
1608
+ }
1609
+ lines.push("");
1610
+ }
1381
1611
  process.stdout.write(lines.join("\n"));
1382
1612
  return 0;
1383
1613
  }
@@ -1431,7 +1661,7 @@ async function poll(dir, once) {
1431
1661
  process.stderr.write(`${error.message}\n`);
1432
1662
  return 1;
1433
1663
  }
1434
- const repo = new FileRepositories(settings.stateDir = settings.stateDir);
1664
+ const repo = new FileRepositories(settings.stateDir);
1435
1665
  await repo.open();
1436
1666
  const controller = new AbortController();
1437
1667
  process.on("SIGINT", () => controller.abort());