tryharness 0.7.32 → 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.
@@ -0,0 +1,737 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { readRunSteps, stopAgentTask } from "./runner.mjs";
5
+ import { provenanceFor } from "./provenance.mjs";
6
+ import { LOCAL_WAKE_AGENTS } from "./wakes.mjs";
7
+ import { aboutOf, member, nameOf, resolveMember } from "./members.mjs";
8
+ import { LIVE_AGENTS, sessionOfProcess } from "./live.mjs";
9
+ import { swarmBlock, swarmDigest } from "./cards.mjs";
10
+ import { PICKABLE, resolvePick, setRunPick } from "./models.mjs";
11
+
12
+ export function createTaskCommands({
13
+ CLOUD_TARGETS,
14
+ OPENED,
15
+ ROOM_AGENTS,
16
+ getActiveRuns,
17
+ boardCommand,
18
+ forwardToHarness,
19
+ frames,
20
+ handleOf,
21
+ inRoom,
22
+ installedAgents,
23
+ lastSeen,
24
+ lessons,
25
+ madeIn,
26
+ getNetwork,
27
+ notifyBoard,
28
+ openTaskRoom,
29
+ openThreadPost,
30
+ pauseGoal,
31
+ placesOf,
32
+ restrictable,
33
+ restrictedWait,
34
+ searchContext,
35
+ setToWait,
36
+ state,
37
+ stopThreadRuns,
38
+ store,
39
+ taskFiles,
40
+ threadFileHits,
41
+ threadMayRun,
42
+ validAgent,
43
+ validRunId,
44
+ windowCannotTake,
45
+ worktrees,
46
+ yourTurns,
47
+ authority,
48
+ actors,
49
+ files: boardFiles,
50
+ }) {
51
+ return (request, { agent, id, expected, lastLooked }) => {
52
+ let outcome;
53
+ if (
54
+ request.command === "board.post" &&
55
+ request.thread &&
56
+ typeof request.thread === "object" &&
57
+ !request.thread[OPENED] &&
58
+ (request.thread.sealed ||
59
+ (request.thread.role === "asker" &&
60
+ store.meta(`relay_pending:${String(request.id || "")}`)))
61
+ ) {
62
+ return {
63
+ pending: openThreadPost(request).then((prepared) => {
64
+ const posted = boardCommand(prepared);
65
+ if (!posted?.ok)
66
+ throw new Error(posted?.error || "the thread was not posted");
67
+ return posted;
68
+ }),
69
+ };
70
+ }
71
+ if (request.command === "board.post") {
72
+ const objective = String(request.objective || "").trim();
73
+ if (!objective) return { ok: false, error: "a task needs an objective" };
74
+ // A thread with another person themselves (not one of their agents) is the person's own: no agent here claims or runs it.
75
+ const personThread =
76
+ Boolean(request.thread) && request.targetAgent === "person";
77
+ if (personThread) request = { ...request, targetAgent: "user" };
78
+ // A target is named the way people write it ("Grok", "Claude Code") and resolved through the roster; a name
79
+ // several members start ("claude") or none matches is refused with who it could be, never guessed.
80
+ if (
81
+ request.targetAgent != null &&
82
+ !personThread &&
83
+ !String(request.targetAgent).includes("/")
84
+ ) {
85
+ const named = resolveMember(request.targetAgent, {
86
+ extra: store
87
+ .agentsSeen()
88
+ .map((row) => row.agent)
89
+ .filter((seen) => !member(seen)),
90
+ });
91
+ if (!named.ok) {
92
+ return {
93
+ ok: false,
94
+ code: "unknown_agent",
95
+ candidates: named.candidates,
96
+ error: named.candidates.length
97
+ ? `"${request.targetAgent}" could be ${named.candidates.map(aboutOf).join("; or ")}. Name one.`
98
+ : `No agent is called "${request.targetAgent}". The agents: ${actors
99
+ .available()
100
+ .filter((name) => name !== agent)
101
+ .join(", ")}.`,
102
+ };
103
+ }
104
+ if (member(named.id) && !member(named.id).target)
105
+ return {
106
+ ok: false,
107
+ code: "not_a_target",
108
+ error: `${nameOf(named.id)} can ask the swarm but cannot be handed work yet.`,
109
+ };
110
+ request = { ...request, targetAgent: named.id };
111
+ }
112
+ if (request.targetAgent != null && !validAgent(request.targetAgent))
113
+ return { ok: false, error: "invalid target agent" };
114
+ // The model and effort the poster names for the run, checked against the agent's own list (models.mjs).
115
+ let pick = null;
116
+ if (request.model) {
117
+ if (!PICKABLE.has(String(request.targetAgent || "")))
118
+ return {
119
+ ok: false,
120
+ error:
121
+ "a model can be named only for one of claude-code, codex, pi or opencode, as target_agent",
122
+ };
123
+ const resolved = resolvePick(
124
+ store,
125
+ String(request.targetAgent),
126
+ request.model,
127
+ request.effort
128
+ );
129
+ if (!resolved.ok) return { ok: false, error: resolved.error };
130
+ pick = resolved.pick;
131
+ }
132
+ // Provenance is code's: the local parent's label and what Harness sent from above the poster can only tighten it.
133
+ const parentTask = request.parentId
134
+ ? store.getTask(String(request.parentId))
135
+ : null;
136
+ const claimed =
137
+ request.provenance &&
138
+ typeof request.provenance === "object" &&
139
+ request.provenance.trust === "agent"
140
+ ? request.provenance
141
+ : null;
142
+ const upstream = parentTask
143
+ ? {
144
+ trust: claimed ? "agent" : parentTask.trust,
145
+ chain: parentTask.origin_chain,
146
+ }
147
+ : claimed;
148
+ const provenance = provenanceFor(agent, upstream, null, {
149
+ personSession: authority.personSession(agent, request.posterPid),
150
+ });
151
+ const goalParent = parentTask?.kind === "goal" ? parentTask : null;
152
+ if (goalParent) {
153
+ if (!inRoom(goalParent, agent))
154
+ return { ok: false, error: `${agent} is not on this goal's team` };
155
+ if (goalParent.status !== "open")
156
+ return { ok: false, error: `the goal is ${goalParent.status}` };
157
+ if (
158
+ request.targetAgent &&
159
+ !goalParent.goal.team.includes(String(request.targetAgent))
160
+ )
161
+ return {
162
+ ok: false,
163
+ error: `${request.targetAgent} is not on this goal's team`,
164
+ };
165
+ if (
166
+ store.failedJobLike(
167
+ goalParent.id,
168
+ objective.slice(0, 500),
169
+ request.targetAgent ? String(request.targetAgent) : null
170
+ )
171
+ ) {
172
+ pauseGoal(
173
+ goalParent.id,
174
+ `${agent} posted again a job that already failed ("${objective.slice(0, 80)}")`
175
+ );
176
+ return {
177
+ ok: false,
178
+ error:
179
+ "that job already failed in this goal; the room is paused for the owner",
180
+ };
181
+ }
182
+ // An ask sent again after it may not have reached Harness was said already (asks.mjs).
183
+ if (request.resend !== true)
184
+ store.roomPost({
185
+ goalId: goalParent.id,
186
+ author: agent,
187
+ kind: "job",
188
+ text: `Posted a job${request.targetAgent ? ` for ${request.targetAgent}` : ""}: ${objective}`,
189
+ mentions: request.targetAgent ? [String(request.targetAgent)] : [],
190
+ });
191
+ }
192
+ if (
193
+ CLOUD_TARGETS.has(String(request.targetAgent || "")) &&
194
+ !request.thread
195
+ ) {
196
+ if (!state.connected)
197
+ return {
198
+ ok: false,
199
+ error: `${request.targetAgent} lives in Harness, and the daemon is not connected to it right now`,
200
+ };
201
+ return forwardToHarness({ ...request, provenance: upstream });
202
+ }
203
+ // Left out, a task from a coding agent for a coding agent runs in the folder the poster works in (its stdio MCP's,
204
+ // which each agent starts in the session's folder); never home or above it.
205
+ const posterFolder =
206
+ !request.thread &&
207
+ !goalParent &&
208
+ request.inSession !== true &&
209
+ authority.RUNNERS.has(agent) &&
210
+ authority.RUNNERS.has(String(request.targetAgent || "")) &&
211
+ typeof request.posterCwd === "string" &&
212
+ path.isAbsolute(request.posterCwd) &&
213
+ !authority.aboveHome(request.posterCwd)
214
+ ? request.posterCwd
215
+ : null;
216
+ // The person's own task for a coding agent that names no folder runs in that agent's scratch folder, so it starts like
217
+ // any covered run (same daily limit, same off switch) instead of waiting for a session to look at the board.
218
+ const target = String(request.targetAgent || "");
219
+ const scratch =
220
+ !request.runWorkspace &&
221
+ !goalParent &&
222
+ !posterFolder &&
223
+ !request.thread &&
224
+ provenance.trust === "user" &&
225
+ authority.RUNNERS.has(target) &&
226
+ installedAgents.includes(target)
227
+ ? authority.scratchFolder(target)
228
+ : null;
229
+ if (scratch) fs.mkdirSync(scratch, { recursive: true });
230
+ const runWorkspace = request.runWorkspace
231
+ ? String(request.runWorkspace)
232
+ : goalParent?.goal.workspace && authority.RUNNERS.has(target)
233
+ ? goalParent.goal.workspace
234
+ : (posterFolder ?? scratch);
235
+ if (runWorkspace && !path.isAbsolute(runWorkspace))
236
+ return {
237
+ ok: false,
238
+ error: "a run needs an absolute workspace directory",
239
+ };
240
+ if (
241
+ runWorkspace &&
242
+ !request.targetAgent &&
243
+ !(Array.isArray(request.targetAgents) && request.targetAgents.length)
244
+ )
245
+ return { ok: false, error: "a run needs a target agent" };
246
+ const refs = Array.isArray(request.contextRefs)
247
+ ? request.contextRefs.slice(0, 50)
248
+ : [];
249
+ // The server may name the task (its run id) so the run record, the session layer and the board agree.
250
+ if (request.id != null && !validRunId(request.id))
251
+ return { ok: false, error: "invalid task id" };
252
+ if (request.id != null && store.getTask(String(request.id)))
253
+ return {
254
+ ok: false,
255
+ error: "a task with this id already exists",
256
+ task: store.getTask(String(request.id)),
257
+ };
258
+ const thread =
259
+ request.thread && typeof request.thread === "object"
260
+ ? request.thread
261
+ : null;
262
+ // A run asked for now, covered or not posted at all: nothing is left waiting that the person did not see.
263
+ if (request.requireStanding === true) {
264
+ const reason =
265
+ thread || !runWorkspace || !request.targetAgent
266
+ ? "a run without a Start needs one target agent and a folder"
267
+ : authority.standingVerdict({
268
+ trust: provenance.trust,
269
+ target: String(request.targetAgent),
270
+ workspace: runWorkspace,
271
+ });
272
+ if (reason)
273
+ return {
274
+ ok: false,
275
+ error: reason,
276
+ standing: { started: false, reason },
277
+ };
278
+ }
279
+ if (
280
+ thread &&
281
+ (!validAgent(thread.with) || !["asker", "target"].includes(thread.role))
282
+ )
283
+ return {
284
+ ok: false,
285
+ error: "a thread needs the other side's agent and a role",
286
+ };
287
+ // Someone whose computer this one has a key for seals its requests: an unsealed one in their name did not come from it.
288
+ if (
289
+ thread &&
290
+ thread.role === "target" &&
291
+ !thread[OPENED] &&
292
+ store.relayPeer(handleOf(thread.with))
293
+ )
294
+ return {
295
+ ok: false,
296
+ error: `${handleOf(thread.with)}'s computer seals its threads; this unsealed one did not come from it`,
297
+ };
298
+ // Several agents at once: one group task with a part per agent.
299
+ const targetAgents = Array.isArray(request.targetAgents)
300
+ ? [...new Set(request.targetAgents.map(String))]
301
+ : null;
302
+ if (targetAgents) {
303
+ if (thread)
304
+ return {
305
+ ok: false,
306
+ error: "a thread with another person has one target",
307
+ };
308
+ if (
309
+ !targetAgents.length ||
310
+ targetAgents.length > 8 ||
311
+ !targetAgents.every(validAgent)
312
+ )
313
+ return {
314
+ ok: false,
315
+ error: "target_agents must be one to eight agent names",
316
+ };
317
+ if (targetAgents.length === 1) request.targetAgent = targetAgents[0];
318
+ else {
319
+ const posted = store.postGroup({
320
+ ...(request.id != null ? { id: String(request.id) } : {}),
321
+ objective: objective.slice(0, 500),
322
+ brief: String(request.brief || "").slice(0, 200000),
323
+ originAgent: agent,
324
+ provenance,
325
+ targetAgents,
326
+ contextRefs: refs,
327
+ runWorkspace,
328
+ runAuthorizedBy: runWorkspace && agent === "user" ? "user" : null,
329
+ });
330
+ for (const part of posted.children) {
331
+ authority.applyStanding(store.getTask(part.id));
332
+ notifyBoard(store.getTask(part.id));
333
+ }
334
+ notifyBoard(posted.group);
335
+ return { ok: true, task: posted.group };
336
+ }
337
+ }
338
+ const task = store.postTask({
339
+ id: request.id != null ? String(request.id) : randomUUID(),
340
+ objective: objective.slice(0, 500),
341
+ brief: String(request.brief || "").slice(0, 200000),
342
+ originAgent: agent,
343
+ provenance,
344
+ targetAgent: request.targetAgent ? String(request.targetAgent) : null,
345
+ parentId: request.parentId ? String(request.parentId) : null,
346
+ contextRefs: refs,
347
+ // Asking for a run in a folder is the person's Start; a scratch folder they never asked for goes by standing permission.
348
+ runWorkspace: thread ? null : runWorkspace,
349
+ runAuthorizedBy:
350
+ !thread && runWorkspace && !scratch && agent === "user"
351
+ ? "user"
352
+ : null,
353
+ });
354
+ if (thread) {
355
+ store.openThread(task.id, {
356
+ withAgent: String(thread.with),
357
+ role: thread.role,
358
+ peerKey:
359
+ thread[OPENED] && thread.peerKey ? String(thread.peerKey) : null,
360
+ });
361
+ getNetwork()?.opened(task.id);
362
+ }
363
+ if (pick) setRunPick(store, task.id, pick, agent);
364
+ // A job in a goal's room runs on the goal's authority; anywhere else, standing permission decides. The goal covers
365
+ // jobs from the person, Harness and the coding agents on this machine, with the person's go (personsGo) unless an
366
+ // agent's words came from above the poster; a job from a member that runs elsewhere (Grok Bot, Muse, a connected
367
+ // app) waits for the person's Start.
368
+ const onGoal =
369
+ agent === "user" ||
370
+ agent === "harness" ||
371
+ (!request.hostedCaller && member(agent)?.runs === "machine");
372
+ const agentWritten = task.trust !== "user";
373
+ const go =
374
+ onGoal &&
375
+ (!agentWritten || (!claimed && !setToWait(String(task.target_agent))));
376
+ const mayStart =
377
+ goalParent &&
378
+ task.run_workspace &&
379
+ threadMayRun(goalParent) &&
380
+ (go || (onGoal && restrictable(task.target_agent, task.run_workspace)));
381
+ const startOnGoal = () => {
382
+ if (go) store.meta(`person-wake:${task.id}`, "1");
383
+ return store.authorizeGoalRun(task.id);
384
+ };
385
+ const standing = thread
386
+ ? undefined
387
+ : goalParent
388
+ ? !task.run_workspace
389
+ ? undefined
390
+ : mayStart && startOnGoal()
391
+ ? {
392
+ started: true,
393
+ by: "goal",
394
+ ...(go ? {} : { restricted: true }),
395
+ }
396
+ : !threadMayRun(goalParent)
397
+ ? undefined
398
+ : {
399
+ started: false,
400
+ reason: !onGoal
401
+ ? `${nameOf(agent)} does not run on this machine, so its job waits for the person's Start.`
402
+ : restrictedWait(String(task.target_agent)),
403
+ }
404
+ : authority.applyStanding(task);
405
+ if (
406
+ !thread &&
407
+ !goalParent &&
408
+ !request.parentId &&
409
+ task.target_agent &&
410
+ task.target_agent !== "harness" &&
411
+ ROOM_AGENTS.includes(task.target_agent)
412
+ )
413
+ openTaskRoom(store.getTask(task.id), agent, provenance, {
414
+ hosted: Boolean(request.hostedCaller),
415
+ });
416
+ const note = task.target_agent
417
+ ? actors.setupNote(task.target_agent)
418
+ : null;
419
+ outcome = {
420
+ ok: true,
421
+ task: store.getTask(task.id),
422
+ thread: thread ? store.getThread(task.id) : null,
423
+ ...(standing ? { standing } : {}),
424
+ ...(note ? { note } : {}),
425
+ };
426
+ } else if (request.command === "board.list") {
427
+ const tasks = store.listTasks({
428
+ agent,
429
+ status: request.status ? String(request.status) : undefined,
430
+ all: request.all === true,
431
+ limit: request.limit,
432
+ });
433
+ const finished =
434
+ agent === "user" || agent === "harness"
435
+ ? []
436
+ : store.finishedFor(agent, lastLooked);
437
+ const extra = finished.length ? { finished } : {};
438
+ // A session starting (nudge.mjs, the Pi and OpenCode plugins) also hears who else is in the swarm.
439
+ if (request.swarm) {
440
+ const local = request.hostedCaller !== true;
441
+ const cards = actors.cardsFor(
442
+ actors.available().filter((name) => name !== agent),
443
+ { lessons: local }
444
+ );
445
+ const told = local ? lessons.told() : [];
446
+ extra.swarm = {
447
+ text: swarmBlock(cards, Date.now(), told),
448
+ digest: swarmDigest(cards, told),
449
+ };
450
+ }
451
+ return request.unread
452
+ ? {
453
+ ok: true,
454
+ tasks,
455
+ ...extra,
456
+ unread: store.unreadFor(agent),
457
+ goals: store.activeGoalsFor(agent).map((goal) => ({
458
+ id: goal.id,
459
+ objective: goal.objective,
460
+ posts: goal.goal.posts,
461
+ })),
462
+ }
463
+ : { ok: true, tasks, ...extra };
464
+ } else if (request.command === "board.context.add") {
465
+ if (!store.getTask(id)) return { ok: false, error: "task not found" };
466
+ const kind = String(request.kind || "note");
467
+ if (!["note", "log", "link", "file", "repro"].includes(kind))
468
+ return {
469
+ ok: false,
470
+ error: "kind must be note, log, link, file or repro",
471
+ };
472
+ const entry = store.addContribution({
473
+ taskId: id,
474
+ kind,
475
+ author: agent,
476
+ text: String(request.text || "").slice(0, 20000),
477
+ source: request.source ? String(request.source).slice(0, 1024) : null,
478
+ });
479
+ return entry
480
+ ? { ok: true, entry, context: store.contextCount(id) }
481
+ : { ok: false, error: "nothing to add" };
482
+ } else if (request.command === "board.context.search") {
483
+ const task = store.getTask(id);
484
+ if (!task) return { ok: false, error: "task not found" };
485
+ const query = String(request.query || "");
486
+ const k = Math.max(
487
+ 1,
488
+ Math.min(20, Number(request.limit ?? request.k) || 8)
489
+ );
490
+ return {
491
+ ok: true,
492
+ pending: Promise.all([
493
+ searchContext(id, query, k),
494
+ threadFileHits(task, query, request.hostedCaller === true),
495
+ ]).then(([found, files]) => ({
496
+ ...found,
497
+ ...(files.length ? { files } : {}),
498
+ })),
499
+ };
500
+ } else if (request.command === "board.get") {
501
+ const task = store.getTask(id);
502
+ const files = task
503
+ ? [...store.taskFiles(id), ...madeIn(task)]
504
+ .filter(
505
+ (file) =>
506
+ boardFiles.visibleFile(file, agent, request.hostedCaller) &&
507
+ (!request.hostedCaller || file.cloud)
508
+ )
509
+ .map((file) => boardFiles.fileView(file, request.hostedCaller))
510
+ : [];
511
+ // What a run did, step by step, when the person asks to see it.
512
+ // Its thread's task frame for an agent on this computer (frames.mjs); it names paths, so never for a hosted caller.
513
+ const frame =
514
+ task && !request.hostedCaller
515
+ ? frames.get(task.kind === "goal" ? id : (task.parent_id ?? ""))
516
+ : null;
517
+ if (task)
518
+ return {
519
+ ok: true,
520
+ task: { ...task, files, ...(frame ? { frame } : {}) },
521
+ ...(request.steps === true
522
+ ? { steps: readRunSteps(taskFiles(id).log, 200) }
523
+ : {}),
524
+ };
525
+ return state.connected
526
+ ? forwardToHarness(request)
527
+ : { ok: false, error: "task not found" };
528
+ } else if (request.command === "board.children")
529
+ return {
530
+ ok: true,
531
+ tasks: store
532
+ .children(id)
533
+ .map((child) => store.getTask(child.id))
534
+ .filter(Boolean),
535
+ };
536
+ else if (request.command === "board.trace")
537
+ return state.connected
538
+ ? forwardToHarness(request)
539
+ : {
540
+ ok: false,
541
+ error:
542
+ "a trace reads the whole chain on this machine and in Harness, and the daemon is not connected to Harness right now",
543
+ };
544
+ else if (request.command === "board.wallet")
545
+ return request.hostedCaller
546
+ ? {
547
+ ok: false,
548
+ error: "the wallet is read only by agents on the person's computer",
549
+ }
550
+ : state.connected
551
+ ? forwardToHarness(request)
552
+ : {
553
+ ok: false,
554
+ error:
555
+ "the wallet lives in Harness, and the daemon is not connected to it right now",
556
+ };
557
+ else if (request.command === "board.standing")
558
+ return { ok: true, standing: authority.standingRules() };
559
+ else if (request.command === "board.standing.check") {
560
+ const reason = authority.standingVerdict({
561
+ trust: "user",
562
+ target: String(request.targetAgent || ""),
563
+ workspace: String(request.workspace || ""),
564
+ });
565
+ return path.isAbsolute(String(request.workspace || ""))
566
+ ? { ok: true, covered: !reason, ...(reason ? { reason } : {}) }
567
+ : { ok: false, error: "a folder must be an absolute path" };
568
+ } else if (
569
+ [
570
+ "board.standing.set",
571
+ "board.standing.off",
572
+ "board.standing.on",
573
+ ].includes(request.command)
574
+ ) {
575
+ if (agent !== "user")
576
+ return {
577
+ ok: false,
578
+ error: "only the person changes standing permission",
579
+ };
580
+ const target = String(request.targetAgent || "");
581
+ if (!authority.RUNNERS.has(target))
582
+ return {
583
+ ok: false,
584
+ error: `standing permission is for a coding agent: ${[...authority.RUNNERS].join(", ")}`,
585
+ };
586
+ if (request.command === "board.standing.off")
587
+ store.setStanding(target, "off");
588
+ else if (request.command === "board.standing.on")
589
+ store.resetStanding(target);
590
+ else {
591
+ const workspaces = Array.isArray(request.workspaces)
592
+ ? [...new Set(request.workspaces.map(String))]
593
+ : [];
594
+ if (!workspaces.length || workspaces.length > 20)
595
+ return { ok: false, error: "name one to twenty folders" };
596
+ const bad = workspaces.find(
597
+ (dir) =>
598
+ !path.isAbsolute(dir) ||
599
+ !fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory()
600
+ );
601
+ if (bad)
602
+ return {
603
+ ok: false,
604
+ error: `${bad} is not an absolute path to a folder`,
605
+ };
606
+ const dailyCap = Number(request.dailyCap);
607
+ if (!Number.isInteger(dailyCap) || dailyCap < 1 || dailyCap > 100)
608
+ return {
609
+ ok: false,
610
+ error: "the daily limit is a whole number from 1 to 100",
611
+ };
612
+ store.setStanding(
613
+ target,
614
+ "named",
615
+ workspaces.map((dir) => path.resolve(dir)),
616
+ dailyCap
617
+ );
618
+ }
619
+ return { ok: true, standing: authority.standingRules() };
620
+ } else if (request.command === "board.agents")
621
+ return {
622
+ ok: true,
623
+ agents: store.agentsSeen(),
624
+ running: [...getActiveRuns().values()].map(
625
+ ({ agent: runAgent, id: taskId }) => ({
626
+ agent: runAgent,
627
+ id: taskId,
628
+ })
629
+ ),
630
+ turns: yourTurns(),
631
+ setup: Object.fromEntries(
632
+ LOCAL_WAKE_AGENTS.map((name) => [name, actors.setupOf(name)])
633
+ ),
634
+ };
635
+ else if (
636
+ ["board.claim", "board.report", "board.answer", "board.release"].includes(
637
+ request.command
638
+ ) &&
639
+ !store.getTask(id) &&
640
+ state.connected
641
+ )
642
+ return forwardToHarness(request);
643
+ else if (
644
+ request.command === "board.claim" &&
645
+ windowCannotTake(request, agent, store.getTask(id))
646
+ )
647
+ return {
648
+ ok: false,
649
+ error:
650
+ "a task given to Harness is taken by an up-to-date Harness window by itself, as its own message; leave it open",
651
+ };
652
+ else if (request.command === "board.claim") {
653
+ outcome = store.claimTask(
654
+ id,
655
+ agent,
656
+ expected,
657
+ Number.isInteger(request.leaseMinutes) ? request.leaseMinutes : 60
658
+ );
659
+ // The person's own session that took it, so the task opens there (its MCP server is a child of that session).
660
+ const claimed = outcome?.ok ? store.getTask(id) : null;
661
+ const reportedBy = (pid) =>
662
+ Object.entries(placesOf(agent)).find(
663
+ ([, place]) => place.pid === pid
664
+ )?.[0] ?? null;
665
+ const session =
666
+ claimed && !claimed.session_id && LIVE_AGENTS.includes(agent)
667
+ ? (sessionOfProcess(
668
+ agent,
669
+ request.claimerPid,
670
+ store.recentSessions(200)
671
+ ) ?? reportedBy(request.claimerPid))
672
+ : null;
673
+ if (session) {
674
+ store.setRunSession(id, session);
675
+ outcome = { ...outcome, task: store.getTask(id) };
676
+ }
677
+ } else if (request.command === "board.report")
678
+ outcome = store.reportTask(
679
+ id,
680
+ agent,
681
+ {
682
+ status: String(request.status || ""),
683
+ result: String(request.result || "").slice(0, 200000),
684
+ },
685
+ expected
686
+ );
687
+ else if (request.command === "board.answer")
688
+ outcome = store.answerTask(
689
+ id,
690
+ agent,
691
+ String(request.answer || "").slice(0, 20000),
692
+ expected
693
+ );
694
+ else if (request.command === "board.release")
695
+ outcome = store.releaseTask(id, agent, expected);
696
+ else if (request.command === "board.remove") {
697
+ if (agent !== "user")
698
+ return {
699
+ ok: false,
700
+ error: "only the person removes work from the board",
701
+ };
702
+ const task = store.getTask(id);
703
+ if (!task || task.removed_at)
704
+ return { ok: false, error: "task not found" };
705
+ if (task.kind === "goal") {
706
+ // A thread's changes are the person's: merged or thrown away on purpose, never lost with the thread.
707
+ const changes = worktrees.summary(id);
708
+ if (changes?.state === "open" && changes.files)
709
+ return {
710
+ ok: false,
711
+ error:
712
+ "this thread has changes that are not merged; merge or discard them first",
713
+ };
714
+ if (task.status === "open") stopThreadRuns(id);
715
+ }
716
+ const removed = store.removeTask(id);
717
+ for (const runId of removed.running) stopAgentTask(runId);
718
+ // Removed on purpose: nothing posts "could not finish" into its thread for it.
719
+ for (const removedId of removed.ids) {
720
+ const gone = store.getTask(removedId);
721
+ lastSeen.set(removedId, {
722
+ ...lastSeen.get(removedId),
723
+ status: gone.status,
724
+ });
725
+ notifyBoard(gone);
726
+ }
727
+ return { ok: true, removed: removed.ids };
728
+ } else if (request.command === "board.run")
729
+ outcome =
730
+ agent === "user"
731
+ ? store.authorizeRun(id, agent)
732
+ : { ok: false, error: "only the user can authorize a run" };
733
+ else return { ok: false, error: "unknown command" };
734
+ if (outcome.ok) notifyBoard(outcome.task);
735
+ return outcome;
736
+ };
737
+ }