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.
@@ -0,0 +1,202 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { compareScreens } from "./screens.mjs";
4
+ import { nameOf } from "./members.mjs";
5
+
6
+ export function createBoardTools({
7
+ MAX_FILE_BYTES,
8
+ askHarness,
9
+ contextEngine,
10
+ folderOf,
11
+ inRoom,
12
+ libraryFolders,
13
+ localEvent,
14
+ localHit,
15
+ localReady,
16
+ ocr,
17
+ getPhones,
18
+ getServerFeatures,
19
+ snippets,
20
+ roomOf,
21
+ state,
22
+ store,
23
+ watchOrListen,
24
+ }) {
25
+ return (request, { agent }) => {
26
+ if (request.command === "board.screens.compare") {
27
+ if (request.hostedCaller)
28
+ return {
29
+ ok: false,
30
+ error: "comparing screenshots runs only for agents on this computer",
31
+ };
32
+ if (!localReady(["ocr"]))
33
+ return {
34
+ ok: false,
35
+ error:
36
+ "the relay's text reader is not downloaded yet; run npx tryharness",
37
+ };
38
+ const read = (file) => {
39
+ const stat =
40
+ typeof file === "string" && path.isAbsolute(file)
41
+ ? fs.statSync(file, { throwIfNoEntry: false })
42
+ : null;
43
+ if (!stat?.isFile() || stat.size > MAX_FILE_BYTES)
44
+ throw new Error(`${file} is not an absolute path to an image`);
45
+ return fs.readFileSync(file);
46
+ };
47
+ let before, after;
48
+ try {
49
+ before = read(request.before);
50
+ after = read(request.after);
51
+ } catch (error) {
52
+ return { ok: false, error: error.message };
53
+ }
54
+ return {
55
+ ok: true,
56
+ pending: compareScreens(before, after, {
57
+ ocr,
58
+ lane: "interactive",
59
+ }).then((result) => {
60
+ localEvent(
61
+ "screens",
62
+ `compared two screenshots: ${result.summary}`,
63
+ result.ms
64
+ );
65
+ return { ok: true, ...result };
66
+ }),
67
+ };
68
+ }
69
+ if (
70
+ request.command === "board.video.watch" ||
71
+ request.command === "board.audio.listen"
72
+ )
73
+ return watchOrListen(request);
74
+ if (request.command === "board.snippet.request") {
75
+ const thread = store.getTask(String(request.id || ""));
76
+ if (!thread || thread.kind !== "goal" || !inRoom(thread, agent))
77
+ return { ok: false, error: "thread not found" };
78
+ if (!request.hostedCaller)
79
+ return {
80
+ ok: false,
81
+ error: "agents on this computer read the folder themselves",
82
+ };
83
+ return {
84
+ ok: true,
85
+ pending: snippets.request({
86
+ threadId: thread.id,
87
+ agent,
88
+ about: request.about,
89
+ where: ["code", "files"].includes(request.in) ? request.in : null,
90
+ }),
91
+ };
92
+ }
93
+ if (
94
+ request.command === "board.snippet.list" ||
95
+ request.command === "board.snippet.decide"
96
+ ) {
97
+ if (agent !== "user" || request.hostedCaller)
98
+ return { ok: false, error: "only the person shares or keeps code" };
99
+ return request.command === "board.snippet.list"
100
+ ? { ok: true, snippets: snippets.list({ all: request.all === true }) }
101
+ : snippets.decide(String(request.id || ""), request.share === true);
102
+ }
103
+ if (
104
+ request.command === "board.files.search" ||
105
+ request.command === "board.media.search"
106
+ ) {
107
+ if (request.hostedCaller)
108
+ return {
109
+ ok: false,
110
+ error:
111
+ "searching the person's files runs only for agents on this computer",
112
+ };
113
+ if (!localReady(["search"]))
114
+ return { ok: false, error: "the local search model is not ready yet" };
115
+ const thread = request.thread
116
+ ? store.getTask(String(request.thread))
117
+ : null;
118
+ const threadId = thread ? (roomOf(thread)?.id ?? thread.id) : null;
119
+ if (!libraryFolders().length && !threadId)
120
+ return {
121
+ ok: false,
122
+ error:
123
+ "no folders are added yet (the person adds one with npx tryharness local add <folder>); give a thread to search its files",
124
+ };
125
+ return {
126
+ ok: true,
127
+ pending: contextEngine
128
+ .searchFiles(String(request.query || "").slice(0, 2_000), {
129
+ folders: true,
130
+ threads: threadId ? [threadId] : [],
131
+ limit: Math.min(20, Number(request.limit) || 8),
132
+ })
133
+ .then((hits) => ({ ok: true, hits: hits.map(localHit) })),
134
+ };
135
+ }
136
+ if (request.command === "board.screen.search") {
137
+ if (request.hostedCaller)
138
+ return {
139
+ ok: false,
140
+ error: "screen search runs only for agents on this computer",
141
+ };
142
+ const query = String(request.query || "")
143
+ .trim()
144
+ .slice(0, 2_000);
145
+ if (!query) return { ok: false, error: "search_screen needs a query" };
146
+ if (!state.connected)
147
+ return {
148
+ ok: false,
149
+ error:
150
+ "the daemon is not connected to Harness, so the person's Harness window cannot be reached",
151
+ };
152
+ if (!getServerFeatures().has("sealed_ask"))
153
+ return {
154
+ ok: false,
155
+ error:
156
+ "the Harness this computer is connected to cannot carry a sealed screen search yet",
157
+ };
158
+ const since = request.since ? Date.parse(String(request.since)) : NaN;
159
+ const input = {
160
+ query,
161
+ ...(Number.isFinite(since)
162
+ ? { from_hours_ago: Math.max(0, (Date.now() - since) / 3_600_000) }
163
+ : {}),
164
+ };
165
+ const tool =
166
+ request.kind === "semantic"
167
+ ? "search_screen_semantic"
168
+ : "search_screen_text";
169
+ return {
170
+ ok: true,
171
+ pending: getPhones().ask(
172
+ { tool, input, agent: nameOf(agent) },
173
+ (envelopes) => askHarness("sealed_ask", { envelopes }, null)
174
+ ),
175
+ };
176
+ }
177
+ if (request.command === "board.code.search") {
178
+ if (request.hostedCaller)
179
+ return {
180
+ ok: false,
181
+ error: "code search runs only for agents on this computer",
182
+ };
183
+ if (!localReady(["search"]))
184
+ return {
185
+ ok: false,
186
+ error:
187
+ "the relay's local models are not downloaded yet; run npx tryharness",
188
+ };
189
+ const folder = folderOf(request);
190
+ if (!folder)
191
+ return { ok: false, error: "search_code needs an absolute folder" };
192
+ return {
193
+ ok: true,
194
+ pending: contextEngine.search({
195
+ query: String(request.query || "").slice(0, 4_000),
196
+ folder,
197
+ }),
198
+ };
199
+ }
200
+ return { ok: false, error: "unknown command" };
201
+ };
202
+ }
@@ -0,0 +1,92 @@
1
+ import { digestSince } from "./digest.mjs";
2
+
3
+ export function createBoardWatches({
4
+ folderOf,
5
+ contextEngine,
6
+ environment,
7
+ frames,
8
+ localEvents,
9
+ notePresence,
10
+ presence,
11
+ store,
12
+ watches,
13
+ }) {
14
+ return (request, { agent }) => {
15
+ if (
16
+ String(request.command).startsWith("board.watch.") ||
17
+ request.command === "board.digest" ||
18
+ request.command === "board.local.events"
19
+ ) {
20
+ if (request.hostedCaller)
21
+ return {
22
+ ok: false,
23
+ error: "watches are only for the person and agents on this computer",
24
+ };
25
+ if (request.command === "board.local.events")
26
+ return {
27
+ ok: true,
28
+ events: localEvents.filter(
29
+ (event) => event.at > String(request.since || "")
30
+ ),
31
+ };
32
+ if (request.command === "board.watch.list")
33
+ return {
34
+ ok: true,
35
+ watches: watches.list(),
36
+ alerts: watches.alerts(String(request.since || "")),
37
+ };
38
+ if (request.command === "board.watch.add") {
39
+ const measure = {
40
+ field: request.field,
41
+ count: request.count,
42
+ age: request.age,
43
+ above: request.above ?? null,
44
+ below: request.below ?? null,
45
+ };
46
+ return watches.add({
47
+ name: request.name,
48
+ command: request.watchCommand,
49
+ folder: folderOf(request),
50
+ everySeconds: Number(request.everySeconds) || 300,
51
+ measure,
52
+ by: agent === "user" ? "user" : agent,
53
+ });
54
+ }
55
+ if (agent !== "user")
56
+ return {
57
+ ok: false,
58
+ error: "only the person starts or removes a watch",
59
+ };
60
+ if (request.command === "board.watch.start")
61
+ return watches.start(String(request.id || ""));
62
+ if (request.command === "board.watch.remove")
63
+ return watches.remove(String(request.id || ""));
64
+ if (request.command === "board.digest") {
65
+ notePresence();
66
+ const since =
67
+ typeof request.since === "string" ? request.since : presence.lastAway;
68
+ const person = environment.person();
69
+ return {
70
+ ok: true,
71
+ presence: {
72
+ away: Boolean(presence.awaySince),
73
+ backAt: presence.backAt,
74
+ inCall: person.inCall,
75
+ idleSeconds: person.idleSeconds,
76
+ },
77
+ ...(since
78
+ ? {
79
+ digest: digestSince(store, since, {
80
+ alerts: watches.alerts(since),
81
+ learning: contextEngine.report(),
82
+ receiptOf: frames.receiptOf,
83
+ }),
84
+ }
85
+ : {}),
86
+ };
87
+ }
88
+ return { ok: false, error: `unknown command ${request.command}` };
89
+ }
90
+ return { ok: false, error: "unknown command" };
91
+ };
92
+ }
package/lib/bridge.mjs ADDED
@@ -0,0 +1,272 @@
1
+ import os from "node:os";
2
+ import { randomUUID } from "node:crypto";
3
+ import WebSocket from "ws";
4
+ import { scrubDeep, restoreDeep } from "./firewall.mjs";
5
+ // The bridge ping interval; smoke tests shorten it.
6
+ const HEARTBEAT_MS = Number(process.env.HARNESS_HEARTBEAT_MS) || 30_000;
7
+ // This machine's IPv4 addresses: they change when it moves between networks. IPv6 privacy addresses rotate on their own.
8
+ const networkAddresses = () =>
9
+ Object.values(os.networkInterfaces())
10
+ .flat()
11
+ .filter((entry) => entry && !entry.internal && entry.family === "IPv4")
12
+ .map((entry) => entry.address)
13
+ .sort()
14
+ .join(",");
15
+
16
+ const SCRUBBED = new Set([
17
+ "board_call",
18
+ "harness_task",
19
+ "harness_steer",
20
+ "coordinate",
21
+ "pick_folder",
22
+ "route_model",
23
+ "react",
24
+ "reflect",
25
+ "wake",
26
+ ]);
27
+ // Requests that only decide (the coordinator's round, a folder pick, a model pick): nothing on Harness's server acts on
28
+ // an email, phone number, wallet address or amount in them, so those go as placeholders too and come back restored.
29
+ // Work that acts (board calls, Harness's own tasks) keeps them, as Bankr needs the real address.
30
+ const DECIDE_ONLY = new Set([
31
+ "coordinate",
32
+ "pick_folder",
33
+ "route_model",
34
+ "react",
35
+ "reflect",
36
+ ]);
37
+
38
+ /** One connection owns request settlement, feature negotiation, outages and reconnects. */
39
+ export function createBridge({
40
+ config,
41
+ state,
42
+ saveStatus,
43
+ log,
44
+ localEvent,
45
+ processing,
46
+ hello,
47
+ onOpen,
48
+ onMessage,
49
+ }) {
50
+ let socket = null;
51
+ let stopped = false;
52
+ let heartbeat = null;
53
+ let serverFeatures = new Set();
54
+ const relayWaiters = new Map();
55
+ const outages = [];
56
+ let offlineSince = Date.now();
57
+ const send = (message) => {
58
+ try {
59
+ if (socket?.readyState === WebSocket.OPEN)
60
+ socket.send(JSON.stringify(message));
61
+ } catch {}
62
+ };
63
+ const askHarness = (type, input, timeoutMs = 15_000, clear = null) => {
64
+ const { scrubber } = processing();
65
+ if (!scrubber || !SCRUBBED.has(type))
66
+ return askBridge(type, { ...input, ...clear }, timeoutMs);
67
+ const vault = new Map();
68
+ const started = performance.now();
69
+ // Only a Harness that reads placeholders as known values gets them (masked_values; an older one would ask the person).
70
+ return scrubDeep(scrubber, input, vault, {
71
+ personal: DECIDE_ONLY.has(type) && serverFeatures.has("masked_values"),
72
+ })
73
+ .then((scrubbed) => {
74
+ if (vault.size)
75
+ localEvent(
76
+ "scrub",
77
+ `hid ${vault.size} item${vault.size === 1 ? "" : "s"} before sending to Harness`,
78
+ performance.now() - started
79
+ );
80
+ return askBridge(type, { ...scrubbed, ...clear }, timeoutMs);
81
+ })
82
+ .then((reply) => (vault.size ? restoreDeep(reply, vault) : reply));
83
+ };
84
+ const askBridge = (type, input, timeoutMs = 15_000) =>
85
+ new Promise((resolve, reject) => {
86
+ if (!state.connected) {
87
+ reject(new Error("the daemon is not connected to Harness"));
88
+ return;
89
+ }
90
+ const requestId = randomUUID();
91
+ // A null timeout waits for the answer or for the connection to drop, which fails every waiting request.
92
+ const timer =
93
+ timeoutMs === null
94
+ ? null
95
+ : setTimeout(() => {
96
+ relayWaiters.delete(requestId);
97
+ reject(
98
+ new Error("Harness did not answer; is the daemon connected?")
99
+ );
100
+ }, timeoutMs);
101
+ relayWaiters.set(
102
+ requestId,
103
+ Object.assign(
104
+ (response) => {
105
+ if (timer) clearTimeout(timer);
106
+ resolve(response);
107
+ },
108
+ {
109
+ reject: (error) => {
110
+ if (timer) clearTimeout(timer);
111
+ reject(error);
112
+ },
113
+ }
114
+ )
115
+ );
116
+ send({ type, requestId, input });
117
+ });
118
+
119
+ let retry = 1_000;
120
+ let reconnectTimer = null;
121
+ let awaitingPong = 0;
122
+ // Drops the connection and dials again in about a second, whatever the backoff had grown to.
123
+ const reconnectNow = (reason) => {
124
+ log(`${reason}; reconnecting`);
125
+ retry = 1_000;
126
+ if (reconnectTimer) {
127
+ clearTimeout(reconnectTimer);
128
+ reconnectTimer = null;
129
+ }
130
+ if (socket && socket.readyState !== WebSocket.CLOSED) socket.terminate();
131
+ else connect();
132
+ };
133
+ const scheduleReconnect = () => {
134
+ if (stopped || reconnectTimer) return;
135
+ const delay = Math.round(retry * (0.8 + Math.random() * 0.4));
136
+ retry = Math.min(30_000, retry * 2);
137
+ reconnectTimer = setTimeout(() => {
138
+ reconnectTimer = null;
139
+ connect();
140
+ }, delay);
141
+ };
142
+ const connect = () => {
143
+ if (stopped) return;
144
+ try {
145
+ const origin = new URL(config.origin);
146
+ origin.protocol = origin.protocol === "https:" ? "wss:" : "ws:";
147
+ origin.pathname = "/api/bridge/ws";
148
+ origin.search = "";
149
+ socket = new WebSocket(origin, {
150
+ headers: { authorization: "Bearer " + config.token },
151
+ });
152
+ socket.on("open", () => {
153
+ retry = 1_000;
154
+ awaitingPong = 0;
155
+ if (offlineSince)
156
+ outages.push({ start: offlineSince, end: Date.now() });
157
+ outages.splice(0, outages.length - 50);
158
+ offlineSince = null;
159
+ state.connected = true;
160
+ state.lastError = null;
161
+ serverFeatures = new Set();
162
+ saveStatus();
163
+ send(hello());
164
+ onOpen();
165
+ });
166
+ socket.on("message", (data) => {
167
+ let message;
168
+ try {
169
+ message = JSON.parse(String(data));
170
+ } catch {
171
+ return;
172
+ }
173
+ if (message.type === "pong") {
174
+ if (awaitingPong) {
175
+ state.pingMs = Date.now() - awaitingPong;
176
+ awaitingPong = 0;
177
+ }
178
+ return;
179
+ }
180
+ if (
181
+ message.type === "bridge_response" &&
182
+ relayWaiters.has(message.requestId)
183
+ ) {
184
+ relayWaiters.get(message.requestId)(
185
+ message.ok
186
+ ? { ok: true, ...(message.result || {}) }
187
+ : {
188
+ ok: false,
189
+ error: message.error || "Harness refused the request",
190
+ }
191
+ );
192
+ relayWaiters.delete(message.requestId);
193
+ return;
194
+ }
195
+
196
+ if (
197
+ message.type === "server_features" &&
198
+ Array.isArray(message.features)
199
+ )
200
+ serverFeatures = new Set(message.features.map(String));
201
+ onMessage(message);
202
+ });
203
+ const dropped = (error) => {
204
+ state.connected = false;
205
+ offlineSince ||= Date.now();
206
+ for (const [requestId, waiter] of relayWaiters) {
207
+ relayWaiters.delete(requestId);
208
+ waiter.reject?.(new Error("the connection to Harness dropped"));
209
+ }
210
+ if (error?.message) state.lastError = error.message;
211
+ saveStatus();
212
+ scheduleReconnect();
213
+ };
214
+ socket.on("close", () => dropped());
215
+ socket.on("error", dropped);
216
+ } catch (error) {
217
+ state.connected = false;
218
+ state.lastError = error.message;
219
+ saveStatus();
220
+ scheduleReconnect();
221
+ }
222
+ };
223
+
224
+ return {
225
+ send,
226
+ ask: askHarness,
227
+ has: (feature) => serverFeatures.has(feature),
228
+ features: () => serverFeatures,
229
+ outagesSince: (since) =>
230
+ [
231
+ ...outages,
232
+ ...(offlineSince ? [{ start: offlineSince, end: null }] : []),
233
+ ].filter((outage) => (outage.end ?? Infinity) >= since),
234
+ reconnect: reconnectNow,
235
+ start() {
236
+ connect();
237
+ // A ping still unanswered when the next is due means the connection is dead: after a Wi-Fi drop a socket can
238
+ // stay open for minutes with nothing behind it. Measured 2026-10-10 against production over in-flight satellite
239
+ // Wi-Fi, 420 round trips: p50 766 ms, p99 1.09 s, one stall of 14.0 s, so one interval is about twice the worst.
240
+ // A change in this machine's addresses (Wi-Fi to hotspot, a network back) reconnects at once.
241
+ // Standby keeps this interval: a longer one waits on measuring how long Harness's proxy holds an idle socket.
242
+ let addresses = networkAddresses();
243
+ heartbeat = setInterval(() => {
244
+ const current = networkAddresses();
245
+ if (current !== addresses) {
246
+ addresses = current;
247
+ reconnectNow("the network changed");
248
+ return;
249
+ }
250
+ if (socket?.readyState !== WebSocket.OPEN) return;
251
+ if (awaitingPong) {
252
+ reconnectNow(
253
+ `Harness did not answer a ping within ${HEARTBEAT_MS / 1000} s`
254
+ );
255
+ return;
256
+ }
257
+ awaitingPong = Date.now();
258
+ send({ type: "ping" });
259
+ }, HEARTBEAT_MS);
260
+ },
261
+ stop() {
262
+ stopped = true;
263
+ clearInterval(heartbeat);
264
+ clearTimeout(reconnectTimer);
265
+ for (const [id, waiter] of relayWaiters) {
266
+ relayWaiters.delete(id);
267
+ waiter.reject(new Error("the connection to Harness dropped"));
268
+ }
269
+ socket?.close();
270
+ },
271
+ };
272
+ }
package/lib/cards.mjs CHANGED
@@ -1,9 +1,6 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
1
  import { createHash } from "node:crypto";
