@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  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 +40 -0
  9. package/dist/active-agents-prompt.js +98 -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 +131 -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 +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,164 @@
1
+ import { type ModelRegistry, resolveModel } from "./model-resolver.ts";
2
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.ts";
3
+ /**
4
+ * Agent pins are authoritative: a qualified `provider/id` pin resolves exactly
5
+ * first, then — via model-resolver's normalization — to the same model id on
6
+ * another AVAILABLE provider. Bare shorthand stays fuzzy through resolveModel.
7
+ *
8
+ * The third step differs by authorship. Built-in default agents (`isDefault`,
9
+ * `source: "default"`) fall back to the parent model with a visible notice:
10
+ * their pins name a preferred provider, not a hard requirement, and refusing
11
+ * the spawn would brick Explore/Plan for anyone without that provider. A
12
+ * user-authored `.md` pin stays strict and never substitutes the parent — the
13
+ * author's explicit choice must not be silently reinterpreted.
14
+ *
15
+ * Returns the resolved model, or — for a strict failure — an error string.
16
+ * A built-in fallback returns `{ model, notice }` so the caller can surface
17
+ * what was substituted; check `typeof result === "string"` for failure first.
18
+ */
19
+ export interface PinFallback {
20
+ pinFallback: true;
21
+ /** The parent model, or undefined to let the session pick its default. */
22
+ model: unknown;
23
+ notice: string;
24
+ }
25
+ export type PinnedModelResult = ReturnType<typeof resolveModel> | PinFallback;
26
+ /** Narrow a resolvePinnedModel result to the built-in parent-model fallback. */
27
+ export declare function isPinFallback(result: unknown): result is PinFallback;
28
+ export declare function resolvePinnedModel(input: string, registry: Pick<ModelRegistry, "find"> & Partial<Omit<ModelRegistry, "find">>, opts?: {
29
+ isBuiltInDefault?: boolean;
30
+ parentModel?: unknown;
31
+ }): PinnedModelResult;
32
+ /**
33
+ * The model-facing `isolation` parameter, shared by the `Agent` tool and the
34
+ * nested delegation tool so the two cannot drift.
35
+ *
36
+ * Shape matters more than wording here. As a single-value optional literal,
37
+ * models that fill every optional parameter — the transcript on #231 shows one
38
+ * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
39
+ * had only `"worktree"` available to fill it with, and kept spawning worktrees
40
+ * across three turns while their own reasoning said to omit the field. Every
41
+ * other optional parameter has an inert filler; this one did not. `"off"` is
42
+ * listed first and described as the default so the harmless value is the
43
+ * obvious one to reach for.
44
+ *
45
+ * The wording tracks Claude Code's own `isolation` parameter, whose phrasing
46
+ * models have the most exposure to: one description on the union rather than
47
+ * per-value ones, opening "Isolation mode.", then a sentence per value in
48
+ * schema order, each with its caveats in a trailing parenthetical. Two clauses
49
+ * are ours, because our shape is not theirs — `"off"` has no counterpart there
50
+ * (their enum is `worktree | remote`, so both of their values do something),
51
+ * and neither does the uncommitted-work warning, which is the specific trap
52
+ * #231 fell into. Deliberately absent is any "only use a worktree when…"
53
+ * restriction: Claude Code's `Agent` tool states the capability and stops, and
54
+ * a second legal value is what lets a model decline one, not being told to.
55
+ */
56
+ declare const isolationParamShape: {
57
+ isolation: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"off">, import("@sinclair/typebox").TLiteral<"worktree">]>>;
58
+ };
59
+ /**
60
+ * Build the `isolation` parameter for a tool schema, or nothing when the
61
+ * project disabled worktrees (`worktreeIsolation: false`).
62
+ *
63
+ * Dropping the field beats accepting it and quietly downgrading. The setting is
64
+ * for a project whose model passes `"worktree"` on *every* call, so a
65
+ * per-result "isolation was disabled" note would be noise on every result and
66
+ * would keep raising the salience of a capability that isn't there. With no
67
+ * field there is nothing to pass, nothing to drop, and nothing to explain — the
68
+ * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
69
+ * cost. The resolver gate and the `agent-manager` check still cover the paths a
70
+ * schema can't reach: agent files, the scheduler, and cross-extension RPC.
71
+ *
72
+ * Like `scheduleParam`, this is read once at tool registration — flipping the
73
+ * setting needs a new pi session for the schema to change.
74
+ */
75
+ export declare function isolationParam(enabled: boolean): Partial<typeof isolationParamShape>;
76
+ /**
77
+ * The model-facing `max_turns` parameter, shared by the top-level `Agent` tool
78
+ * and the nested delegation tool.
79
+ *
80
+ * Like `isolationParam`, this is a `Partial` shape meant to be spread into a
81
+ * `Type.Object`: when caller caps are disabled the field is omitted entirely,
82
+ * so the model is never told a knob exists that the runtime would ignore. The
83
+ * resolver gate and the RPC filter still cover calls that bypass schema
84
+ * validation.
85
+ */
86
+ declare const maxTurnsParamShape: {
87
+ max_turns: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
88
+ };
89
+ /** Build the `max_turns` parameter for a tool schema, or nothing when caller caps are disabled. */
90
+ export declare function maxTurnsParam(enabled: boolean): Partial<typeof maxTurnsParamShape>;
91
+ interface AgentInvocationParams {
92
+ model?: string;
93
+ thinking?: string;
94
+ /**
95
+ * Untyped for the same reason as `isolation` below: the conditional schema
96
+ * spread erases TypeBox's numeric inference. The resolver narrows by runtime
97
+ * type rather than trusting the declaration, which also keeps the
98
+ * unvalidated RPC path safe.
99
+ */
100
+ max_turns?: unknown;
101
+ run_in_background?: boolean;
102
+ inherit_context?: boolean;
103
+ isolated?: boolean;
104
+ /**
105
+ * Untyped on purpose. Both tool schemas now build this field conditionally
106
+ * and spread it, which erases TypeBox's literal inference to `unknown` (the
107
+ * `schedule` param has the same shape). The resolver below narrows by
108
+ * comparison rather than trusting the declaration, which also makes it safe
109
+ * for the cross-extension RPC path, where options arrive unvalidated.
110
+ */
111
+ isolation?: unknown;
112
+ }
113
+ interface ResolveOptions {
114
+ /**
115
+ * Whether worktree isolation is permitted at all. False when the project set
116
+ * `worktreeIsolation: false`, which drops a requested worktree rather than
117
+ * failing the call: the fail-loud precedent covers spawns that *cannot* work,
118
+ * while this one is the user opting out, and throwing would break exactly the
119
+ * calls the `"off"` value exists to tolerate. Defaults to allowed.
120
+ */
121
+ worktreeAllowed?: boolean;
122
+ /**
123
+ * What an unqualified spawn means — neither the call nor the agent file said.
124
+ *
125
+ * Top-level callers pass the `backgroundByDefault` setting (default `true`,
126
+ * following Claude Code). Nested callers pass `false` unconditionally: a
127
+ * detached child is killed by `abortOwnedChildren` when its parent settles
128
+ * and has no notification path of its own, so backgrounding one loses its
129
+ * work. Both call sites pass it explicitly; the `false` fallback only covers
130
+ * a caller that supplies no options at all, which in-tree means tests.
131
+ */
132
+ defaultRunInBackground?: boolean;
133
+ /**
134
+ * Whether the caller's `max_turns` parameter may set the budget. False by
135
+ * default: agent-file and project caps remain authoritative, and a caller
136
+ * limit is dropped. The agent file's own `maxTurns` always wins when set.
137
+ */
138
+ allowPerCallTurnLimits?: boolean;
139
+ }
140
+ export declare function resolveAgentInvocationConfig(agentConfig: AgentConfig | undefined, params: AgentInvocationParams, opts?: ResolveOptions): {
141
+ modelInput?: string;
142
+ modelFromParams: boolean;
143
+ thinking?: ThinkingLevel;
144
+ maxTurns?: number;
145
+ inheritContext: boolean;
146
+ runInBackground: boolean;
147
+ isolated: boolean;
148
+ isolation?: IsolationMode;
149
+ /**
150
+ * Caller parameters an agent file's frontmatter outranked, so the surfaces can
151
+ * say "(asked X)" instead of presenting the effective value as the requested
152
+ * one (#182). Populated only where both sides named something and they
153
+ * disagree — a caller who asked for what they got was still honored.
154
+ *
155
+ * `max_turns` is deliberately absent: no surface renders a requested-vs-
156
+ * effective turn limit, so recording one would be dead data.
157
+ */
158
+ overridden?: {
159
+ thinking?: ThinkingLevel;
160
+ model?: string;
161
+ };
162
+ };
163
+ export declare function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined;
164
+ export {};
@@ -0,0 +1,158 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import { resolveModel } from "./model-resolver.js";
3
+ /** Narrow a resolvePinnedModel result to the built-in parent-model fallback. */
4
+ export function isPinFallback(result) {
5
+ return typeof result === "object" && result !== null && result.pinFallback === true;
6
+ }
7
+ export function resolvePinnedModel(input, registry, opts) {
8
+ const available = registry.getAvailable?.() ?? registry.getAll?.();
9
+ if (input.trim() && !input.includes("/")) {
10
+ return resolveModel(input, { find: (provider, id) => registry.find(provider, id), getAll: () => available ?? [] });
11
+ }
12
+ const slash = input.indexOf("/");
13
+ // Legacy registries may expose only exact lookup; never widen to a different id.
14
+ const model = available ? available.find(model => `${model.provider}/${model.id}` === input)
15
+ : slash > 0 ? registry.find(input.slice(0, slash), input.slice(slash + 1)) : undefined;
16
+ if (model && `${model.provider}/${model.id}` === input)
17
+ return model;
18
+ // Same model id on another available provider (model-resolver normalization:
19
+ // case/dot-dash/date-suffix tolerant). Preferred-provider pin, not a rename:
20
+ // only the provider may differ, never the id.
21
+ if (slash > 0 && available) {
22
+ const wantedId = input.slice(slash + 1);
23
+ const cross = resolveModel(wantedId, {
24
+ find: (provider, id) => registry.find(provider, id),
25
+ getAll: () => available,
26
+ });
27
+ if (typeof cross !== "string" && cross) {
28
+ const crossKey = `${cross.provider}/${cross.id}`;
29
+ const found = available.find(m => `${m.provider}/${m.id}` === crossKey);
30
+ if (found && normalizeModelId(found.id) === normalizeModelId(wantedId))
31
+ return found;
32
+ }
33
+ }
34
+ if (opts?.isBuiltInDefault) {
35
+ const target = opts.parentModel ? "the parent model" : "the session default model";
36
+ return {
37
+ pinFallback: true,
38
+ model: opts.parentModel,
39
+ notice: `Pinned model "${input}" is not available; running with ${target} instead.`,
40
+ };
41
+ }
42
+ 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.`;
43
+ }
44
+ /** Normalize a model id for cross-provider comparison (mirrors model-resolver). */
45
+ function normalizeModelId(id) {
46
+ return id.toLowerCase().replace(/\./g, "-").replace(/-\d{8}$/, "");
47
+ }
48
+ /**
49
+ * The model-facing `isolation` parameter, shared by the `Agent` tool and the
50
+ * nested delegation tool so the two cannot drift.
51
+ *
52
+ * Shape matters more than wording here. As a single-value optional literal,
53
+ * models that fill every optional parameter — the transcript on #231 shows one
54
+ * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
55
+ * had only `"worktree"` available to fill it with, and kept spawning worktrees
56
+ * across three turns while their own reasoning said to omit the field. Every
57
+ * other optional parameter has an inert filler; this one did not. `"off"` is
58
+ * listed first and described as the default so the harmless value is the
59
+ * obvious one to reach for.
60
+ *
61
+ * The wording tracks Claude Code's own `isolation` parameter, whose phrasing
62
+ * models have the most exposure to: one description on the union rather than
63
+ * per-value ones, opening "Isolation mode.", then a sentence per value in
64
+ * schema order, each with its caveats in a trailing parenthetical. Two clauses
65
+ * are ours, because our shape is not theirs — `"off"` has no counterpart there
66
+ * (their enum is `worktree | remote`, so both of their values do something),
67
+ * and neither does the uncommitted-work warning, which is the specific trap
68
+ * #231 fell into. Deliberately absent is any "only use a worktree when…"
69
+ * restriction: Claude Code's `Agent` tool states the capability and stops, and
70
+ * a second legal value is what lets a model decline one, not being told to.
71
+ */
72
+ const isolationParamShape = {
73
+ isolation: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("worktree")], {
74
+ description: '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).',
75
+ })),
76
+ };
77
+ /**
78
+ * Build the `isolation` parameter for a tool schema, or nothing when the
79
+ * project disabled worktrees (`worktreeIsolation: false`).
80
+ *
81
+ * Dropping the field beats accepting it and quietly downgrading. The setting is
82
+ * for a project whose model passes `"worktree"` on *every* call, so a
83
+ * per-result "isolation was disabled" note would be noise on every result and
84
+ * would keep raising the salience of a capability that isn't there. With no
85
+ * field there is nothing to pass, nothing to drop, and nothing to explain — the
86
+ * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
87
+ * cost. The resolver gate and the `agent-manager` check still cover the paths a
88
+ * schema can't reach: agent files, the scheduler, and cross-extension RPC.
89
+ *
90
+ * Like `scheduleParam`, this is read once at tool registration — flipping the
91
+ * setting needs a new pi session for the schema to change.
92
+ */
93
+ export function isolationParam(enabled) {
94
+ return enabled ? isolationParamShape : {};
95
+ }
96
+ /**
97
+ * The model-facing `max_turns` parameter, shared by the top-level `Agent` tool
98
+ * and the nested delegation tool.
99
+ *
100
+ * Like `isolationParam`, this is a `Partial` shape meant to be spread into a
101
+ * `Type.Object`: when caller caps are disabled the field is omitted entirely,
102
+ * so the model is never told a knob exists that the runtime would ignore. The
103
+ * resolver gate and the RPC filter still cover calls that bypass schema
104
+ * validation.
105
+ */
106
+ const maxTurnsParamShape = {
107
+ max_turns: Type.Optional(Type.Number({
108
+ description: "Maximum number of agentic turns before stopping. Omit for unlimited (default).",
109
+ minimum: 1,
110
+ })),
111
+ };
112
+ /** Build the `max_turns` parameter for a tool schema, or nothing when caller caps are disabled. */
113
+ export function maxTurnsParam(enabled) {
114
+ return enabled ? maxTurnsParamShape : {};
115
+ }
116
+ export function resolveAgentInvocationConfig(agentConfig, params, opts) {
117
+ // Precedence first, collapse second — reversing these loses the veto, since
118
+ // an agent file's "off" only outranks a caller's "worktree" while it is still
119
+ // a value. Everything downstream then sees "worktree" or nothing at all.
120
+ const requested = agentConfig?.isolation ?? params.isolation;
121
+ const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : undefined;
122
+ const overriddenThinking = agentConfig?.thinking != null && params.thinking != null
123
+ && agentConfig.thinking !== params.thinking
124
+ ? params.thinking
125
+ : undefined;
126
+ const overriddenModel = agentConfig?.model != null && params.model != null
127
+ && agentConfig.model !== params.model
128
+ ? params.model
129
+ : undefined;
130
+ // A conditional schema spread leaves `max_turns` statically unknown, and the
131
+ // RPC path can carry anything. Narrow to a finite number (`0` stays intact —
132
+ // it is the explicit "unlimited" marker) before the policy gate, so a caller
133
+ // value that is not a number is treated as no opinion rather than reaching
134
+ // normalizeMaxTurns.
135
+ const callerMaxTurns = typeof params.max_turns === "number" && Number.isFinite(params.max_turns)
136
+ ? params.max_turns
137
+ : undefined;
138
+ return {
139
+ modelInput: agentConfig?.model ?? params.model,
140
+ modelFromParams: agentConfig?.model == null && params.model != null,
141
+ thinking: (agentConfig?.thinking ?? params.thinking),
142
+ maxTurns: agentConfig?.maxTurns
143
+ ?? (opts?.allowPerCallTurnLimits === true ? callerMaxTurns : undefined),
144
+ inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
145
+ runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
146
+ isolated: agentConfig?.isolated ?? params.isolated ?? false,
147
+ isolation,
148
+ // Undefined rather than an empty object when nothing was overridden: callers
149
+ // spread this into the invocation snapshot, and an always-present key would
150
+ // put `requestedThinking: undefined` on every record.
151
+ overridden: overriddenThinking || overriddenModel
152
+ ? { thinking: overriddenThinking, model: overriddenModel }
153
+ : undefined,
154
+ };
155
+ }
156
+ export function resolveJoinMode(defaultJoinMode, runInBackground) {
157
+ return runInBackground ? defaultJoinMode : undefined;
158
+ }
@@ -0,0 +1,53 @@
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
+ import type { MemoryScope } from "./types.ts";
14
+ /**
15
+ * Returns true if a name contains characters not allowed in agent/skill names.
16
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
17
+ */
18
+ export declare function isUnsafeName(name: string): boolean;
19
+ /**
20
+ * Returns true if the given path is a symlink (defense against symlink attacks).
21
+ */
22
+ export declare function isSymlink(filePath: string): boolean;
23
+ /**
24
+ * Safely read a file, rejecting symlinks.
25
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
26
+ */
27
+ export declare function safeReadFile(filePath: string): string | undefined;
28
+ /**
29
+ * Resolve the memory directory path for a given agent + scope + cwd.
30
+ * Throws if agentName contains path traversal characters.
31
+ */
32
+ export declare function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string;
33
+ /**
34
+ * Ensure the memory directory exists, creating it if needed.
35
+ * Refuses to create directories if any component in the path is a symlink
36
+ * to prevent symlink-based directory traversal attacks.
37
+ */
38
+ export declare function ensureMemoryDir(memoryDir: string): void;
39
+ /**
40
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
41
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
42
+ */
43
+ export declare function readMemoryIndex(memoryDir: string): string | undefined;
44
+ /**
45
+ * Build the memory block to inject into the agent's system prompt.
46
+ * Also ensures the memory directory exists (creates it if needed).
47
+ */
48
+ export declare function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string;
49
+ /**
50
+ * Build a read-only memory block for agents that lack write/edit tools.
51
+ * Does NOT create the memory directory — agents can only consume existing memory.
52
+ */
53
+ export declare function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string;
package/dist/memory.js ADDED
@@ -0,0 +1,165 @@
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
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join, } from "node:path";
16
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
17
+ /** Maximum lines to read from MEMORY.md */
18
+ const MAX_MEMORY_LINES = 200;
19
+ /**
20
+ * Returns true if a name contains characters not allowed in agent/skill names.
21
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
22
+ */
23
+ export function isUnsafeName(name) {
24
+ if (!name || name.length > 128)
25
+ return true;
26
+ return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
27
+ }
28
+ /**
29
+ * Returns true if the given path is a symlink (defense against symlink attacks).
30
+ */
31
+ export function isSymlink(filePath) {
32
+ try {
33
+ return lstatSync(filePath).isSymbolicLink();
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ /**
40
+ * Safely read a file, rejecting symlinks.
41
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
42
+ */
43
+ export function safeReadFile(filePath) {
44
+ if (!existsSync(filePath))
45
+ return undefined;
46
+ if (isSymlink(filePath))
47
+ return undefined;
48
+ try {
49
+ return readFileSync(filePath, "utf-8");
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ /**
56
+ * Resolve the memory directory path for a given agent + scope + cwd.
57
+ * Throws if agentName contains path traversal characters.
58
+ */
59
+ export function resolveMemoryDir(agentName, scope, cwd) {
60
+ if (isUnsafeName(agentName)) {
61
+ throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
62
+ }
63
+ switch (scope) {
64
+ case "user": {
65
+ const current = join(getAgentDir(), "agent-memory", agentName);
66
+ // Legacy location from when this path was hardcoded. Keep using it if it
67
+ // already holds this agent's memory and the new location hasn't been
68
+ // created yet — otherwise existing memories would be silently orphaned.
69
+ const legacy = join(homedir(), ".pi", "agent-memory", agentName);
70
+ if (!existsSync(current) && existsSync(legacy) && !isSymlink(legacy)) {
71
+ return legacy;
72
+ }
73
+ return current;
74
+ }
75
+ case "project":
76
+ return join(cwd, ".pi", "agent-memory", agentName);
77
+ case "local":
78
+ return join(cwd, ".pi", "agent-memory-local", agentName);
79
+ }
80
+ }
81
+ /**
82
+ * Ensure the memory directory exists, creating it if needed.
83
+ * Refuses to create directories if any component in the path is a symlink
84
+ * to prevent symlink-based directory traversal attacks.
85
+ */
86
+ export function ensureMemoryDir(memoryDir) {
87
+ // If the directory already exists, verify it's not a symlink
88
+ if (existsSync(memoryDir)) {
89
+ if (isSymlink(memoryDir)) {
90
+ throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
91
+ }
92
+ return;
93
+ }
94
+ mkdirSync(memoryDir, { recursive: true });
95
+ }
96
+ /**
97
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
98
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
99
+ */
100
+ export function readMemoryIndex(memoryDir) {
101
+ // Reject symlinked memory directories
102
+ if (isSymlink(memoryDir))
103
+ return undefined;
104
+ const memoryFile = join(memoryDir, "MEMORY.md");
105
+ const content = safeReadFile(memoryFile);
106
+ if (content === undefined)
107
+ return undefined;
108
+ const lines = content.split("\n");
109
+ if (lines.length > MAX_MEMORY_LINES) {
110
+ return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
111
+ }
112
+ return content;
113
+ }
114
+ /**
115
+ * Build the memory block to inject into the agent's system prompt.
116
+ * Also ensures the memory directory exists (creates it if needed).
117
+ */
118
+ export function buildMemoryBlock(agentName, scope, cwd) {
119
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
120
+ // Create the memory directory so the agent can immediately write to it
121
+ ensureMemoryDir(memoryDir);
122
+ const existingMemory = readMemoryIndex(memoryDir);
123
+ const header = `# Agent Memory
124
+
125
+ You have a persistent memory directory at: ${memoryDir}/
126
+ Memory scope: ${scope}
127
+
128
+ This memory persists across sessions. Use it to build up knowledge over time.`;
129
+ const memoryContent = existingMemory
130
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
131
+ : `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
132
+ const instructions = `
133
+
134
+ ## Memory Instructions
135
+ - MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
136
+ - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
137
+ - Each memory file should use this frontmatter format:
138
+ \`\`\`markdown
139
+ ---
140
+ name: <memory name>
141
+ description: <one-line description>
142
+ type: <user|feedback|project|reference>
143
+ ---
144
+ <memory content>
145
+ \`\`\`
146
+ - Update or remove memories that become outdated. Check for existing memories before creating duplicates.
147
+ - You have Read, Write, and Edit tools available for managing memory files.`;
148
+ return header + memoryContent + instructions;
149
+ }
150
+ /**
151
+ * Build a read-only memory block for agents that lack write/edit tools.
152
+ * Does NOT create the memory directory — agents can only consume existing memory.
153
+ */
154
+ export function buildReadOnlyMemoryBlock(agentName, scope, cwd) {
155
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
156
+ const existingMemory = readMemoryIndex(memoryDir);
157
+ const header = `# Agent Memory (read-only)
158
+
159
+ Memory scope: ${scope}
160
+ You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
161
+ const memoryContent = existingMemory
162
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
163
+ : `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
164
+ return header + memoryContent;
165
+ }
@@ -0,0 +1,87 @@
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
+ import { type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
64
+ import type { SubagentType } from "./types.ts";
65
+ export interface MentionCloneOptions {
66
+ /** The MAIN session's context — what the spawn is attributed to, and the
67
+ * source of both the conversation and the live system prompt. */
68
+ ctx: ExtensionContext;
69
+ /** Agent type the handle resolved to. */
70
+ type: SubagentType;
71
+ /** What the user typed after the handle. */
72
+ message: string;
73
+ /** The registered `Agent` tool, reused so the spawn is an ordinary one. */
74
+ agentTool: ToolDefinition;
75
+ }
76
+ export interface MentionCloneResult {
77
+ /** True once the clone actually called `Agent`. */
78
+ spawned: boolean;
79
+ /** Why not, when it didn't. Absent on success. */
80
+ error?: string;
81
+ }
82
+ /**
83
+ * Fork the conversation, let the copy make the tool call, throw the copy away.
84
+ * Never rejects: a clone that cannot run is reported so the caller can fall
85
+ * back to starting the agent directly.
86
+ */
87
+ export declare function runMentionClone(opts: MentionCloneOptions): Promise<MentionCloneResult>;