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,1298 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { harnessHome } from "./paths.mjs";
7
+ import { subjectFor } from "./sources.mjs";
8
+ import { PARENT, SENSE, putSteer } from "./steerQueue.mjs";
9
+ import { howLong } from "./timeSense.mjs";
10
+ import {
11
+ conditionOf,
12
+ holdsNow,
13
+ saysOf,
14
+ sourceOf,
15
+ thingOf,
16
+ whenOf,
17
+ } from "./threadWatches.mjs";
18
+ import { watchOf } from "./waitTool.mjs";
19
+ import {
20
+ marksRoot,
21
+ pollsRoot,
22
+ sessionOf,
23
+ sessionOfPid,
24
+ sessionsAtWork,
25
+ setVolume,
26
+ volumeOf,
27
+ } from "./senseCall.mjs";
28
+
29
+ // The agent's own verbs for its senses (docs/senses-plan.md S4.7, "How an agent meets the world"): look (the glance,
30
+ // zoom, questions in its own terms, time it can scrub, and its volume) and wish (a sense it lacks). Each comes from the
31
+ // agent's MCP server (mcp-stdio.mjs) as a `senses.*` command; its session is found by the agent's process, which each
32
+ // hook after a call notes (senseCall.mjs). Everything here only reads, except the session's own volume and a wish.
33
+ // Code decides only what arrives unasked; what an agent can look at has no ceiling but the log's own (30 days).
34
+
35
+ // The glance names at most this many lines of what changed; the rest are counted.
36
+ const GLANCE_CHANGES = 6;
37
+ // A question's answer names at most this many happenings, newest last, and says how many more there were.
38
+ const ANSWER_LINES = 20;
39
+ const QUESTION_READS = 2_000;
40
+ // A cause is followed back this many steps, and this many effects are named, when zooming into a happening.
41
+ const ZOOM_CAUSES = 4;
42
+ const ZOOM_EFFECTS = 10;
43
+ const SHAPE = "▁▂▃▄▅▆▇█";
44
+
45
+ // A time as the agent can name it back to look's since and until: 24-hour, this computer's zone.
46
+ const hhmm = (at) =>
47
+ new Date(at).toLocaleTimeString([], {
48
+ hour: "2-digit",
49
+ minute: "2-digit",
50
+ hour12: false,
51
+ });
52
+
53
+ /**
54
+ * A time an agent names: "14:30" or "3pm" (today, or yesterday when that is still to come), "2h", "30m" or "1d" ago,
55
+ * or an ISO time. Null when it is none of these.
56
+ */
57
+ export function timeOf(text, now = Date.now()) {
58
+ const said = String(text ?? "")
59
+ .trim()
60
+ .toLowerCase();
61
+ if (!said) return null;
62
+ const ago =
63
+ /^(\d+(?:\.\d+)?)\s*(m|min|minutes?|h|hours?|d|days?)(\s+ago)?$/.exec(said);
64
+ if (ago) {
65
+ const unit =
66
+ ago[2][0] === "m" ? 60_000 : ago[2][0] === "h" ? 3_600_000 : 86_400_000;
67
+ return now - Number(ago[1]) * unit;
68
+ }
69
+ const clock = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?$/.exec(said);
70
+ if (clock) {
71
+ let hour = Number(clock[1]);
72
+ const minute = Number(clock[2] ?? 0);
73
+ if (clock[3] === "pm" && hour < 12) hour += 12;
74
+ if (clock[3] === "am" && hour === 12) hour = 0;
75
+ if (hour > 23 || minute > 59) return null;
76
+ const day = new Date(now);
77
+ day.setHours(hour, minute, 0, 0);
78
+ if (day.getTime() > now) day.setDate(day.getDate() - 1);
79
+ return day.getTime();
80
+ }
81
+ const parsed = Date.parse(String(text));
82
+ return Number.isFinite(parsed) ? parsed : null;
83
+ }
84
+
85
+ const lineOf = (happening) =>
86
+ `h${happening.seq} ${hhmm(happening.at)} ${happening.source}${happening.kind && happening.kind !== "sees" ? `/${happening.kind}` : ""}: ${happening.text}`;
87
+
88
+ /**
89
+ * `store` (meta and the log's table), `events` (the log), `facts`, `nameOf(agent)`. `handles(command)` and
90
+ * `run(request)` answer `senses.look`, `senses.wish` and `senses.wishes` (the person's list).
91
+ */
92
+ export function createSenseTools({
93
+ store,
94
+ events,
95
+ sources = null,
96
+ agents = () => [],
97
+ // Which agents here look signed in (lineup.mjs signedIn), the secrets an agent may use by name (vault.mjs, never
98
+ // their values), and its standing permission (runAuthority.mjs).
99
+ signedIn = () => false,
100
+ secretsFor = async () => [],
101
+ ruleFor = () => null,
102
+ // A reflex's hold or pause (reflexes.mjs): what is on now, and letting one go with a reason.
103
+ reflexes = null,
104
+ nameOf = (agent) => agent,
105
+ // Whether another of the person's computers is reached now (nerves.mjs): its word on the person counts only then.
106
+ reached = () => false,
107
+ home = harnessHome,
108
+ now = () => Date.now(),
109
+ }) {
110
+ const wishesFile = () => path.join(home, "senses", "wishes.json");
111
+ const readJson = (file, fallback) => {
112
+ try {
113
+ return JSON.parse(fs.readFileSync(file, "utf8"));
114
+ } catch {
115
+ return fallback;
116
+ }
117
+ };
118
+ const writeJson = (file, value) => {
119
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
120
+ fs.writeFileSync(`${file}.part`, JSON.stringify(value), { mode: 0o600 });
121
+ fs.renameSync(`${file}.part`, file);
122
+ };
123
+
124
+ // The caller: its session (by its process), that session's folder, and its agent.
125
+ const callerOf = (request) => {
126
+ const session = sessionOfPid(request.agentPid, home);
127
+ const place = session ? sessionOf(session, home) : null;
128
+ return {
129
+ session,
130
+ agent: String(request.agent ?? place?.agent ?? ""),
131
+ folder:
132
+ place?.cwd ?? (typeof request.cwd === "string" ? request.cwd : null),
133
+ };
134
+ };
135
+
136
+ // Whether a happening touches a folder: the file source following it (named by its options, sources.mjs), or one
137
+ // that names the folder.
138
+ const touches = (happening, folder) => {
139
+ if (!folder) return false;
140
+ let real = folder;
141
+ try {
142
+ real = fs.realpathSync(folder);
143
+ } catch {}
144
+ if (happening.subject === subjectFor({ kind: "files", folder: real }))
145
+ return true;
146
+ const where = [
147
+ happening.subject,
148
+ happening.data?.folder,
149
+ happening.data?.cwd,
150
+ ]
151
+ .filter((value) => typeof value === "string")
152
+ .join(" ");
153
+ return where.includes(real) || where.includes(folder);
154
+ };
155
+
156
+ // --- the body knows itself (S4.7d, item 11): what this computer is and has, so no agent spends calls finding out ---
157
+
158
+ let card = null;
159
+ let cardAt = 0;
160
+ const said = (command, args) => {
161
+ try {
162
+ return execFileSync(command, args, {
163
+ encoding: "utf8",
164
+ timeout: 2_000,
165
+ stdio: ["ignore", "pipe", "ignore"],
166
+ }).trim();
167
+ } catch {
168
+ return null;
169
+ }
170
+ };
171
+ /** One line about this computer, read again at most once an hour. */
172
+ const machineCard = () => {
173
+ if (card && now() - cardAt < 3_600_000) return card;
174
+ const system =
175
+ process.platform === "darwin"
176
+ ? `macOS ${said("/usr/bin/sw_vers", ["-productVersion"]) ?? os.release()}`
177
+ : `${os.type()} ${os.release()}`;
178
+ const git =
179
+ said("git", ["--version"])?.replace(/^git version /, "") ?? null;
180
+ const here = agents().map((agent) => nameOf(agent));
181
+ card = `This computer: ${system} on ${os.arch()}, ${Math.round(os.totalmem() / 2 ** 30)} GB memory, ${os.cpus().length} cores; Node ${process.version}${git ? `, git ${git}` : ""}; agents here: ${here.length ? here.join(", ") : "none set up"}.`;
182
+ cardAt = now();
183
+ return card;
184
+ };
185
+
186
+ // --- pace and the others (S4.7e, items 14 and 16) ---
187
+
188
+ /**
189
+ * Pace: whether the person is here or the work has the night, from the newest word of their presence in the log,
190
+ * and the budget the limits leave. One line, or "" when nothing is known.
191
+ */
192
+ const pace = (agent) => {
193
+ // On each of the person's computers its newest word (nerves.mjs carry the others'): in a call on any, here on any,
194
+ // else away since the newest.
195
+ // A computer out of reach may have gone to sleep with its last word "back".
196
+ const latest = store.db
197
+ .all(
198
+ "select kind, at, machine from board_events where seq in (select max(seq) from board_events where source = 'person' and kind in ('away', 'back', 'call', 'call-ended') group by coalesce(machine, ''))",
199
+ []
200
+ )
201
+ .filter((row) => !row.machine || reached(row.machine));
202
+ const newestOf = (kinds) =>
203
+ latest
204
+ .filter((row) => kinds.includes(row.kind))
205
+ .sort((a, b) => b.at.localeCompare(a.at))[0] ?? null;
206
+ const person =
207
+ newestOf(["call"]) ??
208
+ newestOf(["back", "call-ended"]) ??
209
+ newestOf(["away"]);
210
+ const here = !person
211
+ ? null
212
+ : person.kind === "away"
213
+ ? `the person is away since ${hhmm(person.at)}: the work has time, nobody is waiting on it now`
214
+ : person.kind === "call"
215
+ ? `the person is in a call since ${hhmm(person.at)}`
216
+ : `the person is here (back since ${hhmm(person.at)})`;
217
+ // The budget, from the limits' facts (limits.mjs): this agent's runs today and each thread's spend.
218
+ const budget = store.db
219
+ .all(
220
+ "select key, value from board_facts where key = ? or key like 'limits.spend.%'",
221
+ [`limits.standing.${agent}`]
222
+ )
223
+ .map((row) => {
224
+ let value = null;
225
+ try {
226
+ value = JSON.parse(row.value);
227
+ } catch {}
228
+ if (!value || value.level === "none") return null;
229
+ if (row.key.startsWith("limits.standing."))
230
+ return `${value.cap - value.used} of your ${value.cap} runs today left`;
231
+ return `thread ${row.key.slice("limits.spend.".length, "limits.spend.".length + 8)} has ${10 - value.tenths} tenths of its $${value.ceilingUsd} left`;
232
+ })
233
+ .filter(Boolean);
234
+ const parts = [here, ...budget].filter(Boolean);
235
+ return parts.length ? `Pace: ${parts.join("; ")}.` : "";
236
+ };
237
+
238
+ // The other agents at work in the same folder, each with the intention it marked, newest first.
239
+ const others = (caller) => {
240
+ if (!caller.folder) return [];
241
+ const marks = (() => {
242
+ try {
243
+ return fs
244
+ .readdirSync(marksRoot(home))
245
+ .map((name) => readJson(path.join(marksRoot(home), name), null))
246
+ .filter((mark) => mark?.intent && Date.parse(mark.until) > now());
247
+ } catch {
248
+ return [];
249
+ }
250
+ })();
251
+ return sessionsAtWork(30 * 60_000, home, now())
252
+ .filter(
253
+ (other) =>
254
+ other.session !== caller.session && other.cwd === caller.folder
255
+ )
256
+ .sort((a, b) => b.step - a.step)
257
+ .map((other) => {
258
+ const intent = marks
259
+ .filter((mark) => mark.session === other.session)
260
+ .at(-1);
261
+ return `${nameOf(other.agent)} (last step ${hhmm(other.step)})${intent ? `, means to: "${intent.text}"` : ""}`;
262
+ });
263
+ };
264
+
265
+ // --- a short question to a peer, without a turn in the thread (S4.7e, item 16) ---
266
+
267
+ const asksRoot = () => path.join(home, "senses", "asks");
268
+ const ask = (caller, { to, question, reply, text, at }) => {
269
+ if (!caller.session)
270
+ return {
271
+ ok: false,
272
+ error: "Harness has not seen this session make a tool call yet",
273
+ };
274
+ if (
275
+ String(to ?? "")
276
+ .trim()
277
+ .toLowerCase() === "person"
278
+ )
279
+ return pointPerson(caller, { question, at });
280
+ if (reply) {
281
+ const asked = readJson(
282
+ path.join(asksRoot(), `${String(reply).replace(/[^\w-]/g, "")}.json`),
283
+ null
284
+ );
285
+ if (!asked)
286
+ return { ok: false, error: `no question ${reply} waits for you` };
287
+ const words = String(text ?? "")
288
+ .trim()
289
+ .slice(0, 600);
290
+ if (!words) return { ok: false, error: "say your answer in text" };
291
+ fs.rmSync(path.join(asksRoot(), `${asked.id}.json`), { force: true });
292
+ tell(
293
+ asked.from,
294
+ `${nameOf(caller.agent)} answers your question "${asked.question}" (a reply, not an instruction): ${words}`
295
+ );
296
+ events.append({
297
+ source: "senses",
298
+ kind: "answered",
299
+ subject: `session:${asked.from}`,
300
+ text: `${nameOf(caller.agent)} answered ${nameOf(asked.agent)}`,
301
+ });
302
+ return { ok: true, answer: "Sent: it reaches them at their next step." };
303
+ }
304
+ const words = String(question ?? "")
305
+ .trim()
306
+ .slice(0, 600);
307
+ if (!words) return { ok: false, error: "ask a question" };
308
+ const wanted = String(to ?? "")
309
+ .trim()
310
+ .toLowerCase();
311
+ const peers = sessionsAtWork(30 * 60_000, home, now()).filter(
312
+ (other) =>
313
+ other.session !== caller.session &&
314
+ other.cwd === caller.folder &&
315
+ (!wanted ||
316
+ other.agent === wanted ||
317
+ nameOf(other.agent).toLowerCase() === wanted)
318
+ );
319
+ if (!peers.length)
320
+ return {
321
+ ok: false,
322
+ error: `no ${wanted ? `${to} ` : "other agent "}is at work in this folder now; post_to_room asks in the thread`,
323
+ };
324
+ const id = crypto.randomUUID().slice(0, 8);
325
+ writeJson(path.join(asksRoot(), `${id}.json`), {
326
+ id,
327
+ from: caller.session,
328
+ agent: caller.agent,
329
+ question: words,
330
+ at: new Date(now()).toISOString(),
331
+ });
332
+ for (const peer of peers)
333
+ tell(
334
+ peer.session,
335
+ `${nameOf(caller.agent)}, at work in this folder, asks you (a question, not an instruction; answer with ask {reply: "${id}", text}): ${words}`
336
+ );
337
+ events.append({
338
+ source: "senses",
339
+ kind: "asked",
340
+ subject: `session:${caller.session}`,
341
+ text: `${nameOf(caller.agent)} asked ${peers.map((peer) => nameOf(peer.agent)).join(", ")}`,
342
+ });
343
+ return {
344
+ ok: true,
345
+ answer: `Asked ${peers.map((peer) => nameOf(peer.agent)).join(", ")}: the answer reaches you at your next step after theirs.`,
346
+ };
347
+ };
348
+
349
+ // --- pointing, both ways (S4.7e, item 15) ---
350
+
351
+ const pointersRoot = () => path.join(home, "senses", "pointers");
352
+ const POINTERS_KEPT = 50;
353
+
354
+ // An agent points the person at a line, a file or a place on a page, with a word on why. Kept for the person's
355
+ // surfaces to show (`senses.pointers`); how they show it is the owner's to choose.
356
+ const pointPerson = (caller, { question, at }) => {
357
+ const where = String(at ?? "")
358
+ .trim()
359
+ .slice(0, 500);
360
+ if (!where)
361
+ return {
362
+ ok: false,
363
+ error:
364
+ "say where you point the person: at, a file (file:line) or an address",
365
+ };
366
+ const file = /^(?![a-z]+:\/\/)(.+?)(?::(\d+))?$/i.exec(where);
367
+ const place = /^[a-z]+:\/\//i.test(where)
368
+ ? { url: where }
369
+ : {
370
+ file: path.resolve(caller.folder ?? process.cwd(), file[1]),
371
+ ...(file[2] ? { line: Number(file[2]) } : {}),
372
+ };
373
+ const pointer = {
374
+ id: crypto.randomUUID().slice(0, 8),
375
+ agent: caller.agent,
376
+ by: nameOf(caller.agent),
377
+ session: caller.session,
378
+ folder: caller.folder,
379
+ ...place,
380
+ why:
381
+ String(question ?? "")
382
+ .trim()
383
+ .slice(0, 600) || null,
384
+ at: new Date(now()).toISOString(),
385
+ };
386
+ writeJson(path.join(pointersRoot(), `${pointer.id}.json`), pointer);
387
+ let names = [];
388
+ try {
389
+ names = fs.readdirSync(pointersRoot()).sort();
390
+ } catch {}
391
+ for (const name of names.slice(
392
+ 0,
393
+ Math.max(0, names.length - POINTERS_KEPT)
394
+ ))
395
+ fs.rmSync(path.join(pointersRoot(), name), { force: true });
396
+ events.append({
397
+ source: "senses",
398
+ kind: "pointed",
399
+ subject: `session:${caller.session}`,
400
+ text: `${pointer.by} pointed the person at ${place.url ? "a page" : "a file"}`,
401
+ });
402
+ return {
403
+ ok: true,
404
+ pointer: { id: pointer.id },
405
+ answer:
406
+ "Kept for the person, where Harness shows them what agents point at.",
407
+ };
408
+ };
409
+
410
+ // What agents pointed the person at, newest first (the person's surfaces read this).
411
+ const pointers = () => {
412
+ let names = [];
413
+ try {
414
+ names = fs
415
+ .readdirSync(pointersRoot())
416
+ .filter((name) => name.endsWith(".json"));
417
+ } catch {}
418
+ return {
419
+ ok: true,
420
+ pointers: names
421
+ .map((name) => readJson(path.join(pointersRoot(), name), null))
422
+ .filter(Boolean)
423
+ .sort((a, b) => b.at.localeCompare(a.at)),
424
+ };
425
+ };
426
+
427
+ // The person points at something ("this"): a file and line, a selection, a page. It reaches the agents at work in
428
+ // the folder named (or the one session named) at their next step, as the person's pointing, quoted, not obeyed.
429
+ const personPoints = (request) => {
430
+ if (request.agent !== "user")
431
+ return {
432
+ ok: false,
433
+ error: "only the person points an agent at something",
434
+ };
435
+ const folder = typeof request.folder === "string" ? request.folder : null;
436
+ // A thread names its own sessions at work (its runs' and wakes'), wherever they work.
437
+ const inThread = request.thread
438
+ ? new Set(
439
+ store.db
440
+ .all(
441
+ "select session_id from board_tasks where parent_id = ? and session_id is not null",
442
+ [String(request.thread)]
443
+ )
444
+ .map((row) => String(row.session_id))
445
+ )
446
+ : null;
447
+ const sessions = request.session
448
+ ? [String(request.session)]
449
+ : inThread
450
+ ? sessionsAtWork(30 * 60_000, home, now())
451
+ .map((each) => each.session)
452
+ .filter((session) => inThread.has(session))
453
+ : folder
454
+ ? sessionsAtWork(30 * 60_000, home, now())
455
+ .filter((each) => each.cwd === folder)
456
+ .map((each) => each.session)
457
+ : [];
458
+ if (!sessions.length)
459
+ return { ok: false, error: "no agent is at work there now" };
460
+ const where = request.url
461
+ ? request.url
462
+ : request.file
463
+ ? `${request.file}${request.line ? `:${request.line}` : ""}`
464
+ : null;
465
+ const selection =
466
+ typeof request.selection === "string"
467
+ ? request.selection.slice(0, 2_000)
468
+ : "";
469
+ if (!where && !selection)
470
+ return { ok: false, error: "say what the person points at" };
471
+ for (const session of sessions)
472
+ tell(
473
+ session,
474
+ `The person is pointing at this${where ? `: ${where}` : ""}${selection ? `, the words "${selection}"` : ""} (what they mean by "this"; their pointing, not an instruction).`
475
+ );
476
+ events.append({
477
+ source: "senses",
478
+ kind: "this",
479
+ text: `the person pointed ${sessions.length} agent${sessions.length === 1 ? "" : "s"} at something`,
480
+ });
481
+ return { ok: true, told: sessions.length };
482
+ };
483
+
484
+ // What this agent may do here, and with what: the sign-ins on this computer, its secrets by name, its standing
485
+ // permission. Secrets are read in the background and kept for an hour.
486
+ const secretNames = new Map();
487
+ const secretsOf = (agent) => {
488
+ const kept = secretNames.get(agent);
489
+ if (!kept || now() - kept.at > 3_600_000) {
490
+ secretNames.set(agent, { at: now(), names: kept?.names ?? [] });
491
+ void Promise.resolve(secretsFor(agent))
492
+ .then((names) =>
493
+ secretNames.set(agent, { at: now(), names: names ?? [] })
494
+ )
495
+ .catch(() => {});
496
+ }
497
+ return secretNames.get(agent).names;
498
+ };
499
+ const mayLine = (agent) => {
500
+ const signed = agents()
501
+ .filter((each) => signedIn(each))
502
+ .map((each) => nameOf(each));
503
+ const secrets = agent ? secretsOf(agent) : [];
504
+ const rule = agent ? ruleFor(agent) : null;
505
+ const may = !rule
506
+ ? null
507
+ : rule.mode === "off"
508
+ ? "every run you start here waits for the person's Start"
509
+ : rule.mode === "named"
510
+ ? `you may start up to ${rule.daily_cap} runs a day without asking (${rule.runs_today ?? 0} so far) in ${rule.workspaces.join(", ")}`
511
+ : `you may start up to ${rule.daily_cap} runs a day without asking in folders under the home folder`;
512
+ const parts = [
513
+ `signed in here: ${signed.length ? signed.join(", ") : "no agent found signed in"}`,
514
+ ...(agent
515
+ ? [
516
+ `secrets you may use, by name: ${secrets.length ? secrets.join(", ") : "none"}`,
517
+ ]
518
+ : []),
519
+ ...(may ? [may] : []),
520
+ ];
521
+ return `What you have here: ${parts.join("; ")}.`;
522
+ };
523
+
524
+ // --- the glance ---
525
+
526
+ // The disk's free space over the last hours, as a small shape: its direction and its recent past.
527
+ const diskShape = () => {
528
+ let hours = [];
529
+ try {
530
+ hours = JSON.parse(store.meta("machine-disk-history") || "[]");
531
+ } catch {}
532
+ const recent = hours.slice(-8).map((hour) => Number(hour.low));
533
+ if (recent.length < 2) return "";
534
+ const low = Math.min(...recent);
535
+ const high = Math.max(...recent);
536
+ const shape = recent
537
+ .map(
538
+ (value) =>
539
+ SHAPE[
540
+ high === low ? 3 : Math.round(((value - low) / (high - low)) * 7)
541
+ ]
542
+ )
543
+ .join("");
544
+ const change = recent.at(-1) - recent[0];
545
+ const direction = Math.abs(change) < 1e9 ? "→" : change < 0 ? "↓" : "↑";
546
+ return ` ${direction} ${shape}`;
547
+ };
548
+
549
+ // The newest level the log holds for each of this computer's aspects and the limits (kept on home, so a worker has
550
+ // them over the nerves; another computer's own aspects are not this one's).
551
+ const levels = () => {
552
+ const rows = store.db.all(
553
+ "select subject, text, at from board_events where seq in (select max(seq) from board_events where kind = 'level' and (source = 'limits' or (source = 'machine' and machine is null)) group by subject)",
554
+ []
555
+ );
556
+ return new Map(rows.map((row) => [row.subject, row]));
557
+ };
558
+
559
+ const lookFile = (session) =>
560
+ path.join(home, "senses", "reads", session, "look.json");
561
+
562
+ const glance = (caller) => {
563
+ const at = now();
564
+ const level = levels();
565
+ const gauge = (subject, extra = "") =>
566
+ level.has(subject) ? `${level.get(subject).text}${extra}` : null;
567
+ const machine = [
568
+ gauge("disk", diskShape()),
569
+ gauge("memory"),
570
+ gauge("heat"),
571
+ gauge("battery"),
572
+ gauge("network"),
573
+ ].filter(Boolean);
574
+ const limits = [...level.entries()]
575
+ .filter(
576
+ ([subject]) =>
577
+ subject === `limits.standing.${caller.agent}` ||
578
+ subject.startsWith("limits.spend.")
579
+ )
580
+ .map(([, row]) => row.text);
581
+ const last = caller.session
582
+ ? readJson(lookFile(caller.session), null)
583
+ : null;
584
+ const since = last?.seq ?? 0;
585
+ const changed = since
586
+ ? events.read({ after: since, limit: QUESTION_READS }).filter(
587
+ (happening) =>
588
+ // Here: another computer's folder may have the same path.
589
+ (!happening.machine && touches(happening, caller.folder)) ||
590
+ (caller.session &&
591
+ happening.subject === `session:${caller.session}`)
592
+ )
593
+ : [];
594
+ const newest = events.read({ limit: 1 })[0]?.seq ?? since;
595
+ if (caller.session)
596
+ writeJson(lookFile(caller.session), {
597
+ seq: newest,
598
+ at: new Date(at).toISOString(),
599
+ });
600
+ const lines = [
601
+ `Glance, ${hhmm(at)}${caller.folder ? `, ${caller.folder}` : ""}:`,
602
+ `- ${machineCard().replace(/^This computer: /, "this computer: ")}`,
603
+ `- ${mayLine(caller.agent).replace(/^What you have here: /, "what you have here: ")}`,
604
+ `- now: ${machine.length ? machine.join("; ") : "not read yet"}`,
605
+ ...(pace(caller.agent)
606
+ ? [`- ${pace(caller.agent).replace(/^Pace: /, "pace: ")}`]
607
+ : []),
608
+ ...(others(caller).length
609
+ ? [`- others at work here: ${others(caller).join("; ")}`]
610
+ : []),
611
+ last
612
+ ? changed.length
613
+ ? `- since your last look (${hhmm(last.at)}), ${changed.length} happening${changed.length === 1 ? "" : "s"} here:`
614
+ : `- nothing here since your last look (${hhmm(last.at)})`
615
+ : "- your first look: what changed is counted from now",
616
+ ...changed
617
+ .slice(-GLANCE_CHANGES)
618
+ .map((happening) => ` ${lineOf(happening)}`),
619
+ ...(changed.length > GLANCE_CHANGES
620
+ ? [` and ${changed.length - GLANCE_CHANGES} earlier`]
621
+ : []),
622
+ `- volume: ${caller.session ? volumeOf(caller.session, home) : "normal"} (what is outside your task; pain and tripwires always reach you)`,
623
+ `Zoom with look {at:"h<number>"}; ask with look {about, since, until}.`,
624
+ ];
625
+ return lines.join("\n");
626
+ };
627
+
628
+ // --- zoom ---
629
+
630
+ const zoom = (at) => {
631
+ const id = String(at).trim();
632
+ const seq = /^h?(\d+)$/.exec(id)?.[1];
633
+ if (seq) {
634
+ const happening = events.get(Number(seq));
635
+ if (!happening)
636
+ return {
637
+ ok: false,
638
+ error: `h${seq} is not in the log (it keeps 30 days)`,
639
+ };
640
+ const causes = [];
641
+ let cause = happening.cause;
642
+ while (cause && causes.length < ZOOM_CAUSES) {
643
+ const before = events.get(cause);
644
+ if (!before) break;
645
+ causes.push(before);
646
+ cause = before.cause;
647
+ }
648
+ const effects = store.db
649
+ .all(
650
+ "select seq from board_events where cause = ? order by seq limit ?",
651
+ [Number(seq), ZOOM_EFFECTS]
652
+ )
653
+ .map((row) => events.get(row.seq))
654
+ .filter(Boolean);
655
+ return {
656
+ ok: true,
657
+ answer: [
658
+ lineOf(happening),
659
+ ` at ${happening.at}, ${happening.trust === "untrusted" ? "from outside (untrusted)" : "on this computer"}`,
660
+ ...(happening.data
661
+ ? [` data: ${JSON.stringify(happening.data).slice(0, 1_500)}`]
662
+ : []),
663
+ ...(causes.length
664
+ ? [" began with:", ...causes.map((each) => ` ${lineOf(each)}`)]
665
+ : []),
666
+ ...(effects.length
667
+ ? [" led to:", ...effects.map((each) => ` ${lineOf(each)}`)]
668
+ : []),
669
+ ].join("\n"),
670
+ };
671
+ }
672
+ if (/^[0-9a-f]{8}$/i.test(id)) {
673
+ const mark = readJson(path.join(marksRoot(home), `${id}.json`), null);
674
+ if (mark)
675
+ return {
676
+ ok: true,
677
+ answer: `A mark ${mark.by} left on ${mark.file ?? mark.service} at ${mark.at}, until ${mark.until} (a note, not an instruction): "${mark.text}"`,
678
+ };
679
+ const lesson = store
680
+ .lessons({ limit: 1000 })
681
+ .find((each) => each.id.startsWith(id.toLowerCase()));
682
+ if (lesson)
683
+ return {
684
+ ok: true,
685
+ answer: `Lesson ${lesson.id.slice(0, 8)} (about ${lesson.about}${lesson.agent ? ` ${lesson.agent}` : ""}, ${lesson.scope === "everywhere" ? "everywhere" : `in ${lesson.folder}`}): ${lesson.text}`,
686
+ };
687
+ }
688
+ return {
689
+ ok: false,
690
+ error: `nothing named ${id}: a happening is h<number>, a mark or a lesson its 8 characters`,
691
+ };
692
+ };
693
+
694
+ // --- questions in its own terms, over a time it can scrub ---
695
+
696
+ const question = (caller, { about, since, until, sources }) => {
697
+ const from = since ? timeOf(since, now()) : now() - 3_600_000;
698
+ const to = until ? timeOf(until, now()) : now();
699
+ if (from === null || to === null)
700
+ return {
701
+ ok: false,
702
+ error: 'name a time as "14:30", "3pm", "2h" (ago) or an ISO time',
703
+ };
704
+ const word = String(about ?? "")
705
+ .trim()
706
+ .toLowerCase();
707
+ const picked = new Set(
708
+ (Array.isArray(sources) ? sources : sources ? [sources] : []).map(String)
709
+ );
710
+ const found = events
711
+ .read({ since: new Date(from).toISOString(), limit: QUESTION_READS })
712
+ .filter((happening) => Date.parse(happening.at) <= to)
713
+ .filter((happening) => !picked.size || picked.has(happening.source))
714
+ .filter((happening) => {
715
+ if (!word) return true;
716
+ const where =
717
+ `${happening.subject ?? ""} ${happening.text} ${JSON.stringify(happening.data ?? "")}`.toLowerCase();
718
+ return where.includes(word);
719
+ });
720
+ const shown = found.slice(-ANSWER_LINES);
721
+ return {
722
+ ok: true,
723
+ answer: [
724
+ `${found.length} happening${found.length === 1 ? "" : "s"}${word ? ` about "${about}"` : ""} from ${hhmm(from)} to ${hhmm(to)}${found.length > shown.length ? `, the newest ${shown.length}:` : found.length ? ":" : "."}`,
725
+ ...shown.map(lineOf),
726
+ ].join("\n"),
727
+ };
728
+ };
729
+
730
+ // --- wishes ---
731
+
732
+ const wish = (caller, { sense, why }) => {
733
+ const words = String(sense ?? "")
734
+ .trim()
735
+ .replace(/\s+/g, " ");
736
+ if (!words) return { ok: false, error: "say the sense you wish for" };
737
+ const wishes = readJson(wishesFile(), []);
738
+ const key = words.toLowerCase();
739
+ const same = wishes.find((each) => each.key === key);
740
+ const by = nameOf(caller.agent);
741
+ if (same) {
742
+ same.count += 1;
743
+ same.agents = [...new Set([...same.agents, by])];
744
+ same.last = new Date(now()).toISOString();
745
+ } else
746
+ wishes.push({
747
+ key,
748
+ sense: words.slice(0, 300),
749
+ why:
750
+ String(why ?? "")
751
+ .trim()
752
+ .slice(0, 300) || null,
753
+ agents: [by],
754
+ count: 1,
755
+ first: new Date(now()).toISOString(),
756
+ last: new Date(now()).toISOString(),
757
+ });
758
+ writeJson(wishesFile(), wishes);
759
+ events.append({
760
+ source: "senses",
761
+ kind: "wish",
762
+ text: `${by} wished for a sense`,
763
+ });
764
+ return {
765
+ ok: true,
766
+ answer:
767
+ "Kept for the person, with every other agent's wish for the same.",
768
+ };
769
+ };
770
+
771
+ // The person's list: what agents asked for, and what they kept checking for themselves (each poll is a sense they
772
+ // lacked), most wanted first.
773
+ const wishes = () => {
774
+ const asked = readJson(wishesFile(), []).map((each) => ({
775
+ kind: "asked",
776
+ sense: each.sense,
777
+ why: each.why,
778
+ agents: each.agents,
779
+ count: each.count,
780
+ last: each.last,
781
+ }));
782
+ const polled = new Map();
783
+ let names = [];
784
+ try {
785
+ names = fs.readdirSync(pollsRoot(home));
786
+ } catch {}
787
+ for (const name of names) {
788
+ const polls = readJson(path.join(pollsRoot(home), name), null);
789
+ for (const [shape, poll] of Object.entries(polls?.shapes ?? {})) {
790
+ const kept = polled.get(shape) ?? {
791
+ kind: "polled",
792
+ sense: `tell me when \`${shape}\` changes (agents ran it again and again)`,
793
+ why: null,
794
+ agents: [],
795
+ count: 0,
796
+ last: poll.last,
797
+ };
798
+ kept.count += poll.count;
799
+ kept.agents = [...new Set([...kept.agents, nameOf(polls.agent)])];
800
+ if (poll.last > kept.last) kept.last = poll.last;
801
+ polled.set(shape, kept);
802
+ }
803
+ }
804
+ return {
805
+ ok: true,
806
+ wishes: [...asked, ...polled.values()].sort((a, b) => b.count - a.count),
807
+ };
808
+ };
809
+
810
+ // --- expectations (S4.7b): the agent says what it expects; silence means as expected, only a broken one speaks ---
811
+
812
+ const expectationsRoot = () => path.join(home, "senses", "expectations");
813
+ const armed = new Map();
814
+ const OWN_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
815
+ const inside = (file, folder) => {
816
+ const rel = path.relative(folder, file);
817
+ return !rel.startsWith("..") && !path.isAbsolute(rel);
818
+ };
819
+
820
+ const tell = (session, text) =>
821
+ putSteer({ session, agent: PARENT, kind: SENSE, text }, home);
822
+
823
+ const end = (expectation, outcome, why) => {
824
+ const kept = armed.get(expectation.id);
825
+ if (!kept) return;
826
+ armed.delete(expectation.id);
827
+ kept.stop?.();
828
+ clearTimeout(kept.timer);
829
+ fs.rmSync(path.join(expectationsRoot(), `${expectation.id}.json`), {
830
+ force: true,
831
+ });
832
+ const by = nameOf(expectation.agent);
833
+ events.append({
834
+ source: "senses",
835
+ kind: outcome === "broken" ? "expectation broken" : "as expected",
836
+ subject: `session:${expectation.session}`,
837
+ text: `${by}'s expectation ${outcome === "broken" ? "broke" : "held"}: ${why}`,
838
+ });
839
+ if (outcome === "broken")
840
+ tell(
841
+ expectation.session,
842
+ `Your expectation broke${expectation.what ? ` ("${expectation.what}")` : ""}: ${why}.`
843
+ );
844
+ };
845
+
846
+ const arm = (expectation) => {
847
+ const { source, condition } = expectation;
848
+ const state = { prev: undefined };
849
+ const thing = thingOf(source);
850
+ const happened = whenOf(source, condition).replace(/^when /, "");
851
+ const kept = { timer: null, stop: null };
852
+ armed.set(expectation.id, kept);
853
+ kept.timer = setTimeout(
854
+ () =>
855
+ expectation.never
856
+ ? end(
857
+ expectation,
858
+ "kept",
859
+ `${thing}: nothing came of it by ${hhmm(expectation.until)}`
860
+ )
861
+ : end(
862
+ expectation,
863
+ "broken",
864
+ `by ${hhmm(expectation.until)}, ${thing} still had not come to be as expected (${happened})`
865
+ ),
866
+ Math.max(0, Date.parse(expectation.until) - now())
867
+ );
868
+ kept.timer.unref?.();
869
+ kept.stop = sources.subscribe(source, (reading) => {
870
+ if (reading.error) return;
871
+ let met;
872
+ if (source.kind === "files") met = reading.count > 0;
873
+ else if (condition.when === "changes") {
874
+ const says = JSON.stringify(saysOf(source, condition, reading));
875
+ met = state.prev !== undefined && says !== state.prev;
876
+ state.prev = says;
877
+ } else met = holdsNow(source, condition, reading);
878
+ if (!met) return;
879
+ if (expectation.never)
880
+ end(expectation, "broken", `${thing}: ${happened}`);
881
+ else end(expectation, "kept", `${thing}: ${happened}`);
882
+ });
883
+ };
884
+
885
+ const expect = (caller, args) => {
886
+ if (!caller.session)
887
+ return {
888
+ ok: false,
889
+ error: "Harness has not seen this session make a tool call yet",
890
+ };
891
+ const minutes = Math.min(1_440, Math.max(0.1, Number(args.minutes) || 30));
892
+ const until = new Date(now() + minutes * 60_000).toISOString();
893
+ const what =
894
+ String(args.that ?? "")
895
+ .trim()
896
+ .replace(/\s+/g, " ")
897
+ .slice(0, 200) || null;
898
+ if (args.alone === true) {
899
+ if (!caller.folder)
900
+ return { ok: false, error: "Harness does not know your folder yet" };
901
+ writeJson(
902
+ path.join(home, "senses", "reads", caller.session, "alone.json"),
903
+ {
904
+ since: new Date(now()).toISOString(),
905
+ until,
906
+ what: what ?? "nobody else touches this folder",
907
+ }
908
+ );
909
+ return {
910
+ ok: true,
911
+ answer: `Kept until ${hhmm(until)}: if anyone else changes a file in ${caller.folder}, you hear it at once. Silence means no one did.`,
912
+ };
913
+ }
914
+ // A path may be named from the folder the agent works in.
915
+ const from = caller.folder ?? process.cwd();
916
+ const named = watchOf(
917
+ {
918
+ ...args,
919
+ ...(typeof args.file === "string"
920
+ ? { file: path.resolve(from, args.file) }
921
+ : {}),
922
+ ...(typeof args.folder === "string"
923
+ ? { folder: path.resolve(from, args.folder) }
924
+ : {}),
925
+ },
926
+ from
927
+ );
928
+ if (named.error) return { ok: false, error: named.error };
929
+ if (!named.source)
930
+ return {
931
+ ok: false,
932
+ error:
933
+ "name what you expect: a file, a port, an address, a process, a folder, a fact or a time",
934
+ };
935
+ if (named.source.kind === "command")
936
+ return {
937
+ ok: false,
938
+ error:
939
+ "a command run on a timer waits for the person's Start: leave it with wait_for and its command",
940
+ };
941
+ const source = sourceOf(named.source);
942
+ if (source.error) return { ok: false, error: source.error };
943
+ // As for a watch of its own (open item 2): an address outside this computer, or a path outside the folder,
944
+ // waits for the person.
945
+ if (
946
+ source.what === "address" &&
947
+ !OWN_HOSTS.has(new URL(source.address).hostname)
948
+ )
949
+ return {
950
+ ok: false,
951
+ error:
952
+ "an address outside this computer waits for the person's Start: use wait_for",
953
+ };
954
+ const place =
955
+ source.what === "file"
956
+ ? source.file
957
+ : source.kind === "files"
958
+ ? source.folder
959
+ : null;
960
+ if (place && (!caller.folder || !inside(place, caller.folder)))
961
+ return {
962
+ ok: false,
963
+ error:
964
+ "a file or folder outside the one you work in waits for the person's Start: use wait_for",
965
+ };
966
+ const condition = conditionOf(named.condition, source);
967
+ if (condition.error) return { ok: false, error: condition.error };
968
+ const expectation = {
969
+ id: `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
970
+ session: caller.session,
971
+ agent: caller.agent,
972
+ what,
973
+ source,
974
+ condition,
975
+ never: args.never === true,
976
+ until,
977
+ };
978
+ writeJson(
979
+ path.join(expectationsRoot(), `${expectation.id}.json`),
980
+ expectation
981
+ );
982
+ arm(expectation);
983
+ return armed.has(expectation.id)
984
+ ? {
985
+ ok: true,
986
+ answer: `Kept until ${hhmm(until)}: ${thingOf(source)}, ${expectation.never ? "not" : "expected"} ${whenOf(source, condition).replace(/^when /, "")}. Silence means it went as you expect; you hear it only if it does not.`,
987
+ }
988
+ : {
989
+ ok: true,
990
+ answer: expectation.never
991
+ ? `It is already so: ${thingOf(source)} ${whenOf(source, condition).replace(/^when /, "")}. You were told.`
992
+ : `It is already so: ${thingOf(source)} ${whenOf(source, condition).replace(/^when /, "")}.`,
993
+ };
994
+ };
995
+
996
+ // --- try (S4.7c): a change tried in a copy, felt, before the real one ---
997
+
998
+ const triesRoot = () => path.join(home, "senses", "tries");
999
+ const tryTimers = new Map();
1000
+ // Folders a copy leaves out of its comparison: dependencies and git's own.
1001
+ const NOT_COMPARED = new Set(["node_modules", ".git"]);
1002
+ const TRY_MOST_NAMED = 12;
1003
+
1004
+ // A copy that costs nothing until its files change where the disk can (an APFS clone on a Mac, a reflink on Linux),
1005
+ // a plain copy elsewhere; times kept, so what changed in it shows.
1006
+ const copyFolder = (from, to) => {
1007
+ fs.mkdirSync(to, { recursive: true, mode: 0o700 });
1008
+ try {
1009
+ if (process.platform === "darwin")
1010
+ execFileSync("/bin/cp", ["-c", "-R", "-p", `${from}/.`, to], {
1011
+ stdio: "ignore",
1012
+ });
1013
+ else if (process.platform === "linux")
1014
+ execFileSync("cp", ["-a", "--reflink=auto", `${from}/.`, to], {
1015
+ stdio: "ignore",
1016
+ });
1017
+ else throw new Error("no clone here");
1018
+ } catch {
1019
+ fs.cpSync(from, to, { recursive: true, preserveTimestamps: true });
1020
+ }
1021
+ };
1022
+
1023
+ // Every file under a folder but the ones not compared, with its size and time.
1024
+ const filesIn = (root) => {
1025
+ const found = new Map();
1026
+ const walk = (dir) => {
1027
+ let entries = [];
1028
+ try {
1029
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1030
+ } catch {
1031
+ return;
1032
+ }
1033
+ for (const entry of entries) {
1034
+ if (NOT_COMPARED.has(entry.name)) continue;
1035
+ const full = path.join(dir, entry.name);
1036
+ if (entry.isDirectory()) walk(full);
1037
+ else if (entry.isFile()) {
1038
+ const stat = fs.statSync(full);
1039
+ found.set(path.relative(root, full), {
1040
+ size: stat.size,
1041
+ mtimeMs: stat.mtimeMs,
1042
+ });
1043
+ }
1044
+ }
1045
+ };
1046
+ walk(root);
1047
+ return found;
1048
+ };
1049
+ const sameFile = (a, b) => {
1050
+ try {
1051
+ return fs.readFileSync(a).equals(fs.readFileSync(b));
1052
+ } catch {
1053
+ return false;
1054
+ }
1055
+ };
1056
+
1057
+ const endTry = (id, why = null) => {
1058
+ const record = readJson(path.join(triesRoot(), `${id}.json`), null);
1059
+ clearTimeout(tryTimers.get(id));
1060
+ tryTimers.delete(id);
1061
+ if (!record) return null;
1062
+ const original = filesIn(record.folder);
1063
+ const copy = filesIn(record.dir);
1064
+ const added = [...copy.keys()].filter((rel) => !original.has(rel));
1065
+ const removed = [...original.keys()].filter((rel) => !copy.has(rel));
1066
+ const changed = [...copy.keys()].filter((rel) => {
1067
+ const before = original.get(rel);
1068
+ const after = copy.get(rel);
1069
+ if (!before) return false;
1070
+ if (before.size === after.size && before.mtimeMs === after.mtimeMs)
1071
+ return false;
1072
+ return !sameFile(
1073
+ path.join(record.folder, rel),
1074
+ path.join(record.dir, rel)
1075
+ );
1076
+ });
1077
+ fs.rmSync(record.dir, { recursive: true, force: true, maxRetries: 3 });
1078
+ fs.rmSync(path.join(triesRoot(), `${id}.json`), { force: true });
1079
+ const list = (label, rels) =>
1080
+ rels.length
1081
+ ? `${label} ${rels.slice(0, TRY_MOST_NAMED).join(", ")}${rels.length > TRY_MOST_NAMED ? ` and ${rels.length - TRY_MOST_NAMED} more` : ""}`
1082
+ : null;
1083
+ const parts = [
1084
+ list("changed", changed),
1085
+ list("added", added),
1086
+ list("removed", removed),
1087
+ ].filter(Boolean);
1088
+ events.append({
1089
+ source: "senses",
1090
+ kind: "try ended",
1091
+ subject: `session:${record.session}`,
1092
+ text: `a try in a copy ended${why ? ` (${why})` : ""}: ${changed.length} changed, ${added.length} added, ${removed.length} removed`,
1093
+ });
1094
+ return `Against ${record.folder}, the copy ${parts.length ? parts.join("; ") : "is the same"}. It is deleted${why ? ` (${why})` : ""}.`;
1095
+ };
1096
+
1097
+ const armTry = (record) => {
1098
+ const timer = setTimeout(
1099
+ () => {
1100
+ const said = endTry(record.id, "its time ran out");
1101
+ if (said && record.session)
1102
+ tell(record.session, `Your try ${record.id} ended: ${said}`);
1103
+ },
1104
+ Math.max(0, Date.parse(record.until) - now())
1105
+ );
1106
+ timer.unref?.();
1107
+ tryTimers.set(record.id, timer);
1108
+ };
1109
+
1110
+ const startTry = (caller, { files, diff, minutes }) => {
1111
+ if (!caller.session || !caller.folder)
1112
+ return {
1113
+ ok: false,
1114
+ error: "Harness has not seen this session make a tool call yet",
1115
+ };
1116
+ const id = crypto.randomUUID().slice(0, 8);
1117
+ const dir = path.join(os.tmpdir(), `harness-try-${id}`);
1118
+ copyFolder(caller.folder, dir);
1119
+ const put = [];
1120
+ try {
1121
+ for (const [rel, content] of Object.entries(files ?? {})) {
1122
+ const target = path.resolve(dir, rel);
1123
+ if (path.relative(dir, target).startsWith(".."))
1124
+ throw new Error(`${rel} is outside the folder`);
1125
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1126
+ fs.writeFileSync(target, String(content));
1127
+ put.push(path.relative(dir, target));
1128
+ }
1129
+ if (typeof diff === "string" && diff.trim())
1130
+ execFileSync("git", ["apply", "--whitespace=nowarn", "-"], {
1131
+ cwd: dir,
1132
+ input: diff,
1133
+ stdio: ["pipe", "ignore", "pipe"],
1134
+ });
1135
+ } catch (error) {
1136
+ fs.rmSync(dir, { recursive: true, force: true });
1137
+ const said = String(error.stderr ?? error.message)
1138
+ .trim()
1139
+ .split("\n")[0];
1140
+ return { ok: false, error: `the change did not apply: ${said}` };
1141
+ }
1142
+ const lasts = Math.min(24 * 60, Math.max(0.1, Number(minutes) || 60));
1143
+ const record = {
1144
+ id,
1145
+ session: caller.session,
1146
+ folder: caller.folder,
1147
+ dir,
1148
+ at: new Date(now()).toISOString(),
1149
+ until: new Date(now() + lasts * 60_000).toISOString(),
1150
+ };
1151
+ writeJson(path.join(triesRoot(), `${id}.json`), record);
1152
+ armTry(record);
1153
+ return {
1154
+ ok: true,
1155
+ try: { id, path: dir, until: record.until },
1156
+ answer: `A copy of ${caller.folder} is at ${dir}${put.length || diff ? ", with your change" : ""}. Run what you want there with your own tools; try {end: "${id}"} tells you how it differs from the real folder and deletes it. Left alone, it is deleted at ${hhmm(record.until)}.`,
1157
+ };
1158
+ };
1159
+
1160
+ const COMMANDS = {
1161
+ "senses.look": (request) => {
1162
+ const caller = callerOf(request);
1163
+ if (request.release) {
1164
+ if (!reflexes) return { ok: false, error: "no reflex runs here" };
1165
+ const by =
1166
+ request.agent === "user"
1167
+ ? "user"
1168
+ : caller.agent || String(request.agent ?? "");
1169
+ const released = reflexes.release(request.release, {
1170
+ by,
1171
+ reason: request.reason,
1172
+ });
1173
+ return released.ok
1174
+ ? { ok: true, answer: "Let go; your reason is kept with it." }
1175
+ : released;
1176
+ }
1177
+ if (request.volume) {
1178
+ if (!caller.session)
1179
+ return {
1180
+ ok: false,
1181
+ error: "Harness has not seen this session make a tool call yet",
1182
+ };
1183
+ if (!setVolume(caller.session, request.volume, home))
1184
+ return { ok: false, error: 'volume is "normal" or "quiet"' };
1185
+ }
1186
+ if (request.at) return zoom(request.at);
1187
+ if (request.about || request.since || request.until || request.sources)
1188
+ return question(caller, request);
1189
+ return { ok: true, answer: glance(caller) };
1190
+ },
1191
+ "senses.wish": (request) => wish(callerOf(request), request),
1192
+ "senses.wishes": () => wishes(),
1193
+ // The person's: what reflexes hold or pause now, and letting one go.
1194
+ "senses.reflexes": (request) =>
1195
+ request.agent === "user"
1196
+ ? { ok: true, reflexes: reflexes?.active() ?? [] }
1197
+ : { ok: false, error: "the person's list" },
1198
+ "senses.release": (request) =>
1199
+ request.agent === "user"
1200
+ ? (reflexes?.release(request.id, {
1201
+ by: "user",
1202
+ reason: request.reason,
1203
+ }) ?? { ok: false, error: "no reflex runs here" })
1204
+ : {
1205
+ ok: false,
1206
+ error: "an agent lets one go with look {release, reason}",
1207
+ },
1208
+ "senses.ask": (request) => ask(callerOf(request), request),
1209
+ // How long something takes, from the time table on this computer (timeSense.mjs, Phase T.8).
1210
+ "senses.how_long": (request) => {
1211
+ const caller = callerOf(request);
1212
+ return {
1213
+ ok: true,
1214
+ answer: howLong(
1215
+ {
1216
+ session: caller.session,
1217
+ cwd: caller.folder,
1218
+ command:
1219
+ typeof request.asked === "string" && request.asked.trim()
1220
+ ? request.asked
1221
+ : null,
1222
+ },
1223
+ home
1224
+ ),
1225
+ };
1226
+ },
1227
+ "senses.pointers": (request) =>
1228
+ request.agent === "user"
1229
+ ? pointers()
1230
+ : { ok: false, error: "the person's list" },
1231
+ "senses.this": (request) => personPoints(request),
1232
+ // The request's own command is the daemon's; what the agent named is the rest.
1233
+ "senses.try": (request) => {
1234
+ if (request.end) {
1235
+ const said = endTry(String(request.end));
1236
+ return said
1237
+ ? { ok: true, answer: said }
1238
+ : { ok: false, error: `no try named ${request.end}` };
1239
+ }
1240
+ return startTry(callerOf(request), request);
1241
+ },
1242
+ "senses.expect": ({
1243
+ command: _command,
1244
+ agent: _agent,
1245
+ agentPid: _pid,
1246
+ cwd: _cwd,
1247
+ ...named
1248
+ }) => expect(callerOf({ agent: _agent, agentPid: _pid, cwd: _cwd }), named),
1249
+ };
1250
+
1251
+ return {
1252
+ handles: (command) => Object.hasOwn(COMMANDS, command),
1253
+ run: (request) => COMMANDS[request.command](request),
1254
+ /**
1255
+ * The line about this computer a woken agent reads (wakePicture.mjs). Pace stays in the glance: a wake reads only
1256
+ * what touches its thread, never the person's presence (owner, November 13: "yes only what touches the thread").
1257
+ */
1258
+ card: (agent) => [machineCard(), mayLine(agent)].join("\n"),
1259
+ /** Arms again the expectations kept on the computer; one whose time ran out while Harness was off is let go. */
1260
+ start() {
1261
+ // Tries too: one whose time ran out while Harness was off ends now.
1262
+ let tries = [];
1263
+ try {
1264
+ tries = fs
1265
+ .readdirSync(triesRoot())
1266
+ .filter((name) => name.endsWith(".json"));
1267
+ } catch {}
1268
+ for (const name of tries) {
1269
+ const record = readJson(path.join(triesRoot(), name), null);
1270
+ if (record) armTry(record);
1271
+ else fs.rmSync(path.join(triesRoot(), name), { force: true });
1272
+ }
1273
+ let names = [];
1274
+ try {
1275
+ names = fs
1276
+ .readdirSync(expectationsRoot())
1277
+ .filter((name) => name.endsWith(".json"));
1278
+ } catch {}
1279
+ for (const name of names) {
1280
+ const expectation = readJson(path.join(expectationsRoot(), name), null);
1281
+ if (!expectation || Date.parse(expectation.until) <= now()) {
1282
+ fs.rmSync(path.join(expectationsRoot(), name), { force: true });
1283
+ continue;
1284
+ }
1285
+ arm(expectation);
1286
+ }
1287
+ },
1288
+ stop() {
1289
+ for (const timer of tryTimers.values()) clearTimeout(timer);
1290
+ tryTimers.clear();
1291
+ for (const [, kept] of armed) {
1292
+ kept.stop?.();
1293
+ clearTimeout(kept.timer);
1294
+ }
1295
+ armed.clear();
1296
+ },
1297
+ };
1298
+ }