neurastream 0.2.21 → 0.2.22

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 CHANGED
@@ -119,6 +119,10 @@ A request is served only when the peer is a tailnet address that is neither loop
119
119
 
120
120
  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.
121
121
 
122
+ ## Static pages (`neurastream pages`)
123
+
124
+ `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]` publishes an artifact and prints its MagicDNS URL. `pages list` lists published files and `pages off` stops the service. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served.
125
+
122
126
  ## Session rollover
123
127
 
124
128
  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,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.21",
3
+ "version": "0.2.22",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -1,3 +1,4 @@
1
+ import { pagesDoctor } from "../core/pages-doctor.ts";
1
2
  import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
2
3
  import { postReply } from "../core/notify.ts";
3
4
  import { applyQueueEnv } from "../core/queue/env.ts";
@@ -10,6 +11,7 @@ import { runMetrics } from "./metrics.ts";
10
11
  import { runIncident } from "./incident.ts";
11
12
  import { runTraces } from "./traces.ts";
12
13
  import { runUi } from "./ui.ts";
14
+ import { runPages } from "./pages.ts";
13
15
  import { runUninstall } from "../core/uninstall.ts";
14
16
  import { queueMigrate } from "../core/queue-migrate.ts";
15
17
  import { allowedAgents, subagentsPath } from "../core/queue/lib.ts";
