Compare commits
9
Commits
v0.6.2
..
7704924d88
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7704924d88 | ||
|
|
7ffc2f9522 | ||
|
|
f3c6137fed | ||
|
|
7bf4a801b3 | ||
|
|
3e8fe2d06d | ||
|
|
60eb101015 | ||
|
|
72d123b9a0 | ||
|
|
9bf8e508c7 | ||
|
|
d3e79edb9e |
@@ -55,3 +55,7 @@ LLM_PROVIDER=openai
|
|||||||
LLM_BASE_URL=
|
LLM_BASE_URL=
|
||||||
LLM_API_KEY=
|
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.
|
||||||
|
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
|
||||||
|
|||||||
@@ -76,6 +76,8 @@ src/
|
|||||||
|
|
||||||
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
||||||
|
|
||||||
|
**Completion rule for module additions and behavior changes:** include the authenticated v1 API and OpenAPI documentation, assistant tools backed by that API, and a complete reminder lifecycle for every user-visible due date. API, agent, and UI must call the same scoped server services; create/update must synchronize unfired reminders and delete must cancel them.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Data model (v1)
|
## Data model (v1)
|
||||||
|
|||||||
@@ -1,5 +1,23 @@
|
|||||||
# 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)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **agent:** stop tool thrash after writes and log rounds ([72d123b](https://github.com/ginnoir/famapp/commit/72d123b9a0f67589d92614a8d2138912585b0d79))
|
||||||
|
|
||||||
|
## [0.6.3](https://github.com/ginnoir/famapp/compare/v0.6.2...v0.6.3) (2026-07-09)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **agent:** raise tool rounds and ease calendar creates ([d3e79ed](https://github.com/ginnoir/famapp/commit/d3e79edb9ef0b931fa9d6e6629dad2677d661741))
|
||||||
|
|
||||||
## [0.6.2](https://github.com/ginnoir/famapp/compare/v0.6.1...v0.6.2) (2026-07-09)
|
## [0.6.2](https://github.com/ginnoir/famapp/compare/v0.6.1...v0.6.2) (2026-07-09)
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ src/
|
|||||||
|
|
||||||
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
||||||
|
|
||||||
|
**Completion rule for module additions and behavior changes:** include the authenticated v1 API and OpenAPI documentation, assistant tools backed by that API, and a complete reminder lifecycle for every user-visible due date. API, agent, and UI must call the same scoped server services; create/update must synchronize unfired reminders and delete must cancel them.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Data model (v1)
|
## Data model (v1)
|
||||||
|
|||||||
@@ -111,5 +111,6 @@ P2/P3 backlog is filed on Gitea only (no task briefs yet) — see `docs/issues-m
|
|||||||
- Repo: https://github.com/ginnoir/famapp (HTTPS remote on `origin`).
|
- Repo: https://github.com/ginnoir/famapp (HTTPS remote on `origin`).
|
||||||
- Local dev tooling installed: Node 22+, pnpm 10.33.3.
|
- Local dev tooling installed: Node 22+, pnpm 10.33.3.
|
||||||
- `.env` is **not** committed; copy `.env.example` → `.env` when needed.
|
- `.env` is **not** committed; copy `.env.example` → `.env` when needed.
|
||||||
|
- Assistant relative dates use `HOUSEHOLD_TIMEZONE` (default `America/Chicago` if unset).
|
||||||
- VS Code recommended extensions in `.vscode/extensions.json`; copy `.vscode/settings.json.example` → `.vscode/settings.json` for the workspace defaults.
|
- VS Code recommended extensions in `.vscode/extensions.json`; copy `.vscode/settings.json.example` → `.vscode/settings.json` for the workspace defaults.
|
||||||
- Memory files (cross-session, only seen by Claude): `C:\Users\MattC\.claude\projects\C--Users-MattC-Documents-famapp\memory\`.
|
- Memory files (cross-session, only seen by Claude): `C:\Users\MattC\.claude\projects\C--Users-MattC-Documents-famapp\memory\`.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
|||||||
|
-- Custom SQL migration file, put your code below! --
|
||||||
|
CREATE TABLE "pets" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"species" text NOT NULL,
|
||||||
|
"breed" text,
|
||||||
|
"birth_date" date,
|
||||||
|
"notes" text,
|
||||||
|
"primary_image_url" text,
|
||||||
|
"images" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pets_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "pet_appointments" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"pet_id" uuid NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"title" text NOT NULL,
|
||||||
|
"appointment_at" timestamp with time zone NOT NULL,
|
||||||
|
"clinic" text,
|
||||||
|
"notes" text,
|
||||||
|
"calendar_event_id" uuid,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pet_appointments_pet_id_pets_id_fk" FOREIGN KEY ("pet_id") REFERENCES "public"."pets"("id") ON DELETE cascade ON UPDATE no action,
|
||||||
|
CONSTRAINT "pet_appointments_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "pet_vaccinations" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"pet_id" uuid NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"administered_on" date NOT NULL,
|
||||||
|
"due_on" date,
|
||||||
|
"provider" text,
|
||||||
|
"notes" text,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pet_vaccinations_pet_id_pets_id_fk" FOREIGN KEY ("pet_id") REFERENCES "public"."pets"("id") ON DELETE cascade ON UPDATE no action,
|
||||||
|
CONSTRAINT "pet_vaccinations_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "pet_prescriptions" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"pet_id" uuid NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"medication" text NOT NULL,
|
||||||
|
"dosage" text NOT NULL,
|
||||||
|
"instructions" text,
|
||||||
|
"prescribed_on" date,
|
||||||
|
"expires_on" date,
|
||||||
|
"refills_remaining" integer,
|
||||||
|
"active" boolean DEFAULT true NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pet_prescriptions_pet_id_pets_id_fk" FOREIGN KEY ("pet_id") REFERENCES "public"."pets"("id") ON DELETE cascade ON UPDATE no action,
|
||||||
|
CONSTRAINT "pet_prescriptions_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pets_household_idx" ON "pets" USING btree ("household_id");
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pet_appointments_pet_at_idx" ON "pet_appointments" USING btree ("pet_id", "appointment_at");
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pet_vaccinations_pet_due_idx" ON "pet_vaccinations" USING btree ("pet_id", "due_on");
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pet_prescriptions_pet_active_idx" ON "pet_prescriptions" USING btree ("pet_id", "active");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -190,6 +190,13 @@
|
|||||||
"when": 1783561000000,
|
"when": 1783561000000,
|
||||||
"tag": "0026_assistant_model_route",
|
"tag": "0026_assistant_model_route",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 27,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1783648174004,
|
||||||
|
"tag": "0027_pets_module",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "famapp",
|
"name": "famapp",
|
||||||
"version": "0.6.2",
|
"version": "0.6.5",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "pnpm@10.33.3",
|
"packageManager": "pnpm@10.33.3",
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
export function resolveHouseholdTimezone(): string {
|
||||||
|
return process.env.HOUSEHOLD_TIMEZONE?.trim() || process.env.TZ?.trim() || "America/Chicago";
|
||||||
|
}
|
||||||
|
|
||||||
|
function part(parts: Intl.DateTimeFormatPart[], type: Intl.DateTimeFormatPartTypes): number {
|
||||||
|
const value = parts.find((item) => item.type === type)?.value;
|
||||||
|
if (!value) throw new Error(`Missing ${type} timezone part`);
|
||||||
|
return Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function householdDateAt(
|
||||||
|
isoDate: string,
|
||||||
|
hour: number,
|
||||||
|
timeZone = resolveHouseholdTimezone(),
|
||||||
|
): Date {
|
||||||
|
const [year, month, day] = isoDate.split("-").map(Number);
|
||||||
|
if (!year || !month || !day || hour < 0 || hour > 23) throw new Error("Invalid household date");
|
||||||
|
|
||||||
|
const candidate = Date.UTC(year, month - 1, day, hour);
|
||||||
|
const parts = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone,
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
second: "2-digit",
|
||||||
|
hourCycle: "h23",
|
||||||
|
}).formatToParts(new Date(candidate));
|
||||||
|
const formattedAsUtc = Date.UTC(
|
||||||
|
part(parts, "year"),
|
||||||
|
part(parts, "month") - 1,
|
||||||
|
part(parts, "day"),
|
||||||
|
part(parts, "hour"),
|
||||||
|
part(parts, "minute"),
|
||||||
|
part(parts, "second"),
|
||||||
|
);
|
||||||
|
return new Date(candidate - (formattedAsUtc - candidate));
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ export type AssistantChatMessage = {
|
|||||||
role: "user" | "assistant";
|
role: "user" | "assistant";
|
||||||
content: string;
|
content: string;
|
||||||
imageUrl?: string;
|
imageUrl?: string;
|
||||||
|
toolCalls?: Array<{ name: string; status: number }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const STORAGE_VERSION = "v2";
|
const STORAGE_VERSION = "v2";
|
||||||
@@ -19,6 +20,14 @@ function isValidMessage(value: unknown): value is AssistantChatMessage {
|
|||||||
if (row.role !== "user" && row.role !== "assistant") return false;
|
if (row.role !== "user" && row.role !== "assistant") return false;
|
||||||
if (typeof row.content !== "string" || row.content.trim().length === 0) return false;
|
if (typeof row.content !== "string" || row.content.trim().length === 0) return false;
|
||||||
if (row.imageUrl !== undefined && typeof row.imageUrl !== "string") return false;
|
if (row.imageUrl !== undefined && typeof row.imageUrl !== "string") return false;
|
||||||
|
if (row.toolCalls !== undefined) {
|
||||||
|
if (!Array.isArray(row.toolCalls)) return false;
|
||||||
|
for (const call of row.toolCalls) {
|
||||||
|
if (!call || typeof call !== "object") return false;
|
||||||
|
const entry = call as Record<string, unknown>;
|
||||||
|
if (typeof entry.name !== "string" || typeof entry.status !== "number") return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -229,7 +229,11 @@ export function AssistantPanel({ configured, userId, assistantName, assistantMod
|
|||||||
|
|
||||||
setMessages((current) => [
|
setMessages((current) => [
|
||||||
...current,
|
...current,
|
||||||
{ role: "assistant", content: result.message.content },
|
{
|
||||||
|
role: "assistant",
|
||||||
|
content: result.message.content,
|
||||||
|
...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {}),
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -347,6 +351,13 @@ export function AssistantPanel({ configured, userId, assistantName, assistantMod
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{message.content}
|
{message.content}
|
||||||
|
{message.role === "assistant" &&
|
||||||
|
message.toolCalls &&
|
||||||
|
message.toolCalls.length > 0 ? (
|
||||||
|
<p className="mt-1 text-[10px] text-muted-foreground">
|
||||||
|
{message.toolCalls.map((call) => `${call.name}→${call.status}`).join(" · ")}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
const MUTATION_TOOLS = new Set([
|
||||||
|
"add_list_item",
|
||||||
|
"update_list_item",
|
||||||
|
"delete_list_item",
|
||||||
|
"create_list",
|
||||||
|
"update_list",
|
||||||
|
"delete_list",
|
||||||
|
"create_event",
|
||||||
|
"update_event",
|
||||||
|
"delete_event",
|
||||||
|
"create_calendar",
|
||||||
|
"create_note",
|
||||||
|
"update_note",
|
||||||
|
"delete_note",
|
||||||
|
"create_journal_entry",
|
||||||
|
"update_journal_entry",
|
||||||
|
"delete_journal_entry",
|
||||||
|
"create_garden_plant",
|
||||||
|
"update_garden_plant",
|
||||||
|
"delete_garden_plant",
|
||||||
|
"create_garden_container",
|
||||||
|
"update_garden_container",
|
||||||
|
"delete_garden_container",
|
||||||
|
"log_garden_care",
|
||||||
|
"create_garden_care_schedule",
|
||||||
|
"update_garden_care_schedule",
|
||||||
|
"delete_garden_care_schedule",
|
||||||
|
"schedule_garden_care_on_calendar",
|
||||||
|
"create_bang",
|
||||||
|
"update_bang",
|
||||||
|
"delete_bang",
|
||||||
|
"create_share_link",
|
||||||
|
"revoke_share_link",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function isMutationTool(name: string): boolean {
|
||||||
|
return MUTATION_TOOLS.has(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSuccessfulWrite(name: string, status: number, argsJson = ""): boolean {
|
||||||
|
if (!isSuccessfulStatus(status)) return false;
|
||||||
|
if (isMutationTool(name)) return true;
|
||||||
|
if (name !== "call_api") return false;
|
||||||
|
try {
|
||||||
|
const args = JSON.parse(argsJson || "{}") as { method?: string };
|
||||||
|
const method = typeof args.method === "string" ? args.method.toUpperCase() : "";
|
||||||
|
return method === "POST" || method === "PATCH" || method === "DELETE";
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSuccessfulStatus(status: number): boolean {
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fingerprintToolCalls(calls: Array<{ name: string; arguments: string }>): string {
|
||||||
|
return calls.map((call) => `${call.name}:${normalizeArgs(call.arguments)}`).join("|");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function truncateToolResult(result: string, maxChars = 6000): string {
|
||||||
|
if (result.length <= maxChars) return result;
|
||||||
|
return `${result.slice(0, maxChars)}\n…[truncated ${result.length - maxChars} chars]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function summarizeToolTrace(toolCalls: Array<{ name: string; status: number }>): string {
|
||||||
|
if (toolCalls.length === 0) return "No tools were called.";
|
||||||
|
return toolCalls.map((call) => `${call.name}→${call.status}`).join(", ");
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeArgs(argsJson: string): string {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(argsJson || "{}");
|
||||||
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||||
|
return JSON.stringify(parsed);
|
||||||
|
}
|
||||||
|
const sorted: Record<string, unknown> = {};
|
||||||
|
for (const key of Object.keys(parsed as Record<string, unknown>).sort()) {
|
||||||
|
sorted[key] = (parsed as Record<string, unknown>)[key];
|
||||||
|
}
|
||||||
|
return JSON.stringify(sorted);
|
||||||
|
} catch {
|
||||||
|
return argsJson.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,20 @@
|
|||||||
|
import logger from "@/lib/logger";
|
||||||
import { createLlmClient, type ChatMessage, type LlmClient } from "@/lib/llm";
|
import { createLlmClient, type ChatMessage, type LlmClient } from "@/lib/llm";
|
||||||
import { buildVisionContentParts, textFromMessageContent } from "@/lib/llm/content";
|
import { buildVisionContentParts, textFromMessageContent } from "@/lib/llm/content";
|
||||||
import { AGENT_SYSTEM_PROMPT, AGENT_TOOLS } from "../tools";
|
import { AGENT_SYSTEM_PROMPT, AGENT_TOOLS, appendAgentRuntimeContext } from "../tools";
|
||||||
import type { ClientChatMessage } from "../messages";
|
import type { ClientChatMessage } from "../messages";
|
||||||
import { describeToolActivity } from "../tool-labels";
|
import { describeToolActivity } from "../tool-labels";
|
||||||
import { createApiToolExecutor, type ToolExecutor } from "../tool-executor";
|
import { createApiToolExecutor, type ToolExecutor } from "../tool-executor";
|
||||||
|
import {
|
||||||
|
fingerprintToolCalls,
|
||||||
|
isSuccessfulWrite,
|
||||||
|
summarizeToolTrace,
|
||||||
|
truncateToolResult,
|
||||||
|
} from "./loop-guards";
|
||||||
import { resolveAssistantImageDataUrls } from "./resolve-images";
|
import { resolveAssistantImageDataUrls } from "./resolve-images";
|
||||||
import { thinkingLabel, type AgentProgressEvent } from "./progress";
|
import { thinkingLabel, type AgentProgressEvent } from "./progress";
|
||||||
|
|
||||||
const MAX_TOOL_ROUNDS = 8;
|
const MAX_TOOL_ROUNDS = 24;
|
||||||
|
|
||||||
export type AgentToolCallSummary = {
|
export type AgentToolCallSummary = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -41,6 +48,21 @@ async function toLlmUserMessage(message: ClientChatMessage): Promise<ChatMessage
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function forceReplyAfterWrite(writeNames: string[]): ChatMessage {
|
||||||
|
return {
|
||||||
|
role: "user",
|
||||||
|
content: `The write already succeeded (${writeNames.join(", ")}). Stop calling tools and reply to the user in one short sentence confirming what you did.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function forceReplyAfterRepeat(): ChatMessage {
|
||||||
|
return {
|
||||||
|
role: "user",
|
||||||
|
content:
|
||||||
|
"You repeated the same tool call. Stop calling tools and reply with what you already know, or ask one clarifying question.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function runAgentChat(options: {
|
export async function runAgentChat(options: {
|
||||||
messages: ClientChatMessage[];
|
messages: ClientChatMessage[];
|
||||||
request: Request;
|
request: Request;
|
||||||
@@ -53,7 +75,7 @@ export async function runAgentChat(options: {
|
|||||||
const llm = options.llm ?? createLlmClient({ model: options.model });
|
const llm = options.llm ?? createLlmClient({ model: options.model });
|
||||||
const executeTool = options.executeTool ?? createApiToolExecutor(options.request);
|
const executeTool = options.executeTool ?? createApiToolExecutor(options.request);
|
||||||
const onProgress = options.onProgress;
|
const onProgress = options.onProgress;
|
||||||
const systemPrompt = options.systemPrompt ?? AGENT_SYSTEM_PROMPT;
|
const systemPrompt = appendAgentRuntimeContext(options.systemPrompt ?? AGENT_SYSTEM_PROMPT);
|
||||||
|
|
||||||
const userMessages = await Promise.all(
|
const userMessages = await Promise.all(
|
||||||
options.messages.map((message) => toLlmUserMessage(message)),
|
options.messages.map((message) => toLlmUserMessage(message)),
|
||||||
@@ -62,13 +84,16 @@ export async function runAgentChat(options: {
|
|||||||
const transcript: ChatMessage[] = [{ role: "system", content: systemPrompt }, ...userMessages];
|
const transcript: ChatMessage[] = [{ role: "system", content: systemPrompt }, ...userMessages];
|
||||||
|
|
||||||
const toolCalls: AgentToolCallSummary[] = [];
|
const toolCalls: AgentToolCallSummary[] = [];
|
||||||
|
const seenFingerprints = new Set<string>();
|
||||||
|
const successfulWriteNames: string[] = [];
|
||||||
|
let forceReply = false;
|
||||||
|
|
||||||
for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {
|
for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {
|
||||||
onProgress?.({ type: "thinking", label: thinkingLabel(round), round });
|
onProgress?.({ type: "thinking", label: thinkingLabel(round), round });
|
||||||
|
|
||||||
const completion = await llm.chatCompletion({
|
const completion = await llm.chatCompletion({
|
||||||
messages: transcript,
|
messages: transcript,
|
||||||
tools: AGENT_TOOLS,
|
tools: forceReply ? undefined : AGENT_TOOLS,
|
||||||
});
|
});
|
||||||
|
|
||||||
const assistantMessage = completion.message;
|
const assistantMessage = completion.message;
|
||||||
@@ -76,6 +101,15 @@ export async function runAgentChat(options: {
|
|||||||
|
|
||||||
if (!assistantMessage.tool_calls?.length) {
|
if (!assistantMessage.tool_calls?.length) {
|
||||||
onProgress?.({ type: "responding", label: "Writing a reply…" });
|
onProgress?.({ type: "responding", label: "Writing a reply…" });
|
||||||
|
logger.info(
|
||||||
|
{
|
||||||
|
msg: "agent.chat.done",
|
||||||
|
rounds: round + 1,
|
||||||
|
toolCalls: toolCalls.map((call) => `${call.name}:${call.status}`),
|
||||||
|
forcedReply: forceReply,
|
||||||
|
},
|
||||||
|
"agent chat completed",
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
message: {
|
message: {
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
@@ -87,6 +121,36 @@ export async function runAgentChat(options: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (forceReply) {
|
||||||
|
logger.warn(
|
||||||
|
{
|
||||||
|
msg: "agent.chat.forced_tools_ignored",
|
||||||
|
round,
|
||||||
|
names: assistantMessage.tool_calls.map((c) => c.function.name),
|
||||||
|
},
|
||||||
|
"model kept calling tools after force-reply",
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fingerprint = fingerprintToolCalls(
|
||||||
|
assistantMessage.tool_calls.map((call) => ({
|
||||||
|
name: call.function.name,
|
||||||
|
arguments: call.function.arguments,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (seenFingerprints.has(fingerprint)) {
|
||||||
|
logger.warn(
|
||||||
|
{ msg: "agent.chat.duplicate_tools", round, fingerprint, toolCalls: fingerprint },
|
||||||
|
"duplicate tool round detected",
|
||||||
|
);
|
||||||
|
transcript.push(forceReplyAfterRepeat());
|
||||||
|
forceReply = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seenFingerprints.add(fingerprint);
|
||||||
|
|
||||||
for (const toolCall of assistantMessage.tool_calls) {
|
for (const toolCall of assistantMessage.tool_calls) {
|
||||||
const label = describeToolActivity(toolCall.function.name, toolCall.function.arguments);
|
const label = describeToolActivity(toolCall.function.name, toolCall.function.arguments);
|
||||||
onProgress?.({ type: "tool", name: toolCall.function.name, label });
|
onProgress?.({ type: "tool", name: toolCall.function.name, label });
|
||||||
@@ -96,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({
|
||||||
@@ -107,21 +183,69 @@ export async function runAgentChat(options: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
toolCalls.push({ name: toolCall.function.name, status });
|
toolCalls.push({ name: toolCall.function.name, status });
|
||||||
|
logger.info(
|
||||||
|
{
|
||||||
|
msg: "agent.chat.tool",
|
||||||
|
round,
|
||||||
|
name: toolCall.function.name,
|
||||||
|
status,
|
||||||
|
args: toolCall.function.arguments.slice(0, 300),
|
||||||
|
},
|
||||||
|
"agent tool call",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isSuccessfulWrite(toolCall.function.name, status, toolCall.function.arguments)) {
|
||||||
|
successfulWriteNames.push(toolCall.function.name);
|
||||||
|
}
|
||||||
|
|
||||||
transcript.push({
|
transcript.push({
|
||||||
role: "tool",
|
role: "tool",
|
||||||
tool_call_id: toolCall.id,
|
tool_call_id: toolCall.id,
|
||||||
name: toolCall.function.name,
|
name: toolCall.function.name,
|
||||||
content: result,
|
content: truncateToolResult(result),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (successfulWriteNames.length > 0) {
|
||||||
|
transcript.push(forceReplyAfterWrite(successfulWriteNames));
|
||||||
|
forceReply = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onProgress?.({ type: "responding", label: "Wrapping up…" });
|
onProgress?.({ type: "responding", label: "Wrapping up…" });
|
||||||
|
const trace = summarizeToolTrace(toolCalls);
|
||||||
|
|
||||||
|
if (successfulWriteNames.length > 0) {
|
||||||
|
logger.warn(
|
||||||
|
{
|
||||||
|
msg: "agent.chat.forced_summary",
|
||||||
|
rounds: MAX_TOOL_ROUNDS,
|
||||||
|
toolCalls: toolCalls.map((call) => `${call.name}:${call.status}`),
|
||||||
|
},
|
||||||
|
"agent summarizing after write without clean stop",
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
message: {
|
message: {
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
content: "I hit the tool-call limit for this request. Please try a simpler question.",
|
content: `Done. Completed: ${[...new Set(successfulWriteNames)].join(", ")}.`,
|
||||||
|
},
|
||||||
|
toolCalls,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.warn(
|
||||||
|
{
|
||||||
|
msg: "agent.chat.tool_limit",
|
||||||
|
rounds: MAX_TOOL_ROUNDS,
|
||||||
|
toolCalls: toolCalls.map((call) => `${call.name}:${call.status}`),
|
||||||
|
forcedReply: forceReply,
|
||||||
|
},
|
||||||
|
"agent hit tool-call limit",
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
message: {
|
||||||
|
role: "assistant",
|
||||||
|
content: `I hit the tool-call limit for this request. Tools used: ${trace}.`,
|
||||||
},
|
},
|
||||||
toolCalls,
|
toolCalls,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -111,8 +127,11 @@ async function dispatchTool(
|
|||||||
return callApi(request, origin, "GET", `/api/v1/events?${qs.toString()}`);
|
return callApi(request, origin, "GET", `/api/v1/events?${qs.toString()}`);
|
||||||
}
|
}
|
||||||
case "create_event": {
|
case "create_event": {
|
||||||
|
const resolved = await resolveCalendarId(args, request, origin);
|
||||||
|
if ("error" in resolved) return resolved.error;
|
||||||
|
|
||||||
const body: Record<string, unknown> = {
|
const body: Record<string, unknown> = {
|
||||||
calendarId: requireString(args, "calendarId"),
|
calendarId: resolved.calendarId,
|
||||||
title: requireString(args, "title"),
|
title: requireString(args, "title"),
|
||||||
startAt: requireString(args, "startAt"),
|
startAt: requireString(args, "startAt"),
|
||||||
endAt: requireString(args, "endAt"),
|
endAt: requireString(args, "endAt"),
|
||||||
@@ -375,6 +394,49 @@ async function dispatchTool(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function resolveCalendarId(
|
||||||
|
args: Record<string, unknown>,
|
||||||
|
request: Request,
|
||||||
|
origin: string,
|
||||||
|
): Promise<{ calendarId: string } | { error: ApiCallResult }> {
|
||||||
|
const calendarId = typeof args.calendarId === "string" ? args.calendarId.trim() : "";
|
||||||
|
if (calendarId) return { calendarId };
|
||||||
|
|
||||||
|
const calendarsResult = await callApi(request, origin, "GET", "/api/v1/calendars");
|
||||||
|
if (calendarsResult.status !== 200 || !Array.isArray(calendarsResult.body)) {
|
||||||
|
return { error: calendarsResult };
|
||||||
|
}
|
||||||
|
|
||||||
|
const calendars = calendarsResult.body as Array<{ id?: string; name?: string }>;
|
||||||
|
const calendarName =
|
||||||
|
typeof args.calendarName === "string" ? args.calendarName.trim().toLowerCase() : "";
|
||||||
|
|
||||||
|
if (calendarName) {
|
||||||
|
const match = calendars.find(
|
||||||
|
(calendar) =>
|
||||||
|
typeof calendar.name === "string" && calendar.name.toLowerCase() === calendarName,
|
||||||
|
);
|
||||||
|
if (!match?.id) {
|
||||||
|
return {
|
||||||
|
error: {
|
||||||
|
status: 404,
|
||||||
|
body: {
|
||||||
|
error: `No calendar named "${args.calendarName}"`,
|
||||||
|
calendars: calendars.map((calendar) => ({ id: calendar.id, name: calendar.name })),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { calendarId: match.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
const first = calendars[0];
|
||||||
|
if (!first?.id) {
|
||||||
|
return { error: { status: 404, body: { error: "No calendars found" } } };
|
||||||
|
}
|
||||||
|
return { calendarId: first.id };
|
||||||
|
}
|
||||||
|
|
||||||
function requireString(args: Record<string, unknown>, key: string): string {
|
function requireString(args: Record<string, unknown>, key: string): string {
|
||||||
const value = args[key];
|
const value = args[key];
|
||||||
if (typeof value !== "string" || value.trim().length === 0) {
|
if (typeof value !== "string" || value.trim().length === 0) {
|
||||||
@@ -405,13 +467,18 @@ async function getApiDocs(args: Record<string, unknown>): Promise<ApiCallResult>
|
|||||||
const specPath = path.join(process.cwd(), "docs", "api", "openapi.yaml");
|
const specPath = path.join(process.cwd(), "docs", "api", "openapi.yaml");
|
||||||
const spec = await readFile(specPath, "utf8");
|
const spec = await readFile(specPath, "utf8");
|
||||||
const search = typeof args.search === "string" ? args.search.trim().toLowerCase() : "";
|
const search = typeof args.search === "string" ? args.search.trim().toLowerCase() : "";
|
||||||
|
const pathLines = spec
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter((line) => line.startsWith("/api/v1/"));
|
||||||
|
|
||||||
if (!search) {
|
if (!search) {
|
||||||
return {
|
return {
|
||||||
status: 200,
|
status: 200,
|
||||||
body: {
|
body: {
|
||||||
spec,
|
paths: pathLines.slice(0, 80),
|
||||||
hint: "Pass search to filter paths, or use call_api with a /api/v1/* path.",
|
pathCount: pathLines.length,
|
||||||
|
hint: "Pass search (e.g. calendar, events, lists) to get matching lines. Do not request the full OpenAPI dump.",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -423,8 +490,8 @@ async function getApiDocs(args: Record<string, unknown>): Promise<ApiCallResult>
|
|||||||
body: {
|
body: {
|
||||||
search,
|
search,
|
||||||
matchCount: matches.length,
|
matchCount: matches.length,
|
||||||
matches: matches.slice(0, 100),
|
matches: matches.slice(0, 40),
|
||||||
hint: "Use call_api with method and path from the matches above.",
|
hint: "Use a dedicated tool when one exists; otherwise call_api with method and path from the matches above.",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -471,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;
|
||||||
|
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,
|
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;
|
||||||
@@ -490,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 };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -159,11 +159,16 @@ export const AGENT_TOOLS: AgentToolDefinition[] = [
|
|||||||
type: "function",
|
type: "function",
|
||||||
function: {
|
function: {
|
||||||
name: "create_event",
|
name: "create_event",
|
||||||
description: "Create a calendar event.",
|
description:
|
||||||
|
"Create a calendar event. Provide calendarId, or calendarName to match by name, or omit both to use the first visible calendar.",
|
||||||
parameters: {
|
parameters: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
calendarId: { type: "string" },
|
calendarId: { type: "string", description: "UUID of the calendar" },
|
||||||
|
calendarName: {
|
||||||
|
type: "string",
|
||||||
|
description: "Calendar display name when calendarId is unknown",
|
||||||
|
},
|
||||||
title: { type: "string" },
|
title: { type: "string" },
|
||||||
startAt: { type: "string", description: "ISO 8601 start" },
|
startAt: { type: "string", description: "ISO 8601 start" },
|
||||||
endAt: { type: "string", description: "ISO 8601 end" },
|
endAt: { type: "string", description: "ISO 8601 end" },
|
||||||
@@ -175,7 +180,7 @@ export const AGENT_TOOLS: AgentToolDefinition[] = [
|
|||||||
description: "Optional reminder N minutes before start",
|
description: "Optional reminder N minutes before start",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
required: ["calendarId", "title", "startAt", "endAt"],
|
required: ["title", "startAt", "endAt"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -713,15 +718,16 @@ export const AGENT_TOOLS: AgentToolDefinition[] = [
|
|||||||
function: {
|
function: {
|
||||||
name: "get_api_docs",
|
name: "get_api_docs",
|
||||||
description:
|
description:
|
||||||
"Read famapp REST API documentation (OpenAPI). Use when unsure which endpoint to call or no dedicated tool exists. Pass search to filter relevant paths.",
|
"Search famapp REST API docs for /api/v1 paths. Always pass search. Returns matching lines only — not the full OpenAPI file.",
|
||||||
parameters: {
|
parameters: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
search: {
|
search: {
|
||||||
type: "string",
|
type: "string",
|
||||||
description: "Optional keyword to filter paths (e.g. garden, share, journal)",
|
description: "Keyword to filter paths (e.g. garden, share, journal, events)",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
required: ["search"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -762,13 +768,15 @@ export const AGENT_SYSTEM_PROMPT = `You are the famapp household assistant. Help
|
|||||||
|
|
||||||
Use the provided tools to read and update data. Prefer calling tools instead of guessing. Be concise and friendly.
|
Use the provided tools to read and update data. Prefer calling tools instead of guessing. Be concise and friendly.
|
||||||
|
|
||||||
When no dedicated tool fits, or you are unsure how to do something:
|
Prefer a dedicated tool when one exists (create_event, add_list_item, create_note, etc.). After a successful write (2xx), stop calling tools and confirm in one short sentence — do not re-list or re-create.
|
||||||
1. Call get_api_docs with a relevant search term to find the right /api/v1/* endpoint.
|
When no dedicated tool fits, or you need an endpoint that is not wrapped yet:
|
||||||
|
1. Call get_api_docs with a relevant search term (always pass search; never request the full spec).
|
||||||
2. Call call_api with the documented method, path, query, and body.
|
2. Call call_api with the documented method, path, query, and body.
|
||||||
|
If a tool call fails, read the error body and fix the arguments before trying a different approach. Do not repeat the exact same tool call.
|
||||||
|
|
||||||
When the user sends a photo, read dates, times, locations, and action items from it, then use tools to act.
|
When the user sends a photo, read dates, times, locations, and action items from it, then use tools to act.
|
||||||
|
|
||||||
Lists: resolve list ids via list_lists. To complete items, list_list_items then update_list_item with done: true.
|
Lists: resolve list ids via list_lists, or pass listType to add_list_item. To complete items, list_list_items then update_list_item with done: true.
|
||||||
|
|
||||||
Journal: per-user private entries. Valid mood ids: ${JOURNAL_MOOD_IDS}. stress is 1-10. pillsTaken is boolean.
|
Journal: per-user private entries. Valid mood ids: ${JOURNAL_MOOD_IDS}. stress is 1-10. pillsTaken is boolean.
|
||||||
|
|
||||||
@@ -776,4 +784,32 @@ Garden: care types are free text (water, fertilize, prune, etc.). Use list_garde
|
|||||||
|
|
||||||
Sharing: journal entries are not shareable. Shareable types: calendar, calendar.event, list, note, garden.plant, garden.container.
|
Sharing: journal entries are not shareable. Shareable types: calendar, calendar.event, list, note, garden.plant, garden.container.
|
||||||
|
|
||||||
Calendar: use ISO 8601 datetimes. Bang dates use YYYY-MM-DD.`;
|
Calendar: use ISO 8601 datetimes with the household timezone below. Pass calendarId, or calendarName, or omit both to use the first visible calendar. Bang dates use YYYY-MM-DD.`;
|
||||||
|
|
||||||
|
export function resolveHouseholdTimezone(): string {
|
||||||
|
return process.env.HOUSEHOLD_TIMEZONE?.trim() || process.env.TZ?.trim() || "America/Chicago";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appendAgentRuntimeContext(prompt: string, now: Date = new Date()): string {
|
||||||
|
const timeZone = resolveHouseholdTimezone();
|
||||||
|
let localNow: string;
|
||||||
|
try {
|
||||||
|
localNow = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone,
|
||||||
|
weekday: "long",
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
timeZoneName: "short",
|
||||||
|
}).format(now);
|
||||||
|
} catch {
|
||||||
|
localNow = now.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${prompt.trim()}
|
||||||
|
|
||||||
|
Current time: ${localNow} (${timeZone}). ISO now: ${now.toISOString()}. Resolve relative dates from this clock.`;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import {
|
||||||
|
boolean,
|
||||||
|
date,
|
||||||
|
index,
|
||||||
|
integer,
|
||||||
|
jsonb,
|
||||||
|
pgTable,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
uuid,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
import { households } from "../_core/schema";
|
||||||
|
|
||||||
|
export const pets = pgTable(
|
||||||
|
"pets",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
species: text("species").notNull(),
|
||||||
|
breed: text("breed"),
|
||||||
|
birthDate: date("birth_date"),
|
||||||
|
notes: text("notes"),
|
||||||
|
primaryImageUrl: text("primary_image_url"),
|
||||||
|
images: jsonb("images").notNull().default([]).$type<string[]>(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pets_household_idx").on(table.householdId)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export const petAppointments = pgTable(
|
||||||
|
"pet_appointments",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
petId: uuid("pet_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pets.id, { onDelete: "cascade" }),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
title: text("title").notNull(),
|
||||||
|
appointmentAt: timestamp("appointment_at", { withTimezone: true }).notNull(),
|
||||||
|
clinic: text("clinic"),
|
||||||
|
notes: text("notes"),
|
||||||
|
calendarEventId: uuid("calendar_event_id"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pet_appointments_pet_at_idx").on(table.petId, table.appointmentAt)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export const petVaccinations = pgTable(
|
||||||
|
"pet_vaccinations",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
petId: uuid("pet_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pets.id, { onDelete: "cascade" }),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
administeredOn: date("administered_on").notNull(),
|
||||||
|
dueOn: date("due_on"),
|
||||||
|
provider: text("provider"),
|
||||||
|
notes: text("notes"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pet_vaccinations_pet_due_idx").on(table.petId, table.dueOn)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export const petPrescriptions = pgTable(
|
||||||
|
"pet_prescriptions",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
petId: uuid("pet_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pets.id, { onDelete: "cascade" }),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
medication: text("medication").notNull(),
|
||||||
|
dosage: text("dosage").notNull(),
|
||||||
|
instructions: text("instructions"),
|
||||||
|
prescribedOn: date("prescribed_on"),
|
||||||
|
expiresOn: date("expires_on"),
|
||||||
|
refillsRemaining: integer("refills_remaining"),
|
||||||
|
active: boolean("active").notNull().default(true),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pet_prescriptions_pet_active_idx").on(table.petId, table.active)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export type Pet = typeof pets.$inferSelect;
|
||||||
|
export type PetAppointment = typeof petAppointments.$inferSelect;
|
||||||
|
export type PetVaccination = typeof petVaccinations.$inferSelect;
|
||||||
|
export type PetPrescription = typeof petPrescriptions.$inferSelect;
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import type { ApiAuthContext } from "@/lib/api-auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getCurrentSession } from "@/lib/session";
|
||||||
|
import { logActivityForScope } from "@/modules/_core/activity";
|
||||||
|
import { cancelReminder, listReminderOffsets } from "@/modules/_core/reminders";
|
||||||
|
import { petAppointments, petPrescriptions, pets, petVaccinations } from "../schema";
|
||||||
|
import { syncPetAppointmentReminders, syncPetDueDateReminder } from "./reminders";
|
||||||
|
import {
|
||||||
|
appointmentInput,
|
||||||
|
appointmentUpdateInput,
|
||||||
|
petInput,
|
||||||
|
petUpdateInput,
|
||||||
|
prescriptionInput,
|
||||||
|
prescriptionUpdateInput,
|
||||||
|
vaccinationInput,
|
||||||
|
vaccinationUpdateInput,
|
||||||
|
} from "./schemas";
|
||||||
|
|
||||||
|
type Scope = Pick<ApiAuthContext, "householdId" | "userId">;
|
||||||
|
const idInput = z.object({ id: z.string().uuid() });
|
||||||
|
|
||||||
|
async function requirePet(scope: Scope, id: string) {
|
||||||
|
const [pet] = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(and(eq(pets.id, id), eq(pets.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!pet) throw new Error("Pet not found");
|
||||||
|
return pet;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireAppointment(scope: Scope, id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(petAppointments)
|
||||||
|
.where(and(eq(petAppointments.id, id), eq(petAppointments.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) throw new Error("Record not found");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
async function requireVaccination(scope: Scope, id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(petVaccinations)
|
||||||
|
.where(and(eq(petVaccinations.id, id), eq(petVaccinations.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) throw new Error("Record not found");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
async function requirePrescription(scope: Scope, id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(petPrescriptions)
|
||||||
|
.where(and(eq(petPrescriptions.id, id), eq(petPrescriptions.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) throw new Error("Record not found");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
function revalidatePet(id: string) {
|
||||||
|
revalidatePath("/pets");
|
||||||
|
revalidatePath(`/pets/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPetForScope(scope: Scope, input: z.input<typeof petInput>) {
|
||||||
|
const parsed = petInput.parse(input);
|
||||||
|
const [pet] = await db
|
||||||
|
.insert(pets)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
...parsed,
|
||||||
|
breed: parsed.breed ?? null,
|
||||||
|
birthDate: parsed.birthDate ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
primaryImageUrl: parsed.primaryImageUrl ?? parsed.images[0] ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!pet) throw new Error("Pet was not created");
|
||||||
|
await logActivityForScope(scope, {
|
||||||
|
entityType: "pets.pet",
|
||||||
|
entityId: pet.id,
|
||||||
|
action: "create",
|
||||||
|
payload: { name: pet.name },
|
||||||
|
});
|
||||||
|
return pet;
|
||||||
|
}
|
||||||
|
export async function createPet(input: z.input<typeof petInput>) {
|
||||||
|
const { household, user } = await getCurrentSession();
|
||||||
|
const pet = await createPetForScope({ householdId: household.id, userId: user.id }, input);
|
||||||
|
revalidatePet(pet.id);
|
||||||
|
return pet;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updatePetForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof petUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(petUpdateInput).parse(input);
|
||||||
|
await requirePet(scope, parsed.id);
|
||||||
|
const { id, ...changes } = parsed;
|
||||||
|
await db
|
||||||
|
.update(pets)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(pets.id, id));
|
||||||
|
await logActivityForScope(scope, { entityType: "pets.pet", entityId: id, action: "update" });
|
||||||
|
}
|
||||||
|
export async function updatePet(input: { id: string } & z.input<typeof petUpdateInput>) {
|
||||||
|
const { household, user } = await getCurrentSession();
|
||||||
|
await updatePetForScope({ householdId: household.id, userId: user.id }, input);
|
||||||
|
revalidatePet(input.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePetForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, id);
|
||||||
|
await logActivityForScope(scope, {
|
||||||
|
entityType: "pets.pet",
|
||||||
|
entityId: id,
|
||||||
|
action: "delete",
|
||||||
|
payload: { name: pet.name },
|
||||||
|
});
|
||||||
|
await db.delete(pets).where(eq(pets.id, id));
|
||||||
|
}
|
||||||
|
export async function deletePet(input: { id: string }) {
|
||||||
|
const { household, user } = await getCurrentSession();
|
||||||
|
await deletePetForScope({ householdId: household.id, userId: user.id }, input);
|
||||||
|
revalidatePath("/pets");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAppointmentForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: z.input<typeof appointmentInput>,
|
||||||
|
) {
|
||||||
|
const parsed = appointmentInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, parsed.petId);
|
||||||
|
const [row] = await db
|
||||||
|
.insert(petAppointments)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
petId: parsed.petId,
|
||||||
|
title: parsed.title,
|
||||||
|
appointmentAt: parsed.appointmentAt,
|
||||||
|
clinic: parsed.clinic ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!row) throw new Error("Appointment was not created");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetAppointmentReminders({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
appointmentId: row.id,
|
||||||
|
appointmentAt: row.appointmentAt,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
petName: pet.name,
|
||||||
|
title: row.title,
|
||||||
|
offsets: parsed.reminderOffsets,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
export async function updateAppointmentForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof appointmentUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(appointmentUpdateInput).parse(input);
|
||||||
|
const row = await requireAppointment(scope, parsed.id);
|
||||||
|
const pet = await requirePet(scope, row.petId);
|
||||||
|
const offsets = parsed.reminderOffsets ?? (await listReminderOffsets("pets.appointment", row.id));
|
||||||
|
const { id, reminderOffsets: _, ...changes } = parsed;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(petAppointments)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(petAppointments.id, id))
|
||||||
|
.returning();
|
||||||
|
if (!updated) throw new Error("Appointment not found");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetAppointmentReminders({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
appointmentId: id,
|
||||||
|
appointmentAt: updated.appointmentAt,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
petName: pet.name,
|
||||||
|
title: updated.title,
|
||||||
|
offsets,
|
||||||
|
});
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export async function deleteAppointmentForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
await requireAppointment(scope, id);
|
||||||
|
await cancelReminder("pets.appointment", id);
|
||||||
|
await db.delete(petAppointments).where(eq(petAppointments.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createVaccinationForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: z.input<typeof vaccinationInput>,
|
||||||
|
) {
|
||||||
|
const parsed = vaccinationInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, parsed.petId);
|
||||||
|
const [row] = await db
|
||||||
|
.insert(petVaccinations)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
...parsed,
|
||||||
|
dueOn: parsed.dueOn ?? null,
|
||||||
|
provider: parsed.provider ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!row) throw new Error("Vaccination was not created");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.vaccination",
|
||||||
|
entityId: row.id,
|
||||||
|
dueOn: row.dueOn,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Vaccination due: ${pet.name}`,
|
||||||
|
body: row.name,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
export async function updateVaccinationForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof vaccinationUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(vaccinationUpdateInput).parse(input);
|
||||||
|
const row = await requireVaccination(scope, parsed.id);
|
||||||
|
const pet = await requirePet(scope, row.petId);
|
||||||
|
const { id, ...changes } = parsed;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(petVaccinations)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(petVaccinations.id, id))
|
||||||
|
.returning();
|
||||||
|
if (!updated) throw new Error("Vaccination not found");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.vaccination",
|
||||||
|
entityId: id,
|
||||||
|
dueOn: updated.dueOn,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Vaccination due: ${pet.name}`,
|
||||||
|
body: updated.name,
|
||||||
|
});
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export async function deleteVaccinationForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
await requireVaccination(scope, id);
|
||||||
|
await cancelReminder("pets.vaccination", id);
|
||||||
|
await db.delete(petVaccinations).where(eq(petVaccinations.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPrescriptionForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: z.input<typeof prescriptionInput>,
|
||||||
|
) {
|
||||||
|
const parsed = prescriptionInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, parsed.petId);
|
||||||
|
const [row] = await db
|
||||||
|
.insert(petPrescriptions)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
...parsed,
|
||||||
|
instructions: parsed.instructions ?? null,
|
||||||
|
prescribedOn: parsed.prescribedOn ?? null,
|
||||||
|
expiresOn: parsed.expiresOn ?? null,
|
||||||
|
refillsRemaining: parsed.refillsRemaining ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!row) throw new Error("Prescription was not created");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.prescription",
|
||||||
|
entityId: row.id,
|
||||||
|
dueOn: row.active ? row.expiresOn : null,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Prescription due: ${pet.name}`,
|
||||||
|
body: row.medication,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
export async function updatePrescriptionForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof prescriptionUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(prescriptionUpdateInput).parse(input);
|
||||||
|
const row = await requirePrescription(scope, parsed.id);
|
||||||
|
const pet = await requirePet(scope, row.petId);
|
||||||
|
const { id, ...changes } = parsed;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(petPrescriptions)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(petPrescriptions.id, id))
|
||||||
|
.returning();
|
||||||
|
if (!updated) throw new Error("Prescription not found");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.prescription",
|
||||||
|
entityId: id,
|
||||||
|
dueOn: updated.active ? updated.expiresOn : null,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Prescription due: ${pet.name}`,
|
||||||
|
body: updated.medication,
|
||||||
|
});
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export async function deletePrescriptionForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
await requirePrescription(scope, id);
|
||||||
|
await cancelReminder("pets.prescription", id);
|
||||||
|
await db.delete(petPrescriptions).where(eq(petPrescriptions.id, id));
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import { and, asc, desc, eq, or, sql } from "drizzle-orm";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getCurrentSession } from "@/lib/session";
|
||||||
|
import { petAppointments, petPrescriptions, pets, petVaccinations } from "../schema";
|
||||||
|
|
||||||
|
export type PetListItemDto = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
species: string;
|
||||||
|
breed: string | null;
|
||||||
|
primaryImageUrl: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetAppointmentDto = {
|
||||||
|
id: string;
|
||||||
|
petId: string;
|
||||||
|
title: string;
|
||||||
|
appointmentAt: string;
|
||||||
|
clinic: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
calendarEventId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetVaccinationDto = {
|
||||||
|
id: string;
|
||||||
|
petId: string;
|
||||||
|
name: string;
|
||||||
|
administeredOn: string;
|
||||||
|
dueOn: string | null;
|
||||||
|
provider: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetPrescriptionDto = {
|
||||||
|
id: string;
|
||||||
|
petId: string;
|
||||||
|
medication: string;
|
||||||
|
dosage: string;
|
||||||
|
instructions: string | null;
|
||||||
|
prescribedOn: string | null;
|
||||||
|
expiresOn: string | null;
|
||||||
|
refillsRemaining: number | null;
|
||||||
|
active: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetDetailDto = PetListItemDto & {
|
||||||
|
householdId: string;
|
||||||
|
birthDate: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
images: string[];
|
||||||
|
appointments: PetAppointmentDto[];
|
||||||
|
vaccinations: PetVaccinationDto[];
|
||||||
|
prescriptions: PetPrescriptionDto[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const toAppointment = (row: typeof petAppointments.$inferSelect): PetAppointmentDto => ({
|
||||||
|
id: row.id,
|
||||||
|
petId: row.petId,
|
||||||
|
title: row.title,
|
||||||
|
appointmentAt: row.appointmentAt.toISOString(),
|
||||||
|
clinic: row.clinic,
|
||||||
|
notes: row.notes,
|
||||||
|
calendarEventId: row.calendarEventId,
|
||||||
|
});
|
||||||
|
const toVaccination = (row: typeof petVaccinations.$inferSelect): PetVaccinationDto => ({
|
||||||
|
id: row.id,
|
||||||
|
petId: row.petId,
|
||||||
|
name: row.name,
|
||||||
|
administeredOn: row.administeredOn,
|
||||||
|
dueOn: row.dueOn,
|
||||||
|
provider: row.provider,
|
||||||
|
notes: row.notes,
|
||||||
|
});
|
||||||
|
const toPrescription = (row: typeof petPrescriptions.$inferSelect): PetPrescriptionDto => ({
|
||||||
|
id: row.id,
|
||||||
|
petId: row.petId,
|
||||||
|
medication: row.medication,
|
||||||
|
dosage: row.dosage,
|
||||||
|
instructions: row.instructions,
|
||||||
|
prescribedOn: row.prescribedOn,
|
||||||
|
expiresOn: row.expiresOn,
|
||||||
|
refillsRemaining: row.refillsRemaining,
|
||||||
|
active: row.active,
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function listPetsForScope(householdId: string): Promise<PetListItemDto[]> {
|
||||||
|
const rows = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.householdId, householdId))
|
||||||
|
.orderBy(asc(pets.name));
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
species: row.species,
|
||||||
|
breed: row.breed,
|
||||||
|
primaryImageUrl: row.primaryImageUrl,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listPets() {
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
return listPetsForScope(household.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPetForScope(
|
||||||
|
householdId: string,
|
||||||
|
id: string,
|
||||||
|
): Promise<PetDetailDto | null> {
|
||||||
|
const [pet] = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(and(eq(pets.id, id), eq(pets.householdId, householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!pet) return null;
|
||||||
|
const [appointments, vaccinations, prescriptions] = await Promise.all([
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(petAppointments)
|
||||||
|
.where(and(eq(petAppointments.petId, id), eq(petAppointments.householdId, householdId)))
|
||||||
|
.orderBy(desc(petAppointments.appointmentAt)),
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(petVaccinations)
|
||||||
|
.where(and(eq(petVaccinations.petId, id), eq(petVaccinations.householdId, householdId)))
|
||||||
|
.orderBy(desc(petVaccinations.administeredOn)),
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(petPrescriptions)
|
||||||
|
.where(and(eq(petPrescriptions.petId, id), eq(petPrescriptions.householdId, householdId)))
|
||||||
|
.orderBy(desc(petPrescriptions.createdAt)),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
id: pet.id,
|
||||||
|
householdId: pet.householdId,
|
||||||
|
name: pet.name,
|
||||||
|
species: pet.species,
|
||||||
|
breed: pet.breed,
|
||||||
|
birthDate: pet.birthDate,
|
||||||
|
notes: pet.notes,
|
||||||
|
primaryImageUrl: pet.primaryImageUrl,
|
||||||
|
images: pet.images,
|
||||||
|
appointments: appointments.map(toAppointment),
|
||||||
|
vaccinations: vaccinations.map(toVaccination),
|
||||||
|
prescriptions: prescriptions.map(toPrescription),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPet(id: string) {
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
return getPetForScope(household.id, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchPets(query: string, householdId: string) {
|
||||||
|
const term = `%${query}%`;
|
||||||
|
const rows = await db
|
||||||
|
.select({ id: pets.id, name: pets.name, species: pets.species, breed: pets.breed })
|
||||||
|
.from(pets)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(pets.householdId, householdId),
|
||||||
|
or(
|
||||||
|
sql`${pets.name} ilike ${term}`,
|
||||||
|
sql`${pets.species} ilike ${term}`,
|
||||||
|
sql`coalesce(${pets.breed}, '') ilike ${term}`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(10);
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
title: row.name,
|
||||||
|
excerpt: [row.species, row.breed].filter(Boolean).join(" · "),
|
||||||
|
url: `/pets/${row.id}`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPetsOverviewStats(householdId: string) {
|
||||||
|
const [petCount] = await db
|
||||||
|
.select({ count: sql<number>`count(*)::int` })
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.householdId, householdId));
|
||||||
|
const [vaccinations, prescriptions] = await Promise.all([
|
||||||
|
db
|
||||||
|
.select({ count: sql<number>`count(*)::int` })
|
||||||
|
.from(petVaccinations)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(petVaccinations.householdId, householdId),
|
||||||
|
sql`${petVaccinations.dueOn} <= current_date + interval '30 days'`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
db
|
||||||
|
.select({ count: sql<number>`count(*)::int` })
|
||||||
|
.from(petPrescriptions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(petPrescriptions.householdId, householdId),
|
||||||
|
eq(petPrescriptions.active, true),
|
||||||
|
sql`${petPrescriptions.expiresOn} <= current_date + interval '30 days'`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
petCount: Number(petCount?.count ?? 0),
|
||||||
|
dueSoonCount: Number(vaccinations[0]?.count ?? 0) + Number(prescriptions[0]?.count ?? 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { toAppointment, toPrescription, toVaccination };
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { fireAtForEventStart, normalizeReminderOffsets } from "@/lib/reminder-offsets";
|
||||||
|
import { householdDateAt } from "@/lib/household-timezone";
|
||||||
|
import {
|
||||||
|
cancelReminder,
|
||||||
|
scheduleReminder,
|
||||||
|
syncRemindersForEntity,
|
||||||
|
} from "@/modules/_core/reminders";
|
||||||
|
|
||||||
|
export async function syncPetAppointmentReminders(input: {
|
||||||
|
householdId: string;
|
||||||
|
appointmentId: string;
|
||||||
|
appointmentAt: Date;
|
||||||
|
createdBy: string;
|
||||||
|
petName: string;
|
||||||
|
title: string;
|
||||||
|
offsets: number[];
|
||||||
|
}) {
|
||||||
|
await syncRemindersForEntity({
|
||||||
|
householdId: input.householdId,
|
||||||
|
entityType: "pets.appointment",
|
||||||
|
entityId: input.appointmentId,
|
||||||
|
createdBy: input.createdBy,
|
||||||
|
reminders: normalizeReminderOffsets(input.offsets).map((offsetMinutes) => ({
|
||||||
|
fireAt: fireAtForEventStart(input.appointmentAt, offsetMinutes),
|
||||||
|
offsetMinutes,
|
||||||
|
title: `Vet visit: ${input.petName}`,
|
||||||
|
body: input.title,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncPetDueDateReminder(input: {
|
||||||
|
householdId: string;
|
||||||
|
entityType: "pets.vaccination" | "pets.prescription";
|
||||||
|
entityId: string;
|
||||||
|
dueOn: string | null;
|
||||||
|
createdBy: string;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
}) {
|
||||||
|
if (!input.dueOn) {
|
||||||
|
await cancelReminder(input.entityType, input.entityId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await scheduleReminder({
|
||||||
|
householdId: input.householdId,
|
||||||
|
entityType: input.entityType,
|
||||||
|
entityId: input.entityId,
|
||||||
|
fireAt: householdDateAt(input.dueOn, 9),
|
||||||
|
createdBy: input.createdBy,
|
||||||
|
title: input.title,
|
||||||
|
body: input.body,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||||
|
const optionalText = (max: number) => z.string().trim().max(max).nullable().optional();
|
||||||
|
|
||||||
|
export const petInput = z.object({
|
||||||
|
name: z.string().trim().min(1).max(120),
|
||||||
|
species: z.string().trim().min(1).max(80),
|
||||||
|
breed: optionalText(120),
|
||||||
|
birthDate: isoDate.nullable().optional(),
|
||||||
|
notes: optionalText(4000),
|
||||||
|
images: z.array(z.string().min(1)).max(10).default([]),
|
||||||
|
primaryImageUrl: z.string().min(1).nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const petUpdateInput = petInput.partial();
|
||||||
|
|
||||||
|
export const appointmentInput = z.object({
|
||||||
|
petId: z.string().uuid(),
|
||||||
|
title: z.string().trim().min(1).max(160),
|
||||||
|
appointmentAt: z.coerce.date(),
|
||||||
|
clinic: optionalText(160),
|
||||||
|
notes: optionalText(4000),
|
||||||
|
reminderOffsets: z.array(z.number().int().min(0).max(43_200)).default([30]),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const appointmentUpdateInput = appointmentInput.omit({ petId: true }).partial();
|
||||||
|
|
||||||
|
export const vaccinationInput = z.object({
|
||||||
|
petId: z.string().uuid(),
|
||||||
|
name: z.string().trim().min(1).max(160),
|
||||||
|
administeredOn: isoDate,
|
||||||
|
dueOn: isoDate.nullable().optional(),
|
||||||
|
provider: optionalText(160),
|
||||||
|
notes: optionalText(4000),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const vaccinationUpdateInput = vaccinationInput.omit({ petId: true }).partial();
|
||||||
|
|
||||||
|
export const prescriptionInput = z.object({
|
||||||
|
petId: z.string().uuid(),
|
||||||
|
medication: z.string().trim().min(1).max(160),
|
||||||
|
dosage: z.string().trim().min(1).max(160),
|
||||||
|
instructions: optionalText(2000),
|
||||||
|
prescribedOn: isoDate.nullable().optional(),
|
||||||
|
expiresOn: isoDate.nullable().optional(),
|
||||||
|
refillsRemaining: z.number().int().min(0).max(99).nullable().optional(),
|
||||||
|
active: z.boolean().default(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const prescriptionUpdateInput = prescriptionInput.omit({ petId: true }).partial();
|
||||||
|
|
||||||
|
export const scheduleAppointmentInput = z.object({
|
||||||
|
appointmentId: z.string().uuid(),
|
||||||
|
calendarId: z.string().uuid(),
|
||||||
|
});
|
||||||
@@ -83,6 +83,36 @@ describe("runAgentChat", () => {
|
|||||||
assert.equal(result.message.role, "assistant");
|
assert.equal(result.message.role, "assistant");
|
||||||
assert.ok(result.message.content.length > 0);
|
assert.ok(result.message.content.length > 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("appends runtime clock context to the system prompt", async () => {
|
||||||
|
const original = process.env.HOUSEHOLD_TIMEZONE;
|
||||||
|
process.env.HOUSEHOLD_TIMEZONE = "America/Chicago";
|
||||||
|
|
||||||
|
let systemContent = "";
|
||||||
|
const result = await runAgentChat({
|
||||||
|
messages: [{ role: "user", content: "hello" }],
|
||||||
|
request: new Request("http://localhost:3000/api/agent/chat"),
|
||||||
|
systemPrompt: "You are a pirate.",
|
||||||
|
llm: {
|
||||||
|
async chatCompletion(request) {
|
||||||
|
const system = request.messages.find((message) => message.role === "system");
|
||||||
|
systemContent = typeof system?.content === "string" ? system.content : "";
|
||||||
|
return {
|
||||||
|
message: { role: "assistant", content: "Ahoy" },
|
||||||
|
finishReason: "stop",
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(result.message.content, "Ahoy");
|
||||||
|
assert.match(systemContent, /^You are a pirate\./);
|
||||||
|
assert.match(systemContent, /Current time:/);
|
||||||
|
assert.match(systemContent, /America\/Chicago/);
|
||||||
|
|
||||||
|
if (original === undefined) delete process.env.HOUSEHOLD_TIMEZONE;
|
||||||
|
else process.env.HOUSEHOLD_TIMEZONE = original;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("passes a model override to the OpenAI-compatible client", async () => {
|
it("passes a model override to the OpenAI-compatible client", async () => {
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { describe, it } from "node:test";
|
||||||
|
import {
|
||||||
|
fingerprintToolCalls,
|
||||||
|
isSuccessfulWrite,
|
||||||
|
summarizeToolTrace,
|
||||||
|
truncateToolResult,
|
||||||
|
} from "../../src/modules/agent/server/loop-guards";
|
||||||
|
import { runAgentChat } from "../../src/modules/agent/server/run";
|
||||||
|
import type {
|
||||||
|
ChatCompletionRequest,
|
||||||
|
ChatCompletionResult,
|
||||||
|
LlmClient,
|
||||||
|
} from "../../src/lib/llm/types";
|
||||||
|
|
||||||
|
describe("loop-guards", () => {
|
||||||
|
it("fingerprints tool calls stably regardless of key order", () => {
|
||||||
|
const a = fingerprintToolCalls([
|
||||||
|
{ name: "create_event", arguments: '{"title":"Dentist","calendarName":"Family"}' },
|
||||||
|
]);
|
||||||
|
const b = fingerprintToolCalls([
|
||||||
|
{ name: "create_event", arguments: '{"calendarName":"Family","title":"Dentist"}' },
|
||||||
|
]);
|
||||||
|
assert.equal(a, b);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats create_event 201 as a successful write", () => {
|
||||||
|
assert.equal(isSuccessfulWrite("create_event", 201), true);
|
||||||
|
assert.equal(isSuccessfulWrite("list_calendars", 200), false);
|
||||||
|
assert.equal(
|
||||||
|
isSuccessfulWrite("call_api", 201, '{"method":"POST","path":"/api/v1/events"}'),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
isSuccessfulWrite("call_api", 200, '{"method":"GET","path":"/api/v1/events"}'),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("truncates oversized tool results", () => {
|
||||||
|
const result = truncateToolResult("x".repeat(7000), 100);
|
||||||
|
assert.ok(result.length < 200);
|
||||||
|
assert.match(result, /truncated/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("summarizes tool traces", () => {
|
||||||
|
assert.equal(
|
||||||
|
summarizeToolTrace([
|
||||||
|
{ name: "list_calendars", status: 200 },
|
||||||
|
{ name: "create_event", status: 201 },
|
||||||
|
]),
|
||||||
|
"list_calendars→200, create_event→201",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("runAgentChat loop guards", () => {
|
||||||
|
it("stops after a successful write instead of looping", async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const llm: LlmClient = {
|
||||||
|
async chatCompletion(request: ChatCompletionRequest): Promise<ChatCompletionResult> {
|
||||||
|
calls += 1;
|
||||||
|
if (calls === 1) {
|
||||||
|
return {
|
||||||
|
message: {
|
||||||
|
role: "assistant",
|
||||||
|
content: null,
|
||||||
|
tool_calls: [
|
||||||
|
{
|
||||||
|
id: "1",
|
||||||
|
type: "function",
|
||||||
|
function: {
|
||||||
|
name: "create_event",
|
||||||
|
arguments: JSON.stringify({
|
||||||
|
title: "Dentist",
|
||||||
|
startAt: "2026-07-10T15:00:00.000Z",
|
||||||
|
endAt: "2026-07-10T16:00:00.000Z",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
finishReason: "tool_calls",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(request.tools, undefined);
|
||||||
|
return {
|
||||||
|
message: { role: "assistant", content: "Added Dentist to your calendar." },
|
||||||
|
finishReason: "stop",
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await runAgentChat({
|
||||||
|
messages: [{ role: "user", content: "add dentist tomorrow at 10" }],
|
||||||
|
request: new Request("http://localhost:3000/api/agent/chat"),
|
||||||
|
llm,
|
||||||
|
executeTool: async () =>
|
||||||
|
JSON.stringify({ status: 201, body: { id: "evt-1", title: "Dentist" } }),
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.equal(result.toolCalls.length, 1);
|
||||||
|
assert.equal(result.toolCalls[0]?.name, "create_event");
|
||||||
|
assert.match(result.message.content, /Dentist/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("breaks duplicate identical tool rounds", async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const llm: LlmClient = {
|
||||||
|
async chatCompletion(): Promise<ChatCompletionResult> {
|
||||||
|
calls += 1;
|
||||||
|
if (calls <= 2) {
|
||||||
|
return {
|
||||||
|
message: {
|
||||||
|
role: "assistant",
|
||||||
|
content: null,
|
||||||
|
tool_calls: [
|
||||||
|
{
|
||||||
|
id: String(calls),
|
||||||
|
type: "function",
|
||||||
|
function: {
|
||||||
|
name: "list_calendars",
|
||||||
|
arguments: "{}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
finishReason: "tool_calls",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
message: { role: "assistant", content: "You have one Family calendar." },
|
||||||
|
finishReason: "stop",
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await runAgentChat({
|
||||||
|
messages: [{ role: "user", content: "what calendars do I have?" }],
|
||||||
|
request: new Request("http://localhost:3000/api/agent/chat"),
|
||||||
|
llm,
|
||||||
|
executeTool: async () =>
|
||||||
|
JSON.stringify({ status: 200, body: [{ id: "cal-1", name: "Family" }] }),
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(calls, 3);
|
||||||
|
assert.equal(result.toolCalls.length, 1);
|
||||||
|
assert.match(result.message.content, /Family/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { describe, it } from "node:test";
|
||||||
|
import { appendAgentRuntimeContext, resolveHouseholdTimezone } from "../../src/modules/agent/tools";
|
||||||
|
import {
|
||||||
|
createApiToolExecutor,
|
||||||
|
resolveInternalApiBase,
|
||||||
|
} from "../../src/modules/agent/tool-executor";
|
||||||
|
|
||||||
|
describe("appendAgentRuntimeContext", () => {
|
||||||
|
it("appends current time and timezone to the prompt", () => {
|
||||||
|
const original = process.env.HOUSEHOLD_TIMEZONE;
|
||||||
|
process.env.HOUSEHOLD_TIMEZONE = "America/Chicago";
|
||||||
|
|
||||||
|
const now = new Date("2026-07-09T14:30:00.000Z");
|
||||||
|
const result = appendAgentRuntimeContext("Be helpful.", now);
|
||||||
|
|
||||||
|
assert.match(result, /^Be helpful\./);
|
||||||
|
assert.match(result, /Current time:/);
|
||||||
|
assert.match(result, /America\/Chicago/);
|
||||||
|
assert.match(result, /2026-07-09T14:30:00\.000Z/);
|
||||||
|
assert.match(result, /Resolve relative dates from this clock/);
|
||||||
|
|
||||||
|
if (original === undefined) delete process.env.HOUSEHOLD_TIMEZONE;
|
||||||
|
else process.env.HOUSEHOLD_TIMEZONE = original;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveHouseholdTimezone", () => {
|
||||||
|
it("prefers HOUSEHOLD_TIMEZONE over TZ", () => {
|
||||||
|
const originalHousehold = process.env.HOUSEHOLD_TIMEZONE;
|
||||||
|
const originalTz = process.env.TZ;
|
||||||
|
process.env.HOUSEHOLD_TIMEZONE = "America/New_York";
|
||||||
|
process.env.TZ = "UTC";
|
||||||
|
|
||||||
|
assert.equal(resolveHouseholdTimezone(), "America/New_York");
|
||||||
|
|
||||||
|
if (originalHousehold === undefined) delete process.env.HOUSEHOLD_TIMEZONE;
|
||||||
|
else process.env.HOUSEHOLD_TIMEZONE = originalHousehold;
|
||||||
|
if (originalTz === undefined) delete process.env.TZ;
|
||||||
|
else process.env.TZ = originalTz;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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;
|
||||||
|
const posts: Array<{ path: string; body: unknown }> = [];
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const url = String(input);
|
||||||
|
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.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 });
|
||||||
|
}
|
||||||
|
return new Response("not found", { status: 404 });
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
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",
|
||||||
|
JSON.stringify({
|
||||||
|
title: "Dentist",
|
||||||
|
startAt: "2026-07-10T15:00:00.000Z",
|
||||||
|
endAt: "2026-07-10T16:00:00.000Z",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
) as { status: number; body: { calendarId?: string } };
|
||||||
|
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches calendarName case-insensitively", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
|
||||||
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const url = String(input);
|
||||||
|
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.includes("/api/v1/events") && init?.method === "POST") {
|
||||||
|
const body = JSON.parse(String(init.body));
|
||||||
|
return Response.json({ id: "evt-1", ...body }, { status: 201 });
|
||||||
|
}
|
||||||
|
return new Response("not found", { status: 404 });
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const execute = createApiToolExecutor(new Request("http://localhost:3000/api/agent/chat"));
|
||||||
|
const result = JSON.parse(
|
||||||
|
await execute(
|
||||||
|
"create_event",
|
||||||
|
JSON.stringify({
|
||||||
|
calendarName: "work",
|
||||||
|
title: "Standup",
|
||||||
|
startAt: "2026-07-10T15:00:00.000Z",
|
||||||
|
endAt: "2026-07-10T15:30:00.000Z",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
) as { status: number; body: { calendarId?: string } };
|
||||||
|
|
||||||
|
assert.equal(result.status, 201);
|
||||||
|
assert.equal(result.body.calendarId, "cal-2");
|
||||||
|
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { householdDateAt } from "../../src/lib/household-timezone";
|
||||||
|
|
||||||
|
test("householdDateAt preserves 9 AM across Chicago daylight saving time", () => {
|
||||||
|
const formatter = new Intl.DateTimeFormat("en-CA", {
|
||||||
|
timeZone: "America/Chicago",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
hourCycle: "h23",
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const date of ["2026-01-15", "2026-07-15"]) {
|
||||||
|
assert.equal(formatter.format(householdDateAt(date, 9, "America/Chicago")), "09:00");
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import {
|
||||||
|
appointmentInput,
|
||||||
|
petInput,
|
||||||
|
prescriptionInput,
|
||||||
|
scheduleAppointmentInput,
|
||||||
|
vaccinationInput,
|
||||||
|
} from "../../src/modules/pets/server/schemas";
|
||||||
|
|
||||||
|
const PET_ID = "f5a50e32-a217-4d65-ae10-98a1f441d171";
|
||||||
|
const CALENDAR_ID = "bd8e10c2-58f4-4db8-9326-0b50fdda47bb";
|
||||||
|
|
||||||
|
test("pet and medical record schemas accept bounded valid input", () => {
|
||||||
|
assert.equal(petInput.parse({ name: "Mochi", species: "cat", images: [] }).name, "Mochi");
|
||||||
|
assert.equal(
|
||||||
|
appointmentInput.parse({
|
||||||
|
petId: PET_ID,
|
||||||
|
title: "Annual exam",
|
||||||
|
appointmentAt: "2026-08-01T15:00:00.000Z",
|
||||||
|
}).title,
|
||||||
|
"Annual exam",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
vaccinationInput.parse({ petId: PET_ID, name: "Rabies", administeredOn: "2026-07-01" }).name,
|
||||||
|
"Rabies",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
prescriptionInput.parse({ petId: PET_ID, medication: "Apoquel", dosage: "5 mg daily" }).active,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
scheduleAppointmentInput.parse({ appointmentId: PET_ID, calendarId: CALENDAR_ID }),
|
||||||
|
{
|
||||||
|
appointmentId: PET_ID,
|
||||||
|
calendarId: CALENDAR_ID,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pet and medical record schemas reject invalid identifiers, dates, and galleries", () => {
|
||||||
|
assert.throws(() => petInput.parse({ name: "", species: "cat" }));
|
||||||
|
assert.throws(() =>
|
||||||
|
petInput.parse({
|
||||||
|
name: "Mochi",
|
||||||
|
species: "cat",
|
||||||
|
images: Array(11).fill("/api/uploads/pets/a.jpg"),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.throws(() =>
|
||||||
|
appointmentInput.parse({ petId: "not-a-uuid", title: "Exam", appointmentAt: "not-a-date" }),
|
||||||
|
);
|
||||||
|
assert.throws(() =>
|
||||||
|
vaccinationInput.parse({ petId: PET_ID, name: "Rabies", administeredOn: "07/01/2026" }),
|
||||||
|
);
|
||||||
|
assert.throws(() =>
|
||||||
|
scheduleAppointmentInput.parse({ appointmentId: "bad", calendarId: "also-bad" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user