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/cards.mjs CHANGED
@@ -1,15 +1,16 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { member, nameOf } from "./members.mjs";
3
3
  import { agentModelInUse, describeAgentModel } from "./models.mjs";
4
- import { tierOf } from "./modelTiers.mjs";
4
+ import { offices, pins, specialtiesOf } from "./specialties.mjs";
5
5
  import { oneLine } from "./oneLine.mjs";
6
6
 
7
7
  // Each of the person's agents as the others see it: one card, written the same way for every reader (the block an agent
8
8
  // is told when its session starts, list_agents, a thread's brief, the coordinator's round), so work goes to the agent
9
9
  // that fits. The roster says what it is for, what it cannot do, where it runs and whether it can review without changing
10
- // files; this machine adds its model (the person's choice in the relay, else the one its own settings name), how its
11
- // work on this board went, what it holds now, when it last looked, and the person's own note. Facts only: nothing here
12
- // says one agent is better than another.
10
+ // files; this machine adds its model and effort (the person's choice in the relay, else what its own settings name), its
11
+ // specialties with their evidence (specialties.mjs), the specialties the person pinned it for and the offices it holds,
12
+ // how its work on this board went, what it holds now, when it last looked, and the person's own note. Facts only:
13
+ // nothing here says one agent is better than another.
13
14
 
14
15
  // How a member hears that work is waiting for it: how it is set up to be woken (its setup from the daemon, { state, how }),
15
16
  // else its roster wake.
@@ -32,12 +33,21 @@ export const answersFor = (entry) =>
32
33
  const NOTE_LIMIT = 300;
33
34
  const noteKey = (id) => `agent-note:${id}`;
34
35
  export const noteOf = (store, id) => store.meta(noteKey(id)) || null;
