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,244 @@
1
+ /**
2
+ * Model settings screen: global default row, per-type override rows, and clear entries.
3
+ *
4
+ * buildModelSettingsScreen: the screen as a Component (a submenu returns a Component, so it runs inside the caller's screen).
5
+ * buildModelOverridesRow: the topmost menu's "Model overrides" row hosting that screen in place.
6
+ *
7
+ * Overrides here write the configured precedence layers only; a per-call cowboy_agent `model`
8
+ * applies above them at the tool boundary and leaves no state here.
9
+ */
10
+ import { SettingsList, } from "@earendil-works/pi-tui";
11
+ import { getAgentConfig, getAllTypes } from "../../agents/agent-types.js";
12
+ import { agentBulletPrefix } from "../format.js";
13
+ import { getSessionCtx } from "../../shell.js";
14
+ import { buildModelGroups, hasExplicitPerTypeOverride, } from "../../models/model-groups.js";
15
+ import { findModelInRegistry } from "../../utils.js";
16
+ import { SettingsListWrapper } from "./wrappers/settings-list.js";
17
+ import { asSubmenuComponent } from "./screen-host.js";
18
+ import { createClearAllSubmenu, } from "./submenus/target-select.js";
19
+ import { createModelSelectSubmenu } from "./submenus/model-select.js";
20
+ import { SEPARATOR_ID, buildSettingsListTheme, createSearchableSelect, headerItem, } from "./helpers.js";
21
+ /** Pad level labels so every row's tag aligns ("minimal" is the longest at 7 chars). */
22
+ const THINKING_COLUMN_WIDTH = 7;
23
+ /** Global-default display value. Tags mark the winning non-global layer (session > project); untagged means global won. */
24
+ function defaultRowValue(sessionDefault, effectiveDefault, hasProjectDefault, parentModelId) {
25
+ if (sessionDefault != null)
26
+ return `${sessionDefault} [session]`;
27
+ // Nothing configures a default, so the chain falls through to the parent's model.
28
+ if (effectiveDefault == null)
29
+ return parentModelId == null ? "(no model)" : "(inherits parent)";
30
+ return hasProjectDefault ? `${effectiveDefault} [project]` : effectiveDefault;
31
+ }
32
+ function createModelOverridePlumbing(options) {
33
+ const { store, theme, modelOptions, notify, refresh } = options;
34
+ const projectOffered = store.isProjectWritable;
35
+ // Inherit picks null, which clears the key at the picked layer (ADR-0008 delete semantics).
36
+ const modelOverrideOnSelect = (key, label) => (target, model) => {
37
+ const inherits = model === null;
38
+ if (inherits)
39
+ store.mutate.agent.clearModelOverride(key, target);
40
+ else
41
+ store.mutate.agent.setModelOverride(key, model, target);
42
+ notify(inherits
43
+ ? `${label} inherits parent model`
44
+ : `${label} model set to ${model} (${target})`, "info");
45
+ if (inherits)
46
+ refresh();
47
+ };
48
+ const clearOverrideOnSelect = (key, label) => (target) => {
49
+ store.mutate.agent.clearModelOverride(key, target);
50
+ notify(`${label} override cleared (${target})`, "info");
51
+ };
52
+ return {
53
+ // availableLevels filters the nested clear picker (the default and per-type
54
+ // rows pass the levels where the key exists); set entries are never filtered.
55
+ modelSubmenuFor: (typeName, effectiveModel, showClear, availableLevels) => {
56
+ const onSet = modelOverrideOnSelect(typeName, typeName);
57
+ if (showClear) {
58
+ return createModelSelectSubmenu({
59
+ modelOptions,
60
+ showClear: true,
61
+ projectOffered,
62
+ theme,
63
+ currentModel: effectiveModel,
64
+ availableLevels,
65
+ onSet,
66
+ onClear: clearOverrideOnSelect(typeName, typeName),
67
+ });
68
+ }
69
+ return createModelSelectSubmenu({
70
+ modelOptions,
71
+ showClear: false,
72
+ projectOffered,
73
+ theme,
74
+ currentModel: effectiveModel,
75
+ availableLevels,
76
+ onSet,
77
+ });
78
+ },
79
+ levelsFor: (key) => ({
80
+ session: store.sessionModelOverride(key) != null,
81
+ global: store.hasGlobalModelKey(key),
82
+ project: store.hasProjectModelKey(key),
83
+ }),
84
+ };
85
+ }
86
+ /** The "Model Settings" screen as a Component a submenu can host in place. */
87
+ function buildModelSettingsScreen(options) {
88
+ const { ctx, store, theme, modelOptions, piDefaultThinking, close } = options;
89
+ let rebuild;
90
+ const buildItems = (theme) => {
91
+ const items = [];
92
+ const projectOffered = store.isProjectWritable;
93
+ const { levelsFor, modelSubmenuFor } = createModelOverridePlumbing({
94
+ store,
95
+ theme,
96
+ modelOptions,
97
+ notify: (message, type) => ctx.ui.notify(message, type),
98
+ // Inherit picks complete with no value, so refresh the row here.
99
+ refresh: () => rebuild?.(buildItems(theme)),
100
+ });
101
+ const session = getSessionCtx();
102
+ const parentModel = session.model ?? ctx.model;
103
+ const parentModelId = parentModel
104
+ ? `${parentModel.provider}/${parentModel.id}`
105
+ : null;
106
+ const agentConfigSnapshot = store.agentConfigSnapshot();
107
+ const sessionDefault = store.sessionDefaultModel;
108
+ const effectiveDefault = agentConfigSnapshot.default;
109
+ const globalDisplayValue = defaultRowValue(sessionDefault, effectiveDefault, store.hasProjectModelKey("default"), parentModelId);
110
+ const defaultLevels = levelsFor("default");
111
+ items.push({
112
+ id: "defaultModel",
113
+ label: "Global default model",
114
+ currentValue: globalDisplayValue,
115
+ description: "Model used when no session default, per-type override, or agent-template model applies.",
116
+ submenu: modelSubmenuFor("default", effectiveDefault, defaultLevels.session || defaultLevels.global || defaultLevels.project, defaultLevels),
117
+ });
118
+ // One group per resolved model with a listed row, alphabetical by model id.
119
+ const registry = session.modelRegistry;
120
+ const types = getAllTypes();
121
+ const sessionOverrides = {
122
+ default: store.sessionDefaultModel,
123
+ };
124
+ const agentConfigs = {};
125
+ for (const type of types) {
126
+ // Null reads as absent downstream.
127
+ sessionOverrides[type] = store.sessionModelOverride(type);
128
+ agentConfigs[type] = getAgentConfig(type);
129
+ }
130
+ const groups = buildModelGroups({
131
+ types,
132
+ agentConfigs,
133
+ config: agentConfigSnapshot,
134
+ sessionOverrides,
135
+ hasProjectModelKey: (key) => store.hasProjectModelKey(key),
136
+ parentModelId,
137
+ piDefaultThinking,
138
+ findModel: (modelId) => findModelInRegistry(modelId, registry, undefined),
139
+ });
140
+ for (const group of groups) {
141
+ items.push({ id: SEPARATOR_ID, label: " ", currentValue: "" });
142
+ // A null model id means no layer sets a model and the parent has none to inherit.
143
+ items.push(headerItem(theme, group.modelId ?? "(no model)"));
144
+ for (const row of group.rows) {
145
+ items.push({
146
+ id: `type:${row.type}`,
147
+ label: `${agentBulletPrefix(theme)}${row.type}`,
148
+ currentValue: `${row.thinking.padEnd(THINKING_COLUMN_WIDTH)} ${row.tag}`,
149
+ description: `Model for the ${row.type} agent type. Select to set or clear its override.`,
150
+ // Listed rows always carry an explicit override, so Clear is always offered.
151
+ submenu: modelSubmenuFor(row.type, group.modelId, true, levelsFor(row.type)),
152
+ });
153
+ }
154
+ }
155
+ items.push({
156
+ id: SEPARATOR_ID,
157
+ label: "─────────────────────────",
158
+ currentValue: "────────",
159
+ });
160
+ const nonOverridden = types.filter((type) => !hasExplicitPerTypeOverride(sessionOverrides, agentConfigSnapshot, type));
161
+ if (nonOverridden.length > 0) {
162
+ items.push({
163
+ id: "overrideType",
164
+ label: "Override another type...",
165
+ currentValue: "",
166
+ description: "Add a model override for an agent type that currently inherits.",
167
+ submenu: (_currentValue, subDone) => createSearchableSelect(nonOverridden.map((typeName) => ({
168
+ value: typeName,
169
+ label: `${agentBulletPrefix(theme)}${typeName}`,
170
+ })), {
171
+ onSelect: (typeName) => {
172
+ if (typeName == null)
173
+ return subDone();
174
+ const effectiveModel = store.modelFor(typeName, parentModelId, getAgentConfig(typeName));
175
+ return modelSubmenuFor(typeName, effectiveModel, false)(effectiveModel ?? "", subDone);
176
+ },
177
+ onCancel: () => subDone(),
178
+ }, theme),
179
+ });
180
+ }
181
+ items.push({ id: SEPARATOR_ID, label: " ", currentValue: "" });
182
+ // Each level is offered only when it has model settings.
183
+ const availableLevels = {
184
+ session: store.hasSessionModelSettings,
185
+ global: store.hasGlobalModelSettings,
186
+ project: store.hasProjectModelSettings && projectOffered,
187
+ };
188
+ if (availableLevels.session ||
189
+ availableLevels.global ||
190
+ availableLevels.project) {
191
+ items.push({
192
+ id: "clearAll",
193
+ label: "Clear all model overrides...",
194
+ currentValue: "",
195
+ description: "Discard model overrides at the chosen level (session, global, project, or all).",
196
+ submenu: createClearAllSubmenu({
197
+ theme,
198
+ projectOffered,
199
+ availableLevels,
200
+ message: (target) => `Clear all model overrides at the ${target} level?`,
201
+ onConfirm: (target) => {
202
+ store.mutate.agent.clearAllModelOverrides(target);
203
+ ctx.ui.notify(`Model overrides cleared (${target})`, "info");
204
+ },
205
+ }),
206
+ });
207
+ }
208
+ return items;
209
+ };
210
+ const settingsList = new SettingsList(buildItems(theme), 15, buildSettingsListTheme(theme), (_id, _v) => rebuild?.(buildItems(theme)), close);
211
+ const screen = new SettingsListWrapper(settingsList, {
212
+ title: "Model Settings",
213
+ theme,
214
+ onCancel: close,
215
+ onRebuild: (r) => {
216
+ rebuild = r;
217
+ },
218
+ });
219
+ return asSubmenuComponent(screen);
220
+ }
221
+ /** The topmost menu's "Model overrides" row, owning the whole model screen; its value summarizes the global default. */
222
+ export function buildModelOverridesRow(options) {
223
+ const { ctx, store, theme, modelOptions, piDefaultThinking } = options;
224
+ const defaultDisplay = () => {
225
+ const session = getSessionCtx();
226
+ const parentModel = session.model ?? ctx.model;
227
+ return defaultRowValue(store.sessionDefaultModel, store.agentConfigSnapshot().default, store.hasProjectModelKey("default"), parentModel ? `${parentModel.provider}/${parentModel.id}` : null);
228
+ };
229
+ return {
230
+ id: "modelOverrides",
231
+ label: "Model overrides",
232
+ currentValue: defaultDisplay(),
233
+ description: "Global default model plus per-type model overrides; opens the model settings screen.",
234
+ submenu: (_currentValue, done) => buildModelSettingsScreen({
235
+ ctx,
236
+ store,
237
+ theme,
238
+ modelOptions,
239
+ piDefaultThinking,
240
+ // Forward the fresh value so the row repaints without reopening the command.
241
+ close: () => done(defaultDisplay()),
242
+ }),
243
+ };
244
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * menu-spawn-defaults.ts — the spawn-defaults rows the topmost agents menu hosts:
3
+ * the default agent type and the default orchestrator, each with its picker.
4
+ *
5
+ * A pick pre-selects the value in force and persists through the store, so the
6
+ * row's host repaints from the store rather than from the picker's return.
7
+ */
8
+ import { getAgentConfig, getAvailableTypes } from "../../agents/agent-types.js";
9
+ import { getAvailableOrchestrators } from "../../orchestrators/orchestrator-types.js";
10
+ import { DEFAULT_ORCHESTRATORS } from "../../orchestrators/default-orchestrators.js";
11
+ import { DEFAULT_AGENT_TYPE, DEFAULT_ORCHESTRATOR_NAME } from "../../types.js";
12
+ import { SearchableSelectDialog } from "../searchable-select.js";
13
+ /** Picker over registered agent types (current default carries ✓); applies to the next spawn. */
14
+ function createAgentTypeSubmenu(store, notify, theme) {
15
+ return (_currentValue, done) => {
16
+ const available = getAvailableTypes();
17
+ const names = available.length > 0 ? available : [DEFAULT_AGENT_TYPE];
18
+ const items = names.map((name) => ({
19
+ value: name,
20
+ label: name,
21
+ provider: getAgentConfig(name)?.description ?? "",
22
+ }));
23
+ return new SearchableSelectDialog(items, store.agent.defaultAgentType, {
24
+ onSelect: (value) => {
25
+ if (value != null) {
26
+ store.mutate.agent.setDefaultAgentType(value);
27
+ notify(`Agent set to ${value}`, "info");
28
+ }
29
+ done(value ?? undefined);
30
+ },
31
+ onCancel: () => done(),
32
+ }, theme);
33
+ };
34
+ }
35
+ /** Picker over registered orchestrators (code defaults when the registry is empty); current default carries ✓. */
36
+ function createOrchestratorSubmenu(store, notify, theme) {
37
+ return (_currentValue, done) => {
38
+ const available = getAvailableOrchestrators();
39
+ const names = available.length > 0 ? available : Object.keys(DEFAULT_ORCHESTRATORS);
40
+ const items = names.map((name) => ({ value: name, label: name }));
41
+ return new SearchableSelectDialog(items, store.agent.defaultOrchestrator, {
42
+ onSelect: (value) => {
43
+ if (value != null) {
44
+ store.mutate.agent.setDefaultOrchestrator(value);
45
+ notify(`Default orchestrator set to ${value}`, "info");
46
+ }
47
+ done(value ?? undefined);
48
+ },
49
+ onCancel: () => done(),
50
+ }, theme);
51
+ };
52
+ }
53
+ export function buildDefaultAgentTypeRow(options) {
54
+ return {
55
+ id: "defaultAgentType",
56
+ label: "Agent",
57
+ currentValue: options.store.agent.defaultAgentType,
58
+ submenu: createAgentTypeSubmenu(options.store, options.notify, options.theme),
59
+ description: `Agent type used when cowboy_agent omits \`agent_type\`. Default: ${DEFAULT_AGENT_TYPE}.`,
60
+ };
61
+ }
62
+ /** The persisted default orchestrator: every spawn resolves its orchestration template from this row alone. */
63
+ export function buildDefaultOrchestratorRow(options) {
64
+ return {
65
+ id: "defaultOrchestrator",
66
+ label: "Default orchestrator",
67
+ currentValue: options.store.agent.defaultOrchestrator,
68
+ submenu: createOrchestratorSubmenu(options.store, options.notify, options.theme),
69
+ description: `Orchestration template used for every cowboy_agent spawn; the tool accepts no per-call orchestrator input. Default: ${DEFAULT_ORCHESTRATOR_NAME}.`,
70
+ };
71
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Spawn agent wizard: options → worktree name (when new) → prompt → spawn.
3
+ */
4
+ import { SettingsList, SelectList, } from "@earendil-works/pi-tui";
5
+ import { getSupportedThinkingLevels, clampThinkingLevel, } from "@earendil-works/pi-ai";
6
+ import { getAgentConfig, getAvailableTypes } from "../../agents/agent-types.js";
7
+ import { resolveDefaultAgentType, resolveDefaultOrchestrator, resolveWorktreeCheckoutType, } from "../../agents/spawn-defaults.js";
8
+ import { findModelInRegistry } from "../../utils.js";
9
+ import { agentBulletPrefix } from "../format.js";
10
+ import { getManager, getPiInstance, getSessionCtx, getStore, getCoordinator, getRuntime, getWorktreeMaterialization, } from "../../shell.js";
11
+ import { AgentSandbox, formatLaunchCleanupNote } from "../../spawn/sandbox.js";
12
+ import { SEPARATOR_ID, actionReport, buildSettingsListTheme, buildSelectListTheme, withVimKeys, } from "./helpers.js";
13
+ import { CLOSED_SUBMENU, ScreenHost } from "./screen-host.js";
14
+ import { createModelSelectSubmenu } from "./submenus/model-select.js";
15
+ import { buildWorktreeRow, loadWorktreeChoices, showWorktreeNameStep, } from "./menu-spawn-worktree.js";
16
+ import { createInputSubmenu } from "./submenus/numeric-input.js";
17
+ import { createTextEditor } from "./submenus/text-editor.js";
18
+ import { SettingsListWrapper } from "./wrappers/settings-list.js";
19
+ /** How much of the prompt a derived description keeps. */
20
+ const DERIVED_DESCRIPTION_MAX_LENGTH = 50;
21
+ function createThinkingLevelSubmenu(registry, currentModelStr, fallbackModel, theme, onThinkingChange) {
22
+ return (_currentValue, done) => {
23
+ const model = findModelInRegistry(currentModelStr, registry, fallbackModel);
24
+ if (!model) {
25
+ done();
26
+ return CLOSED_SUBMENU;
27
+ }
28
+ const supported = getSupportedThinkingLevels(model);
29
+ const isReasoning = model.reasoning;
30
+ const items = supported.map((level) => ({
31
+ value: level,
32
+ label: level === "off"
33
+ ? "Off"
34
+ : level.charAt(0).toUpperCase() + level.slice(1),
35
+ description: !isReasoning ? "(not supported by this model)" : undefined,
36
+ }));
37
+ if (isReasoning) {
38
+ items.push({ value: "inherit", label: "Inherit" });
39
+ }
40
+ const list = withVimKeys(new SelectList(items, 10, buildSelectListTheme(theme)));
41
+ list.onSelect = (item) => {
42
+ onThinkingChange(item.value === "inherit" ? undefined : item.value);
43
+ done(item.value);
44
+ };
45
+ list.onCancel = () => done();
46
+ return list;
47
+ };
48
+ }
49
+ /** Multi-step spawn wizard: options → worktree name (when new) → prompt → spawn. */
50
+ export async function showSpawnAgentMenu(ctx, modelOptions) {
51
+ const types = getAvailableTypes();
52
+ if (types.length === 0) {
53
+ ctx.ui.notify("No agent types available", "error");
54
+ return;
55
+ }
56
+ // The configured default leads; a value that no longer resolves falls to the first type.
57
+ const configuredType = resolveDefaultAgentType();
58
+ let selectedType = types.includes(configuredType) ? configuredType : types[0];
59
+ const session = getSessionCtx();
60
+ const parentCwd = session.cwd;
61
+ // No cwd, or a cwd outside git, leaves the wizard without a Worktree row.
62
+ const worktrees = await loadWorktreeChoices(getPiInstance(), parentCwd);
63
+ const store = getStore();
64
+ const parentModelId = session.model
65
+ ? `${session.model.provider}/${session.model.id}`
66
+ : null;
67
+ /** Effective model for a type, resolved per call so a type change re-derives it. */
68
+ const modelForType = (type) => store.modelFor(type, parentModelId, getAgentConfig(type)) ?? "";
69
+ let currentModelStr = modelForType(selectedType);
70
+ let currentThinking = getAgentConfig(selectedType)?.thinkingLevel ?? store.agent.defaultThinking;
71
+ let currentBackground = true;
72
+ let forkState = getAgentConfig(selectedType)?.fork ?? false;
73
+ // A new worktree is the default, and its name is asked after Spawn.
74
+ let worktreeChoice = worktrees
75
+ ? { kind: "new" }
76
+ : { kind: "inherit" };
77
+ let currentDescription = "";
78
+ /** Launch defaults follow the type, as they did when the type led the wizard. */
79
+ const applyType = (type) => {
80
+ selectedType = type;
81
+ const config = getAgentConfig(type);
82
+ currentModelStr = modelForType(type);
83
+ currentThinking = config?.thinkingLevel ?? store.agent.defaultThinking;
84
+ forkState = config?.fork ?? false;
85
+ };
86
+ const buildItems = () => {
87
+ // Empty when the whole chain is unset and the parent has no model either.
88
+ const displayModel = currentModelStr || "(no model)";
89
+ const items = [
90
+ {
91
+ id: "spawn",
92
+ label: "Spawn",
93
+ currentValue: "",
94
+ description: "Ask for the worktree name and prompt, then launch",
95
+ submenu: (_v, subDone) => {
96
+ let modelSelection;
97
+ if (currentModelStr) {
98
+ const model = findModelInRegistry(currentModelStr, session.modelRegistry, undefined);
99
+ if (!model) {
100
+ ctx.ui.notify(`Model not found: ${currentModelStr}`, "error");
101
+ subDone();
102
+ return CLOSED_SUBMENU;
103
+ }
104
+ modelSelection = {
105
+ model,
106
+ key: `${model.provider}/${model.id}`,
107
+ };
108
+ }
109
+ closeConfig({
110
+ type: selectedType,
111
+ modelSelection,
112
+ thinkingLevel: currentThinking,
113
+ worktreeChoice,
114
+ description: currentDescription,
115
+ fork: forkState,
116
+ runInBackground: currentBackground,
117
+ });
118
+ return CLOSED_SUBMENU;
119
+ },
120
+ },
121
+ {
122
+ id: SEPARATOR_ID,
123
+ label: " ",
124
+ currentValue: "",
125
+ },
126
+ {
127
+ id: "type",
128
+ label: "Type",
129
+ currentValue: selectedType,
130
+ description: getAgentConfig(selectedType)?.description ?? "Agent type",
131
+ submenu: (_v, outerDone) => {
132
+ const list = new SettingsList(types.map((type) => ({
133
+ id: type,
134
+ label: `${agentBulletPrefix(theme)}${type}`,
135
+ currentValue: type,
136
+ description: getAgentConfig(type)?.description ?? "Agent type",
137
+ submenu: (_tv, _subDone) => {
138
+ outerDone(type);
139
+ return CLOSED_SUBMENU;
140
+ },
141
+ })), 10, buildSettingsListTheme(theme), () => { }, () => outerDone(), { enableSearch: true });
142
+ // Reopening the row lands on the type in force, not the top of the list.
143
+ list.selectItem(selectedType);
144
+ return list;
145
+ },
146
+ },
147
+ {
148
+ id: "model",
149
+ label: "Model",
150
+ currentValue: displayModel,
151
+ description: "Override the default model for this agent",
152
+ submenu: createModelSelectSubmenu({
153
+ modelOptions,
154
+ showClear: false,
155
+ projectOffered: store.isProjectWritable,
156
+ theme,
157
+ onSet: (_target, model) => {
158
+ currentModelStr = model ?? "";
159
+ if (currentThinking != null && currentModelStr) {
160
+ const registry = session.modelRegistry;
161
+ const resolved = findModelInRegistry(currentModelStr, registry, session.model);
162
+ if (resolved) {
163
+ const clamped = clampThinkingLevel(resolved, currentThinking);
164
+ currentThinking = clamped;
165
+ }
166
+ }
167
+ // Rebuild so displayed values reflect the clamp.
168
+ rebuild?.(buildItems());
169
+ },
170
+ }),
171
+ },
172
+ {
173
+ id: "background",
174
+ label: "Background",
175
+ currentValue: currentBackground ? "ON" : "OFF",
176
+ description: "Run the agent in the background",
177
+ values: ["ON", "OFF"],
178
+ },
179
+ {
180
+ id: "fork",
181
+ label: "Fork session",
182
+ currentValue: forkState ? "Yes" : "No",
183
+ description: "Fork the parent session context into the subagent",
184
+ values: ["Yes", "No"],
185
+ },
186
+ ...(worktrees
187
+ ? [
188
+ buildWorktreeRow(worktrees, {
189
+ current: worktreeChoice,
190
+ theme,
191
+ onPick: (pick) => {
192
+ worktreeChoice = pick;
193
+ },
194
+ }),
195
+ ]
196
+ : []),
197
+ {
198
+ id: "thinkingLevel",
199
+ label: "Thinking level",
200
+ currentValue: currentThinking ?? "inherit",
201
+ description: "Set the reasoning effort level",
202
+ submenu: createThinkingLevelSubmenu(session.modelRegistry, currentModelStr, session.model, theme, (level) => {
203
+ currentThinking = level;
204
+ }),
205
+ },
206
+ { id: SEPARATOR_ID, label: " ", currentValue: "" },
207
+ {
208
+ id: "description",
209
+ label: "Description",
210
+ currentValue: currentDescription,
211
+ description: "Short label shown in the agents list; derived from the prompt when left empty",
212
+ submenu: createInputSubmenu(ctx),
213
+ },
214
+ ];
215
+ return items;
216
+ };
217
+ let theme;
218
+ let closeConfig;
219
+ let rebuild;
220
+ /** Creates the named worktree for `agentType`; undefined when it could not be created (already notified). */
221
+ const allocateWorktree = async (branch, agentType) => {
222
+ try {
223
+ return await AgentSandbox.allocate(getPiInstance(), {
224
+ naming: { kind: "explicit", branch },
225
+ parentCwd,
226
+ worktreeRoot: store.agent.worktreeRoot,
227
+ materialization: getWorktreeMaterialization(),
228
+ dirtyCheckout: resolveWorktreeCheckoutType(agentType),
229
+ notify: (message, kind) => ctx.ui.notify(message, kind),
230
+ host: getRuntime().host,
231
+ });
232
+ }
233
+ catch (err) {
234
+ ctx.ui.notify(`Worktree creation failed: ${err instanceof Error ? err.message : String(err)}`, "error");
235
+ return undefined;
236
+ }
237
+ };
238
+ /** Launches the configured run; a `new` worktree is created here so a cancelled wizard leaves none behind. */
239
+ const launch = async (configuration, worktree, prompt) => {
240
+ const pi = getPiInstance();
241
+ // Minted before the worktree so the in-progress line names the handle
242
+ // stop, cleanup, and steer will take.
243
+ const spawnId = getManager().mintSpawnId();
244
+ actionReport(ctx.ui).pending(`Spawning agent ${spawnId} (${configuration.type})`);
245
+ let sandbox;
246
+ if (worktree.kind === "new") {
247
+ sandbox = await allocateWorktree(worktree.branch, configuration.type);
248
+ if (!sandbox)
249
+ return;
250
+ }
251
+ // The run's worktree: the one just allocated, or a picked pre-existing one
252
+ // (which the run works inside without owning). Absent for parent-cwd runs.
253
+ const created = sandbox?.worktree;
254
+ const runWorktree = created !== undefined
255
+ ? { kind: "owned", path: created.path, branch: created.branch }
256
+ : worktree.kind === "picked"
257
+ ? {
258
+ kind: "picked",
259
+ path: worktree.path,
260
+ branch: worktree.branch,
261
+ }
262
+ : undefined;
263
+ const description = configuration.description.trim() !== ""
264
+ ? configuration.description
265
+ : (prompt.split("\n", 1)[0] ?? "").slice(0, DERIVED_DESCRIPTION_MAX_LENGTH);
266
+ const coordinator = getCoordinator();
267
+ const orchestration = resolveDefaultOrchestrator();
268
+ try {
269
+ await coordinator.spawn(session, {
270
+ spawnId,
271
+ type: configuration.type,
272
+ prompt,
273
+ description,
274
+ orchestration,
275
+ modelSelection: configuration.modelSelection,
276
+ thinkingLevel: configuration.thinkingLevel,
277
+ worktree: runWorktree,
278
+ hostRef: sandbox?.hostRef,
279
+ projectTrusted: sandbox?.projectTrusted,
280
+ invocation: {
281
+ modelName: configuration.modelSelection?.model.id,
282
+ thinkingLevel: configuration.thinkingLevel,
283
+ runInBackground: configuration.runInBackground,
284
+ fork: configuration.fork,
285
+ },
286
+ runInBackground: configuration.runInBackground,
287
+ fork: configuration.fork,
288
+ });
289
+ }
290
+ catch (err) {
291
+ const message = `Spawn failed: ${err instanceof Error ? err.message : String(err)}`;
292
+ if (!sandbox) {
293
+ ctx.ui.notify(message, "error");
294
+ return;
295
+ }
296
+ // The worktree the spawn would have owned is cleaned up here.
297
+ const outcome = await sandbox.teardown(pi);
298
+ ctx.ui.notify(`${message}\n\n${formatLaunchCleanupNote(outcome)}`, "error");
299
+ }
300
+ };
301
+ const host = new ScreenHost(ctx);
302
+ const configuration = await host.open(({ theme: screenTheme, close }) => {
303
+ theme = screenTheme;
304
+ closeConfig = close;
305
+ const onChange = (id, newValue) => {
306
+ switch (id) {
307
+ case "type":
308
+ applyType(newValue);
309
+ break;
310
+ case "thinkingLevel":
311
+ currentThinking =
312
+ newValue === "inherit" ? undefined : newValue;
313
+ break;
314
+ case "background":
315
+ currentBackground = newValue === "ON";
316
+ break;
317
+ case "fork":
318
+ forkState = newValue === "Yes";
319
+ break;
320
+ case "description":
321
+ currentDescription = newValue;
322
+ break;
323
+ }
324
+ // Rebuild so displayed values stay in sync after any change.
325
+ rebuild?.(buildItems());
326
+ };
327
+ const settingsList = new SettingsList(buildItems(), 15, buildSettingsListTheme(theme), onChange, close);
328
+ return new SettingsListWrapper(settingsList, {
329
+ title: "Spawn Options",
330
+ theme,
331
+ onCancel: close,
332
+ onRebuild: (r) => {
333
+ rebuild = r;
334
+ },
335
+ });
336
+ });
337
+ if (configuration === undefined)
338
+ return;
339
+ // A "New worktree" choice is only a decision; its name arrives here, on the way
340
+ // to the run, so the config screen never holds a half-answered target.
341
+ let worktree;
342
+ if (configuration.worktreeChoice.kind === "new") {
343
+ const branch = await showWorktreeNameStep(host, (message, kind) => ctx.ui.notify(message, kind));
344
+ if (branch === undefined)
345
+ return;
346
+ worktree = { kind: "new", branch };
347
+ }
348
+ else {
349
+ worktree = configuration.worktreeChoice;
350
+ }
351
+ // Optional: an empty prompt launches the agent with no task to start on.
352
+ const prompt = await host.open(({ tui, theme: screenTheme, keybindings, close }) => new SettingsListWrapper(createTextEditor({
353
+ prefill: "",
354
+ onDone: (text) => close(text),
355
+ onCancel: () => close(),
356
+ tui,
357
+ theme: screenTheme,
358
+ keybindings,
359
+ }), {
360
+ title: "Agent Prompt (optional)",
361
+ theme: screenTheme,
362
+ passthroughKeys: true,
363
+ }));
364
+ if (prompt === undefined)
365
+ return;
366
+ await launch(configuration, worktree, prompt);
367
+ }