tryharness 0.7.54 → 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 (156) hide show
  1. package/README.md +15 -16
  2. package/cli.mjs +377 -62
  3. package/lib/activity.mjs +10 -10
  4. package/lib/adapters.mjs +16 -0
  5. package/lib/agentBinaries.mjs +71 -0
  6. package/lib/agentRuntimeConfig.mjs +1 -1
  7. package/lib/agentRuntimes.mjs +9 -3
  8. package/lib/agentSignIn.mjs +271 -41
  9. package/lib/answers.mjs +5 -5
  10. package/lib/archetypes.d.ts +64 -0
  11. package/lib/archetypes.js +989 -0
  12. package/lib/asks.mjs +4 -4
  13. package/lib/audit.mjs +36 -13
  14. package/lib/backupSetup.mjs +4 -2
  15. package/lib/boardAccess.mjs +17 -11
  16. package/lib/boardBackup.mjs +6 -6
  17. package/lib/boardFileCommands.mjs +6 -6
  18. package/lib/boardFiles.mjs +13 -12
  19. package/lib/boardMirror.mjs +82 -47
  20. package/lib/boardProtocol.json +30 -1
  21. package/lib/boardWaits.mjs +2 -3
  22. package/lib/book.mjs +6 -6
  23. package/lib/bridge.mjs +5 -5
  24. package/lib/cards.mjs +2 -2
  25. package/lib/cloudAgents.mjs +216 -0
  26. package/lib/cloudAi.mjs +1312 -0
  27. package/lib/cloudAssistants.mjs +242 -0
  28. package/lib/cloudBoot.mjs +81 -86
  29. package/lib/cloudSave.mjs +197 -0
  30. package/lib/cloudSsh.mjs +178 -0
  31. package/lib/context.mjs +3 -3
  32. package/lib/contractGate.mjs +34 -12
  33. package/lib/control-client.mjs +9 -1
  34. package/lib/controlSocket.mjs +86 -0
  35. package/lib/coordinator.mjs +103 -101
  36. package/lib/daemon.mjs +1128 -2865
  37. package/lib/desk.mjs +7 -6
  38. package/lib/desktop.mjs +72 -68
  39. package/lib/directLink.mjs +16 -5
  40. package/lib/environment.mjs +2 -1
  41. package/lib/environments.mjs +14 -6
  42. package/lib/firewall.mjs +9 -9
  43. package/lib/folders.mjs +18 -14
  44. package/lib/frames.mjs +2 -3
  45. package/lib/gitHost.mjs +3 -3
  46. package/lib/goalCommands.mjs +25 -7
  47. package/lib/goals.mjs +7 -7
  48. package/lib/guestRequests.mjs +94 -0
  49. package/lib/handoffs.mjs +8 -7
  50. package/lib/handover.mjs +4 -4
  51. package/lib/harnessModel.mjs +6 -6
  52. package/lib/harnessOffers.mjs +266 -0
  53. package/lib/inference.mjs +26 -8
  54. package/lib/jobAnswers.mjs +190 -0
  55. package/lib/landed.mjs +1 -1
  56. package/lib/lane.mjs +42 -11
  57. package/lib/lessons.mjs +16 -16
  58. package/lib/library.mjs +3 -3
  59. package/lib/lineup.mjs +3 -0
  60. package/lib/linkRelay.mjs +574 -0
  61. package/lib/localAgentAsk.mjs +74 -0
  62. package/lib/localStack.mjs +536 -0
  63. package/lib/localmodels.mjs +6 -4
  64. package/lib/loopBackstop.mjs +4 -4
  65. package/lib/machineIdentity.mjs +9 -1
  66. package/lib/machineRoutes.mjs +181 -2
  67. package/lib/machineRuns.mjs +76 -1
  68. package/lib/machineSeal.mjs +39 -12
  69. package/lib/mcp-stdio.mjs +96 -26
  70. package/lib/mcpRelay.mjs +1 -1
  71. package/lib/members.json +13 -0
  72. package/lib/members.mjs +1 -1
  73. package/lib/models.mjs +77 -23
  74. package/lib/museSession.mjs +6 -1
  75. package/lib/nativeHost.mjs +35 -7
  76. package/lib/network.mjs +50 -5
  77. package/lib/notify.mjs +7 -5
  78. package/lib/nudge.mjs +3 -3
  79. package/lib/ocr.mjs +9 -9
  80. package/lib/onboard.mjs +26 -20
  81. package/lib/oneLine.mjs +7 -7
  82. package/lib/ownMachines.mjs +928 -149
  83. package/lib/pairing.mjs +33 -6
  84. package/lib/paths.mjs +15 -1
  85. package/lib/peerProcess.mjs +124 -0
  86. package/lib/personModel.mjs +3 -3
  87. package/lib/personNotices.mjs +151 -0
  88. package/lib/phones.mjs +490 -38
  89. package/lib/placeCommands.mjs +4 -4
  90. package/lib/places.mjs +70 -2
  91. package/lib/profile.mjs +67 -14
  92. package/lib/projectGit.mjs +158 -14
  93. package/lib/projectPieces.mjs +902 -0
  94. package/lib/projectSettings.mjs +7 -4
  95. package/lib/projects.mjs +384 -62
  96. package/lib/provenance.mjs +5 -1
  97. package/lib/proxyLinks.mjs +267 -0
  98. package/lib/reactions.mjs +7 -5
  99. package/lib/readiness.mjs +12 -7
  100. package/lib/record.mjs +19 -6
  101. package/lib/redact.mjs +4 -4
  102. package/lib/relayLimits.mjs +62 -0
  103. package/lib/release.mjs +170 -0
  104. package/lib/releaseKeys.json +6 -0
  105. package/lib/repoLinks.mjs +4 -4
  106. package/lib/roomChannels.mjs +24 -0
  107. package/lib/roomPage.mjs +1 -1
  108. package/lib/runAuthority.mjs +101 -0
  109. package/lib/runBrief.mjs +19 -8
  110. package/lib/runWorker.mjs +14 -5
  111. package/lib/runner.mjs +215 -25
  112. package/lib/runtime-install.mjs +143 -9
  113. package/lib/schedules.mjs +2 -2
  114. package/lib/screens.mjs +1 -1
  115. package/lib/sealed.mjs +11 -2
  116. package/lib/sealedThreads.mjs +671 -0
  117. package/lib/secretPatterns.json +1 -1
  118. package/lib/secrets.mjs +4 -4
  119. package/lib/seen.mjs +6 -6
  120. package/lib/serverWords.mjs +175 -0
  121. package/lib/service.mjs +22 -12
  122. package/lib/sessionControl.mjs +6 -6
  123. package/lib/specialties.mjs +6 -6
  124. package/lib/specialtyKeys.js +4 -5
  125. package/lib/specialtyNotice.mjs +7 -7
  126. package/lib/specialtySnapshot.mjs +5 -5
  127. package/lib/speech.mjs +5 -5
  128. package/lib/store.mjs +140 -39
  129. package/lib/stuck.mjs +1 -1
  130. package/lib/swarm.mjs +167 -16
  131. package/lib/swarmDevices.mjs +319 -0
  132. package/lib/swarmMemory.mjs +27 -25
  133. package/lib/t3.mjs +13 -13
  134. package/lib/taskCommands.mjs +44 -11
  135. package/lib/taskRooms.mjs +125 -0
  136. package/lib/taskRuns.mjs +36 -1
  137. package/lib/team.mjs +41 -18
  138. package/lib/threadActions.mjs +315 -0
  139. package/lib/threadAuthority.mjs +101 -0
  140. package/lib/threadBriefs.mjs +178 -0
  141. package/lib/threadLine.mjs +2 -2
  142. package/lib/threadRuns.mjs +138 -43
  143. package/lib/threadView.mjs +5 -5
  144. package/lib/usageTotals.mjs +2 -3
  145. package/lib/vault.mjs +101 -10
  146. package/lib/vaultCloud.mjs +2 -2
  147. package/lib/vaultCommands.mjs +15 -6
  148. package/lib/vaultTools.js +2 -2
  149. package/lib/verdicts.mjs +328 -0
  150. package/lib/wakes.mjs +1 -1
  151. package/lib/watches.mjs +2 -2
  152. package/lib/windowAsks.mjs +13 -5
  153. package/lib/worktrees.mjs +112 -18
  154. package/npm-shrinkwrap.json +1093 -0
  155. package/package.json +11 -10
  156. package/release.json +220 -0
