@saltpub/agent-autoloop 0.0.0-stage → 0.1.2

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 (171) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/INSTALL.md +118 -0
  3. package/LICENSE +21 -0
  4. package/README.en.md +264 -0
  5. package/README.md +260 -2
  6. package/SECURITY.md +48 -0
  7. package/dist/bin/agent-autoloop.js +2 -0
  8. package/dist/cli/backup.js +144 -0
  9. package/dist/cli/explain.js +84 -0
  10. package/dist/cli/main.js +1016 -0
  11. package/dist/cli/mcp.js +151 -0
  12. package/dist/cli/runs.js +40 -0
  13. package/dist/cli/spend.js +21 -0
  14. package/dist/cli/status.js +304 -0
  15. package/dist/cli/try.js +6 -0
  16. package/dist/cli/uninstall.js +84 -0
  17. package/dist/cli/update.js +65 -0
  18. package/dist/cli/why.js +115 -0
  19. package/dist/host/background-launcher.js +12 -0
  20. package/dist/host/background.js +24 -0
  21. package/dist/host/channels.js +4 -0
  22. package/dist/host/command.js +98 -0
  23. package/dist/host/config.js +37 -0
  24. package/dist/host/files.js +22 -0
  25. package/dist/host/home.js +5 -0
  26. package/dist/host/http.js +43 -0
  27. package/dist/host/launcher.js +188 -0
  28. package/dist/host/lines.js +15 -0
  29. package/dist/host/node-path.js +33 -0
  30. package/dist/host/npm.js +28 -0
  31. package/dist/host/plugins.js +26 -0
  32. package/dist/host/program.js +14 -0
  33. package/dist/host/runtime.js +179 -0
  34. package/dist/host/server.js +159 -0
  35. package/dist/host/service.js +325 -0
  36. package/dist/host/state.js +203 -0
  37. package/dist/host/up.js +162 -0
  38. package/dist/host/update.js +286 -0
  39. package/dist/host/version.js +81 -0
  40. package/dist/kernel/card-page.js +54 -0
  41. package/dist/kernel/credentials.js +16 -0
  42. package/dist/kernel/cron.js +135 -0
  43. package/dist/kernel/decide.js +826 -0
  44. package/dist/kernel/due.js +73 -0
  45. package/dist/kernel/errors.js +9 -0
  46. package/dist/kernel/evolve.js +264 -0
  47. package/dist/kernel/http.js +357 -0
  48. package/dist/kernel/query.js +202 -0
  49. package/dist/kernel/rules.js +20 -0
  50. package/dist/kernel/store.js +52 -0
  51. package/dist/plugins/acp/agent.js +32 -0
  52. package/dist/plugins/acp/bridge.js +204 -0
  53. package/dist/plugins/claude/agent.js +113 -0
  54. package/dist/plugins/codex/agent.js +105 -0
  55. package/dist/plugins/command/agent.js +25 -0
  56. package/dist/plugins/delivery/action.js +25 -0
  57. package/dist/plugins/delivery/agent.js +13 -0
  58. package/dist/plugins/delivery/delivery.js +388 -0
  59. package/dist/plugins/delivery/github.js +201 -0
  60. package/dist/plugins/delivery/handoff.js +50 -0
  61. package/dist/plugins/delivery/input.js +47 -0
  62. package/dist/plugins/delivery/poll.js +72 -0
  63. package/dist/plugins/delivery/project.js +144 -0
  64. package/dist/plugins/delivery/review-ledger.js +82 -0
  65. package/dist/plugins/delivery/review-policy.js +99 -0
  66. package/dist/plugins/delivery/review.js +280 -0
  67. package/dist/plugins/delivery/run.js +204 -0
  68. package/dist/plugins/desktop/channel.js +94 -0
  69. package/dist/plugins/dsh/agent.js +116 -0
  70. package/dist/plugins/feishu/channel.js +245 -0
  71. package/dist/plugins/github/source.js +30 -0
  72. package/dist/plugins/gitlab/source.js +30 -0
  73. package/dist/plugins/omp/agent.js +3 -0
  74. package/dist/plugins/opencode/agent.js +88 -0
  75. package/dist/plugins/pi/agent.js +92 -0
  76. package/dist/plugins/webhook/channel.js +70 -0
  77. package/dist/plugins/webhook/templates.js +34 -0
  78. package/dist/plugins/xiaojiu/channel.js +410 -0
  79. package/dist/plugins/zcode/agent.js +102 -0
  80. package/dist/protocol/client.js +56 -0
  81. package/dist/protocol/conformance.js +184 -0
  82. package/dist/protocol/job.js +1 -0
  83. package/dist/protocol/rules.js +230 -0
  84. package/dist/protocol/schema.js +70 -0
  85. package/dist/protocol/schema.json +985 -0
  86. package/dist/protocol/validate.js +150 -0
  87. package/dist/worker/agents.js +47 -0
  88. package/dist/worker/contract.js +178 -0
  89. package/dist/worker/run.js +52 -0
  90. package/dist/worker/usage.js +45 -0
  91. package/dist/worker/windows.ps1 +48 -0
  92. package/dist/worker/worker.js +595 -0
  93. package/docs/architecture.en.svg +178 -0
  94. package/docs/architecture.svg +178 -0
  95. package/docs/auto-update.md +53 -0
  96. package/docs/plugins.md +139 -0
  97. package/docs/protocol.md +582 -0
  98. package/docs/state-machines.md +77 -0
  99. package/examples/channel.sh +15 -0
  100. package/examples/plugins/hello-agent/agent.ts +40 -0
  101. package/examples/plugins/hello-channel/channel.ts +54 -0
  102. package/examples/plugins/hello-source/source.ts +19 -0
  103. package/examples/recipes/browser-handoff/README.md +44 -0
  104. package/examples/recipes/browser-handoff/SKILL.md +22 -0
  105. package/examples/recipes/browser-handoff/browser.json +10 -0
  106. package/examples/recipes/browser-handoff/handoff.ts +44 -0
  107. package/examples/recipes/browser-handoff/rules.json +19 -0
  108. package/examples/recipes/feedback/README.md +34 -0
  109. package/examples/recipes/feedback/SKILL.md +22 -0
  110. package/examples/recipes/feedback/event.json +8 -0
  111. package/examples/recipes/feedback/rules.json +37 -0
  112. package/examples/recipes/feishu-brief/README.md +28 -0
  113. package/examples/recipes/feishu-brief/SKILL.md +16 -0
  114. package/examples/recipes/feishu-brief/collect.ts +164 -0
  115. package/examples/recipes/feishu-brief/rules.json +57 -0
  116. package/examples/recipes/feishu-brief/sources.json +13 -0
  117. package/examples/recipes/github-issues/README.md +17 -0
  118. package/examples/recipes/github-issues/SKILL.md +18 -0
  119. package/examples/recipes/github-issues/rules.json +30 -0
  120. package/examples/recipes/inbox-triage/README.md +36 -0
  121. package/examples/recipes/inbox-triage/SKILL.md +19 -0
  122. package/examples/recipes/inbox-triage/collect.ts +191 -0
  123. package/examples/recipes/inbox-triage/rules.json +57 -0
  124. package/examples/recipes/inbox-triage/sources.json +8 -0
  125. package/examples/recipes/morning-brief/README.md +17 -0
  126. package/examples/recipes/morning-brief/SKILL.md +17 -0
  127. package/examples/recipes/morning-brief/rules.json +16 -0
  128. package/examples/recipes/ops-alerts/README.md +18 -0
  129. package/examples/recipes/ops-alerts/SKILL.md +34 -0
  130. package/examples/recipes/ops-alerts/restart.sh +5 -0
  131. package/examples/recipes/ops-alerts/rules.json +29 -0
  132. package/examples/recipes/website-watch/README.md +26 -0
  133. package/examples/recipes/website-watch/SKILL.md +19 -0
  134. package/examples/recipes/website-watch/check.ts +86 -0
  135. package/examples/recipes/website-watch/rules.json +56 -0
  136. package/examples/recipes/website-watch/site.json +6 -0
  137. package/examples/skills/weekly-sweep/SKILL.md +17 -0
  138. package/examples/watch-github-issues.sh +23 -0
  139. package/examples/worker.sh +18 -0
  140. package/package.json +55 -4
  141. package/plugins/acp/agent.ts +31 -0
  142. package/plugins/acp/bridge.ts +190 -0
  143. package/plugins/claude/agent.ts +121 -0
  144. package/plugins/codex/agent.ts +103 -0
  145. package/plugins/command/agent.ts +25 -0
  146. package/plugins/delivery/action.ts +29 -0
  147. package/plugins/delivery/action.yml +28 -0
  148. package/plugins/delivery/agent.ts +15 -0
  149. package/plugins/delivery/delivery.ts +408 -0
  150. package/plugins/delivery/github.ts +207 -0
  151. package/plugins/delivery/handoff.ts +72 -0
  152. package/plugins/delivery/input.ts +55 -0
  153. package/plugins/delivery/poll.ts +65 -0
  154. package/plugins/delivery/project.ts +161 -0
  155. package/plugins/delivery/review-ledger.ts +90 -0
  156. package/plugins/delivery/review-policy.ts +126 -0
  157. package/plugins/delivery/review.ts +324 -0
  158. package/plugins/delivery/run.ts +219 -0
  159. package/plugins/desktop/channel.ts +100 -0
  160. package/plugins/dsh/agent.ts +100 -0
  161. package/plugins/feishu/channel.ts +243 -0
  162. package/plugins/github/source.ts +33 -0
  163. package/plugins/gitlab/source.ts +32 -0
  164. package/plugins/omp/agent.ts +4 -0
  165. package/plugins/opencode/agent.ts +78 -0
  166. package/plugins/pi/agent.ts +80 -0
  167. package/plugins/webhook/channel.ts +74 -0
  168. package/plugins/webhook/templates.ts +32 -0
  169. package/plugins/xiaojiu/channel.ts +426 -0
  170. package/plugins/zcode/agent.ts +96 -0
  171. package/skills/agent-autoloop/SKILL.md +260 -0
