tryharness 0.7.81 → 0.7.82

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 (46) hide show
  1. package/README.md +4 -3
  2. package/assets/install.sh +104 -0
  3. package/cli.mjs +203 -321
  4. package/lib/adapters.mjs +7 -6
  5. package/lib/agentRuntimes.mjs +2 -1
  6. package/lib/backupSetup.mjs +0 -52
  7. package/lib/boardProtocol.json +17 -1
  8. package/lib/browserPage.mjs +30 -0
  9. package/lib/daemon.mjs +89 -5
  10. package/lib/desktop.mjs +7 -1
  11. package/lib/dispatcher.mjs +12 -2
  12. package/lib/environments.mjs +4 -11
  13. package/lib/goalCommands.mjs +2 -1
  14. package/lib/hookDialects.mjs +2 -1
  15. package/lib/jobAnswers.mjs +2 -1
  16. package/lib/localStack.mjs +24 -9
  17. package/lib/mcp-stdio.mjs +6 -0
  18. package/lib/museSession.mjs +2 -1
  19. package/lib/nativeHost.mjs +11 -2
  20. package/lib/network.mjs +1 -0
  21. package/lib/notify.mjs +48 -16
  22. package/lib/onboard.mjs +71 -366
  23. package/lib/ownMachines.mjs +4 -1
  24. package/lib/pairing.mjs +0 -84
  25. package/lib/paths.mjs +17 -0
  26. package/lib/personNotices.mjs +9 -25
  27. package/lib/profile.mjs +0 -109
  28. package/lib/projects.mjs +18 -4
  29. package/lib/removeHarness.mjs +91 -0
  30. package/lib/roomChannels.mjs +2 -0
  31. package/lib/runner.mjs +3 -3
  32. package/lib/runtime-install.mjs +22 -2
  33. package/lib/screen.mjs +133 -0
  34. package/lib/selfUpdate.mjs +6 -6
  35. package/lib/service.mjs +120 -7
  36. package/lib/sessionControl.mjs +10 -0
  37. package/lib/setupChoices.mjs +400 -0
  38. package/lib/setupMode.mjs +137 -0
  39. package/lib/t3.mjs +23 -14
  40. package/lib/threadActions.mjs +2 -1
  41. package/lib/toolCheck.mjs +136 -0
  42. package/lib/ui.mjs +15 -1
  43. package/lib/wakes.mjs +3 -3
  44. package/npm-shrinkwrap.json +14 -14
  45. package/package.json +4 -4
  46. package/release.json +47 -40
package/lib/paths.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import os from "node:os";
2
3
  import path from "node:path";
3
4
 
@@ -45,10 +46,26 @@ export const paths = {
45
46
  files: path.join(harnessHome, "files"),
46
47
  runtime: path.join(harnessHome, "runtime"),
47
48
  models: path.join(harnessHome, "models"),
49
+ // Harness's own Node.js, which install.sh downloads and checks (see harnessNode).
50
+ node: path.join(harnessHome, "node"),
48
51
  legacyBridgeConfig: path.join(harnessHome, "bridge.json"),
49
52
  legacySpool: path.join(harnessHome, "pending-sessions.json"),
50
53
  };
51
54
 
