@herbertgao/pi-extensions 2026.11.17 → 2026.11.18

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @herbertgao/pi-extensions
2
2
 
3
+ ## 2026.11.18
4
+
5
+ ### Patch Changes
6
+
7
+ - [#402](https://github.com/HerbertGao/pi-extensions/pull/402) [`f0109df`](https://github.com/HerbertGao/pi-extensions/commit/f0109dfd7bb213fe26260a0c882e45d2bf83935d) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Color the ccstyle Agent tool rows with each type's configured badge. pi-subagents exposes the label and color of every spawnable type over a new `subagents:rpc:list-agents` bus channel and announces registry changes with a `subagents:agents-changed` event; pi-cc-extensions pulls the table on `subagents:ready` and renders Agent rows as padded background badges (same palette, hex, 256-color quantization, and contrast rules as pi-subagents' own badges). Without pi-subagents on the bus the rows stay plain text.
8
+
9
+ - [#401](https://github.com/HerbertGao/pi-extensions/pull/401) [`09bed8a`](https://github.com/HerbertGao/pi-extensions/commit/09bed8a789c603958995746d073982b92a1d92fe) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Pin graphifyy 0.9.113. The CLI stays outside the npm aggregate. Warm AST caches rebuild. Python is now >=3.11.5,<3.15. The Pi skill path is unchanged.
10
+
11
+ - Updated dependencies [[`f0109df`](https://github.com/HerbertGao/pi-extensions/commit/f0109dfd7bb213fe26260a0c882e45d2bf83935d), [`f7e030f`](https://github.com/HerbertGao/pi-extensions/commit/f7e030f578bb73f401d74fa4bac2b67947bc997a)]:
12
+ - @herbertgao/pi-cc-extensions@1.0.21
13
+ - @herbertgao/pi-subagents@0.26.1
14
+ - @herbertgao/pi-inline-skill-commands@0.2.0
15
+
3
16
  ## 2026.11.17
4
17
 
5
18
  ### Patch Changes
@@ -1,5 +1,11 @@
1
1
  # @herbertgao/pi-cc-extensions
2
2
 
3
+ ## 1.0.21-local.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [#402](https://github.com/HerbertGao/pi-extensions/pull/402) [`f0109df`](https://github.com/HerbertGao/pi-extensions/commit/f0109dfd7bb213fe26260a0c882e45d2bf83935d) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Color the ccstyle Agent tool rows with each type's configured badge. pi-subagents exposes the label and color of every spawnable type over a new `subagents:rpc:list-agents` bus channel and announces registry changes with a `subagents:agents-changed` event; pi-cc-extensions pulls the table on `subagents:ready` and renders Agent rows as padded background badges (same palette, hex, 256-color quantization, and contrast rules as pi-subagents' own badges). Without pi-subagents on the bus the rows stay plain text.
8
+
3
9
  ## 1.0.21-local.2
4
10
 
5
11
  ### Patch Changes
@@ -1,5 +1,6 @@
1
1
  import { ToolExecutionComponent, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import type { CompactThinkingController } from "../feature/compact-thinking.ts";
3
+ import { initAgentBadges, refreshAgentBadges } from "./tool/agent-badge.ts";
3
4
  import { installToolGrouping, type ToolGroupingHooks } from "./tool/grouping.ts";
4
5
  import {
5
6
  installCompactMode,
@@ -116,6 +117,9 @@ export default function (
116
117
  ) {
117
118
  // 可选 override:集成测试不依赖用户全局配置。
118
119
  if (configOverride) setConfig(normalizeConfig({ ...config, ...configOverride }));
120
+ // Agent 行的徽章颜色表:subagents:ready 后拉取、agents-changed 时刷新。
121
+ // pi-subagents 缺席或过旧时缓存为空,行渲染保持纯文本。
122
+ initAgentBadges(pi.events);
119
123
  const writeExecutionMetadata = new WriteExecutionMetadataStore();
120
124
  const mouseOwner = {};
121
125
  let installation:
@@ -239,6 +243,9 @@ export default function (
239
243
  });
240
244
 
241
245
  pi.on("session_start", async (event, ctx) => {
246
+ // 徽章表随会话重新拉取:pi-subagents 在场时无论 session_start 处理顺序
247
+ // 先后都会填上;缺席时超时清空,保持纯文本而不是沿用旧颜色。
248
+ refreshAgentBadges(pi.events);
242
249
  // 延后一拍再确认 write 归属:其他扩展同样在各自的 session_start 里注册工具,
243
250
  // 本 handler 执行时可能还看不到对方,此时注册会与对方撞名(注册表先到先得),
244
251
  // 对方的 write 会被静默丢弃。等所有 session_start 跑完,检测结果才是权威的。
@@ -0,0 +1,244 @@
1
+ /**
2
+ * agent-badge.ts — pi-subagents agent badges on ccstyle tool rows.
3
+ *
4
+ * The color math mirrors pi-subagents/src/agent-color.ts (pure ANSI geometry:
5
+ * palette names, hex, 256-color quantization, WCAG contrast). It is copied
6
+ * rather than imported because the two packages must stay independently
7
+ * installable; keep the copies in sync when that file changes.
8
+ *
9
+ * The type→color table is NOT copied: it lives in pi-subagents' registry, so
10
+ * this module pulls it over the event bus (`subagents:rpc:list-agents`) once
11
+ * per session — on `subagents:ready` — and again on `subagents:agents-changed`
12
+ * (a mid-session ephemeral registration). Without an answer the cache stays
13
+ * empty and rows render exactly as before.
14
+ */
15
+
16
+ /** The slice of pi's event bus the list-agents client needs. */
17
+ export interface BadgeEvents {
18
+ on(event: string, handler: (data: unknown) => void): () => void;
19
+ emit(event: string, data: unknown): void;
20
+ }
21
+
22
+ /** Same theme shape pi-subagents' badge renderer takes. */
23
+ export interface BadgeTheme {
24
+ fg(color: string, text: string): string;
25
+ bold?(text: string): string;
26
+ getColorMode?(): "truecolor" | "256color";
27
+ }
28
+
29
+ // ---- Color math (mirrored; see the header) ----
30
+
31
+ export const NAMED_AGENT_COLORS: Readonly<Record<string, string>> = {
32
+ red: "#DC2626",
33
+ blue: "#6A9BCC",
34
+ green: "#16A34A",
35
+ yellow: "#CA8A04",
36
+ purple: "#827DBD",
37
+ orange: "#D97757",
38
+ pink: "#C46686",
39
+ cyan: "#0891B2",
40
+ amber: "#F59E0B",
41
+ teal: "#008080",
42
+ indigo: "#6366F1",
43
+ gold: "#EAB308",
44
+ "neon-green": "#10B981",
45
+ "neon-cyan": "#06B6D4",
46
+ "metallic-blue": "#3B82F6",
47
+ violet: "#8B5CF6",
48
+ rose: "#F43F5E",
49
+ lime: "#84CC16",
50
+ gray: "#6B7280",
51
+ grey: "#6B7280",
52
+ fuchsia: "#D946EF",
53
+ slate: "#64748B",
54
+ navy: "#1E3A8A",
55
+ };
56
+
57
+ const CUBE_VALUES = [0, 95, 135, 175, 215, 255];
58
+ const GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);
59
+ const BLACK = { r: 0, g: 0, b: 0 };
60
+ const WHITE = { r: 255, g: 255, b: 255 };
61
+
62
+ type Rgb = { r: number; g: number; b: number };
63
+
64
+ export function resolveAgentColor(value: string | undefined): string | undefined {
65
+ if (!value) return undefined;
66
+ const normalized = value.trim().toLowerCase();
67
+ const resolved = NAMED_AGENT_COLORS[normalized] ?? normalized;
68
+ return /^#[0-9a-f]{6}$/i.test(resolved) ? resolved.toUpperCase() : undefined;
69
+ }
70
+
71
+ function parseHex(hex: string): Rgb {
72
+ return {
73
+ r: Number.parseInt(hex.slice(1, 3), 16),
74
+ g: Number.parseInt(hex.slice(3, 5), 16),
75
+ b: Number.parseInt(hex.slice(5, 7), 16),
76
+ };
77
+ }
78
+
79
+ function nearest(values: readonly number[], value: number): number {
80
+ return values.reduce(
81
+ (best, v, i) => (Math.abs(value - v) < Math.abs(value - values[best]) ? i : best),
82
+ 0,
83
+ );
84
+ }
85
+
86
+ function rgbTo256({ r, g, b }: Rgb): { index: number; rgb: Rgb } {
87
+ const [rIndex, gIndex, bIndex] = [r, g, b].map((channel) => nearest(CUBE_VALUES, channel));
88
+ const distance = ({ r: cr, g: cg, b: cb }: Rgb) =>
89
+ 0.299 * (r - cr) ** 2 + 0.587 * (g - cg) ** 2 + 0.114 * (b - cb) ** 2;
90
+ const grayIndex = nearest(GRAY_VALUES, Math.round(0.299 * r + 0.587 * g + 0.114 * b));
91
+ const gray = { r: GRAY_VALUES[grayIndex], g: GRAY_VALUES[grayIndex], b: GRAY_VALUES[grayIndex] };
92
+ const cube = { r: CUBE_VALUES[rIndex], g: CUBE_VALUES[gIndex], b: CUBE_VALUES[bIndex] };
93
+ if (Math.max(r, g, b) - Math.min(r, g, b) < 10 && distance(gray) < distance(cube)) {
94
+ return { index: 232 + grayIndex, rgb: gray };
95
+ }
96
+ return { index: 16 + 36 * rIndex + 6 * gIndex + bIndex, rgb: cube };
97
+ }
98
+
99
+ function relativeLuminance({ r, g, b }: Rgb): number {
100
+ const linear = (value: number) => {
101
+ const channel = value / 255;
102
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
103
+ };
104
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
105
+ }
106
+
107
+ /** Render one name as a padded background badge; plain text when no valid color. */
108
+ export function renderAgentBadge(
109
+ name: string,
110
+ color: string | undefined,
111
+ theme: BadgeTheme,
112
+ ): string {
113
+ const resolved = resolveAgentColor(color);
114
+ if (!resolved) return name;
115
+ const rgb = parseHex(resolved);
116
+ const quantized =
117
+ (theme.getColorMode?.() ?? "truecolor") === "256color" ? rgbTo256(rgb) : undefined;
118
+ const shown = quantized?.rgb ?? rgb;
119
+ const contrasting = relativeLuminance(shown) > 0.179 ? BLACK : WHITE;
120
+ const label = theme.bold ? theme.bold(` ${name} `) : ` ${name} `;
121
+ // fg 与 bg 合并在同一个 SGR、以全量 reset 收尾:ccstyle 的行重绘器
122
+ // (stripBackgroundAnsi)只剥以背景码开头的转义,合并序列原样存活;它又在
123
+ // 每个 \u001b[0m 后补回行底色,所以徽章结尾用 0m 而不是 39m/49m —— 后者的
124
+ // 49m 被剥掉后徽章底色会一直铺到行尾。
125
+ const fgPart = quantized
126
+ ? `38;5;${rgbTo256(contrasting).index}`
127
+ : `38;2;${contrasting.r};${contrasting.g};${contrasting.b}`;
128
+ const bgPart = quantized ? `48;5;${quantized.index}` : `48;2;${rgb.r};${rgb.g};${rgb.b}`;
129
+ return `\u001b[${fgPart};${bgPart}m${label}\u001b[0m`;
130
+ }
131
+
132
+ // ---- Cache + bus client ----
133
+
134
+ type AgentBadgeInfo = { displayName?: string; color?: string };
135
+
136
+ /** type (lowercased) → the label and color pi-subagents reported. */
137
+ const badgeCache = new Map<string, AgentBadgeInfo>();
138
+
139
+ function fillCache(agents: Array<Record<string, unknown>>): void {
140
+ badgeCache.clear();
141
+ for (const agent of agents) {
142
+ if (typeof agent?.name !== "string") continue;
143
+ badgeCache.set(agent.name.toLowerCase(), {
144
+ displayName: typeof agent.displayName === "string" ? agent.displayName : undefined,
145
+ color: typeof agent.color === "string" ? agent.color : undefined,
146
+ });
147
+ }
148
+ }
149
+
150
+ /** Monotonic pull generation: only the LATEST pull may mutate the cache. A
151
+ * superseded pull is inert — its timeout must not wipe a newer pull's fill (the
152
+ * aggregate loads cc-extensions before pi-subagents, so the session-start pull
153
+ * races subagents:ready), and its late reply must not overwrite it. */
154
+ let fetchGeneration = 0;
155
+
156
+ async function fetchAgentBadges(events: BadgeEvents, timeoutMs = 2000): Promise<void> {
157
+ const generation = ++fetchGeneration;
158
+ const requestId = `ccstyle-badges-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
159
+ const channel = `subagents:rpc:list-agents:reply:${requestId}`;
160
+ return new Promise((resolve) => {
161
+ let timer: ReturnType<typeof setTimeout>;
162
+ const superseded = () => generation !== fetchGeneration;
163
+ // Silence or a bad reply from the LATEST pull clears the cache: a session
164
+ // where pi-subagents is filtered out must fall back to plain rows, not
165
+ // keep the previous session's colors for types that can no longer spawn.
166
+ const apply = (mutate: () => void) => {
167
+ if (superseded()) return resolve();
168
+ mutate();
169
+ resolve();
170
+ };
171
+ const clearAndResolve = () => apply(() => badgeCache.clear());
172
+ const unsub = events.on(channel, (raw) => {
173
+ clearTimeout(timer);
174
+ unsub();
175
+ const reply = raw as
176
+ | { success: true; data?: { agents?: Array<Record<string, unknown>> } }
177
+ | { success: false };
178
+ // A malformed envelope is silence, not a crash inside the bus dispatch.
179
+ if (!raw || typeof raw !== "object" || typeof reply.success !== "boolean") {
180
+ clearAndResolve();
181
+ return;
182
+ }
183
+ if (reply.success && Array.isArray(reply.data?.agents))
184
+ apply(() => fillCache(reply.data!.agents!));
185
+ else clearAndResolve();
186
+ });
187
+ timer = setTimeout(() => {
188
+ unsub();
189
+ clearAndResolve();
190
+ }, timeoutMs);
191
+ events.emit("subagents:rpc:list-agents", { requestId });
192
+ });
193
+ }
194
+
195
+ let unsubscribeBadges: (() => void) | undefined;
196
+
197
+ /**
198
+ * Subscribe the cache to pi-subagents' lifecycle: pull on ready, re-pull when
199
+ * the spawnable set changes. Idempotent — a second invocation replaces the
200
+ * first subscription, so repeated factory runs (integration tests) never
201
+ * stack listeners. The subscriptions live for the process; subagents:ready
202
+ * re-fires per session.
203
+ */
204
+ export function initAgentBadges(events: BadgeEvents | undefined, timeoutMs = 2000): () => void {
205
+ // Headless hosts and test harnesses may expose no bus; without one there is
206
+ // nothing to pull and rows simply stay plain.
207
+ if (!events?.on || !events.emit) return () => {};
208
+ unsubscribeBadges?.();
209
+ const pull = () => {
210
+ void fetchAgentBadges(events, timeoutMs);
211
+ };
212
+ const unsubReady = events.on("subagents:ready", pull);
213
+ const unsubChanged = events.on("subagents:agents-changed", pull);
214
+ unsubscribeBadges = () => {
215
+ unsubReady();
216
+ unsubChanged();
217
+ };
218
+ return unsubscribeBadges;
219
+ }
220
+
221
+ /** Drop the cached table (tests and the session-start refresh use this). */
222
+ export function clearAgentBadges(): void {
223
+ badgeCache.clear();
224
+ }
225
+
226
+ /** Pull the table now. The renderer calls this on its own session_start: a
227
+ * present pi-subagents refills regardless of handler order (its own ready pull
228
+ * may have run before ours), and an absent one leaves the timeout's clear in
229
+ * place — so a filtered-out session starts plain instead of keeping the
230
+ * previous session's colors. */
231
+ export function refreshAgentBadges(events: BadgeEvents | undefined): void {
232
+ if (!events?.on || !events.emit) return;
233
+ void fetchAgentBadges(events);
234
+ }
235
+
236
+ /** A styled badge for a spawnable type, or undefined when its color is unknown. */
237
+ export function agentBadge(type: string, theme: BadgeTheme): string | undefined {
238
+ const info = badgeCache.get(type.toLowerCase());
239
+ // A configured-but-invalid color is "no badge" (same rule as pi-subagents'
240
+ // hasAgentBadge), so the row keeps its normal toolTitle rendering instead of
241
+ // a bare unstyled name.
242
+ if (!info?.color || !resolveAgentColor(info.color)) return undefined;
243
+ return renderAgentBadge(info.displayName || type, info.color, theme);
244
+ }
@@ -503,7 +503,7 @@ export function createCcstyleTool(
503
503
  cachedIcon = icon;
504
504
  // 路径按最终可用宽度中间截断,避免整行二次截断隐藏文件名。
505
505
  cachedLine = truncateToWidth(
506
- `${lead}${icon} ${renderToolSummary(summary, mainWidth, theme.fg.bind(theme))}${extraStyled}`,
506
+ `${lead}${icon} ${renderToolSummary(summary, mainWidth, theme.fg.bind(theme), theme)}${extraStyled}`,
507
507
  viewportWidth,
508
508
  "",
509
509
  );
@@ -23,6 +23,7 @@ import {
23
23
  } from "./codemode.ts";
24
24
  import { getToolMouseTui } from "../mouse/scroll.ts";
25
25
  import { mcpToolTitle } from "./mcp-title.ts";
26
+ import { type BadgeTheme } from "./agent-badge.ts";
26
27
  import { collapseHintText, isToolTuiFullscreen, showMoreHintText } from "./names.ts";
27
28
  import {
28
29
  contentRowRange,
@@ -370,12 +371,18 @@ function shellResultTail(
370
371
  }
371
372
 
372
373
  /** 子工具折叠行正文:与组内同一套摘要。 */
373
- function toolSummaryText(tool: any, toolStatus: ToolStatus, width: number, fg: Fg): string {
374
+ function toolSummaryText(
375
+ tool: any,
376
+ toolStatus: ToolStatus,
377
+ width: number,
378
+ fg: Fg,
379
+ theme?: BadgeTheme,
380
+ ): string {
374
381
  const summary = askUserResultSummary(tool) ?? codemodeResultSummary(tool) ?? toolSummary(tool);
375
382
  const detail = fg("dim", summary.detail);
376
383
  const result = agentResultTail(tool, fg) + shellResultTail(tool, fg, toolStatus);
377
384
  const mainWidth = Math.max(0, width - visibleWidth(detail) - visibleWidth(result));
378
- return `${renderToolSummary(summary, mainWidth, fg)}${detail}${result}`;
385
+ return `${renderToolSummary(summary, mainWidth, fg, theme)}${detail}${result}`;
379
386
  }
380
387
 
381
388
  /**
@@ -437,7 +444,7 @@ function toolItem(tool: any): GroupDisplayItem {
437
444
  name: toolName(tool),
438
445
  label: toolTitle(tool),
439
446
  status: toolStatus,
440
- summary: (width, theme) => toolSummaryText(tool, toolStatus, width, themeFg(theme)),
447
+ summary: (width, theme) => toolSummaryText(tool, toolStatus, width, themeFg(theme), theme),
441
448
  expandedRows: (width) => expandedToolRows(tool, width),
442
449
  hitTarget: tool,
443
450
  };
@@ -4,6 +4,7 @@ import { visibleWidth } from "@earendil-works/pi-tui";
4
4
  import { keyText } from "../../utils/keybindings.ts";
5
5
  import { config } from "../../config/config.ts";
6
6
  import { oneLine } from "../../utils/format.ts";
7
+ import { agentBadge, type BadgeTheme } from "./agent-badge.ts";
7
8
  import { headTruncateToWidth } from "./result.ts";
8
9
 
9
10
  /** toolLabelClip=0 时不设字符上限,交给渲染时的实际宽度截断。 */
@@ -64,6 +65,8 @@ export type ToolCallSummaryOptions = {
64
65
  export type ToolCallSummary = {
65
66
  main: string;
66
67
  detail: string;
68
+ /** Agent 行的派发类型:渲染层据它在类型有配置色时画徽章,替换标题里的类型名。 */
69
+ agentType?: string;
67
70
  /** 路径摘要保留结构,供最终渲染按实际宽度优先保留文件名。 */
68
71
  path?: { prefix: string; value: string };
69
72
  /** 标题之外的原始载荷(入参 JSON、脚本代码、命令、路径、查询…),已压成单行,渲染时用 muted 接在标题后。 */
@@ -282,6 +285,9 @@ export function toolCallSummary(
282
285
  return {
283
286
  main: `${title} ${displayName}`,
284
287
  detail: "",
288
+ // 徽章按「派发类型」查表,绝不按运行名:general-purpose 运行即使起名
289
+ // Code Reviewer,也不能捡到同名注册类型的颜色。
290
+ agentType: typeof type === "string" ? type : undefined,
285
291
  payload: description ? `\u00b7 ${description}` : undefined,
286
292
  };
287
293
  }
@@ -425,6 +431,7 @@ export function renderToolSummary(
425
431
  summary: ToolCallSummary,
426
432
  width: number,
427
433
  fg: (color: ThemeColor, text: string) => string,
434
+ theme?: BadgeTheme,
428
435
  ): string {
429
436
  // 路径摘要:前缀用标题色,值用次级色并按可用宽度中间截断(文件名优先保留)。
430
437
  if (summary.path) {
@@ -433,6 +440,17 @@ export function renderToolSummary(
433
440
  if (pathWidth < MIN_PAYLOAD_WIDTH) return fg("toolTitle", prefix);
434
441
  return `${fg("toolTitle", prefix)} ${fg("muted", truncatePathToWidth(summary.path.value, Math.min(pathWidth, clipLimit())))}`;
435
442
  }
443
+ // Agent 行:类型有配置色时用 pi-subagents 同款徽章替换「Subagent 类型名」标题,
444
+ // 无色或缓存未命中时保持纯文本(缓存在 subagents:ready / agents-changed 后拉取)。
445
+ if (summary.agentType && theme) {
446
+ const badge = agentBadge(summary.agentType, theme);
447
+ if (badge) {
448
+ const room = width - visibleWidth(badge);
449
+ return room >= MIN_PAYLOAD_WIDTH && summary.payload
450
+ ? `${badge}${fg("muted", headTruncateToWidth(` ${summary.payload}`, room))}`
451
+ : badge;
452
+ }
453
+ }
436
454
  const title = fitToolCallSummary(summary, width);
437
455
  if (!summary.payload) return fg("toolTitle", title);
438
456
  const room = width - visibleWidth(title);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-cc-extensions",
3
- "version": "1.0.21-local.2",
3
+ "version": "1.0.21-local.3",
4
4
  "license": "MIT",
5
5
  "description": "A Pi productivity suite with Claude Code-style UI, context inspection, and agent/session references",
6
6
  "type": "module",
@@ -24,6 +24,24 @@ pi install /absolute/path/to/pi-extensions/packages/pi-inline-skill-commands
24
24
 
25
25
  Restart Pi or run `/reload` after installation. If `@herbertgao/pi-extensions` already provides this extension, do not install the standalone package as well.
26
26
 
27
+ ## Session names
28
+
29
+ Expanding a skill rewrites the stored prompt, so `/resume` would otherwise show the skill body. A brand-new session is therefore named with the prompt you typed, both for a mid-prompt command and for a native start-of-prompt one, and later prompts leave that name alone. Extension-authored prompts do not trigger it.
30
+
31
+ ```text
32
+ Check this using the same pattern /skill:test
33
+ ```
34
+
35
+ That session appears in `/resume` as the sentence above, not as the expanded block. A prompt is named when it carries a recognised skill command: a native start-of-prompt command is named whether or not the skill exists, while a mid-prompt one is named only when it actually expands.
36
+
37
+ Sessions created before this package was installed keep their stored block until you run:
38
+
39
+ ```text
40
+ /resume-session-name
41
+ ```
42
+
43
+ It rebuilds the typed prompt from the first message's skill block (`/skill:name argue this` for a native command, the original sentence for a mid-prompt one) and sets it as the session name. Because a native block stores only the arguments, args that repeat the command itself (`/skill:name write about /skill:name usage`) come back without the leading command. Renaming writes one `session_info` entry, the same as `/name`, so `/name` and `/resume` both see it. The command reports a message and changes nothing when the first message with non-blank text has no skill block.
44
+
27
45
  ## Compatibility
28
46
 
29
47
  Pi currently filters `/` out of extension-provided autocomplete trigger characters. To provide automatic mid-text completion anyway, this package patches `CustomEditor` once and calls its private autocomplete trigger. It does not replace the active editor factory, so editor customizations from other packages remain in place. That internal dependency can break when Pi changes its editor. If the private trigger is unavailable, mid-text Tab completion and submission-time expansion still work.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-inline-skill-commands",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Complete and expand Pi's native /skill:name commands within a larger prompt.",
5
5
  "keywords": [
6
6
  "autocomplete",
@@ -3,10 +3,13 @@ import {
3
3
  CustomEditor,
4
4
  DefaultResourceLoader,
5
5
  getAgentDir,
6
+ parseSkillBlock,
6
7
  SettingsManager,
7
8
  stripFrontmatter,
8
9
  type ExtensionAPI,
9
10
  type ExtensionContext,
11
+ type InputSource,
12
+ type ParsedSkillBlock,
10
13
  type Skill,
11
14
  } from "@earendil-works/pi-coding-agent"
12
15
  import type {
@@ -208,6 +211,40 @@ async function loadSessionSkills(ctx: ExtensionContext): Promise<SkillMap> {
208
211
  )
209
212
  }
210
213
 
214
+ /** Rebuild the typed prompt from a stored skill block, keeping the command readable. */
215
+ function sessionNameFromBlock(block: ParsedSkillBlock): string {
216
+ const rest = block.userMessage?.trim()
217
+ // A body containing `</skill>` makes Pi's non-greedy envelope split early; the tail is not prose.
218
+ if (!rest || rest.includes("<skill ") || rest.includes("</skill>")) {
219
+ return `/skill:${block.name}`
220
+ }
221
+ // Same trailing rule as the expansion pattern: a dotted longer name is a different command.
222
+ const command = new RegExp(
223
+ `(^|${MID_SKILL_BOUNDARY})/skill:${escapeRegExp(block.name)}(?!\\.?[A-Za-z0-9_-])`,
224
+ )
225
+ return command.test(rest) ? rest : `/skill:${block.name} ${rest}`
226
+ }
227
+
228
+ function messageText(message: { content: unknown }): string {
229
+ const content = message.content
230
+ if (typeof content === "string") return content
231
+ if (!Array.isArray(content)) return ""
232
+ return content
233
+ .filter((part) => part?.type === "text")
234
+ .map((part) => part.text as string)
235
+ .join(" ")
236
+ }
237
+
238
+ /** First user message with non-blank text, so a text-less message never decides a name. */
239
+ function firstUserMessageText(ctx: ExtensionContext): string | undefined {
240
+ for (const entry of ctx.sessionManager.getEntries()) {
241
+ if (entry.type !== "message" || entry.message.role !== "user") continue
242
+ const text = messageText(entry.message)
243
+ if (text.trim()) return text
244
+ }
245
+ return undefined
246
+ }
247
+
211
248
  export default function piInlineSkillCommands(pi: ExtensionAPI): void {
212
249
  let skillsPromise: Promise<SkillMap> | undefined
213
250
  installMidSkillTrigger()
@@ -234,6 +271,49 @@ export default function piInlineSkillCommands(pi: ExtensionAPI): void {
234
271
  pi.on("input", async (event, ctx) => {
235
272
  if (!MID_SKILL_COMMAND.test(event.text)) return
236
273
  const text = expandMidSkillCommand(event.text, await getSkills(ctx))
274
+ const nativeStart = event.text.trimStart().startsWith("/skill:")
275
+ if (text === undefined && !nativeStart) return
276
+ try {
277
+ nameFirstSkillPrompt(pi, event.source, event.text, ctx)
278
+ } catch {
279
+ // A session name is cosmetic; never let it abort the expansion below.
280
+ }
237
281
  return text === undefined ? undefined : { action: "transform", text }
238
282
  })
283
+
284
+ pi.registerCommand("resume-session-name", {
285
+ description:
286
+ "Name this session from its first prompt instead of the expanded skill block",
287
+ handler: async (_args, ctx) => {
288
+ const first = firstUserMessageText(ctx)
289
+ if (first === undefined) {
290
+ ctx.ui.notify("This session has no user message with text yet", "info")
291
+ return
292
+ }
293
+ const block = parseSkillBlock(first)
294
+ if (!block) {
295
+ ctx.ui.notify("The first message has no expanded skill block", "info")
296
+ return
297
+ }
298
+ const name = sessionNameFromBlock(block)
299
+ pi.setSessionName(name)
300
+ ctx.ui.notify(`Session name set: ${pi.getSessionName() ?? name}`, "info")
301
+ },
302
+ })
303
+ }
304
+
305
+ /** A fresh session keeps the typed prompt as its name instead of the expanded block. */
306
+ function nameFirstSkillPrompt(
307
+ pi: ExtensionAPI,
308
+ source: InputSource,
309
+ text: string,
310
+ ctx: ExtensionContext,
311
+ ): void {
312
+ // Extension-authored prompts are not the user's first prompt.
313
+ if (source === "extension") return
314
+ if (ctx.sessionManager.getSessionName()) return
315
+ // A text-less first message leaves `/resume` showing the block, so it must not block naming.
316
+ if (firstUserMessageText(ctx) !== undefined) return
317
+ const name = text.trim()
318
+ if (name) pi.setSessionName(name)
239
319
  }
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.26.1-local.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [#402](https://github.com/HerbertGao/pi-extensions/pull/402) [`f0109df`](https://github.com/HerbertGao/pi-extensions/commit/f0109dfd7bb213fe26260a0c882e45d2bf83935d) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Color the ccstyle Agent tool rows with each type's configured badge. pi-subagents exposes the label and color of every spawnable type over a new `subagents:rpc:list-agents` bus channel and announces registry changes with a `subagents:agents-changed` event; pi-cc-extensions pulls the table on `subagents:ready` and renders Agent rows as padded background badges (same palette, hex, 256-color quantization, and contrast rules as pi-subagents' own badges). Without pi-subagents on the bus the rows stay plain text.
8
+
3
9
  ## 0.26.1-local.2
4
10
 
5
11
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  # Driving subagents from another extension
2
2
 
3
- Another pi extension can spawn a subagent, listen for subagent completion, read the result, steer and stop the run — all over the `pi.events` bus, without importing this package directly. Seven request/reply channels (`subagents:rpc:ping`, `subagents:rpc:spawn`, `subagents:rpc:stop`, `subagents:rpc:consume`, `subagents:rpc:steer`, `subagents:rpc:register-agents`, `subagents:rpc:unregister-agents`), the lifecycle events in README's [event table](../README.md#events), one per-message usage event (`subagents:usage`), one terminal `subagents:disposed`, and one in-process registry at `Symbol.for("pi-subagents:manager")`.
3
+ Another pi extension can spawn a subagent, listen for subagent completion, read the result, steer and stop the run — all over the `pi.events` bus, without importing this package directly. Eight request/reply channels (`subagents:rpc:ping`, `subagents:rpc:spawn`, `subagents:rpc:stop`, `subagents:rpc:consume`, `subagents:rpc:steer`, `subagents:rpc:register-agents`, `subagents:rpc:unregister-agents`, `subagents:rpc:list-agents`), the `subagents:agents-changed` registry event, the lifecycle events in README's [event table](../README.md#events), one per-message usage event (`subagents:usage`), one terminal `subagents:disposed`, and one in-process registry at `Symbol.for("pi-subagents:manager")`.
4
4
 
5
5
  The thing worth understanding up front is that **the bus is in-process.** Every "RPC" call here is a synchronous `pi.events.emit` into the same event loop, and every reply comes back the same way. That single fact explains most of what follows: why `signal` and the `on*` callbacks work on a spawn payload at all, why a `consume` fired inside a `subagents:completed` handler lands _before_ the notification decision has been made, and why none of this survives a real process boundary.
6
6
 
@@ -144,6 +144,12 @@ It takes an id only, enforces the same top-level ownership guard as stop, and an
144
144
 
145
145
  Like `consume` and `steer`, both channels are outside the `ping` version handshake: an older build has no handler and never replies, so give the call a timeout and treat expiry as "not available here". The intended caller is `@herbertgao/pi-agency`, which seats an Agency Agents catalog persona this way — the persona body as system prompt, the card name as the agent's label, the card color as its badge.
146
146
 
147
+ ## Listing agents for badge rendering
148
+
149
+ `subagents:rpc:list-agents` `{ requestId }` answers with every enabled type and the label and color its config would render: `{ agents: [{ name, displayName?, color? }] }`. The handler reloads agent files first (the caller wires `refreshAgents`), so the list matches what a spawn right now could use. `@herbertgao/pi-cc-extensions` pulls it once per session — on `subagents:ready` — and draws transcript badges from the answer.
150
+
151
+ Registry mutations announce themselves as `subagents:agents-changed` `{}` on the same bus: emitted by register/unregister (only when something actually changed) and by the file reload whenever the spawnable set actually changed. The comparison covers name, display name and color, so a color-only edit to a file-backed agent is announced too, on the next spawn's reload. A badge holder re-pulls list-agents on it, so a mid-session ephemeral registration gets its color without a new session. Like the register channels, both are outside the `ping` version handshake.
152
+
147
153
  ## The manager registry
148
154
 
149
155
  `globalThis[Symbol.for("pi-subagents:manager")]` (`MANAGER_KEY` and `registryEntry`, `src/index.ts`) is a second integration surface — the standard Node cross-package singleton pattern, no bus involved:
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-subagents",
3
- "version": "0.26.1-local.2",
3
+ "version": "0.26.1-local.3",
4
4
  "description": "Claude Code-style autonomous subagents and workflow orchestration for Pi, with HerbertGao-maintained UI extensions.",
5
5
  "keywords": [
6
6
  "agent",
@@ -160,14 +160,19 @@ export function registerEphemeralAgents(
160
160
  return [...entries.keys()].filter((name) => applied.includes(name))
161
161
  }
162
162
 
163
- /** Remove ephemeral types by name (case-insensitive); file-backed types stay. */
164
- export function unregisterEphemeralAgents(names: readonly string[]): void {
163
+ /** Remove ephemeral types by name (case-insensitive); file-backed types stay.
164
+ * Returns how many were actually removed, so callers can emit change events
165
+ * only for real mutations. */
166
+ export function unregisterEphemeralAgents(names: readonly string[]): number {
167
+ let removed = 0
165
168
  for (const name of names) {
166
169
  const key = resolveKeyIn(ephemeralAgents, name)
167
170
  if (!key) continue
168
171
  ephemeralAgents.delete(key)
169
172
  if (ephemeralOwned.delete(key)) agents.delete(key)
173
+ removed++
170
174
  }
175
+ return removed
171
176
  }
172
177
 
173
178
  /** Drop every ephemeral type; file-backed types stay. Called on session_start. */
@@ -15,6 +15,8 @@
15
15
 
16
16
  import { isTopLevelAgent } from "./agent-manager.js"
17
17
  import {
18
+ getAvailableTypes,
19
+ getConfig,
18
20
  registerEphemeralAgents,
19
21
  unregisterEphemeralAgents,
20
22
  } from "./agent-types.js"
@@ -74,6 +76,9 @@ export interface RpcDeps {
74
76
  pi: unknown // passed through to manager.spawn
75
77
  getCtx: () => unknown | undefined // returns current ExtensionContext
76
78
  manager: SpawnCapable
79
+ /** Reload agent files before list-agents answers, so the list matches what
80
+ * a spawn right now could use. index.ts wires this to reloadCustomAgents. */
81
+ refreshAgents?: () => void
77
82
  }
78
83
 
79
84
  export interface RpcHandle {
@@ -84,6 +89,7 @@ export interface RpcHandle {
84
89
  unsubSteer: () => void
85
90
  unsubRegisterAgents: () => void
86
91
  unsubUnregisterAgents: () => void
92
+ unsubListAgents: () => void
87
93
  }
88
94
 
89
95
  /**
@@ -332,6 +338,9 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
332
338
  ? ` (applied: ${applied.map((name) => `"${name}"`).join(", ")})`
333
339
  : ""),
334
340
  )
341
+ // Badge holders (pi-cc-extensions) re-pull list-agents on this event, so a
342
+ // freshly seated persona gets its colored badge without a new session.
343
+ events.emit("subagents:agents-changed", {})
335
344
  return { agents: applied }
336
345
  })
337
346
 
@@ -341,9 +350,34 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
341
350
  }>(events, "subagents:rpc:unregister-agents", ({ names }) => {
342
351
  if (!Array.isArray(names) || names.some((n) => typeof n !== "string"))
343
352
  throw new Error("unregister-agents requires an array of type names")
344
- unregisterEphemeralAgents(names)
353
+ // Emit only for a real removal — once per actual registry change.
354
+ if (unregisterEphemeralAgents(names) > 0)
355
+ events.emit("subagents:agents-changed", {})
345
356
  })
346
357
 
358
+ // The badge holder's snapshot: every enabled type with the label and color
359
+ // its config would render. pi-cc-extensions pulls this once per session (on
360
+ // subagents:ready) and again on subagents:agents-changed, then draws
361
+ // transcript badges from it. Additive like the other channels: outside the
362
+ // ping handshake, a missing handler just never replies.
363
+ const unsubListAgents = handleRpc<{ requestId: string }>(
364
+ events,
365
+ "subagents:rpc:list-agents",
366
+ () => {
367
+ deps.refreshAgents?.()
368
+ return {
369
+ agents: getAvailableTypes().map((type) => {
370
+ const config = getConfig(type)
371
+ return {
372
+ name: type,
373
+ displayName: config.displayName,
374
+ ...(config.color ? { color: config.color } : {}),
375
+ }
376
+ }),
377
+ }
378
+ },
379
+ )
380
+
347
381
  return {
348
382
  unsubPing,
349
383
  unsubSpawn,
@@ -352,5 +386,6 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
352
386
  unsubSteer,
353
387
  unsubRegisterAgents,
354
388
  unsubUnregisterAgents,
389
+ unsubListAgents,
355
390
  }
356
391
  }
@@ -617,9 +617,31 @@ export default function (pi: ExtensionAPI) {
617
617
  seedProjectTrust(process.cwd())
618
618
 
619
619
  /** Reload agents from package/global/project agent dirs and merge with defaults (called on init and each Agent invocation). */
620
+ /** Current session context; undefined outside a session (also gates the
621
+ * agents-changed emit above to active sessions). */
622
+ let currentCtx: ExtensionContext | undefined
623
+
620
624
  const reloadCustomAgents = (strict = false) => {
625
+ // The before/after comparison feeds subagents:agents-changed, so badge
626
+ // holders re-pull exactly when the spawnable set actually changed. Gated
627
+ // on an active session: the factory-time first load always "changes" the
628
+ // set (defaults → defaults+files) and would fire a pull nobody can answer
629
+ // yet; session_start's own reload runs after currentCtx is set and still
630
+ // announces anything that changed since.
631
+ // Signature covers name, displayName and color: a color-only edit to a
632
+ // file-backed agent is a real change for badge holders, not just a rename.
633
+ const signature = () =>
634
+ getAvailableTypes()
635
+ .map((type) => {
636
+ const config = getConfig(type)
637
+ return `${type}|${config.displayName}|${config.color ?? ""}`
638
+ })
639
+ .join(",")
640
+ const before = signature()
621
641
  const userAgents = loadCustomAgents(process.cwd(), strict)
622
642
  registerAgents(userAgents)
643
+ if (currentCtx !== undefined && signature() !== before)
644
+ pi.events.emit("subagents:agents-changed", {})
623
645
  }
624
646
 
625
647
  // Initial load — the only strict one. A bad edit mid-session must not kill the
@@ -1103,7 +1125,6 @@ export default function (pi: ExtensionAPI) {
1103
1125
  }
1104
1126
 
1105
1127
  // --- Cross-extension RPC via pi.events ---
1106
- let currentCtx: ExtensionContext | undefined
1107
1128
  // RPC handlers + the `subagents:ready` broadcast are wired on `session_start`
1108
1129
  // (a bound lifecycle event), not at factory time. pi runs every extension
1109
1130
  // factory before the `extensions:` filter and only fires lifecycle events for
@@ -1169,6 +1190,7 @@ export default function (pi: ExtensionAPI) {
1169
1190
  rpcHandle = registerRpcHandlers({
1170
1191
  events: pi.events,
1171
1192
  pi,
1193
+ refreshAgents: () => reloadCustomAgents(),
1172
1194
  getCtx: () => currentCtx,
1173
1195
  manager: {
1174
1196
  spawn: spawnTopLevel,
@@ -1508,6 +1530,7 @@ export default function (pi: ExtensionAPI) {
1508
1530
  rpcHandle?.unsubSteer()
1509
1531
  rpcHandle?.unsubRegisterAgents()
1510
1532
  rpcHandle?.unsubUnregisterAgents()
1533
+ rpcHandle?.unsubListAgents()
1511
1534
  rpcHandle = undefined
1512
1535
  currentCtx = undefined
1513
1536
  // Only release the global slot if this activation claimed it — a child
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-extensions",
3
- "version": "2026.11.17",
3
+ "version": "2026.11.18",
4
4
  "description": "Aggregate installer for HerbertGao-maintained Pi extensions.",
5
5
  "keywords": [
6
6
  "extensions",
@@ -41,10 +41,10 @@
41
41
  "@dietrichgebert/ponytail": "5.3.3",
42
42
  "@herbertgao/pi-agency": "0.1.4",
43
43
  "@herbertgao/pi-bark": "0.2.2",
44
- "@herbertgao/pi-cc-extensions": "1.0.21-local.2",
44
+ "@herbertgao/pi-cc-extensions": "1.0.21-local.3",
45
45
  "@herbertgao/pi-impeccable": "0.6.0",
46
- "@herbertgao/pi-inline-skill-commands": "0.1.1",
47
- "@herbertgao/pi-subagents": "0.26.1-local.2",
46
+ "@herbertgao/pi-inline-skill-commands": "0.2.0",
47
+ "@herbertgao/pi-subagents": "0.26.1-local.3",
48
48
  "@herbertgao/sol-pi": "0.4.3",
49
49
  "@juicesharp/rpiv-ask-user-question": "2.15.0",
50
50
  "@juicesharp/rpiv-config": "^2.15.0",