@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.
- package/CHANGELOG.md +19 -0
- package/INSTALL.md +118 -0
- package/LICENSE +21 -0
- package/README.en.md +264 -0
- package/README.md +260 -2
- package/SECURITY.md +48 -0
- package/dist/bin/agent-autoloop.js +2 -0
- package/dist/cli/backup.js +144 -0
- package/dist/cli/explain.js +84 -0
- package/dist/cli/main.js +1016 -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 +304 -0
- package/dist/cli/try.js +6 -0
- package/dist/cli/uninstall.js +84 -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 +43 -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 +55 -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,325 @@
|
|
|
1
|
+
// Login services: launchd on macOS, systemd on Linux, Task Scheduler on Windows. Each starts the hub at login and again if
|
|
2
|
+
// it stops.
|
|
3
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { HOME } from "./home.js";
|
|
9
|
+
import { ENTRY, sibling } from "./program.js";
|
|
10
|
+
import { launcherFile, managedAt } from "./update.js";
|
|
11
|
+
import { stablePath } from "./node-path.js";
|
|
12
|
+
import { powershell, processCommandSync, psQuote } from "./command.js";
|
|
13
|
+
/** A managed install starts through the fixed launcher, which is what can switch versions. */
|
|
14
|
+
const program = () => (managedAt(HOME) ? launcherFile(HOME) : ENTRY);
|
|
15
|
+
/** The launcher takes no arguments; every other program is started with its command. */
|
|
16
|
+
const startsHub = (target) => path.resolve(target) !== path.resolve(launcherFile(HOME));
|
|
17
|
+
/** Another install on this machine (another AGENT_AUTOLOOP_HOME) has a service of its own. */
|
|
18
|
+
const label = () => HOME === path.join(homedir(), ".agent-autoloop")
|
|
19
|
+
? "agent-autoloop"
|
|
20
|
+
: `agent-autoloop-${createHash("sha256").update(HOME).digest("hex").slice(0, 8)}`;
|
|
21
|
+
const plistFile = () => path.join(homedir(), "Library/LaunchAgents", `${label()}.plist`);
|
|
22
|
+
const unitFile = () => path.join(homedir(), ".config/systemd/user", `${label()}.service`);
|
|
23
|
+
const BACKGROUND = sibling(import.meta.dirname, "background.ts");
|
|
24
|
+
const LAUNCHER = path.join(import.meta.dirname, "background-launcher.js");
|
|
25
|
+
const windowsArgument = (word) => `"${word.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`;
|
|
26
|
+
const task = () => `Get-ScheduledTask | Where-Object { $_.TaskName -eq ${psQuote(label())} -and $_.TaskPath -eq '\\' }`;
|
|
27
|
+
/** What the login task starts. Started straight from it, node gets a console window on the desktop, and the task doesn't
|
|
28
|
+
* start it again when it exits. wscript has no console: background-launcher.js starts the hub hidden and again when it stops. */
|
|
29
|
+
export function windowsLauncher() {
|
|
30
|
+
return {
|
|
31
|
+
program: path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "wscript.exe"),
|
|
32
|
+
args: ["//B", "//Nologo", "//E:JScript"]
|
|
33
|
+
.concat([LAUNCHER, process.execPath, "--disable-warning=ExperimentalWarning", BACKGROUND, HOME].map(windowsArgument))
|
|
34
|
+
.join(" "),
|
|
35
|
+
directory: HOME,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** PowerShell that puts a shortcut starting the same thing in `folder` (a PowerShell expression). */
|
|
39
|
+
export function startupShortcut(folder = "[Environment]::GetFolderPath('Startup')") {
|
|
40
|
+
const { program, args, directory } = windowsLauncher();
|
|
41
|
+
return (`$s = (New-Object -ComObject WScript.Shell).CreateShortcut((Join-Path (${folder}) ${psQuote(`${label()}.lnk`)})); ` +
|
|
42
|
+
`$s.TargetPath = ${psQuote(program)}; $s.Arguments = ${psQuote(args)}; $s.WorkingDirectory = ${psQuote(directory)}; $s.Save()`);
|
|
43
|
+
}
|
|
44
|
+
/** For an account that can't, or shouldn't, have the login task: the desktop starts it, with the desktop's rights. */
|
|
45
|
+
export const startupInstead = () => "可以改用「启动」文件夹:在 PowerShell 里运行下面这行,以后登录时由桌面以普通权限拉起中台,退出后照样自动重启," +
|
|
46
|
+
"现在注销再登录一次就开始跑。这样起的中台不算系统服务:doctor 会说服务没在跑;再运行 `agent-autoloop service install` 会去建登录任务," +
|
|
47
|
+
"想继续用「启动」文件夹就别运行它;更新之后注销再登录一次才用上新版。\n\n" +
|
|
48
|
+
startupShortcut();
|
|
49
|
+
function installWindowsService() {
|
|
50
|
+
const { program, args, directory } = windowsLauncher();
|
|
51
|
+
// Registering with -Force replaces the task in place, so the old one and the hub it runs are left alone until Windows
|
|
52
|
+
// has taken the new one: a registration it refuses must not leave the person with no hub.
|
|
53
|
+
try {
|
|
54
|
+
powershell(`
|
|
55
|
+
$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
|
56
|
+
$action = New-ScheduledTaskAction -Execute ${psQuote(program)} -Argument ${psQuote(args)} -WorkingDirectory ${psQuote(directory)}
|
|
57
|
+
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
|
|
58
|
+
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
|
|
59
|
+
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew
|
|
60
|
+
Register-ScheduledTask -TaskName ${psQuote(label())} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
|
|
61
|
+
`);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
// The built-in Administrator with UAC on can't make any task without elevating, however the task is written.
|
|
65
|
+
if (!String(error.stderr ?? error).includes("0x80070005"))
|
|
66
|
+
throw error;
|
|
67
|
+
throw new Error(`Windows 不让这个账号建登录任务(拒绝访问)。${startupInstead()}`);
|
|
68
|
+
}
|
|
69
|
+
// Stopping the task ends wscript, not the hub it started; that one, or one started by hand, is stopped after it.
|
|
70
|
+
powershell(`$task = ${task()}; if ($task.State -eq 'Running') { $task | Stop-ScheduledTask }`);
|
|
71
|
+
stopUp();
|
|
72
|
+
powershell(`Start-ScheduledTask -TaskName ${psQuote(label())}`);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Whether a process holds an administrator's full token while the desktop of its session doesn't: more than the person
|
|
76
|
+
* signed in has. With UAC off, or an Administrator that isn't filtered, the desktop has it too and the Startup folder
|
|
77
|
+
* gives no less. Not knowing (it ended, or isn't ours to ask about) counts as no.
|
|
78
|
+
*/
|
|
79
|
+
export function aboveDesktop(pid) {
|
|
80
|
+
return (powershell(`Add-Type @"
|
|
81
|
+
using System; using System.Diagnostics; using System.Runtime.InteropServices;
|
|
82
|
+
public static class Token {
|
|
83
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
|
|
84
|
+
[DllImport("advapi32.dll")] static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
|
|
85
|
+
[DllImport("advapi32.dll")] static extern bool GetTokenInformation(IntPtr token, int kind, out int value, int size, out int length);
|
|
86
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
87
|
+
static bool Elevated(int pid) {
|
|
88
|
+
IntPtr process = OpenProcess(0x1000, false, pid), token;
|
|
89
|
+
if (process == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();
|
|
90
|
+
try {
|
|
91
|
+
if (!OpenProcessToken(process, 0x8, out token)) throw new System.ComponentModel.Win32Exception();
|
|
92
|
+
int value, length;
|
|
93
|
+
try { if (!GetTokenInformation(token, 20, out value, 4, out length)) throw new System.ComponentModel.Win32Exception(); }
|
|
94
|
+
finally { CloseHandle(token); }
|
|
95
|
+
return value != 0;
|
|
96
|
+
} finally { CloseHandle(process); }
|
|
97
|
+
}
|
|
98
|
+
public static bool AboveDesktop(int pid) {
|
|
99
|
+
try {
|
|
100
|
+
if (!Elevated(pid)) return false;
|
|
101
|
+
int session = Process.GetProcessById(pid).SessionId;
|
|
102
|
+
foreach (Process shell in Process.GetProcessesByName("explorer"))
|
|
103
|
+
if (shell.SessionId == session) return !Elevated(shell.Id);
|
|
104
|
+
} catch {}
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
"@
|
|
109
|
+
[Token]::AboveDesktop(${pid})`) === "True");
|
|
110
|
+
}
|
|
111
|
+
const xml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
112
|
+
const systemdItem = (text, escapeDollar = false) => {
|
|
113
|
+
if (/[\u0000-\u001f\u007f]/u.test(text))
|
|
114
|
+
throw new Error("systemd unit 的值不能包含控制字符");
|
|
115
|
+
let escaped = text.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%");
|
|
116
|
+
if (escapeDollar)
|
|
117
|
+
escaped = escaped.replaceAll("$", () => "$$");
|
|
118
|
+
return `"${escaped}"`;
|
|
119
|
+
};
|
|
120
|
+
export function plist() {
|
|
121
|
+
const logs = path.join(HOME, "logs");
|
|
122
|
+
const systemPaths = ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"];
|
|
123
|
+
const executable = stablePath(process.execPath);
|
|
124
|
+
const searchPath = [path.dirname(executable), ...systemPaths].join(":");
|
|
125
|
+
const target = program();
|
|
126
|
+
const command = [executable, "--disable-warning=ExperimentalWarning", target, ...(startsHub(target) ? ["up"] : [])];
|
|
127
|
+
const programArguments = command.map((part) => `<string>${xml(part)}</string>`).join("");
|
|
128
|
+
const homeEntry = `<key>AGENT_AUTOLOOP_HOME</key><string>${xml(HOME)}</string>`;
|
|
129
|
+
const pathEntry = `<key>PATH</key><string>${xml(searchPath)}</string>`;
|
|
130
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
131
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
132
|
+
<plist version="1.0"><dict>
|
|
133
|
+
<key>Label</key><string>${label()}</string>
|
|
134
|
+
<key>ProgramArguments</key><array>${programArguments}</array>
|
|
135
|
+
<key>EnvironmentVariables</key><dict>${homeEntry}${pathEntry}</dict>
|
|
136
|
+
<key>RunAtLoad</key><true/>
|
|
137
|
+
<key>KeepAlive</key><true/>
|
|
138
|
+
<key>ThrottleInterval</key><integer>10</integer>
|
|
139
|
+
<key>StandardOutPath</key><string>${xml(logs)}/up.log</string>
|
|
140
|
+
<key>StandardErrorPath</key><string>${xml(logs)}/up.log</string>
|
|
141
|
+
</dict></plist>
|
|
142
|
+
`;
|
|
143
|
+
}
|
|
144
|
+
export function unit(options = { home: HOME, executable: process.execPath }) {
|
|
145
|
+
const environment = systemdItem(`AGENT_AUTOLOOP_HOME=${options.home}`);
|
|
146
|
+
const target = options.program ?? program();
|
|
147
|
+
const command = [
|
|
148
|
+
options.executable,
|
|
149
|
+
"--disable-warning=ExperimentalWarning",
|
|
150
|
+
target,
|
|
151
|
+
...(startsHub(target) ? ["up"] : []),
|
|
152
|
+
]
|
|
153
|
+
.map((part) => systemdItem(part, true))
|
|
154
|
+
.join(" ");
|
|
155
|
+
return `[Unit]
|
|
156
|
+
Description=Agent 自动化中台
|
|
157
|
+
|
|
158
|
+
[Service]
|
|
159
|
+
Environment=${environment}
|
|
160
|
+
ExecStart=${command}
|
|
161
|
+
Restart=always
|
|
162
|
+
RestartSec=10
|
|
163
|
+
|
|
164
|
+
[Install]
|
|
165
|
+
WantedBy=default.target
|
|
166
|
+
`;
|
|
167
|
+
}
|
|
168
|
+
const domain = () => `gui/${process.getuid()}`;
|
|
169
|
+
const launchdHasIt = () => spawnSync("launchctl", ["print", `${domain()}/${label()}`], { stdio: "ignore" }).status === 0;
|
|
170
|
+
const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
171
|
+
export function installService() {
|
|
172
|
+
mkdirSync(path.join(HOME, "logs"), { recursive: true, mode: 0o700 });
|
|
173
|
+
if (process.platform === "win32")
|
|
174
|
+
return installWindowsService();
|
|
175
|
+
if (process.platform === "darwin") {
|
|
176
|
+
mkdirSync(path.dirname(plistFile()), { recursive: true });
|
|
177
|
+
writeFileSync(plistFile(), plist());
|
|
178
|
+
// launchd refuses to load a plist others can write, as an unhelpful "Bootstrap failed: 5"; and rewriting one a
|
|
179
|
+
// umask-0 install left world-writable keeps its mode, so the mode is set on every install.
|
|
180
|
+
chmodSync(plistFile(), 0o644);
|
|
181
|
+
spawnSync("launchctl", ["bootout", `${domain()}/${label()}`], { stdio: "ignore" });
|
|
182
|
+
// bootout returns before the old one is gone; loading before that fails and leaves none.
|
|
183
|
+
for (let tries = 0; tries < 100 && launchdHasIt(); tries++)
|
|
184
|
+
pause(100);
|
|
185
|
+
execFileSync("launchctl", ["bootstrap", domain(), plistFile()]);
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
mkdirSync(path.dirname(unitFile()), { recursive: true });
|
|
189
|
+
writeFileSync(unitFile(), unit());
|
|
190
|
+
execFileSync("systemctl", ["--user", "daemon-reload"]);
|
|
191
|
+
execFileSync("systemctl", ["--user", "enable", "--now", label()]);
|
|
192
|
+
execFileSync("systemctl", ["--user", "restart", label()]);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
export function removeService() {
|
|
196
|
+
if (process.platform === "win32") {
|
|
197
|
+
const removed = powershell(`$task = ${task()}; if ($task -and $task.Actions.Arguments.Contains(${psQuote(windowsArgument(BACKGROUND))})) {
|
|
198
|
+
$task | Stop-ScheduledTask
|
|
199
|
+
$task | Unregister-ScheduledTask -Confirm:$false
|
|
200
|
+
'removed'
|
|
201
|
+
}`);
|
|
202
|
+
// Stopping the task ends wscript, not the hub it started, and nothing starts that again now.
|
|
203
|
+
if (removed === "removed")
|
|
204
|
+
stopUp();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const file = process.platform === "darwin" ? plistFile() : unitFile();
|
|
208
|
+
if (!existsSync(file))
|
|
209
|
+
return;
|
|
210
|
+
const service = readFileSync(file, "utf8");
|
|
211
|
+
// Either program counts: an install updated from before the launcher still owns its unit.
|
|
212
|
+
const owns = process.platform === "darwin"
|
|
213
|
+
? (target) => service.includes(xml(target))
|
|
214
|
+
: (target) => service.includes(target);
|
|
215
|
+
const ownsService = owns(program()) || owns(ENTRY);
|
|
216
|
+
if (!ownsService)
|
|
217
|
+
return;
|
|
218
|
+
if (process.platform === "darwin") {
|
|
219
|
+
spawnSync("launchctl", ["bootout", `${domain()}/${label()}`], { stdio: "ignore" });
|
|
220
|
+
rmSync(plistFile(), { force: true });
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
spawnSync("systemctl", ["--user", "disable", "--now", label()], { stdio: "ignore" });
|
|
224
|
+
rmSync(unitFile(), { force: true });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** The process that left its number in up.pid, if it still is that process: the number may be someone else's by now. */
|
|
228
|
+
export function runningUp() {
|
|
229
|
+
const file = path.join(HOME, "up.pid");
|
|
230
|
+
if (!existsSync(file))
|
|
231
|
+
return null;
|
|
232
|
+
const pid = readFileSync(file, "utf8").trim();
|
|
233
|
+
let command = "";
|
|
234
|
+
try {
|
|
235
|
+
command = processCommandSync(Number(pid));
|
|
236
|
+
}
|
|
237
|
+
catch { }
|
|
238
|
+
return /agent-autoloop(\.(ts|js))?"? up\b/.test(command) ? Number(pid) : null;
|
|
239
|
+
}
|
|
240
|
+
/** The launcher's own number, while it still is that process. A hub started by hand has no launcher. */
|
|
241
|
+
function runningLauncher() {
|
|
242
|
+
try {
|
|
243
|
+
const file = path.join(HOME, "update", "launcher.pid");
|
|
244
|
+
if (!existsSync(file))
|
|
245
|
+
return null;
|
|
246
|
+
const pid = JSON.parse(readFileSync(file, "utf8")).pid;
|
|
247
|
+
if (typeof pid !== "number")
|
|
248
|
+
return null;
|
|
249
|
+
return /launcher\.mjs/.test(processCommandSync(pid)) ? pid : null;
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** Stopping a service returns before its process is gone, and one started by hand has no service to stop it. */
|
|
256
|
+
export function stopUp() {
|
|
257
|
+
// The launcher is stopped first: it forwards the signal and doesn't start the hub again.
|
|
258
|
+
const launcher = runningLauncher();
|
|
259
|
+
if (launcher !== null) {
|
|
260
|
+
try {
|
|
261
|
+
process.kill(launcher, "SIGTERM");
|
|
262
|
+
}
|
|
263
|
+
catch { }
|
|
264
|
+
for (let tries = 0; tries < 50 && runningLauncher() !== null; tries++)
|
|
265
|
+
pause(100);
|
|
266
|
+
}
|
|
267
|
+
const pid = runningUp();
|
|
268
|
+
if (pid === null)
|
|
269
|
+
return;
|
|
270
|
+
try {
|
|
271
|
+
process.kill(pid, "SIGTERM");
|
|
272
|
+
}
|
|
273
|
+
catch { }
|
|
274
|
+
for (let tries = 0; tries < 50 && runningUp() !== null; tries++)
|
|
275
|
+
pause(100);
|
|
276
|
+
}
|
|
277
|
+
/** The service this program installs and can restart. */
|
|
278
|
+
export function serviceRunning() {
|
|
279
|
+
if (process.platform === "win32")
|
|
280
|
+
return powershell(`$task = ${task()}; [string]($task -and $task.State -eq 'Running')`) === "True";
|
|
281
|
+
if (process.platform === "darwin")
|
|
282
|
+
return existsSync(plistFile()) && launchdHasIt();
|
|
283
|
+
return spawnSync("systemctl", ["--user", "is-active", "--quiet", label()], { stdio: "ignore" }).status === 0;
|
|
284
|
+
}
|
|
285
|
+
/** Whether its manager has the service going or starting: one stopped by hand, or no manager at all, isn't waited for. */
|
|
286
|
+
function serviceStarting() {
|
|
287
|
+
if (process.platform !== "linux")
|
|
288
|
+
return serviceRunning();
|
|
289
|
+
const state = spawnSync("systemctl", ["--user", "is-active", label()], { encoding: "utf8" }).stdout?.trim();
|
|
290
|
+
return state === "active" || state === "activating" || state === "reloading";
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* A manager says it has started the hub before the hub can answer, and whatever runs next finds nothing there. Waits for
|
|
294
|
+
* it while its manager has it: true once it answers, false if it doesn't in time, null when there's nothing to wait for.
|
|
295
|
+
*/
|
|
296
|
+
export async function untilAnswering(url, patience = 20_000) {
|
|
297
|
+
if (!serviceStarting())
|
|
298
|
+
return null;
|
|
299
|
+
const end = Date.now() + patience;
|
|
300
|
+
for (;;) {
|
|
301
|
+
const answered = await fetch(`${url.replace(/\/$/, "")}/healthz`, { signal: AbortSignal.timeout(2_000) }).then((response) => response.ok, () => false);
|
|
302
|
+
if (answered)
|
|
303
|
+
return true;
|
|
304
|
+
if (Date.now() > end)
|
|
305
|
+
return false;
|
|
306
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/** Where the service's own output goes. */
|
|
310
|
+
export const serviceLogs = () => process.platform === "linux" ? `journalctl --user -u ${label()}` : path.join(HOME, "logs", "up.log");
|
|
311
|
+
/** The name of a system-level unit running this, as a server run by root might have. It's its owner's to restart. */
|
|
312
|
+
export function systemUnit() {
|
|
313
|
+
if (process.platform === "win32")
|
|
314
|
+
return null;
|
|
315
|
+
if (process.platform === "darwin")
|
|
316
|
+
return null;
|
|
317
|
+
return spawnSync("systemctl", ["is-active", "--quiet", label()], { stdio: "ignore" }).status === 0 ? label() : null;
|
|
318
|
+
}
|
|
319
|
+
/** New code counts once what's running starts again. What can't be restarted from here is said back, for the owner. */
|
|
320
|
+
export function restartService() {
|
|
321
|
+
if (serviceRunning())
|
|
322
|
+
return void installService();
|
|
323
|
+
const name = systemUnit();
|
|
324
|
+
return name ? `这台电脑用的是系统级服务,运行 systemctl restart ${name} 才会用上新版。` : undefined;
|
|
325
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { describeCron, dayStart, nextRun, parseCron } from "../kernel/cron.js";
|
|
2
|
+
import { SEEN_EVERY } from "../kernel/due.js";
|
|
3
|
+
import { iso } from "../kernel/evolve.js";
|
|
4
|
+
import { cronOf, eventRule, SCHEDULE } from "../kernel/rules.js";
|
|
5
|
+
/** The columns of the read-only SQL views over the projections, which the queries here read. */
|
|
6
|
+
const VIEWS = {
|
|
7
|
+
events: "id source key type subject summary detail link routed paused received_at",
|
|
8
|
+
runs: "id rule agent grp lane state attempts not_before claim last_result cancel_at resume session link created_at " +
|
|
9
|
+
"claimed_at seen_at finished_at manual summary error usage",
|
|
10
|
+
run_events: "run_id event_id",
|
|
11
|
+
cards: "id key kind title text options recommend about state fyi quiet choice answer by result rule lane grp source " +
|
|
12
|
+
"agent session run_id answer_event version created_at decided_at closed_at",
|
|
13
|
+
deliveries: "card_id channel version ref tries first_try_at not_before error given_up",
|
|
14
|
+
timers: "id rule lane key source agent session about at event_id created_at",
|
|
15
|
+
schedules: "rule cron next_at skipped_at",
|
|
16
|
+
seen: "kind name seen_at",
|
|
17
|
+
keys: "kind name hash created_at",
|
|
18
|
+
pauses: "name by reason since until",
|
|
19
|
+
};
|
|
20
|
+
/** Made anew at every start, so changing them takes no rebuild and no migration. */
|
|
21
|
+
export const viewStatements = Object.entries(VIEWS).map(([table, columns]) => {
|
|
22
|
+
const selected = columns.split(" ").map((column) => `json_extract(data,'$.${column}') AS ${column}`);
|
|
23
|
+
return `DROP VIEW IF EXISTS ${table}; CREATE VIEW ${table} AS SELECT ${selected.join(",")} FROM projections WHERE collection='${table}'`;
|
|
24
|
+
});
|
|
25
|
+
/** Seen this recently counts as online: two minutes of quiet, by a stamp that can be behind by SEEN_EVERY. */
|
|
26
|
+
const ONLINE = 120_000 + SEEN_EVERY;
|
|
27
|
+
const PAGE = 60;
|
|
28
|
+
const WEEK = 7 * 86400_000;
|
|
29
|
+
const SPENDING = `SELECT COUNT(*) AS rounds,
|
|
30
|
+
COALESCE(SUM(COALESCE(json_extract(usage, '$.input'), 0) + COALESCE(json_extract(usage, '$.output'), 0)), 0) AS tokens,
|
|
31
|
+
COALESCE(SUM(json_extract(usage, '$.cached')), 0) AS cached,
|
|
32
|
+
COALESCE(SUM(json_extract(usage, '$.cost')), 0) AS cost,
|
|
33
|
+
COUNT(*) - COUNT(COALESCE(json_extract(usage, '$.input'), json_extract(usage, '$.output'))) AS missingTokens,
|
|
34
|
+
COUNT(*) - COUNT(json_extract(usage, '$.cost')) AS missingCost
|
|
35
|
+
FROM runs WHERE finished_at >= ? AND (claimed_at IS NOT NULL OR usage IS NOT NULL)`;
|
|
36
|
+
const COUNTS = `
|
|
37
|
+
SELECT rule, agent, state, COUNT(*) AS count,
|
|
38
|
+
SUM(CASE WHEN state = 'queued' AND attempts > 0 THEN 1 ELSE 0 END) AS retrying,
|
|
39
|
+
SUM(CASE WHEN state = 'done' AND finished_at >= ? THEN 1 ELSE 0 END) AS today,
|
|
40
|
+
COALESCE(SUM(json_extract(usage, '$.input')), 0) AS input,
|
|
41
|
+
COALESCE(SUM(json_extract(usage, '$.output')), 0) AS output,
|
|
42
|
+
COALESCE(SUM(json_extract(usage, '$.cost')), 0) AS cost
|
|
43
|
+
FROM runs GROUP BY rule, agent, state`;
|
|
44
|
+
// Start from this run's links; scanning events in ID order would revisit the whole history for each run.
|
|
45
|
+
const EVENTS_OF_RUN = `
|
|
46
|
+
SELECT source, type, subject, summary, link FROM run_events CROSS JOIN events ON events.id = run_events.event_id
|
|
47
|
+
WHERE run_events.run_id = ? ORDER BY events.id DESC LIMIT 20`;
|
|
48
|
+
const sum = (counted, field) => counted.reduce((total, row) => total + row[field], 0);
|
|
49
|
+
export function spendingOf(all, now, timezone) {
|
|
50
|
+
const since = (time) => all(SPENDING, [iso(time)])[0];
|
|
51
|
+
return { today: since(dayStart(now, timezone)), week: since(now - WEEK) };
|
|
52
|
+
}
|
|
53
|
+
function tally(counted) {
|
|
54
|
+
const inState = (state) => counted.reduce((total, row) => total + (row.state === state ? row.count : 0), 0);
|
|
55
|
+
return {
|
|
56
|
+
running: inState("claimed"),
|
|
57
|
+
queued: inState("queued"),
|
|
58
|
+
retrying: sum(counted, "retrying"),
|
|
59
|
+
unknown: inState("unknown"),
|
|
60
|
+
done: inState("done"),
|
|
61
|
+
doneToday: sum(counted, "today"),
|
|
62
|
+
nothing: inState("nothing"),
|
|
63
|
+
usage: { input: sum(counted, "input"), output: sum(counted, "output"), cost: sum(counted, "cost") },
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
// Events a pause kept from a rule: only those carry the field. A range on it, and +id, keep to that index instead of
|
|
67
|
+
// walking every event by id.
|
|
68
|
+
const SKIPPED = `SELECT id, source, type, subject, summary, paused, received_at FROM events
|
|
69
|
+
WHERE paused > '' ORDER BY +id DESC LIMIT 20`;
|
|
70
|
+
// The same, for one rule since its pause began, less those a replay has since handed to a run of the rule.
|
|
71
|
+
const SKIPPED_BY = `FROM events WHERE paused > '' AND received_at >= ?
|
|
72
|
+
AND EXISTS (SELECT 1 FROM json_each(paused) WHERE value = ?)
|
|
73
|
+
AND NOT EXISTS (SELECT 1 FROM run_events JOIN runs ON runs.id = run_events.run_id
|
|
74
|
+
WHERE run_events.event_id = events.id AND runs.rule = ?)`;
|
|
75
|
+
/** How many of the events a pause skipped come listed with it; the count says how many there are in all. */
|
|
76
|
+
const LISTED = 20;
|
|
77
|
+
const skippedView = ({ paused, received_at: receivedAt, ...event }) => ({
|
|
78
|
+
...event,
|
|
79
|
+
receivedAt,
|
|
80
|
+
rules: JSON.parse(paused),
|
|
81
|
+
});
|
|
82
|
+
/**
|
|
83
|
+
* What a pause has kept from a rule since `since` and nothing has made up yet, newest first: how many, and the latest of
|
|
84
|
+
* them, or all of them.
|
|
85
|
+
*/
|
|
86
|
+
export function skippedOf(all, rule, since, everything = false) {
|
|
87
|
+
const { count } = all(`SELECT COUNT(*) AS count ${SKIPPED_BY}`, [since, rule, rule])[0];
|
|
88
|
+
const columns = "SELECT id, source, type, subject, summary, paused, received_at";
|
|
89
|
+
const order = `ORDER BY +id DESC${everything ? "" : ` LIMIT ${LISTED}`}`;
|
|
90
|
+
const events = all(`${columns} ${SKIPPED_BY} ${order}`, [since, rule, rule]);
|
|
91
|
+
return { count, events: events.map(skippedView) };
|
|
92
|
+
}
|
|
93
|
+
export function stateOf(now, before, rules, { all, view, unrouted }) {
|
|
94
|
+
const seen = new Map(all("SELECT kind, name, seen_at FROM seen").map((row) => [`${row.kind}:${row.name}`, row.seen_at]));
|
|
95
|
+
const presence = (who) => {
|
|
96
|
+
const seenAt = seen.get(who) ?? null;
|
|
97
|
+
return { seenAt, online: seenAt !== null && now - Date.parse(seenAt) <= ONLINE };
|
|
98
|
+
};
|
|
99
|
+
const counts = all(COUNTS, [iso(dayStart(now, rules.timezone))]);
|
|
100
|
+
const openCards = all("SELECT * FROM cards WHERE state = 'open' ORDER BY id DESC");
|
|
101
|
+
const lastDeliveries = new Map(all("SELECT channel, card_id, tries, error, given_up FROM deliveries " +
|
|
102
|
+
"WHERE (channel, card_id) IN (SELECT channel, MAX(card_id) FROM deliveries GROUP BY channel)").map((row) => [row.channel, row]));
|
|
103
|
+
const recentCards = all("SELECT * FROM cards WHERE state <> 'open' ORDER BY id DESC LIMIT 20");
|
|
104
|
+
const timers = before
|
|
105
|
+
? []
|
|
106
|
+
: all("SELECT rule, lane, key, about, at FROM timers WHERE event_id IS NULL ORDER BY at");
|
|
107
|
+
const older = before ? "WHERE id < ?" : "";
|
|
108
|
+
const page = all(`SELECT * FROM runs ${older} ORDER BY id DESC LIMIT ?`, before ? [before, PAGE + 1] : [PAGE + 1]);
|
|
109
|
+
const active = before ? [] : all("SELECT * FROM runs WHERE state IN ('queued', 'claimed', 'unknown')");
|
|
110
|
+
const hasMore = page.length > PAGE;
|
|
111
|
+
const byId = new Map([...page.slice(0, PAGE), ...active].map((run) => [run.id, run]));
|
|
112
|
+
const visible = [...byId.values()].sort((a, b) => b.id - a.id);
|
|
113
|
+
// A pause past its end is lifted at the next tick; until then it already doesn't hold. A schedule lets its moments pass
|
|
114
|
+
// and keeps no events.
|
|
115
|
+
const timed = new Set(rules.rules.filter((rule) => !eventRule(rule)).map((rule) => rule.name));
|
|
116
|
+
const pauses = all("SELECT name, by, reason, since, until FROM pauses ORDER BY name")
|
|
117
|
+
.filter((pause) => pause.until === null || Date.parse(pause.until) > now)
|
|
118
|
+
.map((pause) => ({
|
|
119
|
+
...pause,
|
|
120
|
+
skipped: timed.has(pause.name) ? null : skippedOf(all, pause.name, pause.since),
|
|
121
|
+
}));
|
|
122
|
+
const pauseOf = (rule) => {
|
|
123
|
+
const pause = pauses.find((p) => p.name === rule.name);
|
|
124
|
+
if (!pause)
|
|
125
|
+
return null;
|
|
126
|
+
const { by, reason, since, until, skipped } = pause;
|
|
127
|
+
return { by, reason, since, until, skipped };
|
|
128
|
+
};
|
|
129
|
+
const skippedAt = new Map(all("SELECT rule, skipped_at FROM schedules").map((row) => [row.rule, row.skipped_at]));
|
|
130
|
+
return {
|
|
131
|
+
now: iso(now),
|
|
132
|
+
timezone: rules.timezone,
|
|
133
|
+
spending: spendingOf(all, now, rules.timezone),
|
|
134
|
+
totals: { ...tally(counts), attention: openCards.length },
|
|
135
|
+
// The owner's own: which matter a card is about, and what its asker left for whoever carries on. Channels don't get them.
|
|
136
|
+
cards: openCards.map((card) => ({ ...view(card), lane: card.lane, about: card.about })),
|
|
137
|
+
recentCards: recentCards.map((card) => ({ ...view(card), lane: card.lane, about: card.about })),
|
|
138
|
+
timers: timers.map(({ rule, lane, key, about, at }) => ({ rule, lane, key, about, at })),
|
|
139
|
+
sources: Object.entries(rules.sources).map(([id, { name }]) => {
|
|
140
|
+
const events = all("SELECT COUNT(*) AS n FROM events WHERE source = ?", [id])[0].n;
|
|
141
|
+
return { id, name, events };
|
|
142
|
+
}),
|
|
143
|
+
lines: rules.rules.map((rule) => ({
|
|
144
|
+
id: rule.name,
|
|
145
|
+
name: rule.name,
|
|
146
|
+
group: rule.group,
|
|
147
|
+
agent: rule.to,
|
|
148
|
+
source: eventRule(rule) ? rule.when.source : SCHEDULE,
|
|
149
|
+
types: eventRule(rule) ? rule.when.types : [],
|
|
150
|
+
every: eventRule(rule) ? null : describeCron(cronOf(rule)),
|
|
151
|
+
next: eventRule(rule) ? null : iso(nextRun(parseCron(cronOf(rule)), now, rules.timezone)),
|
|
152
|
+
totals: tally(counts.filter((row) => row.rule === rule.name)),
|
|
153
|
+
paused: pauseOf(rule),
|
|
154
|
+
skippedAt: eventRule(rule) ? null : (skippedAt.get(rule.name) ?? null),
|
|
155
|
+
})),
|
|
156
|
+
pauses,
|
|
157
|
+
skipped: all(SKIPPED).map(skippedView),
|
|
158
|
+
elsewhere: rules.elsewhere.map(({ name, source, to, cron, where, model, effort }) => {
|
|
159
|
+
const next = iso(nextRun(parseCron(cron), now, rules.timezone) ?? now);
|
|
160
|
+
const shown = { id: name, name, source, agent: to, cron, every: describeCron(cron), next, where };
|
|
161
|
+
return { ...shown, ...(model && { model }), ...(effort && { effort }) };
|
|
162
|
+
}),
|
|
163
|
+
agents: Object.entries(rules.agents).map(([id, { name, use, worker, program }]) => {
|
|
164
|
+
const totals = tally(counts.filter((row) => row.agent === id));
|
|
165
|
+
return { id, name, use, worker, ...(program && { program }), ...presence(`worker:${worker}`), totals };
|
|
166
|
+
}),
|
|
167
|
+
channels: Object.entries(rules.channels).map(([id, { name }]) => {
|
|
168
|
+
// Coming back says the channel's program runs, not that a card got through: the last one it was given says that.
|
|
169
|
+
const last = lastDeliveries.get(id);
|
|
170
|
+
const lastFailure = last?.error
|
|
171
|
+
? {
|
|
172
|
+
card: last.card_id,
|
|
173
|
+
tries: last.tries,
|
|
174
|
+
error: last.error,
|
|
175
|
+
givenUp: !!last.given_up,
|
|
176
|
+
}
|
|
177
|
+
: undefined;
|
|
178
|
+
return { id, name, ...presence(`channel:${id}`), ...(lastFailure && { lastFailure }) };
|
|
179
|
+
}),
|
|
180
|
+
runs: visible.map((run) => ({
|
|
181
|
+
id: run.id,
|
|
182
|
+
rule: run.rule,
|
|
183
|
+
agent: run.agent,
|
|
184
|
+
state: run.state,
|
|
185
|
+
attempts: run.attempts,
|
|
186
|
+
createdAt: run.created_at,
|
|
187
|
+
claimedAt: run.claimed_at,
|
|
188
|
+
finishedAt: run.finished_at,
|
|
189
|
+
notBefore: run.not_before,
|
|
190
|
+
summary: run.summary ?? "",
|
|
191
|
+
error: run.error ?? "",
|
|
192
|
+
link: run.link ?? "",
|
|
193
|
+
session: run.session,
|
|
194
|
+
usage: run.usage ? JSON.parse(run.usage) : null,
|
|
195
|
+
stopping: run.cancel_at !== null,
|
|
196
|
+
manual: Boolean(run.manual),
|
|
197
|
+
events: all(EVENTS_OF_RUN, [run.id]),
|
|
198
|
+
})),
|
|
199
|
+
hasMore,
|
|
200
|
+
nextBefore: hasMore ? page[PAGE - 1].id : null,
|
|
201
|
+
unrouted: unrouted(),
|
|
202
|
+
};
|
|
203
|
+
}
|