tryharness 0.7.82 → 0.7.86

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 (216) hide show
  1. package/README.md +21 -19
  2. package/assets/dsh-plugin.mjs +75 -4
  3. package/assets/herdr-mod/harness/main.js +367 -0
  4. package/assets/herdr-mod/harness/mod.json +6 -0
  5. package/assets/opencode-plugin.js +87 -22
  6. package/assets/pi-extension.ts +81 -2
  7. package/cli.mjs +544 -208
  8. package/lib/adapters.mjs +62 -27
  9. package/lib/agentBinaries.mjs +6 -8
  10. package/lib/agentClaims.mjs +168 -0
  11. package/lib/agentReadTools.json +415 -0
  12. package/lib/agentSignIn.mjs +17 -18
  13. package/lib/agentWiring.mjs +114 -0
  14. package/lib/archetypes.js +10 -11
  15. package/lib/attention.mjs +100 -0
  16. package/lib/audit.mjs +1 -1
  17. package/lib/backupSetup.mjs +6 -28
  18. package/lib/bankrApprovals.mjs +86 -0
  19. package/lib/boardAccess.mjs +40 -66
  20. package/lib/boardBackup.mjs +86 -85
  21. package/lib/boardCommands.mjs +28 -0
  22. package/lib/boardFileCommands.mjs +29 -36
  23. package/lib/boardFiles.mjs +83 -15
  24. package/lib/boardMirror.mjs +78 -11
  25. package/lib/boardProtocol.json +193 -123
  26. package/lib/boardThreads.mjs +19 -37
  27. package/lib/boardTools.mjs +22 -15
  28. package/lib/boardWatches.mjs +43 -15
  29. package/lib/bridge.mjs +7 -3
  30. package/lib/browserAgentTools.mjs +59 -0
  31. package/lib/browserWake.mjs +0 -6
  32. package/lib/cards.mjs +57 -2
  33. package/lib/circling.mjs +189 -0
  34. package/lib/cleanup.mjs +234 -0
  35. package/lib/cloudBoot.mjs +21 -4
  36. package/lib/cloudSave.mjs +46 -5
  37. package/lib/compaction.mjs +8 -1
  38. package/lib/completion.mjs +358 -0
  39. package/lib/computerDevices.mjs +853 -0
  40. package/lib/connectionStatus.mjs +34 -0
  41. package/lib/connectors.mjs +139 -1
  42. package/lib/coordinator.mjs +108 -14
  43. package/lib/coreModels.mjs +36 -12
  44. package/lib/daemon.mjs +2435 -333
  45. package/lib/daemonLock.mjs +103 -0
  46. package/lib/deviceDoor.mjs +308 -0
  47. package/lib/deviceIdentity.mjs +114 -0
  48. package/lib/deviceList.mjs +172 -0
  49. package/lib/deviceSeal.mjs +74 -0
  50. package/lib/dispatcher.mjs +497 -26
  51. package/lib/dispatches.mjs +3 -3
  52. package/lib/environment.mjs +2 -1
  53. package/lib/environments.mjs +67 -41
  54. package/lib/events.mjs +318 -0
  55. package/lib/facts.mjs +170 -0
  56. package/lib/fileSource.mjs +540 -0
  57. package/lib/files.mjs +47 -2
  58. package/lib/gitHost.mjs +39 -1
  59. package/lib/goalCommands.mjs +12 -80
  60. package/lib/handover.mjs +21 -16
  61. package/lib/harnessOffers.mjs +140 -15
  62. package/lib/herdr.mjs +100 -15
  63. package/lib/herdrAppCall.mjs +19 -0
  64. package/lib/herdrCore.mjs +59 -0
  65. package/lib/herdrRuns.mjs +1126 -0
  66. package/lib/hookDialects.mjs +235 -50
  67. package/lib/identityLink.mjs +81 -0
  68. package/lib/inference.mjs +31 -2
  69. package/lib/jamAccess.mjs +82 -0
  70. package/lib/{projectBoard.mjs → jamBoard.mjs} +5 -4
  71. package/lib/{projectGit.mjs → jamGit.mjs} +53 -15
  72. package/lib/jamKey.mjs +274 -0
  73. package/lib/{projectPieces.mjs → jamPieces.mjs} +35 -29
  74. package/lib/{projectSettings.mjs → jamSettings.mjs} +12 -22
  75. package/lib/jamStore.mjs +973 -0
  76. package/lib/jamUpgrade.mjs +112 -0
  77. package/lib/jams.mjs +3079 -0
  78. package/lib/kanban.mjs +13 -7
  79. package/lib/landed.mjs +5 -1
  80. package/lib/library.mjs +41 -22
  81. package/lib/limits.mjs +91 -0
  82. package/lib/lineDiff.mjs +97 -0
  83. package/lib/lineup.mjs +18 -13
  84. package/lib/link.mjs +584 -0
  85. package/lib/localStack.mjs +75 -16
  86. package/lib/localmodels.mjs +58 -78
  87. package/lib/loopBackstop.mjs +2 -1
  88. package/lib/machine.mjs +544 -0
  89. package/lib/machineLink.mjs +446 -0
  90. package/lib/machineRoutes.mjs +68 -19
  91. package/lib/machineRuns.mjs +85 -4
  92. package/lib/machineSeal.mjs +6 -31
  93. package/lib/manager.mjs +134 -12
  94. package/lib/mcp-stdio.mjs +492 -215
  95. package/lib/mcpRelay.mjs +34 -35
  96. package/lib/members.json +2 -2
  97. package/lib/modelRoute.mjs +162 -0
  98. package/lib/nativeHost.mjs +81 -90
  99. package/lib/nativeSenses.mjs +258 -0
  100. package/lib/nerves.mjs +523 -0
  101. package/lib/network.mjs +117 -278
  102. package/lib/networkPlaces.mjs +578 -0
  103. package/lib/nextStep.mjs +95 -0
  104. package/lib/notify.mjs +2 -2
  105. package/lib/nudge.mjs +116 -10
  106. package/lib/onboard.mjs +6 -6
  107. package/lib/originals.mjs +216 -0
  108. package/lib/outsideEvents.mjs +383 -0
  109. package/lib/outsideRuns.mjs +230 -0
  110. package/lib/ownMachines.mjs +674 -256
  111. package/lib/pain.mjs +215 -0
  112. package/lib/pairing.mjs +91 -11
  113. package/lib/paths.mjs +42 -3
  114. package/lib/peerProcess.mjs +21 -7
  115. package/lib/peopleLink.mjs +268 -0
  116. package/lib/personNotices.mjs +3 -2
  117. package/lib/phones.mjs +252 -542
  118. package/lib/placeCards.mjs +282 -0
  119. package/lib/placeChecks.mjs +95 -0
  120. package/lib/placeCommands.mjs +8 -17
  121. package/lib/placeRequests.mjs +152 -0
  122. package/lib/placeStore.mjs +295 -0
  123. package/lib/placeTool.d.ts +12 -0
  124. package/lib/placeTool.js +40 -0
  125. package/lib/places.mjs +63 -14
  126. package/lib/plans.mjs +53 -8
  127. package/lib/presence.mjs +270 -0
  128. package/lib/privateNetwork.d.ts +2 -0
  129. package/lib/privateNetwork.js +93 -0
  130. package/lib/proposals.mjs +300 -0
  131. package/lib/publicFetch.d.ts +32 -0
  132. package/lib/publicFetch.js +248 -0
  133. package/lib/reach.mjs +128 -0
  134. package/lib/rebuildable.mjs +72 -0
  135. package/lib/recall.mjs +216 -0
  136. package/lib/record.mjs +13 -0
  137. package/lib/reflexes.mjs +392 -0
  138. package/lib/relayLimits.mjs +31 -2
  139. package/lib/releaseNotice.mjs +198 -0
  140. package/lib/removeHarness.mjs +15 -4
  141. package/lib/repoLinks.mjs +204 -35
  142. package/lib/runAuthority.mjs +102 -39
  143. package/lib/runBrief.mjs +93 -40
  144. package/lib/runRequests.mjs +52 -14
  145. package/lib/runUsage.mjs +31 -0
  146. package/lib/runWorker.mjs +74 -25
  147. package/lib/runner.mjs +289 -45
  148. package/lib/runtime-install.mjs +37 -8
  149. package/lib/schedules.mjs +171 -47
  150. package/lib/screenWatches.mjs +221 -0
  151. package/lib/sealed.mjs +12 -30
  152. package/lib/sealedThreads.mjs +198 -392
  153. package/lib/secretStore.mjs +178 -0
  154. package/lib/secrets.mjs +11 -0
  155. package/lib/seen.mjs +3 -9
  156. package/lib/selfUpdate.mjs +51 -15
  157. package/lib/senseCall.mjs +1514 -0
  158. package/lib/senseHook.mjs +114 -0
  159. package/lib/senseTools.mjs +1298 -0
  160. package/lib/sessionBriefs.mjs +87 -0
  161. package/lib/sessionControl.mjs +63 -13
  162. package/lib/sessionFiles.mjs +85 -0
  163. package/lib/setupChoices.mjs +12 -3
  164. package/lib/setupMode.mjs +70 -25
  165. package/lib/sharedKeys.mjs +166 -0
  166. package/lib/sleep.mjs +396 -0
  167. package/lib/sources.mjs +306 -0
  168. package/lib/speech.mjs +166 -411
  169. package/lib/spoken.mjs +210 -0
  170. package/lib/steerHook.mjs +3 -1
  171. package/lib/steerQueue.mjs +40 -11
  172. package/lib/store.mjs +323 -130
  173. package/lib/stuck.mjs +85 -7
  174. package/lib/swarm.mjs +157 -49
  175. package/lib/swarmDevices.mjs +25 -85
  176. package/lib/swarmMemory.mjs +93 -9
  177. package/lib/t3.mjs +73 -3
  178. package/lib/taskCommands.mjs +51 -60
  179. package/lib/taskRooms.mjs +30 -4
  180. package/lib/taskRules.json +29 -0
  181. package/lib/taskRules.mjs +21 -0
  182. package/lib/taskRuns.mjs +74 -11
  183. package/lib/team.mjs +2 -1
  184. package/lib/threadActions.mjs +37 -9
  185. package/lib/threadAuthority.mjs +4 -4
  186. package/lib/threadBriefs.mjs +173 -43
  187. package/lib/threadNotes.mjs +320 -0
  188. package/lib/threadRecord.mjs +491 -0
  189. package/lib/threadRuns.mjs +216 -108
  190. package/lib/threadView.mjs +27 -30
  191. package/lib/threadWatches.mjs +1962 -0
  192. package/lib/timeSense.mjs +839 -0
  193. package/lib/tripwires.mjs +454 -0
  194. package/lib/ui.mjs +1 -1
  195. package/lib/vault.mjs +560 -45
  196. package/lib/vaultCommands.mjs +5 -3
  197. package/lib/vaultPeers.mjs +165 -0
  198. package/lib/vaultTools.d.ts +4 -1
  199. package/lib/vaultTools.js +22 -1
  200. package/lib/verdicts.mjs +12 -26
  201. package/lib/versions.mjs +117 -0
  202. package/lib/waitTool.mjs +278 -0
  203. package/lib/wakePicture.mjs +268 -0
  204. package/lib/wakeQueue.mjs +108 -0
  205. package/lib/watchResponses.mjs +533 -0
  206. package/lib/watches.mjs +290 -145
  207. package/lib/windowAsks.mjs +80 -17
  208. package/lib/worktrees.mjs +159 -9
  209. package/npm-shrinkwrap.json +138 -631
  210. package/package.json +7 -6
  211. package/release.json +212 -130
  212. package/lib/callSessions.mjs +0 -51
  213. package/lib/directLink.mjs +0 -349
  214. package/lib/peopleBoard.mjs +0 -131
  215. package/lib/projects.mjs +0 -2917
  216. package/lib/roomChannels.mjs +0 -667
