@aigne/doc-smith 0.8.15-beta.7 → 0.8.15-beta.9

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 (44) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/agents/evaluate/index.yaml +1 -3
  3. package/agents/generate/check-diagram.mjs +1 -1
  4. package/agents/generate/check-need-generate-structure.mjs +2 -7
  5. package/agents/generate/generate-structure.yaml +117 -65
  6. package/agents/generate/index.yaml +1 -2
  7. package/agents/generate/{merge-d2-diagram.yaml → merge-diagram.yaml} +7 -6
  8. package/agents/generate/update-document-structure.yaml +1 -1
  9. package/agents/generate/user-review-document-structure.mjs +1 -0
  10. package/agents/generate/utils/merge-document-structures.mjs +30 -0
  11. package/agents/schema/document-structure-item.yaml +23 -0
  12. package/agents/schema/document-structure-refine-item.yaml +20 -0
  13. package/agents/schema/document-structure.yaml +1 -3
  14. package/agents/update/batch-generate-document.yaml +1 -1
  15. package/agents/update/check-generate-diagram.mjs +26 -0
  16. package/agents/update/generate-diagram.yaml +0 -1
  17. package/agents/update/generate-document.yaml +17 -5
  18. package/agents/update/handle-document-update.yaml +8 -0
  19. package/agents/update/update-document-detail.yaml +2 -2
  20. package/agents/update/update-single-document.yaml +0 -1
  21. package/agents/update/user-review-document.mjs +6 -5
  22. package/agents/utils/load-sources.mjs +53 -13
  23. package/agents/utils/transform-detail-datasources.mjs +3 -3
  24. package/aigne.yaml +9 -4
  25. package/package.json +2 -1
  26. package/prompts/common/document/content-rules-core.md +4 -4
  27. package/prompts/common/document/openapi-usage-rules.md +36 -0
  28. package/prompts/common/document/role-and-personality.md +1 -2
  29. package/prompts/detail/d2-diagram/rules.md +11 -14
  30. package/prompts/detail/d2-diagram/system-prompt.md +0 -14
  31. package/prompts/detail/d2-diagram/user-prompt.md +30 -1
  32. package/prompts/detail/generate/document-rules.md +1 -1
  33. package/prompts/detail/generate/system-prompt.md +0 -6
  34. package/prompts/detail/generate/user-prompt.md +13 -60
  35. package/prompts/detail/update/system-prompt.md +0 -6
  36. package/prompts/detail/update/user-prompt.md +3 -3
  37. package/prompts/structure/generate/system-prompt.md +0 -30
  38. package/prompts/structure/generate/user-prompt.md +66 -27
  39. package/prompts/structure/review/structure-review-system.md +78 -0
  40. package/types/document-structure-schema.mjs +3 -3
  41. package/utils/extract-api.mjs +32 -0
  42. package/utils/file-utils.mjs +14 -87
  43. package/agents/generate/document-structure-tools/generate-sub-structure.mjs +0 -131
  44. package/agents/generate/generate-structure-without-tools.yaml +0 -65
@@ -1,15 +1,10 @@
1
+ <datasources>
2
+ Following are the partial or complete data sources provided by the user to help you design the document structure. Use these data sources to inform your structural planning.
1
3
 
2
- {% include "../../common/document-structure/user-locale-rules.md" %}
3
-
4
- {% include "../../common/document-structure/user-preferences.md" %}
5
-
4
+ {{ datasources }}
6
5
 
7
- <file_list>
8
- {{allFilesPaths}}
9
- </file_list>
10
6
 
11
- <datasources>
12
- {{ datasources }}
7
+ NOTICE: There are additional data source contents not displayed. When operating on the document structure, be sure to consider these undisplayed contents and do not easily delete any nodes unless users explicitly request deletion.
13
8
  </datasources>
14
9
 
15
10
  {% if userContext.openAPISpec %}
@@ -17,7 +12,7 @@
17
12
 
18
13
  **Goal:** Use the provided OpenAPI (Swagger) specification to design how the OpenAPI content and the overall document should be structured together.
19
14
 
20
- **OpenAPI File Content:**
15
+ **OpenAPI File Content:**
21
16
  <openapi_doc>
22
17
 
23
18
  {{ userContext.openAPISpec }}
@@ -47,20 +42,32 @@
47
42
  {% endif %}
48
43
 
49
44
 
