tryharness 0.7.71 → 0.7.73

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 (57) hide show
  1. package/README.md +13 -8
  2. package/assets/opencode-plugin.js +70 -3
  3. package/cli.mjs +27 -12
  4. package/lib/asks.mjs +4 -0
  5. package/lib/boardCommands.mjs +9 -1
  6. package/lib/boardProtocol.json +23 -19
  7. package/lib/bridge.mjs +2 -0
  8. package/lib/capabilityCheck.mjs +86 -0
  9. package/lib/computerAddress.mjs +6 -14
  10. package/lib/coordinator.mjs +259 -30
  11. package/lib/daemon.mjs +164 -133
  12. package/lib/dispatchContract.json +1 -31
  13. package/lib/dispatchTools.js +8 -39
  14. package/lib/dispatches.mjs +27 -285
  15. package/lib/goalCommands.mjs +21 -38
  16. package/lib/herdr.mjs +159 -0
  17. package/lib/hookDialects.mjs +36 -2
  18. package/lib/jobAnswers.mjs +3 -0
  19. package/lib/kanban.mjs +256 -0
  20. package/lib/live.mjs +25 -3
  21. package/lib/localAgentAsk.mjs +20 -29
  22. package/lib/machineRoutes.mjs +1 -5
  23. package/lib/machineRuns.mjs +42 -22
  24. package/lib/manager.mjs +254 -0
  25. package/lib/mcp-stdio.mjs +58 -39
  26. package/lib/moves.mjs +365 -0
  27. package/lib/nudge.mjs +13 -3
  28. package/lib/ownMachines.mjs +122 -12
  29. package/lib/places.mjs +29 -2
  30. package/lib/plans.mjs +7 -1
  31. package/lib/projectSettings.mjs +11 -1
  32. package/lib/projects.mjs +20 -4
  33. package/lib/runAuthority.mjs +104 -35
  34. package/lib/runBrief.mjs +14 -1
  35. package/lib/runWorker.mjs +48 -24
  36. package/lib/runner.mjs +184 -75
  37. package/lib/selfUpdate.mjs +41 -0
  38. package/lib/serverWords.mjs +11 -11
  39. package/lib/sessionControl.mjs +68 -3
  40. package/lib/steerHook.mjs +124 -0
  41. package/lib/steerQueue.mjs +176 -0
  42. package/lib/store.mjs +34 -34
  43. package/lib/subagentSteering.mjs +363 -0
  44. package/lib/subagents.mjs +138 -29
  45. package/lib/swarm.mjs +16 -3
  46. package/lib/taskCommands.mjs +36 -71
  47. package/lib/threadActions.mjs +13 -3
  48. package/lib/threadAuthority.mjs +21 -14
  49. package/lib/threadBriefs.mjs +9 -3
  50. package/lib/threadRuns.mjs +35 -8
  51. package/npm-shrinkwrap.json +14 -14
  52. package/package.json +4 -4
  53. package/release.json +54 -49
  54. package/lib/comfyExecution.mjs +0 -545
  55. package/lib/promptDecider.mjs +0 -471
  56. package/lib/promptFlow.mjs +0 -562
  57. package/lib/promptScopes.mjs +0 -670
