tryharness 0.7.81 → 0.7.83

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 (48) 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 +19 -1
  8. package/lib/browserPage.mjs +30 -0
  9. package/lib/cards.mjs +5 -2
  10. package/lib/daemon.mjs +103 -5
  11. package/lib/desktop.mjs +7 -1
  12. package/lib/dispatcher.mjs +12 -2
  13. package/lib/environments.mjs +4 -11
  14. package/lib/goalCommands.mjs +2 -1
  15. package/lib/hookDialects.mjs +2 -1
  16. package/lib/jobAnswers.mjs +2 -1
  17. package/lib/localStack.mjs +24 -9
  18. package/lib/mcp-stdio.mjs +6 -0
  19. package/lib/members.json +1 -1
  20. package/lib/museSession.mjs +2 -1
  21. package/lib/nativeHost.mjs +11 -2
  22. package/lib/network.mjs +1 -0
  23. package/lib/notify.mjs +48 -16
  24. package/lib/onboard.mjs +71 -366
  25. package/lib/ownMachines.mjs +4 -1
  26. package/lib/pairing.mjs +0 -84
  27. package/lib/paths.mjs +17 -0
  28. package/lib/personNotices.mjs +9 -25
  29. package/lib/profile.mjs +0 -109
  30. package/lib/projects.mjs +18 -4
  31. package/lib/removeHarness.mjs +91 -0
  32. package/lib/roomChannels.mjs +2 -0
  33. package/lib/runner.mjs +3 -3
  34. package/lib/runtime-install.mjs +22 -2
  35. package/lib/screen.mjs +133 -0
  36. package/lib/selfUpdate.mjs +6 -6
  37. package/lib/service.mjs +120 -7
  38. package/lib/sessionControl.mjs +10 -0
  39. package/lib/setupChoices.mjs +400 -0
  40. package/lib/setupMode.mjs +137 -0
  41. package/lib/t3.mjs +23 -14
  42. package/lib/threadActions.mjs +2 -1
  43. package/lib/toolCheck.mjs +136 -0
  44. package/lib/ui.mjs +15 -1
  45. package/lib/wakes.mjs +3 -3
  46. package/npm-shrinkwrap.json +14 -14
  47. package/package.json +4 -4
  48. package/release.json +49 -42
package/lib/service.mjs CHANGED
@@ -3,9 +3,9 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { spawn } from "node:child_process";
5
5
  import { detectAgents, run } from "./commands.mjs";
6
- import { ensureDir } from "./files.mjs";
7
- import { paths } from "./paths.mjs";
8
- import { appProgram } from "./desktop.mjs";
6
+ import { ensureDir, writeJsonAtomic } from "./files.mjs";
7
+ import { harnessNode, paths } from "./paths.mjs";
8
+ import { appProgram, BUNDLE_ID } from "./desktop.mjs";
9
9
 
10
10
  const LABEL = "ai.tryharness.daemon";
11
11
 
