@esso0428/pi-subagents 0.17.6 → 0.17.8

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 (260) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/dist/abortable.d.ts +13 -0
  4. package/dist/abortable.d.ts.map +1 -0
  5. package/dist/abortable.js +43 -0
  6. package/dist/abortable.js.map +1 -0
  7. package/dist/agent-color.d.ts +36 -0
  8. package/dist/agent-color.d.ts.map +1 -0
  9. package/dist/agent-color.js +124 -0
  10. package/dist/agent-color.js.map +1 -0
  11. package/dist/agent-file-toggle.d.ts +126 -0
  12. package/dist/agent-file-toggle.d.ts.map +1 -0
  13. package/dist/agent-file-toggle.js +259 -0
  14. package/dist/agent-file-toggle.js.map +1 -0
  15. package/dist/agent-history.d.ts +4 -0
  16. package/dist/agent-history.d.ts.map +1 -1
  17. package/dist/agent-history.js +47 -1
  18. package/dist/agent-history.js.map +1 -1
  19. package/dist/agent-manager.d.ts +370 -56
  20. package/dist/agent-manager.d.ts.map +1 -1
  21. package/dist/agent-manager.js +1123 -409
  22. package/dist/agent-manager.js.map +1 -1
  23. package/dist/agent-runner.d.ts +100 -10
  24. package/dist/agent-runner.d.ts.map +1 -1
  25. package/dist/agent-runner.js +166 -21
  26. package/dist/agent-runner.js.map +1 -1
  27. package/dist/agent-types.d.ts +57 -5
  28. package/dist/agent-types.d.ts.map +1 -1
  29. package/dist/agent-types.js +164 -32
  30. package/dist/agent-types.js.map +1 -1
  31. package/dist/child-context.d.ts +3 -0
  32. package/dist/child-context.d.ts.map +1 -0
  33. package/dist/child-context.js +13 -0
  34. package/dist/child-context.js.map +1 -0
  35. package/dist/cross-extension-rpc.d.ts +23 -3
  36. package/dist/cross-extension-rpc.d.ts.map +1 -1
  37. package/dist/cross-extension-rpc.js +79 -17
  38. package/dist/cross-extension-rpc.js.map +1 -1
  39. package/dist/custom-agents.d.ts +38 -1
  40. package/dist/custom-agents.d.ts.map +1 -1
  41. package/dist/custom-agents.js +164 -12
  42. package/dist/custom-agents.js.map +1 -1
  43. package/dist/index.d.ts +34 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1912 -492
  46. package/dist/index.js.map +1 -1
  47. package/dist/invocation-config.d.ts +87 -2
  48. package/dist/invocation-config.d.ts.map +1 -1
  49. package/dist/invocation-config.js +71 -3
  50. package/dist/invocation-config.js.map +1 -1
  51. package/dist/mention-clone.d.ts +88 -0
  52. package/dist/mention-clone.d.ts.map +1 -0
  53. package/dist/mention-clone.js +154 -0
  54. package/dist/mention-clone.js.map +1 -0
  55. package/dist/mention.d.ts +82 -0
  56. package/dist/mention.d.ts.map +1 -0
  57. package/dist/mention.js +132 -0
  58. package/dist/mention.js.map +1 -0
  59. package/dist/model-resolver.d.ts +17 -0
  60. package/dist/model-resolver.d.ts.map +1 -1
  61. package/dist/model-resolver.js +15 -0
  62. package/dist/model-resolver.js.map +1 -1
  63. package/dist/model-scope.d.ts +50 -0
  64. package/dist/model-scope.d.ts.map +1 -0
  65. package/dist/model-scope.js +49 -0
  66. package/dist/model-scope.js.map +1 -0
  67. package/dist/nested-tools.d.ts +57 -0
  68. package/dist/nested-tools.d.ts.map +1 -0
  69. package/dist/nested-tools.js +301 -0
  70. package/dist/nested-tools.js.map +1 -0
  71. package/dist/output-file.d.ts +22 -3
  72. package/dist/output-file.d.ts.map +1 -1
  73. package/dist/output-file.js +58 -7
  74. package/dist/output-file.js.map +1 -1
  75. package/dist/prompts.d.ts +23 -0
  76. package/dist/prompts.d.ts.map +1 -1
  77. package/dist/prompts.js +20 -2
  78. package/dist/prompts.js.map +1 -1
  79. package/dist/schedule.d.ts.map +1 -1
  80. package/dist/schedule.js +36 -15
  81. package/dist/schedule.js.map +1 -1
  82. package/dist/settings.d.ts +228 -2
  83. package/dist/settings.d.ts.map +1 -1
  84. package/dist/settings.js +94 -0
  85. package/dist/settings.js.map +1 -1
  86. package/dist/status-note.d.ts +49 -1
  87. package/dist/status-note.d.ts.map +1 -1
  88. package/dist/status-note.js +62 -1
  89. package/dist/status-note.js.map +1 -1
  90. package/dist/structured-output.d.ts +62 -0
  91. package/dist/structured-output.d.ts.map +1 -0
  92. package/dist/structured-output.js +113 -0
  93. package/dist/structured-output.js.map +1 -0
  94. package/dist/types.d.ts +176 -10
  95. package/dist/types.d.ts.map +1 -1
  96. package/dist/ui/agent-mention.d.ts +83 -0
  97. package/dist/ui/agent-mention.d.ts.map +1 -0
  98. package/dist/ui/agent-mention.js +188 -0
  99. package/dist/ui/agent-mention.js.map +1 -0
  100. package/dist/ui/agent-widget.d.ts +97 -75
  101. package/dist/ui/agent-widget.d.ts.map +1 -1
  102. package/dist/ui/agent-widget.js +398 -420
  103. package/dist/ui/agent-widget.js.map +1 -1
  104. package/dist/ui/conversation-blocks.d.ts.map +1 -1
  105. package/dist/ui/conversation-blocks.js +6 -0
  106. package/dist/ui/conversation-blocks.js.map +1 -1
  107. package/dist/ui/conversation-timeline.d.ts +10 -2
  108. package/dist/ui/conversation-timeline.d.ts.map +1 -1
  109. package/dist/ui/conversation-timeline.js +130 -23
  110. package/dist/ui/conversation-timeline.js.map +1 -1
  111. package/dist/ui/conversation-viewer.d.ts +15 -5
  112. package/dist/ui/conversation-viewer.d.ts.map +1 -1
  113. package/dist/ui/conversation-viewer.js +202 -50
  114. package/dist/ui/conversation-viewer.js.map +1 -1
  115. package/dist/ui/fleet-list.d.ts +198 -0
  116. package/dist/ui/fleet-list.d.ts.map +1 -0
  117. package/dist/ui/fleet-list.js +487 -0
  118. package/dist/ui/fleet-list.js.map +1 -0
  119. package/dist/ui/schedule-menu.d.ts.map +1 -1
  120. package/dist/ui/schedule-menu.js +6 -7
  121. package/dist/ui/schedule-menu.js.map +1 -1
  122. package/dist/ui/select-item.d.ts +28 -0
  123. package/dist/ui/select-item.d.ts.map +1 -0
  124. package/dist/ui/select-item.js +35 -0
  125. package/dist/ui/select-item.js.map +1 -0
  126. package/dist/ui/workflow-card.d.ts +176 -0
  127. package/dist/ui/workflow-card.d.ts.map +1 -0
  128. package/dist/ui/workflow-card.js +333 -0
  129. package/dist/ui/workflow-card.js.map +1 -0
  130. package/dist/ui/workflow-dialog.d.ts +306 -0
  131. package/dist/ui/workflow-dialog.d.ts.map +1 -0
  132. package/dist/ui/workflow-dialog.js +844 -0
  133. package/dist/ui/workflow-dialog.js.map +1 -0
  134. package/dist/ui/workflow-menu.d.ts +61 -0
  135. package/dist/ui/workflow-menu.d.ts.map +1 -0
  136. package/dist/ui/workflow-menu.js +148 -0
  137. package/dist/ui/workflow-menu.js.map +1 -0
  138. package/dist/usage.d.ts +86 -1
  139. package/dist/usage.d.ts.map +1 -1
  140. package/dist/usage.js +72 -1
  141. package/dist/usage.js.map +1 -1
  142. package/dist/workflow/collisions.d.ts +96 -0
  143. package/dist/workflow/collisions.d.ts.map +1 -0
  144. package/dist/workflow/collisions.js +89 -0
  145. package/dist/workflow/collisions.js.map +1 -0
  146. package/dist/workflow/entry.d.ts +33 -0
  147. package/dist/workflow/entry.d.ts.map +1 -0
  148. package/dist/workflow/entry.js +30 -0
  149. package/dist/workflow/entry.js.map +1 -0
  150. package/dist/workflow/host.d.ts +63 -0
  151. package/dist/workflow/host.d.ts.map +1 -0
  152. package/dist/workflow/host.js +363 -0
  153. package/dist/workflow/host.js.map +1 -0
  154. package/dist/workflow/journal.d.ts +98 -0
  155. package/dist/workflow/journal.d.ts.map +1 -0
  156. package/dist/workflow/journal.js +121 -0
  157. package/dist/workflow/journal.js.map +1 -0
  158. package/dist/workflow/json-schema.d.ts +52 -0
  159. package/dist/workflow/json-schema.d.ts.map +1 -0
  160. package/dist/workflow/json-schema.js +112 -0
  161. package/dist/workflow/json-schema.js.map +1 -0
  162. package/dist/workflow/meta.d.ts +68 -0
  163. package/dist/workflow/meta.d.ts.map +1 -0
  164. package/dist/workflow/meta.js +318 -0
  165. package/dist/workflow/meta.js.map +1 -0
  166. package/dist/workflow/progress.d.ts +225 -0
  167. package/dist/workflow/progress.d.ts.map +1 -0
  168. package/dist/workflow/progress.js +362 -0
  169. package/dist/workflow/progress.js.map +1 -0
  170. package/dist/workflow/runtime.d.ts +335 -0
  171. package/dist/workflow/runtime.d.ts.map +1 -0
  172. package/dist/workflow/runtime.js +831 -0
  173. package/dist/workflow/runtime.js.map +1 -0
  174. package/dist/workflow/saved.d.ts +91 -0
  175. package/dist/workflow/saved.d.ts.map +1 -0
  176. package/dist/workflow/saved.js +204 -0
  177. package/dist/workflow/saved.js.map +1 -0
  178. package/dist/workflow/task.d.ts +137 -0
  179. package/dist/workflow/task.d.ts.map +1 -0
  180. package/dist/workflow/task.js +208 -0
  181. package/dist/workflow/task.js.map +1 -0
  182. package/dist/workflow/tool-description.d.ts +39 -0
  183. package/dist/workflow/tool-description.d.ts.map +1 -0
  184. package/dist/workflow/tool-description.js +200 -0
  185. package/dist/workflow/tool-description.js.map +1 -0
  186. package/dist/workflow/worker-source.d.ts +48 -0
  187. package/dist/workflow/worker-source.d.ts.map +1 -0
  188. package/dist/workflow/worker-source.js +779 -0
  189. package/dist/workflow/worker-source.js.map +1 -0
  190. package/dist/worktree.d.ts +10 -3
  191. package/dist/worktree.d.ts.map +1 -1
  192. package/dist/worktree.js +58 -54
  193. package/dist/worktree.js.map +1 -1
  194. package/dist/xml.d.ts +11 -0
  195. package/dist/xml.d.ts.map +1 -0
  196. package/dist/xml.js +13 -0
  197. package/dist/xml.js.map +1 -0
  198. package/docs/rpc.md +183 -0
  199. package/docs/superpowers/plans/2026-09-30-upstream-event-workflow-partial-history.md +195 -0
  200. package/docs/superpowers/specs/2026-09-30-upstream-event-workflow-partial-history-design.md +49 -0
  201. package/docs/workflows.md +437 -0
  202. package/examples/agent-tool-description.md +7 -7
  203. package/examples/workflows/compose.js +51 -0
  204. package/examples/workflows/fan-out-audit.js +47 -0
  205. package/examples/workflows/gated-fix.js +60 -0
  206. package/examples/workflows/lib/count-child.js +27 -0
  207. package/examples/workflows/review-panel.js +63 -0
  208. package/examples/workflows/structured-findings.js +78 -0
  209. package/package.json +1 -1
  210. package/src/abortable.ts +43 -0
  211. package/src/agent-color.ts +161 -0
  212. package/src/agent-file-toggle.ts +269 -0
  213. package/src/agent-history.ts +54 -2
  214. package/src/agent-manager.ts +1263 -402
  215. package/src/agent-runner.ts +251 -27
  216. package/src/agent-types.ts +188 -32
  217. package/src/child-context.ts +15 -0
  218. package/src/cross-extension-rpc.ts +96 -20
  219. package/src/custom-agents.ts +170 -13
  220. package/src/index.ts +2029 -536
  221. package/src/invocation-config.ts +118 -3
  222. package/src/mention-clone.ts +196 -0
  223. package/src/mention.ts +141 -0
  224. package/src/model-resolver.ts +18 -0
  225. package/src/model-scope.ts +70 -0
  226. package/src/nested-tools.ts +424 -0
  227. package/src/output-file.ts +61 -6
  228. package/src/prompts.ts +45 -2
  229. package/src/schedule.ts +35 -14
  230. package/src/settings.ts +312 -2
  231. package/src/status-note.ts +66 -1
  232. package/src/structured-output.ts +130 -0
  233. package/src/types.ts +177 -10
  234. package/src/ui/agent-mention.ts +216 -0
  235. package/src/ui/agent-widget.ts +393 -441
  236. package/src/ui/conversation-blocks.ts +6 -0
  237. package/src/ui/conversation-timeline.ts +139 -25
  238. package/src/ui/conversation-viewer.ts +212 -48
  239. package/src/ui/fleet-list.ts +558 -0
  240. package/src/ui/schedule-menu.ts +9 -8
  241. package/src/ui/select-item.ts +45 -0
  242. package/src/ui/workflow-card.ts +470 -0
  243. package/src/ui/workflow-dialog.ts +1115 -0
  244. package/src/ui/workflow-menu.ts +193 -0
  245. package/src/usage.ts +109 -2
  246. package/src/workflow/collisions.ts +123 -0
  247. package/src/workflow/entry.ts +47 -0
  248. package/src/workflow/host.ts +403 -0
  249. package/src/workflow/journal.ts +164 -0
  250. package/src/workflow/json-schema.ts +128 -0
  251. package/src/workflow/meta.ts +325 -0
  252. package/src/workflow/progress.ts +550 -0
  253. package/src/workflow/runtime.ts +1219 -0
  254. package/src/workflow/saved.ts +217 -0
  255. package/src/workflow/task.ts +302 -0
  256. package/src/workflow/tool-description.ts +200 -0
  257. package/src/workflow/worker-source.ts +781 -0
  258. package/src/worktree.ts +69 -55
  259. package/src/xml.ts +13 -0
  260. package/vitest.config.ts +0 -18