55
+ /**
56
+ * The Node.js everything Harness starts runs on: the daemon's service, the installed command, and each agent's Harness
57
+ * MCP server and hooks. Harness's own, in ~/.harness/node, when install.sh put it there, so a Node manager removing the
58
+ * version setup ran on cannot stop Harness later. Someone who set up with plain `npx tryharness` has none, and Harness
59
+ * runs on the Node that ran setup.
60
+ */
61
+ export function harnessNode() {
62
+ const program =
63
+ process.platform === "win32"
64
+ ? path.join(paths.node, "node.exe")
65
+ : path.join(paths.node, "bin", "node");
66
+ return fs.existsSync(program) ? program : process.execPath;
67
+ }
68
+
52
69
  export function historyRoots(agent) {
53
70
  if (agent === "claude-code")
54
71
  return [
@@ -1,17 +1,13 @@
1
1
  import { readJson } from "./files.mjs";
2
2
  import { nameOf } from "./members.mjs";
3
- import { notificationFor, notifyDesktop } from "./notify.mjs";
4
-
5
- // How long since the buddy last collected its notices before the system's own notice says them instead.
6
- const BUDDY_GONE_MS = 10_000;
7
- const BUDDY_KEEPS = 50;
3
+ import { notificationFor, notifyDesktop, takeNotices } from "./notify.mjs";
8
4
 
9
5
  /**
10
6
  * What the person is told about the board, whether or not Harness is open: on the desktop in words, and to their
11
7
  * installed phone as only the kind of thing that waits, so a tap opens it there. Each item is told once.
12
8
  *
13
- * The buddy posts the desktop's notices itself while it runs, so a click opens the item there: it collects them every
14
- * two seconds. Once it has not for ten, the system's own notice says the same words.
9
+ * On a Mac the buddy posts the desktop's notices itself, so a click opens the item there: it collects them every two
10
+ * seconds, and what it has not collected waits for its next launch (notify.mjs).
15
11
  *
16
12
  * Notices are off with `tryharness notify off` (`notifications: false` in the config). Nothing is said while the Mac is
17
13
  * in Standby (`quiet()`). `threadView()` reads a thread as every surface does (threadView.mjs), made after this module.
@@ -26,26 +22,14 @@ export function createPersonNotices({
26
22
  }) {
27
23
  const on = () => readJson(configPath, {}).notifications !== false;
28
24
 
29
- /** A desktop notice, when the person has them on. */
30
- const notify = (text) => {
31
- if (on()) notifyDesktop(text);
25
+ /** A desktop notice, when the person has them on; `thread` is what a click opens. */
26
+ const notify = (text, { thread } = {}) => {
27
+ if (on()) notifyDesktop(text, { thread });
32
28
  };
33
29
 
34
- const forBuddy = { notices: [], collectedAt: 0 };
35
- const buddyCollects = () => Date.now() - forBuddy.collectedAt < BUDDY_GONE_MS;
36
-
37
- /** A notice that opens `item` in `thread` when clicked: the buddy's while it collects them, the system's otherwise. */
38
- const tellDesktop = (title, line, thread, item) => {
39
- if (!buddyCollects()) return notifyDesktop(`${title}: ${line}`);
40
- forBuddy.notices.push({ title, body: line, thread, item });
41
- forBuddy.notices.splice(0, forBuddy.notices.length - BUDDY_KEEPS);
42
- };
43
-
44
- /** The buddy collects what it should post. */
45
- const takeNotices = () => {
46
- forBuddy.collectedAt = Date.now();
47
- return forBuddy.notices.splice(0);
48
- };
30
+ /** A notice that opens `item` in `thread` when clicked. */
31
+ const tellDesktop = (title, line, thread, item) =>
32
+ notifyDesktop(line, { title, thread, item });
49
33
 
50
34
  const firstTime = (id) => {
51
35
  if (store.meta(`told:${id}`)) return false;
package/lib/profile.mjs CHANGED
@@ -1,5 +1,4 @@
1
1
  import fs from "node:fs";
2
- import pc from "picocolors";
3
2
  import { readJson, writeJsonAtomic } from "./files.mjs";
4
3
  import { paths } from "./paths.mjs";
5
4
  import { ARCHETYPE_IDS, archetypeBrief } from "./archetypes.js";
@@ -65,114 +64,6 @@ export function keepProfile(profile, file = paths.profile) {
65
64
  else fs.rmSync(file, { force: true });
66
65
  }
67
66
 
68
- async function request(origin, token, init = {}) {
69
- const response = await fetch(
70
- `${String(origin).replace(/\/$/, "")}/api/mcp/profile`,
71
- {
72
- ...init,
73
- headers: {
74
- authorization: `Bearer ${token}`,
75
- "content-type": "application/json",
76
- },
77
- }
78
- );
79
- const body = await response.json().catch(() => null);
80
- if (!response.ok)
81
- throw Object.assign(
82
- new Error(body?.error || `Harness answered ${response.status}`),
83
- { status: response.status }
84
- );
85
- return body?.profile ?? {};
86
- }
87
-
88
- const preferenceCount = (profile) =>
89
- (profile.hardPreferences?.length ?? 0) +
90
- (profile.softPreferences?.length ?? 0);
91
-
92
- const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
93
-
94
- async function ask(ui, profile) {
95
- ui.note(
96
- "Your agents work for you, so they should know who you are. What you write here is saved to your Harness account, so Harness and the agents on all your computers use it. Change it any time in Harness, Settings, Profile.",
97
- "About you"
98
- );
99
- const name = await ui.text({
100
- message: "What should your agents call you?",
101
- validate: (value) =>
102
- String(value ?? "").trim().length > NAME_LIMIT
103
- ? `Keep it under ${NAME_LIMIT} characters`
104
- : undefined,
105
- });
106
- const displayName = String(name ?? "").trim();
107
- if (!displayName) return null;
108
- const update = { displayName };
109
- if (!preferenceCount(profile)) {
110
- const said = await ui.text({
111
- message:
112
- "Anything they should always keep in mind about how you work? Press Enter to skip.",
113
- placeholder: "Keep answers short, and ask before deleting anything",
114
- validate: (value) =>
115
- String(value ?? "").trim().length > PREFERENCE_LIMIT
116
- ? `Keep it under ${PREFERENCE_LIMIT} characters`
117
- : undefined,
118
- });
119
- const preference = String(said ?? "").trim();
120
- if (preference) update.hardPreferences = [preference];
121
- }
122
- return update;
123
- }
124
-
125
- /**
126
- * Setup's step: imports the person's profile into this computer, asking for their name (and one preference, when they
127
- * have none) if their account has no name yet. Never stops setup: a profile Harness cannot give leaves the last import.
128
- */
129
- export async function setupProfile({
130
- ui,
131
- origin,
132
- token,
133
- file = paths.profile,
134
- }) {
135
- let profile;
136
- try {
137
- profile = await request(origin, token);
138
- } catch (error) {
139
- // A Harness from before profiles reached computers has no such page: nothing is wrong, so nothing is said.
140
- if (error.status === 404) return readProfile(file);
141
- ui.warn(
142
- `Your Harness profile did not load (${error.message}). Your agents will learn your name the next time you run setup.`
143
- );
144
- return readProfile(file);
145
- }
146
- if (!profile.displayName) {
147
- const update = ui.interactive ? await ask(ui, profile) : null;
148
- if (!update) {
149
- ui.info(
150
- "Your agents will not know your name yet. Add it any time in Harness, Settings, Profile, then run setup again."
151
- );
152
- return null;
153
- }
154
- try {
155
- profile = await request(origin, token, {
156
- method: "PUT",
157
- body: JSON.stringify(update),
158
- });
159
- } catch (error) {
160
- // The agents here still get it; the next setup, finding no name in the account, asks again.
161
- profile = { ...profile, ...update };
162
- ui.warn(
163
- `Saved on this computer, but not to your Harness account yet (${error.message}).`
164
- );
165
- }
166
- }
167
- profile = boundedProfile(profile);
168
- writeJsonAtomic(file, profile);
169
- const count = preferenceCount(profile);
170
- ui.success(
171
- `Your agents know you as ${pc.bold(profile.displayName)}${count ? `, with your ${plural(count, "preference")} from Harness` : ""}`
172
- );
173
- return profile;
174
- }
175
-
176
67
  /**
177
68
  * The profile as an agent is told it at the start of a run; empty without one. It comes from Harness's server, so it
178
69
  * reads as what the person told Harness about how they like to work, never as instructions above the task, its
package/lib/projects.mjs CHANGED
@@ -783,7 +783,8 @@ export function createProjects({
783
783
  `${p.partner} left the project. This room stays here; nothing more goes between you.`
784
784
  );
785
785
  notifyDesktop(
786
- `${p.partner} left the project "${oneLine(p.title, 60)}".`
786
+ `${p.partner} left the project "${oneLine(p.title, 60)}".`,
787
+ { thread: p.roomId }
787
788
  );
788
789
  }
789
790
  return { ok: true };
@@ -1386,7 +1387,8 @@ export function createProjects({
1386
1387
  [work.id, ...result.with]
1387
1388
  );
1388
1389
  notifyDesktop(
1389
- `Work clashes in "${oneLine(p.title, 60)}": ${nameOf(agent)} waits while the agents settle it.`
1390
+ `Work clashes in "${oneLine(p.title, 60)}": ${nameOf(agent)} waits while the agents settle it.`,
1391
+ { thread: p.roomId }
1390
1392
  );
1391
1393
  start(
1392
1394
  "review",
@@ -1841,7 +1843,12 @@ export function createProjects({
1841
1843
  opened,
1842
1844
  `${opened.partner} joined. Their agents work here with yours from now on.`
1843
1845
  );
1844
- notifyDesktop(`${opened.partner} joined "${oneLine(opened.title, 60)}".`);
1846
+ notifyDesktop(
1847
+ `${opened.partner} joined "${oneLine(opened.title, 60)}".`,
1848
+ {
1849
+ thread: opened.roomId,
1850
+ }
1851
+ );
1845
1852
  } else
1846
1853
  note(
1847
1854
  opened,
@@ -1863,7 +1870,9 @@ export function createProjects({
1863
1870
  project(p.id),
1864
1871
  `${p.partner} left the project. This room stays here; nothing more goes between you.`
1865
1872
  );
1866
- notifyDesktop(`${p.partner} left the project "${oneLine(p.title, 60)}".`);
1873
+ notifyDesktop(`${p.partner} left the project "${oneLine(p.title, 60)}".`, {
1874
+ thread: p.roomId,
1875
+ });
1867
1876
  };
1868
1877
 
1869
1878
  const leave = (p) => {
@@ -2504,6 +2513,11 @@ export function createProjects({
2504
2513
  )?.status === "joining",
2505
2514
  title: invite.project.title,
2506
2515
  from: invite.project.from,
2516
+ at: invite.createdAt ?? null,
2517
+ // Who comes with the person inviting, by name: a computer on an older version says nothing here.
2518
+ theirAgents: channels
2519
+ .knownAgents(invite.project.agents)
2520
+ .map(nameOf),
2507
2521
  // The sender's computer's key, to compare with them before joining (pinned only on joining).
2508
2522
  fingerprint: invite.fingerprint ?? null,
2509
2523
  kind: invite.project.repo?.first ? "project" : "room",
@@ -0,0 +1,91 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { removeAgentConfigurations } from "./adapters.mjs";
4
+ import { detectAgents } from "./commands.mjs";
5
+ import { uninstallDesktop } from "./desktop.mjs";
6
+ import { readJson, writeJsonAtomic } from "./files.mjs";
7
+ import { removeNativeHost } from "./nativeHost.mjs";
8
+ import { uninstallService } from "./service.mjs";
9
+ import { removeLocalWakes } from "./wakes.mjs";
10
+
11
+ // Taking Harness off this computer: `tryharness uninstall`, and stopping setup before signing in (Ctrl-C in the
12
+ // installer, or Remove Harness in the setup window), which must leave nothing behind.
13
+
14
+ /**
15
+ * Remove what Harness set up here: the app and its login items, the browser's link to this computer, Harness in the
16
+ * person's agents, local wakes and what setup downloaded. The person's own things (board, history, keys, choices)
17
+ * stay unless `everything`; a Harness folder holding none of them, as before the first sign-in, goes whole.
18
+ * `agents` limits the agents undone to those setup changed (all when omitted). The background service goes after the
19
+ * app when `stopService`; otherwise it is the caller's to stop, since it may be the caller. Returns whether the
20
+ * folder went.
21
+ */
22
+ export function removeHarnessHere({
23
+ paths,
24
+ everything = false,
25
+ agents = null,
26
+ stopService = false,
27
+ }) {
28
+ // The app first, so its window goes the moment someone backs out, before the slower steps below.
29
+ uninstallDesktop();
30
+ if (stopService) uninstallService();
31
+ removeNativeHost();
32
+ undoAgents(agents);
33
+ const nothingOfTheirs = !fs.existsSync(paths.database);
34
+ const wholeFolder = everything || nothingOfTheirs;
35
+ const removed = wholeFolder
36
+ ? [paths.home]
37
+ : [...downloadedParts(paths), paths.status, paths.socket];
38
+ for (const target of removed)
39
+ try {
40
+ fs.rmSync(target, { recursive: true, force: true });
41
+ } catch {}
42
+ if (!wholeFolder) keepChoicesOnly(paths.config);
43
+ return { folderRemoved: wholeFolder };
44
+ }
45
+
46
+ /** Stop setup before sign-in from the daemon itself: everything goes, the service last, because stopping it ends us. */
47
+ export function stopSetupHere({ paths }) {
48
+ const result = removeHarnessHere({ paths, agents: chosenAgents(paths) });
49
+ uninstallService();
50
+ return result;
51
+ }
52
+
53
+ /** The agents setup set up before sign-in: the ones the person chose on an earlier install, if any. */
54
+ export function chosenAgents(paths) {
55
+ return readJson(paths.config, {}).swarmAgents ?? [];
56
+ }
57
+
58
+ // Each agent's Harness setup is undone through its own CLI, a second or so apiece, so only the ones changed are.
59
+ function undoAgents(agents) {
60
+ if (agents === null) {
61
+ removeAgentConfigurations();
62
+ removeLocalWakes();
63
+ return;
64
+ }
65
+ if (!agents.length) return;
66
+ removeAgentConfigurations({
67
+ detected: detectAgents().filter((found) => agents.includes(found.agent)),
68
+ });
69
+ if (agents.some((agent) => LOCAL_WAKE_AGENTS.includes(agent)))
70
+ removeLocalWakes();
71
+ }
72
+
73
+ // The agents woken through their own local setup (wakes.mjs).
74
+ const LOCAL_WAKE_AGENTS = ["openclaw", "hermes"];
75
+
76
+ // What setup downloaded into the Harness folder: the daemon's runtime, its command, local models and their engine.
77
+ function downloadedParts(paths) {
78
+ return [
79
+ paths.runtime,
80
+ path.join(paths.home, "bin"),
81
+ paths.models,
82
+ path.join(paths.home, "local"),
83
+ ];
84
+ }
85
+
86
+ // The pairing goes; the person's choices stay (who is in their swarm, who they took out), so setting up again keeps
87
+ // their swarm (a reinstall once came back without Bankr, Quotient, Grok Bot and Muse).
88
+ function keepChoicesOnly(configPath) {
89
+ const { token: _token, ...choices } = readJson(configPath, {});
90
+ if (Object.keys(choices).length) writeJsonAtomic(configPath, choices);
91
+ }
@@ -181,6 +181,7 @@ export function createRoomChannels({
181
181
  settings: room.settings,
182
182
  history: room.history,
183
183
  members: room.members,
184
+ agents: room.agents,
184
185
  ...details(room.id),
185
186
  });
186
187
  const sending = new Set();
@@ -643,6 +644,7 @@ export function createRoomChannels({
643
644
  invite,
644
645
  // Whether an invitation names its real sender and this person, as join requires; throws why not.
645
646
  validate: validateInvite,
647
+ knownAgents,
646
648
  join,
647
649
  setAgents,
648
650
  opened,
package/lib/runner.mjs CHANGED
@@ -9,7 +9,7 @@ import { agentEnvironment } from "./agentnode.mjs";
9
9
  import { runtimeOf } from "./agentRuntimeConfig.mjs";
10
10
  import { runProtocolTask } from "./agentRuntimes.mjs";
11
11
  import { scrubValues } from "./vault.mjs";
12
- import { historyRoots, paths } from "./paths.mjs";
12
+ import { harnessNode, historyRoots, paths } from "./paths.mjs";
13
13
 
14
14
  const running = new Set();
15
15
  const children = new Map();
@@ -312,7 +312,7 @@ export const restrictedClaudeSettings = (cwd, home = os.homedir()) => ({
312
312
  export const restrictedMcpConfig = () => ({
313
313
  mcpServers: {
314
314
  harness: {
315
- command: process.execPath,
315
+ command: harnessNode(),
316
316
  args: [
317
317
  fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)),
318
318
  "--agent",
@@ -554,7 +554,7 @@ export function agentInvocation(task, { executable = null } = {}) {
554
554
  'approval_policy="never"',
555
555
  // Only Harness's board, as for restricted Claude Code: none of the person's other MCP servers.
556
556
  "-c",
557
- `mcp_servers={harness={command=${JSON.stringify(process.execPath)},args=${JSON.stringify([fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)), "--agent", "codex", "--restricted"])}}}`,
557
+ `mcp_servers={harness={command=${JSON.stringify(harnessNode())},args=${JSON.stringify([fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)), "--agent", "codex", "--restricted"])}}}`,
558
558
  "-c",
559
559
  'mcp_servers.harness.default_tools_approval_mode="approve"',
560
560
  ]
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { createRequire } from "node:module";
6
6
  import { ensureDir, readJson, writeJsonAtomic } from "./files.mjs";
7
- import { paths } from "./paths.mjs";
7
+ import { harnessNode, paths } from "./paths.mjs";
8
8
  import {
9
9
  RELEASE_ENTRIES,
10
10
  RELEASE_FILE,
@@ -193,7 +193,7 @@ const launcherFile = () =>
193
193
  path.join(paths.home, "bin", WINDOWS ? "tryharness.cmd" : "tryharness");
194
194
 
195
195
  // The person's command for this computer's Harness: it runs the installed release, never whatever npm has newest.
196
- function writeLauncher(release, nodePath = process.execPath) {
196
+ function writeLauncher(release, nodePath = harnessNode()) {
197
197
  const entry = path.join(release, "cli.mjs");
198
198
  const script = WINDOWS
199
199
  ? `@"${nodePath}" "${entry}" %*\r\n`
@@ -218,6 +218,26 @@ export function relayCommand(words = "") {
218
218
  return `${shown.includes(" ") ? JSON.stringify(shown) : shown}${tail}`;
219
219
  }
220
220
 
221
+ /**
222
+ * Before `tryharness upgrade` sets up a checked release: a computer that runs Harness on its own Node (~/.harness/node,
223
+ * from install.sh) gets the Node the release pins, by the release's own install.sh, so it is downloaded and checked
224
+ * the same way as at install. The Node here stays until the new one is checked and in place. A computer set up with
225
+ * plain npx has no Node of Harness's own and keeps the one it runs on.
226
+ */
227
+ export function updateHarnessNode(releaseRoot) {
228
+ const installer = path.join(releaseRoot, "assets", "install.sh");
229
+ const hasOwnNode = fs.existsSync(paths.node);
230
+ if (WINDOWS || !hasOwnNode || !fs.existsSync(installer)) return;
231
+ const updated = spawnSync("sh", [installer, "--node-only"], {
232
+ stdio: "inherit",
233
+ env: { ...process.env, HARNESS_HOME: paths.home },
234
+ });
235
+ if (updated.status !== 0)
236
+ throw new Error(
237
+ "could not bring the Node.js this release runs on, so it was not set up. Nothing was changed."
238
+ );
239
+ }
240
+
221
241
  /**
222
242
  * `tryharness upgrade`: fetches a release from npm without running any of it (no install scripts), and keeps it only
223
243
  * when it is signed with a key the installed runtime trusts. Returns where it is unpacked, for setup to run from
package/lib/screen.mjs ADDED
@@ -0,0 +1,133 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+
5
+ // Whether setup can show its screens on this computer, or has to give the person a code to type on another one.
6
+ // Only certain facts say there is no screen: no buddy is built for this computer, or this user has no desktop
7
+ // session. Where there is a screen, the buddy opens and the code is printed as well, so a wrong guess only means
8
+ // typing a code. Signs that the person is remote (a login over SSH or mosh above the installer) put the code first
9
+ // and leave the screen alone; the person can say otherwise with --screen or --no-screen.
10
+
11
+ // The computers a buddy is built for (cli/package.json's tryharness-desktop-* packages).
12
+ const BUDDY_BUILT = ["darwin-arm64", "darwin-x64", "linux-x64"];
13
+ // What runs a login from another computer.
14
+ const REMOTE = /^(sshd|sshd-session|mosh-server)$/;
15
+
16
+ const run = (command, args) =>
17
+ spawnSync(command, args, { encoding: "utf8", timeout: 3_000 });
18
+
19
+ /**
20
+ * Where setup shows. `facts` are what `readScreenFacts` reads; kept apart so the rule can be checked on its own.
21
+ * Returns { show: "screen" | "code-first" | "code-only", why }.
22
+ */
23
+ export function whereSetupShows({ buddyBuilt, desktopSession, remote, asked }) {
24
+ if (!buddyBuilt)
25
+ return { show: "code-only", why: "no Harness app for this computer" };
26
+ if (!desktopSession)
27
+ return { show: "code-only", why: "no desktop on this computer" };
28
+ if (asked === "screen") return { show: "screen", why: "asked for" };
29
+ if (asked === "code") return { show: "code-first", why: "asked for" };
30
+ if (remote) return { show: "code-first", why: "signed in from elsewhere" };
31
+ return { show: "screen", why: "at this computer" };
32
+ }
33
+
34
+ /** Read the facts `whereSetupShows` decides on, for the installer running as `pid`. */
35
+ export function readScreenFacts({
36
+ table,
37
+ pid = process.pid,
38
+ env = process.env,
39
+ platform = process.platform,
40
+ arch = process.arch,
41
+ argv = process.argv,
42
+ }) {
43
+ return {
44
+ buddyBuilt: BUDDY_BUILT.includes(`${platform}-${arch}`),
45
+ desktopSession: hasDesktopSession({ env, platform }),
46
+ remote: isRemote({ table, pid }),
47
+ asked: argv.includes("--screen")
48
+ ? "screen"
49
+ : argv.includes("--no-screen")
50
+ ? "code"
51
+ : null,
52
+ };
53
+ }
54
+
55
+ /** Whether the person running setup has a desktop on this computer: on a Mac, a login at its screen. */
56
+ function hasDesktopSession({ env, platform }) {
57
+ // Run with sudo, the desktop to look for is the person's who ran it, not root's.
58
+ const uid = Number(env.SUDO_UID) || os.userInfo().uid;
59
+ if (platform === "darwin")
60
+ return run("launchctl", ["print", `gui/${uid}`]).status === 0;
61
+ if (platform === "linux") {
62
+ if (env.DISPLAY || env.WAYLAND_DISPLAY) return true;
63
+ return graphicalLinuxSession(uid);
64
+ }
65
+ return false;
66
+ }
67
+
68
+ /** A graphical login (X11 or Wayland) of this user that systemd knows, for when the environment does not say. */
69
+ function graphicalLinuxSession(uid) {
70
+ const listed = run("loginctl", ["list-sessions", "--no-legend"]);
71
+ if (listed.status !== 0) return false;
72
+ return (listed.stdout || "")
73
+ .split("\n")
74
+ .map((line) => line.trim().split(/\s+/))
75
+ .filter(([id, user]) => id && Number(user) === uid)
76
+ .some(([id]) => {
77
+ const shown = run("loginctl", ["show-session", id, "-p", "Type"]);
78
+ return /Type=(x11|wayland)/.test(shown.stdout || "");
79
+ });
80
+ }
81
+
82
+ /**
83
+ * Whether the installer was started from another computer: a login over SSH or mosh among the processes above it.
84
+ * Inside tmux the processes above lead to the tmux server, started whenever the session was, so the walk starts from
85
+ * the tmux client showing this session now.
86
+ */
87
+ function isRemote({ table, pid }) {
88
+ if (!table?.size) return false;
89
+ const start = tmuxClientOf(table, pid) ?? pid;
90
+ for (let current = start, steps = 0; current > 1 && steps < 64; steps++) {
91
+ const row = table.get(current);
92
+ if (!row) return false;
93
+ if (REMOTE.test(path.basename(row.comm))) return true;
94
+ current = row.ppid;
95
+ }
96
+ return false;
97
+ }
98
+
99
+ /** The process id of the tmux client showing the pane `pid` runs in, or null outside tmux. */
100
+ function tmuxClientOf(table, pid) {
101
+ const tty = table.get(pid)?.tty;
102
+ if (!tty || !underTmux(table, pid)) return null;
103
+ const panes = run("tmux", [
104
+ "list-panes",
105
+ "-a",
106
+ "-F",
107
+ "#{pane_tty}\t#{session_name}",
108
+ ]);
109
+ const session = (panes.stdout || "")
110
+ .split("\n")
111
+ .map((line) => line.split("\t"))
112
+ .find(([paneTty]) => paneTty === tty || paneTty === `/dev/${tty}`)?.[1];
113
+ if (!session) return null;
114
+ const clients = run("tmux", [
115
+ "list-clients",
116
+ "-t",
117
+ session,
118
+ "-F",
119
+ "#{client_pid}",
120
+ ]);
121
+ const clientPid = Number((clients.stdout || "").split("\n")[0]);
122
+ return clientPid > 1 ? clientPid : null;
123
+ }
124
+
125
+ function underTmux(table, pid) {
126
+ for (let current = pid, steps = 0; current > 1 && steps < 64; steps++) {
127
+ const row = table.get(current);
128
+ if (!row) return false;
129
+ if (/^tmux\b/.test(path.basename(row.comm))) return true;
130
+ current = row.ppid;
131
+ }
132
+ return false;
133
+ }
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { spawn } from "node:child_process";
4
4
  import { fileURLToPath } from "node:url";
5
- import { paths } from "./paths.mjs";
5
+ import { harnessNode, paths } from "./paths.mjs";
6
6
 
7
7
  const CLI = fileURLToPath(new URL("../cli.mjs", import.meta.url));
8
8
 
@@ -22,11 +22,11 @@ export function startUpdate(spec, { from, log = () => {} }) {
22
22
  out,
23
23
  `${new Date().toISOString()} updating from ${from} to ${spec}, as the person asked from home\n`
24
24
  );
25
- const child = spawn(
26
- process.execPath,
27
- [CLI, "upgrade", spec, "--no-desktop"],
28
- { detached: true, stdio: ["ignore", out, out], env: process.env }
29
- );
25
+ const child = spawn(harnessNode(), [CLI, "upgrade", spec, "--no-desktop"], {
26
+ detached: true,
27
+ stdio: ["ignore", out, out],
28
+ env: process.env,
29
+ });
30
30
  child.unref();
31
31
  } finally {
32
32
  fs.closeSync(out);