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,160 @@
1
+ /**
2
+ * Subagent model selection via pi's own model picker.
3
+ *
4
+ * openSubagentModelPicker: opens the /model dialog; a pick sets the SESSION default override.
5
+ * cowboyCompletions: `/cowboy` subcommand completions (`status`, `spawn`, `worktree`, `model`, `enable`, `disable`), the `model` ones carrying full argument text.
6
+ * handleModelArg: `clear` clears the session default, an exact key sets it, else the picker opens.
7
+ *
8
+ * A per-call cowboy_agent `model` wins for one spawn at the tool boundary without touching stored state.
9
+ * The ModelRuntime hides behind ctx.modelRegistry's private `runtime` field; when unreachable,
10
+ * the picker falls back to SearchableSelectDialog.
11
+ */
12
+ import { ModelSelectorComponent, } from "@earendil-works/pi-coding-agent";
13
+ import { fuzzyFilter } from "@earendil-works/pi-tui";
14
+ import { getSessionCtx, getStore } from "../../shell.js";
15
+ import { findModelInRegistry } from "../../utils.js";
16
+ import { SearchableSelectDialog } from "../searchable-select.js";
17
+ import { buildModelOptions } from "./helpers.js";
18
+ import { ScreenHost } from "./screen-host.js";
19
+ /** Set the session default model. In-memory only (cleared at session_start); other layers live in Model settings. */
20
+ function applySessionDefault(store, ctx, model) {
21
+ const key = `${model.provider}/${model.id}`;
22
+ store.mutate.session.setOverride("default", key);
23
+ ctx.ui.notify(`Subagent model set to ${key} (session)`, "info");
24
+ }
25
+ /** The model currently in effect for sub-agents (session → config → parent). */
26
+ function currentSubagentModel(ctx) {
27
+ const store = getStore();
28
+ const session = getSessionCtx();
29
+ const parentModelId = session.model ?? ctx.model;
30
+ const parentKey = parentModelId
31
+ ? `${parentModelId.provider}/${parentModelId.id}`
32
+ : null;
33
+ const currentKey = store.sessionDefaultModel ??
34
+ store.agentConfigSnapshot().default ??
35
+ parentKey;
36
+ return currentKey
37
+ ? findModelInRegistry(currentKey, ctx.modelRegistry, ctx.model)
38
+ : undefined;
39
+ }
40
+ function sessionModelRuntime(ctx) {
41
+ const runtime = ctx.modelRegistry.runtime;
42
+ return runtime && typeof runtime.getAvailableSnapshot === "function"
43
+ ? runtime
44
+ : undefined;
45
+ }
46
+ export async function openSubagentModelPicker(ctx, opts) {
47
+ const store = getStore();
48
+ const runtime = sessionModelRuntime(ctx);
49
+ const scoped = ctx.scopedModels;
50
+ await new ScreenHost(ctx).open(({ tui, theme, close }) => {
51
+ const current = currentSubagentModel(ctx);
52
+ if (!runtime) {
53
+ const session = getSessionCtx();
54
+ const registry = session.modelRegistry;
55
+ const keys = registry.getAvailable().map((m) => `${m.provider}/${m.id}`);
56
+ const items = buildModelOptions(keys, current?.id ?? null, []).filter((o) => o.value != null);
57
+ const dialog = new SearchableSelectDialog(items, current ? `${current.provider}/${current.id}` : null, {
58
+ onSelect: (value) => {
59
+ const model = findModelInRegistry(value, registry, undefined);
60
+ if (model)
61
+ applySessionDefault(store, ctx, model);
62
+ close();
63
+ },
64
+ onCancel: () => close(),
65
+ }, theme);
66
+ return dialog;
67
+ }
68
+ const selector = new ModelSelectorComponent(tui, current, runtime, scoped, (model) => {
69
+ applySessionDefault(store, ctx, model);
70
+ close();
71
+ }, () => close(), opts?.initialSearch);
72
+ return selector;
73
+ });
74
+ }
75
+ /** `model` subcommand completions. Values carry full argument text, matching pi's prefix replacement. */
76
+ export function cowboyCompletions(prefix) {
77
+ const text = prefix;
78
+ const trimmed = text.trim();
79
+ if (trimmed === "model" || trimmed.startsWith("model ")) {
80
+ const rest = trimmed.slice("model".length).trim();
81
+ const models = availableModelsForCompletion();
82
+ const items = [
83
+ {
84
+ value: "model clear",
85
+ label: "clear",
86
+ description: "Clear the session model override (inherit parent/configured default)",
87
+ },
88
+ ...models.map((m) => ({
89
+ value: `model ${m.provider}/${m.id}`,
90
+ label: m.id,
91
+ description: m.provider,
92
+ })),
93
+ ];
94
+ const filtered = fuzzyFilter(items, rest, (i) => `${i.label} ${i.description ?? ""} ${i.value}`);
95
+ return filtered.length > 0 ? filtered : null;
96
+ }
97
+ const items = [
98
+ {
99
+ value: "status",
100
+ label: "status",
101
+ description: "List spawned, queued and settled agents",
102
+ },
103
+ {
104
+ value: "spawn",
105
+ label: "spawn",
106
+ description: "Open the spawn wizard",
107
+ },
108
+ {
109
+ value: "worktree",
110
+ label: "worktree",
111
+ description: "Create a git worktree with no agent attached",
112
+ },
113
+ {
114
+ value: "model",
115
+ label: "model",
116
+ description: "Set the model sub-agents use (opens pi's model picker)",
117
+ },
118
+ {
119
+ value: "enable",
120
+ label: "enable",
121
+ description: "Enable pi-cowboy",
122
+ },
123
+ {
124
+ value: "disable",
125
+ label: "disable",
126
+ description: "Disable pi-cowboy",
127
+ },
128
+ ];
129
+ const filtered = fuzzyFilter(items, trimmed, (i) => i.label);
130
+ return filtered.length > 0 ? filtered : null;
131
+ }
132
+ function availableModelsForCompletion() {
133
+ const session = getSessionCtx();
134
+ const scoped = session.scopedModels;
135
+ if (scoped.length > 0) {
136
+ return scoped.map((s) => s.model);
137
+ }
138
+ try {
139
+ return session.modelRegistry.getAvailable();
140
+ }
141
+ catch {
142
+ return [];
143
+ }
144
+ }
145
+ export async function handleModelArg(value, ctx) {
146
+ const store = getStore();
147
+ if (value === "clear") {
148
+ store.mutate.session.clearOverride("default");
149
+ ctx.ui.notify("Subagent model override cleared (session) — inherits parent/configured default", "info");
150
+ return;
151
+ }
152
+ if (value !== "") {
153
+ const model = findModelInRegistry(value, ctx.modelRegistry, undefined);
154
+ if (model) {
155
+ applySessionDefault(store, ctx, model);
156
+ return;
157
+ }
158
+ }
159
+ await openSubagentModelPicker(ctx, value !== "" ? { initialSearch: value } : undefined);
160
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * screen-host.ts — how the /cowboy screens open and close, and the submenu
3
+ * boundary a screen shares with the list that hosts it.
4
+ *
5
+ * `ScreenHost.open` is one `ctx.ui.custom` call per screen: the builder is handed
6
+ * the theme, the keybindings and the close callback, and the call resolves with
7
+ * what the screen closed with (no value = the user cancelled). pi-tui's custom is
8
+ * modal, so a flow that continues opens its next screen once the previous one
9
+ * resolves; nothing here keeps a stack of screens inside one call.
10
+ *
11
+ * A `SettingItem.submenu` factory returns a Component pi-tui renders in place of
12
+ * the list's rows until the factory's `done` runs, so that boundary needs three
13
+ * shapes of its own: a marker for a factory that completes instead of hosting
14
+ * (`CLOSED_SUBMENU`), a flag marking a hosted screen as the owner of every key
15
+ * (`asSubmenuComponent`), and a view whose body swaps while the frame around it
16
+ * stays put (`SwappableView`).
17
+ */
18
+ import { isFocusable, } from "@earendil-works/pi-tui";
19
+ /** Opens screens through `ctx.ui.custom`, one call each. */
20
+ export class ScreenHost {
21
+ ctx;
22
+ /** The command context these screens belong to (its ui sink, cwd, model). */
23
+ constructor(ctx) {
24
+ this.ctx = ctx;
25
+ }
26
+ /** Open a screen on its own; resolves undefined when the user cancelled. */
27
+ async open(build) {
28
+ return await this.show(build, false);
29
+ }
30
+ /** Open a screen over the one below, for content that reads better on top. */
31
+ async openOverlay(build) {
32
+ return await this.show(build, true);
33
+ }
34
+ async show(build, overlay) {
35
+ return await this.ctx.ui.custom((tui, theme, keybindings, done) => build({ tui, theme, keybindings, close: (result) => done(result) }), overlay ? { overlay: true } : undefined);
36
+ }
37
+ }
38
+ /**
39
+ * Close the submenu a factory is building. pi-tui stores the factory's return
40
+ * value as the row's open submenu and only a falsy one leaves it closed, while
41
+ * `SettingItem.submenu` promises a Component — the cast marks that boundary.
42
+ */
43
+ export const CLOSED_SUBMENU = undefined;
44
+ /**
45
+ * Host a screen as a submenu, where it owns every key. Our frame asks
46
+ * `isFocusable` before it remaps j/k or the horizontal arrows, so the child has
47
+ * to carry a `focused` field to claim them; pi-tui's own lists declare none.
48
+ */
49
+ export function asSubmenuComponent(screen) {
50
+ return Object.assign(screen, { focused: true });
51
+ }
52
+ /**
53
+ * One in-place view whose body swaps: the agent list → a per-agent actions list,
54
+ * a search dialog → the field it opens. The frame around it keeps talking to the
55
+ * same object while reads, writes, rendering and keys follow the body showing.
56
+ */
57
+ export class SwappableView {
58
+ active;
59
+ constructor(initial) {
60
+ this.active = initial;
61
+ }
62
+ /** Show `body` in place of the body showing now. */
63
+ activate(body) {
64
+ this.active = body;
65
+ }
66
+ invalidate() {
67
+ this.active.invalidate();
68
+ }
69
+ render(width) {
70
+ return this.active.render(width);
71
+ }
72
+ handleInput(data) {
73
+ this.active.handleInput?.(data);
74
+ }
75
+ /** Key ownership follows the body, and is what marks this view as a leaf. */
76
+ get focused() {
77
+ return isFocusable(this.active) ? this.active.focused : false;
78
+ }
79
+ set focused(value) {
80
+ if (isFocusable(this.active))
81
+ this.active.focused = value;
82
+ }
83
+ }
84
+ /** Read pi-tui's private list fields from the list instance. */
85
+ export function asListFields(list) {
86
+ return list;
87
+ }
@@ -0,0 +1,23 @@
1
+ /** confirm-submenu.ts — yes/no confirm dialog for destructive SettingsList rows. */
2
+ import { SelectList } from "@earendil-works/pi-tui";
3
+ import { buildSelectListTheme, withVimKeys } from "../helpers.js";
4
+ export function createConfirmSubmenu(options) {
5
+ return (_currentValue, done) => {
6
+ const items = [
7
+ { value: "Yes", label: "Yes", description: options.message },
8
+ { value: "No", label: "No", description: options.message },
9
+ ];
10
+ const list = withVimKeys(new SelectList(items, 5, buildSelectListTheme(options.theme)));
11
+ list.onSelect = (item) => {
12
+ if (item.value === "Yes") {
13
+ options.onConfirm();
14
+ done("Yes");
15
+ }
16
+ else {
17
+ done();
18
+ }
19
+ };
20
+ list.onCancel = () => done();
21
+ return list;
22
+ };
23
+ }
@@ -0,0 +1,42 @@
1
+ /** model-select-submenu.ts — level picker, then model search (ADR-0008). Create inside ctx.ui.custom to capture the theme. */
2
+ import { SearchableSelectDialog } from "../../../ui/searchable-select.js";
3
+ import { buildModelOptions, extractConfiguredModels } from "../helpers.js";
4
+ import { getStore } from "../../../shell.js";
5
+ import { buildLevelItems, createClearPickerSubmenu, createLevelPickerSubmenu, } from "./target-select.js";
6
+ export function createModelSelectSubmenu(options) {
7
+ // Null (inherit) pre-selects the inherit row; a model id pre-selects its row.
8
+ const currentModel = options.currentModel ?? null;
9
+ const onClear = options.showClear === true ? options.onClear : undefined;
10
+ return createLevelPickerSubmenu({
11
+ theme: options.theme,
12
+ items: buildLevelItems({
13
+ offered: { session: true, global: true, project: options.projectOffered },
14
+ includeClear: onClear !== undefined,
15
+ }),
16
+ onPick: (id, subDone, completePicker) => {
17
+ if (id === "clear") {
18
+ return createClearPickerSubmenu({
19
+ theme: options.theme,
20
+ projectOffered: options.projectOffered,
21
+ availableLevels: options.availableLevels,
22
+ onClear: (target) => onClear?.(target),
23
+ })("", subDone);
24
+ }
25
+ const target = id;
26
+ const store = getStore();
27
+ const configuredModels = extractConfiguredModels(store.agentConfigSnapshot());
28
+ return new SearchableSelectDialog(buildModelOptions(options.modelOptions, currentModel, configuredModels), currentModel, {
29
+ onSelect: (modelValue) => {
30
+ options.onSet(target, modelValue);
31
+ // The library forwards only a DEFINED value, so the null inherit
32
+ // row must complete the level picker explicitly.
33
+ if (modelValue == null)
34
+ completePicker();
35
+ else
36
+ subDone(modelValue);
37
+ },
38
+ onCancel: () => subDone(),
39
+ }, options.theme);
40
+ },
41
+ });
42
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * name-field.ts — the single-line name field the worktree flows ask with.
3
+ *
4
+ * What the flows share lives here: one line of input, a rejected submit that
5
+ * notifies and keeps the text, an accepted one that reports the trimmed name,
6
+ * and Escape leaving without a name. Each caller brings its own prefill, rule
7
+ * and wording — the spawn wizard's names are `cow-`-prefixed, the
8
+ * `/cowboy worktree` command's are free-form.
9
+ */
10
+ import { Input } from "@earendil-works/pi-tui";
11
+ /**
12
+ * Whether the field's key handling would take `char` as an operator rather than
13
+ * text. Control characters — C0, DEL, and C1 — are keys (enter submits, escape
14
+ * cancels, backspace and ctrl-u edit) or are dropped; none is ever inserted.
15
+ */
16
+ function isControlCharacter(char) {
17
+ const code = char.codePointAt(0) ?? 0;
18
+ return code < 0x20 || code === 0x7f || (code >= 0x80 && code <= 0x9f);
19
+ }
20
+ /** Single-line name field; a rejected submit keeps the field open on its text. */
21
+ export function createNameField(options) {
22
+ const input = new Input();
23
+ input.focused = true;
24
+ // `setValue` leaves the caret at position 0; typing the prefill lands it after
25
+ // it, where the user continues the name. Only text is typed: control
26
+ // characters are keys to the field, so backspace, ctrl-u and undo would edit
27
+ // the prefill away instead of appearing in the name.
28
+ for (const char of options.prefill) {
29
+ if (!isControlCharacter(char))
30
+ input.handleInput(char);
31
+ }
32
+ input.onSubmit = (value) => {
33
+ const trimmed = value.trim();
34
+ const problem = options.validate(trimmed);
35
+ if (problem) {
36
+ options.notify(options.describeProblem(problem), "error");
37
+ return;
38
+ }
39
+ options.onDone(trimmed);
40
+ };
41
+ input.onEscape = () => options.onCancel();
42
+ return input;
43
+ }
@@ -0,0 +1,61 @@
1
+ /** numeric-input-submenu.ts — numeric input (createNumericSubmenu) and plain text input (createInputSubmenu). */
2
+ import { Input } from "@earendil-works/pi-tui";
3
+ import { validateNumeric } from "../helpers.js";
4
+ /** Numeric submenu erroring via ctx.ui.notify; empty input follows the options' empty-input behavior. */
5
+ export function createNumericSubmenu(ctx, options) {
6
+ const min = options.min ?? 1;
7
+ const fmtLabel = (n) => (n === 0 ? "\u2265 0" : `\u2265 ${n}`);
8
+ const onError = (msg) => ctx.ui.notify(msg, "error");
9
+ return (initialValue, done) => {
10
+ const input = new Input();
11
+ input.setValue(initialValue === "(not set)" ? "" : initialValue);
12
+ input.onSubmit = (value) => {
13
+ const trimmed = value.trim();
14
+ if (!trimmed || /^unlimited$/i.test(trimmed)) {
15
+ switch (options.kind) {
16
+ case "required":
17
+ onError(`Invalid value \u2014 must be a number ${fmtLabel(min)}`);
18
+ return;
19
+ case "defaulted":
20
+ options.onValid?.(options.default);
21
+ done(String(options.default));
22
+ return;
23
+ case "optional":
24
+ options.onEmpty?.();
25
+ done("(not set)");
26
+ return;
27
+ }
28
+ }
29
+ const parsed = validateNumeric(trimmed, min);
30
+ if (parsed === undefined) {
31
+ onError(`Invalid value \u2014 must be a number ${fmtLabel(min)}`);
32
+ return;
33
+ }
34
+ options.onValid?.(parsed);
35
+ done(String(parsed));
36
+ };
37
+ input.onEscape = () => done();
38
+ return input;
39
+ };
40
+ }
41
+ /** Plain-text submenu; empty input errors when `required`, else clears. */
42
+ export function createInputSubmenu(ctx, options) {
43
+ return (initialValue, done) => {
44
+ const input = new Input();
45
+ input.setValue(initialValue);
46
+ input.onSubmit = (value) => {
47
+ const trimmed = value.trim();
48
+ if (!trimmed) {
49
+ if (options?.required) {
50
+ ctx.ui.notify("Cannot be empty", "error");
51
+ return;
52
+ }
53
+ done();
54
+ return;
55
+ }
56
+ done(trimmed);
57
+ };
58
+ input.onEscape = () => done();
59
+ return input;
60
+ };
61
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * target-select.ts — session/global/project/all picker for layered values (ADR-0008).
3
+ * Project needs the store's project target; "All levels" is clear-only;
4
+ * opt-in availableLevels restricts rows to levels carrying the setting.
5
+ */
6
+ import { SettingsList, } from "@earendil-works/pi-tui";
7
+ import { asSubmenuComponent, CLOSED_SUBMENU } from "../screen-host.js";
8
+ import { buildSettingsListTheme, withVimKeys } from "../helpers.js";
9
+ import { createConfirmSubmenu } from "./confirm.js";
10
+ /** Level entries with set vs clear persistence notes. */
11
+ const LEVEL_ENTRIES = {
12
+ session: {
13
+ label: "Session",
14
+ setDescription: "Not saved",
15
+ clearDescription: "Removes from the session",
16
+ },
17
+ global: {
18
+ label: "Global",
19
+ setDescription: "Saves to the global config file",
20
+ clearDescription: "Removes from the global config file",
21
+ },
22
+ project: {
23
+ label: "Project",
24
+ setDescription: "Saves to the project config file",
25
+ clearDescription: "Removes from the project config file",
26
+ },
27
+ };
28
+ function levelItem(target, clearMode) {
29
+ const entry = LEVEL_ENTRIES[target];
30
+ return {
31
+ id: target,
32
+ label: entry.label,
33
+ currentValue: "",
34
+ description: clearMode ? entry.clearDescription : entry.setDescription,
35
+ };
36
+ }
37
+ /** Offered level rows plus optional "Clear..."/"All levels" rows. */
38
+ export function buildLevelItems(options) {
39
+ const items = [];
40
+ if (options.offered.session)
41
+ items.push(levelItem("session", options.clearMode === true));
42
+ if (options.offered.global)
43
+ items.push(levelItem("global", options.clearMode === true));
44
+ if (options.offered.project)
45
+ items.push(levelItem("project", options.clearMode === true));
46
+ if (options.includeClear)
47
+ items.push({ id: "clear", label: "Clear...", currentValue: "" });
48
+ if (options.includeAll)
49
+ items.push({ id: "all", label: "All levels", currentValue: "" });
50
+ return items;
51
+ }
52
+ /** Level picker; a returned Component chains as its submenu, void completes the pick. */
53
+ export function createLevelPickerSubmenu(options) {
54
+ return (_currentValue, done) => {
55
+ const items = options.items.map((item) => ({
56
+ ...item,
57
+ submenu: (_cv, subDone) => {
58
+ const next = options.onPick(item.id, subDone, () => done());
59
+ if (next)
60
+ return next;
61
+ subDone(item.id);
62
+ return CLOSED_SUBMENU;
63
+ },
64
+ }));
65
+ const list = withVimKeys(new SettingsList(items, items.length, buildSettingsListTheme(options.theme), (_id, value) => done(value), () => done()));
66
+ return asSubmenuComponent(list);
67
+ };
68
+ }
69
+ export function createTargetSelectSubmenu(options) {
70
+ const avail = options.availableLevels;
71
+ // includeAll marks clear pickers, selecting the "Removes from..." wording.
72
+ const clearMode = options.includeAll === true;
73
+ const sessionOffered = (options.includeSession ?? true) && (!avail || avail.session);
74
+ const globalOffered = !avail || avail.global;
75
+ const projectOffered = options.projectOffered && (!avail || avail.project);
76
+ const levelsOffered = [sessionOffered, globalOffered, projectOffered].filter(Boolean).length;
77
+ const onClear = options.showClear === true ? options.onClear : undefined;
78
+ const items = buildLevelItems({
79
+ offered: {
80
+ session: sessionOffered,
81
+ global: globalOffered,
82
+ project: projectOffered,
83
+ },
84
+ clearMode,
85
+ includeClear: onClear !== undefined,
86
+ includeAll: avail ? levelsOffered >= 2 : options.includeAll === true,
87
+ });
88
+ return createLevelPickerSubmenu({
89
+ theme: options.theme,
90
+ items,
91
+ onPick: (id, subDone) => {
92
+ if (id === "clear") {
93
+ return createClearPickerSubmenu({
94
+ theme: options.theme,
95
+ projectOffered: options.projectOffered,
96
+ includeSession: options.includeSession ?? true,
97
+ availableLevels: options.availableLevels,
98
+ onClear: (target) => onClear?.(target),
99
+ })("", subDone);
100
+ }
101
+ return options.onPick(id, subDone);
102
+ },
103
+ });
104
+ }
105
+ /** "Clear..." → level picker restricted to levels carrying the setting, plus "All levels". */
106
+ export function createClearPickerSubmenu(options) {
107
+ return createTargetSelectSubmenu({
108
+ theme: options.theme,
109
+ projectOffered: options.projectOffered,
110
+ includeSession: options.includeSession ?? true,
111
+ includeAll: true,
112
+ availableLevels: options.availableLevels,
113
+ onPick: (target) => options.onClear(target),
114
+ });
115
+ }
116
+ /** Clear-all flow: pick a level, then confirm. */
117
+ export function createClearAllSubmenu(options) {
118
+ return (currentValue, done) => createTargetSelectSubmenu({
119
+ theme: options.theme,
120
+ projectOffered: options.projectOffered,
121
+ includeAll: true,
122
+ availableLevels: options.availableLevels,
123
+ onPick: (target, pickDone) => createConfirmSubmenu({
124
+ message: options.message(target),
125
+ theme: options.theme,
126
+ onConfirm: () => options.onConfirm(target),
127
+ })(currentValue, pickDone),
128
+ })(currentValue, done);
129
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * text-editor.ts — multi-line text body for prompts.
3
+ *
4
+ * pi-tui's Editor is the screen's text control here: it wraps, scrolls, keeps
5
+ * history and a kill ring, and takes enter to submit / shift+enter for a
6
+ * newline. It draws its own border, so the frame around it comes from
7
+ * SettingsListWrapper (whose title names the field).
8
+ */
9
+ import { Editor, } from "@earendil-works/pi-tui";
10
+ import { buildSelectListTheme } from "../helpers.js";
11
+ /**
12
+ * Focusable multi-line text body. Focused from the start (it is the only
13
+ * control on screen), so the cursor renders where the text is being typed.
14
+ */
15
+ export function createTextEditor(options) {
16
+ const { tui, theme, keybindings, prefill, onDone, onCancel } = options;
17
+ const editor = new Editor(tui, {
18
+ borderColor: (text) => theme.fg("dim", text),
19
+ selectList: buildSelectListTheme(theme),
20
+ }, { paddingX: 2 });
21
+ editor.focused = true;
22
+ if (prefill)
23
+ editor.setText(prefill);
24
+ editor.onSubmit = (text) => {
25
+ const trimmed = text.trim();
26
+ if (!trimmed && options.required) {
27
+ options.notify("Cannot be empty", "error");
28
+ return;
29
+ }
30
+ onDone(trimmed);
31
+ };
32
+ return {
33
+ render: (width) => editor.render(width),
34
+ invalidate: () => editor.invalidate(),
35
+ handleInput: (data) => {
36
+ if (keybindings.matches(data, "tui.select.cancel")) {
37
+ onCancel();
38
+ return;
39
+ }
40
+ editor.handleInput(data);
41
+ },
42
+ get focused() {
43
+ return editor.focused;
44
+ },
45
+ set focused(value) {
46
+ editor.focused = value;
47
+ },
48
+ };
49
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * worktree-command-name.ts — the `/cowboy worktree` command's name field.
3
+ *
4
+ * The name is the git branch and the directory under the worktree root at once,
5
+ * so it follows git's own branch-name rules instead of the spawn wizard's
6
+ * `cow-`-prefixed grammar, and a name that happens to start with `cow-` is
7
+ * nothing special. It is capped at herdr's agent-name length because the pane
8
+ * adoption names the worktree with it. Submit re-prompts with a notification
9
+ * instead of completing on a rejected name.
10
+ */
11
+ import { HERDR_AGENT_NAME_MAX_LENGTH } from "../../../spawn/worktree-policy.js";
12
+ import { createNameField } from "./name-field.js";
13
+ /** Longest accepted name: the pane adoption carries it as herdr's agent name. */
14
+ export const WORKTREE_COMMAND_NAME_MAX_LENGTH = HERDR_AGENT_NAME_MAX_LENGTH;
15
+ /** Characters git refuses anywhere in a branch name. */
16
+ const ILLEGAL_BRANCH_CHARACTERS = /[ ~^:?*[\\]/;
17
+ /** Whether a branch name holds a character git refuses: a control character, or one of its own set. */
18
+ function hasIllegalCharacter(input) {
19
+ for (const char of input) {
20
+ const code = char.codePointAt(0) ?? 0;
21
+ if (code < 0x20 || code === 0x7f)
22
+ return true;
23
+ if (ILLEGAL_BRANCH_CHARACTERS.test(char))
24
+ return true;
25
+ }
26
+ return false;
27
+ }
28
+ /** Validate a trimmed worktree name as a git branch name; null means accepted. */
29
+ export function validateWorktreeCommandName(input) {
30
+ if (input === "")
31
+ return { kind: "empty-name" };
32
+ if (input.length > WORKTREE_COMMAND_NAME_MAX_LENGTH) {
33
+ return { kind: "too-long" };
34
+ }
35
+ if (hasIllegalCharacter(input)) {
36
+ return { kind: "invalid-characters" };
37
+ }
38
+ const shapeIsWrong = input.startsWith("-") ||
39
+ input.startsWith(".") ||
40
+ input.startsWith("/") ||
41
+ input.endsWith(".") ||
42
+ input.endsWith("/") ||
43
+ input.endsWith(".lock") ||
44
+ input.includes("..") ||
45
+ input.includes("//") ||
46
+ input.includes("@{") ||
47
+ input === "@";
48
+ return shapeIsWrong ? { kind: "invalid-shape" } : null;
49
+ }
50
+ /** User-facing message for a rejected worktree name. */
51
+ export function describeWorktreeCommandNameProblem(problem) {
52
+ switch (problem.kind) {
53
+ case "empty-name":
54
+ return "Enter a name: it becomes the worktree's directory and its git branch.";
55
+ case "too-long":
56
+ return `Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${WORKTREE_COMMAND_NAME_MAX_LENGTH} characters.`;
57
+ case "invalid-characters":
58
+ return "Invalid name: it must be a git branch name, so letters, digits, and - _ . / only — no spaces, and none of ~ ^ : ? * [ \\.";
59
+ case "invalid-shape":
60
+ return "Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock.";
61
+ }
62
+ }
63
+ /** Single-line free-form name field; a rejected submit keeps the text. */
64
+ export function createWorktreeCommandNameInput(options) {
65
+ return createNameField({
66
+ prefill: options.prefill,
67
+ notify: options.notify,
68
+ validate: validateWorktreeCommandName,
69
+ describeProblem: describeWorktreeCommandNameProblem,
70
+ onDone: options.onDone,
71
+ onCancel: options.onCancel,
72
+ });
73
+ }