mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
fix(assistant): green CI round, trip notes the assistant can keep, calmer change cards
- the assistant keeps facts for a trip (remember_for_trip) as a change card, applied into the user's trip notes; existing expenses can be changed - change card fields as a few icon chips with the rest folded under Details, the day band marks only what changes, the week grid as compact tiles - no map button on receipts of things that have no place on the map - tests follow the composer's accessible name, the receipt's status icon and the GL map's container; the hanging stream helper honours an early abort - Postgres probe: qualified columns in the upsert updates; entities restored to the generator's output; strict ratchet reads the SDK client as untyped
This commit is contained in:
@@ -21,7 +21,9 @@ export class AssistantMessages {
|
||||
export const AssistantMessagesSchema = defineEntity({
|
||||
class: AssistantMessages,
|
||||
repository: () => AssistantMessagesRepository,
|
||||
indexes: [{ name: 'idx_assistant_messages_thread', properties: ['thread_id', 'id'] }],
|
||||
indexes: [
|
||||
{ name: 'idx_assistant_messages_thread', properties: ['thread_id', 'id'] },
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
|
||||
|
||||
@@ -30,8 +30,7 @@ export const AssistantToolCallsSchema = defineEntity({
|
||||
id: p.text().primary(),
|
||||
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
|
||||
thread_id: p.integer().persist(false),
|
||||
message: () =>
|
||||
p.manyToOne(AssistantMessages).ref().deleteRule('cascade').hidden().index('idx_assistant_tool_calls_message'),
|
||||
message: () => p.manyToOne(AssistantMessages).ref().deleteRule('cascade').hidden().index('idx_assistant_tool_calls_message'),
|
||||
message_id: p.integer().persist(false).index('idx_assistant_tool_calls_message'),
|
||||
provider_call_id: p.text(),
|
||||
tool_name: p.text(),
|
||||
|
||||
@@ -117,7 +117,7 @@ export class AiConnectionsRepository extends TrekRepository<AiConnections> {
|
||||
: oc.column('user_id').where('user_id', 'is not', null);
|
||||
return target.doUpdateSet({
|
||||
...columns,
|
||||
secrets_version: (eb) => eb('secrets_version', '+', 1),
|
||||
secrets_version: (eb) => eb('ai_connections.secrets_version', '+', 1),
|
||||
status: 'ok',
|
||||
updated_at: () => this.now(),
|
||||
});
|
||||
|
||||
@@ -35,9 +35,9 @@ export class AssistantUsageRepository extends TrekRepository<AssistantUsage> {
|
||||
})
|
||||
.onConflict((oc) =>
|
||||
oc.columns(['user_id', 'day', 'paid_by']).doUpdateSet({
|
||||
turns: (eb) => eb('turns', '+', eb.ref('excluded.turns')),
|
||||
input_tokens: (eb) => eb('input_tokens', '+', eb.ref('excluded.input_tokens')),
|
||||
output_tokens: (eb) => eb('output_tokens', '+', eb.ref('excluded.output_tokens')),
|
||||
turns: (eb) => eb('assistant_usage.turns', '+', eb.ref('excluded.turns')),
|
||||
input_tokens: (eb) => eb('assistant_usage.input_tokens', '+', eb.ref('excluded.input_tokens')),
|
||||
output_tokens: (eb) => eb('assistant_usage.output_tokens', '+', eb.ref('excluded.output_tokens')),
|
||||
}),
|
||||
)
|
||||
.execute();
|
||||
|
||||
@@ -13,7 +13,7 @@ export {
|
||||
} from './helpers';
|
||||
export { McpRegistryService } from './mcp-registry.service';
|
||||
export { McpModule } from './mcp.module';
|
||||
export { McpRegistry, type McpRegistryOptions } from './registry';
|
||||
export { createLocalMcpServer, McpRegistry, type McpRegistryOptions } from './registry';
|
||||
export { createTestRegistry } from './testing';
|
||||
export {
|
||||
type McpAccess,
|
||||
|
||||
@@ -17,7 +17,7 @@ import type {
|
||||
ToolOptions,
|
||||
} from './types';
|
||||
import { ResourceTemplate as SdkResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -478,3 +478,8 @@ export class McpRegistry {
|
||||
registrar.registerPrompt(options.name, config, cb);
|
||||
}
|
||||
}
|
||||
|
||||
/** A server of its own for a client in the same process (the assistant's tool session), to attach a registry to. */
|
||||
export function createLocalMcpServer(name: string): McpServer {
|
||||
return new McpServer({ name, version: '1.0.0' });
|
||||
}
|
||||
|
||||
@@ -370,7 +370,7 @@ export function renderTripCard(card: TripCard): string {
|
||||
type UserPrefs = Readonly<Record<string, unknown>>;
|
||||
|
||||
/** What a traveller writes for the assistant to keep in mind on one trip; longer notes are cut. */
|
||||
const MAX_MEMORY_CHARS = 2_000;
|
||||
export const MAX_MEMORY_CHARS = 2_000;
|
||||
|
||||
/** The notes the user keeps for this trip (`assistant_memory`, by trip id), trimmed; null when there are none. */
|
||||
export function tripMemoryOf(prefs: UserPrefs, tripId: number): string | null {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { AiToolSpec } from '../ai-connections/ai-chat-client.interface';
|
||||
import type { SettingsService } from '../settings/settings.service';
|
||||
import { MAX_MEMORY_CHARS, tripMemoryOf } from './assistant-context';
|
||||
import { REMEMBER_TOOL } from './assistant-tools.constants';
|
||||
import type { ToolRun } from './assistant-tools.service';
|
||||
|
||||
/** The longest single note the model may keep. */
|
||||
const MAX_NOTE_CHARS = 500;
|
||||
|
||||
/** How the model is offered the trip notes: one short fact per call, confirmed by the user like any change. */
|
||||
export const REMEMBER_SPEC: AiToolSpec = {
|
||||
name: REMEMBER_TOOL,
|
||||
description:
|
||||
"Keep a fact or wish about this trip in the user's trip notes, which come along with every later conversation " +
|
||||
'about this trip (for example "we travel as two", "vegetarian", "no museums before 10"). Call it whenever the ' +
|
||||
'user asks you to remember something, instead of saying you cannot. The user confirms it like any change.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
note: {
|
||||
type: 'string',
|
||||
maxLength: MAX_NOTE_CHARS,
|
||||
description: "The fact as one short sentence, in the user's language.",
|
||||
},
|
||||
},
|
||||
required: ['note'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
};
|
||||
|
||||
/** The note a call carries, trimmed; null when there is none. */
|
||||
export function noteOf(args: Record<string, unknown>): string | null {
|
||||
const note = typeof args.note === 'string' ? args.note.trim().slice(0, MAX_NOTE_CHARS) : '';
|
||||
return note || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the note to this trip's notes, below what is there. A note already
|
||||
* kept is not added twice; notes that would run past the limit are refused,
|
||||
* so nothing the user wrote is cut off.
|
||||
*/
|
||||
export async function rememberForTrip(
|
||||
settings: SettingsService,
|
||||
userId: number,
|
||||
tripId: number,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<ToolRun> {
|
||||
const note = noteOf(args);
|
||||
if (!note) return { ok: false, value: 'There is nothing to remember.' };
|
||||
const prefs = await settings.getUserSettings(userId);
|
||||
const current = tripMemoryOf(prefs, tripId);
|
||||
if (current?.split('\n').some((line) => line.trim() === note)) return { ok: true, value: { notes: current } };
|
||||
const next = current ? `${current}\n${note}` : note;
|
||||
if (next.length > MAX_MEMORY_CHARS) {
|
||||
return { ok: false, value: 'The trip notes are full. Ask the user to tidy them up in the chat menu first.' };
|
||||
}
|
||||
const all = prefs.assistant_memory && typeof prefs.assistant_memory === 'object' ? prefs.assistant_memory : {};
|
||||
await settings.upsertSetting(userId, 'assistant_memory', { ...all, [String(tripId)]: next });
|
||||
return { ok: true, value: { notes: next } };
|
||||
}
|
||||
@@ -87,6 +87,7 @@ export const ASSISTANT_WRITE_TOOLS: Readonly<Record<string, AssistantWriteTool>>
|
||||
update_packing_item: { verbKey: 'updatePackingItem', entity: 'packing' },
|
||||
create_todo: { verbKey: 'addTodo', entity: 'todo' },
|
||||
create_budget_item: { verbKey: 'addBudgetItem', entity: 'budget' },
|
||||
update_budget_item: { verbKey: 'updateBudgetItem', entity: 'budget' },
|
||||
create_reservation: { verbKey: 'addReservation', entity: 'reservation' },
|
||||
};
|
||||
|
||||
@@ -105,14 +106,22 @@ export const IMPORT_BOOKING_TOOL = 'import_booking';
|
||||
*/
|
||||
export const ADD_FOUND_PLACE_TOOL = 'add_found_place';
|
||||
|
||||
/**
|
||||
* A fact or wish the user wants kept for this trip ("we are two"). It is no
|
||||
* MCP tool: the server offers it to the model itself, holds it as a change
|
||||
* card like any write and, once applied, adds it to the user's trip notes,
|
||||
* which come along with every later turn about the trip.
|
||||
*/
|
||||
export const REMEMBER_TOOL = 'remember_for_trip';
|
||||
|
||||
/** The model's tools a found place is added through: a new place for the day, or one the trip has already. */
|
||||
const FOUND_PLACE_VIA: ReadonlySet<string> = new Set(['create_and_assign_place', 'assign_place_to_day']);
|
||||
|
||||
/**
|
||||
* Changes the server proposes itself, from an attached file or a search result
|
||||
* the user picked rather than from the model. They are held, decided and
|
||||
* recorded like the writes above, and they are not on the allowlist, so no
|
||||
* session ever offers them to the model. A booking is applied by the server
|
||||
* Changes the server applies itself: a booking from an attached file, a search
|
||||
* result the user picked, a note the user wants kept. They are held, decided
|
||||
* and recorded like the writes above, and they are not on the allowlist; only
|
||||
* the note is offered to the model, by the session itself (REMEMBER_SPEC). A booking is applied by the server
|
||||
* itself; a found place deliberately goes through the MCP tool named in its
|
||||
* `via` argument, so it is applied with the user's rights, broadcast and
|
||||
* undone exactly like the same change proposed by the model.
|
||||
@@ -121,6 +130,7 @@ export const ASSISTANT_SERVER_WRITE_TOOLS: Readonly<Record<string, AssistantWrit
|
||||
[IMPORT_BOOKING_TOOL]: { verbKey: 'importBooking', entity: 'reservation' },
|
||||
// The card names the verb of the `via` tool; these are its fallbacks.
|
||||
[ADD_FOUND_PLACE_TOOL]: { verbKey: 'addPlaceToDay', entity: 'place', quiet: true },
|
||||
[REMEMBER_TOOL]: { verbKey: 'rememberNote', entity: 'memory' },
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { McpRegistryService, type McpRegistryListing } from '../../nest-mcp';
|
||||
import { createLocalMcpServer, McpRegistryService, type McpRegistryListing } from '../../nest-mcp';
|
||||
import type { AiToolSpec } from '../ai-connections/ai-chat-client.interface';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { traceEntry } from '../audit/entry-trace.logger';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
import { REMEMBER_SPEC } from './assistant-memory';
|
||||
import {
|
||||
ASSISTANT_ARG_POLICY,
|
||||
ASSISTANT_READ_TOOLS,
|
||||
@@ -13,11 +14,11 @@ import {
|
||||
ASSISTANT_WRITE_TOOLS,
|
||||
isDeniedTool,
|
||||
PINNED_ARG,
|
||||
REMEMBER_TOOL,
|
||||
} from './assistant-tools.constants';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
|
||||
type ToolArgs = Record<string, unknown>;
|
||||
@@ -121,23 +122,25 @@ function readResult(result: unknown): ToolRun {
|
||||
*/
|
||||
export class AssistantToolSession {
|
||||
constructor(
|
||||
private readonly client: Client,
|
||||
private readonly server: McpServer,
|
||||
private readonly client: InstanceType<typeof Client>,
|
||||
private readonly server: ReturnType<typeof createLocalMcpServer>,
|
||||
private readonly tools: ReadonlyMap<string, ListedTool>,
|
||||
private readonly tripId: number,
|
||||
private readonly audit: (toolName: string) => void,
|
||||
) {}
|
||||
|
||||
/** The tools as the model is offered them. */
|
||||
/** The tools as the model is offered them, with the trip notes the server keeps itself. */
|
||||
specs(): AiToolSpec[] {
|
||||
return [...this.tools.values()].map((tool) => ({
|
||||
const listed = [...this.tools.values()].map((tool) => ({
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: modelSchema(tool.name, tool.inputSchema),
|
||||
}));
|
||||
return [...listed, REMEMBER_SPEC];
|
||||
}
|
||||
|
||||
kindOf(name: string): AssistantToolKind | null {
|
||||
if (name === REMEMBER_TOOL) return 'write';
|
||||
return this.tools.get(name)?.kind ?? null;
|
||||
}
|
||||
|
||||
@@ -208,7 +211,7 @@ export class AssistantToolsService implements OnApplicationBootstrap {
|
||||
* attached: the assistant passes no dynamic tool source.
|
||||
*/
|
||||
async open(userId: number, tripId: number, include: ReadonlySet<string> = ASSISTANT_TOOL_ALLOWLIST) {
|
||||
const server = new McpServer({ name: 'TREK assistant', version: '1.0.0' });
|
||||
const server = createLocalMcpServer('TREK assistant');
|
||||
const around = (info: { kind: string; name: string }, call: () => unknown): unknown =>
|
||||
traceEntry('mcp', `${info.kind} ${info.name} user=${userId} client=assistant`, () =>
|
||||
withRequestContext(this.orm, call),
|
||||
|
||||
@@ -25,6 +25,8 @@ How you work:
|
||||
- The trip card may start with what the user is asking about. A question about "this place", "it" or "here" is about that; never ask which place they mean then.
|
||||
- The user can name days, places and bookings with "@" before the name. The trip card then lists what they named, with the ids; use those.
|
||||
- The app shows the places your searches find as cards with a picture, and the weather you look up as a strip. Do not list them again in your text; say in a sentence or two which ones you suggest and why.
|
||||
- When the user asks you to remember something for this trip (who travels, what they like or avoid), keep it with remember_for_trip; it comes back as <trip_notes> in every later conversation. Never say you cannot remember things.
|
||||
- Existing expenses can be changed with update_budget_item (their ids are in get_trip_summary); never add a second entry to correct one.
|
||||
- If the request is unclear, ask one short question instead of guessing.`;
|
||||
|
||||
/** The standing instructions, telling the model which language to answer in. */
|
||||
|
||||
@@ -36,6 +36,7 @@ import { AssistantBookingImportService } from './assistant-booking-import.servic
|
||||
import { mentionItems } from './assistant-cards.helpers';
|
||||
import { buildTripCard, categoriesFrom, languageName, todayIn, turnContext, type TripCard } from './assistant-context';
|
||||
import { messageIdOf, outputText, partsOf, toChatHistory, toThreadMessages } from './assistant-history';
|
||||
import { rememberForTrip } from './assistant-memory';
|
||||
import { toolOutputForProvider } from './assistant-redact';
|
||||
import { AssistantStreamRegistry } from './assistant-stream.registry';
|
||||
import { titleFrom } from './assistant-title';
|
||||
@@ -47,6 +48,7 @@ import {
|
||||
foundPlaceArgs,
|
||||
IMPORT_BOOKING_TOOL,
|
||||
READ_BOOKING_FILE_TOOL,
|
||||
REMEMBER_TOOL,
|
||||
TURNS_PER_MINUTE,
|
||||
UNDO_WINDOW_MS,
|
||||
writeToolOf,
|
||||
@@ -397,6 +399,7 @@ export class AssistantService {
|
||||
): Promise<ToolRun> {
|
||||
if (name === IMPORT_BOOKING_TOOL) return this.inContext(() => this.bookings.apply(userId, tripId, args));
|
||||
if (name === ADD_FOUND_PLACE_TOOL) return session.call(writeToolOf(name, args), foundPlaceArgs(args));
|
||||
if (name === REMEMBER_TOOL) return this.inContext(() => rememberForTrip(this.settings, userId, tripId, args));
|
||||
return session.call(name, args);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { CardPlace, TripCard } from './assistant-context';
|
||||
import { noteOf } from './assistant-memory';
|
||||
import {
|
||||
ASSISTANT_SERVER_WRITE_TOOLS,
|
||||
ASSISTANT_UNDO_MAP,
|
||||
ASSISTANT_WRITE_TOOLS,
|
||||
IMPORT_BOOKING_TOOL,
|
||||
REMEMBER_TOOL,
|
||||
writeToolOf,
|
||||
} from './assistant-tools.constants';
|
||||
import type {
|
||||
@@ -222,8 +224,7 @@ function route(endpoints: unknown): string {
|
||||
if (!Array.isArray(endpoints)) return '';
|
||||
const end = (role: string) => {
|
||||
const found = endpoints.find((ep: unknown) => (ep as { role?: unknown } | null)?.role === role) as
|
||||
| { name?: unknown; code?: unknown }
|
||||
| undefined;
|
||||
{ name?: unknown; code?: unknown } | undefined;
|
||||
const name = text(found?.name);
|
||||
const code = text(found?.code);
|
||||
if (!name) return code;
|
||||
@@ -270,6 +271,13 @@ interface Described {
|
||||
|
||||
type Describer = (ctx: PreviewContext, args: Args) => Described;
|
||||
|
||||
/** Who shares an expense: the uneven split's members, else the equal one's. */
|
||||
function splitOf(args: Args): unknown {
|
||||
return Array.isArray(args.members)
|
||||
? args.members.map((member: unknown) => (member as { user_id?: unknown } | null)?.user_id)
|
||||
: args.member_ids;
|
||||
}
|
||||
|
||||
const DESCRIBERS: Readonly<Record<string, Describer>> = {
|
||||
create_place: (ctx, args) => {
|
||||
const rows = new Rows();
|
||||
@@ -359,9 +367,6 @@ const DESCRIBERS: Readonly<Record<string, Describer>> = {
|
||||
},
|
||||
create_budget_item: (ctx, args) => {
|
||||
const placeId = id(args, 'place_id');
|
||||
const split = Array.isArray(args.members)
|
||||
? args.members.map((member: unknown) => (member as { user_id?: unknown } | null)?.user_id)
|
||||
: args.member_ids;
|
||||
const rows = new Rows()
|
||||
.add(
|
||||
'price',
|
||||
@@ -370,11 +375,25 @@ const DESCRIBERS: Readonly<Record<string, Describer>> = {
|
||||
: '',
|
||||
)
|
||||
.add('category', text(args.category))
|
||||
.add('members', memberNames(ctx, split))
|
||||
.add('members', memberNames(ctx, splitOf(args)))
|
||||
.add('location', placeName(ctx, placeId))
|
||||
.add('notes', text(args.note));
|
||||
return { subject: text(args.name), rows, dayId: null, placeIds: placeId ? [placeId] : [] };
|
||||
},
|
||||
update_budget_item: (ctx, args) => {
|
||||
const price =
|
||||
typeof args.total_price === 'number'
|
||||
? money(ctx, args.total_price, text(args.currency) || ctx.card.currency)
|
||||
: '';
|
||||
const rows = new Rows()
|
||||
.add('name', text(args.name))
|
||||
.add('price', price)
|
||||
.add('category', text(args.category))
|
||||
.add('members', memberNames(ctx, splitOf(args)))
|
||||
.add('notes', text(args.note));
|
||||
return { subject: text(args.name) || `#${id(args, 'itemId') ?? ''}`, rows, dayId: null, placeIds: [] };
|
||||
},
|
||||
[REMEMBER_TOOL]: (_ctx, args) => ({ subject: noteOf(args) ?? '', rows: new Rows(), dayId: null, placeIds: [] }),
|
||||
create_reservation: (ctx, args) => {
|
||||
const placeId = id(args, 'place_id');
|
||||
const startDay = id(args, 'start_day_id');
|
||||
|
||||
Reference in New Issue
Block a user