@saltpub/agent-autoloop 0.1.4 → 0.1.5

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 (48) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.en.md +9 -9
  3. package/README.md +9 -9
  4. package/dist/cli/dashboard/favicon.svg +8 -0
  5. package/dist/cli/dashboard/index.html +1 -0
  6. package/dist/cli/dashboard.js +1 -0
  7. package/dist/cli/main.js +9 -13
  8. package/dist/cli/runs.js +17 -3
  9. package/dist/cli/status.js +19 -8
  10. package/dist/host/runtime.js +13 -3
  11. package/dist/host/server.js +7 -1
  12. package/dist/host/service.js +8 -2
  13. package/dist/host/settle.js +10 -0
  14. package/dist/host/state.js +36 -20
  15. package/dist/kernel/decide.js +78 -4
  16. package/dist/kernel/due.js +2 -0
  17. package/dist/kernel/evolve.js +3 -0
  18. package/dist/kernel/http.js +11 -0
  19. package/dist/kernel/query.js +5 -0
  20. package/dist/plugins/claude/agent.js +14 -1
  21. package/dist/plugins/codex/agent.js +14 -1
  22. package/dist/plugins/delivery/review.js +2 -2
  23. package/dist/plugins/xiaojiu/channel.js +59 -9
  24. package/dist/protocol/client.js +6 -0
  25. package/dist/protocol/rules.js +1 -1
  26. package/dist/protocol/schema.json +6 -1
  27. package/dist/protocol/validate.js +19 -2
  28. package/dist/worker/agents.js +51 -18
  29. package/dist/worker/worker.js +6 -3
  30. package/docs/plugins.md +4 -2
  31. package/docs/protocol.md +10 -5
  32. package/examples/recipes/feishu-messages/README.md +60 -0
  33. package/examples/recipes/feishu-messages/SKILL.md +16 -0
  34. package/examples/recipes/feishu-messages/rules.json +21 -0
  35. package/examples/recipes/feishu-messages/watch.ts +157 -0
  36. package/examples/recipes/github-issues/rules.json +6 -1
  37. package/examples/recipes/github-issues/watch.ts +39 -0
  38. package/examples/recipes/ops-alerts/README.md +2 -2
  39. package/examples/recipes/ops-alerts/restart.ts +3 -0
  40. package/examples/recipes/ops-alerts/rules.json +1 -1
  41. package/examples/watch-github-issues.sh +3 -22
  42. package/package.json +1 -1
  43. package/plugins/claude/agent.ts +15 -1
  44. package/plugins/codex/agent.ts +14 -1
  45. package/plugins/delivery/review.ts +2 -2
  46. package/plugins/xiaojiu/channel.ts +59 -11
  47. package/skills/agent-autoloop/SKILL.md +21 -7
  48. package/examples/recipes/ops-alerts/restart.sh +0 -5
