tryharness 0.7.53 → 0.7.57

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 (167) hide show
  1. package/README.md +23 -19
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +484 -90
  5. package/lib/activity.mjs +10 -10
  6. package/lib/adapters.mjs +173 -222
  7. package/lib/agentBinaries.mjs +71 -0
  8. package/lib/agentRuntimeConfig.mjs +1 -1
  9. package/lib/agentRuntimes.mjs +34 -18
  10. package/lib/agentSignIn.mjs +456 -0
  11. package/lib/answers.mjs +5 -5
  12. package/lib/archetypes.d.ts +64 -0
  13. package/lib/archetypes.js +989 -0
  14. package/lib/asks.mjs +4 -4
  15. package/lib/audit.mjs +666 -0
  16. package/lib/backupSetup.mjs +143 -0
  17. package/lib/boardAccess.mjs +24 -11
  18. package/lib/boardBackup.mjs +283 -0
  19. package/lib/boardFileCommands.mjs +6 -6
  20. package/lib/boardFiles.mjs +13 -12
  21. package/lib/boardMirror.mjs +124 -25
  22. package/lib/boardProtocol.json +88 -2
  23. package/lib/boardWaits.mjs +101 -0
  24. package/lib/book.mjs +659 -0
  25. package/lib/bridge.mjs +6 -6
  26. package/lib/cards.mjs +138 -28
  27. package/lib/cloudAgents.mjs +216 -0
  28. package/lib/cloudAi.mjs +1312 -0
  29. package/lib/cloudAssistants.mjs +242 -0
  30. package/lib/cloudBoot.mjs +119 -0
  31. package/lib/cloudSave.mjs +197 -0
  32. package/lib/cloudSsh.mjs +178 -0
  33. package/lib/commands.mjs +7 -2
  34. package/lib/context.mjs +19 -5
  35. package/lib/contractGate.mjs +399 -0
  36. package/lib/control-client.mjs +9 -1
  37. package/lib/controlSocket.mjs +86 -0
  38. package/lib/coordinator.mjs +252 -144
  39. package/lib/daemon.mjs +1351 -2767
  40. package/lib/desk.mjs +240 -0
  41. package/lib/desktop.mjs +178 -74
  42. package/lib/directLink.mjs +16 -5
  43. package/lib/environment.mjs +2 -1
  44. package/lib/environments.mjs +247 -9
  45. package/lib/firewall.mjs +9 -9
  46. package/lib/folders.mjs +20 -16
  47. package/lib/frames.mjs +2 -3
  48. package/lib/gitHost.mjs +174 -0
  49. package/lib/goalCommands.mjs +25 -7
  50. package/lib/goals.mjs +7 -7
  51. package/lib/guestRequests.mjs +94 -0
  52. package/lib/handoffs.mjs +8 -7
  53. package/lib/handover.mjs +4 -4
  54. package/lib/harnessModel.mjs +6 -6
  55. package/lib/harnessOffers.mjs +266 -0
  56. package/lib/hookDialects.mjs +298 -0
  57. package/lib/inference.mjs +26 -8
  58. package/lib/jobAnswers.mjs +190 -0
  59. package/lib/landed.mjs +887 -0
  60. package/lib/lane.mjs +42 -11
  61. package/lib/lessons.mjs +16 -16
  62. package/lib/library.mjs +3 -3
  63. package/lib/lineup.mjs +3 -0
  64. package/lib/linkRelay.mjs +574 -0
  65. package/lib/live.mjs +284 -13
  66. package/lib/localAgentAsk.mjs +74 -0
  67. package/lib/localStack.mjs +536 -0
  68. package/lib/localmodels.mjs +6 -4
  69. package/lib/loopBackstop.mjs +4 -4
  70. package/lib/machineIdentity.mjs +9 -1
  71. package/lib/machineRoutes.mjs +181 -2
  72. package/lib/machineRuns.mjs +76 -1
  73. package/lib/machineSeal.mjs +39 -12
  74. package/lib/mcp-stdio.mjs +163 -27
  75. package/lib/mcpRelay.mjs +1 -1
  76. package/lib/members.json +29 -2
  77. package/lib/members.mjs +1 -1
  78. package/lib/models.mjs +85 -31
  79. package/lib/museSession.mjs +21 -13
  80. package/lib/nativeHost.mjs +36 -8
  81. package/lib/neovim.mjs +126 -0
  82. package/lib/network.mjs +50 -5
  83. package/lib/notify.mjs +7 -5
  84. package/lib/nudge.mjs +50 -19
  85. package/lib/ocr.mjs +9 -9
  86. package/lib/onboard.mjs +26 -20
  87. package/lib/oneLine.mjs +7 -7
  88. package/lib/ownMachines.mjs +1223 -140
  89. package/lib/pairing.mjs +60 -16
  90. package/lib/paths.mjs +19 -1
  91. package/lib/peerProcess.mjs +124 -0
  92. package/lib/personModel.mjs +89 -0
  93. package/lib/personNotices.mjs +151 -0
  94. package/lib/phones.mjs +538 -31
  95. package/lib/placeCommands.mjs +4 -4
  96. package/lib/places.mjs +400 -12
  97. package/lib/profile.mjs +67 -14
  98. package/lib/projectGit.mjs +158 -14
  99. package/lib/projectPieces.mjs +902 -0
  100. package/lib/projectSettings.mjs +7 -4
  101. package/lib/projects.mjs +384 -62
  102. package/lib/provenance.mjs +5 -1
  103. package/lib/proxyLinks.mjs +267 -0
  104. package/lib/reactions.mjs +7 -5
  105. package/lib/readiness.mjs +145 -23
  106. package/lib/record.mjs +128 -0
  107. package/lib/redact.mjs +4 -4
  108. package/lib/relayLimits.mjs +62 -0
  109. package/lib/release.mjs +170 -0
  110. package/lib/releaseKeys.json +6 -0
  111. package/lib/repoLinks.mjs +4 -4
  112. package/lib/roomChannels.mjs +24 -0
  113. package/lib/roomPage.mjs +1 -1
  114. package/lib/runAuthority.mjs +101 -0
  115. package/lib/runBrief.mjs +19 -8
  116. package/lib/runWorker.mjs +31 -7
  117. package/lib/runner.mjs +223 -29
  118. package/lib/runtime-install.mjs +143 -9
  119. package/lib/schedules.mjs +2 -2
  120. package/lib/screens.mjs +1 -1
  121. package/lib/sealed.mjs +11 -2
  122. package/lib/sealedThreads.mjs +671 -0
  123. package/lib/secretPatterns.json +1 -1
  124. package/lib/secrets.mjs +4 -4
  125. package/lib/seen.mjs +6 -6
  126. package/lib/serverWords.mjs +175 -0
  127. package/lib/service.mjs +22 -12
  128. package/lib/sessionControl.mjs +378 -90
  129. package/lib/specialties.json +74 -0
  130. package/lib/specialties.mjs +477 -0
  131. package/lib/specialtyKeys.d.ts +3 -0
  132. package/lib/specialtyKeys.js +57 -0
  133. package/lib/specialtyNotice.mjs +147 -0
  134. package/lib/specialtySnapshot.mjs +138 -0
  135. package/lib/speech.mjs +5 -5
  136. package/lib/store.mjs +420 -36
  137. package/lib/stuck.mjs +1 -1
  138. package/lib/swarm.mjs +304 -37
  139. package/lib/swarmDevices.mjs +319 -0
  140. package/lib/swarmMemory.mjs +27 -25
  141. package/lib/t3.mjs +24 -15
  142. package/lib/taskCommands.mjs +80 -20
  143. package/lib/taskRooms.mjs +125 -0
  144. package/lib/taskRuns.mjs +45 -3
  145. package/lib/team.json +255 -148
  146. package/lib/team.mjs +554 -190
  147. package/lib/threadActions.mjs +315 -0
  148. package/lib/threadAuthority.mjs +101 -0
  149. package/lib/threadBriefs.mjs +178 -0
  150. package/lib/threadLine.mjs +116 -0
  151. package/lib/threadRuns.mjs +209 -50
  152. package/lib/threadView.mjs +20 -7
  153. package/lib/usageTotals.mjs +2 -3
  154. package/lib/vault.mjs +101 -10
  155. package/lib/vaultCloud.mjs +2 -2
  156. package/lib/vaultCommands.mjs +15 -6
  157. package/lib/vaultTools.js +2 -2
  158. package/lib/verdicts.mjs +328 -0
  159. package/lib/wakes.mjs +1 -1
  160. package/lib/watches.mjs +2 -2
  161. package/lib/windowAsks.mjs +13 -5
  162. package/lib/worktrees.mjs +157 -25
  163. package/npm-shrinkwrap.json +1093 -0
  164. package/package.json +12 -11
  165. package/release.json +220 -0
  166. package/lib/modelTiers.json +0 -1183
  167. package/lib/modelTiers.mjs +0 -133
