-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathapp.ts
More file actions
1030 lines (953 loc) · 40.6 KB
/
Copy pathapp.ts
File metadata and controls
1030 lines (953 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Hono, type Context } from "hono";
import { getCookie, setCookie } from "hono/cookie";
import { streamSSE } from "hono/streaming";
import { EventBus } from "./events.ts";
import { kitSummaries } from "./kits.ts";
import { registerMcp } from "./mcpHttp.ts";
import { renderHtmlPage } from "./surfacePage.ts";
import { DEFAULT_THEME_ID, themeById, themeOptions } from "./themes.ts";
import {
type Asset,
type AssetKind,
type Comment,
htmlPart,
MAX_ASSET_BYTES,
partsByteLength,
type Store,
type Surface,
type SurfacePart,
type TraceStep,
} from "./types.ts";
import { validateSurfaceParts } from "./surfaceParts.ts";
const MAX_SURFACE_BYTES = 2 * 1024 * 1024;
const MAX_WAIT_SECONDS = 300;
// Bound the session trace: each step's detail is truncated and the per-session
// list rolls, so memory stays flat no matter how long the agent runs.
const MAX_TRACE_STEPS = 2000;
const MAX_STEP_DETAIL = 4000;
const MAX_STEP_LABEL = 500;
// Asset serving policy: only raster images are served inline; everything else
// (incl. svg, json, text, the octet-stream catch-all) is an attachment, so a
// top-level open of /a/:id can never execute an uploaded document as a live
// same-origin script. <img>/fetch ignore Content-Disposition, so embedding and
// inline trace rendering keep working regardless.
const INLINE_IMAGE_TYPES = new Set([
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"image/avif",
]);
const ATTACH_SAFE_TYPES = new Set([
"image/svg+xml",
"application/json",
"application/x-ndjson",
"text/plain",
"text/csv",
]);
function assetServeHeaders(asset: Asset): { contentType: string; disposition: string } {
if (INLINE_IMAGE_TYPES.has(asset.contentType)) {
return { contentType: asset.contentType, disposition: "inline" };
}
const contentType = ATTACH_SAFE_TYPES.has(asset.contentType)
? asset.contentType
: "application/octet-stream";
const name = (asset.filename || asset.id).replace(/[^\w.-]/g, "_");
return { contentType, disposition: `attachment; filename="${name}"` };
}
// Pick an AssetKind when the caller didn't specify one.
function inferAssetKind(contentType: string): AssetKind {
return contentType.startsWith("image/") ? "image" : "file";
}
const isAssetKind = (v: unknown): v is AssetKind => v === "image" || v === "trace" || v === "file";
// base64 -> bytes, runtime-agnostic (atob is a global in Node and Workers).
function decodeBase64(b64: string): Uint8Array {
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
// Docs and onboarding snippets are written against the local default; serve
// them with the real origin so a deployed instance shows copy-pasteable URLs.
const LOCAL_ORIGIN = "http://localhost:8228";
export type AuthenticateHook = (
request: Request,
) => boolean | Response | Promise<boolean | Response>;
export type BasePathHook = string | ((request: Request) => string | null | undefined);
export type PublicReadMode = "session" | "full";
export interface AppOptions {
store: Store;
viewerHtml: string;
guideMarkdown: string;
setupText: string;
agentHowtoText?: string;
// When set (cloud deployments), this hook authorizes requests before any
// app route runs. Return true to allow, false to use the default 401, or a
// Response for custom denials. This is intentionally lower-level than
// authToken so hosts can validate edge-signed assertions without teaching
// sideshow about their session/token systems.
authenticate?: AuthenticateHook;
// When set (self-hosted Worker deployments), every route except /guide,
// /setup, and /agent-howto requires it: Authorization bearer, ?key= query,
// or the cookie it sets. Preserved for backwards compatibility.
authToken?: string;
// Public path prefix for deployments mounted below an origin root, e.g.
// /u/:account in a hosted multi-tenant wrapper. The core still receives
// stripped routes like /api/sessions and /s/:id?part=0; this prefix is only
// used when the server/viewer generate browser-visible URLs.
basePath?: BasePathHook;
// When set, unauthenticated GET routes can be read without bypassing the
// write token. "session" exposes only session-scoped reads; "full" exposes
// every GET route.
publicRead?: PublicReadMode;
// Update notice: the running version and the upgrade hint that fits this
// deployment (npm install vs redeploy). Without `version`, /api/version
// reports nothing and the viewer shows no notice.
version?: string;
upgradeCommand?: string;
// Test seam: replaces the npm-registry/GitHub lookup for the latest release.
fetchLatestRelease?: () => Promise<LatestRelease | null>;
}
export interface LatestRelease {
version: string;
notes?: string;
}
// Newer-than for plain x.y.z strings; prerelease suffixes compare as their
// base version, and garbage compares as "not newer".
function versionGt(a: string, b: string): boolean {
const pa = a.split("-")[0].split(".").map(Number);
const pb = b.split("-")[0].split(".").map(Number);
for (let i = 0; i < 3; i++) {
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
if (d !== 0) return d > 0;
}
return false;
}
// Latest published version from npm, release notes from the matching GitHub
// release. Notes are garnish: if GitHub is unreachable the version alone
// still makes a usable notice.
async function fetchLatestFromRegistry(): Promise<LatestRelease | null> {
const res = await fetch("https://registry.npmjs.org/sideshow/latest");
if (!res.ok) return null;
const pkg = (await res.json()) as { version?: string };
if (typeof pkg.version !== "string") return null;
let notes: string | undefined;
try {
const gh = await fetch(
`https://api.github.com/repos/modem-dev/sideshow/releases/tags/v${pkg.version}`,
{ headers: { "user-agent": "sideshow", accept: "application/vnd.github+json" } },
);
if (gh.ok) {
const rel = (await gh.json()) as { body?: string };
if (typeof rel.body === "string") notes = rel.body;
}
} catch {
// ignore — see above
}
return { version: pkg.version, notes };
}
const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000;
// html parts carry arbitrary markup the viewer renders via a sandboxed iframe,
// so the card list never needs their bodies — strip them to a kind marker.
// diff parts are structured data the viewer renders inline, so keep them whole.
const stripParts = (parts: SurfacePart[]): SurfacePart[] =>
parts.map((p) => (p.kind === "html" ? { kind: "html", html: "" } : p));
const surfaceMeta = (s: Surface) => ({
id: s.id,
sessionId: s.sessionId,
title: s.title,
createdAt: s.createdAt,
updatedAt: s.updatedAt,
version: s.version,
parts: stripParts(s.parts),
});
function isPublicReadAllowed(path: string, mode: PublicReadMode): boolean {
if (mode === "full") return true;
if (path.startsWith("/session/")) return true;
if (path.startsWith("/s/")) return true;
if (path.startsWith("/a/")) return true;
if (path.startsWith("/api/sessions/")) return true;
if (path.startsWith("/api/surfaces/")) return true;
if (path.startsWith("/api/snippets/")) return true;
if (path === "/api/comments") return true;
if (path === "/api/events") return true;
if (path === "/api/theme") return true;
if (path === "/api/version") return true;
if (path === "/api/kits") return true;
return false;
}
// Response to an agent's own write: it already holds the parts it just sent,
// so echo only the identifiers (a diff patch can be large — never send it
// back). Reads (`surfaceMeta`, GET /api/surfaces/:id) still carry parts.
const writeResult = (s: Surface) => ({
id: s.id,
sessionId: s.sessionId,
title: s.title,
createdAt: s.createdAt,
updatedAt: s.updatedAt,
version: s.version,
kinds: s.parts.map((p) => p.kind),
});
export interface CommentWait {
sessionId?: string;
surfaceId?: string;
author?: string;
afterSeq?: number;
waitSeconds: number;
}
export interface Feedback {
surfaceId: string | null;
surfaceTitle: string | null;
text: string;
at: string;
}
// Lean comment shape attached to agent-facing responses.
const feedbackView = (c: Comment): Feedback => ({
surfaceId: c.surfaceId,
surfaceTitle: c.surfaceTitle,
text: c.text,
at: c.createdAt,
});
export function createApp({
store,
viewerHtml,
guideMarkdown,
setupText,
agentHowtoText = setupText,
authenticate,
authToken,
basePath,
publicRead,
version,
upgradeCommand,
fetchLatestRelease,
}: AppOptions) {
const app = new Hono();
const bus = new EventBus();
// Last-resort safety net: any handler that throws (rather than returning a
// status) becomes a clean JSON 500 instead of leaking a stack or a bare crash.
// Validation rejects bad input with 4xx before this, so reaching here means an
// unexpected bug — log it so it isn't swallowed silently.
app.onError((err, c) => {
console.error("sideshow: unhandled error", err);
return c.json({ error: "internal error" }, 500);
});
const normalizeBasePath = (value: string | null | undefined): string => {
if (!value || value === "/") return "";
const withLeading = value.startsWith("/") ? value : `/${value}`;
let end = withLeading.length;
while (end > 0 && withLeading.charCodeAt(end - 1) === 47) end--;
return withLeading.slice(0, end);
};
const requestBasePath = (request: Request): string =>
normalizeBasePath(typeof basePath === "function" ? basePath(request) : basePath);
// Cached, fail-silent update lookup: being offline or rate-limited must
// cost nothing but the absence of the notice. Failures are cached too, so
// a dead network doesn't retry on every viewer load.
let updateCache: { at: number; value: LatestRelease | null } | null = null;
async function latestRelease(): Promise<LatestRelease | null> {
if (updateCache && Date.now() - updateCache.at < UPDATE_CHECK_TTL_MS) return updateCache.value;
const value = await (fetchLatestRelease ?? fetchLatestFromRegistry)().catch(() => null);
updateCache = { at: Date.now(), value };
return value;
}
// --- shared flows (used by both the REST API and the MCP endpoint) ---
// User comments the agent has not seen yet ride along on its next write, so
// agents hear feedback without blocking on the long-poll. The cursor also
// advances past the agent's own comments to keep reads cheap.
async function collectFeedback(sessionId: string): Promise<Feedback[] | undefined> {
const session = await store.getSession(sessionId);
if (!session) return undefined;
const fresh = await store.listComments({ sessionId, afterSeq: session.agentSeq });
if (fresh.length === 0) return undefined;
await store.markAgentSeen(sessionId, fresh[fresh.length - 1].seq);
const feedback = fresh.filter((cm) => cm.author === "user");
return feedback.length > 0 ? feedback.map(feedbackView) : undefined;
}
async function publishSurface(input: {
parts: SurfacePart[];
title?: string;
session?: string;
sessionTitle?: string;
agent?: string;
cwd?: string;
}): Promise<
{ surface: Surface; userFeedback?: Feedback[] } | { error: string; status: 400 | 404 | 413 }
> {
if (input.parts.length === 0) {
return { error: "a surface needs at least one part", status: 400 };
}
if (partsByteLength(input.parts) > MAX_SURFACE_BYTES) {
return { error: `surface exceeds ${MAX_SURFACE_BYTES} bytes`, status: 413 };
}
let sessionId = input.session;
if (sessionId && !(await store.getSession(sessionId))) {
return { error: `session "${sessionId}" not found`, status: 404 };
}
if (!sessionId) {
// sessionTitle applies only here — an existing session keeps its title,
// which the user may have set by renaming it in the viewer.
const session = await store.createSession({
agent: input.agent ?? "agent",
title: input.sessionTitle,
cwd: input.cwd,
});
bus.broadcast({ type: "session-created", id: session.id });
sessionId = session.id;
}
const surface = await store.createSurface({
sessionId,
parts: input.parts,
title: input.title,
});
if (!surface) return { error: "session not found", status: 404 };
bus.broadcast({ type: "surface-created", id: surface.id, sessionId, version: 1 });
return { surface, userFeedback: await collectFeedback(sessionId) };
}
// Store an uploaded blob. Like publishSurface, an explicit session is
// validated and a missing one is auto-created so an upload can precede the
// first publish. The asset's data is dropped from the result (it's bytes).
async function uploadAsset(input: {
data: Uint8Array;
contentType: string;
filename?: string;
kind?: AssetKind;
session?: string;
agent?: string;
}): Promise<{ asset: Omit<Asset, "data"> } | { error: string; status: 400 | 404 | 413 }> {
if (input.data.byteLength === 0) return { error: "empty upload", status: 400 };
if (input.data.byteLength > MAX_ASSET_BYTES) {
return { error: `asset exceeds ${MAX_ASSET_BYTES} bytes`, status: 413 };
}
let sessionId = input.session;
if (sessionId && !(await store.getSession(sessionId))) {
return { error: `session "${sessionId}" not found`, status: 404 };
}
if (!sessionId) {
const session = await store.createSession({ agent: input.agent ?? "agent" });
bus.broadcast({ type: "session-created", id: session.id });
sessionId = session.id;
}
const asset = await store.putAsset({
sessionId,
kind: input.kind ?? inferAssetKind(input.contentType),
contentType: input.contentType || "application/octet-stream",
filename: input.filename,
data: input.data,
});
if (!asset) return { error: "session not found", status: 404 };
const { data: _data, ...meta } = asset;
return { asset: meta };
}
async function reviseSurface(
id: string,
patch: { parts?: SurfacePart[]; title?: string },
): Promise<
{ surface: Surface; userFeedback?: Feedback[] } | { error: string; status: 400 | 404 | 413 }
> {
if (patch.parts) {
if (patch.parts.length === 0) {
return { error: "a surface needs at least one part", status: 400 };
}
if (partsByteLength(patch.parts) > MAX_SURFACE_BYTES) {
return { error: `surface exceeds ${MAX_SURFACE_BYTES} bytes`, status: 413 };
}
}
const surface = await store.updateSurface(id, patch);
if (!surface) return { error: "surface not found", status: 404 };
bus.broadcast({
type: "surface-updated",
id: surface.id,
sessionId: surface.sessionId,
version: surface.version,
});
return { surface, userFeedback: await collectFeedback(surface.sessionId) };
}
async function createComment(input: {
text: string;
surface?: string;
author: string;
}): Promise<
{ comment: Comment; userFeedback?: Feedback[] } | { error: string; status: 400 | 404 }
> {
// Comments always attach to a surface — a comment with nothing to point at
// is just a message to the agent, which is what the agent's own prompt is for.
if (!input.surface) return { error: 'provide a "surface" id', status: 400 };
const surface = await store.getSurface(input.surface);
if (!surface) return { error: "surface not found", status: 404 };
const comment = await store.createComment({
sessionId: surface.sessionId,
surfaceId: surface.id,
author: input.author,
text: input.text.trim(),
});
if (!comment) return { error: "session not found", status: 404 };
bus.broadcast({
type: "comment-created",
id: comment.id,
sessionId: comment.sessionId,
surfaceId: comment.surfaceId,
seq: comment.seq,
});
// agent replies are writes too — piggyback pending feedback on them, but
// never on the user's own comments
const userFeedback =
input.author === "user" ? undefined : await collectFeedback(comment.sessionId);
return { comment, userFeedback };
}
// Long-poll: resolves as soon as a matching comment lands, or at timeout.
async function waitForComments(
q: CommentWait,
): Promise<{ comments: Comment[]; lastSeq: number }> {
// An author=user session wait with no explicit cursor resumes from the
// session's agentSeq — "where the agent left off" lives server-side so the
// CLI, both MCP transports, and piggyback share one exactly-once stream.
let afterSeq = q.afterSeq;
if (afterSeq === undefined && q.author === "user" && q.sessionId) {
afterSeq = (await store.getSession(q.sessionId))?.agentSeq;
}
const query = { sessionId: q.sessionId, surfaceId: q.surfaceId, afterSeq };
const matches = (list: Comment[]) =>
q.author ? list.filter((cm) => cm.author === q.author) : list;
const wait = Math.min(Math.max(q.waitSeconds, 0), MAX_WAIT_SECONDS);
let all = await store.listComments(query);
let comments = matches(all);
if (comments.length === 0 && wait > 0) {
await new Promise<void>((resolve) => {
const timer = setTimeout(done, wait * 1000);
const unsubscribe = bus.subscribe((event) => {
if (event.type !== "comment-created") return;
if (q.sessionId && event.sessionId !== q.sessionId) return;
if (q.surfaceId && event.surfaceId !== q.surfaceId) return;
done();
});
function done() {
clearTimeout(timer);
unsubscribe();
resolve();
}
});
all = await store.listComments(query);
comments = matches(all);
}
// The cursor advances past every comment in the window — not just the
// filtered ones — so the next call doesn't re-read the agent's own
// comments. collectFeedback already does this; mirror it here.
const lastSeq = all.length > 0 ? all[all.length - 1].seq : (afterSeq ?? 0);
// An author=user query is the agent listening (the viewer never filters by
// author) — what it receives here should not be re-delivered as piggyback.
if (q.author === "user" && q.sessionId && all.length > 0) {
await store.markAgentSeen(q.sessionId, lastSeq);
}
return { comments, lastSeq };
}
// --- auth ---
const isAuthenticated = (c: Context): boolean => {
if (!authToken) return true;
if (c.req.header("authorization") === `Bearer ${authToken}`) return true;
if (getCookie(c, "sideshow_key") === authToken) return true;
return c.req.query("key") === authToken;
};
const isUnauthenticatedSessionRead = (c: Context): boolean =>
publicRead === "session" && !isAuthenticated(c);
app.use("*", async (c, next) => {
const path = new URL(c.req.url).pathname;
if (authenticate) {
const result = await authenticate(c.req.raw);
if (result === true) return next();
if (result instanceof Response) return result;
if (path.startsWith("/api") || path === "/mcp") {
return c.json({ error: "unauthorized" }, 401);
}
return c.text("unauthorized", 401);
}
if (!authToken) return next();
if (path === "/guide" || path === "/setup" || path === "/agent-howto") return next();
const key = c.req.query("key");
if (key === authToken) {
setCookie(c, "sideshow_key", authToken, {
httpOnly: true,
sameSite: "Lax",
secure: new URL(c.req.url).protocol === "https:",
maxAge: 60 * 60 * 24 * 90,
path: "/",
});
return next();
}
if (publicRead && c.req.method === "GET" && isPublicReadAllowed(path, publicRead)) {
return next();
}
if (isAuthenticated(c)) return next();
if (path.startsWith("/api") || path === "/mcp") {
return c.json({ error: "unauthorized — send Authorization: Bearer <token>" }, 401);
}
return c.text("unauthorized — open this page as /?key=<your token>", 401);
});
// --- pages and docs ---
const withOrigin = (text: string, c: { req: { url: string } }) =>
text.replaceAll(LOCAL_ORIGIN, new URL(c.req.url).origin);
const withViewerConfig = (text: string, request: Request, isReadonly: boolean) => {
const config = [
`window.__SIDESHOW_BASE_PATH__=${JSON.stringify(requestBasePath(request))};`,
isReadonly ? "window.__SIDESHOW_READONLY__=true;" : "",
isReadonly && publicRead
? `window.__SIDESHOW_PUBLIC_READ__=${JSON.stringify(publicRead)};`
: "",
].join("");
const script = `<script>${config}</script>`;
const headClose = text.lastIndexOf("</head>");
return headClose >= 0
? `${text.slice(0, headClose)}${script}${text.slice(headClose)}`
: `${script}${text}`;
};
const configuredViewerHtml = (c: Context) =>
withViewerConfig(
withOrigin(viewerHtml, { req: { url: c.req.url } }),
c.req.raw,
!!publicRead && !isAuthenticated(c),
);
app.get("/", (c) => c.html(configuredViewerHtml(c)));
app.get("/session/:id", async (c) => {
if (isUnauthenticatedSessionRead(c) && !(await store.getSession(c.req.param("id")))) {
return c.text("Session not found", 404);
}
return c.html(configuredViewerHtml(c));
});
app.get("/session/:id/s/:surfaceId", async (c) => {
if (isUnauthenticatedSessionRead(c)) {
const session = await store.getSession(c.req.param("id"));
const surface = await store.getSurface(c.req.param("surfaceId"));
if (!session || !surface || surface.sessionId !== session.id) {
return c.text("Session or surface not found", 404);
}
}
return c.html(configuredViewerHtml(c));
});
app.get("/guide", (c) => c.text(withOrigin(guideMarkdown, c)));
app.get("/setup", (c) => c.text(withOrigin(setupText, c)));
app.get("/agent-howto", (c) => c.text(withOrigin(agentHowtoText, c)));
// Opt-in html kits available on this board (id, label, summary, classes) —
// for discovery (`sideshow kits`); the CSS/JS payloads are server-only.
app.get("/api/kits", (c) => c.json(kitSummaries()));
// --- theme (one board-level setting) ---
app.get("/api/theme", async (c) => {
const id = (await store.getSetting("theme")) ?? DEFAULT_THEME_ID;
return c.json({ id, themes: themeOptions() });
});
app.put("/api/theme", async (c) => {
const body = await c.req.json().catch(() => null);
const id = body && typeof body.id === "string" ? body.id : null;
if (!id || !themeOptions().some((t) => t.id === id)) {
return c.json({ error: "unknown theme id" }, 400);
}
await store.setSetting("theme", id);
bus.broadcast({ type: "theme-changed", id });
return c.json({ id });
});
// --- sessions ---
app.get("/api/sessions", async (c) => {
const [sessions, surfaces] = await Promise.all([store.listSessions(), store.listSurfaces()]);
const counts = new Map<string, number>();
for (const s of surfaces) counts.set(s.sessionId, (counts.get(s.sessionId) ?? 0) + 1);
return c.json(sessions.map((s) => ({ ...s, surfaceCount: counts.get(s.id) ?? 0 })));
});
app.post("/api/sessions", async (c) => {
const body = await c.req.json().catch(() => ({}));
const session = await store.createSession({
agent: typeof body.agent === "string" ? body.agent : "agent",
title: typeof body.title === "string" ? body.title : undefined,
cwd: typeof body.cwd === "string" ? body.cwd : undefined,
});
bus.broadcast({ type: "session-created", id: session.id });
return c.json(session, 201);
});
app.patch("/api/sessions/:id", async (c) => {
const body = await c.req.json().catch(() => null);
const hasTitle = body && typeof body.title === "string";
const hasShared = body && typeof body.shared === "boolean";
if (!hasTitle && !hasShared) {
return c.json({ error: 'body must include a "title" string or "shared" boolean' }, 400);
}
const id = c.req.param("id");
let session = await store.getSession(id);
if (!session) return c.json({ error: "session not found" }, 404);
if (hasTitle) session = await store.renameSession(id, body.title);
if (hasShared) session = await store.setSessionShared(id, body.shared);
if (!session) return c.json({ error: "session not found" }, 404);
bus.broadcast({ type: "session-updated", id: session.id });
return c.json(session);
});
app.delete("/api/sessions/:id", async (c) => {
const id = c.req.param("id");
if (!(await store.removeSession(id))) return c.json({ error: "session not found" }, 404);
bus.broadcast({ type: "session-deleted", id });
return c.json({ ok: true });
});
const listSessionSurfaces = async (c: any) => {
const session = await store.getSession(c.req.param("id"));
if (!session) return c.json({ error: "session not found" }, 404);
const surfaces = await store.listSurfaces(session.id);
return c.json(surfaces.map(surfaceMeta));
};
app.get("/api/sessions/:id/surfaces", listSessionSurfaces);
app.get("/api/sessions/:id/snippets", listSessionSurfaces); // legacy alias
// --- session trace ---
app.get("/api/sessions/:id/trace", async (c) => {
const session = await store.getSession(c.req.param("id"));
if (!session) return c.json({ error: "session not found" }, 404);
return c.json({ steps: await store.listTrace(session.id) });
});
// Ingest a batch of trace steps (the sync sends a windowed slice, or the tail
// since a cursor). `reset: true` replaces the list, for a full re-sync. Steps
// are sanitized and the per-session list is capped.
app.post("/api/sessions/:id/trace", async (c) => {
const session = await store.getSession(c.req.param("id"));
if (!session) return c.json({ error: "session not found" }, 404);
const body = await c.req.json().catch(() => null);
if (!body || !Array.isArray(body.steps)) {
return c.json({ error: 'body must include "steps" array' }, 400);
}
const clean: TraceStep[] = [];
for (const s of body.steps) {
if (!s || typeof s.label !== "string") continue;
clean.push({
label: s.label.slice(0, MAX_STEP_LABEL),
...(typeof s.kind === "string" && { kind: s.kind.slice(0, 40) }),
...(typeof s.detail === "string" && { detail: s.detail.slice(0, MAX_STEP_DETAIL) }),
...(typeof s.ts === "string" && { ts: s.ts }),
});
}
const prior = body.reset === true ? [] : await store.listTrace(session.id);
const merged = prior.concat(clean);
// roll the list so a long session keeps only its most recent steps
const bounded = merged.length > MAX_TRACE_STEPS ? merged.slice(-MAX_TRACE_STEPS) : merged;
await store.setTrace(session.id, bounded);
bus.broadcast({ type: "trace-updated", sessionId: session.id, count: bounded.length });
return c.json({ ok: true, added: clean.length, count: bounded.length });
});
// --- surfaces ---
const getSurface = async (c: any) => {
const surface = await store.getSurface(c.req.param("id"));
if (!surface) return c.json({ error: "surface not found" }, 404);
return c.json(surface);
};
app.get("/api/surfaces/:id", getSurface);
app.get("/api/snippets/:id", getSurface); // legacy alias
// Accepts either an existing session id, or agent/cwd fields to
// auto-create a session — so a bare `curl` one-liner works with no ceremony.
app.post("/api/surfaces", async (c) => {
const body = await c.req.json().catch(() => null);
if (!body || !Array.isArray(body.parts)) {
return c.json({ error: 'body must include a "parts" array' }, 400);
}
const parsed = validateSurfaceParts(body.parts);
if (!parsed.ok) return c.json({ error: parsed.error }, 400);
return publish(c, body, parsed.parts);
});
// Legacy html-only entry — sugar for a single html part. An optional `kits`
// array opts the part into style/behavior bundles; it's validated (strict)
// like any html part so an unknown kit id is a clean 400.
app.post("/api/snippets", async (c) => {
const body = await c.req.json().catch(() => null);
if (!body || typeof body.html !== "string" || !body.html.trim()) {
return c.json({ error: 'body must include non-empty "html" string' }, 400);
}
const parsed = validateSurfaceParts([htmlPart(body.html, body.kits)]);
if (!parsed.ok) return c.json({ error: parsed.error }, 400);
return publish(c, body, parsed.parts);
});
async function publish(c: any, body: any, parts: SurfacePart[]) {
const result = await publishSurface({
parts,
title: typeof body.title === "string" ? body.title : undefined,
session: typeof body.session === "string" ? body.session : undefined,
sessionTitle: typeof body.sessionTitle === "string" ? body.sessionTitle : undefined,
agent: typeof body.agent === "string" ? body.agent : undefined,
cwd: typeof body.cwd === "string" ? body.cwd : undefined,
});
if ("error" in result) return c.json({ error: result.error }, result.status);
return c.json(
{
...writeResult(result.surface),
...(result.userFeedback && { userFeedback: result.userFeedback }),
},
201,
);
}
const revise = async (c: any) => {
const body = await c.req.json().catch(() => null);
if (!body) return c.json({ error: "invalid JSON body" }, 400);
// surfaces: a `parts` array; snippets: an `html` string (single html part).
let parts: SurfacePart[] | undefined;
if (body.parts !== undefined) {
if (!Array.isArray(body.parts)) return c.json({ error: '"parts" must be an array' }, 400);
const parsed = validateSurfaceParts(body.parts);
if (!parsed.ok) return c.json({ error: parsed.error }, 400);
parts = parsed.parts;
} else if (typeof body.html === "string") {
const parsed = validateSurfaceParts([htmlPart(body.html, body.kits)]);
if (!parsed.ok) return c.json({ error: parsed.error }, 400);
parts = parsed.parts;
}
const result = await reviseSurface(c.req.param("id"), {
parts,
title: typeof body.title === "string" ? body.title : undefined,
});
if ("error" in result) return c.json({ error: result.error }, result.status);
return c.json({
...writeResult(result.surface),
...(result.userFeedback && { userFeedback: result.userFeedback }),
});
};
app.put("/api/surfaces/:id", revise);
app.put("/api/snippets/:id", revise); // legacy alias
const remove = async (c: any) => {
const surface = await store.getSurface(c.req.param("id"));
if (!surface) return c.json({ error: "surface not found" }, 404);
await store.removeSurface(surface.id);
bus.broadcast({ type: "surface-deleted", id: surface.id, sessionId: surface.sessionId });
return c.json({ ok: true });
};
app.delete("/api/surfaces/:id", remove);
app.delete("/api/snippets/:id", remove); // legacy alias
// --- comments ---
app.post("/api/comments", async (c) => {
const body = await c.req.json().catch(() => null);
if (!body || typeof body.text !== "string" || !body.text.trim()) {
return c.json({ error: 'body must include non-empty "text" string' }, 400);
}
const surface = typeof body.surface === "string" ? body.surface : body.snippet;
const result = await createComment({
text: body.text,
surface: typeof surface === "string" ? surface : undefined,
author: typeof body.author === "string" ? body.author : "user",
});
if ("error" in result) return c.json({ error: result.error }, result.status);
return c.json(
{ ...result.comment, ...(result.userFeedback && { userFeedback: result.userFeedback }) },
201,
);
});
// The viewer's update notice: running version vs latest published release.
app.get("/api/version", async (c) => {
if (!version) return c.json({ current: null, latest: null, updateAvailable: false });
const latest = await latestRelease();
const updateAvailable = latest !== null && versionGt(latest.version, version);
return c.json({
current: version,
latest: latest?.version ?? null,
updateAvailable,
upgradeCommand: updateAvailable ? (upgradeCommand ?? null) : null,
notes: updateAvailable ? (latest?.notes ?? null) : null,
});
});
// Long-poll friendly: ?wait=N holds the request open up to N seconds until
// a matching comment arrives. This is how terminal agents block on feedback.
app.get("/api/comments", async (c) => {
const sessionId = c.req.query("session");
const surfaceId = c.req.query("surface") ?? c.req.query("snippet");
if (isUnauthenticatedSessionRead(c)) {
if (!sessionId && !surfaceId) return c.json({ error: "session or surface required" }, 401);
if (sessionId && !(await store.getSession(sessionId))) {
return c.json({ error: "session not found" }, 404);
}
if (surfaceId) {
const surface = await store.getSurface(surfaceId);
if (!surface || (sessionId && surface.sessionId !== sessionId)) {
return c.json({ error: "surface not found" }, 404);
}
}
}
const result = await waitForComments({
sessionId,
surfaceId,
author: c.req.query("author"),
afterSeq: c.req.query("after") ? Number(c.req.query("after")) : undefined,
waitSeconds: Number(c.req.query("wait") ?? 0) || 0,
});
return c.json(result);
});
// --- rendering ---
// Serves one html part of a surface as a themed, sandboxed document. The
// viewer points an iframe here per html part; diff parts render natively in
// the viewer (they are data, not arbitrary markup) and never reach here.
app.get("/s/:id", async (c) => {
const surface = await store.getSurface(c.req.param("id"));
if (!surface) return c.text("Surface not found", 404);
const ver = c.req.query("ver");
let title = surface.title;
let parts = surface.parts;
if (ver && Number(ver) !== surface.version) {
const old = surface.history.find((h) => h.version === Number(ver));
if (!old) return c.text(`Version ${ver} not available`, 404);
title = old.title;
parts = old.parts;
}
const partParam = c.req.query("part");
const publicBasePath = requestBasePath(c.req.raw);
if (partParam == null && publicBasePath) {
return c.redirect(`${publicBasePath}/?surface=${encodeURIComponent(surface.id)}`, 302);
}
const idx = Number(partParam ?? 0);
const part = parts[idx];
if (!part || part.kind !== "html") return c.text("No html part at that index", 404);
c.header("X-Content-Type-Options", "nosniff");
// Theme: an explicit ?theme= (the viewer keys iframe srcs by it so a switch
// reloads the frame) wins; otherwise the persisted board theme; else default.
const themeId = c.req.query("theme") ?? (await store.getSetting("theme")) ?? DEFAULT_THEME_ID;
// Scheme: the viewer passes the light/dark mode it resolved so the iframe is
// pinned to it rather than re-deriving from the OS (which can diverge from
// the chrome across the frame boundary). Absent/invalid → follow the OS.
const modeParam = c.req.query("mode");
const mode = modeParam === "light" || modeParam === "dark" ? modeParam : undefined;
return c.html(
renderHtmlPage({
title,
html: part.html,
origin: new URL(c.req.url).origin,
theme: themeById(themeId),
mode,
kits: part.kits,
}),
);
});
// --- assets (agent-uploaded images, traces, files) ---
// Accepts raw bytes (the asset's own Content-Type, metadata via query) or a
// JSON envelope { data: base64, contentType, ... } — so curl --data-binary
// and a JSON client both work, and MCP can ride base64. The body is read once
// and only treated as an envelope when it is application/json carrying a
// base64 `data` string; a raw JSON asset (no top-level `data`) stays raw.
app.post("/api/assets", async (c) => {
const mime = (c.req.header("content-type") ?? "").split(";")[0].trim().toLowerCase();
// Reject oversize uploads before buffering the body into memory. The
// Content-Length header is the wire size; the post-decode cap in
// uploadAsset still applies (a base64 envelope decodes to ~3/4), so this
// is an early-out for obvious offenders, not the only check.
const declaredLen = Number(c.req.header("content-length") ?? 0);
if (declaredLen > MAX_ASSET_BYTES) {
return c.json({ error: `asset exceeds ${MAX_ASSET_BYTES} bytes` }, 413);
}
const buf = new Uint8Array(await c.req.arrayBuffer());
let envelope: any = null;
if (mime === "application/json") {
try {
const j = JSON.parse(new TextDecoder().decode(buf));
if (j && typeof j.data === "string") envelope = j;
} catch {
// not an envelope — fall through to the raw path
}
}
const kindQ = c.req.query("kind");
const body = envelope
? {
data: decodeBase64(envelope.data),
contentType:
typeof envelope.contentType === "string"
? envelope.contentType
: "application/octet-stream",
filename: typeof envelope.filename === "string" ? envelope.filename : undefined,
kind: isAssetKind(envelope.kind) ? envelope.kind : undefined,
session: typeof envelope.session === "string" ? envelope.session : undefined,
agent: typeof envelope.agent === "string" ? envelope.agent : undefined,
}
: {
data: buf,
contentType: mime || "application/octet-stream",
filename: c.req.query("filename"),
kind: isAssetKind(kindQ) ? kindQ : undefined,
session: c.req.query("session"),
agent: c.req.query("agent"),
};
const result = await uploadAsset(body);
if ("error" in result) return c.json({ error: result.error }, result.status);
const origin = new URL(c.req.url).origin;
return c.json({ ...result.asset, url: `${origin}/a/${result.asset.id}` }, 201);
});
app.get("/a/:id", async (c) => {
const id = c.req.param("id");
let asset = await store.getAsset(id);
// Optimistic uploads: an agent can derive an asset's URL from its content
// hash and publish a surface referencing it before (or while) the bytes are
// uploaded. Rather than 404 in that window, briefly wait for the bytes —
// but only when a live surface actually points at this id, so unknown ids
// still fail fast.
if (!asset && (await store.isAssetReferenced(id))) {
for (let i = 0; i < 20 && !asset; i++) {
await new Promise((resolve) => setTimeout(resolve, 150));
asset = await store.getAsset(id);
}
}
if (!asset) return c.text("Asset not found", 404);
await store.touchAsset(asset.id);
const { contentType, disposition } = assetServeHeaders(asset);
c.header("Content-Type", contentType);
c.header("Content-Disposition", disposition);
c.header("X-Content-Type-Options", "nosniff");
// Short revalidating cache (not immutable) so touch-on-serve keeps firing
// and the LRU clock reflects real views; asset ids are unique anyway.
c.header("Cache-Control", "private, max-age=60");
return c.body(asset.data as unknown as ArrayBuffer);
});
// --- live feed ---
app.get("/api/events", async (c) => {
const sessionId = c.req.query("session");
if (isUnauthenticatedSessionRead(c)) {
if (!sessionId) return c.json({ error: "session required" }, 401);
if (!(await store.getSession(sessionId))) return c.json({ error: "session not found" }, 404);
}
const eventSessionId = (event: Parameters<Parameters<EventBus["subscribe"]>[0]>[0]) => {
if ("sessionId" in event) return event.sessionId;
if (event.type.startsWith("session-")) return event.id;
return undefined;
};
return streamSSE(c, async (stream) => {
const queue: Parameters<Parameters<EventBus["subscribe"]>[0]>[0][] = [];
let wake: (() => void) | null = null;
const unsubscribe = bus.subscribe((event) => {
if (sessionId && eventSessionId(event) !== sessionId) return;
queue.push(event);
wake?.();
});
let open = true;
const close = () => {
open = false;
unsubscribe();
wake?.();
};
stream.onAbort(close);
c.req.raw.signal.addEventListener("abort", close, { once: true });
await stream.writeSSE({ event: "hello", data: "{}" });
while (open) {
while (queue.length > 0) {
await stream.writeSSE({ data: JSON.stringify(queue.shift()) });
}
let pingTimer: ReturnType<typeof setTimeout> | null = null;
await Promise.race([
new Promise<void>((resolve) => {