neurastream 0.2.6 → 0.2.8

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.
@@ -312,6 +312,53 @@ function board(days: number, cfg: Config, source: RunSource): void {
312
312
  printText(text);
313
313
  }
314
314
 
315
+ function exitUsage(cmd: string): number {
316
+ const doc = helpDoc("agent-score");
317
+ const line = doc.split("\n").find(l => l.trim().startsWith(`agent-score ${cmd}`));
318
+ const usage = line ? `usage: ${line.trim()}` : `usage: agent-score ${cmd}`;
319
+ process.stderr.write(`${usage}\n`);
320
+ return 2;
321
+ }
322
+
323
+ const CMD_OPTS: Record<string, { val: Record<string, true>; bool: Record<string, true> }> = {
324
+ accept: {
325
+ val: { "--plan": true, "--phase": true, "--commits": true, "--repo": true, "--branch": true, "--weight": true, "--units": true, "--note": true },
326
+ bool: { "--rework": true },
327
+ },
328
+ diagnose: {
329
+ val: { "--plan": true, "--phase": true, "--evidence": true, "--weight": true, "--note": true, "--repo": true, "--branch": true },
330
+ bool: {},
331
+ },
332
+ validate: {
333
+ val: { "--plan": true, "--phase": true, "--evidence": true, "--section": true, "--weight": true, "--note": true, "--repo": true, "--branch": true },
334
+ bool: { "--rework": true },
335
+ },
336
+ penalty: {
337
+ val: { "--kind": true, "--note": true, "--plan": true, "--repo": true, "--branch": true },
338
+ bool: {},
339
+ },
340
+ };
341
+
342
+ function parseScoreTarget(cmd: string, rest: string[]): { agent: string } | number {
343
+ const spec = CMD_OPTS[cmd];
344
+ if (!spec) return 0;
345
+ if (rest.length === 0 || rest[0]!.startsWith("-")) return exitUsage(cmd);
346
+ const agent = rest[0]!;
347
+ let i = 1;
348
+ while (i < rest.length) {
349
+ const arg = rest[i]!;
350
+ if (!arg.startsWith("-")) return exitUsage(cmd);
351
+ if (spec.bool[arg]) {
352
+ i++;
353
+ } else if (spec.val[arg]) {
354
+ i += 2;
355
+ } else {
356
+ return exitUsage(cmd);
357
+ }
358
+ }
359
+ return { agent };
360
+ }
361
+
315
362
  export function agentScore(args: string[], cfg: Config, source: RunSource): number {
316
363
  mkdirSync(cfg.paths.score_state, { recursive: true });
317
364
  if (args.length < 1 || args[0] === "-h" || args[0] === "--help") {
@@ -324,10 +371,12 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
324
371
  const branch = rest.includes("--branch") ? needOpt(rest, "--branch") : cfg.score.default_branch;
325
372
  try {
326
373
  if (cmd === "accept") {
327
- const agent = rest[0];
374
+ const target = parseScoreTarget(cmd, rest);
375
+ if (typeof target === "number") return target;
376
+ const agent = target.agent;
328
377
  const plan = opt(rest, "--plan");
329
378
  const phase = opt(rest, "--phase");
330
- if (!agent || !plan || !phase || !rest.includes("--commits")) return exitText("accept needs --plan, --phase, --commits");
379
+ if (!plan || !phase || !rest.includes("--commits")) return exitText("accept needs --plan, --phase, --commits");
331
380
  if (!repo) return exitText("accept needs --repo");
332
381
  const commits = expandCommits(repo, needOpt(rest, "--commits"));
333
382
  const bad = commits.filter(c => gitRaw(repo, ["merge-base", "--is-ancestor", c, branch]).code).map(c => c.slice(0, 10));
@@ -341,11 +390,13 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
341
390
  return 0;
342
391
  }
343
392
  if (cmd === "diagnose") {
344
- const agent = rest[0];
393
+ const target = parseScoreTarget(cmd, rest);
394
+ if (typeof target === "number") return target;
395
+ const agent = target.agent;
345
396
  const plan = opt(rest, "--plan");
346
397
  const phase = opt(rest, "--phase");
347
398
  const ev = opt(rest, "--evidence");
348
- if (!agent || !plan || !phase || !ev || !existsSync(ev)) return exitText("diagnose needs --plan, --phase and an existing --evidence file");
399
+ if (!plan || !phase || !ev || !existsSync(ev)) return exitText("diagnose needs --plan, --phase and an existing --evidence file");
349
400
  const weighted = rest.includes("--weight") ? weightFor(rest, plan, phase, cfg, cfg.score.diagnose_weight) : { w: cfg.score.diagnose_weight, src: "default" };
350
401
  record({
351
402
  type: "diagnose", agent, plan, phase, weight: weighted.w, weight_src: weighted.src, evidence: ev, note: opt(rest, "--note") ?? "",
@@ -353,12 +404,14 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
353
404
  return 0;
354
405
  }
355
406
  if (cmd === "validate") {
356
- const agent = rest[0];
407
+ const target = parseScoreTarget(cmd, rest);
408
+ if (typeof target === "number") return target;
409
+ const agent = target.agent;
357
410
  const plan = opt(rest, "--plan");
358
411
  const phase = opt(rest, "--phase");
359
412
  const ev = opt(rest, "--evidence");
360
413
  const section = opt(rest, "--section");
361
- if (!agent || !plan || !phase || !ev || !section) return exitText("validate needs --plan, --phase, --evidence and --section");
414
+ if (!plan || !phase || !ev || !section) return exitText("validate needs --plan, --phase, --evidence and --section");
362
415
  if (!phaseTicked(plan, phase)) return exitText(`refused: ${phase} not ticked in ${plan}`);
363
416
  const { w, src } = weightFor(rest, plan, phase, cfg, null);
364
417
  if (!existsSync(ev)) return exitText(`refused: evidence file not found: ${ev}`);
@@ -376,11 +429,14 @@ export function agentScore(args: string[], cfg: Config, source: RunSource): numb
376
429
  return 0;
377
430
  }
378
431
  if (cmd === "penalty") {
432
+ const target = parseScoreTarget(cmd, rest);
433
+ if (typeof target === "number") return target;
434
+ const agent = target.agent;
379
435
  const kind = opt(rest, "--kind");
380
436
  const note = opt(rest, "--note");
381
437
  const kinds = Object.keys(cfg.score.penalties);
382
438
  if (!kind || !kinds.includes(kind) || !note) return exitText(`penalty needs --kind ${kinds.join("|")} and --note`);
383
- record({ type: "penalty", agent: rest[0], kind, plan: opt(rest, "--plan") ?? "", note }, cfg);
439
+ record({ type: "penalty", agent, kind, plan: opt(rest, "--plan") ?? "", note }, cfg);
384
440
  return 0;
385
441
  }
386
442
  if (cmd === "exempt") {
@@ -105,6 +105,8 @@ export interface Config {
105
105
  main_edit_limit: number;
106
106
  main_window_min: number;
107
107
  unlock_minutes: number;
108
+ /** The owner's whole chat message ("unlock", "unlock N", "lock") moves the guard unlock file. */
109
+ chat_unlock: boolean;
108
110
  plan_read_max_hours: number;
109
111
  idle_stops: number;
110
112
  blocker_timeout_ms: number;
@@ -118,6 +120,8 @@ export interface Config {
118
120
  protected: string[];
119
121
  ledger_command: string;
120
122
  };
123
+ /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
124
+ ui: { enabled: boolean; port: number; owner_login: string };
121
125
  rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
122
126
  metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
123
127
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
@@ -146,6 +150,9 @@ export interface Config {
146
150
  watch_streak: number;
147
151
  };
148
152
  quota: { reset_tz: string; label: string };
153
+ /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
154
+ * The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
155
+ notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
149
156
  priority: { sleep_sec: number };
150
157
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
151
158
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
@@ -288,6 +295,7 @@ function check(cfg: Config): void {
288
295
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
289
296
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
290
297
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
298
+ if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
291
299
  for (const p of cfg.metrics.correction_patterns) {
292
300
  try {
293
301
  new RegExp(p, "i");
@@ -23,6 +23,7 @@ import path from "node:path";
23
23
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
24
24
  import type { Config } from "./config.ts";
25
25
  import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
26
+ import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
26
27
  import * as q from "./queue/lib.ts";
27
28
  import type { Plan } from "./queue/lib.ts";
28
29
 
@@ -57,7 +58,7 @@ function windowFile(): string {
57
58
  return path.join(q.STATE_DIR, "edit-window.json");
58
59
  }
59
60
 
60
- function readWindow(): EditWindow {
61
+ export function readWindow(): EditWindow {
61
62
  try {
62
63
  const w = JSON.parse(readFileSync(windowFile(), "utf8")) as EditWindow;
63
64
  if (Array.isArray(w.used) && typeof w.windowStart === "number") return w;
@@ -65,7 +66,7 @@ function readWindow(): EditWindow {
65
66
  return { used: [], windowStart: 0 };
66
67
  }
67
68
 
68
- function writeWindow(w: EditWindow): void {
69
+ export function writeWindow(w: EditWindow): void {
69
70
  try {
70
71
  mkdirSync(q.STATE_DIR, { recursive: true });
71
72
  writeFileSync(windowFile(), JSON.stringify(w, null, 1));
@@ -193,6 +194,9 @@ function protectedHit(paths: string[], cfg: Config): string | null {
193
194
  const g = q.expandHome(raw);
194
195
  if (g.endsWith("/") ? p.startsWith(g) || `${p}/` === g : p === g) return p;
195
196
  }
197
+ // The user's config file and the configured notify secret files are guard surface too:
198
+ // an agent that could rewrite them could point notify at its own webhook.
199
+ if (notifyProtectedPaths(cfg).includes(p)) return p;
196
200
  }
197
201
  return null;
198
202
  }
@@ -348,6 +352,28 @@ function runsCloser(input: Record<string, unknown>): boolean {
348
352
  });
349
353
  }
350
354
 
355
+ // True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
356
+ // serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
357
+ // owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
358
+ // skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
359
+ function startsOwnerUi(input: Record<string, unknown>): boolean {
360
+ const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
361
+ const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
362
+ return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
363
+ const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
364
+ let i = 0;
365
+ while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
366
+ const cmd = bin(words[i]);
367
+ if ((cmd === "ui" && bin(words[i - 1]) === "neurastream") || (cmd === "neurastream" && bin(words[i + 1]) === "ui")) return true;
368
+ return (
369
+ cmd === "systemctl" &&
370
+ words.some(w => w === "--user") &&
371
+ words.some(w => w === "start" || w === "restart" || w === "enable") &&
372
+ words.some(w => bin(w) === "neurastream-ui" || w.startsWith("neurastream-ui."))
373
+ );
374
+ });
375
+ }
376
+
351
377
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
352
378
  // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
353
379
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
@@ -356,7 +382,11 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
356
382
  return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
357
383
  const plans = q.activePlans();
358
384
  if (e.calls >= cap) {
359
- const planEdit = (e.tool === "write" || e.tool === "edit") && writes.length > 0 && writes.every(p => q.planAt(p, plans));
385
+ // Plan edit targets come from writeTargets (write and structured/hashline edit)
386
+ // with touchedPaths as fallback; plan reads match any read tool.
387
+ const planEdit =
388
+ (e.tool === "write" || e.tool === "edit") &&
389
+ (writes.length > 0 ? writes.every(p => q.planAt(p, plans)) : paths.length > 0 && paths.every(p => q.planAt(p, plans)));
360
390
  const planRead = cfg.guards.read_tools.includes(e.tool) && paths.length > 0 && paths.every(p => q.planAt(p, plans));
361
391
  if (!planEdit && !planRead)
362
392
  return `call budget spent (${e.calls}/${cap}). Only reading and editing your plan's "## Progress" is allowed now: write what you did, what is verified, what is next, then end your run.`;
@@ -505,11 +535,27 @@ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
505
535
  export function checkTool(e: ToolEvent, cfg: Config): Decision {
506
536
  if (cfg.guards.skip_tools.includes(e.tool)) return ALLOW;
507
537
  const input = e.input ?? {};
538
+ // Starting the owner page (plan 20261024_2230 P3c) is the owner's systemd move, never an
539
+ // agent's, unlocked or not: refused plan-guard style like a protected-file write.
540
+ if (cfg.guards.shell_tools.includes(e.tool) && startsOwnerUi(input)) {
541
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} ui-start: ${String(input.command ?? "")}`);
542
+ return deny(
543
+ "plan-guard: starting the owner page (neurastream ui, or systemctl --user start/restart/enable of neurastream-ui) is the owner's move, not an agent's.",
544
+ );
545
+ }
508
546
  // The caller may know paths the text search cannot see (structured edits); union, never shrink.
509
547
  const paths: string[] = [];
510
548
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
511
549
  const writes: string[] = [];
512
550
  for (const p of [...(e.writes ?? []), ...q.writeTargets(e.tool, input, e.cwd)]) if (!writes.includes(p)) writes.push(p);
551
+ // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
552
+ // A call that changes a secret is not a read: its target goes through the protected-write
553
+ // rule above, so the owner's unlock covers it like any guard file.
554
+ const secretHit = notifySecretReadHit(paths.filter(p => !writes.includes(p)), cfg);
555
+ if (secretHit) {
556
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit}`);
557
+ return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`);
558
+ }
513
559
  // Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
514
560
  // of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
515
561
  const rolloverDir = path.join(q.stateDirPath(), "rollover");
@@ -521,7 +567,9 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
521
567
  if (hit && !unlocked(cfg)) {
522
568
  log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} protected: ${hit}`);
523
569
  return deny(
524
- `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal, valid ${cfg.guards.unlock_minutes} min).`,
570
+ `plan-guard: ${hit} is a protected guard file. Only the owner changes it (unlock: \`touch ${q.UNLOCK}\` in a terminal${
571
+ cfg.guards.chat_unlock ? `, or type \`unlock ${cfg.guards.unlock_minutes}\` in chat` : ""
572
+ }, valid ${cfg.guards.unlock_minutes} min).`,
525
573
  );
526
574
  }
527
575
  if (e.agent === "main") {
@@ -590,6 +638,18 @@ function recordMainReads(files: string[], now = Date.now()): void {
590
638
  * Main's tool result: each `path:line:` at a line start (grep -n / grep -rn output) names a file
591
639
  * Main read. Paths resolve against the directory the call ran in (its `cwd`, then any `cd`).
592
640
  */
641
+ export function revertMainEdit(tool: string, input: Record<string, unknown>, cwd: string, cfg: Config): void {
642
+ const files = changedProjectFiles(tool, input, cwd, cfg);
643
+ if (!files.length) return;
644
+ const w = readWindow();
645
+ const entry = `${tool}:${files[0]!}`;
646
+ const idx = w.used.lastIndexOf(entry);
647
+ if (idx >= 0) {
648
+ w.used.splice(idx, 1);
649
+ writeWindow(w);
650
+ }
651
+ }
652
+
593
653
  export function recordMainResult(tool: string, input: Record<string, unknown>, cwd: string, text: string): void {
594
654
  const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
595
655
  const dir = q.shellCwd(String(input.command ?? input.code ?? ""), base);
@@ -0,0 +1,197 @@
1
+ // Chat notify (plan 20261024_2155): Main's final reply is posted to Discord and/or Slack when a
2
+ // session stop hands the turn back to the owner. The webhook URLs live in secret files — the
3
+ // config holds only their paths. This module knows the configured paths, keeps every agent away
4
+ // from them (guard rules in guards.ts), and does the posting. Plain TypeScript, no harness here.
5
+
6
+ import { dirname } from "node:path";
7
+ import { readFileSync, statSync } from "node:fs";
8
+ import { configFile, type Config } from "./config.ts";
9
+
10
+ export type NotifyProviderName = "discord" | "slack";
11
+
12
+ export interface NotifyProvider {
13
+ name: NotifyProviderName;
14
+ /** Path of the secret file holding this provider's webhook URL. */
15
+ file: string;
16
+ }
17
+
18
+ /** The configured providers in posting order; a provider is on when its file path is non-empty. */
19
+ export function notifyProviders(cfg: Config): NotifyProvider[] {
20
+ const out: NotifyProvider[] = [];
21
+ if (cfg.notify.discord_webhook_file) out.push({ name: "discord", file: cfg.notify.discord_webhook_file });
22
+ if (cfg.notify.slack_webhook_file) out.push({ name: "slack", file: cfg.notify.slack_webhook_file });
23
+ return out;
24
+ }
25
+
26
+ /** The configured secret files (paths only; contents are read at post time, never cached). */
27
+ export function notifySecretFiles(cfg: Config): string[] {
28
+ return notifyProviders(cfg).map(p => p.file);
29
+ }
30
+
31
+ /** Writes that change a notify secret or the config file itself need the owner's unlock. */
32
+ export function notifyProtectedPaths(cfg: Config): string[] {
33
+ return [configFile(cfg.paths.home), ...notifySecretFiles(cfg)];
34
+ }
35
+
36
+ const GLOB_META = /[*?[]/;
37
+
38
+ function hitsSecret(p: string, file: string): boolean {
39
+ const dir = dirname(file);
40
+ if (p === file || p === dir || p.startsWith(`${dir}/`)) return true;
41
+ const m = GLOB_META.exec(p);
42
+ if (!m) return false;
43
+ const base = p.slice(0, m.index).replace(/\/+$/, "");
44
+ if (!base) return false;
45
+ // The glob's literal prefix is the secrets dir, sits inside it, or is an ancestor of it:
46
+ // every match it can name is a secret (or reveals the directory listing).
47
+ return base === dir || base.startsWith(`${dir}/`) || dir.startsWith(`${base}/`);
48
+ }
49
+
50
+ /** The first touched read path that hits a configured secret file, its directory, or a glob over
51
+ * them; null otherwise. Refused with or without the guard unlock: no agent ever needs a webhook
52
+ * URL. Reading the config file itself and other files beside the secrets stays allowed. */
53
+ export function notifySecretReadHit(paths: string[], cfg: Config): string | null {
54
+ for (const p of paths) {
55
+ for (const file of notifySecretFiles(cfg)) {
56
+ if (hitsSecret(p, file)) return p;
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+
62
+ export interface NotifyFindings {
63
+ problems: string[];
64
+ warnings: string[];
65
+ }
66
+
67
+ /** Host fragments that mark a webhook URL pasted straight into the config file, by provider. */
68
+ const RAW_URL_LABELS: Record<string, string> = {
69
+ "discord.com/api/webhooks": "discord",
70
+ "discordapp.com/api/webhooks": "discord",
71
+ "hooks.slack.com": "slack",
72
+ };
73
+
74
+ /** Doctor findings for the notify setup: a problem when a secret file is readable by group or
75
+ * others, when the config file holds a raw webhook URL, or when a secret file sits next to
76
+ * config.yml; a warning only when a configured secret file is missing (notify is simply off). */
77
+ export function notifyFindings(cfg: Config): NotifyFindings {
78
+ const problems: string[] = [];
79
+ const warnings: string[] = [];
80
+ const configPath = configFile(cfg.paths.home);
81
+ const configDir = dirname(configPath);
82
+ let raw = "";
83
+ try {
84
+ raw = readFileSync(configPath, "utf8");
85
+ } catch {}
86
+ const rawLabels = new Set<string>();
87
+ for (const [host, label] of Object.entries(RAW_URL_LABELS)) if (raw.includes(host)) rawLabels.add(label);
88
+ for (const label of rawLabels) {
89
+ problems.push(`notify: ${configPath} holds a raw ${label} webhook URL; anyone holding it can post as the bot — keep it in a secret file`);
90
+ }
91
+ for (const p of notifyProviders(cfg)) {
92
+ const key = `notify.${p.name}_webhook_file`;
93
+ let st;
94
+ try {
95
+ st = statSync(p.file);
96
+ } catch {
97
+ warnings.push(`notify: ${key} points at ${p.file}, which does not exist; notify stays off until the owner writes it`);
98
+ continue;
99
+ }
100
+ if ((st.mode & 0o77) !== 0) {
101
+ problems.push(`notify: ${p.file} is readable by group/others (mode ${(st.mode & 0o777).toString(8)}); chmod 600 it`);
102
+ }
103
+ if (dirname(p.file) === configDir) {
104
+ problems.push(`notify: ${p.file} sits next to ${configPath}; keep the webhook files in their own directory`);
105
+ }
106
+ }
107
+ return { problems, warnings };
108
+ }
109
+
110
+ // --- posting ---
111
+
112
+ const DISCORD_LIMIT = 2000;
113
+ const SLACK_LIMIT = 3000;
114
+ const POST_TIMEOUT_MS = 5000;
115
+
116
+ export interface NotifyPostResult {
117
+ provider: NotifyProviderName;
118
+ /** True when every chunk of the reply got a 2xx answer. */
119
+ posted: boolean;
120
+ chunks: number;
121
+ /** Why nothing (or not everything) was posted; empty on success. */
122
+ error: string;
123
+ }
124
+
125
+ /** https, or a loopback http URL (local fakes and self-tests): a real webhook URL is always https. */
126
+ function postableUrl(url: string): boolean {
127
+ if (url.startsWith("https://")) return true;
128
+ return /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])([:/?]|$)/.test(url);
129
+ }
130
+
131
+ /** Split within the provider's limit on line boundaries where possible; a run of text longer than
132
+ * the limit is hard-split, so nothing is ever lost. */
133
+ export function notifyChunks(text: string, limit: number): string[] {
134
+ if (text.length <= limit) return [text];
135
+ const out: string[] = [];
136
+ let rest = text;
137
+ while (rest.length > limit) {
138
+ const nl = rest.lastIndexOf("\n", limit - 1);
139
+ const cut = nl > 0 ? nl + 1 : limit;
140
+ out.push(rest.slice(0, cut));
141
+ rest = rest.slice(cut);
142
+ }
143
+ if (rest.length > 0) out.push(rest);
144
+ return out;
145
+ }
146
+
147
+ function webhookUrl(p: NotifyProvider): { url: string; why: string } {
148
+ let raw = "";
149
+ try {
150
+ raw = readFileSync(p.file, "utf8").trim();
151
+ } catch (err) {
152
+ return { url: "", why: `cannot read ${p.file}: ${err instanceof Error ? err.message : String(err)}` };
153
+ }
154
+ if (raw === "") return { url: "", why: `${p.file} is empty` };
155
+ if (!postableUrl(raw)) return { url: "", why: `${p.file} does not hold an https webhook URL` };
156
+ return { url: raw, why: "" };
157
+ }
158
+
159
+ async function postChunks(provider: NotifyProvider, url: string, chunks: string[]): Promise<NotifyPostResult> {
160
+ const key = provider.name === "discord" ? "content" : "text";
161
+ for (const [i, chunk] of chunks.entries()) {
162
+ try {
163
+ const r = await fetch(url, {
164
+ method: "POST",
165
+ headers: { "content-type": "application/json" },
166
+ body: JSON.stringify({ [key]: chunk }),
167
+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),
168
+ });
169
+ if (!r.ok) {
170
+ return { provider: provider.name, posted: false, chunks: i + 1, error: `${provider.name} answered ${r.status} on chunk ${i + 1}/${chunks.length}` };
171
+ }
172
+ } catch (err) {
173
+ return { provider: provider.name, posted: false, chunks: i + 1, error: `${provider.name} chunk ${i + 1}/${chunks.length} failed: ${err instanceof Error ? err.message : String(err)}` };
174
+ }
175
+ }
176
+ return { provider: provider.name, posted: true, chunks: chunks.length, error: "" };
177
+ }
178
+
179
+ /** Post Main's final reply to every configured provider, chunks in order, one attempt per chunk
180
+ * (5 s timeout). Never throws and never retries: a failed or slow post comes back as a failed
181
+ * result for the caller to log. */
182
+ export async function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
183
+ const providers = notifyProviders(cfg);
184
+ const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text;
185
+ if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
186
+ const out: NotifyPostResult[] = [];
187
+ for (const p of providers) {
188
+ const { url, why } = webhookUrl(p);
189
+ if (url === "") {
190
+ out.push({ provider: p.name, posted: false, chunks: 0, error: why });
191
+ continue;
192
+ }
193
+ const limit = p.name === "discord" ? DISCORD_LIMIT : SLACK_LIMIT;
194
+ out.push(await postChunks(p, url, notifyChunks(body, limit)));
195
+ }
196
+ return out;
197
+ }