@tinyweb_dev/agent-framework-tool 0.1.0 → 0.3.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.
Files changed (141) hide show
  1. package/dist/builtins.cjs +712 -0
  2. package/dist/builtins.cjs.map +1 -0
  3. package/dist/builtins.d.ts +52 -0
  4. package/dist/builtins.d.ts.map +1 -0
  5. package/dist/builtins.js +710 -0
  6. package/dist/builtins.js.map +1 -0
  7. package/dist/display_response.cjs +51 -0
  8. package/dist/display_response.cjs.map +1 -0
  9. package/dist/display_response.d.ts +36 -0
  10. package/dist/display_response.d.ts.map +1 -0
  11. package/dist/display_response.js +49 -0
  12. package/dist/display_response.js.map +1 -0
  13. package/dist/file_read.cjs +28 -0
  14. package/dist/file_read.cjs.map +1 -0
  15. package/dist/file_read.d.ts +14 -0
  16. package/dist/file_read.d.ts.map +1 -0
  17. package/dist/file_read.js +26 -0
  18. package/dist/file_read.js.map +1 -0
  19. package/dist/file_write.cjs +30 -0
  20. package/dist/file_write.cjs.map +1 -0
  21. package/dist/file_write.d.ts +16 -0
  22. package/dist/file_write.d.ts.map +1 -0
  23. package/dist/file_write.js +28 -0
  24. package/dist/file_write.js.map +1 -0
  25. package/dist/image_describe.cjs +69 -0
  26. package/dist/image_describe.cjs.map +1 -0
  27. package/dist/image_describe.d.ts +15 -0
  28. package/dist/image_describe.d.ts.map +1 -0
  29. package/dist/image_describe.js +67 -0
  30. package/dist/image_describe.js.map +1 -0
  31. package/dist/image_edit.cjs +87 -0
  32. package/dist/image_edit.cjs.map +1 -0
  33. package/dist/image_edit.d.ts +20 -0
  34. package/dist/image_edit.d.ts.map +1 -0
  35. package/dist/image_edit.js +85 -0
  36. package/dist/image_edit.js.map +1 -0
  37. package/dist/image_generate.cjs +112 -0
  38. package/dist/image_generate.cjs.map +1 -0
  39. package/dist/image_generate.d.ts +21 -0
  40. package/dist/image_generate.d.ts.map +1 -0
  41. package/dist/image_generate.js +110 -0
  42. package/dist/image_generate.js.map +1 -0
  43. package/dist/index.cjs +1098 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.ts +21 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +1068 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/info/crypto.cjs +78 -0
  50. package/dist/info/crypto.cjs.map +1 -0
  51. package/dist/info/crypto.d.ts +34 -0
  52. package/dist/info/crypto.d.ts.map +1 -0
  53. package/dist/info/crypto.js +76 -0
  54. package/dist/info/crypto.js.map +1 -0
  55. package/dist/info/time.cjs +60 -0
  56. package/dist/info/time.cjs.map +1 -0
  57. package/dist/info/time.d.ts +31 -0
  58. package/dist/info/time.d.ts.map +1 -0
  59. package/dist/info/time.js +58 -0
  60. package/dist/info/time.js.map +1 -0
  61. package/dist/info/weather.cjs +105 -0
  62. package/dist/info/weather.cjs.map +1 -0
  63. package/dist/info/weather.d.ts +41 -0
  64. package/dist/info/weather.d.ts.map +1 -0
  65. package/dist/info/weather.js +103 -0
  66. package/dist/info/weather.js.map +1 -0
  67. package/dist/search/perplexity.cjs +98 -0
  68. package/dist/search/perplexity.cjs.map +1 -0
  69. package/dist/search/perplexity.d.ts +49 -0
  70. package/dist/search/perplexity.d.ts.map +1 -0
  71. package/dist/search/perplexity.js +96 -0
  72. package/dist/search/perplexity.js.map +1 -0
  73. package/dist/shared/html.cjs +57 -0
  74. package/dist/shared/html.cjs.map +1 -0
  75. package/dist/shared/html.d.ts +37 -0
  76. package/dist/shared/html.d.ts.map +1 -0
  77. package/dist/shared/html.js +52 -0
  78. package/dist/shared/html.js.map +1 -0
  79. package/dist/shared/http.cjs +48 -0
  80. package/dist/shared/http.cjs.map +1 -0
  81. package/dist/shared/http.d.ts +11 -0
  82. package/dist/shared/http.d.ts.map +1 -0
  83. package/dist/shared/http.js +42 -0
  84. package/dist/shared/http.js.map +1 -0
  85. package/dist/shared/s3.cjs +98 -0
  86. package/dist/shared/s3.cjs.map +1 -0
  87. package/dist/shared/s3.d.ts +35 -0
  88. package/dist/shared/s3.d.ts.map +1 -0
  89. package/dist/shared/s3.js +96 -0
  90. package/dist/shared/s3.js.map +1 -0
  91. package/dist/shared/storage.cjs +74 -0
  92. package/dist/shared/storage.cjs.map +1 -0
  93. package/dist/shared/storage.d.ts +17 -0
  94. package/dist/shared/storage.d.ts.map +1 -0
  95. package/dist/shared/storage.js +70 -0
  96. package/dist/shared/storage.js.map +1 -0
  97. package/dist/vn/gold.cjs +198 -0
  98. package/dist/vn/gold.cjs.map +1 -0
  99. package/dist/vn/gold.d.ts +36 -0
  100. package/dist/vn/gold.d.ts.map +1 -0
  101. package/dist/vn/gold.js +196 -0
  102. package/dist/vn/gold.js.map +1 -0
  103. package/dist/vn/lottery.cjs +126 -0
  104. package/dist/vn/lottery.cjs.map +1 -0
  105. package/dist/vn/lottery.d.ts +31 -0
  106. package/dist/vn/lottery.d.ts.map +1 -0
  107. package/dist/vn/lottery.js +124 -0
  108. package/dist/vn/lottery.js.map +1 -0
  109. package/dist/web_fetch.cjs +65 -0
  110. package/dist/web_fetch.cjs.map +1 -0
  111. package/dist/web_fetch.d.ts +16 -0
  112. package/dist/web_fetch.d.ts.map +1 -0
  113. package/dist/web_fetch.js +63 -0
  114. package/dist/web_fetch.js.map +1 -0
  115. package/dist/web_search.cjs +98 -0
  116. package/dist/web_search.cjs.map +1 -0
  117. package/dist/web_search.d.ts +19 -0
  118. package/dist/web_search.d.ts.map +1 -0
  119. package/dist/web_search.js +96 -0
  120. package/dist/web_search.js.map +1 -0
  121. package/package.json +109 -30
  122. package/src/builtins.ts +0 -78
  123. package/src/display_response.ts +0 -79
  124. package/src/file_read.ts +0 -31
  125. package/src/file_write.ts +0 -33
  126. package/src/image_describe.ts +0 -58
  127. package/src/image_edit.ts +0 -74
  128. package/src/image_generate.ts +0 -102
  129. package/src/index.ts +0 -47
  130. package/src/info/crypto.ts +0 -79
  131. package/src/info/time.ts +0 -83
  132. package/src/info/weather.ts +0 -134
  133. package/src/search/perplexity.ts +0 -129
  134. package/src/shared/html.ts +0 -87
  135. package/src/shared/http.ts +0 -40
  136. package/src/shared/s3.ts +0 -157
  137. package/src/shared/storage.ts +0 -83
  138. package/src/vn/gold.ts +0 -192
  139. package/src/vn/lottery.ts +0 -129
  140. package/src/web_fetch.ts +0 -80
  141. package/src/web_search.ts +0 -92
