@vite-hub/comments 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +37 -15
  2. package/dist/anchor.d.ts +2 -2
  3. package/dist/{client-diagnostics-CcFpkbAk.js → client-diagnostics-Bubm7Shd.js} +20 -5
  4. package/dist/client-files-CJZl5Kc4.js +53 -0
  5. package/dist/client.d.ts +567 -13
  6. package/dist/client.js +1209 -34
  7. package/dist/{console-h4KlhIik.d.ts → console-D1lwNMZn.d.ts} +2 -0
  8. package/dist/{migrate-BDQ8xqUs.js → database-6hXRnqDE.js} +47 -2
  9. package/dist/database-CTo7mx6t.d.ts +575 -0
  10. package/dist/database.d.ts +2 -1
  11. package/dist/database.js +2 -2
  12. package/dist/{define-43mMR39K.js → define-BMBSVbD9.js} +1 -1
  13. package/dist/{define-B3TF9zzn.d.ts → define-CmIFU96x.d.ts} +8 -4
  14. package/dist/{errors-4gelGVmK.js → errors-BJTZ9iyv.js} +24 -0
  15. package/dist/{errors-C6qptPoG.js → errors-Dq4AHjza.js} +23 -3
  16. package/dist/index-RiHzmV16.d.ts +194 -0
  17. package/dist/index.d.ts +6 -7
  18. package/dist/index.js +57 -9
  19. package/dist/{install-W9ghhGoh.d.ts → install-BGGQKbQ4.d.ts} +9 -3
  20. package/dist/{install-BcMPgPk_.js → install-DrAse1Fa.js} +912 -60
  21. package/dist/{installed-B-PfERBU.js → installed-C3EoqJEY.js} +7 -6
  22. package/dist/{operations-GLeOqgMt.d.ts → operations-BKhUWYkb.d.ts} +10 -5
  23. package/dist/{operations-D4A1Fcgf.d.ts → operations-VyyNZusz.d.ts} +13 -2
  24. package/dist/{operations-DMMIfYPW.js → operations-lsVKE0GH.js} +312 -219
  25. package/dist/operations.d.ts +2 -2
  26. package/dist/operations.js +2 -2
  27. package/dist/overlay/client-DBmJ4C1M.js +4 -0
  28. package/dist/overlay/overlay.js +41 -65
  29. package/dist/page/loader.js +39 -47
  30. package/dist/{page-DtbMOEMd.d.ts → page-Bzj0CszG.d.ts} +1 -10
  31. package/dist/{page-B41ozN63.js → page-DRz_sDY4.js} +1 -1
  32. package/dist/{page-tools-shared-NHUjKI8E.js → page-tools-shared-BNnuPK93.js} +6 -3
  33. package/dist/{plugin-PS8PMYus.js → plugin-DRsNaJaK.js} +34 -8
  34. package/dist/realtime.d.ts +2 -2
  35. package/dist/realtime.js +2 -2
  36. package/dist/reply-id-P_bSuEng.js +12 -0
  37. package/dist/request-log-Dj9Vw7qG.js +105 -0
  38. package/dist/request-origin-CFU0TQ7E.js +49 -0
  39. package/dist/{rpc-RKPAusHp.js → rpc-BQqYx8kb.js} +23 -7
  40. package/dist/{rpc-HBcWtg0T.d.ts → rpc-CuJ5GLIz.d.ts} +1 -1
  41. package/dist/rpc.d.ts +1 -1
  42. package/dist/rpc.js +1 -1
  43. package/dist/runtime/auth.d.ts +2 -2
  44. package/dist/runtime/auth.js +2 -2
  45. package/dist/runtime/console.d.ts +1 -1
  46. package/dist/runtime/console.js +3 -3
  47. package/dist/runtime/index.d.ts +42 -13
  48. package/dist/runtime/index.js +224 -22
  49. package/dist/{server-D8k-0GXe.js → server-Yk610niJ.js} +1 -1
  50. package/dist/server.d.ts +6 -5
  51. package/dist/server.js +6 -6
  52. package/dist/service-Bj-Mg63c.d.ts +73 -0
  53. package/dist/{service-GHhhyQj4.js → service-DA5BwfPQ.js} +71 -14
  54. package/dist/{session-DVx-1Tym.d.ts → session-DUcEor2W.d.ts} +3 -3
  55. package/dist/{session-EkudzUmm.js → session-X_g9dnU5.js} +27 -30
  56. package/dist/{service-CFVm23k7.d.ts → store-CsUNfC1w.d.ts} +11 -72
  57. package/dist/table-names-B9LlRC0B.js +16 -0
  58. package/dist/testing.d.ts +1 -1
  59. package/dist/testing.js +38 -5
  60. package/dist/{types-CZujrMFd.d.ts → types-BLaYh0_f.d.ts} +48 -4
  61. package/dist/{types-BIS0hCEl.d.ts → types-C35INXIs.d.ts} +88 -4
  62. package/dist/vite.d.ts +24 -7
  63. package/dist/vite.js +322 -173
  64. package/package.json +9 -9
  65. package/dist/errors-CyQyKAvy.d.ts +0 -185
  66. package/dist/index-DNhy69Wt.d.ts +0 -83
  67. package/dist/overlay/client-DmsSMOzi.js +0 -4