@@ -1,5 +1,59 @@
1
+ import { Type } from "@sinclair/typebox";
1
2
  import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
2
3
 
4
+ /**
5
+ * The model-facing `isolation` parameter, shared by the `Agent` tool and the
6
+ * nested delegation tool so the two cannot drift.
7
+ *
8
+ * Shape matters more than wording here. As a single-value optional literal,
9
+ * models that fill every optional parameter — the transcript on #231 shows one
10
+ * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
11
+ * had only `"worktree"` available to fill it with, and kept spawning worktrees
12
+ * across three turns while their own reasoning said to omit the field. Every
13
+ * other optional parameter has an inert filler; this one did not. `"off"` is
14
+ * listed first and described as the default so the harmless value is the
15
+ * obvious one to reach for.
16
+ *
17
+ * The wording tracks Claude Code's own `isolation` parameter, whose phrasing
18
+ * models have the most exposure to: one description on the union rather than
19
+ * per-value ones, opening "Isolation mode.", then a sentence per value in
20
+ * schema order, each with its caveats in a trailing parenthetical. Two clauses
21
+ * are ours, because our shape is not theirs — `"off"` has no counterpart there
22
+ * (their enum is `worktree | remote`, so both of their values do something),
23
+ * and neither does the uncommitted-work warning, which is the specific trap
24
+ * #231 fell into. Deliberately absent is any "only use a worktree when…"
25
+ * restriction: Claude Code's `Agent` tool states the capability and stops, and
26
+ * a second legal value is what lets a model decline one, not being told to.
27
+ */
28
+ const isolationParamShape = {
29
+ isolation: Type.Optional(
30
+ Type.Union([Type.Literal("off"), Type.Literal("worktree")], {
31
+ description:
32
+ 'Isolation mode. Default "off". "off" runs the agent in the current checkout, the same as omitting the field. "worktree" creates a temporary git worktree so the agent works on an isolated copy of the repo (a copy cannot see uncommitted or staged changes in the main checkout).',
33
+ }),
34
+ ),
35
+ };
36
+
37
+ /**
38
+ * Build the `isolation` parameter for a tool schema, or nothing when the
39
+ * project disabled worktrees (`worktreeIsolation: false`).
40
+ *
41
+ * Dropping the field beats accepting it and quietly downgrading. The setting is
42
+ * for a project whose model passes `"worktree"` on *every* call, so a
43
+ * per-result "isolation was disabled" note would be noise on every result and
44
+ * would keep raising the salience of a capability that isn't there. With no
45
+ * field there is nothing to pass, nothing to drop, and nothing to explain — the
46
+ * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
47
+ * cost. The resolver gate and the `agent-manager` check still cover the paths a
48
+ * schema can't reach: agent files, the scheduler, and cross-extension RPC.
49
+ *
50
+ * Like `scheduleParam`, this is read once at tool registration — flipping the
51
+ * setting needs a new pi session for the schema to change.
52
+ */
53
+ export function isolationParam(enabled: boolean): Partial<typeof isolationParamShape> {
54
+ return enabled ? isolationParamShape : {};
55
+ }
56
+
3
57
  interface AgentInvocationParams {
4
58
  model?: string;
5
59
  thinking?: string;
@@ -7,12 +61,42 @@ interface AgentInvocationParams {
7
61
  run_in_background?: boolean;
8
62
  inherit_context?: boolean;
9
63
  isolated?: boolean;
10
- isolation?: IsolationMode;
64
+ /**
65
+ * Untyped on purpose. Both tool schemas now build this field conditionally
66
+ * and spread it, which erases TypeBox's literal inference to `unknown` (the
67
+ * `schedule` param has the same shape). The resolver below narrows by
68
+ * comparison rather than trusting the declaration, which also makes it safe
69
+ * for the cross-extension RPC path, where options arrive unvalidated.
70
+ */
71
+ isolation?: unknown;
72
+ }
73
+
74
+ interface ResolveOptions {
75
+ /**
76
+ * Whether worktree isolation is permitted at all. False when the project set
77
+ * `worktreeIsolation: false`, which drops a requested worktree rather than
78
+ * failing the call: the fail-loud precedent covers spawns that *cannot* work,
79
+ * while this one is the user opting out, and throwing would break exactly the
80
+ * calls the `"off"` value exists to tolerate. Defaults to allowed.
81
+ */
82
+ worktreeAllowed?: boolean;
83
+ /**
84
+ * What an unqualified spawn means — neither the call nor the agent file said.
85
+ *
86
+ * Top-level callers pass the `backgroundByDefault` setting (default `true`,
87
+ * following Claude Code). Nested callers pass `false` unconditionally: a
88
+ * detached child is killed by `abortOwnedChildren` when its parent settles
89
+ * and has no notification path of its own, so backgrounding one loses its
90
+ * work. Both call sites pass it explicitly; the `false` fallback only covers
91
+ * a caller that supplies no options at all, which in-tree means tests.
92
+ */
93
+ defaultRunInBackground?: boolean;
11
94
  }
12
95
 
13
96
  export function resolveAgentInvocationConfig(
14
97
  agentConfig: AgentConfig | undefined,
15
98
  params: AgentInvocationParams,
99
+ opts?: ResolveOptions,
16
100
  ): {
17
101
  modelInput?: string;
18
102
  modelFromParams: boolean;
@@ -22,16 +106,47 @@ export function resolveAgentInvocationConfig(
22
106
  runInBackground: boolean;
23
107
  isolated: boolean;
24
108
  isolation?: IsolationMode;
109
+ /**
110
+ * Caller parameters an agent file's frontmatter outranked, so the surfaces can
111
+ * say "(asked X)" instead of presenting the effective value as the requested
112
+ * one (#182). Populated only where both sides named something and they
113
+ * disagree — a caller who asked for what they got was still honored.
114
+ *
115
+ * `max_turns` is deliberately absent: no surface renders a requested-vs-
116
+ * effective turn limit, so recording one would be dead data.
117
+ */
118
+ overridden?: { thinking?: ThinkingLevel; model?: string };
25
119
  } {
120
+ // Precedence first, collapse second — reversing these loses the veto, since
121
+ // an agent file's "off" only outranks a caller's "worktree" while it is still
122
+ // a value. Everything downstream then sees "worktree" or nothing at all.
123
+ const requested = agentConfig?.isolation ?? params.isolation;
124
+ const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : undefined;
125
+
126
+ const overriddenThinking = agentConfig?.thinking != null && params.thinking != null
127
+ && agentConfig.thinking !== params.thinking
128
+ ? params.thinking as ThinkingLevel
129
+ : undefined;
130
+ const overriddenModel = agentConfig?.model != null && params.model != null
131
+ && agentConfig.model !== params.model
132
+ ? params.model
133
+ : undefined;
134
+
26
135
  return {
27
136
  modelInput: agentConfig?.model ?? params.model,
28
137
  modelFromParams: agentConfig?.model == null && params.model != null,
29
138
  thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
30
139
  maxTurns: agentConfig?.maxTurns ?? params.max_turns,
31
140
  inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
32
- runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? false,
141
+ runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
33
142
  isolated: agentConfig?.isolated ?? params.isolated ?? false,
34
- isolation: agentConfig?.isolation ?? params.isolation,
143
+ isolation,
144
+ // Undefined rather than an empty object when nothing was overridden: callers
145
+ // spread this into the invocation snapshot, and an always-present key would
146
+ // put `requestedThinking: undefined` on every record.
147
+ overridden: overriddenThinking || overriddenModel
148
+ ? { thinking: overriddenThinking, model: overriddenModel }
149
+ : undefined,
35
150
  };
36
151
  }
37
152
 
@@ -0,0 +1,196 @@
1
+ /**
2
+ * mention-clone.ts — start a mentioned agent through a clone of this
3
+ * conversation, without putting anything in the chat.
4
+ *
5
+ * Claude Code routes `@agent-<type>` through the main model: the mention
6
+ * becomes a `<system-reminder>` appended to the prompt and the model makes the
7
+ * tool call (see `agentMentionReminder`). That buys the spawned agent a prompt
8
+ * written with conversation context, and costs a visible turn — the model's
9
+ * reasoning and its tool block land in the transcript, for a decision the user
10
+ * already made when they typed the handle.
11
+ *
12
+ * So the turn happens somewhere else. The conversation is cloned into a
13
+ * throwaway in-memory session — same messages, same system prompt, same model —
14
+ * and that copy takes the turn off-screen. A literal clone: the session's own
15
+ * entries, projected by pi's own `sessionEntryToContextMessages`, not
16
+ * `inherit_context`'s text rendering of them.
17
+ *
18
+ * Cloned from memory rather than from the session file, which cannot be relied
19
+ * on: `SessionManager._persist` withholds every write until the first assistant
20
+ * message lands, so a fork taken before then reads an empty file and throws.
21
+ * `buildSessionContext()` has no such timing, and is compaction-aware — it walks
22
+ * the leaf path and substitutes the summary for entries folded into it, so a
23
+ * long conversation clones as what the main model is actually working from. A
24
+ * conversation with nothing in it yet clones to nothing in it yet, which is the
25
+ * correct answer rather than a failure.
26
+ *
27
+ * It is also the oldest of the equivalent Pi APIs — `buildContextEntries` on
28
+ * ReadonlySessionManager and the `sessionEntryToContextMessages` export both
29
+ * arrived in 0.80.5 — where this one has been exported unchanged from before
30
+ * the declared peer floor, and is the same code path (`byId` is only an index
31
+ * cache, so passing it or not cannot change the result). Keeping the floor
32
+ * honest costs nothing here: see the `compat-floor-pi` job.
33
+ *
34
+ * Its `thinkingLevel` is NOT used, and is the one place the newer API would be
35
+ * better. `getSessionContextSettings` starts at "off" and moves only on an
36
+ * explicit `thinking_level_change` entry, so a session where nobody ran
37
+ * `/think` reports "off" rather than the level it is really using. Omitting the
38
+ * field instead lets `createAgentSession` resolve it from settings, which is
39
+ * that real level.
40
+ *
41
+ * Three details make the spawn belong to the real session rather than the
42
+ * clone:
43
+ *
44
+ * - the clone is handed the *registered* `Agent` tool, whose handler closes
45
+ * over the main activation, so it spawns top-level: widget, fleet row,
46
+ * handle, completion notification, all as if the main model had called it;
47
+ * - that tool is re-bound to the main `ExtensionContext`, because the handler
48
+ * reads `cwd`, `model` and `sessionManager.getSessionId()` off it to place
49
+ * the transcript and the `rootSessionId`. The clone's own context would
50
+ * file both under the throwaway fork;
51
+ * - it is called with no tool-call id. The clone's turn produces one, but the
52
+ * real session never issued it, and a `<tool-use-id>` pointing at nothing
53
+ * is exactly the bug the mention-resume path had to fix;
54
+ * - and it is forced into the background. A foreground agent returns its
55
+ * answer as the tool result and is marked `resultConsumed` so no completion
56
+ * notification is sent — correct when the caller is the real conversation,
57
+ * silent loss when the caller is a fork about to be discarded. Background
58
+ * delivery is the only route from a mention back to the main model.
59
+ *
60
+ * The clone gets one tool and one job. It cannot read, write or run anything —
61
+ * an invisible turn with the full toolset could do invisible work.
62
+ */
63
+
64
+ import type { Model } from "@earendil-works/pi-ai";
65
+ import {
66
+ buildSessionContext,
67
+ createAgentSession,
68
+ type ExtensionContext,
69
+ SessionManager,
70
+ type ToolDefinition,
71
+ } from "@earendil-works/pi-coding-agent";
72
+ import { runInChildSessionContext } from "./child-context.js";
73
+ import { agentMentionReminder } from "./mention.js";
74
+ import type { SubagentType, ThinkingLevel } from "./types.js";
75
+
76
+ export interface MentionCloneOptions {
77
+ /** The MAIN session's context — what the spawn is attributed to, and the
78
+ * source of both the conversation and the live system prompt. */
79
+ ctx: ExtensionContext;
80
+ /** Agent type the handle resolved to. */
81
+ type: SubagentType;
82
+ /** What the user typed after the handle. */
83
+ message: string;
84
+ /** The registered `Agent` tool, reused so the spawn is an ordinary one. */
85
+ agentTool: ToolDefinition;
86
+ }
87
+
88
+ export interface MentionCloneResult {
89
+ /** True once the clone actually called `Agent`. */
90
+ spawned: boolean;
91
+ /** Why not, when it didn't. Absent on success. */
92
+ error?: string;
93
+ }
94
+
95
+ /**
96
+ * Fork the conversation, let the copy make the tool call, throw the copy away.
97
+ * Never rejects: a clone that cannot run is reported so the caller can fall
98
+ * back to starting the agent directly.
99
+ */
100
+ export async function runMentionClone(opts: MentionCloneOptions): Promise<MentionCloneResult> {
101
+ const { ctx, type, message, agentTool } = opts;
102
+
103
+ let spawned = false;
104
+ const cloneAgentTool: ToolDefinition = {
105
+ ...agentTool,
106
+ execute: (_cloneToolCallId, params, signal, onUpdate, _cloneCtx) => {
107
+ // One spawn per mention. The clone has a single tool and every reason to
108
+ // stop after using it, but a model that decides to "also" launch a second
109
+ // agent would do it where nobody can see and nobody asked.
110
+ if (spawned) {
111
+ return Promise.resolve({
112
+ content: [{ type: "text" as const, text: "Already started an agent for this mention. Stop here." }],
113
+ details: undefined,
114
+ isError: true,
115
+ });
116
+ }
117
+ spawned = true;
118
+ // undefined tool-call id + the main ctx: see the header. Background is
119
+ // forced rather than left to the clone: `run_in_background` defaults to
120
+ // false, and a foreground agent answers through its TOOL RESULT — which
121
+ // here is delivered into a session that is disposed moments later, so the
122
+ // agent would run, appear in the widget and the fleet, and reach nobody.
123
+ return agentTool.execute(
124
+ undefined as never,
125
+ { ...(params as Record<string, unknown>), run_in_background: true } as typeof params,
126
+ signal,
127
+ onUpdate,
128
+ ctx,
129
+ );
130
+ },
131
+ };
132
+
133
+ let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
134
+ try {
135
+ // Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
136
+ // agent-runner.ts carries the same shim for the same reason — pass both so
137
+ // the clone keeps the parent's providers across the supported range.
138
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: unknown }).runtime;
139
+ // The conversation as the main session resolves it: compaction applied,
140
+ // branch summaries substituted.
141
+ const conversation = buildSessionContext(
142
+ ctx.sessionManager.getEntries(),
143
+ ctx.sessionManager.getLeafId(),
144
+ );
145
+ // Pi 0.82.0 added this; below it the field is absent and the clone takes
146
+ // the settings level instead, which is what a session that never ran
147
+ // `/think` is on anyway. Same shim shape as `modelRuntime` below.
148
+ const thinkingLevel = (ctx as { thinkingLevel?: ThinkingLevel }).thinkingLevel;
149
+ const created = await runInChildSessionContext(() =>
150
+ createAgentSession({
151
+ cwd: ctx.cwd,
152
+ // Nothing about the copy is worth persisting, and an in-memory manager
153
+ // is also what keeps the real session untouched.
154
+ sessionManager: SessionManager.inMemory(ctx.cwd),
155
+ model: ctx.model as Model<never> | undefined,
156
+ ...(thinkingLevel && { thinkingLevel }),
157
+ modelRegistry: ctx.modelRegistry,
158
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime as never }),
159
+ // An allowlist naming exactly the clone's own tool. NOT `noTools:
160
+ // "all"`, whose doc comment ("start with no tools enabled") reads like
161
+ // it spares custom tools and does not: it resolves to an EMPTY
162
+ // allowlist, and `isAllowedTool` then drops every tool from the
163
+ // registry — the custom one included. The clone would be prompted with
164
+ // nothing to call, answer in prose, and every mention would fall
165
+ // through to the direct start with a warning. Same idiom as
166
+ // agent-runner's `tools: sessionTools` beside its nested `customTools`.
167
+ tools: [cloneAgentTool.name],
168
+ customTools: [cloneAgentTool],
169
+ } as Parameters<typeof createAgentSession>[0]),
170
+ );
171
+ session = created.session;
172
+
173
+ // The clone rebuilds a system prompt from cwd and agentDir, which is close
174
+ // but not the live one — extensions contribute to it per turn. Copy the
175
+ // real thing, so the copy reasons under the instructions the user's model
176
+ // is actually working under.
177
+ const systemPrompt = ctx.getSystemPrompt?.();
178
+ if (systemPrompt) session.agent.state.systemPrompt = systemPrompt;
179
+
180
+ // The conversation itself. Pushed rather than assigned so the array the
181
+ // session was built around stays the one it goes on using.
182
+ session.agent.state.messages.push(...conversation.messages);
183
+
184
+ // User text first, reminder after — the order Claude Code's attachment
185
+ // renderer produces, where the reminder trails the message it is about.
186
+ await session.prompt(`${message}\n\n${agentMentionReminder(type)}`);
187
+ } catch (err) {
188
+ return { spawned, error: err instanceof Error ? err.message : String(err) };
189
+ } finally {
190
+ session?.dispose?.();
191
+ }
192
+
193
+ return spawned
194
+ ? { spawned: true }
195
+ : { spawned: false, error: "the conversation clone did not start it" };
196
+ }
package/src/mention.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * mention.ts — the `@handle` grammar for messaging a subagent from the prompt.
3
+ *
4
+ * Claude Code lets you type `@code-review take another look` at the prompt and
5
+ * routes the message to that agent instead of the main model. Its grammar is
6
+ * reproduced here so the two behave identically:
7
+ *
8
+ * - suggestions fire on `@` at the start of the input or after whitespace,
9
+ * followed by `[\w-]*` (so `@src/foo.ts` is a file, never an agent);
10
+ * - a send is recognized only at the START of the input, and only with a
11
+ * non-empty message after the handle. That is why a bare `@code-review`
12
+ * goes to the main model rather than anywhere near the agent.
13
+ *
14
+ * A record's own identity is a UUID plus a deliberately non-unique description,
15
+ * neither of which is typeable, so the handle is derived from the agent type.
16
+ * Colliding handles are numbered (`explore`, `explore-2`), which is also what
17
+ * Claude Code's `allocateName` does — it recycles a name only once the task
18
+ * behind it is gone. Its SendMessage prompt describes the *registry* as
19
+ * latest-wins, which is a different thing and not how names are allocated.
20
+ */
21
+
22
+ /**
23
+ * Suggestion trigger: `@` at a token boundary plus the partial handle typed so
24
+ * far. Ported from Claude Code, including the CJK sentence-ending punctuation
25
+ * it accepts as a boundary.
26
+ */
27
+ export const MENTION_TRIGGER = /(^|[\s。、?!])@([\w-]*)$/;
28
+
29
+ /** Send grammar: leading `@handle`, then a non-empty message. */
30
+ const MENTION_SEND = /^@([\w-]+)\s+([\s\S]+)$/;
31
+
32
+ /**
33
+ * Upper bound on a handle, matching Claude Code's `dSS`. Nothing here generates
34
+ * a name this long, but an agent type or a model-supplied name can be arbitrary
35
+ * text, and an unbounded handle would wrap the suggestion popup.
36
+ */
37
+ const MAX_HANDLE_LENGTH = 64;
38
+
39
+ /**
40
+ * Handles that address something other than a subagent, and so can never be
41
+ * allocated to one. Claude Code reserves exactly this name (`Vq = "main"`),
42
+ * refusing it at spawn and routing it to the main conversation instead.
43
+ */
44
+ const RESERVED_HANDLES: ReadonlySet<string> = new Set(["main"]);
45
+
46
+ /** Whether `@handle` names the main conversation rather than any subagent. */
47
+ export function isReservedHandle(handle: string): boolean {
48
+ return RESERVED_HANDLES.has(handle.toLowerCase());
49
+ }
50
+
51
+ /** Slug of an agent type or name, restricted to the `[\w-]` the grammar allows. */
52
+ export function handleBase(type: string): string {
53
+ const slug = type.toLowerCase()
54
+ .replace(/[^a-z0-9_-]+/g, "-")
55
+ .replace(/^-+|-+$/g, "")
56
+ .slice(0, MAX_HANDLE_LENGTH)
57
+ // The slice can land mid-run and leave the trailing hyphen back.
58
+ .replace(/-+$/, "");
59
+ return slug || "agent";
60
+ }
61
+
62
+ /**
63
+ * `base`, else `base-2`, `base-3`, … — the first form that is neither `taken`
64
+ * nor reserved. Callers pass one shared `taken` set covering type-derived
65
+ * handles and model-supplied aliases alike, so the two can never collide.
66
+ */
67
+ export function assignHandle(base: string, taken: ReadonlySet<string>): string {
68
+ let candidate = base;
69
+ let n = 1;
70
+ while (taken.has(candidate) || RESERVED_HANDLES.has(candidate)) {
71
+ n++;
72
+ candidate = `${base}-${n}`;
73
+ }
74
+ return candidate;
75
+ }
76
+
77
+ /**
78
+ * Map a typed handle back to a registered agent type, so `@explore fix it`
79
+ * reaches the Explore agent even when no instance has ever run. `handleBase` is
80
+ * the single source of truth in both directions, so a type is addressable by
81
+ * exactly the handle its instances would be given.
82
+ */
83
+ export function resolveHandleToType(handle: string, types: readonly string[]): string | undefined {
84
+ const wanted = handle.toLowerCase();
85
+ // A type slugging to a reserved name is unaddressable rather than shadowing
86
+ // it — `assignHandle` refuses that name too, so its instances never hold one.
87
+ if (RESERVED_HANDLES.has(wanted)) return undefined;
88
+ return types.find(type => handleBase(type) === wanted);
89
+ }
90
+
91
+ /**
92
+ * Claude Code documents `@agent-<name>` as the form you type by hand when the
93
+ * picker isn't involved. Accepted here as an exact synonym: the caller tries the
94
+ * handle as written first, so an agent genuinely called `agent-foo` still wins
95
+ * over `@agent-` + `foo`, and only falls back to this when that finds nothing.
96
+ * Returns undefined when the prefix is absent or is the whole handle.
97
+ */
98
+ export function stripAgentPrefix(handle: string): string | undefined {
99
+ const rest = /^agent-(.+)$/i.exec(handle)?.[1];
100
+ return rest || undefined;
101
+ }
102
+
103
+ /**
104
+ * A spawn needs the short description every agent surface renders. A mention
105
+ * carries no separate label, so the message itself becomes one: first line,
106
+ * whitespace collapsed, clipped to roughly the 3-5 words the Agent tool asks of
107
+ * the model.
108
+ */
109
+ export function describeMention(message: string): string {
110
+ const oneLine = message.split("\n", 1)[0].replace(/\s+/g, " ").trim();
111
+ return oneLine.length > 40 ? `${oneLine.slice(0, 39).trimEnd()}…` : oneLine;
112
+ }
113
+
114
+ /**
115
+ * What Claude Code sends the main model when a mention names an agent it could
116
+ * start. Its `@agent-<type>` mention is not a spawn at all: it becomes an
117
+ * `agent_mention` attachment, which renders to a synthetic `isMeta` user
118
+ * message placed after the user's own untouched text — no tool forcing, no
119
+ * allowed-tools narrowing, and the Task tool is not even named. The model reads
120
+ * this and calls the tool itself.
121
+ *
122
+ * Ported verbatim from the 2.1.233 bundle's attachment renderer, trailing space
123
+ * before the closing newline included, so the wording the model was trained
124
+ * against is the wording it gets. The one substitution is ours: pi's equivalent
125
+ * of Task is the `Agent` tool, and the agent listing that teaches valid
126
+ * `subagent_type` values is the tool spec rather than a separate attachment.
127
+ */
128
+ export function agentMentionReminder(type: string): string {
129
+ return `<system-reminder>\nThe user has expressed a desire to invoke the agent "${type}". Please invoke the agent appropriately, passing in the required context to it. \n</system-reminder>`;
130
+ }
131
+
132
+ /**
133
+ * Split `@handle message` into its parts, or null when the text isn't a send —
134
+ * a bare handle, a leading file path, or a mention that isn't at the start.
135
+ */
136
+ export function parseMention(text: string): { handle: string; message: string } | null {
137
+ const match = MENTION_SEND.exec(text);
138
+ if (!match) return null;
139
+ const message = match[2].trim();
140
+ return message ? { handle: match[1], message } : null;
141
+ }
@@ -14,6 +14,24 @@ export interface ModelRegistry {
14
14
  getAvailable?(): any[];
15
15
  }
