@gotgenes/pi-subagents 1.0.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 (86) hide show
  1. package/.markdownlint-cli2.yaml +19 -0
  2. package/.prettierignore +5 -0
  3. package/.release-please-manifest.json +3 -0
  4. package/AGENTS.md +85 -0
  5. package/CHANGELOG.md +495 -0
  6. package/LICENSE +21 -0
  7. package/README.md +528 -0
  8. package/dist/agent-manager.d.ts +108 -0
  9. package/dist/agent-manager.js +390 -0
  10. package/dist/agent-runner.d.ts +93 -0
  11. package/dist/agent-runner.js +428 -0
  12. package/dist/agent-types.d.ts +48 -0
  13. package/dist/agent-types.js +136 -0
  14. package/dist/context.d.ts +12 -0
  15. package/dist/context.js +56 -0
  16. package/dist/cross-extension-rpc.d.ts +46 -0
  17. package/dist/cross-extension-rpc.js +54 -0
  18. package/dist/custom-agents.d.ts +14 -0
  19. package/dist/custom-agents.js +127 -0
  20. package/dist/default-agents.d.ts +7 -0
  21. package/dist/default-agents.js +119 -0
  22. package/dist/env.d.ts +6 -0
  23. package/dist/env.js +28 -0
  24. package/dist/group-join.d.ts +32 -0
  25. package/dist/group-join.js +116 -0
  26. package/dist/index.d.ts +13 -0
  27. package/dist/index.js +1731 -0
  28. package/dist/invocation-config.d.ts +22 -0
  29. package/dist/invocation-config.js +15 -0
  30. package/dist/memory.d.ts +49 -0
  31. package/dist/memory.js +151 -0
  32. package/dist/model-resolver.d.ts +19 -0
  33. package/dist/model-resolver.js +62 -0
  34. package/dist/output-file.d.ts +24 -0
  35. package/dist/output-file.js +86 -0
  36. package/dist/prompts.d.ts +29 -0
  37. package/dist/prompts.js +72 -0
  38. package/dist/schedule-store.d.ts +36 -0
  39. package/dist/schedule-store.js +144 -0
  40. package/dist/schedule.d.ts +109 -0
  41. package/dist/schedule.js +338 -0
  42. package/dist/settings.d.ts +66 -0
  43. package/dist/settings.js +130 -0
  44. package/dist/skill-loader.d.ts +24 -0
  45. package/dist/skill-loader.js +93 -0
  46. package/dist/types.d.ts +164 -0
  47. package/dist/types.js +5 -0
  48. package/dist/ui/agent-widget.d.ts +134 -0
  49. package/dist/ui/agent-widget.js +451 -0
  50. package/dist/ui/conversation-viewer.d.ts +35 -0
  51. package/dist/ui/conversation-viewer.js +252 -0
  52. package/dist/ui/schedule-menu.d.ts +16 -0
  53. package/dist/ui/schedule-menu.js +95 -0
  54. package/dist/usage.d.ts +50 -0
  55. package/dist/usage.js +49 -0
  56. package/dist/worktree.d.ts +36 -0
  57. package/dist/worktree.js +139 -0
  58. package/docs/decisions/0001-deferred-patches.md +75 -0
  59. package/package.json +68 -0
  60. package/prek.toml +24 -0
  61. package/release-please-config.json +22 -0
  62. package/src/agent-manager.ts +482 -0
  63. package/src/agent-runner.ts +625 -0
  64. package/src/agent-types.ts +164 -0
  65. package/src/context.ts +58 -0
  66. package/src/cross-extension-rpc.ts +95 -0
  67. package/src/custom-agents.ts +136 -0
  68. package/src/default-agents.ts +123 -0
  69. package/src/env.ts +33 -0
  70. package/src/group-join.ts +141 -0
  71. package/src/index.ts +1894 -0
  72. package/src/invocation-config.ts +40 -0
  73. package/src/memory.ts +165 -0
  74. package/src/model-resolver.ts +81 -0
  75. package/src/output-file.ts +96 -0
  76. package/src/prompts.ts +105 -0
  77. package/src/schedule-store.ts +143 -0
  78. package/src/schedule.ts +365 -0
  79. package/src/settings.ts +186 -0
  80. package/src/skill-loader.ts +102 -0
  81. package/src/types.ts +176 -0
  82. package/src/ui/agent-widget.ts +533 -0
  83. package/src/ui/conversation-viewer.ts +261 -0
  84. package/src/ui/schedule-menu.ts +104 -0
  85. package/src/usage.ts +60 -0
  86. package/src/worktree.ts +162 -0
