neurastream 0.2.83 → 0.2.85
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/README.md +10 -0
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +27 -0
- package/src/cli/dispatch.ts +3 -0
- package/src/cli/pages.ts +7 -5
- package/src/cli/pressure.ts +29 -0
- package/src/cli/ui.ts +10 -6
- package/src/core/config.ts +10 -0
- package/src/core/pressure.ts +121 -0
- package/src/core/tailscale.ts +25 -0
- package/templates/config.yml +8 -0
package/README.md
CHANGED
|
@@ -173,12 +173,20 @@ A "waiting on you" card or a "done" claim only counts while its own command stil
|
|
|
173
173
|
|
|
174
174
|
One setting decides how much Main does without asking: `autonomy.tier` in the config (default `opinionated`), moved any time by the owner's whole chat message `tier strict|opinionated|full` (when `guards.chat_unlock` is on) or the tier buttons on the phone page — the setting lives in `<queue_state>/autonomy-tier`, a guard-protected path no agent can write. `strict` caps Main's project-file changes at `autonomy.strict_edit_limit` per `guards.main_window_min` minutes and refuses `git push` / `glab mr merge` / `gh pr merge` until the owner types the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message — one landing, valid `autonomy.go_minutes` minutes); `opinionated` keeps today's limits (`guards.main_edit_limit`); `full` drops the cap and lets Main skip an idle higher plan with `Priority skip: <plan> — Main: "<reason>"` (reason ≥ 4 words). No tier loosens the owner-only moves: guard-file edits without the unlock, starting the phone page, reading notify secrets, local `npm publish` and the tier setting itself.
|
|
175
175
|
|
|
176
|
+
## Pressure alerts
|
|
177
|
+
|
|
178
|
+
The omp adapter samples machine pressure every `machine.pressure.sample_sec` (default 10 s) from the kernel's PSI files (`/proc/pressure/memory`, `/proc/pressure/cpu`) and `/proc/meminfo`. A RED line goes into Main's chat once the machine has been red for `red_after_sec` (default 30 s), and repeats every `repeat_sec` (default 600 s) while it stays red. The red thresholds are memory some `mem_some_red` (20 %), memory full `mem_full_red` (5 %), CPU some `cpu_some_red` (60 %), and free memory under `machine.avail_min_mb`. A GREEN line ("room again") follows once the machine has been calm for `green_after_sec` (default 120 s) after a RED. Amber sends nothing. A RED line names the heavy-run lock holder when one is held.
|
|
179
|
+
|
|
180
|
+
This is tell-only: neurastream never pauses, kills or renices a process. The level state lives in `<queue_state>/pressure.json`. `neurastream pressure` prints the current level, the sample and the line Main would read now.
|
|
181
|
+
|
|
176
182
|
## Owner page (`neurastream ui`)
|
|
177
183
|
|
|
178
184
|
`neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
|
|
179
185
|
|
|
180
186
|
With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, five pill tabs — Now, Queue, Agents, Spend, Base (see "Base tab" below), each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
|
|
181
187
|
|
|
188
|
+
When `tailscale ip -4` answers a new address, the server exits within 30 s and its user unit's `Restart=on-failure` starts it on the new address; no manual restart.
|
|
189
|
+
|
|
182
190
|
A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. `ui.allow_this_machine: true` skips only the two this-machine refusals — loopback and the machine's own tailnet IP are then served as the owner, GET and POST — with the risk in one line: any local process can then press the buttons. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
|
|
183
191
|
|
|
184
192
|
An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, question, answer, login); unlock/lock go through the core unlock and log `UNLOCK ui source=ui:<login> minutes=N`. Main's session delivers each record once as a user message — at turn end and on a 15 s poll while idle — and marks the consumed rows in `<queue_state>/owner-inbox.cursor`; subagent sessions never deliver. Both files sit under the queue state dir, so guards refuse agent writes to them: an agent cannot forge an owner answer. Guards also refuse agent commands that start the page (`neurastream ui`, or `systemctl --user start/restart/enable` of `neurastream-ui`): starting it is the owner's move.
|
|
@@ -187,6 +195,8 @@ An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, questio
|
|
|
187
195
|
|
|
188
196
|
`neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records the plan's text hash in `<queue_state>/plan-approvals.json` and never edits the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval record whose hash matches the plan's current text. The publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
|
|
189
197
|
|
|
198
|
+
When `tailscale ip -4` answers a new address, the server exits within 30 s and its user unit's `Restart=on-failure` starts it on the new address; no manual restart.
|
|
199
|
+
|
|
190
200
|
## Base tab (`/?tab=knowledge`)
|
|
191
201
|
|
|
192
202
|
The phone page's Base tab (`/?tab=knowledge`) lists the HTML explainers that live next to the code they explain, so a page is versioned with its repo. The convention is the registration: any git repository directly under `knowledge.roots` (`docs/config.md`, default `$HOME/projects` and `$HOME/Work`) that has a `docs/knowledge/<topic>.html` appears — drop a file in, `git pull`, and it shows up on the next reload once the cached list is older than `knowledge.max_age_s` (300 s); no list to edit and nothing to restart. The repo name is the `origin` remote's basename without `.git` (the checkout directory name when there is no remote), and linked worktrees are skipped so one repo appears once however many checkouts it has. The page is a breadcrumb `knowledge-base / <repo> / <topic>`: the pill opens the repo list (name, topic count, newest update), a repo opens its topic cards (title from the page's `<title>`, plus the last commit date that touched the file), and each earlier segment of the breadcrumb links back. Topic pages are served through the pages server behind the same single-user login. The tab is read-only: there is no upload, write, delete or rename route for a topic, and topics change only through git.
|
package/package.json
CHANGED
|
@@ -52,6 +52,7 @@ import * as q from "../../core/queue/lib.ts";
|
|
|
52
52
|
import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
|
|
53
53
|
import { annotateResetTimes } from "../../core/reset-time.ts";
|
|
54
54
|
import { tryLock, type HeldLock } from "../../core/file-lock.ts";
|
|
55
|
+
import { currentHolder, pressureLevel, pressureMessage, pressureTransition, readPressure, type PressureSample, type PressureState } from "../../core/pressure.ts";
|
|
55
56
|
// Registers the plugin-command matcher into core's writeTargets (side effect).
|
|
56
57
|
import "./package-ops.ts";
|
|
57
58
|
|
|
@@ -632,6 +633,27 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
|
|
|
632
633
|
|
|
633
634
|
/** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
|
|
634
635
|
let activeAdapterReset: (() => void) | null = null;
|
|
636
|
+
/** Pressure alert tick (plan 20261026_0100 P2): classifies one sample, runs the transition, and tells Main on a RED or GREEN fire. The state lives in <queue_state>/pressure.json and is rewritten only when it changes, so a reloaded session does not re-fire. */
|
|
637
|
+
export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSample, now: number): void {
|
|
638
|
+
const file = join(cfg.paths.queue_state, "pressure.json");
|
|
639
|
+
let prev: PressureState | null = null;
|
|
640
|
+
try {
|
|
641
|
+
prev = JSON.parse(readFileSync(file, "utf8")) as PressureState;
|
|
642
|
+
} catch {}
|
|
643
|
+
const level = pressureLevel(sample, cfg);
|
|
644
|
+
const r = pressureTransition(prev, level, now, cfg);
|
|
645
|
+
const next = JSON.stringify(r.state);
|
|
646
|
+
if (next !== JSON.stringify(prev)) {
|
|
647
|
+
try {
|
|
648
|
+
mkdirSync(cfg.paths.queue_state, { recursive: true });
|
|
649
|
+
writeFileSync(file, next);
|
|
650
|
+
} catch {}
|
|
651
|
+
}
|
|
652
|
+
if (r.fire === "red") {
|
|
653
|
+
pi.sendUserMessage(pressureMessage("red", sample, currentHolder(cfg, now)));
|
|
654
|
+
} else if (r.fire === "green") pi.sendUserMessage(pressureMessage("green", sample, null));
|
|
655
|
+
}
|
|
656
|
+
|
|
635
657
|
/** This process's held Main session lock (plan 20261103_1146 P2): the first main session_start
|
|
636
658
|
* locks `<queue_state>/mains/<id>/session.lock` for the process lifetime — the kernel frees it
|
|
637
659
|
* when the process dies. A factory re-run must not release it (P4): dropping it lets another
|
|
@@ -928,6 +950,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
|
|
|
928
950
|
? c.setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS)
|
|
929
951
|
: setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS);
|
|
930
952
|
if (it && typeof it === "object" && "unref" in it && typeof it.unref === "function") it.unref();
|
|
953
|
+
// Pressure alerts (P2): sample the machine every sample_sec; tell Main only on a RED or GREEN fire.
|
|
954
|
+
const sample = (): void => pressureTick(pi, cfg, readPressure(), nowSec());
|
|
955
|
+
const sampleMs = cfg.machine.pressure.sample_sec * 1000;
|
|
956
|
+
const pt: unknown = c.setInterval ? c.setInterval(sample, sampleMs) : setInterval(sample, sampleMs);
|
|
957
|
+
if (pt && typeof pt === "object" && "unref" in pt && typeof pt.unref === "function") pt.unref();
|
|
931
958
|
// Multi-main P3: every held claim heartbeats once a minute while this Main session lives,
|
|
932
959
|
// so a live Main never loses a plan to queue.claim_ttl_min. session_shutdown releases
|
|
933
960
|
// nothing: the TTL frees a crashed or restarted Main's claims the same way.
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { runInit } from "./init.ts";
|
|
|
18
18
|
import { realSetupDeps, runSetup } from "./setup.ts";
|
|
19
19
|
import { PORTED, runMain, runPorted } from "./commands.ts";
|
|
20
20
|
import { runMetrics } from "./metrics.ts";
|
|
21
|
+
import { runPressure } from "./pressure.ts";
|
|
21
22
|
import { runIncident } from "./incident.ts";
|
|
22
23
|
import { runTraces } from "./traces.ts";
|
|
23
24
|
import { runUi } from "./ui.ts";
|
|
@@ -100,6 +101,7 @@ export function helpText(): string {
|
|
|
100
101
|
` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
|
|
101
102
|
" neurastream main [args] run omp under the launcher (automatic session rollover)",
|
|
102
103
|
" neurastream metrics <cmd> self-metrics: report, features, releases, ci, false-alarm, rule (see README)",
|
|
104
|
+
" neurastream pressure machine pressure now: level, the sample, the line Main would read",
|
|
103
105
|
" neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
|
|
104
106
|
" neurastream labels episodes [--since 30d] [--json]",
|
|
105
107
|
" join scored work, agent runs and spawn briefs",
|
|
@@ -155,6 +157,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
155
157
|
if (cmd === "main") return runMain(args);
|
|
156
158
|
if (cmd === "init") return runInit(args);
|
|
157
159
|
if (cmd === "metrics") return runMetrics(args);
|
|
160
|
+
if (cmd === "pressure") return runPressure(args);
|
|
158
161
|
if (cmd === "incident") return runIncident(args);
|
|
159
162
|
if (cmd === "traces") return runTraces(args);
|
|
160
163
|
if (cmd === "labels") return runLabels(args);
|
package/src/cli/pages.ts
CHANGED
|
@@ -4,12 +4,12 @@ import { getAdapter } from "../adapters/index.ts";
|
|
|
4
4
|
import { loadConfig } from "../core/config.ts";
|
|
5
5
|
import { beat, errorLine } from "../core/heartbeat.ts";
|
|
6
6
|
import { readExpiry, sweepPages } from "../core/pages-expiry.ts";
|
|
7
|
-
import { startPagesServer } from "../core/pages.ts";
|
|
7
|
+
import { startPagesServer, type PagesServer } from "../core/pages.ts";
|
|
8
8
|
import { pageNotesGate } from "../core/page-notes.ts";
|
|
9
9
|
import { pagesOff, pagesOn, publishPage, repoForPublish, type Runner } from "../core/pages-setup.ts";
|
|
10
|
-
import { realTailscale, type Tailscale } from "../core/tailscale.ts";
|
|
10
|
+
import { realTailscale, type Tailscale, untilIp4Changes } from "../core/tailscale.ts";
|
|
11
11
|
|
|
12
|
-
export interface PagesDeps { home?: string; runner?: Runner; tailscale?: Tailscale; clock?: () => Date }
|
|
12
|
+
export interface PagesDeps { home?: string; runner?: Runner; tailscale?: Tailscale; clock?: () => Date; ipPollMs?: number }
|
|
13
13
|
const HOUR_MS = 60 * 60 * 1000;
|
|
14
14
|
export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promise<number> {
|
|
15
15
|
const home = deps.home ?? homedir();
|
|
@@ -19,17 +19,19 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
|
|
|
19
19
|
if (args[0] === "off" && args.length === 1) return pagesOff({ home, runner: deps.runner });
|
|
20
20
|
const cfg = loadConfig({ home });
|
|
21
21
|
if (args[0] === "serve" && args.length === 1) {
|
|
22
|
+
const tailscale = deps.tailscale ?? realTailscale;
|
|
23
|
+
let server: PagesServer;
|
|
22
24
|
try {
|
|
23
25
|
if (!cfg.pages.enabled) throw new Error("pages.enabled is false");
|
|
24
26
|
sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock());
|
|
25
|
-
startPagesServer({ cfg, tailscale
|
|
27
|
+
server = startPagesServer({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg) });
|
|
26
28
|
} catch (e) {
|
|
27
29
|
beat(cfg, "pages-serve", { ok: false, detail: errorLine(e) });
|
|
28
30
|
throw e;
|
|
29
31
|
}
|
|
30
32
|
beat(cfg, "pages-serve", { ok: true });
|
|
31
33
|
setInterval(() => { try { sweepPages(cfg.pages.dir, cfg.pages.keep_days, clock()); } catch (e) { console.error(e instanceof Error ? e.message : String(e)); } }, HOUR_MS);
|
|
32
|
-
return
|
|
34
|
+
return untilIp4Changes(tailscale, server.hostname, deps.ipPollMs);
|
|
33
35
|
}
|
|
34
36
|
if (args[0] === "publish" && args[1]) {
|
|
35
37
|
let force = false, keep = false, plan: string | undefined, repo: string | undefined;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// `neurastream pressure`: prints the machine-pressure level, the sample it came from, and the
|
|
2
|
+
// line Main would read for that level. Read only: it never acts on a process.
|
|
3
|
+
|
|
4
|
+
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
5
|
+
import { nowSec } from "../core/clock.ts";
|
|
6
|
+
import { currentHolder, pressureLevel, pressureMessage, readPressure, type PressureSample } from "../core/pressure.ts";
|
|
7
|
+
|
|
8
|
+
/** The three lines the command prints. Amber has nothing to say, so it names that instead of a message. */
|
|
9
|
+
export function pressureReport(cfg: Config, sample: PressureSample, now: number): string {
|
|
10
|
+
const level = pressureLevel(sample, cfg);
|
|
11
|
+
let last = "none (amber: nothing to say)";
|
|
12
|
+
if (level === "red") last = pressureMessage("red", sample, currentHolder(cfg, now));
|
|
13
|
+
if (level === "green") last = pressureMessage("green", sample, null);
|
|
14
|
+
return [`level: ${level}`, `sample: ${JSON.stringify(sample)}`, `last message: ${last}`].join("\n");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function runPressure(args: string[]): number {
|
|
18
|
+
if (args.length > 0) {
|
|
19
|
+
console.error("usage: neurastream pressure");
|
|
20
|
+
return 2;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
console.log(pressureReport(loadConfig(), readPressure(), nowSec()));
|
|
24
|
+
} catch (err) {
|
|
25
|
+
console.error(err instanceof ConfigError ? err.message : String(err));
|
|
26
|
+
return 1;
|
|
27
|
+
}
|
|
28
|
+
return 0;
|
|
29
|
+
}
|
package/src/cli/ui.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
|
9
9
|
import { beat, errorLine } from "../core/heartbeat.ts";
|
|
10
10
|
import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
|
|
11
11
|
import { applyQueueEnv } from "../core/queue/env.ts";
|
|
12
|
-
import { realTailscale, type Tailscale } from "../core/tailscale.ts";
|
|
12
|
+
import { realTailscale, type Tailscale, untilIp4Changes } from "../core/tailscale.ts";
|
|
13
13
|
import { systemTerminal, uiOff, uiOn, type Runner } from "../core/ui-setup.ts";
|
|
14
14
|
|
|
15
15
|
export interface UiDeps {
|
|
@@ -19,10 +19,12 @@ export interface UiDeps {
|
|
|
19
19
|
start?: (opts: OwnerUiOptions) => OwnerUiServer;
|
|
20
20
|
/** Command runner for `ui on`/`ui off` (default: spawnSync of systemctl --user). */
|
|
21
21
|
runner?: Runner;
|
|
22
|
-
/** Tailscale seam for `ui on` (default: realTailscale). */
|
|
22
|
+
/** Tailscale seam for `ui on` and the serve path (default: realTailscale). */
|
|
23
23
|
tailscale?: Tailscale;
|
|
24
24
|
/** HOME the `ui on`/`ui off` config and unit paths resolve against (default: homedir()). */
|
|
25
25
|
home?: string;
|
|
26
|
+
/** How often the serve path checks for a new tailnet address (default: IP4_POLL_MS). */
|
|
27
|
+
ipPollMs?: number;
|
|
26
28
|
}
|
|
27
29
|
|
|
28
30
|
const UI_USAGE = "usage: neurastream ui [on --login <tailscale login> [--port N] | off]";
|
|
@@ -87,14 +89,16 @@ export async function runUi(args: string[] = [], deps: UiDeps = {}): Promise<num
|
|
|
87
89
|
console.error("neurastream ui: ui.owner_login is empty — set the tailscale login that may open the page");
|
|
88
90
|
return 1;
|
|
89
91
|
}
|
|
92
|
+
const tailscale = deps.tailscale ?? realTailscale;
|
|
93
|
+
let server: OwnerUiServer;
|
|
90
94
|
try {
|
|
91
|
-
(deps.start ?? startOwnerUi)({ cfg, tailscale
|
|
95
|
+
server = (deps.start ?? startOwnerUi)({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg) });
|
|
92
96
|
} catch (e) {
|
|
93
97
|
beat(cfg, "ui", { ok: false, detail: errorLine(e) });
|
|
94
98
|
throw e;
|
|
95
99
|
}
|
|
96
100
|
beat(cfg, "ui", { ok: true });
|
|
97
|
-
// src/cli/main.ts exits with
|
|
98
|
-
//
|
|
99
|
-
return
|
|
101
|
+
// Resolves 1 when the tailnet address moves: src/cli/main.ts exits with it, which would end the
|
|
102
|
+
// server, and systemd restarts it on the new address. Otherwise serving runs until systemd or a signal stops it.
|
|
103
|
+
return untilIp4Changes(tailscale, server.hostname, deps.ipPollMs);
|
|
100
104
|
}
|
package/src/core/config.ts
CHANGED
|
@@ -253,6 +253,16 @@ export interface Config {
|
|
|
253
253
|
idle_min_ticks: number;
|
|
254
254
|
watch_sec: number;
|
|
255
255
|
watch_streak: number;
|
|
256
|
+
/** Pressure alerts (src/core/pressure.ts): tell Main when the machine chokes, and when it has room again. Never acts. */
|
|
257
|
+
pressure: {
|
|
258
|
+
sample_sec: number;
|
|
259
|
+
mem_some_red: number;
|
|
260
|
+
mem_full_red: number;
|
|
261
|
+
cpu_some_red: number;
|
|
262
|
+
red_after_sec: number;
|
|
263
|
+
green_after_sec: number;
|
|
264
|
+
repeat_sec: number;
|
|
265
|
+
};
|
|
256
266
|
};
|
|
257
267
|
quota: { reset_tz: string; reset_pattern: string; label: string };
|
|
258
268
|
/** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
// Pressure core: reads the kernel's pressure (PSI) and memory numbers, classifies them, and decides when
|
|
6
|
+
// Main should hear about it. Read and report only; this file never acts on a process.
|
|
7
|
+
|
|
8
|
+
export type PressureLevel = "red" | "green" | "amber";
|
|
9
|
+
export interface PressureSample {
|
|
10
|
+
memSome: number | null;
|
|
11
|
+
memFull: number | null;
|
|
12
|
+
cpuSome: number | null;
|
|
13
|
+
ioFull: number | null;
|
|
14
|
+
availMb: number | null;
|
|
15
|
+
swapFreeMb: number | null;
|
|
16
|
+
}
|
|
17
|
+
export interface PressureState {
|
|
18
|
+
level: PressureLevel;
|
|
19
|
+
since: number;
|
|
20
|
+
lastRed: number | null;
|
|
21
|
+
redSent: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function avg10(line: string | undefined): number | null {
|
|
25
|
+
const m = line?.match(/avg10=([\d.]+)/);
|
|
26
|
+
return m ? Number(m[1]) : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** avg10 of the `some` and `full` lines of a /proc/pressure file; unrecognised text gives nulls. */
|
|
30
|
+
export function parsePsi(text: string): { someAvg10: number | null; fullAvg10: number | null } {
|
|
31
|
+
const lines = text.split("\n");
|
|
32
|
+
return {
|
|
33
|
+
someAvg10: avg10(lines.find((l) => l.startsWith("some "))),
|
|
34
|
+
fullAvg10: avg10(lines.find((l) => l.startsWith("full "))),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readText(path: string): string | null {
|
|
39
|
+
try {
|
|
40
|
+
return readFileSync(path, "utf8");
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Reads the PSI files and /proc/meminfo under root. A missing file is null, never a throw. */
|
|
47
|
+
export function readPressure(root = "/"): PressureSample {
|
|
48
|
+
const psi = (name: string) => parsePsi(readText(join(root, "proc/pressure", name)) ?? "");
|
|
49
|
+
const mem = psi("memory");
|
|
50
|
+
const meminfo = readText(join(root, "proc/meminfo")) ?? "";
|
|
51
|
+
const kbToMb = (key: string): number | null => {
|
|
52
|
+
const m = meminfo.match(new RegExp(`^${key}:\\s+(\\d+) kB`, "m"));
|
|
53
|
+
return m ? Number(m[1]) / 1024 : null;
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
memSome: mem.someAvg10,
|
|
57
|
+
memFull: mem.fullAvg10,
|
|
58
|
+
cpuSome: psi("cpu").someAvg10,
|
|
59
|
+
ioFull: psi("io").fullAvg10,
|
|
60
|
+
availMb: kbToMb("MemAvailable"),
|
|
61
|
+
swapFreeMb: kbToMb("SwapFree"),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const over = (v: number | null, limit: number) => v !== null && v >= limit;
|
|
66
|
+
const under = (v: number | null, limit: number) => v !== null && v < limit;
|
|
67
|
+
|
|
68
|
+
/** Classifies one sample. Red on any stall or low-memory threshold; green only when every reading is well
|
|
69
|
+
* below its threshold; otherwise amber (including when nothing could be read). */
|
|
70
|
+
export function pressureLevel(s: PressureSample, cfg: Config): PressureLevel {
|
|
71
|
+
const p = cfg.machine.pressure;
|
|
72
|
+
const min = cfg.machine.avail_min_mb;
|
|
73
|
+
if (over(s.memSome, p.mem_some_red) || over(s.memFull, p.mem_full_red) || over(s.cpuSome, p.cpu_some_red) || under(s.availMb, min)) {
|
|
74
|
+
return "red";
|
|
75
|
+
}
|
|
76
|
+
const calm = under(s.memSome, p.mem_some_red / 2) && under(s.memFull, p.mem_full_red / 2) && under(s.cpuSome, p.cpu_some_red / 2) && over(s.availMb, min * 1.5);
|
|
77
|
+
return calm ? "green" : "amber";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Advances the level state machine. RED fires once the level has been red for red_after_sec, then at most
|
|
81
|
+
* every repeat_sec. GREEN fires once, after green_after_sec of green, and only after a RED. Amber never fires. */
|
|
82
|
+
export function pressureTransition(prev: PressureState | null, level: PressureLevel, nowSec: number, cfg: Config): { state: PressureState; fire: "red" | "green" | null } {
|
|
83
|
+
const p = cfg.machine.pressure;
|
|
84
|
+
const base: PressureState = prev ?? { level: "amber", since: nowSec, lastRed: null, redSent: false };
|
|
85
|
+
const state = base.level === level ? base : { ...base, level, since: nowSec };
|
|
86
|
+
const held = nowSec - state.since;
|
|
87
|
+
if (level === "red") {
|
|
88
|
+
const due = held >= p.red_after_sec && (state.lastRed === null || nowSec - state.lastRed >= p.repeat_sec);
|
|
89
|
+
return due ? { state: { ...state, lastRed: nowSec, redSent: true }, fire: "red" } : { state, fire: null };
|
|
90
|
+
}
|
|
91
|
+
if (level === "green" && state.redSent && held >= p.green_after_sec) {
|
|
92
|
+
return { state: { ...state, redSent: false }, fire: "green" };
|
|
93
|
+
}
|
|
94
|
+
return { state, fire: null };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The heavy-run holder right now, read from cfg.paths.heavy_owner; null when the file is missing or no lock is held. Shared by the tick and `neurastream pressure`. */
|
|
98
|
+
export function currentHolder(cfg: Config, nowSec: number): string | null {
|
|
99
|
+
const text = readText(cfg.paths.heavy_owner);
|
|
100
|
+
return text === null ? null : heavyHolder(text, nowSec);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The line Main reads. holder is the heavy-run lock holder from heavyHolder, or null. */
|
|
104
|
+
export function pressureMessage(level: "red" | "green", s: PressureSample, holder: string | null): string {
|
|
105
|
+
const mem = s.memSome === null ? "n/a" : `${Math.round(s.memSome)}%`;
|
|
106
|
+
const cpu = s.cpuSome === null ? "n/a" : `${Math.round(s.cpuSome)}%`;
|
|
107
|
+
const free = s.availMb === null ? "n/a" : `${(s.availMb / 1024).toFixed(1)} GB`;
|
|
108
|
+
const tail = level === "green" ? "; room again" : holder === null ? "" : `; heavy-run lock held by ${holder}`;
|
|
109
|
+
return `machine: ${level === "red" ? "RED" : "GREEN"} — memory stall ${mem}, cpu ${cpu}, ${free} free${tail}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Turns the heavy-run owner file ("<who> | <what> | since <stamp> | pid N") into "who (what) for N min".
|
|
113
|
+
* Null when the file is empty. nowSec is in seconds. */
|
|
114
|
+
export function heavyHolder(ownerText: string, nowSec: number): string | null {
|
|
115
|
+
const m = ownerText.match(/^(.*?) \| (.*?) \| since (\S+ \S+) \|/);
|
|
116
|
+
if (!m) return null;
|
|
117
|
+
const [, who = "", what = "", stamp = ""] = m;
|
|
118
|
+
const since = Date.parse(stamp.replace(" ", "T"));
|
|
119
|
+
if (Number.isNaN(since)) return `${who} (${what})`;
|
|
120
|
+
return `${who} (${what}) for ${Math.floor((nowSec * 1000 - since) / 60000)} min`;
|
|
121
|
+
}
|
package/src/core/tailscale.ts
CHANGED
|
@@ -26,6 +26,31 @@ function firstStdoutLine(args: string[]): string | null {
|
|
|
26
26
|
return line || null;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
/** How often the servers check whether `tailscale ip -4` moved to another address. */
|
|
30
|
+
export const IP4_POLL_MS = 30_000;
|
|
31
|
+
|
|
32
|
+
function isIpv4(answer: string | null): answer is string {
|
|
33
|
+
const octets = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(answer ?? "");
|
|
34
|
+
return octets !== null && octets.slice(1).every(o => Number(o) <= 255);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Resolves 1 once `tailscale ip -4` answers a different IPv4 address than `bound`, after printing why
|
|
39
|
+
* to stderr; the caller exits so the service manager restarts it on the new address. Any other answer
|
|
40
|
+
* (the same address, null, or a status-0 line such as "Logged out.") keeps it serving.
|
|
41
|
+
*/
|
|
42
|
+
export function untilIp4Changes(tailscale: Tailscale, bound: string, everyMs = IP4_POLL_MS): Promise<number> {
|
|
43
|
+
const { promise, resolve } = Promise.withResolvers<number>();
|
|
44
|
+
const timer = setInterval(() => {
|
|
45
|
+
const now = tailscale.ip4();
|
|
46
|
+
if (!isIpv4(now) || now === bound) return;
|
|
47
|
+
clearInterval(timer);
|
|
48
|
+
console.error(`tailnet address changed ${bound} → ${now}; exiting so the service manager restarts on the new address`);
|
|
49
|
+
resolve(1);
|
|
50
|
+
}, everyMs);
|
|
51
|
+
return promise;
|
|
52
|
+
}
|
|
53
|
+
|
|
29
54
|
/** The login in `tailscale whois --json` output: multi-line JSON with the login at `UserProfile.LoginName`. Null when absent or unparseable. */
|
|
30
55
|
export function parseWhoisLogin(stdout: string): string | null {
|
|
31
56
|
try {
|
package/templates/config.yml
CHANGED
|
@@ -240,6 +240,14 @@ machine:
|
|
|
240
240
|
idle_min_ticks: 300 # idle ticks before the flag
|
|
241
241
|
watch_sec: 60 # seconds between machine watches
|
|
242
242
|
watch_streak: 3 # consecutive watches before the flag
|
|
243
|
+
pressure: # pressure alerts (src/core/pressure.ts): tell Main when the machine chokes and when it has room; never acts
|
|
244
|
+
sample_sec: 10 # seconds between samples
|
|
245
|
+
mem_some_red: 20 # memory stall avg10 (%) that is red
|
|
246
|
+
mem_full_red: 5 # memory full-stall avg10 (%) that is red
|
|
247
|
+
cpu_some_red: 60 # cpu stall avg10 (%) that is red
|
|
248
|
+
red_after_sec: 30 # seconds red before the RED message
|
|
249
|
+
green_after_sec: 120 # seconds green after a RED before the GREEN message
|
|
250
|
+
repeat_sec: 600 # minimum seconds between two RED messages
|
|
243
251
|
|
|
244
252
|
quota:
|
|
245
253
|
reset_tz: "Asia/Shanghai" # timezone of the quota reset time
|