tryharness 0.7.54 → 0.7.58

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 +384 -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 +141 -50
  81. package/lib/oneLine.mjs +7 -7
  82. package/lib/ownMachines.mjs +928 -149
  83. package/lib/pairing.mjs +39 -8
  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
@@ -0,0 +1,178 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+
6
+ // SSH into a cloud computer (docs/cloud-swarm.md §7), both ends of it.
7
+ //
8
+ // On the box: the keys the person's own devices allowed (createCloudSsh). Boat puts a key on a sandbox for its own
9
+ // account when Harness's server asks, so Harness's server could put one there on its own word. The box's sshd
10
+ // therefore reads, for that account, only the file kept here (bootScript.ts sshGate), and this file is written only
11
+ // when one of the person's registered devices asks: their own computer over the sealed line between their computers
12
+ // (ownMachines.mjs), or a window linked to this computer (phones.mjs). Never on a call from Harness's server.
13
+ //
14
+ // On the person's computer: the key to send (their own, never made here), and the ssh command that pins the host key
15
+ // the box has now, which changes with every resume.
16
+
17
+ const KEY_TYPES = new Set([
18
+ "ssh-ed25519",
19
+ "ecdsa-sha2-nistp256",
20
+ "ecdsa-sha2-nistp384",
21
+ "ecdsa-sha2-nistp521",
22
+ "ssh-rsa",
23
+ "sk-ssh-ed25519@openssh.com",
24
+ "sk-ecdsa-sha2-nistp256@openssh.com",
25
+ ]);
26
+ // More than this many keys is not one person's computers: the oldest goes.
27
+ const MAX_KEYS = 20;
28
+ const MAX_KEY_CHARS = 16_384;
29
+ // The key files a person's computer most likely has, in the order ssh itself tries them.
30
+ const OWN_KEYS = [
31
+ "id_ed25519",
32
+ "id_ecdsa",
33
+ "id_ed25519_sk",
34
+ "id_ecdsa_sk",
35
+ "id_rsa",
36
+ ];
37
+
38
+ /** An OpenSSH public key line as { type, blob }, or null. The key must name its own type inside it. */
39
+ export function parsePublicKey(text) {
40
+ const line = String(text ?? "").trim();
41
+ if (!line || line.length > MAX_KEY_CHARS || /[\r\n]/.test(line)) return null;
42
+ const [type, blob] = line.split(/\s+/);
43
+ if (!KEY_TYPES.has(type) || !/^[A-Za-z0-9+/]+={0,3}$/.test(blob ?? ""))
44
+ return null;
45
+ const bytes = Buffer.from(blob, "base64");
46
+ if (bytes.length < 4) return null;
47
+ const named = bytes.readUInt32BE(0);
48
+ if (bytes.subarray(4, 4 + named).toString("latin1") !== type) return null;
49
+ return { type, blob };
50
+ }
51
+
52
+ /** A key's fingerprint as `ssh-keygen -l` shows it. */
53
+ export const fingerprintOf = (blob) =>
54
+ `SHA256:${createHash("sha256")
55
+ .update(Buffer.from(blob, "base64"))
56
+ .digest("base64")
57
+ .replace(/=+$/, "")}`;
58
+
59
+ // Who allowed a key, kept as its comment: printable and short, as sshd's own line takes it.
60
+ const byLine = (by) =>
61
+ String(by || "your device")
62
+ .replace(/[^A-Za-z0-9 ._()-]/g, "")
63
+ .trim()
64
+ .slice(0, 60) || "your device";
65
+
66
+ /**
67
+ * The box's side. `keysFile`: what sshd reads for the provider's account; `gateFile`: sshd's drop-in that makes it read
68
+ * only that, without which no key is taken (bootScript.ts).
69
+ */
70
+ export function createCloudSsh({ keysFile, gateFile, log = () => {} }) {
71
+ const ready = () => {
72
+ try {
73
+ return fs
74
+ .readFileSync(gateFile, "utf8")
75
+ .includes("AuthorizedKeysCommand");
76
+ } catch {
77
+ return false;
78
+ }
79
+ };
80
+ const read = () => {
81
+ let text = "";
82
+ try {
83
+ text = fs.readFileSync(keysFile, "utf8");
84
+ } catch {}
85
+ return text
86
+ .split("\n")
87
+ .map((line) => {
88
+ const parsed = parsePublicKey(line);
89
+ return parsed
90
+ ? { ...parsed, by: line.trim().split(/\s+/).slice(2).join(" ") }
91
+ : null;
92
+ })
93
+ .filter(Boolean);
94
+ };
95
+ const write = (keys) => {
96
+ const next = `${keysFile}.${process.pid}.tmp`;
97
+ fs.writeFileSync(
98
+ next,
99
+ keys.map((key) => `${key.type} ${key.blob} ${key.by}\n`).join(""),
100
+ { mode: 0o644 }
101
+ );
102
+ fs.renameSync(next, keysFile);
103
+ };
104
+
105
+ /** One of the person's devices lets this key in. `by`: which device, as the person named it. */
106
+ const allow = ({ key, by }) => {
107
+ if (!ready())
108
+ return {
109
+ ok: false,
110
+ error:
111
+ "This cloud computer takes no SSH keys: its SSH gate is not in place. Remove it and add a new one.",
112
+ };
113
+ const parsed = parsePublicKey(key);
114
+ if (!parsed) return { ok: false, error: "That is not an SSH public key." };
115
+ const others = read().filter((kept) => kept.blob !== parsed.blob);
116
+ const keys = [...others, { ...parsed, by: byLine(by) }].slice(-MAX_KEYS);
117
+ write(keys);
118
+ const fingerprint = fingerprintOf(parsed.blob);
119
+ log(`SSH key ${fingerprint} allowed by ${byLine(by)}`);
120
+ return { ok: true, fingerprint };
121
+ };
122
+
123
+ const list = () =>
124
+ read().map((key) => ({ fingerprint: fingerprintOf(key.blob), by: key.by }));
125
+
126
+ return { ready, allow, list };
127
+ }
128
+
129
+ /** The person's own public key: the file named, else the first of ssh's usual ones; null when there is none. */
130
+ export function ownPublicKey(named = null, home = os.homedir()) {
131
+ const files = named
132
+ ? [path.resolve(named.endsWith(".pub") ? named : `${named}.pub`)]
133
+ : OWN_KEYS.map((name) => path.join(home, ".ssh", `${name}.pub`));
134
+ for (const file of files) {
135
+ try {
136
+ const text = fs.readFileSync(file, "utf8").trim();
137
+ if (parsePublicKey(text))
138
+ return { file, privateFile: file.replace(/\.pub$/, ""), text };
139
+ } catch {}
140
+ }
141
+ return null;
142
+ }
143
+
144
+ /**
145
+ * The ssh command for one cloud computer as it is now: its host key pinned under a name of its own in a known_hosts
146
+ * file kept for it, so a resume's new host key replaces the old one and nothing in the person's own known_hosts changes.
147
+ */
148
+ export function sshCommand({
149
+ access,
150
+ computer,
151
+ keyFile,
152
+ knownHostsDir,
153
+ command = [],
154
+ }) {
155
+ const alias = `harness-cloud-${String(computer.id).slice(0, 8)}`;
156
+ fs.mkdirSync(knownHostsDir, { recursive: true, mode: 0o700 });
157
+ const knownHosts = path.join(knownHostsDir, `${alias}.known_hosts`);
158
+ if (access.hostKey)
159
+ fs.writeFileSync(knownHosts, `${alias} ${access.hostKey}\n`, {
160
+ mode: 0o600,
161
+ });
162
+ return [
163
+ "-i",
164
+ keyFile,
165
+ "-o",
166
+ "IdentitiesOnly=yes",
167
+ "-o",
168
+ `HostKeyAlias=${alias}`,
169
+ "-o",
170
+ `UserKnownHostsFile=${knownHosts}`,
171
+ "-o",
172
+ `StrictHostKeyChecking=${access.hostKey ? "yes" : "ask"}`,
173
+ "-p",
174
+ String(access.port),
175
+ `${access.user}@${access.host}`,
176
+ ...(command.length ? ["--", ...command] : []),
177
+ ];
178
+ }
package/lib/context.mjs CHANGED
@@ -120,7 +120,7 @@ export async function rankFiles({
120
120
  const hybrid = (c) => c.dense + 0.25 * (c.lexical / topWords) + 0.2 * c.named;
121
121
  const byHybrid = [...candidates].sort((a, b) => hybrid(b) - hybrid(a));
122
122
  const prior = swarmPrior(history, at);
123
- // No cross-encoder pass: on the owner's own sessions it moved recall by under one point (context-recall v3).
123
+ // No cross-encoder pass: on real sessions it moved recall by under one point.
124
124
  const byDense = [...candidates]
125
125
  .sort((a, b) => b.dense - a.dense)
126
126
  .slice(0, POOL)
@@ -215,8 +215,8 @@ export function createContextEngine({
215
215
  return { root, top: repo.root };
216
216
  };
217
217
  // The background pass keeps each folder's place for a while: asking git blocks the daemon, and the pass asked three
218
- // times for each of 683 sessions every 15 minutes, holding everything else (T3, the buddy, hooks) for up to 11 s
219
- // (October 23, .harness-runs/measure/t3-probe). A brief's pack still asks fresh.
218
+ // times for each of 683 sessions every 15 minutes, holding everything else (T3, the buddy, hooks) for up to 11 s.
219
+ // A brief's pack still asks fresh.
220
220
  const keptPlaces = new Map();
221
221
  const keptPlaceOf = (folder) => {
222
222
  const kept = keptPlaces.get(folder);
@@ -2,8 +2,8 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { MACHINE_RUNNERS, nameOf } from "./members.mjs";
3
3
  import { onchainExecutors, treasurerOf } from "./book.mjs";
4
4
 
5
- // The gate between building a contract and deploying it (docs/swarm-organization.md, "Contracts", Decision 34). Bankr
6
- // builds and deploys as two asks, so its maker is not its only check:
5
+ // The gate between building a contract and deploying it. Bankr builds and deploys as two asks, so its maker is not its
6
+ // only check:
7
7
  //
8
8
  // 1. Build: Bankr returns the source and the compiled code; the treasurer (or the person) files them in the book and
9
9
  // code hashes the runtime code. Every verdict below is bound to that hash, so code filed again after a review is
@@ -223,8 +223,29 @@ function verdictRefusal(row, agent, sha256) {
223
223
  return null;
224
224
  }
225
225
 
226
+ // A verdict is a run's: filed from inside a run the daemon started (its capability, runner.mjs), on the model Harness
227
+ // chose for that run. Neither the agent nor the model is a name the caller writes, so "another reviewer on another
228
+ // model" is a fact about two runs, not two claims.
229
+ function verdictRun(store, agent, run) {
230
+ if (!run || run.agent !== agent)
231
+ return {
232
+ error:
233
+ "a check or a judgment is filed from inside the run that made it, by its Harness tools",
234
+ };
235
+ const model = store.db.get(
236
+ "select json_extract(run_model, '$.model') as model from board_tasks where id = ?",
237
+ [run.id]
238
+ )?.model;
239
+ if (!model)
240
+ return {
241
+ error:
242
+ "Harness did not choose this run's model, so its verdict cannot be told apart from another model's: give the run a model",
243
+ };
244
+ return { id: run.id, model: short(model, 100) };
245
+ }
246
+
226
247
  /** The Check: a coding agent tested exactly this code on a fork with no real funds. */
227
- export function fileCheck(store, agent, { contract, model, sha256, passed }) {
248
+ export function fileCheck(store, agent, { contract, run, sha256, passed }) {
228
249
  const row = contractRow(store, contract);
229
250
  const refusal = verdictRefusal(row, agent, sha256);
230
251
  if (refusal) return { ok: false, error: refusal };
@@ -233,13 +254,14 @@ export function fileCheck(store, agent, { contract, model, sha256, passed }) {
233
254
  ok: false,
234
255
  error: "a coding agent on the person's computers checks a contract",
235
256
  };
236
- if (!short(model, 100))
237
- return { ok: false, error: "a check names the model it ran on" };
257
+ const checker = verdictRun(store, agent, run);
258
+ if (checker.error) return { ok: false, error: checker.error };
259
+ store.meta(`contract-check-run:${row.id}`, checker.id);
238
260
  return {
239
261
  ok: true,
240
262
  contract: update(store, row.id, {
241
263
  check_by: agent,
242
- check_model: short(model, 100),
264
+ check_model: checker.model,
243
265
  check_sha256: row.code_sha256,
244
266
  check_passed: passed === true ? 1 : 0,
245
267
  judge_by: null,
@@ -252,7 +274,7 @@ export function fileCheck(store, agent, { contract, model, sha256, passed }) {
252
274
  }
253
275
 
254
276
  /** The Judge: a reviewer on a model other than the checker's accepted exactly this code, or sent it back. */
255
- export function fileJudge(store, agent, { contract, model, sha256, accepted }) {
277
+ export function fileJudge(store, agent, { contract, run, sha256, accepted }) {
256
278
  const row = contractRow(store, contract);
257
279
  const refusal = verdictRefusal(row, agent, sha256);
258
280
  if (refusal) return { ok: false, error: refusal };
@@ -261,17 +283,17 @@ export function fileJudge(store, agent, { contract, model, sha256, accepted }) {
261
283
  ok: false,
262
284
  error: "it is judged after a check passes on this code",
263
285
  };
264
- const judgeModel = short(model, 100);
265
286
  if (agent === row.check_by)
266
287
  return { ok: false, error: "the checker does not judge its own check" };
267
- if (
268
- !judgeModel ||
269
- judgeModel.toLowerCase() === String(row.check_model).toLowerCase()
270
- )
288
+ const judge = verdictRun(store, agent, run);
289
+ if (judge.error) return { ok: false, error: judge.error };
290
+ const judgeModel = judge.model;
291
+ if (judgeModel.toLowerCase() === String(row.check_model).toLowerCase())
271
292
  return {
272
293
  ok: false,
273
294
  error: `the judge runs on a model other than the checker's (${row.check_model})`,
274
295
  };
296
+ store.meta(`contract-judge-run:${row.id}`, judge.id);
275
297
  return {
276
298
  ok: true,
277
299
  contract: update(store, row.id, {
@@ -1,6 +1,10 @@
1
1
  import net from "node:net";
2
2
  import { paths } from "./paths.mjs";
3
3
 
4
+ // Inside a run Harness started, every call carries that run's capability (runner.mjs): the daemon takes it as the run's
5
+ // agent under the run's limits, whatever agent the call names. The person's own terminal and sessions have none.
6
+ const runToken = process.env.HARNESS_RUN_TOKEN;
7
+
4
8
  export function daemonRequest(message, timeoutMs = 5_000) {
5
9
  return new Promise((resolve, reject) => {
6
10
  let settled = false;
@@ -14,7 +18,11 @@ export function daemonRequest(message, timeoutMs = 5_000) {
14
18
  };
15
19
  socket.setEncoding("utf8");
16
20
  socket.setTimeout(timeoutMs);
17
- socket.on("connect", () => socket.write(JSON.stringify(message) + "\n"));
21
+ socket.on("connect", () =>
22
+ socket.write(
23
+ JSON.stringify(runToken ? { ...message, runToken } : message) + "\n"
24
+ )
25
+ );
18
26
  socket.on("data", (chunk) => {
19
27
  buffer += chunk;
20
28
  const newline = buffer.indexOf("\n");
@@ -0,0 +1,86 @@
1
+ import fs from "node:fs";
2
+ import net from "node:net";
3
+
4
+ // What a control-socket request carries for its handler and no JSON can set: a signal that its caller hung up.
5
+ export const CALLER_GONE = Symbol("the caller hung up");
6
+
7
+ /** Whether a daemon answers on `socketPath` now. */
8
+ export function daemonAnswers(socketPath) {
9
+ return new Promise((resolve) => {
10
+ const probe = net.createConnection(socketPath);
11
+ probe.once("connect", () => {
12
+ probe.destroy();
13
+ resolve(true);
14
+ });
15
+ probe.once("error", () => resolve(false));
16
+ });
17
+ }
18
+
19
+ /**
20
+ * The daemon's local socket (owner-only on macOS and Linux): one JSON object per line in, one answer per line out, for
21
+ * the CLI, the buddy, agents' MCP servers and session hooks on this computer.
22
+ *
23
+ * `answer(request)` returns the answer or a promise of it; a promise that rejects is answered as a refusal with its
24
+ * message. Anything but one JSON object is refused here, so nothing a local process writes can reach a property read
25
+ * on it. A caller that hangs up before its answer (its own timeout, a killed hook) loses that answer; it never takes
26
+ * the daemon, and the runs it holds, down with it. `request[CALLER_GONE]` aborts when it hangs up, so work that can
27
+ * be stopped (a vault request's website call) is.
28
+ *
29
+ * `check(request, socket)` says who is asking before anything is answered: a refusal's words, or null. Who is asking
30
+ * comes from the run that asks or the program that called, never from the name a call writes (runAuthority.mjs).
31
+ */
32
+ export async function listenControl({
33
+ socketPath,
34
+ answer,
35
+ check = async () => null,
36
+ }) {
37
+ const server = net.createServer((socket) => {
38
+ socket.setEncoding("utf8");
39
+ socket.on("error", () => {});
40
+ let buffer = "";
41
+ let taken = false;
42
+ socket.on("data", async (chunk) => {
43
+ buffer += chunk;
44
+ const newline = buffer.indexOf("\n");
45
+ if (newline < 0 || taken) return;
46
+ taken = true;
47
+ const reply = (value) => socket.end(JSON.stringify(value) + "\n");
48
+ let request;
49
+ try {
50
+ request = JSON.parse(buffer.slice(0, newline));
51
+ } catch {
52
+ request = null;
53
+ }
54
+ if (!request || typeof request !== "object" || Array.isArray(request)) {
55
+ reply({ ok: false, error: "invalid request" });
56
+ return;
57
+ }
58
+ const gone = new AbortController();
59
+ socket.on("close", () => gone.abort());
60
+ request[CALLER_GONE] = gone.signal;
61
+ const refused = await check(request, socket).catch(
62
+ () =>
63
+ "Harness could not tell which program asked, so it did not act. Try again."
64
+ );
65
+ if (refused) {
66
+ reply({ ok: false, code: "not_the_person", error: refused });
67
+ return;
68
+ }
69
+ Promise.resolve()
70
+ .then(() => answer(request))
71
+ .then(reply, (error) => reply({ ok: false, error: error.message }));
72
+ });
73
+ });
74
+ await new Promise((resolve, reject) => {
75
+ server.once("error", reject);
76
+ server.listen(socketPath, () => {
77
+ server.off("error", reject);
78
+ resolve();
79
+ });
80
+ });
81
+ if (process.platform !== "win32")
82
+ try {
83
+ fs.chmodSync(socketPath, 0o600);
84
+ } catch {}
85
+ return server;
86
+ }