neurastream 0.3.18 → 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/README.md +88 -490
- 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 +138 -1050
- package/src/adapters/omp/launch.ts +35 -9
- 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/claim.ts +1 -3
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +55 -30
- package/src/cli/guard.ts +0 -3
- package/src/cli/incident.ts +2 -2
- package/src/cli/metrics.ts +1 -1
- package/src/cli/recall.ts +6 -8
- package/src/cli/results-build.ts +2 -4
- package/src/cli/workspace.ts +13 -5
- package/src/core/adapter.ts +16 -0
- package/src/core/autonomy.ts +24 -21
- 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 -2661
- package/src/core/incidents.ts +134 -99
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +11 -9
- package/src/core/mr-sweep.ts +4 -2
- package/src/core/notify.ts +15 -15
- package/src/core/owner-log.ts +19 -17
- package/src/core/owner-topics.ts +38 -48
- 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 -2118
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -78
- package/src/core/plan-approval.ts +24 -26
- package/src/core/queue/lib.ts +170 -137
- package/src/core/queue-cancel.ts +29 -15
- package/src/core/queue-check.ts +5 -7
- package/src/core/queue-close.ts +54 -29
- package/src/core/queue-finished.ts +9 -10
- package/src/core/queue-migrate.ts +1 -3
- package/src/core/queue-trim.ts +2 -4
- package/src/core/results.ts +0 -2
- package/src/core/rollover.ts +2 -3
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +18 -6
- package/src/core/uninstall.ts +2 -0
- package/src/core/watch.ts +3 -2
- package/src/core/queue/env.ts +0 -14
package/src/core/owner-topics.ts
CHANGED
|
@@ -4,25 +4,15 @@
|
|
|
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";
|
|
10
11
|
import { appendJsonLines, entryIdSec, type LogEntry, ownerLogDir, ownerLogFile, readEntries, readLines } from "./owner-log.ts";
|
|
12
|
+
import type { QueuePaths } from "./queue/lib.ts";
|
|
11
13
|
import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
|
|
12
14
|
|
|
13
|
-
export
|
|
14
|
-
model: string;
|
|
15
|
-
system: string;
|
|
16
|
-
prompt: string;
|
|
17
|
-
maxTokens: number;
|
|
18
|
-
/** Reasoning effort for the model ("" or absent = none). */
|
|
19
|
-
effort?: string;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export interface CompleteResult {
|
|
23
|
-
text: string;
|
|
24
|
-
usage: { prompt_tokens: number; completion_tokens: number };
|
|
25
|
-
}
|
|
15
|
+
export type { CompleteRequest, CompleteResult };
|
|
26
16
|
|
|
27
17
|
export type Complete = (req: CompleteRequest) => Promise<CompleteResult>;
|
|
28
18
|
|
|
@@ -102,13 +92,13 @@ const SYSTEM = [
|
|
|
102
92
|
"- continues: always null.",
|
|
103
93
|
].join("\n");
|
|
104
94
|
|
|
105
|
-
export function topicsFile(): string {
|
|
106
|
-
return join(ownerLogDir(), TOPICS_FILE);
|
|
95
|
+
export function topicsFile(paths: Pick<QueuePaths, "queue_state">): string {
|
|
96
|
+
return join(ownerLogDir(paths), TOPICS_FILE);
|
|
107
97
|
}
|
|
108
98
|
|
|
109
99
|
// stdout and stderr of the background `recall topics` run: stats and `topics: fail` lines only.
|
|
110
|
-
export function topicsLogFile(): string {
|
|
111
|
-
return join(ownerLogDir(), TOPICS_LOG_FILE);
|
|
100
|
+
export function topicsLogFile(paths: Pick<QueuePaths, "queue_state">): string {
|
|
101
|
+
return join(ownerLogDir(paths), TOPICS_LOG_FILE);
|
|
112
102
|
}
|
|
113
103
|
|
|
114
104
|
export function topicsDue(count: number, every: number): boolean {
|
|
@@ -172,9 +162,9 @@ function parseRow(line: string): TopicRow | undefined {
|
|
|
172
162
|
|
|
173
163
|
// The index as a reader sees it: file order, where a line replaces every earlier line that reaches into its
|
|
174
164
|
// ids (a re-cut of the open segment, or the closed copy that --close writes). Unparsable lines are skipped.
|
|
175
|
-
function effectiveRows(): TopicRow[] {
|
|
165
|
+
function effectiveRows(paths: Pick<QueuePaths, "queue_state">): TopicRow[] {
|
|
176
166
|
const out: TopicRow[] = [];
|
|
177
|
-
for (const line of [...readLines(topicsFile())].toReversed()) {
|
|
167
|
+
for (const line of [...readLines(topicsFile(paths))].toReversed()) {
|
|
178
168
|
const row = parseRow(line);
|
|
179
169
|
if (row === undefined) continue;
|
|
180
170
|
while (out.length > 0 && out.at(-1)!.to >= row.from) out.pop();
|
|
@@ -183,8 +173,8 @@ function effectiveRows(): TopicRow[] {
|
|
|
183
173
|
return out;
|
|
184
174
|
}
|
|
185
175
|
|
|
186
|
-
export function readTopics(): Segment[] {
|
|
187
|
-
return effectiveRows().filter(isSegment);
|
|
176
|
+
export function readTopics(paths: Pick<QueuePaths, "queue_state">): Segment[] {
|
|
177
|
+
return effectiveRows(paths).filter(isSegment);
|
|
188
178
|
}
|
|
189
179
|
|
|
190
180
|
// The id the next window starts after: the last segment that is closed, or a skipped window.
|
|
@@ -389,7 +379,7 @@ function appendSegments(cfg: Config, segments: readonly AnswerSegment[]): void {
|
|
|
389
379
|
names: s.names.map(clean),
|
|
390
380
|
continues: s.continues,
|
|
391
381
|
}));
|
|
392
|
-
appendJsonLines(topicsFile(), rows);
|
|
382
|
+
appendJsonLines(topicsFile(cfg.paths), rows);
|
|
393
383
|
}
|
|
394
384
|
|
|
395
385
|
// One model call on the window. On a good answer the segments are appended; otherwise nothing is written.
|
|
@@ -442,42 +432,42 @@ async function segmentWindow(
|
|
|
442
432
|
const second = await attemptOnce(cfg, complete, window, retry, earlier, tally);
|
|
443
433
|
if (second.kind === "ok") return undefined;
|
|
444
434
|
if (second.kind === "error") return { reason: second.reason, in: second.in, out: 0 };
|
|
445
|
-
appendJsonLines(topicsFile(), [
|
|
435
|
+
appendJsonLines(topicsFile(cfg.paths), [
|
|
446
436
|
{ from: window[0]!.id, to: window.at(-1)!.id, at: nowSec(), skipped: true, why: second.reason },
|
|
447
437
|
]);
|
|
448
438
|
return { reason: second.reason, in: second.in, out: second.out };
|
|
449
439
|
}
|
|
450
440
|
|
|
451
441
|
// `--close`: the open segment becomes closed (a copy with open:false), so the next window starts after it.
|
|
452
|
-
function closeOpen(): void {
|
|
453
|
-
const last = effectiveRows().at(-1);
|
|
454
|
-
if (last !== undefined && isSegment(last) && last.open) appendJsonLines(topicsFile(), [{ ...last, open: false }]);
|
|
442
|
+
function closeOpen(paths: Pick<QueuePaths, "queue_state">): void {
|
|
443
|
+
const last = effectiveRows(paths).at(-1);
|
|
444
|
+
if (last !== undefined && isSegment(last) && last.open) appendJsonLines(topicsFile(paths), [{ ...last, open: false }]);
|
|
455
445
|
}
|
|
456
446
|
|
|
457
|
-
function oldestFirst(): LogEntry[] {
|
|
458
|
-
return [...readEntries()].toReversed();
|
|
447
|
+
function oldestFirst(paths: Pick<QueuePaths, "queue_state">): LogEntry[] {
|
|
448
|
+
return [...readEntries(paths)].toReversed();
|
|
459
449
|
}
|
|
460
450
|
|
|
461
451
|
// The entries after `afterId`, oldest first. No id means every entry.
|
|
462
|
-
export function newEntries(afterId?: string): LogEntry[] {
|
|
463
|
-
const all = oldestFirst();
|
|
452
|
+
export function newEntries(paths: Pick<QueuePaths, "queue_state">, afterId?: string): LogEntry[] {
|
|
453
|
+
const all = oldestFirst(paths);
|
|
464
454
|
if (afterId === undefined) return all;
|
|
465
455
|
const i = all.findIndex(e => e.id === afterId);
|
|
466
456
|
return i < 0 ? all : all.slice(i + 1);
|
|
467
457
|
}
|
|
468
458
|
|
|
469
459
|
// The entries from `from` to `to`, both inclusive, oldest first. Empty when either id is missing.
|
|
470
|
-
export function rangeEntries(from: string, to: string): LogEntry[] {
|
|
471
|
-
const all = oldestFirst();
|
|
460
|
+
export function rangeEntries(from: string, to: string, paths: Pick<QueuePaths, "queue_state">): LogEntry[] {
|
|
461
|
+
const all = oldestFirst(paths);
|
|
472
462
|
const a = all.findIndex(e => e.id === from);
|
|
473
463
|
const b = all.findIndex(e => e.id === to);
|
|
474
464
|
return a < 0 || b < 0 || b < a ? [] : all.slice(a, b + 1);
|
|
475
465
|
}
|
|
476
466
|
|
|
477
467
|
// Topics whose text holds every word (case-insensitive, any order), in file order.
|
|
478
|
-
export function searchTopics(query: readonly string[]): Segment[] {
|
|
468
|
+
export function searchTopics(query: readonly string[], paths: Pick<QueuePaths, "queue_state">): Segment[] {
|
|
479
469
|
const want = query.map(w => w.toLowerCase());
|
|
480
|
-
return readTopics().filter(s => {
|
|
470
|
+
return readTopics(paths).filter(s => {
|
|
481
471
|
const hay = [s.title, ...s.keywords, ...s.decisions.map(d => d.text), ...s.questions.map(q => q.text), ...s.names]
|
|
482
472
|
.join(" ")
|
|
483
473
|
.toLowerCase();
|
|
@@ -502,9 +492,9 @@ function spread(values: number[]): { mean: number; median: number; p90: number;
|
|
|
502
492
|
}
|
|
503
493
|
|
|
504
494
|
// The ids of the live log file (not the backfill): a segment's lag is measured only where its `to` is live.
|
|
505
|
-
function liveIds(): Set<string> {
|
|
495
|
+
function liveIds(paths: Pick<QueuePaths, "queue_state">): Set<string> {
|
|
506
496
|
const ids = new Set<string>();
|
|
507
|
-
for (const line of readLines(ownerLogFile())) {
|
|
497
|
+
for (const line of readLines(ownerLogFile(paths))) {
|
|
508
498
|
try {
|
|
509
499
|
const e = JSON.parse(line) as Partial<LogEntry>;
|
|
510
500
|
if (typeof e.id === "string") ids.add(e.id);
|
|
@@ -517,18 +507,18 @@ function liveIds(): Set<string> {
|
|
|
517
507
|
|
|
518
508
|
// The one stats line every run ends with. Counts come from the index as it stands; tokens and calls are
|
|
519
509
|
// this run's. Lag is the age, in hours, of each segment's `to` entry, for the segments whose `to` is live.
|
|
520
|
-
function statsLine(tally: Tally): string {
|
|
521
|
-
const rows = effectiveRows();
|
|
510
|
+
function statsLine(tally: Tally, paths: Pick<QueuePaths, "queue_state">): string {
|
|
511
|
+
const rows = effectiveRows(paths);
|
|
522
512
|
const segments = rows.filter(isSegment);
|
|
523
513
|
const skipped = rows.length - segments.length;
|
|
524
|
-
const all = oldestFirst();
|
|
514
|
+
const all = oldestFirst(paths);
|
|
525
515
|
const byId = new Map(all.map((e, index) => [e.id, { index, at: e.at }]));
|
|
526
516
|
const counts = segments.flatMap(s => {
|
|
527
517
|
const a = byId.get(s.from);
|
|
528
518
|
const b = byId.get(s.to);
|
|
529
519
|
return a !== undefined && b !== undefined && b.index >= a.index ? [b.index - a.index + 1] : [];
|
|
530
520
|
});
|
|
531
|
-
const live = liveIds();
|
|
521
|
+
const live = liveIds(paths);
|
|
532
522
|
const lags = segments.flatMap(s => {
|
|
533
523
|
const b = byId.get(s.to);
|
|
534
524
|
return b !== undefined && live.has(s.to) ? [(nowSec() - b.at) / 3600] : [];
|
|
@@ -547,7 +537,7 @@ function statsLine(tally: Tally): string {
|
|
|
547
537
|
// the lines and exits by `failures`.
|
|
548
538
|
export async function runTopics(cfg: Config, complete: Complete, opts: { close: boolean }): Promise<TopicsRun> {
|
|
549
539
|
if (!opts.close && cfg.recall.topics_model === "") return { lines: ["topics: off"], failures: 0 };
|
|
550
|
-
const dir = ownerLogDir();
|
|
540
|
+
const dir = ownerLogDir(cfg.paths);
|
|
551
541
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
552
542
|
chmodSync(dir, 0o700);
|
|
553
543
|
const lock = tryLock(join(dir, LOCK_FILE));
|
|
@@ -556,19 +546,19 @@ export async function runTopics(cfg: Config, complete: Complete, opts: { close:
|
|
|
556
546
|
try {
|
|
557
547
|
const tally: Tally = { calls: 0, tokensIn: 0, tokensOut: 0 };
|
|
558
548
|
if (opts.close) {
|
|
559
|
-
closeOpen();
|
|
560
|
-
return { lines: [statsLine(tally)], failures: 0 };
|
|
549
|
+
closeOpen(cfg.paths);
|
|
550
|
+
return { lines: [statsLine(tally, cfg.paths)], failures: 0 };
|
|
561
551
|
}
|
|
562
|
-
const rows = effectiveRows();
|
|
563
|
-
const window = newEntries(afterClosed(rows)).slice(0, WINDOW);
|
|
564
|
-
if (window.length === 0) return { lines: [statsLine(tally)], failures: 0 };
|
|
552
|
+
const rows = effectiveRows(cfg.paths);
|
|
553
|
+
const window = newEntries(cfg.paths, afterClosed(rows)).slice(0, WINDOW);
|
|
554
|
+
if (window.length === 0) return { lines: [statsLine(tally, cfg.paths)], failures: 0 };
|
|
565
555
|
const last = rows.at(-1);
|
|
566
|
-
if (last !== undefined && isSegment(last) && last.open && window.at(-1)!.id === last.to) return { lines: [statsLine(tally)], failures: 0 };
|
|
556
|
+
if (last !== undefined && isSegment(last) && last.open && window.at(-1)!.id === last.to) return { lines: [statsLine(tally, cfg.paths)], failures: 0 };
|
|
567
557
|
const failed = await segmentWindow(cfg, complete, window, rows, tally);
|
|
568
558
|
const lines = failed
|
|
569
559
|
? [`topics: fail ${window[0]!.id}..${window.at(-1)!.id} ${failed.reason} in=${failed.in} out=${failed.out}`]
|
|
570
560
|
: [];
|
|
571
|
-
lines.push(statsLine(tally));
|
|
561
|
+
lines.push(statsLine(tally, cfg.paths));
|
|
572
562
|
return { lines, failures: failed ? 1 : 0 };
|
|
573
563
|
} finally {
|
|
574
564
|
lock.release();
|
|
@@ -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
|
+
}
|