superagent-skill 0.1.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/README.md +43 -7
- package/SKILL.md +69 -2
- package/lib/cli.mjs +1659 -285
- package/lib/index.mjs +2 -2
- package/lib/{settings-BewLFAqT.mjs → settings-D8KZBXO7.mjs} +355 -15
- package/package.json +7 -4
- package/prompts/delivery.md +4 -0
- package/prompts/pr-review.md +5 -0
- package/prompts/scope.md +5 -0
package/lib/cli.mjs
CHANGED
|
@@ -1,106 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
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, 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";
|
|
5
3
|
import { z } from "zod";
|
|
4
|
+
import { access, appendFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { execFile, spawn } from "node:child_process";
|
|
6
7
|
import { homedir } from "node:os";
|
|
7
|
-
|
|
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
|
-
}
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
104
9
|
// src/infra/commands.ts
|
|
105
10
|
/** Runs the Source CLIs (`gh`, `lark-cli`) and reads their JSON. Every call is bounded and never prompts. */
|
|
106
11
|
var CliError = class extends Error {
|
|
@@ -146,13 +51,76 @@ async function runJson(program, argv, options = {}) {
|
|
|
146
51
|
const error = parsed.error;
|
|
147
52
|
throw new CliError(program, `${program} ${argv.join(" ")}: ${error?.message ?? "failed"}`, text, "");
|
|
148
53
|
}
|
|
149
|
-
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;
|
|
150
55
|
return parsed;
|
|
151
56
|
}
|
|
152
57
|
// src/prompts.ts
|
|
58
|
+
/**
|
|
59
|
+
* The prompt a ticket's agent receives.
|
|
60
|
+
*
|
|
61
|
+
* It is assembled here rather than read from files so that an installation has one thing to read: `settings.yaml`. The
|
|
62
|
+
* team-editable part is `prompts.instructions`, which the operator writes in their own words.
|
|
63
|
+
*/
|
|
64
|
+
/**
|
|
65
|
+
* The rules that hold for every ticket, one file each beside this one.
|
|
66
|
+
*
|
|
67
|
+
* They were files in the DSH bundle, where an operator edited them in the panel; here the text is part of the install,
|
|
68
|
+
* so it is read from the file next to the source rather than copied into this module.
|
|
69
|
+
*/
|
|
70
|
+
const STANDING_FILES = ["scope.md", "delivery.md"];
|
|
71
|
+
const STANDING_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "prompts");
|
|
72
|
+
async function standingRules() {
|
|
73
|
+
return Promise.all(STANDING_FILES.map(async (name) => (await readFile(join(STANDING_DIR, name), "utf8")).trim()));
|
|
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
|
+
}
|
|
153
120
|
/** Composes the prompt for one ticket: who asked, what they asked, and what the agent must not assume. */
|
|
154
121
|
function composePrompt(input) {
|
|
155
|
-
|
|
122
|
+
if (input.isPrReview && input.prNumber) return composePrReviewPrompt(input);
|
|
123
|
+
const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch, standing = [], notes = [] } = input;
|
|
156
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)}`;
|
|
157
125
|
return [
|
|
158
126
|
`# Ticket ${ticket.id}`,
|
|
@@ -162,6 +130,12 @@ function composePrompt(input) {
|
|
|
162
130
|
"## The request",
|
|
163
131
|
"",
|
|
164
132
|
asked,
|
|
133
|
+
...notes.filter(Boolean).flatMap((note) => [
|
|
134
|
+
"",
|
|
135
|
+
"## Notes since the start",
|
|
136
|
+
"",
|
|
137
|
+
quote(note)
|
|
138
|
+
]),
|
|
165
139
|
"",
|
|
166
140
|
"## How to work",
|
|
167
141
|
"",
|
|
@@ -170,12 +144,13 @@ function composePrompt(input) {
|
|
|
170
144
|
"- Run the tests the repository has. Do not claim a check passed unless you ran it.",
|
|
171
145
|
"- Do not merge the pull request. A person merges it.",
|
|
172
146
|
"- If the request needs a decision you cannot make, stop and ask one concrete question.",
|
|
173
|
-
"",
|
|
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."] : [],
|
|
148
|
+
...standing.filter(Boolean).flatMap((rule) => ["", rule]),
|
|
174
149
|
...instructions.trim() ? [
|
|
150
|
+
"",
|
|
175
151
|
"## Team instructions",
|
|
176
152
|
"",
|
|
177
|
-
instructions.trim()
|
|
178
|
-
""
|
|
153
|
+
instructions.trim()
|
|
179
154
|
] : [],
|
|
180
155
|
reportInstructions()
|
|
181
156
|
].join("\n");
|
|
@@ -184,10 +159,624 @@ function composePrompt(input) {
|
|
|
184
159
|
function quote(text) {
|
|
185
160
|
return (text.trim() || "(empty message)").split("\n").map((line) => `> ${line}`).join("\n");
|
|
186
161
|
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
|
|
190
|
-
|
|
162
|
+
// src/policy.ts
|
|
163
|
+
/**
|
|
164
|
+
* How an installation decides who may start work: an explicit request from a listed person, or an owner's unaddressed
|
|
165
|
+
* message that an assessment matches to an enabled rule.
|
|
166
|
+
*
|
|
167
|
+
* The admission table is kept whole here rather than simplified to "listed and addressed": a message that carries no
|
|
168
|
+
* request is still worth assessing when the owner wrote it in a chat the Source reads, because many real requests are a
|
|
169
|
+
* suggestion, not an order. `policy.mode` decides whether such a candidate is accepted (`auto`), only recorded
|
|
170
|
+
* (`observe`), or dropped before an assessment (`off`).
|
|
171
|
+
*/
|
|
172
|
+
/** Which sources this installation's Sources read, and whether they read every message in that scope. */
|
|
173
|
+
function sourceScope(settings) {
|
|
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
|
+
}
|
|
189
|
+
if (input.source === "feishu") {
|
|
190
|
+
if (!settings.feishu?.enabled) return {
|
|
191
|
+
listened: false,
|
|
192
|
+
reason: "sourceOff"
|
|
193
|
+
};
|
|
194
|
+
return {
|
|
195
|
+
listened: true,
|
|
196
|
+
observed: true
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
if (input.source !== "github") return {
|
|
200
|
+
listened: false,
|
|
201
|
+
reason: "unsupported"
|
|
202
|
+
};
|
|
203
|
+
if (!settings.github?.enabled) return {
|
|
204
|
+
listened: false,
|
|
205
|
+
reason: "sourceOff"
|
|
206
|
+
};
|
|
207
|
+
const repository = input.meta.repository ?? settings.github.repository;
|
|
208
|
+
if (!repository) return {
|
|
209
|
+
listened: false,
|
|
210
|
+
reason: "unsupported"
|
|
211
|
+
};
|
|
212
|
+
if (repository.toLowerCase() !== settings.github.repository.toLowerCase()) return {
|
|
213
|
+
listened: false,
|
|
214
|
+
reason: "otherRepository"
|
|
215
|
+
};
|
|
216
|
+
return {
|
|
217
|
+
listened: true,
|
|
218
|
+
observed: Boolean(input.meta.isPr) && Boolean(settings.github.prReview?.enabled)
|
|
219
|
+
};
|
|
220
|
+
} };
|
|
221
|
+
}
|
|
222
|
+
/** The rule a person's unaddressed chat message must match before its candidate may be accepted. */
|
|
223
|
+
const UNASKED_RULE = "unasked";
|
|
224
|
+
/** The Policy of one settings file, rebuilt whenever the round reads it. */
|
|
225
|
+
function buildPolicy(settings, scope) {
|
|
226
|
+
const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : source === "twitter" ? settings.twitter?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
|
|
227
|
+
return {
|
|
228
|
+
version: `${settings.policy.mode}:${settings.policy.rules.filter((rule) => rule.enabled).map((rule) => rule.id).join(",")}`,
|
|
229
|
+
paused: false,
|
|
230
|
+
evalTimeoutMs: 12e4,
|
|
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
|
+
}
|
|
255
|
+
if (!trigger.human) return {
|
|
256
|
+
admissible: false,
|
|
257
|
+
reason: "bot"
|
|
258
|
+
};
|
|
259
|
+
const allowed = trigger.source === "twitter" && settings.twitter?.allowed.length === 0 ? true : people(trigger.source).has(trigger.actor.id.toLowerCase());
|
|
260
|
+
const seen = received ?? scope.scope(trigger);
|
|
261
|
+
const observed = seen.listened && seen.observed;
|
|
262
|
+
const addressed = !!trigger.addressed;
|
|
263
|
+
const basis = addressed ? {
|
|
264
|
+
via: "listed",
|
|
265
|
+
addressed: trigger.addressed
|
|
266
|
+
} : {
|
|
267
|
+
via: "admission",
|
|
268
|
+
cell: "listedUnaddressed"
|
|
269
|
+
};
|
|
270
|
+
if (allowed && addressed) return {
|
|
271
|
+
admissible: true,
|
|
272
|
+
strength: "explicit",
|
|
273
|
+
basis
|
|
274
|
+
};
|
|
275
|
+
if (allowed && observed && settings.policy.mode !== "off") return {
|
|
276
|
+
admissible: true,
|
|
277
|
+
strength: "inferred",
|
|
278
|
+
basis
|
|
279
|
+
};
|
|
280
|
+
return {
|
|
281
|
+
admissible: false,
|
|
282
|
+
reason: allowed ? "notAddressed" : "notAllowed"
|
|
283
|
+
};
|
|
284
|
+
},
|
|
285
|
+
revalidate: () => true,
|
|
286
|
+
admitsInferred: (rules) => settings.policy.mode === "auto" && rules.length > 0 && rules.every((id) => settings.policy.rules.some((rule) => rule.enabled && rule.id === id))
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* The decision an assessment reaches, as a Validation: an accepted candidate needs the `unasked` rule, then one verdict
|
|
291
|
+
* for every enabled rule. `observe` records what `auto` would accept as an ignored Decision, so a person can read the
|
|
292
|
+
* judgements before any of them starts work.
|
|
293
|
+
*/
|
|
294
|
+
function assessmentOutcome(assessment, settings, strength) {
|
|
295
|
+
const enabled = settings.policy.rules.filter((rule) => rule.enabled);
|
|
296
|
+
const judged = new Map(assessment.rule_assessments.map((item) => [item.rule_id, item]));
|
|
297
|
+
const missing = enabled.filter((rule) => !judged.has(rule.id));
|
|
298
|
+
if (missing.length) throw new Error(`No verdict for the rule(s) ${missing.map((rule) => rule.id).join(", ")}`);
|
|
299
|
+
const matches = enabled.filter((rule) => judged.get(rule.id).matched).map((rule) => rule.id);
|
|
300
|
+
const audit = {
|
|
301
|
+
rule_assessments: assessment.rule_assessments,
|
|
302
|
+
direction: assessment.direction,
|
|
303
|
+
intent_evidence: assessment.intent_evidence
|
|
304
|
+
};
|
|
305
|
+
if (assessment.decision !== "accept") return {
|
|
306
|
+
kind: assessment.decision,
|
|
307
|
+
reason: assessment.reason,
|
|
308
|
+
audit
|
|
309
|
+
};
|
|
310
|
+
if (!matches.length) return {
|
|
311
|
+
kind: "ignore",
|
|
312
|
+
audit,
|
|
313
|
+
reason: "No enabled rule matches this message"
|
|
314
|
+
};
|
|
315
|
+
if (!directionAllowed(assessment.direction)) return {
|
|
316
|
+
kind: "ignore",
|
|
317
|
+
audit,
|
|
318
|
+
reason: assessment.intent_evidence ? "The direction is not settled" : "The assessment gives no evidence of intent"
|
|
319
|
+
};
|
|
320
|
+
if (strength === "inferred" && !matches.includes("unasked")) return {
|
|
321
|
+
kind: "ignore",
|
|
322
|
+
audit,
|
|
323
|
+
reason: "The message does not ask for work; only the unasked rule can accept one"
|
|
324
|
+
};
|
|
325
|
+
const accept = {
|
|
326
|
+
kind: "accept",
|
|
327
|
+
title: assessment.title,
|
|
328
|
+
scope: assessment.scope,
|
|
329
|
+
reason: assessment.reason,
|
|
330
|
+
rules: matches,
|
|
331
|
+
audit,
|
|
332
|
+
...assessment.acknowledgement ? { acknowledgement: assessment.acknowledgement } : {}
|
|
333
|
+
};
|
|
334
|
+
if (strength === "inferred" && settings.policy.mode !== "auto") return {
|
|
335
|
+
kind: "ignore",
|
|
336
|
+
reason: `Observe mode: would accept "${assessment.title}"`,
|
|
337
|
+
audit: {
|
|
338
|
+
...audit,
|
|
339
|
+
would_accept: true,
|
|
340
|
+
proposal: accept
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
return accept;
|
|
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
|
+
};
|
|
595
|
+
// src/assess.ts
|
|
596
|
+
/**
|
|
597
|
+
* The assessment of a candidate a person did not address to the agent.
|
|
598
|
+
*
|
|
599
|
+
* One model call reads the messages in a Thread and the enabled rules, and answers one verdict per rule plus a direction:
|
|
600
|
+
* whether a change was asked for, at a target or standard that already exists. The model never decides authority; the
|
|
601
|
+
* Policy and the engine's `admitsInferred` do. A failed or malformed answer ends the assessment as `unavailable`, which a
|
|
602
|
+
* person can see and re-run, rather than as a quiet ignore.
|
|
603
|
+
*/
|
|
604
|
+
/** The JSON the assessor must print. */
|
|
605
|
+
const AssessmentSchema = z.object({
|
|
606
|
+
decision: z.enum([
|
|
607
|
+
"accept",
|
|
608
|
+
"ignore",
|
|
609
|
+
"unavailable"
|
|
610
|
+
]),
|
|
611
|
+
rule_assessments: z.array(RuleAssessmentSchema),
|
|
612
|
+
direction: z.unknown(),
|
|
613
|
+
title: z.string().max(80).nullish().transform((value) => value ?? ""),
|
|
614
|
+
scope: z.string().max(500).nullish().transform((value) => value ?? ""),
|
|
615
|
+
reason: z.string().max(500).nullish().transform((value) => value ?? ""),
|
|
616
|
+
intent_evidence: z.string().max(700).nullable().default(null),
|
|
617
|
+
acknowledgement: z.string().max(200).nullable().default(null)
|
|
618
|
+
});
|
|
619
|
+
/** The talk in a Thread, oldest first, each message cut so the prompt stays bounded. */
|
|
620
|
+
function conversation(thread, triggers, limit = 12) {
|
|
621
|
+
return triggers.slice(-limit).map((trigger) => {
|
|
622
|
+
const text = trigger.text.replace(/\s+/g, " ").trim().slice(0, 1500);
|
|
623
|
+
const who = trigger.human ? trigger.actor.id : "a bot";
|
|
624
|
+
const mark = trigger.addressed ? " (addressed the agent)" : "";
|
|
625
|
+
return `- [${trigger.id}] ${who}${mark} at ${trigger.at}: ${text}`;
|
|
626
|
+
}).join("\n");
|
|
627
|
+
}
|
|
628
|
+
/** The prompt one assessment reads: the rules it must judge, then the discussion. */
|
|
629
|
+
function assessmentPrompt(candidate, settings) {
|
|
630
|
+
const enabled = settings.policy.rules.filter((rule) => rule.enabled);
|
|
631
|
+
return [
|
|
632
|
+
`# A message in a chat the agent reads, not addressed to it`,
|
|
633
|
+
"",
|
|
634
|
+
"Decide whether it asks for work. You do not do the work and you do not change anything.",
|
|
635
|
+
"",
|
|
636
|
+
"## Rules",
|
|
637
|
+
"",
|
|
638
|
+
...[
|
|
639
|
+
`- \`${UNASKED_RULE}\` (The request): the discussion asks for a concrete change to this project, with a target or an`,
|
|
640
|
+
" existing standard to change it towards, and no open design decision. A preference, a hypothetical or a discussion of",
|
|
641
|
+
" another product does not match.",
|
|
642
|
+
...enabled.map((rule) => `- \`${rule.id}\` (${rule.name}): ${rule.instruction}`)
|
|
643
|
+
],
|
|
644
|
+
"",
|
|
645
|
+
"## The discussion",
|
|
646
|
+
"",
|
|
647
|
+
conversation(candidate.thread, candidate.triggers),
|
|
648
|
+
"",
|
|
649
|
+
"## Answer",
|
|
650
|
+
"",
|
|
651
|
+
"Print one JSON object and nothing else:",
|
|
652
|
+
"",
|
|
653
|
+
"```json",
|
|
654
|
+
"{\"decision\": \"accept\" | \"ignore\" | \"unavailable\",",
|
|
655
|
+
" \"rule_assessments\": [{\"rule_id\": \"<id>\", \"matched\": true, \"reason\": \"<one sentence, factual>\"}, ...],",
|
|
656
|
+
" \"direction\": {\"implementation_requested\": true, \"target_basis\": \"specified\" | \"existing-standard\" | \"undetermined\",",
|
|
657
|
+
" \"requires_design_decision\": false, \"evidence\": \"<the words that establish it>\"},",
|
|
658
|
+
" \"title\": \"<a short name for the work, when accepting>\",",
|
|
659
|
+
" \"scope\": \"<what changes, in one sentence>\",",
|
|
660
|
+
" \"reason\": \"<one sentence for a person reading the decision>\",",
|
|
661
|
+
" \"intent_evidence\": \"<the quotation that shows the request>\",",
|
|
662
|
+
" \"acknowledgement\": null}",
|
|
663
|
+
"```",
|
|
664
|
+
"",
|
|
665
|
+
"- Include exactly one `rule_assessments` entry for every rule above, matched or not.",
|
|
666
|
+
"- `accept` only when the discussion asks for a change the rules allow; otherwise `ignore`.",
|
|
667
|
+
"- `unavailable` only when the discussion is unreadable."
|
|
668
|
+
].join("\n");
|
|
669
|
+
}
|
|
670
|
+
/** Reads the JSON object out of what the model printed, tolerating a fenced block or surrounding prose. */
|
|
671
|
+
function parseAssessment(text) {
|
|
672
|
+
const start = text.indexOf("{");
|
|
673
|
+
const end = text.lastIndexOf("}");
|
|
674
|
+
if (start < 0 || end <= start) throw new Error("The assessment printed no JSON object");
|
|
675
|
+
const parsed = AssessmentSchema.parse(JSON.parse(text.slice(start, end + 1)));
|
|
676
|
+
if (parsed.decision === "accept" && !directionAllowed(parsed.direction)) throw new Error("The assessment accepts without a settled direction");
|
|
677
|
+
return parsed;
|
|
678
|
+
}
|
|
679
|
+
/** 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. */
|
|
680
|
+
function claudeAssessor(settings) {
|
|
681
|
+
return async (candidate) => {
|
|
682
|
+
const { agent, binary, model } = settings.assess;
|
|
683
|
+
if (agent !== "claude") throw new Error(`The assessor runs on claude; settings.assess.agent is ${agent}`);
|
|
684
|
+
const env = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== void 0));
|
|
685
|
+
const result = await runProcess(binary ?? "claude", [
|
|
686
|
+
"-p",
|
|
687
|
+
"--output-format",
|
|
688
|
+
"json",
|
|
689
|
+
...model ? ["--model", model] : []
|
|
690
|
+
], {
|
|
691
|
+
cwd: settings.checkout,
|
|
692
|
+
env,
|
|
693
|
+
stdin: assessmentPrompt(candidate, settings),
|
|
694
|
+
signal: AbortSignal.timeout(12e4),
|
|
695
|
+
timeoutMs: 12e4
|
|
696
|
+
});
|
|
697
|
+
if (result.exitCode !== 0) throw new Error(`The assessor exited ${result.exitCode}: ${result.stderr.slice(-500)}`);
|
|
698
|
+
const envelope = JSON.parse(result.stdout);
|
|
699
|
+
if (envelope.is_error) throw new Error(`The assessor failed: ${envelope.result ?? ""}`.slice(0, 500));
|
|
700
|
+
return parseAssessment(envelope.result ?? "");
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
// src/assessing.ts
|
|
704
|
+
/** The name an addressed request gives its ticket: its first line without the mentions, short enough for a branch. */
|
|
705
|
+
function named(candidate) {
|
|
706
|
+
return { title: (candidate.triggers[0]?.text ?? "").split("\n")[0].replace(/@[\w-]+/g, "").trim().slice(0, 60) || "Request" };
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* The Assessor a loop installs: it judges each candidate in one model call, in flight beside the rounds.
|
|
710
|
+
*
|
|
711
|
+
* The call is asynchronous so a slow assessment never holds up a Source. Its outcome is a decision the loop makes: the
|
|
712
|
+
* loop keeps one Engine across rounds, and a command run from this callback would see a Thread the round in flight is in
|
|
713
|
+
* the middle of changing. A verdict for an Eval that ended meanwhile is dropped, and its requeued Triggers get a fresh one.
|
|
714
|
+
*/
|
|
715
|
+
function assessing(options) {
|
|
716
|
+
const running = /* @__PURE__ */ new Map();
|
|
717
|
+
return {
|
|
718
|
+
request(candidate) {
|
|
719
|
+
running.set(candidate.evalId, candidate);
|
|
720
|
+
const explicit = candidate.strength === "explicit";
|
|
721
|
+
(async () => {
|
|
722
|
+
let outcome;
|
|
723
|
+
try {
|
|
724
|
+
const settings = options.settings();
|
|
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 = {
|
|
743
|
+
kind: "accept",
|
|
744
|
+
...named(candidate),
|
|
745
|
+
scope: "",
|
|
746
|
+
reason: "A person addressed the agent"
|
|
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
|
+
}
|
|
755
|
+
} catch (error) {
|
|
756
|
+
outcome = {
|
|
757
|
+
kind: "unavailable",
|
|
758
|
+
reason: `The assessment could not run: ${error.message}`
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
if (!running.has(candidate.evalId)) return;
|
|
762
|
+
running.delete(candidate.evalId);
|
|
763
|
+
const triggerId = candidate.triggers[0]?.id;
|
|
764
|
+
if (triggerId) options.decided.push({
|
|
765
|
+
triggerId,
|
|
766
|
+
outcome: {
|
|
767
|
+
...outcome,
|
|
768
|
+
evalId: candidate.evalId
|
|
769
|
+
}
|
|
770
|
+
});
|
|
771
|
+
})().catch((error) => {
|
|
772
|
+
options.log(`The assessment of ${candidate.evalId} failed: ${error.message}`);
|
|
773
|
+
});
|
|
774
|
+
},
|
|
775
|
+
release(evalId) {
|
|
776
|
+
running.delete(evalId);
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
191
780
|
// src/sources/github.ts
|
|
192
781
|
/**
|
|
193
782
|
* The GitHub Source: turns new mentions and new Issues in one repository into Triggers.
|
|
@@ -199,15 +788,15 @@ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
|
199
788
|
* A notification only says that something mentioned the account. The comment itself is read afterwards, so the Trigger
|
|
200
789
|
* carries what the person wrote, not the notification's summary.
|
|
201
790
|
*/
|
|
202
|
-
const SOURCE$
|
|
791
|
+
const SOURCE$2 = "github";
|
|
203
792
|
/** A thread identifier for an Issue or pull request number; both share one sequence in GitHub. */
|
|
204
793
|
const githubThread = (number) => ({
|
|
205
|
-
source: SOURCE$
|
|
794
|
+
source: SOURCE$2,
|
|
206
795
|
id: String(number)
|
|
207
796
|
});
|
|
208
797
|
/** Where a reply to this number goes. */
|
|
209
798
|
const githubChannel = (repository, number, url) => ({
|
|
210
|
-
source: SOURCE$
|
|
799
|
+
source: SOURCE$2,
|
|
211
800
|
thread: threadKey(githubThread(number)),
|
|
212
801
|
address: {
|
|
213
802
|
number: String(number),
|
|
@@ -282,10 +871,10 @@ function commentTrigger(input) {
|
|
|
282
871
|
const login = comment.user.login;
|
|
283
872
|
return {
|
|
284
873
|
id: key("github-comment", url, String(comment.id ?? ""), at),
|
|
285
|
-
source: SOURCE$
|
|
874
|
+
source: SOURCE$2,
|
|
286
875
|
threads: [githubThread(number)],
|
|
287
876
|
actor: {
|
|
288
|
-
source: SOURCE$
|
|
877
|
+
source: SOURCE$2,
|
|
289
878
|
id: login
|
|
290
879
|
},
|
|
291
880
|
human: isHumanLogin(comment.user) && !sameName(login, agent),
|
|
@@ -348,6 +937,69 @@ async function pollNotifications(input) {
|
|
|
348
937
|
}
|
|
349
938
|
return triggers;
|
|
350
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
|
+
}
|
|
351
1003
|
// src/sources/feishu.ts
|
|
352
1004
|
/**
|
|
353
1005
|
* The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
|
|
@@ -358,17 +1010,17 @@ async function pollNotifications(input) {
|
|
|
358
1010
|
* A chat is listened to only when `settings.feishu.chats` names it, because a bot in a busy chat sees everything and a
|
|
359
1011
|
* Trigger per message would cost the team attention for nothing.
|
|
360
1012
|
*/
|
|
361
|
-
const SOURCE = "feishu";
|
|
1013
|
+
const SOURCE$1 = "feishu";
|
|
362
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
|
|
363
1015
|
* the app's event subscription, so read it from `lark-cli event list` rather than assume it. */
|
|
364
1016
|
const MESSAGE_EVENT = "im.message.receive_v1";
|
|
365
1017
|
const feishuThread = (chatId, rootId, messageId) => ({
|
|
366
|
-
source: SOURCE,
|
|
1018
|
+
source: SOURCE$1,
|
|
367
1019
|
id: `${chatId}:${rootId ?? messageId}`
|
|
368
1020
|
});
|
|
369
1021
|
/** Where a reply to this message goes; `direct` is explicit because group and direct chat ids both start with `oc_`. */
|
|
370
1022
|
const feishuChannel = (chatId, messageId, direct = false) => ({
|
|
371
|
-
source: SOURCE,
|
|
1023
|
+
source: SOURCE$1,
|
|
372
1024
|
thread: `feishu:${chatId}`,
|
|
373
1025
|
address: {
|
|
374
1026
|
chatId,
|
|
@@ -427,10 +1079,10 @@ function feishuTrigger(input, options) {
|
|
|
427
1079
|
const url = event.message_app_link;
|
|
428
1080
|
return {
|
|
429
1081
|
id: key("feishu", event.message_id),
|
|
430
|
-
source: SOURCE,
|
|
1082
|
+
source: SOURCE$1,
|
|
431
1083
|
threads: [feishuThread(event.chat_id, event.root_id, event.message_id)],
|
|
432
1084
|
actor: {
|
|
433
|
-
source: SOURCE,
|
|
1085
|
+
source: SOURCE$1,
|
|
434
1086
|
id: senderId
|
|
435
1087
|
},
|
|
436
1088
|
human: senderType === "user",
|
|
@@ -483,9 +1135,7 @@ async function chatMembers(cli, chatId, signal) {
|
|
|
483
1135
|
chatId,
|
|
484
1136
|
"--member-types",
|
|
485
1137
|
"user",
|
|
486
|
-
"--page-all"
|
|
487
|
-
"--page-limit",
|
|
488
|
-
"0"
|
|
1138
|
+
"--page-all"
|
|
489
1139
|
], { signal })).users ?? []).map((user) => ({
|
|
490
1140
|
id: user.member_id,
|
|
491
1141
|
name: user.name ?? user.member_id
|
|
@@ -639,6 +1289,7 @@ function consumeEvents(options) {
|
|
|
639
1289
|
settled();
|
|
640
1290
|
});
|
|
641
1291
|
child.on("close", (code) => {
|
|
1292
|
+
options.onEnded?.();
|
|
642
1293
|
if (!finished) {
|
|
643
1294
|
reader.flush();
|
|
644
1295
|
if (code !== 0) options.onError(`The event consumer exited with code ${code}`);
|
|
@@ -656,6 +1307,97 @@ function consumeEvents(options) {
|
|
|
656
1307
|
ended
|
|
657
1308
|
};
|
|
658
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
|
+
}
|
|
659
1401
|
// src/infra/worktree.ts
|
|
660
1402
|
/**
|
|
661
1403
|
* Gives a ticket its own git worktree and branch, so two tickets can change one repository at once and neither sees the
|
|
@@ -691,15 +1433,63 @@ async function isGitRepository(directory) {
|
|
|
691
1433
|
}
|
|
692
1434
|
/**
|
|
693
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.
|
|
694
1437
|
*
|
|
695
1438
|
* @throws when git cannot create the worktree, such as when the checkout has no commit yet; the caller then reports the
|
|
696
1439
|
* ticket as failed instead of starting an agent in a directory that is not the repository.
|
|
697
1440
|
*/
|
|
698
1441
|
async function prepareWorktree(options) {
|
|
699
|
-
const { checkout, directory, branch, signal } = options;
|
|
1442
|
+
const { checkout, directory, branch, prNumber, repository, signal } = options;
|
|
700
1443
|
await mkdir(directory, { recursive: true });
|
|
701
1444
|
if ((await readdir(directory)).length) return directory;
|
|
702
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
|
+
}
|
|
703
1493
|
await run("git", [
|
|
704
1494
|
"-C",
|
|
705
1495
|
checkout,
|
|
@@ -721,13 +1511,13 @@ async function prepareWorktree(options) {
|
|
|
721
1511
|
signal,
|
|
722
1512
|
timeoutMs: 12e4
|
|
723
1513
|
}).catch(async (error) => {
|
|
724
|
-
await removeWorktree(checkout, directory, signal);
|
|
1514
|
+
await removeWorktree(checkout, directory, signal, branch);
|
|
725
1515
|
throw new Error(`${directory} is not a branch point: ${error.message}`, { cause: error });
|
|
726
1516
|
});
|
|
727
1517
|
return directory;
|
|
728
1518
|
}
|
|
729
1519
|
/** Removes a ticket's worktree once its ticket ended, so the state directory does not grow without bound. */
|
|
730
|
-
async function removeWorktree(checkout, directory, signal) {
|
|
1520
|
+
async function removeWorktree(checkout, directory, signal, branchToDelete) {
|
|
731
1521
|
try {
|
|
732
1522
|
await run("git", [
|
|
733
1523
|
"-C",
|
|
@@ -741,14 +1531,92 @@ async function removeWorktree(checkout, directory, signal) {
|
|
|
741
1531
|
timeoutMs: 12e4
|
|
742
1532
|
});
|
|
743
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
|
+
};
|
|
744
1604
|
}
|
|
745
1605
|
// src/runner.ts
|
|
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. */
|
|
1607
|
+
const REPLY_MAX = 200;
|
|
1608
|
+
/** The first sentence of a report summary, short enough to send; the record keeps every word. */
|
|
1609
|
+
function deliverable(summary) {
|
|
1610
|
+
const one = summary.replace(/\s+/g, " ").trim();
|
|
1611
|
+
const text = ((one.split(/(?<=[.!?])\s|(?<=[\u3002\uff01\uff1f])/)[0] ?? "") || one).replace(/[\s.!?\u3002\uff01\uff1f]+$/, "");
|
|
1612
|
+
return text.length > REPLY_MAX ? `${text.slice(0, 199).trimEnd()}…` : text || "The work is done.";
|
|
1613
|
+
}
|
|
746
1614
|
function deliver(engine, repo, delivered, log) {
|
|
747
1615
|
for (const ticket of repo.tickets.list()) {
|
|
748
1616
|
const report = latestReport(ticket);
|
|
749
1617
|
if (!ticket.ended || report?.state !== "ready" || delivered.has(`${ticket.id}@${report.at}`)) continue;
|
|
750
1618
|
delivered.add(`${ticket.id}@${report.at}`);
|
|
751
|
-
const text = String(report.summary)
|
|
1619
|
+
const text = deliverable(String(report.summary));
|
|
752
1620
|
try {
|
|
753
1621
|
engine.reply({
|
|
754
1622
|
purpose: "result",
|
|
@@ -761,45 +1629,24 @@ function deliver(engine, repo, delivered, log) {
|
|
|
761
1629
|
}
|
|
762
1630
|
}
|
|
763
1631
|
}
|
|
764
|
-
/**
|
|
765
|
-
|
|
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 {
|
|
1632
|
+
/** Holds outcomes that arrive while no round is listening, and wakes a round to record them. */
|
|
1633
|
+
var WorkQueue = class {
|
|
785
1634
|
items = [];
|
|
786
|
-
handoff;
|
|
787
1635
|
waiter;
|
|
788
|
-
/**
|
|
1636
|
+
/** An outcome that arrived; it is kept even with no round waiting, so one that outlives its round is still recorded. */
|
|
789
1637
|
push(item) {
|
|
790
1638
|
this.items.push(item);
|
|
791
|
-
this.handoff?.(item);
|
|
792
1639
|
this.wake();
|
|
793
1640
|
}
|
|
794
|
-
/**
|
|
1641
|
+
/** What arrived since the last drain. */
|
|
795
1642
|
drain() {
|
|
796
1643
|
return this.items.splice(0);
|
|
797
1644
|
}
|
|
798
|
-
/** Whether
|
|
1645
|
+
/** Whether an outcome waits to be recorded. */
|
|
799
1646
|
ready() {
|
|
800
1647
|
return this.items.length > 0;
|
|
801
1648
|
}
|
|
802
|
-
/** Settles when
|
|
1649
|
+
/** Settles when an outcome arrives, or when `ms` passes. */
|
|
803
1650
|
wait(ms) {
|
|
804
1651
|
if (this.items.length) return Promise.resolve();
|
|
805
1652
|
return new Promise((resolve) => {
|
|
@@ -816,8 +1663,17 @@ var TurnQueue = class {
|
|
|
816
1663
|
this.waiter?.();
|
|
817
1664
|
}
|
|
818
1665
|
};
|
|
819
|
-
/** How long one round waits for
|
|
1666
|
+
/** How long one round waits for an outcome before the next round; one that arrives is recorded at once, not several rounds later. */
|
|
820
1667
|
const TURN_WAIT_MS = 1e3;
|
|
1668
|
+
/** Records the assessments that finished as Decisions; one the Engine refuses is logged, not thrown. */
|
|
1669
|
+
function decide(engine, decided, log) {
|
|
1670
|
+
for (const { triggerId, outcome } of decided) try {
|
|
1671
|
+
const made = engine.decide(triggerId, outcome);
|
|
1672
|
+
log(`Decided ${triggerId}: ${made.kind}${made.ticketId ? `, ticket ${made.ticketId}` : ""}${made.reason?.length ? ` — ${JSON.stringify(made.reason)}` : ""}`);
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
log(`Could not decide ${triggerId}: ${error.message}`);
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
821
1677
|
/** Records the turns that finished, so a ticket ends without the loop holding work in memory; a refused report is logged, not thrown. */
|
|
822
1678
|
function record(engine, repo, finished, log) {
|
|
823
1679
|
for (const item of finished) try {
|
|
@@ -833,17 +1689,36 @@ function record(engine, repo, finished, log) {
|
|
|
833
1689
|
}
|
|
834
1690
|
}
|
|
835
1691
|
/** Posts the messages the Engine queued, one comment per message. */
|
|
836
|
-
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);
|
|
837
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
|
+
}
|
|
838
1711
|
if (message.channel.source === "feishu") {
|
|
839
1712
|
const address = message.channel.address;
|
|
840
1713
|
if (!clis.feishu) {
|
|
841
1714
|
log(`Cannot answer in ${address.chatId}: the Feishu Source is off`);
|
|
842
1715
|
continue;
|
|
843
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}`);
|
|
844
1720
|
try {
|
|
845
1721
|
await reply(clis.feishu, address.messageId, message.text, message.id);
|
|
846
|
-
log(`Answered in ${address.chatId}`);
|
|
847
1722
|
} catch (error) {
|
|
848
1723
|
log(`Could not answer in ${address.chatId}: ${error.message}`);
|
|
849
1724
|
}
|
|
@@ -871,81 +1746,6 @@ async function send(channel, clis, log) {
|
|
|
871
1746
|
/** Where the loop keeps its own bookkeeping, beside the domain state. */
|
|
872
1747
|
const pollKey = "github:poll";
|
|
873
1748
|
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
1749
|
/** Lines one round reads from the stream at most, so a chat that keeps talking does not hold a round open. */
|
|
950
1750
|
const MAX_LINES = 500;
|
|
951
1751
|
/** A failed save of the last round must not stop the next one. */
|
|
@@ -972,17 +1772,38 @@ function outbox() {
|
|
|
972
1772
|
var AgentExecutor = class {
|
|
973
1773
|
options;
|
|
974
1774
|
active = /* @__PURE__ */ new Map();
|
|
1775
|
+
/** Tickets whose turn waits for a free slot, oldest first. */
|
|
1776
|
+
pending = [];
|
|
1777
|
+
pumping = false;
|
|
975
1778
|
constructor(options) {
|
|
976
1779
|
this.options = options;
|
|
977
1780
|
}
|
|
978
1781
|
start(ticket, assignment) {
|
|
979
|
-
const controller = new AbortController();
|
|
980
1782
|
const { site } = this.options;
|
|
981
1783
|
site.started(ticket.id, assignment.id);
|
|
982
|
-
this.
|
|
983
|
-
|
|
1784
|
+
this.pending.push({
|
|
1785
|
+
ticket,
|
|
1786
|
+
assignment
|
|
1787
|
+
});
|
|
1788
|
+
this.pump();
|
|
984
1789
|
}
|
|
985
1790
|
deliver() {}
|
|
1791
|
+
/**
|
|
1792
|
+
* Takes in the tickets a previous process left running. Their agents ended with that process, so a turn that had not
|
|
1793
|
+
* reported is restarted with a recovery note, and one whose report a person still has to act on goes back to the queue
|
|
1794
|
+
* with its inputs. A start from `interrupted` joins the same queue as a new ticket.
|
|
1795
|
+
*/
|
|
1796
|
+
recover(open) {
|
|
1797
|
+
for (const ticket of open) {
|
|
1798
|
+
const assignment = runningAssignment(ticket);
|
|
1799
|
+
if (assignment) this.options.site.interrupted(ticket.id, assignment.id);
|
|
1800
|
+
}
|
|
1801
|
+
for (const ticket of open) for (const assignment of ticket.assignments) if (assignment.state === "pending") this.pending.push({
|
|
1802
|
+
ticket,
|
|
1803
|
+
assignment
|
|
1804
|
+
});
|
|
1805
|
+
this.pump();
|
|
1806
|
+
}
|
|
986
1807
|
/** The Engine's memory of the ticket, so the report lands on a ticket that already holds this round's changes to it. */
|
|
987
1808
|
refresh(ticket) {
|
|
988
1809
|
this.options.engine.updateTicket(ticket);
|
|
@@ -990,23 +1811,53 @@ var AgentExecutor = class {
|
|
|
990
1811
|
stop(ticket) {
|
|
991
1812
|
this.active.get(ticket.id)?.abort();
|
|
992
1813
|
this.active.delete(ticket.id);
|
|
1814
|
+
const waiting = this.pending.findIndex((item) => item.ticket.id === ticket.id);
|
|
1815
|
+
if (waiting >= 0) this.pending.splice(waiting, 1);
|
|
1816
|
+
this.pump();
|
|
1817
|
+
}
|
|
1818
|
+
/** Starts waiting tickets while a slot is free; the turns run beside the rounds, so this never blocks on one. */
|
|
1819
|
+
pump() {
|
|
1820
|
+
if (this.pumping) return;
|
|
1821
|
+
this.pumping = true;
|
|
1822
|
+
Promise.resolve().then(() => {
|
|
1823
|
+
this.pumping = false;
|
|
1824
|
+
while (this.active.size < this.options.maxWorkers && this.pending.length) {
|
|
1825
|
+
const item = this.pending.shift();
|
|
1826
|
+
const controller = new AbortController();
|
|
1827
|
+
this.active.set(item.ticket.id, controller);
|
|
1828
|
+
this.execute(item.ticket, item.assignment, controller);
|
|
1829
|
+
}
|
|
1830
|
+
});
|
|
993
1831
|
}
|
|
994
1832
|
async execute(ticket, assignment, controller) {
|
|
995
|
-
const { settings, runner, stateDir, accounts, feishuCli, site } = this.options;
|
|
1833
|
+
const { settings, runner, stateDir, accounts, feishuCli, site, repo, log } = this.options;
|
|
996
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;
|
|
997
1838
|
try {
|
|
998
1839
|
const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
|
|
999
1840
|
await prepareWorktree({
|
|
1000
1841
|
checkout: settings.checkout,
|
|
1001
1842
|
directory,
|
|
1002
1843
|
branch,
|
|
1844
|
+
prNumber: isPrReview ? prNumber : void 0,
|
|
1845
|
+
repository: settings.github?.repository,
|
|
1003
1846
|
signal: controller.signal
|
|
1004
1847
|
});
|
|
1005
1848
|
if (settings.executor.prepare) await run("/bin/sh", ["-c", settings.executor.prepare], {
|
|
1006
1849
|
env: this.variables(ticket, directory, branch),
|
|
1007
1850
|
timeoutMs: 12e4
|
|
1008
1851
|
});
|
|
1009
|
-
|
|
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;
|
|
1010
1861
|
const result = await runner.run({
|
|
1011
1862
|
prompt,
|
|
1012
1863
|
cwd: directory,
|
|
@@ -1016,9 +1867,62 @@ var AgentExecutor = class {
|
|
|
1016
1867
|
} : accounts, this.variables(ticket, directory, branch)),
|
|
1017
1868
|
signal: controller.signal,
|
|
1018
1869
|
timeoutMs: settings.executor.timeoutMinutes * 6e4,
|
|
1019
|
-
model: settings.executor.model
|
|
1870
|
+
model: settings.executor.model,
|
|
1871
|
+
readOnly: isAutonomous
|
|
1020
1872
|
});
|
|
1021
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
|
+
});
|
|
1022
1926
|
await appendLog(directory, prompt, result.raw.slice(-2e4), report);
|
|
1023
1927
|
site.reported(ticket.id, {
|
|
1024
1928
|
state: report.state ?? (result.ok ? "ready" : "failed"),
|
|
@@ -1029,6 +1933,7 @@ var AgentExecutor = class {
|
|
|
1029
1933
|
site.failed(ticket.id, assignment.id, `The agent could not run: ${error.message}`);
|
|
1030
1934
|
} finally {
|
|
1031
1935
|
this.active.delete(ticket.id);
|
|
1936
|
+
this.pump();
|
|
1032
1937
|
}
|
|
1033
1938
|
}
|
|
1034
1939
|
variables(ticket, directory, branch) {
|
|
@@ -1058,6 +1963,12 @@ async function appendLog(directory, prompt, raw, report) {
|
|
|
1058
1963
|
"",
|
|
1059
1964
|
`## ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
1060
1965
|
"",
|
|
1966
|
+
"**Prompt**",
|
|
1967
|
+
"",
|
|
1968
|
+
"```",
|
|
1969
|
+
prompt,
|
|
1970
|
+
"```",
|
|
1971
|
+
"",
|
|
1061
1972
|
"**Report**",
|
|
1062
1973
|
"",
|
|
1063
1974
|
"```json",
|
|
@@ -1070,8 +1981,7 @@ async function appendLog(directory, prompt, raw, report) {
|
|
|
1070
1981
|
raw,
|
|
1071
1982
|
"```"
|
|
1072
1983
|
].join("\n");
|
|
1073
|
-
|
|
1074
|
-
await mkdir(join(directory, ".superagent"), { recursive: true }).then(() => writeFile(path, `${previous}${entry}\n`));
|
|
1984
|
+
await mkdir(join(directory, ".superagent"), { recursive: true }).then(() => appendFile(path, `${entry}\n`));
|
|
1075
1985
|
}
|
|
1076
1986
|
/**
|
|
1077
1987
|
* The loop that makes an installation run without a person: poll the Sources, assess what they bring, and run the tickets
|
|
@@ -1088,50 +1998,79 @@ async function runLoop(options) {
|
|
|
1088
1998
|
const signal = stop.signal;
|
|
1089
1999
|
const github = settings.github?.enabled ? settings.github : void 0;
|
|
1090
2000
|
const feishu = settings.feishu?.enabled ? settings.feishu : void 0;
|
|
1091
|
-
|
|
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.");
|
|
1092
2003
|
const login = github ? await agentLogin(github.cli, signal) : "";
|
|
2004
|
+
const twitterBot = twitter ? await twitterAccount(twitter.cli, signal) : "";
|
|
1093
2005
|
const accounts = {
|
|
1094
2006
|
stateDir: settings.stateDir,
|
|
1095
2007
|
githubCli: github?.cli ?? "gh",
|
|
1096
2008
|
agentLogin: login
|
|
1097
2009
|
};
|
|
1098
2010
|
await writeEnvironment(accounts, settings.executor.blockedCommands);
|
|
2011
|
+
const standing = await standingRules();
|
|
1099
2012
|
const channel = outbox();
|
|
1100
|
-
const
|
|
2013
|
+
const scope = sourceScope(settings);
|
|
2014
|
+
const decided = new WorkQueue();
|
|
2015
|
+
const finished = new WorkQueue();
|
|
1101
2016
|
const engine = new Engine({
|
|
1102
2017
|
repo,
|
|
1103
|
-
policy: () => buildPolicy(settings),
|
|
1104
|
-
scope
|
|
1105
|
-
assessor:
|
|
2018
|
+
policy: () => buildPolicy(settings, scope),
|
|
2019
|
+
scope,
|
|
2020
|
+
assessor: assessing({
|
|
2021
|
+
settings: () => settings,
|
|
2022
|
+
next: claudeAssessor(settings),
|
|
2023
|
+
decided,
|
|
2024
|
+
log
|
|
2025
|
+
}),
|
|
1106
2026
|
executor: void 0,
|
|
1107
2027
|
outbox: channel
|
|
1108
2028
|
});
|
|
2029
|
+
const site = {
|
|
2030
|
+
started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
|
|
2031
|
+
reported: (ticketId, report) => {
|
|
2032
|
+
record(engine, repo, [{
|
|
2033
|
+
ticketId,
|
|
2034
|
+
report
|
|
2035
|
+
}], log);
|
|
2036
|
+
},
|
|
2037
|
+
failed: (ticketId, _assignmentId, summary) => {
|
|
2038
|
+
record(engine, repo, [{
|
|
2039
|
+
ticketId,
|
|
2040
|
+
report: {
|
|
2041
|
+
state: "failed",
|
|
2042
|
+
summary
|
|
2043
|
+
}
|
|
2044
|
+
}], log);
|
|
2045
|
+
},
|
|
2046
|
+
interrupted: (ticketId, assignmentId) => {
|
|
2047
|
+
try {
|
|
2048
|
+
engine.assignmentInterrupted(ticketId, assignmentId);
|
|
2049
|
+
} catch (error) {
|
|
2050
|
+
log(`Could not recover ${ticketId}: ${error.message}`);
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
};
|
|
1109
2054
|
const executor = new AgentExecutor({
|
|
1110
2055
|
engine,
|
|
1111
2056
|
settings,
|
|
2057
|
+
maxWorkers: settings.executor.maxWorkers,
|
|
1112
2058
|
runner: runnerFor(settings.executor.agent, settings.executor.binary),
|
|
1113
2059
|
stateDir: settings.stateDir,
|
|
1114
2060
|
repository: github?.repository ?? settings.checkout,
|
|
1115
2061
|
agent: login,
|
|
1116
2062
|
accounts,
|
|
1117
2063
|
...feishu ? { feishuCli: feishu.cli } : {},
|
|
1118
|
-
site
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
report
|
|
1123
|
-
}),
|
|
1124
|
-
failed: (ticketId, _assignmentId, summary) => finished.push({
|
|
1125
|
-
ticketId,
|
|
1126
|
-
report: {
|
|
1127
|
-
state: "failed",
|
|
1128
|
-
summary
|
|
1129
|
-
}
|
|
1130
|
-
})
|
|
1131
|
-
},
|
|
1132
|
-
prompt: async (ticket, directory, branch) => {
|
|
2064
|
+
site,
|
|
2065
|
+
repo,
|
|
2066
|
+
log,
|
|
2067
|
+
prompt: async (ticket, directory, branch, prVerification) => {
|
|
1133
2068
|
const trigger = repo.triggers.get(ticket.origin.triggerId);
|
|
1134
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;
|
|
2072
|
+
const notes = ticket.inputs.flatMap((input) => input.kind === "text" ? [input.text] : []);
|
|
2073
|
+
const readOnly = ticket.mandate.strength === "inferred" && !isPrReview;
|
|
1135
2074
|
return composePrompt({
|
|
1136
2075
|
ticket,
|
|
1137
2076
|
trigger,
|
|
@@ -1140,7 +2079,14 @@ async function runLoop(options) {
|
|
|
1140
2079
|
branchPrefix: settings.branchPrefix,
|
|
1141
2080
|
source,
|
|
1142
2081
|
instructions: settings.prompts,
|
|
1143
|
-
branch
|
|
2082
|
+
branch,
|
|
2083
|
+
standing,
|
|
2084
|
+
notes,
|
|
2085
|
+
readOnly,
|
|
2086
|
+
isPrReview,
|
|
2087
|
+
prNumber,
|
|
2088
|
+
prVerification,
|
|
2089
|
+
autoMergeAllowed: Boolean(github?.prReview?.autoMerge)
|
|
1144
2090
|
});
|
|
1145
2091
|
}
|
|
1146
2092
|
});
|
|
@@ -1176,7 +2122,6 @@ async function runLoop(options) {
|
|
|
1176
2122
|
};
|
|
1177
2123
|
const store = (trigger) => {
|
|
1178
2124
|
try {
|
|
1179
|
-
options.repo;
|
|
1180
2125
|
if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
|
|
1181
2126
|
} catch (error) {
|
|
1182
2127
|
log(`Could not store ${trigger.id}: ${error.message}`);
|
|
@@ -1197,13 +2142,7 @@ async function runLoop(options) {
|
|
|
1197
2142
|
};
|
|
1198
2143
|
let handle;
|
|
1199
2144
|
const stopListening = new AbortController();
|
|
1200
|
-
|
|
1201
|
-
stopListening.abort();
|
|
1202
|
-
};
|
|
1203
|
-
const endStream = async () => {
|
|
1204
|
-
unlisten();
|
|
1205
|
-
if (handle) await handle.ended;
|
|
1206
|
-
};
|
|
2145
|
+
if (options.once) caller.addEventListener("abort", () => stopListening.abort(), { once: true });
|
|
1207
2146
|
if (feishu) handle = consumeEvents({
|
|
1208
2147
|
cli: feishu.cli,
|
|
1209
2148
|
signal: stopListening.signal,
|
|
@@ -1211,6 +2150,7 @@ async function runLoop(options) {
|
|
|
1211
2150
|
onListening: (started) => {
|
|
1212
2151
|
handle = started;
|
|
1213
2152
|
},
|
|
2153
|
+
...options.once ? {} : { onEnded: () => stopListening.abort() },
|
|
1214
2154
|
onError: (message) => {
|
|
1215
2155
|
if (!signal.aborted) log(message);
|
|
1216
2156
|
}
|
|
@@ -1219,13 +2159,18 @@ async function runLoop(options) {
|
|
|
1219
2159
|
const nextLine = () => handle ? handle.next(settings.executor.streamIdleMs) : Promise.resolve(false);
|
|
1220
2160
|
const delivered = /* @__PURE__ */ new Set();
|
|
1221
2161
|
engine.options.executor = executor;
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
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
|
+
});
|
|
2168
|
+
try {
|
|
2169
|
+
for (const ticket of repo.tickets.active()) engine.updateTicket(ticket);
|
|
2170
|
+
executor.recover(repo.tickets.active());
|
|
2171
|
+
} catch (error) {
|
|
2172
|
+
log(`Could not recover the tickets left running: ${error.message}`);
|
|
2173
|
+
}
|
|
1229
2174
|
const inRound = /* @__PURE__ */ new Set();
|
|
1230
2175
|
const ingest = () => {
|
|
1231
2176
|
const waiting = repo.triggers.list().filter((trigger) => trigger.source === "feishu");
|
|
@@ -1260,11 +2205,100 @@ async function runLoop(options) {
|
|
|
1260
2205
|
mark: (id) => repo.setMeta(seenKey(id), true)
|
|
1261
2206
|
});
|
|
1262
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
|
+
}
|
|
1263
2221
|
since = round;
|
|
1264
2222
|
repo.setMeta(pollKey, since);
|
|
1265
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
|
+
}
|
|
1266
2300
|
engine.evaluateDue();
|
|
1267
|
-
|
|
2301
|
+
decide(engine, decided.drain(), log);
|
|
1268
2302
|
record(engine, repo, finished.drain(), log);
|
|
1269
2303
|
await repo.flush();
|
|
1270
2304
|
await pull();
|
|
@@ -1273,24 +2307,321 @@ async function runLoop(options) {
|
|
|
1273
2307
|
await repo.flush();
|
|
1274
2308
|
await send(channel, {
|
|
1275
2309
|
...github ? { github: github.cli } : {},
|
|
1276
|
-
...feishu ? { feishu: feishu.cli } : {}
|
|
1277
|
-
|
|
2310
|
+
...feishu ? { feishu: feishu.cli } : {},
|
|
2311
|
+
...twitter ? { twitter: twitter.cli } : {}
|
|
2312
|
+
}, log, settings.attention);
|
|
1278
2313
|
await repo.flush();
|
|
1279
2314
|
await sync();
|
|
1280
2315
|
} catch (error) {
|
|
1281
2316
|
if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
|
|
1282
2317
|
}
|
|
1283
2318
|
if (options.once) break;
|
|
1284
|
-
|
|
2319
|
+
const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity, twitter?.pollSeconds ?? Infinity);
|
|
2320
|
+
let left = options.once ? 0 : seconds * 1e3;
|
|
1285
2321
|
while (left > 0 && !signal.aborted) {
|
|
1286
2322
|
const began = Date.now();
|
|
1287
|
-
|
|
1288
|
-
|
|
2323
|
+
const wait = Math.max(1, Math.min(TURN_WAIT_MS, left));
|
|
2324
|
+
await Promise.race([Promise.race([finished.wait(wait), decided.wait(wait)]), new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
|
|
2325
|
+
if (finished.ready() || decided.ready()) break;
|
|
1289
2326
|
left -= Date.now() - began;
|
|
1290
2327
|
}
|
|
1291
2328
|
}
|
|
1292
2329
|
stop.abort();
|
|
1293
|
-
if (
|
|
2330
|
+
if (options.once && !process.env.VITEST) setImmediate(() => process.exit(process.exitCode ?? 0));
|
|
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;
|
|
1294
2625
|
}
|
|
1295
2626
|
// src/cli.ts
|
|
1296
2627
|
/**
|
|
@@ -1302,12 +2633,20 @@ async function runLoop(options) {
|
|
|
1302
2633
|
const USAGE = `superagent — an agent that turns GitHub and Feishu requests into tickets
|
|
1303
2634
|
|
|
1304
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
|
|
1305
2637
|
superagent status [dir] print open tickets and recent activity as Markdown
|
|
1306
2638
|
superagent doctor [dir] show which coding agents are installed and which one is selected
|
|
1307
2639
|
superagent agents list the coding agents a configuration may name
|
|
1308
2640
|
superagent run <dir> -p <text> run one prompt on the configured agent, in a directory it names
|
|
1309
2641
|
superagent poll [dir] [--once] poll the Sources and run the tickets they bring, once or until interrupted
|
|
1310
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
|
+
|
|
1311
2650
|
Every command that reads an installation takes the directory that holds ${SETTINGS_FILE}.`;
|
|
1312
2651
|
async function exists(path) {
|
|
1313
2652
|
try {
|
|
@@ -1348,8 +2687,32 @@ async function init(dir) {
|
|
|
1348
2687
|
].join("\n"));
|
|
1349
2688
|
return 0;
|
|
1350
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
|
+
}
|
|
1351
2713
|
async function status(dir) {
|
|
1352
|
-
const { tickets, threads, exists: found } = await readState(await stateDirOf(dir));
|
|
2714
|
+
const { tickets, threads, decisions, triggers: all, exists: found } = await readState(await stateDirOf(dir));
|
|
2715
|
+
const triggers = new Map(all.map((trigger) => [trigger.id, trigger]));
|
|
1353
2716
|
if (!found) {
|
|
1354
2717
|
process.stdout.write(`No state directory yet. Run \`superagent init\` first.\n`);
|
|
1355
2718
|
return 1;
|
|
@@ -1378,6 +2741,16 @@ async function status(dir) {
|
|
|
1378
2741
|
lines.push("");
|
|
1379
2742
|
}
|
|
1380
2743
|
if (!tickets.length) lines.push("No tickets yet.", "");
|
|
2744
|
+
const judged = decisions.filter((decision) => decision.strength === "inferred").sort((a, b) => a.at.localeCompare(b.at)).slice(-10);
|
|
2745
|
+
if (judged.length) {
|
|
2746
|
+
lines.push("## Unaddressed messages", "");
|
|
2747
|
+
for (const decision of judged) {
|
|
2748
|
+
const message = decision.triggerIds.map((id) => triggers.get(id)?.text ?? "").join(" ");
|
|
2749
|
+
const what = decision.ticketId ? `ticket \`${decision.ticketId}\`` : decision.kind;
|
|
2750
|
+
lines.push(`- ${decision.at} **${what}** — ${reasonText(decision.reason)}${message ? ` — “${message.replace(/\s+/g, " ").slice(0, 80)}”` : ""}`);
|
|
2751
|
+
}
|
|
2752
|
+
lines.push("");
|
|
2753
|
+
}
|
|
1381
2754
|
process.stdout.write(lines.join("\n"));
|
|
1382
2755
|
return 0;
|
|
1383
2756
|
}
|
|
@@ -1431,7 +2804,7 @@ async function poll(dir, once) {
|
|
|
1431
2804
|
process.stderr.write(`${error.message}\n`);
|
|
1432
2805
|
return 1;
|
|
1433
2806
|
}
|
|
1434
|
-
const repo = new FileRepositories(settings.stateDir
|
|
2807
|
+
const repo = new FileRepositories(settings.stateDir);
|
|
1435
2808
|
await repo.open();
|
|
1436
2809
|
const controller = new AbortController();
|
|
1437
2810
|
process.on("SIGINT", () => controller.abort());
|
|
@@ -1459,6 +2832,7 @@ async function main(argv) {
|
|
|
1459
2832
|
const dirOf = (index) => rest[index] && !rest[index].startsWith("-") ? resolve(rest[index]) : process.cwd();
|
|
1460
2833
|
switch (command) {
|
|
1461
2834
|
case "init": return init(rest[0] ? resolve(rest[0]) : process.cwd());
|
|
2835
|
+
case "setup": return setupSources(dirOf(0), rest);
|
|
1462
2836
|
case "status": return status(dirOf(0));
|
|
1463
2837
|
case "doctor": return doctor(dirOf(0));
|
|
1464
2838
|
case "agents":
|