tryharness 0.7.83 → 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 (215) 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 +191 -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 +52 -0
  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 +2426 -338
  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 +1 -1
  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/originals.mjs +216 -0
  107. package/lib/outsideEvents.mjs +383 -0
  108. package/lib/outsideRuns.mjs +230 -0
  109. package/lib/ownMachines.mjs +674 -256
  110. package/lib/pain.mjs +215 -0
  111. package/lib/pairing.mjs +91 -11
  112. package/lib/paths.mjs +42 -3
  113. package/lib/peerProcess.mjs +21 -7
  114. package/lib/peopleLink.mjs +268 -0
  115. package/lib/personNotices.mjs +3 -2
  116. package/lib/phones.mjs +252 -542
  117. package/lib/placeCards.mjs +282 -0
  118. package/lib/placeChecks.mjs +95 -0
  119. package/lib/placeCommands.mjs +8 -17
  120. package/lib/placeRequests.mjs +152 -0
  121. package/lib/placeStore.mjs +295 -0
  122. package/lib/placeTool.d.ts +12 -0
  123. package/lib/placeTool.js +40 -0
  124. package/lib/places.mjs +63 -14
  125. package/lib/plans.mjs +53 -8
  126. package/lib/presence.mjs +270 -0
  127. package/lib/privateNetwork.d.ts +2 -0
  128. package/lib/privateNetwork.js +93 -0
  129. package/lib/proposals.mjs +300 -0
  130. package/lib/publicFetch.d.ts +32 -0
  131. package/lib/publicFetch.js +248 -0
  132. package/lib/reach.mjs +128 -0
  133. package/lib/rebuildable.mjs +72 -0
  134. package/lib/recall.mjs +216 -0
  135. package/lib/record.mjs +13 -0
  136. package/lib/reflexes.mjs +392 -0
  137. package/lib/relayLimits.mjs +31 -2
  138. package/lib/releaseNotice.mjs +198 -0
  139. package/lib/removeHarness.mjs +15 -4
  140. package/lib/repoLinks.mjs +204 -35
  141. package/lib/runAuthority.mjs +102 -39
  142. package/lib/runBrief.mjs +93 -40
  143. package/lib/runRequests.mjs +52 -14
  144. package/lib/runUsage.mjs +31 -0
  145. package/lib/runWorker.mjs +74 -25
  146. package/lib/runner.mjs +289 -45
  147. package/lib/runtime-install.mjs +37 -8
  148. package/lib/schedules.mjs +171 -47
  149. package/lib/screenWatches.mjs +221 -0
  150. package/lib/sealed.mjs +12 -30
  151. package/lib/sealedThreads.mjs +198 -392
  152. package/lib/secretStore.mjs +178 -0
  153. package/lib/secrets.mjs +11 -0
  154. package/lib/seen.mjs +3 -9
  155. package/lib/selfUpdate.mjs +51 -15
  156. package/lib/senseCall.mjs +1514 -0
  157. package/lib/senseHook.mjs +114 -0
  158. package/lib/senseTools.mjs +1298 -0
  159. package/lib/sessionBriefs.mjs +87 -0
  160. package/lib/sessionControl.mjs +63 -13
  161. package/lib/sessionFiles.mjs +85 -0
  162. package/lib/setupChoices.mjs +12 -3
  163. package/lib/setupMode.mjs +70 -25
  164. package/lib/sharedKeys.mjs +166 -0
  165. package/lib/sleep.mjs +396 -0
  166. package/lib/sources.mjs +306 -0
  167. package/lib/speech.mjs +166 -411
  168. package/lib/spoken.mjs +210 -0
  169. package/lib/steerHook.mjs +3 -1
  170. package/lib/steerQueue.mjs +40 -11
  171. package/lib/store.mjs +323 -130
  172. package/lib/stuck.mjs +85 -7
  173. package/lib/swarm.mjs +157 -49
  174. package/lib/swarmDevices.mjs +25 -85
  175. package/lib/swarmMemory.mjs +93 -9
  176. package/lib/t3.mjs +73 -3
  177. package/lib/taskCommands.mjs +51 -60
  178. package/lib/taskRooms.mjs +30 -4
  179. package/lib/taskRules.json +29 -0
  180. package/lib/taskRules.mjs +21 -0
  181. package/lib/taskRuns.mjs +74 -11
  182. package/lib/team.mjs +2 -1
  183. package/lib/threadActions.mjs +37 -9
  184. package/lib/threadAuthority.mjs +4 -4
  185. package/lib/threadBriefs.mjs +173 -43
  186. package/lib/threadNotes.mjs +320 -0
  187. package/lib/threadRecord.mjs +491 -0
  188. package/lib/threadRuns.mjs +216 -108
  189. package/lib/threadView.mjs +27 -30
  190. package/lib/threadWatches.mjs +1962 -0
  191. package/lib/timeSense.mjs +839 -0
  192. package/lib/tripwires.mjs +454 -0
  193. package/lib/ui.mjs +1 -1
  194. package/lib/vault.mjs +560 -45
  195. package/lib/vaultCommands.mjs +5 -3
  196. package/lib/vaultPeers.mjs +165 -0
  197. package/lib/vaultTools.d.ts +4 -1
  198. package/lib/vaultTools.js +22 -1
  199. package/lib/verdicts.mjs +12 -26
  200. package/lib/versions.mjs +117 -0
  201. package/lib/waitTool.mjs +278 -0
  202. package/lib/wakePicture.mjs +268 -0
  203. package/lib/wakeQueue.mjs +108 -0
  204. package/lib/watchResponses.mjs +533 -0
  205. package/lib/watches.mjs +290 -145
  206. package/lib/windowAsks.mjs +80 -17
  207. package/lib/worktrees.mjs +159 -9
  208. package/npm-shrinkwrap.json +138 -631
  209. package/package.json +7 -6
  210. package/release.json +211 -129
  211. package/lib/callSessions.mjs +0 -51
  212. package/lib/directLink.mjs +0 -349
  213. package/lib/peopleBoard.mjs +0 -131
  214. package/lib/projects.mjs +0 -2917
  215. package/lib/roomChannels.mjs +0 -667