package/dist/index.cjs ADDED
@@ -0,0 +1,1098 @@
1
+ 'use strict';
2
+
3
+ var effect = require('effect');
4
+ var promises = require('fs/promises');
5
+ var path = require('path');
6
+ var cheerio = require('cheerio');
7
+ var agent = require('@tinyweb_dev/agent-framework-agent');
8
+
9
+ // src/shared/storage.ts
10
+ var FileError = class extends Error {
11
+ constructor(message, cause) {
12
+ super(message);
13
+ this.cause = cause;
14
+ this.name = "FileError";
15
+ }
16
+ _tag = "FileError";
17
+ };
18
+ var toBytes = (data) => typeof data === "string" ? new TextEncoder().encode(data) : data;
19
+ var makeMemoryStore = () => {
20
+ const map = /* @__PURE__ */ new Map();
21
+ return {
22
+ read: (key) => effect.Effect.suspend(() => {
23
+ const value = map.get(key);
24
+ if (value === void 0) return effect.Effect.fail(new FileError(`Key not found: ${key}`));
25
+ return effect.Effect.succeed(value);
26
+ }),
27
+ write: (key, data) => effect.Effect.sync(() => {
28
+ map.set(key, toBytes(data));
29
+ return {};
30
+ }),
31
+ list: (prefix) => effect.Effect.sync(() => Array.from(map.keys()).filter((k) => k.startsWith(prefix)))
32
+ };
33
+ };
34
+ var resolveSafe = (basePath, key) => {
35
+ const target = path.join(basePath, key);
36
+ const rel = path.relative(basePath, target);
37
+ if (rel.startsWith("..") || rel.startsWith(path.sep) || rel.includes(`..${path.sep}`)) {
38
+ throw new FileError(`Path traversal blocked: ${key}`);
39
+ }
40
+ return target;
41
+ };
42
+ var makeLocalFS = (basePath) => {
43
+ return {
44
+ read: (key) => effect.Effect.tryPromise({
45
+ try: async () => {
46
+ const path = resolveSafe(basePath, key);
47
+ const buf = await promises.readFile(path);
48
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
49
+ },
50
+ catch: (cause) => new FileError(`Read failed: ${key}`, cause)
51
+ }),
52
+ write: (key, data) => effect.Effect.tryPromise({
53
+ try: async () => {
54
+ const path$1 = resolveSafe(basePath, key);
55
+ await promises.mkdir(path.dirname(path$1), { recursive: true });
56
+ await promises.writeFile(path$1, toBytes(data));
57
+ return { url: `file://${path$1}` };
58
+ },
59
+ catch: (cause) => new FileError(`Write failed: ${key}`, cause)
60
+ }),
61
+ list: (prefix) => effect.Effect.tryPromise({
62
+ try: async () => {
63
+ const dir = resolveSafe(basePath, prefix);
64
+ const entries = await promises.readdir(dir, { recursive: true, withFileTypes: true });
65
+ return entries.filter((e) => e.isFile()).map((e) => path.join(path.relative(basePath, path.join(e.parentPath, e.name))));
66
+ },
67
+ catch: (cause) => new FileError(`List failed: ${prefix}`, cause)
68
+ })
69
+ };
70
+ };
71
+ var joinKey = (prefix, key) => {
72
+ if (!prefix) return key;
73
+ return prefix.endsWith("/") ? `${prefix}${key}` : `${prefix}/${key}`;
74
+ };
75
+ var stripPrefix = (prefix, key) => {
76
+ if (!prefix) return key;
77
+ const full = prefix.endsWith("/") ? prefix : `${prefix}/`;
78
+ return key.startsWith(full) ? key.slice(full.length) : key;
79
+ };
80
+ var toBytes2 = (data) => typeof data === "string" ? new TextEncoder().encode(data) : data;
81
+ async function streamToBytes(body) {
82
+ if (body instanceof Uint8Array) return body;
83
+ if (typeof body === "string") return new TextEncoder().encode(body);
84
+ if (body && typeof body.transformToByteArray === "function") {
85
+ return body.transformToByteArray();
86
+ }
87
+ if (body && typeof body.getReader === "function") {
88
+ const reader = body.getReader();
89
+ const chunks = [];
90
+ let total = 0;
91
+ for (; ; ) {
92
+ const { done, value } = await reader.read();
93
+ if (done) break;
94
+ if (value) {
95
+ chunks.push(value);
96
+ total += value.byteLength;
97
+ }
98
+ }
99
+ const out = new Uint8Array(total);
100
+ let offset = 0;
101
+ for (const chunk of chunks) {
102
+ out.set(chunk, offset);
103
+ offset += chunk.byteLength;
104
+ }
105
+ return out;
106
+ }
107
+ throw new FileError("Unsupported S3 GetObject body type");
108
+ }
109
+ var makeS3Store = (client, options) => {
110
+ const { bucket, prefix, publicUrl, commands } = options;
111
+ return {
112
+ read: (key) => effect.Effect.tryPromise({
113
+ try: async () => {
114
+ const cmd = new commands.GetObjectCommand({ Bucket: bucket, Key: joinKey(prefix, key) });
115
+ const response = await client.send(cmd);
116
+ if (!response.Body) throw new FileError(`Empty S3 object body: ${key}`);
117
+ return await streamToBytes(response.Body);
118
+ },
119
+ catch: (cause) => new FileError(`S3 read failed: ${key}`, cause)
120
+ }),
121
+ write: (key, data) => effect.Effect.tryPromise({
122
+ try: async () => {
123
+ const fullKey = joinKey(prefix, key);
124
+ const cmd = new commands.PutObjectCommand({
125
+ Bucket: bucket,
126
+ Key: fullKey,
127
+ Body: toBytes2(data)
128
+ });
129
+ await client.send(cmd);
130
+ return publicUrl ? { url: publicUrl(fullKey) } : {};
131
+ },
132
+ catch: (cause) => new FileError(`S3 write failed: ${key}`, cause)
133
+ }),
134
+ list: (prefixArg) => effect.Effect.tryPromise({
135
+ try: async () => {
136
+ const cmd = new commands.ListObjectsV2Command({
137
+ Bucket: bucket,
138
+ Prefix: joinKey(prefix, prefixArg)
139
+ });
140
+ const response = await client.send(cmd);
141
+ const items = response.Contents ?? [];
142
+ return items.map((item) => item.Key).filter((k) => typeof k === "string").map((k) => stripPrefix(prefix, k));
143
+ },
144
+ catch: (cause) => new FileError(`S3 list failed: ${prefixArg}`, cause)
145
+ })
146
+ };
147
+ };
148
+
149
+ // src/shared/http.ts
150
+ var HttpToolError = class extends Error {
151
+ constructor(message, status, body) {
152
+ super(message);
153
+ this.status = status;
154
+ this.body = body;
155
+ this.name = "HttpToolError";
156
+ }
157
+ _tag = "HttpToolError";
158
+ };
159
+ var ensureOk = async (res, label) => {
160
+ if (res.ok) return res;
161
+ const body = await res.text().catch(() => "");
162
+ throw new HttpToolError(`${label} ${res.status}: ${body.slice(0, 500)}`, res.status, body);
163
+ };
164
+ var fetchJson = async (url, init) => {
165
+ const res = await fetch(url, init);
166
+ await ensureOk(res, `GET ${url}`);
167
+ return await res.json();
168
+ };
169
+ var postJson = async (url, body, init) => {
170
+ const headers = new Headers(init?.headers);
171
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
172
+ const res = await fetch(url, { method: "POST", body: JSON.stringify(body), ...init, headers });
173
+ await ensureOk(res, `POST ${url}`);
174
+ return await res.json();
175
+ };
176
+ var fetchText = async (url, init) => {
177
+ const res = await fetch(url, init);
178
+ await ensureOk(res, `GET ${url}`);
179
+ return res.text();
180
+ };
181
+ var fetchBytes = async (url, init) => {
182
+ const res = await fetch(url, init);
183
+ await ensureOk(res, `GET ${url}`);
184
+ const buf = await res.arrayBuffer();
185
+ return new Uint8Array(buf);
186
+ };
187
+ var loadHtml = (html) => cheerio.load(html);
188
+ var firstMatchText = ($, selectors) => {
189
+ for (const sel of selectors) {
190
+ const el = $(sel).first();
191
+ if (el.length === 0) continue;
192
+ const txt = el.text().trim();
193
+ if (txt) return txt;
194
+ }
195
+ return void 0;
196
+ };
197
+ var collectText = ($, selector) => {
198
+ const out = [];
199
+ for (const node of $(selector).toArray()) {
200
+ const txt = $(node).text().trim();
201
+ if (txt) out.push(txt);
202
+ }
203
+ return out;
204
+ };
205
+ var parseVndNumber = (s) => {
206
+ const cleaned = s.replace(/[^\d.,-]/g, "").trim();
207
+ if (!cleaned) return NaN;
208
+ const hasDot = cleaned.includes(".");
209
+ const hasComma = cleaned.includes(",");
210
+ if (hasDot && hasComma) {
211
+ const lastDot = cleaned.lastIndexOf(".");
212
+ const lastComma = cleaned.lastIndexOf(",");
213
+ const decimalIdx = Math.max(lastDot, lastComma);
214
+ const intPart = cleaned.slice(0, decimalIdx).replace(/[.,]/g, "");
215
+ const decPart = cleaned.slice(decimalIdx + 1);
216
+ return Number(`${intPart}.${decPart}`);
217
+ }
218
+ if (hasDot) {
219
+ const parts = cleaned.split(".");
220
+ const allGroupsThree = parts.slice(1).every((p) => p.length === 3);
221
+ if (allGroupsThree) return Number(parts.join(""));
222
+ return Number(cleaned);
223
+ }
224
+ if (hasComma) {
225
+ const parts = cleaned.split(",");
226
+ const allGroupsThree = parts.slice(1).every((p) => p.length === 3);
227
+ if (allGroupsThree) return Number(parts.join(""));
228
+ return Number(cleaned.replace(",", "."));
229
+ }
230
+ return Number(cleaned);
231
+ };
232
+ var ResultItem = effect.Schema.Struct({
233
+ title: effect.Schema.String,
234
+ url: effect.Schema.String,
235
+ snippet: effect.Schema.String
236
+ });
237
+ var Parameters = effect.Schema.Struct({
238
+ query: effect.Schema.String,
239
+ limit: effect.Schema.optional(effect.Schema.Number)
240
+ });
241
+ var Success = effect.Schema.Struct({
242
+ results: effect.Schema.Array(ResultItem)
243
+ });
244
+ var searchTavily = async (apiKey, input) => {
245
+ const data = await postJson("https://api.tavily.com/search", {
246
+ api_key: apiKey,
247
+ query: input.query,
248
+ max_results: input.limit ?? 5
249
+ });
250
+ return data.results.map((r) => ({ title: r.title, url: r.url, snippet: r.content ?? "" }));
251
+ };
252
+ var searchBrave = async (apiKey, input) => {
253
+ const params = new URLSearchParams({ q: input.query, count: String(input.limit ?? 5) });
254
+ const data = await fetchJson(`https://api.search.brave.com/res/v1/web/search?${params}`, {
255
+ headers: { "X-Subscription-Token": apiKey, accept: "application/json" }
256
+ });
257
+ const items = data.web?.results ?? [];
258
+ return items.map((r) => ({ title: r.title, url: r.url, snippet: r.description ?? "" }));
259
+ };
260
+ var searchExa = async (apiKey, input) => {
261
+ const data = await postJson(
262
+ "https://api.exa.ai/search",
263
+ { query: input.query, numResults: input.limit ?? 5, contents: { text: true } },
264
+ { headers: { "x-api-key": apiKey } }
265
+ );
266
+ return data.results.map((r) => ({ title: r.title ?? r.url, url: r.url, snippet: (r.text ?? "").slice(0, 500) }));
267
+ };
268
+ var searchSerper = async (apiKey, input) => {
269
+ const data = await postJson(
270
+ "https://google.serper.dev/search",
271
+ { q: input.query, num: input.limit ?? 5 },
272
+ { headers: { "X-API-KEY": apiKey } }
273
+ );
274
+ return (data.organic ?? []).map((r) => ({ title: r.title, url: r.link, snippet: r.snippet ?? "" }));
275
+ };
276
+ var dispatch = (provider, apiKey, input) => {
277
+ if (provider === "tavily") return searchTavily(apiKey, input);
278
+ if (provider === "brave") return searchBrave(apiKey, input);
279
+ if (provider === "exa") return searchExa(apiKey, input);
280
+ if (provider === "serper") return searchSerper(apiKey, input);
281
+ throw new Error(`Unknown web_search provider: ${provider}`);
282
+ };
283
+ var webSearch = (config) => agent.defineTool({
284
+ name: config.name ?? "web_search",
285
+ description: config.description ?? "Search the web and return a list of {title, url, snippet} results.",
286
+ parameters: Parameters,
287
+ success: Success,
288
+ execute: async (input) => ({ results: await dispatch(config.provider, config.apiKey, input) })
289
+ });
290
+ var Parameters2 = effect.Schema.Struct({
291
+ url: effect.Schema.String
292
+ });
293
+ var Success2 = effect.Schema.Struct({
294
+ url: effect.Schema.String,
295
+ title: effect.Schema.optional(effect.Schema.String),
296
+ content: effect.Schema.String
297
+ });
298
+ var HTML_ENTITIES = {
299
+ "&": "&",
300
+ "&lt;": "<",
301
+ "&gt;": ">",
302
+ "&quot;": '"',
303
+ "&#39;": "'",
304
+ "&apos;": "'",
305
+ "&nbsp;": " "
306
+ };
307
+ 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)));
308
+ var extractTitle = (html) => {
309
+ const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
310
+ if (!match) return void 0;
311
+ return decodeEntities(match[1] ?? "").trim() || void 0;
312
+ };
313
+ var htmlToText = (html, maxLength) => {
314
+ 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, " ");
315
+ const collapsed = decodeEntities(stripped).replace(/[ \t]+/g, " ").replace(/\n\s*\n+/g, "\n\n").trim();
316
+ if (collapsed.length <= maxLength) return collapsed;
317
+ return collapsed.slice(0, maxLength) + "\n... [truncated]";
318
+ };
319
+ var webFetch = (config = {}) => {
320
+ const timeout = config.timeoutMs ?? 15e3;
321
+ const maxLength = config.maxLength ?? 1e5;
322
+ const ua = config.userAgent ?? "tinyweb-agent/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
323
+ return agent.defineTool({
324
+ name: config.name ?? "web_fetch",
325
+ description: config.description ?? "Fetch a URL and return its title plus extracted plain-text content.",
326
+ parameters: Parameters2,
327
+ success: Success2,
328
+ execute: async (input) => {
329
+ const controller = new AbortController();
330
+ const timer = setTimeout(() => controller.abort(), timeout);
331
+ const res = await fetch(input.url, {
332
+ headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
333
+ signal: controller.signal
334
+ }).finally(() => clearTimeout(timer));
335
+ if (!res.ok) throw new Error(`Fetch ${input.url} failed: HTTP ${res.status}`);
336
+ const contentType = res.headers.get("content-type") ?? "";
337
+ const raw = await res.text();
338
+ if (contentType.includes("html")) {
339
+ return { url: input.url, title: extractTitle(raw), content: htmlToText(raw, maxLength) };
340
+ }
341
+ return { url: input.url, content: raw.length > maxLength ? raw.slice(0, maxLength) + "\n... [truncated]" : raw };
342
+ }
343
+ });
344
+ };
345
+ var Parameters3 = effect.Schema.Struct({
346
+ prompt: effect.Schema.String,
347
+ size: effect.Schema.optional(effect.Schema.String),
348
+ n: effect.Schema.optional(effect.Schema.Number)
349
+ });
350
+ var Success3 = effect.Schema.Struct({
351
+ url: effect.Schema.String,
352
+ storageKey: effect.Schema.optional(effect.Schema.String)
353
+ });
354
+ var generateOpenAI = async (apiKey, model, input) => {
355
+ const data = await postJson(
356
+ "https://api.openai.com/v1/images/generations",
357
+ { model, prompt: input.prompt, size: input.size, n: input.n ?? 1 },
358
+ { headers: { authorization: `Bearer ${apiKey}` } }
359
+ );
360
+ const first = data.data[0];
361
+ if (!first) throw new Error("OpenAI returned no image data");
362
+ if (first.url) return first.url;
363
+ if (first.b64_json) return `data:image/png;base64,${first.b64_json}`;
364
+ throw new Error("OpenAI image response missing url and b64_json");
365
+ };
366
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
367
+ var generateReplicate = async (apiKey, model, input) => {
368
+ const initial = await postJson(
369
+ "https://api.replicate.com/v1/predictions",
370
+ { version: model, input: { prompt: input.prompt } },
371
+ { headers: { authorization: `Token ${apiKey}` } }
372
+ );
373
+ let current = initial;
374
+ const pollUrl = initial.urls?.get;
375
+ if (!pollUrl) throw new Error("Replicate prediction missing poll url");
376
+ const deadline = Date.now() + 12e4;
377
+ while (current.status !== "succeeded" && current.status !== "failed" && current.status !== "canceled") {
378
+ if (Date.now() > deadline) throw new Error("Replicate timeout after 120s");
379
+ await sleep(1500);
380
+ const r = await fetch(pollUrl, { headers: { authorization: `Token ${apiKey}` } });
381
+ if (!r.ok) throw new Error(`Replicate poll failed: HTTP ${r.status}`);
382
+ current = await r.json();
383
+ }
384
+ if (current.status !== "succeeded") throw new Error(`Replicate ${current.status}: ${current.error ?? "unknown"}`);
385
+ const output = current.output;
386
+ if (Array.isArray(output)) return output[0] ?? "";
387
+ return output ?? "";
388
+ };
389
+ var generate = (provider, apiKey, model, input) => {
390
+ if (provider === "openai") return generateOpenAI(apiKey, model, input);
391
+ if (provider === "replicate") return generateReplicate(apiKey, model, input);
392
+ throw new Error(`Unknown image_generate provider: ${provider}`);
393
+ };
394
+ var defaultModel = (provider) => {
395
+ if (provider === "openai") return "gpt-image-1";
396
+ return "black-forest-labs/flux-schnell";
397
+ };
398
+ var imageGenerate = (config) => agent.defineTool({
399
+ name: config.name ?? "image_generate",
400
+ description: config.description ?? "Generate an image from a prompt. Returns the image URL (and storage key if storage configured).",
401
+ parameters: Parameters3,
402
+ success: Success3,
403
+ execute: async (input) => {
404
+ const model = config.model ?? defaultModel(config.provider);
405
+ const url = await generate(config.provider, config.apiKey, model, input);
406
+ if (!config.storage || url.startsWith("data:")) {
407
+ return { url, storageKey: void 0 };
408
+ }
409
+ const bytes = await fetchBytes(url);
410
+ const ext = url.includes(".webp") ? "webp" : url.includes(".jpg") || url.includes(".jpeg") ? "jpg" : "png";
411
+ const key = `${config.storagePrefix ?? "images"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
412
+ const result = await effect.Effect.runPromise(config.storage.write(key, bytes));
413
+ return { url: result.url ?? url, storageKey: key };
414
+ }
415
+ });
416
+ var Parameters4 = effect.Schema.Struct({
417
+ imageUrl: effect.Schema.String,
418
+ question: effect.Schema.optional(effect.Schema.String)
419
+ });
420
+ var Success4 = effect.Schema.Struct({
421
+ description: effect.Schema.String
422
+ });
423
+ var imageDescribe = (config) => agent.defineTool({
424
+ name: config.name ?? "image_describe",
425
+ description: config.description ?? "Describe the contents of an image. Pass a question to ask something specific.",
426
+ parameters: Parameters4,
427
+ success: Success4,
428
+ execute: async (input) => {
429
+ const baseURL = (config.baseURL ?? "https://api.openai.com/v1").replace(/\/$/, "");
430
+ const model = config.model ?? "gpt-4o-mini";
431
+ const question = input.question ?? "Describe this image in 2-3 sentences.";
432
+ const messages = [
433
+ {
434
+ role: "user",
435
+ content: [
436
+ { type: "text", text: question },
437
+ { type: "image_url", image_url: { url: input.imageUrl } }
438
+ ]
439
+ }
440
+ ];
441
+ const data = await postJson(
442
+ `${baseURL}/chat/completions`,
443
+ { model, messages, max_tokens: 600 },
444
+ { headers: { authorization: `Bearer ${config.apiKey}` } }
445
+ );
446
+ const text = data.choices[0]?.message?.content ?? "";
447
+ return { description: text.trim() };
448
+ }
449
+ });
450
+ var Parameters5 = effect.Schema.Struct({
451
+ imageUrl: effect.Schema.String,
452
+ prompt: effect.Schema.String,
453
+ maskUrl: effect.Schema.optional(effect.Schema.String),
454
+ size: effect.Schema.optional(effect.Schema.String)
455
+ });
456
+ var Success5 = effect.Schema.Struct({
457
+ url: effect.Schema.String,
458
+ storageKey: effect.Schema.optional(effect.Schema.String)
459
+ });
460
+ var toBlob = async (url) => {
461
+ const bytes = await fetchBytes(url);
462
+ return new Blob([bytes]);
463
+ };
464
+ var imageEdit = (config) => agent.defineTool({
465
+ name: config.name ?? "image_edit",
466
+ description: config.description ?? "Edit an image using a text prompt (and optional mask). Returns the edited image URL.",
467
+ parameters: Parameters5,
468
+ success: Success5,
469
+ execute: async (input) => {
470
+ const form = new FormData();
471
+ form.append("model", config.model ?? "gpt-image-1");
472
+ form.append("prompt", input.prompt);
473
+ const imageBlob = await toBlob(input.imageUrl);
474
+ form.append("image", imageBlob, "image.png");
475
+ if (input.maskUrl) {
476
+ const maskBlob = await toBlob(input.maskUrl);
477
+ form.append("mask", maskBlob, "mask.png");
478
+ }
479
+ if (input.size) form.append("size", input.size);
480
+ const res = await fetch("https://api.openai.com/v1/images/edits", {
481
+ method: "POST",
482
+ headers: { authorization: `Bearer ${config.apiKey}` },
483
+ body: form
484
+ });
485
+ if (!res.ok) {
486
+ const body = await res.text().catch(() => "");
487
+ throw new Error(`OpenAI image edit failed: HTTP ${res.status}: ${body.slice(0, 500)}`);
488
+ }
489
+ const data = await res.json();
490
+ const first = data.data[0];
491
+ if (!first) throw new Error("OpenAI returned no image data");
492
+ const url = first.url ?? (first.b64_json ? `data:image/png;base64,${first.b64_json}` : "");
493
+ if (!url) throw new Error("OpenAI image_edit response missing url and b64_json");
494
+ if (!config.storage || url.startsWith("data:")) {
495
+ return { url, storageKey: void 0 };
496
+ }
497
+ const bytes = await fetchBytes(url);
498
+ const key = `${config.storagePrefix ?? "images"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`;
499
+ const written = await effect.Effect.runPromise(config.storage.write(key, bytes));
500
+ return { url: written.url ?? url, storageKey: key };
501
+ }
502
+ });
503
+ var Parameters6 = effect.Schema.Struct({
504
+ key: effect.Schema.String
505
+ });
506
+ var Success6 = effect.Schema.Struct({
507
+ content: effect.Schema.String,
508
+ bytes: effect.Schema.Number
509
+ });
510
+ var fileRead = (config) => agent.defineTool({
511
+ name: config.name ?? "file_read",
512
+ description: config.description ?? "Read a file from configured storage by key. Returns UTF-8 text content.",
513
+ parameters: Parameters6,
514
+ success: Success6,
515
+ execute: async (input) => {
516
+ const bytes = await effect.Effect.runPromise(config.storage.read(input.key));
517
+ const content = new TextDecoder("utf-8").decode(bytes);
518
+ return { content, bytes: bytes.byteLength };
519
+ }
520
+ });
521
+ var Parameters7 = effect.Schema.Struct({
522
+ key: effect.Schema.String,
523
+ content: effect.Schema.String
524
+ });
525
+ var Success7 = effect.Schema.Struct({
526
+ key: effect.Schema.String,
527
+ url: effect.Schema.optional(effect.Schema.String),
528
+ bytes: effect.Schema.Number
529
+ });
530
+ var fileWrite = (config) => agent.defineTool({
531
+ name: config.name ?? "file_write",
532
+ description: config.description ?? "Write a UTF-8 text file to configured storage under the given key.",
533
+ parameters: Parameters7,
534
+ success: Success7,
535
+ execute: async (input) => {
536
+ const bytes = new TextEncoder().encode(input.content);
537
+ const result = await effect.Effect.runPromise(config.storage.write(input.key, bytes));
538
+ return { key: input.key, url: result.url, bytes: bytes.byteLength };
539
+ }
540
+ });
541
+ var Parameters8 = effect.Schema.Struct({
542
+ response: effect.Schema.String
543
+ });
544
+ var Success8 = effect.Schema.Struct({
545
+ response: effect.Schema.String
546
+ });
547
+ var DEFAULT_DESCRIPTION = [
548
+ "Deliver a plain textual response to the user when no other tool is appropriate for the current turn.",
549
+ 'Use this as a fallback to satisfy the "every assistant turn must call at least one tool" constraint',
550
+ "whenever you only need to send textual content \u2014 both short conversational replies and long-form",
551
+ "structured output \u2014 that does not finish the task. Typical use cases:",
552
+ "- Clarifying remarks, brainstorming, short answers, status updates",
553
+ "- Presenting a plan or proposed approach before implementation",
554
+ "- Explaining code, concepts, errors, or trade-offs in depth",
555
+ "- Delivering a long-form report, summary, analysis, or review",
556
+ "- Showing diagrams, tables, or formatted markdown content to the user",
557
+ "",
558
+ "STRICT OUTPUT RULES (must follow exactly):",
559
+ "- Put the ENTIRE message inside the `response` argument of this tool call.",
560
+ "- Do NOT emit ANY free-form assistant text outside the tool call in the same turn. The assistant",
561
+ " text channel MUST be empty when you call `display_response`.",
562
+ '- This means: no preamble, no recap, no "Here is\u2026", no trailing remark before or after the tool',
563
+ " call. Everything the user should see goes inside `response`.",
564
+ "- After you call display_response, STOP. Wait for the user's next message before doing anything",
565
+ " else. Do NOT keep calling tools or generate another turn on your own.",
566
+ "- The `response` must be non-empty.",
567
+ "- Prefer NOT calling display_response if a domain tool (search, weather, etc.) is the right answer.",
568
+ "",
569
+ "Parameters:",
570
+ "- response: (required) The textual message to deliver to the user. Markdown is supported.",
571
+ "",
572
+ "Example (correct \u2014 assistant text is empty, all content is inside the tool call):",
573
+ '{ "response": "I looked at the two options and I think Option A is cleaner because it avoids the extra cache lookup." }'
574
+ ].join("\n");
575
+ var displayResponse = (config = {}) => agent.defineTool({
576
+ name: config.name ?? "display_response",
577
+ description: config.description ?? DEFAULT_DESCRIPTION,
578
+ parameters: Parameters8,
579
+ success: Success8,
580
+ execute: async (input) => ({ response: input.response })
581
+ });
582
+ var Parameters9 = effect.Schema.Struct({
583
+ timezone: effect.Schema.optional(effect.Schema.String),
584
+ locale: effect.Schema.optional(effect.Schema.String)
585
+ });
586
+ var Success9 = effect.Schema.Struct({
587
+ timezone: effect.Schema.String,
588
+ locale: effect.Schema.String,
589
+ iso: effect.Schema.String,
590
+ formatted: effect.Schema.String,
591
+ weekday: effect.Schema.String,
592
+ unix_ms: effect.Schema.Number
593
+ });
594
+ 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"];
595
+ var vietnameseWeekday = (date, timezone) => {
596
+ const fmt = new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short" });
597
+ const short = fmt.format(date);
598
+ const map = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
599
+ const idx = map[short] ?? 0;
600
+ return VN_WEEKDAYS[idx];
601
+ };
602
+ var timeNow = (config = {}) => {
603
+ const defaultTz = config.defaultTimezone ?? "Asia/Ho_Chi_Minh";
604
+ const defaultLocale = config.defaultLocale ?? "vi-VN";
605
+ return agent.defineTool({
606
+ name: config.name ?? "time_now",
607
+ 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.`,
608
+ parameters: Parameters9,
609
+ success: Success9,
610
+ execute: async (input) => {
611
+ const tz = input.timezone ?? defaultTz;
612
+ const locale = input.locale ?? defaultLocale;
613
+ const now = /* @__PURE__ */ new Date();
614
+ const dtf = new Intl.DateTimeFormat(locale, {
615
+ timeZone: tz,
616
+ dateStyle: "full",
617
+ timeStyle: "long"
618
+ });
619
+ const formatted = dtf.format(now);
620
+ const weekday = locale.startsWith("vi") ? vietnameseWeekday(now, tz) : new Intl.DateTimeFormat(locale, { timeZone: tz, weekday: "long" }).format(now);
621
+ return {
622
+ timezone: tz,
623
+ locale,
624
+ iso: now.toISOString(),
625
+ formatted,
626
+ weekday,
627
+ unix_ms: now.getTime()
628
+ };
629
+ }
630
+ });
631
+ };
632
+ var Parameters10 = effect.Schema.Struct({
633
+ location: effect.Schema.optional(effect.Schema.String),
634
+ lang: effect.Schema.optional(effect.Schema.String)
635
+ });
636
+ var Success10 = effect.Schema.Struct({
637
+ location: effect.Schema.String,
638
+ region: effect.Schema.optional(effect.Schema.String),
639
+ country: effect.Schema.optional(effect.Schema.String),
640
+ observed_at: effect.Schema.String,
641
+ temperature_c: effect.Schema.Number,
642
+ feels_like_c: effect.Schema.Number,
643
+ humidity_percent: effect.Schema.Number,
644
+ wind_kmh: effect.Schema.Number,
645
+ wind_direction: effect.Schema.String,
646
+ condition: effect.Schema.String,
647
+ uv_index: effect.Schema.optional(effect.Schema.Number),
648
+ visibility_km: effect.Schema.optional(effect.Schema.Number),
649
+ pressure_mb: effect.Schema.optional(effect.Schema.Number),
650
+ source: effect.Schema.Literal("wttr.in")
651
+ });
652
+ var firstValue = (xs) => xs && xs.length > 0 ? xs[0].value : void 0;
653
+ var num = (s, fallback = 0) => {
654
+ if (!s) return fallback;
655
+ const n = Number(s);
656
+ return Number.isFinite(n) ? n : fallback;
657
+ };
658
+ var weather = (config = {}) => {
659
+ const defaultLocation = config.defaultLocation ?? "Hanoi";
660
+ const defaultLang = config.defaultLang ?? "vi";
661
+ const ua = config.userAgent ?? "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
662
+ const timeout = config.timeoutMs ?? 15e3;
663
+ return agent.defineTool({
664
+ name: config.name ?? "weather",
665
+ 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.`,
666
+ parameters: Parameters10,
667
+ success: Success10,
668
+ execute: async (input) => {
669
+ const loc = (input.location ?? defaultLocation).trim();
670
+ const lang = input.lang ?? defaultLang;
671
+ const url = `https://wttr.in/${encodeURIComponent(loc)}?format=j1&lang=${encodeURIComponent(lang)}`;
672
+ const controller = new AbortController();
673
+ const timer = setTimeout(() => controller.abort(), timeout);
674
+ const data = await fetchJson(url, {
675
+ headers: { "user-agent": ua, accept: "application/json" },
676
+ signal: controller.signal
677
+ }).finally(() => clearTimeout(timer));
678
+ const cur = data.current_condition?.[0];
679
+ if (!cur) throw new Error(`wttr.in returned no current_condition for "${loc}"`);
680
+ const area = data.nearest_area?.[0];
681
+ const condition = (lang === "vi" ? firstValue(cur.lang_vi) : void 0) ?? firstValue(cur.weatherDesc) ?? "N/A";
682
+ const visibility = num(cur.visibilityKm ?? cur.visibility, NaN);
683
+ const pressure = num(cur.pressure, NaN);
684
+ const uv = num(cur.uvIndex, NaN);
685
+ return {
686
+ location: firstValue(area?.areaName) ?? loc,
687
+ region: firstValue(area?.region),
688
+ country: firstValue(area?.country),
689
+ observed_at: cur.localObsDateTime ?? cur.observation_time ?? (/* @__PURE__ */ new Date()).toISOString(),
690
+ temperature_c: num(cur.temp_C),
691
+ feels_like_c: num(cur.FeelsLikeC),
692
+ humidity_percent: num(cur.humidity),
693
+ wind_kmh: num(cur.windspeedKmph),
694
+ wind_direction: cur.winddir16Point ?? "",
695
+ condition,
696
+ uv_index: Number.isFinite(uv) ? uv : void 0,
697
+ visibility_km: Number.isFinite(visibility) ? visibility : void 0,
698
+ pressure_mb: Number.isFinite(pressure) ? pressure : void 0,
699
+ source: "wttr.in"
700
+ };
701
+ }
702
+ });
703
+ };
704
+ var Parameters11 = effect.Schema.Struct({
705
+ symbols: effect.Schema.Array(effect.Schema.String),
706
+ quote: effect.Schema.optional(effect.Schema.String)
707
+ });
708
+ var PriceItem = effect.Schema.Struct({
709
+ symbol: effect.Schema.String,
710
+ quote: effect.Schema.String,
711
+ price: effect.Schema.Number,
712
+ pair: effect.Schema.String
713
+ });
714
+ var Success11 = effect.Schema.Struct({
715
+ prices: effect.Schema.Array(PriceItem),
716
+ observed_at: effect.Schema.String,
717
+ source: effect.Schema.Literal("binance")
718
+ });
719
+ var upper = (s) => s.trim().toUpperCase();
720
+ var cryptoPrice = (config = {}) => {
721
+ const defaultQuote = upper(config.quote ?? "USDT");
722
+ const timeout = config.timeoutMs ?? 1e4;
723
+ return agent.defineTool({
724
+ name: config.name ?? "crypto_price",
725
+ 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.`,
726
+ parameters: Parameters11,
727
+ success: Success11,
728
+ execute: async (input) => {
729
+ const quote = upper(input.quote ?? defaultQuote);
730
+ const pairs = input.symbols.map((s) => `${upper(s)}${quote}`);
731
+ if (pairs.length === 0) throw new Error("symbols must be a non-empty array");
732
+ const arrayParam = encodeURIComponent(JSON.stringify(pairs));
733
+ const url = `https://api.binance.com/api/v3/ticker/price?symbols=${arrayParam}`;
734
+ const controller = new AbortController();
735
+ const timer = setTimeout(() => controller.abort(), timeout);
736
+ const data = await fetchJson(url, { signal: controller.signal }).finally(
737
+ () => clearTimeout(timer)
738
+ );
739
+ const prices = data.map((t) => ({
740
+ symbol: t.symbol.endsWith(quote) ? t.symbol.slice(0, -quote.length) : t.symbol,
741
+ quote,
742
+ price: Number(t.price),
743
+ pair: t.symbol
744
+ }));
745
+ return { prices, observed_at: (/* @__PURE__ */ new Date()).toISOString(), source: "binance" };
746
+ }
747
+ });
748
+ };
749
+ var VendorChoice = effect.Schema.Union([effect.Schema.Literal("btmc"), effect.Schema.Literal("btmh"), effect.Schema.Literal("all")]);
750
+ var Parameters12 = effect.Schema.Struct({
751
+ vendor: effect.Schema.optional(VendorChoice)
752
+ });
753
+ var PriceItem2 = effect.Schema.Struct({
754
+ vendor: effect.Schema.String,
755
+ vendor_full: effect.Schema.String,
756
+ product: effect.Schema.String,
757
+ buy_vnd: effect.Schema.Number,
758
+ sell_vnd: effect.Schema.Number,
759
+ unit: effect.Schema.String,
760
+ source_url: effect.Schema.String
761
+ });
762
+ var Success12 = effect.Schema.Struct({
763
+ items: effect.Schema.Array(PriceItem2),
764
+ observed_at: effect.Schema.String,
765
+ warnings: effect.Schema.Array(effect.Schema.String)
766
+ });
767
+ var UA = "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
768
+ var BTMC_URL = "https://btmc.vn/";
769
+ var BTMH_URL = "https://baotinmanhhai.vn/vi/bang-gia-vang";
770
+ var parseBtmc = (html) => {
771
+ const items = [];
772
+ const warnings = [];
773
+ const startIdx = html.indexOf("NH\u1EAAN TR\xD2N TR\u01A0N B\u1EA2O T\xCDN");
774
+ if (startIdx < 0) {
775
+ warnings.push("BTMC: product label not found \u2014 layout may have changed");
776
+ return { items, warnings };
777
+ }
778
+ const endTag = html.indexOf("C\u1EADp nh\u1EADt l\xFAc", startIdx);
779
+ const region = endTag > 0 ? html.slice(startIdx, endTag) : html.slice(startIdx, startIdx + 4e3);
780
+ const matches = Array.from(region.matchAll(/<b[^>]*>\s*(\d{4,6})\s*<\/b>/g));
781
+ if (matches.length < 2) {
782
+ warnings.push("BTMC: couldn't find two <b> price tags after product label");
783
+ return { items, warnings };
784
+ }
785
+ const buyRaw = Number(matches[0][1]);
786
+ const sellRaw = Number(matches[1][1]);
787
+ if (!Number.isFinite(buyRaw) || !Number.isFinite(sellRaw)) {
788
+ warnings.push("BTMC: price numbers not parseable");
789
+ return { items, warnings };
790
+ }
791
+ items.push({
792
+ vendor: "btmc",
793
+ vendor_full: "B\u1EA3o T\xEDn Minh Ch\xE2u",
794
+ product: "Nh\u1EABn tr\xF2n tr\u01A1n 24K",
795
+ buy_vnd: buyRaw * 1e3,
796
+ sell_vnd: sellRaw * 1e3,
797
+ unit: "VND/ch\u1EC9",
798
+ source_url: BTMC_URL
799
+ });
800
+ return { items, warnings };
801
+ };
802
+ var parseBtmh = (html) => {
803
+ const items = [];
804
+ const warnings = [];
805
+ const $ = loadHtml(html);
806
+ let buyVnd = NaN;
807
+ let sellVnd = NaN;
808
+ let productLabel = "Nh\u1EABn Tr\xF2n \xE9p v\u1EC9 24K";
809
+ for (const tr of $("tr").toArray()) {
810
+ const rowText = $(tr).text();
811
+ if (!rowText.includes("Nh\u1EABn Tr\xF2n \xE9p v\u1EC9") && !rowText.includes("Nh\u1EABn Tr\xF2n")) continue;
812
+ if (!rowText.includes("24K") && !rowText.includes("999.9")) continue;
813
+ const cells = $(tr).find("td, th").toArray();
814
+ if (cells.length < 2) continue;
815
+ productLabel = $(cells[0]).text().trim().replace(/\s+/g, " ").slice(0, 80);
816
+ const numbers = [];
817
+ for (let i = 1; i < cells.length; i++) {
818
+ const raw = $(cells[i]).text().trim();
819
+ const n = parseVndNumber(raw);
820
+ if (Number.isFinite(n) && n > 1e6) numbers.push(n);
821
+ if (numbers.length === 2) break;
822
+ }
823
+ if (numbers.length === 2) {
824
+ sellVnd = numbers[0];
825
+ buyVnd = numbers[1];
826
+ break;
827
+ }
828
+ }
829
+ if (!Number.isFinite(buyVnd) || !Number.isFinite(sellVnd)) {
830
+ warnings.push("BTMH: couldn't locate Nh\u1EABn Tr\xF2n 24K row with two prices");
831
+ return { items, warnings };
832
+ }
833
+ items.push({
834
+ vendor: "btmh",
835
+ vendor_full: "B\u1EA3o T\xEDn M\u1EA1nh H\u1EA3i",
836
+ product: productLabel,
837
+ buy_vnd: buyVnd,
838
+ sell_vnd: sellVnd,
839
+ unit: "VND/ch\u1EC9",
840
+ source_url: BTMH_URL
841
+ });
842
+ return { items, warnings };
843
+ };
844
+ var fetchSafe = async (url, ua, timeoutMs, label) => {
845
+ const controller = new AbortController();
846
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
847
+ return fetchText(url, {
848
+ headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
849
+ signal: controller.signal
850
+ }).then((html) => ({ html, error: null, label })).catch((err) => ({
851
+ html: "",
852
+ error: err instanceof Error ? err.message : String(err),
853
+ label
854
+ })).finally(() => clearTimeout(timer));
855
+ };
856
+ var vnGoldPrice = (config = {}) => {
857
+ const timeout = config.timeoutMs ?? 15e3;
858
+ const ua = config.userAgent ?? UA;
859
+ return agent.defineTool({
860
+ name: config.name ?? "vn_gold_price",
861
+ 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.",
862
+ parameters: Parameters12,
863
+ success: Success12,
864
+ execute: async (input) => {
865
+ const vendor = input.vendor ?? "all";
866
+ const items = [];
867
+ const warnings = [];
868
+ const tasks = [];
869
+ if (vendor === "btmc" || vendor === "all") tasks.push(fetchSafe(BTMC_URL, ua, timeout, "btmc"));
870
+ if (vendor === "btmh" || vendor === "all") tasks.push(fetchSafe(BTMH_URL, ua, timeout, "btmh"));
871
+ const results = await Promise.all(tasks);
872
+ for (const r of results) {
873
+ if (r.error) {
874
+ warnings.push(`${r.label}: fetch failed (${r.error})`);
875
+ continue;
876
+ }
877
+ const parsed = r.label === "btmc" ? parseBtmc(r.html) : parseBtmh(r.html);
878
+ items.push(...parsed.items);
879
+ warnings.push(...parsed.warnings);
880
+ }
881
+ return { items, observed_at: (/* @__PURE__ */ new Date()).toISOString(), warnings };
882
+ }
883
+ });
884
+ };
885
+ var RegionChoice = effect.Schema.Union([
886
+ effect.Schema.Literal("north"),
887
+ effect.Schema.Literal("central"),
888
+ effect.Schema.Literal("south")
889
+ ]);
890
+ var Parameters13 = effect.Schema.Struct({
891
+ region: effect.Schema.optional(RegionChoice)
892
+ });
893
+ var Prize = effect.Schema.Struct({
894
+ name: effect.Schema.String,
895
+ numbers: effect.Schema.Array(effect.Schema.String)
896
+ });
897
+ var Success13 = effect.Schema.Struct({
898
+ region: effect.Schema.String,
899
+ region_label: effect.Schema.String,
900
+ date: effect.Schema.optional(effect.Schema.String),
901
+ prizes: effect.Schema.Array(Prize),
902
+ source_url: effect.Schema.String,
903
+ warnings: effect.Schema.Array(effect.Schema.String)
904
+ });
905
+ var UA2 = "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)";
906
+ var REGION_URLS = {
907
+ north: { url: "https://xoso.com.vn/xo-so-mien-bac/xsmb-p1.html", label: "Mi\u1EC1n B\u1EAFc", code: "XSMB" },
908
+ central: { url: "https://xoso.com.vn/xo-so-mien-trung/xsmt-p1.html", label: "Mi\u1EC1n Trung", code: "XSMT" },
909
+ south: { url: "https://xoso.com.vn/xo-so-mien-nam/xsmn-p1.html", label: "Mi\u1EC1n Nam", code: "XSMN" }
910
+ };
911
+ var parseDate = (sectionText, code) => {
912
+ const re = new RegExp(`${code}\\s+(\\d{2}/\\d{2}/\\d{4})`);
913
+ const m = re.exec(sectionText);
914
+ return m ? m[1] : void 0;
915
+ };
916
+ var vnLottery = (config = {}) => {
917
+ const timeout = config.timeoutMs ?? 15e3;
918
+ const ua = config.userAgent ?? UA2;
919
+ return agent.defineTool({
920
+ name: config.name ?? "vn_lottery",
921
+ 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.",
922
+ parameters: Parameters13,
923
+ success: Success13,
924
+ execute: async (input) => {
925
+ const region = input.region ?? "north";
926
+ const conf = REGION_URLS[region];
927
+ const warnings = [];
928
+ const controller = new AbortController();
929
+ const timer = setTimeout(() => controller.abort(), timeout);
930
+ const html = await fetchText(conf.url, {
931
+ headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
932
+ signal: controller.signal
933
+ }).finally(() => clearTimeout(timer));
934
+ const $ = loadHtml(html);
935
+ const section = $("section[id^='kqngay_']").first();
936
+ if (section.length === 0) {
937
+ warnings.push(`xoso.com.vn: no section[id^='kqngay_'] for ${conf.code}`);
938
+ return {
939
+ region,
940
+ region_label: conf.label,
941
+ prizes: [],
942
+ source_url: conf.url,
943
+ warnings
944
+ };
945
+ }
946
+ const sectionText = section.text();
947
+ const date = parseDate(sectionText, conf.code);
948
+ const prizes = [];
949
+ const rows = section.find("table.table-result tbody tr").toArray();
950
+ for (const tr of rows) {
951
+ const cells = $(tr).find("td").toArray();
952
+ if (cells.length < 2) continue;
953
+ const prizeName = $(cells[0]).text().trim();
954
+ if (!prizeName) continue;
955
+ const numberSpans = $(tr).find("span").toArray();
956
+ const numbers = [];
957
+ for (const sp of numberSpans) {
958
+ const v = $(sp).text().trim();
959
+ if (/^\d{2,6}$/.test(v)) numbers.push(v);
960
+ }
961
+ if (numbers.length === 0) continue;
962
+ prizes.push({ name: prizeName, numbers });
963
+ }
964
+ if (prizes.length === 0) warnings.push(`xoso.com.vn: no prize rows extracted for ${conf.code}`);
965
+ return {
966
+ region,
967
+ region_label: conf.label,
968
+ date,
969
+ prizes,
970
+ source_url: conf.url,
971
+ warnings
972
+ };
973
+ }
974
+ });
975
+ };
976
+ var Parameters14 = effect.Schema.Struct({
977
+ query: effect.Schema.String
978
+ });
979
+ var Citation = effect.Schema.Struct({
980
+ url: effect.Schema.String,
981
+ title: effect.Schema.optional(effect.Schema.String)
982
+ });
983
+ var Success14 = effect.Schema.Struct({
984
+ query: effect.Schema.String,
985
+ answer: effect.Schema.String,
986
+ citations: effect.Schema.Array(Citation),
987
+ model: effect.Schema.String
988
+ });
989
+ var normaliseCitations = (data) => {
990
+ if (data.search_results && data.search_results.length > 0) {
991
+ 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 });
992
+ }
993
+ if (data.citations && data.citations.length > 0) {
994
+ return data.citations.filter((u) => typeof u === "string").map((u) => ({ url: u }));
995
+ }
996
+ return [];
997
+ };
998
+ var perplexitySearch = (config) => {
999
+ if (!config.apiKey) throw new Error("perplexitySearch: apiKey is required");
1000
+ const model = config.model ?? "sonar";
1001
+ const baseURL = config.baseURL ?? "https://api.perplexity.ai";
1002
+ const timeout = config.timeoutMs ?? 3e4;
1003
+ const temperature = config.temperature ?? 0.2;
1004
+ const maxTokens = config.maxTokens ?? 800;
1005
+ const sys = config.systemPrompt ?? "Answer the user's question accurately and concisely. Cite sources by URL. Use the user's language.";
1006
+ return agent.defineTool({
1007
+ name: config.name ?? "perplexity_search",
1008
+ 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.",
1009
+ parameters: Parameters14,
1010
+ success: Success14,
1011
+ execute: async (input) => {
1012
+ const url = `${baseURL.replace(/\/+$/, "")}/chat/completions`;
1013
+ const controller = new AbortController();
1014
+ const timer = setTimeout(() => controller.abort(), timeout);
1015
+ const body = {
1016
+ model,
1017
+ messages: [
1018
+ { role: "system", content: sys },
1019
+ { role: "user", content: input.query }
1020
+ ],
1021
+ temperature,
1022
+ max_tokens: maxTokens
1023
+ };
1024
+ const data = await postJson(url, body, {
1025
+ headers: { authorization: `Bearer ${config.apiKey}` },
1026
+ signal: controller.signal
1027
+ }).finally(() => clearTimeout(timer));
1028
+ const answer = data.choices?.[0]?.message?.content ?? "";
1029
+ if (!answer) throw new Error("perplexitySearch: empty answer from Sonar API");
1030
+ return {
1031
+ query: input.query,
1032
+ answer,
1033
+ citations: normaliseCitations(data),
1034
+ model: data.model ?? model
1035
+ };
1036
+ }
1037
+ });
1038
+ };
1039
+
1040
+ // src/builtins.ts
1041
+ var isEnabled = (v, defaultOn) => {
1042
+ if (v === void 0) return defaultOn;
1043
+ if (v === false) return false;
1044
+ return true;
1045
+ };
1046
+ var cfgOrEmpty = (v) => {
1047
+ if (typeof v === "object" && v !== null) return v;
1048
+ return {};
1049
+ };
1050
+ var builtinTools = (config = {}) => {
1051
+ const tools = {};
1052
+ if (isEnabled(config.time, true)) tools.time_now = timeNow(cfgOrEmpty(config.time));
1053
+ if (isEnabled(config.displayResponse, true))
1054
+ tools.display_response = displayResponse(cfgOrEmpty(config.displayResponse));
1055
+ if (isEnabled(config.weather, false)) tools.weather = weather(cfgOrEmpty(config.weather));
1056
+ if (isEnabled(config.crypto, false)) tools.crypto_price = cryptoPrice(cfgOrEmpty(config.crypto));
1057
+ if (isEnabled(config.vnGold, false)) tools.vn_gold_price = vnGoldPrice(cfgOrEmpty(config.vnGold));
1058
+ if (isEnabled(config.vnLottery, false)) tools.vn_lottery = vnLottery(cfgOrEmpty(config.vnLottery));
1059
+ if (isEnabled(config.webFetch, false)) tools.web_fetch = webFetch(cfgOrEmpty(config.webFetch));
1060
+ if (config.perplexity) tools.perplexity_search = perplexitySearch(config.perplexity);
1061
+ if (config.webSearch) tools.web_search = webSearch(config.webSearch);
1062
+ return tools;
1063
+ };
1064
+
1065
+ // src/index.ts
1066
+ var VERSION = "0.0.1";
1067
+
1068
+ exports.FileError = FileError;
1069
+ exports.HttpToolError = HttpToolError;
1070
+ exports.VERSION = VERSION;
1071
+ exports.builtinTools = builtinTools;
1072
+ exports.collectText = collectText;
1073
+ exports.cryptoPrice = cryptoPrice;
1074
+ exports.displayResponse = displayResponse;
1075
+ exports.fetchBytes = fetchBytes;
1076
+ exports.fetchJson = fetchJson;
1077
+ exports.fetchText = fetchText;
1078
+ exports.fileRead = fileRead;
1079
+ exports.fileWrite = fileWrite;
1080
+ exports.firstMatchText = firstMatchText;
1081
+ exports.imageDescribe = imageDescribe;
1082
+ exports.imageEdit = imageEdit;
1083
+ exports.imageGenerate = imageGenerate;
1084
+ exports.loadHtml = loadHtml;
1085
+ exports.makeLocalFS = makeLocalFS;
1086
+ exports.makeMemoryStore = makeMemoryStore;
1087
+ exports.makeS3Store = makeS3Store;
1088
+ exports.parseVndNumber = parseVndNumber;
1089
+ exports.perplexitySearch = perplexitySearch;
1090
+ exports.postJson = postJson;
1091
+ exports.timeNow = timeNow;
1092
+ exports.vnGoldPrice = vnGoldPrice;
1093
+ exports.vnLottery = vnLottery;
1094
+ exports.weather = weather;
1095
+ exports.webFetch = webFetch;
1096
+ exports.webSearch = webSearch;
1097
+ //# sourceMappingURL=index.cjs.map
1098
+ //# sourceMappingURL=index.cjs.map