@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 785 lines 30.8 KB
Raw
1 import {
2 type ChatAttachment,
3 ChatAttachmentId,
4 CommandId,
5 GUEST_SHARE_TTL_MS,
6 GuestMessageId,
7 GuestShareCreateError,
8 type GuestShareCreateInput,
9 type GuestShareCreateResult,
10 GuestShareId,
11 type GuestRedeemRequest,
12 type GuestStreamEvent,
13 type GuestSubmitRequest,
14 type OrchestrationV2AppThread,
15 type OrchestrationV2CommandOutputFrame,
16 type OrchestrationV2DomainEvent,
17 type OrchestrationV2GetTurnItemResult,
18 type OrchestrationV2ThreadHistoryPage,
19 type OrchestrationV2TurnItem,
20 ThreadId,
21 TurnItemId,
22 } from "@t3tools/contracts";
23 import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline";
24 import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
25 import * as Context from "effect/Context";
26 import * as SecureRandom from "effect/crypto/SecureRandom";
27 import * as DateTime from "effect/DateTime";
28 import * as Duration from "effect/Duration";
29 import * as Effect from "effect/Effect";
30 import * as FileSystem from "effect/FileSystem";
31 import * as Layer from "effect/Layer";
32 import * as Option from "effect/Option";
33 import * as Schedule from "effect/Schedule";
34 import * as Schema from "effect/Schema";
35 import * as Stream from "effect/Stream";
36
37 import { base64UrlDecodeUtf8, base64UrlEncode, timingSafeEqualBase64Url } from "../auth/utils.ts";
38 import * as PayloadSigner from "../auth/PayloadSigner.ts";
39 import {
40 attachmentFileExtension,
41 createAttachmentId,
42 resolveAttachmentPath,
43 resolveAttachmentPathById,
44 threadHtmlRenderAttachmentIds,
45 } from "../attachmentStore.ts";
46 import * as ServerConfig from "../config.ts";
47 import { CloudManagedEndpointRuntime } from "../cloud/ManagedEndpointRuntime.ts";
48 import * as CommandOutputHub from "../orchestration-v2/CommandOutputHub.ts";
49 import { GUEST_FAILURE } from "../orchestration-v2/GuestShareDecider.ts";
50 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
51 import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoalescer.ts";
52 import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts";
53 import {
54 projectTurnItemForDetail,
55 projectTurnItemForWire,
56 threadStreamEventItem,
57 } from "../orchestration-v2/WireProjection.ts";
58 import * as DocumentText from "../provider/DocumentText.ts";
59 import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
60 import * as ServerSettings from "../serverSettings.ts";
61 import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
62 import { guestShareView, guestThreadModel } from "./guestView.ts";
63 import {
64 classifyGuestUploads,
65 GUEST_UPLOAD_HEADER_BYTES,
66 guestHostImageType,
67 type GuestUpload,
68 matchesImageSignature,
69 repliesShowImage,
70 } from "./guestAttachments.ts";
71
72 const SIGNING_SECRET_NAME = "guest-share-signing-key";
73 const SHARE_ID_BYTES = 16;
74 const INVITE_SIGNATURE_BYTES = 16;
75 const SNAPSHOT_ROW_LIMIT = 600;
76 const SNAPSHOT_USER_TURN_LIMIT = 20;
77 // Shares with no open guest stream whose sent image replies are still kept.
78 const SHARED_THREAD_REPLIES_LIMIT = 64;
79 // How soon an open read notices that its link stopped working, such as Connect no longer serving
80 // the host. Closing or replacing the link ends the main stream at once.
81 const ACCESS_RECHECK_INTERVAL = Duration.seconds(30);
82
83 const GUEST_ACCESS_MESSAGES = {
84 ...GUEST_FAILURE,
85 invalid: "This guest link is not valid.",
86 stale_page: "This page is for an older guest link. Reload it to continue.",
87 unavailable: "This item is not available.",
88 rejected: "The owner's server rejected this request.",
89 empty: "Write a message or attach a file.",
90 too_many_files: "Attach up to 4 files to a message.",
91 too_large: "Attached files can total up to 10 MB per message.",
92 unsupported_file: "This file cannot be attached. Images must be PNG, JPEG, GIF, or WebP.",
93 files_busy: GUEST_FAILURE.filesBusy,
94 } as const;
95
96 /** What a guest is told. The message comes from `reason`, never from a cause. */
97 export class GuestShareAccessError extends Schema.TaggedError<GuestShareAccessError>()(
98 "GuestShareAccessError",
99 {
100 reason: Schema.Literals([
101 "invalid",
102 "inactive",
103 "used",
104 "busy",
105 "stale_page",
106 "unavailable",
107 "rejected",
108 "empty",
109 "too_many_files",
110 "too_large",
111 "unsupported_file",
112 "files_busy",
113 ]),
114 },
115 ) {
116 override get message(): string {
117 return GUEST_ACCESS_MESSAGES[this.reason];
118 }
119 }
120
121 const guestFailureReason = (cause: unknown): GuestShareAccessError["reason"] =>
122 cause === GUEST_FAILURE.inactive
123 ? "inactive"
124 : cause === GUEST_FAILURE.used
125 ? "used"
126 : cause === GUEST_FAILURE.busy
127 ? "busy"
128 : cause === GUEST_FAILURE.filesBusy
129 ? "files_busy"
130 : "rejected";
131
132 const SessionClaims = Schema.Struct({
133 kind: Schema.Literal("session"),
134 threadId: ThreadId,
135 shareId: GuestShareId,
136 });
137 type SessionClaims = typeof SessionClaims.Type;
138 const decodeSessionClaims = Schema.decodeUnknownOption(Schema.fromJsonString(SessionClaims));
139
140 const inactive = new GuestShareAccessError({ reason: "inactive" });
141
142 export class GuestShareService extends Context.Service<
143 GuestShareService,
144 {
145 readonly create: (
146 input: GuestShareCreateInput,
147 ) => Effect.Effect<GuestShareCreateResult, GuestShareCreateError>;
148 /** Spends an invite and returns the session token for the guest's cookie. */
149 readonly redeem: (
150 request: GuestRedeemRequest,
151 ) => Effect.Effect<
152 { readonly token: string; readonly shareId: GuestShareId },
153 GuestShareAccessError
154 >;
155 /** Succeeds while the session can still open its share. */
156 readonly check: (session: string) => Effect.Effect<void, GuestShareAccessError>;
157 /** Stores the guest's files as the thread's attachments and records the message with them. */
158 readonly submit: (
159 session: string,
160 request: GuestSubmitRequest,
161 uploads: ReadonlyArray<GuestUpload>,
162 ) => Effect.Effect<void, GuestShareAccessError>;
163 readonly stream: (
164 session: string,
165 ) => Effect.Effect<Stream.Stream<GuestStreamEvent>, GuestShareAccessError>;
166 /** The file of an HTML render in the shared thread, and its title. */
167 readonly render: (
168 session: string,
169 itemId: string,
170 ) => Effect.Effect<{ readonly path: string; readonly title: string }, GuestShareAccessError>;
171 /** One item of the shared thread, as the owner's expanded row loads it, without file diffs. */
172 readonly item: (
173 session: string,
174 itemId: string,
175 ) => Effect.Effect<OrchestrationV2GetTurnItemResult, GuestShareAccessError>;
176 /** Older turns of the shared thread, as the owner's client pages them. */
177 readonly history: (
178 session: string,
179 cursor: string,
180 ) => Effect.Effect<OrchestrationV2ThreadHistoryPage, GuestShareAccessError>;
181 /** A command's output frames, as the owner's expanded row gets them, until the link ends. */
182 readonly commandOutput: (
183 session: string,
184 itemId: string,
185 ) => Effect.Effect<Stream.Stream<OrchestrationV2CommandOutputFrame>, GuestShareAccessError>;
186 /** A file in the shared thread or one of the share's messages, never a dismissed one's. */
187 readonly attachment: (
188 session: string,
189 attachmentId: string,
190 ) => Effect.Effect<
191 { readonly path: string; readonly attachment: ChatAttachment },
192 GuestShareAccessError
193 >;
194 /** An image on the host that an agent reply the guest sees shows, and its type. */
195 readonly media: (
196 session: string,
197 path: string,
198 ) => Effect.Effect<{ readonly path: string; readonly mimeType: string }, GuestShareAccessError>;
199 }
200 >()("t3/guest/GuestShareService") {}
201
202 /** A reply a guest's stream sent, with its image sources once a media request parsed them. */
203 interface SentReply {
204 readonly text: string;
205 sources?: ReadonlyArray<string>;
206 }
207
208 /** The thread record an event carries, for the share and the view. */
209 const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | null => {
210 switch (event.type) {
211 case "thread.guest-share-updated":
212 case "thread.metadata-updated":
213 case "thread.model-selection-updated":
214 case "thread.provider-switched":
215 return event.payload;
216 default:
217 return null;
218 }
219 };
220
221 const make = Effect.gen(function* () {
222 const orchestrator = yield* Orchestrator.OrchestratorV2;
223 const commandOutputs = yield* CommandOutputHub.CommandOutputHub;
224 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
225 const serverSettings = yield* ServerSettings.ServerSettingsService;
226 const managedEndpoint = yield* CloudManagedEndpointRuntime;
227 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
228 const fileSystem = yield* FileSystem.FileSystem;
229 const random = yield* SecureRandom.SecureRandom;
230 const analytics = yield* AnalyticsService.AnalyticsService;
231 const documents = yield* DocumentText.DocumentText;
232 const signer = yield* PayloadSigner.make(SIGNING_SECRET_NAME);
233 /** A truncated HMAC keeps invite links short. 128 bits is still far beyond guessing range. */
234 const inviteSignature = (shareId: string) =>
235 signer.sign(`guest-invite:${shareId}`).pipe(
236 Effect.orDie,
237 Effect.map((signature) =>
238 base64UrlEncode(Buffer.from(signature, "base64url").subarray(0, INVITE_SIGNATURE_BYTES)),
239 ),
240 );
241
242 // Tokens are derived from the share id, so nothing secret is stored and replacing or closing
243 // the share in the thread projection revokes every token for it. An invite is
244 // `<shareId>.<signature>` and the thread is looked up by share id; a session token carries
245 // signed claims.
246 const signInvite = (shareId: GuestShareId) =>
247 inviteSignature(shareId).pipe(Effect.map((signature) => `${shareId}.${signature}`));
248 const signSession = (claims: SessionClaims) => {
249 const payload = base64UrlEncode(JSON.stringify(claims));
250 return signer.sign(payload).pipe(
251 Effect.orDie,
252 Effect.map((signature) => `${payload}.${signature}`),
253 );
254 };
255 const splitToken = (token: string) => {
256 const [payload, signature, extra] = token.split(".");
257 return payload && signature && extra === undefined ? { payload, signature } : null;
258 };
259 const verifyInvite = Effect.fn("GuestShareService.verifyInvite")(function* (token: string) {
260 const parts = splitToken(token);
261 if (parts === null) return Option.none<SessionClaims>();
262 const expected = yield* inviteSignature(parts.payload);
263 if (!timingSafeEqualBase64Url(parts.signature, expected)) {
264 return Option.none<SessionClaims>();
265 }
266 const shareId = GuestShareId.make(parts.payload);
267 const threadId = yield* orchestrator
268 .findGuestShareThreadId(shareId)
269 .pipe(Effect.mapError(() => inactive));
270 return threadId === null
271 ? Option.none<SessionClaims>()
272 : Option.some<SessionClaims>({ kind: "session", threadId, shareId });
273 });
274 // Untraced: runs on every guest request, like the Effect.map it replaced.
275 const verifySession = Effect.fnUntraced(function* (token: string) {
276 const parts = splitToken(token);
277 if (parts === null) return Option.none<SessionClaims>();
278 if (!(yield* signer.verify(parts.payload, parts.signature).pipe(Effect.orDie))) {
279 return Option.none<SessionClaims>();
280 }
281 return decodeSessionClaims(base64UrlDecodeUtf8(parts.payload));
282 });
283
284 const connectHostname = managedEndpoint.inspectConnector.pipe(
285 Effect.map((facts) => facts?.hostname ?? null),
286 );
287 // A beta: while it is off, no link opens and every guest request is refused.
288 const sharingEnabled = serverSettings.getSettings.pipe(
289 Effect.map((settings) => settings.guestSharingEnabled),
290 Effect.orElseSucceed(() => false),
291 );
292
293 const dispatchGuestCommand = (
294 command: Parameters<Orchestrator.OrchestratorV2["Service"]["dispatch"]>[0],
295 ) =>
296 orchestrator.dispatch(command).pipe(
297 Effect.mapError(
298 (error) =>
299 new GuestShareAccessError({
300 reason: guestFailureReason("cause" in error ? error.cause : undefined),
301 }),
302 ),
303 );
304
305 const commandId = (label: string) =>
306 random.uuidV4().pipe(
307 Effect.map((uuid) => CommandId.make(`server:guest-share:${label}:${uuid}`)),
308 Effect.orDie,
309 );
310
311 /** Checks a token against the live share: same id, not expired, and Connect still serving it. */
312 const authorize = Effect.fn("GuestShareService.authorize")(function* (
313 token: string,
314 kind: "invite" | "session",
315 ) {
316 const claims = yield* kind === "invite" ? verifyInvite(token) : verifySession(token);
317 if (Option.isNone(claims)) {
318 return yield* new GuestShareAccessError({ reason: "invalid" });
319 }
320 const { thread } = yield* orchestrator
321 .getThreadRecords(claims.value.threadId, [])
322 .pipe(Effect.mapError(() => inactive));
323 const share = thread.guestShare;
324 const now = yield* DateTime.now;
325 if (
326 !(yield* sharingEnabled) ||
327 !share ||
328 share.id !== claims.value.shareId ||
329 thread.archivedAt !== null ||
330 thread.deletedAt !== null ||
331 DateTime.toEpochMillis(now) >= Date.parse(share.expiresAt) ||
332 (kind === "session" && share.guestName === null) ||
333 (yield* connectHostname) !== share.host
334 ) {
335 return yield* inactive;
336 }
337 return { thread, share };
338 });
339
340 const create = Effect.fn("GuestShareService.create")(function* (input: GuestShareCreateInput) {
341 if (!(yield* sharingEnabled)) {
342 return yield* new GuestShareCreateError({ reason: "disabled" });
343 }
344 const host = yield* connectHostname;
345 if (host === null) {
346 return yield* new GuestShareCreateError({ reason: "connect_unavailable" });
347 }
348 const shareId = GuestShareId.make(base64UrlEncode(yield* random.randomBytes(SHARE_ID_BYTES)));
349 const now = yield* DateTime.now;
350 const expiresAt = DateTime.formatIso(DateTime.add(now, { milliseconds: GUEST_SHARE_TTL_MS }));
351 yield* orchestrator
352 .dispatch({
353 type: "thread.guest-share.open",
354 commandId: yield* commandId("open"),
355 threadId: input.threadId,
356 shareId,
357 host,
358 expiresAt,
359 })
360 .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "thread_unavailable" })));
361 const { thread } = yield* orchestrator
362 .getThreadRecords(input.threadId, [])
363 .pipe(Effect.mapError(() => new GuestShareCreateError({ reason: "read_failed" })));
364 if (!thread.guestShare || thread.guestShare.id !== shareId) {
365 return yield* new GuestShareCreateError({ reason: "changed" });
366 }
367 const credential = yield* signInvite(shareId);
368 return { url: `https://${host}/guest#${credential}`, share: thread.guestShare };
369 });
370
371 const redeem = Effect.fn("GuestShareService.redeem")(function* (request: GuestRedeemRequest) {
372 const { thread, share } = yield* authorize(request.credential, "invite");
373 yield* dispatchGuestCommand({
374 type: "thread.guest-share.redeem",
375 commandId: yield* commandId("redeem"),
376 threadId: thread.id,
377 shareId: share.id,
378 guestName: request.name,
379 });
380 // Guests have no client connection, so their events carry no surface.
381 yield* analytics.record("feature.used", { feature: "guest_share.join" });
382 const token = yield* signSession({ kind: "session", threadId: thread.id, shareId: share.id });
383 return { token, shareId: share.id };
384 });
385
386 const check = Effect.fn("GuestShareService.check")(function* (session: string) {
387 yield* authorize(session, "session");
388 });
389
390 const uploadFailed = new GuestShareAccessError({ reason: "rejected" });
391 const removeStored = (attachments: ReadonlyArray<ChatAttachment>) =>
392 Effect.forEach(
393 attachments,
394 (attachment) => {
395 const path = resolveAttachmentPath({ attachmentsDir, attachment });
396 return path === null
397 ? Effect.void
398 : fileSystem
399 .remove(path, { force: true })
400 .pipe(
401 Effect.andThen(fileSystem.remove(`${path}.txt`, { force: true })),
402 Effect.ignore,
403 );
404 },
405 { discard: true },
406 );
407
408 /**
409 * Checks the files and stores them as the thread's attachments, so a message can wait longer
410 * than the day the pending-upload sweep allows. Send uses them as they are; dismissing the
411 * message or ending the share deletes them.
412 */
413 const storeUploads = Effect.fn("GuestShareService.storeUploads")(function* (
414 threadId: ThreadId,
415 uploads: ReadonlyArray<GuestUpload>,
416 ) {
417 const inspected = yield* Effect.forEach(uploads, (upload) =>
418 Effect.gen(function* () {
419 const info = yield* fileSystem.stat(upload.path);
420 const file = yield* fileSystem.open(upload.path, { flag: "r" });
421 const header = Option.getOrElse(
422 yield* file.readAlloc(GUEST_UPLOAD_HEADER_BYTES),
423 () => new Uint8Array(),
424 );
425 return { ...upload, sizeBytes: Number(info.size), header };
426 }).pipe(
427 Effect.scoped,
428 Effect.mapError(() => uploadFailed),
429 ),
430 );
431 const classified = classifyGuestUploads(inspected);
432 if (!classified.ok) return yield* new GuestShareAccessError({ reason: classified.reason });
433 const stored: Array<ChatAttachment> = [];
434 yield* Effect.forEach(
435 classified.attachments,
436 (draft, index) =>
437 Effect.gen(function* () {
438 const id = createAttachmentId(
439 threadId,
440 draft.type === "file" ? attachmentFileExtension(draft.name) : undefined,
441 );
442 if (id === null) return yield* uploadFailed;
443 const attachment: ChatAttachment = { ...draft, id: ChatAttachmentId.make(id) };
444 const path = resolveAttachmentPath({ attachmentsDir, attachment });
445 if (path === null) return yield* uploadFailed;
446 yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
447 yield* fileSystem.copyFile(uploads[index]!.path, path);
448 stored.push(attachment);
449 yield* documents.ensure(path);
450 }).pipe(Effect.mapError(() => uploadFailed)),
451 { discard: true },
452 ).pipe(Effect.onError(() => removeStored(stored)));
453 return stored;
454 });
455
456 const submit = Effect.fn("GuestShareService.submit")(function* (
457 session: string,
458 request: GuestSubmitRequest,
459 uploads: ReadonlyArray<GuestUpload>,
460 ) {
461 const { thread, share } = yield* authorize(session, "session");
462 if (request.shareId !== share.id) {
463 return yield* new GuestShareAccessError({ reason: "stale_page" });
464 }
465 if (request.text === "" && uploads.length === 0) {
466 return yield* new GuestShareAccessError({ reason: "empty" });
467 }
468 const attachments = yield* storeUploads(thread.id, uploads);
469 yield* dispatchGuestCommand({
470 type: "thread.guest-message.submit",
471 commandId: yield* commandId("submit"),
472 threadId: thread.id,
473 shareId: share.id,
474 guestMessageId: GuestMessageId.make(yield* random.uuidV4()),
475 text: request.text,
476 ...(attachments.length === 0 ? {} : { attachments }),
477 }).pipe(Effect.onError(() => removeStored(attachments)));
478 yield* analytics.record("feature.used", {
479 feature: "guest_message.submit",
480 variant: attachments.length === 0 ? "text_only" : "with_files",
481 });
482 });
483
484 /** Completes once the session no longer opens its share, so open reads end with it. */
485 const untilRevoked = (session: string) =>
486 authorize(session, "session").pipe(
487 Effect.repeat(Schedule.spaced(ACCESS_RECHECK_INTERVAL)),
488 Effect.ignore,
489 );
490
491 // The image replies each share's guest stream has sent, in its opening snapshot or live, so an
492 // image loads while the guest's page can show its reply, inherited ones included. Keyed by
493 // share, so a new link on the thread starts empty. A share with an open stream keeps its
494 // record; past the limit, closed ones are dropped.
495 const sentImageReplies = new Map<
496 GuestShareId,
497 { openStreams: number; readonly replies: Map<string, SentReply> }
498 >();
499 const sentRecord = (shareId: GuestShareId) => {
500 let record = sentImageReplies.get(shareId);
501 if (record === undefined) {
502 record = { openStreams: 0, replies: new Map() };
503 sentImageReplies.set(shareId, record);
504 for (const [id, other] of sentImageReplies) {
505 if (sentImageReplies.size <= SHARED_THREAD_REPLIES_LIMIT) break;
506 if (other.openStreams === 0 && id !== shareId) sentImageReplies.delete(id);
507 }
508 }
509 return record;
510 };
511 const rememberSent = (shareId: GuestShareId, items: Iterable<OrchestrationV2TurnItem>) => {
512 for (const item of items) {
513 if (item.type !== "assistant_message") continue;
514 const key = `${item.threadId}\u0000${item.id}`;
515 // Only replies with image syntax can show an image. One edited to drop its images stops
516 // allowing them.
517 if (item.text.includes("![") || /<img/i.test(item.text)) {
518 sentRecord(shareId).replies.set(key, { text: item.text });
519 } else {
520 sentImageReplies.get(shareId)?.replies.delete(key);
521 }
522 }
523 };
524
525 /**
526 * The thread as the owner's thread subscription sends it: a bounded snapshot, then the same
527 * wire events, batched the same way. Only the share's own state is added.
528 */
529 const stream = Effect.fn("GuestShareService.stream")(function* (session: string) {
530 const { thread, share } = yield* authorize(session, "session");
531 const snapshot = yield* orchestrator
532 .getThreadSnapshotWindow(thread.id, {
533 rowLimit: SNAPSHOT_ROW_LIMIT,
534 userTurnLimit: SNAPSHOT_USER_TURN_LIMIT,
535 })
536 .pipe(Effect.mapError(() => inactive));
537 // The share can end between authorize and this read; the live tail starts after it.
538 if (
539 snapshot.projection.thread.guestShare?.id !== share.id ||
540 snapshot.projection.thread.archivedAt !== null ||
541 snapshot.projection.thread.deletedAt !== null
542 ) {
543 return yield* inactive;
544 }
545 // Read once; a provider configured mid-share shows after the guest reconnects.
546 const providers = yield* providerRegistry.getProviders;
547 const viewOf = (current: OrchestrationV2AppThread) =>
548 guestShareView(current, guestThreadModel(current.modelSelection, providers));
549 const initialView = viewOf(snapshot.projection.thread);
550 if (initialView === null) return yield* inactive;
551
552 const ended: GuestStreamEvent = { type: "ended" };
553 const endsShare = (event: OrchestrationV2DomainEvent) => {
554 if (event.type === "thread.archived" || event.type === "thread.deleted") return true;
555 const updated = threadOf(event);
556 return updated !== null && updated.guestShare?.id !== share.id;
557 };
558 const live = orchestrator
559 .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence })
560 .pipe(
561 Stream.map(threadStreamEventItem),
562 // Ending the source here flushes what the coalescer holds, so `ended` is not held back.
563 Stream.takeUntil((item) => endsShare(item.event)),
564 coalesceThreadLiveStream,
565 Stream.map((item): ReadonlyArray<GuestStreamEvent> => {
566 if (item.kind !== "event") return [];
567 if (endsShare(item.event)) return [ended];
568 if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]);
569 const updated = threadOf(item.event);
570 const view = updated === null ? null : viewOf(updated);
571 return view === null
572 ? [{ type: "thread", item }]
573 : [
574 { type: "thread", item },
575 { type: "view", view },
576 ];
577 }),
578 Stream.flattenIterable,
579 // A failed read closes the response without `ended`: the browser reconnects, and
580 // `authorize` decides whether the link still works.
581 Stream.catchCause(() => Stream.empty),
582 );
583 const untilExpiry = Effect.sleep(
584 Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)),
585 );
586 const openingSnapshot = buildBoundedThreadStreamSnapshot({
587 snapshotSequence: snapshot.snapshotSequence,
588 projection: snapshot.projection,
589 });
590 const opening: ReadonlyArray<GuestStreamEvent> = [
591 { type: "view", view: initialView },
592 { type: "thread", item: openingSnapshot },
593 ];
594 const events = Stream.fromIterable(opening).pipe(
595 Stream.concat(
596 Stream.merge(live, Stream.fromEffect(Effect.as(untilExpiry, ended)), {
597 haltStrategy: "either",
598 }),
599 ),
600 Stream.takeUntil((event) => event.type === "ended"),
601 // Unlinking T3 Connect closes it quietly, so a tunnel that comes back on the same host
602 // keeps the guest in. Turning the beta off closes it the same way. Closing and expiry end
603 // it above, with `ended`.
604 Stream.interruptWhen(
605 Effect.all([connectHostname, sharingEnabled]).pipe(
606 Effect.repeat({
607 schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),
608 until: ([host, enabled]) => host !== share.host || !enabled,
609 }),
610 ),
611 ),
612 );
613 // The record is opened and counted when the stream runs, paired with its release, so a
614 // response whose body never runs (HEAD) touches nothing.
615 return Stream.unwrap(
616 Effect.acquireRelease(
617 Effect.sync(() => {
618 const record = sentRecord(share.id);
619 record.openStreams += 1;
620 rememberSent(
621 share.id,
622 openingSnapshot.projection.visibleTurnItems.map((row) => row.item),
623 );
624 return record;
625 }),
626 (record) =>
627 Effect.sync(() => {
628 record.openStreams -= 1;
629 }),
630 ).pipe(Effect.as(events)),
631 );
632 });
633
634 const unavailable = new GuestShareAccessError({ reason: "unavailable" });
635
636 /** An item of the shared thread, read after the session check. */
637 const threadItem = Effect.fn("GuestShareService.threadItem")(function* (
638 session: string,
639 itemId: string,
640 ) {
641 const { thread } = yield* authorize(session, "session");
642 const id = TurnItemId.make(itemId);
643 const item =
644 (yield* orchestrator
645 .getTurnItem({ threadId: thread.id, itemId: id })
646 .pipe(Effect.mapError(() => unavailable))) ??
647 // A fork shows its source's earlier items, which stay in the source thread.
648 (thread.forkedFrom === null
649 ? null
650 : yield* orchestrator.getTimelinePage(thread.id, { itemId: id, limit: 1 }).pipe(
651 Effect.map((page) => page.items[0]?.item ?? null),
652 Effect.mapError(() => unavailable),
653 ));
654 return item === null ? yield* unavailable : { thread, item };
655 });
656
657 const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) {
658 const { item } = yield* threadItem(session, itemId);
659 if (item.type !== "dynamic_tool") return yield* unavailable;
660 const reference = htmlRenderFromToolItem(item);
661 const [attachmentId] = threadHtmlRenderAttachmentIds(item.threadId, [item]);
662 const path =
663 attachmentId === undefined
664 ? null
665 : resolveAttachmentPathById({ attachmentsDir, attachmentId });
666 if (reference === undefined || path === null) return yield* unavailable;
667 return { path, title: reference.title };
668 });
669
670 const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) {
671 const { item } = yield* threadItem(session, itemId);
672 return {
673 item:
674 item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item),
675 };
676 });
677
678 const history = Effect.fn("GuestShareService.history")(function* (
679 session: string,
680 cursor: string,
681 ) {
682 const { thread, share } = yield* authorize(session, "session");
683 const page = yield* orchestrator
684 .getThreadHistoryPage(thread.id, cursor)
685 .pipe(Effect.mapError(() => unavailable));
686 rememberSent(
687 share.id,
688 page.items.map((row) => row.item),
689 );
690 return page;
691 });
692
693 const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
694 session: string,
695 itemId: string,
696 ) {
697 const { item } = yield* threadItem(session, itemId);
698 if (item.type !== "command_execution") return yield* unavailable;
699 return commandOutputs.subscribe({ threadId: item.threadId, itemId: item.id }).pipe(
700 // A lost hub stream ends the output; the row reloads it when reopened.
701 Stream.catchCause(() => Stream.empty),
702 Stream.interruptWhen(untilRevoked(session)),
703 );
704 });
705
706 const attachment = Effect.fn("GuestShareService.attachment")(function* (
707 session: string,
708 attachmentId: string,
709 ) {
710 const { thread, share } = yield* authorize(session, "session");
711 // A dismissed message's files are deleted with it.
712 const fromShare = share.messages
713 .flatMap((message) => (message.status === "dismissed" ? [] : (message.attachments ?? [])))
714 .find((candidate) => candidate.id === attachmentId);
715 const found =
716 fromShare ??
717 (yield* orchestrator.getThreadRecords(thread.id, ["messages"]).pipe(
718 Effect.map(({ messages }) =>
719 messages
720 .flatMap((message) => message.attachments ?? [])
721 .find((candidate) => candidate.id === attachmentId),
722 ),
723 Effect.mapError(() => unavailable),
724 )) ??
725 // A fork shows its source's earlier messages, which stay in the source thread.
726 (thread.forkedFrom === null
727 ? undefined
728 : yield* orchestrator.getTimelinePage(thread.id, { attachmentId, limit: 1 }).pipe(
729 Effect.map(({ items }) =>
730 items
731 .flatMap(({ item }) => (item.type === "user_message" ? item.attachments : []))
732 .find((candidate) => candidate.id === attachmentId),
733 ),
734 Effect.mapError(() => unavailable),
735 ));
736 const path =
737 found === undefined ? null : resolveAttachmentPath({ attachmentsDir, attachment: found });
738 if (found === undefined || path === null) return yield* unavailable;
739 const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));
740 return exists ? { path, attachment: found } : yield* unavailable;
741 });
742
743 const media = Effect.fn("GuestShareService.media")(function* (session: string, path: string) {
744 const { share } = yield* authorize(session, "session");
745 const mimeType = guestHostImageType(path);
746 if (mimeType === null) return yield* unavailable;
747 const sent = sentImageReplies.get(share.id)?.replies.values() ?? [];
748 // Each sent reply is parsed once, on the first request that needs it.
749 if (
750 !repliesShowImage(
751 path,
752 [...sent],
753 (reply) => (reply.sources ??= chatMarkdownImageSources(reply.text)),
754 )
755 ) {
756 return yield* unavailable;
757 }
758 // The bytes must be the image the name says, as for a guest's own upload.
759 const header = yield* fileSystem.open(path, { flag: "r" }).pipe(
760 Effect.flatMap((file) => file.readAlloc(GUEST_UPLOAD_HEADER_BYTES)),
761 Effect.scoped,
762 Effect.mapError(() => unavailable),
763 );
764 if (Option.isNone(header) || !matchesImageSignature(mimeType, header.value)) {
765 return yield* unavailable;
766 }
767 return { path, mimeType };
768 });
769
770 return GuestShareService.of({
771 create,
772 redeem,
773 check,
774 submit,
775 stream,
776 render,
777 item,
778 history,
779 commandOutput,
780 attachment,
781 media,
782 });
783 });
784
785 export const layer = Layer.effect(GuestShareService, make);