tryharness 0.7.30 → 0.7.32

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.
package/cli.mjs CHANGED
@@ -1231,6 +1231,52 @@ async function goal() {
1231
1231
  }
1232
1232
 
1233
1233
  // The swarm's coordinator: who coordinates, and the record of every round it ran.
1234
+ // When a check-in runs, from its flags: --in 2h, --at 14:30 (or a date), --every 30m, or --daily 09:00 [--days mon-fri].
1235
+ function cadenceFrom() {
1236
+ const minutesOf = (text) => {
1237
+ const found = String(text || "").match(/^(\d+(?:\.\d+)?)\s*(m|h|d)?$/);
1238
+ return found
1239
+ ? Number(found[1]) * { m: 1, h: 60, d: 1440 }[found[2] || "m"]
1240
+ : null;
1241
+ };
1242
+ if (arg("--in")) return { kind: "in", minutes: minutesOf(arg("--in")) };
1243
+ if (arg("--every"))
1244
+ return { kind: "every", minutes: minutesOf(arg("--every")) };
1245
+ if (arg("--at")) {
1246
+ const at = arg("--at");
1247
+ const clock = at.match(/^(\d{1,2}):(\d{2})$/);
1248
+ if (!clock) return { kind: "once", at };
1249
+ // A time of day alone is its next one: today, or tomorrow once today's has passed.
1250
+ const next = new Date();
1251
+ next.setHours(Number(clock[1]), Number(clock[2]), 0, 0);
1252
+ if (next.getTime() <= Date.now()) next.setDate(next.getDate() + 1);
1253
+ return { kind: "once", at: next.toISOString() };
1254
+ }
1255
+ if (arg("--daily")) {
1256
+ const names = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
1257
+ const given = String(arg("--days", "")).toLowerCase();
1258
+ const range = given.match(/^([a-z]{3})-([a-z]{3})$/);
1259
+ const days =
1260
+ given === "weekdays"
1261
+ ? [1, 2, 3, 4, 5]
1262
+ : range
1263
+ ? names
1264
+ .map((_, day) => day)
1265
+ .filter(
1266
+ (day) =>
1267
+ day >= names.indexOf(range[1]) &&
1268
+ day <= names.indexOf(range[2])
1269
+ )
1270
+ : given
1271
+ ? given
1272
+ .split(",")
1273
+ .map((name) => names.indexOf(name.trim().slice(0, 3)))
1274
+ : [];
1275
+ return { kind: "daily", time: arg("--daily"), days };
1276
+ }
1277
+ return null;
1278
+ }
1279
+
1234
1280
  async function swarm() {
1235
1281
  const sub = argv[0] || "rounds";
1236
1282
  if (sub === "coordinator") {
@@ -1277,6 +1323,65 @@ async function swarm() {
1277
1323
  }
1278
1324
  return;
1279
1325
  }
1326
+ // Check-ins: the thread comes back on its own later, once or again and again, waking the agents named or its lead.
1327
+ if (sub === "checkin" && argv[1] === "remove") {
1328
+ if (!argv[2])
1329
+ throw new Error("usage: tryharness swarm checkin remove <id>");
1330
+ const response = await daemonRequest({
1331
+ command: "board.swarm.checkin.remove",
1332
+ agent: "user",
1333
+ checkIn: argv[2],
1334
+ });
1335
+ if (!response.ok) throw new Error(response.error || "it was not removed");
1336
+ console.log("Removed.");
1337
+ return;
1338
+ }
1339
+ if (sub === "checkin") {
1340
+ const usage =
1341
+ 'usage: tryharness swarm checkin <thread> "<what to do>" (--in 2h | --at 14:30 | --every 30m | --daily 09:00 [--days mon-fri]) [--wake codex,claude-code] [--times n] [--until <date>]';
1342
+ if (!argv[1] || !argv[2] || argv[2].startsWith("--"))
1343
+ throw new Error(usage);
1344
+ const response = await daemonRequest({
1345
+ command: "board.swarm.checkin",
1346
+ agent: "user",
1347
+ id: argv[1],
1348
+ what: argv[2],
1349
+ cadence: cadenceFrom(),
1350
+ agents: arg("--wake", "")
1351
+ .split(",")
1352
+ .map((name) => name.trim())
1353
+ .filter(Boolean),
1354
+ maxRuns: arg("--times") === null ? null : Number(arg("--times")),
1355
+ endsAt: arg("--until"),
1356
+ });
1357
+ if (!response.ok) throw new Error(response.error || usage);
1358
+ const set = response.checkIn;
1359
+ console.log(
1360
+ `Check-in set (${set.when}), next at ${new Date(set.nextAt).toLocaleString()}: ${set.what} (${set.id})`
1361
+ );
1362
+ return;
1363
+ }
1364
+ if (sub === "checkins") {
1365
+ const response = await daemonRequest({
1366
+ command: "board.swarm.checkins",
1367
+ agent: "user",
1368
+ ...(argv[1] && !argv[1].startsWith("--") ? { id: argv[1] } : {}),
1369
+ all: has("--all"),
1370
+ });
1371
+ if (!response.ok)
1372
+ throw new Error(response.error || "check-ins unavailable");
1373
+ if (!response.checkIns.length) {
1374
+ console.log(
1375
+ 'No check-ins. Set one: tryharness swarm checkin <thread> "check the render" --in 2h'
1376
+ );
1377
+ return;
1378
+ }
1379
+ for (const entry of response.checkIns)
1380
+ console.log(
1381
+ `${entry.threadId.slice(0, 8)} ${entry.when} · ${entry.by === "user" ? "you set it" : "the lead set it"} · ${entry.state === "on" ? `next ${new Date(entry.nextAt).toLocaleString()}` : `ended: ${entry.endedWhy}`} · ran ${entry.runs} time${entry.runs === 1 ? "" : "s"}${entry.agents.length ? ` · wakes ${entry.agents.join(", ")}` : ""}\n ${entry.what} (${entry.id})`
1382
+ );
1383
+ return;
1384
+ }
1280
1385
  // What a thread may spend of the person's Harness credits: dollars, or off.
1281
1386
  if (sub === "ceiling") {
1282
1387
  if (!argv[1] || argv[2] === undefined)
@@ -1469,6 +1574,74 @@ async function disconnect() {
1469
1574
 
1470
1575
  // How Harness reaches each agent: `agents` walks the whole swarm, `agents setup <agent>` one agent, `agents test <agent>`
1471
1576
  // posts a check and waits for the agent to answer it.
1577
+ // What the swarm learned from the person's words (cli/lib/lessons.mjs): read, change or take out any of it.
1578
+ async function lessons() {
1579
+ const [sub, id] = argv;
1580
+ if (sub === "remove" || sub === "edit") {
1581
+ const text = argv.slice(2).join(" ").trim();
1582
+ if (!id || (sub === "edit" && !text))
1583
+ throw new Error(
1584
+ 'usage: tryharness lessons remove <id> | lessons edit <id> "<the lesson in your words>"'
1585
+ );
1586
+ const response = await daemonRequest({
1587
+ command: `board.swarm.lessons.${sub}`,
1588
+ agent: "user",
1589
+ id,
1590
+ ...(sub === "edit" ? { text } : {}),
1591
+ });
1592
+ if (!response.ok) throw new Error(response.error);
1593
+ console.log(
1594
+ sub === "remove"
1595
+ ? `Taken out: "${response.lesson.text}" No agent is told it from now on.`
1596
+ : `Now in your words: "${response.lesson.text}"`
1597
+ );
1598
+ return;
1599
+ }
1600
+ const replaced = has("--replaced");
1601
+ const response = await daemonRequest({
1602
+ command: "board.swarm.lessons",
1603
+ agent: "user",
1604
+ replaced,
1605
+ });
1606
+ if (!response.ok) throw new Error(response.error);
1607
+ if (!response.lessons.length) {
1608
+ console.log(
1609
+ replaced
1610
+ ? "No lesson has been replaced yet."
1611
+ : "Your swarm has learned nothing from you yet. It learns from what you write in its threads."
1612
+ );
1613
+ return;
1614
+ }
1615
+ const about = (lesson) =>
1616
+ lesson.about === "agent"
1617
+ ? `about ${lesson.agent}`
1618
+ : lesson.about === "work"
1619
+ ? "about the work"
1620
+ : "about you";
1621
+ console.log(
1622
+ replaced
1623
+ ? `Replaced by a later lesson (${response.lessons.length}):`
1624
+ : `What your swarm has learned from you (${response.lessons.length}):`
1625
+ );
1626
+ for (const lesson of response.lessons) {
1627
+ const where =
1628
+ lesson.scope === "this_folder" ? `in ${lesson.folder}` : "everywhere";
1629
+ console.log(
1630
+ ` ${lesson.id.slice(0, 8)} ${about(lesson)}, ${where}: ${lesson.text}`
1631
+ );
1632
+ if (replaced && !lesson.replaced_by)
1633
+ console.log(" taken back by you, with nothing in its place");
1634
+ if (lesson.from)
1635
+ console.log(
1636
+ ` you said "${lesson.from.quote}"${lesson.from.thread ? ` in "${lesson.from.thread}"` : ""}${lesson.evidence.length > 1 ? `, ${lesson.evidence.length} times` : ""}`
1637
+ );
1638
+ }
1639
+ if (!replaced)
1640
+ console.log(
1641
+ '\nTake one out: tryharness lessons remove <id>. Put one in your words: tryharness lessons edit <id> "<text>".'
1642
+ );
1643
+ }
1644
+
1472
1645
  async function agents() {
1473
1646
  const config = readJson(paths.config, {});
1474
1647
  const [sub, agent] = argv;
@@ -1777,7 +1950,7 @@ async function t3() {
1777
1950
 
1778
1951
  function help() {
1779
1952
  console.log(
1780
- `tryharness ${VERSION}\n\nCommands:\n tryharness set up everything and start the daemon\n tryharness desktop open the Harness desktop app (setup opens it too; --no-desktop skips it)\n tryharness status show daemon, bridge, agent, and index health\n tryharness doctor diagnose the complete connection\n tryharness local [learn] the relay's local models, where they run, what is indexed and the last learning\n tryharness local on|off search over your Desktop, Documents and Downloads by what is in the files (on by default)\n tryharness local add|remove <folder> another folder to search the same way\n tryharness watch [add <name> --run <command> [--every 5m] [--field f | --age f | --count text] [--above n] [--below n] | start <id> | remove <id>]\n watches the relay checks and says out loud only when they are off\n tryharness sync [--agent] rescan local coding history in the background\n tryharness task <id> --follow\n follow a delegated agent run in this terminal\n tryharness board [--all] list open work on the machine's task board\n tryharness board post --for <agent> --objective <text> [--file <brief.md>]\n tryharness board show <id>\n tryharness board post --for codex --objective <text> --run --workspace <dir>\n the daemon runs it and reports back on the task\n tryharness board run <id> authorize a run an agent asked for\n tryharness board release <id>\n tryharness board agents when each agent last read the board\n tryharness board --watch follow the board in this terminal\n tryharness notify on|off desktop notifications for what waits on you\n tryharness board send <task> <message> send a held reply to another person's agent\n tryharness board snippet [<id> share|keep] code an agent elsewhere asked to see; nothing leaves until you share it\n tryharness board auto <task> on|off auto-send replies on that thread\n tryharness board end <task> --outcome <text>\n tryharness board context <task> <query> search everything written about a task\n tryharness goal set --objective <text> [--team a,b] [--workspace <dir>] a goal your agents work together in one room\n tryharness goal [list | show <id> | stop <id> | resume <id>]\n tryharness room <goal> | room post <goal> <text> [--ask agent,agent]\n tryharness swarm rounds [<thread>] what the coordinator saw, chose and cost each round\n tryharness swarm health [<thread>] who decided each day's rounds: Harness, a backup, or no one\n tryharness swarm ceiling <thread> <dollars|off> what a thread may spend of your Harness credits\n tryharness swarm coordinator [harness|local] who coordinates your threads\n tryharness connect <handle/agent> --about <text> ask another person's agent to work an issue with yours, sealed to their computer\n tryharness peers the keys of other people's computers this one has worked with, to compare\n tryharness agents how Harness wakes each of your agents, and set up the rest\n tryharness agents setup <agent> | agents test <agent>\n tryharness agents cards what each of your agents is told about the others\n tryharness agents note <agent> <text> [--clear] your own note on an agent's card, told to every other agent\n tryharness agents models [<agent>] [--refresh] the models each coding agent lists and the one it runs on\n tryharness agents model <agent> <model> [--effort <level>] | auto | default the model it runs on; auto lets Harness pick per run\n tryharness agents routing "<text>" [--clear] how Auto picks models for your swarm\n tryharness mcp grok-bot print the MCP snippet that puts Grok Bot on the board\n tryharness link connect the browser you use Harness in to this computer, end to end (--print shows the link)\n tryharness phone pair show a QR code that pairs your phone with this computer\n tryharness phone list | revoke <id>\n tryharness t3 approve Harness in T3 Code once, so your messages go into its threads (t3 status | t3 forget)\n tryharness logs [--follow]\n tryharness disconnect\n`
1953
+ `tryharness ${VERSION}\n\nCommands:\n tryharness set up everything and start the daemon\n tryharness desktop open the Harness desktop app (setup opens it too; --no-desktop skips it)\n tryharness status show daemon, bridge, agent, and index health\n tryharness doctor diagnose the complete connection\n tryharness local [learn] the relay's local models, where they run, what is indexed and the last learning\n tryharness local on|off search over your Desktop, Documents and Downloads by what is in the files (on by default)\n tryharness local add|remove <folder> another folder to search the same way\n tryharness watch [add <name> --run <command> [--every 5m] [--field f | --age f | --count text] [--above n] [--below n] | start <id> | remove <id>]\n watches the relay checks and says out loud only when they are off\n tryharness sync [--agent] rescan local coding history in the background\n tryharness task <id> --follow\n follow a delegated agent run in this terminal\n tryharness board [--all] list open work on the machine's task board\n tryharness board post --for <agent> --objective <text> [--file <brief.md>]\n tryharness board show <id>\n tryharness board post --for codex --objective <text> --run --workspace <dir>\n the daemon runs it and reports back on the task\n tryharness board run <id> authorize a run an agent asked for\n tryharness board release <id>\n tryharness board agents when each agent last read the board\n tryharness board --watch follow the board in this terminal\n tryharness notify on|off desktop notifications for what waits on you\n tryharness board send <task> <message> send a held reply to another person's agent\n tryharness board snippet [<id> share|keep] code an agent elsewhere asked to see; nothing leaves until you share it\n tryharness board auto <task> on|off auto-send replies on that thread\n tryharness board end <task> --outcome <text>\n tryharness board context <task> <query> search everything written about a task\n tryharness goal set --objective <text> [--team a,b] [--workspace <dir>] a goal your agents work together in one room\n tryharness goal [list | show <id> | stop <id> | resume <id>]\n tryharness room <goal> | room post <goal> <text> [--ask agent,agent]\n tryharness swarm rounds [<thread>] what the coordinator saw, chose and cost each round\n tryharness swarm health [<thread>] who decided each day's rounds: Harness, a backup, or no one\n tryharness swarm ceiling <thread> <dollars|off> what a thread may spend of your Harness credits\n tryharness swarm checkin <thread> "<what>" (--in 2h | --at 14:30 | --every 30m | --daily 09:00 [--days mon-fri]) [--wake codex] [--times n] [--until <date>]\n the thread comes back on its own then, waking those agents or its lead\n tryharness swarm checkins [<thread>] [--all] | swarm checkin remove <id>\n tryharness swarm coordinator [harness|local] who coordinates your threads\n tryharness connect <handle/agent> --about <text> ask another person's agent to work an issue with yours, sealed to their computer\n tryharness peers the keys of other people's computers this one has worked with, to compare\n tryharness agents how Harness wakes each of your agents, and set up the rest\n tryharness agents setup <agent> | agents test <agent>\n tryharness agents cards what each of your agents is told about the others\n tryharness agents note <agent> <text> [--clear] your own note on an agent's card, told to every other agent\n tryharness lessons [--replaced] | lessons remove <id> | lessons edit <id> "<text>"\n what your swarm learned from your words, to read, change or take out\n tryharness agents models [<agent>] [--refresh] the models each coding agent lists and the one it runs on\n tryharness agents model <agent> <model> [--effort <level>] | auto | default the model it runs on; auto lets Harness pick per run\n tryharness agents routing "<text>" [--clear] how Auto picks models for your swarm\n tryharness mcp grok-bot print the MCP snippet that puts Grok Bot on the board\n tryharness link connect the browser you use Harness in to this computer, end to end (--print shows the link)\n tryharness phone pair show a QR code that pairs your phone with this computer\n tryharness phone list | revoke <id>\n tryharness t3 approve Harness in T3 Code once, so your messages go into its threads (t3 status | t3 forget)\n tryharness logs [--follow]\n tryharness disconnect\n`
1781
1954
  );
1782
1955
  }
1783
1956
 
@@ -1802,6 +1975,7 @@ try {
1802
1975
  else if (command === "notify") await notify();
1803
1976
  else if (command === "phone") await phone();
1804
1977
  else if (command === "agents") await agents();
1978
+ else if (command === "lessons") await lessons();
1805
1979
  else if (command === "link") await link();
1806
1980
  else if (command === "t3") await t3();
1807
1981
  else if (command === "peers") await peers();
package/lib/activity.mjs CHANGED
@@ -4,6 +4,7 @@ import { execFile } from "node:child_process";
4
4
  import { listJsonl, readJson } from "./files.mjs";
5
5
  import { historyRoots } from "./paths.mjs";
6
6
  import { PS } from "./nudge.mjs";
7
+ import { runningPids } from "./runner.mjs";
7
8
 
8
9
  // Is anything on this machine doing agent work right now? Board runs and queued runs come from
9
10
  // the daemon. Interactive Claude Code, Codex and pi sessions are read from their live processes
@@ -18,13 +19,24 @@ export const QUIET_MS = 5 * 60_000;
18
19
  // Measured 2026-10-10 with ps: an idle server with a file watcher reads 0.0-0.1 %, a working process 99.9-100 %.
19
20
  export const CPU_BUSY = 5;
20
21
 
21
- const AGENT_NAMES = { claude: "claude-code", codex: "codex", pi: "pi" };
22
+ // OpenCode is named so its process and the app hosting it are never paused; its transcripts are not read here.
23
+ const AGENT_NAMES = {
24
+ claude: "claude-code",
25
+ codex: "codex",
26
+ pi: "pi",
27
+ opencode: "opencode",
28
+ };
22
29
  const RUNTIMES = new Set(["node", "bun", "deno"]);
23
30
  // Claude Code runs every tool command in a shell; its other children (MCP servers, caffeinate) are not work.
24
31
  const SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh"]);
25
32
  // Started by Codex or pi during a turn without being a command it ran. A shell may exec the command itself, so any other child counts.
26
33
  const HELPERS = new Set(["caffeinate"]);
27
34
  const TAIL_BYTES = 256 << 10;
35
+ // How far back a turn is looked for when the tail holds no row of one, its newest rows all being huge (a tool result,
36
+ // a request). Measured 2026-10-16 on the owner's transcripts (Claude Code for a week, Codex for two): at the 2,435
37
+ // moments in an open turn when the tail held none, the newest row of the turn began at most 2.3 MB (Claude Code) and
38
+ // 4.5 MB (Codex, a single item) from the end.
39
+ const FAR_TAIL_BYTES = 8 << 20;
28
40
 
29
41
  const base = (token) => path.basename(String(token || "")).replace(/^-/, "");
30
42
 
@@ -68,16 +80,30 @@ const textOf = (content) =>
68
80
  ? content.map((part) => part?.text || "").join("")
69
81
  : "";
70
82
 
71
- /** Whether a transcript's last turn is still open, and when it started, from its newest rows. */
83
+ /**
84
+ * Whether a transcript's last turn is still open, and when it started, from its newest rows.
85
+ * A finished turn's end is its newest row. Rows from inside a turn newer than any end are a turn
86
+ * still open: its prompt lies further back than the rows read (a long turn), or it was started by
87
+ * something other than a typed prompt (another agent's message, a queued command).
88
+ */
72
89
  export function turnOf(agent, rows) {
90
+ let inTurn = false;
91
+ let oldest = null;
92
+ const passed = (row) => {
93
+ inTurn = true;
94
+ oldest = stamp(row.timestamp) ?? oldest;
95
+ };
96
+ const ended = () =>
97
+ inTurn ? { open: true, startedAt: oldest } : { open: false };
73
98
  for (let index = rows.length - 1; index >= 0; index -= 1) {
74
99
  const row = rows[index];
75
100
  if (agent === "codex") {
76
101
  const kind = row.type === "event_msg" ? row.payload?.type : null;
77
102
  if (kind === "task_started")
78
103
  return { open: true, startedAt: stamp(row.timestamp) };
79
- if (kind === "task_complete" || kind === "turn_aborted")
80
- return { open: false };
104
+ if (kind === "task_complete" || kind === "turn_aborted") return ended();
105
+ // Codex writes settings events after a turn ends; only the model's items are inside one.
106
+ if (row.type === "response_item") passed(row);
81
107
  } else if (agent === "pi") {
82
108
  const message = row.type === "message" ? row.message : null;
83
109
  if (!message) continue;
@@ -87,42 +113,58 @@ export function turnOf(agent, rows) {
87
113
  startedAt: stamp(row.timestamp ?? message.timestamp),
88
114
  };
89
115
  if (message.role === "assistant" && message.stopReason !== "toolUse")
90
- return { open: false };
116
+ return ended();
117
+ passed(row);
91
118
  } else {
92
119
  if (row.isMeta || (row.type !== "user" && row.type !== "assistant"))
93
120
  continue;
121
+ // A compaction's summary is written as a user row, but nobody asked anything.
122
+ if (row.isCompactSummary) continue;
94
123
  const content = row.message?.content;
95
124
  if (row.type === "assistant") {
96
- if (row.message?.stop_reason === "end_turn") return { open: false };
125
+ const stop = row.message?.stop_reason;
126
+ // Claude Code retries a refused answer itself: in the owner's transcripts (2026-10-16), each of the 4 refusals
127
+ // that was not its own error row was followed by more of the same turn.
128
+ const retried = stop === "refusal" && !row.isApiErrorMessage;
129
+ // Any other answer that calls no tool ends the turn: end_turn, max_tokens, or Claude Code's own error row
130
+ // (stop_sequence) when the API cannot be reached.
131
+ if (stop && stop !== "tool_use" && !retried) return ended();
132
+ passed(row);
97
133
  continue;
98
134
  }
99
135
  if (
100
136
  Array.isArray(content) &&
101
137
  content.some((part) => part?.type === "tool_result")
102
- )
138
+ ) {
139
+ passed(row);
103
140
  continue;
141
+ }
104
142
  const text = textOf(content);
105
- if (text.startsWith("[Request interrupted by user"))
106
- return { open: false };
143
+ if (text.startsWith("[Request interrupted by user")) return ended();
107
144
  if (text.startsWith("<local-command") || text.startsWith("<command-"))
108
145
  continue;
109
146
  return { open: true, startedAt: stamp(row.timestamp) };
110
147
  }
111
148
  }
112
- return { open: false };
149
+ if (inTurn) return { open: true, startedAt: oldest };
150
+ // Not one row of a turn among these: none has started, or the rows that tell lie further back.
151
+ return { open: false, unknown: true };
113
152
  }
114
153
 
115
- function tailRows(file) {
154
+ /** The rows in a transcript's last `bytes`, and whether those were the whole file. */
155
+ function tailRows(file, bytes) {
116
156
  let fd;
117
157
  try {
118
158
  fd = fs.openSync(file, "r");
119
159
  const size = fs.fstatSync(fd).size;
120
- const length = Math.min(size, TAIL_BYTES);
160
+ const length = Math.min(size, bytes);
121
161
  const buffer = Buffer.alloc(length);
122
162
  fs.readSync(fd, buffer, 0, length, size - length);
123
163
  const lines = buffer.toString("utf8").split("\n");
124
- if (length < size) lines.shift();
125
- return lines.flatMap((line) => {
164
+ const whole = length === size;
165
+ // The first line is cut off unless the read starts at the file's beginning.
166
+ if (!whole) lines.shift();
167
+ const rows = lines.flatMap((line) => {
126
168
  try {
127
169
  const row = JSON.parse(line);
128
170
  return row && typeof row === "object" ? [row] : [];
@@ -130,13 +172,22 @@ function tailRows(file) {
130
172
  return [];
131
173
  }
132
174
  });
175
+ return { rows, whole };
133
176
  } catch {
134
- return [];
177
+ return { rows: [], whole: true };
135
178
  } finally {
136
179
  if (fd !== undefined) fs.closeSync(fd);
137
180
  }
138
181
  }
139
182
 
183
+ /** Whether a transcript's last turn is open, read from its tail, or from further back when the tail cannot tell. */
184
+ function readTurn(agent, file) {
185
+ const near = tailRows(file, TAIL_BYTES);
186
+ const turn = turnOf(agent, near.rows);
187
+ if (!turn.unknown || near.whole) return turn;
188
+ return turnOf(agent, tailRows(file, FAR_TAIL_BYTES).rows);
189
+ }
190
+
140
191
  const stat = (file) => {
141
192
  try {
142
193
  return { file, mtime: fs.statSync(file).mtimeMs };
@@ -145,6 +196,20 @@ const stat = (file) => {
145
196
  }
146
197
  };
147
198
 
199
+ /**
200
+ * A recorded Claude Code session's transcript and its subagents'. A subagent writes its own transcript under the
201
+ * session's folder, and one run in the background works on after the session's own turn has ended. Measured 2026-10-16
202
+ * on the owner's 14 sessions with subagents: 42% of subagent rows were written while the session's transcript alone
203
+ * read finished or quiet for 5 minutes. Subagent transcripts older than the process are an earlier run's.
204
+ */
205
+ function recordedTranscripts(folder, sessionId, startedAt) {
206
+ const own = stat(path.join(folder, `${sessionId}.jsonl`));
207
+ const subagents = listJsonl(path.join(folder, sessionId, "subagents")).filter(
208
+ (item) => item.mtime >= startedAt
209
+ );
210
+ return [own, ...subagents].filter(Boolean);
211
+ }
212
+
148
213
  const exec = (file, args) =>
149
214
  new Promise((resolve) => {
150
215
  execFile(
@@ -186,21 +251,12 @@ async function workingDirectories(pids) {
186
251
  return found;
187
252
  }
188
253
 
189
- /**
190
- * Judges the machine from what was read. `processes` are ps rows, `sessions` are transcripts
191
- * ({ agent, file, mtime, turn, owners: pids of the live agent processes it may belong to }).
192
- */
193
- export function judgeActivity({
194
- processes,
195
- sessions,
196
- runs = [],
197
- queued = 0,
198
- now = Date.now(),
199
- }) {
254
+ /** From ps rows, a lookup of every process under a pid: its children, theirs, and so on. */
255
+ function descendantsIn(processes) {
200
256
  const children = new Map();
201
257
  for (const row of processes)
202
258
  children.set(row.ppid, [...(children.get(row.ppid) || []), row]);
203
- const descendants = (pid) => {
259
+ return (pid) => {
204
260
  const found = [];
205
261
  const pending = [...(children.get(pid) || [])];
206
262
  while (pending.length) {
@@ -210,6 +266,20 @@ export function judgeActivity({
210
266
  }
211
267
  return found;
212
268
  };
269
+ }
270
+
271
+ /**
272
+ * Judges the machine from what was read. `processes` are ps rows, `sessions` are transcripts
273
+ * ({ agent, file, mtime, turn, owners: pids of the live agent processes it may belong to }).
274
+ */
275
+ export function judgeActivity({
276
+ processes,
277
+ sessions,
278
+ runs = [],
279
+ queued = 0,
280
+ now = Date.now(),
281
+ }) {
282
+ const descendants = descendantsIn(processes);
213
283
  const reasons = runs.map((run) => ({
214
284
  kind: "run",
215
285
  agent: run.agent,
@@ -310,17 +380,16 @@ export async function machineActivity({
310
380
  const cwd = record?.cwd || cwds.get(row.pid);
311
381
  if (!cwd) continue;
312
382
  const folder = path.join(root, cwd.replace(/[^a-zA-Z0-9]/g, "-"));
383
+ // Matched by folder instead, the listing walks into the subagents' folders too.
313
384
  const items = record?.sessionId
314
- ? [stat(path.join(folder, `${record.sessionId}.jsonl`))].filter(
315
- Boolean
316
- )
385
+ ? recordedTranscripts(folder, record.sessionId, row.startedAt)
317
386
  : listJsonl(folder).filter((item) => item.mtime >= row.startedAt);
318
387
  for (const item of items)
319
388
  sessions.push({
320
389
  agent,
321
390
  file: item.file,
322
391
  mtime: item.mtime,
323
- turn: turnOf(agent, tailRows(item.file)),
392
+ turn: readTurn(agent, item.file),
324
393
  owners: [row.pid],
325
394
  });
326
395
  }
@@ -331,18 +400,26 @@ export async function machineActivity({
331
400
  agent,
332
401
  file: item.file,
333
402
  mtime: item.mtime,
334
- turn: turnOf(agent, tailRows(item.file)),
403
+ turn: readTurn(agent, item.file),
335
404
  owners: owners.map((row) => row.pid),
336
405
  });
337
406
  }
338
407
  }
339
408
  }
340
409
  }
341
- // Every agent process, whether or not it is working: the desktop app never pauses the app hosting one.
410
+ // Every agent process and every run of the daemon's, whether or not it is working, with everything they started: the
411
+ // desktop app never pauses an app with one of them in it, so neither the app hosting an agent nor an app an agent
412
+ // launched (a browser it drives, an app under test) is paused.
413
+ const descendants = descendantsIn(processes);
414
+ const roots = [
415
+ ...processes.filter((row) => agentOf(row.command)).map((row) => row.pid),
416
+ ...runningPids(),
417
+ ];
418
+ const kept = new Set(
419
+ roots.flatMap((pid) => [pid, ...descendants(pid).map((row) => row.pid)])
420
+ );
342
421
  return {
343
422
  ...judgeActivity({ processes, sessions, runs, queued, now }),
344
- agentPids: processes
345
- .filter((row) => agentOf(row.command))
346
- .map((row) => row.pid),
423
+ agentPids: [...kept],
347
424
  };
348
425
  }
package/lib/asks.mjs CHANGED
@@ -10,6 +10,11 @@ import { nameOf } from "./members.mjs";
10
10
  //
11
11
  // Agents on Harness's server (Bankr, Quotient, Muse) keep their tasks there and take asks side by side. A send that may
12
12
  // have reached Harness is looked up by its id before it goes again, so a retry never makes a second task.
13
+ //
14
+ // An ask for an agent whose earlier ask is running as a turn that takes words mid-turn (Harness on its server) goes into
15
+ // that turn instead of waiting for it: the turn's answer answers both. One the turn ended without reading waits as any
16
+ // other, and goes to the agent as its own task (October 16, the content factory: an ask that waited behind Harness's turn
17
+ // went to Harness after that turn had already answered it).
13
18
 
14
19
  const OPEN_RUN = ["open", "claimed", "running", "needs_input"];
15
20
  // Sends lost on the way to Harness before the ask is given up and said as failed.
@@ -23,6 +28,9 @@ export function createAsks({
23
28
  onServer,
24
29
  earlierWaits,
25
30
  say,
31
+ // The task whose running turn takes the agent's words in this thread, else null; and putting an ask into it.
32
+ turnOf = () => null,
33
+ steer = async () => false,
26
34
  }) {
27
35
  const read = (key) => {
28
36
  try {
@@ -155,6 +163,31 @@ export function createAsks({
155
163
  }
156
164
  };
157
165
 
166
+ // Into the agent's running turn: said in the thread once the turn has it; asked as its own task if the turn cannot take it.
167
+ const steerInto = (thread, ask, taskId) => {
168
+ sending.add(ask.id);
169
+ change(thread.id, ask.id, { steered: taskId });
170
+ void steer(taskId, ask)
171
+ .catch(() => false)
172
+ .then((taken) => {
173
+ sending.delete(ask.id);
174
+ if (taken)
175
+ return say(
176
+ thread,
177
+ `${nameOf(ask.agent)} has ${whose(ask, false)} and reads it at its next step.`
178
+ );
179
+ change(thread.id, ask.id, { steered: null, unsteered: true });
180
+ pump(thread.id, ask.agent);
181
+ });
182
+ };
183
+ // Whether a kept ask is in the agent's running turn still. One whose turn ended unread is kept as any other.
184
+ const inTurn = (thread, ask) => {
185
+ if (!ask.steered) return false;
186
+ if (turnOf(thread.id, ask.agent) === ask.steered) return true;
187
+ change(thread.id, ask.id, { steered: null, unsteered: true });
188
+ return false;
189
+ };
190
+
158
191
  // Sends what can go now of the asks kept for one agent in a thread, oldest first, and says why the rest wait. Returns why
159
192
  // `fresh` could not be asked, when it failed here.
160
193
  const pump = (threadId, agent, fresh = null) => {
@@ -173,7 +206,18 @@ export function createAsks({
173
206
  if (ask.id === fresh) refused = told;
174
207
  continue;
175
208
  }
209
+ if (inTurn(thread, ask)) {
210
+ ahead = true;
211
+ continue;
212
+ }
176
213
  const why = waitOf(thread, ask, ahead);
214
+ const turn =
215
+ why === "turn" && !ask.unsteered ? turnOf(threadId, agent) : null;
216
+ if (turn) {
217
+ ahead = true;
218
+ steerInto(thread, ask, turn);
219
+ continue;
220
+ }
177
221
  if (why) {
178
222
  ahead = true;
179
223
  said(thread, ask, why);
@@ -210,6 +254,8 @@ export function createAsks({
210
254
  }
211
255
  const waiting = kept(threadId).find((each) => each.id === ask.id);
212
256
  const thread = store.getTask(threadId);
257
+ if (!refused && waiting?.steered)
258
+ return `${nameOf(agent)} is working in this thread now: your ask goes into its current turn, or to it next if that turn ends first.`;
213
259
  return (
214
260
  refused ??
215
261
  (waiting?.told && thread
@@ -239,6 +285,18 @@ export function createAsks({
239
285
  for (const thread of store.goals())
240
286
  for (const agent of agentsWaiting(thread.id)) pump(thread.id, agent);
241
287
  },
288
+ // The agent's turn that took asks ended: those it read are answered with it, and their askers are returned to hear
289
+ // its answer; the rest wait as any other ask. Call before the turn's task is reported, so none goes again.
290
+ turnEnded(threadId, taskId, read) {
291
+ const answered = kept(threadId).filter(
292
+ (each) => each.steered === taskId && read.includes(each.id)
293
+ );
294
+ for (const each of answered) forget(threadId, each.id);
295
+ for (const each of kept(threadId))
296
+ if (each.steered === taskId)
297
+ change(threadId, each.id, { steered: null, unsteered: true });
298
+ return [...new Set(answered.map((each) => each.asker))];
299
+ },
242
300
  // The person stopped the thread: what waited stops with it.
243
301
  stopped(threadId) {
244
302
  keep(threadId, []);