@@ -80,6 +82,7 @@ export function helpText(): string {
80
82
  " one go: writes ui.enabled/owner_login (and port) into the config,",
81
83
  " installs and restarts the neurastream-ui user unit, prints the phone",
82
84
  " link; `neurastream ui off` stops and disables it, sets enabled: false",
85
+ " neurastream pages on|off|serve|publish|list host static files over the tailnet",
83
86
  " neurastream agents list | allow <slug>... | deny <slug>...",
84
87
  " the subagent allow-list (## Allowed in notes/subagents.md)",
85
88
  "",
@@ -102,6 +105,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
102
105
  if (cmd === "incident") return runIncident(args);
103
106
  if (cmd === "traces") return runTraces(args);
104
107
  if (cmd === "ui") return runUi(args);
108
+ if (cmd === "pages") return runPages(args);
105
109
  if (cmd === "adapter") return runAdapterInstall(args);
106
110
  if (cmd === "config") {
107
111
  try {
@@ -113,7 +117,10 @@ export async function run(cmd: string, args: string[]): Promise<number> {
113
117
  return 1;
114
118
  }
115
119
  }
116
- if (cmd === "doctor") return runDoctor();
120
+ if (cmd === "doctor") {
121
+ for (const warning of pagesDoctor()) console.warn(`warning: ${warning}`);
122
+ return runDoctor();
123
+ }
117
124
  if (cmd === "notify") return runNotify(args);
118
125
  if (cmd === "uninstall") return runUninstall(args);
119
126
  if (cmd === "queue" && args[0] === "migrate") {
@@ -0,0 +1,21 @@
1
+ import { readdirSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { defaultRunSource } from "../adapters/omp/sessions.ts";
4
+ import { loadConfig } from "../core/config.ts";
5
+ import { startPagesServer } from "../core/pages.ts";
6
+ import { pagesOff, pagesOn, publishPage, type Runner } from "../core/pages-setup.ts";
7
+ import { realTailscale, type Tailscale } from "../core/tailscale.ts";
8
+
9
+ export interface PagesDeps { home?: string; runner?: Runner; tailscale?: Tailscale }
10
+ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promise<number> {
11
+ const home=deps.home ?? homedir();
12
+ try {
13
+ if(args[0]==="on") { let port:number|undefined,dir:string|undefined; for(let i=1;i<args.length;i++){if(args[i]==="--port")port=Number(args[++i]);else if(args[i]==="--dir")dir=args[++i];else return 2;} return pagesOn({home,runner:deps.runner,tailscale:deps.tailscale,port,dir}); }
14
+ if(args[0]==="off"&&args.length===1)return pagesOff({home,runner:deps.runner});
15
+ const cfg=loadConfig({home});
16
+ if(args[0]==="serve"&&args.length===1){if(!cfg.pages.enabled)throw new Error("pages.enabled is false");startPagesServer({cfg,tailscale:deps.tailscale ?? realTailscale,source:defaultRunSource(cfg)});return new Promise<number>(()=>{});}
17
+ if(args[0]==="publish"&&args[1]){let force=false,name:string|undefined;for(const arg of args.slice(2)){if(arg==="--force")force=true;else if(!name)name=arg;else return 2;}const n=publishPage(args[1],name,force,cfg.pages.dir);const host=(deps.tailscale ?? realTailscale).dnsName() ?? "tailnet";console.log(`http://${host}:${cfg.pages.port}/${encodeURIComponent(n)}`);return 0;}
18
+ if(args[0]==="list"&&args.length===1){for(const f of readdirSync(cfg.pages.dir,{withFileTypes:true}).filter(e=>e.isFile()&&!e.name.startsWith(".")))console.log(f.name);return 0;}
19
+ } catch(e){console.error(e instanceof Error?e.message:String(e));return 1;}
20
+ console.error("usage: neurastream pages on [--port N] [--dir D] | off | serve | publish <file> [<name>] [--force] | list");return 2;
21
+ }
@@ -135,6 +135,8 @@ export interface Config {
135
135
  };
136
136
  /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
137
137
  ui: { enabled: boolean; port: number; owner_login: string };
138
+ /** Static pages hosted over the tailnet. */
139
+ pages: { enabled: boolean; port: number; dir: string };
138
140
  rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
139
141
  metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
140
142
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
@@ -405,6 +407,8 @@ function check(cfg: Config): void {
405
407
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
406
408
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
407
409
  if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
410
+ if (!Number.isInteger(cfg.pages.port) || cfg.pages.port < 1 || cfg.pages.port > 65535) throw new ConfigError("pages.port must be an integer between 1 and 65535");
411
+ if (typeof cfg.pages.dir !== "string" || cfg.pages.dir.length === 0) throw new ConfigError("pages.dir must be a non-empty path");
408
412
  for (const p of cfg.metrics.correction_patterns) {
409
413
  try {
410
414
  new RegExp(p, "i");
@@ -56,11 +56,11 @@ export function inboxPath(): string {
56
56
  return `${stateDirPath()}/owner-inbox.jsonl`;
57
57
  }
58
58
 
59
- function isLoopback(peer: string): boolean {
59
+ export function isLoopback(peer: string): boolean {
60
60
  return peer === "::1" || peer === "localhost" || peer.startsWith("127.");
61
61
  }
62
62
 
63
- function isTailnet(peer: string): boolean {
63
+ export function isTailnet(peer: string): boolean {
64
64
  const v4 = /^(\d+)\.(\d+)\./.exec(peer);
65
65
  if (v4) return v4[1] === "100" && Number(v4[2]) >= 64 && Number(v4[2]) <= 127;
66
66
  return TAILNET6.test(peer);
@@ -0,0 +1,14 @@
1
+ import { existsSync, lstatSync, readdirSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { configFile, loadConfig } from "./config.ts";
6
+ import { PAGES_UNIT_TEMPLATE, type Runner } from "./pages-setup.ts";
7
+
8
+ export function pagesDoctor(home=homedir(), runner:Runner=args=>{const r=spawnSync("systemctl",args,{encoding:"utf8"});return{status:r.status,stderr:r.stderr??""}}): string[] {
9
+ const warnings:string[]=[];let cfg;
10
+ try{cfg=loadConfig({home,file:configFile(home)});}catch(e){return [`pages config invalid: ${e instanceof Error?e.message:String(e)}`];}
11
+ if(cfg.pages.enabled){if(!existsSync(cfg.pages.dir))warnings.push(`pages directory missing: ${cfg.pages.dir}`);if(!existsSync(join(home,".config/systemd/user/neurastream-pages.service"))||!existsSync(PAGES_UNIT_TEMPLATE))warnings.push("pages unit file missing");const result=runner(["--user","is-active","neurastream-pages"]);if(result.status!==0)warnings.push("neurastream-pages unit is not active");}
12
+ if(existsSync(cfg.pages.dir)){try{if(readdirSync(cfg.pages.dir).some(name=>{try{return lstatSync(join(cfg.pages.dir,name)).isSymbolicLink();}catch{return false;}}))warnings.push("pages directory contains a symlink");}catch{}}
13
+ return warnings;
14
+ }
@@ -0,0 +1,53 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, basename, extname } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { configFile, loadConfig } from "./config.ts";
7
+ import { realTailscale, type Tailscale } from "./tailscale.ts";
8
+ const HERE = dirname(fileURLToPath(import.meta.url));
9
+ export const PAGES_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-pages.service");
10
+ export interface RunnerResult { status: number | null; stderr: string }
11
+ export type Runner = (args: string[]) => RunnerResult;
12
+ export const systemRunner: Runner = args => { const r = spawnSync("systemctl", args, { encoding:"utf8" }); return { status:r.status, stderr:r.stderr ?? "" }; };
13
+ export interface Setup { home?: string; runner?: Runner; tailscale?: Tailscale }
14
+ function editBlock(text: string | null, values: { enabled: boolean; port: number; dir: string }): string {
15
+ const fresh = ["pages:", ` enabled: ${values.enabled}`, ` port: ${values.port}`, ` dir: "${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`];
16
+ if (text === null) return `${fresh.join("\n")}\n`;
17
+ const lines = text.split("\n");
18
+ let start = -1;
19
+ for (let i = 0; i < lines.length; i++) if (/^pages\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) { start = i; break; }
20
+ if (start < 0) return `${text === "" || text.endsWith("\n") ? text : `${text}\n`}${fresh.join("\n")}\n`;
21
+ let end = start + 1;
22
+ while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
23
+ const setKey = (key: string, value: string): void => {
24
+ const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
25
+ for (let i = start + 1; i < end; i++) if (re.test(lines[i]!)) { lines[i] = lines[i]!.replace(re, `$1${key}: ${value}`); return; }
26
+ let at = start + 1;
27
+ for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
28
+ lines.splice(at, 0, ` ${key}: ${value}`); end++;
29
+ };
30
+ setKey("enabled", String(values.enabled)); setKey("port", String(values.port)); setKey("dir", `"${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`);
31
+ return lines.join("\n");
32
+ }
33
+ export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
34
+ const home = opts.home ?? homedir(), runner = opts.runner ?? systemRunner, ts = opts.tailscale ?? realTailscale;
35
+ const file = configFile(home), old = existsSync(file) ? readFileSync(file,"utf8") : null; const cfg = loadConfig({ home });
36
+ const port = opts.port ?? cfg.pages.port, dir = opts.dir ?? cfg.pages.dir;
37
+ const edited = editBlock(old, { enabled:true, port, dir }); mkdirSync(dirname(file), { recursive:true }); writeFileSync(file, edited);
38
+ mkdirSync(dir, { recursive:true });
39
+ mkdirSync(join(home,".config/systemd/user"),{recursive:true}); copyFileSync(PAGES_UNIT_TEMPLATE, join(home,".config/systemd/user/neurastream-pages.service"));
40
+ for (const args of [["--user","daemon-reload"],["--user","enable","--now","neurastream-pages"]]) { const r=runner(args); if(r.status!==0){console.error(r.stderr);return 1;} }
41
+ const dns=ts.dnsName(); console.log(`pages: http://${dns ?? ts.ip4() ?? "<tailnet>"}:${port}/`); return 0;
42
+ }
43
+ export function pagesOff(opts: Setup = {}): number {
44
+ const home=opts.home ?? homedir(), runner=opts.runner ?? systemRunner, file=configFile(home), old=existsSync(file)?readFileSync(file,"utf8"):null;
45
+ const cfg=loadConfig({home}); writeFileSync(file,editBlock(old,{enabled:false,port:cfg.pages.port,dir:cfg.pages.dir}));
46
+ const r=runner(["--user","stop","neurastream-pages"]); if(r.status!==0){console.error(r.stderr);return 1;} return 0;
47
+ }
48
+ export function publishPage(file: string, name: string | undefined, force: boolean, dir: string): string {
49
+ const source=basename(file), base=(name ?? source.slice(0,source.length-extname(source).length)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");
50
+ const targetName=base+extname(source).toLowerCase(), target=join(dir,targetName); mkdirSync(dir,{recursive:true});
51
+ if(existsSync(target)){const a=readFileSync(file),b=readFileSync(target); if(a.equals(b)) return targetName; if(!force) throw new Error(`pages: ${targetName} exists with different content (use --force)`);}
52
+ copyFileSync(file,target); return targetName;
53
+ }
@@ -0,0 +1,40 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
2
+ import { basename, extname, resolve } from "node:path";
3
+ import type { Config } from "./config.ts";
4
+ import { isLoopback, isTailnet, type UiHttpServer } from "./owner-ui.ts";
5
+ import type { RunSource } from "./adapter.ts";
6
+ import type { Tailscale } from "./tailscale.ts";
7
+
8
+ export interface PagesServer { stop(): void; hostname: string; port: number }
9
+ export interface PagesOptions { cfg: Config; tailscale: Tailscale; source: RunSource; hostname?: string; port?: number; peerOf?: (req: Request, server: UiHttpServer) => string; root?: string }
10
+ const MIME: Record<string, string> = { ".html":"text/html; charset=utf-8", ".css":"text/css; charset=utf-8", ".js":"text/javascript; charset=utf-8", ".mjs":"text/javascript; charset=utf-8", ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".jpeg":"image/jpeg", ".webp":"image/webp", ".json":"application/json", ".txt":"text/plain; charset=utf-8", ".ico":"image/x-icon", ".woff2":"font/woff2", ".map":"application/json" };
11
+ function urlPart(value: string): string { return encodeURI(value).replaceAll("?", "%3F").replaceAll("#", "%23").replaceAll('"', "%22").replaceAll("'", "%27"); }
12
+ function plain(body: string, status: number): Response { return new Response(body, { status, headers: { "content-type":"text/plain; charset=utf-8" } }); }
13
+ export function startPagesServer(opts: PagesOptions): PagesServer {
14
+ const hostname = opts.hostname ?? opts.tailscale.ip4();
15
+ if (!hostname) throw new Error("pages: tailscale ip -4 did not answer");
16
+ const root = resolve(opts.root ?? opts.cfg.pages.dir);
17
+ const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
18
+ const server = Bun.serve({ hostname, port: opts.port ?? opts.cfg.pages.port, async fetch(req, srv) {
19
+ if (req.method !== "GET" && req.method !== "HEAD") return plain("method not allowed", 405);
20
+ const peer = peerOf(req, srv);
21
+ const login = isLoopback(peer) ? null : isTailnet(peer) ? opts.tailscale.whois(peer) : null;
22
+ if (!isLoopback(peer) && (!login || login !== opts.cfg.ui.owner_login)) return plain("forbidden", 403);
23
+ const url = new URL(req.url); let name = decodeURI(url.pathname.slice(1));
24
+ if (name.includes("/") || name.includes("\\") || name === ".." || name.startsWith(".")) return plain("not found", 404);
25
+ if (!name) {
26
+ const index = resolve(root, "index.html");
27
+ if (existsSync(index) && lstatSync(index).isFile()) name = "index.html";
28
+ else {
29
+ const files = existsSync(root) ? readdirSync(root, { withFileTypes:true }).filter(e => !e.name.startsWith(".") && e.isFile()).map(e => e.name) : [];
30
+ const body = `<!doctype html><ul>${files.map(f => `<li><a href="/${urlPart(f)}">${f.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}</a></li>`).join("")}</ul>`;
31
+ return new Response(req.method === "HEAD" ? null : body, { headers:{ "content-type":"text/html; charset=utf-8" } });
32
+ }
33
+ }
34
+ const path = resolve(root, name);
35
+ if (basename(path) !== name || !existsSync(path) || !lstatSync(path).isFile()) return plain("not found", 404);
36
+ const type = MIME[extname(name).toLowerCase()] ?? "application/octet-stream";
37
+ return new Response(req.method === "HEAD" ? null : readFileSync(path), { headers:{ "content-type":type, ...(type === "application/octet-stream" ? { "content-disposition":`attachment; filename*=UTF-8''${urlPart(name)}` } : {}) } });
38
+ }});
39
+ return { stop: () => server.stop(true), hostname, port: Number(server.port) };
40
+ }
@@ -130,6 +130,11 @@ ui:
130
130
  port: 7787
131
131
  owner_login: "" # the tailscale login that may open the page; empty = the page refuses to start
132
132
 
133
+
134
+ pages:
135
+ enabled: false
136
+ port: 7788
137
+ dir: "~/.local/share/neurastream/pages"
133
138
  rollover:
134
139
  enabled: true
135
140
  max_session_mb: 5
@@ -0,0 +1,12 @@
1
+ # User unit for tailnet-hosted static pages.
2
+ [Unit]
3
+ Description=neurastream static pages
4
+ After=network-online.target
5
+
6
+ [Service]
7
+ ExecStart=%h/.bun/bin/neurastream pages serve
8
+ Restart=on-failure
9
+ RestartSec=5
10
+
11
+ [Install]
12
+ WantedBy=default.target