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
package/lib/runner.mjs CHANGED
@@ -1,14 +1,37 @@
1
1
  import fs from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { spawn } from "node:child_process";
6
+ import { randomBytes } from "node:crypto";
7
+ import { agentBinary } from "./agentBinaries.mjs";
5
8
  import { agentEnvironment } from "./agentnode.mjs";
6
9
  import { runtimeOf } from "./agentRuntimeConfig.mjs";
7
10
  import { runProtocolTask } from "./agentRuntimes.mjs";
8
11
  import { scrubValues } from "./vault.mjs";
12
+ import { paths } from "./paths.mjs";
9
13
 
10
14
  const running = new Set();
11
15
  const children = new Map();
16
+ // Each run this daemon starts carries its own capability in its environment (HARNESS_RUN_TOKEN). Its Harness MCP server
17
+ // and the CLI send it with every call on the daemon's socket, which takes such a call as that run's agent under that
18
+ // run's limits, whatever agent it names (runAuthority.mjs checkCaller). It ends with the run.
19
+ const capabilities = new Map();
20
+ const issueCapability = (task) => {
21
+ const token = randomBytes(32).toString("base64url");
22
+ capabilities.set(token, {
23
+ id: task.runId,
24
+ agent: task.agent,
25
+ restricted: task.restricted === true,
26
+ review: task.readOnly === true,
27
+ });
28
+ return token;
29
+ };
30
+
31
+ /** The run a capability belongs to while that run goes on: its id, agent, and whether it is restricted or a review. */
32
+ export function runCapability(token) {
33
+ return capabilities.get(String(token)) ?? null;
34
+ }
12
35
 
13
36
  /** Stops a run in progress (a goal's Stop); its close reports it failed. */
