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,578 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createPublicFetch, publicNetwork } from "./publicFetch.js";
3
+ import {
4
+ DEFAULT_PERSONA,
5
+ actLine,
6
+ cardOf,
7
+ firstSentence,
8
+ leftOutLines,
9
+ nameOf,
10
+ } from "./placeCards.mjs";
11
+ import { checkWrite } from "./placeChecks.mjs";
12
+ import {
13
+ buildRequest,
14
+ linksIn,
15
+ sendRequest,
16
+ takeIssuedKey,
17
+ } from "./placeRequests.mjs";
18
+ import { createPlaceStore } from "./placeStore.mjs";
19
+ import { secretReason } from "./secrets.mjs";
20
+
21
+ // Places at outside networks (owner, November 14: they live on the person's home computer, as automations do): the outside networks the
22
+ // person's swarm joins. The person adds a place from any skill file, looks at its card, joins, says what the swarm may
23
+ // do there and decides what waits for them; agents list the places their swarm is in, read there and write there. Every
24
+ // surface reaches it here: the dashboard, the PiP and the phone sealed from the person's browser, the buddy on this
25
+ // computer, agents here on their own socket and agents on the person's other computers through home, outside agents
26
+ // and Harness's own turns through Harness's server. This computer keeps each place's key in the vault and makes every
27
+ // request, through the outbound guard, so no agent ever holds a key or reaches a place directly.
28
+ //
29
+ // Harness's server keeps none of it. It is asked for what takes a model (reading a skill file into a place, matching a
30
+ // sign-up's fields, judging whether a write says something private) and keeps only how many swarms are in a place,
31
+ // shown to others past a minimum and never who (src/server/places/serverHalf.ts).
32
+
33
+ const ALLOWED = new Set(["read", "drafts", "own"]);
34
+ const PERSON_OPS = new Set([
35
+ "list",
36
+ "add",
37
+ "offer",
38
+ "show",
39
+ "join",
40
+ "leave",
41
+ "allow",
42
+ "persona",
43
+ "limit",
44
+ "accept",
45
+ "decide",
46
+ ]);
47
+ const MODEL_ID = "harness-swarm";
48
+ // Measured on 1f916.ai's GET /api/pulse from the owner's Mac, October 20 (10 samples): median 0.24 s, slowest 0.69 s.
49
+ // 15 s leaves 20 times the slowest; a place slower than that is checked again at its next time.
50
+ export const CHECK_DEADLINE_MS = 15_000;
51
+ // How often due places are looked for: a check-in is every 30 minutes or more, so a minute late is nothing.
52
+ const CHECK_TICK_MS = 60_000;
53
+ // What of a new check-in answer is kept for the person and their agents to see.
54
+ const NEWS_CHARS = 2_000;
55
+
56
+ const fail = (error) => ({ ok: false, error });
57
+
58
+ // The shape of a place Harness's server read (src/server/places/definition.ts), checked before it is kept.
59
+ const readablePlace = (compiled) => {
60
+ const definition = compiled?.definition;
61
+ try {
62
+ return (
63
+ ["join", "join_with_drops"].includes(compiled.verdict) &&
64
+ Array.isArray(compiled.findings) &&
65
+ new URL(definition.origin).protocol === "https:" &&
66
+ new URL(definition.origin).origin === definition.origin &&
67
+ /^[0-9a-f]{64}$/.test(definition.fingerprint) &&
68
+ typeof definition.source === "string" &&
69
+ Array.isArray(definition.actions) &&
70
+ Array.isArray(definition.join) &&
71
+ Array.isArray(definition.rules)
72
+ );
73
+ } catch {
74
+ return false;
75
+ }
76
+ };
77
+ const ref = (value) =>
78
+ String(value ?? "")
79
+ .trim()
80
+ .slice(0, 300);
81
+
82
+ /**
83
+ * `db`: this computer's SQLite. `keys`: the vault's place keys (vault.mjs placeKeys). `askServer(kind, input)`: one of
84
+ * the server's place calls (serverHalf.ts), resolving to its answer or rejecting. `fetch`: through the outbound guard
85
+ * by default.
86
+ */
87
+ export function createNetworkPlaces({
88
+ db,
89
+ keys,
90
+ askServer,
91
+ fetch: fetchImpl = createPublicFetch(publicNetwork, {
92
+ httpsOnly: true,
93
+ who: "Harness",
94
+ }),
95
+ log = () => {},
96
+ }) {
97
+ const store = createPlaceStore(db);
98
+ const live = (id) => {
99
+ const place = store.get(id);
100
+ return place && place.status !== "left" ? place : null;
101
+ };
102
+ const tellServer = (place, joined) =>
103
+ askServer("member", {
104
+ origin: place.origin,
105
+ name: place.name,
106
+ source: place.source,
107
+ joined,
108
+ }).catch((error) =>
109
+ log(
110
+ `places: Harness did not hear ${place.origin} ${joined ? "joined" : "left"}: ${error.message}`
111
+ )
112
+ );
113
+
114
+ /** One op, as `actor`: "user" (the person), "harness" (Harness's own turn) or an agent's name. */
115
+ async function op(input, actor) {
116
+ const name = String(input?.op ?? "");
117
+ // Harness, the person's own assistant, may read a place's skill file into a card for them to look at; joining and
118
+ // everything after it is the person's alone.
119
+ const prepares =
120
+ (name === "add" || name === "offer") && actor === "harness";
121
+ if (PERSON_OPS.has(name) && actor !== "user" && !prepares)
122
+ return fail("only the person does that, in Places");
123
+ switch (name) {
124
+ case "list": {
125
+ const places = store.list();
126
+ const byId = new Map(places.map((place) => [place.id, place]));
127
+ const popular = await askServer("popular", {}).catch(() => ({
128
+ places: [],
129
+ }));
130
+ return {
131
+ ok: true,
132
+ places: places.map((place) => cardOf(place)),
133
+ waiting: store.held().map((act) => {
134
+ const place = byId.get(act.place_id) ?? null;
135
+ return {
136
+ ...actLine(act, place),
137
+ place: place ? nameOf(place) : "",
138
+ site: place ? new URL(place.origin).host : "",
139
+ placeId: act.place_id,
140
+ };
141
+ }),
142
+ popular: (popular.places ?? []).filter(
143
+ (one) => !places.some((place) => place.origin === one.origin)
144
+ ),
145
+ };
146
+ }
147
+ // A skill file read into a place here (the buddy), or one already read on Harness's server by the person's
148
+ // browser or Harness's own turn, which have no deadline of this computer's to wait within.
149
+ case "add": {
150
+ const url = String(input.url ?? "").slice(0, 2_000);
151
+ const text =
152
+ typeof input.text === "string"
153
+ ? input.text.slice(0, 600_000)
154
+ : undefined;
155
+ const compiled = await askServer("compile", {
156
+ url,
157
+ ...(text !== undefined ? { text } : {}),
158
+ }).catch((error) => ({ failed: error.message }));
159
+ if (compiled.failed)
160
+ return fail(`Harness could not read that place: ${compiled.failed}`);
161
+ return offered(compiled);
162
+ }
163
+ case "offer":
164
+ return offered(input.compiled);
165
+ case "show": {
166
+ const place = live(ref(input.id));
167
+ if (!place) return fail("no such place");
168
+ store.seen(place.id);
169
+ return { ok: true, place: cardOf(place, store.acts(place.id)) };
170
+ }
171
+ case "join":
172
+ return join(ref(input.id), input.name);
173
+ case "leave": {
174
+ const place = live(ref(input.id));
175
+ if (!place) return fail("no such place");
176
+ const wasJoined = place.status === "joined";
177
+ store.left(place.id);
178
+ await keys.forget(place.origin);
179
+ // Drafts waiting there are dropped; what already went out stays at the place.
180
+ store.discardHeld(place.id);
181
+ if (wasJoined) void tellServer(place, false);
182
+ return { ok: true };
183
+ }
184
+ case "allow": {
185
+ const place = live(ref(input.id));
186
+ if (!place) return fail("no such place");
187
+ if (place.status !== "joined") return fail("join the place first");
188
+ if (!ALLOWED.has(input.allowed)) return fail("invalid request");
189
+ return {
190
+ ok: true,
191
+ place: cardOf(store.setAllowed(place.id, input.allowed)),
192
+ };
193
+ }
194
+ case "persona": {
195
+ const place = live(ref(input.id));
196
+ if (!place) return fail("no such place");
197
+ const persona = String(input.persona ?? "")
198
+ .trim()
199
+ .slice(0, 600);
200
+ return { ok: true, place: cardOf(store.setPersona(place.id, persona)) };
201
+ }
202
+ case "limit": {
203
+ const place = live(ref(input.id));
204
+ if (!place) return fail("no such place");
205
+ const writes = Number(input.writesPerDay);
206
+ if (!Number.isInteger(writes) || writes < 0 || writes > 50)
207
+ return fail("invalid request");
208
+ return {
209
+ ok: true,
210
+ place: cardOf(store.setWritesPerDay(place.id, writes)),
211
+ };
212
+ }
213
+ case "accept": {
214
+ const place = live(ref(input.id));
215
+ if (!place?.pending) return fail("nothing new to accept");
216
+ return { ok: true, place: cardOf(store.acceptPending(place.id)) };
217
+ }
218
+ case "decide":
219
+ return decide(ref(input.act), input.send === true, input.edited);
220
+ case "places":
221
+ return {
222
+ ok: true,
223
+ places: store
224
+ .list()
225
+ .filter((place) => place.status === "joined")
226
+ .map(forAgents),
227
+ };
228
+ case "do":
229
+ return act(
230
+ ref(input.place),
231
+ String(input.action ?? "")
232
+ .trim()
233
+ .slice(0, 400),
234
+ input.values && typeof input.values === "object" ? input.values : {},
235
+ actor
236
+ );
237
+ default:
238
+ return fail("invalid request");
239
+ }
240
+ }
241
+
242
+ // A place as Harness's server read it (serverHalf.ts compile): the person's to look at, unless it cannot be joined.
243
+ const offered = (compiled) => {
244
+ if (compiled?.verdict === "refused")
245
+ return {
246
+ ok: true,
247
+ refused: String(compiled.reason ?? ""),
248
+ leftOut: leftOutLines(
249
+ Array.isArray(compiled.findings) ? compiled.findings : []
250
+ ),
251
+ };
252
+ if (!readablePlace(compiled))
253
+ return fail("that is not a place Harness read");
254
+ return { ok: true, place: cardOf(store.offer(compiled)) };
255
+ };
256
+
257
+ // A place as an agent reads it: what it may do there and every request it can make.
258
+ const forAgents = (place) => ({
259
+ place: nameOf(place),
260
+ id: place.id,
261
+ origin: place.origin,
262
+ you: place.member_name,
263
+ persona: place.persona || DEFAULT_PERSONA,
264
+ mayDo:
265
+ place.allowed === "read"
266
+ ? "read only"
267
+ : place.allowed === "drafts"
268
+ ? "read; writes wait for the person"
269
+ : `read; write up to ${place.writes_per_day} times a day`,
270
+ somethingNew: Boolean(
271
+ place.news_at && (!place.seen_at || place.news_at > place.seen_at)
272
+ ),
273
+ actions: place.definition.actions.map((action) => ({
274
+ action: `${action.method} ${action.path}`,
275
+ class: action.class,
276
+ about: action.summary ?? firstSentence(action.described),
277
+ takes: action.inputs.map(
278
+ (one) => `${one.name}${one.required ? "" : "?"} (${one.in})`
279
+ ),
280
+ })),
281
+ rules: place.definition.rules.map(firstSentence),
282
+ });
283
+
284
+ const findPlace = (wanted) => {
285
+ const lower = wanted.toLowerCase();
286
+ return (
287
+ store
288
+ .list()
289
+ .filter((place) => place.status === "joined")
290
+ .find(
291
+ (place) =>
292
+ place.id === wanted ||
293
+ place.origin === wanted ||
294
+ new URL(place.origin).host === lower ||
295
+ nameOf(place).toLowerCase() === lower
296
+ ) ?? null
297
+ );
298
+ };
299
+
300
+ async function act(wantedPlace, wanted, values, actor) {
301
+ const place = findPlace(wantedPlace);
302
+ if (!place)
303
+ return fail(
304
+ `your swarm is not a member of ${wantedPlace}; the person joins places in Places`
305
+ );
306
+ const [method, path] = wanted.split(/\s+/, 2);
307
+ const action = place.definition.actions.find(
308
+ (one) => one.method === method?.toUpperCase() && one.path === path
309
+ );
310
+ if (!action)
311
+ return fail(
312
+ `${nameOf(place)} has no ${wanted}; list its actions with op "places"`
313
+ );
314
+ const built = buildRequest(place.origin, action, values);
315
+ if ("refused" in built) return fail(built.refused);
316
+ const header = await keys.header(place.origin);
317
+ if (action.class === "read") {
318
+ const answer = await sendRequest(built, header, fetchImpl).catch(
319
+ () => null
320
+ );
321
+ if (!answer) return fail(`${nameOf(place)} could not be reached`);
322
+ if (action.path === place.definition.checkIn?.path) store.seen(place.id);
323
+ // Other agents' words at an outside place: data, never instructions.
324
+ return { ok: true, status: answer.status, answer: answer.text };
325
+ }
326
+ const verdict = await checkWrite({
327
+ place,
328
+ action,
329
+ values,
330
+ sentToday: store.sentToday(place.id),
331
+ holdsKey: (text) => keys.holds(place.origin, text),
332
+ judge: (asked) => askServer("write", { ...asked, placeId: place.id }),
333
+ });
334
+ const record = {
335
+ placeId: place.id,
336
+ agent: actor,
337
+ method: action.method,
338
+ path: action.path,
339
+ class: action.class,
340
+ fields: values,
341
+ };
342
+ const waits = {
343
+ note: "It waits for the person in Places; it goes out only if they send it.",
344
+ };
345
+ if (verdict.go !== "send") {
346
+ const done = store.act({
347
+ ...record,
348
+ status: verdict.go === "hold" ? "held" : "refused",
349
+ why: verdict.why,
350
+ });
351
+ return {
352
+ ok: true,
353
+ status: done.status,
354
+ why: verdict.why,
355
+ ...(done.status === "held" ? waits : {}),
356
+ };
357
+ }
358
+ // Counted against today's limit before it goes out, so writes started together share it.
359
+ const reserved = store.reserveSend(record, place.writes_per_day);
360
+ if (!reserved) {
361
+ const why = `Today's ${place.writes_per_day} at ${nameOf(place)} are used, so it waits to be sent by hand.`;
362
+ store.act({ ...record, status: "held", why });
363
+ return { ok: true, status: "held", why, ...waits };
364
+ }
365
+ const answer = await sendRequest(built, header, fetchImpl).catch(
366
+ () => null
367
+ );
368
+ store.recordOutcome(
369
+ reserved.id,
370
+ answer && answer.status < 400 ? "sent" : "failed",
371
+ answer?.status ?? null,
372
+ answer?.text ?? "unreachable"
373
+ );
374
+ if (!answer) return fail(`${nameOf(place)} could not be reached`);
375
+ return { ok: true, status: answer.status, answer: answer.text };
376
+ }
377
+
378
+ async function decide(actId, send, edited) {
379
+ const found = store.getAct(actId);
380
+ if (!found || found.status !== "held") return fail("nothing waits there");
381
+ const edits =
382
+ edited && typeof edited === "object"
383
+ ? Object.fromEntries(
384
+ Object.entries(edited).map(([field, value]) => [
385
+ String(field).slice(0, 64),
386
+ String(value).slice(0, 8_000),
387
+ ])
388
+ )
389
+ : null;
390
+ if (edits && Object.keys(edits).some((field) => !(field in found.fields)))
391
+ return fail("an edit can only change the draft's own words");
392
+ const held = edits
393
+ ? { ...found, fields: { ...found.fields, ...edits } }
394
+ : found;
395
+ if (!send) {
396
+ store.decided(held.id, "discarded", null, null);
397
+ return { ok: true, status: "discarded" };
398
+ }
399
+ const place = store.get(held.place_id);
400
+ const action = place?.definition.actions.find(
401
+ (one) => one.method === held.method && one.path === held.path
402
+ );
403
+ if (!place || place.status !== "joined" || !action)
404
+ return fail("that place or request is gone");
405
+ // The person's send still never carries a secret or the place's own key; the day's limit is on what goes out on
406
+ // its own, and the person sending it is their own decision.
407
+ const text = JSON.stringify(held.fields);
408
+ if ((await keys.holds(place.origin, text)) || secretReason(text))
409
+ return fail("it carries a key or secret, so it cannot go");
410
+ const built = buildRequest(place.origin, action, held.fields);
411
+ if ("refused" in built) return fail(built.refused);
412
+ const header = await keys.header(place.origin);
413
+ if (edits) store.editFields(held.id, held.fields);
414
+ // Taken before it goes out: a second click, or another device, finds it already decided.
415
+ if (!store.claimHeld(held.id))
416
+ return fail("it was already sent or discarded");
417
+ const answer = await sendRequest(built, header, fetchImpl).catch(
418
+ () => null
419
+ );
420
+ const ok = Boolean(answer && answer.status < 400);
421
+ store.recordOutcome(
422
+ held.id,
423
+ ok ? "sent" : "failed",
424
+ answer?.status ?? null,
425
+ answer?.text ?? "unreachable"
426
+ );
427
+ return ok
428
+ ? { ok: true, status: "sent" }
429
+ : fail(
430
+ `${nameOf(place)} did not take it (${answer?.status ?? "unreachable"})`
431
+ );
432
+ }
433
+
434
+ async function join(id, wantedName) {
435
+ const place = live(id);
436
+ if (!place) return fail("no such place");
437
+ if (place.status === "joined") return { ok: true, place: cardOf(place) };
438
+ const definition = place.definition;
439
+ const step = definition.join.find((one) => one.kind === "request");
440
+ const asked =
441
+ typeof wantedName === "string" ? wantedName.trim().slice(0, 32) : "";
442
+ const persona = place.persona || DEFAULT_PERSONA;
443
+ if (!step) {
444
+ const memberName =
445
+ asked ||
446
+ (await askServer("signup", { fields: [] }).catch(() => ({}))).handle ||
447
+ `swarm-${randomBytes(3).toString("hex")}`;
448
+ const done = store.joined(place.id, memberName, persona);
449
+ void tellServer(done, true);
450
+ return { ok: true, place: cardOf(done) };
451
+ }
452
+ const action = definition.actions.find(
453
+ (one) => one.method === step.method && one.path === step.path
454
+ );
455
+ if (!action) return fail("the place's sign-up request is missing");
456
+ const fields = action.inputs.filter((input) => input.in !== "path");
457
+ // Which of the sign-up's fields asks for the swarm's name, model or persona: a model's judgment, on the server,
458
+ // which also knows the person's handle there.
459
+ const signup = await askServer("signup", {
460
+ fields: fields.map((one) => ({
461
+ name: one.name,
462
+ about: one.about ?? null,
463
+ })),
464
+ path: action.path,
465
+ }).catch(() => null);
466
+ const memberName =
467
+ asked || signup?.handle || `swarm-${randomBytes(3).toString("hex")}`;
468
+ const values = {};
469
+ for (const field of fields) {
470
+ const picked = signup?.picks?.[field.name];
471
+ const value =
472
+ picked === "member_name"
473
+ ? memberName
474
+ : picked === "model"
475
+ ? MODEL_ID
476
+ : picked === "persona"
477
+ ? persona
478
+ : undefined;
479
+ if (value !== undefined) values[field.name] = value;
480
+ else if (field.required)
481
+ return fail(
482
+ `${nameOf(place)} asks for ${field.name} to join, and Harness cannot tell what to give. Ask one of your agents to read how to join there.`
483
+ );
484
+ }
485
+ const built = buildRequest(place.origin, action, values);
486
+ if ("refused" in built) return fail(built.refused);
487
+ const answer = await sendRequest(built, null, fetchImpl).catch(() => null);
488
+ if (!answer) return fail(`${nameOf(place)} could not be reached`);
489
+ const issued = takeIssuedKey(answer.text);
490
+ store.act({
491
+ placeId: place.id,
492
+ agent: "user",
493
+ method: action.method,
494
+ path: action.path,
495
+ class: action.class,
496
+ fields: values,
497
+ status: answer.status < 400 ? "sent" : "failed",
498
+ answerStatus: answer.status,
499
+ answer: issued.masked,
500
+ });
501
+ if (answer.status >= 400)
502
+ return fail(
503
+ `${nameOf(place)} did not take the sign-up (${answer.status}): ${issued.masked.slice(0, 300)}`
504
+ );
505
+ if (definition.signIn === "bearer" && !issued.key)
506
+ return fail(`${nameOf(place)} signed your swarm up but gave back no key`);
507
+ if (issued.key) {
508
+ const saved = await keys.save(place.origin, issued.key);
509
+ if (saved?.ok === false) return fail(saved.error);
510
+ }
511
+ const done = store.joined(place.id, memberName, persona);
512
+ void tellServer(done, true);
513
+ return {
514
+ ok: true,
515
+ place: cardOf(done),
516
+ // What the place asked of the person after sign-up (a claim post, an email), with the links its answer gave.
517
+ yourPart: definition.join.filter((one) => one.kind === "person"),
518
+ links: linksIn(issued.masked, place.origin),
519
+ };
520
+ }
521
+
522
+ // Check-ins: every joined place's cheap "anything new?" request, on its own cadence. A quiet place (304, or the same
523
+ // answer as last time) costs one request and nothing else; one with something new records it on the place, where
524
+ // the person and their agents see it. No model is woken: acting on news is the person's or an agent's choice.
525
+ async function checkIn(place) {
526
+ const header = await keys.header(place.origin);
527
+ const response = await fetchImpl(
528
+ new URL(place.definition.checkIn.path, place.origin),
529
+ {
530
+ method: "GET",
531
+ redirect: "manual",
532
+ signal: AbortSignal.timeout(CHECK_DEADLINE_MS),
533
+ headers: {
534
+ accept: "application/json",
535
+ ...(place.check_etag ? { "if-none-match": place.check_etag } : {}),
536
+ ...(header ? { [header[0]]: header[1] } : {}),
537
+ },
538
+ }
539
+ ).catch(() => null);
540
+ if (!response || response.status === 304 || !response.ok) {
541
+ store.checked(place.id);
542
+ return;
543
+ }
544
+ const text = (await response.text()).slice(0, NEWS_CHARS);
545
+ const hash = createHash("sha256").update(text).digest("hex");
546
+ // The first answer after joining is where the place stands, not news; news is an answer that changed since.
547
+ store.checked(place.id, {
548
+ etag: response.headers.get("etag"),
549
+ news: { text, hash },
550
+ isNew: place.news !== null && place.news?.hash !== hash,
551
+ });
552
+ }
553
+ let checking = false;
554
+ const checkDue = async () => {
555
+ if (checking) return 0;
556
+ checking = true;
557
+ try {
558
+ const due = store.due();
559
+ await Promise.all(due.map((place) => checkIn(place)));
560
+ return due.length;
561
+ } finally {
562
+ checking = false;
563
+ }
564
+ };
565
+ /** Runs check-ins while this computer is the person's home; returns the stop. */
566
+ const startCheckIns = (isHome) => {
567
+ const timer = setInterval(() => {
568
+ if (isHome())
569
+ void checkDue().catch((error) =>
570
+ log(`places: check-ins failed: ${error.message}`)
571
+ );
572
+ }, CHECK_TICK_MS);
573
+ timer.unref?.();
574
+ return () => clearInterval(timer);
575
+ };
576
+
577
+ return { op, checkDue, startCheckIns };
578
+ }
@@ -0,0 +1,95 @@
1
+ // The next intended step (docs/senses-plan.md S3.5): an agent ends a thread turn that leaves work for later with one
2
+ // line, "Next: what it means to do next", at the end of its last message, as "Deciding:" names what the person is
3
+ // asked (threadLine.mjs). Harness keeps it for the agent's next turn in the thread (wakePicture.mjs) and keeps it out
4
+ // of the thread itself (owner, November 13: "i just dont want the thread to become too polluted with text"). A turn
5
+ // that ends without one has none: a stale plan misleads (owner, the same day).
6
+
7
+ const NEXT = /^\s*[*_]*next:[*_]*\s*(.+?)\s*$/i;
8
+ const DECIDING = /^\s*[*_]*deciding:/i;
9
+ // A step is one line, not a plan.
10
+ const STEP_CHARS = 300;
11
+
12
+ /** Where a message's "Next:" line is: its last line, or the one before a closing "Deciding:" line; -1 when none. */
13
+ const lineOfNext = (lines) => {
14
+ for (let i = lines.length - 1; i >= 0; i--) {
15
+ if (!lines[i].trim() || DECIDING.test(lines[i])) continue;
16
+ return NEXT.test(lines[i]) ? i : -1;
17
+ }
18
+ return -1;
19
+ };
20
+
21
+ /** The step a message says comes next, or null. */
22
+ export function nextStepOf(text) {
23
+ const lines = String(text ?? "").split("\n");
24
+ const at = lineOfNext(lines);
25
+ if (at < 0) return null;
26
+ const step = NEXT.exec(lines[at])[1]
27
+ .replace(/^[`*_"]+|[`*_"]+$/g, "")
28
+ .trim();
29
+ return step ? step.slice(0, STEP_CHARS) : null;
30
+ }
31
+
32
+ /** A message without its "Next:" line, as the thread shows it. */
33
+ export function withoutNextStep(text) {
34
+ const whole = String(text ?? "");
35
+ const lines = whole.split("\n");
36
+ const at = lineOfNext(lines);
37
+ if (at < 0) return whole;
38
+ return [...lines.slice(0, at), ...lines.slice(at + 1)].join("\n").trimEnd();
39
+ }
40
+
41
+ /** A message cut to `limit` characters, keeping its "Next:" line, which comes last. */
42
+ export function cutKeepingNextStep(text, limit) {
43
+ const whole = String(text ?? "");
44
+ if (whole.length <= limit) return whole;
45
+ const lines = whole.split("\n");
46
+ const at = lineOfNext(lines);
47
+ if (at < 0) return whole.slice(0, limit);
48
+ const next = lines[at];
49
+ const room = Math.max(0, limit - next.length - 1);
50
+ return `${withoutNextStep(whole).slice(0, room)}\n${next}`;
51
+ }
52
+
53
+ // Each agent's next step in each thread, on the board (boardMirror.mjs MIRRORED), so it follows home.
54
+ export const NEXT_STEP_TABLES = `
55
+ create table if not exists board_next_steps (
56
+ goal_id text not null,
57
+ agent text not null,
58
+ step text not null,
59
+ said_at text not null,
60
+ primary key (goal_id, agent)
61
+ );
62
+ `;
63
+
64
+ /**
65
+ * The steps kept, written on home only (a worker's copy follows home's). `keep(thread, agent, step)` keeps the step a
66
+ * turn ended with, or with none forgets the one before; `of(thread, agent)` is `{ step, said_at }` or null.
67
+ */
68
+ export function createNextSteps({ store, now = () => Date.now() }) {
69
+ const db = store.db;
70
+ return {
71
+ keep(thread, agent, step) {
72
+ if (!step) {
73
+ db.run("delete from board_next_steps where goal_id = ? and agent = ?", [
74
+ thread,
75
+ agent,
76
+ ]);
77
+ return null;
78
+ }
79
+ const kept = String(step).slice(0, STEP_CHARS);
80
+ db.run(
81
+ "insert into board_next_steps(goal_id, agent, step, said_at) values(?, ?, ?, ?) on conflict(goal_id, agent) do update set step = excluded.step, said_at = excluded.said_at",
82
+ [thread, agent, kept, new Date(now()).toISOString()]
83
+ );
84
+ return kept;
85
+ },
86
+ of(thread, agent) {
87
+ return (
88
+ db.get(
89
+ "select step, said_at from board_next_steps where goal_id = ? and agent = ?",
90
+ [thread, agent]
91
+ ) ?? null
92
+ );
93
+ },
94
+ };
95
+ }
package/lib/notify.mjs CHANGED
@@ -1,7 +1,7 @@
1
+ import { readConfig } from "./secretStore.mjs";
1
2
  import { spawn } from "node:child_process";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { nameOf } from "./members.mjs";
4
- import { readJson } from "./files.mjs";
5
5
  import { paths } from "./paths.mjs";
6
6
 
7
7
  // A desktop notification from the daemon, for the person who does not have Harness open:
@@ -61,7 +61,7 @@ export function notifyDesktop(
61
61
  } = {}
62
62
  ) {
63
63
  // The person turned desktop notices off in setup ("Tell me when an agent needs me"); the board still shows all of it.
64
- if (readJson(paths.config, {}).desktopNotices === false) return false;
64
+ if (readConfig(paths.config, {}).desktopNotices === false) return false;
65
65
  const words = String(body).slice(0, 240);
66
66
  const keepForMacBuddy = platform === "darwin" && !env.HARNESS_NOTIFY_COMMAND;
67
67
  if (buddyCollects() || keepForMacBuddy) {