tryharness 0.7.67 → 0.7.69

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 (54) hide show
  1. package/lib/boardFileCommands.mjs +5 -7
  2. package/lib/boardFiles.mjs +5 -0
  3. package/lib/boardProtocol.json +50 -64
  4. package/lib/boardWaits.mjs +6 -0
  5. package/lib/cards.mjs +13 -1
  6. package/lib/comfyExecution.mjs +545 -0
  7. package/lib/context.mjs +34 -20
  8. package/lib/contextWorker.mjs +199 -0
  9. package/lib/coordinator.mjs +224 -22
  10. package/lib/daemon.mjs +196 -14
  11. package/lib/dispatchContract.json +313 -0
  12. package/lib/dispatchTools.js +87 -0
  13. package/lib/dispatches.mjs +975 -0
  14. package/lib/environment.mjs +54 -69
  15. package/lib/files.mjs +35 -0
  16. package/lib/frames.mjs +5 -9
  17. package/lib/goalCommands.mjs +13 -10
  18. package/lib/kept.mjs +131 -0
  19. package/lib/landed.mjs +1 -34
  20. package/lib/library.mjs +18 -11
  21. package/lib/live.mjs +30 -11
  22. package/lib/localAgentAsk.mjs +27 -4
  23. package/lib/localStack.mjs +17 -13
  24. package/lib/machineRoutes.mjs +5 -0
  25. package/lib/machineRuns.mjs +2 -1
  26. package/lib/mcp-stdio.mjs +42 -1
  27. package/lib/openHere.mjs +36 -0
  28. package/lib/openRequests.mjs +56 -0
  29. package/lib/ownMachines.mjs +232 -24
  30. package/lib/phones.mjs +29 -4
  31. package/lib/places.mjs +44 -11
  32. package/lib/portCalls.mjs +54 -0
  33. package/lib/promptDecider.mjs +471 -0
  34. package/lib/promptFlow.mjs +562 -0
  35. package/lib/promptScopes.mjs +670 -0
  36. package/lib/provenance.mjs +3 -2
  37. package/lib/runAuthority.mjs +14 -2
  38. package/lib/runBrief.mjs +2 -2
  39. package/lib/runWorker.mjs +25 -5
  40. package/lib/runner.mjs +62 -6
  41. package/lib/sealed.mjs +37 -0
  42. package/lib/sessionControl.mjs +47 -14
  43. package/lib/sessionIndex.mjs +11 -3
  44. package/lib/store.mjs +362 -40
  45. package/lib/swarm.mjs +85 -34
  46. package/lib/swarmMemory.mjs +39 -16
  47. package/lib/taskCommands.mjs +125 -1
  48. package/lib/team.json +10 -0
  49. package/lib/team.mjs +287 -26
  50. package/lib/threadBriefs.mjs +43 -31
  51. package/lib/threadRuns.mjs +47 -3
  52. package/npm-shrinkwrap.json +14 -14
  53. package/package.json +4 -4
  54. package/release.json +55 -43
