@tinyweb_dev/agent-framework-tool 0.1.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/LICENSE +21 -0
- package/README.md +114 -0
- package/package.json +50 -0
- package/src/builtins.ts +78 -0
- package/src/display_response.ts +79 -0
- package/src/file_read.ts +31 -0
- package/src/file_write.ts +33 -0
- package/src/image_describe.ts +58 -0
- package/src/image_edit.ts +74 -0
- package/src/image_generate.ts +102 -0
- package/src/index.ts +47 -0
- package/src/info/crypto.ts +79 -0
- package/src/info/time.ts +83 -0
- package/src/info/weather.ts +134 -0
- package/src/search/perplexity.ts +129 -0
- package/src/shared/html.ts +87 -0
- package/src/shared/http.ts +40 -0
- package/src/shared/s3.ts +157 -0
- package/src/shared/storage.ts +83 -0
- package/src/vn/gold.ts +192 -0
- package/src/vn/lottery.ts +129 -0
- package/src/web_fetch.ts +80 -0
- package/src/web_search.ts +92 -0
package/src/shared/s3.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// S3 FileStorage adapter — duck-typed against @aws-sdk/client-s3.
|
|
2
|
+
//
|
|
3
|
+
// Consumer installs the peer dep:
|
|
4
|
+
// bun add @aws-sdk/client-s3
|
|
5
|
+
//
|
|
6
|
+
// Usage:
|
|
7
|
+
// import { S3Client } from "@aws-sdk/client-s3"
|
|
8
|
+
// const s3 = new S3Client({ region: "us-east-1" })
|
|
9
|
+
// const storage = makeS3Store(s3, { bucket: "my-bucket", prefix: "agent/" })
|
|
10
|
+
|
|
11
|
+
import { Effect } from "effect"
|
|
12
|
+
import { FileError, type FileStorage, type WriteResult } from "./storage"
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// AWS SDK v3 minimal duck types — we only need send() with a command
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
export type S3CommandLike = {
|
|
19
|
+
readonly input: Record<string, unknown>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type S3ClientLike = {
|
|
23
|
+
send<R>(command: S3CommandLike): Promise<R>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Constructors for the three commands we use. Consumers will pass the real
|
|
27
|
+
// AWS SDK classes (GetObjectCommand / PutObjectCommand / ListObjectsV2Command)
|
|
28
|
+
// or compatible factories.
|
|
29
|
+
export type S3CommandFactory<TInput extends Record<string, unknown>> = new (
|
|
30
|
+
input: TInput,
|
|
31
|
+
) => S3CommandLike
|
|
32
|
+
|
|
33
|
+
export type S3Commands = {
|
|
34
|
+
readonly GetObjectCommand: S3CommandFactory<{ Bucket: string; Key: string }>
|
|
35
|
+
readonly PutObjectCommand: S3CommandFactory<{
|
|
36
|
+
Bucket: string
|
|
37
|
+
Key: string
|
|
38
|
+
Body: Uint8Array | string
|
|
39
|
+
ContentType?: string
|
|
40
|
+
}>
|
|
41
|
+
readonly ListObjectsV2Command: S3CommandFactory<{ Bucket: string; Prefix?: string }>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// Public options
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
export type S3StoreOptions = {
|
|
49
|
+
readonly bucket: string
|
|
50
|
+
/** Optional prefix prepended to every key (e.g. "agent/"). No leading slash. */
|
|
51
|
+
readonly prefix?: string
|
|
52
|
+
/** Public URL builder (e.g. CloudFront / virtual-hosted-style). Default omits url. */
|
|
53
|
+
readonly publicUrl?: (key: string) => string
|
|
54
|
+
/** AWS SDK command constructors (defaults read from globals if available). */
|
|
55
|
+
readonly commands: S3Commands
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
// Helpers
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
const joinKey = (prefix: string | undefined, key: string): string => {
|
|
63
|
+
if (!prefix) return key
|
|
64
|
+
return prefix.endsWith("/") ? `${prefix}${key}` : `${prefix}/${key}`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const stripPrefix = (prefix: string | undefined, key: string): string => {
|
|
68
|
+
if (!prefix) return key
|
|
69
|
+
const full = prefix.endsWith("/") ? prefix : `${prefix}/`
|
|
70
|
+
return key.startsWith(full) ? key.slice(full.length) : key
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const toBytes = (data: Uint8Array | string): Uint8Array =>
|
|
74
|
+
typeof data === "string" ? new TextEncoder().encode(data) : data
|
|
75
|
+
|
|
76
|
+
async function streamToBytes(body: unknown): Promise<Uint8Array> {
|
|
77
|
+
if (body instanceof Uint8Array) return body
|
|
78
|
+
if (typeof body === "string") return new TextEncoder().encode(body)
|
|
79
|
+
if (body && typeof (body as { transformToByteArray?: () => Promise<Uint8Array> }).transformToByteArray === "function") {
|
|
80
|
+
return (body as { transformToByteArray: () => Promise<Uint8Array> }).transformToByteArray()
|
|
81
|
+
}
|
|
82
|
+
// Web ReadableStream
|
|
83
|
+
if (body && typeof (body as ReadableStream).getReader === "function") {
|
|
84
|
+
const reader = (body as ReadableStream<Uint8Array>).getReader()
|
|
85
|
+
const chunks: Uint8Array[] = []
|
|
86
|
+
let total = 0
|
|
87
|
+
for (;;) {
|
|
88
|
+
const { done, value } = await reader.read()
|
|
89
|
+
if (done) break
|
|
90
|
+
if (value) {
|
|
91
|
+
chunks.push(value)
|
|
92
|
+
total += value.byteLength
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const out = new Uint8Array(total)
|
|
96
|
+
let offset = 0
|
|
97
|
+
for (const chunk of chunks) {
|
|
98
|
+
out.set(chunk, offset)
|
|
99
|
+
offset += chunk.byteLength
|
|
100
|
+
}
|
|
101
|
+
return out
|
|
102
|
+
}
|
|
103
|
+
throw new FileError("Unsupported S3 GetObject body type")
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
// makeS3Store
|
|
108
|
+
// ---------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
export const makeS3Store = (client: S3ClientLike, options: S3StoreOptions): FileStorage => {
|
|
111
|
+
const { bucket, prefix, publicUrl, commands } = options
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
read: (key) =>
|
|
115
|
+
Effect.tryPromise({
|
|
116
|
+
try: async () => {
|
|
117
|
+
const cmd = new commands.GetObjectCommand({ Bucket: bucket, Key: joinKey(prefix, key) })
|
|
118
|
+
const response = await client.send<{ Body?: unknown }>(cmd)
|
|
119
|
+
if (!response.Body) throw new FileError(`Empty S3 object body: ${key}`)
|
|
120
|
+
return await streamToBytes(response.Body)
|
|
121
|
+
},
|
|
122
|
+
catch: (cause) => new FileError(`S3 read failed: ${key}`, cause),
|
|
123
|
+
}),
|
|
124
|
+
|
|
125
|
+
write: (key, data) =>
|
|
126
|
+
Effect.tryPromise<WriteResult, FileError>({
|
|
127
|
+
try: async () => {
|
|
128
|
+
const fullKey = joinKey(prefix, key)
|
|
129
|
+
const cmd = new commands.PutObjectCommand({
|
|
130
|
+
Bucket: bucket,
|
|
131
|
+
Key: fullKey,
|
|
132
|
+
Body: toBytes(data),
|
|
133
|
+
})
|
|
134
|
+
await client.send(cmd)
|
|
135
|
+
return publicUrl ? { url: publicUrl(fullKey) } : {}
|
|
136
|
+
},
|
|
137
|
+
catch: (cause) => new FileError(`S3 write failed: ${key}`, cause),
|
|
138
|
+
}),
|
|
139
|
+
|
|
140
|
+
list: (prefixArg) =>
|
|
141
|
+
Effect.tryPromise({
|
|
142
|
+
try: async () => {
|
|
143
|
+
const cmd = new commands.ListObjectsV2Command({
|
|
144
|
+
Bucket: bucket,
|
|
145
|
+
Prefix: joinKey(prefix, prefixArg),
|
|
146
|
+
})
|
|
147
|
+
const response = await client.send<{ Contents?: { Key?: string }[] }>(cmd)
|
|
148
|
+
const items = response.Contents ?? []
|
|
149
|
+
return items
|
|
150
|
+
.map((item) => item.Key)
|
|
151
|
+
.filter((k): k is string => typeof k === "string")
|
|
152
|
+
.map((k) => stripPrefix(prefix, k))
|
|
153
|
+
},
|
|
154
|
+
catch: (cause) => new FileError(`S3 list failed: ${prefixArg}`, cause),
|
|
155
|
+
}),
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { Effect } from "effect"
|
|
2
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"
|
|
3
|
+
import { dirname, join, relative, sep } from "node:path"
|
|
4
|
+
|
|
5
|
+
export class FileError extends Error {
|
|
6
|
+
readonly _tag = "FileError"
|
|
7
|
+
constructor(message: string, override readonly cause?: unknown) {
|
|
8
|
+
super(message)
|
|
9
|
+
this.name = "FileError"
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type WriteResult = { url?: string }
|
|
14
|
+
|
|
15
|
+
export interface FileStorage {
|
|
16
|
+
read(key: string): Effect.Effect<Uint8Array, FileError>
|
|
17
|
+
write(key: string, data: Uint8Array | string): Effect.Effect<WriteResult, FileError>
|
|
18
|
+
list(prefix: string): Effect.Effect<string[], FileError>
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const toBytes = (data: Uint8Array | string): Uint8Array => (typeof data === "string" ? new TextEncoder().encode(data) : data)
|
|
22
|
+
|
|
23
|
+
export const makeMemoryStore = (): FileStorage => {
|
|
24
|
+
const map = new Map<string, Uint8Array>()
|
|
25
|
+
return {
|
|
26
|
+
read: (key) =>
|
|
27
|
+
Effect.suspend(() => {
|
|
28
|
+
const value = map.get(key)
|
|
29
|
+
if (value === undefined) return Effect.fail(new FileError(`Key not found: ${key}`))
|
|
30
|
+
return Effect.succeed(value)
|
|
31
|
+
}),
|
|
32
|
+
write: (key, data) =>
|
|
33
|
+
Effect.sync(() => {
|
|
34
|
+
map.set(key, toBytes(data))
|
|
35
|
+
return {}
|
|
36
|
+
}),
|
|
37
|
+
list: (prefix) => Effect.sync(() => Array.from(map.keys()).filter((k) => k.startsWith(prefix))),
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const resolveSafe = (basePath: string, key: string): string => {
|
|
42
|
+
const target = join(basePath, key)
|
|
43
|
+
const rel = relative(basePath, target)
|
|
44
|
+
if (rel.startsWith("..") || rel.startsWith(sep) || rel.includes(`..${sep}`)) {
|
|
45
|
+
throw new FileError(`Path traversal blocked: ${key}`)
|
|
46
|
+
}
|
|
47
|
+
return target
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const makeLocalFS = (basePath: string): FileStorage => {
|
|
51
|
+
return {
|
|
52
|
+
read: (key) =>
|
|
53
|
+
Effect.tryPromise({
|
|
54
|
+
try: async () => {
|
|
55
|
+
const path = resolveSafe(basePath, key)
|
|
56
|
+
const buf = await readFile(path)
|
|
57
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
|
|
58
|
+
},
|
|
59
|
+
catch: (cause) => new FileError(`Read failed: ${key}`, cause),
|
|
60
|
+
}),
|
|
61
|
+
write: (key, data) =>
|
|
62
|
+
Effect.tryPromise({
|
|
63
|
+
try: async () => {
|
|
64
|
+
const path = resolveSafe(basePath, key)
|
|
65
|
+
await mkdir(dirname(path), { recursive: true })
|
|
66
|
+
await writeFile(path, toBytes(data))
|
|
67
|
+
return { url: `file://${path}` }
|
|
68
|
+
},
|
|
69
|
+
catch: (cause) => new FileError(`Write failed: ${key}`, cause),
|
|
70
|
+
}),
|
|
71
|
+
list: (prefix) =>
|
|
72
|
+
Effect.tryPromise({
|
|
73
|
+
try: async () => {
|
|
74
|
+
const dir = resolveSafe(basePath, prefix)
|
|
75
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true })
|
|
76
|
+
return entries
|
|
77
|
+
.filter((e) => e.isFile())
|
|
78
|
+
.map((e) => join(relative(basePath, join(e.parentPath, e.name))))
|
|
79
|
+
},
|
|
80
|
+
catch: (cause) => new FileError(`List failed: ${prefix}`, cause),
|
|
81
|
+
}),
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/vn/gold.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `vn_gold_price` — current Vietnamese gold prices (Bảo Tín Minh Châu + Bảo
|
|
3
|
+
* Tín Mạnh Hải).
|
|
4
|
+
*
|
|
5
|
+
* Adapted from `packages/tool/references/daily-info/giavang` which scrapes two
|
|
6
|
+
* sites with bash + Perl regex. Ports the same logic to cheerio + JS regex.
|
|
7
|
+
*
|
|
8
|
+
* Caveats:
|
|
9
|
+
* • These are pure HTML scrapes — when either site changes layout, this tool
|
|
10
|
+
* will return `items: []` plus a `warnings` array explaining what broke.
|
|
11
|
+
* Tell the LLM to inform the user instead of hallucinating a number.
|
|
12
|
+
* • Prices are inherently quote-of-the-minute and only "tham khảo" (advisory).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
16
|
+
import { Schema } from "effect"
|
|
17
|
+
import { fetchText } from "../shared/http"
|
|
18
|
+
import { loadHtml, parseVndNumber } from "../shared/html"
|
|
19
|
+
|
|
20
|
+
export type VnGoldConfig = {
|
|
21
|
+
readonly timeoutMs?: number
|
|
22
|
+
readonly userAgent?: string
|
|
23
|
+
readonly name?: string
|
|
24
|
+
readonly description?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const VendorChoice = Schema.Union([Schema.Literal("btmc"), Schema.Literal("btmh"), Schema.Literal("all")])
|
|
28
|
+
|
|
29
|
+
const Parameters = Schema.Struct({
|
|
30
|
+
vendor: Schema.optional(VendorChoice),
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
const PriceItem = Schema.Struct({
|
|
34
|
+
vendor: Schema.String,
|
|
35
|
+
vendor_full: Schema.String,
|
|
36
|
+
product: Schema.String,
|
|
37
|
+
buy_vnd: Schema.Number,
|
|
38
|
+
sell_vnd: Schema.Number,
|
|
39
|
+
unit: Schema.String,
|
|
40
|
+
source_url: Schema.String,
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
const Success = Schema.Struct({
|
|
44
|
+
items: Schema.Array(PriceItem),
|
|
45
|
+
observed_at: Schema.String,
|
|
46
|
+
warnings: Schema.Array(Schema.String),
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const UA =
|
|
50
|
+
"tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)"
|
|
51
|
+
|
|
52
|
+
const BTMC_URL = "https://btmc.vn/"
|
|
53
|
+
const BTMH_URL = "https://baotinmanhhai.vn/vi/bang-gia-vang"
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* BTMC homepage has a product row labelled "NHẪN TRÒN TRƠN BẢO TÍN MINH CHÂU".
|
|
57
|
+
* Buy + sell are in `<b>` tags rendered as 4–6 digit thousands (eg "12500"
|
|
58
|
+
* meaning 12,500,000 VND/chỉ since the unit is `.000đ/chỉ` in the original
|
|
59
|
+
* bash script). We multiply by 1000 to land on plain VND.
|
|
60
|
+
*/
|
|
61
|
+
const parseBtmc = (html: string): { items: typeof Success.Type.items[number][]; warnings: string[] } => {
|
|
62
|
+
const items: typeof Success.Type.items[number][] = []
|
|
63
|
+
const warnings: string[] = []
|
|
64
|
+
// Bash heuristic: between the product label and "Cập nhật lúc" tag, grab the
|
|
65
|
+
// first two <b>…</b> blocks containing 4–6 digit numbers.
|
|
66
|
+
const startIdx = html.indexOf("NHẪN TRÒN TRƠN BẢO TÍN")
|
|
67
|
+
if (startIdx < 0) {
|
|
68
|
+
warnings.push("BTMC: product label not found — layout may have changed")
|
|
69
|
+
return { items, warnings }
|
|
70
|
+
}
|
|
71
|
+
const endTag = html.indexOf("Cập nhật lúc", startIdx)
|
|
72
|
+
const region = endTag > 0 ? html.slice(startIdx, endTag) : html.slice(startIdx, startIdx + 4000)
|
|
73
|
+
const matches = Array.from(region.matchAll(/<b[^>]*>\s*(\d{4,6})\s*<\/b>/g))
|
|
74
|
+
if (matches.length < 2) {
|
|
75
|
+
warnings.push("BTMC: couldn't find two <b> price tags after product label")
|
|
76
|
+
return { items, warnings }
|
|
77
|
+
}
|
|
78
|
+
const buyRaw = Number(matches[0]![1])
|
|
79
|
+
const sellRaw = Number(matches[1]![1])
|
|
80
|
+
if (!Number.isFinite(buyRaw) || !Number.isFinite(sellRaw)) {
|
|
81
|
+
warnings.push("BTMC: price numbers not parseable")
|
|
82
|
+
return { items, warnings }
|
|
83
|
+
}
|
|
84
|
+
items.push({
|
|
85
|
+
vendor: "btmc",
|
|
86
|
+
vendor_full: "Bảo Tín Minh Châu",
|
|
87
|
+
product: "Nhẫn tròn trơn 24K",
|
|
88
|
+
buy_vnd: buyRaw * 1000,
|
|
89
|
+
sell_vnd: sellRaw * 1000,
|
|
90
|
+
unit: "VND/chỉ",
|
|
91
|
+
source_url: BTMC_URL,
|
|
92
|
+
})
|
|
93
|
+
return { items, warnings }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* BTMH bảng-giá page lists products in a table. The reference bash script
|
|
98
|
+
* targeted "Nhẫn Tròn ép vỉ (Kim Gia Bảo) 24K (999.9)" with the surrounding
|
|
99
|
+
* span price markup. We replicate that with cheerio: find the row whose first
|
|
100
|
+
* cell contains "Nhẫn Tròn ép vỉ" and pull the two price spans.
|
|
101
|
+
*/
|
|
102
|
+
const parseBtmh = (html: string): { items: typeof Success.Type.items[number][]; warnings: string[] } => {
|
|
103
|
+
const items: typeof Success.Type.items[number][] = []
|
|
104
|
+
const warnings: string[] = []
|
|
105
|
+
const $ = loadHtml(html)
|
|
106
|
+
let buyVnd = NaN
|
|
107
|
+
let sellVnd = NaN
|
|
108
|
+
let productLabel = "Nhẫn Tròn ép vỉ 24K"
|
|
109
|
+
for (const tr of $("tr").toArray()) {
|
|
110
|
+
const rowText = $(tr).text()
|
|
111
|
+
if (!rowText.includes("Nhẫn Tròn ép vỉ") && !rowText.includes("Nhẫn Tròn")) continue
|
|
112
|
+
if (!rowText.includes("24K") && !rowText.includes("999.9")) continue
|
|
113
|
+
const cells = $(tr).find("td, th").toArray()
|
|
114
|
+
if (cells.length < 2) continue
|
|
115
|
+
productLabel = $(cells[0]!).text().trim().replace(/\s+/g, " ").slice(0, 80)
|
|
116
|
+
const numbers: number[] = []
|
|
117
|
+
for (let i = 1; i < cells.length; i++) {
|
|
118
|
+
const raw = $(cells[i]!).text().trim()
|
|
119
|
+
const n = parseVndNumber(raw)
|
|
120
|
+
if (Number.isFinite(n) && n > 1_000_000) numbers.push(n)
|
|
121
|
+
if (numbers.length === 2) break
|
|
122
|
+
}
|
|
123
|
+
if (numbers.length === 2) {
|
|
124
|
+
// BTMH table order in the bash script was sell, buy. Replicate.
|
|
125
|
+
sellVnd = numbers[0]!
|
|
126
|
+
buyVnd = numbers[1]!
|
|
127
|
+
break
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (!Number.isFinite(buyVnd) || !Number.isFinite(sellVnd)) {
|
|
131
|
+
warnings.push("BTMH: couldn't locate Nhẫn Tròn 24K row with two prices")
|
|
132
|
+
return { items, warnings }
|
|
133
|
+
}
|
|
134
|
+
items.push({
|
|
135
|
+
vendor: "btmh",
|
|
136
|
+
vendor_full: "Bảo Tín Mạnh Hải",
|
|
137
|
+
product: productLabel,
|
|
138
|
+
buy_vnd: buyVnd,
|
|
139
|
+
sell_vnd: sellVnd,
|
|
140
|
+
unit: "VND/chỉ",
|
|
141
|
+
source_url: BTMH_URL,
|
|
142
|
+
})
|
|
143
|
+
return { items, warnings }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const fetchSafe = async (url: string, ua: string, timeoutMs: number, label: string) => {
|
|
147
|
+
const controller = new AbortController()
|
|
148
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
149
|
+
return fetchText(url, {
|
|
150
|
+
headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
|
|
151
|
+
signal: controller.signal,
|
|
152
|
+
})
|
|
153
|
+
.then((html) => ({ html, error: null as string | null, label }))
|
|
154
|
+
.catch((err: unknown) => ({
|
|
155
|
+
html: "",
|
|
156
|
+
error: err instanceof Error ? err.message : String(err),
|
|
157
|
+
label,
|
|
158
|
+
}))
|
|
159
|
+
.finally(() => clearTimeout(timer))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export const vnGoldPrice = (config: VnGoldConfig = {}) => {
|
|
163
|
+
const timeout = config.timeoutMs ?? 15000
|
|
164
|
+
const ua = config.userAgent ?? UA
|
|
165
|
+
return defineTool({
|
|
166
|
+
name: config.name ?? "vn_gold_price",
|
|
167
|
+
description:
|
|
168
|
+
config.description ??
|
|
169
|
+
"Lấy giá vàng nhẫn tròn 24K Việt Nam (Bảo Tín Minh Châu / Bảo Tín Mạnh Hải). Giá tham khảo, có thể lệch so với thực tế.",
|
|
170
|
+
parameters: Parameters,
|
|
171
|
+
success: Success,
|
|
172
|
+
execute: async (input) => {
|
|
173
|
+
const vendor = input.vendor ?? "all"
|
|
174
|
+
const items: typeof Success.Type.items[number][] = []
|
|
175
|
+
const warnings: string[] = []
|
|
176
|
+
const tasks: Promise<{ html: string; error: string | null; label: string }>[] = []
|
|
177
|
+
if (vendor === "btmc" || vendor === "all") tasks.push(fetchSafe(BTMC_URL, ua, timeout, "btmc"))
|
|
178
|
+
if (vendor === "btmh" || vendor === "all") tasks.push(fetchSafe(BTMH_URL, ua, timeout, "btmh"))
|
|
179
|
+
const results = await Promise.all(tasks)
|
|
180
|
+
for (const r of results) {
|
|
181
|
+
if (r.error) {
|
|
182
|
+
warnings.push(`${r.label}: fetch failed (${r.error})`)
|
|
183
|
+
continue
|
|
184
|
+
}
|
|
185
|
+
const parsed = r.label === "btmc" ? parseBtmc(r.html) : parseBtmh(r.html)
|
|
186
|
+
items.push(...parsed.items)
|
|
187
|
+
warnings.push(...parsed.warnings)
|
|
188
|
+
}
|
|
189
|
+
return { items, observed_at: new Date().toISOString(), warnings }
|
|
190
|
+
},
|
|
191
|
+
})
|
|
192
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `vn_lottery` — Vietnamese lottery results (Xổ Số Miền Bắc/Trung/Nam).
|
|
3
|
+
*
|
|
4
|
+
* Adapted from `packages/tool/references/daily-info/xoso` which scrapes
|
|
5
|
+
* `xoso.com.vn` with bash + Perl regex. Replicates the prize-row extraction
|
|
6
|
+
* with cheerio for the latest day's results.
|
|
7
|
+
*
|
|
8
|
+
* Returns `prizes: []` plus a `warnings` array if the page layout has shifted
|
|
9
|
+
* — never throws.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
13
|
+
import { Schema } from "effect"
|
|
14
|
+
import { fetchText } from "../shared/http"
|
|
15
|
+
import { loadHtml } from "../shared/html"
|
|
16
|
+
|
|
17
|
+
export type VnLotteryConfig = {
|
|
18
|
+
readonly timeoutMs?: number
|
|
19
|
+
readonly userAgent?: string
|
|
20
|
+
readonly name?: string
|
|
21
|
+
readonly description?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const RegionChoice = Schema.Union([
|
|
25
|
+
Schema.Literal("north"),
|
|
26
|
+
Schema.Literal("central"),
|
|
27
|
+
Schema.Literal("south"),
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
const Parameters = Schema.Struct({
|
|
31
|
+
region: Schema.optional(RegionChoice),
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const Prize = Schema.Struct({
|
|
35
|
+
name: Schema.String,
|
|
36
|
+
numbers: Schema.Array(Schema.String),
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
const Success = Schema.Struct({
|
|
40
|
+
region: Schema.String,
|
|
41
|
+
region_label: Schema.String,
|
|
42
|
+
date: Schema.optional(Schema.String),
|
|
43
|
+
prizes: Schema.Array(Prize),
|
|
44
|
+
source_url: Schema.String,
|
|
45
|
+
warnings: Schema.Array(Schema.String),
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const UA =
|
|
49
|
+
"tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)"
|
|
50
|
+
|
|
51
|
+
const REGION_URLS: Record<Schema.Schema.Type<typeof RegionChoice>, { url: string; label: string; code: string }> = {
|
|
52
|
+
north: { url: "https://xoso.com.vn/xo-so-mien-bac/xsmb-p1.html", label: "Miền Bắc", code: "XSMB" },
|
|
53
|
+
central: { url: "https://xoso.com.vn/xo-so-mien-trung/xsmt-p1.html", label: "Miền Trung", code: "XSMT" },
|
|
54
|
+
south: { url: "https://xoso.com.vn/xo-so-mien-nam/xsmn-p1.html", label: "Miền Nam", code: "XSMN" },
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const parseDate = (sectionText: string, code: string): string | undefined => {
|
|
58
|
+
// Bash regex was `${code}\s+(\d{2}/\d{2}/\d{4})`. Same here.
|
|
59
|
+
const re = new RegExp(`${code}\\s+(\\d{2}/\\d{2}/\\d{4})`)
|
|
60
|
+
const m = re.exec(sectionText)
|
|
61
|
+
return m ? m[1] : undefined
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const vnLottery = (config: VnLotteryConfig = {}) => {
|
|
65
|
+
const timeout = config.timeoutMs ?? 15000
|
|
66
|
+
const ua = config.userAgent ?? UA
|
|
67
|
+
return defineTool({
|
|
68
|
+
name: config.name ?? "vn_lottery",
|
|
69
|
+
description:
|
|
70
|
+
config.description ??
|
|
71
|
+
"Lấy kết quả xổ số kiến thiết Việt Nam mới nhất theo miền (mặc định Miền Bắc / XSMB). Nguồn: xoso.com.vn.",
|
|
72
|
+
parameters: Parameters,
|
|
73
|
+
success: Success,
|
|
74
|
+
execute: async (input) => {
|
|
75
|
+
const region = input.region ?? "north"
|
|
76
|
+
const conf = REGION_URLS[region]
|
|
77
|
+
const warnings: string[] = []
|
|
78
|
+
const controller = new AbortController()
|
|
79
|
+
const timer = setTimeout(() => controller.abort(), timeout)
|
|
80
|
+
const html = await fetchText(conf.url, {
|
|
81
|
+
headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
|
|
82
|
+
signal: controller.signal,
|
|
83
|
+
}).finally(() => clearTimeout(timer))
|
|
84
|
+
const $ = loadHtml(html)
|
|
85
|
+
// The bash heuristic grabs the section with id `kqngay_<id>` and the
|
|
86
|
+
// table inside. We mirror that with cheerio.
|
|
87
|
+
const section = $("section[id^='kqngay_']").first()
|
|
88
|
+
if (section.length === 0) {
|
|
89
|
+
warnings.push(`xoso.com.vn: no section[id^='kqngay_'] for ${conf.code}`)
|
|
90
|
+
return {
|
|
91
|
+
region,
|
|
92
|
+
region_label: conf.label,
|
|
93
|
+
prizes: [],
|
|
94
|
+
source_url: conf.url,
|
|
95
|
+
warnings,
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const sectionText = section.text()
|
|
99
|
+
const date = parseDate(sectionText, conf.code)
|
|
100
|
+
const prizes: Schema.Schema.Type<typeof Prize>[] = []
|
|
101
|
+
// Each prize row is `<tr><td>{prizeName}<td>...<span>{number}</span>...`.
|
|
102
|
+
// Cheerio: find `table.table-result tbody tr`.
|
|
103
|
+
const rows = section.find("table.table-result tbody tr").toArray()
|
|
104
|
+
for (const tr of rows) {
|
|
105
|
+
const cells = $(tr).find("td").toArray()
|
|
106
|
+
if (cells.length < 2) continue
|
|
107
|
+
const prizeName = $(cells[0]!).text().trim()
|
|
108
|
+
if (!prizeName) continue
|
|
109
|
+
const numberSpans = $(tr).find("span").toArray()
|
|
110
|
+
const numbers: string[] = []
|
|
111
|
+
for (const sp of numberSpans) {
|
|
112
|
+
const v = $(sp).text().trim()
|
|
113
|
+
if (/^\d{2,6}$/.test(v)) numbers.push(v)
|
|
114
|
+
}
|
|
115
|
+
if (numbers.length === 0) continue
|
|
116
|
+
prizes.push({ name: prizeName, numbers })
|
|
117
|
+
}
|
|
118
|
+
if (prizes.length === 0) warnings.push(`xoso.com.vn: no prize rows extracted for ${conf.code}`)
|
|
119
|
+
return {
|
|
120
|
+
region,
|
|
121
|
+
region_label: conf.label,
|
|
122
|
+
date,
|
|
123
|
+
prizes,
|
|
124
|
+
source_url: conf.url,
|
|
125
|
+
warnings,
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
}
|
package/src/web_fetch.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
2
|
+
import { Schema } from "effect"
|
|
3
|
+
|
|
4
|
+
export type WebFetchConfig = {
|
|
5
|
+
timeoutMs?: number
|
|
6
|
+
maxLength?: number
|
|
7
|
+
userAgent?: string
|
|
8
|
+
name?: string
|
|
9
|
+
description?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const Parameters = Schema.Struct({
|
|
13
|
+
url: Schema.String,
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
const Success = Schema.Struct({
|
|
17
|
+
url: Schema.String,
|
|
18
|
+
title: Schema.optional(Schema.String),
|
|
19
|
+
content: Schema.String,
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const HTML_ENTITIES: Record<string, string> = {
|
|
23
|
+
"&": "&",
|
|
24
|
+
"<": "<",
|
|
25
|
+
">": ">",
|
|
26
|
+
""": '"',
|
|
27
|
+
"'": "'",
|
|
28
|
+
"'": "'",
|
|
29
|
+
" ": " ",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const decodeEntities = (s: string): string =>
|
|
33
|
+
s.replace(/&(?:amp|lt|gt|quot|#39|apos|nbsp);/g, (m) => HTML_ENTITIES[m] ?? m).replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code)))
|
|
34
|
+
|
|
35
|
+
const extractTitle = (html: string): string | undefined => {
|
|
36
|
+
const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)
|
|
37
|
+
if (!match) return undefined
|
|
38
|
+
return decodeEntities(match[1] ?? "").trim() || undefined
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const htmlToText = (html: string, maxLength: number): string => {
|
|
42
|
+
const stripped = html
|
|
43
|
+
.replace(/<script[\s\S]*?<\/script>/gi, "")
|
|
44
|
+
.replace(/<style[\s\S]*?<\/style>/gi, "")
|
|
45
|
+
.replace(/<noscript[\s\S]*?<\/noscript>/gi, "")
|
|
46
|
+
.replace(/<!--[\s\S]*?-->/g, "")
|
|
47
|
+
.replace(/<\/(p|div|li|h\d|br|tr)>/gi, "\n")
|
|
48
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
49
|
+
.replace(/<[^>]+>/g, " ")
|
|
50
|
+
const collapsed = decodeEntities(stripped).replace(/[ \t]+/g, " ").replace(/\n\s*\n+/g, "\n\n").trim()
|
|
51
|
+
if (collapsed.length <= maxLength) return collapsed
|
|
52
|
+
return collapsed.slice(0, maxLength) + "\n... [truncated]"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const webFetch = (config: WebFetchConfig = {}) => {
|
|
56
|
+
const timeout = config.timeoutMs ?? 15000
|
|
57
|
+
const maxLength = config.maxLength ?? 100_000
|
|
58
|
+
const ua = config.userAgent ?? "tinyweb-agent/0.1 (+https://github.com/anomalyco/tinyweb-agent)"
|
|
59
|
+
return defineTool({
|
|
60
|
+
name: config.name ?? "web_fetch",
|
|
61
|
+
description: config.description ?? "Fetch a URL and return its title plus extracted plain-text content.",
|
|
62
|
+
parameters: Parameters,
|
|
63
|
+
success: Success,
|
|
64
|
+
execute: async (input) => {
|
|
65
|
+
const controller = new AbortController()
|
|
66
|
+
const timer = setTimeout(() => controller.abort(), timeout)
|
|
67
|
+
const res = await fetch(input.url, {
|
|
68
|
+
headers: { "user-agent": ua, accept: "text/html,*/*;q=0.8" },
|
|
69
|
+
signal: controller.signal,
|
|
70
|
+
}).finally(() => clearTimeout(timer))
|
|
71
|
+
if (!res.ok) throw new Error(`Fetch ${input.url} failed: HTTP ${res.status}`)
|
|
72
|
+
const contentType = res.headers.get("content-type") ?? ""
|
|
73
|
+
const raw = await res.text()
|
|
74
|
+
if (contentType.includes("html")) {
|
|
75
|
+
return { url: input.url, title: extractTitle(raw), content: htmlToText(raw, maxLength) }
|
|
76
|
+
}
|
|
77
|
+
return { url: input.url, content: raw.length > maxLength ? raw.slice(0, maxLength) + "\n... [truncated]" : raw }
|
|
78
|
+
},
|
|
79
|
+
})
|
|
80
|
+
}
|