feat(assistant): models that read images see the live page

The Studio draws the page on request and uploads it once, each provider gets
the image where it expects it, and a refusal falls back to the text
description. No image is stored.
This commit is contained in:
Maurice
2026-10-22 21:25:46 +00:00
parent 499458f8b2
commit 8b93898b73
38 changed files with 2714 additions and 123 deletions
@@ -2,7 +2,7 @@ import type { AiProviderState } from '../../db/json-columns';
import type { AiConnectionKind } from '@trek/shared';
export type { AiProviderState };
export { AiProviderError } from './providers/provider-errors';
export { AiProviderError, isImageRefusal } from './providers/provider-errors';
/** A tool the model may call: its name, what it is for and its arguments as JSON Schema. */
export interface AiToolSpec {
@@ -18,16 +18,30 @@ export interface AiToolCall {
args: Record<string, unknown>;
}
/**
* An image a message carries to a model that reads images (the Studio page
* the assistant looks at), base64 without line breaks. It lives for one turn
* in memory; nothing stores it.
*/
export interface AiImage {
mimeType: 'image/jpeg' | 'image/png' | 'image/webp';
data: string;
detail?: 'low' | 'high';
}
/**
* The provider-neutral history a turn sends. A tool result answers the call
* with the same id; an assistant message may carry the items its provider
* needs replayed verbatim (`providerState`), which an adapter for another
* provider ignores and rebuilds from the text and the calls instead.
* provider ignores and rebuilds from the text and the calls instead. A user
* message or a tool result may carry images; each adapter places them where
* its provider reads them, and the assistant sends none to a model that reads
* no images.
*/
export type AiChatMessage =
| { role: 'user'; text: string }
| { role: 'user'; text: string; images?: AiImage[] }
| { role: 'assistant'; text: string; toolCalls: AiToolCall[]; providerState?: AiProviderState | null }
| { role: 'tool'; toolCallId: string; name: string; output: string; isError?: boolean };
| { role: 'tool'; toolCallId: string; name: string; output: string; isError?: boolean; images?: AiImage[] };
export interface AiChatRequest {
/** The standing instructions, the same on every turn of a conversation (cached where the provider can). */
@@ -34,6 +34,13 @@ export const AI_DEFAULT_RETENTION: AiRetention = { mode: 'days', days: 90 };
/** The user setting that records which `kind@host` a user was told receives their messages. */
export const AI_PRIVACY_ACK_SETTING = 'assistant_privacy_ack';
/**
* The user setting that records which `kind@host` a user let receive images of
* their Studio pages (journey-studio.md 3.4), asked for on its own: the
* planner's notice says no files leave, which a page image would contradict.
*/
export const AI_STUDIO_IMAGES_ACK_SETTING = 'assistant_privacy_ack_studio_images';
/**
* Why a connection request was refused, as the client reads it from the body's
* `code`: the assistant's error codes, plus the ones only setting up a
@@ -12,6 +12,7 @@ import { pickConnection } from './ai-connection.resolver';
import {
AI_BASE_URLS,
AI_PRIVACY_ACK_SETTING,
AI_STUDIO_IMAGES_ACK_SETTING,
aiHostOf,
aiRefusal,
openrouterOAuthAvailable,
@@ -128,6 +129,7 @@ export class AiConnectionsService implements SharedAiConnectionPort {
? { used: await this.usage.instanceTurnsToday(userId), limit: settings.dailyTurns }
: null,
privacyAcked: acked,
studioImagesAcked: !!effective && (await this.studioImagesAckedFor(userId, `${kindOf(effective)}@${host}`)),
retention: settings.retention,
openrouterOAuth: openrouterOAuthAvailable(),
};
@@ -226,9 +228,23 @@ export class AiConnectionsService implements SharedAiConnectionPort {
return viewOf(await this.ownRow(userId));
}
/** The user saw that `kind@host` receives their messages on the instance's connection. */
/**
* The user saw that `kind@host` receives their messages on the instance's
* connection, or (`scope: 'studio_images'`) that it may also receive images
* of their Studio pages, on any connection.
*/
async ackPrivacy(userId: number, req: AiPrivacyAckRequest): Promise<void> {
await this.settings.upsertSetting(userId, AI_PRIVACY_ACK_SETTING, `${req.kind}@${req.host}`);
const key = req.scope === 'studio_images' ? AI_STUDIO_IMAGES_ACK_SETTING : AI_PRIVACY_ACK_SETTING;
await this.settings.upsertSetting(userId, key, `${req.kind}@${req.host}`);
}
/** Whether the user let this connection receive images of their Studio pages; without it a turn stays text. */
async studioImagesAcked(userId: number, connection: Pick<ResolvedAiConnection, 'kind' | 'host'>): Promise<boolean> {
return this.studioImagesAckedFor(userId, `${connection.kind}@${connection.host}`);
}
private async studioImagesAckedFor(userId: number, target: string): Promise<boolean> {
return (await this.settings.getDecryptedUserSetting(userId, AI_STUDIO_IMAGES_ACK_SETTING)) === target;
}
// ── The instance's connection (admin) ──────────────────────────────────────
@@ -35,6 +35,34 @@ const CHATGPT_FALLBACK_MODELS = [
/** OpenAI's list holds every model of the account; these are the ones a chat with tools cannot use. */
const OPENAI_NOT_FOR_CHAT = /(audio|realtime|transcribe|tts|image|search|instruct|embedding|moderation|codex)/;
/**
* OpenAI chat models that read no images: the first GPT-4 and its dated
* snapshots, GPT-3.5 and the small reasoning models of the o1 and o3 lines.
* Every other chat model on the list reads them. A model this misses is
* caught at run time: the provider refuses the image and the assistant goes
* on without it.
*/
const OPENAI_TEXT_ONLY = /^(?:gpt-3\.5|gpt-4(?:-0\d{3})?$|o1-mini|o1-preview|o3-mini)/;
/** Whether an OpenAI chat model reads images. */
function openAiReadsImages(id: string): boolean {
return !OPENAI_TEXT_ONLY.test(id);
}
/**
* Whether the model a turn runs on reads images, without asking the provider:
* every current Anthropic and Gemini model and every model of a ChatGPT plan
* do, OpenAI's by name. OpenRouter's and a custom server's cannot be told
* from the id alone, so they stay on the page description (journey-studio.md
* 6, cut 5); the model list still says so for OpenRouter where it can. A
* model this takes for one that reads images and that refuses one is caught
* at run time and remembered as text-only.
*/
export function modelReadsImages(kind: AiConnectionKind, model: string): boolean {
if (kind === 'openai') return openAiReadsImages(model);
return kind === 'anthropic' || kind === 'gemini' || kind === 'chatgpt';
}
const openAiListSchema = z.object({ data: z.array(z.object({ id: z.string() })) });
const anthropicListSchema = z.object({
data: z.array(z.object({ id: z.string(), display_name: z.string().optional() })),
@@ -45,6 +73,7 @@ const openRouterListSchema = z.object({
id: z.string(),
name: z.string().optional(),
supported_parameters: z.array(z.string()).optional(),
architecture: z.object({ input_modalities: z.array(z.string()).optional() }).optional(),
pricing: z.object({ prompt: z.string().optional(), completion: z.string().optional() }).optional(),
}),
),
@@ -150,6 +179,7 @@ export class ModelCatalogService {
id: m.id,
label: m.display_name ?? m.id,
supportsTools: true,
supportsImages: true,
}));
}
case 'openai': {
@@ -158,14 +188,14 @@ export class ModelCatalogService {
.data.map((m) => m.id)
.filter((id) => (id.startsWith('gpt-') || /^o\d/.test(id)) && !OPENAI_NOT_FOR_CHAT.test(id))
.sort()
.map((id) => ({ id, label: id, supportsTools: true }));
.map((id) => ({ id, label: id, supportsTools: true, supportsImages: openAiReadsImages(id) }));
}
case 'gemini': {
const body = await this.getJson(target.kind, `${AI_BASE_URLS.gemini}/models`, bearer(secret));
return parsed(openAiListSchema, body)
.data.map((m) => m.id.replace(/^models\//, ''))
.filter((id) => id.startsWith('gemini') && !/(embedding|image|tts|audio)/.test(id))
.map((id) => ({ id, label: id, supportsTools: true }));
.map((id) => ({ id, label: id, supportsTools: true, supportsImages: true }));
}
case 'openrouter': {
// The model list is public; the key is checked on its own first.
@@ -178,6 +208,8 @@ export class ModelCatalogService {
label: m.name ?? m.id,
supportsTools: true,
free: m.pricing?.prompt === '0' && m.pricing?.completion === '0',
// A model OpenRouter lists without its input kinds is taken as one that reads no images.
supportsImages: m.architecture?.input_modalities?.includes('image') ?? false,
}));
}
case 'chatgpt':
@@ -193,12 +225,12 @@ export class ModelCatalogService {
const body = await this.getJson('chatgpt', `${AI_BASE_URLS.chatgpt}/models`, bearer(accessToken));
listed = parsed(chatgptListSchema, body)
.models.filter((m) => m.visibility === 'list' && m.supported_in_api !== false)
.map((m) => ({ id: m.slug, label: m.display_name ?? m.slug, supportsTools: true }));
.map((m) => chatgptModel(m.slug, m.display_name));
} catch (err) {
// A refused sign-in is the answer; anything else falls back to the known list.
if (err instanceof AiProviderError && !err.retryable && err.code !== 'generic') throw err;
}
return listed.length > 0 ? listed : CHATGPT_FALLBACK_MODELS.map((id) => ({ id, label: id, supportsTools: true }));
return listed.length > 0 ? listed : CHATGPT_FALLBACK_MODELS.map((id) => chatgptModel(id));
}
private async customModels(baseUrl: string | null, apiKey: string | null): Promise<AiModelInfo[]> {
@@ -231,6 +263,11 @@ export class ModelCatalogService {
}
}
/** A model of a ChatGPT plan: every one reads images through the Responses API. */
function chatgptModel(id: string, label?: string): AiModelInfo {
return { id, label: label ?? id, supportsTools: true, supportsImages: true };
}
function bearer(secret: string): Record<string, string> {
return { authorization: `Bearer ${secret}` };
}
@@ -4,6 +4,7 @@ import type {
AiChatMessage,
AiChatRequest,
AiFinishReason,
AiImage,
AiToolCall,
} from '../ai-chat-client.interface';
import { AI_BASE_URLS } from '../ai-connections.constants';
@@ -32,10 +33,18 @@ const MAX_TOKENS = 32_000;
type ContentBlock = Record<string, unknown>;
type AnthropicMessage = { role: 'user' | 'assistant'; content: ContentBlock[] };
/** An image as a Messages API block: base64 in the request, never a URL. */
function imageBlock(image: AiImage): ContentBlock {
return { type: 'image', source: { type: 'base64', media_type: image.mimeType, data: image.data } };
}
/**
* The provider-neutral history as Messages API turns: a tool result is a
* `tool_result` block of a user turn, and turns of the same role that follow
* each other merge into one, since the API wants them alternating.
* each other merge into one, since the API wants them alternating. An image
* of a tool result goes inside that `tool_result`, after its text, where the
* model reads it as what the tool produced; a user's images go before their
* words.
*/
export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage[] {
const out: AnthropicMessage[] = [];
@@ -47,18 +56,20 @@ export function toAnthropicMessages(messages: AiChatMessage[]): AnthropicMessage
};
for (const message of messages) {
if (message.role === 'user') {
push('user', [{ type: 'text', text: message.text }]);
push('user', [...(message.images ?? []).map(imageBlock), { type: 'text', text: message.text }]);
} else if (message.role === 'assistant') {
push('assistant', [
...(message.text ? [{ type: 'text', text: message.text }] : []),
...message.toolCalls.map((call) => ({ type: 'tool_use', id: call.id, name: call.name, input: call.args })),
]);
} else {
const images = (message.images ?? []).map(imageBlock);
const output = images.length > 0 ? [{ type: 'text', text: message.output }, ...images] : message.output;
push('user', [
{
type: 'tool_result',
tool_use_id: message.toolCallId,
content: message.output,
content: output,
...(message.isError ? { is_error: true } : {}),
},
]);
@@ -4,6 +4,7 @@ import type {
AiChatMessage,
AiChatRequest,
AiFinishReason,
AiImage,
AiToolCall,
} from '../ai-chat-client.interface';
import { AiProviderError, errorCodeOf, providerFailure } from './provider-errors';
@@ -17,20 +18,43 @@ import {
toProviderSchema,
type AiFetch,
} from './provider-http';
import { imageDataUrl, toolImageCaption, toolImagesEndingAt } from './provider-images';
import { readSseEvents } from './sse-lines';
import type { AiConnectionKind } from '@trek/shared';
/** The end of an OpenAI-compatible stream. */
const DONE = '[DONE]';
/** The provider-neutral history as Chat Completions messages, the instructions and the trip card first. */
/**
* The provider-neutral history as Chat Completions messages, the instructions
* and the trip card first. A tool message takes no image, so the images of a
* step's tool results follow its last result as one user message.
*/
export function toChatMessages(request: AiChatRequest): Record<string, unknown>[] {
const system = [request.system, request.context].filter(Boolean).join('\n\n');
return [{ role: 'system', content: system }, ...request.messages.map(toChatMessage)];
const out: Record<string, unknown>[] = [{ role: 'system', content: system }];
request.messages.forEach((message, index) => {
out.push(toChatMessage(message));
const withImages = toolImagesEndingAt(request.messages, index);
if (withImages.length === 0) return;
const content = withImages.flatMap((tool) => [
{ type: 'text', text: toolImageCaption(tool) },
...(tool.images ?? []).map(imagePart),
]);
out.push({ role: 'user', content });
});
return out;
}
function imagePart(image: AiImage): Record<string, unknown> {
return { type: 'image_url', image_url: { url: imageDataUrl(image), detail: image.detail ?? 'high' } };
}
function toChatMessage(message: AiChatMessage): Record<string, unknown> {
if (message.role === 'user') return { role: 'user', content: message.text };
if (message.role === 'user') {
if (!message.images?.length) return { role: 'user', content: message.text };
return { role: 'user', content: [{ type: 'text', text: message.text }, ...message.images.map(imagePart)] };
}
if (message.role === 'tool') return { role: 'tool', tool_call_id: message.toolCallId, content: message.output };
return {
role: 'assistant',
@@ -4,6 +4,7 @@ import type {
AiChatEvent,
AiChatMessage,
AiChatRequest,
AiImage,
AiProviderState,
} from '../ai-chat-client.interface';
import { AI_BASE_URLS } from '../ai-connections.constants';
@@ -18,6 +19,7 @@ import {
toProviderSchema,
type AiFetch,
} from './provider-http';
import { imageDataUrl, toolImageCaption, toolImagesEndingAt } from './provider-images';
import { readSseEvents } from './sse-lines';
/** The namespace the tools are grouped in, as Sign in with ChatGPT asks for. */
@@ -40,13 +42,28 @@ type ChatgptTokenSource = (rejected?: string) => Promise<string>;
export function toResponsesInput(request: AiChatRequest): Record<string, unknown>[] {
const input: Record<string, unknown>[] = [];
if (request.context) input.push({ type: 'message', role: 'developer', content: request.context });
for (const message of request.messages) input.push(...toItems(message));
request.messages.forEach((message, index) => {
input.push(...toItems(message));
// A call's output is text; the images of a step's results follow its last one as a user message.
const withImages = toolImagesEndingAt(request.messages, index);
if (withImages.length === 0) return;
const content = withImages.flatMap((tool) => [
{ type: 'input_text', text: toolImageCaption(tool) },
...(tool.images ?? []).map(inputImage),
]);
input.push({ type: 'message', role: 'user', content });
});
return input;
}
function inputImage(image: AiImage): Record<string, unknown> {
return { type: 'input_image', image_url: imageDataUrl(image), detail: image.detail ?? 'high' };
}
function toItems(message: AiChatMessage): Record<string, unknown>[] {
if (message.role === 'user') {
return [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: message.text }] }];
const images = (message.images ?? []).map(inputImage);
return [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: message.text }, ...images] }];
}
if (message.role === 'tool') {
return [{ type: 'function_call_output', call_id: message.toolCallId, output: message.output }];
@@ -83,3 +83,40 @@ export function errorCodeOf(body: unknown): string | undefined {
}
return undefined;
}
/**
* The code a refusal carries when the provider said the request's image was
* the problem: a model that reads no images, a format it does not take. The
* assistant then sends the step again without images and remembers the model
* as one that reads none.
*/
export const IMAGE_INPUT_REFUSED = 'image_input_refused';
/** How far into an error body's message the image check reads. */
const MAX_MESSAGE_CHARS = 2000;
/** The providers' wording for an image they refuse ("image_url is only supported by certain models"). */
const NAMES_IMAGE = /\b(?:image|images|image_url|input_image|vision)\b/i;
/** The message out of a provider's JSON error body, wherever it puts it; '' when it has none. */
function errorMessageOf(body: unknown): string {
if (!body || typeof body !== 'object') return '';
const record = body as Record<string, unknown>;
const inner = record.error;
if (inner && typeof inner === 'object' && typeof (inner as Record<string, unknown>).message === 'string') {
return (inner as Record<string, string>).message;
}
if (typeof record.message === 'string') return record.message;
return typeof record.detail === 'string' ? record.detail : '';
}
/** Whether a refused request was refused over its image, read from the status and the error body. */
export function namesImageInput(status: number, body: unknown): boolean {
if (status !== 400 && status !== 415 && status !== 422) return false;
return NAMES_IMAGE.test(errorMessageOf(body).slice(0, MAX_MESSAGE_CHARS));
}
/** Whether a provider error is the refusal of an image (see IMAGE_INPUT_REFUSED). */
export function isImageRefusal(err: unknown): boolean {
return err instanceof AiProviderError && err.providerCode === IMAGE_INPUT_REFUSED;
}
@@ -1,6 +1,6 @@
import { readCappedJson } from '../../../utils/cappedFetch';
import { logWarn } from '../../audit/audit-log.logger';
import { AiProviderError, errorCodeOf, providerFailure } from './provider-errors';
import { AiProviderError, errorCodeOf, IMAGE_INPUT_REFUSED, namesImageInput, providerFailure } from './provider-errors';
import type { AiConnectionKind } from '@trek/shared';
/**
@@ -54,7 +54,11 @@ export async function openProviderStream(
/** The AiProviderError a non-success response stands for, read from its status and its error body. */
export async function refusalOf(kind: AiConnectionKind, res: Response): Promise<AiProviderError> {
const body = await readCappedJson<unknown>(res, MAX_ERROR_BYTES).catch(() => undefined);
const code = errorCodeOf(body);
const named = errorCodeOf(body);
// A refused image is named by its own code, so the turn can send the step again without it; a
// refusal the provider's own code already explains (a plan that does not cover it) keeps that code.
const image = namesImageInput(res.status, body) && providerFailure(kind, res.status, named).code === 'generic';
const code = image ? IMAGE_INPUT_REFUSED : named;
// Status and code only: an error body can quote the request, and the request holds the trip.
logWarn(`[ai] ${kind} refused the request: HTTP ${res.status}${code ? ` (${code})` : ''}`);
return providerFailure(kind, res.status, code);
@@ -0,0 +1,29 @@
import type { AiChatMessage, AiImage } from '../ai-chat-client.interface';
type ToolMessage = Extract<AiChatMessage, { role: 'tool' }>;
/** An image as the data URL the OpenAI-style APIs read: base64 in the request, never a link to TREK. */
export function imageDataUrl(image: AiImage): string {
return `data:${image.mimeType};base64,${image.data}`;
}
/** The line an image of a tool result is introduced with, where it has to travel in a user message. */
export function toolImageCaption(message: ToolMessage): string {
return `The image the call ${message.name} (${message.toolCallId}) produced:`;
}
/**
* The tool results with images whose run ends at `index`: an API that takes
* no image inside a tool result (Chat Completions, Responses) gets them in
* one user message after the last result of the step, since the results must
* follow the assistant's calls directly. Empty while the run goes on, or when
* nothing in it carried an image.
*/
export function toolImagesEndingAt(messages: readonly AiChatMessage[], index: number): ToolMessage[] {
if (messages[index]?.role !== 'tool' || messages[index + 1]?.role === 'tool') return [];
let start = index;
while (start > 0 && messages[start - 1]?.role === 'tool') start--;
return messages
.slice(start, index + 1)
.filter((message): message is ToolMessage => message.role === 'tool' && (message.images?.length ?? 0) > 0);
}
+105 -16
View File
@@ -1,8 +1,10 @@
import type { AiProviderState } from '../../db/json-columns';
import {
AiProviderError,
isImageRefusal,
type AiChatClient,
type AiChatMessage,
type AiImage,
type AiToolCall,
type AiToolSpec,
} from '../ai-connections/ai-chat-client.interface';
@@ -15,22 +17,42 @@ import type { AssistantToolKind, ToolRun } from './assistant-tools.service';
import type { AnswerInput } from './cards/card-types';
import { answerCardOf } from './cards/registry';
import type { UiStreamWriter } from './ui-stream.writer';
import type {
AssistantChangePreview,
AssistantErrorCode,
AssistantMessagePart,
AssistantWeatherDay,
TrekCard,
import {
ASSISTANT_PAGE_IMAGE,
type AssistantChangePreview,
type AssistantErrorCode,
type AssistantMessagePart,
type AssistantPageView,
type AssistantWeatherDay,
type TrekCard,
} from '@trek/shared';
type ToolArgs = Record<string, unknown>;
/** The tools of the turn, as the loop uses them (an AssistantToolSession). */
interface AgentToolPort {
/**
* What a tool call came back with; a look at a Studio page also brings the
* page image for the model (in memory for this turn only) and what the
* message keeps of the look.
*/
export interface AgentToolRun extends ToolRun {
images?: AiImage[];
view?: AssistantPageView;
}
/** The tools of the turn, as the loop uses them (an AssistantToolSession, in the Studio with its page preview). */
export interface AgentToolPort {
specs(): AiToolSpec[];
kindOf(name: string): AssistantToolKind | null;
pinArgs(name: string, args: ToolArgs): { args: ToolArgs } | { error: string };
call(name: string, args: ToolArgs): Promise<ToolRun>;
call(name: string, args: ToolArgs): Promise<AgentToolRun>;
}
/** A Studio turn's page images, as the loop uses them (assistant-vision.ts). */
export interface AgentVision {
/** The provider refused an image: the rest of the turn, and later turns on this model, go without. */
refused(): void;
/** The history a turn starts from, with views of the pages the changes just applied left. */
afterApply(history: readonly AiChatMessage[]): Promise<AiChatMessage[]>;
}
/** What one step leaves in its message row. */
@@ -71,6 +93,13 @@ export interface AgentDeps {
today: string;
/** The card a read's answer shows; the registry's (`answerCardOf`) unless a test hands in its own. */
answerCard?: (tool: string, input: AnswerInput) => TrekCard | null;
/**
* Why a proposed change goes back to the model as its call's error instead
* of to the user (a Studio turn's book check); null holds it as usual.
*/
refusalOf?: (tool: string, args: ToolArgs) => Promise<string | null>;
/** A Studio turn's page images; without it no image ever goes to the model. */
vision?: AgentVision | null;
}
export interface AgentInput {
@@ -103,6 +132,8 @@ interface StepParts {
knownPlaceIds: Set<string>;
/** The answer cards the step has shown; past MAX_CARDS_PER_STEP a read shows none. */
cards: number;
/** The page images of the step's reads, by call id, for the model's next request only. */
images: Map<string, AiImage[]>;
}
/** The longest call id a card is kept under; a read under a longer one shows no card. */
@@ -169,6 +200,12 @@ async function runRead(
...(run.ok ? {} : { isError: true }),
});
if (!run.ok) return;
// A look at a Studio page: the message keeps what was looked at, the model gets one image of it.
if (run.view) {
w.pageView(run.view);
step.parts.push({ type: 'data-trek-page-view', data: run.view });
}
if (run.images?.length) step.images.set(id, run.images.slice(0, 1));
const input = { toolCallId: id, args, value: run.value, card: deps.card, today: deps.today };
const card = id.length <= MAX_CARD_CALL_ID ? (deps.answerCard ?? answerCardOf)(name, input) : null;
if (card && step.cards++ < MAX_CARDS_PER_STEP) {
@@ -221,6 +258,39 @@ interface StepAnswer {
cutOff: boolean;
}
/**
* The history as one model request carries it: the page images of the
* newest `max` messages that have any, one image each; older messages go as
* their text alone, which holds the page's description.
*/
function limitImages(history: readonly AiChatMessage[], max: number): AiChatMessage[] {
let kept = 0;
return history
.slice()
.reverse()
.map((message) => {
if (message.role === 'assistant' || !message.images?.length) return message;
return { ...message, images: kept++ < max ? message.images.slice(0, 1) : undefined };
})
.reverse();
}
/**
* A provider that refused the request over its images (a model that reads
* none after all): the turn's history loses its images, the vision remembers
* the model as text only, and the step is asked again, once. False for any
* other failure, or when there was no image to drop.
*/
function dropImagesAfter(turn: Turn, err: unknown): boolean {
const withImages = turn.history.some((message) => message.role !== 'assistant' && !!message.images?.length);
if (!turn.deps.vision || !withImages || !isImageRefusal(err)) return false;
turn.deps.vision.refused();
turn.history.forEach((message, index) => {
if (message.role !== 'assistant' && message.images) turn.history[index] = { ...message, images: undefined };
});
return true;
}
/** Streams one answer of the model; a failure or a stop ends the turn here, saved as far as it got. */
async function streamAnswer(turn: Turn, rowId: number): Promise<StepAnswer | AgentOutcome> {
const { deps, input, w, signal } = turn;
@@ -230,7 +300,7 @@ async function streamAnswer(turn: Turn, rowId: number): Promise<StepAnswer | Age
{
system: input.system,
context: input.context,
messages: turn.history,
messages: limitImages(turn.history, ASSISTANT_PAGE_IMAGE.perRequest),
tools: deps.tools.specs(),
cacheKey: input.cacheKey,
},
@@ -250,6 +320,9 @@ async function streamAnswer(turn: Turn, rowId: number): Promise<StepAnswer | Age
}
return answer;
} catch (err) {
if (!signal.aborted && !answer.text && answer.received.length === 0 && dropImagesAfter(turn, err)) {
return streamAnswer(turn, rowId);
}
const partial: StepRecord = {
parts: answer.text ? [{ type: 'text', text: answer.text }] : [],
providerState: null,
@@ -282,6 +355,10 @@ async function runCalls(turn: Turn, calls: AiToolCall[], collected: StepParts):
let prepared = kind ? deps.tools.pinArgs(call.name, call.args) : { error: `Unknown tool: ${call.name}` };
const unknownPlace = 'error' in prepared ? null : placeIdRefusal(call.name, prepared.args, turn.knownPlaceIds);
if (unknownPlace) prepared = { error: unknownPlace };
if (kind === 'write' && !('error' in prepared)) {
const refused = await deps.refusalOf?.(call.name, prepared.args);
if (refused) prepared = { error: refused };
}
if (kind === 'read' && !('error' in prepared)) reads += 1;
const overCap = kind === 'write' ? writes > MAX_WRITES_PER_STEP : reads > MAX_READS_PER_STEP;
if ('error' in prepared || overCap) {
@@ -334,19 +411,30 @@ async function holdChanges(turn: Turn, rowId: number, step: StepRecord, held: He
return outcomeOf(turn, 'awaiting');
}
/** Records a step that ran its reads, and hands their answers back for the next one. */
async function carryOn(turn: Turn, rowId: number, step: StepRecord, text: string, calls: AiToolCall[]): Promise<void> {
/**
* Records a step that ran its reads, and hands their answers back for the
* next one, a page image beside the answer of the look that brought it.
*/
async function carryOn(
turn: Turn,
rowId: number,
step: StepRecord,
answer: { text: string; calls: AiToolCall[]; images: ReadonlyMap<string, AiImage[]> },
): Promise<void> {
await turn.deps.store.saveStep(rowId, step, 'complete');
turn.w.finishStep();
const { text, calls, images } = answer;
turn.history.push({ role: 'assistant', text, toolCalls: calls, providerState: step.providerState });
for (const part of step.parts) {
if (part.type !== 'tool-call') continue;
const seen = images.get(part.toolCallId);
turn.history.push({
role: 'tool',
toolCallId: part.toolCallId,
name: part.toolName,
output: outputText(part.result),
...(part.isError ? { isError: true } : {}),
...(seen ? { images: seen } : {}),
});
}
}
@@ -387,7 +475,7 @@ async function runStep(turn: Turn, step: number): Promise<AgentOutcome | null> {
}
const calls = received.map((call) => ({ ...call, id: uniqueCallId(call, input.usedCallIds, deps.newId) }));
const collected: StepParts = { parts, weather: [], knownPlaceIds: turn.knownPlaceIds, cards: 0 };
const collected: StepParts = { parts, weather: [], knownPlaceIds: turn.knownPlaceIds, cards: 0, images: new Map() };
const held = await runCalls(turn, calls, collected);
// One weather strip per step, whatever the step held: it is told before the changes.
const weather = weatherOf(collected.weather);
@@ -403,7 +491,7 @@ async function runStep(turn: Turn, step: number): Promise<AgentOutcome | null> {
return outcomeOf(turn, 'aborted');
}
if (held.length > 0) return holdChanges(turn, rowId, { parts, providerState }, held);
await carryOn(turn, rowId, { parts, providerState }, text, calls);
await carryOn(turn, rowId, { parts, providerState }, { text, calls, images: collected.images });
return null;
}
@@ -428,12 +516,13 @@ async function stepsFrom(turn: Turn, step: number): Promise<AgentOutcome> {
* before its held changes are announced, so a card the client shows always
* exists on the server.
*/
export function runAgentLoop(
export async function runAgentLoop(
deps: AgentDeps,
input: AgentInput,
w: UiStreamWriter,
signal: AbortSignal,
): Promise<AgentOutcome> {
const history = deps.vision ? await deps.vision.afterApply(input.history) : [...input.history];
const knownPlaceIds = new Set(
[...deps.card.places.values()].flatMap((place) => (place.googlePlaceId ? [place.googlePlaceId] : [])),
);
@@ -442,7 +531,7 @@ export function runAgentLoop(
input,
w,
signal,
history: [...input.history],
history,
usage: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },
knownPlaceIds,
nudged: false,
@@ -0,0 +1,101 @@
import type { AiToolSpec } from '../ai-connections/ai-chat-client.interface';
import type { AgentToolPort, AgentToolRun } from './assistant-agent';
import { PREVIEW_BOOK_PAGE_TOOL } from './assistant-tools.constants';
import type { TurnVision } from './assistant-vision';
import { ASSISTANT_PAGE_IMAGE, previewBookPageRequestSchema } from '@trek/shared';
/**
* `preview_book_page`, offered in every Studio turn beside the session's own
* tools (journey-studio.md 4.3, step 2): a read that answers one page in words
* with its findings, as it stands or as an `edit_book_page` with the given
* ops would leave it, and for a model that reads images the page as the
* Studio draws it (AssistantVision). Nothing is saved; the change itself is
* proposed afterwards like any other.
*
* Its `ops` take exactly the schema `edit_book_page` takes in this session,
* so a preview and the edit it checks are one shape. A session without that
* tool (a viewer's) previews pages as they stand. Previews are capped per
* step and per turn, since each can wait seconds for the Studio and costs a
* model an image.
*/
const EDIT_TOOL = 'edit_book_page';
const DESCRIPTION =
'Look at one page of the book before you change it or after: its elements, its findings (overlaps, words past ' +
'their frame, empty frames, low resolution, content in the fold) and, when your model reads images, the page as ' +
'the Studio draws it, with photos of other contributors left as empty frames. With ops (the same ops ' +
'edit_book_page takes) you see the page as that edit would leave it, without saving anything. Preview every ' +
'page you are about to change once, fix what the findings or the image show, then propose the edit. ' +
'With designId (from design_book) you see the page of that design draft instead of the book. ' +
`At most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} previews per step and ${ASSISTANT_PAGE_IMAGE.previewsPerTurn} ` +
'per turn.';
/** The draft a preview may look at instead of the book, by design_book's design_id. */
const DESIGN_ID = { type: 'string', pattern: '^[\\w-]{1,40}$', description: 'A design draft, by its design_id.' };
const TOO_MANY =
`Too many previews: at most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} in one step and ` +
`${ASSISTANT_PAGE_IMAGE.previewsPerTurn} in one turn. Propose the edit and let its card show the findings.`;
/** The preview's spec, its ops taken from the session's `edit_book_page` when it has that tool. */
function previewSpec(specs: readonly AiToolSpec[]): AiToolSpec {
const edit = specs.find((spec) => spec.name === EDIT_TOOL);
const properties = (edit?.parameters.properties ?? {}) as Record<string, unknown>;
const ops = properties.ops;
// Shared parts the ops point at, where the schema keeps them apart.
const shared: Record<string, unknown> = {};
for (const key of ['$defs', 'definitions']) if (edit?.parameters[key]) shared[key] = edit.parameters[key];
return {
name: PREVIEW_BOOK_PAGE_TOOL,
description: DESCRIPTION,
parameters: {
type: 'object',
properties: {
spreadId: { type: 'string', pattern: '^[\\w-]{1,40}$', description: 'The page, by its id from get_book.' },
// A design draft is an editor's: a session without the edit tool previews the book only.
...(ops ? { ops, designId: DESIGN_ID } : {}),
},
required: ['spreadId'],
additionalProperties: false,
...(ops ? shared : {}),
},
};
}
/** The session's tools with the preview beside them, answered through the turn's vision. */
export function withPagePreview(tools: AgentToolPort, vision: TurnVision): AgentToolPort {
let inStep = 0;
let inTurn = 0;
const preview = async (args: Record<string, unknown>): Promise<AgentToolRun> => {
if (inStep >= ASSISTANT_PAGE_IMAGE.previewsPerStep || inTurn >= ASSISTANT_PAGE_IMAGE.previewsPerTurn) {
return { ok: false, value: TOO_MANY };
}
const parsed = previewBookPageRequestSchema.safeParse(args);
if (!parsed.success) {
const issue = parsed.error.issues[0];
const detail = issue ? [issue.path.join('.'), issue.message].join(' ') : '';
return { ok: false, value: `Invalid arguments: ${detail}` };
}
inStep += 1;
inTurn += 1;
const { spreadId, ops, designId } = parsed.data;
return designId ? vision.look(spreadId, ops, designId) : vision.look(spreadId, ops);
};
return {
// The loop asks for the specs once at the start of every step: a new step may preview again.
specs: () => {
inStep = 0;
const listed = tools.specs();
return [...listed, previewSpec(listed)];
},
kindOf: (name) => (name === PREVIEW_BOOK_PAGE_TOOL ? 'read' : tools.kindOf(name)),
pinArgs: (name, args) => {
if (name !== PREVIEW_BOOK_PAGE_TOOL) return tools.pinArgs(name, args);
// The journey is the conversation's; the preview takes no other argument for it.
const { journeyId: _journeyId, ...rest } = args;
return { args: rest };
},
call: (name, args) => (name === PREVIEW_BOOK_PAGE_TOOL ? preview(args) : tools.call(name, args)),
};
}
@@ -0,0 +1,84 @@
/**
* The Studio page images a running turn waits for (journey-studio.md 3.1), as
* an injectable port. The turn streams a `data-trek-render-request` and waits
* here; the Studio tab that holds the stream draws the page and uploads it to
* the renders route, which hands it over. A turn waits a bounded time and
* stops waiting with its own abort; an upload nobody waits for (too late,
* another user's, never asked) is refused. The image lives in memory for that
* one hand-over: nothing here keeps it. In memory today, like the running
* turns themselves (AssistantStreamRegistry).
*/
/** A page image as the Studio uploaded it, checked by the renders route. */
export interface PageImage {
mimeType: 'image/jpeg' | 'image/png' | 'image/webp';
data: Buffer;
width: number;
height: number;
}
/** Whose request an upload answers: the user, their journey and thread, and the request's own id. */
interface RenderKey {
userId: number;
journeyId: number;
threadId: number;
requestId: string;
}
/** A request a turn streamed: whose it is, and the page and book version it asked for. */
export interface RenderWait extends RenderKey {
spreadId: string;
bookVersion: number;
}
/**
* What became of an upload: `taken` by the turn waiting for it, `unknown`
* when no turn of this user waits for that request, `mismatch` when it shows
* another page or version than the one asked for (the turn goes on waiting).
*/
type RenderDelivery = 'taken' | 'unknown' | 'mismatch';
export abstract class AssistantRenderRegistry {
/** The image of a streamed request, or null once `timeoutMs` passed or `signal` aborted. */
abstract wait(request: RenderWait, signal: AbortSignal, timeoutMs: number): Promise<PageImage | null>;
/** Hands an upload to the turn waiting for it. */
abstract deliver(key: RenderKey, page: { spreadId: string; bookVersion: number }, image: PageImage): RenderDelivery;
}
interface Waiting {
request: RenderWait;
settle: (image: PageImage | null) => void;
}
export class InMemoryAssistantRenderRegistry extends AssistantRenderRegistry {
private readonly waiting = new Map<string, Waiting>();
wait(request: RenderWait, signal: AbortSignal, timeoutMs: number): Promise<PageImage | null> {
if (signal.aborted) return Promise.resolve(null);
return new Promise((resolve) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const settle = (image: PageImage | null) => {
clearTimeout(timer);
signal.removeEventListener('abort', onAbort);
if (this.waiting.get(request.requestId)?.settle === settle) this.waiting.delete(request.requestId);
resolve(image);
};
const onAbort = () => settle(null);
timer = setTimeout(() => settle(null), timeoutMs);
signal.addEventListener('abort', onAbort, { once: true });
this.waiting.set(request.requestId, { request, settle });
});
}
deliver(key: RenderKey, page: { spreadId: string; bookVersion: number }, image: PageImage): RenderDelivery {
const entry = this.waiting.get(key.requestId);
const asked = entry?.request;
if (!entry || !asked) return 'unknown';
if (asked.userId !== key.userId || asked.journeyId !== key.journeyId || asked.threadId !== key.threadId) {
return 'unknown';
}
if (asked.spreadId !== page.spreadId || asked.bookVersion !== page.bookVersion) return 'mismatch';
entry.settle(image);
return 'taken';
}
}
@@ -0,0 +1,123 @@
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonsService } from '../addons/addons.service';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { readImageHeader } from '../common/image-header';
import { isManagedBlocked, MANAGED_FORBIDDEN_ERROR, ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service';
import { AssistantBookContext } from './assistant-book-context';
import { AssistantRenderRegistry } from './assistant-render.registry';
import { AssistantRenderUploadDto } from './assistant.dto';
import {
Body,
Controller,
HttpCode,
HttpException,
Param,
Post,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
ASSISTANT_PAGE_IMAGE,
assistantRenderUploadResponseSchema,
drawnPhotoIdsOf,
type AssistantRenderUploadResponse,
} from '@trek/shared';
import { memoryStorage } from 'multer';
const UPLOAD = {
storage: memoryStorage(),
limits: { fileSize: ASSISTANT_PAGE_IMAGE.maxBytes, files: 1 },
};
/** A positive integer route id, or null. */
function routeId(value: string): number | null {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* `POST /api/journeys/:journeyId/assistant/threads/:threadId/renders/:requestId`:
* the Studio page a running turn asked for (journey-studio.md 3.1), drawn by
* the Studio tab that holds the turn's stream and uploaded as one image in
* the field `image`.
*
* It takes a multipart upload, so the addons, the managed install and the
* journey are checked in the handler, as for a file in the trip chat
* (AssistantAttachmentsController): a guard would answer before multer read
* the body. Then the image itself (at most 1 MB by multer, a JPEG, PNG or
* WebP by its first bytes, at most 2048 px on its long edge and 4 MP), the
* photos it says it shows (only the user's own, JourneyAiPhotosService), and
* that a turn of this user on this journey and thread still waits for exactly
* this page and version. The bytes go on as received, decoded by nobody here,
* and are kept nowhere.
*/
@Controller('api/journeys/:journeyId/assistant')
@UseGuards(JwtAuthGuard)
export class AssistantRendersController {
constructor(
private readonly registry: AssistantRenderRegistry,
private readonly books: AssistantBookContext,
private readonly photos: JourneyAiPhotosService,
private readonly addons: AddonsService,
private readonly env: RuntimeEnvService,
) {}
@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it', {
enforcedInHandler: true,
})
@Post('threads/:threadId/renders/:requestId')
@HttpCode(200)
@ResponseContract(assistantRenderUploadResponseSchema)
@UseInterceptors(FileInterceptor('image', UPLOAD))
async upload(
@CurrentUser() user: User,
@Param('journeyId') journeyParam: string,
@Param('threadId') threadParam: string,
@Param('requestId') requestId: string,
@UploadedFile() file: Express.Multer.File | undefined,
@Body() body: AssistantRenderUploadDto,
): Promise<AssistantRenderUploadResponse> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT))) {
throw new HttpException({ error: 'AI assistant addon is not enabled' }, 404);
}
if (isManagedBlocked(this.env)) throw new HttpException(MANAGED_FORBIDDEN_ERROR, 403);
if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) {
throw new HttpException({ error: 'Journey addon is not enabled' }, 404);
}
const journeyId = routeId(journeyParam);
if (journeyId === null || !(await this.books.canOpen(user.id, journeyId))) {
throw new HttpException({ error: 'Journey not found' }, 404);
}
const threadId = routeId(threadParam);
if (threadId === null) throw new HttpException({ error: 'No page was asked for' }, 404);
if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
const header = readImageHeader(file.buffer);
if (!header) throw new HttpException({ error: 'The upload is not a JPEG, PNG or WebP image' }, 415);
const { maxEdge, maxPixels } = ASSISTANT_PAGE_IMAGE;
if (Math.max(header.width, header.height) > maxEdge || header.width * header.height > maxPixels) {
throw new HttpException({ error: `The image is larger than ${maxEdge} px or ${maxPixels / 1_000_000} MP` }, 413);
}
const own = await this.photos.ownPhotoIds(journeyId, user.id);
if (drawnPhotoIdsOf(body.drawnPhotoIds).some((photoId) => !own.has(photoId))) {
throw new HttpException({ error: 'The image shows a photo another member contributed' }, 403);
}
const delivered = this.registry.deliver(
{ userId: user.id, journeyId, threadId, requestId },
{ spreadId: body.spreadId, bookVersion: body.bookVersion },
{ mimeType: header.mimeType, data: file.buffer, width: header.width, height: header.height },
);
if (delivered === 'unknown') throw new HttpException({ error: 'No page was asked for' }, 404);
if (delivered === 'mismatch') {
throw new HttpException({ error: 'The image shows another page or version than the one asked for' }, 409);
}
return { accepted: true };
}
}
@@ -0,0 +1,291 @@
import type { AiChatMessage, AiImage } from '../ai-connections/ai-chat-client.interface';
import { AiConnectionsService } from '../ai-connections/ai-connections.service';
import type { ResolvedAiConnection } from '../ai-connections/ai-connections.types';
import { modelReadsImages } from '../ai-connections/model-catalog.service';
import { logDebug } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { withRequestContext } from '../database/request-context';
import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service';
import { JourneyBookEditService, type BookTrialBase } from '../journey/journey-book-edit.service';
import type { AgentToolPort, AgentToolRun, AgentVision } from './assistant-agent';
import { withPagePreview } from './assistant-book-preview';
import { AssistantRenderRegistry, type PageImage } from './assistant-render.registry';
import type { UiStreamWriter } from './ui-stream.writer';
import { MikroORM } from '@mikro-orm/core';
import { Injectable } from '@nestjs/common';
import {
applyBookOps,
ASSISTANT_PAGE_IMAGE,
bookWriteResultSchema,
describeSpread,
type AssistantPageView,
type AssistantScope,
type BookDocument,
type BookElement,
type BookPageOp,
} from '@trek/shared';
import { randomUUID } from 'node:crypto';
/**
* The Studio assistant looking at a page (journey-studio.md 3): the page in
* words for every model, and for a model that reads images the page as the
* Studio draws it. The server cannot draw a page, so a look streams a render
* request to the Studio tab that holds the turn and waits a bounded time for
* its upload (AssistantRenderRegistry); no image in time is the description
* alone, never an error.
*
* Images go only when all of this holds for the turn: the client draws pages
* (the Studio's chat says so with `renders`), the model reads images (by its
* kind and id, and not refused one before in this process), and the user let
* this connection receive page images (their Studio acknowledgement). Only the
* user's own photos are drawn; the others go as empty frames, before anything
* is rasterised, and the description says so. Nothing of an image is stored:
* the message keeps what was looked at (`data-trek-page-view`), the bytes live
* for the turn's next model request.
*/
/** One Studio turn's view of its pages. */
export interface TurnVision extends AgentVision {
/** Whether this turn sends page images to the model, as of now. */
sendsImages(): boolean;
/**
* One page as it stands or, with `ops`, as an `edit_book_page` with them
* would leave it, nothing saved; with `designId` the page of that design
* draft (design_book) instead of the book's.
*/
look(spreadId: string, ops?: BookPageOp[], designId?: string): Promise<AgentToolRun>;
}
/** What a Studio turn brings to its pages. */
export interface VisionTurnInput {
userId: number;
journeyId: number;
threadId: number;
connection: Pick<ResolvedAiConnection, 'kind' | 'model' | 'host'>;
/** The client draws pages for this turn (the Studio's chat). */
renders: boolean;
w: UiStreamWriter;
signal: AbortSignal;
}
const NO_BOOK = 'This journey has no book yet: create_book makes one.';
const LATE = 'The Studio did not send the page image in time; check the page on its description.';
/** A page image as a model request carries it. */
function asAiImage(image: PageImage): AiImage {
return { mimeType: image.mimeType, data: image.data.toString('base64') };
}
/** The photos an element shows: a photo frame's own, and the pictures a map draws its stops with. */
function photosOf(el: BookElement): number[] {
if (el.kind === 'photo') return el.photoId === null ? [] : [el.photoId];
if (el.kind === 'map') return el.points.flatMap((point) => (point.photoId === null ? [] : [point.photoId]));
return [];
}
/** The photos on a page that the user did not contribute: drawn as empty frames (or plain map stops). */
function hiddenOn(doc: BookDocument, spreadId: string, own: ReadonlySet<number>): number[] {
const spread = doc.spreads.find((s) => s.id === spreadId);
const ids = new Set<number>();
for (const el of spread?.elements ?? []) {
for (const photoId of photosOf(el)) if (!own.has(photoId)) ids.add(photoId);
}
return [...ids];
}
/** The page a successful book write left, from its answer as the model read it; null for anything else. */
function writtenPage(message: AiChatMessage): string | null {
if (message.role !== 'tool' || message.isError) return null;
let parsed: unknown;
try {
parsed = JSON.parse(message.output);
} catch {
return null;
}
const result = bookWriteResultSchema.safeParse(parsed);
return result.success ? (result.data.spread_ids[0] ?? null) : null;
}
/** The page as a proposed edit would leave it (the stored one without ops), or why the book refuses the edit. */
function pageAfter(
doc: BookDocument,
spreadId: string,
ops: BookPageOp[] | undefined,
base: BookTrialBase,
): BookDocument | string {
if (!ops) return doc;
const made = applyBookOps(doc, { spreadId, ops }, base.ctx);
if (made.ok) return made.doc;
const at = made.error.opIndex === null ? '' : ` (operation ${made.error.opIndex})`;
return `Not a change the book takes${at}: ${made.error.code}: ${made.error.message}`;
}
/** What the message keeps of a look: the page, the version, the image's size when one came, the description. */
function viewOf(spreadId: string, bookVersion: number, text: string, image: PageImage | null): AssistantPageView {
return {
spreadId,
bookVersion,
width: image?.width ?? null,
height: image?.height ?? null,
bytes: image ? image.data.length : null,
description: text.slice(0, 20_000),
};
}
/** Why a look found nothing, in the words a tool would answer. */
function reason(err: unknown): string {
if (err instanceof DomainError) return err.mcpMessage ?? err.publicMessage;
return err instanceof Error ? err.message : String(err);
}
/** Builds each Studio turn's vision, and remembers the models a provider refused an image for. */
@Injectable()
export class AssistantVision {
constructor(
private readonly connections: AiConnectionsService,
private readonly books: JourneyBookEditService,
private readonly photos: JourneyAiPhotosService,
private readonly registry: AssistantRenderRegistry,
private readonly orm: MikroORM,
) {}
/** `kind:model` of the models a provider refused an image for, while this process runs. */
private readonly textOnly = new Set<string>();
/** A turn's tools and its vision: a Studio turn's with the page preview beside them, a trip turn's as they are. */
async turnTools(
scope: AssistantScope,
session: AgentToolPort,
input: Omit<VisionTurnInput, 'journeyId'>,
): Promise<{ tools: AgentToolPort; vision: TurnVision | null }> {
if (scope.kind !== 'journey') return { tools: session, vision: null };
const vision = await this.forTurn({ ...input, journeyId: scope.journeyId });
return { tools: withPagePreview(session, vision), vision };
}
async forTurn(input: VisionTurnInput): Promise<TurnVision> {
const model = `${input.connection.kind}:${input.connection.model}`;
let images =
input.renders &&
modelReadsImages(input.connection.kind, input.connection.model) &&
!this.textOnly.has(model) &&
(await withRequestContext(this.orm, () => this.connections.studioImagesAcked(input.userId, input.connection)));
const vision: TurnVision = {
sendsImages: () => images,
look: (spreadId, ops, designId) => this.look(input, images, spreadId, { ops, designId }),
refused: () => {
images = false;
this.textOnly.add(model);
},
afterApply: (history) => (images ? this.afterApply(vision, history) : Promise.resolve([...history])),
};
return vision;
}
/**
* The history a decision's turn starts from, with a view of each page the
* applied book writes left attached to the write's own answer (4.3, step
* 3), so the model checks what the user took before it goes on. At most as
* many as one request carries, one image each, the same page once.
*/
private async afterApply(vision: TurnVision, history: readonly AiChatMessage[]): Promise<AiChatMessage[]> {
const out = [...history];
let start = out.length;
while (start > 0 && out[start - 1]?.role === 'tool') start--;
const seen = new Set<string>();
const targets: Array<{ index: number; spreadId: string }> = [];
for (let index = out.length - 1; index >= start && targets.length < ASSISTANT_PAGE_IMAGE.perRequest; index--) {
const message = out[index];
const spreadId = message ? writtenPage(message) : null;
if (spreadId && !seen.has(spreadId)) {
seen.add(spreadId);
targets.push({ index, spreadId });
}
}
// One after another: the Studio draws one page at a time.
await targets.reduce<Promise<void>>(async (previous, { index, spreadId }) => {
await previous;
const seenPage = await vision.look(spreadId);
const message = out[index];
if (seenPage.images?.length && message?.role === 'tool') out[index] = { ...message, images: seenPage.images };
}, Promise.resolve());
return out;
}
private async look(
input: VisionTurnInput,
withImage: boolean,
spreadId: string,
{ ops, designId }: { ops?: BookPageOp[]; designId?: string },
): Promise<AgentToolRun> {
let base: BookTrialBase;
let own: ReadonlySet<number> | null;
const { journeyId, userId } = input;
try {
// A draft's page is read from the draft at the version it was made against; the book's as it stands.
base = await withRequestContext(this.orm, () =>
designId ? this.books.trialBase(journeyId, userId, designId) : this.books.trialBase(journeyId, userId),
);
// Whose photos the image may show; the journey can have gone away since the turn began.
own = withImage
? await withRequestContext(this.orm, () => this.photos.ownPhotoIds(input.journeyId, input.userId))
: null;
} catch (err) {
return { ok: false, value: reason(err) };
}
if (!base.doc || base.version === null) return { ok: false, value: NO_BOOK };
const doc = pageAfter(base.doc, spreadId, ops, base);
if (typeof doc === 'string') return { ok: false, value: doc };
const hidden = own ? hiddenOn(doc, spreadId, own) : [];
// A page naming more photos than a render request may list is checked on its description alone.
const draws = withImage && hidden.length <= ASSISTANT_PAGE_IMAGE.maxPagePhotos;
const photos = (base.ctx.photos ?? []).map((p) => (hidden.includes(p.photoId) ? { ...p, hidden: true } : p));
const described = describeSpread(doc, spreadId, photos);
if (!described) return { ok: false, value: `This book has no page ${spreadId}: get_book lists its pages.` };
const image = draws
? await this.render(input, { spreadId, bookVersion: base.version, ops, designId, hidden })
: null;
const value = {
spreadId,
index: described.index,
role: described.role,
proposed: !!ops,
description: described.text,
findings: described.findings,
...(withImage ? { image: image ? 'The page as the Studio draws it is attached.' : LATE } : {}),
};
const view = viewOf(spreadId, base.version, described.text, image);
return { ok: true, value, view, ...(image ? { images: [asAiImage(image)] } : {}) };
}
/** Asks the Studio tab for the page and waits for it; null when none came in time or the turn stopped. */
private async render(
input: VisionTurnInput,
page: { spreadId: string; bookVersion: number; ops?: BookPageOp[]; designId?: string; hidden: number[] },
): Promise<PageImage | null> {
const requestId = randomUUID();
const { userId, journeyId, threadId, signal } = input;
const { spreadId, bookVersion, ops, designId, hidden } = page;
// Waiting before asking: an upload that comes back at once finds its turn.
const waiting = this.registry.wait(
{ userId, journeyId, threadId, requestId, spreadId, bookVersion },
signal,
ASSISTANT_PAGE_IMAGE.timeoutMs,
);
// A draft's page: the Studio draws it from the draft (GET .../book-designs/:designId).
const asked = {
requestId,
threadId,
spreadId,
bookVersion,
hiddenPhotoIds: hidden,
...(designId ? { designId } : {}),
};
input.w.renderRequest(ops ? { ...asked, ops } : asked);
const image = await waiting;
// Size and dimensions only: the page shows the user's photos.
if (image) logDebug(`[assistant] page image ${image.width}x${image.height}, ${image.data.length} bytes`);
return image;
}
}
@@ -6,6 +6,8 @@ import {
type AssistantCard,
type AssistantChangePreview,
type AssistantErrorCode,
type AssistantPageRender,
type AssistantPageView,
type AssistantPlaces,
type AssistantWeather,
type UiStreamChunk,
@@ -108,6 +110,17 @@ export class UiStreamWriter {
this.send({ type: 'data-trek-activity', data: activity, transient: true });
}
/** A Studio page the turn asks the Studio tab to draw and upload; only streamed, the message never keeps it. */
renderRequest(request: AssistantPageRender): void {
this.endText();
this.send({ type: 'data-trek-render-request', data: request, transient: true });
}
/** A Studio page the turn looked at: what it was and its description, never the image. */
pageView(view: AssistantPageView): void {
this.send({ type: 'data-trek-page-view', data: view });
}
quota(used: number, limit: number): void {
this.send({ type: 'data-trek-quota', data: { used, limit } });
}
+86
View File
@@ -0,0 +1,86 @@
/**
* What an image is and how large, read from its first bytes without decoding
* it. Shared by the domains that take an image from outside and must check it
* before anything decodes or sends it: the photo imports of AI parsing and
* the Studio page images the assistant hands a model.
*/
export interface ImageHeader {
mimeType: 'image/png' | 'image/jpeg' | 'image/webp';
width: number;
height: number;
}
/** JPEG start-of-frame markers: every SOFn except DHT (C4), JPG (C8) and DAC (CC). */
function isStartOfFrame(marker: number): boolean {
return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
}
function jpegSize(data: Buffer): { width: number; height: number } | null {
let i = 2;
while (i + 4 <= data.length) {
// Stray bytes between segments, which some cameras write, are stepped over.
if (data[i] !== 0xff) {
i += 1;
continue;
}
const marker = data[i + 1];
// Fill bytes, and the markers that carry no length.
if (marker === 0xff) {
i += 1;
continue;
}
if (marker === 0x01 || marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
i += 2;
continue;
}
// The scan or the end came before any frame header.
if (marker === 0xd9 || marker === 0xda) return null;
const length = data.readUInt16BE(i + 2);
if (length < 2) return null;
if (isStartOfFrame(marker)) {
if (i + 9 > data.length) return null;
return { height: data.readUInt16BE(i + 5), width: data.readUInt16BE(i + 7) };
}
i += 2 + length;
}
return null;
}
function webpSize(data: Buffer): { width: number; height: number } | null {
const chunk = data.toString('latin1', 12, 16);
if (chunk === 'VP8 ' && data.length >= 30) {
return { width: data.readUInt16LE(26) & 0x3fff, height: data.readUInt16LE(28) & 0x3fff };
}
if (chunk === 'VP8L' && data.length >= 25) {
const bits = data.readUInt32LE(21);
return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
}
if (chunk === 'VP8X' && data.length >= 30) {
return { width: data.readUIntLE(24, 3) + 1, height: data.readUIntLE(27, 3) + 1 };
}
return null;
}
/**
* PNG from IHDR, JPEG from its frame header, WebP from its VP8, VP8L or VP8X
* chunk. Null when the bytes are none of the three, or do not say.
*/
export function readImageHeader(data: Buffer): ImageHeader | null {
let found: ImageHeader | null = null;
if (data.length >= 24 && data.readUInt32BE(0) === 0x89504e47 && data.toString('latin1', 12, 16) === 'IHDR') {
found = { mimeType: 'image/png', width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
} else if (data.length >= 4 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
const size = jpegSize(data);
found = size && { mimeType: 'image/jpeg', ...size };
} else if (
data.length >= 16 &&
data.toString('latin1', 0, 4) === 'RIFF' &&
data.toString('latin1', 8, 12) === 'WEBP'
) {
const size = webpSize(data);
found = size && { mimeType: 'image/webp', ...size };
}
// A zero edge is a header that defers its size (a JPEG's DNL), which says nothing.
return found && found.width > 0 && found.height > 0 ? found : null;
}
@@ -97,11 +97,19 @@ export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'AssistantController.thread',
'AssistantController.threads',
'AssistantController.undo',
'AssistantRendersController.upload',
'AuthController.createMcpToken',
'AuthController.validateKeys',
'BackupController.restore',
'BackupController.updateAutoSettings',
'BackupController.uploadRestore',
'JourneyAssistantController.chat',
'JourneyAssistantController.decide',
'JourneyAssistantController.deleteThread',
'JourneyAssistantController.stop',
'JourneyAssistantController.thread',
'JourneyAssistantController.threads',
'JourneyAssistantController.undo',
'LlmLocalController.models',
'LlmLocalController.pull',
'NotificationsController.testSmtp',
@@ -0,0 +1,35 @@
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
import { DomainError } from '../common/domain-error';
import { JourneyDomainService } from './journey-domain.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
/**
* Which photos of a journey's gallery the Studio assistant may show a model
* that reads images, for the user asking (journey-studio.md 3.4).
*
* TREK cannot tell who is in a photo; it knows who contributed it. So the
* rule is strict: only the photos the asking user contributed, as
* `trek_photos.owner_id` says, with the journey's owner standing in for a
* photo that names nobody (the fallback the photo proxy uses). Every other
* photo is drawn as an empty frame before the page is rasterised, and an
* uploaded page image that says it shows one is refused.
*/
@Injectable()
export class JourneyAiPhotosService {
constructor(
private readonly journey: JourneyDomainService,
@InjectRepository(JourneyPhotos) private readonly photosRepo: JourneyPhotosRepository,
) {}
/** The gallery photos the user contributed; refused like the journey routes for a journey they cannot open. */
async ownPhotoIds(journeyId: number, userId: number): Promise<Set<number>> {
const journey = await this.journey.canAccessJourney(journeyId, userId);
if (!journey) {
throw new DomainError(404, 'Journey not found', { mcpMessage: 'Journey not found or access denied.' });
}
const gallery = await this.photosRepo.galleryRead(journeyId);
return new Set(gallery.filter((p) => (p.owner_id || journey.user_id) === userId).map((p) => p.photo_id));
}
}
+1 -81
View File
@@ -1,3 +1,4 @@
import { readImageHeader } from '../common/image-header';
import { LLM_PHOTO_EXTENSIONS } from '@trek/shared';
import { Jimp } from 'jimp';
@@ -46,87 +47,6 @@ export const IMAGE_MAX_BYTES = Math.floor(3.5 * 1024 * 1024);
/** A photo TREK will not decode or send: the message says why, for the import's warning. */
export class ImageTooLargeError extends Error {}
export interface ImageHeader {
mimeType: 'image/png' | 'image/jpeg' | 'image/webp';
width: number;
height: number;
}
/** JPEG start-of-frame markers: every SOFn except DHT (C4), JPG (C8) and DAC (CC). */
function isStartOfFrame(marker: number): boolean {
return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
}
function jpegSize(data: Buffer): { width: number; height: number } | null {
let i = 2;
while (i + 4 <= data.length) {
// Stray bytes between segments, which some cameras write, are stepped over.
if (data[i] !== 0xff) {
i += 1;
continue;
}
const marker = data[i + 1];
// Fill bytes, and the markers that carry no length.
if (marker === 0xff) {
i += 1;
continue;
}
if (marker === 0x01 || marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
i += 2;
continue;
}
// The scan or the end came before any frame header.
if (marker === 0xd9 || marker === 0xda) return null;
const length = data.readUInt16BE(i + 2);
if (length < 2) return null;
if (isStartOfFrame(marker)) {
if (i + 9 > data.length) return null;
return { height: data.readUInt16BE(i + 5), width: data.readUInt16BE(i + 7) };
}
i += 2 + length;
}
return null;
}
function webpSize(data: Buffer): { width: number; height: number } | null {
const chunk = data.toString('latin1', 12, 16);
if (chunk === 'VP8 ' && data.length >= 30) {
return { width: data.readUInt16LE(26) & 0x3fff, height: data.readUInt16LE(28) & 0x3fff };
}
if (chunk === 'VP8L' && data.length >= 25) {
const bits = data.readUInt32LE(21);
return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
}
if (chunk === 'VP8X' && data.length >= 30) {
return { width: data.readUIntLE(24, 3) + 1, height: data.readUIntLE(27, 3) + 1 };
}
return null;
}
/**
* What a photo is and how large, read from its first bytes without decoding it:
* PNG from IHDR, JPEG from its frame header, WebP from its VP8, VP8L or VP8X
* chunk. Null when the bytes are none of the three, or do not say.
*/
export function readImageHeader(data: Buffer): ImageHeader | null {
let found: ImageHeader | null = null;
if (data.length >= 24 && data.readUInt32BE(0) === 0x89504e47 && data.toString('latin1', 12, 16) === 'IHDR') {
found = { mimeType: 'image/png', width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
} else if (data.length >= 4 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
const size = jpegSize(data);
found = size && { mimeType: 'image/jpeg', ...size };
} else if (
data.length >= 16 &&
data.toString('latin1', 0, 4) === 'RIFF' &&
data.toString('latin1', 8, 12) === 'WEBP'
) {
const size = webpSize(data);
found = size && { mimeType: 'image/webp', ...size };
}
// A zero edge is a header that defers its size (a JPEG's DNL), which says nothing.
return found && found.width > 0 && found.height > 0 ? found : null;
}
/** Bytes sent as they came, as long as a provider takes them at that size. */
function asTheyCame(data: Buffer, mimeType: string): { data: Buffer; mimeType: string } {
if (data.length > IMAGE_MAX_BYTES) {