tryharness 0.7.83 → 0.7.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +21 -19
  2. package/assets/dsh-plugin.mjs +75 -4
  3. package/assets/herdr-mod/harness/main.js +367 -0
  4. package/assets/herdr-mod/harness/mod.json +6 -0
  5. package/assets/opencode-plugin.js +87 -22
  6. package/assets/pi-extension.ts +81 -2
  7. package/cli.mjs +544 -208
  8. package/lib/adapters.mjs +62 -27
  9. package/lib/agentBinaries.mjs +6 -8
  10. package/lib/agentClaims.mjs +168 -0
  11. package/lib/agentReadTools.json +415 -0
  12. package/lib/agentSignIn.mjs +17 -18
  13. package/lib/agentWiring.mjs +114 -0
  14. package/lib/archetypes.js +10 -11
  15. package/lib/attention.mjs +100 -0
  16. package/lib/audit.mjs +1 -1
  17. package/lib/backupSetup.mjs +6 -28
  18. package/lib/bankrApprovals.mjs +86 -0
  19. package/lib/boardAccess.mjs +40 -66
  20. package/lib/boardBackup.mjs +86 -85
  21. package/lib/boardCommands.mjs +28 -0
  22. package/lib/boardFileCommands.mjs +29 -36
  23. package/lib/boardFiles.mjs +83 -15
  24. package/lib/boardMirror.mjs +78 -11
  25. package/lib/boardProtocol.json +191 -123
  26. package/lib/boardThreads.mjs +19 -37
  27. package/lib/boardTools.mjs +22 -15
  28. package/lib/boardWatches.mjs +43 -15
  29. package/lib/bridge.mjs +7 -3
  30. package/lib/browserAgentTools.mjs +59 -0
  31. package/lib/browserWake.mjs +0 -6
  32. package/lib/cards.mjs +52 -0
  33. package/lib/circling.mjs +189 -0
  34. package/lib/cleanup.mjs +234 -0
  35. package/lib/cloudBoot.mjs +21 -4
  36. package/lib/cloudSave.mjs +46 -5
  37. package/lib/compaction.mjs +8 -1
  38. package/lib/completion.mjs +358 -0
  39. package/lib/computerDevices.mjs +853 -0
  40. package/lib/connectionStatus.mjs +34 -0
  41. package/lib/connectors.mjs +139 -1
  42. package/lib/coordinator.mjs +108 -14
  43. package/lib/coreModels.mjs +36 -12
  44. package/lib/daemon.mjs +2426 -338
  45. package/lib/daemonLock.mjs +103 -0
  46. package/lib/deviceDoor.mjs +308 -0
  47. package/lib/deviceIdentity.mjs +114 -0
  48. package/lib/deviceList.mjs +172 -0
  49. package/lib/deviceSeal.mjs +74 -0
  50. package/lib/dispatcher.mjs +497 -26
  51. package/lib/dispatches.mjs +3 -3
  52. package/lib/environment.mjs +2 -1
  53. package/lib/environments.mjs +67 -41
  54. package/lib/events.mjs +318 -0
  55. package/lib/facts.mjs +170 -0
  56. package/lib/fileSource.mjs +540 -0
  57. package/lib/files.mjs +47 -2
  58. package/lib/gitHost.mjs +39 -1
  59. package/lib/goalCommands.mjs +12 -80
  60. package/lib/handover.mjs +21 -16
  61. package/lib/harnessOffers.mjs +140 -15
  62. package/lib/herdr.mjs +100 -15
  63. package/lib/herdrAppCall.mjs +19 -0
  64. package/lib/herdrCore.mjs +59 -0
  65. package/lib/herdrRuns.mjs +1126 -0
  66. package/lib/hookDialects.mjs +235 -50
  67. package/lib/identityLink.mjs +81 -0
  68. package/lib/inference.mjs +31 -2
  69. package/lib/jamAccess.mjs +82 -0
  70. package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
  71. package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
  72. package/lib/jamKey.mjs +274 -0
  73. package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
  74. package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
  75. package/lib/jamStore.mjs +973 -0
  76. package/lib/jamUpgrade.mjs +112 -0
  77. package/lib/jams.mjs +3079 -0
  78. package/lib/kanban.mjs +13 -7
  79. package/lib/landed.mjs +5 -1
  80. package/lib/library.mjs +41 -22
  81. package/lib/limits.mjs +91 -0
  82. package/lib/lineDiff.mjs +97 -0
  83. package/lib/lineup.mjs +18 -13
  84. package/lib/link.mjs +584 -0
  85. package/lib/localStack.mjs +75 -16
  86. package/lib/localmodels.mjs +58 -78
  87. package/lib/loopBackstop.mjs +2 -1
  88. package/lib/machine.mjs +544 -0
  89. package/lib/machineLink.mjs +446 -0
  90. package/lib/machineRoutes.mjs +68 -19
  91. package/lib/machineRuns.mjs +85 -4
  92. package/lib/machineSeal.mjs +6 -31
  93. package/lib/manager.mjs +134 -12
  94. package/lib/mcp-stdio.mjs +492 -215
  95. package/lib/mcpRelay.mjs +34 -35
  96. package/lib/members.json +1 -1
  97. package/lib/modelRoute.mjs +162 -0
  98. package/lib/nativeHost.mjs +81 -90
  99. package/lib/nativeSenses.mjs +258 -0
  100. package/lib/nerves.mjs +523 -0
  101. package/lib/network.mjs +117 -278
  102. package/lib/networkPlaces.mjs +578 -0
  103. package/lib/nextStep.mjs +95 -0
  104. package/lib/notify.mjs +2 -2
  105. package/lib/nudge.mjs +116 -10
  106. package/lib/originals.mjs +216 -0
  107. package/lib/outsideEvents.mjs +383 -0
  108. package/lib/outsideRuns.mjs +230 -0
  109. package/lib/ownMachines.mjs +674 -256
  110. package/lib/pain.mjs +215 -0
  111. package/lib/pairing.mjs +91 -11
  112. package/lib/paths.mjs +42 -3
  113. package/lib/peerProcess.mjs +21 -7
  114. package/lib/peopleLink.mjs +268 -0
  115. package/lib/personNotices.mjs +3 -2
  116. package/lib/phones.mjs +252 -542
  117. package/lib/placeCards.mjs +282 -0
  118. package/lib/placeChecks.mjs +95 -0
  119. package/lib/placeCommands.mjs +8 -17
  120. package/lib/placeRequests.mjs +152 -0
  121. package/lib/placeStore.mjs +295 -0
  122. package/lib/placeTool.d.ts +12 -0
  123. package/lib/placeTool.js +40 -0
  124. package/lib/places.mjs +63 -14
  125. package/lib/plans.mjs +53 -8
  126. package/lib/presence.mjs +270 -0
  127. package/lib/privateNetwork.d.ts +2 -0
  128. package/lib/privateNetwork.js +93 -0
  129. package/lib/proposals.mjs +300 -0
  130. package/lib/publicFetch.d.ts +32 -0
  131. package/lib/publicFetch.js +248 -0
  132. package/lib/reach.mjs +128 -0
  133. package/lib/rebuildable.mjs +72 -0
  134. package/lib/recall.mjs +216 -0
  135. package/lib/record.mjs +13 -0
  136. package/lib/reflexes.mjs +392 -0
  137. package/lib/relayLimits.mjs +31 -2
  138. package/lib/releaseNotice.mjs +198 -0
  139. package/lib/removeHarness.mjs +15 -4
  140. package/lib/repoLinks.mjs +204 -35
  141. package/lib/runAuthority.mjs +102 -39
  142. package/lib/runBrief.mjs +93 -40
  143. package/lib/runRequests.mjs +52 -14
  144. package/lib/runUsage.mjs +31 -0
  145. package/lib/runWorker.mjs +74 -25
  146. package/lib/runner.mjs +289 -45
  147. package/lib/runtime-install.mjs +37 -8
  148. package/lib/schedules.mjs +171 -47
  149. package/lib/screenWatches.mjs +221 -0
  150. package/lib/sealed.mjs +12 -30
  151. package/lib/sealedThreads.mjs +198 -392
  152. package/lib/secretStore.mjs +178 -0
  153. package/lib/secrets.mjs +11 -0
  154. package/lib/seen.mjs +3 -9
  155. package/lib/selfUpdate.mjs +51 -15
  156. package/lib/senseCall.mjs +1514 -0
  157. package/lib/senseHook.mjs +114 -0
  158. package/lib/senseTools.mjs +1298 -0
  159. package/lib/sessionBriefs.mjs +87 -0
  160. package/lib/sessionControl.mjs +63 -13
  161. package/lib/sessionFiles.mjs +85 -0
  162. package/lib/setupChoices.mjs +12 -3
  163. package/lib/setupMode.mjs +70 -25
  164. package/lib/sharedKeys.mjs +166 -0
  165. package/lib/sleep.mjs +396 -0
  166. package/lib/sources.mjs +306 -0
  167. package/lib/speech.mjs +166 -411
  168. package/lib/spoken.mjs +210 -0
  169. package/lib/steerHook.mjs +3 -1
  170. package/lib/steerQueue.mjs +40 -11
  171. package/lib/store.mjs +323 -130
  172. package/lib/stuck.mjs +85 -7
  173. package/lib/swarm.mjs +157 -49
  174. package/lib/swarmDevices.mjs +25 -85
  175. package/lib/swarmMemory.mjs +93 -9
  176. package/lib/t3.mjs +73 -3
  177. package/lib/taskCommands.mjs +51 -60
  178. package/lib/taskRooms.mjs +30 -4
  179. package/lib/taskRules.json +29 -0
  180. package/lib/taskRules.mjs +21 -0
  181. package/lib/taskRuns.mjs +74 -11
  182. package/lib/team.mjs +2 -1
  183. package/lib/threadActions.mjs +37 -9
  184. package/lib/threadAuthority.mjs +4 -4
  185. package/lib/threadBriefs.mjs +173 -43
  186. package/lib/threadNotes.mjs +320 -0
  187. package/lib/threadRecord.mjs +491 -0
  188. package/lib/threadRuns.mjs +216 -108
  189. package/lib/threadView.mjs +27 -30
  190. package/lib/threadWatches.mjs +1962 -0
  191. package/lib/timeSense.mjs +839 -0
  192. package/lib/tripwires.mjs +454 -0
  193. package/lib/ui.mjs +1 -1
  194. package/lib/vault.mjs +560 -45
  195. package/lib/vaultCommands.mjs +5 -3
  196. package/lib/vaultPeers.mjs +165 -0
  197. package/lib/vaultTools.d.ts +4 -1
  198. package/lib/vaultTools.js +22 -1
  199. package/lib/verdicts.mjs +12 -26
  200. package/lib/versions.mjs +117 -0
  201. package/lib/waitTool.mjs +278 -0
  202. package/lib/wakePicture.mjs +268 -0
  203. package/lib/wakeQueue.mjs +108 -0
  204. package/lib/watchResponses.mjs +533 -0
  205. package/lib/watches.mjs +290 -145
  206. package/lib/windowAsks.mjs +80 -17
  207. package/lib/worktrees.mjs +159 -9
  208. package/npm-shrinkwrap.json +138 -631
  209. package/package.json +7 -6
  210. package/release.json +211 -129
  211. package/lib/callSessions.mjs +0 -51
  212. package/lib/directLink.mjs +0 -349
  213. package/lib/peopleBoard.mjs +0 -131
  214. package/lib/projects.mjs +0 -2917
  215. package/lib/roomChannels.mjs +0 -667
