Open History to see the last commit
1import type { ProviderUserInputAnswers, UserInputAttachments } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import { resolveAttachmentPath } from "../attachmentStore.ts";
6import { ProviderValidationError } from "./Errors.ts";
7
8const quoteReference = Schema.encodeSync(Schema.fromJsonString(Schema.String));
9
10/** Keep provider answer protocols unchanged; paths refer to files on the provider's server. */
11export const appendUserInputAttachmentPaths = Effect.fn("appendUserInputAttachmentPaths")(
12 function* (input: {
13 answers: ProviderUserInputAnswers;
14 attachmentsByQuestionId?: UserInputAttachments | undefined;
15 attachmentsDir: string;
16 }) {
17 const answers = new Map(Object.entries(input.answers));
18 const fs = yield* FileSystem.FileSystem;
19 for (const [questionId, attachments] of Object.entries(input.attachmentsByQuestionId ?? {})) {
20 if (attachments.length === 0) continue;
21 const references: string[] = [];
22 for (const attachment of attachments) {
23 const path = resolveAttachmentPath({ attachmentsDir: input.attachmentsDir, attachment });
24 if (
25 !path ||
26 !(yield* fs.exists(path).pipe(
27 Effect.mapError(
28 (cause) =>
29 new ProviderValidationError({
30 operation: "respondToUserInput",
31 issue: `Could not access attachment '${attachment.name}'.`,
32 cause,
33 }),
34 ),
35 ))
36 ) {
37 return yield* new ProviderValidationError({
38 operation: "respondToUserInput",
39 issue: `Attachment '${attachment.name}' is no longer available. Attach it again.`,
40 });
41 }
42 references.push(
43 `Attached ${attachment.type} ${quoteReference(attachment.name)}: ${quoteReference(path)}`,
44 );
45 }
46 const answer = answers.get(questionId);
47 const text = references.join("\n");
48 answers.set(
49 questionId,
50 Array.isArray(answer)
51 ? [...answer, text]
52 : typeof answer === "string" && answer.length > 0
53 ? `${answer}\n\n${text}`
54 : text,
55 );
56 }
57 return Object.fromEntries(answers);
58 },
59);