@miniaxolotl/grove-server 1.11.24 → 1.11.28

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.
package/dist/server.js CHANGED
@@ -18,7 +18,7 @@ var __export = (target2, all2) => {
18
18
  var define_GROVE_TELEMETRY_default;
19
19
  var init_define_GROVE_TELEMETRY = __esm({
20
20
  "<define:__GROVE_TELEMETRY__>"() {
21
- define_GROVE_TELEMETRY_default = { enabled: true, revision: "9ee71cc987a443c020fbf6030f76664b4cc5e914", version: "1.11.24", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
21
+ define_GROVE_TELEMETRY_default = { enabled: true, revision: "d6b98466a41776dca9beb1ab0d039dc1029d8b79", version: "1.11.28", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
22
22
  }
23
23
  });
24
24
 
@@ -465,7 +465,7 @@ var init_share_durations = __esm({
465
465
  });
466
466
 
467
467
  // lib/shared/src/sharing.ts
468
- import { z as z22 } from "zod";
468
+ import { z as z24 } from "zod";
469
469
  function sharedNoteTitle(content3) {
470
470
  return noteTitle2(content3) || "Untitled note";
471
471
  }
@@ -478,8 +478,8 @@ var init_sharing = __esm({
478
478
  init_search();
479
479
  init_limits();
480
480
  init_share_durations();
481
- shareTokenSchema = z22.string().regex(/^gsh_[A-Za-z0-9_-]{43}$/);
482
- shareDurationSchema = z22.enum([
481
+ shareTokenSchema = z24.string().regex(/^gsh_[A-Za-z0-9_-]{43}$/);
482
+ shareDurationSchema = z24.enum([
483
483
  "1h",
484
484
  "4h",
485
485
  "1d",
@@ -487,45 +487,45 @@ var init_sharing = __esm({
487
487
  "2w",
488
488
  "1mo"
489
489
  ]);
490
- shareMutationSchema = z22.object({
490
+ shareMutationSchema = z24.object({
491
491
  operationId: operationSchema,
492
- expectedVersion: z22.number().int().positive()
492
+ expectedVersion: z24.number().int().positive()
493
493
  }).strict();
494
494
  shareEnableSchema = shareMutationSchema.extend({
495
- expectedVersion: z22.number().int().min(0),
496
- expectedTargetVersion: z22.number().int().positive(),
497
- includeDescendants: z22.boolean().default(false),
495
+ expectedVersion: z24.number().int().min(0),
496
+ expectedTargetVersion: z24.number().int().positive(),
497
+ includeDescendants: z24.boolean().default(false),
498
498
  duration: shareDurationSchema.nullable().optional()
499
499
  });
500
500
  shareScopeSchema = shareMutationSchema.extend({
501
- includeDescendants: z22.boolean().optional(),
501
+ includeDescendants: z24.boolean().optional(),
502
502
  duration: shareDurationSchema.nullable().optional()
503
503
  }).refine(
504
504
  (value) => value.includeDescendants !== void 0 || value.duration !== void 0,
505
505
  "Choose a sharing setting to change"
506
506
  );
507
- publicShareQuerySchema = z22.object({
508
- cursor: z22.string().max(SHARE_CURSOR_MAX).optional(),
509
- limit: z22.coerce.number().int().min(1).max(100).default(30)
507
+ publicShareQuerySchema = z24.object({
508
+ cursor: z24.string().max(SHARE_CURSOR_MAX).optional(),
509
+ limit: z24.coerce.number().int().min(1).max(100).default(30)
510
510
  }).strict();
511
- notebook = z22.object({ id: uuidSchema, name: z22.string() }).strict();
512
- publicNoteSchema = z22.object({
511
+ notebook = z24.object({ id: uuidSchema, name: z24.string() }).strict();
512
+ publicNoteSchema = z24.object({
513
513
  id: uuidSchema,
514
- title: z22.string(),
515
- content: z22.string(),
516
- updatedAt: z22.string(),
517
- linkedNoteIds: z22.array(uuidSchema)
514
+ title: z24.string(),
515
+ content: z24.string(),
516
+ updatedAt: z24.string(),
517
+ linkedNoteIds: z24.array(uuidSchema)
518
518
  }).strict();
519
- publicShareSchema = z22.object({
520
- kind: z22.enum(["note", "notebook"]),
519
+ publicShareSchema = z24.object({
520
+ kind: z24.enum(["note", "notebook"]),
521
521
  root: notebook,
522
522
  notebook: notebook.nullable(),
523
523
  note: publicNoteSchema.nullable(),
524
- notebooks: z22.array(notebook),
525
- notes: z22.array(
524
+ notebooks: z24.array(notebook),
525
+ notes: z24.array(
526
526
  publicNoteSchema.pick({ id: true, title: true, updatedAt: true })
527
527
  ),
528
- nextCursor: z22.string().nullable()
528
+ nextCursor: z24.string().nullable()
529
529
  }).strict();
530
530
  }
531
531
  });
@@ -536,7 +536,7 @@ __export(media_exports, {
536
536
  MediaAttachments: () => MediaAttachments,
537
537
  mediaDescriptor: () => mediaDescriptor
538
538
  });
539
- import { createHash as createHash18, randomUUID as randomUUID13 } from "node:crypto";
539
+ import { createHash as createHash18, randomUUID as randomUUID14 } from "node:crypto";
540
540
  var missing8, conflict4, mediaDescriptor, MediaAttachments;
541
541
  var init_media2 = __esm({
542
542
  "lib/memory/src/media.ts"() {
@@ -590,7 +590,7 @@ var init_media2 = __esm({
590
590
  const quota = await trx("accounts").where({ id: account.id }).first("mediaBytes", "mediaAttempts");
591
591
  if (Number(quota.mediaBytes) + input.bytes > 1024 * 1024 * 1024 || quota.mediaAttempts >= 1e3)
592
592
  throw new GroveError("media_quota", "Media storage limit reached", 429);
593
- const leaseId = randomUUID13(), objectKey = mediaObjectKey(account.id, input.id, leaseId);
593
+ const leaseId = randomUUID14(), objectKey = mediaObjectKey(account.id, input.id, leaseId);
594
594
  const values = {
595
595
  memoryId: input.memoryId,
596
596
  bytes: input.bytes,
@@ -4875,6 +4875,33 @@ var aiPreferences = {
4875
4875
  }
4876
4876
  };
4877
4877
 
4878
+ // lib/database/src/proofing-migration.ts
4879
+ init_define_GROVE_TELEMETRY();
4880
+ var proofingConsents = {
4881
+ name: "20261118_044_proofing_consent",
4882
+ async up(db) {
4883
+ await db.raw(`CREATE TABLE proofing_consents (
4884
+ account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
4885
+ scope text NOT NULL CHECK(scope='grove-note-editor'),
4886
+ version integer NOT NULL CHECK(version>0),
4887
+ generation uuid NOT NULL,
4888
+ automatic boolean NOT NULL,
4889
+ updated_at timestamptz NOT NULL DEFAULT now(),
4890
+ revoked_at timestamptz,
4891
+ CHECK(revoked_at IS NULL OR NOT automatic),
4892
+ PRIMARY KEY(account_id,scope)
4893
+ );
4894
+ ALTER TABLE proofing_consents ENABLE ROW LEVEL SECURITY;
4895
+ ALTER TABLE proofing_consents FORCE ROW LEVEL SECURITY;
4896
+ CREATE POLICY tenant ON proofing_consents USING(account_id=nullif(current_setting('grove.account_id',true),'')::uuid);
4897
+ GRANT SELECT, INSERT, UPDATE ON proofing_consents TO grove_runtime;
4898
+ GRANT SELECT, DELETE ON proofing_consents TO grove_worker;`);
4899
+ },
4900
+ async down() {
4901
+ throw new Error("Use a forward migration");
4902
+ }
4903
+ };
4904
+
4878
4905
  // lib/database/src/queue-migration.ts
4879
4906
  init_define_GROVE_TELEMETRY();
4880
4907
 
@@ -6388,7 +6415,8 @@ var migrations = [
6388
6415
  billingTrial,
6389
6416
  writingAllowance,
6390
6417
  dailyNotes,
6391
- cacheRetention
6418
+ cacheRetention,
6419
+ proofingConsents
6392
6420
  ];
6393
6421
  var migrationSource = {
6394
6422
  getMigrations: async () => migrations,
@@ -6511,6 +6539,9 @@ async function probeDatabase(db) {
6511
6539
  await db.raw(
6512
6540
  "SELECT account_id, local_date, memory_id FROM daily_notes LIMIT 0"
6513
6541
  );
6542
+ await db.raw(
6543
+ "SELECT scope, version, generation, automatic, revoked_at FROM proofing_consents LIMIT 0"
6544
+ );
6514
6545
  }
6515
6546
  var MemoryModel = class extends Model {
6516
6547
  static tableName = "memories";
@@ -6534,7 +6565,7 @@ var MemoryModel = class extends Model {
6534
6565
 
6535
6566
  // packages/api/src/app.ts
6536
6567
  init_define_GROVE_TELEMETRY();
6537
- import { randomUUID as randomUUID18, createHash as createHash24 } from "node:crypto";
6568
+ import { randomUUID as randomUUID19, createHash as createHash24 } from "node:crypto";
6538
6569
 
6539
6570
  // lib/memory/src/index.ts
6540
6571
  init_define_GROVE_TELEMETRY();
@@ -6542,7 +6573,7 @@ import {
6542
6573
  createHash as createHash20,
6543
6574
  createHmac as createHmac6,
6544
6575
  randomBytes as randomBytes3,
6545
- randomUUID as randomUUID14,
6576
+ randomUUID as randomUUID15,
6546
6577
  timingSafeEqual as timingSafeEqual5
6547
6578
  } from "node:crypto";
6548
6579
 
@@ -23201,20 +23232,20 @@ init_define_GROVE_TELEMETRY();
23201
23232
  init_contracts();
23202
23233
  async function resolveConversationContext(trx, scope, selection, query) {
23203
23234
  if (!selection) return { sources: [], notebooks: [] };
23204
- const unavailable6 = () => new GroveError(
23235
+ const unavailable7 = () => new GroveError(
23205
23236
  "context_unavailable",
23206
23237
  "A selected source is unavailable in this conversation. Remove it or choose it again.",
23207
23238
  409
23208
23239
  );
23209
23240
  const books = await trx("projects").whereIn("id", selection.notebooks).where({ status: "active" }).select("id", "version");
23210
23241
  if (books.length !== selection.notebooks.length || books.some((book) => !inConversationScope(scope, book.id)))
23211
- throw unavailable6();
23242
+ throw unavailable7();
23212
23243
  const active4 = () => trx("memories").where({ status: "active" }).where(
23213
23244
  (q) => q.whereNull("expiresAt").orWhere("expiresAt", ">", trx.fn.now())
23214
23245
  );
23215
23246
  const pins = await active4().whereIn("id", selection.notes).select("id", "version", "projectId");
23216
23247
  if (pins.length !== selection.notes.length || pins.some((pin) => !inConversationScope(scope, pin.projectId)))
23217
- throw unavailable6();
23248
+ throw unavailable7();
23218
23249
  const members = active4().whereIn("projectId", selection.notebooks).whereNotIn("id", selection.notes);
23219
23250
  const count2 = await members.clone().count("id as count").first();
23220
23251
  const notebookEligible = Number(count2?.count ?? 0);
@@ -26254,6 +26285,7 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
26254
26285
  return rows.length;
26255
26286
  };
26256
26287
  const count2 = await deleteBatch(table);
26288
+ const proofing = table === "notebook_expiries" ? await deleteBatch("proofing_consents") : 0;
26257
26289
  const daily = table === "notebook_expiries" ? await deleteBatch("daily_notes") : 0;
26258
26290
  const research = table === "inference_usage" ? await trx("research_account_usage").select("day").limit(batchSize) : [];
26259
26291
  if (research.length)
@@ -26266,7 +26298,7 @@ function cleanupHandlers(db, deleteIdentity, cancelBilling) {
26266
26298
  cursor: {
26267
26299
  stage: count2 === batchSize || daily === batchSize || research.length === batchSize || cache === batchSize ? stage : stage + 1
26268
26300
  },
26269
- processed: Number(task.processed) + count2 + daily + research.length + cache
26301
+ processed: Number(task.processed) + count2 + daily + proofing + research.length + cache
26270
26302
  };
26271
26303
  });
26272
26304
  return;
@@ -26872,6 +26904,222 @@ var SpeechJobs = class {
26872
26904
  }
26873
26905
  };
26874
26906
 
26907
+ // lib/memory/src/proofing-consents.ts
26908
+ init_define_GROVE_TELEMETRY();
26909
+ init_contracts();
26910
+ import { randomUUID as randomUUID11 } from "node:crypto";
26911
+
26912
+ // lib/shared/src/proofing-contract.ts
26913
+ init_define_GROVE_TELEMETRY();
26914
+ import { z as z21 } from "zod";
26915
+
26916
+ // lib/shared/src/writing-settings.ts
26917
+ init_define_GROVE_TELEMETRY();
26918
+ import { z as z20 } from "zod";
26919
+
26920
+ // lib/shared/src/writing-markdown.ts
26921
+ init_define_GROVE_TELEMETRY();
26922
+ function projectWritingText(source3) {
26923
+ const ranges = [];
26924
+ const mark = (from, to) => {
26925
+ if (to > from) ranges.push({ from, to });
26926
+ };
26927
+ for (const match of source3.matchAll(/^(?: {4}|\t)[^\r\n]*/gm))
26928
+ mark(match.index, match.index + match[0].length);
26929
+ if (/[`~[<]/.test(source3)) {
26930
+ const bom = Number(source3.startsWith("\uFEFF"));
26931
+ const pending = [fromMarkdown(source3)];
26932
+ while (pending.length) {
26933
+ const node3 = pending.pop();
26934
+ const from = node3.position.start.offset + bom, to = node3.position.end.offset + bom;
26935
+ if (["code", "inlineCode", "html", "definition"].includes(node3.type)) {
26936
+ mark(from, to);
26937
+ continue;
26938
+ }
26939
+ if (node3.type === "link" || node3.type === "linkReference") {
26940
+ const first = node3.children[0]?.position, last = node3.children.at(-1)?.position;
26941
+ if (!first || !last || source3[from] === "<") {
26942
+ mark(from, to);
26943
+ continue;
26944
+ }
26945
+ mark(from, first.start.offset + bom);
26946
+ mark(last.end.offset + bom, to);
26947
+ }
26948
+ if (node3.type === "image" || node3.type === "imageReference") {
26949
+ const label = /^!\[((?:\\.|[^\]\\])*)\]/.exec(source3.slice(from, to));
26950
+ if (!label) mark(from, to);
26951
+ else {
26952
+ mark(from, from + 2);
26953
+ mark(from + 2 + label[1].length, to);
26954
+ }
26955
+ }
26956
+ if ("children" in node3)
26957
+ for (const child of node3.children) pending.push(child);
26958
+ }
26959
+ }
26960
+ for (const match of source3.matchAll(
26961
+ /https?:\/\/[^\s<>]+|\b[\w.+-]+@[\w.-]+\.[a-z]{2,}\b|\b[\p{L}\d]+(?:[_/][\p{L}\d]+)+\b/giu
26962
+ ))
26963
+ mark(match.index, match.index + match[0].length);
26964
+ const protectedSpans = [];
26965
+ for (const span of ranges.sort((a, b) => a.from - b.from)) {
26966
+ const prev = protectedSpans.at(-1);
26967
+ if (prev && prev.to >= span.from) prev.to = Math.max(prev.to, span.to);
26968
+ else protectedSpans.push(span);
26969
+ }
26970
+ let text5 = "", cursor = 0;
26971
+ for (const { from, to } of protectedSpans) {
26972
+ text5 += source3.slice(cursor, from) + source3.slice(from, to).replace(/[^\r\n]/g, " ");
26973
+ cursor = to;
26974
+ }
26975
+ return { text: text5 + source3.slice(cursor), protectedSpans };
26976
+ }
26977
+
26978
+ // lib/shared/src/writing-settings.ts
26979
+ var writingRules = [
26980
+ "brackets",
26981
+ "quotes",
26982
+ "articles",
26983
+ "repetition",
26984
+ "spacing",
26985
+ "capitalization",
26986
+ "redundancy",
26987
+ "agreement",
26988
+ "plurals",
26989
+ "confusion"
26990
+ ];
26991
+ var personalWordLimit = 1e3;
26992
+ var ruleSchema = z20.object({
26993
+ brackets: z20.boolean().default(true),
26994
+ quotes: z20.boolean().default(true),
26995
+ articles: z20.boolean().default(true),
26996
+ repetition: z20.boolean().default(true),
26997
+ spacing: z20.boolean().default(true),
26998
+ capitalization: z20.boolean().default(true),
26999
+ redundancy: z20.boolean().default(true),
27000
+ agreement: z20.boolean().default(true),
27001
+ plurals: z20.boolean().default(true),
27002
+ confusion: z20.boolean().default(true)
27003
+ }).strict();
27004
+ var writingSettingsSchema = z20.object({
27005
+ language: z20.literal("en").default("en"),
27006
+ enabled: z20.boolean().default(true),
27007
+ spelling: z20.boolean().default(true),
27008
+ grammar: z20.boolean().default(true),
27009
+ aiRewrites: z20.boolean().default(true),
27010
+ automatic: z20.boolean().default(true),
27011
+ highlights: z20.boolean().default(true),
27012
+ rules: ruleSchema.default(() => ruleSchema.parse({})),
27013
+ words: z20.array(
27014
+ z20.string().min(1).max(80).regex(/^[\p{L}\p{M}]+(?:['’‐‑-][\p{L}\p{M}]+)*$/u)
27015
+ ).max(personalWordLimit).default([])
27016
+ }).strict();
27017
+ var writingPatchSchema = z20.object({
27018
+ language: z20.literal("en").optional(),
27019
+ enabled: z20.boolean().optional(),
27020
+ spelling: z20.boolean().optional(),
27021
+ grammar: z20.boolean().optional(),
27022
+ aiRewrites: z20.boolean().optional(),
27023
+ automatic: z20.boolean().optional(),
27024
+ highlights: z20.boolean().optional(),
27025
+ rules: z20.partialRecord(z20.enum(writingRules), z20.boolean()).optional(),
27026
+ words: writingSettingsSchema.shape.words.removeDefault().optional()
27027
+ }).strict();
27028
+
27029
+ // lib/shared/src/proofing-contract.ts
27030
+ var proofingScope = "grove-note-editor";
27031
+ var proofingVersion = 1;
27032
+ var consentFields = z21.strictObject({
27033
+ enabled: z21.boolean(),
27034
+ automatic: z21.boolean()
27035
+ });
27036
+ var validConsent = (value) => value.enabled || !value.automatic;
27037
+ var proofingConsentSchema = consentFields.refine(validConsent);
27038
+ var proofingConsentStatusSchema = consentFields.extend({ available: z21.boolean().optional() }).refine(validConsent);
27039
+ var rule = z21.enum(["spelling", ...writingRules]);
27040
+ var proofingCheckSchema = z21.strictObject({
27041
+ text: z21.string().min(1).max(1500).refine(
27042
+ (text5) => !/[\r\n]\s*[\r\n]|\u2029/u.test(text5.replaceAll("\r\n", "\n")) && !/[\p{Cs}]/u.test(text5)
27043
+ ),
27044
+ revision: z21.int().nonnegative(),
27045
+ rules: z21.record(rule, z21.boolean())
27046
+ });
27047
+ var proofingResultSchema = z21.strictObject({
27048
+ revision: z21.int().nonnegative(),
27049
+ complete: z21.boolean(),
27050
+ issues: z21.array(
27051
+ z21.strictObject({
27052
+ id: z21.string().max(80),
27053
+ rule,
27054
+ message: rule,
27055
+ from: z21.int().nonnegative(),
27056
+ to: z21.int().max(1500),
27057
+ original: z21.string().max(160),
27058
+ replacements: z21.array(z21.string().max(100)).max(3)
27059
+ })
27060
+ ).max(50)
27061
+ });
27062
+
27063
+ // lib/memory/src/proofing-consents.ts
27064
+ var ProofingConsents = class {
27065
+ constructor(service) {
27066
+ this.service = service;
27067
+ }
27068
+ service;
27069
+ // access() rechecks account lifecycle and the authoritative session revocation
27070
+ // even when this is the second access within one already-admitted request.
27071
+ state(principal, next) {
27072
+ if (principal.type !== "session" || !principal.sessionId)
27073
+ throw new GroveError(
27074
+ "forbidden",
27075
+ "A signed-in editor session is required",
27076
+ 403
27077
+ );
27078
+ return this.service.access(
27079
+ principal,
27080
+ next ? "admin" : null,
27081
+ async ({ trx, account }) => {
27082
+ const key2 = { accountId: account.id, scope: proofingScope };
27083
+ const old = await trx("proofing_consents").where(key2).first();
27084
+ const current = old?.version === proofingVersion;
27085
+ const enabled = current && !old.revokedAt;
27086
+ const consent = {
27087
+ enabled,
27088
+ automatic: enabled && old.automatic === true
27089
+ };
27090
+ if (!next || (!old || current) && consent.enabled === next.enabled && consent.automatic === next.automatic)
27091
+ return {
27092
+ consent,
27093
+ generation: enabled ? String(old.generation) : null
27094
+ };
27095
+ const generation = randomUUID11();
27096
+ await trx("proofing_consents").insert({
27097
+ ...key2,
27098
+ version: proofingVersion,
27099
+ automatic: next.automatic,
27100
+ generation,
27101
+ updatedAt: trx.fn.now(),
27102
+ revokedAt: next.enabled ? null : trx.fn.now()
27103
+ }).onConflict(["accountId", "scope"]).merge();
27104
+ return { consent: next, generation: next.enabled ? generation : null };
27105
+ }
27106
+ );
27107
+ }
27108
+ async settings(principal, next) {
27109
+ return (await this.state(principal, next)).consent;
27110
+ }
27111
+ async grant(principal, mode, expected) {
27112
+ const { generation, consent } = await this.state(principal);
27113
+ if (!generation || mode === "automatic" && !consent.automatic || expected && expected !== generation)
27114
+ throw new GroveError(
27115
+ "proofing_consent_required",
27116
+ "Review Enhanced grammar in Writing settings.",
27117
+ 403
27118
+ );
27119
+ return generation;
27120
+ }
27121
+ };
27122
+
26875
27123
  // lib/memory/src/exports.ts
26876
27124
  init_define_GROVE_TELEMETRY();
26877
27125
 
@@ -26881,13 +27129,13 @@ init_contracts();
26881
27129
 
26882
27130
  // lib/shared/src/jobs.ts
26883
27131
  init_define_GROVE_TELEMETRY();
26884
- import { z as z21 } from "zod";
27132
+ import { z as z23 } from "zod";
26885
27133
 
26886
27134
  // lib/shared/src/web-capture.ts
26887
27135
  init_define_GROVE_TELEMETRY();
26888
27136
  init_contracts();
26889
27137
  init_limits();
26890
- import { z as z20 } from "zod";
27138
+ import { z as z22 } from "zod";
26891
27139
  var trackingParameters = /* @__PURE__ */ new Set([
26892
27140
  "utm_source",
26893
27141
  "utm_medium",
@@ -26928,56 +27176,56 @@ function normalizeWebUrl(input) {
26928
27176
  throw new Error("Invalid source URL: too long");
26929
27177
  return normalized;
26930
27178
  }
26931
- var webCaptureSchema = z20.object({
26932
- url: z20.string().max(WEB_URL_MAX).transform((value, ctx) => {
27179
+ var webCaptureSchema = z22.object({
27180
+ url: z22.string().max(WEB_URL_MAX).transform((value, ctx) => {
26933
27181
  try {
26934
27182
  return normalizeWebUrl(value);
26935
27183
  } catch {
26936
27184
  ctx.addIssue({ code: "custom", message: "Invalid source URL" });
26937
- return z20.NEVER;
27185
+ return z22.NEVER;
26938
27186
  }
26939
27187
  }),
26940
- title: z20.string().max(300).refine((value) => !containsControlCharacters(value), {
27188
+ title: z22.string().max(300).refine((value) => !containsControlCharacters(value), {
26941
27189
  message: "Source title must be a single line"
26942
27190
  }),
26943
- capturedAt: z20.iso.datetime()
27191
+ capturedAt: z22.iso.datetime()
26944
27192
  }).strict();
26945
- var browserCaptureRequestSchema = z20.object({
26946
- operationId: z20.uuid(),
26947
- id: z20.uuid().optional(),
26948
- expectedVersion: z20.number().int().positive().optional(),
26949
- editSession: z20.uuid().optional(),
27193
+ var browserCaptureRequestSchema = z22.object({
27194
+ operationId: z22.uuid(),
27195
+ id: z22.uuid().optional(),
27196
+ expectedVersion: z22.number().int().positive().optional(),
27197
+ editSession: z22.uuid().optional(),
26950
27198
  content: rememberSchema.shape.content,
26951
- projectId: z20.uuid().nullable(),
26952
- capture: z20.literal("explicit"),
27199
+ projectId: z22.uuid().nullable(),
27200
+ capture: z22.literal("explicit"),
26953
27201
  provenance: webCaptureSchema.optional()
26954
27202
  }).strict().refine(
26955
27203
  (input) => Boolean(input.id) === Boolean(input.expectedVersion),
26956
27204
  "Updates require both id and expectedVersion"
26957
27205
  );
26958
- var browserPageRequestSchema = z20.object({
27206
+ var browserPageRequestSchema = z22.object({
26959
27207
  url: webCaptureSchema.shape.url,
26960
- projectId: z20.uuid().nullable(),
26961
- cursor: z20.string().max(2048).optional()
27208
+ projectId: z22.uuid().nullable(),
27209
+ cursor: z22.string().max(2048).optional()
26962
27210
  }).strict();
26963
27211
 
26964
27212
  // lib/shared/src/jobs.ts
26965
- var exportRequestSchema = z21.object({
26966
- id: z21.uuid(),
26967
- projectId: z21.uuid().optional(),
26968
- includeDescendants: z21.boolean().default(false),
26969
- includeMedia: z21.boolean().optional()
27213
+ var exportRequestSchema = z23.object({
27214
+ id: z23.uuid(),
27215
+ projectId: z23.uuid().optional(),
27216
+ includeDescendants: z23.boolean().default(false),
27217
+ includeMedia: z23.boolean().optional()
26970
27218
  }).strict();
26971
- var importRecordSchema = z21.object({
26972
- sourceId: z21.string().min(1).max(200),
26973
- content: z21.string().min(1).max(6e3),
26974
- projectId: z21.uuid().nullable().default(null),
27219
+ var importRecordSchema = z23.object({
27220
+ sourceId: z23.string().min(1).max(200),
27221
+ content: z23.string().min(1).max(6e3),
27222
+ projectId: z23.uuid().nullable().default(null),
26975
27223
  webCapture: webCaptureSchema.optional()
26976
27224
  }).strict();
26977
- var importRequestSchema = z21.object({
26978
- id: z21.uuid(),
26979
- source: z21.string().regex(/^[a-zA-Z0-9._-]{1,100}$/),
26980
- records: z21.array(importRecordSchema).min(1).max(100)
27225
+ var importRequestSchema = z23.object({
27226
+ id: z23.uuid(),
27227
+ source: z23.string().regex(/^[a-zA-Z0-9._-]{1,100}$/),
27228
+ records: z23.array(importRecordSchema).min(1).max(100)
26981
27229
  }).strict();
26982
27230
 
26983
27231
  // lib/memory/src/index.ts
@@ -26985,7 +27233,7 @@ init_contracts();
26985
27233
 
26986
27234
  // lib/memory/src/connect.ts
26987
27235
  init_define_GROVE_TELEMETRY();
26988
- import { randomUUID as randomUUID11 } from "node:crypto";
27236
+ import { randomUUID as randomUUID12 } from "node:crypto";
26989
27237
  init_contracts();
26990
27238
  var unavailable5 = () => new GroveError(
26991
27239
  "connection_unavailable",
@@ -27043,7 +27291,7 @@ var ConnectionSetup = class {
27043
27291
  );
27044
27292
  const attempt = {
27045
27293
  ...input,
27046
- id: randomUUID11(),
27294
+ id: randomUUID12(),
27047
27295
  connectionId: connection.id,
27048
27296
  clientId: connection.clientId,
27049
27297
  status: hasAccess ? "approved" : "pending",
@@ -27170,7 +27418,7 @@ import {
27170
27418
  createHash as createHash17,
27171
27419
  createHmac as createHmac4,
27172
27420
  randomBytes as randomBytes2,
27173
- randomUUID as randomUUID12,
27421
+ randomUUID as randomUUID13,
27174
27422
  timingSafeEqual as timingSafeEqual3
27175
27423
  } from "node:crypto";
27176
27424
  var hash3 = (value) => createHash17("sha256").update(value).digest("hex");
@@ -27391,7 +27639,7 @@ var Sharing = class {
27391
27639
  return existing;
27392
27640
  }
27393
27641
  const identity = {
27394
- id: existing?.id ?? randomUUID12(),
27642
+ id: existing?.id ?? randomUUID13(),
27395
27643
  accountId
27396
27644
  };
27397
27645
  const fields = {
@@ -27554,16 +27802,16 @@ import { createHash as createHash19, createHmac as createHmac5, timingSafeEqual
27554
27802
 
27555
27803
  // lib/shared/src/conversation-history.ts
27556
27804
  init_define_GROVE_TELEMETRY();
27557
- import { z as z23 } from "zod";
27558
- var conversationHistorySchema = z23.object({
27559
- query: z23.string().trim().max(200).default(""),
27560
- after: z23.string().max(2048).optional()
27805
+ import { z as z25 } from "zod";
27806
+ var conversationHistorySchema = z25.object({
27807
+ query: z25.string().trim().max(200).default(""),
27808
+ after: z25.string().max(2048).optional()
27561
27809
  }).strict();
27562
- var conversationHistoryCursorSchema = z23.object({
27563
- owner: z23.uuid(),
27564
- query: z23.string(),
27565
- id: z23.uuid(),
27566
- at: z23.iso.datetime()
27810
+ var conversationHistoryCursorSchema = z25.object({
27811
+ owner: z25.uuid(),
27812
+ query: z25.string(),
27813
+ id: z25.uuid(),
27814
+ at: z25.iso.datetime()
27567
27815
  });
27568
27816
 
27569
27817
  // lib/memory/src/conversation-history.ts
@@ -27646,11 +27894,11 @@ init_contracts();
27646
27894
  // lib/shared/src/notebook-lifecycle.ts
27647
27895
  init_define_GROVE_TELEMETRY();
27648
27896
  init_contracts();
27649
- import { z as z24 } from "zod";
27650
- var notebookLifecycleSchema = z24.object({
27897
+ import { z as z26 } from "zod";
27898
+ var notebookLifecycleSchema = z26.object({
27651
27899
  operationId: operationSchema,
27652
- expectedVersion: z24.number().int().positive(),
27653
- fingerprint: z24.string().regex(/^[a-f0-9]{64}$/)
27900
+ expectedVersion: z26.number().int().positive(),
27901
+ fingerprint: z26.string().regex(/^[a-f0-9]{64}$/)
27654
27902
  }).strict();
27655
27903
 
27656
27904
  // lib/memory/src/tools.ts
@@ -27764,36 +28012,36 @@ init_contracts();
27764
28012
  // lib/shared/src/system-admin.ts
27765
28013
  init_define_GROVE_TELEMETRY();
27766
28014
  init_contracts();
27767
- import { z as z25 } from "zod";
27768
- var adminChangeSchema = z25.object({
28015
+ import { z as z27 } from "zod";
28016
+ var adminChangeSchema = z27.object({
27769
28017
  accountId: uuidSchema,
27770
28018
  operationId: uuidSchema,
27771
- expectedVersion: z25.number().int().min(0),
27772
- role: z25.enum(["user", "system_admin"]),
27773
- access: z25.enum(["default", "pro", "unlimited"]),
27774
- reason: z25.string().trim().min(3).max(300)
28019
+ expectedVersion: z27.number().int().min(0),
28020
+ role: z27.enum(["user", "system_admin"]),
28021
+ access: z27.enum(["default", "pro", "unlimited"]),
28022
+ reason: z27.string().trim().min(3).max(300)
27775
28023
  }).strict();
27776
- var adminSettingsSchema = z25.object({
27777
- captureEnabled: z25.boolean(),
27778
- recallEnabled: z25.boolean(),
27779
- suspended: z25.boolean(),
27780
- supportNote: z25.string().max(500)
28024
+ var adminSettingsSchema = z27.object({
28025
+ captureEnabled: z27.boolean(),
28026
+ recallEnabled: z27.boolean(),
28027
+ suspended: z27.boolean(),
28028
+ supportNote: z27.string().max(500)
27781
28029
  }).strict();
27782
- var adminSupportSchema = z25.object({
28030
+ var adminSupportSchema = z27.object({
27783
28031
  accountId: uuidSchema,
27784
28032
  operationId: uuidSchema,
27785
- expectedVersion: z25.number().int().min(0),
28033
+ expectedVersion: z27.number().int().min(0),
27786
28034
  expectedSettings: adminSettingsSchema,
27787
28035
  settings: adminSettingsSchema,
27788
- reason: z25.string().trim().min(3).max(300)
28036
+ reason: z27.string().trim().min(3).max(300)
27789
28037
  }).strict();
27790
- var adminTrialResetSchema = z25.object({
28038
+ var adminTrialResetSchema = z27.object({
27791
28039
  accountId: uuidSchema,
27792
28040
  operationId: uuidSchema,
27793
- reason: z25.string().trim().min(3).max(300)
28041
+ reason: z27.string().trim().min(3).max(300)
27794
28042
  }).strict();
27795
- var adminDetailsSchema = z25.object({ accountId: uuidSchema }).strict();
27796
- var adminBrowseSchema = z25.object({ after: uuidSchema.optional() }).strict();
28043
+ var adminDetailsSchema = z27.object({ accountId: uuidSchema }).strict();
28044
+ var adminBrowseSchema = z27.object({ after: uuidSchema.optional() }).strict();
27797
28045
  var usageReportFeatures = [
27798
28046
  "recall",
27799
28047
  "ask",
@@ -27821,9 +28069,9 @@ var emptyUsageReportMetrics = () => Object.fromEntries(
27821
28069
  }
27822
28070
  ])
27823
28071
  );
27824
- var adminUsageReportSchema = z25.object({
27825
- from: z25.iso.date().optional(),
27826
- to: z25.iso.date().optional(),
28072
+ var adminUsageReportSchema = z27.object({
28073
+ from: z27.iso.date().optional(),
28074
+ to: z27.iso.date().optional(),
27827
28075
  after: uuidSchema.optional()
27828
28076
  }).strict().superRefine((input, ctx) => {
27829
28077
  if (!!input.from !== !!input.to || input.from && input.to && (input.from > input.to || Date.parse(input.to) - Date.parse(input.from) > 365 * 864e5))
@@ -28354,7 +28602,7 @@ var MemoryService = class _MemoryService {
28354
28602
  }
28355
28603
  const writer = this.inTransaction(trx);
28356
28604
  const note2 = input.id ? await writer.updateMemory(principal, {
28357
- operationId: randomUUID14(),
28605
+ operationId: randomUUID15(),
28358
28606
  id: input.id,
28359
28607
  expectedVersion: input.expectedVersion,
28360
28608
  editSession: input.editSession,
@@ -28364,7 +28612,7 @@ var MemoryService = class _MemoryService {
28364
28612
  }) : await writer.remember(
28365
28613
  principal,
28366
28614
  rememberSchema.parse({
28367
- operationId: randomUUID14(),
28615
+ operationId: randomUUID15(),
28368
28616
  content: input.content,
28369
28617
  projectId: input.projectId,
28370
28618
  capture: "explicit",
@@ -28737,7 +28985,7 @@ var MemoryService = class _MemoryService {
28737
28985
  version: input.expectedVersion + 1
28738
28986
  }) : await MemoryModel.query(trx).insertAndFetch({
28739
28987
  ...values,
28740
- id: randomUUID14(),
28988
+ id: randomUUID15(),
28741
28989
  status: input.archived ? "archived" : "active"
28742
28990
  });
28743
28991
  if (localDate)
@@ -28829,7 +29077,7 @@ var MemoryService = class _MemoryService {
28829
29077
  const domain2 = this.inTransaction(trx);
28830
29078
  for (const item of input.items)
28831
29079
  await domain2.updateMemory(principal, {
28832
- operationId: randomUUID14(),
29080
+ operationId: randomUUID15(),
28833
29081
  ...item,
28834
29082
  projectId: input.projectId,
28835
29083
  capture: "explicit"
@@ -29023,7 +29271,7 @@ var MemoryService = class _MemoryService {
29023
29271
  trx,
29024
29272
  principal.accountId,
29025
29273
  metric,
29026
- randomUUID14(),
29274
+ randomUUID15(),
29027
29275
  1
29028
29276
  );
29029
29277
  }
@@ -30009,7 +30257,7 @@ ${input.query}`.slice(-1e3) : input.query;
30009
30257
  }).returning("*");
30010
30258
  }
30011
30259
  if (!options.key) return { connection };
30012
- const id2 = randomUUID14();
30260
+ const id2 = randomUUID15();
30013
30261
  const secret = `grv_${id2}_${randomBytes3(32).toString("base64url")}`;
30014
30262
  await trx("api_keys").insert({
30015
30263
  id: id2,
@@ -30122,7 +30370,7 @@ ${input.query}`.slice(-1e3) : input.query;
30122
30370
  throw new GroveError("not_found", "Project not found", 404);
30123
30371
  if (refresh && this.providers.generation && account[briefPreference(scope)]) {
30124
30372
  const target2 = briefTarget(scope);
30125
- const usageOperation = `brief:${randomUUID14()}`;
30373
+ const usageOperation = `brief:${randomUUID15()}`;
30126
30374
  await reserveAction(
30127
30375
  this.db,
30128
30376
  trx,
@@ -30236,6 +30484,143 @@ var sessionPrincipal = (accountId, subject) => ({
30236
30484
  capabilities: [...capabilities]
30237
30485
  });
30238
30486
 
30487
+ // packages/api/src/proofing.ts
30488
+ init_define_GROVE_TELEMETRY();
30489
+ init_contracts();
30490
+ import { z as z28 } from "zod";
30491
+ var families = /* @__PURE__ */ new Map([
30492
+ ["YOUR_YOU_2", "confusion"],
30493
+ ["WHO_S_NN_VB", "confusion"],
30494
+ ["ITS_TO_IT_S", "confusion"],
30495
+ ["IT_IS", "confusion"],
30496
+ ["FEWER_LESS", "confusion"],
30497
+ ["BETWEEN_YOU_AND_I", "agreement"],
30498
+ ["MORFOLOGIK_RULE_EN_US", "spelling"]
30499
+ ]);
30500
+ var upstreamSchema = z28.object({
30501
+ warnings: z28.object({ incompleteResults: z28.boolean() }).optional(),
30502
+ matches: z28.array(
30503
+ z28.object({
30504
+ rule: z28.object({ id: z28.string() }),
30505
+ offset: z28.int(),
30506
+ length: z28.int(),
30507
+ replacements: z28.array(z28.object({ value: z28.string() }))
30508
+ })
30509
+ )
30510
+ });
30511
+ var unavailable6 = () => new GroveError(
30512
+ "proofing_unavailable",
30513
+ "Enhanced grammar is temporarily unavailable.",
30514
+ 503
30515
+ );
30516
+ var maxBytes2 = 64 * 1024;
30517
+ async function upstreamJson(response) {
30518
+ if (!response.ok || !/^application\/json(?:\s*;|$)/i.test(
30519
+ response.headers.get("content-type") ?? ""
30520
+ ) || Number(response.headers.get("content-length")) > maxBytes2 || !response.body)
30521
+ throw unavailable6();
30522
+ const reader = response.body.getReader();
30523
+ let size = 0, json = "";
30524
+ const decoder = new TextDecoder("utf-8", { fatal: true });
30525
+ try {
30526
+ for (; ; ) {
30527
+ const { done, value } = await reader.read();
30528
+ if (done) break;
30529
+ size += value.byteLength;
30530
+ if (size > maxBytes2) throw unavailable6();
30531
+ json += decoder.decode(value, { stream: true });
30532
+ }
30533
+ return upstreamSchema.parse(JSON.parse(json + decoder.decode()));
30534
+ } finally {
30535
+ reader.releaseLock();
30536
+ }
30537
+ }
30538
+ function proofingEndpoint(origin2) {
30539
+ if (origin2 && URL.canParse(origin2)) {
30540
+ const url = new URL(origin2);
30541
+ if (["http:", "https:"].includes(url.protocol) && ["languagetool", "localhost", "127.0.0.1", "[::1]"].includes(
30542
+ url.hostname
30543
+ ) && !url.username && !url.password && url.href === url.origin + "/")
30544
+ return new URL("/v2/check", url);
30545
+ }
30546
+ }
30547
+ function languageTool(origin2) {
30548
+ const endpoint2 = proofingEndpoint(origin2);
30549
+ return async (input, signal) => {
30550
+ signal.throwIfAborted();
30551
+ const ids = [...families].filter(([, family]) => input.rules[family]).map(([id2]) => id2);
30552
+ const projection = projectWritingText(input.text);
30553
+ const result = {
30554
+ revision: input.revision,
30555
+ complete: true,
30556
+ issues: []
30557
+ };
30558
+ if (!ids.length || !projection.text.trim()) return result;
30559
+ if (!endpoint2) throw unavailable6();
30560
+ const controller = new AbortController();
30561
+ const timer = setTimeout(() => controller.abort(), 2500);
30562
+ try {
30563
+ const response = await fetch(endpoint2, {
30564
+ method: "POST",
30565
+ redirect: "error",
30566
+ credentials: "omit",
30567
+ cache: "no-store",
30568
+ signal: AbortSignal.any([controller.signal, signal]),
30569
+ headers: { accept: "application/json" },
30570
+ body: new URLSearchParams({
30571
+ text: projection.text,
30572
+ language: "en-US",
30573
+ level: "default",
30574
+ enabledOnly: "true",
30575
+ enabledRules: ids.join(",")
30576
+ })
30577
+ });
30578
+ const data = await upstreamJson(response);
30579
+ result.complete = !data.warnings?.incompleteResults;
30580
+ for (const match of data.matches) {
30581
+ const rule2 = families.get(match.rule.id), from = match.offset, to = from + match.length;
30582
+ if (!rule2 || !input.rules[rule2] || from < 0 || match.length < 1 || match.length > 160 || to > input.text.length || projection.protectedSpans.some(
30583
+ (span) => from < span.to && to > span.from
30584
+ ))
30585
+ continue;
30586
+ const original = input.text.slice(from, to);
30587
+ if (!original.trim() || new RegExp("\\p{Cs}", "u").test(original)) continue;
30588
+ const replacements = [
30589
+ ...new Set(
30590
+ match.replacements.map((r) => r.value).filter(
30591
+ (v) => v.length <= 100 && !/[\p{C}\r\n]/u.test(v) && v !== original
30592
+ )
30593
+ )
30594
+ ].slice(0, 3);
30595
+ if (match.rule.id === "ITS_TO_IT_S" && original === "its" && /[\p{L},;:]\s+$/u.test(projection.text.slice(0, from)))
30596
+ replacements.sort(
30597
+ (a, b) => Number(b === "it's") - Number(a === "it's")
30598
+ );
30599
+ if (!replacements.length) continue;
30600
+ if (result.issues.length === 50) {
30601
+ result.complete = false;
30602
+ break;
30603
+ }
30604
+ result.issues.push({
30605
+ id: `${rule2}:${from}:${to}`,
30606
+ rule: rule2,
30607
+ message: rule2,
30608
+ from,
30609
+ to,
30610
+ original,
30611
+ replacements
30612
+ });
30613
+ }
30614
+ return result;
30615
+ } catch {
30616
+ throw unavailable6();
30617
+ } finally {
30618
+ clearTimeout(timer);
30619
+ controller.abort();
30620
+ }
30621
+ };
30622
+ }
30623
+
30239
30624
  // packages/api/src/media-input.ts
30240
30625
  init_define_GROVE_TELEMETRY();
30241
30626
  init_contracts();
@@ -30271,7 +30656,7 @@ async function readMediaBytes(source3, signal, maximum = imageLimits.bytes) {
30271
30656
 
30272
30657
  // packages/api/src/billing.ts
30273
30658
  init_define_GROVE_TELEMETRY();
30274
- import { randomUUID as randomUUID15 } from "node:crypto";
30659
+ import { randomUUID as randomUUID16 } from "node:crypto";
30275
30660
  init_contracts();
30276
30661
  var ongoing = (status) => !["canceled", "incomplete_expired"].includes(status);
30277
30662
  var replaceableCheckout = (session, subscriptions) => {
@@ -30541,7 +30926,7 @@ var Billing = class {
30541
30926
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
30542
30927
  checkoutId: null,
30543
30928
  checkoutPrice: price.id,
30544
- checkoutOperation: randomUUID15()
30929
+ checkoutOperation: randomUUID16()
30545
30930
  });
30546
30931
  }
30547
30932
  if (!row.checkoutPrice)
@@ -30591,7 +30976,7 @@ var Billing = class {
30591
30976
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
30592
30977
  checkoutId: null,
30593
30978
  checkoutPrice: null,
30594
- checkoutOperation: randomUUID15()
30979
+ checkoutOperation: randomUUID16()
30595
30980
  });
30596
30981
  return null;
30597
30982
  }
@@ -30654,7 +31039,7 @@ var Billing = class {
30654
31039
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
30655
31040
  checkoutId: null,
30656
31041
  checkoutPrice: price.id,
30657
- checkoutOperation: randomUUID15()
31042
+ checkoutOperation: randomUUID16()
30658
31043
  });
30659
31044
  }
30660
31045
  if (!row.checkoutPrice)
@@ -30724,7 +31109,7 @@ var Billing = class {
30724
31109
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
30725
31110
  checkoutId: null,
30726
31111
  checkoutPrice: null,
30727
- checkoutOperation: randomUUID15()
31112
+ checkoutOperation: randomUUID16()
30728
31113
  });
30729
31114
  return null;
30730
31115
  }
@@ -30807,7 +31192,7 @@ var Billing = class {
30807
31192
  init_define_GROVE_TELEMETRY();
30808
31193
  init_contracts();
30809
31194
  import { createClerkClient } from "@clerk/backend";
30810
- import { z as z26 } from "zod";
31195
+ import { z as z29 } from "zod";
30811
31196
  function clerkAdminDirectory(secretKey) {
30812
31197
  const clerk = createClerkClient({ secretKey });
30813
31198
  return {
@@ -30843,12 +31228,12 @@ var AdminAccounts = class {
30843
31228
  administration;
30844
31229
  async search(principal, raw) {
30845
31230
  await this.administration.accounts(principal, []);
30846
- const { query } = z26.object({ query: z26.string().trim().max(254) }).strict().parse(raw);
31231
+ const { query } = z29.object({ query: z29.string().trim().max(254) }).strict().parse(raw);
30847
31232
  let subjects;
30848
31233
  if (query.startsWith("user_") && /^user_[A-Za-z0-9_-]{1,128}$/.test(query))
30849
31234
  subjects = [query];
30850
31235
  else if (query) {
30851
- if (!z26.email().safeParse(query).success)
31236
+ if (!z29.email().safeParse(query).success)
30852
31237
  throw new GroveError(
30853
31238
  "invalid_request",
30854
31239
  "Search by exact email or user ID",
@@ -30986,7 +31371,7 @@ import { pipeline as pipeline2 } from "node:stream/promises";
30986
31371
 
30987
31372
  // lib/telemetry/src/index.ts
30988
31373
  init_define_GROVE_TELEMETRY();
30989
- import { createHmac as createHmac7, randomUUID as randomUUID17 } from "node:crypto";
31374
+ import { createHmac as createHmac7, randomUUID as randomUUID18 } from "node:crypto";
30990
31375
  import { performance as performance2 } from "node:perf_hooks";
30991
31376
 
30992
31377
  // node_modules/.pnpm/posthog-node@5.56.2_@opentelemetry+api@1.10.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs
@@ -46658,7 +47043,7 @@ function safeMetric(metric, identity) {
46658
47043
 
46659
47044
  // lib/telemetry/src/preference.ts
46660
47045
  init_define_GROVE_TELEMETRY();
46661
- import { randomUUID as randomUUID16 } from "node:crypto";
47046
+ import { randomUUID as randomUUID17 } from "node:crypto";
46662
47047
  import {
46663
47048
  chmodSync,
46664
47049
  closeSync,
@@ -46709,7 +47094,7 @@ function installationIdentity(directory = telemetryDirectory()) {
46709
47094
  try {
46710
47095
  const fd = openSync(path2, "wx", 384);
46711
47096
  try {
46712
- writeFileSync(fd, `${randomUUID16()}
47097
+ writeFileSync(fd, `${randomUUID17()}
46713
47098
  `);
46714
47099
  } finally {
46715
47100
  closeSync(fd);
@@ -47084,7 +47469,7 @@ function telemetry(surface) {
47084
47469
  const server = surface === "api" || surface === "worker";
47085
47470
  const enabled = build.enabled && !environmentDisabled() && (!server || process.env.GROVE_TELEMETRY_ENABLED === "true");
47086
47471
  const directory = telemetryDirectory();
47087
- const identity = enabled ? server ? randomUUID17() : installationIdentity(directory) : "";
47472
+ const identity = enabled ? server ? randomUUID18() : installationIdentity(directory) : "";
47088
47473
  reporter = new Reporter({
47089
47474
  ...build,
47090
47475
  enabled,
@@ -47107,7 +47492,7 @@ var closeTelemetry = (timeoutMs = 550) => Promise.allSettled(
47107
47492
  // packages/api/src/app.ts
47108
47493
  import { Hono } from "hono";
47109
47494
  import { cors } from "hono/cors";
47110
- import { z as z27, ZodError as ZodError2 } from "zod";
47495
+ import { z as z30, ZodError as ZodError2 } from "zod";
47111
47496
  import { Webhook } from "svix";
47112
47497
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
47113
47498
 
@@ -47182,9 +47567,8 @@ init_contracts();
47182
47567
  init_define_GROVE_TELEMETRY();
47183
47568
  init_contracts();
47184
47569
  var busy = () => new GroveError("overloaded", "Grove is busy. Try again shortly.", 503);
47185
- async function admittedRequest(request2, signal) {
47570
+ async function admittedRequest(request2, signal, maximum = 128 * 1024) {
47186
47571
  if (!request2.body) return request2;
47187
- const maximum = 128 * 1024;
47188
47572
  const tooLarge2 = () => new GroveError("too_large", "Request body is too large", 413);
47189
47573
  if (Number(request2.headers.get("content-length")) > maximum) throw tooLarge2();
47190
47574
  let size = 0;
@@ -47531,6 +47915,13 @@ init_media();
47531
47915
  init_models();
47532
47916
  function createApp(deps) {
47533
47917
  const app = new Hono();
47918
+ const proofing = new ProofingConsents(deps.memories);
47919
+ const checkParagraph = languageTool(deps.languageToolUrl);
47920
+ const proofingLane = new Admission(1, 0, 0);
47921
+ const liveSession = (principal) => {
47922
+ if (!principal.sessionExpiresAt || principal.sessionExpiresAt <= Date.now())
47923
+ throw new GroveError("unauthorized", "Sign in to Grove", 401);
47924
+ };
47534
47925
  const writing = new WritingTools(
47535
47926
  deps.memories,
47536
47927
  deps.writingStagingKey,
@@ -47553,7 +47944,7 @@ function createApp(deps) {
47553
47944
  capacity.queueTimeoutMs
47554
47945
  );
47555
47946
  app.use("*", async (c, next) => {
47556
- c.set("requestId", randomUUID18());
47947
+ c.set("requestId", randomUUID19());
47557
47948
  c.header("X-Request-ID", c.get("requestId"));
47558
47949
  c.header("Cache-Control", "private, no-store");
47559
47950
  c.header("X-Content-Type-Options", "nosniff");
@@ -47562,7 +47953,7 @@ function createApp(deps) {
47562
47953
  c.header("X-Robots-Tag", "noindex, nofollow, noarchive");
47563
47954
  const started = performance.now();
47564
47955
  await next();
47565
- if (requestCollectionAllowed(c.req.raw.headers) && !c.req.path.startsWith("/health/"))
47956
+ if (requestCollectionAllowed(c.req.raw.headers) && !c.req.path.startsWith("/v1/proofing/") && !c.req.path.startsWith("/health/"))
47566
47957
  deps.telemetry?.operation(
47567
47958
  "http_request",
47568
47959
  started,
@@ -47680,9 +48071,15 @@ function createApp(deps) {
47680
48071
  c.set("signal", signal);
47681
48072
  c.set("finish", finish);
47682
48073
  try {
47683
- release2 = await (long ? interactive : foreground).acquire(signal);
48074
+ const isCheck = c.req.path === "/v1/proofing/check";
48075
+ release2 = await (isCheck ? proofingLane : long ? interactive : foreground).acquire(signal);
47684
48076
  await withMemoryOperation(async () => {
47685
- if (!mediaUpload) c.req.raw = await admittedRequest(c.req.raw, signal);
48077
+ if (!mediaUpload)
48078
+ c.req.raw = await admittedRequest(
48079
+ c.req.raw,
48080
+ signal,
48081
+ isCheck ? 16384 : c.req.path === "/v1/proofing/consent" ? 512 : void 0
48082
+ );
47686
48083
  await next();
47687
48084
  if (!c.get("streaming") && !c.error) signal.throwIfAborted();
47688
48085
  }, signal);
@@ -47728,13 +48125,13 @@ function createApp(deps) {
47728
48125
  400
47729
48126
  );
47730
48127
  }
47731
- const payload = z27.object({
47732
- type: z27.string(),
47733
- timestamp: z27.number().int(),
47734
- data: z27.object({
47735
- id: z27.string().min(1),
47736
- banned: z27.boolean().optional(),
47737
- locked: z27.boolean().optional()
48128
+ const payload = z30.object({
48129
+ type: z30.string(),
48130
+ timestamp: z30.number().int(),
48131
+ data: z30.object({
48132
+ id: z30.string().min(1),
48133
+ banned: z30.boolean().optional(),
48134
+ locked: z30.boolean().optional()
47738
48135
  })
47739
48136
  }).parse(event);
47740
48137
  await deps.memories.db.transaction(async (trx) => {
@@ -47767,6 +48164,18 @@ function createApp(deps) {
47767
48164
  throw new GroveError("forbidden", "Origin is not allowed", 403);
47768
48165
  c.set("principal", principal);
47769
48166
  c.get("signal").throwIfAborted();
48167
+ if (c.req.path.startsWith("/v1/proofing/")) {
48168
+ if (origin2 !== deps.siteUrl)
48169
+ throw new GroveError("forbidden", "Editor origin is required", 403);
48170
+ if (principal.type !== "session" || !principal.sessionId)
48171
+ throw new GroveError(
48172
+ "forbidden",
48173
+ "A signed-in editor session is required",
48174
+ 403
48175
+ );
48176
+ liveSession(principal);
48177
+ return next();
48178
+ }
47770
48179
  await deps.models?.refresh();
47771
48180
  const sink = deps.telemetry?.forIdentity(
47772
48181
  accountIdentity(c.get("principal").accountId),
@@ -47877,9 +48286,9 @@ function createApp(deps) {
47877
48286
  async (c) => c.json({ success: true, data: await billing2().status(c.get("principal")) })
47878
48287
  );
47879
48288
  app.post("/v1/billing/checkout", async (c) => {
47880
- const input = z27.object({
47881
- interval: z27.enum(["month", "year"]),
47882
- expectedAmount: z27.number().int().positive().optional()
48289
+ const input = z30.object({
48290
+ interval: z30.enum(["month", "year"]),
48291
+ expectedAmount: z30.number().int().positive().optional()
47883
48292
  }).strict().parse(await c.req.json());
47884
48293
  return c.json({
47885
48294
  success: true,
@@ -47895,9 +48304,9 @@ function createApp(deps) {
47895
48304
  async (c) => c.json({ success: true, data: await billing2().portal(c.get("principal")) })
47896
48305
  );
47897
48306
  app.post("/v1/billing/trial", async (c) => {
47898
- const input = z27.object({
47899
- interval: z27.enum(["month", "year"]),
47900
- expectedAmount: z27.number().int().positive().optional()
48307
+ const input = z30.object({
48308
+ interval: z30.enum(["month", "year"]),
48309
+ expectedAmount: z30.number().int().positive().optional()
47901
48310
  }).strict().parse(await c.req.json());
47902
48311
  return c.json({
47903
48312
  success: true,
@@ -47909,6 +48318,31 @@ function createApp(deps) {
47909
48318
  });
47910
48319
  });
47911
48320
  const body = async (c, schema) => schema.parse(await c.req.json());
48321
+ const configured = !!proofingEndpoint(deps.languageToolUrl);
48322
+ function requireChecker() {
48323
+ if (!configured) throw new GroveError("proofing_disabled", "Enhanced grammar is not configured.", 503);
48324
+ }
48325
+ app.get("/v1/proofing/consent", async (c) => {
48326
+ const consent = await proofing.settings(c.get("principal"));
48327
+ return c.json(configured ? consent : { ...consent, available: false });
48328
+ });
48329
+ app.put("/v1/proofing/consent", async (c) => {
48330
+ const value = await body(c, proofingConsentSchema);
48331
+ if (value.enabled) requireChecker();
48332
+ const consent = await proofing.settings(c.get("principal"), value);
48333
+ return c.json(configured ? consent : { ...consent, available: false });
48334
+ });
48335
+ app.post("/v1/proofing/check", async (c) => {
48336
+ requireChecker();
48337
+ const principal = c.get("principal"), input = await body(c, proofingCheckSchema);
48338
+ const mode = z30.enum(["manual", "automatic"]).parse(c.req.header("x-grove-proofing-mode") ?? "manual");
48339
+ const generation = await proofing.grant(principal, mode);
48340
+ liveSession(principal);
48341
+ const result = await checkParagraph(input, c.get("signal"));
48342
+ await proofing.grant(principal, mode, generation);
48343
+ liveSession(principal);
48344
+ return c.json(result);
48345
+ });
47912
48346
  const mutation = async (c, schema) => {
47913
48347
  const value = await c.req.json();
47914
48348
  const key2 = c.req.header("idempotency-key");
@@ -47990,8 +48424,8 @@ function createApp(deps) {
47990
48424
  importStorage();
47991
48425
  const principal = c.get("principal"), conversationId = uuidSchema.parse(c.req.param("conversationId")), id2 = uuidSchema.parse(c.req.param("id"));
47992
48426
  await conversationDocuments2.list(principal, conversationId);
47993
- const length = z27.coerce.number().int().min(1).max(3 * 1024 * 1024).parse(c.req.header("content-length"));
47994
- const hash4 = z27.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"));
48427
+ const length = z30.coerce.number().int().min(1).max(3 * 1024 * 1024).parse(c.req.header("content-length"));
48428
+ const hash4 = z30.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"));
47995
48429
  let filename;
47996
48430
  try {
47997
48431
  filename = decodeURIComponent(c.req.header("x-grove-filename") ?? "");
@@ -48070,7 +48504,7 @@ function createApp(deps) {
48070
48504
  c.get("principal"),
48071
48505
  uuidSchema.parse(c.req.param("conversationId")),
48072
48506
  uuidSchema.parse(c.req.param("id")),
48073
- z27.coerce.number().int().nonnegative().default(0).parse(c.req.query("after"))
48507
+ z30.coerce.number().int().nonnegative().default(0).parse(c.req.query("after"))
48074
48508
  )
48075
48509
  })
48076
48510
  );
@@ -48109,7 +48543,7 @@ function createApp(deps) {
48109
48543
  data: await documentImports2.get(
48110
48544
  c.get("principal"),
48111
48545
  uuidSchema.parse(c.req.param("id")),
48112
- z27.uuid().optional().parse(c.req.query("after"))
48546
+ z30.uuid().optional().parse(c.req.query("after"))
48113
48547
  )
48114
48548
  })
48115
48549
  );
@@ -48117,8 +48551,8 @@ function createApp(deps) {
48117
48551
  importStorage();
48118
48552
  const principal = c.get("principal"), batchId = uuidSchema.parse(c.req.param("batchId")), id2 = uuidSchema.parse(c.req.param("id"));
48119
48553
  await documentImports2.get(principal, batchId);
48120
- const length = z27.coerce.number().int().min(1).max(3 * 1024 * 1024).parse(c.req.header("content-length"));
48121
- const hash4 = z27.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"));
48554
+ const length = z30.coerce.number().int().min(1).max(3 * 1024 * 1024).parse(c.req.header("content-length"));
48555
+ const hash4 = z30.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"));
48122
48556
  let filename;
48123
48557
  try {
48124
48558
  filename = decodeURIComponent(c.req.header("x-grove-filename") ?? "");
@@ -48235,7 +48669,7 @@ function createApp(deps) {
48235
48669
  service,
48236
48670
  c.get("principal"),
48237
48671
  c.req.param("tool"),
48238
- await mutation(c, z27.record(z27.string(), z27.unknown())),
48672
+ await mutation(c, z30.record(z30.string(), z30.unknown())),
48239
48673
  c.get("signal")
48240
48674
  )
48241
48675
  })
@@ -48247,7 +48681,7 @@ function createApp(deps) {
48247
48681
  "Media storage is not configured",
48248
48682
  503
48249
48683
  );
48250
- const id2 = uuidSchema.parse(c.req.param("id")), version2 = c.req.query("version") ? z27.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
48684
+ const id2 = uuidSchema.parse(c.req.param("id")), version2 = c.req.query("version") ? z30.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
48251
48685
  const cancelled = new AbortController(), signal = AbortSignal.any([c.get("signal"), cancelled.signal]);
48252
48686
  const source3 = await noteArchive(
48253
48687
  service,
@@ -48281,10 +48715,10 @@ function createApp(deps) {
48281
48715
  const input = {
48282
48716
  id: uuidSchema.parse(c.req.param("id")),
48283
48717
  memoryId: uuidSchema.parse(c.req.param("memoryId")),
48284
- version: z27.coerce.number().int().positive().parse(c.req.header("x-grove-note-version")),
48285
- bytes: z27.coerce.number().int().min(1).max(imageLimits.bytes).parse(c.req.header("content-length")),
48286
- mime: z27.enum(mediaMimeTypes).parse(c.req.header("content-type")),
48287
- sha256: z27.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"))
48718
+ version: z30.coerce.number().int().positive().parse(c.req.header("x-grove-note-version")),
48719
+ bytes: z30.coerce.number().int().min(1).max(imageLimits.bytes).parse(c.req.header("content-length")),
48720
+ mime: z30.enum(mediaMimeTypes).parse(c.req.header("content-type")),
48721
+ sha256: z30.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"))
48288
48722
  };
48289
48723
  const claim = await attachments.claim(principal, input);
48290
48724
  if (claim.replay)
@@ -48387,7 +48821,7 @@ function createApp(deps) {
48387
48821
  };
48388
48822
  app.get("/v1/memories/:memoryId/media/:id", async (c) => {
48389
48823
  const memoryId = uuidSchema.parse(c.req.param("memoryId")), id2 = uuidSchema.parse(c.req.param("id"));
48390
- const version2 = c.req.query("version") ? z27.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
48824
+ const version2 = c.req.query("version") ? z30.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
48391
48825
  return mediaResponse(
48392
48826
  c,
48393
48827
  () => attachments.read(c.get("principal"), memoryId, id2, version2)
@@ -48444,7 +48878,7 @@ function createApp(deps) {
48444
48878
  })
48445
48879
  );
48446
48880
  app.post("/v1/speech/:id/cancel", async (c) => {
48447
- await mutation(c, z27.object({}).strict());
48881
+ await mutation(c, z30.object({}).strict());
48448
48882
  return c.json({
48449
48883
  success: true,
48450
48884
  data: await speech2.cancel(
@@ -48482,10 +48916,10 @@ function createApp(deps) {
48482
48916
  uuidSchema.parse(c.req.param("id")),
48483
48917
  await body(
48484
48918
  c,
48485
- z27.object({
48486
- operationId: z27.uuid(),
48487
- expectedVersion: z27.number().int().min(0),
48488
- text: z27.string().max(6e3)
48919
+ z30.object({
48920
+ operationId: z30.uuid(),
48921
+ expectedVersion: z30.number().int().min(0),
48922
+ text: z30.string().max(6e3)
48489
48923
  }).strict()
48490
48924
  )
48491
48925
  )
@@ -48638,7 +49072,7 @@ function createApp(deps) {
48638
49072
  })
48639
49073
  );
48640
49074
  app.post("/v1/connect/:id/cancel", async (c) => {
48641
- await body(c, z27.object({}).strict());
49075
+ await body(c, z30.object({}).strict());
48642
49076
  return c.json({
48643
49077
  success: true,
48644
49078
  data: await setup.cancel(
@@ -48648,7 +49082,7 @@ function createApp(deps) {
48648
49082
  });
48649
49083
  });
48650
49084
  app.post("/v1/browser/connect", async (c) => {
48651
- await body(c, z27.object({}).strict());
49085
+ await body(c, z30.object({}).strict());
48652
49086
  const principal = c.get("principal");
48653
49087
  const identity = await service.me(principal);
48654
49088
  const approval = new URL("/app/connections", deps.siteUrl);
@@ -48681,9 +49115,9 @@ function createApp(deps) {
48681
49115
  c.get("principal"),
48682
49116
  await body(
48683
49117
  c,
48684
- z27.object({
48685
- policy: z27.string().min(1).max(100),
48686
- accepted: z27.boolean()
49118
+ z30.object({
49119
+ policy: z30.string().min(1).max(100),
49120
+ accepted: z30.boolean()
48687
49121
  }).strict()
48688
49122
  )
48689
49123
  )
@@ -48713,7 +49147,7 @@ function createApp(deps) {
48713
49147
  })
48714
49148
  );
48715
49149
  app.post("/v1/browser/writing/requests/:id/cancel", async (c) => {
48716
- await body(c, z27.object({}).strict());
49150
+ await body(c, z30.object({}).strict());
48717
49151
  return c.json({
48718
49152
  success: true,
48719
49153
  data: await writing.cancel(
@@ -48748,7 +49182,7 @@ function createApp(deps) {
48748
49182
  success: true,
48749
49183
  data: await service.projects(
48750
49184
  c.get("principal"),
48751
- z27.enum(["active", "archived"]).parse(c.req.query("status") ?? "active")
49185
+ z30.enum(["active", "archived"]).parse(c.req.query("status") ?? "active")
48752
49186
  )
48753
49187
  })
48754
49188
  );
@@ -48849,7 +49283,7 @@ function createApp(deps) {
48849
49283
  app.post("/v1/models/test", async (c) => {
48850
49284
  const input = await body(
48851
49285
  c,
48852
- z27.object({ role: z27.enum(["embedding", "decision", "generation"]) }).strict()
49286
+ z30.object({ role: z30.enum(["embedding", "decision", "generation"]) }).strict()
48853
49287
  );
48854
49288
  if (!deps.models)
48855
49289
  throw new GroveError(
@@ -48915,7 +49349,7 @@ function createApp(deps) {
48915
49349
  app.post("/v1/memories", async (c) => {
48916
49350
  const input = await mutation(
48917
49351
  c,
48918
- z27.union([rememberSchema, memoryUpdateSchema])
49352
+ z30.union([rememberSchema, memoryUpdateSchema])
48919
49353
  );
48920
49354
  return c.json({
48921
49355
  success: true,
@@ -49080,14 +49514,14 @@ function createApp(deps) {
49080
49514
  data: await service.sourceRevision(
49081
49515
  c.get("principal"),
49082
49516
  uuidSchema.parse(c.req.param("id")),
49083
- z27.coerce.number().int().positive().max(2147483647).parse(c.req.param("version"))
49517
+ z30.coerce.number().int().positive().max(2147483647).parse(c.req.param("version"))
49084
49518
  )
49085
49519
  })
49086
49520
  );
49087
49521
  app.post("/v1/memories/:id/reprocess", async (c) => {
49088
49522
  const input = await body(
49089
49523
  c,
49090
- z27.object({ expectedVersion: z27.number().int().positive() }).strict()
49524
+ z30.object({ expectedVersion: z30.number().int().positive() }).strict()
49091
49525
  );
49092
49526
  return c.json({
49093
49527
  success: true,
@@ -49191,7 +49625,7 @@ function createApp(deps) {
49191
49625
  success: true,
49192
49626
  data: await service.conversations.list(
49193
49627
  c.get("principal"),
49194
- z27.uuid().optional().parse(c.req.query("after"))
49628
+ z30.uuid().optional().parse(c.req.query("after"))
49195
49629
  )
49196
49630
  })
49197
49631
  );
@@ -49238,8 +49672,8 @@ function createApp(deps) {
49238
49672
  })
49239
49673
  );
49240
49674
  app.post("/v1/conversations/:id/turns/:turnId/:action", async (c) => {
49241
- const action = z27.enum(["apply", "undo"]).parse(c.req.param("action"));
49242
- await body(c, z27.object({}).strict());
49675
+ const action = z30.enum(["apply", "undo"]).parse(c.req.param("action"));
49676
+ await body(c, z30.object({}).strict());
49243
49677
  return c.json({
49244
49678
  success: true,
49245
49679
  data: await service.conversations.apply(
@@ -49329,7 +49763,7 @@ function createApp(deps) {
49329
49763
  app.post("/v1/account/delete", async (c) => {
49330
49764
  await body(
49331
49765
  c,
49332
- z27.object({ confirm: z27.literal("delete my account") }).strict()
49766
+ z30.object({ confirm: z30.literal("delete my account") }).strict()
49333
49767
  );
49334
49768
  return c.json(
49335
49769
  { success: true, data: await service.deleteAccount(c.get("principal")) },
@@ -49378,7 +49812,7 @@ function createApp(deps) {
49378
49812
  success: true,
49379
49813
  data: await tasks.list(
49380
49814
  c.get("principal"),
49381
- z27.uuid().optional().parse(c.req.query("projectId"))
49815
+ z30.uuid().optional().parse(c.req.query("projectId"))
49382
49816
  )
49383
49817
  })
49384
49818
  );
@@ -49529,7 +49963,8 @@ function clerkVerifier(env) {
49529
49963
  return {
49530
49964
  subject: payload.sub,
49531
49965
  type: "session",
49532
- sessionId: payload.sid
49966
+ sessionId: payload.sid,
49967
+ sessionExpiresAt: payload.exp * 1e3
49533
49968
  };
49534
49969
  }
49535
49970
  const access2 = await clerk.idPOAuthAccessToken.verify(token, {
@@ -49614,7 +50049,8 @@ var Authentication = class {
49614
50049
  if (identity.type === "session")
49615
50050
  return {
49616
50051
  ...sessionPrincipal(account.id, identity.subject),
49617
- sessionId: identity.sessionId
50052
+ sessionId: identity.sessionId,
50053
+ sessionExpiresAt: identity.sessionExpiresAt
49618
50054
  };
49619
50055
  if (!identity.clientId || !Number.isFinite(identity.issuedAt) || !identity.scopes?.includes("openid"))
49620
50056
  throw unauthorized();
@@ -49655,53 +50091,53 @@ init_define_GROVE_TELEMETRY();
49655
50091
 
49656
50092
  // lib/environment/src/index.ts
49657
50093
  init_define_GROVE_TELEMETRY();
49658
- import { z as z28 } from "zod";
49659
- var origin = z28.url().transform((value, ctx) => {
50094
+ import { z as z31 } from "zod";
50095
+ var origin = z31.url().transform((value, ctx) => {
49660
50096
  const url = new URL(value);
49661
50097
  if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) {
49662
50098
  ctx.addIssue({
49663
50099
  code: "custom",
49664
50100
  message: "Use an HTTPS origin (HTTP is allowed on loopback)"
49665
50101
  });
49666
- return z28.NEVER;
50102
+ return z31.NEVER;
49667
50103
  }
49668
50104
  return url.origin;
49669
50105
  });
49670
- var allowance = (value) => z28.coerce.number().int().min(0).max(1e9).default(value);
49671
- var serverSchema = z28.object({
49672
- NODE_ENV: z28.enum(["development", "test", "production"]).default("development"),
49673
- PORT: z28.coerce.number().int().min(1).max(65535).default(26080),
49674
- DATABASE_URL: z28.string().min(1),
49675
- DATABASE_SSL: z28.enum(["require", "disable"]).default("disable"),
49676
- DATABASE_POOL_MAX: z28.coerce.number().int().min(1).max(64).default(8),
49677
- DATABASE_ACQUIRE_TIMEOUT_MS: z28.coerce.number().int().min(100).max(3e4).default(2e3),
49678
- DATABASE_STATEMENT_TIMEOUT_MS: z28.coerce.number().int().min(100).max(3e4).default(1e4),
49679
- API_MAX_IN_FLIGHT: z28.coerce.number().int().min(1).max(256).default(32),
49680
- API_MAX_QUEUED: z28.coerce.number().int().min(0).max(256).default(32),
49681
- API_QUEUE_TIMEOUT_MS: z28.coerce.number().int().min(1).max(5e3).default(250),
49682
- API_REQUEST_TIMEOUT_MS: z28.coerce.number().int().min(100).max(6e4).default(1e4),
49683
- API_INTERACTIVE_CONCURRENCY: z28.coerce.number().int().min(1).max(32).default(4),
49684
- API_INTERACTIVE_TIMEOUT_MS: z28.coerce.number().int().min(100).max(18e4).default(9e4),
50106
+ var allowance = (value) => z31.coerce.number().int().min(0).max(1e9).default(value);
50107
+ var serverSchema = z31.object({
50108
+ NODE_ENV: z31.enum(["development", "test", "production"]).default("development"),
50109
+ PORT: z31.coerce.number().int().min(1).max(65535).default(26080),
50110
+ DATABASE_URL: z31.string().min(1),
50111
+ DATABASE_SSL: z31.enum(["require", "disable"]).default("disable"),
50112
+ DATABASE_POOL_MAX: z31.coerce.number().int().min(1).max(64).default(8),
50113
+ DATABASE_ACQUIRE_TIMEOUT_MS: z31.coerce.number().int().min(100).max(3e4).default(2e3),
50114
+ DATABASE_STATEMENT_TIMEOUT_MS: z31.coerce.number().int().min(100).max(3e4).default(1e4),
50115
+ API_MAX_IN_FLIGHT: z31.coerce.number().int().min(1).max(256).default(32),
50116
+ API_MAX_QUEUED: z31.coerce.number().int().min(0).max(256).default(32),
50117
+ API_QUEUE_TIMEOUT_MS: z31.coerce.number().int().min(1).max(5e3).default(250),
50118
+ API_REQUEST_TIMEOUT_MS: z31.coerce.number().int().min(100).max(6e4).default(1e4),
50119
+ API_INTERACTIVE_CONCURRENCY: z31.coerce.number().int().min(1).max(32).default(4),
50120
+ API_INTERACTIVE_TIMEOUT_MS: z31.coerce.number().int().min(100).max(18e4).default(9e4),
49685
50121
  API_ORIGIN: origin,
49686
50122
  SITE_URL: origin,
49687
50123
  // Public ownership proof, never an account credential. Empty values are omitted below.
49688
- OPENAI_APPS_CHALLENGE: z28.string().min(1).max(512).refine(
50124
+ OPENAI_APPS_CHALLENGE: z31.string().min(1).max(512).refine(
49689
50125
  (value) => !/\s/.test(value),
49690
50126
  "Use the exact non-whitespace verification token"
49691
50127
  ).optional(),
49692
- CLERK_PUBLISHABLE_KEY: z28.string().startsWith("pk_"),
49693
- CLERK_SECRET_KEY: z28.string().startsWith("sk_"),
50128
+ CLERK_PUBLISHABLE_KEY: z31.string().startsWith("pk_"),
50129
+ CLERK_SECRET_KEY: z31.string().startsWith("sk_"),
49694
50130
  CLERK_ISSUER: origin,
49695
- CLERK_WEBHOOK_SIGNING_SECRET: z28.string().min(1),
49696
- GROVE_EDITION: z28.enum(["self-hosted", "cloud"]).default("self-hosted"),
49697
- BILLING_CONFIGURED: z28.enum(["true", "false"]).default("false").transform((value) => value === "true"),
49698
- FLAGS: z28.string().min(1).optional(),
49699
- STRIPE_SECRET_KEY: z28.string().regex(/^(sk|rk)_(test|live)_/).optional(),
49700
- STRIPE_WEBHOOK_SECRET: z28.string().startsWith("whsec_").optional(),
49701
- STRIPE_PRO_PRODUCT_ID: z28.string().startsWith("prod_").optional(),
49702
- STRIPE_PORTAL_CONFIGURATION_ID: z28.string().startsWith("bpc_").optional(),
49703
- STRIPE_PRO_MONTHLY_PRICE_ID: z28.string().startsWith("price_").optional(),
49704
- STRIPE_PRO_YEARLY_PRICE_ID: z28.string().startsWith("price_").optional(),
50131
+ CLERK_WEBHOOK_SIGNING_SECRET: z31.string().min(1),
50132
+ GROVE_EDITION: z31.enum(["self-hosted", "cloud"]).default("self-hosted"),
50133
+ BILLING_CONFIGURED: z31.enum(["true", "false"]).default("false").transform((value) => value === "true"),
50134
+ FLAGS: z31.string().min(1).optional(),
50135
+ STRIPE_SECRET_KEY: z31.string().regex(/^(sk|rk)_(test|live)_/).optional(),
50136
+ STRIPE_WEBHOOK_SECRET: z31.string().startsWith("whsec_").optional(),
50137
+ STRIPE_PRO_PRODUCT_ID: z31.string().startsWith("prod_").optional(),
50138
+ STRIPE_PORTAL_CONFIGURATION_ID: z31.string().startsWith("bpc_").optional(),
50139
+ STRIPE_PRO_MONTHLY_PRICE_ID: z31.string().startsWith("price_").optional(),
50140
+ STRIPE_PRO_YEARLY_PRICE_ID: z31.string().startsWith("price_").optional(),
49705
50141
  BILLING_FREE_GENERATION_DAILY: allowance(
49706
50142
  billingLimits.free.generation.daily
49707
50143
  ),
@@ -49745,51 +50181,51 @@ var serverSchema = z28.object({
49745
50181
  BILLING_PRO_ASSISTANCE_MONTHLY: allowance(resourceLimits.pro.assistance),
49746
50182
  BILLING_PRO_WRITING_MONTHLY: allowance(resourceLimits.pro.writing),
49747
50183
  // Reject old deployment settings instead of silently treating characters as time.
49748
- BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: z28.string().optional(),
49749
- BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: z28.string().optional(),
49750
- EMBEDDING_MODE: z28.enum(["local", "remote", "disabled"]).optional(),
49751
- EMBEDDING_CACHE: z28.string().default("./data/models"),
49752
- EMBEDDING_URL: z28.string().optional(),
49753
- EMBEDDING_MODEL: z28.string().optional(),
49754
- EMBEDDING_API_KEY: z28.string().optional(),
49755
- EMBEDDING_DIMENSIONS: z28.coerce.number().int().min(32).max(16e3).optional(),
49756
- EMBEDDING_QUERY_PREFIX: z28.string().optional(),
49757
- EMBEDDING_DOCUMENT_PREFIX: z28.string().optional(),
49758
- EMBEDDING_DISTANCE_THRESHOLD: z28.coerce.number().min(0).max(2).optional(),
49759
- DECISION_PROVIDER: z28.enum(["system-one", "disabled"]).default("disabled"),
49760
- DECISION_URL: z28.string().optional(),
49761
- DECISION_MODEL: z28.string().optional(),
49762
- DECISION_API_KEY: z28.string().optional(),
49763
- DECISION_PATH: z28.enum(["/decisions", "/systemone"]).default("/decisions"),
49764
- GENERATION_PROVIDER: z28.enum(["minimax", "openai-compatible", "disabled"]).default("disabled"),
49765
- GENERATION_URL: z28.string().optional(),
49766
- GENERATION_MODEL: z28.string().optional(),
49767
- GENERATION_API_KEY: z28.string().optional(),
49768
- GENERATION_OUTPUT_FORMAT: z28.enum(["tool", "json-schema", "json"]).default("tool"),
49769
- GENERATION_REASONING_EFFORT: z28.enum(["low", "medium", "high", "omit"]).default("low"),
49770
- GENERATION_MAX_OUTPUT_TOKENS: z28.coerce.number().int().min(256).max(16384).default(4096),
49771
- DEEPINFRA_API_KEY: z28.string().optional(),
49772
- MINIMAX_API_KEY: z28.string().optional(),
49773
- OPENAI_API_KEY: z28.string().optional(),
49774
- SPEECH_ENABLED: z28.enum(["true", "false"]).default("false").transform((value) => value === "true"),
49775
- TTS_VOICE: z28.enum(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]).default("alloy"),
49776
- MINIMAX_TTS_ENABLED: z28.enum(["true", "false"]).default("false").transform((value) => value === "true"),
49777
- SPEECH_PROVIDER_CONCURRENCY: z28.coerce.number().int().min(1).max(16).default(2),
49778
- EXA_API_KEY: z28.string().optional(),
49779
- TAVILY_API_KEY: z28.string().optional(),
49780
- RESEARCH_DAILY_CALL_LIMIT: z28.coerce.number().int().min(1).max(1e4).default(20),
49781
- RESEARCH_MONTHLY_BUDGET_USD: z28.coerce.number().min(0).max(1e5).default(100),
49782
- MODEL_ADMIN_SUBJECTS: z28.string().default(""),
49783
- MODEL_SETTINGS_KEY: z28.string().regex(/^[0-9a-f]{64}$/i).optional(),
49784
- AI_DAILY_REQUEST_LIMIT: z28.coerce.number().int().min(1).max(1e6).default(2e3),
49785
- AI_CONCURRENCY: z28.coerce.number().int().min(1).max(32).default(4),
49786
- INDEXING_CONCURRENCY: z28.coerce.number().int().min(0).max(32).default(2),
49787
- EMAIL_CONCURRENCY: z28.coerce.number().int().min(0).max(8).default(1),
49788
- MAINTENANCE_CONCURRENCY: z28.coerce.number().int().min(0).max(8).default(1),
49789
- BULK_CONCURRENCY: z28.coerce.number().int().min(0).max(8).default(1),
49790
- JOB_ACCOUNT_CONCURRENCY: z28.coerce.number().int().min(1).max(8).default(2),
49791
- JOB_PROVIDER_CONCURRENCY: z28.coerce.number().int().min(1).max(128).default(8),
49792
- WORKER_LANES: z28.string().default("indexing,enrichment,email,maintenance,bulk").refine(
50184
+ BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: z31.string().optional(),
50185
+ BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: z31.string().optional(),
50186
+ EMBEDDING_MODE: z31.enum(["local", "remote", "disabled"]).optional(),
50187
+ EMBEDDING_CACHE: z31.string().default("./data/models"),
50188
+ EMBEDDING_URL: z31.string().optional(),
50189
+ EMBEDDING_MODEL: z31.string().optional(),
50190
+ EMBEDDING_API_KEY: z31.string().optional(),
50191
+ EMBEDDING_DIMENSIONS: z31.coerce.number().int().min(32).max(16e3).optional(),
50192
+ EMBEDDING_QUERY_PREFIX: z31.string().optional(),
50193
+ EMBEDDING_DOCUMENT_PREFIX: z31.string().optional(),
50194
+ EMBEDDING_DISTANCE_THRESHOLD: z31.coerce.number().min(0).max(2).optional(),
50195
+ DECISION_PROVIDER: z31.enum(["system-one", "disabled"]).default("disabled"),
50196
+ DECISION_URL: z31.string().optional(),
50197
+ DECISION_MODEL: z31.string().optional(),
50198
+ DECISION_API_KEY: z31.string().optional(),
50199
+ DECISION_PATH: z31.enum(["/decisions", "/systemone"]).default("/decisions"),
50200
+ GENERATION_PROVIDER: z31.enum(["minimax", "openai-compatible", "disabled"]).default("disabled"),
50201
+ GENERATION_URL: z31.string().optional(),
50202
+ GENERATION_MODEL: z31.string().optional(),
50203
+ GENERATION_API_KEY: z31.string().optional(),
50204
+ GENERATION_OUTPUT_FORMAT: z31.enum(["tool", "json-schema", "json"]).default("tool"),
50205
+ GENERATION_REASONING_EFFORT: z31.enum(["low", "medium", "high", "omit"]).default("low"),
50206
+ GENERATION_MAX_OUTPUT_TOKENS: z31.coerce.number().int().min(256).max(16384).default(4096),
50207
+ DEEPINFRA_API_KEY: z31.string().optional(),
50208
+ MINIMAX_API_KEY: z31.string().optional(),
50209
+ OPENAI_API_KEY: z31.string().optional(),
50210
+ SPEECH_ENABLED: z31.enum(["true", "false"]).default("false").transform((value) => value === "true"),
50211
+ TTS_VOICE: z31.enum(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]).default("alloy"),
50212
+ MINIMAX_TTS_ENABLED: z31.enum(["true", "false"]).default("false").transform((value) => value === "true"),
50213
+ SPEECH_PROVIDER_CONCURRENCY: z31.coerce.number().int().min(1).max(16).default(2),
50214
+ EXA_API_KEY: z31.string().optional(),
50215
+ TAVILY_API_KEY: z31.string().optional(),
50216
+ RESEARCH_DAILY_CALL_LIMIT: z31.coerce.number().int().min(1).max(1e4).default(20),
50217
+ RESEARCH_MONTHLY_BUDGET_USD: z31.coerce.number().min(0).max(1e5).default(100),
50218
+ MODEL_ADMIN_SUBJECTS: z31.string().default(""),
50219
+ MODEL_SETTINGS_KEY: z31.string().regex(/^[0-9a-f]{64}$/i).optional(),
50220
+ AI_DAILY_REQUEST_LIMIT: z31.coerce.number().int().min(1).max(1e6).default(2e3),
50221
+ AI_CONCURRENCY: z31.coerce.number().int().min(1).max(32).default(4),
50222
+ INDEXING_CONCURRENCY: z31.coerce.number().int().min(0).max(32).default(2),
50223
+ EMAIL_CONCURRENCY: z31.coerce.number().int().min(0).max(8).default(1),
50224
+ MAINTENANCE_CONCURRENCY: z31.coerce.number().int().min(0).max(8).default(1),
50225
+ BULK_CONCURRENCY: z31.coerce.number().int().min(0).max(8).default(1),
50226
+ JOB_ACCOUNT_CONCURRENCY: z31.coerce.number().int().min(1).max(8).default(2),
50227
+ JOB_PROVIDER_CONCURRENCY: z31.coerce.number().int().min(1).max(128).default(8),
50228
+ WORKER_LANES: z31.string().default("indexing,enrichment,email,maintenance,bulk").refine(
49793
50229
  (value) => value.split(",").every(
49794
50230
  (lane) => ["indexing", "enrichment", "email", "maintenance", "bulk"].includes(
49795
50231
  lane
@@ -49797,38 +50233,38 @@ var serverSchema = z28.object({
49797
50233
  ),
49798
50234
  "Unknown worker lane"
49799
50235
  ),
49800
- WORKER_LEGACY_QUEUE: z28.enum(["true", "false"]).default("true").transform((value) => value === "true"),
49801
- EXPORT_STORAGE: z28.enum(["disabled", "local", "s3"]).optional(),
50236
+ WORKER_LEGACY_QUEUE: z31.enum(["true", "false"]).default("true").transform((value) => value === "true"),
50237
+ EXPORT_STORAGE: z31.enum(["disabled", "local", "s3"]).optional(),
49802
50238
  // Explicit opt-in until the revision-scoped media API is available.
49803
- MEDIA_STORAGE: z28.enum(["disabled", "local", "s3"]).default("disabled"),
49804
- MEDIA_DIRECTORY: z28.string().default("./data/media"),
49805
- MEDIA_S3_ENDPOINT: z28.url().optional(),
49806
- MEDIA_S3_REGION: z28.string().default("us-east-1"),
49807
- MEDIA_S3_BUCKET: z28.string().optional(),
49808
- MEDIA_S3_ACCESS_KEY_ID: z28.string().optional(),
49809
- MEDIA_S3_SECRET_ACCESS_KEY: z28.string().optional(),
50239
+ MEDIA_STORAGE: z31.enum(["disabled", "local", "s3"]).default("disabled"),
50240
+ MEDIA_DIRECTORY: z31.string().default("./data/media"),
50241
+ MEDIA_S3_ENDPOINT: z31.url().optional(),
50242
+ MEDIA_S3_REGION: z31.string().default("us-east-1"),
50243
+ MEDIA_S3_BUCKET: z31.string().optional(),
50244
+ MEDIA_S3_ACCESS_KEY_ID: z31.string().optional(),
50245
+ MEDIA_S3_SECRET_ACCESS_KEY: z31.string().optional(),
49810
50246
  // Exact endpoint/bucket receipt from an operator lifecycle/ACL inspection.
49811
50247
  // Spaces scoped keys cannot read these settings; never use an account-wide key in runtime.
49812
- MEDIA_S3_LIFECYCLE_VERIFIED_FOR: z28.string().optional(),
49813
- MEDIA_S3_PATH_STYLE: z28.enum(["true", "false"]).default("false").transform((value) => value === "true"),
49814
- EXPORT_DIRECTORY: z28.string().default("./data/exports"),
49815
- EXPORT_S3_ENDPOINT: z28.url().optional(),
49816
- EXPORT_S3_REGION: z28.string().default("us-east-1"),
49817
- EXPORT_S3_BUCKET: z28.string().optional(),
49818
- EXPORT_S3_ACCESS_KEY_ID: z28.string().optional(),
49819
- EXPORT_S3_SECRET_ACCESS_KEY: z28.string().optional(),
49820
- EXPORT_S3_PATH_STYLE: z28.enum(["true", "false"]).default("false").transform((value) => value === "true"),
49821
- AMQP_URL: z28.url().refine(
50248
+ MEDIA_S3_LIFECYCLE_VERIFIED_FOR: z31.string().optional(),
50249
+ MEDIA_S3_PATH_STYLE: z31.enum(["true", "false"]).default("false").transform((value) => value === "true"),
50250
+ EXPORT_DIRECTORY: z31.string().default("./data/exports"),
50251
+ EXPORT_S3_ENDPOINT: z31.url().optional(),
50252
+ EXPORT_S3_REGION: z31.string().default("us-east-1"),
50253
+ EXPORT_S3_BUCKET: z31.string().optional(),
50254
+ EXPORT_S3_ACCESS_KEY_ID: z31.string().optional(),
50255
+ EXPORT_S3_SECRET_ACCESS_KEY: z31.string().optional(),
50256
+ EXPORT_S3_PATH_STYLE: z31.enum(["true", "false"]).default("false").transform((value) => value === "true"),
50257
+ AMQP_URL: z31.url().refine(
49822
50258
  (value) => new URL(value).protocol === "amqps:",
49823
50259
  "Use TLS for the job broker"
49824
50260
  ).optional(),
49825
- ORGANIZATION_INTERVAL_SECONDS: z28.coerce.number().int().min(60).max(86400).default(900),
49826
- RESEND_API_KEY: z28.string().startsWith("re_").optional(),
49827
- EMAIL_FROM: z28.string().email().default("notifications@mail.usegrove.cloud"),
49828
- CURSOR_SECRET: z28.string().min(32),
49829
- WRITING_STAGING_KEY: z28.string().regex(/^[0-9a-f]{64}$/i).optional(),
49830
- WRITING_PROVIDER_NOTICE: z28.string().trim().min(20).max(1e3).optional(),
49831
- SHARE_LINK_KEY: z28.string().regex(/^[0-9a-f]{64}$/i).optional()
50261
+ ORGANIZATION_INTERVAL_SECONDS: z31.coerce.number().int().min(60).max(86400).default(900),
50262
+ RESEND_API_KEY: z31.string().startsWith("re_").optional(),
50263
+ EMAIL_FROM: z31.string().email().default("notifications@mail.usegrove.cloud"),
50264
+ CURSOR_SECRET: z31.string().min(32),
50265
+ WRITING_STAGING_KEY: z31.string().regex(/^[0-9a-f]{64}$/i).optional(),
50266
+ WRITING_PROVIDER_NOTICE: z31.string().trim().min(20).max(1e3).optional(),
50267
+ SHARE_LINK_KEY: z31.string().regex(/^[0-9a-f]{64}$/i).optional()
49832
50268
  });
49833
50269
  var serverEnvironmentSchema = serverSchema.superRefine((env, ctx) => {
49834
50270
  if (env.WRITING_STAGING_KEY && !env.WRITING_PROVIDER_NOTICE)
@@ -50431,7 +50867,7 @@ init_define_GROVE_TELEMETRY();
50431
50867
  init_media();
50432
50868
  import { constants as constants3 } from "node:fs";
50433
50869
  import { link, lstat, mkdir as mkdir2, open as open2, realpath, unlink as unlink2 } from "node:fs/promises";
50434
- import { randomUUID as randomUUID19 } from "node:crypto";
50870
+ import { randomUUID as randomUUID20 } from "node:crypto";
50435
50871
  import { dirname as dirname4, resolve as resolve3, sep as sep4 } from "node:path";
50436
50872
  import { Readable as Readable4 } from "node:stream";
50437
50873
  import {
@@ -50492,7 +50928,7 @@ function localMedia(root) {
50492
50928
  const publish = async (key2, image, signal) => {
50493
50929
  signal.throwIfAborted();
50494
50930
  const target2 = await directories(key2, true);
50495
- const temporary = `${target2}.${randomUUID19()}.partial`;
50931
+ const temporary = `${target2}.${randomUUID20()}.partial`;
50496
50932
  const file = await open2(
50497
50933
  temporary,
50498
50934
  constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW,
@@ -50578,7 +51014,7 @@ function s3Media(client, bucket, spacesLifecycleVerified = false) {
50578
51014
  { abortSignal: signal }
50579
51015
  );
50580
51016
  if (lifecycle.Rules?.some(
50581
- (rule) => rule.Status === "Enabled" && (rule.Expiration || rule.NoncurrentVersionExpiration)
51017
+ (rule2) => rule2.Status === "Enabled" && (rule2.Expiration || rule2.NoncurrentVersionExpiration)
50582
51018
  ))
50583
51019
  throw new Error("media_bucket_must_not_expire_source");
50584
51020
  } catch (error3) {
@@ -50586,7 +51022,7 @@ function s3Media(client, bucket, spacesLifecycleVerified = false) {
50586
51022
  if (name !== "NoSuchLifecycleConfiguration" && !(name === "AccessDenied" && spacesLifecycleVerified))
50587
51023
  throw error3;
50588
51024
  }
50589
- const probe = `media-probes/${randomUUID19()}`;
51025
+ const probe = `media-probes/${randomUUID20()}`;
50590
51026
  try {
50591
51027
  const put = (body) => client.send(
50592
51028
  new PutObjectCommand2({
@@ -50847,6 +51283,7 @@ async function startServer() {
50847
51283
  telemetry: reporter,
50848
51284
  shareLinkKey: env.SHARE_LINK_KEY,
50849
51285
  writingStagingKey: env.WRITING_STAGING_KEY,
51286
+ languageToolUrl: process.env.LANGUAGETOOL_URL,
50850
51287
  writingProviderNotice: env.WRITING_PROVIDER_NOTICE,
50851
51288
  capacity: {
50852
51289
  concurrency: env.API_MAX_IN_FLIGHT,