@saltpub/agent-autoloop 0.1.4 → 0.1.7

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.en.md +10 -10
  3. package/README.md +10 -10
  4. package/SECURITY.md +1 -1
  5. package/dist/cli/dashboard/favicon.svg +8 -0
  6. package/dist/cli/dashboard/index.html +1 -0
  7. package/dist/cli/dashboard.js +44 -2
  8. package/dist/cli/explain.js +2 -0
  9. package/dist/cli/main.js +36 -21
  10. package/dist/cli/runs.js +17 -3
  11. package/dist/cli/status.js +19 -8
  12. package/dist/host/runtime.js +13 -3
  13. package/dist/host/server.js +7 -1
  14. package/dist/host/service.js +8 -2
  15. package/dist/host/settle.js +10 -0
  16. package/dist/host/state.js +51 -22
  17. package/dist/kernel/decide.js +79 -4
  18. package/dist/kernel/due.js +2 -0
  19. package/dist/kernel/evolve.js +3 -0
  20. package/dist/kernel/http.js +11 -0
  21. package/dist/kernel/query.js +7 -1
  22. package/dist/plugins/claude/agent.js +14 -1
  23. package/dist/plugins/codex/agent.js +56 -6
  24. package/dist/plugins/delivery/project.js +3 -1
  25. package/dist/plugins/delivery/review.js +7 -4
  26. package/dist/plugins/feishu/channel.js +44 -6
  27. package/dist/plugins/xiaojiu/channel.js +59 -9
  28. package/dist/protocol/client.js +6 -0
  29. package/dist/protocol/rules.js +2 -1
  30. package/dist/protocol/schema.json +12 -1
  31. package/dist/protocol/validate.js +19 -2
  32. package/dist/worker/agents.js +55 -18
  33. package/dist/worker/contract.js +1 -0
  34. package/dist/worker/worker.js +112 -34
  35. package/docs/plugins.md +4 -2
  36. package/docs/protocol.md +18 -7
  37. package/examples/plugins/hello-source/source.ts +4 -3
  38. package/examples/recipes/feishu-messages/README.md +60 -0
  39. package/examples/recipes/feishu-messages/SKILL.md +16 -0
  40. package/examples/recipes/feishu-messages/rules.json +21 -0
  41. package/examples/recipes/feishu-messages/watch.ts +157 -0
  42. package/examples/recipes/github-issues/rules.json +6 -1
  43. package/examples/recipes/github-issues/watch.ts +39 -0
  44. package/examples/recipes/ops-alerts/README.md +2 -2
  45. package/examples/recipes/ops-alerts/restart.ts +3 -0
  46. package/examples/recipes/ops-alerts/rules.json +1 -1
  47. package/examples/watch-github-issues.sh +3 -22
  48. package/package.json +1 -1
  49. package/plugins/claude/agent.ts +15 -1
  50. package/plugins/codex/agent.ts +53 -6
  51. package/plugins/delivery/project.ts +2 -1
  52. package/plugins/delivery/review.ts +7 -4
  53. package/plugins/feishu/channel.ts +50 -6
  54. package/plugins/xiaojiu/channel.ts +59 -11
  55. package/skills/agent-autoloop/SKILL.md +24 -7
  56. package/examples/recipes/ops-alerts/restart.sh +0 -5
@@ -1,14 +1,48 @@
1
1
  // Codex: the user's own, installed and signed in by them. A run is a `codex exec` in the background; its thread is kept
2
2
  // on disk, so a retry or an answer can go on in it, and the link opens it in the app.
3
3
  import { execFileSync } from "node:child_process";
4
+ import { readdirSync, statSync } from "node:fs";
5
+ import path from "node:path";
4
6
  import { commandLine, powershell, psQuote } from "../../host/command.ts";
5
7
  import { findProgram, tail, type Adapter } from "../../worker/agents.ts";
6
8
 
7
9
  const SANDBOX = { read: "read-only", edit: "workspace-write", full: "danger-full-access" };
8
- export const IN_THE_APP = [
9
- "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
10
- "/Applications/Codex.app/Contents/Resources/codex",
11
- ];
10
+
11
+ /** The Codex the desktop app installs, for those without one of their own. */
12
+ export function inTheApp() {
13
+ const mac = [
14
+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
15
+ "/Applications/Codex.app/Contents/Resources/codex",
16
+ ];
17
+ // The Windows installer puts codex.exe in %LOCALAPPDATA%\OpenAI\Codex\bin\<id>; an update adds a new <id> beside the
18
+ // old one and deletes the old one, leaving PATH naming the folder it deleted. So read that folder for the newest
19
+ // codex.exe rather than one path an update rewrites: on 2026-11-20 and 2026-11-21 both morning rules failed with
20
+ // 找不到 codex while the program sat in the folder beside the one PATH named.
21
+ const local = process.env.LOCALAPPDATA;
22
+ const root = local ? path.join(local, "OpenAI", "Codex", "bin") : null;
23
+ if (!root) return mac;
24
+ // An update is emptying these folders while this runs, so each is read on its own and one that has gone is left out:
25
+ // a throw here reaches the round as whichever path vanished rather than as 找不到 codex.
26
+ const folders = (() => {
27
+ try {
28
+ return readdirSync(root, { withFileTypes: true });
29
+ } catch {
30
+ // No Codex desktop install, or a bin this account can't read as a folder.
31
+ return [];
32
+ }
33
+ })();
34
+ const found: { file: string; at: number }[] = [];
35
+ for (const entry of folders) {
36
+ if (!entry.isDirectory()) continue;
37
+ const file = path.join(root, entry.name, "codex.exe");
38
+ try {
39
+ found.push({ file, at: statSync(file).mtimeMs });
40
+ } catch {
41
+ // A folder holding another of the app's programs, or one this update is still emptying.
42
+ }
43
+ }
44
+ return [...found.sort((a, b) => b.at - a.at).map((codex) => codex.file), ...mac];
45
+ }
12
46
 
