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