pi-better-subagents 0.27.2 → 0.28.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/catalog-schema.ts CHANGED
@@ -23,6 +23,13 @@ export type DiagnosticSeverity = "error" | "warning" | "info";
23
23
 
24
24
  export const PREFERENCE_KEYS = ["model", "effort", "tier"] as const satisfies readonly PreferenceKey[];
25
25
 
26
+ /**
27
+ * Every key `defaults` (roles) and `overrides` (agents) may carry. `skills` is
28
+ * added here but is not a `PreferenceKey`: model resolution consumes preferences,
29
+ * while skill exposure is reproduced by the launcher from the definition.
30
+ */
31
+ export const DEFINITION_PREFERENCE_KEYS = [...PREFERENCE_KEYS, "skills"] as const;
32
+
26
33
  /** Closed set of thinking levels shared with the existing subagent parser. */
27
34
  export const EFFORT_LEVELS = THINKING_LEVELS;
28
35
 
@@ -135,11 +142,20 @@ export interface Diagnostic {
135
142
  structural: boolean;
136
143
  }
137
144
 
138
- /** Model, effort, and tier only. Absence inherits; null is an explicit value. */
145
+ /**
146
+ * Model, effort, tier, and skill exposure. Absence inherits; null is an explicit value.
147
+ *
148
+ * `skills` is the one launch value here that changes what the child can see
149
+ * rather than how the model is chosen. It stays a definition-owned preference
150
+ * because the launcher reproduces it exactly (`--no-skills` plus `--skill`), the
151
+ * same way it reproduces model and effort, and because it grants nothing: a
152
+ * skill list narrows prompt exposure and cannot add a tool or a permission.
153
+ */
139
154
  export interface PortablePreferences {
140
155
  model?: string | null;
141
156
  effort?: ThinkingLevel | null;
142
157
  tier?: string | null;
158
+ skills?: string[] | null;
143
159
  }
144
160
 
