tryharness 0.7.54 → 0.7.57

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 (156) hide show
  1. package/README.md +15 -16
  2. package/cli.mjs +377 -62
  3. package/lib/activity.mjs +10 -10
  4. package/lib/adapters.mjs +16 -0
  5. package/lib/agentBinaries.mjs +71 -0
  6. package/lib/agentRuntimeConfig.mjs +1 -1
  7. package/lib/agentRuntimes.mjs +9 -3
  8. package/lib/agentSignIn.mjs +271 -41
  9. package/lib/answers.mjs +5 -5
  10. package/lib/archetypes.d.ts +64 -0
  11. package/lib/archetypes.js +989 -0
  12. package/lib/asks.mjs +4 -4
  13. package/lib/audit.mjs +36 -13
  14. package/lib/backupSetup.mjs +4 -2
  15. package/lib/boardAccess.mjs +17 -11
  16. package/lib/boardBackup.mjs +6 -6
  17. package/lib/boardFileCommands.mjs +6 -6
  18. package/lib/boardFiles.mjs +13 -12
  19. package/lib/boardMirror.mjs +82 -47
  20. package/lib/boardProtocol.json +30 -1
  21. package/lib/boardWaits.mjs +2 -3
  22. package/lib/book.mjs +6 -6
  23. package/lib/bridge.mjs +5 -5
  24. package/lib/cards.mjs +2 -2
  25. package/lib/cloudAgents.mjs +216 -0
  26. package/lib/cloudAi.mjs +1312 -0
  27. package/lib/cloudAssistants.mjs +242 -0
  28. package/lib/cloudBoot.mjs +81 -86
  29. package/lib/cloudSave.mjs +197 -0
  30. package/lib/cloudSsh.mjs +178 -0
  31. package/lib/context.mjs +3 -3
  32. package/lib/contractGate.mjs +34 -12
  33. package/lib/control-client.mjs +9 -1
  34. package/lib/controlSocket.mjs +86 -0
  35. package/lib/coordinator.mjs +103 -101
  36. package/lib/daemon.mjs +1128 -2865
  37. package/lib/desk.mjs +7 -6
  38. package/lib/desktop.mjs +72 -68
  39. package/lib/directLink.mjs +16 -5
  40. package/lib/environment.mjs +2 -1
  41. package/lib/environments.mjs +14 -6
  42. package/lib/firewall.mjs +9 -9
  43. package/lib/folders.mjs +18 -14
  44. package/lib/frames.mjs +2 -3
  45. package/lib/gitHost.mjs +3 -3
  46. package/lib/goalCommands.mjs +25 -7
  47. package/lib/goals.mjs +7 -7
  48. package/lib/guestRequests.mjs +94 -0
  49. package/lib/handoffs.mjs +8 -7
  50. package/lib/handover.mjs +4 -4
  51. package/lib/harnessModel.mjs +6 -6
  52. package/lib/harnessOffers.mjs +266 -0
  53. package/lib/inference.mjs +26 -8
  54. package/lib/jobAnswers.mjs +190 -0
  55. package/lib/landed.mjs +1 -1
  56. package/lib/lane.mjs +42 -11
  57. package/lib/lessons.mjs +16 -16
  58. package/lib/library.mjs +3 -3
  59. package/lib/lineup.mjs +3 -0
  60. package/lib/linkRelay.mjs +574 -0
  61. package/lib/localAgentAsk.mjs +74 -0
  62. package/lib/localStack.mjs +536 -0
  63. package/lib/localmodels.mjs +6 -4
  64. package/lib/loopBackstop.mjs +4 -4
  65. package/lib/machineIdentity.mjs +9 -1
  66. package/lib/machineRoutes.mjs +181 -2
  67. package/lib/machineRuns.mjs +76 -1
  68. package/lib/machineSeal.mjs +39 -12
  69. package/lib/mcp-stdio.mjs +96 -26
  70. package/lib/mcpRelay.mjs +1 -1
  71. package/lib/members.json +13 -0
  72. package/lib/members.mjs +1 -1
  73. package/lib/models.mjs +77 -23
  74. package/lib/museSession.mjs +6 -1
  75. package/lib/nativeHost.mjs +35 -7
  76. package/lib/network.mjs +50 -5
  77. package/lib/notify.mjs +7 -5
  78. package/lib/nudge.mjs +3 -3
  79. package/lib/ocr.mjs +9 -9
  80. package/lib/onboard.mjs +26 -20
  81. package/lib/oneLine.mjs +7 -7
  82. package/lib/ownMachines.mjs +928 -149
  83. package/lib/pairing.mjs +33 -6
  84. package/lib/paths.mjs +15 -1
  85. package/lib/peerProcess.mjs +124 -0
  86. package/lib/personModel.mjs +3 -3
  87. package/lib/personNotices.mjs +151 -0
  88. package/lib/phones.mjs +490 -38
  89. package/lib/placeCommands.mjs +4 -4
  90. package/lib/places.mjs +70 -2
  91. package/lib/profile.mjs +67 -14
  92. package/lib/projectGit.mjs +158 -14
  93. package/lib/projectPieces.mjs +902 -0
  94. package/lib/projectSettings.mjs +7 -4
  95. package/lib/projects.mjs +384 -62
  96. package/lib/provenance.mjs +5 -1
  97. package/lib/proxyLinks.mjs +267 -0
  98. package/lib/reactions.mjs +7 -5
  99. package/lib/readiness.mjs +12 -7
  100. package/lib/record.mjs +19 -6
  101. package/lib/redact.mjs +4 -4
  102. package/lib/relayLimits.mjs +62 -0
  103. package/lib/release.mjs +170 -0
  104. package/lib/releaseKeys.json +6 -0
  105. package/lib/repoLinks.mjs +4 -4
  106. package/lib/roomChannels.mjs +24 -0
  107. package/lib/roomPage.mjs +1 -1
  108. package/lib/runAuthority.mjs +101 -0
  109. package/lib/runBrief.mjs +19 -8
  110. package/lib/runWorker.mjs +14 -5
  111. package/lib/runner.mjs +215 -25
  112. package/lib/runtime-install.mjs +143 -9
  113. package/lib/schedules.mjs +2 -2
  114. package/lib/screens.mjs +1 -1
  115. package/lib/sealed.mjs +11 -2
  116. package/lib/sealedThreads.mjs +671 -0
  117. package/lib/secretPatterns.json +1 -1
  118. package/lib/secrets.mjs +4 -4
  119. package/lib/seen.mjs +6 -6
  120. package/lib/serverWords.mjs +175 -0
  121. package/lib/service.mjs +22 -12
  122. package/lib/sessionControl.mjs +6 -6
  123. package/lib/specialties.mjs +6 -6
  124. package/lib/specialtyKeys.js +4 -5
  125. package/lib/specialtyNotice.mjs +7 -7
  126. package/lib/specialtySnapshot.mjs +5 -5
  127. package/lib/speech.mjs +5 -5
  128. package/lib/store.mjs +140 -39
  129. package/lib/stuck.mjs +1 -1
  130. package/lib/swarm.mjs +167 -16
  131. package/lib/swarmDevices.mjs +319 -0
  132. package/lib/swarmMemory.mjs +27 -25
  133. package/lib/t3.mjs +13 -13
  134. package/lib/taskCommands.mjs +44 -11
  135. package/lib/taskRooms.mjs +125 -0
  136. package/lib/taskRuns.mjs +36 -1
  137. package/lib/team.mjs +41 -18
  138. package/lib/threadActions.mjs +315 -0
  139. package/lib/threadAuthority.mjs +101 -0
  140. package/lib/threadBriefs.mjs +178 -0
  141. package/lib/threadLine.mjs +2 -2
  142. package/lib/threadRuns.mjs +138 -43
  143. package/lib/threadView.mjs +5 -5
  144. package/lib/usageTotals.mjs +2 -3
  145. package/lib/vault.mjs +101 -10
  146. package/lib/vaultCloud.mjs +2 -2
  147. package/lib/vaultCommands.mjs +15 -6
  148. package/lib/vaultTools.js +2 -2
  149. package/lib/verdicts.mjs +328 -0
  150. package/lib/wakes.mjs +1 -1
  151. package/lib/watches.mjs +2 -2
  152. package/lib/windowAsks.mjs +13 -5
  153. package/lib/worktrees.mjs +112 -18
  154. package/npm-shrinkwrap.json +1093 -0
  155. package/package.json +11 -10
  156. package/release.json +220 -0
