@herbertgao/pi-extensions 2026.11.16 → 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.
Files changed (23) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/node_modules/@herbertgao/pi-agency/CHANGELOG.md +6 -0
  3. package/node_modules/@herbertgao/pi-agency/README.md +3 -1
  4. package/node_modules/@herbertgao/pi-agency/package.json +1 -1
  5. package/node_modules/@herbertgao/pi-agency/src/index.ts +151 -9
  6. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -0
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/index.ts +7 -0
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/agent-badge.ts +244 -0
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/ccstyle-tool.ts +1 -1
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +10 -3
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +25 -2
  12. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  13. package/node_modules/@herbertgao/pi-inline-skill-commands/README.md +18 -0
  14. package/node_modules/@herbertgao/pi-inline-skill-commands/package.json +1 -1
  15. package/node_modules/@herbertgao/pi-inline-skill-commands/src/index.ts +80 -0
  16. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
  17. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +13 -1
  18. package/node_modules/@herbertgao/pi-subagents/package.json +1 -1
  19. package/node_modules/@herbertgao/pi-subagents/src/agent-color.ts +6 -2
  20. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +87 -1
  21. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +142 -2
  22. package/node_modules/@herbertgao/pi-subagents/src/index.ts +33 -3
  23. package/package.json +8 -8
@@ -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 接在标题后。 */
@@ -269,14 +272,22 @@ export function toolCallSummary(
269
272
  return { main: title, detail: "", payload: clip(args.agent_id) };
270
273
  }
