@esso0428/pi-subagents 0.17.5 → 0.17.7

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 (263) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/README.md +1 -1
  4. package/dist/abortable.d.ts +13 -0
  5. package/dist/abortable.d.ts.map +1 -0
  6. package/dist/abortable.js +43 -0
  7. package/dist/abortable.js.map +1 -0
  8. package/dist/agent-color.d.ts +36 -0
  9. package/dist/agent-color.d.ts.map +1 -0
  10. package/dist/agent-color.js +124 -0
  11. package/dist/agent-color.js.map +1 -0
  12. package/dist/agent-file-toggle.d.ts +126 -0
  13. package/dist/agent-file-toggle.d.ts.map +1 -0
  14. package/dist/agent-file-toggle.js +259 -0
  15. package/dist/agent-file-toggle.js.map +1 -0
  16. package/dist/agent-history.d.ts +4 -0
  17. package/dist/agent-history.d.ts.map +1 -1
  18. package/dist/agent-history.js +47 -1
  19. package/dist/agent-history.js.map +1 -1
  20. package/dist/agent-manager.d.ts +370 -56
  21. package/dist/agent-manager.d.ts.map +1 -1
  22. package/dist/agent-manager.js +1123 -409
  23. package/dist/agent-manager.js.map +1 -1
  24. package/dist/agent-runner.d.ts +100 -10
  25. package/dist/agent-runner.d.ts.map +1 -1
  26. package/dist/agent-runner.js +166 -21
  27. package/dist/agent-runner.js.map +1 -1
  28. package/dist/agent-types.d.ts +57 -5
  29. package/dist/agent-types.d.ts.map +1 -1
  30. package/dist/agent-types.js +164 -32
  31. package/dist/agent-types.js.map +1 -1
  32. package/dist/child-context.d.ts +3 -0
  33. package/dist/child-context.d.ts.map +1 -0
  34. package/dist/child-context.js +13 -0
  35. package/dist/child-context.js.map +1 -0
  36. package/dist/cross-extension-rpc.d.ts +23 -3
  37. package/dist/cross-extension-rpc.d.ts.map +1 -1
  38. package/dist/cross-extension-rpc.js +79 -17
  39. package/dist/cross-extension-rpc.js.map +1 -1
  40. package/dist/custom-agents.d.ts +38 -1
  41. package/dist/custom-agents.d.ts.map +1 -1
  42. package/dist/custom-agents.js +164 -12
  43. package/dist/custom-agents.js.map +1 -1
  44. package/dist/index.d.ts +34 -0
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +1908 -495
  47. package/dist/index.js.map +1 -1
  48. package/dist/invocation-config.d.ts +87 -2
  49. package/dist/invocation-config.d.ts.map +1 -1
  50. package/dist/invocation-config.js +71 -3
  51. package/dist/invocation-config.js.map +1 -1
  52. package/dist/mention-clone.d.ts +88 -0
  53. package/dist/mention-clone.d.ts.map +1 -0
  54. package/dist/mention-clone.js +154 -0
  55. package/dist/mention-clone.js.map +1 -0
  56. package/dist/mention.d.ts +82 -0
  57. package/dist/mention.d.ts.map +1 -0
  58. package/dist/mention.js +132 -0
  59. package/dist/mention.js.map +1 -0
  60. package/dist/model-resolver.d.ts +17 -0
  61. package/dist/model-resolver.d.ts.map +1 -1
  62. package/dist/model-resolver.js +15 -0
  63. package/dist/model-resolver.js.map +1 -1
  64. package/dist/model-scope.d.ts +50 -0
  65. package/dist/model-scope.d.ts.map +1 -0
  66. package/dist/model-scope.js +49 -0
  67. package/dist/model-scope.js.map +1 -0
  68. package/dist/nested-tools.d.ts +57 -0
  69. package/dist/nested-tools.d.ts.map +1 -0
  70. package/dist/nested-tools.js +301 -0
  71. package/dist/nested-tools.js.map +1 -0
  72. package/dist/output-file.d.ts +22 -3
  73. package/dist/output-file.d.ts.map +1 -1
  74. package/dist/output-file.js +58 -7
  75. package/dist/output-file.js.map +1 -1
  76. package/dist/prompts.d.ts +23 -0
  77. package/dist/prompts.d.ts.map +1 -1
  78. package/dist/prompts.js +20 -2
  79. package/dist/prompts.js.map +1 -1
  80. package/dist/schedule.d.ts.map +1 -1
  81. package/dist/schedule.js +36 -15
  82. package/dist/schedule.js.map +1 -1
  83. package/dist/settings.d.ts +228 -2
  84. package/dist/settings.d.ts.map +1 -1
  85. package/dist/settings.js +94 -0
  86. package/dist/settings.js.map +1 -1
  87. package/dist/status-note.d.ts +49 -1
  88. package/dist/status-note.d.ts.map +1 -1
  89. package/dist/status-note.js +62 -1
  90. package/dist/status-note.js.map +1 -1
  91. package/dist/structured-output.d.ts +62 -0
  92. package/dist/structured-output.d.ts.map +1 -0
  93. package/dist/structured-output.js +113 -0
  94. package/dist/structured-output.js.map +1 -0
  95. package/dist/types.d.ts +176 -10
  96. package/dist/types.d.ts.map +1 -1
  97. package/dist/ui/agent-mention.d.ts +83 -0
  98. package/dist/ui/agent-mention.d.ts.map +1 -0
  99. package/dist/ui/agent-mention.js +188 -0
  100. package/dist/ui/agent-mention.js.map +1 -0
  101. package/dist/ui/agent-widget.d.ts +96 -75
  102. package/dist/ui/agent-widget.d.ts.map +1 -1
  103. package/dist/ui/agent-widget.js +397 -420
  104. package/dist/ui/agent-widget.js.map +1 -1
  105. package/dist/ui/conversation-blocks.d.ts.map +1 -1
  106. package/dist/ui/conversation-blocks.js +6 -0
  107. package/dist/ui/conversation-blocks.js.map +1 -1
  108. package/dist/ui/conversation-timeline.d.ts +10 -2
  109. package/dist/ui/conversation-timeline.d.ts.map +1 -1
  110. package/dist/ui/conversation-timeline.js +130 -23
  111. package/dist/ui/conversation-timeline.js.map +1 -1
  112. package/dist/ui/conversation-viewer.d.ts +20 -5
  113. package/dist/ui/conversation-viewer.d.ts.map +1 -1
  114. package/dist/ui/conversation-viewer.js +274 -73
  115. package/dist/ui/conversation-viewer.js.map +1 -1
  116. package/dist/ui/fleet-list.d.ts +198 -0
  117. package/dist/ui/fleet-list.d.ts.map +1 -0
  118. package/dist/ui/fleet-list.js +487 -0
  119. package/dist/ui/fleet-list.js.map +1 -0
  120. package/dist/ui/schedule-menu.d.ts.map +1 -1
  121. package/dist/ui/schedule-menu.js +6 -7
  122. package/dist/ui/schedule-menu.js.map +1 -1
  123. package/dist/ui/select-item.d.ts +28 -0
  124. package/dist/ui/select-item.d.ts.map +1 -0
  125. package/dist/ui/select-item.js +35 -0
  126. package/dist/ui/select-item.js.map +1 -0
  127. package/dist/ui/workflow-card.d.ts +176 -0
  128. package/dist/ui/workflow-card.d.ts.map +1 -0
  129. package/dist/ui/workflow-card.js +333 -0
  130. package/dist/ui/workflow-card.js.map +1 -0
  131. package/dist/ui/workflow-dialog.d.ts +306 -0
  132. package/dist/ui/workflow-dialog.d.ts.map +1 -0
  133. package/dist/ui/workflow-dialog.js +844 -0
  134. package/dist/ui/workflow-dialog.js.map +1 -0
  135. package/dist/ui/workflow-menu.d.ts +61 -0
  136. package/dist/ui/workflow-menu.d.ts.map +1 -0
  137. package/dist/ui/workflow-menu.js +148 -0
  138. package/dist/ui/workflow-menu.js.map +1 -0
  139. package/dist/usage.d.ts +86 -1
  140. package/dist/usage.d.ts.map +1 -1
  141. package/dist/usage.js +72 -1
  142. package/dist/usage.js.map +1 -1
  143. package/dist/workflow/collisions.d.ts +96 -0
  144. package/dist/workflow/collisions.d.ts.map +1 -0
  145. package/dist/workflow/collisions.js +89 -0
  146. package/dist/workflow/collisions.js.map +1 -0
  147. package/dist/workflow/entry.d.ts +33 -0
  148. package/dist/workflow/entry.d.ts.map +1 -0
  149. package/dist/workflow/entry.js +30 -0
  150. package/dist/workflow/entry.js.map +1 -0
  151. package/dist/workflow/host.d.ts +63 -0
  152. package/dist/workflow/host.d.ts.map +1 -0
  153. package/dist/workflow/host.js +363 -0
  154. package/dist/workflow/host.js.map +1 -0
  155. package/dist/workflow/journal.d.ts +98 -0
  156. package/dist/workflow/journal.d.ts.map +1 -0
  157. package/dist/workflow/journal.js +121 -0
  158. package/dist/workflow/journal.js.map +1 -0
  159. package/dist/workflow/json-schema.d.ts +52 -0
  160. package/dist/workflow/json-schema.d.ts.map +1 -0
  161. package/dist/workflow/json-schema.js +112 -0
  162. package/dist/workflow/json-schema.js.map +1 -0
  163. package/dist/workflow/meta.d.ts +68 -0
  164. package/dist/workflow/meta.d.ts.map +1 -0
  165. package/dist/workflow/meta.js +318 -0
  166. package/dist/workflow/meta.js.map +1 -0
  167. package/dist/workflow/progress.d.ts +225 -0
  168. package/dist/workflow/progress.d.ts.map +1 -0
  169. package/dist/workflow/progress.js +362 -0
  170. package/dist/workflow/progress.js.map +1 -0
  171. package/dist/workflow/runtime.d.ts +335 -0
  172. package/dist/workflow/runtime.d.ts.map +1 -0
  173. package/dist/workflow/runtime.js +831 -0
  174. package/dist/workflow/runtime.js.map +1 -0
  175. package/dist/workflow/saved.d.ts +91 -0
  176. package/dist/workflow/saved.d.ts.map +1 -0
  177. package/dist/workflow/saved.js +204 -0
  178. package/dist/workflow/saved.js.map +1 -0
  179. package/dist/workflow/task.d.ts +137 -0
  180. package/dist/workflow/task.d.ts.map +1 -0
  181. package/dist/workflow/task.js +208 -0
  182. package/dist/workflow/task.js.map +1 -0
  183. package/dist/workflow/tool-description.d.ts +39 -0
  184. package/dist/workflow/tool-description.d.ts.map +1 -0
  185. package/dist/workflow/tool-description.js +200 -0
  186. package/dist/workflow/tool-description.js.map +1 -0
  187. package/dist/workflow/worker-source.d.ts +48 -0
  188. package/dist/workflow/worker-source.d.ts.map +1 -0
  189. package/dist/workflow/worker-source.js +779 -0
  190. package/dist/workflow/worker-source.js.map +1 -0
  191. package/dist/worktree.d.ts +10 -3
  192. package/dist/worktree.d.ts.map +1 -1
  193. package/dist/worktree.js +58 -54
  194. package/dist/worktree.js.map +1 -1
  195. package/dist/xml.d.ts +11 -0
  196. package/dist/xml.d.ts.map +1 -0
  197. package/dist/xml.js +13 -0
  198. package/dist/xml.js.map +1 -0
  199. package/docs/rpc.md +183 -0
  200. package/docs/superpowers/plans/2026-09-30-conversation-viewer-scrollbar.md +216 -0
  201. package/docs/superpowers/plans/2026-09-30-upstream-event-workflow-partial-history.md +195 -0
  202. package/docs/superpowers/specs/2026-09-30-conversation-viewer-scrollbar-design.md +82 -0
  203. package/docs/superpowers/specs/2026-09-30-upstream-event-workflow-partial-history-design.md +49 -0
  204. package/docs/workflows.md +437 -0
  205. package/examples/agent-tool-description.md +7 -7
  206. package/examples/workflows/compose.js +51 -0
  207. package/examples/workflows/fan-out-audit.js +47 -0
  208. package/examples/workflows/gated-fix.js +60 -0
  209. package/examples/workflows/lib/count-child.js +27 -0
  210. package/examples/workflows/review-panel.js +63 -0
  211. package/examples/workflows/structured-findings.js +78 -0
  212. package/package.json +1 -1
  213. package/src/abortable.ts +43 -0
  214. package/src/agent-color.ts +161 -0
  215. package/src/agent-file-toggle.ts +269 -0
  216. package/src/agent-history.ts +54 -2
  217. package/src/agent-manager.ts +1263 -402
  218. package/src/agent-runner.ts +251 -27
  219. package/src/agent-types.ts +188 -32
  220. package/src/child-context.ts +15 -0
  221. package/src/cross-extension-rpc.ts +96 -20
  222. package/src/custom-agents.ts +170 -13
  223. package/src/index.ts +2024 -537
  224. package/src/invocation-config.ts +118 -3
  225. package/src/mention-clone.ts +196 -0
  226. package/src/mention.ts +141 -0
  227. package/src/model-resolver.ts +18 -0
  228. package/src/model-scope.ts +70 -0
  229. package/src/nested-tools.ts +424 -0
  230. package/src/output-file.ts +61 -6
  231. package/src/prompts.ts +45 -2
  232. package/src/schedule.ts +35 -14
  233. package/src/settings.ts +312 -2
  234. package/src/status-note.ts +66 -1
  235. package/src/structured-output.ts +130 -0
  236. package/src/types.ts +177 -10
  237. package/src/ui/agent-mention.ts +216 -0
  238. package/src/ui/agent-widget.ts +389 -441
  239. package/src/ui/conversation-blocks.ts +6 -0
  240. package/src/ui/conversation-timeline.ts +139 -25
  241. package/src/ui/conversation-viewer.ts +284 -69
  242. package/src/ui/fleet-list.ts +558 -0
  243. package/src/ui/schedule-menu.ts +9 -8
  244. package/src/ui/select-item.ts +45 -0
  245. package/src/ui/workflow-card.ts +470 -0
  246. package/src/ui/workflow-dialog.ts +1115 -0
  247. package/src/ui/workflow-menu.ts +193 -0
  248. package/src/usage.ts +109 -2
  249. package/src/workflow/collisions.ts +123 -0
  250. package/src/workflow/entry.ts +47 -0
  251. package/src/workflow/host.ts +403 -0
  252. package/src/workflow/journal.ts +164 -0
  253. package/src/workflow/json-schema.ts +128 -0
  254. package/src/workflow/meta.ts +325 -0
  255. package/src/workflow/progress.ts +550 -0
  256. package/src/workflow/runtime.ts +1219 -0
  257. package/src/workflow/saved.ts +217 -0
  258. package/src/workflow/task.ts +302 -0
  259. package/src/workflow/tool-description.ts +200 -0
  260. package/src/workflow/worker-source.ts +781 -0
  261. package/src/worktree.ts +69 -55
  262. package/src/xml.ts +13 -0
  263. package/vitest.config.ts +0 -18
