tryharness 0.7.53 → 0.7.54

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 (69) hide show
  1. package/README.md +10 -5
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +115 -36
  5. package/lib/adapters.mjs +157 -222
  6. package/lib/agentRuntimes.mjs +26 -16
  7. package/lib/agentSignIn.mjs +226 -0
  8. package/lib/audit.mjs +643 -0
  9. package/lib/backupSetup.mjs +141 -0
  10. package/lib/boardAccess.mjs +8 -1
  11. package/lib/boardBackup.mjs +283 -0
  12. package/lib/boardMirror.mjs +71 -7
  13. package/lib/boardProtocol.json +59 -2
  14. package/lib/boardWaits.mjs +102 -0
  15. package/lib/book.mjs +659 -0
  16. package/lib/bridge.mjs +1 -1
  17. package/lib/cards.mjs +138 -28
  18. package/lib/cloudBoot.mjs +124 -0
  19. package/lib/commands.mjs +7 -2
  20. package/lib/context.mjs +18 -4
  21. package/lib/contractGate.mjs +377 -0
  22. package/lib/coordinator.mjs +149 -43
  23. package/lib/daemon.mjs +349 -28
  24. package/lib/desk.mjs +239 -0
  25. package/lib/desktop.mjs +106 -6
  26. package/lib/environments.mjs +237 -7
  27. package/lib/folders.mjs +2 -2
  28. package/lib/gitHost.mjs +174 -0
  29. package/lib/hookDialects.mjs +298 -0
  30. package/lib/landed.mjs +887 -0
  31. package/lib/live.mjs +284 -13
  32. package/lib/mcp-stdio.mjs +68 -2
  33. package/lib/members.json +16 -2
  34. package/lib/models.mjs +8 -8
  35. package/lib/museSession.mjs +16 -13
  36. package/lib/nativeHost.mjs +1 -1
  37. package/lib/neovim.mjs +126 -0
  38. package/lib/nudge.mjs +47 -16
  39. package/lib/ownMachines.mjs +343 -39
  40. package/lib/pairing.mjs +27 -10
  41. package/lib/paths.mjs +4 -0
  42. package/lib/personModel.mjs +89 -0
  43. package/lib/phones.mjs +66 -11
  44. package/lib/places.mjs +330 -10
  45. package/lib/readiness.mjs +135 -18
  46. package/lib/record.mjs +115 -0
  47. package/lib/runWorker.mjs +17 -2
  48. package/lib/runner.mjs +8 -4
  49. package/lib/sessionControl.mjs +377 -89
  50. package/lib/specialties.json +74 -0
  51. package/lib/specialties.mjs +477 -0
  52. package/lib/specialtyKeys.d.ts +3 -0
  53. package/lib/specialtyKeys.js +58 -0
  54. package/lib/specialtyNotice.mjs +147 -0
  55. package/lib/specialtySnapshot.mjs +138 -0
  56. package/lib/store.mjs +284 -1
  57. package/lib/swarm.mjs +137 -21
  58. package/lib/t3.mjs +13 -4
  59. package/lib/taskCommands.mjs +36 -9
  60. package/lib/taskRuns.mjs +9 -2
  61. package/lib/team.json +255 -148
  62. package/lib/team.mjs +529 -188
  63. package/lib/threadLine.mjs +116 -0
  64. package/lib/threadRuns.mjs +75 -11
  65. package/lib/threadView.mjs +15 -2
  66. package/lib/worktrees.mjs +51 -13
  67. package/package.json +4 -4
  68. package/lib/modelTiers.json +0 -1183
  69. package/lib/modelTiers.mjs +0 -133
