Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,6 @@ jobs:

- name: Test
run: pnpm turbo test

- name: Check unused files and dependencies
run: pnpm knip
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"cSpell.words": ["Auguste"]
"cSpell.words": ["Auguste", "openrouter"]
}
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ Foreign key relationships: `Member.familyId β†’ Family`, `MemberAvailability.mem
- **Const Enums**: Used for enums with proper TypeScript types.
- **No `any` Types**: TypeScript strict mode is enabled - avoid `any`.
- **ESM Only**: Package type is `"module"` - uses ES2022 modules.
- **Implementation Plans**: Before implementing a feature, write down the plan in markdown in the `specs/` folder. Use subfolders to group related work (e.g., `specs/meal-planner/`).
- **Business Logic in Domain Layer**: Keep business logic in domain services (`packages/core/src/domain/services/`), not in AI tools. Tools should be thin wrappers that call domain services.

## AI Agents

Expand Down
101 changes: 98 additions & 3 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import {
getMembersByFamilyId,
getAvailabilityByFamilyId,
getPlannerSettingsByFamilyId,
getMealPlanningByFamilyId,
getAllMealPlanningsByFamilyId,
getMealEventsByFamilyId,
} from '@auguste/core';
import dotenv from 'dotenv';
import path from 'path';
Expand Down Expand Up @@ -46,9 +49,16 @@ app.get('/health', (_req, res) => {
app.post('/api/chat', async (req, res) => {
const { message, agentId = 'onboardingAgent', threadId, resourceId, familyId } = req.body;

console.log(`Chat request: agentId=${agentId}, familyId=${familyId}`);

try {
const agent = mastra.getAgent(agentId);

if (!agent) {
console.error(`Agent not found: ${agentId}`);
return res.status(404).json({ error: `Agent not found: ${agentId}` });
}

// Set headers for SSE streaming
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
Expand All @@ -59,17 +69,63 @@ app.post('/api/chat', async (req, res) => {
requestContext.set('familyId', familyId);
}

console.log(`Starting stream for agent: ${agentId}`);

const result = await agent.stream(message, {
threadId,
resourceId,
requestContext,
// Ensure the agent continues to generate a response after tool calls
// Without maxSteps, some models may stop after executing a tool without providing text output
maxSteps: 10,
onStepFinish: ({
text,
toolCalls,
finishReason,
}: {
text?: string;
toolCalls?: unknown[];
finishReason?: string;
}) => {
console.log(
`Step finished: finishReason=${finishReason}, textLength=${text?.length ?? 0}, toolCalls=${toolCalls?.length ?? 0}`,
);
},
});

// Stream text chunks as SSE events
for await (const chunk of result.textStream) {
res.write(`data: ${JSON.stringify({ type: 'text', content: chunk })}\n\n`);
let chunkCount = 0;
// Stream using fullStream to catch all events including errors
for await (const chunk of result.fullStream) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const anyChunk = chunk as any;
if (chunk.type === 'text-delta') {
chunkCount++;
// Mastra fullStream wraps text content in payload.text
const textContent = anyChunk.payload?.text ?? anyChunk.textDelta ?? '';
res.write(`data: ${JSON.stringify({ type: 'text', content: textContent })}\n\n`);
} else if (chunk.type === 'error') {
console.error('Stream error:', chunk.error);
res.write(`data: ${JSON.stringify({ type: 'error', content: String(chunk.error) })}\n\n`);
} else if (chunk.type === 'tool-call') {
const toolName = anyChunk.payload?.toolName || anyChunk.toolName || 'unknown';
const toolArgs = anyChunk.payload?.args || anyChunk.args || {};
console.log(`Tool call: ${toolName}`);
// Send tool-call event to frontend
res.write(`data: ${JSON.stringify({ type: 'tool-call', toolName, args: toolArgs })}\n\n`);
} else if (chunk.type === 'tool-result') {
const toolName = anyChunk.payload?.toolName || anyChunk.toolName || 'unknown';
const toolResult = anyChunk.payload?.result || anyChunk.result || {};
const resultStr = JSON.stringify(toolResult);
console.log(`Tool result: ${toolName} -> ${resultStr.slice(0, 200)}`);
// Send tool-result event to frontend
res.write(
`data: ${JSON.stringify({ type: 'tool-result', toolName, result: toolResult })}\n\n`,
);
}
}

console.log(`Stream completed for agent: ${agentId}, chunks: ${chunkCount}`);

// Send done event
res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
res.end();
Expand Down Expand Up @@ -153,6 +209,45 @@ app.get('/api/family/:id/settings', async (req, res) => {
}
});

// Meal planning endpoints
app.get('/api/family/:id/planning', async (req, res) => {
try {
const { id } = req.params;
const planning = await getMealPlanningByFamilyId(id);

if (!planning) {
return res.status(404).json({ error: 'No meal planning found' });
}

res.json(planning);
} catch (error) {
console.error('Error fetching meal planning:', error);
res.status(500).json({ error: 'Failed to fetch meal planning' });
}
});

app.get('/api/family/:id/plannings', async (req, res) => {
try {
const { id } = req.params;
const plannings = await getAllMealPlanningsByFamilyId(id);
res.json(plannings);
} catch (error) {
console.error('Error fetching all meal plannings:', error);
res.status(500).json({ error: 'Failed to fetch meal plannings' });
}
});

app.get('/api/family/:id/events', async (req, res) => {
try {
const { id } = req.params;
const events = await getMealEventsByFamilyId(id);
res.json(events);
} catch (error) {
console.error('Error fetching meal events:', error);
res.status(500).json({ error: 'Failed to fetch meal events' });
}
});

app.listen(port, () => {
console.log(`API running at http://localhost:${port}`);
});
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-slot": "^1.2.4",
"@tanstack/react-query": "^5.90.16",
"@tanstack/react-router": "^1.149.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
Expand Down
10 changes: 9 additions & 1 deletion apps/web/src/components/chat/chat-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { ChatInput } from './chat-input';
import { SuggestedActions } from './suggested-actions';
import type { Message } from '@/hooks/use-chat';