@@ -0,0 +1,270 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+
5
+ // The person and the repositories (docs/senses-plan.md S2.5, ledger row 4): what environment.mjs reads on demand, as
6
+ // sources that say when it changes. Its readers keep their calls.
7
+ //
8
+ // The person: whether they are at this computer and in a call, read once a minute as the presence check always was
9
+ // (each read starts the system's own commands, S0.3). Away after 20 minutes without input, back at the next input; in a
10
+ // call while a call app is in front. These are happenings in this computer's log, which never leaves it; the app in
11
+ // front is never written down, and nothing about the person becomes a fact other computers copy.
12
+ //
13
+ // A repository: its branch and its commits, read from git's own files as they change (HEAD, the branches' refs), so
14
+ // a switched branch or new commits are said at once, and what moved while Harness was off at the next start. A commit
15
+ // is named by its number and branch, never by its message, which is someone's words.
16
+
17
+ export const PERSON_LOOK_MS = 60_000;
18
+ export const AWAY_SECONDS = 20 * 60;
19
+ // A git operation writes several of its files in turn: they settle this long before the repository is read.
20
+ const GIT_SETTLE_MS = 1_000;
21
+
22
+ /** The person kind for sources.mjs: `{}`, read once a minute from environment.mjs. */
23
+ export function createPersonKind({ environment, now = () => Date.now() }) {
24
+ return {
25
+ describe: () =>
26
+ `reads whether the person is at this computer and in a call every ${PERSON_LOOK_MS / 1000} s`,
27
+ start(_, io) {
28
+ let stopped = false;
29
+ let timer = null;
30
+ const look = () => {
31
+ if (stopped) return;
32
+ const person = environment.person();
33
+ io.report({
34
+ at: now(),
35
+ idleSeconds: person.idleSeconds,
36
+ inCall: person.inCall,
37
+ app: person.app,
38
+ });
39
+ timer = setTimeout(look, PERSON_LOOK_MS);
40
+ timer.unref?.();
41
+ };
42
+ timer = setTimeout(look, 0);
43
+ timer.unref?.();
44
+ return {
45
+ stop() {
46
+ stopped = true;
47
+ clearTimeout(timer);
48
+ },
49
+ };
50
+ },
51
+ };
52
+ }
53
+
54
+ const minutes = (ms) => {
55
+ const total = Math.max(1, Math.round(ms / 60_000));
56
+ return total < 60
57
+ ? `${total} min`
58
+ : `${Math.floor(total / 60)} h${total % 60 ? ` ${total % 60} min` : ""}`;
59
+ };
60
+
61
+ /**
62
+ * Follows the person: keeps `presence` ({ awaySince, lastAway, backAt }, as the buddy reads it) and `inCall`, and says
63
+ * each change in the log. `read()` is the person now (environment.mjs person), for a look between the minute's.
64
+ */
65
+ export function createPresence({
66
+ sources,
67
+ events,
68
+ read = null,
69
+ onAway = () => {},
70
+ now = () => Date.now(),
71
+ }) {
72
+ const presence = { awaySince: null, lastAway: null, backAt: null };
73
+ let inCall = null;
74
+ // Whether this computer can say how long since the person's last input (not on Linux without xprintidle).
75
+ let readable = false;
76
+ let unfollow = null;
77
+ const say = (kind, text, data = null) =>
78
+ events.append({ source: "person", kind, text, data });
79
+ const heard = (reading) => {
80
+ const { idleSeconds } = reading;
81
+ readable = idleSeconds !== null && idleSeconds !== undefined;
82
+ if (idleSeconds !== null && idleSeconds !== undefined) {
83
+ if (idleSeconds >= AWAY_SECONDS && !presence.awaySince) {
84
+ presence.awaySince = new Date(now() - idleSeconds * 1000).toISOString();
85
+ say("away", "the person is away: no input for 20 min", {
86
+ since: presence.awaySince,
87
+ });
88
+ onAway();
89
+ } else if (idleSeconds < 60 && presence.awaySince) {
90
+ presence.lastAway = presence.awaySince;
91
+ presence.backAt = new Date(now()).toISOString();
92
+ presence.awaySince = null;
93
+ say(
94
+ "back",
95
+ `the person is back after ${minutes(Date.parse(presence.backAt) - Date.parse(presence.lastAway))}`,
96
+ { awaySince: presence.lastAway }
97
+ );
98
+ }
99
+ }
100
+ if (inCall !== null && reading.inCall !== inCall)
101
+ say(
102
+ reading.inCall ? "call" : "call-ended",
103
+ reading.inCall ? "the person is in a call" : "the person's call ended"
104
+ );
105
+ inCall = reading.inCall;
106
+ };
107
+ return {
108
+ presence,
109
+ inCall: () => inCall === true,
110
+ /** Whether the person's last input can be read here at all. */
111
+ readable: () => readable,
112
+ /** Reads the person now, between the minute's looks: the digest asks just before it answers. */
113
+ lookNow() {
114
+ if (read) heard(read());
115
+ },
116
+ start() {
117
+ unfollow = sources.subscribe({ kind: "person" }, heard);
118
+ },
119
+ stop() {
120
+ unfollow?.();
121
+ unfollow = null;
122
+ },
123
+ };
124
+ }
125
+
126
+ const git = (args, cwd) => {
127
+ try {
128
+ return execFileSync("git", args, {
129
+ cwd,
130
+ encoding: "utf8",
131
+ stdio: ["ignore", "pipe", "ignore"],
132
+ }).trim();
133
+ } catch {
134
+ return null;
135
+ }
136
+ };
137
+
138
+ /** Where a repository keeps its own files: its top, its folder (HEAD) and the folder its branches share. */
139
+ function gitPlaces(folder) {
140
+ const top = git(["rev-parse", "--show-toplevel"], folder);
141
+ if (!top) return null;
142
+ const own = git(["rev-parse", "--absolute-git-dir"], folder);
143
+ const common = git(["rev-parse", "--git-common-dir"], folder);
144
+ if (!own || !common) return null;
145
+ return { top, own, common: path.resolve(folder, common) };
146
+ }
147
+
148
+ /** The repository kind for sources.mjs: `{ folder }`. A folder in no repository is not followed. */
149
+ export function createRepositoryKind({ now = () => Date.now() } = {}) {
150
+ return {
151
+ describe: ({ folder }) =>
152
+ `says when the repository at ${folder} switches branch or gains commits, and what moved while Harness was off`,
153
+ start({ folder }, io) {
154
+ const places = gitPlaces(folder);
155
+ if (!places) throw new Error(`${folder} is in no repository`);
156
+ const read = () => ({
157
+ branch: git(["branch", "--show-current"], places.top) || null,
158
+ head: git(["rev-parse", "--verify", "-q", "HEAD"], places.top),
159
+ });
160
+ let last = read();
161
+ let stopped = false;
162
+ let settle = null;
163
+ const watchers = [];
164
+
165
+ /** What moved between two reads, as happenings; nothing when nothing did. */
166
+ const tell = (before, after, whileOff = false) => {
167
+ const extra = whileOff ? " while Harness was off" : "";
168
+ const data = {
169
+ top: places.top,
170
+ branch: after.branch,
171
+ head: after.head,
172
+ whileOff,
173
+ };
174
+ if (before.branch !== after.branch && after.branch) {
175
+ io.report(
176
+ { at: now(), ...after },
177
+ {
178
+ kind: "branch",
179
+ text: `the branch is now ${after.branch}${extra}`,
180
+ data: { ...data, was: before.branch },
181
+ }
182
+ );
183
+ return;
184
+ }
185
+ if (!after.head || before.head === after.head) return;
186
+ const ahead =
187
+ before.head &&
188
+ git(
189
+ ["merge-base", "--is-ancestor", before.head, after.head],
190
+ places.top
191
+ ) !== null;
192
+ const count = ahead
193
+ ? Number(
194
+ git(
195
+ ["rev-list", "--count", `${before.head}..${after.head}`],
196
+ places.top
197
+ )
198
+ ) || 1
199
+ : null;
200
+ const where = after.branch ?? "a detached head";
201
+ io.report(
202
+ { at: now(), ...after },
203
+ ahead
204
+ ? {
205
+ kind: "commits",
206
+ text: `${count} commit${count === 1 ? "" : "s"} on ${where} (${after.head.slice(0, 7)})${extra}`,
207
+ data: { ...data, count },
208
+ }
209
+ : {
210
+ kind: "moved",
211
+ text: `${where} moved to ${after.head.slice(0, 7)}, not from where it was${extra}`,
212
+ data: { ...data, was: before.head },
213
+ }
214
+ );
215
+ };
216
+
217
+ const changed = () => {
218
+ if (stopped) return;
219
+ clearTimeout(settle);
220
+ settle = setTimeout(() => {
221
+ if (stopped) return;
222
+ const current = read();
223
+ tell(last, current);
224
+ last = current;
225
+ io.remember(current);
226
+ }, GIT_SETTLE_MS);
227
+ settle.unref?.();
228
+ };
229
+ // Only the files a branch or a commit moves: git rewrites its index at every status, which says nothing here.
230
+ const watch = (where, { recursive = false, only = null } = {}) => {
231
+ try {
232
+ const watcher = fs.watch(
233
+ where,
234
+ { recursive, persistent: false },
235
+ (_, name) => {
236
+ if (!only || only.includes(String(name))) changed();
237
+ }
238
+ );
239
+ watcher.on("error", () => watcher.close());
240
+ watchers.push(watcher);
241
+ } catch {}
242
+ };
243
+ // HEAD in the repository's own folder; the branches, and the refs git packs, in the folder they share.
244
+ watch(places.own, { only: ["HEAD"] });
245
+ if (places.common !== places.own)
246
+ watch(places.common, { only: ["packed-refs"] });
247
+ else watch(places.common, { only: ["HEAD", "packed-refs"] });
248
+ watch(path.join(places.common, "refs", "heads"), {
249
+ recursive:
250
+ process.platform === "darwin" || process.platform === "win32",
251
+ });
252
+
253
+ // What moved while Harness was off.
254
+ const before = io.remembered();
255
+ queueMicrotask(() => {
256
+ if (stopped) return;
257
+ if (before) tell(before, last, true);
258
+ io.remember(last);
259
+ });
260
+
261
+ return {
262
+ stop() {
263
+ stopped = true;
264
+ clearTimeout(settle);
265
+ for (const watcher of watchers) watcher.close();
266
+ },
267
+ };
268
+ },
269
+ };
270
+ }
@@ -0,0 +1,2 @@
1
+ export function isPrivateNetworkHost(hostname: string): boolean;
2
+ export function isPrivateAddress(address: string): boolean;
@@ -0,0 +1,93 @@
1
+ // Which hosts and addresses are anywhere but the public internet. One rule for Harness's server
2
+ // (src/shared/privateNetworkHost.ts, src/server/net/publicFetch.ts) and the person's computer (publicFetch.js), which
3
+ // both call addresses a person, an agent or a site gave them.
4
+
5
+ /**
6
+ * Loopback, private-network, link-local and single-label hosts. Browsing across the user's granted
7
+ * sites never reaches these unless the task's own connected origin is one of them. `hostname` is a
8
+ * WHATWG `URL.hostname`, which already normalizes alternative IPv4 spellings.
9
+ */
10
+ export function isPrivateNetworkHost(hostname) {
11
+ const host = hostname.toLowerCase().replace(/\.$/, "");
12
+ if (host.startsWith("[")) return isPrivateAddress(host.slice(1, -1));
13
+ if (IPV4.test(host)) return isPrivateAddress(host);
14
+ return (
15
+ !host.includes(".") ||
16
+ host === "localhost" ||
17
+ /\.(localhost|local|internal|flycast|home\.arpa|lan)$/.test(host)
18
+ );
19
+ }
20
+
21
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
22
+
23
+ /**
24
+ * Whether an IP address (no brackets) is anywhere but the public internet: loopback, private, carrier-grade NAT,
25
+ * link-local, unique-local (Fly's private 6PN network is fdaa::/16), multicast, reserved, or an IPv6 form that wraps
26
+ * an IPv4 address. Anything that is not an address at all counts as private, so a caller that fails to parse never
27
+ * lets a request through.
28
+ */
29
+ export function isPrivateAddress(address) {
30
+ const v4 = ipv4Octets(address);
31
+ if (v4) return isPrivateIpv4(v4);
32
+ const v6 = ipv6Hextets(address);
33
+ if (!v6) return true;
34
+ const [first, second] = v6;
35
+ const upperZero = v6.slice(0, 5).every((part) => part === 0);
36
+ // ::, ::1 and the deprecated IPv4-compatible ::a.b.c.d.
37
+ if (upperZero && v6[5] === 0) return true;
38
+ // IPv4-mapped ::ffff:a.b.c.d: the URL parser writes it in hex (::ffff:7f00:1), and the socket reaches the IPv4.
39
+ if (upperZero && v6[5] === 0xffff) return true;
40
+ // NAT64 (64:ff9b::/96) and 6to4 (2002::/16) carry an IPv4 address a gateway may reach on its own network.
41
+ if (first === 0x64 && second === 0xff9b) return true;
42
+ if (first === 0x2002) return true;
43
+ // Teredo tunnels to an embedded address, too.
44
+ if (first === 0x2001 && second === 0) return true;
45
+ if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local, Fly 6PN
46
+ if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local
47
+ if ((first & 0xffc0) === 0xfec0) return true; // fec0::/10 old site-local
48
+ if ((first & 0xff00) === 0xff00) return true; // ff00::/8 multicast
49
+ return false;
50
+ }
51
+
52
+ function isPrivateIpv4([a, b, c]) {
53
+ return (
54
+ a === 0 ||
55
+ a === 10 ||
56
+ a === 127 ||
57
+ (a === 100 && b >= 64 && b <= 127) ||
58
+ (a === 169 && b === 254) ||
59
+ (a === 172 && b >= 16 && b <= 31) ||
60
+ (a === 192 && b === 168) ||
61
+ (a === 192 && b === 0 && c === 0) ||
62
+ (a === 198 && (b === 18 || b === 19)) ||
63
+ a >= 224
64
+ );
65
+ }
66
+
67
+ function ipv4Octets(address) {
68
+ const octets = IPV4.exec(address)?.slice(1).map(Number);
69
+ return octets && octets.every((octet) => octet <= 255) ? octets : null;
70
+ }
71
+
72
+ // The eight 16-bit groups of an IPv6 address, or null. Takes "::" shorthand and a dotted IPv4 tail; drops a zone.
73
+ function ipv6Hextets(address) {
74
+ let text = address.toLowerCase().split("%")[0];
75
+ const tail = /:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(text);
76
+ if (tail) {
77
+ const octets = ipv4Octets(tail[1]);
78
+ if (!octets) return null;
79
+ const high = ((octets[0] << 8) | octets[1]).toString(16);
80
+ const low = ((octets[2] << 8) | octets[3]).toString(16);
81
+ text = `${text.slice(0, tail.index)}:${high}:${low}`;
82
+ }
83
+ const halves = text.split("::");
84
+ if (halves.length > 2) return null;
85
+ const groups = (half) => (half ? half.split(":") : []);
86
+ const head = groups(halves[0]);
87
+ const rest = halves.length === 2 ? groups(halves[1]) : [];
88
+ const missing = 8 - head.length - rest.length;
89
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return null;
90
+ const all = [...head, ...Array(missing).fill("0"), ...rest];
91
+ if (!all.every((group) => /^[0-9a-f]{1,4}$/.test(group))) return null;
92
+ return all.map((group) => parseInt(group, 16));
93
+ }
@@ -0,0 +1,300 @@
1
+ // What sleep proposes (docs/senses-plan.md S8.4): a change the record suggests, replayed against what really happened
2
+ // before it is offered, and run only once the person starts it. Two kinds so far:
3
+ // - a watch the person keeps letting pass: have it note what it sees (a fact any agent reads) instead of telling them.
4
+ // The replay counts, from the watch's own tellings, how many they let pass and how many they acted on, which a quiet
5
+ // watch would no longer tell them;
6
+ // - a lesson the dream read as an instruction for one job: retire it. The replay counts the threads the person said
7
+ // it in; one thread bears the reading out, several speak against it.
8
+ // - a new reflex: a watch that told the person, after which they asked the same agent of the thread, again and again.
9
+ // It is offered to wake that agent itself when it trips; the replay counts the tellings they followed that way.
10
+ // - a watch on a limit tuned by what the person did with its past trips (S9.2): when they let every trip pass at
11
+ // numbers up to some value and acted only beyond it, the limit is offered at that value; the replay counts the
12
+ // trips that would still have told them.
13
+ //
14
+ // Each carries what the person's screen names it by (the buddy's Sleep suggests, views/lessons.ts): the thing a watch
15
+ // reads, as its read-back says it, or the lesson's words.
16
+ //
17
+ // Kept on the computer that holds the board, as the person's: listed, started or dismissed by them. A proposal
18
+ // dismissed is not made again for the same watch or lesson.
19
+
20
+ import { thingOf } from "./threadWatches.mjs";
21
+
22
+ const KEY = "proposals";
23
+ // A limit is offered from at least this many trips the person let pass.
24
+ const TUNE_FROM = 3;
25
+ const DISMISSED = "proposals-dismissed";
26
+
27
+ /**
28
+ * `watchesLetPass()` is what sleep counted (sleep.mjs ignored, by watch id); `setResponse(id, response)` changes what
29
+ * a watch does when it trips (threadWatches.mjs); `retireLesson(id, why)` takes a lesson out of the work.
30
+ */
31
+ export function createProposals({
32
+ store,
33
+ watchesLetPass = () => [],
34
+ setResponse = () => null,
35
+ setCondition = () => null,
36
+ retireLesson = () => null,
37
+ now = () => Date.now(),
38
+ }) {
39
+ const read = (key) => {
40
+ try {
41
+ return JSON.parse(store.meta(key) || "[]");
42
+ } catch {
43
+ return [];
44
+ }
45
+ };
46
+ const list = () => read(KEY);
47
+ const save = (proposals) => store.meta(KEY, JSON.stringify(proposals));
48
+ const dismissed = () => new Set(read(DISMISSED));
49
+
50
+ const add = (proposal) => {
51
+ if (dismissed().has(proposal.id)) return null;
52
+ const kept = list().filter((each) => each.id !== proposal.id);
53
+ save([...kept, { ...proposal, at: new Date(now()).toISOString() }]);
54
+ return proposal;
55
+ };
56
+
57
+ /** Proposals from what sleep counted: each watch the person let pass at least half the times it told them. */
58
+ const fromSleep = () => {
59
+ for (const row of watchesLetPass()) {
60
+ const watch = store.db.get(
61
+ "select id, source, response, state from board_watches where id = ?",
62
+ [row.id]
63
+ );
64
+ const response = watch?.response ? JSON.parse(watch.response) : null;
65
+ if (!watch || watch.state === "ended" || response?.do !== "tell")
66
+ continue;
67
+ if (row.letPass < 2 || row.letPass * 2 < row.told) continue;
68
+ const acted = row.told - 1 - row.letPass;
69
+ add({
70
+ id: `quiet:${row.id}`,
71
+ kind: "quiet-watch",
72
+ target: row.id,
73
+ watch: thingOf(JSON.parse(watch.source)),
74
+ text: `${row.label} told you ${row.told} times and you let ${row.letPass} pass. Have it note what it sees for your agents instead of telling you?`,
75
+ replay: {
76
+ told: row.told,
77
+ letPass: row.letPass,
78
+ acted: Math.max(0, acted),
79
+ wouldTell: 0,
80
+ note: `Replayed on its ${row.told} tellings: none would have reached you; ${Math.max(0, acted)} you acted on would have been in its fact instead.`,
81
+ },
82
+ });
83
+ }
84
+ };
85
+
86
+ /**
87
+ * A new reflex: each watch the person answered by asking the same agent of its thread at least twice, and at least
88
+ * half the times it told them, offered to wake that agent itself. What they did is read from their next post in the
89
+ * thread after each telling, before the next.
90
+ */
91
+ const reflexes = () => {
92
+ let fires;
93
+ try {
94
+ fires = store.db.all(
95
+ "select f.watch, f.thread, f.at, w.source, w.response, w.state from board_watch_fires f join board_watches w on w.id = f.watch where f.outcome = 'told the person' and f.edge = 'tripped' and f.thread is not null order by f.watch, f.at"
96
+ );
97
+ } catch {
98
+ return;
99
+ }
100
+ const byWatch = new Map();
101
+ for (const fire of fires)
102
+ byWatch.set(fire.watch, [...(byWatch.get(fire.watch) ?? []), fire]);
103
+ for (const [watch, list] of byWatch) {
104
+ const response = list[0].response ? JSON.parse(list[0].response) : null;
105
+ if (list[0].state === "ended" || response?.do !== "tell") continue;
106
+ const team = store.getTask(list[0].thread)?.goal?.team ?? [];
107
+ const asked = new Map();
108
+ list.forEach((fire, index) => {
109
+ const next = store.db.get(
110
+ `select mentions from board_contributions where task_id = ? and author = 'user' and created_at > ?${list[index + 1] ? " and created_at < ?" : ""} order by seq limit 1`,
111
+ [
112
+ fire.thread,
113
+ fire.at,
114
+ ...(list[index + 1] ? [list[index + 1].at] : []),
115
+ ]
116
+ );
117
+ const mentioned = next?.mentions ? JSON.parse(next.mentions) : [];
118
+ for (const agent of new Set(mentioned))
119
+ if (team.includes(agent))
120
+ asked.set(agent, (asked.get(agent) ?? 0) + 1);
121
+ });
122
+ const [agent, times] = [...asked].sort((a, b) => b[1] - a[1])[0] ?? [];
123
+ if (!agent || times < 2 || times * 2 < list.length) continue;
124
+ add({
125
+ id: `wake:${watch}:${agent}`,
126
+ kind: "wake-agent",
127
+ target: watch,
128
+ agent,
129
+ watch: thingOf(JSON.parse(list[0].source)),
130
+ text: `When watch ${String(watch).slice(0, 8)} told you, you asked ${agent} next ${times} of ${list.length} times. Have it wake ${agent} itself when it trips?`,
131
+ replay: {
132
+ told: list.length,
133
+ asked: times,
134
+ note: `Replayed on its ${list.length} tellings: ${agent} would have been woken at each, ${times} times when you asked it yourself.`,
135
+ },
136
+ });
137
+ }
138
+ };
139
+
140
+ /**
141
+ * A limit tuned by what the person did (S9.2): for each watch on a number that tripped beyond one side of its limits
142
+ * at least TUNE_FROM times, where the person let at least half pass and every one they let pass was nearer the limit
143
+ * than any they acted on, the limit moved to the farthest they let pass. What they did is their next post in the
144
+ * thread after each trip, before the next.
145
+ */
146
+ const tunes = () => {
147
+ let fires;
148
+ try {
149
+ fires = store.db.all(
150
+ "select f.watch, f.thread, f.at, f.value, w.source, w.condition, w.state from board_watch_fires f join board_watches w on w.id = f.watch where f.edge = 'tripped' and f.value is not null and f.thread is not null order by f.watch, f.at"
151
+ );
152
+ } catch {
153
+ return;
154
+ }
155
+ const byWatch = new Map();
156
+ for (const fire of fires)
157
+ byWatch.set(fire.watch, [...(byWatch.get(fire.watch) ?? []), fire]);
158
+ for (const [watch, list] of byWatch) {
159
+ if (list[0].state === "ended") continue;
160
+ const condition = JSON.parse(list[0].condition);
161
+ if (condition.when !== "off") continue;
162
+ const acted = (fire, index) =>
163
+ Boolean(
164
+ store.db.get(
165
+ `select 1 from board_contributions where task_id = ? and author = 'user' and created_at > ?${list[index + 1] ? " and created_at < ?" : ""} limit 1`,
166
+ [
167
+ fire.thread,
168
+ fire.at,
169
+ ...(list[index + 1] ? [list[index + 1].at] : []),
170
+ ]
171
+ )
172
+ );
173
+ for (const side of ["above", "below"]) {
174
+ const limit = condition[side];
175
+ if (limit === null || limit === undefined) continue;
176
+ const beyond = (value) =>
177
+ side === "above" ? value > limit : value < limit;
178
+ const trips = list
179
+ .map((fire, index) => ({
180
+ value: fire.value,
181
+ acted: acted(fire, index),
182
+ }))
183
+ .filter((trip) => beyond(trip.value));
184
+ const passed = trips
185
+ .filter((trip) => !trip.acted)
186
+ .map((trip) => trip.value);
187
+ const followed = trips
188
+ .filter((trip) => trip.acted)
189
+ .map((trip) => trip.value);
190
+ if (passed.length < TUNE_FROM || passed.length * 2 < trips.length)
191
+ continue;
192
+ const to = side === "above" ? Math.max(...passed) : Math.min(...passed);
193
+ if (
194
+ followed.some((value) =>
195
+ side === "above" ? value <= to : value >= to
196
+ )
197
+ )
198
+ continue;
199
+ const source = JSON.parse(list[0].source);
200
+ add({
201
+ id: `tune:${watch}:${side}`,
202
+ kind: "tune-watch",
203
+ target: watch,
204
+ side,
205
+ from: limit,
206
+ to,
207
+ watch: thingOf(source),
208
+ text: `${thingOf(source)} told you ${trips.length} times ${side} ${limit} and you let ${passed.length} pass, none ${side === "above" ? "above" : "below"} ${to}. Tell you only ${side} ${to}?`,
209
+ replay: {
210
+ told: trips.length,
211
+ letPass: passed.length,
212
+ acted: followed.length,
213
+ wouldTell: trips.filter((trip) =>
214
+ side === "above" ? trip.value > to : trip.value < to
215
+ ).length,
216
+ note: `Replayed on its ${trips.length} trips ${side} ${limit}: ${followed.length} you acted on would still have told you, the ${passed.length} you let pass would not.`,
217
+ },
218
+ });
219
+ }
220
+ }
221
+ };
222
+
223
+ /** A lesson the dream read as one job's instruction, offered to retire with the threads it was said in. */
224
+ const retireOffer = (lesson, why) => {
225
+ const threads = new Set(
226
+ (lesson.evidence ?? []).map((entry) => entry.goalId).filter(Boolean)
227
+ );
228
+ return add({
229
+ id: `retire:${lesson.id}`,
230
+ kind: "retire-lesson",
231
+ target: lesson.id,
232
+ lesson: String(lesson.text),
233
+ text: `"${String(lesson.text).slice(0, 160)}" reads as an instruction for one job (${why}). Retire it?`,
234
+ replay: {
235
+ threads: threads.size,
236
+ note:
237
+ threads.size <= 1
238
+ ? "Replayed on the record: you said it in one thread only."
239
+ : `Replayed on the record: you said it in ${threads.size} threads, which speaks against one job.`,
240
+ },
241
+ });
242
+ };
243
+
244
+ /** The person starts a proposal: it runs now. */
245
+ const start = (id) => {
246
+ const proposal = list().find((each) => each.id === id);
247
+ if (!proposal) return null;
248
+ let done = null;
249
+ if (proposal.kind === "quiet-watch")
250
+ done = setResponse(proposal.target, {
251
+ do: "fact",
252
+ key: `watch.${proposal.target.slice(0, 8)}`,
253
+ });
254
+ if (proposal.kind === "wake-agent")
255
+ done = setResponse(proposal.target, {
256
+ do: "wake",
257
+ agent: proposal.agent,
258
+ });
259
+ if (proposal.kind === "tune-watch") {
260
+ const condition = store.db.get(
261
+ "select condition from board_watches where id = ?",
262
+ [proposal.target]
263
+ )?.condition;
264
+ done = condition
265
+ ? setCondition(proposal.target, {
266
+ ...JSON.parse(condition),
267
+ [proposal.side]: proposal.to,
268
+ })
269
+ : null;
270
+ }
271
+ if (proposal.kind === "retire-lesson")
272
+ done = retireLesson(
273
+ proposal.target,
274
+ "the person retired it from a proposal"
275
+ );
276
+ if (!done) return null;
277
+ save(list().filter((each) => each.id !== id));
278
+ return proposal;
279
+ };
280
+
281
+ const dismiss = (id) => {
282
+ const proposal = list().find((each) => each.id === id);
283
+ if (!proposal) return null;
284
+ save(list().filter((each) => each.id !== id));
285
+ store.meta(DISMISSED, JSON.stringify([...dismissed(), id].slice(-500)));
286
+ return proposal;
287
+ };
288
+
289
+ return {
290
+ list,
291
+ fromSleep: () => {
292
+ fromSleep();
293
+ reflexes();
294
+ tunes();
295
+ },
296
+ retireOffer,
297
+ start,
298
+ dismiss,
299
+ };
300
+ }