@astrofoundry/astrogate 0.0.0-stage → 0.1.1

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 (97) hide show
  1. package/README.md +2 -2
  2. package/agents/foreman.md +27 -0
  3. package/cli/astro-install.sh +242 -0
  4. package/cli/astro.sh +449 -0
  5. package/cli/astro.test.ts +65 -0
  6. package/dist/bridge.js +9950 -0
  7. package/dist/claude.js +7899 -0
  8. package/dist/extensions/bridge/index.js +9937 -0
  9. package/dist/extensions/gate/index.js +286 -0
  10. package/dist/extensions/guard/index.js +364 -0
  11. package/dist/extensions/subagents/index.js +8458 -0
  12. package/extensions/bridge/admin.ts +86 -0
  13. package/extensions/bridge/approvals.ts +147 -0
  14. package/extensions/bridge/attachments.ts +65 -0
  15. package/extensions/bridge/chunk.ts +50 -0
  16. package/extensions/bridge/claude-run.test.ts +62 -0
  17. package/extensions/bridge/claude-run.ts +301 -0
  18. package/extensions/bridge/commands.ts +89 -0
  19. package/extensions/bridge/config.ts +263 -0
  20. package/extensions/bridge/conversations.ts +144 -0
  21. package/extensions/bridge/daemon.ts +60 -0
  22. package/extensions/bridge/discord.test.ts +547 -0
  23. package/extensions/bridge/gateway.ts +222 -0
  24. package/extensions/bridge/index.ts +951 -0
  25. package/extensions/bridge/launcher.ts +36 -0
  26. package/extensions/bridge/lifecycle.test.ts +78 -0
  27. package/extensions/bridge/open-work.ts +74 -0
  28. package/extensions/bridge/plugin.ts +172 -0
  29. package/extensions/bridge/quote.ts +39 -0
  30. package/extensions/bridge/reports.ts +65 -0
  31. package/extensions/bridge/rest.ts +217 -0
  32. package/extensions/bridge/setup.ts +218 -0
  33. package/extensions/gate/approvals.test.ts +40 -0
  34. package/extensions/gate/config.ts +110 -0
  35. package/extensions/gate/core.ts +114 -0
  36. package/extensions/gate/index.test.ts +202 -0
  37. package/extensions/gate/index.ts +114 -0
  38. package/extensions/gate/risky.ts +14 -0
  39. package/extensions/gate/types.ts +19 -0
  40. package/extensions/guard/config.test.ts +107 -0
  41. package/extensions/guard/config.ts +120 -0
  42. package/extensions/guard/defaults.ts +40 -0
  43. package/extensions/guard/index.test.ts +313 -0
  44. package/extensions/guard/index.ts +183 -0
  45. package/extensions/guard/rules.test.ts +118 -0
  46. package/extensions/guard/rules.ts +101 -0
  47. package/extensions/guard/types.ts +12 -0
  48. package/extensions/subagents/agents.test.ts +137 -0
  49. package/extensions/subagents/agents.ts +207 -0
  50. package/extensions/subagents/bundled.test.ts +29 -0
  51. package/extensions/subagents/child.test.ts +202 -0
  52. package/extensions/subagents/child.ts +367 -0
  53. package/extensions/subagents/index.test.ts +123 -0
  54. package/extensions/subagents/index.ts +352 -0
  55. package/extensions/subagents/pi-paths.test.ts +39 -0
  56. package/extensions/subagents/pi-paths.ts +58 -0
  57. package/extensions/subagents/render.ts +221 -0
  58. package/extensions/subagents/sessions.test.ts +32 -0
  59. package/extensions/subagents/sessions.ts +34 -0
  60. package/extensions/subagents/ticker.test.ts +40 -0
  61. package/extensions/subagents/ticker.ts +36 -0
  62. package/harness/claude/agents.ts +93 -0
  63. package/harness/claude/claude.test.ts +171 -0
  64. package/harness/claude/hook.ts +77 -0
  65. package/harness/claude/main.ts +122 -0
  66. package/harness/claude/mcp.ts +174 -0
  67. package/harness/claude/settings.ts +63 -0
  68. package/package.json +71 -4
  69. package/release.sha256 +95 -0
  70. package/release.sha256.sig +6 -0
  71. package/specialists/AGENTS.md +67 -0
  72. package/specialists/README.md +81 -0
  73. package/specialists/entry/specialist-cli.sh +22 -0
  74. package/specialists/entry/specialist-install.sh +861 -0
  75. package/specialists/entry/specialist-install.test.ts +305 -0
  76. package/specialists/lib/argv.ts +19 -0
  77. package/specialists/lib/audit.ts +20 -0
  78. package/specialists/lib/config.ts +27 -0
  79. package/specialists/lib/errors.ts +8 -0
  80. package/specialists/lib/flush.test.ts +21 -0
  81. package/specialists/lib/lib.test.ts +87 -0
  82. package/specialists/lib/lock.test.ts +42 -0
  83. package/specialists/lib/lock.ts +67 -0
  84. package/specialists/lib/main.ts +40 -0
  85. package/specialists/lib/output.ts +11 -0
  86. package/specialists/lib/paths.ts +22 -0
  87. package/specialists/lib/pinned.test.ts +55 -0
  88. package/specialists/lib/pinned.ts +67 -0
  89. package/specialists/lib/proc.ts +49 -0
  90. package/specialists/lib/repo.ts +198 -0
  91. package/specialists/lib/runtime.test.ts +81 -0
  92. package/specialists/lib/sanitize.ts +43 -0
  93. package/specialists/lib/secrets.ts +28 -0
  94. package/specialists/lib/ssh.ts +38 -0
  95. package/specialists/lib/tunnel.test.ts +44 -0
  96. package/specialists/lib/tunnel.ts +76 -0
  97. package/specialists/provision/provision.sh +96 -0
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The LaunchAgent's run.sh. Pi's RPC mode exits when stdin closes, so stdin is
3
+ * a FIFO opened read-write: it never reaches end-of-file. `exec` makes Pi the
4
+ * job's own process, so launchd's stop signal reaches Pi, whose shutdown lets
5
+ * the bridge cancel open approvals in Discord before it exits.
6
+ */
7
+ export function runScriptText(pi: string): string {
8
+ return [
9
+ "#!/bin/sh",
10
+ "# Headless Pi host for the Discord bridge. Pi's RPC mode exits when stdin closes; a FIFO opened read-write never closes.",
11
+ "# exec makes Pi the job's process, so launchd's stop signal reaches it and the bridge can close open approvals first.",
12
+ 'export PATH="/opt/homebrew/bin:$HOME/.local/bin:/usr/bin:/bin"',
13
+ "export ASTRO_DISCORD=1",
14
+ 'cd "$HOME"',
15
+ 'fifo="$HOME/.config/astro-discord/stdin.fifo"',
16
+ '[ -p "$fifo" ] || mkfifo -m 600 "$fifo"',
17
+ `exec ${pi} --mode rpc --no-session <> "$fifo"`,
18
+ "",
19
+ ].join("\n");
20
+ }
21
+
22
+ /**
23
+ * The LaunchAgent's run.sh for the bridge as its own process: `exec` makes Node
24
+ * the job's process, so launchd's stop signal reaches the bridge, which closes
25
+ * open approvals before it exits. No harness hosts it.
26
+ */
27
+ export function daemonScriptText(node: string, bundle: string): string {
28
+ return [
29
+ "#!/bin/sh",
30
+ "# The Discord bridge as its own process; it starts Pi or Claude Code for each task (runner in config.json).",
31
+ 'export PATH="/opt/homebrew/bin:$HOME/.local/bin:/usr/bin:/bin"',
32
+ 'cd "$HOME"',
33
+ `exec ${node} ${bundle}`,
34
+ "",
35
+ ].join("\n");
36
+ }
@@ -0,0 +1,78 @@
1
+ import { spawn } from "node:child_process";
2
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
6
+ import { runScriptText } from "./launcher.ts";
7
+ import { busyPath, cancelledApprovalText, interruptedTaskText, readOpenWork, writeOpenWork } from "./open-work.ts";
8
+
9
+ describe("open work record", () => {
10
+ let dir: string;
11
+ beforeEach(() => {
12
+ dir = mkdtempSync(join(tmpdir(), "astro-open-"));
13
+ process.env.ASTRO_DISCORD_DIR = dir;
14
+ });
15
+ afterEach(() => {
16
+ delete process.env.ASTRO_DISCORD_DIR;
17
+ rmSync(dir, { recursive: true, force: true });
18
+ });
19
+
20
+ it("exists only while something is open", () => {
21
+ const work = { since: "t", tasks: [{ specialist: "arcane", channelId: "1", messageId: "2", placeholderId: "3" }], approvals: [] };
22
+ writeOpenWork(work);
23
+ expect(readOpenWork()).toEqual(work);
24
+ writeOpenWork({ since: "t", tasks: [], approvals: [] });
25
+ expect(existsSync(busyPath())).toBe(false);
26
+ expect(readOpenWork()).toBeNull();
27
+ writeFileSync(busyPath(), "not json");
28
+ expect(readOpenWork()).toBeNull();
29
+ });
30
+
31
+ it("records a slash command or button click, which has no user message", () => {
32
+ const work = { since: "t", tasks: [{ specialist: "media", channelId: "1" }], approvals: [] };
33
+ writeOpenWork(work);
34
+ expect(existsSync(busyPath())).toBe(true);
35
+ expect(readOpenWork()).toEqual(work);
36
+ });
37
+
38
+ it("says why an approval was cancelled and a task interrupted", () => {
39
+ expect(cancelledApprovalText("restart")).toMatch(/bridge restarted before a decision, so nothing was run/);
40
+ expect(cancelledApprovalText("crash")).toMatch(/stopped unexpectedly/);
41
+ expect(interruptedTaskText("arcane", "restart")).toMatch(/^❌ \*\*arcane\*\* was interrupted: the bridge restarted\./);
42
+ });
43
+ });
44
+
45
+ describe("launcher", () => {
46
+ let home: string;
47
+ beforeEach(() => {
48
+ home = mkdtempSync(join(tmpdir(), "astro-launch-"));
49
+ mkdirSync(join(home, ".config", "astro-discord"), { recursive: true });
50
+ });
51
+ afterEach(() => rmSync(home, { recursive: true, force: true }));
52
+
53
+ it("keeps stdin open and hands the stop signal to Pi", async () => {
54
+ const out = join(home, "events");
55
+ const fakePi = join(home, "fake-pi.mjs");
56
+ writeFileSync(
57
+ fakePi,
58
+ [
59
+ "#!/usr/bin/env node",
60
+ `import { appendFileSync } from "node:fs";`,
61
+ `const log = (e) => appendFileSync(${JSON.stringify(out)}, e + "\\n");`,
62
+ `log("args " + process.argv.slice(2).join(" "));`,
63
+ `process.stdin.on("end", () => log("eof"));`,
64
+ `process.stdin.resume();`,
65
+ `process.on("SIGTERM", () => { log("term"); process.exit(0); });`,
66
+ ].join("\n"),
67
+ );
68
+ chmodSync(fakePi, 0o755);
69
+ const script = join(home, "run.sh");
70
+ writeFileSync(script, runScriptText(`${process.execPath} ${fakePi}`), { mode: 0o700 });
71
+ const child = spawn("/bin/sh", [script], { env: { HOME: home, PATH: process.env.PATH ?? "" }, stdio: "ignore" });
72
+ await new Promise((resolve) => setTimeout(resolve, 1500));
73
+ child.kill("SIGTERM");
74
+ const code = await new Promise<number | null>((resolve) => child.once("exit", resolve));
75
+ expect(code).toBe(0);
76
+ expect(readFileSync(out, "utf-8").trim().split("\n")).toEqual(["args --mode rpc --no-session", "term"]);
77
+ }, 15_000);
78
+ });
@@ -0,0 +1,74 @@
1
+ import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { configDir } from "./config.ts";
4
+
5
+ /** A running task as far as Discord shows it: the user's message and the bot's "working" reply. */
6
+ export interface OpenTask {
7
+ specialist: string;
8
+ channelId: string;
9
+ /** Absent for a slash command or button click, which has no user message to answer. */
10
+ messageId?: string;
11
+ placeholderId?: string;
12
+ }
13
+
14
+ /** An approval request still waiting for a button. */
15
+ export interface OpenApproval {
16
+ ticketId: string;
17
+ channelId: string;
18
+ messageId: string;
19
+ /** The user's message that carries the 🔒 reaction. */
20
+ userChannelId: string;
21
+ userMessageId: string;
22
+ }
23
+
24
+ /**
25
+ * What the bridge has open in Discord. Written to `busy.json` whenever it
26
+ * changes and removed when nothing is open, so a restart can wait for it and a
27
+ * new process can close what a crashed one left behind.
28
+ */
29
+ export interface OpenWork {
30
+ since: string;
31
+ tasks: OpenTask[];
32
+ approvals: OpenApproval[];
33
+ }
34
+
35
+ export function busyPath(): string {
36
+ return join(configDir(), "busy.json");
37
+ }
38
+
39
+ export function writeOpenWork(work: OpenWork): void {
40
+ const path = busyPath();
41
+ if (work.tasks.length === 0 && work.approvals.length === 0) {
42
+ rmSync(path, { force: true });
43
+ return;
44
+ }
45
+ const tmp = `${path}.tmp`;
46
+ writeFileSync(tmp, `${JSON.stringify(work, null, 2)}\n`, { mode: 0o600 });
47
+ renameSync(tmp, path);
48
+ }
49
+
50
+ /** The record a previous process left, or null when it closed everything. */
51
+ export function readOpenWork(): OpenWork | null {
52
+ let raw: unknown;
53
+ try {
54
+ raw = JSON.parse(readFileSync(busyPath(), "utf-8"));
55
+ } catch {
56
+ return null;
57
+ }
58
+ const r = raw as Partial<OpenWork> | null;
59
+ if (!r || !Array.isArray(r.tasks) || !Array.isArray(r.approvals)) return null;
60
+ return { since: String(r.since ?? ""), tasks: r.tasks, approvals: r.approvals };
61
+ }
62
+
63
+ export type StopReason = "restart" | "crash";
64
+
65
+ export function cancelledApprovalText(reason: StopReason): string {
66
+ return reason === "restart"
67
+ ? "🔌 Cancelled: the bridge restarted before a decision, so nothing was run. Ask again."
68
+ : "🔌 Cancelled: the bridge stopped unexpectedly before a decision, so nothing was run. Ask again.";
69
+ }
70
+
71
+ export function interruptedTaskText(specialist: string, reason: StopReason): string {
72
+ const why = reason === "restart" ? "the bridge restarted" : "the bridge stopped unexpectedly";
73
+ return `❌ **${specialist}** was interrupted: ${why}. Work it had already started may have finished; ask it to check the current state.`;
74
+ }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The contract between the Discord bridge and a site plugin. The bridge keeps
3
+ * what every site needs: the gateway, specialist tasks and their
4
+ * conversations, approvals, open work, and the report clock. A plugin adds a
5
+ * site's reports, buttons, slash commands, and checks. The installed pack
6
+ * ships one plugin as `bridge/index.js`; its default export is a
7
+ * `PluginFactory`. A plugin imports only types and plain helpers from this
8
+ * package, which its bundle carries, because a pack cannot resolve it at run
9
+ * time; everything with state comes through `BridgeApi`. This file has no
10
+ * runtime imports, so a bundle that reads `PLUGIN_API_VERSION` pulls in no Pi code.
11
+ */
12
+ import type { Message } from "@earendil-works/pi-ai";
13
+ import type { ChannelSettings, DiscordConfig, ReportSchedule } from "./config.ts";
14
+ import type { DiscordRest, MessageComponent } from "./rest.ts";
15
+
16
+ /** Raised when the contract changes in a way an older plugin would misread; the bridge refuses another version. */
17
+ export const PLUGIN_API_VERSION = 1;
18
+
19
+ /** A slash command (type 2) or a component click (type 3) as the gateway delivers it. */
20
+ export interface Interaction {
21
+ id: string;
22
+ token: string;
23
+ type: number;
24
+ channel_id?: string;
25
+ message?: { id: string; content?: string; components?: MessageComponent[] };
26
+ data?: { custom_id?: string; component_type?: number; name?: string; options?: { name: string; type: number; value?: string | number | boolean }[] };
27
+ member?: { user?: { id: string } };
28
+ user?: { id: string };
29
+ }
30
+
31
+ export interface ExecResult {
32
+ code: number;
33
+ stdout: string;
34
+ stderr: string;
35
+ }
36
+
37
+ /** Runs one program with an argument list as the bridge's user, never through a shell; resolves even on failure. */
38
+ export type Exec = (file: string, args: string[], options: { timeoutMs: number; env?: Record<string, string> }) => Promise<ExecResult>;
39
+
40
+ /** A specialist task in a thread that the bridge opens for a plugin, such as an investigation of an alert. */
41
+ export interface InvestigationRequest {
42
+ threadId: string;
43
+ /** The bot's first message in the thread; the run's reactions and replies attach to it. */
44
+ starterId: string;
45
+ userId: string;
46
+ task: string;
47
+ }
48
+
49
+ /** Whether a service may restart now, and what still runs on it. */
50
+ export interface Activity {
51
+ idle: boolean;
52
+ running: string[];
53
+ }
54
+
55
+ /** Plugin work that counts as open: a restart waits for it, and a new process tells Discord it was interrupted. */
56
+ export interface TrackedWork {
57
+ channelId: string;
58
+ /** Shown in the bridge's activity, such as "update of Pi 1.4.0". */
59
+ label: string;
60
+ /** The name the interruption notice after a crash gives, such as `media` or `tools`. */
61
+ kind: string;
62
+ /** How a restart tells Discord the work stopped; without it nothing is posted. */
63
+ onShutdown?: () => Promise<void>;
64
+ }
65
+
66
+ /** The answer of a one-shot run of a tool-less agent. */
67
+ export interface OneShotResult {
68
+ failed: boolean;
69
+ /** The agent's final text, or the reason it failed. */
70
+ output: string;
71
+ }
72
+
73
+ /** A specialist task the bridge finished in a channel. */
74
+ export interface FinishedTask {
75
+ specialist: string;
76
+ channelId: string;
77
+ messages: TaskMessage[];
78
+ /** The bot's answer messages, oldest first. */
79
+ answerIds: string[];
80
+ failed: boolean;
81
+ }
82
+
83
+ /** How a channel with `threads: true` names, frames, and shapes the work of its thread per request. */
84
+ export interface ThreadStyle {
85
+ /** The thread's name until the specialist gives a title. */
86
+ name(request: string, now: number): string;
87
+ /** The line put above every task in the thread. */
88
+ context(threadId: string, now: number, fresh: boolean): string;
89
+ /** The answer with its title taken off and the buttons it carries. */
90
+ shape(output: string, texts: readonly string[]): { title: string | null; text: string; buttons: MessageComponent[] | null };
91
+ /** What each answer button asks the specialist, by custom id, as if written in the thread. */
92
+ buttonTasks: Readonly<Record<string, string>>;
93
+ }
94
+
95
+ /** An approval request shown in place of the bridge's standard text. */
96
+ export interface ApprovalView {
97
+ content: string;
98
+ labels: { approve: string; deny: string };
99
+ }
100
+
101
+ export interface ReportDefinition {
102
+ /** Posts one due report for the local `date`; the plugin records its own report state. */
103
+ run(schedule: ReportSchedule, date: string): Promise<unknown>;
104
+ /** The local day of the week it posts on, 0 for Sunday; every day when absent. */
105
+ weekday?: number;
106
+ /** Reports this one posts itself while it is configured; their own times are then unused. */
107
+ includes?: readonly string[];
108
+ /** The state file under the bridge's config directory whose date says whether today's report ran. */
109
+ stateFile: string;
110
+ }
111
+
112
+ export interface BridgeApi {
113
+ readonly apiVersion: number;
114
+ readonly rest: DiscordRest;
115
+ /** The package.json of the installed core, read from disk so an update shows at once. */
116
+ readonly corePackageJson: string;
117
+ log(line: string): void;
118
+ /** The configuration as last read. */
119
+ config(): DiscordConfig;
120
+ /** Reads the configuration again from disk and returns it; a file that does not validate keeps the last one. */
121
+ reloadConfig(): DiscordConfig;
122
+ stopping(): boolean;
123
+ /** Short names of the specialists configured on this host. */
124
+ specialists(): string[];
125
+ /** Whether an agent, such as one the pack ships for its reports, is installed. */
126
+ hasAgent(name: string): boolean;
127
+ /** Settings of a channel or, for a thread, of its parent; null when neither is configured. */
128
+ settingsFor(channelId: string): Promise<{ id: string; settings: ChannelSettings } | null>;
129
+ /** One specialist wrapper through the sudo entry point, without a model; rejects with its stderr. */
130
+ runEntry(service: string, caller: string, args: string[], timeoutMs: number): Promise<string>;
131
+ exec: Exec;
132
+ /** One run of a tool-less agent on a task, in no conversation. */
133
+ oneShot(agentName: string, task: string): Promise<OneShotResult>;
134
+ /** A specialist task in a thread, after any other task of that specialist; resolves true when it succeeded. */
135
+ investigate(specialist: string, request: InvestigationRequest): Promise<boolean>;
136
+ track(key: string, work: TrackedWork): void;
137
+ untrack(key: string): void;
138
+ tracked(key: string): TrackedWork | undefined;
139
+ /** What the bridge itself runs now. */
140
+ activity(): Activity;
141
+ archiveThread(threadId: string): Promise<void>;
142
+ }
143
+
144
+ export interface BridgePlugin {
145
+ readonly apiVersion: number;
146
+ readonly name: string;
147
+ reports?: Readonly<Record<string, ReportDefinition>>;
148
+ /** The application's global slash commands, which the bridge registers once it connects; none leaves the registered list alone. */
149
+ commands?(): readonly unknown[];
150
+ /** Called after the gateway connects: close what a restart left half done. */
151
+ start?(): Promise<void>;
152
+ /** Called every minute. */
153
+ tick?(): void;
154
+ /** A slash command or a click the bridge does not handle itself; resolves true when the plugin handled it. */
155
+ onInteraction?(interaction: Interaction): Promise<boolean>;
156
+ /** Called after every specialist task the bridge answered. */
157
+ afterTask?(task: FinishedTask): Promise<void>;
158
+ /** The specialist a bot message names, so a reply to it goes to that specialist. */
159
+ replySpecialist?(content: string): string | null;
160
+ threads?: ThreadStyle;
161
+ /** An approval request for these wrapper arguments shown its own way, or null for the standard text. */
162
+ approvalView?(args: readonly string[], channel: ChannelSettings | null, owners: string): ApprovalView | null;
163
+ /** The decided request's text for those arguments, or null for the standard text. */
164
+ approvalVerdict?(args: readonly string[], approved: boolean, userId: string): string | null;
165
+ /** Lines `help` adds for a user who may use these specialists. */
166
+ helpLines?(allowed: readonly string[]): string[];
167
+ }
168
+
169
+ export type PluginFactory = (api: BridgeApi) => BridgePlugin | Promise<BridgePlugin>;
170
+
171
+ /** One message of a specialist run, for plugins that read what a task did. */
172
+ export type TaskMessage = Message;
@@ -0,0 +1,39 @@
1
+ /** The parts of a Discord message worth quoting to a specialist. */
2
+ export interface QuotedMessage {
3
+ id?: string;
4
+ content?: string;
5
+ embeds?: { title?: string; description?: string; fields?: { name: string; value: string }[]; footer?: { text: string }; author?: { name?: string } }[];
6
+ attachments?: { filename: string; url?: string; content_type?: string; size?: number }[];
7
+ author?: { id: string; username?: string; bot?: boolean };
8
+ }
9
+
10
+ const QUOTE_LIMIT = 4000;
11
+
12
+ /** Plain text of a message: content, then each embed's texts, then attachment names. */
13
+ export function quoteText(message: QuotedMessage): string {
14
+ const parts: string[] = [];
15
+ const content = message.content?.trim();
16
+ if (content) parts.push(content);
17
+ for (const embed of message.embeds ?? []) {
18
+ const lines = [embed.author?.name, embed.title, embed.description, ...(embed.fields ?? []).map((f) => `${f.name}: ${f.value}`), embed.footer?.text];
19
+ for (const line of lines) {
20
+ const text = line?.trim();
21
+ if (text) parts.push(text);
22
+ }
23
+ }
24
+ if (message.attachments && message.attachments.length > 0) parts.push(`Attachments: ${message.attachments.map((a) => a.filename).join(", ")}`);
25
+ const text = parts.join("\n");
26
+ return text.length > QUOTE_LIMIT ? `${text.slice(0, QUOTE_LIMIT)}…` : text;
27
+ }
28
+
29
+ export interface Quote {
30
+ label: string;
31
+ message: QuotedMessage;
32
+ }
33
+
34
+ /** The task with the replied-to and forwarded messages appended, so the specialist sees what "this" refers to. */
35
+ export function withQuotes(task: string, quotes: readonly Quote[]): string {
36
+ const blocks = quotes.map((q) => ({ label: q.label, text: quoteText(q.message) })).filter((q) => q.text.length > 0);
37
+ if (blocks.length === 0) return task;
38
+ return `${task}\n\n${blocks.map((q) => `${q.label}:\n${q.text}`).join("\n\n")}`;
39
+ }
@@ -0,0 +1,65 @@
1
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { configDir } from "./config.ts";
4
+
5
+ /** What a report records about its last post; a plugin may extend it with its own fields. */
6
+ export interface ReportState {
7
+ /** Local date in the report's time zone, `YYYY-MM-DD`. */
8
+ date: string;
9
+ /** `skipped`: a report another one replaced that day. */
10
+ status: "sending" | "sent" | "failed" | "skipped";
11
+ messageId?: string;
12
+ }
13
+
14
+ /** Local date and minutes past midnight in a time zone. */
15
+ export function zonedNow(timeZone: string, now: Date): { date: string; minutes: number } {
16
+ const parts = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(now);
17
+ const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "";
18
+ return { date: `${get("year")}-${get("month")}-${get("day")}`, minutes: Number(get("hour")) * 60 + Number(get("minute")) };
19
+ }
20
+
21
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
22
+ export const MONDAY = 1;
23
+ export const FRIDAY = 5;
24
+
25
+ /** Local day of the week in a time zone, 0 for Sunday. */
26
+ export function zonedWeekday(timeZone: string, now: Date): number {
27
+ return WEEKDAYS.indexOf(new Intl.DateTimeFormat("en-US", { timeZone, weekday: "short" }).format(now));
28
+ }
29
+
30
+ /**
31
+ * Due once per local date, from the configured time on: a bridge that was down
32
+ * at the report's time posts when it comes back that day. Any record for today,
33
+ * even a failed or interrupted send, means no second message. With `weekday`,
34
+ * only on that local day of the week.
35
+ */
36
+ export function isDue(schedule: { time: string; timeZone: string }, state: ReportState | null, now: Date, weekday?: number): { due: boolean; date: string } {
37
+ const { date, minutes } = zonedNow(schedule.timeZone, now);
38
+ const [h, m] = schedule.time.split(":").map(Number);
39
+ const onDay = weekday === undefined || zonedWeekday(schedule.timeZone, now) === weekday;
40
+ return { due: onDay && minutes >= h * 60 + m && state?.date !== date, date };
41
+ }
42
+
43
+ const STATE_FILE = /^[a-z0-9][a-z0-9.-]*\.json$/;
44
+
45
+ function statePath(file: string): string {
46
+ if (!STATE_FILE.test(file)) throw new Error(`invalid report state file: ${file}`);
47
+ return join(configDir(), file);
48
+ }
49
+
50
+ /** The state a report recorded in `file` under the bridge's config directory, or null when it has none. */
51
+ export function readReportState<T extends ReportState = ReportState>(file: string): T | null {
52
+ try {
53
+ const raw = JSON.parse(readFileSync(statePath(file), "utf-8")) as Partial<T>;
54
+ return typeof raw.date === "string" && typeof raw.status === "string" ? (raw as T) : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ export function writeReportState<T extends ReportState>(file: string, state: T): void {
61
+ const path = statePath(file);
62
+ const tmp = `${path}.tmp`;
63
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, { mode: 0o600 });
64
+ renameSync(tmp, path);
65
+ }