neurastream 0.2.6 → 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.
@@ -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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
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
+ }
@@ -1,9 +1,10 @@
1
1
  // Queue model: ONE index — the main index lists plan files, one absolute path per line (templates/queue/TEMPLATE.md).
2
2
 
3
3
  import { createHash } from "node:crypto";
4
- import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
+ import { accessSync, appendFileSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
+ import type { Config } from "../config.ts";
7
8
 
8
9
  const HOME = os.homedir();
9
10
  // Base set by applyQueueEnv from paths.agent_dir. Specific QUEUE_* vars still win.
@@ -296,11 +297,12 @@ export function planCovers(plan: Plan, p: string, plans: Plan[] = []): boolean {
296
297
  }
297
298
 
298
299
  export function planAt(p: string, plans: Plan[]): Plan | null {
299
- const exact = plans.find(pl => pl.file === p);
300
+ const clean = p.replace(/:[\d+\-,]*(:raw)?$|:raw(:[\d+\-,]+)?$/, "");
301
+ const exact = plans.find(pl => pl.file === clean || pl.file === p);
300
302
  if (exact) return exact;
301
- const g = gitTop(p);
303
+ const g = gitTop(clean);
302
304
  if (!g) return null;
303
- const rel = path.relative(g.top, p);
305
+ const rel = path.relative(g.top, clean);
304
306
  return plans.find(pl => pl.repo === g.repo && path.relative(pl.repo, pl.file) === rel) ?? null;
305
307
  }
306
308
 
@@ -328,7 +330,7 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
328
330
  const out = new Set<string>();
329
331
  const base = typeof input?.cwd === "string" ? path.resolve(cwd, expandHome(input.cwd)) : cwd;
330
332
  const add = (raw: string, from = base) => {
331
- const s = expandHome(raw.trim());
333
+ const s = expandHome(raw.trim().replace(/:[\d+\-,]*(:raw)?$|:raw(:[\d+\-,]+)?$/, ""));
332
334
  if (!s || s.includes("://")) return;
333
335
  out.add(path.resolve(from, s));
334
336
  };
@@ -361,10 +363,14 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
361
363
  export const MUTATING =
362
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\()/;
363
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
+
364
370
  export function changesFiles(toolName: string, input: Record<string, unknown>): boolean {
365
371
  if (toolName === "edit" || toolName === "ast_edit") return true;
366
372
  if (toolName === "write") return true;
367
- 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 ?? "")));
368
374
  }
369
375
 
370
376
  // P8: package-manager and cutover commands change the running guard package.
@@ -480,6 +486,8 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
480
486
  return [...out];
481
487
  }
