tryharness 0.7.45 → 0.7.54

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 (125) hide show
  1. package/README.md +239 -14
  2. package/assets/dsh-plugin.mjs +72 -0
  3. package/assets/opencode-plugin.js +4 -3
  4. package/cli.mjs +497 -196
  5. package/lib/actorRoster.mjs +28 -5
  6. package/lib/adapters.mjs +165 -222
  7. package/lib/agentRuntimeConfig.mjs +36 -0
  8. package/lib/agentRuntimes.mjs +570 -0
  9. package/lib/agentSignIn.mjs +226 -0
  10. package/lib/atlas.mjs +7 -2
  11. package/lib/audit.mjs +643 -0
  12. package/lib/backupSetup.mjs +141 -0
  13. package/lib/boardAccess.mjs +8 -1
  14. package/lib/boardBackup.mjs +283 -0
  15. package/lib/boardCommands.mjs +5 -10
  16. package/lib/boardFileCommands.mjs +2 -1
  17. package/lib/boardMirror.mjs +523 -0
  18. package/lib/boardProtocol.json +263 -6
  19. package/lib/boardTools.mjs +2 -6
  20. package/lib/boardWaits.mjs +102 -0
  21. package/lib/book.mjs +659 -0
  22. package/lib/bridge.mjs +26 -4
  23. package/lib/browserWake.mjs +60 -0
  24. package/lib/cards.mjs +159 -16
  25. package/lib/cloudBoot.mjs +124 -0
  26. package/lib/commands.mjs +25 -5
  27. package/lib/connectionTools.d.ts +13 -0
  28. package/lib/connectionTools.js +45 -0
  29. package/lib/connectorAuth.mjs +309 -0
  30. package/lib/connectorCatalog.json +41 -0
  31. package/lib/connectorCommands.mjs +121 -0
  32. package/lib/connectorGoogle.mjs +513 -0
  33. package/lib/connectors.mjs +805 -0
  34. package/lib/context.mjs +18 -4
  35. package/lib/contractGate.mjs +377 -0
  36. package/lib/coordinator.mjs +152 -39
  37. package/lib/coreModels.mjs +78 -0
  38. package/lib/daemon.mjs +973 -54
  39. package/lib/desk.mjs +239 -0
  40. package/lib/desktop.mjs +113 -8
  41. package/lib/digest.mjs +32 -0
  42. package/lib/directLink.mjs +283 -0
  43. package/lib/environments.mjs +825 -0
  44. package/lib/folders.mjs +4 -4
  45. package/lib/gitHost.mjs +174 -0
  46. package/lib/goalCommands.mjs +58 -14
  47. package/lib/hookDialects.mjs +298 -0
  48. package/lib/inference.mjs +263 -152
  49. package/lib/landed.mjs +887 -0
  50. package/lib/lessons.mjs +6 -0
  51. package/lib/lineup.mjs +324 -0
  52. package/lib/live.mjs +284 -13
  53. package/lib/localmodels.mjs +10 -0
  54. package/lib/machineIdentity.mjs +3 -0
  55. package/lib/machineRoutes.mjs +40 -2
  56. package/lib/machineRuns.mjs +30 -3
  57. package/lib/machineSeal.mjs +69 -10
  58. package/lib/mcp-stdio.mjs +189 -120
  59. package/lib/mcpRelay.mjs +119 -0
  60. package/lib/members.json +26 -0
  61. package/lib/members.mjs +33 -0
  62. package/lib/modelMemory.mjs +100 -0
  63. package/lib/models.mjs +48 -15
  64. package/lib/museSession.mjs +122 -0
  65. package/lib/nativeHost.mjs +203 -0
  66. package/lib/neovim.mjs +126 -0
  67. package/lib/network.mjs +7 -2
  68. package/lib/nudge.mjs +57 -18
  69. package/lib/onboard.mjs +430 -1
  70. package/lib/oneclawLocal.mjs +150 -0
  71. package/lib/ownMachines.mjs +828 -39
  72. package/lib/pairing.mjs +182 -0
  73. package/lib/paths.mjs +8 -0
  74. package/lib/personModel.mjs +89 -0
  75. package/lib/phones.mjs +119 -3
  76. package/lib/placeCommands.mjs +27 -0
  77. package/lib/places.mjs +337 -9
  78. package/lib/plans.mjs +151 -27
  79. package/lib/profile.mjs +152 -0
  80. package/lib/projects.mjs +624 -137
  81. package/lib/readiness.mjs +400 -0
  82. package/lib/record.mjs +115 -0
  83. package/lib/repoLinks.mjs +354 -0
  84. package/lib/roomChannels.mjs +641 -0
  85. package/lib/runBrief.mjs +32 -2
  86. package/lib/runRequests.mjs +157 -0
  87. package/lib/runWorker.mjs +37 -9
  88. package/lib/runner.mjs +74 -11
  89. package/lib/secretPatterns.json +55 -0
  90. package/lib/secrets.mjs +10 -27
  91. package/lib/seen.mjs +102 -0
  92. package/lib/service.mjs +11 -6
  93. package/lib/sessionControl.mjs +386 -96
  94. package/lib/sessionIndex.mjs +5 -3
  95. package/lib/specialties.json +74 -0
  96. package/lib/specialties.mjs +477 -0
  97. package/lib/specialtyKeys.d.ts +3 -0
  98. package/lib/specialtyKeys.js +58 -0
  99. package/lib/specialtyNotice.mjs +147 -0
  100. package/lib/specialtySnapshot.mjs +138 -0
  101. package/lib/store.mjs +829 -29
  102. package/lib/subagents.mjs +8 -4
  103. package/lib/swarm.mjs +483 -37
  104. package/lib/swarmMemory.mjs +947 -0
  105. package/lib/t3.mjs +56 -17
  106. package/lib/taskCommands.mjs +91 -13
  107. package/lib/taskRuns.mjs +68 -11
  108. package/lib/team.json +253 -144
  109. package/lib/team.mjs +538 -147
  110. package/lib/threadLine.mjs +116 -0
  111. package/lib/threadRuns.mjs +78 -12
  112. package/lib/threadView.mjs +66 -16
  113. package/lib/tokenizer.mjs +405 -0
  114. package/lib/ui.mjs +16 -2
  115. package/lib/usageTotals.mjs +148 -0
  116. package/lib/vault.mjs +1144 -0
  117. package/lib/vaultCloud.mjs +117 -0
  118. package/lib/vaultCommands.mjs +201 -0
  119. package/lib/vaultTools.d.ts +12 -0
  120. package/lib/vaultTools.js +42 -0
  121. package/lib/windowAsks.mjs +42 -0
  122. package/lib/workFocus.mjs +59 -0
  123. package/lib/workLinks.mjs +90 -0
  124. package/lib/worktrees.mjs +51 -13
  125. package/package.json +10 -5
