@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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