@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
@@ -316,10 +316,16 @@ export function systemUnit() {
316
316
  return null;
317
317
  return spawnSync("systemctl", ["is-active", "--quiet", label()], { stdio: "ignore" }).status === 0 ? label() : null;
318
318
  }
319
+ /** A system-level unit running this, and no service of ours: installing one beside it would start a second hub. */
320
+ export function leftToSystem() {
321
+ const name = systemUnit();
322
+ return name && !serviceRunning()
323
+ ? `这台电脑用的是系统级服务,运行 systemctl restart ${name} 才会用上新版。`
324
+ : undefined;
325
+ }
319
326
  /** New code counts once what's running starts again. What can't be restarted from here is said back, for the owner. */
320
327
  export function restartService() {
321
328
  if (serviceRunning())
322
329
  return void installService();
323
- const name = systemUnit();
324
- return name ? `这台电脑用的是系统级服务,运行 systemctl restart ${name} 才会用上新版。` : undefined;
330
+ return leftToSystem();
325
331
  }
@@ -0,0 +1,10 @@
1
+ /** Runs once after calls stop for `window` ms: a file written in steps is read whole, not half-written. */
2
+ export function settled(run, window) {
3
+ let timer;
4
+ const schedule = () => {
5
+ clearTimeout(timer);
6
+ timer = setTimeout(run, window);
7
+ };
8
+ schedule.cancel = () => clearTimeout(timer);
9
+ return schedule;
10
+ }
@@ -16,6 +16,7 @@ const VIEWS = {
16
16
  seen: "kind name seen_at",
17
17
  keys: "kind name hash created_at",
18
18
  pauses: "name by reason since until",
19
+ limits: "agent until reason since",
19
20
  };
20
21
  /** Made anew at every start, so changing them takes no rebuild and no migration. */
