pi-cowboy 0.0.0 → 0.3.2

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -2
  3. package/agents/explore.toml +40 -0
  4. package/dist/agents/agent-assets.js +261 -0
  5. package/dist/agents/agent-cleanup.js +284 -0
  6. package/dist/agents/agent-discovery.js +108 -0
  7. package/dist/agents/agent-host.js +10 -0
  8. package/dist/agents/agent-manager.js +367 -0
  9. package/dist/agents/agent-reviver.js +64 -0
  10. package/dist/agents/agent-runner.js +288 -0
  11. package/dist/agents/agent-spawn-store.js +57 -0
  12. package/dist/agents/agent-template.js +46 -0
  13. package/dist/agents/agent-types.js +144 -0
  14. package/dist/agents/batch.js +92 -0
  15. package/dist/agents/cleanup-policy.js +194 -0
  16. package/dist/agents/cleanup-report.js +128 -0
  17. package/dist/agents/default-agents.js +19 -0
  18. package/dist/agents/harness/pi-bolt.js +15 -0
  19. package/dist/agents/harness/pi-compatible.js +68 -0
  20. package/dist/agents/harness/pig.js +16 -0
  21. package/dist/agents/harness/registry.js +27 -0
  22. package/dist/agents/harness.js +32 -0
  23. package/dist/agents/result-file-permissions.js +29 -0
  24. package/dist/agents/run-state.js +270 -0
  25. package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
  26. package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
  27. package/dist/agents/schemas/merge-batch.schema.js +25 -0
  28. package/dist/agents/schemas/steer-batch.schema.js +22 -0
  29. package/dist/agents/schemas/stop-batch.schema.js +18 -0
  30. package/dist/agents/spawn-defaults.js +70 -0
  31. package/dist/agents/subagent-session.js +601 -0
  32. package/dist/agents/tool-cleanup.js +57 -0
  33. package/dist/agents/tool-execution.js +125 -0
  34. package/dist/agents/tool-merge.js +190 -0
  35. package/dist/agents/tool-result.js +17 -0
  36. package/dist/agents/tool-steer.js +89 -0
  37. package/dist/agents/types.js +1 -0
  38. package/dist/availability.js +38 -0
  39. package/dist/config/config-io.js +261 -0
  40. package/dist/config/config-store.js +321 -0
  41. package/dist/config/config-validation.js +173 -0
  42. package/dist/config/layered-config.js +117 -0
  43. package/dist/config/types.js +23 -0
  44. package/dist/cow-support-launch.js +43 -0
  45. package/dist/events.js +146 -0
  46. package/dist/extension-toggle.js +28 -0
  47. package/dist/harness-availability-launch.js +23 -0
  48. package/dist/index.js +52 -0
  49. package/dist/infrastructure/exec-path.js +35 -0
  50. package/dist/infrastructure/git/cow-clone.js +398 -0
  51. package/dist/infrastructure/git/git-materializer.js +342 -0
  52. package/dist/infrastructure/git/git-merger.js +234 -0
  53. package/dist/infrastructure/git/git-retention.js +43 -0
  54. package/dist/infrastructure/git/git-runner.js +145 -0
  55. package/dist/infrastructure/git/git-worktree.js +143 -0
  56. package/dist/infrastructure/git/index.js +11 -0
  57. package/dist/infrastructure/git-client.js +11 -0
  58. package/dist/infrastructure/herdr/agent-stopper.js +60 -0
  59. package/dist/infrastructure/herdr/agents.js +329 -0
  60. package/dist/infrastructure/herdr/herdr-client.js +36 -0
  61. package/dist/infrastructure/herdr/herdr-transport.js +158 -0
  62. package/dist/infrastructure/herdr/index.js +15 -0
  63. package/dist/infrastructure/herdr/panes.js +174 -0
  64. package/dist/infrastructure/herdr/polling.js +44 -0
  65. package/dist/infrastructure/herdr/worktrees.js +76 -0
  66. package/dist/infrastructure/herdr-client.js +6 -0
  67. package/dist/infrastructure/herdr-host.js +163 -0
  68. package/dist/logger.js +79 -0
  69. package/dist/models/model-groups.js +72 -0
  70. package/dist/models/model-precedence.js +50 -0
  71. package/dist/models/model-request.js +108 -0
  72. package/dist/orchestrators/briefing-section.js +14 -0
  73. package/dist/orchestrators/context.js +116 -0
  74. package/dist/orchestrators/cues.js +90 -0
  75. package/dist/orchestrators/default-orchestrators.js +36 -0
  76. package/dist/orchestrators/orchestrator-discovery.js +68 -0
  77. package/dist/orchestrators/orchestrator-template.js +43 -0
  78. package/dist/orchestrators/orchestrator-types.js +78 -0
  79. package/dist/orchestrators/protocol.js +292 -0
  80. package/dist/orchestrators/types.js +7 -0
  81. package/dist/paths.js +66 -0
  82. package/dist/pi-settings.js +7 -0
  83. package/dist/predicates.js +25 -0
  84. package/dist/prompt/prompts.js +110 -0
  85. package/dist/prompt/skill-loader.js +153 -0
  86. package/dist/prompt/subagent-system-prompt.js +173 -0
  87. package/dist/registration.js +220 -0
  88. package/dist/shell.js +225 -0
  89. package/dist/spawn/cow-support.js +53 -0
  90. package/dist/spawn/herdr-launcher.js +80 -0
  91. package/dist/spawn/repo-lock.js +34 -0
  92. package/dist/spawn/sandbox.js +286 -0
  93. package/dist/spawn/spawn-coordinator.js +255 -0
  94. package/dist/spawn/spawn-id.js +39 -0
  95. package/dist/spawn/worktree-policy.js +137 -0
  96. package/dist/status-note.js +30 -0
  97. package/dist/subagent/ipc-protocol.js +68 -0
  98. package/dist/subagent/ipc.js +110 -0
  99. package/dist/subagent/pane-supervisor.js +24 -0
  100. package/dist/subagent/socket-ipc.js +240 -0
  101. package/dist/subagent/supervisor.js +315 -0
  102. package/dist/task-registry.js +258 -0
  103. package/dist/templates/template-files.js +84 -0
  104. package/dist/types.js +84 -0
  105. package/dist/ui/action-report.js +21 -0
  106. package/dist/ui/format.js +47 -0
  107. package/dist/ui/indicator.js +480 -0
  108. package/dist/ui/menu/helpers.js +227 -0
  109. package/dist/ui/menu/menu-agent-settings.js +182 -0
  110. package/dist/ui/menu/menu-agent-status.js +444 -0
  111. package/dist/ui/menu/menu-concurrency.js +226 -0
  112. package/dist/ui/menu/menu-model-settings.js +244 -0
  113. package/dist/ui/menu/menu-spawn-defaults.js +71 -0
  114. package/dist/ui/menu/menu-spawn-wizard.js +367 -0
  115. package/dist/ui/menu/menu-spawn-worktree.js +107 -0
  116. package/dist/ui/menu/menu-system-prompt.js +104 -0
  117. package/dist/ui/menu/menu-worktree-command.js +150 -0
  118. package/dist/ui/menu/menus.js +187 -0
  119. package/dist/ui/menu/model-picker.js +160 -0
  120. package/dist/ui/menu/screen-host.js +87 -0
  121. package/dist/ui/menu/submenus/confirm.js +23 -0
  122. package/dist/ui/menu/submenus/model-select.js +42 -0
  123. package/dist/ui/menu/submenus/name-field.js +43 -0
  124. package/dist/ui/menu/submenus/numeric-input.js +61 -0
  125. package/dist/ui/menu/submenus/target-select.js +129 -0
  126. package/dist/ui/menu/submenus/text-editor.js +49 -0
  127. package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
  128. package/dist/ui/menu/submenus/worktree-name.js +53 -0
  129. package/dist/ui/menu/wrappers/settings-list.js +101 -0
  130. package/dist/ui/searchable-select.js +147 -0
  131. package/dist/ui/types.js +1 -0
  132. package/dist/utils.js +70 -0
  133. package/docs/assets/grazing.png +0 -0
  134. package/docs/assets/herdr-containers.png +0 -0
  135. package/docs/assets/logo-transparent.png +0 -0
  136. package/orchestrators/with-code-review.toml +20 -0
  137. package/package.json +109 -3
