tryharness 0.7.53 → 0.7.54

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 (69) hide show
  1. package/README.md +10 -5
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +115 -36
  5. package/lib/adapters.mjs +157 -222
  6. package/lib/agentRuntimes.mjs +26 -16
  7. package/lib/agentSignIn.mjs +226 -0
  8. package/lib/audit.mjs +643 -0
  9. package/lib/backupSetup.mjs +141 -0
  10. package/lib/boardAccess.mjs +8 -1
  11. package/lib/boardBackup.mjs +283 -0
  12. package/lib/boardMirror.mjs +71 -7
  13. package/lib/boardProtocol.json +59 -2
  14. package/lib/boardWaits.mjs +102 -0
  15. package/lib/book.mjs +659 -0
  16. package/lib/bridge.mjs +1 -1
  17. package/lib/cards.mjs +138 -28
  18. package/lib/cloudBoot.mjs +124 -0
  19. package/lib/commands.mjs +7 -2
  20. package/lib/context.mjs +18 -4
  21. package/lib/contractGate.mjs +377 -0
  22. package/lib/coordinator.mjs +149 -43
  23. package/lib/daemon.mjs +349 -28
  24. package/lib/desk.mjs +239 -0
  25. package/lib/desktop.mjs +106 -6
  26. package/lib/environments.mjs +237 -7
  27. package/lib/folders.mjs +2 -2
  28. package/lib/gitHost.mjs +174 -0
  29. package/lib/hookDialects.mjs +298 -0
  30. package/lib/landed.mjs +887 -0
  31. package/lib/live.mjs +284 -13
  32. package/lib/mcp-stdio.mjs +68 -2
  33. package/lib/members.json +16 -2
  34. package/lib/models.mjs +8 -8
  35. package/lib/museSession.mjs +16 -13
  36. package/lib/nativeHost.mjs +1 -1
  37. package/lib/neovim.mjs +126 -0
  38. package/lib/nudge.mjs +47 -16
  39. package/lib/ownMachines.mjs +343 -39
  40. package/lib/pairing.mjs +27 -10
  41. package/lib/paths.mjs +4 -0
  42. package/lib/personModel.mjs +89 -0
  43. package/lib/phones.mjs +66 -11
  44. package/lib/places.mjs +330 -10
  45. package/lib/readiness.mjs +135 -18
  46. package/lib/record.mjs +115 -0
  47. package/lib/runWorker.mjs +17 -2
  48. package/lib/runner.mjs +8 -4
  49. package/lib/sessionControl.mjs +377 -89
  50. package/lib/specialties.json +74 -0
  51. package/lib/specialties.mjs +477 -0
  52. package/lib/specialtyKeys.d.ts +3 -0
  53. package/lib/specialtyKeys.js +58 -0
  54. package/lib/specialtyNotice.mjs +147 -0
  55. package/lib/specialtySnapshot.mjs +138 -0
  56. package/lib/store.mjs +284 -1
  57. package/lib/swarm.mjs +137 -21
  58. package/lib/t3.mjs +13 -4
  59. package/lib/taskCommands.mjs +36 -9
  60. package/lib/taskRuns.mjs +9 -2
  61. package/lib/team.json +255 -148
  62. package/lib/team.mjs +529 -188
  63. package/lib/threadLine.mjs +116 -0
  64. package/lib/threadRuns.mjs +75 -11
  65. package/lib/threadView.mjs +15 -2
  66. package/lib/worktrees.mjs +51 -13
  67. package/package.json +4 -4
  68. package/lib/modelTiers.json +0 -1183
  69. package/lib/modelTiers.mjs +0 -133
@@ -1,8 +1,9 @@
1
+ import fs from "node:fs";
1
2
  import { createHash } from "node:crypto";
2
3
  import { detectAgents } from "./commands.mjs";
3
4
  import { member, nameOf } from "./members.mjs";
4
5
  import { t3Access, t3Tool } from "./t3.mjs";
5
- import { t3Link } from "./places.mjs";
6
+ import { t3Checkouts, t3Committers, t3Link } from "./places.mjs";
6
7
 
