@saltpub/agent-autoloop 0.0.0-stage → 0.1.3

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 (177) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/INSTALL.md +120 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +268 -0
  5. package/README.md +264 -2
  6. package/SECURITY.md +49 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/agents.js +14 -0
  9. package/dist/cli/backup.js +144 -0
  10. package/dist/cli/dashboard/app.js +424 -0
  11. package/dist/cli/dashboard/index.html +15 -0
  12. package/dist/cli/dashboard/style.css +629 -0
  13. package/dist/cli/dashboard.js +94 -0
  14. package/dist/cli/explain.js +84 -0
  15. package/dist/cli/main.js +1142 -0
  16. package/dist/cli/mcp.js +151 -0
  17. package/dist/cli/runs.js +40 -0
  18. package/dist/cli/spend.js +21 -0
  19. package/dist/cli/status.js +272 -0
  20. package/dist/cli/try.js +6 -0
  21. package/dist/cli/ui.js +75 -0
  22. package/dist/cli/uninstall.js +86 -0
  23. package/dist/cli/update.js +65 -0
  24. package/dist/cli/why.js +115 -0
  25. package/dist/host/background-launcher.js +12 -0
  26. package/dist/host/background.js +24 -0
  27. package/dist/host/channels.js +4 -0
  28. package/dist/host/command.js +98 -0
  29. package/dist/host/config.js +37 -0
  30. package/dist/host/files.js +22 -0
  31. package/dist/host/home.js +5 -0
  32. package/dist/host/http.js +45 -0
  33. package/dist/host/launcher.js +188 -0
  34. package/dist/host/lines.js +15 -0
  35. package/dist/host/node-path.js +33 -0
  36. package/dist/host/npm.js +28 -0
  37. package/dist/host/plugins.js +26 -0
  38. package/dist/host/program.js +14 -0
  39. package/dist/host/runtime.js +179 -0
  40. package/dist/host/server.js +159 -0
  41. package/dist/host/service.js +325 -0
  42. package/dist/host/state.js +203 -0
  43. package/dist/host/up.js +162 -0
  44. package/dist/host/update.js +286 -0
  45. package/dist/host/version.js +81 -0
  46. package/dist/kernel/card-page.js +54 -0
  47. package/dist/kernel/credentials.js +16 -0
  48. package/dist/kernel/cron.js +135 -0
  49. package/dist/kernel/decide.js +826 -0
  50. package/dist/kernel/due.js +73 -0
  51. package/dist/kernel/errors.js +9 -0
  52. package/dist/kernel/evolve.js +264 -0
  53. package/dist/kernel/http.js +357 -0
  54. package/dist/kernel/query.js +202 -0
  55. package/dist/kernel/rules.js +20 -0
  56. package/dist/kernel/store.js +52 -0
  57. package/dist/plugins/acp/agent.js +32 -0
  58. package/dist/plugins/acp/bridge.js +204 -0
  59. package/dist/plugins/claude/agent.js +113 -0
  60. package/dist/plugins/codex/agent.js +105 -0
  61. package/dist/plugins/command/agent.js +25 -0
  62. package/dist/plugins/delivery/action.js +25 -0
  63. package/dist/plugins/delivery/agent.js +13 -0
  64. package/dist/plugins/delivery/delivery.js +388 -0
  65. package/dist/plugins/delivery/github.js +201 -0
  66. package/dist/plugins/delivery/handoff.js +50 -0
  67. package/dist/plugins/delivery/input.js +47 -0
  68. package/dist/plugins/delivery/poll.js +72 -0
  69. package/dist/plugins/delivery/project.js +144 -0
  70. package/dist/plugins/delivery/review-ledger.js +82 -0
  71. package/dist/plugins/delivery/review-policy.js +99 -0
  72. package/dist/plugins/delivery/review.js +280 -0
  73. package/dist/plugins/delivery/run.js +204 -0
  74. package/dist/plugins/desktop/channel.js +94 -0
  75. package/dist/plugins/dsh/agent.js +116 -0
  76. package/dist/plugins/feishu/channel.js +245 -0
  77. package/dist/plugins/github/source.js +30 -0
  78. package/dist/plugins/gitlab/source.js +30 -0
  79. package/dist/plugins/omp/agent.js +3 -0
  80. package/dist/plugins/opencode/agent.js +88 -0
  81. package/dist/plugins/pi/agent.js +92 -0
  82. package/dist/plugins/webhook/channel.js +70 -0
  83. package/dist/plugins/webhook/templates.js +34 -0
  84. package/dist/plugins/xiaojiu/channel.js +410 -0
  85. package/dist/plugins/zcode/agent.js +102 -0
  86. package/dist/protocol/client.js +56 -0
  87. package/dist/protocol/conformance.js +184 -0
  88. package/dist/protocol/job.js +1 -0
  89. package/dist/protocol/rules.js +230 -0
  90. package/dist/protocol/schema.js +70 -0
  91. package/dist/protocol/schema.json +985 -0
  92. package/dist/protocol/validate.js +150 -0
  93. package/dist/worker/agents.js +47 -0
  94. package/dist/worker/contract.js +178 -0
  95. package/dist/worker/run.js +52 -0
  96. package/dist/worker/usage.js +45 -0
  97. package/dist/worker/windows.ps1 +48 -0
  98. package/dist/worker/worker.js +595 -0
  99. package/docs/architecture.en.svg +178 -0
  100. package/docs/architecture.svg +178 -0
  101. package/docs/auto-update.md +53 -0
  102. package/docs/plugins.md +139 -0
  103. package/docs/protocol.md +582 -0
  104. package/docs/state-machines.md +77 -0
  105. package/examples/channel.sh +15 -0
  106. package/examples/plugins/hello-agent/agent.ts +40 -0
  107. package/examples/plugins/hello-channel/channel.ts +54 -0
  108. package/examples/plugins/hello-source/source.ts +19 -0
  109. package/examples/recipes/browser-handoff/README.md +44 -0
  110. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  111. package/examples/recipes/browser-handoff/browser.json +10 -0
  112. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  113. package/examples/recipes/browser-handoff/rules.json +19 -0
  114. package/examples/recipes/feedback/README.md +34 -0
  115. package/examples/recipes/feedback/SKILL.md +22 -0
  116. package/examples/recipes/feedback/event.json +8 -0
  117. package/examples/recipes/feedback/rules.json +37 -0
  118. package/examples/recipes/feishu-brief/README.md +28 -0
  119. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  120. package/examples/recipes/feishu-brief/collect.ts +164 -0
  121. package/examples/recipes/feishu-brief/rules.json +57 -0
  122. package/examples/recipes/feishu-brief/sources.json +13 -0
  123. package/examples/recipes/github-issues/README.md +17 -0
  124. package/examples/recipes/github-issues/SKILL.md +18 -0
  125. package/examples/recipes/github-issues/rules.json +30 -0
  126. package/examples/recipes/inbox-triage/README.md +36 -0
  127. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  128. package/examples/recipes/inbox-triage/collect.ts +191 -0
  129. package/examples/recipes/inbox-triage/rules.json +57 -0
  130. package/examples/recipes/inbox-triage/sources.json +8 -0
  131. package/examples/recipes/morning-brief/README.md +17 -0
  132. package/examples/recipes/morning-brief/SKILL.md +17 -0
  133. package/examples/recipes/morning-brief/rules.json +16 -0
  134. package/examples/recipes/ops-alerts/README.md +18 -0
  135. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  136. package/examples/recipes/ops-alerts/restart.sh +5 -0
  137. package/examples/recipes/ops-alerts/rules.json +29 -0
  138. package/examples/recipes/website-watch/README.md +26 -0
  139. package/examples/recipes/website-watch/SKILL.md +19 -0
  140. package/examples/recipes/website-watch/check.ts +86 -0
  141. package/examples/recipes/website-watch/rules.json +56 -0
  142. package/examples/recipes/website-watch/site.json +6 -0
  143. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  144. package/examples/watch-github-issues.sh +23 -0
  145. package/examples/worker.sh +18 -0
  146. package/package.json +57 -4
  147. package/plugins/acp/agent.ts +31 -0
  148. package/plugins/acp/bridge.ts +190 -0
  149. package/plugins/claude/agent.ts +121 -0
  150. package/plugins/codex/agent.ts +103 -0
  151. package/plugins/command/agent.ts +25 -0
  152. package/plugins/delivery/action.ts +29 -0
  153. package/plugins/delivery/action.yml +28 -0
  154. package/plugins/delivery/agent.ts +15 -0
  155. package/plugins/delivery/delivery.ts +408 -0
  156. package/plugins/delivery/github.ts +207 -0
  157. package/plugins/delivery/handoff.ts +72 -0
  158. package/plugins/delivery/input.ts +55 -0
  159. package/plugins/delivery/poll.ts +65 -0
  160. package/plugins/delivery/project.ts +161 -0
  161. package/plugins/delivery/review-ledger.ts +90 -0
  162. package/plugins/delivery/review-policy.ts +126 -0
  163. package/plugins/delivery/review.ts +324 -0
  164. package/plugins/delivery/run.ts +219 -0
  165. package/plugins/desktop/channel.ts +100 -0
  166. package/plugins/dsh/agent.ts +100 -0
  167. package/plugins/feishu/channel.ts +243 -0
  168. package/plugins/github/source.ts +33 -0
  169. package/plugins/gitlab/source.ts +32 -0
  170. package/plugins/omp/agent.ts +4 -0
  171. package/plugins/opencode/agent.ts +78 -0
  172. package/plugins/pi/agent.ts +80 -0
  173. package/plugins/webhook/channel.ts +74 -0
  174. package/plugins/webhook/templates.ts +32 -0
  175. package/plugins/xiaojiu/channel.ts +426 -0
  176. package/plugins/zcode/agent.ts +96 -0
  177. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,184 @@