@@ -1,15 +1,17 @@
1
- import { t as commentsErrorDiagnostics } from "../errors-C6qptPoG.js";
2
- import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-B41ozN63.js";
3
- import { a as commentThreadSummary, c as hiddenThreadsNote, n as commentAnchorSchema, o as commentThreadsText, r as commentInputSchemas, s as describeCommentThread, t as commentActions } from "../operations-DMMIfYPW.js";
1
+ import "../client-files-CJZl5Kc4.js";
2
+ import { t as commentsErrorDiagnostics } from "../errors-Dq4AHjza.js";
3
+ import { i as commentsRoute, n as commentsPageScope, o as normalizeCommentPage } from "../page-DRz_sDY4.js";
4
+ import { a as commentThreadSummary, c as hiddenThreadsNote, n as commentAnchorSchema, o as commentThreadsText, r as commentInputSchemas, s as describeCommentThread, t as commentActions } from "../operations-lsVKE0GH.js";
4
5
  import { t as invariant } from "../invariant-D8_xBqmZ.js";
5
- import { a as deniedError, d as mentionedPeople, n as can, r as contextSchema } from "../service-GHhhyQj4.js";
6
+ import { h as readAttachment, i as contextSchema, n as base64, o as deniedError, p as mentionedPeople, r as can } from "../service-DA5BwfPQ.js";
6
7
  import { i as text, n as guestFromHeaders, t as authorOf } from "../identity-CBOzgxSf.js";
7
- import { c as validateCommentsDefinition, o as deniedForMissingPolicy } from "../define-43mMR39K.js";
8
+ import { c as validateCommentsDefinition, o as deniedForMissingPolicy } from "../define-BMBSVbD9.js";
8
9
  import { a as runWithActiveCloudflareEnv, i as getActiveCloudflareBinding, r as rememberGitHubToken, t as forgetGitHubToken } from "../tokens-DSbwkVSy.js";
9
- import { r as resolveCommentsRuntime } from "../installed-B-PfERBU.js";
10
- import { t as commentsErrors } from "../errors-4gelGVmK.js";
11
- import { a as viteHubPageSessionHandler, n as resolveCommentsPage, o as forwardedRequestOrigin, t as resolveCommentsIdentity } from "../session-EkudzUmm.js";
12
- import { n as installedComments, t as defineCommentsPlugin } from "../plugin-PS8PMYus.js";
10
+ import { t as forwardedRequestOrigin } from "../request-origin-CFU0TQ7E.js";
11
+ import { t as commentsErrors } from "../errors-BJTZ9iyv.js";
12
+ import { a as runtimeOf, r as resolveCommentsRuntime, t as commentSendOf } from "../installed-C3EoqJEY.js";
13
+ import { a as viteHubPageSessionHandler, n as resolveCommentsPage, t as resolveCommentsIdentity } from "../session-X_g9dnU5.js";
14
+ import { n as installedComments, t as defineCommentsPlugin } from "../plugin-DRsNaJaK.js";
13
15
  import { getStandardContext, installRequestStandardContext } from "@vite-hub/runtime/internal/h3";
14
16
  import * as v from "valibot";
15
17
  import { defineGrant } from "@vite-hub/runtime/internal/grant";
