neurastream 0.2.36 โ†’ 0.2.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,224 @@
1
+ import { closeSync, existsSync, lstatSync, openSync, readdirSync, readFileSync, statSync, writeSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import type { Config } from "./config.ts";
4
+ import { expandHome } from "./queue/lib.ts";
5
+ import { gitRaw } from "./proc.ts";
6
+
7
+ export interface KnowledgeEntry {
8
+ repo: string;
9
+ topic: string;
10
+ title: string;
11
+ /** ISO-8601 date (commit date or mtime fallback). */
12
+ updated: string;
13
+ }
14
+
15
+ interface ManifestFile {
16
+ built: number;
17
+ entries: KnowledgeEntry[];
18
+ }
19
+
20
+ const KNOWLEDGE_DIR = join("docs", "knowledge");
21
+
22
+ /** Text order for the lists: code-unit order, so the same list on every machine. */
23
+ export function byText(a: string, b: string): number {
24
+ return a < b ? -1 : a > b ? 1 : 0;
25
+ }
26
+
27
+ /** One URL path segment or query value: every byte outside the unreserved set becomes %XX. */
28
+ export function urlValue(s: string): string {
29
+ let out = "";
30
+ for (const byte of new TextEncoder().encode(s)) {
31
+ const ch = String.fromCharCode(byte);
32
+ out += /[A-Za-z0-9\-._~]/.test(ch) ? ch : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Inverse of urlValue: %XX byte runs come back as UTF-8 text. */
38
+ export function urlField(s: string): string {
39
+ const bytes: number[] = [];
40
+ for (let i = 0; i < s.length; i++) {
41
+ const hex = s.slice(i + 1, i + 3);
42
+ if (s[i] === "%" && /^[0-9A-Fa-f]{2}$/.test(hex)) {
43
+ bytes.push(parseInt(hex, 16));
44
+ i += 2;
45
+ } else {
46
+ bytes.push(...new TextEncoder().encode(s[i]!));
47
+ }
48
+ }
49
+ return new TextDecoder().decode(new Uint8Array(bytes));
50
+ }
51
+
52
+ function repoKey(repoPath: string): string {
53
+ const remote = gitRaw(repoPath, ["remote", "get-url", "origin"]).stdout.trim();
54
+ if (remote) {
55
+ const base = basename(remote.replace(/\/$/, ""));
56
+ return base.endsWith(".git") ? base.slice(0, -4) : base;
57
+ }
58
+ return basename(repoPath);
59
+ }
60
+
61
+ function parseTitle(html: string, fallback: string): string {
62
+ const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
63
+ if (!m) return fallback;
64
+ const t = m[1]!.replace(/\s+/g, " ").trim();
65
+ return t || fallback;
66
+ }
67
+
68
+ function topicUpdated(repoPath: string, rel: string, abs: string, now: number): string {
69
+ const log = gitRaw(repoPath, ["log", "-1", "--format=%cI", "--", rel]).stdout.trim();
70
+ if (log) return log;
71
+ const mtime = statSync(abs).mtimeMs;
72
+ return new Date(mtime).toISOString();
73
+ }
74
+
75
+ function isLinkedWorktree(repoPath: string): boolean {
76
+ const dot = join(repoPath, ".git");
77
+ return existsSync(dot) && lstatSync(dot).isFile();
78
+ }
79
+
80
+ function isGitCheckout(dir: string): boolean {
81
+ const dot = join(dir, ".git");
82
+ return existsSync(dot) && (lstatSync(dot).isDirectory() || lstatSync(dot).isFile());
83
+ }
84
+
85
+ function scanRepo(repoPath: string, now: number): KnowledgeEntry[] {
86
+ if (isLinkedWorktree(repoPath)) return [];
87
+ const knowDir = join(repoPath, KNOWLEDGE_DIR);
88
+ if (!existsSync(knowDir) || !lstatSync(knowDir).isDirectory()) return [];
89
+ const repo = repoKey(repoPath);
90
+ const out: KnowledgeEntry[] = [];
91
+ for (const ent of readdirSync(knowDir, { withFileTypes: true })) {
92
+ if (!ent.isFile() || !ent.name.endsWith(".html")) continue;
93
+ const topic = ent.name.slice(0, -".html".length);
94
+ const abs = join(knowDir, ent.name);
95
+ let html = "";
96
+ try {
97
+ html = readFileSync(abs, "utf8");
98
+ } catch {
99
+ continue;
100
+ }
101
+ out.push({
102
+ repo,
103
+ topic,
104
+ title: parseTitle(html, topic),
105
+ updated: topicUpdated(repoPath, join(KNOWLEDGE_DIR, ent.name), abs, now),
106
+ });
107
+ }
108
+ out.sort((a, b) => byText(a.repo, b.repo) || byText(a.topic, b.topic));
109
+ return out;
110
+ }
111
+
112
+ /** Pure scan: repos directly under expanded roots; unreadable dirs skipped. */
113
+ export function scanKnowledge(roots: string[], now: number): KnowledgeEntry[] {
114
+ const entries: KnowledgeEntry[] = [];
115
+ for (const raw of roots) {
116
+ let root = "";
117
+ try {
118
+ root = expandHome(raw);
119
+ } catch {
120
+ continue;
121
+ }
122
+ if (!existsSync(root)) continue;
123
+ let names: string[] = [];
124
+ try {
125
+ names = readdirSync(root);
126
+ } catch {
127
+ continue;
128
+ }
129
+ for (const name of names) {
130
+ const repoPath = join(root, name);
131
+ try {
132
+ if (!lstatSync(repoPath).isDirectory()) continue;
133
+ if (!isGitCheckout(repoPath)) continue;
134
+ entries.push(...scanRepo(repoPath, now));
135
+ } catch {
136
+ continue;
137
+ }
138
+ }
139
+ }
140
+ entries.sort((a, b) => byText(a.repo, b.repo) || byText(a.topic, b.topic));
141
+ return entries;
142
+ }
143
+
144
+ export function knowledgeManifestPath(cfg: Config): string {
145
+ return join(expandHome(cfg.paths.queue_state), "knowledge.json");
146
+ }
147
+
148
+ function readManifest(path: string): ManifestFile | null {
149
+ if (!existsSync(path)) return null;
150
+ try {
151
+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
152
+ if (!raw || typeof raw !== "object") return null;
153
+ const built = (raw as ManifestFile).built;
154
+ const entries = (raw as ManifestFile).entries;
155
+ if (typeof built !== "number" || !Array.isArray(entries)) return null;
156
+ return { built, entries };
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ function writeManifest(path: string, data: ManifestFile): void {
163
+ const fd = openSync(path, "w");
164
+ try {
165
+ writeSync(fd, JSON.stringify(data));
166
+ } finally {
167
+ closeSync(fd);
168
+ }
169
+ }
170
+
171
+ /** Cached manifest in queue state; rescans when older than cfg.knowledge.max_age_s. */
172
+ export function knowledgeManifest(cfg: Config, nowSec = Math.floor(Date.now() / 1000)): KnowledgeEntry[] {
173
+ const path = knowledgeManifestPath(cfg);
174
+ const cached = readManifest(path);
175
+ const maxAge = cfg.knowledge.max_age_s;
176
+ if (cached && nowSec - cached.built < maxAge) return cached.entries;
177
+ const entries = scanKnowledge(cfg.knowledge.roots, nowSec * 1000);
178
+ const fresh: ManifestFile = { built: nowSec, entries };
179
+ writeManifest(path, fresh);
180
+ return entries;
181
+ }
182
+
183
+ /** Absolute path to a topic HTML file, or null when repo/topic is unknown. */
184
+ export function resolveKnowledgeTopic(cfg: Config, repo: string, topic: string): string | null {
185
+ if (!/^[a-zA-Z0-9._-]+$/.test(repo) || !/^[a-zA-Z0-9._-]+$/.test(topic)) return null;
186
+ for (const raw of cfg.knowledge.roots) {
187
+ let root = "";
188
+ try {
189
+ root = expandHome(raw);
190
+ } catch {
191
+ continue;
192
+ }
193
+ if (!existsSync(root)) continue;
194
+ let names: string[] = [];
195
+ try {
196
+ names = readdirSync(root);
197
+ } catch {
198
+ continue;
199
+ }
200
+ for (const name of names) {
201
+ const repoPath = join(root, name);
202
+ try {
203
+ if (!lstatSync(repoPath).isDirectory() || !isGitCheckout(repoPath) || isLinkedWorktree(repoPath)) continue;
204
+ if (repoKey(repoPath) !== repo) continue;
205
+ const file = join(repoPath, KNOWLEDGE_DIR, `${topic}.html`);
206
+ if (existsSync(file) && lstatSync(file).isFile()) return file;
207
+ } catch {
208
+ continue;
209
+ }
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+
215
+ /** Read topic bytes for serving; null when missing. */
216
+ export function readKnowledgeTopicFile(cfg: Config, repo: string, topic: string): Buffer<ArrayBuffer> | null {
217
+ const path = resolveKnowledgeTopic(cfg, repo, topic);
218
+ if (!path) return null;
219
+ try {
220
+ return readFileSync(path);
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
@@ -12,6 +12,7 @@ import { log as logGuard } from "./guards.ts";
12
12
  import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
13
13
  import { buildReport } from "./report.ts";
14
14
  import { loadavgLine } from "./host.ts";
15
+ import { providersLine } from "./provider-state.ts";
15
16
  import { mrSweep } from "./mr-sweep.ts";
16
17
 
17
18
  function bin(name: string, cfg: Config): string {
@@ -129,6 +130,10 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
129
130
  for (const line of cap.stdout.split("\n")) {
130
131
  if (/^(PRIORITY IDLE|FULL)/.test(line)) say(line);
131
132
  }
133
+ // Who is rate-limited comes from live data (plan 20261025_1700 P2): printed from the running
134
+ // code, not the installed agent-ledger bin, so a stale install cannot hide the state.
135
+ const providers = providersLine(cfg);
136
+ if (providers) say(providers);
132
137
  say("");
133
138
  say("=== main thread");
134
139
  const health = await run(bin("main-health", cfg), [], { stdin: childStdin, stderr: childStderr });
@@ -17,6 +17,7 @@ import type { Config } from "./config.ts";
17
17
  import { nowSec, strftime } from "./clock.ts";
18
18
  import { cpuCount } from "./host.ts";
19
19
  import { openIncidents } from "./incidents.ts";
20
+ import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
20
21
  import { log } from "./guards.ts";
21
22
  import { readMetricEvents } from "./metrics.ts";
22
23
  import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
@@ -29,6 +30,9 @@ const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
29
30
  /** How long the page keeps an owner message: 12 h, then the sweep removes it (owner, 2026-10-25 19:10). */
30
31
  export const OWNER_MESSAGE_KEEP_SEC = 43200;
31
32
  const REFRESH_SEC = 20;
33
+ /** The page's tabs, in pill order; anything else in `?tab=` renders Now. */
34
+ const TABS: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"], ["knowledge", "Base"]];
35
+ const TAB_IDS = TABS.map(([id]) => id);
32
36
  // Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
33
37
  const TAILNET6 = /^fd7a:115c:a1e0:/i;
34
38
 
@@ -619,8 +623,7 @@ function tilesHtml(data: PageData): string {
619
623
 
620
624
  /** The sticky mockup top bar: logo, pill tabs, and the lock pill that posts the unlock/lock and tier forms. */
621
625
  function topBarHtml(tab: string, lockMinutesLeft: number | null, cfg: Config): string {
622
- const tabs: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"]];
623
- const pills = tabs.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
626
+ const pills = TABS.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
624
627
  const lockLabel = lockMinutesLeft === null ? "๐Ÿ”’ Off" : `๐Ÿ”“ ${lockMinutesLeft} min`;
625
628
  const tabField = `<input type="hidden" name="tab" value="${esc(tab)}">`;
626
629
  const unlockForm = (minutes: number) =>
@@ -715,6 +718,8 @@ export interface PageData {
715
718
  incidents: IncidentRow[] | null;
716
719
  scores: ScoresData | null;
717
720
  machine: MachineRow | null;
721
+ /** Repo-local HTML explainers from the knowledge manifest; null when unreadable. */
722
+ knowledge: KnowledgeEntry[] | null;
718
723
  /** The 24 h tile numbers; null when the run source is unreadable. */
719
724
  stats: NowStats | null;
720
725
  /** The owner's messages newer than the keep window, newest first; null when unreadable. */
@@ -751,6 +756,7 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
751
756
  incidents: safe(() => incidentRows(cfg)),
752
757
  scores: safe(() => scoresData(cfg)),
753
758
  machine: safe(() => machineRow(cfg)),
759
+ knowledge: safe(() => knowledgeManifest(cfg)),
754
760
  stats: safe(() => nowStats(cfg, source, nowSec())),
755
761
  messages: safe(() => recentOwnerMessages(nowSec())),
756
762
  lockMinutesLeft: lockMinutesLeft(cfg),
@@ -875,11 +881,51 @@ bindDetails(document);
875
881
  bindPage();
876
882
  })();`;
877
883
 
884
+ /**
885
+ * The Knowledge tab: repo cards, one repo's topic cards, or one topic in a frame. The breadcrumb's
886
+ * earlier segments link back โ€” knowledge-base โ†’ every repo, `<repo>` โ†’ its topics. Topics are
887
+ * read-only files at docs/knowledge/<topic>.html in a repo under the configured roots; the page
888
+ * bytes come from /knowledge/<repo>/<topic> and there is no route that writes one.
889
+ */
890
+ function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string): string {
891
+ const repoHref = `/?tab=knowledge&repo=${urlValue(repo)}`;
892
+ const crumb =
893
+ repo === ""
894
+ ? ""
895
+ : `<p class="sub"><a href="/?tab=knowledge">knowledge-base</a> / ${topic === "" ? esc(repo) : `<a href="${repoHref}">${esc(repo)}</a>`}${topic === "" ? "" : ` / ${esc(topic)}`}</p>`;
896
+ if (entries.length === 0) {
897
+ return `<h1>Base</h1><div class="card"><p class="empty">No topics yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> and it shows up here on the next reload.</p></div>`;
898
+ }
899
+ if (repo === "") {
900
+ const repos = new Map<string, KnowledgeEntry[]>();
901
+ for (const e of entries) repos.set(e.repo, [...(repos.get(e.repo) ?? []), e]);
902
+ const rows = [...repos.entries()]
903
+ .sort((a, b) => byText(a[0], b[0]))
904
+ .map(([name, list]) => {
905
+ const newest = list.map(e => e.updated).sort().at(-1)!.slice(0, 10);
906
+ return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${list.length} topic${list.length === 1 ? "" : "s"} ยท ${newest}</span></div>`;
907
+ })
908
+ .join("");
909
+ return `<h1>Base</h1><p class="sub">One card per repo with pages in <span class="mono">docs/knowledge/</span> โ€” tap a repo for its topics.</p><div class="card">${rows}</div>`;
910
+ }
911
+ const topics = entries.filter(e => e.repo === repo);
912
+ if (topics.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
913
+ if (topic === "") {
914
+ const rows = topics
915
+ .map(e => `<div class="mrow"><a href="${repoHref}&topic=${urlValue(e.topic)}">${esc(e.title)}</a><span class="mono">${e.updated.slice(0, 10)}</span></div>`)
916
+ .join("");
917
+ return `${crumb}<div class="card">${rows}</div>`;
918
+ }
919
+ const hit = topics.find(e => e.topic === topic);
920
+ if (hit === undefined) return `${crumb}<div class="card"><p class="empty">No topic "${esc(topic)}" in ${esc(repo)}.</p></div>`;
921
+ return `${crumb}<h1>${esc(hit.title)}</h1><div class="card"><iframe class="knowframe" title="${esc(hit.title)}" src="/knowledge/${urlValue(repo)}/${urlValue(topic)}"></iframe></div>`;
922
+ }
923
+
878
924
  /** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
879
925
  export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
880
926
  const req = params.get("tab") ?? "";
881
927
  // Server-rendered tabs: the pill links carry ?tab=; anything unknown renders Now.
882
- const tab = req === "queue" || req === "agents" || req === "spend" ? req : "now";
928
+ const tab = TAB_IDS.includes(req) ? req : "now";
883
929
  const needsBody =
884
930
  data.questions === null
885
931
  ? na("Waiting on you")
@@ -932,7 +978,9 @@ ${merges}
932
978
  <div class="card">
933
979
  ${machine}
934
980
  </div>`
935
- : `<h1>Spend</h1>
981
+ : tab === "knowledge"
982
+ ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "")}`
983
+ : `<h1>Spend</h1>
936
984
  <p class="sub">List price over the last 24 hours.</p>
937
985
  <div class="card">
938
986
  ${spendTileHtml(data)}
@@ -1043,6 +1091,7 @@ tr:last-child td{border-bottom:none}
1043
1091
  .mrow:last-child{border-bottom:none}
1044
1092
  .bad{color:var(--red);font-weight:600}
1045
1093
  .empty{color:var(--mut);padding:14px 16px;margin:0}
1094
+ .knowframe{display:block;width:100%;height:calc(100vh - 220px);min-height:360px;border:0;background:#fff}
1046
1095
  .na{color:var(--mut);font-style:italic;padding:14px 16px;margin:0}
1047
1096
  </style>
1048
1097
  </head>
@@ -1080,7 +1129,7 @@ function redirect(target: string): Response {
1080
1129
 
1081
1130
  /** The POST reply target: the tab the owner was on (a hidden `tab` field; unknown = now, the default), then the receipt. */
1082
1131
  function sentTo(tab: string, sent: string): string {
1083
- const t = tab === "queue" || tab === "agents" || tab === "spend" ? tab : "now";
1132
+ const t = TAB_IDS.includes(tab) ? tab : "now";
1084
1133
  return t === "now" ? `/?${sent}` : `/?tab=${t}&${sent}`;
1085
1134
  }
1086
1135
 
@@ -1091,7 +1140,7 @@ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams): Respo
1091
1140
  status: 200,
1092
1141
  headers: {
1093
1142
  "content-type": "text/html; charset=utf-8",
1094
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
1143
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
1095
1144
  },
1096
1145
  });
1097
1146
  }
@@ -1395,6 +1444,15 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1395
1444
  sweepOwnerMessages(nowSec());
1396
1445
  res = pageRes(cfg, source, url.searchParams);
1397
1446
  code = 200;
1447
+ } else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
1448
+ // The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.
1449
+ const topicPath = /^\/knowledge\/([^/]+)\/([^/]+)$/.exec(url.pathname);
1450
+ const bytes =
1451
+ topicPath === null
1452
+ ? null
1453
+ : readKnowledgeTopicFile(cfg, urlField(topicPath[1]!), urlField(topicPath[2]!));
1454
+ res = bytes === null ? textRes("not found", 404) : new Response(bytes, { headers: { "content-type": "text/html; charset=utf-8" } });
1455
+ code = res.status;
1398
1456
  } else if (req.method === "GET" && url.pathname.startsWith("/message-image/")) {
1399
1457
  const mim = /^\/message-image\/([^/]+)\/([^/]+)$/.exec(url.pathname);
1400
1458
  res = mim ? handleMessageImage(mim[1]!, mim[2]!) : textRes("not found", 404);