pi-cowboy 0.5.0 → 0.9.0

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 (71) hide show
  1. package/README.md +26 -18
  2. package/agents/explore.toml +1 -1
  3. package/dist/agents/agent-assets.js +3 -0
  4. package/dist/agents/agent-cleanup.js +20 -0
  5. package/dist/agents/agent-discovery.js +34 -28
  6. package/dist/agents/agent-manager.js +65 -127
  7. package/dist/agents/agent-runner.js +111 -69
  8. package/dist/agents/agent-template.js +107 -5
  9. package/dist/agents/agent-types.js +0 -1
  10. package/dist/agents/harness/claude/index.js +219 -0
  11. package/dist/agents/harness/claude/staging.js +102 -0
  12. package/dist/agents/harness/codex.js +249 -0
  13. package/dist/agents/harness/opencode/definition.js +65 -0
  14. package/dist/agents/harness/opencode/index.js +218 -0
  15. package/dist/agents/harness/opencode/npm-seed.js +74 -0
  16. package/dist/agents/harness/opencode/permissions.js +48 -0
  17. package/dist/agents/harness/opencode/staging.js +63 -0
  18. package/dist/agents/harness/pane-launcher.js +96 -0
  19. package/dist/agents/harness/pi-bolt.js +3 -3
  20. package/dist/agents/harness/pi-compatible.js +80 -37
  21. package/dist/agents/harness/pig.js +3 -3
  22. package/dist/agents/harness/registry.js +53 -4
  23. package/dist/agents/harness-family.js +23 -0
  24. package/dist/agents/harness.js +86 -8
  25. package/dist/agents/schemas/cowboy-agents.schema.js +16 -5
  26. package/dist/agents/spawn-defaults.js +48 -6
  27. package/dist/agents/subagent-session.js +45 -8
  28. package/dist/agents/tool-execution.js +9 -2
  29. package/dist/availability.js +7 -0
  30. package/dist/concurrency-pools.js +270 -0
  31. package/dist/config/concurrency-limit.js +14 -0
  32. package/dist/config/config-io.js +22 -5
  33. package/dist/config/config-store.js +128 -9
  34. package/dist/config/config-validation.js +87 -7
  35. package/dist/config/types.js +2 -0
  36. package/dist/events.js +2 -1
  37. package/dist/harness-availability-launch.js +19 -4
  38. package/dist/index.js +4 -1
  39. package/dist/infrastructure/git/cow-clone.js +9 -1
  40. package/dist/infrastructure/herdr/agents.js +9 -8
  41. package/dist/infrastructure/herdr-host.js +3 -2
  42. package/dist/models/foreign-model-resolver.js +55 -0
  43. package/dist/models/model-groups.js +3 -1
  44. package/dist/models/model-precedence.js +35 -8
  45. package/dist/models/model-request-types.js +46 -0
  46. package/dist/models/model-request.js +32 -101
  47. package/dist/models/pi-model-resolver.js +88 -0
  48. package/dist/orchestrators/default-orchestrators.js +1 -1
  49. package/dist/orchestrators/protocol.js +29 -10
  50. package/dist/prompt/subagent-system-prompt.js +10 -3
  51. package/dist/registration.js +16 -18
  52. package/dist/spawn/sandbox.js +3 -0
  53. package/dist/subagent/deliverable.js +4 -3
  54. package/dist/subagent/supervisor.js +5 -3
  55. package/dist/task-registry.js +12 -158
  56. package/dist/types.js +1 -1
  57. package/dist/ui/format.js +7 -0
  58. package/dist/ui/menu/helpers.js +23 -9
  59. package/dist/ui/menu/menu-agent-settings.js +1 -1
  60. package/dist/ui/menu/menu-agent-status.js +8 -82
  61. package/dist/ui/menu/menu-concurrency.js +282 -101
  62. package/dist/ui/menu/menu-model-settings.js +114 -30
  63. package/dist/ui/menu/menu-spawn-defaults.js +4 -2
  64. package/dist/ui/menu/menu-spawn-wizard.js +11 -7
  65. package/dist/ui/menu/menus.js +10 -10
  66. package/dist/ui/menu/model-picker.js +37 -21
  67. package/dist/ui/menu/submenus/model-select.js +4 -7
  68. package/dist/ui/menu/submenus/numeric-input.js +2 -2
  69. package/dist/utils.js +10 -0
  70. package/package.json +5 -2
  71. package/orchestrators/with-code-review.toml +0 -20
