neurastream 0.2.26 → 0.2.28

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
@@ -117,7 +117,7 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
117
117
 
118
118
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
119
119
 
120
- With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and "Yes"/"No"/"Reply…" actions whose answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order — drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2" — shown on Now as the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows, the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
120
+ With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and "Yes"/"No"/"Reply…" actions whose answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order — drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2" — shown on Now as the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows, the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
121
121
 
122
122
  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.
123
123
 
@@ -195,6 +195,38 @@ Guard rules around it:
195
195
 
196
196
  "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `🔔 Needs you — <plan>: <question>` (with the `neurastream ui` phone-page link when `ui.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `🔓 Main needs an unlock to continue (<file>)` — the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
197
197
 
198
+ ## Secrets never reach the chat
199
+
200
+ A value the machine holds is hidden before the model, the chat and the session log see it (`src/core/secret-redact.ts`, plan 20261025_2204, incident I-20261025-197). Detection is by **content**, not by file name — the old name list never knew about `~/.npmrc`.
201
+
202
+ - Every tool result of Main and of every subagent goes through the redactor at the omp `tool_result` hook (redact first, then the plan/guard logic works on markers). A hit becomes `[REDACTED:<type>]` and the result gains one line `secret-redact: hid N value(s) (<types>)`. The key name stays: `password = [REDACTED:generic-secret]`.
203
+ - Shapes: npm, GitHub, GitLab, OpenAI/Anthropic/OpenRouter (`sk-…`), the AWS key id and the value after `aws_secret_access_key`, Google, Slack, Discord webhooks, Stripe, JWTs, PEM private keys, URL credentials, `_authToken`/`_password`, and `(password|passwd|secret|token|api_key|access_key|client_secret) = …` with a value of 8 or more characters.
204
+ - Exact values are hidden wherever they appear, whatever the file is called: env vars whose name looks like a credential, `~/.npmrc`, every file in `secrets.known_value_files`, every top-level dotenv file under `paths.work_roots`, and the notify webhook files. File contents are cached per process and re-read when a file's mtime or size changes.
205
+ - `neurastream redact < file` prints the redacted text on stdout and the hit summary on stderr, so another harness hook can pipe a tool result through the same rules. Notify posts (`notify test`, Main's final reply) are scrubbed before they leave.
206
+ - `neurastream doctor` reports `secrets: redactor on, N known value(s), secretgate installed|missing, proxy none|secretgate` — a count only, never a value.
207
+
208
+ Config (`docs/config.md`, `templates/config.yml`):
209
+
210
+ ```yaml
211
+ secrets:
212
+ redact: true
213
+ known_value_files: ["~/.npmrc"]
214
+ extra_patterns: [] # your own shapes: [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
215
+ proxy: "none" # or "secretgate"
216
+ ```
217
+
218
+ ### secretgate as a second net
219
+
220
+ The redactor keeps a secret out of the chat screen and the local session log; it cannot stop a value that reaches the harness another way. [secretgate](https://github.com/secretgate/secretgate) (Apache-2.0) is a local proxy that cleans what leaves the machine, so the two together cover both ends:
221
+
222
+ ```bash
223
+ pipx install secretgate # the binary must be on PATH
224
+ secretgate ca init # create its CA; the command prints the CA path
225
+ # trust that CA for this machine (firefox/chrome/system store, whichever you use)
226
+ ```
227
+
228
+ Then set `secrets.proxy: secretgate` and restart Main: `neurastream main` starts omp as `secretgate wrap -- omp`. When the binary is missing, omp starts normally and one warning says the second net is off — the owner is never blocked by it.
229
+
198
230
  ## Provider rate limits
199
231
 
200
232
  When a Main turn ends on a provider rate limit, neurastream waits it out instead of asking again straight into the limit. The stop guard sees the turn's error text, matches it against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive) and, on a hit, allows the stop without consulting the normal stop rules or touching the idle-stop counters. The chat channels get one post per episode — `⏳ Main is rate limited by its provider until HH:MM (local); it resumes on its own.` — and exactly one resume timer is armed (replacing any earlier one). When the wait is over, the plugin gives Main a new turn: `main-guard: the provider rate limit is over (waited until HH:MM). Continue the queue where you stopped.`, and the guard log carries the whole story:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
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",
@@ -12,6 +12,7 @@ import { fileURLToPath } from "node:url";
12
12
  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
+ import { loadKnownSecrets, proxyOnPath } from "../../core/secret-redact.ts";
15
16
  import { readIndex } from "../../core/queue/lib.ts";
16
17
  import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
17
18
 
@@ -217,6 +218,15 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
217
218
  const notify = notifyFindings(cfg);
218
219
  problems.push(...notify.problems);
219
220
  warnings.push(...notify.warnings);
221
+ // Secrets (plan 20261025_2204): the redactor's state and the second net, count only — doctor
222
+ // never prints a value. A missing proxy binary is a warning, never a problem: the launch path
223
+ // falls back to a plain harness start.
224
+ const known = loadKnownSecrets(cfg).length;
225
+ const proxy = proxyOnPath();
226
+ ok.push(`secrets: redactor ${cfg.secrets.redact ? "on" : "off"}, ${known} known value(s), secretgate ${proxy ? "installed" : "missing"}, proxy ${cfg.secrets.proxy}`);
227
+ if (cfg.secrets.proxy === "secretgate" && !proxy) {
228
+ warnings.push("secrets.proxy is secretgate but secretgate is not on PATH; the harness starts without the proxy (README: Secrets)");
229
+ }
220
230
  const viewed = npmViewVersion(name, env);
221
231
  let registry: string | null = null;
222
232
  if ("warning" in viewed) warnings.push(viewed.warning);
@@ -26,6 +26,7 @@ import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/
26
26
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
27
27
  import { rateLimitWait } from "../../core/rate-limit.ts";
28
28
  import { notifyProviders, postReply } from "../../core/notify.ts";
29
+ import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
29
30
  import { inboxPath } from "../../core/owner-ui.ts";
30
31
  import { realTailscale } from "../../core/tailscale.ts";
31
32
  import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
@@ -45,7 +46,7 @@ import "./package-ops.ts";
45
46
  export interface ExtensionHost {
46
47
  on(event: string, cb: (...args: unknown[]) => unknown): void;
47
48
  registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
48
- sendUserMessage(content: string): void;
49
+ sendUserMessage(content: string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[]): void;
49
50
  sendMessage(message: { customType: string; content: string; display: boolean }, options: { triggerTurn: boolean; deliverAs: "nextTurn" }): void;
50
51
  }
51
52
 
@@ -267,6 +268,28 @@ function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string
267
268
  }
268
269
  }