482
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);
483
491
  for (const m of String(input?.input ?? "").matchAll(/^\[([^\]\n]+?)#[0-9A-Fa-f]{4}\]/gm)) add(m[1] ?? "", cwd);
484
492
  return [...out];
485
493
  }
@@ -493,7 +501,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
493
501
  // generic mutating heuristics fire on its text.
494
502
  const pkgOp = packageOpTarget(code);
495
503
  const subOp = subagentsOpWrites(code);
496
- if (!MUTATING.test(code) && !pkgOp && !subOp) return [];
504
+ if (!MUTATING.test(withoutQuotedRedirects(code)) && !pkgOp && !subOp) return [];
497
505
  let dir = typeof input?.cwd === "string" ? path.resolve(cwd, expandHome(input.cwd)) : cwd;
498
506
  for (const seg of withoutHeredocBodies(code).split(/&&|\|\||;|\n|\|/)) {
499
507
  const s = seg.trim();
@@ -502,9 +510,10 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
502
510
  dir = path.resolve(dir, expandHome((cd[1] ?? "").replace(/^["']|["']$/g, "")));
503
511
  continue;
504
512
  }
505
- for (const m of s.matchAll(/(?:^|[^0-9&>=\-])>{1,2}\s*([^\s&|;)<>]+)/g)) {
513
+ const noQuotedRedirect = withoutQuotedRedirects(s);
514
+ for (const m of noQuotedRedirect.matchAll(/(?:^|[^0-9&>=\-])>{1,2}\s*([^\s&|;)<>]+)/g)) {
506
515
  // A target with no letter, digit, `.` or `/` (`>,`) is prose, not a file.
507
- const target = m[1] ?? "";
516
+ const target = (m[1] ?? "").replace(/^["']|["']$/g, "");
508
517
  if (/[\p{L}\p{N}./]/u.test(target)) add(target, dir);
509
518
  }
510
519
  const words = s.split(/\s+/).filter(Boolean);
@@ -568,6 +577,9 @@ function protectedPaths(): string[] {
568
577
  `${agent}/CANCELLED.md`,
569
578
  `${stateDirPath()}/`,
570
579
  `${agent}/config.yml`,
580
+ // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
581
+ // could rewrite it could point notify at its own webhook.
582
+ `${HOME}/.config/neurastream/config.yml`,
571
583
  `${agent}/notes/subagents.md`,
572
584
  `${agent}/.guard-unlock`,
573
585
  `${path.dirname(agent)}/git-no-verify-guard.mjs`,
@@ -603,6 +615,51 @@ export function unlocked(): boolean {
603
615
  }
604
616
  }
605
617
 
618
+ export interface ChatUnlockResult {
619
+ /** True when the text was a whole-message unlock/lock command that took effect. */
620
+ applied: boolean;
621
+ command?: "unlock" | "lock";
622
+ /** For an unlock: the minutes the existing mtime window stays open (for the owner notice). */
623
+ minutes?: number;
624
+ }
625
+
626
+ const CHAT_CMD = /^(unlock|lock)(?:\s+(\d+))?$/i;
627
+
628
+ /**
629
+ * Owner unlock by chat (guards.chat_unlock): the whole trimmed message, case-insensitive —
630
+ * "unlock" (open for guards.unlock_minutes), "unlock N" (open for exactly N minutes, N clamped
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").
636
+ */
637
+ export function chatUnlock(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatUnlockResult {
638
+ if (!cfg.guards.chat_unlock) return { applied: false };
639
+ const m = CHAT_CMD.exec(text.trim());
640
+ if (!m) return { applied: false };
641
+ const minutes = cfg.guards.unlock_minutes;
642
+ if ((m[1] ?? "").toLowerCase() === "lock") {
643
+ rmSync(unlockPath(), { force: true });
644
+ try {
645
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} LOCK ${word} source=${source}\n`);
646
+ } catch {}
647
+ return { applied: true, command: "lock" };
648
+ }
649
+ const want = m[2] === undefined ? minutes : Number(m[2]);
650
+ if (want < 1) return { applied: false }; // "unlock 0" is no unlock
651
+ const n = Math.min(want, minutes);
652
+ const file = unlockPath();
653
+ writeFileSync(file, "");
654
+ // Backdate the mtime so the existing window (mtime + unlock_minutes) closes after exactly n minutes.
655
+ const past = (Date.now() - (minutes - n) * 60_000) / 1000; // utimesSync takes seconds
656
+ utimesSync(file, past, past);
657
+ try {
658
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} UNLOCK ${word} source=${source} minutes=${n}\n`);
659
+ } catch {}
660
+ return { applied: true, command: "unlock", minutes: n };
661
+ }
662
+
606
663
  export function protectedHit(paths: string[]): string | null {
607
664
  for (const p of paths) for (const g of PROTECTED) if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
608
665
  return null;
@@ -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
+ };
@@ -25,4 +25,4 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
25
25
  |`neurastream incident list --open`|session start, before status reports, when a spawn or stop is blocked|
26
26
  |`machine-guard`, `heavy-run`|machine-guard at session start and before launches; every test run goes through heavy-run|
27
27
 
28
- Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min).
28
+ Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min), or — when `guards.chat_unlock` is on in the config — by typing `unlock 30` in chat (`lock` closes it again).
@@ -104,6 +104,7 @@ guards:
104
104
  main_edit_limit: 5
105
105
  main_window_min: 15
106
106
  unlock_minutes: 30
107
+ chat_unlock: false # the owner's whole chat message "unlock"/"unlock N"/"lock" moves the guard unlock file
107
108
  plan_read_max_hours: 24
108
109
  idle_stops: 3
109
110
  blocker_timeout_ms: 10000
@@ -117,6 +118,11 @@ guards:
117
118
  protected: []
118
119
  ledger_command: "agent-ledger --hours 12"
119
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
+
120
126
  rollover:
121
127
  enabled: true
122
128
  max_session_mb: 5
@@ -156,6 +162,11 @@ quota:
156
162
  reset_tz: "Asia/Shanghai"
157
163
  label: "quota"
158
164
 
165
+ notify:
166
+ discord_webhook_file: "" # file holding the Discord webhook URL; "" = off (README: Notify the owner)
167
+ slack_webhook_file: "" # file holding the Slack webhook URL; "" = off
168
+ prefix: "" # optional label prepended to each posted reply, e.g. "Main:"
169
+
159
170
  priority:
160
171
  sleep_sec: 120
161
172
 
@@ -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