@tinyweb_dev/agent-framework-tool 0.2.0 → 0.4.0
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.
- package/dist/builtins.cjs +820 -0
- package/dist/builtins.cjs.map +1 -0
- package/dist/builtins.d.ts +58 -0
- package/dist/builtins.d.ts.map +1 -0
- package/dist/builtins.js +818 -0
- package/dist/builtins.js.map +1 -0
- package/dist/display_response.cjs +51 -0
- package/dist/display_response.cjs.map +1 -0
- package/dist/display_response.d.ts +36 -0
- package/dist/display_response.d.ts.map +1 -0
- package/dist/display_response.js +49 -0
- package/dist/display_response.js.map +1 -0
- package/dist/file_read.cjs +28 -0
- package/dist/file_read.cjs.map +1 -0
- package/dist/file_read.d.ts +14 -0
- package/dist/file_read.d.ts.map +1 -0
- package/dist/file_read.js +26 -0
- package/dist/file_read.js.map +1 -0
- package/dist/file_write.cjs +30 -0
- package/dist/file_write.cjs.map +1 -0
- package/dist/file_write.d.ts +16 -0
- package/dist/file_write.d.ts.map +1 -0
- package/dist/file_write.js +28 -0
- package/dist/file_write.js.map +1 -0
- package/dist/image_describe.cjs +69 -0
- package/dist/image_describe.cjs.map +1 -0
- package/dist/image_describe.d.ts +15 -0
- package/dist/image_describe.d.ts.map +1 -0
- package/dist/image_describe.js +67 -0
- package/dist/image_describe.js.map +1 -0
- package/dist/image_edit.cjs +87 -0
- package/dist/image_edit.cjs.map +1 -0
- package/dist/image_edit.d.ts +20 -0
- package/dist/image_edit.d.ts.map +1 -0
- package/dist/image_edit.js +85 -0
- package/dist/image_edit.js.map +1 -0
- package/dist/image_generate.cjs +112 -0
- package/dist/image_generate.cjs.map +1 -0
- package/dist/image_generate.d.ts +21 -0
- package/dist/image_generate.d.ts.map +1 -0
- package/dist/image_generate.js +110 -0
- package/dist/image_generate.js.map +1 -0
- package/dist/index.cjs +1209 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1176 -0
- package/dist/index.js.map +1 -0
- package/dist/info/crypto.cjs +78 -0
- package/dist/info/crypto.cjs.map +1 -0
- package/dist/info/crypto.d.ts +34 -0
- package/dist/info/crypto.d.ts.map +1 -0
- package/dist/info/crypto.js +76 -0
- package/dist/info/crypto.js.map +1 -0
- package/dist/info/time.cjs +60 -0
- package/dist/info/time.cjs.map +1 -0
- package/dist/info/time.d.ts +31 -0
- package/dist/info/time.d.ts.map +1 -0
- package/dist/info/time.js +58 -0
- package/dist/info/time.js.map +1 -0
- package/dist/info/weather.cjs +105 -0
- package/dist/info/weather.cjs.map +1 -0
- package/dist/info/weather.d.ts +41 -0
- package/dist/info/weather.d.ts.map +1 -0
- package/dist/info/weather.js +103 -0
- package/dist/info/weather.js.map +1 -0
- package/dist/search/perplexity.cjs +98 -0
- package/dist/search/perplexity.cjs.map +1 -0
- package/dist/search/perplexity.d.ts +49 -0
- package/dist/search/perplexity.d.ts.map +1 -0
- package/dist/search/perplexity.js +96 -0
- package/dist/search/perplexity.js.map +1 -0
- package/dist/shared/html.cjs +57 -0
- package/dist/shared/html.cjs.map +1 -0
- package/dist/shared/html.d.ts +37 -0
- package/dist/shared/html.d.ts.map +1 -0
- package/dist/shared/html.js +52 -0
- package/dist/shared/html.js.map +1 -0
- package/dist/shared/http.cjs +48 -0
- package/dist/shared/http.cjs.map +1 -0
- package/dist/shared/http.d.ts +11 -0
- package/dist/shared/http.d.ts.map +1 -0
- package/dist/shared/http.js +42 -0
- package/dist/shared/http.js.map +1 -0
- package/dist/shared/s3.cjs +98 -0
- package/dist/shared/s3.cjs.map +1 -0
- package/dist/shared/s3.d.ts +35 -0
- package/dist/shared/s3.d.ts.map +1 -0
- package/dist/shared/s3.js +96 -0
- package/dist/shared/s3.js.map +1 -0
- package/dist/shared/storage.cjs +74 -0
- package/dist/shared/storage.cjs.map +1 -0
- package/dist/shared/storage.d.ts +17 -0
- package/dist/shared/storage.d.ts.map +1 -0
- package/dist/shared/storage.js +70 -0
- package/dist/shared/storage.js.map +1 -0
- package/dist/todo/update_todo_list.d.ts +44 -0
- package/dist/todo/update_todo_list.d.ts.map +1 -0
- package/dist/vn/gold.cjs +198 -0
- package/dist/vn/gold.cjs.map +1 -0
- package/dist/vn/gold.d.ts +36 -0
- package/dist/vn/gold.d.ts.map +1 -0
- package/dist/vn/gold.js +196 -0
- package/dist/vn/gold.js.map +1 -0
- package/dist/vn/lottery.cjs +126 -0
- package/dist/vn/lottery.cjs.map +1 -0
- package/dist/vn/lottery.d.ts +31 -0
- package/dist/vn/lottery.d.ts.map +1 -0
- package/dist/vn/lottery.js +124 -0
- package/dist/vn/lottery.js.map +1 -0
- package/dist/web_fetch.cjs +65 -0
- package/dist/web_fetch.cjs.map +1 -0
- package/dist/web_fetch.d.ts +16 -0
- package/dist/web_fetch.d.ts.map +1 -0
- package/dist/web_fetch.js +63 -0
- package/dist/web_fetch.js.map +1 -0
- package/dist/web_search.cjs +98 -0
- package/dist/web_search.cjs.map +1 -0
- package/dist/web_search.d.ts +19 -0
- package/dist/web_search.d.ts.map +1 -0
- package/dist/web_search.js +96 -0
- package/dist/web_search.js.map +1 -0
- package/package.json +109 -30
- package/src/builtins.ts +0 -78
- package/src/display_response.ts +0 -79
- package/src/file_read.ts +0 -31
- package/src/file_write.ts +0 -33
- package/src/image_describe.ts +0 -58
- package/src/image_edit.ts +0 -74
- package/src/image_generate.ts +0 -102
- package/src/index.ts +0 -47
- package/src/info/crypto.ts +0 -79
- package/src/info/time.ts +0 -83
- package/src/info/weather.ts +0 -134
- package/src/search/perplexity.ts +0 -129
- package/src/shared/html.ts +0 -87
- package/src/shared/http.ts +0 -40
- package/src/shared/s3.ts +0 -157
- package/src/shared/storage.ts +0 -83
- package/src/vn/gold.ts +0 -192
- package/src/vn/lottery.ts +0 -129
- package/src/web_fetch.ts +0 -80
- package/src/web_search.ts +0 -92
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var agent = require('@tinyweb_dev/agent-framework-agent');
|
|
4
|
+
var effect = require('effect');
|
|
5
|
+
var cheerio = require('cheerio');
|
|
6
|
+
var crypto = require('crypto');
|
|
7
|
+
|
|
8
|
+
// src/info/time.ts
|
|
9
|
+
var Parameters = effect.Schema.Struct({
|
|
10
|
+
timezone: effect.Schema.optional(effect.Schema.String),
|
|
11
|
+
locale: effect.Schema.optional(effect.Schema.String)
|
|
12
|
+
});
|
|
13
|
+
var Success = effect.Schema.Struct({
|
|
14
|
+
timezone: effect.Schema.String,
|
|
15
|
+
locale: effect.Schema.String,
|
|
16
|
+
iso: effect.Schema.String,
|
|
17
|
+
formatted: effect.Schema.String,
|
|
18
|
+
weekday: effect.Schema.String,
|
|
19
|
+
unix_ms: effect.Schema.Number
|
|
20
|
+
});
|
|
21
|
+
var VN_WEEKDAYS = ["Ch\u1EE7 nh\u1EADt", "Th\u1EE9 hai", "Th\u1EE9 ba", "Th\u1EE9 t\u01B0", "Th\u1EE9 n\u0103m", "Th\u1EE9 s\xE1u", "Th\u1EE9 b\u1EA3y"];
|
|
22
|
+
var vietnameseWeekday = (date, timezone) => {
|
|
23
|
+
const fmt = new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short" });
|
|
24
|
+
const short = fmt.format(date);
|
|
25
|
+
const map = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
26
|
+
const idx = map[short] ?? 0;
|
|
27
|
+
return VN_WEEKDAYS[idx];
|
|
28
|
+
};
|
|
29
|
+
var timeNow = (config = {}) => {
|
|
30
|
+
const defaultTz = config.defaultTimezone ?? "Asia/Ho_Chi_Minh";
|
|
31
|
+
const defaultLocale = config.defaultLocale ?? "vi-VN";
|
|
32
|
+
return agent.defineTool({
|
|
33
|
+
name: config.name ?? "time_now",
|
|
34
|
+
description: config.description ?? `L\u1EA5y th\u1EDDi gian hi\u1EC7n t\u1EA1i theo timezone IANA (m\u1EB7c \u0111\u1ECBnh ${defaultTz}). Tr\u1EA3 v\u1EC1 ISO, \u0111\u1ECBnh d\u1EA1ng th\xE2n thi\u1EC7n, v\xE0 unix timestamp.`,
|
|
35
|
+
parameters: Parameters,
|
|
36
|
+
success: Success,
|
|
37
|
+
execute: async (input) => {
|
|
38
|
+
const tz = input.timezone ?? defaultTz;
|
|
39
|
+
const locale = input.locale ?? defaultLocale;
|
|
40
|
+
const now = /* @__PURE__ */ new Date();
|
|
41
|
+
const dtf = new Intl.DateTimeFormat(locale, {
|
|
42
|
+
timeZone: tz,
|
|
43
|
+
dateStyle: "full",
|
|
44
|
+
timeStyle: "long"
|
|
45
|
+
});
|
|
46
|
+
const formatted = dtf.format(now);
|
|
47
|
+
const weekday = locale.startsWith("vi") ? vietnameseWeekday(now, tz) : new Intl.DateTimeFormat(locale, { timeZone: tz, weekday: "long" }).format(now);
|
|
48
|
+
return {
|
|
49
|
+
timezone: tz,
|
|
50
|
+
locale,
|
|
51
|
+
iso: now.toISOString(),
|
|
52
|
+
formatted,
|
|
53
|
+
weekday,
|
|
54
|
+
unix_ms: now.getTime()
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/shared/http.ts
|
|
61
|
+
var HttpToolError = class extends Error {
|
|
62
|
+
constructor(message, status, body) {
|
|
63
|
+
super(message);
|
|
64
|
+
this.status = status;
|
|
65
|
+
this.body = body;
|
|
66
|
+
this.name = "HttpToolError";
|
|
67
|
+
}
|
|
68
|
+
_tag = "HttpToolError";
|
|
69
|
+
};
|
|
70
|
+
var ensureOk = async (res, label) => {
|
|
71
|
+
if (res.ok) return res;
|
|
72
|
+
const body = await res.text().catch(() => "");
|
|
73
|
+
throw new HttpToolError(`${label} ${res.status}: ${body.slice(0, 500)}`, res.status, body);
|
|
74
|
+
};
|
|
75
|
+
var fetchJson = async (url, init) => {
|
|
76
|
+
const res = await fetch(url, init);
|
|
77
|
+
await ensureOk(res, `GET ${url}`);
|
|
78
|
+
return await res.json();
|
|
79
|
+
};
|
|
80
|
+
var postJson = async (url, body, init) => {
|
|
81
|
+
const headers = new Headers(init?.headers);
|
|
82
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
83
|
+
const res = await fetch(url, { method: "POST", body: JSON.stringify(body), ...init, headers });
|
|
84
|
+
await ensureOk(res, `POST ${url}`);
|
|
85
|
+
return await res.json();
|
|
86
|
+
};
|
|
87
|
+
var fetchText = async (url, init) => {
|
|
88
|
+
const res = await fetch(url, init);
|
|
89
|
+
await ensureOk(res, `GET ${url}`);
|
|
90
|
+
return res.text();
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// src/info/weather.ts
|
|
94
|
+
var Parameters2 = effect.Schema.Struct({
|
|
95
|
+
location: effect.Schema.optional(effect.Schema.String),
|
|
96
|
+
lang: effect.Schema.optional(effect.Schema.String)
|
|
97
|
+
});
|
|
98
|
+
var Success2 = effect.Schema.Struct({
|
|
99
|
+
location: effect.Schema.String,
|
|
100
|
+
region: effect.Schema.optional(effect.Schema.String),
|
|
101
|
+
country: effect.Schema.optional(effect.Schema.String),
|
|
102
|
+
observed_at: effect.Schema.String,
|
|
103
|
+
temperature_c: effect.Schema.Number,
|
|
104
|
+
feels_like_c: effect.Schema.Number,
|
|
105
|
+
humidity_percent: effect.Schema.Number,
|
|
106
|
+
wind_kmh: effect.Schema.Number,
|
|
107
|
+
wind_direction: effect.Schema.String,
|
|
108
|
+
condition: effect.Schema.String,
|
|
109
|
+
uv_index: effect.Schema.optional(effect.Schema.Number),
|
|
110
|
+
visibility_km: effect.Schema.optional(effect.Schema.Number),
|
|
111
|
+
pressure_mb: effect.Schema.optional(effect.Schema.Number),
|
|
112
|
+
source: effect.Schema.Literal("wttr.in")
|
|
113
|
+
});
|
|
114
|
+
var firstValue = (xs) => xs && xs.length > 0 ? xs[0].value : void 0;
|
|
115
|
+
var num = (s, fallback = 0) => {
|
|
116
|
+
if (!s) return fallback;
|
|
117
|
+
const n = Number(s);
|
|
118
|
+
return Number.isFinite(n) ? n : fallback;
|
|
119
|
+
};
|
|
120
|
+
var weather = (config = {}) => {
|
|
121
|
+
const defaultLocation = config.defaultLocation ?? "Hanoi";
|
|
122
|
+
const defaultLang = config.defaultLang ?? "vi";
|
|
123
|
+
const ua = config.userAgent ?? "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
|
|
124
|
+
const timeout = config.timeoutMs ?? 15e3;
|
|
125
|
+
return agent.defineTool({
|
|
126
|
+
name: config.name ?? "weather",
|
|
127
|
+
description: config.description ?? `L\u1EA5y th\u1EDDi ti\u1EBFt hi\u1EC7n t\u1EA1i c\u1EE7a m\u1ED9t \u0111\u1ECBa \u0111i\u1EC3m (city, t\u1EC9nh, ho\u1EB7c t\xEAn s\xE2n bay). M\u1EB7c \u0111\u1ECBnh ${defaultLocation}. Ngu\u1ED3n: wttr.in.`,
|
|
128
|
+
parameters: Parameters2,
|
|
129
|
+
success: Success2,
|
|
130
|
+
execute: async (input) => {
|
|
131
|
+
const loc = (input.location ?? defaultLocation).trim();
|
|
132
|
+
const lang = input.lang ?? defaultLang;
|
|
133
|
+
const url = `https://wttr.in/${encodeURIComponent(loc)}?format=j1&lang=${encodeURIComponent(lang)}`;
|
|
134
|
+
const controller = new AbortController();
|
|
135
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
136
|
+
const data = await fetchJson(url, {
|
|
137
|
+
headers: { "user-agent": ua, accept: "application/json" },
|
|
138
|
+
signal: controller.signal
|
|
139
|
+
}).finally(() => clearTimeout(timer));
|
|
140
|
+
const cur = data.current_condition?.[0];
|
|
141
|
+
if (!cur) throw new Error(`wttr.in returned no current_condition for "${loc}"`);
|
|
142
|
+
const area = data.nearest_area?.[0];
|
|
143
|
+
const condition = (lang === "vi" ? firstValue(cur.lang_vi) : void 0) ?? firstValue(cur.weatherDesc) ?? "N/A";
|
|
144
|
+
const visibility = num(cur.visibilityKm ?? cur.visibility, NaN);
|
|
145
|
+
const pressure = num(cur.pressure, NaN);
|
|
146
|
+
const uv = num(cur.uvIndex, NaN);
|
|
147
|
+
return {
|
|
148
|
+
location: firstValue(area?.areaName) ?? loc,
|
|
149
|
+
region: firstValue(area?.region),
|
|
150
|
+
country: firstValue(area?.country),
|
|
151
|
+
observed_at: cur.localObsDateTime ?? cur.observation_time ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
152
|
+
temperature_c: num(cur.temp_C),
|
|
153
|
+
feels_like_c: num(cur.FeelsLikeC),
|
|
154
|
+
humidity_percent: num(cur.humidity),
|
|
155
|
+
wind_kmh: num(cur.windspeedKmph),
|
|
156
|
+
wind_direction: cur.winddir16Point ?? "",
|
|
157
|
+
condition,
|
|
158
|
+
uv_index: Number.isFinite(uv) ? uv : void 0,
|
|
159
|
+
visibility_km: Number.isFinite(visibility) ? visibility : void 0,
|
|
160
|
+
pressure_mb: Number.isFinite(pressure) ? pressure : void 0,
|
|
161
|
+
source: "wttr.in"
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
var Parameters3 = effect.Schema.Struct({
|
|
167
|
+
symbols: effect.Schema.Array(effect.Schema.String),
|
|
168
|
+
quote: effect.Schema.optional(effect.Schema.String)
|
|
169
|
+
});
|
|
170
|
+
var PriceItem = effect.Schema.Struct({
|
|
171
|
+
symbol: effect.Schema.String,
|
|
172
|
+
quote: effect.Schema.String,
|
|
173
|
+
price: effect.Schema.Number,
|
|
174
|
+
pair: effect.Schema.String
|
|
175
|
+
});
|
|
176
|
+
var Success3 = effect.Schema.Struct({
|
|
177
|
+
prices: effect.Schema.Array(PriceItem),
|
|
178
|
+
observed_at: effect.Schema.String,
|
|
179
|
+
source: effect.Schema.Literal("binance")
|
|
180
|
+
});
|
|
181
|
+
var upper = (s) => s.trim().toUpperCase();
|
|
182
|
+
var cryptoPrice = (config = {}) => {
|
|
183
|
+
const defaultQuote = upper(config.quote ?? "USDT");
|
|
184
|
+
const timeout = config.timeoutMs ?? 1e4;
|
|
185
|
+
return agent.defineTool({
|
|
186
|
+
name: config.name ?? "crypto_price",
|
|
187
|
+
description: config.description ?? `L\u1EA5y gi\xE1 spot hi\u1EC7n t\u1EA1i c\u1EE7a m\u1ED9t ho\u1EB7c nhi\u1EC1u m\xE3 crypto (BTC, ETH, SOL, ...) t\xEDnh theo ${defaultQuote}. Ngu\u1ED3n: Binance.`,
|
|
188
|
+
parameters: Parameters3,
|
|
189
|
+
success: Success3,
|
|
190
|
+
execute: async (input) => {
|
|
191
|
+
const quote = upper(input.quote ?? defaultQuote);
|
|
192
|
+
const pairs = input.symbols.map((s) => `${upper(s)}${quote}`);
|
|
193
|
+
if (pairs.length === 0) throw new Error("symbols must be a non-empty array");
|
|
194
|
+
const arrayParam = encodeURIComponent(JSON.stringify(pairs));
|
|
195
|
+
const url = `https://api.binance.com/api/v3/ticker/price?symbols=${arrayParam}`;
|
|
196
|
+
const controller = new AbortController();
|
|
197
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
198
|
+
const data = await fetchJson(url, { signal: controller.signal }).finally(
|
|
199
|
+
() => clearTimeout(timer)
|
|
200
|
+
);
|
|
201
|
+
const prices = data.map((t) => ({
|
|
202
|
+
symbol: t.symbol.endsWith(quote) ? t.symbol.slice(0, -quote.length) : t.symbol,
|
|
203
|
+
quote,
|
|
204
|
+
price: Number(t.price),
|
|
205
|
+
pair: t.symbol
|
|
206
|
+
}));
|
|
207
|
+
return { prices, observed_at: (/* @__PURE__ */ new Date()).toISOString(), source: "binance" };
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
};
|
|
211
|
+
var loadHtml = (html) => cheerio.load(html);
|
|
212
|
+
var parseVndNumber = (s) => {
|
|
213
|
+
const cleaned = s.replace(/[^\d.,-]/g, "").trim();
|
|
214
|
+
if (!cleaned) return NaN;
|
|
215
|
+
const hasDot = cleaned.includes(".");
|
|
216
|
+
const hasComma = cleaned.includes(",");
|
|
217
|
+
if (hasDot && hasComma) {
|
|
218
|
+
const lastDot = cleaned.lastIndexOf(".");
|
|
219
|
+
const lastComma = cleaned.lastIndexOf(",");
|
|
220
|
+
const decimalIdx = Math.max(lastDot, lastComma);
|
|
221
|
+
const intPart = cleaned.slice(0, decimalIdx).replace(/[.,]/g, "");
|
|
222
|
+
const decPart = cleaned.slice(decimalIdx + 1);
|
|
223
|
+
return Number(`${intPart}.${decPart}`);
|
|
224
|
+
}
|
|
225
|
+
if (hasDot) {
|
|
226
|
+
const parts = cleaned.split(".");
|
|
227
|
+
const allGroupsThree = parts.slice(1).every((p) => p.length === 3);
|
|
228
|
+
if (allGroupsThree) return Number(parts.join(""));
|
|
229
|
+
return Number(cleaned);
|
|
230
|
+
}
|
|
231
|
+
if (hasComma) {
|
|
232
|
+
const parts = cleaned.split(",");
|
|
233
|
+
const allGroupsThree = parts.slice(1).every((p) => p.length === 3);
|
|
234
|
+
if (allGroupsThree) return Number(parts.join(""));
|
|
235
|
+
return Number(cleaned.replace(",", "."));
|
|
236
|
+
}
|
|
237
|
+
return Number(cleaned);
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// src/vn/gold.ts
|
|
241
|
+
var VendorChoice = effect.Schema.Union([effect.Schema.Literal("btmc"), effect.Schema.Literal("btmh"), effect.Schema.Literal("all")]);
|
|
242
|
+
var Parameters4 = effect.Schema.Struct({
|
|
243
|
+
vendor: effect.Schema.optional(VendorChoice)
|
|
244
|
+
});
|
|
245
|
+
var PriceItem2 = effect.Schema.Struct({
|
|
246
|
+
vendor: effect.Schema.String,
|
|
247
|
+
vendor_full: effect.Schema.String,
|
|
248
|
+
product: effect.Schema.String,
|
|
249
|
+
buy_vnd: effect.Schema.Number,
|
|
250
|
+
sell_vnd: effect.Schema.Number,
|
|
251
|
+
unit: effect.Schema.String,
|
|
252
|
+
source_url: effect.Schema.String
|
|
253
|
+
});
|
|
254
|
+
var Success4 = effect.Schema.Struct({
|
|
255
|
+
items: effect.Schema.Array(PriceItem2),
|
|
256
|
+
observed_at: effect.Schema.String,
|
|
257
|
+
warnings: effect.Schema.Array(effect.Schema.String)
|
|
258
|
+
});
|
|
259
|
+
var UA = "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
|
|
260
|
+
var BTMC_URL = "https://btmc.vn/";
|
|
261
|
+
var BTMH_URL = "https://baotinmanhhai.vn/vi/bang-gia-vang";
|
|
262
|
+
var parseBtmc = (html) => {
|
|
263
|
+
const items = [];
|
|
264
|
+
const warnings = [];
|
|
265
|
+
const startIdx = html.indexOf("NH\u1EAAN TR\xD2N TR\u01A0N B\u1EA2O T\xCDN");
|
|
266
|
+
if (startIdx < 0) {
|
|
267
|
+
warnings.push("BTMC: product label not found \u2014 layout may have changed");
|
|
268
|
+
return { items, warnings };
|
|
269
|
+
}
|
|
270
|
+
const endTag = html.indexOf("C\u1EADp nh\u1EADt l\xFAc", startIdx);
|
|
271
|
+
const region = endTag > 0 ? html.slice(startIdx, endTag) : html.slice(startIdx, startIdx + 4e3);
|
|
272
|
+
const matches = Array.from(region.matchAll(/<b[^>]*>\s*(\d{4,6})\s*<\/b>/g));
|
|
273
|
+
if (matches.length < 2) {
|
|
274
|
+
warnings.push("BTMC: couldn't find two <b> price tags after product label");
|
|
275
|
+
return { items, warnings };
|
|
276
|
+
}
|
|
277
|
+
const buyRaw = Number(matches[0][1]);
|
|
278
|
+
const sellRaw = Number(matches[1][1]);
|
|
279
|
+
if (!Number.isFinite(buyRaw) || !Number.isFinite(sellRaw)) {
|
|
280
|
+
warnings.push("BTMC: price numbers not parseable");
|
|
281
|
+
return { items, warnings };
|
|
282
|
+
}
|
|
283
|
+
items.push({
|
|
284
|
+
vendor: "btmc",
|
|
285
|
+
vendor_full: "B\u1EA3o T\xEDn Minh Ch\xE2u",
|
|
286
|
+
product: "Nh\u1EABn tr\xF2n tr\u01A1n 24K",
|
|
287
|
+
buy_vnd: buyRaw * 1e3,
|
|
288
|
+
sell_vnd: sellRaw * 1e3,
|
|
289
|
+
unit: "VND/ch\u1EC9",
|
|
290
|
+
source_url: BTMC_URL
|
|
291
|
+
});
|
|
292
|
+
return { items, warnings };
|
|
293
|
+
};
|
|
294
|
+
var parseBtmh = (html) => {
|
|
295
|
+
const items = [];
|
|
296
|
+
const warnings = [];
|
|
297
|
+
const $ = loadHtml(html);
|
|
298
|
+
let buyVnd = NaN;
|
|
299
|
+
let sellVnd = NaN;
|
|
300
|
+
let productLabel = "Nh\u1EABn Tr\xF2n \xE9p v\u1EC9 24K";
|
|
301
|
+
for (const tr of $("tr").toArray()) {
|
|
302
|
+
const rowText = $(tr).text();
|
|
303
|
+
if (!rowText.includes("Nh\u1EABn Tr\xF2n \xE9p v\u1EC9") && !rowText.includes("Nh\u1EABn Tr\xF2n")) continue;
|
|
304
|
+
if (!rowText.includes("24K") && !rowText.includes("999.9")) continue;
|
|
305
|
+
const cells = $(tr).find("td, th").toArray();
|
|
306
|
+
if (cells.length < 2) continue;
|
|
307
|
+
productLabel = $(cells[0]).text().trim().replace(/\s+/g, " ").slice(0, 80);
|
|
308
|
+
const numbers = [];
|
|
309
|
+
for (let i = 1; i < cells.length; i++) {
|
|
310
|
+
const raw = $(cells[i]).text().trim();
|
|
311
|
+
const n = parseVndNumber(raw);
|
|
312
|
+
if (Number.isFinite(n) && n > 1e6) numbers.push(n);
|
|
313
|
+
if (numbers.length === 2) break;
|
|
314
|
+
}
|
|
315
|
+
if (numbers.length === 2) {
|
|
316
|
+
sellVnd = numbers[0];
|
|
317
|
+
buyVnd = numbers[1];
|
|
318
|
+
break;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (!Number.isFinite(buyVnd) || !Number.isFinite(sellVnd)) {
|
|
322
|
+
warnings.push("BTMH: couldn't locate Nh\u1EABn Tr\xF2n 24K row with two prices");
|
|
323
|
+
return { items, warnings };
|
|
324
|
+
}
|
|
325
|
+
items.push({
|
|
326
|
+
vendor: "btmh",
|
|
327
|
+
vendor_full: "B\u1EA3o T\xEDn M\u1EA1nh H\u1EA3i",
|
|
328
|
+
product: productLabel,
|
|
329
|
+
buy_vnd: buyVnd,
|
|
330
|
+
sell_vnd: sellVnd,
|
|
331
|
+
unit: "VND/ch\u1EC9",
|
|
332
|
+
source_url: BTMH_URL
|
|
333
|
+
});
|
|
334
|
+
return { items, warnings };
|
|
335
|
+
};
|
|
336
|
+
var fetchSafe = async (url, ua, timeoutMs, label) => {
|
|
337
|
+
const controller = new AbortController();
|
|
338
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
339
|
+
return fetchText(url, {
|
|
340
|
+
headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
|
|
341
|
+
signal: controller.signal
|
|
342
|
+
}).then((html) => ({ html, error: null, label })).catch((err) => ({
|
|
343
|
+
html: "",
|
|
344
|
+
error: err instanceof Error ? err.message : String(err),
|
|
345
|
+
label
|
|
346
|
+
})).finally(() => clearTimeout(timer));
|
|
347
|
+
};
|
|
348
|
+
var vnGoldPrice = (config = {}) => {
|
|
349
|
+
const timeout = config.timeoutMs ?? 15e3;
|
|
350
|
+
const ua = config.userAgent ?? UA;
|
|
351
|
+
return agent.defineTool({
|
|
352
|
+
name: config.name ?? "vn_gold_price",
|
|
353
|
+
description: config.description ?? "L\u1EA5y gi\xE1 v\xE0ng nh\u1EABn tr\xF2n 24K Vi\u1EC7t Nam (B\u1EA3o T\xEDn Minh Ch\xE2u / B\u1EA3o T\xEDn M\u1EA1nh H\u1EA3i). Gi\xE1 tham kh\u1EA3o, c\xF3 th\u1EC3 l\u1EC7ch so v\u1EDBi th\u1EF1c t\u1EBF.",
|
|
354
|
+
parameters: Parameters4,
|
|
355
|
+
success: Success4,
|
|
356
|
+
execute: async (input) => {
|
|
357
|
+
const vendor = input.vendor ?? "all";
|
|
358
|
+
const items = [];
|
|
359
|
+
const warnings = [];
|
|
360
|
+
const tasks = [];
|
|
361
|
+
if (vendor === "btmc" || vendor === "all") tasks.push(fetchSafe(BTMC_URL, ua, timeout, "btmc"));
|
|
362
|
+
if (vendor === "btmh" || vendor === "all") tasks.push(fetchSafe(BTMH_URL, ua, timeout, "btmh"));
|
|
363
|
+
const results = await Promise.all(tasks);
|
|
364
|
+
for (const r of results) {
|
|
365
|
+
if (r.error) {
|
|
366
|
+
warnings.push(`${r.label}: fetch failed (${r.error})`);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const parsed = r.label === "btmc" ? parseBtmc(r.html) : parseBtmh(r.html);
|
|
370
|
+
items.push(...parsed.items);
|
|
371
|
+
warnings.push(...parsed.warnings);
|
|
372
|
+
}
|
|
373
|
+
return { items, observed_at: (/* @__PURE__ */ new Date()).toISOString(), warnings };
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
};
|
|
377
|
+
var RegionChoice = effect.Schema.Union([
|
|
378
|
+
effect.Schema.Literal("north"),
|
|
379
|
+
effect.Schema.Literal("central"),
|
|
380
|
+
effect.Schema.Literal("south")
|
|
381
|
+
]);
|
|
382
|
+
var Parameters5 = effect.Schema.Struct({
|
|
383
|
+
region: effect.Schema.optional(RegionChoice)
|
|
384
|
+
});
|
|
385
|
+
var Prize = effect.Schema.Struct({
|
|
386
|
+
name: effect.Schema.String,
|
|
387
|
+
numbers: effect.Schema.Array(effect.Schema.String)
|
|
388
|
+
});
|
|
389
|
+
var Success5 = effect.Schema.Struct({
|
|
390
|
+
region: effect.Schema.String,
|
|
391
|
+
region_label: effect.Schema.String,
|
|
392
|
+
date: effect.Schema.optional(effect.Schema.String),
|
|
393
|
+
prizes: effect.Schema.Array(Prize),
|
|
394
|
+
source_url: effect.Schema.String,
|
|
395
|
+
warnings: effect.Schema.Array(effect.Schema.String)
|
|
396
|
+
});
|
|
397
|
+
var UA2 = "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
|
|
398
|
+
var REGION_URLS = {
|
|
399
|
+
north: { url: "https://xoso.com.vn/xo-so-mien-bac/xsmb-p1.html", label: "Mi\u1EC1n B\u1EAFc", code: "XSMB" },
|
|
400
|
+
central: { url: "https://xoso.com.vn/xo-so-mien-trung/xsmt-p1.html", label: "Mi\u1EC1n Trung", code: "XSMT" },
|
|
401
|
+
south: { url: "https://xoso.com.vn/xo-so-mien-nam/xsmn-p1.html", label: "Mi\u1EC1n Nam", code: "XSMN" }
|
|
402
|
+
};
|
|
403
|
+
var parseDate = (sectionText, code) => {
|
|
404
|
+
const re = new RegExp(`${code}\\s+(\\d{2}/\\d{2}/\\d{4})`);
|
|
405
|
+
const m = re.exec(sectionText);
|
|
406
|
+
return m ? m[1] : void 0;
|
|
407
|
+
};
|
|
408
|
+
var vnLottery = (config = {}) => {
|
|
409
|
+
const timeout = config.timeoutMs ?? 15e3;
|
|
410
|
+
const ua = config.userAgent ?? UA2;
|
|
411
|
+
return agent.defineTool({
|
|
412
|
+
name: config.name ?? "vn_lottery",
|
|
413
|
+
description: config.description ?? "L\u1EA5y k\u1EBFt qu\u1EA3 x\u1ED5 s\u1ED1 ki\u1EBFn thi\u1EBFt Vi\u1EC7t Nam m\u1EDBi nh\u1EA5t theo mi\u1EC1n (m\u1EB7c \u0111\u1ECBnh Mi\u1EC1n B\u1EAFc / XSMB). Ngu\u1ED3n: xoso.com.vn.",
|
|
414
|
+
parameters: Parameters5,
|
|
415
|
+
success: Success5,
|
|
416
|
+
execute: async (input) => {
|
|
417
|
+
const region = input.region ?? "north";
|
|
418
|
+
const conf = REGION_URLS[region];
|
|
419
|
+
const warnings = [];
|
|
420
|
+
const controller = new AbortController();
|
|
421
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
422
|
+
const html = await fetchText(conf.url, {
|
|
423
|
+
headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
|
|
424
|
+
signal: controller.signal
|
|
425
|
+
}).finally(() => clearTimeout(timer));
|
|
426
|
+
const $ = loadHtml(html);
|
|
427
|
+
const section = $("section[id^='kqngay_']").first();
|
|
428
|
+
if (section.length === 0) {
|
|
429
|
+
warnings.push(`xoso.com.vn: no section[id^='kqngay_'] for ${conf.code}`);
|
|
430
|
+
return {
|
|
431
|
+
region,
|
|
432
|
+
region_label: conf.label,
|
|
433
|
+
prizes: [],
|
|
434
|
+
source_url: conf.url,
|
|
435
|
+
warnings
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
const sectionText = section.text();
|
|
439
|
+
const date = parseDate(sectionText, conf.code);
|
|
440
|
+
const prizes = [];
|
|
441
|
+
const rows = section.find("table.table-result tbody tr").toArray();
|
|
442
|
+
for (const tr of rows) {
|
|
443
|
+
const cells = $(tr).find("td").toArray();
|
|
444
|
+
if (cells.length < 2) continue;
|
|
445
|
+
const prizeName = $(cells[0]).text().trim();
|
|
446
|
+
if (!prizeName) continue;
|
|
447
|
+
const numberSpans = $(tr).find("span").toArray();
|
|
448
|
+
const numbers = [];
|
|
449
|
+
for (const sp of numberSpans) {
|
|
450
|
+
const v = $(sp).text().trim();
|
|
451
|
+
if (/^\d{2,6}$/.test(v)) numbers.push(v);
|
|
452
|
+
}
|
|
453
|
+
if (numbers.length === 0) continue;
|
|
454
|
+
prizes.push({ name: prizeName, numbers });
|
|
455
|
+
}
|
|
456
|
+
if (prizes.length === 0) warnings.push(`xoso.com.vn: no prize rows extracted for ${conf.code}`);
|
|
457
|
+
return {
|
|
458
|
+
region,
|
|
459
|
+
region_label: conf.label,
|
|
460
|
+
date,
|
|
461
|
+
prizes,
|
|
462
|
+
source_url: conf.url,
|
|
463
|
+
warnings
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
};
|
|
468
|
+
var Parameters6 = effect.Schema.Struct({
|
|
469
|
+
query: effect.Schema.String
|
|
470
|
+
});
|
|
471
|
+
var Citation = effect.Schema.Struct({
|
|
472
|
+
url: effect.Schema.String,
|
|
473
|
+
title: effect.Schema.optional(effect.Schema.String)
|
|
474
|
+
});
|
|
475
|
+
var Success6 = effect.Schema.Struct({
|
|
476
|
+
query: effect.Schema.String,
|
|
477
|
+
answer: effect.Schema.String,
|
|
478
|
+
citations: effect.Schema.Array(Citation),
|
|
479
|
+
model: effect.Schema.String
|
|
480
|
+
});
|
|
481
|
+
var normaliseCitations = (data) => {
|
|
482
|
+
if (data.search_results && data.search_results.length > 0) {
|
|
483
|
+
return data.search_results.filter((r) => typeof r.url === "string" && r.url.length > 0).map((r) => r.title ? { url: r.url, title: r.title } : { url: r.url });
|
|
484
|
+
}
|
|
485
|
+
if (data.citations && data.citations.length > 0) {
|
|
486
|
+
return data.citations.filter((u) => typeof u === "string").map((u) => ({ url: u }));
|
|
487
|
+
}
|
|
488
|
+
return [];
|
|
489
|
+
};
|
|
490
|
+
var perplexitySearch = (config) => {
|
|
491
|
+
if (!config.apiKey) throw new Error("perplexitySearch: apiKey is required");
|
|
492
|
+
const model = config.model ?? "sonar";
|
|
493
|
+
const baseURL = config.baseURL ?? "https://api.perplexity.ai";
|
|
494
|
+
const timeout = config.timeoutMs ?? 3e4;
|
|
495
|
+
const temperature = config.temperature ?? 0.2;
|
|
496
|
+
const maxTokens = config.maxTokens ?? 800;
|
|
497
|
+
const sys = config.systemPrompt ?? "Answer the user's question accurately and concisely. Cite sources by URL. Use the user's language.";
|
|
498
|
+
return agent.defineTool({
|
|
499
|
+
name: config.name ?? "perplexity_search",
|
|
500
|
+
description: config.description ?? "H\u1ECFi-\u0111\xE1p web v\u1EDBi Perplexity Sonar: nh\u1EADn v\u1EC1 c\xE2u tr\u1EA3 l\u1EDDi \u0111\xE3 t\u1ED5ng h\u1EE3p + citation. D\xF9ng khi c\u1EA7n th\xF4ng tin t\u01B0\u01A1i/\u0111a ngu\u1ED3n.",
|
|
501
|
+
parameters: Parameters6,
|
|
502
|
+
success: Success6,
|
|
503
|
+
execute: async (input) => {
|
|
504
|
+
const url = `${baseURL.replace(/\/+$/, "")}/chat/completions`;
|
|
505
|
+
const controller = new AbortController();
|
|
506
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
507
|
+
const body = {
|
|
508
|
+
model,
|
|
509
|
+
messages: [
|
|
510
|
+
{ role: "system", content: sys },
|
|
511
|
+
{ role: "user", content: input.query }
|
|
512
|
+
],
|
|
513
|
+
temperature,
|
|
514
|
+
max_tokens: maxTokens
|
|
515
|
+
};
|
|
516
|
+
const data = await postJson(url, body, {
|
|
517
|
+
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
518
|
+
signal: controller.signal
|
|
519
|
+
}).finally(() => clearTimeout(timer));
|
|
520
|
+
const answer = data.choices?.[0]?.message?.content ?? "";
|
|
521
|
+
if (!answer) throw new Error("perplexitySearch: empty answer from Sonar API");
|
|
522
|
+
return {
|
|
523
|
+
query: input.query,
|
|
524
|
+
answer,
|
|
525
|
+
citations: normaliseCitations(data),
|
|
526
|
+
model: data.model ?? model
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
};
|
|
531
|
+
var ResultItem = effect.Schema.Struct({
|
|
532
|
+
title: effect.Schema.String,
|
|
533
|
+
url: effect.Schema.String,
|
|
534
|
+
snippet: effect.Schema.String
|
|
535
|
+
});
|
|
536
|
+
var Parameters7 = effect.Schema.Struct({
|
|
537
|
+
query: effect.Schema.String,
|
|
538
|
+
limit: effect.Schema.optional(effect.Schema.Number)
|
|
539
|
+
});
|
|
540
|
+
var Success7 = effect.Schema.Struct({
|
|
541
|
+
results: effect.Schema.Array(ResultItem)
|
|
542
|
+
});
|
|
543
|
+
var searchTavily = async (apiKey, input) => {
|
|
544
|
+
const data = await postJson("https://api.tavily.com/search", {
|
|
545
|
+
api_key: apiKey,
|
|
546
|
+
query: input.query,
|
|
547
|
+
max_results: input.limit ?? 5
|
|
548
|
+
});
|
|
549
|
+
return data.results.map((r) => ({ title: r.title, url: r.url, snippet: r.content ?? "" }));
|
|
550
|
+
};
|
|
551
|
+
var searchBrave = async (apiKey, input) => {
|
|
552
|
+
const params = new URLSearchParams({ q: input.query, count: String(input.limit ?? 5) });
|
|
553
|
+
const data = await fetchJson(`https://api.search.brave.com/res/v1/web/search?${params}`, {
|
|
554
|
+
headers: { "X-Subscription-Token": apiKey, accept: "application/json" }
|
|
555
|
+
});
|
|
556
|
+
const items = data.web?.results ?? [];
|
|
557
|
+
return items.map((r) => ({ title: r.title, url: r.url, snippet: r.description ?? "" }));
|
|
558
|
+
};
|
|
559
|
+
var searchExa = async (apiKey, input) => {
|
|
560
|
+
const data = await postJson(
|
|
561
|
+
"https://api.exa.ai/search",
|
|
562
|
+
{ query: input.query, numResults: input.limit ?? 5, contents: { text: true } },
|
|
563
|
+
{ headers: { "x-api-key": apiKey } }
|
|
564
|
+
);
|
|
565
|
+
return data.results.map((r) => ({ title: r.title ?? r.url, url: r.url, snippet: (r.text ?? "").slice(0, 500) }));
|
|
566
|
+
};
|
|
567
|
+
var searchSerper = async (apiKey, input) => {
|
|
568
|
+
const data = await postJson(
|
|
569
|
+
"https://google.serper.dev/search",
|
|
570
|
+
{ q: input.query, num: input.limit ?? 5 },
|
|
571
|
+
{ headers: { "X-API-KEY": apiKey } }
|
|
572
|
+
);
|
|
573
|
+
return (data.organic ?? []).map((r) => ({ title: r.title, url: r.link, snippet: r.snippet ?? "" }));
|
|
574
|
+
};
|
|
575
|
+
var dispatch = (provider, apiKey, input) => {
|
|
576
|
+
if (provider === "tavily") return searchTavily(apiKey, input);
|
|
577
|
+
if (provider === "brave") return searchBrave(apiKey, input);
|
|
578
|
+
if (provider === "exa") return searchExa(apiKey, input);
|
|
579
|
+
if (provider === "serper") return searchSerper(apiKey, input);
|
|
580
|
+
throw new Error(`Unknown web_search provider: ${provider}`);
|
|
581
|
+
};
|
|
582
|
+
var webSearch = (config) => agent.defineTool({
|
|
583
|
+
name: config.name ?? "web_search",
|
|
584
|
+
description: config.description ?? "Search the web and return a list of {title, url, snippet} results.",
|
|
585
|
+
parameters: Parameters7,
|
|
586
|
+
success: Success7,
|
|
587
|
+
execute: async (input) => ({ results: await dispatch(config.provider, config.apiKey, input) })
|
|
588
|
+
});
|
|
589
|
+
var Parameters8 = effect.Schema.Struct({
|
|
590
|
+
url: effect.Schema.String
|
|
591
|
+
});
|
|
592
|
+
var Success8 = effect.Schema.Struct({
|
|
593
|
+
url: effect.Schema.String,
|
|
594
|
+
title: effect.Schema.optional(effect.Schema.String),
|
|
595
|
+
content: effect.Schema.String
|
|
596
|
+
});
|
|
597
|
+
var HTML_ENTITIES = {
|
|
598
|
+
"&": "&",
|
|
599
|
+
"<": "<",
|
|
600
|
+
">": ">",
|
|
601
|
+
""": '"',
|
|
602
|
+
"'": "'",
|
|
603
|
+
"'": "'",
|
|
604
|
+
" ": " "
|
|
605
|
+
};
|
|
606
|
+
var decodeEntities = (s) => s.replace(/&(?:amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => HTML_ENTITIES[m] ?? m).replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code)));
|
|
607
|
+
var extractTitle = (html) => {
|
|
608
|
+
const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
|
|
609
|
+
if (!match) return void 0;
|
|
610
|
+
return decodeEntities(match[1] ?? "").trim() || void 0;
|
|
611
|
+
};
|
|
612
|
+
var htmlToText = (html, maxLength) => {
|
|
613
|
+
const stripped = html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<noscript[\s\S]*?<\/noscript>/gi, "").replace(/<!--[\s\S]*?-->/g, "").replace(/<\/(p|div|li|h\d|br|tr)>/gi, "\n").replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]+>/g, " ");
|
|
614
|
+
const collapsed = decodeEntities(stripped).replace(/[ \t]+/g, " ").replace(/\n\s*\n+/g, "\n\n").trim();
|
|
615
|
+
if (collapsed.length <= maxLength) return collapsed;
|
|
616
|
+
return collapsed.slice(0, maxLength) + "\n... [truncated]";
|
|
617
|
+
};
|
|
618
|
+
var webFetch = (config = {}) => {
|
|
619
|
+
const timeout = config.timeoutMs ?? 15e3;
|
|
620
|
+
const maxLength = config.maxLength ?? 1e5;
|
|
621
|
+
const ua = config.userAgent ?? "tinyweb-agent/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
|
|
622
|
+
return agent.defineTool({
|
|
623
|
+
name: config.name ?? "web_fetch",
|
|
624
|
+
description: config.description ?? "Fetch a URL and return its title plus extracted plain-text content.",
|
|
625
|
+
parameters: Parameters8,
|
|
626
|
+
success: Success8,
|
|
627
|
+
execute: async (input) => {
|
|
628
|
+
const controller = new AbortController();
|
|
629
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
630
|
+
const res = await fetch(input.url, {
|
|
631
|
+
headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
|
|
632
|
+
signal: controller.signal
|
|
633
|
+
}).finally(() => clearTimeout(timer));
|
|
634
|
+
if (!res.ok) throw new Error(`Fetch ${input.url} failed: HTTP ${res.status}`);
|
|
635
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
636
|
+
const raw = await res.text();
|
|
637
|
+
if (contentType.includes("html")) {
|
|
638
|
+
return { url: input.url, title: extractTitle(raw), content: htmlToText(raw, maxLength) };
|
|
639
|
+
}
|
|
640
|
+
return { url: input.url, content: raw.length > maxLength ? raw.slice(0, maxLength) + "\n... [truncated]" : raw };
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
};
|
|
644
|
+
var Parameters9 = effect.Schema.Struct({
|
|
645
|
+
response: effect.Schema.String
|
|
646
|
+
});
|
|
647
|
+
var Success9 = effect.Schema.Struct({
|
|
648
|
+
response: effect.Schema.String
|
|
649
|
+
});
|
|
650
|
+
var DEFAULT_DESCRIPTION = [
|
|
651
|
+
"Deliver a plain textual response to the user when no other tool is appropriate for the current turn.",
|
|
652
|
+
'Use this as a fallback to satisfy the "every assistant turn must call at least one tool" constraint',
|
|
653
|
+
"whenever you only need to send textual content \u2014 both short conversational replies and long-form",
|
|
654
|
+
"structured output \u2014 that does not finish the task. Typical use cases:",
|
|
655
|
+
"- Clarifying remarks, brainstorming, short answers, status updates",
|
|
656
|
+
"- Presenting a plan or proposed approach before implementation",
|
|
657
|
+
"- Explaining code, concepts, errors, or trade-offs in depth",
|
|
658
|
+
"- Delivering a long-form report, summary, analysis, or review",
|
|
659
|
+
"- Showing diagrams, tables, or formatted markdown content to the user",
|
|
660
|
+
"",
|
|
661
|
+
"STRICT OUTPUT RULES (must follow exactly):",
|
|
662
|
+
"- Put the ENTIRE message inside the `response` argument of this tool call.",
|
|
663
|
+
"- Do NOT emit ANY free-form assistant text outside the tool call in the same turn. The assistant",
|
|
664
|
+
" text channel MUST be empty when you call `display_response`.",
|
|
665
|
+
'- This means: no preamble, no recap, no "Here is\u2026", no trailing remark before or after the tool',
|
|
666
|
+
" call. Everything the user should see goes inside `response`.",
|
|
667
|
+
"- After you call display_response, STOP. Wait for the user's next message before doing anything",
|
|
668
|
+
" else. Do NOT keep calling tools or generate another turn on your own.",
|
|
669
|
+
"- The `response` must be non-empty.",
|
|
670
|
+
"- Prefer NOT calling display_response if a domain tool (search, weather, etc.) is the right answer.",
|
|
671
|
+
"",
|
|
672
|
+
"Parameters:",
|
|
673
|
+
"- response: (required) The textual message to deliver to the user. Markdown is supported.",
|
|
674
|
+
"",
|
|
675
|
+
"Example (correct \u2014 assistant text is empty, all content is inside the tool call):",
|
|
676
|
+
'{ "response": "I looked at the two options and I think Option A is cleaner because it avoids the extra cache lookup." }'
|
|
677
|
+
].join("\n");
|
|
678
|
+
var displayResponse = (config = {}) => agent.defineTool({
|
|
679
|
+
name: config.name ?? "display_response",
|
|
680
|
+
description: config.description ?? DEFAULT_DESCRIPTION,
|
|
681
|
+
parameters: Parameters9,
|
|
682
|
+
success: Success9,
|
|
683
|
+
execute: async (input) => ({ response: input.response })
|
|
684
|
+
});
|
|
685
|
+
var TodoStatusSchema = effect.Schema.Union([
|
|
686
|
+
effect.Schema.Literal("pending"),
|
|
687
|
+
effect.Schema.Literal("in_progress"),
|
|
688
|
+
effect.Schema.Literal("completed")
|
|
689
|
+
]);
|
|
690
|
+
var TodoItemSchema = effect.Schema.Struct({
|
|
691
|
+
id: effect.Schema.String,
|
|
692
|
+
content: effect.Schema.String,
|
|
693
|
+
status: TodoStatusSchema
|
|
694
|
+
});
|
|
695
|
+
var Parameters10 = effect.Schema.Struct({
|
|
696
|
+
todos: effect.Schema.String
|
|
697
|
+
});
|
|
698
|
+
var Success10 = effect.Schema.Struct({
|
|
699
|
+
ok: effect.Schema.Boolean,
|
|
700
|
+
message: effect.Schema.String,
|
|
701
|
+
todos: effect.Schema.Array(TodoItemSchema),
|
|
702
|
+
completed_count: effect.Schema.Number,
|
|
703
|
+
total_count: effect.Schema.Number,
|
|
704
|
+
markdown: effect.Schema.String
|
|
705
|
+
});
|
|
706
|
+
var DEFAULT_DESCRIPTION2 = [
|
|
707
|
+
"Replace the entire TODO list with an updated checklist reflecting the current state. Always provide the full list; the system will overwrite the previous one. This tool is designed for step-by-step task tracking, allowing you to confirm completion of each step before updating, update multiple task statuses at once (e.g., mark one as completed and start the next), and dynamically add new todos discovered during long or complex tasks.",
|
|
708
|
+
"",
|
|
709
|
+
"Checklist Format:",
|
|
710
|
+
"- Use a single-level markdown checklist (no nesting or subtasks)",
|
|
711
|
+
"- List todos in the intended execution order",
|
|
712
|
+
"- Status options: [ ] (pending), [x] (completed), [-] (in progress)",
|
|
713
|
+
"",
|
|
714
|
+
"Core Principles:",
|
|
715
|
+
"- Before updating, always confirm which todos have been completed",
|
|
716
|
+
"- You may update multiple statuses in a single update",
|
|
717
|
+
"- Add new actionable items as they're discovered",
|
|
718
|
+
"- Only mark a task as completed when fully accomplished",
|
|
719
|
+
"- Keep all unfinished tasks unless explicitly instructed to remove",
|
|
720
|
+
"",
|
|
721
|
+
"Example: Initial task list",
|
|
722
|
+
'{ "todos": "[x] Analyze requirements\\n[x] Design architecture\\n[-] Implement core logic\\n[ ] Write tests\\n[ ] Update documentation" }',
|
|
723
|
+
"",
|
|
724
|
+
"Example: After completing implementation",
|
|
725
|
+
'{ "todos": "[x] Analyze requirements\\n[x] Design architecture\\n[x] Implement core logic\\n[-] Write tests\\n[ ] Update documentation\\n[ ] Add performance benchmarks" }',
|
|
726
|
+
"",
|
|
727
|
+
"When to Use:",
|
|
728
|
+
"- Task involves multiple steps or requires ongoing tracking",
|
|
729
|
+
"- Need to update status of several todos at once",
|
|
730
|
+
"- New actionable items are discovered during execution",
|
|
731
|
+
"- Task is complex and benefits from stepwise progress tracking",
|
|
732
|
+
"",
|
|
733
|
+
"When NOT to Use:",
|
|
734
|
+
"- Only a single, trivial task",
|
|
735
|
+
"- Task can be completed in one or two simple steps",
|
|
736
|
+
"- Request is purely conversational or informational"
|
|
737
|
+
].join("\n");
|
|
738
|
+
var parseMarkdownChecklist = (md) => {
|
|
739
|
+
if (typeof md !== "string") return [];
|
|
740
|
+
const normalized = md.includes("\n") || md.includes("\r") ? md : md.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\r/g, "\n");
|
|
741
|
+
const lines = normalized.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
742
|
+
const todos = [];
|
|
743
|
+
for (const line of lines) {
|
|
744
|
+
const match = line.match(/^(?:-\s*)?\[\s*([ xX\-~])\s*\]\s+(.+)$/);
|
|
745
|
+
if (!match) continue;
|
|
746
|
+
const mark = match[1];
|
|
747
|
+
const content = match[2];
|
|
748
|
+
let status = "pending";
|
|
749
|
+
if (mark === "x" || mark === "X") status = "completed";
|
|
750
|
+
else if (mark === "-" || mark === "~") status = "in_progress";
|
|
751
|
+
const id = crypto.createHash("md5").update(content + status).digest("hex");
|
|
752
|
+
todos.push({ id, content, status });
|
|
753
|
+
}
|
|
754
|
+
return todos;
|
|
755
|
+
};
|
|
756
|
+
var todoListToMarkdown = (todos) => todos.map((t) => {
|
|
757
|
+
let box = "[ ]";
|
|
758
|
+
if (t.status === "completed") box = "[x]";
|
|
759
|
+
else if (t.status === "in_progress") box = "[-]";
|
|
760
|
+
return `${box} ${t.content}`;
|
|
761
|
+
}).join("\n");
|
|
762
|
+
var updateTodoList = (config = {}) => agent.defineTool({
|
|
763
|
+
name: config.name ?? "update_todo_list",
|
|
764
|
+
description: config.description ?? DEFAULT_DESCRIPTION2,
|
|
765
|
+
parameters: Parameters10,
|
|
766
|
+
success: Success10,
|
|
767
|
+
execute: async (input) => {
|
|
768
|
+
const todos = parseMarkdownChecklist(input.todos);
|
|
769
|
+
if (todos.length === 0) {
|
|
770
|
+
return {
|
|
771
|
+
ok: false,
|
|
772
|
+
message: "No valid checklist items found. Use markdown lines like `[ ] task`, `[-] task`, or `[x] task`.",
|
|
773
|
+
todos: [],
|
|
774
|
+
completed_count: 0,
|
|
775
|
+
total_count: 0,
|
|
776
|
+
markdown: ""
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
const completed_count = todos.filter((t) => t.status === "completed").length;
|
|
780
|
+
return {
|
|
781
|
+
ok: true,
|
|
782
|
+
message: "Todo list updated successfully.",
|
|
783
|
+
todos,
|
|
784
|
+
completed_count,
|
|
785
|
+
total_count: todos.length,
|
|
786
|
+
markdown: todoListToMarkdown(todos)
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
// src/builtins.ts
|
|
792
|
+
var isEnabled = (v, defaultOn) => {
|
|
793
|
+
if (v === void 0) return defaultOn;
|
|
794
|
+
if (v === false) return false;
|
|
795
|
+
return true;
|
|
796
|
+
};
|
|
797
|
+
var cfgOrEmpty = (v) => {
|
|
798
|
+
if (typeof v === "object" && v !== null) return v;
|
|
799
|
+
return {};
|
|
800
|
+
};
|
|
801
|
+
var builtinTools = (config = {}) => {
|
|
802
|
+
const tools = {};
|
|
803
|
+
if (isEnabled(config.time, true)) tools.time_now = timeNow(cfgOrEmpty(config.time));
|
|
804
|
+
if (isEnabled(config.displayResponse, true))
|
|
805
|
+
tools.display_response = displayResponse(cfgOrEmpty(config.displayResponse));
|
|
806
|
+
if (isEnabled(config.updateTodoList, false))
|
|
807
|
+
tools.update_todo_list = updateTodoList(cfgOrEmpty(config.updateTodoList));
|
|
808
|
+
if (isEnabled(config.weather, false)) tools.weather = weather(cfgOrEmpty(config.weather));
|
|
809
|
+
if (isEnabled(config.crypto, false)) tools.crypto_price = cryptoPrice(cfgOrEmpty(config.crypto));
|
|
810
|
+
if (isEnabled(config.vnGold, false)) tools.vn_gold_price = vnGoldPrice(cfgOrEmpty(config.vnGold));
|
|
811
|
+
if (isEnabled(config.vnLottery, false)) tools.vn_lottery = vnLottery(cfgOrEmpty(config.vnLottery));
|
|
812
|
+
if (isEnabled(config.webFetch, false)) tools.web_fetch = webFetch(cfgOrEmpty(config.webFetch));
|
|
813
|
+
if (config.perplexity) tools.perplexity_search = perplexitySearch(config.perplexity);
|
|
814
|
+
if (config.webSearch) tools.web_search = webSearch(config.webSearch);
|
|
815
|
+
return tools;
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
exports.builtinTools = builtinTools;
|
|
819
|
+
//# sourceMappingURL=builtins.cjs.map
|
|
820
|
+
//# sourceMappingURL=builtins.cjs.map
|