tryharness 0.7.45 → 0.7.53

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 (99) hide show
  1. package/README.md +232 -12
  2. package/cli.mjs +406 -184
  3. package/lib/actorRoster.mjs +28 -5
  4. package/lib/adapters.mjs +9 -1
  5. package/lib/agentRuntimeConfig.mjs +36 -0
  6. package/lib/agentRuntimes.mjs +560 -0
  7. package/lib/atlas.mjs +7 -2
  8. package/lib/boardCommands.mjs +5 -10
  9. package/lib/boardFileCommands.mjs +2 -1
  10. package/lib/boardMirror.mjs +459 -0
  11. package/lib/boardProtocol.json +206 -6
  12. package/lib/boardTools.mjs +2 -6
  13. package/lib/bridge.mjs +25 -3
  14. package/lib/browserWake.mjs +60 -0
  15. package/lib/cards.mjs +35 -2
  16. package/lib/commands.mjs +20 -5
  17. package/lib/connectionTools.d.ts +13 -0
  18. package/lib/connectionTools.js +45 -0
  19. package/lib/connectorAuth.mjs +309 -0
  20. package/lib/connectorCatalog.json +41 -0
  21. package/lib/connectorCommands.mjs +121 -0
  22. package/lib/connectorGoogle.mjs +513 -0
  23. package/lib/connectors.mjs +805 -0
  24. package/lib/coordinator.mjs +8 -1
  25. package/lib/coreModels.mjs +78 -0
  26. package/lib/daemon.mjs +643 -45
  27. package/lib/desktop.mjs +7 -2
  28. package/lib/digest.mjs +32 -0
  29. package/lib/directLink.mjs +283 -0
  30. package/lib/environments.mjs +595 -0
  31. package/lib/folders.mjs +2 -2
  32. package/lib/goalCommands.mjs +58 -14
  33. package/lib/inference.mjs +263 -152
  34. package/lib/lessons.mjs +6 -0
  35. package/lib/lineup.mjs +324 -0
  36. package/lib/localmodels.mjs +10 -0
  37. package/lib/machineIdentity.mjs +3 -0
  38. package/lib/machineRoutes.mjs +40 -2
  39. package/lib/machineRuns.mjs +30 -3
  40. package/lib/machineSeal.mjs +69 -10
  41. package/lib/mcp-stdio.mjs +121 -118
  42. package/lib/mcpRelay.mjs +119 -0
  43. package/lib/members.json +12 -0
  44. package/lib/members.mjs +33 -0
  45. package/lib/modelMemory.mjs +100 -0
  46. package/lib/modelTiers.json +1183 -0
  47. package/lib/modelTiers.mjs +133 -0
  48. package/lib/models.mjs +41 -8
  49. package/lib/museSession.mjs +119 -0
  50. package/lib/nativeHost.mjs +203 -0
  51. package/lib/network.mjs +7 -2
  52. package/lib/nudge.mjs +10 -2
  53. package/lib/onboard.mjs +430 -1
  54. package/lib/oneclawLocal.mjs +150 -0
  55. package/lib/ownMachines.mjs +521 -36
  56. package/lib/pairing.mjs +165 -0
  57. package/lib/paths.mjs +4 -0
  58. package/lib/phones.mjs +61 -0
  59. package/lib/placeCommands.mjs +27 -0
  60. package/lib/places.mjs +10 -2
  61. package/lib/plans.mjs +151 -27
  62. package/lib/profile.mjs +152 -0
  63. package/lib/projects.mjs +624 -137
  64. package/lib/readiness.mjs +283 -0
  65. package/lib/repoLinks.mjs +354 -0
  66. package/lib/roomChannels.mjs +641 -0
  67. package/lib/runBrief.mjs +32 -2
  68. package/lib/runRequests.mjs +157 -0
  69. package/lib/runWorker.mjs +20 -7
  70. package/lib/runner.mjs +67 -8
  71. package/lib/secretPatterns.json +55 -0
  72. package/lib/secrets.mjs +10 -27
  73. package/lib/seen.mjs +102 -0
  74. package/lib/service.mjs +11 -6
  75. package/lib/sessionControl.mjs +10 -8
  76. package/lib/sessionIndex.mjs +5 -3
  77. package/lib/store.mjs +546 -29
  78. package/lib/subagents.mjs +8 -4
  79. package/lib/swarm.mjs +367 -37
  80. package/lib/swarmMemory.mjs +947 -0
  81. package/lib/t3.mjs +43 -13
  82. package/lib/taskCommands.mjs +56 -5
  83. package/lib/taskRuns.mjs +61 -11
  84. package/lib/team.json +17 -15
  85. package/lib/team.mjs +68 -18
  86. package/lib/threadRuns.mjs +3 -1
  87. package/lib/threadView.mjs +51 -14
  88. package/lib/tokenizer.mjs +405 -0
  89. package/lib/ui.mjs +16 -2
  90. package/lib/usageTotals.mjs +148 -0
  91. package/lib/vault.mjs +1144 -0
  92. package/lib/vaultCloud.mjs +117 -0
  93. package/lib/vaultCommands.mjs +201 -0
  94. package/lib/vaultTools.d.ts +12 -0
  95. package/lib/vaultTools.js +42 -0
  96. package/lib/windowAsks.mjs +42 -0
  97. package/lib/workFocus.mjs +59 -0
  98. package/lib/workLinks.mjs +90 -0
  99. package/package.json +9 -4
