fix trans tool

This commit is contained in:
duanfuxiang
2025-06-29 08:28:50 +08:00
parent 772270863c
commit f3a0252ab6
25 changed files with 1173 additions and 441 deletions

View File

@@ -4,6 +4,39 @@ const RegexSearchFilesInstructions = "\n- You can use regex_search_files to perf
const SemanticSearchFilesInstructions = "\n- You can use semantic_search_files to find content based on meaning rather than exact text matches. Semantic search uses embedding vectors to understand concepts and ideas, finding relevant content even when keywords differ. This is especially powerful for discovering thematically related notes, answering conceptual questions about your knowledge base, or finding content when you don't know the exact wording used in the notes."
function getAskModeCapabilitiesSection(
cwd: string,
searchFilesTool: string,
): string {
let searchFilesInstructions: string;
switch (searchFilesTool) {
case 'match':
searchFilesInstructions = MatchSearchFilesInstructions;
break;
case 'regex':
searchFilesInstructions = RegexSearchFilesInstructions;
break;
case 'semantic':
searchFilesInstructions = SemanticSearchFilesInstructions;
break;
default:
searchFilesInstructions = "";
}
return `====
CAPABILITIES
Your primary role is to act as an intelligent Knowledge Assistant deeply integrated within this Obsidian vault. You are equipped with four core capabilities that map directly to user intents:
1. **Insight & Understanding**: This is your most powerful capability. You can synthesize, analyze, compare, and understand content across various scopes. By using the \`insights\` tool, you can process single notes, entire folders, or notes with specific tags to extract high-level insights, summaries, and key points. This allows you to answer complex questions without needing to manually read every single file.
2. **Lookup & Navigate**: You can efficiently locate specific information. You can perform semantic searches for concepts (\`search_files\`) and structured queries for metadata like tags or dates (\`dataview_query\`). The initial file list in \`environment_details\` provides a starting point, but you should use your search tools to find the most relevant information.
3. **Create & Generate**: You can act as a writing partner to create new content. Using the \`write_to_file\` tool, you can draft new notes, brainstorm ideas, or generate structured documents from templates, helping the user expand their knowledge base.
4. **Action & Integration**: You can connect the knowledge in this vault to the outside world. Through the \`use_mcp_tool\`, you can interact with external services like task managers or calendars, turning insights into actions.${searchFilesInstructions}`
}
function getObsidianCapabilitiesSection(
cwd: string,
searchFilesTool: string,
@@ -78,13 +111,16 @@ CAPABILITIES
export function getCapabilitiesSection(
mode: string,
cwd: string,
searchWebTool: string,
searchFileTool: string,
): string {
if (mode === 'ask') {
return getAskModeCapabilitiesSection(cwd, searchFileTool);
}
if (mode === 'research') {
return getDeepResearchCapabilitiesSection();
}
if (mode === 'learn') {
return getLearnModeCapabilitiesSection(cwd, searchWebTool);
return getLearnModeCapabilitiesSection(cwd, searchFileTool);
}
return getObsidianCapabilitiesSection(cwd, searchWebTool);
return getObsidianCapabilitiesSection(cwd, searchFileTool);
}

View File

@@ -1,3 +1,24 @@
function getAskModeObjectiveSection(): string {
return `====
OBJECTIVE
Your primary objective is to accurately fulfill the user's request by methodically following a clear, iterative process.
1. **Analyze and Classify Intent**: First, analyze the user's request to determine its core intent based on the four categories you know: **Insight & Understanding**, **Lookup & Navigate**, **Create & Generate**, or **Action & Integration**. This classification is the most critical step and dictates your entire plan.
2. **Formulate a Plan in <thinking>**: Inside \`<thinking>\` tags, state the identified intent and your step-by-step plan. Your plan must start with selecting the single most appropriate primary tool for the intent (e.g., \`insights\` for understanding, \`search_files\` for lookup, \`write_to_file\` for creation).
3. **Execute Tools with Precision**: Before invoking a tool, you must verify that you have all its required parameters.
* Carefully consider the user's request and the conversation context to see if values for required parameters can be reasonably inferred.
* If all required parameters are present or can be inferred, proceed with the tool use.
* However, if a required parameter is missing and cannot be inferred, **DO NOT** invoke the tool. Instead, use the \`ask_followup_question\` tool to ask the user for the specific missing information. Do not ask for optional parameters if they are not provided.
4. **Synthesize and Respond Directly**: After receiving the tool result, construct your final answer. Do not end your responses with generic questions like "Is there anything else I can help with?". When you have completed the task, state that you are done.
5. **Adhere to All Rules**: In every step, you must strictly adhere to all constraints and formatting requirements defined in the RULES section, especially regarding source citation and tool selection guidelines.
`
}
function getLearnModeObjectiveSection(): string {
return `====
@@ -20,7 +41,7 @@ You enhance learning and comprehension by transforming information into digestib
Before using any tool, analyze the learning context within <thinking></thinking> tags. Consider the user's learning goals, existing knowledge level, and how the current task fits into their broader learning objectives. Prioritize transformation tools for content analysis and focus on creating materials that promote active learning rather than passive consumption.`
}
function getDeepResearchObjectiveSection(): string {
function getDeepResearchObjectiveSection(): string {
return `====
OBJECTIVE
@@ -51,6 +72,9 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
}
export function getObjectiveSection(mode: string): string {
if (mode === 'ask') {
return getAskModeObjectiveSection();
}
if (mode === 'research') {
return getDeepResearchObjectiveSection();
}

View File

@@ -69,6 +69,36 @@ RULES
`
}
function getAskModeRulesSection(
cwd: string,
searchTool: string,
): string {
return `====
RULES
- Your current obsidian directory is: ${cwd.toPosix()}
${getSearchInstructions(searchTool)}
- **Mandatory Thinking Process**: You MUST use <thinking> tags to outline your reasoning and plan before every action. This is not optional.
- **Intent-Driven Tool Selection**: You must strictly follow the "Intent Analysis" guide to select the single most appropriate primary tool (\`search_files\`, \`dataview_query\`, \`insights\`, \`write_to_file\`, or \`use_mcp_tool\`).
- **Use 'insights' for Understanding**: For any request that involves summarizing, analyzing, comparing, or understanding content, your primary tool MUST be \`insights\`. Do not try to manually read multiple files and synthesize them yourself unless the \`insights\` tool is insufficient.
- **Cite Sources with [[WikiLinks]]**: You MUST use Obsidian-style [[WikiLinks]] to reference all source notes. This is a critical rule. The link must be the full relative path of the note from the vault root (e.g., \`[[Daily Notes/2024-05-21]]\`). Never use bare filenames or standard Markdown links (\`[text](path)\`) when referring to notes within the vault.
- **One Tool at a Time**: Use only one tool per message. Wait for the result before deciding on the next step.
## Thinking Tag Structure
You are required to use the following structure inside your <thinking> tags:
<thinking>
**1. Intent:** [Your analysis of the user's intent: Lookup & Navigate, Insight & Understanding, Create & Generate, or Action & Integration]
**2. Plan:**
- Step 1: Based on the intent, I will use the \`[Primary Tool]\` to \`[Action for this tool, e.g., 'get insights on Topic X from the whole vault']\`.
- Step 2: (If necessary, based on the result of Step 1) Use a follow-up tool to refine or act on the result.
- Step 3: Construct the final answer, citing all sources with [[WikiLinks]] if applicable.
**3. Justification:** [Briefly explain why you chose this primary tool based on your intent analysis.]
</thinking>
`
}
function getObsidianRulesSection(
mode: string,
cwd: string,
@@ -107,6 +137,9 @@ export function getRulesSection(
diffStrategy?: DiffStrategy,
experiments?: Record<string, boolean> | undefined,
): string {
if (mode === 'ask') {
return getAskModeRulesSection(cwd, searchTool);
}
if (mode === 'research') {
return getDeepResearchRulesSection();
}

View File

@@ -1,4 +1,3 @@
import os from "os"
import { Platform } from 'obsidian';

View File

@@ -1,3 +1,42 @@
function getAskModeToolUseGuidelines(): string {
return `# Workflow & Decision Guide
When you receive a user question, follow this systematic thinking process to build your action plan:
## Step 1: Intent Analysis
This is your most important task. Carefully analyze the user's question to determine its primary intent from the following categories:
* **Lookup & Navigate**: The user wants to *find and locate* raw information or notes within their vault. The goal is to get a pointer to the original content.
* *Keywords*: "find...", "search for...", "list all notes...", "open the note about...", "where did I mention..."
* *Primary Tools*: \`search_files\`, \`dataview_query\`.
* **Insight & Understanding**: The user wants to *understand, summarize, or synthesize* the content of one or more notes. The goal is a processed answer, not the raw text. This is the primary purpose of the \`insights\` tool.
* *Keywords*: "summarize...", "what are the key points of...", "explain my thoughts on...", "compare A and B...", "analyze the folder..."
* *Primary Tool*: \`insights\`. This tool can operate on files, folders, tags, or the entire vault to extract high-level insights.
* **Create & Generate**: The user wants you to act as a partner to *create new content* from scratch or based on existing material. The goal is a new note in their vault.
* *Keywords*: "draft a blog post...", "create a new note for...", "brainstorm ideas about...", "generate a plan for..."
* *Primary Tool*: \`write_to_file\`.
* **Action & Integration**: The user's request requires interaction with a service *outside* of Obsidian, such as a task manager or calendar.
* *Keywords*: "create a task...", "send an email to...", "schedule an event..."
* *Primary Tool*: \`use_mcp_tool\`.
## Step 2: Primary Tool Execution
Based on your intent analysis, select and execute the single most appropriate primary tool to get initial information.
## Step 3: Enhancement & Follow-up (If Needed)
After getting the primary tool result, decide if you need follow-up tools to complete the answer:
- If \`search_files\` or \`dataview_query\` returned a list of notes and you need to understand their content → Use the \`insights\` tool on the relevant files or folders to extract key information.
- If you need to examine specific raw content → Use \`read_file\` to get the full text of particular notes.
- If you need to save your findings → Use \`write_to_file\` to create a new, well-structured summary note.
## Step 4: Answer Construction & Citation
Build your final response based on all collected and processed information. When the answer is based on vault content, you **MUST** use \`[[WikiLinks]]\` to cite all source notes you consulted.
`
}
function getLearnModeToolUseGuidelines(): string {
return `# Tool Use Guidelines
@@ -68,6 +107,9 @@ By waiting for and carefully considering the user's response after each tool use
}
export function getToolUseGuidelinesSection(mode?: string): string {
if (mode === 'ask') {
return getAskModeToolUseGuidelines()
}
if (mode === 'learn') {
return getLearnModeToolUseGuidelines()
}

View File

@@ -1,4 +1,3 @@
import * as path from 'path'
import { App, normalizePath } from 'obsidian'
@@ -10,9 +9,9 @@ import {
ModeConfig,
PromptComponent,
defaultModeSlug,
defaultModes,
getGroupName,
getModeBySlug,
defaultModes
getModeBySlug
} from "../../utils/modes"
import { DiffStrategy } from "../diff/DiffStrategy"
import { McpHub } from "../mcp/McpHub"
@@ -138,7 +137,7 @@ ${getRulesSection(
experiments,
)}
${getSystemInfoSection(cwd)}
// ${getSystemInfoSection(cwd)}
${getObjectiveSection(mode)}

View File

@@ -0,0 +1,26 @@
import { ToolArgs } from "./types"
export function getCallInsightsDescription(args: ToolArgs): string {
return `## insights
Description: Use for **Information Processing**. After reading a note's content, use this tool to process and distill the information in various ways. You must choose the most appropriate transformation type based on your goal.
Parameters:
- path: (required) The path to the file or folder to be processed (relative to the current working directory: ${args.cwd}).
- transformation: (required) The type of transformation to apply. Must be one of the following:
- **simple_summary**: Creates a clear, simple summary. Use when you need to quickly understand the main points or explain a complex topic easily.
- **key_insights**: Extracts high-level, critical insights and non-obvious connections. Use when you want to understand the deeper meaning or strategic implications.
- **dense_summary**: Provides a comprehensive, information-rich summary. Use when detail is important but you need it in a condensed format.
- **reflections**: Generates deep, reflective questions and perspectives to s·park new ideas. Use when you want to think critically *with* your notes.
- **table_of_contents**: Creates a navigable table of contents for a long document or folder. Use for structuring and organizing content.
- **analyze_paper**: Performs an in-depth analysis of an academic paper, breaking down its components. Use for scholarly or research documents.
Usage:
<insights>
<path>path/to/your/file.md</path>
<type>simple_summary</type>
</insights>
Example: Getting the key insights from a project note
<insights>
<path>Projects/Project_Alpha_Retrospective.md</path>
<type>key_insights</type>
</insights>`
}

View File

@@ -2,12 +2,14 @@ import { ToolArgs } from "./types"
export function getDataviewQueryDescription(args: ToolArgs): string {
return `## dataview_query
Description: Execute advanced queries using the Dataview plugin to retrieve and filter note information across multiple dimensions. Supports complex queries by time, tags, task status, file properties, and more. This is a powerful tool for obtaining structured note data, particularly useful for statistical analysis, content organization, and progress tracking scenarios.
Description: Use for **Metadata Lookup**. Executes a Dataview query to find notes based on structural attributes like tags, folders, dates, or other metadata properties. This is your primary tool when the user's request is about filtering or finding notes with specific characteristics, not about understanding a concept.
Parameters:
- query: (required) The Dataview query statement to execute. Supports DQL (Dataview Query Language) syntax, including TABLE, LIST, TASK query types
- output_format: (optional) Output format, options: table, list, task, calendar (defaults to table)
- query: (required) The Dataview query statement (DQL).
Common Query Patterns:
- Find notes with a tag: \`LIST FROM #project\`
- Find notes in a folder: \`LIST FROM "Meetings"\`
- Find notes by task completion: \`TASK WHERE completed\`
**Time-based Queries:**
- Recently created: \`WHERE file.ctime >= date(today) - dur(7 days)\`
@@ -21,7 +23,6 @@ Common Query Patterns:
**Task-based Queries:**
- Incomplete tasks: \`TASK WHERE !completed\`
- Completed tasks: \`TASK WHERE completed\`
- Specific priority tasks: \`TASK WHERE contains(text, "high priority")\`
**File Property Queries:**

View File

@@ -6,6 +6,7 @@ import { McpHub } from "../../mcp/McpHub"
import { getAccessMcpResourceDescription } from "./access-mcp-resource"
import { getAskFollowupQuestionDescription } from "./ask-followup-question"
import { getAttemptCompletionDescription } from "./attempt-completion"
import { getCallInsightsDescription } from "./call-insights"
import { getDataviewQueryDescription } from "./dataview-query"
import { getFetchUrlsContentDescription } from "./fetch-url-content"
import { getInsertContentDescription } from "./insert-content"
@@ -18,14 +19,6 @@ import { getSwitchModeDescription } from "./switch-mode"
import { ALWAYS_AVAILABLE_TOOLS, TOOL_GROUPS } from "./tool-groups"
import { ToolArgs } from "./types"
import { getUseMcpToolDescription } from "./use-mcp-tool"
import {
getAnalyzePaperDescription,
getDenseSummaryDescription,
getKeyInsightsDescription,
getReflectionsDescription,
getSimpleSummaryDescription,
getTableOfContentsDescription
} from "./use-transformations-tool"
import { getWriteToFileDescription } from "./write-to-file"
// Map of tool names to their description functions
@@ -34,6 +27,7 @@ const toolDescriptionMap: Record<string, (args: ToolArgs) => string | undefined>
write_to_file: (args) => getWriteToFileDescription(args),
search_files: (args) => getSearchFilesDescription(args),
list_files: (args) => getListFilesDescription(args),
insights: (args) => getCallInsightsDescription(args),
dataview_query: (args) => getDataviewQueryDescription(args),
ask_followup_question: () => getAskFollowupQuestionDescription(),
attempt_completion: () => getAttemptCompletionDescription(),
@@ -46,12 +40,6 @@ const toolDescriptionMap: Record<string, (args: ToolArgs) => string | undefined>
args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : "",
search_web: (args): string | undefined => getSearchWebDescription(args),
fetch_urls_content: (args): string | undefined => getFetchUrlsContentDescription(args),
analyze_paper: (args) => getAnalyzePaperDescription(args),
key_insights: (args) => getKeyInsightsDescription(args),
dense_summary: (args) => getDenseSummaryDescription(args),
reflections: (args) => getReflectionsDescription(args),
table_of_contents: (args) => getTableOfContentsDescription(args),
simple_summary: (args) => getSimpleSummaryDescription(args),
}
export function getToolDescriptionsForMode(
@@ -117,11 +105,8 @@ export function getToolDescriptionsForMode(
// Export individual description functions for backward compatibility
export {
getAccessMcpResourceDescription, getAnalyzePaperDescription, getAskFollowupQuestionDescription,
getAttemptCompletionDescription,
getDataviewQueryDescription, getDenseSummaryDescription, getInsertContentDescription, getKeyInsightsDescription, getListFilesDescription,
getReadFileDescription, getReflectionsDescription, getSearchAndReplaceDescription,
getSearchFilesDescription, getSimpleSummaryDescription, getSwitchModeDescription, getTableOfContentsDescription, getUseMcpToolDescription,
getWriteToFileDescription
getAccessMcpResourceDescription, getReadFileDescription, getWriteToFileDescription, getSearchFilesDescription, getListFilesDescription,
getDataviewQueryDescription, getAskFollowupQuestionDescription, getAttemptCompletionDescription, getSwitchModeDescription, getInsertContentDescription,
getUseMcpToolDescription, getSearchAndReplaceDescription, getSearchWebDescription, getFetchUrlsContentDescription, getCallInsightsDescription as getCallInsightsDescription
}

View File

@@ -15,15 +15,10 @@ export const TOOL_DISPLAY_NAMES = {
dataview_query: "query dataview",
use_mcp_tool: "use mcp tools",
access_mcp_resource: "access mcp resources",
insights: "call insights",
ask_followup_question: "ask questions",
attempt_completion: "complete tasks",
switch_mode: "switch modes",
analyze_paper: "analyze papers",
key_insights: "extract key insights",
dense_summary: "create dense summaries",
reflections: "generate reflections",
table_of_contents: "create table of contents",
simple_summary: "create simple summaries",
} as const
// Define available tool groups
@@ -37,8 +32,8 @@ export const TOOL_GROUPS: Record<string, ToolGroupConfig> = {
research: {
tools: ["search_web", "fetch_urls_content"],
},
transformations: {
tools: ["analyze_paper", "key_insights", "dense_summary", "reflections", "table_of_contents", "simple_summary"],
insights: {
tools: ["insights"],
},
mcp: {
tools: ["use_mcp_tool", "access_mcp_resource"],
@@ -75,7 +70,7 @@ export const GROUP_DISPLAY_NAMES: Record<ToolGroup, string> = {
read: "Read Files",
edit: "Edit Files",
research: "Research",
transformations: "Transformations",
insights: "insights",
mcp: "MCP Tools",
modes: "Modes",
}