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.
- package/LICENSE +21 -0
- package/README.md +281 -2
- package/agents/explore.toml +40 -0
- package/dist/agents/agent-assets.js +261 -0
- package/dist/agents/agent-cleanup.js +284 -0
- package/dist/agents/agent-discovery.js +108 -0
- package/dist/agents/agent-host.js +10 -0
- package/dist/agents/agent-manager.js +367 -0
- package/dist/agents/agent-reviver.js +64 -0
- package/dist/agents/agent-runner.js +288 -0
- package/dist/agents/agent-spawn-store.js +57 -0
- package/dist/agents/agent-template.js +46 -0
- package/dist/agents/agent-types.js +144 -0
- package/dist/agents/batch.js +92 -0
- package/dist/agents/cleanup-policy.js +194 -0
- package/dist/agents/cleanup-report.js +128 -0
- package/dist/agents/default-agents.js +19 -0
- package/dist/agents/harness/pi-bolt.js +15 -0
- package/dist/agents/harness/pi-compatible.js +68 -0
- package/dist/agents/harness/pig.js +16 -0
- package/dist/agents/harness/registry.js +27 -0
- package/dist/agents/harness.js +32 -0
- package/dist/agents/result-file-permissions.js +29 -0
- package/dist/agents/run-state.js +270 -0
- package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
- package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
- package/dist/agents/schemas/merge-batch.schema.js +25 -0
- package/dist/agents/schemas/steer-batch.schema.js +22 -0
- package/dist/agents/schemas/stop-batch.schema.js +18 -0
- package/dist/agents/spawn-defaults.js +70 -0
- package/dist/agents/subagent-session.js +601 -0
- package/dist/agents/tool-cleanup.js +57 -0
- package/dist/agents/tool-execution.js +125 -0
- package/dist/agents/tool-merge.js +190 -0
- package/dist/agents/tool-result.js +17 -0
- package/dist/agents/tool-steer.js +89 -0
- package/dist/agents/types.js +1 -0
- package/dist/availability.js +38 -0
- package/dist/config/config-io.js +261 -0
- package/dist/config/config-store.js +321 -0
- package/dist/config/config-validation.js +173 -0
- package/dist/config/layered-config.js +117 -0
- package/dist/config/types.js +23 -0
- package/dist/cow-support-launch.js +43 -0
- package/dist/events.js +146 -0
- package/dist/extension-toggle.js +28 -0
- package/dist/harness-availability-launch.js +23 -0
- package/dist/index.js +52 -0
- package/dist/infrastructure/exec-path.js +35 -0
- package/dist/infrastructure/git/cow-clone.js +398 -0
- package/dist/infrastructure/git/git-materializer.js +342 -0
- package/dist/infrastructure/git/git-merger.js +234 -0
- package/dist/infrastructure/git/git-retention.js +43 -0
- package/dist/infrastructure/git/git-runner.js +145 -0
- package/dist/infrastructure/git/git-worktree.js +143 -0
- package/dist/infrastructure/git/index.js +11 -0
- package/dist/infrastructure/git-client.js +11 -0
- package/dist/infrastructure/herdr/agent-stopper.js +60 -0
- package/dist/infrastructure/herdr/agents.js +329 -0
- package/dist/infrastructure/herdr/herdr-client.js +36 -0
- package/dist/infrastructure/herdr/herdr-transport.js +158 -0
- package/dist/infrastructure/herdr/index.js +15 -0
- package/dist/infrastructure/herdr/panes.js +174 -0
- package/dist/infrastructure/herdr/polling.js +44 -0
- package/dist/infrastructure/herdr/worktrees.js +76 -0
- package/dist/infrastructure/herdr-client.js +6 -0
- package/dist/infrastructure/herdr-host.js +163 -0
- package/dist/logger.js +79 -0
- package/dist/models/model-groups.js +72 -0
- package/dist/models/model-precedence.js +50 -0
- package/dist/models/model-request.js +108 -0
- package/dist/orchestrators/briefing-section.js +14 -0
- package/dist/orchestrators/context.js +116 -0
- package/dist/orchestrators/cues.js +90 -0
- package/dist/orchestrators/default-orchestrators.js +36 -0
- package/dist/orchestrators/orchestrator-discovery.js +68 -0
- package/dist/orchestrators/orchestrator-template.js +43 -0
- package/dist/orchestrators/orchestrator-types.js +78 -0
- package/dist/orchestrators/protocol.js +292 -0
- package/dist/orchestrators/types.js +7 -0
- package/dist/paths.js +66 -0
- package/dist/pi-settings.js +7 -0
- package/dist/predicates.js +25 -0
- package/dist/prompt/prompts.js +110 -0
- package/dist/prompt/skill-loader.js +153 -0
- package/dist/prompt/subagent-system-prompt.js +173 -0
- package/dist/registration.js +220 -0
- package/dist/shell.js +225 -0
- package/dist/spawn/cow-support.js +53 -0
- package/dist/spawn/herdr-launcher.js +80 -0
- package/dist/spawn/repo-lock.js +34 -0
- package/dist/spawn/sandbox.js +286 -0
- package/dist/spawn/spawn-coordinator.js +255 -0
- package/dist/spawn/spawn-id.js +39 -0
- package/dist/spawn/worktree-policy.js +137 -0
- package/dist/status-note.js +30 -0
- package/dist/subagent/ipc-protocol.js +68 -0
- package/dist/subagent/ipc.js +110 -0
- package/dist/subagent/pane-supervisor.js +24 -0
- package/dist/subagent/socket-ipc.js +240 -0
- package/dist/subagent/supervisor.js +315 -0
- package/dist/task-registry.js +258 -0
- package/dist/templates/template-files.js +84 -0
- package/dist/types.js +84 -0
- package/dist/ui/action-report.js +21 -0
- package/dist/ui/format.js +47 -0
- package/dist/ui/indicator.js +480 -0
- package/dist/ui/menu/helpers.js +227 -0
- package/dist/ui/menu/menu-agent-settings.js +182 -0
- package/dist/ui/menu/menu-agent-status.js +444 -0
- package/dist/ui/menu/menu-concurrency.js +226 -0
- package/dist/ui/menu/menu-model-settings.js +244 -0
- package/dist/ui/menu/menu-spawn-defaults.js +71 -0
- package/dist/ui/menu/menu-spawn-wizard.js +367 -0
- package/dist/ui/menu/menu-spawn-worktree.js +107 -0
- package/dist/ui/menu/menu-system-prompt.js +104 -0
- package/dist/ui/menu/menu-worktree-command.js +150 -0
- package/dist/ui/menu/menus.js +187 -0
- package/dist/ui/menu/model-picker.js +160 -0
- package/dist/ui/menu/screen-host.js +87 -0
- package/dist/ui/menu/submenus/confirm.js +23 -0
- package/dist/ui/menu/submenus/model-select.js +42 -0
- package/dist/ui/menu/submenus/name-field.js +43 -0
- package/dist/ui/menu/submenus/numeric-input.js +61 -0
- package/dist/ui/menu/submenus/target-select.js +129 -0
- package/dist/ui/menu/submenus/text-editor.js +49 -0
- package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
- package/dist/ui/menu/submenus/worktree-name.js +53 -0
- package/dist/ui/menu/wrappers/settings-list.js +101 -0
- package/dist/ui/searchable-select.js +147 -0
- package/dist/ui/types.js +1 -0
- package/dist/utils.js +70 -0
- package/docs/assets/grazing.png +0 -0
- package/docs/assets/herdr-containers.png +0 -0
- package/docs/assets/logo-transparent.png +0 -0
- package/orchestrators/with-code-review.toml +20 -0
- package/package.json +109 -3
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-runner.ts — Launch-plan building for herdr-pane subagents.
|
|
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
|
|
7
|
+
* discovery and tool validation.
|
|
8
|
+
*/
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { errorMessage } from "../utils.js";
|
|
13
|
+
import { agentDir } from "../paths.js";
|
|
14
|
+
import { getStore, subagentResultDirFor, subagentResultFileFor, subagentSystemFileFor, subagentTaskFileFor, subagentTokenFor, } from "../shell.js";
|
|
15
|
+
import { buildSubagentSystemPrompt, buildWorktreeBranchSection, } from "../prompt/subagent-system-prompt.js";
|
|
16
|
+
import { getAgentConfig, getConfig, } from "./agent-types.js";
|
|
17
|
+
import { ensureResultDir, writeResultFile } from "./result-file-permissions.js";
|
|
18
|
+
import { resolveHarnessType } from "./spawn-defaults.js";
|
|
19
|
+
// Re-exported for consumers importing it from this module.
|
|
20
|
+
export { buildWorktreeBranchSection };
|
|
21
|
+
function resolveSkillMode(skills, agentConfig) {
|
|
22
|
+
// An empty inlined list inlines nothing, so it must not suppress pi's own
|
|
23
|
+
// skills. The length test, not an isArray test, is what keeps that true.
|
|
24
|
+
const inlinedSkills = agentConfig?.inlinedSkills ?? [];
|
|
25
|
+
const extensionDecidesSkills = skills === false || Array.isArray(skills) || inlinedSkills.length > 0;
|
|
26
|
+
return extensionDecidesSkills ? { kind: "none" } : { kind: "default" };
|
|
27
|
+
}
|
|
28
|
+
/** Reads only SettingsManager configuration — never loads, crawls, or inspects extensions; the child pi owns that. */
|
|
29
|
+
function resolveExtensionSources(entries, settings, cwd) {
|
|
30
|
+
const sources = new Map();
|
|
31
|
+
const addSource = (name, source) => {
|
|
32
|
+
const key = name.toLowerCase();
|
|
33
|
+
const previous = sources.get(key);
|
|
34
|
+
if (previous === undefined)
|
|
35
|
+
sources.set(key, source);
|
|
36
|
+
else if (previous !== source)
|
|
37
|
+
sources.set(key, null);
|
|
38
|
+
};
|
|
39
|
+
for (const packageEntry of settings.packages) {
|
|
40
|
+
const source = typeof packageEntry === "string" ? packageEntry : packageEntry.source;
|
|
41
|
+
const name = extensionSourceName(source);
|
|
42
|
+
if (name)
|
|
43
|
+
addSource(name, source);
|
|
44
|
+
}
|
|
45
|
+
for (const extensionPath of settings.extensionPaths) {
|
|
46
|
+
const name = extensionSourceName(extensionPath);
|
|
47
|
+
if (name)
|
|
48
|
+
addSource(name, extensionPath);
|
|
49
|
+
}
|
|
50
|
+
return entries.map((entry) => {
|
|
51
|
+
if (isPiExtensionSource(entry))
|
|
52
|
+
return entry;
|
|
53
|
+
if (isExistingPath(entry, cwd))
|
|
54
|
+
return entry;
|
|
55
|
+
const name = extensionEntryName(entry);
|
|
56
|
+
const source = sources.get(name.toLowerCase());
|
|
57
|
+
if (source === null) {
|
|
58
|
+
throw new Error(`Extension entry "${entry}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);
|
|
59
|
+
}
|
|
60
|
+
if (source === undefined) {
|
|
61
|
+
throw new Error(`Extension entry "${entry}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);
|
|
62
|
+
}
|
|
63
|
+
return source;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function isPiExtensionSource(value) {
|
|
67
|
+
return value.startsWith("npm:") || value.startsWith("git:");
|
|
68
|
+
}
|
|
69
|
+
function isExistingPath(value, cwd) {
|
|
70
|
+
if (path.isAbsolute(value))
|
|
71
|
+
return fs.existsSync(value);
|
|
72
|
+
return fs.existsSync(path.resolve(cwd, value));
|
|
73
|
+
}
|
|
74
|
+
function extensionEntryName(value) {
|
|
75
|
+
const slashIndex = value.indexOf("/");
|
|
76
|
+
return (slashIndex === -1 ? value : value.slice(0, slashIndex)).toLowerCase();
|
|
77
|
+
}
|
|
78
|
+
function extensionSourceName(source) {
|
|
79
|
+
const withoutFragment = source.split("#", 1)[0].replace(/[\\/]$/, "");
|
|
80
|
+
if (!withoutFragment)
|
|
81
|
+
return undefined;
|
|
82
|
+
if (withoutFragment.startsWith("npm:")) {
|
|
83
|
+
const packageSpec = withoutFragment.slice("npm:".length);
|
|
84
|
+
const packageName = packageSpec.startsWith("@")
|
|
85
|
+
? packageSpec.split("/", 2).at(1)?.split("@", 1)[0]
|
|
86
|
+
: packageSpec.split("@", 1)[0];
|
|
87
|
+
return packageName?.toLowerCase();
|
|
88
|
+
}
|
|
89
|
+
const sourcePath = withoutFragment.startsWith("git:")
|
|
90
|
+
? withoutFragment.slice("git:".length)
|
|
91
|
+
: withoutFragment;
|
|
92
|
+
const base = path.basename(sourcePath);
|
|
93
|
+
const name = path.basename(base, path.extname(base));
|
|
94
|
+
if (name === "index") {
|
|
95
|
+
const parent = path.basename(path.dirname(sourcePath));
|
|
96
|
+
return parent || undefined;
|
|
97
|
+
}
|
|
98
|
+
return name || undefined;
|
|
99
|
+
}
|
|
100
|
+
function notifyLaunchConfigurationError(ctx, message) {
|
|
101
|
+
ctx.ui.notify(`[cowboy] ${message}`, "error");
|
|
102
|
+
throw new Error(message);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The parent session's persisted file, when the runtime has one. `--fork`
|
|
106
|
+
* needs a real path, so an ephemeral (`--no-session`) session has nothing to
|
|
107
|
+
* fork; absence is reported rather than passed through as an empty argument.
|
|
108
|
+
*/
|
|
109
|
+
function resolveParentSessionFile(ctx) {
|
|
110
|
+
const source = ctx;
|
|
111
|
+
const candidate = source.sessionFile ?? source.sessionManager?.getSessionFile?.();
|
|
112
|
+
if (!candidate)
|
|
113
|
+
return undefined;
|
|
114
|
+
return candidate;
|
|
115
|
+
}
|
|
116
|
+
function resolveToolCliEntries(entries, optionName) {
|
|
117
|
+
const resolved = new Set();
|
|
118
|
+
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.
|
|
121
|
+
if (!entry) {
|
|
122
|
+
throw new Error(`Empty entry in ${optionName} is not supported`);
|
|
123
|
+
}
|
|
124
|
+
resolved.add(entry);
|
|
125
|
+
}
|
|
126
|
+
return [...resolved];
|
|
127
|
+
}
|
|
128
|
+
/** The child pi owns extension discovery and tool validation; this only forwards configuration. */
|
|
129
|
+
export async function buildLaunchPlan(pi, ctx, type, prompt, options) {
|
|
130
|
+
const store = getStore();
|
|
131
|
+
const effectiveCwd = options.cwd ?? ctx.cwd;
|
|
132
|
+
const config = getConfig(type, store.agent.loadSkillsImplicitly, store.agent.loadExtensionsImplicitly);
|
|
133
|
+
const agentConfig = getAgentConfig(type);
|
|
134
|
+
const harnessType = resolveHarnessType(type);
|
|
135
|
+
const skillMode = resolveSkillMode(config.skills, agentConfig);
|
|
136
|
+
const warnings = [];
|
|
137
|
+
const bufferNotify = (msg) => {
|
|
138
|
+
warnings.push(msg);
|
|
139
|
+
};
|
|
140
|
+
let extMode = { kind: "default" };
|
|
141
|
+
if (config.extensions === false) {
|
|
142
|
+
extMode = { kind: "none" };
|
|
143
|
+
}
|
|
144
|
+
else if (Array.isArray(config.extensions)) {
|
|
145
|
+
if (config.extensions.length === 0) {
|
|
146
|
+
extMode = { kind: "none" };
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
try {
|
|
150
|
+
const settingsManager = SettingsManager.create(effectiveCwd, agentDir(), { projectTrusted: options.projectTrusted !== false });
|
|
151
|
+
extMode = {
|
|
152
|
+
kind: "paths",
|
|
153
|
+
paths: resolveExtensionSources(config.extensions, {
|
|
154
|
+
packages: settingsManager.getPackages(),
|
|
155
|
+
extensionPaths: settingsManager.getExtensionPaths(),
|
|
156
|
+
}, effectiveCwd),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
161
|
+
notifyLaunchConfigurationError(ctx, message);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
let toolMode;
|
|
166
|
+
try {
|
|
167
|
+
if (agentConfig?.tools === false) {
|
|
168
|
+
toolMode = { kind: "none" };
|
|
169
|
+
}
|
|
170
|
+
else if (Array.isArray(agentConfig?.tools)) {
|
|
171
|
+
toolMode = {
|
|
172
|
+
kind: "include",
|
|
173
|
+
names: resolveToolCliEntries(agentConfig.tools, "tools"),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
else if (agentConfig?.excludeTools?.length) {
|
|
177
|
+
toolMode = {
|
|
178
|
+
kind: "exclude",
|
|
179
|
+
names: resolveToolCliEntries(agentConfig.excludeTools, "excludeTools"),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
185
|
+
notifyLaunchConfigurationError(ctx, message);
|
|
186
|
+
}
|
|
187
|
+
// Neither payload crosses argv as content: herdr's `agent start` encodes
|
|
188
|
+
// argv into the pane shell command and rejects control characters, so the
|
|
189
|
+
// prompt rides as `--system-prompt <system.md>` and the task as `@<prompt.md>`.
|
|
190
|
+
const agentId = options.agentId ?? "unknown";
|
|
191
|
+
const resultDir = subagentResultDirFor(agentId);
|
|
192
|
+
// Owner-only staging: these files may carry secrets; throws, never caught here.
|
|
193
|
+
ensureResultDir(resultDir);
|
|
194
|
+
const resultFile = subagentResultFileFor(agentId);
|
|
195
|
+
const systemFile = subagentSystemFileFor(agentId);
|
|
196
|
+
const taskFile = subagentTaskFileFor(agentId);
|
|
197
|
+
const systemPrompt = await buildSubagentSystemPrompt({
|
|
198
|
+
pi,
|
|
199
|
+
ctx,
|
|
200
|
+
type,
|
|
201
|
+
agentConfig,
|
|
202
|
+
config,
|
|
203
|
+
cwd: effectiveCwd,
|
|
204
|
+
globalSystemPromptMode: store.agent.systemPromptMode,
|
|
205
|
+
globalIncludeContextFiles: store.agent.includeContextFiles,
|
|
206
|
+
worktreePath: options.worktree?.path,
|
|
207
|
+
expectedBranch: options.worktree?.branch,
|
|
208
|
+
agentGuidance: options.agentGuidance,
|
|
209
|
+
resultFile,
|
|
210
|
+
notify: bufferNotify,
|
|
211
|
+
});
|
|
212
|
+
try {
|
|
213
|
+
writeResultFile(systemFile, systemPrompt);
|
|
214
|
+
}
|
|
215
|
+
catch (err) {
|
|
216
|
+
throw new Error(`cannot write the system prompt file ${systemFile}: ${errorMessage(err)}. The agent did not start.`, { cause: err });
|
|
217
|
+
}
|
|
218
|
+
// pi falls back to literal prompt text when --system-prompt names no
|
|
219
|
+
// existing path — that would silently launch with no instructions.
|
|
220
|
+
if (!fs.existsSync(systemFile)) {
|
|
221
|
+
throw new Error(`the system prompt file is missing after the write: ${systemFile}. The agent did not start.`);
|
|
222
|
+
}
|
|
223
|
+
// Throws on failure: a launch without its task file must not proceed.
|
|
224
|
+
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
|
+
}
|
|
271
|
+
}
|
|
272
|
+
piArgs.push(options.projectTrusted === false ? "--no-approve" : "--approve");
|
|
273
|
+
for (const msg of warnings) {
|
|
274
|
+
ctx.ui.notify(`[cowboy] ${msg}`, "warning");
|
|
275
|
+
}
|
|
276
|
+
const modelKey = options.modelSelection?.key;
|
|
277
|
+
return {
|
|
278
|
+
name: agentId,
|
|
279
|
+
cwd: effectiveCwd,
|
|
280
|
+
systemPrompt,
|
|
281
|
+
systemPromptFile: systemFile,
|
|
282
|
+
initialMessage: `@${taskFile}`,
|
|
283
|
+
piArgs,
|
|
284
|
+
resultFile,
|
|
285
|
+
modelKey,
|
|
286
|
+
harness: harnessType,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-spawn-store.ts — Shell-owned canonical AgentSpawn store.
|
|
3
|
+
* Exports AgentSpawnStore, SpawnIdCollisionError.
|
|
4
|
+
*
|
|
5
|
+
* The manager is per-session, so spawns live here in the shell: a spawn
|
|
6
|
+
* outlives its session and stays visible and cleanable. A `/reload`
|
|
7
|
+
* re-imports the extension and rebuilds this store empty. No I/O or
|
|
8
|
+
* lifecycle logic; the only scoping is the lifecycle phase, on request.
|
|
9
|
+
*/
|
|
10
|
+
import { ALL_AGENT_PHASES } from "../types.js";
|
|
11
|
+
import { generateSpawnId, generateUniqueSpawnId } from "../spawn/spawn-id.js";
|
|
12
|
+
/**
|
|
13
|
+
* Thrown when `add` gets an id the store already owns. Overwriting would
|
|
14
|
+
* destroy the live spawn and the stop/cleanup/steer execution it carries, so
|
|
15
|
+
* the original is left untouched.
|
|
16
|
+
*/
|
|
17
|
+
export class SpawnIdCollisionError extends Error {
|
|
18
|
+
spawnId;
|
|
19
|
+
constructor(spawnId) {
|
|
20
|
+
super(`Spawn id ${spawnId} is already registered — an id belongs to exactly one spawn from creation until its explicit drop.`);
|
|
21
|
+
this.name = "SpawnIdCollisionError";
|
|
22
|
+
this.spawnId = spawnId;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Process-lifetime spawn retention by id; drops only on explicit drop. */
|
|
26
|
+
export class AgentSpawnStore {
|
|
27
|
+
spawns = new Map();
|
|
28
|
+
/**
|
|
29
|
+
* Register a spawn at creation. A duplicate id throws and leaves the
|
|
30
|
+
* original untouched; callers mint through `mint()`, so a collision is a bug.
|
|
31
|
+
*/
|
|
32
|
+
add(spawn) {
|
|
33
|
+
if (this.spawns.has(spawn.id)) {
|
|
34
|
+
throw new SpawnIdCollisionError(spawn.id);
|
|
35
|
+
}
|
|
36
|
+
this.spawns.set(spawn.id, spawn);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Mint an id no registered spawn holds, settled ones included: a retained
|
|
40
|
+
* spawn still owns its id. `mint` is injectable so collisions are testable.
|
|
41
|
+
*/
|
|
42
|
+
mint(mint = generateSpawnId) {
|
|
43
|
+
return generateUniqueSpawnId((id) => this.spawns.has(id), mint);
|
|
44
|
+
}
|
|
45
|
+
/** Look one spawn up by id, never phase-filtered. */
|
|
46
|
+
get(id) {
|
|
47
|
+
return this.spawns.get(id);
|
|
48
|
+
}
|
|
49
|
+
/** Drop a spawn once its resources are gone (cleanup success, Clear). */
|
|
50
|
+
drop(id) {
|
|
51
|
+
this.spawns.delete(id);
|
|
52
|
+
}
|
|
53
|
+
/** Spawns in the given phases (default: all), in insertion order. */
|
|
54
|
+
list(phases = ALL_AGENT_PHASES) {
|
|
55
|
+
return [...this.spawns.values()].filter((spawn) => phases.includes(spawn.lifecycle.phase));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-template.ts — The Zod schema for one agent template file.
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for the `.toml` format: snake_case keys, values
|
|
5
|
+
* typed exactly as written, unknown keys rejected so typos fail at load.
|
|
6
|
+
* The type derives via `z.infer`.
|
|
7
|
+
*/
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { VALID_THINKING_LEVELS } from "../utils.js";
|
|
10
|
+
import { VALID_WORKTREE_CHECKOUT_TYPES } from "../spawn/worktree-policy.js";
|
|
11
|
+
import { HARNESS_IDS } from "./harness.js";
|
|
12
|
+
const filterList = z.union([z.boolean(), z.array(z.string())]);
|
|
13
|
+
/**
|
|
14
|
+
* The `[harness]` table: These describe the child process,
|
|
15
|
+
* not the agent's identity or its worktree.
|
|
16
|
+
*/
|
|
17
|
+
const HarnessSchema = z.strictObject({
|
|
18
|
+
model: z.string().optional(),
|
|
19
|
+
thinking: z.enum(VALID_THINKING_LEVELS).optional(),
|
|
20
|
+
tools: z.array(z.string()).optional(),
|
|
21
|
+
exclude_tools: z.array(z.string()).optional(),
|
|
22
|
+
extensions: filterList.optional(),
|
|
23
|
+
skills: filterList.optional(),
|
|
24
|
+
/** 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
|
+
inlined_skills: z.array(z.string()).optional(),
|
|
26
|
+
/** Fork the parent session into the subagent (`pi --fork <sessionFile>`). */
|
|
27
|
+
fork: z.boolean().optional(),
|
|
28
|
+
/** Whether the child's system prompt carries the repo's AGENTS.md context files. */
|
|
29
|
+
include_context_files: z.boolean().optional(),
|
|
30
|
+
});
|
|
31
|
+
export const AgentTemplateSchema = z.strictObject({
|
|
32
|
+
name: z.string().optional(),
|
|
33
|
+
display_name: z.string().optional(),
|
|
34
|
+
description: z.string().optional(),
|
|
35
|
+
// Absent by design: `max_turns` and `max_tokens` would imply a limit nothing
|
|
36
|
+
// enforces, and `output_transcript` would name an output file nothing writes.
|
|
37
|
+
hidden: z.boolean().optional(),
|
|
38
|
+
/** Whether this agent's worktree carries a dirty parent's WIP. */
|
|
39
|
+
worktree_checkout_type: z.enum(VALID_WORKTREE_CHECKOUT_TYPES).optional(),
|
|
40
|
+
/** Absent falls through the merge to inherit an earlier layer's prompt; an explicitly empty string clears it. */
|
|
41
|
+
system_prompt: z.string().optional(),
|
|
42
|
+
/** Which harness owns this agent's launch; omitted falls through to the configured default. */
|
|
43
|
+
harness_type: z.enum(HARNESS_IDS).optional(),
|
|
44
|
+
/** How the child process is launched. Omitted = every field's default. */
|
|
45
|
+
harness: HarnessSchema.optional(),
|
|
46
|
+
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-types.ts — Unified agent type registry.
|
|
3
|
+
*
|
|
4
|
+
* Precedence: default < extension < user < shared < project. Hidden agents
|
|
5
|
+
* stay registered but are excluded from spawning.
|
|
6
|
+
*
|
|
7
|
+
* The registry is session state; it lives in the shell and is read and written
|
|
8
|
+
* here through the shell getters.
|
|
9
|
+
*/
|
|
10
|
+
import { EXTENSION_AGENTS_DIR } from "../paths.js";
|
|
11
|
+
import { getSessionTemplates } from "../shell.js";
|
|
12
|
+
import { scanAgentFilesInDir, mergeAgents, } from "./agent-discovery.js";
|
|
13
|
+
import { DEFAULT_AGENTS } from "./default-agents.js";
|
|
14
|
+
function registry() {
|
|
15
|
+
return getSessionTemplates().agents;
|
|
16
|
+
}
|
|
17
|
+
export function registerAgents(userAgents, options) {
|
|
18
|
+
const agents = new Map();
|
|
19
|
+
if (!options?.disableDefaultAgents) {
|
|
20
|
+
for (const [name, config] of DEFAULT_AGENTS) {
|
|
21
|
+
agents.set(name, config);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
for (const [name, config] of userAgents) {
|
|
25
|
+
agents.set(name, config);
|
|
26
|
+
}
|
|
27
|
+
registry().agents = agents;
|
|
28
|
+
}
|
|
29
|
+
export function setAgentScanDirs(userDir, projectDir, sharedDir) {
|
|
30
|
+
registry().scanDirs = {
|
|
31
|
+
user: userDir,
|
|
32
|
+
project: projectDir,
|
|
33
|
+
shared: sharedDir ?? "",
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export async function scanAndMerge(options) {
|
|
37
|
+
const disableDefaults = options?.disableDefaultAgents === true;
|
|
38
|
+
const notify = options?.notify;
|
|
39
|
+
const scanDirs = registry().scanDirs;
|
|
40
|
+
const [extensionAgents, userAgents, sharedAgents, projectAgents] = await Promise.all([
|
|
41
|
+
disableDefaults
|
|
42
|
+
? Promise.resolve([])
|
|
43
|
+
: scanAgentFilesInDir(EXTENSION_AGENTS_DIR, notify),
|
|
44
|
+
scanAgentFilesInDir(scanDirs.user, notify),
|
|
45
|
+
scanAgentFilesInDir(scanDirs.shared, notify),
|
|
46
|
+
scanAgentFilesInDir(scanDirs.project, notify),
|
|
47
|
+
]);
|
|
48
|
+
const defaults = disableDefaults
|
|
49
|
+
? new Map()
|
|
50
|
+
: DEFAULT_AGENTS;
|
|
51
|
+
// First override layer, so default < extension < user < shared < project.
|
|
52
|
+
const withExtension = mergeAgents(defaults, extensionAgents, [], []);
|
|
53
|
+
return mergeAgents(withExtension, userAgents, sharedAgents, projectAgents);
|
|
54
|
+
}
|
|
55
|
+
/** Worktree agents follow the parent project's uniqueness rules. */
|
|
56
|
+
export async function discoverNewAgents(worktreeDir, options) {
|
|
57
|
+
const merged = await scanAndMerge(options);
|
|
58
|
+
const { agents } = registry();
|
|
59
|
+
let count = 0;
|
|
60
|
+
for (const [name, config] of merged) {
|
|
61
|
+
if (!agents.has(name)) {
|
|
62
|
+
agents.set(name, config);
|
|
63
|
+
count++;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (worktreeDir) {
|
|
67
|
+
const worktreeAgents = await scanAgentFilesInDir(worktreeDir, options?.notify);
|
|
68
|
+
const wtMerged = mergeAgents(new Map(), [], [], worktreeAgents);
|
|
69
|
+
for (const [name, config] of wtMerged) {
|
|
70
|
+
if (!agents.has(name)) {
|
|
71
|
+
agents.set(name, config);
|
|
72
|
+
count++;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return count;
|
|
77
|
+
}
|
|
78
|
+
export function resolveType(name) {
|
|
79
|
+
const { agents } = registry();
|
|
80
|
+
if (!name)
|
|
81
|
+
return { kind: "not-found" };
|
|
82
|
+
if (agents.has(name))
|
|
83
|
+
return { kind: "resolved", key: name };
|
|
84
|
+
const lower = name.toLowerCase();
|
|
85
|
+
const candidates = [];
|
|
86
|
+
for (const key of agents.keys()) {
|
|
87
|
+
if (key.toLowerCase() === lower)
|
|
88
|
+
candidates.push(key);
|
|
89
|
+
}
|
|
90
|
+
if (candidates.length === 1)
|
|
91
|
+
return { kind: "resolved", key: candidates[0] };
|
|
92
|
+
if (candidates.length > 1)
|
|
93
|
+
return { kind: "ambiguous", candidates };
|
|
94
|
+
return { kind: "not-found" };
|
|
95
|
+
}
|
|
96
|
+
/** Resolve a type, discovering from worktreeDir on miss. Trust/validation checks stay in the caller. */
|
|
97
|
+
export async function resolveTypeOrDiscover(type, worktreeDir, notify) {
|
|
98
|
+
let resolution = resolveType(type);
|
|
99
|
+
if (resolution.kind === "not-found") {
|
|
100
|
+
await discoverNewAgents(worktreeDir, { notify });
|
|
101
|
+
resolution = resolveType(type);
|
|
102
|
+
}
|
|
103
|
+
return resolution;
|
|
104
|
+
}
|
|
105
|
+
export function getAgentConfig(name) {
|
|
106
|
+
const resolution = resolveType(name);
|
|
107
|
+
return resolution.kind === "resolved"
|
|
108
|
+
? registry().agents.get(resolution.key)
|
|
109
|
+
: undefined;
|
|
110
|
+
}
|
|
111
|
+
export function getAvailableTypes() {
|
|
112
|
+
return [...registry().agents.entries()]
|
|
113
|
+
.filter(([_, config]) => config.hidden !== true)
|
|
114
|
+
.map(([name]) => name);
|
|
115
|
+
}
|
|
116
|
+
export function getAllTypes() {
|
|
117
|
+
return [...registry().agents.keys()];
|
|
118
|
+
}
|
|
119
|
+
/** undefined means "not explicitly set" → resolve from the global default. */
|
|
120
|
+
function applyGlobalDefaults(skills, extensions, loadSkillsImplicitly, loadExtensionsImplicitly) {
|
|
121
|
+
return {
|
|
122
|
+
skills: skills ?? loadSkillsImplicitly,
|
|
123
|
+
extensions: extensions ?? loadExtensionsImplicitly,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
export function getConfig(type, loadSkillsImplicitly = true, loadExtensionsImplicitly = true) {
|
|
127
|
+
const config = getAgentConfig(type);
|
|
128
|
+
if (config) {
|
|
129
|
+
const { skills, extensions, ...rest } = config;
|
|
130
|
+
const defaults = applyGlobalDefaults(skills, extensions, loadSkillsImplicitly, loadExtensionsImplicitly);
|
|
131
|
+
return {
|
|
132
|
+
displayName: rest.displayName ?? rest.name,
|
|
133
|
+
description: rest.description,
|
|
134
|
+
tools: rest.tools,
|
|
135
|
+
...defaults,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const defaults = applyGlobalDefaults(undefined, undefined, loadSkillsImplicitly, loadExtensionsImplicitly);
|
|
139
|
+
return {
|
|
140
|
+
displayName: "Agent",
|
|
141
|
+
description: "General-purpose agent for complex, multi-step tasks",
|
|
142
|
+
...defaults,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* batch.ts — the batch pipeline every Cowboy batch tool runs.
|
|
3
|
+
*
|
|
4
|
+
* A batch tool handles one or more items of the same kind, and the sequence is
|
|
5
|
+
* the same for all of them: reject a repeated key before touching anything, run
|
|
6
|
+
* the tool's remaining whole-call guards, handle the items one at a time in
|
|
7
|
+
* input order, and return one text block per item next to the per-item
|
|
8
|
+
* outcomes. A tool supplies only its own parts — which parameter it walks, the
|
|
9
|
+
* per-item work, and the rule for a halted batch.
|
|
10
|
+
*/
|
|
11
|
+
import { successResult } from "./tool-result.js";
|
|
12
|
+
/** Between the per-item blocks of a batch result: one batch reads as one document of item blocks. */
|
|
13
|
+
export const BATCH_ITEM_SEPARATOR = "\n\n---\n\n";
|
|
14
|
+
/** How an item is named in the duplicate-key error; a tool names its parameter, never its grammar. */
|
|
15
|
+
const ITEM_NOUNS = {
|
|
16
|
+
agent_ids: { plural: "agent ids" },
|
|
17
|
+
branches: { plural: "branches" },
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Runs one batch: the duplicate-key guard, the tool's remaining guards, then
|
|
21
|
+
* the items sequentially in input order. Each item contributes exactly one
|
|
22
|
+
* outcome and one text block, so `details` and the text always line up.
|
|
23
|
+
*/
|
|
24
|
+
export async function runBatch(spec) {
|
|
25
|
+
const { items } = spec;
|
|
26
|
+
rejectRepeatedKeys(items, spec);
|
|
27
|
+
await spec.prepare?.();
|
|
28
|
+
const steps = batchSteps(spec);
|
|
29
|
+
const outcomes = [];
|
|
30
|
+
const blocks = [];
|
|
31
|
+
const record = ({ outcome, text }) => {
|
|
32
|
+
outcomes.push(outcome);
|
|
33
|
+
blocks.push(text);
|
|
34
|
+
};
|
|
35
|
+
let haltedBy;
|
|
36
|
+
for (const item of items) {
|
|
37
|
+
const halt = steps.halt;
|
|
38
|
+
if (halt !== undefined && haltedBy !== undefined) {
|
|
39
|
+
record(halt.skip(item, haltedBy));
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const handled = await steps.handle(item);
|
|
43
|
+
record(handled);
|
|
44
|
+
if (halt !== undefined && halt.halts(handled.outcome))
|
|
45
|
+
haltedBy = item;
|
|
46
|
+
}
|
|
47
|
+
return successResult(blocks.join(BATCH_ITEM_SEPARATOR), {
|
|
48
|
+
[spec.detailsKey]: outcomes,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** Flattens a tool's handler into the pair form the loop reads, rendering from the outcome where the tool asked for that. */
|
|
52
|
+
function batchSteps(spec) {
|
|
53
|
+
if ("render" in spec) {
|
|
54
|
+
const render = spec.render;
|
|
55
|
+
const halt = spec.halt;
|
|
56
|
+
return {
|
|
57
|
+
handle: async (item) => {
|
|
58
|
+
const outcome = await spec.handleItem(item);
|
|
59
|
+
return { outcome, text: render(outcome) };
|
|
60
|
+
},
|
|
61
|
+
halt: halt === undefined
|
|
62
|
+
? undefined
|
|
63
|
+
: {
|
|
64
|
+
halts: (outcome) => halt.on(outcome),
|
|
65
|
+
skip: (item, haltedBy) => {
|
|
66
|
+
const outcome = halt.skip(item, haltedBy);
|
|
67
|
+
return { outcome, text: render(outcome) };
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const halt = spec.halt;
|
|
73
|
+
return {
|
|
74
|
+
handle: spec.handleItem,
|
|
75
|
+
halt: halt === undefined
|
|
76
|
+
? undefined
|
|
77
|
+
: { halts: (o) => halt.on(o), skip: halt.skip },
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A key passed twice throws before the batch touches anything, so no item is ever half-handled.
|
|
82
|
+
* Compared trimmed, because every tool's handler trims the item before acting on it — two spellings
|
|
83
|
+
* of one key are one repeated key, not two distinct ones.
|
|
84
|
+
*/
|
|
85
|
+
function rejectRepeatedKeys(keys, { toolName, param }) {
|
|
86
|
+
const canonical = keys.map((key) => key.trim());
|
|
87
|
+
const repeated = canonical.filter((key, index) => canonical.indexOf(key) !== index);
|
|
88
|
+
if (repeated.length === 0)
|
|
89
|
+
return;
|
|
90
|
+
const noun = ITEM_NOUNS[param];
|
|
91
|
+
throw new Error(`${toolName} received duplicate ${noun.plural} in \`${param}\`: ${[...new Set(repeated)].join(", ")}. No item was handled.`);
|
|
92
|
+
}
|