tryharness 0.7.45 → 0.7.53

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 (99) hide show
  1. package/README.md +232 -12
  2. package/cli.mjs +406 -184
  3. package/lib/actorRoster.mjs +28 -5
  4. package/lib/adapters.mjs +9 -1
  5. package/lib/agentRuntimeConfig.mjs +36 -0
  6. package/lib/agentRuntimes.mjs +560 -0
  7. package/lib/atlas.mjs +7 -2
  8. package/lib/boardCommands.mjs +5 -10
  9. package/lib/boardFileCommands.mjs +2 -1
  10. package/lib/boardMirror.mjs +459 -0
  11. package/lib/boardProtocol.json +206 -6
  12. package/lib/boardTools.mjs +2 -6
  13. package/lib/bridge.mjs +25 -3
  14. package/lib/browserWake.mjs +60 -0
  15. package/lib/cards.mjs +35 -2
  16. package/lib/commands.mjs +20 -5
  17. package/lib/connectionTools.d.ts +13 -0
  18. package/lib/connectionTools.js +45 -0
  19. package/lib/connectorAuth.mjs +309 -0
  20. package/lib/connectorCatalog.json +41 -0
  21. package/lib/connectorCommands.mjs +121 -0
  22. package/lib/connectorGoogle.mjs +513 -0
  23. package/lib/connectors.mjs +805 -0
  24. package/lib/coordinator.mjs +8 -1
  25. package/lib/coreModels.mjs +78 -0
  26. package/lib/daemon.mjs +643 -45
  27. package/lib/desktop.mjs +7 -2
  28. package/lib/digest.mjs +32 -0
  29. package/lib/directLink.mjs +283 -0
  30. package/lib/environments.mjs +595 -0
  31. package/lib/folders.mjs +2 -2
  32. package/lib/goalCommands.mjs +58 -14
  33. package/lib/inference.mjs +263 -152
  34. package/lib/lessons.mjs +6 -0
  35. package/lib/lineup.mjs +324 -0
  36. package/lib/localmodels.mjs +10 -0
  37. package/lib/machineIdentity.mjs +3 -0
  38. package/lib/machineRoutes.mjs +40 -2
  39. package/lib/machineRuns.mjs +30 -3
  40. package/lib/machineSeal.mjs +69 -10
  41. package/lib/mcp-stdio.mjs +121 -118
  42. package/lib/mcpRelay.mjs +119 -0
  43. package/lib/members.json +12 -0
  44. package/lib/members.mjs +33 -0
  45. package/lib/modelMemory.mjs +100 -0
  46. package/lib/modelTiers.json +1183 -0
  47. package/lib/modelTiers.mjs +133 -0
  48. package/lib/models.mjs +41 -8
  49. package/lib/museSession.mjs +119 -0
  50. package/lib/nativeHost.mjs +203 -0
  51. package/lib/network.mjs +7 -2
  52. package/lib/nudge.mjs +10 -2
  53. package/lib/onboard.mjs +430 -1
  54. package/lib/oneclawLocal.mjs +150 -0
  55. package/lib/ownMachines.mjs +521 -36
  56. package/lib/pairing.mjs +165 -0
  57. package/lib/paths.mjs +4 -0
  58. package/lib/phones.mjs +61 -0
  59. package/lib/placeCommands.mjs +27 -0
  60. package/lib/places.mjs +10 -2
  61. package/lib/plans.mjs +151 -27
  62. package/lib/profile.mjs +152 -0
  63. package/lib/projects.mjs +624 -137
  64. package/lib/readiness.mjs +283 -0
  65. package/lib/repoLinks.mjs +354 -0
  66. package/lib/roomChannels.mjs +641 -0
  67. package/lib/runBrief.mjs +32 -2
  68. package/lib/runRequests.mjs +157 -0
  69. package/lib/runWorker.mjs +20 -7
  70. package/lib/runner.mjs +67 -8
  71. package/lib/secretPatterns.json +55 -0
  72. package/lib/secrets.mjs +10 -27
  73. package/lib/seen.mjs +102 -0
  74. package/lib/service.mjs +11 -6
  75. package/lib/sessionControl.mjs +10 -8
  76. package/lib/sessionIndex.mjs +5 -3
  77. package/lib/store.mjs +546 -29
  78. package/lib/subagents.mjs +8 -4
  79. package/lib/swarm.mjs +367 -37
  80. package/lib/swarmMemory.mjs +947 -0
  81. package/lib/t3.mjs +43 -13
  82. package/lib/taskCommands.mjs +56 -5
  83. package/lib/taskRuns.mjs +61 -11
  84. package/lib/team.json +17 -15
  85. package/lib/team.mjs +68 -18
  86. package/lib/threadRuns.mjs +3 -1
  87. package/lib/threadView.mjs +51 -14
  88. package/lib/tokenizer.mjs +405 -0
  89. package/lib/ui.mjs +16 -2
  90. package/lib/usageTotals.mjs +148 -0
  91. package/lib/vault.mjs +1144 -0
  92. package/lib/vaultCloud.mjs +117 -0
  93. package/lib/vaultCommands.mjs +201 -0
  94. package/lib/vaultTools.d.ts +12 -0
  95. package/lib/vaultTools.js +42 -0
  96. package/lib/windowAsks.mjs +42 -0
  97. package/lib/workFocus.mjs +59 -0
  98. package/lib/workLinks.mjs +90 -0
  99. package/package.json +9 -4
