Compare commits

...
2 Commits
Author SHA1 Message Date
ginnoir 7bf4a801b3 chore: release v0.6.5
CI / checks (push) Has been skipped
Release Image / build-and-push (push) Successful in 7m19s
2026-07-09 00:38:50 -05:00
ginnoir 3e8fe2d06d fix(agent): call api v1 via loopback instead of public url
CI / checks (push) Has been cancelled
Tool self-fetches were hairpinning to fam.ginnoir.com and failing,
so list_calendars/create_event returned 500 and the model gave up.
2026-07-09 00:38:33 -05:00
6 changed files with 130 additions and 17 deletions
+2
View File
@@ -57,3 +57,5 @@ LLM_API_KEY=
LLM_MODEL=llama3.2 LLM_MODEL=llama3.2
# IANA timezone for assistant relative dates ("Thursday at 2"). Falls back to TZ, then America/Chicago. # IANA timezone for assistant relative dates ("Thursday at 2"). Falls back to TZ, then America/Chicago.
HOUSEHOLD_TIMEZONE=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
+6
View File
@@ -1,5 +1,11 @@
# Changelog # Changelog
## [0.6.5](https://github.com/ginnoir/famapp/compare/v0.6.4...v0.6.5) (2026-07-09)
### Bug Fixes
- **agent:** call api v1 via loopback instead of public url ([3e8fe2d](https://github.com/ginnoir/famapp/commit/3e8fe2d06dc31d3a1058b4b8942c46b1220a6b4c))
## [0.6.4](https://github.com/ginnoir/famapp/compare/v0.6.3...v0.6.4) (2026-07-09) ## [0.6.4](https://github.com/ginnoir/famapp/compare/v0.6.3...v0.6.4) (2026-07-09)
### Bug Fixes ### Bug Fixes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "famapp", "name": "famapp",
"version": "0.6.4", "version": "0.6.5",
"private": true, "private": true,
"type": "module", "type": "module",
"packageManager": "pnpm@10.33.3", "packageManager": "pnpm@10.33.3",
+13 -1
View File
@@ -160,8 +160,20 @@ export async function runAgentChat(options: {
try { try {
result = await executeTool(toolCall.function.name, toolCall.function.arguments); 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; 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) { } catch (err) {
status = 500; status = 500;
result = JSON.stringify({ result = JSON.stringify({
+48 -9
View File
@@ -1,3 +1,5 @@
import logger from "@/lib/logger";
type ApiCallResult = { type ApiCallResult = {
status: number; status: number;
body: unknown; body: unknown;
@@ -5,8 +7,22 @@ type ApiCallResult = {
export type ToolExecutor = (name: string, argsJson: string) => Promise<string>; export type ToolExecutor = (name: string, argsJson: string) => Promise<string>;
/** 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 { export function createApiToolExecutor(request: Request): ToolExecutor {
const origin = new URL(request.url).origin; const origin = resolveInternalApiBase(request);
return async (name: string, argsJson: string) => { return async (name: string, argsJson: string) => {
const args = parseArgs(argsJson); const args = parseArgs(argsJson);
@@ -522,14 +538,30 @@ async function callApi(
path: string, path: string,
body?: Record<string, unknown>, body?: Record<string, unknown>,
): Promise<ApiCallResult> { ): Promise<ApiCallResult> {
const response = await fetch(`${origin}${path}`, { const url = `${origin}${path}`;
method, const headers: Record<string, string> = {
headers: { "Content-Type": "application/json",
"Content-Type": "application/json", };
cookie: request.headers.get("cookie") ?? "", const cookie = request.headers.get("cookie");
}, if (cookie) headers.cookie = cookie;
body: body !== undefined ? JSON.stringify(body) : undefined, 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(); const text = await response.text();
let parsed: unknown = null; 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 }; return { status: response.status, body: parsed };
} }
+60 -6
View File
@@ -1,7 +1,10 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { describe, it } from "node:test"; import { describe, it } from "node:test";
import { appendAgentRuntimeContext, resolveHouseholdTimezone } from "../../src/modules/agent/tools"; 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", () => { describe("appendAgentRuntimeContext", () => {
it("appends current time and timezone to the prompt", () => { 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", () => { describe("create_event calendar resolution", () => {
it("uses the first calendar when calendarId and calendarName are omitted", async () => { it("uses the first calendar when calendarId and calendarName are omitted", async () => {
const originalFetch = globalThis.fetch; const originalFetch = globalThis.fetch;
@@ -45,13 +76,13 @@ describe("create_event calendar resolution", () => {
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input); 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([ return Response.json([
{ id: "cal-1", name: "Family" }, { id: "cal-1", name: "Family" },
{ id: "cal-2", name: "Work" }, { 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)); const body = JSON.parse(String(init.body));
posts.push({ path: url, body }); posts.push({ path: url, body });
return Response.json({ id: "evt-1", ...body }, { status: 201 }); 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 }); return new Response("not found", { status: 404 });
}) as typeof fetch; }) 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( const result = JSON.parse(
await execute( await execute(
"create_event", "create_event",
@@ -74,6 +109,7 @@ describe("create_event calendar resolution", () => {
assert.equal(result.status, 201); assert.equal(result.status, 201);
assert.equal(result.body.calendarId, "cal-1"); assert.equal(result.body.calendarId, "cal-1");
assert.equal(posts.length, 1); assert.equal(posts.length, 1);
assert.match(posts[0]!.path, /^http:\/\/127\.0\.0\.1:3000\/api\/v1\/events/);
globalThis.fetch = originalFetch; globalThis.fetch = originalFetch;
}); });
@@ -83,13 +119,13 @@ describe("create_event calendar resolution", () => {
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input); 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([ return Response.json([
{ id: "cal-1", name: "Family" }, { id: "cal-1", name: "Family" },
{ id: "cal-2", name: "Work" }, { 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)); const body = JSON.parse(String(init.body));
return Response.json({ id: "evt-1", ...body }, { status: 201 }); return Response.json({ id: "evt-1", ...body }, { status: 201 });
} }
@@ -114,4 +150,22 @@ describe("create_event calendar resolution", () => {
globalThis.fetch = originalFetch; 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;
});
}); });