@anvia/extensions 0.0.0-stage → 0.2.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 (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -2
  3. package/dist/guardrails/index.d.ts +2 -0
  4. package/dist/guardrails/index.js +4 -0
  5. package/dist/guardrails/length.js +53 -0
  6. package/dist/guardrails/length.js.map +1 -0
  7. package/dist/guardrails/llm-judge.js +91 -0
  8. package/dist/guardrails/llm-judge.js.map +1 -0
  9. package/dist/guardrails/redaction-guardrails.js +92 -0
  10. package/dist/guardrails/redaction-guardrails.js.map +1 -0
  11. package/dist/hooks/audit.js +77 -0
  12. package/dist/hooks/audit.js.map +1 -0
  13. package/dist/hooks/console.js +45 -0
  14. package/dist/hooks/console.js.map +1 -0
  15. package/dist/hooks/index.d.ts +2 -0
  16. package/dist/hooks/index.js +4 -0
  17. package/dist/hooks/usage.js +88 -0
  18. package/dist/hooks/usage.js.map +1 -0
  19. package/dist/index-Bd0LrPbr.d.ts +86 -0
  20. package/dist/index-Bd0LrPbr.d.ts.map +1 -0
  21. package/dist/index-Bov_OeIz.d.ts +20 -0
  22. package/dist/index-Bov_OeIz.d.ts.map +1 -0
  23. package/dist/index-CzQBvrEU.d.ts +29 -0
  24. package/dist/index-CzQBvrEU.d.ts.map +1 -0
  25. package/dist/index-D4FdbT72.d.ts +23 -0
  26. package/dist/index-D4FdbT72.d.ts.map +1 -0
  27. package/dist/index-DC6th6Lq.d.ts +23 -0
  28. package/dist/index-DC6th6Lq.d.ts.map +1 -0
  29. package/dist/index-NVtYgz_h.d.ts +72 -0
  30. package/dist/index-NVtYgz_h.d.ts.map +1 -0
  31. package/dist/index-_OYHBsgm.d.ts +64 -0
  32. package/dist/index-_OYHBsgm.d.ts.map +1 -0
  33. package/dist/index-tDVrZS31.d.ts +26 -0
  34. package/dist/index-tDVrZS31.d.ts.map +1 -0
  35. package/dist/index.d.ts +10 -0
  36. package/dist/index.js +16 -0
  37. package/dist/internal/pattern-redaction.js +46 -0
  38. package/dist/internal/pattern-redaction.js.map +1 -0
  39. package/dist/internal/truncate.js +23 -0
  40. package/dist/internal/truncate.js.map +1 -0
  41. package/dist/internal/url-safety.js +383 -0
  42. package/dist/internal/url-safety.js.map +1 -0
  43. package/dist/middlewares/index.d.ts +2 -0
  44. package/dist/middlewares/index.js +3 -0
  45. package/dist/middlewares/output-limit.js +91 -0
  46. package/dist/middlewares/output-limit.js.map +1 -0
  47. package/dist/middlewares/redaction.js +208 -0
  48. package/dist/middlewares/redaction.js.map +1 -0
  49. package/dist/tools/cache.js +98 -0
  50. package/dist/tools/cache.js.map +1 -0
  51. package/dist/tools/fs/index.d.ts +2 -0
  52. package/dist/tools/fs/index.js +299 -0
  53. package/dist/tools/fs/index.js.map +1 -0
  54. package/dist/tools/fs/path-safety.js +75 -0
  55. package/dist/tools/fs/path-safety.js.map +1 -0
  56. package/dist/tools/http/index.d.ts +2 -0
  57. package/dist/tools/http/index.js +111 -0
  58. package/dist/tools/http/index.js.map +1 -0
  59. package/dist/tools/index.d.ts +19 -0
  60. package/dist/tools/index.d.ts.map +1 -0
  61. package/dist/tools/index.js +8 -0
  62. package/dist/tools/todo/index.d.ts +2 -0
  63. package/dist/tools/todo/index.js +68 -0
  64. package/dist/tools/todo/index.js.map +1 -0
  65. package/dist/tools/web-fetch/html-to-text.js +67 -0
  66. package/dist/tools/web-fetch/html-to-text.js.map +1 -0
  67. package/dist/tools/web-fetch/index.d.ts +2 -0
  68. package/dist/tools/web-fetch/index.js +74 -0
  69. package/dist/tools/web-fetch/index.js.map +1 -0
  70. package/dist/tools/web-search/index.d.ts +2 -0
  71. package/dist/tools/web-search/index.js +52 -0
  72. package/dist/tools/web-search/index.js.map +1 -0
  73. package/dist/tools/web-search/providers.js +234 -0
  74. package/dist/tools/web-search/providers.js.map +1 -0
  75. package/dist/tools/web-search/types.js +1 -0
  76. package/dist/url-safety-tHZmtyx2.d.ts +11 -0
  77. package/dist/url-safety-tHZmtyx2.d.ts.map +1 -0
  78. package/package.json +81 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/tools/fs/index.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n type AnyTool,\n createTool,\n createToolkit,\n type Toolkit,\n type ToolkitOptions,\n} from \"@anvia/core/tool\";\nimport { z } from \"zod\";\nimport { truncateText } from \"../../internal/truncate\";\nimport {\n resolveCanonicalRoot,\n resolveSafeDeleteTarget,\n resolveSafePath,\n toRelativePosixPath,\n} from \"./path-safety\";\n\nexport type FilesystemReadToolName = \"read_file\" | \"list_files\" | \"grep\";\nexport type FilesystemWriteToolName = \"write_file\" | \"edit_file\" | \"delete_file\";\nexport type FilesystemToolName = FilesystemReadToolName | FilesystemWriteToolName;\n\nexport type FilesystemOptions = ToolkitOptions<FilesystemToolName> & {\n /** Directory all file operations are sandboxed to. */\n rootDir: string;\n /** When true, only read_file, list_files, and grep are registered. Default false. */\n readOnly?: boolean | undefined;\n /** Maximum file size in bytes for read/write/grep operations. Default 512_000 (512 KB). */\n maxFileBytes?: number | undefined;\n /** Maximum entries returned by list_files. Default 200. */\n maxEntries?: number | undefined;\n /** Maximum matches returned by grep. Default 100. */\n maxMatches?: number | undefined;\n /** Maximum files scanned by grep before truncating. Default 5_000. */\n maxScannedFiles?: number | undefined;\n /** Maximum characters per matched line in grep output. Default 500. */\n maxMatchLineChars?: number | undefined;\n};\n\nconst DEFAULT_INSTRUCTIONS =\n \"Use filesystem tools to inspect and edit files inside the workspace root. Read files before editing them, and keep paths relative to the workspace root.\";\n\nconst READONLY_INSTRUCTIONS =\n \"Use filesystem tools to inspect files inside the workspace root. Keep paths relative to the workspace root.\";\n\nexport function filesystem(options: FilesystemOptions): Toolkit {\n const maxFileBytes = options.maxFileBytes ?? 512_000;\n const maxEntries = options.maxEntries ?? 200;\n const maxMatches = options.maxMatches ?? 100;\n const maxScannedFiles = options.maxScannedFiles ?? 5_000;\n const maxMatchLineChars = options.maxMatchLineChars ?? 500;\n const readOnly = options.readOnly ?? false;\n\n if (options.rootDir.trim().length === 0) {\n throw new TypeError(\"filesystem rootDir must not be empty.\");\n }\n\n if (!Number.isSafeInteger(maxFileBytes) || maxFileBytes <= 0) {\n throw new RangeError(\"filesystem maxFileBytes must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxEntries) || maxEntries <= 0) {\n throw new RangeError(\"filesystem maxEntries must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxMatches) || maxMatches <= 0) {\n throw new RangeError(\"filesystem maxMatches must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxScannedFiles) || maxScannedFiles <= 0) {\n throw new RangeError(\"filesystem maxScannedFiles must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxMatchLineChars) || maxMatchLineChars <= 0) {\n throw new RangeError(\"filesystem maxMatchLineChars must be a positive safe integer.\");\n }\n\n let rootPromise: Promise<string> | undefined;\n const getRoot = (): Promise<string> => {\n if (rootPromise === undefined) {\n const pending = resolveCanonicalRoot(options.rootDir).catch((error) => {\n if (rootPromise === pending) rootPromise = undefined;\n\n throw error;\n });\n rootPromise = pending;\n }\n\n return rootPromise;\n };\n\n const readFileTool = createTool({\n name: \"read_file\",\n description: \"Read a UTF-8 text file inside the workspace, with optional 1-based line paging.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Workspace-relative path to the file.\"),\n offset: z.number().int().min(1).optional().describe(\"1-based starting line number.\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(2_000)\n .optional()\n .describe(\"Maximum number of lines to return.\"),\n }),\n handler: async (args) => {\n const root = await getRoot();\n const target = await resolveSafePath(root, args.path);\n const info = await stat(target);\n\n if (!info.isFile()) {\n throw new Error(`\"${args.path}\" is not a file.`);\n }\n\n if (info.size > maxFileBytes) {\n throw new Error(\n `File \"${args.path}\" (${info.size} bytes) exceeds maxFileBytes (${maxFileBytes}).`,\n );\n }\n\n const raw = await readFile(target, \"utf8\");\n const allLines = raw.split(/\\r?\\n/);\n const startLine = args.offset ?? 1;\n const startIndex = startLine - 1;\n const endIndex =\n args.limit === undefined\n ? allLines.length\n : Math.min(allLines.length, startIndex + args.limit);\n const slice = allLines.slice(startIndex, endIndex);\n\n return {\n path: toRelativePosixPath(root, target),\n totalLines: allLines.length,\n startLine,\n endLine: slice.length === 0 ? startLine : startIndex + slice.length,\n truncated: endIndex < allLines.length,\n content: slice.join(\"\\n\"),\n };\n },\n });\n\n const listFilesTool = createTool({\n name: \"list_files\",\n description: \"List files and directories inside the workspace.\",\n inputSchema: z.object({\n path: z.string().optional().describe('Workspace-relative directory path (defaults to \".\").'),\n recursive: z\n .boolean()\n .optional()\n .describe(\"Whether to walk subdirectories recursively. Default false.\"),\n }),\n handler: async (args, context) => {\n throwIfAborted(context.abortSignal);\n const root = await getRoot();\n const dir = await resolveSafePath(root, args.path ?? \".\");\n const info = await stat(dir);\n\n if (!info.isDirectory()) {\n throw new Error(`\"${args.path ?? \".\"}\" is not a directory.`);\n }\n\n const entries: Array<{ path: string; type: \"file\" | \"directory\" | \"other\" }> = [];\n let truncated = false;\n\n const walk = async (currentDir: string): Promise<void> => {\n throwIfAborted(context.abortSignal);\n const items = await readdir(currentDir, { withFileTypes: true }).catch((error) => {\n if (isSkippableFsError(error)) return [];\n\n throw error;\n });\n items.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const item of items) {\n throwIfAborted(context.abortSignal);\n\n if (entries.length >= maxEntries) {\n truncated = true;\n return;\n }\n\n const fullPath = path.join(currentDir, item.name);\n let type: \"file\" | \"directory\" | \"other\" = \"other\";\n\n if (item.isDirectory()) {\n type = \"directory\";\n } else if (item.isFile()) {\n type = \"file\";\n }\n\n entries.push({ path: toRelativePosixPath(root, fullPath), type });\n\n if (args.recursive && item.isDirectory()) {\n await walk(fullPath);\n }\n }\n };\n\n await walk(dir);\n\n return {\n path: toRelativePosixPath(root, dir),\n entries,\n truncated,\n };\n },\n });\n\n const grepTool = createTool({\n name: \"grep\",\n description: \"Search for a text or regular expression pattern across files in the workspace.\",\n inputSchema: z.object({\n pattern: z.string().min(1).describe(\"Substring or regex pattern to search for.\"),\n path: z\n .string()\n .optional()\n .describe('Workspace-relative file or directory to search (defaults to \".\").'),\n regex: z\n .boolean()\n .optional()\n .describe(\n \"Treat pattern as a regular expression instead of a literal string. Default false.\",\n ),\n caseSensitive: z.boolean().optional().describe(\"Case-sensitive match. Default true.\"),\n }),\n handler: async (args, context) => {\n throwIfAborted(context.abortSignal);\n const root = await getRoot();\n const target = await resolveSafePath(root, args.path ?? \".\");\n const targetStat = await stat(target);\n const caseSensitive = args.caseSensitive ?? true;\n const matcher = buildLineMatcher(args.pattern, args.regex ?? false, caseSensitive);\n\n const matches: Array<{ path: string; line: number; text: string }> = [];\n let scannedFiles = 0;\n let truncated = false;\n\n const scanFile = async (filePath: string): Promise<void> => {\n throwIfAborted(context.abortSignal);\n\n if (matches.length >= maxMatches || scannedFiles >= maxScannedFiles) {\n truncated = true;\n return;\n }\n\n const fileInfo = await stat(filePath).catch((error) => {\n if (isSkippableFsError(error)) return undefined;\n\n throw error;\n });\n\n if (fileInfo === undefined || !fileInfo.isFile() || fileInfo.size > maxFileBytes) return;\n\n scannedFiles += 1;\n\n const buffer = await readFile(filePath).catch((error) => {\n if (isSkippableFsError(error)) return undefined;\n\n throw error;\n });\n\n if (buffer === undefined || buffer.includes(0)) return;\n\n const lines = buffer.toString(\"utf8\").split(/\\r?\\n/);\n const rel = toRelativePosixPath(root, filePath);\n\n for (let i = 0; i < lines.length; i++) {\n const lineText = lines[i]!;\n\n if (matcher(lineText)) {\n if (matches.length >= maxMatches) {\n truncated = true;\n return;\n }\n\n const clipped = truncateText(lineText, maxMatchLineChars, \"...\").text;\n matches.push({ path: rel, line: i + 1, text: clipped });\n }\n }\n };\n\n const walkDir = async (dirPath: string): Promise<void> => {\n throwIfAborted(context.abortSignal);\n const items = await readdir(dirPath, { withFileTypes: true }).catch((error) => {\n if (isSkippableFsError(error)) return [];\n\n throw error;\n });\n items.sort((a, b) => a.name.localeCompare(b.name));\n\n for (const item of items) {\n throwIfAborted(context.abortSignal);\n\n if (matches.length >= maxMatches || scannedFiles >= maxScannedFiles) {\n truncated = true;\n return;\n }\n\n if (item.name === \".git\" || item.name === \"node_modules\") continue;\n\n const childPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n await walkDir(childPath);\n } else if (item.isFile()) {\n await scanFile(childPath);\n }\n }\n };\n\n if (targetStat.isFile()) {\n await scanFile(target);\n } else if (targetStat.isDirectory()) {\n await walkDir(target);\n }\n\n return { matches, truncated };\n },\n });\n\n const tools: AnyTool[] = [readFileTool, listFilesTool, grepTool];\n\n if (!readOnly) {\n const writeFileTool = createTool({\n name: \"write_file\",\n description: \"Create or overwrite a UTF-8 text file inside the workspace.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Workspace-relative path to write.\"),\n content: z.string().describe(\"Full UTF-8 file contents to write.\"),\n }),\n handler: async (args) => {\n const bytes = Buffer.byteLength(args.content, \"utf8\");\n\n if (bytes > maxFileBytes) {\n throw new Error(`Content (${bytes} bytes) exceeds maxFileBytes (${maxFileBytes}).`);\n }\n\n const root = await getRoot();\n const target = await resolveSafePath(root, args.path, { allowMissing: true });\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, args.content, \"utf8\");\n\n return {\n path: toRelativePosixPath(root, target),\n bytesWritten: bytes,\n };\n },\n });\n\n const editFileTool = createTool({\n name: \"edit_file\",\n description: \"Replace an exact text block in an existing UTF-8 file inside the workspace.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Workspace-relative path to edit.\"),\n oldText: z.string().min(1).describe(\"Exact text to search for.\"),\n newText: z.string().describe(\"Replacement text.\"),\n replaceAll: z\n .boolean()\n .optional()\n .describe(\"Replace all occurrences instead of requiring a unique match. Default false.\"),\n }),\n handler: async (args) => {\n const root = await getRoot();\n const target = await resolveSafePath(root, args.path);\n const info = await stat(target);\n\n if (!info.isFile()) {\n throw new Error(`\"${args.path}\" is not a file.`);\n }\n\n if (info.size > maxFileBytes) {\n throw new Error(\n `File \"${args.path}\" (${info.size} bytes) exceeds maxFileBytes (${maxFileBytes}).`,\n );\n }\n\n const existing = await readFile(target, \"utf8\");\n const occurrences = countOccurrences(existing, args.oldText);\n\n if (occurrences === 0) {\n throw new Error(`oldText was not found in \"${args.path}\".`);\n }\n\n if (occurrences > 1 && !args.replaceAll) {\n throw new Error(\n `oldText matched ${occurrences} times in \"${args.path}\". Provide more context or set replaceAll: true.`,\n );\n }\n\n const updated = args.replaceAll\n ? existing.split(args.oldText).join(args.newText)\n : existing.replace(args.oldText, () => args.newText);\n const bytes = Buffer.byteLength(updated, \"utf8\");\n\n if (bytes > maxFileBytes) {\n throw new Error(`Edited file (${bytes} bytes) exceeds maxFileBytes (${maxFileBytes}).`);\n }\n\n await writeFile(target, updated, \"utf8\");\n return {\n path: toRelativePosixPath(root, target),\n replacements: args.replaceAll ? occurrences : 1,\n };\n },\n });\n\n const deleteFileTool = createTool({\n name: \"delete_file\",\n description: \"Delete a file inside the workspace.\",\n inputSchema: z.object({\n path: z.string().min(1).describe(\"Workspace-relative path to the file to delete.\"),\n }),\n requiresApproval: { reason: \"Deleting a workspace file requires approval.\" },\n handler: async (args) => {\n const root = await getRoot();\n const target = await resolveSafeDeleteTarget(root, args.path);\n await rm(target);\n return {\n path: toRelativePosixPath(root, target),\n deleted: true,\n };\n },\n });\n\n tools.push(writeFileTool, editFileTool, deleteFileTool);\n }\n\n return createToolkit<FilesystemToolName>(\n {\n name: \"filesystem\",\n tools,\n instructions: readOnly ? READONLY_INSTRUCTIONS : DEFAULT_INSTRUCTIONS,\n },\n options,\n );\n}\n\nfunction buildLineMatcher(\n pattern: string,\n useRegex: boolean,\n caseSensitive: boolean,\n): (line: string) => boolean {\n if (useRegex) {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern, caseSensitive ? \"\" : \"i\");\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid grep regular expression \"${pattern}\": ${detail}`);\n }\n\n return (line) => regex.test(line);\n }\n\n if (caseSensitive) {\n return (line) => line.includes(pattern);\n }\n\n const needle = pattern.toLowerCase();\n return (line) => line.toLowerCase().includes(needle);\n}\n\nfunction countOccurrences(text: string, needle: string): number {\n let count = 0;\n let index = 0;\n while ((index = text.indexOf(needle, index)) !== -1) {\n count++;\n index += needle.length;\n }\n return count;\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new Error(\"Filesystem operation aborted.\");\n }\n}\n\nfunction isSkippableFsError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error)) return false;\n\n const code = (error as { code?: unknown }).code;\n return code === \"ENOENT\" || code === \"EACCES\" || code === \"EPERM\" || code === \"ENOTDIR\";\n}\n"],"mappings":";;;;;;;AAuCA,MAAM,uBACJ;AAEF,MAAM,wBACJ;AAEF,SAAgB,WAAW,SAAqC;CAC9D,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,kBAAkB,QAAQ,mBAAmB;CACnD,MAAM,oBAAoB,QAAQ,qBAAqB;CACvD,MAAM,WAAW,QAAQ,YAAY;CAErC,IAAI,QAAQ,QAAQ,KAAK,CAAC,CAAC,WAAW,GACpC,MAAM,IAAI,UAAU,uCAAuC;CAG7D,IAAI,CAAC,OAAO,cAAc,YAAY,KAAK,gBAAgB,GACzD,MAAM,IAAI,WAAW,0DAA0D;CAGjF,IAAI,CAAC,OAAO,cAAc,UAAU,KAAK,cAAc,GACrD,MAAM,IAAI,WAAW,wDAAwD;CAG/E,IAAI,CAAC,OAAO,cAAc,UAAU,KAAK,cAAc,GACrD,MAAM,IAAI,WAAW,wDAAwD;CAG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AAE,UAAU,QAAQ,OAAO;CAE9E,MAAM,OAAQ,MAA6B;CAC3C,OAAO,SAAS,YAAY,SAAS,YAAY,SAAS,WAAW,SAAS;AAChF"}
