@davia/agent 0.1.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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/dist/agent/agent.d.ts +13 -0
  3. package/dist/agent/agent.d.ts.map +1 -0
  4. package/dist/agent/agent.js +40 -0
  5. package/dist/agent/context.d.ts +9 -0
  6. package/dist/agent/context.d.ts.map +1 -0
  7. package/dist/agent/context.js +7 -0
  8. package/dist/agent/helpers/initialization.d.ts +30 -0
  9. package/dist/agent/helpers/initialization.d.ts.map +1 -0
  10. package/dist/agent/helpers/initialization.js +247 -0
  11. package/dist/agent/helpers/messages-caching-handler.d.ts +14 -0
  12. package/dist/agent/helpers/messages-caching-handler.d.ts.map +1 -0
  13. package/dist/agent/helpers/messages-caching-handler.js +162 -0
  14. package/dist/agent/helpers/tools.d.ts +46 -0
  15. package/dist/agent/helpers/tools.d.ts.map +1 -0
  16. package/dist/agent/helpers/tools.js +164 -0
  17. package/dist/agent/helpers/tree.d.ts +15 -0
  18. package/dist/agent/helpers/tree.d.ts.map +1 -0
  19. package/dist/agent/helpers/tree.js +146 -0
  20. package/dist/agent/middlewares/after-model.d.ts +6 -0
  21. package/dist/agent/middlewares/after-model.d.ts.map +1 -0
  22. package/dist/agent/middlewares/after-model.js +19 -0
  23. package/dist/agent/middlewares/initialization.d.ts +17 -0
  24. package/dist/agent/middlewares/initialization.d.ts.map +1 -0
  25. package/dist/agent/middlewares/initialization.js +93 -0
  26. package/dist/agent/prompts/agent.d.ts +9 -0
  27. package/dist/agent/prompts/agent.d.ts.map +1 -0
  28. package/dist/agent/prompts/agent.js +151 -0
  29. package/dist/agent/prompts/blocks/data.d.ts +2 -0
  30. package/dist/agent/prompts/blocks/data.d.ts.map +1 -0
  31. package/dist/agent/prompts/blocks/data.js +90 -0
  32. package/dist/agent/prompts/blocks/excalidraw.d.ts +2 -0
  33. package/dist/agent/prompts/blocks/excalidraw.d.ts.map +1 -0
  34. package/dist/agent/prompts/blocks/excalidraw.js +52 -0
  35. package/dist/agent/prompts/blocks/file_handling.d.ts +2 -0
  36. package/dist/agent/prompts/blocks/file_handling.d.ts.map +1 -0
  37. package/dist/agent/prompts/blocks/file_handling.js +29 -0
  38. package/dist/agent/prompts/blocks/mdx/available_packages.d.ts +2 -0
  39. package/dist/agent/prompts/blocks/mdx/available_packages.d.ts.map +1 -0
  40. package/dist/agent/prompts/blocks/mdx/available_packages.js +8 -0
  41. package/dist/agent/prompts/blocks/mdx/custom_components.d.ts +2 -0
  42. package/dist/agent/prompts/blocks/mdx/custom_components.d.ts.map +1 -0
  43. package/dist/agent/prompts/blocks/mdx/custom_components.js +77 -0
  44. package/dist/agent/prompts/blocks/mdx/davia_specific.d.ts +2 -0
  45. package/dist/agent/prompts/blocks/mdx/davia_specific.d.ts.map +1 -0
  46. package/dist/agent/prompts/blocks/mdx/davia_specific.js +116 -0
  47. package/dist/agent/prompts/blocks/mdx/mdx.d.ts +2 -0
  48. package/dist/agent/prompts/blocks/mdx/mdx.d.ts.map +1 -0
  49. package/dist/agent/prompts/blocks/mdx/mdx.js +91 -0
  50. package/dist/agent/prompts/blocks/mdx/shadcn.d.ts +2 -0
  51. package/dist/agent/prompts/blocks/mdx/shadcn.d.ts.map +1 -0
  52. package/dist/agent/prompts/blocks/mdx/shadcn.js +132 -0
  53. package/dist/agent/prompts/blocks/tiptap.d.ts +2 -0
  54. package/dist/agent/prompts/blocks/tiptap.d.ts.map +1 -0
  55. package/dist/agent/prompts/blocks/tiptap.js +100 -0
  56. package/dist/agent/prompts/index.d.ts +7 -0
  57. package/dist/agent/prompts/index.d.ts.map +1 -0
  58. package/dist/agent/prompts/index.js +6 -0
  59. package/dist/agent/prompts/repo_instructions.d.ts +3 -0
  60. package/dist/agent/prompts/repo_instructions.d.ts.map +1 -0
  61. package/dist/agent/prompts/repo_instructions.js +442 -0
  62. package/dist/agent/prompts/tool_descriptions.d.ts +4 -0
  63. package/dist/agent/prompts/tool_descriptions.d.ts.map +1 -0
  64. package/dist/agent/prompts/tool_descriptions.js +80 -0
  65. package/dist/agent/tools.d.ts +79 -0
  66. package/dist/agent/tools.d.ts.map +1 -0
  67. package/dist/agent/tools.js +303 -0
  68. package/dist/config.d.ts +16 -0
  69. package/dist/config.d.ts.map +1 -0
  70. package/dist/config.js +108 -0
  71. package/dist/index.d.ts +4 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +3 -0
  74. package/dist/main.d.ts +2 -0
  75. package/dist/main.d.ts.map +1 -0
  76. package/dist/main.js +44 -0
  77. package/package.json +57 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Davia Labs, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ import { todoListMiddleware } from "langchain";
