@by-lua/lspec-subagents 1.0.1

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/CHANGELOG.md +482 -0
  2. package/LICENSE +21 -0
  3. package/README.md +123 -0
  4. package/dist/agent-manager.d.ts +108 -0
  5. package/dist/agent-manager.js +391 -0
  6. package/dist/agent-runner.d.ts +95 -0
  7. package/dist/agent-runner.js +377 -0
  8. package/dist/agent-types.d.ts +58 -0
  9. package/dist/agent-types.js +157 -0
  10. package/dist/context.d.ts +12 -0
  11. package/dist/context.js +56 -0
  12. package/dist/cross-extension-rpc.d.ts +46 -0
  13. package/dist/cross-extension-rpc.js +76 -0
  14. package/dist/custom-agents.d.ts +14 -0
  15. package/dist/custom-agents.js +127 -0
  16. package/dist/default-agents.d.ts +12 -0
  17. package/dist/default-agents.js +489 -0
  18. package/dist/env.d.ts +6 -0
  19. package/dist/env.js +28 -0
  20. package/dist/group-join.d.ts +32 -0
  21. package/dist/group-join.js +116 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +1863 -0
  24. package/dist/invocation-config.d.ts +22 -0
  25. package/dist/invocation-config.js +15 -0
  26. package/dist/memory.d.ts +49 -0
  27. package/dist/memory.js +151 -0
  28. package/dist/model-config-loader.d.ts +58 -0
  29. package/dist/model-config-loader.js +157 -0
  30. package/dist/model-resolver.d.ts +19 -0
  31. package/dist/model-resolver.js +62 -0
  32. package/dist/output-file.d.ts +24 -0
  33. package/dist/output-file.js +86 -0
  34. package/dist/prompts.d.ts +29 -0
  35. package/dist/prompts.js +65 -0
  36. package/dist/schedule-store.d.ts +38 -0
  37. package/dist/schedule-store.js +155 -0
  38. package/dist/schedule.d.ts +109 -0
  39. package/dist/schedule.js +338 -0
  40. package/dist/settings.d.ts +66 -0
  41. package/dist/settings.js +130 -0
  42. package/dist/skill-loader.d.ts +24 -0
  43. package/dist/skill-loader.js +93 -0
  44. package/dist/types.d.ts +164 -0
  45. package/dist/types.js +8 -0
  46. package/dist/ui/agent-widget.d.ts +134 -0
  47. package/dist/ui/agent-widget.js +451 -0
  48. package/dist/ui/conversation-viewer.d.ts +35 -0
  49. package/dist/ui/conversation-viewer.js +252 -0
  50. package/dist/ui/schedule-menu.d.ts +16 -0
  51. package/dist/ui/schedule-menu.js +95 -0
  52. package/dist/usage.d.ts +50 -0
  53. package/dist/usage.js +49 -0
  54. package/dist/worktree.d.ts +36 -0
  55. package/dist/worktree.js +139 -0
  56. package/install.sh +77 -0
  57. package/lspec-model-config.example.json +17 -0
  58. package/package.json +50 -0
  59. package/src/agent-manager.ts +483 -0
  60. package/src/agent-runner.ts +486 -0
  61. package/src/agent-types.ts +188 -0
  62. package/src/context.ts +58 -0
  63. package/src/cross-extension-rpc.ts +122 -0
  64. package/src/custom-agents.ts +136 -0
  65. package/src/default-agents.ts +501 -0
  66. package/src/env.ts +33 -0
  67. package/src/group-join.ts +141 -0
  68. package/src/index.ts +2032 -0
  69. package/src/invocation-config.ts +40 -0
  70. package/src/memory.ts +165 -0
  71. package/src/model-config-loader.ts +193 -0
  72. package/src/model-resolver.ts +81 -0
  73. package/src/output-file.ts +96 -0
  74. package/src/prompts.ts +91 -0
  75. package/src/schedule-store.ts +153 -0
  76. package/src/schedule.ts +365 -0
  77. package/src/settings.ts +186 -0
  78. package/src/skill-loader.ts +102 -0
  79. package/src/types.ts +179 -0
  80. package/src/ui/agent-widget.ts +533 -0
  81. package/src/ui/conversation-viewer.ts +261 -0
  82. package/src/ui/schedule-menu.ts +104 -0
  83. package/src/usage.ts +60 -0
  84. package/src/worktree.ts +162 -0
  85. package/uninstall.sh +55 -0
  86. package/update.sh +64 -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,58 @@
