tryharness 0.7.31 → 0.7.33

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/README.md CHANGED
@@ -22,6 +22,54 @@ paged when Harness displays them.
22
22
  The command is idempotent. Run it again after installing another agent or to repair its
23
23
  configuration.
24
24
 
25
+ ## Daemon ownership
26
+
27
+ `lib/daemon.mjs` assembles features in `startDaemon` and connects the local control
28
+ socket and authenticated bridge. Features own their state and command handling:
29
+
30
+ | Module | Owns |
31
+ | --- | --- |
32
+ | `sessionIndex.mjs` | History scans, the OpenCode helper and targeted refreshes |
33
+ | `sessionControl.mjs` | Live sessions, app locations, Open plans and session messages |
34
+ | `runAuthority.mjs` | Prompt identity, workspace coverage and standing permission |
35
+ | `actorRoster.mjs` | Available agents, setup health and cards |
36
+ | `taskRuns.mjs` | Run records, output paging, restart recovery and execution identity |
37
+ | `models.mjs` | Agent catalogs, saved/run choices, agent settings and complete model/effort selections |
38
+ | `harnessModel.mjs` | Harness's own pick: a provider (Harness credits or a kept key or endpoint), a model of Harness's catalog there, and what a thread task carries for it |
39
+ | `roomPage.mjs` | One page of a thread's room, newest first, as every agent reads it (`read_room`, Harness's `thread_posts`) |
40
+ | `bridge.mjs` | Authenticated socket, requests, feature negotiation, heartbeat, reconnects and outage history |
41
+ | `threadRuns.mjs` | Durable pending wakes, fresh briefs, T3 continuity and worktree settlement |
42
+ | `runWorker.mjs` | Authorized board execution, workspace slots, holds, requeues and receipts |
43
+ | `boardFiles.mjs` | File storage, disclosure, redaction and file commands; `boardFileCommands.mjs` is its private command adapter |
44
+ | `goalCommands.mjs`, `taskCommands.mjs` | Goal/room operations and task lifecycle operations |
45
+ | `boardThreads.mjs`, `boardWatches.mjs`, `boardTools.mjs` | Relay-thread messages, watch/digest commands and local tool commands |
46
+ | `boardAccess.mjs` | Plain hosted-call policy and metadata-only responses |
47
+
48
+ `createModelRouter` returns the complete run selection, including model, effort,
49
+ provenance and any fallback explanation. It owns the precedence of a run's explicit
50
+ pick, the person's saved choice or Auto, and the agent's own settings. Missing
51
+ settings stay null. The worker records and executes the result without resolving
52
+ defaults again; `runner.mjs` and `t3.mjs` translate it for their execution formats.
53
+ Cards and model listings read agent settings through the same model module.
54
+
55
+ `boardCommands.mjs` establishes the common request context and dispatches to the
56
+ feature owner. Dispatch grants no authority: each feature still checks identity,
57
+ permissions, versions and sharing before acting. `daemon.mjs` wires thread execution
58
+ and transport through their owners; feature handlers do not own socket retry state.
59
+
60
+ Pending thread calls use the existing local metadata store. After restart, an already
61
+ queued wake keeps its later handoff in the fresh brief. An interrupted run remains
62
+ unknown. A later call for that interrupted agent becomes a held wake and the thread
63
+ asks for Start, so recovery preserves the request without replaying unknown effects.
64
+
65
+ `lib/boardProtocol.json` owns command names, routing, protocol/inbox versions,
66
+ metadata fields and the separate grants for each caller surface. Node consumers use
67
+ `boardProtocol.mjs`; web consumers use `src/schemas/boardProtocol.ts`; the Rust
68
+ desktop adapter embeds the JSON at build time. A surface uses only its own list:
69
+ adding a command to the catalog does not enable it for any caller. Browser and
70
+ hosted Harness grants deliberately differ. When adding a command, update its owner
71
+ and only the intended surface grants, then exercise that caller's runtime path.
72
+
25
73
  ## Operations
26
74
 
