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
package/lib/phones.mjs CHANGED
@@ -1,40 +1,29 @@
1
1
  import os from "node:os";
2
- import fs from "node:fs";
2
+ import { FROM_BROWSER } from "./screenWatches.mjs";
3
3
  import { randomBytes } from "node:crypto";
4
- import { readJson, writeJsonAtomic } from "./files.mjs";
5
4
  import { boardCommandsFor } from "./boardProtocol.mjs";
6
5
  import { isPairCode, normalizeJoinCode } from "./machineSeal.mjs";
7
6
  import {
8
7
  b64u,
9
8
  channelKey,
10
- constantTimeEqual,
11
9
  loadOrCreateIdentity,
12
10
  MAX_SKEW_MS,
13
11
  open,
14
- pairProof,
15
12
  seal,
16
13
  sealFilePart,
17
14
  } from "./sealed.mjs";
18
15
 
19
- // The daemon's side of the person's own devices: pairing offers made on this machine (a QR code
20
- // for a phone, a link opened in a browser), and sealed calls from paired devices, opened here and
21
- // answered here. Harness only carries the envelopes.
16
+ // The daemon's side of the person's own devices: sealed calls from the browsers and phones on the
17
+ // person's signed device list, opened here and answered here. Harness only carries the envelopes.
22
18
  // A phone acts as the person ("user") within PHONE_COMMANDS. A browser is the Harness window on a
23
19
  // desk: it acts as the person or as Harness (the chat owner), within BROWSER_COMMANDS, and reads
24
20
  // the coding sessions and run records Harness used to read in the clear.
25
21
 
26
- const OFFER_TTL_MS = 10 * 60_000;
27
- // After the person turns down a browser's ask, Harness pages do not ask again for a day; after one they left
28
- // unanswered, for an hour. Linking from the terminal (`tryharness link`) is never held back.
29
- const REFUSED_QUIET_MS = 24 * 60 * 60_000;
30
- const ASK_QUIET_MS = 60 * 60_000;
31
- // A cloud computer's offer (cloudOffer) is minted for one window's link the moment the window asks, through Harness,
32
- // and used at once, so it lives two minutes, not the ten a person needs to scan a code or open a link.
33
- const CLOUD_OFFER_TTL_MS = 2 * 60_000;
34
- const MAX_OFFERS = 5;
35
22
  // A message queued at Harness while this computer slept may arrive up to 7 days late; only decisions and posts may.
36
23
  const QUEUED_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
37
24
  const QUEUEABLE = boardCommandsFor("queuedPhone");
25
+ // The calls that open a device's channel to this computer (link.mjs): the only live calls Harness carries.
26
+ const INTRODUCTIONS = new Set(["link.offer", "link.candidates", "link.here"]);
38
27
  // Of those, only what ends or clears work keeps the seven days. Anything that can start an agent (a Start, a post or an
39
28
  // answer that wakes one, a message into a session) is the person's word for now: Harness holding it back for days must
40
29
  // not turn it into a run they no longer expect. An hour covers a computer waking from sleep, not a carrier's delay.
@@ -52,7 +41,6 @@ const queuedMaxAge = (command) =>
52
41
  QUEUED_ENDINGS.has(command) ? QUEUED_MAX_AGE_MS : QUEUED_RUN_MAX_AGE_MS;
53
42
  const ID = /^[A-Za-z0-9_-]{8,64}$/;
54
43
  const KEY = /^[A-Za-z0-9_-]{80,100}$/;
55
- const KINDS = new Set(["phone", "browser"]);
56
44
  const PHONE_COMMANDS = boardCommandsFor("phone");
57
45
  // What the chat owner does on the board, in Harness's name (the commands Harness's server once listed itself).
58
46
  const HARNESS_COMMANDS = boardCommandsFor("harnessBrowser");
@@ -61,74 +49,6 @@ const BROWSER_PERSON_COMMANDS = boardCommandsFor("browserPerson");
61
49
  // The person's own model lane (lane.mjs): only their linked Harness window gives it, sees whether it is kept, and takes it
62
50
  // back, and only as the person, never in a call Harness's chat makes.
63
51
  const LANE_COMMANDS = boardCommandsFor("browserLane");
64
- // What a browser whose key the Harness extension holds may do as the person with no sign that they acted in the page:
65
- // read, end or clear work, and the page's own bookkeeping (seen, followed, a backup's sync). Everything else (words that
66
- // wake an agent, a Start, a grant, a decision) needs the extension to have seen them act there as it sealed the call
67
- // (`gesture`, the page's transient user activation, which no script can make). The page is Harness's to serve; the
68
- // extension's code is not, so this is how a page Harness's server changed cannot speak for the person through the key.
69
- const WITHOUT_GESTURE = new Set([
70
- "board.list",
71
- "board.get",
72
- "board.children",
73
- "board.agents",
74
- "board.thread.read",
75
- "board.goal.list",
76
- "board.goal.get",
77
- "board.room.read",
78
- "board.file.get",
79
- "board.file.add",
80
- "board.swarm.list",
81
- "board.swarm.read",
82
- "board.swarm.file",
83
- "board.swarm.diff",
84
- "board.swarm.agents",
85
- "board.swarm.lessons",
86
- "board.swarm.held",
87
- "board.swarm.places",
88
- "board.swarm.context",
89
- "board.swarm.links",
90
- "board.swarm.seen",
91
- "board.swarm.follow",
92
- "board.swarm.notice",
93
- "board.swarm.specialty",
94
- "board.live",
95
- "board.live.read",
96
- "board.standing.check",
97
- "board.relay.list",
98
- "board.relay.board",
99
- "board.relay.network",
100
- "board.relay.peers",
101
- "board.relay.seen",
102
- "board.project.list",
103
- "board.project.repos",
104
- "board.project.read",
105
- "board.project.held",
106
- "board.repo.find",
107
- "board.repo.clone.read",
108
- "board.connector.list",
109
- "board.connector.tools",
110
- "board.connector.result",
111
- "board.connector.operations",
112
- "board.connector.refresh",
113
- "board.environments.list",
114
- "board.native.read",
115
- "board.vault.list",
116
- "board.vault.dismiss",
117
- "board.vault.backup.sync",
118
- // Ending or taking back is always the person's to do, whatever asked.
119
- ...QUEUED_ENDINGS,
120
- "board.swarm.discard",
121
- "board.standing.off",
122
- "board.connector.revoke",
123
- "board.vault.revoke",
124
- "board.vault.remove",
125
- "board.vault.unshare",
126
- "board.vault.backup.stop",
127
- "board.project.withdraw",
128
- "board.project.decline",
129
- "board.project.leave",
130
- ]);
131
- const HOLDERS = new Set(["page", "extension"]);
132
52
  // The person's devices on all their computers, and their answer to one waiting, from a phone or browser of theirs.
