-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai-tools.ts
More file actions
166 lines (156 loc) · 5.04 KB
/
Copy pathai-tools.ts
File metadata and controls
166 lines (156 loc) · 5.04 KB
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
import type { DataState, LocationValue } from "./live-state";
import type { PhoneLocale } from "./phone-types";
const MAX_LOCATION_AGE_MS = 120_000;
const MAX_SEARCH_QUERY = 500;
export type AiCitationSource = {
readonly title: string;
readonly url: string;
};
export type AiWebSearchUsage = {
readonly model: string;
readonly inputTokens: number;
readonly cachedInputTokens: number;
readonly outputTokens: number;
readonly webSearchCalls: number;
};
export type AiWebSearchResult = {
readonly answer: string;
readonly sources: readonly AiCitationSource[];
readonly usage: AiWebSearchUsage;
};
export type BuiltinAiToolResult =
| {
readonly ok: true;
readonly data: Record<string, unknown>;
readonly sources?: readonly AiCitationSource[];
readonly usage?: AiWebSearchUsage;
}
| {
readonly ok: false;
readonly error: { readonly code: string; readonly message: string };
};
export const BUILTIN_AI_TOOLS = [
{
type: "function" as const,
name: "get_current_time",
description: "Get the exact current local time, date, timezone, and UTC offset.",
parameters: { type: "object", properties: {}, additionalProperties: false },
},
{
type: "function" as const,
name: "get_current_location",
description: "Get the latest exact live GPS location from the user's glasses session. Call only when location is needed.",
parameters: { type: "object", properties: {}, additionalProperties: false },
},
{
type: "function" as const,
name: "search_web",
description: "Search the live web for current or factual information and return grounded sources.",
parameters: {
type: "object",
properties: {
query: { type: "string", minLength: 1, maxLength: MAX_SEARCH_QUERY },
},
required: ["query"],
additionalProperties: false,
},
},
] as const;
function failed(code: string, message: string): BuiltinAiToolResult {
return { ok: false, error: { code, message } };
}
function utcOffset(date: Date): string {
const minutes = -date.getTimezoneOffset();
const sign = minutes >= 0 ? "+" : "-";
const absolute = Math.abs(minutes);
return `${sign}${String(Math.floor(absolute / 60)).padStart(2, "0")}`
+ `:${String(absolute % 60).padStart(2, "0")}`;
}
function parseObject(value: string): Record<string, unknown> | undefined {
if (value.length > 2_048) return undefined;
try {
const parsed: unknown = JSON.parse(value || "{}");
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: undefined;
} catch {
return undefined;
}
}
export async function executeBuiltinAiTool(
name: string,
rawArguments: string,
context: {
readonly locale: PhoneLocale;
readonly now: () => Date;
readonly getLocation: () => DataState<LocationValue>;
readonly searchWeb: (
query: string,
locale: PhoneLocale,
) => Promise<AiWebSearchResult>;
},
): Promise<BuiltinAiToolResult> {
const args = parseObject(rawArguments);
if (!args) return failed("INVALID_ARGUMENTS", "Tool arguments are invalid");
if (name === "get_current_time") {
const date = context.now();
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
return {
ok: true,
data: {
iso: date.toISOString(),
timezone,
utcOffset: utcOffset(date),
locale: context.locale,
display: new Intl.DateTimeFormat(context.locale, {
dateStyle: "full",
timeStyle: "long",
timeZone: timezone,
}).format(date),
},
};
}
if (name === "get_current_location") {
const location = context.getLocation();
const age = context.now().getTime() - (location.fetchedAt ?? 0);
if (
location.status !== "fresh"
|| location.value?.source !== "live"
|| age < 0
|| age > MAX_LOCATION_AGE_MS
) {
return failed("LOCATION_UNAVAILABLE", "Live GPS is unavailable");
}
return {
ok: true,
data: {
latitude: location.value.coordinate.latitude,
longitude: location.value.coordinate.longitude,
accuracyMeters: location.value.accuracy,
speedMetersPerSecond: location.value.speed,
headingDegrees: location.value.heading,
source: "live",
timestamp: new Date(location.fetchedAt ?? context.now().getTime())
.toISOString(),
},
};
}
if (name === "search_web") {
const query = typeof args.query === "string" ? args.query.trim() : "";
if (!query || query.length > MAX_SEARCH_QUERY) {
return failed("INVALID_ARGUMENTS", "A bounded search query is required");
}
try {
const result = await context.searchWeb(query, context.locale);
return {
ok: true,
data: { answer: result.answer, sources: result.sources },
sources: result.sources,
usage: result.usage,
};
} catch {
return failed("WEB_SEARCH_FAILED", "Web search is unavailable");
}
}
return failed("UNKNOWN_TOOL", "The requested tool is unavailable");
}