Open History to see the last commit
1import type { AssetResource } from "@t3tools/contracts";
2import {
3 AssetAttachmentNotFoundError,
4 AssetSourceControlMediaUrlValidationError,
5 AssetPreviewTypeValidationError,
6 AssetProjectFaviconInspectionError,
7 AssetProjectFaviconNotFoundError,
8 AssetProjectFaviconResolutionError,
9 AssetSigningKeyLoadError,
10 AssetWorkspaceAssetInspectionError,
11 AssetWorkspaceAssetNotFoundError,
12 AssetWorkspaceContextNotFoundError,
13 AssetWorkspacePathValidationError,
14 AssetWorkspaceResolutionError,
15 AssetWorkspaceRootNormalizationError,
16 SOURCE_CONTROL_MEDIA_ASSET,
17 ThreadId,
18 NativeAppIconReference,
19 TurnItemId,
20} from "@t3tools/contracts";
21import {
22 hostPreviewMimeTypeFromExtension,
23 isWorkspaceAudioPreviewPath,
24 isWorkspacePreviewEntryPath,
25 isWorkspaceVideoPreviewPath,
26 WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
27} from "@t3tools/shared/filePreview";
28import {
29 IMAGE_DIMENSIONS_HEADER_BYTES,
30 readImageDimensions,
31 type ImageDimensions,
32} from "@t3tools/shared/imageDimensions";
33import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
34import {
35 isProjectFaviconPath,
36 PROJECT_FAVICON_FALLBACK_MARKER,
37} from "@t3tools/shared/projectFavicon";
38import { isNetworkPath } from "@t3tools/shared/path";
39import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
40import * as Clock from "effect/Clock";
41import * as Digest from "effect/crypto/Digest";
42import * as Effect from "effect/Effect";
43import * as Hex from "effect/encoding/Hex";
44import * as FileSystem from "effect/FileSystem";
45import * as Option from "effect/Option";
46import * as Path from "effect/Path";
47import * as Schema from "effect/Schema";
48import * as Stream from "effect/Stream";
49
50import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
51import * as AssetSigner from "./AssetSigner.ts";
52import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
53import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
54import * as ServerConfig from "../config.ts";
55import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
56import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
57import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
58import { isWithinRoot } from "../workspace/KnownWorkspaces.ts";
59import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
60import { toWslDrivePath } from "../workspace/wslDrivePath.ts";
61import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
62import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
63import { extractIcnsPng } from "./icns.ts";
64import { openMediaFile, readMediaFileHeader, type OpenMediaFile } from "./MediaFile.ts";
65import * as HostProcess from "@t3tools/shared/HostProcess";
66
67export const ASSET_ROUTE_PREFIX = "/api/assets";
68
69const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
70const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
71const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
72const PROJECT_FAVICON_VERSION_PREFIX = "v";
73const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
74const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
75// Use server-assigned attachment extensions, never client MIME types.
76const INLINE_PREVIEW_MIME_TYPES: Record<string, string> = {
77 svg: "image/svg+xml",
78 pdf: "application/pdf",
79 html: "text/html",
80 htm: "text/html",
81};
82const inlinePreviewMimeTypeForExtension = (extension: string) =>
83 INLINE_PREVIEW_MIME_TYPES[extension] ??
84 hostPreviewMimeTypeFromExtension(`.${extension}`) ??
85 undefined;
86const PREVIEW_ASSET_EXTENSIONS = new Set([
87 ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
88 // Keep HTML dependency grants independent of newly supported file viewers.
89 ".avif",
90 ".gif",
91 ".ico",
92 ".jpeg",
93 ".jpg",
94 ".png",
95 ".svg",
96 ".webp",
97 ".m4v",
98 ".mp4",
99 ".ogv",
100 ".webm",
101 ".aac",
102 ".flac",
103 ".m4a",
104 ".mp3",
105 ".oga",
106 ".ogg",
107 ".opus",
108 ".wav",
109 ".css",
110 ".js",
111 ".mjs",
112 ".otf",
113 ".ttf",
114 ".woff",
115 ".woff2",
116]);
117
118const AssetClaimsSchema = Schema.Union([
119 Schema.Struct({
120 version: Schema.Literal(1),
121 kind: Schema.Literal("workspace-file"),
122 workspaceRoot: Schema.String,
123 baseRelativePath: Schema.String,
124 expiresAt: Schema.Number,
125 }),
126 Schema.Struct({
127 version: Schema.Literal(1),
128 kind: Schema.Literal("workspace-file-exact"),
129 workspaceRoot: Schema.String,
130 relativePath: Schema.String,
131 expiresAt: Schema.Number,
132 }),
133 Schema.Struct({
134 version: Schema.Literal(1),
135 kind: Schema.Literal("media-file-exact"),
136 filePath: Schema.String,
137 download: Schema.optionalKey(Schema.Boolean),
138 device: Schema.String,
139 inode: Schema.String,
140 expiresAt: Schema.Number,
141 }),
142 Schema.Struct({
143 version: Schema.Literal(1),
144 kind: Schema.Literal("attachment"),
145 attachmentId: Schema.String,
146 download: Schema.optionalKey(Schema.Boolean),
147 fileName: Schema.optionalKey(Schema.String),
148 mimeType: Schema.optionalKey(Schema.String),
149 renderIntent: Schema.optionalKey(Schema.Literal("mcp-app")),
150 expiresAt: Schema.Number,
151 }),
152 Schema.Struct({
153 version: Schema.Literal(1),
154 kind: Schema.Literal("project-favicon"),
155 workspaceRoot: Schema.String,
156 relativePath: Schema.NullOr(Schema.String),
157 expiresAt: Schema.Number,
158 }),
159 Schema.Struct({
160 version: Schema.Literal(1),
161 kind: Schema.Literal("project-favicon-external"),
162 filePath: Schema.String,
163 expiresAt: Schema.Number,
164 }),
165 Schema.Struct({
166 version: Schema.Literal(1),
167 kind: Schema.Literal("native-app-icon"),
168 app: NativeAppIconReference,
169 expiresAt: Schema.Number,
170 }),
171 Schema.Struct({
172 version: Schema.Literal(1),
173 kind: Schema.Literal("tool-output-image"),
174 threadId: ThreadId,
175 itemId: TurnItemId,
176 index: Schema.Number,
177 expiresAt: Schema.Number,
178 }),
179 Schema.Struct({
180 version: Schema.Literal(1),
181 kind: Schema.Literal(SOURCE_CONTROL_MEDIA_ASSET),
182 /** A host's `fetchUrl`, narrowed at mint time; the signature is what keeps it there. */
183 url: Schema.String,
184 cwd: Schema.String,
185 repository: Schema.optionalKey(Schema.String),
186 expiresAt: Schema.Number,
187 }),
188]);
189type AssetClaims = typeof AssetClaimsSchema.Type;
190
191const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
192const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
193const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
194
195export type ResolvedAsset =
196 | {
197 readonly kind: "file";
198 readonly path: string;
199 readonly download?: boolean;
200 readonly fileName?: string;
201 readonly mimeType?: string;
202 readonly file?: OpenMediaFile;
203 readonly renderIntent?: "mcp-app";
204 }
205 | {
206 readonly kind: "bytes";
207 readonly bytes: Uint8Array;
208 readonly mimeType: string;
209 }
210 | {
211 readonly kind: "source-control-media";
212 readonly url: string;
213 readonly cwd: string;
214 readonly repository?: string;
215 readonly expiresAt: number;
216 };
217
218function decodeClaims(encodedPayload: string): AssetClaims | null {
219 try {
220 return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
221 } catch {
222 return null;
223 }
224}
225
226function decodeRelativePath(value: string): string | null {
227 try {
228 return decodeURIComponent(value);
229 } catch {
230 return null;
231 }
232}
233
234export const readMcpAppHtml = Effect.fn("AssetAccess.readMcpAppHtml")(function* (filePath: string) {
235 const fileSystem = yield* FileSystem.FileSystem;
236 // Allow space for stored CSP tags, but bound reads if the attachment grows after minting.
237 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
238 const chunks = yield* Stream.runCollect(fileSystem.stream(filePath, { bytesToRead: limit + 1 }));
239 const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
240 if (size > limit) return null;
241 const bytes = new Uint8Array(size);
242 let position = 0;
243 for (const chunk of chunks) {
244 bytes.set(chunk, position);
245 position += chunk.byteLength;
246 }
247 return bytes;
248});
249
250const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {
251 readonly threadId: ThreadId;
252 readonly itemId: TurnItemId;
253 readonly index: number;
254}) {
255 const orchestrator = yield* Orchestrator.OrchestratorV2;
256 const item = yield* orchestrator.getTurnItem(input);
257 const image =
258 item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;
259 return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH
260 ? null
261 : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };
262});
263
264// Browsers cannot draw .icns; serve its embedded PNG.
265const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* (
266 filePath: string,
267) {
268 if (!filePath.toLowerCase().endsWith(".icns")) {
269 return { kind: "file", path: filePath } satisfies ResolvedAsset;
270 }
271 const fileSystem = yield* FileSystem.FileSystem;
272 const bytes = yield* fileSystem.readFile(filePath).pipe(
273 Effect.tapError((cause) =>
274 Effect.logError("Failed to read project icon image.", { filePath, cause }),
275 ),
276 Effect.orElseSucceed(() => null),
277 );
278 const png = bytes ? extractIcnsPng(bytes, PROJECT_FAVICON_ICNS_MIN_SIZE) : null;
279 return png
280 ? ({ kind: "bytes", bytes: png, mimeType: "image/png" } satisfies ResolvedAsset)
281 : null;
282});
283
284const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (
285 filePath: string,
286) {
287 const fileSystem = yield* FileSystem.FileSystem;
288 const canonicalFile = yield* ProjectFaviconResolver.optionOnNotFound(
289 fileSystem.realPath(filePath),
290 );
291 if (Option.isNone(canonicalFile)) return null;
292
293 const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile.value));
294 if (Option.isNone(info) || info.value.type !== "File") return null;
295 const isServerInternalPath = yield* makeIsServerInternalPath;
296 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
297});
298
299const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
300 function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
301 const fileSystem = yield* FileSystem.FileSystem;
302 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
303 const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(
304 Effect.asSome,
305 Effect.catchTags({
306 WorkspacePathOutsideRootError: () => Effect.succeedNone,
307 }),
308 );
309 if (Option.isNone(resolved)) return null;
310
311 const [canonicalRoot, canonicalFile] = yield* Effect.all([
312 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),
313 ProjectFaviconResolver.optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),
314 ]);
315 if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;
316
317 const path = yield* Path.Path;
318 const relative = path.relative(canonicalRoot.value, canonicalFile.value);
319 if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
320
321 const info = yield* ProjectFaviconResolver.optionOnNotFound(
322 fileSystem.stat(canonicalFile.value),
323 );
324 if (Option.isNone(info) || info.value.type !== "File") return null;
325 const isServerInternalPath = yield* makeIsServerInternalPath;
326 return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
327 },
328);
329
330const resolveCanonicalWorkspaceFileForRequest = (input: {
331 readonly workspaceRoot: string;
332 readonly relativePath: string;
333}) =>
334 resolveCanonicalWorkspaceFile(input).pipe(
335 Effect.tapError((cause) =>
336 Effect.logError("Failed to resolve canonical asset path.", {
337 workspaceRoot: input.workspaceRoot,
338 relativePath: input.relativePath,
339 cause,
340 }),
341 ),
342 Effect.orElseSucceed(() => null),
343 );
344
345const HEADER_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp"]);
346
347const readImageDimensionsFromOpenFile = (filePath: string, file: OpenMediaFile) =>
348 readMediaFileHeader(filePath, file, IMAGE_DIMENSIONS_HEADER_BYTES).pipe(
349 Effect.map(readImageDimensions),
350 Effect.orElseSucceed((): ImageDimensions | null => null),
351 );
352
353// Non-blocking open prevents swapped-in FIFOs from hanging the request.
354const readImageDimensionsFromHeader = (filePath: string) =>
355 openMediaFile(filePath).pipe(
356 Effect.flatMap((file) =>
357 file === null ? Effect.succeed(null) : readImageDimensionsFromOpenFile(filePath, file),
358 ),
359 Effect.scoped,
360 Effect.orElseSucceed((): ImageDimensions | null => null),
361 );
362
363const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMediaFileAsset")(
364 function* (input: {
365 readonly requestedPath: string;
366 readonly expectedCanonicalPath?: string;
367 readonly workspaceRoot: string | undefined;
368 readonly resource: AssetResource;
369 readonly expiresAt: number;
370 }) {
371 const path = yield* Path.Path;
372 // Resolving a network path makes Windows sign in to its host with the
373 // user's NTLM credentials, so only the thread's own project may be on a share.
374 // Windows reads a `\\?\` path as written, `..` included, so the lookup gets
375 // the resolved path this check approved.
376 const requestedPath = path.resolve(input.requestedPath);
377 if (
378 isNetworkPath(input.requestedPath) &&
379 (input.workspaceRoot === undefined ||
380 !isWithinRoot(path, requestedPath, path.resolve(input.workspaceRoot)))
381 ) {
382 return yield* new AssetWorkspaceAssetNotFoundError({
383 resource: input.resource,
384 checkedPath: input.requestedPath,
385 });
386 }
387 const canonicalFile = yield* resolveCanonicalFile(requestedPath).pipe(
388 Effect.mapError(
389 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
390 ),
391 );
392 // The workspace caller pins its containment-checked path; never follow a
393 // replacement symlink to a different file during this second resolution.
394 if (
395 !canonicalFile ||
396 (input.expectedCanonicalPath !== undefined && canonicalFile !== input.expectedCanonicalPath)
397 ) {
398 return yield* new AssetWorkspaceAssetNotFoundError({
399 resource: input.resource,
400 checkedPath: input.requestedPath,
401 });
402 }
403 const download =
404 input.resource._tag === "media-file" && input.resource.disposition === "attachment";
405 if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) {
406 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
407 }
408 const wantsDimensions = HEADER_IMAGE_EXTENSIONS.has(path.extname(canonicalFile).toLowerCase());
409 const opened = yield* openMediaFile(canonicalFile).pipe(
410 Effect.flatMap((file) =>
411 file === null
412 ? Effect.succeed(null)
413 : Effect.map(
414 wantsDimensions
415 ? readImageDimensionsFromOpenFile(canonicalFile, file)
416 : Effect.succeed(null),
417 (dimensions) => ({
418 identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
419 fileRevision: `${file.info.dev}:${file.info.ino}:${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
420 dimensions,
421 }),
422 ),
423 ),
424 Effect.scoped,
425 Effect.mapError(
426 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
427 ),
428 );
429 if (!opened) {
430 return yield* new AssetWorkspaceAssetNotFoundError({
431 resource: input.resource,
432 checkedPath: input.requestedPath,
433 });
434 }
435 return {
436 claims: {
437 version: 1 as const,
438 kind: "media-file-exact" as const,
439 filePath: canonicalFile,
440 ...(download ? { download: true } : {}),
441 ...opened.identity,
442 expiresAt: input.expiresAt,
443 },
444 fileName: path.basename(canonicalFile),
445 fileRevision: opened.fileRevision,
446 imageDimensions: opened.dimensions,
447 };
448 },
449);
450
451const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileAsset")(
452 function* (input: {
453 readonly workspaceRoot: string;
454 readonly requestedPath: string;
455 readonly resource: AssetResource;
456 readonly expiresAt: number;
457 }) {
458 const path = yield* Path.Path;
459 const fileSystem = yield* FileSystem.FileSystem;
460 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
461 const relativePath = path.isAbsolute(input.requestedPath)
462 ? path.relative(input.workspaceRoot, input.requestedPath)
463 : input.requestedPath;
464 const resolved = yield* workspacePaths
465 .resolveRelativePathWithinRoot({ workspaceRoot: input.workspaceRoot, relativePath })
466 .pipe(
467 Effect.mapError(
468 (cause) =>
469 new AssetWorkspacePathValidationError({
470 resource: input.resource,
471 cause,
472 }),
473 ),
474 );
475 const isDraftMedia =
476 input.resource._tag === "draft-workspace-file" &&
477 (isWorkspaceAudioPreviewPath(resolved.relativePath) ||
478 isWorkspaceVideoPreviewPath(resolved.relativePath));
479 if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) {
480 return yield* new AssetPreviewTypeValidationError({
481 resource: input.resource,
482 });
483 }
484 const canonicalFile = yield* resolveCanonicalWorkspaceFile({
485 workspaceRoot: input.workspaceRoot,
486 relativePath: resolved.relativePath,
487 }).pipe(
488 Effect.mapError(
489 (cause) =>
490 new AssetWorkspaceAssetInspectionError({
491 resource: input.resource,
492 cause,
493 }),
494 ),
495 );
496 if (!canonicalFile) {
497 return yield* new AssetWorkspaceAssetNotFoundError({
498 resource: input.resource,
499 });
500 }
501 if (isDraftMedia) {
502 return yield* finalizeAbsoluteMediaFileAsset({
503 ...input,
504 requestedPath: canonicalFile,
505 expectedCanonicalPath: canonicalFile,
506 });
507 }
508 const canonicalWorkspaceRoot = yield* fileSystem.realPath(input.workspaceRoot).pipe(
509 Effect.mapError(
510 (cause) =>
511 new AssetWorkspaceResolutionError({
512 resource: input.resource,
513 cause,
514 }),
515 ),
516 );
517 const imageDimensions = HEADER_IMAGE_EXTENSIONS.has(
518 path.extname(resolved.relativePath).toLowerCase(),
519 )
520 ? yield* readImageDimensionsFromHeader(canonicalFile)
521 : null;
522 return {
523 claims: !/\.html?$/i.test(resolved.relativePath)
524 ? {
525 version: 1 as const,
526 kind: "workspace-file-exact" as const,
527 workspaceRoot: canonicalWorkspaceRoot,
528 relativePath: resolved.relativePath,
529 expiresAt: input.expiresAt,
530 }
531 : {
532 version: 1 as const,
533 kind: "workspace-file" as const,
534 workspaceRoot: canonicalWorkspaceRoot,
535 baseRelativePath: path.dirname(resolved.relativePath),
536 expiresAt: input.expiresAt,
537 },
538 fileName: path.basename(resolved.relativePath),
539 imageDimensions,
540 fileRevision: undefined,
541 };
542 },
543);
544
545export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
546 readonly resource: AssetResource;
547 readonly workspaceRoot?: string;
548 readonly projectFaviconPath?: string;
549 /** Where a cloned project's checkout stands, while the clone tracker still knows it. */
550 readonly projectCheckout?: "pending" | "cloned";
551}) {
552 const fileSystem = yield* FileSystem.FileSystem;
553 const path = yield* Path.Path;
554 const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
555 let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
556 let claims: AssetClaims;
557 let fileName: string;
558 let sourcePath: string | undefined;
559 let imageDimensions: ImageDimensions | null = null;
560 let fileRevision: string | undefined;
561
562 switch (input.resource._tag) {
563 case "media-file": {
564 let requestedPath = expandHomePath(
565 yield* toWslDrivePath(input.resource.path),
566 yield* HostProcess.HomeDirectory,
567 );
568 if (!path.isAbsolute(requestedPath)) {
569 if (!input.workspaceRoot) {
570 return yield* new AssetWorkspaceContextNotFoundError({ resource: input.resource });
571 }
572 const workspaceRoot = yield* workspacePaths
573 .normalizeWorkspaceRoot(input.workspaceRoot)
574 .pipe(
575 Effect.mapError(
576 (cause) =>
577 new AssetWorkspaceRootNormalizationError({ resource: input.resource, cause }),
578 ),
579 );
580 requestedPath = path.resolve(workspaceRoot, requestedPath);
581 }
582 const finalized = yield* finalizeAbsoluteMediaFileAsset({
583 requestedPath,
584 workspaceRoot: input.workspaceRoot,
585 resource: input.resource,
586 expiresAt,
587 });
588 claims = finalized.claims;
589 fileName = finalized.fileName;
590 imageDimensions = finalized.imageDimensions;
591 fileRevision = finalized.fileRevision;
592 break;
593 }
594 case "workspace-file": {
595 if (!input.workspaceRoot) {
596 return yield* new AssetWorkspaceContextNotFoundError({
597 resource: input.resource,
598 });
599 }
600 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(
601 Effect.mapError(
602 (cause) =>
603 new AssetWorkspaceRootNormalizationError({
604 resource: input.resource,
605 cause,
606 }),
607 ),
608 );
609 const finalized = yield* finalizeWorkspaceFileAsset({
610 workspaceRoot,
611 requestedPath: input.resource.path,
612 resource: input.resource,
613 expiresAt,
614 });
615 claims = finalized.claims;
616 fileName = finalized.fileName;
617 imageDimensions = finalized.imageDimensions;
618 break;
619 }
620 case "draft-workspace-file": {
621 const draftWorkspaceRoot = input.workspaceRoot ?? input.resource.cwd;
622 const hostPath =
623 input.resource.path.startsWith("~/") || input.resource.path.startsWith("~\\")
624 ? expandHomePath(input.resource.path, yield* HostProcess.HomeDirectory)
625 : yield* toWslDrivePath(input.resource.path);
626 if (path.isAbsolute(hostPath)) {
627 const finalized = yield* finalizeAbsoluteMediaFileAsset({
628 requestedPath: hostPath,
629 workspaceRoot: draftWorkspaceRoot,
630 resource: input.resource,
631 expiresAt,
632 });
633 claims = finalized.claims;
634 fileName = finalized.fileName;
635 imageDimensions = finalized.imageDimensions;
636 fileRevision = finalized.fileRevision;
637 break;
638 }
639 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(draftWorkspaceRoot).pipe(
640 Effect.mapError(
641 (cause) =>
642 new AssetWorkspaceRootNormalizationError({
643 resource: input.resource,
644 cause,
645 }),
646 ),
647 );
648 const finalized = yield* finalizeWorkspaceFileAsset({
649 workspaceRoot,
650 requestedPath: input.resource.path,
651 resource: input.resource,
652 expiresAt,
653 });
654 claims = finalized.claims;
655 fileName = finalized.fileName;
656 imageDimensions = finalized.imageDimensions;
657 fileRevision = finalized.fileRevision;
658 break;
659 }
660 case "attachment": {
661 const config = yield* ServerConfig.ServerConfig;
662 const attachmentPath = resolveAttachmentPathById({
663 attachmentsDir: config.attachmentsDir,
664 attachmentId: input.resource.attachmentId,
665 });
666 if (!attachmentPath) {
667 return yield* new AssetAttachmentNotFoundError({
668 resource: input.resource,
669 });
670 }
671 const extension = parseAttachmentFileExtension(input.resource.attachmentId);
672 const isGenericFile = extension !== null;
673 const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
674 const isVideo = INLINE_VIDEO_MIME_TYPE_PATTERN.test(videoMimeType);
675 const inlinePreviewMimeType =
676 input.resource.disposition === "inline" && extension !== null
677 ? inlinePreviewMimeTypeForExtension(extension)
678 : undefined;
679 if (!isGenericFile) {
680 imageDimensions = yield* fileSystem.realPath(attachmentPath).pipe(
681 Effect.flatMap(readImageDimensionsFromHeader),
682 Effect.orElseSucceed(() => null),
683 );
684 }
685 claims = {
686 version: 1,
687 kind: "attachment",
688 attachmentId: input.resource.attachmentId,
689 ...(isGenericFile && !isVideo && inlinePreviewMimeType === undefined
690 ? { download: true }
691 : {}),
692 ...(input.resource.fileName !== undefined ? { fileName: input.resource.fileName } : {}),
693 ...(inlinePreviewMimeType !== undefined
694 ? { mimeType: inlinePreviewMimeType }
695 : input.resource.mimeType !== undefined
696 ? { mimeType: isVideo ? videoMimeType : input.resource.mimeType }
697 : {}),
698 ...(input.resource.renderIntent === "mcp-app" && inlinePreviewMimeType === "text/html"
699 ? { renderIntent: "mcp-app" as const }
700 : {}),
701 expiresAt,
702 };
703 fileName = input.resource.fileName ?? path.basename(attachmentPath);
704 break;
705 }
706 case "project-favicon": {
707 const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
708 Effect.mapError(
709 (cause) =>
710 new AssetWorkspaceRootNormalizationError({
711 resource: input.resource,
712 cause,
713 }),
714 ),
715 );
716 const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
717 // A lookup in a half-cloned checkout would cache a miss that outlives the clone.
718 // Once it lands, a miss cached before (by enrichment) is stale too.
719 if (input.projectCheckout === "cloned") yield* faviconResolver.invalidate(workspaceRoot);
720 const faviconPath =
721 input.projectCheckout === "pending"
722 ? null
723 : yield* faviconResolver
724 .resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
725 .pipe(
726 Effect.mapError(
727 (cause) =>
728 new AssetProjectFaviconResolutionError({
729 resource: input.resource,
730 cause,
731 }),
732 ),
733 );
734 const isExternalOverride =
735 faviconPath !== null &&
736 input.projectFaviconPath !== undefined &&
737 path.isAbsolute(input.projectFaviconPath) &&
738 path.normalize(faviconPath) === path.normalize(input.projectFaviconPath);
739 const relativePath =
740 faviconPath && !isExternalOverride ? path.relative(workspaceRoot, faviconPath) : null;
741 const sourceFaviconPath = isExternalOverride ? faviconPath : relativePath;
742 if (sourceFaviconPath && !isProjectFaviconPath(sourceFaviconPath)) {
743 return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
744 }
745 sourcePath = sourceFaviconPath ?? undefined;
746 const canonicalFaviconPath = sourceFaviconPath
747 ? yield* (
748 isExternalOverride
749 ? resolveCanonicalFile(sourceFaviconPath)
750 : resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath: sourceFaviconPath })
751 ).pipe(
752 Effect.mapError(
753 (cause) =>
754 new AssetProjectFaviconInspectionError({
755 resource: input.resource,
756 cause,
757 }),
758 ),
759 )
760 : null;
761 if (sourceFaviconPath && !canonicalFaviconPath) {
762 return yield* new AssetProjectFaviconNotFoundError({
763 resource: input.resource,
764 });
765 }
766 claims =
767 isExternalOverride && canonicalFaviconPath
768 ? {
769 version: 1,
770 kind: "project-favicon-external",
771 filePath: canonicalFaviconPath,
772 expiresAt,
773 }
774 : {
775 version: 1,
776 kind: "project-favicon",
777 workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(
778 Effect.mapError(
779 (cause) =>
780 new AssetWorkspaceResolutionError({
781 resource: input.resource,
782 cause,
783 }),
784 ),
785 ),
786 relativePath,
787 expiresAt,
788 };
789 if (sourceFaviconPath && canonicalFaviconPath) {
790 const digest = yield* Digest.Digest;
791 const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(
792 Effect.mapError(
793 (cause) =>
794 new AssetProjectFaviconInspectionError({
795 resource: input.resource,
796 cause,
797 }),
798 ),
799 );
800 const revision = yield* digest.digest(Digest.sha256, faviconBytes).pipe(
801 Effect.map(Hex.encode),
802 Effect.mapError(
803 (cause) =>
804 new AssetProjectFaviconInspectionError({
805 resource: input.resource,
806 cause,
807 }),
808 ),
809 );
810 fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(sourceFaviconPath)}`;
811 } else {
812 fileName = PROJECT_FAVICON_FALLBACK_MARKER;
813 }
814 break;
815 }
816 case "tool-output-image": {
817 const image = yield* readToolOutputImage(input.resource).pipe(
818 Effect.mapError(
819 (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),
820 ),
821 );
822 if (image === null) {
823 return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });
824 }
825 claims = {
826 version: 1,
827 kind: "tool-output-image",
828 threadId: input.resource.threadId,
829 itemId: input.resource.itemId,
830 index: input.resource.index,
831 expiresAt,
832 };
833 fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;
834 imageDimensions = readImageDimensions(image.bytes);
835 break;
836 }
837 case "native-app-icon": {
838 claims = {
839 version: 1,
840 kind: "native-app-icon",
841 app: input.resource.app,
842 expiresAt,
843 };
844 fileName = "native-app-icon.png";
845 break;
846 }
847 case SOURCE_CONTROL_MEDIA_ASSET: {
848 const media = sourceControlDefinitions.mediaUrl(input.resource.url);
849 if (media === null) {
850 return yield* new AssetSourceControlMediaUrlValidationError({});
851 }
852 const { _tag, ...resource } = input.resource;
853 claims = {
854 version: 1,
855 kind: SOURCE_CONTROL_MEDIA_ASSET,
856 ...resource,
857 url: media.fetchUrl,
858 expiresAt,
859 };
860 fileName = media.fileName;
861 break;
862 }
863 }
864
865 if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
866 const issuedAt = yield* Clock.currentTimeMillis;
867 expiresAt =
868 (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *
869 PROJECT_FAVICON_TOKEN_BUCKET_MS;
870 claims = { ...claims, expiresAt };
871 }
872 if (claims.kind === "attachment" && claims.mimeType === "text/html") {
873 // Stable URLs let immutable HTML reloads hit the cache; image retries need fresh URLs.
874 expiresAt =
875 Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
876 claims = { ...claims, expiresAt };
877 }
878 const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
879 const signer = yield* AssetSigner.AssetSigner;
880 const signature = yield* signer
881 .sign(encodedPayload)
882 .pipe(
883 Effect.mapError((cause) => new AssetSigningKeyLoadError({ resource: input.resource, cause })),
884 );
885 const token = `${encodedPayload}.${signature}`;
886 return {
887 relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
888 expiresAt,
889 ...(sourcePath !== undefined ? { sourcePath } : {}),
890 ...(imageDimensions !== null ? { imageDimensions } : {}),
891 ...(fileRevision !== undefined ? { fileRevision } : {}),
892 };
893});
894
895export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
896 token: string,
897 relativePath: string,
898) {
899 const [encodedPayload, signature] = token.split(".");
900 if (!encodedPayload || !signature) return null;
901
902 const signer = yield* AssetSigner.AssetSigner;
903 const verified = yield* signer.verify(encodedPayload, signature).pipe(
904 Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
905 Effect.orElseSucceed(() => false),
906 );
907 if (!verified) return null;
908
909 const claims = decodeClaims(encodedPayload);
910 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
911
912 if (claims.kind === "attachment") {
913 const config = yield* ServerConfig.ServerConfig;
914 const attachmentPath = resolveAttachmentPathById({
915 attachmentsDir: config.attachmentsDir,
916 attachmentId: claims.attachmentId,
917 });
918 if (!attachmentPath) return null;
919 const fileSystem = yield* FileSystem.FileSystem;
920 const info = yield* ProjectFaviconResolver.optionOnNotFound(
921 fileSystem.stat(attachmentPath),
922 ).pipe(
923 Effect.tapError((cause) =>
924 Effect.logError("Failed to inspect attachment asset.", {
925 attachmentId: claims.attachmentId,
926 path: attachmentPath,
927 cause,
928 }),
929 ),
930 Effect.orElseSucceed(() => Option.none()),
931 );
932 return Option.isSome(info) && info.value.type === "File"
933 ? ({
934 kind: "file",
935 path: attachmentPath,
936 ...(claims.download ? { download: true } : {}),
937 ...(claims.fileName !== undefined ? { fileName: claims.fileName } : {}),
938 ...(claims.mimeType !== undefined ? { mimeType: claims.mimeType } : {}),
939 ...(claims.renderIntent === "mcp-app" ? { renderIntent: "mcp-app" as const } : {}),
940 } satisfies ResolvedAsset)
941 : null;
942 }
943
944 if (claims.kind === "project-favicon") {
945 if (claims.relativePath === null) return null;
946 const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
947 workspaceRoot: claims.workspaceRoot,
948 relativePath: claims.relativePath,
949 });
950 return faviconPath ? yield* projectFaviconAsset(faviconPath) : null;
951 }
952
953 if (claims.kind === "project-favicon-external") {
954 const faviconPath = yield* resolveCanonicalFile(claims.filePath).pipe(
955 Effect.tapError((cause) =>
956 Effect.logError("Failed to resolve canonical asset path.", {
957 filePath: claims.filePath,
958 cause,
959 }),
960 ),
961 Effect.orElseSucceed(() => null),
962 );
963 return faviconPath === claims.filePath ? yield* projectFaviconAsset(faviconPath) : null;
964 }
965
966 if (claims.kind === SOURCE_CONTROL_MEDIA_ASSET) {
967 const { version: _version, ...media } = claims;
968 return { ...media, kind: "source-control-media" } satisfies ResolvedAsset;
969 }
970
971 if (claims.kind === "tool-output-image") {
972 const image = yield* readToolOutputImage(claims).pipe(
973 Effect.tapError((cause) =>
974 Effect.logError("Failed to read tool output image.", {
975 threadId: claims.threadId,
976 itemId: claims.itemId,
977 cause,
978 }),
979 ),
980 Effect.orElseSucceed(() => null),
981 );
982 return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;
983 }
984
985 if (claims.kind === "native-app-icon") {
986 const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;
987 const iconPath = yield* nativeAppIconResolver.resolve(claims.app);
988 return iconPath ? ({ kind: "file", path: iconPath } satisfies ResolvedAsset) : null;
989 }
990
991 const decodedPath = decodeRelativePath(relativePath);
992 if (decodedPath === null) return null;
993 const path = yield* Path.Path;
994 if (claims.kind === "media-file-exact") {
995 if (decodedPath !== path.basename(claims.filePath)) return null;
996 const canonicalFile = yield* resolveCanonicalFile(claims.filePath).pipe(
997 Effect.tapError((cause) =>
998 Effect.logError("Failed to resolve canonical media path.", {
999 filePath: claims.filePath,
1000 cause,
1001 }),
1002 ),
1003 Effect.orElseSucceed(() => null),
1004 );
1005 if (canonicalFile !== claims.filePath) return null;
1006 const mimeType = claims.download
1007 ? "application/octet-stream"
1008 : hostPreviewMimeTypeFromExtension(path.extname(canonicalFile));
1009 if (!mimeType) return null;
1010 const file = yield* openMediaFile(canonicalFile, claims).pipe(
1011 Effect.tapError((cause) =>
1012 Effect.logError("Failed to open canonical media file.", { filePath: canonicalFile, cause }),
1013 ),
1014 Effect.orElseSucceed(() => null),
1015 );
1016 return file
1017 ? ({
1018 kind: "file",
1019 path: canonicalFile,
1020 mimeType,
1021 file,
1022 ...(claims.download ? { download: true, fileName: path.basename(canonicalFile) } : {}),
1023 } satisfies ResolvedAsset)
1024 : null;
1025 }
1026 if (claims.kind === "workspace-file-exact") {
1027 if (decodedPath !== path.basename(claims.relativePath)) return null;
1028 const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1029 workspaceRoot: claims.workspaceRoot,
1030 relativePath: claims.relativePath,
1031 });
1032 return exactWorkspaceFile
1033 ? ({ kind: "file", path: exactWorkspaceFile } satisfies ResolvedAsset)
1034 : null;
1035 }
1036 const segments = decodedPath.split(/[\\/]/);
1037 if (
1038 decodedPath.length === 0 ||
1039 decodedPath.includes("\0") ||
1040 segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
1041 !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
1042 ) {
1043 return null;
1044 }
1045 const joinedRelativePath =
1046 claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
1047 const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({
1048 workspaceRoot: claims.workspaceRoot,
1049 relativePath: joinedRelativePath,
1050 });
1051 return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
1052});