superagent-skill 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.mjs ADDED
@@ -0,0 +1,1487 @@
1
+ import { O as latestReport, P as threadKey, S as key, a as readSettings, c as AGENT_NAMES, g as Engine, h as readState, l as installed, m as FileRepositories, p as reportInstructions, r as defaultSettings, s as writeSettings, t as SETTINGS_FILE, u as runnerFor } from "./settings-BewLFAqT.mjs";
2
+ import { access, lstat, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
3
+ import { delimiter, join, resolve } from "node:path";
4
+ import { execFile, spawn } from "node:child_process";
5
+ import { z } from "zod";
6
+ import { homedir } from "node:os";
7
+ // src/infra/environment.ts
8
+ /**
9
+ * Writes the CLI shims and the isolated git configuration that bind a run to the agent's accounts.
10
+ *
11
+ * Each shim strips its own directory from PATH before it execs, so a wrapper script that resolves `gh` by name reaches the
12
+ * real binary instead of looping. The git configuration replaces the operator's global configuration for the run, so a
13
+ * worker cannot push with the operator's credentials.
14
+ *
15
+ * These are guardrails, not an OS boundary: a run shares the operator's OS user and can read their home directory.
16
+ */
17
+ const MARKER = "# Written by superagent on every start; edits are lost.";
18
+ /** Commands the shims provide, which a blocked list must never shadow. */
19
+ const WORKER_COMMANDS = [
20
+ "gh",
21
+ "git",
22
+ "lark-cli"
23
+ ];
24
+ const workerBin = (stateDir) => join(stateDir, "worker-bin");
25
+ const workerGitConfig = (stateDir) => join(stateDir, "worker-gitconfig");
26
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
27
+ const gitQuote = (value) => `"${value.replace(/[\\"]/g, (char) => `\\${char}`)}"`;
28
+ const credentialHelper = (cli) => `!${shellQuote(cli)} auth git-credential`;
29
+ async function written(file) {
30
+ try {
31
+ const stat = await lstat(file);
32
+ if (!stat.isFile() || stat.size > 4096) return false;
33
+ return (await readFile(file, "utf8")).includes(MARKER);
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+ async function own(file, content) {
39
+ const temporary = `${file}.${process.pid}.tmp`;
40
+ await writeFile(temporary, content, { mode: 384 });
41
+ await rename(temporary, file);
42
+ }
43
+ /**
44
+ * Writes the shims and git configuration, refusing to overwrite files it did not write.
45
+ * @throws when a file in the shim directory or at the git configuration path was written by something else.
46
+ */
47
+ async function writeEnvironment(accounts, blockedCommands) {
48
+ const dir = workerBin(accounts.stateDir);
49
+ await mkdir(dir, { recursive: true });
50
+ const before = await readdir(dir);
51
+ for (const name of before) if (!await written(join(dir, name))) throw new Error(`The file ${join(dir, name)} was not written by superagent; move it away or choose another state directory.`);
52
+ const kept = /* @__PURE__ */ new Set();
53
+ const shim = async (name, body) => {
54
+ const temporary = join(dir, `.${name}.${process.pid}.tmp`);
55
+ await writeFile(temporary, `#!/bin/sh\n${MARKER}\n${body}\n`, { mode: 493 });
56
+ await rename(temporary, join(dir, name));
57
+ kept.add(name);
58
+ };
59
+ const withoutShims = [
60
+ `self=${shellQuote(dir)}`,
61
+ "rest=",
62
+ "IFS=:",
63
+ "set -f",
64
+ "for entry in $PATH; do [ \"$entry\" = \"$self\" ] || rest=\"${rest:+$rest:}$entry\"; done",
65
+ "set +f",
66
+ "unset IFS",
67
+ "PATH=$rest",
68
+ "export PATH"
69
+ ].join("\n");
70
+ const run = (program) => `${withoutShims}\nexec ${shellQuote(program)} "$@"`;
71
+ const fail = (message) => `echo ${shellQuote(message)} >&2\nexit 1`;
72
+ await shim("gh", run(accounts.githubCli));
73
+ await shim("lark-cli", accounts.feishuCli ? run(accounts.feishuCli) : fail("lark-cli is unavailable: this installation has no Feishu bot."));
74
+ for (const name of new Set(blockedCommands.filter((name) => !WORKER_COMMANDS.includes(name)))) await shim(name, fail(`${name} is blocked in this installation; use gh, which acts as ${accounts.agentLogin}.`));
75
+ for (const name of before) if (!kept.has(name)) await unlink(join(dir, name));
76
+ await own(workerGitConfig(accounts.stateDir), [
77
+ MARKER,
78
+ "[user]",
79
+ " useConfigOnly = true",
80
+ "[credential]",
81
+ " helper =",
82
+ "[credential \"https://github.com\"]",
83
+ `\thelper = ${gitQuote(credentialHelper(accounts.githubCli))}`,
84
+ "[url \"https://github.com/\"]",
85
+ " insteadOf = git@github.com:",
86
+ " insteadOf = ssh://git@github.com:",
87
+ "[filter \"lfs\"]",
88
+ " clean = git-lfs clean -- %f",
89
+ " smudge = git-lfs smudge -- %f",
90
+ " process = git-lfs filter-process",
91
+ " required = true"
92
+ ].join("\n") + "\n");
93
+ }
94
+ /** Environment variables a run receives, with the shim directory first on PATH. */
95
+ function runEnvironment(accounts, variables) {
96
+ return {
97
+ ...variables,
98
+ PATH: [workerBin(accounts.stateDir), process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"].join(delimiter),
99
+ GIT_CONFIG_GLOBAL: workerGitConfig(accounts.stateDir),
100
+ GIT_CONFIG_SYSTEM: "/dev/null",
101
+ GIT_TERMINAL_PROMPT: "0"
102
+ };
103
+ }
104
+ // src/infra/commands.ts
105
+ /** Runs the Source CLIs (`gh`, `lark-cli`) and reads their JSON. Every call is bounded and never prompts. */
106
+ var CliError = class extends Error {
107
+ stdout;
108
+ stderr;
109
+ constructor(program, message, stdout, stderr) {
110
+ super(message);
111
+ this.stdout = stdout;
112
+ this.stderr = stderr;
113
+ this.name = "CliError";
114
+ }
115
+ };
116
+ /** Runs a program and returns its standard output; a non-zero exit throws a `CliError` that keeps both streams. */
117
+ function run(program, argv, options = {}) {
118
+ return new Promise((resolve, reject) => {
119
+ const child = execFile(program, argv, {
120
+ cwd: options.cwd,
121
+ env: {
122
+ ...process.env,
123
+ ...options.env
124
+ },
125
+ timeout: options.timeoutMs ?? 12e4,
126
+ maxBuffer: 64 << 20,
127
+ ...options.signal ? { signal: options.signal } : {}
128
+ }, (error, stdout, stderr) => {
129
+ if (error) reject(new CliError(program, `${program} ${argv.join(" ")} failed: ${stderr.trim() || error.message}`, stdout, stderr));
130
+ else resolve(stdout);
131
+ });
132
+ if (options.stdin !== void 0) child.stdin?.end(options.stdin);
133
+ else child.stdin?.end();
134
+ });
135
+ }
136
+ /** Runs a program and parses its JSON output; accepts the plain shape and the `{ok, data}` envelope `lark-cli` uses. */
137
+ async function runJson(program, argv, options = {}) {
138
+ const text = await run(program, argv, options);
139
+ let parsed;
140
+ try {
141
+ parsed = JSON.parse(text);
142
+ } catch {
143
+ throw new CliError(program, `${program} ${argv.join(" ")} did not print JSON: ${text.slice(0, 200)}`, text, "");
144
+ }
145
+ if (parsed && typeof parsed === "object" && "ok" in parsed && parsed.ok === false) {
146
+ const error = parsed.error;
147
+ throw new CliError(program, `${program} ${argv.join(" ")}: ${error?.message ?? "failed"}`, text, "");
148
+ }
149
+ if (parsed && typeof parsed === "object" && "code" in parsed && "data" in parsed) return parsed.data;
150
+ return parsed;
151
+ }
152
+ // src/prompts.ts
153
+ /** Composes the prompt for one ticket: who asked, what they asked, and what the agent must not assume. */
154
+ function composePrompt(input) {
155
+ const { ticket, trigger, repository, agentLogin, branchPrefix, instructions, source = "github", branch } = input;
156
+ 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
+ return [
158
+ `# Ticket ${ticket.id}`,
159
+ "",
160
+ ...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."],
161
+ "",
162
+ "## The request",
163
+ "",
164
+ asked,
165
+ "",
166
+ "## How to work",
167
+ "",
168
+ `- Work only in this directory. It is a worktree of the repository on a new branch.`,
169
+ 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.`,
170
+ "- Run the tests the repository has. Do not claim a check passed unless you ran it.",
171
+ "- Do not merge the pull request. A person merges it.",
172
+ "- If the request needs a decision you cannot make, stop and ask one concrete question.",
173
+ "",
174
+ ...instructions.trim() ? [
175
+ "## Team instructions",
176
+ "",
177
+ instructions.trim(),
178
+ ""
179
+ ] : [],
180
+ reportInstructions()
181
+ ].join("\n");
182
+ }
183
+ /** Indents a person's message so the agent reads it as quoted material, not as instructions to this prompt. */
184
+ function quote(text) {
185
+ return (text.trim() || "(empty message)").split("\n").map((line) => `> ${line}`).join("\n");
186
+ }
187
+ new Intl.Segmenter("zh", { granularity: "word" });
188
+ /** Case-insensitive comparison for GitHub logins and repository names. */
189
+ const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
190
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
191
+ // src/sources/github.ts
192
+ /**
193
+ * The GitHub Source: turns new mentions and new Issues in one repository into Triggers.
194
+ *
195
+ * GitHub delivers a mention to the agent's own account as a notification, so the poll reads notifications rather than
196
+ * every Issue in the repository. The alternative — scanning the repository — costs a request per Issue and reports
197
+ * mentions the agent may never have been able to answer.
198
+ *
199
+ * A notification only says that something mentioned the account. The comment itself is read afterwards, so the Trigger
200
+ * carries what the person wrote, not the notification's summary.
201
+ */
202
+ const SOURCE$1 = "github";
203
+ /** A thread identifier for an Issue or pull request number; both share one sequence in GitHub. */
204
+ const githubThread = (number) => ({
205
+ source: SOURCE$1,
206
+ id: String(number)
207
+ });
208
+ /** Where a reply to this number goes. */
209
+ const githubChannel = (repository, number, url) => ({
210
+ source: SOURCE$1,
211
+ thread: threadKey(githubThread(number)),
212
+ address: {
213
+ number: String(number),
214
+ repository,
215
+ ...url ? { url } : {}
216
+ }
217
+ });
218
+ const githubPage = (repository, number, pr = false) => `https://github.com/${repository}/${pr ? "pull" : "issues"}/${number}`;
219
+ /** Whether `text` mentions `login` as a whole name rather than as a prefix of a longer one. */
220
+ const mentions = (text, login) => new RegExp(`(?:^|[^a-zA-Z0-9_@])@${escapeRegExp(login)}(?![a-zA-Z0-9_-])`, "i").test(text);
221
+ /** True for an account GitHub reports as an ordinary user; a login ending in `[bot]` or an App is not one. */
222
+ const isHumanLogin = (user) => !/\[bot\]$/.test(user.login) && (!user.type || user.type === "User");
223
+ const UserSchema = z.looseObject({
224
+ login: z.string(),
225
+ type: z.string().nullish()
226
+ }).nullish().transform((user) => user ?? {
227
+ login: "ghost",
228
+ type: null
229
+ });
230
+ z.looseObject({
231
+ id: z.string(),
232
+ reason: z.string(),
233
+ updated_at: z.string(),
234
+ subject: z.looseObject({
235
+ title: z.string(),
236
+ url: z.string().nullish(),
237
+ type: z.string(),
238
+ latest_comment_url: z.string().nullish()
239
+ }),
240
+ repository: z.looseObject({
241
+ full_name: z.string(),
242
+ owner: z.looseObject({ login: z.string() }).nullish()
243
+ }).nullish()
244
+ });
245
+ z.looseObject({
246
+ id: z.number().nullish(),
247
+ body: z.string().nullish(),
248
+ user: UserSchema,
249
+ html_url: z.string().nullish(),
250
+ created_at: z.string().nullish(),
251
+ updated_at: z.string().nullish(),
252
+ submitted_at: z.string().nullish(),
253
+ state: z.string().nullish()
254
+ });
255
+ /** Pulls `owner/repo#number` out of a notification subject URL, for the repository the Source watches. */
256
+ function notificationNumber(notification) {
257
+ const match = /\/(?:issues|pulls)\/(\d+)\/?$/.exec(notification.subject.url ?? "");
258
+ if (!match) return void 0;
259
+ return {
260
+ number: Number(match[1]),
261
+ pr: notification.subject.type === "PullRequest"
262
+ };
263
+ }
264
+ /** Reads the comment a notification points at; a notification without a comment URL is a new Issue, which has none. */
265
+ async function notificationComment(notification, cli, repository) {
266
+ const url = notification.subject.latest_comment_url;
267
+ if (!url) return void 0;
268
+ if (!url.includes(`/api.github.com/repos/${repository}/`)) return void 0;
269
+ const path = url.replace(/^https:\/\/api\.github\.com\//, "");
270
+ try {
271
+ return await runJson(cli, ["api", path]);
272
+ } catch {
273
+ return;
274
+ }
275
+ }
276
+ /** 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. */
277
+ function commentTrigger(input) {
278
+ const { repository, number, pr, comment, agent, kind } = input;
279
+ const at = comment.updated_at ?? comment.submitted_at ?? comment.created_at ?? (/* @__PURE__ */ new Date()).toISOString();
280
+ const text = [comment.state && comment.state !== "COMMENTED" ? `${comment.state} review` : "", comment.body ?? ""].filter(Boolean).join("\n\n");
281
+ const url = comment.html_url ?? githubPage(repository, number, pr);
282
+ const login = comment.user.login;
283
+ return {
284
+ id: key("github-comment", url, String(comment.id ?? ""), at),
285
+ source: SOURCE$1,
286
+ threads: [githubThread(number)],
287
+ actor: {
288
+ source: SOURCE$1,
289
+ id: login
290
+ },
291
+ human: isHumanLogin(comment.user) && !sameName(login, agent),
292
+ ...mentions(comment.body ?? "", agent) ? { addressed: "mention" } : {},
293
+ at,
294
+ text,
295
+ channel: githubChannel(repository, number, url),
296
+ url,
297
+ meta: {
298
+ number,
299
+ isPr: pr,
300
+ repository,
301
+ commentId: comment.id ?? null,
302
+ kind
303
+ }
304
+ };
305
+ }
306
+ /** The name a CLI reports for the account it acts as, which the Trigger builder uses to tell the agent's own messages apart. */
307
+ async function agentLogin(cli, signal) {
308
+ return (await runJson(cli, ["api", "user"], { signal })).login;
309
+ }
310
+ /**
311
+ * Polls one round of notifications for `repository` and returns the Triggers it has not seen.
312
+ * `since` is the ISO time of the previous round, or the moment the Source first ran.
313
+ */
314
+ async function pollNotifications(input) {
315
+ const notifications = await runJson(input.cli, ["api", `notifications?all=false&participating=false&since=${encodeURIComponent(input.since)}`], { signal: input.signal });
316
+ const triggers = [];
317
+ for (const notification of notifications) {
318
+ if (!sameName(notification.repository?.full_name ?? "", input.repository)) continue;
319
+ if (!/mention|assign|review_requested|comment/.test(notification.reason)) continue;
320
+ if (input.seen(notification.id)) continue;
321
+ const place = notificationNumber(notification);
322
+ if (!place) {
323
+ input.mark(notification.id);
324
+ continue;
325
+ }
326
+ const comment = await notificationComment(notification, input.cli, input.repository);
327
+ if (!comment) {
328
+ input.mark(notification.id);
329
+ continue;
330
+ }
331
+ if (sameName(comment.user.login, input.agent)) {
332
+ input.mark(notification.id);
333
+ continue;
334
+ }
335
+ if (!mentions(comment.body ?? "", input.agent)) {
336
+ input.mark(notification.id);
337
+ continue;
338
+ }
339
+ triggers.push(commentTrigger({
340
+ repository: input.repository,
341
+ number: place.number,
342
+ pr: place.pr,
343
+ comment,
344
+ agent: input.agent,
345
+ kind: "conversation"
346
+ }));
347
+ input.mark(notification.id);
348
+ }
349
+ return triggers;
350
+ }
351
+ // src/sources/feishu.ts
352
+ /**
353
+ * The Feishu Source: a bot listens in chats, and a message that mentions it, or a direct message, becomes a Trigger.
354
+ *
355
+ * Feishu pushes events, so the Source reads the bot's long-lived event stream rather than polling. That stream is one
356
+ * process (`lark-cli event consume`); `consumeEvents` runs it and hands each message to a callback.
357
+ *
358
+ * A chat is listened to only when `settings.feishu.chats` names it, because a bot in a busy chat sees everything and a
359
+ * Trigger per message would cost the team attention for nothing.
360
+ */
361
+ const SOURCE = "feishu";
362
+ /** 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
+ * the app's event subscription, so read it from `lark-cli event list` rather than assume it. */
364
+ const MESSAGE_EVENT = "im.message.receive_v1";
365
+ const feishuThread = (chatId, rootId, messageId) => ({
366
+ source: SOURCE,
367
+ id: `${chatId}:${rootId ?? messageId}`
368
+ });
369
+ /** Where a reply to this message goes; `direct` is explicit because group and direct chat ids both start with `oc_`. */
370
+ const feishuChannel = (chatId, messageId, direct = false) => ({
371
+ source: SOURCE,
372
+ thread: `feishu:${chatId}`,
373
+ address: {
374
+ chatId,
375
+ messageId,
376
+ ...direct ? { direct: "true" } : {}
377
+ }
378
+ });
379
+ /** One message as the event stream prints it. */
380
+ const EventSchema = z.object({
381
+ message_id: z.string(),
382
+ chat_id: z.string(),
383
+ chat_type: z.enum(["p2p", "group"]),
384
+ sender_id: z.string().optional(),
385
+ sender_type: z.enum(["user", "bot"]).optional(),
386
+ sender: z.object({
387
+ sender_id: z.string(),
388
+ sender_type: z.enum(["user", "bot"])
389
+ }).optional(),
390
+ content: z.string(),
391
+ create_time: z.string(),
392
+ mentions: z.array(z.object({
393
+ id: z.string(),
394
+ key: z.string().optional(),
395
+ name: z.string().optional()
396
+ })).default([]),
397
+ root_id: z.string().optional(),
398
+ parent_id: z.string().optional(),
399
+ message_app_link: z.string().optional()
400
+ });
401
+ /** Feishu sends epoch milliseconds as a string for live events; anything else is passed to `Date`. */
402
+ function feishuTime(value) {
403
+ const time = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
404
+ if (!Number.isFinite(time)) throw new Error(`Unreadable Feishu message time: ${value}`);
405
+ return new Date(time).toISOString();
406
+ }
407
+ /** Replaces Feishu's mention placeholders with the names a reader expects, so the agent sees "@bot fix this". */
408
+ function withMentionNames(text, mentions) {
409
+ return mentions.reduce((result, mention) => mention.key && mention.name ? result.replaceAll(mention.key, `@${mention.name}`) : result, text);
410
+ }
411
+ /** Builds a Trigger for one message, or `undefined` when the bot wrote it or the chat is not listened to. */
412
+ function feishuTrigger(input, options) {
413
+ const parsed = EventSchema.safeParse(input);
414
+ if (!parsed.success) {
415
+ options.onInvalid?.(parsed.error.message);
416
+ return;
417
+ }
418
+ const event = parsed.data;
419
+ const { botId, botAppId, chats, directMessages } = options;
420
+ const senderId = event.sender_id ?? event.sender?.sender_id ?? "";
421
+ const senderType = event.sender_type ?? event.sender?.sender_type ?? "user";
422
+ if (senderId === botId || senderId === botAppId) return void 0;
423
+ const direct = event.chat_type === "p2p";
424
+ if (direct ? !directMessages : !chats.has(event.chat_id)) return void 0;
425
+ const mentioned = event.mentions.some((mention) => !botId || mention.id === botId || mention.id === botAppId);
426
+ if (!direct && !mentioned) return void 0;
427
+ const url = event.message_app_link;
428
+ return {
429
+ id: key("feishu", event.message_id),
430
+ source: SOURCE,
431
+ threads: [feishuThread(event.chat_id, event.root_id, event.message_id)],
432
+ actor: {
433
+ source: SOURCE,
434
+ id: senderId
435
+ },
436
+ human: senderType === "user",
437
+ ...direct ? { addressed: "direct" } : { addressed: "mention" },
438
+ at: feishuTime(event.create_time),
439
+ text: withMentionNames(event.content, event.mentions),
440
+ channel: feishuChannel(event.chat_id, event.message_id, direct),
441
+ ...url ? { url } : {},
442
+ meta: {
443
+ chatId: event.chat_id,
444
+ messageId: event.message_id,
445
+ direct,
446
+ mentioned,
447
+ ...event.root_id ? { rootId: event.root_id } : {}
448
+ }
449
+ };
450
+ }
451
+ /**
452
+ * The bot's own ids, which the Source needs to recognise a mention and to skip its own messages.
453
+ *
454
+ * The open id comes from one listened chat, because a bot that is in no chat reports none. A stream-only bot can still
455
+ * receive direct messages, so a chat it cannot read is not an error.
456
+ */
457
+ async function botIdentity(cli, chatIds, signal) {
458
+ const status = await runJson(cli, ["config", "show"], { signal });
459
+ for (const chatId of chatIds) try {
460
+ const botId = (await runJson(cli, [
461
+ "im",
462
+ "chat.members",
463
+ "bots",
464
+ "--params",
465
+ JSON.stringify({ chat_id: chatId })
466
+ ], { signal })).bots?.find((bot) => bot.bot_id)?.bot_id;
467
+ if (botId) return {
468
+ appId: status.appId,
469
+ botId
470
+ };
471
+ } catch {}
472
+ return {
473
+ appId: status.appId,
474
+ botId: ""
475
+ };
476
+ }
477
+ /** The members of a chat, which fill the allow list when `settings.feishu.syncChat` names it. */
478
+ async function chatMembers(cli, chatId, signal) {
479
+ return ((await runJson(cli, [
480
+ "im",
481
+ "+chat-members-list",
482
+ "--chat-id",
483
+ chatId,
484
+ "--member-types",
485
+ "user",
486
+ "--page-all",
487
+ "--page-limit",
488
+ "0"
489
+ ], { signal })).users ?? []).map((user) => ({
490
+ id: user.member_id,
491
+ name: user.name ?? user.member_id
492
+ }));
493
+ }
494
+ /** Posts a reply in the thread of `messageId`, which is where the person who asked is reading. */
495
+ async function reply(cli, messageId, text, idempotencyKey, signal) {
496
+ await run(cli, [
497
+ "im",
498
+ "+messages-reply",
499
+ "--message-id",
500
+ messageId,
501
+ "--markdown",
502
+ text,
503
+ "--reply-in-thread",
504
+ "--idempotency-key",
505
+ idempotencyKey
506
+ ], { signal });
507
+ }
508
+ /** A small JSON reader for the event stream, which tolerates what other commands print before or between events. */
509
+ var EventReader = class {
510
+ rest = "";
511
+ read;
512
+ failed;
513
+ constructor(read, failed) {
514
+ this.read = read;
515
+ this.failed = failed;
516
+ }
517
+ /** Hands every complete line in `chunk` to the reader, and keeps the rest until the next chunk completes it. */
518
+ push(chunk) {
519
+ this.rest += chunk;
520
+ const lines = this.rest.split("\n");
521
+ this.rest = lines.pop();
522
+ for (const line of lines) if (line.trim()) this.line(line);
523
+ }
524
+ /** Reads what is left when the stream ends. */
525
+ flush() {
526
+ const line = this.rest.trim();
527
+ this.rest = "";
528
+ if (line) this.line(line);
529
+ }
530
+ line(line) {
531
+ try {
532
+ const value = JSON.parse(line);
533
+ if (value && typeof value === "object" && !Array.isArray(value)) this.read(line);
534
+ } catch {
535
+ this.failed(line);
536
+ }
537
+ }
538
+ };
539
+ /** How long a stop leaves the consumer to end on its own before it is killed. */
540
+ const STOP_GRACE_MS = 1e3;
541
+ /**
542
+ * Runs `lark-cli event consume` and hands every message to `onMessage`.
543
+ *
544
+ * The child exits when its stdin closes, so this keeps stdin open for the life of the run and closes it to stop. The
545
+ * consumer also refuses to start while another process holds the app's event connection, which is why one installation
546
+ * should use its own Feishu app.
547
+ *
548
+ * The reader collects whole lines only and hands each to `onMessage` as it reads it. A round waits on `next`, which is
549
+ * 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
550
+ * arrives with the close answers one last `next`, and after the close `next` is false at once.
551
+ */
552
+ function consumeEvents(options) {
553
+ const failed = (line) => {
554
+ options.onError(`Unreadable event: ${line.slice(0, 200)}`);
555
+ };
556
+ let linesRead = 0;
557
+ const reader = new EventReader((line) => {
558
+ options.onMessage(JSON.parse(line));
559
+ linesRead++;
560
+ }, failed);
561
+ let waiting;
562
+ let closing = false;
563
+ let finished = false;
564
+ const unwait = () => {
565
+ const waiter = waiting;
566
+ if (!waiter) return;
567
+ clearTimeout(waiter.timer);
568
+ waiting = void 0;
569
+ waiter.resolve(true);
570
+ };
571
+ const next = (ms) => {
572
+ if (closing || finished) return Promise.resolve(false);
573
+ if (linesRead) {
574
+ linesRead = 0;
575
+ return Promise.resolve(true);
576
+ }
577
+ return new Promise((resolve) => {
578
+ waiting = {
579
+ resolve,
580
+ timer: setTimeout(() => {
581
+ waiting = void 0;
582
+ resolve(false);
583
+ }, ms)
584
+ };
585
+ });
586
+ };
587
+ let child;
588
+ let settled;
589
+ const ended = new Promise((resolve) => {
590
+ settled = resolve;
591
+ });
592
+ const stop = () => {
593
+ if (!child || finished) return;
594
+ if (!child.stdin.destroyed) child.stdin.end();
595
+ setTimeout(() => {
596
+ finished = true;
597
+ child.kill("SIGTERM");
598
+ unwait();
599
+ settled();
600
+ }, STOP_GRACE_MS).unref();
601
+ };
602
+ child = spawn(options.cli, [
603
+ "event",
604
+ "consume",
605
+ MESSAGE_EVENT,
606
+ "--as",
607
+ "bot"
608
+ ], {
609
+ stdio: [
610
+ "pipe",
611
+ "pipe",
612
+ "pipe"
613
+ ],
614
+ env: {
615
+ ...process.env,
616
+ LARKSUITE_CLI_NO_UPDATE_NOTIFIER: "1",
617
+ LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
618
+ }
619
+ });
620
+ child.stdout.on("data", (chunk) => {
621
+ reader.push(chunk.toString());
622
+ unwait();
623
+ });
624
+ child.stderr.on("data", (chunk) => {
625
+ for (const line of chunk.toString().split("\n")) if (/WARN|error/i.test(line)) options.onError(line.slice(0, 400));
626
+ });
627
+ child.on("spawn", () => {
628
+ if (options.signal.aborted) stop();
629
+ else options.onListening?.({
630
+ next,
631
+ stop,
632
+ ended
633
+ });
634
+ });
635
+ child.on("error", (error) => {
636
+ if (!finished) options.onError(String(error));
637
+ finished = true;
638
+ unwait();
639
+ settled();
640
+ });
641
+ child.on("close", (code) => {
642
+ if (!finished) {
643
+ reader.flush();
644
+ if (code !== 0) options.onError(`The event consumer exited with code ${code}`);
645
+ }
646
+ finished = true;
647
+ closing = true;
648
+ unwait();
649
+ settled();
650
+ });
651
+ options.signal.addEventListener("abort", stop, { once: true });
652
+ if (options.signal.aborted) stop();
653
+ return {
654
+ next,
655
+ stop,
656
+ ended
657
+ };
658
+ }
659
+ // src/infra/worktree.ts
660
+ /**
661
+ * Gives a ticket its own git worktree and branch, so two tickets can change one repository at once and neither sees the
662
+ * other's half-finished edits.
663
+ *
664
+ * A worktree rather than a clone: it shares the checkout's object store, so it costs a directory and nothing else. The
665
+ * worktree lives under `stateDir/work/<ticket>`, which is also where the agent's run log goes.
666
+ *
667
+ * A checkout that is not a git repository gets a plain directory instead. That keeps `superagent run` and installations
668
+ * that watch nothing but a chat working.
669
+ */
670
+ /** A short, git-safe branch name for a ticket: a slug of its title, made unique by the ticket's id. */
671
+ function ticketBranch(prefix, title, id) {
672
+ return `${prefix}${title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40).replace(/-$/, "") || "request"}-${id.slice(-6)}`;
673
+ }
674
+ /** Whether `directory` is inside a git work tree. */
675
+ async function isGitRepository(directory) {
676
+ try {
677
+ await access(join(directory, ".git"));
678
+ return true;
679
+ } catch {}
680
+ try {
681
+ await run("git", [
682
+ "-C",
683
+ directory,
684
+ "rev-parse",
685
+ "--is-inside-work-tree"
686
+ ], { timeoutMs: 1e4 });
687
+ return true;
688
+ } catch {
689
+ return false;
690
+ }
691
+ }
692
+ /**
693
+ * Creates the worktree for a ticket and returns its directory.
694
+ *
695
+ * @throws when git cannot create the worktree, such as when the checkout has no commit yet; the caller then reports the
696
+ * ticket as failed instead of starting an agent in a directory that is not the repository.
697
+ */
698
+ async function prepareWorktree(options) {
699
+ const { checkout, directory, branch, signal } = options;
700
+ await mkdir(directory, { recursive: true });
701
+ if ((await readdir(directory)).length) return directory;
702
+ if (!await isGitRepository(checkout)) return directory;
703
+ await run("git", [
704
+ "-C",
705
+ checkout,
706
+ "worktree",
707
+ "add",
708
+ "-b",
709
+ branch,
710
+ directory,
711
+ (await run("git", [
712
+ "-C",
713
+ checkout,
714
+ "rev-parse",
715
+ "HEAD"
716
+ ], {
717
+ signal,
718
+ timeoutMs: 1e4
719
+ })).trim()
720
+ ], {
721
+ signal,
722
+ timeoutMs: 12e4
723
+ }).catch(async (error) => {
724
+ await removeWorktree(checkout, directory, signal);
725
+ throw new Error(`${directory} is not a branch point: ${error.message}`, { cause: error });
726
+ });
727
+ return directory;
728
+ }
729
+ /** 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) {
731
+ try {
732
+ await run("git", [
733
+ "-C",
734
+ checkout,
735
+ "worktree",
736
+ "remove",
737
+ "--force",
738
+ directory
739
+ ], {
740
+ signal,
741
+ timeoutMs: 12e4
742
+ });
743
+ } catch {}
744
+ }
745
+ // src/runner.ts
746
+ function deliver(engine, repo, delivered, log) {
747
+ for (const ticket of repo.tickets.list()) {
748
+ const report = latestReport(ticket);
749
+ if (!ticket.ended || report?.state !== "ready" || delivered.has(`${ticket.id}@${report.at}`)) continue;
750
+ delivered.add(`${ticket.id}@${report.at}`);
751
+ const text = String(report.summary).trim() || "The work is done.";
752
+ try {
753
+ engine.reply({
754
+ purpose: "result",
755
+ ticketId: ticket.id,
756
+ text
757
+ });
758
+ log(`Answered ticket ${ticket.id} in its conversation`);
759
+ } catch (error) {
760
+ log(`Could not answer ticket ${ticket.id}: ${error.message}`);
761
+ }
762
+ }
763
+ }
764
+ /** Decides the requests the assessor accepted, which starts their tickets. */
765
+ function advance(engine, repo, log, candidates) {
766
+ for (const candidate of candidates) {
767
+ const trigger = repo.triggers.get(candidate.triggers[0].id);
768
+ if (!trigger) continue;
769
+ const name = trigger.text.split("\n")[0].replace(/@[\w-]+/g, "").trim().slice(0, 60) || "Request";
770
+ try {
771
+ const decision = engine.decide(trigger.id, {
772
+ kind: "accept",
773
+ title: name,
774
+ scope: name,
775
+ reason: "explicit"
776
+ });
777
+ log(`Accepted ${trigger.id} as ticket ${decision.ticketId ?? "(none)"}`);
778
+ } catch (error) {
779
+ log(`Could not accept ${trigger.id}: ${error.message}`);
780
+ }
781
+ }
782
+ }
783
+ /** Holds the turns' outcomes until a round records them, and wakes that round when one arrives. */
784
+ var TurnQueue = class {
785
+ items = [];
786
+ handoff;
787
+ waiter;
788
+ /** A turn that finished; it is kept even with no round waiting, so a turn that outlives its round is still recorded. */
789
+ push(item) {
790
+ this.items.push(item);
791
+ this.handoff?.(item);
792
+ this.wake();
793
+ }
794
+ /** The turns finished since the last drain. */
795
+ drain() {
796
+ return this.items.splice(0);
797
+ }
798
+ /** Whether a turn is waiting to be recorded. */
799
+ ready() {
800
+ return this.items.length > 0;
801
+ }
802
+ /** Settles when a turn has finished, or when `ms` passes. */
803
+ wait(ms) {
804
+ if (this.items.length) return Promise.resolve();
805
+ return new Promise((resolve) => {
806
+ const finish = () => {
807
+ clearTimeout(timer);
808
+ this.waiter = void 0;
809
+ resolve();
810
+ };
811
+ const timer = setTimeout(finish, ms);
812
+ this.waiter = finish;
813
+ });
814
+ }
815
+ wake() {
816
+ this.waiter?.();
817
+ }
818
+ };
819
+ /** How long one round waits for a turn before the next round; a turn is recorded when it ends, not several rounds later. */
820
+ const TURN_WAIT_MS = 1e3;
821
+ /** Records the turns that finished, so a ticket ends without the loop holding work in memory; a refused report is logged, not thrown. */
822
+ function record(engine, repo, finished, log) {
823
+ for (const item of finished) try {
824
+ const latest = repo.tickets.get(item.ticketId);
825
+ if (latest) engine.updateTicket(latest);
826
+ engine.report(item.ticketId, {
827
+ state: item.report.state,
828
+ summary: item.report.summary,
829
+ ...item.report.question ? { question: item.report.question } : {}
830
+ });
831
+ } catch (error) {
832
+ log(`Could not record the report for ${item.ticketId}: ${error.message}`);
833
+ }
834
+ }
835
+ /** Posts the messages the Engine queued, one comment per message. */
836
+ async function send(channel, clis, log) {
837
+ for (const message of channel.drain()) {
838
+ if (message.channel.source === "feishu") {
839
+ const address = message.channel.address;
840
+ if (!clis.feishu) {
841
+ log(`Cannot answer in ${address.chatId}: the Feishu Source is off`);
842
+ continue;
843
+ }
844
+ try {
845
+ await reply(clis.feishu, address.messageId, message.text, message.id);
846
+ log(`Answered in ${address.chatId}`);
847
+ } catch (error) {
848
+ log(`Could not answer in ${address.chatId}: ${error.message}`);
849
+ }
850
+ continue;
851
+ }
852
+ const address = message.channel.address;
853
+ if (!address.number || !address.repository) continue;
854
+ if (!clis.github) {
855
+ log(`Cannot post on ${address.repository}#${address.number}: the GitHub Source is off`);
856
+ continue;
857
+ }
858
+ try {
859
+ await run(clis.github, [
860
+ "api",
861
+ `repos/${address.repository}/issues/${address.number}/comments`,
862
+ "-f",
863
+ `body=${message.text}`
864
+ ]);
865
+ log(`Posted a message on ${address.repository}#${address.number}`);
866
+ } catch (error) {
867
+ log(`Could not post on ${address.repository}#${address.number}: ${error.message}`);
868
+ }
869
+ }
870
+ }
871
+ /** Where the loop keeps its own bookkeeping, beside the domain state. */
872
+ const pollKey = "github:poll";
873
+ 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
+ /** Lines one round reads from the stream at most, so a chat that keeps talking does not hold a round open. */
950
+ const MAX_LINES = 500;
951
+ /** A failed save of the last round must not stop the next one. */
952
+ function outbox() {
953
+ const messages = /* @__PURE__ */ new Map();
954
+ return {
955
+ send: (message) => {
956
+ if (!messages.has(message.id)) messages.set(message.id, message);
957
+ },
958
+ status: (id) => messages.has(id) ? "pending" : void 0,
959
+ withdraw: (id) => {
960
+ messages.delete(id);
961
+ },
962
+ /** Everything queued so far, for the caller to deliver in order. */
963
+ drain: () => [...messages.values()].sort((a, b) => a.id.localeCompare(b.id))
964
+ };
965
+ }
966
+ /**
967
+ * Runs a ticket on the configured agent.
968
+ *
969
+ * The Engine calls `start` and expects a report through its own callbacks; this keeps the work asynchronous, so the loop
970
+ * never blocks on an agent turn.
971
+ */
972
+ var AgentExecutor = class {
973
+ options;
974
+ active = /* @__PURE__ */ new Map();
975
+ constructor(options) {
976
+ this.options = options;
977
+ }
978
+ start(ticket, assignment) {
979
+ const controller = new AbortController();
980
+ const { site } = this.options;
981
+ site.started(ticket.id, assignment.id);
982
+ this.active.set(ticket.id, controller);
983
+ this.execute(ticket, assignment, controller);
984
+ }
985
+ deliver() {}
986
+ /** The Engine's memory of the ticket, so the report lands on a ticket that already holds this round's changes to it. */
987
+ refresh(ticket) {
988
+ this.options.engine.updateTicket(ticket);
989
+ }
990
+ stop(ticket) {
991
+ this.active.get(ticket.id)?.abort();
992
+ this.active.delete(ticket.id);
993
+ }
994
+ async execute(ticket, assignment, controller) {
995
+ const { settings, runner, stateDir, accounts, feishuCli, site } = this.options;
996
+ const directory = ticket.execution?.directory ?? join(stateDir, "work", ticket.id);
997
+ try {
998
+ const branch = ticketBranch(settings.branchPrefix, ticket.title, ticket.id);
999
+ await prepareWorktree({
1000
+ checkout: settings.checkout,
1001
+ directory,
1002
+ branch,
1003
+ signal: controller.signal
1004
+ });
1005
+ if (settings.executor.prepare) await run("/bin/sh", ["-c", settings.executor.prepare], {
1006
+ env: this.variables(ticket, directory, branch),
1007
+ timeoutMs: 12e4
1008
+ });
1009
+ const prompt = await this.options.prompt(ticket, directory, branch);
1010
+ const result = await runner.run({
1011
+ prompt,
1012
+ cwd: directory,
1013
+ env: runEnvironment(feishuCli ? {
1014
+ ...accounts,
1015
+ feishuCli
1016
+ } : accounts, this.variables(ticket, directory, branch)),
1017
+ signal: controller.signal,
1018
+ timeoutMs: settings.executor.timeoutMinutes * 6e4,
1019
+ model: settings.executor.model
1020
+ });
1021
+ const report = result.report ?? inferReport(result.finalText, result.ok);
1022
+ await appendLog(directory, prompt, result.raw.slice(-2e4), report);
1023
+ site.reported(ticket.id, {
1024
+ state: report.state ?? (result.ok ? "ready" : "failed"),
1025
+ summary: report.summary,
1026
+ question: report.question ?? null
1027
+ });
1028
+ } catch (error) {
1029
+ site.failed(ticket.id, assignment.id, `The agent could not run: ${error.message}`);
1030
+ } finally {
1031
+ this.active.delete(ticket.id);
1032
+ }
1033
+ }
1034
+ variables(ticket, directory, branch) {
1035
+ const trigger = ticket.origin;
1036
+ return {
1037
+ SUPERAGENT_TICKET: ticket.id,
1038
+ SUPERAGENT_DIR: directory,
1039
+ SUPERAGENT_BRANCH: branch,
1040
+ SUPERAGENT_REPOSITORY: this.options.repository,
1041
+ SUPERAGENT_TRIGGER: trigger.triggerId,
1042
+ DSH_SUPERAGENT_DIR: directory,
1043
+ DSH_SUPERAGENT_TICKET: ticket.id,
1044
+ DSH_SUPERAGENT_GITHUB_REPOSITORY: this.options.repository
1045
+ };
1046
+ }
1047
+ };
1048
+ /** Turns an agent that wrote no report into one the Engine can still act on. */
1049
+ function inferReport(text, ok) {
1050
+ return {
1051
+ summary: text.trim().split("\n").filter(Boolean).at(-1)?.slice(0, 500) || (ok ? "The agent finished." : "The agent failed."),
1052
+ state: ok ? "ready" : "failed"
1053
+ };
1054
+ }
1055
+ async function appendLog(directory, prompt, raw, report) {
1056
+ const path = join(directory, ".superagent", "log.md");
1057
+ const entry = [
1058
+ "",
1059
+ `## ${(/* @__PURE__ */ new Date()).toISOString()}`,
1060
+ "",
1061
+ "**Report**",
1062
+ "",
1063
+ "```json",
1064
+ JSON.stringify(report, null, 2),
1065
+ "```",
1066
+ "",
1067
+ "**Agent output**",
1068
+ "",
1069
+ "```",
1070
+ raw,
1071
+ "```"
1072
+ ].join("\n");
1073
+ const previous = await readFile(path, "utf8").catch(() => "");
1074
+ await mkdir(join(directory, ".superagent"), { recursive: true }).then(() => writeFile(path, `${previous}${entry}\n`));
1075
+ }
1076
+ /**
1077
+ * The loop that makes an installation run without a person: poll the Sources, assess what they bring, and run the tickets
1078
+ * the assessment accepts.
1079
+ *
1080
+ * It is a plain async loop, not a daemon protocol: `runLoop` returns when its signal aborts, so a cron job, a shell script,
1081
+ * or a coding agent can each call it for one round with `--once`.
1082
+ */
1083
+ /** Runs rounds until `signal` aborts; each round polls, assesses, and starts the tickets accepted. */
1084
+ async function runLoop(options) {
1085
+ const { settings, repo, signal: caller, log } = options;
1086
+ const stop = new AbortController();
1087
+ if (!options.once) caller.addEventListener("abort", () => stop.abort(), { once: true });
1088
+ const signal = stop.signal;
1089
+ const github = settings.github?.enabled ? settings.github : void 0;
1090
+ const feishu = settings.feishu?.enabled ? settings.feishu : void 0;
1091
+ if (!github && !feishu) throw new Error("No Source is on in settings.yaml; nothing to poll.");
1092
+ const login = github ? await agentLogin(github.cli, signal) : "";
1093
+ const accounts = {
1094
+ stateDir: settings.stateDir,
1095
+ githubCli: github?.cli ?? "gh",
1096
+ agentLogin: login
1097
+ };
1098
+ await writeEnvironment(accounts, settings.executor.blockedCommands);
1099
+ const channel = outbox();
1100
+ const finished = new TurnQueue();
1101
+ const engine = new Engine({
1102
+ repo,
1103
+ policy: () => buildPolicy(settings),
1104
+ scope: sourceScope(settings),
1105
+ assessor: explicitAssessor,
1106
+ executor: void 0,
1107
+ outbox: channel
1108
+ });
1109
+ const executor = new AgentExecutor({
1110
+ engine,
1111
+ settings,
1112
+ runner: runnerFor(settings.executor.agent, settings.executor.binary),
1113
+ stateDir: settings.stateDir,
1114
+ repository: github?.repository ?? settings.checkout,
1115
+ agent: login,
1116
+ accounts,
1117
+ ...feishu ? { feishuCli: feishu.cli } : {},
1118
+ site: {
1119
+ started: (ticketId, assignmentId) => engine.assignmentStarted(ticketId, assignmentId),
1120
+ reported: (ticketId, report) => finished.push({
1121
+ ticketId,
1122
+ report
1123
+ }),
1124
+ failed: (ticketId, _assignmentId, summary) => finished.push({
1125
+ ticketId,
1126
+ report: {
1127
+ state: "failed",
1128
+ summary
1129
+ }
1130
+ })
1131
+ },
1132
+ prompt: async (ticket, directory, branch) => {
1133
+ const trigger = repo.triggers.get(ticket.origin.triggerId);
1134
+ const source = trigger?.source === "feishu" ? "feishu" : "github";
1135
+ return composePrompt({
1136
+ ticket,
1137
+ trigger,
1138
+ repository: github?.repository ?? settings.checkout,
1139
+ agentLogin: login,
1140
+ branchPrefix: settings.branchPrefix,
1141
+ source,
1142
+ instructions: settings.prompts,
1143
+ branch
1144
+ });
1145
+ }
1146
+ });
1147
+ const admitted = /* @__PURE__ */ new Set();
1148
+ const sync = () => !feishu?.syncChat ? Promise.resolve() : chatMembers(feishu.cli, feishu.syncChat, signal).then((members) => {
1149
+ const listed = feishu.allowed.map((id) => id.toLowerCase());
1150
+ const add = members.map((member) => member.id).filter((id) => !listed.includes(id.toLowerCase()) && !admitted.has(id.toLowerCase()));
1151
+ if (add.length) {
1152
+ feishu.allowed.push(...add);
1153
+ for (const id of add) admitted.add(id.toLowerCase());
1154
+ log(`Admitted ${add.length} member(s) of ${feishu.syncChat} from its chat`);
1155
+ }
1156
+ }).catch((error) => {
1157
+ if (!signal.aborted) log(`Could not read the members of ${feishu.syncChat}: ${error.message}`);
1158
+ });
1159
+ await sync();
1160
+ const chats = new Map((feishu?.chats ?? []).map((chat) => [chat.chatId, false]));
1161
+ let identity = Promise.resolve({
1162
+ appId: "",
1163
+ botId: ""
1164
+ });
1165
+ let read = false;
1166
+ const identify = () => {
1167
+ if (read) return;
1168
+ read = true;
1169
+ identity = botIdentity(feishu.cli, [.../* @__PURE__ */ new Set([...chats.keys(), ...feishu.syncChat ? [feishu.syncChat] : []])], signal).catch((error) => {
1170
+ if (!signal.aborted) log(`Could not read the bot's ids: ${error.message}`);
1171
+ return {
1172
+ appId: "",
1173
+ botId: ""
1174
+ };
1175
+ });
1176
+ };
1177
+ const store = (trigger) => {
1178
+ try {
1179
+ options.repo;
1180
+ if (repo.atomic(() => engine.receive(trigger)) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
1181
+ } catch (error) {
1182
+ log(`Could not store ${trigger.id}: ${error.message}`);
1183
+ }
1184
+ };
1185
+ const receive = (event) => {
1186
+ identity.then((bot) => feishuTrigger(event, {
1187
+ botAppId: bot.appId,
1188
+ botId: bot.botId,
1189
+ chats,
1190
+ directMessages: feishu?.directMessages ?? true,
1191
+ onInvalid: (error) => log(`Ignored an event: ${error}`)
1192
+ })).then((trigger) => {
1193
+ if (trigger) store(trigger);
1194
+ }).catch((error) => {
1195
+ log(`Could not store an event: ${error.message}`);
1196
+ });
1197
+ };
1198
+ let handle;
1199
+ const stopListening = new AbortController();
1200
+ const unlisten = () => {
1201
+ stopListening.abort();
1202
+ };
1203
+ const endStream = async () => {
1204
+ unlisten();
1205
+ if (handle) await handle.ended;
1206
+ };
1207
+ if (feishu) handle = consumeEvents({
1208
+ cli: feishu.cli,
1209
+ signal: stopListening.signal,
1210
+ onMessage: receive,
1211
+ onListening: (started) => {
1212
+ handle = started;
1213
+ },
1214
+ onError: (message) => {
1215
+ if (!signal.aborted) log(message);
1216
+ }
1217
+ });
1218
+ /** Waits for the stream's next line: a line that arrives settles it, and a stream that answers nothing is idle. */
1219
+ const nextLine = () => handle ? handle.next(settings.executor.streamIdleMs) : Promise.resolve(false);
1220
+ const delivered = /* @__PURE__ */ new Set();
1221
+ engine.options.executor = executor;
1222
+ finished.handoff = (item) => {
1223
+ try {
1224
+ record(engine, repo, [item], log);
1225
+ } catch (error) {
1226
+ log(`Could not record the report for ${item.ticketId}: ${error.message}`);
1227
+ }
1228
+ };
1229
+ const inRound = /* @__PURE__ */ new Set();
1230
+ const ingest = () => {
1231
+ const waiting = repo.triggers.list().filter((trigger) => trigger.source === "feishu");
1232
+ for (const trigger of waiting) {
1233
+ inRound.add(trigger.id);
1234
+ engine.receive(trigger);
1235
+ }
1236
+ };
1237
+ let since = repo.getMeta(pollKey) ?? (/* @__PURE__ */ new Date()).toISOString();
1238
+ const pull = async () => {
1239
+ if (!feishu) return;
1240
+ for (let lines = 0; lines < MAX_LINES && !signal.aborted; lines++) if (!await nextLine()) break;
1241
+ if (signal.aborted) return;
1242
+ ingest();
1243
+ await repo.reload();
1244
+ };
1245
+ while (!signal.aborted) {
1246
+ const round = (/* @__PURE__ */ new Date()).toISOString();
1247
+ try {
1248
+ if (feishu) identify();
1249
+ ingest();
1250
+ await repo.reload();
1251
+ await pull();
1252
+ if (github) {
1253
+ const triggers = await pollNotifications({
1254
+ cli: github.cli,
1255
+ repository: github.repository,
1256
+ agent: login,
1257
+ since,
1258
+ signal,
1259
+ seen: (id) => repo.getMeta(seenKey(id)) === true,
1260
+ mark: (id) => repo.setMeta(seenKey(id), true)
1261
+ });
1262
+ for (const trigger of triggers) if (engine.receive(trigger) !== "duplicate") log(`Received ${trigger.id} from ${trigger.actor.id} on ${trigger.threads[0].id}`);
1263
+ since = round;
1264
+ repo.setMeta(pollKey, since);
1265
+ }
1266
+ engine.evaluateDue();
1267
+ advance(engine, repo, log, accepted.splice(0));
1268
+ record(engine, repo, finished.drain(), log);
1269
+ await repo.flush();
1270
+ await pull();
1271
+ inRound.clear();
1272
+ deliver(engine, repo, delivered, log);
1273
+ await repo.flush();
1274
+ await send(channel, {
1275
+ ...github ? { github: github.cli } : {},
1276
+ ...feishu ? { feishu: feishu.cli } : {}
1277
+ }, log);
1278
+ await repo.flush();
1279
+ await sync();
1280
+ } catch (error) {
1281
+ if (!signal.aborted) log(`Round failed: ${error.message}\n${error.stack?.split("\n").slice(1, 4).join("\n")}`);
1282
+ }
1283
+ if (options.once) break;
1284
+ let left = Math.min(github?.pollSeconds ?? Infinity, feishu ? 15 : Infinity) * 1e3;
1285
+ while (left > 0 && !signal.aborted) {
1286
+ const began = Date.now();
1287
+ await Promise.race([finished.wait(Math.max(1, Math.min(TURN_WAIT_MS, left))), new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
1288
+ if (finished.ready()) break;
1289
+ left -= Date.now() - began;
1290
+ }
1291
+ }
1292
+ stop.abort();
1293
+ if (feishu) await endStream();
1294
+ }
1295
+ // src/cli.ts
1296
+ /**
1297
+ * `superagent` command line: create an installation, inspect it, and run one ticket by hand.
1298
+ *
1299
+ * The command prints Markdown because people and agents both read it: an agent that needs to know what is open runs
1300
+ * `superagent status` and gets an answer it can put straight into a prompt.
1301
+ */
1302
+ const USAGE = `superagent — an agent that turns GitHub and Feishu requests into tickets
1303
+
1304
+ superagent init [dir] create ${SETTINGS_FILE} and the state directory in dir (default: .)
1305
+ superagent status [dir] print open tickets and recent activity as Markdown
1306
+ superagent doctor [dir] show which coding agents are installed and which one is selected
1307
+ superagent agents list the coding agents a configuration may name
1308
+ superagent run <dir> -p <text> run one prompt on the configured agent, in a directory it names
1309
+ superagent poll [dir] [--once] poll the Sources and run the tickets they bring, once or until interrupted
1310
+
1311
+ Every command that reads an installation takes the directory that holds ${SETTINGS_FILE}.`;
1312
+ async function exists(path) {
1313
+ try {
1314
+ await stat(path);
1315
+ return true;
1316
+ } catch {
1317
+ return false;
1318
+ }
1319
+ }
1320
+ /** The state directory a settings file names, or the default when there is no settings file. */
1321
+ async function stateDirOf(dir) {
1322
+ try {
1323
+ return (await readSettings(join(dir, SETTINGS_FILE))).stateDir;
1324
+ } catch {
1325
+ return join(dir, "state");
1326
+ }
1327
+ }
1328
+ async function init(dir) {
1329
+ const path = join(dir, SETTINGS_FILE);
1330
+ if (await exists(path)) {
1331
+ const current = await readSettings(path);
1332
+ await mkdir(current.stateDir, { recursive: true });
1333
+ await new FileRepositories(current.stateDir).open();
1334
+ process.stdout.write(`${path} already exists; kept its settings and state at ${current.stateDir}.\n`);
1335
+ return 0;
1336
+ }
1337
+ const settings = defaultSettings(resolve(dir), homedir());
1338
+ await writeSettings(path, settings);
1339
+ await mkdir(settings.stateDir, { recursive: true });
1340
+ await new FileRepositories(settings.stateDir).open();
1341
+ process.stdout.write([
1342
+ `Created ${path}.`,
1343
+ "",
1344
+ `State lives in ${settings.stateDir}.`,
1345
+ "",
1346
+ "Next: set `github.repository` and `github.allowed`, choose `executor.agent`, then run `superagent doctor`.",
1347
+ ""
1348
+ ].join("\n"));
1349
+ return 0;
1350
+ }
1351
+ async function status(dir) {
1352
+ const { tickets, threads, exists: found } = await readState(await stateDirOf(dir));
1353
+ if (!found) {
1354
+ process.stdout.write(`No state directory yet. Run \`superagent init\` first.\n`);
1355
+ return 1;
1356
+ }
1357
+ const open = tickets.filter((ticket) => ticket.ended === void 0);
1358
+ const done = tickets.filter((ticket) => ticket.ended !== void 0);
1359
+ const lines = [
1360
+ `# Superagent status`,
1361
+ "",
1362
+ `Open tickets: ${open.length} · Ended: ${done.length} · Threads: ${threads.length}`,
1363
+ ""
1364
+ ];
1365
+ if (open.length) {
1366
+ lines.push("## Open", "");
1367
+ for (const ticket of open) {
1368
+ const latest = ticket.assignments.at(-1);
1369
+ const state = latest ? latest.state : "no assignment";
1370
+ const question = ticket.attention ? ` — waiting on: ${ticket.attention.question}` : "";
1371
+ lines.push(`- \`${ticket.id}\` **${ticket.title}** (${state})${question}`);
1372
+ }
1373
+ lines.push("");
1374
+ }
1375
+ if (done.length) {
1376
+ lines.push("## Ended", "");
1377
+ for (const ticket of done.slice(-10)) lines.push(`- \`${ticket.id}\` ${ticket.title} — ${ticket.ended?.outcome} by ${ticket.ended?.by}`);
1378
+ lines.push("");
1379
+ }
1380
+ if (!tickets.length) lines.push("No tickets yet.", "");
1381
+ process.stdout.write(lines.join("\n"));
1382
+ return 0;
1383
+ }
1384
+ async function doctor(dir) {
1385
+ let settings;
1386
+ try {
1387
+ settings = await readSettings(join(dir, SETTINGS_FILE));
1388
+ } catch (error) {
1389
+ process.stderr.write(`${error.message}\n`);
1390
+ return 1;
1391
+ }
1392
+ const found = await installed();
1393
+ const lines = [
1394
+ "# Superagent doctor",
1395
+ "",
1396
+ "| Agent | Installed |",
1397
+ "| --- | --- |"
1398
+ ];
1399
+ for (const name of AGENT_NAMES) lines.push(`| ${name} | ${found[name] ? "yes" : "no"} |`);
1400
+ const chosen = settings.executor.agent;
1401
+ lines.push("", `Selected: **${chosen}**${found[chosen] ? "" : " — not installed"}`, "");
1402
+ if (settings.github) lines.push(`Repository: \`${settings.github.repository}\`, allowed logins: ${settings.github.allowed.join(", ") || "(none)"}`, "");
1403
+ const stateFound = await exists(settings.stateDir);
1404
+ lines.push(`State directory: \`${settings.stateDir}\`${stateFound ? "" : " — missing, run `superagent init`"}`, "");
1405
+ process.stdout.write(lines.join("\n"));
1406
+ return found[chosen] ? 0 : 1;
1407
+ }
1408
+ /** Runs one prompt on the configured agent and prints the report, which is how a person tests an installation. */
1409
+ async function runOne(dir, prompt) {
1410
+ const settings = await readSettings(join(dir, SETTINGS_FILE));
1411
+ const runner = runnerFor(settings.executor.agent, settings.executor.binary);
1412
+ const controller = new AbortController();
1413
+ process.on("SIGINT", () => controller.abort());
1414
+ const result = await runner.run({
1415
+ prompt: `${prompt}\n${reportInstructions()}`,
1416
+ cwd: resolve(dir),
1417
+ env: { ...process.env },
1418
+ signal: controller.signal,
1419
+ timeoutMs: settings.executor.timeoutMinutes * 6e4
1420
+ });
1421
+ process.stdout.write(`${result.report?.summary ?? result.finalText}\n`);
1422
+ if (!result.ok) process.stderr.write(`The agent exited ${result.exitCode}.\n`);
1423
+ return result.ok ? 0 : 1;
1424
+ }
1425
+ /** Runs the loop for one round or until interrupted, holding the state directory's lock for the whole run. */
1426
+ async function poll(dir, once) {
1427
+ let settings;
1428
+ try {
1429
+ settings = await readSettings(join(dir, SETTINGS_FILE));
1430
+ } catch (error) {
1431
+ process.stderr.write(`${error.message}\n`);
1432
+ return 1;
1433
+ }
1434
+ const repo = new FileRepositories(settings.stateDir = settings.stateDir);
1435
+ await repo.open();
1436
+ const controller = new AbortController();
1437
+ process.on("SIGINT", () => controller.abort());
1438
+ const log = (line) => {
1439
+ process.stdout.write(`${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)} ${line}\n`);
1440
+ };
1441
+ try {
1442
+ await runLoop({
1443
+ settings,
1444
+ repo,
1445
+ signal: controller.signal,
1446
+ log,
1447
+ ...once ? { once: true } : {}
1448
+ });
1449
+ return 0;
1450
+ } catch (error) {
1451
+ process.stderr.write(`${error.message}\n`);
1452
+ return 1;
1453
+ } finally {
1454
+ await repo.flush();
1455
+ }
1456
+ }
1457
+ async function main(argv) {
1458
+ const [command, ...rest] = argv;
1459
+ const dirOf = (index) => rest[index] && !rest[index].startsWith("-") ? resolve(rest[index]) : process.cwd();
1460
+ switch (command) {
1461
+ case "init": return init(rest[0] ? resolve(rest[0]) : process.cwd());
1462
+ case "status": return status(dirOf(0));
1463
+ case "doctor": return doctor(dirOf(0));
1464
+ case "agents":
1465
+ process.stdout.write(`${AGENT_NAMES.join("\n")}\n`);
1466
+ return 0;
1467
+ case "poll": return poll(dirOf(0), rest.includes("--once"));
1468
+ case "run": {
1469
+ const index = rest.indexOf("-p");
1470
+ if (index < 0 || !rest[index + 1]) {
1471
+ process.stderr.write(USAGE + "\n");
1472
+ return 2;
1473
+ }
1474
+ return runOne(dirOf(0), rest[index + 1]);
1475
+ }
1476
+ case void 0:
1477
+ case "-h":
1478
+ case "--help":
1479
+ case "help":
1480
+ process.stdout.write(USAGE + "\n");
1481
+ return command ? 0 : 2;
1482
+ default:
1483
+ process.stderr.write(`Unknown command: ${command}\n\n${USAGE}\n`);
1484
+ return 2;
1485
+ }
1486
+ }
1487
+ export { main };