@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tinyweb-agent-framework contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # @tinyweb-agent-framework/tool
2
+
3
+ Built-in tool factories + FileStorage adapters. Every factory returns a tool ready to plug into `defineAgent({ tools: { ... } })`.
4
+
5
+ ## Quick start: `builtinTools(config)`
6
+
7
+ One-liner to wire the whole catalog. Returns `Record<string, Tool>` you can pass straight into `defineAgent({ tools })`.
8
+
9
+ ```ts
10
+ import { builtinTools } from "@tinyweb-agent-framework/tool"
11
+
12
+ const tools = builtinTools({
13
+ // Zero-config defaults are ON: time_now, weather, crypto_price,
14
+ // vn_gold_price, vn_lottery. Pass `false` to opt out of any of them.
15
+ // Opt-in (need an API key):
16
+ perplexity: { apiKey: process.env.PERPLEXITY_API_KEY! },
17
+ webSearch: { provider: "tavily", apiKey: process.env.TAVILY_API_KEY! },
18
+ })
19
+ ```
20
+
21
+ See the full catalog + tier breakdown in [the docs site guide](../docs/src/content/docs/guides/builtin-tools.md).
22
+
23
+ ## Tools
24
+
25
+ ### Info / utility (zero-config)
26
+
27
+ - `timeNow(config)` — current time in any IANA timezone (default `Asia/Ho_Chi_Minh`).
28
+ - `weather(config)` — current weather snapshot via wttr.in (no API key).
29
+ - `cryptoPrice(config)` — Binance spot ticker, multi-symbol in one call.
30
+
31
+ ### Vietnam locale (zero-config, scrape-based)
32
+
33
+ - `vnGoldPrice(config)` — giá vàng nhẫn 24K (BTMC + Bảo Tín Mạnh Hải).
34
+ - `vnLottery(config)` — kết quả XSMB / XSMT / XSMN từ xoso.com.vn.
35
+
36
+ Both return `warnings: [...]` when the upstream layout drifts instead of throwing.
37
+
38
+ ### Search
39
+
40
+ - `perplexitySearch(config)` — Sonar API (OpenAI-compatible) answers with citations.
41
+ - `webSearch(config)` — Tavily / Brave / Exa / Serper unified.
42
+
43
+ ### `webSearch(config)`
44
+
45
+ ```ts
46
+ import { webSearch } from "@tinyweb-agent-framework/tool"
47
+
48
+ const search = webSearch({ provider: "tavily", apiKey: process.env.TAVILY_API_KEY! })
49
+ // provider: "tavily" | "brave" | "exa" | "serper"
50
+ ```
51
+
52
+ ### `webFetch(config?)`
53
+
54
+ Fetches a URL and returns plain-text content (regex HTML strip, no jsdom).
55
+
56
+ ```ts
57
+ import { webFetch } from "@tinyweb-agent-framework/tool"
58
+ const fetcher = webFetch({ timeoutMs: 15_000, maxLength: 100_000 })
59
+ ```
60
+
61
+ ### `imageGenerate(config)`
62
+
63
+ ```ts
64
+ import { imageGenerate } from "@tinyweb-agent-framework/tool"
65
+ const gen = imageGenerate({
66
+ provider: "openai", // "openai" | "replicate"
67
+ apiKey: process.env.OPENAI_API_KEY!,
68
+ model: "gpt-image-1", // optional
69
+ storage, // optional FileStorage to persist output
70
+ })
71
+ ```
72
+
73
+ ### `imageDescribe(config)` / `imageEdit(config)`
74
+
75
+ ```ts
76
+ import { imageDescribe, imageEdit } from "@tinyweb-agent-framework/tool"
77
+ const describe = imageDescribe({ apiKey: process.env.OPENAI_API_KEY! })
78
+ const edit = imageEdit({ apiKey: process.env.OPENAI_API_KEY!, storage })
79
+ ```
80
+
81
+ ### `fileRead(config)` / `fileWrite(config)`
82
+
83
+ ```ts
84
+ import { fileRead, fileWrite, makeLocalFS } from "@tinyweb-agent-framework/tool"
85
+
86
+ const storage = makeLocalFS("./.agent-data")
87
+ const read = fileRead({ storage })
88
+ const write = fileWrite({ storage })
89
+ ```
90
+
91
+ ## FileStorage adapters
92
+
93
+ - `makeMemoryStore()` — in-memory `Map<string, Uint8Array>`.
94
+ - `makeLocalFS(basePath)` — node:fs with path-traversal guard.
95
+ - `makeS3Store(client, options)` — duck-typed against `@aws-sdk/client-s3` (peer dep).
96
+
97
+ ```ts
98
+ import { S3Client, GetObjectCommand, PutObjectCommand, ListObjectsV2Command } from "@aws-sdk/client-s3"
99
+ import { makeS3Store } from "@tinyweb-agent-framework/tool"
100
+
101
+ const storage = makeS3Store(
102
+ new S3Client({ region: "us-east-1" }),
103
+ {
104
+ bucket: "my-bucket",
105
+ prefix: "agent/",
106
+ commands: { GetObjectCommand, PutObjectCommand, ListObjectsV2Command },
107
+ publicUrl: (key) => `https://cdn.example.com/${key}`,
108
+ },
109
+ )
110
+ ```
111
+
112
+ ## License
113
+
114
+ MIT
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/package.json",
3
+ "name": "@tinyweb_dev/agent-framework-tool",
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "typecheck": "tsc --noEmit",
9
+ "test": "bun test --timeout 30000"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "exports": {
17
+ ".": "./src/index.ts",
18
+ "./builtins": "./src/builtins.ts",
19
+ "./web_search": "./src/web_search.ts",
20
+ "./web_fetch": "./src/web_fetch.ts",
21
+ "./image_generate": "./src/image_generate.ts",
22
+ "./image_describe": "./src/image_describe.ts",
23
+ "./image_edit": "./src/image_edit.ts",
24
+ "./file_read": "./src/file_read.ts",
25
+ "./file_write": "./src/file_write.ts",
26
+ "./display_response": "./src/display_response.ts",
27
+ "./info/time": "./src/info/time.ts",
28
+ "./info/weather": "./src/info/weather.ts",
29
+ "./info/crypto": "./src/info/crypto.ts",
30
+ "./vn/gold": "./src/vn/gold.ts",
31
+ "./vn/lottery": "./src/vn/lottery.ts",
32
+ "./search/perplexity": "./src/search/perplexity.ts",
33
+ "./shared/storage": "./src/shared/storage.ts",
34
+ "./shared/s3": "./src/shared/s3.ts",
35
+ "./shared/http": "./src/shared/http.ts",
36
+ "./shared/html": "./src/shared/html.ts"
37
+ },
38
+ "devDependencies": {
39
+ "@tsconfig/bun": "1.0.9",
40
+ "@types/bun": "1.3.12",
41
+ "typescript": "5.8.2"
42
+ },
43
+ "dependencies": {
44
+ "cheerio": "1.0.0",
45
+ "effect": "4.0.0-beta.59",
46
+ "@tinyweb_dev/agent-framework-core": "0.1.0",
47
+ "@tinyweb_dev/agent-framework-llm": "0.1.0",
48
+ "@tinyweb_dev/agent-framework-agent": "0.1.0"
49
+ }
50
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * `builtinTools(config)` — one-liner bundle that returns a `Record<string, Tool>`
3
+ * suitable for passing straight into `defineAgent({ tools: ... })`.
4
+ *
5
+ * Lets a developer wire common Vietnam-locale chat tools with zero per-tool
6
+ * boilerplate. Default-on: `time_now`, `weather`, `crypto_price`,
7
+ * `vn_lottery`, `vn_gold_price`. Opt-in (because they need an API key):
8
+ * `perplexity` and `web_search`.
9
+ *
10
+ * Pass `false` to a default-on key to disable it:
11
+ *
12
+ * ```ts
13
+ * defineAgent({
14
+ * tools: builtinTools({
15
+ * time: true, // default
16
+ * weather: true, // default
17
+ * crypto: false, // disabled
18
+ * perplexity: { apiKey: process.env.PERPLEXITY_API_KEY! },
19
+ * }),
20
+ * })
21
+ * ```
22
+ */
23
+
24
+ import type { AnyTool } from "@tinyweb-agent-framework/llm"
25
+ import { timeNow, type TimeNowConfig } from "./info/time"
26
+ import { weather, type WeatherConfig } from "./info/weather"
27
+ import { cryptoPrice, type CryptoPriceConfig } from "./info/crypto"
28
+ import { vnGoldPrice, type VnGoldConfig } from "./vn/gold"
29
+ import { vnLottery, type VnLotteryConfig } from "./vn/lottery"
30
+ import { perplexitySearch, type PerplexitySearchConfig } from "./search/perplexity"
31
+ import { webSearch, type WebSearchConfig } from "./web_search"
32
+ import { webFetch, type WebFetchConfig } from "./web_fetch"
33
+ import { displayResponse, type DisplayResponseConfig } from "./display_response"
34
+
35
+ export type BuiltinToolsConfig = {
36
+ /** Default: `true`. Pass `false` or `TimeNowConfig` to override. */
37
+ readonly time?: boolean | TimeNowConfig
38
+ readonly weather?: boolean | WeatherConfig
39
+ readonly crypto?: boolean | CryptoPriceConfig
40
+ readonly vnGold?: boolean | VnGoldConfig
41
+ readonly vnLottery?: boolean | VnLotteryConfig
42
+ /** Opt-in: requires an API key, so default is OFF unless config supplied. */
43
+ readonly perplexity?: PerplexitySearchConfig
44
+ readonly webSearch?: WebSearchConfig
45
+ readonly webFetch?: boolean | WebFetchConfig
46
+ /**
47
+ * Opt-in: only needed when running under a prompt regime that requires
48
+ * "one tool call per turn" (Roo-style task agents). Default OFF — most
49
+ * chat agents should let the model emit plain assistant text instead.
50
+ */
51
+ readonly displayResponse?: boolean | DisplayResponseConfig
52
+ }
53
+
54
+ const isEnabled = (v: boolean | object | undefined, defaultOn: boolean): boolean => {
55
+ if (v === undefined) return defaultOn
56
+ if (v === false) return false
57
+ return true
58
+ }
59
+
60
+ const cfgOrEmpty = <T>(v: boolean | T | undefined): T => {
61
+ if (typeof v === "object" && v !== null) return v as T
62
+ return {} as T
63
+ }
64
+
65
+ export const builtinTools = (config: BuiltinToolsConfig = {}): Record<string, AnyTool> => {
66
+ const tools: Record<string, AnyTool> = {}
67
+ if (isEnabled(config.time, true)) tools.time_now = timeNow(cfgOrEmpty(config.time))
68
+ if (isEnabled(config.displayResponse, true))
69
+ tools.display_response = displayResponse(cfgOrEmpty(config.displayResponse))
70
+ if (isEnabled(config.weather, false)) tools.weather = weather(cfgOrEmpty(config.weather))
71
+ if (isEnabled(config.crypto, false)) tools.crypto_price = cryptoPrice(cfgOrEmpty(config.crypto))
72
+ if (isEnabled(config.vnGold, false)) tools.vn_gold_price = vnGoldPrice(cfgOrEmpty(config.vnGold))
73
+ if (isEnabled(config.vnLottery, false)) tools.vn_lottery = vnLottery(cfgOrEmpty(config.vnLottery))
74
+ if (isEnabled(config.webFetch, false)) tools.web_fetch = webFetch(cfgOrEmpty(config.webFetch))
75
+ if (config.perplexity) tools.perplexity_search = perplexitySearch(config.perplexity)
76
+ if (config.webSearch) tools.web_search = webSearch(config.webSearch)
77
+ return tools
78
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `display_response` — fallback tool for delivering plain conversational
3
+ * or long-form textual content to the user.
4
+ *
5
+ * Adapted from the Roo Code extension's `display_response` native tool
6
+ * (`roo-code-extension/src/core/prompts/tools/native-tools/display_response.ts`).
7
+ *
8
+ * Purpose: some prompt regimes enforce "every assistant turn must call at
9
+ * least one tool" — display_response is the escape hatch the model can
10
+ * use when no domain tool is appropriate (acknowledgements, clarifying
11
+ * remarks, plans, explanations, long-form reports, markdown content).
12
+ * The tool's output is just the `response` argument echoed back, so the
13
+ * model's final user-facing text can be surfaced verbatim by the UI /
14
+ * consumer.
15
+ *
16
+ * NOTE: This is **opt-in**. Most agents in this framework don't need it —
17
+ * the OpenAI Chat protocol already supports plain assistant content
18
+ * alongside tool calls. Use this only when running under a prompt regime
19
+ * (e.g. Roo-style task agents) that strictly requires a tool call per turn.
20
+ *
21
+ * Renderer: not registered in chat-ui's `defaultToolRenderers` because
22
+ * the message is already shown as the assistant bubble's text — surfacing
23
+ * it again as a tool card would duplicate the same content. Consumers
24
+ * who DO want a card can override via `toolRenderers` on `TinywebChat`.
25
+ */
26
+
27
+ import { defineTool } from "@tinyweb-agent-framework/agent"
28
+ import { Schema } from "effect"
29
+
30
+ export type DisplayResponseConfig = {
31
+ readonly name?: string
32
+ readonly description?: string
33
+ }
34
+
35
+ const Parameters = Schema.Struct({
36
+ response: Schema.String,
37
+ })
38
+
39
+ const Success = Schema.Struct({
40
+ response: Schema.String,
41
+ })
42
+
43
+ const DEFAULT_DESCRIPTION = [
44
+ "Deliver a plain textual response to the user when no other tool is appropriate for the current turn.",
45
+ "Use this as a fallback to satisfy the \"every assistant turn must call at least one tool\" constraint",
46
+ "whenever you only need to send textual content — both short conversational replies and long-form",
47
+ "structured output — that does not finish the task. Typical use cases:",
48
+ "- Clarifying remarks, brainstorming, short answers, status updates",
49
+ "- Presenting a plan or proposed approach before implementation",
50
+ "- Explaining code, concepts, errors, or trade-offs in depth",
51
+ "- Delivering a long-form report, summary, analysis, or review",
52
+ "- Showing diagrams, tables, or formatted markdown content to the user",
53
+ "",
54
+ "STRICT OUTPUT RULES (must follow exactly):",
55
+ "- Put the ENTIRE message inside the `response` argument of this tool call.",
56
+ "- Do NOT emit ANY free-form assistant text outside the tool call in the same turn. The assistant",
57
+ " text channel MUST be empty when you call `display_response`.",
58
+ "- This means: no preamble, no recap, no \"Here is…\", no trailing remark before or after the tool",
59
+ " call. Everything the user should see goes inside `response`.",
60
+ "- After you call display_response, STOP. Wait for the user's next message before doing anything",
61
+ " else. Do NOT keep calling tools or generate another turn on your own.",
62
+ "- The `response` must be non-empty.",
63
+ "- Prefer NOT calling display_response if a domain tool (search, weather, etc.) is the right answer.",
64
+ "",
65
+ "Parameters:",
66
+ "- response: (required) The textual message to deliver to the user. Markdown is supported.",
67
+ "",
68
+ "Example (correct — assistant text is empty, all content is inside the tool call):",
69
+ "{ \"response\": \"I looked at the two options and I think Option A is cleaner because it avoids the extra cache lookup.\" }",
70
+ ].join("\n")
71
+
72
+ export const displayResponse = (config: DisplayResponseConfig = {}) =>
73
+ defineTool({
74
+ name: config.name ?? "display_response",
75
+ description: config.description ?? DEFAULT_DESCRIPTION,
76
+ parameters: Parameters,
77
+ success: Success,
78
+ execute: async (input) => ({ response: input.response }),
79
+ })
@@ -0,0 +1,31 @@
1
+ import { defineTool } from "@tinyweb-agent-framework/agent"
2
+ import { Effect, Schema } from "effect"
3
+ import type { FileStorage } from "./shared/storage"
4
+
5
+ export type FileReadConfig = {
6
+ storage: FileStorage
7
+ name?: string
8
+ description?: string
9
+ }
10
+
11
+ const Parameters = Schema.Struct({
12
+ key: Schema.String,
13
+ })
14
+
15
+ const Success = Schema.Struct({
16
+ content: Schema.String,
17
+ bytes: Schema.Number,
18
+ })
19
+
20
+ export const fileRead = (config: FileReadConfig) =>
21
+ defineTool({
22
+ name: config.name ?? "file_read",
23
+ description: config.description ?? "Read a file from configured storage by key. Returns UTF-8 text content.",
24
+ parameters: Parameters,
25
+ success: Success,
26
+ execute: async (input) => {
27
+ const bytes = await Effect.runPromise(config.storage.read(input.key))
28
+ const content = new TextDecoder("utf-8").decode(bytes)
29
+ return { content, bytes: bytes.byteLength }
30
+ },
31
+ })
@@ -0,0 +1,33 @@
1
+ import { defineTool } from "@tinyweb-agent-framework/agent"
2
+ import { Effect, Schema } from "effect"
3
+ import type { FileStorage } from "./shared/storage"
4
+
5
+ export type FileWriteConfig = {
6
+ storage: FileStorage
7
+ name?: string
8
+ description?: string
9
+ }
10
+
11
+ const Parameters = Schema.Struct({
12
+ key: Schema.String,
13
+ content: Schema.String,
14
+ })
15
+
16
+ const Success = Schema.Struct({
17
+ key: Schema.String,
18
+ url: Schema.optional(Schema.String),
19
+ bytes: Schema.Number,
20
+ })
21
+
22
+ export const fileWrite = (config: FileWriteConfig) =>
23
+ defineTool({
24
+ name: config.name ?? "file_write",
25
+ description: config.description ?? "Write a UTF-8 text file to configured storage under the given key.",
26
+ parameters: Parameters,
27
+ success: Success,
28
+ execute: async (input) => {
29
+ const bytes = new TextEncoder().encode(input.content)
30
+ const result = await Effect.runPromise(config.storage.write(input.key, bytes))
31
+ return { key: input.key, url: result.url, bytes: bytes.byteLength }
32
+ },
33
+ })
@@ -0,0 +1,58 @@
1
+ import { defineTool } from "@tinyweb-agent-framework/agent"
2
+ import { Schema } from "effect"
3
+ import { postJson } from "./shared/http"
4
+
5
+ export type ImageDescribeConfig = {
6
+ apiKey: string
7
+ baseURL?: string
8
+ model?: string
9
+ name?: string
10
+ description?: string
11
+ }
12
+
13
+ const Parameters = Schema.Struct({
14
+ imageUrl: Schema.String,
15
+ question: Schema.optional(Schema.String),
16
+ })
17
+
18
+ const Success = Schema.Struct({
19
+ description: Schema.String,
20
+ })
21
+
22
+ type ChatMessage = {
23
+ role: "user"
24
+ content: Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }>
25
+ }
26
+
27
+ type ChatResponse = {
28
+ choices: Array<{ message: { content?: string } }>
29
+ }
30
+
31
+ export const imageDescribe = (config: ImageDescribeConfig) =>
32
+ defineTool({
33
+ name: config.name ?? "image_describe",
34
+ description: config.description ?? "Describe the contents of an image. Pass a question to ask something specific.",
35
+ parameters: Parameters,
36
+ success: Success,
37
+ execute: async (input) => {
38
+ const baseURL = (config.baseURL ?? "https://api.openai.com/v1").replace(/\/$/, "")
39
+ const model = config.model ?? "gpt-4o-mini"
40
+ const question = input.question ?? "Describe this image in 2-3 sentences."
41
+ const messages: ChatMessage[] = [
42
+ {
43
+ role: "user",
44
+ content: [
45
+ { type: "text", text: question },
46
+ { type: "image_url", image_url: { url: input.imageUrl } },
47
+ ],
48
+ },
49
+ ]
50
+ const data = await postJson<ChatResponse>(
51
+ `${baseURL}/chat/completions`,
52
+ { model, messages, max_tokens: 600 },
53
+ { headers: { authorization: `Bearer ${config.apiKey}` } },
54
+ )
55
+ const text = data.choices[0]?.message?.content ?? ""
56
+ return { description: text.trim() }
57
+ },
58
+ })
@@ -0,0 +1,74 @@
1
+ import { defineTool } from "@tinyweb-agent-framework/agent"
2
+ import { Effect, Schema } from "effect"
3
+ import { fetchBytes } from "./shared/http"
4
+ import type { FileStorage } from "./shared/storage"
5
+
6
+ export type ImageEditConfig = {
7
+ apiKey: string
8
+ model?: string
9
+ storage?: FileStorage
10
+ storagePrefix?: string
11
+ name?: string
12
+ description?: string
13
+ }
14
+
15
+ const Parameters = Schema.Struct({
16
+ imageUrl: Schema.String,
17
+ prompt: Schema.String,
18
+ maskUrl: Schema.optional(Schema.String),
19
+ size: Schema.optional(Schema.String),
20
+ })
21
+
22
+ const Success = Schema.Struct({
23
+ url: Schema.String,
24
+ storageKey: Schema.optional(Schema.String),
25
+ })
26
+
27
+ type OpenAIImageData = { url?: string; b64_json?: string }
28
+ type OpenAIImageResponse = { data: OpenAIImageData[] }
29
+
30
+ const toBlob = async (url: string): Promise<Blob> => {
31
+ const bytes = await fetchBytes(url)
32
+ return new Blob([bytes])
33
+ }
34
+
35
+ export const imageEdit = (config: ImageEditConfig) =>
36
+ defineTool({
37
+ name: config.name ?? "image_edit",
38
+ description: config.description ?? "Edit an image using a text prompt (and optional mask). Returns the edited image URL.",
39
+ parameters: Parameters,
40
+ success: Success,
41
+ execute: async (input) => {
42
+ const form = new FormData()
43
+ form.append("model", config.model ?? "gpt-image-1")
44
+ form.append("prompt", input.prompt)
45
+ const imageBlob = await toBlob(input.imageUrl)
46
+ form.append("image", imageBlob, "image.png")
47
+ if (input.maskUrl) {
48
+ const maskBlob = await toBlob(input.maskUrl)
49
+ form.append("mask", maskBlob, "mask.png")
50
+ }
51
+ if (input.size) form.append("size", input.size)
52
+ const res = await fetch("https://api.openai.com/v1/images/edits", {
53
+ method: "POST",
54
+ headers: { authorization: `Bearer ${config.apiKey}` },
55
+ body: form,
56
+ })
57
+ if (!res.ok) {
58
+ const body = await res.text().catch(() => "")
59
+ throw new Error(`OpenAI image edit failed: HTTP ${res.status}: ${body.slice(0, 500)}`)
60
+ }
61
+ const data = (await res.json()) as OpenAIImageResponse
62
+ const first = data.data[0]
63
+ if (!first) throw new Error("OpenAI returned no image data")
64
+ const url = first.url ?? (first.b64_json ? `data:image/png;base64,${first.b64_json}` : "")
65
+ if (!url) throw new Error("OpenAI image_edit response missing url and b64_json")
66
+ if (!config.storage || url.startsWith("data:")) {
67
+ return { url, storageKey: undefined }
68
+ }
69
+ const bytes = await fetchBytes(url)
70
+ const key = `${config.storagePrefix ?? "images"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`
71
+ const written = await Effect.runPromise(config.storage.write(key, bytes))
72
+ return { url: written.url ?? url, storageKey: key }
73
+ },
74
+ })
@@ -0,0 +1,102 @@
1
+ import { defineTool } from "@tinyweb-agent-framework/agent"
2
+ import { Effect, Schema } from "effect"
3
+ import { fetchBytes, postJson } from "./shared/http"
4
+ import type { FileStorage } from "./shared/storage"
5
+
6
+ export type ImageGenProvider = "openai" | "replicate"
7
+
8
+ export type ImageGenerateConfig = {
9
+ provider: ImageGenProvider
10
+ apiKey: string
11
+ model?: string
12
+ storage?: FileStorage
13
+ storagePrefix?: string
14
+ name?: string
15
+ description?: string
16
+ }
17
+
18
+ const Parameters = Schema.Struct({
19
+ prompt: Schema.String,
20
+ size: Schema.optional(Schema.String),
21
+ n: Schema.optional(Schema.Number),
22
+ })
23
+
24
+ const Success = Schema.Struct({
25
+ url: Schema.String,
26
+ storageKey: Schema.optional(Schema.String),
27
+ })
28
+
29
+ type ImageInput = Schema.Schema.Type<typeof Parameters>
30
+
31
+ type OpenAIImageData = { url?: string; b64_json?: string }
32
+ type OpenAIImageResponse = { data: OpenAIImageData[] }
33
+ type ReplicatePrediction = { id: string; status: string; output?: string | string[]; error?: string | null; urls?: { get?: string } }
34
+
35
+ const generateOpenAI = async (apiKey: string, model: string, input: ImageInput): Promise<string> => {
36
+ const data = await postJson<OpenAIImageResponse>(
37
+ "https://api.openai.com/v1/images/generations",
38
+ { model, prompt: input.prompt, size: input.size, n: input.n ?? 1 },
39
+ { headers: { authorization: `Bearer ${apiKey}` } },
40
+ )
41
+ const first = data.data[0]
42
+ if (!first) throw new Error("OpenAI returned no image data")
43
+ if (first.url) return first.url
44
+ if (first.b64_json) return `data:image/png;base64,${first.b64_json}`
45
+ throw new Error("OpenAI image response missing url and b64_json")
46
+ }
47
+
48
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
49
+
50
+ const generateReplicate = async (apiKey: string, model: string, input: ImageInput): Promise<string> => {
51
+ const initial = await postJson<ReplicatePrediction>(
52
+ "https://api.replicate.com/v1/predictions",
53
+ { version: model, input: { prompt: input.prompt } },
54
+ { headers: { authorization: `Token ${apiKey}` } },
55
+ )
56
+ let current = initial
57
+ const pollUrl = initial.urls?.get
58
+ if (!pollUrl) throw new Error("Replicate prediction missing poll url")
59
+ const deadline = Date.now() + 120_000
60
+ while (current.status !== "succeeded" && current.status !== "failed" && current.status !== "canceled") {
61
+ if (Date.now() > deadline) throw new Error("Replicate timeout after 120s")
62
+ await sleep(1500)
63
+ const r = await fetch(pollUrl, { headers: { authorization: `Token ${apiKey}` } })
64
+ if (!r.ok) throw new Error(`Replicate poll failed: HTTP ${r.status}`)
65
+ current = (await r.json()) as ReplicatePrediction
66
+ }
67
+ if (current.status !== "succeeded") throw new Error(`Replicate ${current.status}: ${current.error ?? "unknown"}`)
68
+ const output = current.output
69
+ if (Array.isArray(output)) return output[0] ?? ""
70
+ return output ?? ""
71
+ }
72
+
73
+ const generate = (provider: ImageGenProvider, apiKey: string, model: string, input: ImageInput): Promise<string> => {
74
+ if (provider === "openai") return generateOpenAI(apiKey, model, input)
75
+ if (provider === "replicate") return generateReplicate(apiKey, model, input)
76
+ throw new Error(`Unknown image_generate provider: ${provider as string}`)
77
+ }
78
+
79
+ const defaultModel = (provider: ImageGenProvider): string => {
80
+ if (provider === "openai") return "gpt-image-1"
81
+ return "black-forest-labs/flux-schnell"
82
+ }
83
+
84
+ export const imageGenerate = (config: ImageGenerateConfig) =>
85
+ defineTool({
86
+ name: config.name ?? "image_generate",
87
+ description: config.description ?? "Generate an image from a prompt. Returns the image URL (and storage key if storage configured).",
88
+ parameters: Parameters,
89
+ success: Success,
90
+ execute: async (input) => {
91
+ const model = config.model ?? defaultModel(config.provider)
92
+ const url = await generate(config.provider, config.apiKey, model, input)
93
+ if (!config.storage || url.startsWith("data:")) {
94
+ return { url, storageKey: undefined }
95
+ }
96
+ const bytes = await fetchBytes(url)
97
+ const ext = url.includes(".webp") ? "webp" : url.includes(".jpg") || url.includes(".jpeg") ? "jpg" : "png"
98
+ const key = `${config.storagePrefix ?? "images"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`
99
+ const result = await Effect.runPromise(config.storage.write(key, bytes))
100
+ return { url: result.url ?? url, storageKey: key }
101
+ },
102
+ })