269
270
 
271
+ // Secrets never reach the model, the chat or the session log (plan 20261025_2204): every tool
272
+ // result of every agent — Main and subs both fire tool_result — is redacted here before the rest of
273
+ // the handler, the model, the chat and the session file see it. The rewritten content goes back
274
+ // with one line naming what was hidden; a clean result keeps its original shape and returns nothing.
275
+ function redactToolResult(content: unknown[], cfg: Config): { content: unknown[]; note: string } {
276
+ if (!cfg.secrets.redact || content.length === 0) return { content, note: "" };
277
+ const known = loadKnownSecrets(cfg);
278
+ const hits = new Map<string, number>();
279
+ let changed = false;
280
+ const out = content.map(part => {
281
+ const p = asRecord(part);
282
+ if (p.type !== "text" || typeof p.text !== "string" || p.text === "") return part;
283
+ const r = redactSecrets(p.text, known, cfg.secrets.extra_patterns);
284
+ if (r.hits.length === 0) return part;
285
+ changed = true;
286
+ for (const hit of r.hits) hits.set(hit.type, (hits.get(hit.type) ?? 0) + hit.count);
287
+ return { ...p, text: r.text };
288
+ });
289
+ if (!changed) return { content, note: "" };
290
+ return { content: out, note: redactSummary([...hits].map(([type, count]) => ({ type, count }))) };
291
+ }
292
+
270
293
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
271
294
  // mtime reads. The decisions are in src/core/rollover.ts.
272
295
  const WAIT_NOTICE_MS = 15 * 60_000;