7
8
  const DRIVER_AGENT = {
8
9
  codex: "codex",
@@ -35,14 +36,56 @@ const failure = (error) => ({
35
36
  error: error.message,
36
37
  });
37
38
 
38
- /** Existing work owned by another execution environment, projected into the same swarm view. */
39
- export function createEnvironments({ store, log, notify = () => {} }) {
39
+ // How often T3 Code is read again while a surface on this computer waits for the board (the buddy's old poll, which
40
+ // read it this often).
41
+ const WATCHED_REFRESH_MS = 3_000;
42
+ // Where the person left each recent thread (threadLine.mjs) is read for this many of the newest, from the last two
43
+ // weeks, and only again when a thread has new items.
44
+ const LINE_THREADS = 40;
45
+ const LINE_DAYS_MS = 14 * 24 * 60 * 60 * 1000;
46
+ // The person's last message is looked for among the thread's newest items, at most this many back: a long run of an
47
+ // agent's steps comes between two of their messages.
48
+ const EXCHANGE_ITEMS = 400;
49
+
50
+ /**
51
+ * Existing work owned by another execution environment, projected into the same swarm view. Reads are answered from
52
+ * what T3 Code last said and read it again behind the answer (October 23: reading T3 Code took about 160 ms of every
53
+ * list on every surface); `notify` hears when what it says changed.
54
+ */
55
+ export function createEnvironments({
56
+ store,
57
+ log,
58
+ notify = () => {},
59
+ watched = () => false,
60
+ threadLine = null,
61
+ }) {
40
62
  let providers = [];
41
63
  let threads = new Map();
64
+ // Each thread's own checkout and branch, from T3's record (its list leaves them out): what can land (landed.mjs).
65
+ let checkouts = new Map();
66
+ // The threads that ran a command making a commit, read again at most once a minute and never in a list's way.
67
+ let committers = new Set();
68
+ let committersAt = 0;
69
+ const COMMITTERS_FRESH_MS = 60_000;
42
70
  let projects = new Map();
43
71
  let refreshing = null;
72
+ // Each thread's read as it was last made, kept until T3 says the thread or its subagents changed: one is a page of T3's
73
+ // record per 100 items (October 24: 1 MB and 0.8 to 1.5 s each, asked every 2 s while it was on screen).
74
+ const reads = new Map();
75
+ // Threads the person removed from Harness's list, each until it does something new: id → its last activity then.
76
+ const HIDDEN_KEY = "outside-hidden";
77
+ const hiddenNow = () => {
78
+ try {
79
+ return JSON.parse(store.meta(HIDDEN_KEY) || "{}");
80
+ } catch {
81
+ return {};
82
+ }
83
+ };
44
84
  let lastError = null;
45
85
  let grant = null;
86
+ // The grant the rows held were read under, and what they said, so a refresh that changes nothing tells no one.
87
+ let loadedGrant = null;
88
+ let said = "";
46
89
  const controls = new Map();
47
90
  const keyOf = (id) =>
48
91
  `outside-t3-${createHash("sha256").update(`${t3Access()?.environmentId}:${id}`).digest("hex")}`;
@@ -56,6 +99,7 @@ export function createEnvironments({ store, log, notify = () => {} }) {
56
99
  const clear = () => {
57
100
  providers = [];
58
101
  threads = new Map();
102
+ checkouts = new Map();
59
103
  projects = new Map();
60
104
  };
61
105
  const authorized = () => {
@@ -113,6 +157,18 @@ export function createEnvironments({ store, log, notify = () => {} }) {
113
157
  }
114
158
  return selected;
115
159
  };
160
+ /**
161
+ * A thread's own checkout and branch, as T3 said it or as T3 keeps it; null for a thread working in its project, or
162
+ * one whose checkout T3 has since removed (nothing there to show).
163
+ */
164
+ const checkoutOf = (entry) => {
165
+ const own =
166
+ entry.worktreePath && entry.branch
167
+ ? { path: entry.worktreePath, branch: entry.branch }
168
+ : (checkouts.get(entry.threadId) ?? null);
169
+ return own && fs.existsSync(own.path) ? own : null;
170
+ };
171
+
116
172
  const summary = (entry) => {
117
173
  const family = [...treeOf(entry).values()];
118
174
  const active = family.filter((child) => ACTIVE.has(child.status));
@@ -136,6 +192,8 @@ export function createEnvironments({ store, log, notify = () => {} }) {
136
192
  line: `${nameOf(agent)} · T3 Code`,
137
193
  needsYou: [],
138
194
  done: false,
195
+ // Where the person left it: their last move and what it was about.
196
+ you: threadLine?.of(keyOf(entry.threadId)) ?? null,
139
197
  },
140
198
  folder: projects.get(entry.projectId)?.workspaceRoot ?? null,
141
199
  working: [
@@ -150,6 +208,9 @@ export function createEnvironments({ store, log, notify = () => {} }) {
150
208
  posts: family.reduce((sum, child) => sum + (child.itemCount ?? 0), 0),
151
209
  spend: { runs: 0, cost_usd: null },
152
210
  changes: null,
211
+ // A thread T3 works on in a checkout of its own can land (landed.mjs); one working in the project itself can't
212
+ // be told apart from the person's own work.
213
+ landed: Boolean(checkoutOf(entry) || committers.has(entry.threadId)),
153
214
  createdAt: entry.createdAt,
154
215
  updatedAt:
155
216
  family
@@ -162,6 +223,7 @@ export function createEnvironments({ store, log, notify = () => {} }) {
162
223
  child.settled,
163
224
  child.updatedAt,
164
225
  child.itemCount,
226
+ child.latestRunId ?? null,
165
227
  ]),
166
228
  openItems: [],
167
229
  coordination: null,
@@ -207,6 +269,12 @@ export function createEnvironments({ store, log, notify = () => {} }) {
207
269
  includeSubagents: true,
208
270
  },
209
271
  "threads"
272
+ ).then((listed) =>
273
+ // T3 lists a project's threads without naming the project on each; its folder is the thread's.
274
+ listed.map((entry) => ({
275
+ ...entry,
276
+ projectId: entry.projectId ?? project.id,
277
+ }))
210
278
  )
211
279
  )
212
280
  )
@@ -217,28 +285,151 @@ export function createEnvironments({ store, log, notify = () => {} }) {
217
285
  threads = new Map(
218
286
  listedThreads.map((entry) => [keyOf(entry.threadId), entry])
219
287
  );
288
+ checkouts = t3Checkouts();
289
+
290
+ if (Date.now() - committersAt > COMMITTERS_FRESH_MS) {
291
+ committersAt = Date.now();
292
+ void t3Committers().then((found) => {
293
+ committers = found;
294
+ });
295
+ }
220
296
  lastError = null;
221
- notify();
297
+ catchUpLines();
222
298
  } catch (error) {
223
299
  clear();
224
300
  lastError = error.message;
225
301
  log(`outside environments: ${error.message}`);
226
302
  } finally {
303
+ loadedGrant = startedGrant;
227
304
  refreshing = null;
305
+ const now = JSON.stringify([providers, [...projects], [...threads]]);
306
+ if (now !== said) {
307
+ said = now;
308
+ notify();
309
+ }
228
310
  }
229
311
  })();
230
312
  return refreshing;
231
313
  };
