feat(assistant): trip assistant chat with your own AI connection

Adds an in-app assistant that reads and plans the open trip. Users connect
their own provider (Sign in with ChatGPT, or an Anthropic, OpenAI, Gemini or
OpenRouter key) or use the one the admin set up, including a custom
OpenAI-compatible server. It is an addon and only shows while a connection
is usable.

The chat runs on the existing MCP tools, pinned to the trip. Every change is
held as a change card the user applies or discards, and applied changes can
be undone. On the desktop it is a floating window that can be moved and
resized; on the phone it is fullscreen. Search results show as place cards
that can go onto a day, weather lookups as a strip, proposed places as
ghost markers on the map with a before/after switch, and an answer can be
shared into the trip chat. Booking files can be dropped in and are read
into change cards.
This commit is contained in:
Maurice
2026-10-21 18:52:44 +02:00
parent 31859651d7
commit b64da26651
505 changed files with 51841 additions and 227 deletions
@@ -0,0 +1,55 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AiConnectionsRepository } from '../repositories/AiConnections.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class AiConnections {
[EntityRepositoryType]?: AiConnectionsRepository;
id!: number & Opt;
scope!: string;
user?: Ref<Users> | null;
user_id?: number | null;
kind!: string;
model!: string;
base_url?: string | null;
secrets?: string | null;
secrets_version: number & Opt = 0;
hint?: string | null;
account?: string | null;
status: string & Opt = 'ok';
created_at!: string & Opt;
updated_at!: string & Opt;
}
export const AiConnectionsSchema = defineEntity({
class: AiConnections,
repository: () => AiConnectionsRepository,
uniques: [
{
name: 'idx_ai_connections_instance',
where: 'user_id IS NULL',
properties: ['scope'],
},
{
name: 'idx_ai_connections_user',
where: 'user_id IS NOT NULL',
properties: ['user_id'],
},
],
properties: {
id: p.integer().primary(),
scope: p.text(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').nullable().hidden(),
user_id: p.integer().nullable().persist(false),
kind: p.text(),
model: p.text(),
base_url: p.text().nullable(),
secrets: p.text().nullable(),
secrets_version: p.integer().default(0),
hint: p.text().nullable(),
account: p.text().nullable(),
status: p.text().default('ok'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,37 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantMessagesRepository } from '../repositories/AssistantMessages.repository';
import { DbTimestampType } from '../types';
import { AssistantThreads } from './AssistantThreads.entity';
import { AssistantToolCalls } from './AssistantToolCalls.entity';
export class AssistantMessages {
[EntityRepositoryType]?: AssistantMessagesRepository;
id!: number & Opt;
thread!: Ref<AssistantThreads>;
thread_id!: number;
role!: string;
parts!: string;
provider_state?: string | null;
status: string & Opt = 'complete';
model?: string | null;
created_at!: string & Opt;
assistant_tool_calls_collection = new Collection<AssistantToolCalls>(this);
}
export const AssistantMessagesSchema = defineEntity({
class: AssistantMessages,
repository: () => AssistantMessagesRepository,
indexes: [{ name: 'idx_assistant_messages_thread', properties: ['thread_id', 'id'] }],
properties: {
id: p.integer().primary(),
thread: () => p.manyToOne(AssistantThreads).ref().deleteRule('cascade').hidden(),
thread_id: p.integer().persist(false),
role: p.text(),
parts: p.text(),
provider_state: p.text().nullable(),
status: p.text().default('complete'),
model: p.text().nullable(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
assistant_tool_calls_collection: () => p.oneToMany(AssistantToolCalls).mappedBy('message').hidden(),
},
});
@@ -0,0 +1,44 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantThreadsRepository } from '../repositories/AssistantThreads.repository';
import { DbTimestampType } from '../types';
import { AssistantMessages } from './AssistantMessages.entity';
import { AssistantToolCalls } from './AssistantToolCalls.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class AssistantThreads {
[EntityRepositoryType]?: AssistantThreadsRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
trip!: Ref<Trips>;
trip_id!: number;
title!: string;
created_at!: string & Opt;
last_message_at!: string & Opt;
assistant_messages_collection = new Collection<AssistantMessages>(this);
assistant_tool_calls_collection = new Collection<AssistantToolCalls>(this);
}
export const AssistantThreadsSchema = defineEntity({
class: AssistantThreads,
repository: () => AssistantThreadsRepository,
indexes: [
{
name: 'idx_assistant_threads_user_trip',
properties: ['user_id', 'trip_id', 'last_message_at'],
},
],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_assistant_threads_trip'),
trip_id: p.integer().persist(false).index('idx_assistant_threads_trip'),
title: p.text(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
last_message_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
assistant_messages_collection: () => p.oneToMany(AssistantMessages).mappedBy('thread').hidden(),
assistant_tool_calls_collection: () => p.oneToMany(AssistantToolCalls).mappedBy('thread').hidden(),
},
});
@@ -0,0 +1,46 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantToolCallsRepository } from '../repositories/AssistantToolCalls.repository';
import { DbTimestampType } from '../types';
import { AssistantMessages } from './AssistantMessages.entity';
import { AssistantThreads } from './AssistantThreads.entity';
export class AssistantToolCalls {
[EntityRepositoryType]?: AssistantToolCallsRepository;
id!: string;
thread!: Ref<AssistantThreads>;
thread_id!: number;
message!: Ref<AssistantMessages>;
message_id!: number;
provider_call_id!: string;
tool_name!: string;
args!: string;
preview!: string;
state: string & Opt = 'approval_requested';
result?: string | null;
undo_until?: string | null;
created_at!: string & Opt;
decided_at?: string | null;
}
export const AssistantToolCallsSchema = defineEntity({
class: AssistantToolCalls,
repository: () => AssistantToolCallsRepository,
uniques: [{ properties: ['thread', 'provider_call_id'] }],
properties: {
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_id: p.integer().persist(false).index('idx_assistant_tool_calls_message'),
provider_call_id: p.text(),
tool_name: p.text(),
args: p.text(),
preview: p.text(),
state: p.text().default('approval_requested'),
result: p.text().nullable(),
undo_until: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
decided_at: p.type(DbTimestampType).nullable(),
},
});
@@ -0,0 +1,30 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { AssistantUsageRepository } from '../repositories/AssistantUsage.repository';
import { Users } from './Users.entity';
export class AssistantUsage {
[EntityRepositoryType]?: AssistantUsageRepository;
[PrimaryKeyProp]?: ['user', 'day', 'paid_by'];
user!: Ref<Users>;
user_id!: number;
day!: string;
paid_by!: string;
turns: number & Opt = 0;
input_tokens: number & Opt = 0;
output_tokens: number & Opt = 0;
}
export const AssistantUsageSchema = defineEntity({
class: AssistantUsage,
repository: () => AssistantUsageRepository,
uniques: [{ properties: ['user', 'day', 'paid_by'] }],
properties: {
user: () => p.manyToOne(Users).primary().ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
day: p.text().primary(),
paid_by: p.text().primary(),
turns: p.integer().default(0),
input_tokens: p.integer().default(0),
output_tokens: p.integer().default(0),
},
});
@@ -17,6 +17,7 @@ export class CollabMessages {
reply_to?: number | null;
created_at?: string | null;
deleted?: number | null = 0;
origin?: string | null;
replyToRef?: Ref<CollabMessages> | null;
collab_message_reactions_collection = new Collection<CollabMessageReactions>(this);
collab_messages_collection = new Collection<CollabMessages>(this);
@@ -36,6 +37,7 @@ export const CollabMessagesSchema = defineEntity({
reply_to: p.integer().nullable().persist(false).index('idx_collab_messages_reply_to'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
deleted: p.integer().nullable(),
origin: p.text().nullable(),
replyToRef: () => p.manyToOne(CollabMessages).ref().joinColumn('reply_to').nullable().hidden().index('idx_collab_messages_reply_to'),
collab_message_reactions_collection: () => p.oneToMany(CollabMessageReactions).mappedBy('message').hidden(),
collab_messages_collection: () => p.oneToMany(CollabMessages).mappedBy('replyToRef').hidden(),
+3
View File
@@ -1,6 +1,7 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripsRepository } from '../repositories/Trips.repository';
import { DbTimestampType } from '../types';
import { AssistantThreads } from './AssistantThreads.entity';
import { BudgetCategoryOrder } from './BudgetCategoryOrder.entity';
import { BudgetItems } from './BudgetItems.entity';
import { BudgetSettlements } from './BudgetSettlements.entity';
@@ -55,6 +56,7 @@ export class Trips {
created_at?: string | null;
updated_at?: string | null;
reminder_sent_for?: string | null;
assistant_threads_collection = new Collection<AssistantThreads>(this);
budget_category_order_collection = new Collection<BudgetCategoryOrder>(this);
budget_items_collection = new Collection<BudgetItems>(this);
budget_settlements_collection = new Collection<BudgetSettlements>(this);
@@ -118,6 +120,7 @@ export const TripsSchema = defineEntity({
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`).index('idx_trips_created_at'),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
reminder_sent_for: p.text().nullable(),
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('trip').hidden(),
budget_category_order_collection: () => p.oneToMany(BudgetCategoryOrder).mappedBy('trip').hidden(),
budget_items_collection: () => p.oneToMany(BudgetItems).mappedBy('trip').hidden(),
budget_settlements_collection: () => p.oneToMany(BudgetSettlements).mappedBy('trip').hidden(),
+9
View File
@@ -1,7 +1,10 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { UsersRepository } from '../repositories/Users.repository';
import { DbTimestampType } from '../types';
import { AiConnections } from './AiConnections.entity';
import { AssignmentParticipants } from './AssignmentParticipants.entity';
import { AssistantThreads } from './AssistantThreads.entity';
import { AssistantUsage } from './AssistantUsage.entity';
import { AuditLog } from './AuditLog.entity';
import { BucketList } from './BucketList.entity';
import { BudgetItemMembers } from './BudgetItemMembers.entity';
@@ -129,7 +132,10 @@ export class Users {
display_name?: string | null;
immich_allow_insecure_tls: number & Opt = 0;
email_self_asserted: number & Opt = 0;
ai_connections_collection = new Collection<AiConnections>(this);
assignment_participants_collection = new Collection<AssignmentParticipants>(this);
assistant_threads_collection = new Collection<AssistantThreads>(this);
assistant_usage_collection = new Collection<AssistantUsage>(this);
audit_log_collection = new Collection<AuditLog>(this);
bucket_list_collection = new Collection<BucketList>(this);
budget_item_members_collection = new Collection<BudgetItemMembers>(this);
@@ -283,7 +289,10 @@ export const UsersSchema = defineEntity({
display_name: p.text().nullable(),
immich_allow_insecure_tls: p.integer().default(0),
email_self_asserted: p.integer().default(0),
ai_connections_collection: () => p.oneToMany(AiConnections).mappedBy('user').hidden(),
assignment_participants_collection: () => p.oneToMany(AssignmentParticipants).mappedBy('user').hidden(),
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('user').hidden(),
assistant_usage_collection: () => p.oneToMany(AssistantUsage).mappedBy('user').hidden(),
audit_log_collection: () => p.oneToMany(AuditLog).mappedBy('user').hidden(),
bucket_list_collection: () => p.oneToMany(BucketList).mappedBy('user').hidden(),
budget_item_members_collection: () => p.oneToMany(BudgetItemMembers).mappedBy('user').hidden(),
+10
View File
@@ -1,7 +1,12 @@
import type { EntitySchema } from '@mikro-orm/core';
import { AddonsSchema } from './Addons.entity';
import { AiConnectionsSchema } from './AiConnections.entity';
import { AppSettingsSchema } from './AppSettings.entity';
import { AssignmentParticipantsSchema } from './AssignmentParticipants.entity';
import { AssistantMessagesSchema } from './AssistantMessages.entity';
import { AssistantThreadsSchema } from './AssistantThreads.entity';
import { AssistantToolCallsSchema } from './AssistantToolCalls.entity';
import { AssistantUsageSchema } from './AssistantUsage.entity';
import { AuditLogSchema } from './AuditLog.entity';
import { BucketListSchema } from './BucketList.entity';
import { BudgetCategoryOrderSchema } from './BudgetCategoryOrder.entity';
@@ -155,8 +160,13 @@ import { WebauthnCredentialsSchema } from './WebauthnCredentials.entity';
export const ALL_ENTITIES: readonly EntitySchema[] = [
AddonsSchema,
AiConnectionsSchema,
AppSettingsSchema,
AssignmentParticipantsSchema,
AssistantMessagesSchema,
AssistantThreadsSchema,
AssistantToolCallsSchema,
AssistantUsageSchema,
AuditLogSchema,
BucketListSchema,
BudgetCategoryOrderSchema,
+71
View File
@@ -2,6 +2,8 @@ import type { JsonColumn } from '../utils/json-column';
import {
FERRATAS_RESULT_CAP,
dawarichTrackSegmentSchema,
assistantChangePreviewSchema,
assistantMessagePartSchema,
ferrataSchema,
hikingPreferencesSchema,
obstacleSnapshotSchema,
@@ -17,6 +19,8 @@ import {
tourWaypointSchema,
trackMarksSchema,
type DawarichTrackSegment,
type AssistantChangePreview,
type AssistantMessagePart,
type Ferrata,
type GeometryPoint,
type HikingPreferences,
@@ -328,3 +332,70 @@ export const JOURNEY_RECORDED_DAY_SEGMENTS: JsonColumn<DawarichTrackSegment[]> =
schema: z.array(dawarichTrackSegmentSchema),
fallback: () => [],
};
* The parts of an assistant message as the client renders them: text, tool
* calls with their results and approvals, change previews and receipts. A
* broken row reads as an empty message and is logged.
*/
export const ASSISTANT_MESSAGE_PARTS: JsonColumn<AssistantMessagePart[]> = {
column: 'assistant_messages.parts',
schema: z.array(assistantMessagePartSchema),
fallback: () => [],
};
/**
* What a provider needs replayed as it sent it, when its history cannot be
* rebuilt from the parts: the Responses API's output items (reasoning with its
* encrypted content, function calls) for a conversation that stores nothing on
* the provider's side. A broken row reads as none, and the history is rebuilt
* from the parts instead.
*/
const aiProviderStateSchema = z.object({
adapter: z.literal('openai-responses'),
items: z.array(z.record(z.string(), z.unknown())),
});
export type AiProviderState = z.infer<typeof aiProviderStateSchema>;
export const ASSISTANT_PROVIDER_STATE: JsonColumn<AiProviderState | null> = {
column: 'assistant_messages.provider_state',
schema: aiProviderStateSchema.nullable(),
fallback: () => null,
};
/** The arguments a proposed change runs with once approved, as the model sent them. A broken row runs nothing. */
export const ASSISTANT_TOOL_ARGS: JsonColumn<Record<string, unknown>> = {
column: 'assistant_tool_calls.args',
schema: z.record(z.string(), z.unknown()),
fallback: () => ({}),
};
/** The change card of a proposed change. A broken row reads as none. */
export const ASSISTANT_TOOL_PREVIEW: JsonColumn<AssistantChangePreview | null> = {
column: 'assistant_tool_calls.preview',
schema: assistantChangePreviewSchema.nullable(),
fallback: () => null,
};
/** What an executed change answered, the tool's own result. A broken row reads as none, which offers no undo. */
export const ASSISTANT_TOOL_RESULT: JsonColumn<unknown> = {
column: 'assistant_tool_calls.result',
schema: z.unknown(),
fallback: () => null,
};
/**
* What a ChatGPT sign-in leaves that is not secret: the client id issued to
* this user's registration, the account's subject and the scopes granted. A
* broken row reads as none, so the next sign-in registers afresh.
*/
const aiConnectionAccountSchema = z.object({
clientId: z.string().optional(),
sub: z.string().optional(),
scopes: z.array(z.string()).optional(),
});
export type AiConnectionAccount = z.infer<typeof aiConnectionAccountSchema>;
export const AI_CONNECTION_ACCOUNT: JsonColumn<AiConnectionAccount> = {
column: 'ai_connections.account',
schema: aiConnectionAccountSchema,
fallback: () => ({}),
};
@@ -0,0 +1,19 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface AiConnectionsTable {
id: InsertOptional<number>;
scope: string;
user_id: InsertOptional<number | null>;
kind: string;
model: string;
base_url: InsertOptional<string | null>;
secrets: InsertOptional<string | null>;
secrets_version: InsertOptional<number>;
hint: InsertOptional<string | null>;
account: InsertOptional<string | null>;
status: InsertOptional<string>;
created_at: InsertOptional<string>;
updated_at: InsertOptional<string>;
}
@@ -0,0 +1,14 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface AssistantMessagesTable {
id: InsertOptional<number>;
thread_id: number;
role: string;
parts: string;
provider_state: InsertOptional<string | null>;
status: InsertOptional<string>;
model: InsertOptional<string | null>;
created_at: InsertOptional<string>;
}
@@ -0,0 +1,12 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface AssistantThreadsTable {
id: InsertOptional<number>;
user_id: number;
trip_id: number;
title: string;
created_at: InsertOptional<string>;
last_message_at: InsertOptional<string>;
}
@@ -0,0 +1,18 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface AssistantToolCallsTable {
id: string;
thread_id: number;
message_id: number;
provider_call_id: string;
tool_name: string;
args: string;
preview: string;
state: InsertOptional<string>;
result: InsertOptional<string | null>;
undo_until: InsertOptional<string | null>;
created_at: InsertOptional<string>;
decided_at: InsertOptional<string | null>;
}
@@ -0,0 +1,12 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface AssistantUsageTable {
user_id: number;
day: string;
paid_by: string;
turns: InsertOptional<number>;
input_tokens: InsertOptional<number>;
output_tokens: InsertOptional<number>;
}
@@ -10,4 +10,5 @@ export interface CollabMessagesTable {
reply_to: InsertOptional<number | null>;
created_at: InsertOptional<string | null>;
deleted: InsertOptional<number | null>;
origin: InsertOptional<string | null>;
}
+10
View File
@@ -1,8 +1,13 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { AddonsTable } from './Addons.table';
import type { AiConnectionsTable } from './AiConnections.table';
import type { AppSettingsTable } from './AppSettings.table';
import type { AssignmentParticipantsTable } from './AssignmentParticipants.table';
import type { AssistantMessagesTable } from './AssistantMessages.table';
import type { AssistantThreadsTable } from './AssistantThreads.table';
import type { AssistantToolCallsTable } from './AssistantToolCalls.table';
import type { AssistantUsageTable } from './AssistantUsage.table';
import type { AuditLogTable } from './AuditLog.table';
import type { BucketListTable } from './BucketList.table';
import type { BudgetCategoryOrderTable } from './BudgetCategoryOrder.table';
@@ -162,8 +167,13 @@ import type { WebauthnCredentialsTable } from './WebauthnCredentials.table';
/** Every table of the migrated schema. A repository narrows it: `this.kysely<Pick<DB, 'trips'>>()`. */
export interface DB {
addons: AddonsTable;
ai_connections: AiConnectionsTable;
app_settings: AppSettingsTable;
assignment_participants: AssignmentParticipantsTable;
assistant_messages: AssistantMessagesTable;
assistant_threads: AssistantThreadsTable;
assistant_tool_calls: AssistantToolCallsTable;
assistant_usage: AssistantUsageTable;
audit_log: AuditLogTable;
bucket_list: BucketListTable;
budget_category_order: BudgetCategoryOrderTable;
@@ -0,0 +1,52 @@
import { Migration } from '@mikro-orm/migrations';
/**
* The connections the trip assistant talks to a language model through: at most
* one the admin sets up for everyone (`scope = 'instance'`, no user) and at most
* one per user (`scope = 'user'`).
*
* `secrets` is one encrypted JSON blob (an API key, or ChatGPT's access and
* refresh tokens), rotated as a whole by scripts/migrate-encryption.ts, and
* `secrets_version` counts its writes so a token refresh can replace it only if
* nobody else did in between. `account` holds what a sign-in leaves that is not
* secret (ChatGPT's issued client id, the account's subject and scopes), so a
* signed-out connection can sign in again as the same registration. `hint` is
* what the settings show instead of the secret.
*
* Two kinds are bound to one side: a ChatGPT plan is personal and never the
* instance connection, and a custom base URL (an Ollama in the LAN, say) is
* only ever the admin's (#1772). The checks refuse the other combinations.
*/
export class Migration20200101046200_a_user_can_connect_an_ai_provider extends Migration {
override name = 'Migration20200101046200_a_user_can_connect_an_ai_provider';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS ai_connections (
id INTEGER PRIMARY KEY,
scope TEXT NOT NULL CHECK(scope IN ('instance', 'user')),
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK(kind IN ('anthropic', 'openai', 'gemini', 'openrouter', 'chatgpt', 'custom')),
model TEXT NOT NULL,
base_url TEXT,
secrets TEXT,
secrets_version INTEGER NOT NULL DEFAULT 0,
hint TEXT,
account TEXT,
status TEXT NOT NULL DEFAULT 'ok' CHECK(status IN ('ok', 'needs_reauth', 'signed_out', 'error')),
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK((scope = 'user') = (user_id IS NOT NULL)),
CHECK(kind <> 'chatgpt' OR scope = 'user'),
CHECK(kind <> 'custom' OR (scope = 'instance' AND base_url IS NOT NULL)),
CHECK(base_url IS NULL OR kind = 'custom')
)
`);
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_ai_connections_user ON ai_connections(user_id) WHERE user_id IS NOT NULL',
);
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_ai_connections_instance ON ai_connections(scope) WHERE user_id IS NULL',
);
}
}
@@ -0,0 +1,86 @@
import { Migration } from '@mikro-orm/migrations';
/**
* The trip assistant's memory: one user's conversations about one trip.
*
* `assistant_threads` belong to a user and a trip and go with either.
* `assistant_messages` keep each message's parts as the client renders them
* (`parts`, JSON) and, for providers whose history has to be replayed as they
* sent it, the provider's own items (`provider_state`, JSON).
*
* `assistant_tool_calls` are the changes the assistant proposed and the user
* decides on. The key is our own id, not the provider's: a provider's call id
* is only unique within its conversation (`UNIQUE(thread_id, provider_call_id)`).
* The arguments are stored when the change is proposed and are what runs on
* approval, never what a client sends back; `undo_until` is how long the
* counterpart of an executed change may still be run.
*
* `assistant_usage` counts turns and tokens per user, UTC day and payer, which
* is what the daily limit on the instance's connection is checked against.
*/
export class Migration20200101046210_the_trip_assistant_remembers_its_conversations extends Migration {
override name = 'Migration20200101046210_the_trip_assistant_remembers_its_conversations';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS assistant_threads (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
title TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_message_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_assistant_threads_user_trip ON assistant_threads(user_id, trip_id, last_message_at)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_threads_trip ON assistant_threads(trip_id)');
this.addSql(`
CREATE TABLE IF NOT EXISTS assistant_messages (
id INTEGER PRIMARY KEY,
thread_id INTEGER NOT NULL REFERENCES assistant_threads(id) ON DELETE CASCADE,
role TEXT NOT NULL CHECK(role IN ('user', 'assistant')),
parts TEXT NOT NULL,
provider_state TEXT,
status TEXT NOT NULL DEFAULT 'complete' CHECK(status IN ('complete', 'awaiting_approval', 'aborted', 'error')),
model TEXT,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_messages_thread ON assistant_messages(thread_id, id)');
this.addSql(`
CREATE TABLE IF NOT EXISTS assistant_tool_calls (
id TEXT PRIMARY KEY NOT NULL,
thread_id INTEGER NOT NULL REFERENCES assistant_threads(id) ON DELETE CASCADE,
message_id INTEGER NOT NULL REFERENCES assistant_messages(id) ON DELETE CASCADE,
provider_call_id TEXT NOT NULL,
tool_name TEXT NOT NULL,
args TEXT NOT NULL,
preview TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'approval_requested'
CHECK(state IN ('approval_requested', 'approved', 'rejected', 'executed', 'failed', 'expired', 'undone')),
result TEXT,
undo_until DATETIME,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
decided_at DATETIME,
UNIQUE(thread_id, provider_call_id)
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_tool_calls_message ON assistant_tool_calls(message_id)');
this.addSql(`
CREATE TABLE IF NOT EXISTS assistant_usage (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
day TEXT NOT NULL,
paid_by TEXT NOT NULL CHECK(paid_by IN ('instance', 'user')),
turns INTEGER NOT NULL DEFAULT 0,
input_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, day, paid_by)
)
`);
}
}
@@ -0,0 +1,16 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A trip chat message can say where it came from when nobody typed it in the
* chat: `'assistant'` for an answer of the trip assistant a member shared,
* which the chat marks as such in each reader's language. NULL, as on every
* message before, is one typed in the chat. Only the assistant's share sets
* it; the chat's own routes and tools never do.
*/
export class Migration20200101046220_a_chat_message_can_say_it_came_from_the_assistant extends Migration {
override name = 'Migration20200101046220_a_chat_message_can_say_it_came_from_the_assistant';
override up(): void {
this.addSql(`ALTER TABLE collab_messages ADD COLUMN origin TEXT`);
}
}
@@ -0,0 +1,178 @@
import { currentTimestampKysely } from '../dialect/kysely-functions';
import type { AiConnections } from '../entities/AiConnections.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/**
* One `ai_connections` row as stored. `secrets` is the still-encrypted blob and
* `account` the JSON text of AI_CONNECTION_ACCOUNT; the service opens both.
*/
export interface AiConnectionRow {
id: number;
scope: string;
user_id: number | null;
kind: string;
model: string;
base_url: string | null;
secrets: string | null;
secrets_version: number;
hint: string | null;
account: string | null;
status: string;
created_at: string;
updated_at: string;
}
const _aiConnectionRowKeys: AssertRowKeys<AiConnectionRow, AiConnections> = true;
/** What a save writes; the row's scope and owner are fixed by the call. */
interface AiConnectionWrite {
kind: string;
model: string;
baseUrl: string | null;
secrets: string | null;
hint: string | null;
account: string | null;
}
type AiConnectionsKyselyDB = Pick<DB, 'ai_connections'>;
const COLUMNS = [
'id',
'scope',
'user_id',
'kind',
'model',
'base_url',
'secrets',
'secrets_version',
'hint',
'account',
'status',
'created_at',
'updated_at',
] as const;
/**
* `ai_connections`: the instance's connection (no user) and one per user. A
* save replaces the row of its owner, so the partial unique indexes never see
* a second one; every write of `secrets` counts up `secrets_version`, which is
* what a token refresh compares against before it writes.
*/
export class AiConnectionsRepository extends TrekRepository<AiConnections> {
private db() {
return this.kysely<AiConnectionsKyselyDB>();
}
private now() {
return currentTimestampKysely(this.getEntityManager().getPlatform());
}
async findForUser(userId: number): Promise<AiConnectionRow | null> {
const row = await this.db()
.selectFrom('ai_connections')
.select(COLUMNS)
.where('user_id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
async findInstance(): Promise<AiConnectionRow | null> {
const row = await this.db()
.selectFrom('ai_connections')
.select(COLUMNS)
.where('scope', '=', 'instance')
.where('user_id', 'is', null)
.executeTakeFirst();
return row ?? null;
}
async findById(id: number): Promise<AiConnectionRow | null> {
const row = await this.db().selectFrom('ai_connections').select(COLUMNS).where('id', '=', id).executeTakeFirst();
return row ?? null;
}
/**
* Writes the connection of a user (`userId`) or of the instance (`null`):
* the first one is inserted, a later one replaces it in place (one statement,
* on the partial unique index that keeps it single) and is usable again.
*/
async save(userId: number | null, data: AiConnectionWrite): Promise<void> {
const columns = {
kind: data.kind,
model: data.model,
base_url: data.baseUrl,
secrets: data.secrets,
hint: data.hint,
account: data.account,
};
await this.db()
.insertInto('ai_connections')
.values({ scope: userId === null ? 'instance' : 'user', user_id: userId, ...columns })
.onConflict((oc) => {
const target =
userId === null
? oc.column('scope').where('user_id', 'is', null)
: oc.column('user_id').where('user_id', 'is not', null);
return target.doUpdateSet({
...columns,
secrets_version: (eb) => eb('secrets_version', '+', 1),
status: 'ok',
updated_at: () => this.now(),
});
})
.execute();
}
/**
* Writes refreshed secrets only if nobody wrote them since `expectedVersion`
* was read; false when somebody did, and the caller reads the row again.
*/
async replaceSecretsIfUnchanged(
id: number,
expectedVersion: number,
secrets: string | null,
account: string | null,
): Promise<boolean> {
const result = await this.db()
.updateTable('ai_connections')
.set({
secrets,
secrets_version: expectedVersion + 1,
account,
status: 'ok',
updated_at: this.now(),
})
.where('id', '=', id)
.where('secrets_version', '=', expectedVersion)
.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** Drops the secrets and leaves the connection in `status` (signed out, or waiting for a new sign-in). */
async clearSecrets(id: number, status: string): Promise<void> {
await this.db()
.updateTable('ai_connections')
.set((eb) => ({
secrets: null,
secrets_version: eb('secrets_version', '+', 1),
status,
updated_at: this.now(),
}))
.where('id', '=', id)
.execute();
}
async setModel(id: number, model: string): Promise<void> {
await this.nativeUpdate({ id }, { model });
}
async setStatus(id: number, status: string): Promise<void> {
await this.nativeUpdate({ id }, { status });
}
async deleteById(id: number): Promise<number> {
return this.nativeDelete({ id });
}
}
@@ -0,0 +1,99 @@
import type { AssistantMessages } from '../entities/AssistantMessages.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/**
* One `assistant_messages` row as stored. `parts` and `provider_state` are the
* JSON texts of ASSISTANT_MESSAGE_PARTS and ASSISTANT_PROVIDER_STATE.
*/
export interface AssistantMessageRow {
id: number;
thread_id: number;
role: string;
parts: string;
provider_state: string | null;
status: string;
model: string | null;
created_at: string;
}
const _assistantMessageRowKeys: AssertRowKeys<AssistantMessageRow, AssistantMessages> = true;
/** A message to append; the JSON columns arrive encoded (`encodeJson`). */
interface AssistantMessageInsert {
threadId: number;
role: string;
parts: string;
providerState: string | null;
status: string;
model: string | null;
createdAt: string;
}
/** What a message may still change: its parts, its status and the provider's items. */
interface AssistantMessagePatch {
parts?: string;
status?: string;
providerState?: string | null;
}
type MessagesKyselyDB = Pick<DB, 'assistant_messages'>;
const COLUMNS = ['id', 'thread_id', 'role', 'parts', 'provider_state', 'status', 'model', 'created_at'] as const;
/** `assistant_messages`: the messages of a thread in the order they were written (by id). */
export class AssistantMessagesRepository extends TrekRepository<AssistantMessages> {
private db() {
return this.kysely<MessagesKyselyDB>();
}
async append(message: AssistantMessageInsert): Promise<number> {
const row = await this.db()
.insertInto('assistant_messages')
.values({
thread_id: message.threadId,
role: message.role,
parts: message.parts,
provider_state: message.providerState,
status: message.status,
model: message.model,
created_at: message.createdAt,
})
.returning('id')
.executeTakeFirstOrThrow();
return row.id;
}
async findInThread(id: number, threadId: number): Promise<AssistantMessageRow | null> {
const row = await this.db()
.selectFrom('assistant_messages')
.select(COLUMNS)
.where('id', '=', id)
.where('thread_id', '=', threadId)
.executeTakeFirst();
return row ?? null;
}
/** The last `limit` messages of a thread, oldest first. */
async listLatest(threadId: number, limit: number): Promise<AssistantMessageRow[]> {
const rows = await this.db()
.selectFrom('assistant_messages')
.select(COLUMNS)
.where('thread_id', '=', threadId)
.orderBy('id', 'desc')
.limit(limit)
.execute();
return rows.reverse();
}
async update(id: number, patch: AssistantMessagePatch): Promise<void> {
const set = {
...(patch.parts !== undefined ? { parts: patch.parts } : {}),
...(patch.status !== undefined ? { status: patch.status } : {}),
...(patch.providerState !== undefined ? { provider_state: patch.providerState } : {}),
};
if (Object.keys(set).length === 0) return;
await this.nativeUpdate({ id }, set);
}
}
@@ -0,0 +1,122 @@
import type { AssistantThreads } from '../entities/AssistantThreads.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** One `assistant_threads` row as stored. */
export interface AssistantThreadRow {
id: number;
user_id: number;
trip_id: number;
title: string;
created_at: string;
last_message_at: string;
}
const _assistantThreadRowKeys: AssertRowKeys<AssistantThreadRow, AssistantThreads> = true;
type ThreadsKyselyDB = Pick<DB, 'assistant_threads'>;
const COLUMNS = ['id', 'user_id', 'trip_id', 'title', 'created_at', 'last_message_at'] as const;
/**
* `assistant_threads`: a user's conversations about one trip. Every read and
* delete a request makes names the user and the trip next to the id, so a
* thread is only ever reached by its owner on its own trip.
*/
export class AssistantThreadsRepository extends TrekRepository<AssistantThreads> {
private db() {
return this.kysely<ThreadsKyselyDB>();
}
/** A new thread; answers its id. `at` is both its creation and its last message (`dbNow()`). */
async createThread(userId: number, tripId: number, title: string, at: string): Promise<number> {
const row = await this.db()
.insertInto('assistant_threads')
.values({ user_id: userId, trip_id: tripId, title, created_at: at, last_message_at: at })
.returning('id')
.executeTakeFirstOrThrow();
return row.id;
}
async findOwned(id: number, userId: number, tripId: number): Promise<AssistantThreadRow | null> {
const row = await this.db()
.selectFrom('assistant_threads')
.select(COLUMNS)
.where('id', '=', id)
.where('user_id', '=', userId)
.where('trip_id', '=', tripId)
.executeTakeFirst();
return row ?? null;
}
/** The user's threads on a trip, the most recently used first. */
async listRecent(userId: number, tripId: number, limit: number): Promise<AssistantThreadRow[]> {
return this.db()
.selectFrom('assistant_threads')
.select(COLUMNS)
.where('user_id', '=', userId)
.where('trip_id', '=', tripId)
.orderBy('last_message_at', 'desc')
.orderBy('id', 'desc')
.limit(limit)
.execute();
}
async touch(id: number, at: string): Promise<void> {
await this.nativeUpdate({ id }, { last_message_at: at });
}
/** True when the thread was the user's on that trip and is gone now. */
async deleteOwned(id: number, userId: number, tripId: number): Promise<boolean> {
const result = await this.db()
.deleteFrom('assistant_threads')
.where('id', '=', id)
.where('user_id', '=', userId)
.where('trip_id', '=', tripId)
.executeTakeFirst();
return Number(result.numDeletedRows) > 0;
}
/** Retention: drops the threads nobody wrote in since `cutoff`; answers how many went. */
async deleteIdleBefore(cutoff: string): Promise<number> {
const result = await this.db()
.deleteFrom('assistant_threads')
.where('last_message_at', '<', cutoff)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
/**
* Drops the threads of users who no longer own or belong to the trip they
* are about: removed members keep no conversation about a trip they left.
*/
async deleteWithoutAccess(): Promise<number> {
const result = await this.kysely<Pick<DB, 'assistant_threads' | 'trips' | 'trip_members'>>()
.deleteFrom('assistant_threads')
.where((eb) =>
eb.and([
eb.not(
eb.exists(
eb
.selectFrom('trips')
.select('trips.id')
.whereRef('trips.id', '=', 'assistant_threads.trip_id')
.whereRef('trips.user_id', '=', 'assistant_threads.user_id'),
),
),
eb.not(
eb.exists(
eb
.selectFrom('trip_members')
.select('trip_members.id')
.whereRef('trip_members.trip_id', '=', 'assistant_threads.trip_id')
.whereRef('trip_members.user_id', '=', 'assistant_threads.user_id'),
),
),
]),
)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
}
@@ -0,0 +1,191 @@
import type { AssistantToolCalls } from '../entities/AssistantToolCalls.entity';
import type { DB } from '../kysely/db';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/**
* One `assistant_tool_calls` row as stored. `args`, `preview` and `result` are
* the JSON texts of ASSISTANT_TOOL_ARGS, ASSISTANT_TOOL_PREVIEW and
* ASSISTANT_TOOL_RESULT.
*/
export interface AssistantToolCallRow {
id: string;
thread_id: number;
message_id: number;
provider_call_id: string;
tool_name: string;
args: string;
preview: string;
state: string;
result: string | null;
undo_until: string | null;
created_at: string;
decided_at: string | null;
}
const _assistantToolCallRowKeys: AssertRowKeys<AssistantToolCallRow, AssistantToolCalls> = true;
/** A proposed change as the loop records it, waiting for the user. */
interface AssistantToolCallInsert {
id: string;
threadId: number;
messageId: number;
providerCallId: string;
toolName: string;
args: string;
preview: string;
createdAt: string;
}
type ToolCallsKyselyDB = Pick<DB, 'assistant_tool_calls'>;
const COLUMNS = [
'id',
'thread_id',
'message_id',
'provider_call_id',
'tool_name',
'args',
'preview',
'state',
'result',
'undo_until',
'created_at',
'decided_at',
] as const;
/**
* `assistant_tool_calls`: the changes the assistant proposed. Every state
* change is one conditional UPDATE that only succeeds from the state it
* expects, so two requests deciding or undoing the same call cannot both win.
*/
export class AssistantToolCallsRepository extends TrekRepository<AssistantToolCalls> {
private db() {
return this.kysely<ToolCallsKyselyDB>();
}
async insertProposals(calls: AssistantToolCallInsert[]): Promise<void> {
if (calls.length === 0) return;
await this.db()
.insertInto('assistant_tool_calls')
.values(
calls.map((call) => ({
id: call.id,
thread_id: call.threadId,
message_id: call.messageId,
provider_call_id: call.providerCallId,
tool_name: call.toolName,
args: call.args,
preview: call.preview,
created_at: call.createdAt,
})),
)
.execute();
}
async findInThread(id: string, threadId: number): Promise<AssistantToolCallRow | null> {
const row = await this.db()
.selectFrom('assistant_tool_calls')
.select(COLUMNS)
.where('id', '=', id)
.where('thread_id', '=', threadId)
.executeTakeFirst();
return row ?? null;
}
/** A call of one of the user's threads on that trip; null for anyone else's or another trip's. */
async findOwned(id: string, userId: number, tripId: number): Promise<AssistantToolCallRow | null> {
const row = await this.kysely<Pick<DB, 'assistant_tool_calls' | 'assistant_threads'>>()
.selectFrom('assistant_tool_calls')
.innerJoin('assistant_threads', 'assistant_threads.id', 'assistant_tool_calls.thread_id')
.selectAll('assistant_tool_calls')
.where('assistant_tool_calls.id', '=', id)
.where('assistant_threads.user_id', '=', userId)
.where('assistant_threads.trip_id', '=', tripId)
.executeTakeFirst();
return row ?? null;
}
/** The calls one message proposed, in the order they were stored. */
async listByMessage(messageId: number): Promise<AssistantToolCallRow[]> {
return this.db()
.selectFrom('assistant_tool_calls')
.select(COLUMNS)
.where('message_id', '=', messageId)
.orderBy('created_at')
.orderBy('id')
.execute();
}
/** The calls of a thread still waiting for a decision. */
async listOpen(threadId: number): Promise<AssistantToolCallRow[]> {
return this.db()
.selectFrom('assistant_tool_calls')
.select(COLUMNS)
.where('thread_id', '=', threadId)
.where('state', '=', 'approval_requested')
.orderBy('created_at')
.orderBy('id')
.execute();
}
/**
* Records a decision on a call that is still waiting and was proposed at or
* after `notBefore`; false when it was decided already, expired or is not in
* the thread.
*/
async claimDecision(
id: string,
threadId: number,
approved: boolean,
notBefore: string,
decidedAt: string,
): Promise<boolean> {
const result = await this.db()
.updateTable('assistant_tool_calls')
.set({ state: approved ? 'approved' : 'rejected', decided_at: decidedAt })
.where('id', '=', id)
.where('thread_id', '=', threadId)
.where('state', '=', 'approval_requested')
.where('created_at', '>=', notBefore)
.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** What running an approved call came to: `executed` or `failed`, its result, and how long it may be undone. */
async recordOutcome(id: string, state: string, result: string | null, undoUntil: string | null): Promise<void> {
await this.nativeUpdate({ id }, { state, result, undo_until: undoUntil });
}
/**
* Takes the undo of an executed call of one of the user's threads while its
* window is open; true for exactly one caller.
*/
async claimUndo(id: string, userId: number, now: string): Promise<boolean> {
const result = await this.kysely<Pick<DB, 'assistant_tool_calls' | 'assistant_threads'>>()
.updateTable('assistant_tool_calls')
.set({ state: 'undone' })
.where('id', '=', id)
.where('state', '=', 'executed')
.where('undo_until', '>', now)
.where('thread_id', 'in', (eb) =>
eb
.selectFrom('assistant_threads')
.select('assistant_threads.id')
.where('assistant_threads.user_id', '=', userId),
)
.executeTakeFirst();
return Number(result.numUpdatedRows) > 0;
}
/** Sets the calls still waiting since before `cutoff` to `expired`; answers which, with their message. */
async expireBefore(cutoff: string): Promise<Array<{ id: string; message_id: number }>> {
return this.db()
.updateTable('assistant_tool_calls')
.set({ state: 'expired' })
.where('state', '=', 'approval_requested')
.where('created_at', '<', cutoff)
.returning(['id', 'message_id'])
.execute();
}
}
@@ -0,0 +1,63 @@
import type { AssistantUsage } from '../entities/AssistantUsage.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type AssistantUsageKyselyDB = Pick<DB, 'assistant_usage'>;
/** What one turn adds to a user's day. */
interface AssistantUsageDelta {
turns: number;
inputTokens: number;
outputTokens: number;
}
/**
* `assistant_usage`: turns and tokens per user, UTC day and payer
* (`instance` or `user`). The day is always bound by the caller (`todayUtc()`),
* as in `GoogleApiUsageRepository`; adding to a day is an additive upsert,
* which `em.upsert`'s merge cannot express, hence Kysely.
*/
export class AssistantUsageRepository extends TrekRepository<AssistantUsage> {
private db() {
return this.kysely<AssistantUsageKyselyDB>();
}
async add(userId: number, day: string, paidBy: string, delta: AssistantUsageDelta): Promise<void> {
await this.db()
.insertInto('assistant_usage')
.values({
user_id: userId,
day,
paid_by: paidBy,
turns: delta.turns,
input_tokens: delta.inputTokens,
output_tokens: delta.outputTokens,
})
.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')),
}),
)
.execute();
}
/** The turns a user took on `day` paid by `paidBy`, 0 without a row. */
async turnsOn(userId: number, day: string, paidBy: string): Promise<number> {
const row = await this.db()
.selectFrom('assistant_usage')
.select('turns')
.where('user_id', '=', userId)
.where('day', '=', day)
.where('paid_by', '=', paidBy)
.executeTakeFirst();
return row?.turns ?? 0;
}
/** Drops the days before `day` (exclusive); answers how many rows went. */
async deleteBefore(day: string): Promise<number> {
const result = await this.db().deleteFrom('assistant_usage').where('day', '<', day).executeTakeFirst();
return Number(result.numDeletedRows);
}
}
@@ -13,6 +13,8 @@ export interface CollabMessageRow {
reply_to: number | null;
created_at: string | null;
deleted: number | null;
/** Where the message came from when it was not typed in the chat (`'assistant'`), else null. */
origin: string | null;
}
const _collabMessageRowKeys: AssertRowKeys<CollabMessageRow, CollabMessages> = true;
@@ -166,14 +168,15 @@ export class CollabMessagesRepository extends TrekRepository<CollabMessages> {
return await this.count({ trip: trip_id });
}
/** CB48 (`createMessage`, inside its transaction) — `INSERT INTO collab_messages (trip_id, user_id, text, reply_to) VALUES (?×4)`. Returns the new row's id. */
/** CB48 (`createMessage`, inside its transaction) — `INSERT INTO collab_messages (trip_id, user_id, text, reply_to, origin) VALUES (?×5)`. Returns the new row's id. */
async insertMessage(
trip_id: number | string,
user_id: number,
text: string,
reply_to: number | null,
origin: string | null = null,
): Promise<number> {
return await this.insert({ trip: trip_id, user: user_id, text, reply_to });
return await this.insert({ trip: trip_id, user: user_id, text, reply_to, origin });
}
/** CB54 (`deleteMessage`, inside its transaction) — `UPDATE collab_messages SET deleted = 1 WHERE id = ?`, soft delete — the row survives for the placeholder. */
@@ -1,7 +1,11 @@
import { OauthClients } from '../entities/OauthClients.entity';
import type { DB } from '../kysely/db';
import type { DbTimestamp } from '../types';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
type OauthClientsKyselyDB = Pick<DB, 'oauth_clients' | 'oauth_tokens'>;
/**
* A full `oauth_clients` row (`SELECT * FROM oauth_clients WHERE ...`), as
* the API emits it. `user_id` is the `persist(false)` mirror of the `user`
@@ -88,6 +92,20 @@ export interface OauthClientSdkRow {
created_via: string;
}
/**
* A client registered from its metadata document (`created_via = 'cimd'`): public,
* anonymous, its `client_id` the document URL. `id` and `client_secret_hash` are
* only used when the row is new.
*/
export interface CimdClientUpsertRow {
id: string;
name: string;
client_id: string;
client_secret_hash: string;
redirect_uris: string;
allowed_scopes: string;
}
/** OA21 (`refreshTokens`'s client-auth read) — client auth needs only these three columns. */
export interface OauthClientAuthRow {
client_id: string;
@@ -356,4 +374,54 @@ export class OauthClientsRepository extends TrekRepository<OauthClients> {
const row = await this.findOne({ client_id: clientId });
return row ? (toRow(row) as OauthClientRow) : null;
}
// ---------------------------------------------------------------------
// Client ID Metadata Documents
// ---------------------------------------------------------------------
/**
* `INSERT INTO oauth_clients (...) VALUES (...) ON CONFLICT (client_id) DO
* UPDATE SET name, redirect_uris, allowed_scopes WHERE created_via = 'cimd'`
* — a metadata-document client, refreshed from its document on every
* consent. The WHERE keeps the update off any row another path registered.
*/
async upsertCimdClient(row: CimdClientUpsertRow): Promise<void> {
await this.kysely<OauthClientsKyselyDB>()
.insertInto('oauth_clients')
.values({
id: row.id,
user_id: null,
name: row.name,
client_id: row.client_id,
client_secret_hash: row.client_secret_hash,
redirect_uris: row.redirect_uris,
allowed_scopes: row.allowed_scopes,
is_public: 1,
created_via: 'cimd',
allows_client_credentials: 0,
})
.onConflict((oc) =>
oc
.column('client_id')
.doUpdateSet({ name: row.name, redirect_uris: row.redirect_uris, allowed_scopes: row.allowed_scopes })
.where('oauth_clients.created_via', '=', 'cimd'),
)
.execute();
}
/**
* `DELETE FROM oauth_clients WHERE created_via = 'cimd' AND created_at < ?
* AND client_id NOT IN (SELECT client_id FROM oauth_tokens)` — metadata-
* document clients nobody holds a token for any more. Their consents go with
* them (FK cascade); the next authorization registers the client again.
*/
async deleteUnusedCimdBefore(cutoff: DbTimestamp): Promise<number> {
const result = await this.kysely<OauthClientsKyselyDB>()
.deleteFrom('oauth_clients')
.where('created_via', '=', 'cimd')
.where('created_at', '<', cutoff)
.where('client_id', 'not in', (eb) => eb.selectFrom('oauth_tokens').select('oauth_tokens.client_id'))
.executeTakeFirst();
return Number(result.numDeletedRows ?? 0);
}
}
+9
View File
@@ -141,6 +141,15 @@ export const DEFAULT_ADDONS: AddonRow[] = [
enabled: 0,
sort_order: 15,
},
{
id: 'ai_assistant',
name: 'AI Assistant',
description: 'A chat in the trip that reads the plan and proposes changes you confirm',
type: 'integration',
icon: 'Sparkles',
enabled: 0,
sort_order: 18,
},
{
id: 'collections',
name: 'Collections',