@ulm0/gonogo 0.0.0-stage → 0.1.2

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 (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-BqCn1SM7.js +50 -0
  20. package/dist/client/assets/index-KZtFVMJG.css +1 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/audited.js +133 -0
  25. package/dist/server/blackbox.js +261 -0
  26. package/dist/server/board.js +123 -0
  27. package/dist/server/cleanroom.js +214 -0
  28. package/dist/server/clearance.js +158 -0
  29. package/dist/server/cli.js +763 -0
  30. package/dist/server/command.js +44 -0
  31. package/dist/server/constants.js +465 -0
  32. package/dist/server/docking.js +541 -0
  33. package/dist/server/downlink.js +191 -0
  34. package/dist/server/hangar.js +311 -0
  35. package/dist/server/home.js +520 -0
  36. package/dist/server/hooks.js +166 -0
  37. package/dist/server/hub.js +2642 -0
  38. package/dist/server/launcher.js +547 -0
  39. package/dist/server/livery.js +210 -0
  40. package/dist/server/logchart.js +58 -0
  41. package/dist/server/logsearch.js +112 -0
  42. package/dist/server/massbudget.js +169 -0
  43. package/dist/server/mcp.js +228 -0
  44. package/dist/server/migrate.js +122 -0
  45. package/dist/server/missionlog.js +211 -0
  46. package/dist/server/payload.js +168 -0
  47. package/dist/server/propellant.js +314 -0
  48. package/dist/server/providers.js +199 -0
  49. package/dist/server/recorder.js +176 -0
  50. package/dist/server/relay.js +300 -0
  51. package/dist/server/relaykinds.js +182 -0
  52. package/dist/server/relief.js +226 -0
  53. package/dist/server/rollout.js +172 -0
  54. package/dist/server/schedules.js +277 -0
  55. package/dist/server/tasks.js +272 -0
  56. package/dist/server/telemetry.js +110 -0
  57. package/dist/server/terminal.js +635 -0
  58. package/dist/server/uplinks.js +356 -0
  59. package/dist/server/web.js +1607 -0
  60. package/dist/shared/cron.js +149 -0
  61. package/dist/shared/fuel.js +18 -0
  62. package/dist/shared/livery.js +348 -0
  63. package/dist/shared/positions.js +132 -0
  64. package/dist/shared/protocol.js +245 -0
  65. package/package.json +84 -3
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Relay: Slack, GitHub, Linear and Telegram (docs/relay-spec.md). The inbound half is the uplink kinds of relaykinds.ts; this is
3
+ * the outbound half and what ties the two together.
4
+ *
5
+ * relay.json (mode 0600, written whole through a temporary file and a rename) holds the targets, a Slack channel and a Telegram
6
+ * chat each with the bot token that posts there, and which kinds of Downlink item are sent to them. Every forward is one call
7
+ * of fetch with a timeout, tried again with a growing wait; a token is never logged and never sent to a browser. A message
8
+ * that was forwarded is remembered by the id the service gave it (a Slack `ts`, a Telegram message id), so that a thread
9
+ * reply or a Telegram reply to it comes back as a message to the agent that wrote it (`find`). The clock, fetch and the
10
+ * sleep between tries are injected for tests.
11
+ *
12
+ * shortcut: the targets' tokens are stored as text in the 0600 file (a bot token has to be sent as it is), so encrypt the file
13
+ * if the home folder is ever shared.
14
+ * shortcut: the map of forwarded messages and the list of handled inbound ids are in memory, bounded, and gone at a restart: a
15
+ * reply to a message from before the restart is a message to the uplink's agent (Telegram, a Slack DM) or is dropped (Slack channel).
16
+ * Persist them if restarts get common.
17
+ */
18
+ import { randomBytes } from 'node:crypto';
19
+ import { readFile, rename, writeFile } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+ import { RELAY_FORWARD_KINDS, RELAY_SERVICES } from '../shared/protocol.js';
22
+ import { FILE_MODE, RELAY_BACKOFF_MS, RELAY_FILE, RELAY_NOTE_MAX_CHARS, RELAY_QUEUE_MAX, RELAY_RETRY_AFTER_MAX_MS, RELAY_SEEN_MAX, RELAY_TEXT_MAX_CHARS, RELAY_THREADS_MAX, RELAY_TIMEOUT_MS, RELAY_TRIES, } from './constants.js';
23
+ import { isRecord } from './hooks.js';
24
+ import { cutText, HubError } from './hub.js';
25
+ const pick = (value, path) => path.reduce((at, key) => (isRecord(at) ? at[key] : undefined), value);
26
+ const SERVICES = {
27
+ slack: {
28
+ label: 'Slack',
29
+ token: /^xoxb-[A-Za-z0-9-]{10,200}$/,
30
+ to: /^[CGD][A-Z0-9]{6,20}$/,
31
+ toHint: 'the channel id, such as C0123456789',
32
+ request: (target, text) => ({
33
+ url: 'https://slack.com/api/chat.postMessage',
34
+ headers: { Authorization: `Bearer ${target.token}`, 'Content-Type': 'application/json; charset=utf-8' },
35
+ // `&`, `<` and `>` are Slack's own markup: an agent's text must not be able to say <!channel>
36
+ body: { channel: target.to, text: text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') },
37
+ }),
38
+ answer: (json) => {
39
+ const ts = pick(json, ['ts']);
40
+ const channel = pick(json, ['channel']);
41
+ return {
42
+ ok: pick(json, ['ok']) === true,
43
+ error: typeof pick(json, ['error']) === 'string' ? String(pick(json, ['error'])) : '',
44
+ key: typeof ts === 'string' && typeof channel === 'string' ? `slack:${channel}:${ts}` : null,
45
+ };
46
+ },
47
+ },
48
+ telegram: {
49
+ label: 'Telegram',
50
+ token: /^\d{4,15}:[A-Za-z0-9_-]{20,64}$/,
51
+ to: /^-?[1-9]\d{0,19}$/,
52
+ toHint: 'the chat id, a number such as 123456789',
53
+ request: (target, text) => ({
54
+ // the token is part of the address: this url is never logged
55
+ url: `https://api.telegram.org/bot${target.token}/sendMessage`,
56
+ headers: { 'Content-Type': 'application/json' },
57
+ body: { chat_id: target.to, text },
58
+ }),
59
+ answer: (json, target) => {
60
+ const id = pick(json, ['result', 'message_id']);
61
+ return {
62
+ ok: pick(json, ['ok']) === true,
63
+ error: typeof pick(json, ['description']) === 'string' ? String(pick(json, ['description'])) : '',
64
+ key: typeof id === 'number' ? `telegram:${target.to}:${id}` : null,
65
+ };
66
+ },
67
+ },
68
+ };
69
+ const LABEL = { message: 'Message', redline: 'Redline', tminus: 'T-minus', 'flight-plan': 'Flight Plan' };
70
+ const bad = (message, field) => new HubError('bad_request', message, field);
71
+ const serviceOf = (name) => {
72
+ if (!RELAY_SERVICES.includes(name))
73
+ throw new HubError('not_found', 'unknown service');
74
+ return name;
75
+ };
76
+ const isForward = (kind) => RELAY_FORWARD_KINDS.includes(kind);
77
+ const reasonOf = (error) => (error instanceof Error ? (error.name === 'TimeoutError' ? 'timed out' : error.message) : String(error));
78
+ /** The wait the service asks for, in ms, or null. */
79
+ const retryAfter = (res) => {
80
+ const seconds = Number(res.headers.get('retry-after'));
81
+ return Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds * 1000, RELAY_RETRY_AFTER_MAX_MS) : null;
82
+ };
83
+ export function createRelay(options) {
84
+ const { dir, now, log } = options;
85
+ const path = join(dir, RELAY_FILE);
86
+ const targets = {};
87
+ const last = {};
88
+ /** Everything is sent until the Director chooses. */
89
+ let forwarded = new Set(RELAY_FORWARD_KINDS);
90
+ /** Forwarded messages by the service's own id, oldest first (a Map keeps the order of insertion). */
91
+ const threads = new Map();
92
+ const handled = new Set();
93
+ const queue = [];
94
+ let draining = false;
95
+ let chain = Promise.resolve();
96
+ const closing = new AbortController();
97
+ const later = (fn) => {
98
+ const run = chain.then(fn);
99
+ chain = run.catch((error) => log.error('relay could not write', error));
100
+ return run.then(() => undefined);
101
+ };
102
+ const save = () => {
103
+ const json = JSON.stringify({ version: 1, ...targets, forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)) }, null, 2);
104
+ return later(async () => {
105
+ const tmp = join(dir, `.${RELAY_FILE}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
106
+ await writeFile(tmp, json, { mode: FILE_MODE, flag: 'wx' });
107
+ await rename(tmp, path);
108
+ });
109
+ };
110
+ const view = () => {
111
+ const of = (service) => (targets[service] ? { to: targets[service].to, last: last[service] ?? null } : null);
112
+ return { slack: of('slack'), telegram: of('telegram'), forward: RELAY_FORWARD_KINDS.filter((k) => forwarded.has(k)) };
113
+ };
114
+ /** One message to one service: the id the service gave it, or why it did not go. Never throws, never says the token. */
115
+ async function post(service, target, text, tries) {
116
+ const def = SERVICES[service];
117
+ const { url, headers, body } = def.request(target, text);
118
+ let note = '';
119
+ for (let attempt = 1; attempt <= tries && !closing.signal.aborted; attempt++) {
120
+ let wait = RELAY_BACKOFF_MS * 2 ** (attempt - 1);
121
+ try {
122
+ const res = await options.fetch(url, {
123
+ method: 'POST',
124
+ headers,
125
+ body: JSON.stringify(body),
126
+ // a redirect would carry the token somewhere else
127
+ redirect: 'error',
128
+ signal: AbortSignal.any([AbortSignal.timeout(RELAY_TIMEOUT_MS), closing.signal]),
129
+ });
130
+ const answer = def.answer(await res.json().catch(() => null), target);
131
+ if (res.ok && answer.ok)
132
+ return { ok: true, note: 'sent', key: answer.key };
133
+ note = `${def.label} answered ${res.status}${answer.error === '' ? '' : `: ${answer.error}`}`;
134
+ // a refusal (a wrong token, a channel that is not there) will be the same next time; a busy or broken service may not be
135
+ if (res.status !== 429 && res.status < 500)
136
+ break;
137
+ wait = retryAfter(res) ?? wait;
138
+ }
139
+ catch (error) {
140
+ note = `${def.label}: ${reasonOf(error)}`;
141
+ }
142
+ if (attempt < tries)
143
+ await options.sleep(wait);
144
+ }
145
+ return { ok: false, note: cutText(note.split(target.token).join('(token)'), RELAY_NOTE_MAX_CHARS), key: null };
146
+ }
147
+ async function drain() {
148
+ draining = true;
149
+ try {
150
+ for (let job = queue.shift(); job !== undefined; job = queue.shift()) {
151
+ try {
152
+ await job();
153
+ }
154
+ catch (error) {
155
+ log.error('relay could not send', error instanceof Error ? error.name : 'error');
156
+ }
157
+ }
158
+ }
159
+ finally {
160
+ draining = false;
161
+ }
162
+ }
163
+ /** Sends `text` to every target, one message after the other so that they stay in order. `thread` is what a reply to it will find. */
164
+ function send(text, thread) {
165
+ if (closing.signal.aborted)
166
+ return;
167
+ const clipped = text.length > RELAY_TEXT_MAX_CHARS ? `${cutText(text, RELAY_TEXT_MAX_CHARS - 1)}…` : text;
168
+ for (const service of RELAY_SERVICES) {
169
+ if (!targets[service])
170
+ continue;
171
+ queue.push(async () => {
172
+ // read when it is its turn: a target that was removed or changed while this waited gets nothing, or the new place
173
+ const target = targets[service];
174
+ if (!target)
175
+ return;
176
+ const sent = await post(service, target, clipped, RELAY_TRIES);
177
+ last[service] = { at: now(), ok: sent.ok, note: sent.note };
178
+ if (!sent.ok)
179
+ log.warn(`relay: ${service}: ${sent.note}`);
180
+ else if (thread !== null && sent.key !== null) {
181
+ threads.set(sent.key, thread);
182
+ if (threads.size > RELAY_THREADS_MAX)
183
+ threads.delete(threads.keys().next().value);
184
+ }
185
+ });
186
+ if (queue.length > RELAY_QUEUE_MAX) {
187
+ queue.shift();
188
+ log.warn('relay: the queue is full, the oldest message was dropped');
189
+ }
190
+ }
191
+ if (!draining && queue.length > 0)
192
+ void drain();
193
+ }
194
+ return {
195
+ async load() {
196
+ let saved = null;
197
+ try {
198
+ saved = JSON.parse(await readFile(path, 'utf8'));
199
+ if (!isRecord(saved) || saved.version !== 1)
200
+ throw new Error('not a version 1 relay file');
201
+ }
202
+ catch (error) {
203
+ saved = null;
204
+ if (error.code !== 'ENOENT') {
205
+ // kept aside, so that the next save cannot overwrite the tokens the Director handed over
206
+ // a SyntaxError quotes the text around the fault, which can be part of a token
207
+ log.error(`${RELAY_FILE} could not be read; the targets start empty and the file is kept as ${RELAY_FILE}.bad`, error instanceof SyntaxError ? 'not valid JSON' : error);
208
+ await rename(path, `${path}.bad`).catch(() => undefined);
209
+ }
210
+ }
211
+ if (!isRecord(saved))
212
+ return;
213
+ for (const service of RELAY_SERVICES) {
214
+ const t = saved[service];
215
+ if (t === undefined)
216
+ continue;
217
+ if (isRecord(t) && typeof t.token === 'string' && typeof t.to === 'string' && SERVICES[service].token.test(t.token) && SERVICES[service].to.test(t.to))
218
+ targets[service] = { token: t.token, to: t.to };
219
+ else
220
+ log.warn(`${RELAY_FILE}: the ${service} target was skipped`);
221
+ }
222
+ if (Array.isArray(saved.forward))
223
+ forwarded = new Set(saved.forward.filter((k) => typeof k === 'string' && isForward(k)));
224
+ },
225
+ view,
226
+ async set(name, input) {
227
+ const service = serviceOf(name);
228
+ const def = SERVICES[service];
229
+ if (!isRecord(input))
230
+ throw bad('request body must be a JSON object');
231
+ for (const key of Object.keys(input))
232
+ if (key !== 'token' && key !== 'to')
233
+ throw bad(`unknown field "${key}"`, key);
234
+ if (typeof input.to !== 'string' || !def.to.test(input.to))
235
+ throw bad(`to must be ${def.toHint}`, 'to');
236
+ const token = input.token ?? targets[service]?.token;
237
+ // the message never says the token: it may be a secret that was pasted into the wrong place
238
+ if (typeof token !== 'string' || !def.token.test(token))
239
+ throw bad(input.token === undefined ? 'token is required' : `token is not the bot token of ${def.label}`, 'token');
240
+ targets[service] = { token, to: input.to };
241
+ delete last[service];
242
+ await save();
243
+ return view();
244
+ },
245
+ async remove(name) {
246
+ const service = serviceOf(name);
247
+ delete targets[service];
248
+ delete last[service];
249
+ await save();
250
+ return view();
251
+ },
252
+ async forward(input) {
253
+ if (!isRecord(input))
254
+ throw bad('request body must be a JSON object');
255
+ for (const key of Object.keys(input))
256
+ if (key !== 'kinds')
257
+ throw bad(`unknown field "${key}"`, key);
258
+ const kinds = input.kinds;
259
+ if (!Array.isArray(kinds) || !kinds.every((k) => typeof k === 'string' && isForward(k)))
260
+ throw bad(`kinds must be a list of: ${RELAY_FORWARD_KINDS.join(', ')}`, 'kinds');
261
+ forwarded = new Set(kinds);
262
+ await save();
263
+ return view();
264
+ },
265
+ async test(name) {
266
+ const service = serviceOf(name);
267
+ const target = targets[service];
268
+ if (!target)
269
+ throw new HubError('not_found', `no ${SERVICES[service].label} target`);
270
+ const sent = await post(service, target, 'gonogo relay test: this target is connected.', 1);
271
+ last[service] = { at: now(), ok: sent.ok, note: sent.ok ? 'test sent' : sent.note };
272
+ return view();
273
+ },
274
+ observe(event) {
275
+ if (event.t !== 'activity' || event.item.to !== 'user' || !forwarded.has('message'))
276
+ return;
277
+ const m = event.item;
278
+ send(`${LABEL.message} from ${m.from}${m.subject === '' ? '' : `: ${m.subject}`}\n\n${m.body}`, { id: m.id, agent: m.from, subject: m.subject });
279
+ },
280
+ event(kind, text) {
281
+ if (isForward(kind) && forwarded.has(kind))
282
+ send(`${LABEL[kind]}: ${text}`, null);
283
+ },
284
+ find: (key) => threads.get(key),
285
+ seen(key) {
286
+ if (handled.has(key))
287
+ return true;
288
+ handled.add(key);
289
+ if (handled.size > RELAY_SEEN_MAX)
290
+ handled.delete(handled.values().next().value);
291
+ return false;
292
+ },
293
+ telegramChat: () => targets.telegram?.to ?? null,
294
+ close() {
295
+ closing.abort();
296
+ queue.length = 0;
297
+ return chain.then(() => undefined);
298
+ },
299
+ };
300
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Relay, inbound: the uplink kinds of GitHub, Linear, Slack and Telegram (docs/relay-spec.md). Each kind has the two functions
3
+ * that uplinks.ts asks of a kind: `authentic` (the proof of the service, compared in constant time) and `read` (what the body
4
+ * means). Nothing here touches the network, the files or the clock: a test feeds bodies and headers in.
5
+ *
6
+ * shortcut: GitHub, Linear and Telegram signatures carry no time, so a captured request can be sent again. Slack's carry one
7
+ * (SLACK_SIGNATURE_MAX_AGE_MS). Add a check of Linear's `webhookTimestamp` if a replay ever matters.
8
+ * shortcut: a Slack user is its id (`U123`), a channel its id: names need an API call and a token with more scopes.
9
+ */
10
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
11
+ import { SLACK_SIGNATURE_MAX_AGE_MS } from './constants.js';
12
+ import { isRecord } from './hooks.js';
13
+ import { cutText, HubError } from './hub.js';
14
+ const digest = (text) => createHash('sha256').update(text, 'utf8').digest();
15
+ /** Equal text, in constant time (both are hashed first, so that the lengths match). */
16
+ const same = (a, b) => timingSafeEqual(digest(a), digest(b));
17
+ const hmacHex = (secret, ...parts) => parts.reduce((h, part) => h.update(part), createHmac('sha256', secret)).digest('hex');
18
+ const header = (headers, name) => {
19
+ const value = headers[name];
20
+ return typeof value === 'string' ? value : null;
21
+ };
22
+ const str = (value) => (typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '');
23
+ const get = (value, path) => path.split('.').reduce((at, key) => (isRecord(at) ? at[key] : undefined), value);
24
+ /** One line of at most `max` characters; the text comes from strangers (a title, a commit) and must not break the layout. */
25
+ const line = (value, max = 200) => cutText(str(value).replace(/\s+/g, ' ').trim(), max);
26
+ /** A few lines of the text of an issue or a comment, with a mark where it was cut. */
27
+ const excerpt = (value, max = 1000) => {
28
+ const text = str(value).trim();
29
+ return text.length > max ? `${cutText(text, max)}…` : text;
30
+ };
31
+ const lines = (...parts) => parts.filter((part) => typeof part === 'string' && part !== '').join('\n');
32
+ const text = (message, extra = {}) => ({ text: message, cut: false, ...extra });
33
+ function parse(raw) {
34
+ let body;
35
+ try {
36
+ body = JSON.parse(raw.toString('utf8'));
37
+ }
38
+ catch {
39
+ throw new HubError('bad_request', 'the body is not JSON');
40
+ }
41
+ if (!isRecord(body))
42
+ throw new HubError('bad_request', 'the body is not a JSON object');
43
+ return body;
44
+ }
45
+ /* ---------------------------------------------------------------- GitHub */
46
+ /** `X-Hub-Signature-256: sha256=<hex HMAC-SHA256 of the raw body, keyed with the secret>`. */
47
+ const githubAuthentic = (raw, headers, secret) => {
48
+ const given = header(headers, 'x-hub-signature-256');
49
+ return given !== null && same(given, `sha256=${hmacHex(secret, raw)}`);
50
+ };
51
+ function githubRead(raw, headers) {
52
+ const event = header(headers, 'x-github-event');
53
+ const body = parse(raw);
54
+ const repo = line(get(body, 'repository.full_name'));
55
+ const who = line(get(body, 'sender.login'));
56
+ const action = line(body.action, 40);
57
+ const number = line(get(body, 'issue.number') ?? get(body, 'pull_request.number'), 20);
58
+ switch (event) {
59
+ case 'ping':
60
+ return { answer: { ok: true, ping: true }, note: `ping${repo === '' ? '' : ` from ${repo}`}` };
61
+ case 'push': {
62
+ const commits = Array.isArray(body.commits) ? body.commits : [];
63
+ const listed = commits.slice(0, 5).map((c) => `- ${line(get(c, 'id'), 7)} ${line(str(get(c, 'message')).split('\n')[0], 120)}`);
64
+ const flags = `${body.forced === true ? ' (forced)' : ''}${body.deleted === true ? ' (deleted)' : ''}`;
65
+ return text(lines(`GitHub push to ${repo} ${line(body.ref)} by ${line(get(body, 'pusher.name')) || who}: ${commits.length} commit${commits.length === 1 ? '' : 's'}${flags}`, ...listed, commits.length > 5 && `- and ${commits.length - 5} more`, line(body.compare, 300)));
66
+ }
67
+ case 'pull_request': {
68
+ const pr = get(body, 'pull_request');
69
+ const done = action === 'closed' && get(pr, 'merged') === true ? 'merged' : action;
70
+ return text(lines(`GitHub pull request #${number} ${done} by ${who} in ${repo}: ${line(get(pr, 'title'))}`, `${line(get(pr, 'head.ref'), 100)} into ${line(get(pr, 'base.ref'), 100)}`, line(get(pr, 'html_url'), 300), excerpt(get(pr, 'body')) && `\n${excerpt(get(pr, 'body'))}`));
71
+ }
72
+ case 'issues':
73
+ return text(lines(`GitHub issue #${number} ${action} by ${who} in ${repo}: ${line(get(body, 'issue.title'))}`, line(get(body, 'issue.html_url'), 300), excerpt(get(body, 'issue.body')) && `\n${excerpt(get(body, 'issue.body'))}`));
74
+ case 'issue_comment': {
75
+ const on = get(body, 'issue.pull_request') === undefined ? 'issue' : 'pull request';
76
+ return text(lines(`GitHub comment ${action} by ${who} on ${on} #${number} in ${repo}: ${line(get(body, 'issue.title'))}`, line(get(body, 'comment.html_url'), 300), excerpt(get(body, 'comment.body')) && `\n${excerpt(get(body, 'comment.body'))}`));
77
+ }
78
+ case 'workflow_run': {
79
+ // requested and in_progress are two more messages for each run that tells nothing the last one does not
80
+ if (action !== 'completed')
81
+ return null;
82
+ const run = get(body, 'workflow_run');
83
+ return text(lines(`GitHub workflow "${line(get(run, 'name'), 100)}" run #${line(get(run, 'run_number'), 20)} ${line(get(run, 'conclusion'), 40)} on ${line(get(run, 'head_branch'), 100)} in ${repo}`, line(get(run, 'html_url'), 300)));
84
+ }
85
+ default:
86
+ return null;
87
+ }
88
+ }
89
+ /* ---------------------------------------------------------------- Linear */
90
+ /** `Linear-Signature: <hex HMAC-SHA256 of the raw body, keyed with the signing secret>`. */
91
+ const linearAuthentic = (raw, headers, secret) => {
92
+ const given = header(headers, 'linear-signature');
93
+ return given !== null && same(given.toLowerCase(), hmacHex(secret, raw));
94
+ };
95
+ const PAST = { create: 'created', update: 'updated', remove: 'removed' };
96
+ function linearRead(raw) {
97
+ const body = parse(raw);
98
+ const data = body.data;
99
+ const type = str(body.type);
100
+ const did = PAST[str(body.action)] ?? line(body.action, 40);
101
+ const actor = line(get(body, 'actor.name')) || line(get(data, 'user.name'));
102
+ const by = actor === '' ? '' : ` by ${actor}`;
103
+ const url = line(body.url, 300);
104
+ if (type === 'Issue') {
105
+ const key = line(get(data, 'identifier')) || [line(get(data, 'team.key'), 20), line(get(data, 'number'), 20)].filter(Boolean).join('-');
106
+ const changed = isRecord(body.updatedFrom) ? Object.keys(body.updatedFrom).slice(0, 8).join(', ') : '';
107
+ const state = line(get(data, 'state.name'), 60);
108
+ const assignee = line(get(data, 'assignee.name'), 60);
109
+ return text(lines(`Linear issue ${key} ${did}${by}: ${line(get(data, 'title'))}`, [state && `state ${state}`, assignee && `assigned to ${assignee}`, line(get(data, 'priorityLabel'), 30) && `priority ${line(get(data, 'priorityLabel'), 30)}`, changed && `changed: ${changed}`].filter(Boolean).join(', '), url, excerpt(get(data, 'description')) && `\n${excerpt(get(data, 'description'))}`));
110
+ }
111
+ if (type === 'Comment') {
112
+ return text(lines(`Linear comment ${did}${by} on ${line(get(data, 'issue.title'))}`, url, excerpt(get(data, 'body')) && `\n${excerpt(get(data, 'body'))}`));
113
+ }
114
+ return null;
115
+ }
116
+ /* ---------------------------------------------------------------- Slack */
117
+ /** `X-Slack-Signature: v0=<hex HMAC-SHA256 of "v0:<timestamp>:<raw body>", keyed with the signing secret>`; the timestamp (seconds) is at most five minutes old. */
118
+ const slackAuthentic = (raw, headers, secret, now) => {
119
+ const given = header(headers, 'x-slack-signature');
120
+ const stamp = header(headers, 'x-slack-request-timestamp');
121
+ if (given === null || stamp === null || !/^\d{1,12}$/.test(stamp))
122
+ return false;
123
+ if (Math.abs(now - Number(stamp) * 1000) > SLACK_SIGNATURE_MAX_AGE_MS)
124
+ return false;
125
+ return same(given, `v0=${hmacHex(secret, `v0:${stamp}:`, raw)}`);
126
+ };
127
+ function slackRead(raw, _headers, inbound) {
128
+ const body = parse(raw);
129
+ if (body.type === 'url_verification') {
130
+ if (typeof body.challenge !== 'string')
131
+ throw new HubError('bad_request', 'the challenge is missing');
132
+ return { answer: { challenge: body.challenge }, note: 'challenge answered' };
133
+ }
134
+ const event = body.event;
135
+ if (body.type !== 'event_callback' || !isRecord(event))
136
+ return null;
137
+ const channel = str(event.channel);
138
+ const ts = str(event.ts);
139
+ const user = str(event.user);
140
+ const said = str(event.text).trim();
141
+ // a bot (this one too: what gonogo posts comes back as an event) and a message with a subtype (edits, joins) are not the Director
142
+ if (channel === '' || ts === '' || user === '' || said === '' || event.bot_id !== undefined || event.subtype !== undefined)
143
+ return null;
144
+ const mention = event.type === 'app_mention';
145
+ const direct = event.type === 'message' && event.channel_type === 'im';
146
+ const thread = str(event.thread_ts);
147
+ const parent = thread !== '' && thread !== ts ? inbound.find(`slack:${channel}:${thread}`) : undefined;
148
+ // in a channel only a reply to something gonogo posted counts: the rest of what is said there is not for the agents
149
+ if (!mention && !direct && !(event.type === 'message' && parent !== undefined))
150
+ return null;
151
+ const once = `slack:${channel}:${ts}`;
152
+ if (parent !== undefined)
153
+ return text(excerpt(said, 4000), { to: parent.agent, inReplyTo: parent.id, subject: `Re: ${parent.subject}`.slice(0, 200), once });
154
+ return text(`Slack ${mention ? 'mention' : 'direct message'} from ${user} in ${channel}:\n\n${excerpt(said, 4000)}`, { once });
155
+ }
156
+ /* ---------------------------------------------------------------- Telegram */
157
+ /** `X-Telegram-Bot-Api-Secret-Token` is the `secret_token` given to setWebhook, as it is. */
158
+ const telegramAuthentic = (_raw, headers, secret) => {
159
+ const given = header(headers, 'x-telegram-bot-api-secret-token');
160
+ return given !== null && same(given, secret);
161
+ };
162
+ function telegramRead(raw, _headers, inbound) {
163
+ const message = parse(raw).message;
164
+ const said = str(get(message, 'text')).trim();
165
+ const chat = str(get(message, 'chat.id'));
166
+ // a bot can be found and written to by anybody on Telegram: only the chat of the target is the Director
167
+ if (said === '' || chat === '' || chat !== inbound.telegramChat())
168
+ return null;
169
+ const parent = inbound.find(`telegram:${chat}:${str(get(message, 'reply_to_message.message_id'))}`);
170
+ if (parent !== undefined)
171
+ return text(excerpt(said, 4000), { to: parent.agent, inReplyTo: parent.id, subject: `Re: ${parent.subject}`.slice(0, 200) });
172
+ const name = line(get(message, 'from.first_name'), 60);
173
+ const handle = line(get(message, 'from.username'), 60);
174
+ return text(`Telegram message from ${[name, handle && `@${handle}`].filter(Boolean).join(' ') || 'the Director'} in chat ${chat}:\n\n${excerpt(said, 4000)}`);
175
+ }
176
+ /** The kinds that Relay adds to the generic one (uplinks.ts `KINDS`). */
177
+ export const RELAY_KINDS = {
178
+ github: { authentic: githubAuthentic, read: githubRead },
179
+ linear: { authentic: linearAuthentic, read: linearRead },
180
+ slack: { authentic: slackAuthentic, read: slackRead },
181
+ telegram: { authentic: telegramAuthentic, read: telegramRead },
182
+ };