@@ -0,0 +1,130 @@
1
+ /**
2
+ * structured-output.ts — the synthetic tool behind `agent(prompt, { schema })`.
3
+ *
4
+ * A workflow script that passes a `schema` wants an *object* back, not prose it
5
+ * has to parse. Claude Code does this by giving the child a `StructuredOutput`
6
+ * tool whose input schema is the caller's schema, so the provider fills the
7
+ * fields, and returning the validated payload as the agent's result.
8
+ *
9
+ * We do the same, with one gap named up front: Claude Code *forces* the call,
10
+ * and we cannot. `toolChoice` exists in pi-ai's provider layer but is not
11
+ * plumbed through `AgentSession`, so an extension has no way to require a
12
+ * particular tool. What we have instead is three softer pressures —
13
+ *
14
+ * 1. `constrainedSampling`, so providers that support it hold the payload to
15
+ * the schema at sampling time;
16
+ * 2. the tool's description, snippet and guideline, which say the answer must
17
+ * come through this call;
18
+ * 3. validation here, answering a bad payload with `isError` so the model
19
+ * sees what was wrong and calls again inside the same run.
20
+ *
21
+ * — and, when all three fail, one more prompt from `runAgent`. See
22
+ * {@link structuredRetryPrompt}.
23
+ *
24
+ * The name matches Claude Code's exactly, so a ported prompt that mentions
25
+ * `StructuredOutput` is still telling the truth.
26
+ */
27
+
28
+ import { defineTool, type ToolDefinition } from "@earendil-works/pi-coding-agent";
29
+ import type { CompiledSchema } from "./workflow/json-schema.js";
30
+
31
+ /**
32
+ * Deliberately NOT added to `SUBAGENT_TOOL_NAMES`: that list becomes
33
+ * `EXCLUDED_TOOL_NAMES`, which is exactly the denial this tool has to avoid.
34
+ * Nor to `BUILTIN_TOOL_NAMES` — it is ours to inject, never a name a user may
35
+ * ask for in an agent's `tools:` frontmatter.
36
+ */
37
+ export const STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput";
38
+
39
+ /** What the child produced, filled in as the tool is called. */
40
+ export interface StructuredCapture {
41
+ /** The last payload that validated, canonicalised. Absent until one does. */
42
+ json?: string;
43
+ /** Why the most recent attempt was rejected, for the retry prompt. */
44
+ lastError?: string;
45
+ /** Whether the tool was called at all — "never tried" reads differently. */
46
+ called: boolean;
47
+ }
48
+
49
+ export function createStructuredCapture(): StructuredCapture {
50
+ return { called: false };
51
+ }
52
+
53
+ /**
54
+ * Build the tool for one child.
55
+ *
56
+ * `capture` is the box the caller reads afterwards. It is passed in rather than
57
+ * returned so `runAgent` owns its lifetime and can consult it on every exit
58
+ * path, including the ones where the tool was never reached.
59
+ */
60
+ export function createStructuredOutputTool(
61
+ compiled: CompiledSchema,
62
+ capture: StructuredCapture,
63
+ ): ToolDefinition {
64
+ return defineTool({
65
+ name: STRUCTURED_OUTPUT_TOOL_NAME,
66
+ label: "Structured Output",
67
+ description:
68
+ "Report your final answer. Call this exactly once, with the complete result, and put everything the "
69
+ + "caller needs inside the arguments — text written outside this call is discarded. If a call is "
70
+ + "rejected for not matching the schema, fix the reported fields and call it again.",
71
+ promptSnippet: "Report your final answer as structured data",
72
+ promptGuidelines: [
73
+ "Your final answer MUST be reported by calling StructuredOutput. Prose outside that call is discarded.",
74
+ ],
75
+ // The caller's schema *is* the tool's input schema, verbatim — that is what
76
+ // makes the provider fill the fields. pi types this as TypeBox's `TSchema`,
77
+ // which v1 defines as an open interface, so a plain JSON Schema satisfies
78
+ // it without a cast at runtime or a conversion at author time.
79
+ parameters: compiled.schema as never,
80
+ // "prefer", not "require": a provider that cannot constrain sampling should
81
+ // fall through to validation-and-retry rather than fail the call outright.
82
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
83
+ // Models occasionally send the whole payload as one JSON string instead of
84
+ // an object. Recovering that costs nothing and saves a whole retry.
85
+ prepareArguments: (args: unknown) => {
86
+ if (typeof args !== "string") return args as never;
87
+ try {
88
+ return JSON.parse(args) as never;
89
+ } catch {
90
+ return args as never;
91
+ }
92
+ },
93
+ execute: async (_toolCallId, params) => {
94
+ capture.called = true;
95
+ const verdict = compiled.check(params);
96
+ if (verdict !== true) {
97
+ capture.lastError = verdict;
98
+ // `isError` puts the reason in front of the model as a tool result, so
99
+ // it can correct itself inside this same run. This is where most
100
+ // mismatches are resolved; the prompt-level retry is the backstop.
101
+ return {
102
+ content: [{
103
+ type: "text",
104
+ text: `StructuredOutput did not match the required schema:\n${verdict}\nCall it again with a corrected value.`,
105
+ }],
106
+ isError: true,
107
+ details: {},
108
+ };
109
+ }
110
+ // Last valid call wins: a model that calls twice meant the second one.
111
+ capture.json = JSON.stringify(params);
112
+ capture.lastError = undefined;
113
+ return { content: [{ type: "text", text: "Recorded." }], details: {} };
114
+ },
115
+ }) as ToolDefinition;
116
+ }
117
+
118
+ /**
119
+ * The one extra prompt sent when a run ended with nothing captured.
120
+ *
121
+ * Distinguishes "never called it" from "called it wrongly" — the two need
122
+ * different corrections, and telling a model it got the shape wrong when it
123
+ * never answered at all sends it looking for a mistake it did not make.
124
+ */
125
+ export function structuredRetryPrompt(capture: StructuredCapture): string {
126
+ const reason = capture.called && capture.lastError !== undefined
127
+ ? `Your last ${STRUCTURED_OUTPUT_TOOL_NAME} call did not match the required schema: ${capture.lastError}`
128
+ : `You did not call ${STRUCTURED_OUTPUT_TOOL_NAME}, so your answer was not recorded.`;
129
+ return `${reason}\n\nCall ${STRUCTURED_OUTPUT_TOOL_NAME} now with your complete final answer. Do not reply with prose.`;
130
+ }
package/src/types.ts CHANGED
@@ -17,13 +17,26 @@ export const DEFAULT_AGENT_NAMES = ["general-purpose", "Explore", "Plan"] as con
17
17
  /** Memory scope for persistent agent memory. */
