@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,107 @@
1
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
2
+ /**
3
+ * The model-facing `isolation` parameter, shared by the `Agent` tool and the
4
+ * nested delegation tool so the two cannot drift.
5
+ *
6
+ * Shape matters more than wording here. As a single-value optional literal,
7
+ * models that fill every optional parameter — the transcript on #231 shows one
8
+ * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
9
+ * had only `"worktree"` available to fill it with, and kept spawning worktrees
10
+ * across three turns while their own reasoning said to omit the field. Every
11
+ * other optional parameter has an inert filler; this one did not. `"off"` is
12
+ * listed first and described as the default so the harmless value is the
13
+ * obvious one to reach for.
14
+ *
15
+ * The wording tracks Claude Code's own `isolation` parameter, whose phrasing
16
+ * models have the most exposure to: one description on the union rather than
17
+ * per-value ones, opening "Isolation mode.", then a sentence per value in
18
+ * schema order, each with its caveats in a trailing parenthetical. Two clauses
19
+ * are ours, because our shape is not theirs — `"off"` has no counterpart there
20
+ * (their enum is `worktree | remote`, so both of their values do something),
21
+ * and neither does the uncommitted-work warning, which is the specific trap
22
+ * #231 fell into. Deliberately absent is any "only use a worktree when…"
23
+ * restriction: Claude Code's `Agent` tool states the capability and stops, and
24
+ * a second legal value is what lets a model decline one, not being told to.
25
+ */
26
+ declare const isolationParamShape: {
27
+ isolation: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"off">, import("@sinclair/typebox").TLiteral<"worktree">]>>;
28
+ };
29
+ /**
30
+ * Build the `isolation` parameter for a tool schema, or nothing when the
31
+ * project disabled worktrees (`worktreeIsolation: false`).
32
+ *
33
+ * Dropping the field beats accepting it and quietly downgrading. The setting is
34
+ * for a project whose model passes `"worktree"` on *every* call, so a
35
+ * per-result "isolation was disabled" note would be noise on every result and
36
+ * would keep raising the salience of a capability that isn't there. With no
37
+ * field there is nothing to pass, nothing to drop, and nothing to explain — the
38
+ * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
39
+ * cost. The resolver gate and the `agent-manager` check still cover the paths a
40
+ * schema can't reach: agent files, the scheduler, and cross-extension RPC.
41
+ *
42
+ * Like `scheduleParam`, this is read once at tool registration — flipping the
43
+ * setting needs a new pi session for the schema to change.
44
+ */
45
+ export declare function isolationParam(enabled: boolean): Partial<typeof isolationParamShape>;
46
+ interface AgentInvocationParams {
47
+ model?: string;
48
+ thinking?: string;
49
+ max_turns?: number;
50
+ run_in_background?: boolean;
51
+ inherit_context?: boolean;
52
+ isolated?: boolean;
53
+ /**
54
+ * Untyped on purpose. Both tool schemas now build this field conditionally
55
+ * and spread it, which erases TypeBox's literal inference to `unknown` (the
56
+ * `schedule` param has the same shape). The resolver below narrows by
57
+ * comparison rather than trusting the declaration, which also makes it safe
58
+ * for the cross-extension RPC path, where options arrive unvalidated.
59
+ */
60
+ isolation?: unknown;
61
+ }
62
+ interface ResolveOptions {
63
+ /**
64
+ * Whether worktree isolation is permitted at all. False when the project set
65
+ * `worktreeIsolation: false`, which drops a requested worktree rather than
66
+ * failing the call: the fail-loud precedent covers spawns that *cannot* work,
67
+ * while this one is the user opting out, and throwing would break exactly the
68
+ * calls the `"off"` value exists to tolerate. Defaults to allowed.
69
+ */
70
+ worktreeAllowed?: boolean;
71
+ /**
72
+ * What an unqualified spawn means — neither the call nor the agent file said.
73
+ *
74
+ * Top-level callers pass the `backgroundByDefault` setting (default `true`,
75
+ * following Claude Code). Nested callers pass `false` unconditionally: a
76
+ * detached child is killed by `abortOwnedChildren` when its parent settles
77
+ * and has no notification path of its own, so backgrounding one loses its
78
+ * work. Both call sites pass it explicitly; the `false` fallback only covers
79
+ * a caller that supplies no options at all, which in-tree means tests.
80
+ */
81
+ defaultRunInBackground?: boolean;
82
+ }
83
+ export declare function resolveAgentInvocationConfig(agentConfig: AgentConfig | undefined, params: AgentInvocationParams, opts?: ResolveOptions): {
84
+ modelInput?: string;
85
+ modelFromParams: boolean;
86
+ thinking?: ThinkingLevel;
87
+ maxTurns?: number;
88
+ inheritContext: boolean;
89
+ runInBackground: boolean;
90
+ isolated: boolean;
91
+ isolation?: IsolationMode;
92
+ /**
93
+ * Caller parameters an agent file's frontmatter outranked, so the surfaces can
94
+ * say "(asked X)" instead of presenting the effective value as the requested
95
+ * one (#182). Populated only where both sides named something and they
96
+ * disagree — a caller who asked for what they got was still honored.
97
+ *
98
+ * `max_turns` is deliberately absent: no surface renders a requested-vs-
99
+ * effective turn limit, so recording one would be dead data.
100
+ */
101
+ overridden?: {
102
+ thinking?: ThinkingLevel;
103
+ model?: string;
104
+ };
105
+ };
106
+ export declare function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined;
107
+ export {};
@@ -0,0 +1,83 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ /**
3
+ * The model-facing `isolation` parameter, shared by the `Agent` tool and the
4
+ * nested delegation tool so the two cannot drift.
5
+ *
6
+ * Shape matters more than wording here. As a single-value optional literal,
7
+ * models that fill every optional parameter — the transcript on #231 shows one
8
+ * emitting `resume: ""`, `schedule: ""` and `model: "default"` alongside it —
9
+ * had only `"worktree"` available to fill it with, and kept spawning worktrees
10
+ * across three turns while their own reasoning said to omit the field. Every
11
+ * other optional parameter has an inert filler; this one did not. `"off"` is
12
+ * listed first and described as the default so the harmless value is the
13
+ * obvious one to reach for.
14
+ *
15
+ * The wording tracks Claude Code's own `isolation` parameter, whose phrasing
16
+ * models have the most exposure to: one description on the union rather than
17
+ * per-value ones, opening "Isolation mode.", then a sentence per value in
18
+ * schema order, each with its caveats in a trailing parenthetical. Two clauses
19
+ * are ours, because our shape is not theirs — `"off"` has no counterpart there
20
+ * (their enum is `worktree | remote`, so both of their values do something),
21
+ * and neither does the uncommitted-work warning, which is the specific trap
22
+ * #231 fell into. Deliberately absent is any "only use a worktree when…"
23
+ * restriction: Claude Code's `Agent` tool states the capability and stops, and
24
+ * a second legal value is what lets a model decline one, not being told to.
25
+ */
26
+ const isolationParamShape = {
27
+ isolation: Type.Optional(Type.Union([Type.Literal("off"), Type.Literal("worktree")], {
28
+ 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).',
29
+ })),
30
+ };
31
+ /**
32
+ * Build the `isolation` parameter for a tool schema, or nothing when the
33
+ * project disabled worktrees (`worktreeIsolation: false`).
34
+ *
35
+ * Dropping the field beats accepting it and quietly downgrading. The setting is
36
+ * for a project whose model passes `"worktree"` on *every* call, so a
37
+ * per-result "isolation was disabled" note would be noise on every result and
38
+ * would keep raising the salience of a capability that isn't there. With no
39
+ * field there is nothing to pass, nothing to drop, and nothing to explain — the
40
+ * same trade `scheduleParam` makes for disabled scheduling, at zero LLM-context
41
+ * cost. The resolver gate and the `agent-manager` check still cover the paths a
42
+ * schema can't reach: agent files, the scheduler, and cross-extension RPC.
43
+ *
44
+ * Like `scheduleParam`, this is read once at tool registration — flipping the
45
+ * setting needs a new pi session for the schema to change.
46
+ */
47
+ export function isolationParam(enabled) {
48
+ return enabled ? isolationParamShape : {};
49
+ }
50
+ export function resolveAgentInvocationConfig(agentConfig, params, opts) {
51
+ // Precedence first, collapse second — reversing these loses the veto, since
52
+ // an agent file's "off" only outranks a caller's "worktree" while it is still
53
+ // a value. Everything downstream then sees "worktree" or nothing at all.
54
+ const requested = agentConfig?.isolation ?? params.isolation;
55
+ const isolation = requested === "worktree" && opts?.worktreeAllowed !== false ? "worktree" : undefined;
56
+ const overriddenThinking = agentConfig?.thinking != null && params.thinking != null
57
+ && agentConfig.thinking !== params.thinking
58
+ ? params.thinking
59
+ : undefined;
60
+ const overriddenModel = agentConfig?.model != null && params.model != null
61
+ && agentConfig.model !== params.model
62
+ ? params.model
63
+ : undefined;
64
+ return {
65
+ modelInput: agentConfig?.model ?? params.model,
66
+ modelFromParams: agentConfig?.model == null && params.model != null,
67
+ thinking: (agentConfig?.thinking ?? params.thinking),
68
+ maxTurns: agentConfig?.maxTurns ?? params.max_turns,
69
+ inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
70
+ runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? opts?.defaultRunInBackground ?? false,
71
+ isolated: agentConfig?.isolated ?? params.isolated ?? false,
72
+ isolation,
73
+ // Undefined rather than an empty object when nothing was overridden: callers
74
+ // spread this into the invocation snapshot, and an always-present key would
75
+ // put `requestedThinking: undefined` on every record.
76
+ overridden: overriddenThinking || overriddenModel
77
+ ? { thinking: overriddenThinking, model: overriddenModel }
78
+ : undefined,
79
+ };
80
+ }
81
+ export function resolveJoinMode(defaultJoinMode, runInBackground) {
82
+ return runInBackground ? defaultJoinMode : undefined;
83
+ }
@@ -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.js";
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.js";
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>;
@@ -0,0 +1,153 @@
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 { buildSessionContext, createAgentSession, SessionManager, } from "@earendil-works/pi-coding-agent";
64
+ import { runInChildSessionContext } from "./child-context.js";
65
+ import { agentMentionReminder } from "./mention.js";
66
+ /**
67
+ * Fork the conversation, let the copy make the tool call, throw the copy away.
68
+ * Never rejects: a clone that cannot run is reported so the caller can fall
69
+ * back to starting the agent directly.
70
+ */
71
+ export async function runMentionClone(opts) {
72
+ const { ctx, type, message, agentTool } = opts;
73
+ let spawned = false;
74
+ const cloneAgentTool = {
75
+ ...agentTool,
76
+ execute: (_cloneToolCallId, params, signal, onUpdate, _cloneCtx) => {
77
+ // One spawn per mention. The clone has a single tool and every reason to
78
+ // stop after using it, but a model that decides to "also" launch a second
79
+ // agent would do it where nobody can see and nobody asked.
80
+ if (spawned) {
81
+ return Promise.resolve({
82
+ content: [{ type: "text", text: "Already started an agent for this mention. Stop here." }],
83
+ details: undefined,
84
+ isError: true,
85
+ });
86
+ }
87
+ spawned = true;
88
+ // undefined tool-call id + the main ctx: see the header. Background is
89
+ // forced rather than left to the clone: `run_in_background` defaults to
90
+ // false, and a foreground agent answers through its TOOL RESULT — which
91
+ // here is delivered into a session that is disposed moments later, so the
92
+ // agent would run, appear in the widget and the fleet, and reach nobody.
93
+ return agentTool.execute(undefined, { ...params, run_in_background: true }, signal, onUpdate, ctx);
94
+ },
95
+ };
96
+ let session;
97
+ try {
98
+ // Pi 0.80.8 moved createAgentSession from modelRegistry to modelRuntime;
99
+ // agent-runner.ts carries the same shim for the same reason — pass both so
100
+ // the clone keeps the parent's providers across the supported range.
101
+ const parentModelRuntime = ctx.modelRegistry.runtime;
102
+ // The conversation as the main session resolves it: compaction applied,
103
+ // branch summaries substituted.
104
+ const conversation = buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId());
105
+ // Pi 0.82.0 added this; below it the field is absent and the clone takes
106
+ // the settings level instead, which is what a session that never ran
107
+ // `/think` is on anyway. Same shim shape as `modelRuntime` below.
108
+ const thinkingLevel = ctx.thinkingLevel;
109
+ const created = await runInChildSessionContext(() => createAgentSession({
110
+ cwd: ctx.cwd,
111
+ // Nothing about the copy is worth persisting, and an in-memory manager
112
+ // is also what keeps the real session untouched.
113
+ sessionManager: SessionManager.inMemory(ctx.cwd),
114
+ model: ctx.model,
115
+ ...(thinkingLevel && { thinkingLevel }),
116
+ modelRegistry: ctx.modelRegistry,
117
+ ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
118
+ // An allowlist naming exactly the clone's own tool. NOT `noTools:
119
+ // "all"`, whose doc comment ("start with no tools enabled") reads like
120
+ // it spares custom tools and does not: it resolves to an EMPTY
121
+ // allowlist, and `isAllowedTool` then drops every tool from the
122
+ // registry — the custom one included. The clone would be prompted with
123
+ // nothing to call, answer in prose, and every mention would fall
124
+ // through to the direct start with a warning. Same idiom as
125
+ // agent-runner's `tools: sessionTools` beside its nested `customTools`.
126
+ tools: [cloneAgentTool.name],
127
+ customTools: [cloneAgentTool],
128
+ }));
129
+ session = created.session;
130
+ // The clone rebuilds a system prompt from cwd and agentDir, which is close
131
+ // but not the live one — extensions contribute to it per turn. Copy the
132
+ // real thing, so the copy reasons under the instructions the user's model
133
+ // is actually working under.
134
+ const systemPrompt = ctx.getSystemPrompt?.();
135
+ if (systemPrompt)
136
+ session.agent.state.systemPrompt = systemPrompt;
137
+ // The conversation itself. Pushed rather than assigned so the array the
138
+ // session was built around stays the one it goes on using.
139
+ session.agent.state.messages.push(...conversation.messages);
140
+ // User text first, reminder after — the order Claude Code's attachment
141
+ // renderer produces, where the reminder trails the message it is about.
142
+ await session.prompt(`${message}\n\n${agentMentionReminder(type)}`);
143
+ }
144
+ catch (err) {
145
+ return { spawned, error: err instanceof Error ? err.message : String(err) };
146
+ }
147
+ finally {
148
+ session?.dispose?.();
149
+ }
150
+ return spawned
151
+ ? { spawned: true }
152
+ : { spawned: false, error: "the conversation clone did not start it" };
153
+ }