271
274
  if (name === "agent" || name === "agents") {
272
- const displayName = args.subagent_type ?? args.agent_type ?? args.agent;
275
+ // general-purpose 是无身份的默认类型,命名运行的 name 优先;其余类型(Code Reviewer 等)
276
+ // 自身就是身份,类型名优先于 name。`·` 分隔后描述作灰色载荷:单卡与组内行同一写法。
277
+ const type = args.subagent_type ?? args.agent_type ?? args.agent;
278
+ const displayName =
279
+ typeof type === "string" && type.toLowerCase() !== "general-purpose"
280
+ ? type
281
+ : (args.name ?? type);
273
282
  const description =
274
283
  typeof args.description === "string" ? oneLine(args.description, clipLimit()) : "";
275
284
  if (typeof displayName === "string" && displayName) {
276
- // 类型进标题,`·` 分隔后描述作灰色载荷:单卡与组内行同一写法。
277
285
  return {
278
286
  main: `${title} ${displayName}`,
279
287
  detail: "",
288
+ // 徽章按「派发类型」查表,绝不按运行名:general-purpose 运行即使起名
289
+ // Code Reviewer,也不能捡到同名注册类型的颜色。
290
+ agentType: typeof type === "string" ? type : undefined,
280
291
  payload: description ? `\u00b7 ${description}` : undefined,
281
292
  };
282
293
  }
@@ -420,6 +431,7 @@ export function renderToolSummary(
420
431
  summary: ToolCallSummary,
421
432
  width: number,
422
433
  fg: (color: ThemeColor, text: string) => string,
434
+ theme?: BadgeTheme,
423
435
  ): string {
424
436
  // 路径摘要:前缀用标题色,值用次级色并按可用宽度中间截断(文件名优先保留)。
425
437
  if (summary.path) {
@@ -428,6 +440,17 @@ export function renderToolSummary(
428
440
  if (pathWidth < MIN_PAYLOAD_WIDTH) return fg("toolTitle", prefix);
429
441
  return `${fg("toolTitle", prefix)} ${fg("muted", truncatePathToWidth(summary.path.value, Math.min(pathWidth, clipLimit())))}`;
430
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
+ }
431
454
  const title = fitToolCallSummary(summary, width);
432
455
  if (!summary.payload) return fg("toolTitle", title);
433
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.1",
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,17 @@
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
+
9
+ ## 0.26.1-local.2
10
+
11
+ ### Patch Changes
12
+
13
+ - [#397](https://github.com/HerbertGao/pi-extensions/pull/397) [`42647d1`](https://github.com/HerbertGao/pi-extensions/commit/42647d16b171f766da6135fc937bd087e005a161) Thanks [@HerbertGao](https://github.com/HerbertGao)! - Label an `Agent` run by identity: a registered type (Code Reviewer) keeps its type name while a named generic run shows its own `name`, in both the ccstyle transcript row and the pi-subagents badges. The `name` parameter accepts any characters — labels show it as given, `@handles` are slugged. `agency_register` seats catalog personas as session-scoped agent types over the new `subagents:rpc:register-agents` bus channels: the persona body becomes the system prompt, the card name and color become the label and badge, and the types vanish at the next session start without ever shadowing file-loaded agents.
14
+
3
15
  ## 0.26.1-local.1
4
16
 
5
17
  ### 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. Five request/reply channels (`subagents:rpc:ping`, `subagents:rpc:spawn`, `subagents:rpc:stop`, `subagents:rpc:consume`, `subagents:rpc:steer`), 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
 
@@ -138,6 +138,18 @@ One related thing that lives nowhere else: on every top-level settle, pi-subagen
138
138
 
139
139
  It takes an id only, enforces the same top-level ownership guard as stop, and answers `Agent is not running` for a record that has settled. A message queued before the agent's session exists is flushed when the session is created, exactly as the tool's steer is. A successful steer emits `subagents:steered` `{ id, message }`, as every steer path does. Like `consume`, it is outside the `ping` version handshake: an older build has no handler and the request times out on your side, so give it a timeout and treat expiry as "not available here".
140
140
 
141
+ ## Registering session-scoped agent types
142
+
143
+ `subagents:rpc:register-agents` `{ requestId, agents: [{ name, description, systemPrompt, color? }], tools?: "none" | "builtin" }` registers ephemeral agent types — spawnable immediately as `subagent_type`, surviving every agent-file reload, and cleared on the next `session_start`. The payload is deliberately narrow: the system prompt is applied in replace mode, extension and skill access is refused, and the only tool choice is none or the built-ins. A file-loaded agent with the same name (case-insensitively) wins — the overlay never shadows the user's own agents. `subagents:rpc:unregister-agents` `{ requestId, names }` removes types by name; file-backed types are untouched.
144
+
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
+
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
+
141
153
  ## The manager registry
142
154
 
143
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.1",
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",
@@ -192,15 +192,19 @@ export function renderAgentName(
192
192
  type: string | undefined,
193
193
  theme: AgentNameTheme,
194
194
  style: AgentNameStyle = {},
195
- /** A run's own name, which outranks its type's label while keeping the type's color. */
195
+ /** A run's own name. It outranks only the generic default type; a real type
196
+ * (Code Reviewer) is itself the identity and keeps its own label. */
196
197
  label?: string,
197
198
  ): string {
198
199
  if (!type) {
199
200
  return renderAgentNameLabel(label ?? "Agent", undefined, theme, style)
200
201
  }
201
202
  const config = getConfig(type)
203
+ // general-purpose is the identity-less default: a run's name is the better
204
+ // label there. Any other type is itself the identity and wins over the name.
205
+ const generic = type.toLowerCase() === "general-purpose"
202
206
  return renderAgentNameLabel(
203
- label ?? config.displayName,
207
+ generic ? (label ?? config.displayName) : config.displayName,
204
208
  config.color,
205
209
  theme,
206
210
  style,
@@ -86,14 +86,100 @@ export function buildAgentRegistry(
86
86
 
87
87
  /**
88
88
  * Register agents into the unified registry.
89
- * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name).
89
+ * Starts with DEFAULT_AGENTS, then overlays user agents (overrides defaults with same name),
90
+ * then the ephemeral overlay (see `registerEphemeralAgents`).
90
91
  * Disabled agents (enabled === false) are kept in the registry but excluded from spawning.
91
92
  */
92
93
  export function registerAgents(userAgents: Map<string, AgentConfig>): void {
93
94
  agents.clear()
95
+ // The rebuilt registry is file/default-backed throughout, so no key in it
96
+ // is ours any more — drop ownership before the overlay re-applies.
97
+ ephemeralOwned.clear()
94
98
  for (const [name, config] of buildAgentRegistry(userAgents)) {
95
99
  agents.set(name, config)
96
100
  }
101
+ overlayEphemeral(agents)
102
+ }
103
+
104
+ /**
105
+ * Ephemeral agents: registered at runtime by another extension over the RPC
106
+ * bus (pi-agency seating a catalog persona), overlaid after every file load so
107
+ * they survive `reloadCustomAgents()` — which runs before every spawn and
108
+ * would otherwise wipe them. A file-loaded agent with the same name wins: user
109
+ * files are the authority and an ephemeral overlay never shadows them. The
110
+ * overlay is cleared on each session_start, so a type lives for the current
111
+ * session only.
112
+ */
113
+ const ephemeralAgents = new Map<string, AgentConfig>()
114
+ /** Registry keys currently served by the ephemeral overlay (not file-backed). */
115
+ const ephemeralOwned = new Set<string>()
116
+
117
+ /** Overlay the ephemeral types onto a registry; returns the names applied. */
118
+ function overlayEphemeral(registry: Map<string, AgentConfig>): string[] {
119
+ const applied: string[] = []
120
+ for (const [name, config] of ephemeralAgents) {
121
+ const key = resolveKeyIn(registry, name)
122
+ // A key we do not own is file- or default-backed: the user's type wins
123
+ // and this registration is skipped — never a silent shadow. A key we own
124
+ // is our own previous entry, replaced in place. Both checks are
125
+ // case-insensitive, like spawn resolution.
126
+ if (key !== undefined && !ephemeralOwned.has(key)) continue
127
+ if (key !== undefined && key !== name) {
128
+ registry.delete(key)
129
+ ephemeralOwned.delete(key)
130
+ }
131
+ registry.set(name, config)
132
+ ephemeralOwned.add(name)
133
+ applied.push(name)
134
+ }
135
+ return applied
136
+ }
137
+
138
+ /** Register session-scoped agent types at runtime; spawnable immediately.
139
+ * Returns the names actually applied, so a caller can fail loudly when a name
140
+ * collides with a file-loaded or default type instead of shadowing it. */
141
+ export function registerEphemeralAgents(
142
+ entries: Map<string, AgentConfig>,
143
+ ): string[] {
144
+ for (const [name, config] of entries) {
145
+ // A case-variant of an existing ephemeral key replaces it in place, so
146
+ // one persona cannot leave a second, unreachable entry behind.
147
+ const existing = resolveKeyIn(ephemeralAgents, name)
148
+ if (existing !== undefined && existing !== name)
149
+ ephemeralAgents.delete(existing)
150
+ ephemeralAgents.set(name, config)
151
+ }
152
+ const applied = overlayEphemeral(agents)
153
+ // A skipped name collided with a file/default type: drop it from the store
154
+ // as well, so it cannot silently apply later if that type disappears.
155
+ for (const name of entries.keys()) {
156
+ if (!applied.includes(name)) ephemeralAgents.delete(name)
157
+ }
158
+ // Report only this call's names: the overlay re-applies the whole store, so
159
+ // returning `applied` would list types the caller never sent.
160
+ return [...entries.keys()].filter((name) => applied.includes(name))
161
+ }
162
+
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
168
+ for (const name of names) {
169
+ const key = resolveKeyIn(ephemeralAgents, name)
170
+ if (!key) continue
171
+ ephemeralAgents.delete(key)
172
+ if (ephemeralOwned.delete(key)) agents.delete(key)
173
+ removed++
174
+ }
175
+ return removed
176
+ }
177
+
178
+ /** Drop every ephemeral type; file-backed types stay. Called on session_start. */
179
+ export function clearEphemeralAgents(): void {
180
+ for (const key of ephemeralOwned) agents.delete(key)
181
+ ephemeralOwned.clear()
182
+ ephemeralAgents.clear()
97
183
  }
98
184
 
99
185
  /** Case-insensitive key resolution within a registry. */
@@ -14,9 +14,15 @@
14
14
  */
15
15
 
16
16
  import { isTopLevelAgent } from "./agent-manager.js"
17
+ import {
18
+ getAvailableTypes,
19
+ getConfig,
20
+ registerEphemeralAgents,
21
+ unregisterEphemeralAgents,
22
+ } from "./agent-types.js"
17
23
  import { type ModelRegistry, resolveModel } from "./model-resolver.js"
18
24
  import { checkModelScope } from "./model-scope.js"
19
- import type { AgentRecord } from "./types.js"
25
+ import type { AgentConfig, AgentRecord } from "./types.js"
20
26
 
21
27
  /** Minimal event bus interface needed by the RPC handlers. */
22
28
  export interface EventBus {
@@ -70,6 +76,9 @@ export interface RpcDeps {
70
76
  pi: unknown // passed through to manager.spawn
71
77
  getCtx: () => unknown | undefined // returns current ExtensionContext
72
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
73
82
  }
74
83
 
75
84
  export interface RpcHandle {
@@ -78,6 +87,9 @@ export interface RpcHandle {
78
87
  unsubStop: () => void
79
88
  unsubConsume: () => void
80
89
  unsubSteer: () => void
90
+ unsubRegisterAgents: () => void
91
+ unsubUnregisterAgents: () => void
92
+ unsubListAgents: () => void
81
93
  }
82
94
 
83
95
  /**
@@ -105,6 +117,45 @@ function handleRpc<P extends { requestId: string }>(
105
117
  })
106
118
  }
107
119
 
120
+ /** Validate one register-agents payload entry into an AgentConfig. Narrow on
121
+ * purpose: no tool allowlist beyond none/builtin, no extension or skill access,
122
+ * replace-mode system prompt — a persona is role text, not an executable agent
123
+ * definition. */
124
+ export function ephemeralAgentConfig(
125
+ candidate: unknown,
126
+ index: number,
127
+ ): [string, AgentConfig] {
128
+ if (typeof candidate !== "object" || candidate === null)
129
+ throw new Error(`agents[${index}] must be an object`)
130
+ const { name, description, systemPrompt, color } = candidate as Record<
131
+ string,
132
+ unknown
133
+ >
134
+ if (typeof name !== "string" || !name.trim() || name.length > 64)
135
+ throw new Error(`agents[${index}].name must be 1-64 characters`)
136
+ if (typeof description !== "string" || !description.trim())
137
+ throw new Error(`agents[${index}].description must be a non-empty string`)
138
+ if (typeof systemPrompt !== "string" || !systemPrompt.trim())
139
+ throw new Error(`agents[${index}].systemPrompt must be a non-empty string`)
140
+ if (color !== undefined && (typeof color !== "string" || !color))
141
+ throw new Error(
142
+ `agents[${index}].color must be a non-empty string when given`,
143
+ )
144
+ const trimmed = name.trim()
145
+ return [
146
+ trimmed,
147
+ {
148
+ name: trimmed,
149
+ description,
150
+ systemPrompt,
151
+ color: typeof color === "string" ? color : undefined,
152
+ promptMode: "replace",
153
+ extensions: false,
154
+ skills: false,
155
+ },
156
+ ]
157
+ }
158
+
108
159
  /**
109
160
  * Register ping, spawn, stop, consume, and steer RPC handlers on the event bus.
110
161
  * Returns unsub functions for cleanup.
@@ -247,5 +298,94 @@ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
247
298
  throw new Error("Agent is not running")
248
299
  })
249
300
 
250
- return { unsubPing, unsubSpawn, unsubStop, unsubConsume, unsubSteer }
301
+ // Register session-scoped agent types from another extension (pi-agency
302
+ // seating a catalog persona). Additive like consume/steer: outside the ping
303
+ // version handshake — an older pi-subagents simply never replies and the
304
+ // caller's timeout is the discovery signal.
305
+ const unsubRegisterAgents = handleRpc<{
306
+ requestId: string
307
+ agents: unknown[]
308
+ tools?: unknown
309
+ }>(events, "subagents:rpc:register-agents", ({ agents, tools }) => {
310
+ if (!Array.isArray(agents) || agents.length === 0)
311
+ throw new Error("register-agents requires a non-empty agents array")
312
+ if (tools !== undefined && tools !== "none" && tools !== "builtin")
313
+ throw new Error('tools must be "none" or "builtin"')
314
+ const builtinToolNames = tools === "none" ? [] : undefined
315
+ const entries = new Map<string, AgentConfig>()
316
+ const seen = new Map<string, number>()
317
+ agents.forEach((candidate, index) => {
318
+ const [name, config] = ephemeralAgentConfig(candidate, index)
319
+ const lower = name.toLowerCase()
320
+ const firstIndex = seen.get(lower)
321
+ if (firstIndex !== undefined)
322
+ throw new Error(
323
+ `agents[${index}].name "${name}" duplicates agents[${firstIndex}]`,
324
+ )
325
+ seen.set(lower, index)
326
+ entries.set(name, { ...config, builtinToolNames })
327
+ })
328
+ const applied = registerEphemeralAgents(entries)
329
+ // A skipped name collides with a file-loaded or default type: fail loudly
330
+ // rather than let the caller spawn that type believing it is the persona.
331
+ const skipped = [...entries.keys()].filter(
332
+ (name) => !applied.includes(name),
333
+ )
334
+ if (skipped.length > 0)
335
+ throw new Error(
336
+ `agent type already exists: ${skipped.map((name) => `"${name}"`).join(", ")}` +
337
+ (applied.length > 0
338
+ ? ` (applied: ${applied.map((name) => `"${name}"`).join(", ")})`
339
+ : ""),
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", {})
344
+ return { agents: applied }
345
+ })
346
+
347
+ const unsubUnregisterAgents = handleRpc<{
348
+ requestId: string
349
+ names: unknown
350
+ }>(events, "subagents:rpc:unregister-agents", ({ names }) => {
351
+ if (!Array.isArray(names) || names.some((n) => typeof n !== "string"))
352
+ throw new Error("unregister-agents requires an array of type names")
353
+ // Emit only for a real removal — once per actual registry change.
354
+ if (unregisterEphemeralAgents(names) > 0)
355
+ events.emit("subagents:agents-changed", {})
356
+ })
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
+
381
+ return {
382
+ unsubPing,
383
+ unsubSpawn,
384
+ unsubStop,
385
+ unsubConsume,
386
+ unsubSteer,
387
+ unsubRegisterAgents,
388
+ unsubUnregisterAgents,
389
+ unsubListAgents,
390
+ }
251
391
  }