18
18
  export type MemoryScope = "user" | "project" | "local";
19
19
 
20
- /** Isolation mode for agent execution. */
21
- export type IsolationMode = "worktree";
20
+ /**
21
+ * Isolation mode for agent execution.
22
+ *
23
+ * `"off"` exists for the caller's benefit, not the runtime's: models that fill
24
+ * every optional parameter had no legal way to decline a single-value
25
+ * `isolation` field and kept spawning worktrees they had just reasoned their
26
+ * way out of (#231, #184). It is an input spelling only —
27
+ * `resolveAgentInvocationConfig` collapses it to `undefined`, so nothing
28
+ * downstream sees a value other than `"worktree"`. In an agent file it is a
29
+ * genuine veto, since agent config outranks tool-call params.
30
+ */
31
+ export type IsolationMode = "worktree" | "off";
22
32
 
23
33
  /** Unified agent configuration — used for both default and user-defined agents. */
24
34
  export interface AgentConfig {
25
35
  name: string;
36
+ /** UI name. `display_name` wins; Claude Code's `name` is accepted as a fallback. */
26
37
  displayName?: string;
38
+ /** Claude Code-compatible name color (named color or #RRGGBB). */
39
+ color?: string;
27
40
  description: string;
28
41
  builtinToolNames?: string[];
29
42
  /** Raw `ext:` selector entries from the `tools:` CSV, e.g. ["ext:foo", "ext:bar/x"].
@@ -47,6 +60,11 @@ export interface AgentConfig {
47
60
  outputTranscript?: boolean;
48
61
  /** Optional session directory used when persistSession is true. Omitted = pi's normal session location. */
49
62
  sessionDir?: string;
63
+ /**
64
+ * Nested delegation, off by default: undefined = no nested tools;
65
+ * "all" = any enabled agent; string[] = only those agent types.
66
+ */
67
+ allowedSubagents?: "all" | string[];
50
68
  systemPrompt: string;
51
69
  promptMode: "replace" | "append";
52
70
  /** Default for spawn: fork parent conversation. undefined = caller decides. */
@@ -57,7 +75,10 @@ export interface AgentConfig {
57
75
  isolated?: boolean;
58
76
  /** Persistent memory scope — agents with memory get a persistent directory and MEMORY.md */
59
77
  memory?: MemoryScope;
60
- /** Isolation mode — "worktree" runs the agent in a temporary git worktree */
78
+ /**
79
+ * Isolation mode — "worktree" runs the agent in a temporary git worktree,
80
+ * "off" refuses one even when the caller asks (frontmatter outranks params).
81
+ */
61
82
  isolation?: IsolationMode;
62
83
  /** true = this is an embedded default agent (informational) */
63
84
  isDefault?: boolean;
@@ -65,6 +86,8 @@ export interface AgentConfig {
65
86
  enabled?: boolean;
66
87
  /** Where this agent was loaded from */
67
88
  source?: "default" | "project" | "global";
89
+ /** Path of the .md it was loaded from. Unset for embedded defaults. */
90
+ sourcePath?: string;
68
91
  }
69
92
 
70
93
  export type JoinMode = 'async' | 'group' | 'smart';
@@ -78,9 +101,75 @@ export type JoinMode = 'async' | 'group' | 'smart';
78
101
  */
79
102
  export type WidgetMode = 'all' | 'background' | 'off';
80
103
 
104
+ /**
105
+ * How much of the conversation viewer's transcript is rendered as Markdown.
106
+ * - `off`: every line wraps as literal text, as it did before the mode existed.
107
+ * - `assistant`: assistant text renders as Markdown; tool results stay verbatim
108
+ * and dim. The default, because assistant text *is* Markdown by contract
109
+ * while a tool result is arbitrary bytes — a Markdown pass over a log or a
110
+ * diff eats `#` from shell comments, swallows a `---` line into a setext
111
+ * heading, re-fences indented output and redraws `| a | b |` as a table.
112
+ * (Ordered-list renumbering is the one such rewrite actively suppressed —
113
+ * see `MARKDOWN_OPTIONS` — because it silently changes data, not layout.)
114
+ * - `all`: tool results render as Markdown too, for tools that genuinely emit
115
+ * it (#210's `ctx_execute`), accepting the rewrites above on ones that don't.
116
+ */
117
+ export type ViewerMarkdownMode = 'off' | 'assistant' | 'all';
118
+
119
+ /**
120
+ * How `@handle message` starts an agent that is not already running.
121
+ * - `model`: inject Claude Code's `agent_mention` reminder and let the main
122
+ * model spawn it with the `Agent` tool, which is what Claude Code does.
123
+ * - `direct`: spawn it here, immediately, with the typed message as its prompt
124
+ * and no main-model turn spent.
125
+ * - `off`: `@` means only "attach a file" again.
126
+ *
127
+ * Messaging a running agent and resuming a finished one are direct in every
128
+ * mode — Claude Code only differs from us on the *new* invocation.
129
+ */
130
+ export type AgentMentionMode = 'model' | 'direct' | 'off';
131
+
132
+ /**
133
+ * What survives a record's eviction so `@handle` keeps working. The live record
134
+ * is discarded after ~10 minutes, but the pi session it wrote is still on disk,
135
+ * and this is the little that is needed to find and describe it again.
136
+ */
137
+ export interface AgentTombstone {
138
+ handle: string;
139
+ alias?: string;
140
+ id: string;
141
+ type: SubagentType;
142
+ description: string;
143
+ /** Always set — a record with no session file is never tombstoned. */
144
+ sessionFile: string;
145
+ completedAt: number;
146
+ }
147
+
148
+ /**
149
+ * What `@handle` resolved to: an agent still in memory, or the remains of one
150
+ * whose conversation can be reopened from disk.
151
+ */
152
+ export type MentionResolution =
153
+ | { kind: "live"; record: AgentRecord }
154
+ | { kind: "tombstone"; entry: AgentTombstone };
155
+
81
156
  export interface AgentRecord {
82
157
  id: string;
83
158
  type: SubagentType;
159
+ /**
160
+ * Typeable name for the `@handle message` prompt mention, derived from the
161
+ * agent type and numbered when siblings collide (`explore`, `explore-2`).
162
+ * Top-level agents only — nested children are hidden from every top-level
163
+ * surface, so nothing can address them.
164
+ */
165
+ handle?: string;
166
+ /**
167
+ * A second, memorable handle from the spawner's `name` (`@auth-audit`), drawn
168
+ * from the same namespace as `handle` so the two can never collide. Purely
169
+ * additive: `handle` is assigned regardless, so a named agent stays reachable
170
+ * by its type and `@explore` never comes to mean "start another one".
171
+ */
172
+ alias?: string;
84
173
  description: string;
85
174
  status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error";
86
175
  result?: string;
@@ -91,6 +180,22 @@ export interface AgentRecord {
91
180
  session?: AgentSession;
92
181
  abortController?: AbortController;
93
182
  promise?: Promise<string>;
183
+ /**
184
+ * A caller is awaiting this agent inline (`spawnAndWait`) — what
185
+ * `maxConcurrentForeground` bounds. Distinct from `isBackground === false`,
186
+ * which says only that the agent has an inline result surface: a detached
187
+ * cross-extension RPC spawn is foreground by that measure and yet blocks
188
+ * nobody, so it takes no slot.
189
+ */
190
+ blocking?: boolean;
191
+ /**
192
+ * Present only while the record is "queued": resolves when it leaves the
193
+ * queue, started or aborted. `spawnAndWait` waits on this because a queued
194
+ * record has no `promise` yet. Always resolves, never rejects — a rejection
195
+ * would escape into the caller's tool `execute` and take down pi's whole
196
+ * Promise.all tool batch.
197
+ */
198
+ startGate?: Promise<void>;
94
199
  groupId?: string;
95
200
  joinMode?: JoinMode;
96
201
  /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
@@ -109,8 +214,17 @@ export interface AgentRecord {
109
214
  historyFile?: string;
110
215
  /** Project-relative durable transcript path persisted in the parent session. */
111
216
  transcriptPath?: string;
112
- /** Cleanup function for the output file stream subscription. */
217
+ /**
218
+ * The agent's pi session file, when it was persisted (`persist_session`, or
219
+ * the `rememberAgents` default). Captured so a mention can reopen the
220
+ * conversation after the record itself has been evicted; undefined for an
221
+ * in-memory session, which leaves nothing to reopen.
222
+ */
223
+ sessionFile?: string;
224
+ /** Cleanup function for the optional `.output` stream subscription. */
113
225
  outputCleanup?: () => void;
226
+ /** Cleanup function for the mandatory durable `.pi-subagents` history stream. */
227
+ historyCleanup?: () => void;
114
228
  /**
115
229
  * Lifetime usage breakdown, accumulated via `message_end` events. Survives
116
230
  * compaction. Total = input + output + cacheWrite (cacheRead deliberately
@@ -132,16 +246,63 @@ export interface AgentRecord {
132
246
  isBackground?: boolean;
133
247
  /** Resolved spawn params, captured for UI display. Fixed at spawn time. */
134
248
  invocation?: AgentInvocation;
249
+ /** Nesting depth: top-level subagent = 1. */
250
+ depth?: number;
251
+ /**
252
+ * The validated `StructuredOutput` payload, as canonical JSON.
253
+ *
254
+ * Set only when the spawn asked for a schema. Separate from `result` because
255
+ * `result` is prose for a reader — previewed in the widget, written to the
256
+ * transcript, and appended to with the worktree branch note — and JSON that
257
+ * has been appended to no longer parses.
258
+ */
259
+ structuredJson?: string;
260
+ /** Whether the child needed the extra structured-output prompt. */
261
+ structuredRetried?: boolean;
262
+ /** Parent agent ID for ownership-scoped nested controls. */
263
+ parentAgentId?: string;
264
+ /**
265
+ * The workflow run that owns this child, when a workflow spawned it.
266
+ *
267
+ * Owned the same way a nested child is owned by its parent: filtered out of
268
+ * every top-level surface, and outside the `maxConcurrent` pool. See
269
+ * `isTopLevelAgent`.
270
+ */
271
+ workflowId?: string;
272
+ /** Effective inherited nesting cap for this branch. */
273
+ maxSubagentDepth?: number;
274
+ /**
275
+ * Session id of the root (main) session this branch descends from. Nested
276
+ * spawns inherit it so their transcripts file under the same session
277
+ * directory as their ancestors' instead of the child session's own id.
278
+ */
279
+ rootSessionId?: string;
135
280
  }
136
281
 
282
+ /**
283
+ * What a session reports as its level: pi's `ThinkingLevel` plus the `"off"` a
284
+ * model with thinking disabled reports. Display-only — spawning still takes a
285
+ * `ThinkingLevel`, so this widening cannot leak into an invocation.
286
+ */
287
+ export type EffectiveThinkingLevel = ThinkingLevel | "off";
288
+
137
289
  export interface AgentInvocation {
138
- /** Short display name, e.g. "haiku" — only set when different from parent. */
290
+ /** Short display name for tight rows, e.g. "haiku 4.5". Always set once known. */
139
291
  modelName?: string;
140
- /** Effective model captured from the child session, including inherited models. */
141
- effectiveModelName?: string;
142
- /** Requested/ effective thinking level. */
143
- effectiveThinking?: AgentSession["thinkingLevel"];
144
- thinking?: ThinkingLevel;
292
+ /** Canonical `provider/id`, for surfaces with room to disambiguate providers. */
293
+ modelId?: string;
294
+ /** The level actually in effect, once a session exists to report one. */
295
+ thinking?: EffectiveThinkingLevel;
296
+ /**
297
+ * What the caller asked for, kept only when they did not get it — pi clamped
298
+ * the level to the model's capabilities, or an agent file's frontmatter
299
+ * outranked the parameter (#182). The snapshot exists to answer "did the spawn
300
+ * honor my instructions?" (#62), which it cannot do if the request is lost, so
301
+ * neither `requested*` field is overwritten once set.
302
+ */
303
+ requestedThinking?: EffectiveThinkingLevel;
304
+ /** The caller's `model` parameter, as written, when an agent file's pin won. */
305
+ requestedModel?: string;
145
306
  maxTurns?: number;
146
307
  isolated?: boolean;
147
308
  inheritContext?: boolean;
@@ -158,6 +319,12 @@ export interface NotificationDetails {
158
319
  turnCount: number;
159
320
  maxTurns?: number;
160
321
  totalTokens: number;
322
+ /**
323
+ * Estimated cost in USD, from pi's per-message `usage.cost.total`. Always
324
+ * populated (0 when the model has no pricing); the renderer decides whether
325
+ * to show it, per the `showCost` setting.
326
+ */
327
+ totalCost?: number;
161
328
  durationMs: number;
162
329
  outputFile?: string;
163
330
  error?: string;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * agent-mention.ts — what `@` can address, and the suggestions pi renders for it.
3
+ *
4
+ * A subagent is addressable whether or not it is currently running: a live
5
+ * record is messaged or resumed, an evicted one whose session is still on disk
6
+ * is reopened, and an agent *type* with no instance at all is started. That is
7
+ * the point of the handle — `@explore` means the Explore agent, not "the
8
+ * Explore process that happens to exist right now" — so the roster below unions
9
+ * all three, and the dispatcher and the popup read the same list.
10
+ *
11
+ * Rows are per *agent*, not per handle. An agent given a `name` holds two names
12
+ * (its alias and its type-derived handle) and both resolve, but it lists once,
13
+ * under the alias, with its type moved into the description so the row still
14
+ * says what it is.
15
+ *
16
+ * pi's `CombinedAutocompleteProvider` already owns `@`, where it means "attach a
17
+ * file". Extensions can wrap it (`ctx.ui.addAutocompleteProvider`), so this
18
+ * provider adds the `@` tokens that name an agent and delegates everything else
19
+ * — including all of `applyCompletion`, whose `@`-branch already inserts
20
+ * `item.value` plus a trailing space, which is exactly what a handle needs.
21
+ *
22
+ * Matching mirrors Claude Code: case-insensitive prefix, not fuzzy. What it does
23
+ * NOT mirror is Claude Code dropping files whenever an agent matches. Here `@` is
24
+ * pi's file picker first, and the handles are additive, so a token matching both
25
+ * lists both — agents first. Suppressing on any match sounds narrow and is not:
26
+ * an empty token prefix-matches every handle, so a bare `@` — the gesture people
27
+ * use to browse files — would offer no files at all, and a single letter
28
+ * beginning any handle would do the same.
29
+ *
30
+ * Both halves ship under ONE `prefix`, which is sound because wherever BOTH sides
31
+ * produce rows they measured the same span. pi's `extractAtPrefix` takes the
32
+ * token after the last of `{space, tab, ", ', =}` and keeps it only if it starts
33
+ * with `@`; `MENTION_TRIGGER` matches `@[\w-]*` at the cursor, after start-of-line
34
+ * or `[\s。、?!]`. Where those two disagree, exactly one side answers and there
35
+ * is nothing to merge: `@src/index.ts` and `@"my file` are pi's alone (no handle
36
+ * matches), `=@ex` is pi's alone (`=` is a delimiter to pi, not a boundary to us),
37
+ * and `。@ex` is ours alone (the reverse). A merged response therefore never
38
+ * carries a prefix from one side and an item from the other.
39
+ *
40
+ * Offering never-started types is a deliberate step beyond Claude Code, whose
41
+ * registry holds only live tasks, so an agent you had not launched yet was
42
+ * unaddressable.
43
+ */
44
+
45
+ import type { AutocompleteItem, AutocompleteProvider, AutocompleteSuggestions } from "@earendil-works/pi-tui";
46
+ import type { AgentManager } from "../agent-manager.js";
47
+ import { handleBase, MENTION_TRIGGER } from "../mention.js";
48
+ import type { AgentRecord, AgentTombstone } from "../types.js";
49
+
50
+ /**
51
+ * One thing `@` can address, and what sending to it will do. `typeLabel` is the
52
+ * agent's `display_name`, resolved by the caller: this module stays independent
53
+ * of the type registry, but the popup must agree with FleetView and the widget,
54
+ * which both render the label rather than the raw type.
55
+ */
56
+ export type MentionTarget =
57
+ | { kind: "record"; handle: string; record: AgentRecord; typeLabel: string }
58
+ | { kind: "tombstone"; handle: string; entry: AgentTombstone; typeLabel: string }
59
+ | { kind: "type"; handle: string; type: string; description: string };
60
+
61
+ /** The registry facts the roster needs, so it stays independent of agent-types. */
62
+ export type TypeInfo = { name: string; description: string };
63
+
64
+ /**
65
+ * Everything `@` can reach, in the order the popup lists it: steerable agents
66
+ * first, then the other live ones earliest-launched, then agent types with no
67
+ * live instance. A type whose handle a record already holds is omitted — that
68
+ * name addresses the existing agent, which is what makes `@explore` mean
69
+ * "message the one that's running" and only otherwise "start one".
70
+ */
71
+ export function mentionRoster(
72
+ manager: AgentManager,
73
+ types: readonly TypeInfo[],
74
+ // Identity by default: a caller with no registry to consult gets the raw
75
+ // type, which is also what `getConfig` falls back to when no label is set.
76
+ displayNameOf: (type: string) => string = type => type,
77
+ ): MentionTarget[] {
78
+ const live = (r: AgentRecord) => r.status === "running" || r.status === "queued";
79
+ const records = manager.listAgents()
80
+ .filter(r => r.handle !== undefined && r.parentAgentId === undefined)
81
+ .sort((a, b) => (Number(live(b)) - Number(live(a))) || (a.startedAt - b.startedAt));
82
+
83
+ const taken = new Set<string>();
84
+ const targets: MentionTarget[] = [];
85
+
86
+ // One row per agent, not per handle. An aliased agent lists under its alias
87
+ // only — both names resolve, but showing two rows for one agent reads as two
88
+ // agents. The type handle stays addressable whether or not it is listed.
89
+ for (const record of records) {
90
+ const handle = record.alias ?? record.handle!;
91
+ taken.add(handle.toLowerCase());
92
+ if (record.handle) taken.add(record.handle.toLowerCase());
93
+ targets.push({ kind: "record", handle, record, typeLabel: displayNameOf(record.type) });
94
+ }
95
+
96
+ // Then agents that are gone but whose conversation can be reopened. After the
97
+ // live ones: a running agent is the likelier target, and this keeps the
98
+ // ordering "what exists now, then what can be brought back, then what can be
99
+ // started".
100
+ for (const entry of manager.listTombstones()) {
101
+ const handle = entry.alias ?? entry.handle;
102
+ if (taken.has(handle.toLowerCase())) continue;
103
+ taken.add(handle.toLowerCase());
104
+ taken.add(entry.handle.toLowerCase());
105
+ targets.push({ kind: "tombstone", handle, entry, typeLabel: displayNameOf(entry.type) });
106
+ }
107
+
108
+ for (const type of types) {
109
+ const handle = handleBase(type.name);
110
+ if (taken.has(handle)) continue;
111
+ taken.add(handle);
112
+ targets.push({ kind: "type", handle, type: type.name, description: type.description });
113
+ }
114
+ return targets;
115
+ }
116
+
117
+ export function createMentionProvider(
118
+ current: AutocompleteProvider,
119
+ roster: () => MentionTarget[],
120
+ isEnabled: () => boolean,
121
+ ): AutocompleteProvider {
122
+ // One warning per provider, not per keystroke: `getSuggestions` runs on every
123
+ // character typed after `@`, so an unguarded log would bury the terminal in
124
+ // the time it takes to finish a word.
125
+ let warnedInnerFailure = false;
126
+ return {
127
+ // Only `@` — the contract is "characters that should naturally trigger
128
+ // THIS provider", and pi unions each wrapper's own set onto the outermost
129
+ // one itself (interactive-mode.js:432), so re-declaring the wrapped
130
+ // provider's characters here would both misreport us and duplicate that.
131
+ triggerCharacters: ["@"],
132
+
133
+ async getSuggestions(lines, cursorLine, cursorCol, options): Promise<AutocompleteSuggestions | null> {
134
+ const mine = isEnabled() ? mentionItems(roster(), lines[cursorLine] ?? "", cursorCol) : null;
135
+ // Asked unconditionally: pi owns `@` and must keep answering for it even
136
+ // when a handle matches too. That is the same work vanilla pi does on any
137
+ // `@` keystroke — a capped `fd` search, or nothing at all when the host
138
+ // configured no `fd` path — but we now do it on tokens we used to answer
139
+ // alone, so it must not be able to take the popup down with it. The
140
+ // wrapped provider is not always pi's: another extension may sit inside
141
+ // us, and before this it was never called for a token naming an agent.
142
+ // try/catch, not `.catch()`: a provider that throws SYNCHRONOUSLY never
143
+ // returns the promise a `.catch()` would attach to, and the throw escapes
144
+ // this method as a rejection — which pi does not handle either
145
+ // (components/editor.js:1892 awaits with no catch of its own).
146
+ let theirs: AutocompleteSuggestions | null = null;
147
+ try {
148
+ theirs = await current.getSuggestions(lines, cursorLine, cursorCol, options);
149
+ } catch (err) {
150
+ // Safe to treat as "no files": pi discards any response whose request is
151
+ // no longer current, so an aborted search that surfaces as a rejection
152
+ // cannot leave a stale popup behind (`isAutocompleteRequestCurrent`).
153
+ // Warned rather than swallowed outright — the failure is invisible in
154
+ // the popup, and the same `console.warn` channel already carries this
155
+ // extension's other non-fatal failures.
156
+ if (!warnedInnerFailure) {
157
+ warnedInnerFailure = true;
158
+ console.warn("[pi-subagents] the autocomplete provider below us failed; showing agent rows only:", err);
159
+ }
160
+ theirs = null;
161
+ }
162
+ if (!mine) return theirs;
163
+ if (!theirs) return mine;
164
+ // Agents first: there are a handful of them against pi's 20 file rows, and
165
+ // a handle buried under fuzzy path matches is a handle nobody finds. The
166
+ // prefix is ours by the span argument in the header — identical to pi's
167
+ // whenever both sides have something to say.
168
+ return { items: [...mine.items, ...theirs.items], prefix: mine.prefix };
169
+ },
170
+
171
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
172
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
173
+ },
174
+
175
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
176
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
177
+ },
178
+ };
179
+ }
180
+
181
+ /** Suggestions for the `@…` token under the cursor, or null when it names no agent. */
182
+ function mentionItems(roster: MentionTarget[], line: string, cursorCol: number): AutocompleteSuggestions | null {
183
+ const match = MENTION_TRIGGER.exec(line.slice(0, cursorCol));
184
+ if (!match) return null;
185
+
186
+ const typed = match[2].toLowerCase();
187
+ const items: AutocompleteItem[] = [];
188
+ for (const target of roster) {
189
+ if (!target.handle.toLowerCase().startsWith(typed)) continue;
190
+ items.push({ value: `@${target.handle}`, label: `@${target.handle}`, description: describeTarget(target) });
191
+ }
192
+ return items.length > 0 ? { items, prefix: `@${match[2]}` } : null;
193
+ }
194
+
195
+ /** Name the action that will actually happen, so the list never mispromises. */
196
+ function describeTarget(target: MentionTarget): string {
197
+ if (target.kind === "type") return `start agent · ${summarize(target.description)}`;
198
+ if (target.kind === "tombstone") {
199
+ // No status: the record is gone, and "completed" would imply one is still
200
+ // being tracked. The type carries the identity the handle may not.
201
+ return `resume · ${target.typeLabel} · ${target.entry.description}`;
202
+ }
203
+ const { status, description, alias } = target.record;
204
+ const action = status === "running" || status === "queued" ? "send message" : "resume";
205
+ // A row listed under its alias has lost the type its handle would have shown,
206
+ // so name it — `@auth-audit` alone says nothing about what the agent is.
207
+ // A type-derived row already reads as its type and would just repeat itself.
208
+ const identity = alias ? `${target.typeLabel} · ` : "";
209
+ return `${action} · ${identity}${status} · ${description}`;
210
+ }
211
+
212
+ /** First sentence of an agent description, clipped — these run to paragraphs. */
213
+ function summarize(description: string): string {
214
+ const first = (description.match(/^.*?[.!?](?=\s|$)/s)?.[0] ?? description).replace(/\s+/g, " ").trim();
215
+ return first.length > 60 ? `${first.slice(0, 59).trimEnd()}…` : first;
216
+ }