tryharness 0.7.45 → 0.7.54

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 (125) hide show
  1. package/README.md +239 -14
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +497 -196
  5. package/lib/actorRoster.mjs +28 -5
  6. package/lib/adapters.mjs +165 -222
  7. package/lib/agentRuntimeConfig.mjs +36 -0
  8. package/lib/agentRuntimes.mjs +570 -0
  9. package/lib/agentSignIn.mjs +226 -0
  10. package/lib/atlas.mjs +7 -2
  11. package/lib/audit.mjs +643 -0
  12. package/lib/backupSetup.mjs +141 -0
  13. package/lib/boardAccess.mjs +8 -1
  14. package/lib/boardBackup.mjs +283 -0
  15. package/lib/boardCommands.mjs +5 -10
  16. package/lib/boardFileCommands.mjs +2 -1
  17. package/lib/boardMirror.mjs +523 -0
  18. package/lib/boardProtocol.json +263 -6
  19. package/lib/boardTools.mjs +2 -6
  20. package/lib/boardWaits.mjs +102 -0
  21. package/lib/book.mjs +659 -0
  22. package/lib/bridge.mjs +26 -4
  23. package/lib/browserWake.mjs +60 -0
  24. package/lib/cards.mjs +159 -16
  25. package/lib/cloudBoot.mjs +124 -0
  26. package/lib/commands.mjs +25 -5
  27. package/lib/connectionTools.d.ts +13 -0
  28. package/lib/connectionTools.js +45 -0
  29. package/lib/connectorAuth.mjs +309 -0
  30. package/lib/connectorCatalog.json +41 -0
  31. package/lib/connectorCommands.mjs +121 -0
  32. package/lib/connectorGoogle.mjs +513 -0
  33. package/lib/connectors.mjs +805 -0
  34. package/lib/context.mjs +18 -4
  35. package/lib/contractGate.mjs +377 -0
  36. package/lib/coordinator.mjs +152 -39
  37. package/lib/coreModels.mjs +78 -0
  38. package/lib/daemon.mjs +973 -54
  39. package/lib/desk.mjs +239 -0
  40. package/lib/desktop.mjs +113 -8
  41. package/lib/digest.mjs +32 -0
  42. package/lib/directLink.mjs +283 -0
  43. package/lib/environments.mjs +825 -0
  44. package/lib/folders.mjs +4 -4
  45. package/lib/gitHost.mjs +174 -0
  46. package/lib/goalCommands.mjs +58 -14
  47. package/lib/hookDialects.mjs +298 -0
  48. package/lib/inference.mjs +263 -152
  49. package/lib/landed.mjs +887 -0
  50. package/lib/lessons.mjs +6 -0
  51. package/lib/lineup.mjs +324 -0
  52. package/lib/live.mjs +284 -13
  53. package/lib/localmodels.mjs +10 -0
  54. package/lib/machineIdentity.mjs +3 -0
  55. package/lib/machineRoutes.mjs +40 -2
  56. package/lib/machineRuns.mjs +30 -3
  57. package/lib/machineSeal.mjs +69 -10
  58. package/lib/mcp-stdio.mjs +189 -120
  59. package/lib/mcpRelay.mjs +119 -0
  60. package/lib/members.json +26 -0
  61. package/lib/members.mjs +33 -0
  62. package/lib/modelMemory.mjs +100 -0
  63. package/lib/models.mjs +48 -15
  64. package/lib/museSession.mjs +122 -0
  65. package/lib/nativeHost.mjs +203 -0
  66. package/lib/neovim.mjs +126 -0
  67. package/lib/network.mjs +7 -2
  68. package/lib/nudge.mjs +57 -18
  69. package/lib/onboard.mjs +430 -1
  70. package/lib/oneclawLocal.mjs +150 -0
  71. package/lib/ownMachines.mjs +828 -39
  72. package/lib/pairing.mjs +182 -0
  73. package/lib/paths.mjs +8 -0
  74. package/lib/personModel.mjs +89 -0
  75. package/lib/phones.mjs +119 -3
  76. package/lib/placeCommands.mjs +27 -0
  77. package/lib/places.mjs +337 -9
  78. package/lib/plans.mjs +151 -27
  79. package/lib/profile.mjs +152 -0
  80. package/lib/projects.mjs +624 -137
  81. package/lib/readiness.mjs +400 -0
  82. package/lib/record.mjs +115 -0
  83. package/lib/repoLinks.mjs +354 -0
  84. package/lib/roomChannels.mjs +641 -0
  85. package/lib/runBrief.mjs +32 -2
  86. package/lib/runRequests.mjs +157 -0
  87. package/lib/runWorker.mjs +37 -9
  88. package/lib/runner.mjs +74 -11
  89. package/lib/secretPatterns.json +55 -0
  90. package/lib/secrets.mjs +10 -27
  91. package/lib/seen.mjs +102 -0
  92. package/lib/service.mjs +11 -6
  93. package/lib/sessionControl.mjs +386 -96
  94. package/lib/sessionIndex.mjs +5 -3
  95. package/lib/specialties.json +74 -0
  96. package/lib/specialties.mjs +477 -0
  97. package/lib/specialtyKeys.d.ts +3 -0
  98. package/lib/specialtyKeys.js +58 -0
  99. package/lib/specialtyNotice.mjs +147 -0
  100. package/lib/specialtySnapshot.mjs +138 -0
  101. package/lib/store.mjs +829 -29
  102. package/lib/subagents.mjs +8 -4
  103. package/lib/swarm.mjs +483 -37
  104. package/lib/swarmMemory.mjs +947 -0
  105. package/lib/t3.mjs +56 -17
  106. package/lib/taskCommands.mjs +91 -13
  107. package/lib/taskRuns.mjs +68 -11
  108. package/lib/team.json +253 -144
  109. package/lib/team.mjs +538 -147
  110. package/lib/threadLine.mjs +116 -0
  111. package/lib/threadRuns.mjs +78 -12
  112. package/lib/threadView.mjs +66 -16
  113. package/lib/tokenizer.mjs +405 -0
  114. package/lib/ui.mjs +16 -2
  115. package/lib/usageTotals.mjs +148 -0
  116. package/lib/vault.mjs +1144 -0
  117. package/lib/vaultCloud.mjs +117 -0
  118. package/lib/vaultCommands.mjs +201 -0
  119. package/lib/vaultTools.d.ts +12 -0
  120. package/lib/vaultTools.js +42 -0
  121. package/lib/windowAsks.mjs +42 -0
  122. package/lib/workFocus.mjs +59 -0
  123. package/lib/workLinks.mjs +90 -0
  124. package/lib/worktrees.mjs +51 -13
  125. package/package.json +10 -5
