superagent-skill 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +120 -2
- package/SKILL.md +143 -0
- package/bin/superagent.js +3 -0
- package/lib/cli.mjs +1717 -0
- package/lib/index.mjs +70 -0
- package/lib/settings-D0qG6Mo8.mjs +2968 -0
- package/package.json +57 -4
- package/prompts/delivery.md +4 -0
- package/prompts/scope.md +5 -0
package/lib/cli.mjs
ADDED
|
@@ -0,0 +1,1717 @@
|
|
|
1
|
+
import { C as escapeRegExp, D as reasonText, L as latestReport, S as writeEnvironment, T as Engine, U as threadKey, V as runningAssignment, a as readSettings, b as directionAllowed, c as AGENT_NAMES, g as readState, h as FileRepositories, j as key, l as installed, m as runProcess, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor, v as RuleAssessmentSchema, w as sameName, x as runEnvironment } from "./settings-D0qG6Mo8.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { access, appendFile, mkdir, readFile, readdir, stat } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { execFile, spawn } from "node:child_process";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
// src/infra/commands.ts
|
|
9
|
+
/** Runs the Source CLIs (`gh`, `lark-cli`) and reads their JSON. Every call is bounded and never prompts. */
|
|
10
|
+
var CliError = class extends Error {
|
|
11
|
+
stdout;
|
|
12
|
+
stderr;
|
|
13
|
+
constructor(program, message, stdout, stderr) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.stdout = stdout;
|
|
16
|
+
this.stderr = stderr;
|
|
17
|
+
this.name = "CliError";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/** Runs a program and returns its standard output; a non-zero exit throws a `CliError` that keeps both streams. */
|
|
21
|
+
function run(program, argv, options = {}) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const child = execFile(program, argv, {
|
|
24
|
+
cwd: options.cwd,
|
|
25
|
+
env: {
|
|
26
|
+
...process.env,
|
|
27
|
+
...options.env
|
|
28
|
+
},
|
|
29
|
+
timeout: options.timeoutMs ?? 12e4,
|
|
30
|
+
maxBuffer: 64 << 20,
|
|
31
|
+
...options.signal ? { signal: options.signal } : {}
|
|
32
|
+
}, (error, stdout, stderr) => {
|
|
33
|
+
if (error) reject(new CliError(program, `${program} ${argv.join(" ")} failed: ${stderr.trim() || error.message}`, stdout, stderr));
|
|
34
|
+
else resolve(stdout);
|
|
35
|
+
});
|
|
36
|
+
if (options.stdin !== void 0) child.stdin?.end(options.stdin);
|
|
37
|
+
else child.stdin?.end();
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** Runs a program and parses its JSON output; accepts the plain shape and the `{ok, data}` envelope `lark-cli` uses. */
|
|
41
|
+
async function runJson(program, argv, options = {}) {
|
|
42
|
+
const text = await run(program, argv, options);
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = JSON.parse(text);
|
|
46
|
+
} catch {
|
|
47
|
+
throw new CliError(program, `${program} ${argv.join(" ")} did not print JSON: ${text.slice(0, 200)}`, text, "");
|
|
48
|
+
}
|
|
49
|
+
if (parsed && typeof parsed === "object" && "ok" in parsed && parsed.ok === false) {
|
|
50
|
+
const error = parsed.error;
|
|
51
|
+
throw new CliError(program, `${program} ${argv.join(" ")}: ${error?.message ?? "failed"}`, text, "");
|
|
52
|
+
}
|
|
53
|
+
if (parsed && typeof parsed === "object" && "code" in parsed && "data" in parsed) return parsed.data;
|
|
54
|
+
return parsed;
|
|
55
|
+
}
|
|
56
|
+
// src/prompts.ts
|
|
57
|
+
/**
|
|
58
|
+
* The prompt a ticket's agent receives.
|
|
59
|
+
*
|
|
60
|
+
* It is assembled here rather than read from files so that an installation has one thing to read: `settings.yaml`. The
|
|
61
|
+
* team-editable part is `prompts.instructions`, which the operator writes in their own words.
|
|
62
|
+
*/
|
|
63
|
+
/**
|
|
64
|
+
* The rules that hold for every ticket, one file each beside this one.
|
|
65
|
+
*
|
|
66
|
+
* They were files in the DSH bundle, where an operator edited them in the panel; here the text is part of the install,
|
|
67
|
+
* so it is read from the file next to the source rather than copied into this module.
|
|
68
|
+
*/
|
|
69
|
+
const STANDING_FILES = ["scope.md", "delivery.md"];
|
|
70
|
+
const STANDING_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "prompts");
|
|
71
|
+
async function standingRules() {
|
|
72
|
+
return Promise.all(STANDING_FILES.map(async (name) => (await readFile(join(STANDING_DIR, name), "utf8")).trim()));
|
|
73
|
+
}
|
|
74
|
+
/** Composes the prompt for one ticket: who asked, what they asked, and what the agent must not assume. */
|
|
75
|
+
function composePrompt(input) {
|
|
76
|
+
const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch, standing = [], notes = [] } = input;
|
|
77
|
+
const asked = trigger ? `A person wrote this in ${trigger.url ?? trigger.channel?.thread ?? "the source conversation"}:\n\n${quote(trigger.text)}` : `The ticket has no source message; work on the title alone:\n\n${quote(ticket.title)}`;
|
|
78
|
+
return [
|
|
79
|
+
`# Ticket ${ticket.id}`,
|
|
80
|
+
"",
|
|
81
|
+
...source === "feishu" ? [`You work on the repository \`${repository}\`. The request came from a chat, which has no branch of its own, so open your`, "pull request from a new branch and say in your report where the person can find it."] : [`You work on the repository \`${repository}\`. Your GitHub account is \`${agentLogin}\`; every GitHub action you take is`, "visible to the team under that name."],
|
|
82
|
+
"",
|
|
83
|
+
"## The request",
|
|
84
|
+
"",
|
|
85
|
+
asked,
|
|
86
|
+
...notes.filter(Boolean).flatMap((note) => [
|
|
87
|
+
"",
|
|
88
|
+
"## Notes since the start",
|
|
89
|
+
"",
|
|
90
|
+
quote(note)
|
|
91
|
+
]),
|
|
92
|
+
"",
|
|
93
|
+
"## How to work",
|
|
94
|
+
"",
|
|
95
|
+
`- Work only in this directory. It is a worktree of the repository on a new branch.`,
|
|
96
|
+
branch ? `- Commit on the branch \`${branch}\`, which this directory is already on, and open a pull request from it when done.` : `- Put your branch under \`${branchPrefix}\` followed by a short name, and open a pull request from it when done.`,
|
|
97
|
+
"- Run the tests the repository has. Do not claim a check passed unless you ran it.",
|
|
98
|
+
"- Do not merge the pull request. A person merges it.",
|
|
99
|
+
"- If the request needs a decision you cannot make, stop and ask one concrete question.",
|
|
100
|
+
...standing.filter(Boolean).flatMap((rule) => ["", rule]),
|
|
101
|
+
...instructions.trim() ? [
|
|
102
|
+
"",
|
|
103
|
+
"## Team instructions",
|
|
104
|
+
"",
|
|
105
|
+
instructions.trim()
|
|
106
|
+
] : [],
|
|
107
|
+
reportInstructions()
|
|
108
|
+
].join("\n");
|
|
109
|
+
}
|
|
110
|
+
/** Indents a person's message so the agent reads it as quoted material, not as instructions to this prompt. */
|
|
111
|
+
function quote(text) {
|
|
112
|
+
return (text.trim() || "(empty message)").split("\n").map((line) => `> ${line}`).join("\n");
|
|
113
|
+
}
|
|
114
|
+
// src/policy.ts
|
|
115
|
+
/**
|
|
116
|
+
* How an installation decides who may start work: an explicit request from a listed person, or an owner's unaddressed
|
|
117
|
+
* message that an assessment matches to an enabled rule.
|
|
118
|
+
*
|
|
119
|
+
* The admission table is kept whole here rather than simplified to "listed and addressed": a message that carries no
|
|
120
|
+
* request is still worth assessing when the owner wrote it in a chat the Source reads, because many real requests are a
|
|
121
|
+
* suggestion, not an order. `policy.mode` decides whether such a candidate is accepted (`auto`), only recorded
|
|
122
|
+
* (`observe`), or dropped before an assessment (`off`).
|
|
123
|
+
*/
|
|
124
|
+
/** Which sources this installation's Sources read, and whether they read every message in that scope. */
|
|
125
|
+
function sourceScope(settings) {
|
|
126
|
+
return { scope: (input) => {
|
|
127
|
+
if (input.source === "feishu") {
|
|
128
|
+
if (!settings.feishu?.enabled) return {
|
|
129
|
+
listened: false,
|
|
130
|
+
reason: "sourceOff"
|
|
131
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
listened: true,
|
|
134
|
+
observed: true
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (input.source !== "github") return {
|
|
138
|
+
listened: false,
|
|
139
|
+
reason: "unsupported"
|
|
140
|
+
};
|
|
141
|
+
if (!settings.github?.enabled) return {
|
|
142
|
+
listened: false,
|
|
143
|
+
reason: "sourceOff"
|
|
144
|
+
};
|
|
145
|
+
const repository = input.meta.repository ?? settings.github.repository;
|
|
146
|
+
if (!repository) return {
|
|
147
|
+
listened: false,
|
|
148
|
+
reason: "unsupported"
|
|
149
|
+
};
|
|
150
|
+
if (repository.toLowerCase() !== settings.github.repository.toLowerCase()) return {
|
|
151
|
+
listened: false,
|
|
152
|
+
reason: "otherRepository"
|
|
153
|
+
};
|
|
154
|
+
return {
|
|
155
|
+
listened: true,
|
|
156
|
+
observed: false
|
|
157
|
+
};
|
|
158
|
+
} };
|
|
159
|
+
}
|
|
160
|
+
/** The rule a person's unaddressed chat message must match before its candidate may be accepted. */
|
|
161
|
+
const UNASKED_RULE = "unasked";
|
|
162
|
+
/** The Policy of one settings file, rebuilt whenever the round reads it. */
|
|
163
|
+
function buildPolicy(settings, scope) {
|
|
164
|
+
const people = (source) => new Set((source === "feishu" ? settings.feishu?.allowed : settings.github?.allowed)?.map((id) => id.toLowerCase()) ?? []);
|
|
165
|
+
return {
|
|
166
|
+
version: `${settings.policy.mode}:${settings.policy.rules.filter((rule) => rule.enabled).map((rule) => rule.id).join(",")}`,
|
|
167
|
+
paused: false,
|
|
168
|
+
evalTimeoutMs: 12e4,
|
|
169
|
+
gate: (trigger, _thread, _tickets, received) => {
|
|
170
|
+
if (!trigger.human) return {
|
|
171
|
+
admissible: false,
|
|
172
|
+
reason: "bot"
|
|
173
|
+
};
|
|
174
|
+
const allowed = people(trigger.source).has(trigger.actor.id.toLowerCase());
|
|
175
|
+
const seen = received ?? scope.scope(trigger);
|
|
176
|
+
const observed = seen.listened && seen.observed;
|
|
177
|
+
const addressed = !!trigger.addressed;
|
|
178
|
+
const basis = addressed ? {
|
|
179
|
+
via: "listed",
|
|
180
|
+
addressed: trigger.addressed
|
|
181
|
+
} : {
|
|
182
|
+
via: "admission",
|
|
183
|
+
cell: "listedUnaddressed"
|
|
184
|
+
};
|
|
185
|
+
if (allowed && addressed) return {
|
|
186
|
+
admissible: true,
|
|
187
|
+
strength: "explicit",
|
|
188
|
+
basis
|
|
189
|
+
};
|
|
190
|
+
if (allowed && observed && settings.policy.mode !== "off") return {
|
|
191
|
+
admissible: true,
|
|
192
|
+
strength: "inferred",
|
|
193
|
+
basis
|
|
194
|
+
};
|
|
195
|
+
return {
|
|
196
|
+
admissible: false,
|
|
197
|
+
reason: allowed ? "notAddressed" : "notAllowed"
|
|
198
|
+
};
|
|
199
|
+
},
|
|
200
|
+
revalidate: () => true,
|
|
201
|
+
admitsInferred: (rules) => settings.policy.mode === "auto" && rules.length > 0 && rules.every((id) => settings.policy.rules.some((rule) => rule.enabled && rule.id === id))
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The decision an assessment reaches, as a Validation: an accepted candidate needs the `unasked` rule, then one verdict
|
|
206
|
+
* for every enabled rule. `observe` records what `auto` would accept as an ignored Decision, so a person can read the
|
|
207
|
+
* judgements before any of them starts work.
|
|
208
|
+
*/
|
|
209
|
+
function assessmentOutcome(assessment, settings, strength) {
|
|
210
|
+
const enabled = settings.policy.rules.filter((rule) => rule.enabled);
|
|
211
|
+
const judged = new Map(assessment.rule_assessments.map((item) => [item.rule_id, item]));
|
|
212
|
+
const missing = enabled.filter((rule) => !judged.has(rule.id));
|
|
213
|
+
if (missing.length) throw new Error(`No verdict for the rule(s) ${missing.map((rule) => rule.id).join(", ")}`);
|
|
214
|
+
const matches = enabled.filter((rule) => judged.get(rule.id).matched).map((rule) => rule.id);
|
|
215
|
+
const audit = {
|
|
216
|
+
rule_assessments: assessment.rule_assessments,
|
|
217
|
+
direction: assessment.direction,
|
|
218
|
+
intent_evidence: assessment.intent_evidence
|
|
219
|
+
};
|
|
220
|
+
if (assessment.decision !== "accept") return {
|
|
221
|
+
kind: assessment.decision,
|
|
222
|
+
reason: assessment.reason,
|
|
223
|
+
audit
|
|
224
|
+
};
|
|
225
|
+
if (!matches.length) return {
|
|
226
|
+
kind: "ignore",
|
|
227
|
+
audit,
|
|
228
|
+
reason: "No enabled rule matches this message"
|
|
229
|
+
};
|
|
230
|
+
if (!directionAllowed(assessment.direction)) return {
|
|
231
|
+
kind: "ignore",
|
|
232
|
+
audit,
|
|
233
|
+
reason: assessment.intent_evidence ? "The direction is not settled" : "The assessment gives no evidence of intent"
|
|
234
|
+
};
|
|
235
|
+
if (strength === "inferred" && !matches.includes("unasked")) return {
|
|
236
|
+
kind: "ignore",
|
|
237
|
+
audit,
|
|
238
|
+
reason: "The message does not ask for work; only the unasked rule can accept one"
|
|
239
|
+
};
|
|
240
|
+
const accept = {
|
|
241
|
+
kind: "accept",
|
|
242
|
+
title: assessment.title,
|
|
243
|
+
scope: assessment.scope,
|
|
244
|
+
reason: assessment.reason,
|
|
245
|
+
rules: matches,
|
|
246
|
+
audit,
|
|
247
|
+
...assessment.acknowledgement ? { acknowledgement: assessment.acknowledgement } : {}
|
|
248
|
+
};
|
|
249
|
+
if (strength === "inferred" && settings.policy.mode !== "auto") return {
|
|
250
|
+
kind: "ignore",
|
|
251
|
+
reason: `Observe mode: would accept "${assessment.title}"`,
|
|
252
|
+
audit: {
|
|
253
|
+
...audit,
|
|
254
|
+
would_accept: true,
|
|
255
|
+
proposal: accept
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
return accept;
|
|
259
|
+
}
|
|
260
|
+
// src/assess.ts
|
|
261
|
+
/**
|
|
262
|
+
* The assessment of a candidate a person did not address to the agent.
|
|
263
|
+
*
|
|
264
|
+
* One model call reads the messages in a Thread and the enabled rules, and answers one verdict per rule plus a direction:
|
|
265
|
+
* whether a change was asked for, at a target or standard that already exists. The model never decides authority; the
|
|
266
|
+
* Policy and the engine's `admitsInferred` do. A failed or malformed answer ends the assessment as `unavailable`, which a
|
|
267
|
+
* person can see and re-run, rather than as a quiet ignore.
|
|
268
|
+
*/
|
|
269
|
+
/** The JSON the assessor must print. */
|
|
270
|
+
const AssessmentSchema = z.object({
|
|
271
|
+
decision: z.enum([
|
|
272
|
+
"accept",
|
|
273
|
+
"ignore",
|
|
274
|
+
"unavailable"
|
|
275
|
+
]),
|
|
276
|
+
rule_assessments: z.array(RuleAssessmentSchema),
|
|
277
|
+
direction: z.unknown(),
|
|
278
|
+
title: z.string().max(80).nullish().transform((value) => value ?? ""),
|
|
279
|
+
scope: z.string().max(500).nullish().transform((value) => value ?? ""),
|
|
280
|
+
reason: z.string().max(500).nullish().transform((value) => value ?? ""),
|
|
281
|
+
intent_evidence: z.string().max(700).nullable().default(null),
|
|
282
|
+
acknowledgement: z.string().max(200).nullable().default(null)
|
|
283
|
+
});
|
|
284
|
+
/** The talk in a Thread, oldest first, each message cut so the prompt stays bounded. */
|
|
285
|
+
function conversation(thread, triggers, limit = 12) {
|
|
286
|
+
return triggers.slice(-limit).map((trigger) => {
|
|
287
|
+
const text = trigger.text.replace(/\s+/g, " ").trim().slice(0, 1500);
|
|
288
|
+
const who = trigger.human ? trigger.actor.id : "a bot";
|
|
289
|
+
const mark = trigger.addressed ? " (addressed the agent)" : "";
|
|
290
|
+
return `- [${trigger.id}] ${who}${mark} at ${trigger.at}: ${text}`;
|
|
291
|
+
}).join("\n");
|
|
292
|
+
}
|
|
293
|
+
/** The prompt one assessment reads: the rules it must judge, then the discussion. */
|
|
294
|
+
function assessmentPrompt(candidate, settings) {
|
|
295
|
+
const enabled = settings.policy.rules.filter((rule) => rule.enabled);
|
|
296
|
+
return [
|
|
297
|
+
`# A message in a chat the agent reads, not addressed to it`,
|
|
298
|
+
"",
|
|
299
|
+
"Decide whether it asks for work. You do not do the work and you do not change anything.",
|
|
300
|
+
"",
|
|
301
|
+
"## Rules",
|
|
302
|
+
"",
|
|
303
|
+
...[
|
|
304
|
+
`- \`${UNASKED_RULE}\` (The request): the discussion asks for a concrete change to this project, with a target or an`,
|
|
305
|
+
" existing standard to change it towards, and no open design decision. A preference, a hypothetical or a discussion of",
|
|
306
|
+
" another product does not match.",
|
|
307
|
+
...enabled.map((rule) => `- \`${rule.id}\` (${rule.name}): ${rule.instruction}`)
|
|
308
|
+
],
|
|
309
|
+
"",
|
|
310
|
+
"## The discussion",
|
|
311
|
+
"",
|
|
312
|
+
conversation(candidate.thread, candidate.triggers),
|
|
313
|
+
"",
|
|
314
|
+
"## Answer",
|
|
315
|
+
"",
|
|
316
|
+
"Print one JSON object and nothing else:",
|
|
317
|
+
"",
|
|
318
|
+
"```json",
|
|
319
|
+
"{\"decision\": \"accept\" | \"ignore\" | \"unavailable\",",
|
|
320
|
+
" \"rule_assessments\": [{\"rule_id\": \"<id>\", \"matched\": true, \"reason\": \"<one sentence, factual>\"}, ...],",
|
|
321
|
+
" \"direction\": {\"implementation_requested\": true, \"target_basis\": \"specified\" | \"existing-standard\" | \"undetermined\",",
|
|
322
|
+
" \"requires_design_decision\": false, \"evidence\": \"<the words that establish it>\"},",
|
|
323
|
+
" \"title\": \"<a short name for the work, when accepting>\",",
|
|
324
|
+
" \"scope\": \"<what changes, in one sentence>\",",
|
|
325
|
+
" \"reason\": \"<one sentence for a person reading the decision>\",",
|
|
326
|
+
" \"intent_evidence\": \"<the quotation that shows the request>\",",
|
|
327
|
+
" \"acknowledgement\": null}",
|
|
328
|
+
"```",
|
|
329
|
+
"",
|
|
330
|
+
"- Include exactly one `rule_assessments` entry for every rule above, matched or not.",
|
|
331
|
+
"- `accept` only when the discussion asks for a change the rules allow; otherwise `ignore`.",
|
|
332
|
+
"- `unavailable` only when the discussion is unreadable."
|
|
333
|
+
].join("\n");
|
|
334
|
+
}
|
|
335
|
+
/** Reads the JSON object out of what the model printed, tolerating a fenced block or surrounding prose. */
|
|
336
|
+
function parseAssessment(text) {
|
|
337
|
+
const start = text.indexOf("{");
|
|
338
|
+
const end = text.lastIndexOf("}");
|
|
339
|
+
if (start < 0 || end <= start) throw new Error("The assessment printed no JSON object");
|
|
340
|
+
const parsed = AssessmentSchema.parse(JSON.parse(text.slice(start, end + 1)));
|
|
341
|
+
if (parsed.decision === "accept" && !directionAllowed(parsed.direction)) throw new Error("The assessment accepts without a settled direction");
|
|
342
|
+
return parsed;
|
|
343
|
+
}
|
|
344
|
+
/** A model call that judges one candidate, once per Eval: the engine asks once, and a replay of the same trigger comes as a new Eval. */
|
|
345
|
+
function claudeAssessor(settings) {
|
|
346
|
+
return async (candidate) => {
|
|
347
|
+
const { agent, binary, model } = settings.assess;
|
|
348
|
+
if (agent !== "claude") throw new Error(`The assessor runs on claude; settings.assess.agent is ${agent}`);
|
|
349
|
+
const env = Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== void 0));
|
|
350
|
+
const result = await runProcess(binary ?? "claude", [
|
|
351
|
+
"-p",
|
|
352
|
+
"--output-format",
|
|
353
|
+
"json",
|
|
354
|
+
...model ? ["--model", model] : []
|
|
355
|
+
], {
|
|
356
|
+
cwd: settings.checkout,
|
|
357
|
+
env,
|
|
358
|
+
stdin: assessmentPrompt(candidate, settings),
|
|
359
|
+
signal: AbortSignal.timeout(12e4),
|
|
360
|
+
timeoutMs: 12e4
|
|
361
|
+
});
|
|
362
|
+
if (result.exitCode !== 0) throw new Error(`The assessor exited ${result.exitCode}: ${result.stderr.slice(-500)}`);
|
|
363
|
+
const envelope = JSON.parse(result.stdout);
|
|
364
|
+
if (envelope.is_error) throw new Error(`The assessor failed: ${envelope.result ?? ""}`.slice(0, 500));
|
|
365
|
+
return parseAssessment(envelope.result ?? "");
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
// src/assessing.ts
|
|
369
|
+
/** The name an addressed request gives its ticket: its first line without the mentions, short enough for a branch. */
|
|
370
|
+
function named(candidate) {
|
|
371
|
+
return { title: (candidate.triggers[0]?.text ?? "").split("\n")[0].replace(/@[\w-]+/g, "").trim().slice(0, 60) || "Request" };
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* The Assessor a loop installs: it judges each candidate in one model call, in flight beside the rounds.
|
|
375
|
+
*
|
|
376
|
+
* The call is asynchronous so a slow assessment never holds up a Source. Its outcome is a decision the loop makes: the
|
|
377
|
+
* loop keeps one Engine across rounds, and a command run from this callback would see a Thread the round in flight is in
|
|
378
|
+
* the middle of changing. A verdict for an Eval that ended meanwhile is dropped, and its requeued Triggers get a fresh one.
|
|
379
|
+
*/
|
|
380
|
+
function assessing(options) {
|
|
381
|
+
const running = /* @__PURE__ */ new Map();
|
|
382
|
+
return {
|
|
383
|
+
request(candidate) {
|
|
384
|
+
running.set(candidate.evalId, candidate);
|
|
385
|
+
const explicit = candidate.strength === "explicit";
|
|
386
|
+
(async () => {
|
|
387
|
+
let outcome;
|
|
388
|
+
try {
|
|
389
|
+
const settings = options.settings();
|
|
390
|
+
outcome = explicit ? {
|
|
391
|
+
kind: "accept",
|
|
392
|
+
...named(candidate),
|
|
393
|
+
scope: "",
|
|
394
|
+
reason: "A person addressed the agent"
|
|
395
|
+
} : assessmentOutcome(await options.next(candidate), settings, candidate.strength);
|
|
396
|
+
if (!explicit && outcome.kind === "accept" && !settings.policy.rules.some((rule) => rule.id === "unasked")) outcome = {
|
|
397
|
+
kind: "ignore",
|
|
398
|
+
reason: "The assessment accepts, but no `unasked` rule is enabled"
|
|
399
|
+
};
|
|
400
|
+
} catch (error) {
|
|
401
|
+
outcome = {
|
|
402
|
+
kind: "unavailable",
|
|
403
|
+
reason: `The assessment could not run: ${error.message}`
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
if (!running.has(candidate.evalId)) return;
|
|
407
|
+
running.delete(candidate.evalId);
|
|
408
|
+
const triggerId = candidate.triggers[0]?.id;
|
|
409
|
+
if (triggerId) options.decided.push({
|
|
410
|
+
triggerId,
|
|
411
|
+
outcome: {
|
|
412
|
+
...outcome,
|
|
413
|
+
evalId: candidate.evalId
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
})().catch((error) => {
|
|
417
|
+
options.log(`The assessment of ${candidate.evalId} failed: ${error.message}`);
|
|
418
|
+
});
|
|
419
|
+
},
|
|
420
|
+
release(evalId) {
|
|
421
|
+
running.delete(evalId);
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
// src/sources/github.ts
|
|
426
|
+
/**
|
|
427
|
+
* The GitHub Source: turns new mentions and new Issues in one repository into Triggers.
|
|
428
|
+
*
|
|
429
|
+
* GitHub delivers a mention to the agent's own account as a notification, so the poll reads notifications rather than
|
|
430
|
+
* every Issue in the repository. The alternative — scanning the repository — costs a request per Issue and reports
|
|
431
|
+
* mentions the agent may never have been able to answer.
|
|
432
|
+
*
|
|
433
|
+
* A notification only says that something mentioned the account. The comment itself is read afterwards, so the Trigger
|
|
434
|
+
* carries what the person wrote, not the notification's summary.
|
|
435
|
+
*/
|
|
436
|
+
const SOURCE$1 = "github";
|
|
437
|
+
/** A thread identifier for an Issue or pull request number; both share one sequence in GitHub. */
|
|
438
|
+
const githubThread = (number) => ({
|
|
439
|
+
source: SOURCE$1,
|
|
440
|
+
id: String(number)
|
|
441
|
+
});
|
|
442
|
+
/** Where a reply to this number goes. */
|
|
443
|
+
const githubChannel = (repository, number, url) => ({
|
|
444
|
+
source: SOURCE$1,
|
|
445
|
+
thread: threadKey(githubThread(number)),
|
|
446
|
+
address: {
|
|
447
|
+
number: String(number),
|
|
448
|
+
repository,
|
|
449
|
+
...url ? { url } : {}
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
const githubPage = (repository, number, pr = false) => `https://github.com/${repository}/${pr ? "pull" : "issues"}/${number}`;
|
|
453
|
+
/** Whether `text` mentions `login` as a whole name rather than as a prefix of a longer one. */
|
|
454
|
+
const mentions = (text, login) => new RegExp(`(?:^|[^a-zA-Z0-9_@])@${escapeRegExp(login)}(?![a-zA-Z0-9_-])`, "i").test(text);
|
|
455
|
+
/** True for an account GitHub reports as an ordinary user; a login ending in `[bot]` or an App is not one. */
|
|
456
|
+
const isHumanLogin = (user) => !/\[bot\]$/.test(user.login) && (!user.type || user.type === "User");
|
|
457
|
+
const UserSchema = z.looseObject({
|
|
458
|
+
login: z.string(),
|
|
459
|
+
type: z.string().nullish()
|
|
460
|
+
}).nullish().transform((user) => user ?? {
|
|
461
|
+
login: "ghost",
|
|
462
|
+
type: null
|
|
463
|
+
});
|
|
464
|
+
z.looseObject({
|
|
465
|
+
id: z.string(),
|
|
466
|
+
reason: z.string(),
|
|
467
|
+
updated_at: z.string(),
|
|
468
|
+
subject: z.looseObject({
|
|
469
|
+
title: z.string(),
|
|
470
|
+
url: z.string().nullish(),
|
|
471
|
+
type: z.string(),
|
|
472
|
+
latest_comment_url: z.string().nullish()
|
|
473
|
+
}),
|
|
474
|
+
repository: z.looseObject({
|
|
475
|
+
full_name: z.string(),
|
|
476
|
+
owner: z.looseObject({ login: z.string() }).nullish()
|
|
477
|
+
}).nullish()
|
|
478
|
+
});
|
|
479
|
+
z.looseObject({
|
|
480
|
+
id: z.number().nullish(),
|
|
481
|
+
body: z.string().nullish(),
|
|
482
|
+
user: UserSchema,
|
|
483
|
+
html_url: z.string().nullish(),
|
|
484
|
+
created_at: z.string().nullish(),
|
|
485
|
+
updated_at: z.string().nullish(),
|
|
486
|
+
submitted_at: z.string().nullish(),
|
|
487
|
+
state: z.string().nullish()
|
|
488
|
+
});
|
|
489
|
+
/** Pulls `owner/repo#number` out of a notification subject URL, for the repository the Source watches. */
|
|
490
|
+
function notificationNumber(notification) {
|
|
491
|
+
const match = /\/(?:issues|pulls)\/(\d+)\/?$/.exec(notification.subject.url ?? "");
|
|
492
|
+
if (!match) return void 0;
|
|
493
|
+
return {
|
|
494
|
+
number: Number(match[1]),
|
|
495
|
+
pr: notification.subject.type === "PullRequest"
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
/** Reads the comment a notification points at; a notification without a comment URL is a new Issue, which has none. */
|
|
499
|
+
async function notificationComment(notification, cli, repository) {
|
|
500
|
+
const url = notification.subject.latest_comment_url;
|
|
501
|
+
if (!url) return void 0;
|
|
502
|
+
if (!url.includes(`/api.github.com/repos/${repository}/`)) return void 0;
|
|
503
|
+
const path = url.replace(/^https:\/\/api\.github\.com\//, "");
|
|
504
|
+
try {
|
|
505
|
+
return await runJson(cli, ["api", path]);
|
|
506
|
+
} catch {
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/** Builds a Trigger for a decision to accept or ignore a comment. `kind` names whether it sits on an Issue, a PR or a review. */
|
|
511
|
+
function commentTrigger(input) {
|
|
512
|
+
const { repository, number, pr, comment, agent, kind } = input;
|
|
513
|
+
const at = comment.updated_at ?? comment.submitted_at ?? comment.created_at ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
514
|
+
const text = [comment.state && comment.state !== "COMMENTED" ? `${comment.state} review` : "", comment.body ?? ""].filter(Boolean).join("\n\n");
|
|
515
|
+
const url = comment.html_url ?? githubPage(repository, number, pr);
|
|
516
|
+
const login = comment.user.login;
|
|
517
|
+
return {
|
|
518
|
+
id: key("github-comment", url, String(comment.id ?? ""), at),
|
|
519
|
+
source: SOURCE$1,
|
|
520
|
+
threads: [githubThread(number)],
|
|
521
|
+
actor: {
|
|
522
|
+
source: SOURCE$1,
|
|
523
|
+
id: login
|
|
524
|
+
},
|
|
525
|
+
human: isHumanLogin(comment.user) && !sameName(login, agent),
|
|
526
|
+
...mentions(comment.body ?? "", agent) ? { addressed: "mention" } : {},
|
|
527
|
+
at,
|
|
528
|
+
text,
|
|
529
|
+
channel: githubChannel(repository, number, url),
|
|
530
|
+
url,
|
|
531
|
+
meta: {
|
|
532
|
+
number,
|
|
533
|
+
isPr: pr,
|
|
534
|
+
repository,
|
|
535
|
+
commentId: comment.id ?? null,
|
|
536
|
+
kind
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
/** The name a CLI reports for the account it acts as, which the Trigger builder uses to tell the agent's own messages apart. */
|
|
541
|
+
async function agentLogin(cli, signal) {
|
|
542
|
+
return (await runJson(cli, ["api", "user"], { signal })).login;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Polls one round of notifications for `repository` and returns the Triggers it has not seen.
|
|
546
|
+
* `since` is the ISO time of the previous round, or the moment the Source first ran.
|
|
547
|
+
*/
|
|
548
|
+
async function pollNotifications(input) {
|
|
549
|
+
const notifications = await runJson(input.cli, ["api", `notifications?all=false&participating=false&since=${encodeURIComponent(input.since)}`], { signal: input.signal });
|
|
550
|
+
const triggers = [];
|
|
551
|
+
for (const notification of notifications) {
|
|
552
|
+
if (!sameName(notification.repository?.full_name ?? "", input.repository)) continue;
|
|
553
|
+
if (!/mention|assign|review_requested|comment/.test(notification.reason)) continue;
|
|
554
|
+
if (input.seen(notification.id)) continue;
|
|
555
|
+
const place = notificationNumber(notification);
|
|
556
|
+
if (!place) {
|
|
557
|
+
input.mark(notification.id);
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
const comment = await notificationComment(notification, input.cli, input.repository);
|
|
561
|
+
if (!comment) {
|
|
562
|
+
input.mark(notification.id);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (sameName(comment.user.login, input.agent)) {
|
|
566
|
+
input.mark(notification.id);
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (!mentions(comment.body ?? "", input.agent)) {
|
|
570
|
+
input.mark(notification.id);
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
triggers.push(commentTrigger({
|
|
574
|
+
repository: input.repository,
|
|
575
|
+
number: place.number,
|
|
576
|
+
pr: place.pr,
|
|
577
|
+
comment,
|
|
578
|
+
agent: input.agent,
|
|
579
|
+
kind: "conversation"
|
|
580
|
+
}));
|
|
581
|
+
input.mark(notification.id);
|
|
582
|
+
}
|
|
583
|
+
return triggers;
|
|
584
|
+
}
|
|
585
|
+
// src/sources/feishu.ts
|
|
586
|
+
/**
|
|
587
|
+
* The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
|
|
588
|
+
*
|
|
589
|
+
* Feishu pushes events, so the Source reads the bot's long-lived event stream rather than polling. That stream is one
|
|
590
|
+
* process (`lark-cli event consume`); `consumeEvents` runs it and hands each message to a callback.
|
|
591
|
+
*
|
|
592
|
+
* A chat is listened to only when `settings.feishu.chats` names it, because a bot in a busy chat sees everything and a
|
|
593
|
+
* Trigger per message would cost the team attention for nothing.
|
|
594
|
+
*/
|
|
595
|
+
const SOURCE = "feishu";
|
|
596
|
+
/** The event the Feishu bot subscribes to: a message sent to it or in a chat it is in. The key is generated by Feishu for
|
|
597
|
+
* the app's event subscription, so read it from `lark-cli event list` rather than assume it. */
|
|
598
|
+
const MESSAGE_EVENT = "im.message.receive_v1";
|
|
599
|
+
const feishuThread = (chatId, rootId, messageId) => ({
|
|
600
|
+
source: SOURCE,
|
|
601
|
+
id: `${chatId}:${rootId ?? messageId}`
|
|
602
|
+
});
|
|
603
|
+
/** Where a reply to this message goes; `direct` is explicit because group and direct chat ids both start with `oc_`. */
|
|
604
|
+
const feishuChannel = (chatId, messageId, direct = false) => ({
|
|
605
|
+
source: SOURCE,
|
|
606
|
+
thread: `feishu:${chatId}`,
|
|
607
|
+
address: {
|
|
608
|
+
chatId,
|
|
609
|
+
messageId,
|
|
610
|
+
...direct ? { direct: "true" } : {}
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
/** One message as the event stream prints it. */
|
|
614
|
+
const EventSchema = z.object({
|
|
615
|
+
message_id: z.string(),
|
|
616
|
+
chat_id: z.string(),
|
|
617
|
+
chat_type: z.enum(["p2p", "group"]),
|
|
618
|
+
sender_id: z.string().optional(),
|
|
619
|
+
sender_type: z.enum(["user", "bot"]).optional(),
|
|
620
|
+
sender: z.object({
|
|
621
|
+
sender_id: z.string(),
|
|
622
|
+
sender_type: z.enum(["user", "bot"])
|
|
623
|
+
}).optional(),
|
|
624
|
+
content: z.string(),
|
|
625
|
+
create_time: z.string(),
|
|
626
|
+
mentions: z.array(z.object({
|
|
627
|
+
id: z.string(),
|
|
628
|
+
key: z.string().optional(),
|
|
629
|
+
name: z.string().optional()
|
|
630
|
+
})).default([]),
|
|
631
|
+
root_id: z.string().optional(),
|
|
632
|
+
parent_id: z.string().optional(),
|
|
633
|
+
message_app_link: z.string().optional()
|
|
634
|
+
});
|
|
635
|
+
/** Feishu sends epoch milliseconds as a string for live events; anything else is passed to `Date`. */
|
|
636
|
+
function feishuTime(value) {
|
|
637
|
+
const time = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
|
|
638
|
+
if (!Number.isFinite(time)) throw new Error(`Unreadable Feishu message time: ${value}`);
|
|
639
|
+
return new Date(time).toISOString();
|
|
640
|
+
}
|
|
641
|
+
/** Replaces Feishu's mention placeholders with the names a reader expects, so the agent sees "@bot fix this". */
|
|
642
|
+
function withMentionNames(text, mentions) {
|
|
643
|
+
return mentions.reduce((result, mention) => mention.key && mention.name ? result.replaceAll(mention.key, `@${mention.name}`) : result, text);
|
|
644
|
+
}
|
|
645
|
+
/** Builds a Trigger for one message, or `undefined` when the bot wrote it or the chat is not listened to. */
|
|
646
|
+
function feishuTrigger(input, options) {
|
|
647
|
+
const parsed = EventSchema.safeParse(input);
|
|
648
|
+
if (!parsed.success) {
|
|
649
|
+
options.onInvalid?.(parsed.error.message);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
const event = parsed.data;
|
|
653
|
+
const { botId, botAppId, chats, directMessages } = options;
|
|
654
|
+
const senderId = event.sender_id ?? event.sender?.sender_id ?? "";
|
|
655
|
+
const senderType = event.sender_type ?? event.sender?.sender_type ?? "user";
|
|
656
|
+
if (senderId === botId || senderId === botAppId) return void 0;
|
|
657
|
+
const direct = event.chat_type === "p2p";
|
|
658
|
+
if (direct ? !directMessages : !chats.has(event.chat_id)) return void 0;
|
|
659
|
+
const mentioned = event.mentions.some((mention) => !botId || mention.id === botId || mention.id === botAppId);
|
|
660
|
+
if (!direct && !mentioned) return void 0;
|
|
661
|
+
const url = event.message_app_link;
|
|
662
|
+
return {
|
|
663
|
+
id: key("feishu", event.message_id),
|
|
664
|
+
source: SOURCE,
|
|
665
|
+
threads: [feishuThread(event.chat_id, event.root_id, event.message_id)],
|
|
666
|
+
actor: {
|
|
667
|
+
source: SOURCE,
|
|
668
|
+
id: senderId
|
|
669
|
+
},
|
|
670
|
+
human: senderType === "user",
|
|
671
|
+
...direct ? { addressed: "direct" } : { addressed: "mention" },
|
|
672
|
+
at: feishuTime(event.create_time),
|
|
673
|
+
text: withMentionNames(event.content, event.mentions),
|
|
674
|
+
channel: feishuChannel(event.chat_id, event.message_id, direct),
|
|
675
|
+
...url ? { url } : {},
|
|
676
|
+
meta: {
|
|
677
|
+
chatId: event.chat_id,
|
|
678
|
+
messageId: event.message_id,
|
|
679
|
+
direct,
|
|
680
|
+
mentioned,
|
|
681
|
+
...event.root_id ? { rootId: event.root_id } : {}
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* The bot's own ids, which the Source needs to recognise a mention and to skip its own messages.
|
|
687
|
+
*
|
|
688
|
+
* The open id comes from one listened chat, because a bot that is in no chat reports none. A stream-only bot can still
|
|
689
|
+
* receive direct messages, so a chat it cannot read is not an error.
|
|
690
|
+
*/
|
|
691
|
+
async function botIdentity(cli, chatIds, signal) {
|
|
692
|
+
const status = await runJson(cli, ["config", "show"], { signal });
|
|
693
|
+
for (const chatId of chatIds) try {
|
|
694
|
+
const botId = (await runJson(cli, [
|
|
695
|
+
"im",
|
|
696
|
+
"chat.members",
|
|
697
|
+
"bots",
|
|
698
|
+
"--params",
|
|
699
|
+
JSON.stringify({ chat_id: chatId })
|
|
700
|
+
], { signal })).bots?.find((bot) => bot.bot_id)?.bot_id;
|
|
701
|
+
if (botId) return {
|
|
702
|
+
appId: status.appId,
|
|
703
|
+
botId
|
|
704
|
+
};
|
|
705
|
+
} catch {}
|
|
706
|
+
return {
|
|
707
|
+
appId: status.appId,
|
|
708
|
+
botId: ""
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
/** The members of a chat, which fill the allow list when `settings.feishu.syncChat` names it. */
|
|
712
|
+
async function chatMembers(cli, chatId, signal) {
|
|
713
|
+
return ((await runJson(cli, [
|
|
714
|
+
"im",
|
|
715
|
+
"+chat-members-list",
|
|
716
|
+
"--chat-id",
|
|
717
|
+
chatId,
|
|
718
|
+
"--member-types",
|
|
719
|
+
"user",
|
|
720
|
+
"--page-all",
|
|
721
|
+
"--page-limit",
|
|
722
|
+
"0"
|
|
723
|
+
], { signal })).users ?? []).map((user) => ({
|
|
724
|
+
id: user.member_id,
|
|
725
|
+
name: user.name ?? user.member_id
|
|
726
|
+
}));
|
|
727
|
+
}
|
|
728
|
+
/** Posts a reply in the thread of `messageId`, which is where the person who asked is reading. */
|
|
729
|
+
async function reply(cli, messageId, text, idempotencyKey, signal) {
|
|
730
|
+
await run(cli, [
|
|
731
|
+
"im",
|
|
732
|
+
"+messages-reply",
|
|
733
|
+
"--message-id",
|
|
734
|
+
messageId,
|
|
735
|
+
"--markdown",
|
|
736
|
+
text,
|
|
737
|
+
"--reply-in-thread",
|
|
738
|
+
"--idempotency-key",
|
|
739
|
+
idempotencyKey
|
|
740
|
+
], { signal });
|
|
741
|
+
}
|
|
742
|
+
/** A small JSON reader for the event stream, which tolerates what other commands print before or between events. */
|
|
743
|
+
var EventReader = class {
|
|
744
|
+
rest = "";
|
|
745
|
+
read;
|
|
746
|
+
failed;
|
|
747
|
+
constructor(read, failed) {
|
|
748
|
+
this.read = read;
|
|
749
|
+
this.failed = failed;
|
|
750
|
+
}
|
|
751
|
+
/** Hands every complete line in `chunk` to the reader, and keeps the rest until the next chunk completes it. */
|
|
752
|
+
push(chunk) {
|
|
753
|
+
this.rest += chunk;
|
|
754
|
+
const lines = this.rest.split("\n");
|
|
755
|
+
this.rest = lines.pop();
|
|
756
|
+
for (const line of lines) if (line.trim()) this.line(line);
|
|
757
|
+
}
|
|
758
|
+
/** Reads what is left when the stream ends. */
|
|
759
|
+
flush() {
|
|
760
|
+
const line = this.rest.trim();
|
|
761
|
+
this.rest = "";
|
|
762
|
+
if (line) this.line(line);
|
|
763
|
+
}
|
|
764
|
+
line(line) {
|
|
765
|
+
try {
|
|
766
|
+
const value = JSON.parse(line);
|
|
767
|
+
if (value && typeof value === "object" && !Array.isArray(value)) this.read(line);
|
|
768
|
+
} catch {
|
|
769
|
+
this.failed(line);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
/** How long a stop leaves the consumer to end on its own before it is killed. */
|
|
774
|
+
const STOP_GRACE_MS = 1e3;
|
|
775
|
+
/**
|
|
776
|
+
* Runs `lark-cli event consume` and hands every message to `onMessage`.
|
|
777
|
+
*
|
|
778
|
+
* The child exits when its stdin closes, so this keeps stdin open for the life of the run and closes it to stop. The
|
|
779
|
+
* consumer also refuses to start while another process holds the app's event connection, which is why one installation
|
|
780
|
+
* should use its own Feishu app.
|
|
781
|
+
*
|
|
782
|
+
* The reader collects whole lines only and hands each to `onMessage` as it reads it. A round waits on `next`, which is
|
|
783
|
+
* settled in the same tick as a line is handed over, so no line is lost between the wait and the read; a line that
|
|
784
|
+
* arrives with the close answers one last `next`, and after the close `next` is false at once.
|
|
785
|
+
*/
|
|
786
|
+
function consumeEvents(options) {
|
|
787
|
+
const failed = (line) => {
|
|
788
|
+
options.onError(`Unreadable event: ${line.slice(0, 200)}`);
|
|
789
|
+
};
|
|
790
|
+
let linesRead = 0;
|
|
791
|
+
const reader = new EventReader((line) => {
|
|
792
|
+
options.onMessage(JSON.parse(line));
|
|
793
|
+
linesRead++;
|
|
794
|
+
}, failed);
|
|
795
|
+
let waiting;
|
|
796
|
+
let closing = false;
|
|
797
|
+
let finished = false;
|
|
798
|
+
const unwait = () => {
|
|
799
|
+
const waiter = waiting;
|
|
800
|
+
if (!waiter) return;
|
|
801
|
+
clearTimeout(waiter.timer);
|
|
802
|
+
waiting = void 0;
|
|
803
|
+
waiter.resolve(true);
|
|
804
|
+
};
|
|
805
|
+
const next = (ms) => {
|
|
806
|
+
if (closing || finished) return Promise.resolve(false);
|
|
807
|
+
if (linesRead) {
|
|
808
|
+
linesRead = 0;
|
|
809
|
+
return Promise.resolve(true);
|
|
810
|
+
}
|
|
811
|
+
return new Promise((resolve) => {
|
|
812
|
+
waiting = {
|
|
813
|
+
resolve,
|
|
814
|
+
timer: setTimeout(() => {
|
|
815
|
+
waiting = void 0;
|
|
816
|
+
resolve(false);
|
|
817
|
+
}, ms)
|
|
818
|
+
};
|
|
819
|
+
});
|
|
820
|
+
};
|
|
821
|
+
let child;
|
|
822
|
+
let settled;
|
|
823
|
+
const ended = new Promise((resolve) => {
|
|
824
|
+
settled = resolve;
|
|
825
|
+
});
|
|
826
|
+
const stop = () => {
|
|
827
|
+
if (!child || finished) return;
|
|
828
|
+
if (!child.stdin.destroyed) child.stdin.end();
|
|
829
|
+
setTimeout(() => {
|
|
830
|
+
finished = true;
|
|
831
|
+
child.kill("SIGTERM");
|
|
832
|
+
unwait();
|
|
833
|
+
settled();
|
|
834
|
+
}, STOP_GRACE_MS).unref();
|
|
835
|
+
};
|
|
836
|
+
child = spawn(options.cli, [
|
|
837
|
+
"event",
|
|
838
|
+
"consume",
|
|
839
|
+
MESSAGE_EVENT,
|
|
840
|
+
"--as",
|
|
841
|
+
"bot"
|
|
842
|
+
], {
|
|
843
|
+
stdio: [
|
|
844
|
+
"pipe",
|
|
845
|
+
"pipe",
|
|
846
|
+
"pipe"
|
|
847
|
+
],
|
|
848
|
+
env: {
|
|
849
|
+
...process.env,
|
|
850
|
+
LARKSUITE_CLI_NO_UPDATE_NOTIFIER: "1",
|
|
851
|
+
LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
|
|
852
|
+
}
|
|
853
|
+
});
|
|
854
|
+
child.stdout.on("data", (chunk) => {
|
|
855
|
+
reader.push(chunk.toString());
|
|
856
|
+
unwait();
|
|
857
|
+
});
|
|
858
|
+
child.stderr.on("data", (chunk) => {
|
|
859
|
+
for (const line of chunk.toString().split("\n")) if (/WARN|error/i.test(line)) options.onError(line.slice(0, 400));
|
|
860
|
+
});
|
|
861
|
+
child.on("spawn", () => {
|
|
862
|
+
if (options.signal.aborted) stop();
|
|
863
|
+
else options.onListening?.({
|
|
864
|
+
next,
|
|
865
|
+
stop,
|
|
866
|
+
ended
|
|
867
|
+
});
|
|
868
|
+
});
|
|
869
|
+
child.on("error", (error) => {
|
|
870
|
+
if (!finished) options.onError(String(error));
|
|
871
|
+
finished = true;
|
|
872
|
+
unwait();
|
|
873
|
+
settled();
|
|
874
|
+
});
|
|
875
|
+
child.on("close", (code) => {
|
|
876
|
+
options.onEnded?.();
|
|
877
|
+
if (!finished) {
|
|
878
|
+
reader.flush();
|
|
879
|
+
if (code !== 0) options.onError(`The event consumer exited with code ${code}`);
|
|
880
|
+
}
|
|
881
|
+
finished = true;
|
|
882
|
+
closing = true;
|
|
883
|
+
unwait();
|
|
884
|
+
settled();
|
|
885
|
+
});
|
|
886
|
+
options.signal.addEventListener("abort", stop, { once: true });
|
|
887
|
+
if (options.signal.aborted) stop();
|
|
888
|
+
return {
|
|
889
|
+
next,
|
|
890
|
+
stop,
|
|
891
|
+
ended
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
// src/infra/worktree.ts
|
|
895
|
+
/**
|
|
896
|
+
* Gives a ticket its own git worktree and branch, so two tickets can change one repository at once and neither sees the
|
|
897
|
+
* other's half-finished edits.
|
|
898
|
+
*
|
|
899
|
+
* A worktree rather than a clone: it shares the checkout's object store, so it costs a directory and nothing else. The
|
|
900
|
+
* worktree lives under `stateDir/work/<ticket>`, which is also where the agent's run log goes.
|
|
901
|
+
*
|
|
902
|
+
* A checkout that is not a git repository gets a plain directory instead. That keeps `superagent run` and installations
|
|
903
|
+
* that watch nothing but a chat working.
|
|
904
|
+
*/
|
|
905
|
+
/** A short, git-safe branch name for a ticket: a slug of its title, made unique by the ticket's id. */
|
|
906
|
+
function ticketBranch(prefix, title, id) {
|
|
907
|
+
return `${prefix}${title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40).replace(/-$/, "") || "request"}-${id.slice(-6)}`;
|
|
908
|
+
}
|
|
909
|
+
/** Whether `directory` is inside a git work tree. */
|
|
910
|
+
async function isGitRepository(directory) {
|
|
911
|
+
try {
|
|
912
|
+
await access(join(directory, ".git"));
|
|
913
|
+
return true;
|
|
914
|
+
} catch {}
|
|
915
|
+
try {
|
|
916
|
+
await run("git", [
|
|
917
|
+
"-C",
|
|
918
|
+
directory,
|
|
919
|
+
"rev-parse",
|
|
920
|
+
"--is-inside-work-tree"
|
|
921
|
+
], { timeoutMs: 1e4 });
|
|
922
|
+
return true;
|
|
923
|
+
} catch {
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Creates the worktree for a ticket and returns its directory.
|
|
929
|
+
*
|
|
930
|
+
* @throws when git cannot create the worktree, such as when the checkout has no commit yet; the caller then reports the
|
|
931
|
+
* ticket as failed instead of starting an agent in a directory that is not the repository.
|
|
932
|
+
*/
|
|
933
|
+
async function prepareWorktree(options) {
|
|
934
|
+
const { checkout, directory, branch, signal } = options;
|
|
935
|
+
await mkdir(directory, { recursive: true });
|
|
936
|
+
if ((await readdir(directory)).length) return directory;
|
|
937
|
+
if (!await isGitRepository(checkout)) return directory;
|
|
938
|
+
await run("git", [
|
|
939
|
+
"-C",
|
|
940
|
+
checkout,
|
|
941
|
+
"worktree",
|
|
942
|
+
"add",
|
|
943
|
+
"-b",
|
|
944
|
+
branch,
|
|
945
|
+
directory,
|
|
946
|
+
(await run("git", [
|
|
947
|
+
"-C",
|
|
948
|
+
checkout,
|
|
949
|
+
"rev-parse",
|
|
950
|
+
"HEAD"
|
|
951
|
+
], {
|
|
952
|
+
signal,
|
|
953
|
+
timeoutMs: 1e4
|
|
954
|
+
})).trim()
|
|
955
|
+
], {
|
|
956
|
+
signal,
|
|
957
|
+
timeoutMs: 12e4
|
|
958
|
+
}).catch(async (error) => {
|
|
959
|
+
await removeWorktree(checkout, directory, signal);
|
|
960
|
+
throw new Error(`${directory} is not a branch point: ${error.message}`, { cause: error });
|
|
961
|
+
});
|
|
962
|
+
return directory;
|
|
963
|
+
}
|
|
964
|
+
/** Removes a ticket's worktree once its ticket ended, so the state directory does not grow without bound. */
|
|
965
|
+
async function removeWorktree(checkout, directory, signal) {
|
|
966
|
+
try {
|
|
967
|
+
await run("git", [
|
|
968
|
+
"-C",
|
|
969
|
+
checkout,
|
|
970
|
+
"worktree",
|
|
971
|
+
"remove",
|
|
972
|
+
"--force",
|
|
973
|
+
directory
|
|
974
|
+
], {
|
|
975
|
+
signal,
|
|
976
|
+
timeoutMs: 12e4
|
|
977
|
+
});
|
|
978
|
+
} catch {}
|
|
979
|
+
}
|
|
980
|
+
// src/runner.ts
|
|
981
|
+
/** How long a reply in a conversation may be: a person reads it on a phone, and the evidence belongs in the pull request. */
|
|
982
|
+
const REPLY_MAX = 200;
|
|
983
|
+
/** The first sentence of a report summary, short enough to send; the record keeps every word. */
|
|
984
|
+
function deliverable(summary) {
|
|
985
|
+
const one = summary.replace(/\s+/g, " ").trim();
|
|
986
|
+
const text = ((one.split(/(?<=[.!?])\s|(?<=[\u3002\uff01\uff1f])/)[0] ?? "") || one).replace(/[\s.!?\u3002\uff01\uff1f]+$/, "");
|
|
987
|
+
return text.length > REPLY_MAX ? `${text.slice(0, 199).trimEnd()}…` : text || "The work is done.";
|
|
988
|
+
}
|
|
989
|
+
function deliver(engine, repo, delivered, log) {
|
|
990
|
+
for (const ticket of repo.tickets.list()) {
|
|
991
|
+
const report = latestReport(ticket);
|
|
992
|
+
if (!ticket.ended || report?.state !== "ready" || delivered.has(`${ticket.id}@${report.at}`)) continue;
|
|
993
|
+
delivered.add(`${ticket.id}@${report.at}`);
|
|
994
|
+
const text = deliverable(String(report.summary));
|
|
995
|
+
try {
|
|
996
|
+
engine.reply({
|
|
997
|
+
purpose: "result",
|
|
998
|
+
ticketId: ticket.id,
|
|
999
|
+
text
|
|
1000
|
+
});
|
|
1001
|
+
log(`Answered ticket ${ticket.id} in its conversation`);
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
log(`Could not answer ticket ${ticket.id}: ${error.message}`);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
/** Holds outcomes that arrive while no round is listening, and wakes a round to record them. */
|
|
1008
|
+
var WorkQueue = class {
|
|
1009
|
+
items = [];
|
|
1010
|
+
waiter;
|
|
1011
|
+
/** An outcome that arrived; it is kept even with no round waiting, so one that outlives its round is still recorded. */
|
|
1012
|
+
push(item) {
|
|
1013
|
+
this.items.push(item);
|
|
1014
|
+
this.wake();
|
|
1015
|
+
}
|
|
1016
|
+
/** What arrived since the last drain. */
|
|
1017
|
+
drain() {
|
|
1018
|
+
return this.items.splice(0);
|
|
1019
|
+
}
|
|
1020
|
+
/** Whether an outcome waits to be recorded. */
|
|
1021
|
+
ready() {
|
|
1022
|
+
return this.items.length > 0;
|
|
1023
|
+
}
|
|
1024
|
+
/** Settles when an outcome arrives, or when `ms` passes. */
|
|
1025
|
+
wait(ms) {
|
|
1026
|
+
if (this.items.length) return Promise.resolve();
|
|
1027
|
+
return new Promise((resolve) => {
|
|
1028
|
+
const finish = () => {
|
|
1029
|
+
clearTimeout(timer);
|
|
1030
|
+
this.waiter = void 0;
|
|
1031
|
+
resolve();
|
|
1032
|
+
};
|
|
1033
|
+
const timer = setTimeout(finish, ms);
|
|
1034
|
+
this.waiter = finish;
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
wake() {
|
|
1038
|
+
this.waiter?.();
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
/** How long one round waits for an outcome before the next round; one that arrives is recorded at once, not several rounds later. */
|
|
1042
|
+
const TURN_WAIT_MS = 1e3;
|
|
1043
|
+
/** Records the assessments that finished as Decisions; one the Engine refuses is logged, not thrown. */
|
|
1044
|
+
function decide(engine, decided, log) {
|
|
1045
|
+
for (const { triggerId, outcome } of decided) try {
|
|
1046
|
+
const made = engine.decide(triggerId, outcome);
|
|
1047
|
+
log(`Decided ${triggerId}: ${made.kind}${made.ticketId ? `, ticket ${made.ticketId}` : ""}${made.reason?.length ? ` — ${JSON.stringify(made.reason)}` : ""}`);
|
|
1048
|
+
} catch (error) {
|
|
1049
|
+
log(`Could not decide ${triggerId}: ${error.message}`);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/** Records the turns that finished, so a ticket ends without the loop holding work in memory; a refused report is logged, not thrown. */
|
|
1053
|
+
function record(engine, repo, finished, log) {
|
|
1054
|
+
for (const item of finished) try {
|
|
1055
|
+
const latest = repo.tickets.get(item.ticketId);
|
|
1056
|
+
if (latest) engine.updateTicket(latest);
|
|
1057
|
+
engine.report(item.ticketId, {
|
|
1058
|
+
state: item.report.state,
|
|
1059
|
+
summary: item.report.summary,
|
|
1060
|
+
...item.report.question ? { question: item.report.question } : {}
|
|
1061
|
+
});
|
|
1062
|
+
} catch (error) {
|
|
1063
|
+
log(`Could not record the report for ${item.ticketId}: ${error.message}`);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
/** Posts the messages the Engine queued, one comment per message. */
|
|
1067
|
+
async function send(channel, clis, log) {
|
|
1068
|
+
for (const message of channel.drain()) {
|
|
1069
|
+
if (message.channel.source === "feishu") {
|
|
1070
|
+
const address = message.channel.address;
|
|
1071
|
+
if (!clis.feishu) {
|
|
1072
|
+
log(`Cannot answer in ${address.chatId}: the Feishu Source is off`);
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
try {
|
|
1076
|
+
await reply(clis.feishu, address.messageId, message.text, message.id);
|
|
1077
|
+
log(`Answered in ${address.chatId}`);
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
log(`Could not answer in ${address.chatId}: ${error.message}`);
|
|
1080
|
+
}
|
|
1081
|
+
continue;
|
|
1082
|
+
}
|
|
1083
|
+
const address = message.channel.address;
|
|
1084
|
+
if (!address.number || !address.repository) continue;
|
|
1085
|
+
if (!clis.github) {
|
|
1086
|
+
log(`Cannot post on ${address.repository}#${address.number}: the GitHub Source is off`);
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
try {
|
|
1090
|
+
await run(clis.github, [
|
|
1091
|
+
"api",
|
|
1092
|
+
`repos/${address.repository}/issues/${address.number}/comments`,
|
|
1093
|
+
"-f",
|
|
1094
|
+
`body=${message.text}`
|
|
1095
|
+
]);
|
|
1096
|
+
log(`Posted a message on ${address.repository}#${address.number}`);
|
|
1097
|
+
} catch (error) {
|
|
1098
|
+
log(`Could not post on ${address.repository}#${address.number}: ${error.message}`);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
/** Where the loop keeps its own bookkeeping, beside the domain state. */
|
|
1103
|
+
const pollKey = "github:poll";
|
|
1104
|
+
const seenKey = (id) => `github:seen:${id}`;
|
|
1105
|
+
/** Lines one round reads from the stream at most, so a chat that keeps talking does not hold a round open. */
|
|
1106
|
+
const MAX_LINES = 500;
|
|
1107
|
+
/** A failed save of the last round must not stop the next one. */
|
|
1108
|
+
function outbox() {
|
|
1109
|
+
const messages = /* @__PURE__ */ new Map();
|
|
1110
|
+
return {
|
|
1111
|
+
send: (message) => {
|
|
1112
|
+
if (!messages.has(message.id)) messages.set(message.id, message);
|
|
1113
|
+
},
|
|
1114
|
+
status: (id) => messages.has(id) ? "pending" : void 0,
|
|
1115
|
+
withdraw: (id) => {
|
|
1116
|
+
messages.delete(id);
|
|
1117
|
+
},
|
|
1118
|
+
/** Everything queued so far, for the caller to deliver in order. */
|
|
1119
|
+
drain: () => [...messages.values()].sort((a, b) => a.id.localeCompare(b.id))
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
/**
|
|
1123
|
+
* Runs a ticket on the configured agent.
|
|
1124
|
+
*
|
|
1125
|
+
* The Engine calls `start` and expects a report through its own callbacks; this keeps the work asynchronous, so the loop
|
|
1126
|
+
* never blocks on an agent turn.
|
|
1127
|
+
*/
|
|
1128
|
+
var AgentExecutor = class {
|
|
1129
|
+
options;
|
|
1130
|
+
active = /* @__PURE__ */ new Map();
|
|
1131
|
+
/** Tickets whose turn waits for a free slot, oldest first. */
|
|
1132
|
+
pending = [];
|
|
1133
|
+
pumping = false;
|
|
1134
|
+
constructor(options) {
|
|
1135
|
+
this.options = options;
|
|
1136
|
+
}
|
|
1137
|
+
start(ticket, assignment) {
|
|
1138
|
+
const { site } = this.options;
|
|
1139
|
+
site.started(ticket.id, assignment.id);
|
|
1140
|
+
this.pending.push({
|
|
1141
|
+
ticket,
|
|
1142
|
+
assignment
|
|
1143
|
+
});
|
|
1144
|
+
this.pump();
|
|
1145
|
+
}
|
|
1146
|
+
deliver() {}
|
|
1147
|
+
/**
|
|
1148
|
+
* Takes in the tickets a previous process left running. Their agents ended with that process, so a turn that had not
|
|
1149
|
+
* reported is restarted with a recovery note, and one whose report a person still has to act on goes back to the queue
|
|
1150
|
+
* with its inputs. A start from `interrupted` joins the same queue as a new ticket.
|
|
1151
|
+
*/
|
|
1152
|
+
recover(open) {
|
|
1153
|
+
for (const ticket of open) {
|
|
1154
|
+
const assignment = runningAssignment(ticket);
|
|
1155
|
+
if (assignment) this.options.site.interrupted(ticket.id, assignment.id);
|
|
1156
|
+
}
|
|
1157
|
+
for (const ticket of open) for (const assignment of ticket.assignments) if (assignment.state === "pending") this.pending.push({
|
|
1158
|
+
ticket,
|
|
1159
|
+
assignment
|
|
1160
|
+
});
|
|
1161
|
+
this.pump();
|
|
1162
|
+
}
|
|
1163
|
+
/** The Engine's memory of the ticket, so the report lands on a ticket that already holds this round's changes to it. */
|
|
1164
|
+
refresh(ticket) {
|
|
1165
|
+
this.options.engine.updateTicket(ticket);
|
|
1166
|
+
}
|
|
1167
|
+
stop(ticket) {
|
|
1168
|
+
this.active.get(ticket.id)?.abort();
|
|
1169
|
+
this.active.delete(ticket.id);
|
|
1170
|
+
const waiting = this.pending.findIndex((item) => item.ticket.id === ticket.id);
|
|
1171
|
+
if (waiting >= 0) this.pending.splice(waiting, 1);
|
|
1172
|
+
this.pump();
|
|
1173
|
+
}
|
|
1174
|
+
/** Starts waiting tickets while a slot is free; the turns run beside the rounds, so this never blocks on one. */
|
|
1175
|
+
pump() {
|
|
1176
|
+
if (this.pumping) return;
|
|
1177
|
+
this.pumping = true;
|
|
1178
|
+
Promise.resolve().then(() => {
|
|
1179
|
+
this.pumping = false;
|
|
1180
|
+
while (this.active.size < this.options.maxWorkers && this.pending.length) {
|
|
1181
|
+
const item = this.pending.shift();
|
|
1182
|
+
const controller = new AbortController();
|
|
1183
|
+
this.active.set(item.ticket.id, controller);
|
|
1184
|
+
this.execute(item.ticket, item.assignment, controller);
|
|
1185
|
+
}
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
async execute(ticket, assignment, controller) {
|
|
1189
|
+
const { settings, runner, stateDir, accounts, feishuCli, site } = this.options;
|
|
1190
|
+
const directory = ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
|
|
1191
|
+
try {
|
|
1192
|
+
const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
|
|
1193
|
+
await prepareWorktree({
|
|
1194
|
+
checkout: settings.checkout,
|
|
1195
|
+
directory,
|
|
1196
|
+
branch,
|
|
1197
|
+
signal: controller.signal
|
|
1198
|
+
});
|
|
1199
|
+
if (settings.executor.prepare) await run("/bin/sh", ["-c", settings.executor.prepare], {
|
|
1200
|
+
env: this.variables(ticket, directory, branch),
|
|
1201
|
+
timeoutMs: 12e4
|
|
1202
|
+
});
|
|
1203
|
+
const prompt = await this.options.prompt(ticket, directory, branch);
|
|
1204
|
+
const result = await runner.run({
|
|
1205
|
+
prompt,
|
|
1206
|
+
cwd: directory,
|
|
1207
|
+
env: runEnvironment(feishuCli ? {
|
|
1208
|
+
...accounts,
|
|
1209
|
+
feishuCli
|
|
1210
|
+
} : accounts, this.variables(ticket, directory, branch)),
|
|
1211
|
+
signal: controller.signal,
|
|
1212
|
+
timeoutMs: settings.executor.timeoutMinutes * 6e4,
|
|
1213
|
+
model: settings.executor.model
|
|
1214
|
+
});
|
|
1215
|
+
const report = result.report ?? inferReport(result.finalText, result.ok);
|
|
1216
|
+
await appendLog(directory, prompt, result.raw.slice(-2e4), report);
|
|
1217
|
+
site.reported(ticket.id, {
|
|
1218
|
+
state: report.state ?? (result.ok ? "ready" : "failed"),
|
|
1219
|
+
summary: report.summary,
|
|
1220
|
+
question: report.question ?? null
|
|
1221
|
+
});
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
site.failed(ticket.id, assignment.id, `The agent could not run: ${error.message}`);
|
|
1224
|
+
} finally {
|
|
1225
|
+
this.active.delete(ticket.id);
|
|
1226
|
+
this.pump();
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
variables(ticket, directory, branch) {
|
|
1230
|
+
const trigger = ticket.origin;
|
|
1231
|
+
return {
|
|
1232
|
+
SUPERAGENT_TICKET: ticket.id,
|
|
1233
|
+
SUPERAGENT_DIR: directory,
|
|
1234
|
+
SUPERAGENT_BRANCH: branch,
|
|
1235
|
+
SUPERAGENT_REPOSITORY: this.options.repository,
|
|
1236
|
+
SUPERAGENT_TRIGGER: trigger.triggerId,
|
|
1237
|
+
DSH_SUPERAGENT_DIR: directory,
|
|
1238
|
+
DSH_SUPERAGENT_TICKET: ticket.id,
|
|
1239
|
+
DSH_SUPERAGENT_GITHUB_REPOSITORY: this.options.repository
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
/** Turns an agent that wrote no report into one the Engine can still act on. */
|
|
1244
|
+
function inferReport(text, ok) {
|
|
1245
|
+
return {
|
|
1246
|
+
summary: text.trim().split("\n").filter(Boolean).at(-1)?.slice(0, 500) || (ok ? "The agent finished." : "The agent failed."),
|
|
1247
|
+
state: ok ? "ready" : "failed"
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
async function appendLog(directory, prompt, raw, report) {
|
|
1251
|
+
const path = join(directory, ".superagent", "log.md");
|
|
1252
|
+
const entry = [
|
|
1253
|
+
"",
|
|
1254
|
+
`## ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
1255
|
+
"",
|
|
1256
|
+
"**Prompt**",
|
|
1257
|
+
"",
|
|
1258
|
+
"```",
|
|
1259
|
+
prompt,
|
|
1260
|
+
"```",
|
|
1261
|
+
"",
|
|
1262
|
+
"**Report**",
|
|
1263
|
+
"",
|
|
1264
|
+
"```json",
|
|
1265
|
+
JSON.stringify(report, null, 2),
|
|
1266
|
+
"```",
|
|
1267
|
+
"",
|
|
1268
|
+
"**Agent output**",
|
|
1269
|
+
"",
|
|
1270
|
+
"```",
|
|
1271
|
+
raw,
|
|
1272
|
+
"```"
|
|
1273
|
+
].join("\n");
|
|
1274
|
+
await mkdir(join(directory, ".superagent"), { recursive: true }).then(() => appendFile(path, `${entry}\n`));
|
|
1275
|
+
}
|
|
1276
|
+
/**
|
|
1277
|
+
* The loop that makes an installation run without a person: poll the Sources, assess what they bring, and run the tickets
|
|
1278
|
+
* the assessment accepts.
|
|
1279
|
+
*
|
|
1280
|
+
* It is a plain async loop, not a daemon protocol: `runLoop` returns when its signal aborts, so a cron job, a shell script,
|
|
1281
|
+
* or a coding agent can each call it for one round with `--once`.
|
|
1282
|
+
*/
|
|
1283
|
+
/** Runs rounds until `signal` aborts; each round polls, assesses, and starts the tickets accepted. */
|
|
1284
|
+
async function runLoop(options) {
|
|
1285
|
+
const { settings, repo, signal: caller, log } = options;
|
|
1286
|
+
const stop = new AbortController();
|
|
1287
|
+
if (!options.once) caller.addEventListener("abort", () => stop.abort(), { once: true });
|
|
1288
|
+
const signal = stop.signal;
|
|
1289
|
+
const github = settings.github?.enabled ? settings.github : void 0;
|
|
1290
|
+
const feishu = settings.feishu?.enabled ? settings.feishu : void 0;
|
|
1291
|
+
if (!github && !feishu) throw new Error("No Source is on in settings.yaml; nothing to poll.");
|
|
1292
|
+
const login = github ? await agentLogin(github.cli, signal) : "";
|
|
1293
|
+
const accounts = {
|
|
1294
|
+
stateDir: settings.stateDir,
|
|
1295
|
+
githubCli: github?.cli ?? "gh",
|
|
1296
|
+
agentLogin: login
|
|
1297
|
+
};
|
|
1298
|
+
await writeEnvironment(accounts, settings.executor.blockedCommands);
|
|
1299
|
+
const standing = await standingRules();
|
|
1300
|
+
const channel = outbox();
|
|
1301
|
+
const scope = sourceScope(settings);
|
|
1302
|
+
const decided = new WorkQueue();
|
|
1303
|
+
const finished = new WorkQueue();
|
|
1304
|
+
const engine = new Engine({
|
|
1305
|
+
repo,
|
|
1306
|
+
policy: () => buildPolicy(settings, scope),
|
|
1307
|
+
scope,
|
|
1308
|
+
assessor: assessing({
|
|
1309
|
+
settings: () => settings,
|
|
1310
|
+
next: claudeAssessor(settings),
|
|
1311
|
+
decided,
|
|
1312
|
+
log
|
|
1313
|
+
}),
|
|
1314
|
+
executor: void 0,
|
|
1315
|
+
outbox: channel
|
|
1316
|
+
});
|
|
1317
|
+
const site = {
|
|
1318
|
+
started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
|
|
1319
|
+
reported: (ticketId, report) => {
|
|
1320
|
+
record(engine, repo, [{
|
|
1321
|
+
ticketId,
|
|
1322
|
+
report
|
|
1323
|
+
}], log);
|
|
1324
|
+
},
|
|
1325
|
+
failed: (ticketId, _assignmentId, summary) => {
|
|
1326
|
+
record(engine, repo, [{
|
|
1327
|
+
ticketId,
|
|
1328
|
+
report: {
|
|
1329
|
+
state: "failed",
|
|
1330
|
+
summary
|
|
1331
|
+
}
|
|
1332
|
+
}], log);
|
|
1333
|
+
},
|
|
1334
|
+
interrupted: (ticketId, assignmentId) => {
|
|
1335
|
+
try {
|
|
1336
|
+
engine.assignmentInterrupted(ticketId, assignmentId);
|
|
1337
|
+
} catch (error) {
|
|
1338
|
+
log(`Could not recover ${ticketId}: ${error.message}`);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
};
|
|
1342
|
+
const executor = new AgentExecutor({
|
|
1343
|
+
engine,
|
|
1344
|
+
settings,
|
|
1345
|
+
maxWorkers: settings.executor.maxWorkers,
|
|
1346
|
+
runner: runnerFor(settings.executor.agent, settings.executor.binary),
|
|
1347
|
+
stateDir: settings.stateDir,
|
|
1348
|
+
repository: github?.repository ?? settings.checkout,
|
|
1349
|
+
agent: login,
|
|
1350
|
+
accounts,
|
|
1351
|
+
...feishu ? { feishuCli: feishu.cli } : {},
|
|
1352
|
+
site,
|
|
1353
|
+
prompt: async (ticket, directory, branch) => {
|
|
1354
|
+
const trigger = repo.triggers.get(ticket.origin.triggerId);
|
|
1355
|
+
const source = trigger?.source === "feishu" ? "feishu" : "github";
|
|
1356
|
+
const notes = ticket.inputs.flatMap((input) => input.kind === "text" ? [input.text] : []);
|
|
1357
|
+
return composePrompt({
|
|
1358
|
+
ticket,
|
|
1359
|
+
trigger,
|
|
1360
|
+
repository: github?.repository ?? settings.checkout,
|
|
1361
|
+
agentLogin: login,
|
|
1362
|
+
branchPrefix: settings.branchPrefix,
|
|
1363
|
+
source,
|
|
1364
|
+
instructions: settings.prompts,
|
|
1365
|
+
branch,
|
|
1366
|
+
standing,
|
|
1367
|
+
notes
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
});
|
|
1371
|
+
const admitted = /* @__PURE__ */ new Set();
|
|
1372
|
+
const sync = () => !feishu?.syncChat ? Promise.resolve() : chatMembers(feishu.cli, feishu.syncChat, signal).then((members) => {
|
|
1373
|
+
const listed = feishu.allowed.map((id) => id.toLowerCase());
|
|
1374
|
+
const add = members.map((member) => member.id).filter((id) => !listed.includes(id.toLowerCase()) && !admitted.has(id.toLowerCase()));
|
|
1375
|
+
if (add.length) {
|
|
1376
|
+
feishu.allowed.push(...add);
|
|
1377
|
+
for (const id of add) admitted.add(id.toLowerCase());
|
|
1378
|
+
log(`Admitted ${add.length} member(s) of ${feishu.syncChat} from its chat`);
|
|
1379
|
+
}
|
|
1380
|
+
}).catch((error) => {
|
|
1381
|
+
if (!signal.aborted) log(`Could not read the members of ${feishu.syncChat}: ${error.message}`);
|
|
1382
|
+
});
|
|
1383
|
+
await sync();
|
|
1384
|
+
const chats = new Map((feishu?.chats ?? []).map((chat) => [chat.chatId, false]));
|
|
1385
|
+
let identity = Promise.resolve({
|
|
1386
|
+
appId: "",
|
|
1387
|
+
botId: ""
|
|
1388
|
+
});
|
|
1389
|
+
let read = false;
|
|
1390
|
+
const identify = () => {
|
|
1391
|
+
if (read) return;
|
|
1392
|
+
read = true;
|
|
1393
|
+
identity = botIdentity(feishu.cli, [.../* @__PURE__ */ new Set([...chats.keys(), ...feishu.syncChat ? [feishu.syncChat] : []])], signal).catch((error) => {
|
|
1394
|
+
if (!signal.aborted) log(`Could not read the bot's ids: ${error.message}`);
|
|
1395
|
+
return {
|
|
1396
|
+
appId: "",
|
|
1397
|
+
botId: ""
|
|
1398
|
+
};
|
|
1399
|
+
});
|
|
1400
|
+
};
|
|
1401
|
+
const store = (trigger) => {
|
|
1402
|
+
try {
|
|
1403
|
+
if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
|
|
1404
|
+
} catch (error) {
|
|
1405
|
+
log(`Could not store ${trigger.id}: ${error.message}`);
|
|
1406
|
+
}
|
|
1407
|
+
};
|
|
1408
|
+
const receive = (event) => {
|
|
1409
|
+
identity.then((bot) => feishuTrigger(event, {
|
|
1410
|
+
botAppId: bot.appId,
|
|
1411
|
+
botId: bot.botId,
|
|
1412
|
+
chats,
|
|
1413
|
+
directMessages: feishu?.directMessages ?? true,
|
|
1414
|
+
onInvalid: (error) => log(`Ignored an event: ${error}`)
|
|
1415
|
+
})).then((trigger) => {
|
|
1416
|
+
if (trigger) store(trigger);
|
|
1417
|
+
}).catch((error) => {
|
|
1418
|
+
log(`Could not store an event: ${error.message}`);
|
|
1419
|
+
});
|
|
1420
|
+
};
|
|
1421
|
+
let handle;
|
|
1422
|
+
const stopListening = new AbortController();
|
|
1423
|
+
if (options.once) caller.addEventListener("abort", () => stopListening.abort(), { once: true });
|
|
1424
|
+
if (feishu) handle = consumeEvents({
|
|
1425
|
+
cli: feishu.cli,
|
|
1426
|
+
signal: stopListening.signal,
|
|
1427
|
+
onMessage: receive,
|
|
1428
|
+
onListening: (started) => {
|
|
1429
|
+
handle = started;
|
|
1430
|
+
},
|
|
1431
|
+
...options.once ? {} : { onEnded: () => stopListening.abort() },
|
|
1432
|
+
onError: (message) => {
|
|
1433
|
+
if (!signal.aborted) log(message);
|
|
1434
|
+
}
|
|
1435
|
+
});
|
|
1436
|
+
/** Waits for the stream's next line: a line that arrives settles it, and a stream that answers nothing is idle. */
|
|
1437
|
+
const nextLine = () => handle ? handle.next(settings.executor.streamIdleMs) : Promise.resolve(false);
|
|
1438
|
+
const delivered = /* @__PURE__ */ new Set();
|
|
1439
|
+
engine.options.executor = executor;
|
|
1440
|
+
try {
|
|
1441
|
+
for (const ticket of repo.tickets.active()) engine.updateTicket(ticket);
|
|
1442
|
+
executor.recover(repo.tickets.active());
|
|
1443
|
+
} catch (error) {
|
|
1444
|
+
log(`Could not recover the tickets left running: ${error.message}`);
|
|
1445
|
+
}
|
|
1446
|
+
const inRound = /* @__PURE__ */ new Set();
|
|
1447
|
+
const ingest = () => {
|
|
1448
|
+
const waiting = repo.triggers.list().filter((trigger) => trigger.source === "feishu");
|
|
1449
|
+
for (const trigger of waiting) {
|
|
1450
|
+
inRound.add(trigger.id);
|
|
1451
|
+
engine.receive(trigger);
|
|
1452
|
+
}
|
|
1453
|
+
};
|
|
1454
|
+
let since = repo.getMeta(pollKey) ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1455
|
+
const pull = async () => {
|
|
1456
|
+
if (!feishu) return;
|
|
1457
|
+
for (let lines = 0; lines < MAX_LINES && !signal.aborted; lines++) if (!await nextLine()) break;
|
|
1458
|
+
if (signal.aborted) return;
|
|
1459
|
+
ingest();
|
|
1460
|
+
await repo.reload();
|
|
1461
|
+
};
|
|
1462
|
+
while (!signal.aborted) {
|
|
1463
|
+
const round = (/* @__PURE__ */ new Date()).toISOString();
|
|
1464
|
+
try {
|
|
1465
|
+
if (feishu) identify();
|
|
1466
|
+
ingest();
|
|
1467
|
+
await repo.reload();
|
|
1468
|
+
await pull();
|
|
1469
|
+
if (github) {
|
|
1470
|
+
const triggers = await pollNotifications({
|
|
1471
|
+
cli: github.cli,
|
|
1472
|
+
repository: github.repository,
|
|
1473
|
+
agent: login,
|
|
1474
|
+
since,
|
|
1475
|
+
signal,
|
|
1476
|
+
seen: (id) => repo.getMeta(seenKey(id)) === true,
|
|
1477
|
+
mark: (id) => repo.setMeta(seenKey(id), true)
|
|
1478
|
+
});
|
|
1479
|
+
for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
|
|
1480
|
+
since = round;
|
|
1481
|
+
repo.setMeta(pollKey, since);
|
|
1482
|
+
}
|
|
1483
|
+
engine.evaluateDue();
|
|
1484
|
+
decide(engine, decided.drain(), log);
|
|
1485
|
+
record(engine, repo, finished.drain(), log);
|
|
1486
|
+
await repo.flush();
|
|
1487
|
+
await pull();
|
|
1488
|
+
inRound.clear();
|
|
1489
|
+
deliver(engine, repo, delivered, log);
|
|
1490
|
+
await repo.flush();
|
|
1491
|
+
await send(channel, {
|
|
1492
|
+
...github ? { github: github.cli } : {},
|
|
1493
|
+
...feishu ? { feishu: feishu.cli } : {}
|
|
1494
|
+
}, log);
|
|
1495
|
+
await repo.flush();
|
|
1496
|
+
await sync();
|
|
1497
|
+
} catch (error) {
|
|
1498
|
+
if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
|
|
1499
|
+
}
|
|
1500
|
+
if (options.once) break;
|
|
1501
|
+
const seconds = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity);
|
|
1502
|
+
let left = options.once ? 0 : seconds * 1e3;
|
|
1503
|
+
while (left > 0 && !signal.aborted) {
|
|
1504
|
+
const began = Date.now();
|
|
1505
|
+
const wait = Math.max(1, Math.min(TURN_WAIT_MS, left));
|
|
1506
|
+
await Promise.race([Promise.race([finished.wait(wait), decided.wait(wait)]), new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
|
|
1507
|
+
if (finished.ready() || decided.ready()) break;
|
|
1508
|
+
left -= Date.now() - began;
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
stop.abort();
|
|
1512
|
+
if (options.once && !process.env.VITEST) setImmediate(() => process.exit(process.exitCode ?? 0));
|
|
1513
|
+
}
|
|
1514
|
+
// src/cli.ts
|
|
1515
|
+
/**
|
|
1516
|
+
* `superagent` command line: create an installation, inspect it, and run one ticket by hand.
|
|
1517
|
+
*
|
|
1518
|
+
* The command prints Markdown because people and agents both read it: an agent that needs to know what is open runs
|
|
1519
|
+
* `superagent status` and gets an answer it can put straight into a prompt.
|
|
1520
|
+
*/
|
|
1521
|
+
const USAGE = `superagent — an agent that turns GitHub and Feishu requests into tickets
|
|
1522
|
+
|
|
1523
|
+
superagent init [dir] create ${SETTINGS_FILE} and the state directory in dir (default: .)
|
|
1524
|
+
superagent status [dir] print open tickets and recent activity as Markdown
|
|
1525
|
+
superagent doctor [dir] show which coding agents are installed and which one is selected
|
|
1526
|
+
superagent agents list the coding agents a configuration may name
|
|
1527
|
+
superagent run <dir> -p <text> run one prompt on the configured agent, in a directory it names
|
|
1528
|
+
superagent poll [dir] [--once] poll the Sources and run the tickets they bring, once or until interrupted
|
|
1529
|
+
|
|
1530
|
+
Every command that reads an installation takes the directory that holds ${SETTINGS_FILE}.`;
|
|
1531
|
+
async function exists(path) {
|
|
1532
|
+
try {
|
|
1533
|
+
await stat(path);
|
|
1534
|
+
return true;
|
|
1535
|
+
} catch {
|
|
1536
|
+
return false;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
/** The state directory a settings file names, or the default when there is no settings file. */
|
|
1540
|
+
async function stateDirOf(dir) {
|
|
1541
|
+
try {
|
|
1542
|
+
return (await readSettings(join(dir, SETTINGS_FILE))).stateDir;
|
|
1543
|
+
} catch {
|
|
1544
|
+
return join(dir, "state");
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
async function init(dir) {
|
|
1548
|
+
const path = join(dir, SETTINGS_FILE);
|
|
1549
|
+
if (await exists(path)) {
|
|
1550
|
+
const current = await readSettings(path);
|
|
1551
|
+
await mkdir(current.stateDir, { recursive: true });
|
|
1552
|
+
await new FileRepositories(current.stateDir).open();
|
|
1553
|
+
process.stdout.write(`${path} already exists; kept its settings and state at ${current.stateDir}.\n`);
|
|
1554
|
+
return 0;
|
|
1555
|
+
}
|
|
1556
|
+
const settings = defaultSettings(resolve(dir), homedir());
|
|
1557
|
+
await writeSettings(path, settings);
|
|
1558
|
+
await mkdir(settings.stateDir, { recursive: true });
|
|
1559
|
+
await new FileRepositories(settings.stateDir).open();
|
|
1560
|
+
process.stdout.write([
|
|
1561
|
+
`Created ${path}.`,
|
|
1562
|
+
"",
|
|
1563
|
+
`State lives in ${settings.stateDir}.`,
|
|
1564
|
+
"",
|
|
1565
|
+
"Next: set `github.repository` and `github.allowed`, choose `executor.agent`, then run `superagent doctor`.",
|
|
1566
|
+
""
|
|
1567
|
+
].join("\n"));
|
|
1568
|
+
return 0;
|
|
1569
|
+
}
|
|
1570
|
+
async function status(dir) {
|
|
1571
|
+
const { tickets, threads, decisions, triggers: all, exists: found } = await readState(await stateDirOf(dir));
|
|
1572
|
+
const triggers = new Map(all.map((trigger) => [trigger.id, trigger]));
|
|
1573
|
+
if (!found) {
|
|
1574
|
+
process.stdout.write(`No state directory yet. Run \`superagent init\` first.\n`);
|
|
1575
|
+
return 1;
|
|
1576
|
+
}
|
|
1577
|
+
const open = tickets.filter((ticket) => ticket.ended === void 0);
|
|
1578
|
+
const done = tickets.filter((ticket) => ticket.ended !== void 0);
|
|
1579
|
+
const lines = [
|
|
1580
|
+
`# Superagent status`,
|
|
1581
|
+
"",
|
|
1582
|
+
`Open tickets: ${open.length} · Ended: ${done.length} · Threads: ${threads.length}`,
|
|
1583
|
+
""
|
|
1584
|
+
];
|
|
1585
|
+
if (open.length) {
|
|
1586
|
+
lines.push("## Open", "");
|
|
1587
|
+
for (const ticket of open) {
|
|
1588
|
+
const latest = ticket.assignments.at(-1);
|
|
1589
|
+
const state = latest ? latest.state : "no assignment";
|
|
1590
|
+
const question = ticket.attention ? ` — waiting on: ${ticket.attention.question}` : "";
|
|
1591
|
+
lines.push(`- \`${ticket.id}\` **${ticket.title}** (${state})${question}`);
|
|
1592
|
+
}
|
|
1593
|
+
lines.push("");
|
|
1594
|
+
}
|
|
1595
|
+
if (done.length) {
|
|
1596
|
+
lines.push("## Ended", "");
|
|
1597
|
+
for (const ticket of done.slice(-10)) lines.push(`- \`${ticket.id}\` ${ticket.title} — ${ticket.ended?.outcome} by ${ticket.ended?.by}`);
|
|
1598
|
+
lines.push("");
|
|
1599
|
+
}
|
|
1600
|
+
if (!tickets.length) lines.push("No tickets yet.", "");
|
|
1601
|
+
const judged = decisions.filter((decision) => decision.strength === "inferred").sort((a, b) => a.at.localeCompare(b.at)).slice(-10);
|
|
1602
|
+
if (judged.length) {
|
|
1603
|
+
lines.push("## Unaddressed messages", "");
|
|
1604
|
+
for (const decision of judged) {
|
|
1605
|
+
const message = decision.triggerIds.map((id) => triggers.get(id)?.text ?? "").join(" ");
|
|
1606
|
+
const what = decision.ticketId ? `ticket \`${decision.ticketId}\`` : decision.kind;
|
|
1607
|
+
lines.push(`- ${decision.at} **${what}** — ${reasonText(decision.reason)}${message ? ` — “${message.replace(/\s+/g, " ").slice(0, 80)}”` : ""}`);
|
|
1608
|
+
}
|
|
1609
|
+
lines.push("");
|
|
1610
|
+
}
|
|
1611
|
+
process.stdout.write(lines.join("\n"));
|
|
1612
|
+
return 0;
|
|
1613
|
+
}
|
|
1614
|
+
async function doctor(dir) {
|
|
1615
|
+
let settings;
|
|
1616
|
+
try {
|
|
1617
|
+
settings = await readSettings(join(dir, SETTINGS_FILE));
|
|
1618
|
+
} catch (error) {
|
|
1619
|
+
process.stderr.write(`${error.message}\n`);
|
|
1620
|
+
return 1;
|
|
1621
|
+
}
|
|
1622
|
+
const found = await installed();
|
|
1623
|
+
const lines = [
|
|
1624
|
+
"# Superagent doctor",
|
|
1625
|
+
"",
|
|
1626
|
+
"| Agent | Installed |",
|
|
1627
|
+
"| --- | --- |"
|
|
1628
|
+
];
|
|
1629
|
+
for (const name of AGENT_NAMES) lines.push(`| ${name} | ${found[name] ? "yes" : "no"} |`);
|
|
1630
|
+
const chosen = settings.executor.agent;
|
|
1631
|
+
lines.push("", `Selected: **${chosen}**${found[chosen] ? "" : " — not installed"}`, "");
|
|
1632
|
+
if (settings.github) lines.push(`Repository: \`${settings.github.repository}\`, allowed logins: ${settings.github.allowed.join(", ") || "(none)"}`, "");
|
|
1633
|
+
const stateFound = await exists(settings.stateDir);
|
|
1634
|
+
lines.push(`State directory: \`${settings.stateDir}\`${stateFound ? "" : " — missing, run `superagent init`"}`, "");
|
|
1635
|
+
process.stdout.write(lines.join("\n"));
|
|
1636
|
+
return found[chosen] ? 0 : 1;
|
|
1637
|
+
}
|
|
1638
|
+
/** Runs one prompt on the configured agent and prints the report, which is how a person tests an installation. */
|
|
1639
|
+
async function runOne(dir, prompt) {
|
|
1640
|
+
const settings = await readSettings(join(dir, SETTINGS_FILE));
|
|
1641
|
+
const runner = runnerFor(settings.executor.agent, settings.executor.binary);
|
|
1642
|
+
const controller = new AbortController();
|
|
1643
|
+
process.on("SIGINT", () => controller.abort());
|
|
1644
|
+
const result = await runner.run({
|
|
1645
|
+
prompt: `${prompt}\n${reportInstructions()}`,
|
|
1646
|
+
cwd: resolve(dir),
|
|
1647
|
+
env: { ...process.env },
|
|
1648
|
+
signal: controller.signal,
|
|
1649
|
+
timeoutMs: settings.executor.timeoutMinutes * 6e4
|
|
1650
|
+
});
|
|
1651
|
+
process.stdout.write(`${result.report?.summary ?? result.finalText}\n`);
|
|
1652
|
+
if (!result.ok) process.stderr.write(`The agent exited ${result.exitCode}.\n`);
|
|
1653
|
+
return result.ok ? 0 : 1;
|
|
1654
|
+
}
|
|
1655
|
+
/** Runs the loop for one round or until interrupted, holding the state directory's lock for the whole run. */
|
|
1656
|
+
async function poll(dir, once) {
|
|
1657
|
+
let settings;
|
|
1658
|
+
try {
|
|
1659
|
+
settings = await readSettings(join(dir, SETTINGS_FILE));
|
|
1660
|
+
} catch (error) {
|
|
1661
|
+
process.stderr.write(`${error.message}\n`);
|
|
1662
|
+
return 1;
|
|
1663
|
+
}
|
|
1664
|
+
const repo = new FileRepositories(settings.stateDir);
|
|
1665
|
+
await repo.open();
|
|
1666
|
+
const controller = new AbortController();
|
|
1667
|
+
process.on("SIGINT", () => controller.abort());
|
|
1668
|
+
const log = (line) => {
|
|
1669
|
+
process.stdout.write(`${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${line}\n`);
|
|
1670
|
+
};
|
|
1671
|
+
try {
|
|
1672
|
+
await runLoop({
|
|
1673
|
+
settings,
|
|
1674
|
+
repo,
|
|
1675
|
+
signal: controller.signal,
|
|
1676
|
+
log,
|
|
1677
|
+
...once ? { once: true } : {}
|
|
1678
|
+
});
|
|
1679
|
+
return 0;
|
|
1680
|
+
} catch (error) {
|
|
1681
|
+
process.stderr.write(`${error.message}\n`);
|
|
1682
|
+
return 1;
|
|
1683
|
+
} finally {
|
|
1684
|
+
await repo.flush();
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
async function main(argv) {
|
|
1688
|
+
const [command, ...rest] = argv;
|
|
1689
|
+
const dirOf = (index) => rest[index] && !rest[index].startsWith("-") ? resolve(rest[index]) : process.cwd();
|
|
1690
|
+
switch (command) {
|
|
1691
|
+
case "init": return init(rest[0] ? resolve(rest[0]) : process.cwd());
|
|
1692
|
+
case "status": return status(dirOf(0));
|
|
1693
|
+
case "doctor": return doctor(dirOf(0));
|
|
1694
|
+
case "agents":
|
|
1695
|
+
process.stdout.write(`${AGENT_NAMES.join("\n")}\n`);
|
|
1696
|
+
return 0;
|
|
1697
|
+
case "poll": return poll(dirOf(0), rest.includes("--once"));
|
|
1698
|
+
case "run": {
|
|
1699
|
+
const index = rest.indexOf("-p");
|
|
1700
|
+
if (index < 0 || !rest[index + 1]) {
|
|
1701
|
+
process.stderr.write(USAGE + "\n");
|
|
1702
|
+
return 2;
|
|
1703
|
+
}
|
|
1704
|
+
return runOne(dirOf(0), rest[index + 1]);
|
|
1705
|
+
}
|
|
1706
|
+
case void 0:
|
|
1707
|
+
case "-h":
|
|
1708
|
+
case "--help":
|
|
1709
|
+
case "help":
|
|
1710
|
+
process.stdout.write(USAGE + "\n");
|
|
1711
|
+
return command ? 0 : 2;
|
|
1712
|
+
default:
|
|
1713
|
+
process.stderr.write(`Unknown command: ${command}\n\n${USAGE}\n`);
|
|
1714
|
+
return 2;
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
export { main };
|