neurastream 0.3.20 → 0.3.21

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.
Files changed (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -0,0 +1,209 @@
1
+ // Owner messages (plan P13): inbox path, running-Main target routing, 12h message store, and image serving.
2
+
3
+ import { randomUUID } from "node:crypto";
4
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { nowSec } from "../clock.ts";
6
+ import type { Config } from "../config.ts";
7
+ import { isBusy } from "../file-lock.ts";
8
+ import { MAIN_ID_RE } from "../guards.ts";
9
+ import type { QueuePaths } from "../queue/lib.ts";
10
+ import { jsonFail, jsonSent, receiptText, redirect, textRes } from "./auth.ts";
11
+
12
+ export const MESSAGE_MAX = 4000;
13
+ const MESSAGE_IMAGES_MAX = 4;
14
+ const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
15
+ /** How long the page keeps an owner message: 12 h, then the sweep removes it (owner, 2026-10-25 19:10). */
16
+ export const OWNER_MESSAGE_KEEP_SEC = 43200;
17
+
18
+ /** The inbox the page appends answers to and the adapter delivers from: under the queue state dir. */
19
+ export function inboxPath(paths: Pick<QueuePaths, "queue_state">): string {
20
+ return `${paths.queue_state}/owner-inbox.jsonl`;
21
+ }
22
+
23
+ /** Where the page stores owner messages: under the queue state dir, one dir per message. */
24
+ function ownerMessagesDir(paths: Pick<QueuePaths, "queue_state">): string {
25
+ return `${paths.queue_state}/owner-messages`;
26
+ }
27
+
28
+ /** Main ids with a live running.lock in their main state dir (P5 multi-main): the page's picker list and the @-routing target set. */
29
+ export function runningMains(cfg: Config): string[] {
30
+ let dirs: string[];
31
+ try {
32
+ dirs = readdirSync(`${cfg.paths.queue_state}/mains`);
33
+ } catch {
34
+ return [];
35
+ }
36
+ return dirs
37
+ .filter(d => MAIN_ID_RE.test(d) && isBusy(`${cfg.paths.queue_state}/mains/${d}/running.lock`))
38
+ .toSorted();
39
+ }
40
+
41
+ /** Resolves where a message goes (P5 multi-main): an `@<id> ` prefix or the picker's `to` field names one running Main; empty is every Main. A stale target is refused before anything is stored. */
42
+ export function ownerMessageTarget(text: string, cfg: Config, formTo = ""): { to: string } | { refuse: string } {
43
+ const at = /^@([a-z0-9-]{1,24})(?:\s|$)/.exec(text);
44
+ const target = (at ? at[1] : formTo) ?? "";
45
+ if (!target || !MAIN_ID_RE.test(target)) return { to: "" };
46
+ const running = runningMains(cfg);
47
+ if (running.includes(target)) return { to: target };
48
+ return { refuse: `Main ${target} is not running; running: ${running.length ? running.join(", ") : "none"}` };
49
+ }
50
+
51
+ export interface MessageRow {
52
+ id: string;
53
+ ts: number;
54
+ text: string;
55
+ images: string[];
56
+ }
57
+
58
+ /** The image type from the first bytes — PNG, JPEG, GIF or WEBP — never from the client's name or content type. */
59
+ function imageType(bytes: Uint8Array): "png" | "jpeg" | "gif" | "webp" | null {
60
+ if (
61
+ bytes.length >= 8 &&
62
+ bytes[0] === 0x89 &&
63
+ bytes[1] === 0x50 &&
64
+ bytes[2] === 0x4e &&
65
+ bytes[3] === 0x47 &&
66
+ bytes[4] === 0x0d &&
67
+ bytes[5] === 0x0a &&
68
+ bytes[6] === 0x1a &&
69
+ bytes[7] === 0x0a
70
+ )
71
+ return "png";
72
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpeg";
73
+ if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) return "gif";
74
+ if (
75
+ bytes.length >= 12 &&
76
+ bytes[0] === 0x52 &&
77
+ bytes[1] === 0x49 &&
78
+ bytes[2] === 0x46 &&
79
+ bytes[3] === 0x46 &&
80
+ bytes[8] === 0x57 &&
81
+ bytes[9] === 0x45 &&
82
+ bytes[10] === 0x42 &&
83
+ bytes[11] === 0x50
84
+ )
85
+ return "webp";
86
+ return null;
87
+ }
88
+
89
+ const IMAGE_EXT: Record<string, string> = { png: "png", jpeg: "jpg", gif: "gif", webp: "webp" };
90
+ const IMAGE_MIME: Record<string, string> = { png: "image/png", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
91
+
92
+ /** Removes every message dir older than the keep window; runs on every GET / and every POST /message. */
93
+ export function sweepOwnerMessages(now: number, paths: Pick<QueuePaths, "queue_state">): void {
94
+ const dir = ownerMessagesDir(paths);
95
+ let names: string[];
96
+ try {
97
+ names = readdirSync(dir);
98
+ } catch {
99
+ return;
100
+ }
101
+ for (const name of names) {
102
+ const ts = Number(name.slice(0, name.indexOf("-")));
103
+ if (Number.isFinite(ts) && now - ts <= OWNER_MESSAGE_KEEP_SEC) continue;
104
+ rmSync(`${dir}/${name}`, { recursive: true, force: true });
105
+ }
106
+ }
107
+
108
+ /** The messages newer than the keep window for the "Sent today" list, newest first. A torn dir is skipped, not fatal. */
109
+ export function recentOwnerMessages(now: number, paths: Pick<QueuePaths, "queue_state">): MessageRow[] {
110
+ const dir = ownerMessagesDir(paths);
111
+ let names: string[] = [];
112
+ try {
113
+ names = readdirSync(dir);
114
+ } catch {
115
+ return [];
116
+ }
117
+ const rows: MessageRow[] = [];
118
+ for (const id of names) {
119
+ const dirTs = Number(id.slice(0, id.indexOf("-")));
120
+ if (!Number.isFinite(dirTs) || now - dirTs >= OWNER_MESSAGE_KEEP_SEC) continue;
121
+ try {
122
+ const meta = JSON.parse(readFileSync(`${dir}/${id}/message.json`, "utf8")) as Record<string, unknown>;
123
+ rows.push({
124
+ id,
125
+ ts: Number(meta.ts) || dirTs,
126
+ text: typeof meta.text === "string" ? meta.text : "",
127
+ images: Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [],
128
+ });
129
+ } catch {}
130
+ }
131
+ return rows.sort((a, b) => b.ts - a.ts);
132
+ }
133
+
134
+ /** Stores an owner message (text and images) under a new id and inboxes it for Main (P13/P14). */
135
+ export function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[], to: string, paths: Pick<QueuePaths, "queue_state">): void {
136
+ const ts = nowSec();
137
+ // The dir name starts with a whole-second ts: the sweep and the image route both parse it.
138
+ const id = `${Math.floor(ts)}-${randomUUID().slice(0, 6)}`;
139
+ const dir = `${ownerMessagesDir(paths)}/${id}`;
140
+ mkdirSync(dir, { recursive: true });
141
+ const names: string[] = [];
142
+ for (let i = 0; i < images.length; i++) {
143
+ const name = `${i + 1}.${IMAGE_EXT[images[i]!.kind]}`;
144
+ writeFileSync(`${dir}/${name}`, images[i]!.bytes);
145
+ names.push(name);
146
+ }
147
+ writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, to, images: names })}\n`);
148
+ mkdirSync(paths.queue_state, { recursive: true });
149
+ // The text stays out of owner-inbox.jsonl; Main reads message.json through the id (P14).
150
+ appendFileSync(inboxPath(paths), `${JSON.stringify({ ts, kind: "message", id, login, to })}\n`);
151
+ }
152
+
153
+ // ---- POST /message (plan P13): the owner's one-way note plus images, inboxed by id ----
154
+
155
+ export async function handleMessage(req: Request, cfg: Config, login: string, wantsJson: boolean): Promise<Response> {
156
+ sweepOwnerMessages(nowSec(), cfg.paths);
157
+ const form = await req.formData();
158
+ let text = "";
159
+ let toField = "";
160
+ const files: File[] = [];
161
+ for (const [key, value] of form.entries()) {
162
+ if (key === "text" && typeof value === "string") text = value.trim();
163
+ else if (key === "to" && typeof value === "string") toField = value;
164
+ // A form sent with no file chosen still carries one empty, nameless file part (Bun parses it as a nameless Blob).
165
+ else if (key === "images" && (value as unknown) instanceof Blob) {
166
+ const part = value as unknown as File;
167
+ if (part.size > 0 || Boolean(part.name)) files.push(part);
168
+ }
169
+ }
170
+ const fail = (error: string): Response => (wantsJson ? jsonFail(error, 400) : textRes(error, 400));
171
+ if (!text && !files.length) return fail("write a text or attach an image");
172
+ if (text.length > MESSAGE_MAX) return fail(`text is longer than ${MESSAGE_MAX} chars`);
173
+ if (files.length > MESSAGE_IMAGES_MAX) return fail(`at most ${MESSAGE_IMAGES_MAX} images per message`);
174
+ const images: { bytes: Uint8Array; kind: string }[] = [];
175
+ for (const file of files) {
176
+ if (file.size > MESSAGE_IMAGE_MAX_BYTES) return fail("an image is larger than 10 MB");
177
+ const data = new Uint8Array(await file.arrayBuffer());
178
+ const kind = imageType(data);
179
+ if (!kind) return fail("attachments must be PNG, JPEG, GIF or WEBP images — the type is read from the file itself");
180
+ images.push({ bytes: data, kind });
181
+ }
182
+ // P5: an `@<id>` prefix or the picker's to field names one Main; a stale name is refused before anything is stored.
183
+ const pick = ownerMessageTarget(text, cfg, toField);
184
+ if ("refuse" in pick) return fail(pick.refuse);
185
+ storeOwnerMessage(text, login, images, pick.to, cfg.paths);
186
+ if (wantsJson) return jsonSent("message", receiptText("message", new URLSearchParams()));
187
+ return redirect("/?sent=message");
188
+ }
189
+
190
+ /** Serves one stored message image. Both path pieces are shape-checked and the name must be in message.json — raw input never reaches a path join. */
191
+ export function handleMessageImage(id: string, file: string, paths: Pick<QueuePaths, "queue_state">): Response {
192
+ if (!/^[0-9]+-[0-9a-f]{6}$/.test(id) || !/^[0-9]+\.(png|jpg|gif|webp)$/.test(file)) return textRes("not found", 404);
193
+ const dir = ownerMessagesDir(paths);
194
+ let meta: Record<string, unknown>;
195
+ try {
196
+ meta = JSON.parse(readFileSync(`${dir}/${id}/message.json`, "utf8")) as Record<string, unknown>;
197
+ } catch {
198
+ return textRes("not found", 404);
199
+ }
200
+ const names = Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [];
201
+ if (!names.includes(file)) return textRes("not found", 404);
202
+ try {
203
+ return new Response(readFileSync(`${dir}/${id}/${file}`), {
204
+ headers: { "content-type": IMAGE_MIME[file.slice(file.lastIndexOf(".") + 1)] ?? "application/octet-stream" },
205
+ });
206
+ } catch {
207
+ return textRes("not found", 404);
208
+ }
209
+ }