50
- {% if originalDocumentStructure %}
51
45
  <last_document_structure>
52
- {{originalDocumentStructure}}
46
+ projectName: |
47
+ {{projectName}}
48
+ projectDesc: |
49
+ {{projectDesc}}
50
+
51
+ {% if originalDocumentStructure %}
52
+ {{ originalDocumentStructure | yaml.stringify }}
53
+ {% elseif userContext.originalDocumentStructure %}
54
+ {{ userContext.originalDocumentStructure | yaml.stringify }}
55
+ No previous document structure provided. generate a new structure based on the data sources!
56
+ {% endif %}
57
+
53
58
  </last_document_structure>
54
59
 
55
60
 
61
+ {% include "../../common/document-structure/user-locale-rules.md" %}
62
+
63
+ {% include "../../common/document-structure/user-preferences.md" %}
64
+
56
65
  <last_document_structure_rule>
57
66
  If a previous structural plan (last_document_structure) is provided, follow these rules:
58
67
  1. **Feedback Implementation**: The new structural plan **must** correctly implement all changes requested in user feedback.
59
68
  2. **Unrelated Node Stability**: Nodes not mentioned in user feedback **must not have their path or sourcesIds attributes modified**. `path` and `sourcesIds` are critical identifiers linking existing content, and their stability is paramount.
60
69
  Ideally, other attributes (such as `title`, `description`) should also remain stable, unless these changes are directly caused by a requested modification or result from DataSource updates.
61
70
  </last_document_structure_rule>
62
- {% endif %}
63
-
64
71
 
65
72
  {% if documentStructure %}
66
73
  <review_document_structure>
@@ -92,27 +99,59 @@ Sub-structures must meet the following requirements:
92
99
  - Sub-structures are planned based on DataSources and the parent document's description
93
100
  - The parent document provides an overview of the planned content, while sub-structures directly plan the specific content to be displayed
94
101
  - Further break down and comprehensively display the content planned in the parent document
95
- - All sub-structures must have their parentId value set to {{parentDocument.path}}
102
+ - All sub-structures must have their parentPath value set to {{parentDocument.path}}
96
103
  </parent_document>
97
104
  {% endif %}
98
105
 
99
106
  <instructions>
100
- Your task is to design a detailed structural plan for the document to be generated. This plan will serve as a "blueprint" for subsequent content generation, guiding the LLM on how to organize and present information, ensuring the document is logically clear, easy to understand, well-structured, and comprehensive.
107
+ Your task is to **analyze, refine, and adjust** the existing document structure (`last_document_structure`) based on the partial code repository content currently provided, generating a structural update plan.
108
+ You are not creating a structure from scratch, but rather **performing intelligent updates based on understanding the existing structure** to make the document structure more accurately reflect the latest code content, architectural changes, and logical relationships.
109
+
110
+ ## When using <datasource> data sources, please note the following:
111
+
112
+ - Fully respect the project descriptions and usage instructions in README files, as these typically summarize the project's core functionality and objectives.
113
+ - Pay attention to comments and docstrings in source code files, as these reveal the design intent and usage methods of the code.
114
+ - Understand the relationships between various modules and files, which helps build a logically clear and well-structured document hierarchy.
115
+ - Notice key concepts, APIs, and configuration options in the code, as these are typically important components of the document structure.
116
+ - The generated document structure must include all public modules, interfaces, and features to ensure document completeness and usability.
117
+
118
+
119
+ ## Objective
120
+
121
+ Your output should contain a `structures` array with document structure items that need to be added or updated:
122
+
123
+ - **structures**: Array of document structure items representing incremental changes to the existing document structure. Each item should include a `path` field - the system will automatically replace existing items with matching paths or add new items if the path doesn't exist.
124
+
125
+ IMPORTANT: You should avoid duplicating existing structure items. Only include items that are genuinely new or need updates. The system will automatically merge these changes with the existing document structure based on the `path` field.
126
+
127
+ ## Behavior Rules
128
+
129
+ 1. **Understanding and Inheritance**
130
+ - Fully understand the hierarchical logic, section divisions, and naming style in <last_document_structure>.
131
+ - Perform incremental updates based on this foundation, not complete rewrites.
132
+ - Preserve existing reasonable structures, only modify or extend when there is clear justification.
133
+
134
+ 2. **Contextual Association Analysis**
135
+ - You will receive part of the code repository content (such as partial source files or directory content), please analyze their **documentation value and structural impact**.
136
+ - Identify which parts represent new concepts, APIs, modules, configurations, or features; determine if they require adding or modifying corresponding sections in the document structure.
101
137
 