@@ -0,0 +1,825 @@
1
+ import fs from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { detectAgents } from "./commands.mjs";
4
+ import { member, nameOf } from "./members.mjs";
5
+ import { t3Access, t3Tool } from "./t3.mjs";
6
+ import { t3Checkouts, t3Committers, t3Link } from "./places.mjs";
7
+
8
+ const DRIVER_AGENT = {
9
+ codex: "codex",
10
+ claudeAgent: "claude-code",
11
+ cursor: "cursor",
12
+ grok: "grok-build",
13
+ opencode: "opencode",
14
+ antigravity: "antigravity",
15
+ muse: "muse-code",
16
+ pi: "pi",
17
+ };
18
+ const ACTIVE = new Set([
19
+ "preparing",
20
+ "queued",
21
+ "starting",
22
+ "running",
23
+ "waiting",
24
+ ]);
25
+ const stateOf = (status) =>
26
+ ACTIVE.has(status)
27
+ ? "working"
28
+ : status === "failed"
29
+ ? "failed"
30
+ : ["cancelled", "interrupted"].includes(status)
31
+ ? "stopped"
32
+ : "returned";
33
+ const failure = (error) => ({
34
+ ok: false,
35
+ code: error.code || "environment_error",
36
+ error: error.message,
37
+ });
38
+
39
+ // How often T3 Code is read again while a surface on this computer waits for the board (the buddy's old poll, which
40
+ // read it this often).
41
+ const WATCHED_REFRESH_MS = 3_000;
42
+ // Where the person left each recent thread (threadLine.mjs) is read for this many of the newest, from the last two
43
+ // weeks, and only again when a thread has new items.
44
+ const LINE_THREADS = 40;
45
+ const LINE_DAYS_MS = 14 * 24 * 60 * 60 * 1000;
46
+ // The person's last message is looked for among the thread's newest items, at most this many back: a long run of an
47
+ // agent's steps comes between two of their messages.
48
+ const EXCHANGE_ITEMS = 400;
49
+
50
+ /**
51
+ * Existing work owned by another execution environment, projected into the same swarm view. Reads are answered from
52
+ * what T3 Code last said and read it again behind the answer (October 23: reading T3 Code took about 160 ms of every
53
+ * list on every surface); `notify` hears when what it says changed.
54
+ */
55
+ export function createEnvironments({
56
+ store,
57
+ log,
58
+ notify = () => {},
59
+ watched = () => false,
60
+ threadLine = null,
61
+ }) {
62
+ let providers = [];
63
+ let threads = new Map();
64
+ // Each thread's own checkout and branch, from T3's record (its list leaves them out): what can land (landed.mjs).
65
+ let checkouts = new Map();
66
+ // The threads that ran a command making a commit, read again at most once a minute and never in a list's way.
67
+ let committers = new Set();
68
+ let committersAt = 0;
69
+ const COMMITTERS_FRESH_MS = 60_000;
70
+ let projects = new Map();
71
+ let refreshing = null;
72
+ // Each thread's read as it was last made, kept until T3 says the thread or its subagents changed: one is a page of T3's
73
+ // record per 100 items (October 24: 1 MB and 0.8 to 1.5 s each, asked every 2 s while it was on screen).
74
+ const reads = new Map();
75
+ // Threads the person removed from Harness's list, each until it does something new: id → its last activity then.
76
+ const HIDDEN_KEY = "outside-hidden";
77
+ const hiddenNow = () => {
78
+ try {
79
+ return JSON.parse(store.meta(HIDDEN_KEY) || "{}");
80
+ } catch {
81
+ return {};
82
+ }
83
+ };
84
+ let lastError = null;
85
+ let grant = null;
86
+ // The grant the rows held were read under, and what they said, so a refresh that changes nothing tells no one.
87
+ let loadedGrant = null;
88
+ let said = "";
89
+ const controls = new Map();
90
+ const keyOf = (id) =>
91
+ `outside-t3-${createHash("sha256").update(`${t3Access()?.environmentId}:${id}`).digest("hex")}`;
92
+ const grantOf = (access) =>
93
+ JSON.stringify([
94
+ access?.environmentId,
95
+ access?.grantedAt,
96
+ access?.until,
97
+ access?.state,
98
+ ]);
99
+ const clear = () => {
100
+ providers = [];
101
+ threads = new Map();
102
+ checkouts = new Map();
103
+ projects = new Map();
104
+ };
105
+ const authorized = () => {
106
+ const access = t3Access();
107
+ if (!access || access.state === "expired") {
108
+ clear();
109
+ grant = null;
110
+ return null;
111
+ }
112
+ const current = grantOf(access);
113
+ if (grant !== current) clear();
114
+ grant = current;
115
+ return access;
116
+ };
117
+ const providerAgent = (id) => {
118
+ const provider = providers.find((entry) => entry.providerInstanceId === id);
119
+ return DRIVER_AGENT[provider?.driverKind] || `t3-${id}`;
120
+ };
121
+ const sourceOf = (entry) => ({
122
+ environment: "t3",
123
+ environmentName: "T3 Code",
124
+ threadId: entry.threadId,
125
+ providerInstanceId: entry.providerInstanceId,
126
+ parentThreadId: entry.parentThreadId ?? null,
127
+ relationship: entry.relationshipToParent ?? null,
128
+ native: entry.creationSource === "provider",
129
+ url: t3Link(entry.threadId),
130
+ controls: {
131
+ read: true,
132
+ send:
133
+ authorized()?.state === "send" &&
134
+ entry.relationshipToParent !== "subagent" &&
135
+ entry.creationSource !== "provider",
136
+ stop:
137
+ authorized()?.state === "send" &&
138
+ entry.relationshipToParent !== "subagent" &&
139
+ entry.creationSource !== "provider" &&
140
+ ACTIVE.has(entry.status),
141
+ },
142
+ });
143
+ const treeOf = (root) => {
144
+ const selected = new Map([[root.threadId, root]]);
145
+ let changed = true;
146
+ while (changed) {
147
+ changed = false;
148
+ for (const entry of threads.values())
149
+ if (
150
+ entry.relationshipToParent === "subagent" &&
151
+ selected.has(entry.parentThreadId) &&
152
+ !selected.has(entry.threadId)
153
+ ) {
154
+ selected.set(entry.threadId, entry);
155
+ changed = true;
156
+ }
157
+ }
158
+ return selected;
159
+ };
160
+ /**
161
+ * A thread's own checkout and branch, as T3 said it or as T3 keeps it; null for a thread working in its project, or
162
+ * one whose checkout T3 has since removed (nothing there to show).
163
+ */
164
+ const checkoutOf = (entry) => {
165
+ const own =
166
+ entry.worktreePath && entry.branch
167
+ ? { path: entry.worktreePath, branch: entry.branch }
168
+ : (checkouts.get(entry.threadId) ?? null);
169
+ return own && fs.existsSync(own.path) ? own : null;
170
+ };
171
+
172
+ const summary = (entry) => {
173
+ const family = [...treeOf(entry).values()];
174
+ const active = family.filter((child) => ACTIVE.has(child.status));
175
+ const state = active.length ? "working" : stateOf(entry.status);
176
+ const agent = providerAgent(entry.providerInstanceId);
177
+ return {
178
+ id: keyOf(entry.threadId),
179
+ title: entry.title || "Untitled work",
180
+ objective: entry.title || "Untitled work",
181
+ status: "open",
182
+ agents: [
183
+ ...new Set(
184
+ family.map((child) => providerAgent(child.providerInstanceId))
185
+ ),
186
+ ],
187
+ coordinator: agent,
188
+ source: sourceOf(entry),
189
+ view: {
190
+ title: entry.title || "Untitled work",
191
+ state,
192
+ line: `${nameOf(agent)} · T3 Code`,
193
+ needsYou: [],
194
+ done: false,
195
+ // Where the person left it: their last move and what it was about.
196
+ you: threadLine?.of(keyOf(entry.threadId)) ?? null,
197
+ },
198
+ folder: projects.get(entry.projectId)?.workspaceRoot ?? null,
199
+ working: [
200
+ ...new Set(
201
+ active.map((child) => providerAgent(child.providerInstanceId))
202
+ ),
203
+ ],
204
+ queued: [],
205
+ waiting: null,
206
+ step: null,
207
+ last: null,
208
+ posts: family.reduce((sum, child) => sum + (child.itemCount ?? 0), 0),
209
+ spend: { runs: 0, cost_usd: null },
210
+ changes: null,
211
+ // A thread T3 works on in a checkout of its own can land (landed.mjs); one working in the project itself can't
212
+ // be told apart from the person's own work.
213
+ landed: Boolean(checkoutOf(entry) || committers.has(entry.threadId)),
214
+ createdAt: entry.createdAt,
215
+ updatedAt:
216
+ family
217
+ .map((child) => child.updatedAt)
218
+ .sort()
219
+ .at(-1) ?? entry.updatedAt,
220
+ activityVersion: family.map((child) => [
221
+ child.threadId,
222
+ child.status,
223
+ child.settled,
224
+ child.updatedAt,
225
+ child.itemCount,
226
+ child.latestRunId ?? null,
227
+ ]),
228
+ openItems: [],
229
+ coordination: null,
230
+ };
231
+ };
232
+ async function paged(name, args, field) {
233
+ const result = [];
234
+ let cursor = null;
235
+ const seen = new Set();
236
+ do {
237
+ const page = await t3Tool(name, {
238
+ ...args,
239
+ limit: 100,
240
+ ...(cursor === null ? {} : { cursor }),
241
+ });
242
+ result.push(...(page[field] ?? []));
243
+ cursor = page.nextCursor ?? null;
244
+ if (cursor !== null && seen.has(cursor))
245
+ throw new Error(
246
+ "T3 Code repeated its page cursor; the view is incomplete."
247
+ );
248
+ seen.add(cursor);
249
+ } while (cursor !== null);
250
+ return result;
251
+ }
252
+ const refresh = () => {
253
+ if (!authorized()) return Promise.resolve();
254
+ if (refreshing) return refreshing;
255
+ const startedGrant = grant;
256
+ refreshing = (async () => {
257
+ try {
258
+ const [catalog, listedProjects] = await Promise.all([
259
+ t3Tool("orchestrator_capabilities", {}),
260
+ paged("t3_project_list", {}, "projects"),
261
+ ]);
262
+ const listedThreads = (
263
+ await Promise.all(
264
+ listedProjects.map((project) =>
265
+ paged(
266
+ "t3_thread_list",
267
+ {
268
+ projectId: project.id,
269
+ includeSubagents: true,
270
+ },
271
+ "threads"
272
+ ).then((listed) =>
273
+ // T3 lists a project's threads without naming the project on each; its folder is the thread's.
274
+ listed.map((entry) => ({
275
+ ...entry,
276
+ projectId: entry.projectId ?? project.id,
277
+ }))
278
+ )
279
+ )
280
+ )
281
+ ).flat();
282
+ if (!authorized() || startedGrant !== grant) return;
283
+ providers = catalog.providers ?? [];
284
+ projects = new Map(listedProjects.map((entry) => [entry.id, entry]));
285
+ threads = new Map(
286
+ listedThreads.map((entry) => [keyOf(entry.threadId), entry])
287
+ );
288
+ checkouts = t3Checkouts();
289
+
290
+ if (Date.now() - committersAt > COMMITTERS_FRESH_MS) {
291
+ committersAt = Date.now();
292
+ void t3Committers().then((found) => {
293
+ committers = found;
294
+ });
295
+ }
296
+ lastError = null;
297
+ catchUpLines();
298
+ } catch (error) {
299
+ clear();
300
+ lastError = error.message;
301
+ log(`outside environments: ${error.message}`);
302
+ } finally {
303
+ loadedGrant = startedGrant;
304
+ refreshing = null;
305
+ const now = JSON.stringify([providers, [...projects], [...threads]]);
306
+ if (now !== said) {
307
+ said = now;
308
+ notify();
309
+ }
310
+ }
311
+ })();
312
+ return refreshing;
313
+ };
314
+ // The thread's newest items, as far back as the person's last message: it and the agent's message it answers.
315
+ async function lastExchange(entry) {
316
+ const items = [];
317
+ let after = Math.max(0, (entry.itemCount ?? 0) - EXCHANGE_ITEMS) || null;
318
+ for (let page = 0; page < EXCHANGE_ITEMS / 100; page++) {
319
+ const read = await t3Tool("t3_thread_read", {
320
+ threadId: entry.threadId,
321
+ view: "messages",
322
+ limit: 100,
323
+ // An agent's `Deciding:` line ends its message: room for all of it.
324
+ maxCharsPerItem: 20_000,
325
+ runLimit: 1,
326
+ ...(after === null ? {} : { afterPosition: after }),
327
+ });
328
+ items.push(...(read.items ?? []));
329
+ if (!read.hasMore || read.nextPosition === after) break;
330
+ after = read.nextPosition;
331
+ }
332
+ const said = items.filter((item) =>
333
+ ["user_message", "assistant_message"].includes(item.type)
334
+ );
335
+ // T3's notices to an agent (a subagent finished) are filed as the user's: only the person's own words count.
336
+ const at = said.findLastIndex(
337
+ (item) => item.type === "user_message" && item.createdBy !== "agent"
338
+ );
339
+ if (at < 0) return null;
340
+ const mine = said[at];
341
+ return {
342
+ mine: {
343
+ id: mine.itemId,
344
+ text: mine.text ?? "",
345
+ at: mine.updatedAt ?? entry.updatedAt,
346
+ },
347
+ answered:
348
+ said.slice(0, at).findLast((item) => item.type === "assistant_message")
349
+ ?.text ?? null,
350
+ };
351
+ }
352
+ // Each recent thread's line, behind the list: a thread read again only when it has new items. Lists are drawn again
353
+ // once any line changed.
354
+ const lineChecked = new Map();
355
+ let lining = null;
356
+ function catchUpLines() {
357
+ if (!threadLine || lining) return;
358
+ lining = (async () => {
359
+ const recent = [...threads.values()]
360
+ .filter(
361
+ (entry) =>
362
+ entry.relationshipToParent !== "subagent" &&
363
+ Date.now() - Date.parse(entry.updatedAt) < LINE_DAYS_MS
364
+ )
365
+ .sort((a, b) => String(b.updatedAt).localeCompare(a.updatedAt))
366
+ .slice(0, LINE_THREADS);
367
+ let changed = false;
368
+ for (const entry of recent) {
369
+ const version = `${entry.itemCount}:${entry.updatedAt}`;
370
+ if (lineChecked.get(entry.threadId) === version) continue;
371
+ lineChecked.set(entry.threadId, version);
372
+ try {
373
+ const exchange = await lastExchange(entry);
374
+ if (!exchange) continue;
375
+ if (
376
+ await threadLine.update(keyOf(entry.threadId), {
377
+ title: entry.title || "Untitled work",
378
+ ...exchange,
379
+ })
380
+ )
381
+ changed = true;
382
+ } catch (error) {
383
+ lineChecked.delete(entry.threadId);
384
+ log(`thread line: ${error.message}`);
385
+ }
386
+ }
387
+ if (changed) notify();
388
+ })().finally(() => {
389
+ lining = null;
390
+ });
391
+ }
392
+ /**
393
+ * Before a list: null when the rows held can be shown now (T3 Code is read again behind them), or the first read under
394
+ * this grant to wait for.
395
+ */
396
+ const ready = () => {
397
+ if (!authorized()) return null;
398
+ const reading = refresh();
399
+ return loadedGrant === grant ? null : reading;
400
+ };
401
+ const keepFresh = setInterval(() => {
402
+ if (watched()) void refresh();
403
+ }, WATCHED_REFRESH_MS);
404
+ keepFresh.unref?.();
405
+ const roots = () => {
406
+ if (!authorized()) return [];
407
+ const known = new Set([...threads.values()].map((entry) => entry.threadId));
408
+ const hidden = hiddenNow();
409
+ return [...threads.values()]
410
+ .filter(
411
+ (entry) =>
412
+ entry.relationshipToParent !== "subagent" ||
413
+ !known.has(entry.parentThreadId)
414
+ )
415
+ .map(summary)
416
+ .filter(
417
+ (thread) => hidden[thread.id] !== JSON.stringify(thread.activityVersion)
418
+ );
419
+ };
420
+ /** Removed from Harness's list (T3 keeps it): until it does something new, when it shows again. */
421
+ const hide = (id) => {
422
+ const entry = threads.get(id);
423
+ if (!authorized() || !entry)
424
+ return { ok: false, error: "This source thread is no longer available." };
425
+ const kept = Object.fromEntries(
426
+ Object.entries(hiddenNow()).filter(([key]) => threads.has(key))
427
+ );
428
+ kept[id] = JSON.stringify(summary(entry).activityVersion);
429
+ store.meta(HIDDEN_KEY, JSON.stringify(kept));
430
+ said = "";
431
+ notify();
432
+ return { ok: true };
433
+ };
434
+ const catalog = () => ({
435
+ ok: true,
436
+ environments: [
437
+ { id: "local", name: "This computer", available: true },
438
+ {
439
+ id: "t3",
440
+ name: "T3 Code",
441
+ access: authorized()?.state ?? null,
442
+ error: lastError,
443
+ },
444
+ ],
445
+ agents: [
446
+ ...detectAgents().map((entry) => ({
447
+ id: `local:${entry.agent}`,
448
+ agent: entry.agent,
449
+ name: nameOf(entry.agent),
450
+ environment: "local",
451
+ available: Boolean(entry.path),
452
+ reason: entry.path ? null : "Not found on this computer's PATH.",
453
+ protocol: member(entry.agent)?.runtime?.protocol ?? "native",
454
+ authentication: "not_checked",
455
+ })),
456
+ ...(authorized()
457
+ ? providers.map((entry) => ({
458
+ id: `t3:${entry.providerInstanceId}`,
459
+ agent: providerAgent(entry.providerInstanceId),
460
+ name:
461
+ entry.displayName ||
462
+ nameOf(providerAgent(entry.providerInstanceId)),
463
+ environment: "t3",
464
+ providerInstanceId: entry.providerInstanceId,
465
+ driverKind: entry.driverKind,
466
+ available: entry.canRunChildTask === true,
467
+ reason: entry.constraints?.join(" ") || null,
468
+ models: entry.models ?? [],
469
+ }))
470
+ : []),
471
+ ],
472
+ });
473
+ const owns = (id) => typeof id === "string" && id.startsWith("outside-t3-");
474
+ async function read(id) {
475
+ if (!authorized())
476
+ return {
477
+ ok: false,
478
+ code: "not_connected",
479
+ error: "Connect Harness to T3 Code to read this work.",
480
+ };
481
+ await refresh();
482
+ const readGrant = grant;
483
+ const root = threads.get(id);
484
+ if (!root)
485
+ return { ok: false, error: "This source thread is no longer available." };
486
+ const version = JSON.stringify([grant, summary(root).activityVersion]);
487
+ if (reads.get(id)?.version === version) return reads.get(id).result;
488
+ const selected = treeOf(root);
489
+ const runs = [];
490
+ const posts = [];
491
+ const timeline = [];
492
+ for (const entry of selected.values()) {
493
+ let after = null;
494
+ let more = true;
495
+ const items = [];
496
+ const positions = new Set();
497
+ let detail;
498
+ while (more) {
499
+ const page = await t3Tool("t3_thread_read", {
500
+ threadId: entry.threadId,
501
+ view: "activity",
502
+ limit: 100,
503
+ maxCharsPerItem: 12_000,
504
+ runLimit: 5,
505
+ ...(after === null ? {} : { afterPosition: after }),
506
+ });
507
+ detail = page;
508
+ items.push(...(page.items ?? []));
509
+ more = page.hasMore === true;
510
+ if (
511
+ more &&
512
+ (!Number.isInteger(page.nextPosition) ||
513
+ positions.has(page.nextPosition))
514
+ )
515
+ throw new Error("T3 Code returned an incomplete activity page.");
516
+ positions.add(page.nextPosition);
517
+ after = page.nextPosition;
518
+ }
519
+ const actual = { ...entry, ...detail.thread };
520
+ if (
521
+ !actual.activeRunId &&
522
+ actual.status === "idle" &&
523
+ detail.recentRuns?.[0]?.status
524
+ )
525
+ actual.status = detail.recentRuns[0].status;
526
+ const agent = providerAgent(entry.providerInstanceId);
527
+ const messages = items.filter((item) =>
528
+ ["user_message", "assistant_message"].includes(item.type)
529
+ );
530
+ const answer =
531
+ messages.filter((item) => item.type === "assistant_message").at(-1)
532
+ ?.text ?? null;
533
+ const ownPosts = messages.map((item) => ({
534
+ id: `${entry.threadId}:${item.itemId}`,
535
+ seq: posts.length + messages.indexOf(item) + 1,
536
+ author: item.type === "user_message" ? "user" : agent,
537
+ kind: item.type === "user_message" ? "message" : "result",
538
+ text:
539
+ (item.text ?? "") +
540
+ (item.textTruncated
541
+ ? "\n\n[Truncated by T3 Code. Open the original session for the full item.]"
542
+ : ""),
543
+ created_at: item.updatedAt || entry.updatedAt,
544
+ source: {
545
+ ...sourceOf(entry),
546
+ itemId: item.itemId,
547
+ truncated: item.textTruncated === true,
548
+ },
549
+ }));
550
+ posts.push(...ownPosts);
551
+ timeline.push(
552
+ ...ownPosts.map((post) => ({
553
+ type: "message",
554
+ seq: post.seq,
555
+ author: post.author,
556
+ text: post.text,
557
+ at: post.created_at,
558
+ result: post.kind === "result",
559
+ headline: null,
560
+ asks: false,
561
+ }))
562
+ );
563
+ const status = ACTIVE.has(actual.status)
564
+ ? "running"
565
+ : actual.status === "completed" || actual.settled === true
566
+ ? "done"
567
+ : actual.status === "failed"
568
+ ? "failed"
569
+ : "unknown";
570
+ runs.push({
571
+ kind: "task",
572
+ usage: null,
573
+ id: keyOf(entry.threadId),
574
+ agent,
575
+ ask:
576
+ messages.find((item) => item.type === "user_message")?.text ||
577
+ entry.title,
578
+ askedBy: entry.parentThreadId
579
+ ? providerAgent(
580
+ selected.get(entry.parentThreadId)?.providerInstanceId
581
+ )
582
+ : "user",
583
+ after: selected.has(entry.parentThreadId)
584
+ ? [keyOf(entry.parentThreadId)]
585
+ : [],
586
+ status,
587
+ answer,
588
+ startedAt: entry.createdAt,
589
+ endedAt: ACTIVE.has(actual.status) ? null : entry.updatedAt,
590
+ sessionId: entry.threadId,
591
+ folder:
592
+ actual.worktreePath ??
593
+ projects.get(entry.projectId)?.workspaceRoot ??
594
+ null,
595
+ source: {
596
+ ...sourceOf(actual),
597
+ runId: actual.activeRunId ?? detail.recentRuns?.[0]?.runId ?? null,
598
+ },
599
+ model: { model: entry.model, effort: null, by: "T3 Code" },
600
+ subagents: [],
601
+ steps: items
602
+ .filter(
603
+ (item) =>
604
+ item.type !== "reasoning" &&
605
+ item.type !== "user_message" &&
606
+ item.text
607
+ )
608
+ .slice(-10)
609
+ .map((item) => ({
610
+ kind: item.type === "assistant_message" ? "say" : "do",
611
+ text: item.text.slice(0, 1_000),
612
+ })),
613
+ });
614
+ }
615
+ if (!authorized() || grant !== readGrant)
616
+ return {
617
+ ok: false,
618
+ code: "not_connected",
619
+ error: "T3 Code access changed while reading this work.",
620
+ };
621
+ const result = {
622
+ ok: true,
623
+ thread: { ...summary(root), source: runs[0].source },
624
+ runs,
625
+ posts: posts.sort(
626
+ (a, b) => a.created_at.localeCompare(b.created_at) || a.seq - b.seq
627
+ ),
628
+ timeline: timeline.sort(
629
+ (a, b) => a.at.localeCompare(b.at) || a.seq - b.seq
630
+ ),
631
+ plans: [],
632
+ files: [],
633
+ kept: [],
634
+ rendering: [],
635
+ };
636
+ reads.set(id, { version, result });
637
+ return result;
638
+ }
639
+ async function control(request, agent) {
640
+ if (agent !== "user" || request.hostedCaller)
641
+ return { ok: false, error: "Only the person controls outside sessions." };
642
+ if (authorized()?.state !== "send")
643
+ return {
644
+ ok: false,
645
+ code: "read_only",
646
+ error:
647
+ "T3 Code access is read-only; approve control in T3 to send or stop.",
648
+ };
649
+ const id = String(request.id || "");
650
+ await refresh();
651
+ const entry = threads.get(id);
652
+ if (!entry)
653
+ return {
654
+ ok: false,
655
+ error: "This source session is no longer available.",
656
+ };
657
+ if (
658
+ entry.relationshipToParent === "subagent" ||
659
+ entry.creationSource === "provider"
660
+ )
661
+ return {
662
+ ok: false,
663
+ error:
664
+ "Control this delegated child through its original parent session.",
665
+ };
666
+ if (authorized()?.state !== "send")
667
+ return {
668
+ ok: false,
669
+ code: "read_only",
670
+ error: "T3 Code control access changed. Reconnect before sending.",
671
+ };
672
+ const requestId = String(request.requestId || "");
673
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(requestId))
674
+ return {
675
+ ok: false,
676
+ error: "A stable request identity is required for this action.",
677
+ };
678
+ const action = request.action;
679
+ if (!["send", "steer", "stop"].includes(action))
680
+ return { ok: false, error: "Choose send, steer or stop." };
681
+ const text = String(request.text || "").trim();
682
+ if (action !== "stop" && (!text || text.length > 50_000))
683
+ return {
684
+ ok: false,
685
+ error: "Write a message of at most 50,000 characters.",
686
+ };
687
+ const identity = createHash("sha256")
688
+ .update(
689
+ JSON.stringify({ id, action, text, runId: request.runId ?? null })
690
+ )
691
+ .digest("hex");
692
+ const receiptKey = `outside-control:${t3Access().environmentId}:${requestId}`;
693
+ const previous = controls.get(requestId);
694
+ if (previous)
695
+ return previous.identity === identity
696
+ ? previous.result
697
+ : {
698
+ ok: false,
699
+ error: "This action identity already belongs to different work.",
700
+ };
701
+ const saved = store.meta(receiptKey);
702
+ if (saved) {
703
+ const receipt = JSON.parse(saved);
704
+ if (receipt.identity !== identity)
705
+ return {
706
+ ok: false,
707
+ error: "This action identity already belongs to different work.",
708
+ };
709
+ return (
710
+ receipt.result ?? {
711
+ ok: false,
712
+ uncertain: true,
713
+ error:
714
+ "The previous delivery has no receipt. Inspect the original session before sending another message.",
715
+ }
716
+ );
717
+ }
718
+ const controlGrant = grant;
719
+ const perform = async () => {
720
+ if (grantOf(authorized()) !== controlGrant)
721
+ return {
722
+ ok: false,
723
+ error: "T3 Code access changed before this action.",
724
+ };
725
+ if (action === "stop") {
726
+ if (!request.runId)
727
+ return {
728
+ ok: false,
729
+ error: "Select the current run before stopping it.",
730
+ };
731
+ const current = await t3Tool("t3_thread_read", {
732
+ threadId: entry.threadId,
733
+ limit: 1,
734
+ runLimit: 1,
735
+ });
736
+ if (grantOf(authorized()) !== controlGrant)
737
+ return {
738
+ ok: false,
739
+ error: "T3 Code access changed before stopping this run.",
740
+ };
741
+ if (current.thread?.activeRunId !== request.runId)
742
+ return {
743
+ ok: false,
744
+ code: "changed",
745
+ error:
746
+ "This session changed. Read its current run before stopping it.",
747
+ };
748
+ return {
749
+ ok: true,
750
+ ...(await t3Tool("t3_thread_interrupt", {
751
+ threadId: entry.threadId,
752
+ runId: request.runId,
753
+ })),
754
+ };
755
+ }
756
+ return {
757
+ ok: true,
758
+ ...(await t3Tool("t3_thread_send", {
759
+ threadId: entry.threadId,
760
+ message: text,
761
+ mode: action === "steer" ? "steer" : "auto",
762
+ clientRequestId: requestId,
763
+ })),
764
+ };
765
+ };
766
+ store.meta(receiptKey, JSON.stringify({ identity }));
767
+ const result = perform()
768
+ .catch((error) => ({ ...failure(error), uncertain: true }))
769
+ .then((result) => {
770
+ store.meta(receiptKey, JSON.stringify({ identity, result }));
771
+ return result;
772
+ });
773
+ controls.set(requestId, { identity, result });
774
+ return result;
775
+ }
776
+ const command = (request, agent) => {
777
+ if (request.hostedCaller || !["user", "harness"].includes(agent))
778
+ return {
779
+ ok: false,
780
+ error: "Outside sessions are private to the person.",
781
+ };
782
+ const pending = (operation) => ({ pending: operation.catch(failure) });
783
+ if (request.command === "board.environments.list")
784
+ return pending(refresh().then(catalog));
785
+ if (request.command === "board.environments.control")
786
+ return pending(control(request, agent));
787
+ return { ok: false, error: "Unknown environment command." };
788
+ };
789
+ /** A T3 Code thread's own checkout and branch, for what it put into the world (landed.mjs); null without one. */
790
+ const work = (id) => {
791
+ const entry = threads.get(id);
792
+ if (!authorized() || !entry) return null;
793
+ const own = checkoutOf(entry);
794
+ const project = projects.get(entry.projectId)?.workspaceRoot ?? null;
795
+ // Working in the project itself, it landed work only through the commits it made (landed.mjs reads those).
796
+ if (!own && !(committers.has(entry.threadId) && project)) return null;
797
+ return {
798
+ id,
799
+ threadId: entry.threadId,
800
+ title: entry.title || "Untitled work",
801
+ agent: providerAgent(entry.providerInstanceId),
802
+ branch: own?.branch ?? null,
803
+ path: own?.path ?? project,
804
+ inPlace: !own,
805
+ createdAt: entry.createdAt,
806
+ updatedAt: entry.updatedAt,
807
+ };
808
+ };
809
+ /** Every T3 Code thread working in a checkout of its own, or that made commits in its project. */
810
+ const worked = () => [...threads.keys()].map(work).filter(Boolean);
811
+
812
+ return {
813
+ command,
814
+ refresh,
815
+ ready,
816
+ roots,
817
+ owns,
818
+ read,
819
+ hide,
820
+ control,
821
+ catalog,
822
+ work,
823
+ worked,
824
+ };
825
+ }