@@ -368,7 +391,7 @@ function writeOwnerInboxCursor(n: number): void {
368
391
 
369
392
  /** The user message one inbox record becomes, or null when the record is not one Main can act on.
370
393
  * Records without `kind` are page answers (the original shape). */
371
- export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
394
+ export function ownerInboxMessage(rec: Record<string, unknown>): string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] | null {
372
395
  const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
373
396
  const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
374
397
  switch (kind) {
@@ -394,6 +417,37 @@ export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
394
417
  if (!plan || from === null || to === null) return null;
395
418
  return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
396
419
  }
420
+ case "message": {
421
+ const ts = num(rec.ts);
422
+ const id = asString(rec.id);
423
+ if (ts === null || !/^[0-9]+-[0-9a-f]{6}$/.test(id)) return null;
424
+ const at = strftime(ts, "%H:%M");
425
+ const dir = join(q.stateDirPath(), "owner-messages", id);
426
+ let message: Record<string, unknown>;
427
+ try {
428
+ message = JSON.parse(readFileSync(join(dir, "message.json"), "utf8")) as Record<string, unknown>;
429
+ } catch {
430
+ return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
431
+ }
432
+ const text = asString(message.text);
433
+ const names = Array.isArray(message.images) ? message.images.filter((name): name is string => typeof name === "string" && /^[1-4]\.(png|jpg|gif|webp)$/.test(name)) : [];
434
+ const parts: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] = [];
435
+ const paths = names.map(name => join(dir, name));
436
+ parts.push({
437
+ type: "text",
438
+ text: `Owner message from the phone page (${at}): ${text}${paths.length ? `\nImages:\n${paths.map(path => `- ${path}`).join("\n")}` : ""}`,
439
+ });
440
+ for (const name of names) {
441
+ const ext = name.slice(name.lastIndexOf(".") + 1);
442
+ const mimeType = ext === "jpg" ? "image/jpeg" : `image/${ext}`;
443
+ try {
444
+ parts.push({ type: "image", data: readFileSync(join(dir, name)).toString("base64"), mimeType });
445
+ } catch {
446
+ return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
447
+ }
448
+ }
449
+ return parts;
450
+ }
397
451
  default:
398
452
  return null;
399
453
  }
@@ -719,7 +773,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
719
773
  const c = asCtx(ctx);
720
774
  const id = asString(e.toolCallId);
721
775
  const snap = pending.get(id);
722
- const notes: string[] = [];
776
+ // Redact first: everything below (plan checks, detectors, the returned content, the model,
777
+ // the chat and the session log) then works on text that holds markers, never values.
778
+ const redacted = redactToolResult(Array.isArray(e.content) ? e.content : [], cfg);
779
+ const content = redacted.content;
780
+ const notes: string[] = redacted.note ? [redacted.note] : [];
723
781
  if (snap) {
724
782
  pending.delete(id);
725
783
  for (const [file, before] of snap) {
@@ -748,7 +806,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
748
806
  if (PUSH_MERGE.test(asString(asRecord(e.input).command))) autoClose(cfg);
749
807
  }
750
808
  if ((!c.hasAgent || c.kind === "main") && !e.isError) {
751
- const content = Array.isArray(e.content) ? e.content : [];
752
809
  const text = content.map(p => asString(asRecord(p).text)).join("\n");
753
810
  recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
754
811
  }
@@ -757,12 +814,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
757
814
  }
758
815
  // Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
759
816
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
760
- const content = Array.isArray(e.content) ? e.content : [];
761
817
  mainDetectors(cfg, {
762
818
  bash: { command: asString(asRecord(e.input).command), output: content.map(p => asString(asRecord(p).text)).join("\n") },
763
819
  });
764
820
  }
765
- if (notes.length) return { content: [...(Array.isArray(e.content) ? e.content : []), ...notes.map(text => ({ type: "text", text }))] };
821
+ if (notes.length) return { content: [...content, ...notes.map(text => ({ type: "text", text }))] };
766
822
  return undefined;
767
823
  });
768
824
 
@@ -11,6 +11,7 @@ import { mainStartText } from "../../core/main-start.ts";
11
11
  import { applyQueueEnv } from "../../core/queue/env.ts";
12
12
  import * as q from "../../core/queue/lib.ts";
13
13
  import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath } from "../../core/rollover.ts";
14
+ import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
14
15
  import { adapterLog } from "./index.ts";
15
16
  import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
16
17
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
@@ -18,6 +19,32 @@ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
18
19
  /** The harness the launcher runs. Tests pass another path through LaunchOptions. */
19
20
  export const OMP_BIN = "omp";
20
21
 
