@openmuster/muster 0.0.0-stage → 0.3.1-alpha.3

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 (79) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +309 -2
  3. package/dist/args-DX9QSK1f.js +7043 -0
  4. package/dist/cli.d.ts +1 -0
  5. package/dist/cli.js +31 -0
  6. package/dist/index.d.ts +2138 -0
  7. package/dist/index.js +1951 -0
  8. package/dist/inspect/app.js +163 -0
  9. package/dist/main-CdVlnWHy.js +6 -0
  10. package/dist/main-DgrIMbeA.js +3941 -0
  11. package/dist/mcp-NueWYyQs.js +6 -0
  12. package/dist/module-C-HJjWWo.js +4 -0
  13. package/dist/module-CxoN1MOe.js +439 -0
  14. package/dist/skills/board/SKILL.md +214 -0
  15. package/dist/skills/board/references/build-a-ui.md +63 -0
  16. package/dist/skills/board/references/claude.md +54 -0
  17. package/dist/skills/board/references/codex.md +61 -0
  18. package/dist/skills/board/references/software-factory.md +89 -0
  19. package/dist/skills/board/references/swarm.md +165 -0
  20. package/dist/skills/configure-factory/SKILL.md +116 -0
  21. package/dist/skills/loop-card/SKILL.md +95 -0
  22. package/dist/steps-DtzUdcBE.js +3175 -0
  23. package/docs/01-concepts/01-overview.md +78 -0
  24. package/docs/01-concepts/02-boards.md +71 -0
  25. package/docs/01-concepts/03-channels.md +56 -0
  26. package/docs/01-concepts/04-threads.md +73 -0
  27. package/docs/01-concepts/05-labels.md +65 -0
  28. package/docs/01-concepts/06-actors.md +66 -0
  29. package/docs/01-concepts/07-events.md +133 -0
  30. package/docs/01-concepts/08-tasks.md +248 -0
  31. package/docs/01-concepts/09-watchers.md +175 -0
  32. package/docs/01-concepts/10-schedules.md +39 -0
  33. package/docs/01-concepts/11-access.md +185 -0
  34. package/docs/01-concepts/12-files-and-data.md +79 -0
  35. package/docs/01-concepts/13-budgets.md +35 -0
  36. package/docs/01-concepts/14-runners.md +103 -0
  37. package/docs/01-concepts/15-outgoing-webhooks.md +177 -0
  38. package/docs/01-concepts/16-workflows.md +350 -0
  39. package/docs/01-concepts/17-board-module.md +124 -0
  40. package/docs/01-quickstart.md +140 -0
  41. package/docs/02-sync/01-overview.md +246 -0
  42. package/docs/02-sync/02-github.md +159 -0
  43. package/docs/02-sync/03-linear.md +290 -0
  44. package/docs/02-sync/04-slack.md +228 -0
  45. package/docs/02-sync/05-notion.md +94 -0
  46. package/docs/02-sync/meta.json +4 -0
  47. package/docs/03-guides/01-coding-agents.md +98 -0
  48. package/docs/03-guides/02-swarm.md +85 -0
  49. package/docs/03-guides/03-factory.md +212 -0
  50. package/docs/03-guides/04-inspector.md +69 -0
  51. package/docs/03-guides/05-running-agents.md +85 -0
  52. package/docs/03-guides/06-sandboxed-agents.md +427 -0
  53. package/docs/03-guides/07-build-a-ui.md +80 -0
  54. package/docs/03-guides/08-ci.md +176 -0
  55. package/docs/03-guides/09-daemon.md +104 -0
  56. package/docs/03-guides/10-two-agents.md +76 -0
  57. package/docs/03-guides/11-person-in-the-loop.md +123 -0
  58. package/docs/03-guides/12-unattended.md +110 -0
  59. package/docs/03-guides/13-terminals.md +152 -0
  60. package/docs/03-guides/14-no-cloud.md +82 -0
  61. package/docs/03-guides/15-several-boards.md +90 -0
  62. package/docs/03-guides/16-non-code.md +78 -0
  63. package/docs/03-guides/17-mcp.md +122 -0
  64. package/docs/03-guides/18-a-board-on-a-server.md +162 -0
  65. package/docs/03-guides/19-a-card-queue.md +261 -0
  66. package/docs/03-guides/20-a-feedback-loop.md +233 -0
  67. package/docs/03-guides/21-running-the-loop.md +203 -0
  68. package/docs/03-guides/22-building-from-linear.md +326 -0
  69. package/docs/03-guides/meta.json +32 -0
  70. package/docs/04-reference/01-cli.md +166 -0
  71. package/docs/04-reference/02-handle.md +410 -0
  72. package/docs/04-reference/03-http.md +158 -0
  73. package/docs/04-reference/04-events.md +72 -0
  74. package/docs/04-reference/05-errors.md +221 -0
  75. package/docs/04-reference/06-conformance.md +54 -0
  76. package/docs/04-reference/07-porting.md +116 -0
  77. package/docs/index.md +118 -0
  78. package/docs/meta.json +3 -0
  79. package/package.json +52 -3