@@ -0,0 +1,283 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { nameOf } from "./members.mjs";
5
+ import { paths } from "./paths.mjs";
6
+ import { ensureDir, readJson, writeJsonAtomic } from "./files.mjs";
7
+
8
+ // Whether each coding agent on this computer can take a prompt right now: Harness sends it one short prompt and reads
9
+ // the answer. A sign-in file only suggests an agent is signed in; an answer proves it. Setup checks every agent it finds,
10
+ // walks the person through each one that fails, and the daemon checks again when an agent appears or its sign-in
11
+ // changes (createAgentWatch below), so an agent installed later joins the swarm by itself.
12
+
13
+ /**
14
+ * How long one check may take. Measured October 21, 2026 on the owner's Mac (.harness-runs/measure/agent-probe):
15
+ * with the commands below, 12 checks (Claude Code, Codex, Pi, OpenCode, 3 rounds) answered in 2.1-5.2 s; with the
16
+ * fuller run commands, 12 answered in 2.2-24.9 s, the slowest Pi's first start. Signed out, checks failed in
17
+ * 0.2-14.4 s (Codex retries a 401 for 14 s). 60 s is 2.4x the slowest answer seen. A check that reaches it is
18
+ * reported as slow and can be tried again, never as signed out.
19
+ */
20
+ export const CHECK_DEADLINE_MS = 60_000;
21
+
22
+ const PROMPT = "Reply with exactly one word: ready";
23
+
24
+ // Each agent's shortest headless run that still goes through its own sign-in: no tools, no Harness MCP server, and no
25
+ // session saved to the person's history where the agent allows it (OpenCode has no such switch).
26
+ const CHECKS = {
27
+ "claude-code": () => ({
28
+ command: "claude",
29
+ args: [
30
+ "-p",
31
+ PROMPT,
32
+ "--output-format",
33
+ "json",
34
+ "--no-session-persistence",
35
+ "--strict-mcp-config",
36
+ "--tools",
37
+ "",
38
+ ],
39
+ }),
40
+ codex: () => ({
41
+ command: "codex",
42
+ args: [
43
+ "exec",
44
+ "--ephemeral",
45
+ "--skip-git-repo-check",
46
+ "-c",
47
+ 'sandbox_mode="read-only"',
48
+ "-c",
49
+ 'approval_policy="never"',
50
+ "-",
51
+ ],
52
+ stdin: PROMPT,
53
+ }),
54
+ pi: () => ({
55
+ command: "pi",
56
+ args: ["--no-session", "--no-tools", "-p", PROMPT],
57
+ }),
58
+ opencode: () => ({
59
+ command: "opencode",
60
+ args: ["run", "--title", "Harness check", "--", PROMPT],
61
+ }),
62
+ };
63
+
64
+ /** The agents Harness can check by sending them a prompt. */
65
+ export const CHECKABLE = Object.keys(CHECKS);
66
+
67
+ /** What the person runs to sign an agent in, as setup and the browser say it. */
68
+ export const SIGN_IN = {
69
+ "claude-code": "claude, then type /login",
70
+ codex: "codex login",
71
+ pi: "pi, then type /login",
72
+ opencode: "opencode auth login",
73
+ };
74
+
75
+ // The words each agent prints when it has no sign-in to use: a missing login, a missing key, or a 401 from its provider.
76
+ const SIGNED_OUT =
77
+ /not logged in|please run \/login|use \/login|no api key|api key not found|missing bearer|401|unauthori[sz]ed|invalid api key|authentication/i;
78
+
79
+ const lastLine = (text) =>
80
+ String(text)
81
+ .split("\n")
82
+ .map((line) => line.trim())
83
+ .filter(Boolean)
84
+ .at(-1)
85
+ ?.slice(0, 200) ?? "";
86
+
87
+ /** What one check's output means: ready, signed out, slow, or failed with the agent's own last words. */
88
+ export function readCheck({ code, output, timedOut, missing }) {
89
+ if (missing) return { state: "not_installed", detail: null };
90
+ if (timedOut)
91
+ return {
92
+ state: "slow",
93
+ detail: `did not answer within ${CHECK_DEADLINE_MS / 1000} seconds`,
94
+ };
95
+ if (code === 0 && /\bready\b/i.test(output))
96
+ return { state: "ready", detail: null };
97
+ if (SIGNED_OUT.test(output)) return { state: "signed_out", detail: null };
98
+ return { state: "failed", detail: lastLine(output) || `exit ${code}` };
99
+ }
100
+
101
+ /** Send one agent the check prompt in an empty folder and read its answer. */
102
+ export function checkAgent(
103
+ agent,
104
+ {
105
+ cwd = path.join(paths.home, "checks"),
106
+ run = spawn,
107
+ deadlineMs = CHECK_DEADLINE_MS,
108
+ } = {}
109
+ ) {
110
+ const invocation = CHECKS[agent]?.();
111
+ if (!invocation)
112
+ return Promise.resolve({
113
+ state: "unchecked",
114
+ detail: `Harness cannot check ${nameOf(agent)} by itself`,
115
+ ms: 0,
116
+ });
117
+ ensureDir(cwd);
118
+ const started = Date.now();
119
+ return new Promise((resolve) => {
120
+ let output = "";
121
+ let timedOut = false;
122
+ let settled = false;
123
+ const finish = (result) => {
124
+ if (settled) return;
125
+ settled = true;
126
+ clearTimeout(timer);
127
+ resolve({ ...result, ms: Date.now() - started });
128
+ };
129
+ const child = run(invocation.command, invocation.args, {
130
+ cwd,
131
+ stdio: ["pipe", "pipe", "pipe"],
132
+ });
133
+ const timer = setTimeout(() => {
134
+ timedOut = true;
135
+ child.kill("SIGKILL");
136
+ }, deadlineMs);
137
+ child.stdout?.on("data", (chunk) => (output += chunk));
138
+ child.stderr?.on("data", (chunk) => (output += chunk));
139
+ child.stdin?.on("error", () => {});
140
+ child.stdin?.end(invocation.stdin ?? "");
141
+ child.on("error", (error) =>
142
+ finish(
143
+ readCheck({
144
+ output: error.message,
145
+ missing: error.code === "ENOENT",
146
+ })
147
+ )
148
+ );
149
+ child.on("close", (code) => finish(readCheck({ code, output, timedOut })));
150
+ });
151
+ }
152
+
153
+ /**
154
+ * The daemon's record of each agent's last check, kept in a file so setup, the CLI and the browser read the same answer.
155
+ * Each record keeps a stamp of the agent's sign-in files at the time, so a later sign-in is noticed. Two checks of one
156
+ * agent at once share one run.
157
+ */
158
+ export function createAgentReadiness({
159
+ file = path.join(paths.home, "agent-readiness.json"),
160
+ check = checkAgent,
161
+ stampOf = (agent) => signInStamp(agent),
162
+ onChange = () => {},
163
+ now = () => new Date(),
164
+ } = {}) {
165
+ const running = new Map();
166
+ const all = () => readJson(file, {});
167
+ const of = (agent) => all()[agent] ?? null;
168
+ const run = (agent) => {
169
+ if (running.has(agent)) return running.get(agent);
170
+ const signIn = stampOf(agent);
171
+ const pending = check(agent)
172
+ .then((result) => {
173
+ const entry = {
174
+ state: result.state,
175
+ detail: result.detail,
176
+ ms: result.ms,
177
+ checkedAt: now().toISOString(),
178
+ signIn,
179
+ };
180
+ writeJsonAtomic(file, { ...all(), [agent]: entry });
181
+ onChange(agent, entry);
182
+ return entry;
183
+ })
184
+ .finally(() => running.delete(agent));
185
+ running.set(agent, pending);
186
+ return pending;
187
+ };
188
+ /** Whether the agent's sign-in files changed since its last check (or it was never checked). */
189
+ const signInChanged = (agent) => of(agent)?.signIn !== stampOf(agent);
190
+ return {
191
+ check: run,
192
+ of,
193
+ all,
194
+ signInChanged,
195
+ checking: (agent) => running.has(agent),
196
+ };
197
+ }
198
+
199
+ // The files an agent's sign-in lives in: when one of them changes, the agent may have just signed in.
200
+ function signInFiles(agent, home, env) {
201
+ const dataHome = env.XDG_DATA_HOME || path.join(home, ".local", "share");
202
+ switch (agent) {
203
+ case "claude-code":
204
+ return [
205
+ path.join(home, ".claude.json"),
206
+ path.join(home, ".claude", ".credentials.json"),
207
+ ];
208
+ case "codex":
209
+ return [
210
+ path.join(env.CODEX_HOME || path.join(home, ".codex"), "auth.json"),
211
+ ];
212
+ case "pi":
213
+ return [path.join(home, ".pi", "agent", "auth.json")];
214
+ case "opencode":
215
+ return [path.join(dataHome, "opencode", "auth.json")];
216
+ default:
217
+ return [];
218
+ }
219
+ }
220
+ function signInStamp(agent, home = process.env.HOME, env = process.env) {
221
+ return signInFiles(agent, home, env)
222
+ .map((file) => {
223
+ try {
224
+ return fs.statSync(file).mtimeMs;
225
+ } catch {
226
+ return 0;
227
+ }
228
+ })
229
+ .join(":");
230
+ }
231
+
232
+ /**
233
+ * Agents installed after setup join the swarm by themselves. Every scan looks at the agents Harness can check that are
234
+ * installed here; one never checked, or whose sign-in files changed since its last check, is checked, and a ready one
235
+ * the person never took out of their swarm is added (`join`, lineup.mjs). Nothing is checked again without a change, so
236
+ * a signed-out agent costs one check, not one a minute, and a daemon restart costs none.
237
+ */
238
+ export function createAgentWatch({
239
+ readiness,
240
+ installed,
241
+ inSwarm,
242
+ removedByPerson,
243
+ join,
244
+ log = () => {},
245
+ everyMs = 60_000,
246
+ }) {
247
+ const scan = async () => {
248
+ for (const agent of installed().filter((id) => CHECKABLE.includes(id))) {
249
+ if (removedByPerson(agent) || readiness.checking(agent)) continue;
250
+ const result = readiness.signInChanged(agent)
251
+ ? await readiness.check(agent)
252
+ : readiness.of(agent);
253
+ if (result?.state !== "ready" || inSwarm(agent)) continue;
254
+ const joined = join(agent);
255
+ log(
256
+ joined.ok
257
+ ? `${nameOf(agent)} is ready and joined the swarm`
258
+ : `${nameOf(agent)} is ready but could not join: ${joined.error}`
259
+ );
260
+ }
261
+ };
262
+ let timer = null;
263
+ let scanning = null;
264
+ const tick = () => {
265
+ if (scanning) return scanning;
266
+ scanning = scan()
267
+ .catch((error) => log(`agent watch: ${error.message}`))
268
+ .finally(() => (scanning = null));
269
+ return scanning;
270
+ };
271
+ return {
272
+ scan: tick,
273
+ // Setup has just checked every agent, so the first scan waits one interval and the daemon starts no extra work.
274
+ start() {
275
+ timer = setInterval(tick, everyMs);
276
+ timer.unref?.();
277
+ },
278
+ stop() {
279
+ if (timer) clearInterval(timer);
280
+ timer = null;
281
+ },
282
+ };
283
+ }
@@ -0,0 +1,354 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ import { randomUUID } from "node:crypto";
6
+
7
+ // A room from a repository link: the person pastes a GitHub link (or any git host's), Harness finds that repository on
8
+ // this computer by its shared remote, and the room works there; when it is not here, the person picks a folder and
9
+ // Harness clones it into that folder. Git stays the record: the room is anchored by the checkout's first commit and
10
+ // its origin remote (projectGit.mjs anchorOf), so whatever the people agree on lives on the remote, not in Harness.
11
+ //
12
+ // Board commands, the person's only (an agent does not clone onto the computer):
13
+ // board.repo.find { link } → { repo, here: folder | null, places: [folders to clone into] }
14
+ // board.repo.clone { link, parent } → { folder }
15
+ // With detached:true, clone returns {operation,state:"cloning"}; board.repo.clone.read {operation} returns progress
16
+ // or the final result. Short calls fit existing browser/buddy transports while the owner's clone deadline runs here.
17
+ // Then board.project.create { folder } (or board.project.join { folder }) starts or joins the room as for any folder.
18
+
19
+ const HOSTS = ["github.com", "gitlab.com", "bitbucket.org", "codeberg.org"];
20
+ const NAME = /^[A-Za-z0-9._-]+$/;
21
+
22
+ /**
23
+ * A repository link as people paste it: https://github.com/owner/name, with or without .git, a /tree/… page of it,
24
+ * github.com/owner/name, or git@github.com:owner/name.git. Null for anything else.
25
+ */
26
+ export function parseRepoLink(text) {
27
+ const raw = String(text || "").trim();
28
+ const ssh = raw.match(/^(?:ssh:\/\/)?git@([^:/]+)[:/]([^/]+)\/([^/]+?)\/?$/);
29
+ let host, owner, name;
30
+ if (ssh) [, host, owner, name] = ssh;
31
+ else {
32
+ let url;
33
+ try {
34
+ url = new URL(/^[a-z]+:\/\//i.test(raw) ? raw : `https://${raw}`);
35
+ } catch {
36
+ return null;
37
+ }
38
+ if (!["https:", "http:"].includes(url.protocol)) return null;
39
+ host = url.hostname;
40
+ [owner, name] = url.pathname.split("/").filter(Boolean);
41
+ }
42
+ host = String(host || "")
43
+ .toLowerCase()
44
+ .replace(/^www\./, "");
45
+ name = String(name || "").replace(/\.git$/, "");
46
+ if (!HOSTS.includes(host) || !NAME.test(owner || "") || !NAME.test(name))
47
+ return null;
48
+ return {
49
+ host,
50
+ owner,
51
+ name,
52
+ label: `${owner}/${name}`,
53
+ https: `https://${host}/${owner}/${name}.git`,
54
+ ssh: `git@${host}:${owner}/${name}.git`,
55
+ };
56
+ }
57
+
58
+ /** Whether a remote's address is the linked repository, however it was written. */
59
+ export const sameRepo = (remote, link) => {
60
+ const parsed = parseRepoLink(
61
+ String(remote || "").replace(/\/\/[^@/]+@/, "//")
62
+ );
63
+ return Boolean(
64
+ parsed &&
65
+ parsed.host === link.host &&
66
+ parsed.owner.toLowerCase() === link.owner.toLowerCase() &&
67
+ parsed.name.toLowerCase() === link.name.toLowerCase()
68
+ );
69
+ };
70
+
71
+ /** The origin remote's address from a checkout's git config, read without running git. */
72
+ function originOf(folder) {
73
+ let gitDir = path.join(folder, ".git");
74
+ try {
75
+ if (fs.statSync(gitDir).isFile()) {
76
+ // A worktree: .git names the real directory; its config is the main checkout's.
77
+ const pointed = fs
78
+ .readFileSync(gitDir, "utf8")
79
+ .match(/gitdir:\s*(.+)/)?.[1]
80
+ ?.trim();
81
+ if (!pointed) return null;
82
+ gitDir = path.resolve(folder, pointed, "..", "..");
83
+ }
84
+ const config = fs.readFileSync(path.join(gitDir, "config"), "utf8");
85
+ const section = config
86
+ .split(/^\[/m)
87
+ .find((part) => /^remote "origin"\]/.test(part));
88
+ return section?.match(/^\s*url\s*=\s*(.+)$/m)?.[1]?.trim() ?? null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ /** The folders people keep repositories in, those that exist here; the home folder last. */
95
+ export function usualPlaces(homeDir = os.homedir()) {
96
+ const names = [
97
+ "code",
98
+ "Code",
99
+ "src",
100
+ "dev",
101
+ "Developer",
102
+ "projects",
103
+ "Projects",
104
+ "GitHub",
105
+ "github",
106
+ "repos",
107
+ "workspace",
108
+ path.join("Documents", "GitHub"),
109
+ ];
110
+ const found = [];
111
+ const seen = new Set();
112
+ for (const name of names) {
113
+ const folder = path.join(homeDir, name);
114
+ try {
115
+ const real = fs.realpathSync(folder);
116
+ if (fs.statSync(real).isDirectory() && !seen.has(real)) {
117
+ seen.add(real);
118
+ found.push(real);
119
+ }
120
+ } catch {}
121
+ }
122
+ return [...found, homeDir];
123
+ }
124
+
125
+ /** Git checkouts in a folder and one level below it (two when `deep`). */
126
+ function checkoutsIn(root, deep) {
127
+ const out = [];
128
+ const visit = (folder, depth) => {
129
+ let entries;
130
+ try {
131
+ entries = fs.readdirSync(folder, { withFileTypes: true });
132
+ } catch {
133
+ return;
134
+ }
135
+ if (entries.some((entry) => entry.name === ".git")) {
136
+ out.push(folder);
137
+ return;
138
+ }
139
+ if (depth === 0) return;
140
+ for (const entry of entries)
141
+ if (
142
+ entry.isDirectory() &&
143
+ !entry.name.startsWith(".") &&
144
+ entry.name !== "node_modules" &&
145
+ entry.name !== "Library"
146
+ )
147
+ visit(path.join(folder, entry.name), depth - 1);
148
+ };
149
+ visit(root, deep ? 2 : 1);
150
+ return out;
151
+ }
152
+
153
+ /**
154
+ * This computer's checkout of the linked repository: among the folders the person's agents work in, then the usual
155
+ * places, the first whose origin is that repository. Null when it is not here.
156
+ */
157
+ export function findHere({ link, folders = [], homeDir = os.homedir() }) {
158
+ const places = usualPlaces(homeDir);
159
+ const candidates = [
160
+ ...folders,
161
+ ...places.flatMap((place) => checkoutsIn(place, place !== homeDir)),
162
+ ];
163
+ const seen = new Set();
164
+ for (const folder of candidates) {
165
+ let real;
166
+ try {
167
+ real = fs.realpathSync(folder);
168
+ } catch {
169
+ continue;
170
+ }
171
+ if (seen.has(real)) continue;
172
+ seen.add(real);
173
+ if (sameRepo(originOf(real), link)) return real;
174
+ }
175
+ return null;
176
+ }
177
+
178
+ // How long a clone may wait for the remote to answer: 2 minutes, the owner's value, not yet measured against real
179
+ // GitHub clones. It covers only the wait for the remote's first byte; once the remote is answering, a large
180
+ // repository takes as long as its transfer does.
181
+ export const FIRST_BYTE_MS = 120_000;
182
+
183
+ // What git says before the remote has answered: its own "Cloning into '<folder>'..." line.
184
+ const beforeRemote = (text) =>
185
+ text
186
+ .split(/[\r\n]+/)
187
+ .every((line) => !line.trim() || /^Cloning into /.test(line.trim()));
188
+
189
+ function gitLater(cwd, args, firstByteMs) {
190
+ return new Promise((resolve) => {
191
+ // Its own process group: git hands the network to a helper (git-remote-https, ssh) that would outlive git itself
192
+ // and keep the output open, so giving up stops the whole group.
193
+ const child = spawn("git", args, {
194
+ cwd,
195
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
196
+ detached: true,
197
+ });
198
+ let err = "";
199
+ let answered = false;
200
+ let settled = false;
201
+ const finish = (result) => {
202
+ if (settled) return;
203
+ settled = true;
204
+ clearTimeout(timer);
205
+ resolve(result);
206
+ };
207
+ const timer = setTimeout(() => {
208
+ try {
209
+ process.kill(-child.pid, "SIGTERM");
210
+ } catch {
211
+ child.kill("SIGTERM");
212
+ }
213
+ finish({
214
+ ok: false,
215
+ err: `the remote did not answer within ${Math.round(firstByteMs / 1000)} seconds`,
216
+ });
217
+ }, firstByteMs);
218
+ child.stderr.on("data", (chunk) => {
219
+ err += chunk;
220
+ if (!answered && !beforeRemote(String(chunk))) {
221
+ answered = true;
222
+ clearTimeout(timer);
223
+ }
224
+ });
225
+ child.on("error", (error) => finish({ ok: false, err: error.message }));
226
+ child.on("close", (code) => finish({ ok: code === 0, err: err.trim() }));
227
+ });
228
+ }
229
+
230
+ /**
231
+ * Clone the linked repository into `parent`, as a folder named for it (name-2 and on when one is there). The https
232
+ * address first, then ssh, so either the person's GitHub sign-in or their ssh key opens a private repository.
233
+ */
234
+ export async function cloneInto({ link, parent, firstByteMs = FIRST_BYTE_MS }) {
235
+ const where = String(parent || "");
236
+ if (
237
+ !path.isAbsolute(where) ||
238
+ !fs.existsSync(where) ||
239
+ !fs.statSync(where).isDirectory()
240
+ )
241
+ return { ok: false, error: "Pick a folder that is on this computer." };
242
+ let target = path.join(where, link.name);
243
+ for (let n = 2; fs.existsSync(target); n += 1)
244
+ target = path.join(where, `${link.name}-${n}`);
245
+ let last = null;
246
+ for (const address of [link.https, link.ssh]) {
247
+ // --progress: git reports the remote's answer as it comes, which is what the deadline waits for.
248
+ const cloned = await gitLater(
249
+ where,
250
+ ["clone", "--progress", address, target],
251
+ firstByteMs
252
+ );
253
+ if (cloned.ok) return { ok: true, folder: fs.realpathSync(target) };
254
+ last = cloned.err.split("\n").filter(Boolean).at(-1) ?? "git clone failed";
255
+ fs.rmSync(target, { recursive: true, force: true });
256
+ }
257
+ return {
258
+ ok: false,
259
+ error: `Couldn't clone ${link.label}: ${last}. If it is private, sign in to ${link.host} on this computer (for GitHub: gh auth login) and try again.`,
260
+ };
261
+ }
262
+
263
+ /** The board commands above. `knownFolders`: the folders the person's agents work in (folders.mjs). */
264
+ export function createRepoLinks({
265
+ knownFolders = () => [],
266
+ homeDir = os.homedir(),
267
+ } = {}) {
268
+ const clones = new Map();
269
+ const destinations = new Map();
270
+ const progress = (job) =>
271
+ job.result ?? { ok: true, operation: job.id, state: "cloning" };
272
+ const keepRecentResults = () => {
273
+ const finished = [...clones.values()].filter((job) => job.result);
274
+ for (const job of finished.slice(0, -32)) {
275
+ clones.delete(job.id);
276
+ if (destinations.get(job.key) === job) destinations.delete(job.key);
277
+ }
278
+ };
279
+ const linkOf = (request) => {
280
+ const link = parseRepoLink(request.link);
281
+ return link
282
+ ? { link }
283
+ : {
284
+ error:
285
+ "That is not a repository link. Paste one like https://github.com/owner/name.",
286
+ };
287
+ };
288
+ return {
289
+ command(request, agent) {
290
+ // The person on this computer, not a hosted caller acting as them: a clone writes to this computer's disk.
291
+ if (agent !== "user" || request.hostedCaller === true)
292
+ return { ok: false, error: "Only the person opens a repository link." };
293
+ if (request.command === "board.repo.clone.read") {
294
+ const job = clones.get(request.operation);
295
+ return job
296
+ ? progress(job)
297
+ : {
298
+ ok: false,
299
+ error:
300
+ "That clone is no longer tracked. Find the repository again.",
301
+ };
302
+ }
303
+ const { link, error } = linkOf(request);
304
+ if (!link) return { ok: false, error };
305
+ if (request.command === "board.repo.find") {
306
+ const here = findHere({ link, folders: knownFolders(), homeDir });
307
+ return {
308
+ ok: true,
309
+ repo: { label: link.label, host: link.host, remote: link.https },
310
+ here,
311
+ places: here ? [] : usualPlaces(homeDir),
312
+ };
313
+ }
314
+ if (request.command === "board.repo.clone") {
315
+ const parent = String(request.parent || "");
316
+ let canonicalParent = path.resolve(parent);
317
+ try {
318
+ canonicalParent = fs.realpathSync(parent);
319
+ } catch {}
320
+ const key = JSON.stringify([link.https, canonicalParent]);
321
+ const current = destinations.get(key);
322
+ if (
323
+ request.detached === true &&
324
+ current &&
325
+ (!current.result ||
326
+ (current.result.ok &&
327
+ sameRepo(originOf(current.result.folder), link)))
328
+ )
329
+ return progress(current);
330
+ const already = findHere({ link, folders: knownFolders(), homeDir });
331
+ if (already) return { ok: true, folder: already, cloned: false };
332
+ const pending = cloneInto({ link, parent }).then((done) =>
333
+ done.ok ? { ...done, cloned: true } : done
334
+ );
335
+ if (request.detached !== true) return { pending };
336
+ const job = { id: randomUUID(), key, result: null };
337
+ clones.set(job.id, job);
338
+ destinations.set(key, job);
339
+ void pending
340
+ .catch((failure) => ({ ok: false, error: String(failure) }))
341
+ .then((result) => {
342
+ job.result = result;
343
+ clones.delete(job.id);
344
+ clones.set(job.id, job);
345
+ if (!result.ok && destinations.get(key) === job)
346
+ destinations.delete(key);
347
+ keepRecentResults();
348
+ });
349
+ return progress(job);
350
+ }
351
+ return { ok: false, error: `unknown command ${request.command}` };
352
+ },
353
+ };
354
+ }