1
+ /**
2
+ * model-config-loader.ts — Load centralized model configuration for L-Spec subagents.
3
+ *
4
+ * Inspired by oh-my-opencode-slim's model config approach.
5
+ *
6
+ * Resolution order (highest priority wins):
7
+ * 1. Project: <cwd>/.pi/lspec-model-config.json
8
+ * 2. Global: ~/.pi/agent/lspec-model-config.json
9
+ * 3. Embedded: hardcoded defaults in this file
10
+ */
11
+ export interface ModelConfig {
12
+ /** Map of agent name → model string (e.g. "claude-sonnet-4" or "provider/modelId") */
13
+ agents: Record<string, string>;
14
+ }
15
+ /** The placeholder marker prefix/suffix used in default-agents.ts */
16
+ export declare const MODEL_PLACEHOLDER_PREFIX = "{{model:";
17
+ export declare const MODEL_PLACEHOLDER_SUFFIX = "}}";
18
+ /**
19
+ * Check if a model string is a placeholder like "{{model:explorer}}"
20
+ */
21
+ export declare function isModelPlaceholder(model: string): boolean;
22
+ /**
23
+ * Extract agent name from a placeholder like "{{model:explorer}}" → "explorer"
24
+ */
25
+ export declare function parseModelPlaceholder(model: string): string | null;
26
+ /**
27
+ * Resolve a model placeholder to the actual model string from config.
28
+ * Returns the resolved model, or undefined if the placeholder can't be resolved.
29
+ */
30
+ export declare function resolveModelPlaceholder(model: string | undefined, config: ModelConfig): string | undefined;
31
+ /**
32
+ * Resolve all model placeholders in a map of agent configs.
33
+ * Modifies the map in place.
34
+ */
35
+ export declare function resolveAllPlaceholders(agents: Map<string, {
36
+ model?: string;
37
+ }>, config: ModelConfig): void;
38
+ /**
39
+ * Load model config from disk, merging global + project overrides.
40
+ * Returns the merged config.
41
+ */
42
+ export declare function loadModelConfig(cwd: string): ModelConfig;
43
+ /** Re-export for convenience — returns a fully resolved model for an agent. */
44
+ export declare function getModelForAgent(agentName: string, cwd: string): string | undefined;
45
+ /**
46
+ * Get the global model config file path.
47
+ */
48
+ export declare function getGlobalModelConfigPath(): string;
49
+ /**
50
+ * Get the project model config file path.
51
+ */
52
+ export declare function getProjectModelConfigPath(cwd: string): string;
53
+ /**
54
+ * Save a model assignment for an agent to the config file.
55
+ * Updates global config by default, or project config if specified.
56
+ * Preserves existing entries and metadata keys (_note, _docs, etc).
57
+ */
58
+ export declare function saveModelForAgent(agentName: string, model: string, target?: "global" | "project", cwd?: string): void;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * model-config-loader.ts — Load centralized model configuration for L-Spec subagents.
3
+ *
4
+ * Inspired by oh-my-opencode-slim's model config approach.
5
+ *
6
+ * Resolution order (highest priority wins):
7
+ * 1. Project: <cwd>/.pi/lspec-model-config.json
8
+ * 2. Global: ~/.pi/agent/lspec-model-config.json
9
+ * 3. Embedded: hardcoded defaults in this file
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { getAgentDir } from "@mariozechner/pi-coding-agent";
14
+ /** Embedded defaults — used when no config file exists. Using generic models as reference. */
15
+ const EMBEDDED_DEFAULTS = {
16
+ agents: {
17
+ orchestrator: "claude-sonnet-4",
18
+ explorer: "gpt-4o-mini",
19
+ librarian: "claude-sonnet-4",
20
+ oracle: "claude-opus-4",
21
+ designer: "claude-sonnet-4",
22
+ fixer: "claude-sonnet-4",
23
+ observer: "gpt-4o-mini",
24
+ council: "claude-opus-4",
25
+ councillor: "gpt-4o-mini",
26
+ },
27
+ };
28
+ /** The placeholder marker prefix/suffix used in default-agents.ts */
29
+ export const MODEL_PLACEHOLDER_PREFIX = "{{model:";
30
+ export const MODEL_PLACEHOLDER_SUFFIX = "}}";
31
+ /**
32
+ * Check if a model string is a placeholder like "{{model:explorer}}"
33
+ */
34
+ export function isModelPlaceholder(model) {
35
+ return model.startsWith(MODEL_PLACEHOLDER_PREFIX) && model.endsWith(MODEL_PLACEHOLDER_SUFFIX);
36
+ }
37
+ /**
38
+ * Extract agent name from a placeholder like "{{model:explorer}}" → "explorer"
39
+ */
40
+ export function parseModelPlaceholder(model) {
41
+ if (!isModelPlaceholder(model))
42
+ return null;
43
+ return model.slice(MODEL_PLACEHOLDER_PREFIX.length, -MODEL_PLACEHOLDER_SUFFIX.length);
44
+ }
45
+ /**
46
+ * Resolve a model placeholder to the actual model string from config.
47
+ * Returns the resolved model, or undefined if the placeholder can't be resolved.
48
+ */
49
+ export function resolveModelPlaceholder(model, config) {
50
+ if (!model)
51
+ return undefined;
52
+ if (!isModelPlaceholder(model))
53
+ return model;
54
+ const agentName = parseModelPlaceholder(model);
55
+ if (!agentName)
56
+ return undefined;
57
+ return config.agents[agentName];
58
+ }
59
+ /**
60
+ * Resolve all model placeholders in a map of agent configs.
61
+ * Modifies the map in place.
62
+ */
63
+ export function resolveAllPlaceholders(agents, config) {
64
+ for (const [, agent] of agents) {
65
+ if (agent.model && isModelPlaceholder(agent.model)) {
66
+ const resolved = resolveModelPlaceholder(agent.model, config);
67
+ if (resolved) {
68
+ agent.model = resolved;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ /**
74
+ * Load model config from disk, merging global + project overrides.
75
+ * Returns the merged config.
76
+ */
77
+ export function loadModelConfig(cwd) {
78
+ const config = structuredClone(EMBEDDED_DEFAULTS);
79
+ const globalDir = join(getAgentDir());
80
+ const projectDir = join(cwd, ".pi");
81
+ // Load global config (lower priority)
82
+ const globalPath = join(globalDir, "lspec-model-config.json");
83
+ loadAndMerge(globalPath, config);
84
+ // Load project config (higher priority — overwrites)
85
+ const projectPath = join(projectDir, "lspec-model-config.json");
86
+ loadAndMerge(projectPath, config);
87
+ return config;
88
+ }
89
+ /**
90
+ * Load a JSON config file and merge its agents into the config object.
91
+ */
92
+ function loadAndMerge(path, config) {
93
+ if (!existsSync(path))
94
+ return;
95
+ try {
96
+ const raw = readFileSync(path, "utf-8");
97
+ const parsed = JSON.parse(raw);
98
+ // Skip _note, _docs keys — they're metadata
99
+ if (parsed.agents && typeof parsed.agents === "object") {
100
+ for (const [key, value] of Object.entries(parsed.agents)) {
101
+ if (typeof value === "string") {
102
+ config.agents[key] = value;
103
+ }
104
+ }
105
+ }
106
+ }
107
+ catch {
108
+ // Silently ignore malformed config files
109
+ }
110
+ }
111
+ /** Re-export for convenience — returns a fully resolved model for an agent. */
112
+ export function getModelForAgent(agentName, cwd) {
113
+ const config = loadModelConfig(cwd);
114
+ return config.agents[agentName];
115
+ }
116
+ /**
117
+ * Get the global model config file path.
118
+ */
119
+ export function getGlobalModelConfigPath() {
120
+ return join(getAgentDir(), "lspec-model-config.json");
121
+ }
122
+ /**
123
+ * Get the project model config file path.
124
+ */
125
+ export function getProjectModelConfigPath(cwd) {
126
+ return join(cwd, ".pi", "lspec-model-config.json");
127
+ }
128
+ /**
129
+ * Save a model assignment for an agent to the config file.
130
+ * Updates global config by default, or project config if specified.
131
+ * Preserves existing entries and metadata keys (_note, _docs, etc).
132
+ */
133
+ export function saveModelForAgent(agentName, model, target = "global", cwd) {
134
+ const configPath = target === "project"
135
+ ? getProjectModelConfigPath(cwd ?? process.cwd())
136
+ : getGlobalModelConfigPath();
137
+ // Read existing config or create new
138
+ let existing = {};
139
+ if (existsSync(configPath)) {
140
+ try {
141
+ const raw = readFileSync(configPath, "utf-8");
142
+ existing = JSON.parse(raw);
143
+ }
144
+ catch {
145
+ existing = {};
146
+ }
147
+ }
148
+ // Update the agents section
149
+ if (!existing.agents || typeof existing.agents !== "object") {
150
+ existing.agents = {};
151
+ }
152
+ existing.agents[agentName] = model;
153
+ // Ensure directory exists
154
+ mkdirSync(join(configPath, ".."), { recursive: true });
155
+ // Write back
156
+ writeFileSync(configPath, JSON.stringify(existing, null, 2) + "\n", "utf-8");
157
+ }
@@ -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 "@mariozechner/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. permission/policy systems) 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;