@timmyjl12/pi-subagents 0.0.0-stage → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +18 -0
  9. package/dist/active-agents-prompt.js +34 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +123 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,230 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { type ModelRegistry, resolveModel } from "./model-resolver.js";
3
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
4
+
5
+ /**
6
+ * Agent pins are authoritative: a qualified `provider/id` pin resolves exactly
7
+ * first, then — via model-resolver's normalization — to the same model id on
8
+ * another AVAILABLE provider. Bare shorthand stays fuzzy through resolveModel.
9
+ *
10
+ * The third step differs by authorship. Built-in default agents (`isDefault`,
11
+ * `source: "default"`) fall back to the parent model with a visible notice:
12
+ * their pins name a preferred provider, not a hard requirement, and refusing
13
+ * the spawn would brick Explore/Plan for anyone without that provider. A
14
+ * user-authored `.md` pin stays strict and never substitutes the parent — the
15
+ * author's explicit choice must not be silently reinterpreted.
16
+ *
17
+ * Returns the resolved model, or — for a strict failure — an error string.
18
+ * A built-in fallback returns `{ model, notice }` so the caller can surface
19
+ * what was substituted; check `typeof result === "string"` for failure first.
20
+ */
21
+ export interface PinFallback {
22
+ pinFallback: true;
23
+ /** The parent model, or undefined to let the session pick its default. */
24
+ model: unknown;
25
+ notice: string;
26
+ }
27
+ export type PinnedModelResult = ReturnType<typeof resolveModel> | PinFallback;
28
+
29
+ /** Narrow a resolvePinnedModel result to the built-in parent-model fallback. */
30
+ export function isPinFallback(result: unknown): result is PinFallback {
31
+ return typeof result === "object" && result !== null && (result as { pinFallback?: unknown }).pinFallback === true;
32
+ }
33
+
34
+ export function resolvePinnedModel(
35
+ input: string,
36
+ registry: Pick<ModelRegistry, "find"> & Partial<Omit<ModelRegistry, "find">>,
37
+ opts?: { isBuiltInDefault?: boolean; parentModel?: unknown },
38
+ ): PinnedModelResult {
39
+ const available = registry.getAvailable?.() ?? registry.getAll?.();
40
+ if (input.trim() && !input.includes("/")) {
41
+ return resolveModel(input, { find: (provider, id) => registry.find(provider, id), getAll: () => available ?? [] });
42
+ }
43
+ const slash = input.indexOf("/");
44
+ // Legacy registries may expose only exact lookup; never widen to a different id.
45
+ const model = available ? available.find(model => `${model.provider}/${model.id}` === input)
46
+ : slash > 0 ? registry.find(input.slice(0, slash), input.slice(slash + 1)) : undefined;
47
+ if (model && `${model.provider}/${model.id}` === input) return model;
48
+ // Same model id on another available provider (model-resolver normalization:
49
+ // case/dot-dash/date-suffix tolerant). Preferred-provider pin, not a rename:
50
+ // only the provider may differ, never the id.
51
+ if (slash > 0 && available) {
52
+ const wantedId = input.slice(slash + 1);
53
+ const cross = resolveModel(wantedId, {
54
+ find: (provider, id) => registry.find(provider, id),
55
+ getAll: () => available,
56
+ });
57
+ if (typeof cross !== "string" && cross) {
58
+ const crossKey = `${cross.provider}/${cross.id}`;
59
+ const found = available.find(m => `${m.provider}/${m.id}` === crossKey);
60
+ if (found && normalizeModelId(found.id) === normalizeModelId(wantedId)) return found;
61
+ }
62
+ }
63
+ if (opts?.isBuiltInDefault) {
64
+ const target = opts.parentModel ? "the parent model" : "the session default model";
65
+ return {
66
+ pinFallback: true,
67
+ model: opts.parentModel,
68
+ notice: `Pinned model "${input}" is not available; running with ${target} instead.`,
69
+ };
70
+ }
71
+ return `Pinned model not available: "${input}". Configure/authenticate this exact model or update the agent's model pin; the parent model will not be substituted.`;
72
+ }
73
+
74
+ /** Normalize a model id for cross-provider comparison (mirrors model-resolver). */
75
+ function normalizeModelId(id: string): string {
76
+ return id.toLowerCase().replace(/\./g, "-").replace(/-\d{8}$/, "");
77
+ }
78
+
79
+ /**
80
+ * The model-facing `isolation` parameter, shared by the `Agent` tool and the
81
+ * nested delegation tool so the two cannot drift.
82
+ *
83
+ * Shape matters more than wording here. As a single-value optional literal,
84
+ * models that fill every optional parameter — the transcript on #231 shows one
85
+ * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
86
+ * had only `"worktree"` available to fill it with, and kept spawning worktrees
87
+ * across three turns while their own reasoning said to omit the field. Every
88
+ * other optional parameter has an inert filler; this one did not. `"off"` is
89
+ * listed first and described as the default so the harmless value is the
90
+ * obvious one to reach for.
91
+ *
92
+ * The wording tracks Claude Code's own `isolation` parameter, whose phrasing
93
+ * models have the most exposure to: one description on the union rather than
94
+ * per-value ones, opening "Isolation mode.", then a sentence per value in
95
+ * schema order, each with its caveats in a trailing parenthetical. Two clauses
96
+ * are ours, because our shape is not theirs — `"off"` has no counterpart there
97
+ * (their enum is `worktree | remote`, so both of their values do something),
98
+ * and neither does the uncommitted-work warning, which is the specific trap
99
+ * #231 fell into. Deliberately absent is any "only use a worktree when…"
100
+ * restriction: Claude Code's `Agent` tool states the capability and stops, and
101
+ * a second legal value is what lets a model decline one, not being told to.
102
+ */
103
+ const isolationParamShape = {
104
+ isolation: Type.Optional(
105
+ Type.Union([Type.Literal("off"), Type.Literal("worktree")], {
106
+ description:
107
+ '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).',
108
+ }),
109
+ ),
110
+ };
111
+
112
+ /**
113
+ * Build the `isolation` parameter for a tool schema, or nothing when the
114
+ * project disabled worktrees (`worktreeIsolation: false`).
115
+ *
116
+ * Dropping the field beats accepting it and quietly downgrading. The setting is
117
+ * for a project whose model passes `"worktree"` on *every* call, so a
118
+ * per-result "isolation was disabled" note would be noise on every result and
119
+ * would keep raising the salience of a capability that isn't there. With no
120
+ * field there is nothing to pass, nothing to drop, and nothing to explain — the
121
+ * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
122
+ * cost. The resolver gate and the `agent-manager` check still cover the paths a
123
+ * schema can't reach: agent files, the scheduler, and cross-extension RPC.
124
+ *
125
+ * Like `scheduleParam`, this is read once at tool registration — flipping the
126
+ * setting needs a new pi session for the schema to change.
127
+ */
128
+ export function isolationParam(enabled: boolean): Partial<typeof isolationParamShape> {
129
+ return enabled ? isolationParamShape : {};
130
+ }
131
+
132
+ interface AgentInvocationParams {
133
+ model?: string;
134
+ thinking?: string;
135
+ max_turns?: number;
136
+ run_in_background?: boolean;
137
+ inherit_context?: boolean;
138
+ isolated?: boolean;
139
+ /**
140
+ * Untyped on purpose. Both tool schemas now build this field conditionally
141
+ * and spread it, which erases TypeBox's literal inference to `unknown` (the
142
+ * `schedule` param has the same shape). The resolver below narrows by
143
+ * comparison rather than trusting the declaration, which also makes it safe
144
+ * for the cross-extension RPC path, where options arrive unvalidated.
145
+ */
146
+ isolation?: unknown;
147
+ }
148
+
149
+ interface ResolveOptions {
150
+ /**
151
+ * Whether worktree isolation is permitted at all. False when the project set
152
+ * `worktreeIsolation: false`, which drops a requested worktree rather than
153
+ * failing the call: the fail-loud precedent covers spawns that *cannot* work,
154
+ * while this one is the user opting out, and throwing would break exactly the
155
+ * calls the `"off"` value exists to tolerate. Defaults to allowed.
156
+ */
157
+ worktreeAllowed?: boolean;
158
+ /**
159
+ * What an unqualified spawn means — neither the call nor the agent file said.
160
+ *
161
+ * Top-level callers pass the `backgroundByDefault` setting (default `true`,
162
+ * following Claude Code). Nested callers pass `false` unconditionally: a
163
+ * detached child is killed by `abortOwnedChildren` when its parent settles
164
+ * and has no notification path of its own, so backgrounding one loses its
165
+ * work. Both call sites pass it explicitly; the `false` fallback only covers
166
+ * a caller that supplies no options at all, which in-tree means tests.
167
+ */
168
+ defaultRunInBackground?: boolean;
169
+ }
170
+
171
+ export function resolveAgentInvocationConfig(
172
+ agentConfig: AgentConfig | undefined,
173
+ params: AgentInvocationParams,
174
+ opts?: ResolveOptions,
175
+ ): {
176
+ modelInput?: string;
177
+ modelFromParams: boolean;
178
+ thinking?: ThinkingLevel;
179
+ maxTurns?: number;
180
+ inheritContext: boolean;
181
+ runInBackground: boolean;
182
+ isolated: boolean;
183
+ isolation?: IsolationMode;
184
+ /**
185
+ * Caller parameters an agent file's frontmatter outranked, so the surfaces can
186
+ * say "(asked X)" instead of presenting the effective value as the requested
187
+ * one (#182). Populated only where both sides named something and they
188
+ * disagree — a caller who asked for what they got was still honored.
189
+ *
190
+ * `max_turns` is deliberately absent: no surface renders a requested-vs-
191
+ * effective turn limit, so recording one would be dead data.
192
+ */
193
+ overridden?: { thinking?: ThinkingLevel; model?: string };
194
+ } {
195
+ // Precedence first, collapse second — reversing these loses the veto, since
196
+ // an agent file's "off" only outranks a caller's "worktree" while it is still
197
+ // a value. Everything downstream then sees "worktree" or nothing at all.
198
+ const requested = agentConfig?.isolation ?? params.isolation;
199
+ const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : undefined;
200
+
201
+ const overriddenThinking = agentConfig?.thinking != null && params.thinking != null
202
+ && agentConfig.thinking !== params.thinking
203
+ ? params.thinking as ThinkingLevel
204
+ : undefined;
205
+ const overriddenModel = agentConfig?.model != null && params.model != null
206
+ && agentConfig.model !== params.model
207
+ ? params.model
208
+ : undefined;
209
+
210
+ return {
211
+ modelInput: agentConfig?.model ?? params.model,
212
+ modelFromParams: agentConfig?.model == null && params.model != null,
213
+ thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
214
+ maxTurns: agentConfig?.maxTurns ?? params.max_turns,
215
+ inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
216
+ runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
217
+ isolated: agentConfig?.isolated ?? params.isolated ?? false,
218
+ isolation,
219
+ // Undefined rather than an empty object when nothing was overridden: callers
220
+ // spread this into the invocation snapshot, and an always-present key would
221
+ // put `requestedThinking: undefined` on every record.
222
+ overridden: overriddenThinking || overriddenModel
223
+ ? { thinking: overriddenThinking, model: overriddenModel }
224
+ : undefined,
225
+ };
226
+ }
227
+
228
+ export function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined {
229
+ return runInBackground ? defaultJoinMode : undefined;
230
+ }
package/src/memory.ts ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → getAgentDir()/agent-memory/{agent-name}/ (default ~/.pi/agent/agent-memory/, honors $PI_CODING_AGENT_DIR)
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ *
9
+ * The user scope previously hardcoded ~/.pi/agent-memory/. That legacy location
10
+ * is still honored (read + write) when it exists and the new location doesn't,
11
+ * so existing memories aren't orphaned.
12
+ */
13
+
14
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join, } from "node:path";
17
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
18
+ import type { MemoryScope } from "./types.js";
19
+
20
+ /** Maximum lines to read from MEMORY.md */
21
+ const MAX_MEMORY_LINES = 200;
22
+
23
+ /**
24
+ * Returns true if a name contains characters not allowed in agent/skill names.
25
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
26
+ */
27
+ export function isUnsafeName(name: string): boolean {
28
+ if (!name || name.length > 128) return true;
29
+ return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
30
+ }
31
+
32
+ /**
33
+ * Returns true if the given path is a symlink (defense against symlink attacks).
34
+ */
35
+ export function isSymlink(filePath: string): boolean {
36
+ try {
37
+ return lstatSync(filePath).isSymbolicLink();
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Safely read a file, rejecting symlinks.
45
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
46
+ */
47
+ export function safeReadFile(filePath: string): string | undefined {
48
+ if (!existsSync(filePath)) return undefined;
49
+ if (isSymlink(filePath)) return undefined;
50
+ try {
51
+ return readFileSync(filePath, "utf-8");
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Resolve the memory directory path for a given agent + scope + cwd.
59
+ * Throws if agentName contains path traversal characters.
60
+ */
61
+ export function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string {
62
+ if (isUnsafeName(agentName)) {
63
+ throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
64
+ }
65
+ switch (scope) {
66
+ case "user": {
67
+ const current = join(getAgentDir(), "agent-memory", agentName);
68
+ // Legacy location from when this path was hardcoded. Keep using it if it
69
+ // already holds this agent's memory and the new location hasn't been
70
+ // created yet — otherwise existing memories would be silently orphaned.
71
+ const legacy = join(homedir(), ".pi", "agent-memory", agentName);
72
+ if (!existsSync(current) && existsSync(legacy) && !isSymlink(legacy)) {
73
+ return legacy;
74
+ }
75
+ return current;
76
+ }
77
+ case "project":
78
+ return join(cwd, ".pi", "agent-memory", agentName);
79
+ case "local":
80
+ return join(cwd, ".pi", "agent-memory-local", agentName);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Ensure the memory directory exists, creating it if needed.
86
+ * Refuses to create directories if any component in the path is a symlink
87
+ * to prevent symlink-based directory traversal attacks.
88
+ */
89
+ export function ensureMemoryDir(memoryDir: string): void {
90
+ // If the directory already exists, verify it's not a symlink
91
+ if (existsSync(memoryDir)) {
92
+ if (isSymlink(memoryDir)) {
93
+ throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
94
+ }
95
+ return;
96
+ }
97
+ mkdirSync(memoryDir, { recursive: true });
98
+ }
99
+
100
+ /**
101
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
102
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
103
+ */
104
+ export function readMemoryIndex(memoryDir: string): string | undefined {
105
+ // Reject symlinked memory directories
106
+ if (isSymlink(memoryDir)) return undefined;
107
+
108
+ const memoryFile = join(memoryDir, "MEMORY.md");
109
+ const content = safeReadFile(memoryFile);
110
+ if (content === undefined) return undefined;
111
+
112
+ const lines = content.split("\n");
113
+ if (lines.length > MAX_MEMORY_LINES) {
114
+ return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
115
+ }
116
+ return content;
117
+ }
118
+
119
+ /**
120
+ * Build the memory block to inject into the agent's system prompt.
121
+ * Also ensures the memory directory exists (creates it if needed).
122
+ */
123
+ export function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
124
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
125
+ // Create the memory directory so the agent can immediately write to it
126
+ ensureMemoryDir(memoryDir);
127
+
128
+ const existingMemory = readMemoryIndex(memoryDir);
129
+
130
+ const header = `# Agent Memory
131
+
132
+ You have a persistent memory directory at: ${memoryDir}/
133
+ Memory scope: ${scope}
134
+
135
+ This memory persists across sessions. Use it to build up knowledge over time.`;
136
+
137
+ const memoryContent = existingMemory
138
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
139
+ : `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
140
+
141
+ const instructions = `
142
+
143
+ ## Memory Instructions
144
+ - MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
145
+ - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
146
+ - Each memory file should use this frontmatter format:
147
+ \`\`\`markdown
148
+ ---
149
+ name: <memory name>
150
+ description: <one-line description>
151
+ type: <user|feedback|project|reference>
152
+ ---
153
+ <memory content>
154
+ \`\`\`
155
+ - Update or remove memories that become outdated. Check for existing memories before creating duplicates.
156
+ - You have Read, Write, and Edit tools available for managing memory files.`;
157
+
158
+ return header + memoryContent + instructions;
159
+ }
160
+
161
+ /**
162
+ * Build a read-only memory block for agents that lack write/edit tools.
163
+ * Does NOT create the memory directory — agents can only consume existing memory.
164
+ */
165
+ export function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
166
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
167
+ const existingMemory = readMemoryIndex(memoryDir);
168
+
169
+ const header = `# Agent Memory (read-only)
170
+
171
+ Memory scope: ${scope}
172
+ You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
173
+
174
+ const memoryContent = existingMemory
175
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
176
+ : `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
177
+
178
+ return header + memoryContent;
179
+ }
@@ -0,0 +1,221 @@
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
+ DefaultResourceLoader,
69
+ type ExtensionContext,
70
+ getAgentDir,
71
+ SessionManager,
72
+ type ToolDefinition,
73
+ } from "@earendil-works/pi-coding-agent";
74
+ import { runAsSubagentProcess, runInChildSessionContext } from "./child-context.js";
75
+ import { agentMentionReminder } from "./mention.js";
76
+ import type { SubagentType, ThinkingLevel } from "./types.js";
77
+
78
+ export interface MentionCloneOptions {
79
+ /** The MAIN session's context — what the spawn is attributed to, and the
80
+ * source of both the conversation and the live system prompt. */
81
+ ctx: ExtensionContext;
82
+ /** Agent type the handle resolved to. */
83
+ type: SubagentType;
84
+ /** What the user typed after the handle. */
85
+ message: string;
86
+ /** The registered `Agent` tool, reused so the spawn is an ordinary one. */
87
+ agentTool: ToolDefinition;
88
+ }
89
+
90
+ export interface MentionCloneResult {
91
+ /** True once the clone actually called `Agent`. */
92
+ spawned: boolean;
93
+ /** Why not, when it didn't. Absent on success. */
94
+ error?: string;
95
+ }
96
+
97
+ /**
98
+ * Fork the conversation, let the copy make the tool call, throw the copy away.
99
+ * Never rejects: a clone that cannot run is reported so the caller can fall
100
+ * back to starting the agent directly.
101
+ */
102
+ export async function runMentionClone(opts: MentionCloneOptions): Promise<MentionCloneResult> {
103
+ const { ctx, type, message, agentTool } = opts;
104
+
105
+ let spawned = false;
106
+ const cloneAgentTool: ToolDefinition = {
107
+ ...agentTool,
108
+ execute: (_cloneToolCallId, params, signal, onUpdate, _cloneCtx) => {
109
+ // One spawn per mention. The clone has a single tool and every reason to
110
+ // stop after using it, but a model that decides to "also" launch a second
111
+ // agent would do it where nobody can see and nobody asked.
112
+ if (spawned) {
113
+ return Promise.resolve({
114
+ content: [{ type: "text" as const, text: "Already started an agent for this mention. Stop here." }],
115
+ details: undefined,
116
+ isError: true,
117
+ });
118
+ }
119
+ spawned = true;
120
+ // undefined tool-call id + the main ctx: see the header. Background is
121
+ // forced rather than left to the clone: `run_in_background` defaults to
122
+ // false, and a foreground agent answers through its TOOL RESULT — which
123
+ // here is delivered into a session that is disposed moments later, so the
124
+ // agent would run, appear in the widget and the fleet, and reach nobody.
125
+ return agentTool.execute(
126
+ undefined as never,
127
+ { ...(params as Record<string, unknown>), run_in_background: true } as typeof params,
128
+ signal,
129
+ onUpdate,
130
+ // Pi 1.1 types tool calls with ExtensionToolContext (adds `tools` /
131
+ // `executeTool`). The Agent tool uses neither, and the clone's own tool
132
+ // context belongs to a session disposed moments later, so the main ctx
133
+ // is still the right one to hand over.
134
+ ctx as Parameters<typeof agentTool.execute>[4],
135
+ );
136
+ },
137
+ };
138
+
139
+ let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;
140
+ try {
141
+ // Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
142
+ // agent-runner.ts carries the same shim for the same reason — pass both so
143
+ // the clone keeps the parent's providers across the supported range.
144
+ const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: unknown }).runtime;
145
+ // The conversation as the main session resolves it: compaction applied,
146
+ // branch summaries substituted.
147
+ const conversation = buildSessionContext(
148
+ ctx.sessionManager.getEntries(),
149
+ ctx.sessionManager.getLeafId(),
150
+ );
151
+ // Pi 0.82.0 added this; below it the field is absent and the clone takes
152
+ // the settings level instead, which is what a session that never ran
153
+ // `/think` is on anyway. Same shim shape as `modelRuntime` below.
154
+ const thinkingLevel = (ctx as { thinkingLevel?: ThinkingLevel }).thinkingLevel;
155
+ // Env half of the child marker as well: the clone loads the default
156
+ // extension set in-process, and advisor-style extensions decide their
157
+ // subagent default from PI_SUBAGENT_CHILD, not our AsyncLocalStorage.
158
+ const created = await runAsSubagentProcess(() => runInChildSessionContext(async () => {
159
+ const systemPrompt = ctx.getSystemPrompt?.();
160
+ const resourceLoader = new DefaultResourceLoader({
161
+ cwd: ctx.cwd,
162
+ agentDir: getAgentDir(),
163
+ systemPromptOverride: (base) => systemPrompt || base,
164
+ // The loader override is only a prefix: Pi still adds cwd and context
165
+ // sections. The turn override sends the exact live parent prompt,
166
+ // including its per-turn extensions, instead of rebuilding it again.
167
+ extensionFactories: [(pi) => {
168
+ pi.on("before_agent_start", () => systemPrompt ? { systemPrompt } : undefined);
169
+ }],
170
+ });
171
+ // Loading extensions must stay in the child context too, or this clone
172
+ // could activate a second top-level subagent manager.
173
+ await resourceLoader.reload();
174
+ return createAgentSession({
175
+ cwd: ctx.cwd,
176
+ resourceLoader,
177
+ // Nothing about the copy is worth persisting, and an in-memory manager
178
+ // is also what keeps the real session untouched. Since Pi 0.87 the
179
+ // SessionManager is canonical for request history, so the clone is
180
+ // seeded with the parent's active branch (root to leaf, compaction and
181
+ // branch-summary entries included). Older Pi ignores the entries
182
+ // argument; the push below covers it.
183
+ sessionManager: (SessionManager.inMemory as (
184
+ cwd?: string, options?: undefined, entries?: unknown[],
185
+ ) => SessionManager)(ctx.cwd, undefined, ctx.sessionManager.getBranch()),
186
+ model: ctx.model as Model<never> | undefined,
187
+ ...(thinkingLevel && { thinkingLevel }),
188
+ modelRegistry: ctx.modelRegistry,
189
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime as never }),
190
+ // An allowlist naming exactly the clone's own tool. NOT `noTools:
191
+ // "all"`, whose doc comment ("start with no tools enabled") reads like
192
+ // it spares custom tools and does not: it resolves to an EMPTY
193
+ // allowlist, and `isAllowedTool` then drops every tool from the
194
+ // registry — the custom one included. The clone would be prompted with
195
+ // nothing to call, answer in prose, and every mention would fall
196
+ // through to the direct start with a warning. Same idiom as
197
+ // agent-runner's `tools: sessionTools` beside its nested `customTools`.
198
+ tools: [cloneAgentTool.name],
199
+ customTools: [cloneAgentTool],
200
+ } as Parameters<typeof createAgentSession>[0]);
201
+ }));
202
+ session = created.session;
203
+
204
+ // Pi < 0.87 builds requests from agent state rather than the session
205
+ // manager. Pushed rather than assigned so the array the session was built
206
+ // around stays the one it goes on using.
207
+ if (session.agent.state.messages.length === 0) session.agent.state.messages.push(...conversation.messages);
208
+
209
+ // User text first, reminder after — the order Claude Code's attachment
210
+ // renderer produces, where the reminder trails the message it is about.
211
+ await session.prompt(`${message}\n\n${agentMentionReminder(type)}`);
212
+ } catch (err) {
213
+ return { spawned, error: err instanceof Error ? err.message : String(err) };
214
+ } finally {
215
+ session?.dispose?.();
216
+ }
217
+
218
+ return spawned
219
+ ? { spawned: true }
220
+ : { spawned: false, error: "the conversation clone did not start it" };
221
+ }