102
- Key capabilities and behavioral principles:
103
- - Data Comprehension: Ability to parse and understand structured and unstructured data, identifying key concepts, entities, attributes, relationships, and processes within them.
104
- - Structured Thinking: Strong logical analysis capabilities to decompose complex information into clear chapters, sections, and items, establishing reasonable hierarchical relationships.
105
- - User-Oriented Approach: Ability to flexibly adjust the focus and level of detail in structural planning based on document objectives and audience characteristics provided by users.
106
- - Modular Design: Tendency to divide documents into independent, reusable modules or sections for easy content population and subsequent maintenance.
107
- - Flexibility and Adaptability: Ability to handle multiple types of data sources and design the most suitable documentation structure based on data source characteristics (such as code function/class structures, API endpoints/parameters, text paragraphs/themes).
108
- - Clarity and Completeness: Ensure the final structural plan is easy to understand and can guide the LLM to generate a comprehensive and well-organized document.
138
+ 3. **Structure Adjustment Strategy**
139
+ - If new content supplements details of existing sections, include the updated item in the `structures` array with the same path.
140
+ - If new content introduces new topics, modules, or hierarchies, include new items in the `structures` array with new paths.
141
+ - Ensure the position, hierarchy, and naming of new nodes align with the overall document logic.
109
142
 
143
+ 4. **Consistency and Clarity**
144
+ - Ensure new or modified structure items are consistent with existing structure style.
145
+ - Each structure node (whether new or updated) should include:
146
+ - **Title**
147
+ - **Brief description in one sentence**, describing main content and purpose
148
+ - Maintain clear hierarchy, avoid duplication, ensure logical coherence. Excellent documentation should allow users to quickly understand project structure and content distribution, organized by modules, functional features, and other dimensions.
110
149
 
111
- Objectives:
112
- - Create a clear and logical structural plan that comprehensively presents information from the user-provided context while providing users with intuitive navigation paths.
113
- - Each {{nodeName}} should include: a {{nodeName}} title, a one-sentence introduction describing its main content, with presentation and organization methods tailored to the target audience.
150
+ 5. **Requirements**
151
+ - Follow all rules and guidelines in <document_structure_rules>.
152
+ - Generate rich document structure where functional modules must have sub-documents, comprehensively covering the codebase's functionality and modules, ensuring users can easily get started, understand, and use various modules and main features of the project through documentation.
114
153
 
115
154
  {% include "../../common/document-structure/intj-traits.md" %}
116
155
 
117
- Always follow one principle: You must ensure the final structural plan meets user requirements.
156
+ You must make reasonable incremental modifications based solely on the new information provided while respecting the existing structure, ensuring the final structure remains complete, clear, and extensible.
118
157
  </instructions>