22
+ export interface ProxyPlan {
23
+ /** The command to spawn. */
24
+ cmd: string;
25
+ /** Arguments that come before the harness's own: `wrap -- <harness>` when proxied. */
26
+ prefix: string[];
27
+ /** One stderr line when the proxy was asked for but cannot run; empty otherwise. */
28
+ warning: string;
29
+ }
30
+
31
+ /**
32
+ * `secretgate wrap -- <harness>` when `secrets.proxy: secretgate`, so everything the harness sends
33
+ * leaves through the proxy's own redaction net. A missing binary never blocks the owner: the
34
+ * harness starts normally and one warning says why the second net is off.
35
+ */
36
+ export function proxyPlan(harness: string, cfg: Config, onPath: boolean = proxyOnPath()): ProxyPlan {
37
+ if (cfg.secrets.proxy !== "secretgate") return { cmd: harness, prefix: [], warning: "" };
38
+ if (!onPath) {
39
+ return {
40
+ cmd: harness,
41
+ prefix: [],
42
+ warning: `neurastream: secrets.proxy is secretgate but ${PROXY_BIN} is not on PATH; starting ${harness} without the proxy`,
43
+ };
44
+ }
45
+ return { cmd: PROXY_BIN, prefix: ["wrap", "--", harness], warning: "" };
46
+ }
47
+
21
48
  /** Flags that take the next argument as their value (omp 18.11.1 --help shows them as `--flag=<value>`). */
