@ouro.bot/cli 0.1.0-alpha.1002 → 0.1.0-alpha.1005
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.json +12 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/auth/auth-flow.js +11 -0
- package/dist/heart/auth/github-device-login.js +104 -0
- package/dist/heart/daemon/cli-defaults.js +4 -3
- package/dist/heart/daemon/cli-exec.js +6 -1
- package/dist/heart/daemon/cli-help.js +2 -2
- package/dist/heart/daemon/cli-parse.js +28 -3
- package/dist/heart/daemon/linux-service.js +86 -6
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
|
|
3
3
|
"versions": [
|
|
4
|
+
{
|
|
5
|
+
"version": "0.1.0-alpha.1005",
|
|
6
|
+
"changes": [
|
|
7
|
+
"ouro auth for github-copilot on a host without gh runs GitHub's device login itself: enter the shown code at github.com/login/device on any device."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"version": "0.1.0-alpha.1003",
|
|
12
|
+
"changes": [
|
|
13
|
+
"ouro service install takes --min-mem-available-mb, --max-old-space-size, --oom-score-adj and --alert-file; the supervisor backs off from 5 s to 10 min and stops respawning after 5 crashes in 10 minutes, writing one line to the alert file."
|
|
14
|
+
]
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
"version": "0.1.0-alpha.1002",
|
|
6
18
|
"changes": [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<?xml version="1.0"?>
|
|
2
2
|
<Container version="2">
|
|
3
3
|
<Name>ouro-butler</Name>
|
|
4
|
-
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1005</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
|
@@ -44,6 +44,7 @@ const child_process_1 = require("child_process");
|
|
|
44
44
|
const fs = __importStar(require("fs"));
|
|
45
45
|
const os = __importStar(require("os"));
|
|
46
46
|
const path = __importStar(require("path"));
|
|
47
|
+
const github_device_login_1 = require("./github-device-login");
|
|
47
48
|
const runtime_1 = require("../../nerves/runtime");
|
|
48
49
|
const identity_1 = require("../identity");
|
|
49
50
|
const migrate_config_1 = require("../migrate-config");
|
|
@@ -292,11 +293,21 @@ async function collectRuntimeAuthCredentials(input, deps) {
|
|
|
292
293
|
}
|
|
293
294
|
if (input.provider === "github-copilot") {
|
|
294
295
|
let token = process.env.GH_TOKEN?.trim() || process.env.GITHUB_TOKEN?.trim() || "";
|
|
296
|
+
let ghInstalled = true;
|
|
295
297
|
if (!token) {
|
|
296
298
|
writeAuthProgress(input, "checking GitHub CLI credentials...");
|
|
297
299
|
const result = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
|
|
300
|
+
ghInstalled = result.error?.code !== "ENOENT";
|
|
298
301
|
token = (result.status === 0 && result.stdout ? result.stdout.trim() : "");
|
|
299
302
|
}
|
|
303
|
+
if (!token && !ghInstalled) {
|
|
304
|
+
// No gh on this host (an appliance, a container): GitHub's device flow needs only a code entered elsewhere.
|
|
305
|
+
writeAuthProgress(input, "starting GitHub device login...");
|
|
306
|
+
const deviceLogin = deps.githubDeviceLogin ?? github_device_login_1.githubDeviceLogin;
|
|
307
|
+
// Callers without a progress view (the cold hatch prompt) still need to see the code.
|
|
308
|
+
const showCode = input.onProgress ?? ((message) => { process.stderr.write(`${message}\n`); });
|
|
309
|
+
token = await deviceLogin(showCode);
|
|
310
|
+
}
|
|
300
311
|
if (!token) {
|
|
301
312
|
writeAuthProgress(input, "starting GitHub login...");
|
|
302
313
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GITHUB_CLI_DEFAULT_SCOPES = exports.GITHUB_CLI_OAUTH_CLIENT_ID = void 0;
|
|
4
|
+
exports.githubDeviceLogin = githubDeviceLogin;
|
|
5
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
6
|
+
/**
|
|
7
|
+
* GitHub CLI's public OAuth app and its default scopes: the same client and
|
|
8
|
+
* scopes `gh auth login` requests, so the token is the one the `gh` path
|
|
9
|
+
* yields. Used on hosts without `gh`, such as an appliance.
|
|
10
|
+
*/
|
|
11
|
+
exports.GITHUB_CLI_OAUTH_CLIENT_ID = "178c6fc778ccc68e1d6a";
|
|
12
|
+
exports.GITHUB_CLI_DEFAULT_SCOPES = "repo read:org gist";
|
|
13
|
+
const DEVICE_CODE_URL = "https://github.com/login/device/code";
|
|
14
|
+
const ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
|
|
15
|
+
const DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
16
|
+
const SLOW_DOWN_STEP_MS = 5_000;
|
|
17
|
+
const defaultDeps = {
|
|
18
|
+
fetch: (...args) => fetch(...args),
|
|
19
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
20
|
+
now: () => Date.now(),
|
|
21
|
+
};
|
|
22
|
+
function postForm(deps, url, form) {
|
|
23
|
+
return deps.fetch(url, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
|
|
26
|
+
body: new URLSearchParams(form).toString(),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function readJson(response) {
|
|
30
|
+
try {
|
|
31
|
+
return await response.json();
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return {};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* GitHub's OAuth device flow: shows a code to enter at github.com/login/device
|
|
39
|
+
* on any device, then polls until it is approved. Needs no browser or `gh` on
|
|
40
|
+
* this host. Returns the access token.
|
|
41
|
+
*/
|
|
42
|
+
async function githubDeviceLogin(showCode, deps = defaultDeps) {
|
|
43
|
+
const codeResponse = await postForm(deps, DEVICE_CODE_URL, { client_id: exports.GITHUB_CLI_OAUTH_CLIENT_ID, scope: exports.GITHUB_CLI_DEFAULT_SCOPES });
|
|
44
|
+
if (!codeResponse.ok)
|
|
45
|
+
throw new Error(`GitHub device login could not start (HTTP ${codeResponse.status}).`);
|
|
46
|
+
const code = await readJson(codeResponse);
|
|
47
|
+
if (!code.device_code || !code.user_code || !code.verification_uri) {
|
|
48
|
+
throw new Error("GitHub device login returned no code to enter.");
|
|
49
|
+
}
|
|
50
|
+
showCode(`To sign in to GitHub, open ${code.verification_uri} on any device and enter code ${code.user_code}`);
|
|
51
|
+
(0, runtime_1.emitNervesEvent)({
|
|
52
|
+
component: "daemon",
|
|
53
|
+
event: "daemon.auth_github_device_login_start",
|
|
54
|
+
message: "waiting for GitHub device login approval",
|
|
55
|
+
meta: { verificationUri: code.verification_uri, expiresInSeconds: code.expires_in ?? null },
|
|
56
|
+
});
|
|
57
|
+
try {
|
|
58
|
+
return await pollForToken(code.device_code, code.interval, code.expires_in, deps);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
(0, runtime_1.emitNervesEvent)({
|
|
62
|
+
level: "error",
|
|
63
|
+
component: "daemon",
|
|
64
|
+
event: "daemon.auth_github_device_login_error",
|
|
65
|
+
message: "GitHub device login did not complete",
|
|
66
|
+
meta: { error: error.message },
|
|
67
|
+
});
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function pollForToken(deviceCode, interval, expiresIn, deps) {
|
|
72
|
+
let intervalMs = (interval ?? 5) * 1000;
|
|
73
|
+
const deadline = deps.now() + (expiresIn ?? 900) * 1000;
|
|
74
|
+
while (deps.now() < deadline) {
|
|
75
|
+
await deps.sleep(intervalMs);
|
|
76
|
+
const response = await postForm(deps, ACCESS_TOKEN_URL, {
|
|
77
|
+
client_id: exports.GITHUB_CLI_OAUTH_CLIENT_ID,
|
|
78
|
+
device_code: deviceCode,
|
|
79
|
+
grant_type: DEVICE_GRANT_TYPE,
|
|
80
|
+
});
|
|
81
|
+
const result = await readJson(response);
|
|
82
|
+
if (result.access_token) {
|
|
83
|
+
(0, runtime_1.emitNervesEvent)({
|
|
84
|
+
component: "daemon",
|
|
85
|
+
event: "daemon.auth_github_device_login_end",
|
|
86
|
+
message: "GitHub device login approved",
|
|
87
|
+
meta: {},
|
|
88
|
+
});
|
|
89
|
+
return result.access_token;
|
|
90
|
+
}
|
|
91
|
+
if (result.error === "authorization_pending")
|
|
92
|
+
continue;
|
|
93
|
+
if (result.error === "slow_down") {
|
|
94
|
+
intervalMs = result.interval ? result.interval * 1000 : intervalMs + SLOW_DOWN_STEP_MS;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (result.error === "expired_token")
|
|
98
|
+
break;
|
|
99
|
+
if (result.error === "access_denied")
|
|
100
|
+
throw new Error("GitHub device login was denied.");
|
|
101
|
+
throw new Error(`GitHub device login failed: ${result.error ?? `HTTP ${response.status}`}.`);
|
|
102
|
+
}
|
|
103
|
+
throw new Error("The GitHub device login code expired before it was approved. Run ouro auth again.");
|
|
104
|
+
}
|
|
@@ -125,13 +125,14 @@ function linuxServiceDeps() {
|
|
|
125
125
|
}
|
|
126
126
|
function defaultLinuxService(socketPath) {
|
|
127
127
|
// Resolve the home lazily: building the CLI deps must not consult the home directory.
|
|
128
|
-
const options = (homeDir) => ({
|
|
128
|
+
const options = (homeDir, supervision) => ({
|
|
129
129
|
nodePath: process.execPath,
|
|
130
130
|
entryPath: resolveDaemonBootEntryPath(homeDir),
|
|
131
131
|
socketPath,
|
|
132
132
|
homeDir,
|
|
133
133
|
ouroCliHome: (0, ouro_version_manager_1.getOuroCliHome)(homeDir),
|
|
134
134
|
envPath: process.env.PATH,
|
|
135
|
+
...(supervision ? { supervision } : {}),
|
|
135
136
|
});
|
|
136
137
|
return {
|
|
137
138
|
install: (request) => {
|
|
@@ -139,10 +140,10 @@ function defaultLinuxService(socketPath) {
|
|
|
139
140
|
const deps = linuxServiceDeps();
|
|
140
141
|
if (request.print) {
|
|
141
142
|
const servicePath = request.path ?? (0, linux_service_1.defaultServicePath)(request.init, homeDir, deps.isRoot);
|
|
142
|
-
const content = request.init === "sysv" ? (0, linux_service_1.generateSysvInitScript)(options(homeDir)) : (0, linux_service_1.generateSystemdUnit)(options(homeDir), !deps.isRoot);
|
|
143
|
+
const content = request.init === "sysv" ? (0, linux_service_1.generateSysvInitScript)(options(homeDir, request.supervision)) : (0, linux_service_1.generateSystemdUnit)(options(homeDir, request.supervision), !deps.isRoot);
|
|
143
144
|
return { path: servicePath, content, written: false };
|
|
144
145
|
}
|
|
145
|
-
const installed = (0, linux_service_1.installLinuxService)(deps, options(homeDir), request);
|
|
146
|
+
const installed = (0, linux_service_1.installLinuxService)(deps, options(homeDir, request.supervision), request);
|
|
146
147
|
return { path: installed.record.path, content: installed.content, written: true };
|
|
147
148
|
},
|
|
148
149
|
uninstall: () => (0, linux_service_1.uninstallLinuxService)(linuxServiceDeps(), (0, ouro_version_manager_1.getOuroCliHome)(os.homedir())),
|
|
@@ -6705,7 +6705,12 @@ async function runOuroCli(args, deps = (0, cli_defaults_1.createDefaultOuroCliDe
|
|
|
6705
6705
|
deps.writeStdout(message);
|
|
6706
6706
|
return message;
|
|
6707
6707
|
}
|
|
6708
|
-
const installed = deps.linuxService.install({
|
|
6708
|
+
const installed = deps.linuxService.install({
|
|
6709
|
+
init: command.init,
|
|
6710
|
+
print: command.print,
|
|
6711
|
+
...(command.path ? { path: command.path } : {}),
|
|
6712
|
+
...(command.supervision ? { supervision: command.supervision } : {}),
|
|
6713
|
+
});
|
|
6709
6714
|
const message = installed.written
|
|
6710
6715
|
? [
|
|
6711
6716
|
`installed the Ouro ${command.init} service at ${installed.path}`,
|
|
@@ -47,8 +47,8 @@ exports.COMMAND_REGISTRY = {
|
|
|
47
47
|
service: {
|
|
48
48
|
category: "Lifecycle",
|
|
49
49
|
description: "Run the daemon as a supervised service on Linux without launchd (SysV init script or systemd unit); `ouro up` then starts it through the service",
|
|
50
|
-
usage: "ouro service install --init <sysv|systemd> [--path <file>] [--print] | ouro service uninstall",
|
|
51
|
-
example: "ouro service install --init sysv",
|
|
50
|
+
usage: "ouro service install --init <sysv|systemd> [--path <file>] [--print] [--min-mem-available-mb <mb>] [--max-old-space-size <mb>] [--oom-score-adj <-1000..1000>] [--alert-file <file>] | ouro service uninstall",
|
|
51
|
+
example: "ouro service install --init sysv --min-mem-available-mb 250 --max-old-space-size 160 --oom-score-adj 900",
|
|
52
52
|
subcommands: ["install", "uninstall"],
|
|
53
53
|
},
|
|
54
54
|
dev: {
|
|
@@ -182,7 +182,7 @@ function parseVoiceCommand(args) {
|
|
|
182
182
|
request.files = { inputPath, outputPath };
|
|
183
183
|
return { kind: "voice.join", request };
|
|
184
184
|
}
|
|
185
|
-
const SERVICE_USAGE = "Usage: ouro service install --init <sysv|systemd> [--path <file>] [--print] | ouro service uninstall";
|
|
185
|
+
const SERVICE_USAGE = "Usage: ouro service install --init <sysv|systemd> [--path <file>] [--print] [--min-mem-available-mb <mb>] [--max-old-space-size <mb>] [--oom-score-adj <-1000..1000>] [--alert-file <file>] | ouro service uninstall";
|
|
186
186
|
function parseServiceCommand(args) {
|
|
187
187
|
const [sub, ...rest] = args;
|
|
188
188
|
if (sub === "uninstall" && rest.length === 0)
|
|
@@ -192,10 +192,35 @@ function parseServiceCommand(args) {
|
|
|
192
192
|
let init;
|
|
193
193
|
let servicePath;
|
|
194
194
|
let print = false;
|
|
195
|
+
const supervision = {};
|
|
196
|
+
const integer = (value, min, max) => {
|
|
197
|
+
if (value === undefined || !/^-?\d+$/.test(value))
|
|
198
|
+
return undefined;
|
|
199
|
+
const parsed = Number(value);
|
|
200
|
+
return parsed >= min && parsed <= max ? parsed : undefined;
|
|
201
|
+
};
|
|
195
202
|
for (let index = 0; index < rest.length; index += 1) {
|
|
196
203
|
const token = rest[index];
|
|
197
204
|
const value = rest[index + 1];
|
|
198
|
-
|
|
205
|
+
const megabytes = integer(value, 1, 1_048_576);
|
|
206
|
+
const oomScoreAdj = integer(value, -1000, 1000);
|
|
207
|
+
if (token === "--min-mem-available-mb" && megabytes !== undefined && supervision.minMemAvailableMb === undefined) {
|
|
208
|
+
supervision.minMemAvailableMb = megabytes;
|
|
209
|
+
index += 1;
|
|
210
|
+
}
|
|
211
|
+
else if (token === "--max-old-space-size" && megabytes !== undefined && supervision.maxOldSpaceMb === undefined) {
|
|
212
|
+
supervision.maxOldSpaceMb = megabytes;
|
|
213
|
+
index += 1;
|
|
214
|
+
}
|
|
215
|
+
else if (token === "--oom-score-adj" && oomScoreAdj !== undefined && supervision.oomScoreAdj === undefined) {
|
|
216
|
+
supervision.oomScoreAdj = oomScoreAdj;
|
|
217
|
+
index += 1;
|
|
218
|
+
}
|
|
219
|
+
else if (token === "--alert-file" && value && !value.startsWith("--") && supervision.alertFile === undefined) {
|
|
220
|
+
supervision.alertFile = value;
|
|
221
|
+
index += 1;
|
|
222
|
+
}
|
|
223
|
+
else if (token === "--init" && (value === "sysv" || value === "systemd") && init === undefined) {
|
|
199
224
|
init = value;
|
|
200
225
|
index += 1;
|
|
201
226
|
}
|
|
@@ -212,7 +237,7 @@ function parseServiceCommand(args) {
|
|
|
212
237
|
}
|
|
213
238
|
if (!init)
|
|
214
239
|
throw new Error(SERVICE_USAGE);
|
|
215
|
-
return { kind: "service.install", init, print, ...(servicePath ? { path: servicePath } : {}) };
|
|
240
|
+
return { kind: "service.install", init, print, ...(servicePath ? { path: servicePath } : {}), ...(Object.keys(supervision).length > 0 ? { supervision } : {}) };
|
|
216
241
|
}
|
|
217
242
|
function parseLogsCommand(args) {
|
|
218
243
|
if (args.length === 0)
|
|
@@ -53,6 +53,7 @@ exports.SERVICE_NAME = void 0;
|
|
|
53
53
|
exports.serviceRecordPath = serviceRecordPath;
|
|
54
54
|
exports.shellQuote = shellQuote;
|
|
55
55
|
exports.defaultServicePath = defaultServicePath;
|
|
56
|
+
exports.defaultAlertFile = defaultAlertFile;
|
|
56
57
|
exports.generateSysvInitScript = generateSysvInitScript;
|
|
57
58
|
exports.generateSystemdUnit = generateSystemdUnit;
|
|
58
59
|
exports.readServiceRecord = readServiceRecord;
|
|
@@ -62,7 +63,15 @@ exports.startLinuxService = startLinuxService;
|
|
|
62
63
|
const path = __importStar(require("path"));
|
|
63
64
|
const runtime_1 = require("../../nerves/runtime");
|
|
64
65
|
exports.SERVICE_NAME = "ouro";
|
|
65
|
-
|
|
66
|
+
/** Restart delays double from the first to the cap; a run this long resets them. */
|
|
67
|
+
const RESTART_DELAY_FIRST_SECONDS = 5;
|
|
68
|
+
const RESTART_DELAY_CAP_SECONDS = 600;
|
|
69
|
+
const STABLE_RUN_SECONDS = 600;
|
|
70
|
+
/** The circuit breaker: this many crashes inside the window stops respawning. */
|
|
71
|
+
const BREAKER_CRASHES = 5;
|
|
72
|
+
const BREAKER_WINDOW_SECONDS = 600;
|
|
73
|
+
/** How often a supervisor waiting for memory checks MemAvailable again. */
|
|
74
|
+
const MEMORY_RECHECK_SECONDS = 30;
|
|
66
75
|
function serviceRecordPath(ouroCliHome) {
|
|
67
76
|
return path.join(ouroCliHome, "service.json");
|
|
68
77
|
}
|
|
@@ -81,13 +90,19 @@ function defaultServicePath(init, homeDir, isRoot) {
|
|
|
81
90
|
? path.join("/etc", "systemd", "system", `${exports.SERVICE_NAME}.service`)
|
|
82
91
|
: path.join(homeDir, ".config", "systemd", "user", `${exports.SERVICE_NAME}.service`);
|
|
83
92
|
}
|
|
93
|
+
function defaultAlertFile(ouroCliHome) {
|
|
94
|
+
return path.join(ouroCliHome, "service-alert.log");
|
|
95
|
+
}
|
|
84
96
|
function generateSysvInitScript(options) {
|
|
85
97
|
const logDir = path.join(options.ouroCliHome, "daemon", "logs");
|
|
98
|
+
const supervision = options.supervision ?? {};
|
|
86
99
|
const lines = [
|
|
87
100
|
"#!/bin/sh",
|
|
88
101
|
"# Ouro daemon, written by `ouro service install --init sysv`.",
|
|
89
102
|
"# Runs the daemon in the foreground and restarts it when it fails (non-zero",
|
|
90
|
-
"# exit). A clean exit, such as `ouro stop`, is left stopped.",
|
|
103
|
+
"# exit). A clean exit, such as `ouro stop`, is left stopped. Restarts back off",
|
|
104
|
+
`# from ${RESTART_DELAY_FIRST_SECONDS} s, doubling to ${RESTART_DELAY_CAP_SECONDS} s; ${BREAKER_CRASHES} crashes in ${BREAKER_WINDOW_SECONDS / 60} minutes stop`,
|
|
105
|
+
"# respawning and append one line to ALERT_FILE.",
|
|
91
106
|
"",
|
|
92
107
|
`NODE=${shellQuote(options.nodePath)}`,
|
|
93
108
|
`ENTRY=${shellQuote(options.entryPath)}`,
|
|
@@ -95,21 +110,77 @@ function generateSysvInitScript(options) {
|
|
|
95
110
|
`OURO_HOME=${shellQuote(options.homeDir)}`,
|
|
96
111
|
`LOG_DIR=${shellQuote(logDir)}`,
|
|
97
112
|
`PIDFILE=${shellQuote(path.join(options.ouroCliHome, "service.pid"))}`,
|
|
113
|
+
`ALERT_FILE=${shellQuote(supervision.alertFile ?? defaultAlertFile(options.ouroCliHome))}`,
|
|
114
|
+
`MIN_MEM_AVAILABLE_KB=${(supervision.minMemAvailableMb ?? 0) * 1024}`,
|
|
115
|
+
`MAX_OLD_SPACE_MB=${supervision.maxOldSpaceMb ?? ""}`,
|
|
116
|
+
`OOM_SCORE_ADJ=${supervision.oomScoreAdj ?? ""}`,
|
|
98
117
|
...(options.envPath ? [`PATH=${shellQuote(options.envPath)}`, "export PATH"] : []),
|
|
99
118
|
"",
|
|
119
|
+
"note() {",
|
|
120
|
+
" echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) ouro-service: $*\" >>\"$LOG_DIR/ouro-service.log\"",
|
|
121
|
+
"}",
|
|
122
|
+
"",
|
|
123
|
+
"mem_available_kb() {",
|
|
124
|
+
" while read -r key value unit; do",
|
|
125
|
+
" if [ \"$key\" = \"MemAvailable:\" ]; then echo \"$value\"; return; fi",
|
|
126
|
+
" done </proc/meminfo",
|
|
127
|
+
"}",
|
|
128
|
+
"",
|
|
129
|
+
"# Before each start, wait (without counting a crash) until MemAvailable reaches the floor.",
|
|
130
|
+
"wait_for_memory() {",
|
|
131
|
+
" [ \"$MIN_MEM_AVAILABLE_KB\" -gt 0 ] || return 0",
|
|
132
|
+
" waiting=0",
|
|
133
|
+
" while [ \"$stopping\" -eq 0 ]; do",
|
|
134
|
+
" available=$(mem_available_kb 2>/dev/null)",
|
|
135
|
+
" if [ -z \"$available\" ] || [ \"$available\" -ge \"$MIN_MEM_AVAILABLE_KB\" ]; then",
|
|
136
|
+
" [ \"$waiting\" -eq 1 ] && note \"MemAvailable ${available:-unknown} kB reached the floor; starting\"",
|
|
137
|
+
" return 0",
|
|
138
|
+
" fi",
|
|
139
|
+
" [ \"$waiting\" -eq 0 ] && note \"MemAvailable ${available} kB is below the ${MIN_MEM_AVAILABLE_KB} kB floor; waiting\"",
|
|
140
|
+
" waiting=1",
|
|
141
|
+
` sleep ${MEMORY_RECHECK_SECONDS} &`,
|
|
142
|
+
" wait $!",
|
|
143
|
+
" done",
|
|
144
|
+
"}",
|
|
145
|
+
"",
|
|
100
146
|
"supervise() {",
|
|
101
147
|
" stopping=0",
|
|
102
148
|
" child=",
|
|
149
|
+
` delay=${RESTART_DELAY_FIRST_SECONDS}`,
|
|
150
|
+
" crashes=",
|
|
103
151
|
" trap 'stopping=1; [ -n \"$child\" ] && kill \"$child\" 2>/dev/null' TERM INT",
|
|
104
152
|
" while [ \"$stopping\" -eq 0 ]; do",
|
|
105
|
-
"
|
|
153
|
+
" wait_for_memory",
|
|
154
|
+
" [ \"$stopping\" -eq 1 ] && break",
|
|
155
|
+
" started=$(date +%s)",
|
|
156
|
+
" # The subshell sets oom_score_adj and then becomes node, so the daemon and its workers inherit it.",
|
|
157
|
+
" (",
|
|
158
|
+
" [ -n \"$OOM_SCORE_ADJ\" ] && echo \"$OOM_SCORE_ADJ\" >/proc/self/oom_score_adj 2>/dev/null",
|
|
159
|
+
" HOME=\"$OURO_HOME\" exec \"$NODE\" ${MAX_OLD_SPACE_MB:+--max-old-space-size=$MAX_OLD_SPACE_MB} \"$ENTRY\" --socket \"$SOCKET\"",
|
|
160
|
+
" ) >>\"$LOG_DIR/ouro-daemon-stdout.log\" 2>&1 &",
|
|
106
161
|
" child=$!",
|
|
107
162
|
" wait \"$child\"",
|
|
108
163
|
" code=$?",
|
|
109
164
|
" if [ \"$stopping\" -eq 1 ]; then wait \"$child\" 2>/dev/null; break; fi",
|
|
110
165
|
" [ \"$code\" -eq 0 ] && break",
|
|
111
|
-
|
|
166
|
+
" now=$(date +%s)",
|
|
167
|
+
` [ $((now - started)) -ge ${STABLE_RUN_SECONDS} ] && delay=${RESTART_DELAY_FIRST_SECONDS}`,
|
|
168
|
+
" recent=",
|
|
169
|
+
" count=1",
|
|
170
|
+
" for at in $crashes; do",
|
|
171
|
+
` if [ $((now - at)) -lt ${BREAKER_WINDOW_SECONDS} ]; then recent=\"$recent $at\"; count=$((count + 1)); fi`,
|
|
172
|
+
" done",
|
|
173
|
+
" crashes=\"$recent $now\"",
|
|
174
|
+
` if [ "$count" -ge ${BREAKER_CRASHES} ]; then`,
|
|
175
|
+
` echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) ouro: the daemon crashed $count times in ${BREAKER_WINDOW_SECONDS / 60} minutes (last exit $code); stopped respawning. Fix the cause, then run: $0 start" >>"$ALERT_FILE"`,
|
|
176
|
+
" note \"circuit breaker open after $count crashes; stopped respawning\"",
|
|
177
|
+
" break",
|
|
178
|
+
" fi",
|
|
179
|
+
" note \"daemon exited $code; restarting in ${delay} s\"",
|
|
180
|
+
" sleep \"$delay\" &",
|
|
112
181
|
" wait $!",
|
|
182
|
+
" delay=$((delay * 2))",
|
|
183
|
+
` [ "$delay" -gt ${RESTART_DELAY_CAP_SECONDS} ] && delay=${RESTART_DELAY_CAP_SECONDS}`,
|
|
113
184
|
" done",
|
|
114
185
|
" rm -f \"$PIDFILE\"",
|
|
115
186
|
"}",
|
|
@@ -150,21 +221,30 @@ function generateSysvInitScript(options) {
|
|
|
150
221
|
return lines.join("\n");
|
|
151
222
|
}
|
|
152
223
|
function generateSystemdUnit(options, user) {
|
|
224
|
+
const supervision = options.supervision ?? {};
|
|
225
|
+
const maxOldSpace = supervision.maxOldSpaceMb ? `--max-old-space-size=${supervision.maxOldSpaceMb} ` : "";
|
|
153
226
|
const lines = [
|
|
154
227
|
"# Ouro daemon, written by `ouro service install --init systemd`.",
|
|
155
228
|
"[Unit]",
|
|
156
229
|
"Description=Ouro daemon",
|
|
157
230
|
"After=network-online.target",
|
|
158
231
|
"Wants=network-online.target",
|
|
232
|
+
// The circuit breaker: after this many starts in the window systemd leaves the unit failed.
|
|
233
|
+
`StartLimitIntervalSec=${BREAKER_WINDOW_SECONDS}`,
|
|
234
|
+
`StartLimitBurst=${BREAKER_CRASHES}`,
|
|
159
235
|
"",
|
|
160
236
|
"[Service]",
|
|
161
237
|
"Type=simple",
|
|
162
|
-
`ExecStart=${systemdQuote(options.nodePath)} ${systemdQuote(options.entryPath)} --socket ${systemdQuote(options.socketPath)}`,
|
|
238
|
+
`ExecStart=${systemdQuote(options.nodePath)} ${maxOldSpace}${systemdQuote(options.entryPath)} --socket ${systemdQuote(options.socketPath)}`,
|
|
163
239
|
`Environment=${systemdQuote(`HOME=${options.homeDir}`)}`,
|
|
164
240
|
...(options.envPath ? [`Environment=${systemdQuote(`PATH=${options.envPath}`)}`] : []),
|
|
165
241
|
// A clean exit (ouro stop, SIGTERM) stays stopped; a crash or failed start is retried.
|
|
166
242
|
"Restart=on-failure",
|
|
167
|
-
`RestartSec=${
|
|
243
|
+
`RestartSec=${RESTART_DELAY_FIRST_SECONDS}`,
|
|
244
|
+
// systemd 254+ grows the delay to the cap; older versions ignore these and keep RestartSec.
|
|
245
|
+
"RestartSteps=7",
|
|
246
|
+
`RestartMaxDelaySec=${RESTART_DELAY_CAP_SECONDS}`,
|
|
247
|
+
...(supervision.oomScoreAdj !== undefined ? [`OOMScoreAdjust=${supervision.oomScoreAdj}`] : []),
|
|
168
248
|
"",
|
|
169
249
|
"[Install]",
|
|
170
250
|
`WantedBy=${user ? "default.target" : "multi-user.target"}`,
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1005",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@ouro.bot/cli",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.1005",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@anthropic-ai/sdk": "^0.78.0",
|
|
12
12
|
"@azure/identity": "^4.13.0",
|