@@ -0,0 +1,78 @@
1
+ <role_and_goal>
2
+ You are a **Documentation Structure Refiner** with the analytical mindset of an **INTJ (The Architect)**. You combine expert knowledge in technical documentation architecture and information design with strategic thinking, systematic analysis, and perfectionist attention to detail. Your core strengths are understanding complex systems, creating logically sound blueprints, and anticipating future documentation challenges.
3
+ </role_and_goal>
4
+
5
+ <document_structure>
6
+ projectName: |
7
+ {{projectName}}
8
+ projectDesc: |
9
+ {{projectDesc}}
10
+
11
+ documentStructure:
12
+ {{ documentStructure | yaml.stringify }}
13
+ </document_structure>
14
+
15
+ <instructions>
16
+
17
+ Your task:
18
+ Given an existing document structure (a JSON array or tree of sections), refine and optimize its **hierarchy and order** to improve clarity, usability, and conventional organization.
19
+ ️ You must not add or rename any nodes. You may delete nodes when necessary for better organization and adjust the **order** and **nesting levels** of existing nodes.
20
+
21
+ ---
22
+
23
+ ## Optimization Goals
24
+
25
+ 1. **Logical Order**
26
+ - Introductory materials should always appear at the beginning:
27
+ - “Overview”, “Introduction”, “Quick Start”, “Getting Started”, “Setup” should be near the top.
28
+ - Meta and community-related sections (e.g., “Community”, “Contributing”, “License”, “Changelog”) should always be at the end.
29
+ - Technical reference and configuration sections should appear after conceptual and usage sections.
30
+
31
+ 2. **Hierarchy Correction**
32
+ - Ensure proper depth:
33
+ - “Overview” and “Quick Start” should have **1–2 levels max**.
34
+ - Remove deeply nested technical details from “Overview” or “Quick Start”.
35
+ - Relocate such details under “Architecture”, “API Reference”, or “Modules”.
36
+ - Keep beneficial nodes — you may delete duplicated, redundant, or harmful nodes when needed for clarity.
37
+
38
+ 3. **Grouping and Alignment**
39
+ - Align similar nodes logically (e.g., group “Usage”, “Examples”, “Tutorials” together).
40
+ - Avoid duplication or overlap by reordering or strategic deletion when necessary.
41
+
42
+ 4. **Naming and Identity**
43
+ - You are **not allowed to rename or reword** any section titles or descriptions.
44
+ - Keep all existing keys, identifiers, and text intact.
45
+
46
+ 5. **Balance**
47
+ - Maintain a clean, well-organized hierarchy.
48
+ - Keep top-level nodes concise (≤ 8 preferred).
49
+ - Avoid over-nesting (≤ 4 levels deep).
50
+
51
+ ---
52
+
53
+ ## Behavior Rules
54
+
55
+ - Do **not** add new nodes.
56
+ - You **may** delete nodes when they are redundant, duplicated, or detrimental to documentation clarity.
57
+ - Do **not** rename or rewrite content.
58
+ - You **may** move nodes to different parents or reorder siblings to achieve better logical flow.
59
+ - You **must** maintain structural integrity for all remaining nodes.
60
+ - The output must be a complete, valid document structure array matching the expected schema.
61
+
62
+ ---
63
+
64
+ ## Objective
65
+
66
+ Output a complete `structures` array containing the optimized document structure:
67
+ 1. Include ALL nodes from the input structure (whether modified or not)
68
+ 2. Each item must include: `id`, `title`, `description`, `path`, `parentPath` (if not top-level)
69
+ 3. Apply your optimizations through proper ordering, hierarchy changes, and selective deletion
70
+ 4. Maintain all required fields and ensure paths are valid (start with /, no spaces/special chars)
71
+ 5. **Important**: Only modify structural aspects (`id`, `title`, `description`, `path`, `parentPath`). Do NOT modify `sourceIds` or other data fields
72
+
73
+ **Optimization Approach:**
74
+ - Reorder nodes by adjusting their position in the array
75
+ - Change hierarchy by modifying `parentPath` values (use the path of the new parent node)
76
+ - Delete problematic nodes by simply omitting them from the output array
77
+ - Keep beneficial nodes with their original content intact
78
+ </instructions>
@@ -6,7 +6,7 @@ export const documentItemSchema = z.object({
6
6
  title: z.string().min(1, "Title is required"),
7
7
  description: z.string().min(1, "Description is required"),
8
8
  path: z.string().startsWith("/", 'Path must start with "/"'),
9
- parentId: z.string().nullable(),
9
+ parentId: z.string().nullish(),
10
10
  sourceIds: z.array(z.string()).min(1, "At least one source ID is required"),
11
11
  });
12
12
 
@@ -18,7 +18,7 @@ export const addDocumentInputSchema = z.object({
18
18
  title: z.string().min(1, "Title is required"),
19
19
  description: z.string().min(1, "Description is required"),
20
20
  path: z.string().startsWith("/", 'Path must start with "/"'),
21
- parentId: z.string().nullable().optional(),
21
+ parentId: z.string().nullish(),
22
22
  sourceIds: z.array(z.string()).min(1, "At least one source ID is required"),
23
23
  });
24
24
 