21
22
  export const viewStatements = Object.entries(VIEWS).map(([table, columns]) => {
@@ -90,6 +91,42 @@ export function skippedOf(all, rule, since, everything = false) {
90
91
  const events = all(`${columns} ${SKIPPED_BY} ${order}`, [since, rule, rule]);
91
92
  return { count, events: events.map(skippedView) };
92
93
  }
94
+ /** A rule's tags by its name, as the rules are now: none for one without them or no longer there. */
95
+ function tagsOf(rules) {
96
+ const tags = new Map(rules.rules.map((rule) => [rule.name, rule.tags ?? []]));
97
+ return (rule) => tags.get(rule) ?? [];
98
+ }
99
+ function runView(run, all, tags) {
100
+ return {
101
+ id: run.id,
102
+ rule: run.rule,
103
+ tags,
104
+ agent: run.agent,
105
+ state: run.state,
106
+ attempts: run.attempts,
107
+ createdAt: run.created_at,
108
+ claimedAt: run.claimed_at,
109
+ finishedAt: run.finished_at,
110
+ notBefore: run.not_before,
111
+ summary: run.summary ?? "",
112
+ error: run.error ?? "",
113
+ link: run.link ?? "",
114
+ session: run.session,
115
+ usage: run.usage ? JSON.parse(run.usage) : null,
116
+ stopping: run.cancel_at !== null,
117
+ manual: Boolean(run.manual),
118
+ events: all(EVENTS_OF_RUN, [run.id]),
119
+ };
120
+ }
121
+ export function ruleHistory(all, rules, rule, before) {
122
+ const limit = 20;
123
+ const rows = all(`SELECT * FROM runs WHERE rule = ? AND state NOT IN ('queued', 'claimed') ${before === undefined ? "" : "AND id < ?"}
124
+ ORDER BY id DESC LIMIT ?`, before === undefined ? [rule, limit + 1] : [rule, before, limit + 1]);
125
+ return {
126
+ runs: rows.slice(0, limit).map((run) => runView(run, all, tagsOf(rules)(rule))),
127
+ nextBefore: rows.length > limit ? rows[limit - 1].id : null,
128
+ };
129
+ }
93
130
  export function stateOf(now, before, rules, { all, view, unrouted }) {
94
131
  const seen = new Map(all("SELECT kind, name, seen_at FROM seen").map((row) => [`${row.kind}:${row.name}`, row.seen_at]));
95
132
  const presence = (who) => {
@@ -126,6 +163,7 @@ export function stateOf(now, before, rules, { all, view, unrouted }) {
126
163
  const { by, reason, since, until, skipped } = pause;
127
164
  return { by, reason, since, until, skipped };
128
165
  };
166
+ const tags = tagsOf(rules);
129
167
  const skippedAt = new Map(all("SELECT rule, skipped_at FROM schedules").map((row) => [row.rule, row.skipped_at]));
130
168
  return {
131
169
  now: iso(now),
@@ -133,8 +171,13 @@ export function stateOf(now, before, rules, { all, view, unrouted }) {
133
171
  spending: spendingOf(all, now, rules.timezone),
134
172
  totals: { ...tally(counts), attention: openCards.length },
135
173
  // The owner's own: which matter a card is about, and what its asker left for whoever carries on. Channels don't get them.
136
- cards: openCards.map((card) => ({ ...view(card), lane: card.lane, about: card.about })),
137
- recentCards: recentCards.map((card) => ({ ...view(card), lane: card.lane, about: card.about })),
174
+ cards: openCards.map((card) => ({ ...view(card), tags: tags(card.rule), lane: card.lane, about: card.about })),
175
+ recentCards: recentCards.map((card) => ({
176
+ ...view(card),
177
+ tags: tags(card.rule),
178
+ lane: card.lane,
179
+ about: card.about,
180
+ })),
138
181
  timers: timers.map(({ rule, lane, key, about, at }) => ({ rule, lane, key, about, at })),
139
182
  sources: Object.entries(rules.sources).map(([id, { name }]) => {
140
183
  const events = all("SELECT COUNT(*) AS n FROM events WHERE source = ?", [id])[0].n;
@@ -144,6 +187,7 @@ export function stateOf(now, before, rules, { all, view, unrouted }) {
144
187
  id: rule.name,
145
188
  name: rule.name,
146
189
  group: rule.group,
190
+ tags: rule.tags ?? [],
147
191
  agent: rule.to,
148
192
  source: eventRule(rule) ? rule.when.source : SCHEDULE,
149
193
  types: eventRule(rule) ? rule.when.types : [],
@@ -162,7 +206,10 @@ export function stateOf(now, before, rules, { all, view, unrouted }) {
162
206
  }),
163
207
  agents: Object.entries(rules.agents).map(([id, { name, use, worker, program }]) => {
164
208
  const totals = tally(counts.filter((row) => row.agent === id));
165
- return { id, name, use, worker, ...(program && { program }), ...presence(`worker:${worker}`), totals };
209
+ // Like a pause, one past its end is lifted at the next tick and already holds nothing.
210
+ const limit = all("SELECT until, reason, since FROM limits WHERE agent = ?", [id])[0];
211
+ const limited = limit && Date.parse(limit.until) > now ? limit : null;
212
+ return { id, name, use, worker, ...(program && { program }), ...presence(`worker:${worker}`), totals, limited };
166
213
  }),
167
214
  channels: Object.entries(rules.channels).map(([id, { name }]) => {
168
215
  // Coming back says the channel's program runs, not that a card got through: the last one it was given says that.
@@ -177,25 +224,7 @@ export function stateOf(now, before, rules, { all, view, unrouted }) {
177
224
  : undefined;
178
225
  return { id, name, ...presence(`channel:${id}`), ...(lastFailure && { lastFailure }) };
179
226
  }),
180
- runs: visible.map((run) => ({
181
- id: run.id,
182
- rule: run.rule,
183
- agent: run.agent,
184
- state: run.state,
185
- attempts: run.attempts,
186
- createdAt: run.created_at,
187
- claimedAt: run.claimed_at,
188
- finishedAt: run.finished_at,
189
- notBefore: run.not_before,
190
- summary: run.summary ?? "",
191
- error: run.error ?? "",
192
- link: run.link ?? "",
193
- session: run.session,
194
- usage: run.usage ? JSON.parse(run.usage) : null,
195
- stopping: run.cancel_at !== null,
196
- manual: Boolean(run.manual),
197
- events: all(EVENTS_OF_RUN, [run.id]),
198
- })),
227
+ runs: visible.map((run) => runView(run, all, tags(run.rule))),
199
228
  hasMore,
200
229
  nextBefore: hasMore ? page[PAGE - 1].id : null,
201
230
  unrouted: unrouted(),
@@ -5,13 +5,14 @@ import { latestBefore, nextRun, parseCron } from "./cron.js";
5
5
  import { deadlines, MINUTE, offlineCard, OFFLINE_AFTER, RUN_LEASE, SEEN_EVERY, WORKER_FRESH } from "./due.js";
6
6
  import { AuthError, Conflict, InputError, NotFound } from "./errors.js";
7
7
  import { iso, rows } from "./evolve.js";
8
- import { agentsOf, askedAbout, cardView, configuration, eventsOf, jobOf, openInScope, pauseOf, routingOf, sourceOf, waitingOn, workerOf, workers, } from "./query.js";
8
+ import { agentsOf, askedAbout, cardView, configuration, eventsOf, jobOf, limitOf, openInScope, pauseOf, routingOf, sourceOf, waitingOn, workerOf, workers, } from "./query.js";
9
9
  import { cronOf, eventRule, ruleOf, SCHEDULE, typeMatches } from "./rules.js";
10
10
  import { addUsage, ANSWER_BY, ANSWER_REF, ANSWER_TEXT, DELIVERY_REF, parseEvent, parseResult, } from "../protocol/validate.js";
11
11
  /** Minutes after the first try that a card is sent to a channel again. */
12
12
  const RESEND_AT = [0, 1, 3, 7, 15, 25, 35, 45, 55];
13
13
  /** The last resend and the minute it holds the card: after this a channel has given up. */
14
14
  const RESEND_WINDOW = 57 * MINUTE;
15
+ const LIMIT_LONGEST = 8 * 24 * 60 * MINUTE;
15
16
  /** How long a chain of events causing events can get before it stops being dispatched. */
16
17
  const MAX_HOPS = 8;
17
18
  /** Failures in a row after which a run stops being retried: each try spends the owner's real tokens. */
@@ -79,7 +80,7 @@ function assignQueued(draft, run) {
79
80
  if (!rule)
80
81
  return;
81
82
  const session = rule.to === run.agent ? {} : nulls("session", "resume");
82
- put(draft, "runs", run.id, { agent: rule.to, rules_version: config.version, ...session });
83
+ put(draft, "runs", run.id, { agent: rule.to, grp: rule.group, rules_version: config.version, ...session });
83
84
  }
84
85
  const threadOf = (run) => ({ rule: run.rule, lane: run.lane, grp: run.grp });
85
86
  /** The session a round about to start goes on in. With resume, one that has none takes its thread's last, unless that round was
@@ -118,6 +119,14 @@ function closeOpen(draft, matches, result) {
118
119
  /** Once it's stopped, nothing should still say it will try again, or that it may still be going. */
119
120
  const closeStopped = (draft, run, result) => closeOpen(draft, (key) => key === `run:${run}:failing` || key === `run:${run}:unknown`, result);
120
121
  const closeOffline = (draft, worker) => closeOpen(draft, (key) => key.startsWith(`worker:${worker}:offline:`), "连上了");
122
+ /** An agent's usage limit is over; their shared card closes when nobody is waiting for that reset. */
123
+ function lift(draft, agent, result) {
124
+ const { until } = draft.view.get("limits", agent);
125
+ set(draft, "limits", agent, null);
126
+ if (rows(draft.view, "limits", { until }).length === 0) {
127
+ closeOpen(draft, (key) => key === `limit:${until}`, result);
128
+ }
129
+ }
121
130
  /** Whether a new stamp would tell nothing this one doesn't. One in the future means a clock was set back: it gets redone. */
122
131
  function justSeen({ now }, row) {
123
132
  const age = now - Date.parse(row?.seen_at);
@@ -258,6 +267,9 @@ function claimNext(draft, worker, claim) {
258
267
  // What was queued before a pause, or an answer that came in during one, waits for the resume.
259
268
  if (!rule || !agents.includes(rule.to) || pauseOf(draft.view, rule, draft.now))
260
269
  return false;
270
+ // An agent out of quota fails each round within seconds: only one the owner asked for goes, to try it.
271
+ if (!run.manual && limitOf(draft.view, rule.to, draft.now))
272
+ return false;
261
273
  const agentLimit = draft.rules.agents[rule.to].maxActive;
262
274
  return (Date.parse(run.not_before) <= draft.now &&
263
275
  !claimed.some((other) => other.grp === run.grp && other.lane === run.lane) &&
@@ -325,8 +337,13 @@ function briefError(error, run) {
325
337
  function retryLater(draft, run, result) {
326
338
  const { id } = run;
327
339
  const attempts = run.attempts + 1;
328
- const notBefore = draft.now + Math.min(5 * MINUTE * 2 ** (attempts - 1), 60 * MINUTE);
329
340
  const error = (result.error ?? "").trim().replace(/[。.]+$/, "") || "没说原因";
341
+ const told = result.limitedUntil === undefined ? 0 : Date.parse(result.limitedUntil);
342
+ // A usage limit resets within a week. A time further off is misread, and would hold the agent that long.
343
+ const limitedUntil = told > draft.now && told <= draft.now + LIMIT_LONGEST ? told : 0;
344
+ if (limitedUntil)
345
+ limit(draft, run, limitedUntil, error);
346
+ const notBefore = Math.max(draft.now + Math.min(5 * MINUTE * 2 ** (attempts - 1), 60 * MINUTE), limitedUntil);
330
347
  const unclaimed = nulls("claim", "claimed_at", "seen_at", "cancel_at");
331
348
  const rejected = [];
332
349
  for (const what of ["ask", "resolve", "later", "events"]) {
@@ -369,6 +386,32 @@ function retryLater(draft, run, result) {
369
386
  assignQueued(draft, draft.view.get("runs", id));
370
387
  return rejected;
371
388
  }
389
+ /** An agent out of quota gets no work until it resets, and the owner hears once when that is. */
390
+ function limit(draft, run, until, error) {
391
+ const held = limitOf(draft.view, run.agent, draft.now);
392
+ if (held && Date.parse(held.until) >= until)
393
+ return;
394
+ if (draft.view.get("limits", run.agent))
395
+ lift(draft, run.agent, held ? "恢复时间推后了" : "恢复了");
396
+ put(draft, "limits", run.agent, {
397
+ agent: run.agent,
398
+ until: iso(until),
399
+ reason: error,
400
+ since: held?.since ?? draft.at,
401
+ });
402
+ const time = new Intl.DateTimeFormat("zh-CN", {
403
+ timeZone: draft.rules.timezone,
404
+ month: "numeric",
405
+ day: "numeric",
406
+ hour: "2-digit",
407
+ minute: "2-digit",
408
+ hourCycle: "h23",
409
+ }).format(until);
410
+ const words = `有 Agent 用量到上限了,${time} 前不再派活给仍受限的 Agent。排着的和这期间新来的活都留着,到时自动接着做。` +
411
+ `运行 agent-autoloop status 可以查看当前受限项;想提前试,手动运行一条用到受限 Agent 的规则(agent-autoloop run),跑通就接着给它派活。`;
412
+ // Agents on one account are told the same moment: keyed by it, the owner hears of it once.
413
+ notify(draft, `limit:${iso(until)}`, "Agent 用量到上限", words);
414
+ }
372
415
  function scheduleReview(draft, run, later) {
373
416
  const { rule, lane } = run;
374
417
  const [existing] = rows(draft.view, "timers", { rule, lane, key: later.key, event_id: null });
@@ -470,8 +513,19 @@ function finish(draft, id, token, given) {
470
513
  }
471
514
  else if (result.outcome === "failed")
472
515
  rejected = retryLater(draft, run, result);
473
- else
516
+ else {
474
517
  rejected = applyReceipt(draft, run, result);
518
+ // Only the owner's round is handed out while an agent is held: getting through says it works again.
519
+ const held = limitOf(draft.view, run.agent, draft.now);
520
+ if (held && run.claimed_at >= held.since) {
521
+ // The rounds that hit the limit were put off to the reset: they go now with the rest.
522
+ for (const waiting of rows(draft.view, "runs", { state: "queued", agent: run.agent })) {
523
+ if (waiting.not_before === held.until)
524
+ put(draft, "runs", waiting.id, { not_before: draft.at });
525
+ }
526
+ lift(draft, run.agent, "提前恢复了");
527
+ }
528
+ }
475
529
  put(draft, "runs", id, { last_answer: JSON.stringify(rejected) });
476
530
  return { rejected };
477
531
  }
@@ -553,6 +607,10 @@ function tick(draft) {
553
607
  set(draft, "pauses", pause.name, null);
554
608
  reopen(draft, pause.name, Date.parse(pause.until));
555
609
  }
610
+ for (const limit of rows(draft.view, "limits")) {
611
+ if (Date.parse(limit.until) <= now)
612
+ lift(draft, limit.agent, "恢复了");
613
+ }
556
614
  for (const rule of rules) {
557
615
  if (eventRule(rule))
558
616
  continue;
@@ -705,12 +763,29 @@ const CONTROL = {
705
763
  const HANDLERS = {
706
764
  rules(draft, rules) {
707
765
  put(draft, "config", "rules", { value: rules, version: draft.seq });
766
+ // A schedule's next moment was worked out on the old zone's clock. Forgetting the cron it was counted for has the next
767
+ // tick count again from then, as for a changed cron; this input's own clock isn't the tick's.
768
+ if (draft.rules && rules.timezone !== draft.rules.timezone) {
769
+ for (const schedule of rows(draft.view, "schedules"))
770
+ put(draft, "schedules", schedule.rule, { cron: null });
771
+ }
708
772
  for (const run of rows(draft.view, "runs", { state: "queued" })) {
709
773
  if (ruleOf(rules, run.rule))
710
774
  assignQueued(draft, run);
711
775
  else
712
776
  stopRun(draft, run, "rule-gone", ...ruleGone(run.rule));
713
777
  }
778
+ // Groups are counted, and open cards found, by the group on each row: what's going and what's left open move with
779
+ // their rule, or the old group and the new each let a run through.
780
+ const moved = (table, row) => {
781
+ const group = ruleOf(rules, row.rule)?.group;
782
+ if (group !== undefined && group !== row.grp)
783
+ put(draft, table, row.id, { grp: group });
784
+ };
785
+ for (const run of rows(draft.view, "runs", { state: ["claimed", "unknown"] }))
786
+ moved("runs", run);
787
+ for (const card of rows(draft.view, "cards", { state: "open" }))
788
+ moved("cards", card);
714
789
  closeOpen(draft, (key) => key.startsWith("rules:"), "改好了");
715
790
  },
716
791
  rulesError: (draft, problem) => notify(draft, `rules:${digest(problem)}`, "rules.json 写错了,还在用旧规则", problem),
@@ -40,6 +40,8 @@ export function deadlines(view, now) {
40
40
  if (pause.until !== null)
41
41
  add("pause", pause.name, Date.parse(pause.until));
42
42
  }
43
+ for (const limit of rows(view, "limits"))
44
+ add("limit", limit.agent, Date.parse(limit.until));
43
45
  for (const timer of rows(view, "timers", { event_id: null }))
44
46
  add("later", String(timer.id), Date.parse(timer.at));
45
47
  for (const run of rows(view, "runs", { state: "queued" })) {
@@ -13,6 +13,7 @@ export const TABLES = [
13
13
  "config",
14
14
  "due",
15
15
  "pauses",
16
+ "limits",
16
17
  ];
17
18
  const NUMBERED = new Set(["events", "runs", "cards", "timers"]);
18
19
  const indexes = {
@@ -190,6 +191,8 @@ export function keyOf(table, row) {
190
191
  return `${row.kind}:${row.key}`;
191
192
  if (table === "pauses")
192
193
  return row.name;
194
+ if (table === "limits")
195
+ return row.agent;
193
196
  return "rules";
194
197
  }
195
198
  export function empty(db = new DatabaseSync(":memory:")) {
@@ -332,6 +332,17 @@ async function route(call) {
332
332
  const ruleControl = /^\/v1\/rules\/([^/]+)\/(pause|resume|run|replay)$/.exec(path);
333
333
  if (method === "POST" && ruleControl)
334
334
  return control(call, ruleControl[1], ruleControl[2]);
335
+ if (method === "GET" && path === "/v1/runs") {
336
+ requireKey(call, "owner");
337
+ const rule = call.url.searchParams.get("rule");
338
+ if (!rule)
339
+ throw new InputError("缺规则名");
340
+ const before = call.url.searchParams.get("before");
341
+ if (before !== null && (!POSITIVE_ID.test(before) || !Number.isSafeInteger(Number(before))))
342
+ throw new InputError("编号不正确");
343
+ const page = services.ruleRuns(rule, before === null ? undefined : Number(before));
344
+ return json({ now: iso(call.now), timezone: call.rules.timezone, ...page });
345
+ }
335
346
  if (method === "GET" && path === "/v1/state")
336
347
  return state(call);
337
348
  if (method === "GET" && path === "/v1/stream")
@@ -11,6 +11,11 @@ export function pauseOf(view, rule, now) {
11
11
  const row = view.get("pauses", rule.name);
12
12
  return row && (row.until === null || Date.parse(row.until) > now) ? row : null;
13
13
  }
14
+ /** The usage limit an agent has hit and that hasn't reset yet: until then none of its rounds is handed out. */
15
+ export function limitOf(view, agent, now) {
16
+ const row = view.get("limits", agent);
17
+ return row && Date.parse(row.until) > now ? row : null;
18
+ }
14
19
  export const workerOf = (view, run) => configuration(view, run.rules_version).agents[run.agent]?.worker;
15
20
  export function agentsOf(view, worker) {
16
21
  const agents = Object.entries(configuration(view).agents);
@@ -127,7 +132,7 @@ export function cardView(card, env, ref = null, links = false) {
127
132
  }
128
133
  export function jobOf(view, run, env) {
129
134
  const rules = configuration(view, run.rules_version);
130
- const { name, cwd, skill, prompt, title, emits } = ruleOf(rules, run.rule);
135
+ const { name, cwd, skill, prompt, title, emits, tags } = ruleOf(rules, run.rule);
131
136
  const { maxActive: _maxActive, ...agent } = rules.agents[run.agent];
132
137
  const events = eventsOf(view, run.id);
133
138
  const eventIds = events.map((event) => event.id);
@@ -189,6 +194,7 @@ export function jobOf(view, run, env) {
189
194
  .map(({ id, title, choice, answer, options, decided_at }) => {
190
195
  return { card: id, title, choice: choice === null ? answer : JSON.parse(options)[choice], at: decided_at };
191
196
  }),
197
+ ...(tags && { tags }),
192
198
  },
193
199
  };
194
200
  }
@@ -22,6 +22,19 @@ export function inTheApp() {
22
22
  return builds.map((build) => path.join(root, version, build, "claude.app/Contents/MacOS/claude"));
23
23
  });
24
24
  }
25
+ const HOUR = 3_600_000;
26
+ /**
27
+ * When a subscription's usage limit lets it work again. At its 5-hour limit 2.1.318 ends the turn within two seconds with
28
+ * `api_error` "usage_limit_reached" and the result "You've hit your 5-hour limit · resets 1:50pm (Asia/Shanghai)", after a
29
+ * `rate_limit_event` whose `rate_limit_info.resetsAt` is that moment in Unix seconds. Without one, an hour.
30
+ */
31
+ function limitedUntil(messages, result) {
32
+ if (result.api_error !== "usage_limit_reached")
33
+ return {};
34
+ const info = messages.findLast((message) => message?.type === "rate_limit_event")?.rate_limit_info;
35
+ const resets = Number(info?.resetsAt) * 1000;
36
+ return { limitedUntil: new Date(resets > 0 ? resets : Date.now() + HOUR).toISOString() };
37
+ }
25
38
  export default {
26
39
  command: (turn) => [
27
40
  turn.program ?? findProgram("claude", inTheApp),
@@ -95,7 +108,7 @@ export default {
95
108
  const text = carried === undefined ? said : `${said}\n\n${carried}`;
96
109
  if (result.is_error || result.subtype !== "success") {
97
110
  const error = said.split("\n")[0] || result.errors?.[0] || result.subtype || "没留下结果";
98
- return { ...known, usage, sessionUsage, finished: true, error };
111
+ return { ...known, usage, sessionUsage, finished: true, error, ...limitedUntil(messages, result) };
99
112
  }
100
113
  return { text, ...known, usage, sessionUsage, finished: true };
101
114
  },
@@ -1,13 +1,50 @@
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.js";
5
7
  import { findProgram, tail } from "../../worker/agents.js";
6
8
  const SANDBOX = { read: "read-only", edit: "workspace-write", full: "danger-full-access" };
7
- export const IN_THE_APP = [
8
- "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
9
- "/Applications/Codex.app/Contents/Resources/codex",
10
- ];
9
+ /** The Codex the desktop app installs, for those without one of their own. */
10
+ export function inTheApp() {
11
+ const mac = [
12
+ "/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
13
+ "/Applications/Codex.app/Contents/Resources/codex",
14
+ ];
15
+ // The Windows installer puts codex.exe in %LOCALAPPDATA%\OpenAI\Codex\bin\<id>; an update adds a new <id> beside the
16
+ // old one and deletes the old one, leaving PATH naming the folder it deleted. So read that folder for the newest
17
+ // codex.exe rather than one path an update rewrites: on 2026-11-20 and 2026-11-21 both morning rules failed with
18
+ // 找不到 codex while the program sat in the folder beside the one PATH named.
19
+ const local = process.env.LOCALAPPDATA;
20
+ const root = local ? path.join(local, "OpenAI", "Codex", "bin") : null;
21
+ if (!root)
22
+ return mac;
23
+ // An update is emptying these folders while this runs, so each is read on its own and one that has gone is left out:
24
+ // a throw here reaches the round as whichever path vanished rather than as 找不到 codex.
25
+ const folders = (() => {
26
+ try {
27
+ return readdirSync(root, { withFileTypes: true });
28
+ }
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 = [];
35
+ for (const entry of folders) {
36
+ if (!entry.isDirectory())
37
+ continue;
38
+ const file = path.join(root, entry.name, "codex.exe");
39
+ try {
40
+ found.push({ file, at: statSync(file).mtimeMs });
41
+ }
42
+ catch {
43
+ // A folder holding another of the app's programs, or one this update is still emptying.
44
+ }
45
+ }
46
+ return [...found.sort((a, b) => b.at - a.at).map((codex) => codex.file), ...mac];
47
+ }
11
48
  export default {
12
49
  command: (turn) => {
13
50
  // The elevated Windows sandbox runs as CodexSandboxUsers. Share only the supplied data, never the run token or key.
@@ -23,7 +60,7 @@ export default {
23
60
  [IO.File]::SetAccessControl($file, $acl)
24
61
  `);
25
62
  return [
26
- turn.program ?? findProgram("codex", () => IN_THE_APP),
63
+ turn.program ?? findProgram("codex", inTheApp),
27
64
  "exec",
28
65
  ...(turn.resume ? ["resume"] : []),
29
66
  "--json",
@@ -90,8 +127,9 @@ export default {
90
127
  },
91
128
  link: (session) => `codex://threads/${session}`,
92
129
  check(program) {
130
+ const exe = program ?? findProgram("codex", inTheApp);
93
131
  try {
94
- execFileSync(...commandLine([program ?? findProgram("codex", () => IN_THE_APP), "login", "status"]), {
132
+ execFileSync(...commandLine([exe, "login", "status"]), {
95
133
  encoding: "utf8",
96
134
  timeout: 20_000,
97
135
  stdio: ["ignore", "pipe", "pipe"],
@@ -99,6 +137,18 @@ export default {
99
137
  return null;
100
138
  }
101
139
  catch (error) {
140
+ // `login status` only reads the stored login: a key from the environment (OPENAI_API_KEY, or the
141
+ // provider's env_key such as CRS_API_KEY) still runs, and `codex doctor` is what reports that.
142
+ try {
143
+ const { checks } = JSON.parse(execFileSync(...commandLine([exe, "doctor", "--json"]), {
144
+ encoding: "utf8",
145
+ timeout: 20_000,
146
+ stdio: ["ignore", "pipe", "pipe"],
147
+ }));
148
+ if (checks?.["auth.credentials"]?.status === "ok")
149
+ return null;
150
+ }
151
+ catch { }
102
152
  return `Codex 没有登录或用不了:运行 codex login(${error.message.split("\n")[0]})`;
103
153
  }
104
154
  },
@@ -94,9 +94,11 @@ export function readMainSettings(root, testLocalHealth = false, ref = "origin/ma
94
94
  return settings(JSON.parse(git(root, "show", `${ref}:ops/delivery.json`)), testLocalHealth);
95
95
  }
96
96
  function globToRegExp(pattern) {
97
- const parts = pattern.split(/(\*\*\/|\*)/).map((part) => {
97
+ const parts = pattern.split(/(\*\*\/|(?<=^|\/)\*\*$|\*)/).map((part) => {
98
98
  if (part === "**/")
99
99
  return "(?:.*/)?";
100
+ if (part === "**")
101
+ return ".*";
100
102
  if (part === "*")
101
103
  return "[^/]*";
102
104
  return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -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 } from "./project.js";
8
- import { IN_THE_APP } from "../codex/agent.js";
9
- import { findProgram } from "../../worker/agents.js";
8
+ import { inTheApp } from "../codex/agent.js";
9
+ import { findProgram, tail } from "../../worker/agents.js";
10
10
  import { reviewCovers, reviewSignature, selectReview } from "./review-policy.js";
11
11
  import { ledger, OWNER, renderRound, stalled } from "./review-ledger.js";
12
12
  export { readSharedPolicy, selectReview, sharedPolicy } from "./review-policy.js";
@@ -190,7 +190,7 @@ async function runReviewer(snapshot, reviewer, effort, input) {
190
190
  writeFileSync(changesFile, input.diff);
191
191
  const output = join(snapshot, "review.json");
192
192
  const { command, model } = reviewer;
193
- const codex = () => [findProgram("codex", () => IN_THE_APP), ...codexCommand(output, effort, model)];
193
+ const codex = () => [findProgram("codex", inTheApp), ...codexCommand(output, effort, model)];
194
194
  const argv = command ?? codex();
195
195
  const args = argv.slice(1).map((arg) => arg.replaceAll("{input}", changesFile));
196
196
  const child = execFile(...commandLine([argv[0], ...args]), {
@@ -198,6 +198,9 @@ async function runReviewer(snapshot, reviewer, effort, input) {
198
198
  timeout: REVIEW_MINUTES * 60_000,
199
199
  maxBuffer: 8 * 1024 * 1024,
200
200
  });
201
+ // A reviewer can stop before it reads its prompt, and a long one then fails the write. An error nobody listens for would
202
+ // end this whole run; the exit code and stderr already say why the review didn't happen.
203
+ child.stdin.on("error", () => { });
201
204
  child.stdin.end(input.prompt);
202
205
  const text = await new Promise((resolve, reject) => {
203
206
  let stdout = "";
@@ -209,7 +212,7 @@ async function runReviewer(snapshot, reviewer, effort, input) {
209
212
  ? resolve(stdout)
210
213
  : reject(new Error(signal && child.killed
211
214
  ? `审查超过 ${REVIEW_MINUTES} 分钟没有完成,已停止`
212
- : `审查没有完成:${stderr.slice(-1000)}`)));
215
+ : `审查没有完成:${tail(stderr, 1000)}`)));
213
216
  });
214
217
  return parseReview(command ? text : readFileSync(output, "utf8"));
215
218
  }
@@ -7,6 +7,7 @@ import { execFile, spawn } from "node:child_process";
7
7
  import { setTimeout as wait } from "node:timers/promises";
8
8
  import { eachLine } from "../../host/lines.js";
9
9
  import { commandLine } from "../../host/command.js";
10
+ import { fit } from "../../worker/contract.js";
10
11
  /** Feishu sends these values as JSON in a string, which may be empty. */
11
12
  function safeJson(text) {
12
13
  if (typeof text !== "string" || !text)
@@ -28,6 +29,30 @@ function outcomeOf(card) {
28
29
  return `不用决定了:${card.result ?? ""}`;
29
30
  return card.state === "closed" && card.result ? card.result : null;
30
31
  }
32
+ /** What lark-cli said, on one line and short enough for a log, without cutting a character in half. */
33
+ const oneLine = (text) => fit(String(text ?? "")
34
+ .replace(/\s+/g, " ")
35
+ .trim(), 300);
36
+ /**
37
+ * 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.
38
+ * The bot's permissions come from the app's settings in Feishu's developer console, and signing in again doesn't change
39
+ * them; only the user identity is fixed by lark-cli auth login.
40
+ */
41
+ function explain(where, body, failure, printed, identity) {
42
+ const type = typeof body?.type === "string" ? body.type : "";
43
+ const said = typeof body?.message === "string" ? oneLine(body.message) : "";
44
+ const because = [type, said].filter(Boolean).join(":");
45
+ if (type === "authorization" || type === "authentication") {
46
+ const page = typeof body?.console_url === "string" ? `:${oneLine(body.console_url)}` : "";
47
+ const hint = typeof body?.hint === "string" ? oneLine(body.hint) : "";
48
+ return identity === "bot"
49
+ ? `${where} 没通过飞书授权(${because}):在飞书开发者后台给这个应用开通所需权限${page}`
50
+ : `${where} 没通过飞书授权(${because}):${hint || "在这台电脑运行 lark-cli auth login 重新登录"}`;
51
+ }
52
+ if (because)
53
+ return `${where} 失败:飞书说 ${because}`;
54
+ return `${where} 失败:${(oneLine(printed) || oneLine(failure?.message)).replace(/^Error:\s*/, "") || "没有说明原因"}`;
55
+ }
31
56
  /** One card, as it looks now: the options while it's open, what became of it after. */
32
57
  export function render(card) {
33
58
  const outcome = outcomeOf(card);
@@ -103,15 +128,28 @@ export function render(card) {
103
128
  export default async function feishu({ hub, options, log, signal }) {
104
129
  const program = options.lark ?? "lark-cli";
105
130
  const lark = async (args, input) => {
106
- const printed = await new Promise((resolve, reject) => {
107
- const child = execFile(...commandLine([program, ...args]), { encoding: "utf8", timeout: 60_000, signal }, (error, stdout) => (error ? reject(error) : resolve(stdout)));
108
- child.stdin.on("error", input === undefined ? () => { } : reject);
131
+ const ran = await new Promise((resolve) => {
132
+ const child = execFile(...commandLine([program, ...args]), { encoding: "utf8", timeout: 60_000, signal }, (failure, stdout, stderr) => resolve({ failure: failure ?? undefined, stdout, stderr }));
133
+ child.stdin.on("error", input === undefined ? () => { } : (failure) => resolve({ failure, stdout: "", stderr: "" }));
109
134
  child.stdin.end(input);
110
135
  });
111
- const out = JSON.parse(printed);
112
- if (out.ok === false || out.error) {
113
- throw new Error(`lark-cli ${args.slice(0, 3).join(" ")}: ${JSON.stringify(out.error ?? out).slice(0, 300)}`);
136
+ const where = `lark-cli ${args.slice(0, 3).join(" ")}`;
137
+ // What it did is on stdout; what went wrong is on stderr, and an error body can come with either exit code.
138
+ const printed = ran.failure ? ran.stderr : ran.stdout;
139
+ let out;
140
+ try {
141
+ out = JSON.parse(printed);
142
+ }
143
+ catch {
144
+ out = null;
114
145
  }
146
+ const identity = typeof out?.identity === "string" ? out.identity : args.includes("--as") ? args[args.indexOf("--as") + 1] : "";
147
+ if (out?.ok === false || out?.error)
148
+ throw new Error(explain(where, out.error ?? out, ran.failure, printed, identity));
149
+ if (ran.failure)
150
+ throw new Error(explain(where, null, ran.failure, printed));
151
+ if (!out)
152
+ throw new Error(`${where} 失败:返回的不是 JSON(${oneLine(printed) || "没有输出"})`);
115
153
  return out;
116
154
  };
117
155
  const owner = options.user ?? (await lark(["auth", "status"], "")).identities?.user?.openId;