From c0a6d6f2f98bab3c7f6e160f58a872cefd1238fe Mon Sep 17 00:00:00 2001 From: Abeautifulsnow Date: Wed, 5 Aug 2026 11:15:35 +0800 Subject: [PATCH] feat(agent): add timezone-aware current time tool --- apps/desktop/src/lib/ai/ai.ts | 16 +- crates/dbx-core/src/agent_tools.rs | 238 +++++++++++++++++++++++++++- packages/app-tests/aiPrompt.test.ts | 11 ++ 3 files changed, 256 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.ts index fa265c4e4d..225ac22a37 100644 --- a/apps/desktop/src/lib/ai/ai.ts +++ b/apps/desktop/src/lib/ai/ai.ts @@ -351,23 +351,27 @@ function buildVectorSystemPrompt(context: AiContext, mode: AiAssistantMode, cust } function buildVectorModePromptLines(context: AiContext, mode: AiAssistantMode, isZh: boolean): string[] { + const currentTimeGuidance = currentTimeToolGuidance(); if (mode === "agent") { - return [isZh ? "你处于 Agent 模式。你有以下工具可用:list_collections、browse_collection。" : "You are in Agent mode. You have the following tools available: list_collections, browse_collection."]; + return [isZh ? "你处于 Agent 模式。你有以下工具可用:list_collections、browse_collection、get_current_time。" : "You are in Agent mode. You have the following tools available: list_collections, browse_collection, get_current_time.", currentTimeGuidance]; } return [ isZh ? `你处于 Ask 模式。你只能使用 list_collections 确认集合清单;不要浏览集合数据。${dbLabel(context.databaseType)} 的查询格式为 REST API(METHOD /path + JSON body),具体格式因数据库类型而异。只生成查询请求文本和说明,不要暗示已经执行。` : `You are in Ask mode. You may only use list_collections to inspect collection names; do not browse collection data. ${dbLabel(context.databaseType)} uses a REST API query format (METHOD /path + JSON body) that varies by database type. Generate query strings and explanations only; do not imply execution.`, + currentTimeGuidance, ]; } function buildModePromptLines(mode: AiAssistantMode, isZh: boolean): string[] { + const currentTimeGuidance = currentTimeToolGuidance(); if (mode === "agent") { return [ - isZh ? "你处于 Agent 模式。你有以下工具可用:list_tables、get_columns、execute_query、get_sample_data。" : "You are in Agent mode. You have the following tools available: list_tables, get_columns, execute_query, get_sample_data.", + isZh ? "你处于 Agent 模式。你有以下工具可用:list_tables、get_columns、execute_query、get_sample_data、get_current_time。" : "You are in Agent mode. You have the following tools available: list_tables, get_columns, execute_query, get_sample_data, get_current_time.", isZh ? "用户提出数据查询意图时,必须调用 execute_query 工具执行 SQL,不要只输出 SQL 文本后停止。先用 list_tables/get_columns 了解 schema,再调用 execute_query 获取真实结果,最后基于结果回答用户。" : "When the user expresses a data query intent, you MUST call the execute_query tool to run the SQL — do NOT just output SQL text and stop. Use list_tables/get_columns to understand the schema first, then call execute_query to get real results, then answer based on the actual data.", + currentTimeGuidance, isZh ? "当用户要求写入操作(INSERT/UPDATE/DELETE/CREATE/ALTER/DROP/TRUNCATE 等)时,先在一个 ```sql 代码块中给出精确的写 SQL,再在回复末尾用问句明确询问用户是否确认执行(例如'需要我执行这条 CREATE TABLE 语句吗?')。待用户明确确认后再调用 execute_query,并原样使用该代码块中的 SQL,不得改写、重新格式化或补充语句。禁止不经确认直接执行写入。" : "When the user requests a write operation (INSERT/UPDATE/DELETE/CREATE/ALTER/DROP/TRUNCATE, etc.), first put the exact proposed write SQL in one ```sql code block, then ask for explicit confirmation at the end of your reply with a question that names the specific operation (e.g., 'Should I execute this CREATE TABLE?'). Only call execute_query for writes after the user explicitly confirms, and use the exact SQL from that code block without rewriting, reformatting, or adding statements. Never execute writes without confirmation.", @@ -375,7 +379,13 @@ function buildModePromptLines(mode: AiAssistantMode, isZh: boolean): string[] { ]; } - return [isZh ? "你处于 Ask 模式。只生成 SQL 和说明,不要暗示已经执行或即将自动执行。" : "You are in Ask mode. Generate SQL and explanations only; do not imply that anything has run or will auto-run."]; + return [isZh ? "你处于 Ask 模式。只生成 SQL 和说明,不要暗示已经执行或即将自动执行。" : "You are in Ask mode. Generate SQL and explanations only; do not imply that anything has run or will auto-run.", currentTimeGuidance]; +} + +function currentTimeToolGuidance(): string { + const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + const utcOffsetMinutes = -new Date().getTimezoneOffset(); + return `When a request needs a relative time expression such as yesterday, last 7 days, this month, or today, call get_current_time first with {"timezone":"${timezone}","utc_offset_minutes":${utcOffsetMinutes}}; do not guess the current date or timezone.`; } function schemaCoverageLine(context: AiContext, isZh: boolean): string { diff --git a/crates/dbx-core/src/agent_tools.rs b/crates/dbx-core/src/agent_tools.rs index 014de5dbb1..7cadf44293 100644 --- a/crates/dbx-core/src/agent_tools.rs +++ b/crates/dbx-core/src/agent_tools.rs @@ -111,13 +111,75 @@ pub fn is_vector_db(db_type: DatabaseType) -> bool { matches!(db_type, DatabaseType::Qdrant | DatabaseType::Milvus | DatabaseType::Weaviate | DatabaseType::ChromaDb) } +/// `get_current_time` tool definition — DB-independent utility that returns +/// the current UTC time plus a caller-provided local offset. +fn get_current_time_tool() -> ToolDefinition { + ToolDefinition { + name: "get_current_time", + description: "Get the current date and time with timezone information. \ + Pass the client UTC offset from the system prompt; when \ + omitted, local time safely falls back to UTC. Use this to resolve \ + relative time expressions like \"last 7 days\", \ + \"yesterday\", \"this month\" into concrete dates \ + for constructing SQL queries.", + parameters: json!({ + "type": "object", + "properties": { + "utc_offset_minutes": { + "type": "integer", + "minimum": -1439, + "maximum": 1439, + "description": "Client UTC offset in minutes from the system prompt" + }, + "timezone": { + "type": "string", + "description": "Client IANA timezone name from the system prompt" + } + }, + "required": [] + }), + read_only: true, + parallel_ok: true, + } +} + +/// Execute `get_current_time` — returns a JSON payload with utc, local, +/// utc_offset_minutes, timezone, and readable fields. +fn execute_get_current_time(tool_call: &ToolCall) -> Result { + let utc = chrono::Utc::now(); + let offset_minutes = tool_call.arguments.get("utc_offset_minutes").and_then(serde_json::Value::as_i64).unwrap_or(0); + let offset_minutes = i32::try_from(offset_minutes).map_err(|_| "utc_offset_minutes is out of range".to_string())?; + let offset_seconds = + offset_minutes.checked_mul(60).ok_or_else(|| "utc_offset_minutes is out of range".to_string())?; + let offset = chrono::FixedOffset::east_opt(offset_seconds) + .ok_or_else(|| "utc_offset_minutes must be between -1439 and 1439".to_string())?; + let local = utc.with_timezone(&offset); + let timezone = tool_call + .arguments + .get("timezone") + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| if offset_minutes == 0 { "UTC".to_string() } else { format!("UTC{}", local.format("%:z")) }); + let readable = format!("{} ({timezone}, UTC{})", local.format("%Y-%m-%d %H:%M:%S"), local.format("%:z")); + Ok(serde_json::json!({ + "utc": utc.to_rfc3339(), + "local": local.to_rfc3339(), + "utc_offset_minutes": offset_minutes, + "timezone": timezone, + "readable": readable, + }) + .to_string()) +} + /// Get read-only tool definitions for the given database type. /// Returns vector tools for vector DBs, SQL tools otherwise. pub fn read_only_tools(db_type: DatabaseType) -> Vec { if is_vector_db(db_type) { - vec![list_collections_tool()] + vec![list_collections_tool(), get_current_time_tool()] } else { - vec![list_tables_tool(), get_columns_tool()] + vec![list_tables_tool(), get_columns_tool(), get_current_time_tool()] } } @@ -126,9 +188,9 @@ pub fn read_only_tools(db_type: DatabaseType) -> Vec { /// explain_query for database types that support them. pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) -> Vec { if is_vector_db(db_type) { - return vec![list_collections_tool(), browse_collection_tool()]; + return vec![list_collections_tool(), browse_collection_tool(), get_current_time_tool()]; } - let mut tools = vec![list_tables_tool(), get_columns_tool()]; + let mut tools = vec![list_tables_tool(), get_columns_tool(), get_current_time_tool()]; if supports_sql_query(db_type) { tools.push(execute_query_tool(sql_permissions)); tools.push(get_sample_data_tool()); @@ -358,6 +420,7 @@ pub async fn execute_tool( } } } + "get_current_time" => execute_get_current_time(tool_call), _ => Err(format!("Unknown tool: {}", tool_call.name)), }; @@ -1096,7 +1159,9 @@ for line in sys.stdin: let tools = read_only_tools(DatabaseType::Qdrant); let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect(); - assert_eq!(names, vec!["list_collections"]); + assert!(names.contains(&"list_collections")); + assert!(!names.contains(&"browse_collection")); + assert!(names.contains(&"get_current_time")); } #[test] @@ -1104,7 +1169,9 @@ for line in sys.stdin: let tools = all_tools(DatabaseType::Qdrant, AgentSqlPermissions::default()); let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect(); - assert_eq!(names, vec!["list_collections", "browse_collection"]); + assert!(names.contains(&"list_collections")); + assert!(names.contains(&"browse_collection")); + assert!(names.contains(&"get_current_time")); } #[test] @@ -1468,4 +1535,163 @@ for line in sys.stdin: // allow_write_sql=true when a specific SQL was confirmed. assert!(sql_matches_confirmed_write("INSERT INTO t VALUES (1)", &None)); } + + // ── get_current_time tests ──────────────────────────────────────────── + + #[test] + fn get_current_time_is_in_all_tools_postgres() { + let tools = all_tools(DatabaseType::Postgres, AgentSqlPermissions::default()); + let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect(); + assert!(names.contains(&"get_current_time"), "get_current_time missing from all_tools(Postgres)"); + } + + #[test] + fn get_current_time_is_in_read_only_tools_postgres() { + let tools = read_only_tools(DatabaseType::Postgres); + let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect(); + assert!(names.contains(&"get_current_time"), "get_current_time missing from read_only_tools(Postgres)"); + } + + #[test] + fn get_current_time_is_in_all_tools_qdrant() { + let tools = all_tools(DatabaseType::Qdrant, AgentSqlPermissions::default()); + let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect(); + assert!(names.contains(&"get_current_time"), "get_current_time missing from all_tools(Qdrant)"); + } + + #[test] + fn get_current_time_is_in_read_only_tools_qdrant() { + let tools = read_only_tools(DatabaseType::Qdrant); + let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect(); + assert!(names.contains(&"get_current_time"), "get_current_time missing from read_only_tools(Qdrant)"); + } + + #[test] + fn get_current_time_tool_is_read_only_and_parallel_ok() { + let tool = get_current_time_tool(); + assert!(tool.read_only, "get_current_time must be read_only"); + assert!(tool.parallel_ok, "get_current_time must be parallel_ok"); + } + + #[test] + fn execute_get_current_time_returns_valid_timestamps() { + let before_secs = chrono::Utc::now().timestamp(); + let tool_call = ToolCall { + id: "call-gct".to_string(), + name: "get_current_time".to_string(), + arguments: serde_json::json!({ "utc_offset_minutes": 480, "timezone": "Asia/Shanghai" }), + provider_payload: None, + }; + let result = execute_get_current_time(&tool_call).expect("get_current_time should succeed"); + let after_secs = chrono::Utc::now().timestamp(); + + let parsed: serde_json::Value = + serde_json::from_str(&result).expect("get_current_time result should be valid JSON"); + + let utc_str = parsed["utc"].as_str().expect("utc field should be a string"); + let local_str = parsed["local"].as_str().expect("local field should be a string"); + + // Parse as RFC3339 timestamps. + let _utc_dt = chrono::DateTime::parse_from_rfc3339(utc_str).expect("utc should be valid RFC3339"); + let local_dt = chrono::DateTime::parse_from_rfc3339(local_str).expect("local should be valid RFC3339"); + + // Verify UTC is within tolerance. + let utc_dt_utc = chrono::DateTime::parse_from_rfc3339(utc_str) + .expect("utc should parse as rfc3339") + .with_timezone(&chrono::Utc); + let utc_ts = utc_dt_utc.timestamp(); + assert!( + utc_ts >= before_secs && utc_ts <= after_secs + 1, + "UTC timestamp {utc_ts} should be within [{before_secs}, {after_secs}+1]" + ); + + // Verify local is within tolerance (converted to UTC). + let local_ts = local_dt.with_timezone(&chrono::Utc).timestamp(); + assert!( + local_ts >= before_secs && local_ts <= after_secs + 1, + "Local timestamp {local_ts} (UTC) should be within [{before_secs}, {after_secs}+1]" + ); + + // utc_offset_minutes should match the offset in local. + let offset_minutes = + parsed["utc_offset_minutes"].as_i64().expect("utc_offset_minutes should be an integer") as i32; + let local_offset_secs = local_dt.offset().local_minus_utc(); + // The offset from the RFC3339 timestamp should match utc_offset_minutes * 60. + assert_eq!( + local_offset_secs / 60, + offset_minutes, + "utc_offset_minutes {offset_minutes} does not match local offset {}", + local_offset_secs / 60 + ); + assert_eq!(offset_minutes, 480); + assert_eq!(parsed["timezone"], "Asia/Shanghai"); + + // readable should be a non-empty string. + let readable = parsed["readable"].as_str().expect("readable field should be a string"); + assert!(!readable.is_empty(), "readable should not be empty"); + } + + #[test] + fn execute_get_current_time_defaults_to_utc_without_client_context() { + let tool_call = ToolCall { + id: "call-gct".to_string(), + name: "get_current_time".to_string(), + arguments: serde_json::json!({}), + provider_payload: None, + }; + let result = execute_get_current_time(&tool_call).expect("get_current_time should succeed"); + let parsed: serde_json::Value = serde_json::from_str(&result).unwrap(); + + assert_eq!(parsed["utc_offset_minutes"], 0); + assert_eq!(parsed["timezone"], "UTC"); + assert!(parsed["local"].as_str().unwrap().ends_with("+00:00")); + } + + #[test] + fn execute_get_current_time_labels_offset_when_timezone_name_is_missing() { + let tool_call = ToolCall { + id: "call-gct".to_string(), + name: "get_current_time".to_string(), + arguments: serde_json::json!({ "utc_offset_minutes": -300 }), + provider_payload: None, + }; + let result = execute_get_current_time(&tool_call).expect("get_current_time should succeed"); + let parsed: serde_json::Value = serde_json::from_str(&result).unwrap(); + + assert_eq!(parsed["timezone"], "UTC-05:00"); + assert!(parsed["local"].as_str().unwrap().ends_with("-05:00")); + } + + #[test] + fn execute_tool_get_current_time_is_not_error() { + // Test via execute_tool dispatch. All args can be dummy since the tool + // does not use any of them. + let temp_dir = tempfile::tempdir().unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + rt.block_on(async { + let storage = crate::storage::Storage::open(&temp_dir.path().join("storage.db")).await.unwrap(); + let state = std::sync::Arc::new(crate::connection::AppState::new(storage)); + let tool_call = ToolCall { + id: "call-gct".to_string(), + name: "get_current_time".to_string(), + arguments: serde_json::json!({}), + provider_payload: None, + }; + let result = execute_tool( + &tool_call, + &state, + "dummy", + "dummy", + None, + &DatabaseType::Postgres, + AgentSqlPermissions::default(), + ) + .await; + assert!(!result.is_error, "execute_tool get_current_time should not error: {}", result.content); + let parsed: serde_json::Value = serde_json::from_str(&result.content).expect("result should be valid JSON"); + assert!(parsed["utc"].is_string()); + assert!(parsed["local"].is_string()); + assert!(parsed["readable"].is_string()); + }); + } } diff --git a/packages/app-tests/aiPrompt.test.ts b/packages/app-tests/aiPrompt.test.ts index 4294ae2ca7..d44399a5d7 100644 --- a/packages/app-tests/aiPrompt.test.ts +++ b/packages/app-tests/aiPrompt.test.ts @@ -73,6 +73,9 @@ test("ask mode prompt forbids auto-execution assumptions", () => { assert.match(prompt, /Ask 模式/); assert.match(prompt, /只生成 SQL 和说明/); assert.match(prompt, /不要暗示已经执行或即将自动执行/); + assert.match(prompt, /get_current_time/); + assert.match(prompt, /utc_offset_minutes/); + assert.match(prompt, /timezone/); }); test("prompt gives explicit guidance for truncated schema context", () => { @@ -220,3 +223,11 @@ test("buildUserPrompt skips action instruction for vector databases", () => { assert.match(sqlPrompt, /Action: generate/); assert.match(sqlPrompt, /生成 SQL/); }); + +test("ask mode exposes current-time guidance for relative time filters", () => { + const sqlPrompt = buildSystemPrompt("generate", context(), "ask"); + const vectorPrompt = buildSystemPrompt("generate", vectorContext(), "ask"); + + assert.match(sqlPrompt, /get_current_time/); + assert.match(vectorPrompt, /get_current_time/); +});