package/lib/pairing.mjs CHANGED
@@ -4,9 +4,9 @@ import { spawnSync } from "node:child_process";
4
4
  import { loadMachine, saveMachine } from "./machineIdentity.mjs";
5
5
  import { newPairCode, pairClaim } from "./machineSeal.mjs";
6
6
 
7
- // Connecting a computer to the person's Harness account (src/server/bridge/pairHub.ts is the other end): setup asks
8
- // Harness to hold a pairing, shows the code, and waits on one held stream until the person approves it, which releases
9
- // this computer's connection token down that stream.
7
+ // Connecting a computer to the person's Harness account (Harness's server is the other end): setup asks Harness to hold
8
+ // a pairing, shows the code, and waits on one held stream until the person approves it, which releases this computer's
9
+ // connection token down that stream.
10
10
  //
11
11
  // Setup makes the code itself, and it is one code for the whole join (machineSeal.mjs): approving it in a signed-in
12
12
  // browser connects this computer to the account, and typing it on a computer already connected (the buddy's Add a
@@ -14,8 +14,8 @@ import { newPairCode, pairClaim } from "./machineSeal.mjs";
14
14
  // code's first 4 characters and proof of the whole. A Harness from before this takes neither and makes a code of its
15
15
  // own (an 8-character one, for the account only).