@@ -0,0 +1,124 @@
1
+ import path from "node:path";
2
+ import {
3
+ REDIRECT_HOLD,
4
+ endSteers,
5
+ steerText,
6
+ takeSteers,
7
+ } from "./steerQueue.mjs";
8
+
9
+ // Claude Code's PreToolUse and SubagentStop hooks: what the person told one of its subagents from Harness, given at that
10
+ // subagent's next tool call (steerQueue.mjs). Claude Code names the subagent a hook fires in (agent_id); the session's
11
+ // own model has none. A note reaches the subagent as it finishes; a new brief or a stop holds its calls until it ends its
12
+ // turn, where the new brief reaches it and a stop lets it return what it has.
13
+ // Setup runs this only when a steer waits (the shell guard in hookDialects.mjs), so it starts nothing otherwise.
14
+
15
+ async function readInput() {
16
+ if (process.stdin.isTTY) return null;
17
+ let text = "";
18
+ process.stdin.setEncoding("utf8");
19
+ await Promise.race([
20
+ new Promise((resolve) => {
21
+ process.stdin.on("data", (chunk) => (text += chunk));
22
+ process.stdin.on("end", resolve);
23
+ process.stdin.on("error", resolve);
24
+ }),
25
+ new Promise((resolve) => setTimeout(resolve, 1_000).unref()),
26
+ ]);
27
+ process.stdin.destroy();
28
+ try {
29
+ return JSON.parse(text);
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /** The hook's answer to Claude Code, or null for none. Exported for tests. */
36
+ export function answer(input, home) {
37
+ const session = input?.session_id;
38
+ // The session's own model hears about its subagents as its turn ends (nudge.mjs --stop), where it reads them as the
39
+ // person's.
40
+ if (!session || !input.agent_id) return null;
41
+ const agent = input.agent_id;
42
+ if (input.hook_event_name === "SubagentStop") {
43
+ const left = endSteers(session, agent, { event: "end" }, home);
44
+ return left.length ? { decision: "block", reason: steerText(left) } : null;
45
+ }
46
+ if (input.hook_event_name !== "PreToolUse") return null;
47
+ // Measured live on Claude Code (Haiku and Sonnet, November 1): words given with a tool call, as added context or as
48
+ // the reason it was refused, were read as text a tool returned and set aside, while a refused call stopped the
49
+ // subagent every time; the same words given as it finished (SubagentStop's block) were taken as the person's and
50
+ // acted on. So a note waits for that moment and costs the subagent nothing meanwhile; a stop or a new brief refuses
51
+ // each call until the subagent ends its turn, where the new brief reaches it.
52
+ const items = takeSteers(
53
+ session,
54
+ agent,
55
+ { tool: input.tool_name ?? null },
56
+ home,
57
+ { keep: true }
58
+ );
59
+ const stopped = items.some((item) => item.kind === "stop");
60
+ const redirected = items.some((item) => item.kind === "redirect");
61
+ if (!stopped && !redirected) return null;
62
+ return {
63
+ hookSpecificOutput: {
64
+ hookEventName: "PreToolUse",
65
+ permissionDecision: "deny",
66
+ permissionDecisionReason: stopped ? steerText(items) : REDIRECT_HOLD,
67
+ },
68
+ };
69
+ }
70
+
71
+ // What a subagent asks permission for, in a line: the command, the file or the address it names.
72
+ const named = (input) =>
73
+ String(
74
+ input?.command ??
75
+ input?.file_path ??
76
+ input?.path ??
77
+ input?.url ??
78
+ input?.pattern ??
79
+ ""
80
+ ).slice(0, 200);
81
+
82
+ /**
83
+ * Claude Code's PermissionRequest hook (--ask): when a subagent's permission dialog opens, Harness hears which subagent
84
+ * and what for, so the person sees it named wherever they are. The dialog itself is left to Claude Code.
85
+ */
86
+ async function tellAsk(input) {
87
+ if (input?.hook_event_name !== "PermissionRequest" || !input.agent_id) return;
88
+ const { daemonRequest } = await import("./control-client.mjs");
89
+ const transcript = input.transcript_path
90
+ ? path.join(
91
+ path.dirname(input.transcript_path),
92
+ String(input.session_id),
93
+ "subagents",
94
+ `agent-${input.agent_id}.jsonl`
95
+ )
96
+ : "";
97
+ await daemonRequest(
98
+ {
99
+ command: "board.subagent.asking",
100
+ agent: "claude-code",
101
+ sessionId: input.session_id,
102
+ agentId: input.agent_id,
103
+ tool: input.tool_name,
104
+ what: named(input.tool_input),
105
+ transcript,
106
+ },
107
+ 1_500
108
+ ).catch(() => null);
109
+ }
110
+
111
+ if (import.meta.url === `file://${process.argv[1]}`) {
112
+ if (process.argv.includes("--ask")) {
113
+ try {
114
+ await tellAsk(await readInput());
115
+ } catch {}
116
+ process.exit(0);
117
+ }
118
+ // Never exit 2: that is Claude Code's "block", and a broken hook must not stop work.
119
+ try {
120
+ const reply = answer(await readInput());
121
+ if (reply) process.stdout.write(JSON.stringify(reply) + "\n");
122
+ } catch {}
123
+ process.exit(0);
124
+ }
@@ -0,0 +1,176 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { harnessHome } from "./paths.mjs";
4
+
5
+ // What the person tells a subagent from Harness, waiting for that subagent's next step. The daemon writes; the hook
6
+ // inside each agent (steerHook.mjs for Claude Code, the OpenCode plugin) takes. A steer is one file under
7
+ // steer/<session>/<agent>/, so taking one is a single rename no two processes both win, and the folder is empty
8
+ // whenever nothing waits: the hook's shell guard checks only that, so a tool call with nothing waiting costs no Node
9
+ // start. `agent` is Claude Code's agent_id for one of its subagents, and PARENT for the session's own model (OpenCode's
10
+ // subagents are sessions of their own, so theirs is PARENT too). A taken steer leaves a receipt, which is how the
11
+ // person's window learns when it landed.
12
+
13
+ export const PARENT = "_";
14
+ const ID = /^[A-Za-z0-9._:-]{1,128}$/;
15
+ const KINDS = new Set(["note", "redirect", "stop", "parent"]);
16
+
17
+ export const steerRoot = (home = harnessHome) => path.join(home, "steer");
18
+ const receiptsRoot = (home) => path.join(home, "steer-receipts");
19
+ const folderOf = (home, session, agent) =>
20
+ path.join(steerRoot(home), session, agent || PARENT);
21
+
22
+ const readItem = (file) => {
23
+ try {
24
+ return JSON.parse(fs.readFileSync(file, "utf8"));
25
+ } catch {
26
+ return null;
27
+ }
28
+ };
29
+ const listed = (folder) => {
30
+ try {
31
+ return fs
32
+ .readdirSync(folder)
33
+ .filter((name) => name.endsWith(".json"))
34
+ .sort();
35
+ } catch {
36
+ return [];
37
+ }
38
+ };
39
+ // Empty folders go, so the shell guard sees nothing waiting.
40
+ function prune(home, session, agent) {
41
+ for (const folder of [
42
+ folderOf(home, session, agent),
43
+ path.join(steerRoot(home), session),
44
+ ])
45
+ try {
46
+ fs.rmdirSync(folder);
47
+ } catch {}
48
+ }
49
+
50
+ /** Leaves a steer for one session's subagent (or its own model, PARENT). Returns the steer as written. */
51
+ export function putSteer(
52
+ { session, agent, kind, text = "", about = null },
53
+ home = harnessHome
54
+ ) {
55
+ if (!ID.test(String(session)) || !ID.test(String(agent || PARENT)))
56
+ throw new Error("a steer needs a plain session and agent id");
57
+ if (!KINDS.has(kind)) throw new Error(`unknown steer kind ${kind}`);
58
+ const at = new Date().toISOString();
59
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
60
+ const item = { id, kind, text: String(text), about, at };
61
+ const folder = folderOf(home, session, agent);
62
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
63
+ // Written aside, then renamed in: a hook never reads half a steer.
64
+ const file = path.join(folder, `${id}.json`);
65
+ fs.writeFileSync(`${file}.part`, JSON.stringify(item), { mode: 0o600 });
66
+ fs.renameSync(`${file}.part`, file);
67
+ return item;
68
+ }
69
+
70
+ function receipt(home, item, where) {
71
+ const folder = receiptsRoot(home);
72
+ try {
73
+ fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
74
+ fs.writeFileSync(
75
+ path.join(folder, `${item.id}.json`),
76
+ JSON.stringify({ id: item.id, at: new Date().toISOString(), ...where }),
77
+ { mode: 0o600 }
78
+ );
79
+ } catch {}
80
+ }
81
+
82
+ /**
83
+ * Takes what waits for one session's subagent: every note, redirect and parent note, each once. A stop is not taken:
84
+ * it stays until the subagent ends (endSteers), so every later step is refused too. `where` goes on each receipt
85
+ * (the tool it landed before). With `keep`, nothing but a stop's first landing is marked: the hook only looks.
86
+ */
87
+ export function takeSteers(
88
+ session,
89
+ agent,
90
+ where = {},
91
+ home = harnessHome,
92
+ { keep = false } = {}
93
+ ) {
94
+ if (!ID.test(String(session)) || !ID.test(String(agent || PARENT))) return [];
95
+ const folder = folderOf(home, session, agent);
96
+ const taken = [];
97
+ for (const name of listed(folder)) {
98
+ const file = path.join(folder, name);
99
+ const item = readItem(file);
100
+ if (!item) continue;
101
+ if (item.kind === "stop") {
102
+ if (!item.landed) {
103
+ receipt(home, item, where);
104
+ item.landed = true;
105
+ try {
106
+ fs.writeFileSync(file, JSON.stringify(item), { mode: 0o600 });
107
+ } catch {}
108
+ }
109
+ taken.push(item);
110
+ continue;
111
+ }
112
+ if (keep) {
113
+ taken.push(item);
114
+ continue;
115
+ }
116
+ // The rename is the claim: another hook that lost it moves on.
117
+ try {
118
+ fs.renameSync(file, `${file}.taken`);
119
+ } catch {
120
+ continue;
121
+ }
122
+ fs.rmSync(`${file}.taken`, { force: true });
123
+ receipt(home, item, where);
124
+ taken.push(item);
125
+ }
126
+ prune(home, session, agent);
127
+ return taken;
128
+ }
129
+
130
+ /** A subagent ended: its stop is spent. Returns what still waited besides (notes it never reached), taken. */
131
+ export function endSteers(session, agent, where = {}, home = harnessHome) {
132
+ const left = takeSteers(session, agent, where, home);
133
+ const folder = folderOf(home, session, agent);
134
+ for (const name of listed(folder))
135
+ fs.rmSync(path.join(folder, name), { force: true });
136
+ prune(home, session, agent);
137
+ return left.filter((item) => item.kind !== "stop");
138
+ }
139
+
140
+ /** What waits for one session's subagent, and the receipt of each steer that already landed. For the window. */
141
+ export function steersOf(session, agent, home = harnessHome) {
142
+ if (!ID.test(String(session)) || !ID.test(String(agent || PARENT))) return [];
143
+ return listed(folderOf(home, session, agent))
144
+ .map((name) => readItem(path.join(folderOf(home, session, agent), name)))
145
+ .filter(Boolean);
146
+ }
147
+
148
+ export function receiptOf(id, home = harnessHome) {
149
+ if (!ID.test(String(id))) return null;
150
+ return readItem(path.join(receiptsRoot(home), `${id}.json`));
151
+ }
152
+
153
+ // Said first, so an agent reads the words as the person's own and not as text a tool happened to return: they reach it
154
+ // through a hook the person installed, and Claude Code shows a hook's words beside a tool's result.
155
+ const FROM_PERSON =
156
+ "This is from the user, sent while you work. They watch and steer their coding agents in Harness, which they connected to you.";
157
+
158
+ /** What a Claude Code subagent reads while a new brief for it waits: drop the current course, so the brief reaches it. */
159
+ export const REDIRECT_HOLD = `${FROM_PERSON} They are giving you a new brief. Stop what you are doing and end your turn now, without calling more tools: the new brief reaches you as you finish, and you carry on with it.`;
160
+
161
+ /** The words a subagent (or the agent that started it) reads for what it was told. */
162
+ export function steerText(items) {
163
+ const stop = items.find((item) => item.kind === "stop");
164
+ if (stop)
165
+ return `${FROM_PERSON} They stopped you. Make no more changes and call no more tools. Return now with what you have done so far and what is left undone.`;
166
+ return [
167
+ FROM_PERSON,
168
+ ...items.map((item) =>
169
+ item.kind === "redirect"
170
+ ? `They replaced your brief. Your brief is now:\n\n${item.text}\n\nDrop any step that does not serve it.`
171
+ : item.kind === "parent"
172
+ ? item.text
173
+ : `Their message to you:\n\n${item.text}`
174
+ ),
175
+ ].join("\n\n");
176
+ }
package/lib/store.mjs CHANGED
@@ -1145,8 +1145,10 @@ export function openStore(file) {
1145
1145
  });
1146
1146
  return this.getTask(parentId);
1147
1147
  },
