tryharness 0.7.83 → 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 (215) 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 +191 -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 +52 -0
  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 +2426 -338
  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 +1 -1
  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/originals.mjs +216 -0
  107. package/lib/outsideEvents.mjs +383 -0
  108. package/lib/outsideRuns.mjs +230 -0
  109. package/lib/ownMachines.mjs +674 -256
  110. package/lib/pain.mjs +215 -0
  111. package/lib/pairing.mjs +91 -11
  112. package/lib/paths.mjs +42 -3
  113. package/lib/peerProcess.mjs +21 -7
  114. package/lib/peopleLink.mjs +268 -0
  115. package/lib/personNotices.mjs +3 -2
  116. package/lib/phones.mjs +252 -542
  117. package/lib/placeCards.mjs +282 -0
  118. package/lib/placeChecks.mjs +95 -0
  119. package/lib/placeCommands.mjs +8 -17
  120. package/lib/placeRequests.mjs +152 -0
  121. package/lib/placeStore.mjs +295 -0
  122. package/lib/placeTool.d.ts +12 -0
  123. package/lib/placeTool.js +40 -0
  124. package/lib/places.mjs +63 -14
  125. package/lib/plans.mjs +53 -8
  126. package/lib/presence.mjs +270 -0
  127. package/lib/privateNetwork.d.ts +2 -0
  128. package/lib/privateNetwork.js +93 -0
  129. package/lib/proposals.mjs +300 -0
  130. package/lib/publicFetch.d.ts +32 -0
  131. package/lib/publicFetch.js +248 -0
  132. package/lib/reach.mjs +128 -0
  133. package/lib/rebuildable.mjs +72 -0
  134. package/lib/recall.mjs +216 -0
  135. package/lib/record.mjs +13 -0
  136. package/lib/reflexes.mjs +392 -0
  137. package/lib/relayLimits.mjs +31 -2
  138. package/lib/releaseNotice.mjs +198 -0
  139. package/lib/removeHarness.mjs +15 -4
  140. package/lib/repoLinks.mjs +204 -35
  141. package/lib/runAuthority.mjs +102 -39
  142. package/lib/runBrief.mjs +93 -40
  143. package/lib/runRequests.mjs +52 -14
  144. package/lib/runUsage.mjs +31 -0
  145. package/lib/runWorker.mjs +74 -25
  146. package/lib/runner.mjs +289 -45
  147. package/lib/runtime-install.mjs +37 -8
  148. package/lib/schedules.mjs +171 -47
  149. package/lib/screenWatches.mjs +221 -0
  150. package/lib/sealed.mjs +12 -30
  151. package/lib/sealedThreads.mjs +198 -392
  152. package/lib/secretStore.mjs +178 -0
  153. package/lib/secrets.mjs +11 -0
  154. package/lib/seen.mjs +3 -9
  155. package/lib/selfUpdate.mjs +51 -15
  156. package/lib/senseCall.mjs +1514 -0
  157. package/lib/senseHook.mjs +114 -0
  158. package/lib/senseTools.mjs +1298 -0
  159. package/lib/sessionBriefs.mjs +87 -0
  160. package/lib/sessionControl.mjs +63 -13
  161. package/lib/sessionFiles.mjs +85 -0
  162. package/lib/setupChoices.mjs +12 -3
  163. package/lib/setupMode.mjs +70 -25
  164. package/lib/sharedKeys.mjs +166 -0
  165. package/lib/sleep.mjs +396 -0
  166. package/lib/sources.mjs +306 -0
  167. package/lib/speech.mjs +166 -411
  168. package/lib/spoken.mjs +210 -0
  169. package/lib/steerHook.mjs +3 -1
  170. package/lib/steerQueue.mjs +40 -11
  171. package/lib/store.mjs +323 -130
  172. package/lib/stuck.mjs +85 -7
  173. package/lib/swarm.mjs +157 -49
  174. package/lib/swarmDevices.mjs +25 -85
  175. package/lib/swarmMemory.mjs +93 -9
  176. package/lib/t3.mjs +73 -3
  177. package/lib/taskCommands.mjs +51 -60
  178. package/lib/taskRooms.mjs +30 -4
  179. package/lib/taskRules.json +29 -0
  180. package/lib/taskRules.mjs +21 -0
  181. package/lib/taskRuns.mjs +74 -11
  182. package/lib/team.mjs +2 -1
  183. package/lib/threadActions.mjs +37 -9
  184. package/lib/threadAuthority.mjs +4 -4
  185. package/lib/threadBriefs.mjs +173 -43
  186. package/lib/threadNotes.mjs +320 -0
  187. package/lib/threadRecord.mjs +491 -0
  188. package/lib/threadRuns.mjs +216 -108
  189. package/lib/threadView.mjs +27 -30
  190. package/lib/threadWatches.mjs +1962 -0
  191. package/lib/timeSense.mjs +839 -0
  192. package/lib/tripwires.mjs +454 -0
  193. package/lib/ui.mjs +1 -1
  194. package/lib/vault.mjs +560 -45
  195. package/lib/vaultCommands.mjs +5 -3
  196. package/lib/vaultPeers.mjs +165 -0
  197. package/lib/vaultTools.d.ts +4 -1
  198. package/lib/vaultTools.js +22 -1
  199. package/lib/verdicts.mjs +12 -26
  200. package/lib/versions.mjs +117 -0
  201. package/lib/waitTool.mjs +278 -0
  202. package/lib/wakePicture.mjs +268 -0
  203. package/lib/wakeQueue.mjs +108 -0
  204. package/lib/watchResponses.mjs +533 -0
  205. package/lib/watches.mjs +290 -145
  206. package/lib/windowAsks.mjs +80 -17
  207. package/lib/worktrees.mjs +159 -9
  208. package/npm-shrinkwrap.json +138 -631
  209. package/package.json +7 -6
  210. package/release.json +211 -129
  211. package/lib/callSessions.mjs +0 -51
  212. package/lib/directLink.mjs +0 -349
  213. package/lib/peopleBoard.mjs +0 -131
  214. package/lib/projects.mjs +0 -2917
  215. package/lib/roomChannels.mjs +0 -667
