diff --git a/.env.example b/.env.example index 62618cc..fc2e777 100644 --- a/.env.example +++ b/.env.example @@ -57,3 +57,5 @@ LLM_API_KEY= LLM_MODEL=llama3.2 # IANA timezone for assistant relative dates ("Thursday at 2"). Falls back to TZ, then America/Chicago. HOUSEHOLD_TIMEZONE=America/Chicago +# Optional override for agent tool → /api/v1 self-calls (defaults to http://127.0.0.1:$PORT). +# INTERNAL_API_BASE_URL=http://127.0.0.1:3000 diff --git a/src/modules/agent/server/run.ts b/src/modules/agent/server/run.ts index 27665e8..0b4ef12 100644 --- a/src/modules/agent/server/run.ts +++ b/src/modules/agent/server/run.ts @@ -160,8 +160,20 @@ export async function runAgentChat(options: { try { result = await executeTool(toolCall.function.name, toolCall.function.arguments); - const parsed = JSON.parse(result) as { status?: number }; + const parsed = JSON.parse(result) as { status?: number; body?: unknown }; status = typeof parsed.status === "number" ? parsed.status : 200; + if (status >= 400) { + logger.warn( + { + msg: "agent.chat.tool_error", + round, + name: toolCall.function.name, + status, + body: parsed.body, + }, + "agent tool returned error", + ); + } } catch (err) { status = 500; result = JSON.stringify({ diff --git a/src/modules/agent/tool-executor.ts b/src/modules/agent/tool-executor.ts index e8a1c4c..40065f0 100644 --- a/src/modules/agent/tool-executor.ts +++ b/src/modules/agent/tool-executor.ts @@ -1,3 +1,5 @@ +import logger from "@/lib/logger"; + type ApiCallResult = { status: number; body: unknown; @@ -5,8 +7,22 @@ type ApiCallResult = { export type ToolExecutor = (name: string, argsJson: string) => Promise; +/** Loopback base for in-process tool → /api/v1 calls. Avoids hairpinning to the public URL. */ +export function resolveInternalApiBase(request: Request): string { + const configured = process.env.INTERNAL_API_BASE_URL?.trim(); + if (configured) return configured.replace(/\/$/, ""); + + const port = process.env.PORT?.trim() || "3000"; + const requestUrl = new URL(request.url); + if (requestUrl.hostname === "localhost" || requestUrl.hostname === "127.0.0.1") { + return requestUrl.origin; + } + + return `http://127.0.0.1:${port}`; +} + export function createApiToolExecutor(request: Request): ToolExecutor { - const origin = new URL(request.url).origin; + const origin = resolveInternalApiBase(request); return async (name: string, argsJson: string) => { const args = parseArgs(argsJson); @@ -522,14 +538,30 @@ async function callApi( path: string, body?: Record, ): Promise { - const response = await fetch(`${origin}${path}`, { - method, - headers: { - "Content-Type": "application/json", - cookie: request.headers.get("cookie") ?? "", - }, - body: body !== undefined ? JSON.stringify(body) : undefined, - }); + const url = `${origin}${path}`; + const headers: Record = { + "Content-Type": "application/json", + }; + const cookie = request.headers.get("cookie"); + if (cookie) headers.cookie = cookie; + const authorization = request.headers.get("authorization"); + if (authorization) headers.authorization = authorization; + + let response: Response; + try { + response = await fetch(url, { + method, + headers, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + } catch (err) { + const message = err instanceof Error ? err.message : "fetch failed"; + logger.error( + { msg: "agent.tool.fetch_failed", method, url, error: message }, + "agent tool internal fetch failed", + ); + return { status: 502, body: { error: `Internal API unreachable: ${message}`, url } }; + } const text = await response.text(); let parsed: unknown = null; @@ -541,5 +573,12 @@ async function callApi( } } + if (response.status >= 400) { + logger.warn( + { msg: "agent.tool.api_error", method, url, status: response.status, body: parsed }, + "agent tool API error", + ); + } + return { status: response.status, body: parsed }; } diff --git a/tests/unit/agent-tools-runtime.test.ts b/tests/unit/agent-tools-runtime.test.ts index 82437b1..fa138b9 100644 --- a/tests/unit/agent-tools-runtime.test.ts +++ b/tests/unit/agent-tools-runtime.test.ts @@ -1,7 +1,10 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { appendAgentRuntimeContext, resolveHouseholdTimezone } from "../../src/modules/agent/tools"; -import { createApiToolExecutor } from "../../src/modules/agent/tool-executor"; +import { + createApiToolExecutor, + resolveInternalApiBase, +} from "../../src/modules/agent/tool-executor"; describe("appendAgentRuntimeContext", () => { it("appends current time and timezone to the prompt", () => { @@ -38,6 +41,34 @@ describe("resolveHouseholdTimezone", () => { }); }); +describe("resolveInternalApiBase", () => { + it("uses loopback instead of the public request origin", () => { + const original = process.env.INTERNAL_API_BASE_URL; + const originalPort = process.env.PORT; + delete process.env.INTERNAL_API_BASE_URL; + process.env.PORT = "3000"; + + const base = resolveInternalApiBase(new Request("https://fam.ginnoir.com/api/agent/chat")); + assert.equal(base, "http://127.0.0.1:3000"); + + if (original === undefined) delete process.env.INTERNAL_API_BASE_URL; + else process.env.INTERNAL_API_BASE_URL = original; + if (originalPort === undefined) delete process.env.PORT; + else process.env.PORT = originalPort; + }); + + it("honors INTERNAL_API_BASE_URL when set", () => { + const original = process.env.INTERNAL_API_BASE_URL; + process.env.INTERNAL_API_BASE_URL = "http://127.0.0.1:3010/"; + + const base = resolveInternalApiBase(new Request("https://fam.ginnoir.com/api/agent/chat")); + assert.equal(base, "http://127.0.0.1:3010"); + + if (original === undefined) delete process.env.INTERNAL_API_BASE_URL; + else process.env.INTERNAL_API_BASE_URL = original; + }); +}); + describe("create_event calendar resolution", () => { it("uses the first calendar when calendarId and calendarName are omitted", async () => { const originalFetch = globalThis.fetch; @@ -45,13 +76,13 @@ describe("create_event calendar resolution", () => { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); - if (url.endsWith("/api/v1/calendars") && (!init?.method || init.method === "GET")) { + if (url.includes("/api/v1/calendars") && (!init?.method || init.method === "GET")) { return Response.json([ { id: "cal-1", name: "Family" }, { id: "cal-2", name: "Work" }, ]); } - if (url.endsWith("/api/v1/events") && init?.method === "POST") { + if (url.includes("/api/v1/events") && init?.method === "POST") { const body = JSON.parse(String(init.body)); posts.push({ path: url, body }); return Response.json({ id: "evt-1", ...body }, { status: 201 }); @@ -59,7 +90,11 @@ describe("create_event calendar resolution", () => { return new Response("not found", { status: 404 }); }) as typeof fetch; - const execute = createApiToolExecutor(new Request("http://localhost:3000/api/agent/chat")); + const execute = createApiToolExecutor( + new Request("https://fam.ginnoir.com/api/agent/chat", { + headers: { cookie: "authjs.session-token=test" }, + }), + ); const result = JSON.parse( await execute( "create_event", @@ -74,6 +109,7 @@ describe("create_event calendar resolution", () => { assert.equal(result.status, 201); assert.equal(result.body.calendarId, "cal-1"); assert.equal(posts.length, 1); + assert.match(posts[0]!.path, /^http:\/\/127\.0\.0\.1:3000\/api\/v1\/events/); globalThis.fetch = originalFetch; }); @@ -83,13 +119,13 @@ describe("create_event calendar resolution", () => { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); - if (url.endsWith("/api/v1/calendars") && (!init?.method || init.method === "GET")) { + if (url.includes("/api/v1/calendars") && (!init?.method || init.method === "GET")) { return Response.json([ { id: "cal-1", name: "Family" }, { id: "cal-2", name: "Work" }, ]); } - if (url.endsWith("/api/v1/events") && init?.method === "POST") { + if (url.includes("/api/v1/events") && init?.method === "POST") { const body = JSON.parse(String(init.body)); return Response.json({ id: "evt-1", ...body }, { status: 201 }); } @@ -114,4 +150,22 @@ describe("create_event calendar resolution", () => { globalThis.fetch = originalFetch; }); + + it("returns a clear error when the internal API is unreachable", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => { + throw new TypeError("fetch failed"); + }) as typeof fetch; + + const execute = createApiToolExecutor(new Request("https://fam.ginnoir.com/api/agent/chat")); + const result = JSON.parse(await execute("list_calendars", "{}")) as { + status: number; + body: { error?: string }; + }; + + assert.equal(result.status, 502); + assert.match(String(result.body.error), /unreachable/i); + + globalThis.fetch = originalFetch; + }); });