2
+ export declare const createDaviaAgent: (modelName: string) => Promise<import("langchain").ReactAgent<import("langchain").ResponseFormatUndefined, undefined, import("zod").ZodObject<{
3
+ projectId: import("zod").ZodString;
4
+ projectPath: import("zod").ZodString;
5
+ isUpdate: import("zod").ZodBoolean;
6
+ modelName: import("zod").ZodString;
7
+ }, import("zod/v4/core").$strip>, readonly [import("langchain").AgentMiddleware<undefined, import("zod").ZodObject<{
8
+ projectId: import("zod").ZodString;
9
+ projectPath: import("zod").ZodString;
10
+ isUpdate: import("zod").ZodBoolean;
11
+ modelName: import("zod").ZodString;
12
+ }, import("zod/v4/core").$strip>, any>, typeof todoListMiddleware, import("langchain").AgentMiddleware<undefined, undefined, any>]>>;
13
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAa3E,eAAO,MAAM,gBAAgB,GAAU,WAAW,MAAM;;;;;;;;;;oIAmCvD,CAAC"}
@@ -0,0 +1,40 @@
1
+ import { createAgent, initChatModel, todoListMiddleware } from "langchain";
2
+ import { writeTool, searchReplaceTool, readFileTool, deleteTool, multiEditTool, } from "./tools.js";
3
+ import { repositoryInitializationMiddleware } from "./middlewares/initialization.js";
4
+ import { afterModelCachingMiddleware } from "./middlewares/after-model.js";
5
+ import { contextSchema } from "./context.js";
6
+ // Create and return the agent with the model and tools
7
+ export const createDaviaAgent = async (modelName) => {
8
+ // Select the appropriate model based on the provider
9
+ let modelString;
10
+ switch (modelName) {
11
+ case "anthropic":
12
+ modelString = "claude-sonnet-4-5";
13
+ break;
14
+ case "openai":
15
+ modelString = "openai:gpt-5";
16
+ break;
17
+ case "google":
18
+ modelString = "google-genai:gemini-3-pro-preview";
19
+ break;
20
+ default:
21
+ throw new Error(`Unsupported model provider: ${modelName}`);
22
+ }
23
+ const model = await initChatModel(modelString);
24
+ return createAgent({
25
+ model,
26
+ tools: [
27
+ writeTool,
28
+ searchReplaceTool,
29
+ readFileTool,
30
+ deleteTool,
31
+ multiEditTool,
32
+ ],
33
+ middleware: [
34
+ repositoryInitializationMiddleware,
35
+ todoListMiddleware,
36
+ afterModelCachingMiddleware,
37
+ ],
38
+ contextSchema,
39
+ });
40
+ };
@@ -0,0 +1,9 @@
1
+ import * as z from "zod";
2
+ export declare const contextSchema: z.ZodObject<{
3
+ projectId: z.ZodString;
4
+ projectPath: z.ZodString;
5
+ isUpdate: z.ZodBoolean;
6
+ modelName: z.ZodString;
7
+ }, z.core.$strip>;
8
+ export type ContextType = z.infer<typeof contextSchema>;
9
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/agent/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAEzB,eAAO,MAAM,aAAa;;;;;iBAKxB,CAAC;AAEH,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ import * as z from "zod";
2
+ export const contextSchema = z.object({
3
+ projectId: z.string(),
4
+ projectPath: z.string(),
5
+ isUpdate: z.boolean(),
6
+ modelName: z.string(),
7
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Check if a file should be excluded from content analysis.
3
+ * @param filePath - Path to the file
4
+ * @returns True if the file should be excluded, False otherwise
5
+ */
6
+ export declare function shouldExcludeFile(filePath: string): boolean;
7
+ /**
8
+ * Calculate the maximum characters allowed per file based on token budget.
9
+ * Uses the rule of thumb: 4 characters = 1 token
10
+ * @param totalChars - Total characters in all non-excluded files
11
+ * @param numFiles - Number of non-excluded files
12
+ * @param maxTokens - Maximum tokens allowed for the entire repository
13
+ * @returns Maximum characters allowed per file, or -1 if no limit needed
14
+ */
15
+ export declare function calculateMaxCharsPerFile(totalChars: number, numFiles: number, maxTokens: number): number;
16
+ /**
17
+ * Trim file content from the middle while preserving beginning and end.
18
+ * @param content - Original file content
19
+ * @param maxChars - Maximum characters allowed for this file
20
+ * @param headRatio - Ratio of content to keep from the beginning (default: 0.6)
21
+ * @returns Trimmed content with clear markers showing what was removed
22
+ */
23
+ export declare function trimFileContent(content: string, maxChars: number, headRatio?: number): string;
24
+ /**
25
+ * Read all files from a repository recursively with intelligent trimming.
26
+ * @param sourcePath - Path to the source directory
27
+ * @returns Promise resolving to a dictionary of file paths to trimmed content
28
+ */
29
+ export declare function readRepositoryContent(sourcePath: string): Promise<Record<string, string>>;
30
+ //# sourceMappingURL=initialization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initialization.d.ts","sourceRoot":"","sources":["../../../src/agent/helpers/initialization.ts"],"names":[],"mappings":"AASA;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAqC3D;AAED;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAChB,MAAM,CAUR;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,SAAS,GAAE,MAAY,GACtB,MAAM,CAwBR;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CA8KjC"}
@@ -0,0 +1,247 @@
1
+ import fs from "fs-extra";
2
+ import * as path from "path";
3
+ import ignore from "ignore";
4
+ import { EXCLUDED_FILE_EXTENSIONS, MAX_FILES, MAX_TOKENS, } from "../../config.js";
5
+ /**
6
+ * Check if a file should be excluded from content analysis.
7
+ * @param filePath - Path to the file
8
+ * @returns True if the file should be excluded, False otherwise
9
+ */
10
+ export function shouldExcludeFile(filePath) {
11
+ // Get file extension (case insensitive)
12
+ const filePathLower = filePath.toLowerCase();
13
+ // Check for exact extension matches
14
+ for (const ext of EXCLUDED_FILE_EXTENSIONS) {
15
+ if (filePathLower.endsWith(ext.toLowerCase())) {
16
+ return true;
17
+ }
18
+ }
19
+ // Check for files without extensions that might be binary
20
+ if (!filePathLower.includes(".")) {
21
+ // Common text files without extensions that should be included
22
+ const textFiles = new Set([
23
+ "makefile",
24
+ "dockerfile",
25
+ "readme",
26
+ "license",
27
+ "changelog",
28
+ "authors",
29
+ "contributors",
30
+ "install",
31
+ "configure",
32
+ "makefile.in",
33
+ "gemfile",
34
+ "rakefile",
35
+ "procfile",
36
+ ]);
37
+ const filename = filePathLower.split("/").pop() || "";
38
+ if (!textFiles.has(filename)) {
39
+ return true;
40
+ }
41
+ }
42
+ return false;
43
+ }
44
+ /**
45
+ * Calculate the maximum characters allowed per file based on token budget.
46
+ * Uses the rule of thumb: 4 characters = 1 token
47
+ * @param totalChars - Total characters in all non-excluded files
48
+ * @param numFiles - Number of non-excluded files
49
+ * @param maxTokens - Maximum tokens allowed for the entire repository
50
+ * @returns Maximum characters allowed per file, or -1 if no limit needed
51
+ */
52
+ export function calculateMaxCharsPerFile(totalChars, numFiles, maxTokens) {
53
+ const maxCharsTotal = maxTokens * 4;
54
+ // If total is within budget, no trimming needed
55
+ if (totalChars <= maxCharsTotal) {
56
+ return -1;
57
+ }
58
+ // Calculate per-file limit
59
+ return Math.floor(maxCharsTotal / numFiles);
60
+ }
61
+ /**
62
+ * Trim file content from the middle while preserving beginning and end.
63
+ * @param content - Original file content
64
+ * @param maxChars - Maximum characters allowed for this file
65
+ * @param headRatio - Ratio of content to keep from the beginning (default: 0.6)
66
+ * @returns Trimmed content with clear markers showing what was removed
67
+ */
68
+ export function trimFileContent(content, maxChars, headRatio = 0.6) {
69
+ // If content is within limit, return unchanged
70
+ if (content.length <= maxChars) {
71
+ return content;
72
+ }
73
+ // Calculate how much to keep from beginning and end
74
+ const headChars = Math.floor(maxChars * headRatio);
75
+ const tailChars = maxChars - headChars;
76
+ // Extract beginning and end portions
77
+ const headContent = content.slice(0, headChars);
78
+ const tailContent = content.slice(-tailChars);
79
+ // Calculate how many characters were trimmed
80
+ const trimmedChars = content.length - maxChars;
81
+ // Create trimmed content with clear marker
82
+ const trimmedContent = headContent +
83
+ `\n\n... [TRIMMED ${trimmedChars} chars from middle] ...\n\n` +
84
+ tailContent;
85
+ return trimmedContent;
86
+ }
87
+ /**
88
+ * Read all files from a repository recursively with intelligent trimming.
89
+ * @param sourcePath - Path to the source directory
90
+ * @returns Promise resolving to a dictionary of file paths to trimmed content
91
+ */
92
+ export async function readRepositoryContent(sourcePath) {
93
+ const result = {};
94
+ // Initialize ignore instance
95
+ const ig = ignore();
96
+ // Try to read .gitignore file
97
+ const gitignorePath = path.join(sourcePath, ".gitignore");
98
+ try {
99
+ const gitignoreContent = await fs.readFile(gitignorePath, "utf-8");
100
+ ig.add(gitignoreContent);
101
+ }
102
+ catch {
103
+ // No .gitignore file or can't read it, continue without it
104
+ }
105
+ // Always ignore common directories from all languages and frameworks
106
+ ig.add([
107
+ // Version control
108
+ ".git",
109
+ ".svn",
110
+ ".hg",
111
+ // Node.js / JavaScript
112
+ "node_modules",
113
+ ".next",
114
+ ".turbo",
115
+ ".cache",
116
+ ".parcel-cache",
117
+ ".yarn",
118
+ ".pnp",
119
+ ".pnpm-store",
120
+ // Python
121
+ ".venv",
122
+ "venv",
123
+ "env",
124
+ "ENV",
125
+ "__pycache__",
126
+ ".pytest_cache",
127
+ ".mypy_cache",
128
+ ".tox",
129
+ ".coverage",
130
+ "htmlcov",
131
+ ".hypothesis",
132
+ // Ruby
133
+ ".bundle",
134
+ "vendor/bundle",
135
+ ".rbenv",
136
+ // Java / JVM
137
+ "target",
138
+ ".gradle",
139
+ ".mvn",
140
+ "build",
141
+ "out",
142
+ // Go
143
+ "vendor",
144
+ ".go",
145
+ // Rust
146
+ "Cargo.lock",
147
+ // PHP
148
+ "vendor",
149
+ ".composer",
150
+ // .NET
151
+ "bin",
152
+ "obj",
153
+ ".vs",
154
+ // Build outputs
155
+ "dist",
156
+ "build",
157
+ ".output",
158
+ // Framework-specific
159
+ ".nuxt",
160
+ ".vuepress/dist",
161
+ ".serverless",
162
+ // Infrastructure
163
+ ".terraform",
164
+ ".terraform.lock.hcl",
165
+ ".vagrant",
166
+ ".docker",
167
+ // Testing / Coverage
168
+ "coverage",
169
+ ".nyc_output",
170
+ ".jest",
171
+ // IDE / Editor
172
+ ".idea",
173
+ ".vscode",
174
+ "*.swp",
175
+ "*.swo",
176
+ ".sublime-project",
177
+ ".sublime-workspace",
178
+ // OS
179
+ ".DS_Store",
180
+ "Thumbs.db",
181
+ // Logs
182
+ "*.log",
183
+ "logs",
184
+ ]);
185
+ // Recursively read all files
186
+ const allFiles = [];
187
+ async function traverseDirectory(currentPath) {
188
+ if (allFiles.length >= MAX_FILES) {
189
+ return;
190
+ }
191
+ try {
192
+ const entries = await fs.readdir(currentPath, { withFileTypes: true });
193
+ for (const entry of entries) {
194
+ if (allFiles.length >= MAX_FILES) {
195
+ break;
196
+ }
197
+ const fullPath = path.join(currentPath, entry.name);
198
+ const relativePath = path.relative(sourcePath, fullPath);
199
+ // Skip if ignored by gitignore
200
+ if (ig.ignores(relativePath)) {
201
+ continue;
202
+ }
203
+ if (entry.isDirectory()) {
204
+ await traverseDirectory(fullPath);
205
+ }
206
+ else if (entry.isFile()) {
207
+ // Skip excluded file extensions
208
+ if (!shouldExcludeFile(relativePath)) {
209
+ allFiles.push(fullPath);
210
+ }
211
+ }
212
+ }
213
+ }
214
+ catch {
215
+ // Skip directories we can't read
216
+ }
217
+ }
218
+ await traverseDirectory(sourcePath);
219
+ // Read all file contents
220
+ const fileContents = [];
221
+ for (const filePath of allFiles) {
222
+ try {
223
+ const content = await fs.readFile(filePath, "utf-8");
224
+ const relativePath = path.relative(sourcePath, filePath);
225
+ fileContents.push({ path: relativePath, content });
226
+ }
227
+ catch {
228
+ // Skip files that can't be read
229
+ }
230
+ }
231
+ // Calculate total characters
232
+ const totalChars = fileContents.reduce((sum, file) => sum + file.content.length, 0);
233
+ // Calculate max chars per file
234
+ const maxCharsPerFile = calculateMaxCharsPerFile(totalChars, fileContents.length, MAX_TOKENS);
235
+ // Apply trimming and build result dictionary
236
+ for (const file of fileContents) {
237
+ if (maxCharsPerFile === -1) {
238
+ // No trimming needed
239
+ result[file.path] = file.content;
240
+ }
241
+ else {
242
+ // Apply trimming
243
+ result[file.path] = trimFileContent(file.content, maxCharsPerFile);
244
+ }
245
+ }
246
+ return result;
247
+ }
@@ -0,0 +1,14 @@
1
+ import { BaseMessage } from "langchain";
2
+ /**
3
+ * Ensures only the last AI message has cache control (TTL).
4
+ * Removes cache control from all other AI messages.
5
+ * @param messages - List of messages to modify
6
+ */
7
+ export declare function handleAIMessageCaching(messages: BaseMessage[]): void;
8
+ /**
9
+ * Ensures only the last ToolMessage has cache control (TTL).
10
+ * Converts string content to list format and removes cache control from all other ToolMessages.
11
+ * @param messages - List of messages to modify
12
+ */
13
+ export declare function handleToolMessageCaching(messages: BaseMessage[]): void;
14
+ //# sourceMappingURL=messages-caching-handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages-caching-handler.d.ts","sourceRoot":"","sources":["../../../src/agent/helpers/messages-caching-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,WAAW,EAAE,MAAM,WAAW,CAAC;AA4BhE;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,IAAI,CAwEpE;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,WAAW,EAAE,GAAG,IAAI,CAoFtE"}
@@ -0,0 +1,162 @@
1
+ import { AIMessage, ToolMessage } from "langchain";
2
+ /**
3
+ * Deep clone a message to avoid mutating the original
4
+ * @param message - Message to clone
5
+ * @returns Cloned message
6
+ */
7
+ function cloneMessage(message) {
8
+ // Use structuredClone if available, otherwise fall back to JSON
9
+ if (typeof structuredClone !== "undefined") {
10
+ return structuredClone(message);
11
+ }
12
+ return JSON.parse(JSON.stringify(message));
13
+ }
14
+ /**
15
+ * Ensures only the last AI message has cache control (TTL).
16
+ * Removes cache control from all other AI messages.
17
+ * @param messages - List of messages to modify
18
+ */
19
+ export function handleAIMessageCaching(messages) {
20
+ // Find all AI message indices
21
+ const aiIndices = [];
22
+ for (let i = 0; i < messages.length; i++) {
23
+ if (messages[i] instanceof AIMessage) {
24
+ aiIndices.push(i);
25
+ }
26
+ }
27
+ if (aiIndices.length === 0) {
28
+ return;
29
+ }
30
+ // Remove cache control from all AI messages first
31
+ for (const idx of aiIndices) {
32
+ const aiMsg = messages[idx];
33
+ if (aiMsg && Array.isArray(aiMsg.content)) {
34
+ // Create a deep copy to avoid modifying the original
35
+ const aiMsgCopy = cloneMessage(aiMsg);
36
+ for (const block of aiMsgCopy.content) {
37
+ if (typeof block === "object" &&
38
+ block !== null &&
39
+ "cache_control" in block) {
40
+ const blockWithCache = block;
41
+ delete blockWithCache.cache_control;
42
+ }
43
+ }
44
+ messages[idx] = aiMsgCopy;
45
+ }
46
+ }
47
+ // Add cache control only to the last AI message
48
+ const lastAiIdx = aiIndices[aiIndices.length - 1];
49
+ if (lastAiIdx === undefined) {
50
+ return;
51
+ }
52
+ const lastAiMsg = messages[lastAiIdx];
53
+ if (!lastAiMsg) {
54
+ return;
55
+ }
56
+ if (Array.isArray(lastAiMsg.content) && lastAiMsg.content.length > 0) {
57
+ // Ensure we have a copy to modify
58
+ const lastAiMsgCopy = cloneMessage(lastAiMsg);
59
+ const contentArray = [...lastAiMsgCopy.content];
60
+ const lastBlock = contentArray[contentArray.length - 1];
61
+ // Add cache control to the last content block
62
+ if (typeof lastBlock === "object" && lastBlock !== null) {
63
+ const blockWithCache = { ...lastBlock };
64
+ blockWithCache.cache_control = {
65
+ type: "ephemeral",
66
+ ttl: "5m",
67
+ };
68
+ contentArray[contentArray.length - 1] =
69
+ blockWithCache;
70
+ }
71
+ else {
72
+ // If last block is not a dict, wrap it
73
+ contentArray[contentArray.length - 1] = {
74
+ type: "text",
75
+ text: lastBlock,
76
+ cache_control: { type: "ephemeral", ttl: "5m" },
77
+ };
78
+ }
79
+ lastAiMsgCopy.content = contentArray;
80
+ messages[lastAiIdx] = lastAiMsgCopy;
81
+ }
82
+ }
83
+ /**
84
+ * Ensures only the last ToolMessage has cache control (TTL).
85
+ * Converts string content to list format and removes cache control from all other ToolMessages.
86
+ * @param messages - List of messages to modify
87
+ */
88
+ export function handleToolMessageCaching(messages) {
89
+ // Find all ToolMessage indices
90
+ const toolIndices = [];
91
+ for (let i = 0; i < messages.length; i++) {
92
+ if (messages[i] instanceof ToolMessage) {
93
+ toolIndices.push(i);
94
+ }
95
+ }
96
+ if (toolIndices.length === 0) {
97
+ return;
98
+ }
99
+ // Remove cache control from all ToolMessages first
100
+ for (const idx of toolIndices) {
101
+ const toolMsg = messages[idx];
102
+ if (toolMsg && Array.isArray(toolMsg.content)) {
103
+ // Create a copy to avoid modifying the original
104
+ const toolMsgCopy = cloneMessage(toolMsg);
105
+ for (const block of toolMsgCopy.content) {
106
+ if (typeof block === "object" &&
107
+ block !== null &&
108
+ "cache_control" in block) {
109
+ const blockWithCache = block;
110
+ delete blockWithCache.cache_control;
111
+ }
112
+ }
113
+ messages[idx] = toolMsgCopy;
114
+ }
115
+ }
116
+ // Add cache control only to the last ToolMessage
117
+ const lastToolIdx = toolIndices[toolIndices.length - 1];
118
+ if (lastToolIdx === undefined) {
119
+ return;
120
+ }
121
+ const lastToolMsg = messages[lastToolIdx];
122
+ if (!lastToolMsg) {
123
+ return;
124
+ }
125
+ // Convert string content to list format with cache control
126
+ if (typeof lastToolMsg.content === "string") {
127
+ const lastToolMsgCopy = cloneMessage(lastToolMsg);
128
+ lastToolMsgCopy.content = [
129
+ {
130
+ type: "text",
131
+ text: lastToolMsg.content,
132
+ cache_control: { type: "ephemeral", ttl: "5m" },
133
+ },
134
+ ];
135
+ messages[lastToolIdx] = lastToolMsgCopy;
136
+ }
137
+ else if (Array.isArray(lastToolMsg.content) &&
138
+ lastToolMsg.content.length > 0) {
139
+ // If already a list, add cache control to the first element
140
+ const lastToolMsgCopy = cloneMessage(lastToolMsg);
141
+ const contentArray = [...lastToolMsgCopy.content];
142
+ const firstBlock = contentArray[0];
143
+ if (typeof firstBlock === "object" && firstBlock !== null) {
144
+ const blockWithCache = { ...firstBlock };
145
+ blockWithCache.cache_control = {
146
+ type: "ephemeral",
147
+ ttl: "5m",
148
+ };
149
+ contentArray[0] = blockWithCache;
150
+ }
151
+ else {
152
+ // Wrap non-dict content
153
+ contentArray[0] = {
154
+ type: "text",
155
+ text: firstBlock,
156
+ cache_control: { type: "ephemeral", ttl: "5m" },
157
+ };
158
+ }
159
+ lastToolMsgCopy.content = contentArray;
160
+ messages[lastToolIdx] = lastToolMsgCopy;
161
+ }
162
+ }
@@ -0,0 +1,46 @@
1
+ import { ContextType } from "../context.js";
2
+ /**
3
+ * Create a clickable terminal hyperlink using OSC 8 escape sequence
4
+ */
5
+ export declare function createTerminalLink(url: string, text: string): string;
6
+ /**
7
+ * Generate a log message for file creation based on file type
8
+ */
9
+ export declare function getFileCreationMessage(filePath: string, context: ContextType): string;
10
+ /**
11
+ * Get the base destination path based on isUpdate flag
12
+ */
13
+ export declare function getBaseDestinationPath(projectPath: string, isUpdate: boolean): string;
14
+ /**
15
+ * Get the assets path (for reading existing files)
16
+ */
17
+ export declare function getAssetsPath(projectPath: string): string;
18
+ /**
19
+ * Helper function to resolve file path using runtime context
20
+ * @param filePath - Relative file path
21
+ * @param context - Runtime context with projectPath and isUpdate
22
+ * @returns Absolute file path
23
+ * @throws Error if path validation fails
24
+ */
25
+ export declare function resolveFilePath(filePath: string, context: ContextType): string;
26
+ /**
27
+ * Parse Mermaid diagram to Excalidraw using Puppeteer headless browser
28
+ * This is the same approach used by mermaid-cli for reliable rendering
29
+ * @param mermaidContent - Mermaid diagram definition
30
+ * @returns Excalidraw elements and files
31
+ */
32
+ export declare function parseMermaidWithPuppeteer(mermaidContent: string): Promise<any>;
33
+ /**
34
+ * Helper function to perform robust search and replace with validation
35
+ * @param content - Original file content
36
+ * @param oldString - String to search for
37
+ * @param newString - String to replace with
38
+ * @param replaceAll - Whether to replace all occurrences
39
+ * @returns Object with new content, success status, and error message
40
+ */
41
+ export declare function robustSearchReplace(content: string, oldString: string, newString: string, replaceAll?: boolean): {
42
+ newContent: string;
43
+ success: boolean;
44
+ errorMessage?: string;
45
+ };
46
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../../src/agent/helpers/tools.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAGpE;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,WAAW,GACnB,MAAM,CAmCR;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,OAAO,GAChB,MAAM,CAKR;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,WAAW,GACnB,MAAM,CA2BR;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAAC,cAAc,EAAE,MAAM,gBAmCrE;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,UAAU,GAAE,OAAe,GAC1B;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAwCjE"}