package/lib/members.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { paths } from "./paths.mjs";
2
3
 
3
4
  // The swarm's members, one entry each (members.json): who they are, which road they call in on, where their tasks
4
5
  // live (home), who runs their work (runs), whether others may hand them work (target) and how they are told work is
@@ -11,6 +12,38 @@ const ROSTER = JSON.parse(
11
12
 
12
13
  export const ROSTER_VERSION = ROSTER.version;
13
14
  export const MEMBERS = ROSTER.members;
15
+ // Custom ACP executables are local user configuration, never supplied by a task or a remote catalog.
16
+ try {
17
+ const configured = JSON.parse(readFileSync(paths.config, "utf8")).acpAgents;
18
+ for (const entry of Array.isArray(configured) ? configured : []) {
19
+ if (
20
+ !/^acp-[a-z0-9][a-z0-9-]{0,55}$/.test(entry.id) ||
21
+ MEMBERS.some((known) => known.id === entry.id) ||
22
+ typeof entry.command !== "string" ||
23
+ !entry.command.trim() ||
24
+ !Array.isArray(entry.args) ||
25
+ !entry.args.every((arg) => typeof arg === "string")
26
+ )
27
+ continue;
28
+ MEMBERS.push({
29
+ id: entry.id,
30
+ name: String(entry.name || entry.id),
31
+ aliases: [],
32
+ road: "local",
33
+ home: "machine",
34
+ runs: "machine",
35
+ target: true,
36
+ wake: "run",
37
+ review: false,
38
+ about:
39
+ "works in the thread's folder through its installed ACP executable",
40
+ where: "on this computer",
41
+ limits:
42
+ "Uses its own installed agent and authentication. Does not support restricted or read-only runs.",
43
+ runtime: { protocol: "acp", command: entry.command, args: entry.args },
44
+ });
45
+ }
46
+ } catch {}
14
47
  const byId = new Map(MEMBERS.map((entry) => [entry.id, entry]));
15
48
 
16
49
  export const member = (id) => byId.get(String(id)) ?? null;
@@ -0,0 +1,100 @@
1
+ import os from "node:os";
2
+
3
+ // The local models' share of the computer's memory. The relay sits beside everything else the person runs, a local
4
+ // agent model included, so its models together stay under a ceiling scaled to the machine: 6% of its memory, at least
5
+ // 500 MB (an 8 GB machine) and at most 2 GB. A model about to load makes room by unloading idle models, the least
6
+ // recently used first; a model in use is never unloaded, and a load waits for one to finish instead. A model larger than
7
+ // the ceiling loads only when nothing else is loaded.
8
+
9
+ const SHARE = 0.06;
10
+ const FLOOR_MB = 500;
11
+ const CAP_MB = 2_000;
12
+ // Models not yet measured are charged at one and a half times their files.
13
+ const UNMEASURED_FACTOR = 1.5;
14
+
15
+ export const memoryCeilingMb = (totalBytes = os.totalmem()) =>
16
+ Math.round(
17
+ Math.min(CAP_MB, Math.max(FLOOR_MB, (totalBytes / 2 ** 20) * SHARE))
18
+ );
19
+
20
+ /** What a model is charged: its measured peak (memoryMb in localmodels.mjs), or an allowance from its files' size. */
21
+ export function memoryCostMb(entry) {
22
+ if (entry.memoryMb) return entry.memoryMb;
23
+ const bytes = entry.files.reduce((sum, file) => sum + file.size, 0);
24
+ return Math.round((bytes / 2 ** 20) * UNMEASURED_FACTOR);
25
+ }
26
+
27
+ export function createModelMemory({ ceilingMb, log = () => {} }) {
28
+ const loaded = new Map();
29
+ const inUse = new Map();
30
+ let waiting = [];
31
+
32
+ const usedMb = () =>
33
+ [...loaded.values()].reduce((sum, model) => sum + model.mb, 0);
34
+ const wakeWaiting = () => {
35
+ const ready = waiting;
36
+ waiting = [];
37
+ for (const resolve of ready) resolve();
38
+ };
39
+ const leastRecentIdle = (except) =>
40
+ [...loaded.entries()]
41
+ .filter(([id]) => id !== except && !inUse.get(id))
42
+ .sort(([, a], [, b]) => a.usedAt - b.usedAt)[0];
43
+ const othersLoaded = (id) => [...loaded.keys()].some((other) => other !== id);
44
+
45
+ return {
46
+ ceilingMb,
47
+
48
+ /** Marks a model in use until the returned function is called. */
49
+ use(id) {
50
+ inUse.set(id, (inUse.get(id) ?? 0) + 1);
51
+ const model = loaded.get(id);
52
+ if (model) model.usedAt = performance.now();
53
+ let done = false;
54
+ return () => {
55
+ if (done) return;
56
+ done = true;
57
+ inUse.set(id, inUse.get(id) - 1);
58
+ wakeWaiting();
59
+ };
60
+ },
61
+
62
+ /**
63
+ * Makes room for a model about to load and counts it at mb; unload() takes it out of memory when room is needed.
64
+ * Admitting a loaded model again at a larger mb makes room for the difference (a server taking on another model).
65
+ */
66
+ async admit(id, mb, unload) {
67
+ const countedMb = () => loaded.get(id)?.mb ?? 0;
68
+ if (mb <= countedMb()) return;
69
+ for (;;) {
70
+ const fits = usedMb() - countedMb() + mb <= ceilingMb;
71
+ if (fits || !othersLoaded(id)) break;
72
+ const idle = leastRecentIdle(id);
73
+ if (idle) {
74
+ const [idleId, idleModel] = idle;
75
+ loaded.delete(idleId);
76
+ log(`local models: ${idleId} unloaded to make room for ${id}`);
77
+ await idleModel.unload();
78
+ continue;
79
+ }
80
+ await new Promise((resolve) => waiting.push(resolve));
81
+ }
82
+ if (mb > ceilingMb)
83
+ log(
84
+ `local models: ${id} needs ${mb} MB, over the ${ceilingMb} MB ceiling; it runs alone`
85
+ );
86
+ loaded.set(id, { mb, usedAt: performance.now(), unload });
87
+ },
88
+
89
+ /** A model that left on its own (idle, or its process exited). */
90
+ gone(id) {
91
+ if (loaded.delete(id)) wakeWaiting();
92
+ },
93
+
94
+ status: () => ({
95
+ ceilingMb,
96
+ usedMb: usedMb(),
97
+ models: [...loaded.keys()],
98
+ }),
99
+ };
100
+ }
package/lib/models.mjs CHANGED
@@ -3,8 +3,9 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { spawn } from "node:child_process";
5
5
  import { agentEnvironment } from "./agentnode.mjs";
6
- import { nameOf } from "./members.mjs";
6
+ import { MACHINE_RUNNERS, member, nameOf } from "./members.mjs";
7
7
  import { trackHelper } from "./runner.mjs";
8
+ import { listProtocolModels } from "./agentRuntimes.mjs";
8
9
 
9
10
  // Which model and effort each coding agent runs with, owned by the relay. Every agent lists its own models (Codex,
10
11
  // Pi and OpenCode have a command for it; Claude Code has none, so its list is its own short names plus the Anthropic
@@ -156,15 +157,23 @@ export const catalogOf = (store, agent) =>
156
157
  * Asks each installed agent for its models, all at once so one slow agent holds up no other, and keeps the lists; an
157
158
  * agent whose command fails keeps its last list and the error.
158
159
  */
159
- export async function refreshCatalogs(store, agents, log = () => {}) {
160
+ export async function refreshCatalogs(
161
+ store,
162
+ agents,
163
+ log = () => {},
164
+ { protocols = false } = {}
165
+ ) {
160
166
  await Promise.all(
161
167
  agents
162
- .filter((name) => LISTS[name])
168
+ .filter((name) => LISTS[name] || (protocols && member(name)?.runtime))
163
169
  .map(async (agent) => {
164
170
  try {
165
- const models = LISTS[agent]
166
- .parse(await capture(LISTS[agent].command, LISTS[agent].args))
167
- .filter((entry) => entry.id);
171
+ const offered = LISTS[agent]
172
+ ? LISTS[agent].parse(
173
+ await capture(LISTS[agent].command, LISTS[agent].args)
174
+ )
175
+ : await listProtocolModels(agent, trackHelper);
176
+ const models = offered.filter((entry) => entry.id);
168
177
  store.meta(
169
178
  catalogKey(agent),
170
179
  JSON.stringify({ at: new Date().toISOString(), models })
@@ -267,14 +276,22 @@ export function resolveSpec(store, agent, spec) {
267
276
  }
268
277
 
269
278
  /** The agents whose model the relay sets. */
270
- export const PICKABLE = new Set(["claude-code", ...Object.keys(LISTS)]);
279
+ export const PICKABLE = new Set(MACHINE_RUNNERS);
271
280
  const PICKED = /(?:^|\s)@([a-z][a-z0-9-]*):([^\s]+)/g;
272
281
  /** The picks a post names, `@codex:gpt-6-luna/high`, by agent: { picks: Map, error? }. Only agents in `agents` count. */
273
282
  export function picksIn(store, text, agents) {
274
283
  const picks = new Map();
275
284
  for (const match of String(text || "").matchAll(PICKED)) {
276
285
  const agent = match[1] === "claude" ? "claude-code" : match[1];
277
- if (!agents.includes(agent) || !PICKABLE.has(agent)) continue;
286
+ if (!agents.includes(agent)) continue;
287
+ if (!PICKABLE.has(agent)) {
288
+ if (member(agent)?.runtime)
289
+ return {
290
+ picks,
291
+ error: `${nameOf(agent)}'s model picker is not available yet. Select its model in the installed agent; Harness did not start a run with another model.`,
292
+ };
293
+ continue;
294
+ }
278
295
  const spec = match[2].replace(/[.,;:!?)]+$/, "");
279
296
  const resolved = resolveSpec(store, agent, spec);
280
297
  if (!resolved.ok)
@@ -391,16 +408,32 @@ export function agentModelSettings(id, home = os.homedir()) {
391
408
  };
392
409
  }
393
410
 
394
- // The person's choice in the relay (models.mjs), else what the agent's own settings name. Harness's is a model of its
395
- // catalog on a provider (harnessModel.mjs), else its last model, which no card names.
411
+ // The person's choice in the relay (models.mjs), else what the agent's own settings name, with the effort they name
412
+ // (Codex at xhigh says so on its card). Harness's is a model of its catalog on a provider (harnessModel.mjs), else its
413
+ // last model, which no card names.
396
414
  export const describeAgentModel = (store, id, home) => {
397
415
  const choice = choiceOf(store, id);
398
416
  if (id === "harness") return choice ? (choice.name ?? choice.model) : null;
399
- return choice?.auto
400
- ? "picked for each run by Auto"
401
- : choice
402
- ? describePick(choice)
403
- : agentModelSettings(id, home).model;
417
+ if (choice?.auto) return "picked for each run by Auto";
418
+ if (choice) return describePick(choice);
419
+ const own = agentModelSettings(id, home);
420
+ return own.model || own.effort ? describePick(own) : null;
421
+ };
422
+
423
+ /** What an agent runs on now, for its specialties (specialties.mjs): the person's choice, Auto, or its own settings. */
424
+ export const agentModelInUse = (store, id, home) => {
425
+ const choice = choiceOf(store, id);
426
+ if (choice?.auto) return { auto: true };
427
+ // A choice with no effort runs at its model's default (chooseForRun), so it is rated there.
428
+ if (choice?.model)
429
+ return {
430
+ model: choice.model,
431
+ effort:
432
+ choice.effort ??
433
+ findModel(store, id, choice.model)?.entry?.defaultEffort ??
434
+ null,
435
+ };
436
+ return agentModelSettings(id, home);
404
437
  };
405
438
 
406
439
  /** The pick named for one run (a post, post_task), kept with the run until it starts. */
@@ -0,0 +1,122 @@
1
+ import { fileURLToPath } from "node:url";
2
+
3
+ /** One owned Muse session, including tools and frames sent during its opening handshake. */
4
+ export async function openMuseSession({
5
+ host,
6
+ task,
7
+ signal,
8
+ onApproval,
9
+ onApprovalError,
10
+ observe = () => {},
11
+ }) {
12
+ const { Session, MspError, readSessionDurability } =
13
+ await import("@muse-code/sdk");
14
+ if (!host.initializeResult.grantedCapabilities.includes("sessionMcp"))
15
+ throw new Error(
16
+ "This Muse Code host does not offer session MCP tools. Update the installed CLI before running it with Harness."
17
+ );
18
+ const durability = readSessionDurability(host.initializeResult);
19
+ if (task.sessionId && durability.kind !== "durable")
20
+ throw new Error(
21
+ "This Muse host does not preserve sessions across processes. Harness did not start a replacement conversation."
22
+ );
23
+ const connection = host.connection;
24
+ let session = null;
25
+ let opening = true;
26
+ let closing = false;
27
+ let ended = false;
28
+ const held = [];
29
+ const route = (frame) => {
30
+ if (session && frame.params?.sessionId === session.sessionId) {
31
+ observe(
32
+ "stdout",
33
+ JSON.stringify({ type: "msp.notification", ...frame }) + "\n"
34
+ );
35
+ session.apply(frame);
36
+ } else if (opening) held.push(frame);
37
+ };
38
+ connection.onNotification(route);
39
+ connection.onServerRequest(async (request) => {
40
+ if (request.method === "approval/request") {
41
+ if (session && request.params?.sessionId !== session.sessionId)
42
+ throw new MspError({
43
+ code: -32602,
44
+ message: "This request belongs to another Muse session.",
45
+ data: { kind: "invalidParams", retryable: false },
46
+ });
47
+ route(request);
48
+ return {};
49
+ }
50
+ throw new MspError({
51
+ code: -32601,
52
+ message: `Unsupported Muse request: ${request.method}`,
53
+ data: { kind: "methodNotFound", retryable: false },
54
+ });
55
+ });
56
+ void connection.closed.then(() => {
57
+ ended = true;
58
+ if (!closing) session?.hostExited({ kind: "transportEof" });
59
+ });
60
+ void host.child.exit.then((exit) => {
61
+ ended = true;
62
+ session?.hostExited(exit);
63
+ });
64
+ const verb = task.sessionId ? "session/resume" : "session/start";
65
+ // A readiness check (readiness.mjs) runs without Harness's tools.
66
+ const config = {
67
+ mcpServers: task.withoutHarnessTools
68
+ ? {}
69
+ : {
70
+ harness: {
71
+ transport: "stdio",
72
+ mode: "required",
73
+ command: process.execPath,
74
+ args: [
75
+ fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)),
76
+ "--agent",
77
+ task.agent,
78
+ ],
79
+ env: { HARNESS_RUN_ID: task.runId },
80
+ },
81
+ },
82
+ };
83
+ signal.throwIfAborted();
84
+ const result = await connection.command(verb, {
85
+ config,
86
+ ...(task.sessionId
87
+ ? { sessionId: task.sessionId, excludeItems: true }
88
+ : {
89
+ workspaceRoot: task.cwd,
90
+ ...(task.model ? { modelId: task.model } : {}),
91
+ ...(task.approvalMode ? { approvalMode: task.approvalMode } : {}),
92
+ }),
93
+ });
94
+ signal.throwIfAborted();
95
+ if (ended)
96
+ throw new Error("The Muse host closed while opening this session.");
97
+ const sessionId = result.session?.sessionId;
98
+ if (!sessionId || (task.sessionId && sessionId !== task.sessionId))
99
+ throw new Error(
100
+ "Muse returned a different session identity. Harness did not submit the turn."
101
+ );
102
+ session = new Session({
103
+ connection,
104
+ durability,
105
+ sessionId,
106
+ opening: { verb, result },
107
+ });
108
+ if (onApproval) session.onApproval(onApproval);
109
+ if (onApprovalError) session.onApprovalError(onApprovalError);
110
+ opening = false;
111
+ for (const frame of held)
112
+ if (frame.params?.sessionId === sessionId) route(frame);
113
+ held.length = 0;
114
+ return {
115
+ session,
116
+ resumable: durability.kind === "durable",
117
+ close: async () => {
118
+ closing = true;
119
+ await host.close();
120
+ },
121
+ };
122
+ }
@@ -0,0 +1,203 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { paths } from "./paths.mjs";
5
+
6
+ // The Harness extension finds the daemon on its own computer through Chrome's native messaging: Chrome starts this
7
+ // host for the extension, one message in and one answer out, so the Harness window links to the computer it runs on
8
+ // with no `tryharness link`. The host says which computer this is (its public key and name) and, asked, makes a link
9
+ // offer for this browser exactly as `tryharness link` does; the page pairs with it through Harness, sealed.
10
+ //
11
+ // Only the extension named in the manifest's allowed_origins can start the host (Chrome enforces it). Its ID is fixed
12
+ // by the public key in packages/browser-extension/manifest.json, the Chrome Web Store item's.
13
+
14
+ export const HOST_NAME = "ai.tryharness.daemon";
15
+ export const EXTENSION_IDS = ["ekdjlnkjchjplkadglnaolilhpnokgok"];
16
+ // Chrome refuses a message from a host larger than 1 MB; ours are a few hundred bytes.
17
+ const MAX_MESSAGE_BYTES = 64 * 1024;
18
+
19
+ // Where each Chromium browser reads a person's own host manifests: its user data folder's NativeMessagingHosts.
20
+ // A browser that is not installed (its folder absent) gets none.
21
+ function browserFolders(platform, home) {
22
+ if (platform === "darwin") {
23
+ const support = path.join(home, "Library", "Application Support");
24
+ return [
25
+ "Google/Chrome",
26
+ "Google/Chrome Beta",
27
+ "Google/Chrome Canary",
28
+ "Chromium",
29
+ "BraveSoftware/Brave-Browser",
30
+ "Microsoft Edge",
31
+ "Vivaldi",
32
+ ].map((folder) => path.join(support, folder));
33
+ }
34
+ if (platform === "linux") {
35
+ const config = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
36
+ return [
37
+ "google-chrome",
38
+ "google-chrome-beta",
39
+ "chromium",
40
+ "BraveSoftware/Brave-Browser",
41
+ "microsoft-edge",
42
+ "vivaldi",
43
+ ].map((folder) => path.join(config, folder));
44
+ }
45
+ return [];
46
+ }
47
+
48
+ const manifestFor = (program) => ({
49
+ name: HOST_NAME,
50
+ description:
51
+ "Harness: links the Harness window to the daemon on this computer",
52
+ path: program,
53
+ type: "stdio",
54
+ allowed_origins: EXTENSION_IDS.map((id) => `chrome-extension://${id}/`),
55
+ });
56
+
57
+ /**
58
+ * Installs the host for every Chromium browser on this computer: a launcher in Harness's folder that runs this
59
+ * runtime's CLI, and a manifest beside each browser's profiles. Windows registers hosts in the registry instead, which
60
+ * this does not do yet; there the person links with `tryharness link`.
61
+ */
62
+ export function installNativeHost({
63
+ runtimeRoot,
64
+ nodePath = process.execPath,
65
+ platform = process.platform,
66
+ home = os.homedir(),
67
+ folders = browserFolders(platform, home),
68
+ }) {
69
+ if (platform !== "darwin" && platform !== "linux")
70
+ return {
71
+ installed: [],
72
+ skipped: `native messaging is not set up on ${platform}`,
73
+ };
74
+ const program = path.join(paths.home, "native-host");
75
+ fs.mkdirSync(paths.home, { recursive: true });
76
+ fs.writeFileSync(
77
+ program,
78
+ `#!/bin/sh\nexec ${shellQuote(nodePath)} ${shellQuote(path.join(runtimeRoot, "cli.mjs"))} native-host "$@"\n`,
79
+ { mode: 0o700 }
80
+ );
81
+ const installed = [];
82
+ for (const folder of folders) {
83
+ if (!fs.existsSync(folder)) continue;
84
+ const hosts = path.join(folder, "NativeMessagingHosts");
85
+ fs.mkdirSync(hosts, { recursive: true });
86
+ fs.writeFileSync(
87
+ path.join(hosts, `${HOST_NAME}.json`),
88
+ JSON.stringify(manifestFor(program), null, 2) + "\n"
89
+ );
90
+ installed.push(hosts);
91
+ }
92
+ return { installed, program };
93
+ }
94
+
95
+ /** Takes the host out of every browser and Harness's folder (`tryharness uninstall`). */
96
+ export function removeNativeHost({
97
+ platform = process.platform,
98
+ home = os.homedir(),
99
+ folders = browserFolders(platform, home),
100
+ } = {}) {
101
+ for (const folder of folders)
102
+ fs.rmSync(path.join(folder, "NativeMessagingHosts", `${HOST_NAME}.json`), {
103
+ force: true,
104
+ });
105
+ fs.rmSync(path.join(paths.home, "native-host"), { force: true });
106
+ }
107
+
108
+ const shellQuote = (value) => `'${String(value).replaceAll("'", `'\\''`)}'`;
109
+
110
+ /**
111
+ * The host itself, run by Chrome: reads length-prefixed JSON messages on `input` and answers each on `output`.
112
+ * `daemon(request)` is the daemon's control socket. Answers: `this-computer` with {publicKey, hostname, label, role},
113
+ * `computer-offer` with a pairing link's fragment for this browser.
114
+ */
115
+ export async function serveNativeHost({
116
+ input,
117
+ output,
118
+ daemon,
119
+ pauseMs = 10_000,
120
+ }) {
121
+ let closed = false;
122
+ let listening = false;
123
+ // `listen` (the extension's computerWake.js): from now on what this computer hands the Harness page is passed on as
124
+ // it comes. The daemon not running is waited out, never answered by closing: the open port is how the browser hears.
125
+ const listen = async () => {
126
+ while (!closed) {
127
+ const asked = await daemon(
128
+ { command: "browser.wake.next", waitMs: 25_000 },
129
+ 30_000
130
+ ).catch(() => null);
131
+ for (const message of asked?.messages ?? [])
132
+ if (!closed) writeMessage(output, { type: "for-harness", message });
133
+ if (!asked?.ok && !closed)
134
+ await new Promise((resolve) => setTimeout(resolve, pauseMs));
135
+ }
136
+ };
137
+ const answer = async (message) => {
138
+ if (message?.type === "listen") {
139
+ if (!listening) {
140
+ listening = true;
141
+ void listen();
142
+ }
143
+ return { ok: true, listening: true };
144
+ }
145
+ try {
146
+ if (message?.type === "this-computer") {
147
+ const found = await daemon({ command: "phone.identity" });
148
+ return found?.ok
149
+ ? {
150
+ ok: true,
151
+ computer: {
152
+ publicKey: found.publicKey,
153
+ hostname: found.hostname,
154
+ label: found.label ?? null,
155
+ role: found.role ?? null,
156
+ joined: found.joined !== false,
157
+ connected: found.connected !== false,
158
+ },
159
+ }
160
+ : { ok: false, error: found?.error || "the daemon did not say" };
161
+ }
162
+ if (message?.type === "computer-offer") {
163
+ const made = await daemon({ command: "phone.offer", kind: "browser" });
164
+ if (!made?.ok || typeof made.url !== "string")
165
+ return { ok: false, error: made?.error || "no offer was made" };
166
+ return { ok: true, fragment: new URL(made.url).hash };
167
+ }
168
+ return { ok: false, error: "unknown message" };
169
+ } catch (error) {
170
+ // The daemon not running is the common case: setup was never finished here, or it stopped.
171
+ return {
172
+ ok: false,
173
+ error: `the Harness daemon on this computer is not running (${error.message})`,
174
+ };
175
+ }
176
+ };
177
+ let buffered = Buffer.alloc(0);
178
+ for await (const chunk of input) {
179
+ buffered = Buffer.concat([buffered, chunk]);
180
+ while (buffered.length >= 4) {
181
+ const length = buffered.readUInt32LE(0);
182
+ if (length > MAX_MESSAGE_BYTES) return;
183
+ if (buffered.length < 4 + length) break;
184
+ const body = buffered.subarray(4, 4 + length).toString("utf8");
185
+ buffered = buffered.subarray(4 + length);
186
+ let message = null;
187
+ try {
188
+ message = JSON.parse(body);
189
+ } catch {
190
+ /* answered as unknown */
191
+ }
192
+ writeMessage(output, await answer(message));
193
+ }
194
+ }
195
+ closed = true;
196
+ }
197
+
198
+ export function writeMessage(output, message) {
199
+ const body = Buffer.from(JSON.stringify(message), "utf8");
200
+ const header = Buffer.alloc(4);
201
+ header.writeUInt32LE(body.length, 0);
202
+ output.write(Buffer.concat([header, body]));
203
+ }