1
+ // The protocol, checked over real HTTP against a hub set up for it. It writes events and cards, so never a hub in use.
2
+ import assert from "node:assert/strict";
3
+ import { randomUUID } from "node:crypto";
4
+ import { readFileSync } from "node:fs";
5
+ import { checkSchema } from "./schema.js";
6
+ export async function conformance(base, config, request = fetch) {
7
+ let checks = 0;
8
+ const { keys } = config;
9
+ const tag = randomUUID();
10
+ const call = async (path, key, body, status = 200, schema) => {
11
+ const response = await request(base + path, {
12
+ method: body === undefined ? "GET" : "POST",
13
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
14
+ ...(body !== undefined && { body: JSON.stringify(body) }),
15
+ signal: AbortSignal.timeout(10000),
16
+ });
17
+ checks++;
18
+ assert.equal(response.status, status, `${path} 状态码`);
19
+ const value = await response.json();
20
+ if (schema)
21
+ assert.deepEqual(checkSchema(schema, value), [], `${path} 格式`);
22
+ return value;
23
+ };
24
+ const doors = [
25
+ ["/v1/events", {}, ["source"]],
26
+ ["/v1/events/1", undefined, ["source"]],
27
+ ["/v1/tell", {}, ["source", "worker"]],
28
+ ["/v1/work?claim=probe&wait=0", undefined, ["worker"]],
29
+ ["/v1/cards/next?wait=0", undefined, ["channel"]],
30
+ ["/v1/state", undefined, ["owner"]],
31
+ ["/v1/stream", undefined, ["owner"]],
32
+ ["/v1/runs/1/started", {}, []],
33
+ ["/v1/runs/1/result", {}, []],
34
+ ["/v1/runs/1/cancel", {}, ["owner"]],
35
+ ["/v1/runs/1/why", undefined, ["owner"]],
36
+ ["/v1/cards/1/answer", {}, ["owner", "channel"]],
37
+ ["/v1/cards/1/resolve", {}, ["owner"]],
38
+ ["/v1/cards/1/delivered", {}, ["channel"]],
39
+ ["/v1/cards/1/failed", {}, ["channel"]],
40
+ ];
41
+ const everyKey = Object.entries({ ...keys, absent: "", madeup: "invalid" });
42
+ for (const [path, body, allowed] of doors) {
43
+ for (const [kind, key] of everyKey) {
44
+ if (!allowed.includes(kind))
45
+ await call(path, key, body, 401, "error");
46
+ }
47
+ }
48
+ assert.equal((await call("/healthz", "")).ok, true);
49
+ await call("/v1/not-a-door", keys.owner, undefined, 404, "error");
50
+ await call("/v1/in/missing", "", {}, 404, "error");
51
+ await call("/v1/events", keys.source, { id: tag, type: config.eventType, source: "someone-else" }, 400);
52
+ await call("/v1/events", keys.source, { type: config.eventType }, 400);
53
+ await call("/v1/events", keys.source, { id: tag, type: "not a type" }, 400);
54
+ for (const [body, status] of [
55
+ ["{invalid", 400],
56
+ [JSON.stringify({ id: tag, type: config.eventType, detail: "x".repeat(2 * 1024 * 1024) }), 413],
57
+ ]) {
58
+ const response = await request(base + "/v1/events", {
59
+ method: "POST",
60
+ headers: { authorization: `Bearer ${keys.source}` },
61
+ body,
62
+ });
63
+ checks++;
64
+ assert.equal(response.status, status, "事件正文边界");
65
+ assert.deepEqual(checkSchema("error", await response.json()), []);
66
+ }
67
+ await call("/v1/work?wait=0", keys.worker, undefined, 400);
68
+ await call("/v1/state?before=-1", keys.owner, undefined, 400);
69
+ await call("/v1/stream?after=-1", keys.owner, undefined, 400);
70
+ const event = { id: tag, type: config.eventType, subject: `#${tag}` };
71
+ const accepted = await call("/v1/events", keys.source, event, 200, "eventAck");
72
+ assert.equal(accepted.duplicate, false);
73
+ assert.ok(accepted.routed.length);
74
+ const duplicate = await call("/v1/events", keys.source, event, 200, "eventAck");
75
+ assert.equal(duplicate.event, accepted.event);
76
+ assert.equal(duplicate.duplicate, true);
77
+ const sent = await call(`/v1/events/${accepted.event}`, keys.source, undefined, 200, "eventOutcome");
78
+ assert.deepEqual(sent.routed, accepted.routed);
79
+ const take = () => call(`/v1/work?claim=${tag}&wait=0`, keys.worker, undefined, 200, "work");
80
+ const first = (await take()).job;
81
+ const job = (await take()).job;
82
+ assert.ok(job);
83
+ assert.equal(job.run, first.run);
84
+ await call(`/v1/runs/${job.run}/started`, first.token, {}, 401);
85
+ await call(`/v1/runs/${job.run}/started`, job.token, { session: `session-${tag}` });
86
+ await call("/v1/events", keys.source, { ...event, id: `other-${tag}`, subject: `other-${tag}` });
87
+ const otherJob = (await call(`/v1/work?claim=other-${tag}&wait=0`, keys.worker, undefined, 200, "work")).job;
88
+ assert.ok(otherJob, "检查规则的 parallel 至少要是 2");
89
+ assert.notEqual(otherJob.run, job.run);
90
+ await call(`/v1/runs/${otherJob.run}/result`, job.token, { outcome: "done" }, 401);
91
+ await call(`/v1/runs/${job.run}/result`, otherJob.token, { outcome: "done" }, 401);
92
+ await call(`/v1/runs/${otherJob.run}/result`, otherJob.token, { outcome: "done" });
93
+ await call(`/v1/runs/${job.run}/result`, job.token, { outcome: "unknown" }, 400);
94
+ const result = {
95
+ outcome: "done",
96
+ summary: "一致性检查",
97
+ ask: [
98
+ { title: `选择 ${tag}`, text: "选择一个", options: ["甲", "乙"], key: tag },
99
+ { title: `另一个 ${tag}`, text: "核实后关闭", options: ["甲", "乙"], key: `other-${tag}` },
100
+ ],
101
+ resolve: [{ card: 99999999, reason: "越界" }],
102
+ };
103
+ const receipt = await call(`/v1/runs/${job.run}/result`, job.token, result, 200, "receiptAck");
104
+ assert.equal(receipt.rejected.length, 1);
105
+ const replay = await call(`/v1/runs/${job.run}/result`, job.token, result, 200, "receiptAck");
106
+ assert.equal(replay.duplicate, true);
107
+ assert.deepEqual(replay.rejected, receipt.rejected);
108
+ await call(`/v1/runs/${job.run}/result`, job.token, { outcome: "nothing" }, 409);
109
+ const cards = [];
110
+ for (;;) {
111
+ const { card } = await call("/v1/cards/next?wait=0", keys.channel);
112
+ if (!card)
113
+ break;
114
+ assert.deepEqual(checkSchema("card", card), []);
115
+ cards.push(card);
116
+ await call(`/v1/cards/${card.id}/delivered`, keys.channel, { version: card.version, ref: `probe-${card.id}` });
117
+ }
118
+ const [card, other] = cards.filter(({ kind, title }) => kind === "ask" && title.endsWith(tag));
119
+ assert.ok(card && other);
120
+ const answer = { choice: 0, by: config.answerer, ref: `probe-${card.id}` };
121
+ await call(`/v1/cards/${card.id}/answer`, keys.channel, { ...answer, by: "not-allowed" }, 401);
122
+ await call(`/v1/cards/${card.id}/answer`, keys.channel, { ...answer, ref: "wrong" }, 401);
123
+ await call(`/v1/cards/${card.id}/answer`, keys.channel, { ...answer, choice: 99 }, 400);
124
+ assert.equal((await call(`/v1/cards/${card.id}/answer`, keys.channel, answer)).changed, true);
125
+ assert.equal((await call(`/v1/cards/${card.id}/answer`, keys.channel, { ...answer, choice: 1 })).changed, false);
126
+ await call(`/v1/cards/${other.id}/resolve`, keys.owner, { reason: " " }, 400);
127
+ assert.equal((await call(`/v1/cards/${other.id}/resolve`, keys.owner, { reason: "已核实" })).changed, true);
128
+ assert.equal((await call(`/v1/cards/${other.id}/answer`, keys.owner, { choice: 0 })).changed, false);
129
+ await call(`/v1/cards/${card.id}/failed`, keys.channel, { version: 1, error: "旧消息发送失败" });
130
+ const next = (await take()).job;
131
+ assert.equal(next.context.answers[0].choice, 0);
132
+ await call(`/v1/runs/${next.run}/cancel`, keys.owner, {});
133
+ assert.ok((await call("/v1/work?claim=cancel&capacity=0&wait=0", keys.worker)).cancel.includes(next.run));
134
+ await call(`/v1/runs/${next.run}/result`, next.token, { outcome: "cancelled" });
135
+ const told = await call("/v1/tell", keys.source, { key: tag, text: "检查完成" });
136
+ assert.equal(told.duplicate, false);
137
+ assert.equal((await call("/v1/tell", keys.source, { key: tag, text: "检查完成" })).duplicate, true);
138
+ await call("/v1/tell", keys.worker, { key: tag, task: "not-assigned", text: "不能冒充" }, 401);
139
+ const why = await call(`/v1/runs/${job.run}/why`, keys.owner);
140
+ assert.ok(why.some((fact) => fact.type === "finish"));
141
+ const abort = new AbortController();
142
+ const stream = await request(base + "/v1/stream?after=0", {
143
+ headers: { authorization: `Bearer ${keys.owner}` },
144
+ signal: abort.signal,
145
+ });
146
+ try {
147
+ checks++;
148
+ assert.equal(stream.status, 200);
149
+ assert.match(stream.headers.get("content-type") ?? "", /text\/event-stream/);
150
+ const reader = stream.body.getReader();
151
+ const decoder = new TextDecoder();
152
+ let text = "";
153
+ let count = 0;
154
+ while (!text.includes("\n\n")) {
155
+ const { done, value } = await reader.read();
156
+ assert.ok(!done, "日志流没有完整事实");
157
+ text += decoder.decode(value, { stream: true });
158
+ }
159
+ for (const block of text.split("\n\n").slice(0, -1)) {
160
+ const id = /^id: (\d+)$/m.exec(block);
161
+ const data = /^data: (.+)$/m.exec(block);
162
+ assert.ok(id && data, "日志流缺少事实");
163
+ const fact = JSON.parse(data[1]);
164
+ assert.deepEqual(checkSchema("fact", fact), []);
165
+ assert.equal(fact.seq, Number(id[1]));
166
+ const leaksKeys = fact.changes.some((change) => change.table === "keys");
167
+ assert.ok(!leaksKeys, "日志流泄露密钥记录");
168
+ count++;
169
+ }
170
+ assert.ok(count);
171
+ for (const key of Object.values(keys))
172
+ assert.ok(!text.includes(key));
173
+ await reader.cancel();
174
+ }
175
+ finally {
176
+ abort.abort();
177
+ }
178
+ await call("/v1/state", keys.owner);
179
+ return { checks, passed: true };
180
+ }
181
+ if (import.meta.main) {
182
+ const config = JSON.parse(readFileSync(process.argv[3], "utf8"));
183
+ console.log(JSON.stringify(await conformance(process.argv[2], config), null, 2));
184
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,230 @@
1
+ // rules.json: the sources that may send events, the agents that do the work, the channels that reach the owner, the
2
+ // rules between them and, only to be shown, the scheduled tasks that run elsewhere. A mistake is caught here with a
3
+ // message saying where: at start it stops the hub, later it leaves the old rules running and the owner is told.
4
+ import { nextRun, parseCron } from "../kernel/cron.js";
5
+ import { SCHEDULE } from "../kernel/rules.js";
6
+ export class RulesError extends Error {
7
+ issues;
8
+ constructor(issues) {
9
+ super(`rules.json 有问题:\n${issues.join("\n")}`);
10
+ this.issues = issues;
11
+ }
12
+ }
13
+ const ACCESS = ["read", "edit", "full"];
14
+ const TELLS = ["always", "needed", "never"];
15
+ const ID = /^[a-z][a-z0-9-]*$/;
16
+ const TYPE_PATTERN = /^(\*|[a-z][a-z0-9_.-]{0,63}(\.\*)?)$/;
17
+ const ASK_FIRST = ["删数据", "停服", "花钱", "对外发消息", "改产品方向", "新建或轮换密钥", "修改权限"];
18
+ const NOT_EMPTY = "不能为空";
19
+ const ID_WORDS = "只能用小写字母、数字和 -";
20
+ const isText = (value) => typeof value === "string" && value.trim() !== "";
21
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
22
+ const isWords = (value) => Array.isArray(value) && value.every(isText);
23
+ const isSomeWords = (value) => isWords(value) && value.length > 0;
24
+ const isId = (value) => typeof value === "string" && ID.test(value);
25
+ const isCount = (value) => Number.isInteger(value) && value > 0;
26
+ const isTypes = (value) => isSomeWords(value) && value.every((type) => TYPE_PATTERN.test(type));
27
+ const isCron = (value) => typeof value === "string" && parseCron(value) !== null;
28
+ // One word, as a client may name a session after the first word of its first message. It leads the prompt, which goes to
29
+ // the Agent's command line as an argument: started with a subject from outside it could be read as an option or command.
30
+ const isTitle = (value) => typeof value === "string" &&
31
+ /^[\p{L}\p{N}]\S*$/u.test(value) &&
32
+ !/[{}]/.test(value.replaceAll("{id}", "").replaceAll("{subject}", ""));
33
+ const isFolder = (value) => typeof value === "string" && /^(~[/\\]|\/|[a-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/i.test(value);
34
+ const FOLDER = "要是绝对目录(如 ~/code、/srv/app、C:\\code 或 \\\\服务器\\共享目录)";
35
+ function isKeyOf(table) {
36
+ return (value) => typeof value === "string" && value in table;
37
+ }
38
+ function isZone(zone) {
39
+ try {
40
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
41
+ return isText(zone);
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
47
+ /** Each field present and well formed, and no others: a misspelt field would otherwise be silently ignored. */
48
+ function checkFields(issues, where, value, spec) {
49
+ if (!isObject(value))
50
+ return void issues.push(`${where}要是一个对象`);
51
+ for (const [name, check, problem, optional] of spec) {
52
+ if (!(name in value)) {
53
+ if (!optional)
54
+ issues.push(`${where}缺少 ${name}`);
55
+ }
56
+ else if (!check(value[name]))
57
+ issues.push(`${where}的 ${name} ${problem}`);
58
+ }
59
+ for (const name of Object.keys(value)) {
60
+ if (!spec.some(([known]) => known === name))
61
+ issues.push(`${where}有不认识的字段 ${name}`);
62
+ }
63
+ }
64
+ const nameOf = (entry) => (isObject(entry) && typeof entry.name === "string" ? entry.name : "");
65
+ function checkRule(issues, rules, rule, names, now) {
66
+ const name = nameOf(rule);
67
+ if (names.has(name))
68
+ issues.push(`规则名「${name}」重复了`);
69
+ names.add(name);
70
+ const where = `规则「${name}」`;
71
+ const when = isObject(rule) ? rule.when : undefined;
72
+ checkFields(issues, where, rule, [
73
+ ["name", isText, NOT_EMPTY],
74
+ ["when", isObject, "要是一个对象"],
75
+ ["to", isKeyOf(rules.agents), `不是已登记的 Agent:${isObject(rule) ? rule.to : ""}`],
76
+ ["cwd", isFolder, FOLDER],
77
+ ["skill", isText, NOT_EMPTY, true],
78
+ ["prompt", isText, NOT_EMPTY, true],
79
+ ["title", isTitle, "要是字母或数字开头、不含空白的一个词,占位符只能用 {id}、{subject}", true],
80
+ ["group", isText, NOT_EMPTY, true],
81
+ ["parallel", isCount, "要是正整数", true],
82
+ ["maxActive", isCount, "要是正整数", true],
83
+ ["resume", (value) => typeof value === "boolean", "只能是 true 或 false", true],
84
+ ["tell", (value) => TELLS.includes(value), `只能是 ${TELLS.join("、")}`, true],
85
+ ["emits", isObject, "要是一个对象", true],
86
+ ["channels", isSomeWords, "要是通道编号的列表", true],
87
+ ]);
88
+ if (isObject(when) && "source" in when) {
89
+ checkFields(issues, `${where}的 when `, when, [
90
+ ["source", isKeyOf(rules.sources), `不是已登记的来源:${when.source}`],
91
+ ["types", isTypes, "要是事件类型的列表,可以用 x.* 或 *"],
92
+ ]);
93
+ }
94
+ else if (isObject(when)) {
95
+ if (isCron(when.cron) && nextRun(parseCron(when.cron), now, rules.timezone) === null) {
96
+ issues.push(`${where}的定时永远不会到来:${when.cron}`);
97
+ }
98
+ checkFields(issues, `${where}的 when `, when, [["cron", isCron, "不是有效的 cron"]]);
99
+ }
100
+ if (!isObject(rule))
101
+ return;
102
+ // A plain command needs no words: a script that polls something is an agent too.
103
+ if (!rule.skill && !rule.prompt && rules.agents[rule.to]?.use !== "command") {
104
+ issues.push(`${where}的 skill 和 prompt 至少写一个`);
105
+ }
106
+ if (isObject(rule.emits)) {
107
+ const emittable = (value) => value !== SCHEDULE && isKeyOf(rules.sources)(value);
108
+ checkFields(issues, `${where}的 emits `, rule.emits, [
109
+ ["source", emittable, `不是已登记的来源:${rule.emits.source}`],
110
+ ["types", isTypes, "要是事件类型的列表"],
111
+ ]);
112
+ }
113
+ for (const channel of isSomeWords(rule.channels) ? rule.channels : []) {
114
+ if (!Object.hasOwn(rules.channels, channel))
115
+ issues.push(`${where}的 channels 不是已登记的通道:${channel}`);
116
+ }
117
+ rule.group ??= rule.name;
118
+ rule.tell ??= "needed";
119
+ }
120
+ export function parseRules(json, now, timezone) {
121
+ let parsed;
122
+ try {
123
+ parsed = JSON.parse(json);
124
+ }
125
+ catch (error) {
126
+ throw new RulesError([`不是 JSON:${error.message}`]);
127
+ }
128
+ const issues = [];
129
+ checkFields(issues, "rules.json ", parsed, [
130
+ ["timezone", isZone, "不是有效的时区", true],
131
+ ["askFirst", isWords, "要是文字的列表", true],
132
+ ["sources", isObject, "要是一个对象"],
133
+ ["agents", isObject, "要是一个对象"],
134
+ ["channels", isObject, "要是一个对象", true],
135
+ ["defaultChannels", isSomeWords, "要是通道编号的列表", true],
136
+ ["rules", Array.isArray, "要是一个列表"],
137
+ ["elsewhere", Array.isArray, "要是一个列表", true],
138
+ ]);
139
+ if (issues.length)
140
+ throw new RulesError(issues);
141
+ const rules = parsed;
142
+ rules.timezone ??= timezone;
143
+ rules.askFirst ??= ASK_FIRST;
144
+ rules.channels ??= {};
145
+ rules.elsewhere ??= [];
146
+ if (SCHEDULE in rules.sources)
147
+ issues.push(`来源 ${SCHEDULE} 是保留的,定时用规则的 cron`);
148
+ for (const [id, source] of Object.entries(rules.sources)) {
149
+ if (!ID.test(id))
150
+ issues.push(`来源的编号${ID_WORDS}:${id}`);
151
+ checkFields(issues, `来源 ${id} `, source, [
152
+ ["name", isText, NOT_EMPTY],
153
+ ["adapter", isText, NOT_EMPTY, true],
154
+ ]);
155
+ }
156
+ rules.sources[SCHEDULE] = { name: "定时" };
157
+ for (const [id, channel] of Object.entries(rules.channels)) {
158
+ if (!ID.test(id))
159
+ issues.push(`通道的编号${ID_WORDS}:${id}`);
160
+ checkFields(issues, `通道 ${id} `, channel, [
161
+ ["name", isText, NOT_EMPTY],
162
+ ["answerers", isWords, "要是文字的列表", true],
163
+ ["links", (value) => typeof value === "boolean", "要是 true 或 false", true],
164
+ ]);
165
+ }
166
+ for (const channel of rules.defaultChannels ?? []) {
167
+ if (!Object.hasOwn(rules.channels, channel))
168
+ issues.push(`rules.json 的 defaultChannels 不是已登记的通道:${channel}`);
169
+ }
170
+ for (const [id, agent] of Object.entries(rules.agents)) {
171
+ if (!ID.test(id))
172
+ issues.push(`Agent 的编号${ID_WORDS}:${id}`);
173
+ checkFields(issues, `Agent ${id} `, agent, [
174
+ ["name", isText, NOT_EMPTY],
175
+ ["worker", isId, ID_WORDS],
176
+ ["use", isId, ID_WORDS],
177
+ ["model", isText, NOT_EMPTY, true],
178
+ ["effort", isText, NOT_EMPTY, true],
179
+ ["tier", isText, NOT_EMPTY, true],
180
+ ["access", (value) => ACCESS.includes(value), `只能是 ${ACCESS.join("、")}`, true],
181
+ ["command", isSomeWords, "要是命令行的列表", !isObject(agent) || agent.use !== "command"],
182
+ ["program", isText, "要是一个程序的路径", true],
183
+ ["timeout", isCount, "要是正整数(分钟)", true],
184
+ ["maxActive", isCount, "要是正整数", true],
185
+ ]);
186
+ if (isObject(agent))
187
+ agent.access ??= "edit";
188
+ }
189
+ const names = new Set();
190
+ for (const rule of rules.rules)
191
+ checkRule(issues, rules, rule, names, now);
192
+ if (issues.length)
193
+ throw new RulesError(issues);
194
+ const limits = new Map();
195
+ for (const { group, parallel } of rules.rules) {
196
+ if (limits.has(group) && limits.get(group) !== parallel)
197
+ issues.push(`组「${group}」里的规则 parallel 要一致`);
198
+ limits.set(group, parallel);
199
+ }
200
+ for (const task of rules.elsewhere) {
201
+ const name = nameOf(task);
202
+ if (names.has(name))
203
+ issues.push(`定时任务「${name}」和别的规则或定时任务重名`);
204
+ names.add(name);
205
+ checkFields(issues, `定时任务「${name}」`, task, [
206
+ ["name", isText, NOT_EMPTY],
207
+ ["source", isKeyOf(rules.sources), "不是已登记的来源"],
208
+ ["to", isKeyOf(rules.agents), "不是已登记的 Agent"],
209
+ ["cron", isCron, "不是有效的 cron"],
210
+ ["where", isText, NOT_EMPTY],
211
+ ["model", isText, NOT_EMPTY, true],
212
+ ["effort", isText, NOT_EMPTY, true],
213
+ ["cwd", isFolder, FOLDER, true],
214
+ ["skill", isText, NOT_EMPTY, true],
215
+ ["prompt", isText, NOT_EMPTY, true],
216
+ ]);
217
+ if (!isObject(task))
218
+ continue;
219
+ // Its answers go on like a round of a rule, so they need what a rule needs.
220
+ const words = task.skill !== undefined || task.prompt !== undefined;
221
+ if (words && task.cwd === undefined)
222
+ issues.push(`定时任务「${name}」写了回答后照什么做,还要写 cwd:在哪接着做`);
223
+ if (task.cwd !== undefined && !words && rules.agents[task.to]?.use !== "command") {
224
+ issues.push(`定时任务「${name}」写了 cwd,skill 和 prompt 至少写一个:回答后照什么做`);
225
+ }
226
+ }
227
+ if (issues.length)
228
+ throw new RulesError(issues);
229
+ return rules;
230
+ }
@@ -0,0 +1,70 @@
1
+ // JSON Schema, as much of it as protocol/schema.json uses, so checking the protocol needs nothing installed.
2
+ import { readFileSync } from "node:fs";
3
+ import { dateTime } from "./validate.js";
4
+ export const schemas = JSON.parse(readFileSync(new URL("./schema.json", import.meta.url), "utf8"));
5
+ function hasType(type, item) {
6
+ if (type === "object")
7
+ return item !== null && typeof item === "object" && !Array.isArray(item);
8
+ if (type === "array")
9
+ return Array.isArray(item);
10
+ if (type === "integer")
11
+ return Number.isSafeInteger(item);
12
+ if (type === "null")
13
+ return item === null;
14
+ return typeof item === type;
15
+ }
16
+ const outside = (value, min, max) => (min !== undefined && value < min) || (max !== undefined && value > max);
17
+ function visit(schema, item, path) {
18
+ const passes = (option) => visit(option, item, path).length === 0;
19
+ if (schema.$ref)
20
+ return visit(schemas.$defs[schema.$ref.split("/").at(-1)], item, path);
21
+ if (schema.anyOf && !schema.anyOf.some(passes))
22
+ return [path];
23
+ if (schema.oneOf && schema.oneOf.filter(passes).length !== 1)
24
+ return [path];
25
+ if (schema.const !== undefined && item !== schema.const)
26
+ return [path];
27
+ if (schema.enum && !schema.enum.includes(item))
28
+ return [path];
29
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
30
+ if (schema.type && !types.some((type) => hasType(type, item)))
31
+ return [path];
32
+ if (typeof item === "string") {
33
+ if (outside([...item].length, schema.minLength, schema.maxLength))
34
+ return [path];
35
+ if (schema.pattern && !new RegExp(schema.pattern, "u").test(item))
36
+ return [path];
37
+ }
38
+ if (schema.format === "date-time" && !dateTime(item))
39
+ return [path];
40
+ if (typeof item === "number") {
41
+ if (!Number.isFinite(item) || outside(item, schema.minimum, schema.maximum))
42
+ return [path];
43
+ }
44
+ if (Array.isArray(item)) {
45
+ if (outside(item.length, schema.minItems, schema.maxItems))
46
+ return [path];
47
+ return item.flatMap((child, index) => (schema.items ? visit(schema.items, child, `${path}[${index}]`) : []));
48
+ }
49
+ if (item === null || typeof item !== "object")
50
+ return [];
51
+ const required = schema.required ?? [];
52
+ const errors = required.filter((key) => !Object.hasOwn(item, key)).map((key) => `${path}.${key}`);
53
+ for (const [key, child] of Object.entries(item)) {
54
+ const known = Object.hasOwn(schema.properties ?? {}, key) ? schema.properties[key] : undefined;
55
+ const childPath = `${path}.${key}`;
56
+ if (known)
57
+ errors.push(...visit(known, child, childPath));
58
+ else if (schema.additionalProperties === false)
59
+ errors.push(childPath);
60
+ else if (typeof schema.additionalProperties === "object") {
61
+ errors.push(...visit(schema.additionalProperties, child, childPath));
62
+ }
63
+ }
64
+ return errors;
65
+ }
66
+ export function checkSchema(name, value) {
67
+ if (!Object.hasOwn(schemas.$defs, name))
68
+ throw new Error(`没有这个协议类型:${name}`);
69
+ return visit(schemas.$defs[name], value, name);
70
+ }