tryharness 0.7.53 → 0.7.57

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 (167) hide show
  1. package/README.md +23 -19
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +484 -90
  5. package/lib/activity.mjs +10 -10
  6. package/lib/adapters.mjs +173 -222
  7. package/lib/agentBinaries.mjs +71 -0
  8. package/lib/agentRuntimeConfig.mjs +1 -1
  9. package/lib/agentRuntimes.mjs +34 -18
  10. package/lib/agentSignIn.mjs +456 -0
  11. package/lib/answers.mjs +5 -5
  12. package/lib/archetypes.d.ts +64 -0
  13. package/lib/archetypes.js +989 -0
  14. package/lib/asks.mjs +4 -4
  15. package/lib/audit.mjs +666 -0
  16. package/lib/backupSetup.mjs +143 -0
  17. package/lib/boardAccess.mjs +24 -11
  18. package/lib/boardBackup.mjs +283 -0
  19. package/lib/boardFileCommands.mjs +6 -6
  20. package/lib/boardFiles.mjs +13 -12
  21. package/lib/boardMirror.mjs +124 -25
  22. package/lib/boardProtocol.json +88 -2
  23. package/lib/boardWaits.mjs +101 -0
  24. package/lib/book.mjs +659 -0
  25. package/lib/bridge.mjs +6 -6
  26. package/lib/cards.mjs +138 -28
  27. package/lib/cloudAgents.mjs +216 -0
  28. package/lib/cloudAi.mjs +1312 -0
  29. package/lib/cloudAssistants.mjs +242 -0
  30. package/lib/cloudBoot.mjs +119 -0
  31. package/lib/cloudSave.mjs +197 -0
  32. package/lib/cloudSsh.mjs +178 -0
  33. package/lib/commands.mjs +7 -2
  34. package/lib/context.mjs +19 -5
  35. package/lib/contractGate.mjs +399 -0
  36. package/lib/control-client.mjs +9 -1
  37. package/lib/controlSocket.mjs +86 -0
  38. package/lib/coordinator.mjs +252 -144
  39. package/lib/daemon.mjs +1351 -2767
  40. package/lib/desk.mjs +240 -0
  41. package/lib/desktop.mjs +178 -74
  42. package/lib/directLink.mjs +16 -5
  43. package/lib/environment.mjs +2 -1
  44. package/lib/environments.mjs +247 -9
  45. package/lib/firewall.mjs +9 -9
  46. package/lib/folders.mjs +20 -16
  47. package/lib/frames.mjs +2 -3
  48. package/lib/gitHost.mjs +174 -0
  49. package/lib/goalCommands.mjs +25 -7
  50. package/lib/goals.mjs +7 -7
  51. package/lib/guestRequests.mjs +94 -0
  52. package/lib/handoffs.mjs +8 -7
  53. package/lib/handover.mjs +4 -4
  54. package/lib/harnessModel.mjs +6 -6
  55. package/lib/harnessOffers.mjs +266 -0
  56. package/lib/hookDialects.mjs +298 -0
  57. package/lib/inference.mjs +26 -8
  58. package/lib/jobAnswers.mjs +190 -0
  59. package/lib/landed.mjs +887 -0
  60. package/lib/lane.mjs +42 -11
  61. package/lib/lessons.mjs +16 -16
  62. package/lib/library.mjs +3 -3
  63. package/lib/lineup.mjs +3 -0
  64. package/lib/linkRelay.mjs +574 -0
  65. package/lib/live.mjs +284 -13
  66. package/lib/localAgentAsk.mjs +74 -0
  67. package/lib/localStack.mjs +536 -0
  68. package/lib/localmodels.mjs +6 -4
  69. package/lib/loopBackstop.mjs +4 -4
  70. package/lib/machineIdentity.mjs +9 -1
  71. package/lib/machineRoutes.mjs +181 -2
  72. package/lib/machineRuns.mjs +76 -1
  73. package/lib/machineSeal.mjs +39 -12
  74. package/lib/mcp-stdio.mjs +163 -27
  75. package/lib/mcpRelay.mjs +1 -1
  76. package/lib/members.json +29 -2
  77. package/lib/members.mjs +1 -1
  78. package/lib/models.mjs +85 -31
  79. package/lib/museSession.mjs +21 -13
  80. package/lib/nativeHost.mjs +36 -8
  81. package/lib/neovim.mjs +126 -0
  82. package/lib/network.mjs +50 -5
  83. package/lib/notify.mjs +7 -5
  84. package/lib/nudge.mjs +50 -19
  85. package/lib/ocr.mjs +9 -9
  86. package/lib/onboard.mjs +26 -20
  87. package/lib/oneLine.mjs +7 -7
  88. package/lib/ownMachines.mjs +1223 -140
  89. package/lib/pairing.mjs +60 -16
  90. package/lib/paths.mjs +19 -1
  91. package/lib/peerProcess.mjs +124 -0
  92. package/lib/personModel.mjs +89 -0
  93. package/lib/personNotices.mjs +151 -0
  94. package/lib/phones.mjs +538 -31
  95. package/lib/placeCommands.mjs +4 -4
  96. package/lib/places.mjs +400 -12
  97. package/lib/profile.mjs +67 -14
  98. package/lib/projectGit.mjs +158 -14
  99. package/lib/projectPieces.mjs +902 -0
  100. package/lib/projectSettings.mjs +7 -4
  101. package/lib/projects.mjs +384 -62
  102. package/lib/provenance.mjs +5 -1
  103. package/lib/proxyLinks.mjs +267 -0
  104. package/lib/reactions.mjs +7 -5
  105. package/lib/readiness.mjs +145 -23
  106. package/lib/record.mjs +128 -0
  107. package/lib/redact.mjs +4 -4
  108. package/lib/relayLimits.mjs +62 -0
  109. package/lib/release.mjs +170 -0
  110. package/lib/releaseKeys.json +6 -0
  111. package/lib/repoLinks.mjs +4 -4
  112. package/lib/roomChannels.mjs +24 -0
  113. package/lib/roomPage.mjs +1 -1
  114. package/lib/runAuthority.mjs +101 -0
  115. package/lib/runBrief.mjs +19 -8
  116. package/lib/runWorker.mjs +31 -7
  117. package/lib/runner.mjs +223 -29
  118. package/lib/runtime-install.mjs +143 -9
  119. package/lib/schedules.mjs +2 -2
  120. package/lib/screens.mjs +1 -1
  121. package/lib/sealed.mjs +11 -2
  122. package/lib/sealedThreads.mjs +671 -0
  123. package/lib/secretPatterns.json +1 -1
  124. package/lib/secrets.mjs +4 -4
  125. package/lib/seen.mjs +6 -6
  126. package/lib/serverWords.mjs +175 -0
  127. package/lib/service.mjs +22 -12
  128. package/lib/sessionControl.mjs +378 -90
  129. package/lib/specialties.json +74 -0
  130. package/lib/specialties.mjs +477 -0
  131. package/lib/specialtyKeys.d.ts +3 -0
  132. package/lib/specialtyKeys.js +57 -0
  133. package/lib/specialtyNotice.mjs +147 -0
  134. package/lib/specialtySnapshot.mjs +138 -0
  135. package/lib/speech.mjs +5 -5
  136. package/lib/store.mjs +420 -36
  137. package/lib/stuck.mjs +1 -1
  138. package/lib/swarm.mjs +304 -37
  139. package/lib/swarmDevices.mjs +319 -0
  140. package/lib/swarmMemory.mjs +27 -25
  141. package/lib/t3.mjs +24 -15
  142. package/lib/taskCommands.mjs +80 -20
  143. package/lib/taskRooms.mjs +125 -0
  144. package/lib/taskRuns.mjs +45 -3
  145. package/lib/team.json +255 -148
  146. package/lib/team.mjs +554 -190
  147. package/lib/threadActions.mjs +315 -0
  148. package/lib/threadAuthority.mjs +101 -0
  149. package/lib/threadBriefs.mjs +178 -0
  150. package/lib/threadLine.mjs +116 -0
  151. package/lib/threadRuns.mjs +209 -50
  152. package/lib/threadView.mjs +20 -7
  153. package/lib/usageTotals.mjs +2 -3
  154. package/lib/vault.mjs +101 -10
  155. package/lib/vaultCloud.mjs +2 -2
  156. package/lib/vaultCommands.mjs +15 -6
  157. package/lib/vaultTools.js +2 -2
  158. package/lib/verdicts.mjs +328 -0
  159. package/lib/wakes.mjs +1 -1
  160. package/lib/watches.mjs +2 -2
  161. package/lib/windowAsks.mjs +13 -5
  162. package/lib/worktrees.mjs +157 -25
  163. package/npm-shrinkwrap.json +1093 -0
  164. package/package.json +12 -11
  165. package/release.json +220 -0
  166. package/lib/modelTiers.json +0 -1183
  167. package/lib/modelTiers.mjs +0 -133
