@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, 03:37 UTC

main
ts 258 lines 9.15 KB
Raw
1 import {
2 GUEST_PENDING_ATTACHMENT_BYTES_LIMIT,
3 GUEST_PENDING_MESSAGE_LIMIT,
4 GUEST_RESOLVED_MESSAGE_LIMIT,
5 type GuestMessageAttribution,
6 type GuestMessageId,
7 type OrchestrationMessageContext,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2ServerCommand,
10 type ThreadGuestMessage,
11 type ThreadGuestShare,
12 } from "@t3tools/contracts";
13 import * as DateTime from "effect/DateTime";
14 import * as Result from "effect/Result";
15
16 export type GuestShareCommand = Extract<
17 OrchestrationV2ServerCommand,
18 {
19 readonly type:
20 | "thread.guest-share.open"
21 | "thread.guest-share.redeem"
22 | "thread.guest-share.close"
23 | "thread.guest-message.submit"
24 | "thread.guest-message.dismiss";
25 }
26 >;
27
28 /** Failures a guest may be told about. Any other dispatch failure reaches them as "rejected". */
29 export const GUEST_FAILURE = {
30 inactive: "This guest link is no longer active.",
31 used: "This guest link was already used.",
32 busy: "Wait for the owner to answer your earlier messages.",
33 filesBusy: "Wait for the owner to answer your earlier messages before you attach more files.",
34 } as const;
35
36 const isExpired = (share: ThreadGuestShare, now: DateTime.Utc) =>
37 DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt);
38
39 const pendingAttachments = (share: ThreadGuestShare | null) =>
40 share?.messages.flatMap((message) =>
41 message.status === "pending" ? (message.attachments ?? []) : [],
42 ) ?? [];
43
44 /**
45 * Stored files a share change leaves behind: those of waiting messages that were dismissed or
46 * dropped with the share. A sent message keeps its files, which its thread message now holds.
47 */
48 export function releasedGuestAttachmentIds(
49 before: ThreadGuestShare | null,
50 after: ThreadGuestShare | null,
51 ): ReadonlyArray<string> {
52 const kept = new Set(
53 after !== null && after.id === before?.id
54 ? after.messages.flatMap((message) =>
55 message.status === "dismissed"
56 ? []
57 : (message.attachments ?? []).map((attachment) => attachment.id),
58 )
59 : [],
60 );
61 return pendingAttachments(before)
62 .map((attachment) => attachment.id)
63 .filter((id) => !kept.has(id));
64 }
65
66 /** Keeps every pending message and only the newest resolved ones. */
67 function trimResolved(messages: ReadonlyArray<ThreadGuestMessage>): Array<ThreadGuestMessage> {
68 let resolvedBudget = GUEST_RESOLVED_MESSAGE_LIMIT;
69 const kept: Array<ThreadGuestMessage> = [];
70 for (const message of messages.toReversed()) {
71 if (message.status !== "pending") {
72 if (resolvedBudget === 0) continue;
73 resolvedBudget -= 1;
74 }
75 kept.push(message);
76 }
77 return kept.toReversed();
78 }
79
80 const resolveMessage = (
81 share: ThreadGuestShare,
82 guestMessageId: GuestMessageId,
83 status: "sent" | "dismissed",
84 ): Result.Result<ThreadGuestShare, string> => {
85 const message = share.messages.find((candidate) => candidate.id === guestMessageId);
86 if (message === undefined || message.status !== "pending") {
87 return Result.fail(`Guest message ${guestMessageId} is not pending.`);
88 }
89 return Result.succeed({
90 ...share,
91 messages: trimResolved(
92 share.messages.map((candidate) =>
93 candidate.id === guestMessageId ? { ...candidate, status } : candidate,
94 ),
95 ),
96 });
97 };
98
99 /**
100 * Applies a guest share command to the thread. The orchestrator runs commands one at a time, so
101 * checking state here is what makes a link redeem once and a message send once.
102 */
103 export function decideGuestShareCommand(input: {
104 readonly thread: OrchestrationV2AppThread;
105 readonly command: GuestShareCommand;
106 readonly now: DateTime.Utc;
107 }): Result.Result<OrchestrationV2AppThread, string> {
108 const { thread, command, now } = input;
109 const share = thread.guestShare ?? null;
110 const withShare = (guestShare: ThreadGuestShare | null) =>
111 Result.succeed({ ...thread, guestShare, updatedAt: now });
112
113 switch (command.type) {
114 case "thread.guest-share.open": {
115 if (thread.archivedAt !== null) return Result.fail("Archived threads cannot be shared.");
116 if (share?.messages.some((message) => message.status === "pending")) {
117 return Result.fail("Answer or dismiss waiting guest messages before replacing this link.");
118 }
119 return withShare({
120 id: command.shareId,
121 host: command.host,
122 createdAt: DateTime.formatIso(now),
123 expiresAt: command.expiresAt,
124 guestName: null,
125 messages: [],
126 });
127 }
128 case "thread.guest-share.close":
129 return share === null ? Result.succeed(thread) : withShare(null);
130 case "thread.guest-share.redeem": {
131 if (share === null || share.id !== command.shareId || isExpired(share, now)) {
132 return Result.fail(GUEST_FAILURE.inactive);
133 }
134 if (share.guestName !== null) return Result.fail(GUEST_FAILURE.used);
135 return withShare({ ...share, guestName: command.guestName });
136 }
137 case "thread.guest-message.submit": {
138 if (
139 share === null ||
140 share.id !== command.shareId ||
141 share.guestName === null ||
142 isExpired(share, now)
143 ) {
144 return Result.fail(GUEST_FAILURE.inactive);
145 }
146 if (
147 share.messages.filter((message) => message.status === "pending").length >=
148 GUEST_PENDING_MESSAGE_LIMIT
149 ) {
150 return Result.fail(GUEST_FAILURE.busy);
151 }
152 const attachments = command.attachments ?? [];
153 const pendingBytes = [...pendingAttachments(share), ...attachments].reduce(
154 (total, attachment) => total + attachment.sizeBytes,
155 0,
156 );
157 if (attachments.length > 0 && pendingBytes > GUEST_PENDING_ATTACHMENT_BYTES_LIMIT) {
158 return Result.fail(GUEST_FAILURE.filesBusy);
159 }
160 const guestShare: ThreadGuestShare = {
161 ...share,
162 messages: trimResolved([
163 ...share.messages,
164 {
165 id: command.guestMessageId,
166 text: command.text,
167 status: "pending",
168 submittedAt: DateTime.formatIso(now),
169 ...(attachments.length === 0 ? {} : { attachments }),
170 },
171 ]),
172 };
173 // A request needs the owner, so a settled thread comes back as a new message brings it.
174 return thread.settledOverride === "settled"
175 ? Result.succeed({
176 ...thread,
177 guestShare,
178 settledOverride: null,
179 settledAt: null,
180 unsettledAt: now,
181 updatedAt: now,
182 })
183 : withShare(guestShare);
184 }
185 case "thread.guest-message.dismiss": {
186 if (share === null) return Result.fail("This thread has no guest link.");
187 return Result.map(resolveMessage(share, command.guestMessageId, "dismissed"), (next) => ({
188 ...thread,
189 guestShare: next,
190 updatedAt: now,
191 }));
192 }
193 }
194 }
195
196 /**
197 * Marks a guest message sent. `text` is what the agent receives: it names the guest so the agent
198 * does not mistake it for the owner's words, and so a guest cannot start a slash command.
199 * `guest` lets clients show the guest's own text with their name beside it.
200 */
201 export function decideGuestMessageSend(input: {
202 readonly thread: OrchestrationV2AppThread;
203 readonly guestMessageId: GuestMessageId;
204 readonly now: DateTime.Utc;
205 }): Result.Result<
206 {
207 readonly thread: OrchestrationV2AppThread;
208 readonly text: string;
209 readonly guest: GuestMessageAttribution;
210 },
211 string
212 > {
213 const share = input.thread.guestShare ?? null;
214 if (share === null) return Result.fail("This thread has no guest link.");
215 const message = share.messages.find((candidate) => candidate.id === input.guestMessageId);
216 const name = share.guestName ?? "Guest";
217 const guestText = message?.text ?? "";
218 return Result.map(resolveMessage(share, input.guestMessageId, "sent"), (next) => ({
219 thread: { ...input.thread, guestShare: next, updatedAt: input.now },
220 text: `Message from guest ${name}, sent by the owner:\n\n${guestText}`,
221 guest: { guestMessageId: input.guestMessageId, name, text: guestText, shareId: share.id },
222 }));
223 }
224
225 /**
226 * The owner cancelled a queued send, so the agent never got the message. It shows as dismissed,
227 * which the guest can see, instead of sent with no reply ever coming. A share that changed since
228 * the send is left alone.
229 */
230 export function guestShareAfterCancelledSend(
231 thread: OrchestrationV2AppThread,
232 guest: Pick<GuestMessageAttribution, "guestMessageId" | "shareId">,
233 now: DateTime.Utc,
234 ): OrchestrationV2AppThread {
235 const share = thread.guestShare ?? null;
236 if (share === null || share.id !== guest.shareId) return thread;
237 const message = share.messages.find((candidate) => candidate.id === guest.guestMessageId);
238 if (message?.status !== "sent") return thread;
239 return {
240 ...thread,
241 guestShare: {
242 ...share,
243 messages: share.messages.map((candidate) =>
244 candidate.id === guest.guestMessageId ? { ...candidate, status: "dismissed" } : candidate,
245 ),
246 },
247 updatedAt: now,
248 };
249 }
250
251 /** Guest attribution comes only from `decideGuestMessageSend`; a client cannot claim it. */
252 export function withoutGuestAttribution<
253 C extends { readonly context?: OrchestrationMessageContext | undefined },
254 >(command: C): C {
255 if (command.context?.guest === undefined) return command;
256 const { guest: _guest, ...context } = command.context;
257 return { ...command, context };
258 }