@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,33 @@
|
|
|
1
|
+
// Homebrew keeps a version's files under `Cellar`, and deletes that directory at the next upgrade; `opt` beside it is
|
|
2
|
+
// the link that follows. A program named by its Cellar path dies the next time the machine is upgraded.
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
const CELLARS = ["/opt/homebrew", "/usr/local"];
|
|
5
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6
|
+
const resolve = (path) => {
|
|
7
|
+
try {
|
|
8
|
+
return realpathSync(path);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* The path that keeps working across an upgrade: `opt` when it names this executable, and also when this executable's
|
|
16
|
+
* own directory is already gone and `opt` still resolves. A long-running process outlives the version directory it
|
|
17
|
+
* started from, so the children it starts need the link, not that path.
|
|
18
|
+
*/
|
|
19
|
+
export function stablePath(executable, cellars = CELLARS) {
|
|
20
|
+
const cellar = new RegExp(`^(${cellars.map(escape).join("|")})/Cellar/([^/]+)/[^/]+/bin/([^/]+)$`).exec(executable);
|
|
21
|
+
if (!cellar)
|
|
22
|
+
return executable;
|
|
23
|
+
const opt = `${cellar[1]}/opt/${cellar[2]}/bin/${cellar[3]}`;
|
|
24
|
+
const linked = resolve(opt);
|
|
25
|
+
// No link, or one that goes nowhere: there is nothing better than what is already running.
|
|
26
|
+
if (!linked)
|
|
27
|
+
return executable;
|
|
28
|
+
const current = resolve(executable);
|
|
29
|
+
// Deleted by an upgrade while this process kept running: only the link can start anything now.
|
|
30
|
+
if (!current)
|
|
31
|
+
return opt;
|
|
32
|
+
return current === linked ? opt : executable;
|
|
33
|
+
}
|
package/dist/host/npm.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// npm, run from inside a program npm installed: on Windows its .cmd shim can't be started directly, so run what the shim
|
|
2
|
+
// points at. A command that fails throws; its output is never taken for an answer.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { commandLine } from "./command.js";
|
|
6
|
+
/** The package these files came from; updating and removing it go through npm. */
|
|
7
|
+
export const PACKAGE = "@saltpub/agent-autoloop";
|
|
8
|
+
export function npm(args) {
|
|
9
|
+
const [program, rest] = commandLine(["npm", ...args]);
|
|
10
|
+
const done = spawnSync(program, rest, { encoding: "utf8", windowsHide: true });
|
|
11
|
+
if (done.status !== 0)
|
|
12
|
+
throw new Error(`npm ${args[0]} 没成功:${done.stderr?.trim() || done.error?.message}`);
|
|
13
|
+
return done.stdout.trim();
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Where npm put these files, if it did: `<prefix>/node_modules/@scope/name` on Windows, and
|
|
17
|
+
* `<prefix>/lib/node_modules/@scope/name` elsewhere, whatever prefix was configured. A copy unpacked anywhere else
|
|
18
|
+
* returns null, because npm knows nothing about it.
|
|
19
|
+
*/
|
|
20
|
+
export function npmPrefix(root) {
|
|
21
|
+
const parts = path.resolve(root).split(path.sep);
|
|
22
|
+
if (parts.slice(-3).join(path.sep) !== ["node_modules", ...PACKAGE.split("/")].join(path.sep))
|
|
23
|
+
return null;
|
|
24
|
+
const base = parts.slice(0, -3).join(path.sep) || path.sep;
|
|
25
|
+
if (process.platform !== "win32" && path.basename(base) !== "lib")
|
|
26
|
+
return null;
|
|
27
|
+
return process.platform === "win32" ? base : path.dirname(base);
|
|
28
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
// A plugin in this install's folder wins over one that ships.
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { pathToFileURL } from "node:url";
|
|
13
|
+
import { HOME } from "./home.js";
|
|
14
|
+
import { BUILTINS, COMPILED } from "./program.js";
|
|
15
|
+
export async function loadPlugin(name, kind) {
|
|
16
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name))
|
|
17
|
+
throw new Error(`插件名字不正确:${name}`);
|
|
18
|
+
// A plugin of the user's is .ts; npm ships the built-ins compiled.
|
|
19
|
+
const file = [
|
|
20
|
+
join(HOME, "plugins", name, `${kind}.ts`),
|
|
21
|
+
join(BUILTINS, name, `${kind}${COMPILED ? ".js" : ".ts"}`),
|
|
22
|
+
].find(existsSync);
|
|
23
|
+
if (!file)
|
|
24
|
+
throw new Error(`没有 ${name} 的插件(plugins/${name}/${kind}.ts)`);
|
|
25
|
+
return (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href))).default;
|
|
26
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Where this copy lives: a checkout runs its .ts sources, an npm install the compiled .js under dist/. Anything that starts
|
|
2
|
+
// another part of the program asks here, so both layouts name files that exist.
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
const HERE = import.meta.dirname;
|
|
5
|
+
/** npm gets the build, never the sources. */
|
|
6
|
+
export const COMPILED = path.extname(import.meta.filename) === ".js";
|
|
7
|
+
/** The folder with package.json: two levels above dist/host, one above host in a checkout. */
|
|
8
|
+
export const ROOT = COMPILED ? path.dirname(path.dirname(HERE)) : path.dirname(HERE);
|
|
9
|
+
/** What `agent-autoloop` runs: the compiled entry when installed, the source entry in a checkout. */
|
|
10
|
+
export const ENTRY = path.join(ROOT, COMPILED ? "dist/bin/agent-autoloop.js" : "bin/agent-autoloop.ts");
|
|
11
|
+
/** A script that another process runs, next to the module that starts it, with this copy's extension. */
|
|
12
|
+
export const sibling = (directory, name) => path.join(directory, COMPILED ? name.replace(/\.ts$/, ".js") : name);
|
|
13
|
+
/** Built-in plugins: compiled under dist/ when installed. */
|
|
14
|
+
export const BUILTINS = path.join(ROOT, COMPILED ? "dist/plugins" : "plugins");
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The hub on this machine: its database, the view kept from the log, the rules file, and one way to apply an input.
|
|
2
|
+
// Importing this opens them all, which is why the checks that must survive a bad rules file import it late.
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { DatabaseSync } from "node:sqlite";
|
|
7
|
+
import { HOME, RULES_FILE } from "./home.js";
|
|
8
|
+
import { privateDirectory } from "./files.js";
|
|
9
|
+
import { COMPILED } from "./program.js";
|
|
10
|
+
import { skippedOf, stateOf as state, viewStatements } from "./state.js";
|
|
11
|
+
import { cardHash, digest, whose as keyHolder } from "../kernel/credentials.js";
|
|
12
|
+
import { decide } from "../kernel/decide.js";
|
|
13
|
+
import { NotFound } from "../kernel/errors.js";
|
|
14
|
+
import { initialize, rows, statement } from "../kernel/evolve.js";
|
|
15
|
+
import * as query from "../kernel/query.js";
|
|
16
|
+
import { commitLatest, openView } from "../kernel/store.js";
|
|
17
|
+
import { parseRules as checkRules, RulesError } from "../protocol/rules.js";
|
|
18
|
+
privateDirectory(HOME);
|
|
19
|
+
const masterKeyFile = join(HOME, "master.key");
|
|
20
|
+
if (!existsSync(masterKeyFile)) {
|
|
21
|
+
writeFileSync(masterKeyFile, randomBytes(32).toString("base64url"), { mode: 0o600, flag: "wx" });
|
|
22
|
+
}
|
|
23
|
+
const masterKey = readFileSync(masterKeyFile, "utf8").trim();
|
|
24
|
+
// An empty or cut-short key would still sign links, and card links derive from what channels see. Replacing it would
|
|
25
|
+
// void every link and token, so that is left to the owner.
|
|
26
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(masterKey)) {
|
|
27
|
+
throw new Error(`${masterKeyFile} 坏了(应该是 43 个字符),中台不启动。从备份恢复这个文件;没有备份就删掉它,` +
|
|
28
|
+
"重启会生成新的,但已经发出的卡片链接和正在跑的轮次会失效。");
|
|
29
|
+
}
|
|
30
|
+
export const environment = {
|
|
31
|
+
secret: masterKey,
|
|
32
|
+
publicUrl: process.env.AGENT_AUTOLOOP_PUBLIC_URL ?? "",
|
|
33
|
+
};
|
|
34
|
+
export const db = new DatabaseSync(join(HOME, "hub.db"));
|
|
35
|
+
db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;");
|
|
36
|
+
db.function("card_hash", { deterministic: true }, (id, at) => cardHash(environment, id, at));
|
|
37
|
+
initialize(db);
|
|
38
|
+
// Other processes must see either the old views or the new ones, never the gap between DROP and CREATE.
|
|
39
|
+
db.exec(`BEGIN IMMEDIATE; ${viewStatements.join(";")}; COMMIT`);
|
|
40
|
+
const CARD_HASH_INDEX = "CREATE INDEX IF NOT EXISTS projection_card_hash ON projections(card_hash(json_extract(data,'$.id'),json_extract(data,'$.created_at'))) WHERE collection='cards'";
|
|
41
|
+
// The persisted projection is expendable; the log alone rebuilds it, which an upgrade has to wait for. So only the files that
|
|
42
|
+
// decide what's stored count here, whole, since what they do is spread across helpers and constants. The views above are
|
|
43
|
+
// made anew at every start and need no rebuild.
|
|
44
|
+
const format = digest([`../kernel/evolve${COMPILED ? ".js" : ".ts"}`, `../kernel/credentials${COMPILED ? ".js" : ".ts"}`]
|
|
45
|
+
.map((file) => readFileSync(new URL(file, import.meta.url), "utf8"))
|
|
46
|
+
.join("\n") +
|
|
47
|
+
CARD_HASH_INDEX +
|
|
48
|
+
digest(environment.secret));
|
|
49
|
+
let current = openView(db, format);
|
|
50
|
+
db.exec(CARD_HASH_INDEX);
|
|
51
|
+
export const all = (sql, params = []) => db
|
|
52
|
+
.prepare(sql)
|
|
53
|
+
.all(...params)
|
|
54
|
+
.map((row) => ({ ...row }));
|
|
55
|
+
export const one = (sql, params = []) => {
|
|
56
|
+
const row = db.prepare(sql).get(...params);
|
|
57
|
+
return row ? { ...row } : undefined;
|
|
58
|
+
};
|
|
59
|
+
export function getView() {
|
|
60
|
+
current = openView(db, format);
|
|
61
|
+
return current;
|
|
62
|
+
}
|
|
63
|
+
const listeners = new Set();
|
|
64
|
+
export const onChange = (listener) => {
|
|
65
|
+
listeners.add(listener);
|
|
66
|
+
return () => listeners.delete(listener);
|
|
67
|
+
};
|
|
68
|
+
export function execute(type, args, now = Date.now()) {
|
|
69
|
+
let facts = [];
|
|
70
|
+
let value;
|
|
71
|
+
current = commitLatest(db, format, (latest) => {
|
|
72
|
+
({ facts, value } = decide(latest, { type, args }, now, environment));
|
|
73
|
+
return facts;
|
|
74
|
+
});
|
|
75
|
+
if (facts.length)
|
|
76
|
+
for (const listener of listeners)
|
|
77
|
+
listener(type, facts);
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
export const parseRules = (json, now = Date.now()) => checkRules(json, now, Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
81
|
+
export let rules = query.configuration(current);
|
|
82
|
+
export function reloadRules(file = RULES_FILE) {
|
|
83
|
+
let text;
|
|
84
|
+
try {
|
|
85
|
+
text = readFileSync(file, "utf8");
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
return { problem: unreadable(file, error) };
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
const next = parseRules(text);
|
|
92
|
+
const differs = JSON.stringify(next) !== JSON.stringify(query.configuration(getView()));
|
|
93
|
+
const reportedBroken = (card) => card.key.startsWith("rules:") && card.state === "open";
|
|
94
|
+
if (differs || rows(current, "cards", { state: "open" }).some(reportedBroken))
|
|
95
|
+
execute("rules", [next]);
|
|
96
|
+
rules = next;
|
|
97
|
+
return {};
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof RulesError)
|
|
101
|
+
return { problem: error.message };
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function unreadable(file, error) {
|
|
106
|
+
if (error.code === "ENOENT")
|
|
107
|
+
return `找不到 ${file},被删掉或移走了?放回去就会接着用`;
|
|
108
|
+
if (error.code === "EACCES" || error.code === "EPERM")
|
|
109
|
+
return `没有权限读 ${file},改回能读的权限就会接着用`;
|
|
110
|
+
return `读不到 ${file}:${error.code ?? error.message}`;
|
|
111
|
+
}
|
|
112
|
+
const initial = reloadRules();
|
|
113
|
+
if (!rules)
|
|
114
|
+
throw new Error(initial.problem ?? "缺少规则");
|
|
115
|
+
let toldOf;
|
|
116
|
+
export function tick(now = Date.now()) {
|
|
117
|
+
const { problem } = reloadRules();
|
|
118
|
+
// A file still gone or still wrong is a problem at every tick, and an owner who closed the card has heard.
|
|
119
|
+
if (problem && problem !== toldOf)
|
|
120
|
+
execute("rulesError", [problem], now);
|
|
121
|
+
toldOf = problem;
|
|
122
|
+
execute("tick", [], now);
|
|
123
|
+
}
|
|
124
|
+
export function cardByToken(token) {
|
|
125
|
+
const row = statement(db, "SELECT data FROM projections WHERE collection='cards' AND card_hash(json_extract(data,'$.id'),json_extract(data,'$.created_at'))=?").get(digest(token));
|
|
126
|
+
return row ? JSON.parse(String(row.data)) : undefined;
|
|
127
|
+
}
|
|
128
|
+
export const view = (card, ref = null, links = false) => query.cardView(card, environment, ref, links);
|
|
129
|
+
/** Runs a switch would cut short: queued, running, or whose program hasn't been heard from since it was given one. */
|
|
130
|
+
export const activeRuns = () => Number(one("SELECT count(*) AS n FROM runs WHERE state IN ('queued', 'claimed', 'unknown')")?.n ?? 0);
|
|
131
|
+
export const unrouted = (limit = 20) => query.unrouted(getView(), limit);
|
|
132
|
+
export const skipped = (rule, since, everything = false) => skippedOf(all, rule, since, everything);
|
|
133
|
+
/** Read in one snapshot: its seq is where the log stood for all of it, for a client to go on in /v1/stream from. */
|
|
134
|
+
export function stateOf(now = Date.now(), before) {
|
|
135
|
+
db.exec("BEGIN");
|
|
136
|
+
try {
|
|
137
|
+
const latest = getView();
|
|
138
|
+
return { seq: latest.seq, ...state(now, before, query.configuration(latest), { all, view, unrouted }) };
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
db.exec("COMMIT");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export const keepKeyHash = (kind, name, hash, now = Date.now()) => execute("key", [kind, name, hash], now);
|
|
145
|
+
export function addKey(kind, name, now = Date.now()) {
|
|
146
|
+
const key = randomBytes(32).toString("base64url");
|
|
147
|
+
keepKeyHash(kind, name, digest(key), now);
|
|
148
|
+
return key;
|
|
149
|
+
}
|
|
150
|
+
export const listKeys = () => all("SELECT kind,name,created_at FROM keys ORDER BY kind,name");
|
|
151
|
+
export const whose = (kind, key) => keyHolder(getView(), kind, key);
|
|
152
|
+
export const logAfter = (after = 0, limit = -1) => db
|
|
153
|
+
.prepare("SELECT fact FROM facts WHERE seq > ? ORDER BY seq LIMIT ?")
|
|
154
|
+
.all(after, limit)
|
|
155
|
+
.map((row) => query.safeFact(JSON.parse(String(row.fact))));
|
|
156
|
+
/** The part of the log that explains one run: its events, cards and receipts, and the rules it ran under. */
|
|
157
|
+
export function why(id) {
|
|
158
|
+
const latest = getView();
|
|
159
|
+
if (!latest.get("runs", id))
|
|
160
|
+
throw new NotFound("没有这一轮");
|
|
161
|
+
const events = query.eventsOf(latest, id).map((event) => event.id);
|
|
162
|
+
const cards = [...rows(latest, "cards", { run_id: id }), ...rows(latest, "cards", { answer_event: events })];
|
|
163
|
+
const sequences = new Set();
|
|
164
|
+
const include = (table, key) => {
|
|
165
|
+
for (const row of statement(db, "SELECT seq FROM projection_refs WHERE collection=? AND key=?").all(table, String(key)))
|
|
166
|
+
sequences.add(Number(row.seq));
|
|
167
|
+
};
|
|
168
|
+
include("runs", id);
|
|
169
|
+
const read = (seq) => JSON.parse(String(statement(db, "SELECT fact FROM facts WHERE seq=?").get(seq).fact));
|
|
170
|
+
for (const seq of [...sequences])
|
|
171
|
+
for (const change of read(seq).changes)
|
|
172
|
+
if (change.table === "runs" && change.key === String(id) && change.row?.rules_version)
|
|
173
|
+
sequences.add(change.row.rules_version);
|
|
174
|
+
for (const event of events)
|
|
175
|
+
include("events", event);
|
|
176
|
+
for (const card of cards)
|
|
177
|
+
include("cards", card.id);
|
|
178
|
+
return [...sequences].sort((a, b) => a - b).map((seq) => query.safeFact(read(seq)));
|
|
179
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// What the kernel's doors need from this machine: the clock, a timer for the next deadline, long polls to wake, the
|
|
2
|
+
// rules file to watch, the log as a stream and the webhook plugins.
|
|
3
|
+
import { realpathSync, watch } from "node:fs";
|
|
4
|
+
import { basename, dirname } from "node:path";
|
|
5
|
+
import { RULES_FILE } from "./home.js";
|
|
6
|
+
import { loadPlugin } from "./plugins.js";
|
|
7
|
+
import * as hub from "./runtime.js";
|
|
8
|
+
import { AuthError, NotFound } from "../kernel/errors.js";
|
|
9
|
+
import { createHandler } from "../kernel/http.js";
|
|
10
|
+
/** Past this setTimeout fires at once. */
|
|
11
|
+
const LONGEST_TIMER = 2147483647;
|
|
12
|
+
const TICK_RETRY = 5_000;
|
|
13
|
+
function logStream(after, signal, key) {
|
|
14
|
+
let position = after;
|
|
15
|
+
let unsubscribe = () => { };
|
|
16
|
+
let stop = () => { };
|
|
17
|
+
const detach = () => {
|
|
18
|
+
unsubscribe();
|
|
19
|
+
signal.removeEventListener("abort", stop);
|
|
20
|
+
};
|
|
21
|
+
let send = () => { };
|
|
22
|
+
let stopped = false;
|
|
23
|
+
return new ReadableStream({
|
|
24
|
+
start(controller) {
|
|
25
|
+
stop = () => {
|
|
26
|
+
if (stopped)
|
|
27
|
+
return;
|
|
28
|
+
stopped = true;
|
|
29
|
+
detach();
|
|
30
|
+
controller.close();
|
|
31
|
+
};
|
|
32
|
+
send = () => {
|
|
33
|
+
if (stopped)
|
|
34
|
+
return;
|
|
35
|
+
if (!hub.whose("owner", key))
|
|
36
|
+
return stop();
|
|
37
|
+
if (controller.desiredSize <= 0)
|
|
38
|
+
return;
|
|
39
|
+
for (const fact of hub.logAfter(position, 1)) {
|
|
40
|
+
position = fact.seq;
|
|
41
|
+
const message = `id: ${fact.seq}\nevent: fact\ndata: ${JSON.stringify(fact)}\n\n`;
|
|
42
|
+
controller.enqueue(new TextEncoder().encode(message));
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
unsubscribe = hub.onChange(send);
|
|
46
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
47
|
+
if (signal.aborted)
|
|
48
|
+
stop();
|
|
49
|
+
},
|
|
50
|
+
pull() {
|
|
51
|
+
send();
|
|
52
|
+
},
|
|
53
|
+
cancel() {
|
|
54
|
+
stopped = true;
|
|
55
|
+
detach();
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
async function adaptWebhook(source, headers, body) {
|
|
60
|
+
const adapter = hub.rules.sources[source]?.adapter;
|
|
61
|
+
if (!adapter || !/^[a-z][a-z0-9-]*$/.test(adapter))
|
|
62
|
+
throw new NotFound("这个来源不收 Webhook");
|
|
63
|
+
const translate = await loadPlugin(adapter, "source");
|
|
64
|
+
const secret = process.env[`AGENT_AUTOLOOP_SECRET_${source.toUpperCase().replaceAll("-", "_")}`] ?? "";
|
|
65
|
+
try {
|
|
66
|
+
const events = translate({ headers: Object.fromEntries(headers), body, secret });
|
|
67
|
+
return Array.isArray(events) ? events : [];
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
throw new AuthError("验签没过");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function makeHandler(commit = "dev") {
|
|
74
|
+
let timer;
|
|
75
|
+
let closed = false;
|
|
76
|
+
let retryAt;
|
|
77
|
+
const waiting = new Set();
|
|
78
|
+
const wake = () => {
|
|
79
|
+
for (const waiter of [...waiting])
|
|
80
|
+
waiter.done();
|
|
81
|
+
};
|
|
82
|
+
const fire = () => {
|
|
83
|
+
try {
|
|
84
|
+
hub.tick();
|
|
85
|
+
retryAt = undefined;
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// Another process holding the database too long, say. Nobody is there to catch it, and what it brought is still due.
|
|
89
|
+
console.error(error);
|
|
90
|
+
retryAt = Date.now() + TICK_RETRY;
|
|
91
|
+
}
|
|
92
|
+
wake();
|
|
93
|
+
arm();
|
|
94
|
+
};
|
|
95
|
+
const arm = () => {
|
|
96
|
+
clearTimeout(timer);
|
|
97
|
+
if (closed)
|
|
98
|
+
return;
|
|
99
|
+
const due = hub.one("SELECT MIN(json_extract(data, '$.at')) AS at FROM projections WHERE collection='due'");
|
|
100
|
+
// Whatever the failed tick left is overdue, so it would go at once; and nothing else coming along may lose the retry.
|
|
101
|
+
const next = retryAt ?? Math.min(due?.at ?? Infinity, ...[...waiting].map((waiter) => waiter.until));
|
|
102
|
+
if (!Number.isFinite(next))
|
|
103
|
+
return;
|
|
104
|
+
timer = setTimeout(fire, Math.max(0, Math.min(LONGEST_TIMER, next - Date.now())));
|
|
105
|
+
};
|
|
106
|
+
const unlisten = hub.onChange((type, facts) => {
|
|
107
|
+
// Being seen wakes nobody, unless it changed a card.
|
|
108
|
+
const justSeen = type === "heartbeat" || type === "channelSeen";
|
|
109
|
+
if (!justSeen || facts.some((fact) => fact.changes.some((change) => change.table === "cards")))
|
|
110
|
+
wake();
|
|
111
|
+
arm();
|
|
112
|
+
});
|
|
113
|
+
// libuv 1.52 (Node 24.16+) on Windows asserts and exits on the first change in a folder named through an 8.3 short name.
|
|
114
|
+
const watcher = watch(realpathSync.native(dirname(RULES_FILE)), (_event, file) => {
|
|
115
|
+
if (file === basename(RULES_FILE))
|
|
116
|
+
fire();
|
|
117
|
+
});
|
|
118
|
+
const handle = createHandler({
|
|
119
|
+
commit,
|
|
120
|
+
now: Date.now,
|
|
121
|
+
view: hub.getView,
|
|
122
|
+
environment: hub.environment,
|
|
123
|
+
dispatch: hub.execute,
|
|
124
|
+
state: hub.stateOf,
|
|
125
|
+
skipped: hub.skipped,
|
|
126
|
+
why: hub.why,
|
|
127
|
+
card: hub.cardByToken,
|
|
128
|
+
wait(until, signal) {
|
|
129
|
+
return new Promise((resolve) => {
|
|
130
|
+
const waiter = {
|
|
131
|
+
until,
|
|
132
|
+
done() {
|
|
133
|
+
waiting.delete(waiter);
|
|
134
|
+
signal.removeEventListener("abort", waiter.done);
|
|
135
|
+
resolve();
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
waiting.add(waiter);
|
|
139
|
+
signal.addEventListener("abort", waiter.done, { once: true });
|
|
140
|
+
if (signal.aborted)
|
|
141
|
+
waiter.done();
|
|
142
|
+
arm();
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
stream: logStream,
|
|
146
|
+
adapt: adaptWebhook,
|
|
147
|
+
});
|
|
148
|
+
fire();
|
|
149
|
+
return {
|
|
150
|
+
handle,
|
|
151
|
+
close() {
|
|
152
|
+
closed = true;
|
|
153
|
+
clearTimeout(timer);
|
|
154
|
+
watcher.close();
|
|
155
|
+
unlisten();
|
|
156
|
+
wake();
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|