314
+ // The thread's newest items, as far back as the person's last message: it and the agent's message it answers.
315
+ async function lastExchange(entry) {
316
+ const items = [];
317
+ let after = Math.max(0, (entry.itemCount ?? 0) - EXCHANGE_ITEMS) || null;
318
+ for (let page = 0; page < EXCHANGE_ITEMS / 100; page++) {
319
+ const read = await t3Tool("t3_thread_read", {
320
+ threadId: entry.threadId,
321
+ view: "messages",
322
+ limit: 100,
323
+ // An agent's `Deciding:` line ends its message: room for all of it.
324
+ maxCharsPerItem: 20_000,
325
+ runLimit: 1,
326
+ ...(after === null ? {} : { afterPosition: after }),
327
+ });
328
+ items.push(...(read.items ?? []));
329
+ if (!read.hasMore || read.nextPosition === after) break;
330
+ after = read.nextPosition;
331
+ }
332
+ const said = items.filter((item) =>
333
+ ["user_message", "assistant_message"].includes(item.type)
334
+ );
335
+ // T3's notices to an agent (a subagent finished) are filed as the user's: only the person's own words count.
336
+ const at = said.findLastIndex(
337
+ (item) => item.type === "user_message" && item.createdBy !== "agent"
338
+ );
339
+ if (at < 0) return null;
340
+ const mine = said[at];
341
+ return {
342
+ mine: {
343
+ id: mine.itemId,
344
+ text: mine.text ?? "",
345
+ at: mine.updatedAt ?? entry.updatedAt,
346
+ },
347
+ answered:
348
+ said.slice(0, at).findLast((item) => item.type === "assistant_message")
349
+ ?.text ?? null,
350
+ };
351
+ }
352
+ // Each recent thread's line, behind the list: a thread read again only when it has new items. Lists are drawn again
353
+ // once any line changed.
354
+ const lineChecked = new Map();
355
+ let lining = null;
356
+ function catchUpLines() {
357
+ if (!threadLine || lining) return;
358
+ lining = (async () => {
359
+ const recent = [...threads.values()]
360
+ .filter(
361
+ (entry) =>
362
+ entry.relationshipToParent !== "subagent" &&
363
+ Date.now() - Date.parse(entry.updatedAt) < LINE_DAYS_MS
364
+ )
365
+ .sort((a, b) => String(b.updatedAt).localeCompare(a.updatedAt))
366
+ .slice(0, LINE_THREADS);
367
+ let changed = false;
368
+ for (const entry of recent) {
369
+ const version = `${entry.itemCount}:${entry.updatedAt}`;
370
+ if (lineChecked.get(entry.threadId) === version) continue;
371
+ lineChecked.set(entry.threadId, version);
372
+ try {
373
+ const exchange = await lastExchange(entry);
374
+ if (!exchange) continue;
375
+ if (
376
+ await threadLine.update(keyOf(entry.threadId), {
377
+ title: entry.title || "Untitled work",
378
+ ...exchange,
379
+ })
380
+ )
381
+ changed = true;
382
+ } catch (error) {
383
+ lineChecked.delete(entry.threadId);
384
+ log(`thread line: ${error.message}`);
385
+ }
386
+ }
387
+ if (changed) notify();
388
+ })().finally(() => {
389
+ lining = null;
390
+ });
391
+ }
392
+ /**
393
+ * Before a list: null when the rows held can be shown now (T3 Code is read again behind them), or the first read under
394
+ * this grant to wait for.
395
+ */
396
+ const ready = () => {
397
+ if (!authorized()) return null;
398
+ const reading = refresh();
399
+ return loadedGrant === grant ? null : reading;
400
+ };
401
+ const keepFresh = setInterval(() => {
402
+ if (watched()) void refresh();
403
+ }, WATCHED_REFRESH_MS);
404
+ keepFresh.unref?.();
232
405
  const roots = () => {
233
406
  if (!authorized()) return [];
234
407
  const known = new Set([...threads.values()].map((entry) => entry.threadId));
408
+ const hidden = hiddenNow();
235
409
  return [...threads.values()]
236
410
  .filter(
237
411
  (entry) =>
238
412
  entry.relationshipToParent !== "subagent" ||
239
413
  !known.has(entry.parentThreadId)
240
414
  )
241
- .map(summary);
415
+ .map(summary)
416
+ .filter(
417
+ (thread) => hidden[thread.id] !== JSON.stringify(thread.activityVersion)
418
+ );
419
+ };
420
+ /** Removed from Harness's list (T3 keeps it): until it does something new, when it shows again. */
421
+ const hide = (id) => {
422
+ const entry = threads.get(id);
423
+ if (!authorized() || !entry)
424
+ return { ok: false, error: "This source thread is no longer available." };
425
+ const kept = Object.fromEntries(
426
+ Object.entries(hiddenNow()).filter(([key]) => threads.has(key))
427
+ );
428
+ kept[id] = JSON.stringify(summary(entry).activityVersion);
429
+ store.meta(HIDDEN_KEY, JSON.stringify(kept));
430
+ said = "";
431
+ notify();
432
+ return { ok: true };
242
433
  };
