@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.
- package/CHANGELOG.md +27 -0
- package/INSTALL.md +120 -0
- package/LICENSE +21 -0
- package/README.en.md +268 -0
- package/README.md +264 -2
- package/SECURITY.md +49 -0
- package/dist/bin/agent-autoloop.js +2 -0
- package/dist/cli/agents.js +14 -0
- package/dist/cli/backup.js +144 -0
- package/dist/cli/dashboard/app.js +424 -0
- package/dist/cli/dashboard/index.html +15 -0
- package/dist/cli/dashboard/style.css +629 -0
- package/dist/cli/dashboard.js +94 -0
- package/dist/cli/explain.js +84 -0
- package/dist/cli/main.js +1142 -0
- package/dist/cli/mcp.js +151 -0
- package/dist/cli/runs.js +40 -0
- package/dist/cli/spend.js +21 -0
- package/dist/cli/status.js +272 -0
- package/dist/cli/try.js +6 -0
- package/dist/cli/ui.js +75 -0
- package/dist/cli/uninstall.js +86 -0
- package/dist/cli/update.js +65 -0
- package/dist/cli/why.js +115 -0
- package/dist/host/background-launcher.js +12 -0
- package/dist/host/background.js +24 -0
- package/dist/host/channels.js +4 -0
- package/dist/host/command.js +98 -0
- package/dist/host/config.js +37 -0
- package/dist/host/files.js +22 -0
- package/dist/host/home.js +5 -0
- package/dist/host/http.js +45 -0
- package/dist/host/launcher.js +188 -0
- package/dist/host/lines.js +15 -0
- package/dist/host/node-path.js +33 -0
- package/dist/host/npm.js +28 -0
- package/dist/host/plugins.js +26 -0
- package/dist/host/program.js +14 -0
- package/dist/host/runtime.js +179 -0
- package/dist/host/server.js +159 -0
- package/dist/host/service.js +325 -0
- package/dist/host/state.js +203 -0
- package/dist/host/up.js +162 -0
- package/dist/host/update.js +286 -0
- package/dist/host/version.js +81 -0
- package/dist/kernel/card-page.js +54 -0
- package/dist/kernel/credentials.js +16 -0
- package/dist/kernel/cron.js +135 -0
- package/dist/kernel/decide.js +826 -0
- package/dist/kernel/due.js +73 -0
- package/dist/kernel/errors.js +9 -0
- package/dist/kernel/evolve.js +264 -0
- package/dist/kernel/http.js +357 -0
- package/dist/kernel/query.js +202 -0
- package/dist/kernel/rules.js +20 -0
- package/dist/kernel/store.js +52 -0
- package/dist/plugins/acp/agent.js +32 -0
- package/dist/plugins/acp/bridge.js +204 -0
- package/dist/plugins/claude/agent.js +113 -0
- package/dist/plugins/codex/agent.js +105 -0
- package/dist/plugins/command/agent.js +25 -0
- package/dist/plugins/delivery/action.js +25 -0
- package/dist/plugins/delivery/agent.js +13 -0
- package/dist/plugins/delivery/delivery.js +388 -0
- package/dist/plugins/delivery/github.js +201 -0
- package/dist/plugins/delivery/handoff.js +50 -0
- package/dist/plugins/delivery/input.js +47 -0
- package/dist/plugins/delivery/poll.js +72 -0
- package/dist/plugins/delivery/project.js +144 -0
- package/dist/plugins/delivery/review-ledger.js +82 -0
- package/dist/plugins/delivery/review-policy.js +99 -0
- package/dist/plugins/delivery/review.js +280 -0
- package/dist/plugins/delivery/run.js +204 -0
- package/dist/plugins/desktop/channel.js +94 -0
- package/dist/plugins/dsh/agent.js +116 -0
- package/dist/plugins/feishu/channel.js +245 -0
- package/dist/plugins/github/source.js +30 -0
- package/dist/plugins/gitlab/source.js +30 -0
- package/dist/plugins/omp/agent.js +3 -0
- package/dist/plugins/opencode/agent.js +88 -0
- package/dist/plugins/pi/agent.js +92 -0
- package/dist/plugins/webhook/channel.js +70 -0
- package/dist/plugins/webhook/templates.js +34 -0
- package/dist/plugins/xiaojiu/channel.js +410 -0
- package/dist/plugins/zcode/agent.js +102 -0
- package/dist/protocol/client.js +56 -0
- package/dist/protocol/conformance.js +184 -0
- package/dist/protocol/job.js +1 -0
- package/dist/protocol/rules.js +230 -0
- package/dist/protocol/schema.js +70 -0
- package/dist/protocol/schema.json +985 -0
- package/dist/protocol/validate.js +150 -0
- package/dist/worker/agents.js +47 -0
- package/dist/worker/contract.js +178 -0
- package/dist/worker/run.js +52 -0
- package/dist/worker/usage.js +45 -0
- package/dist/worker/windows.ps1 +48 -0
- package/dist/worker/worker.js +595 -0
- package/docs/architecture.en.svg +178 -0
- package/docs/architecture.svg +178 -0
- package/docs/auto-update.md +53 -0
- package/docs/plugins.md +139 -0
- package/docs/protocol.md +582 -0
- package/docs/state-machines.md +77 -0
- package/examples/channel.sh +15 -0
- package/examples/plugins/hello-agent/agent.ts +40 -0
- package/examples/plugins/hello-channel/channel.ts +54 -0
- package/examples/plugins/hello-source/source.ts +19 -0
- package/examples/recipes/browser-handoff/README.md +44 -0
- package/examples/recipes/browser-handoff/SKILL.md +22 -0
- package/examples/recipes/browser-handoff/browser.json +10 -0
- package/examples/recipes/browser-handoff/handoff.ts +44 -0
- package/examples/recipes/browser-handoff/rules.json +19 -0
- package/examples/recipes/feedback/README.md +34 -0
- package/examples/recipes/feedback/SKILL.md +22 -0
- package/examples/recipes/feedback/event.json +8 -0
- package/examples/recipes/feedback/rules.json +37 -0
- package/examples/recipes/feishu-brief/README.md +28 -0
- package/examples/recipes/feishu-brief/SKILL.md +16 -0
- package/examples/recipes/feishu-brief/collect.ts +164 -0
- package/examples/recipes/feishu-brief/rules.json +57 -0
- package/examples/recipes/feishu-brief/sources.json +13 -0
- package/examples/recipes/github-issues/README.md +17 -0
- package/examples/recipes/github-issues/SKILL.md +18 -0
- package/examples/recipes/github-issues/rules.json +30 -0
- package/examples/recipes/inbox-triage/README.md +36 -0
- package/examples/recipes/inbox-triage/SKILL.md +19 -0
- package/examples/recipes/inbox-triage/collect.ts +191 -0
- package/examples/recipes/inbox-triage/rules.json +57 -0
- package/examples/recipes/inbox-triage/sources.json +8 -0
- package/examples/recipes/morning-brief/README.md +17 -0
- package/examples/recipes/morning-brief/SKILL.md +17 -0
- package/examples/recipes/morning-brief/rules.json +16 -0
- package/examples/recipes/ops-alerts/README.md +18 -0
- package/examples/recipes/ops-alerts/SKILL.md +34 -0
- package/examples/recipes/ops-alerts/restart.sh +5 -0
- package/examples/recipes/ops-alerts/rules.json +29 -0
- package/examples/recipes/website-watch/README.md +26 -0
- package/examples/recipes/website-watch/SKILL.md +19 -0
- package/examples/recipes/website-watch/check.ts +86 -0
- package/examples/recipes/website-watch/rules.json +56 -0
- package/examples/recipes/website-watch/site.json +6 -0
- package/examples/skills/weekly-sweep/SKILL.md +17 -0
- package/examples/watch-github-issues.sh +23 -0
- package/examples/worker.sh +18 -0
- package/package.json +57 -4
- package/plugins/acp/agent.ts +31 -0
- package/plugins/acp/bridge.ts +190 -0
- package/plugins/claude/agent.ts +121 -0
- package/plugins/codex/agent.ts +103 -0
- package/plugins/command/agent.ts +25 -0
- package/plugins/delivery/action.ts +29 -0
- package/plugins/delivery/action.yml +28 -0
- package/plugins/delivery/agent.ts +15 -0
- package/plugins/delivery/delivery.ts +408 -0
- package/plugins/delivery/github.ts +207 -0
- package/plugins/delivery/handoff.ts +72 -0
- package/plugins/delivery/input.ts +55 -0
- package/plugins/delivery/poll.ts +65 -0
- package/plugins/delivery/project.ts +161 -0
- package/plugins/delivery/review-ledger.ts +90 -0
- package/plugins/delivery/review-policy.ts +126 -0
- package/plugins/delivery/review.ts +324 -0
- package/plugins/delivery/run.ts +219 -0
- package/plugins/desktop/channel.ts +100 -0
- package/plugins/dsh/agent.ts +100 -0
- package/plugins/feishu/channel.ts +243 -0
- package/plugins/github/source.ts +33 -0
- package/plugins/gitlab/source.ts +32 -0
- package/plugins/omp/agent.ts +4 -0
- package/plugins/opencode/agent.ts +78 -0
- package/plugins/pi/agent.ts +80 -0
- package/plugins/webhook/channel.ts +74 -0
- package/plugins/webhook/templates.ts +32 -0
- package/plugins/xiaojiu/channel.ts +426 -0
- package/plugins/zcode/agent.ts +96 -0
- package/skills/agent-autoloop/SKILL.md +260 -0
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
// Everything that can change the hub is decided here: given the view and one input, the facts to record and the answer
|
|
2
|
+
// to give. Time and secrets come in as arguments, so the same input on the same view always decides the same.
|
|
3
|
+
import { credential, digest } from "./credentials.js";
|
|
4
|
+
import { latestBefore, nextRun, parseCron } from "./cron.js";
|
|
5
|
+
import { deadlines, MINUTE, offlineCard, OFFLINE_AFTER, RUN_LEASE, SEEN_EVERY, WORKER_FRESH } from "./due.js";
|
|
6
|
+
import { AuthError, Conflict, InputError, NotFound } from "./errors.js";
|
|
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";
|
|
9
|
+
import { cronOf, eventRule, ruleOf, SCHEDULE, typeMatches } from "./rules.js";
|
|
10
|
+
import { addUsage, ANSWER_BY, ANSWER_REF, ANSWER_TEXT, DELIVERY_REF, parseEvent, parseResult, } from "../protocol/validate.js";
|
|
11
|
+
/** Minutes after the first try that a card is sent to a channel again. */
|
|
12
|
+
const RESEND_AT = [0, 1, 3, 7, 15, 25, 35, 45, 55];
|
|
13
|
+
/** The last resend and the minute it holds the card: after this a channel has given up. */
|
|
14
|
+
const RESEND_WINDOW = 57 * MINUTE;
|
|
15
|
+
/** How long a chain of events causing events can get before it stops being dispatched. */
|
|
16
|
+
const MAX_HOPS = 8;
|
|
17
|
+
/** Failures in a row after which a run stops being retried: each try spends the owner's real tokens. */
|
|
18
|
+
const MAX_ATTEMPTS = 10;
|
|
19
|
+
const NOT_TRYING = { tries: 0, first_try_at: null, not_before: null };
|
|
20
|
+
const NOT_DELIVERED = { version: 0, ref: null, ...NOT_TRYING, error: null, given_up: 0 };
|
|
21
|
+
const nulls = (...names) => Object.fromEntries(names.map((name) => [name, null]));
|
|
22
|
+
const CARD_BASICS = { text: "", options: "[]", recommend: null, about: "", state: "open", fyi: 0, quiet: 0 };
|
|
23
|
+
const DEFAULTS = {
|
|
24
|
+
runs: {
|
|
25
|
+
attempts: 0,
|
|
26
|
+
...nulls("claim", "issued", "last_issued", "last_result", "last_answer", "cancel_at", "resume", "session", "link"),
|
|
27
|
+
...nulls("claimed_at", "seen_at", "finished_at", "summary", "error", "usage"),
|
|
28
|
+
},
|
|
29
|
+
cards: {
|
|
30
|
+
...CARD_BASICS,
|
|
31
|
+
...nulls("choice", "answer", "by", "result", "rule"),
|
|
32
|
+
lane: "",
|
|
33
|
+
...nulls("grp", "source", "agent", "session", "run_id", "answer_event"),
|
|
34
|
+
version: 1,
|
|
35
|
+
...nulls("decided_at", "closed_at"),
|
|
36
|
+
},
|
|
37
|
+
deliveries: NOT_DELIVERED,
|
|
38
|
+
};
|
|
39
|
+
export function decide(view, input, now, env) {
|
|
40
|
+
const { type, args } = input;
|
|
41
|
+
if (!Object.hasOwn(HANDLERS, type))
|
|
42
|
+
throw new InputError(`不认识的输入:${type}`);
|
|
43
|
+
const rules = configuration(view);
|
|
44
|
+
const draft = { view: view.fork(), seq: view.seq + 1, type, now, at: iso(now), env, rules, changes: [] };
|
|
45
|
+
const value = HANDLERS[type](draft, ...args);
|
|
46
|
+
// With nothing changed nothing new can come due, and what only the clock changes has a deadline of its own to bring a tick.
|
|
47
|
+
if (!draft.changes.length && type !== "tick")
|
|
48
|
+
return { facts: [], value };
|
|
49
|
+
const due = deadlines(draft.view, now);
|
|
50
|
+
for (const [key, row] of Object.entries(due)) {
|
|
51
|
+
if (JSON.stringify(draft.view.get("due", key)) !== JSON.stringify(row))
|
|
52
|
+
put(draft, "due", key, row);
|
|
53
|
+
}
|
|
54
|
+
for (const { kind, key: name } of rows(draft.view, "due")) {
|
|
55
|
+
const key = `${kind}:${name}`;
|
|
56
|
+
if (!due[key])
|
|
57
|
+
set(draft, "due", key, null);
|
|
58
|
+
}
|
|
59
|
+
return { facts: draft.changes.length ? [factOf(draft, draft.changes)] : [], value };
|
|
60
|
+
}
|
|
61
|
+
function factOf({ seq, now, type }, changes) {
|
|
62
|
+
return { version: 1, seq, at: now, type, changes };
|
|
63
|
+
}
|
|
64
|
+
function set(draft, table, key, row) {
|
|
65
|
+
const change = { table, key: String(key), row };
|
|
66
|
+
draft.changes.push(change);
|
|
67
|
+
draft.view.set(table, String(key), row);
|
|
68
|
+
return row;
|
|
69
|
+
}
|
|
70
|
+
const put = (draft, table, key, fields) => set(draft, table, key, { ...DEFAULTS[table], ...draft.view.get(table, key), ...fields });
|
|
71
|
+
function add(draft, table, fields) {
|
|
72
|
+
const id = (draft.view.next[table] ?? 0) + 1;
|
|
73
|
+
return put(draft, table, id, { ...fields, id });
|
|
74
|
+
}
|
|
75
|
+
const ruleNamed = (draft, name) => ruleOf(draft.rules, name);
|
|
76
|
+
function assignQueued(draft, run) {
|
|
77
|
+
const config = draft.view.get("config", "rules");
|
|
78
|
+
const rule = ruleOf(config.value, run.rule);
|
|
79
|
+
if (!rule)
|
|
80
|
+
return;
|
|
81
|
+
const session = rule.to === run.agent ? {} : nulls("session", "resume");
|
|
82
|
+
put(draft, "runs", run.id, { agent: rule.to, rules_version: config.version, ...session });
|
|
83
|
+
}
|
|
84
|
+
const threadOf = (run) => ({ rule: run.rule, lane: run.lane, grp: run.grp });
|
|
85
|
+
/** 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
|
|
86
|
+
* stopped: what stopped it, or the owner's reason, would meet this one too. Rounds on a thread can share a session, so another
|
|
87
|
+
* still going, or one the hub lost track of, may be running in it: a second process mustn't open it, and a new one starts. */
|
|
88
|
+
function settleSession(draft, run) {
|
|
89
|
+
const rule = ruleNamed(draft, run.rule);
|
|
90
|
+
const thread = { rule: run.rule, lane: run.lane };
|
|
91
|
+
const carried = run.session ?? run.resume;
|
|
92
|
+
let session = carried;
|
|
93
|
+
if (!session && rule?.resume) {
|
|
94
|
+
const [last] = rows(draft.view, "runs", { ...thread, state: ["done", "nothing", "cancelled"] }, 1, true);
|
|
95
|
+
if (last?.state !== "cancelled" && last?.agent === rule.to)
|
|
96
|
+
session = last.session;
|
|
97
|
+
}
|
|
98
|
+
if (!session)
|
|
99
|
+
return;
|
|
100
|
+
const going = rows(draft.view, "runs", { ...thread, state: ["claimed", "unknown"] });
|
|
101
|
+
if (going.some((other) => (other.session ?? other.resume) === session)) {
|
|
102
|
+
put(draft, "runs", run.id, nulls("session", "resume"));
|
|
103
|
+
}
|
|
104
|
+
else if (session !== carried)
|
|
105
|
+
put(draft, "runs", run.id, { resume: session });
|
|
106
|
+
}
|
|
107
|
+
const hopsOf = (draft, run) => Math.max(0, ...eventsOf(draft.view, run.id).map((event) => event.hops ?? 0));
|
|
108
|
+
function closeCard(draft, card, result, by = null, note = null) {
|
|
109
|
+
const closed = { state: "closed", closed_at: draft.at, version: card.version + 1 };
|
|
110
|
+
// A note says how a notice was handled, for looking back at later.
|
|
111
|
+
put(draft, "cards", card.id, { ...closed, result, by: by ?? card.by, ...(note ? { answer: note } : {}) });
|
|
112
|
+
}
|
|
113
|
+
function closeOpen(draft, matches, result) {
|
|
114
|
+
const open = rows(draft.view, "cards", { state: "open" }).filter((card) => matches(card.key));
|
|
115
|
+
for (const card of open)
|
|
116
|
+
closeCard(draft, card, result);
|
|
117
|
+
}
|
|
118
|
+
/** Once it's stopped, nothing should still say it will try again, or that it may still be going. */
|
|
119
|
+
const closeStopped = (draft, run, result) => closeOpen(draft, (key) => key === `run:${run}:failing` || key === `run:${run}:unknown`, result);
|
|
120
|
+
const closeOffline = (draft, worker) => closeOpen(draft, (key) => key.startsWith(`worker:${worker}:offline:`), "连上了");
|
|
121
|
+
/** 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
|
+
function justSeen({ now }, row) {
|
|
123
|
+
const age = now - Date.parse(row?.seen_at);
|
|
124
|
+
return age >= 0 && age < SEEN_EVERY;
|
|
125
|
+
}
|
|
126
|
+
function createCard(draft, spec) {
|
|
127
|
+
const [existing] = rows(draft.view, "cards", { key: spec.key, ...(!spec.once && { state: "open" }) }, 1, true);
|
|
128
|
+
if (existing)
|
|
129
|
+
return { card: existing.id, duplicate: true };
|
|
130
|
+
const { once, run, options, fyi, quiet, ...fields } = spec;
|
|
131
|
+
const stored = {
|
|
132
|
+
run_id: run ?? null,
|
|
133
|
+
options: JSON.stringify(options ?? []),
|
|
134
|
+
fyi: fyi ? 1 : 0,
|
|
135
|
+
quiet: quiet ? 1 : 0,
|
|
136
|
+
};
|
|
137
|
+
const state = fyi ? { state: "closed", closed_at: draft.at } : { state: "open" };
|
|
138
|
+
const card = add(draft, "cards", { ...fields, ...stored, ...state, created_at: draft.at });
|
|
139
|
+
return { card: card.id, duplicate: false };
|
|
140
|
+
}
|
|
141
|
+
const notify = (draft, key, title, text, extra = {}) => createCard(draft, { key, kind: "notice", title, text, ...extra });
|
|
142
|
+
/** A queued run of this rule and thread takes the event, so what comes in while it waits is handled together. */
|
|
143
|
+
function enqueue(draft, rule, event, lane, resume) {
|
|
144
|
+
const rulesVersion = draft.view.get("config", "rules").version;
|
|
145
|
+
const stamps = { not_before: draft.at, created_at: draft.at, rules_version: rulesVersion };
|
|
146
|
+
const run = rows(draft.view, "runs", { rule: rule.name, lane, state: "queued" })[0] ??
|
|
147
|
+
add(draft, "runs", { rule: rule.name, agent: rule.to, grp: rule.group, lane, state: "queued", ...stamps });
|
|
148
|
+
put(draft, "run_events", `${run.id}:${event}`, { run_id: run.id, event_id: event });
|
|
149
|
+
if (resume)
|
|
150
|
+
put(draft, "runs", run.id, { resume });
|
|
151
|
+
return run.id;
|
|
152
|
+
}
|
|
153
|
+
/** Keeps an event under a key of its own: one the hub makes up mustn't collide with one a source sent. */
|
|
154
|
+
function recordEvent(draft, source, event, routed, paused = [], sent = false) {
|
|
155
|
+
let key = event.id;
|
|
156
|
+
for (let suffix = 1; rows(draft.view, "events", { source, key }).length; suffix++) {
|
|
157
|
+
key = `${event.id}:${suffix}`;
|
|
158
|
+
}
|
|
159
|
+
return add(draft, "events", {
|
|
160
|
+
source,
|
|
161
|
+
key,
|
|
162
|
+
type: event.type,
|
|
163
|
+
subject: event.subject ?? "",
|
|
164
|
+
summary: event.summary ?? "",
|
|
165
|
+
detail: event.detail ?? "",
|
|
166
|
+
link: event.link ?? "",
|
|
167
|
+
hops: event.hops ?? 0,
|
|
168
|
+
routed: JSON.stringify(routed),
|
|
169
|
+
// Only where a pause held it back, so the owner's list of what was skipped reads an index of those alone.
|
|
170
|
+
...(paused.length && { paused: JSON.stringify(paused) }),
|
|
171
|
+
// Through the source's own door: only these are its to read back (`eventOutcome`), not what the hub made in its name.
|
|
172
|
+
...(sent && { sent: 1 }),
|
|
173
|
+
received_at: draft.at,
|
|
174
|
+
}).id;
|
|
175
|
+
}
|
|
176
|
+
function ingest(draft, source, given, sent = false) {
|
|
177
|
+
const event = parseEvent(given);
|
|
178
|
+
const existing = rows(draft.view, "events", { source, key: event.id })[0];
|
|
179
|
+
if (existing) {
|
|
180
|
+
return { event: existing.id, duplicate: true, ...routingOf(existing) };
|
|
181
|
+
}
|
|
182
|
+
const tooDeep = event.hops > MAX_HOPS;
|
|
183
|
+
const takes = (rule) => eventRule(rule) && rule.when.source === source && typeMatches(rule.when.types, event.type);
|
|
184
|
+
const matched = tooDeep ? [] : draft.rules.rules.filter(takes);
|
|
185
|
+
// A paused rule doesn't take the event, and nothing is kept back for it: the event is recorded as skipped for it.
|
|
186
|
+
const isPaused = (rule) => !!pauseOf(draft.view, rule, draft.now);
|
|
187
|
+
const paused = matched.filter(isPaused).map((rule) => rule.name);
|
|
188
|
+
const taking = matched.filter((rule) => !isPaused(rule));
|
|
189
|
+
const id = recordEvent(draft, source, event, matched.map((rule) => rule.name), paused, sent);
|
|
190
|
+
if (tooDeep) {
|
|
191
|
+
const words = `同一条处理链已超过 ${MAX_HOPS} 层,后续事件已记录,没有继续派发。`;
|
|
192
|
+
notify(draft, `hops:${source}:${event.id}`, "事件循环已停止", words, { once: true });
|
|
193
|
+
}
|
|
194
|
+
for (const rule of taking)
|
|
195
|
+
enqueue(draft, rule, id, rule.parallel ? event.subject : "");
|
|
196
|
+
return { event: id, duplicate: false, routed: taking.map((rule) => rule.name), paused };
|
|
197
|
+
}
|
|
198
|
+
function heldRun(draft, id, token, states) {
|
|
199
|
+
const run = draft.view.get("runs", id);
|
|
200
|
+
const issued = run && states.includes(run.state) && run.issued !== null;
|
|
201
|
+
if (!issued || credential(draft.env, "run", id, run.issued) !== token)
|
|
202
|
+
throw new AuthError("这件活不归这个令牌");
|
|
203
|
+
return run;
|
|
204
|
+
}
|
|
205
|
+
function cardFromReceipt(draft, run, kind, card) {
|
|
206
|
+
const name = card.key ?? digest(`${card.title}\n${card.text}`).slice(0, 32);
|
|
207
|
+
const session = draft.view.get("runs", run.id).session;
|
|
208
|
+
const fyi = kind === "notice" && card.fyi === true;
|
|
209
|
+
const quiet = kind === "notice" && ruleNamed(draft, run.rule)?.tell === "never";
|
|
210
|
+
const origin = { source: sourceOf(draft.view, run.id), agent: run.agent, session, run: run.id };
|
|
211
|
+
const key = `thread:${run.rule}:${run.lane}:${name}`;
|
|
212
|
+
// Closed as it's made, nothing open stops it coming again: a run trying again says it once.
|
|
213
|
+
if (fyi && rows(draft.view, "cards", { key, run_id: run.id }, 1).length)
|
|
214
|
+
return;
|
|
215
|
+
createCard(draft, { ...card, hops: hopsOf(draft, run), key, kind, fyi, quiet, ...threadOf(run), ...origin });
|
|
216
|
+
}
|
|
217
|
+
/** Notices what has gone quiet: a worker that stopped coming, a run its worker stopped mentioning. */
|
|
218
|
+
function sweep(draft) {
|
|
219
|
+
const { now } = draft;
|
|
220
|
+
for (const worker of workers(draft.view)) {
|
|
221
|
+
const seen = draft.view.get("seen", `worker:${worker}`);
|
|
222
|
+
const lastSeen = seen ? Date.parse(seen.seen_at) : undefined;
|
|
223
|
+
if (lastSeen !== undefined && now - lastSeen <= WORKER_FRESH) {
|
|
224
|
+
closeOffline(draft, worker);
|
|
225
|
+
const inDoubt = (run) => workerOf(draft.view, run) === worker && Date.parse(run.seen_at) < now - RUN_LEASE;
|
|
226
|
+
for (const run of rows(draft.view, "runs", { state: "claimed" }).filter(inDoubt)) {
|
|
227
|
+
put(draft, "runs", run.id, { state: "unknown" });
|
|
228
|
+
const agent = configuration(draft.view, run.rules_version).agents[run.agent].name;
|
|
229
|
+
const words = `交给 ${agent} 后超过 5 分钟没有回音,不确定做没做完;后续新任务照常处理。`;
|
|
230
|
+
notify(draft, `run:${run.id}:unknown`, run.rule, words, threadOf(run));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const waiting = waitingOn(draft.view, worker, now);
|
|
234
|
+
if (!waiting.length)
|
|
235
|
+
continue;
|
|
236
|
+
const since = now - (lastSeen ?? Date.parse(waiting[0].created_at));
|
|
237
|
+
const { key, told } = offlineCard(draft.view, worker, waiting);
|
|
238
|
+
if (since <= OFFLINE_AFTER || told)
|
|
239
|
+
continue;
|
|
240
|
+
const minutes = Math.floor(since / MINUTE);
|
|
241
|
+
const neverSeen = lastSeen === undefined;
|
|
242
|
+
const situation = neverSeen
|
|
243
|
+
? `${worker} 一直没连上中台,有 ${waiting.length} 件任务等了 ${minutes} 分钟没人接`
|
|
244
|
+
: `${worker} 已经 ${minutes} 分钟没连上中台,有 ${waiting.length} 件任务在排队或在跑`;
|
|
245
|
+
const check = neverSeen ? "有没有开机联网" : "是不是关机、休眠或断网了";
|
|
246
|
+
notify(draft, key, "接单程序没连上", `${situation}(请看一眼那台电脑${check})。`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function claimNext(draft, worker, claim) {
|
|
250
|
+
const agents = agentsOf(draft.view, worker);
|
|
251
|
+
const runs = rows(draft.view, "runs", { state: ["queued", "claimed"] });
|
|
252
|
+
const claimed = runs.filter((run) => run.state === "claimed");
|
|
253
|
+
const groupLimit = (group) => draft.rules.rules.find((rule) => rule.group === group)?.parallel ?? 1;
|
|
254
|
+
const claimable = (run) => {
|
|
255
|
+
if (run.state !== "queued")
|
|
256
|
+
return false;
|
|
257
|
+
const rule = ruleNamed(draft, run.rule);
|
|
258
|
+
// What was queued before a pause, or an answer that came in during one, waits for the resume.
|
|
259
|
+
if (!rule || !agents.includes(rule.to) || pauseOf(draft.view, rule, draft.now))
|
|
260
|
+
return false;
|
|
261
|
+
const agentLimit = draft.rules.agents[rule.to].maxActive;
|
|
262
|
+
return (Date.parse(run.not_before) <= draft.now &&
|
|
263
|
+
!claimed.some((other) => other.grp === run.grp && other.lane === run.lane) &&
|
|
264
|
+
claimed.filter((other) => other.grp === run.grp).length < groupLimit(run.grp) &&
|
|
265
|
+
(rule.maxActive === undefined || claimed.filter((other) => other.rule === run.rule).length < rule.maxActive) &&
|
|
266
|
+
(agentLimit === undefined || claimed.filter((other) => other.agent === rule.to).length < agentLimit));
|
|
267
|
+
};
|
|
268
|
+
// The same claim again means the answer got lost: it gets back the run it already has.
|
|
269
|
+
const held = claimed.find((run) => run.claim === claim && workerOf(draft.view, run) === worker);
|
|
270
|
+
const run = held ?? runs.find(claimable);
|
|
271
|
+
if (!run)
|
|
272
|
+
return null;
|
|
273
|
+
if (!held) {
|
|
274
|
+
assignQueued(draft, run);
|
|
275
|
+
settleSession(draft, draft.view.get("runs", run.id));
|
|
276
|
+
}
|
|
277
|
+
const since = held ? { claimed_at: run.claimed_at, link: run.link } : { claimed_at: draft.at, link: null };
|
|
278
|
+
const rules_version = held ? run.rules_version : draft.view.get("config", "rules").version;
|
|
279
|
+
const claiming = { state: "claimed", claim, issued: draft.seq, seen_at: draft.at, rules_version, ...since };
|
|
280
|
+
put(draft, "runs", run.id, { ...claiming, ...nulls("last_issued", "last_result", "last_answer") });
|
|
281
|
+
return jobOf(draft.view, draft.view.get("runs", run.id), draft.env);
|
|
282
|
+
}
|
|
283
|
+
function clearFiredTimers(draft, run) {
|
|
284
|
+
// A fired timer supplies context to its queued/retrying run; keep it until no future claim can need that context.
|
|
285
|
+
// The facts log retains the full timer row and its event link after this projection entry is removed.
|
|
286
|
+
const eventIds = eventsOf(draft.view, run.id).map((event) => event.id);
|
|
287
|
+
if (!eventIds.length)
|
|
288
|
+
return;
|
|
289
|
+
for (const timer of rows(draft.view, "timers", { event_id: eventIds }))
|
|
290
|
+
set(draft, "timers", timer.id, null);
|
|
291
|
+
}
|
|
292
|
+
/** Ends a run nothing will pick up again, and says so. */
|
|
293
|
+
function stopRun(draft, run, why, summary, words) {
|
|
294
|
+
put(draft, "runs", run.id, { state: "cancelled", finished_at: draft.at, summary });
|
|
295
|
+
clearFiredTimers(draft, run);
|
|
296
|
+
closeStopped(draft, run.id, summary);
|
|
297
|
+
notify(draft, `run:${run.id}:${why}`, run.rule, words, threadOf(run));
|
|
298
|
+
}
|
|
299
|
+
const ruleGone = (rule, what = "排着的这一轮") => [
|
|
300
|
+
`规则「${rule}」不在了,不再派发`,
|
|
301
|
+
`规则「${rule}」不在了(删掉或改名了),${what}不再派发。还要做的话重新触发这件事。`,
|
|
302
|
+
];
|
|
303
|
+
/** Enough of what a look-again was for to know it again: it can run to thousands of characters. */
|
|
304
|
+
function opening(about) {
|
|
305
|
+
const chars = [...about.replace(/\s+/g, " ").trim()];
|
|
306
|
+
return chars.length > 60 ? `${chars.slice(0, 60).join("")}…` : chars.join("");
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* What a card about a failing run shows of its error: an agent's error can run to 500 characters over several lines, which a
|
|
310
|
+
* phone can't make sense of. Agents hand back the end of what they printed, the reason last, so the last line, and the end
|
|
311
|
+
* of it when it's long; the whole of it stays on the run, for `why`.
|
|
312
|
+
*/
|
|
313
|
+
function briefError(error, run) {
|
|
314
|
+
const line = error
|
|
315
|
+
.split("\n")
|
|
316
|
+
.findLast((part) => part.trim())
|
|
317
|
+
?.trim() ?? error;
|
|
318
|
+
const characters = [...line];
|
|
319
|
+
if (characters.length <= 120 && line === error)
|
|
320
|
+
return error;
|
|
321
|
+
const cut = characters.length > 120 ? `…${characters.slice(-120).join("")}` : line;
|
|
322
|
+
return `${cut}(完整原因:agent-autoloop why ${run})`;
|
|
323
|
+
}
|
|
324
|
+
/** A run that didn't get through waits to try again, and takes along whatever came in for the same thing meanwhile. */
|
|
325
|
+
function retryLater(draft, run, result) {
|
|
326
|
+
const { id } = run;
|
|
327
|
+
const attempts = run.attempts + 1;
|
|
328
|
+
const notBefore = draft.now + Math.min(5 * MINUTE * 2 ** (attempts - 1), 60 * MINUTE);
|
|
329
|
+
const error = (result.error ?? "").trim().replace(/[。.]+$/, "") || "没说原因";
|
|
330
|
+
const unclaimed = nulls("claim", "claimed_at", "seen_at", "cancel_at");
|
|
331
|
+
const rejected = [];
|
|
332
|
+
for (const what of ["ask", "resolve", "later", "events"]) {
|
|
333
|
+
for (const _ of result[what] ?? [])
|
|
334
|
+
rejected.push({ what, reason: "没跑成的一轮只能发通知" });
|
|
335
|
+
}
|
|
336
|
+
for (const notice of result.notice ?? [])
|
|
337
|
+
cardFromReceipt(draft, run, "notice", notice);
|
|
338
|
+
const failure = { attempts, error, ...unclaimed };
|
|
339
|
+
if (!ruleNamed(draft, run.rule)) {
|
|
340
|
+
put(draft, "runs", id, failure);
|
|
341
|
+
stopRun(draft, run, "rule-gone", ...ruleGone(run.rule));
|
|
342
|
+
return rejected;
|
|
343
|
+
}
|
|
344
|
+
if (attempts >= MAX_ATTEMPTS) {
|
|
345
|
+
// Runs queued for this thread stay apart: they came in since, and get their own count and their own go.
|
|
346
|
+
const summary = `连续 ${MAX_ATTEMPTS} 次没跑成,不再自动重试`;
|
|
347
|
+
const words = `连续 ${MAX_ATTEMPTS} 次自动处理没跑完(卡在:${briefError(error, id)}),不再自动重试。解决后重新触发这件事,它会从头开始。`;
|
|
348
|
+
put(draft, "runs", id, failure);
|
|
349
|
+
stopRun(draft, run, "stopped", summary, words);
|
|
350
|
+
return rejected;
|
|
351
|
+
}
|
|
352
|
+
put(draft, "runs", id, { state: "queued", not_before: iso(notBefore), ...failure });
|
|
353
|
+
const waiting = rows(draft.view, "runs", { rule: run.rule, lane: run.lane, state: "queued" });
|
|
354
|
+
for (const other of waiting.filter((other) => other.id !== id)) {
|
|
355
|
+
for (const link of rows(draft.view, "run_events", { run_id: other.id })) {
|
|
356
|
+
put(draft, "run_events", `${id}:${link.event_id}`, { run_id: id, event_id: link.event_id });
|
|
357
|
+
set(draft, "run_events", `${other.id}:${link.event_id}`, null);
|
|
358
|
+
}
|
|
359
|
+
set(draft, "runs", other.id, null);
|
|
360
|
+
if (other.resume)
|
|
361
|
+
put(draft, "runs", id, { resume: other.resume });
|
|
362
|
+
}
|
|
363
|
+
if (!result.notice?.some((notice) => !notice.fyi) && attempts === 3) {
|
|
364
|
+
const clock = { timeZone: draft.rules.timezone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" };
|
|
365
|
+
const time = new Intl.DateTimeFormat("zh-CN", clock).format(notBefore);
|
|
366
|
+
const words = `连续 3 次自动处理没跑完(卡在:${briefError(error, id)}),${time} 会自动再试。`;
|
|
367
|
+
notify(draft, `run:${id}:failing`, run.rule, words, threadOf(run));
|
|
368
|
+
}
|
|
369
|
+
assignQueued(draft, draft.view.get("runs", id));
|
|
370
|
+
return rejected;
|
|
371
|
+
}
|
|
372
|
+
function scheduleReview(draft, run, later) {
|
|
373
|
+
const { rule, lane } = run;
|
|
374
|
+
const [existing] = rows(draft.view, "timers", { rule, lane, key: later.key, event_id: null });
|
|
375
|
+
if (later.cancel) {
|
|
376
|
+
if (existing)
|
|
377
|
+
set(draft, "timers", existing.id, null);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const session = draft.view.get("runs", run.id).session;
|
|
381
|
+
const fields = {
|
|
382
|
+
at: iso(Date.parse(later.at)),
|
|
383
|
+
about: later.about,
|
|
384
|
+
session,
|
|
385
|
+
agent: run.agent,
|
|
386
|
+
hops: hopsOf(draft, run),
|
|
387
|
+
// Written now, like `hops`: the row names no run for a later round to follow back from, and it is removed when the
|
|
388
|
+
// round it wakes ends, so the ids are recorded while the round that set the check is still here.
|
|
389
|
+
events: JSON.stringify(askedAbout(draft.view, run.id)),
|
|
390
|
+
};
|
|
391
|
+
if (existing)
|
|
392
|
+
return void put(draft, "timers", existing.id, fields);
|
|
393
|
+
const source = sourceOf(draft.view, run.id) ?? SCHEDULE;
|
|
394
|
+
add(draft, "timers", { ...fields, rule, lane, key: later.key, source, event_id: null, created_at: draft.at });
|
|
395
|
+
}
|
|
396
|
+
/** A receipt takes effect here, all of it in the one fact. */
|
|
397
|
+
function applyReceipt(draft, run, result) {
|
|
398
|
+
const { id } = run;
|
|
399
|
+
const rule = ruleNamed(draft, run.rule);
|
|
400
|
+
const summary = result.summary ?? "";
|
|
401
|
+
const rejected = [];
|
|
402
|
+
put(draft, "runs", id, { state: result.outcome, finished_at: draft.at, summary, error: null, cancel_at: null });
|
|
403
|
+
closeOpen(draft, (key) => key === `run:${id}:failing`, "后来跑成了");
|
|
404
|
+
closeOpen(draft, (key) => key === `run:${id}:unknown`, "结果回来了");
|
|
405
|
+
const eventIds = eventsOf(draft.view, id).map((event) => event.id);
|
|
406
|
+
for (const card of rows(draft.view, "cards", { answer_event: eventIds, state: "decided" })) {
|
|
407
|
+
put(draft, "cards", card.id, { state: "done", result: summary, closed_at: draft.at, version: card.version + 1 });
|
|
408
|
+
}
|
|
409
|
+
for (const item of result.resolve ?? []) {
|
|
410
|
+
const card = openInScope(draft.view, run).find((card) => card.id === item.card);
|
|
411
|
+
if (card)
|
|
412
|
+
closeCard(draft, card, item.reason.trim(), `第 ${id} 轮`);
|
|
413
|
+
else
|
|
414
|
+
rejected.push({ card: item.card, reason: "不在本轮核对范围" });
|
|
415
|
+
}
|
|
416
|
+
for (const ask of result.ask ?? [])
|
|
417
|
+
cardFromReceipt(draft, run, "ask", ask);
|
|
418
|
+
for (const notice of result.notice ?? [])
|
|
419
|
+
cardFromReceipt(draft, run, "notice", notice);
|
|
420
|
+
if (rule?.tell === "always" && result.outcome === "done") {
|
|
421
|
+
const once = { fyi: true, once: true, ...threadOf(run), source: sourceOf(draft.view, id), run: id };
|
|
422
|
+
notify(draft, `run:${id}:done`, run.rule, summary, once);
|
|
423
|
+
}
|
|
424
|
+
for (const later of result.later ?? [])
|
|
425
|
+
scheduleReview(draft, run, later);
|
|
426
|
+
const emitted = [];
|
|
427
|
+
for (const event of result.events ?? []) {
|
|
428
|
+
if (rule?.emits && typeMatches(rule.emits.types, event.type)) {
|
|
429
|
+
const sent = ingest(draft, rule.emits.source, { ...event, hops: hopsOf(draft, run) + 1 });
|
|
430
|
+
// A number already taken is an earlier event's, perhaps another source's: what it says isn't what this receipt sent.
|
|
431
|
+
if (!sent.duplicate)
|
|
432
|
+
emitted.push(sent.event);
|
|
433
|
+
}
|
|
434
|
+
else
|
|
435
|
+
rejected.push({ what: "events", reason: `规则「${run.rule}」没有写可以发 ${event.type}` });
|
|
436
|
+
}
|
|
437
|
+
// The source whose event this run took reads them back (`eventOutcome`); nothing else links them to the run.
|
|
438
|
+
if (emitted.length)
|
|
439
|
+
put(draft, "runs", id, { emitted: JSON.stringify(emitted) });
|
|
440
|
+
clearFiredTimers(draft, run);
|
|
441
|
+
return rejected;
|
|
442
|
+
}
|
|
443
|
+
function finish(draft, id, token, given) {
|
|
444
|
+
const hash = digest(JSON.stringify(given ?? null));
|
|
445
|
+
const prior = draft.view.get("runs", id);
|
|
446
|
+
// The same execution handing in again means the answer got lost: it gets the same answer, and nothing happens twice.
|
|
447
|
+
if (prior && prior.last_issued !== null && credential(draft.env, "run", id, prior.last_issued) === token) {
|
|
448
|
+
if (prior.last_result !== hash)
|
|
449
|
+
throw new Conflict("这一次执行已经交过不一样的结果");
|
|
450
|
+
return { rejected: JSON.parse(prior.last_answer ?? "[]"), duplicate: true };
|
|
451
|
+
}
|
|
452
|
+
const run = heldRun(draft, id, token, ["claimed", "unknown"]);
|
|
453
|
+
const result = parseResult(given);
|
|
454
|
+
const session = result.session ?? run.session;
|
|
455
|
+
const usage = result.usage
|
|
456
|
+
? JSON.stringify(addUsage(run.usage ? JSON.parse(run.usage) : undefined, result.usage))
|
|
457
|
+
: run.usage;
|
|
458
|
+
put(draft, "runs", id, { last_issued: run.issued, last_result: hash, issued: null, session, usage });
|
|
459
|
+
let rejected = [];
|
|
460
|
+
// Told to stop, one that failed first has stopped all the same: trying again would start what the owner ended.
|
|
461
|
+
if (result.outcome === "cancelled" || (result.outcome === "failed" && run.cancel_at)) {
|
|
462
|
+
put(draft, "runs", id, {
|
|
463
|
+
state: "cancelled",
|
|
464
|
+
finished_at: draft.at,
|
|
465
|
+
summary: result.summary ?? "",
|
|
466
|
+
cancel_at: null,
|
|
467
|
+
});
|
|
468
|
+
clearFiredTimers(draft, run);
|
|
469
|
+
closeStopped(draft, id, "已停止");
|
|
470
|
+
}
|
|
471
|
+
else if (result.outcome === "failed")
|
|
472
|
+
rejected = retryLater(draft, run, result);
|
|
473
|
+
else
|
|
474
|
+
rejected = applyReceipt(draft, run, result);
|
|
475
|
+
put(draft, "runs", id, { last_answer: JSON.stringify(rejected) });
|
|
476
|
+
return { rejected };
|
|
477
|
+
}
|
|
478
|
+
function answer(draft, id, given) {
|
|
479
|
+
const card = draft.view.get("cards", id);
|
|
480
|
+
if (!card)
|
|
481
|
+
throw new NotFound("没有这张卡片");
|
|
482
|
+
if (given.channel !== undefined) {
|
|
483
|
+
const allowed = draft.rules.channels[given.channel]?.answerers;
|
|
484
|
+
if (allowed && !allowed.includes(given.by ?? ""))
|
|
485
|
+
throw new AuthError("这个人不能回答这张卡片");
|
|
486
|
+
const delivery = draft.view.get("deliveries", `${id}:${given.channel}`);
|
|
487
|
+
if (!delivery?.ref || delivery.ref !== given.ref)
|
|
488
|
+
throw new AuthError("不是发出去的那条消息");
|
|
489
|
+
}
|
|
490
|
+
if (card.state !== "open")
|
|
491
|
+
return { changed: false, state: card.state };
|
|
492
|
+
if (given.by !== undefined && (typeof given.by !== "string" || [...given.by].length > ANSWER_BY)) {
|
|
493
|
+
throw new InputError(`回答人最多 ${ANSWER_BY} 字`);
|
|
494
|
+
}
|
|
495
|
+
if (given.ref !== undefined && (typeof given.ref !== "string" || [...given.ref].length > ANSWER_REF)) {
|
|
496
|
+
throw new InputError(`消息编号最多 ${ANSWER_REF} 字`);
|
|
497
|
+
}
|
|
498
|
+
const words = card.kind === "notice" ? "处理说明" : "回答";
|
|
499
|
+
if (given.text !== undefined && typeof given.text !== "string")
|
|
500
|
+
throw new InputError(`${words}要是文字`);
|
|
501
|
+
const text = given.text?.trim() || null;
|
|
502
|
+
if (text !== null && [...text].length > ANSWER_TEXT)
|
|
503
|
+
throw new InputError(`${words}最多 ${ANSWER_TEXT} 字`);
|
|
504
|
+
if (card.kind === "notice") {
|
|
505
|
+
closeCard(draft, card, "已处理", given.by ?? null, text);
|
|
506
|
+
return { changed: true, state: "closed" };
|
|
507
|
+
}
|
|
508
|
+
const optionCount = JSON.parse(card.options).length;
|
|
509
|
+
const inRange = Number.isInteger(given.choice) && given.choice >= 0 && given.choice < optionCount;
|
|
510
|
+
if (given.choice === undefined ? !text : !inRange)
|
|
511
|
+
throw new InputError("没有这个选项");
|
|
512
|
+
const rule = card.rule ? ruleNamed(draft, card.rule) : undefined;
|
|
513
|
+
const { lane: subject, title: summary, hops = 0 } = card;
|
|
514
|
+
const event = { id: `card:${id}`, type: "card.answered", subject, summary, hops };
|
|
515
|
+
const eventId = recordEvent(draft, card.source ?? SCHEDULE, event, rule ? [rule.name] : []);
|
|
516
|
+
const decision = { choice: given.choice ?? null, answer: text, by: given.by ?? null, decided_at: draft.at };
|
|
517
|
+
put(draft, "cards", id, { state: "decided", ...decision, answer_event: eventId, version: card.version + 1 });
|
|
518
|
+
if (rule)
|
|
519
|
+
enqueue(draft, rule, eventId, card.lane, card.agent === rule.to ? card.session : null);
|
|
520
|
+
return { changed: true, state: "decided" };
|
|
521
|
+
}
|
|
522
|
+
function nextCard(draft, channel) {
|
|
523
|
+
const { now } = draft;
|
|
524
|
+
for (const card of draft.view.deliveryCandidates(channel, now)) {
|
|
525
|
+
const reach = (card.rule ? ruleNamed(draft, card.rule)?.channels : undefined) ?? draft.rules.defaultChannels;
|
|
526
|
+
if (reach && !reach.includes(channel))
|
|
527
|
+
continue;
|
|
528
|
+
const key = `${card.id}:${channel}`;
|
|
529
|
+
const delivery = draft.view.get("deliveries", key) ?? NOT_DELIVERED;
|
|
530
|
+
const recentNote = card.fyi && Date.parse(card.created_at) >= now - 24 * 60 * MINUTE;
|
|
531
|
+
const worthSending = card.state === "open" || delivery.ref !== null || recentNote;
|
|
532
|
+
const resting = delivery.not_before && Date.parse(delivery.not_before) > now;
|
|
533
|
+
if (card.quiet || delivery.version >= card.version || delivery.given_up || resting || !worthSending)
|
|
534
|
+
continue;
|
|
535
|
+
const firstTry = delivery.first_try_at;
|
|
536
|
+
if (delivery.tries >= RESEND_AT.length || (firstTry && now - Date.parse(firstTry) > RESEND_WINDOW)) {
|
|
537
|
+
put(draft, "deliveries", key, { given_up: 1 });
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const attempt = { tries: delivery.tries + 1, first_try_at: firstTry ?? draft.at, not_before: iso(now + MINUTE) };
|
|
541
|
+
put(draft, "deliveries", key, { card_id: card.id, channel, ...attempt });
|
|
542
|
+
return cardView(card, draft.env, delivery.ref, draft.rules.channels[channel]?.links === true);
|
|
543
|
+
}
|
|
544
|
+
return null;
|
|
545
|
+
}
|
|
546
|
+
/** What the clock has brought: schedules come round, reviews come due, and anything gone quiet. */
|
|
547
|
+
function tick(draft) {
|
|
548
|
+
const { now } = draft;
|
|
549
|
+
const { rules, timezone } = draft.rules;
|
|
550
|
+
for (const pause of rows(draft.view, "pauses")) {
|
|
551
|
+
if (pause.until === null || Date.parse(pause.until) > now)
|
|
552
|
+
continue;
|
|
553
|
+
set(draft, "pauses", pause.name, null);
|
|
554
|
+
reopen(draft, pause.name, Date.parse(pause.until));
|
|
555
|
+
}
|
|
556
|
+
for (const rule of rules) {
|
|
557
|
+
if (eventRule(rule))
|
|
558
|
+
continue;
|
|
559
|
+
const text = cronOf(rule);
|
|
560
|
+
const cron = parseCron(text);
|
|
561
|
+
const schedule = draft.view.get("schedules", rule.name);
|
|
562
|
+
const nextAt = () => iso(nextRun(cron, now, timezone));
|
|
563
|
+
if (!schedule || schedule.cron !== text) {
|
|
564
|
+
put(draft, "schedules", rule.name, { rule: rule.name, cron: text, next_at: nextAt() });
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
if (now < Date.parse(schedule.next_at))
|
|
568
|
+
continue;
|
|
569
|
+
const slot = iso(latestBefore(cron, Date.parse(schedule.next_at), now, timezone));
|
|
570
|
+
// Paused, the moment passes without a run, and the next one is the next one: a resume owes nothing.
|
|
571
|
+
if (pauseOf(draft.view, rule, now)) {
|
|
572
|
+
put(draft, "schedules", rule.name, { next_at: nextAt(), skipped_at: slot });
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
const key = `${rule.name}@${slot}`;
|
|
576
|
+
if (!rows(draft.view, "events", { source: SCHEDULE, key }).length) {
|
|
577
|
+
enqueue(draft, rule, recordEvent(draft, SCHEDULE, { id: key, type: "schedule.tick" }, [rule.name]), "");
|
|
578
|
+
}
|
|
579
|
+
put(draft, "schedules", rule.name, { next_at: nextAt() });
|
|
580
|
+
}
|
|
581
|
+
const due = rows(draft.view, "timers", { event_id: null }).filter((timer) => Date.parse(timer.at) <= now);
|
|
582
|
+
for (const timer of due.sort((a, b) => a.at.localeCompare(b.at))) {
|
|
583
|
+
const rule = ruleNamed(draft, timer.rule);
|
|
584
|
+
const event = { id: `timer:${timer.id}`, type: "timer.due", subject: timer.lane, hops: timer.hops ?? 0 };
|
|
585
|
+
const eventId = recordEvent(draft, timer.source, event, rule ? [rule.name] : []);
|
|
586
|
+
if (rule) {
|
|
587
|
+
put(draft, "timers", timer.id, { event_id: eventId });
|
|
588
|
+
enqueue(draft, rule, eventId, timer.lane, timer.agent === rule.to ? timer.session : null);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
const [, words] = ruleGone(timer.rule, `到期的复查「${opening(timer.about)}」`);
|
|
592
|
+
notify(draft, `timer:${timer.id}:rule-gone`, timer.rule, words, { rule: timer.rule, lane: timer.lane });
|
|
593
|
+
set(draft, "timers", timer.id, null);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
sweep(draft);
|
|
597
|
+
}
|
|
598
|
+
/** A schedule whose next moment passed while paused starts again at the first moment from `from`, not with a backlog. */
|
|
599
|
+
function reopen(draft, name, from) {
|
|
600
|
+
const rule = draft.rules.rules.find((rule) => rule.name === name);
|
|
601
|
+
if (!rule || eventRule(rule))
|
|
602
|
+
return;
|
|
603
|
+
const schedule = draft.view.get("schedules", rule.name);
|
|
604
|
+
if (!schedule || Date.parse(schedule.next_at) >= from)
|
|
605
|
+
return;
|
|
606
|
+
const next = nextRun(parseCron(cronOf(rule)), from - 1, draft.rules.timezone);
|
|
607
|
+
put(draft, "schedules", rule.name, { next_at: iso(next) });
|
|
608
|
+
}
|
|
609
|
+
function knownRule(draft, name) {
|
|
610
|
+
// Not ruleNamed: a task elsewhere that can ask goes on like a rule, but the hub neither starts nor holds it.
|
|
611
|
+
const rule = draft.rules.rules.find((rule) => rule.name === name);
|
|
612
|
+
if (rule)
|
|
613
|
+
return rule;
|
|
614
|
+
if (draft.rules.elsewhere.some((task) => task.name === name)) {
|
|
615
|
+
throw new InputError(`「${name}」是在别处跑的定时任务,中台不启动它,也就停不了、跑不了`);
|
|
616
|
+
}
|
|
617
|
+
throw new NotFound(`没有这条规则:${name}`);
|
|
618
|
+
}
|
|
619
|
+
const PAUSE_REASON = 500;
|
|
620
|
+
function pauseFields(draft, given) {
|
|
621
|
+
const { reason = "", until = null } = given ?? {};
|
|
622
|
+
if (typeof reason !== "string" || [...reason].length > PAUSE_REASON) {
|
|
623
|
+
throw new InputError(`暂停原因要是 ${PAUSE_REASON} 字以内的文字`);
|
|
624
|
+
}
|
|
625
|
+
const ends = typeof until === "string" && /(Z|[+-]\d\d:\d\d)$/.test(until) ? Date.parse(until) : NaN;
|
|
626
|
+
if (until !== null && !(ends > draft.now))
|
|
627
|
+
throw new InputError("until 要是带时区、晚于现在的 ISO 时间");
|
|
628
|
+
return { reason: reason.trim(), until: until === null ? null : iso(ends) };
|
|
629
|
+
}
|
|
630
|
+
const pauseView = ({ by, reason, since, until }) => ({ by, reason, since, until });
|
|
631
|
+
/** Owner actions on one rule. They are facts in the log, not edits to rules.json. */
|
|
632
|
+
const CONTROL = {
|
|
633
|
+
pauseRule(draft, name, by, given) {
|
|
634
|
+
knownRule(draft, name);
|
|
635
|
+
const fields = pauseFields(draft, given);
|
|
636
|
+
const existing = draft.view.get("pauses", name);
|
|
637
|
+
const same = existing && existing.reason === fields.reason && existing.until === fields.until;
|
|
638
|
+
if (!same)
|
|
639
|
+
put(draft, "pauses", name, { name, by, since: existing?.since ?? draft.at, ...fields });
|
|
640
|
+
return { changed: !same, rule: name, paused: pauseView(draft.view.get("pauses", name)) };
|
|
641
|
+
},
|
|
642
|
+
resumeRule(draft, name) {
|
|
643
|
+
// A rule taken out of rules.json while paused can still have its pause lifted.
|
|
644
|
+
const pause = draft.view.get("pauses", name);
|
|
645
|
+
if (!pause) {
|
|
646
|
+
knownRule(draft, name);
|
|
647
|
+
return { changed: false, rule: name };
|
|
648
|
+
}
|
|
649
|
+
set(draft, "pauses", name, null);
|
|
650
|
+
reopen(draft, name, draft.now);
|
|
651
|
+
// Which pause it was: what it skipped is read from when it began, and once it's gone nothing else says when.
|
|
652
|
+
return { changed: true, rule: name, paused: pauseView(pause) };
|
|
653
|
+
},
|
|
654
|
+
/** Events a pause kept from the rule, taken by it now as they would have been then: each once, never while paused. */
|
|
655
|
+
replayRule(draft, name, events) {
|
|
656
|
+
const rule = knownRule(draft, name);
|
|
657
|
+
if (!eventRule(rule))
|
|
658
|
+
throw new InputError(`「${name}」是定时规则,暂停时到点不跑、不记事件,没有可补跑的;要补一轮用 run`);
|
|
659
|
+
if (pauseOf(draft.view, rule, draft.now))
|
|
660
|
+
throw new Conflict(`规则「${name}」暂停中,先恢复再补跑`);
|
|
661
|
+
// An event stays as it came, still saying which pauses skipped it. What says it's been made up is a run of this rule
|
|
662
|
+
// holding it, and a link once made only ever moves to another run of the same rule and matter.
|
|
663
|
+
const taken = (id) => rows(draft.view, "run_events", { event_id: id }).some((link) => draft.view.get("runs", link.run_id)?.rule === name);
|
|
664
|
+
const replayed = [];
|
|
665
|
+
const runs = new Set();
|
|
666
|
+
for (const id of [...events].sort((a, b) => a - b)) {
|
|
667
|
+
const event = draft.view.get("events", id);
|
|
668
|
+
if (!event || !JSON.parse(event.paused ?? "[]").includes(name) || taken(id))
|
|
669
|
+
continue;
|
|
670
|
+
runs.add(enqueue(draft, rule, id, rule.parallel ? event.subject : ""));
|
|
671
|
+
replayed.push(id);
|
|
672
|
+
}
|
|
673
|
+
return { events: replayed, runs: [...runs] };
|
|
674
|
+
},
|
|
675
|
+
/** One run now, through the usual queue, from an event of its own that says the owner asked for it. */
|
|
676
|
+
runRule(draft, name, by, given) {
|
|
677
|
+
const rule = knownRule(draft, name);
|
|
678
|
+
const { subject = "", reason = "" } = given ?? {};
|
|
679
|
+
if (typeof reason !== "string" || [...reason].length > PAUSE_REASON) {
|
|
680
|
+
throw new InputError(`说明要是 ${PAUSE_REASON} 字以内的文字`);
|
|
681
|
+
}
|
|
682
|
+
if (pauseOf(draft.view, rule, draft.now))
|
|
683
|
+
throw new Conflict(`规则「${name}」暂停中,先恢复再手动运行`);
|
|
684
|
+
const source = eventRule(rule) ? rule.when.source : SCHEDULE;
|
|
685
|
+
// The same checks as any event: its subject becomes the lane and goes into the prompt.
|
|
686
|
+
const event = parseEvent({
|
|
687
|
+
id: `manual:${draft.seq}`,
|
|
688
|
+
type: "run.manual",
|
|
689
|
+
subject,
|
|
690
|
+
summary: `${by} 手动运行`,
|
|
691
|
+
detail: reason,
|
|
692
|
+
});
|
|
693
|
+
const eventId = recordEvent(draft, source, event, [name]);
|
|
694
|
+
const run = enqueue(draft, rule, eventId, rule.parallel ? subject : "");
|
|
695
|
+
// Waiting out a retry's backoff wouldn't be now: the owner asking is the go-ahead.
|
|
696
|
+
put(draft, "runs", run, { manual: 1, not_before: draft.at });
|
|
697
|
+
return { event: eventId, run };
|
|
698
|
+
},
|
|
699
|
+
};
|
|
700
|
+
/** Every input there is, each with its arguments named. What one returns is what the caller is told. */
|
|
701
|
+
const HANDLERS = {
|
|
702
|
+
rules(draft, rules) {
|
|
703
|
+
put(draft, "config", "rules", { value: rules, version: draft.seq });
|
|
704
|
+
for (const run of rows(draft.view, "runs", { state: "queued" })) {
|
|
705
|
+
if (ruleOf(rules, run.rule))
|
|
706
|
+
assignQueued(draft, run);
|
|
707
|
+
else
|
|
708
|
+
stopRun(draft, run, "rule-gone", ...ruleGone(run.rule));
|
|
709
|
+
}
|
|
710
|
+
closeOpen(draft, (key) => key.startsWith("rules:"), "改好了");
|
|
711
|
+
},
|
|
712
|
+
rulesError: (draft, problem) => notify(draft, `rules:${digest(problem)}`, "rules.json 写错了,还在用旧规则", problem),
|
|
713
|
+
key: (draft, kind, name, hash) => void put(draft, "keys", `${kind}:${name}`, { kind, name, hash, created_at: draft.at }),
|
|
714
|
+
removeKey: (draft, kind, name) => {
|
|
715
|
+
if (!draft.view.get("keys", `${kind}:${name}`))
|
|
716
|
+
return false;
|
|
717
|
+
set(draft, "keys", `${kind}:${name}`, null);
|
|
718
|
+
return true;
|
|
719
|
+
},
|
|
720
|
+
ingest: (draft, source, given) => ingest(draft, source, given, true),
|
|
721
|
+
createCard,
|
|
722
|
+
/** A task elsewhere asks you; your answer goes on like a round of a rule, where its cwd says. */
|
|
723
|
+
ask(draft, name, given) {
|
|
724
|
+
const task = draft.rules.elsewhere.find((task) => task.name === name);
|
|
725
|
+
if (!task.cwd)
|
|
726
|
+
throw new InputError(`定时任务「${name}」没写 cwd,回答了没人接着做:只能 tell`);
|
|
727
|
+
const { key, ...question } = given;
|
|
728
|
+
const matter = key ?? digest(`${question.title}\n${question.text}`).slice(0, 32);
|
|
729
|
+
const thread = { rule: name, lane: "", grp: name, source: task.source, agent: task.to };
|
|
730
|
+
// A key of its own: told once for good, a notice under the same key would never get through after a question.
|
|
731
|
+
return createCard(draft, { ...question, key: `elsewhere-ask:${name}:${matter}`, kind: "ask", ...thread });
|
|
732
|
+
},
|
|
733
|
+
tell(draft, key, title, text) {
|
|
734
|
+
const told = createCard(draft, { key, title, text, kind: "notice", fyi: true, once: true });
|
|
735
|
+
if (!told.duplicate)
|
|
736
|
+
return told;
|
|
737
|
+
// Said again after every channel gave up on it: it gets another go.
|
|
738
|
+
const givenUp = rows(draft.view, "deliveries", { card_id: told.card, given_up: 1 });
|
|
739
|
+
for (const { card_id, channel } of givenUp) {
|
|
740
|
+
put(draft, "deliveries", `${card_id}:${channel}`, { given_up: 0, ...NOT_TRYING });
|
|
741
|
+
}
|
|
742
|
+
if (!givenUp.length)
|
|
743
|
+
return told;
|
|
744
|
+
put(draft, "cards", told.card, { text, created_at: draft.at });
|
|
745
|
+
return { ...told, duplicate: false };
|
|
746
|
+
},
|
|
747
|
+
heartbeat(draft, worker, running) {
|
|
748
|
+
closeOffline(draft, worker);
|
|
749
|
+
const held = (run) => run?.state === "claimed" && workerOf(draft.view, run) === worker;
|
|
750
|
+
const inHand = running.map((id) => draft.view.get("runs", id)).filter(held);
|
|
751
|
+
// All stamped together, so however many runs a worker has on, it's one fact each time.
|
|
752
|
+
if ([draft.view.get("seen", `worker:${worker}`), ...inHand].every((row) => justSeen(draft, row)))
|
|
753
|
+
return;
|
|
754
|
+
put(draft, "seen", `worker:${worker}`, { kind: "worker", name: worker, seen_at: draft.at });
|
|
755
|
+
for (const run of inHand)
|
|
756
|
+
put(draft, "runs", run.id, { seen_at: draft.at });
|
|
757
|
+
},
|
|
758
|
+
channelSeen(draft, name) {
|
|
759
|
+
if (justSeen(draft, draft.view.get("seen", `channel:${name}`)))
|
|
760
|
+
return;
|
|
761
|
+
put(draft, "seen", `channel:${name}`, { kind: "channel", name, seen_at: draft.at });
|
|
762
|
+
},
|
|
763
|
+
claimNext,
|
|
764
|
+
started(draft, id, token, given) {
|
|
765
|
+
const { session, link } = given ?? {};
|
|
766
|
+
for (const [field, value] of Object.entries({ session, link })) {
|
|
767
|
+
if (value !== undefined && (typeof value !== "string" || value.length > 500)) {
|
|
768
|
+
throw new InputError(`${field} 要是 500 字以内的文字`);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
const run = heldRun(draft, id, token, ["claimed"]);
|
|
772
|
+
put(draft, "runs", id, { session: session ?? run.session, link: link ?? run.link, seen_at: draft.at });
|
|
773
|
+
},
|
|
774
|
+
finish,
|
|
775
|
+
cancel(draft, id) {
|
|
776
|
+
const run = draft.view.get("runs", id);
|
|
777
|
+
if (!run)
|
|
778
|
+
throw new NotFound("没有这一轮");
|
|
779
|
+
if (run.state === "queued") {
|
|
780
|
+
put(draft, "runs", id, { state: "cancelled", finished_at: draft.at });
|
|
781
|
+
clearFiredTimers(draft, run);
|
|
782
|
+
closeStopped(draft, id, "已停止");
|
|
783
|
+
}
|
|
784
|
+
else if (run.state === "claimed")
|
|
785
|
+
put(draft, "runs", id, { cancel_at: draft.at });
|
|
786
|
+
else
|
|
787
|
+
throw new InputError("这一轮已经结束了");
|
|
788
|
+
},
|
|
789
|
+
resolve(draft, id, reason, by) {
|
|
790
|
+
const card = draft.view.get("cards", id);
|
|
791
|
+
if (!card)
|
|
792
|
+
throw new NotFound("没有这张卡片");
|
|
793
|
+
if (card.state !== "open")
|
|
794
|
+
return false;
|
|
795
|
+
closeCard(draft, card, reason, by);
|
|
796
|
+
return true;
|
|
797
|
+
},
|
|
798
|
+
answer,
|
|
799
|
+
nextCard,
|
|
800
|
+
delivered(draft, channel, id, version, ref) {
|
|
801
|
+
if (!draft.view.get("cards", id))
|
|
802
|
+
throw new NotFound("没有这张卡片");
|
|
803
|
+
if (ref !== null && (typeof ref !== "string" || [...ref].length > DELIVERY_REF)) {
|
|
804
|
+
throw new InputError(`消息编号最多 ${DELIVERY_REF} 字`);
|
|
805
|
+
}
|
|
806
|
+
const delivery = draft.view.get("deliveries", `${id}:${channel}`) ?? NOT_DELIVERED;
|
|
807
|
+
const sent = { version: Math.max(delivery.version, version), ref: delivery.ref ?? ref };
|
|
808
|
+
put(draft, "deliveries", `${id}:${channel}`, { card_id: id, channel, ...sent, ...NOT_TRYING, error: null });
|
|
809
|
+
},
|
|
810
|
+
failed(draft, channel, id, version, error) {
|
|
811
|
+
const card = draft.view.get("cards", id);
|
|
812
|
+
const delivery = draft.view.get("deliveries", `${id}:${channel}`);
|
|
813
|
+
if (!card || !delivery)
|
|
814
|
+
throw new NotFound("这张卡片没有交给这个通道");
|
|
815
|
+
const firstTry = delivery.first_try_at ? Date.parse(delivery.first_try_at) : draft.now;
|
|
816
|
+
const next = version < card.version
|
|
817
|
+
? { not_before: null }
|
|
818
|
+
: delivery.tries >= RESEND_AT.length
|
|
819
|
+
? { given_up: 1 }
|
|
820
|
+
: { not_before: iso(firstTry + RESEND_AT[delivery.tries] * MINUTE) };
|
|
821
|
+
put(draft, "deliveries", `${id}:${channel}`, { ...next, error: [...String(error)].slice(0, 300).join("") });
|
|
822
|
+
},
|
|
823
|
+
sweep,
|
|
824
|
+
tick,
|
|
825
|
+
...CONTROL,
|
|
826
|
+
};
|