tryharness 0.7.45 → 0.7.53

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 (99) hide show
  1. package/README.md +232 -12
  2. package/cli.mjs +406 -184
  3. package/lib/actorRoster.mjs +28 -5
  4. package/lib/adapters.mjs +9 -1
  5. package/lib/agentRuntimeConfig.mjs +36 -0
  6. package/lib/agentRuntimes.mjs +560 -0
  7. package/lib/atlas.mjs +7 -2
  8. package/lib/boardCommands.mjs +5 -10
  9. package/lib/boardFileCommands.mjs +2 -1
  10. package/lib/boardMirror.mjs +459 -0
  11. package/lib/boardProtocol.json +206 -6
  12. package/lib/boardTools.mjs +2 -6
  13. package/lib/bridge.mjs +25 -3
  14. package/lib/browserWake.mjs +60 -0
  15. package/lib/cards.mjs +35 -2
  16. package/lib/commands.mjs +20 -5
  17. package/lib/connectionTools.d.ts +13 -0
  18. package/lib/connectionTools.js +45 -0
  19. package/lib/connectorAuth.mjs +309 -0
  20. package/lib/connectorCatalog.json +41 -0
  21. package/lib/connectorCommands.mjs +121 -0
  22. package/lib/connectorGoogle.mjs +513 -0
  23. package/lib/connectors.mjs +805 -0
  24. package/lib/coordinator.mjs +8 -1
  25. package/lib/coreModels.mjs +78 -0
  26. package/lib/daemon.mjs +643 -45
  27. package/lib/desktop.mjs +7 -2
  28. package/lib/digest.mjs +32 -0
  29. package/lib/directLink.mjs +283 -0
  30. package/lib/environments.mjs +595 -0
  31. package/lib/folders.mjs +2 -2
  32. package/lib/goalCommands.mjs +58 -14
  33. package/lib/inference.mjs +263 -152
  34. package/lib/lessons.mjs +6 -0
  35. package/lib/lineup.mjs +324 -0
  36. package/lib/localmodels.mjs +10 -0
  37. package/lib/machineIdentity.mjs +3 -0
  38. package/lib/machineRoutes.mjs +40 -2
  39. package/lib/machineRuns.mjs +30 -3
  40. package/lib/machineSeal.mjs +69 -10
  41. package/lib/mcp-stdio.mjs +121 -118
  42. package/lib/mcpRelay.mjs +119 -0
  43. package/lib/members.json +12 -0
  44. package/lib/members.mjs +33 -0
  45. package/lib/modelMemory.mjs +100 -0
  46. package/lib/modelTiers.json +1183 -0
  47. package/lib/modelTiers.mjs +133 -0
  48. package/lib/models.mjs +41 -8
  49. package/lib/museSession.mjs +119 -0
  50. package/lib/nativeHost.mjs +203 -0
  51. package/lib/network.mjs +7 -2
  52. package/lib/nudge.mjs +10 -2
  53. package/lib/onboard.mjs +430 -1
  54. package/lib/oneclawLocal.mjs +150 -0
  55. package/lib/ownMachines.mjs +521 -36
  56. package/lib/pairing.mjs +165 -0
  57. package/lib/paths.mjs +4 -0
  58. package/lib/phones.mjs +61 -0
  59. package/lib/placeCommands.mjs +27 -0
  60. package/lib/places.mjs +10 -2
  61. package/lib/plans.mjs +151 -27
  62. package/lib/profile.mjs +152 -0
  63. package/lib/projects.mjs +624 -137
  64. package/lib/readiness.mjs +283 -0
  65. package/lib/repoLinks.mjs +354 -0
  66. package/lib/roomChannels.mjs +641 -0
  67. package/lib/runBrief.mjs +32 -2
  68. package/lib/runRequests.mjs +157 -0
  69. package/lib/runWorker.mjs +20 -7
  70. package/lib/runner.mjs +67 -8
  71. package/lib/secretPatterns.json +55 -0
  72. package/lib/secrets.mjs +10 -27
  73. package/lib/seen.mjs +102 -0
  74. package/lib/service.mjs +11 -6
  75. package/lib/sessionControl.mjs +10 -8
  76. package/lib/sessionIndex.mjs +5 -3
  77. package/lib/store.mjs +546 -29
  78. package/lib/subagents.mjs +8 -4
  79. package/lib/swarm.mjs +367 -37
  80. package/lib/swarmMemory.mjs +947 -0
  81. package/lib/t3.mjs +43 -13
  82. package/lib/taskCommands.mjs +56 -5
  83. package/lib/taskRuns.mjs +61 -11
  84. package/lib/team.json +17 -15
  85. package/lib/team.mjs +68 -18
  86. package/lib/threadRuns.mjs +3 -1
  87. package/lib/threadView.mjs +51 -14
  88. package/lib/tokenizer.mjs +405 -0
  89. package/lib/ui.mjs +16 -2
  90. package/lib/usageTotals.mjs +148 -0
  91. package/lib/vault.mjs +1144 -0
  92. package/lib/vaultCloud.mjs +117 -0
  93. package/lib/vaultCommands.mjs +201 -0
  94. package/lib/vaultTools.d.ts +12 -0
  95. package/lib/vaultTools.js +42 -0
  96. package/lib/windowAsks.mjs +42 -0
  97. package/lib/workFocus.mjs +59 -0
  98. package/lib/workLinks.mjs +90 -0
  99. package/package.json +9 -4
