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
@@ -15,6 +15,7 @@ import {
15
15
  openNotice,
16
16
  pairClaim,
17
17
  pairKey,
18
+ QUEUED_MAX_AGE_MS,
18
19
  sameProof,
19
20
  sealAnswer,
20
21
  sealCall,
@@ -24,27 +25,74 @@ import {
24
25
  sealAskAnswer,
25
26
  openAskAnswer,
26
27
  } from "./machineSeal.mjs";
27
- import { findMachine, goesHome, queueable } from "./machineRoutes.mjs";
28
+ import {
29
+ computerMay,
30
+ findMachine,
31
+ FROM_MACHINE,
32
+ goesHome,
33
+ queueable,
34
+ } from "./machineRoutes.mjs";
28
35
  import { MERGE_COMMAND, MIRROR_COMMAND } from "./boardMirror.mjs";
36
+ import { DEVICES_COMMAND } from "./swarmDevices.mjs";
37
+ import { member } from "./members.mjs";
38
+ import { WINDOW_TOOLS } from "./windowAsks.mjs";
39
+
40
+ export { FROM_MACHINE };
29
41
 
30
42
  // A worker's key for a direct link, swapped for home's over the sealed channel (directLink.mjs).
31
43
  const DIRECT_COMMAND = "machine.direct";
44
+ // The person's model and effort for an agent live on the computer that runs it (models.mjs reads its own store), so
45
+ // the buddy's Swarm tab reads and sets them on each computer: a worker asks home, home asks the worker that has it.
46
+ const MODELS_COMMAND = "machine.models";
47
+ // A worker passing on the person's choice of another computer as Home (makeHome).
48
+ const HOME_COMMAND = "machine.home";
49
+ // Since when this worker has found home unreachable: { home, since, checked } (watchHome).
50
+ const HOME_AWAY = "home-away";
51
+ // Owner, October 26: a computer with Home switches only once Home has been away about a week. The count survives a
52
+ // restart or a night's sleep (a look at least hourly); a gap of more than a day between looks means this computer was
53
+ // off too and cannot say Home stayed away, so it counts again from then.
54
+ const AWAY_LOOK_MS = 60 * 60_000;
55
+ const AWAY_GAP_MS = 24 * 60 * 60_000;
56
+ const MODEL_COMMAND = "machine.model";
57
+ // A cloud computer's model call through a proxy link, to the computer that holds the link (proxyLinks.mjs).
58
+ const LINK_COMMAND = "machine.link";
59
+ // The person's SSH key let into one of their cloud computers (cloudSsh.mjs): from a computer they drive, through home,
60
+ // to the cloud computer, which takes it only from the home it follows.
61
+ const SSH_COMMAND = "machine.ssh";
62
+ // An agent that runs itself (Hermes, OpenClaw) is shown on a computer it called the board from this recently.
63
+ const SELF_RUN_SEEN_MS = 7 * 24 * 60 * 60_000;
32
64
 
33
65
  // The person's other computers (one swarm across them). One computer holds the board ("home"); every other one is a
34
66
  // worker: its agents' board calls go to home through Harness, sealed with the key the two computers share
35
67
  // (machineSeal.mjs), and home answers them on its board as that agent on that computer. Harness says which computers
36
68
  // there are and carries what they send; a computer trusts another only once the person confirmed it on home with the
37
69
  // worker's join code. A worker keeps what its agents write while home is out of reach and sends it when home is back.
38
- // Known limit: while home sleeps, workers can read nothing and take no new work.
70
+ // A worker not confirmed yet (new, or its home was set up again with a new key) works on a board of its own until the
71
+ // person types its code on home, then brings that board to home (boardMirror.mjs bring): it is never a computer that
72
+ // cannot work: a worker that could not work until home confirmed it would be broken.
39
73
 
40
- // Set on a board request by this module alone: the computer the call came from. JSON cannot carry it, so no caller
41
- // names a computer it is not on.
42
- export const FROM_MACHINE = Symbol("the computer a board call came from");
74
+ // Each computer keeps its own limits on what another of the person's computers may ask of it, and on its own role
75
+ // (security audit 2026-10-25, tier 2): home answers a worker's call only as what that worker is (computerMay), a worker
76
+ // runs what home lists only in a folder it knows (machineRuns.mjs), and a computer moves home, follows another or forgets
77
+ // one only on its own person's word or a sealed statement from a computer it confirmed, never on Harness's list alone.
43
78
 
44
79
  // Wrong join codes a worker takes before it makes a new one: Harness carries the guesses and must not get many.
45
80
  const JOIN_TRIES = 5;
81
+ // How long a join code lasts, setup's included: as long as a pairing code (src/server/bridge/pairHub.ts PAIR_TTL_MS),
82
+ // so a code read off a screen or a web page does not open this computer days later. A waiting computer shows a new one.
83
+ const JOIN_CODE_TTL_MS = 10 * 60_000;
46
84
  // How long home keeps trying a code typed for a computer that is not online yet: as long as its pairing code lasts.
47
85
  const ADD_WAIT_MS = 10 * 60_000;
86
+ // The home this computer follows (its own id while it is home, "" for none): set by the person's join on that home, this
87
+ // computer's own move, or a sealed statement from a computer confirmed here (onRoleStatement). Harness's list names a
88
+ // home; a worker follows it only when it is this one.
89
+ const ACCEPTED = "machine-home";
90
+ // When this computer last changed role or home, so a statement older than that moves nothing.
91
+ const ROLE_AT = "machine-role-at";
92
+ // Sealed notices for the person's other computers that Harness could not take yet (a removal, a statement of home).
93
+ const QUEUED_NOTICES = "machine-notices";
94
+ // Removals Harness has not done yet: tried again once this computer is back on Harness.
95
+ const REMOVALS = "machine-removals";
48
96
  const MB = 1024 * 1024;
49
97
  // What get_file shows inline on a worker, as on home (boardFileCommands.mjs).
50
98
  const INLINE_IMAGE_BYTES = 3.75 * MB;
@@ -73,21 +121,36 @@ export function createOwnMachines({
73
121
  answerMirror = null,
74
122
  // On home: a stand-in's changes, merged (boardMirror.mjs merge).
75
123
  answerMerge = null,
124
+ // On home: another computer's devices, and the person's decisions on them made there (swarmDevices.mjs answer).
125
+ answerDevices = null,
76
126
  // The direct links between the person's computers (directLink.mjs); null keeps every message to Harness.
77
127
  directLink = null,
78
- // How long home must be unreachable on every route before this worker stands in as home; null: it never does (the
79
- // owner sets it once the gaps are measured, owner October 21: "measure first").
128
+ // How long home must be unreachable on every route before this worker stands in as home (daemon.mjs: a week unless
129
+ // the person's config says otherwise); null: it never does.
80
130
  standInAfterMs = null,
81
131
  // This computer stood in for that one: its own changes from now on go back to it (boardMirror.mjs startStandIn).
82
132
  onStoodIn = () => {},
83
133
  // Another computer stands in for this one: it takes home back (boardMirror.mjs takeBack).
84
134
  returning = () => {},
135
+ // This computer works on a board of its own (a worker not confirmed yet), or stopped being home: what it holds goes
136
+ // to home once it is confirmed (boardMirror.mjs bring).
137
+ onOwnBoard = () => {},
85
138
  // This computer's own Harness windows, asked a question for their screen history (phones.mjs ask).
86
139
  askOwnWindows = async () => ({
87
140
  ok: false,
88
141
  code: "unpaired",
89
142
  error: "no Harness window is linked to this computer",
90
143
  }),
144
+ // This computer's own agents' models, read or one set, as the person (swarm.mjs board.swarm.models/model).
145
+ ownModels = async () => ({
146
+ ok: false,
147
+ error: "this computer cannot list its agents' models",
148
+ }),
149
+ // A proxy link's model call from one of the person's cloud computers, on the computer holding the link
150
+ // (proxyLinks.mjs answer); null where none is held.
151
+ answerLink = null,
152
+ // A cloud computer's own SSH keys (cloudSsh.mjs allow): { key, by } in, null on a computer that takes none.
153
+ ownSsh = null,
91
154
  }) {
92
155
  // On home: each worker's folders and the repository each holds, as it said them.
93
156
  const infos = new Map();
@@ -96,6 +159,7 @@ export function createOwnMachines({
96
159
  let siblings = [];
97
160
  let selfListed = null;
98
161
  let standInTimer = null;
162
+ let askingToStandIn = false;
99
163
  let flushing = false;
100
164
  // What home last heard of this computer's folders, false until it heard them on this connection.
101
165
  let toldHome = false;
@@ -103,10 +167,31 @@ export function createOwnMachines({
103
167
  const isHome = () => machine.role !== "worker";
104
168
  const homeListed = () =>
105
169
  siblings.find((sibling) => sibling.role === "home") ?? null;
170
+ // Before this was kept, a worker followed the home it joined and a home itself.
171
+ const acceptedHome = () =>
172
+ store.meta(ACCEPTED) ??
173
+ (machine.role === "worker" ? store.meta("joined-home") : machine.id);
174
+ const accept = (id) => {
175
+ store.meta(ACCEPTED, id ?? "");
176
+ store.meta(ROLE_AT, String(Date.now()));
177
+ };
178
+ // The home Harness lists, when it is the one this computer follows and holds its key.
106
179
  const pinnedHome = () => {
107
180
  const home = homeListed();
108
- return home ? store.ownMachine(home.id) : null;
181
+ return home && home.id === acceptedHome()
182
+ ? store.ownMachine(home.id)
183
+ : null;
109
184
  };
185
+ // Whether this computer was confirmed with another of the person's computers (it joined a home, or confirmed a
186
+ // worker). Older servers also need this in hello to preserve Home when the computer reconnects.
187
+ const confirmedWithAnother = () =>
188
+ Boolean(store.meta("joined-home")) || store.ownMachines().length > 0;
189
+ // Whether this worker holds home's key. Just started, before Harness lists the computers, a worker that was ever
190
+ // confirmed counts as confirmed, so it never writes on its copy of home's board.
191
+ const trusted = () =>
192
+ homeListed() ? Boolean(pinnedHome()) : confirmedWithAnother();
193
+ /** A worker not confirmed into the swarm yet: its agents work on this computer's own board meanwhile. */
194
+ const actsAlone = () => !isHome() && !trusted();
110
195
  const labelOf = (id) =>
111
196
  id === machine.id
112
197
  ? machine.label
@@ -133,17 +218,61 @@ export function createOwnMachines({
133
218
  machineId: machine.id,
134
219
  label: machine.label,
135
220
  ...(machine.role ? { role: machine.role } : {}),
221
+ joined: confirmedWithAnother(),
136
222
  });
137
223
 
138
- /** Harness's answer to this computer's hello: its role on the account. */
139
- const adopt = (given) => {
140
- if (!given || !["home", "worker"].includes(given.role)) return;
141
- if (machine.role && machine.role !== given.role)
224
+ // The role Harness last gave this computer, and whether it was told why it did not take it.
225
+ let given = null;
226
+ let toldKept = null;
227
+ /** Harness's answer to this computer's hello: its role on the account, taken as reconcileRole allows. */
228
+ const adopt = (answer) => {
229
+ if (!answer || !["home", "worker"].includes(answer.role)) return;
230
+ given = answer.role;
231
+ reconcileRole();
232
+ };
233
+ /**
234
+ * This computer's role, moved only where Harness's word can do no harm (S9): on a computer that trusts no other yet, or
235
+ * a home Harness lists under a home it never confirmed (it then trusts nobody and works on its own until the person
236
+ * joins it there). Otherwise a computer becomes home by its own move (makeHome, standIn) and stops being home on a
237
+ * sealed statement from the computer that is home now (onRoleStatement).
238
+ */
239
+ const reconcileRole = () => {
240
+ if (!given || given === machine.role) return;
241
+ if (!machine.role || !confirmedWithAnother())
242
+ return setRole(given, given === "home" ? machine.id : "");
243
+ const home = homeListed();
244
+ if (
245
+ given === "worker" &&
246
+ isHome() &&
247
+ home &&
248
+ !home.standInFor &&
249
+ !store.ownMachine(home.id)
250
+ )
251
+ return setRole("worker", "");
252
+ if (toldKept === given) return;
253
+ toldKept = given;
254
+ log(
255
+ given === "home"
256
+ ? "Harness lists this computer as home, but nobody here moved it: it stays a worker"
257
+ : `Harness lists ${home?.label || "another computer"} as home, but it has not said so itself: this computer stays home until it does`
258
+ );
259
+ };
260
+ const setRole = (role, followed) => {
261
+ if (machine.role && machine.role !== role)
142
262
  log(
143
- `this computer is now ${given.role === "home" ? "home: it holds the board" : "a worker: its agents reach the board on your home computer"}`
263
+ `this computer is now ${role === "home" ? "home: it holds the board" : "a worker: its agents reach the board on your home computer"}`
144
264
  );
145
- machine.role = given.role;
265
+ const leftHome = machine.role === "home" && role === "worker";
266
+ // A stand-in going back hands over what it wrote (boardMirror.mjs handOver); it brings no board of its own.
267
+ const wasStandIn = Boolean(store.meta("standing-in-for"));
268
+ machine.role = role;
269
+ // Setup's code is never a home's join code: a home is not waiting to join anything (M4).
270
+ if (role === "home") machine.joinCode = null;
146
271
  saveMachine(machine);
272
+ accept(followed);
273
+ if (role === "worker") store.meta("standing-in-for", "");
274
+ toldKept = null;
275
+ if (leftHome && !wasStandIn) onOwnBoard();
147
276
  changed();
148
277
  };
149
278
 
@@ -171,8 +300,12 @@ export function createOwnMachines({
171
300
  typeof listed.standInFor === "string" ? listed.standInFor : null,
172
301
  }));
173
302
  changed();
303
+ reconcileRole();
174
304
  retryAdding();
305
+ void sendQueued();
306
+ void retryRemovals();
175
307
  watchHome();
308
+ if (actsAlone()) void workAlone();
176
309
  // Someone stood in for this computer: it takes home back, at once if the stand-in is away too (boardMirror.mjs).
177
310
  if (someoneStandsIn()) returning();
178
311
  if (!homeListed()?.connected) toldHome = false;
@@ -207,27 +340,53 @@ export function createOwnMachines({
207
340
  (link) => link.id === home.id && link.linked
208
341
  );
209
342
  };
210
- // Home gone on every route (Harness lists it offline and no direct link answers): after the person's deadline this
211
- // worker asks Harness to let it stand in. Home back on any route first, nothing happens.
343
+ // Since when this worker has found home unreachable, kept on disk so a restart or the computer sleeping does not start
344
+ // the count again. Each look at home is noted too: a gap longer than AWAY_GAP_MS between two looks means this computer
345
+ // was off and cannot say home stayed away meanwhile, so the count starts again from now.
346
+ const awaySince = (homeId) => {
347
+ const now = Date.now();
348
+ let away = null;
349
+ try {
350
+ away = JSON.parse(store.meta(HOME_AWAY) || "null");
351
+ } catch {}
352
+ const since =
353
+ away?.home === homeId &&
354
+ Number.isFinite(away.since) &&
355
+ now - away.checked <= AWAY_GAP_MS
356
+ ? away.since
357
+ : now;
358
+ store.meta(
359
+ HOME_AWAY,
360
+ JSON.stringify({ home: homeId, since, checked: now })
361
+ );
362
+ return since;
363
+ };
364
+ // Home gone on every route (Harness lists it offline and no direct link answers): once it has been away for the
365
+ // person's deadline this worker asks Harness to let it stand in. Home back on any route first, the count ends.
212
366
  const watchHome = () => {
367
+ clearTimeout(standInTimer);
368
+ standInTimer = null;
213
369
  const waiting =
214
370
  standInAfterMs !== null &&
215
371
  !isHome() &&
216
372
  Boolean(pinnedHome()) &&
217
373
  homeUnreachable();
218
374
  if (!waiting) {
219
- clearTimeout(standInTimer);
220
- standInTimer = null;
375
+ if (store.meta(HOME_AWAY)) store.meta(HOME_AWAY, "");
221
376
  return;
222
377
  }
223
- standInTimer ??= setTimeout(
224
- () => {
225
- standInTimer = null;
226
- if (!isHome() && pinnedHome() && homeUnreachable()) void standIn();
227
- },
228
- // A timer longer than this fires at once (Node's limit, about 24.8 days).
229
- Math.min(standInAfterMs, 2 ** 31 - 1)
230
- );
378
+ const left = awaySince(homeListed().id) + standInAfterMs - Date.now();
379
+ if (left <= 0) {
380
+ if (!askingToStandIn) {
381
+ askingToStandIn = true;
382
+ void standIn().finally(() => (askingToStandIn = false));
383
+ }
384
+ // Refused (another computer stood in first, or Harness was out of reach): asked again at the next look.
385
+ standInTimer = setTimeout(watchHome, AWAY_LOOK_MS);
386
+ return;
387
+ }
388
+ // Looked at again at least hourly, so the look is noted and a computer that slept counts from its own clock.
389
+ standInTimer = setTimeout(watchHome, Math.min(left, AWAY_LOOK_MS));
231
390
  };
232
391
  const standIn = async () => {
233
392
  const answer = await ask("machine_role", {
@@ -235,17 +394,25 @@ export function createOwnMachines({
235
394
  standIn: true,
236
395
  }).catch(() => null);
237
396
  if (answer?.ok !== true || typeof answer.standInFor !== "string") return;
397
+ store.meta(HOME_AWAY, "");
238
398
  onStoodIn(answer.standInFor);
239
- machine.role = "home";
240
- saveMachine(machine);
241
- changed();
399
+ setRole("home", machine.id);
400
+ store.meta("standing-in-for", answer.standInFor);
401
+ // The computer it stands in for hears it from this one, sealed: only then may this one hand its writes back there.
402
+ queueNotice(answer.standInFor, {
403
+ role: {
404
+ home: machine.id,
405
+ at: Date.now(),
406
+ standInFor: answer.standInFor,
407
+ },
408
+ });
242
409
  await applyKept(answer.standInFor);
243
410
  log(
244
411
  `your home computer${labelOf(answer.standInFor) ? ` (${labelOf(answer.standInFor)})` : ""} is unreachable; this computer stands in as home until it is back`
245
412
  );
246
413
  };
247
414
  // What this computer kept for home before standing in (posts, reports) is home's work: done here now, on the board it
248
- // holds, so it goes back with the rest of what it wrote (review, October 21: it waited the whole stand-in).
415
+ // holds, so it goes back with the rest of what it wrote (it once waited the whole stand-in).
249
416
  const applyKept = async (formerHome) => {
250
417
  const pinned = store.ownMachine(formerHome);
251
418
  const kept = outbox();
@@ -269,59 +436,396 @@ export function createOwnMachines({
269
436
  `did ${kept.length} kept write(s) on the board this computer now holds`
270
437
  );
271
438
  };
272
- /** Home taking its place back from the computer that stood in, once it has that computer's changes. */
439
+ // A worker whose home is one it does not trust (its home was set up again, or it is new): what it kept for the home
440
+ // it trusted is done on its own board, which it brings to home once confirmed.
441
+ let alone = false;
442
+ const workAlone = async () => {
443
+ if (alone) return;
444
+ alone = true;
445
+ try {
446
+ onOwnBoard();
447
+ const formerHome = store.meta("joined-home");
448
+ if (formerHome && formerHome !== homeListed()?.id)
449
+ await applyKept(formerHome);
450
+ } catch (error) {
451
+ log(`the writes kept for home could not be done here: ${error.message}`);
452
+ } finally {
453
+ alone = false;
454
+ }
455
+ };
456
+
457
+ /**
458
+ * Home taking its place back from the computer that stood in, once it has that computer's changes. This computer stayed
459
+ * home all along (reconcileRole); Harness routes the swarm here again, and the stand-in hears it from this computer,
460
+ * sealed, so it goes back to being a worker.
461
+ */
273
462
  const reclaim = async () => {
274
- // Only the computer that stood in may merge its writes here afterwards (answerCall).
275
- const standing = homeListed()?.id;
276
- if (standing) store.meta("stood-in-by", standing);
463
+ // The computer Harness lists standing in may hand back what it wrote, sealed, once (answerMergeCall): Harness's list
464
+ // and that computer's own sealed pages together, as with its statement (onRoleStatement), never either alone.
465
+ const standing = someoneStandsIn() ? homeListed().id : null;
277
466
  const answer = await ask("machine_role", {
278
467
  role: "home",
279
468
  reclaim: true,
280
469
  }).catch(() => null);
281
470
  if (answer?.ok !== true) return false;
282
- machine.role = "home";
283
- saveMachine(machine);
284
- changed();
471
+ if (standing && store.ownMachine(standing))
472
+ store.meta("stood-in-by", standing);
473
+ setRole("home", machine.id);
474
+ announceHome();
285
475
  return true;
286
476
  };
287
477
 
288
- /** The person makes this computer home. The board stays on the computer that had it. */
289
- const makeHome = async () => {
478
+ // ---- what this computer says to the others, sealed, and keeps until Harness takes it ----
479
+
480
+ /** This computer is home: each computer confirmed here hears it from this one, not from Harness's list. */
481
+ const announceHome = () => {
482
+ const statement = { role: { home: machine.id, at: Date.now() } };
483
+ for (const pinned of store.ownMachines())
484
+ queueNotice(pinned.machine_id, statement);
485
+ };
486
+ const queuedNotices = () => {
487
+ try {
488
+ return JSON.parse(store.meta(QUEUED_NOTICES) || "[]");
489
+ } catch {
490
+ return [];
491
+ }
492
+ };
493
+ const queueNotice = (to, notice) => {
494
+ const kept = [...queuedNotices(), { to, notice, at: Date.now() }];
495
+ store.meta(QUEUED_NOTICES, JSON.stringify(kept.slice(-200)));
496
+ void sendQueued();
497
+ };
498
+ let sending = false;
499
+ let sendAgain = false;
500
+ // A notice stays here until the other computer took it, and no longer than a queued call lives.
501
+ const sendQueued = async () => {
502
+ if (sending) {
503
+ sendAgain = true;
504
+ return;
505
+ }
506
+ if (!isHome() || !queuedNotices().length) return;
507
+ sending = true;
508
+ sendAgain = false;
509
+ try {
510
+ const done = new Set();
511
+ const parked = new Set();
512
+ for (const entry of queuedNotices()) {
513
+ const key = `${entry.to}:${entry.at}`;
514
+ if (
515
+ Date.now() - entry.at > QUEUED_MAX_AGE_MS ||
516
+ !store.ownMachine(entry.to)
517
+ ) {
518
+ done.add(key);
519
+ continue;
520
+ }
521
+ // Harness keeps one already for that computer while it is offline: nothing more to send until it is back.
522
+ const away =
523
+ siblings.find((sibling) => sibling.id === entry.to)?.connected ===
524
+ false;
525
+ if (entry.parked && away) continue;
526
+ // Done once that computer took it. Kept by Harness for an offline computer, or refused (Harness still listing
527
+ // this computer in its old role, just before it dials again), it is sent again with the next list of computers:
528
+ // Harness hands a kept notice over only when that computer next says hello, which may have just passed. Each
529
+ // notice counts once there (onRoleStatement, removedByHome).
530
+ const answer = await noticeTo(entry.to, entry.notice);
531
+ if (answer?.ok === true && !answer.queued) done.add(key);
532
+ else if (answer?.queued) parked.add(key);
533
+ }
534
+ // Notices queued while these were sent stay for the next round.
535
+ store.meta(
536
+ QUEUED_NOTICES,
537
+ JSON.stringify(
538
+ queuedNotices()
539
+ .filter((entry) => !done.has(`${entry.to}:${entry.at}`))
540
+ .map((entry) =>
541
+ parked.has(`${entry.to}:${entry.at}`)
542
+ ? { ...entry, parked: true }
543
+ : entry
544
+ )
545
+ )
546
+ );
547
+ } finally {
548
+ sending = false;
549
+ // Asked again while these went (a new list of computers, a new notice): once more, for what is left.
550
+ if (sendAgain) void sendQueued();
551
+ }
552
+ };
553
+
554
+ /** Uninstalled: Harness takes this computer off the account, and the pairing it connects with stops working. */
555
+ const leave = async () => {
556
+ const answer = await ask("machine_leave", {}).catch((error) => ({
557
+ ok: false,
558
+ error: error.message,
559
+ }));
560
+ return answer?.left === true
561
+ ? { ok: true }
562
+ : { ok: false, error: answer?.error || "Harness did not answer" };
563
+ };
564
+
565
+ /**
566
+ * The person takes another of their computers off the account (the Swarm map's Remove, npx tryharness machines remove).
567
+ * Never home. On home it is done here first, whatever Harness says (M5): the computer's key and direct link are
568
+ * forgotten, and every computer confirmed here hears it, sealed from home; Harness then takes it off the account and
569
+ * ends its pairing, now or once this computer is back on Harness.
570
+ */
571
+ const remove = async (named) => {
572
+ const target =
573
+ findMachine(all(), named)?.id ??
574
+ store.ownMachines().find((pinned) => pinned.label === named)
575
+ ?.machine_id ??
576
+ String(named || "");
577
+ if (!target) return { ok: false, error: "which computer?" };
578
+ if (target === machine.id)
579
+ return {
580
+ ok: false,
581
+ error: "uninstall Harness to take this computer off",
582
+ };
583
+ const listed = siblings.find((sibling) => sibling.id === target);
584
+ if (listed?.role === "home")
585
+ return {
586
+ ok: false,
587
+ error: "Home keeps the board: make another computer home first.",
588
+ };
589
+ const here = isHome() && Boolean(store.ownMachine(target));
590
+ if (here) {
591
+ const label = labelOf(target) ?? target;
592
+ forget(target);
593
+ for (const pinned of store.ownMachines())
594
+ queueNotice(pinned.machine_id, {
595
+ removed: target,
596
+ at: Date.now(),
597
+ });
598
+ log(`${label} was removed from your swarm on this computer`);
599
+ }
600
+ const answer = await ask("machine_remove", { machineId: target }).catch(
601
+ (error) => ({ ok: false, error: error.message, unreached: true })
602
+ );
603
+ if (answer?.removed === true) {
604
+ removed({ machineId: target });
605
+ return { ok: true };
606
+ }
607
+ if (!here)
608
+ return { ok: false, error: answer?.error || "Harness did not answer" };
609
+ if (answer?.unreached || !answer) keepRemoval(target);
610
+ return {
611
+ ok: true,
612
+ note: answer?.unreached
613
+ ? "Harness is out of reach: it takes the computer off your account once this computer is back on it."
614
+ : `Harness did not take it off your account (${answer?.error || "no answer"}); this computer no longer trusts it.`,
615
+ };
616
+ };
617
+ const forget = (id) => {
618
+ store.unpinOwnMachine(id);
619
+ directLink?.disallow?.(id);
620
+ infos.delete(id);
621
+ store.meta(`bring-armed:${id}`, "");
622
+ if (store.meta("stood-in-by") === id) store.meta("stood-in-by", "");
623
+ changed();
624
+ };
625
+ const removals = () => {
626
+ try {
627
+ return JSON.parse(store.meta(REMOVALS) || "[]");
628
+ } catch {
629
+ return [];
630
+ }
631
+ };
632
+ const keepRemoval = (id) =>
633
+ store.meta(REMOVALS, JSON.stringify([...new Set([...removals(), id])]));
634
+ let removing = false;
635
+ const retryRemovals = async () => {
636
+ if (removing || !removals().length) return;
637
+ removing = true;
638
+ try {
639
+ for (const id of removals()) {
640
+ const answer = await ask("machine_remove", { machineId: id }).catch(
641
+ () => null
642
+ );
643
+ if (!answer) return;
644
+ store.meta(
645
+ REMOVALS,
646
+ JSON.stringify(removals().filter((each) => each !== id))
647
+ );
648
+ if (answer.removed === true) removed({ machineId: id });
649
+ }
650
+ } finally {
651
+ removing = false;
652
+ }
653
+ };
654
+
655
+ /** Harness says a computer was taken off the account: it is no longer listed, and its key is forgotten here. */
656
+ const removed = (message) => {
657
+ const id = String(message?.machineId || "");
658
+ if (id === machine.id) {
659
+ log(
660
+ "this computer was removed from your swarm on another of your computers: run npx tryharness setup to add it again"
661
+ );
662
+ return;
663
+ }
664
+ siblings = siblings.filter((sibling) => sibling.id !== id);
665
+ if (store.ownMachine(id)) {
666
+ forget(id);
667
+ log(`${labelOf(id) ?? id} was removed from your swarm`);
668
+ }
669
+ changed();
670
+ };
671
+
672
+ /** On a worker: home took a computer off the swarm, sealed. This one, or another this computer trusts. */
673
+ const removedByHome = (id) => {
674
+ if (id === machine.id) {
675
+ const home = acceptedHome();
676
+ if (home) forget(home);
677
+ accept("");
678
+ log(
679
+ "your home computer removed this computer from your swarm: it works on its own until you add it again"
680
+ );
681
+ changed();
682
+ return;
683
+ }
684
+ if (!store.ownMachine(id)) return;
685
+ forget(id);
686
+ log(
687
+ `${labelOf(id) ?? id} was removed from your swarm on your home computer`
688
+ );
689
+ };
690
+
691
+ /**
692
+ * This computer takes Home, as the person asked. The board stays on the computer that had it. `computers`: the
693
+ * person's other computers' keys, as the Home before this one pinned them, so they stay confirmed here.
694
+ */
695
+ const becomeHome = async (computers = []) => {
696
+ for (const other of Array.isArray(computers) ? computers : [])
697
+ if (
698
+ typeof other?.id === "string" &&
699
+ other.id !== machine.id &&
700
+ typeof other.publicKey === "string"
701
+ )
702
+ store.pinOwnMachine(
703
+ other.id,
704
+ other.publicKey,
705
+ String(other.label || "")
706
+ );
707
+ if (isHome() && !standingIn()) return { ok: true, before: null };
290
708
  const answer = await ask("machine_role", { role: "home" });
291
709
  if (!answer?.ok)
292
710
  return { ok: false, error: answer?.error || "Harness did not answer" };
293
- machine.role = "home";
294
- saveMachine(machine);
295
- changed();
296
- return { ok: true, before: answer.before ?? null };
711
+ const before = answer.before ?? null;
712
+ // The computer that was home brings its board here once it hears this one is home (boardMirror.mjs bring).
713
+ if (before) store.meta(`bring-armed:${before}`, "1");
714
+ setRole("home", machine.id);
715
+ announceHome();
716
+ return { ok: true, before };
717
+ };
718
+ /**
719
+ * The person makes one of their computers Home: this one, or another, which is asked over the sealed line between
720
+ * the person's computers (through home when this is a worker) and moves Home itself. Harness only records it.
721
+ */
722
+ const makeHome = async (id = null) => {
723
+ const target = String(id || machine.id);
724
+ if (target === machine.id && isHome()) return becomeHome();
725
+ // A worker becoming Home asks through Home while it can, so the person's other computers come along confirmed.
726
+ if (target === machine.id) {
727
+ const pinned = homeListed()?.connected ? pinnedHome() : null;
728
+ const routed = pinned
729
+ ? await callOnce(pinned, {
730
+ command: HOME_COMMAND,
731
+ agent: "user",
732
+ target,
733
+ }).catch(() => null)
734
+ : null;
735
+ return routed?.ok === true ? routed : becomeHome();
736
+ }
737
+ const listed = siblings.find((sibling) => sibling.id === target);
738
+ if (!listed)
739
+ return { ok: false, error: "that is not one of your computers" };
740
+ if (!store.ownMachine(target))
741
+ return {
742
+ ok: false,
743
+ error: `${listed.label || "That computer"} has not joined your swarm yet`,
744
+ };
745
+ if (isHome()) return handHome(target, listed.label);
746
+ const pinned = pinnedHome();
747
+ if (!pinned) return homeListed() ? notJoined() : offline();
748
+ return (
749
+ (await callOnce(pinned, {
750
+ command: HOME_COMMAND,
751
+ agent: "user",
752
+ target,
753
+ })) ?? offline()
754
+ );
755
+ };
756
+
757
+ /**
758
+ * On home: Home goes to another of the person's computers. The others hear its key first (once it is Home this one can
759
+ * no longer send them notices), then it is given their keys and takes Home, so nobody has to be added again.
760
+ */
761
+ const handHome = async (target, label) => {
762
+ const pinned = store.ownMachine(target);
763
+ const others = store
764
+ .ownMachines()
765
+ .filter((other) => other.machine_id !== target);
766
+ for (const other of others)
767
+ await noticeTo(other.machine_id, {
768
+ homeNext: {
769
+ id: target,
770
+ publicKey: pinned.public_key,
771
+ label: pinned.label || label || "",
772
+ },
773
+ });
774
+ return (
775
+ (await askWorker(target, {
776
+ home: true,
777
+ computers: others.map((other) => ({
778
+ id: other.machine_id,
779
+ publicKey: other.public_key,
780
+ label: other.label,
781
+ })),
782
+ })) ?? {
783
+ ok: false,
784
+ error: `${label || "That computer"} did not answer; it may be asleep or offline`,
785
+ }
786
+ );
297
787
  };
298
788
 
299
789
  // ---- the join: the worker's code typed on home pins each computer's key on the other ----
300
790
 
301
- // Setup's code becomes this computer's join code, in place of any made before (pairing.mjs keepJoinCode).
791
+ // Setup's code becomes this computer's join code, in place of any made before (pairing.mjs keepJoinCode), for what is
792
+ // left of its time; a home drops it, since it waits to join nothing (M4).
302
793
  const adoptSetupCode = () => {
303
794
  if (!machine.joinCode) return;
304
795
  const code = normalizeJoinCode(machine.joinCode);
305
- if (code) store.meta("machine-join", JSON.stringify({ code, wrong: 0 }));
796
+ const made = Number(machine.joinCodeAt) || Date.now();
797
+ if (code && machine.role !== "home")
798
+ store.meta(
799
+ "machine-join",
800
+ JSON.stringify({ code, wrong: 0, until: made + JOIN_CODE_TTL_MS })
801
+ );
306
802
  machine.joinCode = null;
803
+ machine.joinCodeAt = null;
307
804
  saveMachine(machine);
308
805
  };
806
+ // The code this computer waits to join with, while it lasts; a code kept before codes expired is spent.
309
807
  const joinState = () => {
310
808
  adoptSetupCode();
311
809
  try {
312
- return JSON.parse(store.meta("machine-join") || "null");
810
+ const saved = JSON.parse(store.meta("machine-join") || "null");
811
+ return saved?.code && Date.now() < Number(saved.until) ? saved : null;
313
812
  } catch {
314
813
  return null;
315
814
  }
316
815
  };
317
816
  const joinCode = () => {
318
- if (isHome() || pinnedHome()) return null;
817
+ if (!waitingToJoin()) return null;
319
818
  const saved = joinState();
320
819
  if (saved?.code) return saved.code;
321
820
  const code = newJoinCode();
322
- store.meta("machine-join", JSON.stringify({ code, wrong: 0 }));
821
+ store.meta(
822
+ "machine-join",
823
+ JSON.stringify({ code, wrong: 0, until: Date.now() + JOIN_CODE_TTL_MS })
824
+ );
323
825
  return code;
324
826
  };
827
+ /** A worker that follows no home here: the only computer a join is for. Never home, never one already joined. */
828
+ const waitingToJoin = () => !isHome() && !pinnedHome();
325
829
  const confirmed = (sibling) => {
326
830
  const pinned = store.ownMachine(sibling.id);
327
831
  return Boolean(
@@ -339,24 +843,32 @@ export function createOwnMachines({
339
843
  "That is not a code from the computer you are adding. It looks like ABCD-EFGH-JKLM-NPQR.",
340
844
  });
341
845
 
342
- /** On home: the person typed a worker's join code. */
343
- const confirm = async (typed) => {
846
+ /**
847
+ * On home: the person typed a worker's join code. `hosted`: it is a computer the person does not drive from (a cloud
848
+ * computer, set up for agents only), so nothing it sends acts as the person (computerMay). A computer added by its
849
+ * code typed here is one the person drives from.
850
+ */
851
+ const confirm = async (typed, { hosted = false } = {}) => {
344
852
  if (!isHome()) return notHome();
345
853
  const code = normalizeJoinCode(typed);
346
854
  if (!code) return badCode();
347
- return tryCode(code, new Set());
855
+ return tryCode(code, new Set(), { hosted });
348
856
  };
349
857
 
350
858
  // Each waiting worker hears a code once: a wrong one counts against its tries (onJoin), so a code kept for a computer
351
- // not online yet must not be guessed at the others again and again.
352
- const tryCode = async (code, tried) => {
859
+ // not online yet must not be guessed at the others again and again. `only.machine` and `only.key` name the one computer
860
+ // the code is for (a cloud computer, added from the person's window), so the code is tried on no other; `only.hosted`
861
+ // marks it as one Harness runs, kept on its pin for what home lets it do (a computer Harness runs also says so itself).
862
+ const tryCode = async (code, tried, only = null) => {
353
863
  const waiting = siblings.filter(
354
864
  (sibling) =>
355
865
  sibling.role === "worker" &&
356
866
  sibling.connected &&
357
867
  sibling.publicKey &&
358
868
  !confirmed(sibling) &&
359
- !tried.has(sibling.id)
869
+ !tried.has(sibling.id) &&
870
+ (!only?.machine ||
871
+ (sibling.id === only.machine && sibling.publicKey === only.key))
360
872
  );
361
873
  const homeKey = identity().publicKey;
362
874
  for (const worker of waiting) {
@@ -370,12 +882,12 @@ export function createOwnMachines({
370
882
  const answer = await ask("machine_relay", {
371
883
  to: worker.id,
372
884
  kind: "join",
373
- body: { homeKey, proof: joinProof(code, "home", keys) },
885
+ body: { homeKey, proof: await joinProof(code, "home", keys) },
374
886
  }).catch((error) => ({ ok: false, error: error.message }));
375
887
  if (
376
888
  !answer?.ok ||
377
889
  typeof answer.proof !== "string" ||
378
- !sameProof(answer.proof, joinProof(code, "worker", keys))
890
+ !sameProof(answer.proof, await joinProof(code, "worker", keys))
379
891
  ) {
380
892
  log(
381
893
  `${worker.label || worker.id} did not join: ${answer?.ok ? "its proof did not match this computer's" : answer?.error}`
@@ -385,8 +897,17 @@ export function createOwnMachines({
385
897
  tried.delete(worker.id);
386
898
  continue;
387
899
  }
388
- store.pinOwnMachine(worker.id, worker.publicKey, worker.label);
389
- log(`confirmed ${worker.label || worker.id} as one of your computers`);
900
+ const hosted = only?.hosted === true || answer.hosted === true;
901
+ store.pinOwnMachine(worker.id, worker.publicKey, worker.label, {
902
+ hosted,
903
+ });
904
+ // It may bring the board it kept on its own here, once (boardMirror.mjs bring, answerCall).
905
+ store.meta(`bring-armed:${worker.id}`, "1");
906
+ log(
907
+ `confirmed ${worker.label || worker.id} as one of your computers${hosted ? " (run by Harness, for agents only)" : ""}`
908
+ );
909
+ // Its first calls may have come before the pin and been refused: it starts over now, sealed, as one of ours.
910
+ void noticeTo(worker.id, { welcome: true });
390
911
  changed();
391
912
  return {
392
913
  ok: true,
@@ -417,7 +938,7 @@ export function createOwnMachines({
417
938
  }
418
939
  entry.trying = true;
419
940
  try {
420
- const answer = await tryCode(entry.code, entry.tried);
941
+ const answer = await tryCode(entry.code, entry.tried, entry.only);
421
942
  if (answer.ok) {
422
943
  Object.assign(entry, {
423
944
  state: "joined",
@@ -436,12 +957,12 @@ export function createOwnMachines({
436
957
  * still waits for one), and home confirms it into the swarm as soon as it is online. A code Harness had nothing
437
958
  * waiting for is one already approved in a browser: it is tried now, on the computers waiting to join.
438
959
  */
439
- const add = async (typed) => {
960
+ const add = async (typed, only = null) => {
440
961
  const code = normalizeJoinCode(typed);
441
962
  if (!code) return badCode();
442
963
  let approved = null;
443
964
  if (isPairCode(code)) {
444
- const answer = await ask("machine_pair", pairClaim(code)).catch(
965
+ const answer = await ask("machine_pair", await pairClaim(code)).catch(
445
966
  (error) => ({ ok: false, error: error.message })
446
967
  );
447
968
  if (!answer?.ok)
@@ -458,7 +979,7 @@ export function createOwnMachines({
458
979
  }
459
980
  : notHome();
460
981
  if (approved === null) {
461
- const answer = await tryCode(code, new Set());
982
+ const answer = await tryCode(code, new Set(), only);
462
983
  return answer.ok ? { ...answer, state: "joined" } : answer;
463
984
  }
464
985
  const entry = {
@@ -468,6 +989,7 @@ export function createOwnMachines({
468
989
  machine: approved,
469
990
  until: Date.now() + ADD_WAIT_MS,
470
991
  tried: new Set(),
992
+ only,
471
993
  };
472
994
  adding.set(entry.id, entry);
473
995
  await tryAdding(entry);
@@ -494,10 +1016,10 @@ export function createOwnMachines({
494
1016
  for (const entry of adding.values()) void tryAdding(entry);
495
1017
  };
496
1018
 
497
- /** On a worker: home asks to join with the code the person typed there. */
498
- const onJoin = (body) => {
1019
+ /** On a worker waiting to join: home asks to join with the code the person typed there. */
1020
+ const onJoin = async (body) => {
499
1021
  const home = homeListed();
500
- const saved = joinState();
1022
+ const saved = waitingToJoin() ? joinState() : null;
501
1023
  if (!home || !saved?.code || typeof body?.homeKey !== "string")
502
1024
  return { ok: false, error: "this computer is not waiting to join" };
503
1025
  const keys = {
@@ -506,13 +1028,19 @@ export function createOwnMachines({
506
1028
  workerId: machine.id,
507
1029
  workerKey: identity().publicKey,
508
1030
  };
509
- if (!sameProof(String(body.proof), joinProof(saved.code, "home", keys))) {
1031
+ if (
1032
+ !sameProof(String(body.proof), await joinProof(saved.code, "home", keys))
1033
+ ) {
510
1034
  const wrong = Number(saved.wrong || 0) + 1;
511
1035
  store.meta(
512
1036
  "machine-join",
513
1037
  JSON.stringify(
514
1038
  wrong >= JOIN_TRIES
515
- ? { code: newJoinCode(), wrong: 0 }
1039
+ ? {
1040
+ code: newJoinCode(),
1041
+ wrong: 0,
1042
+ until: Date.now() + JOIN_CODE_TTL_MS,
1043
+ }
516
1044
  : { ...saved, wrong }
517
1045
  )
518
1046
  );
@@ -522,14 +1050,24 @@ export function createOwnMachines({
522
1050
  error: "that is not this computer's code",
523
1051
  };
524
1052
  }
1053
+ // A new home in place of one this computer trusted before: the old one is not trusted any more (M5).
1054
+ const before = acceptedHome();
1055
+ if (before && before !== home.id && before !== machine.id) forget(before);
525
1056
  store.pinOwnMachine(home.id, body.homeKey, home.label);
1057
+ store.meta("joined-home", home.id);
526
1058
  store.meta("machine-join", "null");
1059
+ accept(home.id);
527
1060
  log(
528
1061
  `joined your swarm: ${home.label || "your home computer"} holds the board`
529
1062
  );
530
1063
  changed();
531
1064
  void flush();
532
- return { ok: true, proof: joinProof(saved.code, "worker", keys) };
1065
+ // A computer Harness runs says so (cloudBoot.mjs), so home keeps it as hosted however its code was typed.
1066
+ return {
1067
+ ok: true,
1068
+ proof: await joinProof(saved.code, "worker", keys),
1069
+ ...(machine.hosted === true ? { hosted: true } : {}),
1070
+ };
533
1071
  };
534
1072
 
535
1073
  // ---- a worker's board calls, sealed to home ----
@@ -566,11 +1104,12 @@ export function createOwnMachines({
566
1104
  });
567
1105
  return { key, requestId, envelope };
568
1106
  };
569
- const deliver = async (key, requestId, envelope) => {
1107
+ // One call's answer and whether home sealed it; null when home could not be reached.
1108
+ const deliverSealed = async (key, requestId, envelope, to = "home") => {
570
1109
  let answer;
571
1110
  try {
572
1111
  answer = await relayTo({
573
- to: "home",
1112
+ to,
574
1113
  kind: "call",
575
1114
  body: { envelope },
576
1115
  });
@@ -580,26 +1119,41 @@ export function createOwnMachines({
580
1119
  if (!answer?.envelope) {
581
1120
  if (["offline", "timed_out"].includes(answer?.code)) return null;
582
1121
  return {
583
- ok: false,
584
- code: answer?.code,
585
- error: answer?.error || "home refused the call",
1122
+ sealed: false,
1123
+ result: {
1124
+ ok: false,
1125
+ code: answer?.code,
1126
+ error: answer?.error || "home refused the call",
1127
+ },
586
1128
  };
587
1129
  }
588
1130
  try {
589
- return await openAnswer(key, answer.envelope, {
590
- workerId: machine.id,
591
- requestId,
592
- });
1131
+ return {
1132
+ sealed: true,
1133
+ result: await openAnswer(key, answer.envelope, {
1134
+ workerId: machine.id,
1135
+ requestId,
1136
+ }),
1137
+ };
593
1138
  } catch {
594
1139
  return {
595
- ok: false,
596
- error:
597
- "the answer could not be opened: it did not come from your home computer",
1140
+ sealed: false,
1141
+ result: {
1142
+ ok: false,
1143
+ error:
1144
+ "the answer could not be opened: it did not come from your home computer",
1145
+ },
598
1146
  };
599
1147
  }
600
1148
  };
1149
+ const deliver = async (key, requestId, envelope, to) =>
1150
+ (await deliverSealed(key, requestId, envelope, to))?.result ?? null;
601
1151
 
602
- /** Writes kept while home was out of reach, in order; stops at the first that still cannot go. */
1152
+ /**
1153
+ * Writes kept while home was out of reach, in order; stops at the first that still cannot go. A write is let go only
1154
+ * when home answered it sealed, or said it already took it: anything else (Harness's word, an answer nobody sealed)
1155
+ * keeps it for the next try, so a refusal Harness makes up cannot throw the person's work away (S10).
1156
+ */
603
1157
  const flush = async () => {
604
1158
  const pinned = pinnedHome();
605
1159
  if (flushing || !pinned) return;
@@ -609,11 +1163,25 @@ export function createOwnMachines({
609
1163
  const [next, ...rest] = outbox();
610
1164
  if (!next) break;
611
1165
  const key = await keyFor(pinned.public_key, machine.id);
612
- const result = await deliver(key, next.requestId, next.envelope);
613
- if (result === null) break;
1166
+ const answered = await deliverSealed(
1167
+ key,
1168
+ next.requestId,
1169
+ next.envelope
1170
+ );
1171
+ const taken =
1172
+ answered !== null &&
1173
+ (answered.sealed || answered.result?.code === "replayed");
1174
+ if (!taken) {
1175
+ if (answered)
1176
+ log(
1177
+ `kept ${next.command} for your home computer: ${answered.result?.error || "no sealed answer"}`
1178
+ );
1179
+ break;
1180
+ }
1181
+ const result = answered.result;
614
1182
  keepOut(rest);
615
1183
  log(
616
- `sent ${next.command} to your home computer: ${result.ok === false && result.code !== "replayed" ? result.error : "taken"}`
1184
+ `sent ${next.command} to your home computer: ${result?.ok === false && result.code !== "replayed" ? result.error : "taken"}`
617
1185
  );
618
1186
  }
619
1187
  // Once a connection: home hears which repositories are here and in which folders, so work for one can come here.
@@ -778,8 +1346,31 @@ export function createOwnMachines({
778
1346
  };
779
1347
  };
780
1348
 
781
- /** Whether a board request made on this computer goes to home. */
782
- const forwards = (request) => !isHome() && goesHome(request.command);
1349
+ /**
1350
+ * Where this computer's copy of the board stands (boardMirror.mjs sync): "return" while another computer stands in as
1351
+ * home for this one (this one stayed home, and takes it back with the stand-in's changes), "home", "alone" (a worker
1352
+ * following no home here) or "follow".
1353
+ */
1354
+ const situation = () =>
1355
+ someoneStandsIn() && store.ownMachine(homeListed().id)
1356
+ ? "return"
1357
+ : isHome()
1358
+ ? "home"
1359
+ : actsAlone()
1360
+ ? "alone"
1361
+ : "follow";
1362
+ /** A call of the board copy's own (boardMirror.mjs): to the stand-in while one stands in for this computer, else home. */
1363
+ const mirrorCall = async (call) => {
1364
+ if (situation() === "return") {
1365
+ const standIn = store.ownMachine(homeListed().id);
1366
+ return (await callOnce(standIn, stripLocal(call))) ?? offline();
1367
+ }
1368
+ return isHome() ? null : callHome(call);
1369
+ };
1370
+
1371
+ /** Whether a board request made on this computer goes to home: not while it works on its own board. */
1372
+ const forwards = (request) =>
1373
+ !isHome() && trusted() && goesHome(request.command);
783
1374
 
784
1375
  // ---- on home: a worker's call, opened, answered on the board and sealed back ----
785
1376
 
@@ -797,7 +1388,7 @@ export function createOwnMachines({
797
1388
 
798
1389
  // The answers home gave lately, by the call they answer: the same sealed call arriving again (over the direct link,
799
1390
  // then through Harness when the link was slow) gets the same answer, or waits for the first, and never runs twice
800
- // (review, October 21: the second was refused as a replay and the agent told its write failed).
1391
+ // (the second was once refused as a replay and the agent told its write failed).
801
1392
  const answered = new Map();
802
1393
  const ANSWERS_KEPT = 500;
803
1394
  const once = (key, run) => {
@@ -833,36 +1424,105 @@ export function createOwnMachines({
833
1424
  firstSeen: (requestId) =>
834
1425
  store.firstPhoneRequest(`machine:${from}`, String(requestId)),
835
1426
  });
836
- if (!opened.ok) return opened;
1427
+ // A call that opened but is stale or already taken is answered sealed, so the worker can trust the refusal.
1428
+ if (!opened.ok)
1429
+ return opened.code === "unreadable"
1430
+ ? opened
1431
+ : {
1432
+ envelope: await sealAnswer(
1433
+ key,
1434
+ from,
1435
+ body.envelope.requestId,
1436
+ opened
1437
+ ),
1438
+ };
837
1439
  const call = opened.call ?? {};
838
1440
  const command = String(call.command || "");
839
- const result =
840
- command === DIRECT_COMMAND
841
- ? await swapDirectKeys(from, call.key)
842
- : command === MIRROR_COMMAND && answerMirror
843
- ? answerMirror(call)
844
- : command === MERGE_COMMAND && answerMerge
845
- ? store.meta("stood-in-by") === from
846
- ? answerMerge(call)
847
- : { ok: false, error: "this computer did not stand in for home" }
848
- : !goesHome(command)
849
- ? {
850
- ok: false,
851
- error: `${command || "that"} runs on the agent's own computer`,
852
- }
853
- : await settle(() =>
854
- boardCommand({
855
- ...stripLocal(call),
856
- // A path names a file on the worker; its bytes come as data.
857
- path: undefined,
858
- command,
859
- [FROM_MACHINE]: from,
860
- })
861
- );
1441
+ const result = await answerOpened(from, pinned, call, command);
862
1442
  return {
863
1443
  envelope: await sealAnswer(key, from, body.envelope.requestId, result),
864
1444
  };
865
1445
  };
1446
+ // What home does with a call it opened from another of the person's computers: the computers' own exchanges, else the
1447
+ // board, as far as that computer may ask (computerMay).
1448
+ const answerOpened = async (from, pinned, call, command) => {
1449
+ if (command === DIRECT_COMMAND) return swapDirectKeys(from, call.key);
1450
+ // Answered for the computer that sealed it, and only for a link allowed for that computer.
1451
+ if (command === LINK_COMMAND)
1452
+ return answerLink
1453
+ ? answerLink(from, call.link)
1454
+ : { ok: false, error: "this computer holds no proxy link" };
1455
+ if (command === MODELS_COMMAND || command === MODEL_COMMAND)
1456
+ return answerModelsCall(call, from, !pinned.hosted);
1457
+ if (command === SSH_COMMAND)
1458
+ return answerSshCall(call, from, !pinned.hosted);
1459
+ // Only the person, from a computer they drive, moves Home (a hosted computer is Harness's to run).
1460
+ if (command === HOME_COMMAND)
1461
+ return call.agent === "user" && !pinned.hosted
1462
+ ? makeHome(call.target)
1463
+ : { ok: false, error: "only the person moves Home" };
1464
+ if (command === MIRROR_COMMAND && answerMirror) return answerMirror(call);
1465
+ if (command === MERGE_COMMAND && answerMerge)
1466
+ return answerMergeCall(from, call);
1467
+ if (command === DEVICES_COMMAND && answerDevices)
1468
+ return answerDevices(from, call, { drives: !pinned.hosted });
1469
+ if (!goesHome(command))
1470
+ return {
1471
+ ok: false,
1472
+ error: `${command || "that"} runs on the agent's own computer`,
1473
+ };
1474
+ const refused = computerMay({
1475
+ command,
1476
+ agent: call.agent,
1477
+ drives: !pinned.hosted,
1478
+ });
1479
+ if (refused) return { ok: false, code: "not_allowed", error: refused };
1480
+ return settle(() =>
1481
+ boardCommand({
1482
+ ...stripLocal(call),
1483
+ // A path names a file on the worker; its bytes come as data.
1484
+ path: undefined,
1485
+ command,
1486
+ [FROM_MACHINE]: from,
1487
+ })
1488
+ );
1489
+ };
1490
+ /**
1491
+ * A board merged in from another computer (M2). A worker brings the board it kept on its own once, when home has just
1492
+ * confirmed it (armed in tryCode) or made it home in its place (makeHome); the computer that stood in for home hands
1493
+ * back what it wrote, once home heard from it, sealed, that it stood in. Either ends with its last page. What a merge
1494
+ * writes never carries the person's Start or trust, and never starts a run (boardMirror.mjs merge).
1495
+ */
1496
+ const answerMergeCall = (from, call) => {
1497
+ const bring = call.bring === true;
1498
+ const allowed = bring
1499
+ ? store.meta(`bring-armed:${from}`) === "1"
1500
+ : store.meta("stood-in-by") === from;
1501
+ if (!allowed)
1502
+ return bring
1503
+ ? {
1504
+ ok: false,
1505
+ code: "not_armed",
1506
+ error:
1507
+ "home takes a computer's own board only once, as it joins; this one already came or was never asked for",
1508
+ }
1509
+ : {
1510
+ ok: false,
1511
+ code: "not_stand_in",
1512
+ error: "this computer did not stand in for home",
1513
+ };
1514
+ const page = call.page ?? {};
1515
+ const answer = answerMerge(page, { bring });
1516
+ if (answer?.ok && Number(page.to) >= Number(page.head)) {
1517
+ store.meta(bring ? `bring-armed:${from}` : "stood-in-by", "");
1518
+ log(
1519
+ bring
1520
+ ? `took ${labelOf(from) ?? from}'s own board`
1521
+ : `took back what ${labelOf(from) ?? from} wrote while it stood in`
1522
+ );
1523
+ }
1524
+ return answer;
1525
+ };
866
1526
 
867
1527
  /** On home: a worker's key for a direct link, taken, and home's own given back. */
868
1528
  const swapDirectKeys = async (workerId, workerKey) => {
@@ -893,26 +1553,91 @@ export function createOwnMachines({
893
1553
  to: workerId,
894
1554
  kind: "notice",
895
1555
  body: { envelope },
896
- }).catch(() => ({ ok: false }));
1556
+ }).catch(() => null);
897
1557
  };
898
1558
 
1559
+ // A notice is sealed by the computer that sent it as home: the home this computer follows, or another it confirmed (one
1560
+ // that moved home to itself, or stands in), tried in turn. Harness's word on who sent it counts for nothing.
1561
+ const openNoticeFromAny = async (body) => {
1562
+ const listed = homeListed()?.id;
1563
+ const candidates = store
1564
+ .ownMachines()
1565
+ .sort(
1566
+ (a, b) =>
1567
+ Number(b.machine_id === listed) - Number(a.machine_id === listed)
1568
+ );
1569
+ for (const pinned of candidates) {
1570
+ const key = await keyFor(pinned.public_key, machine.id);
1571
+ const notice = await openNotice(key, body?.envelope, {
1572
+ workerId: machine.id,
1573
+ firstSeen: (requestId) =>
1574
+ store.firstPhoneRequest(
1575
+ `machine:${pinned.machine_id}`,
1576
+ String(requestId)
1577
+ ),
1578
+ });
1579
+ if (notice) return { from: pinned.machine_id, notice };
1580
+ }
1581
+ return null;
1582
+ };
899
1583
  const onNoticeFromHome = async (body) => {
900
- const pinned = pinnedHome();
901
- if (!pinned) return { ok: false };
902
- const key = await keyFor(pinned.public_key, machine.id);
903
- const notice = await openNotice(key, body?.envelope, {
904
- workerId: machine.id,
905
- firstSeen: (requestId) =>
906
- store.firstPhoneRequest(
907
- `machine:${pinned.machine_id}`,
908
- String(requestId)
909
- ),
910
- });
911
- if (!notice) return { ok: false };
1584
+ const opened = await openNoticeFromAny(body);
1585
+ if (!opened) return { ok: false };
1586
+ const { from, notice } = opened;
1587
+ if (notice.role) {
1588
+ onRoleStatement(from, notice.role);
1589
+ return { ok: true };
1590
+ }
1591
+ // Everything else is the word of the home this computer follows; another's is heard and set aside.
1592
+ if (from !== acceptedHome()) return { ok: true };
1593
+ if (typeof notice.removed === "string") {
1594
+ removedByHome(notice.removed);
1595
+ return { ok: true };
1596
+ }
1597
+ // Home is about to go to another of the person's computers: its key, from the Home this one follows, is pinned now,
1598
+ // so its sealed word that it is Home (onRoleStatement) opens here when it comes.
1599
+ const next = notice.homeNext;
1600
+ if (
1601
+ typeof next?.id === "string" &&
1602
+ next.id !== machine.id &&
1603
+ typeof next.publicKey === "string"
1604
+ ) {
1605
+ store.pinOwnMachine(next.id, next.publicKey, String(next.label || ""));
1606
+ return { ok: true };
1607
+ }
1608
+ // Home confirmed this computer: what it keeps for home, and the board it brings, go now.
1609
+ if (notice.welcome === true) void flush();
912
1610
  onNotice(notice);
913
1611
  return { ok: true };
914
1612
  };
915
1613
 
1614
+ /**
1615
+ * Another computer confirmed here says, sealed, that it is home now (the person moved home there, or it took its place
1616
+ * back from a stand-in), or that it stands in for this one. Only about itself, and only newer than this computer's
1617
+ * own last move. This is how a computer stops being home or follows a new home (S9); Harness's list alone never does.
1618
+ */
1619
+ const onRoleStatement = (from, statement) => {
1620
+ if (statement?.home !== from) return;
1621
+ // A stand-in's statement moves nothing here, so it counts however late Harness delivers it (this computer may have
1622
+ // taken home back by then): it lets that computer hand back what it wrote meanwhile (answerMergeCall), once.
1623
+ if (statement.standInFor) {
1624
+ if (statement.standInFor !== machine.id) return;
1625
+ store.meta("stood-in-by", from);
1626
+ log(
1627
+ `${labelOf(from) ?? from} stands in as home while this computer is unreachable`
1628
+ );
1629
+ changed();
1630
+ returning();
1631
+ return;
1632
+ }
1633
+ if (!(Number(statement.at) > Number(store.meta(ROLE_AT) || 0))) return;
1634
+ if (isHome()) setRole("worker", from);
1635
+ else accept(from);
1636
+ log(`${labelOf(from) ?? from} is home now, as it said itself`);
1637
+ changed();
1638
+ void flush();
1639
+ };
1640
+
916
1641
  /**
917
1642
  * On home: each confirmed worker it can reach hears its copy of the board is behind (boardMirror.mjs): through
918
1643
  * Harness when Harness has it connected, or over the direct link when only that is up.
@@ -949,21 +1674,7 @@ export function createOwnMachines({
949
1674
  for (const worker of siblings.filter(
950
1675
  (sibling) => sibling.role === "worker" && sibling.connected
951
1676
  )) {
952
- const pinned = store.ownMachine(worker.id);
953
- if (!pinned) continue;
954
- const key = await keyFor(pinned.public_key, worker.id);
955
- const requestId = newRequestId();
956
- const envelope = await sealAsk(key, worker.id, requestId, call);
957
- const reply = await relayTo({
958
- to: worker.id,
959
- kind: "ask",
960
- body: { envelope },
961
- }).catch(() => null);
962
- if (!reply?.envelope) continue;
963
- const answer = await openAskAnswer(key, reply.envelope, {
964
- workerId: worker.id,
965
- requestId,
966
- }).catch(() => null);
1677
+ const answer = await askWorker(worker.id, call);
967
1678
  if (!answer) continue;
968
1679
  if (!nobodyThere(answer)) return answer;
969
1680
  found ??= answer;
@@ -971,6 +1682,82 @@ export function createOwnMachines({
971
1682
  return found;
972
1683
  };
973
1684
 
1685
+ /** On home: one sealed question for a confirmed worker and its opened answer; null when none came back. */
1686
+ const askWorker = async (workerId, call) => {
1687
+ const pinned = store.ownMachine(workerId);
1688
+ if (!pinned) return null;
1689
+ const key = await keyFor(pinned.public_key, workerId);
1690
+ const requestId = newRequestId();
1691
+ const envelope = await sealAsk(key, workerId, requestId, call);
1692
+ const reply = await relayTo({
1693
+ to: workerId,
1694
+ kind: "ask",
1695
+ body: { envelope },
1696
+ }).catch(() => null);
1697
+ if (!reply?.envelope) return null;
1698
+ return openAskAnswer(key, reply.envelope, { workerId, requestId }).catch(
1699
+ () => null
1700
+ );
1701
+ };
1702
+
1703
+ /**
1704
+ * On a cloud computer: one call through a proxy link to the computer that holds it, which is home, or (from home) a
1705
+ * worker it confirmed: the pair's key is the only one either holds. The opened answer, or { unreachable, error }
1706
+ * when none came back: "timed_out" when the line's own deadline passed (linkRelay.mjs asks again), anything else
1707
+ * when that computer cannot be reached.
1708
+ */
1709
+ const linkCall = async (holderId, link) => {
1710
+ const home = pinnedHome();
1711
+ const toHome = Boolean(home) && home.machine_id === holderId;
1712
+ const pinned = toHome
1713
+ ? home
1714
+ : isHome()
1715
+ ? store.ownMachine(String(holderId))
1716
+ : null;
1717
+ if (!pinned)
1718
+ return {
1719
+ unreachable: "unconfirmed",
1720
+ error: toHome
1721
+ ? "your home computer has not confirmed this one"
1722
+ : "the computer holding the link is neither this computer's home nor a computer it confirmed",
1723
+ };
1724
+ const workerId = toHome ? machine.id : pinned.machine_id;
1725
+ const key = await keyFor(pinned.public_key, workerId);
1726
+ const requestId = newRequestId();
1727
+ const envelope = toHome
1728
+ ? await sealCall(key, machine.id, requestId, {
1729
+ command: LINK_COMMAND,
1730
+ agent: "user",
1731
+ link,
1732
+ })
1733
+ : await sealAsk(key, workerId, requestId, { link });
1734
+ let reply;
1735
+ try {
1736
+ reply = await relayTo({
1737
+ to: toHome ? "home" : workerId,
1738
+ kind: toHome ? "call" : "ask",
1739
+ body: { envelope },
1740
+ });
1741
+ } catch (error) {
1742
+ return { unreachable: "offline", error: error.message };
1743
+ }
1744
+ if (!reply?.envelope)
1745
+ return {
1746
+ unreachable: reply?.code || "timed_out",
1747
+ error: reply?.error || "no answer came back",
1748
+ };
1749
+ try {
1750
+ return toHome
1751
+ ? await openAnswer(key, reply.envelope, { workerId, requestId })
1752
+ : await openAskAnswer(key, reply.envelope, { workerId, requestId });
1753
+ } catch {
1754
+ return {
1755
+ unreachable: "unsealed",
1756
+ error: "the answer did not come from the computer holding the link",
1757
+ };
1758
+ }
1759
+ };
1760
+
974
1761
  /** On a worker: home's question for the windows linked here, opened, asked and the answer sealed back. */
975
1762
  const onAskFromHome = (body) =>
976
1763
  once(`ask:${sealedKey(body?.envelope)}`, () => onAskFromHomeOnce(body));
@@ -987,7 +1774,24 @@ export function createOwnMachines({
987
1774
  ),
988
1775
  });
989
1776
  if (!call) return { ok: false, error: "the question could not be opened" };
990
- const answer = await askOwnWindows(call);
1777
+ // Home asking for this computer's agents' models is answered here, and Home handing itself here (handHome) is taken;
1778
+ // a question for the windows only from the few they answer for home (M6).
1779
+ // A cloud home's call through a proxy link this computer holds is answered for that home alone (proxyLinks.mjs).
1780
+ const answer =
1781
+ call.home === true
1782
+ ? await becomeHome(call.computers)
1783
+ : call.link && answerLink
1784
+ ? await answerLink(pinned.machine_id, call.link)
1785
+ : call.models
1786
+ ? await ownModels(call.models)
1787
+ : call.ssh
1788
+ ? ownSshAllow(call.ssh)
1789
+ : WINDOW_TOOLS.has(call.tool)
1790
+ ? await askOwnWindows(call)
1791
+ : {
1792
+ ok: false,
1793
+ error: `home cannot ask this computer's windows for ${call.tool}`,
1794
+ };
991
1795
  return {
992
1796
  envelope: await sealAskAnswer(
993
1797
  key,
@@ -1035,6 +1839,7 @@ export function createOwnMachines({
1035
1839
  id: machine.id,
1036
1840
  label: machine.label,
1037
1841
  role: machine.role ?? "home",
1842
+ alone: actsAlone(),
1038
1843
  standingInFor: standingIn()
1039
1844
  ? (labelOf(standingIn()) ?? standingIn())
1040
1845
  : null,
@@ -1052,6 +1857,8 @@ export function createOwnMachines({
1052
1857
  connected: sibling.connected,
1053
1858
  agents: sibling.agents,
1054
1859
  confirmed: confirmed(sibling),
1860
+ // Harness runs it (a cloud computer): what home lets it do is an agents' computer's, never the person's.
1861
+ hosted: store.ownMachine(sibling.id)?.hosted === true,
1055
1862
  standsInForThis: sibling.standInFor === machine.id,
1056
1863
  direct:
1057
1864
  directLink?.status().find((link) => link.id === sibling.id)
@@ -1064,6 +1871,250 @@ export function createOwnMachines({
1064
1871
  };
1065
1872
  };
1066
1873
 
1874
+ // ---- every computer's agents and the models they run, for the buddy's Swarm tab ----
1875
+
1876
+ const modelsRead = (refresh) => ({
1877
+ command: "board.swarm.models",
1878
+ ...(refresh === true ? { refresh: true } : {}),
1879
+ });
1880
+
1881
+ /** One computer as the Swarm tab shows it: its agents' models as it answered, else the agents Harness last listed. */
1882
+ const computerEntry = (computer, answer) => ({
1883
+ id: computer.id,
1884
+ label: computer.label,
1885
+ role: computer.role ?? "home",
1886
+ online: computer.online,
1887
+ models: answer?.ok ? (answer.agents ?? []) : [],
1888
+ agents: answer?.ok ? (answer.installed ?? []) : (computer.agents ?? []),
1889
+ ...(answer?.ok === false ? { error: answer.error } : {}),
1890
+ });
1891
+
1892
+ /** On home: the agents that run themselves, by the computer they last called the board from (home's records). */
1893
+ const selfRunByComputer = () => {
1894
+ const since = new Date(Date.now() - SELF_RUN_SEEN_MS).toISOString();
1895
+ const found = {};
1896
+ for (const { agent, machine: computer } of store.agentsSeenOnComputers(
1897
+ since
1898
+ )) {
1899
+ if (member(agent)?.runs !== "self") continue;
1900
+ (found[computer] ??= []).push(agent);
1901
+ }
1902
+ return found;
1903
+ };
1904
+ const withSelfRun = (computers, selfRun) =>
1905
+ computers.map((computer) => ({
1906
+ ...computer,
1907
+ selfRun: selfRun[computer.id] ?? [],
1908
+ }));
1909
+
1910
+ /** On home: home and each confirmed worker but `except` (the worker asking), each read on its own computer. */
1911
+ const everyComputersModels = async (read, except = null) => {
1912
+ const workers = siblings.filter(
1913
+ (sibling) => sibling.id !== except && confirmed(sibling)
1914
+ );
1915
+ const [own, ...answers] = await Promise.all([
1916
+ ownModels(read),
1917
+ ...workers.map((worker) =>
1918
+ worker.connected
1919
+ ? askWorker(worker.id, { models: read }).then(
1920
+ (answer) =>
1921
+ answer ?? { ok: false, error: `${worker.label} did not answer` }
1922
+ )
1923
+ : null
1924
+ ),
1925
+ ]);
1926
+ return [
1927
+ computerEntry(
1928
+ {
1929
+ id: machine.id,
1930
+ label: machine.label,
1931
+ role: machine.role ?? "home",
1932
+ online: true,
1933
+ agents,
1934
+ },
1935
+ own
1936
+ ),
1937
+ ...workers.map((worker, index) =>
1938
+ computerEntry({ ...worker, online: worker.connected }, answers[index])
1939
+ ),
1940
+ ];
1941
+ };
1942
+
1943
+ // Why the other computers' agents are missing: this one is not joined yet and works on its own, or home is away.
1944
+ const unreachableNote = (answer) =>
1945
+ actsAlone()
1946
+ ? "This computer isn't joined to your home computer yet, so only its own agents show here."
1947
+ : (answer ?? offline()).error;
1948
+
1949
+ /** The person's computers, this one first, each with its agents and the model and effort each runs on. */
1950
+ const models = async ({ refresh = false } = {}) => {
1951
+ const read = modelsRead(refresh);
1952
+ if (isHome())
1953
+ return {
1954
+ ok: true,
1955
+ here: machine.id,
1956
+ computers: withSelfRun(
1957
+ await everyComputersModels(read),
1958
+ selfRunByComputer()
1959
+ ),
1960
+ };
1961
+ const own = computerEntry(
1962
+ {
1963
+ id: machine.id,
1964
+ label: machine.label,
1965
+ role: "worker",
1966
+ online: true,
1967
+ agents,
1968
+ },
1969
+ await ownModels(read)
1970
+ );
1971
+ const pinned = pinnedHome();
1972
+ const fromHome = pinned
1973
+ ? await callOnce(pinned, {
1974
+ command: MODELS_COMMAND,
1975
+ agent: "user",
1976
+ refresh: refresh === true,
1977
+ })
1978
+ : null;
1979
+ const others = fromHome?.ok
1980
+ ? fromHome.computers.filter((computer) => computer.id !== machine.id)
1981
+ : siblings.map((sibling) =>
1982
+ computerEntry({ ...sibling, online: false }, null)
1983
+ );
1984
+ return {
1985
+ ok: true,
1986
+ here: machine.id,
1987
+ computers: withSelfRun([own, ...others], fromHome?.selfRun ?? {}),
1988
+ ...(fromHome?.ok ? {} : { note: unreachableNote(fromHome) }),
1989
+ };
1990
+ };
1991
+
1992
+ /** On home: a worker asking for every computer's models, or setting one; only as the person, setting where they drive. */
1993
+ const answerModelsCall = async (call, from, drives) => {
1994
+ if (call.agent !== "user")
1995
+ return { ok: false, error: "only the person reads or sets models here" };
1996
+ if (call.command === MODEL_COMMAND)
1997
+ return drives
1998
+ ? setModel(call)
1999
+ : {
2000
+ ok: false,
2001
+ error:
2002
+ "That computer runs agents only, so nothing it sends acts as you.",
2003
+ };
2004
+ return {
2005
+ ok: true,
2006
+ computers: await everyComputersModels(modelsRead(call.refresh), from),
2007
+ selfRun: selfRunByComputer(),
2008
+ };
2009
+ };
2010
+
2011
+ /** The person's model and effort for one agent on one computer, set on that computer. */
2012
+ const setModel = async (request) => {
2013
+ const pick = {
2014
+ command: "board.swarm.model",
2015
+ target: request.target,
2016
+ model: request.model,
2017
+ effort: request.effort ?? null,
2018
+ };
2019
+ const computer = String(request.computer || machine.id);
2020
+ if (computer === machine.id) return ownModels(pick);
2021
+ if (isHome()) {
2022
+ const worker = siblings.find((sibling) => sibling.id === computer);
2023
+ if (!worker || !confirmed(worker))
2024
+ return {
2025
+ ok: false,
2026
+ error: "that computer is not one of yours confirmed on home",
2027
+ };
2028
+ return (
2029
+ (await askWorker(computer, { models: pick })) ?? {
2030
+ ok: false,
2031
+ error: `${worker.label} did not answer; it may be asleep or offline`,
2032
+ }
2033
+ );
2034
+ }
2035
+ const pinned = pinnedHome();
2036
+ if (!pinned) return homeListed() ? notJoined() : offline();
2037
+ return (
2038
+ (await callOnce(pinned, {
2039
+ command: MODEL_COMMAND,
2040
+ agent: "user",
2041
+ computer,
2042
+ target: pick.target,
2043
+ model: pick.model,
2044
+ effort: pick.effort,
2045
+ })) ?? offline()
2046
+ );
2047
+ };
2048
+
2049
+ // ---- the person's SSH key into a cloud computer (cloudSsh.mjs) ----
2050
+
2051
+ const ownSshAllow = (ssh) =>
2052
+ ownSsh
2053
+ ? ownSsh({ key: String(ssh?.key ?? ""), by: String(ssh?.by ?? "") })
2054
+ : { ok: false, error: "This computer takes no SSH keys." };
2055
+
2056
+ /** On home: the key into a cloud computer that is one of the person's, confirmed here and run by Harness. */
2057
+ const sshOnWorker = async (computer, ssh) => {
2058
+ const worker = siblings.find((sibling) => sibling.id === computer);
2059
+ if (!worker || !confirmed(worker))
2060
+ return {
2061
+ ok: false,
2062
+ error: "that computer is not one of yours confirmed on home",
2063
+ };
2064
+ if (store.ownMachine(computer)?.hosted !== true)
2065
+ return {
2066
+ ok: false,
2067
+ error: "Only a cloud computer takes an SSH key this way.",
2068
+ };
2069
+ return (
2070
+ (await askWorker(computer, { ssh })) ?? {
2071
+ ok: false,
2072
+ error: `${worker.label} did not answer; it may still be waking up`,
2073
+ }
2074
+ );
2075
+ };
2076
+
2077
+ /** On home: a computer the person drives asks to let their key into one of their cloud computers. */
2078
+ const answerSshCall = (call, from, drives) => {
2079
+ if (call.agent !== "user" || !drives)
2080
+ return {
2081
+ ok: false,
2082
+ error:
2083
+ "That computer runs agents only, so nothing it sends acts as you.",
2084
+ };
2085
+ const ssh = { key: String(call.key ?? ""), by: labelOf(from) ?? "" };
2086
+ const computer = String(call.computer || "");
2087
+ return computer === machine.id
2088
+ ? ownSshAllow(ssh)
2089
+ : sshOnWorker(computer, ssh);
2090
+ };
2091
+
2092
+ /**
2093
+ * The person, at this computer, lets their SSH key into one of their cloud computers: told to it over the sealed line
2094
+ * between their computers, through home. A computer Harness runs cannot do this for them.
2095
+ */
2096
+ const allowSsh = async ({ computer, key }) => {
2097
+ if (machine.hosted === true)
2098
+ return {
2099
+ ok: false,
2100
+ error:
2101
+ "This computer runs agents only, so it cannot let a key in for you. Run tryharness ssh on your own computer.",
2102
+ };
2103
+ const ssh = { key: String(key ?? ""), by: machine.label ?? "" };
2104
+ if (computer === machine.id) return ownSshAllow(ssh);
2105
+ if (isHome()) return sshOnWorker(String(computer || ""), ssh);
2106
+ const pinned = pinnedHome();
2107
+ if (!pinned) return homeListed() ? notJoined() : offline();
2108
+ return (
2109
+ (await callOnce(pinned, {
2110
+ command: SSH_COMMAND,
2111
+ agent: "user",
2112
+ computer,
2113
+ key: ssh.key,
2114
+ })) ?? offline()
2115
+ );
2116
+ };
2117
+
1067
2118
  const status = () => ({
1068
2119
  id: machine.id,
1069
2120
  label: machine.label,
@@ -1082,7 +2133,23 @@ export function createOwnMachines({
1082
2133
  }
1083
2134
  : null,
1084
2135
  waiting: outbox().length,
2136
+ // Working on its own board until the person types this code on home.
2137
+ ...(actsAlone() && joinCode() ? { joinCode: joinCode() } : {}),
1085
2138
  }),
2139
+ // On home: the computers connected and waiting for their code to be typed here.
2140
+ ...(isHome()
2141
+ ? {
2142
+ waitingToJoin: siblings
2143
+ .filter(
2144
+ (sibling) =>
2145
+ sibling.role === "worker" &&
2146
+ sibling.connected &&
2147
+ sibling.publicKey &&
2148
+ !confirmed(sibling)
2149
+ )
2150
+ .map((sibling) => sibling.label),
2151
+ }
2152
+ : {}),
1086
2153
  });
1087
2154
 
1088
2155
  /** The person's computers that have this agent, this one first: what its card says. Only confirmed ones. */
@@ -1184,12 +2251,21 @@ export function createOwnMachines({
1184
2251
  };
1185
2252
  };
1186
2253
 
2254
+ if (machine.role === "home" && machine.joinCode) {
2255
+ machine.joinCode = null;
2256
+ machine.joinCodeAt = null;
2257
+ saveMachine(machine);
2258
+ }
2259
+
1187
2260
  return {
1188
2261
  hello,
1189
2262
  adopt,
1190
2263
  introduce,
1191
2264
  rename,
1192
2265
  makeHome,
2266
+ leave,
2267
+ remove,
2268
+ removed,
1193
2269
  confirm,
1194
2270
  add,
1195
2271
  forwards,
@@ -1197,12 +2273,16 @@ export function createOwnMachines({
1197
2273
  relay,
1198
2274
  noticeTo,
1199
2275
  askWorkerWindows,
2276
+ linkCall,
1200
2277
  tellWorkers,
1201
2278
  fromLink,
1202
2279
  standingIn,
1203
2280
  someoneStandsIn,
2281
+ situation,
2282
+ mirrorCall,
1204
2283
  // A worker confirmed into the swarm: it holds home's key.
1205
2284
  joined: () => Boolean(pinnedHome()),
2285
+ actsAlone,
1206
2286
  standInReachable: () => {
1207
2287
  const home = homeListed();
1208
2288
  return Boolean(
@@ -1216,6 +2296,9 @@ export function createOwnMachines({
1216
2296
  reclaim,
1217
2297
  directStatus: () => directLink?.status() ?? [],
1218
2298
  list,
2299
+ models,
2300
+ setModel,
2301
+ allowSsh,
1219
2302
  status,
1220
2303
  all,
1221
2304
  learn,