@tinyweb_dev/agent-framework-tool 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/builtins.cjs +820 -0
  2. package/dist/builtins.cjs.map +1 -0
  3. package/dist/builtins.d.ts +58 -0
  4. package/dist/builtins.d.ts.map +1 -0
  5. package/dist/builtins.js +818 -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 +1209 -0
  44. package/dist/index.cjs.map +1 -0
  45. package/dist/index.d.ts +22 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +1176 -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/todo/update_todo_list.d.ts +44 -0
  98. package/dist/todo/update_todo_list.d.ts.map +1 -0
  99. package/dist/vn/gold.cjs +198 -0
  100. package/dist/vn/gold.cjs.map +1 -0
  101. package/dist/vn/gold.d.ts +36 -0
  102. package/dist/vn/gold.d.ts.map +1 -0
  103. package/dist/vn/gold.js +196 -0
  104. package/dist/vn/gold.js.map +1 -0
  105. package/dist/vn/lottery.cjs +126 -0
  106. package/dist/vn/lottery.cjs.map +1 -0
  107. package/dist/vn/lottery.d.ts +31 -0
  108. package/dist/vn/lottery.d.ts.map +1 -0
  109. package/dist/vn/lottery.js +124 -0
  110. package/dist/vn/lottery.js.map +1 -0
  111. package/dist/web_fetch.cjs +65 -0
  112. package/dist/web_fetch.cjs.map +1 -0
  113. package/dist/web_fetch.d.ts +16 -0
  114. package/dist/web_fetch.d.ts.map +1 -0
  115. package/dist/web_fetch.js +63 -0
  116. package/dist/web_fetch.js.map +1 -0
  117. package/dist/web_search.cjs +98 -0
  118. package/dist/web_search.cjs.map +1 -0
  119. package/dist/web_search.d.ts +19 -0
  120. package/dist/web_search.d.ts.map +1 -0
  121. package/dist/web_search.js +96 -0
  122. package/dist/web_search.js.map +1 -0
  123. package/package.json +109 -30
  124. package/src/builtins.ts +0 -78
  125. package/src/display_response.ts +0 -79
  126. package/src/file_read.ts +0 -31
  127. package/src/file_write.ts +0 -33
  128. package/src/image_describe.ts +0 -58
  129. package/src/image_edit.ts +0 -74
  130. package/src/image_generate.ts +0 -102
  131. package/src/index.ts +0 -47
  132. package/src/info/crypto.ts +0 -79
  133. package/src/info/time.ts +0 -83
  134. package/src/info/weather.ts +0 -134
  135. package/src/search/perplexity.ts +0 -129
  136. package/src/shared/html.ts +0 -87
  137. package/src/shared/http.ts +0 -40
  138. package/src/shared/s3.ts +0 -157
  139. package/src/shared/storage.ts +0 -83
  140. package/src/vn/gold.ts +0 -192
  141. package/src/vn/lottery.ts +0 -129
  142. package/src/web_fetch.ts +0 -80
  143. package/src/web_search.ts +0 -92