@@ -0,0 +1,357 @@
1
+ // The doors: every request the hub takes, which key it asks for, and which input it becomes. Nothing is decided here.
2
+ import { cardPage, PAGE_HEADERS, wordsPage } from "./card-page.js";
3
+ import { whose } from "./credentials.js";
4
+ import { AuthError, Conflict, InputError, NotFound } from "./errors.js";
5
+ import { iso } from "./evolve.js";
6
+ import { agentsOf, cancels, cardView, configuration, eventOutcome } from "./query.js";
7
+ import { eventRule, ruleOf } from "./rules.js";
8
+ import { isAsk } from "../protocol/validate.js";
9
+ const MAX_BODY = 1024 * 1024;
10
+ const MAX_WAIT_SECONDS = 50;
11
+ const LINK_LIFETIME = 7 * 86400_000;
12
+ const CARD_LINK = /^\/c\/([A-Za-z0-9_-]{1,64})$/;
13
+ const POSITIVE_ID = /^[1-9][0-9]*$/;
14
+ const KEY_HOLDERS = { owner: "本人", worker: "接单程序", channel: "通道", source: "来源" };
15
+ const NO_STORE = { "cache-control": "no-store" };
16
+ class TooLarge extends Error {
17
+ }
18
+ async function readText(request) {
19
+ if (!request.body)
20
+ return "";
21
+ // A little over the limit is read to its end: hanging up mid-upload can cost the client its 413.
22
+ if (Number(request.headers.get("content-length")) > 8 * MAX_BODY)
23
+ throw new TooLarge();
24
+ const reader = request.body.getReader();
25
+ const chunks = [];
26
+ let size = 0;
27
+ for (;;) {
28
+ const { done, value } = await reader.read();
29
+ if (done)
30
+ break;
31
+ size += value.length;
32
+ if (size <= MAX_BODY)
33
+ chunks.push(value);
34
+ if (size > 8 * MAX_BODY)
35
+ throw new TooLarge();
36
+ }
37
+ if (size > MAX_BODY)
38
+ throw new TooLarge();
39
+ return Buffer.concat(chunks).toString("utf8");
40
+ }
41
+ async function readJson(request) {
42
+ const text = await readText(request);
43
+ try {
44
+ return JSON.parse(text);
45
+ }
46
+ catch {
47
+ throw new InputError("不是 JSON");
48
+ }
49
+ }
50
+ const json = (value, status = 200) => Response.json(value, { status, headers: NO_STORE });
51
+ function statusOf(error) {
52
+ if (error instanceof TooLarge)
53
+ return 413;
54
+ if (error instanceof InputError)
55
+ return 400;
56
+ if (error instanceof AuthError)
57
+ return 401;
58
+ if (error instanceof Conflict)
59
+ return 409;
60
+ if (error instanceof NotFound)
61
+ return 404;
62
+ return 500;
63
+ }
64
+ function callFrom(services, request) {
65
+ const url = new URL(request.url);
66
+ const token = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
67
+ const now = services.now();
68
+ const view = services.view();
69
+ return { services, request, url, token, now, view, rules: configuration(view) };
70
+ }
71
+ const keyHolder = (call, kind) => whose(call.view, kind, call.token);
72
+ const act = (call, type, ...args) => call.services.dispatch(type, args, call.services.now());
73
+ function requireKey(call, kind) {
74
+ const holder = keyHolder(call, kind);
75
+ if (!holder)
76
+ throw new AuthError(`要${KEY_HOLDERS[kind]}自己的密钥`);
77
+ return holder;
78
+ }
79
+ function ownerAct(call, type, ...args) {
80
+ requireKey(call, "owner");
81
+ act(call, type, ...args);
82
+ return json({ ok: true });
83
+ }
84
+ /** When a long poll gives up: as long as it asked to wait, up to the most anyone gets. */
85
+ function waitUntil(call) {
86
+ const seconds = Number(call.url.searchParams.get("wait") ?? MAX_WAIT_SECONDS) || 0;
87
+ return call.now + Math.min(Math.max(seconds, 0), MAX_WAIT_SECONDS) * 1000;
88
+ }
89
+ async function cardAtLink(call, linkToken) {
90
+ const { rules, request } = call;
91
+ const { environment } = call.services;
92
+ const card = call.services.card(linkToken);
93
+ const linksInUse = Object.values(rules.channels).some((channel) => channel.links);
94
+ if (!card || !linksInUse)
95
+ throw new NotFound("没有这张卡片");
96
+ if (call.now - Date.parse(card.created_at) > LINK_LIFETIME) {
97
+ throw new AuthError("这个链接过期了。在装它的电脑上运行 agent-autoloop status,还没答的卡片都在那里,可以接着回答");
98
+ }
99
+ if (request.method === "GET")
100
+ return new Response(cardPage(cardView(card, environment)), { headers: PAGE_HEADERS });
101
+ const form = new URLSearchParams(await readText(request));
102
+ const choice = form.has("choice") && { choice: Number(form.get("choice")) };
103
+ act(call, "answer", card.id, { ...choice, text: form.get("text") ?? undefined, by: "链接" });
104
+ return new Response(null, { status: 303, headers: { location: call.url.pathname, ...NO_STORE } });
105
+ }
106
+ async function webhook(call, source) {
107
+ if (!call.rules.sources[source]?.adapter)
108
+ throw new NotFound("这个来源不收 Webhook");
109
+ const events = await call.services.adapt(source, call.request.headers, await readText(call.request));
110
+ return json({ events: events.map((event) => act(call, "ingest", source, event)) });
111
+ }
112
+ async function tell(call) {
113
+ const { rules } = call;
114
+ const source = keyHolder(call, "source");
115
+ const worker = source ? null : keyHolder(call, "worker");
116
+ if (!source && !worker)
117
+ throw new AuthError("要来源或接单程序的密钥");
118
+ const input = await readJson(call.request);
119
+ // A task elsewhere either tells you something or asks you, with a question just as a receipt's.
120
+ if (worker && input && typeof input === "object" && "ask" in input)
121
+ return askAsTask(call, worker, input);
122
+ const expected = source ? ["key", "text"] : ["key", "task", "text"];
123
+ const hasExpected = input && typeof input === "object" && Object.keys(input).sort().join() === expected.join();
124
+ const keyIsValid = typeof input?.key === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(input.key);
125
+ const text = typeof input?.text === "string" ? input.text.trim() : "";
126
+ if (!hasExpected || !keyIsValid || !text || [...text].length > 20_000) {
127
+ throw new InputError("要有正确的 key 和 text,接单程序还要写 task,text 最多 20000 字;问你的写 task 和 ask");
128
+ }
129
+ if (source) {
130
+ return json(act(call, "tell", `source:${source}:${input.key}`, rules.sources[source]?.name ?? source, text));
131
+ }
132
+ const task = taskOf(call, worker, input.task);
133
+ return json(act(call, "tell", `elsewhere:${task.name}:${input.key}`, task.name, text));
134
+ }
135
+ function taskOf({ rules, view }, worker, name) {
136
+ const task = rules.elsewhere.find((task) => task.name === name && agentsOf(view, worker).includes(task.to));
137
+ if (!task)
138
+ throw new AuthError("这台接单程序没有这个定时任务");
139
+ return task;
140
+ }
141
+ function askAsTask(call, worker, input) {
142
+ if (Object.keys(input).sort().join() !== "ask,task" || !isAsk(input.ask)) {
143
+ throw new InputError("问你的只写 task 和 ask,ask 和回执里的一样:title、text、2 到 5 个 options");
144
+ }
145
+ return json(act(call, "ask", taskOf(call, worker, input.task).name, input.ask));
146
+ }
147
+ async function work(call) {
148
+ const { services, request, url, token } = call;
149
+ const worker = requireKey(call, "worker");
150
+ const claim = url.searchParams.get("claim") ?? "";
151
+ if (!claim || claim.length > 200)
152
+ throw new InputError("claim 是这次领活的编号,最多 200 字");
153
+ const running = (url.searchParams.get("running") ?? "").split(",").filter((id) => POSITIVE_ID.test(id));
154
+ act(call, "heartbeat", worker, running.map(Number));
155
+ const until = waitUntil(call);
156
+ for (;;) {
157
+ if (!whose(services.view(), "worker", token))
158
+ throw new AuthError("密钥已失效");
159
+ const wantsWork = !request.signal.aborted && url.searchParams.get("capacity") !== "0";
160
+ const job = wantsWork ? act(call, "claimNext", worker, claim) : null;
161
+ const cancel = cancels(services.view(), worker);
162
+ if (job || cancel.length || services.now() >= until || request.signal.aborted)
163
+ return json({ job, cancel });
164
+ await services.wait(until, request.signal);
165
+ }
166
+ }
167
+ async function nextCard(call) {
168
+ const { services, request, token } = call;
169
+ const channel = requireKey(call, "channel");
170
+ const until = waitUntil(call);
171
+ act(call, "channelSeen", channel);
172
+ for (;;) {
173
+ if (!whose(services.view(), "channel", token))
174
+ throw new AuthError("密钥已失效");
175
+ const card = request.signal.aborted ? null : act(call, "nextCard", channel);
176
+ if (card || services.now() >= until || request.signal.aborted)
177
+ return json({ card });
178
+ await services.wait(until, request.signal);
179
+ }
180
+ }
181
+ async function cardAction(call, id, action) {
182
+ const channel = keyHolder(call, "channel");
183
+ requireKey(call, action === "resolve" || (action === "answer" && !channel) ? "owner" : "channel");
184
+ const given = await readJson(call.request);
185
+ if (action === "resolve") {
186
+ const reason = given?.reason;
187
+ if (typeof reason !== "string" || !reason.trim() || reason.length > 1000) {
188
+ throw new InputError("写一句处理结果,最多 1000 字");
189
+ }
190
+ return json({ changed: act(call, "resolve", id, reason.trim(), "本人") });
191
+ }
192
+ if (action === "answer") {
193
+ const who = channel ? { by: given?.by, ref: given?.ref, channel } : { by: "本人" };
194
+ return json(act(call, "answer", id, { choice: given?.choice, text: given?.text, ...who }));
195
+ }
196
+ if (!Number.isInteger(given?.version))
197
+ throw new InputError("要说明是哪个版本");
198
+ const ref = typeof given.ref === "string" ? given.ref : null;
199
+ act(call, action, channel, id, given.version, action === "delivered" ? ref : String(given.error ?? ""));
200
+ return json({ ok: true });
201
+ }
202
+ const CONTROL_FIELDS = {
203
+ pause: ["reason", "until"],
204
+ resume: [],
205
+ run: ["subject", "reason"],
206
+ replay: ["since"],
207
+ };
208
+ const CONTROL_INPUTS = {
209
+ pause: "pauseRule",
210
+ resume: "resumeRule",
211
+ run: "runRule",
212
+ replay: "replayRule",
213
+ };
214
+ /** Pause, resume, run a rule now, or replay what its pause skipped: the owner's, kept in the log. */
215
+ async function control(call, encoded, action) {
216
+ const holder = requireKey(call, "owner");
217
+ let name;
218
+ try {
219
+ name = decodeURIComponent(encoded);
220
+ }
221
+ catch {
222
+ throw new InputError("名字不正确");
223
+ }
224
+ const text = await readText(call.request);
225
+ let given = {};
226
+ try {
227
+ if (text.trim())
228
+ given = JSON.parse(text);
229
+ }
230
+ catch {
231
+ throw new InputError("不是 JSON");
232
+ }
233
+ if (!given || typeof given !== "object" || Array.isArray(given))
234
+ throw new InputError("要是一个 JSON 对象");
235
+ const unknown = Object.keys(given).filter((field) => !CONTROL_FIELDS[action].includes(field));
236
+ if (unknown.length)
237
+ throw new InputError(`不认识的字段:${unknown.join("、")}`);
238
+ const type = CONTROL_INPUTS[action];
239
+ if (action === "replay") {
240
+ const { since } = given;
241
+ const from = typeof since === "string" && /(Z|[+-]\d\d:\d\d)$/.test(since) ? Date.parse(since) : NaN;
242
+ if (!Number.isFinite(from))
243
+ throw new InputError("since 要是带时区的 ISO 时间:补跑从这个时间起暂停时跳过的事件");
244
+ // Picked out here and checked again as they're taken, so what another replay took in between isn't taken twice.
245
+ const events = call.services.skipped(name, iso(from), true).events.map((event) => event.id);
246
+ return json(act(call, type, name, events));
247
+ }
248
+ const done = action === "resume" ? act(call, type, name) : act(call, type, name, holder, given);
249
+ if (!done.paused)
250
+ return json(done);
251
+ // A schedule lets its moments pass and keeps no events. Read once a resume has lifted the pause, the list is whole:
252
+ // nothing can join it any more.
253
+ const rule = ruleOf(call.rules, name);
254
+ const skipped = rule && !eventRule(rule) ? null : call.services.skipped(name, done.paused.since);
255
+ return json({ ...done, paused: { ...done.paused, skipped } });
256
+ }
257
+ function state(call) {
258
+ requireKey(call, "owner");
259
+ const before = call.url.searchParams.get("before");
260
+ if (before !== null && !POSITIVE_ID.test(before))
261
+ throw new InputError("编号不正确");
262
+ return json(call.services.state(call.now, before === null ? undefined : Number(before)));
263
+ }
264
+ function stream(call) {
265
+ const { request, services, token } = call;
266
+ requireKey(call, "owner");
267
+ const after = call.url.searchParams.get("after") ?? request.headers.get("last-event-id") ?? "0";
268
+ if (!/^\d+$/.test(after) || !Number.isSafeInteger(Number(after)))
269
+ throw new InputError("日志序号不正确");
270
+ const headers = { "content-type": "text/event-stream", ...NO_STORE, "x-accel-buffering": "no" };
271
+ return new Response(services.stream(Number(after), request.signal, token), { headers });
272
+ }
273
+ async function route(call) {
274
+ const { request, services, token } = call;
275
+ const { method } = request;
276
+ const path = call.url.pathname;
277
+ if (method === "GET" && path === "/healthz")
278
+ return json({ ok: true, commit: services.commit });
279
+ // A key's name is whatever `key new` was given; it only has to stay one path segment when encoded.
280
+ const key = /^\/v1\/keys\/(source|worker|channel|owner)\/([^/]+)$/.exec(path);
281
+ if (method === "DELETE" && key) {
282
+ requireKey(call, "owner");
283
+ let name;
284
+ try {
285
+ name = decodeURIComponent(key[2]);
286
+ }
287
+ catch {
288
+ throw new InputError("密钥名字不正确");
289
+ }
290
+ return json({ ok: true, changed: act(call, "removeKey", key[1], name) });
291
+ }
292
+ const link = CARD_LINK.exec(path);
293
+ if (link && ["GET", "POST"].includes(method))
294
+ return cardAtLink(call, link[1]);
295
+ const hook = /^\/v1\/in\/([a-z][a-z0-9-]*)$/.exec(path);
296
+ if (method === "POST" && hook)
297
+ return webhook(call, hook[1]);
298
+ if (method === "POST" && path === "/v1/events") {
299
+ return json(act(call, "ingest", requireKey(call, "source"), await readJson(request)));
300
+ }
301
+ const sent = /^\/v1\/events\/([1-9][0-9]*)$/.exec(path);
302
+ if (method === "GET" && sent) {
303
+ // Another source's event is as missing as one never sent: a source can't learn which numbers are taken.
304
+ const found = eventOutcome(call.view, requireKey(call, "source"), Number(sent[1]));
305
+ if (!found)
306
+ throw new NotFound("没有这条事件");
307
+ return json(found);
308
+ }
309
+ if (method === "POST" && path === "/v1/tell")
310
+ return tell(call);
311
+ if (method === "GET" && path === "/v1/work")
312
+ return work(call);
313
+ const [, runPart, action] = /^\/v1\/runs\/([1-9][0-9]*)\/(started|result|cancel|why)$/.exec(path) ?? [];
314
+ const runId = Number(runPart);
315
+ if (method === "GET" && action === "why") {
316
+ requireKey(call, "owner");
317
+ return json(services.why(runId));
318
+ }
319
+ if (method === "POST" && action === "cancel")
320
+ return ownerAct(call, "cancel", runId);
321
+ if (method === "POST" && action === "started") {
322
+ act(call, "started", runId, token, await readJson(request));
323
+ return json({ ok: true });
324
+ }
325
+ if (method === "POST" && action === "result")
326
+ return json(act(call, "finish", runId, token, await readJson(request)));
327
+ if (method === "GET" && path === "/v1/cards/next")
328
+ return nextCard(call);
329
+ const card = /^\/v1\/cards\/([1-9][0-9]*)\/(delivered|failed|answer|resolve)$/.exec(path);
330
+ if (method === "POST" && card)
331
+ return cardAction(call, Number(card[1]), card[2]);
332
+ const ruleControl = /^\/v1\/rules\/([^/]+)\/(pause|resume|run|replay)$/.exec(path);
333
+ if (method === "POST" && ruleControl)
334
+ return control(call, ruleControl[1], ruleControl[2]);
335
+ if (method === "GET" && path === "/v1/state")
336
+ return state(call);
337
+ if (method === "GET" && path === "/v1/stream")
338
+ return stream(call);
339
+ return json({ error: "没有这个地址" }, 404);
340
+ }
341
+ export function createHandler(services) {
342
+ return async function handle(request) {
343
+ const call = callFrom(services, request);
344
+ try {
345
+ return await route(call);
346
+ }
347
+ catch (error) {
348
+ const status = statusOf(error);
349
+ if (status === 500)
350
+ throw error;
351
+ const message = error instanceof TooLarge ? "请求最多 1024 KB" : error.message;
352
+ if (CARD_LINK.test(call.url.pathname))
353
+ return new Response(wordsPage(message), { status, headers: PAGE_HEADERS });
354
+ return json({ error: message }, status);
355
+ }
356
+ };
357
+ }
@@ -0,0 +1,202 @@
1
+ // Reading the view: what the decisions and the doors ask of it, and the shapes they hand out.
2
+ import { credential } from "./credentials.js";
3
+ import { rows } from "./evolve.js";
4
+ import { ruleOf } from "./rules.js";
5
+ export function configuration(view, version) {
6
+ const current = view.get("config", "rules");
7
+ return (version === undefined || version === current?.version ? current : view.get("config", version))?.value;
8
+ }
9
+ /** The owner's pause that keeps a rule from taking work at this moment, if there is one. */
10
+ export function pauseOf(view, rule, now) {
11
+ const row = view.get("pauses", rule.name);
12
+ return row && (row.until === null || Date.parse(row.until) > now) ? row : null;
13
+ }
14
+ export const workerOf = (view, run) => configuration(view, run.rules_version).agents[run.agent]?.worker;
15
+ export function agentsOf(view, worker) {
16
+ const agents = Object.entries(configuration(view).agents);
17
+ return agents.filter(([, agent]) => agent.worker === worker).map(([id]) => id);
18
+ }
19
+ export const workers = (view) => new Set([
20
+ ...Object.values(configuration(view)?.agents ?? {}).map((agent) => agent.worker),
21
+ ...rows(view, "runs", { state: "claimed" }).map((run) => workerOf(view, run)),
22
+ ]);
23
+ /** What a worker's agents have on: runs in hand and runs ready to be claimed. */
24
+ export function waitingOn(view, worker, now) {
25
+ return rows(view, "runs", { state: ["queued", "claimed"] }).filter((run) => workerOf(view, run) === worker && (run.state === "claimed" || Date.parse(run.not_before) <= now));
26
+ }
27
+ export function eventsOf(view, runId) {
28
+ const links = rows(view, "run_events", { run_id: runId });
29
+ return links.map((link) => view.get("events", link.event_id)).sort((a, b) => a.id - b.id);
30
+ }
31
+ /** The ids of the events a round worked on, with a wake-up it was called by followed back to what that was about. */
32
+ export function askedAbout(view, runId, seen = new Set()) {
33
+ if (runId === null || seen.has(runId))
34
+ return [];
35
+ seen.add(runId);
36
+ const ids = eventsOf(view, runId).flatMap((event) => {
37
+ const cards = rows(view, "cards", { answer_event: event.id });
38
+ if (cards.length === 0) {
39
+ // A check that came due: its row names no run, so what it was set for was written on it when it was set; the row
40
+ // itself is gone once this round ends. A check set before that was written down keeps its own event.
41
+ const [fired] = rows(view, "timers", { event_id: event.id }).filter((timer) => timer.events);
42
+ return fired ? JSON.parse(fired.events) : [event.key];
43
+ }
44
+ return cards.flatMap((card) => (card.run_id === null ? [event.key] : askedAbout(view, card.run_id, seen)));
45
+ });
46
+ return [...new Set(ids)];
47
+ }
48
+ export function sourceOf(view, runId) {
49
+ const sources = [...new Set(eventsOf(view, runId).map((event) => event.source))];
50
+ return sources.length === 1 ? sources[0] : null;
51
+ }
52
+ /** The rules an event went to, and the ones that would have taken it but were paused. */
53
+ export function routingOf(event) {
54
+ const paused = JSON.parse(event.paused ?? "[]");
55
+ return { routed: JSON.parse(event.routed).filter((name) => !paused.includes(name)), paused };
56
+ }
57
+ /**
58
+ * What became of an event, for the source that sent it: every run it is in now, as retries can merge runs. A run's summary
59
+ * and the events its receipt sent are what the Agent made of all its events, so only a run of this source's alone has them.
60
+ */
61
+ export function eventOutcome(view, source, id) {
62
+ const event = view.get("events", id);
63
+ if (event?.source !== source || !event.sent)
64
+ return null;
65
+ const runs = rows(view, "run_events", { event_id: id })
66
+ .map((link) => view.get("runs", link.run_id))
67
+ .sort((a, b) => a.id - b.id);
68
+ return {
69
+ event: event.id,
70
+ ...routingOf(event),
71
+ runs: runs.map((run) => {
72
+ const own = sourceOf(view, run.id) === source;
73
+ const sent = JSON.parse(run.emitted ?? "[]").map((id) => view.get("events", id));
74
+ return {
75
+ run: run.id,
76
+ rule: run.rule,
77
+ state: run.state,
78
+ attempts: run.attempts,
79
+ error: run.error,
80
+ finishedAt: run.finished_at,
81
+ summary: own ? run.summary : null,
82
+ events: own
83
+ ? sent.map(({ key: id, type, subject, summary, detail, link }) => ({
84
+ id,
85
+ type,
86
+ subject,
87
+ summary,
88
+ detail,
89
+ link,
90
+ }))
91
+ : null,
92
+ };
93
+ }),
94
+ };
95
+ }
96
+ /** The cards a run may close: open before it was claimed, from the same source and group. */
97
+ export function openInScope(view, run) {
98
+ const source = sourceOf(view, run.id);
99
+ if (!source || !run.claimed_at)
100
+ return [];
101
+ return rows(view, "cards", { state: "open", grp: run.grp, source }).filter((card) => card.created_at <= run.claimed_at);
102
+ }
103
+ export function cardView(card, env, ref = null, links = false) {
104
+ const { id, version, kind, state, title, text, recommend, choice, answer, by, result } = card;
105
+ const options = kind === "ask" ? JSON.parse(card.options) : state === "open" ? ["已处理"] : [];
106
+ const link = links ? `${env.publicUrl.replace(/\/$/, "")}/c/${credential(env, "card", id, card.created_at)}` : null;
107
+ const when = { createdAt: card.created_at, decidedAt: card.decided_at, closedAt: card.closed_at };
108
+ return {
109
+ id,
110
+ version,
111
+ ref,
112
+ kind,
113
+ state,
114
+ title,
115
+ text,
116
+ options,
117
+ recommend,
118
+ choice,
119
+ answer,
120
+ by,
121
+ result,
122
+ link,
123
+ rule: card.rule,
124
+ ...when,
125
+ };
126
+ }
127
+ export function jobOf(view, run, env) {
128
+ const rules = configuration(view, run.rules_version);
129
+ const { name, cwd, skill, prompt, title, emits } = ruleOf(rules, run.rule);
130
+ const { maxActive: _maxActive, ...agent } = rules.agents[run.agent];
131
+ const events = eventsOf(view, run.id);
132
+ const eventIds = events.map((event) => event.id);
133
+ const thread = { rule: run.rule, lane: run.lane };
134
+ const answers = rows(view, "cards", { ...thread, answer_event: eventIds });
135
+ const timers = rows(view, "timers", { ...thread, event_id: eventIds });
136
+ const waiting = rows(view, "timers", { ...thread, event_id: null });
137
+ const decided = ["decided", "done"]
138
+ .flatMap((state) => rows(view, "cards", { ...thread, state }, 20, true))
139
+ .sort((a, b) => b.id - a.id)
140
+ .slice(0, 20);
141
+ const timerView = (timer) => ({
142
+ key: timer.key,
143
+ about: timer.about,
144
+ at: timer.at,
145
+ // Recorded when the check was set: the row names no run to follow back from, and it goes once the round it wakes ends.
146
+ events: JSON.parse(timer.events ?? "[]"),
147
+ });
148
+ return {
149
+ run: run.id,
150
+ token: credential(env, "run", run.id, run.issued),
151
+ attempt: run.attempts + 1,
152
+ rule: { name, cwd, skill, prompt, title, emits },
153
+ agent: { ...agent, id: run.agent },
154
+ session: run.session ?? run.resume,
155
+ askFirst: rules.askFirst,
156
+ context: {
157
+ events: events.map(({ key: id, source, type, subject, summary, detail, link, received_at: receivedAt, hops }) => {
158
+ const sourceName = rules.sources[source]?.name ?? source;
159
+ return { id, source, sourceName, type, subject, summary, detail, link, receivedAt, hops: hops ?? 0 };
160
+ }),
161
+ answers: answers.map(({ id: card, title, options, choice, answer: text, about, by, decided_at: at, run_id: asked }) => {
162
+ const picked = JSON.parse(options);
163
+ return {
164
+ card,
165
+ title,
166
+ options: picked,
167
+ choice,
168
+ chosen: choice === null ? text : picked[choice],
169
+ text,
170
+ about,
171
+ by,
172
+ at,
173
+ // The round that asked is the only way back to what the question was about: this round's own events are the
174
+ // answer alone, so without these a source cannot tie what the answer led to back to the id it sent (#320).
175
+ events: askedAbout(view, asked),
176
+ };
177
+ }),
178
+ timers: timers.map(timerView),
179
+ waiting: waiting.sort((a, b) => a.at.localeCompare(b.at)).map(timerView),
180
+ open: openInScope(view, run).map(({ id, title, text, created_at }) => ({
181
+ card: id,
182
+ title,
183
+ text,
184
+ at: created_at,
185
+ })),
186
+ decided: decided
187
+ .filter((card) => !answers.some((answer) => answer.id === card.id))
188
+ .map(({ id, title, choice, answer, options, decided_at }) => {
189
+ return { card: id, title, choice: choice === null ? answer : JSON.parse(options)[choice], at: decided_at };
190
+ }),
191
+ },
192
+ };
193
+ }
194
+ export function cancels(view, worker) {
195
+ return rows(view, "runs", { state: "claimed" })
196
+ .filter((run) => run.cancel_at !== null && workerOf(view, run) === worker)
197
+ .map((run) => run.id);
198
+ }
199
+ export function unrouted(view, limit = 20) {
200
+ return rows(view, "events", { routed: "[]" }, limit, true);
201
+ }
202
+ export const safeFact = (fact) => ({ ...fact, changes: fact.changes.filter(({ table }) => table !== "keys") });
@@ -0,0 +1,20 @@
1
+ /** The source of what the clock makes happen. */
2
+ export const SCHEDULE = "schedule";
3
+ function typeMatch(pattern, type) {
4
+ return pattern === "*" || pattern === type || (pattern.endsWith(".*") && type.startsWith(pattern.slice(0, -1)));
5
+ }
6
+ export const typeMatches = (patterns, type) => patterns.some((pattern) => typeMatch(pattern, type));
7
+ export const eventRule = (rule) => "source" in rule.when;
8
+ export const cronOf = (rule) => rule.when.cron;
9
+ /** The rule a run, card or timer names: a rule's own, or a task elsewhere's, which only your answers to it start. */
10
+ export function ruleOf(rules, name) {
11
+ const rule = rules.rules.find((rule) => rule.name === name);
12
+ if (rule)
13
+ return rule;
14
+ const task = rules.elsewhere.find((task) => task.name === name);
15
+ if (!task?.cwd)
16
+ return undefined;
17
+ const { source, to, cwd, skill, prompt } = task;
18
+ // No event type matches none: nothing that comes in starts it.
19
+ return { name, when: { source, types: [] }, to, cwd, skill, prompt, group: name, tell: "needed" };
20
+ }
@@ -0,0 +1,52 @@
1
+ import { Conflict } from "./errors.js";
2
+ import { evolve, initialize, statement, View } from "./evolve.js";
3
+ export function* iterateLog(db, after = 0) {
4
+ for (const row of db.prepare("SELECT fact FROM facts WHERE seq > ? ORDER BY seq").iterate(after))
5
+ yield JSON.parse(String(row.fact));
6
+ }
7
+ function transaction(db, work) {
8
+ if (db.isTransaction)
9
+ return work();
10
+ db.exec("BEGIN IMMEDIATE");
11
+ try {
12
+ const view = work();
13
+ db.exec("COMMIT");
14
+ return view;
15
+ }
16
+ catch (error) {
17
+ db.exec("ROLLBACK");
18
+ throw error;
19
+ }
20
+ }
21
+ export const rebuild = (db, format = "") => {
22
+ initialize(db);
23
+ return transaction(db, () => evolve(new View(db, 0, {}, format), iterateLog(db), db, true));
24
+ };
25
+ export function openView(db, format) {
26
+ initialize(db);
27
+ const saved = statement(db, "SELECT seq,next,format FROM projection_meta WHERE id=1").get();
28
+ if (!saved || saved.format !== format)
29
+ return rebuild(db, format);
30
+ return new View(db, Number(saved.seq), JSON.parse(String(saved.next)), format);
31
+ }
32
+ export function commit(db, view, produce) {
33
+ return transaction(db, () => {
34
+ const latest = Number(statement(db, "SELECT COALESCE(MAX(seq),0) AS seq FROM facts").get().seq);
35
+ if (latest !== view.seq)
36
+ throw new Conflict("日志已变化,请重读后再提交");
37
+ const facts = produce();
38
+ if (!facts.length)
39
+ return view;
40
+ const insert = statement(db, "INSERT INTO facts(seq,fact) VALUES (?,?)");
41
+ for (const fact of facts)
42
+ insert.run(fact.seq, JSON.stringify(fact));
43
+ return evolve(view, facts, db);
44
+ });
45
+ }
46
+ /** Reads the view holding the write lock: commands write to this database too, so one read before it can be stale. */
47
+ export function commitLatest(db, format, produce) {
48
+ return transaction(db, () => {
49
+ const view = openView(db, format);
50
+ return commit(db, view, () => produce(view));
51
+ });
52
+ }
@@ -0,0 +1,32 @@
1
+ import { stablePath } from "../../host/node-path.js";
2
+ import { sibling } from "../../host/program.js";
3
+ import { tail } from "../../worker/agents.js";
4
+ export default {
5
+ command: (turn) => [
6
+ stablePath(process.execPath),
7
+ "--disable-warning=ExperimentalWarning",
8
+ sibling(import.meta.dirname, "bridge.ts"),
9
+ JSON.stringify(turn),
10
+ ],
11
+ read(stdout, code, stderr) {
12
+ let reading = {};
13
+ for (const line of stdout.trim().split("\n")) {
14
+ try {
15
+ reading = { ...reading, ...JSON.parse(line) };
16
+ }
17
+ catch {
18
+ /* A partial final line is read again after the next poll. */
19
+ }
20
+ }
21
+ // Taken back by the bridge when the agent refused the session it was to go on in.
22
+ if (!reading.started)
23
+ delete reading.started;
24
+ if (code !== null && (code !== 0 || !reading.finished || reading.error)) {
25
+ // What the agent itself said, then why it failed. The bridge says that last, unless the agent went on talking.
26
+ const said = tail(stderr);
27
+ const error = said.endsWith(reading.error ?? "") ? said : tail(`${said}\n${reading.error}`);
28
+ return { session: reading.session, started: reading.started, error: error || "ACP 没有完成这一轮" };
29
+ }
30
+ return reading;
31
+ },
32
+ };