14
37
  export function stopAgentTask(runId) {
@@ -72,21 +95,95 @@ export function resolveWorkingDirectory(requested) {
72
95
  return requested;
73
96
  }
74
97
 
98
+ // Where the person keeps what a run held in must never read: other agents' and tools' credentials and keys, under the
99
+ // home folder. Harness's own home (its keys, the board, the vault) is added where it is (paths.home).
100
+ const SECRET_PLACES = [
101
+ ".harness",
102
+ ".claude",
103
+ ".claude.json",
104
+ ".codex",
105
+ ".pi",
106
+ ".config/opencode",
107
+ ".local/share/opencode",
108
+ ".t3",
109
+ ".ssh",
110
+ ".gnupg",
111
+ ".aws",
112
+ ".azure",
113
+ ".kube",
114
+ ".docker",
115
+ ".config/gh",
116
+ ".config/hub",
117
+ ".config/gcloud",
118
+ ".config/solana",
119
+ ".npmrc",
120
+ ".yarnrc.yml",
121
+ ".pypirc",
122
+ ".netrc",
123
+ ".git-credentials",
124
+ ".cargo/credentials.toml",
125
+ ".password-store",
126
+ "Library/Keychains",
127
+ ];
128
+ /** Every place a restricted or review run may not read, as absolute paths. */
129
+ export const secretPlaces = (home = os.homedir()) => [
130
+ ...new Set([
131
+ ...SECRET_PLACES.map((place) => path.join(home, place)),
132
+ paths.home,
133
+ ]),
134
+ ];
135
+ // Claude Code's own file tools are held by deny rules ("//" starts an absolute path). Harness's home holds the
136
+ // worktrees runs work in, so only its own files are named there, never a pattern that would cover a worktree.
137
+ const HARNESS_FILES = [
138
+ "*.json",
139
+ "*.db",
140
+ "*.db-*",
141
+ "*.lock",
142
+ "*.log",
143
+ "*.sock",
144
+ "vault*",
145
+ "*key*",
146
+ "runs/**",
147
+ "files/**",
148
+ "runtime/**",
149
+ "models/**",
150
+ "local/**",
151
+ "checks/**",
152
+ "native-host/**",
153
+ "editor/**",
154
+ ];
155
+ const readDenials = (home) =>
156
+ secretPlaces(home).flatMap((place) =>
157
+ place === paths.home
158
+ ? HARNESS_FILES.map((file) => `Read(/${path.join(place, file)})`)
159
+ : [`Read(/${place})`, `Read(/${place}/**)`]
160
+ );
161
+ // The sandbox holds shell commands to the same places. The run's own folder stays readable even inside Harness's home,
162
+ // where its worktree is, and so do the shell snapshots each agent's shell tool sources before every command.
163
+ const sandboxReads = (cwd, home) => ({
164
+ denyRead: secretPlaces(home),
165
+ allowRead: [
166
+ ...(cwd ? [cwd] : []),
167
+ path.join(home, ".claude", "shell-snapshots"),
168
+ ],
169
+ });
170
+
75
171
  // A run another agent started without the person's tap (docs/member-runs.md): anything that would ask is refused, file
76
- // edits only in its worktree, shell commands only inside the operating system's sandbox with no network, and no hooks or
77
- // settings from the repository. A review gets no edits at all.
78
- export const RESTRICTED_CLAUDE_SETTINGS = {
172
+ // edits only in its worktree, shell commands only inside the operating system's sandbox with no network, nothing read
173
+ // where the person keeps credentials, and no hooks or settings from the repository. A review gets no edits at all.
174
+ export const restrictedClaudeSettings = (cwd, home = os.homedir()) => ({
79
175
  disableAllHooks: true,
80
- permissions: { deny: ["WebFetch", "WebSearch"] },
176
+ permissions: { deny: ["WebFetch", "WebSearch", ...readDenials(home)] },
81
177
  sandbox: {
82
178
  enabled: true,
83
179
  autoAllowBashIfSandboxed: true,
84
180
  allowUnsandboxedCommands: false,
85
181
  failIfUnavailable: true,
86
182
  excludedCommands: [],
183
+ filesystem: sandboxReads(cwd, home),
87
184
  network: { allowedDomains: [], strictAllowlist: true },
88
185
  },
89
- };
186
+ });
90
187
  // Only the Harness board MCP, as Claude Code: none of the person's other MCP servers or claude.ai connectors load.
91
188
  export const restrictedMcpConfig = () => ({
92
189
  mcpServers: {
@@ -109,7 +206,10 @@ const restrictedClaude = (task) => [
109
206
  "--setting-sources",
110
207
  "user",
111
208
  "--settings",
112
- JSON.stringify(RESTRICTED_CLAUDE_SETTINGS),
209
+ JSON.stringify({
210
+ ...restrictedClaudeSettings(task.cwd),
211
+ ...modelWindow(task),
212
+ }),
113
213
  "--strict-mcp-config",
114
214
  "--mcp-config",
115
215
  JSON.stringify(restrictedMcpConfig()),
@@ -138,32 +238,83 @@ const modelFlags = ({ agent, model, effort }) => [
138
238
  ...(model ? (MODEL_FLAGS[agent]?.model(model) ?? []) : []),
139
239
  ...(effort ? (MODEL_FLAGS[agent]?.effort(effort) ?? []) : []),
140
240
  ];
241
+ // Claude Code knows no window for a model of Harness's AI (cloudAi.mjs tells it its default's); a run on one says
242
+ // that model's window and longest answer in its own settings, which outrank the user settings for this run.
243
+ const modelWindow = ({ limits }) =>
244
+ limits
245
+ ? {
246
+ env: {
247
+ CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(limits.contextTokens),
248
+ CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(limits.maxOutputTokens),
249
+ },
250
+ }
251
+ : {};
141
252
 
142
253
  // A review or research turn reads and reports. Plan mode kept Claude Code from editing but also refused the Harness
143
254
  // tools it reads the thread and posts with (October 20, live run: "plan mode blocks the room tools", the findings left
144
255
  // in ~/.claude/plans). Instead: anything not allowed is refused, edits and writes are refused, Harness's tools and
145
256
  // reading are allowed, and shell commands run only inside the operating system's sandbox, which the deny rule keeps
146
257
  // from writing in the working folder (probed live October 20: Harness's tools answer, node and git run, a write in the
147
- // folder is refused; denying edits everywhere also broke Claude Code's own scratch files under /tmp).
148
- export const READ_ONLY_CLAUDE_SETTINGS = {
149
- permissions: { deny: ["Edit(./**)"] },
258
+ // folder is refused; denying edits everywhere also broke Claude Code's own scratch files under /tmp). It reads nothing
259
+ // where the person keeps credentials, loads no settings or hooks from the repository it reviews, and has no web: what
260
+ // it reviews is in the folder and the thread, and a fetch is a way out for what it read.
261
+ export const readOnlyClaudeSettings = (cwd, home = os.homedir()) => ({
262
+ permissions: {
263
+ deny: ["Edit(./**)", "WebFetch", "WebSearch", ...readDenials(home)],
264
+ },
150
265
  sandbox: {
151
266
  enabled: true,
152
267
  autoAllowBashIfSandboxed: true,
153
268
  allowUnsandboxedCommands: false,
269
+ filesystem: sandboxReads(cwd, home),
270
+ network: { allowedDomains: [], strictAllowlist: true },
154
271
  },
155
- };
156
- const readOnlyClaude = () => [
272
+ });
273
+ const readOnlyClaude = (task) => [
157
274
  "--permission-mode",
158
275
  "dontAsk",
159
276
  "--allowedTools",
160
- "Read Grep Glob WebSearch WebFetch mcp__harness",
277
+ "Read Grep Glob mcp__harness",
161
278
  "--disallowedTools",
162
- "Edit Write NotebookEdit",
279
+ "Edit Write NotebookEdit WebFetch WebSearch",
280
+ "--setting-sources",
281
+ "user",
163
282
  "--settings",
164
- JSON.stringify(READ_ONLY_CLAUDE_SETTINGS),
283
+ JSON.stringify({
284
+ ...readOnlyClaudeSettings(task.cwd),
285
+ ...modelWindow(task),
286
+ }),
165
287
  ];
166
288
 
289
+ // Codex's review: its read-only permission profile, with the same places denied to every command it runs (the run's
290
+ // own folder stays readable when it lies inside one) and no web search. Probed with `codex sandbox` 0.164: a denied
291
+ // file is "Operation not permitted", the folder reads, writes and the daemon's socket are refused.
292
+ const codexReview = (task, home = os.homedir()) => {
293
+ const places = Object.fromEntries(
294
+ secretPlaces(home).map((place) => [place, "deny"])
295
+ );
296
+ places[path.join(home, ".codex", "shell_snapshots")] = "read";
297
+ if (task.cwd) places[task.cwd] = "read";
298
+ const table = Object.entries(places)
299
+ .map(
300
+ ([place, access]) => `${JSON.stringify(place)}=${JSON.stringify(access)}`
301
+ )
302
+ .join(",");
303
+ return [
304
+ "-c",
305
+ 'default_permissions="harness-review"',
306
+ "-c",
307
+ 'permissions.harness-review.extends=":read-only"',
308
+ "-c",
309
+ `permissions.harness-review.filesystem={${table}}`,
310
+ "-c",
311
+ 'web_search="disabled"',
312
+ ];
313
+ };
314
+
315
+ /** The coding agents whose runs Harness can hold to read-only: only they review or audit. */
316
+ export const READ_ONLY_AGENTS = new Set(["claude-code", "codex"]);
317
+
167
318
  export function agentInvocation(task) {
168
319
  if (task.agent === "claude-code") {
169
320
  return {
@@ -177,8 +328,18 @@ export function agentInvocation(task) {
177
328
  ...(task.restricted
178
329
  ? restrictedClaude(task)
179
330
  : task.readOnly
180
- ? readOnlyClaude()
181
- : ["--dangerously-skip-permissions"]),
331
+ ? readOnlyClaude(task)
332
+ : [
333
+ "--dangerously-skip-permissions",
334
+ ...(task.limits
335
+ ? ["--settings", JSON.stringify(modelWindow(task))]
336
+ : []),
337
+ ]),
338
+ // Another person's ask: the person's own settings only, never the project's or its local ones (their hooks).
339
+ // Restricted and review runs already keep to the person's own settings.
340
+ ...(task.ownSettingsOnly && !task.restricted && !task.readOnly
341
+ ? ["--setting-sources", "user"]
342
+ : []),
182
343
  "--name",
183
344
  `Harness: ${task.title}`,
184
345
  ...modelFlags(task),
@@ -199,13 +360,12 @@ export function agentInvocation(task) {
199
360
  ...(task.resumeSession ? ["resume", task.resumeSession] : []),
200
361
  "--json",
201
362
  ...modelFlags(task),
202
- // A review still talks to the thread: with approvals off, Codex refused every Harness tool as unapproved, so
203
- // it could not read the room or post what it found (October 14, the chop keeper review). Harness's own tools
204
- // are approved for it; the files stay read-only.
363
+ // A review still talks to the thread: with approvals off, Codex refused every Harness tool as unapproved, so it
364
+ // could not read the room or post what it found. Harness's own tools are approved for it; the files stay
365
+ // read-only.
205
366
  ...(task.readOnly
206
367
  ? [
207
- "-c",
208
- 'sandbox_mode="read-only"',
368
+ ...codexReview(task),
209
369
  "-c",
210
370
  'approval_policy="never"',
211
371
  "-c",
@@ -218,15 +378,21 @@ export function agentInvocation(task) {
218
378
  stdin: task.brief,
219
379
  };
220
380
  }
381
+ // Neither has a read-only mode Harness can hold it to (their runs below are unrestricted), so neither reviews.
382
+ if (task.readOnly && !READ_ONLY_AGENTS.has(task.agent))
383
+ throw new Error(
384
+ `${task.agent} has no read-only mode, so it does not review; Claude Code or Codex can`
385
+ );
221
386
  // Pi has no permission prompts. --approve trusts project-local configuration for
222
- // this non-interactive run; its complete built-in tool set remains enabled.
387
+ // this non-interactive run; its complete built-in tool set remains enabled. Another
388
+ // person's ask ignores project-local files instead (--no-approve).
223
389
  if (task.agent === "pi")
224
390
  return {
225
391
  command: "pi",
226
392
  args: [
227
393
  "--mode",
228
394
  "json",
229
- "--approve",
395
+ task.ownSettingsOnly ? "--no-approve" : "--approve",
230
396
  ...modelFlags(task),
231
397
  "-p",
232
398
  task.brief,
@@ -247,6 +413,10 @@ export function agentInvocation(task) {
247
413
  "--",
248
414
  task.brief,
249
415
  ],
416
+ // Another person's ask: OpenCode reads no opencode.json or .opencode folder from the project.
417
+ ...(task.ownSettingsOnly
418
+ ? { env: { OPENCODE_DISABLE_PROJECT_CONFIG: "1" } }
419
+ : {}),
250
420
  };
251
421
  }
252
422
  throw new Error(`Unsupported agent: ${task.agent}`);
@@ -475,18 +645,21 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
475
645
  let cwd;
476
646
  let invocation;
477
647
  let environment;
648
+ let capability = null;
478
649
  try {
479
650
  cwd = resolveWorkingDirectory(task.cwd);
480
651
  if (runtimeOf(task.agent)) {
481
652
  const controller = new AbortController();
482
653
  running.add(slot);
483
654
  children.set(task.runId, { kill: () => controller.abort() });
655
+ const capability = issueCapability(task);
484
656
  let released = false;
485
657
  const release = () => {
486
658
  if (released) return;
487
659
  released = true;
488
660
  running.delete(slot);
489
661
  children.delete(task.runId);
662
+ capabilities.delete(capability);
490
663
  };
491
664
  let settled = false;
492
665
  const report = (kind, text, extra) => {
@@ -498,7 +671,12 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
498
671
  emit(kind, text, extra);
499
672
  };
500
673
  void runProtocolTask(
501
- { ...task, cwd },
674
+ {
675
+ ...task,
676
+ cwd,
677
+ capability,
678
+ env: { ...(task.env ?? {}), HARNESS_RUN_TOKEN: capability },
679
+ },
502
680
  { ...hooks, emit: report, observe, signal: controller.signal }
503
681
  )
504
682
  .catch((error) => report("failed", error.message, { failure: "exit" }))
@@ -506,17 +684,26 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
506
684
  return;
507
685
  }
508
686
  invocation = agentInvocation(task);
687
+ capability = issueCapability(task);
509
688
  // A Node agent runs on a Node it accepts, whichever Node Harness itself runs on.
510
689
  // The person's environment grants for this run (vault.mjs), over the daemon's own environment.
511
690
  // HARNESS_RUN_ID tells the agent's own Harness tools which run they serve (mcp-stdio.mjs), where its MCP servers
512
- // inherit the agent's environment.
691
+ // inherit the agent's environment; HARNESS_RUN_TOKEN is the run's capability (above).
513
692
  environment = agentEnvironment(invocation.command, {
514
693
  ...process.env,
515
694
  ...(task.env ?? {}),
695
+ ...(invocation.env ?? {}),
516
696
  HARNESS_RUN_ID: task.runId,
697
+ HARNESS_RUN_TOKEN: capability,
517
698
  });
518
699
  if (environment.error) throw new Error(environment.error);
700
+ // The program confirmed for this agent, not the first one on PATH (agentBinaries.mjs).
701
+ const program = agentBinary(task.agent, invocation.command);
702
+ if (!program)
703
+ throw new Error(`${task.agent} is not installed on this computer.`);
704
+ invocation = { ...invocation, command: program };
519
705
  } catch (error) {
706
+ if (capability) capabilities.delete(capability);
520
707
  emit("failed", error.message, { failure: "start" });
521
708
  return;
522
709
  }
@@ -532,6 +719,7 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
532
719
  child.stdin.end(invocation.stdin);
533
720
  } catch (error) {
534
721
  running.delete(slot);
722
+ capabilities.delete(capability);
535
723
  emit("failed", `Could not start ${task.agent}: ${error.message}`, {
536
724
  failure: "start",
537
725
  });
@@ -621,6 +809,7 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
621
809
  child.on("close", (code) => {
622
810
  running.delete(slot);
623
811
  children.delete(task.runId);
812
+ capabilities.delete(capability);
624
813
  if (code === 0 && modelError)
625
814
  emit(
626
815
  "failed",
@@ -648,6 +837,7 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
648
837
  child.on("error", (error) => {
649
838
  running.delete(slot);
650
839
  children.delete(task.runId);
840
+ capabilities.delete(capability);
651
841
  emit("failed", `Could not start ${task.agent}: ${error.message}`, {
652
842
  failure: "start",
653
843
  });
@@ -1,8 +1,20 @@
1
1
  import fs from "node:fs";
2
+ import os from "node:os";
2
3
  import path from "node:path";
4
+ import { spawnSync } from "node:child_process";
3
5
  import { createRequire } from "node:module";
4
6
  import { ensureDir, readJson, writeJsonAtomic } from "./files.mjs";
5
7
  import { paths } from "./paths.mjs";
8
+ import {
9
+ RELEASE_ENTRIES,
10
+ RELEASE_FILE,
11
+ trustedKeys,
12
+ verifyRelease,
13
+ } from "./release.mjs";
14
+
15
+ // The release chain (release.mjs): npm carries releases, the installed runtime decides which it runs. The first
16
+ // install trusts what npx fetched, since nothing is installed yet to check it with. From then on a release is
17
+ // installed, or switched to, only when it is signed with a key the installed runtime already carries.
6
18
 
7
19
  function packageDirectory(packageJson) {
8
20
  return path.dirname(packageJson);
@@ -83,20 +95,53 @@ function copyDependencyClosure(sourceRoot, releaseRoot, roots) {
83
95
  }
84
96
  }
85
97
 
86
- export function installRuntime({ sourceRoot, version }) {
98
+ // A build the person made and chose to install (--local-build) is marked, so setup can switch back to it.
99
+ const LOCAL_BUILD = ".local-build";
100
+
101
+ // Why a release may not be installed or switched to, or null when it may.
102
+ function refusal({ root, keys, allowUnsigned }) {
103
+ if (!keys.length || allowUnsigned) return null;
104
+ if (fs.existsSync(path.join(root, LOCAL_BUILD))) return null;
105
+ const checked = verifyRelease({ root, keys });
106
+ return checked.ok ? null : checked.reason;
107
+ }
108
+
109
+ const refuse = (version, reason) =>
110
+ new Error(
111
+ `this computer's Harness installs only releases signed with Harness's release key, and tryharness ${version} is not: ${reason}. ` +
112
+ "Nothing was changed. If it is a build you made yourself, run it again with --local-build."
113
+ );
114
+
115
+ /** Throws, before setup changes anything, when installRuntime would refuse this release. */
116
+ export function checkRuntime({ sourceRoot, version, allowUnsigned = false }) {
117
+ const installed = currentRuntime();
118
+ const keys = installed ? trustedKeys(installed) : [];
119
+ const release = path.join(paths.runtime, "releases", version);
120
+ const root = fs.existsSync(path.join(release, ".ready"))
121
+ ? release
122
+ : sourceRoot;
123
+ const reason = refusal({ root, keys, allowUnsigned });
124
+ if (reason) throw refuse(version, reason);
125
+ }
126
+
127
+ /**
128
+ * Installs the release at `sourceRoot` as this computer's runtime and switches to it. Refuses (and changes nothing)
129
+ * when a runtime is installed and the release is not signed with a key that runtime trusts; `allowUnsigned` is the
130
+ * person's own --local-build.
131
+ */
132
+ export function installRuntime({ sourceRoot, version, allowUnsigned = false }) {
133
+ const installed = currentRuntime();
134
+ const keys = installed ? trustedKeys(installed) : [];
87
135
  const release = path.join(paths.runtime, "releases", version);
88
136
  const marker = path.join(release, ".ready");
89
- if (!fs.existsSync(marker)) {
137
+ if (fs.existsSync(marker)) {
138
+ const reason = refusal({ root: release, keys, allowUnsigned });
139
+ if (reason) throw refuse(version, reason);
140
+ } else {
90
141
  const staging = `${release}.staging-${process.pid}`;
91
142
  fs.rmSync(staging, { recursive: true, force: true });
92
143
  ensureDir(staging);
93
- for (const entry of [
94
- "cli.mjs",
95
- "package.json",
96
- "README.md",
97
- "lib",
98
- "assets",
99
- ]) {
144
+ for (const entry of [...RELEASE_ENTRIES, RELEASE_FILE]) {
100
145
  const source = path.join(sourceRoot, entry);
101
146
  if (!fs.existsSync(source)) continue;
102
147
  fs.cpSync(source, path.join(staging, entry), {
@@ -104,6 +149,13 @@ export function installRuntime({ sourceRoot, version }) {
104
149
  force: true,
105
150
  });
106
151
  }
152
+ // Checked as copied, so what is checked is what runs.
153
+ const reason = refusal({ root: staging, keys, allowUnsigned });
154
+ if (reason) {
155
+ fs.rmSync(staging, { recursive: true, force: true });
156
+ throw refuse(version, reason);
157
+ }
158
+ if (allowUnsigned) fs.writeFileSync(path.join(staging, LOCAL_BUILD), "");
107
159
  // Everything the package depends on, so a dependency added there cannot be left out here.
108
160
  copyDependencyClosure(
109
161
  sourceRoot,
@@ -123,6 +175,7 @@ export function installRuntime({ sourceRoot, version }) {
123
175
  version,
124
176
  path: release,
125
177
  });
178
+ writeLauncher(release);
126
179
  return release;
127
180
  }
128
181
 
@@ -132,3 +185,84 @@ export function currentRuntime() {
132
185
  ? current.path
133
186
  : null;
134
187
  }
188
+
189
+ // ── The installed command ─────────────────────────────────────────────────────
190
+
191
+ const WINDOWS = process.platform === "win32";
192
+ const launcherFile = () =>
193
+ path.join(paths.home, "bin", WINDOWS ? "tryharness.cmd" : "tryharness");
194
+
195
+ // The person's command for this computer's Harness: it runs the installed release, never whatever npm has newest.
196
+ function writeLauncher(release, nodePath = process.execPath) {
197
+ const entry = path.join(release, "cli.mjs");
198
+ const script = WINDOWS
199
+ ? `@"${nodePath}" "${entry}" %*\r\n`
200
+ : `#!/bin/sh\n# Harness on this computer: the release it checked and installed (runtime-install.mjs).\nexec "${nodePath}" "${entry}" "$@"\n`;
201
+ ensureDir(path.dirname(launcherFile()));
202
+ fs.writeFileSync(launcherFile(), script, { mode: 0o755 });
203
+ }
204
+
205
+ /**
206
+ * How the person runs `tryharness <words>` here: the installed command once Harness is installed, so a hint never
207
+ * sends them to npm for code; `npx tryharness` before that.
208
+ */
209
+ export function relayCommand(words = "") {
210
+ const tail = words ? ` ${words}` : "";
211
+ if (!fs.existsSync(launcherFile())) return `npx tryharness${tail}`;
212
+ const file = launcherFile();
213
+ const homeDir = os.homedir();
214
+ const shown =
215
+ !WINDOWS && file.startsWith(homeDir + path.sep)
216
+ ? `~${file.slice(homeDir.length)}`
217
+ : file;
218
+ return `${shown.includes(" ") ? JSON.stringify(shown) : shown}${tail}`;
219
+ }
220
+
221
+ /**
222
+ * `tryharness upgrade`: fetches a release from npm without running any of it (no install scripts), and keeps it only
223
+ * when it is signed with a key the installed runtime trusts. Returns where it is unpacked, for setup to run from
224
+ * there, and `trusted: false` when no installed runtime carries a key yet (that one is trusted as npx would be).
225
+ */
226
+ export function fetchRelease({
227
+ spec = "latest",
228
+ npm = "npm",
229
+ env = process.env,
230
+ }) {
231
+ const installed = currentRuntime();
232
+ const keys = installed ? trustedKeys(installed) : [];
233
+ const dir = path.join(paths.runtime, `upgrade-${process.pid}`);
234
+ fs.rmSync(dir, { recursive: true, force: true });
235
+ ensureDir(dir);
236
+ const fetched = spawnSync(
237
+ npm,
238
+ [
239
+ "install",
240
+ `tryharness@${spec}`,
241
+ "--prefix",
242
+ dir,
243
+ "--ignore-scripts",
244
+ "--omit=dev",
245
+ "--no-audit",
246
+ "--no-fund",
247
+ "--no-package-lock",
248
+ ],
249
+ { encoding: "utf8", env, shell: WINDOWS }
250
+ );
251
+ const root = path.join(dir, "node_modules", "tryharness");
252
+ if (fetched.status !== 0 || !fs.existsSync(root)) {
253
+ fs.rmSync(dir, { recursive: true, force: true });
254
+ throw new Error(
255
+ `npm could not fetch tryharness@${spec}: ${(fetched.stderr || fetched.error?.message || "").trim().split("\n").pop()}`
256
+ );
257
+ }
258
+ const version = readJson(path.join(root, "package.json"), {}).version;
259
+ if (keys.length) {
260
+ const checked = verifyRelease({ root, keys });
261
+ if (!checked.ok) {
262
+ fs.rmSync(dir, { recursive: true, force: true });
263
+ throw refuse(version, checked.reason);
264
+ }
265
+ return { dir, root, version, trusted: true, key: checked.key };
266
+ }
267
+ return { dir, root, version, trusted: false };
268
+ }
package/lib/schedules.mjs CHANGED
@@ -14,14 +14,14 @@ import { randomUUID } from "node:crypto";
14
14
  const POLL_MS = 30_000;
15
15
  // Within two polls of its time a run is on time; later, its post says it ran late and when it was due.
16
16
  const LATE_AFTER_MS = 2 * POLL_MS;
17
- // The shortest repeat, the same as automations on Harness's server (src/server/schedules/cadence.ts).
17
+ // The shortest repeat, the same as automations on Harness's server (kept in step with it).
18
18
  export const MIN_EVERY_MINUTES = 5;
19
19
  const WHAT_CHARS = 2_000;
20
20
  // A repeating check-in the lead set ends after this many runs; the person can remove it sooner or set their own.
21
21
  export const LEAD_MAX_RUNS = 24;
22
22
  const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
23
23
 
24
- /** The times the lead picks from (src/server/swarm/coordinator.ts COME_BACK), each as the check-in it sets. */
24
+ /** The times the lead picks from (kept in step with Harness's coordinator), each as the check-in it sets. */
25
25
  export const LEAD_TIMES = {
26
26
  in_15_minutes: { kind: "in", minutes: 15 },
27
27
  in_1_hour: { kind: "in", minutes: 60 },
package/lib/screens.mjs CHANGED
@@ -7,7 +7,7 @@ import { decodeImage } from "./ocr.mjs";
7
7
 
8
8
  const CELL = 16;
9
9
  // A cell counts as changed when its pixels differ by more than this on average (0 to 255): re-rendering the same page
10
- // moves anti-aliasing by a little; the ui-checks eval set it against identical renders.
10
+ // moves anti-aliasing by a little; it was set against identical renders.
11
11
  const CELL_DIFF = 6;
12
12
  const MIN_OVERLAP = 0.3;
13
13
 
package/lib/sealed.mjs CHANGED
@@ -2,8 +2,8 @@ import fs from "node:fs";
2
2
  import { timingSafeEqual, webcrypto } from "node:crypto";
3
3
 
4
4
  // Harness sealed channel, version 1 (HSC1): the phone talks to this daemon through Harness, and
5
- // Harness carries only ciphertext. The browser twin is src/shared/crypto/sealedChannel.ts; both
6
- // must produce the same bytes, and smoke `phone-channel` drives one against the other.
5
+ // Harness carries only ciphertext. The Harness app has a browser twin; both must produce the same
6
+ // bytes, and Harness's own release checks drive one against the other.
7
7
  //
8
8
  // - The daemon has a static ECDH P-256 identity. Its public key reaches the phone only inside the
9
9
  // pairing QR code, never through Harness, so Harness cannot stand in for the daemon.
@@ -191,6 +191,15 @@ export async function relayKey(privateKey, peerPublicKey) {
191
191
  ["encrypt", "decrypt"]
192
192
  );
193
193
  }
194
+ // Relay version 2 (security audit K9, October 25). The key two computers share works both ways, so the associated data
195
+ // of every message, file and ending also names the computer that sealed it and the one it is for, by their public keys:
196
+ // one Harness carried back to its sender, or delivered as if from the other direction, does not open. The sealed words
197
+ // say which of the sender's members wrote them; the label Harness carries beside them is not read. The envelope is
198
+ // unchanged (Harness's server carries it as before); the version is the binding that opens it. A computer from before
199
+ // version 2 seals without the direction: what it sends opens only the old way and is refused here, saying why, and it
200
+ // cannot open what this computer sends; both people update Harness.
201
+ export const relayBound = (bound, fromKey, toKey) =>
202
+ `${bound}|v2|${fromKey}>${toKey}`;
194
203
  export async function sealBound(key, bound, value) {
195
204
  const iv = webcrypto.getRandomValues(new Uint8Array(12));
196
205
  const ct = await subtle.encrypt(