@@ -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,12 @@ 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, and the card saying when it would be has nothing more to say. */
123
+ function lift(draft, agent, result) {
124
+ const { until } = draft.view.get("limits", agent);
125
+ set(draft, "limits", agent, null);
126
+ closeOpen(draft, (key) => key === `limit:${until}`, result);
127
+ }
121
128
  /** 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
129
  function justSeen({ now }, row) {
123
130
  const age = now - Date.parse(row?.seen_at);
@@ -258,6 +265,9 @@ function claimNext(draft, worker, claim) {
258
265
  // What was queued before a pause, or an answer that came in during one, waits for the resume.
259
266
  if (!rule || !agents.includes(rule.to) || pauseOf(draft.view, rule, draft.now))
260
267
  return false;
268
+ // An agent out of quota fails each round within seconds: only one the owner asked for goes, to try it.
269
+ if (!run.manual && limitOf(draft.view, rule.to, draft.now))
270
+ return false;
261
271
  const agentLimit = draft.rules.agents[rule.to].maxActive;
262
272
  return (Date.parse(run.not_before) <= draft.now &&
263
273
  !claimed.some((other) => other.grp === run.grp && other.lane === run.lane) &&
@@ -325,8 +335,13 @@ function briefError(error, run) {
325
335
  function retryLater(draft, run, result) {
326
336
  const { id } = run;
327
337
  const attempts = run.attempts + 1;
328
- const notBefore = draft.now + Math.min(5 * MINUTE * 2 ** (attempts - 1), 60 * MINUTE);
329
338
  const error = (result.error ?? "").trim().replace(/[。.]+$/, "") || "没说原因";
339
+ const told = result.limitedUntil === undefined ? 0 : Date.parse(result.limitedUntil);
340
+ // A usage limit resets within a week. A time further off is misread, and would hold the agent that long.
341
+ const limitedUntil = told > draft.now && told <= draft.now + LIMIT_LONGEST ? told : 0;
342
+ if (limitedUntil)
343
+ limit(draft, run, limitedUntil, error);
344
+ const notBefore = Math.max(draft.now + Math.min(5 * MINUTE * 2 ** (attempts - 1), 60 * MINUTE), limitedUntil);
330
345
  const unclaimed = nulls("claim", "claimed_at", "seen_at", "cancel_at");
331
346
  const rejected = [];
332
347
  for (const what of ["ask", "resolve", "later", "events"]) {
@@ -369,6 +384,33 @@ function retryLater(draft, run, result) {
369
384
  assignQueued(draft, draft.view.get("runs", id));
370
385
  return rejected;
371
386
  }
387
+ /** An agent out of quota gets no work until it resets, and the owner hears once when that is. */
388
+ function limit(draft, run, until, error) {
389
+ const held = limitOf(draft.view, run.agent, draft.now);
390
+ if (held && Date.parse(held.until) >= until)
391
+ return;
392
+ if (draft.view.get("limits", run.agent))
393
+ lift(draft, run.agent, held ? "恢复时间推后了" : "恢复了");
394
+ put(draft, "limits", run.agent, {
395
+ agent: run.agent,
396
+ until: iso(until),
397
+ reason: error,
398
+ since: held?.since ?? draft.at,
399
+ });
400
+ const agent = configuration(draft.view, run.rules_version).agents[run.agent]?.name ?? run.agent;
401
+ const time = new Intl.DateTimeFormat("zh-CN", {
402
+ timeZone: draft.rules.timezone,
403
+ month: "numeric",
404
+ day: "numeric",
405
+ hour: "2-digit",
406
+ minute: "2-digit",
407
+ hourCycle: "h23",
408
+ }).format(until);
409
+ const words = `${agent} 用量到上限了(${briefError(error, run.id)}),${time} 前不再派活给它。排着的和这期间新来的活都留着,` +
410
+ `到时自动接着做。想提前试,手动运行一轮「${run.rule}」(agent-autoloop run),跑通就接着给它派活。`;
411
+ // Agents on one account are told the same moment: keyed by it, the owner hears of it once.
412
+ notify(draft, `limit:${iso(until)}`, `${agent} 用量到上限`, words);
413
+ }
372
414
  function scheduleReview(draft, run, later) {
373
415
  const { rule, lane } = run;
374
416
  const [existing] = rows(draft.view, "timers", { rule, lane, key: later.key, event_id: null });
@@ -470,8 +512,19 @@ function finish(draft, id, token, given) {
470
512
  }
471
513
  else if (result.outcome === "failed")
472
514
  rejected = retryLater(draft, run, result);
473
- else
515
+ else {
474
516
  rejected = applyReceipt(draft, run, result);
517
+ // Only the owner's round is handed out while an agent is held: getting through says it works again.
518
+ const held = limitOf(draft.view, run.agent, draft.now);
519
+ if (held && run.claimed_at >= held.since) {
520
+ // The rounds that hit the limit were put off to the reset: they go now with the rest.
521
+ for (const waiting of rows(draft.view, "runs", { state: "queued", agent: run.agent })) {
522
+ if (waiting.not_before === held.until)
523
+ put(draft, "runs", waiting.id, { not_before: draft.at });
524
+ }
525
+ lift(draft, run.agent, "提前恢复了");
526
+ }
527
+ }
475
528
  put(draft, "runs", id, { last_answer: JSON.stringify(rejected) });
476
529
  return { rejected };
477
530
  }
@@ -553,6 +606,10 @@ function tick(draft) {
553
606
  set(draft, "pauses", pause.name, null);
554
607
  reopen(draft, pause.name, Date.parse(pause.until));
555
608
  }
