tryharness 0.7.44 → 0.7.53

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 (101) hide show
  1. package/README.md +232 -12
  2. package/cli.mjs +406 -184
  3. package/lib/actorRoster.mjs +28 -5
  4. package/lib/adapters.mjs +9 -1
  5. package/lib/agentRuntimeConfig.mjs +36 -0
  6. package/lib/agentRuntimes.mjs +560 -0
  7. package/lib/atlas.mjs +7 -2
  8. package/lib/boardCommands.mjs +5 -10
  9. package/lib/boardFileCommands.mjs +2 -1
  10. package/lib/boardMirror.mjs +459 -0
  11. package/lib/boardProtocol.json +259 -6
  12. package/lib/boardTools.mjs +2 -6
  13. package/lib/bridge.mjs +27 -3
  14. package/lib/browserWake.mjs +60 -0
  15. package/lib/cards.mjs +35 -2
  16. package/lib/commands.mjs +20 -5
  17. package/lib/connectionTools.d.ts +13 -0
  18. package/lib/connectionTools.js +45 -0
  19. package/lib/connectorAuth.mjs +309 -0
  20. package/lib/connectorCatalog.json +41 -0
  21. package/lib/connectorCommands.mjs +121 -0
  22. package/lib/connectorGoogle.mjs +513 -0
  23. package/lib/connectors.mjs +805 -0
  24. package/lib/coordinator.mjs +16 -2
  25. package/lib/coreModels.mjs +78 -0
  26. package/lib/daemon.mjs +775 -46
  27. package/lib/desktop.mjs +7 -2
  28. package/lib/digest.mjs +32 -0
  29. package/lib/directLink.mjs +283 -0
  30. package/lib/environments.mjs +595 -0
  31. package/lib/folders.mjs +2 -2
  32. package/lib/goalCommands.mjs +61 -12
  33. package/lib/inference.mjs +263 -152
  34. package/lib/lessons.mjs +6 -0
  35. package/lib/lineup.mjs +324 -0
  36. package/lib/localmodels.mjs +10 -0
  37. package/lib/machineIdentity.mjs +3 -0
  38. package/lib/machineRoutes.mjs +40 -2
  39. package/lib/machineRuns.mjs +30 -3
  40. package/lib/machineSeal.mjs +69 -10
  41. package/lib/mcp-stdio.mjs +180 -98
  42. package/lib/mcpRelay.mjs +119 -0
  43. package/lib/members.json +12 -0
  44. package/lib/members.mjs +33 -0
  45. package/lib/modelMemory.mjs +100 -0
  46. package/lib/modelTiers.json +1183 -0
  47. package/lib/modelTiers.mjs +133 -0
  48. package/lib/models.mjs +41 -8
  49. package/lib/museSession.mjs +119 -0
  50. package/lib/nativeHost.mjs +203 -0
  51. package/lib/network.mjs +38 -1
  52. package/lib/nudge.mjs +10 -2
  53. package/lib/onboard.mjs +430 -1
  54. package/lib/oneclawLocal.mjs +150 -0
  55. package/lib/ownMachines.mjs +521 -36
  56. package/lib/pairing.mjs +165 -0
  57. package/lib/paths.mjs +4 -0
  58. package/lib/phones.mjs +61 -0
  59. package/lib/placeCommands.mjs +27 -0
  60. package/lib/places.mjs +10 -2
  61. package/lib/plans.mjs +151 -27
  62. package/lib/profile.mjs +152 -0
  63. package/lib/projectGit.mjs +328 -0
  64. package/lib/projectSettings.mjs +120 -0
  65. package/lib/projects.mjs +2539 -0
  66. package/lib/readiness.mjs +283 -0
  67. package/lib/repoLinks.mjs +354 -0
  68. package/lib/roomChannels.mjs +641 -0
  69. package/lib/runBrief.mjs +32 -2
  70. package/lib/runRequests.mjs +157 -0
  71. package/lib/runWorker.mjs +20 -7
  72. package/lib/runner.mjs +67 -8
  73. package/lib/secretPatterns.json +55 -0
  74. package/lib/secrets.mjs +10 -27
  75. package/lib/seen.mjs +102 -0
  76. package/lib/service.mjs +11 -6
  77. package/lib/sessionControl.mjs +10 -8
  78. package/lib/sessionIndex.mjs +5 -3
  79. package/lib/store.mjs +559 -30
  80. package/lib/subagents.mjs +8 -4
  81. package/lib/swarm.mjs +379 -38
  82. package/lib/swarmMemory.mjs +947 -0
  83. package/lib/t3.mjs +43 -13
  84. package/lib/taskCommands.mjs +58 -5
  85. package/lib/taskRuns.mjs +61 -11
  86. package/lib/team.json +17 -15
  87. package/lib/team.mjs +68 -18
  88. package/lib/threadRuns.mjs +50 -7
  89. package/lib/threadView.mjs +68 -15
  90. package/lib/tokenizer.mjs +405 -0
  91. package/lib/ui.mjs +16 -2
  92. package/lib/usageTotals.mjs +148 -0
  93. package/lib/vault.mjs +1144 -0
  94. package/lib/vaultCloud.mjs +117 -0
  95. package/lib/vaultCommands.mjs +201 -0
  96. package/lib/vaultTools.d.ts +12 -0
  97. package/lib/vaultTools.js +42 -0
  98. package/lib/windowAsks.mjs +42 -0
  99. package/lib/workFocus.mjs +59 -0
  100. package/lib/workLinks.mjs +90 -0
  101. package/package.json +9 -4