@@ -0,0 +1,22 @@
1
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
2
+ interface AgentInvocationParams {
3
+ model?: string;
4
+ thinking?: string;
5
+ max_turns?: number;
6
+ run_in_background?: boolean;
7
+ inherit_context?: boolean;
8
+ isolated?: boolean;
9
+ isolation?: IsolationMode;
10
+ }
11
+ export declare function resolveAgentInvocationConfig(agentConfig: AgentConfig | undefined, params: AgentInvocationParams): {
12
+ modelInput?: string;
13
+ modelFromParams: boolean;
14
+ thinking?: ThinkingLevel;
15
+ maxTurns?: number;
16
+ inheritContext: boolean;
17
+ runInBackground: boolean;
18
+ isolated: boolean;
19
+ isolation?: IsolationMode;
20
+ };
21
+ export declare function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined;
22
+ export {};
@@ -0,0 +1,15 @@
1
+ export function resolveAgentInvocationConfig(agentConfig, params) {
2
+ return {
3
+ modelInput: agentConfig?.model ?? params.model,
4
+ modelFromParams: agentConfig?.model == null && params.model != null,
5
+ thinking: (agentConfig?.thinking ?? params.thinking),
6
+ maxTurns: agentConfig?.maxTurns ?? params.max_turns,
7
+ inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
8
+ runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? false,
9
+ isolated: agentConfig?.isolated ?? params.isolated ?? false,
10
+ isolation: agentConfig?.isolation ?? params.isolation,
11
+ };
12
+ }
13
+ export function resolveJoinMode(defaultJoinMode, runInBackground) {
14
+ return runInBackground ? defaultJoinMode : undefined;
15
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → ~/.pi/agent-memory/{agent-name}/
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ */
9
+ import type { MemoryScope } from "./types.js";
10
+ /**
11
+ * Returns true if a name contains characters not allowed in agent/skill names.
12
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
13
+ */
14
+ export declare function isUnsafeName(name: string): boolean;
15
+ /**
16
+ * Returns true if the given path is a symlink (defense against symlink attacks).
17
+ */
18
+ export declare function isSymlink(filePath: string): boolean;
19
+ /**
20
+ * Safely read a file, rejecting symlinks.
21
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
22
+ */
23
+ export declare function safeReadFile(filePath: string): string | undefined;
24
+ /**
25
+ * Resolve the memory directory path for a given agent + scope + cwd.
26
+ * Throws if agentName contains path traversal characters.
27
+ */
28
+ export declare function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string;
29
+ /**
30
+ * Ensure the memory directory exists, creating it if needed.
31
+ * Refuses to create directories if any component in the path is a symlink
32
+ * to prevent symlink-based directory traversal attacks.
33
+ */
34
+ export declare function ensureMemoryDir(memoryDir: string): void;
35
+ /**
36
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
37
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
38
+ */
39
+ export declare function readMemoryIndex(memoryDir: string): string | undefined;
40
+ /**
41
+ * Build the memory block to inject into the agent's system prompt.
42
+ * Also ensures the memory directory exists (creates it if needed).
43
+ */
44
+ export declare function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string;
45
+ /**
46
+ * Build a read-only memory block for agents that lack write/edit tools.
47
+ * Does NOT create the memory directory — agents can only consume existing memory.
48
+ */
49
+ export declare function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string;
package/dist/memory.js ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → ~/.pi/agent-memory/{agent-name}/
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ */
9
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { join, } from "node:path";
12
+ /** Maximum lines to read from MEMORY.md */
13
+ const MAX_MEMORY_LINES = 200;
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 function isUnsafeName(name) {
19
+ if (!name || name.length > 128)
20
+ return true;
21
+ return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
22
+ }
23
+ /**
24
+ * Returns true if the given path is a symlink (defense against symlink attacks).
25
+ */
26
+ export function isSymlink(filePath) {
27
+ try {
28
+ return lstatSync(filePath).isSymbolicLink();
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ /**
35
+ * Safely read a file, rejecting symlinks.
36
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
37
+ */
38
+ export function safeReadFile(filePath) {
39
+ if (!existsSync(filePath))
40
+ return undefined;
41
+ if (isSymlink(filePath))
42
+ return undefined;
43
+ try {
44
+ return readFileSync(filePath, "utf-8");
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ /**
51
+ * Resolve the memory directory path for a given agent + scope + cwd.
52
+ * Throws if agentName contains path traversal characters.
53
+ */
54
+ export function resolveMemoryDir(agentName, scope, cwd) {
55
+ if (isUnsafeName(agentName)) {
56
+ throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
57
+ }
58
+ switch (scope) {
59
+ case "user":
60
+ return join(homedir(), ".pi", "agent-memory", agentName);
61
+ case "project":
62
+ return join(cwd, ".pi", "agent-memory", agentName);
63
+ case "local":
64
+ return join(cwd, ".pi", "agent-memory-local", agentName);
65
+ }
66
+ }
67
+ /**
68
+ * Ensure the memory directory exists, creating it if needed.
69
+ * Refuses to create directories if any component in the path is a symlink
70
+ * to prevent symlink-based directory traversal attacks.
71
+ */
72
+ export function ensureMemoryDir(memoryDir) {
73
+ // If the directory already exists, verify it's not a symlink
74
+ if (existsSync(memoryDir)) {
75
+ if (isSymlink(memoryDir)) {
76
+ throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
77
+ }
78
+ return;
79
+ }
80
+ mkdirSync(memoryDir, { recursive: true });
81
+ }
82
+ /**
83
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
84
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
85
+ */
86
+ export function readMemoryIndex(memoryDir) {
87
+ // Reject symlinked memory directories
88
+ if (isSymlink(memoryDir))
89
+ return undefined;
90
+ const memoryFile = join(memoryDir, "MEMORY.md");
91
+ const content = safeReadFile(memoryFile);
92
+ if (content === undefined)
93
+ return undefined;
94
+ const lines = content.split("\n");
95
+ if (lines.length > MAX_MEMORY_LINES) {
96
+ return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
97
+ }
98
+ return content;
99
+ }
100
+ /**
101
+ * Build the memory block to inject into the agent's system prompt.
102
+ * Also ensures the memory directory exists (creates it if needed).
103
+ */
104
+ export function buildMemoryBlock(agentName, scope, cwd) {
105
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
106
+ // Create the memory directory so the agent can immediately write to it
107
+ ensureMemoryDir(memoryDir);
108
+ const existingMemory = readMemoryIndex(memoryDir);
109
+ const header = `# Agent Memory
110
+
111
+ You have a persistent memory directory at: ${memoryDir}/
112
+ Memory scope: ${scope}
113
+
114
+ This memory persists across sessions. Use it to build up knowledge over time.`;
115
+ const memoryContent = existingMemory
116
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
117
+ : `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
118
+ const instructions = `
119
+
120
+ ## Memory Instructions
121
+ - MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
122
+ - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
123
+ - Each memory file should use this frontmatter format:
124
+ \`\`\`markdown
125
+ ---
126
+ name: <memory name>
127
+ description: <one-line description>
128
+ type: <user|feedback|project|reference>
129
+ ---
130
+ <memory content>
131
+ \`\`\`
132
+ - Update or remove memories that become outdated. Check for existing memories before creating duplicates.
133
+ - You have Read, Write, and Edit tools available for managing memory files.`;
134
+ return header + memoryContent + instructions;
135
+ }
136
+ /**
137
+ * Build a read-only memory block for agents that lack write/edit tools.
138
+ * Does NOT create the memory directory — agents can only consume existing memory.
139
+ */
140
+ export function buildReadOnlyMemoryBlock(agentName, scope, cwd) {
141
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
142
+ const existingMemory = readMemoryIndex(memoryDir);
143
+ const header = `# Agent Memory (read-only)
144
+
145
+ Memory scope: ${scope}
146
+ You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
147
+ const memoryContent = existingMemory
148
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
149
+ : `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
150
+ return header + memoryContent;
151
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+ export interface ModelEntry {
5
+ id: string;
6
+ name: string;
7
+ provider: string;
8
+ }
9
+ export interface ModelRegistry {
10
+ find(provider: string, modelId: string): any;
11
+ getAll(): any[];
12
+ getAvailable?(): any[];
13
+ }
14
+ /**
15
+ * Resolve a model string to a Model instance.
16
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
17
+ * Returns the Model on success, or an error message string on failure.
18
+ */
19
+ export declare function resolveModel(input: string, registry: ModelRegistry): any | string;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+ /**
5
+ * Resolve a model string to a Model instance.
6
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
7
+ * Returns the Model on success, or an error message string on failure.
8
+ */
9
+ export function resolveModel(input, registry) {
10
+ // Available models (those with auth configured)
11
+ const all = (registry.getAvailable?.() ?? registry.getAll());
12
+ const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
13
+ // 1. Exact match: "provider/modelId" — only if available (has auth)
14
+ const slashIdx = input.indexOf("/");
15
+ if (slashIdx !== -1) {
16
+ const provider = input.slice(0, slashIdx);
17
+ const modelId = input.slice(slashIdx + 1);
18
+ if (availableSet.has(input.toLowerCase())) {
19
+ const found = registry.find(provider, modelId);
20
+ if (found)
21
+ return found;
22
+ }
23
+ }
24
+ // 2. Fuzzy match against available models
25
+ const query = input.toLowerCase();
26
+ // Score each model: prefer exact id match > id contains > name contains > provider+id contains
27
+ let bestMatch;
28
+ let bestScore = 0;
29
+ for (const m of all) {
30
+ const id = m.id.toLowerCase();
31
+ const name = m.name.toLowerCase();
32
+ const full = `${m.provider}/${m.id}`.toLowerCase();
33
+ let score = 0;
34
+ if (id === query || full === query) {
35
+ score = 100; // exact
36
+ }
37
+ else if (id.includes(query) || full.includes(query)) {
38
+ score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
39
+ }
40
+ else if (name.includes(query)) {
41
+ score = 40 + (query.length / name.length) * 20;
42
+ }
43
+ else if (query.split(/[\s\-/]+/).every(part => id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))) {
44
+ score = 20; // all parts present somewhere
45
+ }
46
+ if (score > bestScore) {
47
+ bestScore = score;
48
+ bestMatch = m;
49
+ }
50
+ }
51
+ if (bestMatch && bestScore >= 20) {
52
+ const found = registry.find(bestMatch.provider, bestMatch.id);
53
+ if (found)
54
+ return found;
55
+ }
56
+ // 3. No match — list available models
57
+ const modelList = all
58
+ .map(m => ` ${m.provider}/${m.id}`)
59
+ .sort()
60
+ .join("\n");
61
+ return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
62
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
8
+ /**
9
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
10
+ * - POSIX: "/home/user/project" → "home-user-project"
11
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
12
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
13
+ */
14
+ export declare function encodeCwd(cwd: string): string;
15
+ /** Create the output file path, ensuring the directory exists.
16
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
17
+ export declare function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string;
18
+ /** Write the initial user prompt entry. */
19
+ export declare function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void;
20
+ /**
21
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
22
+ * Returns a cleanup function that does a final flush and unsubscribes.
23
+ */
24
+ export declare function streamToOutputFile(session: AgentSession, path: string, agentId: string, cwd: string): () => void;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+ import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ /**
11
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
12
+ * - POSIX: "/home/user/project" → "home-user-project"
13
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
14
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
15
+ */
16
+ export function encodeCwd(cwd) {
17
+ return cwd
18
+ .replace(/[/\\]/g, "-") // both separators → dash
19
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
20
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
21
+ }
22
+ /** Create the output file path, ensuring the directory exists.
23
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
24
+ export function createOutputFilePath(cwd, agentId, sessionId) {
25
+ const encoded = encodeCwd(cwd);
26
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
27
+ mkdirSync(root, { recursive: true, mode: 0o700 });
28
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
29
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
30
+ try {
31
+ chmodSync(root, 0o700);
32
+ }
33
+ catch (err) {
34
+ if (process.platform !== "win32")
35
+ throw err;
36
+ }
37
+ const dir = join(root, encoded, sessionId, "tasks");
38
+ mkdirSync(dir, { recursive: true });
39
+ return join(dir, `${agentId}.output`);
40
+ }
41
+ /** Write the initial user prompt entry. */
42
+ export function writeInitialEntry(path, agentId, prompt, cwd) {
43
+ const entry = {
44
+ isSidechain: true,
45
+ agentId,
46
+ type: "user",
47
+ message: { role: "user", content: prompt },
48
+ timestamp: new Date().toISOString(),
49
+ cwd,
50
+ };
51
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
52
+ }
53
+ /**
54
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
55
+ * Returns a cleanup function that does a final flush and unsubscribes.
56
+ */
57
+ export function streamToOutputFile(session, path, agentId, cwd) {
58
+ let writtenCount = 1; // initial user prompt already written
59
+ const flush = () => {
60
+ const messages = session.messages;
61
+ while (writtenCount < messages.length) {
62
+ const msg = messages[writtenCount];
63
+ const entry = {
64
+ isSidechain: true,
65
+ agentId,
66
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
67
+ message: msg,
68
+ timestamp: new Date().toISOString(),
69
+ cwd,
70
+ };
71
+ try {
72
+ appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
73
+ }
74
+ catch { /* ignore write errors */ }
75
+ writtenCount++;
76
+ }
77
+ };
78
+ const unsubscribe = session.subscribe((event) => {
79
+ if (event.type === "turn_end")
80
+ flush();
81
+ });
82
+ return () => {
83
+ flush();
84
+ unsubscribe();
85
+ };
86
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * prompts.ts — System prompt builder for agents.
3
+ */
4
+ import type { AgentConfig, EnvInfo } from "./types.js";
5
+ /** Extra sections to inject into the system prompt (memory, skills, etc.). */
6
+ export interface PromptExtras {
7
+ /** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
8
+ memoryBlock?: string;
9
+ /** Preloaded skill contents to inject. */
10
+ skillBlocks?: {
11
+ name: string;
12
+ content: string;
13
+ }[];
14
+ }
15
+ /**
16
+ * Build the system prompt for an agent from its config.
17
+ *
18
+ * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
19
+ * - "append" mode: env header + parent system prompt + sub-agent context + config.systemPrompt
20
+ * - "append" with empty systemPrompt: pure parent clone
21
+ *
22
+ * Both modes prepend an `<active_agent name="${config.name}"/>` tag so downstream
23
+ * extensions (e.g. `@gotgenes/pi-permission-system`) can resolve per-agent policy
24
+ * inside the child session by parsing the system prompt.
25
+ *
26
+ * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
27
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
28
+ */
29
+ export declare function buildAgentPrompt(config: AgentConfig, cwd: string, env: EnvInfo, parentSystemPrompt?: string, extras?: PromptExtras): string;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * prompts.ts — System prompt builder for agents.
3
+ */
4
+ /**
5
+ * Build the system prompt for an agent from its config.
6
+ *
7
+ * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
8
+ * - "append" mode: env header + parent system prompt + sub-agent context + config.systemPrompt
9
+ * - "append" with empty systemPrompt: pure parent clone
10
+ *
11
+ * Both modes prepend an `<active_agent name="${config.name}"/>` tag so downstream
12
+ * extensions (e.g. `@gotgenes/pi-permission-system`) can resolve per-agent policy
13
+ * inside the child session by parsing the system prompt.
14
+ *
15
+ * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
16
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
17
+ */
18
+ export function buildAgentPrompt(config, cwd, env, parentSystemPrompt, extras) {
19
+ const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
20
+ const envBlock = `# Environment
21
+ Working directory: ${cwd}
22
+ ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
23
+ Platform: ${env.platform}`;
24
+ // Build optional extras suffix
25
+ const extraSections = [];
26
+ if (extras?.memoryBlock) {
27
+ extraSections.push(extras.memoryBlock);
28
+ }
29
+ if (extras?.skillBlocks?.length) {
30
+ for (const skill of extras.skillBlocks) {
31
+ extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
32
+ }
33
+ }
34
+ const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
35
+ if (config.promptMode === "append") {
36
+ const identity = parentSystemPrompt || genericBase;
37
+ const bridge = `<sub_agent_context>
38
+ You are operating as a sub-agent invoked to handle a specific task.
39
+ - Use the read tool instead of cat/head/tail
40
+ - Use the edit tool instead of sed/awk
41
+ - Use the write tool instead of echo/heredoc
42
+ - Use the find tool instead of bash find/ls for file search
43
+ - Use the grep tool instead of bash grep/rg for content search
44
+ - Make independent tool calls in parallel
45
+ - Use absolute file paths
46
+ - Do not use emojis
47
+ - Be concise but complete
48
+ </sub_agent_context>`;
49
+ const customSection = config.systemPrompt?.trim()
50
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
51
+ : "";
52
+ return (activeAgentTag +
53
+ envBlock +
54
+ "\n\n<inherited_system_prompt>\n" +
55
+ identity +
56
+ "\n</inherited_system_prompt>\n\n" +
57
+ bridge +
58
+ customSection +
59
+ extrasSuffix);
60
+ }
61
+ // "replace" mode — env header + the config's full system prompt
62
+ const replaceHeader = `You are a pi coding agent sub-agent.
63
+ You have been invoked to handle a specific task autonomously.
64
+
65
+ ${envBlock}`;
66
+ return (activeAgentTag + replaceHeader + "\n\n" + config.systemPrompt + extrasSuffix);
67
+ }
68
+ /** Fallback base prompt when parent system prompt is unavailable in append mode. */
69
+ const genericBase = `# Role
70
+ You are a general-purpose coding agent for complex, multi-step tasks.
71
+ You have full access to read, write, edit files, and execute commands.
72
+ Do what has been asked; nothing more, nothing less.`;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * schedule-store.ts — File-backed store for scheduled subagents.
3
+ *
4
+ * Session-scoped: each pi session owns its own schedules at
5
+ * `<cwd>/.pi/subagent-schedules/<sessionId>.json`. `/new` starts a fresh
6
+ * empty store; `/resume` reloads.
7
+ *
8
+ * Concurrency model lifted from pi-chonky-tasks/src/task-store.ts: every
9
+ * mutation acquires a PID-based exclusion lock, re-reads the latest state
10
+ * from disk, applies the change, atomic-writes via temp+rename, releases.
11
+ */
12
+ import type { ScheduledSubagent } from "./types.js";
13
+ /** Resolve the storage path for a session-scoped store. */
14
+ export declare function resolveStorePath(cwd: string, sessionId: string): string;
15
+ export declare class ScheduleStore {
16
+ private filePath;
17
+ private lockPath;
18
+ private jobs;
19
+ constructor(filePath: string);
20
+ /** Load from disk into the in-memory cache. Silent on parse errors. */
21
+ private load;
22
+ /** Atomic write via temp file + rename (POSIX-atomic). */
23
+ private save;
24
+ /** Acquire lock → reload → mutate → save → release. */
25
+ private withLock;
26
+ /** Read-only — returns a snapshot of the in-memory cache. */
27
+ list(): ScheduledSubagent[];
28
+ /** Read-only check — uses the cache. */
29
+ hasName(name: string, exceptId?: string): boolean;
30
+ get(id: string): ScheduledSubagent | undefined;
31
+ add(job: ScheduledSubagent): void;
32
+ update(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined;
33
+ remove(id: string): boolean;
34
+ /** Delete the backing file (used when no jobs remain, optional cleanup). */
35
+ deleteFileIfEmpty(): void;
36
+ }