package/lib/schedules.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { CLOCK_LOOK_MS } from "./sources.mjs";
2
3
 
3
4
  // Check-ins: a thread's agents woken again later on their own, for work that runs longer than one turn (a render, a
4
5
  // deploy, a market that settles tomorrow) or that should be looked at again and again. The person
@@ -8,12 +9,18 @@ import { randomUUID } from "node:crypto";
8
9
  // A run missed while the relay was off or the Mac slept happens once when it is back, saying how late it is, never once
9
10
  // for each slot it missed. A paused thread skips its runs and picks up at the next one after it resumes; a one-time
10
11
  // check-in waits for the resume, since it has no next one. A thread that ends ends its check-ins.
12
+ //
13
+ // The clock (sources.mjs) says when the soonest run comes; each time it comes is a happening in the log (events.mjs),
14
+ // which every check-in then due answers. A one-time check-in held for a paused thread waits for `tick`, which each way
15
+ // a thread is opened again calls (swarm.mjs, the daemon's resumed).
16
+ //
17
+ // A check-in is a watch on the clock (docs/senses-plan.md S3.2): a row of kind "check-in" in the watch table
18
+ // (threadWatches.mjs), kept on home, which runs them, and copied to every computer, so they go where home goes. Its run
19
+ // is a wake through the response table (watchResponses.mjs): its post in the thread, then the agents it names or the
20
+ // lead's round.
11
21
 
12
- // Node's timers stop counting while the Mac sleeps, so a long timer would fire hours late; the wall clock is read on a
13
- // short poll instead.
14
- const POLL_MS = 30_000;
15
- // Within two polls of its time a run is on time; later, its post says it ran late and when it was due.
16
- const LATE_AFTER_MS = 2 * POLL_MS;
22
+ // Within two of the clock's looks of its time a run is on time; later, its post says it ran late and when it was due.
23
+ const LATE_AFTER_MS = 2 * CLOCK_LOOK_MS;
17
24
  // The shortest repeat, the same as automations on Harness's server (kept in step with it).
