tryharness 0.7.82 → 0.7.86

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 (216) hide show
  1. package/README.md +21 -19
  2. package/assets/dsh-plugin.mjs +75 -4
  3. package/assets/herdr-mod/harness/main.js +367 -0
  4. package/assets/herdr-mod/harness/mod.json +6 -0
  5. package/assets/opencode-plugin.js +87 -22
  6. package/assets/pi-extension.ts +81 -2
  7. package/cli.mjs +544 -208
  8. package/lib/adapters.mjs +62 -27
  9. package/lib/agentBinaries.mjs +6 -8
  10. package/lib/agentClaims.mjs +168 -0
  11. package/lib/agentReadTools.json +415 -0
  12. package/lib/agentSignIn.mjs +17 -18
  13. package/lib/agentWiring.mjs +114 -0
  14. package/lib/archetypes.js +10 -11
  15. package/lib/attention.mjs +100 -0
  16. package/lib/audit.mjs +1 -1
  17. package/lib/backupSetup.mjs +6 -28
  18. package/lib/bankrApprovals.mjs +86 -0
  19. package/lib/boardAccess.mjs +40 -66
  20. package/lib/boardBackup.mjs +86 -85
  21. package/lib/boardCommands.mjs +28 -0
  22. package/lib/boardFileCommands.mjs +29 -36
  23. package/lib/boardFiles.mjs +83 -15
  24. package/lib/boardMirror.mjs +78 -11
  25. package/lib/boardProtocol.json +193 -123
  26. package/lib/boardThreads.mjs +19 -37
  27. package/lib/boardTools.mjs +22 -15
  28. package/lib/boardWatches.mjs +43 -15
  29. package/lib/bridge.mjs +7 -3
  30. package/lib/browserAgentTools.mjs +59 -0
  31. package/lib/browserWake.mjs +0 -6
  32. package/lib/cards.mjs +57 -2
  33. package/lib/circling.mjs +189 -0
  34. package/lib/cleanup.mjs +234 -0
  35. package/lib/cloudBoot.mjs +21 -4
  36. package/lib/cloudSave.mjs +46 -5
  37. package/lib/compaction.mjs +8 -1
  38. package/lib/completion.mjs +358 -0
  39. package/lib/computerDevices.mjs +853 -0
  40. package/lib/connectionStatus.mjs +34 -0
  41. package/lib/connectors.mjs +139 -1
  42. package/lib/coordinator.mjs +108 -14
  43. package/lib/coreModels.mjs +36 -12
  44. package/lib/daemon.mjs +2435 -333
  45. package/lib/daemonLock.mjs +103 -0
  46. package/lib/deviceDoor.mjs +308 -0
  47. package/lib/deviceIdentity.mjs +114 -0
  48. package/lib/deviceList.mjs +172 -0
  49. package/lib/deviceSeal.mjs +74 -0
  50. package/lib/dispatcher.mjs +497 -26
  51. package/lib/dispatches.mjs +3 -3
  52. package/lib/environment.mjs +2 -1
  53. package/lib/environments.mjs +67 -41
  54. package/lib/events.mjs +318 -0
  55. package/lib/facts.mjs +170 -0
  56. package/lib/fileSource.mjs +540 -0
  57. package/lib/files.mjs +47 -2
  58. package/lib/gitHost.mjs +39 -1
  59. package/lib/goalCommands.mjs +12 -80
  60. package/lib/handover.mjs +21 -16
  61. package/lib/harnessOffers.mjs +140 -15
  62. package/lib/herdr.mjs +100 -15
  63. package/lib/herdrAppCall.mjs +19 -0
  64. package/lib/herdrCore.mjs +59 -0
  65. package/lib/herdrRuns.mjs +1126 -0
  66. package/lib/hookDialects.mjs +235 -50
  67. package/lib/identityLink.mjs +81 -0
  68. package/lib/inference.mjs +31 -2
  69. package/lib/jamAccess.mjs +82 -0
  70. package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
  71. package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
  72. package/lib/jamKey.mjs +274 -0
  73. package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
  74. package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
  75. package/lib/jamStore.mjs +973 -0
  76. package/lib/jamUpgrade.mjs +112 -0
  77. package/lib/jams.mjs +3079 -0
  78. package/lib/kanban.mjs +13 -7
  79. package/lib/landed.mjs +5 -1
  80. package/lib/library.mjs +41 -22
  81. package/lib/limits.mjs +91 -0
  82. package/lib/lineDiff.mjs +97 -0
  83. package/lib/lineup.mjs +18 -13
  84. package/lib/link.mjs +584 -0
  85. package/lib/localStack.mjs +75 -16
  86. package/lib/localmodels.mjs +58 -78
  87. package/lib/loopBackstop.mjs +2 -1
  88. package/lib/machine.mjs +544 -0
  89. package/lib/machineLink.mjs +446 -0
  90. package/lib/machineRoutes.mjs +68 -19
  91. package/lib/machineRuns.mjs +85 -4
  92. package/lib/machineSeal.mjs +6 -31
  93. package/lib/manager.mjs +134 -12
  94. package/lib/mcp-stdio.mjs +492 -215
  95. package/lib/mcpRelay.mjs +34 -35
  96. package/lib/members.json +2 -2
  97. package/lib/modelRoute.mjs +162 -0
  98. package/lib/nativeHost.mjs +81 -90
  99. package/lib/nativeSenses.mjs +258 -0
  100. package/lib/nerves.mjs +523 -0
  101. package/lib/network.mjs +117 -278
  102. package/lib/networkPlaces.mjs +578 -0
  103. package/lib/nextStep.mjs +95 -0
  104. package/lib/notify.mjs +2 -2
  105. package/lib/nudge.mjs +116 -10
  106. package/lib/onboard.mjs +6 -6
  107. package/lib/originals.mjs +216 -0
  108. package/lib/outsideEvents.mjs +383 -0
  109. package/lib/outsideRuns.mjs +230 -0
  110. package/lib/ownMachines.mjs +674 -256
  111. package/lib/pain.mjs +215 -0
  112. package/lib/pairing.mjs +91 -11
  113. package/lib/paths.mjs +42 -3
  114. package/lib/peerProcess.mjs +21 -7
  115. package/lib/peopleLink.mjs +268 -0
  116. package/lib/personNotices.mjs +3 -2
  117. package/lib/phones.mjs +252 -542
  118. package/lib/placeCards.mjs +282 -0
  119. package/lib/placeChecks.mjs +95 -0
  120. package/lib/placeCommands.mjs +8 -17
  121. package/lib/placeRequests.mjs +152 -0
  122. package/lib/placeStore.mjs +295 -0
  123. package/lib/placeTool.d.ts +12 -0
  124. package/lib/placeTool.js +40 -0
  125. package/lib/places.mjs +63 -14
  126. package/lib/plans.mjs +53 -8
  127. package/lib/presence.mjs +270 -0
  128. package/lib/privateNetwork.d.ts +2 -0
  129. package/lib/privateNetwork.js +93 -0
  130. package/lib/proposals.mjs +300 -0
  131. package/lib/publicFetch.d.ts +32 -0
  132. package/lib/publicFetch.js +248 -0
  133. package/lib/reach.mjs +128 -0
  134. package/lib/rebuildable.mjs +72 -0
  135. package/lib/recall.mjs +216 -0
  136. package/lib/record.mjs +13 -0
  137. package/lib/reflexes.mjs +392 -0
  138. package/lib/relayLimits.mjs +31 -2
  139. package/lib/releaseNotice.mjs +198 -0
  140. package/lib/removeHarness.mjs +15 -4
  141. package/lib/repoLinks.mjs +204 -35
  142. package/lib/runAuthority.mjs +102 -39
  143. package/lib/runBrief.mjs +93 -40
  144. package/lib/runRequests.mjs +52 -14
  145. package/lib/runUsage.mjs +31 -0
  146. package/lib/runWorker.mjs +74 -25
  147. package/lib/runner.mjs +289 -45
  148. package/lib/runtime-install.mjs +37 -8
  149. package/lib/schedules.mjs +171 -47
  150. package/lib/screenWatches.mjs +221 -0
  151. package/lib/sealed.mjs +12 -30
  152. package/lib/sealedThreads.mjs +198 -392
  153. package/lib/secretStore.mjs +178 -0
  154. package/lib/secrets.mjs +11 -0
  155. package/lib/seen.mjs +3 -9
  156. package/lib/selfUpdate.mjs +51 -15
  157. package/lib/senseCall.mjs +1514 -0
  158. package/lib/senseHook.mjs +114 -0
  159. package/lib/senseTools.mjs +1298 -0
  160. package/lib/sessionBriefs.mjs +87 -0
  161. package/lib/sessionControl.mjs +63 -13
  162. package/lib/sessionFiles.mjs +85 -0
  163. package/lib/setupChoices.mjs +12 -3
  164. package/lib/setupMode.mjs +70 -25
  165. package/lib/sharedKeys.mjs +166 -0
  166. package/lib/sleep.mjs +396 -0
  167. package/lib/sources.mjs +306 -0
  168. package/lib/speech.mjs +166 -411
  169. package/lib/spoken.mjs +210 -0
  170. package/lib/steerHook.mjs +3 -1
  171. package/lib/steerQueue.mjs +40 -11
  172. package/lib/store.mjs +323 -130
  173. package/lib/stuck.mjs +85 -7
  174. package/lib/swarm.mjs +157 -49
  175. package/lib/swarmDevices.mjs +25 -85
  176. package/lib/swarmMemory.mjs +93 -9
  177. package/lib/t3.mjs +73 -3
  178. package/lib/taskCommands.mjs +51 -60
  179. package/lib/taskRooms.mjs +30 -4
  180. package/lib/taskRules.json +29 -0
  181. package/lib/taskRules.mjs +21 -0
  182. package/lib/taskRuns.mjs +74 -11
  183. package/lib/team.mjs +2 -1
  184. package/lib/threadActions.mjs +37 -9
  185. package/lib/threadAuthority.mjs +4 -4
  186. package/lib/threadBriefs.mjs +173 -43
  187. package/lib/threadNotes.mjs +320 -0
  188. package/lib/threadRecord.mjs +491 -0
  189. package/lib/threadRuns.mjs +216 -108
  190. package/lib/threadView.mjs +27 -30
  191. package/lib/threadWatches.mjs +1962 -0
  192. package/lib/timeSense.mjs +839 -0
  193. package/lib/tripwires.mjs +454 -0
  194. package/lib/ui.mjs +1 -1
  195. package/lib/vault.mjs +560 -45
  196. package/lib/vaultCommands.mjs +5 -3
  197. package/lib/vaultPeers.mjs +165 -0
  198. package/lib/vaultTools.d.ts +4 -1
  199. package/lib/vaultTools.js +22 -1
  200. package/lib/verdicts.mjs +12 -26
  201. package/lib/versions.mjs +117 -0
  202. package/lib/waitTool.mjs +278 -0
  203. package/lib/wakePicture.mjs +268 -0
  204. package/lib/wakeQueue.mjs +108 -0
  205. package/lib/watchResponses.mjs +533 -0
  206. package/lib/watches.mjs +290 -145
  207. package/lib/windowAsks.mjs +80 -17
  208. package/lib/worktrees.mjs +159 -9
  209. package/npm-shrinkwrap.json +138 -631
  210. package/package.json +7 -6
  211. package/release.json +212 -130
  212. package/lib/callSessions.mjs +0 -51
  213. package/lib/directLink.mjs +0 -349
  214. package/lib/peopleBoard.mjs +0 -131
  215. package/lib/projects.mjs +0 -2917
  216. package/lib/roomChannels.mjs +0 -667