145
161
  export interface Provenance {
@@ -213,6 +229,8 @@ export interface SerializeResult {
213
229
  const ID_PATTERN = /^(role|agent)\.[a-z0-9]+(?:[.-][a-z0-9]+)*$/;
214
230
  const MODEL_PATTERN = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._+-]*$/;
215
231
  const TIER_PATTERN = /^[a-z][a-z0-9-]{0,32}$/;
232
+ /** POSIX absolute, or a Windows drive/UNC path. */
233
+ const ABSOLUTE_PATH = /^(?:\/|[A-Za-z]:[\\/]|\\\\)/;
216
234
  const SECRET_KEY = /^(api[_-]?key|apikey|secret|password|passwd|token|access[_-]?token|refresh[_-]?token|credential|credentials|authorization|auth|databaseurl|connectionstring|dsn)$/i;
217
235
  const MULTI_ROLE_KEYS = new Set(["roleIds", "baseRoles", "baseRole", "inherits", "roles"]);
218
236
  const KNOWN_TOP_LEVEL = new Set([
@@ -310,7 +328,7 @@ export function removeAgentOverride(agent: AgentDefinition, key: PreferenceKey):
310
328
 
311
329
  export function updateAgentOverrides(
312
330
  agent: AgentDefinition,
313
- patch: { set?: Partial<PortablePreferences>; remove?: readonly PreferenceKey[] },
331
+ patch: { set?: Partial<PortablePreferences>; remove?: readonly (PreferenceKey | "skills")[] },
314
332
  ): AgentDefinition {
315
333
  const remove = patch.remove ?? [];
316
334
  const set = patch.set ?? {};
@@ -324,9 +342,63 @@ export function updateAgentOverrides(
324
342
  if (Object.prototype.hasOwnProperty.call(set, "model") && set.model !== undefined) overrides.model = set.model;
325
343
  if (Object.prototype.hasOwnProperty.call(set, "effort") && set.effort !== undefined) overrides.effort = set.effort;
326
344
  if (Object.prototype.hasOwnProperty.call(set, "tier") && set.tier !== undefined) overrides.tier = set.tier;
345
+ // Skill exposure is a definition value, not a resolution preference, so it
346
+ // rides the same patch path without joining the model/effort resolution.
347
+ if (Object.prototype.hasOwnProperty.call(set, "skills") && set.skills !== undefined) overrides.skills = set.skills;
327
348
  return { ...agent, overrides };
328
349
  }
329
350
 
351
+ /**
352
+ * One `/agents` skill edit. `inherit` removes the definition's own key,
353
+ * `none` writes `[]`, and `explicit` writes the absolute paths.
354
+ *
355
+ * `explicit` with no paths is rejected on purpose: an empty selected list must
356
+ * not become `[]` (which means "none") or absence (which means discovery).
357
+ */
358
+ export type SkillExposureEdit =
359
+ | { mode: "inherit" }
360
+ | { mode: "none" }
361
+ | { mode: "explicit"; paths: readonly string[] };
362
+
363
+ /** The definition's own skill value: undefined inherits, null suppresses, `[]` is none. */
364
+ export function definitionSkillPreference(definition: CatalogDefinition): string[] | null | undefined {
365
+ const preferences = definition.kind === "role" ? definition.defaults : definition.overrides;
366
+ if (!Object.prototype.hasOwnProperty.call(preferences, "skills")) return undefined;
367
+ return preferences.skills === null || preferences.skills === undefined ? null : [...preferences.skills];
368
+ }
369
+
370
+ /** Absolute definition paths, with the empty selection rejected rather than stored as "none". */
371
+ export function definitionSkillPaths(paths: readonly string[]): string[] {
372
+ if (paths.length === 0) {
373
+ throw new Error("Selected skills needs at least one absolute path. Choose No skill catalog for none.");
374
+ }
375
+ return paths.map((entry, index) => {
376
+ if (typeof entry !== "string" || entry.trim() === "") {
377
+ throw new Error(`Selected skills[${index}] must be a non-empty absolute path.`);
378
+ }
379
+ const path = entry.trim();
380
+ if (!ABSOLUTE_PATH.test(path)) {
381
+ throw new Error(`Selected skills[${index}] must be absolute: ${path}. A definition has no workspace of its own.`);
382
+ }
383
+ return path;
384
+ });
385
+ }
386
+
387
+ /** Apply one edit without flattening inherited values or touching other fields. */
388
+ export function applySkillExposure<T extends CatalogDefinition>(definition: T, edit: SkillExposureEdit): T {
389
+ const paths = edit.mode === "explicit" ? definitionSkillPaths(edit.paths) : undefined;
390
+ const apply = (preferences: PortablePreferences): PortablePreferences => {
391
+ const next = { ...preferences };
392
+ if (edit.mode === "inherit") delete next.skills;
393
+ else if (edit.mode === "none") next.skills = [];
394
+ else next.skills = [...paths!];
395
+ return next;
396
+ };
397
+ return definition.kind === "role"
398
+ ? { ...definition, defaults: apply(definition.defaults) }
399
+ : { ...definition, overrides: apply(definition.overrides) };
400
+ }
401
+
330
402
  export function parseDefinition(markdown: string, sourcePath?: string): ParseResult {
331
403
  const diagnostics: Diagnostic[] = [];
332
404
  try {
@@ -757,6 +829,23 @@ function readInstructionMode(
757
829
  return mode;
758
830
  }
759
831
 
832
+ /**
833
+ * Skill paths in a definition are literal and absolute: a catalog file has no
834
+ * workspace of its own, so a relative path would resolve differently depending
835
+ * on who launches it. Returns undefined for anything that is not such a list.
836
+ */
837
+ function readSkillPaths(value: unknown): string[] | undefined {
838
+ if (!Array.isArray(value)) return undefined;
839
+ const paths: string[] = [];
840
+ for (const entry of value) {
841
+ if (typeof entry !== "string") return undefined;
842
+ const path = entry.trim();
843
+ if (path === "" || !ABSOLUTE_PATH.test(path)) return undefined;
844
+ paths.push(path);
845
+ }
846
+ return paths;
847
+ }
848
+
760
849
  function readPreferences(
761
850
  value: unknown,
762
851
  field: "defaults" | "overrides",
@@ -768,7 +857,7 @@ function readPreferences(
768
857
  ): PortablePreferences | undefined {
769
858
  if (value === undefined) return {};
770
859
  if (!isPlainObject(value)) {
771
- diagnostics.push(problem(DiagnosticCodes.invalidField, `${field} must be a mapping of model, effort, and tier.`, {
860
+ diagnostics.push(problem(DiagnosticCodes.invalidField, `${field} must be a mapping of model, effort, tier, and skills.`, {
772
861
  path: sourcePath,
773
862
  field,
774
863
  id,
@@ -779,7 +868,7 @@ function readPreferences(
779
868
  }
780
869
  const preferences: PortablePreferences = {};
781
870
  for (const key of Object.keys(value)) {
782
- if (!isPreferenceKey(key)) {
871
+ if (!isPreferenceKey(key) && key !== "skills") {
783
872
  const target = `${field}.${key}`;
784
873
  extensions[target] = value[key];
785
874
  if (EXECUTION_KEY_SET.has(key)) {
@@ -793,11 +882,11 @@ function readPreferences(
793
882
  });
794
883
  diagnostics.push(problem(
795
884
  DiagnosticCodes.unsupportedExecutionRestriction,
796
- `${target} is a host execution control, not a portable preference. It was preserved and blocks launch. Model, effort, and tier are the only preference fields.`,
885
+ `${target} is a host execution control, not a portable preference. It was preserved and blocks launch. Model, effort, tier, and skills are the only preference fields.`,
797
886
  { path: sourcePath, field: target, id, blocking: true, structural: false },
798
887
  ));
799
888
  } else {
800
- diagnostics.push(problem(DiagnosticCodes.cosmeticMetadata, `Unknown ${target} was preserved and is not a model, effort, or tier preference.`, {
889
+ diagnostics.push(problem(DiagnosticCodes.cosmeticMetadata, `Unknown ${target} was preserved and is not a model, effort, tier, or skills preference.`, {
801
890
  path: sourcePath,
802
891
  field: target,
803
892
  id,
@@ -813,6 +902,19 @@ function readPreferences(
813
902
  preferences[key] = null;
814
903
  continue;
815
904
  }
905
+ if (key === "skills") {
906
+ const paths = readSkillPaths(item);
907
+ if (!paths) {
908
+ diagnostics.push(problem(
909
+ DiagnosticCodes.invalidField,
910
+ `${field}.skills must be a list of absolute paths to a SKILL.md file or a skill directory; [] loads no skills. Skill paths stay literal so a frozen launch recipe replays the same files.`,
911
+ { path: sourcePath, field: `${field}.skills`, id, blocking: true, structural: true },
912
+ ));
913
+ continue;
914
+ }
915
+ preferences.skills = paths;
916
+ continue;
917
+ }
816
918
  if (key === "model") {
817
919
  if (typeof item !== "string" || !MODEL_PATTERN.test(item)) {
818
920
  diagnostics.push(problem(DiagnosticCodes.invalidField, "model must be provider/model, without an @effort suffix. Set effort separately.", {
@@ -1396,7 +1498,7 @@ function walkNode(node: Node | Pair | null, depth: number, state: { nodes: numbe
1396
1498
 
1397
1499
  function preferenceMapping(preferences: PortablePreferences): Record<string, unknown> {
1398
1500
  const mapping: Record<string, unknown> = {};
1399
- for (const key of PREFERENCE_KEYS) {
1501
+ for (const key of DEFINITION_PREFERENCE_KEYS) {
1400
1502
  if (Object.prototype.hasOwnProperty.call(preferences, key) && preferences[key] !== undefined) {
1401
1503
  mapping[key] = preferences[key];
1402
1504
  }
@@ -1405,7 +1507,7 @@ function preferenceMapping(preferences: PortablePreferences): Record<string, unk
1405
1507
  }
1406
1508
 
1407
1509
  function hasPreference(preferences: PortablePreferences): boolean {
1408
- return PREFERENCE_KEYS.some((key) => preferences[key] !== undefined);
1510
+ return DEFINITION_PREFERENCE_KEYS.some((key) => preferences[key] !== undefined);
1409
1511
  }
1410
1512
 
1411
1513
  function compactDefinition<T extends CatalogDefinition>(definition: T): T {
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `/agents` skill edits persisted through the catalog's definition save path.
3
+ *
4
+ * Skill exposure belongs to `defaults.skills` (roles) and `overrides.skills`
5
+ * (named agents), so unlike model and effort it is not a settings.json
6
+ * preference: changing it must rewrite that definition through
7
+ * `saveDefinition`. The edit is surgical. The prompt, description, and every
8
+ * other preference stay as they were, and `inherit` deletes the key instead of
9
+ * writing a null or copying an inherited value back into the file.
10
+ *
11
+ * A bundled definition is immutable. Editing its skills writes a personal
12
+ * definition with the bundled content unchanged except for the skill value;
13
+ * that is the catalog's existing whole-definition override mechanism. An
14
+ * untrusted project never reaches this code because its definitions are not
15
+ * loaded at all.
16
+ */
17
+ import {
18
+ applySkillExposure,
19
+ definitionSkillPreference,
20
+ type CatalogDefinition,
21
+ type SkillExposureEdit,
22
+ } from "./catalog-schema.ts";
23
+ import { loadCatalog, saveDefinition, type LoadCatalogInput } from "./catalog-store.ts";
24
+
25
+ export interface SkillDefinitionTarget {
26
+ id: string;
27
+ /** The winning source shown when the screen opened; catches a stale edit. */
28
+ winningSource?: { path: string; contentDigest: string };
29
+ }
30
+
31
+ export interface SkillSaveResult {
32
+ ok: boolean;
33
+ message: string;
34
+ path?: string;
35
+ scope?: "user" | "project";
36
+ }
37
+
38
+ function sameSkillValue(left: string[] | null | undefined, right: string[] | null | undefined): boolean {
39
+ if (left === undefined || right === undefined) return left === right;
40
+ if (left === null || right === null) return left === right;
41
+ return left.length === right.length && left.every((value, index) => value === right[index]);
42
+ }
43
+
44
+ function actionLabel(edit: SkillExposureEdit): string {
45
+ if (edit.mode === "inherit") return "inherit";
46
+ if (edit.mode === "none") return "none (--no-skills)";
47
+ return `${edit.paths.length} selected`;
48
+ }
49
+
50
+ function alreadyMessage(definition: CatalogDefinition, edit: SkillExposureEdit): string {
51
+ if (edit.mode === "inherit") {
52
+ return definition.kind === "role"
53
+ ? `Skills already inherit for ${definition.id}; nothing was written.`
54
+ : `Skills already inherit the base role for ${definition.id}; nothing was written.`;
55
+ }
56
+ return `Skills already ${actionLabel(edit)} for ${definition.id}; nothing was written.`;
57
+ }
58
+
59
+ /**
60
+ * Save one skill choice for the definition behind an `/agents` screen.
61
+ *
62
+ * Returns `ok: false` without writing when the screen is stale, the definition
63
+ * is not structurally valid, or the definition save refuses the scope. The
64
+ * caller keeps its screen and reports the message.
65
+ */
66
+ export function saveSkillExposure(
67
+ input: LoadCatalogInput & { entry: SkillDefinitionTarget },
68
+ edit: SkillExposureEdit,
69
+ ): SkillSaveResult {
70
+ try {
71
+ const snapshot = loadCatalog(input);
72
+ const entry = snapshot.roles.get(input.entry.id) ?? snapshot.agents.get(input.entry.id);
73
+ if (!entry?.definition || !entry.structurallyValid || entry.duplicate) {
74
+ throw new Error(`Cannot save skills for ${input.entry.id}: repair the catalog definition first. Nothing changed.`);
75
+ }
76
+ const source = input.entry.winningSource;
77
+ if (!source) throw new Error(`Cannot save skills for ${input.entry.id}: the definition source is unavailable. Reopen its settings.`);
78
+ if (source.path !== entry.path || source.contentDigest !== entry.contentDigest) {
79
+ throw new Error(`${input.entry.id} changed since this screen opened. Reopen its settings. Nothing changed.`);
80
+ }
81
+
82
+ const before = definitionSkillPreference(entry.definition);
83
+ const next = applySkillExposure(entry.definition, edit);
84
+ const after = definitionSkillPreference(next);
85
+ if (sameSkillValue(before, after)) return { ok: true, message: alreadyMessage(entry.definition, edit) };
86
+
87
+ const scope = entry.scope === "project" ? "project" : "user";
88
+ const copiedFromBundled = entry.scope === "bundled";
89
+ const saved = saveDefinition({
90
+ ...input,
91
+ definition: next,
92
+ scope,
93
+ replace: true,
94
+ });
95
+ if (!saved.ok || !saved.path) {
96
+ throw new Error(saved.diagnostics.map((item) => item.message).join(" ") || `The ${scope} definition was not written.`);
97
+ }
98
+
99
+ const reloaded = loadCatalog(input);
100
+ const persisted = reloaded.roles.get(entry.id) ?? reloaded.agents.get(entry.id);
101
+ const reloadedValue = persisted?.definition ? definitionSkillPreference(persisted.definition) : undefined;
102
+ if (!persisted || !persisted.structurallyValid || !sameSkillValue(reloadedValue, after)) {
103
+ throw new Error(`Saved ${saved.path}, but the reloaded catalog did not report that skill value. Reopen its settings before relying on it.`);
104
+ }
105
+
106
+ const prefix = copiedFromBundled ? "Personal definition saved" : "Skills saved";
107
+ return {
108
+ ok: true,
109
+ path: saved.path,
110
+ scope: saved.scope,
111
+ message: `${prefix} (${saved.scope}): ${entry.id} · ${actionLabel(edit)}`,
112
+ };
113
+ } catch (error) {
114
+ return { ok: false, message: error instanceof Error ? error.message : String(error) };
115
+ }
116
+ }
package/catalog-ui.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { Input, SelectList, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
2
  import type { OperationList, OperationView } from "./agent-inspection.ts";
3
- import { EFFORT_LEVELS } from "./catalog-schema.ts";
3
+ import { EFFORT_LEVELS, type SkillExposureEdit } from "./catalog-schema.ts";
4
4
  import { catalogModelChoices, catalogModelOptionLabel, catalogModelScopeLabel, type ScopedModelLike } from "./catalog-editor.ts";
5
5
  import type { AgentSessionOverrides, AgentSettingKey } from "./agent-session-settings.ts";
6
+ import { createSkillPicker, type DiscoveredSkill } from "./skill-picker.ts";
6
7
 
7
8
  type Theme = { fg(color: string, text: string): string; bg?(color: string, text: string): string; bold?(text: string): string; inverse?(text: string): string };
8
9
 
@@ -14,6 +15,10 @@ export interface CatalogEditor {
14
15
  scopedModels?(): readonly ScopedModelLike[];
15
16
  settings(): AgentSessionOverrides;
16
17
  change(id: string, key: AgentSettingKey, value: string | null): void;
18
+ /** Skill exposure is edited through the definition save path, not session settings. */
19
+ changeSkills?(entry: OperationView, edit: SkillExposureEdit): { ok: boolean; message: string };
20
+ /** Loaded Pi skill metadata for the checkbox picker. */
21
+ discoverSkills?(): readonly DiscoveredSkill[];
17
22
  save(id: string): { ok: boolean; message: string };
18
23
  resetToBundled?(entry: OperationView): { ok: boolean; message: string };
19
24
  resetDefinition?(entry: OperationView): { ok: boolean; message: string };
@@ -30,6 +35,47 @@ function modelLabel(entry: OperationView): string {
30
35
  return entry.actualModel ?? entry.requestedModel ?? entry.fields?.model.value ?? "not resolved";
31
36
  }
32
37
 
38
+ /**
39
+ * The definition's visible skill mode. `inherit` is not discovery: an absent
40
+ * value or an explicit null still falls through the global default first.
41
+ */
42
+ export function skillsValueLabel(skills: OperationView["skills"]): string {
43
+ if (!skills) return "(unknown)";
44
+ if (skills.value === null) {
45
+ return skills.source === "agent-override" ? "inherit (role list suppressed)" : "inherit";
46
+ }
47
+ if (skills.value.length === 0) return "no skill catalog";
48
+ return `${skills.value.length} selected · ${skills.value.join(", ")}`;
49
+ }
50
+
51
+ /** Where the effective value comes from: agent override, base role, global config, or discovery. */
52
+ export function skillsOriginLabel(skills: OperationView["skills"], kind?: string): string {
53
+ if (!skills) return "unknown";
54
+ const own = skills.source === "agent-override" ? "override" : skills.source === "role-default"
55
+ ? kind === "role" ? "role default" : "inherited"
56
+ : undefined;
57
+ const base = skills.effective.source === "session" ? "session"
58
+ : skills.effective.source === "global" ? "global"
59
+ : skills.effective.source === "discovery" ? "discovery" : undefined;
60
+ const effective = base && skills.effective.mode === "error" ? `${base} (invalid)` : base;
61
+ if (own && effective) return `${own} → ${effective}`;
62
+ return own ?? effective ?? "discovery";
63
+ }
64
+
65
+ function skillsSettingLines(entry: OperationView, width: number, marker = " ", theme?: Theme): string[] {
66
+ if (!entry.skills) return [];
67
+ return settingLines("Skills", skillsValueLabel(entry.skills), skillsOriginLabel(entry.skills, entry.identity.kind), width, marker, theme);
68
+ }
69
+
70
+ /** The picker starts on the definition's own choice, not the inherited effective value. */
71
+ function skillChoiceIndex(entry: OperationView): 0 | 1 | 2 {
72
+ const skills = entry.skills;
73
+ if (!skills || skills.value === null) return 0;
74
+ const own = entry.identity.kind === "agent" ? skills.source === "agent-override" : true;
75
+ if (!own) return 0;
76
+ return skills.value.length === 0 ? 1 : 2;
77
+ }
78
+
33
79
  function cell(value: string, width: number): string {
34
80
  const clipped = truncateToWidth(value.replace(/[\r\n\t]+/g, " "), width);
35
81
  return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
@@ -112,6 +158,7 @@ export function catalogDetailLines(entry: OperationView, editable = false, width
112
158
  }) : []),
113
159
  ...settingLines("Tier", entry.fields.tier.value ?? "(unset)", entry.fields.tier.source === "role-default" ? "inherited" : entry.fields.tier.source === "agent-override" ? "override" : "absent", contentWidth, " ", theme),
114
160
  ] : []),
161
+ ...skillsSettingLines(entry, contentWidth, " ", theme),
115
162
  `${label("Actual")} ${entry.actualModel ?? "not resolved"}${entry.actualEffort ? ` · ${entry.actualEffort}` : ""}`,
116
163
  "",
117
164
  heading("Effective prompt"),
@@ -151,9 +198,10 @@ export function createCatalogComponent(
151
198
  let revealSetting = false;
152
199
  let picker: SelectList | undefined;
153
200
  let filterPicker: ((filter: string) => void) | undefined;
154
- let pickerKey: AgentSettingKey | undefined;
201
+ let pickerKey: AgentSettingKey | "skills" | undefined;
155
202
  let modelScopeNote: string | undefined;
156
203
  const search = new Input();
204
+ let skillPicker: ReturnType<typeof createSkillPicker> | undefined;
157
205
  let focused = false;
158
206
  let message = "";
159
207
  let error = false;
@@ -188,34 +236,112 @@ export function createCatalogComponent(
188
236
  report(result.message, !result.ok);
189
237
  } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
190
238
  }
239
+ /** Selectable setting rows in display order; Reset is a row, not a save action. */
240
+ function settingKeys(entry: OperationView | undefined): ("model" | "effort" | "skills" | "reset")[] {
241
+ return [
242
+ "model",
243
+ "effort",
244
+ ...(editor?.changeSkills && entry?.skills ? ["skills" as const] : []),
245
+ ...(canReset(entry) ? ["reset" as const] : []),
246
+ ];
247
+ }
248
+ const pickerTheme: ConstructorParameters<typeof SelectList>[2] = {
249
+ selectedPrefix: (text) => theme.fg("accent", text),
250
+ selectedText: (text) => theme.inverse?.(text) ?? theme.fg("accent", text),
251
+ description: (text) => theme.fg("dim", text),
252
+ scrollInfo: (text) => theme.fg("dim", text),
253
+ noMatch: (text) => theme.fg("warning", text),
254
+ };
255
+ function openSkillPaths(current: OperationView) {
256
+ picker = undefined;
257
+ search.focused = false;
258
+ message = "";
259
+ // Only the definition's own list is prefilled. An inherited list is shown
260
+ // in the picker; ticking creates an override instead of silently copying
261
+ // the role's value into this definition.
262
+ const own = current.identity.kind === "agent"
263
+ ? current.skills?.source === "agent-override" ? current.skills.value ?? [] : []
264
+ : current.skills?.value ?? [];
265
+ skillPicker = createSkillPicker({
266
+ theme, skills: editor?.discoverSkills?.() ?? [], selected: own,
267
+ requestRender, getHeight, title: "Selected skills",
268
+ apply(paths) {
269
+ if (!editor?.changeSkills) return { ok: false, message: "Skill editing is unavailable." };
270
+ try {
271
+ const result = editor.changeSkills(current, paths.length === 0
272
+ ? { mode: "none" }
273
+ : { mode: "explicit", paths: [...paths] });
274
+ if (result.ok) {
275
+ refresh();
276
+ report(paths.length === 0
277
+ ? "No skills checked. Skill exposure set to No skill catalog."
278
+ : result.message, false);
279
+ }
280
+ return { ok: result.ok, message: result.message };
281
+ } catch (cause) {
282
+ return { ok: false, message: cause instanceof Error ? cause.message : String(cause) };
283
+ }
284
+ },
285
+ finish() { skillPicker = undefined; requestRender(); },
286
+ cancel() {
287
+ skillPicker = undefined;
288
+ report("Skill selection unchanged.");
289
+ requestRender();
290
+ },
291
+ });
292
+ skillPicker.focused = focused;
293
+ requestRender();
294
+ }
295
+ function editSkills(current: OperationView) {
296
+ if (!editor?.changeSkills) return;
297
+ if (!current.definitionValid) { report("Repair the catalog definition before editing.", true); return; }
298
+ const items = [
299
+ { value: "inherit", label: "Inherit", description: current.identity.kind === "agent" ? "Remove this override; use the base role's list." : "Remove this default; use the global default or discovery." },
300
+ { value: "none", label: "No skill catalog", description: "Load no skills (--no-skills)." },
301
+ { value: "select", label: "Selected skills…", description: "One or more absolute SKILL.md or skill-directory paths." },
302
+ ];
303
+ pickerKey = "skills";
304
+ modelScopeNote = undefined;
305
+ search.focused = false;
306
+ picker = new SelectList(items, 8, pickerTheme);
307
+ picker.onCancel = () => { picker = undefined; };
308
+ picker.onSelect = (item) => {
309
+ if (item.value === "select") { openSkillPaths(current); return; }
310
+ try {
311
+ const result = editor!.changeSkills!(current, item.value === "none" ? { mode: "none" } : { mode: "inherit" });
312
+ refresh();
313
+ picker = undefined;
314
+ report(result.message, !result.ok);
315
+ } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
316
+ };
317
+ const selectedIndex = skillChoiceIndex(current);
318
+ picker.setSelectedIndex(selectedIndex);
319
+ }
191
320
  function edit() {
192
321
  const current = selected();
193
322
  if (!current || !editor) return;
194
- if (settingRow === 2) { reset(current); return; }
323
+ const keys = settingKeys(current);
324
+ const key = keys[settingRow];
325
+ if (!key) { settingRow = 0; return; }
326
+ if (key === "reset") { reset(current); return; }
327
+ if (key === "skills") { editSkills(current); return; }
195
328
  if (!current.definitionValid) { report("Repair the catalog definition before editing.", true); return; }
196
- const key: AgentSettingKey = settingRow === 0 ? "model" : "effort";
329
+ const setting: AgentSettingKey = key === "model" ? "model" : "effort";
197
330
  // Pi treats an empty scope as unrestricted. Scoped choices never include
198
331
  // an out-of-scope saved value; the detail view still displays it.
199
- const choices = key === "model"
332
+ const choices = setting === "model"
200
333
  ? catalogModelChoices({ scoped: editor.scopedModels?.(), available: editor.models(), current: current.fields?.model.value })
201
334
  : undefined;
202
335
  modelScopeNote = choices ? catalogModelScopeLabel(choices) : undefined;
203
336
  const items = [{ value: "", label: "Inherit" }, ...(choices
204
337
  ? choices.values.map((value) => ({ value, label: catalogModelOptionLabel(choices, value) }))
205
338
  : EFFORT_LEVELS.map((value) => ({ value, label: value })))];
206
- pickerKey = key;
339
+ pickerKey = setting;
207
340
  search.setValue("");
208
- search.focused = focused && key === "model";
209
- const pickerTheme: ConstructorParameters<typeof SelectList>[2] = {
210
- selectedPrefix: (text) => theme.fg("accent", text),
211
- selectedText: (text) => theme.inverse?.(text) ?? theme.fg("accent", text),
212
- description: (text) => theme.fg("dim", text),
213
- scrollInfo: (text) => theme.fg("dim", text),
214
- noMatch: (text) => theme.fg("warning", text),
215
- };
341
+ search.focused = focused && setting === "model";
216
342
  const onSelect = (item: { value: string }) => {
217
343
  try {
218
- editor.change(current.id, key, item.value || null);
344
+ editor.change(current.id, setting, item.value || null);
219
345
  refresh();
220
346
  picker = undefined;
221
347
  search.focused = false;
@@ -231,7 +357,7 @@ export function createCatalogComponent(
231
357
  // A saved value the scope does not offer is not in the list. Highlight
232
358
  // the first offered model instead of "Inherit" so Enter does not clear
233
359
  // the saved preference by accident.
234
- const currentIndex = items.findIndex((item) => item.value === current.fields?.[key].value);
360
+ const currentIndex = items.findIndex((item) => item.value === current.fields?.[setting].value);
235
361
  picker!.setSelectedIndex(Math.max(0, currentIndex >= 0 ? currentIndex : choices && choices.scope === "scoped" ? 1 : 0));
236
362
  }
237
363
  const filtered = () => catalog.entries.filter((entry) =>
@@ -253,8 +379,11 @@ export function createCatalogComponent(
253
379
  ...(entry.shadowed.length ? ["", theme.fg("muted", "Shadowed definitions"), ...entry.shadowed.map(source => `${source.scope}: ${source.path}`)] : []),
254
380
  ];
255
381
  else lines = [
256
- ...(editor ? controls : (["model", "effort"] as const).flatMap(key => settingLines(key === "model" ? "Model" : "Effort", entry.fields?.[key].value ?? "(unset)", entry.fields?.[key].inherited || entry.fields?.[key].source === "role-default" ? "inherited" : "catalog", Math.max(1, width - 4), " ", theme))),
257
- "", theme.fg("dim", "Model and effort save separately from instructions."), "",
382
+ ...(editor ? controls : [
383
+ ...(["model", "effort"] as const).flatMap(key => settingLines(key === "model" ? "Model" : "Effort", entry.fields?.[key].value ?? "(unset)", entry.fields?.[key].inherited || entry.fields?.[key].source === "role-default" ? "inherited" : "catalog", Math.max(1, width - 4), " ", theme)),
384
+ ...skillsSettingLines(entry, Math.max(1, width - 4), " ", theme),
385
+ ]),
386
+ "", theme.fg("dim", "Model and effort are session edits. Skills save to the definition."), "",
258
387
  `ID ${entry.id}`, `Scope ${entry.identity.scope ?? "unknown"}`,
259
388
  ...(entry.role?.id && entry.identity.kind === "agent" ? [`Role ${entry.role.id}`] : []),
260
389
  `Tier ${entry.fields?.tier.value ?? "(unset)"}`,
@@ -269,13 +398,18 @@ export function createCatalogComponent(
269
398
 
270
399
  return {
271
400
  get focused() { return focused; },
272
- set focused(value: boolean) { focused = value; search.focused = value && !!picker && pickerKey === "model"; },
401
+ set focused(value: boolean) {
402
+ focused = value;
403
+ search.focused = value && !!picker && pickerKey === "model";
404
+ if (skillPicker) skillPicker.focused = value;
405
+ },
273
406
  render(width: number): string[] {
274
407
  resetPointerRows = [];
275
408
  resetPointerEntry = undefined;
276
409
  const safeWidth = Math.max(1, width);
277
410
  const height = Math.max(1, Math.floor(getHeight()));
278
- const footerRows = (editor ? 2 : 0) + (message ? 2 : 0);
411
+ const messageLines = message ? wrapLine(theme.fg(error ? "error" : "muted", message), safeWidth) : [];
412
+ const footerRows = (editor ? 2 : 0) + (messageLines.length > 0 ? messageLines.length + 1 : 0);
279
413
  const diagnosticRows = Math.min(catalog.diagnostics.length, 3);
280
414
  const listSize = Math.max(1, height - 5 - footerRows - diagnosticRows - 1);
281
415
  const detailSize = Math.max(1, height - 6 - footerRows);
@@ -292,12 +426,16 @@ export function createCatalogComponent(
292
426
  const selectedIndex = rows.findIndex((entry) => entry.id === selectedId);
293
427
  const start = Math.max(0, Math.min(selectedIndex - Math.floor(listSize / 2), rows.length - listSize));
294
428
 
429
+ if (skillPicker) return fit(skillPicker.render(safeWidth));
295
430
  if (picker) return fit([
296
431
  theme.fg("accent", `Agents / ${pickerKey}`), "",
432
+ ...(pickerKey === "skills" && current
433
+ ? [theme.fg("dim", `${skillsValueLabel(current.skills)} · ${skillsOriginLabel(current.skills, current.identity.kind)}`), ""]
434
+ : []),
297
435
  ...(pickerKey === "model" && modelScopeNote ? [theme.fg("dim", modelScopeNote), ""] : []),
298
436
  ...(pickerKey === "model" ? search.render(safeWidth) : []),
299
437
  ...picker.render(safeWidth),
300
- ...(message ? [theme.fg(error ? "error" : "muted", message)] : []),
438
+ ...(messageLines.length ? ["", ...messageLines] : []),
301
439
  ]);
302
440
  const controls = editor && mode === "detail" && current ? [
303
441
  ...["Model", "Effort"].flatMap((label, index) => {
@@ -313,11 +451,13 @@ export function createCatalogComponent(
313
451
  : current.identity.scope === "bundled" && !inherited ? "bundled" : field?.inherited ? "inherited" : "catalog";
314
452
  return settingLines(label, field?.value ?? "(unset)", origin, Math.max(1, safeWidth - 4), settingRow === index ? "> " : " ", theme);
315
453
  }),
316
- ...(canReset(current) ? [theme.fg(settingRow === 2 ? "accent" : "muted", `${settingRow === 2 ? "> " : " "}Reset to bundled`), theme.fg("dim", " Restores model/effort; keeps the role prompt.")] : []),
454
+ ...(editor.changeSkills && current.skills ? skillsSettingLines(current, Math.max(1, safeWidth - 4), settingRow === settingKeys(current).indexOf("skills") ? "> " : " ", theme) : []),
455
+ ...(canReset(current) ? [theme.fg(settingRow === settingKeys(current).indexOf("reset") ? "accent" : "muted", `${settingRow === settingKeys(current).indexOf("reset") ? "> " : " "}Reset to bundled`), theme.fg("dim", " Restores model/effort; keeps the role prompt.")] : []),
317
456
  ] : [];
318
457
  const detailLines = current ? detailRows(current, safeWidth, controls) : [];
458
+ const keys = current ? settingKeys(current) : [];
319
459
  if (editor && mode === "detail") {
320
- settingPositions = ["Model", "Effort", ...(canReset(current) ? ["Reset to bundled"] : [])].map((label) => detailLines.findIndex((text) =>
460
+ settingPositions = ["Model", "Effort", ...(editor.changeSkills && current?.skills ? ["Skills"] : []), ...(canReset(current) ? ["Reset to bundled"] : [])].map((label) => detailLines.findIndex((text) =>
321
461
  new RegExp(`^ [> ] ${label}(?:\\s|$)`).test(text.replace(/\x1b\[[0-9;]*m/g, ""))));
322
462
  if (revealSetting && settingPositions[settingRow] >= 0) {
323
463
  const position = settingPositions[settingRow];
@@ -328,7 +468,7 @@ export function createCatalogComponent(
328
468
  }
329
469
  scroll = Math.max(0, Math.min(scroll, detailLines.length - detailSize));
330
470
  if (mode === "detail" && current && canReset(current)) {
331
- const position = settingPositions[2];
471
+ const position = settingPositions[keys.indexOf("reset")];
332
472
  if (position >= scroll && position < scroll + detailSize) {
333
473
  resetPointerRows = [4 + position - scroll];
334
474
  resetPointerEntry = current;
@@ -367,11 +507,16 @@ export function createCatalogComponent(
367
507
  ...(catalog.diagnostics.length > 2 ? [theme.fg("warning", `! ${catalog.diagnostics.length - 2} more catalog diagnostics`)] : []),
368
508
  ];
369
509
  if (editor) lines.push("", theme.fg("dim", "Ctrl+S Save defaults"));
370
- if (message) lines.push("", theme.fg(error ? "error" : "muted", message));
510
+ if (messageLines.length) lines.push("", ...messageLines);
371
511
  return fit(lines);
372
512
  },
373
513
  handleInput(data: string): void {
374
514
  const rows = filtered();
515
+ if (skillPicker) {
516
+ skillPicker.handleInput(data);
517
+ requestRender();
518
+ return;
519
+ }
375
520
  if (picker) {
376
521
  if (pickerKey === "model" && !(["up", "down", "enter", "escape"] as const).some((key) => matchesKey(data, key))) {
377
522
  search.handleInput(data);
@@ -431,7 +576,7 @@ export function createCatalogComponent(
431
576
  },
432
577
  handleMouse(event: { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean }) {
433
578
  const entry = resetPointerEntry;
434
- const hit = !picker && (mode === "detail" || mode === "prompt") && entry && event.button === "left" && !event.shift && !event.alt && !event.ctrl
579
+ const hit = !picker && !skillPicker && (mode === "detail" || mode === "prompt") && entry && event.button === "left" && !event.shift && !event.alt && !event.ctrl
435
580
  && event.x >= 0 && event.x < event.width && resetPointerRows.includes(event.y);
436
581
  if (event.type === "press") {
437
582
  pressedReset = hit ? entry : undefined;
@@ -445,6 +590,6 @@ export function createCatalogComponent(
445
590
  reset(pressed, mode === "prompt");
446
591
  return { handled: true as const, render: true };
447
592
  },
448
- invalidate() { picker?.invalidate(); search.invalidate(); },
593
+ invalidate() { picker?.invalidate(); search.invalidate(); skillPicker?.invalidate(); },
449
594
  };
450
595
  }