18
25
  export const MIN_EVERY_MINUTES = 5;
19
26
  const WHAT_CHARS = 2_000;
@@ -140,55 +147,165 @@ export function describeCadence(cadence) {
140
147
  return `${days} at ${cadence.time}`;
141
148
  }
142
149
 
150
+ const parsed = (text, fallback) => {
151
+ try {
152
+ return JSON.parse(text) ?? fallback;
153
+ } catch {
154
+ return fallback;
155
+ }
156
+ };
157
+
158
+ /** A check-in as its row in the watch table holds it. */
159
+ const rowOf = (schedule, machineId, at) => ({
160
+ id: schedule.id,
161
+ thread: schedule.threadId,
162
+ machine: machineId,
163
+ armed_by: schedule.by,
164
+ answers: schedule.agents.length ? schedule.agents.join(", ") : "lead",
165
+ source: JSON.stringify({ kind: "clock" }),
166
+ condition: JSON.stringify({ when: "due", cadence: schedule.cadence }),
167
+ response: JSON.stringify({
168
+ do: "wake",
169
+ agents: schedule.agents,
170
+ by: schedule.by,
171
+ post: true,
172
+ }),
173
+ detail: JSON.stringify({
174
+ what: schedule.what,
175
+ maxRuns: schedule.maxRuns,
176
+ endsAt: schedule.endsAt,
177
+ runs: schedule.runs,
178
+ nextAt: schedule.nextAt,
179
+ lastRanAt: schedule.lastRanAt,
180
+ ...(schedule.skipped ? { skipped: schedule.skipped } : {}),
181
+ }),
182
+ state: schedule.state,
183
+ why: schedule.endedWhy ?? null,
184
+ created_at: schedule.createdAt,
185
+ updated_at: at,
186
+ });
187
+
188
+ /** The check-in a row holds, as the commands, the lead's round and the person read it. */
189
+ const scheduleOf = (row) => {
190
+ const detail = parsed(row.detail, {});
191
+ const response = parsed(row.response, {});
192
+ return {
193
+ id: row.id,
194
+ threadId: row.thread,
195
+ what: detail.what ?? "",
196
+ agents: response.agents ?? [],
197
+ cadence: parsed(row.condition, {}).cadence,
198
+ by: row.armed_by === "user" ? "user" : "lead",
199
+ maxRuns: detail.maxRuns ?? null,
200
+ endsAt: detail.endsAt ?? null,
201
+ state: row.state,
202
+ runs: detail.runs ?? 0,
203
+ nextAt: detail.nextAt ?? null,
204
+ lastRanAt: detail.lastRanAt ?? null,
205
+ createdAt: row.created_at,
206
+ ...(detail.skipped ? { skipped: detail.skipped } : {}),
207
+ ...(row.state === "ended" ? { endedWhy: row.why ?? null } : {}),
208
+ };
209
+ };
210
+
143
211
  /**
144
- * The relay's check-ins, kept in the store. `fire(schedule, { late })` is one run; `late` says when it was due, in
145
- * words, when it runs later than that.
212
+ * The relay's check-ins, kept in the watch table. `fire(schedule, { late, cause })` is one run; `late` says when it
213
+ * was due, in words, when it runs later than that; `cause` is the clock's happening in the log. `sources` gives the
214
+ * clock that runs them; without it the caller runs `tick`. Only home runs them (`isHome`); every computer reads them.
146
215
  */
