neurastream 0.2.7 → 0.2.8
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 +9 -0
- package/package.json +10 -2
- package/src/adapters/omp/doctor.ts +9 -1
- package/src/adapters/omp/index.ts +101 -2
- package/src/cli/dispatch.ts +3 -0
- package/src/cli/ui.ts +30 -0
- package/src/core/agent-score.ts +63 -7
- package/src/core/config.ts +3 -0
- package/src/core/guards.ts +49 -3
- package/src/core/owner-ui.ts +347 -0
- package/src/core/queue/lib.ts +24 -15
- package/src/core/tailscale.ts +49 -0
- package/templates/config.yml +5 -0
- package/templates/systemd/neurastream-ui.service +15 -0
package/README.md
CHANGED
|
@@ -32,6 +32,7 @@ flowchart LR
|
|
|
32
32
|
| Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
|
|
33
33
|
| Unlanded work (`wip-check`, `wip-snapshot`, `wip-backup`) | Lists branches on no remote and dirty worktrees; snapshots them as hidden commits; can push them to a backup repo. |
|
|
34
34
|
| Session rollover | When the main session file passes 5 MB, the next owner message starts a fresh session from a handoff note. |
|
|
35
|
+
| Owner page (`neurastream ui`) | One phone-sized page over Tailscale (`ui.*` config): the plans waiting on the owner with answer buttons, the guard unlock, running agents, the queue, recent merges/CI, open incidents, agent scores, machine health. Serves only a tailnet peer whose `tailscale whois` login equals `ui.owner_login`, only with a Host header naming the tailnet address or the MagicDNS name — DNS rebinding and every other visitor get a 403. Answers land in the owner inbox and reach Main once each; agents cannot start the page or write the inbox. |
|
|
35
36
|
|
|
36
37
|
## Requirements
|
|
37
38
|
|
|
@@ -93,6 +94,14 @@ Owner rule: never write a plan when another agent is doing the research or readi
|
|
|
93
94
|
|
|
94
95
|
A plan parked for the owner has one line: `WAITING on owner: <what>`. That line is the only hold, and only Main writes it (plan-guard refuses subagents). The queue summary shows it as a flag on the plan, cut at 80 characters. Compaction and the rollover handoff read the same lines through `ownerHolds`: the compaction context lists each `<plan file>: WAITING on owner: <text>` line (or `none`) and says any other "needs the owner" or "paused" claim is unverified; the handoff's generated state carries the same lines. Main does not keep holds in a handoff note.
|
|
95
96
|
|
|
97
|
+
## Owner page (`neurastream ui`)
|
|
98
|
+
|
|
99
|
+
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). It shows the plans whose `WAITING on owner:` line is open, with answer buttons; the guard unlock (`unlock 5/15/30`, `lock now`); the running agents; the queue; recent merges/CI; open incidents; agent scores; and machine health. No chat, no plan editing, no shell.
|
|
100
|
+
|
|
101
|
+
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. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
|
|
102
|
+
|
|
103
|
+
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.
|
|
104
|
+
|
|
96
105
|
## Session rollover
|
|
97
106
|
|
|
98
107
|
Main's session file grows with every turn. When it reaches `rollover.max_session_mb` (default 5, `docs/config.md`), Main writes a handoff note to `<queue_state>/rollover/<session id>.md`. The note covers the work in progress and its state, the decisions made and why, the next step, and the files involved. Main is asked for it once per session file, when a turn ends.
|
package/package.json
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "neurastream",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
|
|
5
|
-
"keywords": [
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ai-agents",
|
|
7
|
+
"coding-agents",
|
|
8
|
+
"orchestration",
|
|
9
|
+
"guardrails",
|
|
10
|
+
"omp",
|
|
11
|
+
"bun",
|
|
12
|
+
"cli"
|
|
13
|
+
],
|
|
6
14
|
"homepage": "https://github.com/umiddey/neurastream#readme",
|
|
7
15
|
"bugs": "https://github.com/umiddey/neurastream/issues",
|
|
8
16
|
"type": "module",
|
|
@@ -13,6 +13,7 @@ import { blockState, renderBlock } from "../../core/agents-md.ts";
|
|
|
13
13
|
import { loadConfig } from "../../core/config.ts";
|
|
14
14
|
import { notifyFindings } from "../../core/notify.ts";
|
|
15
15
|
import { readIndex } from "../../core/queue/lib.ts";
|
|
16
|
+
import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
|
|
16
17
|
|
|
17
18
|
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
|
18
19
|
|
|
@@ -156,7 +157,7 @@ function npmViewVersion(name: string, env: NodeJS.ProcessEnv): { version: string
|
|
|
156
157
|
return { version };
|
|
157
158
|
}
|
|
158
159
|
|
|
159
|
-
export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env): DoctorReport {
|
|
160
|
+
export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env, tailscale: Tailscale = realTailscale): DoctorReport {
|
|
160
161
|
const pkg = readPackage(PACKAGE_ROOT);
|
|
161
162
|
const name = pkg.name ?? "neurastream";
|
|
162
163
|
const installed = pkg.version ?? "";
|
|
@@ -179,6 +180,13 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
|
|
|
179
180
|
const agents = liveAgentsMd(home);
|
|
180
181
|
const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
|
|
181
182
|
const cfg = loadConfig({ home, env });
|
|
183
|
+
// The owner page (plan 20261024_2230): when it is switched on, the login must be set and
|
|
184
|
+
// tailscale must answer, or the unit will start and refuse, or serve nobody.
|
|
185
|
+
if (cfg.ui.enabled) {
|
|
186
|
+
if (!cfg.ui.owner_login) problems.push("ui.enabled but ui.owner_login is empty");
|
|
187
|
+
else if (tailscale.ip4() === null) problems.push("ui.enabled but tailscale does not answer (tailscale ip -4)");
|
|
188
|
+
else ok.push(`ui owner page: login ${cfg.ui.owner_login}`);
|
|
189
|
+
}
|
|
182
190
|
// One index (20261024_1400_one_index): repo-directory lines in the main index are the old
|
|
183
191
|
// two-level queue; the plans they hold are invisible to queue-check until migrate folds them.
|
|
184
192
|
const idx = cfg.paths.queue_index;
|
|
@@ -17,13 +17,14 @@
|
|
|
17
17
|
|
|
18
18
|
import { execFileSync, spawn } from "node:child_process";
|
|
19
19
|
import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
20
|
-
import { dirname, join } from "node:path";
|
|
20
|
+
import { basename, dirname, join } from "node:path";
|
|
21
21
|
import type { Decision } from "../../core/adapter.ts";
|
|
22
22
|
import { loadConfig, type Config } from "../../core/config.ts";
|
|
23
23
|
import { nowSec } from "../../core/clock.ts";
|
|
24
24
|
import { runDetectorsGated } from "../../core/incident-detectors.ts";
|
|
25
|
-
import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, rekeySpawnFile } from "../../core/guards.ts";
|
|
25
|
+
import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
|
|
26
26
|
import { postReply } from "../../core/notify.ts";
|
|
27
|
+
import { inboxPath } from "../../core/owner-ui.ts";
|
|
27
28
|
import { applyQueueEnv } from "../../core/queue/env.ts";
|
|
28
29
|
import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
|
|
29
30
|
import { readBlocks } from "../../core/metrics.ts";
|
|
@@ -259,6 +260,89 @@ function sizeOf(path: string): number {
|
|
|
259
260
|
}
|
|
260
261
|
}
|
|
261
262
|
|
|
263
|
+
// ---- owner inbox delivery (plan 20261024_2230 P3b) ----
|
|
264
|
+
// The phone page appends answers to <queue_state>/owner-inbox.jsonl — a protected state file, so
|
|
265
|
+
// no agent can forge an owner answer (guards refuse the write). Main's session delivers each
|
|
266
|
+
// record once as a user message (pi.sendUserMessage, no options: idle → a new turn, streaming →
|
|
267
|
+
// the steer queue), at turn end and on a 15 s timer while idle. The consumed-row count lives in
|
|
268
|
+
// <queue_state>/owner-inbox.cursor; subagent sessions never deliver and never move it.
|
|
269
|
+
|
|
270
|
+
/** Idle-poll interval for the owner inbox. */
|
|
271
|
+
export const OWNER_INBOX_POLL_MS = 15_000;
|
|
272
|
+
|
|
273
|
+
/** The delivered cursor: how many owner-inbox rows Main's session has consumed. */
|
|
274
|
+
export function ownerInboxCursorPath(): string {
|
|
275
|
+
return `${q.stateDirPath()}/owner-inbox.cursor`;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function readOwnerInboxCursor(): number {
|
|
279
|
+
try {
|
|
280
|
+
const n = Number(readFileSync(ownerInboxCursorPath(), "utf8").trim());
|
|
281
|
+
return Number.isInteger(n) && n >= 0 ? n : 0;
|
|
282
|
+
} catch {
|
|
283
|
+
return 0;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function writeOwnerInboxCursor(n: number): void {
|
|
288
|
+
try {
|
|
289
|
+
mkdirSync(q.stateDirPath(), { recursive: true });
|
|
290
|
+
writeFileSync(ownerInboxCursorPath(), `${n}\n`);
|
|
291
|
+
} catch {}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** The user message one inbox record becomes, or null when it is not a page answer. */
|
|
295
|
+
export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
|
|
296
|
+
const plan = asString(rec.plan);
|
|
297
|
+
const question = asString(rec.question);
|
|
298
|
+
const answer = asString(rec.answer);
|
|
299
|
+
if (!plan || !question || !answer) return null;
|
|
300
|
+
return `Owner answered on the phone page — ${basename(plan)}: ${question} → ${answer}`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** The JSONL rows after `cursor` (a row count), as records, plus the new cursor. A torn last row
|
|
304
|
+
* (a page write that has not landed completely) stays unconsumed; a malformed complete row is
|
|
305
|
+
* consumed but skipped, so one bad line cannot wedge delivery. */
|
|
306
|
+
export function pendingInboxRecords(text: string, cursor: number): { records: Record<string, unknown>[]; next: number } {
|
|
307
|
+
const endsClean = text === "" || text.endsWith("\n");
|
|
308
|
+
const rows = text.split("\n");
|
|
309
|
+
if (rows.length && rows[rows.length - 1] === "") rows.pop();
|
|
310
|
+
const records: Record<string, unknown>[] = [];
|
|
311
|
+
let next = Math.min(cursor, rows.length);
|
|
312
|
+
for (let i = cursor; i < rows.length; i++) {
|
|
313
|
+
const torn = i === rows.length - 1 && !endsClean;
|
|
314
|
+
try {
|
|
315
|
+
const rec: unknown = JSON.parse((rows[i] ?? "").trim());
|
|
316
|
+
if (rec !== null && typeof rec === "object" && !Array.isArray(rec)) records.push(rec as Record<string, unknown>);
|
|
317
|
+
} catch {}
|
|
318
|
+
if (!torn) next = i + 1;
|
|
319
|
+
}
|
|
320
|
+
return { records, next };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Deliver every inbox row past the cursor once, as a user message to Main; then store the cursor.
|
|
324
|
+
* Synchronous, so the turn-end path and the idle timer cannot interleave. */
|
|
325
|
+
export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
|
|
326
|
+
let text: string;
|
|
327
|
+
try {
|
|
328
|
+
text = readFileSync(inboxPath(), "utf8");
|
|
329
|
+
} catch {
|
|
330
|
+
return; // no inbox yet: nothing to deliver
|
|
331
|
+
}
|
|
332
|
+
const cursor = readOwnerInboxCursor();
|
|
333
|
+
const { records, next } = pendingInboxRecords(text, cursor);
|
|
334
|
+
if (next === cursor) return;
|
|
335
|
+
let delivered = 0;
|
|
336
|
+
for (const rec of records) {
|
|
337
|
+
const msg = ownerInboxMessage(rec);
|
|
338
|
+
if (msg === null) continue;
|
|
339
|
+
pi.sendUserMessage(msg);
|
|
340
|
+
delivered++;
|
|
341
|
+
}
|
|
342
|
+
writeOwnerInboxCursor(next);
|
|
343
|
+
adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
|
|
344
|
+
}
|
|
345
|
+
|
|
262
346
|
/** Register the guard handlers on one extension host. `cfg` is injectable for tests. */
|
|
263
347
|
export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
264
348
|
// The queue library resolves its paths from env snapshots; point them at this config first.
|
|
@@ -267,6 +351,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
267
351
|
let callsSinceStop = 0;
|
|
268
352
|
let idleStops = 0;
|
|
269
353
|
let timer: unknown;
|
|
354
|
+
let inboxTimer: unknown;
|
|
270
355
|
const calls = new Map<string, number>(); // subagent call budget, by agent id
|
|
271
356
|
const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
|
|
272
357
|
// Chat notify (plan 20261024_2155): the last assistant text of the main session, and the text
|
|
@@ -286,6 +371,12 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
286
371
|
: setInterval(() => autoClose(cfg), every);
|
|
287
372
|
if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
|
|
288
373
|
timer = t;
|
|
374
|
+
// The owner-inbox poll (P3b): Main's session only — this handler returned for every other.
|
|
375
|
+
const it: unknown = c.setInterval
|
|
376
|
+
? c.setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS)
|
|
377
|
+
: setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS);
|
|
378
|
+
if (it && typeof it === "object" && "unref" in it && typeof it.unref === "function") it.unref();
|
|
379
|
+
inboxTimer = it;
|
|
289
380
|
});
|
|
290
381
|
|
|
291
382
|
pi.on("before_agent_start", (event, ctx) => {
|
|
@@ -388,6 +479,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
388
479
|
if (d.restore.text === null) rmSync(d.restore.path, { force: true });
|
|
389
480
|
else writeFileSync(d.restore.path, d.restore.text);
|
|
390
481
|
} catch {}
|
|
482
|
+
revertMainEdit(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), cfg);
|
|
391
483
|
return { isError: true, content: [{ type: "text", text: d.reason }] };
|
|
392
484
|
}
|
|
393
485
|
if (d.allow && (!c.hasAgent || c.kind === "main") && q.doneCount(after) > q.doneCount(before) && q.planAt(file, q.activePlans())) {
|
|
@@ -404,6 +496,9 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
404
496
|
const text = content.map(p => asString(asRecord(p).text)).join("\n");
|
|
405
497
|
recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
|
|
406
498
|
}
|
|
499
|
+
if ((!c.hasAgent || c.kind === "main") && e.isError) {
|
|
500
|
+
revertMainEdit(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), cfg);
|
|
501
|
+
}
|
|
407
502
|
// Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
|
|
408
503
|
if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
|
|
409
504
|
const content = Array.isArray(e.content) ? e.content : [];
|
|
@@ -656,6 +751,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
656
751
|
const text = lastAssistantText(rc.sessionFile);
|
|
657
752
|
lastReply = text.trim() ? text : null;
|
|
658
753
|
});
|
|
754
|
+
// Turn end: page answers that arrived during the turn go out now (P3b). Main only.
|
|
755
|
+
pi.on("agent_end", (_e, ctx) => {
|
|
756
|
+
if (isMain(ctx)) deliverOwnerInbox(pi, cfg);
|
|
757
|
+
});
|
|
659
758
|
|
|
660
759
|
// omp is really shutting down: the exit-grace fallback must not fire.
|
|
661
760
|
pi.on("session_shutdown", () => clearGrace?.());
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { runInit } from "./init.ts";
|
|
|
8
8
|
import { PORTED, runMain, runPorted } from "./commands.ts";
|
|
9
9
|
import { runMetrics } from "./metrics.ts";
|
|
10
10
|
import { runIncident } from "./incident.ts";
|
|
11
|
+
import { runUi } from "./ui.ts";
|
|
11
12
|
import { runUninstall } from "../core/uninstall.ts";
|
|
12
13
|
import { queueMigrate } from "../core/queue-migrate.ts";
|
|
13
14
|
import { allowedAgents, subagentsPath } from "../core/queue/lib.ts";
|
|
@@ -60,6 +61,7 @@ export function helpText(): string {
|
|
|
60
61
|
" neurastream main [args] run omp under the launcher (automatic session rollover)",
|
|
61
62
|
" neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
|
|
62
63
|
" neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
|
|
64
|
+
" neurastream ui serve the owner's phone page on the tailnet address (ui.enabled, ui.owner_login)",
|
|
63
65
|
" neurastream agents list | allow <slug>... | deny <slug>...",
|
|
64
66
|
" the subagent allow-list (## Allowed in notes/subagents.md)",
|
|
65
67
|
"",
|
|
@@ -80,6 +82,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
80
82
|
if (cmd === "init") return runInit(args);
|
|
81
83
|
if (cmd === "metrics") return runMetrics(args);
|
|
82
84
|
if (cmd === "incident") return runIncident(args);
|
|
85
|
+
if (cmd === "ui") return runUi();
|
|
83
86
|
if (cmd === "adapter") return runAdapterInstall(args);
|
|
84
87
|
if (cmd === "config") {
|
|
85
88
|
try {
|
package/src/cli/ui.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// `neurastream ui`: serve the owner's phone page on the tailnet address only. Refuses to start
|
|
2
|
+
// when the config has the page off or no owner login; the core startOwnerUi enforces the same
|
|
3
|
+
// two refusals. Runs until killed (systemd user unit templates/systemd/neurastream-ui.service).
|
|
4
|
+
|
|
5
|
+
import { defaultRunSource } from "../adapters/omp/sessions.ts";
|
|
6
|
+
import { ConfigError, loadConfig } from "../core/config.ts";
|
|
7
|
+
import { startOwnerUi } from "../core/owner-ui.ts";
|
|
8
|
+
import { applyQueueEnv } from "../core/queue/env.ts";
|
|
9
|
+
import { realTailscale } from "../core/tailscale.ts";
|
|
10
|
+
|
|
11
|
+
export function runUi(): number {
|
|
12
|
+
let cfg;
|
|
13
|
+
try {
|
|
14
|
+
cfg = loadConfig();
|
|
15
|
+
} catch (err) {
|
|
16
|
+
console.error(err instanceof ConfigError ? err.message : String(err));
|
|
17
|
+
return 1;
|
|
18
|
+
}
|
|
19
|
+
applyQueueEnv(cfg);
|
|
20
|
+
if (!cfg.ui.enabled) {
|
|
21
|
+
console.error("neurastream ui: ui.enabled is false — set it in the config first");
|
|
22
|
+
return 1;
|
|
23
|
+
}
|
|
24
|
+
if (!cfg.ui.owner_login) {
|
|
25
|
+
console.error("neurastream ui: ui.owner_login is empty — set the tailscale login that may open the page");
|
|
26
|
+
return 1;
|
|
27
|
+
}
|
|
28
|
+
startOwnerUi({ cfg, tailscale: realTailscale, source: defaultRunSource(cfg) });
|
|
29
|
+
return 0; // serving never returns; the process runs until killed
|
|
30
|
+
}
|
package/src/core/agent-score.ts
CHANGED
|
@@ -312,6 +312,53 @@ function board(days: number, cfg: Config, source: RunSource): void {
|
|
|
312
312
|
printText(text);
|
|
313
313
|
}
|
|
314
314
|
|
|
315
|
+
function exitUsage(cmd: string): number {
|
|
316
|
+
const doc = helpDoc("agent-score");
|
|
317
|
+
const line = doc.split("\n").find(l => l.trim().startsWith(`agent-score ${cmd}`));
|
|
318
|
+
const usage = line ? `usage: ${line.trim()}` : `usage: agent-score ${cmd}`;
|
|
319
|
+
process.stderr.write(`${usage}\n`);
|
|
320
|
+
return 2;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const CMD_OPTS: Record<string, { val: Record<string, true>; bool: Record<string, true> }> = {
|
|
324
|
+
accept: {
|
|
325
|
+
val: { "--plan": true, "--phase": true, "--commits": true, "--repo": true, "--branch": true, "--weight": true, "--units": true, "--note": true },
|
|
326
|
+
bool: { "--rework": true },
|
|
327
|
+
},
|
|
328
|
+
diagnose: {
|
|
329
|
+
val: { "--plan": true, "--phase": true, "--evidence": true, "--weight": true, "--note": true, "--repo": true, "--branch": true },
|
|
330
|
+
bool: {},
|
|
331
|
+
},
|
|
332
|
+
validate: {
|
|
333
|
+
val: { "--plan": true, "--phase": true, "--evidence": true, "--section": true, "--weight": true, "--note": true, "--repo": true, "--branch": true },
|
|
334
|
+
bool: { "--rework": true },
|
|
335
|
+
},
|
|
336
|
+
penalty: {
|
|
337
|
+
val: { "--kind": true, "--note": true, "--plan": true, "--repo": true, "--branch": true },
|
|
338
|
+
bool: {},
|
|
339
|
+
},
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
function parseScoreTarget(cmd: string, rest: string[]): { agent: string } | number {
|
|
343
|
+
const spec = CMD_OPTS[cmd];
|
|
344
|
+
if (!spec) return 0;
|
|
345
|
+
if (rest.length === 0 || rest[0]!.startsWith("-")) return exitUsage(cmd);
|
|
346
|
+
const agent = rest[0]!;
|
|
347
|
+
let i = 1;
|
|
348
|
+
while (i < rest.length) {
|
|
349
|
+
const arg = rest[i]!;
|
|
350
|
+
if (!arg.startsWith("-")) return exitUsage(cmd);
|
|
351
|
+
if (spec.bool[arg]) {
|
|
352
|
+
i++;
|
|
353
|
+
} else if (spec.val[arg]) {
|
|
354
|
+
i += 2;
|
|
355
|
+
} else {
|
|
356
|
+
return exitUsage(cmd);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return { agent };
|
|
360
|
+
}
|
|
361
|
+
|
|
315
362
|
export function agentScore(args: string[], cfg: Config, source: RunSource): number {
|
|
316
363
|
mkdirSync(cfg.paths.score_state, { recursive: true });
|
|
317
364
|
if (args.length < 1 || args[0] === "-h" || args[0] === "--help") {
|
|
@@ -324,10 +371,12 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
|
|
|
324
371
|
const branch = rest.includes("--branch") ? needOpt(rest, "--branch") : cfg.score.default_branch;
|
|
325
372
|
try {
|
|
326
373
|
if (cmd === "accept") {
|
|
327
|
-
const
|
|
374
|
+
const target = parseScoreTarget(cmd, rest);
|
|
375
|
+
if (typeof target === "number") return target;
|
|
376
|
+
const agent = target.agent;
|
|
328
377
|
const plan = opt(rest, "--plan");
|
|
329
378
|
const phase = opt(rest, "--phase");
|
|
330
|
-
if (!
|
|
379
|
+
if (!plan || !phase || !rest.includes("--commits")) return exitText("accept needs --plan, --phase, --commits");
|
|
331
380
|
if (!repo) return exitText("accept needs --repo");
|
|
332
381
|
const commits = expandCommits(repo, needOpt(rest, "--commits"));
|
|
333
382
|
const bad = commits.filter(c => gitRaw(repo, ["merge-base", "--is-ancestor", c, branch]).code).map(c => c.slice(0, 10));
|
|
@@ -341,11 +390,13 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
|
|
|
341
390
|
return 0;
|
|
342
391
|
}
|
|
343
392
|
if (cmd === "diagnose") {
|
|
344
|
-
const
|
|
393
|
+
const target = parseScoreTarget(cmd, rest);
|
|
394
|
+
if (typeof target === "number") return target;
|
|
395
|
+
const agent = target.agent;
|
|
345
396
|
const plan = opt(rest, "--plan");
|
|
346
397
|
const phase = opt(rest, "--phase");
|
|
347
398
|
const ev = opt(rest, "--evidence");
|
|
348
|
-
if (!
|
|
399
|
+
if (!plan || !phase || !ev || !existsSync(ev)) return exitText("diagnose needs --plan, --phase and an existing --evidence file");
|
|
349
400
|
const weighted = rest.includes("--weight") ? weightFor(rest, plan, phase, cfg, cfg.score.diagnose_weight) : { w: cfg.score.diagnose_weight, src: "default" };
|
|
350
401
|
record({
|
|
351
402
|
type: "diagnose", agent, plan, phase, weight: weighted.w, weight_src: weighted.src, evidence: ev, note: opt(rest, "--note") ?? "",
|
|
@@ -353,12 +404,14 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
|
|
|
353
404
|
return 0;
|
|
354
405
|
}
|
|
355
406
|
if (cmd === "validate") {
|
|
356
|
-
const
|
|
407
|
+
const target = parseScoreTarget(cmd, rest);
|
|
408
|
+
if (typeof target === "number") return target;
|
|
409
|
+
const agent = target.agent;
|
|
357
410
|
const plan = opt(rest, "--plan");
|
|
358
411
|
const phase = opt(rest, "--phase");
|
|
359
412
|
const ev = opt(rest, "--evidence");
|
|
360
413
|
const section = opt(rest, "--section");
|
|
361
|
-
if (!
|
|
414
|
+
if (!plan || !phase || !ev || !section) return exitText("validate needs --plan, --phase, --evidence and --section");
|
|
362
415
|
if (!phaseTicked(plan, phase)) return exitText(`refused: ${phase} not ticked in ${plan}`);
|
|
363
416
|
const { w, src } = weightFor(rest, plan, phase, cfg, null);
|
|
364
417
|
if (!existsSync(ev)) return exitText(`refused: evidence file not found: ${ev}`);
|
|
@@ -376,11 +429,14 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
|
|
|
376
429
|
return 0;
|
|
377
430
|
}
|
|
378
431
|
if (cmd === "penalty") {
|
|
432
|
+
const target = parseScoreTarget(cmd, rest);
|
|
433
|
+
if (typeof target === "number") return target;
|
|
434
|
+
const agent = target.agent;
|
|
379
435
|
const kind = opt(rest, "--kind");
|
|
380
436
|
const note = opt(rest, "--note");
|
|
381
437
|
const kinds = Object.keys(cfg.score.penalties);
|
|
382
438
|
if (!kind || !kinds.includes(kind) || !note) return exitText(`penalty needs --kind ${kinds.join("|")} and --note`);
|
|
383
|
-
record({ type: "penalty", agent
|
|
439
|
+
record({ type: "penalty", agent, kind, plan: opt(rest, "--plan") ?? "", note }, cfg);
|
|
384
440
|
return 0;
|
|
385
441
|
}
|
|
386
442
|
if (cmd === "exempt") {
|
package/src/core/config.ts
CHANGED
|
@@ -120,6 +120,8 @@ export interface Config {
|
|
|
120
120
|
protected: string[];
|
|
121
121
|
ledger_command: string;
|
|
122
122
|
};
|
|
123
|
+
/** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
|
|
124
|
+
ui: { enabled: boolean; port: number; owner_login: string };
|
|
123
125
|
rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
|
|
124
126
|
metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
|
|
125
127
|
/** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
|
|
@@ -293,6 +295,7 @@ function check(cfg: Config): void {
|
|
|
293
295
|
if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
|
|
294
296
|
if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
|
|
295
297
|
if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
|
|
298
|
+
if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
|
|
296
299
|
for (const p of cfg.metrics.correction_patterns) {
|
|
297
300
|
try {
|
|
298
301
|
new RegExp(p, "i");
|
package/src/core/guards.ts
CHANGED
|
@@ -58,7 +58,7 @@ function windowFile(): string {
|
|
|
58
58
|
return path.join(q.STATE_DIR, "edit-window.json");
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
function readWindow(): EditWindow {
|
|
61
|
+
export function readWindow(): EditWindow {
|
|
62
62
|
try {
|
|
63
63
|
const w = JSON.parse(readFileSync(windowFile(), "utf8")) as EditWindow;
|
|
64
64
|
if (Array.isArray(w.used) && typeof w.windowStart === "number") return w;
|
|
@@ -66,7 +66,7 @@ function readWindow(): EditWindow {
|
|
|
66
66
|
return { used: [], windowStart: 0 };
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
-
function writeWindow(w: EditWindow): void {
|
|
69
|
+
export function writeWindow(w: EditWindow): void {
|
|
70
70
|
try {
|
|
71
71
|
mkdirSync(q.STATE_DIR, { recursive: true });
|
|
72
72
|
writeFileSync(windowFile(), JSON.stringify(w, null, 1));
|
|
@@ -352,6 +352,28 @@ function runsCloser(input: Record<string, unknown>): boolean {
|
|
|
352
352
|
});
|
|
353
353
|
}
|
|
354
354
|
|
|
355
|
+
// True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
|
|
356
|
+
// serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
|
|
357
|
+
// owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
|
|
358
|
+
// skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
|
|
359
|
+
function startsOwnerUi(input: Record<string, unknown>): boolean {
|
|
360
|
+
const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
|
|
361
|
+
const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
|
|
362
|
+
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
363
|
+
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
364
|
+
let i = 0;
|
|
365
|
+
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
|
|
366
|
+
const cmd = bin(words[i]);
|
|
367
|
+
if ((cmd === "ui" && bin(words[i - 1]) === "neurastream") || (cmd === "neurastream" && bin(words[i + 1]) === "ui")) return true;
|
|
368
|
+
return (
|
|
369
|
+
cmd === "systemctl" &&
|
|
370
|
+
words.some(w => w === "--user") &&
|
|
371
|
+
words.some(w => w === "start" || w === "restart" || w === "enable") &&
|
|
372
|
+
words.some(w => bin(w) === "neurastream-ui" || w.startsWith("neurastream-ui."))
|
|
373
|
+
);
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
355
377
|
// Subagent half of a tool call (the original plan-guard checkCall without the main return).
|
|
356
378
|
// `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
|
|
357
379
|
function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
|
|
@@ -360,7 +382,11 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
|
|
|
360
382
|
return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
|
|
361
383
|
const plans = q.activePlans();
|
|
362
384
|
if (e.calls >= cap) {
|
|
363
|
-
|
|
385
|
+
// Plan edit targets come from writeTargets (write and structured/hashline edit)
|
|
386
|
+
// with touchedPaths as fallback; plan reads match any read tool.
|
|
387
|
+
const planEdit =
|
|
388
|
+
(e.tool === "write" || e.tool === "edit") &&
|
|
389
|
+
(writes.length > 0 ? writes.every(p => q.planAt(p, plans)) : paths.length > 0 && paths.every(p => q.planAt(p, plans)));
|
|
364
390
|
const planRead = cfg.guards.read_tools.includes(e.tool) && paths.length > 0 && paths.every(p => q.planAt(p, plans));
|
|
365
391
|
if (!planEdit && !planRead)
|
|
366
392
|
return `call budget spent (${e.calls}/${cap}). Only reading and editing your plan's "## Progress" is allowed now: write what you did, what is verified, what is next, then end your run.`;
|
|
@@ -509,6 +535,14 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
|
|
|
509
535
|
export function checkTool(e: ToolEvent, cfg: Config): Decision {
|
|
510
536
|
if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
|
|
511
537
|
const input = e.input ?? {};
|
|
538
|
+
// Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
|
|
539
|
+
// agent's, unlocked or not: refused plan-guard style like a protected-file write.
|
|
540
|
+
if (cfg.guards.shell_tools.includes(e.tool) && startsOwnerUi(input)) {
|
|
541
|
+
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ui-start: ${String(input.command ?? "")}`);
|
|
542
|
+
return deny(
|
|
543
|
+
"plan-guard: starting the owner page (neurastream ui, or systemctl --user start/restart/enable of neurastream-ui) is the owner's move, not an agent's.",
|
|
544
|
+
);
|
|
545
|
+
}
|
|
512
546
|
// The caller may know paths the text search cannot see (structured edits); union, never shrink.
|
|
513
547
|
const paths: string[] = [];
|
|
514
548
|
for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
|
|
@@ -604,6 +638,18 @@ function recordMainReads(files: string[], now = Date.now()): void {
|
|
|
604
638
|
* Main's tool result: each `path:line:` at a line start (grep -n / grep -rn output) names a file
|
|
605
639
|
* Main read. Paths resolve against the directory the call ran in (its `cwd`, then any `cd`).
|
|
606
640
|
*/
|
|
641
|
+
export function revertMainEdit(tool: string, input: Record<string, unknown>, cwd: string, cfg: Config): void {
|
|
642
|
+
const files = changedProjectFiles(tool, input, cwd, cfg);
|
|
643
|
+
if (!files.length) return;
|
|
644
|
+
const w = readWindow();
|
|
645
|
+
const entry = `${tool}:${files[0]!}`;
|
|
646
|
+
const idx = w.used.lastIndexOf(entry);
|
|
647
|
+
if (idx >= 0) {
|
|
648
|
+
w.used.splice(idx, 1);
|
|
649
|
+
writeWindow(w);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
607
653
|
export function recordMainResult(tool: string, input: Record<string, unknown>, cwd: string, text: string): void {
|
|
608
654
|
const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
|
|
609
655
|
const dir = q.shellCwd(String(input.command ?? input.code ?? ""), base);
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
// Owner phone page (plan 20261024_2230): one server-rendered page over Tailscale that shows the
|
|
2
|
+
// questions waiting on the owner, the guard unlock, the running agents, the queue, recent CI,
|
|
3
|
+
// open incidents, agent scores and machine health. Answers are appended to the owner inbox
|
|
4
|
+
// (<queue_state>/owner-inbox.jsonl) where the adapter picks them up; unlock/lock go through the
|
|
5
|
+
// core chatUnlock. Every section is built from the existing core readers, never by shelling out
|
|
6
|
+
// to a CLI. Tailscale is an injected Tailscale value (src/core/tailscale.ts has the real one) so
|
|
7
|
+
// tests never call the binary; the peer address is an injectable seam too, so tests bind
|
|
8
|
+
// 127.0.0.1 while the real server binds only the tailnet address from `tailscale ip -4`.
|
|
9
|
+
|
|
10
|
+
import { appendFileSync, mkdirSync, readFileSync, statSync, statfsSync } from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import { basename } from "node:path";
|
|
13
|
+
import type { RunSource } from "./adapter.ts";
|
|
14
|
+
import type { Config } from "./config.ts";
|
|
15
|
+
import { nowSec, strftime } from "./clock.ts";
|
|
16
|
+
import { cpuCount } from "./host.ts";
|
|
17
|
+
import { openIncidents } from "./incidents.ts";
|
|
18
|
+
import { log } from "./guards.ts";
|
|
19
|
+
import { readMetricEvents } from "./metrics.ts";
|
|
20
|
+
import { activePlans, chatUnlock, expandHome, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
|
|
21
|
+
import type { Tailscale } from "./tailscale.ts";
|
|
22
|
+
|
|
23
|
+
const ANSWER_MAX = 2000;
|
|
24
|
+
const REFRESH_SEC = 20;
|
|
25
|
+
// Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
|
|
26
|
+
const TAILNET6 = /^fd7a:115c:a1e0:/i;
|
|
27
|
+
|
|
28
|
+
/** The slice of Bun's server the page needs: the peer address of a request. Bun.serve's return satisfies it. */
|
|
29
|
+
export interface UiHttpServer {
|
|
30
|
+
requestIP(req: Request): { address: string; family: string; port: number } | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface OwnerUiServer {
|
|
34
|
+
stop(): void;
|
|
35
|
+
hostname: string;
|
|
36
|
+
port: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface OwnerUiOptions {
|
|
40
|
+
cfg: Config;
|
|
41
|
+
tailscale: Tailscale;
|
|
42
|
+
source: RunSource;
|
|
43
|
+
/** Bind address. Default: the tailnet address from `tailscale ip -4`. Tests bind 127.0.0.1. */
|
|
44
|
+
hostname?: string;
|
|
45
|
+
/** Bind port. Default: ui.port; 0 picks a free port (tests). */
|
|
46
|
+
port?: number;
|
|
47
|
+
/** The peer address of a request. Default: the socket address. Tests inject fixture peers. */
|
|
48
|
+
peerOf?: (req: Request, server: UiHttpServer) => string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type Auth = { ok: true; login: string } | { ok: false; why: string };
|
|
52
|
+
|
|
53
|
+
/** The inbox the page appends answers to and the adapter delivers from: under the queue state dir. */
|
|
54
|
+
export function inboxPath(): string {
|
|
55
|
+
return `${stateDirPath()}/owner-inbox.jsonl`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isLoopback(peer: string): boolean {
|
|
59
|
+
return peer === "::1" || peer === "localhost" || peer.startsWith("127.");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isTailnet(peer: string): boolean {
|
|
63
|
+
const v4 = /^(\d+)\.(\d+)\./.exec(peer);
|
|
64
|
+
if (v4) return v4[1] === "100" && Number(v4[2]) >= 64 && Number(v4[2]) <= 127;
|
|
65
|
+
return TAILNET6.test(peer);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals ui.owner_login. Everything else is a 403. */
|
|
69
|
+
export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): Auth {
|
|
70
|
+
if (!cfg.ui.owner_login) return { ok: false, why: "ui.owner_login is empty" };
|
|
71
|
+
if (isLoopback(peer)) return { ok: false, why: "loopback peer" };
|
|
72
|
+
if (!isTailnet(peer)) return { ok: false, why: "peer is not a tailnet address" };
|
|
73
|
+
if (peer === tailscale.ip4()) return { ok: false, why: "this machine's own tailnet address" };
|
|
74
|
+
const login = tailscale.whois(peer);
|
|
75
|
+
if (!login) return { ok: false, why: "tailscale whois failed" };
|
|
76
|
+
if (login !== cfg.ui.owner_login) return { ok: false, why: "not the owner's login" };
|
|
77
|
+
return { ok: true, login };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---- sections ----
|
|
81
|
+
|
|
82
|
+
interface Section {
|
|
83
|
+
title: string;
|
|
84
|
+
body: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function section(title: string, build: () => string): Section {
|
|
88
|
+
try {
|
|
89
|
+
return { title, body: build() };
|
|
90
|
+
} catch {
|
|
91
|
+
// One unreadable source must never take the page down.
|
|
92
|
+
return { title, body: "<p>unavailable</p>" };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function esc(s: string): string {
|
|
97
|
+
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function answerForm(plan: Plan): string {
|
|
101
|
+
return [
|
|
102
|
+
`<form method="post" action="/answer">`,
|
|
103
|
+
`<input type="hidden" name="plan" value="${esc(plan.file)}">`,
|
|
104
|
+
`<p><strong>${esc(basename(plan.file))}</strong><br>${esc(plan.waitingLine ?? "")}</p>`,
|
|
105
|
+
`<button type="submit" name="answer" value="yes">yes</button>`,
|
|
106
|
+
`<button type="submit" name="answer" value="no">no</button>`,
|
|
107
|
+
`<input type="text" name="answer_text" maxlength="${ANSWER_MAX}" placeholder="short answer">`,
|
|
108
|
+
`<button type="submit">send</button>`,
|
|
109
|
+
`</form>`,
|
|
110
|
+
].join("\n");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function questionsBody(cfg: Config): string {
|
|
114
|
+
const waiting = activePlans(cfg.paths.queue_index).filter(p => p.waiting && p.status === "open" && p.waitingLine);
|
|
115
|
+
return waiting.length ? waiting.map(answerForm).join("\n") : "<p>nothing is waiting on you</p>";
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function guardsBody(cfg: Config): string {
|
|
119
|
+
let state = "<p>guards locked</p>";
|
|
120
|
+
try {
|
|
121
|
+
const end = statSync(unlockPath()).mtimeMs + cfg.guards.unlock_minutes * 60_000;
|
|
122
|
+
const left = Math.round((end - Date.now()) / 60_000);
|
|
123
|
+
if (left > 0) state = `<p>guards <strong>unlocked</strong> for ~${left} more min</p>`;
|
|
124
|
+
} catch {}
|
|
125
|
+
const button = (minutes: number) =>
|
|
126
|
+
`<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"><button type="submit">unlock ${minutes}</button></form>`;
|
|
127
|
+
return [
|
|
128
|
+
state,
|
|
129
|
+
button(5),
|
|
130
|
+
button(15),
|
|
131
|
+
button(30),
|
|
132
|
+
`<form method="post" action="/lock"><button type="submit">lock now</button></form>`,
|
|
133
|
+
].join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function agentsBody(cfg: Config, source: RunSource): string {
|
|
137
|
+
const cut = nowSec() - cfg.ledger.default_hours * 3600;
|
|
138
|
+
const live = source
|
|
139
|
+
.listRuns(cut)
|
|
140
|
+
.filter(r => r.status === "running" || r.status === "waiting")
|
|
141
|
+
.map(r => `${r.id} ${r.statusDetail} ${r.model}`);
|
|
142
|
+
return live.length ? `<pre>${esc(live.join("\n"))}</pre>` : "<p>no agents running or waiting</p>";
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function queueBody(cfg: Config): string {
|
|
146
|
+
const plans = activePlans(cfg.paths.queue_index).map(
|
|
147
|
+
p => `${basename(p.file)} — ${p.status ?? "?"}${p.waiting ? " — WAITING on owner" : ""}`,
|
|
148
|
+
);
|
|
149
|
+
return plans.length ? `<pre>${esc(plans.join("\n"))}</pre>` : "<p>the queue is empty</p>";
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function ciBody(cfg: Config): string {
|
|
153
|
+
const rows = readMetricEvents(cfg)
|
|
154
|
+
.filter(e => e.type === "ci")
|
|
155
|
+
.slice(-10)
|
|
156
|
+
.reverse()
|
|
157
|
+
.map(e => `${String(e.mr)} — ${Number(e.tries)} pipeline(s) — ${strftime(Number(e.ts), "%m-%d %H:%M")}`);
|
|
158
|
+
return rows.length ? `<pre>${esc(rows.join("\n"))}</pre>` : "<p>no CI runs recorded</p>";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function incidentsBody(cfg: Config): string {
|
|
162
|
+
const open = openIncidents(cfg).map(i => `${i.id} [${i.source}/${i.kind}] ${i.summary}${i.count > 1 ? ` — ${i.count}x` : ""}`);
|
|
163
|
+
return open.length ? `<pre>${esc(open.join("\n"))}</pre>` : "<p>no open incidents</p>";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function scoresBody(cfg: Config): string {
|
|
167
|
+
return `<pre>${esc(readFileSync(cfg.paths.ranking_board, "utf8").trimEnd())}</pre>`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function machineBody(cfg: Config): string {
|
|
171
|
+
const st = statfsSync(expandHome(cfg.machine.disk_path));
|
|
172
|
+
const freeGb = (Number(st.bavail) * Number(st.bsize)) / 1e9;
|
|
173
|
+
const load = os.loadavg()[0] ?? 0;
|
|
174
|
+
const cores = cpuCount();
|
|
175
|
+
const loadMax = cfg.machine.load_max > 0 ? cfg.machine.load_max : cores + cfg.machine.load_over_cores;
|
|
176
|
+
const disk = `disk ${freeGb.toFixed(0)} GB free in ${cfg.machine.disk_path} (min ${cfg.machine.disk_min_gb} GB)${freeGb < cfg.machine.disk_min_gb ? " — LOW" : ""}`;
|
|
177
|
+
const loadLine = `load ${load.toFixed(2)} on ${cores} cores (max ${loadMax})${load > loadMax ? " — HIGH" : ""}`;
|
|
178
|
+
return `<pre>${esc([disk, loadLine].join("\n"))}</pre>`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function buildSections(cfg: Config, source: RunSource): Section[] {
|
|
182
|
+
return [
|
|
183
|
+
section("Waiting on you", () => questionsBody(cfg)),
|
|
184
|
+
section("Guards", () => guardsBody(cfg)),
|
|
185
|
+
section("Agents", () => agentsBody(cfg, source)),
|
|
186
|
+
section("Queue", () => queueBody(cfg)),
|
|
187
|
+
section("Merges / CI", () => ciBody(cfg)),
|
|
188
|
+
section("Incidents", () => incidentsBody(cfg)),
|
|
189
|
+
section("Agent scores", () => scoresBody(cfg)),
|
|
190
|
+
section("Machine", () => machineBody(cfg)),
|
|
191
|
+
];
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function renderPage(sections: Section[]): string {
|
|
195
|
+
const body = sections.map(s => `<section><h2>${esc(s.title)}</h2>${s.body}</section>`).join("\n");
|
|
196
|
+
return `<!doctype html>
|
|
197
|
+
<html lang="en">
|
|
198
|
+
<head>
|
|
199
|
+
<meta charset="utf-8">
|
|
200
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
201
|
+
<meta http-equiv="refresh" content="${REFRESH_SEC}">
|
|
202
|
+
<title>neurastream</title>
|
|
203
|
+
<style>
|
|
204
|
+
:root { color-scheme: light dark; }
|
|
205
|
+
body { font-family: system-ui, sans-serif; margin: 0 auto; padding: 1rem; max-width: 40rem; font-size: 1.05rem; line-height: 1.45; }
|
|
206
|
+
section { border: 1px solid #8884; border-radius: 10px; padding: 0.75rem 1rem; margin-bottom: 1rem; }
|
|
207
|
+
h2 { font-size: 1.15rem; margin: 0 0 0.5rem; }
|
|
208
|
+
button { font-size: 1.15rem; padding: 0.55rem 1.1rem; margin: 0.2rem 0.2rem 0.2rem 0; border-radius: 8px; }
|
|
209
|
+
input[type=text] { font-size: 1.1rem; padding: 0.5rem; width: 55%; border-radius: 8px; }
|
|
210
|
+
pre { white-space: pre-wrap; margin: 0; font-size: 0.95rem; overflow-wrap: anywhere; }
|
|
211
|
+
form { margin: 0.3rem 0; }
|
|
212
|
+
@media (prefers-color-scheme: dark) { body { background: #111; color: #eee; } section { border-color: #6668; } }
|
|
213
|
+
@media (prefers-color-scheme: light) { body { background: #fff; color: #111; } }
|
|
214
|
+
</style>
|
|
215
|
+
</head>
|
|
216
|
+
<body>
|
|
217
|
+
${body}
|
|
218
|
+
</body>
|
|
219
|
+
</html>`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ---- request plumbing ----
|
|
223
|
+
|
|
224
|
+
async function fieldsOf(req: Request): Promise<Record<string, string>> {
|
|
225
|
+
const ct = req.headers.get("content-type") ?? "";
|
|
226
|
+
if (ct.includes("application/json")) {
|
|
227
|
+
const raw: unknown = await req.json();
|
|
228
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
229
|
+
return Object.fromEntries(Object.entries(raw as Record<string, unknown>).map(([k, v]) => [k, String(v)]));
|
|
230
|
+
}
|
|
231
|
+
const form = await req.formData();
|
|
232
|
+
return Object.fromEntries([...form.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function textRes(body: string, status: number): Response {
|
|
236
|
+
return new Response(`${body}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function redirect(): Response {
|
|
240
|
+
return new Response(null, { status: 303, headers: { location: "/" } });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function handleAnswer(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
244
|
+
const planFile = (fields.plan ?? "").trim();
|
|
245
|
+
const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
|
|
246
|
+
if (!planFile || !answer) return textRes("plan and answer are required", 400);
|
|
247
|
+
if (answer.length > ANSWER_MAX) return textRes(`answer is longer than ${ANSWER_MAX} chars`, 400);
|
|
248
|
+
const plan = activePlans(cfg.paths.queue_index).find(p => p.file === planFile);
|
|
249
|
+
if (!plan || plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
|
|
250
|
+
return textRes("plan is not open and waiting", 409);
|
|
251
|
+
}
|
|
252
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
253
|
+
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), plan: planFile, question: plan.waitingLine, answer, login })}\n`);
|
|
254
|
+
return redirect();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function handleUnlock(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
258
|
+
const minutes = fields.minutes ?? "";
|
|
259
|
+
if (minutes !== "" && !/^\d+$/.test(minutes)) return textRes("minutes must be a number", 400);
|
|
260
|
+
const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
|
|
261
|
+
if (!result.applied) return textRes("unlock refused: guards.chat_unlock is off", 409);
|
|
262
|
+
return redirect();
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function handleLock(cfg: Config, login: string): Response {
|
|
266
|
+
const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
|
|
267
|
+
if (!result.applied) return textRes("lock refused: guards.chat_unlock is off", 409);
|
|
268
|
+
return redirect();
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Starts the page. Refuses to start when ui.enabled is false or ui.owner_login is empty, and on the default hostname when tailscale does not answer. */
|
|
272
|
+
export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
|
|
273
|
+
const { cfg, tailscale, source } = opts;
|
|
274
|
+
if (!cfg.ui.enabled) throw new Error("owner ui: ui.enabled is false — set it in the config first");
|
|
275
|
+
if (!cfg.ui.owner_login) throw new Error("owner ui: ui.owner_login is empty — set the tailscale login that may open the page");
|
|
276
|
+
const hostname = opts.hostname ?? tailscale.ip4();
|
|
277
|
+
if (!hostname) throw new Error("owner ui: tailscale ip -4 did not answer — is tailscale up?");
|
|
278
|
+
const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
|
|
279
|
+
// Host allowlist (plan P3a): a DNS-rebinding page sends evil.example's Host with a matching
|
|
280
|
+
// Origin from the owner's own phone, so the peer and Origin checks alone pass it. On every
|
|
281
|
+
// request, before whois, the Host header must name this page — the tailnet address or the
|
|
282
|
+
// MagicDNS name (dnsName(), trailing dot stripped) — with the served port. Anything else is a
|
|
283
|
+
// 403 no matter whose peer it is. Built once, against the bound port (tests bind 0).
|
|
284
|
+
let allowedHosts: string[] | null = null;
|
|
285
|
+
const hostAllowed = (hostHeader: string, port: number | undefined): boolean => {
|
|
286
|
+
// No bound port (never expected): nothing is allowed — fail closed.
|
|
287
|
+
if (port === undefined) return false;
|
|
288
|
+
if (allowedHosts === null) {
|
|
289
|
+
const dns = tailscale.dnsName();
|
|
290
|
+
allowedHosts = [tailscale.ip4(), dns].filter((h): h is string => Boolean(h)).map(h => `${h}:${port}`);
|
|
291
|
+
}
|
|
292
|
+
return allowedHosts.includes(hostHeader);
|
|
293
|
+
};
|
|
294
|
+
const server = Bun.serve({
|
|
295
|
+
hostname,
|
|
296
|
+
port: opts.port ?? cfg.ui.port,
|
|
297
|
+
fetch: async (req, srv) => {
|
|
298
|
+
const url = new URL(req.url);
|
|
299
|
+
let code = 500;
|
|
300
|
+
let login: string | null = null;
|
|
301
|
+
let res: Response;
|
|
302
|
+
try {
|
|
303
|
+
const hostHeader = req.headers.get("host") ?? "";
|
|
304
|
+
if (!hostAllowed(hostHeader, srv.port)) {
|
|
305
|
+
res = textRes("forbidden: host is not this page", 403);
|
|
306
|
+
code = 403;
|
|
307
|
+
} else {
|
|
308
|
+
const auth = authenticate(cfg, tailscale, peerOf(req, srv));
|
|
309
|
+
if (!auth.ok) {
|
|
310
|
+
res = textRes("forbidden: this page serves only the owner", 403);
|
|
311
|
+
code = 403;
|
|
312
|
+
} else {
|
|
313
|
+
login = auth.login;
|
|
314
|
+
if (req.method === "POST" && req.headers.get("origin") !== `http://${hostHeader}`) {
|
|
315
|
+
res = textRes("forbidden: origin is not this page", 403);
|
|
316
|
+
code = 403;
|
|
317
|
+
} else if (req.method === "GET" && url.pathname === "/") {
|
|
318
|
+
res = new Response(renderPage(buildSections(cfg, source)), {
|
|
319
|
+
status: 200,
|
|
320
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
321
|
+
});
|
|
322
|
+
code = 200;
|
|
323
|
+
} else if (req.method === "POST" && url.pathname === "/answer") {
|
|
324
|
+
res = handleAnswer(cfg, await fieldsOf(req), login);
|
|
325
|
+
code = res.status;
|
|
326
|
+
} else if (req.method === "POST" && url.pathname === "/unlock") {
|
|
327
|
+
res = handleUnlock(cfg, await fieldsOf(req), login);
|
|
328
|
+
code = res.status;
|
|
329
|
+
} else if (req.method === "POST" && url.pathname === "/lock") {
|
|
330
|
+
res = handleLock(cfg, login);
|
|
331
|
+
code = res.status;
|
|
332
|
+
} else {
|
|
333
|
+
res = textRes("not found", 404);
|
|
334
|
+
code = 404;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
} catch {
|
|
339
|
+
res = textRes("internal error", 500);
|
|
340
|
+
code = 500;
|
|
341
|
+
}
|
|
342
|
+
log(cfg.paths.guard_log, `UI ${req.method} ${url.pathname} login=${login ?? "-"} → ${code}`);
|
|
343
|
+
return res;
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
return { stop: () => server.stop(true), hostname, port: Number(server.port) };
|
|
347
|
+
}
|
package/src/core/queue/lib.ts
CHANGED
|
@@ -297,11 +297,12 @@ export function planCovers(plan: Plan, p: string, plans: Plan[] = []): boolean {
|
|
|
297
297
|
}
|
|
298
298
|
|
|
299
299
|
export function planAt(p: string, plans: Plan[]): Plan | null {
|
|
300
|
-
const
|
|
300
|
+
const clean = p.replace(/:[\d+\-,]*(:raw)?$|:raw(:[\d+\-,]+)?$/, "");
|
|
301
|
+
const exact = plans.find(pl => pl.file === clean || pl.file === p);
|
|
301
302
|
if (exact) return exact;
|
|
302
|
-
const g = gitTop(
|
|
303
|
+
const g = gitTop(clean);
|
|
303
304
|
if (!g) return null;
|
|
304
|
-
const rel = path.relative(g.top,
|
|
305
|
+
const rel = path.relative(g.top, clean);
|
|
305
306
|
return plans.find(pl => pl.repo === g.repo && path.relative(pl.repo, pl.file) === rel) ?? null;
|
|
306
307
|
}
|
|
307
308
|
|
|
@@ -329,7 +330,7 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
|
|
|
329
330
|
const out = new Set<string>();
|
|
330
331
|
const base = typeof input?.cwd === "string" ? path.resolve(cwd, expandHome(input.cwd)) : cwd;
|
|
331
332
|
const add = (raw: string, from = base) => {
|
|
332
|
-
const s = expandHome(raw.trim());
|
|
333
|
+
const s = expandHome(raw.trim().replace(/:[\d+\-,]*(:raw)?$|:raw(:[\d+\-,]+)?$/, ""));
|
|
333
334
|
if (!s || s.includes("://")) return;
|
|
334
335
|
out.add(path.resolve(from, s));
|
|
335
336
|
};
|
|
@@ -362,10 +363,14 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
|
|
|
362
363
|
export const MUTATING =
|
|
363
364
|
/(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=\-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
|
|
364
365
|
|
|
366
|
+
export function withoutQuotedRedirects(code: string): string {
|
|
367
|
+
return code.replace(/'[^']*'/g, m => m.replace(/>/g, " ")).replace(/"(?:[^"\\]|\\.)*"/g, m => m.replace(/>/g, " "));
|
|
368
|
+
}
|
|
369
|
+
|
|
365
370
|
export function changesFiles(toolName: string, input: Record<string, unknown>): boolean {
|
|
366
371
|
if (toolName === "edit" || toolName === "ast_edit") return true;
|
|
367
372
|
if (toolName === "write") return true;
|
|
368
|
-
return SHELL_TOOLS.has(toolName) && MUTATING.test(String(input?.command ?? input?.code ?? ""));
|
|
373
|
+
return SHELL_TOOLS.has(toolName) && MUTATING.test(withoutQuotedRedirects(String(input?.command ?? input?.code ?? "")));
|
|
369
374
|
}
|
|
370
375
|
|
|
371
376
|
// P8: package-manager and cutover commands change the running guard package.
|
|
@@ -481,6 +486,8 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
|
|
|
481
486
|
return [...out];
|
|
482
487
|
}
|
|
483
488
|
if (toolName === "edit") {
|
|
489
|
+
const target = typeof input?.path === "string" ? input.path : typeof input?.file === "string" ? input.file : "";
|
|
490
|
+
if (target) add(target, cwd);
|
|
484
491
|
for (const m of String(input?.input ?? "").matchAll(/^\[([^\]\n]+?)#[0-9A-Fa-f]{4}\]/gm)) add(m[1] ?? "", cwd);
|
|
485
492
|
return [...out];
|
|
486
493
|
}
|
|
@@ -494,7 +501,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
|
|
|
494
501
|
// generic mutating heuristics fire on its text.
|
|
495
502
|
const pkgOp = packageOpTarget(code);
|
|
496
503
|
const subOp = subagentsOpWrites(code);
|
|
497
|
-
if (!MUTATING.test(code) && !pkgOp && !subOp) return [];
|
|
504
|
+
if (!MUTATING.test(withoutQuotedRedirects(code)) && !pkgOp && !subOp) return [];
|
|
498
505
|
let dir = typeof input?.cwd === "string" ? path.resolve(cwd, expandHome(input.cwd)) : cwd;
|
|
499
506
|
for (const seg of withoutHeredocBodies(code).split(/&&|\|\||;|\n|\|/)) {
|
|
500
507
|
const s = seg.trim();
|
|
@@ -503,9 +510,10 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
|
|
|
503
510
|
dir = path.resolve(dir, expandHome((cd[1] ?? "").replace(/^["']|["']$/g, "")));
|
|
504
511
|
continue;
|
|
505
512
|
}
|
|
506
|
-
|
|
513
|
+
const noQuotedRedirect = withoutQuotedRedirects(s);
|
|
514
|
+
for (const m of noQuotedRedirect.matchAll(/(?:^|[^0-9&>=\-])>{1,2}\s*([^\s&|;)<>]+)/g)) {
|
|
507
515
|
// A target with no letter, digit, `.` or `/` (`>,`) is prose, not a file.
|
|
508
|
-
const target = m[1] ?? "";
|
|
516
|
+
const target = (m[1] ?? "").replace(/^["']|["']$/g, "");
|
|
509
517
|
if (/[\p{L}\p{N}./]/u.test(target)) add(target, dir);
|
|
510
518
|
}
|
|
511
519
|
const words = s.split(/\s+/).filter(Boolean);
|
|
@@ -620,12 +628,13 @@ const CHAT_CMD = /^(unlock|lock)(?:\s+(\d+))?$/i;
|
|
|
620
628
|
/**
|
|
621
629
|
* Owner unlock by chat (guards.chat_unlock): the whole trimmed message, case-insensitive —
|
|
622
630
|
* "unlock" (open for guards.unlock_minutes), "unlock N" (open for exactly N minutes, N clamped
|
|
623
|
-
* to 1..unlock_minutes) or "lock" (close again). Only the adapter
|
|
624
|
-
* owner really typed; a model, a tool result or a machine prompt must
|
|
625
|
-
* is written or removed from the extension process
|
|
626
|
-
* not see the write. Every applied unlock/lock is
|
|
631
|
+
* to 1..unlock_minutes) or "lock" (close again). Only the adapter and the owner page call this,
|
|
632
|
+
* with text the owner really typed or tapped; a model, a tool result or a machine prompt must
|
|
633
|
+
* never reach it. The file is written or removed from the extension process (or the ui server),
|
|
634
|
+
* not through a tool call, so plan-guard does not see the write. Every applied unlock/lock is
|
|
635
|
+
* logged to the plan-guard log with `word` naming the entry point ("chat" or "ui").
|
|
627
636
|
*/
|
|
628
|
-
export function chatUnlock(text: string, cfg: Config, source: string): ChatUnlockResult {
|
|
637
|
+
export function chatUnlock(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatUnlockResult {
|
|
629
638
|
if (!cfg.guards.chat_unlock) return { applied: false };
|
|
630
639
|
const m = CHAT_CMD.exec(text.trim());
|
|
631
640
|
if (!m) return { applied: false };
|
|
@@ -633,7 +642,7 @@ export function chatUnlock(text: string, cfg: Config, source: string): ChatUnloc
|
|
|
633
642
|
if ((m[1] ?? "").toLowerCase() === "lock") {
|
|
634
643
|
rmSync(unlockPath(), { force: true });
|
|
635
644
|
try {
|
|
636
|
-
appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} LOCK
|
|
645
|
+
appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} LOCK ${word} source=${source}\n`);
|
|
637
646
|
} catch {}
|
|
638
647
|
return { applied: true, command: "lock" };
|
|
639
648
|
}
|
|
@@ -646,7 +655,7 @@ export function chatUnlock(text: string, cfg: Config, source: string): ChatUnloc
|
|
|
646
655
|
const past = (Date.now() - (minutes - n) * 60_000) / 1000; // utimesSync takes seconds
|
|
647
656
|
utimesSync(file, past, past);
|
|
648
657
|
try {
|
|
649
|
-
appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} UNLOCK
|
|
658
|
+
appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} UNLOCK ${word} source=${source} minutes=${n}\n`);
|
|
650
659
|
} catch {}
|
|
651
660
|
return { applied: true, command: "unlock", minutes: n };
|
|
652
661
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The only place that names the tailscale binary. The owner page (src/core/owner-ui.ts) takes
|
|
2
|
+
// a Tailscale value instead of calling these directly, so tests inject a fixture and never run
|
|
3
|
+
// the real binary or bind the real tailnet address.
|
|
4
|
+
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
|
|
7
|
+
export interface Tailscale {
|
|
8
|
+
/** This machine's tailnet IPv4 address (first line of `tailscale ip -4`), or null when tailscale fails or answers nothing. */
|
|
9
|
+
ip4(): string | null;
|
|
10
|
+
/** This machine's MagicDNS name (`Self.DNSName` of `tailscale status --self --json`), trailing dot stripped, or null on failure. */
|
|
11
|
+
dnsName(): string | null;
|
|
12
|
+
/** The login that owns the peer address (`User.LoginName` of `tailscale whois --json <peer>`), or null on failure. */
|
|
13
|
+
whois(peer: string): string | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function firstStdoutLine(args: string[]): string | null {
|
|
17
|
+
const r = spawnSync("tailscale", args, { encoding: "utf8", timeout: 8000 });
|
|
18
|
+
if (r.error || r.status !== 0) return null;
|
|
19
|
+
const line = (r.stdout ?? "").split("\n").map(l => l.trim()).filter(Boolean)[0];
|
|
20
|
+
return line || null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const realTailscale: Tailscale = {
|
|
24
|
+
ip4() {
|
|
25
|
+
return firstStdoutLine(["ip", "-4"]);
|
|
26
|
+
},
|
|
27
|
+
dnsName() {
|
|
28
|
+
try {
|
|
29
|
+
const r = spawnSync("tailscale", ["status", "--self", "--json"], { encoding: "utf8", timeout: 8000 });
|
|
30
|
+
if (r.error || r.status !== 0) return null;
|
|
31
|
+
const parsed = JSON.parse(r.stdout ?? "") as { Self?: { DNSName?: unknown } };
|
|
32
|
+
const name = parsed.Self?.DNSName;
|
|
33
|
+
return typeof name === "string" && name ? name.replace(/\.+$/, "") : null;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
whois(peer) {
|
|
39
|
+
const line = firstStdoutLine(["whois", "--json", peer]);
|
|
40
|
+
if (!line) return null;
|
|
41
|
+
try {
|
|
42
|
+
const parsed = JSON.parse(line) as { User?: { LoginName?: unknown } };
|
|
43
|
+
const login = parsed.User?.LoginName;
|
|
44
|
+
return typeof login === "string" && login ? login : null;
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
};
|
package/templates/config.yml
CHANGED
|
@@ -118,6 +118,11 @@ guards:
|
|
|
118
118
|
protected: []
|
|
119
119
|
ledger_command: "agent-ledger --hours 12"
|
|
120
120
|
|
|
121
|
+
ui:
|
|
122
|
+
enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
|
|
123
|
+
port: 7787
|
|
124
|
+
owner_login: "" # the tailscale login that may open the page; empty = the page refuses to start
|
|
125
|
+
|
|
121
126
|
rollover:
|
|
122
127
|
enabled: true
|
|
123
128
|
max_session_mb: 5
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# User unit for the owner's phone page (neurastream ui). The installer copies this into
|
|
2
|
+
# ~/.config/systemd/user/; agents never install or start it — the owner does, after setting
|
|
3
|
+
# ui.enabled and ui.owner_login in the config.
|
|
4
|
+
|
|
5
|
+
[Unit]
|
|
6
|
+
Description=neurastream owner page (neurastream ui)
|
|
7
|
+
After=network-online.target
|
|
8
|
+
|
|
9
|
+
[Service]
|
|
10
|
+
ExecStart=%h/.bun/bin/neurastream ui
|
|
11
|
+
Restart=on-failure
|
|
12
|
+
RestartSec=5
|
|
13
|
+
|
|
14
|
+
[Install]
|
|
15
|
+
WantedBy=default.target
|