tryharness 0.7.37 → 0.7.38

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/lib/activity.mjs CHANGED
@@ -181,7 +181,7 @@ function tailRows(file, bytes) {
181
181
  }
182
182
 
183
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) {
184
+ export function readTurn(agent, file) {
185
185
  const near = tailRows(file, TAIL_BYTES);
186
186
  const turn = turnOf(agent, near.rows);
187
187
  if (!turn.unknown || near.whole) return turn;
package/lib/store.mjs CHANGED
@@ -1568,7 +1568,7 @@ export function openStore(file) {
1568
1568
  threadRuns(goalId) {
1569
1569
  return execute(
1570
1570
  "all",
1571
- `select id, kind, objective, target_agent, claimed_by, status, holder, result, session_id, run_workspace, run_authorized_at, usage, run_model, created_at, updated_at, reported_at
1571
+ `select id, kind, objective, origin_agent, target_agent, claimed_by, status, holder, result, session_id, run_workspace, run_authorized_at, usage, run_model, created_at, updated_at, reported_at
1572
1572
  from board_tasks where parent_id = ? and kind in ('wake', 'task') order by created_at asc`,
1573
1573
  goalId
1574
1574
  ).map((row) => ({
@@ -0,0 +1,332 @@
1
+ // The subagents an agent's own session spawned during a run, read from where each agent keeps them, so a thread's
2
+ // canvas can hang them under the agent that started them. Claude Code writes each one's transcript and a .meta.json
3
+ // beside its session; Codex writes each one as its own rollout naming the parent thread; OpenCode keeps each one as a
4
+ // child session in its database. Pi has no subagents of its own. What a finished subagent did never changes, so it is
5
+ // read once.
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { spawnSync } from "node:child_process";
10
+ import { readJson } from "./files.mjs";
11
+ import { historyRoots } from "./paths.mjs";
12
+ import { QUIET_MS, readTurn } from "./activity.mjs";
13
+ import { sessionFeed } from "./live.mjs";
14
+ import { stepsOf } from "./runner.mjs";
15
+
16
+ const PLAIN_ID = /^[A-Za-z0-9._:-]{1,128}$/;
17
+ const MAX = 12;
18
+ const STEPS = 4;
19
+ const STEP_TEXT = 160;
20
+ // A rollout's first line names its parent thread; the base instructions that follow can run far past this.
21
+ const HEAD_BYTES = 16 << 10;
22
+ const SQLITE = "/usr/bin/sqlite3";
23
+
24
+ const iso = (ms) =>
25
+ Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : null;
26
+ const stamp = (value) =>
27
+ (typeof value === "number" ? value : Date.parse(value || "")) || null;
28
+ const words = (text) =>
29
+ String(text || "")
30
+ .replace(/\s+/g, " ")
31
+ .trim();
32
+ const clip = (text, limit) => {
33
+ const said = words(text);
34
+ return said.length > limit ? `${said.slice(0, limit - 1)}…` : said;
35
+ };
36
+ // Codex passes messages between its agents encrypted: nothing a person can read.
37
+ const sealed = (text) => /gAAAA[\w-]{24,}/.test(text);
38
+ const lastSteps = (items) =>
39
+ items
40
+ .filter(
41
+ (item) =>
42
+ (item.kind === "say" || item.kind === "do") && !sealed(item.text)
43
+ )
44
+ .slice(-STEPS)
45
+ .map((item) => ({ kind: item.kind, text: clip(item.text, STEP_TEXT) }));
46
+
47
+ function head(file, bytes = HEAD_BYTES) {
48
+ let fd;
49
+ try {
50
+ fd = fs.openSync(file, "r");
51
+ const buffer = Buffer.alloc(bytes);
52
+ const read = fs.readSync(fd, buffer, 0, bytes, 0);
53
+ return buffer.subarray(0, read).toString("utf8");
54
+ } catch {
55
+ return "";
56
+ } finally {
57
+ if (fd !== undefined) fs.closeSync(fd);
58
+ }
59
+ }
60
+ const mtimeOf = (file) => {
61
+ try {
62
+ return fs.statSync(file).mtimeMs;
63
+ } catch {
64
+ return null;
65
+ }
66
+ };
67
+
68
+ /** OpenCode's database, where it keeps every session and its children. */
69
+ const opencodeDb = () =>
70
+ path.join(
71
+ process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share"),
72
+ "opencode",
73
+ "opencode.db"
74
+ );
75
+ function opencodeRows(sql) {
76
+ const db = opencodeDb();
77
+ if (!fs.existsSync(db) || !fs.existsSync(SQLITE)) return [];
78
+ const found = spawnSync(
79
+ SQLITE,
80
+ ["-readonly", "-json", "-cmd", ".timeout 500", db, sql],
81
+ { encoding: "utf8", timeout: 3_000 }
82
+ );
83
+ if (found.status !== 0) return [];
84
+ try {
85
+ return JSON.parse(found.stdout || "[]");
86
+ } catch {
87
+ return [];
88
+ }
89
+ }
90
+ const quote = (value) => `'${String(value).replace(/'/g, "''")}'`;
91
+
92
+ /**
93
+ * The subagents of one run: `{ id, parent, type, task, startedAt, endedAt, live, depth, steps }`, oldest first.
94
+ * `parent` is the subagent that spawned it, or null for the run's own session. `now` is for tests.
95
+ */
96
+ export function createSubagents({ now = () => Date.now() } = {}) {
97
+ // Finished subagents by file (or OpenCode session), and Claude Code's folder for each session.
98
+ const done = new Map();
99
+ const claudeFolders = new Map();
100
+ const rolloutHeads = new Map();
101
+
102
+ // A subagent counts as working while its own record says its turn is open and it wrote something lately.
103
+ const settled = (key, value) => {
104
+ if (!value.live) done.set(key, value);
105
+ return value;
106
+ };
107
+
108
+ function claudeFolder(sessionId) {
109
+ if (claudeFolders.has(sessionId)) return claudeFolders.get(sessionId);
110
+ for (const root of historyRoots("claude-code")) {
111
+ let projects = [];
112
+ try {
113
+ projects = fs.readdirSync(root);
114
+ } catch {
115
+ continue;
116
+ }
117
+ for (const project of projects) {
118
+ const folder = path.join(root, project, sessionId, "subagents");
119
+ if (fs.existsSync(folder)) {
120
+ claudeFolders.set(sessionId, folder);
121
+ return folder;
122
+ }
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ function claude(sessionId) {
129
+ const folder = claudeFolder(sessionId);
130
+ if (!folder) return [];
131
+ let names = [];
132
+ try {
133
+ names = fs.readdirSync(folder).filter((name) => name.endsWith(".jsonl"));
134
+ } catch {
135
+ return [];
136
+ }
137
+ return names.map((name) => {
138
+ const file = path.join(folder, name);
139
+ if (done.has(file)) return done.get(file);
140
+ const meta = readJson(file.replace(/\.jsonl$/, ".meta.json"), {}) ?? {};
141
+ let first = null;
142
+ try {
143
+ first = JSON.parse(head(file).split("\n")[0]);
144
+ } catch {}
145
+ const mtime = mtimeOf(file);
146
+ const open =
147
+ meta.finished !== true &&
148
+ readTurn("claude-code", file).open &&
149
+ now() - (mtime ?? 0) < QUIET_MS;
150
+ const prompt = first?.message?.content;
151
+ return settled(file, {
152
+ id: name.replace(/^agent-|\.jsonl$/g, ""),
153
+ parent: null,
154
+ type: meta.agentType || "subagent",
155
+ task: clip(
156
+ meta.description ||
157
+ (typeof prompt === "string" ? prompt : prompt?.[0]?.text),
158
+ 120
159
+ ),
160
+ startedAt: iso(stamp(first?.timestamp) ?? mtime),
161
+ endedAt: open ? null : iso(mtime),
162
+ live: open,
163
+ depth: Number(meta.spawnDepth) || 1,
164
+ steps: lastSteps(sessionFeed("claude-code", file, 40)),
165
+ });
166
+ });
167
+ }
168
+
169
+ // Codex's rollouts by day folder (YYYY/MM/DD), from the run's start to its end.
170
+ function codexFiles(from, to) {
171
+ const files = [];
172
+ const day = new Date(from);
173
+ day.setHours(0, 0, 0, 0);
174
+ for (; day.getTime() <= to; day.setDate(day.getDate() + 1)) {
175
+ const parts = [
176
+ String(day.getFullYear()),
177
+ String(day.getMonth() + 1).padStart(2, "0"),
178
+ String(day.getDate()).padStart(2, "0"),
179
+ ];
180
+ for (const root of historyRoots("codex")) {
181
+ const folder = path.join(root, ...parts);
182
+ let names = [];
183
+ try {
184
+ names = fs.readdirSync(folder);
185
+ } catch {
186
+ continue;
187
+ }
188
+ for (const name of names)
189
+ if (name.startsWith("rollout-") && name.endsWith(".jsonl"))
190
+ files.push(path.join(folder, name));
191
+ }
192
+ }
193
+ return files;
194
+ }
195
+ function rolloutHead(file) {
196
+ if (rolloutHeads.has(file)) return rolloutHeads.get(file);
197
+ const line = head(file).split("\n")[0];
198
+ const parent = /"parent_thread_id":"([^"]+)"/.exec(line)?.[1] ?? null;
199
+ const found = parent
200
+ ? {
201
+ id: /"payload":\{[^]*?"id":"([^"]+)"/.exec(line)?.[1] ?? null,
202
+ parent,
203
+ nickname: /"agent_nickname":"([^"]+)"/.exec(line)?.[1] ?? null,
204
+ role: /"agent_role":"([^"]+)"/.exec(line)?.[1] ?? null,
205
+ path: /"agent_path":"([^"]+)"/.exec(line)?.[1] ?? null,
206
+ kind: /"subagent":"([^"]+)"/.exec(line)?.[1] ?? null,
207
+ depth: Number(/"depth":(\d+)/.exec(line)?.[1]) || 1,
208
+ at: stamp(/"timestamp":"([^"]+)"/.exec(line)?.[1]),
209
+ }
210
+ : null;
211
+ // Only a file's first line is read, and that never changes once written.
212
+ if (line.endsWith("}")) rolloutHeads.set(file, found);
213
+ return found;
214
+ }
215
+ function codex(sessionId, startedAt, endedAt) {
216
+ const from = (stamp(startedAt) ?? now()) - 60_000;
217
+ const to = stamp(endedAt) ?? now();
218
+ const children = codexFiles(from, to)
219
+ .filter((file) => (mtimeOf(file) ?? 0) >= from)
220
+ .map((file) => ({ file, head: rolloutHead(file) }))
221
+ .filter((item) => item.head?.id);
222
+ // The run's own children, then theirs.
223
+ const found = [];
224
+ const parents = new Set([sessionId]);
225
+ for (let depth = 0; depth < 4; depth++) {
226
+ const next = children.filter(
227
+ (item) => parents.has(item.head.parent) && !found.includes(item)
228
+ );
229
+ if (!next.length) break;
230
+ found.push(...next);
231
+ for (const item of next) parents.add(item.head.id);
232
+ }
233
+ return found.map(({ file, head: meta }) => {
234
+ if (done.has(file)) return done.get(file);
235
+ const mtime = mtimeOf(file);
236
+ const open =
237
+ readTurn("codex", file).open && now() - (mtime ?? 0) < QUIET_MS;
238
+ const task = meta.path
239
+ ? meta.path.split("/").at(-1).replace(/_/g, " ")
240
+ : meta.kind;
241
+ return settled(file, {
242
+ id: meta.id,
243
+ parent: meta.parent === sessionId ? null : meta.parent,
244
+ type: meta.role || meta.kind || "agent",
245
+ task: clip(
246
+ meta.nickname && task
247
+ ? `${meta.nickname}: ${task}`
248
+ : task || meta.nickname || "",
249
+ 120
250
+ ),
251
+ startedAt: iso(meta.at ?? mtime),
252
+ endedAt: open ? null : iso(mtime),
253
+ live: open,
254
+ depth: meta.depth,
255
+ steps: lastSteps(sessionFeed("codex", file, 40)),
256
+ });
257
+ });
258
+ }
259
+
260
+ function opencode(sessionId) {
261
+ if (!PLAIN_ID.test(sessionId)) return [];
262
+ const rows = opencodeRows(
263
+ `with recursive kids(id, parent_id, title, agent, time_created, time_updated, depth) as (
264
+ select id, parent_id, title, agent, time_created, time_updated, 1 from session where parent_id = ${quote(sessionId)}
265
+ union all select s.id, s.parent_id, s.title, s.agent, s.time_created, s.time_updated, k.depth + 1
266
+ from session s join kids k on s.parent_id = k.id where k.depth < 4)
267
+ select k.*, (select data from message m where m.session_id = k.id order by m.time_created desc limit 1) as last
268
+ from kids k order by time_created limit ${MAX * 2}`
269
+ );
270
+ return rows.map((row) => {
271
+ if (done.has(row.id)) return done.get(row.id);
272
+ let last = null;
273
+ try {
274
+ last = JSON.parse(row.last || "null");
275
+ } catch {}
276
+ const open =
277
+ !(last?.role === "assistant" && last?.time?.completed) &&
278
+ now() - Number(row.time_updated) < QUIET_MS;
279
+ const parts = opencodeRows(
280
+ `select data from part where session_id = ${quote(row.id)} order by time_created desc limit 30`
281
+ );
282
+ const steps = parts.reverse().flatMap((part) => {
283
+ try {
284
+ const data = JSON.parse(part.data);
285
+ return stepsOf({ type: data.type, part: data });
286
+ } catch {
287
+ return [];
288
+ }
289
+ });
290
+ return settled(row.id, {
291
+ id: row.id,
292
+ parent: row.parent_id === sessionId ? null : row.parent_id,
293
+ type: row.agent || "subagent",
294
+ task: clip(
295
+ String(row.title || "").replace(/\s*\(@[\w-]+ subagent\)\s*$/, ""),
296
+ 120
297
+ ),
298
+ startedAt: iso(Number(row.time_created)),
299
+ endedAt: open ? null : iso(Number(row.time_updated)),
300
+ live: open,
301
+ depth: Number(row.depth) || 1,
302
+ steps: lastSteps(steps),
303
+ });
304
+ });
305
+ }
306
+
307
+ return {
308
+ /** The subagents a run's session spawned while the run went on, oldest first. */
309
+ of({ agent, sessionId, startedAt, endedAt }) {
310
+ if (!sessionId || !PLAIN_ID.test(String(sessionId))) return [];
311
+ const id = String(sessionId);
312
+ const found =
313
+ agent === "claude-code"
314
+ ? claude(id)
315
+ : agent === "codex"
316
+ ? codex(id, startedAt, endedAt)
317
+ : agent === "opencode"
318
+ ? opencode(id)
319
+ : [];
320
+ // A resumed session keeps the subagents of its earlier runs: only the ones started during this run.
321
+ const from = (stamp(startedAt) ?? 0) - 60_000;
322
+ const to = stamp(endedAt) ?? Infinity;
323
+ return found
324
+ .filter((sub) => {
325
+ const at = stamp(sub.startedAt) ?? 0;
326
+ return at >= from && at <= to;
327
+ })
328
+ .sort((a, b) => (stamp(a.startedAt) ?? 0) - (stamp(b.startedAt) ?? 0))
329
+ .slice(-MAX);
330
+ },
331
+ };
332
+ }
package/lib/swarm.mjs CHANGED
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { readRunSteps } from "./runner.mjs";
6
+ import { createSubagents } from "./subagents.mjs";
6
7
  import { nameOf, resolveMember } from "./members.mjs";