@@ -80,7 +80,7 @@ function windowsUser(env = process.env) {
80
80
 
81
81
  export function installWindowsTask({
82
82
  runtimeRoot,
83
- nodePath = process.execPath,
83
+ nodePath = harnessNode(),
84
84
  execute = run,
85
85
  env = process.env,
86
86
  }) {
@@ -136,6 +136,8 @@ export function uninstallWindowsTask({ execute = run } = {}) {
136
136
 
137
137
  function agentPath() {
138
138
  const dirs = new Set([
139
+ path.dirname(harnessNode()),
140
+ // The Node setup ran on stays reachable for the person's own tools, after Harness's own.
139
141
  path.dirname(process.execPath),
140
142
  "/opt/homebrew/bin",
141
143
  "/usr/local/bin",
@@ -182,10 +184,73 @@ function retireLegacyBridge() {
182
184
  }
183
185
  }
184
186
 
187
+ // The Harness app's one background item on a Mac (packages/desktop/helper/ai.tryharness.agent.plist), which the app
188
+ // registers when setup finishes so macOS announces it once and by the app's name. Until then the daemon runs through
189
+ // the app's launcher outside launchd, which macOS does not announce; the launcher's pid is kept to stop it by.
190
+ const APP_LABEL = "ai.tryharness.agent";
191
+ const launcherPidFile = () => path.join(paths.home, "launcher.pid");
192
+
193
+ /** Whether this Mac's daemon runs as the Harness app's background item rather than the installer's own launchd plist. */
194
+ export function appRunsService(platform = process.platform) {
195
+ const launcher = appProgram("HarnessDaemon", { platform });
196
+ if (!launcher) return false;
197
+ const item = path.join(
198
+ path.dirname(launcher),
199
+ "..",
200
+ "Library",
201
+ "LaunchAgents",
202
+ `${APP_LABEL}.plist`
203
+ );
204
+ return fs.existsSync(item) && !fs.existsSync(servicePath(platform));
205
+ }
206
+
207
+ /** Whether Harness is still set to run here: its service, or the launcher setup started, is there. */
208
+ export function serviceRunning(platform = process.platform) {
209
+ if (platform === "darwin" && appRunsService(platform))
210
+ return appItemLoaded() || launcherPid() !== null;
211
+ const file = servicePath(platform);
212
+ return !file || fs.existsSync(file);
213
+ }
214
+
215
+ function appItemLoaded() {
216
+ return run("launchctl", ["print", `gui/${process.getuid()}/${APP_LABEL}`]).ok;
217
+ }
218
+
219
+ /** The launcher setup started, while it runs: its pid, or null. */
220
+ function launcherAlive() {
221
+ const pid = Number(fs.readFileSync(launcherPidFile(), "utf8").trim() || 0);
222
+ if (!pid) return null;
223
+ // An exited launcher this process started stays listed (a zombie) until this process reaps it, which it cannot do
224
+ // while it waits here synchronously: ps tells running from exited.
225
+ const state = run("ps", ["-o", "stat=", "-p", String(pid)]).stdout?.trim();
226
+ return state && !state.startsWith("Z") ? pid : null;
227
+ }
228
+
229
+ function launcherPid() {
230
+ try {
231
+ return launcherAlive();
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+
237
+ /** Stop the launcher setup started, by its pid, and wait for it to go. */
238
+ function stopLauncher() {
239
+ const pid = launcherPid();
240
+ if (!pid) return;
241
+ try {
242
+ process.kill(pid, "SIGTERM");
243
+ } catch {}
244
+ for (let waited = 0; waited < 5_000 && launcherPid(); waited += 100)
245
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
246
+ fs.rmSync(launcherPidFile(), { force: true });
247
+ }
248
+
185
249
  /** Whether the Harness app's launcher is here on a Mac but the daemon does not start through it yet. */
186
250
  export function launcherMissing(platform = process.platform) {
187
251
  if (platform !== "darwin" || !appProgram("HarnessDaemon", { platform }))
188
252
  return false;
253
+ if (appRunsService(platform)) return false;
189
254
  try {
190
255
  return !fs
191
256
  .readFileSync(servicePath(platform), "utf8")
@@ -197,7 +262,7 @@ export function launcherMissing(platform = process.platform) {
197
262
 
198
263
  export function installService({
199
264
  runtimeRoot,
200
- nodePath = process.execPath,
265
+ nodePath = harnessNode(),
201
266
  platform = process.platform,
202
267
  execute = run,
203
268
  }) {
@@ -209,8 +274,17 @@ export function installService({
209
274
  return installWindowsTask({ runtimeRoot, nodePath, execute });
210
275
  if (platform === "darwin") {
211
276
  const plist = servicePath(platform);
212
- // Through the Harness app's launcher when the app is here, so macOS asks for the person's folders as Harness.
277
+ // Through the Harness app's launcher when the app is here, so macOS asks for the person's folders as Harness, and
278
+ // tied to the app, so Login Items and the background-activity notice name Harness rather than its signer or Node.
213
279
  const launcher = appProgram("HarnessDaemon", { platform });
280
+ // What the launcher runs when the app's background item, or the app itself, starts it with no arguments.
281
+ if (launcher)
282
+ writeJsonAtomic(path.join(paths.home, "service.json"), {
283
+ program: [nodePath, entry, "daemon"],
284
+ path: envPath,
285
+ log: paths.log,
286
+ });
287
+ if (launcher && appRunsService(platform)) return startThroughApp(launcher);
214
288
  const program = [
215
289
  ...(launcher ? [launcher] : []),
216
290
  nodePath,
@@ -225,7 +299,7 @@ export function installService({
225
299
  `<?xml version="1.0" encoding="UTF-8"?>
226
300
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
227
301
  <plist version="1.0"><dict>
228
- <key>Label</key><string>${LABEL}</string>
302
+ <key>Label</key><string>${LABEL}</string>${launcher ? `\n <key>AssociatedBundleIdentifiers</key><string>${BUNDLE_ID}</string>` : ""}
229
303
  <key>ProgramArguments</key><array>${program.map((arg) => `<string>${xml(arg)}</string>`).join("")}</array>
230
304
  <key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(envPath)}</string><key>MallocLargeCache</key><string>0</string></dict>
231
305
  <key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer>
@@ -293,10 +367,49 @@ export function installService({
293
367
  return { manager: "detached", file: null };
294
368
  }
295
369
 
370
+ // The app's background item restarts onto a new release at once; before setup registered it, the launcher setup
371
+ // started is replaced by one running this release.
372
+ function startThroughApp(launcher) {
373
+ if (appItemLoaded()) {
374
+ run("launchctl", [
375
+ "kickstart",
376
+ "-k",
377
+ `gui/${process.getuid()}/${APP_LABEL}`,
378
+ ]);
379
+ return { manager: "Harness app" };
380
+ }
381
+ stopLauncher();
382
+ // The app starts it (background.rs run_daemon_now), so macOS counts the daemon's folder reads as Harness's, not as
383
+ // this terminal's (seen November 3: picking a folder in setup asked nothing). Without a screen to open the app on,
384
+ // or an app that does not start it, the launcher starts here.
385
+ const app = path.resolve(path.dirname(launcher), "..", "..");
386
+ if (run("open", ["-g", app]).ok && waitFor(() => launcherPid() !== null))
387
+ return { manager: "Harness app" };
388
+ const child = spawn(launcher, [], { detached: true, stdio: "ignore" });
389
+ child.unref();
390
+ fs.writeFileSync(launcherPidFile(), String(child.pid));
391
+ return { manager: "Harness app" };
392
+ }
393
+
394
+ // How long the app may take to open and start the daemon; past it the installer starts the daemon itself, which still
395
+ // works, counted as the terminal's. Measured November 3 on the owner's M5 Pro, 3 scripted installs, from the installer's
396
+ // start (so an upper bound on open→daemon): 4.5 s on the first (app just installed, cold) and 1.6 s twice after, the
397
+ // daemon each time within 0.5 s of the app coming up. 10 s is over twice the cold one.
398
+ const APP_STARTS_DAEMON_MS = 10_000;
399
+
400
+ function waitFor(condition) {
401
+ for (let waited = 0; waited < APP_STARTS_DAEMON_MS; waited += 200) {
402
+ if (condition()) return true;
403
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
404
+ }
405
+ return false;
406
+ }
407
+
296
408
  export function uninstallService({
297
409
  platform = process.platform,
298
410
  execute = run,
299
411
  } = {}) {
412
+ if (platform === "darwin") stopLauncher();
300
413
  const file = servicePath(platform);
301
414
  if (platform === "win32") {
302
415
  uninstallWindowsTask({ execute });
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { paths } from "./paths.mjs";
4
+ import { readJson } from "./files.mjs";
4
5
  import { runningPids, runningProcesses } from "./runner.mjs";
5
6
  import { PROCESS_NAMES, nativeSessionId } from "./swarm.mjs";
6
7
  import { member, nameOf } from "./members.mjs";
@@ -488,10 +489,17 @@ export function createSessionControl({
488
489
  .sort((a, b) => b.count - a.count)[0]?.place;
489
490
  return (seeded.homes[agentId] =
490
491
  seen ??
492
+ picked().all ??
491
493
  (CODING_AGENTS.includes(agentId) && terminal
492
494
  ? terminalPlace(terminal)
493
495
  : null));
494
496
  };
497
+ // Where the person said threads open, in setup or settings (setupChoices.mjs): `all` when Harness cannot tell where
498
+ // they work, and per agent, which always wins for that agent.
499
+ const picked = () => {
500
+ const workplace = readJson(paths.config, {}).workplace ?? {};
501
+ return { all: workplace.all ?? null, agents: workplace.agents ?? {} };
502
+ };
495
503
  /** A place with the app that opens it now (T3's running build, an editor's install); null when it is not on this computer. */
496
504
  const usable = (place) => {
497
505
  if (!place) return null;
@@ -516,6 +524,8 @@ export function createSessionControl({
516
524
  return place;
517
525
  };
518
526
  const homeOf = (agentId) => {
527
+ const chosen = usable(picked().agents[agentId]);
528
+ if (chosen) return chosen;
519
529
  const tally = new Map();
520
530
  for (const place of Object.values(placesOf(agentId))) {
521
531
  if (!place?.kind || place.kind === "unknown") continue;
@@ -0,0 +1,400 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { readJson, writeJsonAtomic } from "./files.mjs";
6
+ import { appDirs, EDITOR_IDS, editorInstall, t3App } from "./places.mjs";
7
+ import { herdrInstalled } from "./herdr.mjs";
8
+ import { processTable } from "./live.mjs";
9
+
10
+ // What the setup screens choose, kept in the config the rest of Harness reads: where threads open (`workplace`,
11
+ // sessionControl.mjs homeOf) and which of the folders macOS guards file search may read (`searchFolders`,
12
+ // localStack.mjs). Asked for by the app's setup window and its settings, on the control socket.
13
+
14
+ // The folders macOS asks about before any program reads them; nothing reads one the person did not pick.
15
+ const ASKED = ["Downloads", "Documents", "Desktop"];
16
+ // Terminals Open can start a session in on a Mac (sessionControl.mjs), by their app's name.
17
+ const MAC_TERMINALS = [
18
+ "Ghostty",
19
+ "iTerm",
20
+ "WezTerm",
21
+ "Warp",
22
+ "kitty",
23
+ "Alacritty",
24
+ "Hyper",
25
+ ];
26
+ const EDITOR_NAMES = {
27
+ cursor: "Cursor",
28
+ windsurf: "Windsurf",
29
+ "vscode-insiders": "VS Code Insiders",
30
+ vscode: "VS Code",
31
+ };
32
+ const FOUND_AT_MOST = 8;
33
+ // A folder as the person reads it: their home as ~.
34
+ const shown = (folder) => {
35
+ const home = os.homedir();
36
+ const inHome = folder === home || folder.startsWith(home + path.sep);
37
+ return {
38
+ path: folder,
39
+ name: inHome ? "~" + folder.slice(home.length) : folder,
40
+ };
41
+ };
42
+
43
+ const COMMANDS = new Set([
44
+ "setup.apps",
45
+ "setup.workplace",
46
+ "setup.folders",
47
+ "setup.folder",
48
+ "setup.findFolders",
49
+ ]);
50
+
51
+ /**
52
+ * Everything Harness can open threads in that is on this computer, open ones first: T3 Code, the editors, the Mac
53
+ * terminals, herdr and Neovim. On Linux only those it can open there: T3 Code, the editors whose command-line tool is
54
+ * installed and herdr (terminals, and so Neovim, do not open from Harness on Linux yet).
55
+ */
56
+ export function appsHere({
57
+ platform = process.platform,
58
+ running = runningApps(),
59
+ } = {}) {
60
+ const apps = [];
61
+ const t3 = t3App();
62
+ if (t3)
63
+ apps.push({
64
+ id: "t3",
65
+ name: "T3 Code",
66
+ app: t3.app,
67
+ place: { kind: "t3", name: "T3 Code" },
68
+ });
69
+ for (const id of EDITOR_IDS) {
70
+ const install =
71
+ platform === "darwin" ? editorInstall(id) : editorOnPath(id);
72
+ if (install)
73
+ apps.push({
74
+ id,
75
+ name: EDITOR_NAMES[id],
76
+ app: install.app,
77
+ place: {
78
+ kind: "editor",
79
+ editor: id,
80
+ name: EDITOR_NAMES[id],
81
+ app: install.app,
82
+ cli: install.cli,
83
+ surface: "terminal",
84
+ },
85
+ });
86
+ }
87
+ if (platform === "darwin") {
88
+ for (const name of MAC_TERMINALS) {
89
+ const app = appIn(`${name}.app`);
90
+ if (app)
91
+ apps.push({
92
+ id: name.toLowerCase(),
93
+ name,
94
+ app,
95
+ place: terminal(name, app),
96
+ });
97
+ }
98
+ const appleTerminal = "/System/Applications/Utilities/Terminal.app";
99
+ apps.push({
100
+ id: "terminal",
101
+ name: "Terminal",
102
+ app: appleTerminal,
103
+ place: terminal("Terminal", appleTerminal),
104
+ });
105
+ }
106
+ // Places Harness opens threads in that are not apps: herdr (its tabs, through its own server) and, on a Mac, Neovim
107
+ // (in a tab of a Neovim already open, else the terminal picked above, or the one open now, running it).
108
+ if (herdrInstalled({}))
109
+ apps.push({
110
+ id: "herdr",
111
+ name: "herdr",
112
+ app: null,
113
+ place: { kind: "herdr", name: "herdr" },
114
+ });
115
+ if (platform === "darwin" && commandOnPath("nvim")) {
116
+ const terminals = apps.filter((entry) => entry.place.kind === "terminal");
117
+ const host =
118
+ terminals.find((entry) =>
119
+ running.some((comm) => comm.startsWith(`${entry.app}/`))
120
+ ) ?? terminals[0];
121
+ apps.push({
122
+ id: "nvim",
123
+ name: "Neovim",
124
+ app: null,
125
+ place: { kind: "nvim", name: "Neovim", app: host?.app ?? null },
126
+ });
127
+ }
128
+ const isOpen = (entry) =>
129
+ Boolean(entry.app) &&
130
+ running.some((comm) => comm.startsWith(`${entry.app}/`));
131
+ return apps
132
+ .map((entry) => ({ ...entry, running: isOpen(entry) }))
133
+ .sort((a, b) => Number(b.running) - Number(a.running))
134
+ .map((entry) => ({ ...entry, icon: appIcon(entry.app) }));
135
+ }
136
+
137
+ // Each app's own icon on a Mac, as a small PNG the setup screen can show: read from the app's icns with sips, which
138
+ // macOS has built in, once per app. Elsewhere, or for an app without an icns, the screen shows its initials.
139
+ const icons = new Map();
140
+ function appIcon(app, platform = process.platform) {
141
+ if (platform !== "darwin" || !app?.endsWith(".app")) return null;
142
+ if (icons.has(app)) return icons.get(app);
143
+ let icon = null;
144
+ try {
145
+ const named = spawnSync(
146
+ "plutil",
147
+ [
148
+ "-extract",
149
+ "CFBundleIconFile",
150
+ "raw",
151
+ path.join(app, "Contents", "Info.plist"),
152
+ ],
153
+ { encoding: "utf8", timeout: 3_000 }
154
+ );
155
+ const file = (named.stdout || "").trim();
156
+ const icns = path.join(
157
+ app,
158
+ "Contents",
159
+ "Resources",
160
+ file.endsWith(".icns") ? file : `${file}.icns`
161
+ );
162
+ if (file && fs.existsSync(icns)) {
163
+ const out = path.join(
164
+ os.tmpdir(),
165
+ `harness-icon-${process.pid}-${icons.size}.png`
166
+ );
167
+ const made = spawnSync(
168
+ "sips",
169
+ ["-s", "format", "png", "-Z", "64", icns, "--out", out],
170
+ { timeout: 5_000 }
171
+ );
172
+ if (made.status === 0 && fs.existsSync(out)) {
173
+ icon = `data:image/png;base64,${fs.readFileSync(out).toString("base64")}`;
174
+ fs.rmSync(out, { force: true });
175
+ }
176
+ }
177
+ } catch {}
178
+ icons.set(app, icon);
179
+ return icon;
180
+ }
181
+
182
+ const terminal = (name, app) => ({ kind: "terminal", name, app });
183
+
184
+ function appIn(file) {
185
+ for (const dir of appDirs()) {
186
+ const at = path.join(dir, file);
187
+ if (fs.existsSync(at)) return at;
188
+ }
189
+ return null;
190
+ }
191
+
192
+ function editorOnPath(id) {
193
+ const cli = { cursor: "cursor", windsurf: "windsurf", vscode: "code" }[id];
194
+ const at = cli ? commandOnPath(cli) : null;
195
+ return at ? { app: path.dirname(at), cli: at } : null;
196
+ }
197
+
198
+ function commandOnPath(name) {
199
+ const found = spawnSync("sh", ["-c", `command -v ${name}`], {
200
+ encoding: "utf8",
201
+ });
202
+ const at = (found.stdout || "").trim();
203
+ return found.status === 0 && at ? at : null;
204
+ }
205
+
206
+ function runningApps() {
207
+ return [...processTable({ fresh: true }).values()].map((row) => row.comm);
208
+ }
209
+
210
+ /**
211
+ * Folders whose name holds `query`'s letters in order, for setup's "+ Add": the folders the person already works in
212
+ * first, then the folders in their home and, on a Mac, the folders Spotlight already knows by name. Never lists the
213
+ * inside of a folder macOS guards, which would set off the very prompt this avoids.
214
+ */
215
+ export function findFolders(query, { known = [], home = os.homedir() } = {}) {
216
+ const wanted = String(query || "").toLowerCase();
217
+ if (!wanted) return known.slice(0, FOUND_AT_MOST);
218
+ const matches = (folder) =>
219
+ inOrder(path.basename(folder).toLowerCase(), wanted);
220
+ const top = topFolders(home);
221
+ const spotlight =
222
+ process.platform === "darwin" ? spotlightFolders(wanted) : [];
223
+ return [...new Set([...known, ...top, ...spotlight])]
224
+ .filter(matches)
225
+ .slice(0, FOUND_AT_MOST);
226
+ }
227
+
228
+ function inOrder(name, letters) {
229
+ let at = 0;
230
+ for (const letter of name) if (letter === letters[at]) at++;
231
+ return at === letters.length;
232
+ }
233
+
234
+ // Folders in the home folder and two levels into each, skipping hidden ones, Library, the folders macOS guards and
235
+ // what holds no one's own work (node_modules), so listing them never sets off a macOS prompt.
236
+ const SKIP = new Set(["Library", "node_modules", ...ASKED]);
237
+ function topFolders(home, depth = 3) {
238
+ const found = [];
239
+ const walk = (dir, level) => {
240
+ let entries = [];
241
+ try {
242
+ entries = fs.readdirSync(dir, { withFileTypes: true });
243
+ } catch {
244
+ return;
245
+ }
246
+ for (const entry of entries) {
247
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
248
+ if (SKIP.has(entry.name)) continue;
249
+ const at = path.join(dir, entry.name);
250
+ found.push(at);
251
+ if (level < depth && found.length < 4_000) walk(at, level + 1);
252
+ }
253
+ };
254
+ walk(home, 1);
255
+ return found;
256
+ }
257
+
258
+ function spotlightFolders(wanted) {
259
+ const found = spawnSync(
260
+ "mdfind",
261
+ [
262
+ "-onlyin",
263
+ os.homedir(),
264
+ `kMDItemContentType == "public.folder" && kMDItemFSName == "*${wanted.replace(/["*\\]/g, "")}*"c`,
265
+ ],
266
+ { encoding: "utf8", timeout: 3_000 }
267
+ );
268
+ return (found.stdout || "")
269
+ .split("\n")
270
+ .filter((line) => line && !line.includes("/Library/") && !/\/\./.test(line))
271
+ .slice(0, 40);
272
+ }
273
+
274
+ /** The setup choices on the control socket. `knownFolders()` is where the person already works (folders.mjs). */
275
+ export function createSetupChoices({
276
+ configPath,
277
+ knownFolders = () => [],
278
+ home = os.homedir(),
279
+ }) {
280
+ const config = () => readJson(configPath, {});
281
+ const save = (change) =>
282
+ writeJsonAtomic(configPath, { ...config(), ...change });
283
+ const pickedNow = () => {
284
+ const current = config();
285
+ return new Set(
286
+ Array.isArray(current.searchFolders) ? current.searchFolders : ASKED
287
+ );
288
+ };
289
+ const savePicked = (picked) =>
290
+ save({ searchFolders: ASKED.filter((entry) => picked.has(entry)) });
291
+
292
+ // A guarded folder is read the moment it is picked, so macOS asks then, beside the tap, not later when the index
293
+ // first reaches it (owner, November 3: "a little jarring"). The read waits off the event loop for the person's
294
+ // answer, which can take longer than the app waits for a reply: the screen follows `asking`. A refusal takes the
295
+ // pick back.
296
+ const asking = new Set();
297
+ const refused = new Set();
298
+ const askMacOS = (name, folder, takeBack) => {
299
+ asking.add(name);
300
+ refused.delete(name);
301
+ fs.promises
302
+ .readdir(folder)
303
+ .catch((error) => {
304
+ if (error?.code !== "EPERM" && error?.code !== "EACCES") return;
305
+ refused.add(name);
306
+ takeBack();
307
+ })
308
+ .finally(() => asking.delete(name));
309
+ };
310
+ const guarded = (folder) =>
311
+ ASKED.some(
312
+ (name) =>
313
+ folder === path.join(home, name) ||
314
+ folder.startsWith(path.join(home, name) + path.sep)
315
+ );
316
+
317
+ const answer = (request) => {
318
+ switch (request.command) {
319
+ case "setup.apps":
320
+ return {
321
+ ok: true,
322
+ apps: appsHere(),
323
+ workplace: config().workplace ?? { all: null, agents: {} },
324
+ };
325
+ case "setup.workplace": {
326
+ // `place` from setup.apps, or null: for one agent, null means it follows the general pick.
327
+ const place = request.place ?? null;
328
+ const workplace = config().workplace ?? { all: null, agents: {} };
329
+ const agent = request.target ? String(request.target) : null;
330
+ const agents = { ...workplace.agents };
331
+ if (agent && place) agents[agent] = place;
332
+ if (agent && !place) delete agents[agent];
333
+ save({
334
+ workplace: { all: agent ? workplace.all : place, agents },
335
+ });
336
+ return { ok: true };
337
+ }
338
+ case "setup.folders": {
339
+ const current = config();
340
+ return {
341
+ ok: true,
342
+ asked: ASKED,
343
+ picked: Array.isArray(current.searchFolders)
344
+ ? current.searchFolders
345
+ : ASKED,
346
+ asking: [...asking],
347
+ refused: [...refused],
348
+ added: (Array.isArray(current.localFolders)
349
+ ? current.localFolders
350
+ : []
351
+ ).map(shown),
352
+ };
353
+ }
354
+ case "setup.folder": {
355
+ const current = config();
356
+ const name = String(request.name || "");
357
+ const on = request.on === true;
358
+ if (ASKED.includes(name)) {
359
+ const picked = pickedNow();
360
+ if (on) picked.add(name);
361
+ else picked.delete(name);
362
+ savePicked(picked);
363
+ if (on)
364
+ askMacOS(name, path.join(home, name), () => {
365
+ const now = pickedNow();
366
+ now.delete(name);
367
+ savePicked(now);
368
+ });
369
+ return { ok: true };
370
+ }
371
+ const folder = path.resolve(name.replace(/^~(?=$|\/)/, home));
372
+ // Inside a guarded folder even a check that it exists makes macOS ask, and would hold the daemon while it
373
+ // does: there the read below, which waits off the event loop, is the check.
374
+ const inGuarded = guarded(folder);
375
+ if (on && !inGuarded && !fs.existsSync(folder))
376
+ return { ok: false, error: "That folder is not on this computer." };
377
+ const added = new Set(current.localFolders ?? []);
378
+ if (on) added.add(folder);
379
+ else added.delete(folder);
380
+ save({ localFolders: [...added] });
381
+ if (on && inGuarded)
382
+ askMacOS(shown(folder).name, folder, () => {
383
+ const now = new Set(config().localFolders ?? []);
384
+ now.delete(folder);
385
+ save({ localFolders: [...now] });
386
+ });
387
+ return { ok: true };
388
+ }
389
+ case "setup.findFolders":
390
+ return {
391
+ ok: true,
392
+ folders: findFolders(request.query, { known: knownFolders() }).map(
393
+ shown
394
+ ),
395
+ };
396
+ }
397
+ return { ok: false, error: "unknown command" };
398
+ };
399
+ return { handles: (command) => COMMANDS.has(command), answer };
400
+ }