@@ -0,0 +1,1126 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { spawn } from "node:child_process";
5
+ import { herdrAppDo } from "./herdr.mjs";
6
+ import { callCore } from "./herdrCore.mjs";
7
+ import { historyRoots, paths } from "./paths.mjs";
8
+ import { resumeLine } from "./places.mjs";
9
+ import { sessionFeed, sessionFile } from "./live.mjs";
10
+ import { agentBinary } from "./agentBinaries.mjs";
11
+ import { nameOf } from "./members.mjs";
12
+ import {
13
+ actsOf,
14
+ agentInvocation,
15
+ piSessionFile,
16
+ stepsOf,
17
+ trackRun,
18
+ } from "./runner.mjs";
19
+
20
+ // A thread's turn for Claude Code, Codex, Pi or OpenCode, run where a person who uses that agent in the Herdr app works: in a Herdr
21
+ // tab, the interactive agent they know, on the same session, folder, model and permissions the turn would run with
22
+ // here. The thread gets a space of its own in Herdr, named for it; each agent a tab there, and its next turn goes into
23
+ // that tab while the session still runs in it. The person watches it work, types into it, and can carry on after.
24
+ // Harness follows the turn in the agent's own record of the session (its steps, last words and tokens) and ends it at
25
+ // the agent's own end of turn; Stop interrupts it in Herdr.
26
+ //
27
+ // Only the person's own turns (no review, no restricted run, no other person's ask, no granted secrets): the tab runs in
28
+ // their own shell, with no run token.
29
+
30
+ const READ_MS = 1_000;
31
+ // Reads in a row an agent is up in its tab without having begun, before the thread says it waits on the person.
32
+ const SETTLED_READS = 3;
33
+ // A tab's login shell in the foreground: the agent itself is not running there.
34
+ const SHELLS = new Set([
35
+ "zsh",
36
+ "bash",
37
+ "sh",
38
+ "fish",
39
+ "dash",
40
+ "ksh",
41
+ "tcsh",
42
+ "csh",
43
+ "nu",
44
+ "-zsh",
45
+ "-bash",
46
+ ]);
47
+
48
+ /** What a session's record says from `offset` on: its new lines, and where the next read starts. */
49
+ function readFrom(file, offset) {
50
+ let size;
51
+ try {
52
+ size = fs.statSync(file).size;
53
+ } catch {
54
+ return { rows: [], offset };
55
+ }
56
+ if (size <= offset) return { rows: [], offset };
57
+ const handle = fs.openSync(file, "r");
58
+ const buffer = Buffer.alloc(size - offset);
59
+ fs.readSync(handle, buffer, 0, buffer.length, offset);
60
+ fs.closeSync(handle);
61
+ const text = buffer.toString("utf8");
62
+ // Only whole lines: the last may still be being written.
63
+ const end = text.lastIndexOf("\n");
64
+ if (end < 0) return { rows: [], offset };
65
+ const rows = [];
66
+ for (const line of text.slice(0, end).split("\n"))
67
+ try {
68
+ if (line.startsWith("{")) rows.push(JSON.parse(line));
69
+ } catch {}
70
+ return { rows, offset: offset + Buffer.byteLength(text.slice(0, end + 1)) };
71
+ }
72
+
73
+ /** The words of a message: a string, or its text blocks. */
74
+ const wordsOf = (content) =>
75
+ typeof content === "string"
76
+ ? content
77
+ : (Array.isArray(content) ? content : [])
78
+ .map((block) => (typeof block?.text === "string" ? block.text : ""))
79
+ .join("\n")
80
+ .trim();
81
+
82
+ const realOrSame = (folder) => {
83
+ try {
84
+ return fs.realpathSync(String(folder));
85
+ } catch {
86
+ return String(folder);
87
+ }
88
+ };
89
+ /** A JSONL file's first row, read without the rest. */
90
+ function firstLine(file) {
91
+ try {
92
+ const handle = fs.openSync(file, "r");
93
+ const buffer = Buffer.alloc(64 << 10);
94
+ const read = fs.readSync(handle, buffer, 0, buffer.length, 0);
95
+ fs.closeSync(handle);
96
+ return JSON.parse(buffer.toString("utf8", 0, read).split("\n")[0]);
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ const sizeOf = (file) => {
103
+ try {
104
+ return fs.statSync(file).size;
105
+ } catch {
106
+ return 0;
107
+ }
108
+ };
109
+
110
+ // ── Claude Code ──────────────────────────────────────────────────────────────────────────────────────────────────
111
+ // Its session can be named before it starts (--session-id), so its record is known from the first moment.
112
+
113
+ // Claude Code's flags for a run it prints (-p and its JSON), which an interactive session does not take.
114
+ const PRINT_ONLY = new Set(["-p", "--output-format", "--verbose"]);
115
+
116
+ const claude = {
117
+ namesSession: true,
118
+ // It reports its state to Herdr (OSC 7501), seen in a real Herdr: silence before its first report means it asks.
119
+ reportsStatus: true,
120
+ /** Its command line for this turn as an interactive session, the brief left out (Herdr adds it as the task). */
121
+ argv(run, sessionId) {
122
+ const { command, args } = agentInvocation({ ...run, brief: "" });
123
+ const kept = [];
124
+ for (let i = 0; i < args.length; i++) {
125
+ // -p and --output-format each take the word after them.
126
+ if (PRINT_ONLY.has(args[i])) {
127
+ if (args[i] !== "--verbose") i++;
128
+ continue;
129
+ }
130
+ kept.push(args[i]);
131
+ }
132
+ return [
133
+ command,
134
+ ...kept,
135
+ ...(run.resumeSession ? [] : ["--session-id", sessionId]),
136
+ ];
137
+ },
138
+ /** Its record of a session in a folder: its projects folder, the folder's path made a name. */
139
+ record: (folder, sessionId) =>
140
+ path.join(
141
+ historyRoots("claude-code")[0],
142
+ folder.replace(/[^a-zA-Z0-9]/g, "-"),
143
+ `${sessionId}.jsonl`
144
+ ),
145
+ /**
146
+ * One turn as its record shows it. It starts at the brief typed in; tokens are per message, which Claude Code writes
147
+ * once per block with the same usage, so each message counts once. It records no dollars for an interactive
148
+ * session: they stay missing.
149
+ */
150
+ turn() {
151
+ const messages = new Map();
152
+ let started = false;
153
+ return {
154
+ read(row) {
155
+ if (row.type === "user" && !row.isMeta && !row.toolUseResult) {
156
+ started = true;
157
+ return { asked: wordsOf(row.message?.content) };
158
+ }
159
+ if (!started || row.type !== "assistant" || !row.message) return {};
160
+ if (row.message.id && row.message.usage)
161
+ messages.set(row.message.id, row.message.usage);
162
+ return {
163
+ steps: stepsOf(row),
164
+ acts: actsOf(row),
165
+ end: row.message.stop_reason === "end_turn" ? "done" : null,
166
+ };
167
+ },
168
+ usage() {
169
+ if (!messages.size) return null;
170
+ const usage = {
171
+ input_tokens: 0,
172
+ output_tokens: 0,
173
+ cache_read_tokens: 0,
174
+ cache_write_tokens: 0,
175
+ cost_usd: null,
176
+ };
177
+ for (const u of messages.values()) {
178
+ usage.input_tokens += Number(u.input_tokens) || 0;
179
+ usage.output_tokens += Number(u.output_tokens) || 0;
180
+ usage.cache_read_tokens += Number(u.cache_read_input_tokens) || 0;
181
+ usage.cache_write_tokens +=
182
+ Number(u.cache_creation_input_tokens) || 0;
183
+ }
184
+ return usage;
185
+ },
186
+ };
187
+ },
188
+ };
189
+
190
+ // ── Codex ────────────────────────────────────────────────────────────────────────────────────────────────────────
191
+ // Its session gets its id as it starts: found by the tab it runs in, which its own SessionStart hook reports
192
+ // (HC_TERMINAL_ID). It runs with --no-daemon, as Herdr starts it: a shared Codex server would carry the first tab's
193
+ // identity into every later session.
194
+
195
+ // Codex's words for a run it prints (exec, its JSON, its prompt on stdin), which an interactive session does not take.
196
+ const EXEC_ONLY = new Set(["exec", "--json", "--skip-git-repo-check", "-"]);
197
+
198
+ // What a Codex tool call in its session record ran or changed, for going in circles (circling.mjs): a shell command; in
199
+ // Codex's code mode, the script it ran (run again unchanged, it is the same command); or the files a patch touches.
200
+ const PATCH_FILE = /^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm;
201
+ const SHELL_CALLS = new Set(["shell", "shell_command", "exec_command"]);
202
+ export function codexActs(payload) {
203
+ const name = String(payload.name ?? "");
204
+ let input = payload.input ?? payload.arguments ?? null;
205
+ if (typeof input === "string" && payload.type === "function_call")
206
+ try {
207
+ input = JSON.parse(input);
208
+ } catch {}
209
+ if (payload.type === "local_shell_call") {
210
+ const command = payload.action?.command;
211
+ return Array.isArray(command) && command.length
212
+ ? [{ command: command.join(" ") }]
213
+ : [];
214
+ }
215
+ if (name === "apply_patch") {
216
+ const patch =
217
+ typeof input === "string" ? input : String(input?.input ?? "");
218
+ const files = [...patch.matchAll(PATCH_FILE)].map((found) =>
219
+ found[1].trim()
220
+ );
221
+ return files.length ? [{ files }] : [];
222
+ }
223
+ if (name === "exec" && typeof input === "string" && input.trim())
224
+ return [{ command: input }];
225
+ if (SHELL_CALLS.has(name)) {
226
+ const command = input?.cmd ?? input?.command;
227
+ if (typeof command === "string" && command) return [{ command }];
228
+ if (Array.isArray(command) && command.length)
229
+ return [{ command: command.join(" ") }];
230
+ }
231
+ return [];
232
+ }
233
+
234
+ const codex = {
235
+ namesSession: false,
236
+ // It reports its state to Herdr (OSC 7501), seen in a real Herdr: silence before its first report means it asks.
237
+ reportsStatus: true,
238
+ // A resumed session may go on in its old rollout or in a new one named for it: the newest is read, from its start,
239
+ // and rows from before the turn was asked for are passed over (Codex stamps every row).
240
+ movesRecord: true,
241
+ argv(run) {
242
+ const { command, args } = agentInvocation({ ...run, resumeSession: null });
243
+ const kept = args.filter((arg) => !EXEC_ONLY.has(arg));
244
+ return run.resumeSession
245
+ ? [command, "resume", ...kept, "--no-daemon", run.resumeSession]
246
+ : [command, ...kept, "--no-daemon"];
247
+ },
248
+ /**
249
+ * The session it started in this folder after Herdr was asked for the tab, from its own rollouts (the first line of
250
+ * each names its session, folder and start): for a tab whose hook said nothing, as when Harness's hooks aren't in.
251
+ */
252
+ async ownSession(cwd, since, marker) {
253
+ const root = historyRoots("codex")[0];
254
+ const here = realOrSame(cwd);
255
+ const days = [0, 1].map((back) => {
256
+ const day = new Date(since - back * 86_400_000);
257
+ return path.join(
258
+ root,
259
+ String(day.getFullYear()),
260
+ String(day.getMonth() + 1).padStart(2, "0"),
261
+ String(day.getDate()).padStart(2, "0")
262
+ );
263
+ });
264
+ const found = [];
265
+ for (const dir of days) {
266
+ let names = [];
267
+ try {
268
+ names = fs
269
+ .readdirSync(dir)
270
+ .filter((name) => name.startsWith("rollout-"));
271
+ } catch {
272
+ continue;
273
+ }
274
+ for (const name of names) {
275
+ const file = path.join(dir, name);
276
+ if (fs.statSync(file).mtimeMs < since) continue;
277
+ const meta = firstLine(file)?.payload;
278
+ const started = Date.parse(meta?.timestamp ?? "");
279
+ if (!meta?.id || realOrSame(meta.cwd) !== here || started < since)
280
+ continue;
281
+ // Only the one the tab's words started: another Codex session can begin in the same folder meanwhile.
282
+ if (marker && !fs.readFileSync(file, "utf8").includes(marker)) continue;
283
+ found.push({ id: meta.id, started });
284
+ }
285
+ }
286
+ return found.sort((a, b) => b.started - a.started)[0]?.id ?? null;
287
+ },
288
+ /** Its record of a session: a rollout named for it in a dated folder, newest days first. */
289
+ record(_folder, sessionId) {
290
+ const root = historyRoots("codex")[0];
291
+ const suffix = `-${sessionId}.jsonl`;
292
+ const newest = (dir) => {
293
+ try {
294
+ return fs.readdirSync(dir).sort().reverse();
295
+ } catch {
296
+ return [];
297
+ }
298
+ };
299
+ for (const year of newest(root))
300
+ for (const month of newest(path.join(root, year)))
301
+ for (const day of newest(path.join(root, year, month))) {
302
+ const dir = path.join(root, year, month, day);
303
+ const file = newest(dir).find((name) => name.endsWith(suffix));
304
+ if (file) return path.join(dir, file);
305
+ }
306
+ return null;
307
+ },
308
+ /**
309
+ * One turn as its rollout shows it: from its task_started to its task_complete. Codex keeps its session's running
310
+ * token totals; the turn's are the change over it, its input with the cached tokens taken out, as every other agent
311
+ * reports input.
312
+ */
313
+ turn(since) {
314
+ let started = false,
315
+ before = null,
316
+ after = null,
317
+ lastSaid = "";
318
+ const totals = (u) => ({
319
+ input: Number(u?.input_tokens) || 0,
320
+ cached: Number(u?.cached_input_tokens) || 0,
321
+ output: Number(u?.output_tokens) || 0,
322
+ });
323
+ return {
324
+ read(row) {
325
+ const payload = row.payload ?? {};
326
+ if (row.timestamp && Date.parse(row.timestamp) < since) return {};
327
+ if (row.type === "event_msg" && payload.type === "task_started")
328
+ started = true;
329
+ if (!started) return {};
330
+ if (row.type === "event_msg" && payload.type === "user_message")
331
+ return { asked: String(payload.message ?? "") };
332
+ if (row.type === "event_msg" && payload.type === "token_count") {
333
+ const info = payload.info;
334
+ if (info?.total_token_usage) {
335
+ const total = totals(info.total_token_usage);
336
+ const last = totals(info.last_token_usage);
337
+ before ??= {
338
+ input: total.input - last.input,
339
+ cached: total.cached - last.cached,
340
+ output: total.output - last.output,
341
+ };
342
+ after = total;
343
+ }
344
+ return {};
345
+ }
346
+ // Its last words come again at the end of the turn: said once.
347
+ if (row.type === "event_msg" && payload.type === "task_complete") {
348
+ const words = String(payload.last_agent_message ?? "").trim();
349
+ return {
350
+ end: "done",
351
+ steps:
352
+ words && words !== lastSaid ? [{ kind: "say", text: words }] : [],
353
+ };
354
+ }
355
+ if (row.type === "event_msg" && payload.type === "turn_aborted")
356
+ return { end: "aborted" };
357
+ if (row.type !== "response_item") return {};
358
+ if (payload.type === "message" && payload.role === "assistant") {
359
+ const said = (payload.content ?? [])
360
+ .map((block) => block?.text || "")
361
+ .join("\n")
362
+ .trim();
363
+ if (said) lastSaid = said;
364
+ return { steps: said ? [{ kind: "say", text: said }] : [] };
365
+ }
366
+ if (
367
+ ["function_call", "custom_tool_call", "local_shell_call"].includes(
368
+ payload.type
369
+ )
370
+ )
371
+ return {
372
+ acts: codexActs(payload),
373
+ steps: [
374
+ {
375
+ kind: "do",
376
+ text: `${payload.name ?? "shell"}: ${String(
377
+ payload.arguments ?? payload.input ?? ""
378
+ )
379
+ .replace(/\s+/g, " ")
380
+ .slice(0, 200)}`,
381
+ },
382
+ ],
383
+ };
384
+ return {};
385
+ },
386
+ usage() {
387
+ if (!before || !after) return null;
388
+ const cached = after.cached - before.cached;
389
+ return {
390
+ input_tokens: after.input - before.input - cached,
391
+ output_tokens: after.output - before.output,
392
+ cache_read_tokens: cached,
393
+ cache_write_tokens: 0,
394
+ cost_usd: null,
395
+ };
396
+ },
397
+ };
398
+ },
399
+ };
400
+
401
+ // ── Pi ───────────────────────────────────────────────────────────────────────────────────────────────────────────
402
+ // Its session can be named before it starts (--session-id, created if missing), and it takes its first message after
403
+ // `--`, where Herdr puts the task. It records each message's tokens and its own price.
404
+
405
+ // Pi's words for a run it prints (its JSON mode, -p and the brief), which an interactive session does not take.
406
+ const PI_PRINT_ONLY = new Set(["--mode", "-p", "--session"]);
407
+
408
+ const pi = {
409
+ namesSession: true,
410
+ // It reports its state to Herdr (OSC 7501), seen in a real Herdr: silence before its first report means it asks.
411
+ reportsStatus: true,
412
+ argv(run, sessionId) {
413
+ const { command, args } = agentInvocation({ ...run, brief: "" });
414
+ const kept = [];
415
+ for (let i = 0; i < args.length; i++) {
416
+ // Each takes the word after it: json, the brief, the session's file.
417
+ if (PI_PRINT_ONLY.has(args[i])) {
418
+ i++;
419
+ continue;
420
+ }
421
+ kept.push(args[i]);
422
+ }
423
+ return [command, ...kept, "--session-id", sessionId, "--"];
424
+ },
425
+ record: (_folder, sessionId) => piSessionFile(sessionId),
426
+ /** One turn: from the brief to an answer that asks for no tool; tokens and dollars as Pi recorded each message. */
427
+ turn() {
428
+ const usages = [];
429
+ let started = false;
430
+ return {
431
+ read(row) {
432
+ const message = row.type === "message" ? row.message : null;
433
+ if (!message) return {};
434
+ if (message.role === "user") {
435
+ started = true;
436
+ return { asked: wordsOf(message.content) };
437
+ }
438
+ if (!started || message.role !== "assistant") return {};
439
+ if (message.usage) usages.push(message.usage);
440
+ return {
441
+ steps: stepsOf({ type: "message_end", message }),
442
+ acts: actsOf({ type: "message_end", message }),
443
+ end:
444
+ message.stopReason && message.stopReason !== "toolUse"
445
+ ? message.stopReason === "aborted"
446
+ ? "aborted"
447
+ : "done"
448
+ : null,
449
+ };
450
+ },
451
+ usage() {
452
+ if (!usages.length) return null;
453
+ const priced = usages.some((u) =>
454
+ Number.isFinite(Number(u.cost?.total))
455
+ );
456
+ return {
457
+ input_tokens: usages.reduce(
458
+ (sum, u) => sum + (Number(u.input) || 0),
459
+ 0
460
+ ),
461
+ output_tokens: usages.reduce(
462
+ (sum, u) => sum + (Number(u.output) || 0),
463
+ 0
464
+ ),
465
+ cache_read_tokens: usages.reduce(
466
+ (sum, u) => sum + (Number(u.cacheRead) || 0),
467
+ 0
468
+ ),
469
+ cache_write_tokens: usages.reduce(
470
+ (sum, u) => sum + (Number(u.cacheWrite) || 0),
471
+ 0
472
+ ),
473
+ cost_usd: priced
474
+ ? usages.reduce((sum, u) => sum + (Number(u.cost?.total) || 0), 0)
475
+ : null,
476
+ };
477
+ },
478
+ };
479
+ },
480
+ };
481
+
482
+ // ── OpenCode ─────────────────────────────────────────────────────────────────────────────────────────────────────
483
+ // Its sessions live in its own database, read with `opencode export <id>`; a new session gets its id as it starts,
484
+ // found by the tab its plugin reports. Its TUI takes the first message as --prompt, which Herdr's task fills.
485
+
486
+ /** OpenCode's own record of a session, as `opencode export` prints it; null when it can't be read now. */
487
+ function exportOf(sessionId) {
488
+ return new Promise((resolve) => {
489
+ let command;
490
+ try {
491
+ command = agentBinary("opencode", "opencode");
492
+ } catch {
493
+ return resolve(null);
494
+ }
495
+ if (!command) return resolve(null);
496
+ const child = spawn(command, ["export", String(sessionId)], {
497
+ stdio: ["ignore", "pipe", "ignore"],
498
+ });
499
+ let out = "";
500
+ child.stdout.on("data", (chunk) => (out += chunk));
501
+ child.on("error", () => resolve(null));
502
+ child.on("close", () => {
503
+ try {
504
+ resolve(JSON.parse(out));
505
+ } catch {
506
+ resolve(null);
507
+ }
508
+ });
509
+ });
510
+ }
511
+
512
+ const opencode = {
513
+ namesSession: false,
514
+ /** The session it started in this folder after Herdr was asked for the tab, as `opencode session list` gives them. */
515
+ ownSession: async (cwd, since, marker) => {
516
+ let command;
517
+ try {
518
+ command = agentBinary("opencode", "opencode");
519
+ } catch {
520
+ return null;
521
+ }
522
+ if (!command) return null;
523
+ const listed = await new Promise((resolve) => {
524
+ const child = spawn(
525
+ command,
526
+ ["session", "list", "--format", "json", "-n", "20"],
527
+ {
528
+ // It lists the sessions of the project the folder it runs in belongs to.
529
+ cwd,
530
+ stdio: ["ignore", "pipe", "ignore"],
531
+ }
532
+ );
533
+ let out = "";
534
+ child.stdout.on("data", (chunk) => (out += chunk));
535
+ child.on("error", () => resolve([]));
536
+ child.on("close", () => {
537
+ try {
538
+ resolve(JSON.parse(out));
539
+ } catch {
540
+ resolve([]);
541
+ }
542
+ });
543
+ });
544
+ const here = realOrSame(cwd);
545
+ const candidates = (Array.isArray(listed) ? listed : [])
546
+ .filter(
547
+ (entry) =>
548
+ realOrSame(entry.directory) === here && Number(entry.created) >= since
549
+ )
550
+ .sort((a, b) => b.created - a.created);
551
+ // Only the one the tab's words started: Harness's own check of OpenCode, or another session, can begin in the same
552
+ // folder meanwhile (a readiness check once did).
553
+ for (const entry of candidates) {
554
+ if (!marker) return entry.id;
555
+ const session = await exportOf(entry.id);
556
+ if (JSON.stringify(session?.messages?.slice(0, 2) ?? []).includes(marker))
557
+ return entry.id;
558
+ }
559
+ return null;
560
+ },
561
+ argv(run) {
562
+ const { command, args } = agentInvocation({
563
+ ...run,
564
+ resumeSession: null,
565
+ title: "",
566
+ });
567
+ const kept = [];
568
+ for (let i = 0; i < args.length; i++) {
569
+ if (args[i] === "--") break;
570
+ if (args[i] === "run") continue;
571
+ // Each takes the word after it: json, the title.
572
+ if (args[i] === "--format" || args[i] === "--title") {
573
+ i++;
574
+ continue;
575
+ }
576
+ kept.push(args[i]);
577
+ }
578
+ return [
579
+ command,
580
+ ...kept,
581
+ ...(run.resumeSession ? ["--session", run.resumeSession] : []),
582
+ "--prompt",
583
+ ];
584
+ },
585
+ /** Its record is read whole each time: its messages, oldest first. */
586
+ snapshot: async (sessionId) => {
587
+ const session = await exportOf(sessionId);
588
+ return Array.isArray(session?.messages) ? session.messages : null;
589
+ },
590
+ /** One turn: from the brief to a finished answer that calls no tool; tokens and dollars as OpenCode recorded them. */
591
+ turn(since) {
592
+ const said = new Set();
593
+ const spent = new Map();
594
+ let started = false;
595
+ return {
596
+ read(message) {
597
+ const info = message.info ?? {};
598
+ if ((info.time?.created ?? 0) < since) return {};
599
+ if (info.role === "user") {
600
+ started = true;
601
+ return { asked: wordsOf(message.parts) };
602
+ }
603
+ if (!started || info.role !== "assistant") return {};
604
+ if (info.tokens) spent.set(info.id, info);
605
+ const steps = [];
606
+ const acts = [];
607
+ for (const part of message.parts ?? []) {
608
+ const done =
609
+ (part.type === "text" && part.time?.end && part.text?.trim()) ||
610
+ (part.type === "tool" && part.state?.status === "completed");
611
+ if (!done || said.has(part.id)) continue;
612
+ said.add(part.id);
613
+ acts.push(...actsOf({ type: "message.part.updated", part }));
614
+ steps.push(
615
+ part.type === "text"
616
+ ? { kind: "say", text: part.text.trim() }
617
+ : {
618
+ kind: "do",
619
+ text: `${part.tool}: ${String(part.state?.title ?? "").slice(0, 200)}`,
620
+ }
621
+ );
622
+ }
623
+ const finished =
624
+ info.time?.completed && info.finish && info.finish !== "tool-calls";
625
+ return { steps, acts, end: finished ? "done" : null };
626
+ },
627
+ usage() {
628
+ if (!spent.size) return null;
629
+ const all = [...spent.values()];
630
+ const sum = (pick) =>
631
+ all.reduce((total, info) => total + (Number(pick(info)) || 0), 0);
632
+ return {
633
+ input_tokens: sum((info) => info.tokens.input),
634
+ output_tokens: sum((info) => info.tokens.output),
635
+ cache_read_tokens: sum((info) => info.tokens.cache?.read),
636
+ cache_write_tokens: sum((info) => info.tokens.cache?.write),
637
+ cost_usd: all.some((info) => Number.isFinite(Number(info.cost)))
638
+ ? sum((info) => info.cost)
639
+ : null,
640
+ };
641
+ },
642
+ };
643
+ },
644
+ };
645
+
646
+ // ── The other agents Herdr starts ────────────────────────────────────────────────────────────────────────────────
647
+ // Each started as Herdr starts it from its own agent menu (herdr-app defaults/programs.json `run`), the brief as its
648
+ // first message, which Herdr appends; resumed by the line a person types (places.mjs). Its session is the one its own
649
+ // hook places in the tab; its turn is read through Harness's reader of its session record (live.mjs sessionFeed),
650
+ // whose rows carry no end of turn: the turn ends when Herdr counts it finished. No tokens: none of their records
651
+ // gives them per turn, and a missing figure stays missing. Only without a model picked for the run: a tab runs the
652
+ // agent on its own settings, and a picked model is honoured by running it headless instead.
653
+
654
+ const HERDR_RUN = {
655
+ cursor: ["cursor-agent"],
656
+ copilot: ["copilot"],
657
+ "grok-build": ["grok"],
658
+ antigravity: ["agy"],
659
+ };
660
+ // Not here: DeepSeek Harness, Kilo, Devin and Muse Code. Herdr starts only DeepSeek Harness of them, and it runs no
661
+ // hook that would say which session its tab holds; they run headless as before.
662
+
663
+ const fed = (agent) => ({
664
+ namesSession: false,
665
+ endsByHerdr: true,
666
+ needsOwnSettings: true,
667
+ // Recorded apart from the program its headless runs use, which can be another (Antigravity's ACP server).
668
+ binaryKey: `${agent}@herdr`,
669
+ argv(run) {
670
+ const resume = run.resumeSession
671
+ ? resumeLine(agent, run.resumeSession)
672
+ : null;
673
+ return resume ? resume.split(" ") : [...HERDR_RUN[agent]];
674
+ },
675
+ snapshot: async (sessionId, cwd) => {
676
+ const file = sessionFile(agent, sessionId, cwd);
677
+ return file ? sessionFeed(agent, file, 200) : null;
678
+ },
679
+ /** One turn: from the person's (Harness's) words on, its steps; read from a record that is re-read whole. */
680
+ turn(since) {
681
+ const seen = new Set();
682
+ const keyOf = (item) => `${item.at}|${item.kind}|${item.text}`;
683
+ let started = false;
684
+ return {
685
+ /** What the record holds as the turn starts: not this turn's, timestamps or not (Cursor's rows have none). */
686
+ prime(items) {
687
+ for (const item of items ?? []) seen.add(keyOf(item));
688
+ },
689
+ read(item) {
690
+ const at = item.at ? Date.parse(item.at) : null;
691
+ if (at !== null && at < since) return {};
692
+ const key = keyOf(item);
693
+ if (seen.has(key)) return {};
694
+ seen.add(key);
695
+ if (item.kind === "you") {
696
+ started = true;
697
+ return { asked: item.text };
698
+ }
699
+ if (!started) return {};
700
+ return { steps: [{ kind: item.kind, text: item.text }] };
701
+ },
702
+ usage: () => null,
703
+ };
704
+ },
705
+ });
706
+
707
+ const DIALECTS = {
708
+ "claude-code": claude,
709
+ codex,
710
+ pi,
711
+ opencode,
712
+ ...Object.fromEntries(
713
+ Object.keys(HERDR_RUN).map((agent) => [agent, fed(agent)])
714
+ ),
715
+ };
716
+ /** Whether a run of this agent, on this model pick, can be shown in a Herdr tab. */
717
+ export const herdrTakes = (agent, { model } = {}) =>
718
+ Boolean(DIALECTS[agent]) && !(DIALECTS[agent].needsOwnSettings && model);
719
+ /** Whether an agent's turns can run in a Herdr tab. */
720
+ export const runsInHerdr = (agent) => Boolean(DIALECTS[agent]);
721
+
722
+ /**
723
+ * What the tab is given for the turn: one line a person watching it can read, naming the thread, with the agent's full
724
+ * brief in a file of Harness's own (the owner, November 11: "Short line + file"; the whole brief filled the tab).
725
+ * The file is the person's alone (0600), in Harness's runs folder, kept with the run's log.
726
+ */
727
+ const briefPath = (run) => path.join(paths.runs, `${run.runId}.brief.md`);
728
+ function tabMessage(run) {
729
+ fs.mkdirSync(paths.runs, { recursive: true, mode: 0o700 });
730
+ const file = briefPath(run);
731
+ fs.writeFileSync(file, run.brief, { mode: 0o600 });
732
+ return `Harness · ${run.herdr.threadName}: your brief for this turn is in ${file}. Read it whole, then do what it says.`;
733
+ }
734
+
735
+ /** A tab for the turn: in the thread's space while Herdr still has it, else a new space for the thread. */
736
+ function openTab(run, argv, message) {
737
+ const { herdr } = run;
738
+ const name = nameOf(run.agent);
739
+ const tab = { name, folder: run.cwd, argv, task: message };
740
+ if (herdr.space) {
741
+ const placed = herdrAppDo("tab.new", { ...tab, space: herdr.space });
742
+ if (placed?.terminal) return placed;
743
+ }
744
+ return herdrAppDo("space.new", {
745
+ name: herdr.threadName,
746
+ folder: run.cwd,
747
+ tab: name,
748
+ argv,
749
+ task: message,
750
+ });
751
+ }
752
+
753
+ /**
754
+ * What a terminal's agent last reported (working, blocked, idle, done, error), or null. herdr-core gives it as the
755
+ * report itself, `{ state, app, kind }`, as a real core 0.1.20 does; a bare word is taken as the state too.
756
+ */
757
+ const reportedState = (terminal) =>
758
+ terminal?.status?.state ??
759
+ (typeof terminal?.status === "string" ? terminal.status : null);
760
+
761
+ /**
762
+ * The tab where the thread's session of this agent still runs and waits for the person: the turn goes into it, as a
763
+ * message typed there would, with Herdr's count of the turns it has finished. Null when it has ended, is working or
764
+ * waiting on a question, or Herdr's core is not there.
765
+ */
766
+ async function waitingTab(herdr) {
767
+ const id = herdr.tab?.terminal;
768
+ if (!id || !herdr.core) return null;
769
+ try {
770
+ const got = await callCore(herdr.core, "terminal.get", { terminal: id });
771
+ const state = got?.terminal ?? got;
772
+ if (state?.state !== "live") return null;
773
+ if (["working", "blocked"].includes(reportedState(state))) return null;
774
+ return { id, turn: Number(state.turn) || 0 };
775
+ } catch {
776
+ return null;
777
+ }
778
+ }
779
+
780
+ /**
781
+ * What is new in a session's record since the last call: its file from where the last call stopped, the newest file
782
+ * for an agent whose record can move, or (OpenCode) its whole export, which its turn reader dedupes.
783
+ */
784
+ function recordReader(dialect, cwd) {
785
+ return {
786
+ cwd,
787
+ sessionId: null,
788
+ record: null,
789
+ offset: 0,
790
+ /** Starts at the record's end: what it holds already is not this turn's. */
791
+ from(sessionId) {
792
+ this.sessionId = sessionId;
793
+ this.record = dialect.record?.(cwd, sessionId) ?? null;
794
+ this.offset = this.record ? sizeOf(this.record) : 0;
795
+ },
796
+ async next() {
797
+ if (!this.sessionId) return [];
798
+ if (dialect.snapshot)
799
+ return (await dialect.snapshot(this.sessionId)) ?? [];
800
+ this.record ??= dialect.record(cwd, this.sessionId);
801
+ if (this.record && dialect.movesRecord) {
802
+ const newest = dialect.record(cwd, this.sessionId);
803
+ if (newest && newest !== this.record) {
804
+ this.record = newest;
805
+ this.offset = 0;
806
+ }
807
+ }
808
+ if (!this.record) return [];
809
+ const fresh = readFrom(this.record, this.offset);
810
+ this.offset = fresh.offset;
811
+ return fresh.rows;
812
+ },
813
+ };
814
+ }
815
+
816
+ // After a turn, what the person and the agent say to each other in its tab goes on being read, and the thread is shown
817
+ // it (the owner, November 11: shown, without waking the swarm). Until Harness's next turn there, or the tab goes.
818
+ const FOLLOW_MS = 2_000;
819
+ // Per tab: its stop, and the session it reads.
820
+ const followers = new Map();
821
+ const stopFollowing = (terminal) => followers.get(terminal)?.stop();
822
+ /** A turn on a session takes it back from every tab followed for it: the session may go on in a new tab. */
823
+ const stopFollowingSession = (session) => {
824
+ for (const follower of [...followers.values()])
825
+ if (follower.session === session) follower.stop();
826
+ };
827
+
828
+ function followTab(terminal, { dialect, reader, core, mirror }) {
829
+ // What the record already holds is the turn just finished, not the person's.
830
+ const fresh = () => {
831
+ const next = dialect.turn(Date.now());
832
+ if (next.prime && dialect.snapshot)
833
+ void dialect
834
+ .snapshot(reader.sessionId, reader.cwd)
835
+ .then((items) => next.prime(items));
836
+ return next;
837
+ };
838
+ let turn = fresh(),
839
+ asked = null,
840
+ answer = "",
841
+ timer = null,
842
+ done = false,
843
+ // Herdr's count of the agent's finished turns, for an agent whose record marks no end of turn.
844
+ turnsSeen = null,
845
+ // A turn Herdr counted finished whose answer the record may not show yet: kept until it does.
846
+ ended = false;
847
+ const stop = () => {
848
+ done = true;
849
+ clearTimeout(timer);
850
+ if (followers.get(terminal)?.stop === stop) followers.delete(terminal);
851
+ };
852
+ const exchanged = () => {
853
+ ended = false;
854
+ if (asked || answer) mirror({ asked, answer });
855
+ turn = fresh();
856
+ asked = null;
857
+ answer = "";
858
+ };
859
+ const tick = async () => {
860
+ if (done) return;
861
+ // The tab first: one that has gone says nothing more, though its session may go on elsewhere.
862
+ if (core)
863
+ try {
864
+ const got = await callCore(core, "terminal.get", { terminal });
865
+ const state = got?.terminal ?? got;
866
+ if (state?.state === "finished") return stop();
867
+ const count = Number(state?.turn) || 0;
868
+ const finishedOne =
869
+ turnsSeen !== null &&
870
+ count > turnsSeen &&
871
+ ["done", "idle"].includes(reportedState(state));
872
+ ended ||= finishedOne;
873
+ if (turnsSeen === null || finishedOne) turnsSeen = count;
874
+ } catch (error) {
875
+ if (error.kind === "not_found") return stop();
876
+ }
877
+ for (const row of await reader.next()) {
878
+ if (done) return;
879
+ const read = turn.read(row);
880
+ if (read.asked) asked = read.asked;
881
+ for (const one of read.steps ?? [])
882
+ if (one.kind === "say") answer = one.text;
883
+ if (read.end) exchanged();
884
+ }
885
+ if (dialect.endsByHerdr && ended && answer) exchanged();
886
+ if (!done) timer = setTimeout(() => void tick(), FOLLOW_MS);
887
+ };
888
+ stopFollowing(terminal);
889
+ followers.set(terminal, { stop, session: reader.sessionId });
890
+ timer = setTimeout(() => void tick(), FOLLOW_MS);
891
+ }
892
+
893
+ export function runInHerdr(run, emit, observe, hooks = {}) {
894
+ const dialect = DIALECTS[run.agent];
895
+ const name = nameOf(run.agent);
896
+ const askedAt = Date.now();
897
+ const turn = dialect.turn(askedAt);
898
+ let sessionId =
899
+ run.resumeSession ?? (dialect.namesSession ? randomUUID() : null);
900
+ const reader = recordReader(dialect, run.cwd);
901
+ let terminal = null,
902
+ placedAt = 0,
903
+ timer = null,
904
+ stopped = false,
905
+ finished = false,
906
+ last = "",
907
+ blocked = false,
908
+ begun = false,
909
+ unbegunReads = 0,
910
+ // Herdr's count of the turns the tab's agent has finished, as this turn started (a new tab: none).
911
+ turnsBefore = 0,
912
+ unreadEnds = 0;
913
+ const step = (one) => {
914
+ observe("stdout", `${JSON.stringify({ type: "harness.step", ...one })}\n`);
915
+ emit("progress", one.text.slice(0, 200), { step: one });
916
+ };
917
+ const interrupt = () =>
918
+ terminal &&
919
+ callCore(run.herdr.core, "terminal.interrupt", { terminal }).catch(
920
+ () => {}
921
+ );
922
+ const release = trackRun(run.runId, () => {
923
+ stopped = true;
924
+ void interrupt();
925
+ finish("failed", "Stopped.", "person");
926
+ });
927
+ // `nothingSaid`: the turn ended with nothing written; one that ended to wait says so instead (runWorker.mjs).
928
+ function finish(kind, text, failure, nothingSaid = false) {
929
+ if (finished) return;
930
+ finished = true;
931
+ clearTimeout(timer);
932
+ release();
933
+ emit(kind, text.slice(0, 20_000), {
934
+ usage: turn.usage(),
935
+ ...(failure ? { failure } : {}),
936
+ ...(nothingSaid ? { nothingSaid } : {}),
937
+ });
938
+ if (kind === "done" && terminal && run.herdr.mirror)
939
+ followTab(terminal, {
940
+ dialect,
941
+ reader,
942
+ core: run.herdr.core,
943
+ mirror: run.herdr.mirror,
944
+ });
945
+ }
946
+ /** The session a new tab's agent started, once its own hook has placed it there. */
947
+ const findSession = async () => {
948
+ sessionId =
949
+ run.herdr.sessionIn?.(run.agent, terminal, placedAt) ??
950
+ (await dialect.ownSession?.(run.cwd, placedAt, briefPath(run))) ??
951
+ null;
952
+ if (!sessionId) return;
953
+ // A session started in the tab: its record is read from its start.
954
+ reader.sessionId = sessionId;
955
+ emit("session", sessionId, { cwd: run.cwd });
956
+ run.herdr.onPlaced?.({ terminal, session: sessionId });
957
+ };
958
+ const read = async () => {
959
+ if (finished) return;
960
+ if (!reader.sessionId) await findSession();
961
+ for (const row of await reader.next()) {
962
+ const { asked, steps = [], acts = [], end = null } = turn.read(row);
963
+ // What it ran and changed, for going in circles (circling.mjs).
964
+ for (const act of acts) hooks.acted?.(act);
965
+ // Only what this turn's reader takes as new: a record re-read whole repeats what came before.
966
+ if (asked || steps.length || end) begun = true;
967
+ for (const one of steps) {
968
+ if (one.kind === "say") last = one.text;
969
+ step(one);
970
+ }
971
+ if (end === "done")
972
+ return finish(
973
+ "done",
974
+ last || `${name} finished the turn in Herdr.`,
975
+ null,
976
+ !last
977
+ );
978
+ if (end === "aborted")
979
+ return finish(
980
+ "failed",
981
+ `${name}'s turn was interrupted in Herdr${last ? `: ${last}` : "."}`,
982
+ "exit"
983
+ );
984
+ }
985
+ return watchTab();
986
+ };
987
+ /** What Herdr's core sees of the tab, then the next read. */
988
+ async function watchTab() {
989
+ // What Herdr's core sees of the tab: closed before the turn ended, or the agent waiting on the person there (a
990
+ // permission, a question, its first-run confirmation), which the thread says once each time it starts waiting.
991
+ if (run.herdr.core)
992
+ try {
993
+ const got = await callCore(run.herdr.core, "terminal.get", {
994
+ terminal,
995
+ });
996
+ const state = got?.terminal ?? got;
997
+ if (state?.state === "finished")
998
+ return finish(
999
+ "failed",
1000
+ `The ${name} tab in Herdr closed before the turn ended${last ? `: ${last}` : "."}`,
1001
+ "exit"
1002
+ );
1003
+ const nowBlocked = reportedState(state) === "blocked";
1004
+ if (nowBlocked && !blocked)
1005
+ step({
1006
+ kind: "do",
1007
+ text: `${name} is waiting for you in its Herdr tab (a permission or a question).`,
1008
+ });
1009
+ blocked = nowBlocked;
1010
+ // Up in the tab but not yet begun: an agent asks before its session starts (Claude Code whether to trust a
1011
+ // folder it hasn't opened before) and reports nothing to Herdr while it asks. Settled over a few reads, so an
1012
+ // agent still starting is not taken for one asking.
1013
+ const shell = SHELLS.has(
1014
+ path.basename(String(state?.foreground?.name ?? ""))
1015
+ );
1016
+ const asking =
1017
+ dialect.reportsStatus &&
1018
+ !state?.reported &&
1019
+ !begun &&
1020
+ Boolean(state?.foreground) &&
1021
+ !shell;
1022
+ unbegunReads = asking ? unbegunReads + 1 : 0;
1023
+ // An agent whose record marks no end of turn: done when Herdr counts the turn finished and it has said
1024
+ // something since it began.
1025
+ if (
1026
+ dialect.endsByHerdr &&
1027
+ begun &&
1028
+ last &&
1029
+ Number(state?.turn) > turnsBefore &&
1030
+ ["done", "idle"].includes(reportedState(state))
1031
+ )
1032
+ return finish("done", last);
1033
+ // The agent told Herdr it finished a turn, yet its record holds nothing of it: Claude Code saves none when
1034
+ // the tab inherited another session's marker (Herdr started from inside a Claude Code session). Its answer
1035
+ // is only in the tab; the turn ends saying so rather than waiting for a record that won't come.
1036
+ const endedUnread =
1037
+ !begun &&
1038
+ Number(state?.turn) > turnsBefore &&
1039
+ ["done", "idle"].includes(reportedState(state));
1040
+ unreadEnds = endedUnread ? unreadEnds + 1 : 0;
1041
+ if (unreadEnds === SETTLED_READS)
1042
+ return finish(
1043
+ "failed",
1044
+ `${name} finished in its Herdr tab, but Harness can't read its session record there, so its answer is only in that tab.`,
1045
+ "exit"
1046
+ );
1047
+ if (unbegunReads === SETTLED_READS)
1048
+ step({
1049
+ kind: "do",
1050
+ text: `${name} is waiting for you in its Herdr tab before it starts (it may ask whether to trust this folder).`,
1051
+ });
1052
+ } catch (error) {
1053
+ // Herdr removed the tab's terminal altogether (its tab closed, or `hc rm`): gone as a finished one is.
1054
+ if (error.kind === "not_found")
1055
+ return finish(
1056
+ "failed",
1057
+ `The ${name} tab in Herdr closed before the turn ended${last ? `: ${last}` : "."}`,
1058
+ "exit"
1059
+ );
1060
+ }
1061
+ timer = setTimeout(() => void read(), READ_MS);
1062
+ }
1063
+ emit("accepted");
1064
+ void (async () => {
1065
+ // A resumed session's record already holds its earlier turns: this turn is read from its end.
1066
+ if (sessionId) reader.from(sessionId);
1067
+ if (sessionId && turn.prime)
1068
+ turn.prime(await dialect.snapshot(sessionId, run.cwd));
1069
+ // The tab and the session are Harness's again for this turn: what is said there is this turn's, not a side
1070
+ // conversation, in whichever tab it goes on.
1071
+ if (run.herdr.tab?.terminal) stopFollowing(run.herdr.tab.terminal);
1072
+ if (sessionId) stopFollowingSession(sessionId);
1073
+ const waiting = await waitingTab(run.herdr);
1074
+ const message = tabMessage(run);
1075
+ // Taken before Herdr is asked: the agent's hook can place its new session as soon as the tab exists.
1076
+ placedAt = Date.now();
1077
+ if (waiting) {
1078
+ try {
1079
+ await callCore(run.herdr.core, "terminal.send", {
1080
+ terminal: waiting.id,
1081
+ text: message,
1082
+ });
1083
+ terminal = waiting.id;
1084
+ turnsBefore = waiting.turn;
1085
+ } catch {}
1086
+ }
1087
+ if (!terminal) {
1088
+ // The program confirmed for this agent, as a headless run starts it (agentBinaries.mjs): never what the tab's
1089
+ // login shell would find first on its PATH under the agent's name.
1090
+ const [command, ...args] = dialect.argv(run, sessionId);
1091
+ let program;
1092
+ try {
1093
+ program = agentBinary(dialect.binaryKey ?? run.agent, command);
1094
+ } catch (error) {
1095
+ return finish("failed", error.message, "start");
1096
+ }
1097
+ if (!program)
1098
+ return finish(
1099
+ "failed",
1100
+ `${run.agent} is not installed on this computer.`,
1101
+ "start"
1102
+ );
1103
+ placedAt = Date.now();
1104
+ const placed = openTab(run, [program, ...args], message);
1105
+ if (!placed?.terminal) {
1106
+ release();
1107
+ if (run.fallback && !stopped)
1108
+ return run.fallback("Herdr did not open a tab for the turn.");
1109
+ return finish(
1110
+ "failed",
1111
+ "Herdr did not open a tab for the turn.",
1112
+ "start"
1113
+ );
1114
+ }
1115
+ terminal = placed.terminal;
1116
+ run.herdr.onPlaced?.({
1117
+ space: placed.space ?? run.herdr.space ?? null,
1118
+ terminal,
1119
+ session: sessionId,
1120
+ });
1121
+ }
1122
+ if (sessionId) emit("session", sessionId, { cwd: run.cwd });
1123
+ if (stopped) return void interrupt();
1124
+ void read();
1125
+ })();
1126
+ }