27
75
  ```sh
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
@@ -31,6 +32,11 @@ const SHELLS = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh"]);
31
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.
32
33
  const HELPERS = new Set(["caffeinate"]);
33
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;
34
40
 
35
41
  const base = (token) => path.basename(String(token || "")).replace(/^-/, "");
36
42
 
@@ -112,9 +118,17 @@ export function turnOf(agent, rows) {
112
118
  } else {
113
119
  if (row.isMeta || (row.type !== "user" && row.type !== "assistant"))
114
120
  continue;
121
+ // A compaction's summary is written as a user row, but nobody asked anything.
122
+ if (row.isCompactSummary) continue;
115
123
  const content = row.message?.content;
116
124
  if (row.type === "assistant") {
117
- if (row.message?.stop_reason === "end_turn") return ended();
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();
118
132
  passed(row);
119
133
  continue;
120
134
  }
@@ -132,20 +146,25 @@ export function turnOf(agent, rows) {
132
146
  return { open: true, startedAt: stamp(row.timestamp) };
133
147
  }
134
148
  }
135
- return ended();
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 };
136
152
  }
137
153
 
138
- function tailRows(file) {
154
+ /** The rows in a transcript's last `bytes`, and whether those were the whole file. */
155
+ function tailRows(file, bytes) {
139
156
  let fd;
140
157
  try {
141
158
  fd = fs.openSync(file, "r");
142
159
  const size = fs.fstatSync(fd).size;
143
- const length = Math.min(size, TAIL_BYTES);
160
+ const length = Math.min(size, bytes);
144
161
  const buffer = Buffer.alloc(length);
145
162
  fs.readSync(fd, buffer, 0, length, size - length);
146
163
  const lines = buffer.toString("utf8").split("\n");
147
- if (length < size) lines.shift();
148
- 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) => {
149
168
  try {
150
169
  const row = JSON.parse(line);
151
170
  return row && typeof row === "object" ? [row] : [];
@@ -153,13 +172,22 @@ function tailRows(file) {
153
172
  return [];
154
173
  }
155
174
  });
175
+ return { rows, whole };
156
176
  } catch {
157
- return [];
177
+ return { rows: [], whole: true };
158
178
  } finally {
159
179
  if (fd !== undefined) fs.closeSync(fd);
160
180
  }
161
181
  }
162
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
+
163
191
  const stat = (file) => {
164
192
  try {
165
193
  return { file, mtime: fs.statSync(file).mtimeMs };
@@ -168,6 +196,20 @@ const stat = (file) => {
168
196
  }
169
197
  };
170
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
+
171
213
  const exec = (file, args) =>
172
214
  new Promise((resolve) => {
173
215
  execFile(
@@ -209,21 +251,12 @@ async function workingDirectories(pids) {
209
251
  return found;
210
252
  }
211
253
 
212
- /**
213
- * Judges the machine from what was read. `processes` are ps rows, `sessions` are transcripts
214
- * ({ agent, file, mtime, turn, owners: pids of the live agent processes it may belong to }).
215
- */
216
- export function judgeActivity({
217
- processes,
218
- sessions,
219
- runs = [],
220
- queued = 0,
221
- now = Date.now(),
222
- }) {
254
+ /** From ps rows, a lookup of every process under a pid: its children, theirs, and so on. */
255
+ function descendantsIn(processes) {
223
256
  const children = new Map();
224
257
  for (const row of processes)
225
258
  children.set(row.ppid, [...(children.get(row.ppid) || []), row]);
226
- const descendants = (pid) => {
259
+ return (pid) => {
227
260
  const found = [];
228
261
  const pending = [...(children.get(pid) || [])];
229
262
  while (pending.length) {
@@ -233,6 +266,20 @@ export function judgeActivity({
233
266
  }
234
267
  return found;
235
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);
236
283
  const reasons = runs.map((run) => ({
237
284
  kind: "run",
238
285
  agent: run.agent,
@@ -333,17 +380,16 @@ export async function machineActivity({
333
380
  const cwd = record?.cwd || cwds.get(row.pid);
334
381
  if (!cwd) continue;
335
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.
336
384
  const items = record?.sessionId
337
- ? [stat(path.join(folder, `${record.sessionId}.jsonl`))].filter(
338
- Boolean
339
- )
385
+ ? recordedTranscripts(folder, record.sessionId, row.startedAt)
340
386
  : listJsonl(folder).filter((item) => item.mtime >= row.startedAt);
341
387
  for (const item of items)
342
388
  sessions.push({
343
389
  agent,
344
390
  file: item.file,
345
391
  mtime: item.mtime,
346
- turn: turnOf(agent, tailRows(item.file)),
392
+ turn: readTurn(agent, item.file),
347
393
  owners: [row.pid],
348
394
  });
349
395
  }
@@ -354,18 +400,26 @@ export async function machineActivity({
354
400
  agent,
355
401
  file: item.file,
356
402
  mtime: item.mtime,
357
- turn: turnOf(agent, tailRows(item.file)),
403
+ turn: readTurn(agent, item.file),
358
404
  owners: owners.map((row) => row.pid),
359
405
  });
360
406
  }
361
407
  }
362
408
  }
363
409
  }
364
- // 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
+ );
365
421
  return {
366
422
  ...judgeActivity({ processes, sessions, runs, queued, now }),
367
- agentPids: processes
368
- .filter((row) => agentOf(row.command))
369
- .map((row) => row.pid),
423
+ agentPids: [...kept],
370
424
  };
371
425
  }
@@ -0,0 +1,106 @@
1
+ import { CLOUD_HOMED, TARGETS as ROOM_AGENTS } from "./members.mjs";
2
+ import { localWakes, LOCAL_WAKE_AGENTS } from "./wakes.mjs";
3
+ import { swarmCards } from "./cards.mjs";
4
+ import { nameOf } from "./members.mjs";
5
+
6
+ export function createActorRoster({
7
+ store,
8
+ installedAgents,
9
+ authority,
10
+ localWaker,
11
+ connected,
12
+ }) {
13
+ const RUNNERS = authority.RUNNERS;
14
+ const CLOUD_AGENTS = new Set(CLOUD_HOMED);
15
+ // What each agent that runs elsewhere needs before it picks up work by itself (Grok Bot, Muse), as Harness last said
16
+ // (`agent_setup`, sent on connect and on every change); OpenClaw and Hermes are set up and woken here.
17
+ let cloudSetup = new Map();
18
+ const SETUP_STATES = ["not_set_up", "waiting", "answering", "not_answering"];
19
+ /** { state, how, detail } for an agent that must be set up before it picks up work, null for one Harness starts. */
20
+ const setupOf = (agent) => {
21
+ if (cloudSetup.has(agent)) return cloudSetup.get(agent);
22
+ if (!LOCAL_WAKE_AGENTS.includes(agent)) return null;
23
+ const saved = localWakes()[agent];
24
+ if (!saved)
25
+ return { state: "not_set_up", how: "local-webhook", detail: null };
26
+ const health = localWaker.status()[agent];
27
+ if (health && !health.answering)
28
+ return {
29
+ state: "not_answering",
30
+ how: "local-webhook",
31
+ detail: health.lastFailure,
32
+ };
33
+ const seenAt = store
34
+ .agentsSeen()
35
+ .find((row) => row.agent === agent)?.last_seen_at;
36
+ return {
37
+ state:
38
+ seenAt && Date.parse(seenAt) >= Date.parse(saved.savedAt || 0)
39
+ ? "answering"
40
+ : "waiting",
41
+ how: "local-webhook",
42
+ detail: null,
43
+ };
44
+ };
45
+ // Said to whoever hands work to an agent that will not pick it up by itself (the server says the same for its own).
46
+ const setupNote = (agent) => {
47
+ const setup = setupOf(agent);
48
+ if (setup?.state === "not_set_up")
49
+ return `${nameOf(agent)} is not set up to pick up work by itself yet, so this waits until the person sets it up in Harness.`;
50
+ if (setup?.state === "not_answering")
51
+ return `${nameOf(agent)} is not answering right now, so this waits until it does.`;
52
+ return null;
53
+ };
54
+ /** The agents this person can ask right now: coding agents installed here, the server's while connected, any agent that has used the board, and those Harness says can be set up. */
55
+ const available = () => {
56
+ const seen = new Set(store.agentsSeen().map((row) => row.agent));
57
+ const woken = localWakes();
58
+ return ROOM_AGENTS.filter(
59
+ (agent) =>
60
+ agent === "harness" ||
61
+ (RUNNERS.has(agent)
62
+ ? installedAgents.includes(agent)
63
+ : CLOUD_AGENTS.has(agent)
64
+ ? connected()
65
+ : seen.has(agent) || Boolean(woken[agent]) || cloudSetup.has(agent))
66
+ );
67
+ };
68
+ // Each agent's card (cards.mjs) as every other agent is told it, its setup included; `lessons`: what the person said
69
+ // about each, for a reader on this computer or Harness only.
70
+ const cardsFor = (ids, { lessons = true } = {}) =>
71
+ swarmCards(
72
+ store,
73
+ ids.map((id) => ({ id, setup: setupOf(id) })),
74
+ { lessons }
75
+ );
76
+ // The person's words from other threads (lessons.mjs) stay with the agents on this computer and Harness.
77
+ const readsLessonsHere = (agent) => RUNNERS.has(agent) || agent === "harness";
78
+
79
+ const updateCloudSetup = (entries) => {
80
+ cloudSetup = new Map(
81
+ entries
82
+ .filter(
83
+ (entry) =>
84
+ entry &&
85
+ typeof entry.agent === "string" &&
86
+ SETUP_STATES.includes(entry.state)
87
+ )
88
+ .map((entry) => [
89
+ entry.agent,
90
+ {
91
+ state: entry.state,
92
+ how: typeof entry.how === "string" ? entry.how : null,
93
+ detail: typeof entry.detail === "string" ? entry.detail : null,
94
+ },
95
+ ])
96
+ );
97
+ };
98
+ return {
99
+ setupOf,
100
+ setupNote,
101
+ available,
102
+ cardsFor,
103
+ readsLessonsHere,
104
+ updateCloudSetup,
105
+ };
106
+ }