File size: 38,170 Bytes
5b13359 8ed2aac 5b13359 8ed2aac 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 0c8a99f 5b13359 8ed2aac 5b13359 8ed2aac 5b13359 8ed2aac 5b13359 8ed2aac 5b13359 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 | import { z } from 'zod/v4'
import { buildTool, type ToolDef } from '../../Tool.js'
import { lazySchema } from '../../utils/lazySchema.js'
import { logError } from '../../utils/log.js'
import { LOCATION_TOOL_NAME, PROMPT } from './prompt.js'
import {
getToolUseSummary,
renderToolResultMessage,
renderToolUseMessage,
renderToolUseProgressMessage,
} from './UI.js'
import { fetchImagesAsInline } from '../../utils/inlineImageUtils.js'
// โโ Region detection โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/** Chinese cities known to be in mainland China */
const CHINA_CITIES = new Set([
'ๅไบฌ', 'ไธๆตท', 'ๅนฟๅท', 'ๆทฑๅณ', 'ๆ้ฝ', 'ๆญๅท', 'ๆญฆๆฑ', '่ฅฟๅฎ', '้ๅบ',
'ๅไบฌ', 'ๅคฉๆดฅ', '่ๅท', '้ฟๆฒ', '้ๅท', 'ไธ่', '้ๅฒ', 'ๆฒ้ณ', 'ๅฎๆณข',
'ๆๆ', 'ๅคง่ฟ', 'ๅฆ้จ', 'ๅ่ฅ', 'ไฝๅฑฑ', '็ฆๅท', 'ๅๅฐๆปจ', 'ๆตๅ', 'ๆธฉๅท',
'้ฟๆฅ', '็ณๅฎถๅบ', 'ๅธธๅท', 'ๆณๅท', 'ๅๅฎ', '่ดต้ณ', 'ๅๆ', 'ๅคชๅ', '็ๅฐ',
'ๅๅ
ด', 'ๅ้', '้ๅ', '็ ๆตท', 'ๆ ๅท', 'ๅพๅท', 'ๆตทๅฃ', 'ไน้ฒๆจ้ฝ', '็ปๅ
ด',
'ไธญๅฑฑ', 'ๅฐๅท', 'ๅ
ฐๅท', 'beijing', 'shanghai', 'guangzhou', 'shenzhen',
'chengdu', 'hangzhou', 'wuhan', 'xi\'an', 'chongqing', 'nanjing',
'tianjin', 'suzhou', 'changsha', 'zhengzhou', 'qingdao', 'shenyang',
'kunming', 'dalian', 'xiamen', 'hefei', 'foshan', 'fuzhou', 'harbin',
'jinan', 'changchun', 'shijiazhuang', 'nanning', 'guiyang', 'nanchang',
'taiyuan', 'haikou', 'urumqi', 'lanzhou', 'macau', 'macao', 'hong kong',
'xianggang',
])
const NON_CHINA_COUNTRIES = new Set([
'japan', 'korea', 'south korea', 'usa', 'united states', 'uk', 'united kingdom',
'france', 'germany', 'italy', 'spain', 'australia', 'canada', 'brazil',
'india', 'thailand', 'vietnam', 'singapore', 'malaysia', 'indonesia',
'philippines', 'russia', 'mexico', 'turkey', 'egypt', 'switzerland',
'sweden', 'norway', 'finland', 'denmark', 'netherlands', 'belgium',
'portugal', 'greece', 'ireland', 'new zealand', 'argentina', 'chile',
'peru', 'colombia', 'south africa', 'nigeria', 'kenya', 'morocco',
'็พๅฝ', 'ๆฅๆฌ', '้ฉๅฝ', '่ฑๅฝ', 'ๆณๅฝ', 'ๅพทๅฝ', 'ๆๅคงๅฉ', '่ฅฟ็ญ็',
'ๆพณๅคงๅฉไบ', 'ๅ ๆฟๅคง', 'ๅทด่ฅฟ', 'ๅฐๅบฆ', 'ๆณฐๅฝ', '่ถๅ', 'ๆฐๅ ๅก',
'้ฉฌๆฅ่ฅฟไบ', 'ไฟ็ฝๆฏ', 'ๅ่ณๅ
ถ', 'ๅๅ', '็ๅฃซ', '่ทๅ
ฐ', 'ๆฐ่ฅฟๅ
ฐ',
])
function isChinaMainland(location: string): boolean {
// Normalize curly/smart quotes to straight quotes for matching
const normalized = location.replace(/[\u2018\u2019]/g, "'")
// Contains Chinese characters โ likely China
if (/[\u4e00-\u9fff]/.test(normalized)) {
// Check for non-China country names in Chinese
const lower = normalized.toLowerCase()
for (const country of NON_CHINA_COUNTRIES) {
if (lower.includes(country)) return false
}
return true
}
const lower = normalized.toLowerCase().trim()
// Check Chinese city names
for (const city of CHINA_CITIES) {
if (lower.startsWith(city) || lower.includes(` ${city}`) || lower.includes(`, ${city}`)) {
return true
}
}
// If it looks like a country name, check against known non-China list
if (NON_CHINA_COUNTRIES.has(lower)) return false
// Default: if location is purely alphabetic/pinyin, assume non-China
return false
}
/** Parse "lat,lng" coordinate string (e.g. "34.2583,108.9286") */
function parseCoords(input: string): { lat: number; lng: number } | null {
const trimmed = input.trim()
const match = trimmed.match(/^(-?\d+\.?\d*)\s*[,๏ผ]\s*(-?\d+\.?\d*)$/)
if (!match) return null
const lat = parseFloat(match[1])
const lng = parseFloat(match[2])
if (isNaN(lat) || isNaN(lng)) return null
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null
return { lat, lng }
}
/** Detect China mainland from coordinates (rough bounding box) */
function isChinaCoords(lat: number, lng: number): boolean {
return lat >= 18 && lat <= 54 && lng >= 73 && lng <= 135
}
/** Build a LocationResult from parsed coordinates */
function coordsToLocation(lat: number, lng: number): LocationResult {
return {
lat,
lng,
formattedAddress: `${lat.toFixed(6)}, ${lng.toFixed(6)}`,
displayName: `${lat.toFixed(6)}, ${lng.toFixed(6)}`,
}
}
/** IP geolocation result for the locate action */
type IpGeoInfo = {
ip: string
city: string
region: string
country: string
lat?: number
lng?: number
}
/** Scan nearby WiFi access points via nmcli */
async function scanWiFi(): Promise<{ macAddress: string; signalStrength: number }[]> {
try {
const cmd = new Deno.Command('nmcli', {
args: ['-t', '-f', 'BSSID,SIGNAL', 'device', 'wifi', 'list'],
stdout: 'piped',
stderr: 'null',
})
const { stdout } = await cmd.output()
const text = new TextDecoder().decode(stdout)
return text.trim().split('\n')
.filter(Boolean)
.map(line => {
// nmcli -t escapes colons inside values as \:, split on unescaped :
const fields = line.split(/(?<!\\):/)
if (fields.length < 2) return null
const bssid = fields[0].replace(/\\([\da-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16)))
const signal = parseInt(fields[1], 10)
if (isNaN(signal)) return null
return { macAddress: bssid, signalStrength: signal }
})
.filter((a): a is NonNullable<typeof a> => a !== null)
} catch {
return []
}
}
/** Google Geolocation API โ uses WiFi AP data for precise positioning */
// Amap WiโFi ๅบ็ซๅฎไฝ๏ผๅฝๅ
๏ผโ ไฝฟ็จ apilocate.amap.com/position๏ผGET๏ผ
async function amapWiFiGeolocateAPI(wifiAPs: { macAddress: string; signalStrength: number }[]): Promise<{ lat: number; lng: number; accuracy: number } | null> {
const key = process.env.AMAP_API_KEY
if (!key) return null
try {
if (wifiAPs.length < 2) return null // Amap ่ฆๆฑ่ณๅฐ 2 ไธช AP
// ๆ้ macs ๅๆฐ๏ผmac1,signal1,ssid1|mac2,signal2,ssid2|...
// signal ไธบ่ด dBm๏ผnmcli ่ฟๅ 0โ100๏ผๅ่ดไฝไธบ่ฟไผผๅผ๏ผ
const macs = wifiAPs.slice(0, 30).map(ap =>
`${ap.macAddress},${-ap.signalStrength},`
).join('|')
const params = new URLSearchParams({
key,
accesstype: '1',
cdma: '0',
macs,
output: 'json',
})
const res = await fetch(`https://apilocate.amap.com/position?${params}`, {
method: 'GET',
signal: AbortSignal.timeout(10000),
})
if (!res.ok) return null
const data = await res.json() as any
// Amap ่ฟๅ { status: "1", info: "OK", result: { location: "lng,lat", radius: number, ... } }
if (data.status === '1' && data.result?.location) {
const [lng, lat] = data.result.location.split(',').map(Number)
if (!isNaN(lat) && !isNaN(lng)) {
return {
lat,
lng,
accuracy: data.result.radius || 0,
}
}
}
return null
} catch {
return null
}
}
// Google Geolocation API๏ผๆตทๅค๏ผ
async function googleGeolocateAPI(wifiAPs: { macAddress: string; signalStrength: number }[]): Promise<{ lat: number; lng: number; accuracy: number } | null> {
const key = process.env.GOOGLE_MAPS_API_KEY
if (!key) return null
try {
const body: any = {}
if (wifiAPs.length > 0) {
body.wifiAccessPoints = wifiAPs.slice(0, 20)
body.considerIp = false
} else {
body.considerIp = true
}
const res = await fetch('https://www.googleapis.com/geolocation/v1/geolocate?key=' + key, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10000),
})
if (!res.ok) return null
const data = await res.json() as any
if (data.location?.lat && data.location?.lng) {
return {
lat: data.location.lat,
lng: data.location.lng,
accuracy: data.accuracy || 0,
}
}
return null
} catch {
return null
}
}
/**
* Detect user location via IP (3 fallback services).
* Only used by the explicit `locate` action.
*/
async function ipGeolocate(): Promise<IpGeoInfo> {
const services = [
'https://ipinfo.io/json',
'https://ipapi.co/json/',
'http://ip-api.com/json/',
]
for (const url of services) {
try {
const res = await fetch(url, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(5000),
})
if (!res.ok) continue
const data = await res.json() as any
// ipinfo.io
if (data.city) {
const loc = data.loc?.split(',').map(Number) as [number, number] | undefined
return {
ip: data.ip || 'unknown',
city: data.city,
region: data.region || '',
country: data.country || '',
lat: loc?.[0],
lng: loc?.[1],
}
}
// ipapi.co
if (data.city) {
return {
ip: data.ip || 'unknown',
city: data.city,
region: data.region || '',
country: data.country_name || data.country || '',
lat: data.latitude,
lng: data.longitude,
}
}
// ip-api.com
if (data.city) {
return {
ip: data.query || 'unknown',
city: data.city,
region: data.regionName || data.region || '',
country: data.country || '',
lat: data.lat,
lng: data.lon,
}
}
} catch {
continue
}
}
throw new Error('Could not determine location via IP (all geolocation services failed)')
}
// โโ Input / Output schemas โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const inputSchema = lazySchema(() =>
z.strictObject({
action: z.enum(['geocode', 'search_places', 'get_directions', 'plan_trip', 'locate'])
.describe('The action to perform'),
location: z.any().optional().default('').describe('The location name, address, or origin for directions (optional for locate; defaults to empty string)'),
destination: z.string().optional()
.describe('Destination location (required for get_directions and plan_trip)'),
query: z.string().optional()
.describe('Search query for places (e.g., restaurants, attractions, hotels). Required for search_places'),
radius: z.number().min(1).max(50000).optional().default(5000)
.describe('Search radius in meters (default: 5000, max: 50000)'),
mode: z.enum(['driving', 'walking', 'transit', 'bicycling']).optional().default('driving')
.describe('Transport mode for directions (default: driving)'),
waypoints: z.array(z.string()).max(10).optional()
.describe('Intermediate stops for multi-city trip planning (max 10)'),
type: z.string().optional()
.describe('POI type filter for Amap (e.g., ้ค้ฅฎ, ้
ๅบ, ๆฏ็น, ่ดญ็ฉ). Only applies to China locations'),
region: z.enum(['china', 'international']).optional()
.describe('Force region. Auto-detected if not specified'),
language: z.string().optional().default('zh-CN')
.describe('Response language (default: zh-CN)'),
}),
)
type Input = z.infer<ReturnType<typeof inputSchema>>
type LocationResult = {
lat: number
lng: number
formattedAddress: string
displayName: string
}
type PlaceResult = {
name: string
address: string
lat: number
lng: number
rating?: number
types?: string[]
phone?: string
website?: string
openingHours?: string
photos?: string[]
/** Amap-specific fields */
distance?: string
businessArea?: string
cost?: string
recommendation?: string
tag?: string
}
type DirectionStep = {
instruction: string
distance: string
duration: string
mode?: string
polyline?: string
}
type DirectionLeg = {
steps: DirectionStep[]
distance: string
duration: string
startAddress: string
endAddress: string
}
type DirectionsResult = {
origin: string
destination: string
mode: string
legs: DirectionLeg[]
totalDistance: string
totalDuration: string
polyline?: string
transitInfo?: string
tolls?: string
trafficRestriction?: string
}
type Output = {
action: string
region: 'china' | 'international'
geocoding?: LocationResult
places?: PlaceResult[]
directions?: DirectionsResult
error?: string
rawData?: unknown
ipGeo?: IpGeoInfo
images?: Array<{ url: string; base64: string; mediaType: string }>
}
// โโ Amap API helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function getAmapKey(): string {
const key = process.env.AMAP_API_KEY
if (!key) throw new Error('AMAP_API_KEY environment variable is not set')
return key
}
async function amapGeocode(location: string, city?: string): Promise<LocationResult> {
const key = getAmapKey()
const params = new URLSearchParams({ key, address: location })
if (city) params.set('city', city)
const res = await fetch(`https://restapi.amap.com/v3/geocode/geo?${params}`, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000),
})
if (!res.ok) throw new Error(`Amap geocode HTTP ${res.status}`)
const data = await res.json() as any
if (data.status !== '1' || !data.geocodes?.length) {
throw new Error(`Amap geocode failed: ${data.info || 'no results'}`)
}
const [lng, lat] = data.geocodes[0].location.split(',').map(Number)
return {
lat,
lng,
formattedAddress: data.geocodes[0].formatted_address || location,
displayName: data.geocodes[0].formatted_address || location,
}
}
async function amapSearchPlaces(
location: string,
query?: string,
type?: string,
radius?: number,
/** Pre-resolved coordinates (skip geocoding) */
geo?: LocationResult,
): Promise<PlaceResult[]> {
const key = getAmapKey()
// Use pre-resolved coordinates if available, otherwise geocode
const resolved = geo ?? await amapGeocode(location)
const allPois: any[] = []
const maxPages = 20 // ้ซๅพทๆๅค่ฟๅ 10000 ๆก (offset 10000 ร page 1 ๅฐฑๅค ไบ๏ผๅ้ ็ถๅ็จ)
const pageSize = 1000
for (let page = 1; page <= maxPages; page++) {
const params = new URLSearchParams({
key,
location: `${resolved.lng},${resolved.lat}`,
radius: String(radius || 5000),
offset: String(pageSize),
page: String(page),
extensions: 'all',
})
if (query) params.set('keywords', query)
if (type) params.set('types', type)
const res = await fetch(`https://restapi.amap.com/v3/place/around?${params}`, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(15000),
})
if (!res.ok) throw new Error(`Amap around search HTTP ${res.status}`)
const data = await res.json() as any
if (data.status !== '1') {
throw new Error(`Amap search failed: ${data.info}`)
}
const pois = data.pois || []
allPois.push(...pois)
// ๅฆๆ้้ ๆฒๆปฟ pageSize๏ผๆๅทฒ้็ธฝๆธ๏ผๅๆญข็ฟป้
if (pois.length < pageSize || allPois.length >= Number(data.count || 0)) break
// ้ซๅพท้ๅถๆฏ็ง 3 ๆฌก่ซๆฑ๏ผ็จๅพฎ็ญไธไธ
await new Promise(r => setTimeout(r, 350))
}
return allPois.map((poi: any) => ({
name: poi.name,
address: poi.address || '',
lat: parseFloat(poi.location?.split(',')[1] || '0'),
lng: parseFloat(poi.location?.split(',')[0] || '0'),
distance: poi.distance,
businessArea: poi.business_area,
cost: poi.cost,
type: poi.type,
tag: (poi.type || '').split(';').filter(Boolean).join(', '),
photos: (poi.photos || []).map((p: any) => p.url).filter(Boolean),
openingHours: poi.opentime || poi.biz_ext?.opentime,
recommendation: poi.recommend || poi.biz_ext?.rating,
}))
}
async function amapDirections(
origin: string,
destination: string,
mode: string,
/** Pre-resolved origin coordinates (skip geocoding) */
origGeo?: LocationResult,
/** Pre-resolved destination coordinates (skip geocoding) */
destGeo?: LocationResult,
): Promise<DirectionsResult> {
const key = getAmapKey()
const originGeo = origGeo ?? await amapGeocode(origin)
const destinationGeo = destGeo ?? await amapGeocode(destination)
// Map our mode to Amap mode
const amapMode = mode === 'transit' ? 'transit' : 'driving'
const apiUrl = amapMode === 'transit'
? 'https://restapi.amap.com/v3/direction/transit/integrated'
: 'https://restapi.amap.com/v3/direction/driving'
const params = new URLSearchParams({
key,
origin: `${originGeo.lng},${originGeo.lat}`,
destination: `${destinationGeo.lng},${destinationGeo.lat}`,
extensions: 'all',
strategy: '0',
})
if (amapMode === 'transit') {
params.set('city', '')
params.set('cityd', '')
}
const res = await fetch(`${apiUrl}?${params}`, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(15000),
})
if (!res.ok) throw new Error(`Amap directions HTTP ${res.status}`)
const data = await res.json() as any
if (data.status !== '1' || !data.route) {
throw new Error(`Amap directions failed: ${data.info || 'no route'}`)
}
const route = data.route
const path = route.paths?.[0] || route.transits?.[0]
if (!path) throw new Error('No route found')
const legs: DirectionLeg[] = [{
steps: (path.steps || []).map((s: any) => ({
instruction: s.instruction || '',
distance: `${(parseFloat(s.distance) / 1000).toFixed(1)} km`,
duration: `${Math.round(parseFloat(s.duration) / 60)} min`,
polyline: s.polyline,
})),
distance: `${(parseFloat(path.distance) / 1000).toFixed(1)} km`,
duration: `${Math.round(parseFloat(path.duration) / 60)} min`,
startAddress: origin,
endAddress: destination,
}]
const result: DirectionsResult = {
origin,
destination,
mode,
legs,
totalDistance: legs[0].distance,
totalDuration: legs[0].duration,
}
if (amapMode === 'transit') {
result.transitInfo = `Transit: ${path.transit_mode || 'public transport'}`
result.tolls = path.tolls ? `ยฅ${path.tolls}` : undefined
}
return result
}
// โโ Google Maps API helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
function getGoogleKey(): string {
const key = process.env.GOOGLE_MAPS_API_KEY
if (!key) throw new Error('GOOGLE_MAPS_API_KEY environment variable is not set')
return key
}
async function googleGeocode(location: string, language?: string): Promise<LocationResult> {
const key = getGoogleKey()
const params = new URLSearchParams({ address: location, key })
if (language) params.set('language', language)
const res = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?${params}`, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(10000),
})
if (!res.ok) throw new Error(`Google geocode HTTP ${res.status}`)
const data = await res.json() as any
if (data.status !== 'OK' || !data.results?.length) {
throw new Error(`Google geocode failed: ${data.status} โ ${data.error_message || 'no results'}`)
}
const result = data.results[0]
return {
lat: result.geometry.location.lat,
lng: result.geometry.location.lng,
formattedAddress: result.formatted_address,
displayName: result.formatted_address,
}
}
async function googleSearchPlaces(
location: string,
query?: string,
radius?: number,
language?: string,
/** Pre-resolved coordinates (skip geocoding) */
geo?: LocationResult,
): Promise<PlaceResult[]> {
const key = getGoogleKey()
const resolved = geo ?? await googleGeocode(location, language)
const allPlaces: any[] = []
const baseUrl = query
? 'https://maps.googleapis.com/maps/api/place/textsearch/json'
: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
let nextPageToken: string | undefined
for (let page = 0; page < 3; page++) { // Google ๆๅค 60 ๆข๏ผ3 ้ ร 20๏ผ
const params = new URLSearchParams({ key, language: language || 'zh-CN' })
if (page === 0) {
if (query) {
params.set('query', `${query} in ${location}`)
} else {
params.set('location', `${resolved.lat},${resolved.lng}`)
params.set('radius', String(radius || 5000))
}
} else if (nextPageToken) {
// ็ฟป้ ้่ฆ็ญ 2 ็ง่ฎ token ็ๆ
await new Promise(r => setTimeout(r, 2000))
params.set('pagetoken', nextPageToken)
}
const res = await fetch(`${baseUrl}?${params}`, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(15000),
})
if (!res.ok) throw new Error(`Google places search HTTP ${res.status}`)
const data = await res.json() as any
if (data.status !== 'OK') {
if (allPlaces.length > 0) break // ็ฟป้ ๅคฑๆไฝๅทฒๆ็ตๆ๏ผ็นผ็บ
throw new Error(`Google places search failed: ${data.status} โ ${data.error_message || ''}`)
}
allPlaces.push(...(data.results || []))
nextPageToken = data.next_page_token
if (!nextPageToken) break
}
return parseGooglePlacesResults(allPlaces, resolved)
}
function parseGooglePlacesResults(results: any[], geo: LocationResult): PlaceResult[] {
return (results || []).map((place: any) => ({
name: place.name,
address: place.formatted_address || place.vicinity || '',
lat: place.geometry?.location?.lat || geo.lat,
lng: place.geometry?.location?.lng || geo.lng,
rating: place.rating,
types: place.types,
phone: place.formatted_phone_number,
website: place.website,
openingHours: place.opening_hours?.open_now ? 'Open now' : undefined,
photos: (place.photos || []).map((p: any) =>
`https://maps.googleapis.com/maps/api/place/photo?maxwidth=800&photoreference=${p.photo_reference}&key=${getGoogleKey()}`
),
cost: place.price_level ? '๐ฐ'.repeat(place.price_level) : undefined,
}))
}
async function googleDirections(
origin: string,
destination: string,
mode: string,
language?: string,
): Promise<DirectionsResult> {
const key = getGoogleKey()
const params = new URLSearchParams({
origin,
destination,
mode,
key,
language: language || 'zh-CN',
alternatives: 'true',
})
const res = await fetch(`https://maps.googleapis.com/maps/api/directions/json?${params}`, {
headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(15000),
})
if (!res.ok) throw new Error(`Google directions HTTP ${res.status}`)
const data = await res.json() as any
if (data.status !== 'OK' || !data.routes?.length) {
throw new Error(`Google directions failed: ${data.status} โ ${data.error_message || 'no route'}`)
}
const route = data.routes[0]
const legs: DirectionLeg[] = (route.legs || []).map((leg: any) => ({
steps: (leg.steps || []).map((s: any) => ({
instruction: s.html_instructions?.replace(/<[^>]+>/g, '') || '',
distance: s.distance?.text || '',
duration: s.duration?.text || '',
mode: s.travel_mode,
})),
distance: leg.distance?.text || '',
duration: leg.duration?.text || '',
startAddress: leg.start_address || origin,
endAddress: leg.end_address || destination,
}))
return {
origin,
destination,
mode,
legs,
totalDistance: legs[0]?.distance || '',
totalDuration: legs[0]?.duration || '',
polyline: route.overview_polyline?.points,
}
}
// โโ Main call logic โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
async function handleGeocode(
location: string,
region: 'china' | 'international',
language?: string,
/** Pre-resolved coordinates (skip geocoding) */
coords?: LocationResult,
): Promise<LocationResult> {
if (coords) return coords
if (region === 'china') {
return await amapGeocode(location)
}
return await googleGeocode(location, language)
}
async function handleSearchPlaces(
location: string,
query: string | undefined,
type: string | undefined,
radius: number | undefined,
region: 'china' | 'international',
language?: string,
/** Pre-resolved coordinates (skip geocoding) */
coords?: LocationResult,
): Promise<PlaceResult[]> {
if (region === 'china') {
return await amapSearchPlaces(location, query, type, radius, coords)
}
return await googleSearchPlaces(location, query, radius, language, coords)
}
async function handleDirections(
origin: string,
destination: string,
mode: string,
region: 'china' | 'international',
language?: string,
/** Pre-resolved origin coordinates */
origCoords?: LocationResult,
/** Pre-resolved destination coordinates */
destCoords?: LocationResult,
): Promise<DirectionsResult> {
if (region === 'china') {
return await amapDirections(origin, destination, mode, origCoords, destCoords)
}
return await googleDirections(origin, destination, mode, language)
}
async function handlePlanTrip(
origin: string,
destination: string,
waypoints: string[] | undefined,
mode: string,
region: 'china' | 'international',
language?: string,
/** Pre-resolved origin coordinates */
origCoords?: LocationResult,
/** Pre-resolved destination coordinates */
destCoords?: LocationResult,
) {
// Multi-stop: combine waypoints into a single route
if (waypoints && waypoints.length > 0) {
// We run directions sequentially for each leg to get complete info
const legs: DirectionLeg[] = []
let currentOrigin = origin
let currentCoords = origCoords
for (const wp of waypoints) {
const leg = await handleDirections(currentOrigin, wp, mode, region, language, currentCoords)
legs.push(...leg.legs)
currentOrigin = wp
currentCoords = undefined // waypoints are strings, not coordinates
}
// Final leg
const finalLeg = await handleDirections(currentOrigin, destination, mode, region, language, undefined, destCoords)
legs.push(...finalLeg.legs)
const totalDist = legs.reduce((sum, l) => sum + parseFloat(l.distance) || 0, 0)
const totalDur = legs.reduce((sum, l) => sum + parseFloat(l.duration) || 0, 0)
return {
origin,
destination,
mode,
legs,
totalDistance: `${totalDist.toFixed(1)} km`,
totalDuration: `${Math.round(totalDur)} min`,
waypoints: [origin, ...waypoints, destination],
}
}
// Simple point-to-point
return await handleDirections(origin, destination, mode, region, language)
}
// โโ Tool export โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
type LocationToolProgress = {
type: 'query_update' | 'results_received'
action?: string
location?: string
}
export const LocationTool = buildTool({
name: LOCATION_TOOL_NAME,
searchHint: 'geographic search, POI, maps, directions, travel planning',
shouldDefer: true,
getToolUseSummary,
getActivityDescription(input) {
const loc = input?.location || ''
const action = input?.action || 'query'
return `${action} for "${loc}"`
},
isEnabled() {
return true
},
get inputSchema() {
return inputSchema()
},
isConcurrencySafe() {
return true
},
isReadOnly() {
return true
},
toAutoClassifierInput(input) {
return input?.action
? `${input.action}: ${input?.location || '(IP auto-detect)'}`
: ''
},
async checkPermissions() {
return { behavior: 'allow' }
},
async prompt() {
return PROMPT
},
renderToolUseMessage,
renderToolUseProgressMessage,
renderToolResultMessage,
extractSearchText(output) {
if (!output) return ''
const parts: string[] = []
if (output.geocoding) parts.push(`geocode: ${output.geocoding.formattedAddress}`)
if (output.places?.length) parts.push(`places: ${output.places.length} results`)
if (output.directions) parts.push(`route: ${output.directions.origin} โ ${output.directions.destination}`)
return parts.join('; ')
},
async validateInput(input) {
if (input?.action !== 'locate' && (!input?.location || input?.location.length === 0)) {
return { result: false, message: 'Missing location parameter', errorCode: 1 }
}
if (input.action === 'get_directions' || input.action === 'plan_trip') {
if (!input.destination) {
return { result: false, message: 'Missing destination parameter for directions/trip', errorCode: 1 }
}
}
if (input.action === 'search_places' && !input.query && !input.type) {
return { result: false, message: 'Missing query or type parameter for place search', errorCode: 1 }
}
return { result: true }
},
async call(input, _context, _canUseTool, _parentMessage, onProgress) {
const { action, location, destination, query, radius, mode, waypoints, type, region: forcedRegion, language } = input
// Detect coordinate input (e.g. "34.2583,108.9286")
const originCoords = typeof location === 'string' ? parseCoords(location) : undefined
const destCoords = destination ? parseCoords(destination) : undefined
// Region: coordinates override text-based detection
let region = forcedRegion
if (!region && originCoords) {
region = isChinaCoords(originCoords.lat, originCoords.lng) ? 'china' : 'international'
}
if (!region && location) {
region = isChinaMainland(location) ? 'china' : 'international'
}
if (!region) {
region = 'international'
}
// Build pre-resolved origin LocationResult from coordinates
const originLocationResult = originCoords ? coordsToLocation(originCoords.lat, originCoords.lng) : undefined
const destLocationResult = destCoords ? coordsToLocation(destCoords.lat, destCoords.lng) : undefined
if (onProgress) {
onProgress({
toolUseID: 'location-start',
data: { type: 'query_update', action, location: location || '(locate)' },
})
}
try {
let ipGeo: IpGeoInfo | undefined
let geocoding: LocationResult | undefined
let places: PlaceResult[] | undefined
let directions: DirectionsResult | undefined
let images: Output['images']
switch (action) {
case 'geocode':
geocoding = await handleGeocode(location, region, language, originLocationResult)
break
case 'search_places':
places = await handleSearchPlaces(location, query, type, radius ?? 5000, region, language, originLocationResult)
break
case 'get_directions':
if (!destination) throw new Error('Destination is required for directions')
directions = await handleDirections(location, destination, mode ?? 'driving', region, language, originLocationResult, destLocationResult)
break
case 'plan_trip':
if (!destination) throw new Error('Destination is required for trip planning')
const planResult = await handlePlanTrip(location, destination, waypoints, mode ?? 'driving', region, language, originLocationResult, destLocationResult)
directions = planResult as DirectionsResult
break
case 'locate': {
// 1. ้ฆๅ
ๅฐ่ฏๅฝๅ
Amap WiโFi ๅฎไฝ๏ผ่ฅๅจไธญๅฝๅคง้๏ผ
const wifiAPs = await scanWiFi()
const amapLoc = await amapWiFiGeolocateAPI(wifiAPs)
if (amapLoc) {
region = isChinaCoords(amapLoc.lat, amapLoc.lng) ? 'china' : 'international'
geocoding = coordsToLocation(amapLoc.lat, amapLoc.lng)
ipGeo = {
ip: 'amap-wifi',
city: `${amapLoc.lat.toFixed(4)},${amapLoc.lng.toFixed(4)}`,
region: `accuracy: ${amapLoc.accuracy}m`,
country: region === 'china' ? 'CN' : 'unknown',
lat: amapLoc.lat,
lng: amapLoc.lng,
}
break
}
// 2. ่ฅ Amap ๆช่ฟๅๆไธๅจไธญๅฝๅคง้๏ผๅฐ่ฏๅฝๅค Google Geolocation API
const googleLoc = await googleGeolocateAPI(wifiAPs)
if (googleLoc) {
region = 'international'
geocoding = coordsToLocation(googleLoc.lat, googleLoc.lng)
ipGeo = {
ip: 'google-geolocation',
city: `${googleLoc.lat.toFixed(4)},${googleLoc.lng.toFixed(4)}`,
region: `accuracy: ${googleLoc.accuracy}m`,
country: 'unknown',
lat: googleLoc.lat,
lng: googleLoc.lng,
}
break
}
// 3. ๆๅๅ้ๅฐ IP ๅฎไฝ๏ผๅๅธ็บง๏ผ
ipGeo = await ipGeolocate()
const detectRegion = ipGeo.country === 'CN' ? 'china' : 'international'
const detectCoords = ipGeo.lat && ipGeo.lng
? coordsToLocation(ipGeo.lat, ipGeo.lng)
: undefined
if (detectCoords) {
geocoding = detectCoords
} else {
geocoding = await handleGeocode(ipGeo.city, detectRegion, language)
}
region = detectRegion
break
}
}
if (onProgress) {
onProgress({
toolUseID: 'location-results',
data: {
type: 'results_received',
action,
location: action === 'locate' ? ipGeo?.city : location,
...(places && { count: places.length }),
} as any,
})
}
if (places && places.length > 0) {
const photoUrls = places
.flatMap((p) => p.photos ?? [])
.slice(0, 6)
if (photoUrls.length > 0) {
images = await fetchImagesAsInline(photoUrls, 6)
}
}
return {
data: {
action,
region,
geocoding,
places,
directions,
ipGeo,
images,
} satisfies Output,
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
logError('LocationTool error', error)
return {
data: {
action,
region,
error: errorMessage,
ipGeo,
} satisfies Output,
}
}
},
mapToolResultToToolResultBlockParam(output: Output, toolUseID: string) {
const lines: string[] = []
lines.push(`๐ Location Result [${output.action}]`)
lines.push(`Region: ${output.region === 'china' ? 'ไธญๅฝๅคง้' : 'ๆตทๅค'}`)
if (output.ipGeo) {
const g = output.ipGeo
lines.push(`IP: ${g.ip} โ ${g.city}, ${g.region} (${g.country})`)
if (g.lat && g.lng) lines.push(`Coords: ${g.lat}, ${g.lng}`)
}
lines.push('')
if (output.error) {
lines.push(`Error: ${output.error}`)
}
if (output.geocoding) {
const g = output.geocoding
lines.push(`โโ ๅฐ็็ผ็ ็ปๆ`)
lines.push(`โ ๅฐๅ: ${g.formattedAddress}`)
lines.push(`โ ๅๆ : ${g.lat}, ${g.lng}`)
lines.push(`โ ๅฐๅพ: https://${output.region === 'china' ? 'uri.amap.com/marker?position=' : 'www.google.com/maps?q='}${g.lat},${g.lng}`)
lines.push(`โโโโโ\n`)
}
if (output.places && output.places.length > 0) {
lines.push(`โโ ๆ็ดข็ปๆ (${output.places.length} ๆก)`)
output.places.forEach((p, i) => {
lines.push(`โ`)
lines.push(`โ [${i + 1}] ${p.name}`)
if (p.address) lines.push(`โ ๅฐๅ: ${p.address}`)
if (p.distance) lines.push(`โ ่ท็ฆป: ${p.distance}็ฑณ`)
if (p.tag) lines.push(`โ ็ฑปๅซ: ${p.tag}`)
if (p.rating) lines.push(`โ ่ฏๅ: ${'โญ'.repeat(Math.round(p.rating))} (${p.rating})`)
if (p.cost) lines.push(`โ ๆถ่ดน: ${p.cost}`)
if (p.openingHours) lines.push(`โ ่ฅไธ: ${p.openingHours}`)
if (p.phone) lines.push(`โ ็ต่ฏ: ${p.phone}`)
if (p.photos?.length) {
lines.push(`โ ็
ง็: ${p.photos.map((ph, idx) => `[ๅพ${idx + 1}](${ph})`).join(' ')}`)
}
})
lines.push(`โโโโโ\n`)
}
if (output.directions) {
const d = output.directions
lines.push(`โโ ่ทฏ็บฟ่งๅ`)
lines.push(`โ ่ตท็น: ${d.origin}`)
lines.push(`โ ็ป็น: ${d.destination}`)
lines.push(`โ ไบค้ๆนๅผ: ${d.mode}`)
lines.push(`โ ๆป่ท็ฆป: ${d.totalDistance}`)
lines.push(`โ ้ข่ฎก่ๆถ: ${d.totalDuration}`)
if (d.transitInfo) lines.push(`โ ๅ
ฌๅ
ฑไบค้: ${d.transitInfo}`)
if (d.tolls) lines.push(`โ ้่ก่ดน: ${d.tolls}`)
if (d.legs.length > 0) {
lines.push(`โ`)
d.legs.forEach((leg, li) => {
if (d.legs.length > 1) lines.push(`โ ่ทฏๆฎต ${li + 1}: ${leg.startAddress} โ ${leg.endAddress}`)
lines.push(`โ ่ท็ฆป: ${leg.distance} | ๆถ้ด: ${leg.duration}`)
leg.steps.slice(0, 10).forEach(s => {
const instr = s.instruction.length > 80 ? s.instruction.slice(0, 80) + 'โฆ' : s.instruction
lines.push(`โ โ ${instr} (${s.distance}, ${s.duration})`)
})
if (leg.steps.length > 10) {
lines.push(`โ โฆ ่ฟๆ ${leg.steps.length - 10} ไธชๆญฅ้ชค`)
}
})
}
lines.push(`โโโโโ`)
}
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: [
{ type: 'text', text: lines.join('\n') },
...(output.images?.map((img) => ({
type: 'image' as const,
source: {
type: 'base64' as const,
data: img.base64,
media_type: img.mediaType as 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp',
},
})) ?? []),
],
}
},
}) satisfies ToolDef<ReturnType<typeof inputSchema>, Output, LocationToolProgress>
|