package/lib/pain.mjs ADDED
@@ -0,0 +1,215 @@
1
+ import fs from "node:fs";
2
+ import { windowFor } from "./handover.mjs";
3
+ import { harnessHome } from "./paths.mjs";
4
+ import { sessionsAtWork } from "./senseCall.mjs";
5
+ import { PARENT, SENSE, putSteer, takeSteers } from "./steerQueue.mjs";
6
+
7
+ // Pain, told at once (docs/senses-plan.md S4.4): when the computer or a limit starts to hurt (machine.mjs and
8
+ // limits.mjs say a level changed in the log), every agent at work that it touches hears one line at its next tool
9
+ // call, beside the result. Pain is never muted, whatever the session's volume. The computer's pain reaches every agent
10
+ // working on it; a thread's spend reaches the agents working for that thread; an agent's daily cap reaches that agent.
11
+ // A pain that eases before it was told is taken back; one that was told says it eased. A newer level replaces an older
12
+ // one not yet told, so a busy agent hears only the latest.
13
+
14
+ // An agent whose last tool call ended within this long is at work; one idle longer hears of it at its next wake.
15
+ const AT_WORK_MS = 15 * 60_000;
16
+
17
+ // Which levels hurt, for each of the computer's aspects (machine.mjs).
18
+ const HURTS = {
19
+ disk: (level) => level === "tight" || level === "critical",
20
+ memory: (level) => level === "warn" || level === "critical",
21
+ heat: (level) => level === "serious" || level === "critical",
22
+ battery: (level) => level === "low",
23
+ };
24
+
25
+ // A context about to fill is felt early (spend and context, rule 11): told once at each of these shares of the window,
26
+ // well before agents compact (handover.mjs: Codex at a median 87%, as low as 58%; Claude Code at 96.6% or more).
27
+ const FILLS = [0.7, 0.85];
28
+ const CONTEXT_LOOK_MS = 60_000;
29
+ // The end of a session's own record holds its last model call.
30
+ const TAIL_BYTES = 1_000_000;
31
+
32
+ /** The last model call in the end of an agent's own session file: `{ input, model, window }`, or null. */
33
+ export function lastCallOf(agent, file) {
34
+ let text = "";
35
+ try {
36
+ const size = fs.statSync(file).size;
37
+ const handle = fs.openSync(file, "r");
38
+ const length = Math.min(size, TAIL_BYTES);
39
+ const buffer = Buffer.alloc(length);
40
+ fs.readSync(handle, buffer, 0, length, size - length);
41
+ fs.closeSync(handle);
42
+ text = buffer.toString("utf8");
43
+ } catch {
44
+ return null;
45
+ }
46
+ const found = { input: null, model: null, window: null };
47
+ for (const line of text.split("\n")) {
48
+ let row = null;
49
+ try {
50
+ row = JSON.parse(line);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (agent === "claude-code") {
55
+ const usage = row.type === "assistant" ? row.message?.usage : null;
56
+ if (usage) {
57
+ found.input =
58
+ (usage.input_tokens || 0) +
59
+ (usage.cache_creation_input_tokens || 0) +
60
+ (usage.cache_read_input_tokens || 0);
61
+ found.model = row.message?.model ?? found.model;
62
+ }
63
+ } else {
64
+ const payload = row.payload ?? {};
65
+ if (row.type === "turn_context" && payload.model)
66
+ found.model = payload.model;
67
+ if (
68
+ row.type === "event_msg" &&
69
+ payload.type === "token_count" &&
70
+ payload.info
71
+ ) {
72
+ found.window = payload.info.model_context_window ?? found.window;
73
+ found.input =
74
+ payload.info.last_token_usage?.input_tokens ?? found.input;
75
+ }
76
+ if (row.type === "token_usage_record" && payload.usage)
77
+ found.input = payload.usage.input_tokens ?? found.input;
78
+ }
79
+ }
80
+ return found.input === null ? null : found;
81
+ }
82
+
83
+ const hurts = (happening) => {
84
+ const level = happening.data?.level;
85
+ if (happening.source === "machine")
86
+ return Boolean(HURTS[happening.subject]?.(level));
87
+ return level === "near" || level === "reached";
88
+ };
89
+
90
+ /**
91
+ * `events` is the log (it is followed). `sessionsOfThread(thread)` are the sessions of the runs working for a thread.
92
+ * `start()` follows; `stop()` stops.
93
+ */
94
+ export function createPain({
95
+ events,
96
+ store = null,
97
+ sessionsOfThread = () => [],
98
+ home = harnessHome,
99
+ now = () => Date.now(),
100
+ }) {
101
+ // Session and pain told (its note was taken), so its easing is said too.
102
+ const told = new Set();
103
+ // Session and pain with a note put, not yet known to be taken.
104
+ const put = new Set();
105
+ let stop = null;
106
+
107
+ // The sessions a happening touches.
108
+ const touched = (happening) => {
109
+ const atWork = sessionsAtWork(AT_WORK_MS, home, now());
110
+ const subject = String(happening.subject ?? "");
111
+ if (happening.source === "machine") return atWork;
112
+ if (subject.startsWith("limits.spend.")) {
113
+ const thread = subject.slice("limits.spend.".length);
114
+ const inThread = new Set(sessionsOfThread(thread).map(String));
115
+ return atWork.filter((each) => inThread.has(each.session));
116
+ }
117
+ if (subject.startsWith("limits.standing.")) {
118
+ const agent = subject.slice("limits.standing.".length);
119
+ return atWork.filter((each) => each.agent === agent);
120
+ }
121
+ return [];
122
+ };
123
+
124
+ const onHappening = (happening) => {
125
+ if (happening.kind !== "level") return;
126
+ if (happening.source !== "machine" && happening.source !== "limits") return;
127
+ const pain = hurts(happening);
128
+ const subject = String(happening.subject);
129
+ for (const { session } of touched(happening)) {
130
+ const key = `${session}\u0000${subject}`;
131
+ if (!pain && !put.has(key) && !told.has(key)) continue;
132
+ // The note still waiting about this pain: replaced by the newest, or taken back as it eased.
133
+ const waiting = takeSteers(session, PARENT, { event: "replaced" }, home, {
134
+ only: (item) => item.kind === SENSE && item.about?.pain === subject,
135
+ });
136
+ if (put.has(key) && !waiting.length) told.add(key);
137
+ put.delete(key);
138
+ if (pain) {
139
+ putSteer(
140
+ {
141
+ session,
142
+ agent: PARENT,
143
+ kind: SENSE,
144
+ text: `Pain: ${happening.text}.`,
145
+ about: { pain: subject },
146
+ },
147
+ home
148
+ );
149
+ put.add(key);
150
+ } else if (told.has(key)) {
151
+ putSteer(
152
+ {
153
+ session,
154
+ agent: PARENT,
155
+ kind: SENSE,
156
+ text: `Eased: ${happening.text}.`,
157
+ about: { pain: subject },
158
+ },
159
+ home
160
+ );
161
+ told.delete(key);
162
+ }
163
+ }
164
+ };
165
+
166
+ // How full each working session's context is, from its own record, against its model's window.
167
+ const filled = new Map();
168
+ const lookAtContexts = () => {
169
+ for (const each of sessionsAtWork(AT_WORK_MS, home, now())) {
170
+ if (!each.transcript || !["claude-code", "codex"].includes(each.agent))
171
+ continue;
172
+ const call = lastCallOf(each.agent, each.transcript);
173
+ if (!call) continue;
174
+ const known = store
175
+ ? windowFor(store, each.agent, call)
176
+ : call.window
177
+ ? { window: call.window }
178
+ : null;
179
+ if (!known?.window) continue;
180
+ const share = call.input / known.window;
181
+ const reached = FILLS.filter((fill) => share >= fill).at(-1);
182
+ const told = filled.get(each.session) ?? 0;
183
+ if (!reached || reached <= told) continue;
184
+ filled.set(each.session, reached);
185
+ const percent = Math.round(share * 100);
186
+ putSteer(
187
+ {
188
+ session: each.session,
189
+ agent: PARENT,
190
+ kind: SENSE,
191
+ text: `Pain: your context is ${percent}% full (${Math.round(call.input / 1000)}k of ${Math.round(known.window / 1000)}k tokens) and will be cut before long. Write your own notes now, in your words: what you are doing and why, what you decided and ruled out, what is open, and your next step.`,
192
+ about: { pain: "context" },
193
+ },
194
+ home
195
+ );
196
+ }
197
+ };
198
+ let contextTimer = null;
199
+
200
+ return {
201
+ start() {
202
+ stop ??= events.follow(onHappening);
203
+ contextTimer ??= setInterval(lookAtContexts, CONTEXT_LOOK_MS);
204
+ contextTimer.unref?.();
205
+ },
206
+ stop() {
207
+ stop?.();
208
+ stop = null;
209
+ clearInterval(contextTimer);
210
+ contextTimer = null;
211
+ },
212
+ /** Looks at the working sessions' contexts now (each minute otherwise). */
213
+ lookAtContexts,
214
+ };
215
+ }
package/lib/pairing.mjs CHANGED
@@ -3,6 +3,11 @@ import os from "node:os";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { loadMachine, saveMachine } from "./machineIdentity.mjs";
5
5
  import { newPairCode, pairClaim } from "./machineSeal.mjs";
6
+ import {
7
+ approvalCode,
8
+ approvalCommitment,
9
+ newApprovalSecret,
10
+ } from "./deviceIdentity.mjs";
6
11
 
7
12
  // Connecting a computer to the person's Harness account (Harness's server is the other end): setup asks Harness to hold
8
13
  // a pairing, shows the code, and waits on one held stream until the person approves it, which releases this computer's
@@ -17,8 +22,13 @@ import { newPairCode, pairClaim } from "./machineSeal.mjs";
17
22
  // Once connected, a computer Harness added to an account that already has a home is told where to type its code, and
18
23
  // works on its own meanwhile (joinSwarm).
19
24
 
20
- /** Ask Harness to hold a pairing for this computer. Returns { pairId, code, own } (own: setup made the code). */
21
- export async function startPairing(origin, agents) {
25
+ /**
26
+ * Ask Harness to hold a pairing for this computer. Returns { pairId, code, own } (own: setup made the code). `device`
27
+ * is this computer's id, name and public keys (deviceIdentity.mjs): the device that approves it signs exactly these
28
+ * onto the person's list, after the person matched the code both show. `commitment` locks in this computer's secret
29
+ * for that code before any device challenges it (deviceIdentity.mjs approvalCommitment).
30
+ */
31
+ export async function startPairing(origin, agents, device, commitment) {
22
32
  // The name the computer goes by everywhere else (machineIdentity.mjs).
23
33
  const hostname = os
24
34
  .hostname()
@@ -36,6 +46,8 @@ export async function startPairing(origin, agents) {
36
46
  const response = await start({
37
47
  hostname,
38
48
  agents,
49
+ device,
50
+ commitment,
39
51
  ...(await pairClaim(code)),
40
52
  });
41
53
  // Another computer's setup holds a code with the same first 4 characters.
@@ -46,7 +58,7 @@ export async function startPairing(origin, agents) {
46
58
  const { pairId } = await response.json();
47
59
  return { pairId, code, own: true };
48
60
  }
49
- const response = await start({ hostname, agents });
61
+ const response = await start({ hostname, agents, device, commitment });
50
62
  if (!response.ok)
51
63
  throw new Error(`pairing unavailable (HTTP ${response.status})`);
52
64
  const { pairId, code } = await response.json();
@@ -56,19 +68,16 @@ export async function startPairing(origin, agents) {
56
68
  /**
57
69
  * The page setup opens to approve this computer (src/main/mobile/PairComputer.tsx), in its address fragment: what
58
70
  * 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
71
+ * is also this computer's join secret and stays in the terminal and the person's own computers' Harness. An older
61
72
  * Harness's 8-character code is the account's only, and rides as it is (`c`).
62
73
  */
63
- export async function setupPageUrl(origin, { code, own }, browserLink = null) {
74
+ export async function setupPageUrl(origin, { code, own }) {
64
75
  const approval = own
65
76
  ? (({ lookup, verifier }) => ({ l: lookup, a: verifier }))(
66
77
  await pairClaim(code)
67
78
  )
68
79
  : { c: code };
69
- const fragment = [new URLSearchParams(approval).toString(), browserLink]
70
- .filter(Boolean)
71
- .join("&");
80
+ const fragment = new URLSearchParams(approval).toString();
72
81
  return `${String(origin).replace(/\/$/, "")}/pair#${fragment}`;
73
82
  }
74
83
 
@@ -81,8 +90,75 @@ export function keepJoinCode(machineFile, code) {
81
90
  });
82
91
  }
83
92
 
84
- /** Wait for the person's approval. Resolves with the connection token; rejects on expiry or a dropped stream. */
85
- export async function waitForApproval(origin, pairId) {
93
+ /**
94
+ * The secret behind this computer's commitment, revealed to the device that challenged it, with the commitment for
95
+ * its next secret (`{ challenge, reveal, next }`); or only a new commitment (`{ next }`). Tried a few times: an answer
96
+ * that never arrives leaves the approving device waiting. Returns whether Harness took it.
97
+ */
98
+ export async function revealSecret(origin, pairId, body) {
99
+ for (let attempt = 0; attempt < 3; attempt++) {
100
+ const response = await fetch(origin + "/api/pair/reveal", {
101
+ method: "POST",
102
+ headers: { "content-type": "application/json" },
103
+ body: JSON.stringify({ pairId, ...body }),
104
+ signal: AbortSignal.timeout(15_000),
105
+ }).catch(() => null);
106
+ if (response?.ok) return true;
107
+ // Another device's challenge took its place, or the pairing ended: nothing to answer.
108
+ if (response && response.status < 500) return false;
109
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
110
+ }
111
+ return false;
112
+ }
113
+
114
+ /**
115
+ * This computer's side of comparing codes with the device approving it (src/shared/deviceApproval.ts), for one
116
+ * pairing at a time: `commitment()` to start a pairing with, `answer(pairId, challenge)` for each challenge its held
117
+ * stream hears, `code()` for the code to show once answered (null before). `keys`: { sealingKey, signingKey }.
118
+ */
119
+ export async function createApprovalAnswers(origin, keys) {
120
+ const fresh = async () => {
121
+ const secret = newApprovalSecret();
122
+ return { secret, commitment: await approvalCommitment(keys, secret) };
123
+ };
124
+ let approval = await fresh();
125
+ let code = null;
126
+ return {
127
+ commitment: () => approval.commitment,
128
+ code: () => code,
129
+ /** A new pairing: a secret no challenge has seen. */
130
+ async renew() {
131
+ approval = await fresh();
132
+ code = null;
133
+ },
134
+ async answer(pairId, challenge) {
135
+ const answered = approval;
136
+ const made = await approvalCode(keys, answered.secret, challenge);
137
+ // The next secret is in place before this one goes out, so no secret answers two challenges.
138
+ approval = await fresh();
139
+ code = null;
140
+ if (
141
+ await revealSecret(origin, pairId, {
142
+ challenge,
143
+ reveal: answered.secret,
144
+ next: approval.commitment,
145
+ })
146
+ ) {
147
+ code = made;
148
+ return made;
149
+ }
150
+ // Turned down, or never heard: that secret went out, so the next one takes its place at Harness too.
151
+ await revealSecret(origin, pairId, { next: approval.commitment });
152
+ return null;
153
+ },
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Wait for the person's approval. Resolves with the connection token; rejects on expiry or a dropped stream.
159
+ * `onChallenge` answers each device that starts comparing codes with this computer meanwhile.
160
+ */
161
+ export async function waitForApproval(origin, pairId, onChallenge = null) {
86
162
  const response = await fetch(origin + "/api/pair/wait/" + pairId, {
87
163
  headers: { accept: "text/event-stream" },
88
164
  });
@@ -102,6 +178,10 @@ export async function waitForApproval(origin, pairId) {
102
178
  .find((entry) => entry.startsWith("data: "));
103
179
  if (!line) continue;
104
180
  const payload = JSON.parse(line.slice(6));
181
+ if (payload.challenge) {
182
+ await onChallenge?.(payload.challenge);
183
+ continue;
184
+ }
105
185
  if (payload.token) return payload.token;
106
186
  if (payload.error) throw new Error(payload.error);
107
187
  }
package/lib/paths.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
4
5
 
5
6
  // HARNESS_HOME is deliberately task-specific. It also makes every filesystem-affecting
6
7
  // command testable without touching a developer's real ~/.harness installation.
@@ -33,8 +34,12 @@ export const paths = {
33
34
  : path.join(harnessHome, "daemon.sock"),
34
35
  log: path.join(harnessHome, "daemon.log"),
35
36
  phoneIdentity: path.join(harnessHome, "phone-identity.json"),
36
- // The browser link setup makes for the page that approves this computer (phones.mjs writeBrowserOffer).
37
- browserOffer: path.join(harnessHome, "browser-offer.json"),
37
+ // This computer's id and signing key on the person's device list (deviceIdentity.mjs).
38
+ deviceIdentity: path.join(harnessHome, "device-identity.json"),
39
+ // The newest record of the person's device list this computer has seen, so an older list is refused.
40
+ deviceListSeen: path.join(harnessHome, "device-list-seen.json"),
41
+ // A recovery code this computer made for the person and has not shown them yet (computerDevices.mjs).
42
+ recoveryCode: path.join(harnessHome, "recovery-code.json"),
38
43
  machine: path.join(harnessHome, "machine.json"),
39
44
  // The person's name and preferences from their Harness profile (profile.mjs).
40
45
  profile: path.join(harnessHome, "profile.json"),
@@ -78,10 +83,13 @@ export function historyRoots(agent) {
78
83
  path.join(os.homedir(), ".codex", "sessions"),
79
84
  ];
80
85
  if (agent === "pi") {
86
+ // Harness's own setting replaces where Pi keeps sessions, as it does for Claude Code and Codex; added to them, a
87
+ // test daemon still read the person's real Pi history.
88
+ if (process.env.HARNESS_PI_HISTORY_ROOT)
89
+ return [process.env.HARNESS_PI_HISTORY_ROOT];
81
90
  return Array.from(
82
91
  new Set(
83
92
  [
84
- process.env.HARNESS_PI_HISTORY_ROOT,
85
93
  process.env.PI_CODING_AGENT_SESSION_DIR,
86
94
  process.env.PI_CODING_AGENT_DIR
87
95
  ? path.join(process.env.PI_CODING_AGENT_DIR, "sessions")
@@ -100,3 +108,34 @@ export function historyRoots(agent) {
100
108
  }
101
109
  return [];
102
110
  }
111
+
112
+ /** The installed release under a name that stays the same across updates (runtime-install.mjs links it). */
113
+ export const currentRuntimeLink = () => path.join(paths.runtime, "current");
114
+
115
+ /**
116
+ * The name an agent's hooks run Harness by: the `current` link when it leads to `release` (an installed release),
117
+ * else `release` itself (a checkout run from source, or Windows). A hook's command then stays the same across
118
+ * updates, so an agent that asks the person to approve a changed hook (Codex) asks once.
119
+ */
120
+ export function stableRuntimeRoot(release) {
121
+ const link = currentRuntimeLink();
122
+ try {
123
+ if (fs.realpathSync(link) === fs.realpathSync(release)) return link;
124
+ } catch {}
125
+ return release;
126
+ }
127
+
128
+ /**
129
+ * Whether the module at `metaUrl` is the program Node was started with. By real paths: an agent's hook starts it by the
130
+ * linked name (stableRuntimeRoot), which Node resolves, so the names differ though the file is the same.
131
+ */
132
+ export function ranAsProgram(metaUrl) {
133
+ try {
134
+ return (
135
+ fs.realpathSync(process.argv[1] ?? "") ===
136
+ fs.realpathSync(fileURLToPath(metaUrl))
137
+ );
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
@@ -1,5 +1,5 @@
1
1
  import fs from "node:fs";
2
- import { execFile } from "node:child_process";
2
+ import { execFile, spawnSync } from "node:child_process";
3
3
  import { PS } from "./nudge.mjs";
4
4
 
5
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
@@ -87,6 +87,20 @@ async function linuxPeers(fd) {
87
87
  ].map((match) => Number(match[1]));
88
88
  }
89
89
 
90
+ /**
91
+ * When a process started, as the system says: with its number, it tells a process Harness started from a later one
92
+ * given the same number (after a restart, say). "" where that cannot be read (Windows, or ps failing).
93
+ */
94
+ export function processStart(pid) {
95
+ if (process.platform === "win32") return "";
96
+ const listed = spawnSync(PS, ["-o", "lstart=", "-p", String(pid)], {
97
+ encoding: "utf8",
98
+ // One format whatever language the daemon was started in (launchd's or a terminal's).
99
+ env: { ...process.env, LC_ALL: "C" },
100
+ });
101
+ return listed.stdout?.trim() ?? "";
102
+ }
103
+
90
104
  /** Whether this system can name a socket's peer at all. */
91
105
  export const seesPeers = ["darwin", "linux"].includes(process.platform);
92
106
 
@@ -110,15 +124,15 @@ export async function processParents() {
110
124
  return parent;
111
125
  }
112
126
 
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) {
127
+ /** The one of `roots` that any of `pids` is or descends from, by the parents in `parent`; null when none is. */
128
+ export function rootOf(pids, roots, parent) {
115
129
  const wanted = new Set(roots);
116
- return pids.some((pid) => {
130
+ for (const pid of pids) {
117
131
  const seen = new Set();
118
132
  for (let at = pid; at > 1 && !seen.has(at); at = parent.get(at)) {
119
- if (wanted.has(at)) return true;
133
+ if (wanted.has(at)) return at;
120
134
  seen.add(at);
121
135
  }
122
- return false;
123
- });
136
+ }
137
+ return null;
124
138
  }