tryharness 0.7.82 → 0.7.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/README.md +21 -19
  2. package/assets/dsh-plugin.mjs +75 -4
  3. package/assets/herdr-mod/harness/main.js +367 -0
  4. package/assets/herdr-mod/harness/mod.json +6 -0
  5. package/assets/opencode-plugin.js +87 -22
  6. package/assets/pi-extension.ts +81 -2
  7. package/cli.mjs +544 -208
  8. package/lib/adapters.mjs +62 -27
  9. package/lib/agentBinaries.mjs +6 -8
  10. package/lib/agentClaims.mjs +168 -0
  11. package/lib/agentReadTools.json +415 -0
  12. package/lib/agentSignIn.mjs +17 -18
  13. package/lib/agentWiring.mjs +114 -0
  14. package/lib/archetypes.js +10 -11
  15. package/lib/attention.mjs +100 -0
  16. package/lib/audit.mjs +1 -1
  17. package/lib/backupSetup.mjs +6 -28
  18. package/lib/bankrApprovals.mjs +86 -0
  19. package/lib/boardAccess.mjs +40 -66
  20. package/lib/boardBackup.mjs +86 -85
  21. package/lib/boardCommands.mjs +28 -0
  22. package/lib/boardFileCommands.mjs +29 -36
  23. package/lib/boardFiles.mjs +83 -15
  24. package/lib/boardMirror.mjs +78 -11
  25. package/lib/boardProtocol.json +193 -123
  26. package/lib/boardThreads.mjs +19 -37
  27. package/lib/boardTools.mjs +22 -15
  28. package/lib/boardWatches.mjs +43 -15
  29. package/lib/bridge.mjs +7 -3
  30. package/lib/browserAgentTools.mjs +59 -0
  31. package/lib/browserWake.mjs +0 -6
  32. package/lib/cards.mjs +57 -2
  33. package/lib/circling.mjs +189 -0
  34. package/lib/cleanup.mjs +234 -0
  35. package/lib/cloudBoot.mjs +21 -4
  36. package/lib/cloudSave.mjs +46 -5
  37. package/lib/compaction.mjs +8 -1
  38. package/lib/completion.mjs +358 -0
  39. package/lib/computerDevices.mjs +853 -0
  40. package/lib/connectionStatus.mjs +34 -0
  41. package/lib/connectors.mjs +139 -1
  42. package/lib/coordinator.mjs +108 -14
  43. package/lib/coreModels.mjs +36 -12
  44. package/lib/daemon.mjs +2435 -333
  45. package/lib/daemonLock.mjs +103 -0
  46. package/lib/deviceDoor.mjs +308 -0
  47. package/lib/deviceIdentity.mjs +114 -0
  48. package/lib/deviceList.mjs +172 -0
  49. package/lib/deviceSeal.mjs +74 -0
  50. package/lib/dispatcher.mjs +497 -26
  51. package/lib/dispatches.mjs +3 -3
  52. package/lib/environment.mjs +2 -1
  53. package/lib/environments.mjs +67 -41
  54. package/lib/events.mjs +318 -0
  55. package/lib/facts.mjs +170 -0
  56. package/lib/fileSource.mjs +540 -0
  57. package/lib/files.mjs +47 -2
  58. package/lib/gitHost.mjs +39 -1
  59. package/lib/goalCommands.mjs +12 -80
  60. package/lib/handover.mjs +21 -16
  61. package/lib/harnessOffers.mjs +140 -15
  62. package/lib/herdr.mjs +100 -15
  63. package/lib/herdrAppCall.mjs +19 -0
  64. package/lib/herdrCore.mjs +59 -0
  65. package/lib/herdrRuns.mjs +1126 -0
  66. package/lib/hookDialects.mjs +235 -50
  67. package/lib/identityLink.mjs +81 -0
  68. package/lib/inference.mjs +31 -2
  69. package/lib/jamAccess.mjs +82 -0
  70. package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
  71. package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
  72. package/lib/jamKey.mjs +274 -0
  73. package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
  74. package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
  75. package/lib/jamStore.mjs +973 -0
  76. package/lib/jamUpgrade.mjs +112 -0
  77. package/lib/jams.mjs +3079 -0
  78. package/lib/kanban.mjs +13 -7
  79. package/lib/landed.mjs +5 -1
  80. package/lib/library.mjs +41 -22
  81. package/lib/limits.mjs +91 -0
  82. package/lib/lineDiff.mjs +97 -0
  83. package/lib/lineup.mjs +18 -13
  84. package/lib/link.mjs +584 -0
  85. package/lib/localStack.mjs +75 -16
  86. package/lib/localmodels.mjs +58 -78
  87. package/lib/loopBackstop.mjs +2 -1
  88. package/lib/machine.mjs +544 -0
  89. package/lib/machineLink.mjs +446 -0
  90. package/lib/machineRoutes.mjs +68 -19
  91. package/lib/machineRuns.mjs +85 -4
  92. package/lib/machineSeal.mjs +6 -31
  93. package/lib/manager.mjs +134 -12
  94. package/lib/mcp-stdio.mjs +492 -215
  95. package/lib/mcpRelay.mjs +34 -35
  96. package/lib/members.json +2 -2
  97. package/lib/modelRoute.mjs +162 -0
  98. package/lib/nativeHost.mjs +81 -90
  99. package/lib/nativeSenses.mjs +258 -0
  100. package/lib/nerves.mjs +523 -0
  101. package/lib/network.mjs +117 -278
  102. package/lib/networkPlaces.mjs +578 -0
  103. package/lib/nextStep.mjs +95 -0
  104. package/lib/notify.mjs +2 -2
  105. package/lib/nudge.mjs +116 -10
  106. package/lib/onboard.mjs +6 -6
  107. package/lib/originals.mjs +216 -0
  108. package/lib/outsideEvents.mjs +383 -0
  109. package/lib/outsideRuns.mjs +230 -0
  110. package/lib/ownMachines.mjs +674 -256
  111. package/lib/pain.mjs +215 -0
  112. package/lib/pairing.mjs +91 -11
  113. package/lib/paths.mjs +42 -3
  114. package/lib/peerProcess.mjs +21 -7
  115. package/lib/peopleLink.mjs +268 -0
  116. package/lib/personNotices.mjs +3 -2
  117. package/lib/phones.mjs +252 -542
  118. package/lib/placeCards.mjs +282 -0
  119. package/lib/placeChecks.mjs +95 -0
  120. package/lib/placeCommands.mjs +8 -17
  121. package/lib/placeRequests.mjs +152 -0
  122. package/lib/placeStore.mjs +295 -0
  123. package/lib/placeTool.d.ts +12 -0
  124. package/lib/placeTool.js +40 -0
  125. package/lib/places.mjs +63 -14
  126. package/lib/plans.mjs +53 -8
  127. package/lib/presence.mjs +270 -0
  128. package/lib/privateNetwork.d.ts +2 -0
  129. package/lib/privateNetwork.js +93 -0
  130. package/lib/proposals.mjs +300 -0
  131. package/lib/publicFetch.d.ts +32 -0
  132. package/lib/publicFetch.js +248 -0
  133. package/lib/reach.mjs +128 -0
  134. package/lib/rebuildable.mjs +72 -0
  135. package/lib/recall.mjs +216 -0
  136. package/lib/record.mjs +13 -0
  137. package/lib/reflexes.mjs +392 -0
  138. package/lib/relayLimits.mjs +31 -2
  139. package/lib/releaseNotice.mjs +198 -0
  140. package/lib/removeHarness.mjs +15 -4
  141. package/lib/repoLinks.mjs +204 -35
  142. package/lib/runAuthority.mjs +102 -39
  143. package/lib/runBrief.mjs +93 -40
  144. package/lib/runRequests.mjs +52 -14
  145. package/lib/runUsage.mjs +31 -0
  146. package/lib/runWorker.mjs +74 -25
  147. package/lib/runner.mjs +289 -45
  148. package/lib/runtime-install.mjs +37 -8
  149. package/lib/schedules.mjs +171 -47
  150. package/lib/screenWatches.mjs +221 -0
  151. package/lib/sealed.mjs +12 -30
  152. package/lib/sealedThreads.mjs +198 -392
  153. package/lib/secretStore.mjs +178 -0
  154. package/lib/secrets.mjs +11 -0
  155. package/lib/seen.mjs +3 -9
  156. package/lib/selfUpdate.mjs +51 -15
  157. package/lib/senseCall.mjs +1514 -0
  158. package/lib/senseHook.mjs +114 -0
  159. package/lib/senseTools.mjs +1298 -0
  160. package/lib/sessionBriefs.mjs +87 -0
  161. package/lib/sessionControl.mjs +63 -13
  162. package/lib/sessionFiles.mjs +85 -0
  163. package/lib/setupChoices.mjs +12 -3
  164. package/lib/setupMode.mjs +70 -25
  165. package/lib/sharedKeys.mjs +166 -0
  166. package/lib/sleep.mjs +396 -0
  167. package/lib/sources.mjs +306 -0
  168. package/lib/speech.mjs +166 -411
  169. package/lib/spoken.mjs +210 -0
  170. package/lib/steerHook.mjs +3 -1
  171. package/lib/steerQueue.mjs +40 -11
  172. package/lib/store.mjs +323 -130
  173. package/lib/stuck.mjs +85 -7
  174. package/lib/swarm.mjs +157 -49
  175. package/lib/swarmDevices.mjs +25 -85
  176. package/lib/swarmMemory.mjs +93 -9
  177. package/lib/t3.mjs +73 -3
  178. package/lib/taskCommands.mjs +51 -60
  179. package/lib/taskRooms.mjs +30 -4
  180. package/lib/taskRules.json +29 -0
  181. package/lib/taskRules.mjs +21 -0
  182. package/lib/taskRuns.mjs +74 -11
  183. package/lib/team.mjs +2 -1
  184. package/lib/threadActions.mjs +37 -9
  185. package/lib/threadAuthority.mjs +4 -4
  186. package/lib/threadBriefs.mjs +173 -43
  187. package/lib/threadNotes.mjs +320 -0
  188. package/lib/threadRecord.mjs +491 -0
  189. package/lib/threadRuns.mjs +216 -108
  190. package/lib/threadView.mjs +27 -30
  191. package/lib/threadWatches.mjs +1962 -0
  192. package/lib/timeSense.mjs +839 -0
  193. package/lib/tripwires.mjs +454 -0
  194. package/lib/ui.mjs +1 -1
  195. package/lib/vault.mjs +560 -45
  196. package/lib/vaultCommands.mjs +5 -3
  197. package/lib/vaultPeers.mjs +165 -0
  198. package/lib/vaultTools.d.ts +4 -1
  199. package/lib/vaultTools.js +22 -1
  200. package/lib/verdicts.mjs +12 -26
  201. package/lib/versions.mjs +117 -0
  202. package/lib/waitTool.mjs +278 -0
  203. package/lib/wakePicture.mjs +268 -0
  204. package/lib/wakeQueue.mjs +108 -0
  205. package/lib/watchResponses.mjs +533 -0
  206. package/lib/watches.mjs +290 -145
  207. package/lib/windowAsks.mjs +80 -17
  208. package/lib/worktrees.mjs +159 -9
  209. package/npm-shrinkwrap.json +138 -631
  210. package/package.json +7 -6
  211. package/release.json +212 -130
  212. package/lib/callSessions.mjs +0 -51
  213. package/lib/directLink.mjs +0 -349
  214. package/lib/peopleBoard.mjs +0 -131
  215. package/lib/projects.mjs +0 -2917
  216. package/lib/roomChannels.mjs +0 -667
