neurastream 0.2.27 → 0.2.29
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 +33 -1
- package/package.json +1 -1
- package/src/adapters/omp/doctor.ts +10 -0
- package/src/adapters/omp/index.ts +33 -7
- package/src/adapters/omp/launch.ts +30 -1
- package/src/cli/dispatch.ts +29 -0
- package/src/core/autonomy.ts +11 -5
- package/src/core/config.ts +35 -1
- package/src/core/guards.ts +7 -6
- package/src/core/notify.ts +6 -1
- package/src/core/secret-redact.ts +317 -0
- package/templates/AGENTS.md +1 -1
- package/templates/config.yml +8 -1
package/README.md
CHANGED
|
@@ -111,7 +111,7 @@ A plan parked for the owner has one line: `WAITING on owner: <what>`. That line
|
|
|
111
111
|
|
|
112
112
|
## Autonomy tiers
|
|
113
113
|
|
|
114
|
-
One setting decides how much Main does without asking: `autonomy.tier` in the config (default `opinionated`), moved any time by the owner's whole chat message `tier strict|opinionated|full` (when `guards.chat_unlock` is on) or the tier buttons on the phone page — the setting lives in `<queue_state>/autonomy-tier`, a guard-protected path no agent can write. `strict` caps Main's project-file changes at `autonomy.strict_edit_limit` per `guards.main_window_min` minutes and refuses `git push` / `glab mr merge` / `gh pr merge` until the owner types `go`
|
|
114
|
+
One setting decides how much Main does without asking: `autonomy.tier` in the config (default `opinionated`), moved any time by the owner's whole chat message `tier strict|opinionated|full` (when `guards.chat_unlock` is on) or the tier buttons on the phone page — the setting lives in `<queue_state>/autonomy-tier`, a guard-protected path no agent can write. `strict` caps Main's project-file changes at `autonomy.strict_edit_limit` per `guards.main_window_min` minutes and refuses `git push` / `glab mr merge` / `gh pr merge` until the owner types the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message — one landing, valid `autonomy.go_minutes` minutes); `opinionated` keeps today's limits (`guards.main_edit_limit`); `full` drops the cap and lets Main skip an idle higher plan with `Priority skip: <plan> — Main: "<reason>"` (reason ≥ 4 words). No tier loosens the owner-only moves: guard-file edits without the unlock, starting the phone page, reading notify secrets, local `npm publish` and the tier setting itself.
|
|
115
115
|
|
|
116
116
|
## Owner page (`neurastream ui`)
|
|
117
117
|
|
|
@@ -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
|
@@ -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";
|
|
@@ -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;
|
|
@@ -750,7 +773,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
750
773
|
const c = asCtx(ctx);
|
|
751
774
|
const id = asString(e.toolCallId);
|
|
752
775
|
const snap = pending.get(id);
|
|
753
|
-
|
|
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] : [];
|
|
754
781
|
if (snap) {
|
|
755
782
|
pending.delete(id);
|
|
756
783
|
for (const [file, before] of snap) {
|
|
@@ -779,7 +806,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
779
806
|
if (PUSH_MERGE.test(asString(asRecord(e.input).command))) autoClose(cfg);
|
|
780
807
|
}
|
|
781
808
|
if ((!c.hasAgent || c.kind === "main") && !e.isError) {
|
|
782
|
-
const content = Array.isArray(e.content) ? e.content : [];
|
|
783
809
|
const text = content.map(p => asString(asRecord(p).text)).join("\n");
|
|
784
810
|
recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
|
|
785
811
|
}
|
|
@@ -788,12 +814,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
788
814
|
}
|
|
789
815
|
// Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
|
|
790
816
|
if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
|
|
791
|
-
const content = Array.isArray(e.content) ? e.content : [];
|
|
792
817
|
mainDetectors(cfg, {
|
|
793
818
|
bash: { command: asString(asRecord(e.input).command), output: content.map(p => asString(asRecord(p).text)).join("\n") },
|
|
794
819
|
});
|
|
795
820
|
}
|
|
796
|
-
if (notes.length) return { content: [...
|
|
821
|
+
if (notes.length) return { content: [...content, ...notes.map(text => ({ type: "text", text }))] };
|
|
797
822
|
return undefined;
|
|
798
823
|
});
|
|
799
824
|
|
|
@@ -1126,8 +1151,9 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
1126
1151
|
};
|
|
1127
1152
|
|
|
1128
1153
|
// Chat unlock + autonomy tiers (guards.chat_unlock): the owner's whole message "unlock"/
|
|
1129
|
-
// "unlock N"/"lock" moves the guard unlock file, "tier <name>" sets the autonomy tier and
|
|
1130
|
-
// "go" approves one strict landing
|
|
1154
|
+
// "unlock N"/"lock" moves the guard unlock file, "tier <name>" sets the autonomy tier and the
|
|
1155
|
+
// approve phrase (autonomy.go_phrase, default "go push") approves one strict landing
|
|
1156
|
+
// (src/core/queue/lib.ts chatUnlock, src/core/autonomy.ts
|
|
1131
1157
|
// chatTier/chatGo). Only prompts the owner really typed
|
|
1132
1158
|
// count: the local terminal (input event, source "interactive") and collab guest prompts from
|
|
1133
1159
|
// write peers. This handler is registered BEFORE the rollover input handler below, so the unlock
|
|
@@ -1151,7 +1177,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
1151
1177
|
const notifyGo = (ctx: unknown, r: { minutes?: number }): void => {
|
|
1152
1178
|
const c = asRolloverCtx(ctx);
|
|
1153
1179
|
if (!c || r.minutes === undefined) return;
|
|
1154
|
-
c.notify(
|
|
1180
|
+
c.notify(`${cfg.autonomy.go_phrase}: one push/merge approved for ${r.minutes} min`);
|
|
1155
1181
|
};
|
|
1156
1182
|
pi.on("input", (event, ctx) => {
|
|
1157
1183
|
if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
|
|
@@ -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(
|
|
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());
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -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 {
|
package/src/core/autonomy.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Autonomy tiers (I-20261025-177): one owner setting — strict / opinionated / full — that the
|
|
2
|
-
// guards follow. The tier and
|
|
2
|
+
// guards follow. The tier and the one-shot approve phrase (autonomy.go_phrase, default "go push")
|
|
3
|
+
// are written only by the owner's own words (the same
|
|
3
4
|
// paths as chatUnlock: the terminal input event and collab write-peer messages) or the
|
|
4
5
|
// authenticated phone page; never by a tool call (the state dir is protected) and never from
|
|
5
6
|
// model text. Every tier keeps the owner-only moves owner-only; no tier loosens them.
|
|
@@ -59,20 +60,25 @@ export function chatTier(text: string, cfg: Config, source: string, word: "chat"
|
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
export interface ChatGoResult {
|
|
62
|
-
/** True when the text was a whole-message
|
|
63
|
+
/** True when the text was a whole-message approve phrase that took effect. */
|
|
63
64
|
applied: boolean;
|
|
64
65
|
/** The minutes this `go` stays valid (autonomy.go_minutes), for the owner notice. */
|
|
65
66
|
minutes?: number;
|
|
66
67
|
}
|
|
67
68
|
|
|
69
|
+
/** The shape a phrase is matched in: trimmed, lowercased, inner whitespace collapsed. */
|
|
70
|
+
const goWords = (s: string): string => s.trim().toLowerCase().replace(/\s+/g, " ");
|
|
71
|
+
|
|
68
72
|
/**
|
|
69
73
|
* The strict tier's one-shot landing approval by chat (guards.chat_unlock): the whole trimmed
|
|
70
|
-
* message
|
|
71
|
-
*
|
|
74
|
+
* message matching `autonomy.go_phrase` (default "go push") — case-insensitive, inner spaces
|
|
75
|
+
* collapsed — touches `<state dir>/autonomy-go`; the next strict push/merge consumes it
|
|
76
|
+
* (takeGo). Same trust rules as chatTier. A bare "go" is an ordinary message (I-20261025-201):
|
|
77
|
+
* it approves nothing.
|
|
72
78
|
*/
|
|
73
79
|
export function chatGo(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatGoResult {
|
|
74
80
|
if (!cfg.guards.chat_unlock) return { applied: false };
|
|
75
|
-
if (text
|
|
81
|
+
if (goWords(text) !== goWords(cfg.autonomy.go_phrase)) return { applied: false };
|
|
76
82
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
77
83
|
writeFileSync(goFile(), "");
|
|
78
84
|
try {
|
package/src/core/config.ts
CHANGED
|
@@ -140,8 +140,10 @@ export interface Config {
|
|
|
140
140
|
tier: "strict" | "opinionated" | "full";
|
|
141
141
|
/** Main's project-file changes per guards.main_window_min window in tier strict. */
|
|
142
142
|
strict_edit_limit: number;
|
|
143
|
-
/** Minutes
|
|
143
|
+
/** Minutes the approve phrase approves exactly one push/merge in tier strict. */
|
|
144
144
|
go_minutes: number;
|
|
145
|
+
/** The whole chat message that approves one push/merge in tier strict (default "go push"; matched case-insensitively with inner spaces collapsed). */
|
|
146
|
+
go_phrase: string;
|
|
145
147
|
};
|
|
146
148
|
/** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
|
|
147
149
|
ui: { enabled: boolean; port: number; owner_login: string };
|
|
@@ -178,6 +180,18 @@ export interface Config {
|
|
|
178
180
|
/** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
|
|
179
181
|
* The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
|
|
180
182
|
notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
|
|
183
|
+
/** Content redaction (src/core/secret-redact.ts, plan 20261025_2204): every tool result, every
|
|
184
|
+
* notify post and `neurastream redact` go through it. Detection is by content, not file name. */
|
|
185
|
+
secrets: {
|
|
186
|
+
redact: boolean;
|
|
187
|
+
/** Files whose `KEY=value` lines are secret values; top-level dotenv files under
|
|
188
|
+
* paths.work_roots are read as well. */
|
|
189
|
+
known_value_files: string[];
|
|
190
|
+
/** The owner's own shapes: `{type, regex}`; a hit prints as `[REDACTED:<type>]`. */
|
|
191
|
+
extra_patterns: { type: string; regex: string }[];
|
|
192
|
+
/** A second net on the wire: wrap the harness in `secretgate wrap --` at launch. */
|
|
193
|
+
proxy: "none" | "secretgate";
|
|
194
|
+
};
|
|
181
195
|
priority: { sleep_sec: number };
|
|
182
196
|
alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
|
|
183
197
|
snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
|
|
@@ -414,6 +428,8 @@ function check(cfg: Config): void {
|
|
|
414
428
|
throw new ConfigError("autonomy.strict_edit_limit must be an integer >= 1");
|
|
415
429
|
if (!Number.isInteger(cfg.autonomy.go_minutes) || cfg.autonomy.go_minutes < 1)
|
|
416
430
|
throw new ConfigError("autonomy.go_minutes must be an integer >= 1");
|
|
431
|
+
if (typeof cfg.autonomy.go_phrase !== "string" || cfg.autonomy.go_phrase.trim() === "")
|
|
432
|
+
throw new ConfigError("autonomy.go_phrase must be a non-empty string");
|
|
417
433
|
if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
|
|
418
434
|
throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
|
|
419
435
|
}
|
|
@@ -512,6 +528,24 @@ function check(cfg: Config): void {
|
|
|
512
528
|
if (!Array.isArray(edges) || edges.some((v, i) => !Number.isInteger(v) || v < 1 || (i > 0 && v <= edges[i - 1]!))) {
|
|
513
529
|
throw new ConfigError("traces.briefs.char_buckets must be ascending positive integers");
|
|
514
530
|
}
|
|
531
|
+
if (cfg.secrets.proxy !== "none" && cfg.secrets.proxy !== "secretgate") {
|
|
532
|
+
throw new ConfigError('secrets.proxy must be "none" or "secretgate"');
|
|
533
|
+
}
|
|
534
|
+
if (typeof cfg.secrets.redact !== "boolean") throw new ConfigError("secrets.redact must be true or false");
|
|
535
|
+
if (!Array.isArray(cfg.secrets.known_value_files) || cfg.secrets.known_value_files.some((p) => typeof p !== "string" || p === "")) {
|
|
536
|
+
throw new ConfigError("secrets.known_value_files must be a list of non-empty paths");
|
|
537
|
+
}
|
|
538
|
+
if (!Array.isArray(cfg.secrets.extra_patterns)) throw new ConfigError("secrets.extra_patterns must be a list");
|
|
539
|
+
for (const pattern of cfg.secrets.extra_patterns) {
|
|
540
|
+
if (!isObj(pattern) || typeof pattern.type !== "string" || pattern.type === "" || typeof pattern.regex !== "string" || pattern.regex === "") {
|
|
541
|
+
throw new ConfigError("secrets.extra_patterns entries must be {type, regex} with non-empty strings");
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
new RegExp(pattern.regex);
|
|
545
|
+
} catch {
|
|
546
|
+
throw new ConfigError(`secrets.extra_patterns.${pattern.type}: not a valid regex: ${pattern.regex}`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
515
549
|
for (const [key, value] of Object.entries(cfg.paths)) {
|
|
516
550
|
if (key === "work_roots") {
|
|
517
551
|
if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
|
package/src/core/guards.ts
CHANGED
|
@@ -700,12 +700,13 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
|
|
|
700
700
|
return ALLOW;
|
|
701
701
|
}
|
|
702
702
|
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
703
|
-
// Strict landing gate (20261025_1940 P2): in tier strict every push/merge waits for the
|
|
704
|
-
// owner's
|
|
705
|
-
// Opinionated and full keep today's allowance. Owner-only rules above are
|
|
703
|
+
// Strict landing gate (20261025_1940 P2, P5): in tier strict every push/merge waits for the
|
|
704
|
+
// owner's approve phrase (autonomy.go_phrase, default "go push"); the landing that consumes
|
|
705
|
+
// it goes through. Opinionated and full keep today's allowance. Owner-only rules above are
|
|
706
|
+
// untouched.
|
|
706
707
|
if (landingCommand(input) && currentTier(cfg) === "strict" && !takeGo(cfg)) {
|
|
707
|
-
log(cfg.paths.guard_log, "BLOCK landing: tier strict, no
|
|
708
|
-
return deny(
|
|
708
|
+
log(cfg.paths.guard_log, "BLOCK landing: tier strict, no approve phrase");
|
|
709
|
+
return deny(`main-guard: tier strict — type "${cfg.autonomy.go_phrase}" to approve one push/merge`);
|
|
709
710
|
}
|
|
710
711
|
const command = String(input?.command ?? input?.code ?? "");
|
|
711
712
|
for (const entry of cfg.guards.bypass_spawn) {
|
|
@@ -937,7 +938,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
|
937
938
|
const tier = currentTier(cfg);
|
|
938
939
|
const tierNote =
|
|
939
940
|
tier === "strict"
|
|
940
|
-
? `Main changes at most ${cfg.autonomy.strict_edit_limit} project files per ${cfg.guards.main_window_min} min, and every git push / glab mr merge / gh pr merge waits for your "
|
|
941
|
+
? `Main changes at most ${cfg.autonomy.strict_edit_limit} project files per ${cfg.guards.main_window_min} min, and every git push / glab mr merge / gh pr merge waits for your "${cfg.autonomy.go_phrase}" (one landing, valid ${cfg.autonomy.go_minutes} min).`
|
|
941
942
|
: tier === "full"
|
|
942
943
|
? `Main works unattended: no edit cap, its own "Priority skip: <plan> — Main: \\"<reason>\\"" skips pass, pushes and merges go through. Owner-only moves (guard files, the phone page, notify secrets, the unlock) stay locked.`
|
|
943
944
|
: `Main changes at most ${cfg.guards.main_edit_limit} project files per ${cfg.guards.main_window_min} min; pushes and merges go through.`;
|
package/src/core/notify.ts
CHANGED
|
@@ -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(
|
|
223
|
+
out.push(await postChunks(p, url, notifyChunks(scrubbed, limit)));
|
|
219
224
|
}
|
|
220
225
|
return out;
|
|
221
226
|
});
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
// Secrets never reach the model, the chat or the session log (plan 20261025_2204, incident
|
|
2
|
+
// I-20261025-197). Detection is by CONTENT, not by file name: gitleaks-style shapes plus the exact
|
|
3
|
+
// values this machine holds (env vars, ~/.npmrc, dotenv files under the work roots, notify webhook
|
|
4
|
+
// URLs). Every hit becomes `[REDACTED:<type>]`; the value itself never appears in the returned
|
|
5
|
+
// text, in the hit list or in a log line — the hits carry a type and a count only.
|
|
6
|
+
//
|
|
7
|
+
// Pure TypeScript, no harness and no agent: the harness adapter (tool_result), notify.ts (outbound
|
|
8
|
+
// posts), `neurastream redact` and doctor all call this one module.
|
|
9
|
+
|
|
10
|
+
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import type { Config } from "./config.ts";
|
|
14
|
+
|
|
15
|
+
/** One owner-defined shape: the marker type and its regex source. */
|
|
16
|
+
export interface SecretPattern {
|
|
17
|
+
type: string;
|
|
18
|
+
regex: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RedactHit {
|
|
22
|
+
type: string;
|
|
23
|
+
count: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface RedactResult {
|
|
27
|
+
text: string;
|
|
28
|
+
hits: RedactHit[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface Rule {
|
|
32
|
+
/** Named in `[REDACTED:<type>]` and in the hit summary. */
|
|
33
|
+
type: string;
|
|
34
|
+
regex: RegExp;
|
|
35
|
+
/** Leading capture groups kept verbatim (a key name, an assignment prefix) before the marker. */
|
|
36
|
+
keep?: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Shape rules in application order: a structural prefix (`_authToken=`, a URL's user part) is
|
|
40
|
+
// recognised before the bare token shapes, and the generic assignment rule runs after both so a
|
|
41
|
+
// token keeps its own type name. Every regex is linear: no nested quantifier over the same text.
|
|
42
|
+
// The `(?!\[REDACTED:)` lookahead keeps a rule from matching a value an earlier rule already
|
|
43
|
+
// replaced — `OPENAI_API_KEY=[REDACTED:sk-key]` must not become a generic hit.
|
|
44
|
+
const RULES: Rule[] = [
|
|
45
|
+
{ type: "private-key", regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g },
|
|
46
|
+
{ type: "npmrc-auth-token", regex: /(_authToken\s*=\s*)(?!\[REDACTED:)\S+/g, keep: 1 },
|
|
47
|
+
{ type: "npmrc-password", regex: /(_password\s*=\s*)(?!\[REDACTED:)\S+/g, keep: 1 },
|
|
48
|
+
{ type: "url-password", regex: /\b([a-z][a-z0-9+.-]*:\/\/[^\s/@:]+:)(?!\[REDACTED:)[^\s/@]+(?=@)/gi, keep: 1 },
|
|
49
|
+
{ type: "aws-secret-access-key", regex: /(aws_secret_access_key\s*[:=]\s*['"]?)(?!\[REDACTED:)[A-Za-z0-9/+=]{16,}/gi, keep: 1 },
|
|
50
|
+
{ type: "aws-access-key-id", regex: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
|
|
51
|
+
{ type: "github-token", regex: /\b(?:gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,})\b/g },
|
|
52
|
+
{ type: "gitlab-token", regex: /\bglpat-[A-Za-z0-9_-]{16,}\b/g },
|
|
53
|
+
{ type: "npm-token", regex: /\bnpm_[A-Za-z0-9]{36}\b/g },
|
|
54
|
+
{ type: "sk-key", regex: /\bsk-(?:ant-|or-|proj-)?[A-Za-z0-9_-]{16,}\b/g },
|
|
55
|
+
{ type: "google-api-key", regex: /\bAIza[0-9A-Za-z_-]{35}\b/g },
|
|
56
|
+
{ type: "slack-token", regex: /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g },
|
|
57
|
+
{ type: "discord-webhook", regex: /\bhttps?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_-]+/g },
|
|
58
|
+
{ type: "stripe-key", regex: /\b[rs]k_(?:live|test)_[A-Za-z0-9]{10,}\b/g },
|
|
59
|
+
{ type: "jwt", regex: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g },
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
// Runs after the shapes above and after the owner's own patterns, so a specific shape names the
|
|
63
|
+
// value first; only what nothing else recognised becomes `generic-secret`. The key name may be
|
|
64
|
+
// a multi-part name (`DB_PASSWORD=`, `MY_APP_TOKEN:`): the identifier is kept whole, so the reader still
|
|
65
|
+
// sees which key was hidden, and only the value goes.
|
|
66
|
+
const GENERIC_RULE: Rule = {
|
|
67
|
+
type: "generic-secret",
|
|
68
|
+
regex: /([A-Za-z0-9_.-]*(?:password|passwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret))(\s*[:=]\s*)(['"]?)(?!\[REDACTED:)([^\s'",;]{8,})/gi,
|
|
69
|
+
keep: 3,
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** The external proxy that can sit on the wire as a second net (plan 20261025_2204, P3). */
|
|
73
|
+
export const PROXY_BIN = "secretgate";
|
|
74
|
+
|
|
75
|
+
/** Whether the proxy binary is on PATH. Never spawned here: launch and doctor only need to know. */
|
|
76
|
+
export function proxyOnPath(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
77
|
+
for (const dir of (env.PATH ?? "").split(":")) {
|
|
78
|
+
if (dir === "") continue;
|
|
79
|
+
try {
|
|
80
|
+
if (statSync(join(dir, PROXY_BIN)).isFile()) return true;
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A known value shorter than this is not redacted: it would shred ordinary text. */
|
|
87
|
+
const MIN_KNOWN_LEN = 8;
|
|
88
|
+
|
|
89
|
+
/** Env var names whose values count as secrets. */
|
|
90
|
+
const SECRET_ENV_NAME = /KEY|TOKEN|SECRET|PASSWORD|PASS|AUTH|CREDENTIAL|WEBHOOK/i;
|
|
91
|
+
|
|
92
|
+
/** A dotenv file at the top of a repo: `.` + `env` and anything after it (`.env`, `.env.local`). */
|
|
93
|
+
const DOTENV_NAME = /^\.env/;
|
|
94
|
+
|
|
95
|
+
/** Files larger than this are not scanned for values: no env file or webhook file is that big. */
|
|
96
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
97
|
+
|
|
98
|
+
function bump(counts: Map<string, number>, type: string): void {
|
|
99
|
+
counts.set(type, (counts.get(type) ?? 0) + 1);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function escapeRegExp(value: string): string {
|
|
103
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const extraCache = new Map<string, RegExp>();
|
|
107
|
+
|
|
108
|
+
/** Owner-defined shapes, built once per process; a bad regex cannot reach here (config.check). */
|
|
109
|
+
function extraRules(extra: SecretPattern[]): Rule[] {
|
|
110
|
+
const out: Rule[] = [];
|
|
111
|
+
for (const p of extra) {
|
|
112
|
+
if (typeof p?.type !== "string" || p.type === "" || typeof p.regex !== "string" || p.regex === "") continue;
|
|
113
|
+
let re = extraCache.get(p.regex);
|
|
114
|
+
if (!re) {
|
|
115
|
+
try {
|
|
116
|
+
re = new RegExp(p.regex, "g");
|
|
117
|
+
} catch {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
extraCache.set(p.regex, re);
|
|
121
|
+
}
|
|
122
|
+
out.push({ type: p.type, regex: re });
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function applyRule(text: string, rule: Rule, counts: Map<string, number>): string {
|
|
128
|
+
const keep = rule.keep ?? 0;
|
|
129
|
+
return text.replace(rule.regex, (...args: unknown[]) => {
|
|
130
|
+
const prefix = args
|
|
131
|
+
.slice(1, 1 + keep)
|
|
132
|
+
.map(g => (typeof g === "string" ? g : ""))
|
|
133
|
+
.join("");
|
|
134
|
+
bump(counts, rule.type);
|
|
135
|
+
return `${prefix}[REDACTED:${rule.type}]`;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Exact values, deduped, longest first so a value that contains another is matched whole. */
|
|
140
|
+
function knownPattern(values: Iterable<string>): RegExp | null {
|
|
141
|
+
const seen = new Set<string>();
|
|
142
|
+
for (const value of values) {
|
|
143
|
+
const text = value.trim();
|
|
144
|
+
if (text.length >= MIN_KNOWN_LEN) seen.add(text);
|
|
145
|
+
}
|
|
146
|
+
if (seen.size === 0) return null;
|
|
147
|
+
const pattern = [...seen]
|
|
148
|
+
.sort((a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0))
|
|
149
|
+
.map(escapeRegExp)
|
|
150
|
+
.join("|");
|
|
151
|
+
return new RegExp(pattern, "g");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Replaces every secret in `text` with `[REDACTED:<type>]` and reports what it hid. `known` holds
|
|
156
|
+
* exact values (see `loadKnownSecrets`); `extra` holds the owner's own shapes. Running it twice on
|
|
157
|
+
* the same text is stable: a marker matches no rule.
|
|
158
|
+
*/
|
|
159
|
+
export function redactSecrets(text: string, known: Iterable<string> = [], extra: SecretPattern[] = []): RedactResult {
|
|
160
|
+
if (text === "") return { text, hits: [] };
|
|
161
|
+
const counts = new Map<string, number>();
|
|
162
|
+
let out = text;
|
|
163
|
+
for (const rule of RULES) out = applyRule(out, rule, counts);
|
|
164
|
+
for (const rule of extraRules(extra)) out = applyRule(out, rule, counts);
|
|
165
|
+
out = applyRule(out, GENERIC_RULE, counts);
|
|
166
|
+
const knownRe = knownPattern(known);
|
|
167
|
+
if (knownRe) {
|
|
168
|
+
out = out.replace(knownRe, () => {
|
|
169
|
+
bump(counts, "known-value");
|
|
170
|
+
return "[REDACTED:known-value]";
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
return { text: out, hits: [...counts].map(([type, count]) => ({ type, count })) };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The one line the adapter adds to a tool result when it hid anything. Types only, never values. */
|
|
177
|
+
export function redactSummary(hits: RedactHit[]): string {
|
|
178
|
+
const total = hits.reduce((n, h) => n + h.count, 0);
|
|
179
|
+
return `secret-redact: hid ${total} value(s) (${hits.map(h => h.type).join(", ")})`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// --- known values ---
|
|
183
|
+
|
|
184
|
+
interface CachedFile {
|
|
185
|
+
mtimeMs: number;
|
|
186
|
+
size: number;
|
|
187
|
+
values: string[];
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
type FileKind = "npmrc" | "env" | "text";
|
|
191
|
+
|
|
192
|
+
const fileCache = new Map<string, CachedFile>();
|
|
193
|
+
let discovered: { roots: string; atMs: number; files: string[] } | null = null;
|
|
194
|
+
/** The work-root dotenv list is a directory walk, not a file read: rescan at this interval. */
|
|
195
|
+
const DISCOVERY_TTL_MS = 60_000;
|
|
196
|
+
const MAX_REPO_DIRS = 500;
|
|
197
|
+
|
|
198
|
+
/** Forgets every cached file and the discovered dotenv list (tests switch sandboxes). */
|
|
199
|
+
export function clearKnownSecretsCache(): void {
|
|
200
|
+
fileCache.clear();
|
|
201
|
+
discovered = null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** `_authToken` and `_password` values of an npmrc. */
|
|
205
|
+
function npmrcValues(text: string): string[] {
|
|
206
|
+
const out: string[] = [];
|
|
207
|
+
for (const line of text.split("\n")) {
|
|
208
|
+
const m = /^\s*(?:\/\/[^\s=]*:)?_(?:authToken|password)\s*=\s*(\S+)/i.exec(line);
|
|
209
|
+
if (m?.[1]) out.push(m[1]);
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** `KEY=value` values of an env-style file (quotes stripped, comments ignored). */
|
|
215
|
+
function envValues(text: string): string[] {
|
|
216
|
+
const out: string[] = [];
|
|
217
|
+
for (const line of text.split("\n")) {
|
|
218
|
+
const m = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/.exec(line);
|
|
219
|
+
if (!m?.[1]) continue;
|
|
220
|
+
let value = m[1].trim();
|
|
221
|
+
if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) value = value.slice(1, -1);
|
|
222
|
+
const hash = value.search(/\s#/);
|
|
223
|
+
if (hash !== -1) value = value.slice(0, hash).trim();
|
|
224
|
+
if (value !== "") out.push(value);
|
|
225
|
+
}
|
|
226
|
+
return out;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function fileValues(path: string, kind: FileKind): string[] {
|
|
230
|
+
const key = `${kind}\0${path}`;
|
|
231
|
+
let size: number;
|
|
232
|
+
let mtimeMs: number;
|
|
233
|
+
try {
|
|
234
|
+
const st = statSync(path);
|
|
235
|
+
if (!st.isFile() || st.size > MAX_FILE_BYTES) return [];
|
|
236
|
+
size = st.size;
|
|
237
|
+
mtimeMs = st.mtimeMs;
|
|
238
|
+
} catch {
|
|
239
|
+
fileCache.delete(key);
|
|
240
|
+
return [];
|
|
241
|
+
}
|
|
242
|
+
const hit = fileCache.get(key);
|
|
243
|
+
if (hit && hit.mtimeMs === mtimeMs && hit.size === size) return hit.values;
|
|
244
|
+
let text: string;
|
|
245
|
+
try {
|
|
246
|
+
text = readFileSync(path, "utf8");
|
|
247
|
+
} catch {
|
|
248
|
+
return hit?.values ?? [];
|
|
249
|
+
}
|
|
250
|
+
const values = kind === "npmrc" ? npmrcValues(text) : kind === "env" ? envValues(text) : [text.trim()];
|
|
251
|
+
fileCache.set(key, { mtimeMs, size, values });
|
|
252
|
+
return values;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Dotenv files at the top of `dir` (its own, not its subdirectories'). */
|
|
256
|
+
function envFilesIn(dir: string): string[] {
|
|
257
|
+
let entries;
|
|
258
|
+
try {
|
|
259
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
260
|
+
} catch {
|
|
261
|
+
return [];
|
|
262
|
+
}
|
|
263
|
+
return entries.filter(e => e.isFile() && DOTENV_NAME.test(e.name)).map(e => join(dir, e.name));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Every top-level dotenv file under a work root, plus each repo directory's own. */
|
|
267
|
+
function workRootEnvFiles(roots: string[]): string[] {
|
|
268
|
+
const key = roots.join("\0");
|
|
269
|
+
const nowMs = Date.now();
|
|
270
|
+
if (discovered && discovered.roots === key && nowMs - discovered.atMs < DISCOVERY_TTL_MS) return discovered.files;
|
|
271
|
+
const files = new Set<string>();
|
|
272
|
+
for (const root of roots) {
|
|
273
|
+
for (const file of envFilesIn(root)) files.add(file);
|
|
274
|
+
let repos;
|
|
275
|
+
try {
|
|
276
|
+
repos = readdirSync(root, { withFileTypes: true });
|
|
277
|
+
} catch {
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
let seen = 0;
|
|
281
|
+
for (const entry of repos) {
|
|
282
|
+
if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
283
|
+
if (seen++ >= MAX_REPO_DIRS) break;
|
|
284
|
+
for (const file of envFilesIn(join(root, entry.name))) files.add(file);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const list = [...files];
|
|
288
|
+
discovered = { roots: key, atMs: nowMs, files: list };
|
|
289
|
+
return list;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** The notify webhook files: the URL in one is a secret like any other (config holds only paths). */
|
|
293
|
+
function notifyFiles(cfg: Config): string[] {
|
|
294
|
+
return [cfg.notify.discord_webhook_file, cfg.notify.slack_webhook_file].filter(f => typeof f === "string" && f !== "");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The exact values this machine holds, so a secret is hidden wherever it appears whatever the file
|
|
299
|
+
* is called: env vars whose name looks like a credential, `~/.npmrc`, `secrets.known_value_files`,
|
|
300
|
+
* every top-level dotenv file under `paths.work_roots`, and the notify webhook files. File contents
|
|
301
|
+
* are cached per process and re-read when a file's mtime or size changes.
|
|
302
|
+
*/
|
|
303
|
+
export function loadKnownSecrets(cfg: Config, env: NodeJS.ProcessEnv = process.env): string[] {
|
|
304
|
+
const out = new Set<string>();
|
|
305
|
+
const add = (value: string): void => {
|
|
306
|
+
const text = value.trim();
|
|
307
|
+
if (text.length >= MIN_KNOWN_LEN) out.add(text);
|
|
308
|
+
};
|
|
309
|
+
for (const [name, value] of Object.entries(env)) {
|
|
310
|
+
if (typeof value === "string" && SECRET_ENV_NAME.test(name)) add(value);
|
|
311
|
+
}
|
|
312
|
+
for (const value of fileValues(join(homedir(), ".npmrc"), "npmrc")) add(value);
|
|
313
|
+
for (const file of cfg.secrets.known_value_files) for (const value of fileValues(file, "env")) add(value);
|
|
314
|
+
for (const file of workRootEnvFiles(cfg.paths.work_roots)) for (const value of fileValues(file, "env")) add(value);
|
|
315
|
+
for (const file of notifyFiles(cfg)) for (const value of fileValues(file, "text")) add(value);
|
|
316
|
+
return [...out];
|
|
317
|
+
}
|
package/templates/AGENTS.md
CHANGED
|
@@ -28,4 +28,4 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
|
|
|
28
28
|
|
|
29
29
|
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).
|
|
30
30
|
|
|
31
|
-
Autonomy tiers: the owner sets how much Main does unattended with one word — `tier strict` (edit cap `autonomy.strict_edit_limit`; every `git push`, `glab mr merge` or `gh pr merge` also waits until the owner types `go
|
|
31
|
+
Autonomy tiers: the owner sets how much Main does unattended with one word — `tier strict` (edit cap `autonomy.strict_edit_limit`; every `git push`, `glab mr merge` or `gh pr merge` also waits until the owner types the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message), which approves exactly one landing for `autonomy.go_minutes` minutes), `tier opinionated` (the limits above), or `tier full` (no edit cap, and a `Priority skip: <plan> — Main: "<reason>"` line with a reason of at least four words may skip an idle higher plan). Pushes stay owner-ruled in strict and opinionated as above; whatever the tier, guard files, the phone page, notify secrets and the unlock stay owner-only.
|
package/templates/config.yml
CHANGED
|
@@ -128,7 +128,8 @@ guards:
|
|
|
128
128
|
autonomy:
|
|
129
129
|
tier: opinionated # strict | opinionated | full: how much Main does without asking; the owner moves it with `tier <name>` in chat or a button on the phone page
|
|
130
130
|
strict_edit_limit: 2 # Main's project-file changes per main_window_min in tier strict
|
|
131
|
-
go_minutes: 10 # minutes
|
|
131
|
+
go_minutes: 10 # minutes the approve phrase approves exactly one push/merge in tier strict
|
|
132
|
+
go_phrase: "go push" # the whole chat message that approves one push/merge in tier strict (I-20261025-201); a bare `go` is an ordinary message
|
|
132
133
|
|
|
133
134
|
ui:
|
|
134
135
|
enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
|
|
@@ -186,6 +187,12 @@ notify:
|
|
|
186
187
|
slack_webhook_file: "" # file holding the Slack webhook URL; "" = off
|
|
187
188
|
prefix: "" # optional label prepended to each posted reply, e.g. "Main:"
|
|
188
189
|
|
|
190
|
+
secrets: # content redaction (src/core/secret-redact.ts); a hit prints as [REDACTED:<type>]
|
|
191
|
+
redact: true # every tool result, every notify post and `neurastream redact` go through the redactor
|
|
192
|
+
known_value_files: ["~/.npmrc"] # files whose KEY=value lines are secret values; every top-level `.env…` file under paths.work_roots is read too
|
|
193
|
+
extra_patterns: [] # your own shapes, e.g. [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
|
|
194
|
+
proxy: "none" # "none" | "secretgate": launch the harness as `secretgate wrap -- omp` (README: Secrets)
|
|
195
|
+
|
|
189
196
|
priority:
|
|
190
197
|
sleep_sec: 120
|
|
191
198
|
|