@compilr-dev/sdk 0.1.3 → 0.1.5
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.
- package/dist/index.d.ts +4 -2
- package/dist/index.js +12 -0
- package/dist/system-prompt/builder.d.ts +115 -0
- package/dist/system-prompt/builder.js +255 -0
- package/dist/system-prompt/index.d.ts +34 -0
- package/dist/system-prompt/index.js +34 -0
- package/dist/system-prompt/modules.d.ts +124 -0
- package/dist/system-prompt/modules.js +356 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -43,7 +43,9 @@ export { resolveProvider, detectProviderFromEnv, createProviderFromType } from '
|
|
|
43
43
|
export { DEFAULT_MODELS, getContextWindow, DEFAULT_CONTEXT_WINDOW } from './models.js';
|
|
44
44
|
export { type ModelTier, type TierInfo, type ProviderModelMap, MODEL_TIERS, TIER_INFO, isValidTier, type ThinkingFormat, type ModelStatus, type ModelInfo, MODEL_REGISTRY, getModelsForProvider, getModelsSortedForDisplay, getModelInfo, isKnownModel, isModelSupported, getThinkingFormat, getStatusIndicator, getStatusLabel, getDefaultModelForTier, areThinkingFormatsCompatible, shouldClearHistoryOnModelChange, getModelContextWindow, getModelDisplayName, getModelDescription, getModelForTier, getTierMappings, getTierDisplayName, getShortModelName, getDefaultTierMappings, type ProviderMetadata, type OthersProviderModel, PROVIDER_METADATA, TOGETHER_MODELS, GROQ_MODELS, FIREWORKS_MODELS, PERPLEXITY_MODELS, OPENROUTER_MODELS, getModelsForOthersProvider, getOthersProviders, getProviderMetadata, isOthersProvider, } from './models/index.js';
|
|
45
45
|
export { assembleTools, deduplicateTools } from './tools.js';
|
|
46
|
-
export {
|
|
47
|
-
export type {
|
|
46
|
+
export { SystemPromptBuilder, buildSystemPrompt, detectGitRepository, getModuleStats, ALL_MODULES, IDENTITY_MODULE, STYLE_MODULE, TASK_EXECUTION_MODULE, TODO_MANAGEMENT_MODULE, TOOL_USAGE_DIRECT_MODULE, TOOL_USAGE_META_MODULE, DELEGATION_MODULE, GIT_SAFETY_MODULE, SUGGEST_MODULE, IMPORTANT_RULES_MODULE, ENVIRONMENT_MODULE, shouldIncludeModule, getEstimatedTokensForConditions, getTotalEstimatedTokens, } from './system-prompt/index.js';
|
|
47
|
+
export type { SystemPromptContext, BuildResult, SystemPromptModule, ModuleConditions, } from './system-prompt/index.js';
|
|
48
|
+
export { defineTool, createSuccessResult, createErrorResult, mergeHooks, createLoggingHooks, createClaudeProvider, createOpenAIProvider, createGeminiNativeProvider, createOllamaProvider, createTogetherProvider, createGroqProvider, createFireworksProvider, createPerplexityProvider, createOpenRouterProvider, createMockProvider, MockProvider, Agent, ContextManager, DEFAULT_CONTEXT_CONFIG, createTaskTool, createSuggestTool, defaultAgentTypes, TOOL_SETS, BUILTIN_GUARDRAILS, TOOL_NAMES, getDefaultShellManager, builtinSkills, AnchorManager, MCPManager, AgentError, ProviderError, ToolError, ToolTimeoutError, MaxIterationsError, AbortError, } from '@compilr-dev/agents';
|
|
49
|
+
export type { Tool, HooksConfig, AgentEvent, Message, LLMProvider, AnchorInput, ToolExecutionResult, AgentRunResult, PermissionHandler, ToolPermission, AgentTypeConfig, GuardrailTriggeredHandler, BeforeLLMHookResult, BeforeToolHook, BeforeToolHookResult, AfterToolHook, AgentState, AgentConfig, SessionInfo, Anchor, AnchorScope, AnchorClearOptions, AnchorPriority, AnchorQueryOptions, FileAccessType, FileAccess, GuardrailResult, GuardrailContext, MCPClient, MCPToolDefinition, } from '@compilr-dev/agents';
|
|
48
50
|
export { readFileTool, writeFileTool, createBashTool, bashTool, bashOutputTool, killShellTool, grepTool, globTool, editTool, todoWriteTool, todoReadTool, createTodoTools, TodoStore, webFetchTool, suggestTool, } from '@compilr-dev/agents';
|
|
49
51
|
export { gitStatusTool, gitDiffTool, gitLogTool, gitCommitTool, gitBranchTool, gitStashTool, gitBlameTool, gitFileHistoryTool, detectProjectTool, findProjectRootTool, runTestsTool, runLintTool, runBuildTool, runFormatTool, findDefinitionTool, findReferencesTool, findTodosTool, checkOutdatedTool, findVulnerabilitiesTool, analyzeTestCoverageTool, getFileStructureTool, getComplexityTool, allCodingTools, unifiedTools, } from '@compilr-dev/agents-coding';
|
package/dist/index.js
CHANGED
|
@@ -61,6 +61,16 @@ getModelForTier, getTierMappings, getTierDisplayName, getShortModelName, getDefa
|
|
|
61
61
|
// =============================================================================
|
|
62
62
|
export { assembleTools, deduplicateTools } from './tools.js';
|
|
63
63
|
// =============================================================================
|
|
64
|
+
// System Prompt Builder
|
|
65
|
+
// =============================================================================
|
|
66
|
+
export {
|
|
67
|
+
// Builder
|
|
68
|
+
SystemPromptBuilder, buildSystemPrompt, detectGitRepository, getModuleStats,
|
|
69
|
+
// Module constants
|
|
70
|
+
ALL_MODULES, IDENTITY_MODULE, STYLE_MODULE, TASK_EXECUTION_MODULE, TODO_MANAGEMENT_MODULE, TOOL_USAGE_DIRECT_MODULE, TOOL_USAGE_META_MODULE, DELEGATION_MODULE, GIT_SAFETY_MODULE, SUGGEST_MODULE, IMPORTANT_RULES_MODULE, ENVIRONMENT_MODULE,
|
|
71
|
+
// Module utilities
|
|
72
|
+
shouldIncludeModule, getEstimatedTokensForConditions, getTotalEstimatedTokens, } from './system-prompt/index.js';
|
|
73
|
+
// =============================================================================
|
|
64
74
|
// Re-exports from @compilr-dev/agents (convenience — no need to install separately)
|
|
65
75
|
// =============================================================================
|
|
66
76
|
export {
|
|
@@ -84,6 +94,8 @@ TOOL_NAMES, getDefaultShellManager,
|
|
|
84
94
|
builtinSkills,
|
|
85
95
|
// Anchors
|
|
86
96
|
AnchorManager,
|
|
97
|
+
// MCP (class — used as value in dynamic imports)
|
|
98
|
+
MCPManager,
|
|
87
99
|
// Error types
|
|
88
100
|
AgentError, ProviderError, ToolError, ToolTimeoutError, MaxIterationsError, AbortError, } from '@compilr-dev/agents';
|
|
89
101
|
// =============================================================================
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Prompt Builder
|
|
3
|
+
*
|
|
4
|
+
* Assembles system prompt from modules based on current context.
|
|
5
|
+
* Provides ~50% token reduction by only including relevant modules.
|
|
6
|
+
*
|
|
7
|
+
* Git/CWD detection is injectable via SystemPromptContext for non-Node environments.
|
|
8
|
+
* Falls back to execSync detection in Node.js when not provided.
|
|
9
|
+
*/
|
|
10
|
+
import { type SystemPromptModule } from './modules.js';
|
|
11
|
+
/**
|
|
12
|
+
* Context used to determine which modules to include
|
|
13
|
+
*/
|
|
14
|
+
export interface SystemPromptContext {
|
|
15
|
+
/** Is the current directory a git repository? */
|
|
16
|
+
hasGit?: boolean;
|
|
17
|
+
/** Current workflow mode */
|
|
18
|
+
mode?: 'flexible' | 'guided' | 'plan';
|
|
19
|
+
/** Is there an active project? */
|
|
20
|
+
hasProject?: boolean;
|
|
21
|
+
/** Are meta-tools enabled? */
|
|
22
|
+
enableMetaTools?: boolean;
|
|
23
|
+
/** Does the agent have a role-specific identity? (team agents) */
|
|
24
|
+
hasRoleIdentity?: boolean;
|
|
25
|
+
/** Active project name (for explicit identification) */
|
|
26
|
+
projectName?: string;
|
|
27
|
+
/** Project context from COMPILR.md (appended at end) */
|
|
28
|
+
projectContext?: string;
|
|
29
|
+
/** Guided mode context (appended at end) */
|
|
30
|
+
guidedModeContext?: string;
|
|
31
|
+
/** Plan mode context (appended at end) */
|
|
32
|
+
planModeContext?: string;
|
|
33
|
+
/** Meta-tools index (appended at end) */
|
|
34
|
+
metaToolsIndex?: string;
|
|
35
|
+
/** Working directory override (defaults to process.cwd()) */
|
|
36
|
+
cwd?: string;
|
|
37
|
+
/** Git user.name override (skips execSync detection) */
|
|
38
|
+
gitUserName?: string;
|
|
39
|
+
/** Git user.email override (skips execSync detection) */
|
|
40
|
+
gitUserEmail?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Build result with metadata for debugging
|
|
44
|
+
*/
|
|
45
|
+
export interface BuildResult {
|
|
46
|
+
/** The assembled system prompt */
|
|
47
|
+
prompt: string;
|
|
48
|
+
/** Modules that were included */
|
|
49
|
+
includedModules: string[];
|
|
50
|
+
/** Modules that were excluded (with reasons) */
|
|
51
|
+
excludedModules: Array<{
|
|
52
|
+
id: string;
|
|
53
|
+
reason: string;
|
|
54
|
+
}>;
|
|
55
|
+
/** Estimated token count */
|
|
56
|
+
estimatedTokens: number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Detect if a directory is a git repository.
|
|
60
|
+
* Uses execSync when available; returns false in non-Node environments.
|
|
61
|
+
*/
|
|
62
|
+
export declare function detectGitRepository(cwd?: string): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* SystemPromptBuilder - assembles modular system prompts
|
|
65
|
+
*/
|
|
66
|
+
export declare class SystemPromptBuilder {
|
|
67
|
+
private context;
|
|
68
|
+
private readonly modules;
|
|
69
|
+
constructor(context?: SystemPromptContext, modules?: SystemPromptModule[]);
|
|
70
|
+
/**
|
|
71
|
+
* Update context (e.g., when mode changes)
|
|
72
|
+
*/
|
|
73
|
+
setContext(context: Partial<SystemPromptContext>): void;
|
|
74
|
+
/**
|
|
75
|
+
* Get current context
|
|
76
|
+
*/
|
|
77
|
+
getContext(): SystemPromptContext;
|
|
78
|
+
/**
|
|
79
|
+
* Build the system prompt based on current context
|
|
80
|
+
*/
|
|
81
|
+
build(): BuildResult;
|
|
82
|
+
/**
|
|
83
|
+
* Build and return just the prompt string
|
|
84
|
+
*/
|
|
85
|
+
buildPrompt(): string;
|
|
86
|
+
/**
|
|
87
|
+
* Get estimated token count for current context
|
|
88
|
+
*/
|
|
89
|
+
getEstimatedTokens(): number;
|
|
90
|
+
/**
|
|
91
|
+
* Get a summary of what modules will be included/excluded
|
|
92
|
+
*/
|
|
93
|
+
getSummary(): {
|
|
94
|
+
included: string[];
|
|
95
|
+
excluded: Array<{
|
|
96
|
+
id: string;
|
|
97
|
+
reason: string;
|
|
98
|
+
}>;
|
|
99
|
+
estimatedTokens: number;
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Convenience function to build a system prompt
|
|
104
|
+
*/
|
|
105
|
+
export declare function buildSystemPrompt(context?: SystemPromptContext): string;
|
|
106
|
+
/**
|
|
107
|
+
* Get module stats for debugging
|
|
108
|
+
*/
|
|
109
|
+
export declare function getModuleStats(): {
|
|
110
|
+
totalModules: number;
|
|
111
|
+
conditionalModules: number;
|
|
112
|
+
alwaysIncludedModules: number;
|
|
113
|
+
maxTokens: number;
|
|
114
|
+
minTokens: number;
|
|
115
|
+
};
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Prompt Builder
|
|
3
|
+
*
|
|
4
|
+
* Assembles system prompt from modules based on current context.
|
|
5
|
+
* Provides ~50% token reduction by only including relevant modules.
|
|
6
|
+
*
|
|
7
|
+
* Git/CWD detection is injectable via SystemPromptContext for non-Node environments.
|
|
8
|
+
* Falls back to execSync detection in Node.js when not provided.
|
|
9
|
+
*/
|
|
10
|
+
import { ALL_MODULES, shouldIncludeModule, getEstimatedTokensForConditions, } from './modules.js';
|
|
11
|
+
/**
|
|
12
|
+
* Get git configuration (user.name and user.email).
|
|
13
|
+
* Returns provided overrides, or auto-detects via execSync in Node.js.
|
|
14
|
+
*/
|
|
15
|
+
function getGitConfig(context) {
|
|
16
|
+
// Use injected values if provided
|
|
17
|
+
if (context.gitUserName !== undefined && context.gitUserEmail !== undefined) {
|
|
18
|
+
return { userName: context.gitUserName, userEmail: context.gitUserEmail };
|
|
19
|
+
}
|
|
20
|
+
let userName = context.gitUserName ?? '(not set - commits will fail)';
|
|
21
|
+
let userEmail = context.gitUserEmail ?? '(not set - commits will fail)';
|
|
22
|
+
try {
|
|
23
|
+
// Dynamic import to avoid bundler issues in non-Node environments
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
25
|
+
const { execSync } = require('child_process');
|
|
26
|
+
if (context.gitUserName === undefined) {
|
|
27
|
+
try {
|
|
28
|
+
const name = execSync('git config --global user.name', {
|
|
29
|
+
encoding: 'utf8',
|
|
30
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
31
|
+
}).trim();
|
|
32
|
+
if (name)
|
|
33
|
+
userName = name;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// Not configured
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (context.gitUserEmail === undefined) {
|
|
40
|
+
try {
|
|
41
|
+
const email = execSync('git config --global user.email', {
|
|
42
|
+
encoding: 'utf8',
|
|
43
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
44
|
+
}).trim();
|
|
45
|
+
if (email)
|
|
46
|
+
userEmail = email;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Not configured
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// child_process not available (browser/edge runtime)
|
|
55
|
+
}
|
|
56
|
+
return { userName, userEmail };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Detect if a directory is a git repository.
|
|
60
|
+
* Uses execSync when available; returns false in non-Node environments.
|
|
61
|
+
*/
|
|
62
|
+
export function detectGitRepository(cwd) {
|
|
63
|
+
try {
|
|
64
|
+
// Dynamic import to avoid bundler issues in non-Node environments
|
|
65
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
66
|
+
const { execSync } = require('child_process');
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
68
|
+
const { existsSync } = require('fs');
|
|
69
|
+
const dir = cwd ?? process.cwd();
|
|
70
|
+
// Check for .git directory
|
|
71
|
+
if (existsSync(`${dir}/.git`)) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
// Also check via git command (handles worktrees, etc.)
|
|
75
|
+
execSync('git rev-parse --is-inside-work-tree', {
|
|
76
|
+
cwd: dir,
|
|
77
|
+
encoding: 'utf8',
|
|
78
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
79
|
+
});
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Replace placeholders in module content
|
|
88
|
+
*/
|
|
89
|
+
function replacePlaceholders(content, context) {
|
|
90
|
+
const gitConfig = getGitConfig(context);
|
|
91
|
+
let cwd;
|
|
92
|
+
try {
|
|
93
|
+
cwd = context.cwd ?? process.cwd();
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
cwd = context.cwd ?? '(unknown)';
|
|
97
|
+
}
|
|
98
|
+
return content
|
|
99
|
+
.replace('{{CWD}}', cwd)
|
|
100
|
+
.replace('{{GIT_USER_NAME}}', gitConfig.userName)
|
|
101
|
+
.replace('{{GIT_USER_EMAIL}}', gitConfig.userEmail);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* SystemPromptBuilder - assembles modular system prompts
|
|
105
|
+
*/
|
|
106
|
+
export class SystemPromptBuilder {
|
|
107
|
+
context;
|
|
108
|
+
modules;
|
|
109
|
+
constructor(context = {}, modules) {
|
|
110
|
+
// Auto-detect git if not specified
|
|
111
|
+
this.context = {
|
|
112
|
+
...context,
|
|
113
|
+
hasGit: context.hasGit ?? detectGitRepository(context.cwd),
|
|
114
|
+
};
|
|
115
|
+
this.modules = modules ?? ALL_MODULES;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Update context (e.g., when mode changes)
|
|
119
|
+
*/
|
|
120
|
+
setContext(context) {
|
|
121
|
+
this.context = { ...this.context, ...context };
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Get current context
|
|
125
|
+
*/
|
|
126
|
+
getContext() {
|
|
127
|
+
return { ...this.context };
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Build the system prompt based on current context
|
|
131
|
+
*/
|
|
132
|
+
build() {
|
|
133
|
+
const includedModules = [];
|
|
134
|
+
const excludedModules = [];
|
|
135
|
+
const parts = [];
|
|
136
|
+
// Process each module
|
|
137
|
+
for (const module of this.modules) {
|
|
138
|
+
if (shouldIncludeModule(module, this.context)) {
|
|
139
|
+
includedModules.push(module.id);
|
|
140
|
+
parts.push(replacePlaceholders(module.content, this.context));
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
// Determine reason for exclusion
|
|
144
|
+
let reason = 'Unknown';
|
|
145
|
+
if (module.conditions?.hasGit && !this.context.hasGit) {
|
|
146
|
+
reason = 'Not a git repository';
|
|
147
|
+
}
|
|
148
|
+
else if (module.conditions?.enableMetaTools && !this.context.enableMetaTools) {
|
|
149
|
+
reason = 'Meta-tools not enabled';
|
|
150
|
+
}
|
|
151
|
+
else if (module.conditions?.modes && this.context.mode) {
|
|
152
|
+
reason = `Mode is ${this.context.mode}, requires ${module.conditions.modes.join('/')}`;
|
|
153
|
+
}
|
|
154
|
+
else if (module.conditions?.hasProject && !this.context.hasProject) {
|
|
155
|
+
reason = 'No active project';
|
|
156
|
+
}
|
|
157
|
+
excludedModules.push({ id: module.id, reason });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Join modules with separators
|
|
161
|
+
let prompt = parts.join('\n\n---\n\n');
|
|
162
|
+
// Append meta-tools index if provided
|
|
163
|
+
if (this.context.metaToolsIndex) {
|
|
164
|
+
prompt += `\n\n---\n\n${this.context.metaToolsIndex}`;
|
|
165
|
+
}
|
|
166
|
+
// Append project context if provided
|
|
167
|
+
if (this.context.projectContext) {
|
|
168
|
+
const projectHeader = this.context.projectName
|
|
169
|
+
? `## Project Context (${this.context.projectName})`
|
|
170
|
+
: '## Project Context';
|
|
171
|
+
prompt += `\n\n---\n\n${projectHeader}\n\nThe following is project-specific context loaded from COMPILR.md:\n\n${this.context.projectContext}`;
|
|
172
|
+
}
|
|
173
|
+
else if (this.context.projectName) {
|
|
174
|
+
prompt += `\n\n---\n\n## Active Project\n\nThe current project is: **${this.context.projectName}**`;
|
|
175
|
+
}
|
|
176
|
+
// Append guided mode context if provided
|
|
177
|
+
if (this.context.guidedModeContext) {
|
|
178
|
+
prompt += `\n\n---\n\n${this.context.guidedModeContext}`;
|
|
179
|
+
}
|
|
180
|
+
// Append plan mode context if provided
|
|
181
|
+
if (this.context.planModeContext) {
|
|
182
|
+
prompt += `\n\n---\n\n${this.context.planModeContext}`;
|
|
183
|
+
}
|
|
184
|
+
// Calculate estimated tokens
|
|
185
|
+
const baseTokens = getEstimatedTokensForConditions(this.context);
|
|
186
|
+
// Rough estimate for appended contexts (4 chars ≈ 1 token)
|
|
187
|
+
const appendedTokens = Math.ceil(((this.context.projectContext?.length ?? 0) +
|
|
188
|
+
(this.context.guidedModeContext?.length ?? 0) +
|
|
189
|
+
(this.context.planModeContext?.length ?? 0) +
|
|
190
|
+
(this.context.metaToolsIndex?.length ?? 0)) /
|
|
191
|
+
4);
|
|
192
|
+
return {
|
|
193
|
+
prompt,
|
|
194
|
+
includedModules,
|
|
195
|
+
excludedModules,
|
|
196
|
+
estimatedTokens: baseTokens + appendedTokens,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Build and return just the prompt string
|
|
201
|
+
*/
|
|
202
|
+
buildPrompt() {
|
|
203
|
+
return this.build().prompt;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Get estimated token count for current context
|
|
207
|
+
*/
|
|
208
|
+
getEstimatedTokens() {
|
|
209
|
+
return this.build().estimatedTokens;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Get a summary of what modules will be included/excluded
|
|
213
|
+
*/
|
|
214
|
+
getSummary() {
|
|
215
|
+
const result = this.build();
|
|
216
|
+
return {
|
|
217
|
+
included: result.includedModules,
|
|
218
|
+
excluded: result.excludedModules,
|
|
219
|
+
estimatedTokens: result.estimatedTokens,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Convenience function to build a system prompt
|
|
225
|
+
*/
|
|
226
|
+
export function buildSystemPrompt(context = {}) {
|
|
227
|
+
const builder = new SystemPromptBuilder(context);
|
|
228
|
+
return builder.buildPrompt();
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Get module stats for debugging
|
|
232
|
+
*/
|
|
233
|
+
export function getModuleStats() {
|
|
234
|
+
const conditional = ALL_MODULES.filter((m) => m.conditions);
|
|
235
|
+
const always = ALL_MODULES.filter((m) => !m.conditions);
|
|
236
|
+
// Max: all modules
|
|
237
|
+
const maxTokens = getEstimatedTokensForConditions({
|
|
238
|
+
hasGit: true,
|
|
239
|
+
enableMetaTools: true,
|
|
240
|
+
hasProject: true,
|
|
241
|
+
});
|
|
242
|
+
// Min: no conditional modules
|
|
243
|
+
const minTokens = getEstimatedTokensForConditions({
|
|
244
|
+
hasGit: false,
|
|
245
|
+
enableMetaTools: false,
|
|
246
|
+
hasProject: false,
|
|
247
|
+
});
|
|
248
|
+
return {
|
|
249
|
+
totalModules: ALL_MODULES.length,
|
|
250
|
+
conditionalModules: conditional.length,
|
|
251
|
+
alwaysIncludedModules: always.length,
|
|
252
|
+
maxTokens,
|
|
253
|
+
minTokens,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modular System Prompt
|
|
3
|
+
*
|
|
4
|
+
* Token-optimized system prompt that only includes relevant modules
|
|
5
|
+
* based on current context (git repo, mode, project, etc.).
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { SystemPromptBuilder, buildSystemPrompt } from '@compilr-dev/sdk';
|
|
10
|
+
*
|
|
11
|
+
* // Simple usage
|
|
12
|
+
* const prompt = buildSystemPrompt({ hasGit: true, enableMetaTools: true });
|
|
13
|
+
*
|
|
14
|
+
* // Builder pattern for more control
|
|
15
|
+
* const builder = new SystemPromptBuilder({ hasGit: true });
|
|
16
|
+
* builder.setContext({ enableMetaTools: true, projectContext: '...' });
|
|
17
|
+
* const result = builder.build();
|
|
18
|
+
* console.log(`Included: ${result.includedModules.join(', ')}`);
|
|
19
|
+
* console.log(`Est. tokens: ${result.estimatedTokens}`);
|
|
20
|
+
*
|
|
21
|
+
* // Injectable context (for non-Node environments)
|
|
22
|
+
* const prompt2 = buildSystemPrompt({
|
|
23
|
+
* hasGit: true,
|
|
24
|
+
* cwd: '/app',
|
|
25
|
+
* gitUserName: 'Alice',
|
|
26
|
+
* gitUserEmail: 'alice@example.com',
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* // Custom modules
|
|
30
|
+
* const builder2 = new SystemPromptBuilder({}, [STYLE_MODULE, TASK_EXECUTION_MODULE]);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export { SystemPromptBuilder, buildSystemPrompt, detectGitRepository, getModuleStats, type SystemPromptContext, type BuildResult, } from './builder.js';
|
|
34
|
+
export { ALL_MODULES, IDENTITY_MODULE, STYLE_MODULE, TASK_EXECUTION_MODULE, TODO_MANAGEMENT_MODULE, TOOL_USAGE_DIRECT_MODULE, TOOL_USAGE_META_MODULE, DELEGATION_MODULE, GIT_SAFETY_MODULE, SUGGEST_MODULE, IMPORTANT_RULES_MODULE, ENVIRONMENT_MODULE, shouldIncludeModule, getEstimatedTokensForConditions, getTotalEstimatedTokens, type SystemPromptModule, type ModuleConditions, } from './modules.js';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modular System Prompt
|
|
3
|
+
*
|
|
4
|
+
* Token-optimized system prompt that only includes relevant modules
|
|
5
|
+
* based on current context (git repo, mode, project, etc.).
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { SystemPromptBuilder, buildSystemPrompt } from '@compilr-dev/sdk';
|
|
10
|
+
*
|
|
11
|
+
* // Simple usage
|
|
12
|
+
* const prompt = buildSystemPrompt({ hasGit: true, enableMetaTools: true });
|
|
13
|
+
*
|
|
14
|
+
* // Builder pattern for more control
|
|
15
|
+
* const builder = new SystemPromptBuilder({ hasGit: true });
|
|
16
|
+
* builder.setContext({ enableMetaTools: true, projectContext: '...' });
|
|
17
|
+
* const result = builder.build();
|
|
18
|
+
* console.log(`Included: ${result.includedModules.join(', ')}`);
|
|
19
|
+
* console.log(`Est. tokens: ${result.estimatedTokens}`);
|
|
20
|
+
*
|
|
21
|
+
* // Injectable context (for non-Node environments)
|
|
22
|
+
* const prompt2 = buildSystemPrompt({
|
|
23
|
+
* hasGit: true,
|
|
24
|
+
* cwd: '/app',
|
|
25
|
+
* gitUserName: 'Alice',
|
|
26
|
+
* gitUserEmail: 'alice@example.com',
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* // Custom modules
|
|
30
|
+
* const builder2 = new SystemPromptBuilder({}, [STYLE_MODULE, TASK_EXECUTION_MODULE]);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export { SystemPromptBuilder, buildSystemPrompt, detectGitRepository, getModuleStats, } from './builder.js';
|
|
34
|
+
export { ALL_MODULES, IDENTITY_MODULE, STYLE_MODULE, TASK_EXECUTION_MODULE, TODO_MANAGEMENT_MODULE, TOOL_USAGE_DIRECT_MODULE, TOOL_USAGE_META_MODULE, DELEGATION_MODULE, GIT_SAFETY_MODULE, SUGGEST_MODULE, IMPORTANT_RULES_MODULE, ENVIRONMENT_MODULE, shouldIncludeModule, getEstimatedTokensForConditions, getTotalEstimatedTokens, } from './modules.js';
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Prompt Modules
|
|
3
|
+
*
|
|
4
|
+
* Modular system prompt for token optimization.
|
|
5
|
+
* Each module has content and optional conditions for inclusion.
|
|
6
|
+
*
|
|
7
|
+
* Token savings: ~50% reduction on average by only including relevant modules.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Conditions that determine if a module should be included
|
|
11
|
+
*/
|
|
12
|
+
export interface ModuleConditions {
|
|
13
|
+
/** Include only if in a git repository */
|
|
14
|
+
hasGit?: boolean;
|
|
15
|
+
/** Include only in these workflow modes */
|
|
16
|
+
modes?: ('flexible' | 'guided' | 'plan')[];
|
|
17
|
+
/** Include only if there's an active project */
|
|
18
|
+
hasProject?: boolean;
|
|
19
|
+
/** Include only if meta-tools are enabled */
|
|
20
|
+
enableMetaTools?: boolean;
|
|
21
|
+
/** Include only if NO role identity is specified (for default identity module) */
|
|
22
|
+
noRoleIdentity?: boolean;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A system prompt module
|
|
26
|
+
*/
|
|
27
|
+
export interface SystemPromptModule {
|
|
28
|
+
/** Unique identifier */
|
|
29
|
+
id: string;
|
|
30
|
+
/** Human-readable name */
|
|
31
|
+
name: string;
|
|
32
|
+
/** The actual prompt content */
|
|
33
|
+
content: string;
|
|
34
|
+
/** Conditions for inclusion (empty = always include) */
|
|
35
|
+
conditions?: ModuleConditions;
|
|
36
|
+
/** Estimated token count (for debugging/optimization) */
|
|
37
|
+
estimatedTokens: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Default identity module - only included when NO role is specified
|
|
41
|
+
* When a specialized role (pm, arch, qa, etc.) is used, this is skipped
|
|
42
|
+
* and the role's identity is prepended instead.
|
|
43
|
+
*/
|
|
44
|
+
export declare const IDENTITY_MODULE: SystemPromptModule;
|
|
45
|
+
/**
|
|
46
|
+
* Style module - always included
|
|
47
|
+
* Defines tone, style, and behavioral guidelines that apply to ALL agents
|
|
48
|
+
*/
|
|
49
|
+
export declare const STYLE_MODULE: SystemPromptModule;
|
|
50
|
+
/**
|
|
51
|
+
* Task execution module - always included
|
|
52
|
+
* Defines how to approach coding tasks
|
|
53
|
+
*/
|
|
54
|
+
export declare const TASK_EXECUTION_MODULE: SystemPromptModule;
|
|
55
|
+
/**
|
|
56
|
+
* Todo management module - always included
|
|
57
|
+
* Defines how to use the todo_write tool
|
|
58
|
+
*/
|
|
59
|
+
export declare const TODO_MANAGEMENT_MODULE: SystemPromptModule;
|
|
60
|
+
/**
|
|
61
|
+
* Tool usage module (direct tools) - always included
|
|
62
|
+
* Lists tools that are always available
|
|
63
|
+
*/
|
|
64
|
+
export declare const TOOL_USAGE_DIRECT_MODULE: SystemPromptModule;
|
|
65
|
+
/**
|
|
66
|
+
* Tool usage module (meta-tools) - only if enableMetaTools=true
|
|
67
|
+
* Explains how to use specialized tools via meta-tools
|
|
68
|
+
*/
|
|
69
|
+
export declare const TOOL_USAGE_META_MODULE: SystemPromptModule;
|
|
70
|
+
/**
|
|
71
|
+
* Token delegation module - always included
|
|
72
|
+
* CRITICAL for token efficiency - teaches agent to use sub-agents
|
|
73
|
+
*/
|
|
74
|
+
export declare const DELEGATION_MODULE: SystemPromptModule;
|
|
75
|
+
/**
|
|
76
|
+
* Git safety module - only if hasGit=true
|
|
77
|
+
* Defines safety rules for git operations
|
|
78
|
+
*/
|
|
79
|
+
export declare const GIT_SAFETY_MODULE: SystemPromptModule;
|
|
80
|
+
/**
|
|
81
|
+
* Suggest module - always included
|
|
82
|
+
* Defines how to use the suggest tool
|
|
83
|
+
*/
|
|
84
|
+
export declare const SUGGEST_MODULE: SystemPromptModule;
|
|
85
|
+
/**
|
|
86
|
+
* Important rules module - always included
|
|
87
|
+
* Summary of critical rules
|
|
88
|
+
*/
|
|
89
|
+
export declare const IMPORTANT_RULES_MODULE: SystemPromptModule;
|
|
90
|
+
/**
|
|
91
|
+
* Environment module - always included
|
|
92
|
+
* Current working directory and git config
|
|
93
|
+
* Note: {{PLACEHOLDERS}} are replaced at runtime
|
|
94
|
+
*/
|
|
95
|
+
export declare const ENVIRONMENT_MODULE: SystemPromptModule;
|
|
96
|
+
/**
|
|
97
|
+
* All modules in the order they should appear in the prompt.
|
|
98
|
+
* Modules without conditions are always included.
|
|
99
|
+
*/
|
|
100
|
+
export declare const ALL_MODULES: SystemPromptModule[];
|
|
101
|
+
/**
|
|
102
|
+
* Get total estimated tokens for all modules
|
|
103
|
+
*/
|
|
104
|
+
export declare function getTotalEstimatedTokens(): number;
|
|
105
|
+
/**
|
|
106
|
+
* Get estimated tokens for modules that match given conditions
|
|
107
|
+
*/
|
|
108
|
+
export declare function getEstimatedTokensForConditions(conditions: {
|
|
109
|
+
hasGit?: boolean;
|
|
110
|
+
enableMetaTools?: boolean;
|
|
111
|
+
mode?: 'flexible' | 'guided' | 'plan';
|
|
112
|
+
hasProject?: boolean;
|
|
113
|
+
hasRoleIdentity?: boolean;
|
|
114
|
+
}): number;
|
|
115
|
+
/**
|
|
116
|
+
* Check if a module should be included based on conditions
|
|
117
|
+
*/
|
|
118
|
+
export declare function shouldIncludeModule(module: SystemPromptModule, context: {
|
|
119
|
+
hasGit?: boolean;
|
|
120
|
+
enableMetaTools?: boolean;
|
|
121
|
+
mode?: 'flexible' | 'guided' | 'plan';
|
|
122
|
+
hasProject?: boolean;
|
|
123
|
+
hasRoleIdentity?: boolean;
|
|
124
|
+
}): boolean;
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* System Prompt Modules
|
|
3
|
+
*
|
|
4
|
+
* Modular system prompt for token optimization.
|
|
5
|
+
* Each module has content and optional conditions for inclusion.
|
|
6
|
+
*
|
|
7
|
+
* Token savings: ~50% reduction on average by only including relevant modules.
|
|
8
|
+
*/
|
|
9
|
+
// =============================================================================
|
|
10
|
+
// MODULE DEFINITIONS
|
|
11
|
+
// =============================================================================
|
|
12
|
+
/**
|
|
13
|
+
* Default identity module - only included when NO role is specified
|
|
14
|
+
* When a specialized role (pm, arch, qa, etc.) is used, this is skipped
|
|
15
|
+
* and the role's identity is prepended instead.
|
|
16
|
+
*/
|
|
17
|
+
export const IDENTITY_MODULE = {
|
|
18
|
+
id: 'identity',
|
|
19
|
+
name: 'Default Identity',
|
|
20
|
+
estimatedTokens: 50,
|
|
21
|
+
conditions: {
|
|
22
|
+
noRoleIdentity: true, // Only include if no role identity is specified
|
|
23
|
+
},
|
|
24
|
+
content: `You are a coding assistant running in a terminal CLI.
|
|
25
|
+
|
|
26
|
+
You help users with software engineering tasks: writing code, debugging, refactoring, explaining concepts, managing projects, and more.`,
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Style module - always included
|
|
30
|
+
* Defines tone, style, and behavioral guidelines that apply to ALL agents
|
|
31
|
+
*/
|
|
32
|
+
export const STYLE_MODULE = {
|
|
33
|
+
id: 'style',
|
|
34
|
+
name: 'Tone and Style',
|
|
35
|
+
estimatedTokens: 150,
|
|
36
|
+
content: `## Tone and Style
|
|
37
|
+
|
|
38
|
+
- Your output displays in a terminal. Keep responses short and concise.
|
|
39
|
+
- Use GitHub-flavored markdown for formatting.
|
|
40
|
+
- Only use emojis if the user explicitly requests them.
|
|
41
|
+
- Output text to communicate. Never use tools (like bash echo) to communicate.
|
|
42
|
+
- NEVER create files unless absolutely necessary. Always prefer editing existing files.
|
|
43
|
+
- When referencing code, include file path and line number: src/utils.ts:42
|
|
44
|
+
|
|
45
|
+
## Professional Objectivity
|
|
46
|
+
|
|
47
|
+
Prioritize technical accuracy over validating the user's beliefs. Provide direct, objective technical info without unnecessary praise or emotional validation. Disagree when necessary - objective guidance is more valuable than false agreement.
|
|
48
|
+
|
|
49
|
+
Avoid phrases like "You're absolutely right!" or "Great question!" - just answer directly.
|
|
50
|
+
|
|
51
|
+
## No Time Estimates
|
|
52
|
+
|
|
53
|
+
Never predict how long tasks will take. Avoid phrases like "this will take a few minutes" or "quick fix". Focus on what needs to be done, not duration.`,
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Task execution module - always included
|
|
57
|
+
* Defines how to approach coding tasks
|
|
58
|
+
*/
|
|
59
|
+
export const TASK_EXECUTION_MODULE = {
|
|
60
|
+
id: 'task-execution',
|
|
61
|
+
name: 'Task Execution',
|
|
62
|
+
estimatedTokens: 150,
|
|
63
|
+
content: `## Doing Tasks
|
|
64
|
+
|
|
65
|
+
When the user requests software engineering work:
|
|
66
|
+
|
|
67
|
+
1. **Read before modifying**: NEVER propose changes to code you haven't read. Always read files first.
|
|
68
|
+
2. **Use todo_write for complex tasks**: Track progress on multi-step work (3+ steps).
|
|
69
|
+
3. **Avoid over-engineering**:
|
|
70
|
+
- Only make changes that are directly requested
|
|
71
|
+
- Don't add features beyond what was asked
|
|
72
|
+
- Don't add error handling for scenarios that can't happen
|
|
73
|
+
- Don't create abstractions for one-time operations
|
|
74
|
+
- Three similar lines is better than a premature abstraction
|
|
75
|
+
4. **Security awareness**: Don't introduce vulnerabilities (injection, XSS, SQL injection). If you notice insecure code, fix it immediately.
|
|
76
|
+
5. **Clean up completely**: If something is unused, delete it. No backwards-compatibility hacks.`,
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Todo management module - always included
|
|
80
|
+
* Defines how to use the todo_write tool
|
|
81
|
+
*/
|
|
82
|
+
export const TODO_MANAGEMENT_MODULE = {
|
|
83
|
+
id: 'todo-management',
|
|
84
|
+
name: 'Todo Management',
|
|
85
|
+
estimatedTokens: 250,
|
|
86
|
+
content: `## Task Management (todo_write)
|
|
87
|
+
|
|
88
|
+
Use todo_write to track progress on multi-step tasks.
|
|
89
|
+
|
|
90
|
+
When to use:
|
|
91
|
+
- Tasks with 3+ distinct steps
|
|
92
|
+
- User provides multiple tasks
|
|
93
|
+
- Complex work requiring planning
|
|
94
|
+
|
|
95
|
+
When NOT to use:
|
|
96
|
+
- Single, trivial tasks
|
|
97
|
+
- Purely informational questions
|
|
98
|
+
- Tasks completable in 1-2 steps
|
|
99
|
+
|
|
100
|
+
### Task Dependencies (blockedBy)
|
|
101
|
+
|
|
102
|
+
Use the \`blockedBy\` field to declare dependencies between tasks. Values are 1-based task positions in the array.
|
|
103
|
+
When a task cannot start until another finishes, set blockedBy to indicate the dependency. This helps track execution order.
|
|
104
|
+
|
|
105
|
+
Example: Task #3 depends on #1 and #2:
|
|
106
|
+
\`\`\`
|
|
107
|
+
{ content: "Run tests", status: "pending", blockedBy: [1, 2] }
|
|
108
|
+
\`\`\`
|
|
109
|
+
Completed tasks automatically move to the bottom of the displayed list.
|
|
110
|
+
|
|
111
|
+
### Example: When to use todo_write
|
|
112
|
+
|
|
113
|
+
User: Fix the type errors and run the tests
|
|
114
|
+
Assistant: I'll track this multi-step task:
|
|
115
|
+
[Uses todo_write: "Fix type errors", "Run tests" (blockedBy: [1])]
|
|
116
|
+
[Marks "Fix type errors" as in_progress]
|
|
117
|
+
[Reads files, fixes errors]
|
|
118
|
+
[Marks "Fix type errors" complete, "Run tests" in_progress]
|
|
119
|
+
[Runs tests]
|
|
120
|
+
[Marks "Run tests" complete]
|
|
121
|
+
|
|
122
|
+
### Example: When NOT to use todo_write
|
|
123
|
+
|
|
124
|
+
User: What does this function do?
|
|
125
|
+
Assistant: [Reads the file and explains directly - no todo needed for a simple question]`,
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Tool usage module (direct tools) - always included
|
|
129
|
+
* Lists tools that are always available
|
|
130
|
+
*/
|
|
131
|
+
export const TOOL_USAGE_DIRECT_MODULE = {
|
|
132
|
+
id: 'tool-usage-direct',
|
|
133
|
+
name: 'Tool Usage (Direct)',
|
|
134
|
+
estimatedTokens: 100,
|
|
135
|
+
content: `## Tool Usage
|
|
136
|
+
|
|
137
|
+
IMPORTANT: Tool names are lowercase with underscores.
|
|
138
|
+
|
|
139
|
+
### Direct Tools (always available)
|
|
140
|
+
- **File operations**: read_file, write_file, edit, glob, grep
|
|
141
|
+
- **Shell**: bash (use run_in_background=true for long-running), bash_output, kill_shell
|
|
142
|
+
- **Task management**: todo_write, todo_read
|
|
143
|
+
- **User interaction**: ask_user, ask_user_simple
|
|
144
|
+
- **Sub-agents**: task (types: explore, code-review, plan, debug, test-runner, refactor, security-audit, general)`,
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Tool usage module (meta-tools) - only if enableMetaTools=true
|
|
148
|
+
* Explains how to use specialized tools via meta-tools
|
|
149
|
+
*/
|
|
150
|
+
export const TOOL_USAGE_META_MODULE = {
|
|
151
|
+
id: 'tool-usage-meta',
|
|
152
|
+
name: 'Tool Usage (Meta)',
|
|
153
|
+
estimatedTokens: 250,
|
|
154
|
+
conditions: { enableMetaTools: true },
|
|
155
|
+
content: `### Specialized Tools
|
|
156
|
+
|
|
157
|
+
These are **CLI system tools** — they operate on the Compilr CLI's internal database, NOT on the user's application. Never confuse them with the user's project backend (e.g., localhost servers).
|
|
158
|
+
|
|
159
|
+
Key categories:
|
|
160
|
+
- **Git**: git_status, git_diff, git_log, git_commit, git_branch
|
|
161
|
+
- **Project Management**: project_get, project_list, project_create, project_update
|
|
162
|
+
- **Work Items**: workitem_query, workitem_add, workitem_update, workitem_next
|
|
163
|
+
- **Documents**: project_document_add, project_document_get, project_document_list
|
|
164
|
+
- **Planning**: plan_create, plan_get, plan_list
|
|
165
|
+
- **Runners**: run_tests, run_lint
|
|
166
|
+
- **Anchors**: anchor_add, anchor_list, anchor_remove
|
|
167
|
+
|
|
168
|
+
### Document Storage (CRITICAL)
|
|
169
|
+
|
|
170
|
+
Project documents (PRD, architecture, design, notes) are stored in the **database**, not the filesystem.
|
|
171
|
+
- **Read**: \`project_document_get({ doc_type: "prd" })\` or \`project_document_list()\`
|
|
172
|
+
- **Write**: \`project_document_add({ doc_type: "prd", title: "...", content: "..." })\`
|
|
173
|
+
- Do NOT use write_file or edit for project documents — always use these database tools
|
|
174
|
+
- Valid doc_types: prd, architecture, design, notes, session-note`,
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Token delegation module - always included
|
|
178
|
+
* CRITICAL for token efficiency - teaches agent to use sub-agents
|
|
179
|
+
*/
|
|
180
|
+
export const DELEGATION_MODULE = {
|
|
181
|
+
id: 'delegation',
|
|
182
|
+
name: 'Token Efficiency & Delegation',
|
|
183
|
+
estimatedTokens: 200,
|
|
184
|
+
content: `## Token Efficiency & Delegation
|
|
185
|
+
|
|
186
|
+
Use the **task** tool (sub-agent) for:
|
|
187
|
+
- **File exploration**: "find files", "what's in this directory", "explore codebase"
|
|
188
|
+
- **Code search**: "where is X defined", "find usages of Y"
|
|
189
|
+
- **Analysis**: "analyze module", "understand architecture", "review code"
|
|
190
|
+
- **Multi-file operations**: Tasks touching 5+ files
|
|
191
|
+
|
|
192
|
+
### Rules
|
|
193
|
+
1. Exploration/search questions → task(explore)
|
|
194
|
+
2. Code review → task(code-review)
|
|
195
|
+
3. Planning → task(plan)
|
|
196
|
+
4. Simple answers (no file access) → respond directly
|
|
197
|
+
5. Code edits → do it yourself (never delegate edits)`,
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* Git safety module - only if hasGit=true
|
|
201
|
+
* Defines safety rules for git operations
|
|
202
|
+
*/
|
|
203
|
+
export const GIT_SAFETY_MODULE = {
|
|
204
|
+
id: 'git-safety',
|
|
205
|
+
name: 'Git Safety Protocol',
|
|
206
|
+
estimatedTokens: 300,
|
|
207
|
+
conditions: { hasGit: true },
|
|
208
|
+
content: `## Git Safety Protocol
|
|
209
|
+
|
|
210
|
+
When working with git:
|
|
211
|
+
|
|
212
|
+
1. **Never update git config** without explicit user request
|
|
213
|
+
2. **Never force push** to main/master - warn if requested
|
|
214
|
+
3. **Never use --amend** unless:
|
|
215
|
+
- User explicitly requested it, AND
|
|
216
|
+
- Commit was created by you in this session, AND
|
|
217
|
+
- Commit has NOT been pushed to remote
|
|
218
|
+
4. **Check before destructive operations**:
|
|
219
|
+
- git reset --hard (loses uncommitted changes)
|
|
220
|
+
- git checkout -- file (discards local changes)
|
|
221
|
+
- git clean (deletes untracked files)
|
|
222
|
+
5. **Only commit when asked** - don't commit proactively
|
|
223
|
+
|
|
224
|
+
### Commit Workflow
|
|
225
|
+
1. Run git_status to see changes
|
|
226
|
+
2. Run git_diff to review what will be committed
|
|
227
|
+
3. Check recent git_log for commit message style
|
|
228
|
+
4. Create focused commit with clear message
|
|
229
|
+
5. Never commit files with secrets (.env, credentials.json)`,
|
|
230
|
+
};
|
|
231
|
+
/**
|
|
232
|
+
* Suggest module - always included
|
|
233
|
+
* Defines how to use the suggest tool
|
|
234
|
+
*/
|
|
235
|
+
export const SUGGEST_MODULE = {
|
|
236
|
+
id: 'suggest',
|
|
237
|
+
name: 'Next Action Suggestions',
|
|
238
|
+
estimatedTokens: 100,
|
|
239
|
+
content: `## Next Action Suggestions
|
|
240
|
+
|
|
241
|
+
After completing a task, call the suggest tool to recommend the next action.
|
|
242
|
+
|
|
243
|
+
Good suggestions are short commands or actions:
|
|
244
|
+
- "run npm test"
|
|
245
|
+
- "commit the changes"
|
|
246
|
+
- "check the error log"
|
|
247
|
+
|
|
248
|
+
CALL the suggest tool - never write "suggest: ..." as text.`,
|
|
249
|
+
};
|
|
250
|
+
/**
|
|
251
|
+
* Important rules module - always included
|
|
252
|
+
* Summary of critical rules
|
|
253
|
+
*/
|
|
254
|
+
export const IMPORTANT_RULES_MODULE = {
|
|
255
|
+
id: 'important-rules',
|
|
256
|
+
name: 'Important Rules',
|
|
257
|
+
estimatedTokens: 200,
|
|
258
|
+
content: `## IMPORTANT RULES (read carefully)
|
|
259
|
+
|
|
260
|
+
1. Tool names are lowercase with underscores - use exactly as shown
|
|
261
|
+
2. ALWAYS read files before proposing changes to them
|
|
262
|
+
3. After calling a tool, respond with the result - never end silently
|
|
263
|
+
4. Use todo_write for multi-step tasks (3+ steps)
|
|
264
|
+
5. Don't over-engineer - implement exactly what was asked
|
|
265
|
+
6. Check for security issues - fix insecure code immediately
|
|
266
|
+
7. **DELEGATE exploration to sub-agents** - use task(explore) for file searches, code navigation, and analysis. NEVER accumulate exploration results in your own context.
|
|
267
|
+
8. Call suggest tool after completing tasks (don't write "suggest:" as text)
|
|
268
|
+
9. When user asks "what files...", "where is...", "find..." - ALWAYS use task(explore), not direct tool calls`,
|
|
269
|
+
};
|
|
270
|
+
/**
|
|
271
|
+
* Environment module - always included
|
|
272
|
+
* Current working directory and git config
|
|
273
|
+
* Note: {{PLACEHOLDERS}} are replaced at runtime
|
|
274
|
+
*/
|
|
275
|
+
export const ENVIRONMENT_MODULE = {
|
|
276
|
+
id: 'environment',
|
|
277
|
+
name: 'Environment Info',
|
|
278
|
+
estimatedTokens: 50,
|
|
279
|
+
content: `Current working directory: {{CWD}}
|
|
280
|
+
Git configuration:
|
|
281
|
+
- user.name: {{GIT_USER_NAME}}
|
|
282
|
+
- user.email: {{GIT_USER_EMAIL}}`,
|
|
283
|
+
};
|
|
284
|
+
// =============================================================================
|
|
285
|
+
// ALL MODULES (in order)
|
|
286
|
+
// =============================================================================
|
|
287
|
+
/**
|
|
288
|
+
* All modules in the order they should appear in the prompt.
|
|
289
|
+
* Modules without conditions are always included.
|
|
290
|
+
*/
|
|
291
|
+
export const ALL_MODULES = [
|
|
292
|
+
IDENTITY_MODULE, // Conditional: only when no role identity
|
|
293
|
+
STYLE_MODULE,
|
|
294
|
+
TASK_EXECUTION_MODULE,
|
|
295
|
+
TODO_MANAGEMENT_MODULE,
|
|
296
|
+
TOOL_USAGE_DIRECT_MODULE,
|
|
297
|
+
TOOL_USAGE_META_MODULE, // Conditional: enableMetaTools
|
|
298
|
+
DELEGATION_MODULE,
|
|
299
|
+
GIT_SAFETY_MODULE, // Conditional: hasGit
|
|
300
|
+
SUGGEST_MODULE,
|
|
301
|
+
IMPORTANT_RULES_MODULE,
|
|
302
|
+
ENVIRONMENT_MODULE,
|
|
303
|
+
];
|
|
304
|
+
/**
|
|
305
|
+
* Get total estimated tokens for all modules
|
|
306
|
+
*/
|
|
307
|
+
export function getTotalEstimatedTokens() {
|
|
308
|
+
return ALL_MODULES.reduce((sum, m) => sum + m.estimatedTokens, 0);
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Get estimated tokens for modules that match given conditions
|
|
312
|
+
*/
|
|
313
|
+
export function getEstimatedTokensForConditions(conditions) {
|
|
314
|
+
let total = 0;
|
|
315
|
+
for (const module of ALL_MODULES) {
|
|
316
|
+
if (shouldIncludeModule(module, conditions)) {
|
|
317
|
+
total += module.estimatedTokens;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return total;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Check if a module should be included based on conditions
|
|
324
|
+
*/
|
|
325
|
+
export function shouldIncludeModule(module, context) {
|
|
326
|
+
// No conditions = always include
|
|
327
|
+
if (!module.conditions) {
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
330
|
+
const { conditions } = module;
|
|
331
|
+
// Check noRoleIdentity condition - only include if NO role identity is specified
|
|
332
|
+
// This allows team agents to define their own identity without conflict
|
|
333
|
+
if (conditions.noRoleIdentity && context.hasRoleIdentity) {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
// Check hasGit condition
|
|
337
|
+
if (conditions.hasGit !== undefined && conditions.hasGit !== context.hasGit) {
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
// Check enableMetaTools condition
|
|
341
|
+
if (conditions.enableMetaTools !== undefined &&
|
|
342
|
+
conditions.enableMetaTools !== context.enableMetaTools) {
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
// Check modes condition
|
|
346
|
+
if (conditions.modes && context.mode) {
|
|
347
|
+
if (!conditions.modes.includes(context.mode)) {
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
// Check hasProject condition
|
|
352
|
+
if (conditions.hasProject !== undefined && conditions.hasProject !== context.hasProject) {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
return true;
|
|
356
|
+
}
|