5
2
  import { member } from "./members.mjs";
6
- import { choiceOf, describePick } from "./models.mjs";
3
+ import { describeAgentModel } from "./models.mjs";
7
4
 
8
5
  // Each of the person's agents as the others see it: one card, written the same way for every reader (the block an agent
9
6
  // is told when its session starts, list_agents, a thread's brief, the coordinator's round), so work goes to the agent
@@ -43,83 +40,6 @@ export function setNote(store, id, text) {
43
40
  return note || null;
44
41
  }
45
42
 
46
- // The model a coding agent's own settings name, as it runs here (the daemon passes no model of its own). Only that key
47
- // is read; null when the settings name none.
48
- const readText = (file) => {
49
- try {
50
- return fs.readFileSync(file, "utf8");
51
- } catch {
52
- return null;
53
- }
54
- };
55
- const readJson = (file) => {
56
- const text = readText(file);
57
- if (text === null) return null;
58
- try {
59
- return JSON.parse(text.replace(/^\s*\/\/.*$/gm, ""));
60
- } catch {
61
- return null;
62
- }
63
- };
64
- const MODELS = {
65
- "claude-code": (home) =>
66
- readJson(path.join(home, ".claude", "settings.json"))?.model,
67
- // Top-level keys come before the first [section].
68
- codex: (home) =>
69
- readText(path.join(home, ".codex", "config.toml"))
70
- ?.split(/^\s*\[/m)[0]
71
- .match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1],
72
- pi: (home) => {
73
- const settings = readJson(path.join(home, ".pi", "agent", "settings.json"));
74
- return settings?.defaultModel
75
- ? [settings.defaultProvider, settings.defaultModel]
76
- .filter(Boolean)
77
- .join("/")
78
- : null;
79
- },
80
- opencode: (home) =>
81
- (
82
- readJson(path.join(home, ".config", "opencode", "opencode.json")) ??
83
- readJson(path.join(home, ".config", "opencode", "opencode.jsonc"))
84
- )?.model,
85
- };
86
- export function modelOf(id, home = os.homedir()) {
87
- const found = MODELS[id]?.(home);
88
- return typeof found === "string" && found.trim()
89
- ? found.trim().slice(0, 100)
90
- : null;
91
- }
92
-
93
- // The effort an agent's own settings name, which it applies to any model it runs without one named. Named on each run
94
- // with the model, as the buddy shows them; OpenCode's settings name no default variant.
95
- const EFFORTS = {
96
- "claude-code": (home) =>
97
- readJson(path.join(home, ".claude", "settings.json"))?.effortLevel,
98
- codex: (home) =>
99
- readText(path.join(home, ".codex", "config.toml"))
100
- ?.split(/^\s*\[/m)[0]
101
- .match(/^\s*model_reasoning_effort\s*=\s*"([^"]+)"/m)?.[1],
102
- pi: (home) =>
103
- readJson(path.join(home, ".pi", "agent", "settings.json"))
104
- ?.defaultThinkingLevel,
105
- };
106
- export function effortOf(id, home = os.homedir()) {
107
- const found = EFFORTS[id]?.(home);
108
- return typeof found === "string" && found.trim()
109
- ? found.trim().toLowerCase().slice(0, 40)
110
- : null;
111
- }
112
-
113
- // The person's choice in the relay (models.mjs), else what the agent's own settings name.
114
- const modelLine = (store, id, home) => {
115
- const choice = choiceOf(store, id);
116
- return choice?.auto
117
- ? "picked for each run by Auto"
118
- : choice
119
- ? describePick(choice)
120
- : modelOf(id, home);
121
- };
122
-
123
43
  const RECENT = 50;
124
44
  const median = (values) => {
125
45
  const sorted = [...values].sort((a, b) => a - b);
@@ -185,9 +105,11 @@ export function swarmCards(store, entries, { home, lessons = true } = {}) {
185
105
  ...(roster.runs === "machine"
186
106
  ? {
187
107
  review: roster.review === true,
188
- model: modelLine(store, entry.id, home),
108
+ model: describeAgentModel(store, entry.id, home),
189
109
  }
190
- : {}),
110
+ : entry.id === "harness" && describeAgentModel(store, entry.id, home)
111
+ ? { model: describeAgentModel(store, entry.id, home) }
112
+ : {}),
191
113
  answers: answersFor(entry),
192
114
  record: {
193
115
  done: done.done,