π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(server): split the 1,433-line shareChat router into sub-domain modules (#21095)
Arvin Xuf64d193d0788
diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsdeleted file mode 100644index 42714bda80a..00000000000--- a/apps/server/src/routers/lambda/shareChat.ts+++ /dev/null@@ -1,1433 +0,0 @@-import { randomUUID } from 'node:crypto';--import {- AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,- AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,- AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,- SHARE_UPLOAD_STORAGE_BLOCK_PREFIX,- SHARE_VISITOR_MAX_FILE_SIZE,- SHARE_VISITOR_MAX_FILES_PER_TURN,- SHARE_VISITOR_PROMPT_MAX_LENGTH,-} from '@lobechat/const';-import type { ChatMessageError } from '@lobechat/types';-import {- agentShareDocumentAccessScope,- agentShareFileAccessScope,- agentShareWorkAccessScope,- ChatErrorType,- RequestTrigger,- UserInterventionConfigSchema,-} from '@lobechat/types';-import { nanoid } from '@lobechat/utils';-import { TRPCError } from '@trpc/server';-import debug from 'debug';-import pMap from 'p-map';-import { z } from 'zod';--import { resolveAgentInterventionBySource } from '@/business/server/agent-run/agentInterventionReview';-import { checkAgentShareSpendAllowance } from '@/business/server/agent-share/spendGate';-import { serverDBEnv } from '@/config/db';-import { AgentShareModel } from '@/database/models/agentShare';-import { DocumentModel } from '@/database/models/document';-import { FileModel } from '@/database/models/file';-import { FileUploadModel } from '@/database/models/fileUpload';-import {- HumanApprovalAlreadyResolvedError,- MessageModel,- sanitizeVisitorError,-} from '@/database/models/message';-import { TopicModel } from '@/database/models/topic';-import { UserModel } from '@/database/models/user';-import type { LobeChatDatabase } from '@/database/type';-import { authedProcedure, router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { signUserJWT } from '@/libs/trpc/utils/internalJwt';-import { FileS3 } from '@/server/modules/S3';-import { AiAgentService } from '@/server/services/aiAgent';-import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';-import { FileService } from '@/server/services/file';-import { FileUploadService } from '@/server/services/fileUpload';-import { reserveUpload } from '@/server/services/fileUploadReservation';--import { mapAgentInterventionTRPCError } from './_helpers/agentInterventionError';-import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';-import { execAgentClientIdsSchema } from './_helpers/execAgentClientIds';-import { toClientExecAgentResult } from './_helpers/groupMemberContinuationResult';-import { ResolveAgentInterventionBySourceSchema } from './_schema/agentIntervention';-import {- type AgentInterventionDispatchContext,- bridgeLegacyResumeToSourceIntervention,- dispatchClaimedAgentIntervention,- ResumeApprovalDecisionSchema,- ResumeToolResultSchema,- validateResumePayload,-} from './aiAgent';--const log = debug('lobe-server:router:shareChat');--/**- * Visitor-facing execution chain for shared agents (Agent Share).- *- * All procedures authenticate the VISITOR (ctx.userId) but operate on rows in- * the Agent's owning scope: topics/messages carry the creator's userId plus the- * Agent's workspaceId when present, and `topics.senderId = visitor` for- * scoping. Every- * read/write here is therefore manually authorized: resolve the share via- * {@link resolveLinkShareOrThrow}, then require- * `topic.senderId === visitor && topic.agentId === share.agentId`- * ({@link findVisitorTopicOrThrow}).- *- * A visitor topic is tied to its share through `(agentId, senderId)`. Turning- * sharing off and back on keeps the same share row, so that visitor's older- * conversations remain available and continue counting toward the topic cap.- *- * Workspace identity is resolved from the share row, never from visitor- * headers, and is threaded through every model/service that persists data or- * invokes the runtime.- */-const shareChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {- // Visitor access depends on deployment support and share permissions,- // not the publishing rollout flag.- assertAgentShareVisitorEnabled();-- return opts.next();-});--const ShareTopicScopeSchema = z.object({- shareId: z.string(),- topicId: z.string(),-});--/**- * Resolve a share for the VISITOR execution path.- *- * Stricter than the plain `findByShareIdWithAccessCheck` used by the read-only- * share page: that helper deliberately lets the OWNER through on a `private`- * share (so they can preview their own unpublished page), but the owner never- * uses this visitor chain β they chat with their own agent through- * `aiAgent.execAgent`. Requiring `link` here keeps this entry point in exact- * agreement with the per-step revalidation- * (`AgentShareModel.isRunStillAuthorized`, which also demands `link`), so a- * run can never be authorized to start under a rule its own step loop would- * immediately abort it for.- */-const resolveLinkShareOrThrow = async (db: LobeChatDatabase, shareId: string, viewerId: string) => {- const share = await AgentShareModel.findByShareIdWithAccessCheck(db, shareId, viewerId);-- if (share.visibility !== 'link') {- throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });- }-- return share;-};--/**- * Resolve a visitor-owned share topic or fail closed. The topic row belongs to- * the creator (creator-scoped TopicModel), so the senderId + agentId match is- * the ONLY thing standing between a visitor and the creator's other topics.- */-const findVisitorTopicOrThrow = async (- topicModel: TopicModel,- params: { agentId: string; topicId: string; visitorUserId: string },-) => {- const topic = await topicModel.findById(params.topicId);-- if (!topic || topic.senderId !== params.visitorUserId || topic.agentId !== params.agentId) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });- }-- return topic;-};--/**- * Convert an internal startup failure into a visitor-safe `TRPCError` β reuses- * `sanitizeVisitorError` (`packages/database/src/models/message.ts`) instead of- * a third ad-hoc redaction. `execAgent`/`interruptTask` can throw BEFORE any- * Gateway streaming starts (e.g. the queue or runtime backend returns a- * diagnostic), a failure surface neither existing visitor projection covers β- * `toVisitorMessage` only runs over persisted rows and the Gateway event- * sanitizer only runs over live stream events β so without this, the raw- * `error.message` (which can carry the creator's provider/infra diagnostic,- * since the run executes under the CREATOR's identity) went straight to the- * visitor. Logs the raw error server-side and returns only the classified- * `{ type }` (or `{ message }` for the narrow allowlisted codes) that- * `sanitizeVisitorError` already deems visitor-safe.- *- * `showErrorDetails` (the owner's opt-in on the share config) bypasses the- * projection, exactly as it does for persisted rows and live stream events.- *- * Also the sink for a RESOLVED (not thrown) `{ success: false, error }` from- * `AiAgentService.execAgent` β a `createOperation` startup failure resolves- * rather than rejects there, so the visitor-facing `execAgent` handler below- * re-throws that case through this same function instead of letting the raw- * message escape via a normal `return`.- */-const toVisitorSafeStartupError = (- context: string,- error: unknown,- options: { showErrorDetails?: boolean } = {},-): TRPCError => {- log('%s failed: %O', context, error);-- const raw = error as { message?: unknown; type?: unknown } | null | undefined;- const safe = sanitizeVisitorError(- raw && typeof raw === 'object'- ? ({- message: typeof raw.message === 'string' ? raw.message : undefined,- type: raw.type,- } as ChatMessageError)- : undefined,- options,- );-- // `type` widens to `string | number` (the numeric HTTP-status error codes),- // while `TRPCError.message` is `string | undefined` β stringify rather than- // drop the numeric codes, which are exactly as visitor-safe as the rest.- const publicMessage = safe?.message ?? safe?.type;-- return new TRPCError({- cause: error,- code: 'INTERNAL_SERVER_ERROR',- message: publicMessage === undefined ? 'Internal error' : String(publicMessage),- });-};--/**- * Authorize a visitor to act on a share run. It is not enough that the topic- * belongs to this visitor: `operationId` must also match the operation- * CURRENTLY recorded as running on that topic. Without that check a visitor- * could pass an arbitrary operationId (topics/operations are creator-owned- * rows) and reach an unrelated run on the creator's account.- *- * Returns the creator-scoped service, same as `execAgent`: the run's operation- * / thread rows were written under the creator's identity.- */-const authorizeVisitorRunningOperation = async (- db: LobeChatDatabase,- visitorUserId: string,- input: { operationId: string; shareId: string; topicId: string },-) => {- const share = await resolveLinkShareOrThrow(db, input.shareId, visitorUserId);-- const topicModel = new TopicModel(db, share.ownerId, share.workspaceId ?? undefined, undefined, {- includeShareVisitor: true,- });- const topic = await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId: input.topicId,- visitorUserId,- });-- const runningOperationId = topic.metadata?.runningOperation?.operationId;- if (!runningOperationId || runningOperationId !== input.operationId) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'No matching running operation found on this topic',- });- }-- const aiAgentService = new AiAgentService(db, share.ownerId, {- includeShareVisitor: true,- workspaceId: share.workspaceId ?? undefined,- });-- return { aiAgentService, share };-};--type LinkShare = Awaited<ReturnType<typeof resolveLinkShareOrThrow>>;--/**- * Everything a share VISITOR run executes with: the creator-scoped service and- * models (the run's rows are written under the creator's identity) plus the- * `shareGate` that strips whatever the share config does not grant.- *- * Built fresh from the live share row on every call β a fresh turn and an- * intervention continuation alike β so a continuation is gated by the share's- * CURRENT config, never by a snapshot taken when the run parked.- */-const createShareRunScope = async (- db: LobeChatDatabase,- share: LinkShare,- visitorUserId: string,-) => {- const workspaceId = share.workspaceId ?? undefined;- const modelOptions = { includeShareVisitor: true } as const;- const topicModel = new TopicModel(db, share.ownerId, workspaceId, undefined, modelOptions);- const messageModel = new MessageModel(db, share.ownerId, workspaceId, undefined, modelOptions);-- const shareGate: AgentShareGate = {- agentId: share.agentId,- shareConfig: share.shareConfig,- // See `AgentShareGate.shareId`'s JSDoc β the share instance this run is- // authorized against, and the token every later revalidation compares.- shareId: share.shareId,- visitorUserId,- };-- // Creator's Market access token, mirroring aiAgentProcedure β the- // server-side tool runtime authenticates against the Market API with it.- let marketAccessToken: string | undefined;- if (!share.workspaceId) {- try {- const userModel = new UserModel(db, share.ownerId);- const settings = await userModel.getUserSettings();- marketAccessToken = (settings?.market as any)?.accessToken;- } catch {- // non-fatal β MarketService falls back to trustedClientToken- }- }-- const aiAgentService = new AiAgentService(db, share.ownerId, {- // Share visitor turns persist under the creator's `userId` β the- // service's internal `messageModel`/`topicModel`/runtime must be- // constructed with the visitor scope so reads/writes on- // `topics.senderId <> NULL` rows aren't filtered out.- includeShareVisitor: true,- marketAccessToken,- workspaceId,- });-- /**- * Dispatch context for an intervention the VISITOR resolved: the actor is- * the visitor, the continuation runs as the creator under `shareGate`.- */- const dispatchContext: AgentInterventionDispatchContext = {- aiAgentService,- serverDB: db,- shareGate,- userId: visitorUserId,- workspaceId: share.workspaceId,- };-- return { aiAgentService, dispatchContext, messageModel, shareGate, topicModel };-};--/**- * Storage key prefix for a share's visitor uploads, under the CREATOR's file- * namespace. The prefix is what ties an upload session / file row back to a- * specific share on the settle and abort paths: a visitor can only complete or- * release reservations that live under their share's prefix, never one of the- * creator's own uploads.- */-const shareUploadPrefix = (share: {- ownerId: string;- shareId: string;- workspaceId: string | null;-}) =>- share.workspaceId- ? `files/workspaces/${share.workspaceId}/agent-share/${share.shareId}/`- : `files/${share.ownerId}/agent-share/${share.shareId}/`;--/**- * Visitor-facing storage refusal, one shape for two causes: the share's own- * `maxFileStorage` cap (`share_limit`), or the creator's account-level block- * from the deployment's upload check (`creator_quota`). The latter's original- * reason describes the creator's billing state; it is collapsed here because- * a stranger with the link must not learn it, and the visitor's remedy is the- * same either way. The client matches only the prefix.- */-const shareStorageBlocked = (cause: 'creator_quota' | 'share_limit') =>- new TRPCError({ code: 'FORBIDDEN', message: `${SHARE_UPLOAD_STORAGE_BLOCK_PREFIX}${cause}` });--const toVisitorStorageBlock = (error: unknown) => {- if (- error instanceof TRPCError &&- error.code === 'FORBIDDEN' &&- error.message.startsWith(SHARE_UPLOAD_STORAGE_BLOCK_PREFIX) &&- error.message !== `${SHARE_UPLOAD_STORAGE_BLOCK_PREFIX}share_limit`- ) {- log('creator storage block collapsed for visitor: %s', error.message);- return shareStorageBlocked('creator_quota');- }- return error;-};--/** Basename only β a visitor-supplied name must not steer the storage key. */-const sanitizeUploadName = (name: string) =>- name- .replaceAll(/[/\\]/g, '_')- .replaceAll(/\p{Cc}/gu, '')- .trim() || 'file';--/**- * Every attachment id a visitor pins to a turn must be a file THIS visitor- * uploaded through THIS share (`shareChat.createFile`). Visitor uploads live- * under the creator's account, so a creator-scoped lookup would happily- * resolve any of the creator's files β the `agentShare` provenance on the row- * is the only thing that stops a visitor from naming an arbitrary id and- * having the creator's own document injected into the run. `NOT_FOUND` on- * purpose β same fail-closed shape as the topic guard, revealing nothing- * about whether the id exists for someone else.- */-const assertShareVisitorFiles = async (- db: LobeChatDatabase,- share: { ownerId: string; shareId: string; workspaceId: string | null },- visitorUserId: string,- fileIds: string[] | undefined,-) => {- if (!fileIds?.length) return;-- const uniqueIds = Array.from(new Set(fileIds));- const rows = await new FileModel(db, share.ownerId, share.workspaceId ?? undefined).findByIds(- uniqueIds,- agentShareFileAccessScope({ shareId: share.shareId, visitorUserId }),- );- if (rows.length !== uniqueIds.length) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });- }-};--/**- * Metadata a visitor may attach to their upload β the same intrinsic- * image/audio facts the owner upload path records client-side, so share- * attachments render (dimensions, duration) exactly like owner ones. Anything- * else (notably `agentShare`) is server-written.- */-const ShareUploadMetadataSchema = z- .object({- codec: z.string().max(64),- durationMs: z.number().nonnegative(),- height: z.number().positive(),- mimeType: z.string().max(255),- ratio: z.number().positive(),- width: z.number().positive(),- })- .partial();--export const shareChatRouter = router({- /**- * Release a share upload reservation the visitor abandoned (PUT failed or- * was cancelled). Scoped to the share's own key prefix so a visitor cannot- * release one of the creator's in-flight uploads.- */- abortUpload: shareChatProcedure- .input(z.object({ pathname: z.string().min(1), shareId: z.string() }))- .mutation(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- if (!input.pathname.startsWith(shareUploadPrefix(share))) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });- }-- const fileUploadService = new FileUploadService(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- );- const upload = await fileUploadService.findLatest(input.pathname);- if (upload?.status === 'active') await fileUploadService.release(input.pathname);-- return { success: true };- }),-- /**- * Settle a share upload into a file row β the visitor counterpart of- * `file.createFile`.- *- * The row is written under the CREATOR: share conversations are creator-owned- * data (topics/messages already are), and the creator's storage quota is what- * paid for the reservation in `createUploadUrl`. What makes it the visitor's- * attachment rather than a creator resource is the server-written- * `metadata.agentShare` provenance every share read/write path checks.- *- * Deliberately simpler than the owner path: no knowledge base / parent- * folder / visibility, and no content hash at all. Every share upload is its- * own object under its own reserved key, so the row must stay OUT of the- * hash-keyed `global_files` dedup graph: a row registered there with a hash- * some other file already holds would have its object skipped by the- * refcount in `FileModel.delete` and orphaned in storage on `removeFile`- * (with the visitor never able to see or free it), while its share-cap bytes- * were released. A visitor attachment is only ever reached through the- * message it was sent with, so nothing needs the hash.- */- createFile: shareChatProcedure- .input(- z.object({- fileType: z.string().min(1).max(255),- metadata: ShareUploadMetadataSchema.optional(),- name: z.string().min(1).max(255),- pathname: z.string().min(1),- shareId: z.string(),- size: z.number().int().min(0).max(SHARE_VISITOR_MAX_FILE_SIZE),- }),- )- .mutation(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- if (!input.pathname.startsWith(shareUploadPrefix(share))) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });- }-- const fileUploadService = new FileUploadService(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- );- const fileService = new FileService(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- );-- // No legacy (reservation-less) path here: the share upload flow was born- // with reservations, so a pathname without an active session is either- // expired, already settled, or never ours.- const activeUpload = await fileUploadService.touchActive(input.pathname);- if (!activeUpload) {- throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });- }-- let actualSize: number;- try {- actualSize = (await fileService.getFileMetadata(input.pathname)).contentLength;- } catch {- await fileUploadService.releaseBestEffort(input.pathname);- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Uploaded file is unavailable' });- }- if (input.size !== activeUpload.size || actualSize !== activeUpload.size) {- await fileUploadService.releaseBestEffort(input.pathname);- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Uploaded file size mismatch' });- }-- const parts = input.pathname.split('/');- const filename = parts.pop()!;- const dirname = parts.join('/');-- const { id } = await ctx.serverDB.transaction(async (trx) => {- // Transfer hard revocation locks this same Agent row before it snapshots- // and deletes share files. Taking the lock first gives the two paths a- // single order: if settlement wins, transfer sees and removes this- // file; if transfer wins, the locked recheck below rejects the stale- // share before a new file row can escape the cleanup snapshot.- const tx = trx as LobeChatDatabase;- const lockedAgent = await AgentShareModel.lockScopedAgentRow(tx, share.agentId, {- userId: share.ownerId,- workspaceId: share.workspaceId ?? undefined,- });- if (- !lockedAgent ||- !(await AgentShareModel.isRunStillAuthorized(tx, {- agentId: share.agentId,- shareId: share.shareId,- }))- ) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' });- }-- const lockedUpload = await fileUploadService.model.findLatestByPathnameForUpdate(- input.pathname,- trx,- );- if (lockedUpload?.id !== activeUpload.id || lockedUpload.status !== 'active') {- throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });- }-- const file = await new FileModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- ).create(- {- fileType: input.fileType,- metadata: {- ...input.metadata,- agentShare: { shareId: share.shareId, visitorUserId: ctx.userId },- date: new Date().toISOString().slice(0, 10),- dirname,- filename,- path: input.pathname,- },- name: sanitizeUploadName(input.name),- size: actualSize,- url: input.pathname,- },- false,- trx,- );-- const settled = await fileUploadService.model.settle(lockedUpload.id, file.id, trx);- if (!settled) {- throw new TRPCError({ code: 'CONFLICT', message: 'Upload could not be settled' });- }- return file;- });-- log('createFile: share=%s visitor=%s file=%s', input.shareId, ctx.userId, id);-- return { id, url: await fileService.getFileAccessUrl({ id, url: input.pathname }) };- }),-- /**- * Reserve storage and mint a pre-signed PUT for a visitor attachment β the- * visitor counterpart of `upload.createS3PreSignedUrl`.- *- * The reservation is taken under the CREATOR: the bytes count against the- * creator's storage quota, so it is the creator's `storage_block:*` reason- * (not the visitor's plan) that decides whether the upload is admitted. The- * key lives under the share's own prefix so `createFile` / `abortUpload` can- * prove the session belongs to this share.- */- createUploadUrl: shareChatProcedure- .input(- z.object({- name: z.string().min(1).max(255),- shareId: z.string(),- // `min(1)` is load-bearing beyond validation: the reservation runs the- // size through the deployment's upload check AS THE CREATOR, so a- // visitor-supplied negative size must never reach it β and a zero-byte- // reservation adds nothing to the cap sum, so it would let unbounded- // rows (and objects) pile up under the creator's prefix.- size: z.number().int().min(1).max(SHARE_VISITOR_MAX_FILE_SIZE),- }),- )- .mutation(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- const maxFileStorage =- share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE;- // Cheap pre-check before any storage round-trip; the real, race-free- // check is `admit` below. `<= 0` is the creator turning attachments off- // and refuses regardless of size.- if (maxFileStorage <= 0 || input.size > maxFileStorage) {- throw shareStorageBlocked('share_limit');- }-- const prefix = shareUploadPrefix(share);- const pathname = `${prefix}${nanoid()}/${sanitizeUploadName(input.name)}`;- const s3 = new FileS3();- const uploadModel = new FileUploadModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- );- const fileModel = new FileModel(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined);-- try {- await reserveUpload({- // The share's own cap: settled visitor files plus every live- // reservation under the share prefix, counted inside the reservation- // transaction. The counts alone are not race-free (the reservation's- // own row lock comes after this hook), so the decision is serialized- // per share first β see `AgentShareModel.lockUploadAdmission`.- admit: async (transaction) => {- await AgentShareModel.lockUploadAdmission(transaction, share.shareId);- const settled = await fileModel.countAgentShareUsage(share.shareId, transaction);- const reserved = await uploadModel.countLiveUsageUnderPrefix(prefix, transaction);- if (settled + reserved + input.size > maxFileStorage) {- throw shareStorageBlocked('share_limit');- }- },- clientIp: ctx.clientIp ?? undefined,- db: ctx.serverDB,- model: uploadModel,- pathname,- size: input.size,- storage: s3,- userId: share.ownerId,- workspaceId: share.workspaceId,- });- } catch (error) {- throw toVisitorStorageBlock(error);- }-- try {- return { pathname, url: await s3.createPreSignedUrl(pathname, input.size) };- } catch (error) {- await new FileUploadService(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- ).releaseBestEffort(pathname);- throw error;- }- }),-- /**- * Execute a shared agent as a visitor β the gateway-transport mirror of- * `aiAgent.execAgent`, restricted to the share surface: fixed agent, no- * device/local targets, share-config tool allowlist, per-visitor caps.- */- execAgent: shareChatProcedure- .input(- z- .object({- /** Client-minted row ids, honoured verbatim (see `execAgentClientIdsSchema`). */- clientIds: execAgentClientIdsSchema,- /**- * Ids of files the VISITOR uploaded through `shareChat.createFile`.- * Re-checked below against the file rows' share provenance β see- * `assertShareVisitorFiles`.- */- fileIds: z- .array(z.string().min(1).max(64))- .max(SHARE_VISITOR_MAX_FILES_PER_TURN)- .optional(),- /**- * The pending tool message a resume targets. Set only together with one- * of the `resume*` payloads β a visitor never regenerates or continues- * from an arbitrary message.- */- parentMessageId: z.string().optional(),- /** See `SHARE_VISITOR_PROMPT_MAX_LENGTH`'s JSDoc for the size-bound rationale. */- prompt: z.string().max(SHARE_VISITOR_PROMPT_MAX_LENGTH),- /**- * Legacy (message-row) resume of the visitor's own parked run β the- * fallback when the deployment has no durable intervention store; see- * `resolveInterventionBySource` for the primary path.- */- resumeApproval: ResumeApprovalDecisionSchema.optional(),- resumeApprovals: z.array(ResumeApprovalDecisionSchema).min(1).optional(),- resumeToolResult: ResumeToolResultSchema.optional(),- shareId: z.string(),- /** Queued behind a running turn; see `aiAgent.execAgent`'s `steer`. */- steer: z.boolean().optional(),- /** Absent β the run creates a new visitor topic (counted against the topic cap). */- topicId: z.string().nullish(),- /**- * The VISITOR's own approval mode / allow list. A share run is approved- * by the visitor, so it honors their preference exactly like the owner's- * own chat honors the owner's; absent β `manual` (see- * `AiAgentService.execAgent`).- */- userInterventionConfig: UserInterventionConfigSchema.optional(),- })- .superRefine((data, refinementCtx) => {- validateResumePayload(data, refinementCtx);- const isResume = Boolean(- data.resumeApproval || data.resumeApprovals || data.resumeToolResult,- );- if (data.parentMessageId && !isResume) {- refinementCtx.addIssue({- code: 'custom',- message: 'parentMessageId is only accepted with an intervention resume',- path: ['parentMessageId'],- });- }- if (isResume && !data.topicId) {- refinementCtx.addIssue({- code: 'custom',- message: 'topicId is required for an intervention resume',- path: ['topicId'],- });- }- }),- )- .mutation(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- // Spend admission runs FIRST, before any row is created: a run rejected- // by the runtime billing path instead fails mid-run, after the topic and- // placeholder messages have persisted, leaving junk topics with a "..."- // assistant row. No-op in deployments that do not meter share spend.- const spendGate = await checkAgentShareSpendAllowance({- agentId: share.agentId,- monthlySpendLimit: share.shareConfig.monthlySpendLimit,- ownerUserId: share.ownerId,- shareId: share.shareId,- visitorUserId: ctx.userId,- workspaceId: share.workspaceId ?? undefined,- });- if (!spendGate.allowed) {- throw new TRPCError({- code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareSpendLimitExceeded,- });- }-- const isResume = Boolean(- input.resumeApproval || input.resumeApprovals || input.resumeToolResult,- );- if (isResume && input.fileIds?.length) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'An intervention resume cannot attach files',- });- }-- // Verify every attachment is this visitor's own share upload before it- // is handed to a run that executes (and reads files) as the creator.- // Also ahead of any row creation, like the spend gate β a foreign id- // must not leave a topic behind.- await assertShareVisitorFiles(ctx.serverDB, share, ctx.userId, input.fileIds);-- // Runtime-normalized (findByShareIdWithAccessCheck fills defaults), but- // the config TYPE keeps every field optional β re-apply the same default- // constants rather than asserting non-null.- const maxTopicsPerVisitor =- share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR;- const maxTurnsPerTopic =- share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;- const { aiAgentService, dispatchContext, messageModel, shareGate, topicModel } =- await createShareRunScope(ctx.serverDB, share, ctx.userId);-- // Fast, UX-only pre-check for both caps: reject an obviously-over-cap- // request BEFORE paying for agent-config/tool resolution, instead of only- // at dispatch. This is NOT the enforcement: it is a plain unlocked count,- // so a burst of concurrent requests can all read the same pre-insert- // count and all pass. The atomic, authoritative gate is- // `reserveShareVisitorTopicOrThrow` / `reserveShareVisitorTurnOrThrow`- // (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`), which- // locks and re-checks the same counters immediately around the real- // topic/message INSERT inside `AiAgentService.execAgent`.- if (input.topicId) {- await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId: input.topicId,- visitorUserId: ctx.userId,- });-- // A resume continues the turn the visitor already spent β it adds no- // user message (`reserveShareVisitorTurn` skips it too), so a visitor- // on their last allowed turn can still answer that turn's approval.- const turnCount = isResume- ? 0- : await messageModel.countByTopic({- role: 'user',- topicId: input.topicId,- });- if (turnCount >= maxTurnsPerTopic) {- throw new TRPCError({- code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareTurnLimitExceeded,- });- }- } else {- const topicCount = await topicModel.countBySender({- agentId: share.agentId,- senderId: ctx.userId,- });- if (topicCount >= maxTopicsPerVisitor) {- throw new TRPCError({- code: 'TOO_MANY_REQUESTS',- message: ChatErrorType.ShareTopicLimitExceeded,- });- }- }-- log('execAgent: share=%s visitor=%s topic=%s', input.shareId, ctx.userId, input.topicId);-- try {- if (isResume) {- // Claim the durable generic intervention first when the deployment- // provides a durable store, scoped to this visitor's own share run;- // falls through to the legacy message-row resume when no durable row- // exists.- const bridged = await bridgeLegacyResumeToSourceIntervention(- {- messageModel,- parentMessageId: input.parentMessageId,- resumeApproval: input.resumeApproval,- resumeApprovals: input.resumeApprovals,- resumeToolResult: input.resumeToolResult,- shareVisitor: {- agentId: share.agentId,- ownerUserId: share.ownerId,- topicId: input.topicId!,- },- },- dispatchContext,- );- if (bridged) return bridged;- }-- const result = await aiAgentService.execAgent({- agentId: share.agentId,- appContext: { topicId: input.topicId },- clientIds: input.clientIds,- clientIp: ctx.clientIp ?? undefined,- // Share uploads are creator-owned rows (see `createFile` below), so- // the creator-scoped runtime resolves them like any owner attachment.- fileIds: input.fileIds,- // `interactiveStart: true` (the `aiAgent.execAgent` owner path's- // default) makes `TopicModel.tryReserveTaskCallback` skip its- // `runningOperation` liveness check entirely β a policy that is safe- // there ONLY because the owner's OWN client serializes sends.- //- // An untrusted visitor has no such client-side gate: firing two- // concurrent `execAgent` mutations for the SAME topic would let both- // pass the reservation (each only contends on the short-lived- // `taskCallbackReservation`, released right after the first operation- // is CREATED, long before it finishes streaming), so both would- // create creator-credentialed operations. The second operation's- // `runningOperation` marker write then overwrites the first's,- // leaving the first unreachable by `shareChat.interruptTask` (which- // matches on the topic's current marker) β an orphaned run that keeps- // using tools and the creator's budget until it finishes on its own.- //- // Leaving this `false` routes visitor sends through the SAME- // liveness-checked reservation every non-interactive start uses: a- // second concurrent send for a topic with a live operation is- // rejected instead of silently displacing the first.- //- // A resume is the exception: the topic is still held by the parked- // (`waiting_for_human`) operation it answers, so the liveness check- // would always reject it as busy. Its concurrency guard is the- // exactly-once approval claim instead (`claimApprovalResume` locks the- // pending tool rows via `resolveHumanApproval`), so a duplicate resume- // fails there rather than starting a second continuation.- interactiveStart: isResume,- parentMessageId: input.parentMessageId,- prompt: input.prompt,- resume: isResume,- resumeApproval: input.resumeApproval,- resumeApprovals: input.resumeApprovals,- resumeToolResult: input.resumeToolResult,- shareGate,- steer: input.steer,- // Not `RequestTrigger.Chat`: a share run is billed to the CREATOR,- // so its spend rows must be separable from the creator's own chat- // spend (they land on the same account). The trigger rides- // `state.origin.trigger` all the way into the spend-log metadata.- trigger: RequestTrigger.AgentShare,- userAgent: ctx.userAgent ?? undefined,- userInterventionConfig: input.userInterventionConfig,- });-- // `AiAgentService.execAgent` RESOLVES (does not throw) when- // `createOperation` itself fails to start (e.g. the queue/runtime- // backend is unavailable). That `error` is the same raw- // `error.message` the thrown path guards against, so it must go through- // the exact same projection instead of reaching the visitor verbatim.- //- // Reject rather than sanitize-and-return: the Gateway client never- // checks `result.success` β it unconditionally treats the resolved- // value as a live operation and connects with its- // `operationId`/`token`. A sanitized `success: false` object would- // still be consumed as if the run started, opening a WebSocket for an- // operation that never began.- if (!result.success) {- throw toVisitorSafeStartupError(- 'execAgent',- { message: result.error },- { showErrorDetails: share.shareConfig.showErrorDetails },- );- }-- return result;- } catch (error: any) {- if (error instanceof TRPCError) throw error;- if (error instanceof HumanApprovalAlreadyResolvedError) {- throw new TRPCError({- cause: error,- code: 'CONFLICT',- message: 'This approval has already been resolved.',- });- }-- throw toVisitorSafeStartupError('execAgent', error, {- showErrorDetails: share.shareConfig.showErrorDetails,- });- }- }),-- /**- * One document a visitor's share run produced (the open target of a- * `document` Work card). Read under the visitor's share document scope, so- * only a document stamped with exactly this share/topic/visitor resolves β- * the creator's own documents and other visitors' documents 404.- */- getDocument: shareChatProcedure- .input(ShareTopicScopeSchema.extend({ documentId: z.string() }))- .query(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- const topicModel = new TopicModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );- await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId: input.topicId,- visitorUserId: ctx.userId,- });-- const documentModel = new DocumentModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- agentShareDocumentAccessScope({- shareId: share.shareId,- topicId: input.topicId,- visitorUserId: ctx.userId,- }),- );- const document = await documentModel.findById(input.documentId);- if (!document) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });-- // Narrow projection: no metadata / source / owner columns cross the- // share boundary β the visitor only needs what the read-only viewer shows.- return {- content: document.content,- fileType: document.fileType,- id: document.id,- title: document.title,- updatedAt: document.updatedAt,- };- }),-- /** Messages of one visitor-owned share topic. */- getMessages: shareChatProcedure- .input(ShareTopicScopeSchema.extend({ includeFileWorks: z.boolean().optional() }))- .query(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- const topicModel = new TopicModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );- await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId: input.topicId,- visitorUserId: ctx.userId,- });-- const messageModel = new MessageModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );- const fileService = new FileService(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- );-- // queryForVisitor strips the creator's `sender` identity, and β unless the- // share opts in via `showModelInfo` / `showErrorDetails` β the spend/model- // snapshot and raw error payload too. Share messages persist under the- // CREATOR's account (see the module doc above), so the raw `query()` result- // would otherwise leak the creator's account identity to the visitor.- return messageModel.queryForVisitor(- { includeFileWorks: input.includeFileWorks, topicId: input.topicId },- {- postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),- redaction: {- showErrorDetails: share.shareConfig.showErrorDetails,- showModelInfo: share.shareConfig.showModelInfo,- },- // Work summaries are assembled under the visitor's OWN share scope:- // only Works registered from this share topic resolve, never the- // creator's ordinary Works (see `workMatchesAccessScope`).- //- // Gated on the client's `includeFileWorks` opt-in: pre-Works clients- // (rolling deploys, cached sessions, lagging desktop builds) never- // send it and have no share-aware open handler for the cards, so- // they keep the old Work-free response instead of dead cards.- workAccessScope: input.includeFileWorks- ? agentShareWorkAccessScope({- shareId: share.shareId,- topicId: input.topicId,- visitorUserId: ctx.userId,- })- : undefined,- },- );- }),-- /** The visitor's own topics on this shared agent. */- getTopics: shareChatProcedure- .input(z.object({ shareId: z.string() }))- .query(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- // The list is intentionally NOT bounded by the share's live- // `maxTopicsPerVisitor`: that cap gates ADMISSION of new topics (the- // COUNT check in `execAgent` above), and a creator may lower it below- // what a visitor already created. Tying the page size to it would hide- // those older conversations with no pagination or deep link to reach- // them, so the model applies its own fixed, generous list bound instead.- const topicModel = new TopicModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );- return topicModel.queryBySender({- agentId: share.agentId,- senderId: ctx.userId,- });- }),-- /**- * Resolve an intervention (approve / reject / answer / skip / stop) parked on- * the VISITOR's own share run β the visitor counterpart of- * `aiAgent.resolveAgentInterventionBySource`. A share run is approved by the- * visitor: granting a tool to visitors grants its normal approval flow.- *- * The visitor must own `topicId` under this live share; the business slot- * then binds the durable batch to exactly this creator/agent/topic and a- * share-run operation, so a visitor can never resolve anyone else's run and- * the owner can never resolve a visitor's run through their own endpoints.- * The continuation is dispatched under a `shareGate` rebuilt from the live- * share row (see {@link createShareRunScope}).- *- * `unavailable` means the deployment has no durable intervention store (OSS);- * the client then falls back to `execAgent`'s legacy `resume*` payloads.- */- resolveInterventionBySource: shareChatProcedure- .input(- ResolveAgentInterventionBySourceSchema.extend({- shareId: z.string(),- topicId: z.string(),- }),- )- .mutation(async ({ input, ctx }) => {- const { shareId, topicId, ...source } = input;- const share = await resolveLinkShareOrThrow(ctx.serverDB, shareId, ctx.userId);- const { dispatchContext, topicModel } = await createShareRunScope(- ctx.serverDB,- share,- ctx.userId,- );- await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId,- visitorUserId: ctx.userId,- });-- // A server-side `remember` writes the OWNER's allow list, so a visitor- // may only approve once here; their "don't ask again" goes to their own- // allow list client-side (see `approveToolCalling`).- if (source.action.type === 'approve_tool' && source.action.scope === 'remember') {- throw new TRPCError({ code: 'FORBIDDEN', message: 'Visitors can only approve once' });- }-- log(- 'resolveInterventionBySource: share=%s visitor=%s topic=%s operation=%s action=%s',- shareId,- ctx.userId,- topicId,- source.operationId,- source.action.type,- );-- const resolution = await resolveAgentInterventionBySource({- ...source,- actorUserId: ctx.userId,- shareVisitor: { agentId: share.agentId, ownerUserId: share.ownerId, topicId },- workspaceId: share.workspaceId ?? undefined,- }).catch((error: unknown) => {- throw mapAgentInterventionTRPCError(error);- });-- if (!resolution.handled) {- return {- contractVersion: 2 as const,- status: 'unavailable' as const,- success: false as const,- };- }- if (resolution.state === 'already_resolved') {- return {- contractVersion: 2 as const,- state: resolution.state,- status: resolution.status,- success: true as const,- };- }-- try {- const dispatch = await dispatchClaimedAgentIntervention(resolution, dispatchContext);- return {- contractVersion: 2 as const,- ...(dispatch.execution && { execution: toClientExecAgentResult(dispatch.execution) }),- state: resolution.state,- status: dispatch.status,- success: true as const,- };- } catch (error: any) {- if (error instanceof TRPCError) throw error;-- throw toVisitorSafeStartupError('resolveInterventionBySource', error, {- showErrorDetails: share.shareConfig.showErrorDetails,- });- }- }),-- /**- * Stop the visitor's own parked run from its pending approval card β the- * visitor counterpart of `aiAgent.stopPendingApproval`, used when the- * deployment has no durable intervention store (OSS) or the rows predate it.- * `InterventionController.stopPendingApproval` re-checks that the operation- * is the parked owner of `topicId` and every message belongs to it.- */- stopPendingApproval: shareChatProcedure- .input(- ShareTopicScopeSchema.extend({- batchId: z.string().min(1),- operationId: z.string().min(1),- toolMessageIds: z.array(z.string()).min(1),- }),- )- .mutation(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);- const { aiAgentService, dispatchContext, messageModel, topicModel } =- await createShareRunScope(ctx.serverDB, share, ctx.userId);- await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId: input.topicId,- visitorUserId: ctx.userId,- });-- const stopPlugins = await pMap(- input.toolMessageIds,- (id) => messageModel.findMessagePlugin(id),- { concurrency: 5 },- );- const hasGenericSource = stopPlugins.every(- (plugin) =>- Boolean(plugin?.toolCallId) &&- plugin?.intervention?.operationId === input.operationId &&- plugin.intervention.batchId === input.batchId,- );- if (hasGenericSource) {- const sourceResolution = await resolveAgentInterventionBySource({- action: { scope: 'operation', type: 'stop' },- actorUserId: ctx.userId,- batchId: input.batchId,- operationId: input.operationId,- resolutionRequestId: randomUUID(),- shareVisitor: {- agentId: share.agentId,- ownerUserId: share.ownerId,- topicId: input.topicId,- },- targets: stopPlugins.map((plugin, index) => ({- toolCallId: plugin!.toolCallId!,- toolMessageId: input.toolMessageIds[index],- })),- workspaceId: share.workspaceId ?? undefined,- }).catch((error: unknown) => {- throw mapAgentInterventionTRPCError(error);- });- if (sourceResolution.handled) {- if (sourceResolution.state === 'already_resolved') {- throw new TRPCError({- code: 'CONFLICT',- message: 'This approval has already been resolved.',- });- }- try {- await dispatchClaimedAgentIntervention(sourceResolution, dispatchContext);- } catch (error: any) {- if (error instanceof TRPCError) throw error;-- throw toVisitorSafeStartupError('stopPendingApproval', error, {- showErrorDetails: share.shareConfig.showErrorDetails,- });- }- return {- operationId: input.operationId,- settledToolMessageIds: input.toolMessageIds,- success: true,- };- }- }-- try {- return await aiAgentService.stopPendingApproval({- batchId: input.batchId,- operationId: input.operationId,- toolMessageIds: input.toolMessageIds,- topicId: input.topicId,- });- } catch (error: any) {- if (error instanceof TRPCError) throw error;-- throw toVisitorSafeStartupError('stopPendingApproval', error, {- showErrorDetails: share.shareConfig.showErrorDetails,- });- }- }),-- /**- * Interrupt a running share operation β the visitor counterpart of- * `aiAgent.interruptTask`. Visitors have no owner-scoped access to- * `aiAgent.interruptTask` (its models are scoped to the caller, and share- * runs execute under the CREATOR's identity), so without this endpoint a- * visitor's Stop / tab-close cannot reach the server: the run keeps streaming- * and consuming the creator's budget until it finishes on its own.- *- * Authorization is intentionally stricter than `execAgent`/`getMessages`;- * see {@link authorizeVisitorRunningOperation}.- */- interruptTask: shareChatProcedure- .input(ShareTopicScopeSchema.extend({ operationId: z.string() }))- .mutation(async ({ input, ctx }) => {- const { aiAgentService, share } = await authorizeVisitorRunningOperation(- ctx.serverDB,- ctx.userId,- input,- );-- log(- 'interruptTask: share=%s visitor=%s topic=%s operation=%s',- input.shareId,- ctx.userId,- input.topicId,- input.operationId,- );-- try {- return await aiAgentService.interruptTask({- operationId: input.operationId,- topicId: input.topicId,- });- } catch (error: any) {- if (error instanceof TRPCError) throw error;-- throw toVisitorSafeStartupError('interruptTask', error, {- showErrorDetails: share.shareConfig.showErrorDetails,- });- }- }),-- /**- * The visitor counterpart of `aiAgent.setQueuedMessages`: a visitor can queue- * follow-ups behind a share run too, and needs the same early hand-back.- * Authorized exactly like `interruptTask`.- */- setQueuedMessages: shareChatProcedure- .input(ShareTopicScopeSchema.extend({ operationId: z.string(), pending: z.boolean() }))- .mutation(async ({ input, ctx }) => {- const { aiAgentService, share } = await authorizeVisitorRunningOperation(- ctx.serverDB,- ctx.userId,- input,- );-- log(- 'setQueuedMessages: share=%s visitor=%s topic=%s operation=%s pending=%s',- input.shareId,- ctx.userId,- input.topicId,- input.operationId,- input.pending,- );-- try {- return await aiAgentService.setQueuedMessages({- operationId: input.operationId,- pending: input.pending,- });- } catch (error: any) {- if (error instanceof TRPCError) throw error;-- throw toVisitorSafeStartupError('setQueuedMessages', error, {- showErrorDetails: share.shareConfig.showErrorDetails,- });- }- }),-- /**- * Mint the per-VISITOR Gateway JWT for the multiplexed v2 WebSocket β the- * visitor counterpart of `aiAgent.issueGatewayUserToken`. Same subject rule- * as `refreshGatewayToken` (sign for the visitor: share ops register their- * stream under `streamOwnerUserId = visitor`, and the hub keys on the JWT- * `sub`), but without a running-operation check: the token authenticates the- * user hub socket, and each `subscribe` is authorized per op by the gateway.- * The share must still resolve as link-visible for this caller so a revoked- * or private share cannot be used to open a hub socket from its page.- */- issueGatewayUserToken: shareChatProcedure- .input(z.object({ shareId: z.string() }))- .query(async ({ input, ctx }) => {- await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- const token = await signUserJWT(ctx.userId);-- return { token };- }),-- /**- * Refresh the Gateway WS JWT for a running share operation β the visitor- * counterpart of `aiAgent.refreshGatewayToken` (which cannot serve visitors:- * its TopicModel is scoped to the caller, and share topics belong to the- * creator). Signs for the VISITOR β the gateway channel is registered under- * their id (`streamOwnerUserId`), and a creator-signed token in the visitor's- * browser would be creator account access.- */- refreshGatewayToken: shareChatProcedure- .input(ShareTopicScopeSchema)- .query(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- const topicModel = new TopicModel(- ctx.serverDB,- share.ownerId,- share.workspaceId ?? undefined,- undefined,- { includeShareVisitor: true },- );- const topic = await findVisitorTopicOrThrow(topicModel, {- agentId: share.agentId,- topicId: input.topicId,- visitorUserId: ctx.userId,- });-- // A present marker is not proof of a live run: it is cleared best-effort- // at finish, so a stale one would send the visitor's browser to reconnect- // to a finished operation, register it as "running" locally, and drop the- // topic's fetched history as in-flight noise (a frozen skeleton list).- // NOT_FOUND is what the client already treats as "stale marker, clear it".- const runningOperation = topic.metadata?.runningOperation;- if (- !runningOperation ||- !(await topicModel.isRunningOperationAlive(ctx.serverDB, runningOperation))- ) {- throw new TRPCError({- code: 'NOT_FOUND',- message: 'No running operation found on this topic',- });- }-- const token = await signUserJWT(ctx.userId);-- return { token };- }),-- /**- * Drop a share upload the visitor removed from their draft before sending.- * Only the uploading visitor's own share files qualify (provenance check),- * and only while no message references the row β once sent, the attachment- * is part of a creator-owned conversation and stays put.- *- * Share rows are created outside `global_files` (see `createFile`), so their- * persisted provenance tells `FileModel` that the row owns its object.- */- removeFile: shareChatProcedure- .input(z.object({ fileId: z.string().min(1).max(64), shareId: z.string() }))- .mutation(async ({ input, ctx }) => {- const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);-- const fileModel = new FileModel(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined);- const accessScope = agentShareFileAccessScope({- shareId: share.shareId,- visitorUserId: ctx.userId,- });- const existing = await fileModel.findById(input.fileId, { accessScope });- if (!existing) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });- }-- const file = await fileModel.deleteUnreferenced(input.fileId, {- accessScope,- removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,- });- if (!file) return;-- await new FileService(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined).deleteFile(- file.url!,- );- }),-});--export type ShareChatRouter = typeof shareChatRouter;diff --git a/apps/server/src/routers/lambda/shareChat/conversation.ts b/apps/server/src/routers/lambda/shareChat/conversation.tsnew file mode 100644index 00000000000..e8d1977eb08--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/conversation.ts@@ -0,0 +1,150 @@+import { agentShareDocumentAccessScope, agentShareWorkAccessScope } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { DocumentModel } from '@/database/models/document';+import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import { router } from '@/libs/trpc/lambda';+import { FileService } from '@/server/services/file';++import { findVisitorTopicOrThrow, resolveLinkShareOrThrow } from './guards';+import { shareChatProcedure, ShareTopicScopeSchema } from './procedures';++export const conversationRouter = router({+ /** The visitor's own topics on this shared agent. */+ getTopics: shareChatProcedure+ .input(z.object({ shareId: z.string() }))+ .query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ // The list is intentionally NOT bounded by the share's live+ // `maxTopicsPerVisitor`: that cap gates ADMISSION of new topics (the+ // COUNT check in `execAgent`, `exec.ts`), and a creator may lower it below+ // what a visitor already created. Tying the page size to it would hide+ // those older conversations with no pagination or deep link to reach+ // them, so the model applies its own fixed, generous list bound instead.+ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ return topicModel.queryBySender({+ agentId: share.agentId,+ senderId: ctx.userId,+ });+ }),+ /** Messages of one visitor-owned share topic. */+ getMessages: shareChatProcedure+ .input(ShareTopicScopeSchema.extend({ includeFileWorks: z.boolean().optional() }))+ .query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const messageModel = new MessageModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ const fileService = new FileService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );++ // queryForVisitor strips the creator's `sender` identity, and β unless the+ // share opts in via `showModelInfo` / `showErrorDetails` β the spend/model+ // snapshot and raw error payload too. Share messages persist under the+ // CREATOR's account (see the `shareChatProcedure` doc in `procedures.ts`), so the raw `query()` result+ // would otherwise leak the creator's account identity to the visitor.+ return messageModel.queryForVisitor(+ { includeFileWorks: input.includeFileWorks, topicId: input.topicId },+ {+ postProcessUrl: (path, file) => fileService.getFileAccessUrl({ id: file.id, url: path }),+ redaction: {+ showErrorDetails: share.shareConfig.showErrorDetails,+ showModelInfo: share.shareConfig.showModelInfo,+ },+ // Work summaries are assembled under the visitor's OWN share scope:+ // only Works registered from this share topic resolve, never the+ // creator's ordinary Works (see `workMatchesAccessScope`).+ //+ // Gated on the client's `includeFileWorks` opt-in: pre-Works clients+ // (rolling deploys, cached sessions, lagging desktop builds) never+ // send it and have no share-aware open handler for the cards, so+ // they keep the old Work-free response instead of dead cards.+ workAccessScope: input.includeFileWorks+ ? agentShareWorkAccessScope({+ shareId: share.shareId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ })+ : undefined,+ },+ );+ }),+ /**+ * One document a visitor's share run produced (the open target of a+ * `document` Work card). Read under the visitor's share document scope, so+ * only a document stamped with exactly this share/topic/visitor resolves β+ * the creator's own documents and other visitors' documents 404.+ */+ getDocument: shareChatProcedure+ .input(ShareTopicScopeSchema.extend({ documentId: z.string() }))+ .query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const documentModel = new DocumentModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ agentShareDocumentAccessScope({+ shareId: share.shareId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ }),+ );+ const document = await documentModel.findById(input.documentId);+ if (!document) throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });++ // Narrow projection: no metadata / source / owner columns cross the+ // share boundary β the visitor only needs what the read-only viewer shows.+ return {+ content: document.content,+ fileType: document.fileType,+ id: document.id,+ title: document.title,+ updatedAt: document.updatedAt,+ };+ }),+});diff --git a/apps/server/src/routers/lambda/shareChat/exec.ts b/apps/server/src/routers/lambda/shareChat/exec.tsnew file mode 100644index 00000000000..9998444d33b--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/exec.ts@@ -0,0 +1,346 @@+import {+ AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR,+ AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC,+ SHARE_VISITOR_MAX_FILES_PER_TURN,+ SHARE_VISITOR_PROMPT_MAX_LENGTH,+} from '@lobechat/const';+import {+ agentShareFileAccessScope,+ ChatErrorType,+ RequestTrigger,+ UserInterventionConfigSchema,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import debug from 'debug';+import { z } from 'zod';++import { checkAgentShareSpendAllowance } from '@/business/server/agent-share/spendGate';+import { FileModel } from '@/database/models/file';+import { HumanApprovalAlreadyResolvedError } from '@/database/models/message';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';++import { execAgentClientIdsSchema } from '../_helpers/execAgentClientIds';+import {+ bridgeLegacyResumeToSourceIntervention,+ ResumeApprovalDecisionSchema,+ ResumeToolResultSchema,+ validateResumePayload,+} from '../aiAgent';+import {+ findVisitorTopicOrThrow,+ resolveLinkShareOrThrow,+ toVisitorSafeStartupError,+} from './guards';+import { shareChatProcedure } from './procedures';+import { createShareRunScope } from './runScope';++const log = debug('lobe-server:router:shareChat');++/**+ * Every attachment id a visitor pins to a turn must be a file THIS visitor+ * uploaded through THIS share (`shareChat.createFile`). Visitor uploads live+ * under the creator's account, so a creator-scoped lookup would happily+ * resolve any of the creator's files β the `agentShare` provenance on the row+ * is the only thing that stops a visitor from naming an arbitrary id and+ * having the creator's own document injected into the run. `NOT_FOUND` on+ * purpose β same fail-closed shape as the topic guard, revealing nothing+ * about whether the id exists for someone else.+ */+const assertShareVisitorFiles = async (+ db: LobeChatDatabase,+ share: { ownerId: string; shareId: string; workspaceId: string | null },+ visitorUserId: string,+ fileIds: string[] | undefined,+) => {+ if (!fileIds?.length) return;++ const uniqueIds = Array.from(new Set(fileIds));+ const rows = await new FileModel(db, share.ownerId, share.workspaceId ?? undefined).findByIds(+ uniqueIds,+ agentShareFileAccessScope({ shareId: share.shareId, visitorUserId }),+ );+ if (rows.length !== uniqueIds.length) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ }+};++export const execRouter = router({+ /**+ * Execute a shared agent as a visitor β the gateway-transport mirror of+ * `aiAgent.execAgent`, restricted to the share surface: fixed agent, no+ * device/local targets, share-config tool allowlist, per-visitor caps.+ */+ execAgent: shareChatProcedure+ .input(+ z+ .object({+ /** Client-minted row ids, honoured verbatim (see `execAgentClientIdsSchema`). */+ clientIds: execAgentClientIdsSchema,+ /**+ * Ids of files the VISITOR uploaded through `shareChat.createFile`.+ * Re-checked below against the file rows' share provenance β see+ * `assertShareVisitorFiles`.+ */+ fileIds: z+ .array(z.string().min(1).max(64))+ .max(SHARE_VISITOR_MAX_FILES_PER_TURN)+ .optional(),+ /**+ * The pending tool message a resume targets. Set only together with one+ * of the `resume*` payloads β a visitor never regenerates or continues+ * from an arbitrary message.+ */+ parentMessageId: z.string().optional(),+ /** See `SHARE_VISITOR_PROMPT_MAX_LENGTH`'s JSDoc for the size-bound rationale. */+ prompt: z.string().max(SHARE_VISITOR_PROMPT_MAX_LENGTH),+ /**+ * Legacy (message-row) resume of the visitor's own parked run β the+ * fallback when the deployment has no durable intervention store; see+ * `resolveInterventionBySource` for the primary path.+ */+ resumeApproval: ResumeApprovalDecisionSchema.optional(),+ resumeApprovals: z.array(ResumeApprovalDecisionSchema).min(1).optional(),+ resumeToolResult: ResumeToolResultSchema.optional(),+ shareId: z.string(),+ /** Queued behind a running turn; see `aiAgent.execAgent`'s `steer`. */+ steer: z.boolean().optional(),+ /** Absent β the run creates a new visitor topic (counted against the topic cap). */+ topicId: z.string().nullish(),+ /**+ * The VISITOR's own approval mode / allow list. A share run is approved+ * by the visitor, so it honors their preference exactly like the owner's+ * own chat honors the owner's; absent β `manual` (see+ * `AiAgentService.execAgent`).+ */+ userInterventionConfig: UserInterventionConfigSchema.optional(),+ })+ .superRefine((data, refinementCtx) => {+ validateResumePayload(data, refinementCtx);+ const isResume = Boolean(+ data.resumeApproval || data.resumeApprovals || data.resumeToolResult,+ );+ if (data.parentMessageId && !isResume) {+ refinementCtx.addIssue({+ code: 'custom',+ message: 'parentMessageId is only accepted with an intervention resume',+ path: ['parentMessageId'],+ });+ }+ if (isResume && !data.topicId) {+ refinementCtx.addIssue({+ code: 'custom',+ message: 'topicId is required for an intervention resume',+ path: ['topicId'],+ });+ }+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ // Spend admission runs FIRST, before any row is created: a run rejected+ // by the runtime billing path instead fails mid-run, after the topic and+ // placeholder messages have persisted, leaving junk topics with a "..."+ // assistant row. No-op in deployments that do not meter share spend.+ const spendGate = await checkAgentShareSpendAllowance({+ agentId: share.agentId,+ monthlySpendLimit: share.shareConfig.monthlySpendLimit,+ ownerUserId: share.ownerId,+ shareId: share.shareId,+ visitorUserId: ctx.userId,+ workspaceId: share.workspaceId ?? undefined,+ });+ if (!spendGate.allowed) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareSpendLimitExceeded,+ });+ }++ const isResume = Boolean(+ input.resumeApproval || input.resumeApprovals || input.resumeToolResult,+ );+ if (isResume && input.fileIds?.length) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'An intervention resume cannot attach files',+ });+ }++ // Verify every attachment is this visitor's own share upload before it+ // is handed to a run that executes (and reads files) as the creator.+ // Also ahead of any row creation, like the spend gate β a foreign id+ // must not leave a topic behind.+ await assertShareVisitorFiles(ctx.serverDB, share, ctx.userId, input.fileIds);++ // Runtime-normalized (findByShareIdWithAccessCheck fills defaults), but+ // the config TYPE keeps every field optional β re-apply the same default+ // constants rather than asserting non-null.+ const maxTopicsPerVisitor =+ share.shareConfig.maxTopicsPerVisitor ?? AGENT_SHARE_DEFAULT_MAX_TOPICS_PER_VISITOR;+ const maxTurnsPerTopic =+ share.shareConfig.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;+ const { aiAgentService, dispatchContext, messageModel, shareGate, topicModel } =+ await createShareRunScope(ctx.serverDB, share, ctx.userId);++ // Fast, UX-only pre-check for both caps: reject an obviously-over-cap+ // request BEFORE paying for agent-config/tool resolution, instead of only+ // at dispatch. This is NOT the enforcement: it is a plain unlocked count,+ // so a burst of concurrent requests can all read the same pre-insert+ // count and all pass. The atomic, authoritative gate is+ // `reserveShareVisitorTopicOrThrow` / `reserveShareVisitorTurnOrThrow`+ // (`apps/server/src/services/aiAgent/shareVisitorAbuseGuards.ts`), which+ // locks and re-checks the same counters immediately around the real+ // topic/message INSERT inside `AiAgentService.execAgent`.+ if (input.topicId) {+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ // A resume continues the turn the visitor already spent β it adds no+ // user message (`reserveShareVisitorTurn` skips it too), so a visitor+ // on their last allowed turn can still answer that turn's approval.+ const turnCount = isResume+ ? 0+ : await messageModel.countByTopic({+ role: 'user',+ topicId: input.topicId,+ });+ if (turnCount >= maxTurnsPerTopic) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareTurnLimitExceeded,+ });+ }+ } else {+ const topicCount = await topicModel.countBySender({+ agentId: share.agentId,+ senderId: ctx.userId,+ });+ if (topicCount >= maxTopicsPerVisitor) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.ShareTopicLimitExceeded,+ });+ }+ }++ log('execAgent: share=%s visitor=%s topic=%s', input.shareId, ctx.userId, input.topicId);++ try {+ if (isResume) {+ // Claim the durable generic intervention first when the deployment+ // provides a durable store, scoped to this visitor's own share run;+ // falls through to the legacy message-row resume when no durable row+ // exists.+ const bridged = await bridgeLegacyResumeToSourceIntervention(+ {+ messageModel,+ parentMessageId: input.parentMessageId,+ resumeApproval: input.resumeApproval,+ resumeApprovals: input.resumeApprovals,+ resumeToolResult: input.resumeToolResult,+ shareVisitor: {+ agentId: share.agentId,+ ownerUserId: share.ownerId,+ topicId: input.topicId!,+ },+ },+ dispatchContext,+ );+ if (bridged) return bridged;+ }++ const result = await aiAgentService.execAgent({+ agentId: share.agentId,+ appContext: { topicId: input.topicId },+ clientIds: input.clientIds,+ clientIp: ctx.clientIp ?? undefined,+ // Share uploads are creator-owned rows (see `createFile` in `upload.ts`), so+ // the creator-scoped runtime resolves them like any owner attachment.+ fileIds: input.fileIds,+ // `interactiveStart: true` (the `aiAgent.execAgent` owner path's+ // default) makes `TopicModel.tryReserveTaskCallback` skip its+ // `runningOperation` liveness check entirely β a policy that is safe+ // there ONLY because the owner's OWN client serializes sends.+ //+ // An untrusted visitor has no such client-side gate: firing two+ // concurrent `execAgent` mutations for the SAME topic would let both+ // pass the reservation (each only contends on the short-lived+ // `taskCallbackReservation`, released right after the first operation+ // is CREATED, long before it finishes streaming), so both would+ // create creator-credentialed operations. The second operation's+ // `runningOperation` marker write then overwrites the first's,+ // leaving the first unreachable by `shareChat.interruptTask` (which+ // matches on the topic's current marker) β an orphaned run that keeps+ // using tools and the creator's budget until it finishes on its own.+ //+ // Leaving this `false` routes visitor sends through the SAME+ // liveness-checked reservation every non-interactive start uses: a+ // second concurrent send for a topic with a live operation is+ // rejected instead of silently displacing the first.+ //+ // A resume is the exception: the topic is still held by the parked+ // (`waiting_for_human`) operation it answers, so the liveness check+ // would always reject it as busy. Its concurrency guard is the+ // exactly-once approval claim instead (`claimApprovalResume` locks the+ // pending tool rows via `resolveHumanApproval`), so a duplicate resume+ // fails there rather than starting a second continuation.+ interactiveStart: isResume,+ parentMessageId: input.parentMessageId,+ prompt: input.prompt,+ resume: isResume,+ resumeApproval: input.resumeApproval,+ resumeApprovals: input.resumeApprovals,+ resumeToolResult: input.resumeToolResult,+ shareGate,+ steer: input.steer,+ // Not `RequestTrigger.Chat`: a share run is billed to the CREATOR,+ // so its spend rows must be separable from the creator's own chat+ // spend (they land on the same account). The trigger rides+ // `state.origin.trigger` all the way into the spend-log metadata.+ trigger: RequestTrigger.AgentShare,+ userAgent: ctx.userAgent ?? undefined,+ userInterventionConfig: input.userInterventionConfig,+ });++ // `AiAgentService.execAgent` RESOLVES (does not throw) when+ // `createOperation` itself fails to start (e.g. the queue/runtime+ // backend is unavailable). That `error` is the same raw+ // `error.message` the thrown path guards against, so it must go through+ // the exact same projection instead of reaching the visitor verbatim.+ //+ // Reject rather than sanitize-and-return: the Gateway client never+ // checks `result.success` β it unconditionally treats the resolved+ // value as a live operation and connects with its+ // `operationId`/`token`. A sanitized `success: false` object would+ // still be consumed as if the run started, opening a WebSocket for an+ // operation that never began.+ if (!result.success) {+ throw toVisitorSafeStartupError(+ 'execAgent',+ { message: result.error },+ { showErrorDetails: share.shareConfig.showErrorDetails },+ );+ }++ return result;+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;+ if (error instanceof HumanApprovalAlreadyResolvedError) {+ throw new TRPCError({+ cause: error,+ code: 'CONFLICT',+ message: 'This approval has already been resolved.',+ });+ }++ throw toVisitorSafeStartupError('execAgent', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/shareChat/gateway.ts b/apps/server/src/routers/lambda/shareChat/gateway.tsnew file mode 100644index 00000000000..4d61354abd6--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/gateway.ts@@ -0,0 +1,77 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { TopicModel } from '@/database/models/topic';+import { router } from '@/libs/trpc/lambda';+import { signUserJWT } from '@/libs/trpc/utils/internalJwt';++import { findVisitorTopicOrThrow, resolveLinkShareOrThrow } from './guards';+import { shareChatProcedure, ShareTopicScopeSchema } from './procedures';++export const gatewayRouter = router({+ /**+ * Mint the per-VISITOR Gateway JWT for the multiplexed v2 WebSocket β the+ * visitor counterpart of `aiAgent.issueGatewayUserToken`. Same subject rule+ * as `refreshGatewayToken` (sign for the visitor: share ops register their+ * stream under `streamOwnerUserId = visitor`, and the hub keys on the JWT+ * `sub`), but without a running-operation check: the token authenticates the+ * user hub socket, and each `subscribe` is authorized per op by the gateway.+ * The share must still resolve as link-visible for this caller so a revoked+ * or private share cannot be used to open a hub socket from its page.+ */+ issueGatewayUserToken: shareChatProcedure+ .input(z.object({ shareId: z.string() }))+ .query(async ({ input, ctx }) => {+ await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const token = await signUserJWT(ctx.userId);++ return { token };+ }),+ /**+ * Refresh the Gateway WS JWT for a running share operation β the visitor+ * counterpart of `aiAgent.refreshGatewayToken` (which cannot serve visitors:+ * its TopicModel is scoped to the caller, and share topics belong to the+ * creator). Signs for the VISITOR β the gateway channel is registered under+ * their id (`streamOwnerUserId`), and a creator-signed token in the visitor's+ * browser would be creator account access.+ */+ refreshGatewayToken: shareChatProcedure+ .input(ShareTopicScopeSchema)+ .query(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const topicModel = new TopicModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ undefined,+ { includeShareVisitor: true },+ );+ const topic = await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ // A present marker is not proof of a live run: it is cleared best-effort+ // at finish, so a stale one would send the visitor's browser to reconnect+ // to a finished operation, register it as "running" locally, and drop the+ // topic's fetched history as in-flight noise (a frozen skeleton list).+ // NOT_FOUND is what the client already treats as "stale marker, clear it".+ const runningOperation = topic.metadata?.runningOperation;+ if (+ !runningOperation ||+ !(await topicModel.isRunningOperationAlive(ctx.serverDB, runningOperation))+ ) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'No running operation found on this topic',+ });+ }++ const token = await signUserJWT(ctx.userId);++ return { token };+ }),+});diff --git a/apps/server/src/routers/lambda/shareChat/guards.ts b/apps/server/src/routers/lambda/shareChat/guards.tsnew file mode 100644index 00000000000..323b2e82636--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/guards.ts@@ -0,0 +1,108 @@+import type { ChatMessageError } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import debug from 'debug';++import { AgentShareModel } from '@/database/models/agentShare';+import { sanitizeVisitorError } from '@/database/models/message';+import type { TopicModel } from '@/database/models/topic';+import type { LobeChatDatabase } from '@/database/type';++const log = debug('lobe-server:router:shareChat');++/**+ * Resolve a share for the VISITOR execution path.+ *+ * Stricter than the plain `findByShareIdWithAccessCheck` used by the read-only+ * share page: that helper deliberately lets the OWNER through on a `private`+ * share (so they can preview their own unpublished page), but the owner never+ * uses this visitor chain β they chat with their own agent through+ * `aiAgent.execAgent`. Requiring `link` here keeps this entry point in exact+ * agreement with the per-step revalidation+ * (`AgentShareModel.isRunStillAuthorized`, which also demands `link`), so a+ * run can never be authorized to start under a rule its own step loop would+ * immediately abort it for.+ */+export const resolveLinkShareOrThrow = async (+ db: LobeChatDatabase,+ shareId: string,+ viewerId: string,+) => {+ const share = await AgentShareModel.findByShareIdWithAccessCheck(db, shareId, viewerId);++ if (share.visibility !== 'link') {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'This share is private' });+ }++ return share;+};++/**+ * Resolve a visitor-owned share topic or fail closed. The topic row belongs to+ * the creator (creator-scoped TopicModel), so the senderId + agentId match is+ * the ONLY thing standing between a visitor and the creator's other topics.+ */+export const findVisitorTopicOrThrow = async (+ topicModel: TopicModel,+ params: { agentId: string; topicId: string; visitorUserId: string },+) => {+ const topic = await topicModel.findById(params.topicId);++ if (!topic || topic.senderId !== params.visitorUserId || topic.agentId !== params.agentId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });+ }++ return topic;+};++/**+ * Convert an internal startup failure into a visitor-safe `TRPCError` β reuses+ * `sanitizeVisitorError` (`packages/database/src/models/message.ts`) instead of+ * a third ad-hoc redaction. `execAgent`/`interruptTask` can throw BEFORE any+ * Gateway streaming starts (e.g. the queue or runtime backend returns a+ * diagnostic), a failure surface neither existing visitor projection covers β+ * `toVisitorMessage` only runs over persisted rows and the Gateway event+ * sanitizer only runs over live stream events β so without this, the raw+ * `error.message` (which can carry the creator's provider/infra diagnostic,+ * since the run executes under the CREATOR's identity) went straight to the+ * visitor. Logs the raw error server-side and returns only the classified+ * `{ type }` (or `{ message }` for the narrow allowlisted codes) that+ * `sanitizeVisitorError` already deems visitor-safe.+ *+ * `showErrorDetails` (the owner's opt-in on the share config) bypasses the+ * projection, exactly as it does for persisted rows and live stream events.+ *+ * Also the sink for a RESOLVED (not thrown) `{ success: false, error }` from+ * `AiAgentService.execAgent` β a `createOperation` startup failure resolves+ * rather than rejects there, so the visitor-facing `execAgent` handler (`exec.ts`)+ * re-throws that case through this same function instead of letting the raw+ * message escape via a normal `return`.+ */+export const toVisitorSafeStartupError = (+ context: string,+ error: unknown,+ options: { showErrorDetails?: boolean } = {},+): TRPCError => {+ log('%s failed: %O', context, error);++ const raw = error as { message?: unknown; type?: unknown } | null | undefined;+ const safe = sanitizeVisitorError(+ raw && typeof raw === 'object'+ ? ({+ message: typeof raw.message === 'string' ? raw.message : undefined,+ type: raw.type,+ } as ChatMessageError)+ : undefined,+ options,+ );++ // `type` widens to `string | number` (the numeric HTTP-status error codes),+ // while `TRPCError.message` is `string | undefined` β stringify rather than+ // drop the numeric codes, which are exactly as visitor-safe as the rest.+ const publicMessage = safe?.message ?? safe?.type;++ return new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: publicMessage === undefined ? 'Internal error' : String(publicMessage),+ });+};diff --git a/apps/server/src/routers/lambda/shareChat/index.procedures.test.ts b/apps/server/src/routers/lambda/shareChat/index.procedures.test.tsnew file mode 100644index 00000000000..4ae2976b85c--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/index.procedures.test.ts@@ -0,0 +1,43 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { shareChatRouter } from '.';++/**+ * Pins the router's public surface: every procedure path, its kind, and its+ * middleware chain length (which encodes the procedure builder and its input+ * parsers). Splitting the router across files must keep all three.+ */+describe('shareChatRouter procedures', () => {+ const procedures = (shareChatRouter as any)._def.procedures as Record<string, any>;++ it('exposes exactly the expected procedure paths', () => {+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));+ });++ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {+ expect(procedures[name]._def.type).toBe(type);+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);+ });+});++function expected(): Array<+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]+> {+ return [+ ['abortUpload', 'mutation', 11],+ ['createFile', 'mutation', 11],+ ['createUploadUrl', 'mutation', 11],+ ['execAgent', 'mutation', 11],+ ['getDocument', 'query', 11],+ ['getMessages', 'query', 11],+ ['getTopics', 'query', 11],+ ['interruptTask', 'mutation', 11],+ ['issueGatewayUserToken', 'query', 11],+ ['refreshGatewayToken', 'query', 11],+ ['removeFile', 'mutation', 11],+ ['resolveInterventionBySource', 'mutation', 11],+ ['setQueuedMessages', 'mutation', 11],+ ['stopPendingApproval', 'mutation', 11],+ ];+}diff --git a/apps/server/src/routers/lambda/shareChat/index.ts b/apps/server/src/routers/lambda/shareChat/index.tsnew file mode 100644index 00000000000..42b6a0c433e--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/index.ts@@ -0,0 +1,17 @@+import { mergeRouters } from '@/libs/trpc/lambda';++import { conversationRouter } from './conversation';+import { execRouter } from './exec';+import { gatewayRouter } from './gateway';+import { runControlRouter } from './runControl';+import { uploadRouter } from './upload';++export const shareChatRouter = mergeRouters(+ uploadRouter,+ execRouter,+ conversationRouter,+ runControlRouter,+ gatewayRouter,+);++export type ShareChatRouter = typeof shareChatRouter;diff --git a/apps/server/src/routers/lambda/shareChat/procedures.ts b/apps/server/src/routers/lambda/shareChat/procedures.tsnew file mode 100644index 00000000000..ddff2ba2713--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/procedures.ts@@ -0,0 +1,39 @@+import { z } from 'zod';++import { authedProcedure } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++import { assertAgentShareVisitorEnabled } from '../_helpers/agentShareFeatureGate';++/**+ * Visitor-facing execution chain for shared agents (Agent Share).+ *+ * All procedures authenticate the VISITOR (ctx.userId) but operate on rows in+ * the Agent's owning scope: topics/messages carry the creator's userId plus the+ * Agent's workspaceId when present, and `topics.senderId = visitor` for+ * scoping. Every+ * read/write here is therefore manually authorized: resolve the share via+ * {@link resolveLinkShareOrThrow}, then require+ * `topic.senderId === visitor && topic.agentId === share.agentId`+ * ({@link findVisitorTopicOrThrow}).+ *+ * A visitor topic is tied to its share through `(agentId, senderId)`. Turning+ * sharing off and back on keeps the same share row, so that visitor's older+ * conversations remain available and continue counting toward the topic cap.+ *+ * Workspace identity is resolved from the share row, never from visitor+ * headers, and is threaded through every model/service that persists data or+ * invokes the runtime.+ */+export const shareChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ // Visitor access depends on deployment support and share permissions,+ // not the publishing rollout flag.+ assertAgentShareVisitorEnabled();++ return opts.next();+});++export const ShareTopicScopeSchema = z.object({+ shareId: z.string(),+ topicId: z.string(),+});diff --git a/apps/server/src/routers/lambda/shareChat/runControl.ts b/apps/server/src/routers/lambda/shareChat/runControl.tsnew file mode 100644index 00000000000..ffaf625b343--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/runControl.ts@@ -0,0 +1,338 @@+import { randomUUID } from 'node:crypto';++import { TRPCError } from '@trpc/server';+import debug from 'debug';+import pMap from 'p-map';+import { z } from 'zod';++import { resolveAgentInterventionBySource } from '@/business/server/agent-run/agentInterventionReview';+import { TopicModel } from '@/database/models/topic';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { AiAgentService } from '@/server/services/aiAgent';++import { mapAgentInterventionTRPCError } from '../_helpers/agentInterventionError';+import { toClientExecAgentResult } from '../_helpers/groupMemberContinuationResult';+import { ResolveAgentInterventionBySourceSchema } from '../_schema/agentIntervention';+import { dispatchClaimedAgentIntervention } from '../aiAgent';+import {+ findVisitorTopicOrThrow,+ resolveLinkShareOrThrow,+ toVisitorSafeStartupError,+} from './guards';+import { shareChatProcedure, ShareTopicScopeSchema } from './procedures';+import { createShareRunScope } from './runScope';++const log = debug('lobe-server:router:shareChat');++/**+ * Authorize a visitor to act on a share run. It is not enough that the topic+ * belongs to this visitor: `operationId` must also match the operation+ * CURRENTLY recorded as running on that topic. Without that check a visitor+ * could pass an arbitrary operationId (topics/operations are creator-owned+ * rows) and reach an unrelated run on the creator's account.+ *+ * Returns the creator-scoped service, same as `execAgent`: the run's operation+ * / thread rows were written under the creator's identity.+ */+const authorizeVisitorRunningOperation = async (+ db: LobeChatDatabase,+ visitorUserId: string,+ input: { operationId: string; shareId: string; topicId: string },+) => {+ const share = await resolveLinkShareOrThrow(db, input.shareId, visitorUserId);++ const topicModel = new TopicModel(db, share.ownerId, share.workspaceId ?? undefined, undefined, {+ includeShareVisitor: true,+ });+ const topic = await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId,+ });++ const runningOperationId = topic.metadata?.runningOperation?.operationId;+ if (!runningOperationId || runningOperationId !== input.operationId) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: 'No matching running operation found on this topic',+ });+ }++ const aiAgentService = new AiAgentService(db, share.ownerId, {+ includeShareVisitor: true,+ workspaceId: share.workspaceId ?? undefined,+ });++ return { aiAgentService, share };+};++export const runControlRouter = router({+ /**+ * Resolve an intervention (approve / reject / answer / skip / stop) parked on+ * the VISITOR's own share run β the visitor counterpart of+ * `aiAgent.resolveAgentInterventionBySource`. A share run is approved by the+ * visitor: granting a tool to visitors grants its normal approval flow.+ *+ * The visitor must own `topicId` under this live share; the business slot+ * then binds the durable batch to exactly this creator/agent/topic and a+ * share-run operation, so a visitor can never resolve anyone else's run and+ * the owner can never resolve a visitor's run through their own endpoints.+ * The continuation is dispatched under a `shareGate` rebuilt from the live+ * share row (see {@link createShareRunScope}).+ *+ * `unavailable` means the deployment has no durable intervention store (OSS);+ * the client then falls back to `execAgent`'s legacy `resume*` payloads.+ */+ resolveInterventionBySource: shareChatProcedure+ .input(+ ResolveAgentInterventionBySourceSchema.extend({+ shareId: z.string(),+ topicId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { shareId, topicId, ...source } = input;+ const share = await resolveLinkShareOrThrow(ctx.serverDB, shareId, ctx.userId);+ const { dispatchContext, topicModel } = await createShareRunScope(+ ctx.serverDB,+ share,+ ctx.userId,+ );+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId,+ visitorUserId: ctx.userId,+ });++ // A server-side `remember` writes the OWNER's allow list, so a visitor+ // may only approve once here; their "don't ask again" goes to their own+ // allow list client-side (see `approveToolCalling`).+ if (source.action.type === 'approve_tool' && source.action.scope === 'remember') {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Visitors can only approve once' });+ }++ log(+ 'resolveInterventionBySource: share=%s visitor=%s topic=%s operation=%s action=%s',+ shareId,+ ctx.userId,+ topicId,+ source.operationId,+ source.action.type,+ );++ const resolution = await resolveAgentInterventionBySource({+ ...source,+ actorUserId: ctx.userId,+ shareVisitor: { agentId: share.agentId, ownerUserId: share.ownerId, topicId },+ workspaceId: share.workspaceId ?? undefined,+ }).catch((error: unknown) => {+ throw mapAgentInterventionTRPCError(error);+ });++ if (!resolution.handled) {+ return {+ contractVersion: 2 as const,+ status: 'unavailable' as const,+ success: false as const,+ };+ }+ if (resolution.state === 'already_resolved') {+ return {+ contractVersion: 2 as const,+ state: resolution.state,+ status: resolution.status,+ success: true as const,+ };+ }++ try {+ const dispatch = await dispatchClaimedAgentIntervention(resolution, dispatchContext);+ return {+ contractVersion: 2 as const,+ ...(dispatch.execution && { execution: toClientExecAgentResult(dispatch.execution) }),+ state: resolution.state,+ status: dispatch.status,+ success: true as const,+ };+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('resolveInterventionBySource', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),+ /**+ * Stop the visitor's own parked run from its pending approval card β the+ * visitor counterpart of `aiAgent.stopPendingApproval`, used when the+ * deployment has no durable intervention store (OSS) or the rows predate it.+ * `InterventionController.stopPendingApproval` re-checks that the operation+ * is the parked owner of `topicId` and every message belongs to it.+ */+ stopPendingApproval: shareChatProcedure+ .input(+ ShareTopicScopeSchema.extend({+ batchId: z.string().min(1),+ operationId: z.string().min(1),+ toolMessageIds: z.array(z.string()).min(1),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);+ const { aiAgentService, dispatchContext, messageModel, topicModel } =+ await createShareRunScope(ctx.serverDB, share, ctx.userId);+ await findVisitorTopicOrThrow(topicModel, {+ agentId: share.agentId,+ topicId: input.topicId,+ visitorUserId: ctx.userId,+ });++ const stopPlugins = await pMap(+ input.toolMessageIds,+ (id) => messageModel.findMessagePlugin(id),+ { concurrency: 5 },+ );+ const hasGenericSource = stopPlugins.every(+ (plugin) =>+ Boolean(plugin?.toolCallId) &&+ plugin?.intervention?.operationId === input.operationId &&+ plugin.intervention.batchId === input.batchId,+ );+ if (hasGenericSource) {+ const sourceResolution = await resolveAgentInterventionBySource({+ action: { scope: 'operation', type: 'stop' },+ actorUserId: ctx.userId,+ batchId: input.batchId,+ operationId: input.operationId,+ resolutionRequestId: randomUUID(),+ shareVisitor: {+ agentId: share.agentId,+ ownerUserId: share.ownerId,+ topicId: input.topicId,+ },+ targets: stopPlugins.map((plugin, index) => ({+ toolCallId: plugin!.toolCallId!,+ toolMessageId: input.toolMessageIds[index],+ })),+ workspaceId: share.workspaceId ?? undefined,+ }).catch((error: unknown) => {+ throw mapAgentInterventionTRPCError(error);+ });+ if (sourceResolution.handled) {+ if (sourceResolution.state === 'already_resolved') {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'This approval has already been resolved.',+ });+ }+ try {+ await dispatchClaimedAgentIntervention(sourceResolution, dispatchContext);+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('stopPendingApproval', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ return {+ operationId: input.operationId,+ settledToolMessageIds: input.toolMessageIds,+ success: true,+ };+ }+ }++ try {+ return await aiAgentService.stopPendingApproval({+ batchId: input.batchId,+ operationId: input.operationId,+ toolMessageIds: input.toolMessageIds,+ topicId: input.topicId,+ });+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('stopPendingApproval', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),+ /**+ * Interrupt a running share operation β the visitor counterpart of+ * `aiAgent.interruptTask`. Visitors have no owner-scoped access to+ * `aiAgent.interruptTask` (its models are scoped to the caller, and share+ * runs execute under the CREATOR's identity), so without this endpoint a+ * visitor's Stop / tab-close cannot reach the server: the run keeps streaming+ * and consuming the creator's budget until it finishes on its own.+ *+ * Authorization is intentionally stricter than `execAgent`/`getMessages`;+ * see {@link authorizeVisitorRunningOperation}.+ */+ interruptTask: shareChatProcedure+ .input(ShareTopicScopeSchema.extend({ operationId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const { aiAgentService, share } = await authorizeVisitorRunningOperation(+ ctx.serverDB,+ ctx.userId,+ input,+ );++ log(+ 'interruptTask: share=%s visitor=%s topic=%s operation=%s',+ input.shareId,+ ctx.userId,+ input.topicId,+ input.operationId,+ );++ try {+ return await aiAgentService.interruptTask({+ operationId: input.operationId,+ topicId: input.topicId,+ });+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('interruptTask', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),+ /**+ * The visitor counterpart of `aiAgent.setQueuedMessages`: a visitor can queue+ * follow-ups behind a share run too, and needs the same early hand-back.+ * Authorized exactly like `interruptTask`.+ */+ setQueuedMessages: shareChatProcedure+ .input(ShareTopicScopeSchema.extend({ operationId: z.string(), pending: z.boolean() }))+ .mutation(async ({ input, ctx }) => {+ const { aiAgentService, share } = await authorizeVisitorRunningOperation(+ ctx.serverDB,+ ctx.userId,+ input,+ );++ log(+ 'setQueuedMessages: share=%s visitor=%s topic=%s operation=%s pending=%s',+ input.shareId,+ ctx.userId,+ input.topicId,+ input.operationId,+ input.pending,+ );++ try {+ return await aiAgentService.setQueuedMessages({+ operationId: input.operationId,+ pending: input.pending,+ });+ } catch (error: any) {+ if (error instanceof TRPCError) throw error;++ throw toVisitorSafeStartupError('setQueuedMessages', error, {+ showErrorDetails: share.shareConfig.showErrorDetails,+ });+ }+ }),+});diff --git a/apps/server/src/routers/lambda/shareChat/runScope.ts b/apps/server/src/routers/lambda/shareChat/runScope.tsnew file mode 100644index 00000000000..436b3152edd--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/runScope.ts@@ -0,0 +1,77 @@+import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import { UserModel } from '@/database/models/user';+import type { LobeChatDatabase } from '@/database/type';+import { AiAgentService } from '@/server/services/aiAgent';+import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';++import { type AgentInterventionDispatchContext } from '../aiAgent';+import type { resolveLinkShareOrThrow } from './guards';++type LinkShare = Awaited<ReturnType<typeof resolveLinkShareOrThrow>>;++/**+ * Everything a share VISITOR run executes with: the creator-scoped service and+ * models (the run's rows are written under the creator's identity) plus the+ * `shareGate` that strips whatever the share config does not grant.+ *+ * Built fresh from the live share row on every call β a fresh turn and an+ * intervention continuation alike β so a continuation is gated by the share's+ * CURRENT config, never by a snapshot taken when the run parked.+ */+export const createShareRunScope = async (+ db: LobeChatDatabase,+ share: LinkShare,+ visitorUserId: string,+) => {+ const workspaceId = share.workspaceId ?? undefined;+ const modelOptions = { includeShareVisitor: true } as const;+ const topicModel = new TopicModel(db, share.ownerId, workspaceId, undefined, modelOptions);+ const messageModel = new MessageModel(db, share.ownerId, workspaceId, undefined, modelOptions);++ const shareGate: AgentShareGate = {+ agentId: share.agentId,+ shareConfig: share.shareConfig,+ // See `AgentShareGate.shareId`'s JSDoc β the share instance this run is+ // authorized against, and the token every later revalidation compares.+ shareId: share.shareId,+ visitorUserId,+ };++ // Creator's Market access token, mirroring aiAgentProcedure β the+ // server-side tool runtime authenticates against the Market API with it.+ let marketAccessToken: string | undefined;+ if (!share.workspaceId) {+ try {+ const userModel = new UserModel(db, share.ownerId);+ const settings = await userModel.getUserSettings();+ marketAccessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService falls back to trustedClientToken+ }+ }++ const aiAgentService = new AiAgentService(db, share.ownerId, {+ // Share visitor turns persist under the creator's `userId` β the+ // service's internal `messageModel`/`topicModel`/runtime must be+ // constructed with the visitor scope so reads/writes on+ // `topics.senderId <> NULL` rows aren't filtered out.+ includeShareVisitor: true,+ marketAccessToken,+ workspaceId,+ });++ /**+ * Dispatch context for an intervention the VISITOR resolved: the actor is+ * the visitor, the continuation runs as the creator under `shareGate`.+ */+ const dispatchContext: AgentInterventionDispatchContext = {+ aiAgentService,+ serverDB: db,+ shareGate,+ userId: visitorUserId,+ workspaceId: share.workspaceId,+ };++ return { aiAgentService, dispatchContext, messageModel, shareGate, topicModel };+};diff --git a/apps/server/src/routers/lambda/shareChat/upload.ts b/apps/server/src/routers/lambda/shareChat/upload.tsnew file mode 100644index 00000000000..aa073a4ea35--- /dev/null+++ b/apps/server/src/routers/lambda/shareChat/upload.ts@@ -0,0 +1,369 @@+import {+ AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE,+ SHARE_UPLOAD_STORAGE_BLOCK_PREFIX,+ SHARE_VISITOR_MAX_FILE_SIZE,+} from '@lobechat/const';+import { agentShareFileAccessScope } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import { TRPCError } from '@trpc/server';+import debug from 'debug';+import { z } from 'zod';++import { serverDBEnv } from '@/config/db';+import { AgentShareModel } from '@/database/models/agentShare';+import { FileModel } from '@/database/models/file';+import { FileUploadModel } from '@/database/models/fileUpload';+import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { FileS3 } from '@/server/modules/S3';+import { FileService } from '@/server/services/file';+import { FileUploadService } from '@/server/services/fileUpload';+import { reserveUpload } from '@/server/services/fileUploadReservation';++import { resolveLinkShareOrThrow } from './guards';+import { shareChatProcedure } from './procedures';++const log = debug('lobe-server:router:shareChat');++/**+ * Storage key prefix for a share's visitor uploads, under the CREATOR's file+ * namespace. The prefix is what ties an upload session / file row back to a+ * specific share on the settle and abort paths: a visitor can only complete or+ * release reservations that live under their share's prefix, never one of the+ * creator's own uploads.+ */+const shareUploadPrefix = (share: {+ ownerId: string;+ shareId: string;+ workspaceId: string | null;+}) =>+ share.workspaceId+ ? `files/workspaces/${share.workspaceId}/agent-share/${share.shareId}/`+ : `files/${share.ownerId}/agent-share/${share.shareId}/`;++/**+ * Visitor-facing storage refusal, one shape for two causes: the share's own+ * `maxFileStorage` cap (`share_limit`), or the creator's account-level block+ * from the deployment's upload check (`creator_quota`). The latter's original+ * reason describes the creator's billing state; it is collapsed here because+ * a stranger with the link must not learn it, and the visitor's remedy is the+ * same either way. The client matches only the prefix.+ */+const shareStorageBlocked = (cause: 'creator_quota' | 'share_limit') =>+ new TRPCError({ code: 'FORBIDDEN', message: `${SHARE_UPLOAD_STORAGE_BLOCK_PREFIX}${cause}` });++const toVisitorStorageBlock = (error: unknown) => {+ if (+ error instanceof TRPCError &&+ error.code === 'FORBIDDEN' &&+ error.message.startsWith(SHARE_UPLOAD_STORAGE_BLOCK_PREFIX) &&+ error.message !== `${SHARE_UPLOAD_STORAGE_BLOCK_PREFIX}share_limit`+ ) {+ log('creator storage block collapsed for visitor: %s', error.message);+ return shareStorageBlocked('creator_quota');+ }+ return error;+};++/** Basename only β a visitor-supplied name must not steer the storage key. */+const sanitizeUploadName = (name: string) =>+ name+ .replaceAll(/[/\\]/g, '_')+ .replaceAll(/\p{Cc}/gu, '')+ .trim() || 'file';++/**+ * Metadata a visitor may attach to their upload β the same intrinsic+ * image/audio facts the owner upload path records client-side, so share+ * attachments render (dimensions, duration) exactly like owner ones. Anything+ * else (notably `agentShare`) is server-written.+ */+const ShareUploadMetadataSchema = z+ .object({+ codec: z.string().max(64),+ durationMs: z.number().nonnegative(),+ height: z.number().positive(),+ mimeType: z.string().max(255),+ ratio: z.number().positive(),+ width: z.number().positive(),+ })+ .partial();++export const uploadRouter = router({+ /**+ * Release a share upload reservation the visitor abandoned (PUT failed or+ * was cancelled). Scoped to the share's own key prefix so a visitor cannot+ * release one of the creator's in-flight uploads.+ */+ abortUpload: shareChatProcedure+ .input(z.object({ pathname: z.string().min(1), shareId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);+ if (!input.pathname.startsWith(shareUploadPrefix(share))) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });+ }++ const fileUploadService = new FileUploadService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );+ const upload = await fileUploadService.findLatest(input.pathname);+ if (upload?.status === 'active') await fileUploadService.release(input.pathname);++ return { success: true };+ }),+ /**+ * Settle a share upload into a file row β the visitor counterpart of+ * `file.createFile`.+ *+ * The row is written under the CREATOR: share conversations are creator-owned+ * data (topics/messages already are), and the creator's storage quota is what+ * paid for the reservation in `createUploadUrl`. What makes it the visitor's+ * attachment rather than a creator resource is the server-written+ * `metadata.agentShare` provenance every share read/write path checks.+ *+ * Deliberately simpler than the owner path: no knowledge base / parent+ * folder / visibility, and no content hash at all. Every share upload is its+ * own object under its own reserved key, so the row must stay OUT of the+ * hash-keyed `global_files` dedup graph: a row registered there with a hash+ * some other file already holds would have its object skipped by the+ * refcount in `FileModel.delete` and orphaned in storage on `removeFile`+ * (with the visitor never able to see or free it), while its share-cap bytes+ * were released. A visitor attachment is only ever reached through the+ * message it was sent with, so nothing needs the hash.+ */+ createFile: shareChatProcedure+ .input(+ z.object({+ fileType: z.string().min(1).max(255),+ metadata: ShareUploadMetadataSchema.optional(),+ name: z.string().min(1).max(255),+ pathname: z.string().min(1),+ shareId: z.string(),+ size: z.number().int().min(0).max(SHARE_VISITOR_MAX_FILE_SIZE),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);+ if (!input.pathname.startsWith(shareUploadPrefix(share))) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Upload not found' });+ }++ const fileUploadService = new FileUploadService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );+ const fileService = new FileService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );++ // No legacy (reservation-less) path here: the share upload flow was born+ // with reservations, so a pathname without an active session is either+ // expired, already settled, or never ours.+ const activeUpload = await fileUploadService.touchActive(input.pathname);+ if (!activeUpload) {+ throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });+ }++ let actualSize: number;+ try {+ actualSize = (await fileService.getFileMetadata(input.pathname)).contentLength;+ } catch {+ await fileUploadService.releaseBestEffort(input.pathname);+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Uploaded file is unavailable' });+ }+ if (input.size !== activeUpload.size || actualSize !== activeUpload.size) {+ await fileUploadService.releaseBestEffort(input.pathname);+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Uploaded file size mismatch' });+ }++ const parts = input.pathname.split('/');+ const filename = parts.pop()!;+ const dirname = parts.join('/');++ const { id } = await ctx.serverDB.transaction(async (trx) => {+ // Transfer hard revocation locks this same Agent row before it snapshots+ // and deletes share files. Taking the lock first gives the two paths a+ // single order: if settlement wins, transfer sees and removes this+ // file; if transfer wins, the locked recheck below rejects the stale+ // share before a new file row can escape the cleanup snapshot.+ const tx = trx as LobeChatDatabase;+ const lockedAgent = await AgentShareModel.lockScopedAgentRow(tx, share.agentId, {+ userId: share.ownerId,+ workspaceId: share.workspaceId ?? undefined,+ });+ if (+ !lockedAgent ||+ !(await AgentShareModel.isRunStillAuthorized(tx, {+ agentId: share.agentId,+ shareId: share.shareId,+ }))+ ) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Share not found' });+ }++ const lockedUpload = await fileUploadService.model.findLatestByPathnameForUpdate(+ input.pathname,+ trx,+ );+ if (lockedUpload?.id !== activeUpload.id || lockedUpload.status !== 'active') {+ throw new TRPCError({ code: 'CONFLICT', message: 'Upload session is no longer active' });+ }++ const file = await new FileModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ ).create(+ {+ fileType: input.fileType,+ metadata: {+ ...input.metadata,+ agentShare: { shareId: share.shareId, visitorUserId: ctx.userId },+ date: new Date().toISOString().slice(0, 10),+ dirname,+ filename,+ path: input.pathname,+ },+ name: sanitizeUploadName(input.name),+ size: actualSize,+ url: input.pathname,+ },+ false,+ trx,+ );++ const settled = await fileUploadService.model.settle(lockedUpload.id, file.id, trx);+ if (!settled) {+ throw new TRPCError({ code: 'CONFLICT', message: 'Upload could not be settled' });+ }+ return file;+ });++ log('createFile: share=%s visitor=%s file=%s', input.shareId, ctx.userId, id);++ return { id, url: await fileService.getFileAccessUrl({ id, url: input.pathname }) };+ }),+ /**+ * Reserve storage and mint a pre-signed PUT for a visitor attachment β the+ * visitor counterpart of `upload.createS3PreSignedUrl`.+ *+ * The reservation is taken under the CREATOR: the bytes count against the+ * creator's storage quota, so it is the creator's `storage_block:*` reason+ * (not the visitor's plan) that decides whether the upload is admitted. The+ * key lives under the share's own prefix so `createFile` / `abortUpload` can+ * prove the session belongs to this share.+ */+ createUploadUrl: shareChatProcedure+ .input(+ z.object({+ name: z.string().min(1).max(255),+ shareId: z.string(),+ // `min(1)` is load-bearing beyond validation: the reservation runs the+ // size through the deployment's upload check AS THE CREATOR, so a+ // visitor-supplied negative size must never reach it β and a zero-byte+ // reservation adds nothing to the cap sum, so it would let unbounded+ // rows (and objects) pile up under the creator's prefix.+ size: z.number().int().min(1).max(SHARE_VISITOR_MAX_FILE_SIZE),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const maxFileStorage =+ share.shareConfig.maxFileStorage ?? AGENT_SHARE_DEFAULT_MAX_FILE_STORAGE;+ // Cheap pre-check before any storage round-trip; the real, race-free+ // check is `admit` below. `<= 0` is the creator turning attachments off+ // and refuses regardless of size.+ if (maxFileStorage <= 0 || input.size > maxFileStorage) {+ throw shareStorageBlocked('share_limit');+ }++ const prefix = shareUploadPrefix(share);+ const pathname = `${prefix}${nanoid()}/${sanitizeUploadName(input.name)}`;+ const s3 = new FileS3();+ const uploadModel = new FileUploadModel(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ );+ const fileModel = new FileModel(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined);++ try {+ await reserveUpload({+ // The share's own cap: settled visitor files plus every live+ // reservation under the share prefix, counted inside the reservation+ // transaction. The counts alone are not race-free (the reservation's+ // own row lock comes after this hook), so the decision is serialized+ // per share first β see `AgentShareModel.lockUploadAdmission`.+ admit: async (transaction) => {+ await AgentShareModel.lockUploadAdmission(transaction, share.shareId);+ const settled = await fileModel.countAgentShareUsage(share.shareId, transaction);+ const reserved = await uploadModel.countLiveUsageUnderPrefix(prefix, transaction);+ if (settled + reserved + input.size > maxFileStorage) {+ throw shareStorageBlocked('share_limit');+ }+ },+ clientIp: ctx.clientIp ?? undefined,+ db: ctx.serverDB,+ model: uploadModel,+ pathname,+ size: input.size,+ storage: s3,+ userId: share.ownerId,+ workspaceId: share.workspaceId,+ });+ } catch (error) {+ throw toVisitorStorageBlock(error);+ }++ try {+ return { pathname, url: await s3.createPreSignedUrl(pathname, input.size) };+ } catch (error) {+ await new FileUploadService(+ ctx.serverDB,+ share.ownerId,+ share.workspaceId ?? undefined,+ ).releaseBestEffort(pathname);+ throw error;+ }+ }),+ /**+ * Drop a share upload the visitor removed from their draft before sending.+ * Only the uploading visitor's own share files qualify (provenance check),+ * and only while no message references the row β once sent, the attachment+ * is part of a creator-owned conversation and stays put.+ *+ * Share rows are created outside `global_files` (see `createFile`), so their+ * persisted provenance tells `FileModel` that the row owns its object.+ */+ removeFile: shareChatProcedure+ .input(z.object({ fileId: z.string().min(1).max(64), shareId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ const share = await resolveLinkShareOrThrow(ctx.serverDB, input.shareId, ctx.userId);++ const fileModel = new FileModel(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined);+ const accessScope = agentShareFileAccessScope({+ shareId: share.shareId,+ visitorUserId: ctx.userId,+ });+ const existing = await fileModel.findById(input.fileId, { accessScope });+ if (!existing) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });+ }++ const file = await fileModel.deleteUnreferenced(input.fileId, {+ accessScope,+ removeGlobalFile: serverDBEnv.REMOVE_GLOBAL_FILE,+ });+ if (!file) return;++ await new FileService(ctx.serverDB, share.ownerId, share.workspaceId ?? undefined).deleteFile(+ file.url!,+ );+ }),+});