tryharness 0.7.62 → 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({
package/lib/runner.mjs CHANGED
@@ -9,7 +9,7 @@ import { agentEnvironment } from "./agentnode.mjs";
9
9
  import { runtimeOf } from "./agentRuntimeConfig.mjs";
10
10
  import { runProtocolTask } from "./agentRuntimes.mjs";
11
11
  import { scrubValues } from "./vault.mjs";
12
- import { paths } from "./paths.mjs";
12
+ import { historyRoots, paths } from "./paths.mjs";
13
13
 
14
14
  const running = new Set();
15
15
  const children = new Map();
@@ -234,6 +234,33 @@ const MODEL_FLAGS = {
234
234
  effort: (level) => ["--variant", level],
235
235
  },
236
236
  };
237
+ // Pi keeps each session in `<sessions>/<project>/<time>_<id>.jsonl`. Given only an id, Pi asks on the terminal whether
238
+ // to fork a session from another folder, and a non-interactive run cannot answer; given the file, it opens it. With
239
+ // no file, the run starts a new session: an id Pi can't find ends the run.
240
+ const piSessionFile = (sessionId) => {
241
+ const name = `_${sessionId}.jsonl`;
242
+ for (const root of historyRoots("pi")) {
243
+ let projects = [];
244
+ try {
245
+ projects = fs.readdirSync(root, { withFileTypes: true });
246
+ } catch {
247
+ continue;
248
+ }
249
+ for (const project of projects) {
250
+ if (!project.isDirectory()) continue;
251
+ const folder = path.join(root, project.name);
252
+ let files = [];
253
+ try {
254
+ files = fs.readdirSync(folder);
255
+ } catch {
256
+ continue;
257
+ }
258
+ const file = files.find((entry) => entry.endsWith(name));
259
+ if (file) return path.join(folder, file);
260
+ }
261
+ }
262
+ return null;
263
+ };
237
264
  const modelFlags = ({ agent, model, effort }) => [
238
265
  ...(model ? (MODEL_FLAGS[agent]?.model(model) ?? []) : []),
239
266
  ...(effort ? (MODEL_FLAGS[agent]?.effort(effort) ?? []) : []),
@@ -386,7 +413,10 @@ export function agentInvocation(task) {
386
413
  // Pi has no permission prompts. --approve trusts project-local configuration for
387
414
  // this non-interactive run; its complete built-in tool set remains enabled. Another
388
415
  // person's ask ignores project-local files instead (--no-approve).
389
- if (task.agent === "pi")
416
+ if (task.agent === "pi") {
417
+ const session = task.resumeSession
418
+ ? piSessionFile(task.resumeSession)
419
+ : null;
390
420
  return {
391
421
  command: "pi",
392
422
  args: [
@@ -394,10 +424,12 @@ export function agentInvocation(task) {
394
424
  "json",
395
425
  task.ownSettingsOnly ? "--no-approve" : "--approve",
396
426
  ...modelFlags(task),
427
+ ...(session ? ["--session", session] : []),
397
428
  "-p",
398
429
  task.brief,
399
430
  ],
400
431
  };
432
+ }
401
433
  if (task.agent === "opencode") {
402
434
  return {
403
435
  command: "opencode",
@@ -756,6 +788,7 @@ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
756
788
  continue;
757
789
  }
758
790
  const sessionId =
791
+ (event.type === "session" ? event.id : null) ||
759
792
  event.session_id ||
760
793
  event.sessionId ||
761
794
  event.sessionID ||
@@ -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
+ }
@@ -422,6 +422,13 @@ export function createSessionControl({
422
422
  return app ? { name: path.basename(app, ".app"), app } : setupTerminal();
423
423
  };
424
424
  const lastResort = () => personTerminal() ?? { name: "Terminal", app: null };
425
+ // DeepSeek Harness and Muse Code take no session to resume from a terminal: their sessions reopen only in their own
426
+ // apps. Open starts the agent in the session's folder there instead, and says it is not that session.
427
+ const startsFresh = (agentId, sessionId) =>
428
+ Boolean(sessionId && agentCommand(agentId)) &&
429
+ !resumeLine(agentId, sessionId);
430
+ const freshNote = (agentId, where) =>
431
+ `${nameOf(agentId)} can't be opened at an earlier session from Harness, so it starts fresh in ${where}. Its earlier sessions are in its own app.`;
425
432
  const terminalPlace = ({ name, app }) => ({ kind: "terminal", name, app });
426
433
 
427
434
  // An agent's home: the place most of its sessions started in over the last thirty days (ties: the latest), where its
@@ -647,22 +654,30 @@ export function createSessionControl({
647
654
  : { opensIn: name, note: busy };
648
655
  // In a Neovim of theirs still open (this one first, else the latest they used the agent in), in a new tab; with
649
656
  // none open, the buddy opens their terminal with Neovim running the session.
650
- const command = sessionId
651
- ? resumeLine(agentId, sessionId)
652
- : agentCommand(agentId);
657
+ const fresh = startsFresh(agentId, sessionId);
658
+ const command =
659
+ sessionId && !fresh
660
+ ? resumeLine(agentId, sessionId)
661
+ : agentCommand(agentId);
653
662
  for (const open of act ? neovimsFor(agentId, place) : []) {
654
663
  const shown = resumeInNeovim(open.server, command, folder);
655
- if (shown) return { opensIn: name, ...focusTerminal(shown, open) };
664
+ if (shown)
665
+ return {
666
+ opensIn: name,
667
+ ...focusTerminal(shown, open),
668
+ ...(fresh ? { note: freshNote(agentId, name) } : {}),
669
+ };
656
670
  }
657
671
  return {
658
672
  opensIn: name,
659
673
  resume: {
660
674
  agent: agentId,
661
- session: sessionId ?? null,
675
+ session: fresh ? null : (sessionId ?? null),
662
676
  cwd: folder ?? null,
663
677
  app: place.app ?? null,
664
678
  within: "nvim",
665
679
  },
680
+ ...(fresh ? { note: freshNote(agentId, name) } : {}),
666
681
  };
667
682
  }
668
683
  if (place.kind === "terminal") {
@@ -671,14 +686,16 @@ export function createSessionControl({
671
686
  return place.app
672
687
  ? { opensIn: name, app: place.app, note: busy }
673
688
  : { opensIn: name, note: busy };
689
+ const fresh = startsFresh(agentId, sessionId);
674
690
  return {
675
691
  opensIn: name,
676
692
  resume: {
677
693
  agent: agentId,
678
- session: sessionId ?? null,
694
+ session: fresh ? null : (sessionId ?? null),
679
695
  cwd: folder ?? null,
680
696
  app: place.app ?? null,
681
697
  },
698
+ ...(fresh ? { note: freshNote(agentId, name) } : {}),
682
699
  };
683
700
  }
684
701
  return place.app ? { opensIn: name, app: place.app } : null;
@@ -841,9 +858,11 @@ export function createSessionControl({
841
858
  placePlan(agentId, homeOf(agentId), sessionId, where, act) ??
842
859
  placePlan(agentId, usable(own), sessionId, where, act);
843
860
  if (plan) return plan;
844
- // Nothing else shows it (T3 never had it, say): the exact session, picked up in the person's terminal.
845
- if (CODING_AGENTS.includes(agentId)) {
861
+ // Nothing else shows it (T3 never had it, say): the exact session, picked up in the person's terminal; an agent
862
+ // that can't resume one there starts in its folder.
863
+ if (CODING_AGENTS.includes(agentId) || startsFresh(agentId, sessionId)) {
846
864
  const terminal = lastResort();
865
+ const fresh = startsFresh(agentId, sessionId);
847
866
  // Until Harness may send into T3, a thread's runs happen in Harness's own copy of the repo, which T3 doesn't list.
848
867
  const inCopy =
849
868
  sessionId &&
@@ -854,10 +873,11 @@ export function createSessionControl({
854
873
  opensIn: terminal.name,
855
874
  resume: {
856
875
  agent: agentId,
857
- session: sessionId,
876
+ session: fresh ? null : sessionId,
858
877
  cwd: where,
859
878
  app: terminal.app,
860
879
  },
880
+ ...(fresh ? { note: freshNote(agentId, terminal.name) } : {}),
861
881
  ...(inCopy
862
882
  ? {
863
883
  note: `This run happened in Harness's own copy of the repo, which T3 Code doesn't list, so it opens in ${terminal.name}. Approve Harness in T3 Code and this thread's next turns run there.`,
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;