133
53
  const DEVICE_DECISIONS = new Set(["devices.list", "devices.answer"]);
134
54
  const BROWSER_READS = boardCommandsFor("browserReads");
@@ -143,19 +63,23 @@ const PHONE_MACHINE_COMMANDS = boardCommandsFor("phoneMachines");
143
63
  // (models.mjs): only there, and only as the person.
144
64
  const SIGN_IN_COMMANDS = boardCommandsFor("browserSignIn");
145
65
  // The person's window lets one of their cloud computers use a model endpoint this computer reaches (proxyLinks.mjs):
146
- // only as the person, and with the extension's key only when it saw them act in the page, since the link opens what
147
- // only this computer reaches to a computer Harness runs.
66
+ // only as the person, since the link opens what only this computer reaches to a computer Harness runs.
148
67
  const LINK_COMMANDS = boardCommandsFor("browserLinks");
149
- // The person's window lets their SSH key into this cloud computer (cloudSsh.mjs): only as the person, and with the
150
- // extension's key only when it saw them act in the page.
68
+ // The person's window lets their SSH key into this cloud computer (cloudSsh.mjs): only as the person.
151
69
  const SSH_COMMANDS = boardCommandsFor("browserSsh");
70
+ // What this computer asks a browser for the bytes of a picture that browser asked to put on a thread (board.file.attach):
71
+ // the browser answers only for a picture it is attaching right then (src/main/agents/sealedAsk.ts).
72
+ export const PICTURE_BYTES_TOOL = "picture_bytes";
73
+ const EVIDENCE_ID = /^ev_([a-z]+(?:_file)?)_[A-Za-z0-9_-]{1,80}$/;
74
+ const EXTENSIONS = {
75
+ "image/webp": "webp",
76
+ "image/png": "png",
77
+ "image/jpeg": "jpg",
78
+ };
152
79
 