package/lib/nerves.mjs ADDED
@@ -0,0 +1,523 @@
1
+ // The nerves between the person's computers (docs/senses-plan.md S6): what happened on one computer that another of the
2
+ // person's computers asked for reaches it, in order, once. Facts already travel with the board copy (boardMirror.mjs);
3
+ // happenings travel here.
4
+ //
5
+ // What crosses: pain (the computer's levels, a limit's), tripwires and reflexes, the person's presence, what touches a
6
+ // thread (its runs, its watches, its folder's files and repository, work in it that got stuck), and a change to the
7
+ // original of a file another computer's agent read through Harness, once that computer asked for it. Nothing else
8
+ // leaves its computer (spend and context, rule 7). Each computer sends its own happenings and, on home, what its other
9
+ // computers sent, to each computer but the one it happened on: workers reach each other through home.
10
+ //
11
+ // How: each computer's stream to another is its own log in order, numbered by the log, filtered by what the other wants.
12
+ // A message says the number of the last happening the stream sent before it; the other side takes it only when that is
13
+ // no later than what it already has, ignores what it already has, and answers with the last number it holds. Anything
14
+ // lost is sent again from there. Pain and tripwires go at once with what waits before them; the rest waits up to five
15
+ // seconds, or until a hundred are waiting (owner, November 14). A cause always goes before what it caused: the stream is
16
+ // in the log's order, which is the order of causes.
17
+ //
18
+ // The road: the channel between the two computers. With none open, home's messages for a worker wait in Harness's
19
+ // mailbox (sealed, kept while the worker is away, delivered in order when it is back); a worker's for home stay in its
20
+ // own log and go when home is back, since Harness keeps notices only for workers. A link that breaks is said on both
21
+ // ends, in the log and in `tryharness machines`, and each end keeps working (open item 3: a worker alone runs its
22
+ // reflexes and wakes only its own agents on work already started, watchResponses.mjs).
23
+
24
+ export const NERVE_KIND = "nerve";
25
+
26
+ // The rest waits this long, or until this many are waiting (owner, November 14: "5 seconds").
27
+ const BATCH_MS = 5_000;
28
+ const MOST = 100;
29
+ // One look for what to send reads at most this many happenings; the rest is looked at with the next.
30
+ const MOST_SCANNED = 2_000;
31
+ // What another computer has not confirmed is sent again this often while there is a road.
32
+ const RETRY_MS = 30_000;
33
+ // A refusal says where the other side is; sent again from there at most this many times in a row.
34
+ const RESENDS = 3;
35
+ // Harness's mailbox keeps a notice of at most 16,000 characters, sealed (src/server/bridge/machines.ts), and 200 for one
36
+ // computer: a message for it is cut to fit with room for the seal, and the nerves take at most a quarter of the 200, so
37
+ // the mailbox keeps room for home's other notices. What does not fit waits in the log for the channel.
38
+ const MAIL_CHARS = 9_000;
39
+ const MOST_MAILED = 50;
40
+
41
+ // Pain and tripwires: sent at once.
42
+ const URGENT = (happening) =>
43
+ (happening.kind === "level" &&
44
+ (happening.source === "machine" || happening.source === "limits")) ||
45
+ (happening.source === "senses" &&
46
+ (happening.kind === "tripwire" ||
47
+ happening.kind === "expectation broken")) ||
48
+ happening.source === "reflex" ||
49
+ (happening.source === "files" && happening.kind === "original changed");
50
+
51
+ const ORIGINAL = /^file:(.+)$/;
52
+
53
+ const parsed = (text, fallback) => {
54
+ try {
55
+ return text ? JSON.parse(text) : fallback;
56
+ } catch {
57
+ return fallback;
58
+ }
59
+ };
60
+
61
+ /** A length of time in words: "45 s", "12 min", "1.5 h". */
62
+ const spanOf = (ms) =>
63
+ ms < 60_000
64
+ ? `${Math.max(1, Math.round(ms / 1000))} s`
65
+ : ms < 3_600_000
66
+ ? `${Math.round(ms / 60_000)} min`
67
+ : `${Number((ms / 3_600_000).toFixed(1))} h`;
68
+
69
+ /**
70
+ * The nerves of this computer. `peers()` lists the person's computers this one keeps a nerve with (`{ id, label }`);
71
+ * `linked(id)` whether the channel to one is open now; `send(id, message)` one message over that channel, its answer or
72
+ * null; `mail(id, message)` one message to Harness's mailbox, true once Harness took it (home to a worker only; null
73
+ * where there is none). `touches(happening)` names the thread a happening of this computer touches, or null.
74
+ * `onArrival(from, happening)` hears each happening as it arrives and is kept; `onWant(from, files)` hears which
75
+ * attached files' originals another computer asked to hear about.
76
+ */
77
+ export function createNerves({
78
+ events,
79
+ store,
80
+ machineId,
81
+ peers = () => [],
82
+ linked = () => false,
83
+ send = async () => null,
84
+ mail = null,
85
+ touches = () => null,
86
+ onArrival = () => {},
87
+ onWant = () => {},
88
+ batchMs = BATCH_MS,
89
+ most = MOST,
90
+ log = () => {},
91
+ now = () => Date.now(),
92
+ }) {
93
+ const meta = (key, value) =>
94
+ value === undefined ? store.meta(key) : store.meta(key, value);
95
+ const numberAt = (key) => Number(meta(key) || 0) || 0;
96
+
97
+ // What another computer confirmed it holds of this one's stream.
98
+ const ackedOf = (peer) => numberAt(`nerve-acked:${peer}`);
99
+ const setAcked = (peer, seq) => meta(`nerve-acked:${peer}`, String(seq));
100
+ // The last happening put in Harness's mailbox for it, not confirmed yet.
101
+ const mailedOf = (peer) => numberAt(`nerve-mailed:${peer}`);
102
+ const setMailed = (peer, seq) => meta(`nerve-mailed:${peer}`, String(seq));
103
+ // The last of another computer's stream this one holds.
104
+ const gotOf = (peer) => numberAt(`nerve-got:${peer}`);
105
+ // Which attached files' originals another computer asked to hear about, and which this one asked of it.
106
+ const wantOf = (peer) => parsed(meta(`nerve-want:${peer}`), { files: [] });
107
+ const askedOf = (peer) => parsed(meta(`nerve-asked:${peer}`), { files: [] });
108
+
109
+ const labelOf = (peer) =>
110
+ peers().find((each) => each.id === peer)?.label || "another computer";
111
+ const newest = () => events.read({ limit: 1 })[0]?.seq ?? 0;
112
+
113
+ // A stream new to a computer starts at the log's end when it is first known (a computer joining is not sent thirty
114
+ // days of history), or just before the first happening it would carry.
115
+ const begin = (peer, before = newest()) => {
116
+ if (meta(`nerve-acked:${peer}`)) return;
117
+ setAcked(peer, before);
118
+ meta(`nerve-start:${peer}`, String(before));
119
+ };
120
+
121
+ /** Whether `peer` wants the happening: never one that happened there, and only what is listed above. */
122
+ const wanted = (peer, happening) => {
123
+ if (happening.machine === peer) return false;
124
+ if (happening.source === "nerve") return false;
125
+ if (URGENT(happening) && happening.source !== "files") return true;
126
+ if (happening.source === "person") return true;
127
+ const original = ORIGINAL.exec(String(happening.subject ?? ""));
128
+ if (original && happening.source === "files")
129
+ return wantOf(peer).files.includes(original[1]);
130
+ if (happening.machine) return Boolean(happening.data?.thread);
131
+ return Boolean(touches(happening));
132
+ };
133
+
134
+ // A happening as it crosses: where it happened and its number there, its cause named the same way, and the thread it
135
+ // touches as this computer knows it (only the computer it happened on knows its folders).
136
+ const wireOf = (happening) => {
137
+ const before = happening.cause ? events.get(happening.cause) : null;
138
+ const thread = happening.machine ? null : touches(happening);
139
+ const data =
140
+ thread && happening.data?.thread == null
141
+ ? { ...(happening.data ?? {}), thread }
142
+ : happening.data;
143
+ return {
144
+ seq: happening.seq,
145
+ machine: happening.machine ?? machineId,
146
+ origin: happening.origin ?? happening.seq,
147
+ at: happening.at,
148
+ source: happening.source,
149
+ kind: happening.kind,
150
+ subject: happening.subject,
151
+ text: happening.text,
152
+ ...(happening.ms === undefined ? {} : { ms: happening.ms }),
153
+ data: data ?? null,
154
+ cause: before
155
+ ? {
156
+ machine: before.machine ?? machineId,
157
+ origin: before.origin ?? before.seq,
158
+ }
159
+ : null,
160
+ hops: happening.hops,
161
+ trust: happening.trust,
162
+ };
163
+ };
164
+
165
+ // Where a look for what to send may start without reading again what it read and found nothing in.
166
+ const scanned = new Map();
167
+ /**
168
+ * What waits for `peer` after `after`: up to `most`, in the log's order, pain and tripwires first among them; with
169
+ * `chars`, as many as fit in that many characters (one alone that does not fit goes without its data).
170
+ */
171
+ const waiting = (peer, after, { chars = Infinity } = {}) => {
172
+ const items = [];
173
+ let at = Math.max(
174
+ after,
175
+ scanned.get(peer)?.after === after ? scanned.get(peer).at : after
176
+ );
177
+ for (let read = 0; read < MOST_SCANNED && items.length < most;) {
178
+ const page = events.read({ after: at, limit: 100 });
179
+ if (!page.length) break;
180
+ for (const happening of page) {
181
+ at = happening.seq;
182
+ if (wanted(peer, happening)) items.push(happening);
183
+ if (items.length >= most) break;
184
+ }
185
+ read += page.length;
186
+ if (page.length < 100) break;
187
+ }
188
+ if (!items.length) scanned.set(peer, { after, at });
189
+ // In the log's order, then pain and tripwires to the front unless a cause of theirs is in the message (it goes
190
+ // first, so what it caused never arrives before it).
191
+ const inMessage = new Set(items.map((each) => each.seq));
192
+ const first = items.filter(
193
+ (each) => URGENT(each) && !(each.cause && inMessage.has(each.cause))
194
+ );
195
+ const rest = items.filter((each) => !first.includes(each));
196
+ if (chars === Infinity)
197
+ return {
198
+ items: [...first, ...rest].map(wireOf),
199
+ through: items.length
200
+ ? Math.max(...items.map((each) => each.seq))
201
+ : after,
202
+ };
203
+ // Fitted in the log's order, so what is left out is all later than what goes.
204
+ const fitted = new Map();
205
+ let size = 0;
206
+ for (const happening of items) {
207
+ let wire = wireOf(happening);
208
+ let length = JSON.stringify(wire).length;
209
+ if (!fitted.size && length > chars) {
210
+ wire = { ...wire, data: { cut: true } };
211
+ length = JSON.stringify(wire).length;
212
+ }
213
+ if (fitted.size && size + length > chars) break;
214
+ fitted.set(wire.seq, wire);
215
+ size += length;
216
+ }
217
+ return {
218
+ items: [...first, ...rest]
219
+ .filter((each) => fitted.has(each.seq))
220
+ .map((each) => fitted.get(each.seq)),
221
+ through: fitted.size ? Math.max(...fitted.keys()) : after,
222
+ };
223
+ };
224
+
225
+ const messageOf = (peer, after, items) => {
226
+ const asked = askedOf(peer);
227
+ const start = numberAt(`nerve-start:${peer}`);
228
+ return {
229
+ after,
230
+ // Where this computer's stream to the peer began: one that holds nothing yet takes only a message from there,
231
+ // so a later message (Harness's mailbox gives them in no fixed order) never skips an earlier one.
232
+ ...(start ? { start } : {}),
233
+ items,
234
+ ...(asked.files.length ? { want: asked } : {}),
235
+ };
236
+ };
237
+
238
+ // ---- sending ----
239
+
240
+ const flushing = new Set();
241
+ const again = new Set();
242
+ const timers = new Map();
243
+
244
+ // One message over the open channel: "more" when there is more to send, "gone" when the channel went, "done".
245
+ const overChannel = async (peer, state) => {
246
+ const after = ackedOf(peer);
247
+ const { items, through } = waiting(peer, after);
248
+ if (!items.length && !state.wantToSay) return "done";
249
+ const answer = await send(peer, {
250
+ kind: NERVE_KIND,
251
+ body: messageOf(peer, after, items),
252
+ }).catch(() => null);
253
+ // No answer on a channel still open: sent again with the next retry.
254
+ if (!answer) return linked(peer) ? "done" : "gone";
255
+ if (answer.ok === true) {
256
+ state.wantToSay = false;
257
+ const got = Number(answer.got);
258
+ if (!Number.isSafeInteger(got)) return "done";
259
+ setAcked(peer, got);
260
+ if (mailedOf(peer) && got >= mailedOf(peer)) {
261
+ setMailed(peer, 0);
262
+ meta(`nerve-mail-count:${peer}`, "0");
263
+ }
264
+ return items.length && got >= through ? "more" : "done";
265
+ }
266
+ // Refused: the other side says what it holds, and the stream is sent again from there.
267
+ const holds = Number(answer.got);
268
+ if (!Number.isSafeInteger(holds) || ++state.resends > RESENDS) {
269
+ log(
270
+ `nerves: ${labelOf(peer)} refused what was sent: ${answer.error ?? "no reason"}`
271
+ );
272
+ return "done";
273
+ }
274
+ setAcked(peer, holds);
275
+ setMailed(peer, 0);
276
+ meta(`nerve-mail-count:${peer}`, "0");
277
+ scanned.delete(peer);
278
+ return "more";
279
+ };
280
+
281
+ // Nothing open: home's messages for a worker wait in Harness's mailbox, each after the last one put there.
282
+ const mailCount = (peer) => numberAt(`nerve-mail-count:${peer}`);
283
+ const intoMailbox = async (peer) => {
284
+ if (!mail || mailCount(peer) >= MOST_MAILED) return "done";
285
+ const after = Math.max(ackedOf(peer), mailedOf(peer));
286
+ const { items, through } = waiting(peer, after, { chars: MAIL_CHARS });
287
+ if (!items.length) return "done";
288
+ const taken = await mail(peer, {
289
+ kind: NERVE_KIND,
290
+ body: messageOf(peer, after, items),
291
+ }).catch(() => null);
292
+ if (taken !== true) return "done";
293
+ log(
294
+ `nerves: ${items.length} for ${labelOf(peer)} wait in Harness's mailbox (after ${after}, through ${through})`
295
+ );
296
+ setMailed(peer, through);
297
+ meta(`nerve-mail-count:${peer}`, String(mailCount(peer) + 1));
298
+ return "more";
299
+ };
300
+
301
+ const flush = async (peer) => {
302
+ clearTimeout(timers.get(peer));
303
+ timers.delete(peer);
304
+ if (flushing.has(peer)) {
305
+ again.add(peer);
306
+ return;
307
+ }
308
+ flushing.add(peer);
309
+ again.delete(peer);
310
+ try {
311
+ begin(peer);
312
+ const state = {
313
+ resends: 0,
314
+ wantToSay: askedOf(peer).files.length > 0,
315
+ };
316
+ for (;;) {
317
+ const step = linked(peer)
318
+ ? await overChannel(peer, state)
319
+ : await intoMailbox(peer);
320
+ if (step === "done") break;
321
+ }
322
+ } catch (error) {
323
+ log(`nerves: ${labelOf(peer)}: ${error.message}`);
324
+ } finally {
325
+ flushing.delete(peer);
326
+ if (again.has(peer)) void flush(peer);
327
+ }
328
+ };
329
+
330
+ const soon = (peer) => {
331
+ if (timers.has(peer)) return;
332
+ const timer = setTimeout(() => void flush(peer), batchMs);
333
+ timer.unref?.();
334
+ timers.set(peer, timer);
335
+ };
336
+
337
+ // Each happening kept here, this computer's own or one that arrived: at once to whoever wants it when it hurts, else
338
+ // with the next batch.
339
+ const counted = new Map();
340
+ const heard = (happening) => {
341
+ for (const { id: peer } of peers()) {
342
+ if (!wanted(peer, happening)) continue;
343
+ begin(peer, happening.seq - 1);
344
+ const count = (counted.get(peer) ?? 0) + 1;
345
+ if (URGENT(happening) || count >= most) {
346
+ counted.set(peer, 0);
347
+ void flush(peer);
348
+ } else {
349
+ counted.set(peer, count);
350
+ soon(peer);
351
+ }
352
+ }
353
+ };
354
+
355
+ // ---- the link breaking and coming back ----
356
+
357
+ const linkedNow = new Map();
358
+ const cutOf = (peer) => meta(`nerve-cut:${peer}`) || null;
359
+ const linkChanged = (peer) => {
360
+ const known = peers().find((each) => each.id === peer);
361
+ if (!known) return;
362
+ const was = linkedNow.get(peer) ?? false;
363
+ const is = linked(peer);
364
+ linkedNow.set(peer, is);
365
+ if (was === is) return;
366
+ if (!is) {
367
+ const since = new Date(now()).toISOString();
368
+ meta(`nerve-cut:${peer}`, since);
369
+ events.append({
370
+ source: "nerve",
371
+ kind: "cut",
372
+ subject: `machine:${peer}`,
373
+ text: `the link with ${known.label || "another computer"} broke; each keeps working on its own`,
374
+ data: { machine: peer },
375
+ });
376
+ return;
377
+ }
378
+ const since = cutOf(peer);
379
+ if (since) {
380
+ meta(`nerve-cut:${peer}`, "");
381
+ events.append({
382
+ source: "nerve",
383
+ kind: "back",
384
+ subject: `machine:${peer}`,
385
+ text: `the link with ${known.label || "another computer"} is back after ${spanOf(now() - Date.parse(since))}`,
386
+ data: { machine: peer, ms: now() - Date.parse(since) },
387
+ });
388
+ }
389
+ void flush(peer);
390
+ };
391
+
392
+ // ---- receiving ----
393
+
394
+ /**
395
+ * A message from another of the person's computers, over the channel or out of the mailbox: taken when it follows
396
+ * what this computer holds of that stream. What this computer holds is the answer either way.
397
+ */
398
+ const receive = (from, body) => {
399
+ const peer = String(from || "");
400
+ if (!peers().some((each) => each.id === peer))
401
+ return { ok: false, error: "not one of the person's computers here" };
402
+ if (Array.isArray(body?.want?.files)) {
403
+ const files = body.want.files.map(String).slice(0, 1_000);
404
+ const before = wantOf(peer).files;
405
+ meta(`nerve-want:${peer}`, JSON.stringify({ files }));
406
+ if (JSON.stringify(before) !== JSON.stringify(files)) onWant(peer, files);
407
+ }
408
+ const got = gotOf(peer);
409
+ const after = Number(body?.after);
410
+ if (!Number.isSafeInteger(after) || after < 0)
411
+ return { ok: false, got, error: "a message says what it follows" };
412
+ const start = Number(body?.start);
413
+ // Holding nothing yet, a message from after the stream's start waits for the ones before it; the sender is told
414
+ // the start, and sends from there.
415
+ if (
416
+ got === 0 &&
417
+ Number.isSafeInteger(start) &&
418
+ start > 0 &&
419
+ after > start
420
+ ) {
421
+ log(
422
+ `nerves: from ${labelOf(peer)}, a message after ${after} waits for what came before it (the stream began after ${start})`
423
+ );
424
+ return {
425
+ ok: false,
426
+ got: start,
427
+ error: "something before it has not arrived",
428
+ };
429
+ }
430
+ if (after > got && got > 0) {
431
+ log(
432
+ `nerves: from ${labelOf(peer)}, a message after ${after} waits for what came before it (this computer holds ${got})`
433
+ );
434
+ return { ok: false, got, error: "something before it has not arrived" };
435
+ }
436
+ const items = (Array.isArray(body?.items) ? body.items : [])
437
+ .filter((item) => Number.isSafeInteger(Number(item?.seq)))
438
+ .sort((a, b) => Number(a.seq) - Number(b.seq));
439
+ let holds = Math.max(got, after);
440
+ for (const item of items) {
441
+ if (Number(item.seq) <= got) continue;
442
+ const cause =
443
+ item.cause?.machine === machineId
444
+ ? Number(item.cause.origin)
445
+ : item.cause;
446
+ const kept = events.receive({
447
+ machine:
448
+ item.machine && item.machine !== machineId ? item.machine : peer,
449
+ origin: item.origin ?? item.seq,
450
+ at: item.at,
451
+ source: item.source,
452
+ kind: item.kind,
453
+ subject: item.subject ?? null,
454
+ text: item.text ?? "",
455
+ ms: item.ms ?? null,
456
+ data: item.data ?? null,
457
+ cause,
458
+ hops: item.hops,
459
+ trust: item.trust,
460
+ });
461
+ holds = Number(item.seq);
462
+ if (kept)
463
+ try {
464
+ onArrival(peer, kept);
465
+ } catch (error) {
466
+ log(`nerves: an arrival from ${labelOf(peer)}: ${error.message}`);
467
+ }
468
+ }
469
+ meta(`nerve-got:${peer}`, String(holds));
470
+ return { ok: true, got: holds };
471
+ };
472
+
473
+ let stopFollowing = null;
474
+ let retry = null;
475
+
476
+ return {
477
+ start() {
478
+ for (const { id } of peers()) {
479
+ begin(id);
480
+ linkedNow.set(id, linked(id));
481
+ }
482
+ stopFollowing = events.follow(heard, { arrivals: true });
483
+ retry = setInterval(() => {
484
+ for (const { id } of peers()) {
485
+ begin(id);
486
+ void flush(id);
487
+ }
488
+ }, RETRY_MS);
489
+ retry.unref?.();
490
+ for (const { id } of peers()) void flush(id);
491
+ },
492
+ stop() {
493
+ stopFollowing?.();
494
+ clearInterval(retry);
495
+ for (const timer of timers.values()) clearTimeout(timer);
496
+ timers.clear();
497
+ },
498
+ receive,
499
+ linkChanged,
500
+ /** Sends what waits for `peer` now (tests, and a computer that just came back). */
501
+ flush,
502
+ /** Asks `peer` to say when the originals of these attached files change there (S6.5). */
503
+ want(peer, files) {
504
+ const asked = askedOf(peer).files;
505
+ const all = [...new Set([...asked, ...files.map(String)])];
506
+ if (all.length === asked.length) return;
507
+ meta(`nerve-asked:${peer}`, JSON.stringify({ files: all.slice(-1_000) }));
508
+ void flush(peer);
509
+ },
510
+ /** Each computer's nerve: whether it is linked, since when it is not, and what it has not confirmed. */
511
+ status() {
512
+ return peers().map(({ id, label }) => ({
513
+ id,
514
+ label,
515
+ linked: linked(id),
516
+ cutSince: cutOf(id),
517
+ acked: ackedOf(id),
518
+ got: gotOf(id),
519
+ mailed: mailedOf(id) || null,
520
+ }));
521
+ },
522
+ };
523
+ }