tryharness 0.7.54 → 0.7.58

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 (156) hide show
  1. package/README.md +15 -16
  2. package/cli.mjs +384 -62
  3. package/lib/activity.mjs +10 -10
  4. package/lib/adapters.mjs +16 -0
  5. package/lib/agentBinaries.mjs +71 -0
  6. package/lib/agentRuntimeConfig.mjs +1 -1
  7. package/lib/agentRuntimes.mjs +9 -3
  8. package/lib/agentSignIn.mjs +271 -41
  9. package/lib/answers.mjs +5 -5
  10. package/lib/archetypes.d.ts +64 -0
  11. package/lib/archetypes.js +989 -0
  12. package/lib/asks.mjs +4 -4
  13. package/lib/audit.mjs +36 -13
  14. package/lib/backupSetup.mjs +4 -2
  15. package/lib/boardAccess.mjs +17 -11
  16. package/lib/boardBackup.mjs +6 -6
  17. package/lib/boardFileCommands.mjs +6 -6
  18. package/lib/boardFiles.mjs +13 -12
  19. package/lib/boardMirror.mjs +82 -47
  20. package/lib/boardProtocol.json +30 -1
  21. package/lib/boardWaits.mjs +2 -3
  22. package/lib/book.mjs +6 -6
  23. package/lib/bridge.mjs +5 -5
  24. package/lib/cards.mjs +2 -2
  25. package/lib/cloudAgents.mjs +216 -0
  26. package/lib/cloudAi.mjs +1312 -0
  27. package/lib/cloudAssistants.mjs +242 -0
  28. package/lib/cloudBoot.mjs +81 -86
  29. package/lib/cloudSave.mjs +197 -0
  30. package/lib/cloudSsh.mjs +178 -0
  31. package/lib/context.mjs +3 -3
  32. package/lib/contractGate.mjs +34 -12
  33. package/lib/control-client.mjs +9 -1
  34. package/lib/controlSocket.mjs +86 -0
  35. package/lib/coordinator.mjs +103 -101
  36. package/lib/daemon.mjs +1128 -2865
  37. package/lib/desk.mjs +7 -6
  38. package/lib/desktop.mjs +72 -68
  39. package/lib/directLink.mjs +16 -5
  40. package/lib/environment.mjs +2 -1
  41. package/lib/environments.mjs +14 -6
  42. package/lib/firewall.mjs +9 -9
  43. package/lib/folders.mjs +18 -14
  44. package/lib/frames.mjs +2 -3
  45. package/lib/gitHost.mjs +3 -3
  46. package/lib/goalCommands.mjs +25 -7
  47. package/lib/goals.mjs +7 -7
  48. package/lib/guestRequests.mjs +94 -0
  49. package/lib/handoffs.mjs +8 -7
  50. package/lib/handover.mjs +4 -4
  51. package/lib/harnessModel.mjs +6 -6
  52. package/lib/harnessOffers.mjs +266 -0
  53. package/lib/inference.mjs +26 -8
  54. package/lib/jobAnswers.mjs +190 -0
  55. package/lib/landed.mjs +1 -1
  56. package/lib/lane.mjs +42 -11
  57. package/lib/lessons.mjs +16 -16
  58. package/lib/library.mjs +3 -3
  59. package/lib/lineup.mjs +3 -0
  60. package/lib/linkRelay.mjs +574 -0
  61. package/lib/localAgentAsk.mjs +74 -0
  62. package/lib/localStack.mjs +536 -0
  63. package/lib/localmodels.mjs +6 -4
  64. package/lib/loopBackstop.mjs +4 -4
  65. package/lib/machineIdentity.mjs +9 -1
  66. package/lib/machineRoutes.mjs +181 -2
  67. package/lib/machineRuns.mjs +76 -1
  68. package/lib/machineSeal.mjs +39 -12
  69. package/lib/mcp-stdio.mjs +96 -26
  70. package/lib/mcpRelay.mjs +1 -1
  71. package/lib/members.json +13 -0
  72. package/lib/members.mjs +1 -1
  73. package/lib/models.mjs +77 -23
  74. package/lib/museSession.mjs +6 -1
  75. package/lib/nativeHost.mjs +35 -7
  76. package/lib/network.mjs +50 -5
  77. package/lib/notify.mjs +7 -5
  78. package/lib/nudge.mjs +3 -3
  79. package/lib/ocr.mjs +9 -9
  80. package/lib/onboard.mjs +141 -50
  81. package/lib/oneLine.mjs +7 -7
  82. package/lib/ownMachines.mjs +928 -149
  83. package/lib/pairing.mjs +39 -8
  84. package/lib/paths.mjs +15 -1
  85. package/lib/peerProcess.mjs +124 -0
  86. package/lib/personModel.mjs +3 -3
  87. package/lib/personNotices.mjs +151 -0
  88. package/lib/phones.mjs +490 -38
  89. package/lib/placeCommands.mjs +4 -4
  90. package/lib/places.mjs +70 -2
  91. package/lib/profile.mjs +67 -14
  92. package/lib/projectGit.mjs +158 -14
  93. package/lib/projectPieces.mjs +902 -0
  94. package/lib/projectSettings.mjs +7 -4
  95. package/lib/projects.mjs +384 -62
  96. package/lib/provenance.mjs +5 -1
  97. package/lib/proxyLinks.mjs +267 -0
  98. package/lib/reactions.mjs +7 -5
  99. package/lib/readiness.mjs +12 -7
  100. package/lib/record.mjs +19 -6
  101. package/lib/redact.mjs +4 -4
  102. package/lib/relayLimits.mjs +62 -0
  103. package/lib/release.mjs +170 -0
  104. package/lib/releaseKeys.json +6 -0
  105. package/lib/repoLinks.mjs +4 -4
  106. package/lib/roomChannels.mjs +24 -0
  107. package/lib/roomPage.mjs +1 -1
  108. package/lib/runAuthority.mjs +101 -0
  109. package/lib/runBrief.mjs +19 -8
  110. package/lib/runWorker.mjs +14 -5
  111. package/lib/runner.mjs +215 -25
  112. package/lib/runtime-install.mjs +143 -9
  113. package/lib/schedules.mjs +2 -2
  114. package/lib/screens.mjs +1 -1
  115. package/lib/sealed.mjs +11 -2
  116. package/lib/sealedThreads.mjs +671 -0
  117. package/lib/secretPatterns.json +1 -1
  118. package/lib/secrets.mjs +4 -4
  119. package/lib/seen.mjs +6 -6
  120. package/lib/serverWords.mjs +175 -0
  121. package/lib/service.mjs +22 -12
  122. package/lib/sessionControl.mjs +6 -6
  123. package/lib/specialties.mjs +6 -6
  124. package/lib/specialtyKeys.js +4 -5
  125. package/lib/specialtyNotice.mjs +7 -7
  126. package/lib/specialtySnapshot.mjs +5 -5
  127. package/lib/speech.mjs +5 -5
  128. package/lib/store.mjs +140 -39
  129. package/lib/stuck.mjs +1 -1
  130. package/lib/swarm.mjs +167 -16
  131. package/lib/swarmDevices.mjs +319 -0
  132. package/lib/swarmMemory.mjs +27 -25
  133. package/lib/t3.mjs +13 -13
  134. package/lib/taskCommands.mjs +44 -11
  135. package/lib/taskRooms.mjs +125 -0
  136. package/lib/taskRuns.mjs +36 -1
  137. package/lib/team.mjs +41 -18
  138. package/lib/threadActions.mjs +315 -0
  139. package/lib/threadAuthority.mjs +101 -0
  140. package/lib/threadBriefs.mjs +178 -0
  141. package/lib/threadLine.mjs +2 -2
  142. package/lib/threadRuns.mjs +138 -43
  143. package/lib/threadView.mjs +5 -5
  144. package/lib/usageTotals.mjs +2 -3
  145. package/lib/vault.mjs +101 -10
  146. package/lib/vaultCloud.mjs +2 -2
  147. package/lib/vaultCommands.mjs +15 -6
  148. package/lib/vaultTools.js +2 -2
  149. package/lib/verdicts.mjs +328 -0
  150. package/lib/wakes.mjs +1 -1
  151. package/lib/watches.mjs +2 -2
  152. package/lib/windowAsks.mjs +13 -5
  153. package/lib/worktrees.mjs +112 -18
  154. package/npm-shrinkwrap.json +1093 -0
  155. package/package.json +11 -10
  156. package/release.json +220 -0
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
@@ -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. */
@@ -149,11 +176,15 @@ export async function joinSwarm({
149
176
  const started = Date.now();
150
177
  let told = false;
151
178
  while (listed?.joinCode && Date.now() - started < waitMs) {
179
+ // The steps go above the spinner once: a spinner line wider than the terminal wraps, and every frame then
180
+ // prints it again.
152
181
  if (!told && Date.now() - started > quietMs) {
153
182
  told = true;
154
- spin.message(
155
- `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.`
183
+ spin.stop(`Waiting for ${homeName()}`);
184
+ ui.info(
185
+ `On ${homeName()}, 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.`
156
186
  );
187
+ spin.start(`Waiting for ${homeName()}`);
157
188
  }
158
189
  await new Promise((resolve) => setTimeout(resolve, 1_000));
159
190
  listed = (await read()) ?? listed;
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"),
@@ -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
+ }
@@ -8,9 +8,9 @@ import path from "node:path";
8
8
  // to lend: it is never used.
9
9
 
10
10
  /**
11
- * How long one label may take. Measured on the owner's M5 Pro with Flint (a reasoning model on llama.cpp), 80 labels of
12
- * real thread messages, October 23, while e2e suites ran beside it: median 18.6 s and 22.0 s in two rounds, slowest
13
- * 48.6 s. 90 s leaves about 1.85x over the slowest; a label is made once, in the background, so waiting costs nothing.
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
14
  */
15
15
  const LABEL_TIMEOUT_MS = 90_000;
16
16
  const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
@@ -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
+ }