neurastream 0.2.12 → 0.2.14
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 +31 -1
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +130 -9
- package/src/adapters/omp/install.ts +14 -7
- package/src/adapters/omp/sessions.ts +10 -4
- package/src/adapters/omp/traces.ts +167 -0
- package/src/cli/dispatch.ts +11 -0
- package/src/cli/guard.ts +7 -1
- package/src/cli/traces.ts +157 -0
- package/src/core/adapter.ts +36 -0
- package/src/core/agent-score.ts +7 -0
- package/src/core/config.ts +36 -0
- package/src/core/guards.ts +136 -14
- package/src/core/incident-detectors.ts +88 -1
- package/src/core/incidents.ts +2 -2
- package/src/core/owner-ui.ts +586 -100
- package/src/core/queue/lib.ts +18 -12
- package/src/core/rate-limit.ts +63 -0
- package/src/core/trace-actions.ts +487 -0
- package/src/core/trace-claims.ts +239 -0
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +29 -0
package/README.md
CHANGED
|
@@ -94,11 +94,15 @@ Owner rule: never write a plan when another agent is doing the research or readi
|
|
|
94
94
|
|
|
95
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.
|
|
96
96
|
|
|
97
|
+
## Queue priority
|
|
98
|
+
|
|
99
|
+
`INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names: a higher plan that is idle (open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase) and not staffed by a running job must be named in a `Priority skip: <plan> — <why>` line, or the spawn is refused. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page.
|
|
100
|
+
|
|
97
101
|
## Owner page (`neurastream ui`)
|
|
98
102
|
|
|
99
103
|
`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`.
|
|
100
104
|
|
|
101
|
-
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).
|
|
105
|
+
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). The page reads top to bottom: a sticky status strip with the amber "needs you" count plus working/CI/disk signals that turn red only when something is actually wrong; 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 named actions ("Yes, go ahead", "No", "Reply…") whose answer shows as a one-time receipt ("Sent to Main · 08:12"); a working-now row per running or waiting agent; and closed details blocks for the queue (one flat 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"), merges/CI, incidents, agent scores (a real table) and machine health. A sticky bottom bar holds the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now") and, when `guards.chat_unlock` is off, says so in plain words with the exact config line. 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>` renders a preview without a server). No chat, no plan editing, no shell.
|
|
102
106
|
|
|
103
107
|
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.
|
|
104
108
|
|
|
@@ -172,6 +176,32 @@ Guard rules around it:
|
|
|
172
176
|
|
|
173
177
|
"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.
|
|
174
178
|
|
|
179
|
+
## Provider rate limits
|
|
180
|
+
|
|
181
|
+
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:
|
|
182
|
+
|
|
183
|
+
```
|
|
184
|
+
RATE-LIMIT stop: resume at 08:12 (35s, attempt 1)
|
|
185
|
+
notify: posted (rate-limit)
|
|
186
|
+
RATE-LIMIT resume: new turn sent (waited until 08:12)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: the wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message before expiry takes over and cancels the resume (`RATE-LIMIT resume cancelled: owner message`), and a rate-limited deferred hand-back (an `agent_end` while an async job is pending) arms the same timer instead of logging "no reply text". The words and the waits live in `config.yml` (`guards.rate_limit`, `docs/config.md`); turns that did not end on a rate limit are unaffected.
|
|
190
|
+
|
|
191
|
+
omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what neurastream waits out.
|
|
192
|
+
|
|
193
|
+
## Trace claims (`neurastream traces claims`)
|
|
194
|
+
|
|
195
|
+
Agents' final reports assert results — "530 passed", "exit 0", commit SHAs, heavy-run labels, changed files. This command reads a run's trace (its session file, read-only) and checks each claim in the run's last assistant message against what the run's own tool activity shows: a count or exit code must appear in some tool output, a commit SHA must be printed by the output of a git command the run itself ran, a heavy-run label must appear in a quoted heavy-run call, and a changed path must be carried by an edit/write call or a shell write in the path's own command segment. A claim nothing shows becomes a `claim-unbacked` finding.
|
|
196
|
+
|
|
197
|
+
```
|
|
198
|
+
neurastream traces claims --since 24h # every run touched in the window
|
|
199
|
+
neurastream traces claims NsTracesVerifyGlm # one run, by id
|
|
200
|
+
neurastream traces claims --since 24h --json # machine-readable
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Known boundary: a report that cites other runs' work (Main quoting a subagent, a relaunched agent quoting its predecessor) can produce `claim-unbacked` findings that are true in this run's trace but provable only in the cited run's own trace.
|
|
204
|
+
|
|
175
205
|
## Self-metrics
|
|
176
206
|
|
|
177
207
|
`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
|
@@ -21,16 +21,19 @@ 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, strftime } from "../../core/clock.ts";
|
|
24
|
-
import { runDetectorsGated } from "../../core/incident-detectors.ts";
|
|
25
|
-
import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
|
|
24
|
+
import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
|
|
25
|
+
import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
|
|
26
|
+
import { rateLimitWait } from "../../core/rate-limit.ts";
|
|
26
27
|
import { notifyProviders, postReply } from "../../core/notify.ts";
|
|
27
28
|
import { inboxPath } from "../../core/owner-ui.ts";
|
|
28
29
|
import { realTailscale } from "../../core/tailscale.ts";
|
|
30
|
+
import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
|
|
29
31
|
import { applyQueueEnv } from "../../core/queue/env.ts";
|
|
30
32
|
import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
|
|
31
33
|
import { readBlocks } from "../../core/metrics.ts";
|
|
32
34
|
import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
|
|
33
|
-
import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
|
|
35
|
+
import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
|
|
36
|
+
import { parseTraceFile } from "./traces.ts";
|
|
34
37
|
import { packageJsonPath, packageVersion } from "./package-root.ts";
|
|
35
38
|
import * as q from "../../core/queue/lib.ts";
|
|
36
39
|
// Registers the plugin-command matcher into core's writeTargets (side effect).
|
|
@@ -70,6 +73,8 @@ interface EventReply {
|
|
|
70
73
|
text: string;
|
|
71
74
|
stopReason: string | null;
|
|
72
75
|
toolCalls: number;
|
|
76
|
+
/** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
|
|
77
|
+
errorMessage: string | null;
|
|
73
78
|
}
|
|
74
79
|
|
|
75
80
|
function lastAssistantIn(messages: unknown): EventReply | null {
|
|
@@ -87,6 +92,7 @@ function lastAssistantIn(messages: unknown): EventReply | null {
|
|
|
87
92
|
text,
|
|
88
93
|
stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
|
|
89
94
|
toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
|
|
95
|
+
errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
|
|
90
96
|
};
|
|
91
97
|
}
|
|
92
98
|
return null;
|
|
@@ -148,6 +154,41 @@ function mainDetectors(cfg: Config, extra: { prompt?: string; bash?: { command:
|
|
|
148
154
|
}
|
|
149
155
|
}
|
|
150
156
|
|
|
157
|
+
/**
|
|
158
|
+
* D6 + D7 over a subagent's own trace, right after an allowed Progress edit (plan
|
|
159
|
+
* 20261024_0301 P6): the sub's session file (its harness session manager hands it out) is
|
|
160
|
+
* parsed as the run's trace, every high suspicious action folds as a D6 incident, and when the
|
|
161
|
+
* new Progress bullet claims `Findings: none` the cross-product reads hidden behind that claim
|
|
162
|
+
* fold as D7 (`unreported-finding`) with the agent-score penalty — the bullet is the claim
|
|
163
|
+
* source the owner named, so it replaces the final-text check. The newest added bullet decides
|
|
164
|
+
* (Progress runs newest-first). Best effort: a failure is logged, never thrown — a broken
|
|
165
|
+
* detector must not break the verified edit.
|
|
166
|
+
*/
|
|
167
|
+
function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before: string, after: string): void {
|
|
168
|
+
try {
|
|
169
|
+
const entries = newProgressEntries(before, after);
|
|
170
|
+
if (entries.length === 0) return;
|
|
171
|
+
const sessionFile = call(asRecord(asRecord(ctx).sessionManager), "getSessionFile");
|
|
172
|
+
if (typeof sessionFile !== "string" || sessionFile === "") return;
|
|
173
|
+
const events = parseTraceFile(sessionFile, runIdOf(sessionFile));
|
|
174
|
+
const rules = actionsRules(cfg);
|
|
175
|
+
const input: DetectorInput = { actions: suspiciousActions(events, rules) };
|
|
176
|
+
if (/^none\.?$/i.test(findingsValue(entries[0]!) ?? "")) {
|
|
177
|
+
// The plan's repo spelled like its owned_repos entry: a checkout named "pm-mr196" is "pm",
|
|
178
|
+
// so the run's reads of its own repo never count as another product's.
|
|
179
|
+
const repoDir = q.planRepo(planFile);
|
|
180
|
+
input.unreported = unreportedFindings(events, rules, {
|
|
181
|
+
repo: ownedRepoOf(`${repoDir}/`, rules.owned_repos) ?? basename(repoDir),
|
|
182
|
+
plan: planFile,
|
|
183
|
+
claimedNone: true,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
runDetectors(cfg, input);
|
|
187
|
+
} catch (err) {
|
|
188
|
+
adapterLog(cfg, `sub action detectors failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
151
192
|
// Background queue-close for every plan Main marked complete. Ported from the
|
|
152
193
|
// original autoClose: same filter, same "--- auto-close attempt" log line, detached child with
|
|
153
194
|
// stdio on the per-plan close log. QUEUE_CLOSE_BIN overrides the binary (tests); without it the
|
|
@@ -419,6 +460,48 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
419
460
|
// emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
|
|
420
461
|
// mid-work report, never a hand-back.
|
|
421
462
|
let stopBlocked = false;
|
|
463
|
+
// Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
|
|
464
|
+
// form one episode. The attempt doubles the wait, the owner chat is told once per episode, and
|
|
465
|
+
// ONE timer gives Main a new turn when the wait is over; an owner message before expiry takes
|
|
466
|
+
// over and cancels it. Any turn that ends without a limit resets the episode and disarms it.
|
|
467
|
+
let rateAttempt = 0;
|
|
468
|
+
let rateTimer: NodeJS.Timeout | null = null;
|
|
469
|
+
const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
|
|
470
|
+
const clearRateTimer = (): void => {
|
|
471
|
+
if (rateTimer !== null) {
|
|
472
|
+
clearTimeout(rateTimer);
|
|
473
|
+
rateTimer = null;
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
const disarmRateEpisode = (): void => {
|
|
477
|
+
clearRateTimer();
|
|
478
|
+
rateAttempt = 0;
|
|
479
|
+
};
|
|
480
|
+
// The one resume: replacing any armed timer, exactly one new user message when the wait is over.
|
|
481
|
+
const armRateResume = (untilMs: number): void => {
|
|
482
|
+
clearRateTimer();
|
|
483
|
+
rateTimer = setTimeout(() => {
|
|
484
|
+
rateTimer = null;
|
|
485
|
+
pi.sendUserMessage(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`);
|
|
486
|
+
adapterLog(cfg, `RATE-LIMIT resume: new turn sent (waited until ${rateClock(untilMs)})`);
|
|
487
|
+
}, untilMs - Date.now());
|
|
488
|
+
};
|
|
489
|
+
// A turn that ended on a rate limit: log, tell the owner once per episode, arm the resume.
|
|
490
|
+
const onRateLimitedStop = (untilMs: number, waitMs: number): void => {
|
|
491
|
+
rateAttempt++;
|
|
492
|
+
const at = rateClock(untilMs);
|
|
493
|
+
adapterLog(cfg, `RATE-LIMIT stop: resume at ${at} (${Math.round(waitMs / 1000)}s, attempt ${rateAttempt})`);
|
|
494
|
+
if (rateAttempt === 1) {
|
|
495
|
+
adapterLog(cfg, "notify: posted (rate-limit)");
|
|
496
|
+
void postReply(`⏳ Main is rate limited by its provider until ${at} (local); it resumes on its own.`, cfg).then(results => {
|
|
497
|
+
for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
armRateResume(untilMs);
|
|
501
|
+
};
|
|
502
|
+
// The rate-limit decision for one turn end, from the event's own last assistant message.
|
|
503
|
+
const rateLimitOf = (reply: EventReply | null): { untilMs: number; waitMs: number } | null =>
|
|
504
|
+
rateLimitWait(reply?.stopReason ?? null, reply?.errorMessage ?? null, Date.now(), cfg.guards.rate_limit, rateAttempt + 1);
|
|
422
505
|
// One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
|
|
423
506
|
// the decision never awaits the post; a failed or slow post logs one line and never blocks
|
|
424
507
|
// or retries.
|
|
@@ -583,11 +666,14 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
583
666
|
const snap = new Map<string, string>();
|
|
584
667
|
snapshotPlans(tool, input, cwd, snap, !isSub);
|
|
585
668
|
// Drain (src/core/rollover.ts): while a rollover is pending no new subagent starts; the
|
|
586
|
-
// running ones finish first. Subagents' own tool calls are unaffected.
|
|
587
|
-
|
|
669
|
+
// running ones finish first. Subagents' own tool calls are unaffected. Main's task calls
|
|
670
|
+
// also carry the running job labels for the priority gate (20261025_0215 P2).
|
|
671
|
+
let runningJobs: string[] | undefined;
|
|
672
|
+
if (!isSub && tool === "task") {
|
|
588
673
|
const rc = asRolloverCtx(ctx);
|
|
589
|
-
|
|
590
|
-
|
|
674
|
+
runningJobs = rc?.runningJobs();
|
|
675
|
+
if (cfg.rollover.enabled && rc) {
|
|
676
|
+
const why = spawnRefusal(rolloverSnapshot(rc).state, runningJobs ?? []);
|
|
591
677
|
if (why) {
|
|
592
678
|
const tasks = Array.isArray(input.tasks) ? input.tasks : [];
|
|
593
679
|
adapterLog(cfg, `BLOCK spawn ${String(asRecord(tasks[0]).agent ?? "task")}: rollover pending`);
|
|
@@ -596,7 +682,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
596
682
|
}
|
|
597
683
|
}
|
|
598
684
|
const d = checkTool(
|
|
599
|
-
{ tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command) },
|
|
685
|
+
{ tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command), runningJobs },
|
|
600
686
|
cfg,
|
|
601
687
|
);
|
|
602
688
|
if (!d.allow) {
|
|
@@ -645,6 +731,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
645
731
|
const note = trimProgress(file);
|
|
646
732
|
if (note) notes.push(note);
|
|
647
733
|
}
|
|
734
|
+
// Live D6+D7 over the sub's own session as soon as it reports into the plan (P6).
|
|
735
|
+
if (d.allow && c.kind === "sub") subActionDetectors(cfg, ctx, file, before, after);
|
|
648
736
|
}
|
|
649
737
|
}
|
|
650
738
|
if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash" && !e.isError) {
|
|
@@ -683,6 +771,16 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
683
771
|
// BEFORE agent_end, so a file read would lag a whole turn.
|
|
684
772
|
const stopMsg = asRecord(e).last_assistant_message;
|
|
685
773
|
const reply = stopMsg ? lastAssistantIn([stopMsg]) : lastAssistantIn(asRecord(e).messages);
|
|
774
|
+
// A turn that ended on a provider rate limit waits it out (plan 20261025_0640): ALLOW before
|
|
775
|
+
// the rollover and queue decisions — any block here would re-ask straight into the limit —
|
|
776
|
+
// and without touching the idle-stop counters: checkStop is not consulted.
|
|
777
|
+
const rl = rateLimitOf(reply);
|
|
778
|
+
if (rl) {
|
|
779
|
+
onRateLimitedStop(rl.untilMs, rl.waitMs);
|
|
780
|
+
return undefined;
|
|
781
|
+
}
|
|
782
|
+
// Any turn that ends without a rate limit ends the episode and disarms its resume timer.
|
|
783
|
+
disarmRateEpisode();
|
|
686
784
|
// A pending rollover decides the stop and checkStop is not consulted: its queue, incident and cancel
|
|
687
785
|
// blocks would hold Main at a wait the new session raises again through main-start, and its "spawn an
|
|
688
786
|
// agent" text is refused while the rollover is pending.
|
|
@@ -918,13 +1016,24 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
918
1016
|
adapterLog(cfg, "notify: skipped (stop blocked, agent_end)");
|
|
919
1017
|
return;
|
|
920
1018
|
}
|
|
1019
|
+
const reply = lastAssistantIn(asRecord(e).messages);
|
|
1020
|
+
// The same rate-limit check as session_stop (plan 20261025_0640): a rate-limited deferred
|
|
1021
|
+
// hand-back arms the resume timer instead of logging "no reply text" — its reply carries an
|
|
1022
|
+
// error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
|
|
1023
|
+
// episode state stays as it is.
|
|
1024
|
+
const rl = rateLimitOf(reply);
|
|
1025
|
+
if (rl) {
|
|
1026
|
+
onRateLimitedStop(rl.untilMs, rl.waitMs);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
921
1029
|
const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
|
|
922
1030
|
if (jobCount === 0) {
|
|
923
1031
|
adapterLog(cfg, "notify: skipped (no pending job, agent_end)");
|
|
924
1032
|
return;
|
|
925
1033
|
}
|
|
926
|
-
const reply = lastAssistantIn(asRecord(e).messages);
|
|
927
1034
|
if (!reply || !reply.text) {
|
|
1035
|
+
// A turn that ended on some other no-text outcome is a turn end without a rate limit.
|
|
1036
|
+
disarmRateEpisode();
|
|
928
1037
|
adapterLog(cfg, "notify: skipped (no reply text, agent_end hand-back)");
|
|
929
1038
|
return;
|
|
930
1039
|
}
|
|
@@ -935,6 +1044,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
935
1044
|
);
|
|
936
1045
|
return;
|
|
937
1046
|
}
|
|
1047
|
+
// A real hand-back: the turn ended without a rate limit — the episode is over.
|
|
1048
|
+
disarmRateEpisode();
|
|
938
1049
|
notifyHandback(reply, "agent_end hand-back");
|
|
939
1050
|
});
|
|
940
1051
|
// Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
|
|
@@ -974,6 +1085,16 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
|
|
|
974
1085
|
return null;
|
|
975
1086
|
};
|
|
976
1087
|
|
|
1088
|
+
// An owner message while a rate-limit resume is pending takes over: the resume timer is
|
|
1089
|
+
// cancelled (plan 20261025_0640). Registered before the chat-unlock input handler below, so it
|
|
1090
|
+
// sees every owner input even when the unlock short-circuits with { handled: true }.
|
|
1091
|
+
pi.on("input", (_event, ctx) => {
|
|
1092
|
+
if (!isMain(ctx)) return undefined;
|
|
1093
|
+
if (rateTimer === null) return undefined;
|
|
1094
|
+
clearRateTimer();
|
|
1095
|
+
adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
|
|
1096
|
+
return undefined;
|
|
1097
|
+
});
|
|
977
1098
|
// Chat unlock (guards.chat_unlock): the owner's whole message "unlock"/"unlock N"/"lock" moves
|
|
978
1099
|
// the guard unlock file (src/core/queue/lib.ts chatUnlock). Only prompts the owner really typed
|
|
979
1100
|
// count: the local terminal (input event, source "interactive") and collab guest prompts from
|
|
@@ -78,7 +78,7 @@ function copyPins(dest: string): { copied: string[]; kept: string[] } {
|
|
|
78
78
|
return { copied, kept };
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
function writeOverlay(file: string): "written" | "unchanged" {
|
|
81
|
+
export function writeOverlay(file: string): "written" | "unchanged" {
|
|
82
82
|
let text = readFileSync(file, "utf8");
|
|
83
83
|
let changed = false;
|
|
84
84
|
if (!/^adapter:/m.test(text)) {
|
|
@@ -88,13 +88,20 @@ function writeOverlay(file: string): "written" | "unchanged" {
|
|
|
88
88
|
}
|
|
89
89
|
const missing = PROTECTED.filter(p => !text.includes(p));
|
|
90
90
|
if (missing.length) {
|
|
91
|
-
const lines = missing.map(p => ` - "${p}"`).join("
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
91
|
+
const lines = missing.map(p => ` - "${p}"\n`).join("");
|
|
92
|
+
// The items always go under their own `protected:` key: the empty list becomes a block
|
|
93
|
+
// list, an existing block list gains them under its header, a missing key is added at
|
|
94
|
+
// the top of `guards:`. Any other form (a flow list with items) is the owner's to fix.
|
|
95
|
+
if (/^ {2}protected: \[\][ \t]*$/m.test(text)) {
|
|
96
|
+
text = text.replace(/^ {2}protected: \[\][ \t]*\n?/m, ` protected:\n${lines}`);
|
|
97
|
+
} else if (/^ {2}protected:[ \t]*\n/m.test(text)) {
|
|
98
|
+
text = text.replace(/^ {2}protected:[ \t]*\n/m, ` protected:\n${lines}`);
|
|
99
|
+
} else if (/^ {2}protected:/m.test(text)) {
|
|
100
|
+
throw new Error(`${file}: guards.protected is not a block list; list it as " protected:" with " - " items, then rerun`);
|
|
101
|
+
} else if (/^guards:[ \t]*\n/m.test(text)) {
|
|
102
|
+
text = text.replace(/^guards:[ \t]*\n/m, `guards:\n protected:\n${lines}`);
|
|
96
103
|
} else {
|
|
97
|
-
throw new Error(`${file} has no guards
|
|
104
|
+
throw new Error(`${file} has no guards: section to extend`);
|
|
98
105
|
}
|
|
99
106
|
changed = true;
|
|
100
107
|
}
|
|
@@ -27,13 +27,13 @@ function walk(dir: string, depth: number, out: string[]): void {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
function jsonlAt(root: string, levels: number): string[] {
|
|
30
|
+
export function jsonlAt(root: string, levels: number): string[] {
|
|
31
31
|
const out: string[] = [];
|
|
32
32
|
walk(root, levels, out);
|
|
33
33
|
return out;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
function parseTs(ts: string): number | null {
|
|
36
|
+
export function parseTs(ts: string): number | null {
|
|
37
37
|
const s = ts.slice(0, 19);
|
|
38
38
|
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(s)) return null;
|
|
39
39
|
const [date, time] = s.split("T") as [string, string];
|
|
@@ -45,7 +45,7 @@ function parseTs(ts: string): number | null {
|
|
|
45
45
|
return local.getTime() / 1000 - timezone;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
function asObj(v: unknown): Record<string, unknown> | null {
|
|
48
|
+
export 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
|
|
|
@@ -55,6 +55,12 @@ function costOf(m: Record<string, unknown>): number {
|
|
|
55
55
|
return c && typeof c.total === "number" ? c.total : 0;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/** Ledger run id for a session file: `MAIN <HH-MM-SS>` for dated main files, stem otherwise. */
|
|
59
|
+
export function runIdOf(file: string): string {
|
|
60
|
+
const stem = basename(file).slice(0, -6);
|
|
61
|
+
return /^\d{4}/.test(stem) ? `MAIN ${stem.slice(11, 19)}` : stem;
|
|
62
|
+
}
|
|
63
|
+
|
|
58
64
|
function build(file: string, cfg: Config, mtime: number): Run | null {
|
|
59
65
|
let text: string;
|
|
60
66
|
try {
|
|
@@ -64,7 +70,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
|
|
|
64
70
|
}
|
|
65
71
|
const stem = basename(file).slice(0, -6);
|
|
66
72
|
const isMain = /^\d{4}/.test(stem);
|
|
67
|
-
const id =
|
|
73
|
+
const id = runIdOf(file);
|
|
68
74
|
let model = "?";
|
|
69
75
|
let scoreModel = "?";
|
|
70
76
|
let calls = 0;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// Session-file trace reader: replays one run's raw activity as TraceEvents (plan
|
|
2
|
+
// 20261024_0300 P1). Run-id derivation matches the ledger (src/adapters/omp/sessions.ts):
|
|
3
|
+
// dated depth-1 files are main runs with id `MAIN <HH-MM-SS>` from the stem, deeper files are
|
|
4
|
+
// subagent runs with the bare stem as id. Every line type this harness writes that carries
|
|
5
|
+
// trace-relevant data is mapped; anything else (session banners, custom lines, compaction
|
|
6
|
+
// notes, unparseable lines) is skipped.
|
|
7
|
+
|
|
8
|
+
import { readFileSync, statSync } from "node:fs";
|
|
9
|
+
import { dirname } from "node:path";
|
|
10
|
+
import type { TraceEvent, TraceSource, TraceUsage } from "../../core/adapter.ts";
|
|
11
|
+
import { asObj, jsonlAt, parseTs, runIdOf } from "./sessions.ts";
|
|
12
|
+
|
|
13
|
+
function str(v: unknown): string | undefined {
|
|
14
|
+
return typeof v === "string" && v !== "" ? v : undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function num(v: unknown): number {
|
|
18
|
+
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function usageOf(u: unknown): TraceUsage | undefined {
|
|
22
|
+
const o = asObj(u);
|
|
23
|
+
if (!o) return undefined;
|
|
24
|
+
const c = asObj(o.cost);
|
|
25
|
+
return {
|
|
26
|
+
input: num(o.input),
|
|
27
|
+
output: num(o.output),
|
|
28
|
+
cacheRead: num(o.cacheRead),
|
|
29
|
+
cacheWrite: num(o.cacheWrite),
|
|
30
|
+
totalTokens: num(o.totalTokens),
|
|
31
|
+
cost: c ? num(c.total) : 0,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function textOf(content: unknown): string {
|
|
36
|
+
if (typeof content === "string") return content;
|
|
37
|
+
if (!Array.isArray(content)) return "";
|
|
38
|
+
return content
|
|
39
|
+
.map((p) => (asObj(p)?.type === "text" ? String(asObj(p)?.text ?? "") : ""))
|
|
40
|
+
.filter((t) => t !== "")
|
|
41
|
+
.join("\n");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Every trace event in one session file, in file order. */
|
|
45
|
+
export function parseTraceFile(file: string, runId: string): TraceEvent[] {
|
|
46
|
+
let text: string;
|
|
47
|
+
try {
|
|
48
|
+
text = readFileSync(file, "utf8");
|
|
49
|
+
} catch {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
const out: TraceEvent[] = [];
|
|
53
|
+
for (const line of text.split("\n")) {
|
|
54
|
+
if (!line.trim()) continue;
|
|
55
|
+
let parsed: unknown;
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(line);
|
|
58
|
+
} catch {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const d = asObj(parsed);
|
|
62
|
+
if (!d) continue;
|
|
63
|
+
const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
|
|
64
|
+
if (d.type === "model_change") {
|
|
65
|
+
out.push({ kind: "modelChange", ts, runId, model: str(d.model), provider: str(d.provider) });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (d.type === "model_usage") {
|
|
69
|
+
const usage = usageOf(d.usage);
|
|
70
|
+
if (usage) out.push({ kind: "usage", ts, runId, model: str(d.model), provider: str(d.provider), usage });
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const m = asObj(d.message) ?? (d.type === "message" || d.role ? d : null);
|
|
74
|
+
if (!m) continue;
|
|
75
|
+
const role = str(m.role);
|
|
76
|
+
const model = str(m.model);
|
|
77
|
+
const provider = str(m.provider);
|
|
78
|
+
const usage = usageOf(m.usage);
|
|
79
|
+
if (role === "assistant") {
|
|
80
|
+
const content = Array.isArray(m.content) ? m.content : [];
|
|
81
|
+
for (const part of content) {
|
|
82
|
+
const p = asObj(part);
|
|
83
|
+
if (!p) continue;
|
|
84
|
+
if (p.type === "text") {
|
|
85
|
+
const t = String(p.text ?? "");
|
|
86
|
+
if (t.trim()) out.push({ kind: "assistantText", ts, runId, text: t, model, provider, usage });
|
|
87
|
+
} else if (p.type === "toolCall") {
|
|
88
|
+
out.push({
|
|
89
|
+
kind: "toolCall",
|
|
90
|
+
ts,
|
|
91
|
+
runId,
|
|
92
|
+
tool: str(p.name) ?? "?",
|
|
93
|
+
args: asObj(p.arguments) ?? {},
|
|
94
|
+
model,
|
|
95
|
+
provider,
|
|
96
|
+
usage,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
} else if (role === "toolResult") {
|
|
101
|
+
out.push({
|
|
102
|
+
kind: "toolResult",
|
|
103
|
+
ts,
|
|
104
|
+
runId,
|
|
105
|
+
tool: str(m.toolName) ?? "?",
|
|
106
|
+
isError: m.isError === true,
|
|
107
|
+
text: textOf(m.content),
|
|
108
|
+
usage,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Every run id with a trace under the root, each mapped to its newest file. */
|
|
116
|
+
export function ompTraceRuns(root: string): { runId: string; file: string; mtimeSec: number }[] {
|
|
117
|
+
const newest: Record<string, { file: string; mtimeSec: number }> = {};
|
|
118
|
+
for (const file of [...jsonlAt(root, 1), ...jsonlAt(root, 2)]) {
|
|
119
|
+
let mt: number;
|
|
120
|
+
try {
|
|
121
|
+
mt = statSync(file).mtimeMs;
|
|
122
|
+
} catch {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const mtimeSec = mt / 1000;
|
|
126
|
+
const id = runIdOf(file);
|
|
127
|
+
const prev = newest[id];
|
|
128
|
+
if (!prev || mtimeSec > prev.mtimeSec) newest[id] = { file, mtimeSec };
|
|
129
|
+
}
|
|
130
|
+
return Object.entries(newest).map(([runId, v]) => ({ runId, file: v.file, mtimeSec: v.mtimeSec }));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** TraceSource over a sessions root: dated main files at depth 1, subagent files at depth 2. */
|
|
134
|
+
export function ompTraceSource(root: string): TraceSource {
|
|
135
|
+
return {
|
|
136
|
+
events(runId: string): TraceEvent[] {
|
|
137
|
+
const file = ompTraceRuns(root).find((r) => r.runId === runId)?.file;
|
|
138
|
+
return file ? parseTraceFile(file, runId) : [];
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface RelatedTrace {
|
|
144
|
+
/** The subagent run's trace run id — the agent name. */
|
|
145
|
+
name: string;
|
|
146
|
+
mtimeSec: number;
|
|
147
|
+
events: TraceEvent[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The subagent runs of one Main run: the depth-2 session files under the Main file's session
|
|
152
|
+
* dir (plan 20261024_0301 P5) — the runs Main spawned there, whose results Main's report cites.
|
|
153
|
+
* Non-Main run ids have none.
|
|
154
|
+
*/
|
|
155
|
+
export function subagentTraces(root: string, mainRunId: string): RelatedTrace[] {
|
|
156
|
+
if (!mainRunId.startsWith("MAIN ")) return [];
|
|
157
|
+
const main = ompTraceRuns(root).find((r) => r.runId === mainRunId);
|
|
158
|
+
if (!main) return [];
|
|
159
|
+
return jsonlAt(dirname(main.file), 1).map((file) => {
|
|
160
|
+
const name = runIdOf(file);
|
|
161
|
+
let mtimeSec = 0;
|
|
162
|
+
try {
|
|
163
|
+
mtimeSec = statSync(file).mtimeMs / 1000;
|
|
164
|
+
} catch {}
|
|
165
|
+
return { name, mtimeSec, events: parseTraceFile(file, name) };
|
|
166
|
+
});
|
|
167
|
+
}
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { runInit } from "./init.ts";
|
|
|
8
8
|
import { PORTED, runMain, runPorted } from "./commands.ts";
|
|
9
9
|
import { runMetrics } from "./metrics.ts";
|
|
10
10
|
import { runIncident } from "./incident.ts";
|
|
11
|
+
import { runTraces } from "./traces.ts";
|
|
11
12
|
import { runUi } from "./ui.ts";
|
|
12
13
|
import { runUninstall } from "../core/uninstall.ts";
|
|
13
14
|
import { queueMigrate } from "../core/queue-migrate.ts";
|
|
@@ -61,6 +62,15 @@ export function helpText(): string {
|
|
|
61
62
|
" neurastream main [args] run omp under the launcher (automatic session rollover)",
|
|
62
63
|
" neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
|
|
63
64
|
" neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
|
|
65
|
+
" neurastream traces claims <runId|--since 24h> [--json]",
|
|
66
|
+
" check a run's final-report claims (test counts, exit codes,",
|
|
67
|
+
" SHAs, heavy-run labels, changed paths) against the run's own",
|
|
68
|
+
" tool activity; unmatched ones print as claim-unbacked findings",
|
|
69
|
+
" neurastream traces actions <runId|--since 24h> [--json]",
|
|
70
|
+
" list the suspicious tool actions a run's trace shows (secret-",
|
|
71
|
+
" path reads, network commands to unknown hosts, writes outside",
|
|
72
|
+
" the allowed roots or on deny paths, pipes into a shell); the",
|
|
73
|
+
" high ones also open realtime suspicious-action incidents",
|
|
64
74
|
" neurastream ui serve the owner's phone page on the tailnet address (ui.enabled, ui.owner_login)",
|
|
65
75
|
" neurastream ui on --login <tailscale login> [--port N]",
|
|
66
76
|
" one go: writes ui.enabled/owner_login (and port) into the config,",
|
|
@@ -86,6 +96,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
86
96
|
if (cmd === "init") return runInit(args);
|
|
87
97
|
if (cmd === "metrics") return runMetrics(args);
|
|
88
98
|
if (cmd === "incident") return runIncident(args);
|
|
99
|
+
if (cmd === "traces") return runTraces(args);
|
|
89
100
|
if (cmd === "ui") return runUi(args);
|
|
90
101
|
if (cmd === "adapter") return runAdapterInstall(args);
|
|
91
102
|
if (cmd === "config") {
|
package/src/cli/guard.ts
CHANGED
|
@@ -44,6 +44,7 @@ function toolEvent(p: Record<string, unknown>): ToolEvent {
|
|
|
44
44
|
paths: asStringList(p.paths),
|
|
45
45
|
writes: asStringList(p.writes),
|
|
46
46
|
command: asString(p.command),
|
|
47
|
+
...(p.runningJobs === undefined ? {} : { runningJobs: asStringList(p.runningJobs) }),
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
50
|
|
|
@@ -59,7 +60,12 @@ function decide(event: string, p: Record<string, unknown>, cfg: Config): Decisio
|
|
|
59
60
|
return checkInject(e, cfg);
|
|
60
61
|
}
|
|
61
62
|
case "spawn": {
|
|
62
|
-
const e: SpawnEvent = {
|
|
63
|
+
const e: SpawnEvent = {
|
|
64
|
+
agent: asString(p.agent),
|
|
65
|
+
invocationKind: asString(p.invocationKind, "task"),
|
|
66
|
+
brief: asString(p.brief ?? p.context ?? p.task),
|
|
67
|
+
...(p.runningJobs === undefined ? {} : { runningJobs: asStringList(p.runningJobs) }),
|
|
68
|
+
};
|
|
63
69
|
return checkSpawn(e, cfg);
|
|
64
70
|
}
|
|
65
71
|
case "plan-edit": {
|