@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/src/vn/gold.ts DELETED
@@ -1,192 +0,0 @@
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
- }
package/src/vn/lottery.ts DELETED
@@ -1,129 +0,0 @@
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 DELETED
@@ -1,80 +0,0 @@
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
- "&amp;": "&",
24
- "&lt;": "<",
25
- "&gt;": ">",
26
- "&quot;": '"',
27
- "&#39;": "'",
28
- "&apos;": "'",
29
- "&nbsp;": " ",
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
- }
package/src/web_search.ts DELETED
@@ -1,92 +0,0 @@
1
- import { defineTool } from "@tinyweb-agent-framework/agent"
2
- import { Schema } from "effect"
3
- import { fetchJson, postJson } from "./shared/http"
4
-
5
- export type WebSearchProvider = "tavily" | "brave" | "exa" | "serper"
6
-
7
- export type WebSearchConfig = {
8
- provider: WebSearchProvider
9
- apiKey: string
10
- name?: string
11
- description?: string
12
- }
13
-
14
- const ResultItem = Schema.Struct({
15
- title: Schema.String,
16
- url: Schema.String,
17
- snippet: Schema.String,
18
- })
19
-
20
- const Parameters = Schema.Struct({
21
- query: Schema.String,
22
- limit: Schema.optional(Schema.Number),
23
- })
24
-
25
- const Success = Schema.Struct({
26
- results: Schema.Array(ResultItem),
27
- })
28
-
29
- type SearchInput = Schema.Schema.Type<typeof Parameters>
30
- type SearchResult = Schema.Schema.Type<typeof ResultItem>
31
-
32
- type TavilyResult = { title: string; url: string; content?: string }
33
- type TavilyResponse = { results: TavilyResult[] }
34
- type BraveResult = { title: string; url: string; description?: string }
35
- type BraveResponse = { web?: { results?: BraveResult[] } }
36
- type ExaResult = { title?: string; url: string; text?: string }
37
- type ExaResponse = { results: ExaResult[] }
38
- type SerperResult = { title: string; link: string; snippet?: string }
39
- type SerperResponse = { organic?: SerperResult[] }
40
-
41
- const searchTavily = async (apiKey: string, input: SearchInput): Promise<SearchResult[]> => {
42
- const data = await postJson<TavilyResponse>("https://api.tavily.com/search", {
43
- api_key: apiKey,
44
- query: input.query,
45
- max_results: input.limit ?? 5,
46
- })
47
- return data.results.map((r) => ({ title: r.title, url: r.url, snippet: r.content ?? "" }))
48
- }
49
-
50
- const searchBrave = async (apiKey: string, input: SearchInput): Promise<SearchResult[]> => {
51
- const params = new URLSearchParams({ q: input.query, count: String(input.limit ?? 5) })
52
- const data = await fetchJson<BraveResponse>(`https://api.search.brave.com/res/v1/web/search?${params}`, {
53
- headers: { "X-Subscription-Token": apiKey, accept: "application/json" },
54
- })
55
- const items = data.web?.results ?? []
56
- return items.map((r) => ({ title: r.title, url: r.url, snippet: r.description ?? "" }))
57
- }
58
-
59
- const searchExa = async (apiKey: string, input: SearchInput): Promise<SearchResult[]> => {
60
- const data = await postJson<ExaResponse>(
61
- "https://api.exa.ai/search",
62
- { query: input.query, numResults: input.limit ?? 5, contents: { text: true } },
63
- { headers: { "x-api-key": apiKey } },
64
- )
65
- return data.results.map((r) => ({ title: r.title ?? r.url, url: r.url, snippet: (r.text ?? "").slice(0, 500) }))
66
- }
67
-
68
- const searchSerper = async (apiKey: string, input: SearchInput): Promise<SearchResult[]> => {
69
- const data = await postJson<SerperResponse>(
70
- "https://google.serper.dev/search",
71
- { q: input.query, num: input.limit ?? 5 },
72
- { headers: { "X-API-KEY": apiKey } },
73
- )
74
- return (data.organic ?? []).map((r) => ({ title: r.title, url: r.link, snippet: r.snippet ?? "" }))
75
- }
76
-
77
- const dispatch = (provider: WebSearchProvider, apiKey: string, input: SearchInput): Promise<SearchResult[]> => {
78
- if (provider === "tavily") return searchTavily(apiKey, input)
79
- if (provider === "brave") return searchBrave(apiKey, input)
80
- if (provider === "exa") return searchExa(apiKey, input)
81
- if (provider === "serper") return searchSerper(apiKey, input)
82
- throw new Error(`Unknown web_search provider: ${provider as string}`)
83
- }
84
-
85
- export const webSearch = (config: WebSearchConfig) =>
86
- defineTool({
87
- name: config.name ?? "web_search",
88
- description: config.description ?? "Search the web and return a list of {title, url, snippet} results.",
89
- parameters: Parameters,
90
- success: Success,
91
- execute: async (input) => ({ results: await dispatch(config.provider, config.apiKey, input) }),
92
- })