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.
- package/package.json +1 -1
- package/src/adapters/index.ts +3 -2
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/auto-close.ts +64 -0
- package/src/adapters/omp/chat-commands.ts +161 -0
- package/src/adapters/omp/inbox.ts +221 -0
- package/src/adapters/omp/index.ts +115 -1039
- package/src/adapters/omp/launch.ts +31 -3
- package/src/adapters/omp/rate-limit-controller.ts +196 -0
- package/src/adapters/omp/rollover-controller.ts +334 -0
- package/src/adapters/omp/types.ts +143 -0
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +37 -16
- package/src/cli/recall.ts +3 -2
- package/src/cli/results-build.ts +1 -1
- package/src/cli/workspace.ts +13 -2
- package/src/core/adapter.ts +16 -0
- package/src/core/blockers.ts +326 -30
- package/src/core/file-lock.ts +71 -12
- package/src/core/guards/plan-edit.ts +338 -0
- package/src/core/guards/planner.ts +70 -0
- package/src/core/guards/review.ts +391 -0
- package/src/core/guards/spawn.ts +699 -0
- package/src/core/guards/state.ts +581 -0
- package/src/core/guards/stop.ts +235 -0
- package/src/core/guards/tool.ts +541 -0
- package/src/core/guards.ts +12 -2658
- package/src/core/incidents.ts +125 -91
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +10 -8
- package/src/core/owner-topics.ts +2 -13
- package/src/core/owner-ui/auth.ts +164 -0
- package/src/core/owner-ui/data.ts +437 -0
- package/src/core/owner-ui/handlers.ts +250 -0
- package/src/core/owner-ui/messages.ts +209 -0
- package/src/core/owner-ui/render.ts +714 -0
- package/src/core/owner-ui/results.ts +266 -0
- package/src/core/owner-ui/server.ts +142 -0
- package/src/core/owner-ui.ts +11 -2121
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -77
- package/src/core/plan-approval.ts +12 -14
- package/src/core/queue/lib.ts +88 -39
- package/src/core/queue-cancel.ts +21 -17
- package/src/core/queue-close.ts +48 -23
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +13 -2
- package/src/core/uninstall.ts +2 -0
package/src/core/incidents.ts
CHANGED
|
@@ -9,10 +9,11 @@
|
|
|
9
9
|
// findings (plan-guard: the Findings: items of a subagent's new Progress entry), watch (the
|
|
10
10
|
// src/core/watch.ts watcher: failed/stale heartbeats, failed units).
|
|
11
11
|
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
+
import { join, resolve } from "node:path";
|
|
14
14
|
import { nowSec, strftime } from "./clock.ts";
|
|
15
15
|
import type { Config } from "./config.ts";
|
|
16
|
+
import { withFileLock, writeAtomicSync } from "./file-lock.ts";
|
|
16
17
|
import * as q from "./queue/lib.ts";
|
|
17
18
|
|
|
18
19
|
export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces" | "watch";
|
|
@@ -132,9 +133,8 @@ function readStore(file: string): { incidents: IncidentRec[]; resolutions: Resol
|
|
|
132
133
|
return { incidents, resolutions, proposals, lines };
|
|
133
134
|
}
|
|
134
135
|
|
|
135
|
-
function
|
|
136
|
-
|
|
137
|
-
writeFileSync(file, `${lines.join("\n")}\n`);
|
|
136
|
+
function writeIncidentLines(file: string, lines: string[]): void {
|
|
137
|
+
writeAtomicSync(file, `${lines.join("\n")}\n`);
|
|
138
138
|
}
|
|
139
139
|
|
|
140
140
|
/** Every incident in file order, each folded with its last resolution record (if any). */
|
|
@@ -162,39 +162,40 @@ export function openIncidents(cfg: Config): IncidentView[] {
|
|
|
162
162
|
/** Records a sighting. Returns the (open) incident; `deduped` says an open one was updated. */
|
|
163
163
|
export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()): { incident: IncidentView; deduped: boolean } {
|
|
164
164
|
const file = incidentsFile(cfg);
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
open
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
165
|
+
return withFileLock(`${file}.lock`, () => {
|
|
166
|
+
const store = readStore(file);
|
|
167
|
+
const fingerprint = input.fingerprint ?? defaultFingerprint(input);
|
|
168
|
+
const open = store.incidents.find(
|
|
169
|
+
i => i.fingerprint === fingerprint && !store.resolutions.some(r => r.id === i.id),
|
|
170
|
+
);
|
|
171
|
+
if (open) {
|
|
172
|
+
open.count += 1;
|
|
173
|
+
open.lastSeen = now;
|
|
174
|
+
const lines = store.lines.map(line => {
|
|
175
|
+
const rec = parseLine(line);
|
|
176
|
+
return rec && !("type" in rec) && rec.id === open.id ? JSON.stringify(open) : line;
|
|
177
|
+
});
|
|
178
|
+
writeIncidentLines(file, lines);
|
|
179
|
+
return { incident: { ...open, resolution: null, proposal: null }, deduped: true };
|
|
180
|
+
}
|
|
181
|
+
const day = strftime(now, "%Y%m%d");
|
|
182
|
+
const prefix = `I-${day}-`;
|
|
183
|
+
const used = store.incidents.filter(i => i.id.startsWith(prefix)).map(i => Number(i.id.slice(prefix.length)) || 0);
|
|
184
|
+
const rec: IncidentRec = {
|
|
185
|
+
id: `${prefix}${(used.length ? Math.max(...used) : 0) + 1}`,
|
|
186
|
+
fingerprint,
|
|
187
|
+
source: input.source,
|
|
188
|
+
kind: input.kind,
|
|
189
|
+
summary: input.summary,
|
|
190
|
+
evidence: input.evidence ?? "",
|
|
191
|
+
ts: now,
|
|
192
|
+
count: 1,
|
|
193
|
+
lastSeen: now,
|
|
194
|
+
rule: input.rule,
|
|
195
|
+
};
|
|
196
|
+
writeIncidentLines(file, [...store.lines, JSON.stringify(rec)]);
|
|
197
|
+
return { incident: { ...rec, resolution: null, proposal: null }, deduped: false };
|
|
198
|
+
});
|
|
198
199
|
}
|
|
199
200
|
|
|
200
201
|
/**
|
|
@@ -204,23 +205,24 @@ export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()):
|
|
|
204
205
|
*/
|
|
205
206
|
export function planIncident(cfg: Config, id: string, planPath: string): string | null {
|
|
206
207
|
const file = incidentsFile(cfg);
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
208
|
+
return withFileLock(`${file}.lock`, () => {
|
|
209
|
+
const store = readStore(file);
|
|
210
|
+
if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
|
|
211
|
+
const res = store.resolutions.filter(r => r.id === id).at(-1);
|
|
212
|
+
if (res) return `incident ${id} already has a ${res.type} record`;
|
|
213
|
+
const abs = resolve(q.expandHome(planPath));
|
|
214
|
+
if (!existsSync(abs)) return `plan file not found: ${abs}`;
|
|
215
|
+
if (!q.readIndex(cfg.paths.queue_index).includes(abs)) return `${abs} is not listed in ${cfg.paths.queue_index}`;
|
|
216
|
+
let text: string;
|
|
217
|
+
try {
|
|
218
|
+
text = readFileSync(abs, "utf8");
|
|
219
|
+
} catch {
|
|
220
|
+
return `cannot read ${abs}`;
|
|
221
|
+
}
|
|
222
|
+
if (!text.includes(`INCIDENT ${id}`)) return `${abs} must contain "INCIDENT ${id}" so the guards can see the fix names the incident`;
|
|
223
|
+
writeIncidentLines(file, [...store.lines, JSON.stringify({ type: "plan", id, plan: abs })]);
|
|
224
|
+
return null;
|
|
225
|
+
});
|
|
224
226
|
}
|
|
225
227
|
|
|
226
228
|
// The owner's own words, as the inject hook saw them (<queue_state>/owner-messages.jsonl, last
|
|
@@ -267,16 +269,45 @@ export function readOwnerAnswers(paths: Pick<q.QueuePaths, "queue_state">): Owne
|
|
|
267
269
|
}
|
|
268
270
|
}
|
|
269
271
|
|
|
270
|
-
|
|
272
|
+
function writeOwnerStoreUnlocked(messages: OwnerMessage[], answers: OwnerAnswer[], file: string): void {
|
|
273
|
+
writeAtomicSync(
|
|
274
|
+
file,
|
|
275
|
+
`${[...messages.slice(-50).map(m => JSON.stringify(m)), ...answers.slice(-20).map(a => JSON.stringify(a))].join("\n")}\n`,
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Rewrites the store atomically under a lock: the newest 50 messages, then the newest 20 answers. */
|
|
271
280
|
export function writeOwnerStore(messages: OwnerMessage[], answers: OwnerAnswer[], paths: Pick<q.QueuePaths, "queue_state">): void {
|
|
272
281
|
const file = ownerMessagesFile(paths);
|
|
273
|
-
|
|
274
|
-
|
|
282
|
+
withFileLock(`${file}.lock`, () => {
|
|
283
|
+
writeOwnerStoreUnlocked(messages, answers, file);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Append one owner message to the owner-messages store under its file lock.
|
|
289
|
+
*
|
|
290
|
+
* Args:
|
|
291
|
+
* text (string): Owner message text
|
|
292
|
+
* paths (Pick<q.QueuePaths, "queue_state">): Queue state directory paths
|
|
293
|
+
* at (number): Unix timestamp in seconds (defaults to `nowSec()`)
|
|
294
|
+
*
|
|
295
|
+
* Returns:
|
|
296
|
+
* void
|
|
297
|
+
*/
|
|
298
|
+
export function appendOwnerMessage(text: string, paths: Pick<q.QueuePaths, "queue_state">, at = nowSec()): void {
|
|
299
|
+
const file = ownerMessagesFile(paths);
|
|
300
|
+
withFileLock(`${file}.lock`, () => {
|
|
301
|
+
writeOwnerStoreUnlocked([...readOwnerMessages(paths), { at, text }], readOwnerAnswers(paths), file);
|
|
302
|
+
});
|
|
275
303
|
}
|
|
276
304
|
|
|
277
305
|
/** Records a real Main turn end as an answer in the same store (P5b); throws so the caller logs the failure. */
|
|
278
306
|
export function appendOwnerAnswer(answer: string, paths: Pick<q.QueuePaths, "queue_state">, at = nowSec()): void {
|
|
279
|
-
|
|
307
|
+
const file = ownerMessagesFile(paths);
|
|
308
|
+
withFileLock(`${file}.lock`, () => {
|
|
309
|
+
writeOwnerStoreUnlocked(readOwnerMessages(paths), [...readOwnerAnswers(paths), { at, answer }], file);
|
|
310
|
+
});
|
|
280
311
|
}
|
|
281
312
|
|
|
282
313
|
export function ownerSaid(words: string, messages: OwnerMessage[], now: number): boolean {
|
|
@@ -292,15 +323,16 @@ const PROOF_REF = /\S+:\d+/;
|
|
|
292
323
|
* owner taps it on the phone page or a plan closes it. A newer proposal replaces the older one. */
|
|
293
324
|
export function proposeIncident(cfg: Config, id: string, why: string, now = nowSec()): string | null {
|
|
294
325
|
const file = incidentsFile(cfg);
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
326
|
+
return withFileLock(`${file}.lock`, () => {
|
|
327
|
+
const store = readStore(file);
|
|
328
|
+
const rec = store.incidents.find(i => i.id === id);
|
|
329
|
+
if (!rec) return `unknown incident ${id}`;
|
|
330
|
+
if (store.resolutions.some(r => r.id === id)) return `incident ${id} already has a resolution record`;
|
|
331
|
+
if (!isFindingKind(rec.kind)) return `refused: propose is for finding incidents (agent-finding, main-finding); ${id} is ${rec.kind}`;
|
|
332
|
+
if (!PROOF_REF.test(why)) return "refused: the why must cite the proof as file:line, e.g. src/core/guards.ts:40";
|
|
333
|
+
writeIncidentLines(file, [...store.lines, JSON.stringify({ type: "propose", id, why: why.trim(), ts: now })]);
|
|
334
|
+
return null;
|
|
335
|
+
});
|
|
304
336
|
}
|
|
305
337
|
|
|
306
338
|
/** Records why an incident is not a bug (or not worth fixing); an empty why is refused. A finding
|
|
@@ -310,21 +342,22 @@ export function proposeIncident(cfg: Config, id: string, why: string, now = nowS
|
|
|
310
342
|
* owner page's authenticated POST /incident ("false alarm" tap); only that handler passes it. */
|
|
311
343
|
export function dismissIncident(cfg: Config, id: string, why: string, owner?: string, tapLogin?: string): string | null {
|
|
312
344
|
const file = incidentsFile(cfg);
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
if (
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
345
|
+
return withFileLock(`${file}.lock`, () => {
|
|
346
|
+
const store = readStore(file);
|
|
347
|
+
const rec = store.incidents.find(i => i.id === id);
|
|
348
|
+
if (!rec) return `unknown incident ${id}`;
|
|
349
|
+
const res = store.resolutions.filter(r => r.id === id).at(-1);
|
|
350
|
+
if (res) return `incident ${id} already has a ${res.type} record`;
|
|
351
|
+
if (!why.trim()) return "refused: an empty --why would hide the incident without a recorded reason";
|
|
352
|
+
if (isFindingKind(rec.kind) && tapLogin === undefined) {
|
|
353
|
+
if (owner === undefined)
|
|
354
|
+
return `refused: a ${rec.kind} is dismissed only with the owner's words: --owner "<quote>" (part of an owner message of the last 24 h)`;
|
|
355
|
+
if (!ownerSaid(owner, readOwnerMessages(cfg.paths), nowSec()))
|
|
356
|
+
return "refused: the --owner quote is not part of an owner message of the last 24 h";
|
|
357
|
+
}
|
|
358
|
+
writeIncidentLines(file, [...store.lines, JSON.stringify({ type: "dismiss", id, why })]);
|
|
359
|
+
return null;
|
|
360
|
+
});
|
|
328
361
|
}
|
|
329
362
|
|
|
330
363
|
/**
|
|
@@ -335,12 +368,13 @@ export function dismissIncident(cfg: Config, id: string, why: string, owner?: st
|
|
|
335
368
|
*/
|
|
336
369
|
export function fixedIncident(cfg: Config, id: string, plan: string, now = nowSec()): string | null {
|
|
337
370
|
const file = incidentsFile(cfg);
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
371
|
+
return withFileLock(`${file}.lock`, () => {
|
|
372
|
+
const store = readStore(file);
|
|
373
|
+
if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
|
|
374
|
+
const res = store.resolutions.filter(r => r.id === id).at(-1);
|
|
375
|
+
// A plan record is the normal path (planned, then fixed); dismissed or fixed is final.
|
|
376
|
+
if (res && res.type !== "plan") return `incident ${id} already has a ${res.type} record`;
|
|
377
|
+
writeIncidentLines(file, [...store.lines, JSON.stringify({ type: "fixed", id, plan, ts: now })]);
|
|
378
|
+
return null;
|
|
379
|
+
});
|
|
346
380
|
}
|
|
@@ -6,7 +6,14 @@ import { cpuCount } from "./host.ts";
|
|
|
6
6
|
|
|
7
7
|
const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "../../templates/machine-guard.sh");
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
export interface MachineGuardOptions {
|
|
10
|
+
/** Absolute path to the CLI entrypoint (`src/cli/main.ts`) invoked by `machine-guard.sh` for heavy-run status. */
|
|
11
|
+
heavyMain: string;
|
|
12
|
+
/** Runtime executable that runs `heavyMain` (default: `"bun"`). */
|
|
13
|
+
heavyStatus?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function envFor(cfg: Config, opts: MachineGuardOptions): NodeJS.ProcessEnv {
|
|
10
17
|
const cores = cpuCount();
|
|
11
18
|
const loadMax = cfg.machine.load_max > 0 ? cfg.machine.load_max : cores + cfg.machine.load_over_cores;
|
|
12
19
|
return {
|
|
@@ -21,8 +28,8 @@ function envFor(cfg: Config): NodeJS.ProcessEnv {
|
|
|
21
28
|
HEAVY_LOCK: cfg.paths.heavy_lock,
|
|
22
29
|
HEAVY_OWNER: cfg.paths.heavy_owner,
|
|
23
30
|
HEAVY_IDLE_STATE: cfg.paths.heavy_idle_state,
|
|
24
|
-
HEAVY_STATUS:
|
|
25
|
-
HEAVY_MAIN:
|
|
31
|
+
HEAVY_STATUS: opts.heavyStatus ?? "bun",
|
|
32
|
+
HEAVY_MAIN: opts.heavyMain,
|
|
26
33
|
DISK_PATH: cfg.machine.disk_path,
|
|
27
34
|
WORK_ROOT: cfg.paths.work_roots[0] ?? join(cfg.paths.home, "Work"),
|
|
28
35
|
WATCH_SEC: String(cfg.machine.watch_sec),
|
|
@@ -30,9 +37,20 @@ function envFor(cfg: Config): NodeJS.ProcessEnv {
|
|
|
30
37
|
};
|
|
31
38
|
}
|
|
32
39
|
|
|
33
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Runs `templates/machine-guard.sh` with thresholds derived from config and caller-supplied heavy-run runner paths.
|
|
42
|
+
*
|
|
43
|
+
* Args:
|
|
44
|
+
* args (string[]): CLI arguments (`--watch` optional)
|
|
45
|
+
* cfg (Config): Loaded neurastream configuration
|
|
46
|
+
* opts (MachineGuardOptions): Required `heavyMain` CLI path and optional `heavyStatus` runtime command
|
|
47
|
+
*
|
|
48
|
+
* Returns:
|
|
49
|
+
* number: Exit status from `machine-guard.sh`
|
|
50
|
+
*/
|
|
51
|
+
export function machineGuard(args: string[], cfg: Config, opts: MachineGuardOptions): number {
|
|
34
52
|
const r = spawnSync("bash", [SCRIPT, ...(args[0] === "--watch" ? ["--watch"] : [])], {
|
|
35
|
-
env: envFor(cfg),
|
|
53
|
+
env: envFor(cfg, opts),
|
|
36
54
|
encoding: "utf8",
|
|
37
55
|
});
|
|
38
56
|
if (r.stdout) process.stdout.write(r.stdout);
|
package/src/core/main-start.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
5
4
|
import type { RunSource, TraceEvent } from "./adapter.ts";
|
|
6
5
|
import { readEvents } from "./agent-score.ts";
|
|
7
6
|
import type { Config } from "./config.ts";
|
|
@@ -78,6 +77,8 @@ export interface MainStartDeps {
|
|
|
78
77
|
episodesFor?: (cutoff: number) => Episode[];
|
|
79
78
|
/** Finished task results parsed from Main's session file (the adapter's format knowledge). */
|
|
80
79
|
results?: TaskResult[];
|
|
80
|
+
/** Runs `neurastream doctor` and returns its combined output; absent omits the doctor body. */
|
|
81
|
+
doctor?: () => Promise<string> | string;
|
|
81
82
|
}
|
|
82
83
|
|
|
83
84
|
// Real-time detectors at main-start (plan 20261022_2330 P3): best effort, logged, never thrown.
|
|
@@ -203,13 +204,14 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
203
204
|
if (lines.length) say(lines.join("\n"));
|
|
204
205
|
} catch {}
|
|
205
206
|
say("=== doctor");
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
207
|
+
if (deps.doctor) {
|
|
208
|
+
try {
|
|
209
|
+
const text = await deps.doctor();
|
|
210
|
+
out.push(text.endsWith("\n") || text === "" ? text : `${text}\n`);
|
|
211
|
+
} catch (err) {
|
|
212
|
+
say(err instanceof Error ? err.message : String(err));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
213
215
|
try {
|
|
214
216
|
const sweep = mrSweep({ paths: cfg.paths });
|
|
215
217
|
if (sweep.lines.length) {
|
package/src/core/owner-topics.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { chmodSync, mkdirSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
|
+
import type { CompleteRequest, CompleteResult } from "./adapter.ts";
|
|
7
8
|
import { nowSec } from "./clock.ts";
|
|
8
9
|
import type { Config } from "./config.ts";
|
|
9
10
|
import { tryLock } from "./file-lock.ts";
|
|
@@ -11,19 +12,7 @@ import { appendJsonLines, entryIdSec, type LogEntry, ownerLogDir, ownerLogFile,
|
|
|
11
12
|
import type { QueuePaths } from "./queue/lib.ts";
|
|
12
13
|
import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
|
|
13
14
|
|
|
14
|
-
export
|
|
15
|
-
model: string;
|
|
16
|
-
system: string;
|
|
17
|
-
prompt: string;
|
|
18
|
-
maxTokens: number;
|
|
19
|
-
/** Reasoning effort for the model ("" or absent = none). */
|
|
20
|
-
effort?: string;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface CompleteResult {
|
|
24
|
-
text: string;
|
|
25
|
-
usage: { prompt_tokens: number; completion_tokens: number };
|
|
26
|
-
}
|
|
15
|
+
export type { CompleteRequest, CompleteResult };
|
|
27
16
|
|
|
28
17
|
export type Complete = (req: CompleteRequest) => Promise<CompleteResult>;
|
|
29
18
|
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Owner UI authentication, DNS-rebinding/Origin guards, CSP, form parsing, and response helpers.
|
|
2
|
+
|
|
3
|
+
import { nowSec, strftime } from "../clock.ts";
|
|
4
|
+
import type { Config } from "../config.ts";
|
|
5
|
+
import type { Tailscale } from "../tailscale.ts";
|
|
6
|
+
|
|
7
|
+
export const ANSWER_MAX = 2000;
|
|
8
|
+
/** The page's tabs, in pill order; anything else in `?tab=` renders Now. */
|
|
9
|
+
export const TABS: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"], ["knowledge", "Base"], ["results", "Results"]];
|
|
10
|
+
export const TAB_IDS = TABS.map(([id]) => id);
|
|
11
|
+
// Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
|
|
12
|
+
const TAILNET6 = /^fd7a:115c:a1e0:/i;
|
|
13
|
+
|
|
14
|
+
/** The slice of Bun's server the page needs: the peer address of a request. Bun.serve's return satisfies it. */
|
|
15
|
+
export interface UiHttpServer {
|
|
16
|
+
requestIP(req: Request): { address: string; family: string; port: number } | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type Auth = { ok: true; login: string } | { ok: false; why: string };
|
|
20
|
+
|
|
21
|
+
export function isLoopback(peer: string): boolean {
|
|
22
|
+
return peer === "::1" || peer === "localhost" || peer.startsWith("127.");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isTailnet(peer: string): boolean {
|
|
26
|
+
const v4 = /^(\d+)\.(\d+)\./.exec(peer);
|
|
27
|
+
if (v4) return v4[1] === "100" && Number(v4[2]) >= 64 && Number(v4[2]) <= 127;
|
|
28
|
+
return TAILNET6.test(peer);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals workspace.owner_login. Everything else is a 403. With `workspace.allow_this_machine`, this machine itself (loopback and its own tailnet IP) is served as the owner too — any local process can then press the buttons. */
|
|
32
|
+
export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): Auth {
|
|
33
|
+
if (!cfg.workspace.owner_login) return { ok: false, why: "workspace.owner_login is empty" };
|
|
34
|
+
if (cfg.workspace.allow_this_machine && (isLoopback(peer) || peer === tailscale.ip4())) return { ok: true, login: cfg.workspace.owner_login };
|
|
35
|
+
if (isLoopback(peer)) return { ok: false, why: "loopback peer" };
|
|
36
|
+
if (!isTailnet(peer)) return { ok: false, why: "peer is not a tailnet address" };
|
|
37
|
+
if (peer === tailscale.ip4()) return { ok: false, why: "this machine's own tailnet address" };
|
|
38
|
+
const login = tailscale.whois(peer);
|
|
39
|
+
if (!login) return { ok: false, why: "tailscale whois failed" };
|
|
40
|
+
if (login !== cfg.workspace.owner_login) return { ok: false, why: "not the owner's login" };
|
|
41
|
+
return { ok: true, login };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* DNS-rebinding guard, built once per server. A page on another host sends that Host with a
|
|
46
|
+
* matching Origin, so the peer and Origin checks alone would pass it. The Host header must
|
|
47
|
+
* name this server — the tailnet address or the MagicDNS name (dnsName(), trailing dot already
|
|
48
|
+
* stripped) — with the served port. When `allowLoopback` is enabled (e.g. `workspace.allow_this_machine`),
|
|
49
|
+
* loopback hosts (`127.0.0.1`, `localhost`, `[::1]`) are also permitted. No bound port: nothing is
|
|
50
|
+
* allowed. The phone page, pages server, and team server all call this.
|
|
51
|
+
*/
|
|
52
|
+
export function hostAllowlist(
|
|
53
|
+
tailscale: { ip4(): string | null; dnsName(): string | null },
|
|
54
|
+
opts?: { allowLoopback?: boolean },
|
|
55
|
+
): (hostHeader: string, port: number | undefined) => boolean {
|
|
56
|
+
let allowedHosts: string[] | null = null;
|
|
57
|
+
return (hostHeader, port) => {
|
|
58
|
+
// No bound port (never expected): nothing is allowed — fail closed.
|
|
59
|
+
if (port === undefined) return false;
|
|
60
|
+
if (allowedHosts === null) {
|
|
61
|
+
const dns = tailscale.dnsName();
|
|
62
|
+
const hosts = [tailscale.ip4(), dns].filter((h): h is string => Boolean(h));
|
|
63
|
+
if (opts?.allowLoopback) hosts.push("127.0.0.1", "localhost", "[::1]");
|
|
64
|
+
allowedHosts = hosts.map(h => `${h}:${port}`);
|
|
65
|
+
}
|
|
66
|
+
return allowedHosts.includes(hostHeader);
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** True when Origin is exactly `http://` plus the Host header. Callers apply it to the methods they write. */
|
|
71
|
+
export function originIsHost(origin: string | null, hostHeader: string): boolean {
|
|
72
|
+
return origin === `http://${hostHeader}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The owner pages' CSP: the one inline script takes this response's nonce; the team page shares it. */
|
|
76
|
+
export function pageCsp(nonce: string): string {
|
|
77
|
+
return `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'`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function fieldsOf(req: Request): Promise<Record<string, string>> {
|
|
81
|
+
const ct = req.headers.get("content-type") ?? "";
|
|
82
|
+
if (ct.includes("application/json")) {
|
|
83
|
+
const raw: unknown = await req.json();
|
|
84
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
85
|
+
return Object.fromEntries(Object.entries(raw as Record<string, unknown>).map(([k, v]) => [k, String(v)]));
|
|
86
|
+
}
|
|
87
|
+
const form = await req.formData();
|
|
88
|
+
return Object.fromEntries([...form.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function textRes(body: string, status: number): Response {
|
|
92
|
+
return new Response(`${body}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function redirect(target: string): Response {
|
|
96
|
+
return new Response(null, { status: 303, headers: { location: target } });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The POST reply target: the tab the owner was on (a hidden `tab` field; unknown = now, the default), then the receipt. */
|
|
100
|
+
export function sentTo(tab: string, sent: string): string {
|
|
101
|
+
const t = TAB_IDS.includes(tab) ? tab : "now";
|
|
102
|
+
return t === "now" ? `/?${sent}` : `/?tab=${t}&${sent}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The JSON POST replies (P11b): the receipt text rides along so the page script never re-derives it. */
|
|
106
|
+
export function jsonSent(sent: string, receipt?: string | null): Response {
|
|
107
|
+
return Response.json(receipt ? { ok: true, sent, receipt } : { ok: true, sent });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function jsonFail(error: string, status: number): Response {
|
|
111
|
+
return Response.json({ ok: false, error }, { status });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function esc(s: string): string {
|
|
115
|
+
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function na(label: string): string {
|
|
119
|
+
return `<p class="na">${esc(label)} unavailable</p>`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function receiptText(sent: string, params: URLSearchParams): string | null {
|
|
123
|
+
let text: string;
|
|
124
|
+
switch (sent) {
|
|
125
|
+
case "answer":
|
|
126
|
+
case "message":
|
|
127
|
+
text = `Sent to Main · ${strftime(nowSec(), "%H:%M")}`;
|
|
128
|
+
break;
|
|
129
|
+
case "team-answer": {
|
|
130
|
+
const team = params.get("team") ?? "";
|
|
131
|
+
text = `Sent to team ${team} · ${strftime(nowSec(), "%H:%M")}`;
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
case "incident-closed":
|
|
135
|
+
text = `Marked as a false alarm · ${strftime(nowSec(), "%H:%M")}`;
|
|
136
|
+
break;
|
|
137
|
+
case "incident-bug":
|
|
138
|
+
text = `Sent to Main to plan the fix · ${strftime(nowSec(), "%H:%M")}`;
|
|
139
|
+
break;
|
|
140
|
+
case "unlock": {
|
|
141
|
+
const minutes = Number(params.get("minutes"));
|
|
142
|
+
text = Number.isInteger(minutes) && minutes > 0 ? `Unlocked for ${minutes} min` : "Unlocked";
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
case "lock":
|
|
146
|
+
text = "Locked";
|
|
147
|
+
break;
|
|
148
|
+
case "reorder": {
|
|
149
|
+
// The rank counts the OPEN plans (what the page shows), not every INDEX.md line.
|
|
150
|
+
const to = Number(params.get("to"));
|
|
151
|
+
text = Number.isInteger(to) && to > 0 ? `Moved to #${to} of open plans · Main sees it next turn` : "Moved · Main sees it next turn";
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
case "unlock-off":
|
|
155
|
+
text = "Refused — chat unlock is off";
|
|
156
|
+
break;
|
|
157
|
+
case "stale":
|
|
158
|
+
text = "Already handled — Main cleared this question before your answer; your answer was still passed on.";
|
|
159
|
+
break;
|
|
160
|
+
default:
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
return text;
|
|
164
|
+
}
|