package/dist/index.js ADDED
@@ -0,0 +1,1951 @@
1
+ import { A as file, B as fetchFile, G as SEND_MS, H as refused, M as mint, N as verify, Q as channelPath, R as declared, S as listen, U as sizeOf, V as noteOut, W as withLines, b as createHandler, d as board, it as misuse, j as boardKey, k as boardPath, rt as Failure, w as SANDBOX_ROUTES, z as env } from "./args-DX9QSK1f.js";
2
+ import { A as claude, C as boardPolicy, D as agentEnv, F as conformance, M as generic, O as runLocal, P as http, S as applyPolicy, T as installationToken, a as workflowResult, d as workflowsPath, f as e2b, h as vercel, j as codex, k as AGENTS, m as cloudflare, o as fenced, u as loadWorkflows, w as githubApp } from "./steps-DtzUdcBE.js";
3
+ import { mkdirSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { createHmac, timingSafeEqual } from "node:crypto";
7
+ import { spawn } from "node:child_process";
8
+
9
+ //#region src/watch/command.ts
10
+ const WATCHER_ENV = [
11
+ "PATH",
12
+ "HOME",
13
+ "USER",
14
+ "LOGNAME",
15
+ "SHELL",
16
+ "LANG",
17
+ "LC_ALL",
18
+ "TMPDIR",
19
+ "MUSTER_DIR",
20
+ "MUSTER_BOARD",
21
+ "MUSTER_CONFIG",
22
+ "MUSTER_URL",
23
+ "MUSTER_INSECURE_HTTP"
24
+ ];
25
+ /**
26
+ * What a watcher's command starts with: built from nothing, then the few names above. The host holds
27
+ * the platforms' secrets in its own environment, and what it wakes is often an agent reading text a
28
+ * stranger wrote, so nothing else is passed on unless the watcher names it.
29
+ */
30
+ function watcherEnv(extra, allow = [], from = process.env) {
31
+ const env$1 = {};
32
+ for (const name of [...WATCHER_ENV, ...allow]) if (from[name] !== void 0) env$1[name] = from[name];
33
+ return {
34
+ ...env$1,
35
+ ...extra
36
+ };
37
+ }
38
+ /** Whether a gate's output says not to wake: its last non-empty line is JSON with `wake: false`. */
39
+ function gateSaysNo(stdout) {
40
+ const last = stdout.split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
41
+ if (!last) return false;
42
+ try {
43
+ return JSON.parse(last).wake === false;
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+ /** The most of a command's output kept: a gate's answer is its last line. */
49
+ const KEPT = 64 * 1024;
50
+ /**
51
+ * Runs a command in a process group of its own. A gate (`answer`) is read whole: settled once it has
52
+ * exited and its output has closed, so an answer printed by a child it left behind is heard. A command
53
+ * that wakes something (`wake`) writes to this process's output and is settled when it exits: what it
54
+ * started in the background (an agent) lives on, and nothing here waits for it or kills it. Until it is
55
+ * settled, `signal` tells the group to stop, and kills it after `grace`.
56
+ */
57
+ function run(argv, env$1, signal, grace, mode) {
58
+ return new Promise((resolve$1) => {
59
+ let stdout = "";
60
+ let settled = false;
61
+ const settle = (ended) => {
62
+ if (settled) return;
63
+ settled = true;
64
+ signal.removeEventListener("abort", stop);
65
+ resolve$1({
66
+ ...ended,
67
+ stdout
68
+ });
69
+ };
70
+ const child = spawn(argv[0], argv.slice(1), {
71
+ env: env$1,
72
+ stdio: [
73
+ "ignore",
74
+ mode === "answer" ? "pipe" : "inherit",
75
+ "inherit"
76
+ ],
77
+ detached: true
78
+ });
79
+ const group = (name) => {
80
+ try {
81
+ if (child.pid !== void 0) process.kill(-child.pid, name);
82
+ } catch {}
83
+ };
84
+ function stop() {
85
+ group("SIGTERM");
86
+ setTimeout(() => group("SIGKILL"), grace).unref();
87
+ }
88
+ child.stdout?.on("data", (chunk) => {
89
+ stdout += chunk.toString();
90
+ if (stdout.length > KEPT) stdout = stdout.slice(-KEPT);
91
+ });
92
+ child.on("error", () => settle({
93
+ code: 127,
94
+ signal: null
95
+ }));
96
+ child.on(mode === "answer" ? "close" : "exit", (code, killed) => settle({
97
+ code,
98
+ signal: killed
99
+ }));
100
+ if (signal.aborted) stop();
101
+ else signal.addEventListener("abort", stop, { once: true });
102
+ });
103
+ }
104
+ /**
105
+ * What a command a watcher wakes starts with: nothing of this process's environment but PATH, HOME and
106
+ * the like, the names the watcher passes on, and a pointer to what happened. Never the text: the
107
+ * command reads the thread itself, as the profile it is woken as.
108
+ */
109
+ function pointer(context) {
110
+ const { event, watcher, board: board$1 } = context;
111
+ const env$1 = {
112
+ MUSTER_WATCHER: watcher.name,
113
+ MUSTER_THREAD: event.thread === null ? "" : String(event.thread),
114
+ MUSTER_CHANNEL: event.channel ?? "",
115
+ MUSTER_EVENT: String(event.seq),
116
+ MUSTER_EVENT_TYPE: event.type,
117
+ MUSTER_ATTEMPT: String(context.attempt)
118
+ };
119
+ if (watcher.as !== null) env$1.MUSTER_PROFILE = watcher.as;
120
+ const where = board$1.backend.where;
121
+ if (board$1.backend.kind === "file" && where !== ":memory:") {
122
+ env$1.MUSTER_DIR = dirname(where);
123
+ env$1.MUSTER_BOARD = basename(where, ".db");
124
+ }
125
+ return env$1;
126
+ }
127
+ const wordsOf = (argv, context) => {
128
+ const words = typeof argv === "function" ? argv(context) : argv;
129
+ if (!Array.isArray(words) || words.length === 0 || !words.every((word) => typeof word === "string")) throw new Error("A command is a list of words, the first the program to run.");
130
+ return words;
131
+ };
132
+ /**
133
+ * A watcher's `run` that starts a command, the way to wake an agent: `command(['./wake.sh'])`, or
134
+ * `command(({ event }) => ['./wake.sh', String(event.thread)])`. It is woken with a pointer in its
135
+ * environment (`MUSTER_THREAD`, `MUSTER_EVENT`, ...) and nothing else of this process's but what `env`
136
+ * names. Exit 0 is delivered; anything else is a failed try. At the watcher's timeout its process group
137
+ * is stopped.
138
+ */
139
+ function command(argv, options = {}) {
140
+ const grace = options.grace ?? 5e3;
141
+ return async (context) => {
142
+ const env$1 = watcherEnv(pointer(context), options.env ?? []);
143
+ const named = new Set(options.env ?? []);
144
+ const elsewhere = [
145
+ "MUSTER_URL",
146
+ "MUSTER_INSECURE_HTTP",
147
+ ...pointer(context).MUSTER_DIR === void 0 ? ["MUSTER_DIR", "MUSTER_BOARD"] : []
148
+ ];
149
+ for (const name of elsewhere) if (!named.has(name)) delete env$1[name];
150
+ if (options.gate !== void 0) {
151
+ if (gateSaysNo((await run(wordsOf(options.gate, context), env$1, context.signal, grace, "answer")).stdout)) return;
152
+ }
153
+ const words = wordsOf(argv, context);
154
+ const ended = await run(words, env$1, context.signal, grace, "wake");
155
+ if (ended.code === 0) return;
156
+ const why = ended.code === null ? `killed by ${ended.signal ?? "a signal"}` : `exit ${ended.code}`;
157
+ throw Object.assign(/* @__PURE__ */ new Error(`${words[0]} ended with ${why}`), { why });
158
+ };
159
+ }
160
+
161
+ //#endregion
162
+ //#region src/sync/providers.ts
163
+ const hmac = (secret, body) => createHmac("sha256", secret).update(body).digest("hex");
164
+ const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
165
+ const bad = () => new Failure("unauthorized", "bad signature");
166
+ const slug = (text) => text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "run";
167
+ const CONTROL = /[\u0000-\u001f\u007f]+/g;
168
+ /** The most labels and assignees a thread is filed under: a message holds 64 labels, and its own come too. */
169
+ const MOST_FILED = 40;
170
+ /**
171
+ * A platform's names (its labels, an item's assignees) as board labels under a prefix:
172
+ * `tag.needs-review=needs review`. The key is the name cut down to what a label key may hold, the prefix
173
+ * included; the value is the name in lowercase, so a filter written once matches however it was typed
174
+ * there. A name with nothing a key can hold makes no label. Two names that make one key are one label,
175
+ * the one that sorts first, so what a thread carries doesn't turn on the order a platform listed them in.
176
+ */
177
+ function filed(prefix, names) {
178
+ const out = /* @__PURE__ */ new Map();
179
+ for (const name of names.filter((each) => typeof each === "string").sort()) {
180
+ const key = name.toLowerCase().replace(/[^a-z0-9_.]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64 - prefix.length);
181
+ const value = name.replace(CONTROL, " ").trim().toLowerCase().slice(0, 256);
182
+ if (key && value && !out.has(prefix + key)) out.set(prefix + key, value);
183
+ }
184
+ return [...out];
185
+ }
186
+ /** What an item is filed under, tags before assignees, up to the most a thread takes. */
187
+ const filedUnder = (tags, assignees) => Object.fromEntries([...filed("tag.", tags), ...filed("assignee.", assignees)].slice(0, MOST_FILED));
188
+ async function send(fetcher, url, init) {
189
+ const response = await fetcher(url, {
190
+ signal: AbortSignal.timeout(SEND_MS),
191
+ ...init
192
+ });
193
+ const body = await response.json().catch(() => ({}));
194
+ if (!response.ok) throw new Failure(`platform_${response.status}`, `The platform answered ${response.status}.`);
195
+ return body;
196
+ }
197
+ /** GitHub catch-up reads at most this many pages of 100 of each list per repo. */
198
+ const GITHUB_CATCHUP_PAGES = 10;
199
+ /** Past a catch-up's page cap, how many more pages it reads while all of it changed at one time. */
200
+ const CATCHUP_EXTRA_PAGES = 5;
201
+ /** Of several lists cut short, the next catch-up starts where the one read least far got to. */
202
+ const soonest = (cuts) => {
203
+ const first = [...cuts].sort((a, b) => Date.parse(a.resume) - Date.parse(b.resume))[0];
204
+ const skipped = cuts.flatMap((cut) => cut.skipped ? [cut.skipped] : []);
205
+ return {
206
+ resume: first.resume,
207
+ ...skipped.length ? { skipped: skipped.sort()[0] } : {}
208
+ };
209
+ };
210
+ const newestOf = (times) => Math.max(...times.filter((time) => !Number.isNaN(time)));
211
+ /**
212
+ * Where the next catch-up starts after one cut short, given when the changes it read were made. It goes back to
213
+ * the newest of them, so others made at that same time are read again, not skipped. Unless that is no later than
214
+ * where this one started: then so many changed at one time that reading them again would never move on, so it
215
+ * goes past that time and says so (`skipped`). A platform whose `since` takes what changed at that time
216
+ * (`inclusive`) has times to the second (`step`).
217
+ */
218
+ function cutShort(times, since, inclusive, step) {
219
+ const newest = newestOf(times);
220
+ const again = inclusive ? newest : newest - 1;
221
+ if (again > Date.parse(since)) return { resume: new Date(again).toISOString() };
222
+ return {
223
+ resume: new Date(newest + (inclusive ? step : 0)).toISOString(),
224
+ skipped: new Date(newest).toISOString()
225
+ };
226
+ }
227
+ /**
228
+ * GitHub: issues, pull requests and their comments come in as threads. Nothing goes back unless a repo mirrors.
229
+ * `token` is one that may comment, needed only where a repo mirrors; `appId` and `appKey` name a GitHub App
230
+ * to comment as instead.
231
+ */
232
+ const github = (options) => {
233
+ if (options.appId === void 0 !== (options.appKey === void 0)) throw misuse("invalid_sync", "A github sync needs \"appId\" and \"appKey\" together: the App's ID and its private key.");
234
+ return declared("github", options, githubWith, ["appId", "appKey"]);
235
+ };
236
+ /** How long before an App's token runs out a new one is made: no request goes out with one about to end. */
237
+ const APP_TOKEN_MARGIN_MS = 5 * 6e4;
238
+ function githubWith(options) {
239
+ const api = options.api ?? "https://api.github.com";
240
+ let app;
241
+ if (options.appId !== void 0 && options.appKey !== void 0) try {
242
+ app = githubApp({
243
+ GITHUB_APP_ID: options.appId,
244
+ [options.appKey.includes("-----BEGIN") ? "GITHUB_APP_PRIVATE_KEY" : "GITHUB_APP_KEY_FILE"]: options.appKey
245
+ });
246
+ } catch (error) {
247
+ throw new Failure("invalid_config", `A github sync's App can't be used: ${error.message}`, { hint: "\"appId\" is the App's numeric ID, and \"appKey\" its private key or the path to it." });
248
+ }
249
+ /**
250
+ * The App's token for each repository, kept until it is about to run out, and asked for once however many
251
+ * requests wait on it. One that couldn't be made is asked for again by the next request.
252
+ */
253
+ const tokens = /* @__PURE__ */ new Map();
254
+ const mint$1 = (repo, fetcher, now) => {
255
+ const [owner, name] = repo.split("/");
256
+ const to = options.repos[repo];
257
+ const pulls = typeof to === "string" || typeof to === "object" && to.pulls !== void 0;
258
+ const made = installationToken(app, {
259
+ owner,
260
+ name,
261
+ slug: repo
262
+ }, {
263
+ issues: "write",
264
+ metadata: "read",
265
+ ...pulls ? { pull_requests: "write" } : {}
266
+ }, {
267
+ api,
268
+ fetch: fetcher,
269
+ now
270
+ });
271
+ tokens.set(repo, made);
272
+ made.catch(() => tokens.get(repo) === made && tokens.delete(repo));
273
+ return made;
274
+ };
275
+ /** What a request to `repo` is signed with: the App's token for it when there is an App, or else `token`. */
276
+ const bearer = async (repo, fetcher) => {
277
+ if (!app) return `Bearer ${options.token}`;
278
+ const now = (options.now ?? Date.now)();
279
+ const held = tokens.get(repo) ?? mint$1(repo, fetcher, now);
280
+ let token = await held;
281
+ if (Date.parse(token.expiresAt) - now < APP_TOKEN_MARGIN_MS) token = await (tokens.get(repo) === held ? mint$1(repo, fetcher, now) : tokens.get(repo));
282
+ return `Bearer ${token.token}`;
283
+ };
284
+ const named = (message, text) => withLines(text, message.attachments.map((file$1) => noteOut(`${file$1.name} (${sizeOf(file$1.size)})`, "GitHub takes no uploads, it is on the board")));
285
+ /**
286
+ * An issue's or a pull request's labels and assignees, as GitHub lists them now. Every event about one
287
+ * carries both whole, so the thread is made to say the same: `owns` is each list the item came with.
288
+ */
289
+ const filing = (item) => {
290
+ const names = (list, field) => Array.isArray(list) ? list.map((each) => each?.[field]) : [];
291
+ return {
292
+ labels: filedUnder(names(item.labels, "name"), names(item.assignees, "login")),
293
+ owns: [...Array.isArray(item.labels) ? ["tag."] : [], ...Array.isArray(item.assignees) ? ["assignee."] : []]
294
+ };
295
+ };
296
+ /** An issue or pull request as a thread's first message, written by whoever opened it, in the state it is in now. */
297
+ const rootOf = (repo, item, isPull, id) => {
298
+ const thread = `${repo}#${item.number}`;
299
+ const opener = item.user?.login;
300
+ const merged = Boolean(item.merged || item.merged_at || item.pull_request?.merged_at);
301
+ return {
302
+ id,
303
+ author: String(opener ?? "unknown"),
304
+ place: `${repo}|${isPull ? "pulls" : "issues"}`,
305
+ self: options.bot !== void 0 && opener === options.bot,
306
+ kind: "root",
307
+ thread,
308
+ external: thread,
309
+ text: `${item.title ?? ""}\n\n${item.body ?? ""}`.trim(),
310
+ labels: {
311
+ kind: isPull ? "pr" : "issue",
312
+ state: item.state === "closed" ? merged ? "merged" : "closed" : "open",
313
+ ref: thread,
314
+ ...filing(item).labels
315
+ }
316
+ };
317
+ };
318
+ const mapping = (place) => {
319
+ const [repo, kind] = place.split("|");
320
+ return {
321
+ repo,
322
+ kind,
323
+ to: options.repos[repo]
324
+ };
325
+ };
326
+ return {
327
+ type: "github",
328
+ verify({ headers, body }) {
329
+ if (!same(headers["x-hub-signature-256"] ?? "", `sha256=${hmac(options.secret, body)}`)) throw bad();
330
+ },
331
+ parse({ headers, body }) {
332
+ const payload = JSON.parse(body);
333
+ const kind = headers["x-github-event"];
334
+ const delivery = `gh:${hmac("id", body).slice(0, 32)}`;
335
+ const repo = payload.repository?.full_name;
336
+ if (!repo) return [];
337
+ const self = options.bot !== void 0 && payload.sender?.login === options.bot;
338
+ const author = String(payload.sender?.login ?? "unknown");
339
+ const item = payload.issue ?? payload.pull_request;
340
+ const isPull = payload.pull_request !== void 0 || payload.issue?.pull_request !== void 0;
341
+ const place = `${repo}|${isPull ? "pulls" : "issues"}`;
342
+ const thread = item ? `${repo}#${item.number}` : "";
343
+ const base = {
344
+ id: delivery,
345
+ author,
346
+ place,
347
+ self
348
+ };
349
+ if ((kind === "issues" || kind === "pull_request") && payload.action === "opened") return [{
350
+ ...base,
351
+ kind: "root",
352
+ thread,
353
+ external: thread,
354
+ text: `${item.title}\n\n${item.body ?? ""}`.trim(),
355
+ labels: {
356
+ kind: isPull ? "pr" : "issue",
357
+ state: "open",
358
+ ref: thread,
359
+ ...filing(item).labels
360
+ }
361
+ }];
362
+ const withRoot = (events) => {
363
+ if (!item) return events;
364
+ const { author: opener, text, labels } = rootOf(repo, item, isPull, "");
365
+ return events.map((event) => ({
366
+ ...event,
367
+ parent: {
368
+ author: opener,
369
+ text: text ?? "",
370
+ labels: labels ?? {}
371
+ }
372
+ }));
373
+ };
374
+ if ((kind === "issues" || kind === "pull_request") && [
375
+ "labeled",
376
+ "unlabeled",
377
+ "assigned",
378
+ "unassigned"
379
+ ].includes(payload.action)) return withRoot([{
380
+ ...base,
381
+ kind: "labels",
382
+ thread,
383
+ external: delivery,
384
+ ...filing(item)
385
+ }]);
386
+ if ((kind === "issues" || kind === "pull_request") && (payload.action === "closed" || payload.action === "reopened")) return [{
387
+ ...base,
388
+ kind: "labels",
389
+ thread,
390
+ external: `${delivery}`,
391
+ labels: { state: payload.action === "reopened" ? "open" : item.merged ? "merged" : "closed" }
392
+ }];
393
+ if (kind === "issue_comment" && payload.action === "edited") return [{
394
+ ...base,
395
+ kind: "edit",
396
+ thread,
397
+ external: `comment:${payload.comment.id}`,
398
+ text: String(payload.comment.body ?? "")
399
+ }];
400
+ if (kind === "issue_comment" && payload.action === "deleted") return [{
401
+ ...base,
402
+ kind: "delete",
403
+ thread,
404
+ external: `comment:${payload.comment.id}`
405
+ }];
406
+ if ((kind === "issues" || kind === "pull_request") && payload.action === "edited") return [{
407
+ ...base,
408
+ kind: "edit",
409
+ thread,
410
+ external: thread,
411
+ text: `${item.title}\n\n${item.body ?? ""}`.trim()
412
+ }];
413
+ if (kind === "issue_comment" && payload.action === "created") return withRoot([{
414
+ ...base,
415
+ kind: "reply",
416
+ thread,
417
+ external: `comment:${payload.comment.id}`,
418
+ text: String(payload.comment.body ?? "")
419
+ }]);
420
+ if (kind === "pull_request_review" && payload.action === "submitted") {
421
+ const out = [{
422
+ ...base,
423
+ kind: "labels",
424
+ thread,
425
+ external: delivery,
426
+ labels: { review: String(payload.review.state).toLowerCase() }
427
+ }];
428
+ if (payload.review.body) out.push({
429
+ ...base,
430
+ id: `${delivery}:body`,
431
+ kind: "reply",
432
+ thread,
433
+ external: `review:${payload.review.id}`,
434
+ text: String(payload.review.body)
435
+ });
436
+ return withRoot(out);
437
+ }
438
+ if (kind === "workflow_run" && payload.action === "completed") return (payload.workflow_run.pull_requests ?? []).map((pull, index) => ({
439
+ ...base,
440
+ id: `${delivery}:${index}`,
441
+ place: `${repo}|pulls`,
442
+ kind: "labels",
443
+ thread: `${repo}#${pull.number}`,
444
+ external: `${delivery}:${index}`,
445
+ labels: { [`ci.${slug(String(payload.workflow_run.name ?? "run"))}`]: String(payload.workflow_run.conclusion ?? "unknown") }
446
+ }));
447
+ return [];
448
+ },
449
+ channelFor(place) {
450
+ const { kind, to } = mapping(place);
451
+ const channel = typeof to === "string" ? to : to?.[kind];
452
+ return channel ? channelPath(channel) : null;
453
+ },
454
+ placeFor(channel) {
455
+ for (const [repo, to] of Object.entries(options.repos)) if (typeof to === "object" && to.mirror === true && to.issues === channel) return `${repo}|issues`;
456
+ return null;
457
+ },
458
+ async update(external, text, place, fetcher) {
459
+ if (!external.startsWith("comment:")) return;
460
+ const repo = place.split("|")[0];
461
+ await send(fetcher, `${api}/repos/${repo}/issues/comments/${external.slice(8)}`, {
462
+ method: "PATCH",
463
+ headers: {
464
+ authorization: await bearer(repo, fetcher),
465
+ accept: "application/vnd.github+json",
466
+ "content-type": "application/json",
467
+ "user-agent": "muster"
468
+ },
469
+ body: JSON.stringify({ body: text })
470
+ });
471
+ },
472
+ async remove(external, place, fetcher) {
473
+ if (!external.startsWith("comment:")) return;
474
+ const repo = place.split("|")[0];
475
+ await fetcher(`${api}/repos/${repo}/issues/comments/${external.slice(8)}`, {
476
+ method: "DELETE",
477
+ headers: {
478
+ authorization: await bearer(repo, fetcher),
479
+ accept: "application/vnd.github+json",
480
+ "user-agent": "muster"
481
+ }
482
+ });
483
+ },
484
+ async catchUp(since, fetcher) {
485
+ if (!options.token && !app) return [];
486
+ const out = [];
487
+ const cuts = [];
488
+ const when = (list) => list.map((each) => Date.parse(String(each.updated_at)));
489
+ /**
490
+ * A list oldest change first, up to the page cap. Each page after the first is asked for from the newest change
491
+ * read so far, not by its number: something changed during the read moves to the end, not past a page already
492
+ * read. Only a whole page changed in the same second goes by number, and that may run a few pages past the cap.
493
+ */
494
+ const read = async (repo, path) => {
495
+ const headers = {
496
+ authorization: await bearer(repo, fetcher),
497
+ accept: "application/vnd.github+json",
498
+ "user-agent": "muster"
499
+ };
500
+ const out$1 = [];
501
+ let from = since;
502
+ let page = 1;
503
+ for (let asked = 1; asked <= GITHUB_CATCHUP_PAGES + CATCHUP_EXTRA_PAGES; asked++) {
504
+ if (asked > GITHUB_CATCHUP_PAGES && page === 1) break;
505
+ const got = await send(fetcher, `${api}/repos/${repo}/${path}since=${encodeURIComponent(from)}&sort=updated&direction=asc&per_page=100&page=${page}`, { headers });
506
+ if (!Array.isArray(got)) throw new Failure("platform_refused", "GitHub did not answer with a list.");
507
+ out$1.push(...got);
508
+ if (got.length < 100) return out$1;
509
+ const newest = newestOf(when(got));
510
+ if (!Number.isFinite(newest)) throw new Failure("platform_refused", "GitHub listed changes without when they were made.");
511
+ if (newest > Date.parse(from)) {
512
+ from = new Date(newest).toISOString();
513
+ page = 1;
514
+ } else page++;
515
+ }
516
+ cuts.push(cutShort(when(out$1), since, true, 1e3));
517
+ return out$1;
518
+ };
519
+ for (const repo of Object.keys(options.repos)) {
520
+ const items = await read(repo, "issues?state=all&");
521
+ const parents = /* @__PURE__ */ new Map();
522
+ for (const item of items) {
523
+ const root = rootOf(repo, item, item.pull_request !== void 0, `catchup:issue:${repo}#${item.number}`);
524
+ out.push(root);
525
+ parents.set(String(item.number), {
526
+ author: root.author,
527
+ text: root.text ?? "",
528
+ labels: root.labels ?? {}
529
+ });
530
+ const filedNow = filing(item);
531
+ out.push({
532
+ ...root,
533
+ author: "",
534
+ self: false,
535
+ ...item.updated_at ? { at: String(item.updated_at) } : {},
536
+ id: `catchup:state:${repo}#${item.number}:${item.updated_at ?? ""}`,
537
+ kind: "labels",
538
+ external: `catchup:state:${repo}#${item.number}:${item.updated_at ?? ""}`,
539
+ labels: {
540
+ state: root.labels.state,
541
+ ...filedNow.labels
542
+ },
543
+ owns: filedNow.owns
544
+ });
545
+ }
546
+ const comments = await read(repo, "issues/comments?");
547
+ for (const comment of comments) {
548
+ const number = String(comment.issue_url ?? "").split("/").pop();
549
+ const isPull = String(comment.html_url ?? "").includes("/pull/");
550
+ const parent = parents.get(number ?? "");
551
+ out.push({
552
+ id: `catchup:comment:${comment.id}`,
553
+ author: String(comment.user?.login ?? "unknown"),
554
+ place: `${repo}|${isPull ? "pulls" : "issues"}`,
555
+ self: options.bot !== void 0 && comment.user?.login === options.bot,
556
+ kind: "reply",
557
+ thread: `${repo}#${number}`,
558
+ external: `comment:${comment.id}`,
559
+ text: String(comment.body ?? ""),
560
+ ...parent ? { parent } : {}
561
+ });
562
+ }
563
+ }
564
+ return cuts.length ? {
565
+ events: out,
566
+ ...soonest(cuts)
567
+ } : out;
568
+ },
569
+ mirrors(place) {
570
+ const { to } = mapping(place);
571
+ return typeof to === "object" && to.mirror === true && (options.token !== void 0 || app !== void 0);
572
+ },
573
+ async deliver(message, target, fetcher) {
574
+ const headersFor = async (repo$1) => ({
575
+ authorization: await bearer(repo$1, fetcher),
576
+ accept: "application/vnd.github+json",
577
+ "content-type": "application/json",
578
+ "user-agent": "muster"
579
+ });
580
+ if (target.threadExternal === null) {
581
+ const repo$1 = target.place.split("|")[0];
582
+ const headers = await headersFor(repo$1);
583
+ const [title, ...rest] = message.text.split("\n");
584
+ const made = await send(fetcher, `${api}/repos/${repo$1}/issues`, {
585
+ method: "POST",
586
+ headers,
587
+ body: JSON.stringify({
588
+ title: title.slice(0, 250),
589
+ body: named(message, rest.join("\n").trim())
590
+ })
591
+ });
592
+ return {
593
+ external: `${repo$1}#${made.number}`,
594
+ thread: `${repo$1}#${made.number}`,
595
+ labels: {
596
+ kind: "issue",
597
+ state: "open",
598
+ ref: `${repo$1}#${made.number}`
599
+ }
600
+ };
601
+ }
602
+ const [repo, number] = target.threadExternal.split("#");
603
+ return { external: `comment:${(await send(fetcher, `${api}/repos/${repo}/issues/${number}/comments`, {
604
+ method: "POST",
605
+ headers: await headersFor(repo),
606
+ body: JSON.stringify({ body: named(message, message.text) })
607
+ })).id}` };
608
+ }
609
+ };
610
+ }
611
+ /** Catch-up reads at most this many pages of each list, of this many each: Linear limits requests and their cost. */
612
+ const LINEAR_CATCHUP_PAGES = 10;
613
+ const LINEAR_CATCHUP_PAGE = 50;
614
+ /** Linear: issues and comments come in as threads, and board replies go back as comments. */
615
+ const linear = (options) => {
616
+ if (options.clientId === void 0 !== (options.clientSecret === void 0)) throw misuse("invalid_sync", "A linear sync needs \"clientId\" and \"clientSecret\" together: the OAuth application's own.");
617
+ return declared("linear", options, linearWith, [
618
+ "clientId",
619
+ "clientSecret",
620
+ "appSecret"
621
+ ]);
622
+ };
623
+ /** How often Linear is told an issue is still being worked on: a session with nothing new for 30 minutes goes stale. */
624
+ const LINEAR_WORKING_TTL_MS = 25 * 6e4;
625
+ /**
626
+ * What an app's token may do unless the module says: read what comes in, and write the comments and issues that go
627
+ * back. Anything else that asks for a token for the same app asks with these: a token asked for with other scopes ends
628
+ * the app's earlier ones, the sync's included.
629
+ */
630
+ const LINEAR_SCOPES = ["read", "write"];
631
+ function linearWith(options) {
632
+ const team = (place) => options.teams[place];
633
+ const api = options.api ?? "https://api.linear.app/graphql";
634
+ const app = options.clientId !== void 0 && options.clientSecret !== void 0 ? {
635
+ id: options.clientId,
636
+ secret: options.clientSecret
637
+ } : void 0;
638
+ /**
639
+ * The app's own user in the workspace, once Linear has said who it is. What an agent session says as it ends
640
+ * is a comment by that user, which the board has no ID for: so with sessions on, a comment by it isn't brought in.
641
+ */
642
+ let appUser;
643
+ const own = (author) => options.bot !== void 0 && author === options.bot || appUser !== void 0 && author === appUser;
644
+ /** Whether the sync has something to send and read with: a token, or an app to ask for one. */
645
+ const signed = options.token !== void 0 || app !== void 0;
646
+ /**
647
+ * The app's own token: asked for once, kept until it is about to run out (thirty days, and Linear gives no
648
+ * refresh token, so the next one is asked for the same way), and asked for again after one Linear refused.
649
+ */
650
+ let appToken;
651
+ const askToken = (fetcher) => {
652
+ const now = (options.now ?? Date.now)();
653
+ const asked = send(fetcher, new URL("/oauth/token", api).href, {
654
+ method: "POST",
655
+ headers: { "content-type": "application/x-www-form-urlencoded" },
656
+ body: new URLSearchParams({
657
+ grant_type: "client_credentials",
658
+ scope: (options.scopes ?? LINEAR_SCOPES).join(","),
659
+ client_id: app.id,
660
+ client_secret: app.secret
661
+ }).toString()
662
+ }).then((answer) => {
663
+ if (typeof answer?.access_token !== "string" || !answer.access_token) throw new Failure("platform_refused", `Linear made no token for the app${typeof answer?.error_description === "string" ? `: ${answer.error_description.slice(0, 200)}` : ""}.`);
664
+ return {
665
+ token: answer.access_token,
666
+ until: now + (Number(answer.expires_in) || 0) * 1e3
667
+ };
668
+ });
669
+ appToken = asked;
670
+ asked.catch(() => appToken === asked && (appToken = void 0));
671
+ return asked;
672
+ };
673
+ /**
674
+ * What an issue is filed under, as the webhook says it: its labels, its assignee, its priority and its
675
+ * project. Linear leaves an empty assignee or project out rather than sending `null`, so one that is
676
+ * missing with no ID either is empty, and one named by its ID alone is left as it was. Its labels are
677
+ * the whole list when the payload has one, and none when it lists no label IDs.
678
+ *
679
+ * How a payload is read here, and the profile-handle pattern, follow `propertiesOf` and `handleOf` in
680
+ * @vercel/board's `sync/linear.ts` (Apache-2.0, Copyright Vercel, Inc.).
681
+ */
682
+ const filing = (data) => {
683
+ const labels = {};
684
+ const unset = [];
685
+ const owns = [];
686
+ const tags = Array.isArray(data.labels) ? data.labels.map((each) => each?.name) : Array.isArray(data.labelIds) && data.labelIds.length === 0 ? [] : null;
687
+ if (tags) owns.push("tag.");
688
+ const handle = data.assignee ? /\/profiles\/([^/?#]+)/.exec(String(data.assignee.url ?? ""))?.[1] ?? data.assignee.displayName ?? data.assignee.name : null;
689
+ if (data.assignee || !data.assigneeId) owns.push("assignee.");
690
+ Object.assign(labels, filedUnder(tags ?? [], handle ? [handle] : []));
691
+ const priority = [
692
+ "",
693
+ "urgent",
694
+ "high",
695
+ "medium",
696
+ "low"
697
+ ][Number(data.priority)];
698
+ if (priority) labels.priority = priority;
699
+ else if (data.priority === 0) unset.push("priority");
700
+ const project = typeof data.project?.name === "string" ? data.project.name.replace(CONTROL, " ").trim().toLowerCase().slice(0, 256) : "";
701
+ if (project) labels.project = project;
702
+ else if (!data.project && !data.projectId) unset.push("project");
703
+ return {
704
+ labels,
705
+ unset,
706
+ owns
707
+ };
708
+ };
709
+ /** An issue as the API lists it, in the shape its webhook has: its labels are a list there, not a page of one. */
710
+ const listed = (issue) => Array.isArray(issue.labels?.nodes) ? {
711
+ ...issue,
712
+ labels: issue.labels.nodes
713
+ } : issue;
714
+ let organization;
715
+ const authorization = async (fetcher) => {
716
+ if (app) {
717
+ const held = appToken;
718
+ let got = await (held ?? askToken(fetcher));
719
+ if (got.until - (options.now ?? Date.now)() < APP_TOKEN_MARGIN_MS) got = await (appToken === held || !appToken ? askToken(fetcher) : appToken);
720
+ return `Bearer ${got.token}`;
721
+ }
722
+ const token = options.token;
723
+ return token.startsWith("lin_api_") || /^bearer /i.test(token) ? token : `Bearer ${token}`;
724
+ };
725
+ /** Files uploaded to Linear, as the markdown links its text carries. Links anywhere else are only text. */
726
+ const uploads = (text) => {
727
+ const found = [...String(text ?? "").matchAll(/!?\[([^\]\n]*)\]\((https:\/\/uploads\.linear\.app\/[^\s)]+)\)/g)].map((match) => ({
728
+ url: match[2],
729
+ name: match[1] || match[2].split("/").pop()
730
+ }));
731
+ const once = found.filter((file$1, index) => found.findIndex((other) => other.url === file$1.url) === index);
732
+ return once.length ? once : void 0;
733
+ };
734
+ const postAs = async (query, variables, fetcher) => {
735
+ const ask = async () => send(fetcher, api, {
736
+ method: "POST",
737
+ headers: {
738
+ authorization: await authorization(fetcher),
739
+ "content-type": "application/json"
740
+ },
741
+ body: JSON.stringify({
742
+ query,
743
+ variables
744
+ })
745
+ });
746
+ try {
747
+ return await ask();
748
+ } catch (error) {
749
+ if (!app || !(error instanceof Failure) || error.reason !== "platform_401") throw error;
750
+ appToken = void 0;
751
+ return ask();
752
+ }
753
+ };
754
+ /** An issue as a thread's first message, as its webhook would have brought it, in the state it is in now. */
755
+ const rootOf = (issue, id) => {
756
+ const thread = `issue:${issue.id}`;
757
+ const author = String(issue.creator?.id ?? "unknown");
758
+ return {
759
+ id,
760
+ author,
761
+ place: String(issue.team?.key ?? ""),
762
+ self: own(author),
763
+ kind: "root",
764
+ thread,
765
+ external: thread,
766
+ text: `${issue.title ?? ""}\n\n${issue.description ?? ""}`.trim(),
767
+ labels: {
768
+ kind: "issue",
769
+ ref: String(issue.identifier ?? ""),
770
+ ...issue.state?.name ? { state: slug(String(issue.state.name)) } : {},
771
+ ...filing(listed(issue)).labels
772
+ },
773
+ ...uploads(issue.description) ? { files: uploads(issue.description) } : {}
774
+ };
775
+ };
776
+ return {
777
+ type: "linear",
778
+ verify({ headers, body }) {
779
+ const signature = headers["linear-signature"] ?? "";
780
+ if (!same(signature, hmac(options.secret, body)) && !(options.appSecret !== void 0 && same(signature, hmac(options.appSecret, body)))) throw bad();
781
+ },
782
+ ...options.agent && app ? {
783
+ workingTtl: LINEAR_WORKING_TTL_MS,
784
+ async working(target, step, now, fetcher) {
785
+ const kept = now.state ?? {};
786
+ if (typeof kept.user === "string") appUser = kept.user;
787
+ if (appUser === void 0) {
788
+ const who = (await postAs("{ viewer { id } }", void 0, fetcher))?.data?.viewer?.id;
789
+ if (typeof who === "string" && who) appUser = who;
790
+ }
791
+ const said = async (session$1) => {
792
+ return (await postAs("mutation($input: AgentActivityCreateInput!) { agentActivityCreate(input: $input) { success } }", { input: {
793
+ agentSessionId: session$1,
794
+ content: {
795
+ type: step === "end" ? "response" : "thought",
796
+ body: now.text
797
+ },
798
+ ...step === "end" ? {} : { ephemeral: true }
799
+ } }, fetcher))?.data?.agentActivityCreate?.success === true;
800
+ };
801
+ const state = (session$1) => ({
802
+ ...session$1 ? { session: session$1 } : {},
803
+ ...appUser ? { user: appUser } : {}
804
+ });
805
+ let session = typeof kept.session === "string" ? kept.session : void 0;
806
+ if (session && await said(session)) return state(session);
807
+ if (step === "end" && !session) return state();
808
+ if (session && step !== "start") throw new Failure("platform_refused", "Linear did not take the session's activity.");
809
+ const opened = await postAs("mutation($input: AgentSessionCreateOnIssue!) { agentSessionCreateOnIssue(input: $input) { success agentSession { id } } }", { input: { issueId: target.threadExternal.replace(/^issue:/, "") } }, fetcher);
810
+ session = opened?.data?.agentSessionCreateOnIssue?.agentSession?.id;
811
+ if (typeof session !== "string" || !session) {
812
+ const why = opened?.errors?.[0]?.extensions?.userPresentableMessage ?? opened?.errors?.[0]?.message;
813
+ throw new Failure("platform_refused", `Linear opened no agent session${typeof why === "string" ? `: ${why.slice(0, 200)}` : "."}`);
814
+ }
815
+ if (!await said(session)) throw new Failure("platform_refused", "Linear did not take the session's activity.");
816
+ return state(session);
817
+ }
818
+ } : {},
819
+ parse({ headers, body }) {
820
+ if (!same(headers["linear-signature"] ?? "", hmac(options.secret, body))) return [];
821
+ const payload = JSON.parse(body);
822
+ const data = payload.data ?? {};
823
+ const delivery = `lin:${hmac("id", body).slice(0, 32)}`;
824
+ const author = String(data.userId ?? data.user?.id ?? payload.actor?.id ?? "unknown");
825
+ const self = own(author);
826
+ const updated = typeof data.updatedAt === "string" ? { updated: data.updatedAt } : {};
827
+ if (payload.type === "Issue" && payload.action === "create") {
828
+ const thread = `issue:${data.id}`;
829
+ return [{
830
+ id: delivery,
831
+ author: String(data.creatorId ?? author),
832
+ place: String(data.team?.key ?? ""),
833
+ self,
834
+ kind: "root",
835
+ thread,
836
+ external: thread,
837
+ text: `${data.title}\n\n${data.description ?? ""}`.trim(),
838
+ labels: {
839
+ kind: "issue",
840
+ ref: String(data.identifier ?? ""),
841
+ ...data.state?.name ? { state: slug(String(data.state.name)) } : {},
842
+ ...filing(data).labels
843
+ },
844
+ ...uploads(data.description) ? { files: uploads(data.description) } : {}
845
+ }];
846
+ }
847
+ if (payload.type === "Issue" && payload.action === "update") {
848
+ const filed$1 = filing(data);
849
+ const opener = typeof data.title === "string" ? rootOf({
850
+ ...data,
851
+ creator: data.creator ?? (data.creatorId ? { id: data.creatorId } : void 0)
852
+ }, "") : null;
853
+ const parent = opener ? { parent: {
854
+ author: opener.author,
855
+ text: opener.text ?? "",
856
+ labels: opener.labels ?? {}
857
+ } } : {};
858
+ const labelled = {
859
+ id: delivery,
860
+ author,
861
+ place: String(data.team?.key ?? ""),
862
+ self,
863
+ kind: "labels",
864
+ thread: `issue:${data.id}`,
865
+ external: delivery,
866
+ ...filed$1,
867
+ labels: {
868
+ ...data.state?.name ? { state: slug(String(data.state.name)) } : {},
869
+ ...filed$1.labels
870
+ },
871
+ ...parent,
872
+ ...updated
873
+ };
874
+ const from = payload.updatedFrom ?? {};
875
+ if (!(typeof data.title === "string" && ("title" in from || "description" in from))) return [labelled];
876
+ return [labelled, {
877
+ id: `${delivery}:text`,
878
+ author,
879
+ place: labelled.place,
880
+ self,
881
+ kind: "edit",
882
+ thread: `issue:${data.id}`,
883
+ external: `issue:${data.id}`,
884
+ text: `${data.title}\n\n${data.description ?? ""}`.trim(),
885
+ ...updated
886
+ }];
887
+ }
888
+ if (payload.type === "Comment" && (payload.action === "update" || payload.action === "remove")) return [{
889
+ id: delivery,
890
+ author,
891
+ place: String(data.issue?.team?.key ?? data.team?.key ?? ""),
892
+ self,
893
+ kind: payload.action === "remove" ? "delete" : "edit",
894
+ thread: `issue:${data.issueId ?? data.issue?.id}`,
895
+ external: `comment:${data.id}`,
896
+ ...payload.action === "update" ? {
897
+ text: String(data.body ?? ""),
898
+ ...updated
899
+ } : {}
900
+ }];
901
+ if (payload.type === "Comment" && payload.action === "create") {
902
+ const issue = data.issue;
903
+ const parent = typeof issue?.title === "string" ? { parent: {
904
+ author: "",
905
+ text: issue.title.trim(),
906
+ labels: {
907
+ kind: "issue",
908
+ ...issue.identifier ? { ref: String(issue.identifier) } : {}
909
+ }
910
+ } } : {};
911
+ return [{
912
+ id: delivery,
913
+ author,
914
+ place: String(data.issue?.team?.key ?? data.team?.key ?? ""),
915
+ self,
916
+ kind: "reply",
917
+ thread: `issue:${data.issueId ?? data.issue?.id}`,
918
+ external: `comment:${data.id}`,
919
+ text: String(data.body ?? ""),
920
+ ...uploads(data.body) ? { files: uploads(data.body) } : {},
921
+ ...parent,
922
+ ...updated
923
+ }];
924
+ }
925
+ return [];
926
+ },
927
+ channelFor(place) {
928
+ const to = team(place);
929
+ const channel = typeof to === "string" ? to : to?.channel;
930
+ return channel ? channelPath(channel) : null;
931
+ },
932
+ placeFor(channel) {
933
+ for (const [key, to] of Object.entries(options.teams)) if ((typeof to === "string" ? to : to.channel) === channel) return key;
934
+ return null;
935
+ },
936
+ mirrors(place) {
937
+ const to = team(place);
938
+ return signed && to !== void 0 && !(typeof to === "object" && to.mirror === false);
939
+ },
940
+ async download(file$1, fetcher, limit) {
941
+ if (!signed) throw refused("no token to fetch it with");
942
+ organization ??= postAs("{ organization { id } }", void 0, fetcher).then((answer) => {
943
+ const id = answer?.data?.organization?.id;
944
+ if (typeof id !== "string" || !id) throw new Failure("platform_refused", "Linear did not say which workspace the key is for.");
945
+ return id;
946
+ });
947
+ const workspace = await organization.catch((error) => {
948
+ organization = void 0;
949
+ throw error;
950
+ });
951
+ if ((URL.canParse(file$1.url) ? new URL(file$1.url).pathname.split("/")[1] : void 0) !== workspace) throw refused("not an upload of this board's Linear workspace");
952
+ return fetchFile(fetcher, file$1.url, {
953
+ hosts: ["uploads.linear.app"],
954
+ headers: { authorization: await authorization(fetcher) },
955
+ limit
956
+ });
957
+ },
958
+ async catchUp(since, fetcher) {
959
+ if (!signed) return [];
960
+ const keys = Object.keys(options.teams);
961
+ if (keys.length === 0) return [];
962
+ const refused$1 = (field, answer) => new Failure("platform_refused", `Linear did not list ${field}: ${String(answer?.errors?.[0]?.message ?? "no data").slice(0, 200)}`);
963
+ /**
964
+ * Reads a list oldest change first, up to the page cap. A call that fails throws, and the board asks again
965
+ * from the same point. Issues sort that way; comments can't be sorted, and Linear lists them newest first,
966
+ * so they are read from the end backwards. Cut short, it says where the next catch-up starts: the newest
967
+ * change it read, less a millisecond, so one made in that same millisecond is read again, not skipped.
968
+ */
969
+ const read = async (field, nodes, filter) => {
970
+ const type = field === "issues" ? "IssueFilter" : "CommentFilter";
971
+ const list = async (variables, args, page) => {
972
+ const answer = await postAs(`query($filter: ${type}, $cursor: String) { ${field}(filter: $filter, ${args}) { nodes { ${nodes} } pageInfo { ${page} } } }`, variables, fetcher);
973
+ const got = answer?.data?.[field];
974
+ if (!got || !Array.isArray(got.nodes)) throw refused$1(field, answer);
975
+ return got;
976
+ };
977
+ const out$1 = [];
978
+ let cursor = null;
979
+ let more = false;
980
+ const when = (list$1) => list$1.map((node) => Date.parse(String(node.updatedAt)));
981
+ const from = Date.parse(filter.updatedAt.gt);
982
+ for (let page = 0; page < LINEAR_CATCHUP_PAGES + CATCHUP_EXTRA_PAGES; page++) {
983
+ if (page >= LINEAR_CATCHUP_PAGES && newestOf(when(out$1)) - 1 > from) break;
984
+ const got = field === "issues" ? await list({
985
+ filter,
986
+ cursor
987
+ }, `first: ${LINEAR_CATCHUP_PAGE}, after: $cursor, sort: [{ updatedAt: { order: Ascending } }]`, "hasNextPage endCursor") : await list({
988
+ filter,
989
+ cursor
990
+ }, `last: ${LINEAR_CATCHUP_PAGE}, before: $cursor, orderBy: updatedAt`, "hasPreviousPage startCursor");
991
+ out$1.push(...got.nodes);
992
+ const next = field === "issues" ? [got.pageInfo?.hasNextPage, got.pageInfo?.endCursor] : [got.pageInfo?.hasPreviousPage, got.pageInfo?.startCursor];
993
+ more = Boolean(next[0] && next[1]);
994
+ if (!more) break;
995
+ cursor = String(next[1]);
996
+ }
997
+ if (!more || out$1.length === 0) return { nodes: out$1 };
998
+ const times = out$1.map((node) => Date.parse(String(node.updatedAt))).filter((time) => !Number.isNaN(time));
999
+ if (times.length !== out$1.length) throw new Failure("platform_refused", `Linear listed ${field} without when they changed.`);
1000
+ if ((await list({
1001
+ filter: {
1002
+ ...filter,
1003
+ updatedAt: {
1004
+ gt: filter.updatedAt.gt,
1005
+ lt: new Date(Math.min(...times)).toISOString()
1006
+ }
1007
+ },
1008
+ cursor: null
1009
+ }, "first: 1", "hasNextPage")).nodes.length > 0) throw new Failure("platform_refused", `Linear did not list ${field} oldest first.`);
1010
+ return {
1011
+ nodes: out$1,
1012
+ cut: cutShort(times, filter.updatedAt.gt, false, 0)
1013
+ };
1014
+ };
1015
+ const issueFields = "id identifier title description creator { id } team { key } state { name } priority assignee { id name displayName url } project { name } labels { nodes { name } } updatedAt";
1016
+ const changed = { updatedAt: { gt: since } };
1017
+ const issues = await read("issues", issueFields, {
1018
+ ...changed,
1019
+ team: { key: { in: keys } }
1020
+ });
1021
+ const comments = await read("comments", `id body updatedAt user { id } issue { ${issueFields} }`, {
1022
+ ...changed,
1023
+ issue: { team: { key: { in: keys } } }
1024
+ });
1025
+ const out = [];
1026
+ for (const issue of issues.nodes) {
1027
+ const root = rootOf(issue, `catchup:issue:${issue.id}`);
1028
+ out.push(root);
1029
+ if (root.labels?.state) {
1030
+ const filedNow = filing(listed(issue));
1031
+ out.push({
1032
+ ...root,
1033
+ id: `catchup:state:${issue.id}:${issue.updatedAt ?? ""}`,
1034
+ author: "",
1035
+ self: false,
1036
+ ...issue.updatedAt ? {
1037
+ at: String(issue.updatedAt),
1038
+ updated: String(issue.updatedAt)
1039
+ } : {},
1040
+ kind: "labels",
1041
+ external: `catchup:state:${issue.id}:${issue.updatedAt ?? ""}`,
1042
+ ...filedNow,
1043
+ labels: {
1044
+ state: root.labels.state,
1045
+ ...filedNow.labels
1046
+ }
1047
+ });
1048
+ }
1049
+ }
1050
+ for (const comment of comments.nodes) {
1051
+ if (!comment.issue?.id) continue;
1052
+ const { author, text, labels, place } = rootOf(comment.issue, "");
1053
+ const by = String(comment.user?.id ?? "unknown");
1054
+ out.push({
1055
+ id: `catchup:comment:${comment.id}`,
1056
+ author: by,
1057
+ place,
1058
+ self: own(by),
1059
+ kind: "reply",
1060
+ thread: `issue:${comment.issue.id}`,
1061
+ external: `comment:${comment.id}`,
1062
+ text: String(comment.body ?? ""),
1063
+ parent: {
1064
+ author,
1065
+ text: text ?? "",
1066
+ labels: labels ?? {}
1067
+ },
1068
+ ...uploads(comment.body) ? { files: uploads(comment.body) } : {},
1069
+ ...comment.updatedAt ? { updated: String(comment.updatedAt) } : {}
1070
+ });
1071
+ }
1072
+ const cuts = [issues.cut, comments.cut].filter((cut) => cut !== void 0);
1073
+ return cuts.length ? {
1074
+ events: out,
1075
+ ...soonest(cuts)
1076
+ } : out;
1077
+ },
1078
+ async deliver(message, target, fetcher, read) {
1079
+ const post = (query, variables) => postAs(query, variables, fetcher);
1080
+ const lines = [];
1081
+ for (const file$1 of message.attachments) {
1082
+ const bytes = read(file$1.id);
1083
+ if (!bytes) {
1084
+ lines.push(noteOut(file$1.name, "the board no longer has it"));
1085
+ continue;
1086
+ }
1087
+ try {
1088
+ const upload = (await post("mutation($type: String!, $name: String!, $size: Int!) { fileUpload(contentType: $type, filename: $name, size: $size) { success uploadFile { uploadUrl assetUrl headers { key value } } } }", {
1089
+ type: file$1.type,
1090
+ name: file$1.name,
1091
+ size: bytes.length
1092
+ }))?.data?.fileUpload?.uploadFile;
1093
+ const to = URL.canParse(String(upload?.uploadUrl)) ? new URL(String(upload.uploadUrl)) : null;
1094
+ if (!to || to.protocol !== "https:" || to.hostname !== "storage.googleapis.com" || to.port !== "" || to.username !== "" || !String(upload.assetUrl).startsWith("https://uploads.linear.app/")) throw new Failure("platform_refused", "Linear gave no upload URL.");
1095
+ const headers = {
1096
+ "content-type": file$1.type,
1097
+ "cache-control": "public, max-age=31536000"
1098
+ };
1099
+ for (const { key, value } of upload.headers ?? []) if (/^(x-goog-[a-z0-9-]+|content-disposition)$/i.test(String(key))) headers[String(key).toLowerCase()] = String(value);
1100
+ const put = await fetcher(to.href, {
1101
+ method: "PUT",
1102
+ headers,
1103
+ body: new Uint8Array(bytes),
1104
+ redirect: "manual",
1105
+ signal: AbortSignal.timeout(SEND_MS)
1106
+ });
1107
+ if (!put.ok) throw new Failure(`platform_${put.status}`, `Linear's storage answered ${put.status}.`);
1108
+ lines.push(`${file$1.type.startsWith("image/") ? "!" : ""}[${file$1.name.replace(/[[\]\n]/g, "_")}](${upload.assetUrl})`);
1109
+ } catch {
1110
+ lines.push(noteOut(file$1.name, "Linear did not take it"));
1111
+ }
1112
+ }
1113
+ if (target.threadExternal === null) {
1114
+ const teamId = (await post("query($key: String!) { teams(filter: { key: { eq: $key } }) { nodes { id } } }", { key: target.place }))?.data?.teams?.nodes?.[0]?.id;
1115
+ if (!teamId) throw new Failure("platform_refused", `Linear has no team "${target.place}".`);
1116
+ const [title, ...rest] = message.text.split("\n");
1117
+ const created = (await post("mutation($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { id identifier state { name } } } }", { input: {
1118
+ teamId,
1119
+ title: title.slice(0, 250),
1120
+ description: withLines(rest.join("\n").trim(), lines)
1121
+ } }))?.data?.issueCreate?.issue;
1122
+ const issue = created?.id;
1123
+ if (!issue) throw new Failure("platform_refused", "Linear did not make the issue.");
1124
+ const labels = {
1125
+ kind: "issue",
1126
+ ...created.identifier ? { ref: String(created.identifier) } : {},
1127
+ ...created.state?.name ? { state: slug(String(created.state.name)) } : {}
1128
+ };
1129
+ return {
1130
+ external: `issue:${issue}`,
1131
+ thread: `issue:${issue}`,
1132
+ labels
1133
+ };
1134
+ }
1135
+ const id = (await post("mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { id } } }", { input: {
1136
+ issueId: target.threadExternal.replace(/^issue:/, ""),
1137
+ body: withLines(message.text, lines)
1138
+ } }))?.data?.commentCreate?.comment?.id;
1139
+ if (!id) throw new Failure("platform_refused", "Linear did not make the comment.");
1140
+ return { external: `comment:${id}` };
1141
+ }
1142
+ };
1143
+ }
1144
+ /** How often Slack is told a thread is still being worked on: it stops showing it an hour after it was last told. */
1145
+ const SLACK_WORKING_TTL_MS = 50 * 6e4;
1146
+ /**
1147
+ * Requests one catch-up tick makes for what was posted while down, shared by the mapped channels, each getting at
1148
+ * least three. Ticks come a minute apart while a read is cut short: Slack allows an app made for its own
1149
+ * workspace 50 or more of these a minute.
1150
+ */
1151
+ const SLACK_REQUESTS = 24;
1152
+ /** Threads started before the downtime, among the 200 messages before it, whose new replies a tick reads per channel. */
1153
+ const SLACK_OLD_THREADS = 2;
1154
+ /** How far back from its start a catch-up looks for those threads. */
1155
+ const SLACK_LOOKBACK_US = 168 * 3600 * 1e6;
1156
+ /** History is read oldest first, a stretch of time at a time: this long to begin with, longer while quiet. */
1157
+ const SLACK_WINDOW_US = 1800 * 1e6;
1158
+ /** The shortest stretch. One busier than a tick can read is gone past, and said to be. */
1159
+ const SLACK_MIN_WINDOW_US = 60 * 1e6;
1160
+ /** Pages a stretch longer than the shortest may take before it is read as shorter ones. */
1161
+ const SLACK_STRETCH_PAGES = 2;
1162
+ /** A Slack ts, `1700000000.000100`, as whole microseconds, and back. */
1163
+ const fromTs = (ts) => {
1164
+ const [seconds = "0", fraction = ""] = String(ts).split(".");
1165
+ return Number(seconds) * 1e6 + Number(fraction.padEnd(6, "0").slice(0, 6));
1166
+ };
1167
+ const toTs = (us) => `${Math.floor(us / 1e6)}.${String(us % 1e6).padStart(6, "0")}`;
1168
+ /** Slack: messages in mapped channels come in as threads, and board replies go back into the Slack thread. */
1169
+ const slack = (options) => declared("slack", options, slackWith);
1170
+ function slackWith(options) {
1171
+ const now = options.now ?? (() => Date.now());
1172
+ const base = options.api ?? "https://slack.com/api";
1173
+ /** The files on a message. One Slack only links to, or no longer offers, is named and not fetched. */
1174
+ const filesOf = (files) => {
1175
+ if (!Array.isArray(files) || files.length === 0) return void 0;
1176
+ return files.map((file$1) => {
1177
+ const url = String(file$1.url_private_download ?? file$1.url_private ?? "");
1178
+ const skip = file$1.mode === "external" || file$1.is_external === true || file$1.filetype === "remote" ? "a link to somewhere outside Slack" : !url || file$1.mode === "tombstone" || file$1.mode === "hidden_by_limit" ? "Slack does not offer it" : void 0;
1179
+ return {
1180
+ url,
1181
+ id: String(file$1.id ?? ""),
1182
+ name: String(file$1.name ?? file$1.title ?? file$1.id ?? "file"),
1183
+ ...file$1.mimetype ? { type: String(file$1.mimetype) } : {},
1184
+ ...typeof file$1.size === "number" ? { size: file$1.size } : {},
1185
+ ...skip ? { skip } : {}
1186
+ };
1187
+ });
1188
+ };
1189
+ const isSelf = (message) => message.bot_id !== void 0 && (options.bot === void 0 || message.bot_id === options.bot);
1190
+ /** A Web API read. Slack says no with a 200 and `ok: false`, which is a failure here too, never "nothing new". */
1191
+ const api = async (fetcher, method, query) => {
1192
+ const body = await send(fetcher, `${base}/${method}?${new URLSearchParams(query)}`, { headers: { authorization: `Bearer ${options.token}` } });
1193
+ if (body.ok !== true) throw new Failure(`slack_${body.error ?? "error"}`, `Slack refused ${method}: ${body.error ?? "unknown"}.`);
1194
+ return body;
1195
+ };
1196
+ /** A message read back, as the webhook for it would have made it. */
1197
+ const inbound = (channel, each, thread, parent) => ({
1198
+ id: `catchup:${channel}:${each.ts}`,
1199
+ author: String(each.user ?? each.bot_id ?? "unknown"),
1200
+ place: channel,
1201
+ self: isSelf(each),
1202
+ kind: thread === each.ts ? "root" : "reply",
1203
+ thread: `${channel}:${thread}`,
1204
+ external: `${channel}:${each.ts}`,
1205
+ text: String(each.text ?? ""),
1206
+ ...parent ? { parent } : {},
1207
+ ...filesOf(each.files) ? { files: filesOf(each.files) } : {}
1208
+ });
1209
+ const isPlain = (each) => (each.subtype === void 0 || each.subtype === "file_share") && (each.thread_ts === void 0 || each.thread_ts === each.ts);
1210
+ /** Whether a thread may have had replies after a point. A parent that doesn't say when its last came is read to find out. */
1211
+ const repliedAfter = (each, from) => Number(each.reply_count) > 0 && (each.latest_reply === void 0 || fromTs(each.latest_reply) > from);
1212
+ /** A thread's replies after a point, oldest first, in up to `pages` requests; `done` is false if there were more. */
1213
+ const repliesOf = async (fetcher, channel, parent, from, pages) => {
1214
+ const opener = isSelf(parent) ? void 0 : {
1215
+ author: String(parent.user ?? parent.bot_id ?? "unknown"),
1216
+ text: String(parent.text ?? ""),
1217
+ labels: {}
1218
+ };
1219
+ const out = [];
1220
+ let cursor = "";
1221
+ let used = 0;
1222
+ while (used < pages) {
1223
+ const got = await api(fetcher, "conversations.replies", {
1224
+ channel,
1225
+ ts: parent.ts,
1226
+ oldest: toTs(from),
1227
+ limit: "200",
1228
+ ...cursor ? { cursor } : {}
1229
+ });
1230
+ used++;
1231
+ for (const reply of got.messages ?? []) if (reply.ts !== parent.ts && fromTs(reply.ts) > from && (reply.subtype === void 0 || reply.subtype === "file_share")) out.push(inbound(channel, reply, parent.ts, opener));
1232
+ cursor = got.has_more ? got.response_metadata?.next_cursor ?? "" : "";
1233
+ if (!cursor) return {
1234
+ events: out,
1235
+ used,
1236
+ done: true
1237
+ };
1238
+ }
1239
+ return {
1240
+ events: out,
1241
+ used,
1242
+ done: false
1243
+ };
1244
+ };
1245
+ /**
1246
+ * What was posted in a stretch of time, and the replies in threads started in it, in up to `pages` history pages
1247
+ * and `budget` requests in all. Not `done` when there was more: what it did read is kept in `events`, newest
1248
+ * history first if it was the history that ran over.
1249
+ */
1250
+ const stretch = async (fetcher, channel, lo, hi, from, pages, budget) => {
1251
+ const messages = [];
1252
+ let cursor = "";
1253
+ let used = 0;
1254
+ let done = true;
1255
+ for (;;) {
1256
+ const got = await api(fetcher, "conversations.history", {
1257
+ channel,
1258
+ oldest: toTs(lo - 1),
1259
+ latest: toTs(hi),
1260
+ limit: "200",
1261
+ ...cursor ? { cursor } : {}
1262
+ });
1263
+ used++;
1264
+ messages.push(...got.messages ?? []);
1265
+ cursor = got.has_more ? got.response_metadata?.next_cursor ?? "" : "";
1266
+ if (!cursor) break;
1267
+ if (used >= Math.min(pages, budget)) {
1268
+ done = false;
1269
+ break;
1270
+ }
1271
+ }
1272
+ const historyPages = used;
1273
+ if (!done && used < budget) return {
1274
+ events: [],
1275
+ used,
1276
+ pages: historyPages,
1277
+ done
1278
+ };
1279
+ messages.sort((a, b) => fromTs(a.ts) - fromTs(b.ts));
1280
+ const events = [];
1281
+ for (const each of messages) {
1282
+ if (!isPlain(each)) continue;
1283
+ events.push(inbound(channel, each, each.ts));
1284
+ if (!repliedAfter(each, from)) continue;
1285
+ if (used >= budget) {
1286
+ done = false;
1287
+ continue;
1288
+ }
1289
+ const replies = await repliesOf(fetcher, channel, each, from, budget - used);
1290
+ used += replies.used;
1291
+ events.push(...replies.events);
1292
+ if (!replies.done) done = false;
1293
+ }
1294
+ return {
1295
+ events,
1296
+ used,
1297
+ pages: historyPages,
1298
+ done
1299
+ };
1300
+ };
1301
+ return {
1302
+ type: "slack",
1303
+ verify({ headers, body }) {
1304
+ const stamp = headers["x-slack-request-timestamp"] ?? "";
1305
+ if (!/^\d+$/.test(stamp) || Math.abs(now() / 1e3 - Number(stamp)) > 300) throw bad();
1306
+ if (!same(headers["x-slack-signature"] ?? "", `v0=${hmac(options.secret, `v0:${stamp}:${body}`)}`)) throw bad();
1307
+ },
1308
+ challenge({ body }) {
1309
+ const payload = JSON.parse(body);
1310
+ return payload.type === "url_verification" ? String(payload.challenge) : null;
1311
+ },
1312
+ parse({ body }) {
1313
+ const payload = JSON.parse(body);
1314
+ const event = payload.event ?? {};
1315
+ if (payload.type !== "event_callback" || event.type !== "message") return [];
1316
+ const self = (message) => message.bot_id !== void 0 && (options.bot === void 0 || message.bot_id === options.bot);
1317
+ if (event.subtype === "message_changed" && event.message) return [{
1318
+ id: String(payload.event_id ?? `${event.channel}:${event.ts}`),
1319
+ author: String(event.message.user ?? "unknown"),
1320
+ place: String(event.channel),
1321
+ self: self(event.message),
1322
+ kind: "edit",
1323
+ thread: `${event.channel}:${event.message.thread_ts ?? event.message.ts}`,
1324
+ external: `${event.channel}:${event.message.ts}`,
1325
+ text: String(event.message.text ?? "")
1326
+ }];
1327
+ if (event.subtype === "message_deleted") return [{
1328
+ id: String(payload.event_id ?? `${event.channel}:${event.ts}`),
1329
+ author: String(event.previous_message?.user ?? "unknown"),
1330
+ place: String(event.channel),
1331
+ self: false,
1332
+ kind: "delete",
1333
+ thread: `${event.channel}:${event.previous_message?.thread_ts ?? event.deleted_ts}`,
1334
+ external: `${event.channel}:${event.deleted_ts}`
1335
+ }];
1336
+ if (event.subtype !== void 0 && event.subtype !== "file_share") return [];
1337
+ const root = event.thread_ts === void 0 || event.thread_ts === event.ts;
1338
+ return [{
1339
+ id: String(payload.event_id ?? `${event.channel}:${event.ts}`),
1340
+ author: String(event.user ?? event.bot_id ?? "unknown"),
1341
+ place: String(event.channel),
1342
+ self: event.bot_id !== void 0 && (options.bot === void 0 || event.bot_id === options.bot),
1343
+ kind: root ? "root" : "reply",
1344
+ thread: `${event.channel}:${event.thread_ts ?? event.ts}`,
1345
+ external: `${event.channel}:${event.ts}`,
1346
+ text: String(event.text ?? ""),
1347
+ ...filesOf(event.files) ? { files: filesOf(event.files) } : {}
1348
+ }];
1349
+ },
1350
+ channelFor(place) {
1351
+ const to = options.channels[place];
1352
+ const channel = typeof to === "string" ? to : to?.channel;
1353
+ return channel ? channelPath(channel) : null;
1354
+ },
1355
+ placeFor(channel) {
1356
+ for (const [id, to] of Object.entries(options.channels)) if ((typeof to === "string" ? to : to.channel) === channel) return id;
1357
+ return null;
1358
+ },
1359
+ async update(external, text, _place, fetcher) {
1360
+ const [channel, ts] = external.split(":");
1361
+ await send(fetcher, `${base}/chat.update`, {
1362
+ method: "POST",
1363
+ headers: {
1364
+ authorization: `Bearer ${options.token}`,
1365
+ "content-type": "application/json; charset=utf-8"
1366
+ },
1367
+ body: JSON.stringify({
1368
+ channel,
1369
+ ts,
1370
+ text
1371
+ })
1372
+ });
1373
+ },
1374
+ ...options.agent ? {
1375
+ workingTtl: SLACK_WORKING_TTL_MS,
1376
+ async working(target, step, _now, fetcher) {
1377
+ const [channel, ts] = target.threadExternal.split(":");
1378
+ const answer = await send(fetcher, `${base}/agents.sessions.setStatus`, {
1379
+ method: "POST",
1380
+ headers: {
1381
+ authorization: `Bearer ${options.token}`,
1382
+ "content-type": "application/json; charset=utf-8"
1383
+ },
1384
+ body: JSON.stringify({
1385
+ channel_id: channel,
1386
+ thread_ts: ts,
1387
+ status: step === "end" ? "active" : "processing"
1388
+ })
1389
+ });
1390
+ if (answer.ok !== true) throw new Failure(`slack_${answer.error ?? "error"}`, `Slack refused the status: ${answer.error ?? "unknown"}.`);
1391
+ return null;
1392
+ }
1393
+ } : {},
1394
+ async remove(external, _place, fetcher) {
1395
+ const [channel, ts] = external.split(":");
1396
+ await send(fetcher, `${base}/chat.delete`, {
1397
+ method: "POST",
1398
+ headers: {
1399
+ authorization: `Bearer ${options.token}`,
1400
+ "content-type": "application/json; charset=utf-8"
1401
+ },
1402
+ body: JSON.stringify({
1403
+ channel,
1404
+ ts
1405
+ })
1406
+ });
1407
+ },
1408
+ async catchUp(since, fetcher) {
1409
+ if (!options.token) return [];
1410
+ const channels = Object.keys(options.channels);
1411
+ const start = Date.parse(since) * 1e3;
1412
+ const end = now() * 1e3;
1413
+ const events = [];
1414
+ let resume = end;
1415
+ let skipped;
1416
+ for (const channel of channels) {
1417
+ const before = await api(fetcher, "conversations.history", {
1418
+ channel,
1419
+ oldest: toTs(Math.max(0, start - SLACK_LOOKBACK_US)),
1420
+ latest: toTs(start),
1421
+ limit: "200"
1422
+ });
1423
+ for (const parent of (before.messages ?? []).filter((each) => isPlain(each) && repliedAfter(each, start)).slice(0, SLACK_OLD_THREADS)) events.push(...(await repliesOf(fetcher, channel, parent, start, 1)).events);
1424
+ let lo = start;
1425
+ let width = SLACK_WINDOW_US;
1426
+ let budget = Math.max(3, Math.floor(SLACK_REQUESTS / channels.length));
1427
+ let moved = false;
1428
+ while (lo < end && budget > 0) {
1429
+ if (!moved && budget <= 2) width = SLACK_MIN_WINDOW_US;
1430
+ const shortest = width <= SLACK_MIN_WINDOW_US;
1431
+ const hi = Math.min(lo + width, end);
1432
+ const read = await stretch(fetcher, channel, lo, hi, start, shortest ? budget : SLACK_STRETCH_PAGES, shortest || moved ? budget : budget - 2);
1433
+ budget -= read.used;
1434
+ if (read.done || shortest) {
1435
+ if (!read.done) skipped = Math.min(skipped ?? lo, lo);
1436
+ events.push(...read.events);
1437
+ lo = hi;
1438
+ moved = true;
1439
+ if (read.done && read.pages === 1) width *= 2;
1440
+ continue;
1441
+ }
1442
+ width = Math.max(SLACK_MIN_WINDOW_US, Math.floor(width / 4));
1443
+ }
1444
+ resume = Math.min(resume, lo);
1445
+ }
1446
+ if (resume >= end && skipped === void 0) return events;
1447
+ const at = (point) => new Date(Math.floor(point / 1e3)).toISOString();
1448
+ return {
1449
+ events,
1450
+ resume: at(resume),
1451
+ ...skipped !== void 0 ? { skipped: at(skipped) } : {}
1452
+ };
1453
+ },
1454
+ mirrors(place) {
1455
+ const to = options.channels[place];
1456
+ return options.token !== void 0 && to !== void 0 && !(typeof to === "object" && to.mirror === false);
1457
+ },
1458
+ async download(file$1, fetcher, limit) {
1459
+ if (!options.token) throw refused("no token to fetch it with");
1460
+ const got = await fetchFile(fetcher, file$1.url, {
1461
+ hosts: ["files.slack.com"],
1462
+ headers: { authorization: `Bearer ${options.token}` },
1463
+ limit,
1464
+ ...file$1.size !== void 0 ? { size: file$1.size } : {}
1465
+ });
1466
+ if ((got.type ?? "").startsWith("text/html") && !(file$1.type ?? "").startsWith("text/html")) throw refused("Slack sent a page, not the file: does the app have files:read?");
1467
+ if (file$1.size !== void 0 && got.bytes.length !== file$1.size) throw refused(`Slack sent ${sizeOf(got.bytes.length)}, not the ${sizeOf(file$1.size)} it named`);
1468
+ return got;
1469
+ },
1470
+ async deliver(message, target, fetcher, read) {
1471
+ const [channel, ts] = (target.threadExternal ?? target.place).split(":");
1472
+ const auth = { authorization: `Bearer ${options.token}` };
1473
+ const uploaded = [];
1474
+ const lines = [];
1475
+ for (const file$1 of message.attachments) {
1476
+ const bytes = read(file$1.id);
1477
+ if (!bytes) {
1478
+ lines.push(noteOut(file$1.name, "the board no longer has it"));
1479
+ continue;
1480
+ }
1481
+ try {
1482
+ const got = await send(fetcher, `${base}/files.getUploadURLExternal`, {
1483
+ method: "POST",
1484
+ headers: {
1485
+ ...auth,
1486
+ "content-type": "application/x-www-form-urlencoded"
1487
+ },
1488
+ body: new URLSearchParams({
1489
+ filename: file$1.name,
1490
+ length: String(bytes.length)
1491
+ }).toString()
1492
+ });
1493
+ const to = new URL(String(got.upload_url ?? "about:blank"));
1494
+ if (got.ok !== true || to.protocol !== "https:" || to.hostname !== "files.slack.com") throw new Failure("platform_refused", "Slack gave no upload URL.");
1495
+ const put = await fetcher(to.href, {
1496
+ method: "POST",
1497
+ headers: { "content-type": "application/octet-stream" },
1498
+ body: new Uint8Array(bytes),
1499
+ redirect: "manual",
1500
+ signal: AbortSignal.timeout(SEND_MS)
1501
+ });
1502
+ if (!put.ok) throw new Failure(`platform_${put.status}`, `Slack answered ${put.status}.`);
1503
+ uploaded.push({
1504
+ id: String(got.file_id),
1505
+ title: file$1.name
1506
+ });
1507
+ } catch {
1508
+ lines.push(noteOut(file$1.name, "Slack did not take it"));
1509
+ }
1510
+ }
1511
+ const text = withLines(message.text, lines);
1512
+ const made = await send(fetcher, `${base}/chat.postMessage`, {
1513
+ method: "POST",
1514
+ headers: {
1515
+ ...auth,
1516
+ "content-type": "application/json; charset=utf-8"
1517
+ },
1518
+ body: JSON.stringify({
1519
+ channel,
1520
+ thread_ts: ts,
1521
+ text
1522
+ })
1523
+ });
1524
+ if (made.ok !== true) throw new Failure(`slack_${made.error ?? "error"}`, `Slack refused the message: ${made.error ?? "unknown"}.`);
1525
+ if (uploaded.length) try {
1526
+ const shared = await send(fetcher, `${base}/files.completeUploadExternal`, {
1527
+ method: "POST",
1528
+ headers: {
1529
+ ...auth,
1530
+ "content-type": "application/json; charset=utf-8"
1531
+ },
1532
+ body: JSON.stringify({
1533
+ files: uploaded,
1534
+ channel_id: channel,
1535
+ thread_ts: ts ?? made.ts
1536
+ })
1537
+ });
1538
+ if (shared.ok !== true) throw new Failure(`slack_${shared.error ?? "error"}`, "Slack did not share the files.");
1539
+ } catch {
1540
+ await send(fetcher, `${base}/chat.update`, {
1541
+ method: "POST",
1542
+ headers: {
1543
+ ...auth,
1544
+ "content-type": "application/json; charset=utf-8"
1545
+ },
1546
+ body: JSON.stringify({
1547
+ channel,
1548
+ ts: made.ts,
1549
+ text: withLines(text, uploaded.map((file$1) => noteOut(file$1.title, "Slack did not take it")))
1550
+ })
1551
+ }).catch(() => void 0);
1552
+ uploaded.length = 0;
1553
+ }
1554
+ return {
1555
+ external: `${channel}:${made.ts}`,
1556
+ ...target.threadExternal === null ? { thread: `${channel}:${made.ts}` } : {},
1557
+ ...uploaded.length ? { files: uploaded.map((file$1) => file$1.id) } : {}
1558
+ };
1559
+ }
1560
+ };
1561
+ }
1562
+ /** Catch-up reads at most this many pages of each Notion database, of 100 each. */
1563
+ const NOTION_CATCHUP_PAGES = 10;
1564
+ /** The most of a page a thread's first message holds: the rest is on Notion, a link away. */
1565
+ const NOTION_TEXT_MAX = 9e3;
1566
+ /** Notion takes at most 2,000 characters in one rich text item, and 100 items in a comment. */
1567
+ const NOTION_RICH_MAX = 2e3;
1568
+ /**
1569
+ * Notion: each page of a mapped database is a thread, its title and text the first message and its Status the
1570
+ * `state` label, and its comments are replies, both ways. Notion's webhooks say only what changed, so each event
1571
+ * is read from Notion's API on the ticker before it is imported. `secret` is the subscription's verification
1572
+ * token, which Notion signs every delivery with.
1573
+ */
1574
+ const notion = (options) => declared("notion", options, notionWith);
1575
+ /** What `secret` is set to until Notion has sent its verification token: the one time an unsigned request is taken. */
1576
+ const NOTION_PENDING = "pending";
1577
+ /** A Notion ID as one form: lowercase, without dashes, so a database named either way is the same one. */
1578
+ const notionId = (id) => String(id ?? "").replace(/-/g, "").toLowerCase();
1579
+ /** Where a Notion subscription's one-time verification token is written for the operator, and nowhere else. */
1580
+ const notionTokenFile = () => join(process.env.MUSTER_CONFIG ?? join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "muster"), "notion-verification-token");
1581
+ function notionWith(options) {
1582
+ const api = (options.api ?? "https://api.notion.com/v1").replace(/\/$/, "");
1583
+ const databases = new Map(Object.entries(options.databases).map(([id, to]) => [notionId(id), to]));
1584
+ const call = (fetcher, path, init = {}) => {
1585
+ if (!options.token) throw new Failure("platform_refused", "The Notion sync has no token to read Notion with.");
1586
+ return send(fetcher, `${api}${path}`, {
1587
+ method: init.method ?? "GET",
1588
+ headers: {
1589
+ authorization: `Bearer ${options.token}`,
1590
+ "notion-version": options.version ?? "2026-03-11",
1591
+ ...init.body !== void 0 ? { "content-type": "application/json" } : {}
1592
+ },
1593
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
1594
+ });
1595
+ };
1596
+ const plain = (rich$1) => Array.isArray(rich$1) ? rich$1.map((each) => String(each?.plain_text ?? each?.text?.content ?? "")).join("") : "";
1597
+ /** Text as Notion's rich text, in items it takes, as much of it as a comment can hold. */
1598
+ const rich = (text) => {
1599
+ const out = [];
1600
+ for (let at = 0; at < text.length && out.length < 100; at += NOTION_RICH_MAX) out.push({ text: { content: text.slice(at, at + NOTION_RICH_MAX) } });
1601
+ return out.length ? out : [{ text: { content: " " } }];
1602
+ };
1603
+ /** The database a page is in, as this sync names it: its data source, or its database on an older workspace. */
1604
+ const placeOf = (page) => {
1605
+ const parent = page.parent ?? {};
1606
+ for (const id of [parent.data_source_id, parent.database_id]) if (id && databases.has(notionId(id))) return notionId(id);
1607
+ return null;
1608
+ };
1609
+ const titleOf = (page) => {
1610
+ for (const property of Object.values(page.properties ?? {})) if (property?.type === "title") return plain(property.title).trim();
1611
+ return "";
1612
+ };
1613
+ /** Its Status, or a select called Status, as the thread's `state` label. */
1614
+ const stateOf = (page) => {
1615
+ for (const [name, property] of Object.entries(page.properties ?? {})) {
1616
+ const value = property?.type === "status" ? property.status?.name : property?.type === "select" && /^status$/i.test(name) ? property.select?.name : void 0;
1617
+ if (typeof value === "string" && value) return slug(value);
1618
+ }
1619
+ };
1620
+ const byOf = (who) => String(who?.id ?? "");
1621
+ const selfOf = (who) => options.bot !== void 0 && who?.id !== void 0 && notionId(who.id) === notionId(options.bot);
1622
+ /** A page as a thread's first message: its title, a blank line, its text as markdown, cut to what a message holds. */
1623
+ const pageText = async (page, fetcher) => {
1624
+ const body = await call(fetcher, `/pages/${page.id}/markdown`).then((answer) => String(answer?.markdown ?? ""), (error) => {
1625
+ if (error instanceof Failure && error.reason === "platform_404") return "";
1626
+ throw error;
1627
+ });
1628
+ const text = `${titleOf(page)}\n\n${body}`.trim();
1629
+ return text.length > NOTION_TEXT_MAX ? `${text.slice(0, NOTION_TEXT_MAX)}\n\n… the rest is on Notion: ${String(page.url ?? "")}` : text;
1630
+ };
1631
+ const pageLabels = (page) => {
1632
+ const state = stateOf(page);
1633
+ return {
1634
+ kind: "page",
1635
+ ...typeof page.url === "string" ? { ref: page.url.slice(0, 256) } : {},
1636
+ ...state ? { state } : {}
1637
+ };
1638
+ };
1639
+ /** What a page is now, as the first message of a thread the board may not have yet. */
1640
+ const parentOf = async (page, fetcher) => ({
1641
+ author: byOf(page.created_by),
1642
+ text: await pageText(page, fetcher),
1643
+ labels: pageLabels(page)
1644
+ });
1645
+ const isVerification = (body) => {
1646
+ try {
1647
+ const parsed = JSON.parse(body);
1648
+ return parsed !== null && typeof parsed === "object" && Object.keys(parsed).length === 1 && typeof parsed.verification_token === "string" && /^secret_[A-Za-z0-9]{10,200}$/.test(parsed.verification_token);
1649
+ } catch {
1650
+ return false;
1651
+ }
1652
+ };
1653
+ return {
1654
+ type: "notion",
1655
+ verify({ headers, body }) {
1656
+ const signature = headers["x-notion-signature"];
1657
+ if (options.secret === NOTION_PENDING) {
1658
+ if (isVerification(body)) return;
1659
+ throw bad();
1660
+ }
1661
+ if (!same(signature ?? "", `sha256=${hmac(options.secret, body)}`)) throw bad();
1662
+ },
1663
+ challenge({ body }) {
1664
+ if (options.secret !== NOTION_PENDING || !isVerification(body)) return null;
1665
+ try {
1666
+ const file$1 = notionTokenFile();
1667
+ mkdirSync(dirname(file$1), { recursive: true });
1668
+ writeFileSync(file$1, `${JSON.parse(body).verification_token}\n`, {
1669
+ mode: 384,
1670
+ flag: "wx"
1671
+ });
1672
+ } catch {}
1673
+ return "ok";
1674
+ },
1675
+ parse({ body }) {
1676
+ const payload = JSON.parse(body);
1677
+ const type = String(payload.type ?? "");
1678
+ const entity = payload.entity ?? {};
1679
+ const data = payload.data ?? {};
1680
+ const author = payload.authors?.[0];
1681
+ const base = {
1682
+ id: `notion:${payload.id}`,
1683
+ author: byOf(author),
1684
+ place: "",
1685
+ self: selfOf(author),
1686
+ unread: true
1687
+ };
1688
+ if (!entity.id) return [];
1689
+ const page = `page:${notionId(entity.id)}`;
1690
+ if (type === "page.created") return [{
1691
+ ...base,
1692
+ kind: "root",
1693
+ thread: page,
1694
+ external: page
1695
+ }];
1696
+ if (type === "page.content_updated") return [{
1697
+ ...base,
1698
+ kind: "edit",
1699
+ thread: page,
1700
+ external: page
1701
+ }];
1702
+ if (type === "page.properties_updated") return [{
1703
+ ...base,
1704
+ kind: "labels",
1705
+ thread: page,
1706
+ external: base.id
1707
+ }];
1708
+ if (type === "page.deleted") return [{
1709
+ ...base,
1710
+ kind: "delete",
1711
+ thread: page,
1712
+ external: page
1713
+ }];
1714
+ if (type.startsWith("comment.") && data.page_id) {
1715
+ const kind = type === "comment.created" ? "reply" : type === "comment.updated" ? "edit" : type === "comment.deleted" ? "delete" : null;
1716
+ if (kind) return [{
1717
+ ...base,
1718
+ kind,
1719
+ thread: `page:${notionId(data.page_id)}`,
1720
+ external: `comment:${notionId(entity.id)}`
1721
+ }];
1722
+ }
1723
+ return [];
1724
+ },
1725
+ async read(event, fetcher) {
1726
+ const page = await call(fetcher, `/pages/${event.thread.replace(/^page:/, "")}`);
1727
+ const place = placeOf(page);
1728
+ if (place === null) return [];
1729
+ const read = {
1730
+ ...event,
1731
+ place
1732
+ };
1733
+ if (event.kind === "delete") return [read];
1734
+ if (!event.external.startsWith("comment:")) {
1735
+ const text = await pageText(page, fetcher);
1736
+ if (event.kind === "root") return [{
1737
+ ...read,
1738
+ author: byOf(page.created_by),
1739
+ self: selfOf(page.created_by),
1740
+ text,
1741
+ labels: pageLabels(page)
1742
+ }];
1743
+ const parent = { parent: {
1744
+ author: byOf(page.created_by),
1745
+ text,
1746
+ labels: pageLabels(page)
1747
+ } };
1748
+ return [{
1749
+ ...read,
1750
+ kind: "edit",
1751
+ external: event.thread,
1752
+ author: byOf(page.last_edited_by),
1753
+ self: selfOf(page.last_edited_by),
1754
+ text,
1755
+ ...parent
1756
+ }, {
1757
+ ...read,
1758
+ id: `${event.id}:labels`,
1759
+ kind: "labels",
1760
+ external: `${event.id}:labels`,
1761
+ labels: pageLabels(page),
1762
+ ...parent
1763
+ }];
1764
+ }
1765
+ const comment = await call(fetcher, `/comments/${event.external.replace(/^comment:/, "")}`);
1766
+ return [{
1767
+ ...read,
1768
+ author: byOf(comment.created_by),
1769
+ self: selfOf(comment.created_by),
1770
+ text: plain(comment.rich_text),
1771
+ parent: await parentOf(page, fetcher)
1772
+ }];
1773
+ },
1774
+ channelFor(place) {
1775
+ const to = databases.get(notionId(place));
1776
+ const channel = typeof to === "string" ? to : to?.channel;
1777
+ return channel ? channelPath(channel) : null;
1778
+ },
1779
+ placeFor(channel) {
1780
+ for (const [id, to] of databases) if ((typeof to === "string" ? to : to.channel) === channel) return id;
1781
+ return null;
1782
+ },
1783
+ mirrors(place) {
1784
+ const to = databases.get(notionId(place));
1785
+ return options.token !== void 0 && to !== void 0 && !(typeof to === "object" && to.mirror === false);
1786
+ },
1787
+ async update(external, text, _place, fetcher) {
1788
+ if (!external.startsWith("comment:")) return;
1789
+ await call(fetcher, `/comments/${external.slice(8)}`, {
1790
+ method: "PATCH",
1791
+ body: { rich_text: rich(text) }
1792
+ });
1793
+ },
1794
+ async remove(external, _place, fetcher) {
1795
+ if (!external.startsWith("comment:")) return;
1796
+ await call(fetcher, `/comments/${external.slice(8)}`, { method: "DELETE" });
1797
+ },
1798
+ async catchUp(since, fetcher) {
1799
+ if (!options.token) return [];
1800
+ const out = [];
1801
+ const cuts = [];
1802
+ for (const id of databases.keys()) {
1803
+ const pages = [];
1804
+ let cursor;
1805
+ let more = false;
1806
+ for (let read = 0; read < NOTION_CATCHUP_PAGES; read++) {
1807
+ const answer = await call(fetcher, `/data_sources/${id}/query`, {
1808
+ method: "POST",
1809
+ body: {
1810
+ filter: {
1811
+ timestamp: "last_edited_time",
1812
+ last_edited_time: { after: since }
1813
+ },
1814
+ sorts: [{
1815
+ timestamp: "last_edited_time",
1816
+ direction: "ascending"
1817
+ }],
1818
+ page_size: 100,
1819
+ ...cursor ? { start_cursor: cursor } : {}
1820
+ }
1821
+ });
1822
+ if (!Array.isArray(answer?.results)) throw new Failure("platform_refused", "Notion did not list the database's pages.");
1823
+ pages.push(...answer.results.filter((each) => each?.object === "page"));
1824
+ more = Boolean(answer.has_more && answer.next_cursor);
1825
+ if (!more) break;
1826
+ cursor = String(answer.next_cursor);
1827
+ }
1828
+ for (const page of pages) {
1829
+ const pageId = notionId(page.id);
1830
+ const thread = `page:${pageId}`;
1831
+ const text = await pageText(page, fetcher);
1832
+ const labels = pageLabels(page);
1833
+ const edited = String(page.last_edited_time ?? "");
1834
+ out.push({
1835
+ id: `catchup:page:${pageId}`,
1836
+ author: byOf(page.created_by),
1837
+ place: id,
1838
+ self: selfOf(page.created_by),
1839
+ kind: "root",
1840
+ thread,
1841
+ external: thread,
1842
+ text,
1843
+ labels
1844
+ });
1845
+ out.push({
1846
+ id: `catchup:edit:${pageId}:${edited}`,
1847
+ author: byOf(page.last_edited_by),
1848
+ self: selfOf(page.last_edited_by),
1849
+ place: id,
1850
+ kind: "edit",
1851
+ thread,
1852
+ external: thread,
1853
+ text
1854
+ });
1855
+ out.push({
1856
+ id: `catchup:state:${pageId}:${edited}`,
1857
+ author: "",
1858
+ place: id,
1859
+ kind: "labels",
1860
+ thread,
1861
+ external: `catchup:state:${pageId}:${edited}`,
1862
+ labels,
1863
+ ...edited ? { at: edited } : {}
1864
+ });
1865
+ const parent = {
1866
+ author: byOf(page.created_by),
1867
+ text,
1868
+ labels
1869
+ };
1870
+ let start;
1871
+ for (let read = 0; read < NOTION_CATCHUP_PAGES; read++) {
1872
+ const comments = await call(fetcher, `/comments?block_id=${page.id}&page_size=100${start ? `&start_cursor=${encodeURIComponent(start)}` : ""}`);
1873
+ for (const comment of Array.isArray(comments?.results) ? comments.results : []) {
1874
+ const made = String(comment.created_time ?? "") > since;
1875
+ const changed = String(comment.last_edited_time ?? "") > since;
1876
+ if (!made && !changed) continue;
1877
+ const external = `comment:${notionId(comment.id)}`;
1878
+ const common = {
1879
+ author: byOf(comment.created_by),
1880
+ place: id,
1881
+ self: selfOf(comment.created_by),
1882
+ thread,
1883
+ external,
1884
+ text: plain(comment.rich_text),
1885
+ parent
1886
+ };
1887
+ out.push({
1888
+ ...common,
1889
+ id: `catchup:comment:${notionId(comment.id)}`,
1890
+ kind: "reply"
1891
+ });
1892
+ if (changed) out.push({
1893
+ ...common,
1894
+ id: `catchup:comment:${notionId(comment.id)}:${String(comment.last_edited_time)}`,
1895
+ kind: "edit"
1896
+ });
1897
+ }
1898
+ if (!comments?.has_more || !comments.next_cursor) break;
1899
+ start = String(comments.next_cursor);
1900
+ }
1901
+ }
1902
+ if (more) cuts.push(cutShort(pages.map((page) => Date.parse(String(page.last_edited_time))), since, false, 0));
1903
+ }
1904
+ return cuts.length ? {
1905
+ events: out,
1906
+ ...soonest(cuts)
1907
+ } : out;
1908
+ },
1909
+ async deliver(message, target, fetcher, read) {
1910
+ const lines = message.attachments.map((file$1) => read(file$1.id) ? noteOut(file$1.name, "the Notion sync sends no files yet") : noteOut(file$1.name, "the board no longer has it"));
1911
+ if (target.threadExternal === null) {
1912
+ const source = await call(fetcher, `/data_sources/${target.place}`);
1913
+ const title = Object.entries(source?.properties ?? {}).find(([, property]) => property?.type === "title")?.[0];
1914
+ if (!title) throw new Failure("platform_refused", "Notion did not say which property is the database's title.");
1915
+ const [first, ...rest] = message.text.split("\n");
1916
+ const body = withLines(rest.join("\n").trim(), lines);
1917
+ const made$1 = await call(fetcher, "/pages", {
1918
+ method: "POST",
1919
+ body: {
1920
+ parent: { data_source_id: target.place },
1921
+ properties: { [title]: { title: rich(first.slice(0, NOTION_RICH_MAX)) } },
1922
+ children: body ? [{
1923
+ object: "block",
1924
+ type: "paragraph",
1925
+ paragraph: { rich_text: rich(body) }
1926
+ }] : []
1927
+ }
1928
+ });
1929
+ if (!made$1?.id) throw new Failure("platform_refused", "Notion did not make the page.");
1930
+ const thread = `page:${notionId(made$1.id)}`;
1931
+ return {
1932
+ external: thread,
1933
+ thread,
1934
+ labels: pageLabels(made$1)
1935
+ };
1936
+ }
1937
+ const made = await call(fetcher, "/comments", {
1938
+ method: "POST",
1939
+ body: {
1940
+ parent: { page_id: target.threadExternal.replace(/^page:/, "") },
1941
+ rich_text: rich(withLines(message.text, lines))
1942
+ }
1943
+ });
1944
+ if (!made?.id) throw new Failure("platform_refused", "Notion did not make the comment.");
1945
+ return { external: `comment:${notionId(made.id)}` };
1946
+ }
1947
+ };
1948
+ }
1949
+
1950
+ //#endregion
1951
+ export { AGENTS, Failure, LINEAR_SCOPES, SANDBOX_ROUTES, agentEnv, applyPolicy, board, boardKey, boardPath, boardPolicy, claude, cloudflare, codex, command, conformance, createHandler, e2b, env, fenced, file, generic, github, http, linear, listen, loadWorkflows, mint, notion, runLocal, slack, vercel, verify, workflowResult, workflowsPath };