13
47
  export default {
14
48
  command: (turn) => {
@@ -25,7 +59,7 @@ export default {
25
59
  [IO.File]::SetAccessControl($file, $acl)
26
60
  `);
27
61
  return [
28
- turn.program ?? findProgram("codex", () => IN_THE_APP),
62
+ turn.program ?? findProgram("codex", inTheApp),
29
63
  "exec",
30
64
  ...(turn.resume ? ["resume"] : []),
31
65
  "--json",
@@ -89,14 +123,27 @@ export default {
89
123
  },
90
124
  link: (session) => `codex://threads/${session}`,
91
125
  check(program) {
126
+ const exe = program ?? findProgram("codex", inTheApp);
92
127
  try {
93
- execFileSync(...commandLine([program ?? findProgram("codex", () => IN_THE_APP), "login", "status"]), {
128
+ execFileSync(...commandLine([exe, "login", "status"]), {
94
129
  encoding: "utf8",
95
130
  timeout: 20_000,
96
131
  stdio: ["ignore", "pipe", "pipe"],
97
132
  });
98
133
  return null;
99
134
  } catch (error) {
135
+ // `login status` only reads the stored login: a key from the environment (OPENAI_API_KEY, or the
136
+ // provider's env_key such as CRS_API_KEY) still runs, and `codex doctor` is what reports that.
137
+ try {
138
+ const { checks } = JSON.parse(
139
+ execFileSync(...commandLine([exe, "doctor", "--json"]), {
140
+ encoding: "utf8",
141
+ timeout: 20_000,
142
+ stdio: ["ignore", "pipe", "pipe"],
143
+ }),
144
+ );
145
+ if (checks?.["auth.credentials"]?.status === "ok") return null;
146
+ } catch {}
100
147
  return `Codex 没有登录或用不了:运行 codex login(${(error as Error).message.split("\n")[0]})`;
101
148
  }
102
149
  },
@@ -105,8 +105,9 @@ export function readMainSettings(root: string, testLocalHealth = false, ref = "o
105
105
  }
106
106
 
107
107
  function globToRegExp(pattern: string) {
108
- const parts = pattern.split(/(\*\*\/|\*)/).map((part) => {
108
+ const parts = pattern.split(/(\*\*\/|(?<=^|\/)\*\*$|\*)/).map((part) => {
109
109
  if (part === "**/") return "(?:.*/)?";
110
+ if (part === "**") return ".*";
110
111
  if (part === "*") return "[^/]*";
111
112
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
112
113
  });
@@ -5,8 +5,8 @@ import { execFile } from "node:child_process";
5
5
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { AGENT, git, matches, PLAIN_FILE_MODES, type Reviewer, type Settings } from "./project.ts";
8
- import { IN_THE_APP } from "../codex/agent.ts";
9
- import { findProgram } from "../../worker/agents.ts";
8
+ import { inTheApp } from "../codex/agent.ts";
9
+ import { findProgram, tail } from "../../worker/agents.ts";
10
10
  import { reviewCovers, reviewSignature, selectReview, type SharedPolicy } from "./review-policy.ts";
11
11
  import { ledger, OWNER, renderRound, stalled } from "./review-ledger.ts";
12
12
 
@@ -241,7 +241,7 @@ async function runReviewer(
241
241
  writeFileSync(changesFile, input.diff);
242
242
  const output = join(snapshot, "review.json");
243
243
  const { command, model } = reviewer;
244
- const codex = () => [findProgram("codex", () => IN_THE_APP), ...codexCommand(output, effort, model)];
244
+ const codex = () => [findProgram("codex", inTheApp), ...codexCommand(output, effort, model)];
245
245
  const argv = command ?? codex();
246
246
  const args = argv.slice(1).map((arg) => arg.replaceAll("{input}", changesFile));
247
247
  const child = execFile(...commandLine([argv[0], ...args]), {
@@ -249,6 +249,9 @@ async function runReviewer(
249
249
  timeout: REVIEW_MINUTES * 60_000,
250
250
  maxBuffer: 8 * 1024 * 1024,
251
251
  });
252
+ // A reviewer can stop before it reads its prompt, and a long one then fails the write. An error nobody listens for would
253
+ // end this whole run; the exit code and stderr already say why the review didn't happen.
254
+ child.stdin!.on("error", () => {});
252
255
  child.stdin!.end(input.prompt);
253
256
  const text = await new Promise<string>((resolve, reject) => {
254
257
  let stdout = "";
@@ -263,7 +266,7 @@ async function runReviewer(
263
266
  new Error(
264
267
  signal && child.killed
265
268
  ? `审查超过 ${REVIEW_MINUTES} 分钟没有完成,已停止`
266
- : `审查没有完成:${stderr.slice(-1000)}`,
269
+ : `审查没有完成:${tail(stderr, 1000)}`,
267
270
  ),
268
271
  ),
269
272
  );
@@ -8,6 +8,7 @@ import { setTimeout as wait } from "node:timers/promises";
8
8
  import type { Card, ChannelContext } from "../../host/channels.ts";
9
9
  import { eachLine } from "../../host/lines.ts";
10
10
  import { commandLine } from "../../host/command.ts";
11
+ import { fit } from "../../worker/contract.ts";
11
12
 
12
13
  /** Feishu sends these values as JSON in a string, which may be empty. */
13
14
  function safeJson(text: unknown): any {
@@ -27,6 +28,35 @@ function outcomeOf(card: Card) {
27
28
  return card.state === "closed" && card.result ? card.result : null;
28
29
  }
29
30
 
31
+ /** What lark-cli said, on one line and short enough for a log, without cutting a character in half. */
32
+ const oneLine = (text: unknown) =>
33
+ fit(
34
+ String(text ?? "")
35
+ .replace(/\s+/g, " ")
36
+ .trim(),
37
+ 300,
38
+ );
39
+
40
+ /**
41
+ * A failure as the reason and the next thing to do: the CLI's error body is JSON meant for a program, not the reader.
42
+ * The bot's permissions come from the app's settings in Feishu's developer console, and signing in again doesn't change
43
+ * them; only the user identity is fixed by lark-cli auth login.
44
+ */
45
+ function explain(where: string, body: any, failure: Error | undefined, printed: string, identity?: string) {
46
+ const type = typeof body?.type === "string" ? body.type : "";
47
+ const said = typeof body?.message === "string" ? oneLine(body.message) : "";
48
+ const because = [type, said].filter(Boolean).join(":");
49
+ if (type === "authorization" || type === "authentication") {
50
+ const page = typeof body?.console_url === "string" ? `:${oneLine(body.console_url)}` : "";
51
+ const hint = typeof body?.hint === "string" ? oneLine(body.hint) : "";
52
+ return identity === "bot"
53
+ ? `${where} 没通过飞书授权(${because}):在飞书开发者后台给这个应用开通所需权限${page}`
54
+ : `${where} 没通过飞书授权(${because}):${hint || "在这台电脑运行 lark-cli auth login 重新登录"}`;
55
+ }
56
+ if (because) return `${where} 失败:飞书说 ${because}`;
57
+ return `${where} 失败:${(oneLine(printed) || oneLine(failure?.message)).replace(/^Error:\s*/, "") || "没有说明原因"}`;
58
+ }
59
+
30
60
  /** One card, as it looks now: the options while it's open, what became of it after. */
31
61
  export function render(card: Card) {
32
62
  const outcome = outcomeOf(card);
@@ -104,19 +134,33 @@ export function render(card: Card) {
104
134
  export default async function feishu({ hub, options, log, signal }: ChannelContext) {
105
135
  const program = (options.lark as string | undefined) ?? "lark-cli";
106
136
  const lark = async (args: string[], input?: string) => {
107
- const printed = await new Promise<string>((resolve, reject) => {
137
+ const ran = await new Promise<{ failure?: Error; stdout: string; stderr: string }>((resolve) => {
108
138
  const child = execFile(
109
139
  ...commandLine([program, ...args]),
110
140
  { encoding: "utf8", timeout: 60_000, signal },
111
- (error, stdout) => (error ? reject(error) : resolve(stdout)),
141
+ (failure, stdout, stderr) => resolve({ failure: failure ?? undefined, stdout, stderr }),
142
+ );
143
+ child.stdin!.on(
144
+ "error",
145
+ input === undefined ? () => {} : (failure) => resolve({ failure, stdout: "", stderr: "" }),
112
146
  );
113
- child.stdin!.on("error", input === undefined ? () => {} : reject);
114
147
  child.stdin!.end(input);
115
148
  });
116
- const out = JSON.parse(printed);
117
- if (out.ok === false || out.error) {
118
- throw new Error(`lark-cli ${args.slice(0, 3).join(" ")}: ${JSON.stringify(out.error ?? out).slice(0, 300)}`);
149
+ const where = `lark-cli ${args.slice(0, 3).join(" ")}`;
150
+ // What it did is on stdout; what went wrong is on stderr, and an error body can come with either exit code.
151
+ const printed = ran.failure ? ran.stderr : ran.stdout;
152
+ let out: any;
153
+ try {
154
+ out = JSON.parse(printed);
155
+ } catch {
156
+ out = null;
119
157
  }
158
+ const identity =
159
+ typeof out?.identity === "string" ? out.identity : args.includes("--as") ? args[args.indexOf("--as") + 1] : "";
160
+ if (out?.ok === false || out?.error)
161
+ throw new Error(explain(where, out.error ?? out, ran.failure, printed, identity));
162
+ if (ran.failure) throw new Error(explain(where, null, ran.failure, printed));
163
+ if (!out) throw new Error(`${where} 失败:返回的不是 JSON(${oneLine(printed) || "没有输出"})`);
120
164
  return out;
121
165
  };
122
166
  const owner = (options.user as string | undefined) ?? (await lark(["auth", "status"], "")).identities?.user?.openId;
@@ -3,11 +3,18 @@
3
3
  // as `card_action_trigger` callbacks; there is no signature, so the path has to be unguessable, reachable only through
4
4
  // HTTPS in front of it, and the clicker has to be in this channel's answerers. Several bots may share one listener: the
5
5
  // callback's header.appId decides which channel answers. The send API has no idempotency key, so a lost delivery report
6
- // can make a second message. Card messages are updated in place from the session the send response or the click carries;
6
+ // can make a second message. Sends try `/open/im/v1/messages` first and fall back to `/open/im/v2/messages`.
7
+ // Card messages are updated in place from the session the send response or the click carries;
7
8
  // markdown bodies cannot be patched, so those only report the new version. API contract: https://im-document.4399om.com
8
9
  // config.json: "channels": { "xiaojiu": { "use": "xiaojiu", "key": "…", "appId": "…", "appSecret": "…",
9
10
  // "session": "<snSessionId>" } } — or "staffNo": "GZ1234" for a private chat
10
- // optional "webhook": { "listen": "0.0.0.0:9700", "path": "/xiaojiu/<unguessable>" }
11
+ // optional "webhook": { "listen": "0.0.0.0:9700", "path": "/xiaojiu/<unguessable>",
12
+ // "forward": "http://127.0.0.1:65532/webhook/<profile>" }
13
+ // "forward" gets every callback that isn't a click on a button this channel drew — message_receive, clicks on
14
+ // someone else's card messages — re-POSTed as the same JSON. One bot has one callback URL, so a bot shared with
15
+ // another program (a chat bridge) points at this channel and this channel hands the rest along; a failed forward
16
+ // answers 500 and the platform retries, which the receiver's own event-id dedupe absorbs. Without "forward" those
17
+ // callbacks get a plain 200 and go nowhere.
11
18
  // rules.json: "channels": { "xiaojiu": { "name": "小九", "links": true, "answerers": ["GZ1234"] } }
12
19
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
13
20
  import type { Card, ChannelContext } from "../../host/channels.ts";
@@ -36,6 +43,7 @@ type Route = {
36
43
  path: string;
37
44
  log: (line: string) => void;
38
45
  answer: (click: Click) => Promise<void>;
46
+ forward?: string;
39
47
  };
40
48
  type Listener = { server: Server; url: string; routes: Set<Route> };
41
49
 
@@ -83,7 +91,7 @@ function bind(listen: string): Promise<Listener> {
83
91
  }
84
92
 
85
93
  async function joinWebhook(
86
- options: { listen?: unknown; path?: unknown },
94
+ options: { listen?: unknown; path?: unknown; forward?: unknown },
87
95
  appId: string,
88
96
  log: (line: string) => void,
89
97
  answer: (click: Click) => Promise<void>,
@@ -92,6 +100,10 @@ async function joinWebhook(
92
100
  const path = typeof options.path === "string" ? options.path.trim() : "";
93
101
  if (!listen) throw new Error("webhook.listen 要写 主机:端口");
94
102
  if (!path.startsWith("/") || /\s/.test(path)) throw new Error(`webhook.path 要以 / 开头、不含空白:${path}`);
103
+ const forward = typeof options.forward === "string" ? options.forward.trim() : "";
104
+ if (forward && !/^https?:\/\/\S+$/.test(forward)) {
105
+ throw new Error(`webhook.forward 要写 http(s) 地址:${forward}`);
106
+ }
95
107
  let pending = listeners.get(listen);
96
108
  if (!pending) {
97
109
  pending = bind(listen);
@@ -102,9 +114,9 @@ async function joinWebhook(
102
114
  if ([...listener.routes].some((route) => route.appId === appId && route.path === path)) {
103
115
  throw new Error(`webhook 已经有 appId ${appId} 在 ${path}`);
104
116
  }
105
- const route: Route = { appId, path, log, answer };
117
+ const route: Route = { appId, path, log, answer, ...(forward ? { forward } : {}) };
106
118
  listener.routes.add(route);
107
- log(`webhook 在 ${listener.url}${path} 收卡片回答(appId ${appId})`);
119
+ log(`webhook 在 ${listener.url}${path} 收卡片回答(appId ${appId})${forward ? `,其余回调转发 ${forward}` : ""}`);
108
120
  return async () => {
109
121
  listener.routes.delete(route);
110
122
  if (listener.routes.size) return;
@@ -131,10 +143,17 @@ async function handleRequest(request: IncomingMessage, response: ServerResponse,
131
143
  const known = [...listener.routes].some((candidate) => candidate.path === pathname);
132
144
  return reply(response, known ? 403 : 404, { error: known ? "this appId isn't this path's bot" : "not found" });
133
145
  }
134
- if (text(record(header)?.type) !== "card_action_trigger") return reply(response, 200, { ok: true });
135
- const click = cardClick(body);
146
+ const type = text(record(header)?.type) ?? "未知类型";
147
+ const click = type === "card_action_trigger" ? cardClick(body) : null;
136
148
  if (!click) {
137
- route.log("xiaojiu 回调里没有能回答卡片的按钮信息,已忽略");
149
+ // Ours only if it's a press on a button this channel drew. Everything else — chat messages, presses on card
150
+ // messages another program sent through the same bot — belongs to the forward address when there is one.
151
+ if (route.forward) {
152
+ if (await forwardTo(route.forward, body)) return reply(response, 200, { ok: true });
153
+ route.log(`转发 ${type} 回调到 ${route.forward} 失败`);
154
+ return reply(response, 500, { error: "forward failed" });
155
+ }
156
+ if (type === "card_action_trigger") route.log("xiaojiu 回调里没有能回答卡片的按钮信息,已忽略");
138
157
  return reply(response, 200, { ok: true });
139
158
  }
140
159
  try {
@@ -154,6 +173,21 @@ async function handleRequest(request: IncomingMessage, response: ServerResponse,
154
173
  }
155
174
  }
156
175
 
176
+ /** A callback this channel doesn't own goes to the configured address as the same JSON. false: the platform retries. */
177
+ async function forwardTo(url: string, body: unknown) {
178
+ try {
179
+ const response = await fetch(url, {
180
+ method: "POST",
181
+ headers: { "content-type": "application/json" },
182
+ body: JSON.stringify(body),
183
+ signal: AbortSignal.timeout(10_000),
184
+ });
185
+ return response.ok;
186
+ } catch {
187
+ return false;
188
+ }
189
+ }
190
+
157
191
  class BadRequest extends Error {
158
192
  readonly status: number;
159
193
  constructor(status: number, message: string) {
@@ -287,7 +321,7 @@ export default async function xiaojiu({ hub, options, log, signal }: ChannelCont
287
321
  const appSecret = options.appSecret as string | undefined;
288
322
  const session = options.session as string | undefined;
289
323
  const staffNo = options.staffNo as string | undefined;
290
- const webhook = options.webhook as { listen?: unknown; path?: unknown } | undefined;
324
+ const webhook = options.webhook as { listen?: unknown; path?: unknown; forward?: unknown } | undefined;
291
325
  if (!appId || !appSecret || (!session && !staffNo)) {
292
326
  throw new Error("xiaojiu 通道要在 config.json 写 appId、appSecret,以及 session(群会话)或 staffNo(私聊工号)");
293
327
  }
@@ -339,6 +373,21 @@ export default async function xiaojiu({ hub, options, log, signal }: ChannelCont
339
373
  }
340
374
  }
341
375
 
376
+ /** v1 is the documented endpoint; v2 takes what v1 refuses, so it is the fallback only. Whichever answers, the
377
+ * caller hears one outcome: only both refusing is a failure, and only then does the hub start its one-minute retry. */
378
+ async function send(body: unknown): Promise<unknown> {
379
+ try {
380
+ return await post("/open/im/v1/messages", body);
381
+ } catch (error) {
382
+ log(`xiaojiu v1 发送失败,改用 v2:${error}`);
383
+ try {
384
+ return await post("/open/im/v2/messages", body);
385
+ } catch (fallback) {
386
+ throw new Error(`v1:${error};v2:${fallback}`);
387
+ }
388
+ }
389
+ }
390
+
342
391
  // Where each card message lives: the platform's message id -> its session, learned when we sent it.
343
392
  const locations = new Map<string, string>();
344
393
  let lastSession = session;
@@ -390,8 +439,7 @@ export default async function xiaojiu({ hub, options, log, signal }: ChannelCont
390
439
  continue;
391
440
  }
392
441
  try {
393
- const envelope = await post(
394
- "/open/im/v2/messages",
442
+ const envelope = await send(
395
443
  webhook
396
444
  ? {
397
445
  ...(session ? { snSessionId: session } : { receiveId: staffNo }),
@@ -11,6 +11,8 @@ description: 配置 Agent 自动化中台:加规则、接新的事件插件、
11
11
 
12
12
  `agent-autoloop status` 列出谁在线、等用户什么、在做什么、做过什么,还有按完成时间统计的今天和最近 7 天的轮数、Token 和费用(Token 含缓存,写出其中缓存占多少;同一轮重试的已报用量相加,没上报的轮数会写出来)。终端里它带颜色,接管道、被 Agent 调用或设了 `NO_COLOR` 时是纯文本。`agent-autoloop status --json` 输出 `/v1/state` 的原样结构,给脚本和看板用。`agent-autoloop answer <卡片> <序号>` 回答,`agent-autoloop resolve <卡片> <结果>` 结案,`agent-autoloop stop <第几轮>` 停掉一轮,等整个进程组退出才报告已停。
13
13
 
14
+ 用户说 Agent 额度用完了、中台还在一轮轮派活时:内置的 Claude Code 插件已经会报恢复时间,中台到那时前不派活给这个 Agent,排着的事件到点自动接着做,不用暂停规则或调小 `parallel`;`status` 在这个 Agent 后面写着几点恢复。想提前试,对用它的一条规则 `agent-autoloop run`,跑通就恢复派活。别的 CLI 要有这个行为,在它的插件 `read` 里返回 `limitedUntil`(见 `docs/plugins.md`)。
15
+
14
16
  续接会话也只算这次新增的用量。`~/.agent-autoloop/worker/usage/` 存着相减要用的累计值,没有记录的续接(比如删了这个目录)这次不报 Codex 的 Token 和 Claude Code 的费用,下一次恢复正常。本人打开链接在同一个会话里接着聊用掉的量,会算进下一次续接。旧回执不重算。
15
17
 
16
18
  中台自己不画界面。用户想要一个页面看全局,先让他运行 `agent-autoloop dashboard`(本机只读看板,默认 `http://127.0.0.1:3351`,`--port` 换端口,`--no-open` 不打开浏览器);不够用再写一个:读 `GET /v1/state`,密钥是 `config.json` 的 `owner`,要跟着变化就从状态里的 `seq` 接 `GET /v1/stream?after=<seq>`,请求见 `docs/protocol.md` 的「本人」一节。
@@ -23,18 +25,31 @@ description: 配置 Agent 自动化中台:加规则、接新的事件插件、
23
25
 
24
26
  ```json
25
27
  { "name": "处理 issue", "when": { "source": "github", "types": ["issues.opened"] }, "to": "claude", "cwd": "~/code/app", "skill": "handle-issue", "parallel": 3 }
26
- { "name": "早报", "when": { "cron": "0 9 * * *" }, "to": "codex", "cwd": "~/notes", "prompt": "写今天的早报。" }
28
+ { "name": "早报", "when": { "cron": "0 9 * * *" }, "to": "codex", "cwd": "~/notes", "prompt": "写今天的早报。", "tell": "always" }
27
29
  ```
28
30
 
29
- - 同一个对象的事件要分开处理、互不等待,就写 `parallel`。一台接单程序同时跑几轮还受 `config.json` 的 `worker.capacity` 限制,默认 2,要多跑就一起调大。
31
+ - `tell` 只能是字符串 `"always"`(每轮做成都发)、`"needed"`(只在有卡片时,默认)或 `"never"`(只压住回执里的通知),不是 `true` 或 `false`;提问和中台自己的告警不受 `never` 影响。
32
+ - 一轮的结论只有最后一条消息的第一行:`tell: "always"` 发的那张卡正文就是这一行,第二行起的内容不进结论,只留在轮次输出文件里(结束后留 14 天)。要让人看到正文(汇总表、完整报告),在规则的 `prompt` 或手册里要求 Agent 把它写进回执的 `notice`,第一行只写一句能独立成立的话,不要写「以下是……」这种引子。
33
+ - `when` 只能写事件或定时其中一种。事件的 `types` 是字符串列表,写具体类型、`x.*`(前缀匹配)或 `*`(全部);定时只写 `{ "cron": "0 9 * * *" }`,不要再加 `source`、`types`。
34
+ - 定时规则大部分是「先看看有没有、有才动手」时,把检查拆给 `use: "command"` 的脚本规则(写上 `emits`,范本见 `examples/recipes/github-issues/`):脚本不花 Token,有发现才发事件,监听事件的 LLM 规则才动手。活本身就是 LLM 干的(写早报、做摘要)不用拆。
35
+ - 允许回执发事件时写 `"emits": { "source": "github", "types": ["issues.labeled"] }`;`source` 要是已登记的来源,不能是保留的 `schedule`,不写 `emits` 就不能发。
36
+ - 同一个对象的事件要分开处理、互不等待,就写 `parallel`,值要是正整数。一台接单程序同时跑几轮还受 `config.json` 的 `worker.capacity` 限制,默认 2,要多跑就一起调大。
30
37
  - 对话这类要马上回的活,不想排在批量的长任务后面:把批量的规则都写进同一个 `group`,`parallel` 写得比 `worker.capacity` 小,留下的名额长任务占不了,对话来了直接领。比如 `capacity` 是 4,批量那组写 `"group": "batch", "parallel": 3`。同一组的规则 `parallel` 写成一样的。
31
38
  - 同组一共并行三轮,但单条规则每次只跑一轮时,在规则里加 `"maxActive": 1`。每个对象仍单独排队。在 `agents` 里也可以给单个 Agent 加 `maxActive`,限制它跨规则同时跑几轮。
32
39
  - 同一个对象的新事件要接着上一轮的会话(比如同一个对话的后续消息),就写 `"resume": true`;默认每次开新会话。上一轮被停掉、可能还在跑或者换了 Agent 时开新的。不写 `parallel` 时整条规则的事件都接同一个会话。
40
+ - 规则多了要分组(按项目、团队)时,给规则写 `"tags": ["shop"]`:中台不解释,只原样带进 `/v1/state` 的规则、轮次和卡片,以及这条规则每一轮的资料文件。规则放在一个 `rules.json` 里;几份分开维护的,合并成一份再换上去,先用 `agent-autoloop check` 校验。
33
41
  - 一个事项一轮开一个会话、客户端里的会话名字都一样分不清时,给规则写 `"title": "tapd-{id}-测试"`:它单独占提示词第一行,`{subject}` 换成事件的对象,`{id}` 换成对象按 `/ # :` 分开的最后一段。要是字母或数字开头、不含空白的一个词。
34
42
  - 要停一条规则,用 `agent-autoloop pause <规则> --reason …`(到点自动恢复加 `--until`),恢复用 `resume <规则>`,现在就跑一轮用 `run <规则>`;不用为了停规则去改 `rules.json`。暂停期间来的事件这条规则不接、也不排队;`resume` 会列出这次暂停跳过的事件,有就如实告诉用户;用户说要补,再运行它给出的 `agent-autoloop replay <规则> --since <时间>`,一次补完、每条只补一次,不用 `run` 一条条补。
35
43
  - 改规则前可以先写成草稿,用 `agent-autoloop check <草稿>` 校验,不影响正在跑的中台。
36
44
  - 默认的先问清单是 `askFirst`,用户说什么事必须先问他,就改这里。
37
- - 用户在别的地方定时跑的任务(Claude、Codex 应用里),写进 `elsewhere`,只在 `agent-autoloop status` 里列出来;它们要找用户时运行 `agent-autoloop tell <编号> --task <任务名>`,内容从标准输入传。要用户拍板的,给这个任务写上 `cwd` 和 `skill` 或 `prompt`,任务里运行 `agent-autoloop ask --task <任务名>`,标准输入传回执那样的 `ask`:卡片带选项,用户点了,中台叫醒它的 Agent 在 `cwd` 照 `skill`、`prompt` 接着做,回答在这一轮资料文件的 `answers` 里。
45
+
46
+ 用户在别的地方定时跑的任务(Claude、Codex 应用里),写进 `elsewhere`,只在 `agent-autoloop status` 里列出来。每一项必填 `name`、`source`、`to`、`cron`、`where`,例如:
47
+
48
+ ```json
49
+ { "name": "每周清理", "source": "shop", "to": "claude", "cron": "0 6 * * 0", "where": "Claude 应用的定时任务", "cwd": "~/code/shop", "skill": "weekly-sweep" }
50
+ ```
51
+
52
+ `source` 和 `to` 用已登记的编号,`where` 是显示用的说明。这些任务要找用户时运行 `agent-autoloop tell <编号> --task <任务名>`,内容从标准输入传。要用户拍板的,给这个任务写上 `cwd` 和 `skill` 或 `prompt`,任务里运行 `agent-autoloop ask --task <任务名>`,标准输入传回执那样的 `ask`:卡片带选项,用户点了,中台叫醒它的 Agent 在 `cwd` 照 `skill`、`prompt` 接着做,回答在这一轮资料文件的 `answers` 里。
38
53
 
39
54
  现成场景和内置插件从 [README](../../README.md#拿来即用的场景模板)进入,开发示例见[写插件](../../docs/plugins.md)。用户想接自动化时先从例子改,不要从零写:`examples/recipes/` 里有早报(`morning-brief`)、处理 GitHub issue(`github-issues`)、线上报错(`ops-alerts`)、反馈处理(`feedback`)、网站巡检(`website-watch`)、飞书周报与业务摘要(`feishu-brief`)和 Claude 浏览器交接(`browser-handoff`),每个都有规则、Skill 和写明权限原因的 README。反馈、巡检、飞书摘要和浏览器交接默认飞书本人私聊;按模板说明替换虚构标识,业务资料留在私有目录,读取用本人身份,通知用机器人身份。要写新的 Agent、通道或事件插件,看教程 `docs/plugins.md` 和最小例子 `examples/plugins/`。
40
55
 
@@ -53,7 +68,7 @@ description: 配置 Agent 自动化中台:加规则、接新的事件插件、
53
68
 
54
69
  1. **对方能发 HTTP**:`agent-autoloop key new source <名字>` 拿密钥(这是新建密钥,先问用户),`rules.json` 的 `sources` 登记,对方 `POST /v1/events`。对方要知道这件事后来做完没有、结论是什么,用同一把密钥 `GET /v1/events/<应答里的 event>`,不用给它本人的密钥。
55
70
  2. **对方有自己的 Webhook 格式**:在 `~/.agent-autoloop/plugins/<名字>/source.ts` 写一个函数,验签并翻译成事件(见 `plugins/github/source.ts`),来源写 `"adapter": "<名字>"`,地址是 `/v1/in/<来源>`,秘密放 `~/.agent-autoloop/secrets.env` 的 `AGENT_AUTOLOOP_SECRET_<来源>`(来源名转大写,`-` 换成 `_`),改完重启中台(`agent-autoloop service install`)。对方要能连到中台,所以中台要在服务器上,或者用隧道。
56
- 3. **对方推不过来,或者中台在家里**:定时跑一段脚本轮询,见 `examples/watch-github-issues.sh`。规则用 `use: "command"` 的 Agent,写上 `emits`。没新东西不花 Token。
71
+ 3. **对方推不过来,或者中台在家里**:定时跑一段脚本轮询,见 `examples/recipes/github-issues/watch.ts`(规则里写 `["node", "<路径>", "owner/repo"]`,Windows 也能跑)。规则用 `use: "command"` 的 Agent,写上 `emits`。没新东西不花 Token。
57
72
 
58
73
  ## 接一个 Agent
59
74
 
@@ -65,7 +80,9 @@ description: 配置 Agent 自动化中台:加规则、接新的事件插件、
65
80
 
66
81
  退出码不是 0 算没跑成。要会话接续、打开会话的链接和用量统计,在 `~/.agent-autoloop/plugins/<名字>/agent.ts` 写一个插件(照 `plugins/codex/agent.ts`):`command` 给命令行,`read` 从输出读最后一条消息和会话,Agent 收下提示词后带上 `started: true`(否则干到一半断了会开新会话重做),`link` 给链接。
67
82
 
68
- `access` 默认 `edit`,专用插件翻译成对应 CLI 的权限;`command` 只传参数,不替任意程序限制权限,按该 CLI 文档配置。要完整权限、不审批的话写 `full`,先和用户说清楚。
83
+ `access` 只能是字符串 `"read"`、`"edit"`(默认)或 `"full"`,不是布尔值;专用插件把它翻译成对应 CLI 的权限。`command` 只传参数,不替任意程序限制权限,按该 CLI 文档配置。要完整权限、不审批的话写 `"full"`,先和用户说清楚。
84
+
85
+ 专用插件的 `model`、`effort`、`tier` 都是可选字符串,例如 `"effort": "high"`;`tier` 只有 Codex 插件使用,原样传成它的 `service_tier`,如 `"priority"`。ACP 和 ZCode 的模型设置例外见下文。
69
86
 
70
87
  内置的 Claude Code、Codex、OpenCode、pi、OMP、DeepSeek Harness 要走第三方网关、代理,或者启动前要先设好环境变量:写一个小脚本,设好变量再 `exec claude "$@"`(Codex、OpenCode、pi、OMP、DSH 照此换成 `codex`、`opencode`、`pi`、`omp`、`dsh`),Agent 里写 `"program": "脚本的绝对路径"`。插件照旧解析输出、续接会话、统计用量,只是启动的是这个脚本;不用改成 `use: "command"`。令牌放在脚本读的文件里,不写进 `rules.json`。接单程序启动 Agent 前会去掉继承来的 `CLAUDE_CODE_*` 变量,要用的写在脚本里。`agent-autoloop doctor` 也用这个脚本检查登录。脚本能读到 `AGENT_AUTOLOOP_RUN`(第几轮)和 `AGENT_AUTOLOOP_CONTEXT`(资料文件),比如按轮次准备工作目录再 `cd` 进去。
71
88
 
@@ -106,7 +123,7 @@ Claude 主任务要委托 Codex 操作网页时,从 `examples/recipes/browser-
106
123
 
107
124
  同一个飞书应用的卡片点击只能有一个监听,只在一台电脑上跑。重启后日志说“飞书那边还记着这个应用的另一条事件连接”,是飞书还没放开旧连接,可能要几个小时;中台每分钟重试一次,期间卡片点击收不到。`lark-cli event status`、`event stop` 只管本机,管不了飞书那边的旧连接;别的电脑也在跑这个应用的监听就先停掉它。
108
125
 
109
- **小九(4399 IM)**:内置 `plugins/xiaojiu/channel.ts`。`config.json` 写开放平台的 `appId`、`appSecret`,以及 `session`(群会话)或 `staffNo`(私聊工号)。不配 `webhook` 时卡片发成 Markdown 文字,回答走卡片链接,`rules.json` 要写 `"links": true`。配了 `webhook`(`{ "listen": "0.0.0.0:9700", "path": "/xiaojiu/<猜不到的路径>" }`)时发卡片消息,选项和通知的“已处理”是按钮;平台把点击以 `card_action_trigger` POST 回 `path`,`header.appId` 决定交给哪个通道,多个 bot 可以共用一个监听地址和路径。回调没有签名,路径要不可猜、前面加 HTTPS,`answerers` 写允许点击的工号。回答后卡片消息原地更新;Markdown 消息平台不能改。同一个应用只在一台电脑上收回调。
126
+ **小九(4399 IM)**:内置 `plugins/xiaojiu/channel.ts`。`config.json` 写开放平台的 `appId`、`appSecret`,以及 `session`(群会话)或 `staffNo`(私聊工号)。不配 `webhook` 时卡片发成 Markdown 文字,回答走卡片链接,`rules.json` 要写 `"links": true`。配了 `webhook`(`{ "listen": "0.0.0.0:9700", "path": "/xiaojiu/<猜不到的路径>" }`)时发卡片消息,选项和通知的“已处理”是按钮;平台把点击以 `card_action_trigger` POST 回 `path`,`header.appId` 决定交给哪个通道,多个 bot 可以共用一个监听地址和路径。回调没有签名,路径要不可猜、前面加 HTTPS,`answerers` 写允许点击的工号。回答后卡片消息原地更新;Markdown 消息平台不能改。同一个应用只在一台电脑上收回调。一个 bot 只有一个回调地址:同一个 bot 还要给别的程序(如 xiaojiu-agent-bridge 聊天桥)用时,在 `webhook` 里加 `"forward": "http://127.0.0.1:65532/webhook/<bridge 的 profile 名>"`,平台回调指向本通道,本通道收到不是自己按钮的回调(`message_receive`、外来卡片的点击)原样转发过去,转发失败回 500 让平台重试;不配 `forward` 时这些回调回 200 丢弃。bridge 侧不用改:回调无签名,它认 body 里的 appId 和事件编号去重,profile 的 cwd、权限、提示词都在它自己配置里。
110
127
 
111
128
  **只会发文字的(钉钉、企微的群机器人,Slack、Discord 的 Webhook)**:用 `plugins/webhook/channel.ts`,`config.json` 的通道项写 `"use": "webhook"`、`"platform": "dingtalk"` 和 `"url": "已有的 Webhook 地址"`;平台也可选 `wecom`、`slack`、`discord`。别的平台只要收 JSON POST 也能接:不写 `platform`,写 `url` 和带 `{text}` 的 `body`,比如 Telegram 写 `"url": "https://api.telegram.org/bot<机器人令牌>/sendMessage"`、`"body": { "chat_id": "…", "text": "{text}" }`。`rules.json` 里写 `"links": true`,卡片链接本身就能回答;`config.json` 的 `hub.publicUrl` 要配成手机或电脑能打开的地址。
112
129
 
@@ -243,7 +260,7 @@ MCP 服务不区分调用方,都按本人记录(`answer` 记成本人,`emi
243
260
 
244
261
  电脑不用开放任何端口,它们自己连过去。
245
262
 
246
- 服务器上自己写的系统级 systemd unit,名字要和 `agent-autoloop service install` 用的一样(默认 `agent-autoloop`),`doctor` 才认得出。`agent-autoloop update` 不碰它,更新后自己运行 `systemctl restart` 才会用上新版。npm 安装的副本会自己检查更新,新版本等手上的轮次跑完再换、起不来退回上一版,见 `docs/auto-update.md`。
263
+ 服务器上自己写的系统级 systemd unit,名字要和 `agent-autoloop service install` 用的一样(默认 `agent-autoloop`),`doctor` 才认得出。`agent-autoloop update`、再跑一遍安装命令和 `service install` 都不碰它,只提示你自己运行 `systemctl restart`,运行后才会用上新版。npm 安装的副本会自己检查更新,新版本等手上的轮次跑完再换、起不来退回上一版,见 `docs/auto-update.md`。
247
264
 
248
265
  ## 日志与恢复
249
266
 
@@ -1,5 +0,0 @@
1
- #!/bin/sh
2
- # The one thing here that touches production. It runs outside any sandbox, as you, whatever access the Agent has.
3
- # It can run twice: a failure is tried again, and the hub only promises at least once.
4
- set -e
5
- echo "这是占位脚本,还没有真的重启。把这一行换成你的重启命令和健康检查,第一行输出会发给你。"