147
216
  export function createSchedules({
148
217
  store,
149
218
  fire,
219
+ sources = null,
220
+ machineId = "home",
221
+ isHome = () => true,
150
222
  log = () => {},
151
223
  now = () => Date.now(),
152
224
  }) {
153
- const list = () => {
154
- try {
155
- return JSON.parse(store.meta("schedules") || "[]");
156
- } catch {
157
- return [];
158
- }
159
- };
160
- const save = (schedules) =>
161
- store.meta("schedules", JSON.stringify(schedules));
162
- const update = (id, change) =>
163
- save(
164
- list().map((schedule) =>
165
- schedule.id === id ? { ...schedule, ...change } : schedule
225
+ const db = store.db;
226
+ const list = () =>
227
+ db
228
+ .all(
229
+ "select * from board_watches where kind = 'check-in' order by created_at, id"
166
230
  )
231
+ .map(scheduleOf);
232
+ const write = (schedule) => {
233
+ const row = rowOf(schedule, machineId, new Date(now()).toISOString());
234
+ db.run(
235
+ "insert into board_watches(id, thread, machine, armed_by, answers, source, condition, kind, response, detail, state, why, armed, created_at, updated_at) values(?, ?, ?, ?, ?, ?, ?, 'check-in', ?, ?, ?, ?, null, ?, ?) on conflict(id) do update set answers = excluded.answers, response = excluded.response, detail = excluded.detail, state = excluded.state, why = excluded.why, updated_at = excluded.updated_at",
236
+ [
237
+ row.id,
238
+ row.thread,
239
+ row.machine,
240
+ row.armed_by,
241
+ row.answers,
242
+ row.source,
243
+ row.condition,
244
+ row.response,
245
+ row.detail,
246
+ row.state,
247
+ row.why,
248
+ row.created_at,
249
+ row.updated_at,
250
+ ]
167
251
  );
252
+ };
253
+ const update = (id, change) => {
254
+ const schedule = list().find((entry) => entry.id === id);
255
+ if (schedule) write({ ...schedule, ...change });
256
+ };
168
257
  const ended = (why) => ({ state: "ended", endedWhy: why, nextAt: null });
169
258
  const shown = (schedule) => ({
170
259
  ...schedule,
171
260
  when: describeCadence(schedule.cadence),
172
261
  });
173
- let timer = null,
174
- soon = null;
175
- // The next run sooner than the next poll gets a timer of its own, so it runs on time while the Mac is awake. A run held
176
- // for a paused thread is left to the polls.
177
- const armSoonest = () => {
178
- clearTimeout(soon);
179
- if (!timer) return;
262
+ // Today's check-ins, kept in home's meta before they were rows: each moves in once, with its id, runs and next run.
263
+ // The meta is left as it was.
264
+ const moveIn = () => {
265
+ if (!isHome() || store.meta("schedules-moved") === "1") return;
266
+ for (const schedule of parsed(store.meta("schedules"), []))
267
+ if (!db.get("select id from board_watches where id = ?", [schedule.id]))
268
+ write(schedule);
269
+ store.meta("schedules-moved", "1");
270
+ };
271
+ let started = false;
272
+ // The time the clock is asked for: the soonest run, and how to stop asking. A run already due (missed while the relay
273
+ // was off) is asked for too, so the clock says how late it came; a one-time check-in held for a paused thread is not.
274
+ let waitingFor = null;
275
+ const held = (schedule, at) =>
276
+ schedule.cadence.kind === "once" &&
277
+ Date.parse(schedule.nextAt) <= at &&
278
+ store.getTask(schedule.threadId)?.status === "paused";
279
+ const arm = () => {
280
+ if (!started || !sources || !isHome()) {
281
+ waitingFor?.stop();
282
+ waitingFor = null;
283
+ return;
284
+ }
180
285
  const at = now();
181
- const waits = list()
182
- .filter((schedule) => schedule.state === "on")
183
- .map((schedule) => Date.parse(schedule.nextAt) - at)
184
- .filter((wait) => wait > 0 && wait < POLL_MS);
185
- if (!waits.length) return;
186
- soon = setTimeout(tick, Math.min(...waits));
187
- soon.unref?.();
286
+ const times = list()
287
+ .filter((schedule) => schedule.state === "on" && !held(schedule, at))
288
+ .map((schedule) => Date.parse(schedule.nextAt));
289
+ const soonest = times.length ? Math.min(...times) : null;
290
+ if (waitingFor?.at === soonest) return;
291
+ waitingFor?.stop();
292
+ waitingFor = null;
293
+ if (soonest === null) return;
294
+ const asked = {
295
+ at: soonest,
296
+ stop: sources.subscribe({ kind: "clock", at: soonest }, (reading) => {
297
+ asked.stop();
298
+ if (waitingFor === asked) waitingFor = null;
299
+ tick(reading?.event ?? null);
300
+ }),
301
+ };
302
+ waitingFor = asked;
188
303
  };
189
304
 
190
- // One pass over every check-in: run what is due, once each however many runs it missed.
191
- const tick = () => {
305
+ // One pass over every check-in: run what is due, once each however many runs it missed. Only home runs them.
306
+ const tick = (cause = null) => {
307
+ if (!isHome()) return arm();
308
+ moveIn();
192
309
  const at = now();
193
310
  for (const schedule of list()) {
194
311
  if (schedule.state !== "on" || Date.parse(schedule.nextAt) > at) continue;
@@ -228,12 +345,13 @@ export function createSchedules({
228
345
  at - dueAt > LATE_AFTER_MS
229
346
  ? `${clock(new Date(dueAt))} on ${shortDate(new Date(dueAt))}`
230
347
  : null,
348
+ cause,
231
349
  });
232
350
  } catch (error) {
233
351
  log(`check-in ${schedule.id}: ${error.message}`);
234
352
  }
235
353
  }
236
- armSoonest();
354
+ arm();
237
355
  };
238
356
 
239
357
  /** Every check-in on a thread (or every thread's), with when it runs in words; ended ones only when asked. */
@@ -295,8 +413,8 @@ export function createSchedules({
295
413
  lastRanAt: null,
296
414
  createdAt: new Date(now()).toISOString(),
297
415
  };
298
- save([...list(), schedule]);
299
- armSoonest();
416
+ write(schedule);
417
+ arm();
300
418
  return { ok: true, schedule: shown(schedule) };
301
419
  };
302
420
 
@@ -330,6 +448,7 @@ export function createSchedules({
330
448
  if (!schedule || schedule.state !== "on")
331
449
  return { ok: false, error: "no such check-in" };
332
450
  update(id, ended("you removed it"));
451
+ arm();
333
452
  return {
334
453
  ok: true,
335
454
  schedule: shown(list().find((entry) => entry.id === id)),
@@ -345,17 +464,22 @@ export function createSchedules({
345
464
  }));
346
465
  },
347
466
  tick,
348
- /** Starts the poll, running at once whatever came due while the relay was off. */
467
+ /** Once started: runs what is due and asks the clock again, as when this computer became home or stopped being it. */
468
+ lookAgain() {
469
+ if (started) tick();
470
+ },
471
+ /** Starts the check-ins: what came due while the relay was off runs at once, as the clock says it came late. */
349
472
  start() {
350
- if (timer) return;
351
- tick();
352
- timer = setInterval(tick, POLL_MS);
353
- timer.unref?.();
473
+ if (started) return;
474
+ started = true;
475
+ moveIn();
476
+ if (sources) arm();
477
+ else tick();
354
478
  },
355
479
  stop() {
356
- clearInterval(timer);
357
- clearTimeout(soon);
358
- timer = null;
480
+ started = false;
481
+ waitingFor?.stop();
482
+ waitingFor = null;
359
483
  },
360
484
  };
361
485
  }
@@ -0,0 +1,221 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ // Screen watches a thread keeps (docs/senses-plan.md S7.1; the browser's side is src/main/owner/watchOps.ts). The
4
+ // browser's watchers are the only thing that sees the person's screen, so a thread's screen watch runs there: this
5
+ // computer keeps it on the board with its thread (threadWatches.mjs, source kind "screen") and installs it in the
6
+ // person's browser through the door, under its own key. What comes back is only that it fired (its intent, the number
7
+ // it read and its short detail), that it can no longer see, and that it sees again; the fire is a happening in this
8
+ // computer's log, from outside (what is on a screen is a page's, not the person's), and wakes the thread by the one wake
9
+ // path. While no browser can see it the watch is blind, and the thread says so; it is installed again when a browser
10
+ // is back. A browser that reloads forgets its watches: a call from it is the sign it is back, and at most every 10 s
11
+ // (threadWatches.mjs's own reconcile pace) the browser is asked what it holds and given what it lost.
12
+
13
+ const RECONCILE_MS = 10_000;
14
+ /** Set by phones.mjs on a browser's own `board.watch.screen`: JSON cannot carry it, so nothing else can say a fire. */
15
+ export const FROM_BROWSER = Symbol("a browser's own word about a screen watch");
16
+ // A door call's deadline: a watch's first look waits as long (threadWatches.mjs FIRST_LOOK_MS).
17
+ const DOOR_MS = 10_000;
18
+
19
+ const keyOf = (options) =>
20
+ createHash("sha256")
21
+ .update(JSON.stringify(options.spec ?? null))
22
+ .digest("hex")
23
+ .slice(0, 24);
24
+
25
+ // What an agent asks for in plain fields (the watch_screen tool), as the browser's watcher spec
26
+ // (src/schemas/watcherSpec.ts): a label on the screen, and what happens at it. An edit distance of 1 for the label, as
27
+ // the screen tools tell models to use for short labels (src/runtime/client-channel/screenTools.ts).
28
+ const WHEN = ["appears", "disappears", "changes", "above", "below"];
29
+ const SIDES = {
30
+ right: "same-row-right",
31
+ below: "below",
32
+ left: "same-row-left",
33
+ };
34
+
35
+ /** The screen watch an agent's watch_screen names, as board.watch.arm takes it, or `{ error }`. */
36
+ export function screenWatchRequest(args) {
37
+ const intent = String(args.intent ?? "").trim();
38
+ const label = String(args.label ?? "").trim();
39
+ const when = String(args.when ?? "");
40
+ if (!intent) return { error: "say in plain words what to watch for" };
41
+ if (!label || label.length > 120)
42
+ return {
43
+ error: "name the text on the screen it sits by (120 characters at most)",
44
+ };
45
+ if (!WHEN.includes(when))
46
+ return { error: `when is one of: ${WHEN.join(", ")}` };
47
+ const numeric = when === "above" || when === "below";
48
+ if (numeric && !Number.isFinite(Number(args.value)))
49
+ return { error: "above and below need the number" };
50
+ const nearby = Array.isArray(args.nearby)
51
+ ? args.nearby.map(String).filter(Boolean).slice(0, 4)
52
+ : [];
53
+ const spec = {
54
+ intent: intent.slice(0, 200),
55
+ anchor: { kind: "text", label, fuzz: 1, context: nearby },
56
+ ...(numeric
57
+ ? {
58
+ binding: {
59
+ kind: "value",
60
+ relation: SIDES[args.side] ?? SIDES.right,
61
+ type: "number",
62
+ },
63
+ }
64
+ : {}),
65
+ predicate: numeric
66
+ ? {
67
+ kind: "threshold",
68
+ op: when === "above" ? ">" : "<",
69
+ value: Number(args.value),
70
+ }
71
+ : when === "changes"
72
+ ? { kind: "region-change" }
73
+ : { kind: when === "appears" ? "appearance" : "disappearance" },
74
+ action: "thread",
75
+ };
76
+ return {
77
+ command: "board.watch.arm",
78
+ ...(typeof args.thread === "string" && args.thread
79
+ ? { thread: args.thread }
80
+ : {}),
81
+ source: {
82
+ kind: "screen",
83
+ spec,
84
+ ...(typeof args.page === "string" && args.page
85
+ ? { page: args.page }
86
+ : {}),
87
+ },
88
+ };
89
+ }
90
+
91
+ /**
92
+ * `askWindows(call)` asks the person's browser here (windowAsks.mjs); `computer()` is this computer's { id, label }.
93
+ * `kind` is the source adapter; `heard(request)` takes a browser's `board.watch.screen`; `browserCalled()` is told of
94
+ * every call a browser makes here.
95
+ */
96
+ export function createScreenWatches({
97
+ askWindows,
98
+ computer,
99
+ log = () => {},
100
+ now = () => Date.now(),
101
+ }) {
102
+ // Each running screen source by its key: its reporter, its options and whether a browser holds it now.
103
+ const running = new Map();
104
+ let lastCheck = 0;
105
+
106
+ const door = async (input) => {
107
+ const reply = await askWindows({
108
+ background: true,
109
+ door: {
110
+ op: "device.watch",
111
+ caller: {
112
+ kind: "daemon",
113
+ computer: computer(),
114
+ purpose: "a thread's screen watch",
115
+ route: "none",
116
+ },
117
+ input,
118
+ },
119
+ timeoutMs: DOOR_MS,
120
+ }).catch(() => null);
121
+ if (reply?.ok === true && reply.door?.ok === true) return reply.door.value;
122
+ const refused = reply?.door?.ok === false ? reply.door.error : null;
123
+ const reason = refused
124
+ ? String(refused.reason ?? refused.code ?? "")
125
+ : String(reply?.error ?? "");
126
+ throw new Error(reason || "no browser can see it now");
127
+ };
128
+
129
+ const install = async (key) => {
130
+ const entry = running.get(key);
131
+ if (!entry) return;
132
+ try {
133
+ await door({ action: "install", spec: entry.options.spec, keep: key });
134
+ entry.held = true;
135
+ entry.report({ at: now(), sees: true });
136
+ } catch (error) {
137
+ entry.held = false;
138
+ entry.report({ at: now(), error: error.message });
139
+ }
140
+ };
141
+
142
+ /** What the browser holds, and each watch it lost installed again. */
143
+ const reconcile = async () => {
144
+ if (!running.size) return;
145
+ let held;
146
+ try {
147
+ held = new Set(
148
+ ((await door({ action: "list" }))?.watches ?? []).map(
149
+ (watch) => watch.keep
150
+ )
151
+ );
152
+ } catch {
153
+ return;
154
+ }
155
+ for (const key of running.keys()) if (!held.has(key)) await install(key);
156
+ };
157
+
158
+ const kind = {
159
+ describe: (options) =>
160
+ `asks your browser to watch the screen for "${String(options.spec?.intent ?? "")}"`,
161
+ start(options, io) {
162
+ const key = keyOf(options);
163
+ running.set(key, { options, report: io.report, held: false });
164
+ // Never before start returns (sources.mjs).
165
+ const first = setImmediate(() => void install(key));
166
+ return {
167
+ stop() {
168
+ clearImmediate(first);
169
+ running.delete(key);
170
+ void door({ action: "kill", id: key }).catch(() => undefined);
171
+ },
172
+ };
173
+ },
174
+ };
175
+
176
+ /** A browser's word about one of this computer's watches: fired, cannot see, sees again. */
177
+ const heard = (request) => {
178
+ const entry = running.get(String(request.keep || ""));
179
+ if (!entry)
180
+ return { ok: false, error: "this computer keeps no such watch" };
181
+ if (request.event === "fired")
182
+ entry.report(
183
+ {
184
+ at: now(),
185
+ fired: {
186
+ value: typeof request.value === "number" ? request.value : null,
187
+ detail: String(request.detail ?? "").slice(0, 200),
188
+ },
189
+ },
190
+ {
191
+ kind: "fired",
192
+ text: `a screen watch fired${request.detail ? ` (${String(request.detail).slice(0, 120)})` : ""}`,
193
+ data: { key: request.keep },
194
+ trust: "untrusted",
195
+ }
196
+ );
197
+ else if (request.event === "blind") {
198
+ entry.held = false;
199
+ entry.report({
200
+ at: now(),
201
+ error: String(request.why || "it can no longer see the screen").slice(
202
+ 0,
203
+ 200
204
+ ),
205
+ });
206
+ } else if (request.event === "sees") {
207
+ entry.held = true;
208
+ entry.report({ at: now(), sees: true });
209
+ } else return { ok: false, error: "fired, blind or sees" };
210
+ return { ok: true };
211
+ };
212
+
213
+ /** Any call from a browser here: it is back, so what it does not hold is installed again (at most every 10 s). */
214
+ const browserCalled = () => {
215
+ if (!running.size || now() - lastCheck < RECONCILE_MS) return;
216
+ lastCheck = now();
217
+ void reconcile().catch((error) => log(`screen watches: ${error.message}`));
218
+ };
219
+
220
+ return { kind, heard, browserCalled };
221
+ }
package/lib/sealed.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import fs from "node:fs";
2
1
  import { timingSafeEqual, webcrypto } from "node:crypto";
2
+ import { readSecretFile, writeSecretFile } from "./secretStore.mjs";
3
3
 
4
4
  // Harness sealed channel, version 1 (HSC1): the phone talks to this daemon through Harness, and
5
5
  // Harness carries only ciphertext. The Harness app has a browser twin; both must produce the same
@@ -31,7 +31,8 @@ export const fromB64u = (text) =>
31
31
 
32
32
  export async function loadOrCreateIdentity(file) {
33
33
  try {
34
- const saved = JSON.parse(fs.readFileSync(file, "utf8"));
34
+ // In the keychain for the person's own Harness on a Mac (secretStore.mjs), else this 0600 file.
35
+ const saved = JSON.parse(readSecretFile(file));
35
36
  const privateKey = await subtle.importKey(
36
37
  "jwk",
37
38
  saved.privateJwk,
@@ -51,40 +52,14 @@ export async function loadOrCreateIdentity(file) {
51
52
  new Uint8Array(await subtle.exportKey("raw", pair.publicKey))
52
53
  );
53
54
  const privateJwk = await subtle.exportKey("jwk", pair.privateKey);
54
- fs.writeFileSync(
55
+ writeSecretFile(
55
56
  file,
56
57
  JSON.stringify({ version: SEALED_VERSION, publicKey, privateJwk }),
57
- { mode: 0o600, flag: "wx" }
58
+ { exclusive: true }
58
59
  );
59
60
  return loadOrCreateIdentity(file);
60
61
  }
61
62
 
62
- export async function pairProof(
63
- secret,
64
- offerId,
65
- devicePublicKey,
66
- daemonPublicKey
67
- ) {
68
- const key = await subtle.importKey(
69
- "raw",
70
- fromB64u(secret),
71
- { name: "HMAC", hash: "SHA-256" },
72
- false,
73
- ["sign"]
74
- );
75
- return b64u(
76
- new Uint8Array(
77
- await subtle.sign(
78
- "HMAC",
79
- key,
80
- encoder.encode(
81
- `HSC1-pair\n${offerId}\n${devicePublicKey}\n${daemonPublicKey}`
82
- )
83
- )
84
- )
85
- );
86
- }
87
-
88
63
  export async function channelKey(privateKey, peerPublicKey, deviceId) {
89
64
  const peer = await subtle.importKey(
90
65
  "raw",
@@ -189,6 +164,13 @@ export async function open(key, direction, envelope) {
189
164
  return JSON.parse(decoder.decode(plain));
190
165
  }
191
166
 
167
+ // What Harness sealed to this computer as it arrived (src/shared/crypto/sealedChannel.ts sealToComputer): an outside
168
+ // event, from a key pair made for it alone. Throws on a wrong key, id or any changed byte.
169
+ export async function openFromOutside(privateKey, envelope) {
170
+ const key = await channelKey(privateKey, envelope.from, envelope.deviceId);
171
+ return open(key, "x2d", envelope);
172
+ }
173
+
192
174
  export function constantTimeEqual(a, b) {
193
175
  const left = Buffer.from(String(a)),
194
176
  right = Buffer.from(String(b));