1148
- // Run authority is a separate write from the post: an agent may ask for a run, only the user grants it.
1149
- authorizeRun(id, agent) {
1148
+ // Run authority is a separate write from the post: an agent may ask for a run, only the user grants it. A thread's
1149
+ // task naming no folder runs in `scratch`, the thread's scratch folder here, or in the one the computer it is for
1150
+ // makes (machineRuns.mjs), as one started on standing permission does.
1151
+ authorizeRun(id, agent, { scratch = null } = {}) {
1150
1152
  if (this.getThread(id))
1151
1153
  return {
1152
1154
  ok: false,
@@ -1165,9 +1167,12 @@ export function openStore(file) {
1165
1167
  const now = new Date().toISOString();
1166
1168
  const written = execute(
1167
1169
  "run",
1168
- `update board_tasks set run_authorized_by = @agent, run_authorized_at = @now, updated_at = @now, version = version + 1
1169
- where id = @id and status = 'open' and (run_workspace is not null or (kind = 'wake' and target_machine is not null)) and run_authorized_at is null`,
1170
- { id, agent, now }
1170
+ `update board_tasks set run_authorized_by = @agent, run_authorized_at = @now, updated_at = @now, version = version + 1,
1171
+ run_workspace = case when kind = 'task' and parent_id is not null then coalesce(run_workspace, @scratch) else run_workspace end
1172
+ where id = @id and status = 'open' and run_authorized_at is null
1173
+ and (run_workspace is not null or (kind = 'wake' and target_machine is not null)
1174
+ or (kind = 'task' and parent_id is not null and coalesce(@scratch, target_machine) is not null))`,
1175
+ { id, agent, now, scratch }
1171
1176
  );
1172
1177
  if (written.changes === 1) return { ok: true, task: this.getTask(id) };
1173
1178
  return conflict(this.getTask(id), agent, null, (task) =>
@@ -1178,9 +1183,9 @@ export function openStore(file) {
1178
1183
  : `task is ${task.status}`
1179
1184
  );
1180
1185
  },
1181
- // Standing permission: an agent starts the work the person or Harness posts for it without a Start each time. By
1182
- // default it covers the folders the person has used that agent in (its indexed sessions); the person can name
1183
- // folders instead (mode 'named') or turn it off ('off'). Only the person changes it; the daemon decides each post.
1186
+ // Standing permission: an agent starts the work the person, Harness or their own agents post for it without a Start
1187
+ // each time. By default it covers any folder below home (runAuthority.mjs covers); the person can name folders and a
1188
+ // daily limit instead (mode 'named') or turn it off ('off'). Only the person changes it; the daemon decides each post.
1184
1189
  setStanding(agent, mode, workspaces = [], dailyCap = DEFAULT_DAILY_RUNS) {
1185
1190
  execute(
1186
1191
  "run",
@@ -1258,16 +1263,14 @@ export function openStore(file) {
1258
1263
  proposers: row?.proposers_set
1259
1264
  ? JSON.parse(row.proposers)
1260
1265
  : [...PROPOSERS],
1261
- runs_today:
1262
- Number(this.meta(`prompt-quota:${since}:${agent}`) || "0") +
1263
- Number(
1264
- execute(
1265
- "get",
1266
- "select count(*) as n from board_tasks where target_agent = ? and run_authorized_by = 'standing' and run_authorized_at >= ?",
1267
- agent,
1268
- since
1269
- ).n
1270
- ),
1266
+ runs_today: Number(
1267
+ execute(
1268
+ "get",
1269
+ "select count(*) as n from board_tasks where target_agent = ? and run_authorized_by = 'standing' and run_authorized_at >= ?",
1270
+ agent,
1271
+ since
1272
+ ).n
1273
+ ),
1271
1274
  };
1272
1275
  });
1273
1276
  },
@@ -1342,29 +1345,18 @@ export function openStore(file) {
1342
1345
  scopeRef = null,
1343
1346
  expectedScope = null,
1344
1347
  nextScope = null,
1345
- quota = null,
1346
1348
  }) {
1347
1349
  db.exec("begin immediate");
1348
1350
  try {
1349
1351
  const task = this.getTask(id);
1350
1352
  const key = `dispatch-grant:${id}`;
1351
- const rule = quota
1352
- ? this.standing([quota.agent], quota.period)[0]
1353
- : null;
1354
1353
  if (
1355
1354
  this.meta(key) !== expectedGrant ||
1356
1355
  task?.version !== expectedVersion ||
1357
1356
  task.status !== "open" ||
1358
1357
  task.run_authorized_at ||
1359
1358
  (scopeRef &&
1360
- this.meta(`dispatch-scope:${scopeRef}`) !== expectedScope) ||
1361
- (quota &&
1362
- (quota.remaining < 1 ||
1363
- this.meta(quota.key) !== quota.expected ||
1364
- rule.daily_cap !== quota.limit ||
1365
- rule.set_at !== quota.rule_epoch ||
1366
- rule.mode !== quota.rule_mode ||
1367
- rule.runs_today >= rule.daily_cap))
1359
+ this.meta(`dispatch-scope:${scopeRef}`) !== expectedScope)
1368
1360
  ) {
1369
1361
  db.exec("commit");
1370
1362
  return false;
@@ -1384,7 +1376,6 @@ export function openStore(file) {
1384
1376
  }
1385
1377
  this.meta(key, nextGrant);
1386
1378
  if (scopeRef) this.meta(`dispatch-scope:${scopeRef}`, nextScope);
1387
- if (quota) this.meta(quota.key, quota.next);
1388
1379
  db.exec("commit");
1389
1380
  return true;
1390
1381
  } catch (error) {
@@ -3004,7 +2995,8 @@ export function openStore(file) {
3004
2995
  * A thread's turn that one of the person's own agents elsewhere asked for, or the task it posted itself for a coding
3005
2996
  * agent, started on its agent's standing permission: the rule read, the day's runs counted and the row authorized in
3006
2997
  * one transaction, so two asks at once never both take the last run of the day. It counts as one of the day's
3007
- * standing runs, whoever asked. `covered`: whether the rule covers `folder`, the folder checked (runAuthority.mjs).
2998
+ * standing runs, whoever asked. `covered`: whether the rule covers `folder`, the folder checked, and `pastLimit`
2999
+ * whether the day's runs reach a limit the person set (runAuthority.mjs).
3008
3000
  * `scratch`: where a posted task naming no folder runs on this computer; another computer's makes its own. The
3009
3001
  * receipt keeps the rule's revision, the folder checked, and the agent, folder and computer it was admitted to run
3010
3002
  * with, for the check again before it starts (runAuthority.mjs proposedHold). Null when
@@ -3012,7 +3004,15 @@ export function openStore(file) {
3012
3004
  */
3013
3005
  authorizeProposed(
3014
3006
  id,
3015
- { agent, proposer, since, covered, folder = null, scratch = null }
3007
+ {
3008
+ agent,
3009
+ proposer,
3010
+ since,
3011
+ covered,
3012
+ pastLimit,
3013
+ folder = null,
3014
+ scratch = null,
3015
+ }
3016
3016
  ) {
3017
3017
  db.exec("begin immediate");
3018
3018
  try {
@@ -3024,7 +3024,7 @@ export function openStore(file) {
3024
3024
  ? "not-proposer"
3025
3025
  : !covered(rule)
3026
3026
  ? "outside"
3027
- : rule.runs_today >= rule.daily_cap
3027
+ : pastLimit(rule)
3028
3028
  ? "cap"
3029
3029
  : null;
3030
3030
  const now = new Date().toISOString();