7
8
  import { setNote, swarmBlock, swarmCards, swarmDigest } from "./cards.mjs";
8
9
  import {
@@ -106,6 +107,8 @@ export function createSwarm({
106
107
  // The person's post read for their reaction and for lessons (reactions.mjs, lessons.mjs), and what was learned.
107
108
  heardPerson = () => {},
108
109
  lessons = null,
110
+ // The subagents each run's own session spawned (subagents.mjs), for the thread's canvas.
111
+ subagents = createSubagents(),
109
112
  }) {
110
113
  // What the person let a thread spend of their Harness credits, in dollars, or null for no limit of its own.
111
114
  const ceilingOf = (threadId) => {
@@ -351,10 +354,30 @@ export function createSwarm({
351
354
  : [],
352
355
  });
353
356
 
357
+ // Who handed a run its work and what they asked: a task names its poster; a wake, whoever woke it (threadRuns.mjs),
358
+ // read back from the words it was woken with for wakes from before the asker was kept.
359
+ const askOf = (run) => {
360
+ if (run.kind !== "wake")
361
+ return { askedBy: run.origin_agent, ask: run.objective };
362
+ let why = null;
363
+ try {
364
+ why = JSON.parse(store.meta(`wake-reason:${run.id}`) || "null");
365
+ } catch {}
366
+ const said = /^(\S+) (?:mentioned|asked) you: ([^]*)$/.exec(
367
+ why?.reason ?? ""
368
+ );
369
+ return {
370
+ askedBy: why?.asker ?? said?.[1] ?? run.origin_agent,
371
+ ask: said?.[2] ?? why?.reason ?? run.objective,
372
+ };
373
+ };
374
+
354
375
  const read = (thread, hostedCaller = false) => {
355
376
  const runs = store.threadRuns(thread.id).map((run) => ({
356
377
  id: run.id,
357
378
  agent: run.claimed_by || run.target_agent,
379
+ ...askOf(run),
380
+ answer: run.result ? run.result.slice(0, 600) : null,
358
381
  kind: run.kind,
359
382
  status: run.status,
360
383
  awaitingStart: awaitingStart(run),
@@ -368,6 +391,15 @@ export function createSwarm({
368
391
  ...step,
369
392
  text: step.text.slice(0, SAY_LIMIT),
370
393
  })),
394
+ // A hosted caller is told nothing about this computer's sessions.
395
+ subagents: hostedCaller
396
+ ? []
397
+ : subagents.of({
398
+ agent: run.claimed_by || run.target_agent,
399
+ sessionId: run.session_id,
400
+ startedAt: run.created_at,
401
+ endedAt: run.reported_at,
402
+ }),
371
403
  }));
372
404
  return {
373
405
  ok: true,
@@ -322,7 +322,10 @@ export function createThreadRuns({
322
322
  kind: "wake",
323
323
  });
324
324
  if (t3) store.meta(`t3-run:${wake.id}`, "1");
325
- store.meta(`wake-reason:${wake.id}`, JSON.stringify({ reason, review }));
325
+ store.meta(
326
+ `wake-reason:${wake.id}`,
327
+ JSON.stringify({ reason, review, asker })
328
+ );
326
329
  if (pick) setRunPick(store, wake.id, pick, asker);
327
330
  // A review runs with the agent's own read-only switch (runner.mjs); only Claude Code and Codex have one.
328
331
  if (review) store.meta(`review:${wake.id}`, "1");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tryharness",
3
- "version": "0.7.37",
3
+ "version": "0.7.38",
4
4
  "description": "Harness Relay: the daemon that turns the agents on this machine into your personal swarm. Memory, history, and work handed between any of them.",
5
5
  "bin": {
6
6
  "tryharness": "cli.mjs"