@@ -145,8 +145,10 @@ export function createOwnMachines({
145
145
  changed = () => {},
146
146
  onNotice = () => {},
147
147
  // The folders worked in here with the repository each holds: [{ path, repository }].
148
+ // `fresh: true` rereads their current repository identities for an inventory request.
148
149
  folders = () => [],
149
150
  repositoryOf = () => null,
151
+ inventoryChanged = () => {},
150
152
  homeBack = () => {},
151
153
  // On home: a worker's call for the board's changes (boardMirror.mjs since).
152
154
  answerMirror = null,
@@ -186,11 +188,27 @@ export function createOwnMachines({
186
188
  // A proxy link's model call from one of the person's cloud computers, on the computer holding the link
187
189
  // (proxyLinks.mjs answer); null where none is held.
188
190
  answerLink = null,
191
+ // Bounded GPU operations, admitted only over the pinned Home's sealed ask.
192
+ answerPrompt = null,
189
193
  // A cloud computer's own SSH keys (cloudSsh.mjs allow): { key, by } in, null on a computer that takes none.
190
194
  ownSsh = null,
191
195
  }) {
192
196
  // On home: each worker's folders and the repository each holds, as it said them.
193
197
  const infos = new Map();
198
+ const inventoryRequests = new Map();
199
+ // Previous folders help diagnose a reconnect, never authorize placement.
200
+ const inventoryOf = (id) => {
201
+ const info = infos.get(id);
202
+ return {
203
+ state: info?.current ? "ready" : info ? "stale" : "unknown",
204
+ receivedAt: info?.receivedAt ?? null,
205
+ repositories: [
206
+ ...new Set((info?.folders ?? []).map((folder) => folder.repository)),
207
+ ],
208
+ pending: Boolean(inventoryRequests.get(id)?.pending),
209
+ error: inventoryRequests.get(id)?.error ?? null,
210
+ };
211
+ };
194
212
  // The account's other computers as Harness last listed them: { id, label, role, connected, agents, publicKey,
195
213
  // standInFor }, and this one as Harness lists it.
196
214
  let siblings = [];
@@ -302,6 +320,8 @@ export function createOwnMachines({
302
320
  const leftHome = machine.role === "home" && role === "worker";
303
321
  // A stand-in going back hands over what it wrote (boardMirror.mjs handOver); it brings no board of its own.
304
322
  const wasStandIn = Boolean(store.meta("standing-in-for"));
323
+ for (const info of infos.values()) info.current = false;
324
+ inventoryRequests.clear();
305
325
  machine.role = role;
306
326
  // Setup's code is never a home's join code: a home is not waiting to join anything (M4).
307
327
  if (role === "home") machine.joinCode = null;
@@ -347,6 +367,27 @@ export function createOwnMachines({
347
367
  if (someoneStandsIn()) returning();
348
368
  if (!homeListed()?.connected) toldHome = false;
349
369
  else if (!isHome()) void flush();
370
+ if (isHome()) {
371
+ for (const sibling of siblings) {
372
+ const prior = before.get(sibling.id);
373
+ if (
374
+ !sibling.connected ||
375
+ !prior?.connected ||
376
+ prior.publicKey !== sibling.publicKey
377
+ ) {
378
+ const info = infos.get(sibling.id);
379
+ if (info) info.current = false;
380
+ inventoryRequests.delete(sibling.id);
381
+ }
382
+ if (
383
+ sibling.connected &&
384
+ confirmed(sibling) &&
385
+ inventoryOf(sibling.id).state !== "ready"
386
+ )
387
+ void refreshInventory(sibling.id);
388
+ }
389
+ inventoryChanged();
390
+ }
350
391
  };
351
392
 
352
393
  const rename = async (label) => {
@@ -1200,7 +1241,7 @@ export function createOwnMachines({
1200
1241
  if (session?.id === "none") session = null;
1201
1242
  try {
1202
1243
  for (;;) {
1203
- const [next, ...rest] = outbox();
1244
+ const [next] = outbox();
1204
1245
  if (!next) break;
1205
1246
  const key = await keyFor(pinned.public_key, machine.id);
1206
1247
  const answered = await deliverSealed(
@@ -1219,7 +1260,9 @@ export function createOwnMachines({
1219
1260
  break;
1220
1261
  }
1221
1262
  const result = answered.result;
1222
- keepOut(rest);
1263
+ // A receipt can be queued while this delivery is awaiting its answer.
1264
+ // Remove only the delivered item, preserving concurrently appended work.
1265
+ keepOut(outbox().filter((item) => item.requestId !== next.requestId));
1223
1266
  log(
1224
1267
  `sent ${next.command} to your home computer: ${result?.ok === false && result.code !== "replayed" ? result.error : "taken"}`
1225
1268
  );
@@ -1425,6 +1468,9 @@ export function createOwnMachines({
1425
1468
  // Kept, sealed, until home is back; the call carries when it was written.
1426
1469
  const { requestId, envelope } = await send(pinned, call, { queued: true });
1427
1470
  keepOut([...outbox(), { requestId, envelope, command: call.command }]);
1471
+ // Home may have reconnected during the failed call, after its connection
1472
+ // notification already drained the queue. Give this newly queued item a turn.
1473
+ if (homeListed()?.connected) void flush();
1428
1474
  return {
1429
1475
  ok: true,
1430
1476
  queued: true,
@@ -1757,6 +1803,62 @@ export function createOwnMachines({
1757
1803
  }).catch(() => null);
1758
1804
  };
1759
1805
 
1806
+ // Home can restart without breaking the worker's connection to Harness.
1807
+ // Ask explicitly instead of relying on that worker noticing a goodbye.
1808
+ const refreshInventory = async (workerId, { force = false } = {}) => {
1809
+ const sibling = siblings.find((peer) => peer.id === workerId);
1810
+ if (!isHome() || !sibling?.connected || !confirmed(sibling))
1811
+ return {
1812
+ ok: false,
1813
+ error: "inventory needs a connected, confirmed worker",
1814
+ };
1815
+ if (!force && inventoryRequests.has(workerId))
1816
+ return { ok: true, inventory: inventoryOf(workerId) };
1817
+ const request = { id: randomUUID(), pending: true, error: null };
1818
+ inventoryRequests.set(workerId, request);
1819
+ const info = infos.get(workerId);
1820
+ if (info) info.current = false;
1821
+ changed();
1822
+ // A sealed answer completes the snapshot, rather than acknowledging only
1823
+ // its notice. Old workers refuse the unknown question. A missing transport
1824
+ // answer gets one retry; no separate deadline or timer is introduced here.
1825
+ for (let attempt = 0; attempt < 2; attempt++) {
1826
+ const answer = await askWorker(workerId, { inventory: true }).catch(
1827
+ () => null
1828
+ );
1829
+ if (inventoryRequests.get(workerId) !== request) break;
1830
+ if (
1831
+ answer?.ok === true &&
1832
+ learn(workerId, { request: request.id, folders: answer.folders })
1833
+ )
1834
+ break;
1835
+ if (answer) break;
1836
+ }
1837
+ if (inventoryRequests.get(workerId) === request) {
1838
+ request.pending = false;
1839
+ request.error = "Repository inventory did not arrive";
1840
+ changed();
1841
+ inventoryChanged(workerId);
1842
+ }
1843
+ return {
1844
+ ok: inventoryOf(workerId).state === "ready",
1845
+ inventory: inventoryOf(workerId),
1846
+ };
1847
+ };
1848
+
1849
+ const reportInventory = async (request) => {
1850
+ const home = pinnedHome();
1851
+ if (isHome() || !home) return;
1852
+ const here = folders({ fresh: true });
1853
+ const reported = await callOnce(home, {
1854
+ command: "board.machine.info",
1855
+ agent: "user",
1856
+ folders: here,
1857
+ inventoryRequest: request,
1858
+ });
1859
+ if (reported?.ok === true) toldHome = JSON.stringify(here);
1860
+ };
1861
+
1760
1862
  // A notice is sealed by the computer that sent it as home: the home this computer follows, or another it confirmed (one
1761
1863
  // that moved home to itself, or stands in), tried in turn. Harness's word on who sent it counts for nothing.
1762
1864
  const openNoticeFromAny = async (body) => {
@@ -1793,6 +1895,12 @@ export function createOwnMachines({
1793
1895
  }
1794
1896
  // Everything else is the word of the home this computer follows; another's is heard and set aside.
1795
1897
  if (from !== acceptedHome()) return { ok: true };
1898
+ if (!isHome() && typeof notice.inventoryRequest === "string") {
1899
+ void reportInventory(notice.inventoryRequest).catch((error) =>
1900
+ log(`repository inventory was not reported: ${error.message}`)
1901
+ );
1902
+ return { ok: true };
1903
+ }
1796
1904
  if (typeof notice.removed === "string") {
1797
1905
  removedByHome(notice.removed);
1798
1906
  return { ok: true };
@@ -1990,22 +2098,26 @@ export function createOwnMachines({
1990
2098
  // a question for the windows only from the few they answer for home (M6).
1991
2099
  // A cloud home's call through a proxy link this computer holds is answered for that home alone (proxyLinks.mjs).
1992
2100
  const answer =
1993
- call.home === true
1994
- ? await becomeHome(call.computers)
1995
- : call.link && answerLink
1996
- ? await answerLink(pinned.machine_id, call.link)
1997
- : call.models
1998
- ? await ownModels(call.models)
1999
- : call.live
2000
- ? await ownLive(call.live)
2001
- : call.ssh
2002
- ? ownSshAllow(call.ssh)
2003
- : WINDOW_TOOLS.has(call.tool)
2004
- ? await askOwnWindows(call)
2005
- : {
2006
- ok: false,
2007
- error: `home cannot ask this computer's windows for ${call.tool}`,
2008
- };
2101
+ call.prompt && answerPrompt
2102
+ ? await answerPrompt(call.prompt, pinned.machine_id)
2103
+ : call.inventory === true
2104
+ ? { ok: true, folders: folders({ fresh: true }) }
2105
+ : call.home === true
2106
+ ? await becomeHome(call.computers)
2107
+ : call.link && answerLink
2108
+ ? await answerLink(pinned.machine_id, call.link)
2109
+ : call.models
2110
+ ? await ownModels(call.models)
2111
+ : call.live
2112
+ ? await ownLive(call.live)
2113
+ : call.ssh
2114
+ ? ownSshAllow(call.ssh)
2115
+ : WINDOW_TOOLS.has(call.tool)
2116
+ ? await askOwnWindows(call)
2117
+ : {
2118
+ ok: false,
2119
+ error: `home cannot ask this computer's windows for ${call.tool}`,
2120
+ };
2009
2121
  return {
2010
2122
  envelope: await sealAskAnswer(
2011
2123
  key,
@@ -2072,6 +2184,7 @@ export function createOwnMachines({
2072
2184
  connected: sibling.connected,
2073
2185
  agents: sibling.agents,
2074
2186
  confirmed: confirmed(sibling),
2187
+ ...(isHome() ? { inventory: inventoryOf(sibling.id) } : {}),
2075
2188
  // Harness runs it (a cloud computer): what home lets it do is an agents' computer's, never the person's.
2076
2189
  hosted: store.ownMachine(sibling.id)?.hosted === true,
2077
2190
  standsInForThis: sibling.standInFor === machine.id,
@@ -2350,10 +2463,63 @@ export function createOwnMachines({
2350
2463
  );
2351
2464
  };
2352
2465
 
2353
- /** On home: a worker's call for every computer's sessions, or for one session read where it runs. */
2466
+ /**
2467
+ * Open, on the computer an agent's session or thread is on, where the person would go to see it there (owner, October
2468
+ * 28): that computer plans and opens it (openRequests.mjs). Home reaches the worker; a worker goes through home.
2469
+ */
2470
+ const openSession = async (request) => {
2471
+ const target = String(request.machine || machine.id);
2472
+ const open = {
2473
+ to: request.to,
2474
+ sessionId: request.sessionId,
2475
+ folder: request.folder,
2476
+ fresh: request.fresh === true,
2477
+ // Or a thread in that computer's T3 Code.
2478
+ thread: request.thread,
2479
+ };
2480
+ if (target === machine.id) return ownLive({ open });
2481
+ if (isHome()) {
2482
+ if (
2483
+ !siblings.some((sibling) => sibling.id === target && confirmed(sibling))
2484
+ )
2485
+ return { ok: false, error: "that computer is not in your swarm" };
2486
+ const answer = await askWorker(target, { live: { open } });
2487
+ if (!answer)
2488
+ return {
2489
+ ok: false,
2490
+ error: `${labelOf(target) ?? "That computer"} did not answer`,
2491
+ };
2492
+ // A computer older than Open there answers that it only lists and reads.
2493
+ if (!answer.ok && /listed or read/.test(String(answer.error)))
2494
+ return {
2495
+ ok: false,
2496
+ error: `${labelOf(target) ?? "That computer"} opens things for you once it has the latest tryharness.`,
2497
+ };
2498
+ return answer;
2499
+ }
2500
+ const pinned = pinnedHome();
2501
+ if (!pinned) return { ok: false, error: unreachableNote(null) };
2502
+ const answer = await callOnce(pinned, {
2503
+ command: LIVE_COMMAND,
2504
+ agent: "user",
2505
+ open,
2506
+ machine: target,
2507
+ });
2508
+ // A home older than Open there answers with every computer's sessions instead.
2509
+ if (answer?.ok && answer.computers)
2510
+ return {
2511
+ ok: false,
2512
+ error:
2513
+ "Your home computer passes this on once it has the latest tryharness.",
2514
+ };
2515
+ return answer ?? offline();
2516
+ };
2517
+
2518
+ /** On home: a worker's call for every computer's sessions, for one session read where it runs, or for an Open there. */
2354
2519
  const answerLiveCall = async (call, from) => {
2355
2520
  if (call.agent !== "user")
2356
2521
  return { ok: false, error: "only the person reads their sessions" };
2522
+ if (call.open) return openSession({ ...call.open, machine: call.machine });
2357
2523
  if (call.read) return readSession({ ...call.read, machine: call.machine });
2358
2524
  return { ok: true, computers: await everyComputersLive(from) };
2359
2525
  };
@@ -2519,20 +2685,23 @@ export function createOwnMachines({
2519
2685
 
2520
2686
  /**
2521
2687
  * For the coordinator: the person's computers with this agent, each with whether it is online and has the thread's
2522
- * repository. Undefined while the agent is on this computer alone.
2688
+ * repository, including an agent installed on this computer alone.
2523
2689
  */
2524
2690
  const computersFor = (agent, workspace) => {
2525
2691
  const computers = computersWith(agent);
2526
- if (!computers.some((computer) => !computer.here)) return undefined;
2527
2692
  const repository = workspace ? repositoryOf(workspace) : null;
2528
2693
  return computers.map(({ id, label, online, here }) => ({
2694
+ id,
2529
2695
  label,
2530
2696
  online,
2697
+ ...(!here ? { inventory: inventoryOf(id) } : {}),
2531
2698
  ...(repository
2532
2699
  ? {
2533
2700
  thread_repository: here
2534
2701
  ? true
2535
- : namesOf(infos.get(id)?.folders ?? []).includes(repository),
2702
+ : inventoryOf(id).state === "ready"
2703
+ ? namesOf(infos.get(id).folders).includes(repository)
2704
+ : null,
2536
2705
  }
2537
2706
  : {}),
2538
2707
  }));
@@ -2540,7 +2709,33 @@ export function createOwnMachines({
2540
2709
 
2541
2710
  /** On home: what a worker said it has (its folders and their repositories), sealed, so work can go to it. */
2542
2711
  const learn = (id, info) => {
2543
- infos.set(String(id), { folders: info.folders ?? [] });
2712
+ id = String(id);
2713
+ if (!store.ownMachine(id)) return false;
2714
+ if (info.request && inventoryRequests.get(id)?.id !== info.request)
2715
+ return false;
2716
+ if (
2717
+ !Array.isArray(info.folders) ||
2718
+ info.folders.some(
2719
+ (folder) =>
2720
+ typeof folder?.path !== "string" ||
2721
+ !path.isAbsolute(folder.path) ||
2722
+ typeof folder.repository !== "string"
2723
+ )
2724
+ )
2725
+ return false;
2726
+ const folders = info.folders.slice(0, 200).map((folder) => ({
2727
+ path: folder.path.slice(0, 1024),
2728
+ repository: folder.repository.slice(0, 300),
2729
+ }));
2730
+ const receivedAt = new Date().toISOString();
2731
+ infos.set(id, { folders, receivedAt, current: true });
2732
+ inventoryRequests.delete(id);
2733
+ log(
2734
+ `repository inventory received from ${labelOf(id) ?? id}: ${info.folders.length} folders`
2735
+ );
2736
+ changed();
2737
+ inventoryChanged(id);
2738
+ return true;
2544
2739
  };
2545
2740
  const namesOf = (list) => [
2546
2741
  ...new Set(list.map((folder) => folder.repository).filter(Boolean)),
@@ -2565,6 +2760,7 @@ export function createOwnMachines({
2565
2760
  for (const sibling of siblings) {
2566
2761
  if (!sibling.agents.includes(agent) || !store.ownMachine(sibling.id))
2567
2762
  continue;
2763
+ if (inventoryOf(sibling.id).state !== "ready") continue;
2568
2764
  const folder = infos
2569
2765
  .get(sibling.id)
2570
2766
  ?.folders.find((each) => each.repository === repository)?.path;
@@ -2582,9 +2778,12 @@ export function createOwnMachines({
2582
2778
  const label = labelOf(id) ?? "that computer";
2583
2779
  if (!sibling || !store.ownMachine(id))
2584
2780
  return { error: `${label} is not connected` };
2781
+ if (!sibling.connected) return { error: `${label} is offline` };
2585
2782
  if (!sibling.agents.includes(agent))
2586
2783
  return { error: `${nameOf(agent)} is not on ${label}` };
2587
2784
  if (!workspace) return { machine: id, folder: null };
2785
+ if (inventoryOf(id).state !== "ready")
2786
+ return { error: `${label}'s repository inventory is not ready` };
2588
2787
  const repository = repositoryOf(workspace);
2589
2788
  const folder = repository
2590
2789
  ? infos.get(id)?.folders.find((each) => each.repository === repository)
@@ -2608,7 +2807,10 @@ export function createOwnMachines({
2608
2807
  },
2609
2808
  ...siblings.map((sibling) => ({
2610
2809
  ...sibling,
2611
- repositories: namesOf(infos.get(sibling.id)?.folders ?? []),
2810
+ repositories:
2811
+ inventoryOf(sibling.id).state === "ready"
2812
+ ? namesOf(infos.get(sibling.id).folders)
2813
+ : [],
2612
2814
  })),
2613
2815
  ];
2614
2816
 
@@ -2718,6 +2920,10 @@ export function createOwnMachines({
2718
2920
  answerAs,
2719
2921
  pushViews,
2720
2922
  askWorkerWindows,
2923
+ promptTo: (workerId, call) =>
2924
+ isHome() && store.ownMachine(workerId)?.hosted !== true
2925
+ ? askWorker(workerId, { prompt: call })
2926
+ : Promise.resolve(null),
2721
2927
  linkCall,
2722
2928
  tellWorkers,
2723
2929
  fromLink,
@@ -2744,11 +2950,13 @@ export function createOwnMachines({
2744
2950
  models,
2745
2951
  sessions,
2746
2952
  readSession,
2953
+ openSession,
2747
2954
  setModel,
2748
2955
  allowSsh,
2749
2956
  status,
2750
2957
  all,
2751
2958
  learn,
2959
+ refreshInventory,
2752
2960
  placeElsewhere,
2753
2961
  placeOn,
2754
2962
  computerNamed,
package/lib/phones.mjs CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  open,
14
14
  pairProof,
15
15
  seal,
16
+ sealFilePart,
16
17
  } from "./sealed.mjs";
17
18
 
18
19
  // The daemon's side of the person's own devices: pairing offers made on this machine (a QR code
@@ -181,7 +182,11 @@ export async function createPhoneDesk({
181
182
  const identity = await loadOrCreateIdentity(identityFile);
182
183
  const offers = new Map();
183
184
  const keys = new Map();
184
- const hostname = os.hostname().slice(0, 64);
185
+ // The name the person knows this computer by (machine.json's label, which `npx tryharness machines name` changes),
186
+ // not its network name: macOS renames that on its own after a clash on the network, and a phone linking
187
+ // MacBook-Pro-3 said it was linking a MacBook-Pro-4 the person had never heard of.
188
+ const hostname = () =>
189
+ machines()?.status()?.label ?? os.hostname().slice(0, 64);
185
190
 
186
191
  const setupOffer = setupOfferFile ? readSetupOffer(setupOfferFile) : null;
187
192
  if (setupOffer)
@@ -221,7 +226,7 @@ export async function createPhoneDesk({
221
226
  byHarness,
222
227
  expiresAt: Date.now() + ttlMs,
223
228
  });
224
- return { o: offerId, s: secret, k: identity.publicKey, h: hostname };
229
+ return { o: offerId, s: secret, k: identity.publicKey, h: hostname() };
225
230
  };
226
231
 
227
232
  // What the QR code or link carries. The secret and the daemon's key never pass through Harness.
@@ -427,7 +432,7 @@ export async function createPhoneDesk({
427
432
  String(requestId),
428
433
  {
429
434
  paired: true,
430
- hostname,
435
+ hostname: hostname(),
431
436
  label,
432
437
  kind: device.kind,
433
438
  version,
@@ -586,6 +591,26 @@ export async function createPhoneDesk({
586
591
  };
587
592
  }
588
593
  const result = await answer(request.call, device, { holder, gesture });
594
+ // A file part asked for as bytes goes sealed as bytes; anything else, and every older phone, as JSON.
595
+ if (
596
+ request.call?.command === "board.file.get" &&
597
+ request.call.raw === true &&
598
+ result?.ok === true &&
599
+ typeof result.data === "string"
600
+ ) {
601
+ const { data, ...header } = result;
602
+ return {
603
+ ok: true,
604
+ envelope: await sealFilePart(
605
+ key,
606
+ "d2p",
607
+ device.id,
608
+ envelope.requestId,
609
+ header,
610
+ Buffer.from(data, "base64")
611
+ ),
612
+ };
613
+ }
589
614
  return {
590
615
  ok: true,
591
616
  envelope: await seal(key, "d2p", device.id, envelope.requestId, result),
@@ -628,7 +653,7 @@ export async function createPhoneDesk({
628
653
  const answer = async (callInput, device, sealedBy) => {
629
654
  const command = String(callInput?.command || "");
630
655
  if (command === "phone.hello")
631
- return { ok: true, hostname, version, kind: device.kind };
656
+ return { ok: true, hostname: hostname(), version, kind: device.kind };
632
657
  // A device sends a file's bytes. A path names a file already on this computer, which only an agent here may attach.
633
658
  if (command === "board.file.add" && callInput?.path != null)
634
659
  return {
package/lib/places.mjs CHANGED
@@ -6,6 +6,7 @@ import { spawn, spawnSync } from "node:child_process";
6
6
  import { historyRoots, paths } from "./paths.mjs";
7
7
  import { agentEnvironment } from "./agentnode.mjs";
8
8
  import { mainCheckout } from "./worktrees.mjs";
9
+ import { kept } from "./kept.mjs";
9
10
 
10
11
  // Where a coding session runs, and how it opens there again. A session's place comes from its own environment: the
11
12
  // Harness piece inside the agent sends it when the session starts (the Claude Code and Codex hooks, nudge.mjs; the
@@ -695,13 +696,37 @@ function t3Query(home, sql) {
695
696
  );
696
697
  return found.status === 0 ? (found.stdout || "").trim() : null;
697
698
  }
698
- const t3Tables = (home) =>
699
- new Set(
700
- (
701
- t3Query(home, "select name from sqlite_master where type = 'table';") ||
702
- ""
703
- ).split("\n")
704
- );
699
+ // The same reads, answered from memory and taken again beside the daemon's thread (kept.mjs): T3's tables change only
700
+ // when T3 updates, and what it runs now is asked for on every read of the buddy's live list (t3ThreadRecent,
701
+ // t3WorkingRecently). A decision made once, such as whether a thread's round waits for T3, reads now.
702
+ function* t3QuerySteps(home, sql) {
703
+ const db = t3Database(home);
704
+ if (!db || !fs.existsSync(SQLITE)) return null;
705
+ const out = yield [SQLITE, ["-readonly", "-cmd", ".timeout 500", db, sql]];
706
+ return out === null ? null : out.trim();
707
+ }
708
+ const keptT3Query = (freshMs, staleMs, wanting) =>
709
+ kept(t3QuerySteps, {
710
+ freshMs,
711
+ staleMs,
712
+ keyOf: (home, sql) => `${home}\0${sql}`,
713
+ wanting,
714
+ });
715
+ // No answer (T3 not installed or started yet) is asked again, so a T3 that starts later is seen; so is a table the kept
716
+ // list lacks, so a T3 that updated since (or just made its tables) is seen at once.
717
+ const T3_TABLES_SQL = "select name from sqlite_master where type = 'table';";
718
+ const tableNames = (tables) => (tables || "").split("\n");
719
+ const t3QueryTables = keptT3Query(
720
+ 10 * 60_000,
721
+ Infinity,
722
+ (tables, _home, _sql, needed) =>
723
+ !tables || Boolean(needed && !tableNames(tables).includes(needed))
724
+ );
725
+ const t3QueryRecent = keptT3Query(2_000, 15_000);
726
+ const t3Tables = (home) => ({
727
+ has: (name) =>
728
+ tableNames(t3QueryTables(home, T3_TABLES_SQL, name)).includes(name),
729
+ });
705
730
 
706
731
  /** A read of T3's record that never holds the daemon (its database is gigabytes; a cold read took 5.7 s). */
707
732
  function t3QueryLater(home, sql) {
@@ -816,7 +841,7 @@ export function t3Checkouts(home = t3Home()) {
816
841
  * provider thread; 0.0.45 in provider_session_runtime), else T3's import of it. A T3 thread's own id (a turn Harness
817
842
  * handed to T3, t3.mjs runInT3) is that thread.
818
843
  */
819
- export function t3Thread(sessionId, home = t3Home()) {
844
+ export function t3Thread(sessionId, home = t3Home(), query = t3Query) {
820
845
  if (!PLAIN_ID.test(String(sessionId || ""))) return null;
821
846
  const tables = t3Tables(home);
822
847
  // The id is checked above: letters, digits and . _ : - only.
@@ -835,13 +860,17 @@ export function t3Thread(sessionId, home = t3Home()) {
835
860
  );
836
861
  if (!parts.length) return null;
837
862
  return (
838
- t3Query(
863
+ query(
839
864
  home,
840
865
  `select thread_id from (${parts.join(" union all ")}) order by at desc limit 1;`
841
866
  ) || null
842
867
  );
843
868
  }
844
869
 
870
+ /** t3Thread as of a reading up to a couple of seconds old, for the buddy's live list. */
871
+ export const t3ThreadRecent = (sessionId, home = t3Home()) =>
872
+ t3Thread(sessionId, home, t3QueryRecent);
873
+
845
874
  /** T3 Code's own link to one of its threads (t3code://threads/<environment>/<thread>). */
846
875
  export function t3Link(threadId, home = t3Home()) {
847
876
  let environment = "";
@@ -958,7 +987,7 @@ export function t3Model(agent, home = t3Home()) {
958
987
  * its folder (the thread's worktree, else its project's). Codex in T3 runs on Codex's shared background server, outside
959
988
  * T3's app, so this is how its running sessions there are found.
960
989
  */
961
- export function t3Working(agent, home = t3Home()) {
990
+ export function t3Working(agent, home = t3Home(), query = t3Query) {
962
991
  const provider = t3Provider(agent);
963
992
  const tables = t3Tables(home);
964
993
  if (
@@ -968,7 +997,7 @@ export function t3Working(agent, home = t3Home()) {
968
997
  )
969
998
  return [];
970
999
  const projects = tables.has("projection_projects");
971
- const rows = t3Query(
1000
+ const rows = query(
972
1001
  home,
973
1002
  `select p.thread_id || char(9) || json_extract(p.payload_json, '$.nativeThreadRef.nativeId') || char(9) || coalesce(json_extract(t.payload_json, '$.worktreePath'), ${projects ? "r.workspace_root, " : ""}'') || char(9) || p.updated_at
974
1003
  from orchestration_v2_projection_provider_threads p join orchestration_v2_projection_threads t on t.thread_id = p.thread_id${projects ? " left join projection_projects r on r.project_id = t.project_id" : ""}
@@ -986,6 +1015,10 @@ export function t3Working(agent, home = t3Home()) {
986
1015
  }));
987
1016
  }
988
1017
 
1018
+ /** t3Working as of a reading up to a couple of seconds old, for the buddy's live list. */
1019
+ export const t3WorkingRecently = (agent, home = t3Home()) =>
1020
+ t3Working(agent, home, t3QueryRecent);
1021
+
989
1022
  /**
990
1023
  * What a turn T3 Code ran used, from T3's own record of the provider's turns for that run (every attempt): tokens in
991
1024
  * and out, cached and cache-written. T3 records no price, so the cost stays unknown. Null when T3 has no record of it.
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Calls across a worker thread's port, both ways: each side answers calls to the functions it serves and calls the
3
+ * other side's by name, getting a promise. Arguments and results are copied (structured clone), so a function or a
4
+ * class instance cannot cross; a Buffer arrives as a Uint8Array.
5
+ *
6
+ * The daemon runs its JavaScript, its WASM SQLite and every synchronous file read on one thread, so work that reads a
7
+ * large database runs in a worker (contextWorker.mjs) and asks the daemon only for what the daemon owns.
8
+ */
9
+ export function portCalls(port, serve = {}) {
10
+ let next = 0;
11
+ const waiting = new Map();
12
+
13
+ const answer = async ({ call, name, args }) => {
14
+ try {
15
+ const fn = serve[name];
16
+ if (typeof fn !== "function") throw new Error(`${name} is not served`);
17
+ const value = await fn(...args);
18
+ port.postMessage({ reply: call, value });
19
+ } catch (error) {
20
+ port.postMessage({
21
+ reply: call,
22
+ error: error instanceof Error ? error.message : String(error),
23
+ });
24
+ }
25
+ };
26
+
27
+ port.on("message", (message) => {
28
+ if (message?.call !== undefined) return void answer(message);
29
+ const pending = waiting.get(message?.reply);
30
+ if (!pending) return;
31
+ waiting.delete(message.reply);
32
+ if (message.error !== undefined) pending.reject(new Error(message.error));
33
+ else pending.resolve(message.value);
34
+ });
35
+
36
+ return {
37
+ call: (name, ...args) =>
38
+ new Promise((resolve, reject) => {
39
+ const id = next++;
40
+ waiting.set(id, { resolve, reject });
41
+ try {
42
+ port.postMessage({ call: id, name, args });
43
+ } catch (error) {
44
+ waiting.delete(id);
45
+ reject(error);
46
+ }
47
+ }),
48
+ /** Fails every call still waiting, as when the other side has gone. */
49
+ fail(why) {
50
+ for (const pending of waiting.values()) pending.reject(new Error(why));
51
+ waiting.clear();
52
+ },
53
+ };
54
+ }