pi-subagent-manager 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -140,7 +140,7 @@ Automatic project discovery requires project trust. Only agent definitions are o
140
140
 
141
141
  ### Configuration and thread UI
142
142
 
143
- - `/agents types`: open the bordered agent-definition browser and two-column editor: **field names** on the left, **current values** on the right. **↑↓/Tab** selects fields, **Enter** edits, **Ctrl+S** saves, and **Esc** discards the draft. Multiline field dialogs use **Enter** for a newline and **Ctrl+S** to apply to the draft. Edit the system prompt, models, thinking, tools, color and save scope. Model preferences use an ordered picker: add available models (scoped entries are marked), remove entries, and move them up/down. The YAML editor edits the header together; **External editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
143
+ - `/agents types`: open the bordered agent-definition browser and two-column editor: **field names** on the left, **current values** on the right. **↑↓/Tab** selects fields, **Enter** edits, **Ctrl+S** saves, and **Esc** discards the draft. Multiline field dialogs use **Enter** for a newline and **Ctrl+S** to apply to the draft. Edit the system prompt, models, thinking, tools, color and save scope. Model preferences use an ordered picker: add available models (scoped entries are marked), remove entries, and move them up/down. When adding or replacing a model, [fuzzysort](https://github.com/farzher/fuzzysort) fuzzy-matches the draft's `modelSuggestions` against provider/id and display name: scoped matches first, other matches next (ranked by best match score), then remaining models alphabetically without duplicates. Typing filters these groups; without suggestions the list is alphabetical. Suggestions only aid selection and never change runtime model resolution. The YAML editor edits the header together; **External editor** edits the whole Markdown file using `$VISUAL`, `$EDITOR`, or `vi`.
144
144
  - `/agents import`: select individual external definitions for model-driven migration.
145
145
  - `/agents reload`: reload definitions and show diagnostics.
146
146
  - `/agents` or `/agents settings`: open a bordered settings dialog. Choose **Subagent Mode** (**Off**, **Opportunistic**, or **Orchestration**), edit level, concurrency and retained-thread limits, toggle **Scoped model filtering**, choose global or trusted-project scope, and save with **Ctrl+S**. The mode field and chooser explain each option. Settings apply immediately without interrupting existing work. **Agent definitions** opens the type editor.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagent-manager",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Hierarchical, steerable subagent threads for pi",
5
5
  "type": "module",
6
6
  "engines": {
@@ -45,6 +45,7 @@
45
45
  "format:check": "prettier --check --print-width 100 src tests agents .github docs/default-agents.md README.md"
46
46
  },
47
47
  "dependencies": {
48
+ "fuzzysort": "^4.0.2",
48
49
  "shell-quote": "^1.8.3",
49
50
  "yaml": "^2.8.1"
50
51
  },
package/src/dialog.ts CHANGED
@@ -29,10 +29,10 @@ export interface DialogEditorHost extends DialogHost {
29
29
  export interface DialogRow {
30
30
  id: string;
31
31
  label: string;
32
- labelPrefix?: { text: string; color: Parameters<Theme["fg"]>[0] };
33
32
  /** Trusted formatter receives sanitized text; generated ANSI styling is kept when clipping. */
34
33
  renderLabel?: (label: string, theme: Theme) => string;
35
34
  value?: string;
35
+ valueColor?: Parameters<Theme["fg"]>[0];
36
36
  help?: string;
37
37
  }
38
38
  export const DIALOG_OPTIONS = {
@@ -245,21 +245,19 @@ export class DialogMenu {
245
245
  ...this.rows.slice(start, start + this.viewport).map((row, i) => {
246
246
  const selected = start + i === this.selected;
247
247
  const color = (text: string) => selected ? this.theme.fg("accent", text) : text;
248
- const prefix = row.labelPrefix
249
- ? truncateToWidth(`${dialogText(row.labelPrefix.text)} `, labelWidth, "")
250
- : "";
251
248
  const plainLabel = dialogText(row.label);
252
249
  const label = truncateToWidth(
253
250
  row.renderLabel ? row.renderLabel(plainLabel, this.theme) : plainLabel,
254
- labelWidth - visibleWidth(prefix),
251
+ labelWidth,
255
252
  "",
256
253
  true,
257
254
  );
258
- const padding = " ".repeat(Math.max(0, labelWidth - visibleWidth(prefix) - visibleWidth(label)));
255
+ const padding = " ".repeat(Math.max(0, labelWidth - visibleWidth(label)));
256
+ const value = dialogText(row.value ?? "");
259
257
  return color(`${selected ? "›" : " "} `)
260
- + (row.labelPrefix ? this.theme.fg(row.labelPrefix.color, prefix) : "")
261
258
  + (row.renderLabel ? label : color(label))
262
- + color(`${padding} │ ${dialogText(row.value ?? "")}`);
259
+ + color(`${padding} │ `)
260
+ + (row.valueColor ? this.theme.fg(row.valueColor, value) : color(value));
263
261
  }),
264
262
  "",
265
263
  ...help.map((line) => this.theme.fg("muted", ` ${line}`)),
@@ -1,3 +1,4 @@
1
+ import fuzzysort, { type SnapshotKeys } from "fuzzysort";
1
2
  import type { Api, Model } from "@earendil-works/pi-ai";
2
3
  import {
3
4
  getSelectListTheme,
@@ -7,7 +8,6 @@ import {
7
8
  } from "@earendil-works/pi-coding-agent";
8
9
  import {
9
10
  Container,
10
- fuzzyFilter,
11
11
  getKeybindings,
12
12
  Input,
13
13
  SelectList,
@@ -31,6 +31,10 @@ export const MODEL_EDITOR_CANCEL = Symbol("model-editor-cancel");
31
31
 
32
32
  type AvailableModel = Pick<Model<Api>, "provider" | "id" | "name">;
33
33
 
34
+ interface ModelSelectItem extends SelectItem {
35
+ group?: string;
36
+ }
37
+
34
38
  type ModelEditorMode =
35
39
  | { kind: "menu" }
36
40
  | { kind: "actions"; index: number }
@@ -46,6 +50,7 @@ interface OrderedModelEditorComponentOptions {
46
50
  availableModels: readonly AvailableModel[];
47
51
  scopedModels: readonly ScopedModel[];
48
52
  initialModels?: readonly string[];
53
+ modelSuggestions?: readonly string[];
49
54
  onDone(models: string[]): void;
50
55
  onCancel(): void;
51
56
  }
@@ -58,6 +63,13 @@ function renderModelIdentity(identity: string): string {
58
63
  return sanitizeModelText(identity);
59
64
  }
60
65
 
66
+ function modelSearchText(text: string): string {
67
+ // Providers spell the same version differently (sonnet-5.5 vs sonnet-5-5).
68
+ // Strip separators rather than splitting them into repeated numeric terms;
69
+ // raw identities and labels remain untouched.
70
+ return sanitizeModelText(text).replace(/[._:/-]+/g, "");
71
+ }
72
+
61
73
  function sortModels(models: readonly AvailableModel[]): AvailableModel[] {
62
74
  const unique = new Map<string, AvailableModel>();
63
75
  for (const model of models) unique.set(modelIdentity(model), model);
@@ -80,19 +92,6 @@ function describeModel(
80
92
  return [name, annotation].filter(Boolean).join(" · ");
81
93
  }
82
94
 
83
- function buildSearchText(
84
- model: AvailableModel,
85
- scopedIdentities: ReadonlySet<string>,
86
- ): string {
87
- return [
88
- renderModelIdentity(modelIdentity(model)),
89
- sanitizeModelText(model.name),
90
- describeModel(model, scopedIdentities),
91
- ]
92
- .filter(Boolean)
93
- .join(" ");
94
- }
95
-
96
95
  export class OrderedModelEditorComponent extends Container {
97
96
  private readonly tui: {
98
97
  requestRender(force?: boolean): void;
@@ -100,6 +99,8 @@ export class OrderedModelEditorComponent extends Container {
100
99
  };
101
100
  private readonly theme: Theme;
102
101
  private readonly allModels: readonly AvailableModel[];
102
+ private readonly modelSearch: SnapshotKeys<AvailableModel>;
103
+ private readonly suggestedScores: ReadonlyMap<string, number>;
103
104
  private readonly modelsByIdentity = new Map<string, AvailableModel>();
104
105
  private readonly scopedIdentities: ReadonlySet<string>;
105
106
  private readonly onDone: (models: string[]) => void;
@@ -112,7 +113,7 @@ export class OrderedModelEditorComponent extends Container {
112
113
  private mode: ModelEditorMode;
113
114
  private pickerQuery = "";
114
115
  private pickerSelectedValue: string | undefined;
115
- private currentItems: SelectItem[] = [];
116
+ private currentItems: ModelSelectItem[] = [];
116
117
  private selectList = new SelectList(
117
118
  [],
118
119
  1,
@@ -130,6 +131,15 @@ export class OrderedModelEditorComponent extends Container {
130
131
  this.tui = options.tui;
131
132
  this.theme = options.theme;
132
133
  this.allModels = sortModels(options.availableModels);
134
+ // The registry is fixed for this dialog; prepare searchable fields once.
135
+ // Scope annotations deliberately aren't searchable model metadata.
136
+ this.modelSearch = fuzzysort.snapshot(this.allModels, {
137
+ keys: [
138
+ (model) => modelSearchText(modelIdentity(model)),
139
+ (model) => modelSearchText(model.name),
140
+ ],
141
+ });
142
+ this.suggestedScores = this.searchScores(options.modelSuggestions ?? []);
133
143
  this.onDone = options.onDone;
134
144
  this.onCancel = options.onCancel;
135
145
  for (const model of this.allModels)
@@ -192,17 +202,31 @@ export class OrderedModelEditorComponent extends Container {
192
202
  if (this.searchInput) header.push(...this.searchInput.render(inner));
193
203
  const budget = Math.max(1, height - 4 - header.length);
194
204
  const selected = this.selectList.getSelectedItem()?.value;
205
+ // Headings are visual rows only: keyboard navigation selects models, not groups.
206
+ const displayRows: (ModelSelectItem | string)[] = [];
207
+ let previousGroup: string | undefined;
208
+ for (const item of this.currentItems) {
209
+ if (item.group && item.group !== previousGroup) {
210
+ displayRows.push(item.group);
211
+ }
212
+ previousGroup = item.group;
213
+ displayRows.push(item);
214
+ }
195
215
  const index = Math.max(
196
216
  0,
197
- this.currentItems.findIndex((item) => item.value === selected),
217
+ displayRows.findIndex(
218
+ (row) => typeof row !== "string" && row.value === selected,
219
+ ),
198
220
  );
199
221
  const start = Math.max(
200
222
  0,
201
- Math.min(index - budget + 1, this.currentItems.length - budget),
223
+ Math.min(index - budget + 1, displayRows.length - budget),
202
224
  );
203
- const rows = this.currentItems.slice(start, start + budget).map((item) => {
204
- const text = `${item.value === selected ? "›" : " "} ${item.label} ${this.theme.fg("muted", item.description ?? "")}`;
205
- return item.value === selected ? this.theme.fg("accent", text) : text;
225
+ // Only format visible rows; a registry can contain thousands of models.
226
+ const rows = displayRows.slice(start, start + budget).map((row) => {
227
+ if (typeof row === "string") return this.theme.fg("muted", row);
228
+ const text = `${row.value === selected ? "›" : " "} ${row.label} ${this.theme.fg("muted", row.description ?? "")}`;
229
+ return row.value === selected ? this.theme.fg("accent", text) : text;
206
230
  });
207
231
  if (!rows.length) rows.push(this.theme.fg("muted", "No matching models"));
208
232
  return frameDialog(
@@ -440,7 +464,9 @@ export class OrderedModelEditorComponent extends Container {
440
464
  this.theme.fg(
441
465
  "muted",
442
466
  this.withScopeWarning(
443
- "Search by provider/id or model name. Already-selected duplicates are hidden.",
467
+ this.suggestedScores.size
468
+ ? "Suggested matches: scoped first, then other models; the rest A–Z. Type to search."
469
+ : "Search by provider/id or model name. Models A–Z; selected duplicates are hidden.",
444
470
  ),
445
471
  ),
446
472
  );
@@ -544,23 +570,71 @@ export class OrderedModelEditorComponent extends Container {
544
570
  return list;
545
571
  }
546
572
 
547
- private getPickerItems(replaceIndex: number | undefined): SelectItem[] {
573
+ private searchScores(queries: readonly string[]): Map<string, number> {
574
+ const scores = new Map<string, number>();
575
+ const uniqueQueries = new Set(
576
+ queries.map((query) => modelSearchText(query).trim()).filter(Boolean),
577
+ );
578
+ for (const query of uniqueQueries) {
579
+ // Both defaults are restrictive (10 results, score >= .5); collect every
580
+ // fuzzy match so suggestions aren't silently capped or omitted.
581
+ for (const result of fuzzysort.go(query, this.modelSearch, {
582
+ limit: 0,
583
+ threshold: 0,
584
+ })) {
585
+ const identity = modelIdentity(result.obj);
586
+ scores.set(identity, Math.max(scores.get(identity) ?? 0, result.score));
587
+ }
588
+ }
589
+ return scores;
590
+ }
591
+
592
+ private getPickerItems(replaceIndex: number | undefined): ModelSelectItem[] {
548
593
  const excluded = new Set(
549
594
  this.draft.filter((_, index) => index !== replaceIndex),
550
595
  );
551
- const available = this.allModels.filter(
552
- (model) => !excluded.has(modelIdentity(model)),
553
- );
554
- const filtered = this.pickerQuery
555
- ? fuzzyFilter(available, this.pickerQuery, (model) =>
556
- buildSearchText(model, this.scopedIdentities),
557
- )
558
- : available;
559
- return filtered.map((model) => ({
560
- value: modelIdentity(model),
561
- label: renderModelIdentity(modelIdentity(model)),
562
- description: describeModel(model, this.scopedIdentities),
563
- }));
596
+ const query = this.pickerQuery.trim();
597
+ const queryScores = query ? this.searchScores([query]) : undefined;
598
+ const scoped: AvailableModel[] = [];
599
+ const other: AvailableModel[] = [];
600
+ const remaining: AvailableModel[] = [];
601
+ for (const model of this.allModels) {
602
+ const identity = modelIdentity(model);
603
+ if (excluded.has(identity) || (queryScores && !queryScores.has(identity)))
604
+ continue;
605
+ if (this.suggestedScores.has(identity)) {
606
+ (this.scopedIdentities.has(identity) ? scoped : other).push(model);
607
+ } else {
608
+ remaining.push(model);
609
+ }
610
+ }
611
+ const bySuggestionScore = (a: AvailableModel, b: AvailableModel) =>
612
+ this.suggestedScores.get(modelIdentity(b))! -
613
+ this.suggestedScores.get(modelIdentity(a))!;
614
+ // Stable score sorting preserves alphabetical order for ties. The last
615
+ // tier retains the registry's alphabetical order, irrespective of scope.
616
+ scoped.sort(bySuggestionScore);
617
+ other.sort(bySuggestionScore);
618
+ const items = (
619
+ models: AvailableModel[],
620
+ group: string,
621
+ ): ModelSelectItem[] =>
622
+ models.map((model) => ({
623
+ value: modelIdentity(model),
624
+ label: renderModelIdentity(modelIdentity(model)),
625
+ description: describeModel(model, this.scopedIdentities),
626
+ group,
627
+ }));
628
+ return [
629
+ ...items(scoped, "Suggested matches · scoped models"),
630
+ ...items(other, "Suggested matches · other models"),
631
+ ...items(
632
+ remaining,
633
+ scoped.length || other.length
634
+ ? "All other models · A–Z"
635
+ : "All models · A–Z",
636
+ ),
637
+ ];
564
638
  }
565
639
 
566
640
  private describeDraftIdentity(identity: string): string {
@@ -580,6 +654,7 @@ export class OrderedModelEditorComponent extends Container {
580
654
  export async function editModelPreferences(
581
655
  ctx: ExtensionCommandContext,
582
656
  currentModels?: readonly string[],
657
+ modelSuggestions?: readonly string[],
583
658
  ): Promise<readonly string[] | typeof MODEL_EDITOR_CANCEL> {
584
659
  if (ctx.mode !== "tui") {
585
660
  if (ctx.hasUI) {
@@ -603,6 +678,7 @@ export async function editModelPreferences(
603
678
  availableModels,
604
679
  scopedModels: ctx.scopedModels,
605
680
  initialModels: currentModels,
681
+ modelSuggestions,
606
682
  onDone: (models) => done(models),
607
683
  onCancel: () => done(MODEL_EDITOR_CANCEL),
608
684
  }),
@@ -133,7 +133,8 @@ async function configureAgentsDialog(
133
133
  {
134
134
  id: "save",
135
135
  label: "Save and apply",
136
- labelPrefix: dirty ? { text: "(changes)", color: "warning" as const } : undefined,
136
+ value: dirty ? "(changes)" : undefined,
137
+ valueColor: dirty ? "warning" as const : undefined,
137
138
  help: "Save all values to the selected scope and reload settings now. Project overrides still take precedence. Running agents and retained sessions are kept.",
138
139
  },
139
140
  {
package/src/ui.ts CHANGED
@@ -1062,12 +1062,14 @@ async function editAgentTypesDialog(
1062
1062
  let draft: AgentType = original
1063
1063
  ? structuredClone(original)
1064
1064
  : { name: "new-agent", description: "New agent", systemPrompt: "" };
1065
+ const originalContent = serializeAgentType(draft);
1065
1066
  let selectedId: string | undefined;
1066
1067
  let saveScope: "user" | "project" =
1067
1068
  original?.source === "project" && store.canSaveProject()
1068
1069
  ? "project"
1069
1070
  : "user";
1070
1071
  while (true) {
1072
+ const dirty = !original || serializeAgentType(draft) !== originalContent;
1071
1073
  const field = await dialogMenu(
1072
1074
  ctx,
1073
1075
  `Edit ${sanitizeText(draft.name)} (unsaved)`,
@@ -1077,16 +1079,19 @@ async function editAgentTypesDialog(
1077
1079
  return {
1078
1080
  id: action,
1079
1081
  label: EDIT_FIELD_LABELS[action],
1082
+ valueColor: action === "Save" && dirty ? "warning" as const : undefined,
1080
1083
  value:
1081
- action === "Source"
1082
- ? (original?.source ?? "New draft")
1083
- : action === "Save scope"
1084
- ? saveScope === "user"
1085
- ? "Global"
1086
- : "Trusted project"
1087
- : separator >= 0
1088
- ? decorated.slice(separator + 2)
1089
- : "",
1084
+ action === "Save" && dirty
1085
+ ? "(changes)"
1086
+ : action === "Source"
1087
+ ? (original?.source ?? "New draft")
1088
+ : action === "Save scope"
1089
+ ? saveScope === "user"
1090
+ ? "Global"
1091
+ : "Trusted project"
1092
+ : separator >= 0
1093
+ ? decorated.slice(separator + 2)
1094
+ : "",
1090
1095
  help:
1091
1096
  action === "Source"
1092
1097
  ? (original?.filePath ??
@@ -1165,6 +1170,7 @@ async function editAgentTypesDialog(
1165
1170
  const value = await editModelPreferences(
1166
1171
  ctx,
1167
1172
  getModelPreferences(candidate),
1173
+ candidate.modelSuggestions,
1168
1174
  );
1169
1175
  if (value === MODEL_EDITOR_CANCEL) continue;
1170
1176
  if (value.length === 0) {