609
+ for (const limit of rows(draft.view, "limits")) {
610
+ if (Date.parse(limit.until) <= now)
611
+ lift(draft, limit.agent, "恢复了");
612
+ }
556
613
  for (const rule of rules) {
557
614
  if (eventRule(rule))
558
615
  continue;
@@ -705,12 +762,29 @@ const CONTROL = {
705
762
  const HANDLERS = {
706
763
  rules(draft, rules) {
707
764
  put(draft, "config", "rules", { value: rules, version: draft.seq });
765
+ // A schedule's next moment was worked out on the old zone's clock. Forgetting the cron it was counted for has the next
766
+ // tick count again from then, as for a changed cron; this input's own clock isn't the tick's.
767
+ if (draft.rules && rules.timezone !== draft.rules.timezone) {
768
+ for (const schedule of rows(draft.view, "schedules"))
769
+ put(draft, "schedules", schedule.rule, { cron: null });
770
+ }
708
771
  for (const run of rows(draft.view, "runs", { state: "queued" })) {
709
772
  if (ruleOf(rules, run.rule))
710
773
  assignQueued(draft, run);
711
774
  else
712
775
  stopRun(draft, run, "rule-gone", ...ruleGone(run.rule));
713
776
  }
777
+ // Groups are counted, and open cards found, by the group on each row: what's going and what's left open move with
778
+ // their rule, or the old group and the new each let a run through.
779
+ const moved = (table, row) => {
780
+ const group = ruleOf(rules, row.rule)?.group;
781
+ if (group !== undefined && group !== row.grp)
782
+ put(draft, table, row.id, { grp: group });
783
+ };
784
+ for (const run of rows(draft.view, "runs", { state: ["claimed", "unknown"] }))
785
+ moved("runs", run);
786
+ for (const card of rows(draft.view, "cards", { state: "open" }))
787
+ moved("cards", card);
714
788
  closeOpen(draft, (key) => key.startsWith("rules:"), "改好了");
715
789
  },
716
790
  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);
@@ -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
  },
@@ -90,8 +90,9 @@ export default {
90
90
  },
91
91
  link: (session) => `codex://threads/${session}`,
92
92
  check(program) {
93
+ const exe = program ?? findProgram("codex", () => IN_THE_APP);
93
94
  try {
94
- execFileSync(...commandLine([program ?? findProgram("codex", () => IN_THE_APP), "login", "status"]), {
95
+ execFileSync(...commandLine([exe, "login", "status"]), {
95
96
  encoding: "utf8",
96
97
  timeout: 20_000,
97
98
  stdio: ["ignore", "pipe", "pipe"],
@@ -99,6 +100,18 @@ export default {
99
100
  return null;
100
101
  }
101
102
  catch (error) {
103
+ // `login status` only reads the stored login: a key from the environment (OPENAI_API_KEY, or the
104
+ // provider's env_key such as CRS_API_KEY) still runs, and `codex doctor` is what reports that.
105
+ try {
106
+ const { checks } = JSON.parse(execFileSync(...commandLine([exe, "doctor", "--json"]), {
107
+ encoding: "utf8",
108
+ timeout: 20_000,
109
+ stdio: ["ignore", "pipe", "pipe"],
110
+ }));
111
+ if (checks?.["auth.credentials"]?.status === "ok")
112
+ return null;
113
+ }
114
+ catch { }
102
115
  return `Codex 没有登录或用不了:运行 codex login(${error.message.split("\n")[0]})`;
103
116
  }
104
117
  },
@@ -6,7 +6,7 @@ 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
8
  import { IN_THE_APP } from "../codex/agent.js";
9
- import { findProgram } from "../../worker/agents.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";
@@ -209,7 +209,7 @@ async function runReviewer(snapshot, reviewer, effort, input) {
209
209
  ? resolve(stdout)
210
210
  : reject(new Error(signal && child.killed
211
211
  ? `审查超过 ${REVIEW_MINUTES} 分钟没有完成,已停止`
212
- : `审查没有完成:${stderr.slice(-1000)}`)));
212
+ : `审查没有完成:${tail(stderr, 1000)}`)));
213
213
  });
214
214
  return parseReview(command ? text : readFileSync(output, "utf8"));
215
215
  }
@@ -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 } from "node:http";
13
20
  // The platform's business code for "too fast": the manual says to wait and try again.
