tryharness 0.7.41 → 0.7.43

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 (46) hide show
  1. package/cli.mjs +118 -5
  2. package/lib/actorRoster.mjs +16 -2
  3. package/lib/adapters.mjs +2 -1
  4. package/lib/answers.mjs +30 -0
  5. package/lib/boardCommands.mjs +9 -1
  6. package/lib/boardFiles.mjs +1 -1
  7. package/lib/boardProtocol.json +1 -0
  8. package/lib/bridge.mjs +49 -9
  9. package/lib/cards.mjs +22 -4
  10. package/lib/compaction.mjs +90 -0
  11. package/lib/context.mjs +19 -11
  12. package/lib/coordinator.mjs +176 -12
  13. package/lib/daemon.mjs +424 -44
  14. package/lib/fit.mjs +65 -0
  15. package/lib/folders.mjs +20 -0
  16. package/lib/frames.mjs +3 -2
  17. package/lib/goalCommands.mjs +12 -0
  18. package/lib/handover.mjs +128 -0
  19. package/lib/loopBackstop.mjs +104 -0
  20. package/lib/machineIdentity.mjs +43 -0
  21. package/lib/machineRoutes.mjs +97 -0
  22. package/lib/machineRuns.mjs +133 -0
  23. package/lib/machineSeal.mjs +157 -0
  24. package/lib/mcp-stdio.mjs +54 -11
  25. package/lib/nudge.mjs +211 -44
  26. package/lib/oneLine.mjs +27 -0
  27. package/lib/ownMachines.mjs +748 -0
  28. package/lib/paths.mjs +1 -0
  29. package/lib/plans.mjs +3 -2
  30. package/lib/provenance.mjs +4 -1
  31. package/lib/runBrief.mjs +346 -0
  32. package/lib/runWorker.mjs +24 -173
  33. package/lib/runner.mjs +26 -2
  34. package/lib/store.mjs +232 -16
  35. package/lib/stuck.mjs +198 -0
  36. package/lib/swarm.mjs +3 -1
  37. package/lib/taskCommands.mjs +268 -31
  38. package/lib/taskRuns.mjs +9 -0
  39. package/lib/team.json +192 -0
  40. package/lib/team.mjs +417 -0
  41. package/lib/threadRuns.mjs +18 -7
  42. package/lib/threadView.mjs +13 -0
  43. package/lib/trails.mjs +49 -0
  44. package/lib/wakes.mjs +201 -69
  45. package/lib/worktrees.mjs +9 -0
  46. package/package.json +1 -1