@@ -1,9 +1,12 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
- import { ensureDir, readJson } from "./files.mjs";
4
+ import { ensureDir, updateJson } from "./files.mjs";
5
5
  import { steerRoot } from "./steerQueue.mjs";
6
- import { harnessNode } from "./paths.mjs";
6
+ import { callsRoot, marksRoot, tripsRoot } from "./senseCall.mjs";
7
+ import { timeRoot } from "./timeSense.mjs";
8
+ import { harnessHome, harnessNode, stableRuntimeRoot } from "./paths.mjs";
9
+ import { outsideHeldRoot } from "./outsideRuns.mjs";
7
10
 
8
11
  // How each agent runs session hooks: the file it reads them from, that file's shape, and what it does with a hook's
9
12
  // output. Harness hooks three moments, by the names Claude Code gave them: a session starting (its board notice, where it
@@ -11,24 +14,59 @@ import { harnessNode } from "./paths.mjs";
11
14
  // it going). Setup writes each agent's file from here (installSessionHooks); nudge.mjs answers each agent in its own
12
15
  // words (hookDialect). Every other setting and hook in a file is kept; setup replaces Harness's entries and uninstall
13
16
  // takes only them out. Read from each agent's own docs and source, October 2026.
17
+ //
18
+ // A fourth moment, after each tool call: what Harness noticed while the agent works (a watch or wait answering, the same
19
+ // command run again and again) reaches the model there, as text beside the tool's result (docs/senses-plan.md S3.6;
20
+ // nudge.mjs --step). Every agent that has such a hook gets it, as alike as each allows (owner, November 13: "they
21
+ // should all work as closely to the same as possible").
14
22
  export const HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "Stop"];