@@ -9,6 +9,10 @@ export function createActorRoster({
9
9
  authority,
10
10
  localWaker,
11
11
  connected,
12
+ // Whether the person put this agent in their swarm (lineup.mjs); an agent they did not is never offered.
13
+ inLineup = () => true,
14
+ // A coding agent's last check (readiness.mjs): whether it took a prompt, so every surface shows it ready or not.
15
+ readinessOf = () => null,
12
16
  // The person's computers that have this agent, this one included: [{ label, online, here }] (ownMachines.mjs).
13
17
  computersWith = () => [],
14
18
  }) {
@@ -53,19 +57,23 @@ export function createActorRoster({
53
57
  return `${nameOf(agent)} is not answering right now, so this waits until it does.`;
54
58
  return null;
55
59
  };
56
- /** The agents this person can ask right now: coding agents installed here, the server's while connected, any agent that has used the board, and those Harness says can be set up. */
60
+ /** The agents this person can ask right now, of those in their swarm: coding agents installed here, the server's while connected, any agent that has used the board, and those Harness says can be set up. */
57
61
  const available = () => {
58
62
  const seen = new Set(store.agentsSeen().map((row) => row.agent));
59
63
  const woken = localWakes();
60
64
  return ROOM_AGENTS.filter(
61
65
  (agent) =>
62
66
  agent === "harness" ||
67
+ // A coding agent is in the lineup of the computer it runs on, which runs it only then (installedAgents).
63
68
  (RUNNERS.has(agent)
64
69
  ? installedAgents.includes(agent) ||
65
70
  computersWith(agent).some((computer) => !computer.here)
66
- : CLOUD_AGENTS.has(agent)
67
- ? connected()
68
- : seen.has(agent) || Boolean(woken[agent]) || cloudSetup.has(agent))
71
+ : inLineup(agent) &&
72
+ (CLOUD_AGENTS.has(agent)
73
+ ? connected()
74
+ : seen.has(agent) ||
75
+ Boolean(woken[agent]) ||
76
+ cloudSetup.has(agent)))
69
77
  );
70
78
  };
71
79
  // Each agent's card (cards.mjs) as every other agent is told it, its setup included; `lessons`: what the person said
@@ -80,12 +88,27 @@ export function createActorRoster({
80
88
  }
81
89
  : card;
82
90
  };
91
+ const withReadiness = (card) => {
92
+ const check = RUNNERS.has(card.id) ? readinessOf(card.id) : null;
93
+ return check
94
+ ? {
95
+ ...card,
96
+ readiness: {
97
+ state: check.state,
98
+ detail: check.detail,
99
+ checkedAt: check.checkedAt,
100
+ },
101
+ }
102
+ : card;
103
+ };
83
104
  const cardsFor = (ids, { lessons = true } = {}) =>
84
105
  swarmCards(
85
106
  store,
86
107
  ids.map((id) => ({ id, setup: setupOf(id) })),
87
108
  { lessons }
88
- ).map(withMachines);
109
+ )
110
+ .map(withMachines)
111
+ .map(withReadiness);
89
112
  // The person's words from other threads (lessons.mjs) stay with the agents on this computer and Harness.