35
- /** The tier the person set for an agent (top, middle or bottom), or null for the benchmark's. */
36
- export const tierChoice = (store, id) =>
37
- store.meta(`tier-choice:${id}`) || null;
38
- export function setTier(store, id, tier) {
39
- store.meta(`tier-choice:${id}`, tier ?? "");
40
- return tier ?? null;
36
+
37
+ /** An agent's specialties on the model and effort it runs on now (the person's choice, Auto, or its own settings). */
38
+ export function agentSpecialties(store, id, home) {
39
+ const roster = member(id) ?? {};
40
+ const inUse =
41
+ roster.runs === "machine" || id === "harness"
42
+ ? agentModelInUse(store, id, home)
43
+ : {};
44
+ const model = inUse.model ?? null;
45
+ const effort = inUse.effort ?? null;
46
+ return {
47
+ model,
48
+ effort,
49
+ specialties: specialtiesOf(store, id, { model, effort, harness: id }),
50
+ };
41
51
  }
42
52
 
43
53
  /** The person's own words about one agent ("use it for reviews"); empty clears it. */
@@ -56,6 +66,27 @@ const median = (values) => {
56
66
  return sorted.length ? sorted[Math.floor(sorted.length / 2)] : null;
57
67
  };
58
68
 
69
+ // A card's specialties, pins and offices as a coordinator round on Harness's server carries them: ids for pins and
70
+ // offices, each specialty without its name, which the server takes from the same list.
71
+ const roundSpecialty = (view) => ({
72
+ id: view.id,
73
+ source: view.source,
74
+ primary: view.primary,
75
+ evidence: view.evidence.slice(0, 300),
76
+ record: view.record
77
+ ? {
78
+ accepted: view.record.accepted,
79
+ rejected: view.record.rejected,
80
+ judged: view.record.judged,
81
+ }
82
+ : null,
83
+ });
84
+ export const roundFields = (card) => ({
85
+ specialties: card.specialties?.map(roundSpecialty),
86
+ pinned: card.pinned?.map((pin) => pin.id),
87
+ offices: card.offices?.map((office) => office.id),
88
+ });
89
+
59
90
  /** Cards for the given roster entries ({ id, setup? }), in their order. A card's setup is its state alone ("not_set_up"). */
60
91
  // `lessons`: what the person has said about each agent (lessons.mjs), left off a card going to a caller off this computer.
61
92
  export function swarmCards(store, entries, { home, lessons = true } = {}) {
@@ -95,6 +126,8 @@ export function swarmCards(store, entries, { home, lessons = true } = {}) {
95
126
  const checks = store.receiptCounts?.() ?? {};
96
127
  // The person's verdicts on its work (reactions.mjs; a store from before reactions has none).
97
128
  const verdicts = store.verdictCounts?.() ?? {};
129
+ const pinned = pins(store);
130
+ const held = offices(store);
98
131
  return entries.map((entry) => {
99
132
  const roster = member(entry.id) ?? {};
100
133
  const done = work.get(entry.id) ?? {
@@ -120,13 +153,14 @@ export function swarmCards(store, entries, { home, lessons = true } = {}) {
120
153
  : entry.id === "harness" && describeAgentModel(store, entry.id, home)
121
154
  ? { model: describeAgentModel(store, entry.id, home) }
122
155
  : {}),
123
- // How strong its model is, for the roles with a floor (team.json): the person's tier for it, else the benchmark's.
124
- tier: tierOf({
125
- ...(roster.runs === "machine" || entry.id === "harness"
126
- ? agentModelInUse(store, entry.id, home)
127
- : {}),
128
- chosen: tierChoice(store, entry.id),
129
- }),
156
+ // What it is shown to do well on its model, each with its evidence, primary first.
157
+ specialties: agentSpecialties(store, entry.id, home).specialties,
158
+ pinned: pinned
159
+ .filter((pin) => pin.agent === entry.id)
160
+ .map((pin) => ({ id: pin.specialty, name: pin.name })),
161
+ offices: held
162
+ .filter((office) => office.holder === entry.id)
163
+ .map((office) => ({ id: office.id, name: office.name })),
130
164
  answers: answersFor(entry),
131
165
  record: {
132
166
  done: done.done,
@@ -160,8 +194,48 @@ const span = (minutes) =>
160
194
  const sentence = (text) =>
161
195
  `${text.charAt(0).toUpperCase()}${text.slice(1)}${/[.!?]$/.test(text) ? "" : "."}`;
162
196
 
163
- /** One card as one line of plain text. */
164
- export function cardLine(card, now = Date.now()) {
197
+ const names = (entries) => entries.map((entry) => entry.name).join(", ");
198
+
199
+ /**
200
+ * What a card says of an agent's specialties, the specialties the person pinned it for and the offices it holds.
201
+ * `evidence`: each specialty with where it comes from (list_agents), else its name alone (a session start).
202
+ */
203
+ export function specialtiesLine(card, { evidence = true } = {}) {
204
+ const views = card.specialties;
205
+ if (!views) return "";
206
+ const parts = [];
207
+ if (!views.length)
208
+ parts.push(
209
+ !evidence
210
+ ? "No specialties yet."
211
+ : card.model
212
+ ? "No specialties yet: none from the benchmarks Harness tracks for its model, and no record here."
213
+ : "No specialties yet: no record here, and the person has added none."
214
+ );
215
+ else {
216
+ const shown = (view) =>
217
+ evidence && view.evidence ? `${view.name} (${view.evidence})` : view.name;
218
+ const primary = views.find((view) => view.primary) ?? views[0];
219
+ const others = views.filter((view) => view !== primary);
220
+ parts.push(`Primary: ${shown(primary)}.`);
221
+ if (others.length) parts.push(`Also: ${others.map(shown).join(", ")}.`);
222
+ // Its earned specialties came with it from its last model; its record on this one starts over.
223
+ if (
224
+ views.some((view) => view.earnedOn) &&
225
+ !views.some((view) => view.record?.judged)
226
+ )
227
+ parts.push("New model, earning its record here.");
228
+ }
229
+ if (card.pinned?.length) parts.push(`Pinned: ${names(card.pinned)}.`);
230
+ if (card.offices?.length)
231
+ parts.push(
232
+ `${card.offices.length > 1 ? "Offices" : "Office"}: ${names(card.offices)}.`
233
+ );
234
+ return parts.join(" ");
235
+ }
236
+
237
+ /** One card as one line of plain text; `evidence: false` names its specialties without their evidence. */
238
+ export function cardLine(card, now = Date.now(), { evidence = true } = {}) {
165
239
  const parts = [`@${card.id} (${card.name}): ${sentence(card.about)}`];
166
240
  if (card.limits) parts.push(card.limits);
167
241
  if (card.review !== undefined)
@@ -170,11 +244,19 @@ export function cardLine(card, now = Date.now()) {
170
244
  ? "Can review without changing files."
171
245
  : "Has no review-only mode: its runs may change files."
172
246
  );
173
- // The model is read from the agent's own settings, so it is one line like every other agent-written field here.
174
- if (card.where)
175
- parts.push(
176
- `Runs ${card.where}${card.model ? `, model ${oneLine(card.model)}` : ""}.`
177
- );
247
+ // The model and effort are read from the agent's own settings, so they are one line like every other agent-written
248
+ // field here. A setting that names an effort and no model says the effort alone.
249
+ if (card.where) {
250
+ const model = card.model ? oneLine(card.model) : "";
251
+ const named = !model
252
+ ? ""
253
+ : model.startsWith("effort ")
254
+ ? `, ${model}`
255
+ : `, model ${model}`;
256
+ parts.push(`Runs ${card.where}${named}.`);
257
+ }
258
+ const specialties = specialtiesLine(card, { evidence });
259
+ if (specialties) parts.push(specialties);
178
260
  if (card.machines?.length)
179
261
  parts.push(
180
262
  `On the person's computers: ${card.machines.map((computer) => `${card.name} (${computer.label}${computer.online ? "" : ", offline"})`).join(", ")}; name one with target_machine.`
@@ -220,7 +302,9 @@ export function cardLine(card, now = Date.now()) {
220
302
  /** One card in short form, for a session start short of room: who it is and what it is for. list_agents has the rest. */
221
303
  export function shortCardLine(card) {
222
304
  const unset = card.setup ? ` ${sentence(card.answers)}` : "";
223
- return `- @${card.id} (${card.name}): ${sentence(card.about)}${unset}`;
305
+ const primary = card.specialties?.find((view) => view.primary);
306
+ const known = primary ? ` Primary: ${primary.name}.` : "";
307
+ return `- @${card.id} (${card.name}): ${sentence(card.about)}${known}${unset}`;
224
308
  }
225
309
 
226
310
  /**
@@ -262,12 +346,20 @@ export const toldBlock = (told) =>
262
346
  ].join("\n")
263
347
  : "";
264
348
 
265
- /** The block an agent is told when its session starts: every other agent's card, and what the person has told the swarm. */
266
- export function swarmBlock(cards, now = Date.now(), told = []) {
349
+ /**
350
+ * Every other agent's card, and what the person has told the swarm: the block an agent is told when its session starts
351
+ * (`evidence: false`, specialties by name) and list_agents' text (each specialty with its evidence).
352
+ */
353
+ export function swarmBlock(
354
+ cards,
355
+ now = Date.now(),
356
+ told = [],
357
+ { evidence = true } = {}
358
+ ) {
267
359
  if (!cards.length) return toldBlock(told);
268
360
  return [
269
361
  SWARM_HEADER,
270
- ...cards.map((card) => cardLine(card, now)),
362
+ ...cards.map((card) => cardLine(card, now, { evidence })),
271
363
  ...(told.length ? ["", toldBlock(told)] : []),
272
364
  ].join("\n");
273
365
  }
@@ -291,6 +383,24 @@ export const swarmDigest = (cards, told = []) =>
291
383
  ...(card.machines ? [card.machines] : []),
292
384
  // Only when there are some, so a swarm with no lessons keeps the digest it had and is not told again.
293
385
  ...(card.lessons ? [card.lessons] : []),
386
+ // What it is good at, with each record, and the person's pins and appointments: agents are told again when
387
+ // any of it changes. Only when there are some, like the lessons.
388
+ ...(card.specialties?.length
389
+ ? [
390
+ card.specialties.map((view) => [
391
+ view.id,
392
+ view.source,
393
+ view.primary,
394
+ view.evidence,
395
+ ]),
396
+ ]
397
+ : []),
398
+ ...(card.pinned?.length
399
+ ? [card.pinned.map((pin) => `pin:${pin.id}`)]
400
+ : []),
401
+ ...(card.offices?.length
402
+ ? [card.offices.map((office) => `office:${office.id}`)]
403
+ : []),
294
404
  ])
295
405
  .concat(told.length ? [told.map((lesson) => lesson.text)] : [])
296
406
  )
@@ -0,0 +1,216 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { readFileSync } from "node:fs";
5
+ import { resolveCommand } from "./commands.mjs";
6
+
7
+ // The agents on a cloud computer (docs/cloud-swarm.md §4.0, §5.4). The person picks them in their window while the
8
+ // computer builds; Harness keeps the answer, and this module, on the computer itself, asks for it with the computer's
9
+ // own token and installs each chosen agent that is not here yet, as the harness user, then joins it to the swarm the
10
+ // way `tryharness agents add` does. It asks again whenever Harness says the answer changed, so "Add an agent" later is
11
+ // the same path. Nothing is removed here: an agent taken out of the setup stays installed and out of the lineup.
12
+ // Each installed agent then runs on the AI the person chose for it (setup.ai: Harness's, their plan, their key or
13
+ // their proxy link), applied by cloudAi.mjs after every sync.
14
+
15
+ const { cloud: CLOUD_LIST } = JSON.parse(
16
+ readFileSync(new URL("./members.json", import.meta.url), "utf8")
17
+ );
18
+
19
+ const quote = (value) => `'${String(value).replace(/'/g, `'"'"'`)}'`;
20
+
21
+ /** The command that installs one agent from the list: npm into ~/.local, or the agent's own install script. */
22
+ export function installCommand(row, home = os.homedir()) {
23
+ if (row.install.npm)
24
+ return [
25
+ "npm",
26
+ [
27
+ "install",
28
+ "--global",
29
+ "--prefix",
30
+ path.join(home, ".local"),
31
+ "--no-fund",
32
+ "--no-audit",
33
+ row.install.npm,
34
+ ],
35
+ ];
36
+ const args = (row.install.args ?? []).map(quote).join(" ");
37
+ return [
38
+ "bash",
39
+ [
40
+ "-c",
41
+ `set -o pipefail; curl -fsSL ${quote(row.install.script)} | bash${args ? ` -s -- ${args}` : ""}`,
42
+ ],
43
+ ];
44
+ }
45
+
46
+ export function createCloudAgents({
47
+ config,
48
+ log = () => {},
49
+ fetchImpl = fetch,
50
+ run = spawn,
51
+ env = process.env,
52
+ home = os.homedir(),
53
+ // Harness's own copy, in the harness user's home: the machine image may bring its own (Boat ships claude, codex,
54
+ // opencode, pi, hermes and openclaw in /usr/local/bin), which is not the one Harness installed or keeps updated.
55
+ installed = (row) =>
56
+ resolveCommand(row.command, env)?.startsWith(home + path.sep) ?? false,
57
+ // Puts one installed agent in the swarm (lineup.mjs joinAgent through the daemon's lineup commands).
58
+ join = () => ({ ok: true }),
59
+ // After a chat assistant is installed, when the person chose Telegram (cli/lib/cloudAssistants.mjs, another part).
60
+ afterAssistant = async () => {},
61
+ // Telegram moved to another computer or was turned off: the assistant comes off Harness's relay.
62
+ withoutAssistant = async () => {},
63
+ // Points the installed agents at the AI the person chose for each (cloudAi.mjs apply).
64
+ applyAi = async () => ({ failed: {} }),
65
+ }) {
66
+ const states = new Map();
67
+ // Whether each installed chat assistant is on Harness's relay now; unknown after a restart, so the first sync
68
+ // settles it either way.
69
+ const relayed = new Map();
70
+ let chosen = [];
71
+ let telegram = false;
72
+ let answers = {};
73
+ let running = null;
74
+ let again = false;
75
+
76
+ const setState = (agent, state, detail = null) => {
77
+ states.set(agent, { agent, state, detail });
78
+ log(`${agent}: ${state}${detail ? ` (${detail})` : ""}`);
79
+ };
80
+
81
+ const readSetup = async () => {
82
+ const response = await fetchImpl(
83
+ `${String(config.origin).replace(/\/$/, "")}/api/cloud/setup`,
84
+ { headers: { authorization: `Bearer ${config.token}` } }
85
+ );
86
+ if (!response.ok)
87
+ throw new Error(`Harness answered ${response.status} for the setup`);
88
+ const setup = await response.json();
89
+ return {
90
+ agents: Array.isArray(setup.agents) ? setup.agents.map(String) : [],
91
+ telegram: setup.telegram === true,
92
+ ai: setup.ai && typeof setup.ai === "object" ? setup.ai : {},
93
+ };
94
+ };
95
+
96
+ // An install runs to its end; its output stays on this computer, in the daemon's log only when it fails.
97
+ const install = (row) =>
98
+ new Promise((resolve) => {
99
+ const [command, args] = installCommand(row, home);
100
+ let tail = "";
101
+ const child = run(command, args, {
102
+ env: { ...env, HOME: home },
103
+ stdio: ["ignore", "pipe", "pipe"],
104
+ });
105
+ const keep = (chunk) => (tail = (tail + chunk).slice(-2000));
106
+ child.stdout?.on("data", keep);
107
+ child.stderr?.on("data", keep);
108
+ child.on("error", (error) =>
109
+ resolve({ ok: false, detail: error.message })
110
+ );
111
+ child.on("close", (code) =>
112
+ resolve(
113
+ code === 0
114
+ ? { ok: true }
115
+ : {
116
+ ok: false,
117
+ detail: `exit ${code}: ${tail.trim().split("\n").at(-1) ?? ""}`,
118
+ }
119
+ )
120
+ );
121
+ });
122
+
123
+ const bringUp = async (row) => {
124
+ if (!installed(row)) {
125
+ setState(row.agent, "installing");
126
+ const result = await install(row);
127
+ if (!result.ok || !installed(row))
128
+ return setState(
129
+ row.agent,
130
+ "failed",
131
+ result.detail ?? `${row.command} is not on the PATH after its install`
132
+ );
133
+ }
134
+ const joined = join(row.agent);
135
+ if (!joined?.ok)
136
+ return setState(row.agent, "failed", joined?.error ?? null);
137
+ setState(row.agent, "installed");
138
+ };
139
+
140
+ // Telegram can be turned on, moved here, or moved away long after an assistant was installed, so this runs on
141
+ // every sync, not only after an install.
142
+ const settleTelegram = async () => {
143
+ for (const row of CLOUD_LIST) {
144
+ if (row.signIn !== "assistant") continue;
145
+ if (states.get(row.agent)?.state !== "installed") continue;
146
+ const wanted = telegram && chosen.includes(row.agent);
147
+ if (relayed.get(row.agent) === wanted) continue;
148
+ try {
149
+ if (wanted) await afterAssistant({ agent: row.agent });
150
+ else await withoutAssistant({ agent: row.agent });
151
+ relayed.set(row.agent, wanted);
152
+ } catch (error) {
153
+ log(
154
+ `${row.agent}: Telegram not ${wanted ? "set up" : "turned off"}: ${error.message}`
155
+ );
156
+ }
157
+ }
158
+ };
159
+
160
+ const syncOnce = async () => {
161
+ const setup = await readSetup();
162
+ chosen = setup.agents;
163
+ telegram = setup.telegram;
164
+ answers = setup.ai;
165
+ // In the list's order, one at a time: two installers writing ~/.local at once can break each other.
166
+ for (const row of CLOUD_LIST) {
167
+ if (!chosen.includes(row.agent)) continue;
168
+ if (states.get(row.agent)?.state === "installed") continue;
169
+ if (!states.has(row.agent)) setState(row.agent, "waiting");
170
+ await bringUp(row);
171
+ }
172
+ await settleTelegram();
173
+ await applyAi({
174
+ answers,
175
+ agents: chosen.filter(
176
+ (agent) => states.get(agent)?.state === "installed"
177
+ ),
178
+ });
179
+ };
180
+
181
+ /** Ask Harness what the person chose and install what is missing; a call during a sync runs it once more after. */
182
+ const sync = () => {
183
+ if (running) {
184
+ again = true;
185
+ return running;
186
+ }
187
+ running = (async () => {
188
+ do {
189
+ again = false;
190
+ try {
191
+ await syncOnce();
192
+ } catch (error) {
193
+ log(`setup not read: ${error.message}`);
194
+ }
195
+ } while (again);
196
+ running = null;
197
+ })();
198
+ return running;
199
+ };
200
+
201
+ /** Each chosen agent's state, in the list's order, for the person's window. */
202
+ const status = () =>
203
+ CLOUD_LIST.filter((row) => chosen.includes(row.agent)).map(
204
+ (row) =>
205
+ states.get(row.agent) ?? {
206
+ agent: row.agent,
207
+ state: "waiting",
208
+ detail: null,
209
+ }
210
+ );
211
+
212
+ /** The AI the person chose for an agent here: "harness", "plan", "key" or "link"; null before Harness has said. */
213
+ const aiOf = (agent) => answers[agent] ?? null;
214
+
215
+ return { sync, status, aiOf, busy: () => Boolean(running) };
216
+ }