@@ -0,0 +1,165 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import { spawnSync } from "node:child_process";
4
+ import { loadMachine, saveMachine } from "./machineIdentity.mjs";
5
+ import { newPairCode, pairClaim } from "./machineSeal.mjs";
6
+
7
+ // Connecting a computer to the person's Harness account (src/server/bridge/pairHub.ts is the other end): setup asks
8
+ // Harness to hold a pairing, shows the code, and waits on one held stream until the person approves it, which releases
9
+ // this computer's connection token down that stream.
10
+ //
11
+ // Setup makes the code itself, and it is one code for the whole join (machineSeal.mjs): approving it in a signed-in
12
+ // browser connects this computer to the account, and typing it on a computer already connected (the buddy's Add a
13
+ // computer) also brings it into the swarm, because the daemon here takes it as its join code. Harness hears only the
14
+ // code's first 4 characters and proof of the whole. A Harness from before this takes neither and makes a code of its
15
+ // own (an 8-character one, for the account only).
16
+ //
17
+ // Once connected, a computer Harness added to an account that already has a home waits here until home confirms it
18
+ // with the same code (joinSwarm).
19
+
20
+ /** Ask Harness to hold a pairing for this computer. Returns { pairId, code, own } (own: setup made the code). */
21
+ export async function startPairing(origin, agents) {
22
+ // The name the computer goes by everywhere else (machineIdentity.mjs).
23
+ const hostname = os
24
+ .hostname()
25
+ .replace(/\.local$/, "")
26
+ .slice(0, 64);
27
+ const start = (body) =>
28
+ fetch(origin + "/api/pair/start", {
29
+ method: "POST",
30
+ headers: { "content-type": "application/json" },
31
+ body: JSON.stringify(body),
32
+ signal: AbortSignal.timeout(15_000),
33
+ });
34
+ for (let attempt = 0; attempt < 3; attempt++) {
35
+ const code = newPairCode();
36
+ const response = await start({ hostname, agents, ...pairClaim(code) });
37
+ // Another computer's setup holds a code with the same first 4 characters.
38
+ if (response.status === 409) continue;
39
+ if (response.status === 400) break;
40
+ if (!response.ok)
41
+ throw new Error(`pairing unavailable (HTTP ${response.status})`);
42
+ const { pairId } = await response.json();
43
+ return { pairId, code, own: true };
44
+ }
45
+ const response = await start({ hostname, agents });
46
+ if (!response.ok)
47
+ throw new Error(`pairing unavailable (HTTP ${response.status})`);
48
+ const { pairId, code } = await response.json();
49
+ return { pairId, code, own: false };
50
+ }
51
+
52
+ /** Keep setup's code for the daemon, which takes it as this computer's join code. */
53
+ export function keepJoinCode(machineFile, code) {
54
+ saveMachine(machineFile, { ...loadMachine(machineFile), joinCode: code });
55
+ }
56
+
57
+ /** Wait for the person's approval. Resolves with the connection token; rejects on expiry or a dropped stream. */
58
+ export async function waitForApproval(origin, pairId) {
59
+ const response = await fetch(origin + "/api/pair/wait/" + pairId, {
60
+ headers: { accept: "text/event-stream" },
61
+ });
62
+ if (!response.ok || !response.body) throw new Error("pairing stream failed");
63
+ const reader = response.body.getReader();
64
+ const decoder = new TextDecoder();
65
+ let buffer = "";
66
+ for (;;) {
67
+ const { done, value } = await reader.read();
68
+ if (done) break;
69
+ buffer += decoder.decode(value, { stream: true });
70
+ const frames = buffer.split("\n\n");
71
+ buffer = frames.pop() || "";
72
+ for (const frame of frames) {
73
+ const line = frame
74
+ .split("\n")
75
+ .find((entry) => entry.startsWith("data: "));
76
+ if (!line) continue;
77
+ const payload = JSON.parse(line.slice(6));
78
+ if (payload.token) return payload.token;
79
+ if (payload.error) throw new Error(payload.error);
80
+ }
81
+ }
82
+ throw new Error("pairing stream ended without approval");
83
+ }
84
+
85
+ // A computer that runs on a battery sleeps with its lid; one without stays on, and the board is reachable only while
86
+ // the computer holding it is on (ownMachines.mjs). Unknown reads as a battery, so nothing is suggested.
87
+ export function hasBattery() {
88
+ if (process.platform === "darwin")
89
+ return /InternalBattery/.test(
90
+ spawnSync("pmset", ["-g", "batt"], { encoding: "utf8" }).stdout || ""
91
+ );
92
+ if (process.platform === "linux") {
93
+ try {
94
+ return fs
95
+ .readdirSync("/sys/class/power_supply")
96
+ .some((name) => name.startsWith("BAT"));
97
+ } catch {
98
+ return true;
99
+ }
100
+ }
101
+ return true;
102
+ }
103
+
104
+ const JOIN_WAIT_MS = 10 * 60_000;
105
+ // How long a computer approved from home's buddy usually takes to be confirmed there, before setup says where to type.
106
+ const JOIN_QUIET_MS = 8_000;
107
+
108
+ /**
109
+ * After the daemon connects: Harness has made this computer home (the first on the account) or added it. An added one
110
+ * waits until home confirms it with the same code, then may be offered home when it suits that better. Returns the
111
+ * role. `daemonRequest` reaches this computer's daemon.
112
+ */
113
+ export async function joinSwarm({
114
+ ui,
115
+ code,
116
+ daemonRequest,
117
+ battery = hasBattery,
118
+ quietMs = JOIN_QUIET_MS,
119
+ waitMs = JOIN_WAIT_MS,
120
+ }) {
121
+ const read = () =>
122
+ daemonRequest({ command: "machines.list" }).catch(() => null);
123
+ let listed = await read();
124
+ if (!listed?.ok || listed.self.role !== "worker") return "home";
125
+ const homeName = () =>
126
+ listed.machines.find((machine) => machine.role === "home")?.label ||
127
+ "your home computer";
128
+ if (listed.joinCode) {
129
+ const spin = ui.spinner();
130
+ spin.start(`Joining your swarm on ${homeName()}`);
131
+ const started = Date.now();
132
+ let told = false;
133
+ while (listed?.joinCode && Date.now() - started < waitMs) {
134
+ if (!told && Date.now() - started > quietMs) {
135
+ told = true;
136
+ spin.message(
137
+ `Waiting for ${homeName()}. There, click the Harness icon in the menu bar, choose Add a Computer, and type ${listed.joinCode}${listed.joinCode === code ? " (the same code)" : ""}. Or run there: npx tryharness machines add ${listed.joinCode}`
138
+ );
139
+ }
140
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
141
+ listed = (await read()) ?? listed;
142
+ }
143
+ if (listed.joinCode) {
144
+ spin.stop(
145
+ `Not in your swarm yet. On ${homeName()}, run: npx tryharness machines add ${listed.joinCode}`,
146
+ 2
147
+ );
148
+ return "worker";
149
+ }
150
+ spin.stop(`Joined your swarm. ${homeName()} holds the board.`);
151
+ } else ui.success(`In your swarm. ${homeName()} holds the board.`);
152
+ if (!ui.interactive || battery()) return "worker";
153
+ const move = await ui.confirm({
154
+ message: `This computer stays on, so work could go on here while ${homeName()} sleeps. Make it your main computer? Your threads and board so far stay on ${homeName()}.`,
155
+ initialValue: false,
156
+ });
157
+ if (!move) return "worker";
158
+ const moved = await daemonRequest({ command: "machines.home" }, 20_000);
159
+ if (!moved.ok) {
160
+ ui.warn(`Not moved: ${moved.error}`);
161
+ return "worker";
162
+ }
163
+ ui.success("This is your main computer now.");
164
+ return "home";
165
+ }
package/lib/paths.mjs CHANGED
@@ -18,7 +18,11 @@ export const paths = {
18
18
  : path.join(harnessHome, "daemon.sock"),
19
19
  log: path.join(harnessHome, "daemon.log"),
20
20
  phoneIdentity: path.join(harnessHome, "phone-identity.json"),
21
+ // The browser link setup makes for the page that approves this computer (phones.mjs writeBrowserOffer).
22
+ browserOffer: path.join(harnessHome, "browser-offer.json"),
21
23
  machine: path.join(harnessHome, "machine.json"),
24
+ // The person's name and preferences from their Harness profile (profile.mjs).
25
+ profile: path.join(harnessHome, "profile.json"),
22
26
  runs: path.join(harnessHome, "runs"),
23
27
  files: path.join(harnessHome, "files"),
24
28
  runtime: path.join(harnessHome, "runtime"),
package/lib/phones.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  import os from "node:os";
2
+ import fs from "node:fs";
2
3
  import { randomBytes } from "node:crypto";
4
+ import { readJson, writeJsonAtomic } from "./files.mjs";
3
5
  import { boardCommandsFor } from "./boardProtocol.mjs";
4
6
  import {
5
7
  b64u,
@@ -40,6 +42,8 @@ const BROWSER_READS = boardCommandsFor("browserReads");
40
42
  export async function createPhoneDesk({
41
43
  store,
42
44
  identityFile,
45
+ // A browser link setup made before this daemon ran (writeBrowserOffer): taken in once, then the file is gone.
46
+ setupOfferFile = null,
43
47
  boardCommand,
44
48
  reads = {},
45
49
  version,
@@ -52,6 +56,14 @@ export async function createPhoneDesk({
52
56
  const keys = new Map();
53
57
  const hostname = os.hostname().slice(0, 64);
54
58
 
59
+ const setupOffer = setupOfferFile ? takeSetupOffer(setupOfferFile) : null;
60
+ if (setupOffer)
61
+ offers.set(setupOffer.offerId, {
62
+ secret: setupOffer.secret,
63
+ kind: "browser",
64
+ expiresAt: setupOffer.expiresAt,
65
+ });
66
+
55
67
  const sweep = () => {
56
68
  const now = Date.now();
57
69
  for (const [id, offer] of offers)
@@ -239,6 +251,12 @@ export async function createPhoneDesk({
239
251
  const command = String(callInput?.command || "");
240
252
  if (command === "phone.hello")
241
253
  return { ok: true, hostname, version, kind: device.kind };
254
+ // A device sends a file's bytes. A path names a file already on this computer, which only an agent here may attach.
255
+ if (command === "board.file.add" && callInput?.path != null)
256
+ return {
257
+ ok: false,
258
+ error: "a phone or browser attaches a file's content, not a path",
259
+ };
242
260
  if (device.kind === "browser") {
243
261
  if (LANE_COMMANDS.has(command)) {
244
262
  if (!lane || callInput.as === "harness")
@@ -298,6 +316,12 @@ export async function createPhoneDesk({
298
316
  agent: as,
299
317
  // A Harness window's own call, which daemon.mjs checks before it takes a task given to Harness.
300
318
  fromWindow: as === "harness",
319
+ // A connected app's or a secret's call from Harness's window is hosted, whatever the browser says: grants
320
+ // that keep an app's content or a secret's use on this computer stay here (connectors.mjs, vault.mjs).
321
+ ...(as === "harness" &&
322
+ /^board\.(connector|vault)\./.test(String(command))
323
+ ? { hostedCaller: true }
324
+ : {}),
301
325
  ...(writtenBy.length
302
326
  ? { provenance: { trust: "agent", chain: writtenBy } }
303
327
  : {}),
@@ -413,3 +437,40 @@ export async function createPhoneDesk({
413
437
  identity,
414
438
  };
415
439
  }
440
+
441
+ // Setup's browser link (cli.mjs): the page that approves this computer links the same browser in the same step, so
442
+ // setup makes the offer itself, before the daemon runs, and puts it in that page's address fragment with the pairing
443
+ // code. The daemon takes it in when it starts. Same secret, key, ten minutes and one use as a link the daemon makes.
444
+ export async function writeBrowserOffer({ identityFile, offerFile }) {
445
+ const identity = await loadOrCreateIdentity(identityFile);
446
+ const offer = {
447
+ offerId: b64u(randomBytes(16)),
448
+ secret: b64u(randomBytes(32)),
449
+ expiresAt: Date.now() + OFFER_TTL_MS,
450
+ };
451
+ writeJsonAtomic(offerFile, offer);
452
+ return new URLSearchParams({
453
+ v: "1",
454
+ o: offer.offerId,
455
+ s: offer.secret,
456
+ k: identity.publicKey,
457
+ // The name the computer goes by everywhere else (pairing.mjs, machineIdentity.mjs).
458
+ h: os
459
+ .hostname()
460
+ .replace(/\.local$/, "")
461
+ .slice(0, 64),
462
+ }).toString();
463
+ }
464
+
465
+ function takeSetupOffer(file) {
466
+ const offer = readJson(file, null);
467
+ try {
468
+ fs.unlinkSync(file);
469
+ } catch {}
470
+ return offer &&
471
+ ID.test(String(offer.offerId)) &&
472
+ typeof offer.secret === "string" &&
473
+ offer.expiresAt > Date.now()
474
+ ? offer
475
+ : null;
476
+ }
@@ -0,0 +1,27 @@
1
+ // Places on the person's computer: the desktop buddy reaches the outside networks its swarm is in through this
2
+ // daemon, which asks Harness over its bridge (`place_op`, src/server/places/places.ts). Harness holds each place's key
3
+ // and makes every request; this side only carries the person's ops. Only the person ("user") calls these: agents
4
+ // use the `place` tool, which Harness answers itself.
5
+
6
+ export function createPlaceCommands({ askHarness }) {
7
+ const command = (request, agent) => {
8
+ if (agent !== "user")
9
+ return { ok: false, error: "only the person manages places from here" };
10
+ if (request.command !== "board.place.op")
11
+ return { ok: false, error: `unknown command ${request.command}` };
12
+ const { command: _command, agent: _agent, ...input } = request;
13
+ return {
14
+ pending: askHarness("place_op", input).then(
15
+ (answer) =>
16
+ answer.ok
17
+ ? answer
18
+ : {
19
+ ok: false,
20
+ error: answer.error || "Harness refused the request",
21
+ },
22
+ (error) => ({ ok: false, error: error.message })
23
+ ),
24
+ };
25
+ };
26
+ return { command };
27
+ }
package/lib/places.mjs CHANGED
@@ -336,8 +336,16 @@ const AGENTS = {
336
336
  link: (scheme, id) => `${scheme}://openai.chatgpt/local/${id}`,
337
337
  },
338
338
  },
339
- pi: { command: "pi", resume: "pi --session" },
340
- opencode: { command: "opencode", resume: "opencode --session" },
339
+ pi: { command: "pi", resume: "pi --session", t3: "pi" },
340
+ opencode: {
341
+ command: "opencode",
342
+ resume: "opencode --session",
343
+ t3: "opencode",
344
+ },
345
+ cursor: { command: "cursor-agent", t3: "cursor" },
346
+ "grok-build": { command: "grok", t3: "grok" },
347
+ antigravity: { command: "agy_acp_server.par", t3: "antigravity" },
348
+ "muse-code": { command: "muse", t3: "muse" },
341
349
  };
342
350
  export const agentCommand = (agent) => AGENTS[agent]?.command ?? null;
343
351
  /** An agent's provider in T3 Code ("claudeAgent", "codex"); null for an agent T3 does not run. */
package/lib/plans.mjs CHANGED
@@ -5,6 +5,9 @@
5
5
  // The person wires nodes on the buddy's canvas; agents do it with post_task's `after`; a template is the same nodes
6
6
  // and wires as JSON, with {{blanks}} filled in when it is used. A node can only wait on work that exists or on nodes
7
7
  // given with it, so no wiring can loop.
8
+ // The person's drafts are plan nodes too, kept here so every device that shows the thread (the buddy, the phone) sees
9
+ // and edits the same ones: a draft's agent, prompt and wiring can change, and nothing of it starts until the person
10
+ // runs it, when it waits like any other node.
8
11
  import fs from "node:fs";
9
12
  import path from "node:path";
10
13
  import { randomUUID } from "node:crypto";
@@ -31,6 +34,20 @@ const blanksIn = (texts) => [
31
34
  ),
32
35
  ];
33
36
 
37
+ /** What a node is asked, from its prompt: the first line is its objective, a longer prompt is its brief. */
38
+ function askOf(node, key) {
39
+ const objective = words(node?.objective || node?.prompt)
40
+ .split("\n")[0]
41
+ .slice(0, 500);
42
+ const brief = words(
43
+ node?.brief ?? (words(node?.prompt).includes("\n") ? node.prompt : "")
44
+ );
45
+ if (!objective) return { error: `node ${key} asks nothing` };
46
+ if ((objective + brief).length > PROMPT_LIMIT)
47
+ return { error: `node ${key}'s prompt is over ${PROMPT_LIMIT} characters` };
48
+ return { objective, brief };
49
+ }
50
+
34
51
  /** Nodes in an order where each comes after everything it waits on, or null when the wiring loops. */
35
52
  function ordered(nodes, waitsOn) {
36
53
  const byKey = new Map(nodes.map((node) => [node.key, node]));
@@ -252,10 +269,15 @@ export function createPlans({
252
269
  return plan;
253
270
  }
254
271
 
255
- /** Adds nodes to a thread's plan; those waiting on nothing (or only on finished work) start at once. */
256
- function add(threadId, by, given) {
272
+ /**
273
+ * Adds nodes to a thread's plan; those waiting on nothing (or only on finished work) start at once. As drafts they
274
+ * start only when the person runs them.
275
+ */
276
+ function add(threadId, by, given, { draft = false } = {}) {
257
277
  const thread = threadOf(threadId);
258
278
  if (!thread) return { ok: false, error: "thread not found" };
279
+ if (draft && by !== "user")
280
+ return { ok: false, error: "only the person keeps drafts" };
259
281
  if (!Array.isArray(given) || !given.length)
260
282
  return { ok: false, error: "no nodes to add" };
261
283
  const plan = planOf(thread.id);
@@ -274,23 +296,13 @@ export function createPlans({
274
296
  ok: false,
275
297
  error: `${agent || "no one"} cannot be in a thread`,
276
298
  };
277
- const objective = words(node?.objective || node?.prompt)
278
- .split("\n")[0]
279
- .slice(0, 500);
280
- const brief = words(
281
- node?.brief ?? (words(node?.prompt).includes("\n") ? node.prompt : "")
282
- );
283
- if (!objective) return { ok: false, error: `node ${key} asks nothing` };
284
- if ((objective + brief).length > PROMPT_LIMIT)
285
- return {
286
- ok: false,
287
- error: `node ${key}'s prompt is over ${PROMPT_LIMIT} characters`,
288
- };
299
+ const asked = askOf(node, key);
300
+ if (asked.error) return { ok: false, error: asked.error };
289
301
  nodes.push({
290
302
  key,
291
303
  agent,
292
- objective,
293
- brief,
304
+ objective: asked.objective,
305
+ brief: asked.brief,
294
306
  after: Array.isArray(node?.after) ? node.after.map(String) : [],
295
307
  });
296
308
  }
@@ -319,17 +331,20 @@ export function createPlans({
319
331
  objective: node.objective,
320
332
  brief: node.brief,
321
333
  after: node.after.map((ref) => ids.get(ref) ?? ref),
322
- state: "waiting",
334
+ state: draft ? "draft" : "waiting",
323
335
  at,
324
336
  });
325
337
  savePlan(thread.id, plan);
326
- const settled = settle(thread.id);
338
+ return outcome(thread.id, ids);
339
+ }
340
+
341
+ /** What became of nodes just added or run: the tasks that started, the nodes still waiting or kept as drafts. */
342
+ function outcome(threadId, ids) {
343
+ const settled = settle(threadId);
327
344
  const mine = settled.filter((node) => [...ids.values()].includes(node.id));
328
345
  return {
329
346
  ok: true,
330
- nodes: Object.fromEntries(
331
- nodes.map((node) => [node.key, ids.get(node.key)])
332
- ),
347
+ nodes: Object.fromEntries(ids),
333
348
  started: mine.filter((node) => node.taskId).map((node) => node.taskId),
334
349
  waiting: mine
335
350
  .filter((node) => node.state === "waiting")
@@ -337,9 +352,97 @@ export function createPlans({
337
352
  blocked: mine
338
353
  .filter((node) => node.state === "blocked")
339
354
  .map((node) => ({ id: node.id, reason: node.reason })),
355
+ drafts: mine
356
+ .filter((node) => node.state === "draft")
357
+ .map((node) => node.id),
340
358
  };
341
359
  }
342
360
 
361
+ /** Whether `ref` is something a node in this thread may wait on: another plan node, or a task in the thread. */
362
+ const waitable = (threadId, plan, ref) =>
363
+ plan.some((other) => other.id === ref) ||
364
+ store.getTask(ref)?.parent_id === threadId;
365
+ const loops = (plan) => {
366
+ const ids = new Set(plan.map((node) => node.id));
367
+ return !ordered(
368
+ plan.map((node) => ({ key: node.id, after: node.after })),
369
+ (node) => node.after.filter((ref) => ids.has(ref))
370
+ );
371
+ };
372
+
373
+ /** A draft's agent, prompt or wiring (`change`), changed by the person. */
374
+ function edit(threadId, nodeId, change) {
375
+ const thread = threadOf(threadId);
376
+ if (!thread) return { ok: false, error: "thread not found" };
377
+ const plan = planOf(thread.id);
378
+ const node = plan.find((n) => n.id === String(nodeId || ""));
379
+ if (!node) return { ok: false, error: "no such step" };
380
+ if (node.state !== "draft")
381
+ return { ok: false, error: "only a draft can change" };
382
+ const next = { ...node };
383
+ if (change.agent !== undefined) {
384
+ const agent = words(change.agent);
385
+ if (!roomAgents.includes(agent))
386
+ return {
387
+ ok: false,
388
+ error: `${agent || "no one"} cannot be in a thread`,
389
+ };
390
+ next.agent = agent;
391
+ }
392
+ if (change.prompt !== undefined) {
393
+ const asked = askOf({ prompt: change.prompt }, node.key);
394
+ if (asked.error) return { ok: false, error: asked.error };
395
+ next.objective = asked.objective;
396
+ next.brief = asked.brief;
397
+ }
398
+ if (change.after !== undefined) {
399
+ if (!Array.isArray(change.after))
400
+ return { ok: false, error: "after is a list" };
401
+ const after = [...new Set(change.after.map(String))];
402
+ for (const ref of after) {
403
+ if (ref === node.id)
404
+ return { ok: false, error: "a step cannot wait for itself" };
405
+ if (!waitable(thread.id, plan, ref))
406
+ return { ok: false, error: `${ref} is not work in this thread` };
407
+ }
408
+ next.after = after;
409
+ }
410
+ const changed = plan.map((n) => (n.id === node.id ? next : n));
411
+ if (loops(changed))
412
+ return { ok: false, error: "the wires go round in a loop" };
413
+ savePlan(thread.id, changed);
414
+ return { ok: true };
415
+ }
416
+
417
+ /** The person's drafts set going: the ones named (all of them when none are) and every draft they wait for. */
418
+ function run(threadId, named) {
419
+ const thread = threadOf(threadId);
420
+ if (!thread) return { ok: false, error: "thread not found" };
421
+ const plan = planOf(thread.id);
422
+ const drafts = plan.filter((node) => node.state === "draft");
423
+ const wanted = Array.isArray(named) ? named.map(String) : null;
424
+ if (wanted?.some((id) => !drafts.some((node) => node.id === id)))
425
+ return { ok: false, error: "that is not a draft here" };
426
+ const chosen = new Set();
427
+ const visit = (node) => {
428
+ if (chosen.has(node)) return;
429
+ chosen.add(node);
430
+ for (const ref of node.after) {
431
+ const up = drafts.find((other) => other.id === ref);
432
+ if (up) visit(up);
433
+ }
434
+ };
435
+ for (const node of drafts)
436
+ if (!wanted || wanted.includes(node.id)) visit(node);
437
+ if (!chosen.size) return { ok: false, error: "no drafts to run" };
438
+ for (const node of chosen) node.state = "waiting";
439
+ savePlan(thread.id, plan);
440
+ return outcome(
441
+ thread.id,
442
+ new Map([...chosen].map((node) => [node.id, node.id]))
443
+ );
444
+ }
445
+
343
446
  // ── Templates, kept with the daemon so agents can use them too ────────────────
344
447
  const templateFile = (name) => path.join(folder, `${slugOf(name)}.json`);
345
448
  function templates() {
@@ -377,7 +480,7 @@ export function createPlans({
377
480
  };
378
481
 
379
482
  /** Puts a template's nodes into a thread, its blanks filled; the nodes with nothing wired into them start now. */
380
- function fromTemplate(threadId, by, checked, values = {}) {
483
+ function fromTemplate(threadId, by, checked, values = {}, options = {}) {
381
484
  const empty = checked.blanks.filter((name) => !words(values[name]));
382
485
  if (empty.length)
383
486
  return {
@@ -400,7 +503,8 @@ export function createPlans({
400
503
  after: checked.template.wires
401
504
  .filter((w) => w.to === node.key)
402
505
  .map((w) => w.from),
403
- }))
506
+ })),
507
+ options
404
508
  );
405
509
  }
406
510
 
@@ -419,6 +523,7 @@ export function createPlans({
419
523
  by,
420
524
  agent,
421
525
  objective,
526
+ brief,
422
527
  after,
423
528
  state,
424
529
  reason,
@@ -430,6 +535,8 @@ export function createPlans({
430
535
  by,
431
536
  agent,
432
537
  objective,
538
+ // A draft's whole prompt, so whoever edits it starts from what was written.
539
+ ...(state === "draft" ? { prompt: brief || objective } : {}),
433
540
  after,
434
541
  state,
435
542
  reason: reason ?? null,
@@ -453,7 +560,16 @@ export function createPlans({
453
560
  command(request, agent) {
454
561
  const command = String(request.command);
455
562
  if (command === "board.plan.add")
456
- return add(request.id, agent, request.nodes);
563
+ return add(request.id, agent, request.nodes, {
564
+ draft: request.draft === true,
565
+ });
566
+ if (command === "board.plan.edit")
567
+ return (
568
+ personOnly(agent) ??
569
+ edit(request.id, request.node, request.change ?? {})
570
+ );
571
+ if (command === "board.plan.run")
572
+ return personOnly(agent) ?? run(request.id, request.nodes);
457
573
  if (command === "board.plan.remove") {
458
574
  const refused = personOnly(agent);
459
575
  if (refused) return refused;
@@ -465,8 +581,9 @@ export function createPlans({
465
581
  ok: false,
466
582
  error: "that step has started; stop it in the thread",
467
583
  };
584
+ // Drafts wired to it are only drafts: they lose the wire. A step already set going would wait forever.
468
585
  const waiting = plan.filter(
469
- (n) => n.after.includes(node.id) && !n.taskId
586
+ (n) => n.after.includes(node.id) && !n.taskId && n.state !== "draft"
470
587
  );
471
588
  if (waiting.length)
472
589
  return {
@@ -475,7 +592,13 @@ export function createPlans({
475
592
  };
476
593
  savePlan(
477
594
  String(request.id),
478
- plan.filter((n) => n.id !== node.id)
595
+ plan
596
+ .filter((n) => n.id !== node.id)
597
+ .map((n) =>
598
+ n.state === "draft"
599
+ ? { ...n, after: n.after.filter((ref) => ref !== node.id) }
600
+ : n
601
+ )
479
602
  );
480
603
  return { ok: true };
481
604
  }
@@ -530,7 +653,8 @@ export function createPlans({
530
653
  request.id,
531
654
  agent,
532
655
  checked,
533
- request.fill && typeof request.fill === "object" ? request.fill : {}
656
+ request.fill && typeof request.fill === "object" ? request.fill : {},
657
+ { draft: request.draft === true }
534
658
  );
535
659
  }
536
660
  return { ok: false, error: `unknown command ${command}` };