@@ -1,23 +1,32 @@
1
1
  /**
2
2
  * agent-runner.ts — Launch-plan building for herdr-pane subagents.
3
3
  *
4
- * Produces a `SubagentLaunchPlan`: tool/extension flags, staged prompt
5
- * files, and argv for a real `pi` process (prompt text compiled by
6
- * `../prompt/subagent-system-prompt.js`). The child process owns extension
4
+ * Produces a `SubagentLaunchPlan`: staged prompt files and the launch
5
+ * context, with the argv owned by the resolved harness (prompt text compiled
6
+ * by `../prompt/subagent-system-prompt.js`). The child process owns extension
7
7
  * discovery and tool validation.
8
8
  */
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { SettingsManager, } from "@earendil-works/pi-coding-agent";
12
12
  import { errorMessage } from "../utils.js";
13
- import { agentDir, subagentResultDirFor, subagentResultFileFor, subagentSystemFileFor, subagentTaskFileFor, subagentTokenFor, } from "../paths.js";
13
+ import { agentDir, subagentResultDirFor, subagentResultFileFor, subagentSystemFileFor, subagentTaskFileFor, } from "../paths.js";
14
14
  import { getStore } from "../shell.js";
15
15
  import { buildSubagentSystemPrompt, buildWorktreeBranchSection, } from "../prompt/subagent-system-prompt.js";
16
+ import { harnessFor } from "./harness/registry.js";
17
+ import { harnessFamilyOf } from "./harness-family.js";
16
18
  import { getAgentConfig, getConfig, } from "./agent-types.js";
17
19
  import { ensureResultDir, writeResultFile } from "./result-file-permissions.js";
18
- import { resolveHarnessType } from "./spawn-defaults.js";
19
20
  // Re-exported for consumers importing it from this module.
20
21
  export { buildWorktreeBranchSection };