@@ -30,7 +32,8 @@ const createBody = v.object({
30
32
  const replyBody = v.object({
31
33
  body: commentInputSchemas.reply.entries.body,
32
34
  mentions: commentInputSchemas.reply.entries.mentions,
33
- attachments: commentInputSchemas.reply.entries.attachments
35
+ attachments: commentInputSchemas.reply.entries.attachments,
36
+ requestId: commentInputSchemas.reply.entries.requestId
34
37
  });
35
38
  const editBody = v.object({
36
39
  body: commentInputSchemas.edit.entries.body,
@@ -51,8 +54,14 @@ const fieldBody = v.object({
51
54
  function status(code) {
52
55
  switch (code) {
53
56
  case "COMMENTS_NOT_FOUND":
54
- case "COMMENTS_CONTENT_MISSING": return 404;
57
+ case "COMMENTS_CONTENT_MISSING":
58
+ case "COMMENTS_SEND_OFF": return 404;
59
+ case "COMMENTS_SEND_GRANT_INVALID": return 401;
60
+ case "COMMENTS_SEND_CODE_EXPIRED": return 410;
61
+ case "COMMENTS_SEND_CODE_USED": return 409;
62
+ case "COMMENTS_SEND_CODE_REFUSED": return 422;
55
63
  case "COMMENTS_FORBIDDEN":
64
+ case "COMMENTS_SEND_INSECURE":
56
65
  case "COMMENTS_POLICY_MISSING":
57
66
  case "COMMENTS_FIELD_FORBIDDEN": return 403;
58
67
  case "COMMENTS_RESOLVED":
@@ -170,7 +179,7 @@ function leaseHolder(error) {
170
179
  return typeof name === "string" && name ? name : "Someone";
171
180
  }
172
181
  /**
173
- * The Comments API at `/api/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
182
+ * The Comments API at `/_vitehub/comments/**`, as a Fetchable: mount it as a Nitro or H3 route, or call
174
183
  * `fetch(request)`. The overlay calls it; every route checks the `authorize` policy of `defineComments()` for the user of
175
184
  * the request, and inline edits also check `content.can()`.
176
185
  */
@@ -272,6 +281,7 @@ function createCommentsHandler(options) {
272
281
  url: `${route}/auth/github`
273
282
  } : void 0;
274
283
  const signOut = user && user.github && github ? `${route}/auth/sign-out` : void 0;
284
+ const send = Boolean(comments.options.send && user && !user.guest && comment && await commentSendOf(comments));
275
285
  return json({ data: {
276
286
  user: user ? authorOf(user) : null,
277
287
  ...user && user.github ? { github: user.github } : {},
@@ -286,6 +296,7 @@ function createCommentsHandler(options) {
286
296
  realtime: options.realtime,
287
297
  ...options.presence === false ? { presence: false } : {},
288
298
  content: Boolean(options.content),
299
+ ...send ? { send: true } : {},
289
300
  ...subject ? { subject } : {},
290
301
  ...revision === void 0 ? {} : { revision }
291
302
  } });
@@ -481,9 +492,80 @@ function createCommentsHandler(options) {
481
492
  const env = request["~standard"].runtime?.cloudflare?.env;
482
493
  return env ? await runWithActiveCloudflareEnv(env, () => handle(request)) : await handle(request);
483
494
  } };
495
+ async function sendRoute(request, url, parts, pageOf) {
496
+ const service = await commentSendOf(comments);
497
+ if (!service) return failure$1(commentsErrors.COMMENTS_SEND_OFF());
498
+ const method = request.method;
499
+ const [, action, code] = parts;
500
+ if (method === "POST" && action === "pair" && !code) {
501
+ const [error, paired] = await service.pair(await readJson(request), forwardedRequestOrigin(request));
502
+ return error ? json({
503
+ error,
504
+ reason: {
505
+ COMMENTS_SEND_CODE_EXPIRED: "expired",
506
+ COMMENTS_SEND_CODE_USED: "used",
507
+ COMMENTS_SEND_CODE_REFUSED: "refused",
508
+ COMMENTS_SEND_INSECURE: "insecure"
509
+ }[error.code] ?? "invalid"
510
+ }, { status: status(error.code) }) : json({ data: paired });
511
+ }
512
+ if (method === "GET" && action && action.startsWith("send_") && !code) {
513
+ const token = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
514
+ if (!token) return failure$1(commentsErrors.COMMENTS_SEND_GRANT_INVALID());
515
+ return respond(await service.read(decodeURIComponent(action), token));
516
+ }
517
+ const { user, gate } = await identityOf(request);
518
+ const pathname = url.pathname;
519
+ const caller = async () => {
520
+ const subject = (await pageOf())?.subject;
521
+ if (!subject) return void 0;
522
+ return {
523
+ user,
524
+ gate,
525
+ subject,
526
+ page: normalizeCommentPage(url.searchParams.get("page") ?? "/"),
527
+ origin: forwardedRequestOrigin(request),
528
+ route: pathname.slice(0, pathname.indexOf(commentsRoute) + commentsRoute.length)
529
+ };
530
+ };
531
+ if (action === "pair" && code && !parts[3]) {
532
+ const who = {
533
+ user,
534
+ gate,
535
+ subject: {
536
+ kind: "page",
537
+ id: "/"
538
+ },
539
+ page: "/",
540
+ origin: "",
541
+ route: ""
542
+ };
543
+ if (method === "GET") return json({ data: await service.check(who, decodeURIComponent(code)) });
544
+ if (method === "DELETE") {
545
+ await service.cancel(who, decodeURIComponent(code));
546
+ return json({ data: null });
547
+ }
548
+ }
549
+ const who = await caller();
550
+ if (!who) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "page: Give the page that Send is on." }));
551
+ if (method === "GET" && action === "status" && !code) return json({ data: await service.status(who) });
552
+ if (method === "POST" && action === "start" && !code) return respond(await service.start(who));
553
+ if (method === "POST" && action === "allow" && !code) {
554
+ const body = await readJson(request);
555
+ const given = typeof body === "object" && body !== null ? Reflect.get(body, "code") : void 0;
556
+ if (typeof given !== "string" || !given) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "code: Send the setup code that the agent used." }));
557
+ const selection = typeof body === "object" && body !== null ? Reflect.get(body, "selection") : void 0;
558
+ return respond(await service.allow(who, given, typeof selection === "string" ? selection : ""));
559
+ }
560
+ if (method === "POST" && !action) return respond(await service.send(who));
561
+ return json({ error: {
562
+ code: "COMMENTS_NOT_FOUND",
563
+ why: `No Comments route ${method} ${url.pathname.slice(url.pathname.indexOf(commentsRoute) + commentsRoute.length)}.`
564
+ } }, { status: 404 });
565
+ }
484
566
  async function route(request) {
485
567
  const url = new URL(request.url);
486
- const path = url.pathname.slice(url.pathname.indexOf("/api/_vitehub/comments") + 22).replace(/\/+$/, "") || "/";
568
+ const path = url.pathname.slice(url.pathname.indexOf("/_vitehub/comments") + 18).replace(/\/+$/, "") || "/";
487
569
  const parts = path.split("/").filter(Boolean);
488
570
  const method = request.method;
489
571
  const page = url.searchParams.get("page");
@@ -494,10 +576,11 @@ function createCommentsHandler(options) {
494
576
  id: subjectId
495
577
  } } : void 0;
496
578
  const subjectOf = async () => (await pageOf())?.subject;
497
- if (method !== "GET" && !sameOrigin(request)) return json({ error: {
579
+ if (method !== "GET" && !(method === "POST" && path === "/send/pair") && !sameOrigin(request)) return json({ error: {
498
580
  code: "COMMENTS_FORBIDDEN",
499
581
  why: "Comments requests must come from the site's own pages."
500
582
  } }, { status: 403 });
583
+ if (parts[0] === "send") return await sendRoute(request, url, parts, pageOf);
501
584
  if (method === "GET" && path === "/session") {
502
585
  const current = await pageOf();
503
586
  return await session(request, current?.subject, current?.revision);
@@ -547,10 +630,11 @@ function createCommentsHandler(options) {
547
630
  const threadId = decodeURIComponent(parts[1]);
548
631
  const action = parts[2];
549
632
  const messageId = parts[3] ? decodeURIComponent(parts[3]) : void 0;
550
- if (method === "GET" && !action) return await act(request, "read", (who) => commentActions.get({ id: threadId }, who), (thread, who) => threadResponse(who, thread));
633
+ if (method === "GET" && !action) return await act(request, "read", (who) => commentActions.get({ threadId }, who), (thread, who) => threadResponse(who, thread));
551
634
  if (method === "POST" && action === "comments" && !messageId) {
552
635
  const parsed = v.safeParse(replyBody, await readJson(request));
553
636
  if (!parsed.success) return invalid(parsed.issues);
637
+ if (request.headers.has("x-vitehub-comments-outbox-account") && !("requestId" in parsed.output && parsed.output.requestId)) return failure$1(commentsErrors.COMMENTS_INVALID_INPUT({ issue: "Queued replies need server support for requestId." }));
554
638
  return await act(request, "write", (who) => commentActions.reply({
555
639
  ...parsed.output,
556
640
  threadId
@@ -676,6 +760,49 @@ function spend(grant, action, threadId) {
676
760
  const allowed = toolGrant.consume(grant);
677
761
  invariant(allowed.action === action && allowed.threadId === threadId, "each Comments tool spends the grant that it issued for the same action and thread");
678
762
  }
763
+ /** The bytes of images that one `comments_get_thread` answer carries, before Base64. */
764
+ const maximumThreadImageBytes = 4194304;
765
+ /**
766
+ * The image attachments of a thread, in message order, for a reader who may read it, until they reach
767
+ * `maximumThreadImageBytes`. `notes` says which files the Agent does not see, and why.
768
+ */
769
+ async function threadImages(comments, thread, user) {
770
+ const runtime = await runtimeOf(comments);
771
+ if (!runtime) return {
772
+ images: [],
773
+ notes: [`Could not read the attachments: ${commentsErrors.COMMENTS_NOT_INSTALLED().why}`]
774
+ };
775
+ const images = [];
776
+ const notes = [];
777
+ let bytes = 0;
778
+ for (const key of thread.messages.flatMap((message) => message.attachments)) try {
779
+ const file = await readAttachment(runtime, key, {
780
+ thread,
781
+ user
782
+ });
783
+ if (!file.inline) continue;
784
+ if (bytes + file.size > maximumThreadImageBytes) {
785
+ notes.push(`Not shown: ${key}, because the images of one answer stay under ${maximumThreadImageBytes / 1024 / 1024} MB.`);
786
+ continue;
787
+ }
788
+ images.push({
789
+ data: base64(new Uint8Array(await file.data.arrayBuffer())),
790
+ mimeType: file.type
791
+ });
792
+ bytes += file.size;
793
+ } catch (error) {
794
+ if (commentsErrorDiagnostics.COMMENTS_R0020.is(error)) notes.push(`Could not read ${key}: The file is missing or unavailable.`);
795
+ else if (commentsErrorDiagnostics.COMMENTS_R0014.is(error) || commentsErrorDiagnostics.COMMENTS_R0021.is(error)) notes.push(`Could not read ${key}: The app has no attachment reader.`);
796
+ else {
797
+ console.warn(`[vitehub] Comments could not read attachment ${JSON.stringify(key)}:`, error);
798
+ notes.push(`Could not read ${key}: The file could not be loaded.`);
799
+ }
800
+ }
801
+ return {
802
+ images,
803
+ notes
804
+ };
805
+ }
679
806
  /**
680
807
  * The Comments tools for an app's own MCP server. Each call resolves the Comments identity and checks `authorize`,
681
808
  * as the overlay does. The server supplies the checked `context.user`. ViteHub MCP offers the comment operations instead.
@@ -719,7 +846,7 @@ function commentsMcpTools(comments, options = {}) {
719
846
  })
720
847
  };
721
848
  }
722
- return [
849
+ const tools = [
723
850
  {
724
851
  name: "comments_list_threads",
725
852
  title: "List ViteHub Comments threads",
@@ -817,7 +944,7 @@ function commentsMcpTools(comments, options = {}) {
817
944
  {
818
945
  name: "comments_get_thread",
819
946
  title: "Read a ViteHub Comments thread",
820
- description: "ViteHub Comments: read one thread that people left with the Comments toolbar: its page, the element and Vue components with their source files, the browser and build, and every comment with its time. Use it to find the code to change.",
947
+ description: "ViteHub Comments: read one thread that people left with the Comments toolbar: its page, the element and Vue components with their source files, the browser and build, every comment with its time, and the images attached to it. Use it to find the code to change.",
821
948
  section: "comments",
822
949
  annotations: { readOnlyHint: true },
823
950
  inputSchema: {
@@ -830,11 +957,14 @@ function commentsMcpTools(comments, options = {}) {
830
957
  additionalProperties: false
831
958
  },
832
959
  async call(input, context) {
833
- const found = await threadFor(input, await identityFor(context), "read");
960
+ const identity = await identityFor(context);
961
+ const found = await threadFor(input, identity, "read");
834
962
  if (!("thread" in found)) return found;
835
963
  const { thread } = found;
964
+ const { images, notes } = await threadImages(comments, thread, identity.user);
836
965
  return {
837
- text: describeCommentThread(thread),
966
+ text: [describeCommentThread(thread), ...notes].join("\n"),
967
+ ...images.length ? { images } : {},
838
968
  structured: { thread: { ...thread } }
839
969
  };
840
970
  }
@@ -854,7 +984,11 @@ function commentsMcpTools(comments, options = {}) {
854
984
  body: {
855
985
  type: "string",
856
986
  description: "Markdown, at most 10,000 characters."
857
- }
987
+ },
988
+ ...comments.options.send ? { send: {
989
+ type: "string",
990
+ description: "The send ID from comments_get_send when answering an ask."
991
+ } } : {}
858
992
  },
859
993
  required: ["id", "body"],
860
994
  additionalProperties: false
@@ -866,10 +1000,23 @@ function commentsMcpTools(comments, options = {}) {
866
1000
  const { thread, grant } = found;
867
1001
  const author = identity.user ? authorOf(identity.user) : guestFor(context);
868
1002
  if (!author) return forbidden("write");
1003
+ const send = text(input.send);
1004
+ if (send) {
1005
+ const service = await commentSendOf(comments);
1006
+ const opened = identity.user && !identity.user.guest && await service?.readOwn(identity.user, send, {
1007
+ gate: identity.gate,
1008
+ console: admitted
1009
+ });
1010
+ if (!opened || !opened.threads.some((entry) => entry.id === thread.id && entry.role === "ask")) return forbidden("write");
1011
+ }
869
1012
  spend(grant, "write", thread.id);
870
1013
  const [error, message] = await comments.reply(thread.id, {
871
1014
  body: text(input.body) ?? "",
872
- author
1015
+ author,
1016
+ ...send ? { actor: {
1017
+ id: "comments-mcp",
1018
+ name: "Comments agent"
1019
+ } } : {}
873
1020
  });
874
1021
  if (error) return failure(error.why);
875
1022
  await comments.flush();
@@ -919,6 +1066,61 @@ function commentsMcpTools(comments, options = {}) {
919
1066
  }
920
1067
  }
921
1068
  ];
1069
+ if (comments.options.send) tools.push({
1070
+ name: "comments_get_send",
1071
+ title: "Read a ViteHub Comments send",
1072
+ description: "ViteHub Comments: read the threads that the signed-in user sent to their agent with Send in the comment pill. Each thread says whether it is an ask, the user's own question, or a quote, what someone else said. Without an id, it reads the user's latest send that no agent read yet. Answer each ask with comments_reply, passing the send ID as `send`.",
1073
+ section: "comments",
1074
+ annotations: { readOnlyHint: true },
1075
+ inputSchema: {
1076
+ type: "object",
1077
+ properties: { id: {
1078
+ type: "string",
1079
+ description: "The send id, such as send_… from the delivery. Default: the latest unread send."
1080
+ } },
1081
+ additionalProperties: false
1082
+ },
1083
+ async call(input, context) {
1084
+ const { user, gate } = await identityFor(context);
1085
+ if (!user || user.guest) return forbidden("read");
1086
+ const service = await commentSendOf(comments);
1087
+ if (!service) return failure(`${commentsErrors.COMMENTS_SEND_OFF().why} ${commentsErrors.COMMENTS_SEND_OFF().fix}`);
1088
+ const id = text(input.id);
1089
+ const opened = await service.readOwn(user, id, {
1090
+ gate,
1091
+ console: admitted
1092
+ });
1093
+ if (!opened) return failure(id ? `No send ${id} of this user.` : "This user has no send that an agent did not read yet.");
1094
+ const { send, threads } = opened;
1095
+ return {
1096
+ text: [`Send ${send.id} from ${send.page}, ${new Date(send.createdAt).toISOString()}: ${threads.length} ${threads.length === 1 ? "thread" : "threads"}.`, ...threads.flatMap((thread) => ["", `${thread.role === "ask" ? "Ask" : "Quote"}: ${describeCommentThread(thread)}`])].join("\n"),
1097
+ structured: {
1098
+ send: { ...send },
1099
+ threads: threads.map((thread) => ({ ...thread }))
1100
+ }
1101
+ };
1102
+ }
1103
+ });
1104
+ return tools;
1105
+ }
1106
+ //#endregion
1107
+ //#region ../internal/src/runtime/mcp-server.ts
1108
+ /** The MCP result of a `ViteHubMcpTool` call: a text block, then one image block for each image. */
1109
+ function mcpToolResult(result) {
1110
+ const content = [{
1111
+ type: "text",
1112
+ text: result.text
1113
+ }];
1114
+ for (const image of result.images ?? []) content.push({
1115
+ type: "image",
1116
+ data: image.data,
1117
+ mimeType: image.mimeType
1118
+ });
1119
+ return {
1120
+ content,
1121
+ ...result.structured ? { structuredContent: result.structured } : {},
1122
+ isError: result.isError === true
1123
+ };
922
1124
  }
923
1125
  new TextEncoder();
924
1126
  /** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
@@ -1110,4 +1312,4 @@ function createCommentsGitHubLogin(options = {}) {
1110
1312
  };
1111
1313
  }
1112
1314
  //#endregion
1113
- export { commentsDefinitionOf, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, selectCommentsDatabase, viteHubPageSessionHandler };
1315
+ export { commentsDefinitionOf, commentsMcpTools, createCommentsGitHubLogin, createCommentsHandler, defineCommentsPlugin, githubLoginEnv, installedComments, mcpToolResult, selectCommentsDatabase, viteHubPageSessionHandler };
@@ -1,4 +1,4 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-Dq4AHjza.js";
2
2
  //#region src/operations-core/server.ts
3
3
  const key = Symbol.for("vitehub.comments.runtime");
4
4
  const scope = globalThis;
package/dist/server.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { d as CommentsPeople, x as validateCommentsDefinition } from "./define-B3TF9zzn.js";
2
- import { a as maximumCommentBodyLength, c as CommentsTables, i as CommentsRuntime, l as createCommentsStore, n as CommentsAttachmentStore, o as CommentsDatabase, r as CommentsForgeHooks, s as CommentsStore } from "./service-CFVm23k7.js";
3
- import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-GLeOqgMt.js";
4
- import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-HBcWtg0T.js";
5
- import { n as installComments, t as InstallCommentsOptions } from "./install-W9ghhGoh.js";
1
+ import { b as validateCommentsDefinition, d as CommentsPeople } from "./define-CmIFU96x.js";
2
+ import { i as createCommentsStore, n as CommentsStore, r as CommentsTables, t as CommentsDatabase } from "./store-CsUNfC1w.js";
3
+ import { a as maximumCommentBodyLength, i as CommentsRuntime, n as CommentsAttachmentStore, r as CommentsForgeHooks } from "./service-Bj-Mg63c.js";
4
+ import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-BKhUWYkb.js";
5
+ import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-CuJ5GLIz.js";
6
+ import { n as installComments, t as InstallCommentsOptions } from "./install-BGGQKbQ4.js";
6
7
  //#region src/operations-core/server.d.ts
7
8
  /** Where mentions find people. The same shape as `defineComments({ people })`. */
8
9
  export type CommentsUsers = CommentsPeople;
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
- import { r as createCommentsStore, t as installComments } from "./install-BcMPgPk_.js";
2
- import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-DMMIfYPW.js";
3
- import { t as createRpcTransport } from "./rpc-RKPAusHp.js";
4
- import { u as maximumCommentBodyLength } from "./service-GHhhyQj4.js";
5
- import { c as validateCommentsDefinition } from "./define-43mMR39K.js";
6
- import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-D8k-0GXe.js";
1
+ import { r as createCommentsStore, t as installComments } from "./install-DrAse1Fa.js";
2
+ import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-lsVKE0GH.js";
3
+ import { t as createRpcTransport } from "./rpc-BQqYx8kb.js";
4
+ import { f as maximumCommentBodyLength } from "./service-DA5BwfPQ.js";
5
+ import { c as validateCommentsDefinition } from "./define-BMBSVbD9.js";
6
+ import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-Yk610niJ.js";
7
7
  export { commentActions, commentAnchorSchema, commentInputSchemas, commentsOperations, commentsRuntime, createAuthUsers, createCommentsStore, createRpcTransport, hasCommentsRuntime, installComments, installCommentsRuntime, maximumCommentBodyLength, validateCommentsDefinition };
@@ -0,0 +1,73 @@
1
+ import { T as CommentThread } from "./types-BLaYh0_f.js";
2
+ import { d as CommentsPeople, g as CommentsUser, l as CommentsDefinition } from "./define-CmIFU96x.js";
3
+ import { n as CommentsStore } from "./store-CsUNfC1w.js";
4
+ import "valibot";
5
+ //#region ../internal/src/runtime/client-rate-limit.d.ts
6
+ /** The part of `checkRateLimit()` from `vite-hub/rate-limit` that a public write calls. */
7
+ type SharedRateLimit = (request: Request, name: string, options: {
8
+ key: string;
9
+ limit: number;
10
+ window: `${number}${"ms" | "s" | "m" | "h" | "d"}`;
11
+ }) => Promise<[unknown, {
12
+ allowed: boolean;
13
+ reason?: string;
14
+ retryAfter?: number;
15
+ cause?: unknown;
16
+ } | undefined]>;
17
+ //#endregion
18
+ //#region src/operations-core/service.d.ts
19
+ /** Longest message, in characters. */
20
+ declare const maximumCommentBodyLength = 10000;
21
+ /** The parts of a Blob store that attachments use: `blob` of `@vite-hub/blob`. */
22
+ interface CommentsAttachmentStore {
23
+ put: (pathname: string, body: Uint8Array, options: {
24
+ contentType: string;
25
+ }) => Promise<readonly [unknown, unknown]>;
26
+ get?: (pathname: string) => Promise<readonly [unknown, Blob | null | undefined]>;
27
+ }
28
+ /** A file to answer, with the headers that keep a browser from running it. */
29
+ interface CommentsAttachmentBody {
30
+ key: string;
31
+ name: string;
32
+ /** The stored media type when Comments attaches that type, else `application/octet-stream`. */
33
+ type: string;
34
+ size: number;
35
+ /** Whether a browser may show it in the page: images other than SVG. */
36
+ inline: boolean;
37
+ data: Blob;
38
+ }
39
+ /** The pull request sync of `defineComments({ forge })`. */
40
+ interface CommentsForgeHooks {
41
+ /** Starts the sync of a thread after a change. */
42
+ changed: (threadId: string) => void;
43
+ /** The threads with their `forge` link. */
44
+ attach: (threads: CommentThread[]) => Promise<CommentThread[]>;
45
+ }
46
+ /** Everything that the comment operations, the server API, and the overlay API share. */
47
+ interface CommentsRuntime {
48
+ definition: CommentsDefinition;
49
+ /**
50
+ * The app's `identify`, given the server event of a call. With it, the comment operations ask it for the user, as
51
+ * the overlay API does, instead of taking the Console's user.
52
+ */
53
+ identify?: (event: unknown) => Promise<CommentsUser | null>;
54
+ store: CommentsStore;
55
+ /** The Auth adapter. `people` wins over it. Without both, `@` finds the authors that the store knows. */
56
+ users?: CommentsPeople;
57
+ /** Vite's serve command, for the default guest policy. */
58
+ development?: boolean;
59
+ /** The Blob store for attachments, when the app has one and no `storeAttachment`. */
60
+ attachments?: CommentsAttachmentStore;
61
+ forge?: CommentsForgeHooks;
62
+ /**
63
+ * `checkRateLimit` of ViteHub Rate Limit, when it counts in a KV store that every server process shares. Guest writes
64
+ * then count under the Rate Limit name `comments`. Without it, they count in the memory of this process.
65
+ */
66
+ rateLimit?: SharedRateLimit;
67
+ /** Work that runs after the answer, such as `onMention`. `flush()` of the server API waits for it. */
68
+ background?: (task: Promise<unknown>) => void;
69
+ /** Runs after someone opens a thread again. With Send, it puts back the sends that carried the thread. */
70
+ reopened?: (thread: CommentThread) => Promise<unknown>;
71
+ }
72
+ //#endregion
73
+ export { maximumCommentBodyLength as a, CommentsRuntime as i, CommentsAttachmentStore as n, SharedRateLimit as o, CommentsForgeHooks as r, CommentsAttachmentBody as t };
@@ -1,8 +1,10 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
- import { t as foldName } from "./fold-name-B7Zb3-MF.js";
1
+ import { t as replyMessageId } from "./reply-id-P_bSuEng.js";
2
+ import { t as commentsErrorDiagnostics } from "./errors-Dq4AHjza.js";
3
3
  import { t as isPagePath } from "./path--zk6PEMz.js";
4
+ import { t as foldName } from "./fold-name-B7Zb3-MF.js";
4
5
  import { r as guestIdPrefix } from "./identity-CBOzgxSf.js";
5
- import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-43mMR39K.js";
6
+ import { i as defaultPolicy, o as deniedForMissingPolicy, t as builtinCommentSubjects } from "./define-BMBSVbD9.js";
7
+ import { t as logFailure } from "./request-log-Dj9Vw7qG.js";
6
8
  import * as v from "valibot";
7
9
  //#region ../internal/src/runtime/client-rate-limit.ts
8
10
  const windowPattern = /^(\d+)(ms|s|m|h|d)$/;
@@ -144,20 +146,23 @@ function scopeOf(runtime, target) {
144
146
  }
145
147
  /**
146
148
  * The one access policy of every surface: `authorize`, else `defaultPolicy()`. Only `true` allows. `gate` says what the
147
- * server checked before, such as the Console's section access; `development` defaults to the runtime's.
149
+ * server checked before, such as the Console's section access; `development` defaults to the runtime's. `authorize`
150
+ * gets `development` from it. It gets `console` only from `context`: a mention check keeps the writer's gate, but the
151
+ * mentioned person was not admitted by the Console.
148
152
  */
149
153
  async function can(runtime, context, gate = {}) {
150
154
  const { authorize } = runtime.definition;
151
155
  const subject = context.subject ?? context.thread?.subject;
152
- const full = {
153
- ...context,
154
- user: context.user ? { ...context.user } : null,
155
- ...subject ? { subject } : {}
156
- };
157
156
  const checked = {
158
157
  ...gate,
159
158
  development: gate.development ?? runtime.development === true
160
159
  };
160
+ const full = {
161
+ ...context,
162
+ user: context.user ? { ...context.user } : null,
163
+ ...subject ? { subject } : {},
164
+ development: checked.development
165
+ };
161
166
  if (authorize) return await authorize(full) === true;
162
167
  if (defaultPolicy(full.user, checked, full.action)) return true;
163
168
  if (deniedForMissingPolicy(runtime.definition, full.user, checked)) warnMissingPolicy();
@@ -299,7 +304,7 @@ const contextSchema = v.object({
299
304
  }))
300
305
  });
301
306
  const revisionSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
302
- /** The retry key of `comments.create`, such as `crypto.randomUUID()`. */
307
+ /** The retry key of `comments.create` and `comments.reply`, such as `crypto.randomUUID()`. */
303
308
  const requestIdSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(200));
304
309
  const attachmentKey = v.pipe(v.string(), v.minLength(1), v.maxLength(500));
305
310
  function invalid(issues, field) {
@@ -342,10 +347,23 @@ async function announce(runtime, thread, message, mentions, fresh, options) {
342
347
  thread
343
348
  });
344
349
  } catch (error) {
345
- globalThis.console.error("[vitehub] Comments onComment failed:", error);
350
+ logFailure({
351
+ field: "comments",
352
+ fields: {
353
+ hook: "onComment",
354
+ thread: thread.id
355
+ },
356
+ message: "Comments onComment failed",
357
+ error,
358
+ ...options.request ? { request: options.request } : {}
359
+ }, () => globalThis.console.error("[vitehub] Comments onComment failed:", error));
346
360
  }
347
361
  if (!onMention || !fresh.length) return;
348
362
  const link = subjectDefinition(runtime, thread.subject.kind)?.link?.(thread);
363
+ const keep = (promise) => {
364
+ options.waitUntil?.(promise);
365
+ runtime.background?.(promise);
366
+ };
349
367
  const task = (async () => {
350
368
  try {
351
369
  await onMention({
@@ -355,7 +373,16 @@ async function announce(runtime, thread, message, mentions, fresh, options) {
355
373
  ...link ? { link } : {}
356
374
  });
357
375
  } catch (error) {
358
- globalThis.console.error("[vitehub] Comments onMention failed:", error);
376
+ logFailure({
377
+ field: "comments",
378
+ fields: {
379
+ hook: "onMention",
380
+ thread: thread.id
381
+ },
382
+ message: "Comments onMention failed",
383
+ error,
384
+ waitUntil: keep
385
+ }, () => globalThis.console.error("[vitehub] Comments onMention failed:", error));
359
386
  }
360
387
  })();
361
388
  options.waitUntil?.(task);
@@ -418,13 +445,30 @@ async function createThread(runtime, input, options = {}) {
418
445
  if (created.id !== threadId) return retried(created, input, options.canRead);
419
446
  await announce(runtime, created, created.messages[0], mentioned, mentioned, {
420
447
  comment: true,
448
+ ...options.request ? { request: options.request } : {},
421
449
  ...options.waitUntil ? { waitUntil: options.waitUntil } : {}
422
450
  });
423
451
  runtime.forge?.changed(created.id);
424
452
  return created;
425
453
  }
454
+ /** The message that an earlier reply with this `requestId` stored in the thread. A retry gets it back before the reply checks. */
455
+ async function earlierReply(thread, requestId) {
456
+ if (requestId === void 0) return void 0;
457
+ const id = await replyMessageId(thread.id, check(requestIdSchema, requestId, "requestId"));
458
+ return thread.messages.find((message) => message.id === id);
459
+ }
460
+ /** Only the author of the first call gets its message back. */
461
+ function retriedReply(thread, message, author) {
462
+ if (message.author.id !== personOf(author).id) throw fail(commentsErrorDiagnostics.COMMENTS_R0022(), 409);
463
+ return {
464
+ message,
465
+ thread
466
+ };
467
+ }
426
468
  /** Adds a message to a thread. The caller checked access. */
427
469
  async function replyToThread(runtime, thread, input, options = {}) {
470
+ const earlier = await earlierReply(thread, input.requestId);
471
+ if (earlier) return retriedReply(thread, earlier, input.author);
428
472
  if (thread.status === "resolved" && !options.allowResolved) throw fail(commentsErrorDiagnostics.COMMENTS_R0016(), 409);
429
473
  const attachments = attachmentsOf(input.attachments);
430
474
  const body = cleanBody(runtime, {
@@ -442,7 +486,7 @@ async function replyToThread(runtime, thread, input, options = {}) {
442
486
  user,
443
487
  ...options.gate ? { gate: options.gate } : {}
444
488
  });
445
- const id = newId("message");
489
+ const id = input.requestId === void 0 ? newId("message") : await replyMessageId(thread.id, input.requestId);
446
490
  let next;
447
491
  try {
448
492
  next = await runtime.store.addMessage(thread.id, {
@@ -455,6 +499,12 @@ async function replyToThread(runtime, thread, input, options = {}) {
455
499
  ...input.actor ? { actor: input.actor } : {}
456
500
  }, { allowResolved: options.allowResolved === true });
457
501
  } catch (error) {
502
+ if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0022") {
503
+ const stored = await runtime.store.getById(thread.id);
504
+ const winner = stored?.messages.find((message) => message.id === id);
505
+ if (stored && winner) return retriedReply(stored, winner, input.author);
506
+ throw fail(error, 409);
507
+ }
458
508
  if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0016") throw fail(error, 409);
459
509
  if (error instanceof Error && Reflect.get(error, "code") === "COMMENTS_R0002") throw fail(error, 404);
460
510
  throw error;
@@ -462,6 +512,7 @@ async function replyToThread(runtime, thread, input, options = {}) {
462
512
  const message = next.messages.find((entry) => entry.id === id);
463
513
  await announce(runtime, next, message, mentioned, mentioned, {
464
514
  comment: true,
515
+ ...options.request ? { request: options.request } : {},
465
516
  ...options.waitUntil ? { waitUntil: options.waitUntil } : {}
466
517
  });
467
518
  runtime.forge?.changed(next.id);
@@ -569,6 +620,12 @@ async function attachmentThread(runtime, key, readable) {
569
620
  } while (cursor);
570
621
  throw fail(commentsErrorDiagnostics.COMMENTS_R0020({ key }), 404);
571
622
  }
623
+ /** The Base64 text of the bytes of an attachment, for the operations and the MCP tools. */
624
+ function base64(bytes) {
625
+ let binary = "";
626
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
627
+ return btoa(binary);
628
+ }
572
629
  /**
573
630
  * Reads the file of `key` with `readAttachment`, else from the Blob store, for a reader who may read `thread`. A
574
631
  * stored type that Comments does not attach, such as SVG from an app's own hook, answers as a download.
@@ -606,4 +663,4 @@ async function readAttachment(runtime, key, context) {
606
663
  };
607
664
  }
608
665
  //#endregion
609
- export { createClientRateLimit as S, scopeOf as _, deniedError as a, clientAddressKey as b, fail as c, mentionedPeople as d, personOf as f, retried as g, requestIdSchema as h, createThread as i, maximumAttachmentBytes as l, replyToThread as m, can as n, earlierThread as o, readAttachment as p, contextSchema as r, editMessage as s, attachmentThread as t, maximumCommentBodyLength as u, storeAttachment as v, clientRateLimitIssue as x, suggest as y };
666
+ export { clientAddressKey as C, suggest as S, createClientRateLimit as T, requestIdSchema as _, createThread as a, scopeOf as b, earlierThread as c, maximumAttachmentBytes as d, maximumCommentBodyLength as f, replyToThread as g, readAttachment as h, contextSchema as i, editMessage as l, personOf as m, base64 as n, deniedError as o, mentionedPeople as p, can as r, earlierReply as s, attachmentThread as t, fail as u, retried as v, clientRateLimitIssue as w, storeAttachment as x, retriedReply as y };