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
package/lib/runBrief.mjs CHANGED
@@ -4,6 +4,7 @@ import { claudeMemNotes } from "./claudemem.mjs";
4
4
  import { toldBlock } from "./cards.mjs";
5
5
  import { fitSections } from "./fit.mjs";
6
6
  import { oneLine } from "./oneLine.mjs";
7
+ import { profileBrief, readProfile } from "./profile.mjs";
7
8
 
8
9
  // What a board run is told when it starts, and which session it continues. The brief is made of named sections, each
9
10
  // with a priority, its source and a pointer to where the agent finds it (fit.mjs); over the budget the lowest-priority,
@@ -30,6 +31,8 @@ export function createRunBriefs({
30
31
  localEvent,
31
32
  localReady,
32
33
  log,
34
+ // The swarm's long-running memory (swarmMemory.mjs): what other threads and earlier jobs found, failed at or settled.
35
+ memory = null,
33
36
  roomGuide,
34
37
  store,
35
38
  threadFilesNote,
@@ -65,7 +68,7 @@ export function createRunBriefs({
65
68
 
66
69
  // The context engine's pack (context.mjs), the thread's task frame and the person's lessons that fit this work.
67
70
  const localContext = async (task, agent, { wake, room, dryRun }) => {
68
- const found = { pack: null, frame: "", lessons: [] };
71
+ const found = { pack: null, frame: "", lessons: [], memory: null };
69
72
  try {
70
73
  const thread = wake ? store.getTask(task.parent_id) : null;
71
74
  // The request is the task's own words, or for a thread turn the thread and its newest posts.
@@ -139,6 +142,16 @@ export function createRunBriefs({
139
142
  `lessons-carried:${task.id}`,
140
143
  JSON.stringify(found.lessons.map((lesson) => lesson.id))
141
144
  );
145
+ // Only for an agent that runs on this computer: memory holds the person's words and every thread's work.
146
+ found.memory =
147
+ memory && RUNNERS.has(agent)
148
+ ? await memory.forBrief({
149
+ agent,
150
+ folder: home,
151
+ threadId,
152
+ text: request,
153
+ })
154
+ : null;
142
155
  } catch (error) {
143
156
  log(`context pack for ${task.id}: ${error.message}`);
144
157
  }
@@ -160,6 +173,7 @@ export function createRunBriefs({
160
173
 
161
174
  const sectionsFor = ({ task, agent, wake, room, local, memory }) => {
162
175
  const pack = local.pack?.parts ?? {};
176
+ const person = RUNNERS.has(agent) ? readProfile() : null;
163
177
  const refs = task.context_refs.map(
164
178
  (ref) => `- ${ref.kind}: ${ref.ref}${ref.note ? ` (${ref.note})` : ""}`
165
179
  );
@@ -190,6 +204,14 @@ export function createRunBriefs({
190
204
  pointer: `Context: ${refs.length} reference${refs.length === 1 ? "" : "s"}; get_task ${task.id} lists them.`,
191
205
  },
192
206
  ...(room?.kind === "goal" ? [roomSection(room, agent)] : []),
207
+ // Who the agent works for, from the profile setup imported (profile.mjs); like lessons, only for agents here.
208
+ {
209
+ name: "the person",
210
+ priority: "recommended",
211
+ source: "Harness profile",
212
+ text: person ? profileBrief(person) : "",
213
+ pointer: person ? `You are working for ${person.displayName}.` : "",
214
+ },
193
215
  {
194
216
  name: "task frame",
195
217
  priority: "recommended",
@@ -197,6 +219,14 @@ export function createRunBriefs({
197
219
  text: local.frame,
198
220
  pointer: `What the relay knows about this task on this computer: get_task ${task.id} carries it.`,
199
221
  },
222
+ {
223
+ name: "swarm memory",
224
+ priority: "recommended",
225
+ source: "swarm memory",
226
+ text: local.memory?.text ?? "",
227
+ pointer:
228
+ "What other threads and earlier jobs found, failed at or settled: swarm_memory finds it by what you are looking for.",
229
+ },
200
230
  {
201
231
  name: "lessons",
202
232
  priority: "optional",
@@ -225,7 +255,7 @@ export function createRunBriefs({
225
255
  source: "context engine",
226
256
  text: pack.earlier ?? "",
227
257
  pointer:
228
- "Earlier sessions on these files: search_swarm finds what any of the person's agents did before.",
258
+ "Earlier sessions on these files: swarm_memory finds what any of the person's agents did before.",
229
259
  },
230
260
  {
231
261
  name: "library files",
@@ -0,0 +1,157 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { nameOf } from "./members.mjs";
3
+
4
+ /** Native permission choices for running, owned executions. A decision never starts or resumes a run. */
5
+ export function createRunRequests({ store, notifyBoard }) {
6
+ const pending = new Map();
7
+ const records = JSON.parse(store.meta("native-run-requests") || "[]").map(
8
+ (entry) =>
9
+ entry.status === "waiting" ? { ...entry, status: "interrupted" } : entry
10
+ );
11
+ const save = () => store.meta("native-run-requests", JSON.stringify(records));
12
+ save();
13
+ const running = (entry) => {
14
+ const task = store.getTask(entry.runId);
15
+ return task?.status === "running" && task.target_agent === entry.agent;
16
+ };
17
+ const tell = (entry) => notifyBoard(store.getTask(entry.runId));
18
+ const request = ({ runId, agent, approval, signal }) => {
19
+ signal.throwIfAborted();
20
+ if (!running({ runId, agent }))
21
+ throw new Error(
22
+ "This native permission does not belong to a running task."
23
+ );
24
+ const choices = approval.availableChoices.filter(
25
+ (choice) =>
26
+ choice.scope === "once" &&
27
+ ["approved", "denied", "abort"].includes(choice.decision)
28
+ );
29
+ if (!choices.length)
30
+ throw new Error(
31
+ "The agent offered no one-time decision Harness can present. Configure this permission in the original application."
32
+ );
33
+ const details = String(approval.rawArgs || "");
34
+ if (details.length > 20_000)
35
+ throw new Error(
36
+ "This native permission is too large to review here. Open the original application before granting it."
37
+ );
38
+ const entry = {
39
+ id: randomUUID(),
40
+ runId,
41
+ agent,
42
+ approvalId: approval.approvalId,
43
+ requirement: approval.currentRequirementId,
44
+ revision: createHash("sha256")
45
+ .update(JSON.stringify(approval))
46
+ .digest("hex"),
47
+ text: `Requested action: ${approval.toolName}`,
48
+ details,
49
+ protectedWrite: approval.protectedWrite === true,
50
+ choices: choices.map(({ choiceId, label, decision }) => ({
51
+ id: choiceId,
52
+ label,
53
+ allow: decision === "approved",
54
+ })),
55
+ status: "waiting",
56
+ at: new Date().toISOString(),
57
+ };
58
+ for (const old of pending.values())
59
+ if (
60
+ old.entry.runId === runId &&
61
+ old.entry.approvalId === entry.approvalId
62
+ )
63
+ old.close(
64
+ "replaced",
65
+ new Error("The native permission changed before it was answered.")
66
+ );
67
+ records.push(entry);
68
+ return new Promise((resolve, reject) => {
69
+ const close = (status, error, choice) => {
70
+ if (!pending.has(entry.id)) return;
71
+ entry.status = status;
72
+ pending.delete(entry.id);
73
+ signal.removeEventListener("abort", aborted);
74
+ save();
75
+ tell(entry);
76
+ if (error) {
77
+ error.code = `native_${status}`;
78
+ reject(error);
79
+ } else resolve({ choiceId: choice });
80
+ };
81
+ const aborted = () =>
82
+ close(
83
+ "cancelled",
84
+ new Error(
85
+ "This run stopped before the native permission was answered."
86
+ )
87
+ );
88
+ pending.set(entry.id, { entry, close });
89
+ signal.addEventListener("abort", aborted, { once: true });
90
+ save();
91
+ tell(entry);
92
+ if (signal.aborted) aborted();
93
+ });
94
+ };
95
+ const needs = (runId) =>
96
+ [...pending.values()]
97
+ .filter(({ entry }) => entry.runId === runId && running(entry))
98
+ .map(({ entry }) => ({
99
+ id: `permission:${entry.id}`,
100
+ kind: "permission",
101
+ agent: entry.agent,
102
+ runId,
103
+ requestId: entry.id,
104
+ text: `${nameOf(entry.agent)} needs your permission to continue.`,
105
+ at: entry.at,
106
+ }));
107
+ const finish = (runId) => {
108
+ for (const held of pending.values())
109
+ if (held.entry.runId === runId)
110
+ held.close(
111
+ "ended",
112
+ new Error("This run ended before its native permission was answered.")
113
+ );
114
+ };
115
+ const command = (input, agent) => {
116
+ if (agent !== "user" || input.hostedCaller)
117
+ return {
118
+ ok: false,
119
+ code: "sealed_only",
120
+ error:
121
+ "Read and answer native permissions on your computer or a browser linked to it.",
122
+ };
123
+ const held = pending.get(String(input.requestId || ""));
124
+ if (!held || !running(held.entry))
125
+ return {
126
+ ok: false,
127
+ code: "not_pending",
128
+ error: "This native permission is no longer waiting.",
129
+ };
130
+ const { entry } = held;
131
+ if (input.runId !== entry.runId)
132
+ return {
133
+ ok: false,
134
+ error: "This native permission belongs to another run.",
135
+ };
136
+ if (input.command === "board.native.read")
137
+ return { ok: true, request: entry };
138
+ if (input.command !== "board.native.decide")
139
+ return { ok: false, error: "Unknown native request command." };
140
+ if (input.revision !== entry.revision)
141
+ return {
142
+ ok: false,
143
+ code: "changed",
144
+ error:
145
+ "Read this native permission's current request before answering.",
146
+ };
147
+ const choice = entry.choices.find((option) => option.id === input.choiceId);
148
+ if (!choice)
149
+ return {
150
+ ok: false,
151
+ error: "Choose one of the native options shown for this request.",
152
+ };
153
+ held.close("submitted", null, choice.id);
154
+ return { ok: true, status: "submitted" };
155
+ };
156
+ return { request, needs, command, finish };
157
+ }
package/lib/runWorker.mjs CHANGED
@@ -8,6 +8,12 @@ import { sessionFile } from "./live.mjs";
8
8
  import { oneLine } from "./oneLine.mjs";
9
9
 
10
10
  // `briefs` (runBrief.mjs) says what each run is told and which session it continues.
11
+ /** Another agent's words on a goal's authority, without the person's tap or go (person-wake): restricted (docs/member-runs.md). */
12
+ export const restrictedRun = (store, task) =>
13
+ task.trust !== "user" &&
14
+ task.run_authorized_by === "goal" &&
15
+ store.meta(`person-wake:${task.id}`) !== "1";
16
+
11
17
  export function createRunWorker({
12
18
  RESCAN_MS,
13
19
  authority,
@@ -15,6 +21,9 @@ export function createRunWorker({
15
21
  contextEngine,
16
22
  installedAgents,
17
23
  machineId = () => null,
24
+ // A worker's board tables are a copy of home's: what it runs comes from home (machineRuns.mjs), never from the copy.
25
+ holdsBoard = () => true,
26
+ onlyItsOwn = () => false,
18
27
  localEvent,
19
28
  log,
20
29
  modelForRun,
@@ -23,9 +32,12 @@ export function createRunWorker({
23
32
  sync,
24
33
  taskRuns,
25
34
  threadRuns,
35
+ vaultEnv = () => null,
36
+ // A run's receipt was just kept (audit.mjs audits the run's claims with it).
37
+ onReceipt = () => {},
26
38
  }) {
27
39
  const { RUNNERS, standingRules } = authority;
28
- const { commitWake, settleWake, ranOutsideT3, t3Turn, taskInT3 } =
40
+ const { startTurn, commitRun, settleWake, ranOutsideT3, t3Turn, taskInT3 } =
29
41
  threadRuns.worker;
30
42
  const activeRuns = new Map();
31
43
  const lastStepNotice = new Map();
@@ -97,9 +109,11 @@ export function createRunWorker({
97
109
  notifyBoard(store.getTask(task.parent_id));
98
110
  };
99
111
  const runBoard = () => {
100
- if (runsHeld) return;
112
+ if (runsHeld || !holdsBoard()) return;
101
113
  // One run per folder at a time: each thread's worktree is its own folder, so threads run side by side.
102
- for (const task of store.runnableTasks(installedAgents, machineId())) {
114
+ for (const task of store.runnableTasks(installedAgents, machineId(), {
115
+ only: onlyItsOwn(),
116
+ })) {
103
117
  const agent = task.target_agent;
104
118
  // Where a task runs is settled once, before its slot: a run T3 carries out holds its thread, not a folder.
105
119
  if (task.kind === "task" && store.meta(`t3-run:${task.id}`) === null)
@@ -109,6 +123,13 @@ export function createRunWorker({
109
123
  noteWaiting(task, activeRuns.get(slot));
110
124
  continue;
111
125
  }
126
+ // A task T3 carries out still waits for a run working in its folder, such as the turn of the agent that handed it
127
+ // on: two runs never work one checkout at once.
128
+ const folder =
129
+ task.kind === "task" && slot.startsWith("t3:") && task.run_workspace
130
+ ? path.resolve(task.run_workspace)
131
+ : null;
132
+ if (folder && activeRuns.has(folder)) continue;
112
133
  // An agent resumes one session per thread: its review waits while its own turn there runs.
113
134
  if (slot.startsWith("review:") && runsInThread(agent, task.parent_id))
114
135
  continue;
@@ -143,15 +164,16 @@ export function createRunWorker({
143
164
  if (resumeSession && !task.session_id)
144
165
  store.setRunSession(task.id, resumeSession);
145
166
  const readOnly = store.meta(`review:${task.id}`) === "1";
146
- // Another agent's words on a goal's authority, without the person's tap or go (person-wake): restricted (docs/member-runs.md).
147
- const restricted =
148
- task.trust !== "user" &&
149
- task.run_authorized_by === "goal" &&
150
- store.meta(`person-wake:${task.id}`) !== "1";
167
+ const restricted = restrictedRun(store, task);
151
168
  const chosen = await modelForRun(task, agent);
152
169
  store.setRunModel(task.id, chosen);
153
170
  const { model, effort } = chosen;
154
171
  const t3 = inT3 ? t3Turn(task, agent, { model, effort }) : null;
172
+ // The person's environment grants (vault.mjs), never for a run they did not authorize: the values are in this
173
+ // run's environment, and what it says is scrubbed of them.
174
+ const secrets = restricted ? null : vaultEnv(task, agent);
175
+ const granted = secrets && Object.keys(secrets.env).length ? secrets : null;
176
+ startTurn(task);
155
177
  taskRuns.startTask(
156
178
  {
157
179
  runId: task.id,
@@ -166,6 +188,7 @@ export function createRunWorker({
166
188
  ...(readOnly ? { readOnly } : {}),
167
189
  ...(restricted ? { restricted } : {}),
168
190
  ...(t3 ? { t3 } : {}),
191
+ ...(granted ? { env: granted.env, scrub: granted.values } : {}),
169
192
  },
170
193
  (kind, text, extra) => {
171
194
  // The agent's session in a thread is resumed when the thread calls on it again; in T3 it is the agent's T3 thread.
@@ -214,6 +237,8 @@ export function createRunWorker({
214
237
  // A stopped run's task is already closed, so nothing else frees the agent's next run.
215
238
  setImmediate(runBoard);
216
239
  if (extra?.usage) store.setRunUsage(task.id, extra.usage);
240
+ // Its changes are committed before it reports, so the audit of its report sees what was not.
241
+ commitRun(task);
217
242
  // A run that failed without reaching its agent's own report ended early: the runner says why.
218
243
  const reported = store.reportTask(task.id, agent, {
219
244
  status: kind,
@@ -227,7 +252,6 @@ export function createRunWorker({
227
252
  );
228
253
  // A coding agent's finished turn settles once its receipt is read, so the coordinator's round that follows sees
229
254
  // what the run's own session shows (frames.mjs); the receipt is posted after the agent's own words.
230
- if (wake) commitWake(task);
231
255
  if (kind === "done" && RUNNERS.has(agent))
232
256
  void receiptFor(task.id, agent, { post: !wake }).then((line) => {
233
257
  if (wake) {
@@ -295,6 +319,9 @@ export function createRunWorker({
295
319
  test:
296
320
  result.tests.filter((test) => test.afterChange).at(-1)?.command ??
297
321
  null,
322
+ // Whether that last test passed, so a run that changed nothing still shows its tests passing (audit.mjs).
323
+ testOk:
324
+ result.tests.filter((test) => test.afterChange).at(-1)?.ok ?? null,
298
325
  repeatedFailures: result.repeatedFailures,
299
326
  at: new Date().toISOString(),
300
327
  })
@@ -306,6 +333,7 @@ export function createRunWorker({
306
333
  text: line,
307
334
  source: "receipts",
308
335
  });
336
+ onReceipt(taskId);
309
337
  localEvent("receipt", `${nameOf(agent)}'s run: ${result.verdict}`);
310
338
  void contextEngine.refresh();
311
339
  const forThread =
package/lib/runner.mjs CHANGED
@@ -3,6 +3,9 @@ import { fileURLToPath } from "node:url";
3
3
  import path from "node:path";
4
4
  import { spawn } from "node:child_process";
5
5
  import { agentEnvironment } from "./agentnode.mjs";
6
+ import { runtimeOf } from "./agentRuntimeConfig.mjs";
7
+ import { runProtocolTask } from "./agentRuntimes.mjs";
8
+ import { scrubValues } from "./vault.mjs";
6
9
 
7
10
  const running = new Set();
8
11
  const children = new Map();
@@ -15,9 +18,19 @@ export function stopAgentTask(runId) {
15
18
  return true;
16
19
  }
17
20
 
21
+ /**
22
+ * Stops every agent process the relay started, as the daemon shuts down. Without the daemon nothing reads their output
23
+ * or reports their end, and they would keep running (and holding memory) with no one waiting on them; the next daemon
24
+ * treats their turns as interrupted. Runs another app carries out are that app's to end.
25
+ */
26
+ export function stopAllRuns() {
27
+ for (const child of children.values())
28
+ if (!child.external) child.kill("SIGTERM");
29
+ }
30
+
18
31
  /** A run another app carries out (T3 Code, t3.mjs): Stop reaches it through `stop`. Returns its release. */
19
32
  export function trackRun(runId, stop) {
20
- const entry = { pid: null, kill: stop };
33
+ const entry = { pid: null, kill: stop, external: true };
21
34
  children.set(runId, entry);
22
35
  return () => {
23
36
  if (children.get(runId) === entry) children.delete(runId);
@@ -36,6 +49,13 @@ export function runningPids() {
36
49
  return [...children.values()].map((child) => child.pid).filter(Boolean);
37
50
  }
38
51
 
52
+ /** Each run in progress with its process, so a session one of them started is known as that run's. */
53
+ export function runningProcesses() {
54
+ return [...children]
55
+ .filter(([run, child]) => child.pid && !run.startsWith("helper:"))
56
+ .map(([run, child]) => ({ run, pid: child.pid }));
57
+ }
58
+
39
59
  export function resolveWorkingDirectory(requested) {
40
60
  if (!requested || !path.isAbsolute(requested))
41
61
  throw new Error("Delegated tasks require an absolute working directory.");
@@ -76,6 +96,7 @@ export const restrictedMcpConfig = () => ({
76
96
  fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)),
77
97
  "--agent",
78
98
  "claude-code",
99
+ "--restricted",
79
100
  ],
80
101
  },
81
102
  },
@@ -435,7 +456,7 @@ export function readRunSteps(file, limit = 200) {
435
456
  return steps.slice(-limit);
436
457
  }
437
458
 
438
- export function runAgentTask(task, emit, observe = () => {}) {
459
+ export function runAgentTask(task, emit, observe = () => {}, hooks = {}) {
439
460
  // One run per folder: two agents in one checkout would trip over each other; a thread's worktree is its own folder.
440
461
  // A read-only review edits nothing, so it goes beside whoever writes there (runWorker.mjs keeps one per agent).
441
462
  const slot = task.readOnly
@@ -456,9 +477,44 @@ export function runAgentTask(task, emit, observe = () => {}) {
456
477
  let environment;
457
478
  try {
458
479
  cwd = resolveWorkingDirectory(task.cwd);
480
+ if (runtimeOf(task.agent)) {
481
+ const controller = new AbortController();
482
+ running.add(slot);
483
+ children.set(task.runId, { kill: () => controller.abort() });
484
+ let released = false;
485
+ const release = () => {
486
+ if (released) return;
487
+ released = true;
488
+ running.delete(slot);
489
+ children.delete(task.runId);
490
+ };
491
+ let settled = false;
492
+ const report = (kind, text, extra) => {
493
+ if (settled) return;
494
+ if (["done", "failed"].includes(kind)) {
495
+ settled = true;
496
+ release();
497
+ }
498
+ emit(kind, text, extra);
499
+ };
500
+ void runProtocolTask(
501
+ { ...task, cwd },
502
+ { ...hooks, emit: report, observe, signal: controller.signal }
503
+ )
504
+ .catch((error) => report("failed", error.message, { failure: "exit" }))
505
+ .finally(release);
506
+ return;
507
+ }
459
508
  invocation = agentInvocation(task);
460
509
  // A Node agent runs on a Node it accepts, whichever Node Harness itself runs on.
461
- environment = agentEnvironment(invocation.command);
510
+ // The person's environment grants for this run (vault.mjs), over the daemon's own environment.
511
+ // HARNESS_RUN_ID tells the agent's own Harness tools which run they serve (mcp-stdio.mjs), where its MCP servers
512
+ // inherit the agent's environment.
513
+ environment = agentEnvironment(invocation.command, {
514
+ ...process.env,
515
+ ...(task.env ?? {}),
516
+ HARNESS_RUN_ID: task.runId,
517
+ });
462
518
  if (environment.error) throw new Error(environment.error);
463
519
  } catch (error) {
464
520
  emit("failed", error.message, { failure: "start" });
@@ -485,6 +541,12 @@ export function runAgentTask(task, emit, observe = () => {}) {
485
541
  children.set(task.runId, child);
486
542
 
487
543
  let resultText = "";
544
+ // A run with secrets in its environment (vault.mjs): its words are cleaned of them before anything is cut short, so
545
+ // a cut never leaves part of a value behind.
546
+ const clean = (text) =>
547
+ task.scrub instanceof Map && task.scrub.size
548
+ ? scrubValues(text, task.scrub)
549
+ : text;
488
550
  let modelError = "";
489
551
  let tail = "";
490
552
  let buffer = "";
@@ -498,7 +560,7 @@ export function runAgentTask(task, emit, observe = () => {}) {
498
560
  buffer = lines.pop() || "";
499
561
  for (const line of lines) {
500
562
  if (!line.trim()) continue;
501
- tail = (tail + "\n" + line).slice(-4_000);
563
+ tail = clean(tail + "\n" + line).slice(-4_000);
502
564
  let event;
503
565
  try {
504
566
  event = JSON.parse(line);
@@ -546,13 +608,15 @@ export function runAgentTask(task, emit, observe = () => {}) {
546
608
  : "";
547
609
  }
548
610
  for (const step of stepsOf(event))
549
- emit("progress", step.text.slice(0, 200), { step });
611
+ emit("progress", clean(step.text).slice(0, 200), {
612
+ step: { ...step, text: clean(step.text) },
613
+ });
550
614
  }
551
615
  });
552
616
  child.stderr?.on("data", (chunk) => {
553
617
  const raw = String(chunk);
554
618
  observe("stderr", raw);
555
- tail = (tail + "\n" + raw).slice(-4_000);
619
+ tail = clean(tail + "\n" + raw).slice(-4_000);
556
620
  });
557
621
  child.on("close", (code) => {
558
622
  running.delete(slot);
@@ -560,17 +624,16 @@ export function runAgentTask(task, emit, observe = () => {}) {
560
624
  if (code === 0 && modelError)
561
625
  emit(
562
626
  "failed",
563
- `${task.agent} stopped on an error from its model: ${modelError}`.slice(
564
- 0,
565
- 4_000
566
- ),
627
+ clean(
628
+ `${task.agent} stopped on an error from its model: ${modelError}`
629
+ ).slice(0, 4_000),
567
630
  { usage: usage.result(), failure: "exit" }
568
631
  );
569
632
  else if (code === 0)
570
633
  emit(
571
634
  "done",
572
635
  (
573
- resultText ||
636
+ clean(resultText) ||
574
637
  "The run finished; check the repository for its changes."
575
638
  ).slice(0, 20_000),
576
639
  { usage: usage.result() }
@@ -0,0 +1,55 @@
1
+ {
2
+ "about": "What must never leave in a message to someone else's agent or an outside place: keys and tokens by their well-known shapes, private-key blocks, env-style assignments of secrets, and anything that announces itself as a seed phrase. Read by the daemon (cli/lib/secrets.mjs) and by Harness's server (src/shared/secrets.ts), so both check the same list.",
3
+ "patterns": [
4
+ {
5
+ "reason": "a private key block",
6
+ "source": "-----BEGIN [A-Z ]*PRIVATE KEY-----",
7
+ "flags": ""
8
+ },
9
+ {
10
+ "reason": "an OpenAI-style API key",
11
+ "source": "\\bsk-[A-Za-z0-9_-]{20,}\\b",
12
+ "flags": ""
13
+ },
14
+ {
15
+ "reason": "an AWS access key",
16
+ "source": "\\bAKIA[0-9A-Z]{16}\\b",
17
+ "flags": ""
18
+ },
19
+ {
20
+ "reason": "a GitHub token",
21
+ "source": "\\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\\b|\\bgithub_pat_[A-Za-z0-9_]{40,}\\b",
22
+ "flags": ""
23
+ },
24
+ {
25
+ "reason": "a Slack token",
26
+ "source": "\\bxox[abpr]-[A-Za-z0-9-]{10,}\\b",
27
+ "flags": ""
28
+ },
29
+ {
30
+ "reason": "a JSON web token",
31
+ "source": "\\beyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b",
32
+ "flags": ""
33
+ },
34
+ {
35
+ "reason": "a 32-byte hex key",
36
+ "source": "\\b(0x)?[0-9a-fA-F]{64}\\b",
37
+ "flags": ""
38
+ },
39
+ {
40
+ "reason": "a Harness connection token",
41
+ "source": "\\bhmcp_[A-Za-z0-9]{12,}\\b",
42
+ "flags": ""
43
+ },
44
+ {
45
+ "reason": "a secret assigned in env style",
46
+ "source": "\\b[A-Z0-9_]*(SECRET|TOKEN|PASSWORD|PRIVATE_KEY|API_KEY)[A-Z0-9_]*\\s*[=:]\\s*['\"]?[^\\s'\"]{8,}",
47
+ "flags": ""
48
+ },
49
+ {
50
+ "reason": "a seed phrase",
51
+ "source": "\\b(seed phrase|mnemonic|recovery phrase)\\b[\\s\\S]{0,40}?(\\b[a-z]{3,8}\\b[\\s,]+){11,}",
52
+ "flags": "i"
53
+ }
54
+ ]
55
+ }
package/lib/secrets.mjs CHANGED
@@ -1,33 +1,16 @@
1
+ import { readFileSync } from "node:fs";
2
+
1
3
  // The outbound guard on a thread: what must never leave the machine in a reply to another
2
4
  // person's agent. A hit does not block forever; it holds the message for the person, with the
3
- // reason, so they can strip it or send it knowingly. Patterns are deliberately plain and
4
- // conservative: keys and tokens by their well-known shapes, private-key blocks, env-style
5
- // assignments of secrets, and anything that announces itself as a seed phrase.
5
+ // reason, so they can strip it or send it knowingly. The patterns live in secretPatterns.json, which
6
+ // Harness's server reads too (src/shared/secrets.ts), so both check the same list.
6
7
 
7
- const PATTERNS = [
8
- { reason: "a private key block", test: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
9
- { reason: "an OpenAI-style API key", test: /\bsk-[A-Za-z0-9_-]{20,}\b/ },
10
- { reason: "an AWS access key", test: /\bAKIA[0-9A-Z]{16}\b/ },
11
- {
12
- reason: "a GitHub token",
13
- test: /\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{40,}\b/,
14
- },
15
- { reason: "a Slack token", test: /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/ },
16
- {
17
- reason: "a JSON web token",
18
- test: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
19
- },
20
- { reason: "a 32-byte hex key", test: /\b(0x)?[0-9a-fA-F]{64}\b/ },
21
- { reason: "a Harness connection token", test: /\bhmcp_[A-Za-z0-9]{12,}\b/ },
22
- {
23
- reason: "a secret assigned in env style",
24
- test: /\b[A-Z0-9_]*(SECRET|TOKEN|PASSWORD|PRIVATE_KEY|API_KEY)[A-Z0-9_]*\s*[=:]\s*['"]?[^\s'"]{8,}/,
25
- },
26
- {
27
- reason: "a seed phrase",
28
- test: /\b(seed phrase|mnemonic|recovery phrase)\b[\s\S]{0,40}?(\b[a-z]{3,8}\b[\s,]+){11,}/i,
29
- },
30
- ];
8
+ const PATTERNS = JSON.parse(
9
+ readFileSync(new URL("./secretPatterns.json", import.meta.url), "utf8")
10
+ ).patterns.map((pattern) => ({
11
+ reason: pattern.reason,
12
+ test: new RegExp(pattern.source, pattern.flags),
13
+ }));
31
14
 
32
15
  /** The reason a text must be held, or null when nothing in it looks like a secret. */
33
16
  export function secretReason(text) {