@@ -0,0 +1,173 @@
1
+ /**
2
+ * subagent-system-prompt.ts — The standing system prompt of a subagent spawn.
3
+ *
4
+ * Pure prompt compiler: resolved agent template, spawn config, and spawn
5
+ * identity in; full system-prompt text out. agent-runner.ts owns what this
6
+ * module does not: staging the text to `system.md` and assembling the pi
7
+ * argv. External sources arrive as plain arguments, so the composer holds no
8
+ * shell state and unit-tests with fakes.
9
+ */
10
+ import fs from "node:fs";
11
+ import { loadProjectContextFiles, } from "@earendil-works/pi-coding-agent";
12
+ import { errorMessage, GIT_EXEC_TIMEOUT_MS } from "../utils.js";
13
+ import { agentDir } from "../paths.js";
14
+ import { customPromptPath } from "../config/config-io.js";
15
+ import { DEFAULT_AGENTS } from "../agents/default-agents.js";
16
+ import { buildOrchestrationGuidance } from "../orchestrators/briefing-section.js";
17
+ import { buildAgentPrompt, } from "./prompts.js";
18
+ import { loadSkillMeta, inlineSkills } from "./skill-loader.js";
19
+ async function execGit(pi, args, cwd) {
20
+ try {
21
+ const result = await pi.exec("git", args, {
22
+ cwd,
23
+ timeout: GIT_EXEC_TIMEOUT_MS,
24
+ });
25
+ return result.code === 0 ? result.stdout.trim() : null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ /** Environment detection through `pi.exec`, so the git probes inherit the parent pane's environment. */
32
+ async function detectEnv(pi, cwd) {
33
+ const gitRoot = await execGit(pi, ["rev-parse", "--is-inside-work-tree"], cwd);
34
+ const isGitRepo = gitRoot === "true";
35
+ const branch = isGitRepo
36
+ ? await execGit(pi, ["branch", "--show-current"], cwd)
37
+ : null;
38
+ return {
39
+ isGitRepo,
40
+ branch,
41
+ platform: process.platform,
42
+ };
43
+ }
44
+ /** Resolve the mode's external sources (parent prompt, custom file, AGENTS.md). A missing source warns on `notify` and degrades the prompt — it never fails the launch. */
45
+ async function resolveSystemPromptSources(ctx, cwd, notify, agentConfig, mode, globalIncludeContextFiles) {
46
+ const promptPath = customPromptPath();
47
+ const includeContextFiles = agentConfig?.includeContextFiles ?? globalIncludeContextFiles;
48
+ const extras = {};
49
+ if (mode === "inherit") {
50
+ try {
51
+ extras.parentSystemPrompt = ctx.getSystemPrompt();
52
+ }
53
+ catch (err) {
54
+ notify(`Failed to get parent system prompt: ${errorMessage(err)}. Falling back to replace mode.`);
55
+ }
56
+ }
57
+ if (mode === "custom") {
58
+ try {
59
+ const content = fs.readFileSync(promptPath, "utf-8").trim();
60
+ if (content) {
61
+ extras.customSystemPrompt = content;
62
+ }
63
+ else {
64
+ notify(`Custom prompt file is empty: ${promptPath}. Falling back to replace mode.`);
65
+ }
66
+ }
67
+ catch (err) {
68
+ if (err?.code === "ENOENT") {
69
+ notify(`Custom prompt file not found: ${promptPath}. Falling back to replace mode.`);
70
+ }
71
+ else {
72
+ notify(`Failed to read custom prompt file: ${errorMessage(err)}. Falling back to replace mode.`);
73
+ }
74
+ }
75
+ }
76
+ if (includeContextFiles) {
77
+ try {
78
+ extras.contextFiles = loadProjectContextFiles({
79
+ cwd,
80
+ agentDir: agentDir(),
81
+ });
82
+ }
83
+ catch {
84
+ // Context files are supplementary; their absence is not fatal.
85
+ }
86
+ }
87
+ return extras;
88
+ }
89
+ /** Build the agent-specific prompt parts with configured skills loaded. An unregistered type falls back to the embedded general-purpose template. */
90
+ async function buildPrompt(type, agentConfig, config, cwd, env, systemPromptMode, resolverExtras) {
91
+ const extras = { ...resolverExtras };
92
+ const inlinedSkills = agentConfig?.inlinedSkills ?? [];
93
+ if (inlinedSkills.length > 0) {
94
+ extras.inlinedSkills = await inlineSkills(inlinedSkills, cwd);
95
+ }
96
+ if (Array.isArray(config.skills)) {
97
+ extras.skillMetas = await loadSkillMeta(config.skills, cwd);
98
+ }
99
+ if (agentConfig) {
100
+ return await buildAgentPrompt(agentConfig, cwd, env, extras, systemPromptMode);
101
+ }
102
+ const fallback = DEFAULT_AGENTS.get("general-purpose");
103
+ if (!fallback)
104
+ throw new Error(`No fallback config available for unknown type "${type}"`);
105
+ return await buildAgentPrompt({ ...fallback, name: type }, cwd, env, extras, systemPromptMode);
106
+ }
107
+ /** Join non-empty sections with one blank line. Agent guidance (with its whitespace) survives verbatim. */
108
+ function joinPromptSections(sections) {
109
+ return sections
110
+ .filter((section) => Boolean(section?.trim()))
111
+ .join("\n\n");
112
+ }
113
+ /** The branch to name: the detected one when it carries something, else the expected one. */
114
+ function branchName(detected, expected) {
115
+ return detected !== null && detected !== "" ? detected : expected;
116
+ }
117
+ /** Branch block: detected checkout branch, else the expected branch pinned at create time. Empty when not a worktree run. */
118
+ export function buildWorktreeBranchSection(worktreePath, isGitRepo, detectedBranch, expectedBranch) {
119
+ const name = worktreePath && isGitRepo
120
+ ? branchName(detectedBranch, expectedBranch)
121
+ : undefined;
122
+ if (!name)
123
+ return "";
124
+ return [
125
+ "",
126
+ "## Worktree branch",
127
+ "",
128
+ `You are working in a git worktree on branch \`${name}\`.`,
129
+ "Every commit you make and every merge you run lands on THIS branch — never on `main` or any other branch.",
130
+ "Do NOT switch branches and do NOT merge into `main` yourself. Report the branch name in your final response so the orchestrator can merge it with the merge_cowboy_branch tool.",
131
+ ].join("\n");
132
+ }
133
+ /** Steering contract: mid-run instructions outrank the task; divergences must be disclosed so the orchestrator can tell a requested change from scope slip. */
134
+ function buildSteeringInstructions() {
135
+ return [
136
+ "## Steering & Mid-Run Instructions",
137
+ "- You may receive additional instructions or steering messages while working (from the user or the orchestrator).",
138
+ "- Always treat mid-run steering and follow-up instructions as having higher priority than your original initial prompt.",
139
+ "- In your final report (written to the result file), you MUST explicitly disclose any steering or direction changes you received during implementation.",
140
+ "- If steering or code review comments caused you to diverge from, modify, or abandon parts of the original goal, clearly explain what changed and why, so the orchestrator understands that the divergence was intentional and requested.",
141
+ ].join("\n");
142
+ }
143
+ /** Deliverable contract: the path the child writes to, in the wording the parent reads back. */
144
+ function buildResultInstruction(resultFile) {
145
+ return [
146
+ "",
147
+ "When you have completed the task, write your complete final response verbatim to the file:",
148
+ resultFile,
149
+ "",
150
+ "Write the full final answer as Markdown to that file, then reply with a one-line confirmation. The parent session reads that file as your deliverable.",
151
+ ].join("\n");
152
+ }
153
+ /**
154
+ * Compile one spawn's standing system prompt. Composition order is fixed:
155
+ * shared prefix, identity, skills, spawn contract (branch, steering,
156
+ * deliverable), orchestrator guidance LAST. The task itself is never here;
157
+ * it is the pane's initial message.
158
+ */
159
+ export async function buildSubagentSystemPrompt(options) {
160
+ const { pi, ctx, cwd, notify } = options;
161
+ const env = await detectEnv(pi, cwd);
162
+ const extras = await resolveSystemPromptSources(ctx, cwd, notify, options.agentConfig, options.globalSystemPromptMode, options.globalIncludeContextFiles);
163
+ const parts = await buildPrompt(options.type, options.agentConfig, options.config, cwd, env, options.globalSystemPromptMode, extras);
164
+ return joinPromptSections([
165
+ parts.prefix,
166
+ parts.identity,
167
+ parts.skills,
168
+ buildWorktreeBranchSection(options.worktreePath, env.isGitRepo, env.branch, options.expectedBranch),
169
+ buildSteeringInstructions(),
170
+ buildResultInstruction(options.resultFile),
171
+ buildOrchestrationGuidance(options.agentGuidance),
172
+ ]);
173
+ }
@@ -0,0 +1,220 @@
1
+ import { Type } from "typebox";
2
+ import { Text } from "@earendil-works/pi-tui";
3
+ import { CowboyAgentsSchema, } from "./agents/schemas/cowboy-agents.schema.js";
4
+ import { StopBatchSchema } from "./agents/schemas/stop-batch.schema.js";
5
+ import { CleanupBatchSchema } from "./agents/schemas/cleanup-batch.schema.js";
6
+ import { MergeBatchSchema } from "./agents/schemas/merge-batch.schema.js";
7
+ import { SteerBatchSchema } from "./agents/schemas/steer-batch.schema.js";
8
+ import { getAvailableTypes } from "./agents/agent-types.js";
9
+ import { executeAgentTool, executeStopAgentTool, } from "./agents/tool-execution.js";
10
+ import { executeCleanupAgentTool } from "./agents/tool-cleanup.js";
11
+ import { executeMergeBranchTool } from "./agents/tool-merge.js";
12
+ import { executeSteerAgentTool } from "./agents/tool-steer.js";
13
+ import { isExtensionEnabled, syncExtensionIndicator, } from "./extension-toggle.js";
14
+ import { getPiInstance, getStore } from "./shell.js";
15
+ /** The one place a tool name is spelled; the tools below are named from these. */
16
+ export const COWBOY_TOOLS = {
17
+ agent: "cowboy_agent",
18
+ stopAgent: "stop_cowboy_agent",
19
+ mergeBranch: "merge_cowboy_branch",
20
+ steerAgent: "steer_cowboy_agent",
21
+ cleanupAgent: "cleanup_cowboy_agent",
22
+ };
23
+ export const COWBOY_TOOL_NAMES = Object.values(COWBOY_TOOLS);
24
+ // The /cowboy UI is imported lazily so none of it runs at boot.
25
+ // "prefer" falls back gracefully on providers without strict mode.
26
+ const CONSTRAINED_SAMPLING = {
27
+ type: "json_schema",
28
+ strict: "prefer",
29
+ };
30
+ /**
31
+ * Rebuild the per-item `agent_type` description so it lists the agent types
32
+ * known at registration time. The shape — and therefore the derived type in
33
+ * `cowboy-agents.schema.ts` — is unchanged; only the description text differs.
34
+ */
35
+ function cowboyAgentsSchemaWithTypes(types) {
36
+ const agentTypeDescription = types.length > 0
37
+ ? `Optional agent type; when omitted the configured default agent type is used ("general-purpose" unless changed in settings). An unknown or ambiguous name is rejected before any agent in the batch spawns. Available: ${types.join(",")}`
38
+ : `Optional agent type; when omitted the configured default agent type is used ("general-purpose" unless changed in settings). An unknown or ambiguous name is rejected before any agent in the batch spawns.`;
39
+ const params = Type.Object({
40
+ prompt: CowboyAgentsSchema.properties.agents.items.properties.prompt,
41
+ task_name: CowboyAgentsSchema.properties.agents.items.properties.task_name,
42
+ agent_type: Type.Optional(Type.String({ description: agentTypeDescription })),
43
+ model: CowboyAgentsSchema.properties.agents.items.properties.model,
44
+ }, { additionalProperties: false, required: ["prompt", "task_name"] });
45
+ return Type.Object({
46
+ agents: Type.Array(params, { minItems: 1 }),
47
+ run_in_background: CowboyAgentsSchema.properties.run_in_background,
48
+ }, { additionalProperties: false, required: ["agents"] });
49
+ }
50
+ /** Re-registers the agent tool once the session's agent types are known. */
51
+ export function registerAgentTool(pi) {
52
+ const params = cowboyAgentsSchemaWithTypes(getAvailableTypes());
53
+ const tool = {
54
+ name: COWBOY_TOOLS.agent,
55
+ label: COWBOY_TOOLS.agent,
56
+ description: "Delegate one or more tasks to agents. Each agent gets an isolated worktree and a fresh pi process — pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes — do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles — do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. When an agent settles, the completion message names its `cow-` branch and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",
57
+ parameters: params,
58
+ execute: executeAgentTool,
59
+ constrainedSampling: CONSTRAINED_SAMPLING,
60
+ };
61
+ pi.registerTool(tool);
62
+ }
63
+ /**
64
+ * Persists the switch and runs the half the new value calls for. The tools are
65
+ * registered once at extension initialization, so the switch only moves their
66
+ * names in and out of the active set.
67
+ */
68
+ export function setExtensionEnabled(ui, enabled) {
69
+ getStore().mutate.agent.setExtensionEnabled(enabled);
70
+ if (enabled)
71
+ activateExtension(ui);
72
+ else
73
+ deactivateExtension(ui);
74
+ }
75
+ /**
76
+ * Puts the Cowboy tools in the active set, re-registering the agent tool so its
77
+ * `agent_type` list carries the types this session scanned, and shows the
78
+ * presence marker in the top-right corner.
79
+ */
80
+ export function activateExtension(ui) {
81
+ const pi = getPiInstance();
82
+ registerAgentTool(pi);
83
+ pi.setActiveTools([
84
+ ...new Set([...pi.getActiveTools(), ...COWBOY_TOOL_NAMES]),
85
+ ]);
86
+ syncExtensionIndicator(ui);
87
+ }
88
+ /**
89
+ * Takes the Cowboy tools out of the active set and clears the presence marker.
90
+ * pi has no way to unregister a tool, so an inactive name is what keeps the
91
+ * model from being offered one — and pi rejects a call to it.
92
+ */
93
+ export function deactivateExtension(ui) {
94
+ const pi = getPiInstance();
95
+ pi.setActiveTools(pi.getActiveTools().filter((name) => !COWBOY_TOOL_NAMES.includes(name)));
96
+ syncExtensionIndicator(ui);
97
+ }
98
+ /** The Cowboy tools — registered once at extension initialization. */
99
+ export function registerTools(pi) {
100
+ registerAgentTool(pi);
101
+ const stopAgentTool = {
102
+ name: COWBOY_TOOLS.stopAgent,
103
+ label: COWBOY_TOOLS.stopAgent,
104
+ description: "Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order — stopped, reported as already settled, or reported unknown — and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped — pass each id once. Stopping interrupts the pi process (its pane is left in place) and settles the agent as stopped. Nothing is removed — the worktree and branch are preserved.",
105
+ parameters: StopBatchSchema,
106
+ execute: executeStopAgentTool,
107
+ constrainedSampling: CONSTRAINED_SAMPLING,
108
+ renderResult: (result, _options, theme, context) => {
109
+ const isError = context.isError ?? false;
110
+ const content = result.content.at(0);
111
+ const text = content?.type === "text" ? content.text : "";
112
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
113
+ return new Text(`${icon} ${text}`, 0, 0);
114
+ },
115
+ };
116
+ // @ts-expect-error — matching pi's exact generic would force an import this repo avoids.
117
+ pi.registerTool(stopAgentTool);
118
+ const mergeBranchTool = {
119
+ name: COWBOY_TOOLS.mergeBranch,
120
+ label: COWBOY_TOOLS.mergeBranch,
121
+ description: "Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges — pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch — the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",
122
+ parameters: MergeBatchSchema,
123
+ execute: executeMergeBranchTool,
124
+ constrainedSampling: CONSTRAINED_SAMPLING,
125
+ };
126
+ pi.registerTool(mergeBranchTool);
127
+ const steerAgentTool = {
128
+ name: COWBOY_TOOLS.steerAgent,
129
+ label: COWBOY_TOOLS.steerAgent,
130
+ description: "Send one message to one or more agents in one call: pass every id in `agent_ids` and the single `message` delivered to each. Each id is handled independently in input order — delivered, or refused with its reason — and one id's refusal never blocks the rest. A repeated id in `agent_ids` is rejected before anything is delivered — pass each id once. A spawned agent receives the message before its next model call; a SETTLED one is REVIVED — spawned again, given the message, and it sends you another completion message when it settles again. That second result arrives only as that completion message: the spawn's result promise closed with the first turn and never opens again. Delivery is fire-and-forget: nothing here waits for an agent to act on it, so do not poll for a reply. The message is entered into the agent's pi session, so it can also be a bash command: `!command` runs the command and sends its output to the agent's context; `!!command` runs it without adding the output to the agent's context. A QUEUED agent cannot be steered — it has no pane yet; wait for a concurrency slot first. An agent whose pane is gone (cleaned up) cannot be steered either, and neither can an agent being TORN DOWN — wait for its report. Every refusal states its reason and what to do about it.",
131
+ parameters: SteerBatchSchema,
132
+ execute: executeSteerAgentTool,
133
+ constrainedSampling: CONSTRAINED_SAMPLING,
134
+ };
135
+ pi.registerTool(steerAgentTool);
136
+ const cleanupAgentTool = {
137
+ name: COWBOY_TOOLS.cleanupAgent,
138
+ label: COWBOY_TOOLS.cleanupAgent,
139
+ description: "Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order — located, cleaned up, and reported with its own agent status / pane / worktree / branch block — and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed — pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result — an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort — each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal — the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) — those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result — and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",
140
+ parameters: CleanupBatchSchema,
141
+ execute: executeCleanupAgentTool,
142
+ constrainedSampling: CONSTRAINED_SAMPLING,
143
+ };
144
+ pi.registerTool(cleanupAgentTool);
145
+ pi.registerMessageRenderer("subagent-result", (message, _options, theme) => {
146
+ const content = typeof message === "object" &&
147
+ typeof message.content === "string"
148
+ ? message.content
149
+ : "";
150
+ const isError = /\b(error|stopped)\b/.test(content.slice(0, 200));
151
+ const icon = theme.fg(isError ? "error" : "success", isError ? "✗" : "✓");
152
+ return new Text(`${icon} ${content}`, 0, 0);
153
+ });
154
+ }
155
+ /**
156
+ * The model keys a spawn can be given: the session's scoped models when any are
157
+ * scoped, otherwise every model the registry offers.
158
+ */
159
+ function subagentModelOptions(ctx) {
160
+ // Empty array means no scoping. Cast through unknown: the field is
161
+ // absent from older ExtensionCommandContext typings.
162
+ const scoped = ctx.scopedModels;
163
+ return scoped?.length
164
+ ? scoped.map((s) => `${s.model.provider}/${s.model.id}`)
165
+ : ctx.modelRegistry.getAvailable().map((m) => `${m.provider}/${m.id}`);
166
+ }
167
+ /** The /cowboy command — the human surface that turns the extension back on. */
168
+ export function registerCowboyCommand(pi) {
169
+ // Named cowboy so it never clashes with other subagent extensions' /agents.
170
+ pi.registerCommand("cowboy", {
171
+ description: "Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session — opens pi's model picker.",
172
+ getArgumentCompletions: async (prefix) => (await import("./ui/menu/model-picker.js")).cowboyCompletions(prefix),
173
+ handler: async (args, ctx) => {
174
+ const subcommand = args.trim();
175
+ // The first word names the subcommand and the rest is its inline argument,
176
+ // so a tab or a run of spaces separates them exactly as one space does.
177
+ const [word, ...inline] = subcommand.split(/\s+/);
178
+ if (subcommand === "enable" || subcommand === "disable") {
179
+ const enable = subcommand === "enable";
180
+ if (isExtensionEnabled() === enable) {
181
+ ctx.ui.notify(`pi-cowboy is already ${enable ? "enabled" : "disabled"}`, "info");
182
+ return;
183
+ }
184
+ setExtensionEnabled(ctx.ui, enable);
185
+ ctx.ui.notify(enable ? "pi-cowboy enabled" : "pi-cowboy disabled", "info");
186
+ return;
187
+ }
188
+ if (word === "worktree") {
189
+ // Off, the switch is the whole menu — but a worktree is a git artifact
190
+ // that needs none of the cowboy tools, so this one still runs.
191
+ const { showWorktreeCommandMenu } = await import("./ui/menu/menu-worktree-command.js");
192
+ await showWorktreeCommandMenu(ctx, inline.join(" "));
193
+ return;
194
+ }
195
+ // Off, the switch is the whole menu: the rows these three open are
196
+ // unreachable, so the subcommands that open them are refused the same way.
197
+ const opensAHiddenRow = word === "model" || subcommand === "spawn" || subcommand === "status";
198
+ if (opensAHiddenRow && !isExtensionEnabled()) {
199
+ ctx.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.", "warning");
200
+ return;
201
+ }
202
+ if (word === "model") {
203
+ const { handleModelArg } = await import("./ui/menu/model-picker.js");
204
+ await handleModelArg(inline.join(" "), ctx);
205
+ return;
206
+ }
207
+ if (subcommand === "spawn" || subcommand === "status") {
208
+ const { showAgentsActionMenu } = await import("./ui/menu/menus.js");
209
+ await showAgentsActionMenu(ctx, subcommand, subagentModelOptions(ctx));
210
+ return;
211
+ }
212
+ if (subcommand !== "") {
213
+ ctx.ui.notify(`Unknown option "${word}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`, "warning");
214
+ return;
215
+ }
216
+ const { showAgentsMainMenu } = await import("./ui/menu/menus.js");
217
+ await showAgentsMainMenu(ctx, subagentModelOptions(ctx));
218
+ },
219
+ });
220
+ }
package/dist/shell.js ADDED
@@ -0,0 +1,225 @@
1
+ /**
2
+ * shell.ts — the single mutable container for all per-session state.
3
+ * Handler modules read via getter functions — no module-level mutable globals.
4
+ */
5
+ import * as path from "node:path";
6
+ import { RepoLock } from "./spawn/repo-lock.js";
7
+ import { resolveWorktreeMaterialization, } from "./spawn/worktree-policy.js";
8
+ import { resolveHarness } from "./agents/harness.js";
9
+ import { unprobed } from "./availability.js";
10
+ import { AgentSpawnStore } from "./agents/agent-spawn-store.js";
11
+ import { ConfigStore } from "./config/config-store.js";
12
+ import { subagentResultDir } from "./paths.js";
13
+ import { SUBAGENT_SYSTEM_FILE_NAME, SUBAGENT_TASK_FILE_NAME } from "./types.js";
14
+ const NO_SCAN_DIRS = { user: "", project: "", shared: "" };
15
+ /** Empty registries — the state every session starts from. */
16
+ export function createSessionTemplates() {
17
+ return {
18
+ agents: { agents: new Map(), scanDirs: NO_SCAN_DIRS },
19
+ orchestrators: { orchestrators: new Map(), scanDirs: NO_SCAN_DIRS },
20
+ };
21
+ }
22
+ const shell = {
23
+ // Bound by the extension factory / session_start, in that order.
24
+ pi: null,
25
+ sessionCtx: null,
26
+ manager: null,
27
+ store: new ConfigStore(),
28
+ coordinator: null,
29
+ runtime: null,
30
+ agentSpawns: new AgentSpawnStore(),
31
+ repoLock: new RepoLock(),
32
+ sessionTemplates: createSessionTemplates(),
33
+ indicatorMarker: null,
34
+ cowAvailability: unprobed(),
35
+ cowAvailabilityClaim: 0,
36
+ harnessAvailability: unprobed(),
37
+ };
38
+ export function getPiInstance() {
39
+ if (shell.pi === null) {
40
+ throw new Error("pi instance read before the extension factory bound it");
41
+ }
42
+ return shell.pi;
43
+ }
44
+ export function getSessionCtx() {
45
+ if (shell.sessionCtx === null) {
46
+ throw new Error("session context read before session_start fired");
47
+ }
48
+ return shell.sessionCtx;
49
+ }
50
+ /**
51
+ * The session's manager. A tool only runs in a session whose start bound one,
52
+ * so a read outside that window is a bug to name, not a state to branch on.
53
+ */
54
+ export function getManager() {
55
+ if (shell.manager === null) {
56
+ throw new Error("agent manager read outside a live session");
57
+ }
58
+ return shell.manager;
59
+ }
60
+ /**
61
+ * The manager when a live session has bound one — for lifecycle and menu paths
62
+ * that must degrade instead of running.
63
+ */
64
+ export function getManagerOrNull() {
65
+ return shell.manager;
66
+ }
67
+ export function getStore() {
68
+ return shell.store;
69
+ }
70
+ /**
71
+ * The mounted presence marker. It owns both its overlay handle and the poll
72
+ * keeping it current, so taking it down is its own business — this slot is only
73
+ * who is mounted.
74
+ */
75
+ export function getIndicatorMarker() {
76
+ return shell.indicatorMarker;
77
+ }
78
+ export function setIndicatorMarker(marker) {
79
+ shell.indicatorMarker = marker;
80
+ }
81
+ /**
82
+ * Deliberately never reset — not by setManager, not by shutdown — so spawns
83
+ * outlive a same-process session replacement (/new, /resume, /fork) and stay
84
+ * listed and cleanable. Rebuilt empty by a /reload, which re-imports this module.
85
+ */
86
+ export function getAgentSpawns() {
87
+ return shell.agentSpawns;
88
+ }
89
+ /**
90
+ * The session's one repository lock, shared by every worktree-creating flow so two
91
+ * spawns cannot both hold it. Deliberately never reset: a run holding it must keep
92
+ * excluding the runs queued behind it, even across a session replacement.
93
+ */
94
+ export function getRepoLock() {
95
+ return shell.repoLock;
96
+ }
97
+ /**
98
+ * The session's coordinator. A spawn only happens inside a live session, whose
99
+ * start bound one, so a read outside that window is a bug to name.
100
+ */
101
+ export function getCoordinator() {
102
+ if (shell.coordinator === null) {
103
+ throw new Error("spawn coordinator read outside a live session");
104
+ }
105
+ return shell.coordinator;
106
+ }
107
+ /**
108
+ * The coordinator when a live session has bound one — for lifecycle paths that
109
+ * must degrade instead of running.
110
+ */
111
+ export function getCoordinatorOrNull() {
112
+ return shell.coordinator;
113
+ }
114
+ /** Which materializations the worktree volume can honor; unknown until the probe lands. */
115
+ export function getCowAvailability() {
116
+ return shell.cowAvailability;
117
+ }
118
+ /**
119
+ * Open a claim for a probe that is starting. Every claim opened earlier is now
120
+ * stale, so a slower one cannot land on top of this one.
121
+ */
122
+ export function beginCowAvailabilityProbe() {
123
+ shell.cowAvailabilityClaim += 1;
124
+ return shell.cowAvailabilityClaim;
125
+ }
126
+ /** Record a verdict, but only under the current claim. Answers whether it was recorded. */
127
+ export function setCowAvailability(claim, availability) {
128
+ if (claim !== shell.cowAvailabilityClaim)
129
+ return false;
130
+ shell.cowAvailability = availability;
131
+ return true;
132
+ }
133
+ /** Which harnesses this machine can launch; unknown until the launch probe lands. */
134
+ export function getHarnessAvailability() {
135
+ return shell.harnessAvailability;
136
+ }
137
+ export function setHarnessAvailability(availability) {
138
+ shell.harnessAvailability = availability;
139
+ }
140
+ /**
141
+ * The materialization this session's spawns use: the setting, narrowed to what
142
+ * the worktree volume can actually do. Every reader goes through this, so the
143
+ * menu, the wizard and the launcher cannot disagree.
144
+ */
145
+ export function getWorktreeMaterialization() {
146
+ return resolveWorktreeMaterialization(shell.store.agent.worktreeMaterialization, shell.cowAvailability);
147
+ }
148
+ /**
149
+ * The harness this session's spawns use: the setting, narrowed to what this
150
+ * machine can launch. Every reader goes through the spawn defaults, so the menu
151
+ * and a spawn cannot disagree.
152
+ */
153
+ export function getHarnessType() {
154
+ return resolveHarness(shell.store.agent.harnessType, shell.harnessAvailability);
155
+ }
156
+ export function getRuntime() {
157
+ return shell.runtime;
158
+ }
159
+ export function getSessionTemplates() {
160
+ return shell.sessionTemplates;
161
+ }
162
+ export function setPiInstance(pi) {
163
+ shell.pi = pi;
164
+ }
165
+ export function setSessionCtx(ctx) {
166
+ shell.sessionCtx = ctx;
167
+ }
168
+ export function setManager(m) {
169
+ shell.manager = m;
170
+ }
171
+ export function setCoordinator(c) {
172
+ shell.coordinator = c;
173
+ }
174
+ export function setRuntime(r) {
175
+ shell.runtime = r;
176
+ }
177
+ /**
178
+ * Installs a session's template registries. A session start installs empty ones,
179
+ * so a session that replaced another can never read the replaced one's templates.
180
+ */
181
+ export function setSessionTemplates(next) {
182
+ shell.sessionTemplates = next;
183
+ }
184
+ /**
185
+ * Rides in the child's argv (a worktree-created pane gets no pane env, so env
186
+ * is not a reliable channel). When present, the extension stays inert so a
187
+ * subagent can never spawn further subagents.
188
+ *
189
+ * The shape is shell-inert on purpose: herdr types the launch arguments into the
190
+ * pane's shell, and `[...]` would be a glob there — zsh aborts the whole
191
+ * command line with "no matches found" before pi ever runs.
192
+ */
193
+ export function subagentTokenFor(agentId) {
194
+ return `cowboy-subagent-${agentId}`;
195
+ }
196
+ /** The token within one argv entry; the id is a spawn id or an agent name. */
197
+ const SUBAGENT_TOKEN = /cowboy-subagent-([A-Za-z0-9_-]+)/;
198
+ /** Agent id from our argv's subagent token, or undefined in a root session. */
199
+ export function detectSubagentSpawn(argv = process.argv) {
200
+ for (const arg of argv) {
201
+ const match = SUBAGENT_TOKEN.exec(arg);
202
+ if (match)
203
+ return match[1];
204
+ }
205
+ return undefined;
206
+ }
207
+ /** Canonical staging directory for a subagent id (parent and child derive the same path). */
208
+ export function subagentResultDirFor(agentId) {
209
+ return path.join(subagentResultDir(), agentId);
210
+ }
211
+ /** Canonical result.md for a subagent id. */
212
+ export function subagentResultFileFor(agentId) {
213
+ return path.join(subagentResultDirFor(agentId), "result.md");
214
+ }
215
+ /** pi reads a file from `--system-prompt` when the value names an existing path. */
216
+ export function subagentSystemFileFor(agentId) {
217
+ return path.join(subagentResultDirFor(agentId), SUBAGENT_SYSTEM_FILE_NAME);
218
+ }
219
+ /** Canonical task file for a subagent id — the `@<file>` initial message. */
220
+ export function subagentTaskFileFor(agentId) {
221
+ return path.join(subagentResultDirFor(agentId), SUBAGENT_TASK_FILE_NAME);
222
+ }
223
+ export function isInsideHerdr() {
224
+ return process.env.HERDR_ENV === "1";
225
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * cow-support.ts — finding out whether the volume worktrees land on can clone,
3
+ * and saying so as the materializations it can honor.
4
+ *
5
+ * The answer is a policy (`resolveWorktreeMaterialization` in
6
+ * `worktree-policy.ts` and the generic `selectable` in `availability.ts`); this
7
+ * module owns only how the answer is found.
8
+ *
9
+ * The session's result lives in the shell, so reading it never reaches for a
10
+ * global, and the probe runs once at launch rather than per spawn.
11
+ */
12
+ import * as fs from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import * as path from "node:path";
15
+ import { defaultCowCloneDeps, } from "../infrastructure/git/cow-clone.js";
16
+ import { defaultWorktreeRoot } from "../paths.js";
17
+ import { probed } from "../availability.js";
18
+ import { VALID_WORKTREE_MATERIALIZATIONS, } from "./worktree-policy.js";
19
+ /**
20
+ * Probe the volume the worktrees will be created on. Any failure to clone — an
21
+ * ext4 volume, a kernel without the ioctl, a `cp` without `--reflink` — is the
22
+ * same answer: this volume cannot clone, so git's classic checkout is all that is
23
+ * left to offer.
24
+ */
25
+ export async function detectCowAvailability(exec, dir) {
26
+ try {
27
+ await defaultCowCloneDeps(exec).probe(dir);
28
+ return probed(VALID_WORKTREE_MATERIALIZATIONS);
29
+ }
30
+ catch {
31
+ return probed(["checkout"]);
32
+ }
33
+ }
34
+ /**
35
+ * The nearest existing directory at or above `target`. The worktree root may not
36
+ * exist yet at launch, and only its filesystem matters to the probe.
37
+ */
38
+ export function probeTargetFor(worktreeRoot) {
39
+ let dir = path.resolve(worktreeRoot ?? defaultWorktreeRoot());
40
+ for (;;) {
41
+ try {
42
+ if (fs.statSync(dir).isDirectory())
43
+ return dir;
44
+ }
45
+ catch {
46
+ // not there yet; climb
47
+ }
48
+ const parent = path.dirname(dir);
49
+ if (parent === dir)
50
+ return tmpdir();
51
+ dir = parent;
52
+ }
53
+ }