@miniaxolotl/grove-server 1.11.2 → 1.11.4

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/worker.js CHANGED
@@ -13,7 +13,7 @@ var __export = (target, all2) => {
13
13
  var define_GROVE_TELEMETRY_default;
14
14
  var init_define_GROVE_TELEMETRY = __esm({
15
15
  "<define:__GROVE_TELEMETRY__>"() {
16
- define_GROVE_TELEMETRY_default = { enabled: true, revision: "862ea7d1f1b5b843f5080d549c4a33c177f39a5e", version: "1.11.2", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
16
+ define_GROVE_TELEMETRY_default = { enabled: true, revision: "6ed25ff0ae691845950d57b87349be2ad4e36a9f", version: "1.11.4", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
17
17
  }
18
18
  });
19
19
 
@@ -2008,6 +2008,237 @@ var billing = {
2008
2008
  }
2009
2009
  };
2010
2010
 
2011
+ // lib/database/src/system-admin-migration.ts
2012
+ init_define_GROVE_TELEMETRY();
2013
+ var systemAdministration = {
2014
+ name: "20261025_025_system_administration",
2015
+ async up(db) {
2016
+ await db.raw(`
2017
+ CREATE TABLE account_administration (
2018
+ account_id uuid PRIMARY KEY REFERENCES public.accounts(id),
2019
+ role text NOT NULL DEFAULT 'user' CHECK (role IN ('user','system_admin')),
2020
+ access text NOT NULL DEFAULT 'default' CHECK (access IN ('default','pro','unlimited')),
2021
+ version integer NOT NULL DEFAULT 0 CHECK (version >= 0)
2022
+ );
2023
+ ALTER TABLE account_administration ENABLE ROW LEVEL SECURITY;
2024
+ CREATE POLICY tenant ON account_administration FOR SELECT
2025
+ USING (account_id = NULLIF(current_setting('grove.account_id',true),'')::uuid);
2026
+ CREATE TABLE system_admin_audit (
2027
+ id uuid PRIMARY KEY, actor_id uuid REFERENCES public.accounts(id),
2028
+ account_id uuid NOT NULL REFERENCES public.accounts(id),
2029
+ kind text NOT NULL CHECK (kind IN ('change','bootstrap')),
2030
+ reason text NOT NULL CHECK (length(reason) BETWEEN 3 AND 300),
2031
+ before jsonb NOT NULL, after jsonb NOT NULL,
2032
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()
2033
+ );
2034
+ CREATE INDEX system_admin_audit_recent ON system_admin_audit(created_at DESC, id);
2035
+ ALTER TABLE system_admin_audit ENABLE ROW LEVEL SECURITY;
2036
+ REVOKE ALL ON account_administration,system_admin_audit FROM PUBLIC,grove_runtime,grove_worker;
2037
+ GRANT SELECT ON account_administration TO grove_runtime,grove_worker;
2038
+
2039
+ CREATE FUNCTION grove_admin_state(target uuid) RETURNS jsonb
2040
+ LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2041
+ SELECT jsonb_build_object('accountId',a.id,'subject',a.clerk_subject,
2042
+ 'status',a.status,'createdAt',a.created_at,
2043
+ 'role',COALESCE(s.role,'user'),'access',COALESCE(s.access,'default'),
2044
+ 'version',COALESCE(s.version,0))
2045
+ FROM public.accounts a LEFT JOIN public.account_administration s ON s.account_id=a.id
2046
+ WHERE a.id=target
2047
+ $$;
2048
+ CREATE FUNCTION grove_admin_guard() RETURNS uuid
2049
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2050
+ DECLARE actor uuid := NULLIF(current_setting('grove.account_id',true),'')::uuid;
2051
+ BEGIN
2052
+ -- A fresh role snapshot after the lock wait fences concurrent revocation.
2053
+ PERFORM pg_advisory_xact_lock(68142025);
2054
+ IF NOT EXISTS(SELECT 1 FROM public.account_administration s
2055
+ JOIN public.accounts a ON a.id=s.account_id
2056
+ WHERE s.account_id=actor AND s.role='system_admin' AND a.status='active') THEN
2057
+ RAISE EXCEPTION 'system_admin_required' USING ERRCODE='GA001';
2058
+ END IF;
2059
+ RETURN actor;
2060
+ END $$;
2061
+ CREATE FUNCTION grove_admin_accounts(wanted text[] DEFAULT NULL) RETURNS jsonb
2062
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2063
+ DECLARE result jsonb;
2064
+ BEGIN
2065
+ PERFORM public.grove_admin_guard();
2066
+ SELECT COALESCE(jsonb_agg(public.grove_admin_state(a.id) ORDER BY a.created_at DESC,a.id),'[]'::jsonb)
2067
+ INTO result FROM (SELECT id,created_at FROM public.accounts
2068
+ WHERE status IN ('active','disabled') AND (wanted IS NULL OR clerk_subject=ANY(wanted))
2069
+ ORDER BY created_at DESC,id LIMIT 30) a;
2070
+ RETURN result;
2071
+ END $$;
2072
+ CREATE FUNCTION grove_admin_change(target uuid, operation uuid, expected integer,
2073
+ wanted_role text, wanted_access text, explanation text) RETURNS jsonb
2074
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2075
+ DECLARE actor uuid; previous public.system_admin_audit; old jsonb; result jsonb;
2076
+ BEGIN
2077
+ actor := public.grove_admin_guard();
2078
+ IF wanted_role NOT IN ('user','system_admin') OR wanted_role IS NULL
2079
+ OR wanted_access NOT IN ('default','pro','unlimited') OR wanted_access IS NULL
2080
+ OR explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300
2081
+ OR expected IS NULL OR expected < 0 OR operation IS NULL THEN
2082
+ RAISE EXCEPTION 'invalid_request' USING ERRCODE='GA002';
2083
+ END IF;
2084
+ SELECT * INTO previous FROM public.system_admin_audit WHERE id=operation;
2085
+ IF FOUND THEN
2086
+ IF previous.actor_id IS DISTINCT FROM actor OR previous.account_id IS DISTINCT FROM target
2087
+ OR previous.reason IS DISTINCT FROM explanation
2088
+ OR previous.after->>'role' IS DISTINCT FROM wanted_role
2089
+ OR previous.after->>'access' IS DISTINCT FROM wanted_access
2090
+ OR (previous.before->>'version')::integer IS DISTINCT FROM expected THEN
2091
+ RAISE EXCEPTION 'operation_conflict' USING ERRCODE='GA003';
2092
+ END IF;
2093
+ RETURN previous.after;
2094
+ END IF;
2095
+ old := public.grove_admin_state(target);
2096
+ IF old IS NULL OR old->>'status' <> 'active' THEN
2097
+ RAISE EXCEPTION 'account_unavailable' USING ERRCODE='GA004';
2098
+ END IF;
2099
+ IF (old->>'version')::integer <> expected THEN
2100
+ RAISE EXCEPTION 'admin_version_conflict' USING ERRCODE='GA005';
2101
+ END IF;
2102
+ IF old->>'role'='system_admin' AND wanted_role='user' AND NOT EXISTS(
2103
+ SELECT 1 FROM public.account_administration s JOIN public.accounts a ON a.id=s.account_id
2104
+ WHERE s.role='system_admin' AND a.status='active' AND s.account_id<>target) THEN
2105
+ RAISE EXCEPTION 'last_system_admin' USING ERRCODE='GA006';
2106
+ END IF;
2107
+ INSERT INTO public.account_administration(account_id,role,access,version)
2108
+ VALUES(target,wanted_role,wanted_access,expected+1)
2109
+ ON CONFLICT(account_id) DO UPDATE SET role=EXCLUDED.role,access=EXCLUDED.access,version=EXCLUDED.version;
2110
+ result := public.grove_admin_state(target);
2111
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
2112
+ VALUES(operation,actor,target,'change',explanation,old,result);
2113
+ RETURN result;
2114
+ END $$;
2115
+ CREATE FUNCTION grove_admin_audit() RETURNS jsonb
2116
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2117
+ DECLARE result jsonb;
2118
+ BEGIN
2119
+ PERFORM public.grove_admin_guard();
2120
+ SELECT COALESCE(jsonb_agg(jsonb_build_object('id',id,'actorId',actor_id,
2121
+ 'accountId',account_id,'kind',kind,'reason',reason,'before',before,'after',after,
2122
+ 'createdAt',created_at) ORDER BY created_at DESC,id),'[]'::jsonb)
2123
+ INTO result FROM (SELECT * FROM public.system_admin_audit ORDER BY created_at DESC,id LIMIT 50) recent;
2124
+ RETURN result;
2125
+ END $$;
2126
+ CREATE FUNCTION grove_bootstrap_system_admin(subject text, explanation text) RETURNS uuid
2127
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2128
+ DECLARE target uuid; old jsonb;
2129
+ BEGIN
2130
+ PERFORM pg_advisory_xact_lock(68142025);
2131
+ SELECT id INTO target FROM public.accounts WHERE clerk_subject=subject AND status='active';
2132
+ IF target IS NULL THEN RAISE EXCEPTION 'account_unavailable'; END IF;
2133
+ IF explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300 THEN
2134
+ RAISE EXCEPTION 'invalid_request';
2135
+ END IF;
2136
+ IF EXISTS(SELECT 1 FROM public.account_administration WHERE account_id=target AND role='system_admin') THEN RETURN target; END IF;
2137
+ IF EXISTS(SELECT 1 FROM public.account_administration WHERE role='system_admin') THEN
2138
+ RAISE EXCEPTION 'already_bootstrapped';
2139
+ END IF;
2140
+ old := public.grove_admin_state(target);
2141
+ INSERT INTO public.account_administration(account_id,role,version) VALUES(target,'system_admin',1)
2142
+ ON CONFLICT(account_id) DO UPDATE SET role='system_admin',version=public.account_administration.version+1;
2143
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
2144
+ VALUES(gen_random_uuid(),NULL,target,'bootstrap',explanation,old,public.grove_admin_state(target));
2145
+ RETURN target;
2146
+ END $$;
2147
+ REVOKE ALL ON FUNCTION grove_admin_state(uuid),grove_admin_guard(),grove_admin_accounts(text[]),
2148
+ grove_admin_change(uuid,uuid,integer,text,text,text),grove_admin_audit(),
2149
+ grove_bootstrap_system_admin(text,text) FROM PUBLIC,grove_runtime,grove_worker;
2150
+ GRANT EXECUTE ON FUNCTION grove_admin_accounts(text[]),grove_admin_change(uuid,uuid,integer,text,text,text),
2151
+ grove_admin_audit() TO grove_runtime;
2152
+ `);
2153
+ },
2154
+ async down() {
2155
+ throw new Error("Use a forward migration");
2156
+ }
2157
+ };
2158
+
2159
+ // lib/database/src/speech-cache-migration.ts
2160
+ init_define_GROVE_TELEMETRY();
2161
+ var speechCache = {
2162
+ name: "20261024_024_speech_cache",
2163
+ async up(db) {
2164
+ await db.raw(`
2165
+ -- Cache metadata belongs to the tracked object, not its short-lived request.
2166
+ -- Existing speech/ objects retain their original deadlines and lifecycle.
2167
+ ALTER TABLE export_objects
2168
+ ADD COLUMN speech_memory_id uuid,
2169
+ ADD COLUMN speech_text_hash text,
2170
+ ADD COLUMN speech_cache_key text,
2171
+ ADD COLUMN speech_sha256 text,
2172
+ ADD CONSTRAINT export_objects_speech_memory FOREIGN KEY(account_id,speech_memory_id)
2173
+ REFERENCES memories(account_id,id),
2174
+ ADD CONSTRAINT export_objects_speech_metadata CHECK (
2175
+ (speech_memory_id IS NULL AND speech_text_hash IS NULL AND speech_cache_key IS NULL AND speech_sha256 IS NULL)
2176
+ OR (speech_memory_id IS NOT NULL AND speech_text_hash IS NOT NULL AND speech_cache_key IS NOT NULL AND speech_sha256 IS NOT NULL
2177
+ AND speech_text_hash ~ '^[a-f0-9]{64}$' AND speech_cache_key ~ '^[a-f0-9]{64}$'
2178
+ AND speech_sha256 ~ '^[a-f0-9]{64}$' AND object_key LIKE 'narration/%'));
2179
+ CREATE INDEX export_objects_speech_cache ON export_objects(account_id,speech_cache_key)
2180
+ WHERE speech_cache_key IS NOT NULL;
2181
+ CREATE INDEX export_objects_speech_memory ON export_objects(account_id,speech_memory_id)
2182
+ WHERE speech_memory_id IS NOT NULL;
2183
+
2184
+ -- Every write path (including Undo, imports and API edits) gets the same
2185
+ -- retention transition. Expired objects can already be claimed for removal:
2186
+ -- never revive one, even if its bytes have not been physically deleted yet.
2187
+ CREATE FUNCTION grove_speech_cache_text() RETURNS trigger LANGUAGE plpgsql
2188
+ SET search_path=pg_catalog,public,pg_temp AS $$
2189
+ BEGIN
2190
+ UPDATE export_objects SET expires_at=CASE
2191
+ WHEN NEW.status='active' AND NEW.deleted_at IS NULL
2192
+ AND (NEW.expires_at IS NULL OR NEW.expires_at>now())
2193
+ AND speech_text_hash=encode(sha256(convert_to(NEW.content,'UTF8')),'hex')
2194
+ THEN coalesce(NEW.expires_at+interval '7 days','infinity'::timestamptz)
2195
+ ELSE least(expires_at,now()+interval '7 days') END
2196
+ WHERE account_id=NEW.account_id AND speech_memory_id=NEW.id AND expires_at>now();
2197
+ RETURN NULL;
2198
+ END $$;
2199
+ REVOKE ALL ON FUNCTION grove_speech_cache_text() FROM PUBLIC;
2200
+ CREATE TRIGGER speech_cache_text AFTER UPDATE OF content,status,deleted_at,expires_at ON memories
2201
+ FOR EACH ROW EXECUTE FUNCTION grove_speech_cache_text();
2202
+ `);
2203
+ },
2204
+ async down() {
2205
+ throw new Error("Use a forward migration");
2206
+ }
2207
+ };
2208
+
2209
+ // lib/database/src/speech-duration-migration.ts
2210
+ init_define_GROVE_TELEMETRY();
2211
+ var speechDuration = {
2212
+ name: "20261025_026_speech_duration",
2213
+ async up(db) {
2214
+ await db.raw(`
2215
+ ALTER TABLE speech_usage ADD COLUMN duration_ms bigint NOT NULL DEFAULT 0 CHECK(duration_ms>=0);
2216
+ -- Retain character counters. Unknown historical audio/failed attempts get
2217
+ -- a conservative bound: 3 MiB of MP3 at minimum 8 kbps plus one 72 ms frame.
2218
+ -- Do not reset current-month usage or claim an exact conversion from text.
2219
+ UPDATE speech_usage SET duration_ms=requests::bigint*3145800 WHERE kind='speech_synthesize';
2220
+ CREATE FUNCTION grove_speech_legacy_duration() RETURNS trigger LANGUAGE plpgsql
2221
+ SET search_path=pg_catalog,public,pg_temp AS $$
2222
+ BEGIN
2223
+ IF NEW.kind='speech_synthesize' THEN
2224
+ IF TG_OP='INSERT' AND NEW.requests>0 AND NEW.duration_ms=0 THEN
2225
+ NEW.duration_ms:=NEW.requests::bigint*3145800;
2226
+ ELSIF TG_OP='UPDATE' AND NEW.requests>OLD.requests AND NEW.duration_ms=OLD.duration_ms THEN
2227
+ NEW.duration_ms:=OLD.duration_ms+(NEW.requests-OLD.requests)::bigint*3145800;
2228
+ END IF;
2229
+ END IF;
2230
+ RETURN NEW;
2231
+ END $$;
2232
+ REVOKE ALL ON FUNCTION grove_speech_legacy_duration() FROM PUBLIC;
2233
+ CREATE TRIGGER speech_legacy_duration BEFORE INSERT OR UPDATE ON speech_usage
2234
+ FOR EACH ROW EXECUTE FUNCTION grove_speech_legacy_duration();
2235
+ `);
2236
+ },
2237
+ async down() {
2238
+ throw new Error("Use a forward migration");
2239
+ }
2240
+ };
2241
+
2011
2242
  // lib/database/src/speech-voices-migration.ts
2012
2243
  init_define_GROVE_TELEMETRY();
2013
2244
  var speechVoices = {
@@ -4360,7 +4591,10 @@ var migrations = [
4360
4591
  researchTools,
4361
4592
  speechDefaults,
4362
4593
  speechVoices,
4363
- billing
4594
+ billing,
4595
+ speechCache,
4596
+ systemAdministration,
4597
+ speechDuration
4364
4598
  ];
4365
4599
  var migrationSource = {
4366
4600
  getMigrations: async () => migrations,
@@ -4440,6 +4674,7 @@ async function probeDatabase(db) {
4440
4674
  );
4441
4675
  await db.raw("SELECT id, lane, lease_id FROM background_tasks LIMIT 0");
4442
4676
  await db.raw("SELECT status, archive_operation_id FROM projects LIMIT 0");
4677
+ await db.raw("SELECT duration_ms FROM speech_usage LIMIT 0");
4443
4678
  await db.raw("SELECT archive_operation_id FROM memories LIMIT 0");
4444
4679
  await db.raw("SELECT tools, tools_version FROM conversations LIMIT 0");
4445
4680
  const versions = await db.raw(
@@ -4470,6 +4705,33 @@ var MemoryModel = class extends Model {
4470
4705
  // lib/environment/src/index.ts
4471
4706
  init_define_GROVE_TELEMETRY();
4472
4707
  import { z } from "zod";
4708
+
4709
+ // lib/shared/src/billing.ts
4710
+ init_define_GROVE_TELEMETRY();
4711
+ var billingFlagKey = "billing-enabled";
4712
+ var billingPriceFlagKey = "billing-pro-monthly-usd";
4713
+ var billingLimits = {
4714
+ free: {
4715
+ generation: { daily: 1e3, monthly: 31e3 },
4716
+ research: { daily: 20, monthly: 620 },
4717
+ transcription: { daily: null, monthly: 72e5 },
4718
+ synthesis: { daily: null, monthly: 72e5 }
4719
+ },
4720
+ pro: {
4721
+ generation: { daily: 5e3, monthly: 155e3 },
4722
+ research: { daily: 100, monthly: 3100 },
4723
+ transcription: { daily: null, monthly: 288e5 },
4724
+ synthesis: { daily: null, monthly: 288e5 }
4725
+ }
4726
+ };
4727
+ var billingUnits = {
4728
+ generation: "requests",
4729
+ research: "calls",
4730
+ transcription: "milliseconds",
4731
+ synthesis: "milliseconds"
4732
+ };
4733
+
4734
+ // lib/environment/src/index.ts
4473
4735
  var origin = z.url().transform((value, ctx) => {
4474
4736
  const url = new URL(value);
4475
4737
  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))) {
@@ -4498,6 +4760,11 @@ var serverSchema = z.object({
4498
4760
  API_INTERACTIVE_TIMEOUT_MS: z.coerce.number().int().min(100).max(18e4).default(9e4),
4499
4761
  API_ORIGIN: origin,
4500
4762
  SITE_URL: origin,
4763
+ // Public ownership proof, never an account credential. Empty values are omitted below.
4764
+ OPENAI_APPS_CHALLENGE: z.string().min(1).max(512).refine(
4765
+ (value) => !/\s/.test(value),
4766
+ "Use the exact non-whitespace verification token"
4767
+ ).optional(),
4501
4768
  CLERK_PUBLISHABLE_KEY: z.string().startsWith("pk_"),
4502
4769
  CLERK_SECRET_KEY: z.string().startsWith("sk_"),
4503
4770
  CLERK_ISSUER: origin,
@@ -4511,18 +4778,35 @@ var serverSchema = z.object({
4511
4778
  STRIPE_PORTAL_CONFIGURATION_ID: z.string().startsWith("bpc_").optional(),
4512
4779
  STRIPE_PRO_MONTHLY_PRICE_ID: z.string().startsWith("price_").optional(),
4513
4780
  STRIPE_PRO_YEARLY_PRICE_ID: z.string().startsWith("price_").optional(),
4514
- BILLING_FREE_GENERATION_DAILY: allowance(10),
4515
- BILLING_FREE_GENERATION_MONTHLY: allowance(100),
4516
- BILLING_PRO_GENERATION_DAILY: allowance(200),
4517
- BILLING_PRO_GENERATION_MONTHLY: allowance(2e3),
4518
- BILLING_FREE_RESEARCH_DAILY: allowance(3),
4519
- BILLING_FREE_RESEARCH_MONTHLY: allowance(10),
4520
- BILLING_PRO_RESEARCH_DAILY: allowance(20),
4521
- BILLING_PRO_RESEARCH_MONTHLY: allowance(200),
4522
- BILLING_FREE_TRANSCRIPTION_MONTHLY_MS: allowance(6e5),
4523
- BILLING_PRO_TRANSCRIPTION_MONTHLY_MS: allowance(72e5),
4524
- BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: allowance(1e4),
4525
- BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: allowance(2e5),
4781
+ BILLING_FREE_GENERATION_DAILY: allowance(
4782
+ billingLimits.free.generation.daily
4783
+ ),
4784
+ BILLING_FREE_GENERATION_MONTHLY: allowance(
4785
+ billingLimits.free.generation.monthly
4786
+ ),
4787
+ BILLING_PRO_GENERATION_DAILY: allowance(billingLimits.pro.generation.daily),
4788
+ BILLING_PRO_GENERATION_MONTHLY: allowance(
4789
+ billingLimits.pro.generation.monthly
4790
+ ),
4791
+ BILLING_FREE_RESEARCH_DAILY: allowance(billingLimits.free.research.daily),
4792
+ BILLING_FREE_RESEARCH_MONTHLY: allowance(billingLimits.free.research.monthly),
4793
+ BILLING_PRO_RESEARCH_DAILY: allowance(billingLimits.pro.research.daily),
4794
+ BILLING_PRO_RESEARCH_MONTHLY: allowance(billingLimits.pro.research.monthly),
4795
+ BILLING_FREE_TRANSCRIPTION_MONTHLY_MS: allowance(
4796
+ billingLimits.free.transcription.monthly
4797
+ ),
4798
+ BILLING_PRO_TRANSCRIPTION_MONTHLY_MS: allowance(
4799
+ billingLimits.pro.transcription.monthly
4800
+ ),
4801
+ BILLING_FREE_SYNTHESIS_MONTHLY_MS: allowance(
4802
+ billingLimits.free.synthesis.monthly
4803
+ ),
4804
+ BILLING_PRO_SYNTHESIS_MONTHLY_MS: allowance(
4805
+ billingLimits.pro.synthesis.monthly
4806
+ ),
4807
+ // Reject old deployment settings instead of silently treating characters as time.
4808
+ BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: z.string().optional(),
4809
+ BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: z.string().optional(),
4526
4810
  EMBEDDING_MODE: z.enum(["local", "remote", "disabled"]).optional(),
4527
4811
  EMBEDDING_CACHE: z.string().default("./data/models"),
4528
4812
  EMBEDDING_URL: z.string().optional(),
@@ -4605,6 +4889,15 @@ var serverSchema = z.object({
4605
4889
  SHARE_LINK_KEY: z.string().regex(/^[0-9a-f]{64}$/i).optional()
4606
4890
  });
4607
4891
  var serverEnvironmentSchema = serverSchema.superRefine((env, ctx) => {
4892
+ for (const tier of ["FREE", "PRO"]) {
4893
+ const path = `BILLING_${tier}_SYNTHESIS_MONTHLY_CHARACTERS`;
4894
+ if (env[path] !== void 0)
4895
+ ctx.addIssue({
4896
+ code: "custom",
4897
+ path: [path],
4898
+ message: "Replace SYNTHESIS_MONTHLY_CHARACTERS with SYNTHESIS_MONTHLY_MS; characters are not audio duration"
4899
+ });
4900
+ }
4608
4901
  if (env.BILLING_CONFIGURED && (env.GROVE_EDITION !== "cloud" || !env.FLAGS || !env.STRIPE_SECRET_KEY || !env.STRIPE_WEBHOOK_SECRET || !env.STRIPE_PRO_PRODUCT_ID && !env.STRIPE_PRO_MONTHLY_PRICE_ID && !env.STRIPE_PRO_YEARLY_PRICE_ID))
4609
4902
  ctx.addIssue({
4610
4903
  code: "custom",
@@ -4621,6 +4914,18 @@ function readServerEnvironment(env = process.env) {
4621
4914
  );
4622
4915
  }
4623
4916
 
4917
+ // packages/api/src/runtime.ts
4918
+ import { createClient as createClient2 } from "@vercel/flags-core";
4919
+
4920
+ // lib/shared/src/speech-voices.ts
4921
+ init_define_GROVE_TELEMETRY();
4922
+ var miniMaxTtsFlagKey = "minimax-tts-enabled";
4923
+ var speechVoiceIds = ["reed", "willow", "cedar", "brook"];
4924
+ var defaultSpeechVoice = "reed";
4925
+ function isSpeechVoice(value) {
4926
+ return speechVoiceIds.some((id) => id === value);
4927
+ }
4928
+
4624
4929
  // lib/memory/src/index.ts
4625
4930
  init_define_GROVE_TELEMETRY();
4626
4931
  import {
@@ -4650,9 +4955,8 @@ var policy = {
4650
4955
  init_define_GROVE_TELEMETRY();
4651
4956
  import { createHash as createHash2 } from "node:crypto";
4652
4957
 
4653
- // lib/ai/src/speech.ts
4958
+ // lib/ai/src/audio-duration.ts
4654
4959
  init_define_GROVE_TELEMETRY();
4655
- import { createHash } from "node:crypto";
4656
4960
 
4657
4961
  // lib/shared/src/speech.ts
4658
4962
  init_define_GROVE_TELEMETRY();
@@ -11806,14 +12110,6 @@ function defaultOnError(left, right) {
11806
12110
  }
11807
12111
  }
11808
12112
 
11809
- // lib/shared/src/speech-voices.ts
11810
- init_define_GROVE_TELEMETRY();
11811
- var speechVoiceIds = ["reed", "willow", "cedar", "brook"];
11812
- var defaultSpeechVoice = "reed";
11813
- function isSpeechVoice(value) {
11814
- return speechVoiceIds.some((id) => id === value);
11815
- }
11816
-
11817
12113
  // lib/shared/src/speech.ts
11818
12114
  var speechRequestSchema = z2.object({
11819
12115
  id: z2.uuid(),
@@ -11828,7 +12124,10 @@ var speechLimits = {
11828
12124
  audioBytes: 3 * 1024 * 1024,
11829
12125
  dailyRequests: 20,
11830
12126
  dailyAudioMs: 6e5,
11831
- dailyCharacters: 6e4
12127
+ dailyCharacters: 6e4,
12128
+ // MPEG Layer III's minimum supported bitrate is 8 kbps (one byte/ms).
12129
+ // Include one maximum-length frame for conservative pre-dispatch reservations.
12130
+ maximumAudioMs: 3 * 1024 * 1024 + 72
11832
12131
  };
11833
12132
  function speechText(content3) {
11834
12133
  const tree = fromMarkdown(content3);
@@ -11866,7 +12165,43 @@ function speechText(content3) {
11866
12165
  return text3(tree).replace(/\n[ \t]*\n(?:[ \t]*\n)+/g, "\n\n").trim();
11867
12166
  }
11868
12167
 
12168
+ // lib/ai/src/audio-duration.ts
12169
+ function mp3DurationMs(bytes) {
12170
+ const invalid = () => new InferenceError("provider_invalid_audio", false);
12171
+ if (!bytes.length || bytes.length > speechLimits.audioBytes) throw invalid();
12172
+ let offset = 0, end = bytes.length, seconds = 0, frames = 0;
12173
+ if (bytes.subarray(0, 3).toString() === "ID3") {
12174
+ if (bytes.length < 10 || ![2, 3, 4].includes(bytes[3]) || bytes.subarray(6, 10).some((value) => value & 128))
12175
+ throw invalid();
12176
+ const size = bytes[6] * 2097152 + bytes[7] * 16384 + bytes[8] * 128 + bytes[9];
12177
+ offset = 10 + size + (bytes[3] === 4 && bytes[5] & 16 ? 10 : 0);
12178
+ }
12179
+ if (end >= 128 && bytes.subarray(end - 128, end - 125).toString() === "TAG")
12180
+ end -= 128;
12181
+ while (offset < end) {
12182
+ if (offset + 4 > end || bytes[offset] !== 255 || (bytes[offset + 1] & 224) !== 224)
12183
+ throw invalid();
12184
+ const version2 = bytes[offset + 1] >> 3 & 3;
12185
+ const layer = bytes[offset + 1] >> 1 & 3;
12186
+ const rate = bytes[offset + 2] >> 2 & 3;
12187
+ const bitrateIndex = bytes[offset + 2] >> 4;
12188
+ if (version2 === 1 || layer !== 1 || rate === 3 || bitrateIndex === 0 || bitrateIndex === 15)
12189
+ throw invalid();
12190
+ const sampleRate = [44100, 48e3, 32e3][rate] / (version2 === 3 ? 1 : version2 === 2 ? 2 : 4);
12191
+ const bitrate = (version2 === 3 ? [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320] : [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160])[bitrateIndex] * 1e3;
12192
+ const frameBytes = Math.floor((version2 === 3 ? 144 : 72) * bitrate / sampleRate) + (bytes[offset + 2] >> 1 & 1);
12193
+ if (offset + frameBytes > end) throw invalid();
12194
+ seconds += (version2 === 3 ? 1152 : 576) / sampleRate;
12195
+ offset += frameBytes;
12196
+ frames++;
12197
+ }
12198
+ if (!frames) throw invalid();
12199
+ return Math.ceil(seconds * 1e3);
12200
+ }
12201
+
11869
12202
  // lib/ai/src/speech.ts
12203
+ init_define_GROVE_TELEMETRY();
12204
+ import { createHash } from "node:crypto";
11870
12205
  async function requestSpeech(config, url, body, parent, maximum, contentType = "application/json") {
11871
12206
  const signal = AbortSignal.any([
11872
12207
  parent,
@@ -12851,6 +13186,9 @@ var grantSchema = z7.object({
12851
13186
  var connectionSchema = grantSchema.extend({
12852
13187
  clientId: z7.string().min(1).max(500)
12853
13188
  });
13189
+ var connectionUpdateSchema = grantSchema.extend({
13190
+ expectedState: z7.string().regex(/^[a-f0-9]{64}$/).optional()
13191
+ });
12854
13192
  var agentSchema = z7.enum(["opencode", "claude", "codex"]);
12855
13193
  var connectSchema = z7.object({
12856
13194
  agent: agentSchema,
@@ -12951,25 +13289,30 @@ var notebookToolLifecycleSchema = z8.object({
12951
13289
  );
12952
13290
  var memoryTools = {
12953
13291
  remember: {
13292
+ title: "Save a memory",
12954
13293
  schema: rememberSchema,
12955
13294
  description: "Save a concise memory or replace it by id/expectedVersion. Corrections replace metadata too: prefer update_memory for partial edits. Reuse operationId on retries. Handoffs default to 30 days; expired records are hidden and later soft-deleted."
12956
13295
  },
12957
13296
  recall: {
13297
+ title: "Recall saved context",
12958
13298
  schema: recallSchema,
12959
13299
  readOnly: true,
12960
13300
  description: "Recall bounded relevant active memories in the explicit project/personal scope. Without query, retrieve a compact profile and selected task handoff."
12961
13301
  },
12962
13302
  memories: {
13303
+ title: "Find memories",
12963
13304
  schema: listSchema,
12964
13305
  readOnly: true,
12965
13306
  description: "Search and list notes with IDs, versions, provenance, status/tag filters and cursor pagination. Omit projectId to inspect all granted scopes; null means Personal."
12966
13307
  },
12967
13308
  forget: {
13309
+ title: "Delete selected memories",
12968
13310
  schema: forgetSchema,
12969
13311
  destructive: true,
12970
13312
  description: "Soft-delete exact note IDs at their expectedVersion. Retained authored history is hidden, not physically erased. There is no ordinary restore/Undo for deletion. Inspect each outcome; previously delivered text cannot be retracted."
12971
13313
  },
12972
13314
  get_memory: {
13315
+ title: "Read a memory",
12973
13316
  schema: z8.object({
12974
13317
  id: uuidSchema,
12975
13318
  revision: z8.number().int().positive().optional()
@@ -12978,19 +13321,23 @@ var memoryTools = {
12978
13321
  description: "Read one exact note by ID, optionally at a historical revision. Current scope, deletion and historical-source expiry checks still apply."
12979
13322
  },
12980
13323
  memory_history: {
13324
+ title: "Read memory history",
12981
13325
  schema: z8.object({ id: uuidSchema }).strict(),
12982
13326
  readOnly: true,
12983
13327
  description: "Read up to 100 most recent revisions of an accessible note. Use get_memory with revision for historical content."
12984
13328
  },
12985
13329
  update_memory: {
13330
+ title: "Update a memory",
12986
13331
  schema: memoryUpdateSchema,
12987
13332
  description: "Partially update a note at expectedVersion. Omitted content, scope, kind, provenance and lifetime are preserved. projectId moves the note; null means Personal. Reuse operationId on retry."
12988
13333
  },
12989
13334
  move_memories: {
13335
+ title: "Move memories",
12990
13336
  schema: moveMemoriesSchema,
12991
13337
  description: "Atomically move up to 50 exact ID/version notes into an existing notebook (projectId) or Personal (null). Preserve content and metadata; source and destination must be granted. Reuse operationId."
12992
13338
  },
12993
13339
  archive_memory: {
13340
+ title: "Archive a memory",
12994
13341
  schema: z8.object({
12995
13342
  id: uuidSchema,
12996
13343
  operationId: operationSchema,
@@ -12999,23 +13346,28 @@ var memoryTools = {
12999
13346
  description: "Archive an exact note at expectedVersion, removing it from recall. Content/history remain available; restore_memory reverses archive. Reuse operationId."
13000
13347
  },
13001
13348
  restore_memory: {
13349
+ title: "Restore a memory",
13002
13350
  schema: versionSchema.extend({ id: uuidSchema }),
13003
13351
  description: "Restore an archived/expired note or a historical revision at expectedVersion. Deleted notes cannot be restored. Optional revision selects history; durable removes expiry. Reuse operationId."
13004
13352
  },
13005
13353
  notebooks: {
13354
+ title: "Find notebooks",
13006
13355
  schema: notebookListSchema,
13007
13356
  readOnly: true,
13008
13357
  description: "List/search granted notebooks (folders) with IDs, names, parentId, versions and cursor pagination. Follow every page to build a tree. Archived notebooks require an owner website session."
13009
13358
  },
13010
13359
  create_notebook: {
13360
+ title: "Create a notebook",
13011
13361
  schema: notebookCreateSchema,
13012
13362
  description: "Create a notebook, optionally under parentId. Requires all-project write access or an owner session. Reuse operationId for retry-safe creation."
13013
13363
  },
13014
13364
  update_notebook: {
13365
+ title: "Update a notebook",
13015
13366
  schema: notebookUpdateSchema,
13016
13367
  description: "Rename and/or move an existing notebook at expectedVersion. Omitted fields are preserved; parentId=null moves to root. Source and parent must be granted; cycles are rejected. Reuse operationId."
13017
13368
  },
13018
13369
  notebook_lifecycle: {
13370
+ title: "Manage notebook lifecycle",
13019
13371
  schema: notebookToolLifecycleSchema,
13020
13372
  destructive: true,
13021
13373
  description: "Owner website session only: preview a notebook subtree, then archive/restore/soft-delete using its fingerprint, expectedVersion and operationId. Agent OAuth/API keys cannot administer subtrees. Deletion hides retained history and has no ordinary Undo."
@@ -15460,27 +15812,6 @@ async function runAssistanceJob(db, providers, dailyLimit, job, resolveProfiles,
15460
15812
 
15461
15813
  // lib/memory/src/billing-quotas.ts
15462
15814
  init_define_GROVE_TELEMETRY();
15463
-
15464
- // lib/shared/src/billing.ts
15465
- init_define_GROVE_TELEMETRY();
15466
- var billingFlagKey = "billing-enabled";
15467
- var billingPriceFlagKey = "billing-pro-monthly-usd";
15468
- var billingLimits = {
15469
- free: {
15470
- generation: { daily: 10, monthly: 100 },
15471
- research: { daily: 3, monthly: 10 },
15472
- transcription: { daily: null, monthly: 6e5 },
15473
- synthesis: { daily: null, monthly: 1e4 }
15474
- },
15475
- pro: {
15476
- generation: { daily: 200, monthly: 2e3 },
15477
- research: { daily: 20, monthly: 200 },
15478
- transcription: { daily: null, monthly: 72e5 },
15479
- synthesis: { daily: null, monthly: 2e5 }
15480
- }
15481
- };
15482
-
15483
- // lib/memory/src/billing-quotas.ts
15484
15815
  var configurations = /* @__PURE__ */ new WeakMap();
15485
15816
  function configureBillingQuotas(db, configuration) {
15486
15817
  configurations.set(db, configuration);
@@ -15489,13 +15820,16 @@ async function billingUsage(db, trx, accountId) {
15489
15820
  const config = configurations.get(db);
15490
15821
  if (!config) return null;
15491
15822
  const account = await trx("accounts").where({ id: accountId }).first("clerkSubject");
15492
- if (!account || !await config.enabled(account.clerkSubject)) return null;
15823
+ if (!account) return null;
15824
+ const grant = await trx("account_administration").where({ accountId }).first("access");
15825
+ const override = grant?.access === "pro" || grant?.access === "unlimited" ? grant.access : null;
15826
+ if (!override && !await config.enabled(account.clerkSubject)) return null;
15493
15827
  const paid = await trx("billing_subscriptions").where({ accountId }).whereIn("status", ["active", "trialing"]).where((query) => {
15494
15828
  query.whereIn("priceId", config.priceIds);
15495
15829
  if (config.productId) query.orWhere({ productId: config.productId });
15496
15830
  }).where("periodEnd", ">", trx.fn.now()).first("id");
15497
- const plan = paid ? "pro" : "free";
15498
- const limits2 = (config.limits ?? billingLimits)[plan];
15831
+ const plan = override ?? (paid ? "pro" : "free");
15832
+ const limits2 = (config.limits ?? billingLimits)[plan === "unlimited" ? "pro" : plan];
15499
15833
  const {
15500
15834
  rows: [clock]
15501
15835
  } = await trx.raw(`SELECT
@@ -15506,7 +15840,7 @@ async function billingUsage(db, trx, accountId) {
15506
15840
  const metrics2 = {};
15507
15841
  for (const metric of Object.keys(limits2)) {
15508
15842
  const table = metric === "generation" ? "inference_usage" : metric === "research" ? "research_account_usage" : "speech_usage";
15509
- const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : "units";
15843
+ const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : metric === "synthesis" ? "durationMs" : "units";
15510
15844
  const query = trx(table).where({ accountId }).whereBetween("day", [clock.month, clock.today]);
15511
15845
  if (metric === "generation") query.where({ role: "generation" });
15512
15846
  if (metric === "transcription" || metric === "synthesis")
@@ -15522,8 +15856,8 @@ async function billingUsage(db, trx, accountId) {
15522
15856
  metrics2[metric] = {
15523
15857
  today: Number(usage.today),
15524
15858
  month: Number(usage.month),
15525
- dailyLimit: limits2[metric].daily,
15526
- monthlyLimit: limits2[metric].monthly
15859
+ dailyLimit: plan === "unlimited" ? null : limits2[metric].daily,
15860
+ monthlyLimit: plan === "unlimited" ? null : limits2[metric].monthly
15527
15861
  };
15528
15862
  }
15529
15863
  return {
@@ -15533,12 +15867,6 @@ async function billingUsage(db, trx, accountId) {
15533
15867
  metrics: metrics2
15534
15868
  };
15535
15869
  }
15536
- async function billingAllows(db, trx, accountId, metric, units = 1) {
15537
- const snapshot = await billingUsage(db, trx, accountId);
15538
- if (!snapshot) return true;
15539
- const usage = snapshot.metrics[metric];
15540
- return (usage.dailyLimit === null || usage.today + units <= usage.dailyLimit) && usage.month + units <= usage.monthlyLimit;
15541
- }
15542
15870
 
15543
15871
  // lib/memory/src/processing.ts
15544
15872
  var briefTarget = (scope) => `${scope.projectId ?? "personal"}${scope.taskId ? `:task:${scope.taskId}` : ""}`;
@@ -15736,10 +16064,15 @@ async function reserve(db, trx, accountId, role, limit) {
15736
16064
  await trx.raw("SELECT pg_advisory_xact_lock(hashtextextended(?, 6))", [
15737
16065
  accountId
15738
16066
  ]);
15739
- const result = await trx("inference_usage").whereRaw("day = (now() AT TIME ZONE 'UTC')::date").sum("requests as count").first();
15740
- if (Number(result?.count ?? 0) >= limit) return false;
15741
- if (role === "generation" && !await billingAllows(db, trx, accountId, "generation"))
15742
- return false;
16067
+ const billing2 = await billingUsage(db, trx, accountId);
16068
+ const result = await trx("inference_usage").whereRaw("day = (now() AT TIME ZONE 'UTC')::date").modify((query) => {
16069
+ if (billing2) query.whereNot({ role: "generation" });
16070
+ }).sum("requests as count").first();
16071
+ if (billing2 && role === "generation") {
16072
+ const usage = billing2.metrics.generation;
16073
+ if (usage.dailyLimit !== null && usage.today >= usage.dailyLimit || usage.monthlyLimit !== null && usage.month >= usage.monthlyLimit)
16074
+ return false;
16075
+ } else if (Number(result?.count ?? 0) >= limit) return false;
15743
16076
  await trx.raw(
15744
16077
  `INSERT INTO inference_usage(account_id, role, day, requests) VALUES (?, ?, (now() AT TIME ZONE 'UTC')::date, 1)
15745
16078
  ON CONFLICT(account_id, day, role) DO UPDATE SET requests = inference_usage.requests + 1`,
@@ -16207,11 +16540,21 @@ var askToolIds = Object.keys(askToolCatalog);
16207
16540
 
16208
16541
  // lib/shared/src/conversations.ts
16209
16542
  var askToolsSchema = z12.object({ exa: z12.boolean(), tavily: z12.boolean(), organize: z12.boolean() }).strict();
16543
+ var askToolsPatchSchema = askToolsSchema.partial().refine(
16544
+ (patch) => Object.keys(patch).length > 0,
16545
+ "Choose at least one tool to update"
16546
+ );
16210
16547
  var toolSettingsSchema = z12.object({
16211
16548
  tools: askToolsSchema,
16212
16549
  expectedVersion: z12.number().int().nonnegative(),
16213
- saveDefault: z12.boolean().optional()
16214
- }).strict();
16550
+ saveDefault: z12.boolean().optional(),
16551
+ defaultPatch: askToolsPatchSchema.optional()
16552
+ }).strict().refine(
16553
+ ({ tools, saveDefault, defaultPatch }) => !defaultPatch || saveDefault && Object.entries(defaultPatch).every(
16554
+ ([key2, value]) => tools[key2] === value
16555
+ ),
16556
+ "Saved defaults must match the changed conversation tools"
16557
+ );
16215
16558
  var researchRequestSchema = z12.object({
16216
16559
  provider: z12.enum(["exa", "tavily"]),
16217
16560
  query: z12.string().max(500),
@@ -16688,6 +17031,14 @@ var summary = (row) => ({
16688
17031
  tools: row.tools ?? defaultAskTools,
16689
17032
  toolsVersion: row.toolsVersion ?? 0
16690
17033
  });
17034
+ async function saveToolDefaults(trx, account, patch) {
17035
+ const defaults2 = {
17036
+ ...askToolsSchema.parse(account.askTools ?? defaultAskTools),
17037
+ ...patch
17038
+ };
17039
+ await trx("accounts").where({ id: account.id }).update({ askTools: JSON.stringify(defaults2) });
17040
+ return defaults2;
17041
+ }
16691
17042
  var Conversations = class {
16692
17043
  constructor(service, present, revise) {
16693
17044
  this.service = service;
@@ -16750,11 +17101,23 @@ var Conversations = class {
16750
17101
  tools: JSON.stringify(row.tools),
16751
17102
  toolsVersion: row.toolsVersion
16752
17103
  });
16753
- if (input.saveDefault)
16754
- await trx("accounts").where({ id: account.id }).update({ askTools: JSON.stringify(row.tools) });
16755
- return this.read(trx, row);
17104
+ const defaults2 = input.saveDefault ? await saveToolDefaults(trx, account, input.defaultPatch ?? row.tools) : void 0;
17105
+ return {
17106
+ ...await this.read(trx, row),
17107
+ ...defaults2 ? { defaults: defaults2 } : {}
17108
+ };
16756
17109
  });
16757
17110
  }
17111
+ async configureDefaults(principal, input) {
17112
+ const patch = askToolsPatchSchema.parse(input);
17113
+ return this.service.access(
17114
+ principal,
17115
+ "admin",
17116
+ async ({ trx, account }) => ({
17117
+ defaults: await saveToolDefaults(trx, account, patch)
17118
+ })
17119
+ );
17120
+ }
16758
17121
  async get(principal, id) {
16759
17122
  return this.service.access(principal, "admin", async ({ trx }) => {
16760
17123
  const row = await trx("conversations").where({ id }).first();
@@ -17298,19 +17661,20 @@ var Conversations = class {
17298
17661
  );
17299
17662
  if (previous2) return { cached: previous2.sources };
17300
17663
  if (runs.length >= 6) return { limited: true };
17301
- if (!await billingAllows(
17664
+ const billing2 = await billingUsage(
17302
17665
  this.service.db,
17303
17666
  trx,
17304
- principal.accountId,
17305
- "research"
17306
- ))
17667
+ principal.accountId
17668
+ );
17669
+ const usage = billing2?.metrics.research;
17670
+ if (usage && (usage.dailyLimit !== null && usage.today >= usage.dailyLimit || usage.monthlyLimit !== null && usage.month >= usage.monthlyLimit))
17307
17671
  return { limited: true };
17308
17672
  const { rows } = await trx.raw(
17309
17673
  "SELECT grove_research_reserve(?,?,?,?) AS admitted",
17310
17674
  [
17311
17675
  request2.provider,
17312
17676
  operation,
17313
- this.service.researchLimits.dailyCalls,
17677
+ usage ? usage.dailyLimit : this.service.researchLimits.dailyCalls,
17314
17678
  this.service.researchLimits.monthlyMicrodollars
17315
17679
  ]
17316
17680
  );
@@ -18261,12 +18625,21 @@ var keys = (kind) => kind === "speech_transcribe" ? {
18261
18625
  version: "readAloudVersion",
18262
18626
  provider: "synthesis"
18263
18627
  };
18628
+ var unavailable2 = () => new GroveError("speech_unavailable", "Speech is not configured", 503);
18264
18629
  var changed = () => new GroveError(
18265
18630
  "speech_changed",
18266
18631
  "The note, transcript or speech settings changed. Start again.",
18267
18632
  409
18268
18633
  );
18269
- var synthesisProtocol = "speech-voices-v1";
18634
+ var synthesisProtocol = "speech-content-cache-v1";
18635
+ async function synthesisAvailable(provider) {
18636
+ if (!provider) return false;
18637
+ try {
18638
+ return provider.available ? await provider.available() === true : true;
18639
+ } catch {
18640
+ return false;
18641
+ }
18642
+ }
18270
18643
  function configuredProfile(configuration, kind, voiceId) {
18271
18644
  if (kind === "speech_transcribe") return configuration?.transcription;
18272
18645
  return configuration?.synthesis === synthesisProtocol && isSpeechVoice(voiceId) ? configuration.synthesisProfiles[voiceId] : void 0;
@@ -18304,6 +18677,8 @@ async function source2(trx, memoryId, version2, mediaId) {
18304
18677
  return {
18305
18678
  object: void 0,
18306
18679
  text: text3,
18680
+ textHash: createHash8("sha256").update(note.content).digest("hex"),
18681
+ expiresAt: note.expiresAt,
18307
18682
  units: text3.length,
18308
18683
  transcriptVersion: void 0
18309
18684
  };
@@ -18317,6 +18692,8 @@ async function validate(trx, row, providers) {
18317
18692
  if (!payload.profile || configuredProfile(configuration, row.kind, payload.voiceId) !== payload.profile || selectedProvider(providers, row.kind, payload.voiceId)?.profile !== payload.profile)
18318
18693
  throw changed();
18319
18694
  const control = await trx("processing_control").first("epoch");
18695
+ if (row.kind === "speech_synthesize" && !await synthesisAvailable(providers.synthesis?.[payload.voiceId]))
18696
+ throw unavailable2();
18320
18697
  const session = await trx.raw(
18321
18698
  "SELECT grove_speech_session_active(?::uuid) AS active",
18322
18699
  [row.id]
@@ -18332,6 +18709,8 @@ async function validate(trx, row, providers) {
18332
18709
  );
18333
18710
  if (current.object && (current.object.sha256 !== payload.sha256 || current.transcriptVersion !== payload.transcriptVersion))
18334
18711
  throw changed();
18712
+ if (row.kind === "speech_synthesize" && current.textHash !== payload.textHash)
18713
+ throw changed();
18335
18714
  return current;
18336
18715
  }
18337
18716
  function speechHandlers(service, providers, store, readSource, db = service.db, concurrency = 2) {
@@ -18350,6 +18729,7 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18350
18729
  return validate(trx, row, providers);
18351
18730
  });
18352
18731
  let slot = false;
18732
+ let durationReservation;
18353
18733
  const watcher = (async () => {
18354
18734
  try {
18355
18735
  while (!monitoring.signal.aborted) {
@@ -18376,19 +18756,31 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18376
18756
  await validate(trx, row, providers);
18377
18757
  const usage = await trx("speech_usage").where({ kind: row.kind }).whereRaw("day=(now() AT TIME ZONE 'UTC')::date").first();
18378
18758
  const limit = row.kind === "speech_transcribe" ? speechLimits.dailyAudioMs : speechLimits.dailyCharacters;
18379
- if ((usage?.requests ?? 0) >= speechLimits.dailyRequests || (usage?.units ?? 0) + current.units > limit || !await billingAllows(
18380
- db,
18381
- trx,
18382
- row.accountId,
18383
- key2.provider,
18384
- current.units
18385
- ))
18759
+ const billing2 = await billingUsage(db, trx, row.accountId);
18760
+ const metric = billing2?.metrics[key2.provider];
18761
+ const timed = row.kind === "speech_synthesize";
18762
+ const reservation = timed ? Math.min(
18763
+ speechLimits.maximumAudioMs,
18764
+ metric ? Math.max(
18765
+ 0,
18766
+ Math.min(
18767
+ metric.monthlyLimit === null ? Infinity : metric.monthlyLimit - metric.month,
18768
+ metric.dailyLimit === null ? Infinity : metric.dailyLimit - metric.today
18769
+ )
18770
+ ) : Infinity
18771
+ ) : current.units;
18772
+ if ((usage?.requests ?? 0) >= speechLimits.dailyRequests || !billing2 && (usage?.units ?? 0) + current.units > limit || reservation <= 0 || metric && (metric.monthlyLimit !== null && metric.month + reservation > metric.monthlyLimit || metric.dailyLimit !== null && metric.today + reservation > metric.dailyLimit))
18386
18773
  throw new TaskError("speech_budget", false);
18387
- await trx.raw(
18388
- `INSERT INTO speech_usage(account_id,kind,day,requests,units) VALUES(?,?,(now() AT TIME ZONE 'UTC')::date,1,?)
18389
- ON CONFLICT(account_id,day,kind) DO UPDATE SET requests=speech_usage.requests+1,units=speech_usage.units+excluded.units`,
18390
- [row.accountId, row.kind, current.units]
18774
+ const {
18775
+ rows: [counter]
18776
+ } = await trx.raw(
18777
+ `INSERT INTO speech_usage(account_id,kind,day,requests,units,duration_ms) VALUES(?,?,(now() AT TIME ZONE 'UTC')::date,1,?,?)
18778
+ ON CONFLICT(account_id,day,kind) DO UPDATE SET requests=speech_usage.requests+1,units=speech_usage.units+excluded.units,duration_ms=speech_usage.duration_ms+excluded.duration_ms
18779
+ RETURNING day::text`,
18780
+ [row.accountId, row.kind, current.units, timed ? reservation : 0]
18391
18781
  );
18782
+ if (timed)
18783
+ durationReservation = { day: counter.day, units: reservation };
18392
18784
  });
18393
18785
  const result = await budgetedInference(
18394
18786
  db,
@@ -18420,9 +18812,12 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18420
18812
  const bytes = await provider.synthesize(current.text, signal);
18421
18813
  if (!bytes.length || bytes.length > speechLimits.audioBytes)
18422
18814
  throw new TaskError("speech_audio_limit", false);
18815
+ const durationMs = mp3DurationMs(bytes);
18816
+ if (!durationReservation || durationMs > durationReservation.units)
18817
+ throw new TaskError("speech_budget", false);
18423
18818
  await check();
18424
18819
  signal.throwIfAborted();
18425
- const objectKey = `speech/${row.accountId}/${row.id}/${randomUUID5()}.mp3`;
18820
+ const objectKey = `narration/${row.accountId}/${row.id}/${randomUUID5()}.mp3`;
18426
18821
  await tenant(db, row.accountId, async (trx) => {
18427
18822
  await trx("accounts").where({ id: row.accountId }).forUpdate().first();
18428
18823
  await validate(trx, row, providers);
@@ -18437,13 +18832,35 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18437
18832
  return {
18438
18833
  key: objectKey,
18439
18834
  bytes: bytes.length,
18835
+ durationMs,
18440
18836
  sha256: createHash8("sha256").update(bytes).digest("hex")
18441
18837
  };
18442
18838
  }
18443
18839
  );
18444
18840
  signal.throwIfAborted();
18445
18841
  await taskTransaction(db, row, async (trx) => {
18446
- await validate(trx, row, providers);
18842
+ const source3 = await validate(trx, row, providers);
18843
+ if (row.kind === "speech_synthesize" && "key" in result) {
18844
+ if (!durationReservation || typeof result.durationMs !== "number")
18845
+ throw new TaskError("speech_budget", false);
18846
+ await trx("speech_usage").where({
18847
+ accountId: row.accountId,
18848
+ kind: row.kind,
18849
+ day: durationReservation.day
18850
+ }).decrement(
18851
+ "durationMs",
18852
+ durationReservation.units - result.durationMs
18853
+ );
18854
+ await trx("export_objects").where({ objectKey: result.key, taskId: row.id }).update({
18855
+ speechMemoryId: row.payload.memoryId,
18856
+ speechTextHash: row.payload.textHash,
18857
+ speechCacheKey: row.payload.cacheKey,
18858
+ speechSha256: result.sha256,
18859
+ expiresAt: source3.expiresAt ? trx.raw("?::timestamptz+interval '7 days'", [
18860
+ source3.expiresAt
18861
+ ]) : trx.raw("'infinity'::timestamptz")
18862
+ });
18863
+ }
18447
18864
  return { complete: true, processed: 1, result };
18448
18865
  });
18449
18866
  } catch (error3) {
@@ -18833,11 +19250,16 @@ function exportHandlers(db, store, media) {
18833
19250
  });
18834
19251
  };
18835
19252
  const artifact_cleanup = async (task, signal) => {
18836
- const objects = await tenant(
18837
- db,
18838
- task.accountId,
18839
- (trx) => trx("export_objects").where("expiresAt", "<=", trx.fn.now()).orderBy("objectKey").limit(100)
18840
- );
19253
+ const objects = await tenant(db, task.accountId, async (trx) => {
19254
+ await trx("accounts").where({ id: task.accountId }).forUpdate().first();
19255
+ const expired = await trx("export_objects").where("expiresAt", "<=", trx.fn.now()).orderBy("objectKey").limit(100).forUpdate();
19256
+ if (expired.length)
19257
+ await trx("export_objects").whereIn(
19258
+ "objectKey",
19259
+ expired.map((object) => object.objectKey)
19260
+ ).update({ expiresAt: trx.raw("'-infinity'::timestamptz") });
19261
+ return expired;
19262
+ });
18841
19263
  for (const object of objects) {
18842
19264
  signal.throwIfAborted();
18843
19265
  await store.remove(object.objectKey, signal);
@@ -19105,6 +19527,21 @@ var notebookLifecycleSchema = z16.object({
19105
19527
  fingerprint: z16.string().regex(/^[a-f0-9]{64}$/)
19106
19528
  }).strict();
19107
19529
 
19530
+ // lib/memory/src/system-admin.ts
19531
+ init_define_GROVE_TELEMETRY();
19532
+
19533
+ // lib/shared/src/system-admin.ts
19534
+ init_define_GROVE_TELEMETRY();
19535
+ import { z as z17 } from "zod";
19536
+ var adminChangeSchema = z17.object({
19537
+ accountId: uuidSchema,
19538
+ operationId: uuidSchema,
19539
+ expectedVersion: z17.number().int().min(0),
19540
+ role: z17.enum(["user", "system_admin"]),
19541
+ access: z17.enum(["default", "pro", "unlimited"]),
19542
+ reason: z17.string().trim().min(3).max(300)
19543
+ }).strict();
19544
+
19108
19545
  // lib/memory/src/index.ts
19109
19546
  var missing3 = () => new GroveError("not_found", "Memory not found", 404);
19110
19547
  var forbidden = () => new GroveError(
@@ -20273,11 +20710,33 @@ ${input.query}`.slice(-1e3) : input.query;
20273
20710
  if (created) currentTelemetry().capture("notebook_created");
20274
20711
  return result;
20275
20712
  }
20713
+ connectionState(connection) {
20714
+ return createHmac2("sha256", this.cursorSecret).update(
20715
+ JSON.stringify([
20716
+ "connection-review-v1",
20717
+ connection.accountId,
20718
+ connection.id,
20719
+ connection.clientId,
20720
+ connection.name,
20721
+ [...connection.capabilities].sort(),
20722
+ connection.personal,
20723
+ connection.allProjects,
20724
+ [...connection.projectIds].sort(),
20725
+ connection.expiresAt,
20726
+ connection.revokedAt,
20727
+ connection.authorizedAfter,
20728
+ connection.setup ?? null
20729
+ ])
20730
+ ).digest("hex");
20731
+ }
20276
20732
  async connections(principal) {
20277
20733
  return this.access(
20278
20734
  principal,
20279
20735
  "admin",
20280
- async ({ trx }) => trx("connections").orderBy("createdAt", "desc").limit(100)
20736
+ async ({ trx }) => (await trx("connections").orderBy("createdAt", "desc").limit(100)).map((connection) => ({
20737
+ ...connection,
20738
+ state: this.connectionState(connection)
20739
+ }))
20281
20740
  );
20282
20741
  }
20283
20742
  async grant(principal, input, options = {}) {
@@ -20297,6 +20756,12 @@ ${input.query}`.slice(-1e3) : input.query;
20297
20756
  const old = await trx("connections").where({ id: options.id }).forUpdate().first();
20298
20757
  if (!old)
20299
20758
  throw new GroveError("not_found", "Connection not found", 404);
20759
+ if (options.expectedState && options.expectedState !== this.connectionState(old))
20760
+ throw new GroveError(
20761
+ "connection_conflict",
20762
+ "Connection access changed. Close this dialog, refresh Connections, and review the current permissions before saving.",
20763
+ 409
20764
+ );
20300
20765
  if (old.revokedAt && !old.clientId)
20301
20766
  throw new GroveError(
20302
20767
  "connection_revoked",
@@ -21027,6 +21492,7 @@ var Billing = class {
21027
21492
  ) : [];
21028
21493
  return {
21029
21494
  enabled,
21495
+ units: billingUnits,
21030
21496
  ...state,
21031
21497
  prices,
21032
21498
  proLimits: this.options.proLimits ?? billingLimits.pro
@@ -21286,7 +21752,7 @@ function createBilling(env, service) {
21286
21752
  },
21287
21753
  synthesis: {
21288
21754
  daily: null,
21289
- monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_CHARACTERS`]
21755
+ monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_MS`]
21290
21756
  }
21291
21757
  });
21292
21758
  const prices = {
@@ -21341,7 +21807,7 @@ import {
21341
21807
  import { Upload } from "@aws-sdk/lib-storage";
21342
21808
  var validateKey = (key2) => {
21343
21809
  const uuid2 = "[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}";
21344
- if (!/^exports\/[a-f0-9-]+\/[a-f0-9-]+\/[a-f0-9-]+\.ndjson$/.test(key2) && !new RegExp(`^speech/${uuid2}/${uuid2}/${uuid2}\\.mp3$`).test(key2))
21810
+ if (!/^exports\/[a-f0-9-]+\/[a-f0-9-]+\/[a-f0-9-]+\.ndjson$/.test(key2) && !new RegExp(`^(speech|narration)/${uuid2}/${uuid2}/${uuid2}\\.mp3$`).test(key2))
21345
21811
  throw new Error("invalid_artifact_key");
21346
21812
  return key2;
21347
21813
  };
@@ -21397,7 +21863,7 @@ function s3Artifacts(client, bucket) {
21397
21863
  Bucket: bucket,
21398
21864
  Key: validateKey(key2),
21399
21865
  Body: data,
21400
- ContentType: key2.startsWith("speech/") ? "audio/mpeg" : "application/x-ndjson",
21866
+ ContentType: key2.endsWith(".mp3") ? "audio/mpeg" : "application/x-ndjson",
21401
21867
  CacheControl: "private, no-store"
21402
21868
  };
21403
21869
  if (Buffer.isBuffer(data)) {
@@ -21710,6 +22176,9 @@ async function createRuntime() {
21710
22176
  "SELECT transcription_enabled,read_aloud_enabled,read_aloud_voice_id FROM accounts LIMIT 0"
21711
22177
  );
21712
22178
  await db.raw("SELECT synthesis_profiles FROM speech_configuration LIMIT 0");
22179
+ await db.raw(
22180
+ "SELECT speech_cache_key,speech_text_hash FROM export_objects LIMIT 0"
22181
+ );
21713
22182
  if (env.MEDIA_STORAGE !== "disabled") {
21714
22183
  await db.raw(
21715
22184
  "SELECT status,lease_id,object_key,duration_ms FROM media_objects LIMIT 0"
@@ -21753,42 +22222,23 @@ async function createRuntime() {
21753
22222
  artifacts?.close?.();
21754
22223
  throw error3;
21755
22224
  }
21756
- let speech2 = {};
21757
- if (env.SPEECH_ENABLED) {
21758
- if (!env.OPENAI_API_KEY?.trim()) {
21759
- artifacts?.close?.();
21760
- media?.close?.();
21761
- throw new Error("speech_api_key_required");
21762
- }
21763
- const remote = createOpenAiSpeech({
21764
- apiKey: env.OPENAI_API_KEY,
21765
- voice: env.TTS_VOICE
21766
- });
21767
- speech2 = {
21768
- ...media ? { transcription: remote.transcription } : {},
21769
- ...artifacts ? { synthesis: { reed: remote.synthesis } } : {}
21770
- };
21771
- if (env.MINIMAX_TTS_ENABLED) {
21772
- if (!env.MINIMAX_API_KEY?.trim() || !artifacts) {
21773
- artifacts?.close?.();
21774
- media?.close?.();
21775
- throw new Error("minimax_speech_key_and_storage_required");
21776
- }
21777
- speech2.synthesis = {
21778
- ...speech2.synthesis,
21779
- ...Object.fromEntries(
21780
- Object.entries(miniMaxSpeechVoices).map(([id, voice]) => [
21781
- id,
21782
- {
21783
- ...createMiniMaxSpeech({ apiKey: env.MINIMAX_API_KEY, voice }),
21784
- sampleId: `${id}-v1`
21785
- }
21786
- ])
21787
- )
21788
- };
21789
- }
22225
+ const speechFlags = env.SPEECH_ENABLED && env.FLAGS ? createClient2(env.FLAGS, { staleIfError: 0, staleWhileRevalidate: 0 }) : void 0;
22226
+ let speech2;
22227
+ let billingRuntime;
22228
+ try {
22229
+ speech2 = createSpeechProviders(
22230
+ env,
22231
+ !!media,
22232
+ !!artifacts,
22233
+ speechFlags ? async () => (await speechFlags.evaluate(miniMaxTtsFlagKey, false)).value === true : void 0
22234
+ );
22235
+ billingRuntime = createBilling(env, memories);
22236
+ } catch (error3) {
22237
+ await speechFlags?.shutdown();
22238
+ artifacts?.close?.();
22239
+ media?.close?.();
22240
+ throw error3;
21790
22241
  }
21791
- const billingRuntime = createBilling(env, memories);
21792
22242
  return {
21793
22243
  env,
21794
22244
  db,
@@ -21799,6 +22249,7 @@ async function createRuntime() {
21799
22249
  speech: speech2,
21800
22250
  billing: billingRuntime?.billing,
21801
22251
  close: async () => {
22252
+ await speechFlags?.shutdown();
21802
22253
  await billingRuntime?.close();
21803
22254
  artifacts?.close?.();
21804
22255
  media?.close?.();
@@ -21810,6 +22261,37 @@ async function createRuntime() {
21810
22261
  throw error3;
21811
22262
  }
21812
22263
  }
22264
+ function createSpeechProviders(env, media, artifacts, minimaxEnabled) {
22265
+ if (!env.SPEECH_ENABLED) return {};
22266
+ if (!env.OPENAI_API_KEY?.trim()) throw new Error("speech_api_key_required");
22267
+ const remote = createOpenAiSpeech({
22268
+ apiKey: env.OPENAI_API_KEY,
22269
+ voice: env.TTS_VOICE
22270
+ });
22271
+ const speech2 = {
22272
+ ...media ? { transcription: remote.transcription } : {},
22273
+ ...artifacts ? { synthesis: { reed: remote.synthesis } } : {}
22274
+ };
22275
+ const configured = !!env.MINIMAX_API_KEY?.trim() && artifacts;
22276
+ if (!env.FLAGS && env.MINIMAX_TTS_ENABLED && !configured)
22277
+ throw new Error("minimax_speech_key_and_storage_required");
22278
+ if (configured && (env.FLAGS ? !!minimaxEnabled : env.MINIMAX_TTS_ENABLED)) {
22279
+ speech2.synthesis = {
22280
+ ...speech2.synthesis,
22281
+ ...Object.fromEntries(
22282
+ Object.entries(miniMaxSpeechVoices).map(([id, voice]) => [
22283
+ id,
22284
+ {
22285
+ ...createMiniMaxSpeech({ apiKey: env.MINIMAX_API_KEY, voice }),
22286
+ sampleId: `${id}-v1`,
22287
+ ...env.FLAGS ? { available: minimaxEnabled } : {}
22288
+ }
22289
+ ])
22290
+ )
22291
+ };
22292
+ }
22293
+ return speech2;
22294
+ }
21813
22295
 
21814
22296
  // packages/api/src/mail.ts
21815
22297
  init_define_GROVE_TELEMETRY();
@@ -21934,8 +22416,8 @@ This is a transactional account notification.`,
21934
22416
  // packages/api/src/broker.ts
21935
22417
  init_define_GROVE_TELEMETRY();
21936
22418
  import amqp from "amqplib";
21937
- import { z as z17 } from "zod";
21938
- var envelope = z17.object({ kind: z17.enum(["memory", "email", "task"]), id: z17.uuid() }).strict();
22419
+ import { z as z18 } from "zod";
22420
+ var envelope = z18.object({ kind: z18.enum(["memory", "email", "task"]), id: z18.uuid() }).strict();
21939
22421
  var queueName = (lane) => `grove.jobs.v2.${lane}`;
21940
22422
  var limits = {
21941
22423
  "x-message-ttl": 36e5,