tryharness 0.7.31 → 0.7.33

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/asks.mjs CHANGED
@@ -10,6 +10,11 @@ import { nameOf } from "./members.mjs";
10
10
  //
11
11
  // Agents on Harness's server (Bankr, Quotient, Muse) keep their tasks there and take asks side by side. A send that may
12
12
  // have reached Harness is looked up by its id before it goes again, so a retry never makes a second task.
13
+ //
14
+ // An ask for an agent whose earlier ask is running as a turn that takes words mid-turn (Harness on its server) goes into
15
+ // that turn instead of waiting for it: the turn's answer answers both. One the turn ended without reading waits as any
16
+ // other, and goes to the agent as its own task (October 16, the content factory: an ask that waited behind Harness's turn
17
+ // went to Harness after that turn had already answered it).
13
18
 
14
19
  const OPEN_RUN = ["open", "claimed", "running", "needs_input"];
15
20
  // Sends lost on the way to Harness before the ask is given up and said as failed.
@@ -23,6 +28,9 @@ export function createAsks({
23
28
  onServer,
24
29
  earlierWaits,
25
30
  say,
31
+ // The task whose running turn takes the agent's words in this thread, else null; and putting an ask into it.
32
+ turnOf = () => null,
33
+ steer = async () => false,
26
34
  }) {
27
35
  const read = (key) => {
28
36
  try {
@@ -155,6 +163,31 @@ export function createAsks({
155
163
  }
156
164
  };
157
165
 
166
+ // Into the agent's running turn: said in the thread once the turn has it; asked as its own task if the turn cannot take it.
167
+ const steerInto = (thread, ask, taskId) => {
168
+ sending.add(ask.id);
169
+ change(thread.id, ask.id, { steered: taskId });
170
+ void steer(taskId, ask)
171
+ .catch(() => false)
172
+ .then((taken) => {
173
+ sending.delete(ask.id);
174
+ if (taken)
175
+ return say(
176
+ thread,
177
+ `${nameOf(ask.agent)} has ${whose(ask, false)} and reads it at its next step.`
178
+ );
179
+ change(thread.id, ask.id, { steered: null, unsteered: true });
180
+ pump(thread.id, ask.agent);
181
+ });
182
+ };
183
+ // Whether a kept ask is in the agent's running turn still. One whose turn ended unread is kept as any other.
184
+ const inTurn = (thread, ask) => {
185
+ if (!ask.steered) return false;
186
+ if (turnOf(thread.id, ask.agent) === ask.steered) return true;
187
+ change(thread.id, ask.id, { steered: null, unsteered: true });
188
+ return false;
189
+ };
190
+
158
191
  // Sends what can go now of the asks kept for one agent in a thread, oldest first, and says why the rest wait. Returns why
159
192
  // `fresh` could not be asked, when it failed here.
160
193
  const pump = (threadId, agent, fresh = null) => {
@@ -173,7 +206,18 @@ export function createAsks({
173
206
  if (ask.id === fresh) refused = told;
174
207
  continue;
175
208
  }
209
+ if (inTurn(thread, ask)) {
210
+ ahead = true;
211
+ continue;
212
+ }
176
213
  const why = waitOf(thread, ask, ahead);
214
+ const turn =
215
+ why === "turn" && !ask.unsteered ? turnOf(threadId, agent) : null;
216
+ if (turn) {
217
+ ahead = true;
218
+ steerInto(thread, ask, turn);
219
+ continue;
220
+ }
177
221
  if (why) {
178
222
  ahead = true;
179
223
  said(thread, ask, why);
@@ -210,6 +254,8 @@ export function createAsks({
210
254
  }
211
255
  const waiting = kept(threadId).find((each) => each.id === ask.id);
212
256
  const thread = store.getTask(threadId);
257
+ if (!refused && waiting?.steered)
258
+ return `${nameOf(agent)} is working in this thread now: your ask goes into its current turn, or to it next if that turn ends first.`;
213
259
  return (
214
260
  refused ??
215
261
  (waiting?.told && thread
@@ -239,6 +285,18 @@ export function createAsks({
239
285
  for (const thread of store.goals())
240
286
  for (const agent of agentsWaiting(thread.id)) pump(thread.id, agent);
241
287
  },
288
+ // The agent's turn that took asks ended: those it read are answered with it, and their askers are returned to hear
289
+ // its answer; the rest wait as any other ask. Call before the turn's task is reported, so none goes again.
290
+ turnEnded(threadId, taskId, read) {
291
+ const answered = kept(threadId).filter(
292
+ (each) => each.steered === taskId && read.includes(each.id)
293
+ );
294
+ for (const each of answered) forget(threadId, each.id);
295
+ for (const each of kept(threadId))
296
+ if (each.steered === taskId)
297
+ change(threadId, each.id, { steered: null, unsteered: true });
298
+ return [...new Set(answered.map((each) => each.asker))];
299
+ },
242
300
  // The person stopped the thread: what waited stops with it.
243
301
  stopped(threadId) {
244
302
  keep(threadId, []);
@@ -0,0 +1,328 @@
1
+ import { boardCommandsFor, boardMetadata } from "./boardProtocol.mjs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { documentText, isDocument } from "./files.mjs";
4
+ import { secretReason } from "./secrets.mjs";
5
+ import { imageKind } from "./ocr.mjs";
6
+
7
+ export function createBoardAccess({
8
+ store,
9
+ inRoom,
10
+ boardCommand,
11
+ sendThreadMessage,
12
+ notifyBoard,
13
+ namedPath,
14
+ textLike,
15
+ coveredImage,
16
+ }) {
17
+ // Once a browser is paired (store.sealedOnly), Harness's plain calls get metadata only: who, which state,
18
+ // when, the same as every board_changed already carries, and never the words (objectives, briefs,
19
+ // results, room posts, folders). The person's and Harness's own reads and writes come sealed from a paired
20
+ // device. What still works in the clear, for what runs on Harness's servers: a run's status, the
21
+ // timeline's counts, a trace's timings, a bounty's check that a guest posted; a hosted caller (Muse, Grok
22
+ // Bot, any connector) works the tasks it is part of in full, which it has to read.
23
+ const SEALED_ONLY = {
24
+ ok: false,
25
+ code: "sealed_only",
26
+ error:
27
+ "this computer answers Harness only end to end encrypted; connect this browser to it: npx tryharness link",
28
+ };
29
+ // Narrowing only: the timeline's Stop turns standing permission off.
30
+ const PLAIN_PERSON_COMMANDS = boardCommandsFor("plainPerson");
31
+ const PLAIN_HARNESS_READS = boardCommandsFor("plainHarnessReads");
32
+ const TASK_METADATA = boardMetadata.task;
33
+ const GOAL_METADATA = boardMetadata.goal;
34
+ const pick = (value, keys) =>
35
+ Object.fromEntries(
36
+ keys.filter((key) => key in value).map((key) => [key, value[key]])
37
+ );
38
+ const withoutWords = (task) =>
39
+ task && typeof task === "object"
40
+ ? {
41
+ ...pick(task, TASK_METADATA),
42
+ objective: "",
43
+ brief: "",
44
+ result: null,
45
+ context_refs: [],
46
+ run_workspace: task.run_workspace ? "(sealed)" : null,
47
+ redacted: true,
48
+ ...(task.goal && typeof task.goal === "object"
49
+ ? { goal: pick(task.goal, GOAL_METADATA) }
50
+ : {}),
51
+ }
52
+ : task;
53
+ const metadataOnly = (result) =>
54
+ result && typeof result === "object"
55
+ ? {
56
+ ...result,
57
+ redacted: true,
58
+ ...(result.task ? { task: withoutWords(result.task) } : {}),
59
+ ...(Array.isArray(result.tasks)
60
+ ? { tasks: result.tasks.map(withoutWords) }
61
+ : {}),
62
+ ...(Array.isArray(result.goals)
63
+ ? { goals: result.goals.map(withoutWords) }
64
+ : {}),
65
+ ...(Array.isArray(result.posts)
66
+ ? {
67
+ posts: result.posts.map((post) =>
68
+ pick(post, ["id", "seq", "author", "kind", "created_at"])
69
+ ),
70
+ }
71
+ : {}),
72
+ ...(Array.isArray(result.files) ? { files: [] } : {}),
73
+ ...(result.goal && typeof result.goal === "object" && !result.task
74
+ ? { goal: pick(result.goal, ["id", "status"]) }
75
+ : {}),
76
+ }
77
+ : result;
78
+ // Harness's own notice in a goal's room (a bounty): kept as a note that mentions and wakes no one, shared with guests when asked.
79
+ const plainNotice = (input) => {
80
+ const goal = store.getTask(String(input.id || ""));
81
+ if (!goal || goal.kind !== "goal")
82
+ return { ok: false, error: "goal not found" };
83
+ if (goal.status !== "open")
84
+ return { ok: false, error: `the goal is ${goal.status}` };
85
+ const text = String(input.text || "")
86
+ .trim()
87
+ .slice(0, 2_000);
88
+ if (!text || secretReason(text))
89
+ return { ok: false, error: "a notice needs plain text" };
90
+ const post = store.roomPost({
91
+ goalId: goal.id,
92
+ author: "harness",
93
+ kind: "note",
94
+ text,
95
+ });
96
+ if (input.shareWithGuests === true)
97
+ for (const guest of goal.goal.guests) {
98
+ if (
99
+ !store.getThread(guest.thread) ||
100
+ store.getThread(guest.thread).closed_at
101
+ )
102
+ continue;
103
+ const sent = store.postMessage({
104
+ id: randomUUID(),
105
+ taskId: guest.thread,
106
+ sender: "harness",
107
+ text,
108
+ refs: [],
109
+ flagReason: null,
110
+ });
111
+ if (sent.ok && sent.message.state === "sent")
112
+ sendThreadMessage(sent.message);
113
+ }
114
+ notifyBoard(store.getTask(goal.id));
115
+ return {
116
+ ok: true,
117
+ post: pick(post, ["id", "seq", "author", "kind", "created_at"]),
118
+ };
119
+ };
120
+ const roomOf = (task) => {
121
+ const parent = task?.parent_id ? store.getTask(task.parent_id) : null;
122
+ return parent?.kind === "goal" ? parent : null;
123
+ };
124
+ // What an agent attached in a task's thread while it held the task: with the files on the task, what the task made.
125
+ const madeIn = (task) => {
126
+ const room = roomOf(task),
127
+ by = task.claimed_by || task.target_agent;
128
+ return room && task.claimed_at
129
+ ? store
130
+ .taskFiles(room.id)
131
+ .filter(
132
+ (file) => file.author === by && file.created_at >= task.claimed_at
133
+ )
134
+ : [];
135
+ };
136
+ // What a caller through Harness may see: what it posted, holds or is named in, and the threads it is on. Work posted
137
+ // for anyone stays with the agents on this machine.
138
+ const visibleTo = (task, agent) =>
139
+ Boolean(task) &&
140
+ (task.target_agent === agent ||
141
+ task.origin_agent === agent ||
142
+ task.claimed_by === agent ||
143
+ (task.kind === "goal" && inRoom(task, agent)) ||
144
+ Boolean(roomOf(task) && inRoom(roomOf(task), agent)));
145
+ // What leaves this computer for an agent through Harness: any text in the answer that looks like a secret (the room's
146
+ // check, cli/lib/secrets.mjs) is replaced with a notice; the person still reads it in full here (docs/member-runs.md).
147
+ const withoutSecrets = (value) => {
148
+ if (typeof value === "string") {
149
+ const flag = secretReason(value);
150
+ return flag
151
+ ? `[held on the person's computer: this looked like ${flag}]`
152
+ : value;
153
+ }
154
+ if (Array.isArray(value)) return value.map(withoutSecrets);
155
+ if (value && typeof value === "object")
156
+ return Object.fromEntries(
157
+ Object.entries(value).map(([key, item]) => [key, withoutSecrets(item)])
158
+ );
159
+ return value;
160
+ };
161
+ const plainBoard = (input) => {
162
+ const agent = String(input.agent || "");
163
+ // A file's bytes are checked as a whole: a text file that holds a secret stays here; an image goes with what must not
164
+ // leave covered (coveredImage); other binary files are not text to check.
165
+ if (input.command === "board.file.get") {
166
+ const answer = answerPlain(input);
167
+ if (!answer?.ok) return answer;
168
+ const file = store.file(String(input.fileId || ""));
169
+ // A document is checked by its words, which are what an agent reads; the person still gets the file itself.
170
+ const words =
171
+ file && isDocument(file.mime)
172
+ ? documentText(namedPath(file), file.mime)
173
+ : null;
174
+ const flag =
175
+ (textLike(answer.file.mime) &&
176
+ secretReason(Buffer.from(answer.data, "base64").toString("utf8"))) ||
177
+ (words && secretReason(words));
178
+ if (flag)
179
+ return {
180
+ ok: false,
181
+ error: `held on the person's computer: this file looked like it holds ${flag}`,
182
+ };
183
+ if (words !== null && agent !== "user")
184
+ return { ok: true, file: withoutSecrets(answer.file), text: words };
185
+ const image =
186
+ (answer.file.mime.startsWith("image/") &&
187
+ !textLike(answer.file.mime)) ||
188
+ imageKind(Buffer.from(answer.data.slice(0, 12), "base64"));
189
+ return image
190
+ ? {
191
+ pending: coveredImage(
192
+ { ...answer, file: withoutSecrets(answer.file) },
193
+ file,
194
+ agent
195
+ ),
196
+ }
197
+ : { ...answer, file: withoutSecrets(answer.file) };
198
+ }
199
+ if (agent !== "user" && agent !== "harness") {
200
+ const answer = answerPlain(input);
201
+ return answer?.pending
202
+ ? { pending: answer.pending.then(withoutSecrets) }
203
+ : withoutSecrets(answer);
204
+ }
205
+ return answerPlain(input);
206
+ };
207
+ const answerPlain = (input) => {
208
+ const agent = String(input.agent || "");
209
+ // The person's and Harness's calls are answered in full only while no browser is paired; a hosted agent is always
210
+ // limited to what it is part of, paired or not.
211
+ if (!store.sealedOnly() && (agent === "user" || agent === "harness"))
212
+ return boardCommand(input);
213
+ const command = String(input.command || "");
214
+ // A thread Harness posts on accept: on the asking side, only one this machine asked for (it supplies the words itself).
215
+ if (
216
+ command === "board.post" &&
217
+ input.thread &&
218
+ typeof input.thread === "object" &&
219
+ agent === "user"
220
+ ) {
221
+ return input.thread.role === "asker" &&
222
+ store.meta(`relay_pending:${String(input.id || "")}`)
223
+ ? boardCommand(input)
224
+ : SEALED_ONLY;
225
+ }
226
+ if (agent === "harness" && PLAIN_HARNESS_READS.has(command)) {
227
+ const result = boardCommand(
228
+ command === "board.list" ? { ...input, all: true } : input
229
+ );
230
+ return result?.pending
231
+ ? { pending: result.pending.then(metadataOnly) }
232
+ : metadataOnly(result);
233
+ }
234
+ // A hosted agent's search goes through Harness: only the threads it is in, never the machine's sessions.
235
+ if (
236
+ command === "board.swarm.search" &&
237
+ agent !== "user" &&
238
+ agent !== "harness"
239
+ )
240
+ return boardCommand({ ...input, teamOnly: true });
241
+ if (
242
+ command === "board.code.search" ||
243
+ command === "board.media.search" ||
244
+ command === "board.files.search" ||
245
+ command === "board.screens.compare" ||
246
+ command === "board.video.watch" ||
247
+ command === "board.audio.listen" ||
248
+ command === "board.screen.search"
249
+ )
250
+ return {
251
+ ok: false,
252
+ error:
253
+ "this runs only for agents on this computer: what it reads never leaves it",
254
+ };
255
+ if (
256
+ String(command).startsWith("board.watch.") ||
257
+ command === "board.digest" ||
258
+ command === "board.local.events"
259
+ )
260
+ return {
261
+ ok: false,
262
+ error: "watches are only for the person and agents on this computer",
263
+ };
264
+ if (agent === "harness" && command === "board.room.post")
265
+ return plainNotice(input);
266
+ if (agent === "user" || agent === "harness")
267
+ return PLAIN_PERSON_COMMANDS.has(command)
268
+ ? boardCommand(input)
269
+ : SEALED_ONLY;
270
+ if (command === "board.list") {
271
+ const listed = boardCommand({ ...input, all: false });
272
+ return listed?.ok && Array.isArray(listed.tasks)
273
+ ? {
274
+ ...listed,
275
+ tasks: listed.tasks.filter((task) => visibleTo(task, agent)),
276
+ }
277
+ : listed;
278
+ }
279
+ if (command === "board.goal.list") {
280
+ const listed = boardCommand(input);
281
+ return listed?.ok
282
+ ? {
283
+ ...listed,
284
+ goals: listed.goals.filter((goal) =>
285
+ inRoom(store.getTask(goal.id) || { goal: { team: [] } }, agent)
286
+ ),
287
+ }
288
+ : listed;
289
+ }
290
+ const id = String(input.id || "");
291
+ const task = id ? store.getTask(id) : null;
292
+ if (command === "board.post") {
293
+ const parent = input.parentId
294
+ ? store.getTask(String(input.parentId))
295
+ : null;
296
+ return input.parentId && parent && !visibleTo(parent, agent)
297
+ ? { ok: false, error: "task not found" }
298
+ : boardCommand(input);
299
+ }
300
+ if (
301
+ ["board.thread.read", "board.thread.post"].includes(command) &&
302
+ task &&
303
+ task.claimed_by !== agent
304
+ )
305
+ return { ok: false, error: "task not found" };
306
+ if (command === "board.children" && task && visibleTo(task, agent)) {
307
+ const listed = boardCommand(input);
308
+ return listed?.ok
309
+ ? {
310
+ ...listed,
311
+ tasks: listed.tasks.filter((child) => visibleTo(child, agent)),
312
+ }
313
+ : listed;
314
+ }
315
+ // A task this machine does not hold is the server's own (boardCommand forwards it); one it holds is shown only to its parties.
316
+ if (task && !visibleTo(task, agent))
317
+ return {
318
+ ok: false,
319
+ error:
320
+ command.startsWith("board.goal.") || command.startsWith("board.room.")
321
+ ? "goal not found"
322
+ : "task not found",
323
+ };
324
+ return boardCommand(input);
325
+ };
326
+
327
+ return { plainBoard, roomOf, madeIn, visibleTo, SEALED_ONLY };
328
+ }
@@ -0,0 +1,28 @@
1
+ import { boardCommandOwner } from "./boardProtocol.mjs";
2
+
3
+ // Every transport enters the same request context before a feature applies its
4
+ // own rules. Routing selects an implementation; it grants no execution authority.
5
+ export function createBoardCommands({
6
+ store,
7
+ validAgent,
8
+ touchListener,
9
+ handlers,
10
+ task,
11
+ }) {
12
+ return (request) => {
13
+ if (!validAgent(request.agent))
14
+ return { ok: false, error: "board requests need an agent name" };
15
+ if (request.command === "board.post") touchListener();
16
+ const agent = String(request.agent);
17
+ const lastLooked = store.lastSeenAt(agent);
18
+ store.touchAgent(agent);
19
+ const id = String(request.id || "");
20
+ const expected = Number.isInteger(request.expectedVersion)
21
+ ? request.expectedVersion
22
+ : null;
23
+ const context = { agent, lastLooked, id, expected };
24
+ const owner = boardCommandOwner(String(request.command));
25
+ const handler = Object.hasOwn(handlers, owner) ? handlers[owner] : task;
26
+ return handler(request, context);
27
+ };
28
+ }
@@ -0,0 +1,228 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { documentText, ensureDir, isDocument, mimeFor } from "./files.mjs";
4
+ import { paths } from "./paths.mjs";
5
+
6
+ export function createBoardFileCommands({
7
+ FILE_LIMITS,
8
+ FILE_PART_BYTES,
9
+ MAX_FILE_BYTES,
10
+ MB,
11
+ blobPath,
12
+ fileLimit,
13
+ fileLine,
14
+ fileName,
15
+ fileView,
16
+ keepBlob,
17
+ namedPath,
18
+ notifyBoard,
19
+ readFilesSoon,
20
+ roomOf,
21
+ store,
22
+ textLike,
23
+ tooBig,
24
+ visibleFile,
25
+ }) {
26
+ return (request, { agent, id }) => {
27
+ if (request.command === "board.file.add") {
28
+ const task = store.getTask(id);
29
+ if (!task) return { ok: false, error: "task not found" };
30
+ let bytes;
31
+ if (request.path != null) {
32
+ // Only an agent on this computer names a path on it.
33
+ if (request.hostedCaller)
34
+ return {
35
+ ok: false,
36
+ error:
37
+ "an agent reaching this computer through Harness attaches a file's content (data), not a path",
38
+ };
39
+ const file = String(request.path);
40
+ const stat = path.isAbsolute(file)
41
+ ? fs.statSync(file, { throwIfNoEntry: false })
42
+ : null;
43
+ if (!stat?.isFile())
44
+ return {
45
+ ok: false,
46
+ error: `${file} is not an absolute path to a file`,
47
+ };
48
+ if (stat.size > MAX_FILE_BYTES)
49
+ return tooBig(
50
+ stat.size,
51
+ FILE_LIMITS.find((limit) => limit.bytes === MAX_FILE_BYTES)
52
+ );
53
+ bytes = fs.readFileSync(file);
54
+ } else if (typeof request.data === "string" && request.data)
55
+ bytes = Buffer.from(request.data, "base64");
56
+ else
57
+ return {
58
+ ok: false,
59
+ error: "give the file's path or its content as base64 data",
60
+ };
61
+ // A file sent in parts, in order (a sealed message carries about 1 MB): kept aside until its last part arrives.
62
+ if (request.upload !== undefined) {
63
+ const upload = String(request.upload),
64
+ offset = Number(request.offset),
65
+ total = Number(request.total);
66
+ const partial = path.join(paths.files, "uploads", `${agent}-${upload}`);
67
+ if (
68
+ !/^[\w-]{8,64}$/.test(upload) ||
69
+ !Number.isSafeInteger(total) ||
70
+ total > MAX_FILE_BYTES ||
71
+ offset !==
72
+ (offset ? fs.statSync(partial, { throwIfNoEntry: false })?.size : 0)
73
+ )
74
+ return {
75
+ ok: false,
76
+ error:
77
+ "a part must follow the one before it, within the file's size",
78
+ };
79
+ ensureDir(path.dirname(partial));
80
+ (offset ? fs.appendFileSync : fs.writeFileSync)(partial, bytes, {
81
+ mode: 0o600,
82
+ });
83
+ if (offset + bytes.length < total)
84
+ return { ok: true, received: offset + bytes.length };
85
+ bytes = fs.readFileSync(partial);
86
+ fs.rmSync(partial, { force: true });
87
+ if (bytes.length !== total)
88
+ return {
89
+ ok: false,
90
+ error: `the parts came to ${bytes.length} of the file's ${total} bytes`,
91
+ };
92
+ }
93
+ if (!bytes.length) return { ok: false, error: "the file is empty" };
94
+ const name = fileName(
95
+ request.name ||
96
+ (request.path != null ? path.basename(String(request.path)) : "")
97
+ );
98
+ const mime =
99
+ typeof request.mime === "string" &&
100
+ /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/i.test(request.mime)
101
+ ? request.mime.toLowerCase()
102
+ : mimeFor(name);
103
+ const limit = fileLimit(mime, bytes);
104
+ if (bytes.length > limit.bytes) return tooBig(bytes.length, limit);
105
+ // Shared with the agents on Harness's side unless whoever attached it keeps it on the computer (owner, October 14:
106
+ // "shared should be default ... the user should select if something shouldnt be shared"); bytes that came through
107
+ // Harness were readable there already. To another person's computer a file still goes only sealed.
108
+ const file = store.addFile({
109
+ taskId: id,
110
+ name,
111
+ mime,
112
+ bytes: bytes.length,
113
+ sha256: keepBlob(bytes),
114
+ author: agent,
115
+ cloud: request.hostedCaller === true || request.cloud !== false,
116
+ });
117
+ // Said in the thread the task is in, with its id, so every agent there can open it.
118
+ const place = roomOf(task)?.id ?? id;
119
+ store.addContribution({
120
+ taskId: place,
121
+ kind: "file",
122
+ author: agent,
123
+ text: `${agent} attached ${fileLine(file)}`,
124
+ source: `file:${file.id}`,
125
+ });
126
+ notifyBoard(store.getTask(place));
127
+ readFilesSoon();
128
+ return { ok: true, file: fileView(file, request.hostedCaller) };
129
+ } else if (request.command === "board.file.share") {
130
+ // Whether the agents on Harness's side may read a file: the person's call, either way, on any file. A call through
131
+ // Harness in the clear (an unpaired browser) may only keep a file here: Harness must not be able to open one up.
132
+ if (agent !== "user")
133
+ return {
134
+ ok: false,
135
+ error: "only the person shares a file or keeps it on this computer",
136
+ };
137
+ if (request.hostedCaller && request.cloud === true)
138
+ return {
139
+ ok: false,
140
+ code: "sealed_only",
141
+ error:
142
+ "share a file from the buddy or a browser linked to this computer: npx tryharness link",
143
+ };
144
+ const file = store.file(String(request.fileId || ""));
145
+ if (!file) return { ok: false, error: "file not found" };
146
+ store.setFileCloud(file.id, request.cloud === true);
147
+ store.meta(
148
+ `file-share:${file.id}`,
149
+ JSON.stringify({ by: "user", at: new Date().toISOString() })
150
+ );
151
+ notifyBoard(
152
+ store.getTask(roomOf(store.getTask(file.task_id))?.id ?? file.task_id)
153
+ );
154
+ return { ok: true, file: fileView(store.file(file.id), false) };
155
+ } else if (request.command === "board.file.get") {
156
+ const file = store.file(String(request.fileId || ""));
157
+ if (!file || !visibleFile(file, agent, request.hostedCaller))
158
+ return { ok: false, error: "file not found" };
159
+ if (request.hostedCaller && !file.cloud)
160
+ return {
161
+ ok: false,
162
+ code: "sealed",
163
+ error:
164
+ "this file stays on the person's computers: the agent that attached it did not share it with cloud agents",
165
+ };
166
+ if (!file.present)
167
+ return {
168
+ ok: false,
169
+ error: "this file is still on its way from the other computer",
170
+ };
171
+ // A part of the file for the person's own phone or linked browser: a sealed answer carries about 1 MB
172
+ // (src/shared/bridge/sealedWire.ts), so a larger file is read in parts. A caller through Harness gets the whole
173
+ // file, which the checks in plainBoard read as a whole.
174
+ if (request.offset !== undefined && !request.hostedCaller) {
175
+ const offset = Number(request.offset),
176
+ length = Number(request.length ?? FILE_PART_BYTES);
177
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= file.bytes)
178
+ return {
179
+ ok: false,
180
+ error: "offset must be a byte within the file",
181
+ };
182
+ if (
183
+ !Number.isSafeInteger(length) ||
184
+ length < 1 ||
185
+ length > FILE_PART_BYTES
186
+ )
187
+ return {
188
+ ok: false,
189
+ error: `a part is 1 to ${FILE_PART_BYTES} bytes`,
190
+ };
191
+ const part = Buffer.alloc(Math.min(length, file.bytes - offset));
192
+ const fd = fs.openSync(blobPath(file.sha256), "r");
193
+ try {
194
+ fs.readSync(fd, part, 0, part.length, offset);
195
+ } finally {
196
+ fs.closeSync(fd);
197
+ }
198
+ return {
199
+ ok: true,
200
+ file: fileView(file, false),
201
+ offset,
202
+ data: part.toString("base64"),
203
+ };
204
+ }
205
+ // An agent here that can take only an image or text inline gets anything else (a video) by its path alone.
206
+ const inline =
207
+ request.inlineOnly !== true ||
208
+ (/^image\/(png|jpeg|gif|webp)$/.test(file.mime) &&
209
+ file.bytes <= 3.75 * MB) ||
210
+ (textLike(file.mime) && file.bytes <= 200_000);
211
+ // A document's words too, for an agent here whose tools do not read it.
212
+ const words =
213
+ request.inlineOnly === true && isDocument(file.mime)
214
+ ? documentText(namedPath(file), file.mime)
215
+ : null;
216
+ return {
217
+ ok: true,
218
+ file: fileView(file, request.hostedCaller),
219
+ ...(inline
220
+ ? {
221
+ data: fs.readFileSync(blobPath(file.sha256)).toString("base64"),
222
+ }
223
+ : {}),
224
+ ...(words !== null ? { text: words } : {}),
225
+ };
226
+ } else return { ok: false, error: "unknown command" };
227
+ };
228
+ }