153
80
  export async function createPhoneDesk({
154
81
  store,
155
82
  identityFile,
156
- // A browser link setup made before this daemon ran (writeBrowserOffer). The file stays until the offer is used or
157
- // expires, so a daemon that restarts in between (setup's own, an update, the service's keep-alive) still has it.
158
- setupOfferFile = null,
159
83
  boardCommand,
160
84
  reads = {},
161
85
  version,
@@ -163,44 +87,58 @@ export async function createPhoneDesk({
163
87
  machine = () => null,
164
88
  lane = null,
165
89
  machines = () => null,
166
- // A cloud computer (config.cloud): Harness runs it, so Harness may ask it for a link offer for one of the person's
167
- // windows (cloudOffer). Every other computer makes an offer only on this computer.
90
+ // A cloud computer (config.cloud): Harness runs it.
168
91
  cloud = false,
169
92
  signIn = null,
170
93
  // The proxy links this computer holds for the person's cloud computers (proxyLinks.mjs), or null on a cloud computer.
171
94
  links = null,
172
95
  // A cloud computer's SSH keys (cloudSsh.mjs allow), or null where the person cannot SSH in.
173
96
  ssh = null,
174
- // Tells the person, on this computer, about their devices: a browser asking to link, a device newly linked.
175
- notify = () => {},
176
- // The swarm's one list of the person's devices (swarmDevices.mjs), or null: what lets a device in, and where the
177
- // person's decision on one made elsewhere is carried out.
97
+ // The swarm's one list of the person's devices (swarmDevices.mjs), or null: whether a device waits for the person,
98
+ // and where the person's decision on one made elsewhere is carried out.
178
99
  devices = () => null,
179
- origin = () => null,
100
+ // The person's signed device list (computerDevices.mjs deviceOnList): a browser or phone on it reaches this computer
101
+ // and is kept here on its first call; any other is refused, one kept here from before the list included (L4.7d).
102
+ // Null: only devices already kept here (tests that stand for a computer without the list).
103
+ personsDevices = null,
104
+ // The link (link.mjs): a device's page introduces its WebRTC channel to this computer with a sealed "link.offer".
105
+ link = null,
180
106
  // Where what a linked window did to this computer is written (daemon.log).
181
107
  log = () => {},
182
108
  }) {
183
109
  const identity = await loadOrCreateIdentity(identityFile);
184
- const offers = new Map();
185
110
  const keys = new Map();
186
111
  // The name the person knows this computer by (machine.json's label, which `npx tryharness machines name` changes),
187
- // not its network name: macOS renames that on its own after a clash on the network, and a phone linking
188
- // MacBook-Pro-3 said it was linking a MacBook-Pro-4 the person had never heard of.
112
+ // not its network name: macOS renames that on its own after a clash on the network, and a phone
113
+ // reaching MacBook-Pro-3 said it was reaching a MacBook-Pro-4 the person had never heard of.
189
114
  const hostname = () =>
190
115
  machines()?.status()?.label ?? os.hostname().slice(0, 64);
191
116
 
192
- const setupOffer = setupOfferFile ? readSetupOffer(setupOfferFile) : null;
193
- if (setupOffer)
194
- offers.set(setupOffer.offerId, {
195
- secret: setupOffer.secret,
196
- kind: "browser",
197
- expiresAt: setupOffer.expiresAt,
198
- });
199
-
200
- const sweep = () => {
201
- const now = Date.now();
202
- for (const [id, offer] of offers)
203
- if (offer.expiresAt < now) offers.delete(id);
117
+ // Recent answers, by the call they answered, oldest first. A copy of a call older than MAX_SKEW_MS is refused as
118
+ // stale before it gets here, so none is kept longer; a file part's answer is up to 1.4 MB, so the total is bounded.
119
+ const answers = new Map();
120
+ const ANSWERS_KEPT_CHARS = 32 * 1024 * 1024;
121
+ const keepAnswer = (call, answer) => {
122
+ const kept = { at: Date.now(), answer, chars: 0 };
123
+ answers.set(call, kept);
124
+ answer.then(
125
+ (result) => {
126
+ kept.chars = JSON.stringify(result ?? null).length;
127
+ trimAnswers();
128
+ },
129
+ () => answers.delete(call)
130
+ );
131
+ return answer;
132
+ };
133
+ const trimAnswers = () => {
134
+ let total = 0;
135
+ for (const { chars } of answers.values()) total += chars;
136
+ for (const [call, kept] of answers) {
137
+ const fresh = Date.now() - kept.at <= MAX_SKEW_MS;
138
+ if (fresh && total <= ANSWERS_KEPT_CHARS) break;
139
+ answers.delete(call);
140
+ total -= kept.chars;
141
+ }
204
142
  };
205
143
  const keyFor = async (device) => {
206
144
  if (!keys.has(device.id))
@@ -211,240 +149,7 @@ export async function createPhoneDesk({
211
149
  return keys.get(device.id);
212
150
  };
213
151
 
214
- // One pairing offer, kept here until it is used once or expires. `holder`: where the device keeps its key (only the
215
- // extension's own request makes an "extension" one); `byHarness`: Harness's server asked for it (cloudOffer), so the
216
- // device it links waits for the person (swarmDevices.mjs).
217
- const mint = (kind, ttlMs, { holder = "page", byHarness = false } = {}) => {
218
- if (!HOLDERS.has(holder)) throw new Error(`unknown key holder ${holder}`);
219
- sweep();
220
- if (offers.size >= MAX_OFFERS) offers.delete(offers.keys().next().value);
221
- const offerId = b64u(randomBytes(16));
222
- const secret = b64u(randomBytes(32));
223
- offers.set(offerId, {
224
- secret,
225
- kind,
226
- holder,
227
- byHarness,
228
- expiresAt: Date.now() + ttlMs,
229
- });
230
- return { o: offerId, s: secret, k: identity.publicKey, h: hostname() };
231
- };
232
-
233
- // What the QR code or link carries. The secret and the daemon's key never pass through Harness.
234
- // The kind is fixed here, on the machine: a page cannot turn a phone's code into a browser's.
235
- const offer = (origin, kind = "phone", { holder = "page" } = {}) => {
236
- if (!KINDS.has(kind)) throw new Error(`unknown device kind ${kind}`);
237
- const minted = mint(kind, OFFER_TTL_MS, { holder });
238
- const offerId = minted.o;
239
- const fragment = new URLSearchParams({ v: "1", ...minted });
240
- const page = kind === "browser" ? "/link" : "/m/pair";
241
- return {
242
- offerId,
243
- kind,
244
- expiresInSeconds: OFFER_TTL_MS / 1000,
245
- url: `${String(origin).replace(/\/$/, "")}${page}#${fragment}`,
246
- };
247
- };
248
-
249
- // A Harness page asking, through the extension's native host (nativeHost.mjs), for a link offer for its browser. The
250
- // page is served by Harness, so it never gets one on its own word: the person allows it here, on the computer (the
251
- // buddy's settings or `tryharness phone allow`). One ask waits at a time; another page's ask joins it. An ask the
252
- // person turned down, or left, is not raised again for a while, so opening Harness does not nag.
253
- const linkAsks = new Map();
254
- let quietUntil = 0;
255
- const askWords = (label) =>
256
- `${label} asks to link to this computer. Allow it only if you just opened Harness there: in Harness's settings on this computer, or with npx tryharness phone allow.`;
257
- const settleAsk = (ask, state, url = null) => {
258
- ask.state = state;
259
- ask.url = url;
260
- for (const wake of ask.waiters.splice(0)) wake();
261
- };
262
- const sweepAsks = () => {
263
- const now = Date.now();
264
- for (const ask of linkAsks.values())
265
- if (ask.state === "waiting" && ask.expiresAt < now) {
266
- settleAsk(ask, "expired");
267
- quietUntil = Math.max(quietUntil, now + ASK_QUIET_MS);
268
- }
269
- for (const [id, ask] of linkAsks)
270
- if (ask.expiresAt + OFFER_TTL_MS < now) linkAsks.delete(id);
271
- };
272
- const askLink = (label) => {
273
- sweepAsks();
274
- const waiting = [...linkAsks.values()].find(
275
- (ask) => ask.state === "waiting"
276
- );
277
- if (waiting) return waiting;
278
- if (Date.now() < quietUntil)
279
- return { id: null, state: "refused", waiters: [] };
280
- const ask = {
281
- id: b64u(randomBytes(12)),
282
- label: cleanLabel(label, "A browser"),
283
- askedAt: new Date().toISOString(),
284
- expiresAt: Date.now() + OFFER_TTL_MS,
285
- state: "waiting",
286
- url: null,
287
- waiters: [],
288
- };
289
- linkAsks.set(ask.id, ask);
290
- notify(askWords(ask.label), `ask:${ask.id}`);
291
- // The person may answer it on any of their computers.
292
- void devices()?.report();
293
- return ask;
294
- };
295
- const linkAsk = {
296
- /** The native host's ask: the same ask while it waits, answered once the person decides or it runs out. */
297
- async request({ id = null, label, waitMs = 25_000 }) {
298
- const ask = (id && linkAsks.get(String(id))) || askLink(label);
299
- if (ask.state === "waiting")
300
- await new Promise((resolve) => {
301
- const timer = setTimeout(
302
- resolve,
303
- Math.max(0, Math.min(waitMs, ask.expiresAt - Date.now()))
304
- );
305
- ask.waiters.push(() => {
306
- clearTimeout(timer);
307
- resolve();
308
- });
309
- });
310
- sweepAsks();
311
- const url = ask.state === "allowed" ? ask.url : null;
312
- // The offer goes to the one host that asked first; any later answer for this ask gets none.
313
- if (url) ask.url = null;
314
- const state = ask.state === "allowed" && !url ? "used" : ask.state;
315
- return { ok: true, id: ask.id, state, url };
316
- },
317
- list: () => {
318
- sweepAsks();
319
- return [...linkAsks.values()]
320
- .filter((ask) => ask.state === "waiting")
321
- .map(({ id, label, askedAt }) => ({ id, label, askedAt }));
322
- },
323
- /** The person's answer, from this computer. */
324
- answer(id, allow) {
325
- sweepAsks();
326
- const ask = linkAsks.get(String(id));
327
- if (!ask || ask.state !== "waiting")
328
- return { ok: false, error: "that browser is no longer asking" };
329
- if (!allow) {
330
- quietUntil = Date.now() + REFUSED_QUIET_MS;
331
- settleAsk(ask, "refused");
332
- void devices()?.report();
333
- return { ok: true, state: "refused" };
334
- }
335
- const made = offer(origin() || "https://tryharness.ai", "browser");
336
- settleAsk(ask, "allowed", made.url);
337
- void devices()?.report();
338
- return { ok: true, state: "allowed" };
339
- },
340
- };
341
-
342
- // The Harness extension asking, through its native host, to hold this browser's link itself. Chrome starts the host
343
- // only for the extension (nativeHost.mjs allowed_origins), and the extension asks on its own, never on a page's word,
344
- // so no page Harness serves ever holds this key: the person is not asked, as setup's own link is not. The new device
345
- // is told on this computer like any other.
346
- const extensionOffer = (origin) => {
347
- const made = offer(origin || "https://tryharness.ai", "browser", {
348
- holder: "extension",
349
- });
350
- return { ok: true, fragment: new URL(made.url).hash };
351
- };
352
-
353
- /**
354
- * A cloud computer's link offer for one of the person's windows, asked for by Harness's server, which runs this
355
- * computer and already holds what the offer opens. Fresh on every ask, one use, two minutes: an offer read from
356
- * Harness's database or a window's earlier answer links nothing, and every device it links shows in the person's
357
- * list of this computer's devices.
358
- */
359
- const cloudOffer = () =>
360
- cloud
361
- ? {
362
- ok: true,
363
- offer: mint("browser", CLOUD_OFFER_TTL_MS, { byHarness: true }),
364
- }
365
- : {
366
- ok: false,
367
- error: "only a cloud computer makes a link offer for Harness",
368
- };
369
-
370
- const pair = async (input) => {
371
- sweep();
372
- const { offerId, deviceId, devicePublicKey, proof, requestId } = input;
373
- if (
374
- ![offerId, deviceId, requestId].every((value) =>
375
- ID.test(String(value))
376
- ) ||
377
- !KEY.test(String(devicePublicKey))
378
- )
379
- return { ok: false, error: "invalid pairing request" };
380
- const pending = offers.get(String(offerId));
381
- // One attempt per code, right or wrong: a guessed proof burns the code.
382
- offers.delete(String(offerId));
383
- const seeded = pending?.byHarness === true;
384
- if (setupOffer && String(offerId) === setupOffer.offerId)
385
- removeFile(setupOfferFile);
386
- if (!pending)
387
- return {
388
- ok: false,
389
- error:
390
- "this pairing code expired or was already used; make a new one on the computer",
391
- };
392
- if (
393
- !constantTimeEqual(
394
- proof,
395
- await pairProof(
396
- pending.secret,
397
- offerId,
398
- devicePublicKey,
399
- identity.publicKey
400
- )
401
- )
402
- )
403
- return { ok: false, error: "the pairing proof did not match" };
404
- if (store.getPhone(String(deviceId)))
405
- return { ok: false, error: "this device is already paired" };
406
- const label = cleanLabel(
407
- input.label,
408
- pending.kind === "browser" ? "Browser" : "Phone"
409
- );
410
- const device = store.addPhone({
411
- id: String(deviceId),
412
- label,
413
- publicKey: String(devicePublicKey),
414
- kind: pending.kind,
415
- holder: pending.holder ?? "page",
416
- });
417
- // An offer Harness asked for (a cloud computer's link for a window) lets nothing in by itself: the person allows the device.
418
- const state = devices()?.paired(device, { seeded }) ?? "listed";
419
- // Every new device is told on this computer, where the person can take it back: a page that paired one of its
420
- // own is seen here.
421
- notify(
422
- state === "waiting"
423
- ? `${label} was linked to this computer through Harness, not from one of your computers, so it does nothing until you allow it on any of your computers or devices: npx tryharness phone allow ${device.id.slice(0, 8)}.`
424
- : `${label} is now linked to this computer as your ${device.kind}. Not you? Disconnect it in Harness's settings here, or with npx tryharness phone revoke ${device.id.slice(0, 8)}.`,
425
- `device:${device.id}`
426
- );
427
- return {
428
- ok: true,
429
- envelope: await seal(
430
- await keyFor(device),
431
- "d2p",
432
- device.id,
433
- String(requestId),
434
- {
435
- paired: true,
436
- hostname: hostname(),
437
- label,
438
- kind: device.kind,
439
- version,
440
- ...(state === "waiting" ? { waiting: true } : {}),
441
- }
442
- ),
443
- };
444
- };
445
-
446
- const call = async (envelope) => {
447
- sweep();
152
+ const call = async (envelope, { relayed = false } = {}) => {
448
153
  if (
449
154
  !envelope ||
450
155
  envelope.v !== 1 ||
@@ -455,7 +160,64 @@ export async function createPhoneDesk({
455
160
  ) {
456
161
  return { ok: false, error: "invalid envelope" };
457
162
  }
458
- const device = store.getPhone(envelope.deviceId);
163
+ let device = store.getPhone(envelope.deviceId);
164
+ const listed = personsDevices
165
+ ? await personsDevices(String(envelope.deviceId)).then(
166
+ (found) => found ?? { absent: true },
167
+ () => ({ unread: true })
168
+ )
169
+ : null;
170
+ if (listed?.unread)
171
+ return {
172
+ ok: false,
173
+ code: "unlisted",
174
+ error:
175
+ "this computer could not read your device list yet: try again once it reaches Harness",
176
+ };
177
+ if (listed?.absent)
178
+ return {
179
+ ok: false,
180
+ code: "unpaired",
181
+ error:
182
+ "this device is not on your device list: approve it there to reach this computer",
183
+ };
184
+ // A device kept here under another key than the list's is not the one on the list.
185
+ const listedKey = listed?.device
186
+ ? Buffer.from(listed.device.sealingKey, "base64").toString("base64url")
187
+ : null;
188
+ if (device && listedKey && device.public_key !== listedKey)
189
+ return {
190
+ ok: false,
191
+ code: "unpaired",
192
+ error:
193
+ "this device is not on your device list: approve it there to reach this computer",
194
+ };
195
+ if (listed?.removed && device && !device.revoked_at) {
196
+ revoke(device.id);
197
+ device = store.getPhone(envelope.deviceId);
198
+ }
199
+ // One of the person's browsers or phones on their signed list: its line is made with its sealing key there.
200
+ // Read again after the wait: another first call from the same device may have recorded it meanwhile.
201
+ device ??= store.getPhone(envelope.deviceId);
202
+ if (
203
+ !device &&
204
+ listed?.device &&
205
+ (listed.device.kind === "browser" || listed.device.kind === "phone")
206
+ ) {
207
+ device = store.addPhone({
208
+ id: listed.device.deviceId,
209
+ label: listed.device.label,
210
+ publicKey: Buffer.from(listed.device.sealingKey, "base64").toString(
211
+ "base64url"
212
+ ),
213
+ kind: listed.device.kind,
214
+ });
215
+ log(
216
+ `${listed.device.label} reached this computer as one of your devices`
217
+ );
218
+ // Home keeps the swarm's one list of devices, where the person can disconnect this one from any computer.
219
+ void devices()?.report();
220
+ }
459
221
  if (!device)
460
222
  return { ok: false, error: "unknown device", code: "unpaired" };
461
223
  if (device.revoked_at)
@@ -489,6 +251,19 @@ export async function createPhoneDesk({
489
251
  error: "only posts and decisions wait for the computer",
490
252
  code: "refused",
491
253
  };
254
+ // Through Harness come only a channel's introduction and what waited for this computer while it was off: every
255
+ // live call goes over the device's own channel (docs/one-link-plan.md L8.3; owner, November 13: one road).
256
+ if (
257
+ relayed &&
258
+ !queued &&
259
+ !INTRODUCTIONS.has(String(request?.call?.command || ""))
260
+ )
261
+ return {
262
+ ok: false,
263
+ error:
264
+ "this call goes over the device's own channel to the computer, not through Harness",
265
+ code: "channel_only",
266
+ };
492
267
  const age =
493
268
  typeof request?.ts === "number" ? Date.now() - request.ts : Infinity;
494
269
  if (
@@ -501,82 +276,29 @@ export async function createPhoneDesk({
501
276
  error: "the message is too old or the device's clock is off",
502
277
  code: "stale",
503
278
  };
504
- // Which kind of key sealed it, kept with the call's record. Only the extension says whether the person acted.
505
- const holder = device.holder === "extension" ? "extension" : "page";
506
- const gesture = holder === "extension" ? request?.gesture === true : null;
279
+ // The very same call (its request id with its random iv), so a forged one under a real call's id cannot stand in.
280
+ const sameCall = `${device.id}:${envelope.requestId}:${envelope.iv}`;
281
+ // A call sent again after its road dropped (the link, link.ts) gets the answer it already had, or waits for it.
507
282
  if (
283
+ // Every key is held by the person's page now; the record's column stays for calls an older version kept.
508
284
  !store.firstPhoneRequest(device.id, String(envelope.requestId), {
509
- sealedBy: holder,
510
- gesture,
285
+ sealedBy: "page",
511
286
  })
512
287
  )
513
- return {
514
- ok: false,
515
- error: "this message was already received",
516
- code: "replayed",
517
- };
288
+ return (
289
+ answers.get(sameCall)?.answer ?? {
290
+ ok: false,
291
+ error: "this message was already received",
292
+ code: "replayed",
293
+ }
294
+ );
518
295
  store.touchPhone(device.id);
519
296
  // Any message from a paired device keeps a Mac in Standby awake for the next hour (Lid-Closed Mode).
520
297
  onMessage();
521
- // A device moving its link to a new key (phoneChannel.ts rekey, from keys whose shared secret could be exported):
522
- // asked under the old key, which opens nothing once the new one is kept.
523
- if (request.call?.command === "phone.rekey") {
524
- const publicKey = String(request.call.publicKey ?? "");
525
- // The extension's keys were never exportable, so its link never moves: a page asking it to would take it.
526
- if (!KEY.test(publicKey) || queued || holder === "extension")
527
- return {
528
- ok: true,
529
- envelope: await seal(key, "d2p", device.id, envelope.requestId, {
530
- ok: false,
531
- error: "invalid key",
532
- }),
533
- };
534
- store.rekeyPhone(device.id, publicKey);
535
- keys.delete(device.id);
536
- return {
537
- ok: true,
538
- envelope: await seal(key, "d2p", device.id, envelope.requestId, {
539
- ok: true,
540
- }),
541
- };
542
- }
543
- // The extension took this browser's link over from the page (deskKey.js): the link the page held is retired, so a
544
- // page Harness serves later cannot use it. Only a browser link a page held, and only from the extension's.
545
- if (request.call?.command === "phone.retire") {
546
- const retired = [];
547
- if (holder === "extension" && !queued)
548
- for (const id of (Array.isArray(request.call.ids)
549
- ? request.call.ids
550
- : []
551
- ).slice(0, 8)) {
552
- const other = store.getPhone(String(id));
553
- if (
554
- other &&
555
- other.id !== device.id &&
556
- other.kind === "browser" &&
557
- other.holder !== "extension" &&
558
- !other.revoked_at &&
559
- revoke(other.id).ok
560
- )
561
- retired.push(other.id);
562
- }
563
- return {
564
- ok: true,
565
- envelope: await seal(key, "d2p", device.id, envelope.requestId, {
566
- ok: holder === "extension",
567
- retired,
568
- }),
569
- };
570
- }
571
- if (request.call?.command === "phone.forget") {
572
- const forgotten = revoke(device.id);
573
- return {
574
- ok: true,
575
- envelope: await seal(key, "d2p", device.id, envelope.requestId, {
576
- ok: forgotten.ok,
577
- }),
578
- };
579
- }
298
+ return keepAnswer(sameCall, respond({ request, device, key, envelope }));
299
+ };
300
+
301
+ const respond = async ({ request, device, key, envelope }) => {
580
302
  // The person's Disconnect for another device, from one they paired; Harness's own calls through a browser never.
581
303
  if (request.call?.command === "phone.revoke") {
582
304
  const result =
@@ -591,7 +313,7 @@ export async function createPhoneDesk({
591
313
  }),
592
314
  };
593
315
  }
594
- const result = await answer(request.call, device, { holder, gesture });
316
+ const result = await answer(request.call, device);
595
317
  // A file part asked for as bytes goes sealed as bytes; anything else, and every older phone, as JSON.
596
318
  if (
597
319
  request.call?.command === "board.file.get" &&
@@ -631,30 +353,33 @@ export async function createPhoneDesk({
631
353
  };
632
354
 
633
355
  // The person's devices across their computers, and their Allow or Don't allow for one waiting, from a device of
634
- // theirs already let in (a waiting one is refused before this). Never Harness's chat; with the extension's key, only
635
- // when it saw the person act in the page.
636
- const decideOnDevices = async (command, callInput, sealedBy) => {
356
+ // theirs already let in (a waiting one is refused before this). Never Harness's chat.
357
+ const decideOnDevices = async (command, callInput) => {
637
358
  const swarm = devices();
638
359
  if (!swarm || callInput?.as === "harness")
639
360
  return { ok: false, error: "only the person allows a device" };
640
361
  if (command === "devices.list") return { ok: true, swarm: swarm.list() };
641
- if (sealedBy.holder === "extension" && !sealedBy.gesture)
642
- return {
643
- ok: false,
644
- code: "gesture",
645
- error:
646
- "nothing was done: the Harness extension saw no click or key in the page when this was asked in your name. Try it again from the page.",
647
- };
648
362
  return swarm.decide(
649
363
  String(callInput.id ?? ""),
650
364
  callInput.allow === true ? "allow" : "refuse"
651
365
  );
652
366
  };
653
367
 
654
- const answer = async (callInput, device, sealedBy) => {
368
+ const answer = async (callInput, device) => {
655
369
  const command = String(callInput?.command || "");
656
370
  if (command === "phone.hello")
657
371
  return { ok: true, hostname: hostname(), version, kind: device.kind };
372
+ // A page of this device opening its own channel to this computer: its offer, sealed like any call.
373
+ // Its offer and addresses, and (L4.7a) whether it runs on this machine: only yes or no comes back.
374
+ const linkCalls = {
375
+ "link.offer": "offer",
376
+ "link.candidates": "candidates",
377
+ "link.here": "here",
378
+ };
379
+ if (command in linkCalls)
380
+ return link
381
+ ? link[linkCalls[command]](device, callInput)
382
+ : { ok: false, error: "this computer has no link" };
658
383
  // A device sends a file's bytes. A path names a file already on this computer, which only an agent here may attach.
659
384
  if (command === "board.file.add" && callInput?.path != null)
660
385
  return {
@@ -662,7 +387,7 @@ export async function createPhoneDesk({
662
387
  error: "a phone or browser attaches a file's content, not a path",
663
388
  };
664
389
  if (DEVICE_DECISIONS.has(command))
665
- return decideOnDevices(command, callInput, sealedBy);
390
+ return decideOnDevices(command, callInput);
666
391
  if (device.kind === "browser") {
667
392
  if (LANE_COMMANDS.has(command)) {
668
393
  if (!lane || callInput.as === "harness")
@@ -723,13 +448,6 @@ export async function createPhoneDesk({
723
448
  : `a browser cannot call ${command} here`,
724
449
  };
725
450
  if (command === "links.list") return links.list();
726
- if (sealedBy.holder === "extension" && !sealedBy.gesture)
727
- return {
728
- ok: false,
729
- code: "gesture",
730
- error:
731
- "nothing was done: the Harness extension saw no click or key in the page when this was asked in your name. Try it again from the page.",
732
- };
733
451
  if (command === "links.forget") return links.forget(callInput.id);
734
452
  return links.allow({
735
453
  computer: callInput.computer,
@@ -741,13 +459,6 @@ export async function createPhoneDesk({
741
459
  if (SSH_COMMANDS.has(command)) {
742
460
  if (!ssh || callInput.as === "harness")
743
461
  return { ok: false, error: `a browser cannot call ${command} here` };
744
- if (sealedBy.holder === "extension" && !sealedBy.gesture)
745
- return {
746
- ok: false,
747
- code: "gesture",
748
- error:
749
- "nothing was done: the Harness extension saw no click or key in the page when this was asked in your name. Try it again from the page.",
750
- };
751
462
  return ssh({ key: String(callInput.key ?? ""), by: device.label });
752
463
  }
753
464
  if (MACHINE_COMMANDS.has(command)) {
@@ -789,18 +500,6 @@ export async function createPhoneDesk({
789
500
  }
790
501
  // The browser says whose call it is: the person's own action, or the chat owner's tool call.
791
502
  const as = callInput.as === "harness" ? "harness" : "user";
792
- if (
793
- as === "user" &&
794
- sealedBy.holder === "extension" &&
795
- !sealedBy.gesture &&
796
- !WITHOUT_GESTURE.has(command)
797
- )
798
- return {
799
- ok: false,
800
- code: "gesture",
801
- error:
802
- "nothing was done: the Harness extension saw no click or key in the page when this was asked in your name. Try it again from the page.",
803
- };
804
503
  if (
805
504
  !(as === "harness" ? HARNESS_COMMANDS : BROWSER_PERSON_COMMANDS).has(
806
505
  command
@@ -829,13 +528,15 @@ export async function createPhoneDesk({
829
528
  provenance: _provenance,
830
529
  ...rest
831
530
  } = callInput;
531
+ if (command === "board.file.attach")
532
+ return attachHeldPicture(rest, device, as);
832
533
  return settled(() =>
833
534
  boardCommand({
834
535
  ...rest,
835
536
  command,
836
537
  agent: as,
837
- // Which kind of key sealed it (a page's or the extension's) and whether the person acted, for rules after this.
838
- sealedBy,
538
+ // A browser's word about a screen watch this computer keeps (screenWatches.mjs): only a browser says it.
539
+ ...(command === "board.watch.screen" ? { [FROM_BROWSER]: true } : {}),
839
540
  // A Harness window's own call, which daemon.mjs checks before it takes a task given to Harness.
840
541
  fromWindow: as === "harness",
841
542
  // A connected app's or a secret's call from Harness's window is hosted, whatever the browser says: grants
@@ -890,32 +591,88 @@ export async function createPhoneDesk({
890
591
  );
891
592
  };
892
593
 
893
- // Harness's bridge message: a pairing or a sealed call. Everything returned is safe to pass through Harness.
894
- const handle = async (input) =>
895
- input?.kind === "pair"
896
- ? pair(input)
897
- : input?.kind === "call"
898
- ? call(input.envelope)
899
- : { ok: false, error: "unknown sealed request" };
594
+ // A picture the browser holds (a capture, a tab photo) put on a thread: this computer asks the browser that asked for
595
+ // the picture's bytes, over that browser's own channel with it, and adds the file as board.file.add does. Only a
596
+ // browser running on this computer is asked (owner, November 12: each computer asks only the browsers on it).
597
+ const attachHeldPicture = async (callInput, device, as) => {
598
+ const evidence = String(callInput.evidence ?? "");
599
+ const named = EVIDENCE_ID.exec(evidence);
600
+ if (!named || named[1] === "thread_file")
601
+ return { ok: false, error: "name the picture by its evidence id" };
602
+ const held = await ask(
603
+ { tool: PICTURE_BYTES_TOOL, input: { id: evidence } },
604
+ { device: device.id }
605
+ );
606
+ const bytes = held?.ok === true ? held.bytes : null;
607
+ if (typeof bytes?.dataBase64 !== "string" || !bytes.dataBase64)
608
+ return {
609
+ ok: false,
610
+ error: `the picture did not come from the browser: ${held?.error ?? "it did not answer"}`,
611
+ };
612
+ const mime = String(bytes.mediaType || "image/webp");
613
+ const name =
614
+ String(callInput.filename ?? "").trim() ||
615
+ `${named[1]}-${evidence.slice(-8)}.${EXTENSIONS[mime] ?? "img"}`;
616
+ return settled(() =>
617
+ boardCommand({
618
+ command: "board.file.add",
619
+ id: callInput.id,
620
+ name,
621
+ mime,
622
+ data: bytes.dataBase64,
623
+ ...(callInput.cloud === false ? { cloud: false } : {}),
624
+ agent: as,
625
+ fromWindow: as === "harness",
626
+ })
627
+ );
628
+ };
629
+
630
+ // A sealed call, as it arrives over the device's channel (link.mjs) or, `relayed`, through Harness's bridge message.
631
+ // Everything returned is safe to pass through Harness.
632
+ const handle = async (input, { relayed = false } = {}) =>
633
+ input?.kind === "call"
634
+ ? call(input.envelope, { relayed })
635
+ : { ok: false, error: "unknown sealed request" };
900
636
 
901
637
  // The other way round: this computer asking the person's own Harness window for what only the window holds (its
902
- // screen history). The question is sealed to every browser linked here ("d2b") under one fresh request id; Harness
903
- // hands the envelopes to the window that is open (`carry`, the bridge's leg), only a browser holding one of these
904
- // links can open its envelope, and its answer comes back sealed ("b2d") for this request id alone. Harness sees which
905
- // devices, sizes and timing, never the question or the answer.
906
- const ask = async (call, carry) => {
907
- const browsers = store
638
+ // screen history). Only the browsers running on this computer are asked (L4.7, owner, November 12: each computer asks
639
+ // only the browsers running on it), over the channel each holds with it (link.mjs): the question is sealed to each
640
+ // ("d2b") under one fresh request id, and its answer comes back sealed ("b2d") for this request id alone. A browser on
641
+ // another computer is asked by that computer, over the computers' own link (ownMachines.mjs askOtherWindows).
642
+ // `device` asks that one browser alone: the one whose picture it is, or the one an agent named (by id or name).
643
+ // `timeoutMs`: the question's own deadline (a door call's, deviceDoor.mjs), else the link's.
644
+ const ask = async (call, { device: only = null, timeoutMs } = {}) => {
645
+ const named = (device) =>
646
+ device.id === only ||
647
+ String(device.label ?? "").toLowerCase() ===
648
+ String(only).trim().toLowerCase();
649
+ const listed = store
908
650
  .phones()
909
- .filter((device) => device.kind === "browser" && !device.revoked_at)
910
- .slice(0, 8)
911
- .map((device) => store.getPhone(device.id));
912
- if (!browsers.length)
651
+ .filter(
652
+ (device) =>
653
+ device.kind === "browser" &&
654
+ !device.revoked_at &&
655
+ (!only || named(device))
656
+ );
657
+ if (!listed.length)
913
658
  return {
914
659
  ok: false,
915
660
  code: "unpaired",
916
661
  error:
917
- "no Harness window is linked to this computer: the person links one with npx tryharness link",
662
+ "no Harness window has reached this computer yet: the person opens Harness in a browser on their devices, which reaches it by itself",
918
663
  };
664
+ const here = new Set(link?.browsersHere() ?? []);
665
+ const browsers = listed
666
+ .filter((device) => here.has(device.id))
667
+ .slice(0, 8)
668
+ .map((device) => store.getPhone(device.id));
669
+ const closed = {
670
+ ok: false,
671
+ code: "closed",
672
+ error:
673
+ "the person's Harness window isn't open: ask them to open Harness, then try again",
674
+ };
675
+ if (!browsers.length) return closed;
919
676
  const requestId = b64u(randomBytes(16));
920
677
  const ts = Date.now();
921
678
  const envelopes = await Promise.all(
@@ -923,19 +680,8 @@ export async function createPhoneDesk({
923
680
  seal(await keyFor(device), "d2b", device.id, requestId, { ts, call })
924
681
  )
925
682
  );
926
- const reply = await carry(envelopes);
927
- if (reply?.window === "closed")
928
- return {
929
- ok: false,
930
- code: "closed",
931
- error:
932
- "the person's Harness window isn't open: ask them to open Harness, then try again",
933
- };
934
- if (reply?.window !== "open")
935
- return {
936
- ok: false,
937
- error: reply?.error || "Harness could not carry the question",
938
- };
683
+ const reply = await link.ask(envelopes, timeoutMs ? { timeoutMs } : {});
684
+ if (!reply) return closed;
939
685
  if (!reply.ok || !reply.envelope)
940
686
  return {
941
687
  ok: false,
@@ -964,15 +710,29 @@ export async function createPhoneDesk({
964
710
  };
965
711
  }
966
712
  store.touchPhone(device.id);
967
- return answer;
713
+ // Which browser answered, for the agent's "[from <browser>]" (deviceDoor.mjs).
714
+ return { ...answer, browser: { id: device.id, label: device.label } };
968
715
  };
969
716
 
717
+ // A disconnected device's channels close with it, not when it next calls (docs/one-link-plan.md L6.1).
970
718
  const revoke = (id) => {
971
719
  keys.delete(String(id));
972
720
  const result = store.revokePhone(String(id));
721
+ link?.close(String(id));
973
722
  void devices()?.report();
974
723
  return result;
975
724
  };
725
+ /** A browser or phone taken off the person's list: disconnected here, and every channel it holds closed now. */
726
+ const removedFromList = (id) => {
727
+ const kept = store.getPhone(String(id));
728
+ const open = link?.count(String(id)) ?? 0;
729
+ if (kept && !kept.revoked_at) revoke(id);
730
+ else link?.close(String(id));
731
+ if (open)
732
+ log(
733
+ `link: ${kept?.label || id} was taken off your devices; its ${open === 1 ? "channel" : `${open} channels`} closed`
734
+ );
735
+ };
976
736
  // The person's Disconnect for any device of theirs: paired here, or with another of their computers.
977
737
  const disconnect = async (id) =>
978
738
  store.getPhone(id)
@@ -983,63 +743,13 @@ export async function createPhoneDesk({
983
743
  });
984
744
 
985
745
  return {
986
- offer,
987
- linkAsk,
988
- extensionOffer,
989
- cloudOffer,
990
746
  handle,
991
747
  ask,
992
748
  revoke,
749
+ removedFromList,
993
750
  disconnect,
994
751
  list: () => store.phones(),
995
752
  publicKey: identity.publicKey,
996
753
  identity,
997
754
  };
998
755
  }
999
-
1000
- // Setup's browser link (cli.mjs): the page that approves this computer links the same browser in the same step, so
1001
- // setup makes the offer itself, before the daemon runs, and puts it in that page's address fragment with the pairing
1002
- // code. The daemon takes it in when it starts. Same secret, key, ten minutes and one use as a link the daemon makes.
1003
- export async function writeBrowserOffer({ identityFile, offerFile }) {
1004
- const identity = await loadOrCreateIdentity(identityFile);
1005
- const offer = {
1006
- offerId: b64u(randomBytes(16)),
1007
- secret: b64u(randomBytes(32)),
1008
- expiresAt: Date.now() + OFFER_TTL_MS,
1009
- };
1010
- writeJsonAtomic(offerFile, offer);
1011
- return new URLSearchParams({
1012
- v: "1",
1013
- o: offer.offerId,
1014
- s: offer.secret,
1015
- k: identity.publicKey,
1016
- // The name the computer goes by everywhere else (pairing.mjs, machineIdentity.mjs).
1017
- h: os
1018
- .hostname()
1019
- .replace(/\.local$/, "")
1020
- .slice(0, 64),
1021
- }).toString();
1022
- }
1023
-
1024
- // A device's name as the person sees it in their list: whatever the page said, letters, digits and a few marks only.
1025
- const cleanLabel = (label, fallback) =>
1026
- String(label || fallback)
1027
- .replace(/[^\p{L}\p{N} ._'-]/gu, "")
1028
- .slice(0, 40) || fallback;
1029
-
1030
- function removeFile(file) {
1031
- try {
1032
- fs.unlinkSync(file);
1033
- } catch {}
1034
- }
1035
-
1036
- function readSetupOffer(file) {
1037
- const offer = readJson(file, null);
1038
- const usable =
1039
- offer &&
1040
- ID.test(String(offer.offerId)) &&
1041
- typeof offer.secret === "string" &&
1042
- offer.expiresAt > Date.now();
1043
- if (!usable) removeFile(file);
1044
- return usable ? offer : null;
1045
- }