243
434
  const catalog = () => ({
244
435
  ok: true,
@@ -292,6 +483,8 @@ export function createEnvironments({ store, log, notify = () => {} }) {
292
483
  const root = threads.get(id);
293
484
  if (!root)
294
485
  return { ok: false, error: "This source thread is no longer available." };
486
+ const version = JSON.stringify([grant, summary(root).activityVersion]);
487
+ if (reads.get(id)?.version === version) return reads.get(id).result;
295
488
  const selected = treeOf(root);
296
489
  const runs = [];
297
490
  const posts = [];
@@ -425,7 +618,7 @@ export function createEnvironments({ store, log, notify = () => {} }) {
425
618
  code: "not_connected",
426
619
  error: "T3 Code access changed while reading this work.",
427
620
  };
428
- return {
621
+ const result = {
429
622
  ok: true,
430
623
  thread: { ...summary(root), source: runs[0].source },
431
624
  runs,
@@ -440,6 +633,8 @@ export function createEnvironments({ store, log, notify = () => {} }) {
440
633
  kept: [],
441
634
  rendering: [],
442
635
  };
636
+ reads.set(id, { version, result });
637
+ return result;
443
638
  }
444
639
  async function control(request, agent) {
445
640
  if (agent !== "user" || request.hostedCaller)
@@ -591,5 +786,40 @@ export function createEnvironments({ store, log, notify = () => {} }) {
591
786
  return pending(control(request, agent));
592
787
  return { ok: false, error: "Unknown environment command." };
593
788
  };
594
- return { command, refresh, roots, owns, read, control, catalog };
789
+ /** A T3 Code thread's own checkout and branch, for what it put into the world (landed.mjs); null without one. */
790
+ const work = (id) => {
791
+ const entry = threads.get(id);
792
+ if (!authorized() || !entry) return null;
793
+ const own = checkoutOf(entry);
794
+ const project = projects.get(entry.projectId)?.workspaceRoot ?? null;
795
+ // Working in the project itself, it landed work only through the commits it made (landed.mjs reads those).
796
+ if (!own && !(committers.has(entry.threadId) && project)) return null;
797
+ return {
798
+ id,
799
+ threadId: entry.threadId,
800
+ title: entry.title || "Untitled work",
801
+ agent: providerAgent(entry.providerInstanceId),
802
+ branch: own?.branch ?? null,
803
+ path: own?.path ?? project,
804
+ inPlace: !own,
805
+ createdAt: entry.createdAt,
806
+ updatedAt: entry.updatedAt,
807
+ };
808
+ };
809
+ /** Every T3 Code thread working in a checkout of its own, or that made commits in its project. */
810
+ const worked = () => [...threads.keys()].map(work).filter(Boolean);
811
+
812
+ return {
813
+ command,
814
+ refresh,
815
+ ready,
816
+ roots,
817
+ owns,
818
+ read,
819
+ hide,
820
+ control,
821
+ catalog,
822
+ work,
823
+ worked,
824
+ };
595
825
  }
package/lib/folders.mjs CHANGED
@@ -32,13 +32,13 @@ export const isDir = (dir) =>
32
32
  path.isAbsolute(dir) &&
33
33
  fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory() === true;
34
34
 
35
- const within = (dir, root) => {
35
+ export const within = (dir, root) => {
36
36
  const rel = root ? path.relative(root, dir) : "..";
37
37
  return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
38
38
  };
39
39
 
40
40
  /** A folder Harness may offer or pick by itself: not the home folder or above it, not hidden, not Harness's own, not gone. */
41
- function offerable(dir) {
41
+ export function offerable(dir) {
42
42
  const real = realDir(dir);
43
43
  if (!real || !isDir(real) || within(real, realDir(paths.home))) return false;
44
44
  const home = realDir(os.homedir()) ?? os.homedir();
@@ -0,0 +1,174 @@
1
+ import { spawn } from "node:child_process";
2
+ import { resolveCommand } from "./commands.mjs";
3
+
4
+ // Where a repository's work is out in the world: its git host's pages, read from the remote's address, and (on GitHub)
5
+ // its pull requests through the person's own `gh` sign-in. Nothing here signs in or keeps a token of its own.
6
+
7
+ const HOSTS = [
8
+ { host: "github.com", kind: "github", name: "GitHub" },
9
+ { host: "gitlab.com", kind: "gitlab", name: "GitLab" },
10
+ { host: "bitbucket.org", kind: "bitbucket", name: "Bitbucket" },
11
+ ];
12
+
13
+ /**
14
+ * The web home of a remote (`git@github.com:acme/widgets.git`, `https://github.com/acme/widgets`, `ssh://...`): its
15
+ * host, its owner/name path and the page that shows it. Null for a remote with no web page (a folder, a bare path).
16
+ */
17
+ export function remoteWeb(remote) {
18
+ const text = String(remote || "").trim();
19
+ const scp = /^[\w.-]+@([\w.-]+):(.+)$/.exec(text);
20
+ const url = scp
21
+ ? { host: scp[1], path: scp[2] }
22
+ : (() => {
23
+ try {
24
+ const parsed = new URL(text);
25
+ if (!["https:", "http:", "ssh:", "git:"].includes(parsed.protocol))
26
+ return null;
27
+ return { host: parsed.hostname, path: parsed.pathname };
28
+ } catch {
29
+ return null;
30
+ }
31
+ })();
32
+ if (!url?.host) return null;
33
+ const slug = url.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
34
+ if (!slug.includes("/")) return null;
35
+ const known = HOSTS.find((entry) => entry.host === url.host);
36
+ return {
37
+ kind: known?.kind ?? "other",
38
+ name: known?.name ?? url.host,
39
+ slug,
40
+ web: `https://${url.host}/${slug}`,
41
+ };
42
+ }
43
+
44
+ /** The page that shows a pull request's changes, on the host that has it. */
45
+ export function changesPage(host, request) {
46
+ if (host.kind === "gitlab") return `${request.url}/diffs`;
47
+ if (host.kind === "bitbucket") return `${request.url}/diff`;
48
+ return `${request.url}/files`;
49
+ }
50
+
51
+ /** The page that shows one commit, on the host that has it. */
52
+ export function commitPage(host, sha) {
53
+ if (host.kind === "gitlab") return `${host.web}/-/commit/${sha}`;
54
+ if (host.kind === "bitbucket") return `${host.web}/commits/${sha}`;
55
+ return `${host.web}/commit/${sha}`;
56
+ }
57
+
58
+ // A branch name keeps its slashes in a page's address; anything else in it is escaped.
59
+ const inPath = (branch) =>
60
+ String(branch).split("/").map(encodeURIComponent).join("/");
61
+
62
+ /** The page comparing a pushed branch with the branch it would go into, for a branch with no pull request. */
63
+ export function comparePage(host, base, branch) {
64
+ if (host.kind === "gitlab")
65
+ return `${host.web}/-/compare/${base}...${inPath(branch)}`;
66
+ if (host.kind === "bitbucket")
67
+ return `${host.web}/branches/compare/${encodeURIComponent(branch)}%0D${base}`;
68
+ return `${host.web}/compare/${base}...${inPath(branch)}`;
69
+ }
70
+
71
+ const FIELDS =
72
+ "number,title,state,isDraft,url,headRefName,author,createdAt,mergedAt,updatedAt";
73
+ // Measured October 23 on the person's Mac: `gh pr list --limit 100` took 301-918 ms (32 runs over three
74
+ // repositories, the busiest cli/cli and vercel/next.js) and `gh pr view` 347-790 ms (10 runs). Ten seconds is about
75
+ // ten times the slowest; past it the board says GitHub did not answer rather than waiting on it.
76
+ const GH_DEADLINE_MS = 10_000;
77
+ const LIST_FRESH_MS = 60_000;
78
+ const ONE_FRESH_MS = 5 * 60_000;
79
+
80
+ /** A pull request as the board shows it: what it is, where it stands, whose branch. */
81
+ const requestOf = (row) => ({
82
+ number: row.number,
83
+ title: row.title,
84
+ state: row.state === "OPEN" && row.isDraft ? "DRAFT" : row.state,
85
+ url: row.url,
86
+ branch: row.headRefName,
87
+ author: row.author?.login ?? null,
88
+ createdAt: row.createdAt ?? null,
89
+ mergedAt: row.mergedAt || null,
90
+ updatedAt: row.updatedAt ?? null,
91
+ });
92
+
93
+ /**
94
+ * GitHub's pull requests through `gh`, kept a minute (a single one five) so a surface reading the board every few
95
+ * seconds asks GitHub at most once a minute. `answer` is how the board says it could not ask.
96
+ */
97
+ export function createGithub({ log = () => {} } = {}) {
98
+ const kept = new Map();
99
+ const ask = (args) =>
100
+ new Promise((resolve) => {
101
+ const gh = resolveCommand("gh");
102
+ if (!gh) return resolve({ ok: false, answer: "no_gh" });
103
+ const child = spawn(gh, args, {
104
+ env: { ...process.env, GH_PROMPT_DISABLED: "1", NO_COLOR: "1" },
105
+ stdio: ["ignore", "pipe", "pipe"],
106
+ });
107
+ let out = "";
108
+ let err = "";
109
+ const timer = setTimeout(() => child.kill("SIGTERM"), GH_DEADLINE_MS);
110
+ child.stdout.on("data", (chunk) => (out += chunk));
111
+ child.stderr.on("data", (chunk) => (err += chunk));
112
+ child.on("error", () => {
113
+ clearTimeout(timer);
114
+ resolve({ ok: false, answer: "no_gh" });
115
+ });
116
+ child.on("close", (code, signal) => {
117
+ clearTimeout(timer);
118
+ if (code === 0) {
119
+ try {
120
+ return resolve({ ok: true, value: JSON.parse(out || "null") });
121
+ } catch {}
122
+ }
123
+ const said = err.trim().split("\n")[0];
124
+ if (signal) log(`gh did not answer in ${GH_DEADLINE_MS / 1000}s`);
125
+ else if (said) log(`gh: ${said}`);
126
+ resolve({
127
+ ok: false,
128
+ answer: signal
129
+ ? "slow"
130
+ : /auth login|not logged|authentication/i.test(err)
131
+ ? "signed_out"
132
+ : /could not resolve to a/i.test(err)
133
+ ? "missing"
134
+ : "error",
135
+ });
136
+ });
137
+ });
138
+ const cached = (key, freshMs, fetch) => {
139
+ const entry = kept.get(key);
140
+ if (entry && Date.now() - entry.at < freshMs) return entry.value;
141
+ const value = fetch();
142
+ kept.set(key, { at: Date.now(), value });
143
+ return value;
144
+ };
145
+
146
+ return {
147
+ /** The repository's hundred most recent pull requests, open, merged and closed. */
148
+ list: (slug) =>
149
+ cached(`list:${slug}`, LIST_FRESH_MS, () =>
150
+ ask([
151
+ "pr",
152
+ "list",
153
+ "-R",
154
+ slug,
155
+ "--state",
156
+ "all",
157
+ "--limit",
158
+ "100",
159
+ "--json",
160
+ FIELDS,
161
+ ]).then((reply) =>
162
+ reply.ok ? { ok: true, requests: reply.value.map(requestOf) } : reply
163
+ )
164
+ ),
165
+ /** One pull request by its number, for one a thread named that is older than the list reaches. */
166
+ one: (slug, number) =>
167
+ cached(`one:${slug}#${number}`, ONE_FRESH_MS, () =>
168
+ ask(["pr", "view", String(number), "-R", slug, "--json", FIELDS]).then(
169
+ (reply) =>
170
+ reply.ok ? { ok: true, request: requestOf(reply.value) } : reply
171
+ )
172
+ ),
173
+ };
174
+ }