mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
191 lines
7.7 KiB
TypeScript
191 lines
7.7 KiB
TypeScript
import { AssistantMessages } from '../../db/entities/AssistantMessages.entity';
|
|
import { AssistantToolCalls } from '../../db/entities/AssistantToolCalls.entity';
|
|
import {
|
|
ASSISTANT_MESSAGE_PARTS_WRITE,
|
|
ASSISTANT_TOOL_ARGS,
|
|
ASSISTANT_TOOL_PREVIEW,
|
|
ASSISTANT_TOOL_RESULT,
|
|
} from '../../db/json-columns';
|
|
import type { AssistantMessagesRepository } from '../../db/repositories/AssistantMessages.repository';
|
|
import type {
|
|
AssistantToolCallRow,
|
|
AssistantToolCallsRepository,
|
|
} from '../../db/repositories/AssistantToolCalls.repository';
|
|
import { dbNow, utcSuffix } from '../../db/types';
|
|
import { decodeJson, encodeJson } from '../../utils/json-column';
|
|
import { withRequestContext } from '../database/request-context';
|
|
import { bookingConfirmationFrom, createsBooking, withBookingConfirmation } from './assistant-booking-intent';
|
|
import {
|
|
appliedPlanPreview,
|
|
DISCARDED,
|
|
type Outcome,
|
|
withOutcomes,
|
|
withPlanEdits,
|
|
} from './assistant-decisions.helpers';
|
|
import { messageTextOf, outputText, partsOf } from './assistant-history';
|
|
import { toolOutputForProvider } from './assistant-output';
|
|
import { UNDO_WINDOW_MS, writeToolOf } from './assistant-tools.constants';
|
|
import type { ToolRun } from './assistant-tools.service';
|
|
import { AssistantCardContext } from './cards/card-context';
|
|
import { ASSISTANT_UNDO_MAP } from './cards/registry';
|
|
import { appliedChange } from './tool-call-preview.helpers';
|
|
import type { UiStreamWriter } from './ui-stream.writer';
|
|
import { MikroORM } from '@mikro-orm/core';
|
|
import { InjectRepository } from '@mikro-orm/nestjs';
|
|
import { Injectable } from '@nestjs/common';
|
|
import {
|
|
withoutRepeatedBookingReference,
|
|
type AssistantMessagePart,
|
|
type AssistantPlanEdits,
|
|
type AssistantScope,
|
|
} from '@trek/shared';
|
|
|
|
/** Where one applied change reports to: the stream, and what its message records. */
|
|
interface AppliedSink {
|
|
w: UiStreamWriter;
|
|
unrun: Set<string>;
|
|
outcomes: Map<string, Outcome>;
|
|
receipts: AssistantMessagePart[];
|
|
/** The trip the conversation is on, for the receipts; null in a Studio conversation. */
|
|
tripId: number | null;
|
|
}
|
|
|
|
/** Executes approved assistant changes and records receipts in their proposing message. */
|
|
@Injectable()
|
|
export class AssistantDecisionExecutor {
|
|
constructor(
|
|
private readonly orm: MikroORM,
|
|
private readonly cardContext: AssistantCardContext,
|
|
@InjectRepository(AssistantMessages) private readonly messages: AssistantMessagesRepository,
|
|
@InjectRepository(AssistantToolCalls) private readonly toolCalls: AssistantToolCallsRepository,
|
|
) {}
|
|
|
|
/**
|
|
* Runs the applied changes (and only those) with their stored arguments,
|
|
* streams each result and receipt, and writes the outcome into the message
|
|
* that proposed them. `run` runs one change: through its tool, or, for a
|
|
* booking from a file, through the booking import.
|
|
*
|
|
* @txIndependent every change runs its tool, which commits on its own,
|
|
* before its outcome is recorded; a later failure must not take back an
|
|
* earlier change's record.
|
|
*/
|
|
async apply(
|
|
run: (name: string, args: Record<string, unknown>) => Promise<ToolRun>,
|
|
threadId: number,
|
|
decided: Array<{ call: AssistantToolCallRow; approved: boolean; planEdits?: AssistantPlanEdits }>,
|
|
{ w, unrun, scope }: { w: UiStreamWriter; unrun: Set<string>; scope: AssistantScope },
|
|
): Promise<boolean> {
|
|
const outcomes = new Map<string, Outcome>();
|
|
const receipts: AssistantMessagePart[] = [];
|
|
const tripId = scope.kind === 'trip' ? scope.tripId : null;
|
|
const bookings = decided.filter(({ call }) => createsBooking(call.tool_name));
|
|
const confirmations = new Map(
|
|
await Promise.all(
|
|
bookings
|
|
.filter(({ approved }) => approved)
|
|
.map(async ({ call }) => {
|
|
const request = await this.inContext(() => this.messages.lastUserBefore(threadId, call.message_id));
|
|
return [call.id, request ? bookingConfirmationFrom(messageTextOf(request)) : null] as const;
|
|
}),
|
|
),
|
|
);
|
|
// One after another: a change may build on the one before it.
|
|
await decided.reduce<Promise<void>>(async (previous, { call, approved, planEdits }) => {
|
|
await previous;
|
|
const execute = (name: string, args: Record<string, unknown>) =>
|
|
run(name, withBookingConfirmation(name, args, confirmations.get(call.id), bookings.length === 1));
|
|
await this.applyOne(execute, call, approved, planEdits, { w, unrun, outcomes, receipts, tripId });
|
|
}, Promise.resolve());
|
|
await this.record(threadId, decided[0].call.message_id, outcomes, receipts);
|
|
return [...outcomes.values()].every((outcome) => outcome.approved && !outcome.isError);
|
|
}
|
|
|
|
/** Runs one decided change, or records it as discarded, and tells the client what became of it. */
|
|
private async applyOne(
|
|
run: (name: string, args: Record<string, unknown>) => Promise<ToolRun>,
|
|
call: AssistantToolCallRow,
|
|
approved: boolean,
|
|
planEdits: AssistantPlanEdits | undefined,
|
|
{ w, unrun, outcomes, receipts, tripId }: AppliedSink,
|
|
): Promise<void> {
|
|
if (!approved) {
|
|
w.toolDenied(call.id);
|
|
outcomes.set(call.id, { approved: false, result: DISCARDED, isError: false });
|
|
return;
|
|
}
|
|
const stored = decodeJson(ASSISTANT_TOOL_ARGS, call.args, `tool call ${call.id}`);
|
|
const tool = writeToolOf(call.tool_name, stored);
|
|
let args = withPlanEdits(tool, stored, planEdits);
|
|
if (
|
|
tool === 'create_reservation' &&
|
|
typeof args.notes === 'string' &&
|
|
typeof args.confirmation_number === 'string'
|
|
) {
|
|
const notes = withoutRepeatedBookingReference(args.notes, args.confirmation_number);
|
|
if (notes !== args.notes) args = { ...args, notes: notes || undefined };
|
|
}
|
|
const ran = await run(call.tool_name, args);
|
|
const output = toolOutputForProvider(call.tool_name, ran.value);
|
|
const preview = decodeJson(ASSISTANT_TOOL_PREVIEW, call.preview, `tool call ${call.id}`);
|
|
const undoable = ran.ok && !!ASSISTANT_UNDO_MAP[writeToolOf(call.tool_name, args)]?.args(args, ran.value, preview);
|
|
const undoUntil = undoable ? dbNow(new Date(Date.now() + UNDO_WINDOW_MS)) : null;
|
|
await this.inContext(() =>
|
|
this.toolCalls.recordOutcome(
|
|
call.id,
|
|
ran.ok ? 'executed' : 'failed',
|
|
encodeJson(ASSISTANT_TOOL_RESULT, ran.value),
|
|
undoUntil,
|
|
),
|
|
);
|
|
unrun.delete(call.id);
|
|
outcomes.set(call.id, { approved: true, result: output, isError: !ran.ok });
|
|
if (!ran.ok) {
|
|
w.toolError(call.id, outputText(output));
|
|
return;
|
|
}
|
|
w.toolOutput(call.id, output);
|
|
const edited = appliedPlanPreview(preview, planEdits, ran.value);
|
|
if (edited) {
|
|
w.change(edited);
|
|
receipts.push({ type: 'data-trek-change', data: edited });
|
|
}
|
|
const applied = appliedChange(
|
|
call.tool_name,
|
|
call.id,
|
|
args,
|
|
ran.value,
|
|
preview?.dayId ?? null,
|
|
utcSuffix(undoUntil),
|
|
{ preview, tripId },
|
|
);
|
|
if (applied) {
|
|
w.applied(applied);
|
|
receipts.push({ type: 'data-trek-applied', data: applied });
|
|
}
|
|
this.cardContext.receipt(w, receipts, call, args, ran.value, preview);
|
|
}
|
|
|
|
/** Writes what became of the decided changes into the message that proposed them. */
|
|
async record(
|
|
threadId: number,
|
|
messageId: number,
|
|
outcomes: ReadonlyMap<string, Outcome>,
|
|
receipts: AssistantMessagePart[],
|
|
): Promise<void> {
|
|
await this.inContext(async () => {
|
|
const row = await this.messages.findInThread(messageId, threadId);
|
|
if (!row) return;
|
|
const parts = withOutcomes(partsOf(row), outcomes);
|
|
await this.messages.update(messageId, {
|
|
parts: encodeJson(ASSISTANT_MESSAGE_PARTS_WRITE, [...parts, ...receipts]),
|
|
status: 'complete',
|
|
});
|
|
});
|
|
}
|
|
|
|
private inContext<T>(fn: () => Promise<T>): Promise<T> {
|
|
return withRequestContext(this.orm, fn);
|
|
}
|
|
}
|