@@ -0,0 +1,75 @@
1
+ import { lstat, realpath, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ // src/tools/fs/path-safety.ts
4
+ async function resolveCanonicalRoot(rootDir) {
5
+ const trimmed = rootDir.trim();
6
+ if (trimmed.length === 0) throw new TypeError("filesystem rootDir must not be empty.");
7
+ const canonical = await realpath(path.resolve(trimmed));
8
+ if (!(await stat(canonical)).isDirectory()) throw new Error(`filesystem rootDir "${rootDir}" is not a directory.`);
9
+ return canonical;
10
+ }
11
+ async function resolveSafePath(canonicalRoot, requestedPath, options = {}) {
12
+ if (requestedPath.includes("\0")) throw new Error("Path must not contain null bytes.");
13
+ const normalizedInput = requestedPath.trim() === "" ? "." : requestedPath;
14
+ const candidate = path.resolve(canonicalRoot, normalizedInput);
15
+ if (!isPathWithinRoot(canonicalRoot, candidate)) throw new Error(`Path "${requestedPath}" escapes the configured rootDir.`);
16
+ try {
17
+ const resolved = await realpath(candidate);
18
+ if (!isPathWithinRoot(canonicalRoot, resolved)) throw new Error(`Path "${requestedPath}" resolves outside rootDir via symlink.`);
19
+ return resolved;
20
+ } catch (error) {
21
+ if (!options.allowMissing || !isNotFoundError(error)) throw error;
22
+ }
23
+ const missingSegments = [];
24
+ let cursor = candidate;
25
+ while (true) try {
26
+ const ancestorReal = await realpath(cursor);
27
+ if (!isPathWithinRoot(canonicalRoot, ancestorReal)) throw new Error(`Path "${requestedPath}" resolves outside rootDir via symlink.`);
28
+ const finalPath = path.resolve(ancestorReal, ...missingSegments.reverse());
29
+ if (!isPathWithinRoot(canonicalRoot, finalPath)) throw new Error(`Path "${requestedPath}" escapes the configured rootDir.`);
30
+ return finalPath;
31
+ } catch (error) {
32
+ if (!isNotFoundError(error)) throw error;
33
+ await assertNotDanglingSymlink(cursor, requestedPath);
34
+ const parent = path.dirname(cursor);
35
+ if (parent === cursor) throw new Error(`Path "${requestedPath}" escapes the configured rootDir.`);
36
+ missingSegments.push(path.basename(cursor));
37
+ cursor = parent;
38
+ }
39
+ }
40
+ async function resolveSafeDeleteTarget(canonicalRoot, requestedPath) {
41
+ if (requestedPath.includes("\0")) throw new Error("Path must not contain null bytes.");
42
+ const normalizedInput = requestedPath.trim();
43
+ if (normalizedInput.length === 0) throw new Error("Path must not be empty.");
44
+ const candidate = path.resolve(canonicalRoot, normalizedInput);
45
+ if (!isPathWithinRoot(canonicalRoot, candidate)) throw new Error(`Path "${requestedPath}" escapes the configured rootDir.`);
46
+ if (candidate === canonicalRoot) throw new Error("Refusing to delete workspace rootDir.");
47
+ const parentReal = await resolveSafePath(canonicalRoot, path.dirname(candidate));
48
+ const targetPath = path.join(parentReal, path.basename(candidate));
49
+ if (!isPathWithinRoot(canonicalRoot, targetPath) || targetPath === canonicalRoot) throw new Error(`Path "${requestedPath}" escapes the configured rootDir.`);
50
+ const entryStat = await lstat(targetPath);
51
+ if (entryStat.isSymbolicLink()) throw new Error(`Refusing to delete symlink "${requestedPath}".`);
52
+ if (!entryStat.isFile()) throw new Error(`"${requestedPath}" is not a file.`);
53
+ return targetPath;
54
+ }
55
+ function isPathWithinRoot(rootPath, targetPath) {
56
+ const relative = path.relative(rootPath, targetPath);
57
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
58
+ }
59
+ function toRelativePosixPath(rootPath, targetPath) {
60
+ const relative = path.relative(rootPath, targetPath);
61
+ return relative === "" ? "." : relative.split(path.sep).join("/");
62
+ }
63
+ async function assertNotDanglingSymlink(cursor, requestedPath) {
64
+ try {
65
+ if ((await lstat(cursor)).isSymbolicLink()) throw new Error(`Path "${requestedPath}" traverses a dangling symlink.`);
66
+ } catch (error) {
67
+ if (!isNotFoundError(error)) throw error;
68
+ }
69
+ }
70
+ function isNotFoundError(error) {
71
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
72
+ }
73
+ export { isPathWithinRoot, resolveCanonicalRoot, resolveSafeDeleteTarget, resolveSafePath, toRelativePosixPath };
74
+
75
+ //# sourceMappingURL=path-safety.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-safety.js","names":[],"sources":["../../../src/tools/fs/path-safety.ts"],"sourcesContent":["import { lstat, realpath, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function resolveCanonicalRoot(rootDir: string): Promise<string> {\n const trimmed = rootDir.trim();\n\n if (trimmed.length === 0) {\n throw new TypeError(\"filesystem rootDir must not be empty.\");\n }\n\n const canonical = await realpath(path.resolve(trimmed));\n const info = await stat(canonical);\n\n if (!info.isDirectory()) {\n throw new Error(`filesystem rootDir \"${rootDir}\" is not a directory.`);\n }\n\n return canonical;\n}\n\nexport async function resolveSafePath(\n canonicalRoot: string,\n requestedPath: string,\n options: { allowMissing?: boolean } = {},\n): Promise<string> {\n if (requestedPath.includes(\"\\0\")) {\n throw new Error(\"Path must not contain null bytes.\");\n }\n\n const normalizedInput = requestedPath.trim() === \"\" ? \".\" : requestedPath;\n const candidate = path.resolve(canonicalRoot, normalizedInput);\n\n if (!isPathWithinRoot(canonicalRoot, candidate)) {\n throw new Error(`Path \"${requestedPath}\" escapes the configured rootDir.`);\n }\n\n try {\n const resolved = await realpath(candidate);\n\n if (!isPathWithinRoot(canonicalRoot, resolved)) {\n throw new Error(`Path \"${requestedPath}\" resolves outside rootDir via symlink.`);\n }\n\n return resolved;\n } catch (error) {\n if (!options.allowMissing || !isNotFoundError(error)) {\n throw error;\n }\n }\n\n const missingSegments: string[] = [];\n let cursor = candidate;\n\n while (true) {\n try {\n const ancestorReal = await realpath(cursor);\n\n if (!isPathWithinRoot(canonicalRoot, ancestorReal)) {\n throw new Error(`Path \"${requestedPath}\" resolves outside rootDir via symlink.`);\n }\n\n const finalPath = path.resolve(ancestorReal, ...missingSegments.reverse());\n\n if (!isPathWithinRoot(canonicalRoot, finalPath)) {\n throw new Error(`Path \"${requestedPath}\" escapes the configured rootDir.`);\n }\n\n return finalPath;\n } catch (error) {\n if (!isNotFoundError(error)) {\n throw error;\n }\n\n await assertNotDanglingSymlink(cursor, requestedPath);\n\n const parent = path.dirname(cursor);\n\n if (parent === cursor) {\n throw new Error(`Path \"${requestedPath}\" escapes the configured rootDir.`);\n }\n\n missingSegments.push(path.basename(cursor));\n cursor = parent;\n }\n }\n}\n\nexport async function resolveSafeDeleteTarget(\n canonicalRoot: string,\n requestedPath: string,\n): Promise<string> {\n if (requestedPath.includes(\"\\0\")) {\n throw new Error(\"Path must not contain null bytes.\");\n }\n\n const normalizedInput = requestedPath.trim();\n\n if (normalizedInput.length === 0) {\n throw new Error(\"Path must not be empty.\");\n }\n\n const candidate = path.resolve(canonicalRoot, normalizedInput);\n\n if (!isPathWithinRoot(canonicalRoot, candidate)) {\n throw new Error(`Path \"${requestedPath}\" escapes the configured rootDir.`);\n }\n\n if (candidate === canonicalRoot) {\n throw new Error(\"Refusing to delete workspace rootDir.\");\n }\n\n const parentReal = await resolveSafePath(canonicalRoot, path.dirname(candidate));\n const targetPath = path.join(parentReal, path.basename(candidate));\n\n if (!isPathWithinRoot(canonicalRoot, targetPath) || targetPath === canonicalRoot) {\n throw new Error(`Path \"${requestedPath}\" escapes the configured rootDir.`);\n }\n\n const entryStat = await lstat(targetPath);\n\n if (entryStat.isSymbolicLink()) {\n throw new Error(`Refusing to delete symlink \"${requestedPath}\".`);\n }\n\n if (!entryStat.isFile()) {\n throw new Error(`\"${requestedPath}\" is not a file.`);\n }\n\n return targetPath;\n}\n\nexport function isPathWithinRoot(rootPath: string, targetPath: string): boolean {\n const relative = path.relative(rootPath, targetPath);\n return (\n relative === \"\" ||\n (relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))\n );\n}\n\nexport function toRelativePosixPath(rootPath: string, targetPath: string): string {\n const relative = path.relative(rootPath, targetPath);\n return relative === \"\" ? \".\" : relative.split(path.sep).join(\"/\");\n}\n\nasync function assertNotDanglingSymlink(cursor: string, requestedPath: string): Promise<void> {\n try {\n const entry = await lstat(cursor);\n\n if (entry.isSymbolicLink()) {\n throw new Error(`Path \"${requestedPath}\" traverses a dangling symlink.`);\n }\n } catch (error) {\n if (!isNotFoundError(error)) {\n throw error;\n }\n }\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === \"ENOENT\"\n );\n}\n"],"mappings":";;;AAGA,eAAsB,qBAAqB,SAAkC;CAC3E,MAAM,UAAU,QAAQ,KAAK;CAE7B,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,UAAU,uCAAuC;CAG7D,MAAM,YAAY,MAAM,SAAS,KAAK,QAAQ,OAAO,CAAC;CAGtD,IAAI,EAAC,MAFc,KAAK,SAAS,EAAA,CAEvB,YAAY,GACpB,MAAM,IAAI,MAAM,uBAAuB,QAAQ,sBAAsB;CAGvE,OAAO;AACT;AAEA,eAAsB,gBACpB,eACA,eACA,UAAsC,CAAC,GACtB;CACjB,IAAI,cAAc,SAAS,IAAI,GAC7B,MAAM,IAAI,MAAM,mCAAmC;CAGrD,MAAM,kBAAkB,cAAc,KAAK,MAAM,KAAK,MAAM;CAC5D,MAAM,YAAY,KAAK,QAAQ,eAAe,eAAe;CAE7D,IAAI,CAAC,iBAAiB,eAAe,SAAS,GAC5C,MAAM,IAAI,MAAM,SAAS,cAAc,kCAAkC;CAG3E,IAAI;EACF,MAAM,WAAW,MAAM,SAAS,SAAS;EAEzC,IAAI,CAAC,iBAAiB,eAAe,QAAQ,GAC3C,MAAM,IAAI,MAAM,SAAS,cAAc,wCAAwC;EAGjF,OAAO;CACT,SAAS,OAAO;EACd,IAAI,CAAC,QAAQ,gBAAgB,CAAC,gBAAgB,KAAK,GACjD,MAAM;CAEV;CAEA,MAAM,kBAA4B,CAAC;CACnC,IAAI,SAAS;CAEb,OAAO,MACL,IAAI;EACF,MAAM,eAAe,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G;CAGlE,IAAI,CAAC,UAAU,OAAO,GACpB,MAAM,IAAI,MAAM,IAAI,cAAc,iBAAiB;CAGrD,OAAO;AACT;AAEA,SAAgB,iBAAiB,UAAkB,YAA6B;CAC9E,MAAM,WAAW,KAAK,SAAS,UAAU,UAAU;CACnD,OACE,aAAa,MACZ,aAAa,QAAQ,CAAC,SAAS,WAAW,KAAK,KAAK,KAAK,KAAK,CAAC,KAAK,WAAW,QAAQ;AAE5F;AAEA,SAAgB,oBAAoB,UAAkB,YAA4B;CAChF,MAAM,WAAW,KAAK,SAAS,UAAU,UAAU;CACnD,OAAO,aAAa,KAAK,MAAM,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AAClE;AAEA,eAAe,yBAAyB,QAAgB,eAAsC;CAC5F,IAAI;EAGF,KAAI,MAFgB,MAAM,MAAM,EAAA,CAEtB,eAAe,GACvB,MAAM,IAAI,MAAM,SAAS,cAAc,gCAAgC;CAE3E,SAAS,OAAO;EACd,IAAI,CAAC,gBAAgB,KAAK,GACxB,MAAM;CAEV;AACF;AAEA,SAAS,gBAAgB,OAAyB;CAChD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C"}
@@ -0,0 +1,2 @@
1
+ import { i as httpClient, n as HttpClientToolName, r as HttpMethod, t as HttpClientOptions } from "../../index-D4FdbT72.js";
2
+ export { HttpClientOptions, HttpClientToolName, HttpMethod, httpClient };
@@ -0,0 +1,111 @@
1
+ import { truncateText } from "../../internal/truncate.js";
2
+ import { parseHttpUrl, safeFetch } from "../../internal/url-safety.js";
3
+ import { z } from "zod";
4
+ import { createTool, createToolkit } from "@anvia/core/tool";
5
+ // src/tools/http/index.ts
6
+ const ALL_METHODS = [
7
+ "GET",
8
+ "POST",
9
+ "PUT",
10
+ "PATCH",
11
+ "DELETE",
12
+ "HEAD"
13
+ ];
14
+ const DEFAULT_INSTRUCTIONS = "Use http_request to call configured HTTP endpoints. Authentication headers are injected automatically; do not include secrets in parameters.";
15
+ function httpClient(options) {
16
+ const parsedBase = options.baseUrl === void 0 ? void 0 : parseHttpUrl(options.baseUrl);
17
+ if (options.allowedHosts !== void 0 && options.allowedHosts.length === 0) throw new TypeError("httpClient allowedHosts must not be empty when specified.");
18
+ let allowedHosts;
19
+ let allowedOrigins = options.allowedOrigins;
20
+ if (options.allowedHosts !== void 0) allowedHosts = options.allowedHosts;
21
+ else if (parsedBase !== void 0) {
22
+ allowedHosts = [parsedBase.hostname];
23
+ allowedOrigins ??= [parsedBase.origin];
24
+ }
25
+ if (allowedHosts === void 0 || allowedHosts.length === 0) throw new TypeError("httpClient requires either baseUrl or at least one allowedHosts entry.");
26
+ const allowedMethods = (options.allowedMethods ?? ALL_METHODS).map((method) => method.toUpperCase());
27
+ if (allowedMethods.length === 0) throw new TypeError("httpClient allowedMethods must not be empty.");
28
+ const maxBytes = options.maxBytes ?? 512e3;
29
+ const maxChars = options.maxChars ?? 16e3;
30
+ const maxRedirects = options.maxRedirects ?? 3;
31
+ const timeoutMs = options.timeoutMs ?? 15e3;
32
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("httpClient maxBytes must be a positive safe integer.");
33
+ if (!Number.isSafeInteger(maxChars) || maxChars <= 0) throw new RangeError("httpClient maxChars must be a positive safe integer.");
34
+ if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0) throw new RangeError("httpClient maxRedirects must be a non-negative safe integer.");
35
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError("httpClient timeoutMs must be a positive finite number.");
36
+ const allowedMethodSet = new Set(allowedMethods);
37
+ const configHeaders = normalizeHeaders(options.headers);
38
+ const protectedHeaderNames = Object.keys(configHeaders);
39
+ const requestTool = createTool({
40
+ name: "http_request",
41
+ description: parsedBase !== void 0 ? `Send an HTTP request to ${parsedBase.origin} (methods: ${allowedMethods.join(", ")}).` : `Send an HTTP request to allowed hosts (${allowedHosts.join(", ")}; methods: ${allowedMethods.join(", ")}).`,
42
+ inputSchema: z.object({
43
+ method: z.enum(ALL_METHODS).default("GET").describe(`HTTP method. Allowed: ${allowedMethods.join(", ")}.`),
44
+ url: z.string().min(1).describe(parsedBase !== void 0 ? "Relative path (resolved against baseUrl) or full allowed http(s) URL." : "Full allowed http(s) URL."),
45
+ query: z.record(z.string(), z.string()).optional().describe("Optional query parameters."),
46
+ headers: z.record(z.string(), z.string()).optional().describe("Optional request headers (cannot override configured auth headers)."),
47
+ body: z.string().optional().describe("Optional request body string (e.g. JSON).")
48
+ }),
49
+ handler: async (args, context) => {
50
+ const method = args.method.toUpperCase();
51
+ if (!allowedMethodSet.has(method)) throw new Error(`HTTP method "${method}" is not allowed. Allowed methods: ${allowedMethods.join(", ")}.`);
52
+ const resolvedUrl = resolveRequestUrl(args.url, parsedBase);
53
+ if (args.query !== void 0) for (const [key, value] of Object.entries(args.query)) resolvedUrl.searchParams.set(key, value);
54
+ const mergedHeaders = mergeHeaders(args.headers, configHeaders);
55
+ const response = await safeFetch(resolvedUrl.toString(), {
56
+ method,
57
+ headers: mergedHeaders,
58
+ protectedHeaderNames,
59
+ allowedMethods,
60
+ body: args.body,
61
+ allowedHosts,
62
+ allowedOrigins,
63
+ blockedHosts: options.blockedHosts,
64
+ allowPrivateAddresses: options.allowPrivateAddresses,
65
+ resolveAddress: options.resolveAddress,
66
+ maxBytes,
67
+ maxRedirects,
68
+ timeoutMs,
69
+ abortSignal: context.abortSignal,
70
+ fetch: options.fetch
71
+ });
72
+ const { text, truncated } = truncateText(response.bodyText, maxChars);
73
+ return {
74
+ url: response.url,
75
+ status: response.status,
76
+ statusText: response.statusText,
77
+ headers: response.headers,
78
+ body: text,
79
+ truncated: truncated || response.bodyTruncated
80
+ };
81
+ }
82
+ });
83
+ return createToolkit({
84
+ name: "http-client",
85
+ tools: [requestTool],
86
+ instructions: DEFAULT_INSTRUCTIONS
87
+ }, options);
88
+ }
89
+ function resolveRequestUrl(raw, baseUrl) {
90
+ if (baseUrl !== void 0) try {
91
+ return new URL(raw, baseUrl);
92
+ } catch {
93
+ throw new Error(`Invalid request URL "${raw}".`);
94
+ }
95
+ return parseHttpUrl(raw);
96
+ }
97
+ function normalizeHeaders(headers) {
98
+ if (headers === void 0) return {};
99
+ const out = {};
100
+ for (const [key, value] of Object.entries(headers)) out[key.toLowerCase()] = value;
101
+ return out;
102
+ }
103
+ function mergeHeaders(modelHeaders, configHeaders) {
104
+ const merged = {};
105
+ if (modelHeaders !== void 0) for (const [key, value] of Object.entries(modelHeaders)) merged[key.toLowerCase()] = value;
106
+ for (const [key, value] of Object.entries(configHeaders)) merged[key] = value;
107
+ return merged;
108
+ }
109
+ export { httpClient };
110
+
111
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/tools/http/index.ts"],"sourcesContent":["import { createTool, createToolkit, type Toolkit, type ToolkitOptions } from \"@anvia/core/tool\";\nimport { z } from \"zod\";\nimport { truncateText } from \"../../internal/truncate\";\nimport { parseHttpUrl, safeFetch, type UrlSafetyOptions } from \"../../internal/url-safety\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"HEAD\";\nexport type HttpClientToolName = \"http_request\";\n\nexport type HttpClientOptions = ToolkitOptions<HttpClientToolName> &\n UrlSafetyOptions & {\n /** Optional base URL. Relative request paths resolve against it. */\n baseUrl?: string | undefined;\n /** HTTP methods the model may call. Defaults to GET, POST, PUT, PATCH, DELETE, HEAD. */\n allowedMethods?: readonly HttpMethod[] | undefined;\n /** Config-level headers (e.g. auth tokens) always injected and never overridden by the model. */\n headers?: Record<string, string> | undefined;\n /** Maximum response bytes read from the network. Default 512_000. */\n maxBytes?: number | undefined;\n /** Maximum characters returned to the model. Default 16_000. */\n maxChars?: number | undefined;\n /** Maximum HTTP redirects followed. Default 3. */\n maxRedirects?: number | undefined;\n /** Custom fetch implementation (useful for testing). */\n fetch?: typeof globalThis.fetch | undefined;\n };\n\nconst ALL_METHODS = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\"] as const;\nconst DEFAULT_INSTRUCTIONS =\n \"Use http_request to call configured HTTP endpoints. Authentication headers are injected automatically; do not include secrets in parameters.\";\n\nexport function httpClient(options: HttpClientOptions): Toolkit {\n const parsedBase = options.baseUrl === undefined ? undefined : parseHttpUrl(options.baseUrl);\n\n if (options.allowedHosts !== undefined && options.allowedHosts.length === 0) {\n throw new TypeError(\"httpClient allowedHosts must not be empty when specified.\");\n }\n\n let allowedHosts: readonly string[] | undefined;\n let allowedOrigins: readonly string[] | undefined = options.allowedOrigins;\n\n if (options.allowedHosts !== undefined) {\n allowedHosts = options.allowedHosts;\n } else if (parsedBase !== undefined) {\n allowedHosts = [parsedBase.hostname];\n allowedOrigins ??= [parsedBase.origin];\n }\n\n if (allowedHosts === undefined || allowedHosts.length === 0) {\n throw new TypeError(\"httpClient requires either baseUrl or at least one allowedHosts entry.\");\n }\n\n const allowedMethods = (options.allowedMethods ?? ALL_METHODS).map(\n (method) => method.toUpperCase() as HttpMethod,\n );\n\n if (allowedMethods.length === 0) {\n throw new TypeError(\"httpClient allowedMethods must not be empty.\");\n }\n\n const maxBytes = options.maxBytes ?? 512_000;\n const maxChars = options.maxChars ?? 16_000;\n const maxRedirects = options.maxRedirects ?? 3;\n const timeoutMs = options.timeoutMs ?? 15_000;\n\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new RangeError(\"httpClient maxBytes must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxChars) || maxChars <= 0) {\n throw new RangeError(\"httpClient maxChars must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0) {\n throw new RangeError(\"httpClient maxRedirects must be a non-negative safe integer.\");\n }\n\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\"httpClient timeoutMs must be a positive finite number.\");\n }\n\n const allowedMethodSet = new Set<string>(allowedMethods);\n const configHeaders = normalizeHeaders(options.headers);\n const protectedHeaderNames = Object.keys(configHeaders);\n\n const requestTool = createTool({\n name: \"http_request\",\n description:\n parsedBase !== undefined\n ? `Send an HTTP request to ${parsedBase.origin} (methods: ${allowedMethods.join(\", \")}).`\n : `Send an HTTP request to allowed hosts (${allowedHosts.join(\", \")}; methods: ${allowedMethods.join(\", \")}).`,\n inputSchema: z.object({\n method: z\n .enum(ALL_METHODS)\n .default(\"GET\")\n .describe(`HTTP method. Allowed: ${allowedMethods.join(\", \")}.`),\n url: z\n .string()\n .min(1)\n .describe(\n parsedBase !== undefined\n ? \"Relative path (resolved against baseUrl) or full allowed http(s) URL.\"\n : \"Full allowed http(s) URL.\",\n ),\n query: z.record(z.string(), z.string()).optional().describe(\"Optional query parameters.\"),\n headers: z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional request headers (cannot override configured auth headers).\"),\n body: z.string().optional().describe(\"Optional request body string (e.g. JSON).\"),\n }),\n handler: async (args, context) => {\n const method = args.method.toUpperCase();\n\n if (!allowedMethodSet.has(method)) {\n throw new Error(\n `HTTP method \"${method}\" is not allowed. Allowed methods: ${allowedMethods.join(\", \")}.`,\n );\n }\n\n const resolvedUrl = resolveRequestUrl(args.url, parsedBase);\n\n if (args.query !== undefined) {\n for (const [key, value] of Object.entries(args.query)) {\n resolvedUrl.searchParams.set(key, value);\n }\n }\n\n const mergedHeaders = mergeHeaders(args.headers, configHeaders);\n const response = await safeFetch(resolvedUrl.toString(), {\n method,\n headers: mergedHeaders,\n protectedHeaderNames,\n allowedMethods,\n body: args.body,\n allowedHosts,\n allowedOrigins,\n blockedHosts: options.blockedHosts,\n allowPrivateAddresses: options.allowPrivateAddresses,\n resolveAddress: options.resolveAddress,\n maxBytes,\n maxRedirects,\n timeoutMs,\n abortSignal: context.abortSignal,\n fetch: options.fetch,\n });\n\n const { text, truncated } = truncateText(response.bodyText, maxChars);\n return {\n url: response.url,\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n body: text,\n truncated: truncated || response.bodyTruncated,\n };\n },\n });\n\n return createToolkit<HttpClientToolName>(\n {\n name: \"http-client\",\n tools: [requestTool],\n instructions: DEFAULT_INSTRUCTIONS,\n },\n options,\n );\n}\n\nfunction resolveRequestUrl(raw: string, baseUrl: URL | undefined): URL {\n if (baseUrl !== undefined) {\n try {\n return new URL(raw, baseUrl);\n } catch {\n throw new Error(`Invalid request URL \"${raw}\".`);\n }\n }\n\n return parseHttpUrl(raw);\n}\n\nfunction normalizeHeaders(headers: Record<string, string> | undefined): Record<string, string> {\n if (headers === undefined) return {};\n\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n out[key.toLowerCase()] = value;\n }\n return out;\n}\n\nfunction mergeHeaders(\n modelHeaders: Record<string, string> | undefined,\n configHeaders: Record<string, string>,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n\n if (modelHeaders !== undefined) {\n for (const [key, value] of Object.entries(modelHeaders)) {\n merged[key.toLowerCase()] = value;\n }\n }\n\n for (const [key, value] of Object.entries(configHeaders)) {\n merged[key] = value;\n }\n\n return merged;\n}\n"],"mappings":";;;;;AA0BA,MAAM,cAAc;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAU;AAAM;AACpE,MAAM,uBACJ;AAEF,SAAgB,WAAW,SAAqC;CAC9D,MAAM,aAAa,QAAQ,YAAY,KAAA,IAAY,KAAA,IAAY,aAAa,QAAQ,OAAO;CAE3F,IAAI,QAAQ,iBAAiB,KAAA,KAAa,QAAQ,aAAa,WAAW,GACxE,MAAM,IAAI,UAAU,2DAA2D;CAGjF,IAAI;CACJ,IAAI,iBAAgD,QAAQ;CAE5D,IAAI,QAAQ,iBAAiB,KAAA,GAC3B,eAAe,QAAQ;MAClB,IAAI,eAAe,KAAA,GAAW;EACnC,eAAe,CAAC,WAAW,QAAQ;EACnC,mBAAmB,CAAC,WAAW,MAAM;CACvC;CAEA,IAAI,iBAAiB,KAAA,KAAa,aAAa,WAAW,GACxD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AQ;EACN,MAAM,IAAI,MAAM,wBAAwB,IAAI,GAAG;CACjD;CAGF,OAAO,aAAa,GAAG;AACzB;AAEA,SAAS,iBAAiB,SAAqE;CAC7F,IAAI,YAAY,KAAA,GAAW,OAAO,CAAC;CAEnC,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,IAAI,IAAI,YAAY,KAAK;CAE3B,OAAO;AACT;AAEA,SAAS,aACP,cACA,eACwB;CACxB,MAAM,SAAiC,CAAC;CAExC,IAAI,iBAAiB,KAAA,GACnB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,YAAY,GACpD,OAAO,IAAI,YAAY,KAAK;CAIhC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,aAAa,GACrD,OAAO,OAAO;CAGhB,OAAO;AACT"}
@@ -0,0 +1,19 @@
1
+ import { a as filesystem, i as FilesystemWriteToolName, n as FilesystemReadToolName, r as FilesystemToolName, t as FilesystemOptions } from "../index-DC6th6Lq.js";
2
+ import { i as httpClient, n as HttpClientToolName, r as HttpMethod, t as HttpClientOptions } from "../index-D4FdbT72.js";
3
+ import { a as TodoStore, i as TodoStatus, n as TodoItem, o as TodoToolName, r as TodoOptions, s as todo, t as InMemoryTodoStore } from "../index-tDVrZS31.js";
4
+ import { n as WebFetchToolName, r as webFetch, t as WebFetchOptions } from "../index-Bov_OeIz.js";
5
+ import { a as TavilyProviderOptions, c as searxng, d as WebSearchProvider, f as WebSearchProviderResponse, h as WebSearchToolName, i as SearxngProviderOptions, l as tavily, m as WebSearchResult, n as BraveProviderOptions, o as brave, p as WebSearchRequest, r as ExaProviderOptions, s as exa, t as webSearch, u as WebSearchOptions } from "../index-NVtYgz_h.js";
6
+ import { AnyTool, Toolkit } from "@anvia/core/tool";
7
+ export type ToolCacheOptions = {
8
+ /** Time-to-live for cached results in milliseconds. */
9
+ ttlMs: number;
10
+ /** Maximum number of cached entries (LRU eviction). Default 100. */
11
+ maxEntries?: number | undefined;
12
+ /** Optional allowlist of tool names to cache when wrapping a Toolkit. */
13
+ tools?: readonly string[] | undefined;
14
+ /** Optional custom clock for deterministic testing. */
15
+ now?: (() => number) | undefined;
16
+ };
17
+ export declare function withToolCache<T extends AnyTool | Toolkit>(target: T, options: ToolCacheOptions): T;
18
+ export { type BraveProviderOptions, type ExaProviderOptions, FilesystemOptions, FilesystemReadToolName, FilesystemToolName, FilesystemWriteToolName, HttpClientOptions, HttpClientToolName, HttpMethod, InMemoryTodoStore, type SearxngProviderOptions, type TavilyProviderOptions, TodoItem, TodoOptions, TodoStatus, TodoStore, TodoToolName, WebFetchOptions, WebFetchToolName, type WebSearchOptions, type WebSearchProvider, type WebSearchProviderResponse, type WebSearchRequest, type WebSearchResult, type WebSearchToolName, brave, exa, filesystem, httpClient, searxng, tavily, todo, webFetch, webSearch };
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/tools/cache.ts"],"mappings":";;;;;;YASY;;EAEV;;EAEA;;EAEA;;EAEA;;wBAUc,cAAc,UAAU,UAAU,SAChD,QAAQ,GACR,SAAS,mBACR"}
@@ -0,0 +1,8 @@
1
+ import { withToolCache } from "./cache.js";
2
+ import { filesystem } from "./fs/index.js";
3
+ import { httpClient } from "./http/index.js";
4
+ import { InMemoryTodoStore, todo } from "./todo/index.js";
5
+ import { webFetch } from "./web-fetch/index.js";
6
+ import { brave, exa, searxng, tavily } from "./web-search/providers.js";
7
+ import { webSearch } from "./web-search/index.js";
8
+ export { InMemoryTodoStore, brave, exa, filesystem, httpClient, searxng, tavily, todo, webFetch, webSearch, withToolCache };
@@ -0,0 +1,2 @@
1
+ import { a as TodoStore, i as TodoStatus, n as TodoItem, o as TodoToolName, r as TodoOptions, s as todo, t as InMemoryTodoStore } from "../../index-tDVrZS31.js";
2
+ export { InMemoryTodoStore, TodoItem, TodoOptions, TodoStatus, TodoStore, TodoToolName, todo };
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+ import { createTool, createToolkit } from "@anvia/core/tool";
3
+ // src/tools/todo/index.ts
4
+ var InMemoryTodoStore = class {
5
+ items = [];
6
+ constructor(initial = []) {
7
+ this.items = initial.map((item) => ({ ...item }));
8
+ }
9
+ get() {
10
+ return this.items.map((item) => ({ ...item }));
11
+ }
12
+ set(items) {
13
+ this.items = items.map((item) => ({ ...item }));
14
+ }
15
+ };
16
+ const todoItemSchema = z.object({
17
+ id: z.string().trim().min(1).describe("Stable short identifier for the task."),
18
+ content: z.string().trim().min(1).describe("Clear description of the task."),
19
+ status: z.enum([
20
+ "pending",
21
+ "in_progress",
22
+ "completed",
23
+ "cancelled"
24
+ ])
25
+ });
26
+ const DEFAULT_INSTRUCTIONS = "Use todo_write and todo_read to track multi-step work. Keep at most one task in_progress at a time and update statuses as steps finish.";
27
+ function todo(options = {}) {
28
+ const store = options.store ?? new InMemoryTodoStore();
29
+ const maxItems = options.maxItems ?? 50;
30
+ if (!Number.isSafeInteger(maxItems) || maxItems <= 0) throw new RangeError("todo maxItems must be a positive safe integer.");
31
+ const readTool = createTool({
32
+ name: "todo_read",
33
+ description: "Read the current task list.",
34
+ inputSchema: z.object({}),
35
+ handler: async () => {
36
+ const items = await store.get();
37
+ return {
38
+ count: items.length,
39
+ items: items.map((item) => ({ ...item }))
40
+ };
41
+ }
42
+ });
43
+ const writeTool = createTool({
44
+ name: "todo_write",
45
+ description: "Replace the current task list with an updated ordered list of tasks.",
46
+ inputSchema: z.object({ items: z.array(todoItemSchema).max(maxItems).describe("The full updated ordered task list.") }),
47
+ handler: async (args) => {
48
+ const seen = /* @__PURE__ */ new Set();
49
+ for (const item of args.items) {
50
+ if (seen.has(item.id)) throw new Error(`Duplicate todo item id "${item.id}".`);
51
+ seen.add(item.id);
52
+ }
53
+ await store.set(args.items);
54
+ return {
55
+ count: args.items.length,
56
+ items: args.items.map((item) => ({ ...item }))
57
+ };
58
+ }
59
+ });
60
+ return createToolkit({
61
+ name: "todo",
62
+ tools: [readTool, writeTool],
63
+ instructions: DEFAULT_INSTRUCTIONS
64
+ }, options);
65
+ }
66
+ export { InMemoryTodoStore, todo };
67
+
68
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/tools/todo/index.ts"],"sourcesContent":["import { createTool, createToolkit, type Toolkit, type ToolkitOptions } from \"@anvia/core/tool\";\nimport { z } from \"zod\";\n\nexport type TodoStatus = \"pending\" | \"in_progress\" | \"completed\" | \"cancelled\";\n\nexport type TodoItem = {\n id: string;\n content: string;\n status: TodoStatus;\n};\n\nexport interface TodoStore {\n get(): readonly TodoItem[] | Promise<readonly TodoItem[]>;\n set(items: readonly TodoItem[]): void | Promise<void>;\n}\n\nexport class InMemoryTodoStore implements TodoStore {\n private items: TodoItem[] = [];\n\n constructor(initial: readonly TodoItem[] = []) {\n this.items = initial.map((item) => ({ ...item }));\n }\n\n get(): readonly TodoItem[] {\n return this.items.map((item) => ({ ...item }));\n }\n\n set(items: readonly TodoItem[]): void {\n this.items = items.map((item) => ({ ...item }));\n }\n}\n\nexport type TodoToolName = \"todo_read\" | \"todo_write\";\n\nexport type TodoOptions = ToolkitOptions<TodoToolName> & {\n store?: TodoStore | undefined;\n /** Maximum number of todo items allowed. Default 50. */\n maxItems?: number | undefined;\n};\n\nconst todoItemSchema = z.object({\n id: z.string().trim().min(1).describe(\"Stable short identifier for the task.\"),\n content: z.string().trim().min(1).describe(\"Clear description of the task.\"),\n status: z.enum([\"pending\", \"in_progress\", \"completed\", \"cancelled\"]),\n});\n\nconst DEFAULT_INSTRUCTIONS =\n \"Use todo_write and todo_read to track multi-step work. Keep at most one task in_progress at a time and update statuses as steps finish.\";\n\nexport function todo(options: TodoOptions = {}): Toolkit {\n const store = options.store ?? new InMemoryTodoStore();\n const maxItems = options.maxItems ?? 50;\n\n if (!Number.isSafeInteger(maxItems) || maxItems <= 0) {\n throw new RangeError(\"todo maxItems must be a positive safe integer.\");\n }\n\n const readTool = createTool({\n name: \"todo_read\",\n description: \"Read the current task list.\",\n inputSchema: z.object({}),\n handler: async () => {\n const items = await store.get();\n return {\n count: items.length,\n items: items.map((item) => ({ ...item })),\n };\n },\n });\n\n const writeTool = createTool({\n name: \"todo_write\",\n description: \"Replace the current task list with an updated ordered list of tasks.\",\n inputSchema: z.object({\n items: z.array(todoItemSchema).max(maxItems).describe(\"The full updated ordered task list.\"),\n }),\n handler: async (args) => {\n const seen = new Set<string>();\n for (const item of args.items) {\n if (seen.has(item.id)) {\n throw new Error(`Duplicate todo item id \"${item.id}\".`);\n }\n\n seen.add(item.id);\n }\n\n await store.set(args.items);\n return {\n count: args.items.length,\n items: args.items.map((item) => ({ ...item })),\n };\n },\n });\n\n return createToolkit<TodoToolName>(\n {\n name: \"todo\",\n tools: [readTool, writeTool],\n instructions: DEFAULT_INSTRUCTIONS,\n },\n options,\n );\n}\n"],"mappings":";;;AAgBA,IAAa,oBAAb,MAAoD;CAClD,QAA4B,CAAC;CAE7B,YAAY,UAA+B,CAAC,GAAG;EAC7C,KAAK,QAAQ,QAAQ,KAAK,UAAU,EAAE,GAAG,KAAK,EAAE;CAClD;CAEA,MAA2B;EACzB,OAAO,KAAK,MAAM,KAAK,UAAU,EAAE,GAAG,KAAK,EAAE;CAC/C;CAEA,IAAI,OAAkC;EACpC,KAAK,QAAQ,MAAM,KAAK,UAAU,EAAE,GAAG,KAAK,EAAE;CAChD;AACF;AAUA,MAAM,iBAAiB,EAAE,OAAO;CAC9B,IAAI,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,uCAAuC;CAC7E,SAAS,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,gCAAgC;CAC3E,QAAQ,EAAE,KAAK;EAAC;EAAW;EAAe;EAAa;CAAW,CAAC;AACrE,CAAC;AAED,MAAM,uBAC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 };
10
+ function stripNonContentBlocks(html) {
11
+ return html.replace(/<!--[\s\S]*?(?:-->|$)/g, " ").replace(/<(script|style|noscript|svg|template)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi, " ");
12
+ }
13
+ function extractHtmlTitle(html) {
14
+ const cleaned = stripNonContentBlocks(html);
15
+ const match = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(cleaned);
16
+ if (match === null) return void 0;
17
+ const decoded = decodeHtmlEntities(stripTags(match[1] ?? "")).replace(/\s+/g, " ").trim();
18
+ return decoded.length > 0 ? decoded : void 0;
19
+ }
20
+ function htmlToReadableText(html) {
21
+ let text = stripNonContentBlocks(html);
22
+ text = text.replace(/<h([1-6])\b[^>]*>([\s\S]*?)<\/h\1\s*>/gi, (_m, level, inner) => {
23
+ return `\n\n${"#".repeat(Number(level))} ${stripTags(inner).trim()}\n\n`;
24
+ });
25
+ text = text.replace(/<li\b[^>]*>/gi, "\n- ");
26
+ text = text.replace(/<br\s*\/?>/gi, "\n");
27
+ text = text.replace(/<\/(p|div|section|article|main|header|footer|tr|blockquote|pre|ul|ol)\s*>/gi, "\n\n");
28
+ text = text.replace(/<td\b[^>]*>|<th\b[^>]*>/gi, " | ");
29
+ text = stripTags(text);
30
+ text = decodeHtmlEntities(text);
31
+ const lines = text.replace(/\r\n/g, "\n").split("\n").map((line) => line.replace(/[ \t]+/g, " ").trim());
32
+ const compacted = [];
33
+ let blankRun = 0;
34
+ for (const line of lines) if (line.length === 0) {
35
+ blankRun++;
36
+ if (blankRun <= 1 && compacted.length > 0) compacted.push("");
37
+ } else {
38
+ blankRun = 0;
39
+ compacted.push(line);
40
+ }
41
+ return compacted.join("\n").trim();
42
+ }
43
+ function stripTags(input) {
44
+ return input.replace(/<[^>]+>/g, " ");
45
+ }
46
+ function decodeHtmlEntities(input) {
47
+ return input.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, body) => {
48
+ const lower = body.toLowerCase();
49
+ if (lower in ENTITY_MAP) return ENTITY_MAP[lower];
50
+ if (lower.startsWith("#x")) {
51
+ const codePoint = Number.parseInt(lower.slice(2), 16);
52
+ return Number.isFinite(codePoint) ? safeFromCodePoint(codePoint, match) : match;
53
+ }
54
+ if (lower.startsWith("#")) {
55
+ const codePoint = Number.parseInt(lower.slice(1), 10);
56
+ return Number.isFinite(codePoint) ? safeFromCodePoint(codePoint, match) : match;
57
+ }
58
+ return match;
59
+ });
60
+ }
61
+ function safeFromCodePoint(codePoint, fallback) {
62
+ if (codePoint < 0 || codePoint > 1114111) return fallback;
63
+ return String.fromCodePoint(codePoint);
64
+ }
65
+ export { extractHtmlTitle, htmlToReadableText };
66
+
67
+ //# sourceMappingURL=html-to-text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html-to-text.js","names":[],"sources":["../../../src/tools/web-fetch/html-to-text.ts"],"sourcesContent":["const ENTITY_MAP: Record<string, string> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n\nfunction stripNonContentBlocks(html: string): string {\n return html\n .replace(/<!--[\\s\\S]*?(?:-->|$)/g, \" \")\n .replace(/<(script|style|noscript|svg|template)\\b[^>]*>[\\s\\S]*?(?:<\\/\\1\\s*>|$)/gi, \" \");\n}\n\nexport function extractHtmlTitle(html: string): string | undefined {\n const cleaned = stripNonContentBlocks(html);\n const match = /<title\\b[^>]*>([\\s\\S]*?)<\\/title\\s*>/i.exec(cleaned);\n\n if (match === null) return undefined;\n\n const decoded = decodeHtmlEntities(stripTags(match[1] ?? \"\"))\n .replace(/\\s+/g, \" \")\n .trim();\n return decoded.length > 0 ? decoded : undefined;\n}\n\nexport function htmlToReadableText(html: string): string {\n let text = stripNonContentBlocks(html);\n\n text = text.replace(\n /<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1\\s*>/gi,\n (_m, level: string, inner: string) => {\n const hashes = \"#\".repeat(Number(level));\n return `\\n\\n${hashes} ${stripTags(inner).trim()}\\n\\n`;\n },\n );\n text = text.replace(/<li\\b[^>]*>/gi, \"\\n- \");\n text = text.replace(/<br\\s*\\/?>/gi, \"\\n\");\n text = text.replace(\n /<\\/(p|div|section|article|main|header|footer|tr|blockquote|pre|ul|ol)\\s*>/gi,\n \"\\n\\n\",\n );\n text = text.replace(/<td\\b[^>]*>|<th\\b[^>]*>/gi, \" | \");\n\n text = stripTags(text);\n text = decodeHtmlEntities(text);\n\n const lines = text\n .replace(/\\r\\n/g, \"\\n\")\n .split(\"\\n\")\n .map((line) => line.replace(/[ \\t]+/g, \" \").trim());\n\n const compacted: string[] = [];\n let blankRun = 0;\n for (const line of lines) {\n if (line.length === 0) {\n blankRun++;\n\n if (blankRun <= 1 && compacted.length > 0) compacted.push(\"\");\n } else {\n blankRun = 0;\n compacted.push(line);\n }\n }\n\n return compacted.join(\"\\n\").trim();\n}\n\nfunction stripTags(input: string): string {\n return input.replace(/<[^>]+>/g, \" \");\n}\n\nfunction decodeHtmlEntities(input: string): string {\n return input.replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi, (match, body: string) => {\n const lower = body.toLowerCase();\n\n if (lower in ENTITY_MAP) {\n return ENTITY_MAP[lower]!;\n }\n\n if (lower.startsWith(\"#x\")) {\n const codePoint = Number.parseInt(lower.slice(2), 16);\n return Number.isFinite(codePoint) ? safeFromCodePoint(codePoint, match) : match;\n }\n\n if (lower.startsWith(\"#\")) {\n const codePoint = Number.parseInt(lower.slice(1), 10);\n return Number.isFinite(codePoint) ? safeFromCodePoint(codePoint, match) : match;\n }\n\n return match;\n });\n}\n\nfunction safeFromCodePoint(codePoint: number, fallback: string): string {\n if (codePoint < 0 || codePoint > 0x10ffff) return fallback;\n\n return String.fromCodePoint(codePoint);\n}\n"],"mappings":";AAAA,MAAM,aAAqC;CACzC,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,MAAM;AACR;AAEA,SAAS,sBAAsB,MAAsB;CACnD,OAAO,K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AO,MAAM,QAAQ,YAAY,GAAG;AACtC;AAEA,SAAS,mBAAmB,OAAuB;CACjD,OAAO,MAAM,QAAQ,kCAAkC,OAAO,SAAiB;EAC7E,MAAM,QAAQ,KAAK,YAAY;EAE/B,IAAI,SAAS,YACX,OAAO,WAAW;EAGpB,IAAI,MAAM,WAAW,IAAI,GAAG;GAC1B,MAAM,YAAY,OAAO,SAAS,MAAM,MAAM,CAAC,GAAG,EAAE;GACpD,OAAO,OAAO,SAAS,SAAS,IAAI,kBAAkB,WAAW,KAAK,IAAI;EAC5E;EAEA,IAAI,MAAM,WAAW,GAAG,GAAG;GACzB,MAAM,YAAY,OAAO,SAAS,MAAM,MAAM,CAAC,GAAG,EAAE;GACpD,OAAO,OAAO,SAAS,SAAS,IAAI,kBAAkB,WAAW,KAAK,IAAI;EAC5E;EAEA,OAAO;CACT,CAAC;AACH;AAEA,SAAS,kBAAkB,WAAmB,UAA0B;CACtE,IAAI,YAAY,KAAK,YAAY,SAAU,OAAO;CAElD,OAAO,OAAO,cAAc,SAAS;AACvC"}
@@ -0,0 +1,2 @@
1
+ import { n as WebFetchToolName, r as webFetch, t as WebFetchOptions } from "../../index-Bov_OeIz.js";
2
+ export { WebFetchOptions, WebFetchToolName, webFetch };
@@ -0,0 +1,74 @@
1
+ import { truncateText } from "../../internal/truncate.js";
2
+ import { safeFetch } from "../../internal/url-safety.js";
3
+ import { extractHtmlTitle, htmlToReadableText } from "./html-to-text.js";
4
+ import { z } from "zod";
5
+ import { createTool, createToolkit } from "@anvia/core/tool";
6
+ // src/tools/web-fetch/index.ts
7
+ const DEFAULT_USER_AGENT = "anvia-web-fetch/0.1";
8
+ const DEFAULT_INSTRUCTIONS = "Use web_fetch to read the content of a specific http(s) URL. Prefer targeted pages rather than fetching many URLs at once.";
9
+ function webFetch(options = {}) {
10
+ const maxBytes = options.maxBytes ?? 1e6;
11
+ const maxChars = options.maxChars ?? 16e3;
12
+ const maxRedirects = options.maxRedirects ?? 5;
13
+ const timeoutMs = options.timeoutMs ?? 15e3;
14
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("webFetch maxBytes must be a positive safe integer.");
15
+ if (!Number.isSafeInteger(maxChars) || maxChars <= 0) throw new RangeError("webFetch maxChars must be a positive safe integer.");
16
+ if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0) throw new RangeError("webFetch maxRedirects must be a non-negative safe integer.");
17
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError("webFetch timeoutMs must be a positive finite number.");
18
+ const normalizedCustomHeaders = {};
19
+ for (const [key, value] of Object.entries(options.headers ?? {})) normalizedCustomHeaders[key.toLowerCase()] = value;
20
+ const requestHeaders = {
21
+ accept: "text/html, text/plain, application/json, text/markdown;q=0.9, */*;q=0.1",
22
+ "user-agent": options.userAgent ?? DEFAULT_USER_AGENT,
23
+ ...normalizedCustomHeaders
24
+ };
25
+ const protectedHeaderNames = Object.keys(normalizedCustomHeaders);
26
+ const fetchTool = createTool({
27
+ name: "web_fetch",
28
+ description: "Fetch a web page or text document over HTTP(S) and return its readable content.",
29
+ inputSchema: z.object({
30
+ url: z.string().min(1).describe("The http:// or https:// URL to fetch."),
31
+ format: z.enum(["text", "raw"]).optional().describe("Return cleaned readable text (default \"text\") or raw response body (\"raw\").")
32
+ }),
33
+ handler: async (args, context) => {
34
+ const response = await safeFetch(args.url, {
35
+ method: "GET",
36
+ headers: requestHeaders,
37
+ protectedHeaderNames,
38
+ allowedHosts: options.allowedHosts,
39
+ allowedOrigins: options.allowedOrigins,
40
+ blockedHosts: options.blockedHosts,
41
+ allowPrivateAddresses: options.allowPrivateAddresses,
42
+ resolveAddress: options.resolveAddress,
43
+ maxBytes,
44
+ maxRedirects,
45
+ timeoutMs,
46
+ abortSignal: context.abortSignal,
47
+ fetch: options.fetch
48
+ });
49
+ const contentType = response.headers["content-type"] ?? "";
50
+ const lowerContentType = contentType.toLowerCase();
51
+ const isHtml = lowerContentType.includes("text/html") || lowerContentType.includes("application/xhtml+xml") || /^\s*<(?:!doctype|html)\b/i.test(response.bodyText);
52
+ const title = isHtml ? extractHtmlTitle(response.bodyText) : void 0;
53
+ const body = args.format === "raw" || !isHtml ? response.bodyText : htmlToReadableText(response.bodyText);
54
+ const { text, truncated } = truncateText(body, maxChars);
55
+ const payload = {
56
+ url: response.url,
57
+ status: response.status,
58
+ contentType,
59
+ content: text,
60
+ truncated: truncated || response.bodyTruncated
61
+ };
62
+ if (title !== void 0) payload.title = title;
63
+ return payload;
64
+ }
65
+ });
66
+ return createToolkit({
67
+ name: "web-fetch",
68
+ tools: [fetchTool],
69
+ instructions: DEFAULT_INSTRUCTIONS
70
+ }, options);
71
+ }
72
+ export { webFetch };
73
+
74
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/tools/web-fetch/index.ts"],"sourcesContent":["import { createTool, createToolkit, type Toolkit, type ToolkitOptions } from \"@anvia/core/tool\";\nimport { z } from \"zod\";\nimport { truncateText } from \"../../internal/truncate\";\nimport { safeFetch, type UrlSafetyOptions } from \"../../internal/url-safety\";\nimport { extractHtmlTitle, htmlToReadableText } from \"./html-to-text\";\n\nexport type WebFetchToolName = \"web_fetch\";\n\nexport type WebFetchOptions = ToolkitOptions<WebFetchToolName> &\n UrlSafetyOptions & {\n /** Maximum response bytes read from the network. Default 1_000_000 (1 MB). */\n maxBytes?: number | undefined;\n /** Maximum characters returned to the model. Default 16_000. */\n maxChars?: number | undefined;\n /** Maximum HTTP redirects followed. Default 5. */\n maxRedirects?: number | undefined;\n /** Custom User-Agent header. */\n userAgent?: string | undefined;\n /** Additional request headers sent on every fetch. */\n headers?: Record<string, string> | undefined;\n /** Custom fetch implementation (useful for testing). */\n fetch?: typeof globalThis.fetch | undefined;\n };\n\nconst DEFAULT_USER_AGENT = \"anvia-web-fetch/0.1\";\nconst DEFAULT_INSTRUCTIONS =\n \"Use web_fetch to read the content of a specific http(s) URL. Prefer targeted pages rather than fetching many URLs at once.\";\n\nexport function webFetch(options: WebFetchOptions = {}): Toolkit {\n const maxBytes = options.maxBytes ?? 1_000_000;\n const maxChars = options.maxChars ?? 16_000;\n const maxRedirects = options.maxRedirects ?? 5;\n const timeoutMs = options.timeoutMs ?? 15_000;\n\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new RangeError(\"webFetch maxBytes must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxChars) || maxChars <= 0) {\n throw new RangeError(\"webFetch maxChars must be a positive safe integer.\");\n }\n\n if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0) {\n throw new RangeError(\"webFetch maxRedirects must be a non-negative safe integer.\");\n }\n\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\"webFetch timeoutMs must be a positive finite number.\");\n }\n\n const normalizedCustomHeaders: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.headers ?? {})) {\n normalizedCustomHeaders[key.toLowerCase()] = value;\n }\n\n const requestHeaders: Record<string, string> = {\n accept: \"text/html, text/plain, application/json, text/markdown;q=0.9, */*;q=0.1\",\n \"user-agent\": options.userAgent ?? DEFAULT_USER_AGENT,\n ...normalizedCustomHeaders,\n };\n const protectedHeaderNames = Object.keys(normalizedCustomHeaders);\n\n const fetchTool = createTool({\n name: \"web_fetch\",\n description: \"Fetch a web page or text document over HTTP(S) and return its readable content.\",\n inputSchema: z.object({\n url: z.string().min(1).describe(\"The http:// or https:// URL to fetch.\"),\n format: z\n .enum([\"text\", \"raw\"])\n .optional()\n .describe('Return cleaned readable text (default \"text\") or raw response body (\"raw\").'),\n }),\n handler: async (args, context) => {\n const response = await safeFetch(args.url, {\n method: \"GET\",\n headers: requestHeaders,\n protectedHeaderNames,\n allowedHosts: options.allowedHosts,\n allowedOrigins: options.allowedOrigins,\n blockedHosts: options.blockedHosts,\n allowPrivateAddresses: options.allowPrivateAddresses,\n resolveAddress: options.resolveAddress,\n maxBytes,\n maxRedirects,\n timeoutMs,\n abortSignal: context.abortSignal,\n fetch: options.fetch,\n });\n\n const contentType = response.headers[\"content-type\"] ?? \"\";\n const lowerContentType = contentType.toLowerCase();\n const isHtml =\n lowerContentType.includes(\"text/html\") ||\n lowerContentType.includes(\"application/xhtml+xml\") ||\n /^\\s*<(?:!doctype|html)\\b/i.test(response.bodyText);\n\n const title = isHtml ? extractHtmlTitle(response.bodyText) : undefined;\n const body =\n args.format === \"raw\" || !isHtml\n ? response.bodyText\n : htmlToReadableText(response.bodyText);\n const { text, truncated } = truncateText(body, maxChars);\n\n const payload: Record<string, unknown> = {\n url: response.url,\n status: response.status,\n contentType,\n content: text,\n truncated: truncated || response.bodyTruncated,\n };\n\n if (title !== undefined) payload.title = title;\n\n return payload;\n },\n });\n\n return createToolkit<WebFetchToolName>(\n {\n name: \"web-fetch\",\n tools: [fetchTool],\n instructions: DEFAULT_INSTRUCTIONS,\n },\n options,\n );\n}\n"],"mappings":";;;;;;AAwBA,MAAM,qBAAqB;AAC3B,MAAM,uBACJ;AAEF,SAAgB,SAAS,UAA2B,CAAC,GAAY;CAC/D,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,YAAY,QAAQ,aAAa;CAEvC,IAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,YAAY,GACjD,MAAM,IAAI,WAAW,oDAAoD;CAG3E,IAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,YAAY,GACjD,MAAM,IAAI,WAAW,oDAAoD;CAG3E,IAAI,CAAC,OAAO,cAAc,YAAY,KAAK,eAAe,GACxD,MAAM,IAAI,WAAW,4DAA4D;CAGnF,IAAI,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,GAC9C,MAAM,IAAI,WAAW,sDAAsD;CAG7E,MAAM,0BAAkD,CAAC;CACzD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,WAAW,CAAC,C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EACE,MAAM;EACN,OAAO,CAAC,SAAS;EACjB,cAAc;CAChB,GACA,OACF;AACF"}
@@ -0,0 +1,2 @@
1
+ import { a as TavilyProviderOptions, c as searxng, d as WebSearchProvider, f as WebSearchProviderResponse, h as WebSearchToolName, i as SearxngProviderOptions, l as tavily, m as WebSearchResult, n as BraveProviderOptions, o as brave, p as WebSearchRequest, r as ExaProviderOptions, s as exa, t as webSearch, u as WebSearchOptions } from "../../index-NVtYgz_h.js";
2
+ export { type BraveProviderOptions, type ExaProviderOptions, type SearxngProviderOptions, type TavilyProviderOptions, type WebSearchOptions, type WebSearchProvider, type WebSearchProviderResponse, type WebSearchRequest, type WebSearchResult, type WebSearchToolName, brave, exa, searxng, tavily, webSearch };