package/lib/phones.mjs CHANGED
@@ -23,27 +23,126 @@ import {
23
23
  // the coding sessions and run records Harness used to read in the clear.
24
24
 
25
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;
26
33
  const MAX_OFFERS = 5;
27
34
  // A message queued at Harness while this computer slept may arrive up to 7 days late; only decisions and posts may.
28
35
  const QUEUED_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
29
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;
30
52
  const ID = /^[A-Za-z0-9_-]{8,64}$/;
31
53
  const KEY = /^[A-Za-z0-9_-]{80,100}$/;
32
54
  const KINDS = new Set(["phone", "browser"]);
33
55
  const PHONE_COMMANDS = boardCommandsFor("phone");
34
- // 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).
35
57
  const HARNESS_COMMANDS = boardCommandsFor("harnessBrowser");
36
58
  // The person's linked window also manages relay connections and reads lessons.
37
59
  const BROWSER_PERSON_COMMANDS = boardCommandsFor("browserPerson");
38
60
  // The person's own model lane (lane.mjs): only their linked Harness window gives it, sees whether it is kept, and takes it
39
61
  // back, and only as the person, never in a call Harness's chat makes.
40
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"]);
41
132
  const BROWSER_READS = boardCommandsFor("browserReads");
42
- // The person's linked window adds a computer to the swarm (docs/cloud-swarm.md §5.5): how a cloud worker joins, with
43
- // home pinning its key exactly as for a code the person typed here. Only as the person, never in a Harness chat call.
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.
44
135
  const MACHINE_COMMANDS = boardCommandsFor("browserMachines");
45
- // The person's window signs a cloud computer's agents in (agentSignIn.mjs): only there, and only as the person.
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.
46
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");
47
146
 
48
147
  export async function createPhoneDesk({
49
148
  store,
@@ -58,10 +157,20 @@ export async function createPhoneDesk({
58
157
  machine = () => null,
59
158
  lane = null,
60
159
  machines = () => null,
61
- // A cloud computer's link offer (cloudBoot.mjs): made by Harness, which runs the computer, and kept until the
62
- // computer is removed, so any of the person's windows can link to it. Every other computer has none.
63
- seededOffer = 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,
64
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,
65
174
  }) {
66
175
  const identity = await loadOrCreateIdentity(identityFile);
67
176
  const offers = new Map();
@@ -90,22 +199,32 @@ export async function createPhoneDesk({
90
199
  return keys.get(device.id);
91
200
  };
92
201
 
93
- // What the QR code or link carries. The secret and the daemon's key never pass through Harness.
94
- // The kind is fixed here, on the machine: a page cannot turn a phone's code into a browser's.
95
- const offer = (origin, kind = "phone") => {
96
- 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}`);
97
207
  sweep();
98
208
  if (offers.size >= MAX_OFFERS) offers.delete(offers.keys().next().value);
99
209
  const offerId = b64u(randomBytes(16));
100
210
  const secret = b64u(randomBytes(32));
101
- offers.set(offerId, { secret, kind, expiresAt: Date.now() + OFFER_TTL_MS });
102
- const fragment = new URLSearchParams({
103
- v: "1",
104
- o: offerId,
105
- s: secret,
106
- k: identity.publicKey,
107
- h: hostname,
211
+ offers.set(offerId, {
212
+ secret,
213
+ kind,
214
+ holder,
215
+ byHarness,
216
+ expiresAt: Date.now() + ttlMs,
108
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 });
109
228
  const page = kind === "browser" ? "/link" : "/m/pair";
110
229
  return {
111
230
  offerId,
@@ -115,6 +234,127 @@ export async function createPhoneDesk({
115
234
  };
116
235
  };
117
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
+
118
358
  const pair = async (input) => {
119
359
  sweep();
120
360
  const { offerId, deviceId, devicePublicKey, proof, requestId } = input;
@@ -125,13 +365,10 @@ export async function createPhoneDesk({
125
365
  !KEY.test(String(devicePublicKey))
126
366
  )
127
367
  return { ok: false, error: "invalid pairing request" };
128
- const seeded = seededOffer?.offerId === String(offerId);
129
- const pending = seeded
130
- ? { secret: seededOffer.secret, kind: "browser" }
131
- : offers.get(String(offerId));
132
- // One attempt per code, right or wrong: a guessed proof burns the code. The cloud offer's secret is 256 random bits
133
- // that only Harness and the person's windows hold, so it is not burned.
134
- if (!seeded) offers.delete(String(offerId));
368
+ const pending = offers.get(String(offerId));
369
+ // One attempt per code, right or wrong: a guessed proof burns the code.
370
+ offers.delete(String(offerId));
371
+ const seeded = pending?.byHarness === true;
135
372
  if (setupOffer && String(offerId) === setupOffer.offerId)
136
373
  removeFile(setupOfferFile);
137
374
  if (!pending)
@@ -154,17 +391,27 @@ export async function createPhoneDesk({
154
391
  return { ok: false, error: "the pairing proof did not match" };
155
392
  if (store.getPhone(String(deviceId)))
156
393
  return { ok: false, error: "this device is already paired" };
157
- const fallback = pending.kind === "browser" ? "Browser" : "Phone";
158
- const label =
159
- String(input.label || fallback)
160
- .replace(/[^\p{L}\p{N} ._'-]/gu, "")
161
- .slice(0, 40) || fallback;
394
+ const label = cleanLabel(
395
+ input.label,
396
+ pending.kind === "browser" ? "Browser" : "Phone"
397
+ );
162
398
  const device = store.addPhone({
163
399
  id: String(deviceId),
164
400
  label,
165
401
  publicKey: String(devicePublicKey),
166
402
  kind: pending.kind,
403
+ holder: pending.holder ?? "page",
167
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
+ );
168
415
  return {
169
416
  ok: true,
170
417
  envelope: await seal(
@@ -172,7 +419,14 @@ export async function createPhoneDesk({
172
419
  "d2p",
173
420
  device.id,
174
421
  String(requestId),
175
- { 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
+ }
176
430
  ),
177
431
  };
178
432
  };
@@ -198,6 +452,13 @@ export async function createPhoneDesk({
198
452
  error: "this device was disconnected from the computer",
199
453
  code: "revoked",
200
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
+ };
201
462
  const key = await keyFor(device);
202
463
  let request;
203
464
  try {
@@ -220,7 +481,7 @@ export async function createPhoneDesk({
220
481
  typeof request?.ts === "number" ? Date.now() - request.ts : Infinity;
221
482
  if (
222
483
  queued
223
- ? age > QUEUED_MAX_AGE_MS || age < -MAX_SKEW_MS
484
+ ? age > queuedMaxAge(String(request.call.command)) || age < -MAX_SKEW_MS
224
485
  : Math.abs(age) > MAX_SKEW_MS
225
486
  )
226
487
  return {
@@ -228,7 +489,15 @@ export async function createPhoneDesk({
228
489
  error: "the message is too old or the device's clock is off",
229
490
  code: "stale",
230
491
  };
231
- 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
+ )
232
501
  return {
233
502
  ok: false,
234
503
  error: "this message was already received",
@@ -237,6 +506,56 @@ export async function createPhoneDesk({
237
506
  store.touchPhone(device.id);
238
507
  // Any message from a paired device keeps a Mac in Standby awake for the next hour (Lid-Closed Mode).
239
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
+ }
240
559
  if (request.call?.command === "phone.forget") {
241
560
  const forgotten = revoke(device.id);
242
561
  return {
@@ -246,7 +565,21 @@ export async function createPhoneDesk({
246
565
  }),
247
566
  };
248
567
  }
249
- 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 });
250
583
  return {
251
584
  ok: true,
252
585
  envelope: await seal(key, "d2p", device.id, envelope.requestId, result),
@@ -265,7 +598,28 @@ export async function createPhoneDesk({
265
598
  }
266
599
  };
267
600
 
268
- 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) => {
269
623
  const command = String(callInput?.command || "");
270
624
  if (command === "phone.hello")
271
625
  return { ok: true, hostname, version, kind: device.kind };
@@ -275,6 +629,8 @@ export async function createPhoneDesk({
275
629
  ok: false,
276
630
  error: "a phone or browser attaches a file's content, not a path",
277
631
  };
632
+ if (DEVICE_DECISIONS.has(command))
633
+ return decideOnDevices(command, callInput, sealedBy);
278
634
  if (device.kind === "browser") {
279
635
  if (LANE_COMMANDS.has(command)) {
280
636
  if (!lane || callInput.as === "harness")
@@ -293,18 +649,71 @@ export async function createPhoneDesk({
293
649
  try {
294
650
  if (command === "agents.signin.status") return signIn.status();
295
651
  if (command === "agents.signin.start")
296
- return signIn.start(String(callInput.agent || ""));
652
+ return signIn.start(
653
+ String(callInput.agent || ""),
654
+ callInput.plan === undefined ? undefined : String(callInput.plan)
655
+ );
297
656
  if (command === "agents.signin.read")
298
657
  return signIn.read(callInput.id);
299
658
  if (command === "agents.signin.send")
300
659
  return signIn.send(callInput.id, callInput.text);
301
660
  if (command === "agents.signin.key")
302
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
+ );
303
676
  return signIn.stop(callInput.id);
304
677
  } catch (error) {
305
678
  return { ok: false, error: error.message };
306
679
  }
307
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
+ }
308
717
  if (MACHINE_COMMANDS.has(command)) {
309
718
  const own = machines();
310
719
  if (!own || callInput.as === "harness")
@@ -318,7 +727,16 @@ export async function createPhoneDesk({
318
727
  ok: false,
319
728
  error: "a browser adds a computer only with its join code",
320
729
  };
321
- return own.add(code);
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 });
322
740
  }
323
741
  if (BROWSER_READS.has(command)) {
324
742
  const read = reads[command];
@@ -332,6 +750,18 @@ export async function createPhoneDesk({
332
750
  }
333
751
  // The browser says whose call it is: the person's own action, or the chat owner's tool call.
334
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
+ };
335
765
  if (
336
766
  !(as === "harness" ? HARNESS_COMMANDS : BROWSER_PERSON_COMMANDS).has(
337
767
  command
@@ -365,6 +795,8 @@ export async function createPhoneDesk({
365
795
  ...rest,
366
796
  command,
367
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,
368
800
  // A Harness window's own call, which daemon.mjs checks before it takes a task given to Harness.
369
801
  fromWindow: as === "harness",
370
802
  // A connected app's or a secret's call from Harness's window is hosted, whatever the browser says: grants
@@ -475,14 +907,28 @@ export async function createPhoneDesk({
475
907
 
476
908
  const revoke = (id) => {
477
909
  keys.delete(String(id));
478
- return store.revokePhone(String(id));
910
+ const result = store.revokePhone(String(id));
911
+ void devices()?.report();
912
+ return result;
479
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
+ });
480
922
 
481
923
  return {
482
924
  offer,
925
+ linkAsk,
926
+ extensionOffer,
927
+ cloudOffer,
483
928
  handle,
484
929
  ask,
485
930
  revoke,
931
+ disconnect,
486
932
  list: () => store.phones(),
487
933
  publicKey: identity.publicKey,
488
934
  identity,
@@ -513,6 +959,12 @@ export async function writeBrowserOffer({ identityFile, offerFile }) {
513
959
  }).toString();
514
960
  }
515
961
 
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
+
516
968
  function removeFile(file) {
517
969
  try {
518
970
  fs.unlinkSync(file);