16
16
  //
17
- // Once connected, a computer Harness added to an account that already has a home waits here until home confirms it
18
- // with the same code (joinSwarm).
17
+ // Once connected, a computer Harness added to an account that already has a home is told where to type its code, and
18
+ // works on its own meanwhile (joinSwarm).
19
19
 
20
20
  /** Ask Harness to hold a pairing for this computer. Returns { pairId, code, own } (own: setup made the code). */
21
21
  export async function startPairing(origin, agents) {
@@ -33,7 +33,11 @@ export async function startPairing(origin, agents) {
33
33
  });
34
34
  for (let attempt = 0; attempt < 3; attempt++) {
35
35
  const code = newPairCode();
36
- const response = await start({ hostname, agents, ...pairClaim(code) });
36
+ const response = await start({
37
+ hostname,
38
+ agents,
39
+ ...(await pairClaim(code)),
40
+ });
37
41
  // Another computer's setup holds a code with the same first 4 characters.
38
42
  if (response.status === 409) continue;
39
43
  if (response.status === 400) break;
@@ -49,9 +53,32 @@ export async function startPairing(origin, agents) {
49
53
  return { pairId, code, own: false };
50
54
  }
51
55
 
52
- /** Keep setup's code for the daemon, which takes it as this computer's join code. */
56
+ /**
57
+ * The page setup opens to approve this computer (src/main/mobile/PairComputer.tsx), in its address fragment: what
58
+ * Harness already holds of the code (its first 4 characters and the verifier, `l` and `a`), never the code itself, which
59
+ * is also this computer's join secret and stays in the terminal and the person's own computers' Harness. Then the
60
+ * browser link setup made for the daemon (`v,o,s,k,h`, phones.mjs writeBrowserOffer), when there is one. An older
61
+ * Harness's 8-character code is the account's only, and rides as it is (`c`).
62
+ */
63
+ export async function setupPageUrl(origin, { code, own }, browserLink = null) {
64
+ const approval = own
65
+ ? (({ lookup, verifier }) => ({ l: lookup, a: verifier }))(
66
+ await pairClaim(code)
67
+ )
68
+ : { c: code };
69
+ const fragment = [new URLSearchParams(approval).toString(), browserLink]
70
+ .filter(Boolean)
71
+ .join("&");
72
+ return `${String(origin).replace(/\/$/, "")}/pair#${fragment}`;
73
+ }
74
+
75
+ /** Keep setup's code for the daemon, which takes it as this computer's join code for as long as a pairing code lasts. */
53
76
  export function keepJoinCode(machineFile, code) {
54
- saveMachine(machineFile, { ...loadMachine(machineFile), joinCode: code });
77
+ saveMachine(machineFile, {
78
+ ...loadMachine(machineFile),
79
+ joinCode: code,
80
+ joinCodeAt: Date.now(),
81
+ });
55
82
  }
56
83
 
57
84
  /** Wait for the person's approval. Resolves with the connection token; rejects on expiry or a dropped stream. */
@@ -101,14 +128,22 @@ export function hasBattery() {
101
128
  return true;
102
129
  }
103
130
 
131
+ // How long setup waits, at its end, for the person to type this computer's code on home. It works on its own meanwhile,
132
+ // so the wait only lets setup say it joined; the person may close it.
104
133
  const JOIN_WAIT_MS = 10 * 60_000;
105
134
  // How long a computer approved from home's buddy usually takes to be confirmed there, before setup says where to type.
106
135
  const JOIN_QUIET_MS = 8_000;
107
136
 
137
+ const names = (labels) =>
138
+ labels.length > 1
139
+ ? `${labels.slice(0, -1).join(", ")} and ${labels.at(-1)}`
140
+ : labels[0];
141
+
108
142
  /**
109
- * After the daemon connects: Harness has made this computer home (the first on the account) or added it. An added one
110
- * waits until home confirms it with the same code, then may be offered home when it suits that better. Returns the
111
- * role. `daemonRequest` reaches this computer's daemon.
143
+ * At the end of setup, once the daemon is connected: Harness has made this computer home or added it. An added one not
144
+ * confirmed yet works on its own board until the person types its code on home (ownMachines.mjs); setup says where and
145
+ * waits for it, then may offer home to a computer that suits that better. On home, the computers that still need their
146
+ * code typed here are named. Returns the role. `daemonRequest` reaches this computer's daemon.
112
147
  */
113
148
  export async function joinSwarm({
114
149
  ui,
@@ -121,7 +156,17 @@ export async function joinSwarm({
121
156
  const read = () =>
122
157
  daemonRequest({ command: "machines.list" }).catch(() => null);
123
158
  let listed = await read();
124
- if (!listed?.ok || listed.self.role !== "worker") return "home";
159
+ if (!listed?.ok) return "home";
160
+ if (listed.self.role !== "worker") {
161
+ const waiting = listed.machines
162
+ .filter((machine) => machine.role === "worker" && !machine.confirmed)
163
+ .map((machine) => machine.label);
164
+ if (waiting.length)
165
+ ui.info(
166
+ `${names(waiting)} ${waiting.length > 1 ? "are" : "is"} on your account but not in your swarm here yet, and ${waiting.length > 1 ? "each works" : "works"} on its own meanwhile. To bring ${waiting.length > 1 ? "each" : "it"} in, run npx tryharness machines there and type the code it shows here: Add a Computer in the Harness menu.`
167
+ );
168
+ return "home";
169
+ }
125
170
  const homeName = () =>
126
171
  listed.machines.find((machine) => machine.role === "home")?.label ||
127
172
  "your home computer";
@@ -134,7 +179,7 @@ export async function joinSwarm({
134
179
  if (!told && Date.now() - started > quietMs) {
135
180
  told = true;
136
181
  spin.message(
137
- `Waiting for ${homeName()}. There, click the Harness icon in the menu bar, choose Add a Computer, and type ${listed.joinCode}${listed.joinCode === code ? " (the same code)" : ""}. Or run there: npx tryharness machines add ${listed.joinCode}`
182
+ `Waiting for ${homeName()}. There, click the Harness icon in the menu bar, choose Add a Computer, and type ${listed.joinCode}${listed.joinCode === code ? " (the same code)" : ""}. Or run there: npx tryharness machines add ${listed.joinCode}. This computer already works on its own, so you can close this.`
138
183
  );
139
184
  }
140
185
  await new Promise((resolve) => setTimeout(resolve, 1_000));
@@ -142,8 +187,7 @@ export async function joinSwarm({
142
187
  }
143
188
  if (listed.joinCode) {
144
189
  spin.stop(
145
- `Not in your swarm yet. On ${homeName()}, run: npx tryharness machines add ${listed.joinCode}`,
146
- 2
190
+ `This computer works on its own until it joins your swarm. To bring it in, type ${listed.joinCode} on ${homeName()}: Add a Computer in the Harness menu there, or npx tryharness machines add ${listed.joinCode}. What it does meanwhile goes to ${homeName()} when it joins.`
147
191
  );
148
192
  return "worker";
149
193
  }
@@ -151,7 +195,7 @@ export async function joinSwarm({
151
195
  } else ui.success(`In your swarm. ${homeName()} holds the board.`);
152
196
  if (!ui.interactive || battery()) return "worker";
153
197
  const move = await ui.confirm({
154
- message: `This computer stays on, so work could go on here while ${homeName()} sleeps. Make it your main computer? Your threads and board so far stay on ${homeName()}.`,
198
+ message: `This computer stays on, so work could go on here while ${homeName()} sleeps. Make it your main computer? Your threads and board come with it.`,
155
199
  initialValue: false,
156
200
  });
157
201
  if (!move) return "worker";
package/lib/paths.mjs CHANGED
@@ -7,6 +7,20 @@ export const harnessHome = process.env.HARNESS_HOME
7
7
  ? path.resolve(process.env.HARNESS_HOME)
8
8
  : path.join(os.homedir(), ".harness");
9
9
 
10
+ // Windows named pipes share one namespace for every user of the machine: the daemon's is named for its user, so
11
+ // another account's program does not find (or take) it by the one well-known name. The desktop app names it the same
12
+ // way (packages/desktop/src-tauri/src/daemon.rs). Node sets no access list on a pipe; Windows' default for one lets
13
+ // other accounts read but not write it.
14
+ function pipeOwner() {
15
+ let name = "";
16
+ try {
17
+ name = os.userInfo().username;
18
+ } catch {}
19
+ return (name || process.env.USERNAME || "user")
20
+ .toLowerCase()
21
+ .replace(/[^a-z0-9._-]/g, "_");
22
+ }
23
+
10
24
  export const paths = {
11
25
  home: harnessHome,
12
26
  config: path.join(harnessHome, "config.json"),
@@ -14,7 +28,7 @@ export const paths = {
14
28
  status: path.join(harnessHome, "daemon-status.json"),
15
29
  socket:
16
30
  process.platform === "win32"
17
- ? "\\\\.\\pipe\\tryharness-daemon"
31
+ ? `\\\\.\\pipe\\tryharness-daemon-${pipeOwner()}`
18
32
  : path.join(harnessHome, "daemon.sock"),
19
33
  log: path.join(harnessHome, "daemon.log"),
20
34
  phoneIdentity: path.join(harnessHome, "phone-identity.json"),
@@ -23,6 +37,10 @@ export const paths = {
23
37
  machine: path.join(harnessHome, "machine.json"),
24
38
  // The person's name and preferences from their Harness profile (profile.mjs).
25
39
  profile: path.join(harnessHome, "profile.json"),
40
+ // The terminal app setup last ran in (places.mjs noteSetupTerminal).
41
+ terminal: path.join(harnessHome, "terminal.json"),
42
+ // A cloud computer's seeded link offer (cloudBoot.mjs); absent everywhere else.
43
+ cloud: path.join(harnessHome, "cloud.json"),
26
44
  runs: path.join(harnessHome, "runs"),
27
45
  files: path.join(harnessHome, "files"),
28
46
  runtime: path.join(harnessHome, "runtime"),
@@ -0,0 +1,124 @@
1
+ import fs from "node:fs";
2
+ import { execFile } from "node:child_process";
3
+ import { PS } from "./nudge.mjs";
4
+
5
+ // Which program is at the other end of a connection to the daemon's socket, and whether it is inside a run the daemon
6
+ // started. Node cannot read a Unix socket's peer (no SO_PEERCRED or LOCAL_PEERPID), so this asks the system's own
7
+ // tools: lsof on macOS, ss with /proc on Linux. A program that left its run's process tree (a double fork) is not
8
+ // found by this; the run's capability in its environment (runAuthority.mjs) covers the rest of what a run calls with.
9
+
10
+ const LIST_LIMIT = 64 * 1024 * 1024;
11
+ // By full path: a daemon started by launchd or systemd has a short PATH, often without the sbin folders.
12
+ const tool = (name) =>
13
+ ["/usr/sbin", "/usr/bin", "/sbin", "/bin"]
14
+ .map((dir) => `${dir}/${name}`)
15
+ .find((file) => fs.existsSync(file)) || name;
16
+ const LSOF = tool("lsof");
17
+ const SS = tool("ss");
18
+
19
+ const run = (command, args) =>
20
+ new Promise((resolve) => {
21
+ execFile(
22
+ command,
23
+ args,
24
+ { encoding: "utf8", maxBuffer: LIST_LIMIT },
25
+ (error, stdout) => resolve(error && !stdout ? null : String(stdout))
26
+ );
27
+ });
28
+
29
+ // lsof -F prints one field per line: p<pid>, f<fd>, d<device>, n<name>. The daemon's end of the connection is its own
30
+ // fd; the client's end is the socket whose name points at that device ("->0x…").
31
+ async function macPeers(fd) {
32
+ // -b and -w: never wait on a kernel call or print warnings; a socket's device and peer are read all the same.
33
+ const listing = await run(LSOF, ["-n", "-P", "-b", "-w", "-U", "-F", "pfdn"]);
34
+ if (listing === null) return null;
35
+ const entries = [];
36
+ let pid = null;
37
+ let entry = null;
38
+ for (const line of listing.split("\n")) {
39
+ const field = line[0];
40
+ const value = line.slice(1);
41
+ if (field === "p") pid = Number(value);
42
+ else if (field === "f") {
43
+ entry = { pid, fd: value, device: null, name: "" };
44
+ entries.push(entry);
45
+ } else if (entry && field === "d") entry.device = value;
46
+ else if (entry && field === "n") entry.name = value;
47
+ }
48
+ const mine = entries.find(
49
+ (each) => each.pid === process.pid && each.fd === String(fd)
50
+ );
51
+ if (!mine?.device) return null;
52
+ return entries
53
+ .filter(
54
+ (each) => each.pid !== process.pid && each.name === `->${mine.device}`
55
+ )
56
+ .map((each) => each.pid);
57
+ }
58
+
59
+ // ss -xp names each Unix socket by its inode with its peer's inode and the processes holding it.
60
+ async function linuxPeers(fd) {
61
+ let inode;
62
+ try {
63
+ inode = /socket:\[(\d+)\]/.exec(
64
+ fs.readlinkSync(`/proc/self/fd/${fd}`)
65
+ )?.[1];
66
+ } catch {
67
+ return null;
68
+ }
69
+ if (!inode) return null;
70
+ const listing = await run(SS, ["-x", "-a", "-n", "-p", "-H"]);
71
+ if (listing === null) return null;
72
+ const rows = listing
73
+ .split("\n")
74
+ .map((line) => line.trim().split(/\s+/))
75
+ .filter((cells) => cells.length >= 8);
76
+ // Columns: netid state recv send local local-inode peer peer-inode [users:((…,pid=N,fd=M))]
77
+ const mine = rows.find((cells) => cells[5] === inode);
78
+ const peerInode = mine?.[7];
79
+ if (!peerInode || peerInode === "0") return null;
80
+ const peer = rows.find((cells) => cells[5] === peerInode);
81
+ if (!peer) return [];
82
+ return [
83
+ ...peer
84
+ .slice(8)
85
+ .join(" ")
86
+ .matchAll(/pid=(\d+)/g),
87
+ ].map((match) => Number(match[1]));
88
+ }
89
+
90
+ /** Whether this system can name a socket's peer at all. */
91
+ export const seesPeers = ["darwin", "linux"].includes(process.platform);
92
+
93
+ /** The process ids holding the other end of a local socket connection; null when the system cannot say. */
94
+ export async function peerPids(socket) {
95
+ const fd = socket?._handle?.fd;
96
+ if (!seesPeers || !Number.isInteger(fd) || fd < 0) return null;
97
+ if (process.platform === "darwin") return macPeers(fd);
98
+ return linuxPeers(fd);
99
+ }
100
+
101
+ /** One snapshot of the process table: each process id's parent. Null when it cannot be read. */
102
+ export async function processParents() {
103
+ const table = await run(PS, ["-A", "-o", "pid=,ppid="]);
104
+ if (table === null) return null;
105
+ const parent = new Map();
106
+ for (const line of table.split("\n")) {
107
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
108
+ if (pid) parent.set(pid, ppid);
109
+ }
110
+ return parent;
111
+ }
112
+
113
+ /** Whether any of `pids` is one of `roots` or descends from one, by the parents in `parent`. */
114
+ export function descendsFrom(pids, roots, parent) {
115
+ const wanted = new Set(roots);
116
+ return pids.some((pid) => {
117
+ const seen = new Set();
118
+ for (let at = pid; at > 1 && !seen.has(at); at = parent.get(at)) {
119
+ if (wanted.has(at)) return true;
120
+ seen.add(at);
121
+ }
122
+ return false;
123
+ });
124
+ }
@@ -0,0 +1,89 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ // The person's own language model on this computer, when they run one for pi (its models.json, in PI_CODING_AGENT_DIR
6
+ // or ~/.pi/agent): an OpenAI-compatible server on this machine. Harness uses it only for small labels of the person's
7
+ // own words (threadLine.mjs), so nothing they wrote leaves the computer for it. A provider anywhere else is not theirs
8
+ // to lend: it is never used.
9
+
10
+ /**
11
+ * How long one label may take. Measured on an M5 Pro with Flint (a reasoning model on llama.cpp), 80 labels of real
12
+ * thread messages, while end-to-end tests ran beside it: median 18.6 s and 22.0 s in two rounds, slowest 48.6 s. 90 s
13
+ * leaves about 1.85x over the slowest; a label is made once, in the background, so waiting costs nothing.
14
+ */
15
+ const LABEL_TIMEOUT_MS = 90_000;
16
+ const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
17
+
18
+ const modelsFile = () =>
19
+ path.join(
20
+ process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent"),
21
+ "models.json"
22
+ );
23
+
24
+ /** The first model pi lists on a server on this computer, or null. */
25
+ export function localModel(file = modelsFile()) {
26
+ let config;
27
+ try {
28
+ config = JSON.parse(fs.readFileSync(file, "utf8"));
29
+ } catch {
30
+ return null;
31
+ }
32
+ for (const provider of Object.values(config?.providers ?? {})) {
33
+ let url;
34
+ try {
35
+ url = new URL(provider.baseUrl);
36
+ } catch {
37
+ continue;
38
+ }
39
+ const model = provider.models?.[0]?.id;
40
+ if (!LOCAL_HOSTS.has(url.hostname) || !model) continue;
41
+ return {
42
+ baseUrl: provider.baseUrl.replace(/\/$/, ""),
43
+ model,
44
+ apiKey: provider.apiKey || "local",
45
+ reasoning: provider.models[0].reasoning === true,
46
+ };
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * Asks the person's local model a short question and returns its JSON answer, or null when there is no local model,
53
+ * it does not answer in time, or what it says is not JSON.
54
+ */
55
+ export async function askLocal(system, user, { fetchImpl = fetch } = {}) {
56
+ const local = localModel();
57
+ if (!local) return null;
58
+ try {
59
+ const res = await fetchImpl(`${local.baseUrl}/chat/completions`, {
60
+ method: "POST",
61
+ headers: {
62
+ "content-type": "application/json",
63
+ authorization: `Bearer ${local.apiKey}`,
64
+ },
65
+ body: JSON.stringify({
66
+ model: local.model,
67
+ temperature: 0,
68
+ // A reasoning model thinks before it answers: room for both, and as little thinking as it allows.
69
+ max_tokens: local.reasoning ? 3000 : 200,
70
+ ...(local.reasoning
71
+ ? { chat_template_kwargs: { reasoning_effort: "low" } }
72
+ : {}),
73
+ messages: [
74
+ { role: "system", content: system },
75
+ { role: "user", content: user },
76
+ ],
77
+ }),
78
+ signal: AbortSignal.timeout(LABEL_TIMEOUT_MS),
79
+ });
80
+ if (!res.ok) return null;
81
+ const body = await res.json();
82
+ const text = String(body.choices?.[0]?.message?.content ?? "")
83
+ .replace(/^```(?:json)?|```$/g, "")
84
+ .trim();
85
+ return JSON.parse(text);
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
@@ -0,0 +1,151 @@
1
+ import { readJson } from "./files.mjs";
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;
8
+
9
+ /**
10
+ * What the person is told about the board, whether or not Harness is open: on the desktop in words, and to their
11
+ * installed phone as only the kind of thing that waits, so a tap opens it there. Each item is told once.
12
+ *
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.
15
+ *
16
+ * Notices are off with `tryharness notify off` (`notifications: false` in the config). Nothing is said while the Mac is
17
+ * in Standby (`quiet()`). `threadView()` reads a thread as every surface does (threadView.mjs), made after this module.
18
+ */
19
+ export function createPersonNotices({
20
+ store,
21
+ configPath,
22
+ send,
23
+ serverHas,
24
+ threadView,
25
+ quiet,
26
+ }) {
27
+ const on = () => readJson(configPath, {}).notifications !== false;
28
+
29
+ /** A desktop notice, when the person has them on. */
30
+ const notify = (text) => {
31
+ if (on()) notifyDesktop(text);
32
+ };
33
+
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
+ };
49
+
50
+ const firstTime = (id) => {
51
+ if (store.meta(`told:${id}`)) return false;
52
+ store.meta(`told:${id}`, new Date().toISOString());
53
+ return true;
54
+ };
55
+
56
+ // A server from before a kind of notice hears only that something needs the person.
57
+ const toPhone = (feature, message) =>
58
+ send(serverHas(feature) ? message : { type: "needs_you" });
59
+
60
+ // Each item that begins to wait on the person in a thread is told once: on the desktop in words, and to the phone as
61
+ // only its kind, its thread and its id.
62
+ const tellNeedsYou = (threadId) => {
63
+ const thread = store.getTask(threadId);
64
+ if (!thread || thread.kind !== "goal") return;
65
+ const row = threadView().row(thread);
66
+ for (const item of row.needsYou) {
67
+ if (!firstTime(item.id)) continue;
68
+ if (on() && !quiet())
69
+ tellDesktop(row.title, threadView().itemLine(item), threadId, item.id);
70
+ toPhone("needs_you_item", {
71
+ type: "needs_you",
72
+ kind: item.kind,
73
+ thread: threadId,
74
+ item: item.id,
75
+ });
76
+ }
77
+ };
78
+
79
+ /**
80
+ * An app operation an agent asked for waits for the person's approval (connectors.mjs). The desktop notice opens
81
+ * Settings at it: the buddy reads "app:" as an app connection, not a thread.
82
+ */
83
+ const approval = (operation, connection) => {
84
+ if (!firstTime(operation.id)) return;
85
+ if (on() && !quiet())
86
+ tellDesktop(
87
+ connection?.label || "An app",
88
+ `${nameOf(operation.agent)} asks to ${operation.effect} with ${operation.tool}. Approve or decline it in Settings.`,
89
+ `app:${operation.connection}`,
90
+ operation.id
91
+ );
92
+ toPhone("needs_you_approval", {
93
+ type: "needs_you",
94
+ kind: "approval",
95
+ app: operation.connection,
96
+ item: operation.id,
97
+ });
98
+ };
99
+
100
+ // The thread a task belongs to (itself for a thread), or null for work outside one.
101
+ const threadOf = (task) =>
102
+ task.kind === "goal"
103
+ ? task.id
104
+ : task.parent_id && store.getTask(task.parent_id)?.kind === "goal"
105
+ ? task.parent_id
106
+ : null;
107
+
108
+ // A run that needs the person's Start, or a question asked of the person.
109
+ const waitsForPerson = (task) =>
110
+ Boolean(task) &&
111
+ task.kind !== "goal" &&
112
+ ((task.status === "open" &&
113
+ Boolean(task.run_workspace) &&
114
+ !task.run_authorized_at) ||
115
+ (task.status === "needs_input" && task.holder === "user"));
116
+
117
+ /**
118
+ * A task changed from `previous` (its last status, holder and run fields). What waits on the person outside a thread
119
+ * is told on the desktop once per change: a run an agent asked for, a question, an unknown outcome, work posted for
120
+ * Harness, a claim gone stale. In a thread its needs-you items are told instead. Their phone hears that something
121
+ * began to wait, and that work they asked for finished.
122
+ */
123
+ const changed = (task, previous) => {
124
+ const thread = threadOf(task);
125
+ if (on() && !(thread && waitsForPerson(task))) {
126
+ const body = notificationFor(task, { previous });
127
+ if (body) notifyDesktop(body);
128
+ }
129
+ if (thread) setImmediate(() => tellNeedsYou(thread));
130
+ else if (waitsForPerson(task) && !waitsForPerson(previous))
131
+ send({ type: "needs_you" });
132
+ if (
133
+ task.origin_agent === "user" &&
134
+ task.kind === "task" &&
135
+ ["done", "failed"].includes(task.status) &&
136
+ previous &&
137
+ !["done", "failed"].includes(previous.status)
138
+ )
139
+ send({ type: "finished" });
140
+ };
141
+
142
+ return {
143
+ on,
144
+ notify,
145
+ tellDesktop,
146
+ takeNotices,
147
+ approval,
148
+ changed,
149
+ toPhone,
150
+ };
151
+ }