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,292 @@
1
+ /**
2
+ * protocol.ts — the delegation dialogue layer: intent parsing, the turn
3
+ * (sandbox → spawn), and the spawned/queued/settled cues.
4
+ *
5
+ * Nothing happens before validation: `parse` resolves agent type,
6
+ * orchestrator, and model (credential probe included) and can throw BEFORE
7
+ * the turn provisions a sandbox — an unusable model never leaves a checkout
8
+ * behind, and a duplicate task name is rejected with the existing attempt
9
+ * left spawned. Every turn returns a dual payload — prose `message` plus
10
+ * structured `details` — produced together, so one never ships without the
11
+ * other. Shell getters are read at call time, never cached.
12
+ */
13
+ import { ACTIVE_AGENT_PHASES, hasOutcome, isActivePhase, lifecycleStartTime, lifecycleStatus, } from "../types.js";
14
+ import { BATCH_ITEM_SEPARATOR } from "../agents/batch.js";
15
+ import { getStatusNote } from "../status-note.js";
16
+ import { buildTaskSlug, buildWorktreeBranch, buildWorktreePath, resolveWorktreeRoot, } from "../spawn/worktree-policy.js";
17
+ import { formatRetentionClause, resolveMainCheckout, } from "../infrastructure/git-client.js";
18
+ import { getAgentConfig, resolveTypeOrDiscover, } from "../agents/agent-types.js";
19
+ import { resolveAgentTypeParam, resolveDefaultOrchestrator, } from "../agents/spawn-defaults.js";
20
+ import { readModelRequest, resolveModelRequest, } from "../models/model-request.js";
21
+ import { getCoordinator, getManager, getPiInstance, getSessionCtx, getStore, } from "../shell.js";
22
+ import { assertNever, parseThinkingLevel } from "../utils.js";
23
+ import { queuedCueContext, settledCueContext, spawnCueContext, } from "./context.js";
24
+ import { renderCue } from "./cues.js";
25
+ /** Compact one-line list of active agents: "id (type), id (type)". */
26
+ export function formatActiveAgents(manager = getManager()) {
27
+ const agents = manager
28
+ .listAgents(ACTIVE_AGENT_PHASES)
29
+ .filter((a) => isActivePhase(a.lifecycle.phase));
30
+ if (agents.length === 0)
31
+ return "none";
32
+ return agents.map((a) => `${a.id} (${a.display.type})`).join(", ");
33
+ }
34
+ /** Details payload for one spawn: always type and description; includeStatus adds status and herdr location, includeRunInfo adds the model/thinking and elapsed time. A stop initiator is not a details field — the result note carries it. */
35
+ export function buildAgentDetails(spawn, opts) {
36
+ const details = {
37
+ type: spawn.display.type,
38
+ description: spawn.display.description,
39
+ };
40
+ if (spawn.display.taskSlug) {
41
+ details.taskSlug = spawn.display.taskSlug;
42
+ }
43
+ if (spawn.display.worktree) {
44
+ details.worktreePath = spawn.display.worktree.path;
45
+ details.worktreeBranch = spawn.display.worktree.branch;
46
+ }
47
+ if (spawn.display.worktree?.kind === "owned") {
48
+ details.worktreeManaged = true;
49
+ }
50
+ const host = spawn.execution.host;
51
+ if (host) {
52
+ details.herdrAgent = host.name;
53
+ details.herdrPane = host.paneId;
54
+ details.herdrTab = host.tabId;
55
+ }
56
+ if (opts?.includeStatus) {
57
+ details.status = lifecycleStatus(spawn.lifecycle);
58
+ }
59
+ if (opts?.includeRunInfo) {
60
+ const elapsedMs = hasOutcome(spawn.lifecycle)
61
+ ? spawn.lifecycle.completedAt - lifecycleStartTime(spawn.lifecycle)
62
+ : 0;
63
+ details.durationMs = elapsedMs;
64
+ details.modelName = spawn.display.invocation?.modelName;
65
+ details.modelId = spawn.display.invocation?.modelName;
66
+ details.thinkingLevel = spawn.display.invocation?.thinkingLevel;
67
+ }
68
+ return details;
69
+ }
70
+ /** One cue outcome per lifecycle: completed carries its result, error its message, and a run that has not ended reads as a stop. */
71
+ function settledOutcome(lifecycle) {
72
+ // A cue rendered before the run ended has no result or error to render; the stop arm is the outcome shape that carries neither.
73
+ if (!hasOutcome(lifecycle))
74
+ return { kind: "stopped" };
75
+ switch (lifecycle.status) {
76
+ case "completed":
77
+ return { kind: "completed", result: lifecycle.result };
78
+ case "error":
79
+ return { kind: "failed", error: lifecycle.error };
80
+ case "stopped":
81
+ return { kind: "stopped" };
82
+ default:
83
+ return assertNever(lifecycle);
84
+ }
85
+ }
86
+ /** Result text plus status note, for display. Errors pass through verbatim. Worktree settles append a lifecycle note stating what remains and directing the orchestrator to call cleanup_cowboy_agent — removal is never implied to happen on its own. */
87
+ export function formatResultContent(spawn) {
88
+ const lifecycle = spawn.lifecycle;
89
+ // A retention reason exists only on an ended run: it records a tree kept at settlement or by cleanup.
90
+ const retention = hasOutcome(lifecycle)
91
+ ? lifecycle.worktreeRetentionReason
92
+ : undefined;
93
+ const config = spawn.display.orchestration;
94
+ const worktree = spawn.display.worktree?.kind === "owned"
95
+ ? spawn.display.worktree
96
+ : undefined;
97
+ return renderCue(config.cues, "settled", settledCueContext({
98
+ outcome: settledOutcome(lifecycle),
99
+ statusNote: getStatusNote(lifecycle) || undefined,
100
+ worktree: worktree
101
+ ? {
102
+ path: worktree.path,
103
+ branch: worktree.branch,
104
+ retention: retention ? formatRetentionClause(retention) : undefined,
105
+ // Only a reported run leaves its process alive; a launch failure
106
+ // never started one, and a stopped settle is interrupt-only.
107
+ processAlive: lifecycle.phase === "settled" && lifecycle.status === "completed",
108
+ }
109
+ : undefined,
110
+ }));
111
+ }
112
+ /** One delegation turn, bound to its validated intent. */
113
+ export class DelegationProtocol {
114
+ /** The validated intent — fixed at parse time. */
115
+ intent;
116
+ constructor(intent) {
117
+ this.intent = intent;
118
+ }
119
+ /** Validate a single spawn's params into its delegation intent. Throws for an unusable task name, agent type or model before anything is provisioned. */
120
+ static async parse(params, ctx, toolCallId) {
121
+ const agentType = resolveAgentTypeParam(params.agent_type);
122
+ const prompt = params.prompt;
123
+ // The orchestrator MUST name the task — the branch reads as the task, not the agent type. No derivation fallback.
124
+ const taskName = typeof params.task_name === "string" ? params.task_name.trim() : "";
125
+ if (!taskName) {
126
+ throw new Error(`cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the \`task_name\` parameter — it names the agent's branch/tab/worktree/agent so you can recognize it at a glance.`);
127
+ }
128
+ const taskSlug = buildTaskSlug(taskName);
129
+ // A configured template name that no longer resolves degrades to `default` instead of failing the spawn.
130
+ const orchestrator = resolveDefaultOrchestrator();
131
+ // An unrunnable caller-supplied model fails here, before touching the in-flight attempt or leaving a checkout behind. Provenance is explicit (ModelRequest), never inferred from the args object.
132
+ const requested = resolveModelRequest(readModelRequest(params), ctx.modelRegistry, ctx.model);
133
+ // Also scan the spawned worktree's .pi/agents/ — it can define a type the parent checkout lacks — unless the target is untrusted. The checkout is not provisioned yet, so only the parent project's directory is scanned here. The type resolves here rather than in `run`, so an unknown name fails the whole batch before any item spawns.
134
+ const resolution = await resolveTypeOrDiscover(agentType, undefined, (message, kind) => {
135
+ ctx.ui.notify(message, kind);
136
+ });
137
+ if (resolution.kind === "ambiguous") {
138
+ throw new Error(`Ambiguous agent type: ${agentType}. Candidates: ${resolution.candidates.join(", ")}. Use the exact registered name — nothing was spawned.`);
139
+ }
140
+ if (resolution.kind === "not-found") {
141
+ throw new Error(`Unknown agent type: ${agentType} — nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);
142
+ }
143
+ // Background is the default — delegation never blocks the orchestrator's turn. Only an explicit run_in_background: false opts into foreground.
144
+ const isBackground = params.run_in_background !== false;
145
+ return new DelegationProtocol({
146
+ ctx,
147
+ toolCallId,
148
+ taskSlug,
149
+ prompt,
150
+ description: prompt.split("\n")[0].slice(0, 80) || prompt.slice(0, 80),
151
+ agentType,
152
+ resolvedType: resolution.key,
153
+ orchestrator,
154
+ fork: getAgentConfig(agentType)?.fork ?? false,
155
+ modelSelection: requested.kind === "resolved"
156
+ ? { model: requested.model, key: requested.modelKey }
157
+ : undefined,
158
+ isBackground,
159
+ thinkingOverride: params.thinking,
160
+ });
161
+ }
162
+ /** Run the turn: compute the worktree the launch will provision, spawn through the coordinator, then project the spawn into the spawned or queued cue. Nothing is provisioned here — a queued run gets its worktree and pane only when it is granted a slot. */
163
+ async run(signal) {
164
+ const { ctx, isBackground, taskSlug, resolvedType } = this.intent;
165
+ const pi = getPiInstance();
166
+ // One id per spawn names the worktree branch AND the herdr agent. Minted through the manager, so it is unique against every retained spawn.
167
+ const spawnId = getManager().mintSpawnId();
168
+ // The checkout the launch will create, named by the same policy the sandbox uses, so the cue can name the branch the orchestrator merges without the worktree existing yet.
169
+ const worktree = await this.expectedWorktree(pi, spawnId);
170
+ const thinkingLevel = parseThinkingLevel(this.intent.thinkingOverride) ??
171
+ getAgentConfig(resolvedType)?.thinkingLevel ??
172
+ getStore().agent.defaultThinking;
173
+ const modelName = this.intent.modelSelection?.model.id;
174
+ const { agentId, spawn } = await getCoordinator().spawn(ctx, {
175
+ spawnId,
176
+ type: resolvedType,
177
+ prompt: this.intent.prompt,
178
+ description: this.intent.description,
179
+ taskSlug,
180
+ orchestration: this.intent.orchestrator,
181
+ modelSelection: this.intent.modelSelection,
182
+ thinkingLevel,
183
+ fork: this.intent.fork,
184
+ // Coordinates only: the launch provisions the checkout once the run holds a slot.
185
+ worktree,
186
+ invocation: {
187
+ modelName,
188
+ thinkingLevel,
189
+ fork: this.intent.fork,
190
+ },
191
+ runInBackground: isBackground,
192
+ signal: isBackground ? undefined : signal,
193
+ });
194
+ if (this.intent.toolCallId) {
195
+ spawn.display.toolCallId = this.intent.toolCallId;
196
+ }
197
+ if (!isBackground) {
198
+ const details = buildAgentDetails(spawn, { includeRunInfo: true });
199
+ // Foreground results share the `{ agents: [...] }` shape with the batch
200
+ // path so callers can read a single access pattern.
201
+ details.agentId = agentId;
202
+ if (hasOutcome(spawn.lifecycle) && spawn.lifecycle.status === "error") {
203
+ throw new Error(`agent ${agentId} stopped with an error: ${spawn.lifecycle.error || "no error message was recorded"}`);
204
+ }
205
+ return { message: formatResultContent(spawn), details };
206
+ }
207
+ // The spawn-time cue is gated on the worktree the launch will provision, never on a spawn field: its branch names exactly the ref the orchestrator merges.
208
+ const cueWorktree = worktree;
209
+ if (spawn.lifecycle.phase === "queued") {
210
+ const spawnedCount = getManager()
211
+ .listAgents(ACTIVE_AGENT_PHASES)
212
+ .filter((a) => a.lifecycle.phase === "spawned").length;
213
+ const body = renderCue(this.intent.orchestrator.cues, "queued", queuedCueContext({
214
+ agentId,
215
+ worktree: cueWorktree,
216
+ queueRunning: spawnedCount,
217
+ }));
218
+ const details = buildAgentDetails(spawn);
219
+ details.agentId = agentId;
220
+ details.status = "queued";
221
+ return { message: `[Agent queued] ${body}`, details };
222
+ }
223
+ const body = renderCue(this.intent.orchestrator.cues, "spawned", spawnCueContext({ agentId, worktree: cueWorktree }));
224
+ const details = buildAgentDetails(spawn);
225
+ details.agentId = agentId;
226
+ details.status = "spawned";
227
+ return { message: `[Agent spawned] ${body}`, details };
228
+ }
229
+ /**
230
+ * The worktree the launch will create for `spawnId`, or undefined outside a
231
+ * repository. Pure naming: it applies the sandbox's own root resolution and
232
+ * branch policy so the cue names the exact path the checkout will land on,
233
+ * but creates nothing.
234
+ */
235
+ async expectedWorktree(pi, spawnId) {
236
+ const repoRoot = await resolveMainCheckout(pi, getSessionCtx().cwd).catch(() => undefined);
237
+ if (repoRoot === undefined)
238
+ return undefined;
239
+ const root = resolveWorktreeRoot(getStore().agent.worktreeRoot, repoRoot);
240
+ return {
241
+ kind: "owned",
242
+ path: buildWorktreePath(root, this.intent.taskSlug, spawnId),
243
+ branch: buildWorktreeBranch(this.intent.taskSlug, spawnId),
244
+ };
245
+ }
246
+ }
247
+ /**
248
+ * Run a batch delegation: one validated call shape, one or more spawns.
249
+ *
250
+ * The single-item blocking guard lives here, not in the schema: a
251
+ * non-background call must have exactly one item, and the check fires before
252
+ * any item parses or any side effect runs. Every item parses — task name,
253
+ * model and agent type — before any item runs, so a bad item fails the whole
254
+ * call with no worktree, pane or spawn behind it. Two items sharing a task
255
+ * name are refused for the same reason.
256
+ *
257
+ * Spawns run in parallel; the coordinator's registry caps concurrency and
258
+ * queues overflow, so a 10-item batch against a 4-slot cap still fans out
259
+ * cleanly without any new queuing in this layer.
260
+ */
261
+ export async function runDelegationBatch(callParams, ctx, toolCallId, signal) {
262
+ if (callParams.agents.length > 1 && callParams.run_in_background === false) {
263
+ throw new Error("run_in_background: false requires exactly one agent");
264
+ }
265
+ // The call-level blocking flag threads into every per-item parse so the
266
+ // single-item and batch paths share one validation rule.
267
+ const itemInputs = callParams.agents.map((item) => ({
268
+ ...item,
269
+ run_in_background: callParams.run_in_background,
270
+ }));
271
+ // Every item parses before any item runs, so one bad item fails the whole
272
+ // call while nothing is provisioned.
273
+ const protocols = await Promise.all(itemInputs.map((item) => DelegationProtocol.parse(item, ctx, toolCallId)));
274
+ rejectRepeatedTaskSlugs(protocols);
275
+ const results = await Promise.all(protocols.map((p) => p.run(signal)));
276
+ // Single-item foreground still nests its details under `agents[0]` so
277
+ // every cowboy_agent return shape is `{ message, details: { agents: [...] } }`
278
+ // — callers should never branch on the spawn count.
279
+ const message = results.map((r) => r.message).join(BATCH_ITEM_SEPARATOR);
280
+ const details = {
281
+ agents: results.map((r) => r.details),
282
+ };
283
+ return { message, details };
284
+ }
285
+ /** A task name used twice in one call can never succeed: the first item is in flight by the time the second is admitted, so the registry refuses it and the call fails with the first agent's id lost. Refuse the repeat here instead, while nothing has spawned. */
286
+ function rejectRepeatedTaskSlugs(protocols) {
287
+ const slugs = protocols.map((protocol) => protocol.intent.taskSlug);
288
+ const repeated = slugs.filter((slug, index) => slugs.indexOf(slug) !== index);
289
+ if (repeated.length === 0)
290
+ return;
291
+ throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(repeated)].join(", ")} — nothing was spawned. Give every item in \`agents\` its own task_name.`);
292
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * types.ts — Shared orchestrator declarations: cue events, the cue template
3
+ * set, and the config/summary shapes. Per-cue variable sets live in
4
+ * context.ts — no shared "every variable" list, so a cue can never grow a
5
+ * variable the others silently inherit.
6
+ */
7
+ export {};
package/dist/paths.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * paths.ts — extension-level directory resolution.
3
+ * Everything here is a FUNCTION, not a module-scope constant: the agent dir
4
+ * can be redirected per process, so a snapshot would freeze the wrong
5
+ * directory — and resolving it must not pull pi's library barrel into the
6
+ * boot-time import graph.
7
+ */
8
+ import * as fs from "node:fs";
9
+ import { homedir, tmpdir } from "node:os";
10
+ import * as path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import pkg from "../package.json" with { type: "json" };
13
+ export const EXTENSION_NAME = pkg.name;
14
+ const AGENT_DIR_ENV_VAR = "PI_CODING_AGENT_DIR";
15
+ /**
16
+ * pi's agent dir, resolved locally so boot never imports pi's barrel.
17
+ * Semantics match pi's own `getAgentDir`: the env override wins (with tilde
18
+ * expansion), otherwise `~/.pi/agent`.
19
+ */
20
+ export function agentDir() {
21
+ const override = process.env[AGENT_DIR_ENV_VAR];
22
+ if (override)
23
+ return expandTilde(override);
24
+ return path.join(homedir(), ".pi", "agent");
25
+ }
26
+ function expandTilde(value) {
27
+ if (value === "~")
28
+ return homedir();
29
+ if (value.startsWith("~/"))
30
+ return path.join(homedir(), value.slice(2));
31
+ return value;
32
+ }
33
+ /**
34
+ * The one spelling the filesystem agrees this location has, or `undefined` when
35
+ * it has none. A directory has as many names as there are routes to it — a
36
+ * symlinked home, a bind mount, `/tmp` on macOS — and comparing those spellings
37
+ * as text reports one place as several. Anything that compares or keys on a
38
+ * path canonicalizes first.
39
+ *
40
+ * `undefined` rather than a fallback: a path that does not exist yet has no
41
+ * real spelling, and only the caller knows what to compare it with then.
42
+ */
43
+ export function canonicalPath(value) {
44
+ try {
45
+ return fs.realpathSync.native(value);
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ export function defaultExtensionDir() {
52
+ return path.join(agentDir(), EXTENSION_NAME);
53
+ }
54
+ export function defaultWorktreeRoot() {
55
+ return path.join(defaultExtensionDir(), "worktrees");
56
+ }
57
+ /**
58
+ * Staging root for a spawn's briefing, prompt and result files:
59
+ * `<tmpdir>/pi-cowboy/<agentId>/`. Resolved per call, like every directory
60
+ * here, so a `TMPDIR` override moves the whole staging area with it.
61
+ */
62
+ export function subagentResultDir() {
63
+ return path.join(tmpdir(), "pi-cowboy");
64
+ }
65
+ export const EXTENSION_AGENTS_DIR = fileURLToPath(new URL("../agents/", import.meta.url));
66
+ export const EXTENSION_ORCHESTRATORS_DIR = fileURLToPath(new URL("../orchestrators/", import.meta.url));
@@ -0,0 +1,7 @@
1
+ /** pi-settings.ts — pi's `defaultThinkingLevel` setting. `agentDir` is injectable for tests. */
2
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ import { agentDir as resolveAgentDir } from "./paths.js";
4
+ /** pi's `defaultThinkingLevel` for `cwd` (project over global). `agentDir` is injectable for tests. */
5
+ export async function getPiDefaultThinkingLevel(cwd, agentDir) {
6
+ return SettingsManager.create(cwd, agentDir ?? resolveAgentDir()).getDefaultThinkingLevel();
7
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * predicates.ts — shared leaf predicates used across layers.
3
+ * `isTaskAgentName` lives here so the infrastructure layer need not import
4
+ * across the layer boundary into spawn/. Its pattern derives from the
5
+ * spawn-id leaf (`SPAWN_ID_ALPHABET`, `SPAWN_ID_LENGTH`), never re-typed, so
6
+ * an alphabet change cannot silently stop matching real agent names.
7
+ */
8
+ import { SPAWN_ID_ALPHABET, SPAWN_ID_LENGTH } from "./spawn/spawn-id.js";
9
+ const SPAWN_ID_PATTERN = `[${SPAWN_ID_ALPHABET}]{${SPAWN_ID_LENGTH}}`;
10
+ /**
11
+ * Agent names are `cow-<slug>-<id>`. The slug boundary is explicit — `fix`
12
+ * must not match `fix-login-flow-<id>` — hence the full anchored shape
13
+ * instead of a prefix test.
14
+ */
15
+ export function isTaskAgentName(name, taskSlug) {
16
+ // taskSlug comes from buildTaskSlug: only [a-z0-9_-], no regex metacharacters.
17
+ return new RegExp(`^cow-${taskSlug}-${SPAWN_ID_PATTERN}$`).test(name);
18
+ }
19
+ /**
20
+ * A keyed object, not an array: callers reading fields off untrusted JSON read
21
+ * `undefined` rather than an array's absent properties.
22
+ */
23
+ export function isRecord(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
@@ -0,0 +1,110 @@
1
+ /** prompts.ts — System prompt builder for agents. Every agent gets a fresh context — no inherited parent identity. */
2
+ import { formatSkillsForPrompt, } from "@earendil-works/pi-coding-agent";
3
+ /** Strip pi scaffolding (<project_context>, skills block, date/cwd lines) from a parent prompt. Inherit mode re-adds these from the subagent's own config. */
4
+ function stripScaffolding(prompt) {
5
+ let result = prompt;
6
+ result = result.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g, "\n");
7
+ result = result.replace(/\n?(?:The following skills provide[\s\S]*?)?<\s*available_skills\s*>[\s\S]*?<\/\s*available_skills\s*>\n?/g, "\n");
8
+ result = result.replace(/\n?Current date:.*\n?/g, "\n");
9
+ result = result.replace(/\n?Current working directory:.*\n?/g, "\n");
10
+ result = result.replace(/\n{3,}/g, "\n\n");
11
+ return result.trim();
12
+ }
13
+ /**
14
+ * Build the agent prompt from its config. Modes: replace (default, env +
15
+ * agent's systemPrompt, no generic header), inherit (stripped parent prompt +
16
+ * env + systemPrompt), custom (prompt file + env + systemPrompt). The agent's
17
+ * systemPrompt is always included in `<agent_instructions>`.
18
+ */
19
+ export async function buildAgentPrompt(config, cwd, env, extras, mode = "replace") {
20
+ const envLines = [
21
+ "# Environment",
22
+ `Working directory: ${cwd}`,
23
+ env.isGitRepo ? "Git repository: yes" : "Not a git repository",
24
+ ];
25
+ if (env.isGitRepo && env.branch) {
26
+ envLines.push(`Branch: ${env.branch}`);
27
+ }
28
+ envLines.push(`Platform: ${env.platform}`);
29
+ const envBlock = envLines.join("\n");
30
+ const hasSkills = Boolean(extras?.skillMetas?.length) ||
31
+ Boolean(extras?.inlinedSkills?.length);
32
+ let extrasSuffix = "";
33
+ if (hasSkills) {
34
+ const skillLines = [];
35
+ if (extras?.skillMetas?.length) {
36
+ const piSkills = extras.skillMetas.map((m) => ({
37
+ name: m.name,
38
+ description: m.description,
39
+ filePath: m.location,
40
+ baseDir: "",
41
+ sourceInfo: {},
42
+ disableModelInvocation: m.disableModelInvocation,
43
+ }));
44
+ const formatted = formatSkillsForPrompt(piSkills);
45
+ const skillElements = formatted.match(/<skill>[\s\S]*?<\/skill>/g);
46
+ if (skillElements)
47
+ skillLines.push(...skillElements);
48
+ }
49
+ for (const skill of extras?.inlinedSkills ?? []) {
50
+ skillLines.push(`<skill><name>${escapeXml(skill.name)}</name><description>${escapeXml(skill.description)}</description><content>${escapeXml(skill.content)}</content></skill>`);
51
+ }
52
+ const lines = [
53
+ "The following skills provide specialized instructions for specific tasks.",
54
+ "Use the read tool to load a skill's file when the task matches its description.",
55
+ "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
56
+ "",
57
+ "<available_skills>",
58
+ ...skillLines,
59
+ "</available_skills>",
60
+ ];
61
+ extrasSuffix = `\n\n${lines.join("\n")}`;
62
+ }
63
+ const agentInstructions = `\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`;
64
+ let contextSuffix = "";
65
+ if (extras?.contextFiles?.length) {
66
+ const lines = [
67
+ "<project_context>",
68
+ "",
69
+ "Project-specific instructions and guidelines:",
70
+ "",
71
+ ];
72
+ for (const file of extras.contextFiles) {
73
+ lines.push(`<project_instructions path="${escapeXml(file.path)}">`);
74
+ lines.push(file.content);
75
+ lines.push(`</project_instructions>`);
76
+ lines.push("");
77
+ }
78
+ lines.push("</project_context>");
79
+ contextSuffix = `\n\n${lines.join("\n")}`;
80
+ }
81
+ const activeAgentTag = buildActiveAgentTag(config);
82
+ const rawHeader = mode === "inherit"
83
+ ? extras?.parentSystemPrompt
84
+ : mode === "custom"
85
+ ? extras?.customSystemPrompt
86
+ : undefined;
87
+ // Parent/custom headers carry pi's scaffolding; strip it since we re-add these from the subagent's own config. Replace mode adds no header.
88
+ const customHeader = rawHeader ? stripScaffolding(rawHeader) : rawHeader;
89
+ const basePrompt = customHeader ? `${customHeader}\n\n${envBlock}` : envBlock;
90
+ return {
91
+ prefix: `${basePrompt}${contextSuffix}`,
92
+ identity: `${activeAgentTag}\n${agentInstructions}`,
93
+ skills: extrasSuffix,
94
+ };
95
+ }
96
+ /** The `<active_agent>` tag: registered name, display name when configured, description as the body. The description belongs on the identity tag, not in the task. */
97
+ function buildActiveAgentTag(config) {
98
+ const displayName = config.displayName?.trim();
99
+ const displayAttr = displayName
100
+ ? ` display_name="${escapeXml(displayName)}"`
101
+ : "";
102
+ const nameAttr = `name="${escapeXml(config.name)}"${displayAttr}`;
103
+ const description = config.description.trim();
104
+ if (!description)
105
+ return `<active_agent ${nameAttr}/>`;
106
+ return `<active_agent ${nameAttr}>\n${escapeXml(description)}\n</active_agent>`;
107
+ }
108
+ function escapeXml(value) {
109
+ return value.replace(/</g, "&lt;").replace(/>/g, "&gt;");
110
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * skill-loader.ts — Load skills using Pi's exported APIs, so subagents see
3
+ * the same skills as the parent session.
4
+ *
5
+ * Roots, in precedence order (first match wins by name):
6
+ * 1. Ancestor .agents/skills (cwd → git root, root .md files filtered out)
7
+ * 2. ~/.agents/skills (root .md files filtered out)
8
+ * 3. ~/.pi/agent/skills (Pi's user default)
9
+ * 4. <cwd>/.pi/skills (Pi's project default)
10
+ *
11
+ * Root .md files are filtered out of .agents/skills because Pi's "agents"
12
+ * mode (no root files) is not exported.
13
+ */
14
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join, resolve } from "node:path";
17
+ import { loadSkills, loadSkillsFromDir, } from "@earendil-works/pi-coding-agent";
18
+ import { isUnsafeName } from "../utils.js";
19
+ function loadAllSkills(cwd) {
20
+ const resolvedCwd = resolve(cwd);
21
+ const ancestorsSkills = loadAncestorAgentsSkills(resolvedCwd, loadSkillsFromDir);
22
+ const homeAgentsResult = loadSkillsFromDir({
23
+ dir: join(homedir(), ".agents", "skills"),
24
+ source: "agents",
25
+ });
26
+ const homeAgentsSkills = filterRootMdFiles(homeAgentsResult.skills, join(homedir(), ".agents", "skills"));
27
+ const defaultsResult = loadSkills({
28
+ cwd: resolvedCwd,
29
+ agentDir: join(homedir(), ".pi", "agent"),
30
+ skillPaths: [],
31
+ includeDefaults: true,
32
+ });
33
+ const nameSet = new Set();
34
+ const realPathSet = new Set();
35
+ const result = [];
36
+ for (const skill of [
37
+ ...ancestorsSkills,
38
+ ...homeAgentsSkills,
39
+ ...defaultsResult.skills,
40
+ ]) {
41
+ const realPath = canonicalizePath(skill.filePath);
42
+ if (realPathSet.has(realPath) || nameSet.has(skill.name))
43
+ continue;
44
+ nameSet.add(skill.name);
45
+ realPathSet.add(realPath);
46
+ result.push(skill);
47
+ }
48
+ return result;
49
+ }
50
+ /** Walk cwd → git root, loading each `.agents/skills` dir. Root .md files are filtered: the exported API has no "agents" mode. */
51
+ function loadAncestorAgentsSkills(resolvedCwd, loadSkillsFromDir) {
52
+ const gitRoot = findGitRoot(resolvedCwd);
53
+ const result = [];
54
+ let dir = resolvedCwd;
55
+ while (true) {
56
+ const agentsSkillsDir = join(dir, ".agents", "skills");
57
+ const dirResult = loadSkillsFromDir({
58
+ dir: agentsSkillsDir,
59
+ source: "agents",
60
+ });
61
+ result.push(...filterRootMdFiles(dirResult.skills, agentsSkillsDir));
62
+ if (dir === gitRoot)
63
+ break;
64
+ const parent = resolve(dir, "..");
65
+ if (parent === dir)
66
+ break;
67
+ dir = parent;
68
+ }
69
+ return result;
70
+ }
71
+ /** Filter root .md files out of `.agents/skills` (subdir skills only): a root skill's parent is the skills root itself. */
72
+ function filterRootMdFiles(skills, skillsRoot) {
73
+ const normalizedRoot = resolve(skillsRoot);
74
+ return skills.filter((skill) => {
75
+ const parent = resolve(skill.filePath, "..");
76
+ return parent !== normalizedRoot;
77
+ });
78
+ }
79
+ function findGitRoot(dir) {
80
+ let current = resolve(dir);
81
+ while (true) {
82
+ if (existsSync(join(current, ".git")))
83
+ return current;
84
+ const parent = resolve(current, "..");
85
+ if (parent === current)
86
+ return current;
87
+ current = parent;
88
+ }
89
+ }
90
+ /** Canonical path, following symlinks; raw path when unresolvable. */
91
+ function canonicalizePath(filePath) {
92
+ try {
93
+ return realpathSync(filePath);
94
+ }
95
+ catch {
96
+ return filePath;
97
+ }
98
+ }
99
+ export async function inlineSkills(skillNames, cwd) {
100
+ const skills = loadAllSkills(cwd);
101
+ return skillNames.map((name) => {
102
+ if (isUnsafeName(name)) {
103
+ return {
104
+ name,
105
+ description: "",
106
+ content: `(Skill "${name}" skipped: name contains path traversal characters)`,
107
+ };
108
+ }
109
+ const match = skills.find((s) => s.name === name);
110
+ if (!match) {
111
+ return {
112
+ name,
113
+ description: "",
114
+ content: `(Skill "${name}" not found in .pi/skills/, .agents/skills/, or global skill locations)`,
115
+ };
116
+ }
117
+ try {
118
+ return {
119
+ name,
120
+ description: match.description,
121
+ content: readFileSync(match.filePath, "utf-8").trim(),
122
+ };
123
+ }
124
+ catch {
125
+ return {
126
+ name,
127
+ description: "",
128
+ content: `(Skill "${name}" not found in .pi/skills/, .agents/skills/, or global skill locations)`,
129
+ };
130
+ }
131
+ });
132
+ }
133
+ /** Skill metadata only (no content), for the whitelist — the agent reads full content on demand. */
134
+ export async function loadSkillMeta(skillNames, cwd) {
135
+ const skills = loadAllSkills(cwd);
136
+ return skillNames.map((name) => {
137
+ const match = skills.find((s) => s.name === name);
138
+ if (!match) {
139
+ return {
140
+ name,
141
+ description: `(Skill "${name}" not found)`,
142
+ location: "",
143
+ disableModelInvocation: false,
144
+ };
145
+ }
146
+ return {
147
+ name,
148
+ description: match.description,
149
+ location: match.filePath,
150
+ disableModelInvocation: match.disableModelInvocation,
151
+ };
152
+ });
153
+ }