tryharness 0.7.32 → 0.7.34

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/models.mjs CHANGED
@@ -1,4 +1,6 @@
1
+ import fs from "node:fs";
1
2
  import os from "node:os";
3
+ import path from "node:path";
2
4
  import { spawn } from "node:child_process";
3
5
  import { agentEnvironment } from "./agentnode.mjs";
4
6
  import { nameOf } from "./members.mjs";
@@ -321,6 +323,86 @@ export const describePick = (pick) =>
321
323
  .filter(Boolean)
322
324
  .join(", ");
323
325
 
326
+ // Agent settings are read at selection time. Null means the agent names no value;
327
+ // execution adapters then leave that flag unset.
328
+ const readText = (file) => {
329
+ try {
330
+ return fs.readFileSync(file, "utf8");
331
+ } catch {
332
+ return null;
333
+ }
334
+ };
335
+ const readJson = (file) => {
336
+ const text = readText(file);
337
+ if (text === null) return null;
338
+ try {
339
+ return JSON.parse(text.replace(/^\s*\/\/.*$/gm, ""));
340
+ } catch {
341
+ return null;
342
+ }
343
+ };
344
+ const MODELS = {
345
+ "claude-code": (home) =>
346
+ readJson(path.join(home, ".claude", "settings.json"))?.model,
347
+ // Top-level keys come before the first [section].
348
+ codex: (home) =>
349
+ readText(path.join(home, ".codex", "config.toml"))
350
+ ?.split(/^\s*\[/m)[0]
351
+ .match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1],
352
+ pi: (home) => {
353
+ const settings = readJson(path.join(home, ".pi", "agent", "settings.json"));
354
+ return settings?.defaultModel
355
+ ? [settings.defaultProvider, settings.defaultModel]
356
+ .filter(Boolean)
357
+ .join("/")
358
+ : null;
359
+ },
360
+ opencode: (home) =>
361
+ (
362
+ readJson(path.join(home, ".config", "opencode", "opencode.json")) ??
363
+ readJson(path.join(home, ".config", "opencode", "opencode.jsonc"))
364
+ )?.model,
365
+ };
366
+ // The effort an agent's own settings name, which it applies to any model it runs without one named. Named on each run
367
+ // with the model, as the buddy shows them; OpenCode's settings name no default variant.
368
+ const EFFORTS = {
369
+ "claude-code": (home) =>
370
+ readJson(path.join(home, ".claude", "settings.json"))?.effortLevel,
371
+ codex: (home) =>
372
+ readText(path.join(home, ".codex", "config.toml"))
373
+ ?.split(/^\s*\[/m)[0]
374
+ .match(/^\s*model_reasoning_effort\s*=\s*"([^"]+)"/m)?.[1],
375
+ pi: (home) =>
376
+ readJson(path.join(home, ".pi", "agent", "settings.json"))
377
+ ?.defaultThinkingLevel,
378
+ };
379
+ export function agentModelSettings(id, home = os.homedir()) {
380
+ const model = MODELS[id]?.(home);
381
+ const effort = EFFORTS[id]?.(home);
382
+ return {
383
+ model:
384
+ typeof model === "string" && model.trim()
385
+ ? model.trim().slice(0, 100)
386
+ : null,
387
+ effort:
388
+ typeof effort === "string" && effort.trim()
389
+ ? effort.trim().toLowerCase().slice(0, 40)
390
+ : null,
391
+ };
392
+ }
393
+
394
+ // The person's choice in the relay (models.mjs), else what the agent's own settings name. Harness's is a model of its
395
+ // catalog on a provider (harnessModel.mjs), else its last model, which no card names.
396
+ export const describeAgentModel = (store, id, home) => {
397
+ const choice = choiceOf(store, id);
398
+ if (id === "harness") return choice ? (choice.name ?? choice.model) : null;
399
+ return choice?.auto
400
+ ? "picked for each run by Auto"
401
+ : choice
402
+ ? describePick(choice)
403
+ : agentModelSettings(id, home).model;
404
+ };
405
+
324
406
  /** The pick named for one run (a post, post_task), kept with the run until it starts. */