@@ -44,7 +44,7 @@ export const deleteDocumentOutputSchema = z.object({
44
44
  // Move document schemas
45
45
  export const moveDocumentInputSchema = z.object({
46
46
  path: z.string().min(1, "Path is required"),
47
- newParentId: z.string().nullable().optional(),
47
+ newParentId: z.string().nullish(),
48
48
  });
49
49
 
50
50
  export const moveDocumentOutputSchema = z.object({
@@ -0,0 +1,32 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { transpileDeclaration } from "typescript";
3
+
4
+ export async function extractApi(path) {
5
+ const content = await readFile(path, "utf8");
6
+
7
+ const lang = languages.find((lang) => lang.match(path, content));
8
+ if (lang) {
9
+ return lang.extract(path, content);
10
+ }
11
+
12
+ return content;
13
+ }
14
+
15
+ const languages = [
16
+ {
17
+ match: (path) => /\.m?(js|ts)x?$/.test(path),
18
+ extract: extractJsApi,
19
+ },
20
+ ];
21
+
22
+ async function extractJsApi(_path, content) {
23
+ const res = transpileDeclaration(content, {
24
+ compilerOptions: {
25
+ declaration: true,
26
+ emitDeclarationOnly: true,
27
+ allowJs: true,
28
+ },
29
+ });
30
+
31
+ return res.outputText.trim();
32
+ }
@@ -11,8 +11,8 @@ import { gunzipSync } from "node:zlib";
11
11
 
12
12
  import { debug } from "./debug.mjs";
13
13
  import { isGlobPattern } from "./utils.mjs";
14
- import { INTELLIGENT_SUGGESTION_TOKEN_THRESHOLD } from "./constants/index.mjs";
15
14
  import { uploadFiles } from "./upload-files.mjs";
15
+ import { extractApi } from "./extract-api.mjs";
16
16
 
17
17
  /**
18
18
  * Check if a directory is inside a git repository using git command
@@ -508,7 +508,9 @@ export async function readFileContents(files, baseDir = process.cwd(), options =
508
508
 
509
509
  return null;
510
510
  } else {
511
- const content = await readFile(file, "utf8");
511
+ const content = await extractApi(file);
512
+ if (!content) return null;
513
+
512
514
  const relativePath = path.relative(baseDir, file);
513
515
  return {
514
516
  sourceId: relativePath,
@@ -527,6 +529,11 @@ export async function readFileContents(files, baseDir = process.cwd(), options =
527
529
  return results.filter((result) => result !== null);
528
530
  }
529
531
 
532
+ export function calculateTokens(text) {
533
+ const tokens = encode(text);
534
+ return tokens.length;
535
+ }
536
+
530
537
  /**
531
538
  * Calculate total lines and tokens from file contents
532
539
  * @param {Array<{content: string}>} sourceFiles - Array of objects containing content property
@@ -552,97 +559,17 @@ export function calculateFileStats(sourceFiles) {
552
559
  }
553
560
 
554
561
  /**
555
- * Build sources content string based on context size
556
- * For large contexts, only include core project files to avoid token limit issues
562
+ * Build sources content string
557
563
  * @param {Array<{sourceId: string, content: string}>} sourceFiles - Array of source file objects
558
- * @param {boolean} isLargeContext - Whether the context is large
559
564
  * @returns {string} Concatenated sources content with sourceId comments
560
565
  */
561
- export function buildSourcesContent(sourceFiles, isLargeContext = false) {
562
- // Define core file patterns that represent project structure and key information
563
- const coreFilePatterns = [
564
- // Configuration files
565
- /package\.json$/,
566
- /tsconfig\.json$/,
567
- /jsconfig\.json$/,
568
- /\.env\.example$/,
569
- /Cargo\.toml$/,
570
- /go\.mod$/,
571
- /pom\.xml$/,
572
- /build\.gradle$/,
573
- /Gemfile$/,
574
- /requirements\.txt$/,
575
- /Pipfile$/,
576
- /composer\.json$/,
577
- /pyproject\.toml$/,
578
-
579
- // Documentation
580
- /README\.md$/i,
581
- /CHANGELOG\.md$/i,
582
- /CONTRIBUTING\.md$/i,
583
- /\.github\/.*\.md$/i,
584
-
585
- // Entry points and main files
586
- /index\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
587
- /main\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
588
- /app\.(js|ts|jsx|tsx|py)$/,
589
- /server\.(js|ts|jsx|tsx|py)$/,
590
-
591
- // API definitions
592
- /api\/.*\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
593
- /routes\/.*\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
594
- /controllers\/.*\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
595
-
596
- // Type definitions and schemas
597
- /types\.(ts|d\.ts)$/,
598
- /schema\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
599
- /.*\.d\.ts$/,
600
-
601
- // Core utilities
602
- /utils\/.*\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
603
- /lib\/.*\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
604
- /helpers\/.*\.(js|ts|jsx|tsx|py|go|rs|java|rb|php)$/,
605
- ];
606
-
607
- // Function to check if a file is a core file
608
- const isCoreFile = (filePath) => {
609
- return coreFilePatterns.some((pattern) => pattern.test(filePath));
610
- };
611
-
566
+ export function buildSourcesContent(sourceFiles) {
612
567
  // Build sources string
613
568
  let allSources = "";
614
569
 
615
- if (isLargeContext) {
616
- // Only include core files for large contexts
617
- const coreFiles = sourceFiles.filter((source) => isCoreFile(source.sourceId));
618
-
619
- // Determine which files to use and set appropriate message
620
- const filesToInclude = coreFiles.length > 0 ? coreFiles : sourceFiles;
621
- const noteMessage =
622
- coreFiles.length > 0
623
- ? "// Note: Context is large, showing only core project files.\n"
624
- : "// Note: Context is large, showing a sample of files.\n";
625
-
626
- allSources += noteMessage;
627
- let accumulatedTokens = 0;
628
-
629
- for (const source of filesToInclude) {
630
- const fileContent = `// sourceId: ${source.sourceId}\n${source.content}\n`;
631
- const fileTokens = encode(fileContent);
632
-
633
- // Check if adding this file would exceed the token limit
634
- if (accumulatedTokens + fileTokens.length > INTELLIGENT_SUGGESTION_TOKEN_THRESHOLD) {
635
- break;
636
- }
637
-
638
- allSources += fileContent;
639
- accumulatedTokens += fileTokens.length;
640
- }
641
- } else {
642
- // Include all files for normal contexts
643
- for (const source of sourceFiles) {
644
- allSources += `// sourceId: ${source.sourceId}\n${source.content}\n`;
645
- }
570
+ // Include all files for normal contexts
571
+ for (const source of sourceFiles) {
572
+ allSources += `\n// sourceId: ${source.sourceId}\n${source.content}\n`;
646
573
  }
647
574
 
648
575
  return allSources;
@@ -1,131 +0,0 @@
1
- import {
2
- buildSourcesContent,
3
- calculateFileStats,
4
- loadFilesFromPaths,
5
- readFileContents,
6
- } from "../../../utils/file-utils.mjs";
7
- import {
8
- INTELLIGENT_SUGGESTION_TOKEN_THRESHOLD,
9
- DEFAULT_EXCLUDE_PATTERNS,
10
- DEFAULT_INCLUDE_PATTERNS,
11
- } from "../../../utils/constants/index.mjs";
12
- import { toRelativePath } from "../../../utils/utils.mjs";
13
-
14
- export default async function generateSubStructure(
15
- {
16
- parentDocument,
17
- subSourcePaths,
18
- includePatterns,
19
- excludePatterns,
20
- useDefaultPatterns = true,
21
- ...rest
22
- },
23
- options,
24
- ) {
25
- const sourcePaths = subSourcePaths?.map((item) => item.path);
26
- if (!sourcePaths || sourcePaths.length === 0) {
27
- return {
28
- subStructure: [],
29
- };
30
- }
31
-
32
- let files = await loadFilesFromPaths(sourcePaths, {
33
- includePatterns,
34
- excludePatterns,
35
- useDefaultPatterns,
36
- defaultIncludePatterns: DEFAULT_INCLUDE_PATTERNS,
37
- defaultExcludePatterns: DEFAULT_EXCLUDE_PATTERNS,
38
- });
39
- files = [...new Set(files)];
40
-
41
- // all files path
42
- const allFilesPaths = files.map((file) => `- ${toRelativePath(file)}`).join("\n");
43
-
44
- // Read all source files using the utility function
45
- const sourceFiles = await readFileContents(files, process.cwd());
46
-
47
- // Count tokens and lines using utility function
48
- const { totalTokens } = calculateFileStats(sourceFiles);
49
-
50
- // check if totalTokens is too large
51
- let isLargeContext = false;
52
- if (totalTokens > INTELLIGENT_SUGGESTION_TOKEN_THRESHOLD) {
53
- isLargeContext = true;
54
- }
55
-
56
- // Build allSources string using utility function
57
- const allSources = buildSourcesContent(sourceFiles, isLargeContext);
58
-
59
- // Performance optimization:
60
- // Using both structured output and Tool with Gemini model causes redundant calls
61
- // Only use Tool when context is very large
62
- const generateStructureAgent = isLargeContext
63
- ? options.context.agents["generateStructure"]
64
- : options.context.agents["generateStructureWithoutTools"];
65
- const result = await options.context.invoke(generateStructureAgent, {
66
- ...rest,
67
- isSubStructure: true,
68
- parentDocument,
69
- datasources: allSources,
70
- allFilesPaths,
71
- isLargeContext,
72
- files,
73
- totalTokens,
74
- });
75
-
76
- return {
77
- subStructure: result.documentStructure || [],
78
- message: `Generated a sub structure for '${parentDocument.path}' successfully. Please merge all sub-structures to output the complete document structure.`,
79
- };
80
- }
81
-
82
- generateSubStructure.description = `
83
- Generates a sub-structure.
84
- Handles large file sets by splitting them into smaller sub-document structures when the context size exceeds limits. This approach ensures more focused and complete documentation generation.
85
- `;
86
-
87
- generateSubStructure.inputSchema = {
88
- type: "object",
89
- properties: {
90
- parentDocument: {
91
- type: "object",
92
- description: "The parent node to generate a sub structure for",
93
- properties: {
94
- title: { type: "string", description: "The title of the parent node" },
95
- description: { type: "string", description: "The description of the parent node" },
96
- path: {
97
- type: "string",
98
- description:
99
- "The path of the parent node, Path in URL format, cannot be empty, cannot contain spaces or special characters, must start with /, no need to include language level, e.g., /zh/about should return /about ",
100
- },
101
- parentId: { type: "string", description: "The parent ID of the parent node" },
102
- sourceIds: { type: "array", description: "The source IDs of the parent node" },
103
- },
104
- },
105
- subSourcePaths: {
106
- type: "array",
107
- description: "The source paths of the sub structure",
108
- items: {
109
- type: "object",
110
- properties: {
111
- path: { type: "string", description: "The source path of the sub structure" },
112
- reason: { type: "string", description: "The reason for selecting the source path" },
113
- },
114
- required: ["path", "reason"],
115
- },
116
- },
117
- },
118
- };
119
-
120
- generateSubStructure.outputSchema = {
121
- type: "object",
122
- properties: {
123
- subStructure: {
124
- type: "array",
125
- description:
126
- "The sub structure of the parent node, need merge all sub-structures and output the complete document structure.",
127
- },
128
- message: { type: "string", description: "The message of the sub structure" },
129
- },
130
- required: ["subStructure"],
131
- };
@@ -1,65 +0,0 @@
1
- name: generateStructureWithoutTools
2
- description: Generate the structure and organization of your documentation
3
- instructions:
4
- - role: system
5
- url: ../../prompts/structure/generate/system-prompt.md
6
- - role: user
7
- url: ../../prompts/structure/generate/user-prompt.md
8
- task_render_mode: collapse
9
- task_title: Generate the structure of the documentation
10
- input_schema:
11
- type: object
12
- properties:
13
- rules:
14
- type: string
15
- description: Your specific requirements for documentation structure
16
- locale:
17
- type: string
18
- description: Primary language for documentation (e.g., zh, en, ja)
19
- datasources:
20
- type: string
21
- description: Project content and context to help generate documentation structure
22
- targetAudience:
23
- type: string
24
- description: Target audience for the documentation
25
- nodeName:
26
- type: string
27
- description: Specific section or page name to focus on
28
- glossary:
29
- type: string
30
- description: Glossary for consistent terminology
31
- feedback:
32
- type: string
33
- description: Tell us how to improve the documentation structure
34
- userPreferences:
35
- type: string
36
- description: Your saved preferences for structure and documentation style
37
- docsType:
38
- type: string
39
- description: "Documentation type (options: general, getting-started, reference, faq)"
40
- default: general
41
- required:
42
- - rules
43
- - datasources
44
- output_schema:
45
- type: object
46
- properties:
47
- projectName:
48
- type: string
49
- description: Project name identified from your content sources
50
- projectDesc:
51
- type: string
52
- description: Brief project description generated from content analysis (under 50 words)
53
- documentStructure: ../schema/document-structure.yaml
54
- documentStructureTree:
55
- type: string
56
- description: |
57
- Visual tree structure showing documentation hierarchy with indented levels for easy review:
58
- ```
59
- - Home
60
- - Getting Started
61
- - Installation
62
- - Requirements
63
- ```
64
- required:
65
- - documentStructure