@townco/agent 0.1.130 → 0.1.132

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.
@@ -1,135 +0,0 @@
1
- /**
2
- * Document extraction tool for extracting relevant information from large files
3
- *
4
- * Uses the document context extractor to intelligently extract relevant
5
- * information from large documents based on a query/requirements description.
6
- */
7
- import * as fs from "node:fs/promises";
8
- import { tool } from "langchain";
9
- import { z } from "zod";
10
- import { createLogger } from "../../../logger.js";
11
- import { countTokens } from "../../../utils/token-counter.js";
12
- import { extractDocumentContext } from "../../hooks/predefined/document-context-extractor/index.js";
13
- const logger = createLogger("document-extract-tool");
14
- // Minimum document size (in tokens) to use extraction
15
- // Smaller documents are returned as-is
16
- const MIN_EXTRACTION_THRESHOLD = 10000;
17
- // Default target size for extraction output
18
- const DEFAULT_TARGET_TOKENS = 20000;
19
- /**
20
- * Document extraction tool
21
- *
22
- * Reads a file and extracts relevant information based on the provided query.
23
- * For large documents, uses intelligent chunking and relevance scoring.
24
- * Small documents are returned as-is.
25
- */
26
- const documentExtract = tool(async ({ session_id, file_path, query, target_tokens, }) => {
27
- try {
28
- // Read the file content
29
- const content = await fs.readFile(file_path, "utf-8");
30
- // Try to parse as JSON, otherwise treat as plain text
31
- let parsedContent;
32
- try {
33
- parsedContent = JSON.parse(content);
34
- }
35
- catch {
36
- // Not JSON, wrap as text object
37
- parsedContent = { content };
38
- }
39
- // Count tokens in the document
40
- const documentTokens = await countTokens(content);
41
- logger.info("Document extraction requested", {
42
- filePath: file_path,
43
- documentTokens,
44
- query: query.substring(0, 100),
45
- sessionId: session_id,
46
- });
47
- // If document is small enough, return as-is
48
- if (documentTokens <= MIN_EXTRACTION_THRESHOLD) {
49
- logger.info("Document below extraction threshold, returning as-is", {
50
- documentTokens,
51
- threshold: MIN_EXTRACTION_THRESHOLD,
52
- });
53
- return content;
54
- }
55
- // Use document context extractor for large documents
56
- const targetSize = target_tokens ?? DEFAULT_TARGET_TOKENS;
57
- const result = await extractDocumentContext(parsedContent, "document_extract", // toolName
58
- `extract-${Date.now()}`, // toolCallId
59
- { file_path, query }, // toolInput
60
- query, // conversationContext (use query as context)
61
- targetSize, session_id, undefined);
62
- if (result.success && result.extractedData) {
63
- logger.info("Document extraction successful", {
64
- originalTokens: result.metadata.originalTokens,
65
- extractedTokens: result.extractedTokens,
66
- chunksProcessed: result.metadata.chunksProcessed,
67
- chunksExtractedFrom: result.metadata.chunksExtractedFrom,
68
- });
69
- // Return extracted content as formatted string
70
- return JSON.stringify(result.extractedData, null, 2);
71
- }
72
- // Extraction failed
73
- logger.error("Document extraction failed", {
74
- error: result.error,
75
- phase: result.metadata.phase,
76
- });
77
- return `Error: Failed to extract from document: ${result.error}`;
78
- }
79
- catch (error) {
80
- const errorMessage = error instanceof Error ? error.message : String(error);
81
- logger.error("Document extract tool error", {
82
- filePath: file_path,
83
- error: errorMessage,
84
- });
85
- // Check for common errors
86
- if (errorMessage.includes("ENOENT") ||
87
- errorMessage.includes("no such file")) {
88
- return `Error: File not found at path: ${file_path}`;
89
- }
90
- if (errorMessage.includes("EACCES")) {
91
- return `Error: Permission denied reading file: ${file_path}`;
92
- }
93
- return `Error: ${errorMessage}`;
94
- }
95
- }, {
96
- name: "document_extract",
97
- description: "Extract relevant information from a large document file based on a query. " +
98
- "Use this tool when you need to find specific information in a large file " +
99
- "(e.g., JSON data, logs, API responses) that would be too large to process directly. " +
100
- "The tool intelligently identifies and extracts the most relevant portions of the document. " +
101
- "For small files (under 10,000 tokens), returns the full content.",
102
- schema: z.object({
103
- session_id: z
104
- .string()
105
- .optional()
106
- .describe("INTERNAL USE ONLY - Auto-injected by system"),
107
- file_path: z
108
- .string()
109
- .describe("Absolute path to the file to extract from (e.g., '/tmp/data.json')"),
110
- query: z
111
- .string()
112
- .describe("Description of what information to extract from the document. " +
113
- "Be specific about what you're looking for."),
114
- target_tokens: z
115
- .number()
116
- .optional()
117
- .describe("Target size for extracted output in tokens (default: 20000). " +
118
- "Use smaller values if you need a more concise summary."),
119
- }),
120
- });
121
- // Add metadata for UI display
122
- documentExtract.prettyName =
123
- "Extract from Document";
124
- documentExtract.icon = "FileSearch";
125
- documentExtract.verbiage = {
126
- active: "Extracting relevant information from {file_path}",
127
- past: "Extracted relevant information from {file_path}",
128
- paramKey: "file_path",
129
- };
130
- /**
131
- * Factory function to create the document extract tool
132
- */
133
- export function makeDocumentExtractTool() {
134
- return documentExtract;
135
- }
@@ -1,47 +0,0 @@
1
- import { z } from "zod";
2
- interface GenerateImageResult {
3
- success: boolean;
4
- filePath?: string | undefined;
5
- fileName?: string | undefined;
6
- imageUrl?: string | undefined;
7
- textResponse?: string | undefined;
8
- mimeType?: string | undefined;
9
- error?: string | undefined;
10
- }
11
- /** Create generate image tool using direct GEMINI_API_KEY/GOOGLE_API_KEY */
12
- export declare function makeGenerateImageTool(): import("langchain").DynamicStructuredTool<z.ZodObject<{
13
- prompt: z.ZodString;
14
- aspectRatio: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
15
- "16:9": "16:9";
16
- "1:1": "1:1";
17
- "3:4": "3:4";
18
- "4:3": "4:3";
19
- "5:4": "5:4";
20
- "9:16": "9:16";
21
- }>>>;
22
- }, z.core.$strip>, {
23
- prompt: string;
24
- aspectRatio: "16:9" | "1:1" | "3:4" | "4:3" | "5:4" | "9:16";
25
- }, {
26
- prompt: string;
27
- aspectRatio?: "16:9" | "1:1" | "3:4" | "4:3" | "5:4" | "9:16" | undefined;
28
- }, GenerateImageResult>;
29
- /** Create generate image tool using Town proxy */
30
- export declare function makeTownGenerateImageTool(): import("langchain").DynamicStructuredTool<z.ZodObject<{
31
- prompt: z.ZodString;
32
- aspectRatio: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
33
- "16:9": "16:9";
34
- "1:1": "1:1";
35
- "3:4": "3:4";
36
- "4:3": "4:3";
37
- "5:4": "5:4";
38
- "9:16": "9:16";
39
- }>>>;
40
- }, z.core.$strip>, {
41
- prompt: string;
42
- aspectRatio: "16:9" | "1:1" | "3:4" | "4:3" | "5:4" | "9:16";
43
- }, {
44
- prompt: string;
45
- aspectRatio?: "16:9" | "1:1" | "3:4" | "4:3" | "5:4" | "9:16" | undefined;
46
- }, GenerateImageResult>;
47
- export {};
@@ -1,175 +0,0 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
3
- import { GoogleGenAI } from "@google/genai";
4
- import { getShedAuth } from "@townco/core/auth";
5
- import { tool } from "langchain";
6
- import { z } from "zod";
7
- import { getSessionContext, getToolOutputDir, hasSessionContext, } from "../../session-context";
8
- let _directGenaiClient = null;
9
- let _townGenaiClient = null;
10
- /** Get Google GenAI client using direct GEMINI_API_KEY/GOOGLE_API_KEY environment variable */
11
- function getDirectGenAIClient() {
12
- if (_directGenaiClient) {
13
- return _directGenaiClient;
14
- }
15
- const apiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
16
- if (!apiKey) {
17
- throw new Error("GEMINI_API_KEY or GOOGLE_API_KEY environment variable is required to use the generate_image tool. " +
18
- "Please set one of them to your Google AI API key.");
19
- }
20
- _directGenaiClient = new GoogleGenAI({ apiKey });
21
- return _directGenaiClient;
22
- }
23
- /** Get Google GenAI client using Town proxy with authenticated credentials */
24
- function getTownGenAIClient() {
25
- if (_townGenaiClient) {
26
- return _townGenaiClient;
27
- }
28
- const shedAuth = getShedAuth();
29
- if (!shedAuth) {
30
- throw new Error("Not logged in. Run 'town login' or set SHED_API_KEY to use the town_generate_image tool.");
31
- }
32
- // Configure the client to use shed as proxy
33
- // The SDK will send requests to {shedUrl}/api/gemini/{apiVersion}/{path}
34
- _townGenaiClient = new GoogleGenAI({
35
- apiKey: shedAuth.accessToken,
36
- httpOptions: {
37
- baseUrl: `${shedAuth.shedUrl}/api/gemini/`,
38
- },
39
- });
40
- return _townGenaiClient;
41
- }
42
- function makeGenerateImageToolInternal(getClient) {
43
- const generateImage = tool(async ({ prompt, aspectRatio = "1:1" }) => {
44
- try {
45
- if (!hasSessionContext()) {
46
- throw new Error("GenerateImage tool requires session context. Ensure the tool is called within a session.");
47
- }
48
- const { sessionId } = getSessionContext();
49
- const toolOutputDir = getToolOutputDir("GenerateImage");
50
- const client = getClient();
51
- // Use Gemini 3 Pro Image for image generation
52
- // Note: imageConfig is a valid API option but not yet in the TypeScript types
53
- // biome-ignore lint/suspicious/noExplicitAny: imageConfig not yet typed in @google/genai
54
- const config = {
55
- responseModalities: ["TEXT", "IMAGE"],
56
- imageConfig: {
57
- aspectRatio: aspectRatio,
58
- },
59
- };
60
- const response = await client.models.generateContent({
61
- model: "gemini-3-pro-image-preview",
62
- contents: [{ text: prompt }],
63
- config,
64
- });
65
- if (!response.candidates || response.candidates.length === 0) {
66
- return {
67
- success: false,
68
- error: "No response from the model. The request may have been filtered.",
69
- };
70
- }
71
- const candidate = response.candidates[0];
72
- if (!candidate) {
73
- return {
74
- success: false,
75
- error: "No candidate in the response.",
76
- };
77
- }
78
- const parts = candidate.content?.parts;
79
- if (!parts || parts.length === 0) {
80
- return {
81
- success: false,
82
- error: "No content parts in the response.",
83
- };
84
- }
85
- let imageData;
86
- let textResponse;
87
- let mimeType;
88
- for (const part of parts) {
89
- if (part.text) {
90
- textResponse = part.text;
91
- }
92
- else if (part.inlineData) {
93
- imageData = part.inlineData.data;
94
- mimeType = part.inlineData.mimeType || "image/png";
95
- }
96
- }
97
- if (!imageData) {
98
- return {
99
- success: false,
100
- error: "No image was generated in the response.",
101
- ...(textResponse ? { textResponse } : {}),
102
- };
103
- }
104
- // Save image to session-scoped tool output directory
105
- await mkdir(toolOutputDir, { recursive: true });
106
- // Generate unique filename
107
- const timestamp = Date.now();
108
- const extension = mimeType === "image/jpeg" ? "jpg" : "png";
109
- const fileName = `image-${timestamp}.${extension}`;
110
- const filePath = join(toolOutputDir, fileName);
111
- // Save image to file
112
- const buffer = Buffer.from(imageData, "base64");
113
- await writeFile(filePath, buffer);
114
- // Create URL for the static file server
115
- // The agent HTTP server serves static files from the agent directory
116
- // Use AGENT_BASE_URL if set (for production), otherwise construct from BIND_HOST/PORT
117
- const port = process.env.PORT || "3100";
118
- const hostname = process.env.BIND_HOST || "localhost";
119
- const baseUrl = process.env.AGENT_BASE_URL || `http://${hostname}:${port}`;
120
- const imageUrl = `${baseUrl}/static/.sessions/${sessionId}/artifacts/tool-GenerateImage/${fileName}`;
121
- return {
122
- success: true,
123
- filePath,
124
- fileName,
125
- imageUrl,
126
- ...(mimeType ? { mimeType } : {}),
127
- ...(textResponse ? { textResponse } : {}),
128
- };
129
- }
130
- catch (error) {
131
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
132
- return {
133
- success: false,
134
- error: `Image generation failed: ${errorMessage}`,
135
- };
136
- }
137
- }, {
138
- name: "GenerateImage",
139
- description: "Generate an image based on a text prompt using Google's Gemini image generation model. " +
140
- "Returns an imageUrl that can be displayed to the user. After calling this tool, " +
141
- "include the imageUrl in your response as a markdown image like ![Description](imageUrl) " +
142
- "so the user can see the generated image.\n" +
143
- "- Creates images from detailed text descriptions\n" +
144
- "- Supports various aspect ratios for different use cases\n" +
145
- "- Be specific in prompts about style, composition, colors, and subjects\n" +
146
- "\n" +
147
- "Usage notes:\n" +
148
- " - Provide detailed, specific prompts for best results\n" +
149
- " - The generated image is saved to the session directory and served via URL\n" +
150
- " - Always display the result using markdown: ![description](imageUrl)\n",
151
- schema: z.object({
152
- prompt: z
153
- .string()
154
- .describe("A detailed description of the image to generate. Be specific about style, composition, colors, and subjects."),
155
- aspectRatio: z
156
- .enum(["1:1", "3:4", "4:3", "9:16", "16:9", "5:4"])
157
- .optional()
158
- .default("1:1")
159
- .describe("The aspect ratio of the generated image."),
160
- }),
161
- });
162
- // biome-ignore lint/suspicious/noExplicitAny: Need to add custom properties to LangChain tool
163
- generateImage.prettyName = "Generate Image";
164
- // biome-ignore lint/suspicious/noExplicitAny: Need to add custom properties to LangChain tool
165
- generateImage.icon = "Image";
166
- return generateImage;
167
- }
168
- /** Create generate image tool using direct GEMINI_API_KEY/GOOGLE_API_KEY */
169
- export function makeGenerateImageTool() {
170
- return makeGenerateImageToolInternal(getDirectGenAIClient);
171
- }
172
- /** Create generate image tool using Town proxy */
173
- export function makeTownGenerateImageTool() {
174
- return makeGenerateImageToolInternal(getTownGenAIClient);
175
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * Check if a port is available
3
- */
4
- export declare function isPortAvailable(port: number): Promise<boolean>;
5
- /**
6
- * Find the next available port starting from the given port
7
- */
8
- export declare function findAvailablePort(startPort: number, maxAttempts?: number): Promise<number>;
@@ -1,35 +0,0 @@
1
- import { createServer } from "node:net";
2
- /**
3
- * Check if a port is available
4
- */
5
- export async function isPortAvailable(port) {
6
- return new Promise((resolve) => {
7
- const server = createServer();
8
- server.once("error", (err) => {
9
- if (err.code === "EADDRINUSE") {
10
- resolve(false);
11
- }
12
- else {
13
- resolve(false);
14
- }
15
- });
16
- server.once("listening", () => {
17
- server.close();
18
- resolve(true);
19
- });
20
- server.listen(port);
21
- });
22
- }
23
- /**
24
- * Find the next available port starting from the given port
25
- */
26
- export async function findAvailablePort(startPort, maxAttempts = 100) {
27
- for (let i = 0; i < maxAttempts; i++) {
28
- const port = startPort + i;
29
- const available = await isPortAvailable(port);
30
- if (available) {
31
- return port;
32
- }
33
- }
34
- throw new Error(`Could not find an available port between ${startPort} and ${startPort + maxAttempts - 1}`);
35
- }