325
407
  export const setRunPick = (store, runId, pick, by) =>
326
408
  store.meta(`model:${runId}`, JSON.stringify({ ...pick, by }));
@@ -391,26 +473,23 @@ export const routeInput = ({
391
473
  });
392
474
 
393
475
  /**
394
- * The model and effort a run starts with: { model, effort, by, note? }, or null for the agent's own settings. `by` says
395
- * who chose: "you" (the person's post), another agent's id, "your choice" (the person's setting) or "auto".
396
- * Auto asks Harness only when the person allows it (not the privacy setting) and Harness can answer.
476
+ * Returns the complete run selection: model, effort, provenance and any fallback
477
+ * explanation. Missing agent settings stay null, never a guessed model or effort.
478
+ * Auto asks Harness only outside the privacy setting and when Harness can answer.
397
479
  */
398
480
  export function createModelRouter({
399
481
  store,
400
482
  askHarness,
401
483
  canAsk,
402
484
  privacy,
403
- ownModel,
485
+ home,
404
486
  workOf,
405
487
  log = () => {},
406
488
  }) {
407
- return async function modelForRun(task, agent) {
489
+ async function chooseForRun(task, agent) {
408
490
  const named = runPick(store, task.id);
409
- const pick =
410
- named ??
411
- (choiceOf(store, agent)
412
- ? { ...choiceOf(store, agent), by: "your choice" }
413
- : null);
491
+ const saved = choiceOf(store, agent);
492
+ const pick = named ?? (saved ? { ...saved, by: "your choice" } : null);
414
493
  if (!pick) return null;
415
494
  const by = named ? (named.by === "user" ? "you" : named.by) : pick.by;
416
495
  // A model picked without an effort runs at the default its list gives it, the one the buddy shows, named on the run
@@ -460,7 +539,7 @@ export function createModelRouter({
460
539
  agent,
461
540
  ...workOf(task),
462
541
  routing: routingOf(store),
463
- ownModel: ownModel(agent),
542
+ ownModel: agentModelSettings(agent, home).model,
464
543
  models,
465
544
  record: recordByModel(store, agent),
466
545
  }),
@@ -500,5 +579,22 @@ export function createModelRouter({
500
579
  `Harness could not pick a model (${error.message}); it ran on its own settings`
501
580
  );
502
581
  }
582
+ }
583
+ return async function modelForRun(task, agent) {
584
+ const chosen = await chooseForRun(task, agent);
585
+ // Read defaults after Auto returns, so a settings change during its request
586
+ // is reflected in the run. A fully specified pick needs no settings read.
587
+ const own =
588
+ chosen?.model != null && chosen?.effort != null
589
+ ? null
590
+ : agentModelSettings(agent, home);
591
+ const picked = Boolean(chosen?.model);
592
+ return {
593
+ ...chosen,
594
+ model: chosen?.model ?? own.model,
595
+ effort: chosen?.effort ?? own.effort,
596
+ by: picked ? chosen.by : (chosen?.by ?? "its settings"),
597
+ ...(picked ? {} : { ownSettings: true }),
598
+ };
503
599
  };
504
600
  }
package/lib/phones.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import os from "node:os";
2
2
  import { randomBytes } from "node:crypto";
3
+ import { boardCommandsFor } from "./boardProtocol.mjs";
3
4
  import {
4
5
  b64u,
5
6
  channelKey,
@@ -22,133 +23,19 @@ const OFFER_TTL_MS = 10 * 60_000;
22
23
  const MAX_OFFERS = 5;
23
24
  // A message queued at Harness while this computer slept may arrive up to 7 days late; only decisions and posts may.
24
25
  const QUEUED_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
25
- const QUEUEABLE = new Set([
26
- "board.post",
27
- "board.run",
28
- "board.release",
29
- "board.answer",
30
- "board.remove",
31
- "board.thread.post",
32
- "board.thread.send",
33
- "board.thread.discard",
34
- "board.thread.end",
35
- "board.goal.stop",
36
- "board.swarm.start",
37
- "board.swarm.post",
38
- "board.swarm.stop",
39
- "board.swarm.stop_all",
40
- "board.swarm.resume",
41
- "board.swarm.start_run",
42
- ]);
26
+ const QUEUEABLE = boardCommandsFor("queuedPhone");
43
27
  const ID = /^[A-Za-z0-9_-]{8,64}$/;
44
28
  const KEY = /^[A-Za-z0-9_-]{80,100}$/;
45
29
  const KINDS = new Set(["phone", "browser"]);
46
- const PHONE_COMMANDS = new Set([
47
- "board.list",
48
- "board.get",
49
- "board.children",
50
- "board.agents",
51
- "board.post",
52
- "board.run",
53
- "board.release",
54
- "board.answer",
55
- "board.remove",
56
- "board.thread.read",
57
- "board.thread.post",
58
- "board.thread.send",
59
- "board.thread.discard",
60
- "board.thread.auto",
61
- "board.thread.end",
62
- "board.goal.list",
63
- "board.goal.get",
64
- "board.goal.stop",
65
- "board.room.read",
66
- // A thread's files: shown, opened and downloaded, and shared or kept on this computer, by the person.
67
- "board.file.get",
68
- "board.file.share",
69
- "board.swarm.list",
70
- "board.swarm.read",
71
- "board.swarm.start",
72
- "board.swarm.post",
73
- "board.swarm.stop",
74
- "board.swarm.stop_all",
75
- "board.swarm.resume",
76
- "board.swarm.folder",
77
- "board.swarm.coordinator",
78
- "board.swarm.diff",
79
- "board.swarm.merge",
80
- "board.swarm.discard",
81
- "board.swarm.start_run",
82
- "board.swarm.agents",
83
- "board.swarm.note",
84
- // Where a thread works: the folders offered, any folder browsed to, and where a message would work (folders.mjs).
85
- "board.swarm.places",
86
- "board.swarm.browse",
87
- "board.swarm.place",
88
- // The person's own running sessions, read and messaged as from the desktop app; never queued (a session may be gone).
89
- "board.live",
90
- "board.live.read",
91
- "board.live.say",
92
- ]);
30
+ const PHONE_COMMANDS = boardCommandsFor("phone");
93
31
  // What the chat owner does on the board, in Harness's name (was src/server/mcp/board.ts HARNESS_COMMANDS).
94
- const HARNESS_COMMANDS = new Set([
95
- "board.list",
96
- "board.get",
97
- "board.post",
98
- "board.claim",
99
- "board.report",
100
- "board.answer",
101
- "board.thread.read",
102
- "board.thread.post",
103
- "board.standing.check",
104
- "board.goal.create",
105
- "board.goal.get",
106
- "board.goal.list",
107
- "board.goal.finish",
108
- "board.room.read",
109
- "board.room.post",
110
- "board.room.search",
111
- "board.children",
112
- "board.agents",
113
- "board.swarm.list",
114
- "board.swarm.read",
115
- "board.swarm.diff",
116
- ]);
117
- // Swarms talking to swarms (network.mjs), from the Harness window: the person's own, never Harness's.
118
- const RELAY_PERSON_COMMANDS = [
119
- "board.relay.list",
120
- "board.relay.network",
121
- "board.relay.decide",
122
- "board.relay.request",
123
- "board.relay.seen",
124
- "board.relay.defaults",
125
- "board.relay.peers",
126
- ];
127
- const BROWSER_PERSON_COMMANDS = new Set([
128
- ...PHONE_COMMANDS,
129
- "board.goal.resume",
130
- // What the swarm learned from the person (lessons.mjs), read in the PiP; the phone app has no view of it.
131
- "board.swarm.lessons",
132
- "board.standing",
133
- "board.standing.check",
134
- "board.standing.off",
135
- ...RELAY_PERSON_COMMANDS,
136
- ]);
32
+ const HARNESS_COMMANDS = boardCommandsFor("harnessBrowser");
33
+ // The person's linked window also manages relay connections and reads lessons.
34
+ const BROWSER_PERSON_COMMANDS = boardCommandsFor("browserPerson");
137
35
  // The person's own model lane (lane.mjs): only their linked Harness window gives it, sees whether it is kept, and takes it
138
36
  // back, and only as the person, never in a call Harness's chat makes.
139
- const LANE_COMMANDS = new Set([
140
- "harness.lane.share",
141
- "harness.lane.forget",
142
- "harness.lane.status",
143
- ]);
144
- const BROWSER_READS = new Set([
145
- "sessions.search",
146
- "sessions.read",
147
- "sessions.raw",
148
- "tasks.status",
149
- "relay.request",
150
- "relay.open",
151
- ]);
37
+ const LANE_COMMANDS = boardCommandsFor("browserLane");
38
+ const BROWSER_READS = boardCommandsFor("browserReads");
152
39
 
153
40
  export async function createPhoneDesk({
154
41
  store,
@@ -0,0 +1,44 @@
1
+ // One page of a thread's room as any agent reads it: its newest posts, the ones before a post (`before`) going back, or
2
+ // the ones after a post (`since`) catching up. Each page says where the posts on either side of it start, and fits in
3
+ // one tool result (October 17: 27 posts of a video thread came to 64,553 characters, more than Claude Code takes in one).
4
+ const PAGE_CHARS = 30_000;
5
+ const PAGE_POSTS = 50;
6
+
7
+ const size = (post) => post.text.length + 200;
8
+
9
+ export function roomPage(store, goalId, { since, before } = {}) {
10
+ if (Number(since) > 0) {
11
+ const after = store.roomPosts(goalId, since, PAGE_POSTS + 1);
12
+ const posts = [];
13
+ let used = 0;
14
+ for (const post of after.slice(0, PAGE_POSTS)) {
15
+ if (posts.length && used + size(post) > PAGE_CHARS) break;
16
+ posts.push(post);
17
+ used += size(post);
18
+ }
19
+ return {
20
+ posts,
21
+ earlierBefore: null,
22
+ laterAfter: posts.length < after.length ? posts.at(-1).seq : null,
23
+ };
24
+ }
25
+ const recent = store.recentRoomPosts(goalId, {
26
+ before,
27
+ limit: PAGE_POSTS,
28
+ });
29
+ const posts = [];
30
+ let used = 0;
31
+ for (const post of [...recent.posts].reverse()) {
32
+ if (posts.length && used + size(post) > PAGE_CHARS) break;
33
+ posts.unshift(post);
34
+ used += size(post);
35
+ }
36
+ return {
37
+ posts,
38
+ earlierBefore:
39
+ posts.length < recent.posts.length
40
+ ? (posts[0]?.seq ?? null)
41
+ : recent.earlierBefore,
42
+ laterAfter: Number(before) > 0 ? (posts.at(-1)?.seq ?? null) : null,
43
+ };
44
+ }
@@ -0,0 +1,109 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { spawnSync } from "node:child_process";
5
+ import { PS } from "./nudge.mjs";
6
+ import { paths } from "./paths.mjs";
7
+ import { MACHINE_RUNNERS } from "./members.mjs";
8
+
9
+ export function createRunAuthority({ store, installedAgents }) {
10
+ const RUNNERS = new Set(MACHINE_RUNNERS);
11
+ // A session the person typed in: its prompt hook (Claude Code, Codex) or its extension or plugin (pi, OpenCode) names
12
+ // the agent process, the parent of the board MCP it posts through.
13
+ // A run this daemon started is never one (the daemon is its parent), and an agent holding another agent's task writes
14
+ // as an agent until it reports.
15
+ const promptedBy = new Map();
16
+ // Unknown parent: not the person's.
17
+ const parentOf = (pid) =>
18
+ Number(
19
+ spawnSync(PS, ["-o", "ppid=", "-p", String(pid)], {
20
+ encoding: "utf8",
21
+ }).stdout?.trim()
22
+ ) || null;
23
+ const personSession = (agent, pid) => {
24
+ if (
25
+ !RUNNERS.has(agent) ||
26
+ !Number.isInteger(pid) ||
27
+ promptedBy.get(pid) !== agent
28
+ )
29
+ return false;
30
+ const parent = parentOf(pid);
31
+ return (
32
+ parent !== null && parent !== process.pid && !store.holdsAgentTask(agent)
33
+ );
34
+ };
35
+ const runners = () => installedAgents.filter((agent) => RUNNERS.has(agent));
36
+ const startOfToday = () => {
37
+ const day = new Date();
38
+ day.setHours(0, 0, 0, 0);
39
+ return day.toISOString();
40
+ };
41
+ const realDir = (dir) => {
42
+ try {
43
+ return fs.realpathSync(dir);
44
+ } catch {
45
+ return path.resolve(dir);
46
+ }
47
+ };
48
+ const within = (dir, root) => {
49
+ const rel = path.relative(realDir(root), realDir(dir));
50
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
51
+ };
52
+ const aboveHome = (dir) => within(os.homedir(), dir);
53
+ // A coding agent's own scratch folder, for the person's tasks that name none: nothing of theirs is in it.
54
+ const scratchFolder = (agent) => path.join(paths.home, "work", agent);
55
+ const covers = (rule, dir) =>
56
+ realDir(dir) === realDir(scratchFolder(rule.agent)) ||
57
+ rule.workspaces.some((root) =>
58
+ rule.mode === "default" && aboveHome(root)
59
+ ? realDir(root) === realDir(dir)
60
+ : within(dir, root)
61
+ );
62
+ const standingRules = () => store.standing(runners(), startOfToday());
63
+ // null when the run may start now; otherwise why it waits for the person.
64
+ const standingVerdict = ({ trust, target, workspace }) => {
65
+ if (trust !== "user")
66
+ return "Another agent wrote it, so it never starts without the person.";
67
+ const rule = standingRules().find((entry) => entry.agent === target);
68
+ if (!rule)
69
+ return `${target} is not a coding agent installed on this machine.`;
70
+ if (rule.mode === "off")
71
+ return `${target} is set to wait for the person's Start.`;
72
+ if (!covers(rule, workspace))
73
+ return rule.mode === "default"
74
+ ? `${target} has not worked in ${workspace} before, so its first run there waits for the person.`
75
+ : `${workspace} is outside the folders ${target} may run in without asking (${rule.workspaces.join(", ")}).`;
76
+ if (rule.runs_today >= rule.daily_cap)
77
+ return `${target} already started ${rule.runs_today} runs today without asking, its daily limit.`;
78
+ return null;
79
+ };
80
+ const applyStanding = (task) => {
81
+ if (!task?.run_workspace || task.run_authorized_at) return undefined;
82
+ const start = `It waits for the person's Start on the Harness Board, or: npx tryharness board run ${task.id}`;
83
+ const reason = standingVerdict({
84
+ trust: task.trust,
85
+ target: task.target_agent,
86
+ workspace: task.run_workspace,
87
+ });
88
+ if (reason) return { started: false, reason: `${reason} ${start}` };
89
+ return store.authorizeStanding(task.id)
90
+ ? { started: true }
91
+ : { started: false, reason: `It could not be authorized. ${start}` };
92
+ };
93
+
94
+ const markPrompt = (pids, agent) => {
95
+ for (const pid of Array.isArray(pids) ? pids.slice(0, 2) : [])
96
+ if (Number.isInteger(pid) && pid > 1) promptedBy.set(pid, agent);
97
+ };
98
+ return {
99
+ RUNNERS,
100
+ within,
101
+ personSession,
102
+ aboveHome,
103
+ scratchFolder,
104
+ standingRules,
105
+ standingVerdict,
106
+ applyStanding,
107
+ markPrompt,
108
+ };
109
+ }