@opensumi/ide-ai-native 3.9.1-next-1748593694.0 → 3.9.1-next-1748939097.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 (118) hide show
  1. package/lib/browser/chat/chat-model.d.ts.map +1 -1
  2. package/lib/browser/chat/chat-model.js +3 -1
  3. package/lib/browser/chat/chat-model.js.map +1 -1
  4. package/lib/browser/chat/chat-proxy.service.d.ts +0 -2
  5. package/lib/browser/chat/chat-proxy.service.d.ts.map +1 -1
  6. package/lib/browser/chat/chat-proxy.service.js +50 -57
  7. package/lib/browser/chat/chat-proxy.service.js.map +1 -1
  8. package/lib/browser/chat/chat.view.d.ts.map +1 -1
  9. package/lib/browser/chat/chat.view.js +11 -7
  10. package/lib/browser/chat/chat.view.js.map +1 -1
  11. package/lib/browser/components/ChatMentionInput.d.ts.map +1 -1
  12. package/lib/browser/components/ChatMentionInput.js +123 -27
  13. package/lib/browser/components/ChatMentionInput.js.map +1 -1
  14. package/lib/browser/components/ChatToolRender.module.less +1 -0
  15. package/lib/browser/components/components.module.less +7 -0
  16. package/lib/browser/components/mention-input/mention-input.d.ts.map +1 -1
  17. package/lib/browser/components/mention-input/mention-input.js +155 -13
  18. package/lib/browser/components/mention-input/mention-input.js.map +1 -1
  19. package/lib/browser/components/mention-input/mention-input.module.less +165 -0
  20. package/lib/browser/components/mention-input/types.d.ts +2 -1
  21. package/lib/browser/components/mention-input/types.d.ts.map +1 -1
  22. package/lib/browser/components/mention-input/types.js +1 -0
  23. package/lib/browser/components/mention-input/types.js.map +1 -1
  24. package/lib/browser/context/llm-context.service.d.ts +18 -2
  25. package/lib/browser/context/llm-context.service.d.ts.map +1 -1
  26. package/lib/browser/context/llm-context.service.js +168 -20
  27. package/lib/browser/context/llm-context.service.js.map +1 -1
  28. package/lib/browser/contrib/intelligent-completions/decoration/additions-deletions.decoration.d.ts.map +1 -1
  29. package/lib/browser/contrib/intelligent-completions/decoration/additions-deletions.decoration.js.map +1 -1
  30. package/lib/browser/contrib/intelligent-completions/diff-computer.js +1 -1
  31. package/lib/browser/contrib/intelligent-completions/diff-computer.js.map +1 -1
  32. package/lib/browser/contrib/terminal/terminal.feature.registry.js.map +1 -1
  33. package/lib/browser/index.d.ts.map +1 -1
  34. package/lib/browser/index.js +7 -0
  35. package/lib/browser/index.js.map +1 -1
  36. package/lib/browser/mcp/base-apply.service.d.ts +2 -2
  37. package/lib/browser/mcp/base-apply.service.d.ts.map +1 -1
  38. package/lib/browser/mcp/base-apply.service.js.map +1 -1
  39. package/lib/browser/mcp/tools/getDiagnosticsByPath.js.map +1 -1
  40. package/lib/browser/mcp/tools/getOpenEditorFileDiagnostics.js.map +1 -1
  41. package/lib/browser/mcp/tools/handlers/ListDir.js.map +1 -1
  42. package/lib/browser/mcp/tools/runTerminalCmd.js.map +1 -1
  43. package/lib/browser/preferences/schema.d.ts.map +1 -1
  44. package/lib/browser/preferences/schema.js +5 -0
  45. package/lib/browser/preferences/schema.js.map +1 -1
  46. package/lib/browser/rules/rules.contribution.d.ts +29 -0
  47. package/lib/browser/rules/rules.contribution.d.ts.map +1 -0
  48. package/lib/browser/rules/rules.contribution.js +94 -0
  49. package/lib/browser/rules/rules.contribution.js.map +1 -0
  50. package/lib/browser/rules/rules.module.less +174 -0
  51. package/lib/browser/rules/rules.service.d.ts +25 -0
  52. package/lib/browser/rules/rules.service.d.ts.map +1 -0
  53. package/lib/browser/rules/rules.service.js +180 -0
  54. package/lib/browser/rules/rules.service.js.map +1 -0
  55. package/lib/browser/rules/rules.view.d.ts +3 -0
  56. package/lib/browser/rules/rules.view.d.ts.map +1 -0
  57. package/lib/browser/rules/rules.view.js +76 -0
  58. package/lib/browser/rules/rules.view.js.map +1 -0
  59. package/lib/browser/widget/inline-stream-diff/live-preview.component.d.ts.map +1 -1
  60. package/lib/browser/widget/inline-stream-diff/live-preview.component.js.map +1 -1
  61. package/lib/common/MDC_PARSER_README.md +171 -0
  62. package/lib/common/index.d.ts +2 -0
  63. package/lib/common/index.d.ts.map +1 -1
  64. package/lib/common/index.js +2 -0
  65. package/lib/common/index.js.map +1 -1
  66. package/lib/common/llm-context.d.ts +19 -0
  67. package/lib/common/llm-context.d.ts.map +1 -1
  68. package/lib/common/llm-context.js.map +1 -1
  69. package/lib/common/mdc-parser.d.ts +60 -0
  70. package/lib/common/mdc-parser.d.ts.map +1 -0
  71. package/lib/common/mdc-parser.js +250 -0
  72. package/lib/common/mdc-parser.js.map +1 -0
  73. package/lib/common/prompts/context-prompt-provider.d.ts +0 -2
  74. package/lib/common/prompts/context-prompt-provider.d.ts.map +1 -1
  75. package/lib/common/prompts/context-prompt-provider.js +35 -29
  76. package/lib/common/prompts/context-prompt-provider.js.map +1 -1
  77. package/lib/common/prompts/system-prompt.d.ts +2 -0
  78. package/lib/common/prompts/system-prompt.d.ts.map +1 -0
  79. package/lib/common/prompts/system-prompt.js +5 -0
  80. package/lib/common/prompts/system-prompt.js.map +1 -0
  81. package/lib/common/types.d.ts +7 -0
  82. package/lib/common/types.d.ts.map +1 -1
  83. package/lib/node/base-language-model.d.ts.map +1 -1
  84. package/lib/node/base-language-model.js.map +1 -1
  85. package/package.json +24 -24
  86. package/src/browser/chat/chat-model.ts +3 -1
  87. package/src/browser/chat/chat-proxy.service.ts +68 -81
  88. package/src/browser/chat/chat.view.tsx +19 -7
  89. package/src/browser/components/ChatMentionInput.tsx +143 -31
  90. package/src/browser/components/ChatToolRender.module.less +1 -0
  91. package/src/browser/components/components.module.less +7 -0
  92. package/src/browser/components/mention-input/mention-input.module.less +165 -0
  93. package/src/browser/components/mention-input/mention-input.tsx +244 -29
  94. package/src/browser/components/mention-input/types.ts +1 -0
  95. package/src/browser/context/llm-context.service.ts +185 -21
  96. package/src/browser/contrib/intelligent-completions/decoration/additions-deletions.decoration.ts +1 -1
  97. package/src/browser/contrib/intelligent-completions/diff-computer.ts +1 -1
  98. package/src/browser/contrib/terminal/terminal.feature.registry.ts +1 -1
  99. package/src/browser/index.ts +8 -0
  100. package/src/browser/mcp/base-apply.service.ts +0 -1
  101. package/src/browser/mcp/tools/getDiagnosticsByPath.ts +1 -1
  102. package/src/browser/mcp/tools/getOpenEditorFileDiagnostics.ts +1 -1
  103. package/src/browser/mcp/tools/handlers/ListDir.ts +1 -1
  104. package/src/browser/mcp/tools/runTerminalCmd.ts +1 -1
  105. package/src/browser/preferences/schema.ts +5 -0
  106. package/src/browser/rules/rules.contribution.ts +105 -0
  107. package/src/browser/rules/rules.module.less +174 -0
  108. package/src/browser/rules/rules.service.ts +189 -0
  109. package/src/browser/rules/rules.view.tsx +127 -0
  110. package/src/browser/widget/inline-stream-diff/live-preview.component.tsx +0 -1
  111. package/src/common/MDC_PARSER_README.md +171 -0
  112. package/src/common/index.ts +3 -0
  113. package/src/common/llm-context.ts +23 -0
  114. package/src/common/mdc-parser.ts +298 -0
  115. package/src/common/prompts/context-prompt-provider.ts +55 -40
  116. package/src/common/prompts/system-prompt.ts +2 -0
  117. package/src/common/types.ts +8 -0
  118. package/src/node/base-language-model.ts +0 -1