package/lib/phones.mjs CHANGED
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { readJson, writeJsonAtomic } from "./files.mjs";
5
5
  import { boardCommandsFor } from "./boardProtocol.mjs";
6
+ import { isPairCode, normalizeJoinCode } from "./machineSeal.mjs";
6
7
  import {
7
8
  b64u,
8
9
  channelKey,
@@ -22,27 +23,132 @@ import {
22
23
  // the coding sessions and run records Harness used to read in the clear.
23
24
 
24
25
  const OFFER_TTL_MS = 10 * 60_000;
26
+ // After the person turns down a browser's ask, Harness pages do not ask again for a day; after one they left
27
+ // unanswered, for an hour. Linking from the terminal (`tryharness link`) is never held back.
28
+ const REFUSED_QUIET_MS = 24 * 60 * 60_000;
29
+ const ASK_QUIET_MS = 60 * 60_000;
30
+ // A cloud computer's offer (cloudOffer) is minted for one window's link the moment the window asks, through Harness,
31
+ // and used at once, so it lives two minutes, not the ten a person needs to scan a code or open a link.
32
+ const CLOUD_OFFER_TTL_MS = 2 * 60_000;
25
33
  const MAX_OFFERS = 5;
26
34
  // A message queued at Harness while this computer slept may arrive up to 7 days late; only decisions and posts may.
27
35
  const QUEUED_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
28
36
  const QUEUEABLE = boardCommandsFor("queuedPhone");
37
+ // Of those, only what ends or clears work keeps the seven days. Anything that can start an agent (a Start, a post or an
38
+ // answer that wakes one, a message into a session) is the person's word for now: Harness holding it back for days must
39
+ // not turn it into a run they no longer expect. An hour covers a computer waking from sleep, not a carrier's delay.
40
+ const QUEUED_RUN_MAX_AGE_MS = 60 * 60 * 1000;
41
+ const QUEUED_ENDINGS = new Set([
42
+ "board.release",
43
+ "board.remove",
44
+ "board.thread.discard",
45
+ "board.thread.end",
46
+ "board.goal.stop",
47
+ "board.swarm.stop",
48
+ "board.swarm.stop_all",
49
+ ]);
50
+ const queuedMaxAge = (command) =>
51
+ QUEUED_ENDINGS.has(command) ? QUEUED_MAX_AGE_MS : QUEUED_RUN_MAX_AGE_MS;
29
52
  const ID = /^[A-Za-z0-9_-]{8,64}$/;
30
53
  const KEY = /^[A-Za-z0-9_-]{80,100}$/;
31
54
  const KINDS = new Set(["phone", "browser"]);
32
55
  const PHONE_COMMANDS = boardCommandsFor("phone");
33
- // What the chat owner does on the board, in Harness's name (was src/server/mcp/board.ts HARNESS_COMMANDS).
56
+ // What the chat owner does on the board, in Harness's name (the commands Harness's server once listed itself).
34
57
  const HARNESS_COMMANDS = boardCommandsFor("harnessBrowser");
35
58
  // The person's linked window also manages relay connections and reads lessons.
36
59
  const BROWSER_PERSON_COMMANDS = boardCommandsFor("browserPerson");
37
60
  // The person's own model lane (lane.mjs): only their linked Harness window gives it, sees whether it is kept, and takes it
38
61
  // back, and only as the person, never in a call Harness's chat makes.
39
62
  const LANE_COMMANDS = boardCommandsFor("browserLane");
63
+ // What a browser whose key the Harness extension holds may do as the person with no sign that they acted in the page:
64
+ // read, end or clear work, and the page's own bookkeeping (seen, followed, a backup's sync). Everything else (words that
65
+ // wake an agent, a Start, a grant, a decision) needs the extension to have seen them act there as it sealed the call
66
+ // (`gesture`, the page's transient user activation, which no script can make). The page is Harness's to serve; the
67
+ // extension's code is not, so this is how a page Harness's server changed cannot speak for the person through the key.
68
+ const WITHOUT_GESTURE = new Set([
69
+ "board.list",
70
+ "board.get",
71
+ "board.children",
72
+ "board.agents",
73
+ "board.thread.read",
74
+ "board.goal.list",
75
+ "board.goal.get",
76
+ "board.room.read",
77
+ "board.file.get",
78
+ "board.file.add",
79
+ "board.swarm.list",
80
+ "board.swarm.read",
81
+ "board.swarm.file",
82
+ "board.swarm.diff",
83
+ "board.swarm.agents",
84
+ "board.swarm.lessons",
85
+ "board.swarm.held",
86
+ "board.swarm.places",
87
+ "board.swarm.context",
88
+ "board.swarm.links",
89
+ "board.swarm.seen",
90
+ "board.swarm.follow",
91
+ "board.swarm.notice",
92
+ "board.swarm.specialty",
93
+ "board.live",
94
+ "board.live.read",
95
+ "board.standing.check",
96
+ "board.relay.list",
97
+ "board.relay.network",
98
+ "board.relay.peers",
99
+ "board.relay.seen",
100
+ "board.project.list",
101
+ "board.project.repos",
102
+ "board.project.read",
103
+ "board.project.held",
104
+ "board.repo.find",
105
+ "board.repo.clone.read",
106
+ "board.connector.list",
107
+ "board.connector.tools",
108
+ "board.connector.result",
109
+ "board.connector.operations",
110
+ "board.connector.refresh",
111
+ "board.environments.list",
112
+ "board.native.read",
113
+ "board.vault.list",
114
+ "board.vault.dismiss",
115
+ "board.vault.backup.sync",
116
+ // Ending or taking back is always the person's to do, whatever asked.
117
+ ...QUEUED_ENDINGS,
118
+ "board.swarm.discard",
119
+ "board.standing.off",
120
+ "board.connector.revoke",
121
+ "board.vault.revoke",
122
+ "board.vault.remove",
123
+ "board.vault.unshare",
124
+ "board.vault.backup.stop",
125
+ "board.project.withdraw",
126
+ "board.project.decline",
127
+ "board.project.leave",
128
+ ]);
129
+ const HOLDERS = new Set(["page", "extension"]);
130
+ // The person's devices on all their computers, and their answer to one waiting, from a phone or browser of theirs.
131
+ const DEVICE_DECISIONS = new Set(["devices.list", "devices.answer"]);
40
132
  const BROWSER_READS = boardCommandsFor("browserReads");
133
+ // The person's linked window adds a computer to the swarm: how a cloud worker joins, with home pinning its key exactly
134
+ // as for a code the person typed here. Only as the person, never in a Harness chat call.
135
+ const MACHINE_COMMANDS = boardCommandsFor("browserMachines");
136
+ // The person's window signs a cloud computer's agents in (agentSignIn.mjs) and picks the model each runs on
137
+ // (models.mjs): only there, and only as the person.
138
+ const SIGN_IN_COMMANDS = boardCommandsFor("browserSignIn");
139
+ // The person's window lets one of their cloud computers use a model endpoint this computer reaches (proxyLinks.mjs):
140
+ // only as the person, and with the extension's key only when it saw them act in the page, since the link opens what
141
+ // only this computer reaches to a computer Harness runs.
142
+ const LINK_COMMANDS = boardCommandsFor("browserLinks");
143
+ // The person's window lets their SSH key into this cloud computer (cloudSsh.mjs): only as the person, and with the
144
+ // extension's key only when it saw them act in the page.
145
+ const SSH_COMMANDS = boardCommandsFor("browserSsh");
41
146
 
42
147
  export async function createPhoneDesk({
43
148
  store,
44
149
  identityFile,
45
- // A browser link setup made before this daemon ran (writeBrowserOffer): taken in once, then the file is gone.
150
+ // A browser link setup made before this daemon ran (writeBrowserOffer). The file stays until the offer is used or
151
+ // expires, so a daemon that restarts in between (setup's own, an update, the service's keep-alive) still has it.
46
152
  setupOfferFile = null,
47
153
  boardCommand,
48
154
  reads = {},
@@ -50,13 +156,28 @@ export async function createPhoneDesk({
50
156
  onMessage = () => {},
51
157
  machine = () => null,
52
158
  lane = null,
159
+ machines = () => null,
160
+ // A cloud computer (config.cloud): Harness runs it, so Harness may ask it for a link offer for one of the person's
161
+ // windows (cloudOffer). Every other computer makes an offer only on this computer.
162
+ cloud = false,
163
+ signIn = null,
164
+ // The proxy links this computer holds for the person's cloud computers (proxyLinks.mjs), or null on a cloud computer.
165
+ links = null,
166
+ // A cloud computer's SSH keys (cloudSsh.mjs allow), or null where the person cannot SSH in.
167
+ ssh = null,
168
+ // Tells the person, on this computer, about their devices: a browser asking to link, a device newly linked.
169
+ notify = () => {},
170
+ // The swarm's one list of the person's devices (swarmDevices.mjs), or null: what lets a device in, and where the
171
+ // person's decision on one made elsewhere is carried out.
172
+ devices = () => null,
173
+ origin = () => null,
53
174
  }) {
54
175
  const identity = await loadOrCreateIdentity(identityFile);
55
176
  const offers = new Map();
56
177
  const keys = new Map();
57
178
  const hostname = os.hostname().slice(0, 64);
58
179
 
59
- const setupOffer = setupOfferFile ? takeSetupOffer(setupOfferFile) : null;
180
+ const setupOffer = setupOfferFile ? readSetupOffer(setupOfferFile) : null;
60
181
  if (setupOffer)
61
182
  offers.set(setupOffer.offerId, {
62
183
  secret: setupOffer.secret,
@@ -78,22 +199,32 @@ export async function createPhoneDesk({
78
199
  return keys.get(device.id);
79
200
  };
80
201
 
81
- // What the QR code or link carries. The secret and the daemon's key never pass through Harness.
82
- // The kind is fixed here, on the machine: a page cannot turn a phone's code into a browser's.
83
- const offer = (origin, kind = "phone") => {
84
- if (!KINDS.has(kind)) throw new Error(`unknown device kind ${kind}`);
202
+ // One pairing offer, kept here until it is used once or expires. `holder`: where the device keeps its key (only the
203
+ // extension's own request makes an "extension" one); `byHarness`: Harness's server asked for it (cloudOffer), so the
204
+ // device it links waits for the person (swarmDevices.mjs).
205
+ const mint = (kind, ttlMs, { holder = "page", byHarness = false } = {}) => {
206
+ if (!HOLDERS.has(holder)) throw new Error(`unknown key holder ${holder}`);
85
207
  sweep();
86
208
  if (offers.size >= MAX_OFFERS) offers.delete(offers.keys().next().value);
87
209
  const offerId = b64u(randomBytes(16));
88
210
  const secret = b64u(randomBytes(32));
89
- offers.set(offerId, { secret, kind, expiresAt: Date.now() + OFFER_TTL_MS });
90
- const fragment = new URLSearchParams({
91
- v: "1",
92
- o: offerId,
93
- s: secret,
94
- k: identity.publicKey,
95
- h: hostname,
211
+ offers.set(offerId, {
212
+ secret,
213
+ kind,
214
+ holder,
215
+ byHarness,
216
+ expiresAt: Date.now() + ttlMs,
96
217
  });
218
+ return { o: offerId, s: secret, k: identity.publicKey, h: hostname };
219
+ };
220
+
221
+ // What the QR code or link carries. The secret and the daemon's key never pass through Harness.
222
+ // The kind is fixed here, on the machine: a page cannot turn a phone's code into a browser's.
223
+ const offer = (origin, kind = "phone", { holder = "page" } = {}) => {
224
+ if (!KINDS.has(kind)) throw new Error(`unknown device kind ${kind}`);
225
+ const minted = mint(kind, OFFER_TTL_MS, { holder });
226
+ const offerId = minted.o;
227
+ const fragment = new URLSearchParams({ v: "1", ...minted });
97
228
  const page = kind === "browser" ? "/link" : "/m/pair";
98
229
  return {
99
230
  offerId,
@@ -103,6 +234,127 @@ export async function createPhoneDesk({
103
234
  };
104
235
  };
105
236
 
237
+ // A Harness page asking, through the extension's native host (nativeHost.mjs), for a link offer for its browser. The
238
+ // page is served by Harness, so it never gets one on its own word: the person allows it here, on the computer (the
239
+ // buddy's settings or `tryharness phone allow`). One ask waits at a time; another page's ask joins it. An ask the
240
+ // person turned down, or left, is not raised again for a while, so opening Harness does not nag.
241
+ const linkAsks = new Map();
242
+ let quietUntil = 0;
243
+ const askWords = (label) =>
244
+ `${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.`;
245
+ const settleAsk = (ask, state, url = null) => {
246
+ ask.state = state;
247
+ ask.url = url;
248
+ for (const wake of ask.waiters.splice(0)) wake();
249
+ };
250
+ const sweepAsks = () => {
251
+ const now = Date.now();
252
+ for (const ask of linkAsks.values())
253
+ if (ask.state === "waiting" && ask.expiresAt < now) {
254
+ settleAsk(ask, "expired");
255
+ quietUntil = Math.max(quietUntil, now + ASK_QUIET_MS);
256
+ }
257
+ for (const [id, ask] of linkAsks)
258
+ if (ask.expiresAt + OFFER_TTL_MS < now) linkAsks.delete(id);
259
+ };
260
+ const askLink = (label) => {
261
+ sweepAsks();
262
+ const waiting = [...linkAsks.values()].find(
263
+ (ask) => ask.state === "waiting"
264
+ );
265
+ if (waiting) return waiting;
266
+ if (Date.now() < quietUntil)
267
+ return { id: null, state: "refused", waiters: [] };
268
+ const ask = {
269
+ id: b64u(randomBytes(12)),
270
+ label: cleanLabel(label, "A browser"),
271
+ askedAt: new Date().toISOString(),
272
+ expiresAt: Date.now() + OFFER_TTL_MS,
273
+ state: "waiting",
274
+ url: null,
275
+ waiters: [],
276
+ };
277
+ linkAsks.set(ask.id, ask);
278
+ notify(askWords(ask.label), `ask:${ask.id}`);
279
+ // The person may answer it on any of their computers.
280
+ void devices()?.report();
281
+ return ask;
282
+ };
283
+ const linkAsk = {
284
+ /** The native host's ask: the same ask while it waits, answered once the person decides or it runs out. */
285
+ async request({ id = null, label, waitMs = 25_000 }) {
286
+ const ask = (id && linkAsks.get(String(id))) || askLink(label);
287
+ if (ask.state === "waiting")
288
+ await new Promise((resolve) => {
289
+ const timer = setTimeout(
290
+ resolve,
291
+ Math.max(0, Math.min(waitMs, ask.expiresAt - Date.now()))
292
+ );
293
+ ask.waiters.push(() => {
294
+ clearTimeout(timer);
295
+ resolve();
296
+ });
297
+ });
298
+ sweepAsks();
299
+ const url = ask.state === "allowed" ? ask.url : null;
300
+ // The offer goes to the one host that asked first; any later answer for this ask gets none.
301
+ if (url) ask.url = null;
302
+ const state = ask.state === "allowed" && !url ? "used" : ask.state;
303
+ return { ok: true, id: ask.id, state, url };
304
+ },
305
+ list: () => {
306
+ sweepAsks();
307
+ return [...linkAsks.values()]
308
+ .filter((ask) => ask.state === "waiting")
309
+ .map(({ id, label, askedAt }) => ({ id, label, askedAt }));
310
+ },
311
+ /** The person's answer, from this computer. */
312
+ answer(id, allow) {
313
+ sweepAsks();
314
+ const ask = linkAsks.get(String(id));
315
+ if (!ask || ask.state !== "waiting")
316
+ return { ok: false, error: "that browser is no longer asking" };
317
+ if (!allow) {
318
+ quietUntil = Date.now() + REFUSED_QUIET_MS;
319
+ settleAsk(ask, "refused");
320
+ void devices()?.report();
321
+ return { ok: true, state: "refused" };
322
+ }
323
+ const made = offer(origin() || "https://tryharness.ai", "browser");
324
+ settleAsk(ask, "allowed", made.url);
325
+ void devices()?.report();
326
+ return { ok: true, state: "allowed" };
327
+ },
328
+ };
329
+
330
+ // The Harness extension asking, through its native host, to hold this browser's link itself. Chrome starts the host
331
+ // only for the extension (nativeHost.mjs allowed_origins), and the extension asks on its own, never on a page's word,
332
+ // so no page Harness serves ever holds this key: the person is not asked, as setup's own link is not. The new device
333
+ // is told on this computer like any other.
334
+ const extensionOffer = (origin) => {
335
+ const made = offer(origin || "https://tryharness.ai", "browser", {
336
+ holder: "extension",
337
+ });
338
+ return { ok: true, fragment: new URL(made.url).hash };
339
+ };
340
+
341
+ /**
342
+ * A cloud computer's link offer for one of the person's windows, asked for by Harness's server, which runs this
343
+ * computer and already holds what the offer opens. Fresh on every ask, one use, two minutes: an offer read from
344
+ * Harness's database or a window's earlier answer links nothing, and every device it links shows in the person's
345
+ * list of this computer's devices.
346
+ */
347
+ const cloudOffer = () =>
348
+ cloud
349
+ ? {
350
+ ok: true,
351
+ offer: mint("browser", CLOUD_OFFER_TTL_MS, { byHarness: true }),
352
+ }
353
+ : {
354
+ ok: false,
355
+ error: "only a cloud computer makes a link offer for Harness",
356
+ };
357
+
106
358
  const pair = async (input) => {
107
359
  sweep();
108
360
  const { offerId, deviceId, devicePublicKey, proof, requestId } = input;
@@ -116,6 +368,9 @@ export async function createPhoneDesk({
116
368
  const pending = offers.get(String(offerId));
117
369
  // One attempt per code, right or wrong: a guessed proof burns the code.
118
370
  offers.delete(String(offerId));
371
+ const seeded = pending?.byHarness === true;
372
+ if (setupOffer && String(offerId) === setupOffer.offerId)
373
+ removeFile(setupOfferFile);
119
374
  if (!pending)
120
375
  return {
121
376
  ok: false,
@@ -136,17 +391,27 @@ export async function createPhoneDesk({
136
391
  return { ok: false, error: "the pairing proof did not match" };
137
392
  if (store.getPhone(String(deviceId)))
138
393
  return { ok: false, error: "this device is already paired" };
139
- const fallback = pending.kind === "browser" ? "Browser" : "Phone";
140
- const label =
141
- String(input.label || fallback)
142
- .replace(/[^\p{L}\p{N} ._'-]/gu, "")
143
- .slice(0, 40) || fallback;
394
+ const label = cleanLabel(
395
+ input.label,
396
+ pending.kind === "browser" ? "Browser" : "Phone"
397
+ );
144
398
  const device = store.addPhone({
145
399
  id: String(deviceId),
146
400
  label,
147
401
  publicKey: String(devicePublicKey),
148
402
  kind: pending.kind,
403
+ holder: pending.holder ?? "page",
149
404
  });
405
+ // An offer Harness asked for (a cloud computer's link for a window) lets nothing in by itself: the person allows the device.
406
+ const state = devices()?.paired(device, { seeded }) ?? "listed";
407
+ // Every new device is told on this computer, where the person can take it back: a page that paired one of its
408
+ // own is seen here.
409
+ notify(
410
+ state === "waiting"
411
+ ? `${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)}.`
412
+ : `${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)}.`,
413
+ `device:${device.id}`
414
+ );
150
415
  return {
151
416
  ok: true,
152
417
  envelope: await seal(
@@ -154,7 +419,14 @@ export async function createPhoneDesk({
154
419
  "d2p",
155
420
  device.id,
156
421
  String(requestId),
157
- { paired: true, hostname, label, kind: device.kind, version }
422
+ {
423
+ paired: true,
424
+ hostname,
425
+ label,
426
+ kind: device.kind,
427
+ version,
428
+ ...(state === "waiting" ? { waiting: true } : {}),
429
+ }
158
430
  ),
159
431
  };
160
432
  };
@@ -180,6 +452,13 @@ export async function createPhoneDesk({
180
452
  error: "this device was disconnected from the computer",
181
453
  code: "revoked",
182
454
  };
455
+ if (devices()?.waiting(device.id))
456
+ return {
457
+ ok: false,
458
+ error:
459
+ "this device waits for the person to allow it on one of their computers or devices (npx tryharness phone allow)",
460
+ code: "waiting",
461
+ };
183
462
  const key = await keyFor(device);
184
463
  let request;
185
464
  try {
@@ -202,7 +481,7 @@ export async function createPhoneDesk({
202
481
  typeof request?.ts === "number" ? Date.now() - request.ts : Infinity;
203
482
  if (
204
483
  queued
205
- ? age > QUEUED_MAX_AGE_MS || age < -MAX_SKEW_MS
484
+ ? age > queuedMaxAge(String(request.call.command)) || age < -MAX_SKEW_MS
206
485
  : Math.abs(age) > MAX_SKEW_MS
207
486
  )
208
487
  return {
@@ -210,7 +489,15 @@ export async function createPhoneDesk({
210
489
  error: "the message is too old or the device's clock is off",
211
490
  code: "stale",
212
491
  };
213
- if (!store.firstPhoneRequest(device.id, String(envelope.requestId)))
492
+ // Which kind of key sealed it, kept with the call's record. Only the extension says whether the person acted.
493
+ const holder = device.holder === "extension" ? "extension" : "page";
494
+ const gesture = holder === "extension" ? request?.gesture === true : null;
495
+ if (
496
+ !store.firstPhoneRequest(device.id, String(envelope.requestId), {
497
+ sealedBy: holder,
498
+ gesture,
499
+ })
500
+ )
214
501
  return {
215
502
  ok: false,
216
503
  error: "this message was already received",
@@ -219,6 +506,56 @@ export async function createPhoneDesk({
219
506
  store.touchPhone(device.id);
220
507
  // Any message from a paired device keeps a Mac in Standby awake for the next hour (Lid-Closed Mode).
221
508
  onMessage();
509
+ // A device moving its link to a new key (phoneChannel.ts rekey, from keys whose shared secret could be exported):
510
+ // asked under the old key, which opens nothing once the new one is kept.
511
+ if (request.call?.command === "phone.rekey") {
512
+ const publicKey = String(request.call.publicKey ?? "");
513
+ // The extension's keys were never exportable, so its link never moves: a page asking it to would take it.
514
+ if (!KEY.test(publicKey) || queued || holder === "extension")
515
+ return {
516
+ ok: true,
517
+ envelope: await seal(key, "d2p", device.id, envelope.requestId, {
518
+ ok: false,
519
+ error: "invalid key",
520
+ }),
521
+ };
522
+ store.rekeyPhone(device.id, publicKey);
523
+ keys.delete(device.id);
524
+ return {
525
+ ok: true,
526
+ envelope: await seal(key, "d2p", device.id, envelope.requestId, {
527
+ ok: true,
528
+ }),
529
+ };
530
+ }
531
+ // The extension took this browser's link over from the page (deskKey.js): the link the page held is retired, so a
532
+ // page Harness serves later cannot use it. Only a browser link a page held, and only from the extension's.
533
+ if (request.call?.command === "phone.retire") {
534
+ const retired = [];
535
+ if (holder === "extension" && !queued)
536
+ for (const id of (Array.isArray(request.call.ids)
537
+ ? request.call.ids
538
+ : []
539
+ ).slice(0, 8)) {
540
+ const other = store.getPhone(String(id));
541
+ if (
542
+ other &&
543
+ other.id !== device.id &&
544
+ other.kind === "browser" &&
545
+ other.holder !== "extension" &&
546
+ !other.revoked_at &&
547
+ revoke(other.id).ok
548
+ )
549
+ retired.push(other.id);
550
+ }
551
+ return {
552
+ ok: true,
553
+ envelope: await seal(key, "d2p", device.id, envelope.requestId, {
554
+ ok: holder === "extension",
555
+ retired,
556
+ }),
557
+ };
558
+ }
222
559
  if (request.call?.command === "phone.forget") {
223
560
  const forgotten = revoke(device.id);
224
561
  return {
@@ -228,7 +565,21 @@ export async function createPhoneDesk({
228
565
  }),
229
566
  };
230
567
  }
231
- const result = await answer(request.call, device);
568
+ // The person's Disconnect for another device, from one they paired; Harness's own calls through a browser never.
569
+ if (request.call?.command === "phone.revoke") {
570
+ const result =
571
+ request.call.as === "harness"
572
+ ? { ok: false, error: "only the person disconnects a device" }
573
+ : await disconnect(String(request.call.id || ""));
574
+ return {
575
+ ok: true,
576
+ envelope: await seal(key, "d2p", device.id, envelope.requestId, {
577
+ ok: result.ok,
578
+ ...(result.error ? { error: result.error } : {}),
579
+ }),
580
+ };
581
+ }
582
+ const result = await answer(request.call, device, { holder, gesture });
232
583
  return {
233
584
  ok: true,
234
585
  envelope: await seal(key, "d2p", device.id, envelope.requestId, result),
@@ -247,7 +598,28 @@ export async function createPhoneDesk({
247
598
  }
248
599
  };
249
600
 
250
- const answer = async (callInput, device) => {
601
+ // The person's devices across their computers, and their Allow or Don't allow for one waiting, from a device of
602
+ // theirs already let in (a waiting one is refused before this). Never Harness's chat; with the extension's key, only
603
+ // when it saw the person act in the page.
604
+ const decideOnDevices = async (command, callInput, sealedBy) => {
605
+ const swarm = devices();
606
+ if (!swarm || callInput?.as === "harness")
607
+ return { ok: false, error: "only the person allows a device" };
608
+ if (command === "devices.list") return { ok: true, swarm: swarm.list() };
609
+ if (sealedBy.holder === "extension" && !sealedBy.gesture)
610
+ return {
611
+ ok: false,
612
+ code: "gesture",
613
+ error:
614
+ "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.",
615
+ };
616
+ return swarm.decide(
617
+ String(callInput.id ?? ""),
618
+ callInput.allow === true ? "allow" : "refuse"
619
+ );
620
+ };
621
+
622
+ const answer = async (callInput, device, sealedBy) => {
251
623
  const command = String(callInput?.command || "");
252
624
  if (command === "phone.hello")
253
625
  return { ok: true, hostname, version, kind: device.kind };
@@ -257,6 +629,8 @@ export async function createPhoneDesk({
257
629
  ok: false,
258
630
  error: "a phone or browser attaches a file's content, not a path",
259
631
  };
632
+ if (DEVICE_DECISIONS.has(command))
633
+ return decideOnDevices(command, callInput, sealedBy);
260
634
  if (device.kind === "browser") {
261
635
  if (LANE_COMMANDS.has(command)) {
262
636
  if (!lane || callInput.as === "harness")
@@ -269,6 +643,101 @@ export async function createPhoneDesk({
269
643
  credentialSource: callInput.credentialSource,
270
644
  });
271
645
  }
646
+ if (SIGN_IN_COMMANDS.has(command)) {
647
+ if (!signIn || callInput.as === "harness")
648
+ return { ok: false, error: `a browser cannot call ${command} here` };
649
+ try {
650
+ if (command === "agents.signin.status") return signIn.status();
651
+ if (command === "agents.signin.start")
652
+ return signIn.start(
653
+ String(callInput.agent || ""),
654
+ callInput.plan === undefined ? undefined : String(callInput.plan)
655
+ );
656
+ if (command === "agents.signin.read")
657
+ return signIn.read(callInput.id);
658
+ if (command === "agents.signin.send")
659
+ return signIn.send(callInput.id, callInput.text);
660
+ if (command === "agents.signin.key")
661
+ return signIn.useKey(String(callInput.agent || ""), callInput.key);
662
+ if (command === "agents.signin.link")
663
+ return signIn.useLink(String(callInput.agent || ""), {
664
+ holder: callInput.holder,
665
+ holderLabel: callInput.holderLabel,
666
+ link: callInput.link,
667
+ model: callInput.model,
668
+ });
669
+ if (command === "agents.models")
670
+ return signIn.models(callInput.refresh === true);
671
+ if (command === "agents.model")
672
+ return signIn.setModel(
673
+ String(callInput.agent || ""),
674
+ callInput.model === null ? null : String(callInput.model || "")
675
+ );
676
+ return signIn.stop(callInput.id);
677
+ } catch (error) {
678
+ return { ok: false, error: error.message };
679
+ }
680
+ }
681
+ if (LINK_COMMANDS.has(command)) {
682
+ if (!links || callInput.as === "harness")
683
+ return {
684
+ ok: false,
685
+ error: cloud
686
+ ? "A proxy link is set up on your own computer that reaches your model, not on a cloud computer."
687
+ : `a browser cannot call ${command} here`,
688
+ };
689
+ if (command === "links.list") return links.list();
690
+ if (sealedBy.holder === "extension" && !sealedBy.gesture)
691
+ return {
692
+ ok: false,
693
+ code: "gesture",
694
+ error:
695
+ "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.",
696
+ };
697
+ if (command === "links.forget") return links.forget(callInput.id);
698
+ return links.allow({
699
+ computer: callInput.computer,
700
+ baseUrl: callInput.baseUrl,
701
+ key: callInput.key ?? null,
702
+ label: callInput.label ?? null,
703
+ });
704
+ }
705
+ if (SSH_COMMANDS.has(command)) {
706
+ if (!ssh || callInput.as === "harness")
707
+ return { ok: false, error: `a browser cannot call ${command} here` };
708
+ if (sealedBy.holder === "extension" && !sealedBy.gesture)
709
+ return {
710
+ ok: false,
711
+ code: "gesture",
712
+ error:
713
+ "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.",
714
+ };
715
+ return ssh({ key: String(callInput.key ?? ""), by: device.label });
716
+ }
717
+ if (MACHINE_COMMANDS.has(command)) {
718
+ const own = machines();
719
+ if (!own || callInput.as === "harness")
720
+ return { ok: false, error: `a browser cannot call ${command} here` };
721
+ if (command === "machines.list") return own.list();
722
+ // Only a join code, which confirms a computer already connected to the account and waiting to join; setup's
723
+ // 16-character code would also release a new computer's connection, which stays the buddy's and the CLI's.
724
+ const code = normalizeJoinCode(callInput.code);
725
+ if (!code || isPairCode(code))
726
+ return {
727
+ ok: false,
728
+ error: "a browser adds a computer only with its join code",
729
+ };
730
+ // A browser adds only a cloud computer, which Harness runs: it names that one computer and its key, so home
731
+ // tries the code on no other, and home keeps it as hosted, an agents' computer that is never the person.
732
+ const machine = String(callInput.machine || "");
733
+ const key = String(callInput.key || "");
734
+ if (!ID.test(machine) || !KEY.test(key))
735
+ return {
736
+ ok: false,
737
+ error: "a browser adds a computer only by naming it and its key",
738
+ };
739
+ return own.add(code, { machine, key, hosted: true });
740
+ }
272
741
  if (BROWSER_READS.has(command)) {
273
742
  const read = reads[command];
274
743
  if (!read)
@@ -281,6 +750,18 @@ export async function createPhoneDesk({
281
750
  }
282
751
  // The browser says whose call it is: the person's own action, or the chat owner's tool call.
283
752
  const as = callInput.as === "harness" ? "harness" : "user";
753
+ if (
754
+ as === "user" &&
755
+ sealedBy.holder === "extension" &&
756
+ !sealedBy.gesture &&
757
+ !WITHOUT_GESTURE.has(command)
758
+ )
759
+ return {
760
+ ok: false,
761
+ code: "gesture",
762
+ error:
763
+ "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.",
764
+ };
284
765
  if (
285
766
  !(as === "harness" ? HARNESS_COMMANDS : BROWSER_PERSON_COMMANDS).has(
286
767
  command
@@ -314,6 +795,8 @@ export async function createPhoneDesk({
314
795
  ...rest,
315
796
  command,
316
797
  agent: as,
798
+ // Which kind of key sealed it (a page's or the extension's) and whether the person acted, for rules after this.
799
+ sealedBy,
317
800
  // A Harness window's own call, which daemon.mjs checks before it takes a task given to Harness.
318
801
  fromWindow: as === "harness",
319
802
  // A connected app's or a secret's call from Harness's window is hosted, whatever the browser says: grants
@@ -424,14 +907,28 @@ export async function createPhoneDesk({
424
907
 
425
908
  const revoke = (id) => {
426
909
  keys.delete(String(id));
427
- return store.revokePhone(String(id));
910
+ const result = store.revokePhone(String(id));
911
+ void devices()?.report();
912
+ return result;
428
913
  };
914
+ // The person's Disconnect for any device of theirs: paired here, or with another of their computers.
915
+ const disconnect = async (id) =>
916
+ store.getPhone(id)
917
+ ? revoke(id)
918
+ : ((await devices()?.decide(id, "remove")) ?? {
919
+ ok: false,
920
+ error: "no phone with that id",
921
+ });
429
922
 
430
923
  return {
431
924
  offer,
925
+ linkAsk,
926
+ extensionOffer,
927
+ cloudOffer,
432
928
  handle,
433
929
  ask,
434
930
  revoke,
931
+ disconnect,
435
932
  list: () => store.phones(),
436
933
  publicKey: identity.publicKey,
437
934
  identity,
@@ -462,15 +959,25 @@ export async function writeBrowserOffer({ identityFile, offerFile }) {
462
959
  }).toString();
463
960
  }
464
961
 
465
- function takeSetupOffer(file) {
466
- const offer = readJson(file, null);
962
+ // A device's name as the person sees it in their list: whatever the page said, letters, digits and a few marks only.
963
+ const cleanLabel = (label, fallback) =>
964
+ String(label || fallback)
965
+ .replace(/[^\p{L}\p{N} ._'-]/gu, "")
966
+ .slice(0, 40) || fallback;
967
+
968
+ function removeFile(file) {
467
969
  try {
468
970
  fs.unlinkSync(file);
469
971
  } catch {}
470
- return offer &&
972
+ }
973
+
974
+ function readSetupOffer(file) {
975
+ const offer = readJson(file, null);
976
+ const usable =
977
+ offer &&
471
978
  ID.test(String(offer.offerId)) &&
472
979
  typeof offer.secret === "string" &&
473
- offer.expiresAt > Date.now()
474
- ? offer
475
- : null;
980
+ offer.expiresAt > Date.now();
981
+ if (!usable) removeFile(file);
982
+ return usable ? offer : null;
476
983
  }