22
49
  export const VALUE_FLAGS: Record<string, true> = {
23
50
  "--model": true, "--smol": true, "--slow": true, "--plan": true, "--goal": true, "--prewalk-into": true,
@@ -105,6 +132,8 @@ interface RelaunchRequest {
105
132
  export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchOptions = {}): Promise<number> {
106
133
  applyQueueEnv(cfg);
107
134
  const harness = opts.harness ?? OMP_BIN;
135
+ const proxy = proxyPlan(harness, cfg);
136
+ if (proxy.warning) console.error(proxy.warning);
108
137
  const mainStart = opts.mainStart ?? mainStartText;
109
138
  const carried = carriedArgs(args);
110
139
  const loaded = packageVersion(packageJsonPath());
@@ -141,7 +170,7 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
141
170
  }
142
171
  for (;;) {
143
172
  const started = Date.now();
144
- const code = await runChild(harness, runArgs, { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
173
+ const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
145
174
  const req = readRequest(started, cfg);
146
175
  if (req === null) return code;
147
176
  const installed = packageVersion(packageJsonPath());
@@ -1,6 +1,8 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { pagesDoctor } from "../core/pages-doctor.ts";
2
3
  import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
3
4
  import { postReply } from "../core/notify.ts";
5
+ import { loadKnownSecrets, redactSecrets, redactSummary } from "../core/secret-redact.ts";
4
6
  import { applyQueueEnv } from "../core/queue/env.ts";
5
7
  import { runAdapterInstall } from "../adapters/omp/install.ts";
6
8
  import { runDoctor } from "../adapters/omp/doctor.ts";
@@ -57,6 +59,8 @@ export function helpText(): string {
57
59
  " config + agent-dir state); prints the list, refuses outside HOME",
58
60
  " neurastream doctor report hand-edited live files and a stale install",
59
61
  " neurastream notify test post a test message to the configured Discord/Slack webhooks",
62
+ " neurastream redact filter stdin through the secret redactor: stdout gets the text,",
63
+ " stderr the hit summary (types and counts only)",
60
64
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
61
65
  " neurastream config [--json] print the merged config (defaults + file + env)",
62
66
  " neurastream guard <event> --json",
@@ -122,6 +126,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
122
126
  return runDoctor();
123
127
  }
124
128
  if (cmd === "notify") return runNotify(args);
129
+ if (cmd === "redact") return runRedact(args);
125
130
  if (cmd === "uninstall") return runUninstall(args);
126
131
  if (cmd === "queue" && args[0] === "migrate") {
127
132
  try {
@@ -177,6 +182,30 @@ function runNotify(args: string[]): number | Promise<number> {
177
182
  });
178
183
  }
179
184
 
185
+ const REDACT_USAGE = "usage: neurastream redact < text (stdin to stdout; the hit summary goes to stderr)";
186
+
187
+ /** `neurastream redact`: the core the adapter and notify use, as a filter, so another harness hook
188
+ * can pipe a tool result through the same rules. The text is passed through untouched except for
189
+ * the markers; stderr gets the type names and counts, never a value. */
190
+ function runRedact(args: string[]): number {
191
+ if (args.length > 0) {
192
+ console.error(REDACT_USAGE);
193
+ return 2;
194
+ }
195
+ let cfg: Config;
196
+ try {
197
+ cfg = loadConfig();
198
+ } catch (err) {
199
+ console.error(err instanceof ConfigError ? err.message : String(err));
200
+ return 1;
201
+ }
202
+ const text = readFileSync(0, "utf8");
203
+ const result = redactSecrets(text, loadKnownSecrets(cfg), cfg.secrets.extra_patterns);
204
+ process.stdout.write(result.text);
205
+ console.error(result.hits.length > 0 ? redactSummary(result.hits) : "secret-redact: nothing to hide");
206
+ return 0;
207
+ }
208
+
180
209
  const AGENTS_USAGE = "usage: neurastream agents list | allow <slug>... | deny <slug>...";
181
210
 
182
211
  function runAgents(args: string[]): number {
@@ -178,6 +178,18 @@ export interface Config {
178
178
  /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
179
179
  * The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
180
180
  notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
181
+ /** Content redaction (src/core/secret-redact.ts, plan 20261025_2204): every tool result, every
182
+ * notify post and `neurastream redact` go through it. Detection is by content, not file name. */
183
+ secrets: {
184
+ redact: boolean;
185
+ /** Files whose `KEY=value` lines are secret values; top-level dotenv files under
186
+ * paths.work_roots are read as well. */
187
+ known_value_files: string[];
188
+ /** The owner's own shapes: `{type, regex}`; a hit prints as `[REDACTED:<type>]`. */
189
+ extra_patterns: { type: string; regex: string }[];
190
+ /** A second net on the wire: wrap the harness in `secretgate wrap --` at launch. */
191
+ proxy: "none" | "secretgate";
192
+ };
181
193
  priority: { sleep_sec: number };
182
194
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
183
195
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
@@ -512,6 +524,24 @@ function check(cfg: Config): void {
512
524
  if (!Array.isArray(edges) || edges.some((v, i) => !Number.isInteger(v) || v < 1 || (i > 0 && v <= edges[i - 1]!))) {
513
525
  throw new ConfigError("traces.briefs.char_buckets must be ascending positive integers");
514
526
  }
527
+ if (cfg.secrets.proxy !== "none" && cfg.secrets.proxy !== "secretgate") {
528
+ throw new ConfigError('secrets.proxy must be "none" or "secretgate"');
529
+ }
530
+ if (typeof cfg.secrets.redact !== "boolean") throw new ConfigError("secrets.redact must be true or false");
531
+ if (!Array.isArray(cfg.secrets.known_value_files) || cfg.secrets.known_value_files.some((p) => typeof p !== "string" || p === "")) {
532
+ throw new ConfigError("secrets.known_value_files must be a list of non-empty paths");
533
+ }
534
+ if (!Array.isArray(cfg.secrets.extra_patterns)) throw new ConfigError("secrets.extra_patterns must be a list");
535
+ for (const pattern of cfg.secrets.extra_patterns) {
536
+ if (!isObj(pattern) || typeof pattern.type !== "string" || pattern.type === "" || typeof pattern.regex !== "string" || pattern.regex === "") {
537
+ throw new ConfigError("secrets.extra_patterns entries must be {type, regex} with non-empty strings");
538
+ }
539
+ try {
540
+ new RegExp(pattern.regex);
541
+ } catch {
542
+ throw new ConfigError(`secrets.extra_patterns.${pattern.type}: not a valid regex: ${pattern.regex}`);
543
+ }
544
+ }
515
545
  for (const [key, value] of Object.entries(cfg.paths)) {
516
546
  if (key === "work_roots") {
517
547
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -6,6 +6,7 @@
6
6
  import { dirname } from "node:path";
7
7
  import { readFileSync, statSync } from "node:fs";
8
8
  import { configFile, type Config } from "./config.ts";
9
+ import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
9
10
 
10
11
  export type NotifyProviderName = "discord" | "slack";
11
12
 
@@ -207,6 +208,10 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
207
208
  const providers = notifyProviders(cfg);
208
209
  const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text;
209
210
  if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
211
+ // The chat is where a secret does its damage (plan 20261025_2204): a reply can carry a value
212
+ // the owner pasted or one the redactor's tool_result pass never saw, so the post is scrubbed
213
+ // here too, after the prefix and before the split.
214
+ const scrubbed = cfg.secrets.redact ? redactSecrets(body, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text : body;
210
215
  const out: NotifyPostResult[] = [];
211
216
  for (const p of providers) {
212
217
  const { url, why } = webhookUrl(p);
@@ -215,7 +220,7 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
215
220
  continue;
216
221
  }
217
222
  const limit = p.name === "discord" ? DISCORD_LIMIT : SLACK_LIMIT;
218
- out.push(await postChunks(p, url, notifyChunks(body, limit)));
223
+ out.push(await postChunks(p, url, notifyChunks(scrubbed, limit)));
219
224
  }
220
225
  return out;
221
226
  });