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
+ * config-validation.ts — load-time validation for config files.
3
+ * Invalid values are dropped so built-in defaults apply; file bytes are
4
+ * untouched and each drop warns once with file, key, got, and expected.
5
+ */
6
+ import { Type } from "typebox";
7
+ import { Check } from "typebox/value";
8
+ import { HARNESS_IDS } from "../agents/harness.js";
9
+ import { isRecord } from "../predicates.js";
10
+ const MODEL_KEY = {
11
+ schema: Type.Union([Type.String(), Type.Null()]),
12
+ expected: "string or null",
13
+ };
14
+ const BOOL = { schema: Type.Boolean(), expected: "boolean" };
15
+ const NUM = { schema: Type.Number(), expected: "number" };
16
+ const SYSTEM_PROMPT_MODE = {
17
+ schema: Type.Union([
18
+ Type.Literal("replace"),
19
+ Type.Literal("inherit"),
20
+ Type.Literal("custom"),
21
+ ]),
22
+ expected: '"replace" | "inherit" | "custom"',
23
+ };
24
+ const THINKING = {
25
+ schema: Type.Union([
26
+ Type.Literal("off"),
27
+ Type.Literal("minimal"),
28
+ Type.Literal("low"),
29
+ Type.Literal("medium"),
30
+ Type.Literal("high"),
31
+ Type.Literal("xhigh"),
32
+ Type.Literal("max"),
33
+ ]),
34
+ expected: '"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"',
35
+ };
36
+ const WORKTREE_MATERIALIZATION = {
37
+ schema: Type.Union([Type.Literal("copy-on-write"), Type.Literal("checkout")]),
38
+ expected: '"copy-on-write" | "checkout"',
39
+ };
40
+ const WORKTREE_CHECKOUT_TYPE = {
41
+ schema: Type.Union([Type.Literal("dirty"), Type.Literal("clean")]),
42
+ expected: '"dirty" | "clean"',
43
+ };
44
+ const WORKTREE_ROOT = {
45
+ schema: Type.String(),
46
+ expected: "string",
47
+ };
48
+ /** Built from the harness vocabulary, so a newly added harness is configurable without touching this file. */
49
+ const HARNESS = {
50
+ schema: Type.Union(HARNESS_IDS.map((id) => Type.Literal(id))),
51
+ expected: HARNESS_IDS.map((id) => `"${id}"`).join(" | "),
52
+ };
53
+ /** Empty strings are dropped so read-time fallback applies. */
54
+ const NON_EMPTY_STRING = {
55
+ schema: Type.String({ minLength: 1 }),
56
+ expected: "non-empty string",
57
+ };
58
+ /** An agent key outside the table is a per-type model key. */
59
+ const AGENT_KEY_SPECS = {
60
+ default: MODEL_KEY,
61
+ defaultAgentType: NON_EMPTY_STRING,
62
+ defaultOrchestrator: NON_EMPTY_STRING,
63
+ systemPromptMode: SYSTEM_PROMPT_MODE,
64
+ includeContextFiles: BOOL,
65
+ defaultThinking: THINKING,
66
+ loadSkillsImplicitly: BOOL,
67
+ loadExtensionsImplicitly: BOOL,
68
+ disableDefaultAgents: BOOL,
69
+ extensionEnabled: BOOL,
70
+ showActiveIndicator: BOOL,
71
+ grazingEnabled: BOOL,
72
+ worktreeRoot: WORKTREE_ROOT,
73
+ worktreeMaterialization: WORKTREE_MATERIALIZATION,
74
+ worktreeCheckoutType: WORKTREE_CHECKOUT_TYPE,
75
+ harnessType: HARNESS,
76
+ };
77
+ function describeValue(value) {
78
+ if (Array.isArray(value))
79
+ return "array";
80
+ if (value === null)
81
+ return "null";
82
+ if (typeof value === "object")
83
+ return "object";
84
+ return typeof value;
85
+ }
86
+ function formatIncompatibleWarning(filePath, keyPath, value, expected) {
87
+ return (`[subagents] Incompatible value in ${filePath}: "${keyPath}" is ${describeValue(value)}, ` +
88
+ `expected ${expected}. Set it again in the /cowboy menu, or edit or delete the file to fix it.`);
89
+ }
90
+ function warnIncompatible(filePath, keyPath, value, expected) {
91
+ console.warn(formatIncompatibleWarning(filePath, keyPath, value, expected));
92
+ }
93
+ const EXPECTED_OBJECT = "object";
94
+ /** Never throws: a missed check reads as invalid so the load survives it. */
95
+ function isValidValue(spec, value) {
96
+ try {
97
+ return Check(spec.schema, value);
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ }
103
+ /** Validate one file layer, dropping invalid values. Never throws: bad input reads as empty. */
104
+ export function validateRawLayer(raw, filePath) {
105
+ const cleaned = {};
106
+ if (!isRecord(raw)) {
107
+ warnIncompatible(filePath, "(config)", raw, EXPECTED_OBJECT);
108
+ return cleaned;
109
+ }
110
+ if (raw.agent !== undefined) {
111
+ if (!isRecord(raw.agent)) {
112
+ warnIncompatible(filePath, "agent", raw.agent, EXPECTED_OBJECT);
113
+ }
114
+ else {
115
+ const agent = cleanAgentEntries(raw.agent, filePath);
116
+ if (Object.keys(agent).length > 0)
117
+ cleaned.agent = agent;
118
+ }
119
+ }
120
+ if (raw.concurrency !== undefined) {
121
+ const concurrency = cleanConcurrencySection(raw.concurrency, filePath);
122
+ if (Object.keys(concurrency).length > 0)
123
+ cleaned.concurrency = concurrency;
124
+ }
125
+ return cleaned;
126
+ }
127
+ /** An agent key outside the table is a per-type model key. */
128
+ function cleanAgentEntries(agent, filePath) {
129
+ const kept = {};
130
+ for (const [key, value] of Object.entries(agent)) {
131
+ if (value === undefined)
132
+ continue;
133
+ const spec = AGENT_KEY_SPECS[key] ?? MODEL_KEY;
134
+ if (isValidValue(spec, value))
135
+ kept[key] = value;
136
+ else
137
+ warnIncompatible(filePath, `agent.${key}`, value, spec.expected);
138
+ }
139
+ return kept;
140
+ }
141
+ /** Plain typeof checks: every value here is a bare number. */
142
+ function cleanConcurrencySection(concurrency, filePath) {
143
+ const kept = {};
144
+ if (!isRecord(concurrency)) {
145
+ warnIncompatible(filePath, "concurrency", concurrency, EXPECTED_OBJECT);
146
+ return kept;
147
+ }
148
+ if (concurrency.default !== undefined) {
149
+ if (typeof concurrency.default === "number")
150
+ kept.default = concurrency.default;
151
+ else
152
+ warnIncompatible(filePath, "concurrency.default", concurrency.default, NUM.expected);
153
+ }
154
+ for (const section of ["providers", "models"]) {
155
+ const entries = concurrency[section];
156
+ if (entries === undefined)
157
+ continue;
158
+ if (!isRecord(entries)) {
159
+ warnIncompatible(filePath, `concurrency.${section}`, entries, EXPECTED_OBJECT);
160
+ continue;
161
+ }
162
+ const keptEntries = {};
163
+ for (const [key, value] of Object.entries(entries)) {
164
+ if (typeof value === "number")
165
+ keptEntries[key] = value;
166
+ else
167
+ warnIncompatible(filePath, `concurrency.${section}.${key}`, value, NUM.expected);
168
+ }
169
+ if (Object.keys(keptEntries).length > 0)
170
+ kept[section] = keptEntries;
171
+ }
172
+ return kept;
173
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * layered-config.ts — the three-layer raw config: project file over global
3
+ * file over the built-in defaults, with the session layer kept by the caller.
4
+ *
5
+ * Every change routes through `mutate` or `clear`, so persistence and target
6
+ * resolution happen the same way for each slice of the file, and the project
7
+ * layer is only ever created by a write.
8
+ */
9
+ import { createConfigIO, mergeDefaults, mergeLayers, } from "./config-io.js";
10
+ const fileConfigIO = createConfigIO();
11
+ function projectLayerFrom(loaded) {
12
+ if (loaded.project)
13
+ return { kind: "present", raw: loaded.project };
14
+ if (loaded.projectStatus === "untrusted" ||
15
+ loaded.projectStatus === "malformed") {
16
+ return { kind: "refused", status: loaded.projectStatus };
17
+ }
18
+ return { kind: "creatable" };
19
+ }
20
+ export class LayeredConfig {
21
+ io;
22
+ globalRaw;
23
+ projectLayer;
24
+ constructor(io = fileConfigIO) {
25
+ this.io = io;
26
+ const loaded = io.load();
27
+ this.globalRaw = loaded.global;
28
+ this.projectLayer = projectLayerFrom(loaded);
29
+ }
30
+ /** Project file over global file over the built-in defaults. */
31
+ get effective() {
32
+ return mergeDefaults(mergeLayers(this.globalRaw, this.project));
33
+ }
34
+ get global() {
35
+ return this.globalRaw;
36
+ }
37
+ /** Null when no project layer exists. */
38
+ get project() {
39
+ return this.projectLayer.kind === "present" ? this.projectLayer.raw : null;
40
+ }
41
+ /** A write creates an absent project file; only an untrusted or malformed one is refused. */
42
+ get isProjectWritable() {
43
+ return this.projectLayer.kind !== "refused";
44
+ }
45
+ /** A global file the loader could not parse is never written over. */
46
+ get isGlobalWritable() {
47
+ return this.io.isGlobalWritable();
48
+ }
49
+ /** Does not reload; session_start follows with reload(). */
50
+ setProjectDir(projectDir) {
51
+ this.io = createConfigIO(projectDir);
52
+ }
53
+ /** Re-reads both files. */
54
+ reload() {
55
+ const loaded = this.io.load();
56
+ this.globalRaw = loaded.global;
57
+ this.projectLayer = projectLayerFrom(loaded);
58
+ }
59
+ /**
60
+ * Applies `update` to one raw layer and persists it. A write creates an
61
+ * absent project layer; when the project target is unavailable the change is
62
+ * refused with a warning. False means nothing was written.
63
+ */
64
+ mutate(target, update) {
65
+ if (target === "global" && !this.globalWritableOrWarn())
66
+ return false;
67
+ const layer = target === "global" ? this.global : this.projectLayerToWrite();
68
+ if (layer === null)
69
+ return false;
70
+ update(layer);
71
+ if (target === "global")
72
+ this.io.saveGlobal(layer);
73
+ else
74
+ this.io.saveProject(layer);
75
+ return true;
76
+ }
77
+ /**
78
+ * Applies `update` to the raw layer(s) a target names, and `clearSession` to
79
+ * the caller's session layer. Only layers that exist change: a clear never
80
+ * creates a project file.
81
+ */
82
+ clear(target, update, clearSession) {
83
+ if (target === "session" || target === "all")
84
+ clearSession();
85
+ if (target === "global" || target === "all") {
86
+ if (this.globalWritableOrWarn()) {
87
+ update(this.globalRaw);
88
+ this.io.saveGlobal(this.globalRaw);
89
+ }
90
+ }
91
+ const project = this.project;
92
+ if (project && (target === "project" || target === "all")) {
93
+ update(project);
94
+ this.io.saveProject(project);
95
+ }
96
+ }
97
+ /** True when a global write may replace the file on disk. */
98
+ globalWritableOrWarn() {
99
+ if (this.isGlobalWritable)
100
+ return true;
101
+ console.warn("[subagents] Refusing to write global config (malformed); change not saved");
102
+ return false;
103
+ }
104
+ /** The project layer a write may touch, creating the file when it is absent. */
105
+ projectLayerToWrite() {
106
+ const project = this.projectLayer;
107
+ if (project.kind === "present")
108
+ return project.raw;
109
+ if (project.kind === "refused") {
110
+ console.warn(`[subagents] Project config target unavailable (${project.status}); change ignored`);
111
+ return null;
112
+ }
113
+ const raw = {};
114
+ this.projectLayer = { kind: "present", raw };
115
+ return raw;
116
+ }
117
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Non-model keys in config.agent — preserved when clearing all overrides.
3
+ * `isProjectAllowedAgentKey` reads this list: a project file may carry only
4
+ * the model family and per-type model keys.
5
+ */
6
+ export const CONFIG_AGENT_NON_MODEL_KEYS = [
7
+ "default",
8
+ "defaultAgentType",
9
+ "defaultOrchestrator",
10
+ "systemPromptMode",
11
+ "includeContextFiles",
12
+ "defaultThinking",
13
+ "loadSkillsImplicitly",
14
+ "loadExtensionsImplicitly",
15
+ "disableDefaultAgents",
16
+ "extensionEnabled",
17
+ "showActiveIndicator",
18
+ "grazingEnabled",
19
+ "worktreeRoot",
20
+ "worktreeMaterialization",
21
+ "worktreeCheckoutType",
22
+ "harnessType",
23
+ ];
@@ -0,0 +1,43 @@
1
+ /**
2
+ * cow-support-launch.ts — ask the worktree volume, once per session, which
3
+ * materializations it can honor, and let the shell answer for every later reader.
4
+ *
5
+ * Kicked off at launch and never awaited: a spawn that arrives before the probe
6
+ * lands resolves the way it always did, and the setting narrows itself once the
7
+ * answer is in. Never awaited because a probe shells out and a launch must not
8
+ * block on it; each probe carries a claim, so a slow one cannot overwrite the
9
+ * answer of a newer probe about a different volume.
10
+ */
11
+ import { detectCowAvailability, probeTargetFor } from "./spawn/cow-support.js";
12
+ import { probed, unprobed } from "./availability.js";
13
+ import { beginCowAvailabilityProbe, getStore, setCowAvailability, } from "./shell.js";
14
+ /** `pi.exec` as the cloner's seam: the same one place shells out of the extension. */
15
+ function execOf(pi) {
16
+ return (command, args, options) => pi.exec(command, args, options);
17
+ }
18
+ export function startCowSupportProbe(pi) {
19
+ probe(pi, beginCowAvailabilityProbe());
20
+ }
21
+ /**
22
+ * Ask again, because the worktree root can move to another volume. The answer
23
+ * goes back to unknown first so no reader sees the previous volume's verdict
24
+ * while the new probe runs.
25
+ */
26
+ export function refreshCowSupportProbe(pi) {
27
+ const claim = beginCowAvailabilityProbe();
28
+ setCowAvailability(claim, unprobed());
29
+ probe(pi, claim);
30
+ }
31
+ /**
32
+ * Run one probe and record its verdict under the claim it was opened with. An
33
+ * older probe that answers later describes a volume nobody asked about any
34
+ * more, so its claim is stale and the shell discards the verdict.
35
+ */
36
+ function probe(pi, claim) {
37
+ const target = probeTargetFor(getStore().agent.worktreeRoot);
38
+ void detectCowAvailability(execOf(pi), target).then((availability) => {
39
+ setCowAvailability(claim, availability);
40
+ }, () => {
41
+ setCowAvailability(claim, probed(["checkout"]));
42
+ });
43
+ }
package/dist/events.js ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * events.ts — session lifecycle wiring.
3
+ * session_start loads the config and the agent/orchestrator templates, wires the
4
+ * manager + coordinator, then puts the active set and the presence marker in
5
+ * line with the switch; the tool_call listener injects resolved models.
6
+ */
7
+ import * as path from "node:path";
8
+ import { agentDir } from "./paths.js";
9
+ import { registerAgents, setAgentScanDirs, scanAndMerge, } from "./agents/agent-types.js";
10
+ import { registerOrchestrators, setOrchestratorScanDirs, scanAndMergeOrchestrators, } from "./orchestrators/orchestrator-types.js";
11
+ import { AgentManager } from "./agents/agent-manager.js";
12
+ import { ACTIVE_AGENT_PHASES } from "./types.js";
13
+ import { SpawnCoordinator } from "./spawn/spawn-coordinator.js";
14
+ import { toolCallListener } from "./agents/tool-execution.js";
15
+ import { activateExtension, deactivateExtension } from "./registration.js";
16
+ import { isExtensionEnabled } from "./extension-toggle.js";
17
+ import { hideExtensionIndicator } from "./ui/indicator.js";
18
+ import { createSessionTemplates, getManagerOrNull, getCoordinatorOrNull, getStore, setSessionCtx, setManager, setCoordinator, setRuntime, setSessionTemplates, } from "./shell.js";
19
+ /** Idempotent — safe to call on every session_start. */
20
+ function ensureManagerAndCoordinator() {
21
+ if (!getManagerOrNull()) {
22
+ const newManager = new AgentManager(undefined, getStore().concurrency);
23
+ setManager(newManager);
24
+ // Config side-effect target: concurrency setters call setConcurrency.
25
+ getStore().setDeps({ manager: newManager });
26
+ const coordinator = new SpawnCoordinator(newManager);
27
+ setCoordinator(coordinator);
28
+ newManager.setOnComplete((spawn) => {
29
+ coordinator.onAgentComplete(spawn);
30
+ });
31
+ newManager.setOnFollowUp((spawn, deliverable) => {
32
+ coordinator.onAgentFollowUp(spawn, deliverable);
33
+ });
34
+ }
35
+ }
36
+ async function scanAndRegisterAgents(ctx) {
37
+ const agentDirPath = agentDir();
38
+ const userAgentDir = path.join(agentDirPath, "agents");
39
+ const projectTrusted = ctx.isProjectTrusted();
40
+ const sharedAgentDir = projectTrusted
41
+ ? path.join(ctx.cwd, ".agents", "agents")
42
+ : "";
43
+ const projectAgentDir = projectTrusted
44
+ ? path.join(ctx.cwd, ".pi", "agents")
45
+ : "";
46
+ // Scan dirs persist for on-demand discovery later in the session.
47
+ setAgentScanDirs(userAgentDir, projectAgentDir, sharedAgentDir);
48
+ const disableDefaults = getStore().agent.disableDefaultAgents;
49
+ const merged = await scanAndMerge({
50
+ disableDefaultAgents: disableDefaults,
51
+ // The sink makes skipped malformed files visible.
52
+ notify: (message, kind) => {
53
+ ctx.ui.notify(message, kind);
54
+ },
55
+ });
56
+ registerAgents(merged, { disableDefaultAgents: disableDefaults });
57
+ }
58
+ async function scanAndRegisterOrchestrators(ctx) {
59
+ const agentDirPath = agentDir();
60
+ const userOrchestratorDir = path.join(agentDirPath, "orchestrators");
61
+ const projectTrusted = ctx.isProjectTrusted();
62
+ const sharedOrchestratorDir = projectTrusted
63
+ ? path.join(ctx.cwd, ".agents", "orchestrators")
64
+ : "";
65
+ const projectOrchestratorDir = projectTrusted
66
+ ? path.join(ctx.cwd, ".pi", "orchestrators")
67
+ : "";
68
+ // Scan dirs persist for on-demand discovery later in the session.
69
+ setOrchestratorScanDirs(userOrchestratorDir, projectOrchestratorDir, sharedOrchestratorDir);
70
+ const merged = await scanAndMergeOrchestrators({
71
+ // The sink makes skipped malformed files visible.
72
+ notify: (message, kind) => {
73
+ ctx.ui.notify(message, kind);
74
+ },
75
+ });
76
+ registerOrchestrators(merged);
77
+ }
78
+ /**
79
+ * Config, templates, manager and coordinator: everything a session needs
80
+ * whatever the switch says, because the /cowboy menus read the registries.
81
+ */
82
+ async function loadSessionConfig(ctx) {
83
+ // Fresh registries before the scan: a session never serves the templates registered by the session it replaced.
84
+ setSessionTemplates(createSessionTemplates());
85
+ // Mirrors the .pi/agents scan-dir trust gate.
86
+ const projectDir = ctx.isProjectTrusted()
87
+ ? path.join(ctx.cwd, ".pi")
88
+ : undefined;
89
+ getStore().setProjectDir(projectDir);
90
+ getStore().reload();
91
+ ensureManagerAndCoordinator();
92
+ await scanAndRegisterAgents(ctx);
93
+ await scanAndRegisterOrchestrators(ctx);
94
+ }
95
+ export function setupEventListeners(pi) {
96
+ pi.on("tool_call", toolCallListener);
97
+ pi.on("session_start", async (_event, ctx) => {
98
+ setSessionCtx(ctx);
99
+ await loadSessionConfig(ctx);
100
+ if (isExtensionEnabled()) {
101
+ activateExtension(ctx.ui);
102
+ }
103
+ else {
104
+ // A session that replaced an enabled one can still hold the registered tools.
105
+ deactivateExtension(ctx.ui);
106
+ if (ctx.hasUI) {
107
+ ctx.ui.notify("Cowboy extension is disabled — its tools are not loaded. Run /cowboy enable to turn it back on.", "info");
108
+ }
109
+ }
110
+ });
111
+ pi.on("session_shutdown", async (_event, ctx) => {
112
+ const currentManager = getManagerOrNull();
113
+ if (currentManager) {
114
+ // Active phases only: only in-flight work is a pane left running.
115
+ const active = currentManager.listAgents(ACTIVE_AGENT_PHASES);
116
+ if (active.length > 0 && ctx.hasUI) {
117
+ ctx.ui.notify(`${active.length} subagent pane(s) left running in herdr (tracking stopped for the previous session)`, "warning");
118
+ }
119
+ }
120
+ // Panes keep running in herdr — they are independent processes; only tracking stops.
121
+ getCoordinatorOrNull()?.dispose();
122
+ setCoordinator(null);
123
+ setRuntime(null);
124
+ getStore().dispose();
125
+ const mgr = getManagerOrNull();
126
+ if (mgr) {
127
+ mgr.dispose();
128
+ setManager(null);
129
+ }
130
+ // The marker polls the spawn store on a timer, so it goes with the runtime
131
+ // that owns that store; a reload mounts a fresh one in its place.
132
+ hideExtensionIndicator();
133
+ });
134
+ // Ensure the terminal cursor and buffer are ALWAYS restored when exiting
135
+ process.on("exit", () => {
136
+ try {
137
+ // \x1b[?2026l = End synchronized output mode (unfreezes buffered output)
138
+ // \x1b[?25h = Show hardware cursor (DECTCSR)
139
+ // \x1b[0m = Reset colors & text attributes (SGR reset)
140
+ process.stderr.write("\x1b[?2026l\x1b[?25h\x1b[0m");
141
+ }
142
+ catch {
143
+ // Ignore if streams are already closed
144
+ }
145
+ });
146
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * extension-toggle.ts — the persisted state of the on/off switch and the
3
+ * indicator setting, and the on-screen marker they decide.
4
+ */
5
+ import { getStore } from "./shell.js";
6
+ import { hideExtensionIndicator, showExtensionIndicator, } from "./ui/indicator.js";
7
+ export function isExtensionEnabled() {
8
+ return getStore().agent.extensionEnabled;
9
+ }
10
+ /** The marker needs both: an enabled extension, and the setting left on. */
11
+ function isActiveIndicatorShown() {
12
+ return isExtensionEnabled() && getStore().agent.showActiveIndicator;
13
+ }
14
+ /** Draw 🤠 while the marker is wanted, and take it down when it is not. */
15
+ export function syncExtensionIndicator(ui) {
16
+ if (isActiveIndicatorShown())
17
+ showExtensionIndicator(ui);
18
+ else
19
+ hideExtensionIndicator();
20
+ }
21
+ /**
22
+ * Persists the indicator setting and redraws the marker the new value calls
23
+ * for, so the setting takes effect the moment it is flipped.
24
+ */
25
+ export function setShowActiveIndicator(ui, show) {
26
+ getStore().mutate.agent.setShowActiveIndicator(show);
27
+ syncExtensionIndicator(ui);
28
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * harness-availability-launch.ts — ask PATH, once at launch, which harnesses this
3
+ * machine can launch, and let the shell answer for every later reader.
4
+ *
5
+ * The scan is synchronous, so the answer is in the shell before the first menu can
6
+ * open and there is no claim to defend: unlike the volume probe, this verdict
7
+ * cannot land out of order.
8
+ */
9
+ import { HARNESS_IDS } from "./agents/harness.js";
10
+ import { harnessFor } from "./agents/harness/registry.js";
11
+ import { probed } from "./availability.js";
12
+ import { setHarnessAvailability } from "./shell.js";
13
+ /**
14
+ * What this machine can launch: each id its own harness reports as launchable.
15
+ * Iterating the vocabulary, not a hand-written list, so a harness added to
16
+ * `HARNESS_IDS` is judged by the same rule rather than silently dropped.
17
+ */
18
+ export function detectHarnessAvailability() {
19
+ return probed(HARNESS_IDS.filter((id) => harnessFor(id).available()));
20
+ }
21
+ export function startHarnessAvailabilityProbe() {
22
+ setHarnessAvailability(detectHarnessAvailability());
23
+ }
package/dist/index.js ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * index.ts — herdr-pane subagents extension entry point.
3
+ * The tool's per-call `model` parameter is the caller's and is never written
4
+ * by the listener; config lives in ConfigStore.
5
+ */
6
+ import { setPiInstance, setRuntime, isInsideHerdr } from "./shell.js";
7
+ import { announceReadyForSpawn } from "./subagent/ipc-protocol.js";
8
+ import { createHerdrRuntime } from "./infrastructure/herdr-host.js";
9
+ import { missingCloneProgramReport } from "./infrastructure/git/cow-clone.js";
10
+ import { registerCowboyCommand, registerTools } from "./registration.js";
11
+ import { setupEventListeners } from "./events.js";
12
+ import { startCowSupportProbe } from "./cow-support-launch.js";
13
+ import { startHarnessAvailabilityProbe } from "./harness-availability-launch.js";
14
+ /**
15
+ * Report a failed prerequisite once the UI exists. The entry point has no
16
+ * context, so the message waits for the session event; the extension stays
17
+ * unregistered either way.
18
+ */
19
+ function reportInactive(pi, message) {
20
+ pi.on("session_start", async (_event, ctx) => {
21
+ if (ctx.hasUI) {
22
+ ctx.ui.notify(message, "error");
23
+ }
24
+ });
25
+ }
26
+ export default function (pi) {
27
+ // Subagents launch through the parent session's `herdr` CLI.
28
+ if (!isInsideHerdr())
29
+ return;
30
+ // Stay inert so subagents can never spawn further subagents — but first tell
31
+ // the parent this process booted.
32
+ if (announceReadyForSpawn())
33
+ return;
34
+ // A program the clone path needs is missing, so copy-on-write could never
35
+ // work here. Staying unregistered says so once; a volume that cannot clone
36
+ // still activates and falls back to a classic checkout.
37
+ const prereq = missingCloneProgramReport();
38
+ if (prereq !== undefined) {
39
+ reportInactive(pi, prereq);
40
+ return;
41
+ }
42
+ setPiInstance(pi);
43
+ setRuntime(createHerdrRuntime(pi));
44
+ // Registered once, here: the switch toggles them through the active set.
45
+ registerTools(pi);
46
+ registerCowboyCommand(pi);
47
+ setupEventListeners(pi);
48
+ // What the worktree volume can do decides which materializations stay on offer.
49
+ startCowSupportProbe(pi);
50
+ // Which harnesses are on PATH decides which stay on offer.
51
+ startHarnessAvailabilityProbe();
52
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * exec-path.ts — resolving a program the way a shell would, over this process's
3
+ * PATH. The clone path and the harness availability probe both ask this question,
4
+ * and both must answer it the same way.
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ /**
9
+ * Absolute path of the first executable `name` on PATH; undefined when there is
10
+ * none. Only a regular file counts: `X_OK` alone is also true of a directory, and
11
+ * a directory named after a program is not that program.
12
+ */
13
+ export function commandPath(name) {
14
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
15
+ if (dir === "")
16
+ continue;
17
+ const candidate = path.join(dir, name);
18
+ try {
19
+ // `statSync` follows a symlink, so a link to an executable counts and a
20
+ // broken or dangling one does not.
21
+ if (!fs.statSync(candidate).isFile())
22
+ continue;
23
+ fs.accessSync(candidate, fs.constants.X_OK);
24
+ return candidate;
25
+ }
26
+ catch {
27
+ // next directory
28
+ }
29
+ }
30
+ return undefined;
31
+ }
32
+ /** First executable `name` on PATH; the bare name if there is none. */
33
+ export function resolveCommand(name) {
34
+ return commandPath(name) ?? name;
35
+ }