23
+ // After each tool call: what it read and wrote, kept as the session's, and Harness's readings for the agent at work
24
+ // (senseHook.mjs --after), under each agent's own name for it.
25
+ export const AFTER_TOOL = "AfterTool";
26
+ // Before each tool call: the tripwire on a write (senseHook.mjs --before; docs/senses-plan.md S4.3), run only while a
27
+ // trip waits.
28
+ export const BEFORE_TOOL = "BeforeTool";
29
+ // The answer that refuses a tool call with a reason, in Claude Code's words, which Codex, Devin and Grok Build read too.
30
+ const claudeHold = (text) =>
31
+ JSON.stringify({
32
+ hookSpecificOutput: {
33
+ hookEventName: "PreToolUse",
34
+ permissionDecision: "deny",
35
+ permissionDecisionReason: text,
36
+ },
37
+ });
38
+ // The text an after-call hook adds beside a tool's result, in Claude Code's words, which Codex, Devin and Grok Build
39
+ // read too. Each other agent's own words are with its dialect below.
40
+ // After a call, or after one that failed (Claude Code's PostToolUseFailure, where recall answers an error).
41
+ const claudeAfter = (text, event = "PostToolUse") =>
42
+ JSON.stringify({
43
+ hookSpecificOutput: {
44
+ hookEventName: event === "PostToolUseFailure" ? event : "PostToolUse",
45
+ additionalContext: text,
46
+ },
47
+ });
15
48
  // Claude Code alone also runs Harness at each tool call, as each subagent ends and as a permission dialog opens, for what
16
49
  // the person tells one of its subagents and what a subagent asks (steerHook.mjs); its hooks name the subagent they fire in.
17
50
  export const STEER_EVENTS = ["PreToolUse", "SubagentStop", "PermissionRequest"];
18
51
 
19
52
  const isHarnessHook = (entry) =>