type ChatContext = 'family' | 'planner';

interface ChatPanelProps {
messages: Message[];
isLoading: boolean;
Expand All @@ -11,6 +13,7 @@ interface ChatPanelProps {
onSend: () => void;
messagesEndRef: React.RefObject<HTMLDivElement | null>;
disabled?: boolean;
context?: ChatContext;
}

export function ChatPanel({
Expand All @@ -21,6 +24,7 @@ export function ChatPanel({
onSend,
messagesEndRef,
disabled = false,
context = 'family',
}: ChatPanelProps) {
const hasMessages = messages.length > 0;

Expand All @@ -37,7 +41,11 @@ export function ChatPanel({
{hasMessages ? (
<MessageList messages={messages} isLoading={isLoading} messagesEndRef={messagesEndRef} />
) : (
<SuggestedActions onSelect={handleSuggestedAction} disabled={disabled} />
<SuggestedActions
onSelect={handleSuggestedAction}
disabled={disabled}
context={context}
/>
)}
</div>

Expand Down
8 changes: 7 additions & 1 deletion apps/web/src/components/chat/message-item.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import { cn } from '@auguste/ui/lib/utils';
import ReactMarkdown from 'react-markdown';
import type { Message } from '@/hooks/use-chat';
import { ToolCallsSection } from './tool-calls-section';

interface MessageItemProps {
message: Message;
}

export function MessageItem({ message }: MessageItemProps) {
const isAssistant = message.role === 'assistant';
const hasToolCalls = isAssistant && message.toolCalls && message.toolCalls.length > 0;

return (
<div className={cn('flex items-start mb-6', !isAssistant && 'justify-end')}>
<div className={cn('flex flex-col mb-6', !isAssistant && 'items-end')}>
{/* Message bubble */}
<div
className={cn(
'relative px-5 py-2.5 text-sm transition-all duration-300',
Expand Down Expand Up @@ -48,6 +51,9 @@ export function MessageItem({ message }: MessageItemProps) {
)}
</div>
</div>

{/* Tool calls - subtle text below the message */}
{hasToolCalls && <ToolCallsSection toolCalls={message.toolCalls!} />}
</div>
);
}
88 changes: 67 additions & 21 deletions apps/web/src/components/chat/suggested-actions.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,84 @@
type ContextType = 'family' | 'planner';

interface SuggestedActionsProps {
onSelect: (message: string) => void;
disabled?: boolean;
context?: ContextType;
}

const suggestions = [
{
label: 'Add new member',
message: 'I would like to add a new family member',
icon: 'πŸ‘€',
},
{
label: 'Set availability',
message: 'I want to set meal availability for family members',
icon: 'πŸ“…',
interface Suggestion {
label: string;
message: string;
icon: string;
}

interface ContextConfig {
title: string;
subtitle: string;
suggestions: Suggestion[];
}

const contextConfigs: Record<ContextType, ContextConfig> = {
family: {
title: "Hello! I'm Auguste",
subtitle: 'Your AI meal planning assistant. How can I help you today?',
suggestions: [
{
label: 'Add new member',
message: 'I would like to add a new family member',
icon: 'πŸ‘€',
},
{
label: 'Set availability',
message: 'I want to set meal availability for family members',
icon: 'πŸ“…',
},
{
label: 'Food preferences',
message: 'I want to specify food preferences or allergies',
icon: 'πŸ₯—',
},
],
},
{
label: 'Food preferences',
message: 'I want to specify food preferences or allergies',
icon: 'πŸ₯—',
planner: {
title: "Let's Plan Your Meals",
subtitle: 'I can help you create delicious meal plans for your family.',
suggestions: [
{
label: 'Plan meals for the next week',
message: 'Plan meals for the next week',
icon: 'πŸ“†',
},
{
label: 'Suggest meals for a specific date',
message: 'Suggest meals for a specific date',
icon: '🍽️',
},
{
label: 'Adjust meal plan for a specific date',
message: 'Adjust meal plan for a specific date',
icon: '✏️',
},
],
},
];
};

export function SuggestedActions({
onSelect,
disabled = false,
context = 'family',
}: SuggestedActionsProps) {
const config = contextConfigs[context];

export function SuggestedActions({ onSelect, disabled = false }: SuggestedActionsProps) {
return (
<div className="flex flex-col items-center justify-center h-full px-4">
<div className="text-center mb-8">
<h2 className="text-2xl font-serif text-escoffier-green mb-2">Hello! I'm Auguste</h2>
<p className="text-escoffier-green/70">
Your AI meal planning assistant. How can I help you today?
</p>
<h2 className="text-2xl font-serif text-escoffier-green mb-2">{config.title}</h2>
<p className="text-escoffier-green/70">{config.subtitle}</p>
</div>

<div className="flex flex-wrap justify-center gap-3 max-w-md">
{suggestions.map((suggestion) => (
{config.suggestions.map((suggestion) => (
<button
type="button"
key={suggestion.label}
Expand Down
Loading