@@ -72,6 +79,10 @@ async function joinWebhook(options, appId, log, answer) {
72
79
  throw new Error("webhook.listen 要写 主机:端口");
73
80
  if (!path.startsWith("/") || /\s/.test(path))
74
81
  throw new Error(`webhook.path 要以 / 开头、不含空白:${path}`);
82
+ const forward = typeof options.forward === "string" ? options.forward.trim() : "";
83
+ if (forward && !/^https?:\/\/\S+$/.test(forward)) {
84
+ throw new Error(`webhook.forward 要写 http(s) 地址:${forward}`);
85
+ }
75
86
  let pending = listeners.get(listen);
76
87
  if (!pending) {
77
88
  pending = bind(listen);
@@ -82,9 +93,9 @@ async function joinWebhook(options, appId, log, answer) {
82
93
  if ([...listener.routes].some((route) => route.appId === appId && route.path === path)) {
83
94
  throw new Error(`webhook 已经有 appId ${appId} 在 ${path}`);
84
95
  }
85
- const route = { appId, path, log, answer };
96
+ const route = { appId, path, log, answer, ...(forward ? { forward } : {}) };
86
97
  listener.routes.add(route);
87
- log(`webhook 在 ${listener.url}${path} 收卡片回答(appId ${appId})`);
98
+ log(`webhook 在 ${listener.url}${path} 收卡片回答(appId ${appId})${forward ? `,其余回调转发 ${forward}` : ""}`);
88
99
  return async () => {
89
100
  listener.routes.delete(route);
90
101
  if (listener.routes.size)
@@ -112,11 +123,19 @@ async function handleRequest(request, response, listener) {
112
123
  const known = [...listener.routes].some((candidate) => candidate.path === pathname);
113
124
  return reply(response, known ? 403 : 404, { error: known ? "this appId isn't this path's bot" : "not found" });
114
125
  }
115
- if (text(record(header)?.type) !== "card_action_trigger")
116
- return reply(response, 200, { ok: true });
117
- const click = cardClick(body);
126
+ const type = text(record(header)?.type) ?? "未知类型";
127
+ const click = type === "card_action_trigger" ? cardClick(body) : null;
118
128
  if (!click) {
119
- route.log("xiaojiu 回调里没有能回答卡片的按钮信息,已忽略");
129
+ // Ours only if it's a press on a button this channel drew. Everything else — chat messages, presses on card
130
+ // messages another program sent through the same bot — belongs to the forward address when there is one.
131
+ if (route.forward) {
132
+ if (await forwardTo(route.forward, body))
133
+ return reply(response, 200, { ok: true });
134
+ route.log(`转发 ${type} 回调到 ${route.forward} 失败`);
135
+ return reply(response, 500, { error: "forward failed" });
136
+ }
137
+ if (type === "card_action_trigger")
138
+ route.log("xiaojiu 回调里没有能回答卡片的按钮信息,已忽略");
120
139
  return reply(response, 200, { ok: true });
121
140
  }
122
141
  try {
@@ -138,6 +157,21 @@ async function handleRequest(request, response, listener) {
138
157
  return reply(response, 500, { error: "internal server error" });
139
158
  }
140
159
  }
160
+ /** A callback this channel doesn't own goes to the configured address as the same JSON. false: the platform retries. */
161
+ async function forwardTo(url, body) {
162
+ try {
163
+ const response = await fetch(url, {
164
+ method: "POST",
165
+ headers: { "content-type": "application/json" },
166
+ body: JSON.stringify(body),
167
+ signal: AbortSignal.timeout(10_000),
168
+ });
169
+ return response.ok;
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ }
141
175
  class BadRequest extends Error {
142
176
  status;
143
177
  constructor(status, message) {
@@ -320,6 +354,22 @@ export default async function xiaojiu({ hub, options, log, signal }) {
320
354
  return envelope;
321
355
  }
322
356
  }
357
+ /** v1 is the documented endpoint; v2 takes what v1 refuses, so it is the fallback only. Whichever answers, the
358
+ * caller hears one outcome: only both refusing is a failure, and only then does the hub start its one-minute retry. */
359
+ async function send(body) {
360
+ try {
361
+ return await post("/open/im/v1/messages", body);
362
+ }
363
+ catch (error) {
364
+ log(`xiaojiu v1 发送失败,改用 v2:${error}`);
365
+ try {
366
+ return await post("/open/im/v2/messages", body);
367
+ }
368
+ catch (fallback) {
369
+ throw new Error(`v1:${error};v2:${fallback}`);
370
+ }
371
+ }
372
+ }
323
373
  // Where each card message lives: the platform's message id -> its session, learned when we sent it.
324
374
  const locations = new Map();
325
375
  let lastSession = session;
@@ -374,7 +424,7 @@ export default async function xiaojiu({ hub, options, log, signal }) {
374
424
  continue;
375
425
  }
376
426
  try {
377
- const envelope = await post("/open/im/v2/messages", webhook
427
+ const envelope = await send(webhook
378
428
  ? {
379
429
  ...(session ? { snSessionId: session } : { receiveId: staffNo }),
380
430
  msgType: "card",
@@ -44,6 +44,12 @@ export function hubClient(url, key) {
44
44
  tell: (body) => call("POST", "/v1/tell", { body }),
45
45
  why: (id) => call("GET", `/v1/runs/${id}/why`),
46
46
  removeKey: (kind, name) => call("DELETE", `/v1/keys/${encodeURIComponent(kind)}/${encodeURIComponent(name)}`),
47
+ ruleRuns: (rule, before) => {
48
+ const query = new URLSearchParams({ rule });
49
+ if (before !== undefined)
50
+ query.set("before", String(before));
51
+ return call("GET", `/v1/runs?${query}`);
52
+ },
47
53
  state: (before) => call("GET", before === undefined ? "/v1/state" : `/v1/state?before=${before}`),
48
54
  cancel: (run) => call("POST", `/v1/runs/${run}/cancel`, { body: {} }),
49
55
  resolve: (card, reason) => call("POST", `/v1/cards/${card}/resolve`, { body: { reason } }),
@@ -150,7 +150,7 @@ export function parseRules(json, now, timezone) {
150
150
  issues.push(`来源的编号${ID_WORDS}:${id}`);
151
151
  checkFields(issues, `来源 ${id} `, source, [
152
152
  ["name", isText, NOT_EMPTY],
153
- ["adapter", isText, NOT_EMPTY, true],
153
+ ["adapter", isId, ID_WORDS, true],
154
154
  ]);
155
155
  }
156
156
  rules.sources[SCHEDULE] = { name: "定时" };
@@ -156,7 +156,7 @@
156
156
  },
157
157
  "text": {
158
158
  "type": "string",
159
- "maxLength": 4000,
159
+ "maxLength": 50000,
160
160
  "minLength": 1,
161
161
  "pattern": "\\S"
162
162
  },
@@ -247,6 +247,11 @@
247
247
  "type": "string",
248
248
  "maxLength": 500
249
249
  },
250
+ "limitedUntil": {
251
+ "type": "string",
252
+ "format": "date-time",
253
+ "pattern": "(Z|[+-]\\d\\d:\\d\\d)$"
254
+ },
250
255
  "session": {
251
256
  "type": "string",
252
257
  "maxLength": 500
@@ -6,6 +6,8 @@ export const EVENT_TYPE = /^[a-z][a-z0-9_.-]{0,63}$/;
6
6
  export const ANSWER_TEXT = 4000;
7
7
  export const ANSWER_BY = 500;
8
8
  export const ANSWER_REF = 500;
9
+ /** A notice can carry a full report; a card in a chat app stays the reader's business. */
10
+ export const NOTICE_TEXT = 50_000;
9
11
  /** A channel's own reference to the message it sent. */
10
12
  export const DELIVERY_REF = 500;
11
13
  /** Missing figures stay missing: zero is a price or token count that was actually reported. */
@@ -99,7 +101,7 @@ const validAsk = (ask) => only(ask, ["title", "text", "options", "recommend", "a
99
101
  export const isAsk = (value) => isItem(value) && validAsk(value);
100
102
  const validNotice = (notice) => only(notice, ["title", "text", "key", "fyi"]) &&
101
103
  text(notice.title, 200) &&
102
- text(notice.text, 4000) &&
104
+ text(notice.text, NOTICE_TEXT) &&
103
105
  optional(notice.key, 100) &&
104
106
  (notice.fyi === undefined || typeof notice.fyi === "boolean");
105
107
  const validResolve = (item) => only(item, ["card", "reason"]) &&
@@ -119,7 +121,19 @@ export function parseResult(input) {
119
121
  throw new InputError("结果要是一个 JSON 对象");
120
122
  }
121
123
  const result = { ...input };
122
- if (!only(result, ["outcome", "summary", "error", "session", "usage", "ask", "notice", "resolve", "later", "events"])) {
124
+ if (!only(result, [
125
+ "outcome",
126
+ "summary",
127
+ "error",
128
+ "limitedUntil",
129
+ "session",
130
+ "usage",
131
+ "ask",
132
+ "notice",
133
+ "resolve",
134
+ "later",
135
+ "events",
136
+ ])) {
123
137
  throw new InputError("结果里有不认识的字段");
124
138
  }
125
139
  if (!["done", "nothing", "failed", "cancelled"].includes(result.outcome)) {
@@ -128,6 +142,9 @@ export function parseResult(input) {
128
142
  if (!optional(result.summary, 500) || !optional(result.error, 500) || !optional(result.session, 500)) {
129
143
  throw new InputError("summary、error、session 最多 500 字");
130
144
  }
145
+ if (result.limitedUntil !== undefined && (result.outcome !== "failed" || !dateTime(result.limitedUntil))) {
146
+ throw new InputError("limitedUntil 只能跟 failed 一起交,要是带时区的 ISO 时间");
147
+ }
131
148
  if (!validUsage(result.usage))
132
149
  throw new InputError("usage 要是对象,里面要是有限的非负数字");
133
150
  if (!listOf(result.ask, 5, validAsk)) {
@@ -3,7 +3,8 @@
3
3
  // then the ones that ship. Anything with a print mode needs no file at all: `use: "command"` with a command line in
4
4
  // rules.json.
5
5
  import { execFileSync } from "node:child_process";
6
- import { existsSync } from "node:fs";
6
+ import { accessSync, constants, existsSync, statSync } from "node:fs";
7
+ import path from "node:path";
7
8
  import { findOnPath } from "../host/command.js";
8
9
  import { loadPlugin } from "../host/plugins.js";
9
10
  const adapters = new Map();
@@ -18,25 +19,52 @@ export async function adapterFor(use) {
18
19
  // Only hits are kept: an update can leave a program missing for a moment (`npm install -g` removes the old one
19
20
  // first), and a kept miss would fail every later run until the worker restarts.
20
21
  const found = new Map();
21
- /** Where a program is: on the login shell's PATH (launchd and systemd start with a bare one), or in one of these. */
22
+ /** The last line a shell prints for a script, or null if it fails or prints nothing. */
23
+ function shellSays(flags, script) {
24
+ try {
25
+ const printed = execFileSync(process.env.SHELL ?? "/bin/sh", [...flags, script], {
26
+ encoding: "utf8",
27
+ timeout: 15_000,
28
+ stdio: ["ignore", "pipe", "ignore"],
29
+ });
30
+ return printed.trim().split("\n").at(-1) || null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /** A program on the PATH a rule's command line runs with: the login shell's on Unix. */
37
+ export function onPath(name) {
38
+ if (process.platform === "win32")
39
+ return findOnPath(name, [".exe", ".com", ".cmd", ".ps1"]);
40
+ return shellSays(["-lc"], `command -v ${name}`);
41
+ }
42
+ /** A program on the PATH an interactive shell sets up: ~/.zshrc and ~/.bashrc are where installers tell people to add it. */
43
+ function inTerminal(name) {
44
+ // The PATH, not `command -v`: in a terminal that can print an alias. +m: an interactive zsh with job control takes the
45
+ // terminal's foreground and doesn't hand it back, so Ctrl-C would no longer reach the command that asked.
46
+ const folders = shellSays(["+m", "-ic"], "printenv PATH")?.split(":") ?? [];
47
+ // An empty entry or `.` means the folder the shell was in, not one the worker can name.
48
+ const absolute = folders.filter((folder) => path.isAbsolute(folder));
49
+ return absolute.map((folder) => path.join(folder, name)).find(isProgram) ?? null;
50
+ }
51
+ function isProgram(file) {
52
+ try {
53
+ accessSync(file, constants.X_OK);
54
+ return statSync(file).isFile();
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ /**
61
+ * Where a program is: on the login shell's PATH (launchd and systemd start with a bare one), on the PATH a terminal sets
62
+ * up, or in one of these.
63
+ */
22
64
  export function findProgram(name, elsewhere = () => []) {
23
65
  let program = found.get(name);
24
66
  if (!program) {
25
- let onPath = null;
26
- if (process.platform === "win32")
27
- onPath = findOnPath(name, [".exe", ".com", ".cmd", ".ps1"]);
28
- else {
29
- try {
30
- const printed = execFileSync(process.env.SHELL ?? "/bin/sh", ["-lc", `command -v ${name}`], {
31
- encoding: "utf8",
32
- timeout: 15_000,
33
- stdio: ["ignore", "pipe", "ignore"],
34
- });
35
- onPath = printed.trim().split("\n").at(-1) || null;
36
- }
37
- catch { }
38
- }
39
- program = onPath ?? elsewhere().find(existsSync);
67
+ program = onPath(name) ?? (process.platform === "win32" ? null : inTerminal(name)) ?? elsewhere().find(existsSync);
40
68
  if (!program)
41
69
  throw new Error(`找不到 ${name}:先装好并登录`);
42
70
  found.set(name, program);
@@ -44,4 +72,9 @@ export function findProgram(name, elsewhere = () => []) {
44
72
  return program;
45
73
  }
46
74
  /** The end of some output, for saying why something failed. */
47
- export const tail = (text, length = 300) => text.trim().slice(-length);
75
+ export const tail = (text, length = 300) => {
76
+ const cut = text.trim().slice(-length);
77
+ // Where the window starts is an arbitrary unit of what it printed, so it can open on the second half of a character,
78
+ // which no store or terminal can hold. Its end is never a first half: text that is text doesn't start with one.
79
+ return /^[\udc00-\udfff]/.test(cut) ? cut.slice(1) : cut;
80
+ };
@@ -11,7 +11,7 @@ import { HubError } from "../protocol/client.js";
11
11
  import { HOME } from "../host/home.js";
12
12
  import { sibling } from "../host/program.js";
13
13
  import { commandLine, processCommand } from "../host/command.js";
14
- import { addUsage } from "../protocol/validate.js";
14
+ import { addUsage, dateTime } from "../protocol/validate.js";
15
15
  import { adapterFor } from "./agents.js";
16
16
  import { promptFor, readMessage, repairPrompt, resultFrom } from "./contract.js";
17
17
  import { loadUsage, saveUsage, usageDelta } from "./usage.js";
@@ -345,7 +345,8 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
345
345
  return discardReceipt(entry, adapter, error);
346
346
  // The conversation may not be there to go on in, or something else has it open: this go carries on in a new one.
347
347
  // Not once the turn has started: a new one would do its work again. The hub tries again later, in this one.
348
- if (entry.resume && !entry.triedFresh && entry.repairs === 0 && !seen.started) {
348
+ // Out of quota, a new one would fail the same way.
349
+ if (entry.resume && !entry.triedFresh && entry.repairs === 0 && !seen.started && !seen.limitedUntil) {
349
350
  log(`run ${entry.run}: couldn't go on in ${entry.resume} (${error}); starting a new session`);
350
351
  entry.triedFresh = true;
351
352
  entry.resume = null;
@@ -358,7 +359,9 @@ export function createWorker({ hub, name, capacity = 2, log = () => { }, unreach
358
359
  return endWith(entry, { outcome: "failed", error: String(failure).slice(0, 500) });
359
360
  }
360
361
  }
361
- return endWith(entry, { outcome: "failed", error: error.slice(0, 500), ...known, ...usage });
362
+ // The hub refuses a whole result with a time it can't read, and the run would wait for a result that never comes.
363
+ const limited = dateTime(seen.limitedUntil) && { limitedUntil: seen.limitedUntil };
364
+ return endWith(entry, { outcome: "failed", error: error.slice(0, 500), ...limited, ...known, ...usage });
362
365
  }
363
366
  const { result, problem } = resultFrom(readMessage(seen.text), { session, usage: entry.usage });
364
367
  if (entry.repairs && !problem && result.outcome === "failed")