@@ -1,10 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { randomBytes } from "node:crypto";
3
+ import { randomBytes, randomUUID } from "node:crypto";
4
4
  import { documentText, ensureDir, isDocument, mimeFor } from "./files.mjs";
5
5
  import { FILE_PART_BYTES } from "./boardFiles.mjs";
6
6
  import { fingerprint } from "./sealed.mjs";
7
7
  import {
8
+ isPairCode,
8
9
  joinProof,
9
10
  newJoinCode,
10
11
  newRequestId,
@@ -12,13 +13,22 @@ import {
12
13
  openAnswer,
13
14
  openCall,
14
15
  openNotice,
16
+ pairClaim,
15
17
  pairKey,
16
18
  sameProof,
17
19
  sealAnswer,
18
20
  sealCall,
19
21
  sealNotice,
22
+ sealAsk,
23
+ openAsk,
24
+ sealAskAnswer,
25
+ openAskAnswer,
20
26
  } from "./machineSeal.mjs";
21
27
  import { findMachine, goesHome, queueable } from "./machineRoutes.mjs";
28
+ import { MERGE_COMMAND, MIRROR_COMMAND } from "./boardMirror.mjs";
29
+
30
+ // A worker's key for a direct link, swapped for home's over the sealed channel (directLink.mjs).
31
+ const DIRECT_COMMAND = "machine.direct";
22
32
 
23
33
  // The person's other computers (one swarm across them). One computer holds the board ("home"); every other one is a
24
34
  // worker: its agents' board calls go to home through Harness, sealed with the key the two computers share
@@ -33,6 +43,8 @@ export const FROM_MACHINE = Symbol("the computer a board call came from");
33
43
 
34
44
  // Wrong join codes a worker takes before it makes a new one: Harness carries the guesses and must not get many.
35
45
  const JOIN_TRIES = 5;
46
+ // How long home keeps trying a code typed for a computer that is not online yet: as long as its pairing code lasts.
47
+ const ADD_WAIT_MS = 10 * 60_000;
36
48
  const MB = 1024 * 1024;
37
49
  // What get_file shows inline on a worker, as on home (boardFileCommands.mjs).
38
50
  const INLINE_IMAGE_BYTES = 3.75 * MB;
@@ -57,11 +69,33 @@ export function createOwnMachines({
57
69
  folders = () => [],
58
70
  repositoryOf = () => null,
59
71
  homeBack = () => {},
72
+ // On home: a worker's call for the board's changes (boardMirror.mjs since).
73
+ answerMirror = null,
74
+ // On home: a stand-in's changes, merged (boardMirror.mjs merge).
75
+ answerMerge = null,
76
+ // The direct links between the person's computers (directLink.mjs); null keeps every message to Harness.
77
+ 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").
80
+ standInAfterMs = null,
81
+ // This computer stood in for that one: its own changes from now on go back to it (boardMirror.mjs startStandIn).
82
+ onStoodIn = () => {},
83
+ // Another computer stands in for this one: it takes home back (boardMirror.mjs takeBack).
84
+ returning = () => {},
85
+ // This computer's own Harness windows, asked a question for their screen history (phones.mjs ask).
86
+ askOwnWindows = async () => ({
87
+ ok: false,
88
+ code: "unpaired",
89
+ error: "no Harness window is linked to this computer",
90
+ }),
60
91
  }) {
61
92
  // On home: each worker's folders and the repository each holds, as it said them.
62
93
  const infos = new Map();
63
- // The account's other computers as Harness last listed them: { id, label, role, connected, agents, publicKey }.
94
+ // The account's other computers as Harness last listed them: { id, label, role, connected, agents, publicKey,
95
+ // standInFor }, and this one as Harness lists it.
64
96
  let siblings = [];
97
+ let selfListed = null;
98
+ let standInTimer = null;
65
99
  let flushing = false;
66
100
  // What home last heard of this computer's folders, false until it heard them on this connection.
67
101
  let toldHome = false;
@@ -82,6 +116,17 @@ export function createOwnMachines({
82
116
  const keyFor = (peerKey, workerId) =>
83
117
  pairKey(identity().privateKey, peerKey, workerId);
84
118
 
119
+ // A message for another of the person's computers: over the direct link when there is one and it answers, through
120
+ // Harness otherwise. Sealed the same either way.
121
+ const relayTo = async (input) => {
122
+ const peer = input.to === "home" ? homeListed()?.id : input.to;
123
+ const direct =
124
+ peer && directLink
125
+ ? await directLink.request(peer, { kind: input.kind, body: input.body })
126
+ : null;
127
+ return direct ?? ask("machine_relay", input);
128
+ };
129
+
85
130
  // ---- who this computer is, and the others ----
86
131
 
87
132
  const hello = () => ({
@@ -107,6 +152,8 @@ export function createOwnMachines({
107
152
  if (!Array.isArray(message?.machines)) return;
108
153
  // Harness lists an offline computer's agents as none: they are what it had when it was last on.
109
154
  const before = new Map(siblings.map((sibling) => [sibling.id, sibling]));
155
+ selfListed =
156
+ message.machines.find((listed) => listed?.id === machine.id) ?? null;
110
157
  siblings = message.machines
111
158
  .filter((listed) => listed && listed.id !== machine.id)
112
159
  .map((listed) => ({
@@ -120,8 +167,14 @@ export function createOwnMachines({
120
167
  : (before.get(String(listed.id))?.agents ?? []),
121
168
  publicKey:
122
169
  typeof listed.publicKey === "string" ? listed.publicKey : null,
170
+ standInFor:
171
+ typeof listed.standInFor === "string" ? listed.standInFor : null,
123
172
  }));
124
173
  changed();
174
+ retryAdding();
175
+ watchHome();
176
+ // Someone stood in for this computer: it takes home back, at once if the stand-in is away too (boardMirror.mjs).
177
+ if (someoneStandsIn()) returning();
125
178
  if (!homeListed()?.connected) toldHome = false;
126
179
  else if (!isHome()) void flush();
127
180
  };
@@ -138,6 +191,100 @@ export function createOwnMachines({
138
191
  return { ok: true, label: name };
139
192
  };
140
193
 
194
+ // ---- standing in while home is unreachable, and home taking its place back ----
195
+
196
+ /** The computer this one stands in for as home, or null. */
197
+ const standingIn = () =>
198
+ isHome() && typeof selfListed?.standInFor === "string"
199
+ ? selfListed.standInFor
200
+ : null;
201
+ /** Whether another computer stands in as home for this one. */
202
+ const someoneStandsIn = () => homeListed()?.standInFor === machine.id;
203
+ const homeUnreachable = () => {
204
+ const home = homeListed();
205
+ if (!home || home.connected || home.standInFor) return false;
206
+ return !(directLink?.status() ?? []).some(
207
+ (link) => link.id === home.id && link.linked
208
+ );
209
+ };
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.
212
+ const watchHome = () => {
213
+ const waiting =
214
+ standInAfterMs !== null &&
215
+ !isHome() &&
216
+ Boolean(pinnedHome()) &&
217
+ homeUnreachable();
218
+ if (!waiting) {
219
+ clearTimeout(standInTimer);
220
+ standInTimer = null;
221
+ return;
222
+ }
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
+ );
231
+ };
232
+ const standIn = async () => {
233
+ const answer = await ask("machine_role", {
234
+ role: "home",
235
+ standIn: true,
236
+ }).catch(() => null);
237
+ if (answer?.ok !== true || typeof answer.standInFor !== "string") return;
238
+ onStoodIn(answer.standInFor);
239
+ machine.role = "home";
240
+ saveMachine(machine);
241
+ changed();
242
+ await applyKept(answer.standInFor);
243
+ log(
244
+ `your home computer${labelOf(answer.standInFor) ? ` (${labelOf(answer.standInFor)})` : ""} is unreachable; this computer stands in as home until it is back`
245
+ );
246
+ };
247
+ // 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).
249
+ const applyKept = async (formerHome) => {
250
+ const pinned = store.ownMachine(formerHome);
251
+ const kept = outbox();
252
+ if (!pinned || !kept.length) return;
253
+ const key = await keyFor(pinned.public_key, machine.id);
254
+ for (const entry of kept) {
255
+ const opened = await openCall(key, entry.envelope, {
256
+ from: machine.id,
257
+ firstSeen: () => true,
258
+ });
259
+ if (opened.ok)
260
+ await settle(() =>
261
+ boardCommand({
262
+ ...stripLocal(opened.call),
263
+ command: opened.call.command,
264
+ })
265
+ );
266
+ }
267
+ keepOut([]);
268
+ log(
269
+ `did ${kept.length} kept write(s) on the board this computer now holds`
270
+ );
271
+ };
272
+ /** Home taking its place back from the computer that stood in, once it has that computer's changes. */
273
+ 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);
277
+ const answer = await ask("machine_role", {
278
+ role: "home",
279
+ reclaim: true,
280
+ }).catch(() => null);
281
+ if (answer?.ok !== true) return false;
282
+ machine.role = "home";
283
+ saveMachine(machine);
284
+ changed();
285
+ return true;
286
+ };
287
+
141
288
  /** The person makes this computer home. The board stays on the computer that had it. */
142
289
  const makeHome = async () => {
143
290
  const answer = await ask("machine_role", { role: "home" });
@@ -151,7 +298,16 @@ export function createOwnMachines({
151
298
 
152
299
  // ---- the join: the worker's code typed on home pins each computer's key on the other ----
153
300
 
301
+ // Setup's code becomes this computer's join code, in place of any made before (pairing.mjs keepJoinCode).
302
+ const adoptSetupCode = () => {
303
+ if (!machine.joinCode) return;
304
+ const code = normalizeJoinCode(machine.joinCode);
305
+ if (code) store.meta("machine-join", JSON.stringify({ code, wrong: 0 }));
306
+ machine.joinCode = null;
307
+ saveMachine(machine);
308
+ };
154
309
  const joinState = () => {
310
+ adoptSetupCode();
155
311
  try {
156
312
  return JSON.parse(store.meta("machine-join") || "null");
157
313
  } catch {
@@ -173,28 +329,38 @@ export function createOwnMachines({
173
329
  );
174
330
  };
175
331
 
332
+ const notHome = () => ({
333
+ ok: false,
334
+ error: `Add a computer on your home computer${homeListed() ? ` (${homeListed().label})` : ""}, not here.`,
335
+ });
336
+ const badCode = () => ({
337
+ ok: false,
338
+ error:
339
+ "That is not a code from the computer you are adding. It looks like ABCD-EFGH-JKLM-NPQR.",
340
+ });
341
+
176
342
  /** On home: the person typed a worker's join code. */
177
343
  const confirm = async (typed) => {
178
- if (!isHome())
179
- return {
180
- ok: false,
181
- error: `Confirm a computer on your home computer${homeListed() ? ` (${homeListed().label})` : ""}, not here.`,
182
- };
344
+ if (!isHome()) return notHome();
183
345
  const code = normalizeJoinCode(typed);
184
- if (!code)
185
- return {
186
- ok: false,
187
- error: "A join code is 12 letters and digits, like ABCD-EFGH-JKLM.",
188
- };
346
+ if (!code) return badCode();
347
+ return tryCode(code, new Set());
348
+ };
349
+
350
+ // 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) => {
189
353
  const waiting = siblings.filter(
190
354
  (sibling) =>
191
355
  sibling.role === "worker" &&
192
356
  sibling.connected &&
193
357
  sibling.publicKey &&
194
- !confirmed(sibling)
358
+ !confirmed(sibling) &&
359
+ !tried.has(sibling.id)
195
360
  );
196
361
  const homeKey = identity().publicKey;
197
362
  for (const worker of waiting) {
363
+ tried.add(worker.id);
198
364
  const keys = {
199
365
  homeId: machine.id,
200
366
  homeKey,
@@ -214,6 +380,9 @@ export function createOwnMachines({
214
380
  log(
215
381
  `${worker.label || worker.id} did not join: ${answer?.ok ? "its proof did not match this computer's" : answer?.error}`
216
382
  );
383
+ // Only a code it refused (or a proof that did not match) cost it a try; one it never heard is tried again.
384
+ if (!answer?.ok && answer?.code !== "wrong_code")
385
+ tried.delete(worker.id);
217
386
  continue;
218
387
  }
219
388
  store.pinOwnMachine(worker.id, worker.publicKey, worker.label);
@@ -227,12 +396,104 @@ export function createOwnMachines({
227
396
  }
228
397
  return {
229
398
  ok: false,
399
+ code: waiting.length ? "no_match" : "none_waiting",
230
400
  error: waiting.length
231
401
  ? "No computer waiting to join has that code. On the computer you are adding, npx tryharness machines shows its code."
232
402
  : "No computer is waiting to join. Start Harness on the computer you are adding (npx tryharness), then type the code it shows.",
233
403
  };
234
404
  };
235
405
 
406
+ // ---- adding a computer with setup's one code (the buddy's Add a Computer, npx tryharness machines add) ----
407
+
408
+ // Codes typed here, kept while the computer they are for comes online: id → { code, state, machine, until, tried }.
409
+ const adding = new Map();
410
+
411
+ const tryAdding = async (entry) => {
412
+ if (entry.state !== "waiting" || entry.trying) return;
413
+ if (Date.now() > entry.until) {
414
+ entry.state = "expired";
415
+ changed();
416
+ return;
417
+ }
418
+ entry.trying = true;
419
+ try {
420
+ const answer = await tryCode(entry.code, entry.tried);
421
+ if (answer.ok) {
422
+ Object.assign(entry, {
423
+ state: "joined",
424
+ machine: answer.machine,
425
+ fingerprint: answer.fingerprint,
426
+ });
427
+ changed();
428
+ }
429
+ } finally {
430
+ entry.trying = false;
431
+ }
432
+ };
433
+
434
+ /**
435
+ * The person typed the code a new computer shows. Harness releases that computer's connection to the account (when it
436
+ * still waits for one), and home confirms it into the swarm as soon as it is online. A code Harness had nothing
437
+ * waiting for is one already approved in a browser: it is tried now, on the computers waiting to join.
438
+ */
439
+ const add = async (typed) => {
440
+ const code = normalizeJoinCode(typed);
441
+ if (!code) return badCode();
442
+ let approved = null;
443
+ if (isPairCode(code)) {
444
+ const answer = await ask("machine_pair", pairClaim(code)).catch(
445
+ (error) => ({ ok: false, error: error.message })
446
+ );
447
+ if (!answer?.ok)
448
+ return { ok: false, error: answer?.error || "Harness did not answer" };
449
+ approved = answer.approved ? String(answer.hostname || "") : null;
450
+ }
451
+ if (!isHome())
452
+ return approved !== null
453
+ ? {
454
+ ok: true,
455
+ state: "approved",
456
+ machine: approved,
457
+ note: `It is connected to your account. To bring it into your swarm, type the same code on your home computer${homeListed() ? ` (${homeListed().label})` : ""}.`,
458
+ }
459
+ : notHome();
460
+ if (approved === null) {
461
+ const answer = await tryCode(code, new Set());
462
+ return answer.ok ? { ...answer, state: "joined" } : answer;
463
+ }
464
+ const entry = {
465
+ id: randomBytes(6).toString("hex"),
466
+ code,
467
+ state: "waiting",
468
+ machine: approved,
469
+ until: Date.now() + ADD_WAIT_MS,
470
+ tried: new Set(),
471
+ };
472
+ adding.set(entry.id, entry);
473
+ await tryAdding(entry);
474
+ return { ok: true, ...addingView(entry) };
475
+ };
476
+ const addingView = ({ id, state, machine: label, fingerprint: key }) => ({
477
+ id,
478
+ state,
479
+ machine: label || null,
480
+ ...(key ? { fingerprint: key } : {}),
481
+ });
482
+ // What the buddy shows while it waits: codes past their time read expired, and are let go an hour later.
483
+ const currentAdding = () => {
484
+ const now = Date.now();
485
+ for (const [id, entry] of adding) {
486
+ if (entry.state === "waiting" && now > entry.until)
487
+ entry.state = "expired";
488
+ if (now > entry.until + 60 * 60_000) adding.delete(id);
489
+ }
490
+ return [...adding.values()].map(addingView);
491
+ };
492
+ const retryAdding = () => {
493
+ if (!isHome()) return;
494
+ for (const entry of adding.values()) void tryAdding(entry);
495
+ };
496
+
236
497
  /** On a worker: home asks to join with the code the person typed there. */
237
498
  const onJoin = (body) => {
238
499
  const home = homeListed();
@@ -255,7 +516,11 @@ export function createOwnMachines({
255
516
  : { ...saved, wrong }
256
517
  )
257
518
  );
258
- return { ok: false, error: "that is not this computer's code" };
519
+ return {
520
+ ok: false,
521
+ code: "wrong_code",
522
+ error: "that is not this computer's code",
523
+ };
259
524
  }
260
525
  store.pinOwnMachine(home.id, body.homeKey, home.label);
261
526
  store.meta("machine-join", "null");
@@ -274,7 +539,7 @@ export function createOwnMachines({
274
539
  return {
275
540
  ok: false,
276
541
  code: "unconfirmed",
277
- error: `This computer is not confirmed for your swarm yet. On your home computer${home?.label ? ` (${home.label})` : ""}, run: npx tryharness machines confirm ${joinCode() ?? "<the code npx tryharness machines shows here>"}`,
542
+ error: `This computer is not confirmed for your swarm yet. On your home computer${home?.label ? ` (${home.label})` : ""}, choose Add a Computer in the Harness menu and type ${joinCode() ?? "the code npx tryharness machines shows here"}, or run: npx tryharness machines add ${joinCode() ?? "<code>"}`,
278
543
  };
279
544
  };
280
545
  const offline = () => ({
@@ -304,7 +569,7 @@ export function createOwnMachines({
304
569
  const deliver = async (key, requestId, envelope) => {
305
570
  let answer;
306
571
  try {
307
- answer = await ask("machine_relay", {
572
+ answer = await relayTo({
308
573
  to: "home",
309
574
  kind: "call",
310
575
  body: { envelope },
@@ -362,6 +627,19 @@ export function createOwnMachines({
362
627
  });
363
628
  if (told?.ok === true) toldHome = said;
364
629
  }
630
+ // Each side learns the other's key for a direct link, sealed, so each admits only the other (directLink.mjs).
631
+ const ownKey = await directLink?.key();
632
+ if (ownKey) {
633
+ const swapped = await callOnce(pinned, {
634
+ command: DIRECT_COMMAND,
635
+ agent: "user",
636
+ key: ownKey,
637
+ });
638
+ if (typeof swapped?.key === "string") {
639
+ directLink.allow(pinned.machine_id, swapped.key, { dialer: true });
640
+ void directLink.dial(pinned.machine_id);
641
+ }
642
+ }
365
643
  // Home is there for this computer: the work it keeps for it may start.
366
644
  if (toldHome) homeBack();
367
645
  } finally {
@@ -467,7 +745,12 @@ export function createOwnMachines({
467
745
  const callHome = async (request) => {
468
746
  const pinned = pinnedHome();
469
747
  if (!pinned) return homeListed() ? notJoined() : offline();
470
- const call = stripLocal(request);
748
+ // A task started here gets its id here, so it is the same task whether home takes it now or once it is back.
749
+ const call = stripLocal(
750
+ request.command === "board.post" && request.id == null
751
+ ? { ...request, id: randomUUID() }
752
+ : request
753
+ );
471
754
  if (call.command === "board.file.add" && call.path != null)
472
755
  return (await attach(pinned, call)) ?? offline();
473
756
  if (call.command === "board.file.get" && call.offset === undefined)
@@ -481,6 +764,16 @@ export function createOwnMachines({
481
764
  return {
482
765
  ok: true,
483
766
  queued: true,
767
+ ...(call.command === "board.post"
768
+ ? {
769
+ task: {
770
+ id: call.id,
771
+ objective: call.objective,
772
+ target_agent: call.targetAgent ?? null,
773
+ status: "open",
774
+ },
775
+ }
776
+ : {}),
484
777
  note: `Your home computer${homeListed()?.label ? ` (${homeListed().label})` : ""} is out of reach; this goes to it as soon as it is back.`,
485
778
  };
486
779
  };
@@ -502,14 +795,36 @@ export function createOwnMachines({
502
795
  }
503
796
  };
504
797
 
505
- const answerCall = async (from, body) => {
798
+ // The answers home gave lately, by the call they answer: the same sealed call arriving again (over the direct link,
799
+ // 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).
801
+ const answered = new Map();
802
+ const ANSWERS_KEPT = 500;
803
+ const once = (key, run) => {
804
+ if (answered.has(key)) return answered.get(key);
805
+ const answer = run();
806
+ answered.set(key, answer);
807
+ if (answered.size > ANSWERS_KEPT)
808
+ answered.delete(answered.keys().next().value);
809
+ return answer;
810
+ };
811
+
812
+ // Keyed by the sealed envelope itself (its random iv with its request id): only the very same call matches, so a
813
+ // forged one under a real call's id cannot stand in for it.
814
+ const sealedKey = (envelope) =>
815
+ `${envelope?.deviceId}:${envelope?.requestId}:${envelope?.iv}`;
816
+ const answerCall = (from, body) =>
817
+ once(`call:${from}:${sealedKey(body?.envelope)}`, () =>
818
+ answerCallOnce(from, body)
819
+ );
820
+ const answerCallOnce = async (from, body) => {
506
821
  const pinned = store.ownMachine(String(from));
507
822
  if (!isHome() || !pinned)
508
823
  return {
509
824
  ok: false,
510
825
  code: "unconfirmed",
511
826
  error: isHome()
512
- ? "This computer is not confirmed on home. On home, run: npx tryharness machines confirm <the code npx tryharness machines shows on this computer>"
827
+ ? "This computer is not confirmed on home. On home, choose Add a Computer in the Harness menu and type the code npx tryharness machines shows on this computer."
513
828
  : "This computer is not home.",
514
829
  };
515
830
  const key = await keyFor(pinned.public_key, from);
@@ -521,32 +836,60 @@ export function createOwnMachines({
521
836
  if (!opened.ok) return opened;
522
837
  const call = opened.call ?? {};
523
838
  const command = String(call.command || "");
524
- const result = !goesHome(command)
525
- ? {
526
- ok: false,
527
- error: `${command || "that"} runs on the agent's own computer`,
528
- }
529
- : await settle(() =>
530
- boardCommand({
531
- ...stripLocal(call),
532
- // A path names a file on the worker; its bytes come as data.
533
- path: undefined,
534
- command,
535
- [FROM_MACHINE]: from,
536
- })
537
- );
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
+ );
538
862
  return {
539
863
  envelope: await sealAnswer(key, from, body.envelope.requestId, result),
540
864
  };
541
865
  };
542
866
 
867
+ /** On home: a worker's key for a direct link, taken, and home's own given back. */
868
+ const swapDirectKeys = async (workerId, workerKey) => {
869
+ const ownKey = await directLink?.key();
870
+ if (!ownKey) return { ok: true, key: null };
871
+ directLink.allow(workerId, workerKey);
872
+ return { ok: true, key: ownKey };
873
+ };
874
+
875
+ /** A message that came over a direct link: what Harness's machine_relay would have handed over, from that computer. */
876
+ const fromLink = (peerId, body) =>
877
+ isHome()
878
+ ? body?.kind === "call"
879
+ ? answerCall(peerId, body.body)
880
+ : Promise.resolve({ ok: false, error: "home takes only calls" })
881
+ : ["notice", "ask"].includes(body?.kind) &&
882
+ peerId === pinnedHome()?.machine_id
883
+ ? relay({ from: "home", kind: body.kind, body: body.body })
884
+ : Promise.resolve({ ok: false, error: "a worker takes only home's" });
885
+
543
886
  /** On home: a notice for a worker (a run to stop), kept by Harness while it is offline. */
544
887
  const noticeTo = async (workerId, notice) => {
545
888
  const pinned = store.ownMachine(workerId);
546
889
  if (!isHome() || !pinned) return { ok: false };
547
890
  const key = await keyFor(pinned.public_key, workerId);
548
891
  const envelope = await sealNotice(key, workerId, newRequestId(), notice);
549
- return ask("machine_relay", {
892
+ return relayTo({
550
893
  to: workerId,
551
894
  kind: "notice",
552
895
  body: { envelope },
@@ -570,7 +913,92 @@ export function createOwnMachines({
570
913
  return { ok: true };
571
914
  };
572
915
 
573
- /** Harness's machine_relay for this computer: a call (on home), a join or a notice (on a worker). */
916
+ /**
917
+ * On home: each confirmed worker it can reach hears its copy of the board is behind (boardMirror.mjs): through
918
+ * Harness when Harness has it connected, or over the direct link when only that is up.
919
+ */
920
+ const tellWorkers = (notice) => {
921
+ if (!isHome()) return;
922
+ const linked = new Set(
923
+ (directLink?.status() ?? [])
924
+ .filter((link) => link.linked)
925
+ .map((link) => link.id)
926
+ );
927
+ for (const worker of siblings.filter(
928
+ (sibling) =>
929
+ sibling.role === "worker" &&
930
+ (sibling.connected || linked.has(sibling.id))
931
+ ))
932
+ if (store.ownMachine(worker.id)) void noticeTo(worker.id, notice);
933
+ };
934
+
935
+ // ---- the person's Harness windows on the other computers ----
936
+
937
+ // The windows a question finds nothing in: none linked, or none open. Any other answer, a refusal included, is final.
938
+ const nobodyThere = (answer) =>
939
+ answer?.ok === false && ["unpaired", "closed"].includes(answer.code);
940
+
941
+ /**
942
+ * On home: a question for the person's Harness windows linked to the workers (each window links to the computer it
943
+ * runs on), asked of each confirmed worker that is connected, in turn. The first that has one answers; null when none
944
+ * was asked or none had a window.
945
+ */
946
+ const askWorkerWindows = async (call) => {
947
+ if (!isHome()) return null;
948
+ let found = null;
949
+ for (const worker of siblings.filter(
950
+ (sibling) => sibling.role === "worker" && sibling.connected
951
+ )) {
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);
967
+ if (!answer) continue;
968
+ if (!nobodyThere(answer)) return answer;
969
+ found ??= answer;
970
+ }
971
+ return found;
972
+ };
973
+
974
+ /** On a worker: home's question for the windows linked here, opened, asked and the answer sealed back. */
975
+ const onAskFromHome = (body) =>
976
+ once(`ask:${sealedKey(body?.envelope)}`, () => onAskFromHomeOnce(body));
977
+ const onAskFromHomeOnce = async (body) => {
978
+ const pinned = pinnedHome();
979
+ if (!pinned) return { ok: false, error: "this computer is not confirmed" };
980
+ const key = await keyFor(pinned.public_key, machine.id);
981
+ const call = await openAsk(key, body?.envelope, {
982
+ workerId: machine.id,
983
+ firstSeen: (requestId) =>
984
+ store.firstPhoneRequest(
985
+ `machine:${pinned.machine_id}`,
986
+ String(requestId)
987
+ ),
988
+ });
989
+ if (!call) return { ok: false, error: "the question could not be opened" };
990
+ const answer = await askOwnWindows(call);
991
+ return {
992
+ envelope: await sealAskAnswer(
993
+ key,
994
+ machine.id,
995
+ body.envelope.requestId,
996
+ answer
997
+ ),
998
+ };
999
+ };
1000
+
1001
+ /** Harness's machine_relay for this computer: a call (on home), a join, a notice or a question (on a worker). */
574
1002
  const relay = (input) =>
575
1003
  input?.kind === "call"
576
1004
  ? answerCall(String(input.from || ""), input.body)
@@ -578,7 +1006,9 @@ export function createOwnMachines({
578
1006
  ? Promise.resolve(onJoin(input.body))
579
1007
  : input?.kind === "notice"
580
1008
  ? onNoticeFromHome(input.body)
581
- : Promise.resolve({ ok: false, error: "unknown message" });
1009
+ : input?.kind === "ask"
1010
+ ? onAskFromHome(input.body)
1011
+ : Promise.resolve({ ok: false, error: "unknown message" });
582
1012
 
583
1013
  // ---- what the person and status read ----
584
1014
 
@@ -605,11 +1035,15 @@ export function createOwnMachines({
605
1035
  id: machine.id,
606
1036
  label: machine.label,
607
1037
  role: machine.role ?? "home",
1038
+ standingInFor: standingIn()
1039
+ ? (labelOf(standingIn()) ?? standingIn())
1040
+ : null,
608
1041
  fingerprint: identity()
609
1042
  ? await fingerprint(identity().publicKey)
610
1043
  : null,
611
1044
  },
612
1045
  joinCode: joinCode(),
1046
+ adding: currentAdding(),
613
1047
  machines: await Promise.all(
614
1048
  listed.map(async (sibling) => ({
615
1049
  id: sibling.id,
@@ -618,6 +1052,10 @@ export function createOwnMachines({
618
1052
  connected: sibling.connected,
619
1053
  agents: sibling.agents,
620
1054
  confirmed: confirmed(sibling),
1055
+ standsInForThis: sibling.standInFor === machine.id,
1056
+ direct:
1057
+ directLink?.status().find((link) => link.id === sibling.id)
1058
+ ?.linked === true,
621
1059
  fingerprint: sibling.publicKey
622
1060
  ? await fingerprint(sibling.publicKey)
623
1061
  : null,
@@ -630,6 +1068,9 @@ export function createOwnMachines({
630
1068
  id: machine.id,
631
1069
  label: machine.label,
632
1070
  role: machine.role ?? null,
1071
+ ...(standingIn()
1072
+ ? { standingInFor: labelOf(standingIn()) ?? standingIn() }
1073
+ : {}),
633
1074
  ...(isHome()
634
1075
  ? {}
635
1076
  : {
@@ -721,6 +1162,28 @@ export function createOwnMachines({
721
1162
  })),
722
1163
  ];
723
1164
 
1165
+ /** The name beside an agent's words from that computer ("Codex (linux)"): only once the person has more than one. */
1166
+ const shownLabel = (id) => (all().length > 1 ? labelOf(id) : null);
1167
+
1168
+ /**
1169
+ * Where an agent calling from that computer is: its name, whether it is home (which keeps the board), home's name and
1170
+ * the person's other computers. What an agent is told of itself (cards.mjs youLine); null for a computer not known here.
1171
+ */
1172
+ const whereIs = (id) => {
1173
+ const computers = all();
1174
+ const here = computers.find((computer) => computer.id === id);
1175
+ if (!labelOf(id)) return null;
1176
+ return {
1177
+ computer: labelOf(id),
1178
+ home: (here?.role ?? "home") === "home",
1179
+ homeLabel:
1180
+ computers.find((computer) => computer.role === "home")?.label ?? null,
1181
+ others: computers
1182
+ .filter((computer) => computer.id !== id)
1183
+ .map((computer) => computer.label),
1184
+ };
1185
+ };
1186
+
724
1187
  return {
725
1188
  hello,
726
1189
  adopt,
@@ -728,10 +1191,30 @@ export function createOwnMachines({
728
1191
  rename,
729
1192
  makeHome,
730
1193
  confirm,
1194
+ add,
731
1195
  forwards,
732
1196
  callHome,
733
1197
  relay,
734
1198
  noticeTo,
1199
+ askWorkerWindows,
1200
+ tellWorkers,
1201
+ fromLink,
1202
+ standingIn,
1203
+ someoneStandsIn,
1204
+ // A worker confirmed into the swarm: it holds home's key.
1205
+ joined: () => Boolean(pinnedHome()),
1206
+ standInReachable: () => {
1207
+ const home = homeListed();
1208
+ return Boolean(
1209
+ home &&
1210
+ (home.connected ||
1211
+ (directLink?.status() ?? []).some(
1212
+ (link) => link.id === home.id && link.linked
1213
+ ))
1214
+ );
1215
+ },
1216
+ reclaim,
1217
+ directStatus: () => directLink?.status() ?? [],
735
1218
  list,
736
1219
  status,
737
1220
  all,
@@ -740,6 +1223,8 @@ export function createOwnMachines({
740
1223
  computersWith,
741
1224
  computersFor,
742
1225
  labelOf,
1226
+ shownLabel,
1227
+ whereIs,
743
1228
  find: (named) => findMachine(all(), named),
744
1229
  isHome,
745
1230
  self: () => machine.id,