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,570 @@
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
+ // An existing session is loaded (its history replayed) or, where the agent offers only that, resumed without its
263
+ // history (session/resume, as DeepSeek Harness's ACP does).
264
+ const capabilities = initialized.agentCapabilities ?? {};
265
+ const reopen = !task.sessionId
266
+ ? "session/new"
267
+ : capabilities.loadSession
268
+ ? "session/load"
269
+ : capabilities.sessionCapabilities?.resume
270
+ ? "session/resume"
271
+ : null;
272
+ if (!reopen)
273
+ throw new Error(
274
+ "This ACP agent cannot resume its existing session; Harness did not start a replacement."
275
+ );
276
+ const args = {
277
+ cwd: task.cwd,
278
+ // A readiness check (readiness.mjs) runs without Harness's tools.
279
+ mcpServers: task.withoutHarnessTools
280
+ ? []
281
+ : [
282
+ {
283
+ name: "harness",
284
+ command: process.execPath,
285
+ args: [
286
+ fileURLToPath(new URL("./mcp-stdio.mjs", import.meta.url)),
287
+ "--agent",
288
+ task.agent,
289
+ ],
290
+ env: [{ name: "HARNESS_RUN_ID", value: task.runId }],
291
+ },
292
+ ],
293
+ ...(task.sessionId ? { sessionId: task.sessionId } : {}),
294
+ };
295
+ const session = await connection.agent.request(reopen, args);
296
+ sessionId = task.sessionId || session.sessionId;
297
+ if (!sessionId)
298
+ throw new Error("The ACP agent did not identify its session.");
299
+ emit("session", sessionId, { cwd: task.cwd });
300
+ let configuration = session.configOptions ?? [];
301
+ for (const [category, value] of [
302
+ ["model", task.model],
303
+ ["thought_level", task.effort],
304
+ ]) {
305
+ if (!value) continue;
306
+ const option = configuration.find((entry) => entry.category === category);
307
+ if (!option)
308
+ throw new Error(
309
+ `This ACP agent did not offer a ${category} selection; its settings were not substituted.`
310
+ );
311
+ if (!optionsOf(option).some((entry) => entry.value === value))
312
+ throw new Error(
313
+ `This ACP agent did not offer the requested ${category}; Harness did not submit the turn.`
314
+ );
315
+ const applied = await connection.agent.request(
316
+ "session/set_config_option",
317
+ {
318
+ sessionId,
319
+ configId: option.id,
320
+ value,
321
+ }
322
+ );
323
+ configuration = applied.configOptions;
324
+ if (
325
+ applied.configOptions?.find((entry) => entry.id === option.id)
326
+ ?.currentValue !== value
327
+ )
328
+ throw new Error(
329
+ `The ACP agent did not apply the requested ${category}; Harness did not submit the turn.`
330
+ );
331
+ }
332
+ // Loading history must not become this run's answer or bill.
333
+ answer = "";
334
+ prompting = true;
335
+ const result = await connection.agent.request("session/prompt", {
336
+ sessionId,
337
+ prompt: [{ type: "text", text: task.brief }],
338
+ });
339
+ signal.throwIfAborted();
340
+ if (result.stopReason !== "end_turn")
341
+ throw new Error(`ACP turn stopped: ${result.stopReason}.`);
342
+ emit("done", answer || "The agent completed its turn.", {
343
+ usage:
344
+ totalCost === null || baselineCost === null || totalCost < baselineCost
345
+ ? null
346
+ : {
347
+ cost_usd: totalCost - baselineCost,
348
+ input_tokens: null,
349
+ output_tokens: null,
350
+ cache_read_tokens: null,
351
+ cache_write_tokens: null,
352
+ },
353
+ });
354
+ } catch (error) {
355
+ emit("failed", error.message, {
356
+ failure: "exit",
357
+ usage:
358
+ totalCost === null || baselineCost === null || totalCost < baselineCost
359
+ ? null
360
+ : {
361
+ cost_usd: totalCost - baselineCost,
362
+ input_tokens: null,
363
+ output_tokens: null,
364
+ cache_read_tokens: null,
365
+ cache_write_tokens: null,
366
+ },
367
+ });
368
+ } finally {
369
+ signal.removeEventListener("abort", cancel);
370
+ connection.close();
371
+ child.stdin.end();
372
+ child.kill("SIGTERM");
373
+ }
374
+ }
375
+
376
+ async function runMuse(
377
+ task,
378
+ runtime,
379
+ { emit, observe, signal, requestApproval }
380
+ ) {
381
+ if (Number(process.versions.node.split(".")[0]) < 20)
382
+ throw new Error("Muse Code's SDK requires Node 20 or newer.");
383
+ const { spawnMspConnection } = await import("@muse-code/sdk");
384
+ signal.throwIfAborted();
385
+ const handshake = spawnMspConnection({
386
+ command: runtime.command,
387
+ args: runtime.args,
388
+ cwd: task.cwd,
389
+ env: runtime.env,
390
+ onStderr: (text) => observe("stderr", text),
391
+ });
392
+ const cancel = () => {
393
+ void handshake.close().catch(() => {});
394
+ };
395
+ signal.addEventListener("abort", cancel, { once: true });
396
+ let client;
397
+ try {
398
+ const host = await handshake.initialize({
399
+ clientInfo: CLIENT_INFO,
400
+ capabilities: {
401
+ requestedCapabilities: ["sessionMcp"],
402
+ userInputDialogs: false,
403
+ },
404
+ });
405
+ signal.throwIfAborted();
406
+ emit("accepted");
407
+ client = await openMuseSession({
408
+ host,
409
+ observe,
410
+ task: { ...task, approvalMode: runtime.approvalMode },
411
+ signal,
412
+ onApproval: requestApproval
413
+ ? async (approval) => {
414
+ const chosen = await requestApproval(approval, signal);
415
+ signal.throwIfAborted();
416
+ return chosen;
417
+ }
418
+ : undefined,
419
+ onApprovalError: (failure) => {
420
+ if (
421
+ failure.kind === "handlerThrew" &&
422
+ ["native_replaced", "native_cancelled", "native_ended"].includes(
423
+ failure.error?.code
424
+ )
425
+ )
426
+ return;
427
+ if (
428
+ failure.kind === "submitFailed" &&
429
+ [-32051, -32053].includes(failure.error?.code)
430
+ ) {
431
+ progress(
432
+ emit,
433
+ observe,
434
+ "do",
435
+ "The native permission changed. Review its current request before answering."
436
+ );
437
+ return;
438
+ }
439
+ progress(
440
+ emit,
441
+ observe,
442
+ "do",
443
+ `Muse permission could not be confirmed (${failure.kind}).`
444
+ );
445
+ void handshake.close().catch(() => {});
446
+ },
447
+ });
448
+ const { session } = client;
449
+ let original = session.opening?.result?.session;
450
+ if (
451
+ typeof original?.workspaceRoot !== "string" ||
452
+ realpathSync(original.workspaceRoot) !== realpathSync(task.cwd)
453
+ )
454
+ throw new Error(
455
+ "Muse Code opened a different working folder; Harness did not submit the turn."
456
+ );
457
+ if (original.activeTurnId !== null)
458
+ throw new Error(
459
+ "Muse has not shown this session to be idle. Harness did not change its model or submit another turn."
460
+ );
461
+ if (task.sessionId && task.model && original.modelId !== task.model) {
462
+ const catalog = await host.connection.request("model/list", {
463
+ sessionId: session.sessionId,
464
+ });
465
+ if (!catalog.models?.some((model) => model.modelId === task.model))
466
+ throw new Error(
467
+ "Muse Code did not offer this model for the existing session. Harness did not submit the turn."
468
+ );
469
+ await host.connection.command("session/setModel", {
470
+ sessionId: session.sessionId,
471
+ model: { modelId: task.model, providerId: catalog.providerId },
472
+ });
473
+ const confirmed = await host.connection.command("session/read", {
474
+ sessionId: session.sessionId,
475
+ });
476
+ original = confirmed.session;
477
+ if (
478
+ original.sessionId !== session.sessionId ||
479
+ original.activeTurnId !== null ||
480
+ realpathSync(original.workspaceRoot) !== realpathSync(task.cwd)
481
+ )
482
+ throw new Error(
483
+ "The Muse session changed while applying this model. Harness did not submit the turn."
484
+ );
485
+ }
486
+ if (task.model && original.modelId !== task.model)
487
+ throw new Error(
488
+ "Muse Code did not apply the requested model; Harness did not submit the turn."
489
+ );
490
+ if (task.effort) {
491
+ const catalog = await host.connection.request("model/list", {
492
+ sessionId: session.sessionId,
493
+ });
494
+ const offered = catalog.models?.find(
495
+ (entry) => entry.modelId === original.modelId
496
+ );
497
+ if (
498
+ !Array.isArray(offered?.variants) ||
499
+ !offered.variants.includes(task.effort)
500
+ )
501
+ throw new Error(
502
+ "Muse Code did not offer this model's requested effort; Harness did not submit the turn."
503
+ );
504
+ }
505
+ emit("session", session.sessionId, {
506
+ cwd: task.cwd,
507
+ resumable: client.resumable,
508
+ });
509
+ const turn = await session.sendUserTurn({
510
+ input: [{ type: "text", text: task.brief }],
511
+ ...(task.effort ? { reasoningEffort: task.effort } : {}),
512
+ });
513
+ const messages = new Map();
514
+ for await (const item of turn.items()) {
515
+ observe(
516
+ "stdout",
517
+ JSON.stringify({ sessionId: session.sessionId, item }) + "\n"
518
+ );
519
+ if (item.kind === "agentMessage" && typeof item.text === "string") {
520
+ messages.set(item.itemId, item.text);
521
+ progress(emit, observe, "say", item.text);
522
+ }
523
+ if (item.kind === "toolCall")
524
+ progress(
525
+ emit,
526
+ observe,
527
+ "do",
528
+ item.displayLabel?.active || item.toolName || "Working in Muse Code"
529
+ );
530
+ }
531
+ const outcome = await turn.completed;
532
+ signal.throwIfAborted();
533
+ const succeeded =
534
+ outcome.kind === "completed" && outcome.params.terminal === "completed";
535
+ const usage = outcome.params?.usage;
536
+ const text = succeeded
537
+ ? [...messages.values()].join("\n") || "Muse Code completed its turn."
538
+ : outcome.params?.error?.message ||
539
+ `Muse Code turn ${outcome.params?.terminal || outcome.kind}.`;
540
+ emit(succeeded ? "done" : "failed", text, {
541
+ usage: usage
542
+ ? {
543
+ input_tokens: usage.inputTokens,
544
+ output_tokens: usage.outputTokens,
545
+ cache_read_tokens: usage.cacheReadTokens ?? null,
546
+ cache_write_tokens: usage.cacheWriteTokens ?? null,
547
+ cost_usd: null,
548
+ }
549
+ : null,
550
+ });
551
+ } finally {
552
+ signal.removeEventListener("abort", cancel);
553
+ if (client) await client.close();
554
+ else await handshake.close();
555
+ }
556
+ }
557
+
558
+ /** ACP and MSP adapters share the existing run lifecycle; native permissions remain the agent's. */
559
+ export async function runProtocolTask(task, hooks) {
560
+ if (task.readOnly || task.restricted)
561
+ throw new Error(
562
+ `${task.agent} cannot enforce Harness's restricted or read-only contract. Choose an agent that can.`
563
+ );
564
+ const selected = selectedRuntime(task.agent, task.env);
565
+ task = { ...task, sessionId: task.resumeSession ?? task.sessionId };
566
+ const runtime = selected;
567
+ return runtime.protocol === "msp"
568
+ ? runMuse(task, selected, hooks)
569
+ : runAcp(task, selected, hooks);
570
+ }