@@ -0,0 +1,748 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ import { documentText, ensureDir, isDocument, mimeFor } from "./files.mjs";
5
+ import { FILE_PART_BYTES } from "./boardFiles.mjs";
6
+ import { fingerprint } from "./sealed.mjs";
7
+ import {
8
+ joinProof,
9
+ newJoinCode,
10
+ newRequestId,
11
+ normalizeJoinCode,
12
+ openAnswer,
13
+ openCall,
14
+ openNotice,
15
+ pairKey,
16
+ sameProof,
17
+ sealAnswer,
18
+ sealCall,
19
+ sealNotice,
20
+ } from "./machineSeal.mjs";
21
+ import { findMachine, goesHome, queueable } from "./machineRoutes.mjs";
22
+
23
+ // The person's other computers (one swarm across them). One computer holds the board ("home"); every other one is a
24
+ // worker: its agents' board calls go to home through Harness, sealed with the key the two computers share
25
+ // (machineSeal.mjs), and home answers them on its board as that agent on that computer. Harness says which computers
26
+ // there are and carries what they send; a computer trusts another only once the person confirmed it on home with the
27
+ // worker's join code. A worker keeps what its agents write while home is out of reach and sends it when home is back.
28
+ // Known limit: while home sleeps, workers can read nothing and take no new work.
29
+
30
+ // Set on a board request by this module alone: the computer the call came from. JSON cannot carry it, so no caller
31
+ // names a computer it is not on.
32
+ export const FROM_MACHINE = Symbol("the computer a board call came from");
33
+
34
+ // Wrong join codes a worker takes before it makes a new one: Harness carries the guesses and must not get many.
35
+ const JOIN_TRIES = 5;
36
+ const MB = 1024 * 1024;
37
+ // What get_file shows inline on a worker, as on home (boardFileCommands.mjs).
38
+ const INLINE_IMAGE_BYTES = 3.75 * MB;
39
+ const INLINE_TEXT_BYTES = 200_000;
40
+ const textLike = (mime) =>
41
+ mime.startsWith("text/") ||
42
+ ["application/json", "application/xml", "image/svg+xml"].includes(mime);
43
+
44
+ export function createOwnMachines({
45
+ store,
46
+ log,
47
+ machine,
48
+ saveMachine,
49
+ identity,
50
+ agents = [],
51
+ ask,
52
+ boardCommand,
53
+ filesRoot,
54
+ changed = () => {},
55
+ onNotice = () => {},
56
+ // The folders worked in here with the repository each holds: [{ path, repository }].
57
+ folders = () => [],
58
+ repositoryOf = () => null,
59
+ homeBack = () => {},
60
+ }) {
61
+ // On home: each worker's folders and the repository each holds, as it said them.
62
+ const infos = new Map();
63
+ // The account's other computers as Harness last listed them: { id, label, role, connected, agents, publicKey }.
64
+ let siblings = [];
65
+ let flushing = false;
66
+ // What home last heard of this computer's folders, false until it heard them on this connection.
67
+ let toldHome = false;
68
+
69
+ const isHome = () => machine.role !== "worker";
70
+ const homeListed = () =>
71
+ siblings.find((sibling) => sibling.role === "home") ?? null;
72
+ const pinnedHome = () => {
73
+ const home = homeListed();
74
+ return home ? store.ownMachine(home.id) : null;
75
+ };
76
+ const labelOf = (id) =>
77
+ id === machine.id
78
+ ? machine.label
79
+ : (siblings.find((sibling) => sibling.id === id)?.label ??
80
+ store.ownMachine(id)?.label ??
81
+ null);
82
+ const keyFor = (peerKey, workerId) =>
83
+ pairKey(identity().privateKey, peerKey, workerId);
84
+
85
+ // ---- who this computer is, and the others ----
86
+
87
+ const hello = () => ({
88
+ machineId: machine.id,
89
+ label: machine.label,
90
+ ...(machine.role ? { role: machine.role } : {}),
91
+ });
92
+
93
+ /** Harness's answer to this computer's hello: its role on the account. */
94
+ const adopt = (given) => {
95
+ if (!given || !["home", "worker"].includes(given.role)) return;
96
+ if (machine.role && machine.role !== given.role)
97
+ log(
98
+ `this computer is now ${given.role === "home" ? "home: it holds the board" : "a worker: its agents reach the board on your home computer"}`
99
+ );
100
+ machine.role = given.role;
101
+ saveMachine(machine);
102
+ changed();
103
+ };
104
+
105
+ /** Harness's list of the account's computers, sent on every hello and every goodbye. */
106
+ const introduce = (message) => {
107
+ if (!Array.isArray(message?.machines)) return;
108
+ // Harness lists an offline computer's agents as none: they are what it had when it was last on.
109
+ const before = new Map(siblings.map((sibling) => [sibling.id, sibling]));
110
+ siblings = message.machines
111
+ .filter((listed) => listed && listed.id !== machine.id)
112
+ .map((listed) => ({
113
+ id: String(listed.id),
114
+ label: String(listed.label || ""),
115
+ role: listed.role === "home" ? "home" : "worker",
116
+ connected: listed.connected === true,
117
+ agents:
118
+ listed.connected === true && Array.isArray(listed.agents)
119
+ ? listed.agents.map(String)
120
+ : (before.get(String(listed.id))?.agents ?? []),
121
+ publicKey:
122
+ typeof listed.publicKey === "string" ? listed.publicKey : null,
123
+ }));
124
+ changed();
125
+ if (!homeListed()?.connected) toldHome = false;
126
+ else if (!isHome()) void flush();
127
+ };
128
+
129
+ const rename = async (label) => {
130
+ const name = String(label || "")
131
+ .trim()
132
+ .slice(0, 64);
133
+ if (!name) return { ok: false, error: "give the computer a name" };
134
+ machine.label = name;
135
+ saveMachine(machine);
136
+ changed();
137
+ await ask("machine_label", { label: name }).catch(() => null);
138
+ return { ok: true, label: name };
139
+ };
140
+
141
+ /** The person makes this computer home. The board stays on the computer that had it. */
142
+ const makeHome = async () => {
143
+ const answer = await ask("machine_role", { role: "home" });
144
+ if (!answer?.ok)
145
+ return { ok: false, error: answer?.error || "Harness did not answer" };
146
+ machine.role = "home";
147
+ saveMachine(machine);
148
+ changed();
149
+ return { ok: true, before: answer.before ?? null };
150
+ };
151
+
152
+ // ---- the join: the worker's code typed on home pins each computer's key on the other ----
153
+
154
+ const joinState = () => {
155
+ try {
156
+ return JSON.parse(store.meta("machine-join") || "null");
157
+ } catch {
158
+ return null;
159
+ }
160
+ };
161
+ const joinCode = () => {
162
+ if (isHome() || pinnedHome()) return null;
163
+ const saved = joinState();
164
+ if (saved?.code) return saved.code;
165
+ const code = newJoinCode();
166
+ store.meta("machine-join", JSON.stringify({ code, wrong: 0 }));
167
+ return code;
168
+ };
169
+ const confirmed = (sibling) => {
170
+ const pinned = store.ownMachine(sibling.id);
171
+ return Boolean(
172
+ pinned && (!sibling.publicKey || pinned.public_key === sibling.publicKey)
173
+ );
174
+ };
175
+
176
+ /** On home: the person typed a worker's join code. */
177
+ 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
+ };
183
+ 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
+ };
189
+ const waiting = siblings.filter(
190
+ (sibling) =>
191
+ sibling.role === "worker" &&
192
+ sibling.connected &&
193
+ sibling.publicKey &&
194
+ !confirmed(sibling)
195
+ );
196
+ const homeKey = identity().publicKey;
197
+ for (const worker of waiting) {
198
+ const keys = {
199
+ homeId: machine.id,
200
+ homeKey,
201
+ workerId: worker.id,
202
+ workerKey: worker.publicKey,
203
+ };
204
+ const answer = await ask("machine_relay", {
205
+ to: worker.id,
206
+ kind: "join",
207
+ body: { homeKey, proof: joinProof(code, "home", keys) },
208
+ }).catch((error) => ({ ok: false, error: error.message }));
209
+ if (
210
+ !answer?.ok ||
211
+ typeof answer.proof !== "string" ||
212
+ !sameProof(answer.proof, joinProof(code, "worker", keys))
213
+ ) {
214
+ log(
215
+ `${worker.label || worker.id} did not join: ${answer?.ok ? "its proof did not match this computer's" : answer?.error}`
216
+ );
217
+ continue;
218
+ }
219
+ store.pinOwnMachine(worker.id, worker.publicKey, worker.label);
220
+ log(`confirmed ${worker.label || worker.id} as one of your computers`);
221
+ changed();
222
+ return {
223
+ ok: true,
224
+ machine: worker.label,
225
+ fingerprint: await fingerprint(worker.publicKey),
226
+ };
227
+ }
228
+ return {
229
+ ok: false,
230
+ error: waiting.length
231
+ ? "No computer waiting to join has that code. On the computer you are adding, npx tryharness machines shows its code."
232
+ : "No computer is waiting to join. Start Harness on the computer you are adding (npx tryharness), then type the code it shows.",
233
+ };
234
+ };
235
+
236
+ /** On a worker: home asks to join with the code the person typed there. */
237
+ const onJoin = (body) => {
238
+ const home = homeListed();
239
+ const saved = joinState();
240
+ if (!home || !saved?.code || typeof body?.homeKey !== "string")
241
+ return { ok: false, error: "this computer is not waiting to join" };
242
+ const keys = {
243
+ homeId: home.id,
244
+ homeKey: body.homeKey,
245
+ workerId: machine.id,
246
+ workerKey: identity().publicKey,
247
+ };
248
+ if (!sameProof(String(body.proof), joinProof(saved.code, "home", keys))) {
249
+ const wrong = Number(saved.wrong || 0) + 1;
250
+ store.meta(
251
+ "machine-join",
252
+ JSON.stringify(
253
+ wrong >= JOIN_TRIES
254
+ ? { code: newJoinCode(), wrong: 0 }
255
+ : { ...saved, wrong }
256
+ )
257
+ );
258
+ return { ok: false, error: "that is not this computer's code" };
259
+ }
260
+ store.pinOwnMachine(home.id, body.homeKey, home.label);
261
+ store.meta("machine-join", "null");
262
+ log(
263
+ `joined your swarm: ${home.label || "your home computer"} holds the board`
264
+ );
265
+ changed();
266
+ void flush();
267
+ return { ok: true, proof: joinProof(saved.code, "worker", keys) };
268
+ };
269
+
270
+ // ---- a worker's board calls, sealed to home ----
271
+
272
+ const notJoined = () => {
273
+ const home = homeListed();
274
+ return {
275
+ ok: false,
276
+ 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>"}`,
278
+ };
279
+ };
280
+ const offline = () => ({
281
+ ok: false,
282
+ code: "home_offline",
283
+ error: `Your home computer${homeListed()?.label ? ` (${homeListed().label})` : ""} is offline, so the board can't be reached from this computer right now.`,
284
+ });
285
+
286
+ const outbox = () => {
287
+ try {
288
+ return JSON.parse(store.meta("machine-outbox") || "[]");
289
+ } catch {
290
+ return [];
291
+ }
292
+ };
293
+ const keepOut = (list) => store.meta("machine-outbox", JSON.stringify(list));
294
+
295
+ // One sealed call to home and its opened answer; null when home could not be reached.
296
+ const send = async (pinned, call, { queued = false } = {}) => {
297
+ const key = await keyFor(pinned.public_key, machine.id);
298
+ const requestId = newRequestId();
299
+ const envelope = await sealCall(key, machine.id, requestId, call, {
300
+ queued,
301
+ });
302
+ return { key, requestId, envelope };
303
+ };
304
+ const deliver = async (key, requestId, envelope) => {
305
+ let answer;
306
+ try {
307
+ answer = await ask("machine_relay", {
308
+ to: "home",
309
+ kind: "call",
310
+ body: { envelope },
311
+ });
312
+ } catch {
313
+ return null;
314
+ }
315
+ if (!answer?.envelope) {
316
+ if (["offline", "timed_out"].includes(answer?.code)) return null;
317
+ return {
318
+ ok: false,
319
+ code: answer?.code,
320
+ error: answer?.error || "home refused the call",
321
+ };
322
+ }
323
+ try {
324
+ return await openAnswer(key, answer.envelope, {
325
+ workerId: machine.id,
326
+ requestId,
327
+ });
328
+ } catch {
329
+ return {
330
+ ok: false,
331
+ error:
332
+ "the answer could not be opened: it did not come from your home computer",
333
+ };
334
+ }
335
+ };
336
+
337
+ /** Writes kept while home was out of reach, in order; stops at the first that still cannot go. */
338
+ const flush = async () => {
339
+ const pinned = pinnedHome();
340
+ if (flushing || !pinned) return;
341
+ flushing = true;
342
+ try {
343
+ for (;;) {
344
+ const [next, ...rest] = outbox();
345
+ if (!next) break;
346
+ const key = await keyFor(pinned.public_key, machine.id);
347
+ const result = await deliver(key, next.requestId, next.envelope);
348
+ if (result === null) break;
349
+ keepOut(rest);
350
+ log(
351
+ `sent ${next.command} to your home computer: ${result.ok === false && result.code !== "replayed" ? result.error : "taken"}`
352
+ );
353
+ }
354
+ // Once a connection: home hears which repositories are here and in which folders, so work for one can come here.
355
+ const here = folders();
356
+ const said = JSON.stringify(here);
357
+ if (toldHome !== said) {
358
+ const told = await callOnce(pinned, {
359
+ command: "board.machine.info",
360
+ agent: "user",
361
+ folders: here,
362
+ });
363
+ if (told?.ok === true) toldHome = said;
364
+ }
365
+ // Home is there for this computer: the work it keeps for it may start.
366
+ if (toldHome) homeBack();
367
+ } finally {
368
+ flushing = false;
369
+ }
370
+ };
371
+
372
+ const stripLocal = (request) => {
373
+ const {
374
+ agent,
375
+ command,
376
+ claimerPid: _claimer,
377
+ posterPid: _poster,
378
+ pids: _pids,
379
+ ...rest
380
+ } = request;
381
+ return { ...rest, command, agent };
382
+ };
383
+
384
+ const callOnce = async (pinned, call) => {
385
+ const { key, requestId, envelope } = await send(pinned, call);
386
+ return deliver(key, requestId, envelope);
387
+ };
388
+
389
+ // A file on this computer goes to home as its bytes, in parts a sealed call carries.
390
+ const attach = async (pinned, request) => {
391
+ const file = String(request.path);
392
+ const stat = path.isAbsolute(file)
393
+ ? fs.statSync(file, { throwIfNoEntry: false })
394
+ : null;
395
+ if (!stat?.isFile())
396
+ return { ok: false, error: `${file} is not an absolute path to a file` };
397
+ const bytes = fs.readFileSync(file);
398
+ const { path: _path, ...rest } = request;
399
+ const base = { ...rest, name: request.name || path.basename(file) };
400
+ if (bytes.length <= FILE_PART_BYTES)
401
+ return callOnce(pinned, { ...base, data: bytes.toString("base64") });
402
+ const upload = randomBytes(12).toString("base64url");
403
+ let answer = null;
404
+ for (let offset = 0; offset < bytes.length; offset += FILE_PART_BYTES) {
405
+ answer = await callOnce(pinned, {
406
+ ...base,
407
+ upload,
408
+ offset,
409
+ total: bytes.length,
410
+ data: bytes
411
+ .subarray(offset, offset + FILE_PART_BYTES)
412
+ .toString("base64"),
413
+ });
414
+ if (!answer || answer.ok === false) return answer;
415
+ }
416
+ return answer;
417
+ };
418
+
419
+ // A file on home is opened from a copy on this computer, fetched in parts.
420
+ const open = async (pinned, request) => {
421
+ const fileId = String(request.fileId || "");
422
+ const parts = [];
423
+ let file = null;
424
+ for (let offset = 0; !file || offset < file.bytes;) {
425
+ const answer = await callOnce(pinned, {
426
+ command: "board.file.get",
427
+ agent: request.agent,
428
+ fileId,
429
+ offset,
430
+ length: FILE_PART_BYTES,
431
+ });
432
+ if (!answer || answer.ok === false) return answer;
433
+ file = answer.file;
434
+ const part = Buffer.from(String(answer.data || ""), "base64");
435
+ if (!part.length) break;
436
+ parts.push(part);
437
+ offset += part.length;
438
+ }
439
+ const bytes = Buffer.concat(parts);
440
+ const local = path.join(
441
+ filesRoot,
442
+ "from-home",
443
+ String(file.id || fileId).replace(/[^\w-]/g, ""),
444
+ path.basename(String(file.name || "file")).replace(/^\.+/, "") || "file"
445
+ );
446
+ ensureDir(path.dirname(local));
447
+ fs.writeFileSync(local, bytes, { mode: 0o600 });
448
+ const mime = file.mime || mimeFor(local);
449
+ const inline =
450
+ request.inlineOnly !== true ||
451
+ (/^image\/(png|jpeg|gif|webp)$/.test(mime) &&
452
+ bytes.length <= INLINE_IMAGE_BYTES) ||
453
+ (textLike(mime) && bytes.length <= INLINE_TEXT_BYTES);
454
+ const words =
455
+ request.inlineOnly === true && isDocument(mime)
456
+ ? documentText(local, mime)
457
+ : null;
458
+ return {
459
+ ok: true,
460
+ file: { ...file, path: local },
461
+ ...(inline ? { data: bytes.toString("base64") } : {}),
462
+ ...(words !== null ? { text: words } : {}),
463
+ };
464
+ };
465
+
466
+ /** On a worker: one of its agents' board calls, answered by home. */
467
+ const callHome = async (request) => {
468
+ const pinned = pinnedHome();
469
+ if (!pinned) return homeListed() ? notJoined() : offline();
470
+ const call = stripLocal(request);
471
+ if (call.command === "board.file.add" && call.path != null)
472
+ return (await attach(pinned, call)) ?? offline();
473
+ if (call.command === "board.file.get" && call.offset === undefined)
474
+ return (await open(pinned, call)) ?? offline();
475
+ const answer = await callOnce(pinned, call);
476
+ if (answer) return answer;
477
+ if (!queueable(call.command)) return offline();
478
+ // Kept, sealed, until home is back; the call carries when it was written.
479
+ const { requestId, envelope } = await send(pinned, call, { queued: true });
480
+ keepOut([...outbox(), { requestId, envelope, command: call.command }]);
481
+ return {
482
+ ok: true,
483
+ queued: true,
484
+ note: `Your home computer${homeListed()?.label ? ` (${homeListed().label})` : ""} is out of reach; this goes to it as soon as it is back.`,
485
+ };
486
+ };
487
+
488
+ /** Whether a board request made on this computer goes to home. */
489
+ const forwards = (request) => !isHome() && goesHome(request.command);
490
+
491
+ // ---- on home: a worker's call, opened, answered on the board and sealed back ----
492
+
493
+ const settle = async (run) => {
494
+ try {
495
+ const result = run();
496
+ return result?.pending ? { ok: true, ...(await result.pending) } : result;
497
+ } catch (error) {
498
+ return {
499
+ ok: false,
500
+ error: `the board could not answer: ${error.message}`,
501
+ };
502
+ }
503
+ };
504
+
505
+ const answerCall = async (from, body) => {
506
+ const pinned = store.ownMachine(String(from));
507
+ if (!isHome() || !pinned)
508
+ return {
509
+ ok: false,
510
+ code: "unconfirmed",
511
+ 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>"
513
+ : "This computer is not home.",
514
+ };
515
+ const key = await keyFor(pinned.public_key, from);
516
+ const opened = await openCall(key, body?.envelope, {
517
+ from,
518
+ firstSeen: (requestId) =>
519
+ store.firstPhoneRequest(`machine:${from}`, String(requestId)),
520
+ });
521
+ if (!opened.ok) return opened;
522
+ const call = opened.call ?? {};
523
+ 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
+ );
538
+ return {
539
+ envelope: await sealAnswer(key, from, body.envelope.requestId, result),
540
+ };
541
+ };
542
+
543
+ /** On home: a notice for a worker (a run to stop), kept by Harness while it is offline. */
544
+ const noticeTo = async (workerId, notice) => {
545
+ const pinned = store.ownMachine(workerId);
546
+ if (!isHome() || !pinned) return { ok: false };
547
+ const key = await keyFor(pinned.public_key, workerId);
548
+ const envelope = await sealNotice(key, workerId, newRequestId(), notice);
549
+ return ask("machine_relay", {
550
+ to: workerId,
551
+ kind: "notice",
552
+ body: { envelope },
553
+ }).catch(() => ({ ok: false }));
554
+ };
555
+
556
+ const onNoticeFromHome = async (body) => {
557
+ const pinned = pinnedHome();
558
+ if (!pinned) return { ok: false };
559
+ const key = await keyFor(pinned.public_key, machine.id);
560
+ const notice = await openNotice(key, body?.envelope, {
561
+ workerId: machine.id,
562
+ firstSeen: (requestId) =>
563
+ store.firstPhoneRequest(
564
+ `machine:${pinned.machine_id}`,
565
+ String(requestId)
566
+ ),
567
+ });
568
+ if (!notice) return { ok: false };
569
+ onNotice(notice);
570
+ return { ok: true };
571
+ };
572
+
573
+ /** Harness's machine_relay for this computer: a call (on home), a join or a notice (on a worker). */
574
+ const relay = (input) =>
575
+ input?.kind === "call"
576
+ ? answerCall(String(input.from || ""), input.body)
577
+ : input?.kind === "join"
578
+ ? Promise.resolve(onJoin(input.body))
579
+ : input?.kind === "notice"
580
+ ? onNoticeFromHome(input.body)
581
+ : Promise.resolve({ ok: false, error: "unknown message" });
582
+
583
+ // ---- what the person and status read ----
584
+
585
+ const list = async () => {
586
+ const listed = [
587
+ ...siblings,
588
+ ...store
589
+ .ownMachines()
590
+ .filter(
591
+ (pinned) => !siblings.some((each) => each.id === pinned.machine_id)
592
+ )
593
+ .map((pinned) => ({
594
+ id: pinned.machine_id,
595
+ label: pinned.label,
596
+ role: "worker",
597
+ connected: false,
598
+ agents: [],
599
+ publicKey: pinned.public_key,
600
+ })),
601
+ ];
602
+ return {
603
+ ok: true,
604
+ self: {
605
+ id: machine.id,
606
+ label: machine.label,
607
+ role: machine.role ?? "home",
608
+ fingerprint: identity()
609
+ ? await fingerprint(identity().publicKey)
610
+ : null,
611
+ },
612
+ joinCode: joinCode(),
613
+ machines: await Promise.all(
614
+ listed.map(async (sibling) => ({
615
+ id: sibling.id,
616
+ label: sibling.label,
617
+ role: sibling.role,
618
+ connected: sibling.connected,
619
+ agents: sibling.agents,
620
+ confirmed: confirmed(sibling),
621
+ fingerprint: sibling.publicKey
622
+ ? await fingerprint(sibling.publicKey)
623
+ : null,
624
+ }))
625
+ ),
626
+ };
627
+ };
628
+
629
+ const status = () => ({
630
+ id: machine.id,
631
+ label: machine.label,
632
+ role: machine.role ?? null,
633
+ ...(isHome()
634
+ ? {}
635
+ : {
636
+ home: homeListed()
637
+ ? {
638
+ label: homeListed().label,
639
+ connected: homeListed().connected,
640
+ confirmed: Boolean(pinnedHome()),
641
+ }
642
+ : null,
643
+ waiting: outbox().length,
644
+ }),
645
+ });
646
+
647
+ /** The person's computers that have this agent, this one first: what its card says. Only confirmed ones. */
648
+ const computersWith = (agent) => [
649
+ ...(agents.includes(agent)
650
+ ? [{ id: machine.id, label: machine.label, online: true, here: true }]
651
+ : []),
652
+ ...siblings
653
+ .filter((sibling) => sibling.agents.includes(agent) && confirmed(sibling))
654
+ .map((sibling) => ({
655
+ id: sibling.id,
656
+ label: sibling.label,
657
+ online: sibling.connected,
658
+ here: false,
659
+ })),
660
+ ];
661
+
662
+ /**
663
+ * For the coordinator: the person's computers with this agent, each with whether it is online and has the thread's
664
+ * repository. Undefined while the agent is on this computer alone.
665
+ */
666
+ const computersFor = (agent, workspace) => {
667
+ const computers = computersWith(agent);
668
+ if (!computers.some((computer) => !computer.here)) return undefined;
669
+ const repository = workspace ? repositoryOf(workspace) : null;
670
+ return computers.map(({ id, label, online, here }) => ({
671
+ label,
672
+ online,
673
+ ...(repository
674
+ ? {
675
+ thread_repository: here
676
+ ? true
677
+ : namesOf(infos.get(id)?.folders ?? []).includes(repository),
678
+ }
679
+ : {}),
680
+ }));
681
+ };
682
+
683
+ /** On home: what a worker said it has (its folders and their repositories), sealed, so work can go to it. */
684
+ const learn = (id, info) => {
685
+ infos.set(String(id), { folders: info.folders ?? [] });
686
+ };
687
+ const namesOf = (list) => [
688
+ ...new Set(list.map((folder) => folder.repository).filter(Boolean)),
689
+ ];
690
+
691
+ /**
692
+ * On home: another computer with this agent and a checkout of the thread's repository, and that folder, for a thread
693
+ * turn this computer cannot take itself. Null when there is none (the turn waits for the agent here, as before).
694
+ */
695
+ const placeElsewhere = (agent, workspace) => {
696
+ const repository = isHome() && workspace ? repositoryOf(workspace) : null;
697
+ if (!repository) return null;
698
+ for (const sibling of siblings) {
699
+ if (!sibling.agents.includes(agent) || !store.ownMachine(sibling.id))
700
+ continue;
701
+ const folder = infos
702
+ .get(sibling.id)
703
+ ?.folders.find((each) => each.repository === repository)?.path;
704
+ if (folder) return { machine: sibling.id, folder };
705
+ }
706
+ return null;
707
+ };
708
+
709
+ /** The computers the board may name: this one and every other the person has, with their agents and repositories. */
710
+ const all = () => [
711
+ {
712
+ id: machine.id,
713
+ label: machine.label,
714
+ role: machine.role ?? "home",
715
+ agents,
716
+ repositories: namesOf(folders()),
717
+ },
718
+ ...siblings.map((sibling) => ({
719
+ ...sibling,
720
+ repositories: namesOf(infos.get(sibling.id)?.folders ?? []),
721
+ })),
722
+ ];
723
+
724
+ return {
725
+ hello,
726
+ adopt,
727
+ introduce,
728
+ rename,
729
+ makeHome,
730
+ confirm,
731
+ forwards,
732
+ callHome,
733
+ relay,
734
+ noticeTo,
735
+ list,
736
+ status,
737
+ all,
738
+ learn,
739
+ placeElsewhere,
740
+ computersWith,
741
+ computersFor,
742
+ labelOf,
743
+ find: (named) => findMachine(all(), named),
744
+ isHome,
745
+ self: () => machine.id,
746
+ siblings: () => siblings,
747
+ };
748
+ }