tryharness 0.7.64 → 0.7.66

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.
@@ -3,7 +3,12 @@ import path from "node:path";
3
3
  import { randomBytes, randomUUID } from "node:crypto";
4
4
  import { documentText, ensureDir, isDocument, mimeFor } from "./files.mjs";
5
5
  import { FILE_PART_BYTES } from "./boardFiles.mjs";
6
- import { fingerprint } from "./sealed.mjs";
6
+ import {
7
+ fingerprint,
8
+ MAX_SKEW_MS,
9
+ open as openSealed,
10
+ seal,
11
+ } from "./sealed.mjs";
7
12
  import { nameOf } from "./members.mjs";
8
13
  import {
9
14
  isPairCode,
@@ -37,11 +42,20 @@ import { MERGE_COMMAND, MIRROR_COMMAND } from "./boardMirror.mjs";
37
42
  import { DEVICES_COMMAND } from "./swarmDevices.mjs";
38
43
  import { member } from "./members.mjs";
39
44
  import { WINDOW_TOOLS } from "./windowAsks.mjs";
45
+ import { createCallSessions } from "./callSessions.mjs";
46
+ import { VIEW_COMMAND, VIEW_DROP_COMMAND } from "./liveViews.mjs";
40
47
 
41
48
  export { FROM_MACHINE };
42
49
 
43
50
  // A worker's key for a direct link, swapped for home's over the sealed channel (directLink.mjs).
44
51
  const DIRECT_COMMAND = "machine.direct";
52
+ // A worker asking home for a session for its calls through Harness (callSessions.mjs).
53
+ const SESSION_COMMAND = "machine.session";
54
+ // A call over the direct link, as it is: the link's own encryption admits only the pinned computer (directLink.mjs).
55
+ const DIRECT_CALL = "call.direct";
56
+ // Home's views for a worker (liveViews.mjs): their kind on the direct link, and the direction they are sealed for.
57
+ const VIEWS_KIND = "views";
58
+ const VIEWS_SEAL = "h2v";
45
59
  // The person's model and effort for an agent live on the computer that runs it (models.mjs reads its own store), so
46
60
  // the buddy's Swarm tab reads and sets them on each computer: a worker asks home, home asks the worker that has it.
47
61
  const MODELS_COMMAND = "machine.models";
@@ -118,6 +132,9 @@ const textLike = (mime) =>
118
132
  export function createOwnMachines({
119
133
  store,
120
134
  log,
135
+ // On home: the views it keeps for its computers; on a worker: its copies of them (liveViews.mjs). Made after this.
136
+ liveViews = () => null,
137
+ viewCopies = () => null,
121
138
  machine,
122
139
  saveMachine,
123
140
  identity,
@@ -637,6 +654,7 @@ export function createOwnMachines({
637
654
  const forget = (id) => {
638
655
  store.unpinOwnMachine(id);
639
656
  directLink?.disallow?.(id);
657
+ callSessions.end(id);
640
658
  infos.delete(id);
641
659
  store.meta(`bring-armed:${id}`, "");
642
660
  if (store.meta("stood-in-by") === id) store.meta("stood-in-by", "");
@@ -1178,6 +1196,8 @@ export function createOwnMachines({
1178
1196
  const pinned = pinnedHome();
1179
1197
  if (flushing || !pinned) return;
1180
1198
  flushing = true;
1199
+ // Home is back, perhaps updated: a home that had no sessions is asked again.
1200
+ if (session?.id === "none") session = null;
1181
1201
  try {
1182
1202
  for (;;) {
1183
1203
  const [next, ...rest] = outbox();
@@ -1247,10 +1267,66 @@ export function createOwnMachines({
1247
1267
  return { ...rest, command, agent };
1248
1268
  };
1249
1269
 
1270
+ // A call to home: over the direct link as it is, else through Harness sealed in a session, under one request id on
1271
+ // both roads so home answers it once (owner, October 28). A home older than sessions takes it sealed on its own.
1250
1272
  const callOnce = async (pinned, call) => {
1251
- const { key, requestId, envelope } = await send(pinned, call);
1273
+ const requestId = newRequestId();
1274
+ return (
1275
+ (await directCall(pinned, requestId, call)) ??
1276
+ (await sessionCall(pinned, requestId, call))
1277
+ );
1278
+ };
1279
+ const directCall = async (pinned, requestId, call) => {
1280
+ if (!directLink) return null;
1281
+ const reply = await directLink.request(pinned.machine_id, {
1282
+ kind: DIRECT_CALL,
1283
+ body: { requestId, call },
1284
+ });
1285
+ return reply && "answer" in reply ? reply.answer : null;
1286
+ };
1287
+ const sealedCall = async (pinned, requestId, call, session = null) => {
1288
+ const key = await keyFor(pinned.public_key, machine.id);
1289
+ const envelope = await sealCall(key, machine.id, requestId, call, {
1290
+ session,
1291
+ });
1252
1292
  return deliver(key, requestId, envelope);
1253
1293
  };
1294
+ // The session home gave this computer: { home, id }, a handshake in flight, or "none" for a home without sessions.
1295
+ let session = null;
1296
+ const sessionWith = (pinned) => {
1297
+ if (session?.home === pinned.machine_id) return session.id;
1298
+ const asking = (async () => {
1299
+ const answer = await sealedCall(pinned, newRequestId(), {
1300
+ command: SESSION_COMMAND,
1301
+ agent: "user",
1302
+ });
1303
+ const id =
1304
+ answer?.ok === true && typeof answer.session === "string"
1305
+ ? answer.session
1306
+ : answer
1307
+ ? "none"
1308
+ : null;
1309
+ session = id ? { home: pinned.machine_id, id } : null;
1310
+ return id;
1311
+ })();
1312
+ session = { home: pinned.machine_id, id: asking };
1313
+ return asking;
1314
+ };
1315
+ const sessionCall = async (pinned, requestId, call, again = true) => {
1316
+ const id = await sessionWith(pinned);
1317
+ if (!id) return null;
1318
+ const answer = await sealedCall(
1319
+ pinned,
1320
+ requestId,
1321
+ call,
1322
+ id === "none" ? null : id
1323
+ );
1324
+ if (answer?.code === "session_expired" && again) {
1325
+ if (session?.id === id) session = null;
1326
+ return sessionCall(pinned, requestId, call, false);
1327
+ }
1328
+ return answer;
1329
+ };
1254
1330
 
1255
1331
  // A file on this computer goes to home as its bytes, in parts a sealed call carries.
1256
1332
  const attach = async (pinned, request) => {
@@ -1411,6 +1487,8 @@ export function createOwnMachines({
1411
1487
  // (the second was once refused as a replay and the agent told its write failed).
1412
1488
  const answered = new Map();
1413
1489
  const ANSWERS_KEPT = 500;
1490
+ // The sessions home holds for its computers' calls through Harness (callSessions.mjs).
1491
+ const callSessions = createCallSessions();
1414
1492
  const once = (key, run) => {
1415
1493
  if (answered.has(key)) return answered.get(key);
1416
1494
  const answer = run();
@@ -1443,6 +1521,8 @@ export function createOwnMachines({
1443
1521
  from,
1444
1522
  firstSeen: (requestId) =>
1445
1523
  store.firstPhoneRequest(`machine:${from}`, String(requestId)),
1524
+ inSession: (session, requestId) =>
1525
+ callSessions.take(from, session, String(requestId)),
1446
1526
  });
1447
1527
  // A call that opened but is stale or already taken is answered sealed, so the worker can trust the refusal.
1448
1528
  if (!opened.ok)
@@ -1458,15 +1538,44 @@ export function createOwnMachines({
1458
1538
  };
1459
1539
  const call = opened.call ?? {};
1460
1540
  const command = String(call.command || "");
1461
- const result = await answerOpened(from, pinned, call, command);
1541
+ // A call in a session may already have come over the direct link, under the same request id: answered once.
1542
+ const result = opened.session
1543
+ ? await answerOnce(from, body.envelope.requestId, () =>
1544
+ answerOpened(from, pinned, call, command)
1545
+ )
1546
+ : await answerOpened(from, pinned, call, command);
1462
1547
  return {
1463
1548
  envelope: await sealAnswer(key, from, body.envelope.requestId, result),
1464
1549
  };
1465
1550
  };
1551
+ const answerOnce = (from, requestId, run) =>
1552
+ once(`request:${from}:${requestId}`, run);
1553
+ /** On home: a call over the direct link from that computer, answered as it came (the link said who sent it). */
1554
+ const answerDirect = async (from, body) => {
1555
+ const pinned = store.ownMachine(String(from));
1556
+ const requestId = String(body?.requestId ?? "");
1557
+ if (!isHome() || !pinned || !/^[\w-]{8,64}$/.test(requestId))
1558
+ return { ok: false, error: "home takes only its own computers' calls" };
1559
+ const call = body?.call ?? {};
1560
+ return {
1561
+ answer: await answerOnce(from, requestId, () =>
1562
+ answerOpened(from, pinned, call, String(call.command || ""))
1563
+ ),
1564
+ };
1565
+ };
1466
1566
  // What home does with a call it opened from another of the person's computers: the computers' own exchanges, else the
1467
1567
  // board, as far as that computer may ask (computerMay).
1468
1568
  const answerOpened = async (from, pinned, call, command) => {
1469
1569
  if (command === DIRECT_COMMAND) return swapDirectKeys(from, call.key);
1570
+ if (command === SESSION_COMMAND)
1571
+ return { ok: true, session: callSessions.start(from) };
1572
+ if (command === VIEW_COMMAND || command === VIEW_DROP_COMMAND) {
1573
+ const views = liveViews();
1574
+ if (!views) return { ok: false, error: "home keeps no views" };
1575
+ return command === VIEW_COMMAND
1576
+ ? views.subscribe(from, { ...(call.request ?? {}), agent: call.agent })
1577
+ : views.drop(from, Array.isArray(call.ids) ? call.ids : []);
1578
+ }
1470
1579
  // Answered for the computer that sealed it, and only for a link allowed for that computer.
1471
1580
  if (command === LINK_COMMAND)
1472
1581
  return answerLink
@@ -1566,11 +1675,74 @@ export function createOwnMachines({
1566
1675
  isHome()
1567
1676
  ? body?.kind === "call"
1568
1677
  ? answerCall(peerId, body.body)
1569
- : Promise.resolve({ ok: false, error: "home takes only calls" })
1570
- : ["notice", "ask"].includes(body?.kind) &&
1571
- peerId === pinnedHome()?.machine_id
1572
- ? relay({ from: "home", kind: body.kind, body: body.body })
1573
- : Promise.resolve({ ok: false, error: "a worker takes only home's" });
1678
+ : body?.kind === DIRECT_CALL
1679
+ ? answerDirect(peerId, body.body)
1680
+ : Promise.resolve({ ok: false, error: "home takes only calls" })
1681
+ : body?.kind === VIEWS_KIND && peerId === pinnedHome()?.machine_id
1682
+ ? Promise.resolve(onViews(body.body))
1683
+ : ["notice", "ask"].includes(body?.kind) &&
1684
+ peerId === pinnedHome()?.machine_id
1685
+ ? relay({ from: "home", kind: body.kind, body: body.body })
1686
+ : Promise.resolve({ ok: false, error: "a worker takes only home's" });
1687
+
1688
+ /** On home: a read answered as that computer's own call would be (liveViews.mjs keeps it as a view). */
1689
+ const answerAs = async (workerId, request) => {
1690
+ const pinned = store.ownMachine(String(workerId));
1691
+ if (!isHome() || !pinned) throw new Error("that computer is not confirmed");
1692
+ return answerOpened(
1693
+ workerId,
1694
+ pinned,
1695
+ { ...request, agent: request.agent ?? "user" },
1696
+ String(request.command || "")
1697
+ );
1698
+ };
1699
+ /**
1700
+ * On home: what changed in a computer's views (liveViews.mjs). Over the direct link as it is; through Harness sealed
1701
+ * for that computer as a notice Harness already carries ("h2v", read only as views), with when it was sent, so an old
1702
+ * one is set aside. Whether it arrived.
1703
+ */
1704
+ const pushViews = async (workerId, body) => {
1705
+ const pinned = store.ownMachine(String(workerId));
1706
+ if (!isHome() || !pinned) return false;
1707
+ const direct = directLink
1708
+ ? await directLink.request(workerId, { kind: VIEWS_KIND, body })
1709
+ : null;
1710
+ if (direct) return direct.ok === true;
1711
+ const key = await keyFor(pinned.public_key, workerId);
1712
+ const envelope = await seal(key, VIEWS_SEAL, workerId, newRequestId(), {
1713
+ ts: Date.now(),
1714
+ views: body.views,
1715
+ mirror: body.mirror === true,
1716
+ });
1717
+ const answer = await ask("machine_relay", {
1718
+ to: workerId,
1719
+ kind: "notice",
1720
+ body: { envelope },
1721
+ }).catch(() => null);
1722
+ return answer?.ok === true && !answer.queued;
1723
+ };
1724
+ // On a worker: home's push, applied to this computer's copies; one saying the board moved catches its copy up.
1725
+ const onViews = (body) => {
1726
+ const copies = viewCopies();
1727
+ if (!copies) return { ok: false, error: "no views here" };
1728
+ if (body?.mirror === true) onNotice({ mirror: true });
1729
+ return copies.onPush(body);
1730
+ };
1731
+ // On a worker: home's views, from the home this computer follows, opened and handed to its copies; null when the
1732
+ // envelope is not views.
1733
+ const openViews = async (envelope) => {
1734
+ const pinned = pinnedHome();
1735
+ if (!pinned || envelope?.deviceId !== machine.id) return null;
1736
+ try {
1737
+ const key = await keyFor(pinned.public_key, machine.id);
1738
+ const opened = await openSealed(key, VIEWS_SEAL, envelope);
1739
+ if (Math.abs(Date.now() - Number(opened.ts)) > MAX_SKEW_MS)
1740
+ return { ok: true };
1741
+ return onViews({ views: opened.views, mirror: opened.mirror === true });
1742
+ } catch {
1743
+ return null;
1744
+ }
1745
+ };
1574
1746
 
1575
1747
  /** On home: a notice for a worker (a run to stop), kept by Harness while it is offline. */
1576
1748
  const noticeTo = async (workerId, notice) => {
@@ -1610,6 +1782,8 @@ export function createOwnMachines({
1610
1782
  return null;
1611
1783
  };
1612
1784
  const onNoticeFromHome = async (body) => {
1785
+ const views = await openViews(body?.envelope);
1786
+ if (views) return views;
1613
1787
  const opened = await openNoticeFromAny(body);
1614
1788
  if (!opened) return { ok: false };
1615
1789
  const { from, notice } = opened;
@@ -1683,7 +1857,16 @@ export function createOwnMachines({
1683
1857
  sibling.role === "worker" &&
1684
1858
  (sibling.connected || linked.has(sibling.id))
1685
1859
  ))
1686
- if (store.ownMachine(worker.id)) void noticeTo(worker.id, notice);
1860
+ if (store.ownMachine(worker.id)) void tellWorker(worker.id, notice);
1861
+ };
1862
+ // "The board moved" goes with home's pushes, which keep no request ids (liveViews.mjs); a worker older than them is
1863
+ // sent the sealed notice.
1864
+ const tellWorker = async (workerId, notice) => {
1865
+ const pushed =
1866
+ notice?.mirror === true && Object.keys(notice).length === 1
1867
+ ? await pushViews(workerId, { views: [], mirror: true })
1868
+ : false;
1869
+ if (!pushed) await noticeTo(workerId, notice);
1687
1870
  };
1688
1871
 
1689
1872
  // ---- the person's Harness windows on the other computers ----
@@ -2368,7 +2551,16 @@ export function createOwnMachines({
2368
2551
  * turn this computer cannot take itself. Null when there is none (the turn waits for the agent here, as before).
2369
2552
  */
2370
2553
  const placeElsewhere = (agent, workspace) => {
2371
- const repository = isHome() && workspace ? repositoryOf(workspace) : null;
2554
+ if (!isHome()) return null;
2555
+ // A thread with no folder needs no repository: any computer with the agent takes it, in its own scratch folder
2556
+ // (scratch.mjs, machineRuns.mjs).
2557
+ if (!workspace) {
2558
+ const sibling = siblings.find(
2559
+ (each) => each.agents.includes(agent) && store.ownMachine(each.id)
2560
+ );
2561
+ return sibling ? { machine: sibling.id, folder: null } : null;
2562
+ }
2563
+ const repository = repositoryOf(workspace);
2372
2564
  if (!repository) return null;
2373
2565
  for (const sibling of siblings) {
2374
2566
  if (!sibling.agents.includes(agent) || !store.ownMachine(sibling.id))
@@ -2392,7 +2584,8 @@ export function createOwnMachines({
2392
2584
  return { error: `${label} is not connected` };
2393
2585
  if (!sibling.agents.includes(agent))
2394
2586
  return { error: `${nameOf(agent)} is not on ${label}` };
2395
- const repository = workspace ? repositoryOf(workspace) : null;
2587
+ if (!workspace) return { machine: id, folder: null };
2588
+ const repository = repositoryOf(workspace);
2396
2589
  const folder = repository
2397
2590
  ? infos.get(id)?.folders.find((each) => each.repository === repository)
2398
2591
  ?.path
@@ -2481,6 +2674,8 @@ export function createOwnMachines({
2481
2674
  callHome,
2482
2675
  relay,
2483
2676
  noticeTo,
2677
+ answerAs,
2678
+ pushViews,
2484
2679
  askWorkerWindows,
2485
2680
  linkCall,
2486
2681
  tellWorkers,
package/lib/phones.mjs CHANGED
@@ -175,6 +175,8 @@ export async function createPhoneDesk({
175
175
  // person's decision on one made elsewhere is carried out.
176
176
  devices = () => null,
177
177
  origin = () => null,
178
+ // Where what a linked window did to this computer is written (daemon.log).
179
+ log = () => {},
178
180
  }) {
179
181
  const identity = await loadOrCreateIdentity(identityFile);
180
182
  const offers = new Map();
@@ -640,6 +642,10 @@ export async function createPhoneDesk({
640
642
  if (!lane || callInput.as === "harness")
641
643
  return { ok: false, error: `a browser cannot call ${command} here` };
642
644
  if (command === "harness.lane.status") return lane.status();
645
+ // Which window gave or took back the lane, so a lane that went missing can be traced (October 28).
646
+ log(
647
+ `harness lane: ${command.slice("harness.lane.".length)} from ${device.label} (${device.id})`
648
+ );
643
649
  return command === "harness.lane.forget"
644
650
  ? lane.forget()
645
651
  : lane.share({
@@ -0,0 +1,39 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { paths } from "./paths.mjs";
4
+
5
+ // A thread with no folder works in a scratch folder of its own, on whichever of the person's computers takes its turn
6
+ // (owner, October 28): the thread's files and nothing else, so its agents need none of the person's repositories. The
7
+ // same place on every computer, under that computer's own Harness folder.
8
+
9
+ /** Where a thread's scratch folder is on this computer. */
10
+ export const threadScratch = (threadId) =>
11
+ path.join(
12
+ paths.home,
13
+ "work",
14
+ "threads",
15
+ String(threadId).replace(/[^\w-]/g, "")
16
+ );
17
+
18
+ /**
19
+ * The thread's scratch folder made, with each of `files` ({ name, path }) put in it under its own name: a hard link to
20
+ * the bytes this computer keeps, else a copy. A name already there keeps what it holds (an agent may have changed it).
21
+ */
22
+ export function prepareScratch(threadId, files = []) {
23
+ const dir = threadScratch(threadId);
24
+ fs.mkdirSync(dir, { recursive: true });
25
+ for (const file of files) {
26
+ const name = path.basename(String(file.name || "")).replace(/^\.+/, "");
27
+ if (!name || !file.path) continue;
28
+ const target = path.join(dir, name);
29
+ if (fs.existsSync(target)) continue;
30
+ try {
31
+ fs.linkSync(file.path, target);
32
+ } catch {
33
+ try {
34
+ fs.copyFileSync(file.path, target);
35
+ } catch {}
36
+ }
37
+ }
38
+ return dir;
39
+ }
package/lib/store.mjs CHANGED
@@ -472,6 +472,10 @@ export function openStore(file) {
472
472
  db.exec("alter table phone_requests add column sealed_by text");
473
473
  db.exec("alter table phone_requests add column gesture integer");
474
474
  }
475
+ // Forgetting old request ids finds them by age instead of reading every one: the person's computers send a few a second.
476
+ db.exec(
477
+ "create index if not exists phone_requests_received_idx on phone_requests(received_at)"
478
+ );
475
479
  // A thread whose other side's computer holds a key: everything on it goes sealed to that key.
476
480
  if (
477
481
  !db
@@ -570,6 +574,7 @@ export function openStore(file) {
570
574
  run: (...values) => call("run", values),
571
575
  };
572
576
  };
577
+ let phoneRequestsPrunedAt = 0;
573
578
  const execute = (method, sql, ...values) => {
574
579
  const bound = bindings(values);
575
580
  return bound === undefined ? db[method](sql) : db[method](sql, bound);
@@ -2598,12 +2603,13 @@ export function openStore(file) {
2598
2603
  !this.meta(`task-room:${goal.id}`)
2599
2604
  );
2600
2605
  },
2606
+ // A turn of a thread with no folder on another computer names none: that computer makes its own scratch folder.
2601
2607
  authorizeGoalRun(id) {
2602
2608
  const now = new Date().toISOString();
2603
2609
  return (
2604
2610
  execute(
2605
2611
  "run",
2606
- "update board_tasks set run_authorized_by = 'goal', run_authorized_at = @now, updated_at = @now, version = version + 1 where id = @id and status = 'open' and run_workspace is not null and run_authorized_at is null",
2612
+ "update board_tasks set run_authorized_by = 'goal', run_authorized_at = @now, updated_at = @now, version = version + 1 where id = @id and status = 'open' and (run_workspace is not null or (kind = 'wake' and target_machine is not null)) and run_authorized_at is null",
2607
2613
  { id, now }
2608
2614
  ).changes === 1
2609
2615
  );
@@ -3517,18 +3523,22 @@ export function openStore(file) {
3517
3523
  )
3518
3524
  );
3519
3525
  },
3520
- // A request id is accepted once per phone, across restarts; ids older than the queue's 7 days are forgotten.
3526
+ // A request id is accepted once per phone, across restarts; ids older than the queue's 7 days are forgotten, an
3527
+ // hour's worth at a time, so a call does not pay for the forgetting.
3521
3528
  firstPhoneRequest(
3522
3529
  deviceId,
3523
3530
  requestId,
3524
3531
  { sealedBy = null, gesture = null } = {}
3525
3532
  ) {
3526
3533
  const now = new Date();
3527
- execute(
3528
- "run",
3529
- "delete from phone_requests where received_at < ?",
3530
- new Date(now.getTime() - 8 * 24 * 60 * 60 * 1000).toISOString()
3531
- );
3534
+ if (now.getTime() - phoneRequestsPrunedAt > 60 * 60 * 1000) {
3535
+ phoneRequestsPrunedAt = now.getTime();
3536
+ execute(
3537
+ "run",
3538
+ "delete from phone_requests where received_at < ?",
3539
+ new Date(now.getTime() - 8 * 24 * 60 * 60 * 1000).toISOString()
3540
+ );
3541
+ }
3532
3542
  if (
3533
3543
  execute(
3534
3544
  "get",
package/lib/t3.mjs CHANGED
@@ -483,12 +483,19 @@ const matching = (provider, model) => {
483
483
  * looked up with T3's search. An older T3 lists every model and leaves out none, so it is never searched.
484
484
  */
485
485
  async function selectionFor({ instanceId, model, effort } = {}) {
486
- if (!model) return null;
487
486
  const offering = async (args) =>
488
487
  (await t3Tool("orchestrator_capabilities", args)).providers?.find(
489
488
  (entry) => entry.providerInstanceId === instanceId
490
489
  );
491
490
  const listed = await offering({});
491
+ // T3 lists every agent it knows, an agent switched off or not installed there too ("Pi default", with its
492
+ // constraints): such a turn runs where the caller can run the agent itself.
493
+ if (listed?.constraints?.length)
494
+ throw new T3Error(
495
+ "unavailable",
496
+ `T3 Code can't run ${listed.displayName ?? instanceId} (${listed.constraints.join(" ")})`
497
+ );
498
+ if (!model) return null;
492
499
  const searched =
493
500
  !matching(listed, model) && listed?.omittedModels
494
501
  ? await offering({ search: model })
@@ -698,8 +705,13 @@ export function runInT3(run, emit, observe) {
698
705
  void read();
699
706
  } catch (error) {
700
707
  // T3 Code did not answer before the turn began, though it was there a moment before (twice a turn failed this way
701
- // while T3 was running): where the caller can run the agent itself, it does.
702
- if (error.code === "not_running" && !runId && run.fallback && !stopped) {
708
+ // while T3 was running), or it can't run this agent: where the caller can run the agent itself, it does.
709
+ if (
710
+ ["not_running", "unavailable"].includes(error.code) &&
711
+ !runId &&
712
+ run.fallback &&
713
+ !stopped
714
+ ) {
703
715
  letGo();
704
716
  run.fallback(error.message);
705
717
  return;
@@ -282,13 +282,50 @@ export function createThreadActions({
282
282
  * looks again; loose work is also told to whoever posted it (the person on the desktop, an agent in the work's room
283
283
  * or on the task, and by a wake where it can be woken). A claim past its lease still tells the person on the desktop.
284
284
  */
285
+ /**
286
+ * A claim past its lease with no report is let go and offered to its agent again, once; the second time the person
287
+ * is asked (owner, October 28: a Harness turn lost in a daemon restart and Grok Bot's silent claim held a thread
288
+ * for hours). A Harness turn still running here is alive, whatever its lease says.
289
+ */
290
+ const retryLapsed = (finding) => {
291
+ const { task } = finding;
292
+ // A thread's part only (what the owner decided); loose work keeps showing stale until its poster or the person acts.
293
+ if (!finding.thread) return false;
294
+ const retries = `lease-retries:${task.id}`;
295
+ if (Number(store.meta(retries) || 0) >= 1) return false;
296
+ if (
297
+ finding.agent === "harness" &&
298
+ harness.turnOf(task.parent_id) === task.id
299
+ )
300
+ return false;
301
+ const released = boardCommand()({
302
+ command: "board.release",
303
+ agent: "user",
304
+ id: task.id,
305
+ });
306
+ if (!released?.ok) return false;
307
+ store.meta(retries, "1");
308
+ if (finding.agent === "harness") harness.reofferAll();
309
+ else wakeAgain(finding.agent, task.id);
310
+ notifyBoard(store.getTask(task.id));
311
+ return true;
312
+ };
313
+
285
314
  const tellStuck = (finding) => {
286
315
  const { task } = finding;
316
+ const thread = finding.thread ? store.getTask(finding.thread) : null;
317
+ if (finding.kind === "lease" && retryLapsed(finding)) {
318
+ if (thread)
319
+ say(
320
+ thread,
321
+ `${finding.text} It was let go and offered to ${nameOf(finding.agent)} again.`
322
+ );
323
+ return;
324
+ }
287
325
  if (finding.kind === "lease")
288
326
  notices.notify(
289
- `${nameOf(finding.agent)} stopped checking in on: ${String(task.objective).slice(0, 80)}. Release it from the buddy or your phone.`
327
+ `${nameOf(finding.agent)} stopped checking in again on: ${String(task.objective).slice(0, 80)}. Release it from the buddy or your phone, or give it to another agent.`
290
328
  );
291
- const thread = finding.thread ? store.getTask(finding.thread) : null;
292
329
  if (thread) say(thread, finding.text);
293
330
  // Work posted on its own lives in a room of its own (task-room): it is still loose work, told to its poster too.
294
331
  const loose = !thread || store.meta(`task-room:${thread.id}`) === task.id;
@@ -9,6 +9,7 @@ import { t3Access, steerT3Run } from "./t3.mjs";
9
9
  import { t3Model, t3Open, t3Project, t3Provider } from "./places.mjs";
10
10
  import { within } from "./folders.mjs";
11
11
  import { namedFiles } from "./worktrees.mjs";
12
+ import { prepareScratch } from "./scratch.mjs";
12
13
 
13
14
  // The agents with a read-only switch (runner.mjs): only they talk out a clash in a shared project without waiting.
14
15
  const REVIEWERS = new Set(
@@ -43,12 +44,17 @@ export function createThreadRuns({
43
44
  // Stops a run in progress where it runs: on this computer, or on the one that took it (a sealed notice from home).
44
45
  // Whether it was stopping.
45
46
  stopRun = () => false,
47
+ // A folder-less thread's files ({ name, path }), put in its scratch folder when a turn starts here (scratch.mjs).
48
+ threadFiles = () => [],
46
49
  }) {
47
50
  const { RUNNERS } = authority;
48
51
  const inT3 = (thread, agent, review) => {
49
52
  if (review || !t3Provider(agent) || !thread.goal.workspace) return false;
50
53
  const tree = worktrees.get(thread.id);
51
- if (tree?.state === "t3") return true;
54
+ // An agent works where the person uses it most (homeOf), whichever agent's turn put the thread's checkout in T3
55
+ // Code: only one whose home is T3 is handed there, and any other works here in the same checkout. Pi, used only in
56
+ // a terminal, was handed to T3 because Claude Code's turn had moved the thread there, and its turn failed.
57
+ if (tree?.state === "t3") return homeOf(agent)?.kind === "t3";
52
58
  // A task's room works in place, which T3 does in its project's own checkout; a thread carrying on a terminal
53
59
  // session in place resumes that session here.
54
60
  const movable =
@@ -380,18 +386,8 @@ export function createThreadRuns({
380
386
  : null);
381
387
  if (!installedAgents.includes(agent) && !elsewhere) return;
382
388
  const goal = task.goal;
383
- if (!goal.workspace) {
384
- if (!store.meta(`goal-folder-note:${goalId}:${agent}`)) {
385
- store.meta(`goal-folder-note:${goalId}:${agent}`, "1");
386
- store.roomPost({
387
- goalId,
388
- author: "harness",
389
- kind: "note",
390
- text: `${nameOf(agent)} cannot start: this thread has no folder to work in. Choose one for the thread in Harness, or: npx tryharness goal folder ${goalId} <dir>`,
391
- });
392
- }
393
- return;
394
- }
389
+ // A thread with no folder works in its own scratch folder on whichever computer takes the turn (scratch.mjs).
390
+ const scratch = !goal.workspace;
395
391
  if (store.openWake(goalId, agent)) {
396
392
  if (fromAnotherPerson(asker))
397
393
  store.meta(`other-person-run:${store.openWake(goalId, agent)}`, "1");
@@ -454,7 +450,10 @@ export function createThreadRuns({
454
450
  // works on its own branch here, never in T3's checkout.
455
451
  const t3 = !elsewhere && !shared && inT3(task, agent, review);
456
452
  // The person uses this agent in T3 Code but this turn runs here: the thread says why, once for each reason.
457
- const gap = t3 || review || elsewhere ? null : t3Gap(agent, goal.workspace);
453
+ const gap =
454
+ t3 || review || elsewhere || scratch
455
+ ? null
456
+ : t3Gap(agent, goal.workspace);
458
457
  if (gap && !store.meta(`t3-gap-note:${goalId}:${agent}:${gap}`)) {
459
458
  store.meta(`t3-gap-note:${goalId}:${agent}:${gap}`, "1");
460
459
  store.roomPost({
@@ -465,7 +464,10 @@ export function createThreadRuns({
465
464
  });
466
465
  }
467
466
  let folder = elsewhere?.folder ?? goal.workspace;
468
- if (!t3 && !elsewhere)
467
+ // Another computer makes its own scratch folder for the turn (machineRuns.mjs), so none is named for it here.
468
+ if (scratch)
469
+ folder = elsewhere ? null : prepareScratch(goalId, threadFiles(task));
470
+ else if (!t3 && !elsewhere)
469
471
  try {
470
472
  folder =
471
473
  (shared ? shared.folderFor(task, agent, { review }) : null) ??