20
- ["/lib/nudge.mjs", "/lib/steerHook.mjs"].some((file) =>
53
+ ["/lib/nudge.mjs", "/lib/steerHook.mjs", "/lib/senseHook.mjs"].some((file) =>
21
54
  JSON.stringify(entry).includes(file)
22
55
  );
23
56
  const objectOr = (value) =>
24
57
  value && typeof value === "object" && !Array.isArray(value) ? value : {};
25
- const withOurs = (list, ours) => [
58
+ const withOurs = (list, ...ours) => [
26
59
  ...(Array.isArray(list) ? list : []).filter((entry) => !isHarnessHook(entry)),
27
- ...(ours ? [ours] : []),
60
+ ...ours.filter(Boolean),
28
61
  ];
29
62
 
30
63
  // Claude Code's shape: settings.hooks[event] holds [{ matcher?, hooks: [{ type: "command", command, timeout }] }].
31
- const claudeShape = ({ start = {}, startHook = {} } = {}) => ({
64
+ const claudeShape = ({
65
+ start = {},
66
+ startHook = {},
67
+ failure = false,
68
+ compacting = false,
69
+ } = {}) => ({
32
70
  write: (settings, commands) => {
33
71
  const hooks = objectOr(settings.hooks);
34
72
  const next = { ...hooks };
@@ -41,20 +79,49 @@ const claudeShape = ({ start = {}, startHook = {} } = {}) => ({
41
79
  : { hooks: [{ ...hook, timeout: 10 }] }
42
80
  );
43
81
  }
82
+ const entry = (command) =>
83
+ command ? { hooks: [{ type: "command", command, timeout: 5 }] } : null;
44
84
  for (const event of STEER_EVENTS) {
45
- if (commands[event])
85
+ const before = event === "PreToolUse" ? commands[BEFORE_TOOL] : null;
86
+ if (commands[event] || before)
87
+ next[event] = withOurs(
88
+ hooks[event],
89
+ entry(commands[event]),
90
+ entry(before)
91
+ );
92
+ else if (Array.isArray(hooks[event]))
93
+ next[event] = withOurs(hooks[event]);
94
+ }
95
+ // After a call; and, where the agent has it, after one that failed, so an error's shape reaches recall.
96
+ for (const event of failure
97
+ ? ["PostToolUse", "PostToolUseFailure"]
98
+ : ["PostToolUse"]) {
99
+ if (commands[AFTER_TOOL])
46
100
  next[event] = withOurs(hooks[event], {
47
- hooks: [{ type: "command", command: commands[event], timeout: 5 }],
101
+ hooks: [
102
+ { type: "command", command: commands[AFTER_TOOL], timeout: 5 },
103
+ ],
48
104
  });
49
105
  else if (Array.isArray(hooks[event]))
50
106
  next[event] = withOurs(hooks[event]);
51
107
  }
108
+ // Before a compaction, where the agent has it: the summary's instructions (senseHook.mjs --compacting).
109
+ if (compacting && commands.PreCompact)
110
+ next.PreCompact = withOurs(hooks.PreCompact, {
111
+ hooks: [{ type: "command", command: commands.PreCompact, timeout: 5 }],
112
+ });
52
113
  return { ...settings, hooks: next };
53
114
  },
54
115
  erase: (settings) => {
55
116
  if (!settings.hooks) return settings;
56
117
  const hooks = { ...objectOr(settings.hooks) };
57
- for (const event of [...HOOK_EVENTS, ...STEER_EVENTS])
118
+ for (const event of [
119
+ ...HOOK_EVENTS,
120
+ ...STEER_EVENTS,
121
+ "PostToolUse",
122
+ "PostToolUseFailure",
123
+ "PreCompact",
124
+ ])
58
125
  if (Array.isArray(hooks[event])) hooks[event] = withOurs(hooks[event]);
59
126
  return { ...settings, hooks };
60
127
  },
@@ -65,34 +132,39 @@ const flatShape = ({ names, entry }) => ({
65
132
  write: (settings, commands) => {
66
133
  const hooks = objectOr(settings.hooks);
67
134
  const next = { ...hooks };
68
- for (const event of HOOK_EVENTS)
135
+ for (const event of [...HOOK_EVENTS, AFTER_TOOL, BEFORE_TOOL]) {
136
+ if (!names[event]) continue;
69
137
  next[names[event]] = withOurs(
70
138
  hooks[names[event]],
71
- entry(commands[event])
139
+ commands[event] ? entry(commands[event]) : null
72
140
  );
141
+ }
73
142
  return { ...settings, version: settings.version ?? 1, hooks: next };
74
143
  },
75
144
  erase: (settings) => {
76
145
  if (!settings.hooks) return settings;
77
146
  const hooks = { ...objectOr(settings.hooks) };
78
- for (const event of HOOK_EVENTS)
79
- if (Array.isArray(hooks[names[event]]))
147
+ for (const event of [...HOOK_EVENTS, AFTER_TOOL, BEFORE_TOOL])
148
+ if (names[event] && Array.isArray(hooks[names[event]]))
80
149
  hooks[names[event]] = withOurs(hooks[names[event]]);
81
150
  return { ...settings, hooks };
82
151
  },
83
152
  });
84
153
 
85
- // Antigravity's file holds named sets of hooks; Harness's is the set named "harness".
154
+ // Antigravity's file holds named sets of hooks; Harness's is the set named "harness". Two of Harness's hooks can run at
155
+ // one event, each its own entry.
86
156
  const namedShape = ({ name, names }) => ({
87
- write: (settings, commands) => ({
88
- ...settings,
89
- [name]: Object.fromEntries(
90
- HOOK_EVENTS.map((event) => [
91
- names[event],
92
- [{ type: "command", command: commands[event], timeout: 10 }],
93
- ])
94
- ),
95
- }),
157
+ write: (settings, commands) => {
158
+ const set = {};
159
+ for (const event of [...HOOK_EVENTS, AFTER_TOOL]) {
160
+ if (!names[event] || !commands[event]) continue;
161
+ set[names[event]] = [
162
+ ...(set[names[event]] ?? []),
163
+ { type: "command", command: commands[event], timeout: 10 },
164
+ ];
165
+ }
166
+ return { ...settings, [name]: set };
167
+ },
96
168
  erase: (settings) => {
97
169
  if (!(name in settings)) return settings;
98
170
  const { [name]: _ours, ...rest } = settings;
@@ -103,15 +175,22 @@ const namedShape = ({ name, names }) => ({
103
175
  const asText = (text) => text;
104
176
  const claudeBlock = (text) =>
105
177
  JSON.stringify({ decision: "block", reason: text });
178
+ // Antigravity's way to add a message: a step it puts into the conversation as a system message.
179
+ const injected = (text) =>
180
+ JSON.stringify({
181
+ injectSteps: [{ systemMessage: { systemMessage: text } }],
182
+ });
106
183
 
107
184
  const DIALECTS = {
108
185
  // Other agents read Claude Code's files and run its hooks as their own: --check-host (nudge.mjs startedByAnother).
109
186
  "claude-code": {
110
187
  file: (home) => path.join(home, ".claude", "settings.json"),
111
- shape: claudeShape(),
188
+ shape: claudeShape({ failure: true, compacting: true }),
112
189
  flags: ["--check-host"],
113
190
  context: { SessionStart: asText, UserPromptSubmit: asText },
114
191
  block: claudeBlock,
192
+ after: claudeAfter,
193
+ hold: claudeHold,
115
194
  },
116
195
  // Codex runs the session-start hook after a compaction too, so the session hears its work again (compaction.mjs).
117
196
  // It asks the person to trust a new or changed hook once, with /hooks in its TUI, before it runs; setup says so.
@@ -123,9 +202,12 @@ const DIALECTS = {
123
202
  }),
124
203
  context: { SessionStart: asText, UserPromptSubmit: asText },
125
204
  block: claudeBlock,
205
+ after: claudeAfter,
206
+ hold: claudeHold,
126
207
  },
127
208
  // Grok Build reads every JSON file in ~/.grok/hooks, so Harness's hooks are a file of their own. It ignores what its
128
- // session-start and prompt hooks print: its notice comes in the MCP server's instructions.
209
+ // session-start and prompt hooks print: its notice comes in the MCP server's instructions. Its hook after a tool call
210
+ // adds text from 1.0.14 (its changelog); one before that would take Harness's reading and drop it.
129
211
  "grok-build": {
130
212
  file: (home, env) =>
131
213
  path.join(
@@ -137,6 +219,9 @@ const DIALECTS = {
137
219
  shape: claudeShape(),
138
220
  context: {},
139
221
  block: claudeBlock,
222
+ after: claudeAfter,
223
+ afterSince: "1.0.14",
224
+ hold: claudeHold,
140
225
  },
141
226
  // Copilot's CLI reads every JSON file in ~/.copilot/hooks. Only JSON from its session-start hook reaches the model;
142
227
  // its prompt hook's output is dropped.
@@ -153,6 +238,8 @@ const DIALECTS = {
153
238
  SessionStart: "sessionStart",
154
239
  UserPromptSubmit: "userPromptSubmitted",
155
240
  Stop: "agentStop",
241
+ [AFTER_TOOL]: "postToolUse",
242
+ [BEFORE_TOOL]: "preToolUse",
156
243
  },
157
244
  entry: (command) => ({ type: "command", bash: command, timeoutSec: 10 }),
158
245
  }),
@@ -160,6 +247,13 @@ const DIALECTS = {
160
247
  SessionStart: (text) => JSON.stringify({ additionalContext: text }),
161
248
  },
162
249
  block: claudeBlock,
250
+ // Added to the tool's result, which the model reads on the same turn.
251
+ after: (text) => JSON.stringify({ additionalContext: text }),
252
+ hold: (text) =>
253
+ JSON.stringify({
254
+ permissionDecision: "deny",
255
+ permissionDecisionReason: text,
256
+ }),
163
257
  },
164
258
  // Cursor (its CLI and its app) reads ~/.cursor/hooks.json, which the person's own hooks share. Its prompt hook cannot
165
259
  // add context; its stop hook hands back a follow-up the agent sends as the person's next message. Grok Build runs
@@ -171,6 +265,8 @@ const DIALECTS = {
171
265
  SessionStart: "sessionStart",
172
266
  UserPromptSubmit: "beforeSubmitPrompt",
173
267
  Stop: "stop",
268
+ [AFTER_TOOL]: "postToolUse",
269
+ [BEFORE_TOOL]: "preToolUse",
174
270
  },
175
271
  entry: (command) => ({ command, timeout: 10 }),
176
272
  }),
@@ -179,10 +275,15 @@ const DIALECTS = {
179
275
  SessionStart: (text) => JSON.stringify({ additional_context: text }),
180
276
  },
181
277
  block: (text) => JSON.stringify({ followup_message: text }),
278
+ // Put into the conversation after the tool's result.
279
+ after: (text) => JSON.stringify({ additional_context: text }),
280
+ hold: (text) => JSON.stringify({ permission: "deny", agent_message: text }),
182
281
  },
183
282
  // Antigravity reads ~/.gemini/config/hooks.json (CLI, app and IDE). It has no prompt event: PreInvocation runs before
184
283
  // each model call. Its session start does not run when a conversation is resumed, and a stop that continues adds the
185
- // message as a system message.
284
+ // message as a system message. Its hook after a tool call cannot add text, so Harness's readings come before its next
285
+ // model call instead, the same moment for the model. That moment names no tool call, so what Antigravity reads and
286
+ // writes is not kept and no write of its is held (afterNamesCall).
186
287
  antigravity: {
187
288
  file: (home) => path.join(home, ".gemini", "config", "hooks.json"),
188
289
  shape: namedShape({
@@ -191,15 +292,15 @@ const DIALECTS = {
191
292
  SessionStart: "SessionStart",
192
293
  UserPromptSubmit: "PreInvocation",
193
294
  Stop: "Stop",
295
+ [AFTER_TOOL]: "PreInvocation",
194
296
  },
195
297
  }),
196
298
  context: {
197
- SessionStart: (text) =>
198
- JSON.stringify({
199
- injectSteps: [{ systemMessage: { systemMessage: text } }],
200
- }),
299
+ SessionStart: (text) => injected(text),
201
300
  },
202
301
  block: (text) => JSON.stringify({ decision: "continue", reason: text }),
302
+ after: (text) => injected(text),
303
+ afterNamesCall: false,
203
304
  },
204
305
  // Devin's CLI keeps its hooks in its config.json (beside its other settings), in Claude Code's shape, and takes
205
306
  // context only as JSON. It also runs Claude Code's hooks, which stand down there (--check-host).
@@ -223,6 +324,8 @@ const DIALECTS = {
223
324
  }),
224
325
  },
225
326
  block: claudeBlock,
327
+ after: claudeAfter,
328
+ hold: claudeHold,
226
329
  },
227
330
  };
228
331
 
@@ -263,6 +366,29 @@ export function sessionHooksPath(
263
366
  return DIALECTS[agent].file(homeDir, env);
264
367
  }
265
368
 
369
+ /** Whether an agent's hook after a tool call adds what it prints, at the version setup found (null: not known). */
370
+ export function takesStepNotes(agent, version = null) {
371
+ const dialect = DIALECTS[agent];
372
+ if (!dialect?.after) return false;
373
+ return !dialect.afterSince || atLeast(version, dialect.afterSince);
374
+ }
375
+
376
+ // "1.0.14" or "grok 1.2.0 (abc)": the first version in it, compared part by part.
377
+ const partsOf = (text) =>
378
+ /(\d+)\.(\d+)(?:\.(\d+))?/
379
+ .exec(String(text ?? ""))
380
+ ?.slice(1)
381
+ .map((part) => Number(part ?? 0)) ?? null;
382
+ const atLeast = (version, least) => {
383
+ const have = partsOf(version);
384
+ const need = partsOf(least);
385
+ if (!have || !need) return false;
386
+ for (let i = 0; i < need.length; i++)
387
+ if (have[i] !== need[i]) return have[i] > need[i];
388
+ return true;
389
+ };
390
+
391
+ /** Writes an agent's session hooks. `version`: the agent's own, where setup read it, for a hook only later ones take. */
266
392
  export function installSessionHooks(
267
393
  agent,
268
394
  {
@@ -270,47 +396,105 @@ export function installSessionHooks(
270
396
  homeDir = os.homedir(),
271
397
  nodePath = harnessNode(),
272
398
  env = process.env,
399
+ version = null,
273
400
  }
274
401
  ) {
275
402
  const dialect = DIALECTS[agent];
276
403
  const file = dialect.file(homeDir, env);
404
+ // By a name that stays the same across Harness's updates, so a changed command never asks for approval again.
405
+ const root = stableRuntimeRoot(runtimeRoot);
277
406
  const nudge = [
278
407
  JSON.stringify(nodePath),
279
- JSON.stringify(path.join(runtimeRoot, "lib", "nudge.mjs")),
408
+ JSON.stringify(path.join(root, "lib", "nudge.mjs")),
409
+ "--agent",
410
+ agent,
411
+ ...(dialect.flags ?? []),
412
+ ].join(" ");
413
+ const sense = [
414
+ JSON.stringify(nodePath),
415
+ JSON.stringify(path.join(root, "lib", "senseHook.mjs")),
280
416
  "--agent",
281
417
  agent,
282
418
  ...(dialect.flags ?? []),
283
419
  ].join(" ");
420
+ const notes = takesStepNotes(agent, version);
421
+ // Each call's start, noted by the shell before it under the agent's process ($PPID) with no Node start, so the hook
422
+ // after it knows what changed while the call ran (senseCall.mjs callsRoot).
423
+ const shell = process.platform !== "win32";
424
+ if (shell) ensureDir(callsRoot());
425
+ const callStarts = shell
426
+ ? `: > ${JSON.stringify(callsRoot())}/"$PPID" 2>/dev/null; `
427
+ : "";
428
+ const agentPid = shell ? ' --agent-pid "$PPID"' : "";
429
+ // After a call: every call is kept as the session's (what it read is the start of a tripwire), so Node starts at each
430
+ // one (S0.6: 21 to 23 ms); where the call is not named, Harness's readings alone, while one waits.
431
+ const after =
432
+ dialect.afterNamesCall === false
433
+ ? notes
434
+ ? guarded(`${nudge} --step`)
435
+ : null
436
+ : `${sense} --after${notes ? "" : " --quiet"}${agentPid}`;
284
437
  const commands = {
285
438
  SessionStart: nudge,
286
439
  // Mid-session: on every prompt, one line only when the queue changed since the session last saw it.
287
440
  UserPromptSubmit: `${nudge} --if-changed`,
288
441
  Stop: `${nudge} --stop`,
289
- ...(agent === "claude-code" ? steerCommands(runtimeRoot, nodePath) : {}),
442
+ ...(after ? { [AFTER_TOOL]: after } : {}),
443
+ ...(dialect.hold
444
+ ? {
445
+ [BEFORE_TOOL]: callStarts + beforeGuard(`${sense} --before`, shell),
446
+ }
447
+ : {}),
448
+ ...(agent === "claude-code" ? steerCommands(root, nodePath) : {}),
449
+ PreCompact: `${sense} --compacting`,
290
450
  };
291
- const settings = dialect.ownFile ? {} : readJson(file, {});
292
- ensureDir(path.dirname(file));
293
- fs.writeFileSync(
294
- file,
295
- JSON.stringify(dialect.shape.write(settings, commands), null, 2) + "\n"
296
- );
451
+ if (dialect.ownFile) {
452
+ ensureDir(path.dirname(file));
453
+ fs.writeFileSync(
454
+ file,
455
+ JSON.stringify(dialect.shape.write({}, commands), null, 2) + "\n"
456
+ );
457
+ return;
458
+ }
459
+ // The person's own settings file: everything else in it stays.
460
+ updateJson(file, (settings) => dialect.shape.write(settings, commands));
297
461
  }
298
462
 
299
- // Claude Code runs these on every tool call of every session, so a shell test of the steer folder goes first: Node
300
- // starts only when a steer waits somewhere (steerQueue.mjs keeps the folder empty otherwise).
463
+ // The hook before each call (senseHook.mjs --before): Node starts only while a trip or a reflex's hold waits, while a
464
+ // mark another agent left is alive (it is said before the write or command it is about), for a call that may replace or
465
+ // remove a file (a whole write, a patch deleting one, a shell command with `rm` or `>`), whose file is kept first
466
+ // (senseCall.mjs saveBefore), for a commit or a push (a test run before the session's changes, timeSense.mjs), and for
467
+ // a command whose usual here is long (timeSense.mjs writes long.sh, the test for those), and while a thread's turn that
468
+ // began outside holds the commands that send work off the computer (outsideRuns.mjs). The shell reads the call once
469
+ // and hands it on.
470
+ // First, with no process started, the shell notes the call's own start under its id, where the agent gives one, so two
471
+ // calls at once each keep their own (timeSense.mjs, Phase T.1).
472
+ const ownStart = (shell) =>
473
+ shell
474
+ ? `id=; case "$input" in *'"tool_use_id":"'*) id=\${input#*'"tool_use_id":"'};; *'"tool_use_id": "'*) id=\${input#*'"tool_use_id": "'};; *'"call_id":"'*) id=\${input#*'"call_id":"'};; esac; id=\${id%%'"'*}; case "$id" in ''|*[!A-Za-z0-9_.:-]*) id=;; esac; [ -n "$id" ] && : > ${JSON.stringify(callsRoot())}/"$PPID.$id" 2>/dev/null; `
475
+ : "";
476
+ const beforeGuard = (hook, shell = false) =>
477
+ process.platform === "win32"
478
+ ? hook
479
+ : `input=$(cat); ${ownStart(shell)}risky=; case "$input" in *'"Write"'*|*'"write"'*|*'Delete File'*|*'"command"'*'rm '*|*'"command"'*'>'*|*'git commit'*|*'git push'*) risky=1;; esac; [ -f ${JSON.stringify(path.join(timeRoot(), "long.sh"))} ] && . ${JSON.stringify(path.join(timeRoot(), "long.sh"))}; held=; for f in ${JSON.stringify(outsideHeldRoot(harnessHome))}/*.json; do [ -e "$f" ] && held=1; break; done; if [ -n "$risky" ] || [ -n "$(ls -A ${JSON.stringify(tripsRoot())} 2>/dev/null)$(ls -A ${JSON.stringify(marksRoot())} 2>/dev/null)" ] || [ -n "$held" ]; then printf '%s' "$input" | ${hook}; fi; true`;
480
+
481
+ // A hook run on every tool call of every session: a shell test of the steer folder goes first, so Node starts only when
482
+ // something waits somewhere (steerQueue.mjs keeps the folder empty otherwise).
483
+ const guarded = (hook, folder = steerRoot()) =>
484
+ process.platform === "win32"
485
+ ? hook
486
+ : `[ -n "$(ls -A ${JSON.stringify(folder)} 2>/dev/null)" ] && ${hook} || true`;
487
+
488
+ // Claude Code's own: what the person tells one of its subagents, and what a subagent asks (steerHook.mjs).
301
489
  function steerCommands(runtimeRoot, nodePath) {
302
490
  const hook = [
303
491
  JSON.stringify(nodePath),
304
492
  JSON.stringify(path.join(runtimeRoot, "lib", "steerHook.mjs")),
305
493
  ].join(" ");
306
- const guarded =
307
- process.platform === "win32"
308
- ? hook
309
- : `[ -n "$(ls -A ${JSON.stringify(steerRoot())} 2>/dev/null)" ] && ${hook} || true`;
310
494
  // A permission dialog is rare, and a subagent's must reach the person whether or not a steer waits.
311
495
  return {
312
- PreToolUse: guarded,
313
- SubagentStop: guarded,
496
+ PreToolUse: guarded(hook),
497
+ SubagentStop: guarded(hook),
314
498
  PermissionRequest: `${hook} --ask`,
315
499
  };
316
500
  }
@@ -326,8 +510,9 @@ export function removeSessionHooks(
326
510
  fs.rmSync(file, { force: true });
327
511
  return;
328
512
  }
329
- const settings = readJson(file, null);
330
- const erased = settings && dialect.shape.erase(settings);
331
- if (erased && erased !== settings)
332
- fs.writeFileSync(file, JSON.stringify(erased, null, 2) + "\n");
513
+ if (!fs.existsSync(file)) return;
514
+ updateJson(file, (settings) => {
515
+ const erased = dialect.shape.erase(settings);
516
+ return erased && erased !== settings ? erased : null;
517
+ });
333
518
  }
@@ -0,0 +1,81 @@
1
+ import { webcrypto } from "node:crypto";
2
+
3
+ // The computer's twin of src/shared/identityLink.ts: when the person's identity keys change, the old signing key signs
4
+ // the new keys, and a friend's computer follows each link from the keys it pinned to the new ones without asking
5
+ // anyone. Keys are raw P-256 points in base64, as in the person's shared keys.
6
+
7
+ const { subtle } = webcrypto;
8
+ const SIGNING = { name: "ECDSA", namedCurve: "P-256" };
9
+ const SIGNATURE = { name: "ECDSA", hash: "SHA-256" };
10
+ const toBase64 = (bytes) => Buffer.from(bytes).toString("base64");
11
+ const fromBase64 = (text) =>
12
+ new Uint8Array(Buffer.from(String(text), "base64"));
13
+
14
+ const linkBytes = (link) =>
15
+ new TextEncoder().encode(
16
+ [
17
+ "harness identity link v1",
18
+ link.prev.publicKey,
19
+ link.prev.signingKey,
20
+ link.next.publicKey,
21
+ link.next.signingKey,
22
+ link.by,
23
+ link.at,
24
+ ].join("\n")
25
+ );
26
+
27
+ /** The link from the identity's keys before ({ publicKey, signingKey }) to its new ones, signed with the keys before. */
28
+ export async function signIdentityLink({
29
+ prev,
30
+ next,
31
+ by,
32
+ prevSigningPrivateKey,
33
+ }) {
34
+ const unsigned = { v: 1, prev, next, by, at: new Date().toISOString() };
35
+ const signature = await subtle.sign(
36
+ SIGNATURE,
37
+ prevSigningPrivateKey,
38
+ linkBytes(unsigned)
39
+ );
40
+ return { ...unsigned, signature: toBase64(new Uint8Array(signature)) };
41
+ }
42
+
43
+ /** Whether the link is signed by the signing key it starts from. */
44
+ export async function identityLinkHolds(link) {
45
+ try {
46
+ const key = await subtle.importKey(
47
+ "raw",
48
+ fromBase64(link.prev.signingKey),
49
+ SIGNING,
50
+ false,
51
+ ["verify"]
52
+ );
53
+ return await subtle.verify(
54
+ SIGNATURE,
55
+ key,
56
+ fromBase64(link.signature),
57
+ linkBytes(link)
58
+ );
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The keys reached from `pinned` by following `links` in order, each signed by the keys before it. Throws when a link
66
+ * does not start where the one before ended, or its signature does not hold.
67
+ */
68
+ export async function followIdentityLinks(pinned, links) {
69
+ let at = pinned;
70
+ for (const link of links ?? []) {
71
+ if (
72
+ link?.prev?.publicKey !== at.publicKey ||
73
+ link?.prev?.signingKey !== at.signingKey
74
+ )
75
+ throw new Error("the identity's links do not follow from its keys");
76
+ if (!(await identityLinkHolds(link)))
77
+ throw new Error("an identity link is not signed by the keys before it");
78
+ at = { publicKey: link.next.publicKey, signingKey: link.next.signingKey };
79
+ }
80
+ return at;
81
+ }
package/lib/inference.mjs CHANGED
@@ -272,6 +272,9 @@ export function createInference({
272
272
  const chooseDevice = async () => {
273
273
  const known = device();
274
274
  if (known) return known.gpu;
275
+ // The check runs on the search model. Without it the GPU build runs (llama.cpp uses the CPU where there is no GPU)
276
+ // and the check waits until the search model is here: one model must not need another to start.
277
+ if (!modelsPresent(root, ["search"], list)) return true;
275
278
  const timed = async (gpu) => {
276
279
  const trial = await launch(gpu);
277
280
  try {
@@ -326,8 +329,6 @@ export function createInference({
326
329
  if (server && server.child.exitCode === null)
327
330
  return Promise.resolve(server);
328
331
  starting ||= (async () => {
329
- if (!modelsPresent(root, ["search"], list))
330
- throw new Error("the search model is not downloaded yet");
331
332
  const started = await launch(await chooseDevice());
332
333
  // Only this server's exit clears it: a restarted server must not be forgotten when the old one goes.
333
334
  started.child.on("exit", () => {
@@ -356,6 +357,8 @@ export function createInference({
356
357
  };
357
358
  /** The server, with room made for the model about to run on it. Call while the llama lane holds "llama" in use. */
358
359
  const llamaFor = async (id) => {
360
+ if (!modelsPresent(root, [id], list))
361
+ throw new Error(`the ${id} model is not downloaded yet`);
359
362
  const serving = new Set([...llamaServing, id]);
360
363
  const mb = [...serving].reduce(
361
364
  (sum, model) => sum + memoryCostMb(modelById(model, list)),
@@ -616,6 +619,32 @@ export function createInference({
616
619
  else list.push(entry);
617
620
  if (server) await stopServer();
618
621
  },
622
+ /** The chat models Harness serves that are downloaded here (not the search model, which only embeds). */
623
+ chatModels: () =>
624
+ list
625
+ .filter((entry) => entry.runtime === "llama" && entry.id !== "search")
626
+ .map((entry) => entry.id)
627
+ .filter((id) => modelsPresent(root, [id], list)),
628
+ /**
629
+ * Where a downloaded model Harness serves answers now, started if it was not: `{ base, headers }` for an OpenAI-style
630
+ * request to pass through as it is (the route at the model, modelRoute.mjs, streams through it).
631
+ */
632
+ serving: (id, { lane = "interactive" } = {}) =>
633
+ schedule("llama", lane, () =>
634
+ inUse("llama", async () => {
635
+ if (!modelsPresent(root, [id], list))
636
+ throw new Error(
637
+ `${modelById(id, list)?.name ?? id} is not downloaded yet`
638
+ );
639
+ let ready = await llamaFor(id);
640
+ if (!ready.serves?.has(id)) {
641
+ await stopServer();
642
+ ready = await llamaFor(id);
643
+ }
644
+ // Its key goes with every request: the model server answers nothing without it.
645
+ return { base: ready.base, headers: { ...keyed } };
646
+ })
647
+ ),
619
648
  chat: (id, request, { lane = "handoff" } = {}) =>
620
649
  schedule("llama", lane, () =>
621
650
  inUse("llama", async () => {