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.
package/README.md CHANGED
@@ -25,13 +25,14 @@ flowchart LR
25
25
  |---|---|
26
26
  | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. |
27
27
  | Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
28
- | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). |
28
+ | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). With `guards.chat_unlock` on (default off), the owner's whole chat message `unlock` / `unlock N` / `lock` — typed in the terminal or through a collab guest prompt from a write peer — moves that file instead; nothing a model, a subagent or a tool produces can. |
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs 2. |
30
30
  | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
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.
@@ -119,6 +128,46 @@ In both modes:
119
128
  - The previous session file stays where it is.
120
129
  - `rollover.enabled: false` turns the feature off.
121
130
 
131
+ ## Notify the owner
132
+
133
+ When Main's turn ends and the session stop hands back to the owner, neurastream posts Main's final reply to the configured chat channels — deterministic code in the adapter, no model call, no tokens, never forgotten. Discord, Slack, both, or neither: notify is off until a webhook file exists.
134
+
135
+ The webhook URL is a secret (anyone holding it can post as the bot), so it never goes into `config.yml`. The config holds the file's path only (`docs/config.md`):
136
+
137
+ ```yaml
138
+ notify:
139
+ discord_webhook_file: "~/.config/neurastream/secrets/discord-webhook" # "" = off
140
+ slack_webhook_file: "~/.config/neurastream/secrets/slack-webhook" # "" = off
141
+ prefix: "" # optional label prepended to each post, e.g. "Main:"
142
+ ```
143
+
144
+ Set a channel up:
145
+
146
+ - Discord: Server Settings → Integrations → Webhooks → New Webhook → copy the URL.
147
+ - Slack: add the "Incoming Webhooks" app to your workspace → copy the webhook URL for your channel.
148
+
149
+ Then write the URL into its secret file — as the owner, in a terminal (the guard refuses agents; the examples show the path, never a URL):
150
+
151
+ ```sh
152
+ umask 077
153
+ mkdir -p ~/.config/neurastream/secrets
154
+ printf '%s' '<url>' > ~/.config/neurastream/secrets/discord-webhook
155
+ chmod 600 ~/.config/neurastream/secrets/discord-webhook
156
+ ```
157
+
158
+ Repeat for `slack-webhook`, then check:
159
+
160
+ ```sh
161
+ neurastream doctor # problems: a loose file mode, a raw URL in config.yml, a secret next to config.yml; warning: a missing file
162
+ neurastream notify test # posts one line to every configured channel; exit 1 when one fails
163
+ ```
164
+
165
+ Guard rules around it:
166
+
167
+ - No agent (Main included) can read a configured secret file, list its directory, or glob over it — unlock or not. Writes to the secret files and to `~/.config/neurastream/config.yml` need the owner's unlock like any guard file.
168
+ - A stop the guard blocks posts nothing; when Main continues and really hands back later, that later stop posts the final text. A subagent session never posts, and a relaunch (the launcher's rollover) posts nothing.
169
+ - The post never delays the stop decision: it times out at 5 seconds per chunk, makes one attempt, and writes one guard-log line when a channel fails. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible.
170
+
122
171
  ## Self-metrics
123
172
 
124
173
  `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.6",
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": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
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",
@@ -11,7 +11,9 @@ import { dirname, join, relative, resolve } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { blockState, renderBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
+ import { notifyFindings } from "../../core/notify.ts";
14
15
  import { readIndex } from "../../core/queue/lib.ts";
16
+ import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
15
17
 
16
18
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
17
19
 
@@ -155,7 +157,7 @@ function npmViewVersion(name: string, env: NodeJS.ProcessEnv): { version: string
155
157
  return { version };
156
158
  }
157
159
 
158
- 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 {
159
161
  const pkg = readPackage(PACKAGE_ROOT);
160
162
  const name = pkg.name ?? "neurastream";
161
163
  const installed = pkg.version ?? "";
@@ -178,6 +180,13 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
178
180
  const agents = liveAgentsMd(home);
179
181
  const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
180
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
+ }
181
190
  // One index (20261024_1400_one_index): repo-directory lines in the main index are the old
182
191
  // two-level queue; the plans they hold are invisible to queue-check until migrate folds them.
183
192
  const idx = cfg.paths.queue_index;
@@ -196,6 +205,9 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
196
205
  if (state === "ok") ok.push(`${agents} neurastream block`);
197
206
  else problems.push(`${state}: ${agents} neurastream block`);
198
207
  const warnings: string[] = [];
208
+ const notify = notifyFindings(cfg);
209
+ problems.push(...notify.problems);
210
+ warnings.push(...notify.warnings);
199
211
  const viewed = npmViewVersion(name, env);
200
212
  let registry: string | null = null;
201
213
  if ("warning" in viewed) warnings.push(viewed.warning);
@@ -17,17 +17,19 @@
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
+ import { postReply } from "../../core/notify.ts";
27
+ import { inboxPath } from "../../core/owner-ui.ts";
26
28
  import { applyQueueEnv } from "../../core/queue/env.ts";
27
29
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
28
30
  import { readBlocks } from "../../core/metrics.ts";
29
31
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
30
- import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
32
+ import { defaultCompletedResults, defaultRunSource, lastAssistantText } from "./sessions.ts";
31
33
  import { packageJsonPath, packageVersion } from "./package-root.ts";
32
34
  import * as q from "../../core/queue/lib.ts";
33
35
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -258,6 +260,89 @@ function sizeOf(path: string): number {
258
260
  }
259
261
  }
260
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
+
261
346
  /** Register the guard handlers on one extension host. `cfg` is injectable for tests. */
262
347
  export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
263
348
  // The queue library resolves its paths from env snapshots; point them at this config first.
@@ -266,8 +351,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
266
351
  let callsSinceStop = 0;
267
352
  let idleStops = 0;
268
353
  let timer: unknown;
354
+ let inboxTimer: unknown;
269
355
  const calls = new Map<string, number>(); // subagent call budget, by agent id
270
356
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
357
+ // Chat notify (plan 20261024_2155): the last assistant text of the main session, and the text
358
+ // a stop already posted (attempted) — one post per distinct text, never a retry loop.
359
+ let lastReply: string | null = null;
360
+ let postedReply: string | null = null;
271
361
 
272
362
  pi.on("session_start", (_e, ctx) => {
273
363
  const c = asCtx(ctx);
@@ -281,6 +371,12 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
281
371
  : setInterval(() => autoClose(cfg), every);
282
372
  if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
283
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;
284
380
  });
285
381
 
286
382
  pi.on("before_agent_start", (event, ctx) => {
@@ -383,6 +479,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
383
479
  if (d.restore.text === null) rmSync(d.restore.path, { force: true });
384
480
  else writeFileSync(d.restore.path, d.restore.text);
385
481
  } catch {}
482
+ revertMainEdit(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), cfg);
386
483
  return { isError: true, content: [{ type: "text", text: d.reason }] };
387
484
  }
388
485
  if (d.allow && (!c.hasAgent || c.kind === "main") && q.doneCount(after) > q.doneCount(before) && q.planAt(file, q.activePlans())) {
@@ -399,6 +496,9 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
399
496
  const text = content.map(p => asString(asRecord(p).text)).join("\n");
400
497
  recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
401
498
  }
499
+ if ((!c.hasAgent || c.kind === "main") && e.isError) {
500
+ revertMainEdit(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), cfg);
501
+ }
402
502
  // Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
403
503
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
404
504
  const content = Array.isArray(e.content) ? e.content : [];
@@ -415,6 +515,17 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
415
515
  if (c.hasAgent && c.kind !== "main") return;
416
516
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
417
517
  if (relaunched) return undefined;
518
+ // The stop hands the turn back to the owner: post Main's final reply, once per distinct
519
+ // text. Fire-and-forget: the decision never awaits the post; a failed or slow post logs
520
+ // one line and never blocks or retries.
521
+ const notifyOwner = (): void => {
522
+ const text = lastReply;
523
+ if (!text || text === postedReply) return;
524
+ postedReply = text;
525
+ void postReply(text, cfg).then(results => {
526
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
527
+ });
528
+ };
418
529
  // A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
419
530
  // blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
420
531
  // agent" text is refused while the rollover is pending.
@@ -427,15 +538,21 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
427
538
  }
428
539
  if (snap.state === "ready" || snap.state === "wait-jobs") {
429
540
  adapterLog(cfg, `ALLOW stop: rollover ${snap.state}`);
430
- // Under the launcher a ready rollover starts now; plain omp waits for the owner's next message.
431
- if (snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1") requestRelaunch(rc, notePath(rc.sessionId));
541
+ // Under the launcher a ready rollover starts now (not a hand-back to the owner);
542
+ // plain omp waits for the owner's next message.
543
+ const handsToOwner = !(snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && requestRelaunch(rc, notePath(rc.sessionId)));
544
+ if (handsToOwner) notifyOwner();
432
545
  return undefined;
433
546
  }
434
547
  }
435
548
  const d = checkStop({ agent: "main", callsSinceStop, idleStops, ledgerText: ledgerText(cfg) }, cfg);
436
549
  callsSinceStop = d.state?.callsSinceStop ?? 0;
437
550
  idleStops = d.state?.idleStops ?? idleStops;
438
- return d.allow ? undefined : { decision: "block", reason: d.reason };
551
+ if (d.allow) {
552
+ notifyOwner();
553
+ return undefined;
554
+ }
555
+ return { decision: "block", reason: d.reason };
439
556
  });
440
557
 
441
558
  // Session rollover (src/core/rollover.ts). Main's session size decides when a handoff note is
@@ -623,6 +740,21 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
623
740
  }
624
741
  };
625
742
  pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
743
+ // The text a later allowed stop posts: the last assistant message of each terminal run end in
744
+ // the main session (omp 18.11.1 sets willContinue on a non-terminal end). A blocked stop keeps
745
+ // Main talking, so the final run end overwrites this before the stop that really hands back.
746
+ pi.on("agent_end", (e, ctx) => {
747
+ if (!isMain(ctx)) return;
748
+ if (asRecord(e).willContinue === true) return;
749
+ const rc = asRolloverCtx(ctx);
750
+ if (!rc) return;
751
+ const text = lastAssistantText(rc.sessionFile);
752
+ lastReply = text.trim() ? text : null;
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
+ });
626
758
 
627
759
  // omp is really shutting down: the exit-grace fallback must not fire.
628
760
  pi.on("session_shutdown", () => clearGrace?.());
@@ -653,6 +785,64 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
653
785
  return null;
654
786
  };
655
787
 
788
+ // Chat unlock (guards.chat_unlock): the owner's whole message "unlock"/"unlock N"/"lock" moves
789
+ // the guard unlock file (src/core/queue/lib.ts chatUnlock). Only prompts the owner really typed
790
+ // count: the local terminal (input event, source "interactive") and collab guest prompts from
791
+ // write peers. This handler is registered BEFORE the rollover input handler below, so the unlock
792
+ // wins while a rollover is ready or in flight (emitInput short-circuits on { handled: true }).
793
+ const notifyUnlock = (ctx: unknown, r: { command?: "unlock" | "lock"; minutes?: number }): void => {
794
+ const c = asRolloverCtx(ctx);
795
+ if (!c) return;
796
+ if (r.command === "unlock" && r.minutes !== undefined) {
797
+ const until = new Date(Date.now() + r.minutes * 60_000).toLocaleTimeString();
798
+ c.notify(`guard unlocked for ${r.minutes} min (until ${until})`);
799
+ } else if (r.command === "lock") {
800
+ c.notify("guard locked again");
801
+ }
802
+ };
803
+ pi.on("input", (event, ctx) => {
804
+ if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
805
+ const e = asRecord(event);
806
+ if (asString(e.source) !== "interactive") return undefined;
807
+ const r = q.chatUnlock(asString(e.text), cfg, "interactive");
808
+ if (!r.applied) return undefined;
809
+ notifyUnlock(ctx, r);
810
+ return { handled: true };
811
+ });
812
+ // A collab guest prompt (collab/host.ts #handlePrompt, write peers only) is NOT an input event:
813
+ // it is session.promptCustomMessage({ customType: "collab-prompt", details: { from },
814
+ // attribution: "user" }), which lands in the agent context — the adapter sees it on the
815
+ // "context" event (types.ts ContextEvent, the messages about to go to the LLM). The message
816
+ // stays in the transcript, so later LLM calls replay it: a seen key (timestamp + text) is acted
817
+ // on once, and a resumed session replaying old prompts is stopped by the age limit.
818
+ const seenChatPrompts = new Set<string>();
819
+ const CHAT_PROMPT_MAX_AGE_MS = 10 * 60_000;
820
+ pi.on("context", (event, ctx) => {
821
+ if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
822
+ const messages = asRecord(event).messages;
823
+ if (!Array.isArray(messages)) return undefined;
824
+ for (const raw of messages) {
825
+ const m = asRecord(raw);
826
+ if (m.role !== "custom" || m.customType !== "collab-prompt" || m.attribution !== "user") continue;
827
+ const from = asString(asRecord(m.details).from);
828
+ if (from === "") continue;
829
+ const text =
830
+ typeof m.content === "string"
831
+ ? m.content
832
+ : Array.isArray(m.content)
833
+ ? m.content.map(c => asString(asRecord(c).text)).join("")
834
+ : "";
835
+ const timestamp = typeof m.timestamp === "number" ? m.timestamp : 0;
836
+ if (Date.now() - timestamp > CHAT_PROMPT_MAX_AGE_MS) continue;
837
+ const key = `${timestamp}:${text}`;
838
+ if (seenChatPrompts.has(key)) continue;
839
+ seenChatPrompts.add(key);
840
+ const r = q.chatUnlock(text, cfg, `collab:${from}`);
841
+ if (r.applied) notifyUnlock(ctx, r);
842
+ }
843
+ return undefined;
844
+ });
845
+
656
846
  // Under the launcher the relaunch is the only rollover path: a plain interactive message in the ready
657
847
  // state requests it, and every such message joins the pending request's draft, in order. Plain omp keeps
658
848
  // `/main-rollover <text>`: the message becomes the owner's first message of the new session.
@@ -49,6 +49,37 @@ function asObj(v: unknown): Record<string, unknown> | null {
49
49
  return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
50
50
  }
51
51
 
52
+ /** The joined text of the session file's last assistant message, trimmed; "" when there is none
53
+ * (unreadable file, no assistant message, or a tool-use-only ending). */
54
+ export function lastAssistantText(file: string): string {
55
+ let text: string;
56
+ try {
57
+ text = readFileSync(file, "utf8");
58
+ } catch {
59
+ return "";
60
+ }
61
+ let out = "";
62
+ for (const line of text.split("\n")) {
63
+ if (!line.trim()) continue;
64
+ let parsed: unknown;
65
+ try {
66
+ parsed = JSON.parse(line);
67
+ } catch {
68
+ continue;
69
+ }
70
+ const d = asObj(parsed);
71
+ if (!d) continue;
72
+ const m = asObj(d.message) ?? d;
73
+ if (m.role !== "assistant") continue;
74
+ const content = Array.isArray(m.content) ? m.content : [];
75
+ const texts = content
76
+ .filter((c): c is Record<string, unknown> => asObj(c) !== null && asObj(c)?.type === "text")
77
+ .map(c => String(c.text ?? ""));
78
+ out = texts.join("\n").trim();
79
+ }
80
+ return out;
81
+ }
82
+
52
83
  function costOf(m: Record<string, unknown>): number {
53
84
  const u = asObj(m.usage);
54
85
  const c = u ? asObj(u.cost) : null;
@@ -1,4 +1,5 @@
1
- import { ConfigError, configFile, loadConfig } from "../core/config.ts";
1
+ import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
2
+ import { postReply } from "../core/notify.ts";
2
3
  import { applyQueueEnv } from "../core/queue/env.ts";
3
4
  import { runAdapterInstall } from "../adapters/omp/install.ts";
4
5
  import { runDoctor } from "../adapters/omp/doctor.ts";
@@ -7,6 +8,7 @@ import { runInit } from "./init.ts";
7
8
  import { PORTED, runMain, runPorted } from "./commands.ts";
8
9
  import { runMetrics } from "./metrics.ts";
9
10
  import { runIncident } from "./incident.ts";
11
+ import { runUi } from "./ui.ts";
10
12
  import { runUninstall } from "../core/uninstall.ts";
11
13
  import { queueMigrate } from "../core/queue-migrate.ts";
12
14
  import { allowedAgents, subagentsPath } from "../core/queue/lib.ts";
@@ -51,6 +53,7 @@ export function helpText(): string {
51
53
  " template-identical pins and the AGENTS.md block (--purge adds",
52
54
  " config + agent-dir state); prints the list, refuses outside HOME",
53
55
  " neurastream doctor report hand-edited live files and a stale install",
56
+ " neurastream notify test post a test message to the configured Discord/Slack webhooks",
54
57
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
55
58
  " neurastream config [--json] print the merged config (defaults + file + env)",
56
59
  " neurastream guard <event> --json",
@@ -58,6 +61,7 @@ export function helpText(): string {
58
61
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
59
62
  " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
60
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)",
61
65
  " neurastream agents list | allow <slug>... | deny <slug>...",
62
66
  " the subagent allow-list (## Allowed in notes/subagents.md)",
63
67
  "",
@@ -78,6 +82,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
78
82
  if (cmd === "init") return runInit(args);
79
83
  if (cmd === "metrics") return runMetrics(args);
80
84
  if (cmd === "incident") return runIncident(args);
85
+ if (cmd === "ui") return runUi();
81
86
  if (cmd === "adapter") return runAdapterInstall(args);
82
87
  if (cmd === "config") {
83
88
  try {
@@ -90,6 +95,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
90
95
  }
91
96
  }
92
97
  if (cmd === "doctor") return runDoctor();
98
+ if (cmd === "notify") return runNotify(args);
93
99
  if (cmd === "uninstall") return runUninstall(args);
94
100
  if (cmd === "queue" && args[0] === "migrate") {
95
101
  try {
@@ -116,6 +122,35 @@ export async function run(cmd: string, args: string[]): Promise<number> {
116
122
  return 2;
117
123
  }
118
124
 
125
+ const NOTIFY_USAGE = "usage: neurastream notify test";
126
+
127
+ /** `neurastream notify test`: post one line to every configured provider; exit 1 when any fails. */
128
+ function runNotify(args: string[]): number | Promise<number> {
129
+ if (args[0] !== "test" || args.length !== 1) {
130
+ console.error(NOTIFY_USAGE);
131
+ return 2;
132
+ }
133
+ let cfg: Config;
134
+ try {
135
+ cfg = loadConfig();
136
+ } catch (err) {
137
+ console.error(err instanceof ConfigError ? err.message : String(err));
138
+ return 1;
139
+ }
140
+ return postReply("neurastream notify test", cfg).then(results => {
141
+ let failed = 0;
142
+ for (const r of results) {
143
+ if (r.posted) console.log(`notify ${r.provider}: posted (${r.chunks} chunk${r.chunks === 1 ? "" : "s"})`);
144
+ else {
145
+ failed++;
146
+ console.error(`notify ${r.provider}: ${r.error}`);
147
+ }
148
+ }
149
+ if (results.length === 0) console.log("notify: no provider configured (notify.discord_webhook_file / notify.slack_webhook_file)");
150
+ return failed > 0 ? 1 : 0;
151
+ });
152
+ }
153
+
119
154
  const AGENTS_USAGE = "usage: neurastream agents list | allow <slug>... | deny <slug>...";
120
155
 
121
156
  function runAgents(args: string[]): number {
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
+ }