16
16
 
17
+ /**
18
+ * Both display forms of a model. The short one goes on tight rows (the widget,
19
+ * the Agent tool result), the canonical one where there is room to disambiguate
20
+ * two providers serving a similarly-named model (the conversation viewer).
21
+ *
22
+ * One function, because `index.ts` labels the model it resolved before the run
23
+ * and `agent-manager.ts` relabels it from the live session afterwards — the two
24
+ * must agree or the label would visibly change the moment the session starts.
25
+ */
26
+ export function describeModel(
27
+ model: { provider: string; id: string; name?: string },
28
+ ): { modelName: string; modelId: string } {
29
+ return {
30
+ modelName: (model.name ?? model.id).replace(/^Claude\s+/i, "").toLowerCase(),
31
+ modelId: `${model.provider}/${model.id}`,
32
+ };
33
+ }
34
+
17
35
  /**
18
36
  * Resolve a model string to a Model instance.
19
37
  * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
@@ -0,0 +1,70 @@
1
+ /**
2
+ * model-scope.ts — `scopeModels` policy, shared by the top-level Agent tool and
3
+ * the nested delegation tools so a nested spawn can't escape the allowlist the
4
+ * top-level path enforces.
5
+ *
6
+ * State lives here (rather than in an index.ts closure) for the same reason
7
+ * `disableDefaults` lives in agent-types.ts: both entry points need it.
8
+ */
9
+
10
+ import { isModelInScope, type ModelRegistryRef, readEnabledModels, resolveEnabledModels } from "./enabled-models.js";
11
+
12
+ /**
13
+ * When enabled, subagent model choices are validated against `enabledModels`
14
+ * from pi's settings — both global `<agentDir>/settings.json` and project-local
15
+ * `<cwd>/.pi/settings.json` (project overrides global). Off by default; opt-in
16
+ * via `/agents → Settings`. See the SubagentsSettings.scopeModels docstring for
17
+ * the hard-error vs warn-and-proceed policy and its rationale.
18
+ */
19
+ let scopeModelsEnabled = false;
20
+
21
+ export function isScopeModelsEnabled(): boolean { return scopeModelsEnabled; }
22
+ export function setScopeModelsEnabled(enabled: boolean): void { scopeModelsEnabled = enabled; }
23
+
24
+ export type ModelScopeVerdict =
25
+ /** In scope, or nothing to validate against (feature off / no allowlist). */
26
+ | { kind: "ok" }
27
+ /** Caller-supplied out-of-scope choice — refuse the spawn with this message. */
28
+ | { kind: "error"; message: string }
29
+ /** Frontmatter-pinned or parent-inherited — proceed, but tell the user. */
30
+ | { kind: "warn"; message: string };
31
+
32
+ /**
33
+ * Check the effective resolved model against the user's enabledModels list.
34
+ *
35
+ * scopeModels guards against *runtime* LLM choices, not user-level config:
36
+ * - Caller-supplied out-of-scope → hard error (the orchestrator made an explicit
37
+ * out-of-scope choice; surface it so it picks differently).
38
+ * - Frontmatter-pinned or parent-inherited out-of-scope → warn but proceed (the
39
+ * user authored/installed this agent or chose the parent's model; trust it).
40
+ */
41
+ export function checkModelScope(args: {
42
+ model: { provider: string; id: string } | undefined;
43
+ cwd: string;
44
+ modelRegistry: ModelRegistryRef;
45
+ /** True when the model came from the tool call rather than frontmatter. */
46
+ callerSupplied: boolean;
47
+ /** Display name used in the warning toast. */
48
+ agentLabel: string;
49
+ /** The raw `model:` input, when there was one. */
50
+ modelInput?: string;
51
+ }): ModelScopeVerdict {
52
+ const { model, cwd, modelRegistry, callerSupplied, agentLabel, modelInput } = args;
53
+ if (!scopeModelsEnabled || !model) return { kind: "ok" };
54
+
55
+ const allowed = resolveEnabledModels(readEnabledModels(cwd), modelRegistry, cwd);
56
+ if (!allowed || isModelInScope(model, allowed)) return { kind: "ok" };
57
+
58
+ if (callerSupplied) {
59
+ const list = [...allowed].sort().map(m => ` ${m}`).join("\n");
60
+ return {
61
+ kind: "error",
62
+ message: `Model not in scope: "${modelInput}".\n\nAllowed models (from enabledModels):\n${list}`,
63
+ };
64
+ }
65
+ const modelLabel = modelInput ?? `${model.provider}/${model.id}`;
66
+ return {
67
+ kind: "warn",
68
+ message: `Agent "${agentLabel}" using out-of-scope model "${modelLabel}"`,
69
+ };
70
+ }