@@ -1,5 +1,7 @@
1
1
  import { Event, URI } from '@opensumi/ide-core-common/lib/utils';
2
2
 
3
+ import { ProjectRule } from './types';
4
+
3
5
  export interface LLMContextService {
4
6
  /**
5
7
  * 开始自动收集
@@ -21,6 +23,11 @@ export interface LLMContextService {
21
23
  */
22
24
  addFolderToContext(uri: URI, isManual?: boolean): void;
23
25
 
26
+ /**
27
+ * 添加规则到 context 中
28
+ */
29
+ addRuleToContext(uri: URI, isManual?: boolean): void;
30
+
24
31
  /**
25
32
  * 清除上下文
26
33
  */
@@ -33,6 +40,7 @@ export interface LLMContextService {
33
40
  viewed: FileContext[];
34
41
  attached: FileContext[];
35
42
  attachedFolders: FileContext[];
43
+ attachedRules: ProjectRule[];
36
44
  version: number;
37
45
  }>;
38
46
 
@@ -42,6 +50,18 @@ export interface LLMContextService {
42
50
  */
43
51
  removeFileFromContext(uri: URI, isManual?: boolean): void;
44
52
 
53
+ /**
54
+ * 从 context 中移除文件夹
55
+ * @param uri URI
56
+ */
57
+ removeFolderFromContext(uri: URI): void;
58
+
59
+ /**
60
+ * 从 context 中移除规则
61
+ * @param uri URI
62
+ */
63
+ removeRuleFromContext(uri: URI): void;
64
+
45
65
  /** 导出为可序列化格式 */
46
66
  serialize(): Promise<SerializedContext>;
47
67
  }
@@ -58,12 +78,15 @@ export interface AttachFileContext {
58
78
  lineErrors: string[];
59
79
  path: string;
60
80
  language: string;
81
+ selection?: [number, number];
61
82
  }
62
83
 
63
84
  export interface SerializedContext {
64
85
  recentlyViewFiles: string[];
65
86
  attachedFiles: Array<AttachFileContext>;
66
87
  attachedFolders: string[];
88
+ attachedRules: string[];
89
+ globalRules: string[];
67
90
  }
68
91
 
69
92
  export enum LLM_CONTEXT_KEY {
@@ -0,0 +1,298 @@
1
+ /**
2
+ * MDC 文件的 frontmatter 接口定义
3
+ */
4
+ export interface IMDCFrontmatter {
5
+ description?: string;
6
+ globs?: string | string[];
7
+ alwaysApply?: boolean;
8
+ [key: string]: any;
9
+ }
10
+
11
+ /**
12
+ * MDC 文件解析结果接口
13
+ */
14
+ export interface IMDCParseResult {
15
+ frontmatter: IMDCFrontmatter;
16
+ content: string;
17
+ }
18
+
19
+ /**
20
+ * MDC 文件内容结构
21
+ */
22
+ export interface IMDCContent {
23
+ frontmatter: IMDCFrontmatter;
24
+ content: string;
25
+ }
26
+
27
+ /**
28
+ * 解析简单的 YAML 值
29
+ * @param value - 要解析的值字符串
30
+ * @returns 解析后的值
31
+ */
32
+ function parseYamlValue(value: string): any {
33
+ const trimmed = value.trim();
34
+
35
+ // 布尔值
36
+ if (trimmed === 'true') {
37
+ return true;
38
+ }
39
+ if (trimmed === 'false') {
40
+ return false;
41
+ }
42
+
43
+ // null/undefined
44
+ if (trimmed === 'null' || trimmed === '~' || trimmed === '') {
45
+ return null;
46
+ }
47
+
48
+ // 数字
49
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
50
+ return trimmed.includes('.') ? parseFloat(trimmed) : parseInt(trimmed, 10);
51
+ }
52
+
53
+ // 数组 (简单格式: [item1, item2, item3] 或 - item 格式)
54
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
55
+ const arrayContent = trimmed.slice(1, -1).trim();
56
+ if (!arrayContent) {
57
+ return [];
58
+ }
59
+ return arrayContent.split(',').map((item) => parseYamlValue(item));
60
+ }
61
+
62
+ // 字符串 (移除引号)
63
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
64
+ return trimmed.slice(1, -1);
65
+ }
66
+
67
+ // 默认作为字符串处理
68
+ return trimmed;
69
+ }
70
+
71
+ /**
72
+ * 按行解析 YAML frontmatter
73
+ * @param frontmatterStr - frontmatter 字符串
74
+ * @returns 解析后的对象
75
+ */
76
+ function parseFrontmatterByLine(frontmatterStr: string): IMDCFrontmatter {
77
+ const result: IMDCFrontmatter = {};
78
+ const lines = frontmatterStr.split('\n');
79
+ let currentKey: string | null = null;
80
+ let arrayItems: string[] = [];
81
+ let isInArray = false;
82
+
83
+ for (const line of lines) {
84
+ const trimmedLine = line.trim();
85
+
86
+ // 跳过空行和注释
87
+ if (!trimmedLine || trimmedLine.startsWith('#')) {
88
+ continue;
89
+ }
90
+
91
+ // 检查是否是数组项 (以 - 开头)
92
+ if (trimmedLine.startsWith('- ')) {
93
+ if (currentKey && isInArray) {
94
+ arrayItems.push(trimmedLine.slice(2).trim());
95
+ }
96
+ continue;
97
+ }
98
+
99
+ // 如果之前在处理数组,现在遇到新的键值对,先保存数组
100
+ if (isInArray && currentKey) {
101
+ result[currentKey] = arrayItems.map((item) => parseYamlValue(item));
102
+ arrayItems = [];
103
+ isInArray = false;
104
+ currentKey = null;
105
+ }
106
+
107
+ // 解析键值对
108
+ const colonIndex = trimmedLine.indexOf(':');
109
+ if (colonIndex === -1) {
110
+ continue;
111
+ }
112
+
113
+ const key = trimmedLine.slice(0, colonIndex).trim();
114
+ const value = trimmedLine.slice(colonIndex + 1).trim();
115
+
116
+ currentKey = key;
117
+
118
+ if (value) {
119
+ result[key] = parseYamlValue(value);
120
+ isInArray = false;
121
+ } else {
122
+ isInArray = true;
123
+ arrayItems = [];
124
+ }
125
+ }
126
+
127
+ // 处理最后的数组
128
+ if (isInArray && currentKey) {
129
+ result[currentKey] = arrayItems.map((item) => parseYamlValue(item));
130
+ }
131
+
132
+ return result;
133
+ }
134
+
135
+ /**
136
+ * 序列化对象为简单的 YAML 格式
137
+ * @param obj - 要序列化的对象
138
+ * @returns YAML 字符串
139
+ */
140
+ function serializeToYaml(obj: any): string {
141
+ const lines: string[] = [];
142
+
143
+ for (const [key, value] of Object.entries(obj)) {
144
+ if (value === null || value === undefined) {
145
+ lines.push(`${key}:`);
146
+ } else if (Array.isArray(value)) {
147
+ if (value.length === 0) {
148
+ lines.push(`${key}: []`);
149
+ } else {
150
+ lines.push(`${key}:`);
151
+ for (const item of value) {
152
+ lines.push(` - ${typeof item === 'string' ? item : JSON.stringify(item)}`);
153
+ }
154
+ }
155
+ } else if (typeof value === 'string') {
156
+ // 如果字符串包含特殊字符或空格,使用引号
157
+ if (value.includes(':') || value.includes('#') || value.includes('\n') || value.trim() !== value) {
158
+ lines.push(`${key}: "${value.replace(/"/g, '\\"')}"`);
159
+ } else {
160
+ lines.push(`${key}: ${value}`);
161
+ }
162
+ } else {
163
+ lines.push(`${key}: ${value}`);
164
+ }
165
+ }
166
+
167
+ return lines.join('\n');
168
+ }
169
+
170
+ /**
171
+ * 解析 .mdc 文件内容
172
+ * @param rawContent - 原始文件内容
173
+ * @returns 解析后的结果,包含 frontmatter 和 content
174
+ */
175
+ export function parseMDC(rawContent: string): IMDCParseResult {
176
+ const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/;
177
+ const match = rawContent.match(frontmatterRegex);
178
+
179
+ if (!match) {
180
+ // 如果没有 frontmatter,整个内容作为 content
181
+ return {
182
+ frontmatter: {},
183
+ content: rawContent.trim(),
184
+ };
185
+ }
186
+
187
+ const [, frontmatterStr, content] = match;
188
+
189
+ let frontmatter: IMDCFrontmatter = {};
190
+
191
+ try {
192
+ // 按行解析 YAML frontmatter
193
+ frontmatter = parseFrontmatterByLine(frontmatterStr);
194
+ } catch (error) {
195
+ // 如果解析失败,返回空的 frontmatter
196
+ frontmatter = {};
197
+ }
198
+
199
+ return {
200
+ frontmatter,
201
+ content: content.trim(),
202
+ };
203
+ }
204
+
205
+ /**
206
+ * 序列化 MDC 内容为字符串
207
+ * @param mdcContent - MDC 内容对象
208
+ * @returns 序列化后的字符串
209
+ */
210
+ export function serializeMDC(mdcContent: IMDCContent): string {
211
+ const { frontmatter, content } = mdcContent;
212
+
213
+ // 如果 frontmatter 为空或没有有效内容,只返回 content
214
+ if (!frontmatter || Object.keys(frontmatter).length === 0) {
215
+ return content;
216
+ }
217
+
218
+ try {
219
+ // 序列化 frontmatter 为 YAML
220
+ const frontmatterStr = serializeToYaml(frontmatter);
221
+
222
+ return `---\n${frontmatterStr}\n---\n${content}`;
223
+ } catch (error) {
224
+ // 如果序列化失败,只返回 content
225
+ return content;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * 验证 MDC frontmatter 是否有效
231
+ * @param frontmatter - 要验证的 frontmatter 对象
232
+ * @returns 验证结果
233
+ */
234
+ export function validateMDCFrontmatter(frontmatter: any): frontmatter is IMDCFrontmatter {
235
+ if (typeof frontmatter !== 'object' || frontmatter === null) {
236
+ return false;
237
+ }
238
+
239
+ // 可选的字段类型检查
240
+ if (frontmatter.description !== undefined && typeof frontmatter.description !== 'string') {
241
+ return false;
242
+ }
243
+
244
+ if (frontmatter.globs !== undefined) {
245
+ if (typeof frontmatter.globs !== 'string' && !Array.isArray(frontmatter.globs)) {
246
+ return false;
247
+ }
248
+ if (Array.isArray(frontmatter.globs)) {
249
+ if (!frontmatter.globs.every((glob: any) => typeof glob === 'string')) {
250
+ return false;
251
+ }
252
+ }
253
+ }
254
+
255
+ if (frontmatter.alwaysApply !== undefined && typeof frontmatter.alwaysApply !== 'boolean') {
256
+ return false;
257
+ }
258
+
259
+ return true;
260
+ }
261
+
262
+ /**
263
+ * 创建默认的 MDC frontmatter
264
+ * @returns 默认的 frontmatter 对象
265
+ */
266
+ export function createDefaultMDCFrontmatter(): IMDCFrontmatter {
267
+ return {
268
+ description: '',
269
+ globs: '',
270
+ alwaysApply: false,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * 更新 MDC 文件的 frontmatter
276
+ * @param rawContent - 原始文件内容
277
+ * @param newFrontmatter - 新的 frontmatter
278
+ * @returns 更新后的文件内容
279
+ */
280
+ export function updateMDCFrontmatter(rawContent: string, newFrontmatter: Partial<IMDCFrontmatter>): string {
281
+ const parsed = parseMDC(rawContent);
282
+ const updatedFrontmatter = { ...parsed.frontmatter, ...newFrontmatter };
283
+
284
+ return serializeMDC({
285
+ frontmatter: updatedFrontmatter,
286
+ content: parsed.content,
287
+ });
288
+ }
289
+
290
+ /**
291
+ * 从 MDC 内容中提取纯文本内容(不包含 frontmatter)
292
+ * @param rawContent - 原始文件内容
293
+ * @returns 纯文本内容
294
+ */
295
+ export function extractMDCContent(rawContent: string): string {
296
+ const parsed = parseMDC(rawContent);
297
+ return parsed.content;
298
+ }
@@ -2,7 +2,7 @@ import { Autowired, Injectable } from '@opensumi/di';
2
2
  import { WorkbenchEditorService } from '@opensumi/ide-editor/lib/common/editor';
3
3
  import { IWorkspaceService } from '@opensumi/ide-workspace';
4
4
 
5
- import { SerializedContext } from '../llm-context';
5
+ import { AttachFileContext, SerializedContext } from '../llm-context';
6
6
 
7
7
  export const ChatAgentPromptProvider = Symbol('ChatAgentPromptProvider');
8
8
 
@@ -23,14 +23,17 @@ export class DefaultChatAgentPromptProvider implements ChatAgentPromptProvider {
23
23
  protected readonly workspaceService: IWorkspaceService;
24
24
 
25
25
  async provideContextPrompt(context: SerializedContext, userMessage: string) {
26
- const currentFileInfo =
27
- context.attachedFiles.length > 0 || context.attachedFolders.length > 0 ? null : await this.getCurrentFileInfo();
26
+ let currentFileInfo = await this.getCurrentFileInfo();
27
+ if (context.attachedFiles.some((file) => file.path === currentFileInfo?.path)) {
28
+ currentFileInfo = null;
29
+ }
28
30
 
29
31
  return this.buildPromptTemplate({
30
- recentFiles: this.buildRecentFilesSection(context.recentlyViewFiles),
31
- attachedFiles: this.buildAttachedFilesSection(context.attachedFiles),
32
- attachedFolders: this.buildAttachedFoldersSection(context.attachedFolders),
32
+ attachedFiles: context.attachedFiles,
33
+ attachedFolders: context.attachedFolders,
33
34
  currentFile: currentFileInfo,
35
+ attachedRules: context.attachedRules,
36
+ globalRules: context.globalRules,
34
37
  userMessage,
35
38
  });
36
39
  }
@@ -46,33 +49,56 @@ export class DefaultChatAgentPromptProvider implements ChatAgentPromptProvider {
46
49
  const currentPath =
47
50
  (await this.workspaceService.asRelativePath(currentModel.uri))?.path || currentModel.uri.codeUri.fsPath;
48
51
 
52
+ // 获取当前选中行信息
53
+ const selection = editor?.monacoEditor?.getSelection();
54
+ const currentLine = selection ? selection.startLineNumber : undefined;
55
+ let lineContent = '';
56
+
57
+ if (currentLine && editor?.monacoEditor) {
58
+ const model = editor.monacoEditor.getModel();
59
+ if (model) {
60
+ lineContent = model.getLineContent(currentLine)?.trim() || '';
61
+ }
62
+ }
63
+
49
64
  return {
50
65
  path: currentPath,
51
66
  languageId: currentModel.languageId,
52
67
  content: currentModel.getText(),
68
+ currentLine,
69
+ lineContent,
53
70
  };
54
71
  }
55
72
 
56
- private buildPromptTemplate({
57
- recentFiles,
73
+ private async buildPromptTemplate({
58
74
  attachedFiles,
59
75
  attachedFolders,
60
76
  currentFile,
77
+ attachedRules,
78
+ globalRules,
61
79
  userMessage,
62
80
  }: {
63
- recentFiles: string;
64
- attachedFiles: string;
65
- attachedFolders: string;
66
- currentFile: { path: string; languageId: string; content: string } | null;
81
+ attachedFiles: AttachFileContext[];
82
+ attachedFolders: string[];
83
+ currentFile: {
84
+ path: string;
85
+ languageId: string;
86
+ content: string;
87
+ currentLine?: number;
88
+ lineContent?: string;
89
+ } | null;
90
+ attachedRules: string[];
91
+ globalRules: string[];
67
92
  userMessage: string;
68
93
  }) {
69
94
  const sections = [
95
+ ...globalRules,
96
+ ...attachedFolders,
70
97
  '<additional_data>',
71
98
  'Below are some potentially helpful/relevant pieces of information for figuring out to respond',
72
- recentFiles,
73
- attachedFiles,
74
- attachedFolders,
75
99
  this.buildCurrentFileSection(currentFile),
100
+ this.buildAttachedFilesSection(attachedFiles),
101
+ ...attachedRules,
76
102
  '</additional_data>',
77
103
  '<user_query>',
78
104
  userMessage,
@@ -82,17 +108,7 @@ export class DefaultChatAgentPromptProvider implements ChatAgentPromptProvider {
82
108
  return sections.join('\n');
83
109
  }
84
110
 
85
- private buildRecentFilesSection(files: string[]): string {
86
- if (!files.length) {
87
- return '';
88
- }
89
-
90
- return `<recently_viewed_files>
91
- ${files.map((file, idx) => ` ${idx + 1}: ${file}`).join('\n')}
92
- </recently_viewed_files>`;
93
- }
94
-
95
- private buildAttachedFilesSection(files: { path: string; content: string; lineErrors: string[] }[]): string {
111
+ private buildAttachedFilesSection(files: AttachFileContext[]): string {
96
112
  if (!files.length) {
97
113
  return '';
98
114
  }
@@ -112,9 +128,9 @@ ${files.map((file, idx) => ` ${idx + 1}: ${file}`).join('\n')}
112
128
  return `<attached_files>\n${fileContents}\n</attached_files>`;
113
129
  }
114
130
 
115
- private buildFileContentSection(file: { path: string; content: string }): string {
131
+ private buildFileContentSection(file: AttachFileContext): string {
116
132
  return `<file_contents>
117
- \`\`\`${file.path}
133
+ \`\`\`${file.path}${file.selection ? `, lines: ${file.selection?.[0]}-${file.selection?.[1]}` : ''}
118
134
  ${file.content}
119
135
  \`\`\`
120
136
  </file_contents>`;
@@ -128,23 +144,22 @@ ${file.content}
128
144
  return `<linter_errors>\n${errors.join('\n')}\n</linter_errors>`;
129
145
  }
130
146
 
131
- private buildAttachedFoldersSection(folders: string[]): string {
132
- if (!folders.length) {
147
+ private buildCurrentFileSection(
148
+ fileInfo: { path: string; languageId: string; content: string; currentLine?: number; lineContent?: string } | null,
149
+ ): string {
150
+ if (!fileInfo) {
133
151
  return '';
134
152
  }
135
153
 
136
- return `<attached_folders>\n${folders.join('\n')}</attached_folders>`;
137
- }
154
+ let currentFileSection = `<current_file>\nPath: ${fileInfo.path}`;
138
155
 
139
- private buildCurrentFileSection(fileInfo: { path: string; languageId: string; content: string } | null): string {
140
- if (!fileInfo) {
141
- return '';
156
+ if (fileInfo.currentLine && fileInfo.lineContent) {
157
+ currentFileSection += `\nCurrently selected line: ${fileInfo.currentLine}`;
158
+ currentFileSection += `\nLine ${fileInfo.currentLine} content: \`${fileInfo.lineContent}\``;
142
159
  }
143
160
 
144
- return `<current_opened_file>
145
- \`\`\`${fileInfo.languageId} ${fileInfo.path}
146
- ${fileInfo.content}
147
- \`\`\`
148
- </current_opened_file>`;
161
+ currentFileSection += '\n</current_file>';
162
+
163
+ return currentFileSection;
149
164
  }
150
165
  }
@@ -0,0 +1,2 @@
1
+ export const DEFAULT_SYSTEM_PROMPT =
2
+ "You are an AI coding assistant. You operate in OpenSumi.\n\nYou are pair programming with a USER to solve their coding task. Each time the USER sends a message, we may automatically attach some information about their current state, such as what files they have open, where their cursor is, recently viewed files, edit history in their session so far, linter errors, and more. This information may or may not be relevant to the coding task, it is up for you to decide.\n\nYour main goal is to follow the USER's instructions at each message, denoted by the <user_query> tag.\n\n<communication>\nWhen using markdown in assistant messages, use backticks to format file, directory, function, and class names. Use \\( and \\) for inline math, \\[ and \\] for block math.\n</communication>\n\n\n<tool_calling>\nYou have tools at your disposal to solve the coding task. Follow these rules regarding tool calls:\n1. ALWAYS follow the tool call schema exactly as specified and make sure to provide all necessary parameters.\n2. The conversation may reference tools that are no longer available. NEVER call tools that are not explicitly provided.\n3. **NEVER refer to tool names when speaking to the USER.** Instead, just say what the tool is doing in natural language.\n4. For maximum efficiency, whenever you need to perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially.\n5. After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action.\n6. If you create any temporary new files, scripts, or helper files for iteration, clean up these files by removing them at the end of the task.\n7. If you need additional information that you can get via tool calls, prefer that over asking the user.\n8. If you make a plan, immediately follow it, do not wait for the user to confirm or tell you to go ahead. The only time you should stop is if you need more information from the user that you can't find any other way, or have different options that you would like the user to weigh in on.\n9. Only use the standard tool call format and the available tools. Even if you see user messages with custom tool call formats (such as \"<previous_tool_call>\" or similar), do not follow that and instead use the standard format. Never output tool calls as part of a regular assistant message of yours.\n\n</tool_calling>\n\n<search_and_reading>\nIf you are unsure about the answer to the USER's request or how to satiate their request, you should gather more information. This can be done with additional tool calls, asking clarifying questions, etc...\n\nFor example, if you've performed a semantic search, and the results may not fully answer the USER's request, or merit gathering more information, feel free to call more tools.\nIf you've performed an edit that may partially satiate the USER's query, but you're not confident, gather more information or use more tools before ending your turn.\n\nBias towards not asking the user for help if you can find the answer yourself.\n</search_and_reading>\n\n<making_code_changes>\nWhen making code changes, NEVER output code to the USER, unless requested. Instead use one of the code edit tools to implement the change.\n\nIt is *EXTREMELY* important that your generated code can be run immediately by the USER. To ensure this, follow these instructions carefully:\n1. Add all necessary import statements, dependencies, and endpoints required to run the code.\n2. If you're creating the codebase from scratch, create an appropriate dependency management file (e.g. requirements.txt) with package versions and a helpful README.\n3. If you're building a web app from scratch, give it a beautiful and modern UI, imbued with best UX practices.\n4. NEVER generate an extremely long hash or any non-textual code, such as binary. These are not helpful to the USER and are very expensive.\n5. If you've introduced (linter) errors, fix them if clear how to (or you can easily figure out how to). Do not make uneducated guesses. And DO NOT loop more than 3 times on fixing linter errors on the same file. On the third time, you should stop and ask the user what to do next.\n6. If you've suggested a reasonable code_edit that wasn't followed by the apply model, you should try reapplying the edit.\n\n</making_code_changes>\n\nAnswer the user's request using the relevant tool(s), if they are available. Check that all the required parameters for each tool call are provided or can reasonably be inferred from context. IF there are no relevant tools or there are missing values for required parameters, ask the user to supply these values; otherwise proceed with the tool calls. If the user provides a specific value for a parameter (for example provided in quotes), make sure to use that value EXACTLY. DO NOT make up values for or ask about optional parameters. Carefully analyze descriptive terms in the request as they may indicate required parameter values that should be included even if not explicitly quoted.\n\n<summarization>\nIf you see a section called \"<most_important_user_query>\", you should treat that query as the one to answer, and ignore previous user queries. If you are asked to summarize the conversation, you MUST NOT use any tools, even if they are available. You MUST answer the \"<most_important_user_query>\" query.\n</summarization>\n\n\n\nYou MUST use the following format when citing code regions or blocks:\n```12:15:app/components/Todo.tsx\n// ... existing code ...\n```\nThis is the ONLY acceptable format for code citations. The format is ```startLine:endLine:filepath where startLine and endLine are line numbers.";
@@ -135,3 +135,11 @@ export interface SSEClientTransportOptions {
135
135
  */
136
136
  requestInit?: RequestInit;
137
137
  }
138
+
139
+ export interface ProjectRule {
140
+ path: string;
141
+ content: string;
142
+ description?: string;
143
+ globs?: string | string[];
144
+ alwaysApply?: boolean;
145
+ }
@@ -6,7 +6,6 @@ import { ChatReadableStream, INodeLogger } from '@opensumi/ide-core-node';
6
6
  import { CancellationToken } from '@opensumi/ide-utils';
7
7
 
8
8
  import { ModelInfo } from '../common';
9
- import { compressToolResultSmart, getBase64ImageSize } from '../common/image-compression';
10
9
  import {
11
10
  IToolInvocationRegistryManager,
12
11
  ToolInvocationRegistryManager,