import { WorkspaceArtifactRequestedTools, type McpConnectionAccountBinding, type AppServerManifest, type SiteAssetManifest, type ToolGatewayIdentity, type WorkspaceArtifact, type WorkspaceArtifactDetailResponse, type WorkspaceArtifactEvent, type WorkspaceArtifactMutationResponse, type WorkspaceArtifactVersion, } from "@opengeni/contracts"; import { parseVerifiedAttemptToolCatalog } from "@opengeni/codemode"; import { and, desc, eq, lt, or, sql } from "drizzle-orm"; import { isDeepStrictEqual } from "node:util"; import type { Database } from "./database"; import { withRlsContext, withWorkspaceRls, withWorkspaceSubjectRls } from "./database"; import * as schema from "./schema"; import { hydrateStoredAttemptToolCatalog } from "./session-content-blobs"; import { parseAcceptedMcpAccountBindings } from "./mcp-account-bindings"; import { sameSitePublicationRequest, sitePublicationRequest } from "./site-publication-request"; type ArtifactRow = typeof schema.workspaceArtifacts.$inferSelect; /** * Who is reading Sites: the person, or the person an agent acts for. They see * every workspace Site plus their own Only me Sites. Null (keys, services and * runs without a person) sees workspace Sites only. Every read and mutation * takes one, so no path can skip the audience. */ export type WorkspaceArtifactViewer = { subjectId: string | null }; /** Internal replay reads of an operation the caller already proved it owns. */ const OPERATION_REPLAY = Symbol("operation-replay"); function visibleTo(viewer: WorkspaceArtifactViewer) { return viewer.subjectId === null ? eq(schema.workspaceArtifacts.visibility, "workspace_shared") : or( eq(schema.workspaceArtifacts.visibility, "workspace_shared"), eq(schema.workspaceArtifacts.ownerSubjectId, viewer.subjectId), )!; } /** Any exact publication from this session establishes the Site association. */ export async function hasWorkspaceArtifactSessionLink( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, sessionId: string, artifactId: string, ): Promise { return withWorkspaceRls(db, workspaceId, async (scoped) => { const rows = await scoped .select({ id: schema.workspaceArtifacts.id }) .from(schema.workspaceArtifacts) .where( and( eq(schema.workspaceArtifacts.workspaceId, workspaceId), eq(schema.workspaceArtifacts.id, artifactId), visibleTo(viewer), sql`exists (select 1 from ${schema.workspaceArtifactVersions} as published_version where published_version.artifact_id = ${schema.workspaceArtifacts.id} and published_version.workspace_id = ${schema.workspaceArtifacts.workspaceId} and published_version.source_session_id = ${sessionId}::uuid)`, ), ) .limit(1); return rows.length === 1; }); } /** Validate a published Site identity without loading its HTML or version history. */ export async function getWorkspaceSiteSessionOrigin( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, siteId: string, versionId: string, ): Promise<{ siteId: string; title: string; revision: number }> { return withWorkspaceRls(db, workspaceId, async (scoped) => { const [origin] = await scoped .select({ siteId: schema.workspaceArtifacts.id, title: schema.workspaceArtifacts.title, revision: schema.workspaceArtifactVersions.revision, }) .from(schema.workspaceArtifacts) .innerJoin( schema.workspaceArtifactVersions, and( eq(schema.workspaceArtifactVersions.artifactId, schema.workspaceArtifacts.id), eq(schema.workspaceArtifactVersions.workspaceId, workspaceId), eq(schema.workspaceArtifactVersions.id, versionId), ), ) .where( and( eq(schema.workspaceArtifacts.workspaceId, workspaceId), eq(schema.workspaceArtifacts.id, siteId), visibleTo(viewer), ), ) .limit(1); if (!origin) throw new WorkspaceArtifactNotFoundError("App origin not found"); return origin; }); } export async function createWorkspaceArtifactUpload( db: Database, input: { accountId: string; workspaceId: string; ownerId: string; }, ) { return withRlsContext(db, input, async (scoped) => { const [row] = await scoped .insert(schema.workspaceArtifactUploads) .values({ ...input, expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), }) .returning(); return row!; }); } export async function getWorkspaceArtifactUpload(db: Database, workspaceId: string, id: string) { return withWorkspaceRls(db, workspaceId, async (scoped) => { const [row] = await scoped .select() .from(schema.workspaceArtifactUploads) .where( and( eq(schema.workspaceArtifactUploads.workspaceId, workspaceId), eq(schema.workspaceArtifactUploads.id, id), ), ); return row ?? null; }); } async function retainArtifactUpload(tx: Database, input: PublishMetadata) { if (!input.uploadId) return; const [row] = await tx .update(schema.workspaceArtifactUploads) .set({ status: "published" }) .where( and( eq(schema.workspaceArtifactUploads.workspaceId, input.workspaceId), eq(schema.workspaceArtifactUploads.id, input.uploadId), or( eq(schema.workspaceArtifactUploads.status, "published"), and( eq(schema.workspaceArtifactUploads.status, "pending"), sql`${schema.workspaceArtifactUploads.expiresAt} > now()`, ), ), ), ) .returning(); if (!row) throw new WorkspaceArtifactOperationError("App upload expired or unavailable"); } /** Claim expired uploads before deleting blobs; publication takes the same row lock. */ export async function expireWorkspaceArtifactUploads(db: Database, workspaceId: string) { return withWorkspaceRls(db, workspaceId, async (scoped) => scoped .update(schema.workspaceArtifactUploads) .set({ status: sql`CASE WHEN ${schema.workspaceArtifactUploads.status} = 'published' THEN 'published' ELSE 'expired' END`, }) .where( and( eq(schema.workspaceArtifactUploads.workspaceId, workspaceId), sql`${schema.workspaceArtifactUploads.expiresAt} < now()`, ), ) .returning(), ); } type VersionRow = typeof schema.workspaceArtifactVersions.$inferSelect; type EventRow = typeof schema.workspaceArtifactEvents.$inferSelect; type ArtifactMutationToolName = | "artifacts_create" | "artifacts_publish" | "artifacts_rollback" | "artifacts_archive" | "artifacts_restore" | "app_install" | "app_upgrade"; export class WorkspaceArtifactNotFoundError extends Error { readonly name = "WorkspaceArtifactNotFoundError"; } /** * Records that a person opened a Site in the console, for the order of their * own Site rows. Only a Site this viewer can see is recorded; the row grants * nothing. Repeated opens only move the time forward. */ export async function recordSiteOpened( db: Database, input: { workspaceId: string; subjectId: string; viewer: WorkspaceArtifactViewer; siteId: string; }, ): Promise<{ openedAt: string }> { return await withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (scoped) => { const [site] = await scoped .select({ accountId: schema.workspaceArtifacts.accountId }) .from(schema.workspaceArtifacts) .where( and( eq(schema.workspaceArtifacts.workspaceId, input.workspaceId), eq(schema.workspaceArtifacts.id, input.siteId), visibleTo(input.viewer), ), ) .limit(1); if (!site) throw new WorkspaceArtifactNotFoundError("App not found"); const [row] = await scoped .insert(schema.siteOpens) .values({ accountId: site.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, siteId: input.siteId, }) .onConflictDoUpdate({ target: [schema.siteOpens.workspaceId, schema.siteOpens.subjectId, schema.siteOpens.siteId], set: { openedAt: sql`greatest(${schema.siteOpens.openedAt}, now())` }, }) .returning({ openedAt: schema.siteOpens.openedAt }); // Opening a Site again brings an archived Site row back to the sidebar. await scoped .update(schema.siteSidebarStates) .set({ archivedAt: null, updatedAt: sql`now()` }) .where( and( eq(schema.siteSidebarStates.workspaceId, input.workspaceId), eq(schema.siteSidebarStates.subjectId, input.subjectId), eq(schema.siteSidebarStates.siteId, input.siteId), sql`${schema.siteSidebarStates.archivedAt} is not null`, ), ); return { openedAt: row!.openedAt.toISOString() }; }); } /** One person's sidebar state for one Site row. */ export type SiteSidebarState = { siteId: string; pinned: boolean; pinnedAt: string | null; archived: boolean; archivedAt: string | null; }; /** * Pins or archives a Site row in one person's sidebar. Personal like session * pins: it never changes the Site, its publication or its audience, and only * a Site this viewer can see is recorded. Archiving hides the row (and the * conversations listed under it) until it is restored or the Site is opened * again; a pin survives archive and returns with the row. Repeating a state * keeps its original time. */ export async function setSiteSidebarState( db: Database, input: { workspaceId: string; subjectId: string; viewer: WorkspaceArtifactViewer; siteId: string; pinned?: boolean | undefined; archived?: boolean | undefined; }, ): Promise { return await withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, async (scoped) => { const [site] = await scoped .select({ accountId: schema.workspaceArtifacts.accountId }) .from(schema.workspaceArtifacts) .where( and( eq(schema.workspaceArtifacts.workspaceId, input.workspaceId), eq(schema.workspaceArtifacts.id, input.siteId), visibleTo(input.viewer), ), ) .limit(1); if (!site) throw new WorkspaceArtifactNotFoundError("App not found"); const stamp = (next: boolean | undefined, column: "pinned_at" | "archived_at") => next === undefined ? sql.raw(`site_sidebar_states.${column}`) : next ? sql.raw(`coalesce(site_sidebar_states.${column}, now())`) : sql`null`; const [row] = await scoped .insert(schema.siteSidebarStates) .values({ accountId: site.accountId, workspaceId: input.workspaceId, subjectId: input.subjectId, siteId: input.siteId, pinnedAt: input.pinned ? sql`now()` : null, archivedAt: input.archived ? sql`now()` : null, }) .onConflictDoUpdate({ target: [ schema.siteSidebarStates.workspaceId, schema.siteSidebarStates.subjectId, schema.siteSidebarStates.siteId, ], set: { pinnedAt: stamp(input.pinned, "pinned_at"), archivedAt: stamp(input.archived, "archived_at"), updatedAt: sql`now()`, }, }) .returning({ pinnedAt: schema.siteSidebarStates.pinnedAt, archivedAt: schema.siteSidebarStates.archivedAt, }); return { siteId: input.siteId, pinned: row!.pinnedAt !== null, pinnedAt: row!.pinnedAt?.toISOString() ?? null, archived: row!.archivedAt !== null, archivedAt: row!.archivedAt?.toISOString() ?? null, }; }); } export class WorkspaceArtifactConflictError extends Error { readonly name = "WorkspaceArtifactConflictError"; constructor( message: string, readonly currentVersionId: string | null = null, ) { super(message); } } export class WorkspaceArtifactOperationError extends Error { readonly name = "WorkspaceArtifactOperationError"; } /** The Site is visible to the caller, but only its owner may do this. */ export class WorkspaceArtifactOwnerRequiredError extends Error { readonly name = "WorkspaceArtifactOwnerRequiredError"; } function iso(value: Date | string): string { return (value instanceof Date ? value : new Date(value)).toISOString(); } function versionFromRow(row: VersionRow): WorkspaceArtifactVersion { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, artifactId: row.artifactId, revision: row.revision, contentType: "text/html", contentSha256: row.contentSha256, sizeBytes: row.sizeBytes, sourceSha256: row.sourceSha256, sourceSizeBytes: row.sourceSizeBytes, requestedTools: WorkspaceArtifactRequestedTools.parse(row.requestedTools), sourceSessionId: row.sourceSessionId, sourceTurnId: row.sourceTurnId, sourceAttemptId: row.sourceAttemptId, sourceExecutionGeneration: row.sourceExecutionGeneration, createdBySubjectId: row.createdBySubjectId, createdAt: iso(row.createdAt), }; } function eventFromRow(row: EventRow): WorkspaceArtifactEvent { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, artifactId: row.artifactId, type: row.type, fromVersionId: row.fromVersionId, toVersionId: row.toVersionId, sourceSessionId: row.sourceSessionId, sourceTurnId: row.sourceTurnId, sourceAttemptId: row.sourceAttemptId, sourceExecutionGeneration: row.sourceExecutionGeneration, actorSubjectId: row.actorSubjectId, reason: row.reason, createdAt: iso(row.createdAt), }; } function artifactFromRow(row: ArtifactRow, version: VersionRow | null): WorkspaceArtifact { return { id: row.id, accountId: row.accountId, workspaceId: row.workspaceId, slug: row.slug, title: row.title, description: row.description, status: row.status, visibility: row.visibility === "user_private" ? "private" : "workspace", ownerSubjectId: row.ownerSubjectId, currentVersion: version ? versionFromRow(version) : null, createdBySubjectId: row.createdBySubjectId, createdAt: iso(row.createdAt), updatedAt: iso(row.updatedAt), }; } async function currentVersion(scopedDb: any, artifact: ArtifactRow): Promise { if (!artifact.currentVersionId) return null; const [row] = await scopedDb .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, artifact.workspaceId), eq(schema.workspaceArtifactVersions.id, artifact.currentVersionId), ), ) .limit(1); return row ?? null; } async function artifactRow( scopedDb: any, workspaceId: string, artifactId: string, viewer: WorkspaceArtifactViewer | typeof OPERATION_REPLAY, lock = false, ) { let query = scopedDb .select() .from(schema.workspaceArtifacts) .where( and( eq(schema.workspaceArtifacts.workspaceId, workspaceId), eq(schema.workspaceArtifacts.id, artifactId), ...(viewer === OPERATION_REPLAY ? [] : [visibleTo(viewer)]), ), ) .limit(1); if (lock) query = query.for("update"); const [row] = await query; return (row as ArtifactRow | undefined) ?? null; } /** Whether this viewer can see the Site at all, without loading its history. */ export async function isWorkspaceArtifactVisible( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, artifactId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ id: schema.workspaceArtifacts.id }) .from(schema.workspaceArtifacts) .where( and( eq(schema.workspaceArtifacts.workspaceId, workspaceId), eq(schema.workspaceArtifacts.id, artifactId), visibleTo(viewer), ), ) .limit(1); return row !== undefined; }); } export async function listWorkspaceArtifacts( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, options: { limit?: number; cursor?: string; status?: "active" | "archived"; sourceSessionId?: string; } = {}, ): Promise<{ artifacts: WorkspaceArtifact[]; nextCursor: string | null; truncated: boolean; }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const limit = Math.min(Math.max(options.limit ?? 50, 1), 100); const cursor = options.cursor ? decodeListCursor(options.cursor) : null; const visibility = and( eq(schema.workspaceArtifacts.workspaceId, workspaceId), visibleTo(viewer), ...(options.sourceSessionId ? [ sql`exists (select 1 from ${schema.workspaceArtifactVersions} as published_version where published_version.artifact_id = ${schema.workspaceArtifacts.id} and published_version.workspace_id = ${schema.workspaceArtifacts.workspaceId} and published_version.source_session_id = ${options.sourceSessionId}::uuid)`, ] : []), ...(options.status ? [eq(schema.workspaceArtifacts.status, options.status)] : []), ...(cursor ? [ or( lt(schema.workspaceArtifacts.updatedAt, cursor.updatedAt), and( eq(schema.workspaceArtifacts.updatedAt, cursor.updatedAt), lt(schema.workspaceArtifacts.id, cursor.id), ), ), ] : []), ); const rows = await scopedDb .select() .from(schema.workspaceArtifacts) .where(visibility) .orderBy(desc(schema.workspaceArtifacts.updatedAt), desc(schema.workspaceArtifacts.id)) .limit(limit + 1); const truncated = rows.length > limit; const pageRows = rows.slice(0, limit); const artifacts = await Promise.all( pageRows.map(async (row) => artifactFromRow(row, await currentVersion(scopedDb, row))), ); const tail = truncated ? pageRows.at(-1) : null; return { artifacts, nextCursor: tail ? encodeListCursor(tail) : null, truncated, }; }); } const artifactCursorId = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; function encodeListCursor(row: ArtifactRow): string { return Buffer.from(JSON.stringify([iso(row.updatedAt), row.id]), "utf8").toString("base64url"); } function decodeListCursor(value: string): { updatedAt: Date; id: string } { try { const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8")); if ( !Array.isArray(parsed) || parsed.length !== 2 || typeof parsed[0] !== "string" || typeof parsed[1] !== "string" || !artifactCursorId.test(parsed[1]) ) { throw new Error("invalid shape"); } const updatedAt = new Date(parsed[0]); if (!Number.isFinite(updatedAt.getTime())) throw new Error("invalid timestamp"); return { updatedAt, id: parsed[1] }; } catch { throw new WorkspaceArtifactOperationError("Invalid artifact list cursor"); } } export async function getWorkspaceArtifact( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, artifactId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const artifact = await artifactRow(scopedDb, workspaceId, artifactId, viewer); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); const [versionRows, eventRows, current] = await Promise.all([ scopedDb .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, workspaceId), eq(schema.workspaceArtifactVersions.artifactId, artifactId), ), ) .orderBy(desc(schema.workspaceArtifactVersions.revision)) .limit(101), scopedDb .select() .from(schema.workspaceArtifactEvents) .where( and( eq(schema.workspaceArtifactEvents.workspaceId, workspaceId), eq(schema.workspaceArtifactEvents.artifactId, artifactId), ), ) .orderBy(desc(schema.workspaceArtifactEvents.createdAt)) .limit(101), currentVersion(scopedDb, artifact), ]); return { artifact: artifactFromRow(artifact, current), versions: versionRows.slice(0, 100).map(versionFromRow), events: eventRows.slice(0, 100).map(eventFromRow), versionsTruncated: versionRows.length > 100, eventsTruncated: eventRows.length > 100, }; }); } /** * The Site and its current version alone, without its history: what an open * Site view checks every few seconds to see whether a new version is live. */ export async function getWorkspaceArtifactCurrent( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, artifactId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const artifact = await artifactRow(scopedDb, workspaceId, artifactId, viewer); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); return artifactFromRow(artifact, await currentVersion(scopedDb, artifact)); }); } export async function getWorkspaceArtifactContentRef( db: Database, workspaceId: string, viewer: WorkspaceArtifactViewer, artifactId: string, versionId?: string, ): Promise<{ artifactId: string; status: WorkspaceArtifact["status"]; version: WorkspaceArtifactVersion; contentKey: string; sourceKey: string | null; assetManifest: SiteAssetManifest | null; }> { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const artifact = await artifactRow(scopedDb, workspaceId, artifactId, viewer); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); const targetId = versionId ?? artifact.currentVersionId; if (!targetId) throw new WorkspaceArtifactNotFoundError("Artifact has no published version"); const [version] = await scopedDb .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, workspaceId), eq(schema.workspaceArtifactVersions.artifactId, artifactId), eq(schema.workspaceArtifactVersions.id, targetId), ), ) .limit(1); if (!version) throw new WorkspaceArtifactNotFoundError("Artifact version not found"); return { artifactId, status: artifact.status, version: versionFromRow(version), contentKey: version.contentKey, sourceKey: version.sourceKey, assetManifest: version.assetManifest ?? null, }; }); } /** * The asset manifest of one version, for the console's asset route. That * route has no signed-in caller (app frames send no credentials): the * version's unguessable token in the URL is the capability, checked by the * caller against this manifest. Null for an unknown version or a * single-file app. */ export async function getSiteVersionAssetManifest( db: Database, workspaceId: string, versionId: string, ): Promise { return await withWorkspaceRls(db, workspaceId, async (scopedDb) => { const [row] = await scopedDb .select({ assetManifest: schema.workspaceArtifactVersions.assetManifest }) .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, workspaceId), eq(schema.workspaceArtifactVersions.id, versionId), ), ) .limit(1); return row?.assetManifest ?? null; }); } type PublishMetadata = { uploadId?: string; accountId: string; workspaceId: string; contentKey: string; contentSha256: string | null; sizeBytes: number; sourceKey: string | null; sourceSha256: string | null; sourceSizeBytes: number | null; requestedTools?: ToolGatewayIdentity[]; /** Asset files of a multi-file build; omitted or null for a single-file app. */ assetManifest?: SiteAssetManifest | null; /** * App server code (docs/app-server-code.md): a new version's code, null to * remove it, or omitted to keep the current version's code (publish). */ serverManifest?: AppServerManifest | null; /** `requestedTools` as the caller declared them, before the server paired connector identities. */ declaredRequestedTools?: ToolGatewayIdentity[]; operationKey: string; actorSubjectId: string; sourceSessionId: string | null; sourceTurnId: string | null; sourceAttemptId: string | null; sourceExecutionGeneration: number | null; sourceToolName: ArtifactMutationToolName | null; persistContent: () => Promise; discardContent: () => Promise; }; async function discardPersistedArtifactContent( input: Pick, error: unknown, ): Promise { await input.discardContent().catch(() => undefined); throw error; } type ArtifactOperationReplay = NonNullable>>; function persistedArtifactContentIsReferenced( replay: ArtifactOperationReplay, input: Pick, ): boolean { return ( replay.version.contentKey === input.contentKey || (input.sourceKey !== null && replay.version.sourceKey === input.sourceKey) ); } async function reconcilePersistedArtifactMutation( db: Database, input: PublishMetadata, error: unknown, validateReplay: (replay: ArtifactOperationReplay) => void, ): Promise { let replay: ArtifactOperationReplay | null; try { replay = await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { await lockOperation(scopedDb, input.workspaceId, input.operationKey); return await replayForOperation(scopedDb, input.workspaceId, input.operationKey); }, ); } catch { // The transaction outcome is still unknown. Leaking an unreferenced object // is recoverable; deleting content that may have committed is not. throw error; } if (!replay) return await discardPersistedArtifactContent(input, error); try { validateReplay(replay); } catch (replayError) { if (!persistedArtifactContentIsReferenced(replay, input)) { await input.discardContent().catch(() => undefined); } throw replayError; } if (!persistedArtifactContentIsReferenced(replay, input)) { await input.discardContent().catch(() => undefined); } return mutationResult( replay.artifact, replay.version, replay.event, true, replay.current ?? replay.version, ); } async function assertAttemptAuthority( scopedDb: any, input: Pick< PublishMetadata, | "accountId" | "workspaceId" | "actorSubjectId" | "sourceSessionId" | "sourceTurnId" | "sourceAttemptId" | "sourceExecutionGeneration" | "sourceToolName" >, ): Promise { const provenance = [ input.sourceSessionId, input.sourceTurnId, input.sourceAttemptId, input.sourceExecutionGeneration, ]; if (provenance.every((value) => value === null)) return; if (provenance.some((value) => value === null) || input.sourceToolName === null) { throw new WorkspaceArtifactOperationError("Artifact attempt provenance is incomplete"); } const rows = (await scopedDb.execute(sql` WITH locked_workspace AS MATERIALIZED ( SELECT workspace.id, workspace.account_id FROM workspaces workspace WHERE workspace.id = ${input.workspaceId}::uuid AND workspace.account_id = ${input.accountId}::uuid FOR KEY SHARE OF workspace ), locked_session AS MATERIALIZED ( SELECT session.id, session.account_id, session.workspace_id, session.active_turn_id, session.first_party_mcp_tools, session.first_party_mcp_permissions FROM sessions session JOIN locked_workspace workspace ON workspace.id = session.workspace_id AND workspace.account_id = session.account_id WHERE session.id = ${input.sourceSessionId}::uuid AND session.active_turn_id = ${input.sourceTurnId}::uuid AND session.first_party_mcp_tools @> jsonb_build_array(${input.sourceToolName}::text) AND ( session.first_party_mcp_permissions IS NULL OR session.first_party_mcp_permissions @> '["artifacts:publish"]'::jsonb ) FOR NO KEY UPDATE OF session ), locked_turn AS MATERIALIZED ( -- The exact live attempt and the session's selected tool and permission -- are the authority. A run without a person (an owner-less scheduled -- task) writes the workspace's artifacts like any other run; the -- audience layer gives it no Only me owner. SELECT turn.id, turn.account_id, turn.workspace_id, turn.session_id, turn.active_attempt_id, turn.execution_generation FROM session_turns turn JOIN locked_session session ON session.id = turn.session_id AND session.workspace_id = turn.workspace_id AND session.account_id = turn.account_id WHERE turn.id = ${input.sourceTurnId}::uuid AND turn.active_attempt_id = ${input.sourceAttemptId}::uuid AND turn.execution_generation = ${input.sourceExecutionGeneration} AND turn.status IN ('running', 'requires_action', 'recovering', 'waiting_capacity') FOR UPDATE OF turn ), locked_attempt AS MATERIALIZED ( SELECT attempt.id, attempt.account_id, attempt.workspace_id, attempt.session_id, attempt.turn_id, attempt.execution_generation FROM session_turn_attempts attempt JOIN locked_turn turn ON turn.id = attempt.turn_id AND turn.session_id = attempt.session_id AND turn.workspace_id = attempt.workspace_id AND turn.account_id = attempt.account_id WHERE attempt.id = ${input.sourceAttemptId}::uuid AND attempt.execution_generation = ${input.sourceExecutionGeneration} AND attempt.state IN ('claimed', 'running') AND NOT EXISTS ( SELECT 1 FROM session_attempt_interruptions interruption WHERE interruption.workspace_id = attempt.workspace_id AND interruption.attempt_id = attempt.id AND interruption.state IN ('pending', 'delivered', 'acknowledged') ) FOR UPDATE OF attempt ) SELECT attempt.id FROM locked_session session JOIN locked_turn turn ON true JOIN locked_attempt attempt ON true `)) as unknown as Array<{ id: string }>; if (!rows[0]) { throw new WorkspaceArtifactOperationError( "Artifact mutation requires the exact active attempt, execution generation, and immutable human authority", ); } } type AttemptToolCatalogScope = Pick< PublishMetadata, | "accountId" | "workspaceId" | "sourceSessionId" | "sourceTurnId" | "sourceAttemptId" | "sourceExecutionGeneration" >; async function assertArtifactRequestedToolsInAttemptCatalog( scopedDb: any, input: AttemptToolCatalogScope, requestedTools: readonly ToolGatewayIdentity[], ): Promise { const missing = await requestedToolsMissingFromAttemptCatalog(scopedDb, input, requestedTools); if (missing.length > 0) throw new WorkspaceArtifactOperationError( "Artifact requested tools must be present in the exact attempt tool catalog", ); } /** * The requested tools an agent attempt may not declare: neither in its exact * tool catalog nor a connector identity paired with one of its own account * routes. Empty for a caller that is not an attempt. Throws when the * attempt's catalog can't be read. */ export async function artifactRequestedToolsMissingFromAttemptCatalog( db: Database, input: AttemptToolCatalogScope, requestedTools: readonly ToolGatewayIdentity[], ): Promise { if (input.sourceAttemptId === null || requestedTools.length === 0) return []; return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await requestedToolsMissingFromAttemptCatalog(scopedDb, input, requestedTools), ); } async function requestedToolsMissingFromAttemptCatalog( scopedDb: any, input: AttemptToolCatalogScope, requestedTools: readonly ToolGatewayIdentity[], ): Promise { if (input.sourceAttemptId === null || requestedTools.length === 0) return []; if ( input.sourceSessionId === null || input.sourceTurnId === null || input.sourceExecutionGeneration === null ) { throw new WorkspaceArtifactOperationError("Artifact attempt provenance is incomplete"); } const [row] = await scopedDb .select({ catalog: schema.sessionAttemptToolCatalogs.catalog, contentRefs: schema.sessionAttemptToolCatalogs.contentRefs, }) .from(schema.sessionAttemptToolCatalogs) .where( and( eq(schema.sessionAttemptToolCatalogs.accountId, input.accountId), eq(schema.sessionAttemptToolCatalogs.workspaceId, input.workspaceId), eq(schema.sessionAttemptToolCatalogs.sessionId, input.sourceSessionId), eq(schema.sessionAttemptToolCatalogs.turnId, input.sourceTurnId), eq(schema.sessionAttemptToolCatalogs.attemptId, input.sourceAttemptId), eq(schema.sessionAttemptToolCatalogs.executionGeneration, input.sourceExecutionGeneration), ), ) .limit(1); let allowed: Set; try { const catalog = parseVerifiedAttemptToolCatalog( row ? await hydrateStoredAttemptToolCatalog(scopedDb, row) : undefined, ); allowed = new Set(catalog.entries.map((entry) => toolIdentityKey(entry.identity))); } catch { throw new WorkspaceArtifactOperationError( "Artifact requested tool authority is unavailable for the exact attempt", ); } const missing = requestedTools.filter((identity) => !allowed.has(toolIdentityKey(identity))); if (missing.length === 0) return []; // A connector identity paired with one of the attempt's own account routes // (`account-`, which is all an agent sees) is the same tool: the // turn's frozen account bindings name the connector behind each route. const [turn] = await scopedDb .select({ bindings: schema.sessionTurns.mcpAccountBindings }) .from(schema.sessionTurns) .where( and( eq(schema.sessionTurns.workspaceId, input.workspaceId), eq(schema.sessionTurns.sessionId, input.sourceSessionId), eq(schema.sessionTurns.id, input.sourceTurnId), ), ) .limit(1); let bindings: McpConnectionAccountBinding[]; try { bindings = parseAcceptedMcpAccountBindings(turn?.bindings) ?? []; } catch { bindings = []; } const paired = (identity: ToolGatewayIdentity) => bindings.some( (binding) => binding.canonicalServerId === identity.serverId && allowed.has(toolIdentityKey({ serverId: binding.serverId, toolName: identity.toolName })), ); return missing.filter((identity) => !paired(identity)); } function toolIdentityKey(identity: ToolGatewayIdentity): string { return `${identity.serverId}\u0000${identity.toolName}`; } async function replayForOperation(scopedDb: any, workspaceId: string, operationKey: string) { const [event] = await scopedDb .select() .from(schema.workspaceArtifactEvents) .where( and( eq(schema.workspaceArtifactEvents.workspaceId, workspaceId), eq(schema.workspaceArtifactEvents.operationKey, operationKey), ), ) .limit(1); if (!event) return null; const artifact = await artifactRow(scopedDb, workspaceId, event.artifactId, OPERATION_REPLAY); if (!artifact) return null; const [version] = await scopedDb .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, workspaceId), eq(schema.workspaceArtifactVersions.id, event.toVersionId), ), ) .limit(1); if (!version) return null; let fromVersion: VersionRow | null = null; if (event.fromVersionId) { const [row] = await scopedDb .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, workspaceId), eq(schema.workspaceArtifactVersions.id, event.fromVersionId), ), ) .limit(1); fromVersion = row ?? null; } return { artifact, version, fromVersion, event, current: await currentVersion(scopedDb, artifact), } as const; } async function lockOperation(scopedDb: any, workspaceId: string, operationKey: string) { await scopedDb.execute( sql`SELECT pg_advisory_xact_lock(hashtextextended(${`${workspaceId}:${operationKey}`}, 0))`, ); } function assertCreateReplay(replay: Awaited>) { if ( !replay || replay.event.type !== "published" || replay.event.fromVersionId !== null || replay.version.revision !== 1 ) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for a different operation", ); } } function assertCreateReplayMatchesInput( replay: ArtifactOperationReplay, input: PublishMetadata & { slug: string; title: string; description: string | null; requestedSlug?: string | null; }, ): void { assertCreateReplay(replay); if (!sameSitePublicationRequest(replay.event.requestInput, input)) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for different publication input", ); } } function assertPublishReplay( replay: Awaited>, artifactId: string, expectedCurrentVersionId: string, ) { if ( !replay || replay.event.type !== "published" || replay.event.artifactId !== artifactId || replay.event.fromVersionId !== expectedCurrentVersionId ) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for a different operation", ); } } function assertPublishReplayMatchesInput( replay: ArtifactOperationReplay, input: PublishMetadata & { artifactId: string; expectedCurrentVersionId: string; }, ): void { assertPublishReplay(replay, input.artifactId, input.expectedCurrentVersionId); if (!sameSitePublicationRequest(replay.event.requestInput, input)) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for different publication input", ); } const expectedRequestedTools = input.requestedTools ?? replay.fromVersion?.requestedTools; if (!expectedRequestedTools) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for a publication with missing source authority", ); } } function assertRollbackReplay( replay: Awaited>, artifactId: string, versionId: string, expectedCurrentVersionId: string, reason: string, ) { if ( !replay || replay.event.type !== "rolled_back" || replay.event.artifactId !== artifactId || replay.event.toVersionId !== versionId || replay.event.fromVersionId !== expectedCurrentVersionId || replay.event.reason !== reason ) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for a different operation", ); } } function assertStatusReplay( replay: Awaited>, artifactId: string, status: "active" | "archived", expectedCurrentVersionId: string, reason: string, ) { const expectedType = status === "archived" ? "archived" : "restored"; if ( !replay || replay.event.type !== expectedType || replay.event.artifactId !== artifactId || replay.event.fromVersionId !== expectedCurrentVersionId || replay.event.toVersionId !== expectedCurrentVersionId || replay.event.reason !== reason ) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for a different operation", ); } } /** A Site the caller cannot see is indistinguishable from one that does not exist. */ async function requireVisibleArtifact( scopedDb: any, input: { workspaceId: string; artifactId: string; viewer: WorkspaceArtifactViewer }, ): Promise { if (!(await artifactRow(scopedDb, input.workspaceId, input.artifactId, input.viewer))) throw new WorkspaceArtifactNotFoundError("Artifact not found"); } function mutationResult( artifact: ArtifactRow, version: VersionRow, event: EventRow, replayed: boolean, displayedCurrentVersion: VersionRow = version, ): WorkspaceArtifactMutationResponse { return { artifact: artifactFromRow(artifact, displayedCurrentVersion), version: versionFromRow(version), event: eventFromRow(event), replayed, }; } export async function createWorkspaceArtifact( db: Database, input: PublishMetadata & { artifactId: string; slug: string; title: string; description: string | null; requestedSlug?: string | null; /** Who can see it; `user_private` needs an owner. */ visibility: "workspace_shared" | "user_private"; /** The person it is published for: the human caller or the human an agent acts for. */ ownerSubjectId: string | null; }, ): Promise { let contentPersisted = false; try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { await lockOperation(tx, input.workspaceId, input.operationKey); const replay = await replayForOperation(tx, input.workspaceId, input.operationKey); if (replay) { assertCreateReplayMatchesInput(replay, input); return mutationResult( replay.artifact, replay.version, replay.event, true, replay.current ?? replay.version, ); } await assertAttemptAuthority(tx, input); await retainArtifactUpload(tx, input); await assertArtifactRequestedToolsInAttemptCatalog(tx, input, input.requestedTools ?? []); await input.persistContent(); contentPersisted = true; const [artifact] = await tx .insert(schema.workspaceArtifacts) .values({ id: input.artifactId, accountId: input.accountId, workspaceId: input.workspaceId, slug: input.slug, title: input.title, description: input.description, createdBySubjectId: input.actorSubjectId, visibility: input.visibility, ownerSubjectId: input.ownerSubjectId, }) .returning(); const [version] = await tx .insert(schema.workspaceArtifactVersions) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, revision: 1, contentKey: input.contentKey, contentSha256: input.contentSha256, sizeBytes: input.sizeBytes, sourceKey: input.sourceKey, sourceSha256: input.sourceSha256, sourceSizeBytes: input.sourceSizeBytes, requestedTools: input.requestedTools ?? [], assetManifest: input.assetManifest ?? null, serverManifest: input.serverManifest ?? null, operationKey: input.operationKey, sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, createdBySubjectId: input.actorSubjectId, }) .returning(); const [updated] = await tx .update(schema.workspaceArtifacts) .set({ currentVersionId: version!.id, updatedAt: new Date(), }) .where(eq(schema.workspaceArtifacts.id, artifact!.id)) .returning(); const [event] = await tx .insert(schema.workspaceArtifactEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, type: "published", fromVersionId: null, toVersionId: version!.id, operationKey: input.operationKey, requestDigest: null, requestInput: sitePublicationRequest(input), sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, actorSubjectId: input.actorSubjectId, reason: "Initial publication", }) .returning(); return mutationResult(updated!, version!, event!, false); }); }, ); } catch (error) { if (contentPersisted) { return await reconcilePersistedArtifactMutation(db, input, error, (replay) => { assertCreateReplayMatchesInput(replay, input); }); } throw error; } } /** What a duplicate's receipt records, so a retry replays only the same request. */ function duplicateRequest(input: { sourceArtifactId: string; title?: string | undefined }) { return { duplicateOf: input.sourceArtifactId, title: input.title ?? null }; } /** * A new Site from a Site's current version. Stored Site content is immutable * and never collected per version, so the copy's first version references * the original's HTML and source objects instead of copying their bytes. * A retry with the same operation replays before the original is read again, * so later edits to the original cannot turn a committed copy into a conflict. */ export async function duplicateWorkspaceArtifact( db: Database, input: Pick< PublishMetadata, | "accountId" | "workspaceId" | "operationKey" | "actorSubjectId" | "sourceSessionId" | "sourceTurnId" | "sourceAttemptId" | "sourceExecutionGeneration" | "sourceToolName" > & { viewer: WorkspaceArtifactViewer; sourceArtifactId: string; artifactId: string; /** Omitted: `defaultTitle` of the original's title. */ title?: string; defaultTitle: (originalTitle: string) => string; slugFor: (title: string, artifactId: string) => string; /** Who can see the copy, from the original's visibility. */ resolveAudience: (visibility: WorkspaceArtifact["visibility"]) => Promise<{ visibility: "workspace_shared" | "user_private"; ownerSubjectId: string | null; }>; }, ): Promise { const request = duplicateRequest(input); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await lockOperation(tx, input.workspaceId, input.operationKey); const replay = await replayForOperation(tx, input.workspaceId, input.operationKey); if (replay) { if ( replay.event.type !== "published" || !isDeepStrictEqual(replay.event.requestInput, request) ) { throw new WorkspaceArtifactConflictError( "Idempotency key was already used for a different request", ); } return mutationResult( replay.artifact, replay.version, replay.event, true, replay.current ?? replay.version, ); } const original = await artifactRow( tx, input.workspaceId, input.sourceArtifactId, input.viewer, ); if (!original) throw new WorkspaceArtifactNotFoundError("Artifact not found"); const source = await currentVersion(tx, original); if (!source) throw new WorkspaceArtifactNotFoundError("Artifact has no published version"); const requestedTools = WorkspaceArtifactRequestedTools.parse(source.requestedTools); await assertAttemptAuthority(tx, input); await assertArtifactRequestedToolsInAttemptCatalog(tx, input, requestedTools); const audience = await input.resolveAudience( original.visibility === "user_private" ? "private" : "workspace", ); const title = input.title ?? input.defaultTitle(original.title); const [artifact] = await tx .insert(schema.workspaceArtifacts) .values({ id: input.artifactId, accountId: input.accountId, workspaceId: input.workspaceId, slug: input.slugFor(title, input.artifactId), title, description: original.description, createdBySubjectId: input.actorSubjectId, visibility: audience.visibility, ownerSubjectId: audience.ownerSubjectId, }) .returning(); const [version] = await tx .insert(schema.workspaceArtifactVersions) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, revision: 1, contentKey: source.contentKey, contentSha256: source.contentSha256, sizeBytes: source.sizeBytes, sourceKey: source.sourceKey, sourceSha256: source.sourceSha256, sourceSizeBytes: source.sourceSizeBytes, requestedTools, // The copy serves the same immutable files under its own version. assetManifest: source.assetManifest, // And the same server code (its files are content-addressed per workspace). serverManifest: source.serverManifest, operationKey: input.operationKey, sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, createdBySubjectId: input.actorSubjectId, }) .returning(); const [updated] = await tx .update(schema.workspaceArtifacts) .set({ currentVersionId: version!.id, updatedAt: new Date() }) .where(eq(schema.workspaceArtifacts.id, artifact!.id)) .returning(); const [event] = await tx .insert(schema.workspaceArtifactEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, type: "published", fromVersionId: null, toVersionId: version!.id, operationKey: input.operationKey, requestDigest: null, requestInput: request, sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, actorSubjectId: input.actorSubjectId, reason: `Duplicated from “${original.title}”`, }) .returning(); return mutationResult(updated!, version!, event!, false); }), ); } export async function publishWorkspaceArtifactVersion( db: Database, input: PublishMetadata & { artifactId: string; expectedCurrentVersionId: string; title?: string; description?: string | null; viewer: WorkspaceArtifactViewer; }, ): Promise { let contentPersisted = false; try { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { await lockOperation(tx, input.workspaceId, input.operationKey); await requireVisibleArtifact(tx, input); const replay = await replayForOperation(tx, input.workspaceId, input.operationKey); if (replay) { assertPublishReplayMatchesInput(replay, input); return mutationResult( replay.artifact, replay.version, replay.event, true, replay.current ?? replay.version, ); } await assertAttemptAuthority(tx, input); await retainArtifactUpload(tx, input); const artifact = await artifactRow( tx, input.workspaceId, input.artifactId, input.viewer, true, ); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); if (artifact.status !== "active") { throw new WorkspaceArtifactOperationError("Archived artifacts cannot be published"); } if (artifact.currentVersionId !== input.expectedCurrentVersionId) { throw new WorkspaceArtifactConflictError( "Artifact changed in another request", artifact.currentVersionId, ); } const current = await currentVersion(tx, artifact); if (!current) throw new WorkspaceArtifactNotFoundError("Artifact has no current version"); await assertArtifactRequestedToolsInAttemptCatalog( tx, input, input.requestedTools ?? current.requestedTools, ); const [latest] = await tx .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, input.workspaceId), eq(schema.workspaceArtifactVersions.artifactId, input.artifactId), ), ) .orderBy(desc(schema.workspaceArtifactVersions.revision)) .limit(1); await input.persistContent(); contentPersisted = true; const [version] = await tx .insert(schema.workspaceArtifactVersions) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, revision: (latest?.revision ?? 0) + 1, contentKey: input.contentKey, contentSha256: input.contentSha256, sizeBytes: input.sizeBytes, sourceKey: input.sourceKey, sourceSha256: input.sourceSha256, sourceSizeBytes: input.sourceSizeBytes, requestedTools: input.requestedTools ?? current.requestedTools, assetManifest: input.assetManifest ?? null, // Server code carries over unless this publish brings its own (or removes it). serverManifest: input.serverManifest === undefined ? (current.serverManifest ?? null) : input.serverManifest, operationKey: input.operationKey, sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, createdBySubjectId: input.actorSubjectId, }) .returning(); const update: Partial = { currentVersionId: version!.id, updatedAt: new Date(), }; if (input.title !== undefined) update.title = input.title; if (input.description !== undefined) update.description = input.description; const [updated] = await tx .update(schema.workspaceArtifacts) .set(update) .where(eq(schema.workspaceArtifacts.id, artifact.id)) .returning(); const [event] = await tx .insert(schema.workspaceArtifactEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, type: "published", fromVersionId: artifact.currentVersionId, toVersionId: version!.id, operationKey: input.operationKey, requestDigest: null, requestInput: sitePublicationRequest(input), sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, actorSubjectId: input.actorSubjectId, reason: `Published revision ${version!.revision}`, }) .returning(); return mutationResult(updated!, version!, event!, false); }); }, ); } catch (error) { if (contentPersisted) { return await reconcilePersistedArtifactMutation(db, input, error, (replay) => { assertPublishReplayMatchesInput(replay, input); }); } throw error; } } export async function rollbackWorkspaceArtifact( db: Database, input: Omit< PublishMetadata, | "contentKey" | "contentSha256" | "sizeBytes" | "sourceKey" | "sourceSha256" | "sourceSizeBytes" | "requestedTools" | "persistContent" | "discardContent" > & { artifactId: string; versionId: string; expectedCurrentVersionId: string; reason: string; viewer: WorkspaceArtifactViewer; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { return await scopedDb.transaction(async (tx) => { await lockOperation(tx, input.workspaceId, input.operationKey); await requireVisibleArtifact(tx, input); const replay = await replayForOperation(tx, input.workspaceId, input.operationKey); if (replay) { assertRollbackReplay( replay, input.artifactId, input.versionId, input.expectedCurrentVersionId, input.reason, ); return mutationResult( replay.artifact, replay.version, replay.event, true, replay.current ?? replay.version, ); } await assertAttemptAuthority(tx, input); const artifact = await artifactRow( tx, input.workspaceId, input.artifactId, input.viewer, true, ); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); if (artifact.status !== "active") { throw new WorkspaceArtifactOperationError("Archived artifacts cannot be rolled back"); } if (artifact.currentVersionId !== input.expectedCurrentVersionId) throw new WorkspaceArtifactConflictError( "Artifact changed in another request", artifact.currentVersionId, ); const [target] = await tx .select() .from(schema.workspaceArtifactVersions) .where( and( eq(schema.workspaceArtifactVersions.workspaceId, input.workspaceId), eq(schema.workspaceArtifactVersions.artifactId, input.artifactId), eq(schema.workspaceArtifactVersions.id, input.versionId), ), ) .limit(1); if (!target) throw new WorkspaceArtifactNotFoundError("Artifact version not found"); await assertArtifactRequestedToolsInAttemptCatalog(tx, input, target.requestedTools); const [updated] = await tx .update(schema.workspaceArtifacts) .set({ currentVersionId: target.id, updatedAt: new Date() }) .where(eq(schema.workspaceArtifacts.id, artifact.id)) .returning(); const [event] = await tx .insert(schema.workspaceArtifactEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, type: "rolled_back", fromVersionId: artifact.currentVersionId, toVersionId: target.id, operationKey: input.operationKey, sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, actorSubjectId: input.actorSubjectId, reason: input.reason, }) .returning(); return mutationResult(updated!, target, event!, false); }); }, ); } export async function setWorkspaceArtifactStatus( db: Database, input: Omit< PublishMetadata, | "contentKey" | "contentSha256" | "sizeBytes" | "sourceKey" | "sourceSha256" | "sourceSizeBytes" | "requestedTools" | "persistContent" | "discardContent" > & { artifactId: string; status: "active" | "archived"; expectedCurrentVersionId: string; reason: string; viewer: WorkspaceArtifactViewer; }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { await lockOperation(tx, input.workspaceId, input.operationKey); await requireVisibleArtifact(tx, input); const replay = await replayForOperation(tx, input.workspaceId, input.operationKey); if (replay) { assertStatusReplay( replay, input.artifactId, input.status, input.expectedCurrentVersionId, input.reason, ); return mutationResult( replay.artifact, replay.version, replay.event, true, replay.current ?? replay.version, ); } await assertAttemptAuthority(tx, input); const artifact = await artifactRow( tx, input.workspaceId, input.artifactId, input.viewer, true, ); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); if (artifact.currentVersionId !== input.expectedCurrentVersionId) { throw new WorkspaceArtifactConflictError( "Artifact changed in another request", artifact.currentVersionId, ); } const current = await currentVersion(tx, artifact); if (!current) throw new WorkspaceArtifactNotFoundError("Artifact has no current version"); if (input.status === "active") { await assertArtifactRequestedToolsInAttemptCatalog(tx, input, current.requestedTools); } if (artifact.status === input.status) { throw new WorkspaceArtifactOperationError( input.status === "archived" ? "Artifact is already archived" : "Artifact is already active", ); } const [updated] = await tx .update(schema.workspaceArtifacts) .set({ status: input.status, updatedAt: new Date() }) .where(eq(schema.workspaceArtifacts.id, artifact.id)) .returning(); const [event] = await tx .insert(schema.workspaceArtifactEvents) .values({ accountId: input.accountId, workspaceId: input.workspaceId, artifactId: input.artifactId, type: input.status === "archived" ? "archived" : "restored", fromVersionId: current.id, toVersionId: current.id, operationKey: input.operationKey, sourceSessionId: input.sourceSessionId, sourceTurnId: input.sourceTurnId, sourceAttemptId: input.sourceAttemptId, sourceExecutionGeneration: input.sourceExecutionGeneration, actorSubjectId: input.actorSubjectId, reason: input.reason, }) .returning(); return mutationResult(updated!, current, event!, false); }), ); } /** * Change who can see a Site. Only its owner can, and only while they can see * it; anyone else gets the same answer as for a Site that does not exist, or, * when the Site is shared with them, an owner-required refusal. Whether the * owner may make anything Only me is decided by the caller first. */ export async function updateWorkspaceArtifactVisibility( db: Database, input: { workspaceId: string; artifactId: string; viewer: WorkspaceArtifactViewer; visibility: "workspace_shared" | "user_private"; }, ): Promise { return await withWorkspaceRls(db, input.workspaceId, async (scopedDb) => { const artifact = await artifactRow( scopedDb, input.workspaceId, input.artifactId, input.viewer, true, ); if (!artifact) throw new WorkspaceArtifactNotFoundError("Artifact not found"); if (input.viewer.subjectId === null || artifact.ownerSubjectId !== input.viewer.subjectId) throw new WorkspaceArtifactOwnerRequiredError( "Only the person who owns this app can change who can see it", ); const [updated] = artifact.visibility === input.visibility ? [artifact] : await scopedDb .update(schema.workspaceArtifacts) .set({ visibility: input.visibility }) .where( and( eq(schema.workspaceArtifacts.workspaceId, input.workspaceId), eq(schema.workspaceArtifacts.id, artifact.id), ), ) .returning(); return artifactFromRow(updated!, await currentVersion(scopedDb, updated!)); }); }