90
113
  const readsLessonsHere = (agent) => RUNNERS.has(agent) || agent === "harness";
91
114
 
package/lib/adapters.mjs CHANGED
@@ -409,7 +409,7 @@ export function configureAgents({
409
409
  configured: fs.existsSync(assets.pi),
410
410
  detail: "extension installed",
411
411
  });
412
- } else {
412
+ } else if (agent === "opencode") {
413
413
  installAsset(
414
414
  path.join(runtimeRoot, "assets", "opencode-plugin.js"),
415
415
  assets.opencode,
@@ -434,6 +434,14 @@ export function configureAgents({
434
434
  ? "MCP and plugin configured"
435
435
  : `plugin installed; MCP: ${diagnostic(added)}`,
436
436
  });
437
+ } else {
438
+ states.push({
439
+ agent,
440
+ installed: true,
441
+ configured: true,
442
+ detail:
443
+ "Uses its installed protocol for each Harness run; native login and permissions still apply.",
444
+ });
437
445
  }
438
446
  }
439
447
  return states;
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { member } from "./members.mjs";
3
+ import { paths } from "./paths.mjs";
4
+
5
+ /** Installed agents only: the owner's executable selection never comes from a model or task. */
6
+ export function runtimeOf(agent) {
7
+ const runtime = member(agent)?.runtime;
8
+ if (!runtime) return null;
9
+ let configured;
10
+ try {
11
+ configured = JSON.parse(readFileSync(paths.config, "utf8")).agentCommands?.[
12
+ agent
13
+ ];
14
+ } catch {}
15
+ const defaultCommand =
16
+ agent === "antigravity" && process.platform === "win32"
17
+ ? "agy_acp_server.exe"
18
+ : runtime.command;
19
+ const command =
20
+ typeof configured?.command === "string" && configured.command.trim()
21
+ ? configured.command
22
+ : defaultCommand;
23
+ const args =
24
+ Array.isArray(configured?.args) &&
25
+ configured.args.every((arg) => typeof arg === "string")
26
+ ? configured.args
27
+ : runtime.args;
28
+ return {
29
+ ...runtime,
30
+ command,
31
+ args,
32
+ ...(typeof configured?.approvalMode === "string"
33
+ ? { approvalMode: configured.approvalMode }
34
+ : {}),
35
+ };
36
+ }
@@ -0,0 +1,560 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { Readable, Writable } from "node:stream";
4
+ import { fileURLToPath } from "node:url";
5
+ import { tmpdir } from "node:os";
6
+ import { agentEnvironment } from "./agentnode.mjs";
7
+ import { resolveCommand } from "./commands.mjs";
8
+ import { runtimeOf } from "./agentRuntimeConfig.mjs";
9
+ import { openMuseSession } from "./museSession.mjs";
10
+
11
+ const progress = (emit, observe, kind, text) => {
12
+ observe(
13
+ "stdout",
14
+ JSON.stringify({ type: "harness.step", kind, text }) + "\n"
15
+ );
16
+ emit("progress", text.slice(0, 200), { step: { kind, text } });
17
+ };
18
+ const stopped = () => new Error("The person stopped this run.");
19
+ const CLIENT_INFO = {
20
+ name: "harness",
21
+ title: "Harness",
22
+ version: JSON.parse(
23
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
24
+ ).version,
25
+ };
26
+
27
+ const optionsOf = (option) =>
28
+ (option?.options ?? []).flatMap((entry) => entry.options ?? [entry]);
29
+ const selectedRuntime = (agent, grantedEnv = null) => {
30
+ const runtime = runtimeOf(agent);
31
+ const command = runtime && resolveCommand(runtime.command);
32
+ if (!command)
33
+ throw new Error(
34
+ `Install and authenticate ${agent}, or configure its executable in Harness.`
35
+ );
36
+ const environment = agentEnvironment(
37
+ command,
38
+ grantedEnv ? { ...process.env, ...grantedEnv } : process.env
39
+ );
40
+ if (environment.error) throw new Error(environment.error);
41
+ return { ...runtime, command, env: environment.env };
42
+ };
43
+
44
+ /** Explicit discovery opens a disposable protocol connection, never an inference turn. */
45
+ export async function listProtocolModels(agent, observeChild = () => {}) {
46
+ const runtime = selectedRuntime(agent);
47
+ if (runtime.protocol === "msp") {
48
+ const { spawnMspConnection } = await import("@muse-code/sdk");
49
+ const handshake = spawnMspConnection({
50
+ command: runtime.command,
51
+ args: runtime.args,
52
+ env: runtime.env,
53
+ cwd: tmpdir(),
54
+ });
55
+ try {
56
+ const host = await handshake.initialize({ clientInfo: CLIENT_INFO });
57
+ const catalog = await host.connection.request("model/list", {});
58
+ if (catalog.providerId !== "meta")
59
+ throw new Error(
60
+ "Muse Code returned a model catalog for another provider."
61
+ );
62
+ return (catalog.models ?? [])
63
+ .filter((entry) => typeof entry.modelId === "string")
64
+ .map((entry) => ({
65
+ id: entry.modelId,
66
+ about: entry.displayLabel ?? null,
67
+ // Unknown or absent effort capabilities stay unknown, never a guessed list.
68
+ efforts: Array.isArray(entry.variants) ? entry.variants : [],
69
+ defaultEffort:
70
+ Array.isArray(entry.variants) &&
71
+ entry.variants.includes(entry.defaultReasoningEffort)
72
+ ? entry.defaultReasoningEffort
73
+ : null,
74
+ context: null,
75
+ }));
76
+ } finally {
77
+ await handshake.close();
78
+ }
79
+ }
80
+ const acp = await import("@agentclientprotocol/sdk");
81
+ const child = spawn(runtime.command, runtime.args, {
82
+ cwd: tmpdir(),
83
+ env: runtime.env,
84
+ });
85
+ observeChild(child);
86
+ child.stdin.on("error", () => {});
87
+ child.stderr.resume();
88
+ let connection;
89
+ child.on("error", (error) => connection?.close(error));
90
+ child.on("close", () =>
91
+ connection?.close(
92
+ new Error("The agent closed before its model catalog was read.")
93
+ )
94
+ );
95
+ connection = acp
96
+ .client(CLIENT_INFO)
97
+ .onRequest("session/request_permission", () => ({
98
+ outcome: { outcome: "cancelled" },
99
+ }))
100
+ .connect(
101
+ acp.ndJsonStream(
102
+ Writable.toWeb(child.stdin),
103
+ Readable.toWeb(child.stdout)
104
+ )
105
+ );
106
+ try {
107
+ await connection.agent.request("initialize", {
108
+ protocolVersion: acp.PROTOCOL_VERSION,
109
+ clientInfo: CLIENT_INFO,
110
+ clientCapabilities: {
111
+ fs: { readTextFile: false, writeTextFile: false },
112
+ terminal: false,
113
+ },
114
+ });
115
+ const session = await connection.agent.request("session/new", {
116
+ cwd: tmpdir(),
117
+ mcpServers: [],
118
+ });
119
+ const modelOption = session.configOptions?.find(
120
+ (entry) => entry.category === "model" && entry.type === "select"
121
+ );
122
+ return optionsOf(modelOption).map((entry) => ({
123
+ id: entry.value,
124
+ about: entry.name ?? null,
125
+ efforts: [],
126
+ defaultEffort: null,
127
+ context: null,
128
+ }));
129
+ } finally {
130
+ connection.close();
131
+ child.stdin.end();
132
+ child.kill("SIGTERM");
133
+ }
134
+ }
135
+
136
+ async function runAcp(task, runtime, hooks) {
137
+ const { emit, observe, signal, requestApproval } = hooks;
138
+ const acp = await import("@agentclientprotocol/sdk");
139
+ signal.throwIfAborted();
140
+ const child = spawn(runtime.command, runtime.args, {
141
+ cwd: task.cwd,
142
+ env: runtime.env,
143
+ });
144
+ let processError;
145
+ child.on("error", (error) => {
146
+ processError = error;
147
+ connection?.close(error);
148
+ });
149
+ child.stdin.on("error", () => {});
150
+ child.stderr.on("data", (chunk) => observe("stderr", String(chunk)));
151
+ let connection;
152
+ let sessionId;
153
+ let answer = "";
154
+ let totalCost = null;
155
+ let baselineCost = task.sessionId ? null : 0;
156
+ let prompting = false;
157
+ const app = acp
158
+ .client(CLIENT_INFO)
159
+ .onRequest("session/request_permission", async ({ params: request }) => {
160
+ // These adapters accept only person-authorized unrestricted runs. Never persist a permission grant.
161
+ if (!prompting || signal.aborted || request.sessionId !== sessionId)
162
+ return { outcome: { outcome: "cancelled" } };
163
+ if (requestApproval) {
164
+ const approvalId = `${sessionId}:${request.toolCall.toolCallId}`;
165
+ try {
166
+ const selected = await requestApproval(
167
+ {
168
+ approvalId,
169
+ currentRequirementId: { approvalId, sourceIndex: 0 },
170
+ toolName:
171
+ request.toolCall.title || request.toolCall.kind || "its tool",
172
+ rawArgs: JSON.stringify(
173
+ request.toolCall.rawInput ?? request.toolCall
174
+ ),
175
+ availableChoices: request.options
176
+ .filter((option) =>
177
+ ["allow_once", "reject_once"].includes(option.kind)
178
+ )
179
+ .map((option) => ({
180
+ choiceId: option.optionId,
181
+ label: option.name,
182
+ scope: "once",
183
+ decision:
184
+ option.kind === "allow_once" ? "approved" : "denied",
185
+ })),
186
+ },
187
+ signal
188
+ );
189
+ if (!prompting || signal.aborted)
190
+ return { outcome: { outcome: "cancelled" } };
191
+ return {
192
+ outcome: { outcome: "selected", optionId: selected.choiceId },
193
+ };
194
+ } catch {
195
+ return { outcome: { outcome: "cancelled" } };
196
+ }
197
+ }
198
+ const choice = request.options.find(
199
+ (option) => option.kind === "allow_once"
200
+ );
201
+ return {
202
+ outcome: choice
203
+ ? { outcome: "selected", optionId: choice.optionId }
204
+ : { outcome: "cancelled" },
205
+ };
206
+ })
207
+ .onNotification(
208
+ "session/update",
209
+ ({ params: { sessionId: source, update } }) => {
210
+ if (!sessionId || source !== sessionId) return;
211
+ observe("stdout", JSON.stringify({ sessionId: source, update }) + "\n");
212
+ if (
213
+ update.sessionUpdate === "agent_message_chunk" &&
214
+ update.content?.type === "text"
215
+ ) {
216
+ answer += update.content.text;
217
+ progress(emit, observe, "say", answer.slice(-1_000));
218
+ }
219
+ if (
220
+ ["tool_call", "tool_call_update"].includes(update.sessionUpdate) &&
221
+ update.title
222
+ )
223
+ progress(emit, observe, "do", update.title);
224
+ if (
225
+ update.sessionUpdate === "usage_update" &&
226
+ update.cost?.currency === "USD" &&
227
+ Number.isFinite(update.cost.amount)
228
+ ) {
229
+ totalCost = update.cost.amount;
230
+ if (!prompting) baselineCost = totalCost;
231
+ }
232
+ }
233
+ );
234
+ connection = app.connect(
235
+ acp.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout))
236
+ );
237
+ child.on("close", () =>
238
+ connection.close(
239
+ processError ||
240
+ new Error("The ACP process exited before the turn completed.")
241
+ )
242
+ );
243
+ const cancel = () => {
244
+ if (sessionId)
245
+ void connection.agent
246
+ .notify("session/cancel", { sessionId })
247
+ .catch(() => {});
248
+ connection.close(stopped());
249
+ child.kill("SIGTERM");
250
+ };
251
+ signal.addEventListener("abort", cancel, { once: true });
252
+ emit("accepted");
253
+ try {
254
+ const initialized = await connection.agent.request("initialize", {
255
+ protocolVersion: acp.PROTOCOL_VERSION,
256
+ clientInfo: CLIENT_INFO,
257
+ clientCapabilities: {
258
+ fs: { readTextFile: false, writeTextFile: false },
259
+ terminal: false,
260
+ },
261
+ });
262
+ if (task.sessionId && !initialized.agentCapabilities?.loadSession)
263
+ throw new Error(
264
+ "This ACP agent cannot resume its existing session; Harness did not start a replacement."
265
+ );
266
+ const args = {
267
+ cwd: task.cwd,
268
+ mcpServers: [
269
+ {
270
+ name: "harness",
271
+ command: process.execPath,
272
+ args: [
273
+ fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)),
274
+ "--agent",
275
+ task.agent,
276
+ ],
277
+ env: [{ name: "HARNESS_RUN_ID", value: task.runId }],
278
+ },
279
+ ],
280
+ ...(task.sessionId ? { sessionId: task.sessionId } : {}),
281
+ };
282
+ const session = await connection.agent.request(
283
+ task.sessionId ? "session/load" : "session/new",
284
+ args
285
+ );
286
+ sessionId = task.sessionId || session.sessionId;
287
+ if (!sessionId)
288
+ throw new Error("The ACP agent did not identify its session.");
289
+ emit("session", sessionId, { cwd: task.cwd });
290
+ let configuration = session.configOptions ?? [];
291
+ for (const [category, value] of [
292
+ ["model", task.model],
293
+ ["thought_level", task.effort],
294
+ ]) {
295
+ if (!value) continue;
296
+ const option = configuration.find((entry) => entry.category === category);
297
+ if (!option)
298
+ throw new Error(
299
+ `This ACP agent did not offer a ${category} selection; its settings were not substituted.`
300
+ );
301
+ if (!optionsOf(option).some((entry) => entry.value === value))
302
+ throw new Error(
303
+ `This ACP agent did not offer the requested ${category}; Harness did not submit the turn.`
304
+ );
305
+ const applied = await connection.agent.request(
306
+ "session/set_config_option",
307
+ {
308
+ sessionId,
309
+ configId: option.id,
310
+ value,
311
+ }
312
+ );
313
+ configuration = applied.configOptions;
314
+ if (
315
+ applied.configOptions?.find((entry) => entry.id === option.id)
316
+ ?.currentValue !== value
317
+ )
318
+ throw new Error(
319
+ `The ACP agent did not apply the requested ${category}; Harness did not submit the turn.`
320
+ );
321
+ }
322
+ // Loading history must not become this run's answer or bill.
323
+ answer = "";
324
+ prompting = true;
325
+ const result = await connection.agent.request("session/prompt", {
326
+ sessionId,
327
+ prompt: [{ type: "text", text: task.brief }],
328
+ });
329
+ signal.throwIfAborted();
330
+ if (result.stopReason !== "end_turn")
331
+ throw new Error(`ACP turn stopped: ${result.stopReason}.`);
332
+ emit("done", answer || "The agent completed its turn.", {
333
+ usage:
334
+ totalCost === null || baselineCost === null || totalCost < baselineCost
335
+ ? null
336
+ : {
337
+ cost_usd: totalCost - baselineCost,
338
+ input_tokens: null,
339
+ output_tokens: null,
340
+ cache_read_tokens: null,
341
+ cache_write_tokens: null,
342
+ },
343
+ });
344
+ } catch (error) {
345
+ emit("failed", error.message, {
346
+ failure: "exit",
347
+ usage:
348
+ totalCost === null || baselineCost === null || totalCost < baselineCost
349
+ ? null
350
+ : {
351
+ cost_usd: totalCost - baselineCost,
352
+ input_tokens: null,
353
+ output_tokens: null,
354
+ cache_read_tokens: null,
355
+ cache_write_tokens: null,
356
+ },
357
+ });
358
+ } finally {
359
+ signal.removeEventListener("abort", cancel);
360
+ connection.close();
361
+ child.stdin.end();
362
+ child.kill("SIGTERM");
363
+ }
364
+ }
365
+
366
+ async function runMuse(
367
+ task,
368
+ runtime,
369
+ { emit, observe, signal, requestApproval }
370
+ ) {
371
+ if (Number(process.versions.node.split(".")[0]) < 20)
372
+ throw new Error("Muse Code's SDK requires Node 20 or newer.");
373
+ const { spawnMspConnection } = await import("@muse-code/sdk");
374
+ signal.throwIfAborted();
375
+ const handshake = spawnMspConnection({
376
+ command: runtime.command,
377
+ args: runtime.args,
378
+ cwd: task.cwd,
379
+ env: runtime.env,
380
+ onStderr: (text) => observe("stderr", text),
381
+ });
382
+ const cancel = () => {
383
+ void handshake.close().catch(() => {});
384
+ };
385
+ signal.addEventListener("abort", cancel, { once: true });
386
+ let client;
387
+ try {
388
+ const host = await handshake.initialize({
389
+ clientInfo: CLIENT_INFO,
390
+ capabilities: {
391
+ requestedCapabilities: ["sessionMcp"],
392
+ userInputDialogs: false,
393
+ },
394
+ });
395
+ signal.throwIfAborted();
396
+ emit("accepted");
397
+ client = await openMuseSession({
398
+ host,
399
+ observe,
400
+ task: { ...task, approvalMode: runtime.approvalMode },
401
+ signal,
402
+ onApproval: requestApproval
403
+ ? async (approval) => {
404
+ const chosen = await requestApproval(approval, signal);
405
+ signal.throwIfAborted();
406
+ return chosen;
407
+ }
408
+ : undefined,
409
+ onApprovalError: (failure) => {
410
+ if (
411
+ failure.kind === "handlerThrew" &&
412
+ ["native_replaced", "native_cancelled", "native_ended"].includes(
413
+ failure.error?.code
414
+ )
415
+ )
416
+ return;
417
+ if (
418
+ failure.kind === "submitFailed" &&
419
+ [-32051, -32053].includes(failure.error?.code)
420
+ ) {
421
+ progress(
422
+ emit,
423
+ observe,
424
+ "do",
425
+ "The native permission changed. Review its current request before answering."
426
+ );
427
+ return;
428
+ }
429
+ progress(
430
+ emit,
431
+ observe,
432
+ "do",
433
+ `Muse permission could not be confirmed (${failure.kind}).`
434
+ );
435
+ void handshake.close().catch(() => {});
436
+ },
437
+ });
438
+ const { session } = client;
439
+ let original = session.opening?.result?.session;
440
+ if (
441
+ typeof original?.workspaceRoot !== "string" ||
442
+ realpathSync(original.workspaceRoot) !== realpathSync(task.cwd)
443
+ )
444
+ throw new Error(
445
+ "Muse Code opened a different working folder; Harness did not submit the turn."
446
+ );
447
+ if (original.activeTurnId !== null)
448
+ throw new Error(
449
+ "Muse has not shown this session to be idle. Harness did not change its model or submit another turn."
450
+ );
451
+ if (task.sessionId && task.model && original.modelId !== task.model) {
452
+ const catalog = await host.connection.request("model/list", {
453
+ sessionId: session.sessionId,
454
+ });
455
+ if (!catalog.models?.some((model) => model.modelId === task.model))
456
+ throw new Error(
457
+ "Muse Code did not offer this model for the existing session. Harness did not submit the turn."
458
+ );
459
+ await host.connection.command("session/setModel", {
460
+ sessionId: session.sessionId,
461
+ model: { modelId: task.model, providerId: catalog.providerId },
462
+ });
463
+ const confirmed = await host.connection.command("session/read", {
464
+ sessionId: session.sessionId,
465
+ });
466
+ original = confirmed.session;
467
+ if (
468
+ original.sessionId !== session.sessionId ||
469
+ original.activeTurnId !== null ||
470
+ realpathSync(original.workspaceRoot) !== realpathSync(task.cwd)
471
+ )
472
+ throw new Error(
473
+ "The Muse session changed while applying this model. Harness did not submit the turn."
474
+ );
475
+ }
476
+ if (task.model && original.modelId !== task.model)
477
+ throw new Error(
478
+ "Muse Code did not apply the requested model; Harness did not submit the turn."
479
+ );
480
+ if (task.effort) {
481
+ const catalog = await host.connection.request("model/list", {
482
+ sessionId: session.sessionId,
483
+ });
484
+ const offered = catalog.models?.find(
485
+ (entry) => entry.modelId === original.modelId
486
+ );
487
+ if (
488
+ !Array.isArray(offered?.variants) ||
489
+ !offered.variants.includes(task.effort)
490
+ )
491
+ throw new Error(
492
+ "Muse Code did not offer this model's requested effort; Harness did not submit the turn."
493
+ );
494
+ }
495
+ emit("session", session.sessionId, {
496
+ cwd: task.cwd,
497
+ resumable: client.resumable,
498
+ });
499
+ const turn = await session.sendUserTurn({
500
+ input: [{ type: "text", text: task.brief }],
501
+ ...(task.effort ? { reasoningEffort: task.effort } : {}),
502
+ });
503
+ const messages = new Map();
504
+ for await (const item of turn.items()) {
505
+ observe(
506
+ "stdout",
507
+ JSON.stringify({ sessionId: session.sessionId, item }) + "\n"
508
+ );
509
+ if (item.kind === "agentMessage" && typeof item.text === "string") {
510
+ messages.set(item.itemId, item.text);
511
+ progress(emit, observe, "say", item.text);
512
+ }
513
+ if (item.kind === "toolCall")
514
+ progress(
515
+ emit,
516
+ observe,
517
+ "do",
518
+ item.displayLabel?.active || item.toolName || "Working in Muse Code"
519
+ );
520
+ }
521
+ const outcome = await turn.completed;
522
+ signal.throwIfAborted();
523
+ const succeeded =
524
+ outcome.kind === "completed" && outcome.params.terminal === "completed";
525
+ const usage = outcome.params?.usage;
526
+ const text = succeeded
527
+ ? [...messages.values()].join("\n") || "Muse Code completed its turn."
528
+ : outcome.params?.error?.message ||
529
+ `Muse Code turn ${outcome.params?.terminal || outcome.kind}.`;
530
+ emit(succeeded ? "done" : "failed", text, {
531
+ usage: usage
532
+ ? {
533
+ input_tokens: usage.inputTokens,
534
+ output_tokens: usage.outputTokens,
535
+ cache_read_tokens: usage.cacheReadTokens ?? null,
536
+ cache_write_tokens: usage.cacheWriteTokens ?? null,
537
+ cost_usd: null,
538
+ }
539
+ : null,
540
+ });
541
+ } finally {
542
+ signal.removeEventListener("abort", cancel);
543
+ if (client) await client.close();
544
+ else await handshake.close();
545
+ }
546
+ }
547
+
548
+ /** ACP and MSP adapters share the existing run lifecycle; native permissions remain the agent's. */
549
+ export async function runProtocolTask(task, hooks) {
550
+ if (task.readOnly || task.restricted)
551
+ throw new Error(
552
+ `${task.agent} cannot enforce Harness's restricted or read-only contract. Choose an agent that can.`
553
+ );
554
+ const selected = selectedRuntime(task.agent, task.env);
555
+ task = { ...task, sessionId: task.resumeSession ?? task.sessionId };
556
+ const runtime = selected;
557
+ return runtime.protocol === "msp"
558
+ ? runMuse(task, selected, hooks)
559
+ : runAcp(task, selected, hooks);
560
+ }