@@ -1,134 +0,0 @@
1
- /**
2
- * `weather` — current weather snapshot via wttr.in JSON.
3
- *
4
- * Adapted from `packages/tool/references/daily-info/thoitiet` which curls
5
- * `wttr.in/${location}?0&m&lang=vi` for plain text. We use the JSON variant
6
- * (`?format=j1`) instead — LLMs parse structured data more reliably than the
7
- * ASCII art block returned by `?0`.
8
- *
9
- * Zero-config: wttr.in is free and key-less. Be a good citizen — wttr.in
10
- * asks clients to set a real `User-Agent` so they can rate-limit abusers.
11
- */
12
-
13
- import { defineTool } from "@tinyweb-agent-framework/agent"
14
- import { Schema } from "effect"
15
- import { fetchJson } from "../shared/http"
16
-
17
- export type WeatherConfig = {
18
- readonly defaultLocation?: string
19
- /** Language for `lang_*` description fields. wttr.in supports vi, en, fr, ... */
20
- readonly defaultLang?: string
21
- readonly userAgent?: string
22
- readonly timeoutMs?: number
23
- readonly name?: string
24
- readonly description?: string
25
- }
26
-
27
- const Parameters = Schema.Struct({
28
- location: Schema.optional(Schema.String),
29
- lang: Schema.optional(Schema.String),
30
- })
31
-
32
- const Success = Schema.Struct({
33
- location: Schema.String,
34
- region: Schema.optional(Schema.String),
35
- country: Schema.optional(Schema.String),
36
- observed_at: Schema.String,
37
- temperature_c: Schema.Number,
38
- feels_like_c: Schema.Number,
39
- humidity_percent: Schema.Number,
40
- wind_kmh: Schema.Number,
41
- wind_direction: Schema.String,
42
- condition: Schema.String,
43
- uv_index: Schema.optional(Schema.Number),
44
- visibility_km: Schema.optional(Schema.Number),
45
- pressure_mb: Schema.optional(Schema.Number),
46
- source: Schema.Literal("wttr.in"),
47
- })
48
-
49
- // Subset of the wttr.in `?format=j1` response we care about.
50
- // Reference: https://github.com/chubin/wttr.in (search "JSON output")
51
- type WttrCondition = {
52
- temp_C?: string
53
- FeelsLikeC?: string
54
- humidity?: string
55
- windspeedKmph?: string
56
- winddir16Point?: string
57
- weatherDesc?: { value: string }[]
58
- lang_vi?: { value: string }[]
59
- uvIndex?: string
60
- visibilityKm?: string
61
- visibility?: string
62
- pressure?: string
63
- observation_time?: string
64
- localObsDateTime?: string
65
- }
66
-
67
- type WttrArea = {
68
- areaName?: { value: string }[]
69
- region?: { value: string }[]
70
- country?: { value: string }[]
71
- }
72
-
73
- type WttrResponse = {
74
- current_condition?: WttrCondition[]
75
- nearest_area?: WttrArea[]
76
- }
77
-
78
- const firstValue = (xs: { value: string }[] | undefined): string | undefined =>
79
- xs && xs.length > 0 ? xs[0]!.value : undefined
80
-
81
- const num = (s: string | undefined, fallback = 0): number => {
82
- if (!s) return fallback
83
- const n = Number(s)
84
- return Number.isFinite(n) ? n : fallback
85
- }
86
-
87
- export const weather = (config: WeatherConfig = {}) => {
88
- const defaultLocation = config.defaultLocation ?? "Hanoi"
89
- const defaultLang = config.defaultLang ?? "vi"
90
- const ua = config.userAgent ?? "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)"
91
- const timeout = config.timeoutMs ?? 15000
92
- return defineTool({
93
- name: config.name ?? "weather",
94
- description:
95
- config.description ??
96
- `Lấy thời tiết hiện tại của một địa điểm (city, tỉnh, hoặc tên sân bay). Mặc định ${defaultLocation}. Nguồn: wttr.in.`,
97
- parameters: Parameters,
98
- success: Success,
99
- execute: async (input) => {
100
- const loc = (input.location ?? defaultLocation).trim()
101
- const lang = input.lang ?? defaultLang
102
- const url = `https://wttr.in/${encodeURIComponent(loc)}?format=j1&lang=${encodeURIComponent(lang)}`
103
- const controller = new AbortController()
104
- const timer = setTimeout(() => controller.abort(), timeout)
105
- const data = await fetchJson<WttrResponse>(url, {
106
- headers: { "user-agent": ua, accept: "application/json" },
107
- signal: controller.signal,
108
- }).finally(() => clearTimeout(timer))
109
- const cur = data.current_condition?.[0]
110
- if (!cur) throw new Error(`wttr.in returned no current_condition for "${loc}"`)
111
- const area = data.nearest_area?.[0]
112
- const condition = (lang === "vi" ? firstValue(cur.lang_vi) : undefined) ?? firstValue(cur.weatherDesc) ?? "N/A"
113
- const visibility = num(cur.visibilityKm ?? cur.visibility, NaN)
114
- const pressure = num(cur.pressure, NaN)
115
- const uv = num(cur.uvIndex, NaN)
116
- return {
117
- location: firstValue(area?.areaName) ?? loc,
118
- region: firstValue(area?.region),
119
- country: firstValue(area?.country),
120
- observed_at: cur.localObsDateTime ?? cur.observation_time ?? new Date().toISOString(),
121
- temperature_c: num(cur.temp_C),
122
- feels_like_c: num(cur.FeelsLikeC),
123
- humidity_percent: num(cur.humidity),
124
- wind_kmh: num(cur.windspeedKmph),
125
- wind_direction: cur.winddir16Point ?? "",
126
- condition,
127
- uv_index: Number.isFinite(uv) ? uv : undefined,
128
- visibility_km: Number.isFinite(visibility) ? visibility : undefined,
129
- pressure_mb: Number.isFinite(pressure) ? pressure : undefined,
130
- source: "wttr.in" as const,
131
- }
132
- },
133
- })
134
- }
@@ -1,129 +0,0 @@
1
- /**
2
- * `perplexity_search` — answer a question via Perplexity Sonar API.
3
- *
4
- * Unlike `web_search` (which returns raw `{title,url,snippet}` results for the
5
- * LLM to synthesize), Perplexity's Sonar models return a **synthesized
6
- * answer + citations** in one shot. That:
7
- *
8
- * • Saves output tokens on the main model (Perplexity does the summary).
9
- * • Cuts hallucination risk because citations are grounded in retrieved
10
- * pages.
11
- * • Costs more per call but is cheaper than running web_search + a long
12
- * follow-up turn.
13
- *
14
- * The Sonar API is **OpenAI Chat Completions-compatible**:
15
- * `POST https://api.perplexity.ai/chat/completions` with the standard
16
- * `{ model, messages }` body. We hit it with `postJson` and pull out the
17
- * `choices[0].message.content` plus the top-level `citations` array.
18
- *
19
- * Docs: https://docs.perplexity.ai/docs/sdk/overview
20
- */
21
-
22
- import { defineTool } from "@tinyweb-agent-framework/agent"
23
- import { Schema } from "effect"
24
- import { postJson } from "../shared/http"
25
-
26
- export type PerplexityModel = "sonar" | "sonar-pro" | "sonar-reasoning" | "sonar-reasoning-pro"
27
-
28
- export type PerplexitySearchConfig = {
29
- readonly apiKey: string
30
- /** Default Sonar variant. Cheaper-and-good = "sonar"; deepest = "sonar-reasoning-pro". */
31
- readonly model?: PerplexityModel
32
- /** Optional system prompt prepended on every call. Keeps the answer style on-brand. */
33
- readonly systemPrompt?: string
34
- /** Override the base URL if you proxy through your own gateway. */
35
- readonly baseURL?: string
36
- readonly timeoutMs?: number
37
- /** Generation params. Defaults are sensible for grounded short answers. */
38
- readonly temperature?: number
39
- readonly maxTokens?: number
40
- readonly name?: string
41
- readonly description?: string
42
- }
43
-
44
- const Parameters = Schema.Struct({
45
- query: Schema.String,
46
- })
47
-
48
- const Citation = Schema.Struct({
49
- url: Schema.String,
50
- title: Schema.optional(Schema.String),
51
- })
52
-
53
- const Success = Schema.Struct({
54
- query: Schema.String,
55
- answer: Schema.String,
56
- citations: Schema.Array(Citation),
57
- model: Schema.String,
58
- })
59
-
60
- // Sonar response shape — OpenAI-compatible plus top-level extras.
61
- type SonarMessage = { role: string; content: string }
62
- type SonarChoice = { message: SonarMessage; finish_reason?: string }
63
- type SonarSearchResult = { url?: string; title?: string }
64
- type SonarResponse = {
65
- model?: string
66
- choices: SonarChoice[]
67
- // Older revisions returned `citations: string[]`. Newer ones return
68
- // `search_results: [{ url, title, ... }]`. Support both.
69
- citations?: string[]
70
- search_results?: SonarSearchResult[]
71
- }
72
-
73
- const normaliseCitations = (data: SonarResponse): { url: string; title?: string }[] => {
74
- if (data.search_results && data.search_results.length > 0) {
75
- return data.search_results
76
- .filter((r): r is SonarSearchResult & { url: string } => typeof r.url === "string" && r.url.length > 0)
77
- .map((r) => (r.title ? { url: r.url, title: r.title } : { url: r.url }))
78
- }
79
- if (data.citations && data.citations.length > 0) {
80
- return data.citations.filter((u) => typeof u === "string").map((u) => ({ url: u }))
81
- }
82
- return []
83
- }
84
-
85
- export const perplexitySearch = (config: PerplexitySearchConfig) => {
86
- if (!config.apiKey) throw new Error("perplexitySearch: apiKey is required")
87
- const model = config.model ?? "sonar"
88
- const baseURL = config.baseURL ?? "https://api.perplexity.ai"
89
- const timeout = config.timeoutMs ?? 30000
90
- const temperature = config.temperature ?? 0.2
91
- const maxTokens = config.maxTokens ?? 800
92
- const sys =
93
- config.systemPrompt ??
94
- "Answer the user's question accurately and concisely. Cite sources by URL. Use the user's language."
95
- return defineTool({
96
- name: config.name ?? "perplexity_search",
97
- description:
98
- config.description ??
99
- "Hỏi-đáp web với Perplexity Sonar: nhận về câu trả lời đã tổng hợp + citation. Dùng khi cần thông tin tươi/đa nguồn.",
100
- parameters: Parameters,
101
- success: Success,
102
- execute: async (input) => {
103
- const url = `${baseURL.replace(/\/+$/, "")}/chat/completions`
104
- const controller = new AbortController()
105
- const timer = setTimeout(() => controller.abort(), timeout)
106
- const body = {
107
- model,
108
- messages: [
109
- { role: "system", content: sys },
110
- { role: "user", content: input.query },
111
- ],
112
- temperature,
113
- max_tokens: maxTokens,
114
- }
115
- const data = await postJson<SonarResponse>(url, body, {
116
- headers: { authorization: `Bearer ${config.apiKey}` },
117
- signal: controller.signal,
118
- }).finally(() => clearTimeout(timer))
119
- const answer = data.choices?.[0]?.message?.content ?? ""
120
- if (!answer) throw new Error("perplexitySearch: empty answer from Sonar API")
121
- return {
122
- query: input.query,
123
- answer,
124
- citations: normaliseCitations(data),
125
- model: data.model ?? model,
126
- }
127
- },
128
- })
129
- }
@@ -1,87 +0,0 @@
1
- /**
2
- * Shared HTML scraping helpers.
3
- *
4
- * Centralises cheerio import so tools don't each pull it directly. Adds:
5
- * • `loadHtml(html)` — typed wrapper returning a `cheerio.Cheerio` root.
6
- * • `firstMatchText(root, selectors)` — try a list of selectors in order;
7
- * return the first non-empty .text() found. Useful for resilient scrapers
8
- * where the upstream site has multiple legacy layouts.
9
- * • `collectText(root, selector)` — collect trimmed text for every match.
10
- * • `parseVndNumber(s)` — parse `"125.500.000"` (Vietnamese thousand sep)
11
- * and `"125,500.50"` into a number.
12
- *
13
- * Cheerio is loaded eagerly (top-level import). Bun handles its ESM build
14
- * transparently. We re-export the `Cheerio` and `CheerioAPI` types so call
15
- * sites don't have to take a direct dep on cheerio.
16
- */
17
-
18
- import { load, type CheerioAPI, type Cheerio } from "cheerio"
19
-
20
- export type HtmlRoot = CheerioAPI
21
-
22
- export const loadHtml = (html: string): HtmlRoot => load(html)
23
-
24
- /**
25
- * Try each selector in order; return the trimmed `.text()` of the first match
26
- * with non-empty content. Returns `undefined` if nothing matches.
27
- */
28
- export const firstMatchText = ($: HtmlRoot, selectors: readonly string[]): string | undefined => {
29
- for (const sel of selectors) {
30
- const el = $(sel).first()
31
- if (el.length === 0) continue
32
- const txt = el.text().trim()
33
- if (txt) return txt
34
- }
35
- return undefined
36
- }
37
-
38
- /**
39
- * Collect `.text()` (trimmed, non-empty) for every match of the selector.
40
- */
41
- export const collectText = ($: HtmlRoot, selector: string): string[] => {
42
- const out: string[] = []
43
- // Cheerio's `each` types the second arg as `AnyNode` from domhandler. We
44
- // don't want a direct domhandler dep, so we let TS infer via `.toArray()`
45
- // which returns the node array typed by cheerio itself.
46
- for (const node of $(selector).toArray()) {
47
- const txt = $(node).text().trim()
48
- if (txt) out.push(txt)
49
- }
50
- return out
51
- }
52
-
53
- /**
54
- * Parse a Vietnamese-style number like "125.500.000" → 125500000, or
55
- * "1,234.56" → 1234.56. Heuristic: if there's both `.` and `,`, assume the
56
- * last separator is the decimal mark. If only `.` is present and groups are
57
- * exactly 3 digits, treat them as thousands.
58
- */
59
- export const parseVndNumber = (s: string): number => {
60
- const cleaned = s.replace(/[^\d.,-]/g, "").trim()
61
- if (!cleaned) return NaN
62
- const hasDot = cleaned.includes(".")
63
- const hasComma = cleaned.includes(",")
64
- if (hasDot && hasComma) {
65
- const lastDot = cleaned.lastIndexOf(".")
66
- const lastComma = cleaned.lastIndexOf(",")
67
- const decimalIdx = Math.max(lastDot, lastComma)
68
- const intPart = cleaned.slice(0, decimalIdx).replace(/[.,]/g, "")
69
- const decPart = cleaned.slice(decimalIdx + 1)
70
- return Number(`${intPart}.${decPart}`)
71
- }
72
- if (hasDot) {
73
- const parts = cleaned.split(".")
74
- const allGroupsThree = parts.slice(1).every((p) => p.length === 3)
75
- if (allGroupsThree) return Number(parts.join(""))
76
- return Number(cleaned)
77
- }
78
- if (hasComma) {
79
- const parts = cleaned.split(",")
80
- const allGroupsThree = parts.slice(1).every((p) => p.length === 3)
81
- if (allGroupsThree) return Number(parts.join(""))
82
- return Number(cleaned.replace(",", "."))
83
- }
84
- return Number(cleaned)
85
- }
86
-
87
- export type { Cheerio, CheerioAPI }
@@ -1,40 +0,0 @@
1
- export class HttpToolError extends Error {
2
- readonly _tag = "HttpToolError"
3
- constructor(message: string, readonly status?: number, readonly body?: string) {
4
- super(message)
5
- this.name = "HttpToolError"
6
- }
7
- }
8
-
9
- const ensureOk = async (res: Response, label: string): Promise<Response> => {
10
- if (res.ok) return res
11
- const body = await res.text().catch(() => "")
12
- throw new HttpToolError(`${label} ${res.status}: ${body.slice(0, 500)}`, res.status, body)
13
- }
14
-
15
- export const fetchJson = async <T = unknown>(url: string, init?: RequestInit): Promise<T> => {
16
- const res = await fetch(url, init)
17
- await ensureOk(res, `GET ${url}`)
18
- return (await res.json()) as T
19
- }
20
-
21
- export const postJson = async <T = unknown>(url: string, body: unknown, init?: RequestInit): Promise<T> => {
22
- const headers = new Headers(init?.headers)
23
- if (!headers.has("content-type")) headers.set("content-type", "application/json")
24
- const res = await fetch(url, { method: "POST", body: JSON.stringify(body), ...init, headers })
25
- await ensureOk(res, `POST ${url}`)
26
- return (await res.json()) as T
27
- }
28
-
29
- export const fetchText = async (url: string, init?: RequestInit): Promise<string> => {
30
- const res = await fetch(url, init)
31
- await ensureOk(res, `GET ${url}`)
32
- return res.text()
33
- }
34
-
35
- export const fetchBytes = async (url: string, init?: RequestInit): Promise<Uint8Array> => {
36
- const res = await fetch(url, init)
37
- await ensureOk(res, `GET ${url}`)
38
- const buf = await res.arrayBuffer()
39
- return new Uint8Array(buf)
40
- }
package/src/shared/s3.ts DELETED
@@ -1,157 +0,0 @@
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
- }
@@ -1,83 +0,0 @@
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
- }