22
+ // ── Launch plan ─────────────────────────────────────────────────────
23
+ /**
24
+ * Resolve the skill mode: `default` leaves pi's own discovery alone, so an
25
+ * implicit `skills: true` reaches the agent through pi's skill section.
26
+ * `none` suppresses that discovery because the extension decides the agent's
27
+ * skills itself — an explicit list is rendered into the prompt here, and
28
+ * `skills: false` withholds skills entirely.
29
+ */
21
30
  function resolveSkillMode(skills, agentConfig) {
22
31
  // An empty inlined list inlines nothing, so it must not suppress pi's own
23
32
  // skills. The length test, not an isArray test, is what keeps that true.
@@ -116,8 +125,9 @@ function resolveParentSessionFile(ctx) {
116
125
  function resolveToolCliEntries(entries, optionName) {
117
126
  const resolved = new Set();
118
127
  for (const entry of entries) {
119
- // pi takes bare tool names. An extension's tools are named by the extension
120
- // itself, so there is nothing to qualify here and nothing to strip.
128
+ // Each family writes bare tool names in its own vocabulary. An
129
+ // extension's tools are named by the extension itself, so there is
130
+ // nothing to qualify here and nothing to strip.
121
131
  if (!entry) {
122
132
  throw new Error(`Empty entry in ${optionName} is not supported`);
123
133
  }
@@ -125,13 +135,58 @@ function resolveToolCliEntries(entries, optionName) {
125
135
  }
126
136
  return [...resolved];
127
137
  }
138
+ /**
139
+ * The launch request for one harness, by family. The switch is exhaustive over
140
+ * `HarnessId`, so a kind added to `HARNESS_IDS` without a branch here fails to
141
+ * compile instead of being handed another family's request.
142
+ */
143
+ function buildLaunchRequest(harnessType, sharedInputs, piInputs, opencodeInputs, codexInputs) {
144
+ switch (harnessType) {
145
+ case "pi":
146
+ case "pig":
147
+ case "pi-bolt":
148
+ return { ...sharedInputs, family: "pi", ...piInputs };
149
+ case "opencode":
150
+ return { ...sharedInputs, family: "opencode", ...opencodeInputs };
151
+ case "codex":
152
+ return { ...sharedInputs, family: "codex", ...codexInputs };
153
+ case "claude":
154
+ return { ...sharedInputs, family: "claude" };
155
+ default: {
156
+ const unhandled = harnessType;
157
+ throw new Error(`unhandled harness: ${String(unhandled)}`);
158
+ }
159
+ }
160
+ }
161
+ /**
162
+ * The harness's argv, from the request this launch carries. The request's own
163
+ * family tag selects the harness, so one family's argv cannot be built from
164
+ * another family's inputs; the switch is exhaustive over the tag, so a family
165
+ * added to `HarnessLaunchRequest` without a branch fails to compile.
166
+ */
167
+ function buildHarnessArgs(request) {
168
+ switch (request.family) {
169
+ case "pi":
170
+ return harnessFor("pi").buildArgs(request);
171
+ case "opencode":
172
+ return harnessFor("opencode").buildArgs(request);
173
+ case "codex":
174
+ return harnessFor("codex").buildArgs(request);
175
+ case "claude":
176
+ return harnessFor("claude").buildArgs(request);
177
+ default: {
178
+ const unhandled = request;
179
+ throw new Error(`unhandled harness family: ${String(unhandled)}`);
180
+ }
181
+ }
182
+ }
128
183
  /** The child pi owns extension discovery and tool validation; this only forwards configuration. */
129
184
  export async function buildLaunchPlan(pi, ctx, type, prompt, options) {
130
185
  const store = getStore();
131
186
  const effectiveCwd = options.cwd ?? ctx.cwd;
132
187
  const config = getConfig(type, store.agent.loadSkillsImplicitly, store.agent.loadExtensionsImplicitly);
133
188
  const agentConfig = getAgentConfig(type);
134
- const harnessType = resolveHarnessType(type);
189
+ const harnessType = options.harness;
135
190
  const skillMode = resolveSkillMode(config.skills, agentConfig);
136
191
  const warnings = [];
137
192
  const bufferNotify = (msg) => {
@@ -162,21 +217,26 @@ export async function buildLaunchPlan(pi, ctx, type, prompt, options) {
162
217
  }
163
218
  }
164
219
  }
165
- let toolMode;
220
+ let toolSelection = { kind: "default" };
166
221
  try {
167
- if (agentConfig?.tools === false) {
168
- toolMode = { kind: "none" };
222
+ // Exactly one harness launches a spawn, so exactly one family's slice
223
+ // decides: its names are already in that family's vocabulary. A family the
224
+ // template does not name launches unfiltered — never with another
225
+ // family's list, and never translated.
226
+ const filter = agentConfig?.toolsByFamily?.[harnessFamilyOf(harnessType)];
227
+ if (filter?.tools === false) {
228
+ toolSelection = { kind: "none" };
169
229
  }
170
- else if (Array.isArray(agentConfig?.tools)) {
171
- toolMode = {
230
+ else if (Array.isArray(filter?.tools)) {
231
+ toolSelection = {
172
232
  kind: "include",
173
- names: resolveToolCliEntries(agentConfig.tools, "tools"),
233
+ names: resolveToolCliEntries(filter.tools, "tools"),
174
234
  };
175
235
  }
176
- else if (agentConfig?.excludeTools?.length) {
177
- toolMode = {
236
+ else if (filter?.excludeTools?.length) {
237
+ toolSelection = {
178
238
  kind: "exclude",
179
- names: resolveToolCliEntries(agentConfig.excludeTools, "excludeTools"),
239
+ names: resolveToolCliEntries(filter.excludeTools, "excludeTools"),
180
240
  };
181
241
  }
182
242
  }
@@ -222,67 +282,49 @@ export async function buildLaunchPlan(pi, ctx, type, prompt, options) {
222
282
  }
223
283
  // Throws on failure: a launch without its task file must not proceed.
224
284
  writeResultFile(taskFile, prompt);
225
- // --system-prompt names the prompt FILE, so the subagent token rides via
226
- // --append-system-prompt (a path cannot carry the marker).
227
- const piArgs = [
228
- "--system-prompt",
229
- systemFile,
230
- "--append-system-prompt",
231
- subagentTokenFor(agentId),
232
- "--name",
233
- agentId,
234
- "--no-context-files",
235
- ];
236
- if (options.modelSelection) {
237
- piArgs.push("--model", options.modelSelection.key);
238
- }
239
- if (options.thinkingLevel) {
240
- piArgs.push("--thinking", options.thinkingLevel);
241
- }
242
- if (options.fork) {
243
- const forkSessionFile = resolveParentSessionFile(ctx);
244
- if (forkSessionFile) {
245
- piArgs.push("--fork", forkSessionFile);
246
- }
247
- else {
248
- bufferNotify("Fork session is enabled, but no parent session file is available; launching without --fork");
249
- }
250
- }
251
- if (toolMode?.kind === "none") {
252
- piArgs.push("--no-tools");
253
- }
254
- else if (toolMode?.kind === "include") {
255
- piArgs.push("--tools", toolMode.names.join(","));
256
- }
257
- else if (toolMode?.kind === "exclude") {
258
- piArgs.push("--exclude-tools", toolMode.names.join(","));
259
- }
260
- if (skillMode.kind === "none") {
261
- piArgs.push("--no-skills");
262
- }
263
- if (extMode.kind === "none") {
264
- piArgs.push("--no-extensions");
265
- }
266
- else if (extMode.kind === "paths") {
267
- piArgs.push("--no-extensions");
268
- for (const extPath of extMode.paths) {
269
- piArgs.push("-e", extPath);
270
- }
285
+ const forkSessionFile = options.fork
286
+ ? resolveParentSessionFile(ctx)
287
+ : undefined;
288
+ if (options.fork && forkSessionFile === undefined) {
289
+ bufferNotify("Fork session is enabled, but no parent session file is available; launching without --fork");
271
290
  }
272
- piArgs.push(options.projectTrusted === false ? "--no-approve" : "--approve");
291
+ // The harness owns the argv — including how the task rides — because the
292
+ // CLI surface is the harness's, not the orchestrator's. One request is built
293
+ // here, keyed by family, and the argv is built from that same object: pi's
294
+ // flags only ever reach a pi-family harness, opencode's variant only
295
+ // reaches opencode's, and codex's trust only reaches codex.
296
+ const sharedInputs = {
297
+ subagentId: agentId,
298
+ systemPromptFile: systemFile,
299
+ taskFile,
300
+ resultFile,
301
+ modelKey: options.modelSelection?.key ?? null,
302
+ toolSelection,
303
+ };
304
+ const piInputs = {
305
+ thinkingLevel: options.thinkingLevel ?? null,
306
+ forkSessionFile: forkSessionFile ?? null,
307
+ skills: skillMode,
308
+ extensions: extMode,
309
+ projectTrusted: options.projectTrusted !== false,
310
+ };
311
+ const opencodeInputs = {
312
+ variant: agentConfig?.variant ?? null,
313
+ };
314
+ const codexInputs = {
315
+ projectTrusted: options.projectTrusted !== false,
316
+ };
317
+ const launch = buildLaunchRequest(harnessType, sharedInputs, piInputs, opencodeInputs, codexInputs);
318
+ const piArgs = buildHarnessArgs(launch);
273
319
  for (const msg of warnings) {
274
320
  ctx.ui.notify(`[cowboy] ${msg}`, "warning");
275
321
  }
276
- const modelKey = options.modelSelection?.key;
277
322
  return {
278
323
  name: agentId,
279
324
  cwd: effectiveCwd,
280
325
  systemPrompt,
281
- systemPromptFile: systemFile,
282
- initialMessage: `@${taskFile}`,
283
326
  piArgs,
284
- resultFile,
285
- modelKey,
327
+ launch,
286
328
  harness: harnessType,
287
329
  };
288
330
  }
@@ -8,25 +8,127 @@
8
8
  import { z } from "zod";
9
9
  import { VALID_THINKING_LEVELS } from "../utils.js";
10
10
  import { VALID_WORKTREE_CHECKOUT_TYPES } from "../spawn/worktree-policy.js";
11
+ import { compactDefined } from "../templates/template-files.js";
11
12
  import { HARNESS_IDS } from "./harness.js";
12
13
  const filterList = z.union([z.boolean(), z.array(z.string())]);
13
14
  /**
14
- * The `[harness]` table: These describe the child process,
15
- * not the agent's identity or its worktree.
15
+ * The pi family's own `[harness]` keys, shared by their `[harness.pi]` table
16
+ * and their flat alias at the top level. The family-neutral key
17
+ * (`include_context_files`) stays at the top level; a second family adds its
18
+ * own strict table beside `pi` rather than widening this one.
19
+ *
20
+ * `model` belongs here with the pi family's keys, not with the neutral ones: a
21
+ * model key names an entry in one harness's catalogue, so a neutral slot could
22
+ * only ever be right for one family and wrong for the rest. The flat spelling
23
+ * stays loadable as the pi family's own, and the transform files it under
24
+ * `pi` like any other pi key. The same holds for `tools` / `exclude_tools`: a
25
+ * name list is catalogue-scoped, so the flat spelling is pi's, opencode
26
+ * reads only its own table's pair, and codex — which has no tools flag —
27
+ * reads only its own table's model; claude reads only its own pair.
16
28
  */
17
- const HarnessSchema = z.strictObject({
29
+ const PI_HARNESS_SHAPE = {
30
+ /** A model key in pi's catalogue, as "provider/model-id". */
18
31
  model: z.string().optional(),
19
32
  thinking: z.enum(VALID_THINKING_LEVELS).optional(),
20
- tools: z.array(z.string()).optional(),
21
- exclude_tools: z.array(z.string()).optional(),
22
33
  extensions: filterList.optional(),
23
34
  skills: filterList.optional(),
24
35
  /** Names inlined in full into the system prompt; a `skills` entry is only a name, description, and file path. An empty list inlines nothing. */
25
36
  inlined_skills: z.array(z.string()).optional(),
26
37
  /** Fork the parent session into the subagent (`pi --fork <sessionFile>`). */
27
38
  fork: z.boolean().optional(),
39
+ /** Tools available to a pi-family launch, in pi's own vocabulary. */
40
+ tools: z.array(z.string()).optional(),
41
+ /** Tools withheld from a pi-family launch, in pi's own vocabulary. */
42
+ exclude_tools: z.array(z.string()).optional(),
43
+ };
44
+ const PiHarnessSchema = z.strictObject(PI_HARNESS_SHAPE);
45
+ /** opencode's own `[harness.opencode]` keys; no other family reads them. */
46
+ const OpencodeHarnessSchema = z.strictObject({
47
+ /** A model key in opencode's catalogue, as "provider/model-id". */
48
+ model: z.string().optional(),
49
+ /** The reasoning-effort variant opencode's agent definition carries (the `--variant` of `opencode run`, which is not a flag of the command pi-cowboy launches). */
50
+ variant: z.string().optional(),
51
+ /** Tools available to an opencode launch, as opencode's permission keys. */
52
+ tools: z.array(z.string()).optional(),
53
+ /** Tools withheld from an opencode launch, as opencode's permission keys. */
54
+ exclude_tools: z.array(z.string()).optional(),
55
+ });
56
+ /**
57
+ * codex's own `[harness.codex]` keys; no other family reads them. codex has
58
+ * no tools flag, so the table carries the model alone — a tool pair here
59
+ * would have no reader.
60
+ */
61
+ const CodexHarnessSchema = z.strictObject({
62
+ /** A model key in codex's catalogue, as "provider/model-id". */
63
+ model: z.string().optional(),
64
+ });
65
+ /** claude's own `[harness.claude]` keys; no other family reads them. */
66
+ const ClaudeHarnessSchema = z.strictObject({
67
+ /** A model key in claude's catalogue, as "provider/model-id" (`anthropic/<alias>`); the launch strips the prefix to the bare alias the CLI takes. */
68
+ model: z.string().optional(),
69
+ /** Tools available to a claude launch, as claude's own tool names (`Bash`, `Read`, …), carried onto `--tools` exactly as written. */
70
+ tools: z.array(z.string()).optional(),
71
+ /** Tools withheld from a claude launch, as claude's own tool names, carried onto `--disallowedTools` exactly as written. */
72
+ exclude_tools: z.array(z.string()).optional(),
73
+ });
74
+ /** One family's tool arms as parsed, arbitrated to the single filter a launch reads: whitelist wins when both arms are set. */
75
+ function toToolFilter(tools, excludeTools) {
76
+ if (tools !== undefined)
77
+ return { tools };
78
+ if (excludeTools !== undefined)
79
+ return { excludeTools };
80
+ return undefined;
81
+ }
82
+ /**
83
+ * The `[harness]` table describes the child process, not the agent's identity
84
+ * or its worktree. The one family-neutral key (`include_context_files`) sits
85
+ * here; every catalogue-scoped key sits with its family — a model key with the
86
+ * family whose catalogue defines it, a tool list with the family whose names
87
+ * it is written in — under `[harness.<family>]`, with pi's spellings also
88
+ * loadable flat.
89
+ *
90
+ * A pi-only key written flat under `[harness]` means the same slice as
91
+ * `[harness.pi]`, so both spellings load; an explicit `[harness.pi]` value wins
92
+ * over its flat twin, per key. The transform collapses the family tables into
93
+ * the one shape the resolution code reads, so the on-disk keying stops at this
94
+ * boundary — and it keeps the model keys and the tool filters keyed by family,
95
+ * so the slice a launch reads is the one its own catalogue wrote.
96
+ */
97
+ const HarnessSchema = z
98
+ .strictObject({
28
99
  /** Whether the child's system prompt carries the repo's AGENTS.md context files. */
29
100
  include_context_files: z.boolean().optional(),
101
+ pi: PiHarnessSchema.optional(),
102
+ opencode: OpencodeHarnessSchema.optional(),
103
+ codex: CodexHarnessSchema.optional(),
104
+ claude: ClaudeHarnessSchema.optional(),
105
+ ...PI_HARNESS_SHAPE,
106
+ })
107
+ .transform(({ pi, opencode, codex, claude, ...flat }) => {
108
+ const { model: flatModel, tools: flatTools, exclude_tools: flatExcludeTools, ...sharedFlat } = flat;
109
+ const { model: piModel, tools: piTools, exclude_tools: piExcludeTools, ...piSlice } = compactDefined(pi ?? {});
110
+ const { model: opencodeModel, tools: opencodeTools, exclude_tools: opencodeExcludeTools, ...opencodeSlice } = compactDefined(opencode ?? {});
111
+ const { model: codexModel, ...codexSlice } = compactDefined(codex ?? {});
112
+ const { model: claudeModel, tools: claudeTools, exclude_tools: claudeExcludeTools, } = compactDefined(claude ?? {});
113
+ const modelsByFamily = compactDefined({
114
+ pi: piModel ?? flatModel,
115
+ opencode: opencodeModel,
116
+ codex: codexModel,
117
+ claude: claudeModel,
118
+ });
119
+ const toolsByFamily = compactDefined({
120
+ pi: toToolFilter(piTools ?? flatTools, piExcludeTools ?? flatExcludeTools),
121
+ opencode: toToolFilter(opencodeTools, opencodeExcludeTools),
122
+ claude: toToolFilter(claudeTools, claudeExcludeTools),
123
+ });
124
+ return {
125
+ ...sharedFlat,
126
+ ...piSlice,
127
+ ...opencodeSlice,
128
+ ...codexSlice,
129
+ ...(Object.keys(modelsByFamily).length > 0 ? { modelsByFamily } : {}),
130
+ ...(Object.keys(toolsByFamily).length > 0 ? { toolsByFamily } : {}),
131
+ };
30
132
  });
31
133
  export const AgentTemplateSchema = z.strictObject({
32
134
  name: z.string().optional(),
@@ -131,7 +131,6 @@ export function getConfig(type, loadSkillsImplicitly = true, loadExtensionsImpli
131
131
  return {
132
132
  displayName: rest.displayName ?? rest.name,
133
133
  description: rest.description,
134
- tools: rest.tools,
135
134
  ...defaults,
136
135
  };
137
136
  }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * harness/claude/index.ts — the claude harness: a binary of its own, staged
3
+ * and launched behind the pane's `claude`.
4
+ *
5
+ * claude is not a pi-compatible binary: its task cannot ride the argv at all
6
+ * (herdr rejects multi-line arguments, and a task is multi-line text), so the
7
+ * launcher appends it as the positional initial prompt — past a `--` that ends
8
+ * option parsing, `"$(cat '<taskFile>')"` expands inside the pane's shell, where herdr's single-line
9
+ * argv encoding never reaches. `prepare` stages the config directory claude is
10
+ * pointed at (staging.ts), installs that launcher into the pane, and then
11
+ * proves the pane can see the staged files and resolve the binary; `buildArgs`
12
+ * is claude's interactive CLI with the task deliberately absent;
13
+ * `teardown` removes the staged tree.
14
+ *
15
+ * `listModels` is a curated constant: claude has no CLI enumeration, and a
16
+ * wrong list is worse than a short one, so it names only the aliases a real
17
+ * run was seen to answer (`haiku`, `sonnet`, `opus`) and nothing it was seen
18
+ * to refuse.
19
+ *
20
+ * The strict `[harness.claude]` table carries only `model` and the tool pair,
21
+ * both in claude's own vocabulary: the tool names ride `--tools` /
22
+ * `--disallowedTools` exactly as written, with no translation, and the model
23
+ * key's `anthropic/` prefix is stripped at the argv boundary because the CLI
24
+ * takes a bare alias or full model name.
25
+ */
26
+ import { commandPath } from "../../../infrastructure/exec-path.js";
27
+ import { subagentTokenFor } from "../../../paths.js";
28
+ import { installPaneLauncher } from "../pane-launcher.js";
29
+ import { claudeSettingsFile, removeClaudeStaging, writeClaudeStaging, } from "./staging.js";
30
+ /** Budget for the pane's staged-state proof; shell builtins, no CLI boot. */
31
+ const STAGED_PROOF_TIMEOUT_MS = 15_000;
32
+ /** The command herdr types into the pane; the launcher is installed under it. */
33
+ const CLAUDE_COMMAND = "claude";
34
+ /** Signature carried by this launcher, so pane verification proves which launcher landed. */
35
+ const LAUNCHER_SIGNATURE = "CLAUDE_LAUNCHER_3f7a1d";
36
+ /** Token the verify command echoes once the launcher body is confirmed. */
37
+ const LAUNCHER_READY_MARKER = "CLAUDE_VERIFIED";
38
+ /** Token the staged-state proof echoes once the pane sees the launch state. */
39
+ const STAGED_MARKER = "CLAUDE_STAGED";
40
+ /**
41
+ * The launcher body: the credential rename first, then claude's config
42
+ * directory and the memory suppression a spawn needs (pi-cowboy renders
43
+ * context into the system prompt itself, so the worktree's memory files would
44
+ * only load twice), then the real binary with the pane's own arguments and
45
+ * the task as its positional initial prompt.
46
+ *
47
+ * The rename keeps the consent predicate from ever seeing a key: with
48
+ * `ANTHROPIC_API_KEY` unset it cannot fire, and the key resolves through the
49
+ * staged `apiKeyHelper` instead, which has no approval check. The `unset` is
50
+ * load-bearing — a staged helper alone does not suppress the dialog while the
51
+ * variable is still set (verified against the real CLI: the TUI parks at the
52
+ * consent prompt). Pane-side, `env` therefore shows `COWBOY_API_KEY` where
53
+ * the ambient key was: that absence is this line working, not a missing
54
+ * credential. On a keyless run the rename is a no-op, so the launcher deletes the helper's line from
55
+ * the staged settings — a configured-but-failing helper errors instead of
56
+ * falling through to OAuth, and only an absent helper leaves that path open.
57
+ * The deletion names the line's key rather than its number, so it survives
58
+ * reformatting as long as the helper keeps its own line (see staging.ts);
59
+ * `grep` + `mv` are POSIX-portable where `sed -i` is not, and a failed trim
60
+ * leaves the file untouched (loud helper error) rather than half-edited.
61
+ *
62
+ * Bare `claude` keeps the pane's `PATH` the authority on which binary runs,
63
+ * and `command` bypasses this very function. The `$(cat …)` expansion is what
64
+ * delivers a multi-line task: herdr encodes the argv it types and refuses
65
+ * multi-line arguments, but this expansion happens inside the pane's shell,
66
+ * past that encoding, as one word of the launched command. The `--` before it
67
+ * ends option parsing: `--tools` / `--disallowedTools` are variadic and would
68
+ * otherwise swallow the task as another tool name (and a task starting with
69
+ * `-` would parse as a flag), leaving the TUI idle with no initial prompt.
70
+ */
71
+ function launcherBody(configDir, taskFile) {
72
+ const settings = singleQuote(claudeSettingsFile(configDir));
73
+ const trimmed = singleQuote(`${claudeSettingsFile(configDir)}.tmp`);
74
+ return [
75
+ `if [ -n "\${ANTHROPIC_API_KEY:-}" ]; then export COWBOY_API_KEY="$ANTHROPIC_API_KEY"; unset ANTHROPIC_API_KEY; else grep -v '"apiKeyHelper"' ${settings} > ${trimmed} && mv ${trimmed} ${settings}; fi`,
76
+ `export CLAUDE_CONFIG_DIR=${singleQuote(configDir)}`,
77
+ "export CLAUDE_CODE_DISABLE_CLAUDE_MDS=1",
78
+ `command claude "$@" -- "$(cat ${singleQuote(taskFile)})"`,
79
+ ].join("; ");
80
+ }
81
+ /**
82
+ * A value as one POSIX shell word: single quotes around it, and the `'\''` dance
83
+ * for any single quote inside. Every path this harness passes is its own temp
84
+ * path, but the launcher is a shell command herdr types into the pane, so the
85
+ * value is quoted rather than trusted.
86
+ */
87
+ function singleQuote(value) {
88
+ return `'${value.replaceAll("'", "'\\''")}'`;
89
+ }
90
+ /**
91
+ * The proof that the pane can launch what prepare staged, read back through
92
+ * the shell that will run it.
93
+ *
94
+ * `command -v` (not `claude --version`) proves the binary resolves on the
95
+ * pane's `PATH` — which need not match the parent's — without booting the CLI
96
+ * into a networked update check. The lookup runs past an `unset -f` in a
97
+ * subshell because `command -v` resolves functions before `PATH`: without it
98
+ * the check would pass on the launcher this install just defined, even with
99
+ * no binary anywhere, and the failure below could never fire. The subshell
100
+ * keeps the installed launcher intact for the launch that follows. The
101
+ * `test -r` pair proves the staged settings and the task file the launcher
102
+ * names are visible from the pane; without them the TUI would park at its
103
+ * onboarding or trust dialog, which nothing in the argv or exit status
104
+ * reports. The marker is broken with a `""` so only the shell's evaluation
105
+ * of the command — not the command line's own echo, which `wait-output` also
106
+ * sees — produces the contiguous token.
107
+ */
108
+ function stagedProof(configDir, taskFile) {
109
+ return {
110
+ command: `test -r ${singleQuote(claudeSettingsFile(configDir))} && test -r ${singleQuote(taskFile)} && (unset -f ${CLAUDE_COMMAND}; command -v ${CLAUDE_COMMAND} >/dev/null) && echo CLAUDE_""STAGED`,
111
+ output: STAGED_MARKER,
112
+ timeoutMs: STAGED_PROOF_TIMEOUT_MS,
113
+ failure: `failed to prepare the pane: the pane never proved it can see the staged claude state — the settings ${claudeSettingsFile(configDir)}, the task ${taskFile}, or the claude binary on its PATH. The agent did not start.`,
114
+ };
115
+ }
116
+ /**
117
+ * The model key as claude's `--model` takes it: the CLI accepts a bare alias
118
+ * (`sonnet`) or a full model name, never the `provider/model` shape every
119
+ * layer stores, so the `anthropic/` prefix is stripped at this boundary. A key
120
+ * outside the anthropic provider rides as written — there is nothing to
121
+ * translate it to, and the API surfaces the mistake.
122
+ */
123
+ function claudeModelName(modelKey) {
124
+ const prefix = "anthropic/";
125
+ return modelKey.startsWith(prefix) ? modelKey.slice(prefix.length) : modelKey;
126
+ }
127
+ /**
128
+ * The tool selection as claude's tool flags, in claude's own names
129
+ * (`Bash`, `Read`, `Write`, `Edit`, `Glob`, `Grep`, `Task`, …) exactly as the
130
+ * template wrote them. `--tools ""` is claude's spelling of none; the default
131
+ * case emits no flag, so claude's own discovery stands.
132
+ */
133
+ function toolArgs(request) {
134
+ switch (request.toolSelection.kind) {
135
+ case "default":
136
+ return [];
137
+ case "none":
138
+ return ["--tools", ""];
139
+ case "include":
140
+ return ["--tools", request.toolSelection.names.join(",")];
141
+ case "exclude":
142
+ return ["--disallowedTools", request.toolSelection.names.join(",")];
143
+ }
144
+ }
145
+ /**
146
+ * Every model this harness offers, as `anthropic/<alias>` keys. claude's CLI
147
+ * has no list command, so this list is curated, not discovered: each alias was
148
+ * seen to answer on the real CLI, and an alias that was seen refused stays
149
+ * off. A menu therefore offers only models a launch can actually run.
150
+ */
151
+ const CLAUDE_MODELS = [
152
+ { key: "anthropic/haiku", label: "haiku" },
153
+ { key: "anthropic/sonnet", label: "sonnet" },
154
+ { key: "anthropic/opus", label: "opus" },
155
+ ];
156
+ export const claudeHarness = {
157
+ id: "claude",
158
+ agentMuxKind: "claude",
159
+ available: () => commandPath("claude") !== undefined,
160
+ /**
161
+ * Stage the config directory, install the launcher that points claude at it
162
+ * and appends the task, and prove the pane sees the staged state behind it.
163
+ * A launch reaches the CLI through this pane state alone, so it is verified
164
+ * here rather than assumed.
165
+ */
166
+ async prepare({ pi, paneId, cwd, launch, }) {
167
+ const configDir = writeClaudeStaging({
168
+ subagentId: launch.subagentId,
169
+ cwd,
170
+ });
171
+ await installPaneLauncher(pi, paneId, {
172
+ commandName: CLAUDE_COMMAND,
173
+ body: launcherBody(configDir, launch.taskFile),
174
+ signature: LAUNCHER_SIGNATURE,
175
+ readyMarker: LAUNCHER_READY_MARKER,
176
+ proof: stagedProof(configDir, launch.taskFile),
177
+ });
178
+ },
179
+ /**
180
+ * `--system-prompt-file` replaces claude's default system prompt (parity
181
+ * with the pi family, which also replaces): the staged prompt already
182
+ * carries the rendered context, so the default's own tool guidance is the
183
+ * price of the replace. The identity rides `--append-system-prompt`, which
184
+ * appends rather than replaces. `--dangerously-skip-permissions` is what
185
+ * lets a background pane run tools without approvals, with its interactive
186
+ * acceptance pre-seeded in the staged settings. `--setting-sources user`
187
+ * and `--strict-mcp-config` keep the worktree's own settings and MCP
188
+ * servers out of the spawn, so a launch reads only what this harness
189
+ * staged. The task is absent: the launcher appends it as the positional
190
+ * initial prompt, because multi-line text cannot cross herdr's argv.
191
+ */
192
+ buildArgs(request) {
193
+ const args = [
194
+ "--system-prompt-file",
195
+ request.systemPromptFile,
196
+ "--append-system-prompt",
197
+ subagentTokenFor(request.subagentId),
198
+ "-n",
199
+ request.subagentId,
200
+ "--dangerously-skip-permissions",
201
+ "--setting-sources",
202
+ "user",
203
+ "--strict-mcp-config",
204
+ ];
205
+ if (request.modelKey !== null)
206
+ args.push("--model", claudeModelName(request.modelKey));
207
+ args.push(...toolArgs(request));
208
+ return args;
209
+ },
210
+ // The list is a constant, not a fetch: claude offers no enumeration command,
211
+ // so there is nothing to memoize, nothing to warm, and nothing that can fail.
212
+ listModels: () => Promise.resolve(CLAUDE_MODELS),
213
+ prefetchModels: (_pi) => { },
214
+ // Best effort and idempotent: the staged tree is this harness's only
215
+ // filesystem state, and a launch that failed before prepare staged nothing.
216
+ teardown: async ({ subagentId }) => {
217
+ removeClaudeStaging(subagentId);
218
+ },
219
+ };