@@ -0,0 +1,89 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ // The person's own language model on this computer, when they run one for pi (its models.json, in PI_CODING_AGENT_DIR
6
+ // or ~/.pi/agent): an OpenAI-compatible server on this machine. Harness uses it only for small labels of the person's
7
+ // own words (threadLine.mjs), so nothing they wrote leaves the computer for it. A provider anywhere else is not theirs
8
+ // to lend: it is never used.
9
+
10
+ /**
11
+ * How long one label may take. Measured on the owner's M5 Pro with Flint (a reasoning model on llama.cpp), 80 labels of
12
+ * real thread messages, October 23, while e2e suites ran beside it: median 18.6 s and 22.0 s in two rounds, slowest
13
+ * 48.6 s. 90 s leaves about 1.85x over the slowest; a label is made once, in the background, so waiting costs nothing.
14
+ */
15
+ const LABEL_TIMEOUT_MS = 90_000;
16
+ const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
17
+
18
+ const modelsFile = () =>
19
+ path.join(
20
+ process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent"),
21
+ "models.json"
22
+ );
23
+
24
+ /** The first model pi lists on a server on this computer, or null. */
25
+ export function localModel(file = modelsFile()) {
26
+ let config;
27
+ try {
28
+ config = JSON.parse(fs.readFileSync(file, "utf8"));
29
+ } catch {
30
+ return null;
31
+ }
32
+ for (const provider of Object.values(config?.providers ?? {})) {
33
+ let url;
34
+ try {
35
+ url = new URL(provider.baseUrl);
36
+ } catch {
37
+ continue;
38
+ }
39
+ const model = provider.models?.[0]?.id;
40
+ if (!LOCAL_HOSTS.has(url.hostname) || !model) continue;
41
+ return {
42
+ baseUrl: provider.baseUrl.replace(/\/$/, ""),
43
+ model,
44
+ apiKey: provider.apiKey || "local",
45
+ reasoning: provider.models[0].reasoning === true,
46
+ };
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * Asks the person's local model a short question and returns its JSON answer, or null when there is no local model,
53
+ * it does not answer in time, or what it says is not JSON.
54
+ */
55
+ export async function askLocal(system, user, { fetchImpl = fetch } = {}) {
56
+ const local = localModel();
57
+ if (!local) return null;
58
+ try {
59
+ const res = await fetchImpl(`${local.baseUrl}/chat/completions`, {
60
+ method: "POST",
61
+ headers: {
62
+ "content-type": "application/json",
63
+ authorization: `Bearer ${local.apiKey}`,
64
+ },
65
+ body: JSON.stringify({
66
+ model: local.model,
67
+ temperature: 0,
68
+ // A reasoning model thinks before it answers: room for both, and as little thinking as it allows.
69
+ max_tokens: local.reasoning ? 3000 : 200,
70
+ ...(local.reasoning
71
+ ? { chat_template_kwargs: { reasoning_effort: "low" } }
72
+ : {}),
73
+ messages: [
74
+ { role: "system", content: system },
75
+ { role: "user", content: user },
76
+ ],
77
+ }),
78
+ signal: AbortSignal.timeout(LABEL_TIMEOUT_MS),
79
+ });
80
+ if (!res.ok) return null;
81
+ const body = await res.json();
82
+ const text = String(body.choices?.[0]?.message?.content ?? "")
83
+ .replace(/^```(?:json)?|```$/g, "")
84
+ .trim();
85
+ return JSON.parse(text);
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
package/lib/phones.mjs CHANGED
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { readJson, writeJsonAtomic } from "./files.mjs";
5
5
  import { boardCommandsFor } from "./boardProtocol.mjs";
6
+ import { isPairCode, normalizeJoinCode } from "./machineSeal.mjs";
6
7
  import {
7
8
  b64u,
8
9
  channelKey,
@@ -38,11 +39,17 @@ const BROWSER_PERSON_COMMANDS = boardCommandsFor("browserPerson");
38
39
  // back, and only as the person, never in a call Harness's chat makes.
39
40
  const LANE_COMMANDS = boardCommandsFor("browserLane");
40
41
  const BROWSER_READS = boardCommandsFor("browserReads");
42
+ // The person's linked window adds a computer to the swarm (docs/cloud-swarm.md §5.5): how a cloud worker joins, with
43
+ // home pinning its key exactly as for a code the person typed here. Only as the person, never in a Harness chat call.
44
+ const MACHINE_COMMANDS = boardCommandsFor("browserMachines");
45
+ // The person's window signs a cloud computer's agents in (agentSignIn.mjs): only there, and only as the person.
46
+ const SIGN_IN_COMMANDS = boardCommandsFor("browserSignIn");
41
47
 
42
48
  export async function createPhoneDesk({
43
49
  store,
44
50
  identityFile,
45
- // A browser link setup made before this daemon ran (writeBrowserOffer): taken in once, then the file is gone.
51
+ // A browser link setup made before this daemon ran (writeBrowserOffer). The file stays until the offer is used or
52
+ // expires, so a daemon that restarts in between (setup's own, an update, the service's keep-alive) still has it.
46
53
  setupOfferFile = null,
47
54
  boardCommand,
48
55
  reads = {},
@@ -50,13 +57,18 @@ export async function createPhoneDesk({
50
57
  onMessage = () => {},
51
58
  machine = () => null,
52
59
  lane = null,
60
+ machines = () => null,
61
+ // A cloud computer's link offer (cloudBoot.mjs): made by Harness, which runs the computer, and kept until the
62
+ // computer is removed, so any of the person's windows can link to it. Every other computer has none.
63
+ seededOffer = null,
64
+ signIn = null,
53
65
  }) {
54
66
  const identity = await loadOrCreateIdentity(identityFile);
55
67
  const offers = new Map();
56
68
  const keys = new Map();
57
69
  const hostname = os.hostname().slice(0, 64);
58
70
 
59
- const setupOffer = setupOfferFile ? takeSetupOffer(setupOfferFile) : null;
71
+ const setupOffer = setupOfferFile ? readSetupOffer(setupOfferFile) : null;
60
72
  if (setupOffer)
61
73
  offers.set(setupOffer.offerId, {
62
74
  secret: setupOffer.secret,
@@ -113,9 +125,15 @@ export async function createPhoneDesk({
113
125
  !KEY.test(String(devicePublicKey))
114
126
  )
115
127
  return { ok: false, error: "invalid pairing request" };
116
- const pending = offers.get(String(offerId));
117
- // One attempt per code, right or wrong: a guessed proof burns the code.
118
- offers.delete(String(offerId));
128
+ const seeded = seededOffer?.offerId === String(offerId);
129
+ const pending = seeded
130
+ ? { secret: seededOffer.secret, kind: "browser" }
131
+ : offers.get(String(offerId));
132
+ // One attempt per code, right or wrong: a guessed proof burns the code. The cloud offer's secret is 256 random bits
133
+ // that only Harness and the person's windows hold, so it is not burned.
134
+ if (!seeded) offers.delete(String(offerId));
135
+ if (setupOffer && String(offerId) === setupOffer.offerId)
136
+ removeFile(setupOfferFile);
119
137
  if (!pending)
120
138
  return {
121
139
  ok: false,
@@ -269,6 +287,39 @@ export async function createPhoneDesk({
269
287
  credentialSource: callInput.credentialSource,
270
288
  });
271
289
  }
290
+ if (SIGN_IN_COMMANDS.has(command)) {
291
+ if (!signIn || callInput.as === "harness")
292
+ return { ok: false, error: `a browser cannot call ${command} here` };
293
+ try {
294
+ if (command === "agents.signin.status") return signIn.status();
295
+ if (command === "agents.signin.start")
296
+ return signIn.start(String(callInput.agent || ""));
297
+ if (command === "agents.signin.read")
298
+ return signIn.read(callInput.id);
299
+ if (command === "agents.signin.send")
300
+ return signIn.send(callInput.id, callInput.text);
301
+ if (command === "agents.signin.key")
302
+ return signIn.useKey(String(callInput.agent || ""), callInput.key);
303
+ return signIn.stop(callInput.id);
304
+ } catch (error) {
305
+ return { ok: false, error: error.message };
306
+ }
307
+ }
308
+ if (MACHINE_COMMANDS.has(command)) {
309
+ const own = machines();
310
+ if (!own || callInput.as === "harness")
311
+ return { ok: false, error: `a browser cannot call ${command} here` };
312
+ if (command === "machines.list") return own.list();
313
+ // Only a join code, which confirms a computer already connected to the account and waiting to join; setup's
314
+ // 16-character code would also release a new computer's connection, which stays the buddy's and the CLI's.
315
+ const code = normalizeJoinCode(callInput.code);
316
+ if (!code || isPairCode(code))
317
+ return {
318
+ ok: false,
319
+ error: "a browser adds a computer only with its join code",
320
+ };
321
+ return own.add(code);
322
+ }
272
323
  if (BROWSER_READS.has(command)) {
273
324
  const read = reads[command];
274
325
  if (!read)
@@ -462,15 +513,19 @@ export async function writeBrowserOffer({ identityFile, offerFile }) {
462
513
  }).toString();
463
514
  }
464
515
 
465
- function takeSetupOffer(file) {
466
- const offer = readJson(file, null);
516
+ function removeFile(file) {
467
517
  try {
468
518
  fs.unlinkSync(file);
469
519
  } catch {}
470
- return offer &&
520
+ }
521
+
522
+ function readSetupOffer(file) {
523
+ const offer = readJson(file, null);
524
+ const usable =
525
+ offer &&
471
526
  ID.test(String(offer.offerId)) &&
472
527
  typeof offer.secret === "string" &&
473
- offer.expiresAt > Date.now()
474
- ? offer
475
- : null;
528
+ offer.expiresAt > Date.now();
529
+ if (!usable) removeFile(file);
530
+ return usable ? offer : null;
476
531
  }
package/lib/places.mjs CHANGED
@@ -3,7 +3,7 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { spawn, spawnSync } from "node:child_process";
6
- import { paths } from "./paths.mjs";
6
+ import { historyRoots, paths } from "./paths.mjs";
7
7
  import { agentEnvironment } from "./agentnode.mjs";
8
8
  import { mainCheckout } from "./worktrees.mjs";
9
9
 
@@ -11,7 +11,8 @@ import { mainCheckout } from "./worktrees.mjs";
11
11
  // Harness piece inside the agent sends it when the session starts (the Claude Code and Codex hooks, nudge.mjs; the
12
12
  // opencode plugin; the pi extension), or the daemon reads it from the running process when nothing did. Terminals and
13
13
  // editors put their own ids into everything they start, the same on every OS (TERM_PROGRAM, TMUX_PANE, WEZTERM_PANE,
14
- // KITTY_WINDOW_ID, VSCODE_GIT_ASKPASS_NODE: the editor's own install); macOS adds the app (__CFBundleIdentifier).
14
+ // KITTY_WINDOW_ID, NVIM: Neovim's server, VSCODE_GIT_ASKPASS_NODE: the editor's own install); macOS adds the app
15
+ // (__CFBundleIdentifier).
15
16
  //
16
17
  // Any other agent (a custom harness) does the same with one line to the daemon's socket as a session starts:
17
18
  // {"command":"board.live.place","agent":"<its id>","sessionId":"<id>","folder":"<absolute path>","pids":[<its pid>],
@@ -31,6 +32,7 @@ export const PLACE_ENV = [
31
32
  "WEZTERM_PANE",
32
33
  "KITTY_WINDOW_ID",
33
34
  "KITTY_LISTEN_ON",
35
+ "NVIM",
34
36
  "WT_SESSION",
35
37
  "VSCODE_GIT_ASKPASS_NODE",
36
38
  "CLAUDE_CODE_ENTRYPOINT",
@@ -313,6 +315,117 @@ export function editorTerminalStarts(editorId, command) {
313
315
  ).length;
314
316
  }
315
317
 
318
+ // How each agent marks a session the person ran in a terminal, in the first lines of its file: Claude Code's
319
+ // entrypoint "cli" (its panel says claude-vscode, the Agent SDK sdk-*), Codex's originator "codex-tui" (codex_exec,
320
+ // T3 Code and the editor extension say otherwise).
321
+ // Each kept at a fixed depth: Claude Code's under its project folders, Codex's under year, month and day (a session's
322
+ // subagents, deeper, are not sessions of the person's).
323
+ const TERMINAL_MARKS = {
324
+ "claude-code": { mark: /"entrypoint":\s*"cli"/, depth: 1 },
325
+ codex: { mark: /"originator":\s*"codex-tui"/, depth: 3 },
326
+ };
327
+ const SESSION_FILES_READ = 300;
328
+ const SESSION_HEAD = 20_000;
329
+
330
+ /**
331
+ * How many of an agent's sessions since `since` (ms) the person ran in a terminal, by the agent's own session files:
332
+ * what is known of where they work before Harness recorded any place. The newest SESSION_FILES_READ files only.
333
+ */
334
+ export function terminalSessions(agent, since) {
335
+ const { mark, depth: fileDepth } = TERMINAL_MARKS[agent] ?? {};
336
+ const root = mark ? historyRoots(agent)[0] : null;
337
+ if (!root) return 0;
338
+ const files = [];
339
+ const walk = (dir, depth) => {
340
+ let entries = [];
341
+ try {
342
+ entries = fs.readdirSync(dir, { withFileTypes: true });
343
+ } catch {
344
+ return;
345
+ }
346
+ for (const entry of entries) {
347
+ const file = path.join(dir, entry.name);
348
+ if (entry.isDirectory() && depth < fileDepth) walk(file, depth + 1);
349
+ else if (
350
+ depth === fileDepth &&
351
+ entry.isFile() &&
352
+ entry.name.endsWith(".jsonl")
353
+ ) {
354
+ const at = fs.statSync(file).mtimeMs;
355
+ if (at >= since) files.push({ file, at });
356
+ }
357
+ }
358
+ };
359
+ walk(root, 0);
360
+ return files
361
+ .sort((a, b) => b.at - a.at)
362
+ .slice(0, SESSION_FILES_READ)
363
+ .filter(({ file }) => mark.test(fileHead(file, SESSION_HEAD))).length;
364
+ }
365
+
366
+ // Runs nobody typed into, as the agent marks them in its own session file: Claude Code's `claude -p`, `codex exec`.
367
+ const BACKGROUND_MARKS = {
368
+ "claude-code": /"entrypoint":\s*"sdk-cli"/,
369
+ codex: /"originator":\s*"codex_exec"/,
370
+ };
371
+ const TEMP_FOLDERS = [
372
+ ...new Set(
373
+ [os.tmpdir(), "/tmp", "/var/folders"].flatMap((folder) => [
374
+ folder,
375
+ realFolder(folder),
376
+ ])
377
+ ),
378
+ ].map((folder) => folder.replace(/\/$/, "") + path.sep);
379
+
380
+ function realFolder(folder) {
381
+ try {
382
+ return fs.realpathSync(folder);
383
+ } catch {
384
+ return folder;
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Why a session looks like no person's, from its own record when nothing saw it start: "unattended" when its agent marks
390
+ * it as run without a person; "temporary" when it ran in a temporary folder since deleted (a test's leftovers, or an
391
+ * agent trying something out). Null otherwise. What started it is not in the file.
392
+ */
393
+ export function backgroundOf(agent, file, folder) {
394
+ if (BACKGROUND_MARKS[agent] && file && unattended(agent, file))
395
+ return "unattended";
396
+ const temporary =
397
+ folder && TEMP_FOLDERS.some((temp) => folder.startsWith(temp));
398
+ return temporary && !fs.existsSync(folder) ? "temporary" : null;
399
+ }
400
+
401
+ // A session file's start never changes once the agent has written how it runs: each is read until then, then kept
402
+ // (Open's lists ask every few seconds).
403
+ const marked = new Map();
404
+ function unattended(agent, file) {
405
+ if (marked.has(file)) return marked.get(file);
406
+ const head = fileHead(file, SESSION_HEAD);
407
+ const found = BACKGROUND_MARKS[agent].test(head);
408
+ if (/"(entrypoint|originator)"/.test(head)) {
409
+ if (marked.size > 5000) marked.clear();
410
+ marked.set(file, found);
411
+ }
412
+ return found;
413
+ }
414
+
415
+ function fileHead(file, length) {
416
+ let fd = null;
417
+ try {
418
+ fd = fs.openSync(file, "r");
419
+ const buffer = Buffer.alloc(length);
420
+ const read = fs.readSync(fd, buffer, 0, length, 0);
421
+ return buffer.toString("utf8", 0, read);
422
+ } catch {
423
+ return "";
424
+ } finally {
425
+ if (fd !== null) fs.closeSync(fd);
426
+ }
427
+ }
428
+
316
429
  // ── The agents ────────────────────────────────────────────────────────────────
317
430
 
318
431
  /** How each agent picks a session up again; its own panel in an editor, when it has one; its name in T3 Code. */
@@ -325,6 +438,7 @@ const AGENTS = {
325
438
  extension: "anthropic.claude-code",
326
439
  link: (scheme, id) =>
327
440
  `${scheme}://anthropic.claude-code/open?session=${id}`,
441
+ lists: claudePanelLists,
328
442
  },
329
443
  },
330
444
  codex: {
@@ -342,9 +456,22 @@ const AGENTS = {
342
456
  resume: "opencode --session",
343
457
  t3: "opencode",
344
458
  },
345
- cursor: { command: "cursor-agent", t3: "cursor" },
346
- "grok-build": { command: "grok", t3: "grok" },
347
- antigravity: { command: "agy_acp_server.par", t3: "antigravity" },
459
+ cursor: {
460
+ command: "cursor-agent",
461
+ resume: "cursor-agent --resume",
462
+ t3: "cursor",
463
+ },
464
+ "grok-build": { command: "grok", resume: "grok --resume", t3: "grok" },
465
+ copilot: { command: "copilot", resume: "copilot --resume" },
466
+ devin: { command: "devin", resume: "devin -r" },
467
+ kilo: { command: "kilo", resume: "kilo --session" },
468
+ // DeepSeek Harness's sessions reopen in its web app, which takes no session link here: none to type.
469
+ dsh: { command: "dsh" },
470
+ antigravity: {
471
+ command: "agy",
472
+ resume: "agy --conversation",
473
+ t3: "antigravity",
474
+ },
348
475
  "muse-code": { command: "muse", t3: "muse" },
349
476
  };
350
477
  export const agentCommand = (agent) => AGENTS[agent]?.command ?? null;
@@ -451,6 +578,15 @@ export function editorSessionWorkspace(
451
578
  return file;
452
579
  }
453
580
 
581
+ /**
582
+ * Whether an agent's panel can show a session it is not showing now. Its link opens any session id, but a session the
583
+ * panel leaves out of its list opens as an empty conversation, so Open sends only the ones it lists.
584
+ */
585
+ export function panelLists(agent, sessionId, folder) {
586
+ const lists = AGENTS[agent]?.panel?.lists;
587
+ return lists ? lists(sessionId, folder) : true;
588
+ }
589
+
454
590
  /** A session in its agent's own panel in an editor (Claude Code's, OpenAI's Codex extension), when it is installed there. */
455
591
  export function panelLink(agent, editorId, sessionId) {
456
592
  const panel = AGENTS[agent]?.panel;
@@ -465,6 +601,68 @@ export function panelLink(agent, editorId, sessionId) {
465
601
  return panel.link(editor.scheme, sessionId);
466
602
  }
467
603
 
604
+ // Claude Code's panel leaves out sessions run through the Agent SDK (T3 Code's, Harness's own runs) and its background
605
+ // ones: the entrypoint at the head of the session's file (else at its end), the sessionKind on its first message.
606
+ // Read from the extension itself, anthropic.claude-code 2.1.306 (October 23, 2026).
607
+ const SDK_ENTRYPOINTS = new Set(["sdk-cli", "sdk-ts", "sdk-py"]);
608
+ const BACKGROUND_KINDS = new Set(["daemon", "daemon-worker"]);
609
+ const FILE_END = 65_536;
610
+
611
+ function claudePanelLists(sessionId, folder) {
612
+ const file = claudeSessionFile(sessionId, folder);
613
+ if (!file) return false;
614
+ const [head, tail] = fileEnds(file);
615
+ const entrypoint = fieldIn(head, "entrypoint") ?? fieldIn(tail, "entrypoint");
616
+ if (SDK_ENTRYPOINTS.has(entrypoint)) return false;
617
+ const firstMessage =
618
+ head.split("\n").find((line) => line.includes('"parentUuid":')) ?? head;
619
+ return !BACKGROUND_KINDS.has(fieldIn(firstMessage, "sessionKind"));
620
+ }
621
+
622
+ /** A Claude Code session's file: in the projects folder named for its working folder, else in whichever one holds it. */
623
+ function claudeSessionFile(sessionId, folder) {
624
+ if (!UUID.test(String(sessionId || ""))) return null;
625
+ const root = historyRoots("claude-code")[0];
626
+ const name = `${sessionId}.jsonl`;
627
+ const named = folder
628
+ ? path.join(root, folder.replace(/[^a-zA-Z0-9]/g, "-"), name)
629
+ : null;
630
+ if (named && fs.existsSync(named)) return named;
631
+ let projects = [];
632
+ try {
633
+ projects = fs.readdirSync(root);
634
+ } catch {
635
+ return null;
636
+ }
637
+ return (
638
+ projects
639
+ .map((project) => path.join(root, project, name))
640
+ .find((file) => fs.existsSync(file)) ?? null
641
+ );
642
+ }
643
+
644
+ function fileEnds(file) {
645
+ const fd = fs.openSync(file, "r");
646
+ try {
647
+ const size = fs.fstatSync(fd).size;
648
+ const read = (start, length) => {
649
+ const buffer = Buffer.alloc(length);
650
+ fs.readSync(fd, buffer, 0, length, start);
651
+ return buffer.toString("utf8");
652
+ };
653
+ const tailStart = Math.max(0, size - FILE_END);
654
+ return [
655
+ read(0, Math.min(size, FILE_END)),
656
+ read(tailStart, size - tailStart),
657
+ ];
658
+ } finally {
659
+ fs.closeSync(fd);
660
+ }
661
+ }
662
+
663
+ const fieldIn = (text, field) =>
664
+ new RegExp(`"${field}":\\s*"([^"]*)"`).exec(text)?.[1] ?? null;
665
+
468
666
  // ── T3 Code ───────────────────────────────────────────────────────────────────
469
667
 
470
668
  const SQLITE = "/usr/bin/sqlite3";
@@ -505,6 +703,73 @@ const t3Tables = (home) =>
505
703
  ).split("\n")
506
704
  );
507
705
 
706
+ /** A read of T3's record that never holds the daemon (its database is gigabytes; a cold read took 5.7 s). */
707
+ function t3QueryLater(home, sql) {
708
+ const db = t3Database(home);
709
+ if (!db || !fs.existsSync(SQLITE)) return Promise.resolve(null);
710
+ return new Promise((resolve) => {
711
+ const child = spawn(
712
+ SQLITE,
713
+ ["-readonly", "-cmd", ".timeout 2000", db, sql],
714
+ {
715
+ stdio: ["ignore", "pipe", "ignore"],
716
+ }
717
+ );
718
+ let out = "";
719
+ child.stdout.on("data", (chunk) => (out += chunk));
720
+ child.on("error", () => resolve(null));
721
+ child.on("close", (code) => resolve(code === 0 ? out.trim() : null));
722
+ });
723
+ }
724
+
725
+ // What a command that makes a commit looks like in T3's record of a thread's steps.
726
+ const COMMITTING = `type = 'command_execution' and (json_extract(payload_json, '$.input') like '%git%commit%' or json_extract(payload_json, '$.input') like '%git%merge%')`;
727
+
728
+ /** The T3 Code threads that ran a command making a commit: those can have landed work in the project itself. */
729
+ export async function t3Committers(home = t3Home()) {
730
+ const rows = await t3QueryLater(
731
+ home,
732
+ `select distinct thread_id from orchestration_v2_projection_turn_items where ${COMMITTING};`
733
+ );
734
+ return new Set((rows || "").split("\n").filter(Boolean));
735
+ }
736
+
737
+ /** A T3 Code thread's commands that made commits, as it ran them: what it typed and what came back. */
738
+ export async function t3CommitCommands(threadId, home = t3Home()) {
739
+ if (!PLAIN_ID.test(String(threadId || ""))) return [];
740
+ const rows = await t3QueryLater(
741
+ home,
742
+ `select json_object('input', json_extract(payload_json, '$.input'), 'output', json_extract(payload_json, '$.output')) from orchestration_v2_projection_turn_items where thread_id = '${threadId}' and ${COMMITTING} order by ordinal;`
743
+ );
744
+ const commands = [];
745
+ for (const line of (rows || "").split("\n"))
746
+ try {
747
+ commands.push(JSON.parse(line));
748
+ } catch {}
749
+ return commands;
750
+ }
751
+
752
+ /**
753
+ * T3 Code's threads that work in a checkout of their own, by thread id: the checkout and its branch, from T3's own
754
+ * record (its thread list over MCP leaves them out; only a thread's full read has them).
755
+ */
756
+ export function t3Checkouts(home = t3Home()) {
757
+ const found = new Map();
758
+ if (!t3Tables(home).has("orchestration_v2_projection_threads")) return found;
759
+ const rows = t3Query(
760
+ home,
761
+ `select json_object('id', thread_id, 'path', json_extract(payload_json, '$.worktreePath'), 'branch', json_extract(payload_json, '$.branch')) from orchestration_v2_projection_threads where deleted_at is null and json_extract(payload_json, '$.worktreePath') is not null;`
762
+ );
763
+ for (const line of (rows || "").split("\n")) {
764
+ try {
765
+ const row = JSON.parse(line);
766
+ if (row.path && row.branch)
767
+ found.set(row.id, { path: row.path, branch: row.branch });
768
+ } catch {}
769
+ }
770
+ return found;
771
+ }
772
+
508
773
  /**
509
774
  * The T3 Code thread that has a provider session: the thread T3 ran it in (nightlies record the session on the thread's
510
775
  * provider thread; 0.0.45 in provider_session_runtime), else T3's import of it. A T3 thread's own id (a turn Harness
@@ -593,7 +858,7 @@ export function t3Project(folder, home = t3Home()) {
593
858
  * T3 Code's thread for a folder, so T3 opens on the right workspace: the newest one in that worktree, else the newest
594
859
  * working in its project's own folder when the folder is that, else the newest in its project.
595
860
  */
596
- export function t3ThreadIn(folder, home = t3Home()) {
861
+ export function t3ThreadIn(folder, provider = null, home = t3Home()) {
597
862
  const dir = folder ? realDir(folder) : null;
598
863
  if (!dir || !t3Tables(home).has("orchestration_v2_projection_threads"))
599
864
  return null;
@@ -601,12 +866,13 @@ export function t3ThreadIn(folder, home = t3Home()) {
601
866
  const rows = (
602
867
  t3Query(
603
868
  home,
604
- "select thread_id || char(9) || coalesce(project_id, '') || char(9) || coalesce(json_extract(payload_json, '$.worktreePath'), '') from orchestration_v2_projection_threads where deleted_at is null and archived_at is null order by updated_at desc;"
869
+ "select thread_id || char(9) || coalesce(project_id, '') || char(9) || coalesce(json_extract(payload_json, '$.worktreePath'), '') || char(9) || coalesce(default_provider, '') from orchestration_v2_projection_threads where deleted_at is null and archived_at is null order by updated_at desc;"
605
870
  ) || ""
606
871
  )
607
872
  .split("\n")
608
873
  .map((line) => line.split("\t"))
609
- .filter(([id]) => id);
874
+ // Only the agent's own threads: another agent's thread in the same folder is not where this one works.
875
+ .filter(([id, , , by]) => id && (!provider || by === provider));
610
876
  const inProject = project ? rows.filter(([, id]) => id === project.id) : [];
611
877
  const found =
612
878
  rows.find(([, , tree]) => tree && realDir(tree) === dir) ??
@@ -810,11 +1076,19 @@ const TERMINAL_NAMES = {
810
1076
  alacritty: "Alacritty",
811
1077
  };
812
1078
 
1079
+ /** Whether an app is a terminal app (not an editor or T3 Code, whose own terminals a session can also run in). */
1080
+ export const isTerminalApp = (app) =>
1081
+ typeof app === "string" &&
1082
+ [...Object.values(TERMINAL_NAMES), "iTerm2"].includes(
1083
+ path.basename(app, ".app")
1084
+ );
1085
+
813
1086
  /**
814
1087
  * Where a session runs, from its environment and the app found up its process tree (`host`, live.mjs hostApp):
815
1088
  * t3 T3 Code;
816
1089
  * editor an editor built on VS Code: its terminal, or an agent's own panel there ("surface");
817
1090
  * codex-app the Codex app;
1091
+ * nvim a Neovim terminal: its server (neovim.mjs), and the terminal app and pane Neovim itself runs in;
818
1092
  * terminal a terminal app, with the ids that pick its pane on any OS (tmux, WezTerm, kitty) and its tty;
819
1093
  * app any other app.
820
1094
  * The environment comes first: the app a process sits under can be a different one (a terminal started from an editor).
@@ -856,8 +1130,6 @@ export function placeFrom({
856
1130
  };
857
1131
  if (env.T3CODE_CLI_PATH || bundle === T3_BUNDLE)
858
1132
  return { kind: "t3", name: "T3 Code", folder };
859
- const editor = editorOf();
860
- if (editor) return editorPlace(editor);
861
1133
  const ids = {
862
1134
  tty,
863
1135
  tmux: env.TMUX && /^%\d+$/.test(env.TMUX_PANE || "") ? env.TMUX_PANE : null,
@@ -866,6 +1138,19 @@ export function placeFrom({
866
1138
  ? { id: env.KITTY_WINDOW_ID, socket: env.KITTY_LISTEN_ON || null }
867
1139
  : null,
868
1140
  };
1141
+ // Inside Neovim, whatever it runs in (an editor's terminal too): the pane ids are Neovim's own, its tty is not.
1142
+ if (env.NVIM && env.CLAUDE_CODE_ENTRYPOINT !== "claude-vscode")
1143
+ return {
1144
+ kind: "nvim",
1145
+ name: "Neovim",
1146
+ server: env.NVIM,
1147
+ app: host?.app ?? null,
1148
+ ...ids,
1149
+ tty: null,
1150
+ folder,
1151
+ };
1152
+ const editor = editorOf();
1153
+ if (editor) return editorPlace(editor);
869
1154
  if (env.TERM_PROGRAM && env.TERM_PROGRAM !== "vscode")
870
1155
  return {
871
1156
  kind: "terminal",
@@ -892,6 +1177,41 @@ export function placeFrom({
892
1177
  return host ? { kind: "app", name: hostName, app: host.app, folder } : null;
893
1178
  }
894
1179
 
1180
+ /**
1181
+ * Setup notes the terminal app it runs in (a person types npx tryharness where they work): what Open falls back to
1182
+ * before Harness has seen the person's sessions anywhere. Anything but a terminal app (an editor's terminal, T3) is not
1183
+ * kept.
1184
+ */
1185
+ export function noteSetupTerminal({
1186
+ env = process.env,
1187
+ host = null,
1188
+ tty = null,
1189
+ }) {
1190
+ const place = placeFrom({ env: placeEnv(env), host, tty });
1191
+ if (place?.kind !== "terminal" || !isTerminalApp(place.app)) return;
1192
+ try {
1193
+ fs.writeFileSync(
1194
+ paths.terminal,
1195
+ JSON.stringify({ name: place.name, app: place.app, at: Date.now() }) +
1196
+ "\n"
1197
+ );
1198
+ } catch {}
1199
+ }
1200
+
1201
+ /** The terminal app setup last ran in, while it is on this computer; null without one. */
1202
+ export function setupTerminal() {
1203
+ try {
1204
+ const { name, app } = JSON.parse(fs.readFileSync(paths.terminal, "utf8"));
1205
+ return typeof name === "string" &&
1206
+ typeof app === "string" &&
1207
+ fs.existsSync(app)
1208
+ ? { name, app }
1209
+ : null;
1210
+ } catch {
1211
+ return null;
1212
+ }
1213
+ }
1214
+
895
1215
  /** One key per place the person uses an agent in: both T3 builds are T3; an editor's terminal and its panel differ. */
896
1216
  export const placeKey = (place) =>
897
1217
  place.kind === "editor"