@@ -0,0 +1,1312 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ import { withEnvSettings } from "./cloudAssistants.mjs";
6
+ import { nameOf } from "./members.mjs";
7
+
8
+ // "Harness takes care of it" on a cloud computer: each agent the person put on Harness's AI is pointed at Harness's
9
+ // inference gateway (src/server/cloudAi/) in its own settings, and an agent put back on its plan or own key has
10
+ // Harness's settings taken out again, so its own sign-in applies. The computer asks Harness for its AI key with its
11
+ // connection token (POST /api/cloud/ai-key); the key spends inference for the computer's owner and nothing else,
12
+ // and stops working when the computer is removed.
13
+ //
14
+ // Which models an agent may run there is Harness's answer for this computer's owner (the gateway's model list, by
15
+ // what pays: the free model, Auto, or Auto and every model a Choice week or credits pay for). Each agent is given
16
+ // every one of them, each with its real context window and longest answer, so it compacts at the right point, and
17
+ // the person's choice for the agent (models.mjs, `choiceOf`) as its default; Auto ("harness") when there is none or
18
+ // the choice is no longer offered. A run names its model with the agent's own flag (runner.mjs), as on any computer.
19
+ // What each agent needs was read from its own CLI (October 25):
20
+ //
21
+ // - Claude Code: the env block of its user settings (base URL, the key as a bearer, its model and that model's
22
+ // window and answer), and hasCompletedOnboarding in ~/.claude.json, without which its first start checks
23
+ // Anthropic's servers.
24
+ // - Codex: a custom model provider on the Responses wire at the top of config.toml, written as dotted keys so the
25
+ // tables already in the file stay where they are, and a catalog entry for each model from its own bundled one.
26
+ // - OpenCode and Kilo: an OpenAI-compatible provider in their JSON settings with each model, the default model, Auto
27
+ // as the small model.
28
+ // - Pi: a provider in models.json with each model, the default in settings.json.
29
+ // - OpenClaw: its own onboard, with a custom endpoint whose key it reads from its .env, then each model and the
30
+ // default set with its own config command.
31
+ // - Hermes: its config.yaml custom endpoint (hermes config set), its key in its .env; it takes the default model's
32
+ // window, and has no setting for its longest answer (the gateway keeps a request within the model's).
33
+ //
34
+ // What Harness changed is recorded here, so taking it out puts back what was there before (the person's own key in
35
+ // Claude Code's settings, their default model in Pi or OpenCode).
36
+ //
37
+ // The same settings point an agent the person put on their own proxy link at this computer's local link address
38
+ // (linkRelay.mjs), with the link's model: the link's calls go sealed to the person's computer that holds it. Either
39
+ // way the provider is called "harness" in the agent's own settings, since that names what Harness wrote and takes
40
+ // out again; the name the person sees there says which it is. An agent on the person's own key keeps its own
41
+ // settings, with only its provider's address changed to the same local address (KEY_ROUTES below).
42
+ //
43
+ // This module is the one rule for where each agent's inference goes on this computer (the inference boundary): what
44
+ // the person chose for it (setup.ai: Harness's AI, their plan, their key or their proxy link) decides what is written
45
+ // at every sync, and before each run starts (taskRuns.mjs) the same answer is checked against what is in place.
46
+ // Owner, October 26: the person's own link or key falls back to Harness's providers. A call it does not answer goes
47
+ // to Harness's AI on Auto (linkRelay.mjs), an agent whose own link or key is not set up yet runs on Harness's AI
48
+ // until it is, and the run says so when it ends (noteFor). On the privacy setting nothing goes to Harness: the call
49
+ // or the run fails and says why. An agent on Harness's AI that is not set up does not start.
50
+
51
+ // The name agents use for Auto, where Harness picks the model for each request (src/server/cloudAi/models.ts).
52
+ const AUTO = "harness";
53
+ // What agents were told before Harness's model list could be read: Auto's window and answer as the gateway counts
54
+ // a model whose limits it cannot read (models.ts CLOUD_AI_CONTEXT_TOKENS, CLOUD_AI_MAX_OUTPUT_TOKENS).
55
+ const AUTO_ONLY = {
56
+ lane: null,
57
+ auto: {
58
+ id: AUTO,
59
+ name: "Auto",
60
+ image: true,
61
+ contextTokens: 128_000,
62
+ maxOutputTokens: 16_384,
63
+ },
64
+ models: [],
65
+ note: null,
66
+ };
67
+ // The agents that name a model by its provider first (harness/<model>), as their own lists show it.
68
+ const NAMED_BY_PROVIDER = new Set(["pi", "opencode", "kilo", "openclaw"]);
69
+
70
+ /** A model of Harness's as an agent names it: in its run flag, its list and the person's choice. */
71
+ export const agentModelId = (agent, id) =>
72
+ NAMED_BY_PROVIDER.has(agent) ? `harness/${id}` : id;
73
+
74
+ // A model in the list Pi and OpenClaw keep: its window, its answer and whether it sees images. Cost is Harness's
75
+ // to count, so theirs reads zero. A proxy link's model has no limits Harness knows: the agent's own defaults stand.
76
+ const listedModel = (model) => ({
77
+ id: model.id,
78
+ name: model.name,
79
+ reasoning: false,
80
+ input: model.image ? ["text", "image"] : ["text"],
81
+ ...(model.contextTokens ? { contextWindow: model.contextTokens } : {}),
82
+ ...(model.maxOutputTokens ? { maxTokens: model.maxOutputTokens } : {}),
83
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
84
+ });
85
+
86
+ const MARK_START =
87
+ "# >>> Harness AI (written by Harness; removed when this agent signs in another way)";
88
+ const MARK_END = "# <<< Harness AI";
89
+ const SAVED = "# harness-saved: ";
90
+
91
+ const readJson = (file) => {
92
+ try {
93
+ return JSON.parse(fs.readFileSync(file, "utf8"));
94
+ } catch (error) {
95
+ if (error.code === "ENOENT") return {};
96
+ throw new Error(`${file} is not JSON Harness can edit`);
97
+ }
98
+ };
99
+ const writeFile = (file, text) => {
100
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
101
+ fs.writeFileSync(file, text, { mode: 0o600 });
102
+ fs.chmodSync(file, 0o600);
103
+ };
104
+ const writeJson = (file, value) =>
105
+ writeFile(file, JSON.stringify(value, null, 2) + "\n");
106
+ const readText = (file) => {
107
+ try {
108
+ return fs.readFileSync(file, "utf8");
109
+ } catch {
110
+ return "";
111
+ }
112
+ };
113
+
114
+ /** Runs one command to its end; resolves its exit code and output, never rejects. */
115
+ function runCommand(command, args, { env }) {
116
+ return new Promise((resolve) => {
117
+ let output = "";
118
+ const child = spawn(command, args, {
119
+ env,
120
+ stdio: ["ignore", "pipe", "pipe"],
121
+ });
122
+ child.stdout.on("data", (chunk) => (output += chunk));
123
+ child.stderr.on("data", (chunk) => (output += chunk));
124
+ child.on("error", (error) => resolve({ code: -1, output: error.message }));
125
+ child.on("close", (code) => resolve({ code, output }));
126
+ });
127
+ }
128
+
129
+ // ---- Codex's config.toml: Harness's lines in one marked block at the top ----
130
+
131
+ /** The file without Harness's block, and with the top-level lines Harness set aside put back. */
132
+ export function withoutCodexBlock(text) {
133
+ const start = text.indexOf(MARK_START);
134
+ const end = text.indexOf(MARK_END);
135
+ const stripped =
136
+ start >= 0 && end > start
137
+ ? text.slice(0, start) + text.slice(end + MARK_END.length + 1)
138
+ : text;
139
+ return stripped
140
+ .split("\n")
141
+ .map((line) => (line.startsWith(SAVED) ? line.slice(SAVED.length) : line))
142
+ .join("\n");
143
+ }
144
+
145
+ /**
146
+ * The file with Harness's provider as the one Codex uses. Top-level keys must come before the first table, so the
147
+ * block goes first, and the person's own `model` and `model_provider` lines are set aside (commented, to come back).
148
+ */
149
+ export function withCodexBlock(text, ai, agentUrl, catalog = null) {
150
+ const lines = withoutCodexBlock(text).split("\n");
151
+ const firstTable = lines.findIndex((line) => /^\s*\[/.test(line));
152
+ const topEnd = firstTable < 0 ? lines.length : firstTable;
153
+ const kept = lines.map((line, index) =>
154
+ index < topEnd && /^\s*(model|model_provider)\s*=/.test(line)
155
+ ? SAVED + line
156
+ : line
157
+ );
158
+ const provider = [
159
+ `name = ${JSON.stringify(ai.label ?? "Harness")}`,
160
+ `base_url = ${JSON.stringify(`${agentUrl}/v1`)}`,
161
+ `wire_api = "responses"`,
162
+ `experimental_bearer_token = ${JSON.stringify(ai.key)}`,
163
+ `requires_openai_auth = false`,
164
+ ].join(", ");
165
+ const block = [
166
+ MARK_START,
167
+ `model_provider = "harness"`,
168
+ `model = ${JSON.stringify(ai.model)}`,
169
+ `model_providers.harness = { ${provider} }`,
170
+ ...(catalog ? [`model_catalog_json = ${JSON.stringify(catalog)}`] : []),
171
+ MARK_END,
172
+ ];
173
+ return [...block, ...kept].join("\n").replace(/\n*$/, "\n");
174
+ }
175
+
176
+ /**
177
+ * Codex plans each turn from its model catalog; for a model it does not know it warns that it may do worse and
178
+ * leaves out apply_patch, its own editing tool. The installed Codex's bundled entry for a model on the plain
179
+ * Responses wire (no code mode, no lite wire) is copied under each of Harness's models. Null when Codex has none.
180
+ */
181
+ export function codexCatalogEntry(listing, ai) {
182
+ let models;
183
+ try {
184
+ models = JSON.parse(
185
+ listing.slice(listing.indexOf("{"), listing.lastIndexOf("}") + 1)
186
+ ).models;
187
+ } catch {
188
+ return null;
189
+ }
190
+ const base = (Array.isArray(models) ? models : []).find(
191
+ (model) =>
192
+ !model.tool_mode &&
193
+ !model.use_responses_lite &&
194
+ model.visibility === "list" &&
195
+ model.apply_patch_tool_type
196
+ );
197
+ if (!base) return null;
198
+ return {
199
+ models: ai.models.map((model) => ({
200
+ ...base,
201
+ slug: model.id,
202
+ display_name: model.name,
203
+ description:
204
+ model.id === AUTO
205
+ ? "Harness picks the model for each request."
206
+ : `${model.name}, on ${ai.where ?? "Harness's AI"}.`,
207
+ upgrade: null,
208
+ prefer_websockets: false,
209
+ input_modalities: model.image ? ["text", "image"] : ["text"],
210
+ // A proxy link's model keeps the window of the entry it is copied from: Harness knows none of its own.
211
+ ...(model.contextTokens
212
+ ? {
213
+ context_window: model.contextTokens,
214
+ max_context_window: model.contextTokens,
215
+ }
216
+ : {}),
217
+ })),
218
+ };
219
+ }
220
+
221
+ // ---- each agent: point it at Harness, or take Harness out ----
222
+
223
+ function locations(home, env) {
224
+ const config = env.XDG_CONFIG_HOME || path.join(home, ".config");
225
+ const claudeDir = env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
226
+ return {
227
+ claudeSettings: path.join(claudeDir, "settings.json"),
228
+ claudeState: env.CLAUDE_CONFIG_DIR
229
+ ? path.join(claudeDir, ".claude.json")
230
+ : path.join(home, ".claude.json"),
231
+ codexConfig: path.join(
232
+ env.CODEX_HOME || path.join(home, ".codex"),
233
+ "config.toml"
234
+ ),
235
+ codexCatalog: path.join(
236
+ env.CODEX_HOME || path.join(home, ".codex"),
237
+ "harness-models.json"
238
+ ),
239
+ opencode: path.join(config, "opencode", "opencode.json"),
240
+ // Kilo is OpenCode's fork and reads the same settings under its own name (not installed here to check).
241
+ kilo: path.join(config, "kilo", "kilo.json"),
242
+ piDir: env.PI_CODING_AGENT_DIR || path.join(home, ".pi", "agent"),
243
+ openclawEnv: path.join(
244
+ env.OPENCLAW_STATE_DIR || path.join(home, ".openclaw"),
245
+ ".env"
246
+ ),
247
+ hermesEnv: path.join(env.HERMES_HOME || path.join(home, ".hermes"), ".env"),
248
+ };
249
+ }
250
+
251
+ // Claude Code's env keys Harness sets, and the person's own key, which would otherwise go to Harness alongside.
252
+ const CLAUDE_KEYS = [
253
+ "ANTHROPIC_BASE_URL",
254
+ "ANTHROPIC_AUTH_TOKEN",
255
+ "ANTHROPIC_API_KEY",
256
+ "ANTHROPIC_MODEL",
257
+ "ANTHROPIC_SMALL_FAST_MODEL",
258
+ "ANTHROPIC_DEFAULT_OPUS_MODEL",
259
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
260
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
261
+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS",
262
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
263
+ ];
264
+
265
+ const pick = (object, keys) =>
266
+ Object.fromEntries(
267
+ keys
268
+ .filter((key) => object?.[key] !== undefined)
269
+ .map((key) => [key, object[key]])
270
+ );
271
+
272
+ // Each agent's two moves. apply returns what it set aside, which remove gets back to restore.
273
+ const AGENTS = {
274
+ "claude-code": {
275
+ apply: async ({ ai, url, where }) => {
276
+ const settings = readJson(where.claudeSettings);
277
+ const env = settings.env ?? {};
278
+ const saved = pick(env, CLAUDE_KEYS);
279
+ for (const key of CLAUDE_KEYS) delete env[key];
280
+ const small = ai.small ?? AUTO;
281
+ settings.env = {
282
+ ...env,
283
+ ANTHROPIC_BASE_URL: url,
284
+ ANTHROPIC_AUTH_TOKEN: ai.key,
285
+ ANTHROPIC_MODEL: ai.model,
286
+ ANTHROPIC_SMALL_FAST_MODEL: small,
287
+ // --model opus, sonnet or haiku name these, so a run that asks for one still lands where the person chose:
288
+ // on Harness, on Auto; on a proxy link, on its model.
289
+ ANTHROPIC_DEFAULT_OPUS_MODEL: small,
290
+ ANTHROPIC_DEFAULT_SONNET_MODEL: small,
291
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: small,
292
+ // Claude Code knows none of these models' windows itself; a run on another model names its own (runner.mjs).
293
+ ...(ai.contextTokens
294
+ ? { CLAUDE_CODE_MAX_CONTEXT_TOKENS: String(ai.contextTokens) }
295
+ : {}),
296
+ ...(ai.maxOutputTokens
297
+ ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(ai.maxOutputTokens) }
298
+ : {}),
299
+ };
300
+ writeJson(where.claudeSettings, settings);
301
+ // Without it the first start asks Anthropic's servers whether it may begin, whatever the base URL.
302
+ const state = readJson(where.claudeState);
303
+ if (state.hasCompletedOnboarding !== true)
304
+ writeJson(where.claudeState, {
305
+ ...state,
306
+ hasCompletedOnboarding: true,
307
+ });
308
+ return saved;
309
+ },
310
+ remove: async ({ where, saved }) => {
311
+ const settings = readJson(where.claudeSettings);
312
+ const env = settings.env ?? {};
313
+ for (const key of CLAUDE_KEYS) delete env[key];
314
+ settings.env = { ...env, ...saved };
315
+ if (!Object.keys(settings.env).length) delete settings.env;
316
+ writeJson(where.claudeSettings, settings);
317
+ },
318
+ },
319
+ codex: {
320
+ apply: async ({ ai, agentUrl, where, run, env }) => {
321
+ const listing = await run("codex", ["debug", "models", "--bundled"], {
322
+ env,
323
+ });
324
+ const entry =
325
+ listing.code === 0 ? codexCatalogEntry(listing.output, ai) : null;
326
+ if (entry) writeJson(where.codexCatalog, entry);
327
+ else fs.rmSync(where.codexCatalog, { force: true });
328
+ writeFile(
329
+ where.codexConfig,
330
+ withCodexBlock(
331
+ readText(where.codexConfig),
332
+ ai,
333
+ agentUrl,
334
+ entry ? where.codexCatalog : null
335
+ )
336
+ );
337
+ return {};
338
+ },
339
+ remove: async ({ where }) => {
340
+ const text = readText(where.codexConfig);
341
+ if (text) writeFile(where.codexConfig, withoutCodexBlock(text));
342
+ fs.rmSync(where.codexCatalog, { force: true });
343
+ },
344
+ },
345
+ opencode: openCodeFamily("opencode"),
346
+ kilo: openCodeFamily("kilo"),
347
+ pi: {
348
+ apply: async ({ ai, agentUrl, where }) => {
349
+ const modelsFile = path.join(where.piDir, "models.json");
350
+ const settingsFile = path.join(where.piDir, "settings.json");
351
+ const models = readJson(modelsFile);
352
+ models.providers = {
353
+ ...models.providers,
354
+ harness: {
355
+ name: ai.label ?? "Harness",
356
+ baseUrl: `${agentUrl}/v1`,
357
+ api: "openai-completions",
358
+ apiKey: ai.key,
359
+ models: ai.models.map(listedModel),
360
+ },
361
+ };
362
+ writeJson(modelsFile, models);
363
+ const settings = readJson(settingsFile);
364
+ const saved = pick(settings, ["defaultProvider", "defaultModel"]);
365
+ writeJson(settingsFile, {
366
+ ...settings,
367
+ defaultProvider: "harness",
368
+ defaultModel: ai.model,
369
+ });
370
+ return saved.defaultProvider === "harness" ? {} : saved;
371
+ },
372
+ remove: async ({ where, saved }) => {
373
+ const modelsFile = path.join(where.piDir, "models.json");
374
+ const settingsFile = path.join(where.piDir, "settings.json");
375
+ const models = readJson(modelsFile);
376
+ if (models.providers?.harness) {
377
+ delete models.providers.harness;
378
+ writeJson(modelsFile, models);
379
+ }
380
+ const settings = readJson(settingsFile);
381
+ if (settings.defaultProvider === "harness") {
382
+ delete settings.defaultProvider;
383
+ delete settings.defaultModel;
384
+ writeJson(settingsFile, { ...settings, ...saved });
385
+ }
386
+ },
387
+ },
388
+ openclaw: {
389
+ apply: async ({ ai, agentUrl, where, run, env, options }) => {
390
+ // The key stays in OpenClaw's .env, which it reads itself: its config names it rather than holding it.
391
+ writeFile(
392
+ where.openclawEnv,
393
+ withEnvSettings(readText(where.openclawEnv), {
394
+ HARNESS_AI_KEY: ai.key,
395
+ })
396
+ );
397
+ const configured = await run(
398
+ "openclaw",
399
+ ["config", "get", "models.providers.harness.baseUrl"],
400
+ { env }
401
+ );
402
+ if (
403
+ configured.code !== 0 ||
404
+ !configured.output.includes(`${agentUrl}/v1`)
405
+ )
406
+ await onboardOpenClaw({ ai, agentUrl, run, env, options });
407
+ // Its models, each with its window and answer, all allowed, and the person's choice the one it runs.
408
+ const settings = [
409
+ ["models.providers.harness.models", ai.models.map(listedModel)],
410
+ [
411
+ "agents.defaults.models",
412
+ Object.fromEntries(
413
+ ai.models.map((model) => [`harness/${model.id}`, {}])
414
+ ),
415
+ ],
416
+ ];
417
+ for (const [key, value] of settings) {
418
+ const set = await run(
419
+ "openclaw",
420
+ ["config", "set", key, JSON.stringify(value), "--strict-json"],
421
+ { env }
422
+ );
423
+ if (set.code !== 0)
424
+ throw new Error(
425
+ `openclaw config set ${key} failed (exit ${set.code})`
426
+ );
427
+ }
428
+ const primary = await run(
429
+ "openclaw",
430
+ [
431
+ "config",
432
+ "set",
433
+ "agents.defaults.model.primary",
434
+ `harness/${ai.model}`,
435
+ ],
436
+ { env }
437
+ );
438
+ if (primary.code !== 0)
439
+ throw new Error(
440
+ `openclaw config set agents.defaults.model.primary failed (exit ${primary.code})`
441
+ );
442
+ return {};
443
+ },
444
+ remove: async ({ where, run, env }) => {
445
+ await removeOpenClaw({ run, env });
446
+ const text = readText(where.openclawEnv);
447
+ if (text)
448
+ writeFile(
449
+ where.openclawEnv,
450
+ withEnvSettings(text, {}, ["HARNESS_AI_KEY"])
451
+ );
452
+ },
453
+ },
454
+ hermes: {
455
+ apply: async ({ ai, agentUrl, where, run, env }) => {
456
+ writeFile(
457
+ where.hermesEnv,
458
+ withEnvSettings(readText(where.hermesEnv), { HARNESS_AI_KEY: ai.key })
459
+ );
460
+ const settings = [
461
+ ["model.provider", "custom"],
462
+ ["model.base_url", `${agentUrl}/v1`],
463
+ ["model.default", ai.model],
464
+ ["model.key_env", "HARNESS_AI_KEY"],
465
+ // Known, so Hermes does not probe the endpoint for it before every run; a proxy link's it probes.
466
+ ...(ai.contextTokens
467
+ ? [["model.context_length", String(ai.contextTokens)]]
468
+ : []),
469
+ ];
470
+ if (!ai.contextTokens)
471
+ await run("hermes", ["config", "unset", "model.context_length"], {
472
+ env,
473
+ });
474
+ for (const [key, value] of settings) {
475
+ const set = await run("hermes", ["config", "set", key, value], { env });
476
+ if (set.code !== 0)
477
+ throw new Error(`hermes config set ${key} failed (exit ${set.code})`);
478
+ }
479
+ return {};
480
+ },
481
+ remove: async ({ where, run, env }) => {
482
+ for (const key of [
483
+ "model.base_url",
484
+ "model.key_env",
485
+ "model.context_length",
486
+ "model.default",
487
+ ])
488
+ await run("hermes", ["config", "unset", key], { env });
489
+ // Back to choosing for itself; a plan's sign-in then names its own provider (agentSignIn.mjs).
490
+ await run("hermes", ["config", "set", "model.provider", "auto"], { env });
491
+ const text = readText(where.hermesEnv);
492
+ if (text)
493
+ writeFile(
494
+ where.hermesEnv,
495
+ withEnvSettings(text, {}, ["HARNESS_AI_KEY"])
496
+ );
497
+ },
498
+ },
499
+ };
500
+
501
+ // OpenClaw's own onboard, with Harness as a custom endpoint and Auto as its first model. A second onboard with a new
502
+ // address would add "harness-2", so the old one is taken out first.
503
+ async function onboardOpenClaw({ ai, agentUrl, run, env, options }) {
504
+ await removeOpenClaw({ run, env });
505
+ const onboard = await run(
506
+ "openclaw",
507
+ [
508
+ "onboard",
509
+ "--non-interactive",
510
+ "--accept-risk",
511
+ "--flow",
512
+ "quickstart",
513
+ options.installDaemon ? "--install-daemon" : "--no-install-daemon",
514
+ "--skip-ui",
515
+ "--skip-health",
516
+ "--auth-choice",
517
+ "custom-api-key",
518
+ "--custom-provider-id",
519
+ "harness",
520
+ "--custom-base-url",
521
+ `${agentUrl}/v1`,
522
+ "--custom-model-id",
523
+ ai.small ?? AUTO,
524
+ "--custom-compatibility",
525
+ "openai",
526
+ "--secret-input-mode",
527
+ "ref",
528
+ ],
529
+ { env: { ...env, CUSTOM_API_KEY: ai.key } }
530
+ );
531
+ if (onboard.code !== 0)
532
+ throw new Error(`openclaw onboard failed (exit ${onboard.code})`);
533
+ // Onboard names the key by the variable it was given; the .env above holds it as Harness's own.
534
+ const keyRef = await run(
535
+ "openclaw",
536
+ [
537
+ "config",
538
+ "set",
539
+ "models.providers.harness.apiKey",
540
+ JSON.stringify({
541
+ source: "env",
542
+ provider: "default",
543
+ id: "HARNESS_AI_KEY",
544
+ }),
545
+ "--strict-json",
546
+ ],
547
+ { env }
548
+ );
549
+ if (keyRef.code !== 0)
550
+ throw new Error(`openclaw config set failed (exit ${keyRef.code})`);
551
+ }
552
+
553
+ async function removeOpenClaw({ run, env }) {
554
+ const primary = await run(
555
+ "openclaw",
556
+ ["config", "get", "agents.defaults.model.primary"],
557
+ { env }
558
+ );
559
+ const allowed = await run(
560
+ "openclaw",
561
+ ["config", "get", "agents.defaults.models", "--json"],
562
+ { env }
563
+ );
564
+ await run("openclaw", ["config", "unset", "models.providers.harness"], {
565
+ env,
566
+ });
567
+ // Harness's models come off the allowed list; any of the person's own stay.
568
+ const listed = (() => {
569
+ try {
570
+ const text = allowed.output;
571
+ return JSON.parse(
572
+ text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1)
573
+ );
574
+ } catch {
575
+ return null;
576
+ }
577
+ })();
578
+ if (listed && Object.keys(listed).some((id) => id.startsWith("harness/"))) {
579
+ const kept = Object.fromEntries(
580
+ Object.entries(listed).filter(([id]) => !id.startsWith("harness/"))
581
+ );
582
+ await run(
583
+ "openclaw",
584
+ Object.keys(kept).length
585
+ ? [
586
+ "config",
587
+ "set",
588
+ "agents.defaults.models",
589
+ JSON.stringify(kept),
590
+ "--strict-json",
591
+ ]
592
+ : ["config", "unset", "agents.defaults.models"],
593
+ { env }
594
+ );
595
+ }
596
+ if (primary.output.includes("harness/"))
597
+ await run(
598
+ "openclaw",
599
+ ["config", "unset", "agents.defaults.model.primary"],
600
+ {
601
+ env,
602
+ }
603
+ );
604
+ }
605
+
606
+ function openCodeFamily(agent) {
607
+ const fileOf = (where) => where[agent];
608
+ return {
609
+ apply: async ({ ai, agentUrl, where }) => {
610
+ const file = fileOf(where);
611
+ const settings = readJson(file);
612
+ const saved = pick(settings, ["model", "small_model"]);
613
+ settings.provider = {
614
+ ...settings.provider,
615
+ harness: {
616
+ npm: "@ai-sdk/openai-compatible",
617
+ name: ai.label ?? "Harness",
618
+ options: { baseURL: `${agentUrl}/v1`, apiKey: ai.key },
619
+ models: Object.fromEntries(
620
+ ai.models.map((model) => [
621
+ model.id,
622
+ {
623
+ name: model.name,
624
+ tool_call: true,
625
+ attachment: model.image,
626
+ reasoning: false,
627
+ temperature: true,
628
+ ...(model.contextTokens && model.maxOutputTokens
629
+ ? {
630
+ limit: {
631
+ context: model.contextTokens,
632
+ output: model.maxOutputTokens,
633
+ },
634
+ }
635
+ : {}),
636
+ },
637
+ ])
638
+ ),
639
+ },
640
+ };
641
+ settings.model = `harness/${ai.model}`;
642
+ settings.small_model = `harness/${ai.small ?? AUTO}`;
643
+ writeJson(file, settings);
644
+ return String(saved.model ?? "").startsWith("harness/") ? {} : saved;
645
+ },
646
+ remove: async ({ where, saved }) => {
647
+ const file = fileOf(where);
648
+ const settings = readJson(file);
649
+ if (settings.provider?.harness) delete settings.provider.harness;
650
+ if (settings.provider && !Object.keys(settings.provider).length)
651
+ delete settings.provider;
652
+ for (const key of ["model", "small_model"])
653
+ if (String(settings[key] ?? "").startsWith("harness/"))
654
+ delete settings[key];
655
+ writeJson(file, { ...settings, ...saved });
656
+ },
657
+ };
658
+ }
659
+
660
+ /** The agents Harness can point at its own AI. */
661
+ export const HARNESS_AI_AGENTS = Object.keys(AGENTS);
662
+
663
+ // ---- an agent on the person's own key: only its provider's address is changed, to this computer's ----
664
+ // The agent keeps its own models and sends its own key (Harness gives the key to the agent as it was given), so a call
665
+ // reaches its provider through this computer's model address, which hands it on and, when the key does not answer,
666
+ // to Harness's AI instead (linkRelay.mjs). Each agent's way to change a provider's address, from its own docs:
667
+ // Claude Code's ANTHROPIC_BASE_URL; Codex's top-level openai_base_url; Pi's models.json provider baseUrl ("set only
668
+ // its baseUrl. Its models and authentication stay unchanged"); OpenCode's and Kilo's provider options.baseURL.
669
+
670
+ const OWN_ADDRESS = "http://127.0.0.1:";
671
+ const routedHere = (value) => String(value ?? "").startsWith(OWN_ADDRESS);
672
+
673
+ const KEY_ROUTES = {
674
+ "claude-code": {
675
+ apply: async ({ route, key, where }) => {
676
+ const settings = readJson(where.claudeSettings);
677
+ const env = settings.env ?? {};
678
+ const saved = pick(env, ["ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY"]);
679
+ settings.env = {
680
+ ...env,
681
+ ANTHROPIC_BASE_URL: `${route}/anthropic`,
682
+ ANTHROPIC_API_KEY: key.key,
683
+ };
684
+ writeJson(where.claudeSettings, settings);
685
+ return saved;
686
+ },
687
+ remove: async ({ where, saved }) => {
688
+ const settings = readJson(where.claudeSettings);
689
+ const env = settings.env ?? {};
690
+ if (routedHere(env.ANTHROPIC_BASE_URL)) {
691
+ delete env.ANTHROPIC_BASE_URL;
692
+ delete env.ANTHROPIC_API_KEY;
693
+ }
694
+ settings.env = { ...env, ...saved };
695
+ if (!Object.keys(settings.env).length) delete settings.env;
696
+ writeJson(where.claudeSettings, settings);
697
+ },
698
+ },
699
+ codex: {
700
+ apply: async ({ route, key, where }) => {
701
+ const lines = withoutCodexBlock(readText(where.codexConfig));
702
+ const block = [
703
+ MARK_START,
704
+ `openai_base_url = ${JSON.stringify(`${route}/${key.provider}/v1`)}`,
705
+ MARK_END,
706
+ ].join("\n");
707
+ writeFile(where.codexConfig, `${block}\n${lines}`.replace(/\n*$/, "\n"));
708
+ return {};
709
+ },
710
+ remove: async ({ where }) => {
711
+ const text = readText(where.codexConfig);
712
+ if (text) writeFile(where.codexConfig, withoutCodexBlock(text));
713
+ },
714
+ },
715
+ pi: {
716
+ apply: async ({ route, key, where }) => {
717
+ const file = path.join(where.piDir, "models.json");
718
+ const models = readJson(file);
719
+ models.providers = {
720
+ ...models.providers,
721
+ [key.provider]: {
722
+ ...models.providers?.[key.provider],
723
+ baseUrl: `${route}/${key.provider}/v1`,
724
+ },
725
+ };
726
+ writeJson(file, models);
727
+ return {};
728
+ },
729
+ remove: async ({ where }) => {
730
+ const file = path.join(where.piDir, "models.json");
731
+ const models = readJson(file);
732
+ for (const [name, provider] of Object.entries(models.providers ?? {})) {
733
+ if (!routedHere(provider?.baseUrl)) continue;
734
+ const { baseUrl: _routed, ...rest } = provider;
735
+ if (Object.keys(rest).length) models.providers[name] = rest;
736
+ else delete models.providers[name];
737
+ }
738
+ writeJson(file, models);
739
+ },
740
+ },
741
+ opencode: openCodeKeyRoute("opencode"),
742
+ kilo: openCodeKeyRoute("kilo"),
743
+ };
744
+
745
+ function openCodeKeyRoute(agent) {
746
+ return {
747
+ apply: async ({ route, key, where }) => {
748
+ const settings = readJson(where[agent]);
749
+ const own = settings.provider?.[key.provider] ?? {};
750
+ settings.provider = {
751
+ ...settings.provider,
752
+ [key.provider]: {
753
+ ...own,
754
+ options: { ...own.options, baseURL: `${route}/${key.provider}/v1` },
755
+ },
756
+ };
757
+ writeJson(where[agent], settings);
758
+ return {};
759
+ },
760
+ remove: async ({ where }) => {
761
+ const settings = readJson(where[agent]);
762
+ for (const [name, provider] of Object.entries(settings.provider ?? {})) {
763
+ if (!routedHere(provider?.options?.baseURL)) continue;
764
+ const { baseURL: _routed, ...options } = provider.options;
765
+ const rest = { ...provider, options };
766
+ if (!Object.keys(options).length) delete rest.options;
767
+ if (Object.keys(rest).length) settings.provider[name] = rest;
768
+ else delete settings.provider[name];
769
+ }
770
+ if (settings.provider && !Object.keys(settings.provider).length)
771
+ delete settings.provider;
772
+ writeJson(where[agent], settings);
773
+ },
774
+ };
775
+ }
776
+
777
+ /** The agents whose own key Harness routes through this computer's model address. */
778
+ export const KEY_ROUTE_AGENTS = Object.keys(KEY_ROUTES);
779
+
780
+ /** One model's words in a list: how much it holds, how long it answers, and whether it sees images. */
781
+ const tokenWords = (count) =>
782
+ count >= 1_000_000
783
+ ? `${Math.round(count / 100_000) / 10}M`
784
+ : `${Math.round(count / 1_000)}K`;
785
+ const aboutModel = (model) =>
786
+ [
787
+ model.id === AUTO && model.name === "Auto"
788
+ ? "Harness picks the model for each request"
789
+ : null,
790
+ `holds ${tokenWords(model.contextTokens)} tokens, answers up to ${tokenWords(model.maxOutputTokens)}`,
791
+ model.image ? "sees images" : null,
792
+ ]
793
+ .filter(Boolean)
794
+ .join(", ");
795
+
796
+ const usableOffer = (offer) =>
797
+ offer?.auto?.id === AUTO && Array.isArray(offer.models) ? offer : null;
798
+
799
+ export function createCloudAi({
800
+ config,
801
+ log = () => {},
802
+ fetchImpl = fetch,
803
+ run = runCommand,
804
+ env = process.env,
805
+ home = os.homedir(),
806
+ // OpenClaw's onboard installs its gateway as a service, as it does for a plan (agentSignIn.mjs).
807
+ installDaemon = true,
808
+ // The person's choice of model for an agent, as the agent names it (models.mjs), or null for Auto.
809
+ choiceOf = () => null,
810
+ // This computer's local model address for the person's own links and keys (linkRelay.mjs): start() gives
811
+ // { baseUrl, keyBaseUrl, token }, test() tries a link. Null where they are not offered.
812
+ linkRelay = null,
813
+ // The privacy setting: nothing goes to Harness, so an agent whose own link or key is not set up does not run.
814
+ privacy = () => false,
815
+ }) {
816
+ const stateFile = path.join(home, ".harness", "cloud-ai.json");
817
+ const where = locations(home, env);
818
+ const childEnv = { ...env, HOME: home };
819
+ const readState = () => {
820
+ try {
821
+ return {
822
+ links: {},
823
+ keys: {},
824
+ ...JSON.parse(fs.readFileSync(stateFile, "utf8")),
825
+ };
826
+ } catch {
827
+ return { ai: null, offer: null, applied: {}, links: {}, keys: {} };
828
+ }
829
+ };
830
+ let state = readState();
831
+ const save = () => writeJson(stateFile, state);
832
+ // The person's last answers, so a new model list or a new choice is applied again with them. Kept with the state,
833
+ // so a run started before the first sync after a restart is held to them too.
834
+ let last = state.answers
835
+ ? { answers: state.answers, agents: state.agents ?? [] }
836
+ : null;
837
+ // Why an agent's chosen inference could not be put in place at the last sync, said when a run of it is refused.
838
+ const notSetUp = {};
839
+ // Agents already pointed at the link address call it from the first moment, before any sync after a restart.
840
+ if (
841
+ linkRelay &&
842
+ Object.values(state.applied).some((applied) =>
843
+ ["link", "standin", "key"].includes(applied.kind)
844
+ )
845
+ )
846
+ void linkRelay
847
+ .start()
848
+ .catch((error) => log(`link address did not start: ${error.message}`));
849
+
850
+ const origin = String(config.origin).replace(/\/$/, "");
851
+ const askForKey = async () => {
852
+ const response = await fetchImpl(`${origin}/api/cloud/ai-key`, {
853
+ method: "POST",
854
+ headers: { authorization: `Bearer ${config.token}` },
855
+ });
856
+ if (!response.ok)
857
+ throw new Error(`Harness answered ${response.status} for the AI key`);
858
+ const answer = await response.json();
859
+ if (!answer.key || !answer.baseUrl)
860
+ throw new Error("Harness sent an incomplete AI key");
861
+ state.ai = answer;
862
+ save();
863
+ return answer;
864
+ };
865
+ // Harness's model list for this computer's owner, with the key: a key Harness no longer takes (the computer
866
+ // enrolled again) is replaced, and every agent gets the new one. A list that cannot be read keeps the last one.
867
+ const readOffer = async (ai) => {
868
+ const response = await fetchImpl(`${ai.baseUrl}/harness/v1/models`, {
869
+ headers: { authorization: `Bearer ${ai.key}` },
870
+ }).catch(() => null);
871
+ if (response?.status === 401) return { refused: true };
872
+ const body = response?.ok ? await response.json().catch(() => null) : null;
873
+ return { offer: usableOffer(body?.harness) };
874
+ };
875
+ const current = async () => {
876
+ let ai = state.ai;
877
+ let read = ai ? await readOffer(ai) : { refused: true };
878
+ if (read.refused) {
879
+ ai = await askForKey();
880
+ read = await readOffer(ai);
881
+ }
882
+ if (read.offer) {
883
+ state.offer = read.offer;
884
+ save();
885
+ }
886
+ return { ai, offer: usableOffer(state.offer) ?? AUTO_ONLY };
887
+ };
888
+
889
+ /** What one agent is told: every model, each with its limits, and the person's choice as its default. */
890
+ const settingFor = (agent, ai, offer) => {
891
+ const wanted = String(choiceOf(agent) ?? "").replace(/^harness\//, "");
892
+ const model = offer.models.find((each) => each.id === wanted) ?? offer.auto;
893
+ return {
894
+ kind: "harness",
895
+ key: ai.key,
896
+ baseUrl: ai.baseUrl,
897
+ label: "Harness",
898
+ where: "Harness's AI",
899
+ model: model.id,
900
+ small: AUTO,
901
+ contextTokens: model.contextTokens,
902
+ maxOutputTokens: model.maxOutputTokens,
903
+ models: [offer.auto, ...offer.models],
904
+ };
905
+ };
906
+ /** What one agent on a proxy link is told: this computer's link address, its token, and the link's one model. */
907
+ const linkSettingFor = (link, relay) => ({
908
+ kind: "link",
909
+ key: relay.token,
910
+ baseUrl: relay.baseUrl,
911
+ label: "Your proxy link",
912
+ where: "your proxy link",
913
+ model: link.model,
914
+ small: link.model,
915
+ contextTokens: null,
916
+ maxOutputTokens: null,
917
+ models: [
918
+ {
919
+ id: link.model,
920
+ name: link.model,
921
+ image: false,
922
+ contextTokens: null,
923
+ maxOutputTokens: null,
924
+ },
925
+ ],
926
+ });
927
+ const fingerprint = (setting) =>
928
+ JSON.stringify([
929
+ setting.kind,
930
+ setting.baseUrl,
931
+ setting.key,
932
+ setting.model,
933
+ setting.models.map((model) => [
934
+ model.id,
935
+ model.name,
936
+ model.image,
937
+ model.contextTokens,
938
+ model.maxOutputTokens,
939
+ ]),
940
+ ]);
941
+
942
+ const context = (agent, ai) => {
943
+ const url = `${ai.baseUrl}/${agent}`;
944
+ return {
945
+ ai,
946
+ url,
947
+ agentUrl: url,
948
+ where,
949
+ run,
950
+ env: childEnv,
951
+ options: { installDaemon },
952
+ };
953
+ };
954
+
955
+ /** An agent on its own key: only its provider's address is changed, to this computer's model address. */
956
+ const keySettingFor = (agent, ownKey, relay) => ({
957
+ kind: "key",
958
+ key: ownKey.key,
959
+ baseUrl: `${relay.keyBaseUrl}/${agent}`,
960
+ where: "your API key",
961
+ model: null,
962
+ models: [],
963
+ ownKey,
964
+ });
965
+ /**
966
+ * An agent whose own link or key is not set up here yet: pointed at this computer's link address, where each call
967
+ * goes to Harness's AI on Auto and says why (linkRelay.mjs), until the person's own is in place.
968
+ */
969
+ const standInSettingFor = (relay) => ({
970
+ ...linkSettingFor({ model: AUTO }, relay),
971
+ kind: "standin",
972
+ label: "Harness's AI, until yours is set up",
973
+ where: "Harness's AI until the person's own is set up",
974
+ });
975
+
976
+ // How the person said each agent gets its AI, and what Harness writes for it: Harness's gateway ("harness"), this
977
+ // computer's link address ("link", or "standin" while their link or key is not set up), their provider's address
978
+ // changed to this computer's ("key"), or nothing (their plan). The one rule apply and a run's start both read.
979
+ const kindOf = (agent) =>
980
+ state.applied[agent] ? (state.applied[agent].kind ?? "harness") : null;
981
+ // The writers of each kind: the agent's provider settings, or only its provider's address.
982
+ const writersOf = (kind) => (kind === "key" ? KEY_ROUTES : AGENTS);
983
+ const ownWords = (answer) =>
984
+ answer === "key" ? "your API key" : "your proxy link";
985
+
986
+ const takeOut = async (agent) => {
987
+ const applied = state.applied[agent];
988
+ await writersOf(applied.kind)[agent].remove({
989
+ ...context(agent, state.ai ?? { baseUrl: origin }),
990
+ saved: applied.saved ?? {},
991
+ });
992
+ delete state.applied[agent];
993
+ save();
994
+ };
995
+
996
+ // Writes one agent's settings when they differ from what is in place; the reason it could not, or null.
997
+ const put = async (agent, setting) => {
998
+ let applied = state.applied[agent];
999
+ const print = fingerprint(setting);
1000
+ if (applied?.fingerprint === print) return null;
1001
+ try {
1002
+ // Going between the two kinds of writer, the first is taken out whole, putting back what it set aside, so the
1003
+ // second sets aside the person's own settings again.
1004
+ if (applied && writersOf(kindOf(agent)) !== writersOf(setting.kind)) {
1005
+ await takeOut(agent);
1006
+ applied = null;
1007
+ }
1008
+ const saved =
1009
+ setting.kind === "key"
1010
+ ? await KEY_ROUTES[agent].apply({
1011
+ route: setting.baseUrl,
1012
+ key: setting.ownKey,
1013
+ where,
1014
+ })
1015
+ : await AGENTS[agent].apply(context(agent, setting));
1016
+ state.applied[agent] = {
1017
+ kind: setting.kind,
1018
+ key: setting.kind === "key" ? null : setting.key,
1019
+ fingerprint: print,
1020
+ // The person's own settings from before Harness's first change, kept through key and kind changes.
1021
+ saved: applied?.saved ?? saved,
1022
+ };
1023
+ save();
1024
+ log(
1025
+ `${agent}: on ${setting.where}${setting.model ? `, on ${setting.model}` : ""}`
1026
+ );
1027
+ return null;
1028
+ } catch (error) {
1029
+ log(`${agent}: not set up on ${setting.where}: ${error.message}`);
1030
+ return error.message;
1031
+ }
1032
+ };
1033
+
1034
+ /**
1035
+ * Make each agent's settings match the person's answers: `answers` is setup.ai, `agents` the chosen agents that
1036
+ * are installed here. An agent on "harness" is pointed at Harness with every model it may run and its default
1037
+ * (again, if the key, the list or the choice changed); one on "link" at this computer's link address with its
1038
+ * link's model, once a link is kept for it (useLink); one on "key" through this computer's model address, once its
1039
+ * key is kept (keepKey); one on "link" or "key" not set up yet at the link address, where its calls run on
1040
+ * Harness's AI and say why; any other agent Harness had pointed anywhere, chosen or not, has Harness's settings
1041
+ * taken out, so its own plan applies.
1042
+ */
1043
+ const apply = async ({ answers = {}, agents = [] }) => {
1044
+ last = { answers, agents };
1045
+ state.answers = answers;
1046
+ state.agents = agents;
1047
+ save();
1048
+ const chosen = (kind) =>
1049
+ agents.filter((agent) => answers[agent] === kind && AGENTS[agent]);
1050
+ const failed = {};
1051
+ const onHarness = chosen("harness");
1052
+ const onOwn = linkRelay ? [...chosen("link"), ...chosen("key")] : [];
1053
+ if (onOwn.length) {
1054
+ const relay = await linkRelay.start().catch((error) => {
1055
+ for (const agent of onOwn)
1056
+ failed[agent] =
1057
+ `this computer's model address did not start: ${error.message}`;
1058
+ return null;
1059
+ });
1060
+ for (const agent of relay ? onOwn : []) {
1061
+ const answer = answers[agent];
1062
+ const setting =
1063
+ answer === "link" && state.links[agent]
1064
+ ? linkSettingFor(state.links[agent], relay)
1065
+ : answer === "key" && state.keys[agent] && KEY_ROUTES[agent]
1066
+ ? keySettingFor(agent, state.keys[agent], relay)
1067
+ : standInSettingFor(relay);
1068
+ const why = await put(agent, setting);
1069
+ if (why) failed[agent] = why;
1070
+ }
1071
+ }
1072
+ if (onHarness.length) {
1073
+ let found = null;
1074
+ try {
1075
+ found = await current();
1076
+ } catch (error) {
1077
+ log(`Harness AI not set up: ${error.message}`);
1078
+ for (const agent of onHarness) failed[agent] = error.message;
1079
+ }
1080
+ for (const agent of found ? onHarness : []) {
1081
+ const why = await put(agent, settingFor(agent, found.ai, found.offer));
1082
+ if (why) failed[agent] = why;
1083
+ }
1084
+ }
1085
+ const kept = [...onHarness, ...onOwn];
1086
+ for (const agent of Object.keys(state.applied)) {
1087
+ if (kept.includes(agent)) continue;
1088
+ try {
1089
+ await takeOut(agent);
1090
+ log(`${agent}: Harness's settings taken out; its own sign-in applies`);
1091
+ } catch (error) {
1092
+ failed[agent] ??=
1093
+ `Harness's settings could not be taken out: ${error.message}`;
1094
+ log(`${agent}: Harness's settings not taken out: ${error.message}`);
1095
+ }
1096
+ }
1097
+ for (const agent of Object.keys(notSetUp)) delete notSetUp[agent];
1098
+ Object.assign(notSetUp, failed);
1099
+ return { failed };
1100
+ };
1101
+
1102
+ /** Reads Harness's model list again and applies it, and any changed choice, with the person's last answers. */
1103
+ const refresh = () => (last ? apply(last) : Promise.resolve({ failed: {} }));
1104
+
1105
+ /** Whether this agent runs on Harness's AI here now. */
1106
+ const onHarness = (agent) => kindOf(agent) === "harness";
1107
+
1108
+ /** Whether Harness's settings point this agent anywhere here now: Harness's AI, or the person's own link or key. */
1109
+ const written = (agent) => kindOf(agent) !== null;
1110
+
1111
+ /** The proxy link an agent runs on here, while the person's answer for it is the link. */
1112
+ const linkOf = (agent) =>
1113
+ last?.answers?.[agent] === "link" ? (state.links[agent] ?? null) : null;
1114
+
1115
+ /**
1116
+ * How an agent's calls at this computer's link address run (linkRelay.mjs): through its link, or, while the person's
1117
+ * own link or key is not set up here, on Harness's AI with the reason. Null for an agent on neither.
1118
+ */
1119
+ const routeOf = (agent) => {
1120
+ const answer = last?.answers?.[agent];
1121
+ if (answer !== "link" && answer !== "key") return null;
1122
+ const link = linkOf(agent);
1123
+ if (link) return { kind: "link", link };
1124
+ return {
1125
+ kind: "standin",
1126
+ reason:
1127
+ answer === "link"
1128
+ ? "your proxy link is not set up on this computer yet"
1129
+ : "no API key is set up for it on this computer yet",
1130
+ };
1131
+ };
1132
+
1133
+ /** The key the person gave this computer for an agent, while their answer for it is their key. */
1134
+ const keyOf = (agent) =>
1135
+ last?.answers?.[agent] === "key" ? (state.keys?.[agent] ?? null) : null;
1136
+
1137
+ /**
1138
+ * The person's own key for an agent, kept on this computer (agentSignIn.mjs gives it to the agent too): its calls
1139
+ * then go through this computer's model address to that provider, and to Harness's AI when the key does not answer.
1140
+ */
1141
+ const keepKey = async (agent, { provider, key }) => {
1142
+ state.keys = { ...state.keys, [agent]: { provider, key } };
1143
+ save();
1144
+ await refresh();
1145
+ };
1146
+
1147
+ /** Harness's AI for this computer, for a call the person's own link or key did not answer (linkRelay.mjs). */
1148
+ const harnessAi = async () => (await current()).ai;
1149
+
1150
+ /**
1151
+ * The words a run ends with when any of its agent's calls went to Harness's AI because the person's own link or key
1152
+ * did not answer (taskRuns.mjs), or null: once per run, without the link's address or the key.
1153
+ */
1154
+ const noteFor = (agent, since) => {
1155
+ const switched = linkRelay?.switchedSince(agent, since);
1156
+ if (!switched) return null;
1157
+ const yours = ownWords(switched.kind);
1158
+ return `${nameOf(agent)} ran on Harness's AI for this, charged to your pass or credits, because ${yours} did not answer: ${switched.reason}. Its next calls try ${yours} first.`;
1159
+ };
1160
+
1161
+ // Each agent's last link test: { state: "testing" | "kept" | "failed", model?, error? }. A model on the person's
1162
+ // computer may take longer to answer its first call (loading) than a call from their window may wait, so the test
1163
+ // runs here on its own and the window reads how it went (linkTestOf, with the agent's sign-in row).
1164
+ const linkTests = {};
1165
+
1166
+ const testLink = async (agent, candidate, model) => {
1167
+ const tested = await linkRelay
1168
+ .test(agent, candidate, model)
1169
+ .catch((error) => ({ ok: false, error: error.message }));
1170
+ if (!tested.ok) {
1171
+ linkTests[agent] = { state: "failed", error: tested.error };
1172
+ return;
1173
+ }
1174
+ state.links[agent] = { ...candidate, model: tested.model };
1175
+ save();
1176
+ log(
1177
+ `${agent}: proxy link through ${candidate.holderLabel ?? candidate.holder} kept, on ${tested.model}`
1178
+ );
1179
+ linkTests[agent] = { state: "kept", model: tested.model };
1180
+ await refresh();
1181
+ };
1182
+
1183
+ /**
1184
+ * A link the person set up for an agent (the computer holding it, the link's id there, and its model), tested with
1185
+ * one real call through it and kept only if that answered; then applied, when the person's answer for the agent is
1186
+ * the link. Answers at once: the test's outcome is read with linkTestOf.
1187
+ */
1188
+ const useLink = (agent, { holder, holderLabel = null, link, model }) => {
1189
+ if (!AGENTS[agent])
1190
+ return { ok: false, error: `${agent} cannot run on a proxy link.` };
1191
+ if (!linkRelay)
1192
+ return { ok: false, error: "This computer does not take proxy links." };
1193
+ if (!holder || !link)
1194
+ return { ok: false, error: "Name the computer and the link to use." };
1195
+ if (linkTests[agent]?.state !== "testing") {
1196
+ linkTests[agent] = { state: "testing" };
1197
+ void testLink(
1198
+ agent,
1199
+ {
1200
+ holder: String(holder),
1201
+ holderLabel: holderLabel ? String(holderLabel).slice(0, 80) : null,
1202
+ link: String(link),
1203
+ },
1204
+ model ? String(model) : null
1205
+ );
1206
+ }
1207
+ return { ok: true, testing: true };
1208
+ };
1209
+
1210
+ /** How the last link test for an agent went, or null when none ran since this computer started. */
1211
+ const linkTestOf = (agent) => linkTests[agent] ?? null;
1212
+
1213
+ /**
1214
+ * The inference boundary at a run's start: null when the agent may run (on what the person chose, or, for their own
1215
+ * link or key not set up here yet, on Harness's AI until it is, said when the run ends), else why it does not start.
1216
+ * On the privacy setting an agent whose own link or key is not set up does not run on Harness's AI. An agent the
1217
+ * person said nothing about on this computer is not Harness's to hold.
1218
+ */
1219
+ const refusal = (agent) => {
1220
+ const answer = last?.answers?.[agent];
1221
+ if (answer == null) return null;
1222
+ const kind = kindOf(agent);
1223
+ const name = nameOf(agent);
1224
+ const why = notSetUp[agent] ? ` (${notSetUp[agent]})` : "";
1225
+ if (answer === "harness")
1226
+ return kind === "harness"
1227
+ ? null
1228
+ : `${name} is set to run on Harness's AI on this computer, and that is not set up yet${why}. It did not start on anything else.`;
1229
+ if (answer === "link" || answer === "key") {
1230
+ const yours = ownWords(answer);
1231
+ if (!kind)
1232
+ return `${name} is set to run on ${yours} on this computer, and this computer could not point it there${why}. It did not start.`;
1233
+ if (kind === "standin" && privacy())
1234
+ return `${name} is set to run on ${yours} on this computer, which is not set up here yet, and your privacy setting keeps it from running on Harness's AI instead. It did not start.`;
1235
+ return null;
1236
+ }
1237
+ return kind
1238
+ ? `${name} still has Harness's settings on this computer although you chose your own plan for it${why}. It did not start, so it does not run on what you did not choose.`
1239
+ : null;
1240
+ };
1241
+
1242
+ /**
1243
+ * An agent's models as its model list keeps them (models.mjs), each named as the agent names it. On Harness's AI:
1244
+ * Auto first, with the lane they run on and the words for a pick that runs on Auto or the free model. On a proxy
1245
+ * link: the link's model; while the person's own is not set up, Auto alone. Null for an agent on its own key (its
1246
+ * own list) or one Harness's settings do not point anywhere.
1247
+ */
1248
+ const catalogOf = (agent) => {
1249
+ if (kindOf(agent) === "standin")
1250
+ return {
1251
+ standin: true,
1252
+ models: [
1253
+ {
1254
+ id: agentModelId(agent, AUTO),
1255
+ name: "Auto",
1256
+ about: "on Harness's AI until your own link or key is set up here",
1257
+ efforts: [],
1258
+ auto: true,
1259
+ },
1260
+ ],
1261
+ };
1262
+ if (kindOf(agent) === "link") {
1263
+ const link = state.links[agent];
1264
+ return link
1265
+ ? {
1266
+ link: { holder: link.holderLabel ?? link.holder },
1267
+ models: [
1268
+ {
1269
+ id: agentModelId(agent, link.model),
1270
+ name: link.model,
1271
+ about: `on your proxy link through ${link.holderLabel ?? "your computer"}`,
1272
+ efforts: [],
1273
+ },
1274
+ ],
1275
+ }
1276
+ : null;
1277
+ }
1278
+ if (!onHarness(agent)) return null;
1279
+ const offer = usableOffer(state.offer) ?? AUTO_ONLY;
1280
+ return {
1281
+ harness: { lane: offer.lane, note: offer.note },
1282
+ models: [offer.auto, ...offer.models].map((model) => ({
1283
+ id: agentModelId(agent, model.id),
1284
+ name: model.name,
1285
+ about: aboutModel(model),
1286
+ efforts: [],
1287
+ context: model.contextTokens,
1288
+ maxOutput: model.maxOutputTokens,
1289
+ image: model.image,
1290
+ ...(model.id === AUTO ? { auto: true } : {}),
1291
+ })),
1292
+ };
1293
+ };
1294
+
1295
+ return {
1296
+ apply,
1297
+ refresh,
1298
+ onHarness,
1299
+ written,
1300
+ kindOf,
1301
+ linkOf,
1302
+ routeOf,
1303
+ keyOf,
1304
+ keepKey,
1305
+ harnessAi,
1306
+ noteFor,
1307
+ useLink,
1308
+ linkTestOf,
1309
+ refusal,
1310
+ catalogOf,
1311
+ };
1312
+ }