@miniaxolotl/grove-server 1.11.3 → 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: "311212e29921d19c8f58b2ca5382ec0790867293", version: "1.11.3", 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))) {
@@ -4516,18 +4778,35 @@ var serverSchema = z.object({
4516
4778
  STRIPE_PORTAL_CONFIGURATION_ID: z.string().startsWith("bpc_").optional(),
4517
4779
  STRIPE_PRO_MONTHLY_PRICE_ID: z.string().startsWith("price_").optional(),
4518
4780
  STRIPE_PRO_YEARLY_PRICE_ID: z.string().startsWith("price_").optional(),
4519
- BILLING_FREE_GENERATION_DAILY: allowance(10),
4520
- BILLING_FREE_GENERATION_MONTHLY: allowance(100),
4521
- BILLING_PRO_GENERATION_DAILY: allowance(200),
4522
- BILLING_PRO_GENERATION_MONTHLY: allowance(2e3),
4523
- BILLING_FREE_RESEARCH_DAILY: allowance(3),
4524
- BILLING_FREE_RESEARCH_MONTHLY: allowance(10),
4525
- BILLING_PRO_RESEARCH_DAILY: allowance(20),
4526
- BILLING_PRO_RESEARCH_MONTHLY: allowance(200),
4527
- BILLING_FREE_TRANSCRIPTION_MONTHLY_MS: allowance(6e5),
4528
- BILLING_PRO_TRANSCRIPTION_MONTHLY_MS: allowance(72e5),
4529
- BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: allowance(1e4),
4530
- 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(),
4531
4810
  EMBEDDING_MODE: z.enum(["local", "remote", "disabled"]).optional(),
4532
4811
  EMBEDDING_CACHE: z.string().default("./data/models"),
4533
4812
  EMBEDDING_URL: z.string().optional(),
@@ -4610,6 +4889,15 @@ var serverSchema = z.object({
4610
4889
  SHARE_LINK_KEY: z.string().regex(/^[0-9a-f]{64}$/i).optional()
4611
4890
  });
4612
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
+ }
4613
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))
4614
4902
  ctx.addIssue({
4615
4903
  code: "custom",
@@ -4626,6 +4914,18 @@ function readServerEnvironment(env = process.env) {
4626
4914
  );
4627
4915
  }
4628
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
+
4629
4929
  // lib/memory/src/index.ts
4630
4930
  init_define_GROVE_TELEMETRY();
4631
4931
  import {
@@ -4655,9 +4955,8 @@ var policy = {
4655
4955
  init_define_GROVE_TELEMETRY();
4656
4956
  import { createHash as createHash2 } from "node:crypto";
4657
4957
 
4658
- // lib/ai/src/speech.ts
4958
+ // lib/ai/src/audio-duration.ts
4659
4959
  init_define_GROVE_TELEMETRY();
4660
- import { createHash } from "node:crypto";
4661
4960
 
4662
4961
  // lib/shared/src/speech.ts
4663
4962
  init_define_GROVE_TELEMETRY();
@@ -11811,14 +12110,6 @@ function defaultOnError(left, right) {
11811
12110
  }
11812
12111
  }
11813
12112
 
11814
- // lib/shared/src/speech-voices.ts
11815
- init_define_GROVE_TELEMETRY();
11816
- var speechVoiceIds = ["reed", "willow", "cedar", "brook"];
11817
- var defaultSpeechVoice = "reed";
11818
- function isSpeechVoice(value) {
11819
- return speechVoiceIds.some((id) => id === value);
11820
- }
11821
-
11822
12113
  // lib/shared/src/speech.ts
11823
12114
  var speechRequestSchema = z2.object({
11824
12115
  id: z2.uuid(),
@@ -11833,7 +12124,10 @@ var speechLimits = {
11833
12124
  audioBytes: 3 * 1024 * 1024,
11834
12125
  dailyRequests: 20,
11835
12126
  dailyAudioMs: 6e5,
11836
- 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
11837
12131
  };
11838
12132
  function speechText(content3) {
11839
12133
  const tree = fromMarkdown(content3);
@@ -11871,7 +12165,43 @@ function speechText(content3) {
11871
12165
  return text3(tree).replace(/\n[ \t]*\n(?:[ \t]*\n)+/g, "\n\n").trim();
11872
12166
  }
11873
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
+
11874
12202
  // lib/ai/src/speech.ts
12203
+ init_define_GROVE_TELEMETRY();
12204
+ import { createHash } from "node:crypto";
11875
12205
  async function requestSpeech(config, url, body, parent, maximum, contentType = "application/json") {
11876
12206
  const signal = AbortSignal.any([
11877
12207
  parent,
@@ -15482,27 +15812,6 @@ async function runAssistanceJob(db, providers, dailyLimit, job, resolveProfiles,
15482
15812
 
15483
15813
  // lib/memory/src/billing-quotas.ts
15484
15814
  init_define_GROVE_TELEMETRY();
15485
-
15486
- // lib/shared/src/billing.ts
15487
- init_define_GROVE_TELEMETRY();
15488
- var billingFlagKey = "billing-enabled";
15489
- var billingPriceFlagKey = "billing-pro-monthly-usd";
15490
- var billingLimits = {
15491
- free: {
15492
- generation: { daily: 10, monthly: 100 },
15493
- research: { daily: 3, monthly: 10 },
15494
- transcription: { daily: null, monthly: 6e5 },
15495
- synthesis: { daily: null, monthly: 1e4 }
15496
- },
15497
- pro: {
15498
- generation: { daily: 200, monthly: 2e3 },
15499
- research: { daily: 20, monthly: 200 },
15500
- transcription: { daily: null, monthly: 72e5 },
15501
- synthesis: { daily: null, monthly: 2e5 }
15502
- }
15503
- };
15504
-
15505
- // lib/memory/src/billing-quotas.ts
15506
15815
  var configurations = /* @__PURE__ */ new WeakMap();
15507
15816
  function configureBillingQuotas(db, configuration) {
15508
15817
  configurations.set(db, configuration);
@@ -15511,13 +15820,16 @@ async function billingUsage(db, trx, accountId) {
15511
15820
  const config = configurations.get(db);
15512
15821
  if (!config) return null;
15513
15822
  const account = await trx("accounts").where({ id: accountId }).first("clerkSubject");
15514
- 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;
15515
15827
  const paid = await trx("billing_subscriptions").where({ accountId }).whereIn("status", ["active", "trialing"]).where((query) => {
15516
15828
  query.whereIn("priceId", config.priceIds);
15517
15829
  if (config.productId) query.orWhere({ productId: config.productId });
15518
15830
  }).where("periodEnd", ">", trx.fn.now()).first("id");
15519
- const plan = paid ? "pro" : "free";
15520
- const limits2 = (config.limits ?? billingLimits)[plan];
15831
+ const plan = override ?? (paid ? "pro" : "free");
15832
+ const limits2 = (config.limits ?? billingLimits)[plan === "unlimited" ? "pro" : plan];
15521
15833
  const {
15522
15834
  rows: [clock]
15523
15835
  } = await trx.raw(`SELECT
@@ -15528,7 +15840,7 @@ async function billingUsage(db, trx, accountId) {
15528
15840
  const metrics2 = {};
15529
15841
  for (const metric of Object.keys(limits2)) {
15530
15842
  const table = metric === "generation" ? "inference_usage" : metric === "research" ? "research_account_usage" : "speech_usage";
15531
- const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : "units";
15843
+ const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : metric === "synthesis" ? "durationMs" : "units";
15532
15844
  const query = trx(table).where({ accountId }).whereBetween("day", [clock.month, clock.today]);
15533
15845
  if (metric === "generation") query.where({ role: "generation" });
15534
15846
  if (metric === "transcription" || metric === "synthesis")
@@ -15544,8 +15856,8 @@ async function billingUsage(db, trx, accountId) {
15544
15856
  metrics2[metric] = {
15545
15857
  today: Number(usage.today),
15546
15858
  month: Number(usage.month),
15547
- dailyLimit: limits2[metric].daily,
15548
- monthlyLimit: limits2[metric].monthly
15859
+ dailyLimit: plan === "unlimited" ? null : limits2[metric].daily,
15860
+ monthlyLimit: plan === "unlimited" ? null : limits2[metric].monthly
15549
15861
  };
15550
15862
  }
15551
15863
  return {
@@ -15555,12 +15867,6 @@ async function billingUsage(db, trx, accountId) {
15555
15867
  metrics: metrics2
15556
15868
  };
15557
15869
  }
15558
- async function billingAllows(db, trx, accountId, metric, units = 1) {
15559
- const snapshot = await billingUsage(db, trx, accountId);
15560
- if (!snapshot) return true;
15561
- const usage = snapshot.metrics[metric];
15562
- return (usage.dailyLimit === null || usage.today + units <= usage.dailyLimit) && usage.month + units <= usage.monthlyLimit;
15563
- }
15564
15870
 
15565
15871
  // lib/memory/src/processing.ts
15566
15872
  var briefTarget = (scope) => `${scope.projectId ?? "personal"}${scope.taskId ? `:task:${scope.taskId}` : ""}`;
@@ -15758,10 +16064,15 @@ async function reserve(db, trx, accountId, role, limit) {
15758
16064
  await trx.raw("SELECT pg_advisory_xact_lock(hashtextextended(?, 6))", [
15759
16065
  accountId
15760
16066
  ]);
15761
- const result = await trx("inference_usage").whereRaw("day = (now() AT TIME ZONE 'UTC')::date").sum("requests as count").first();
15762
- if (Number(result?.count ?? 0) >= limit) return false;
15763
- if (role === "generation" && !await billingAllows(db, trx, accountId, "generation"))
15764
- 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;
15765
16076
  await trx.raw(
15766
16077
  `INSERT INTO inference_usage(account_id, role, day, requests) VALUES (?, ?, (now() AT TIME ZONE 'UTC')::date, 1)
15767
16078
  ON CONFLICT(account_id, day, role) DO UPDATE SET requests = inference_usage.requests + 1`,
@@ -16229,11 +16540,21 @@ var askToolIds = Object.keys(askToolCatalog);
16229
16540
 
16230
16541
  // lib/shared/src/conversations.ts
16231
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
+ );
16232
16547
  var toolSettingsSchema = z12.object({
16233
16548
  tools: askToolsSchema,
16234
16549
  expectedVersion: z12.number().int().nonnegative(),
16235
- saveDefault: z12.boolean().optional()
16236
- }).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
+ );
16237
16558
  var researchRequestSchema = z12.object({
16238
16559
  provider: z12.enum(["exa", "tavily"]),
16239
16560
  query: z12.string().max(500),
@@ -16710,6 +17031,14 @@ var summary = (row) => ({
16710
17031
  tools: row.tools ?? defaultAskTools,
16711
17032
  toolsVersion: row.toolsVersion ?? 0
16712
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
+ }
16713
17042
  var Conversations = class {
16714
17043
  constructor(service, present, revise) {
16715
17044
  this.service = service;
@@ -16772,11 +17101,23 @@ var Conversations = class {
16772
17101
  tools: JSON.stringify(row.tools),
16773
17102
  toolsVersion: row.toolsVersion
16774
17103
  });
16775
- if (input.saveDefault)
16776
- await trx("accounts").where({ id: account.id }).update({ askTools: JSON.stringify(row.tools) });
16777
- 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
+ };
16778
17109
  });
16779
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
+ }
16780
17121
  async get(principal, id) {
16781
17122
  return this.service.access(principal, "admin", async ({ trx }) => {
16782
17123
  const row = await trx("conversations").where({ id }).first();
@@ -17320,19 +17661,20 @@ var Conversations = class {
17320
17661
  );
17321
17662
  if (previous2) return { cached: previous2.sources };
17322
17663
  if (runs.length >= 6) return { limited: true };
17323
- if (!await billingAllows(
17664
+ const billing2 = await billingUsage(
17324
17665
  this.service.db,
17325
17666
  trx,
17326
- principal.accountId,
17327
- "research"
17328
- ))
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))
17329
17671
  return { limited: true };
17330
17672
  const { rows } = await trx.raw(
17331
17673
  "SELECT grove_research_reserve(?,?,?,?) AS admitted",
17332
17674
  [
17333
17675
  request2.provider,
17334
17676
  operation,
17335
- this.service.researchLimits.dailyCalls,
17677
+ usage ? usage.dailyLimit : this.service.researchLimits.dailyCalls,
17336
17678
  this.service.researchLimits.monthlyMicrodollars
17337
17679
  ]
17338
17680
  );
@@ -18283,12 +18625,21 @@ var keys = (kind) => kind === "speech_transcribe" ? {
18283
18625
  version: "readAloudVersion",
18284
18626
  provider: "synthesis"
18285
18627
  };
18628
+ var unavailable2 = () => new GroveError("speech_unavailable", "Speech is not configured", 503);
18286
18629
  var changed = () => new GroveError(
18287
18630
  "speech_changed",
18288
18631
  "The note, transcript or speech settings changed. Start again.",
18289
18632
  409
18290
18633
  );
18291
- 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
+ }
18292
18643
  function configuredProfile(configuration, kind, voiceId) {
18293
18644
  if (kind === "speech_transcribe") return configuration?.transcription;
18294
18645
  return configuration?.synthesis === synthesisProtocol && isSpeechVoice(voiceId) ? configuration.synthesisProfiles[voiceId] : void 0;
@@ -18326,6 +18677,8 @@ async function source2(trx, memoryId, version2, mediaId) {
18326
18677
  return {
18327
18678
  object: void 0,
18328
18679
  text: text3,
18680
+ textHash: createHash8("sha256").update(note.content).digest("hex"),
18681
+ expiresAt: note.expiresAt,
18329
18682
  units: text3.length,
18330
18683
  transcriptVersion: void 0
18331
18684
  };
@@ -18339,6 +18692,8 @@ async function validate(trx, row, providers) {
18339
18692
  if (!payload.profile || configuredProfile(configuration, row.kind, payload.voiceId) !== payload.profile || selectedProvider(providers, row.kind, payload.voiceId)?.profile !== payload.profile)
18340
18693
  throw changed();
18341
18694
  const control = await trx("processing_control").first("epoch");
18695
+ if (row.kind === "speech_synthesize" && !await synthesisAvailable(providers.synthesis?.[payload.voiceId]))
18696
+ throw unavailable2();
18342
18697
  const session = await trx.raw(
18343
18698
  "SELECT grove_speech_session_active(?::uuid) AS active",
18344
18699
  [row.id]
@@ -18354,6 +18709,8 @@ async function validate(trx, row, providers) {
18354
18709
  );
18355
18710
  if (current.object && (current.object.sha256 !== payload.sha256 || current.transcriptVersion !== payload.transcriptVersion))
18356
18711
  throw changed();
18712
+ if (row.kind === "speech_synthesize" && current.textHash !== payload.textHash)
18713
+ throw changed();
18357
18714
  return current;
18358
18715
  }
18359
18716
  function speechHandlers(service, providers, store, readSource, db = service.db, concurrency = 2) {
@@ -18372,6 +18729,7 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18372
18729
  return validate(trx, row, providers);
18373
18730
  });
18374
18731
  let slot = false;
18732
+ let durationReservation;
18375
18733
  const watcher = (async () => {
18376
18734
  try {
18377
18735
  while (!monitoring.signal.aborted) {
@@ -18398,19 +18756,31 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18398
18756
  await validate(trx, row, providers);
18399
18757
  const usage = await trx("speech_usage").where({ kind: row.kind }).whereRaw("day=(now() AT TIME ZONE 'UTC')::date").first();
18400
18758
  const limit = row.kind === "speech_transcribe" ? speechLimits.dailyAudioMs : speechLimits.dailyCharacters;
18401
- if ((usage?.requests ?? 0) >= speechLimits.dailyRequests || (usage?.units ?? 0) + current.units > limit || !await billingAllows(
18402
- db,
18403
- trx,
18404
- row.accountId,
18405
- key2.provider,
18406
- current.units
18407
- ))
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))
18408
18773
  throw new TaskError("speech_budget", false);
18409
- await trx.raw(
18410
- `INSERT INTO speech_usage(account_id,kind,day,requests,units) VALUES(?,?,(now() AT TIME ZONE 'UTC')::date,1,?)
18411
- ON CONFLICT(account_id,day,kind) DO UPDATE SET requests=speech_usage.requests+1,units=speech_usage.units+excluded.units`,
18412
- [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]
18413
18781
  );
18782
+ if (timed)
18783
+ durationReservation = { day: counter.day, units: reservation };
18414
18784
  });
18415
18785
  const result = await budgetedInference(
18416
18786
  db,
@@ -18442,9 +18812,12 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18442
18812
  const bytes = await provider.synthesize(current.text, signal);
18443
18813
  if (!bytes.length || bytes.length > speechLimits.audioBytes)
18444
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);
18445
18818
  await check();
18446
18819
  signal.throwIfAborted();
18447
- const objectKey = `speech/${row.accountId}/${row.id}/${randomUUID5()}.mp3`;
18820
+ const objectKey = `narration/${row.accountId}/${row.id}/${randomUUID5()}.mp3`;
18448
18821
  await tenant(db, row.accountId, async (trx) => {
18449
18822
  await trx("accounts").where({ id: row.accountId }).forUpdate().first();
18450
18823
  await validate(trx, row, providers);
@@ -18459,13 +18832,35 @@ function speechHandlers(service, providers, store, readSource, db = service.db,
18459
18832
  return {
18460
18833
  key: objectKey,
18461
18834
  bytes: bytes.length,
18835
+ durationMs,
18462
18836
  sha256: createHash8("sha256").update(bytes).digest("hex")
18463
18837
  };
18464
18838
  }
18465
18839
  );
18466
18840
  signal.throwIfAborted();
18467
18841
  await taskTransaction(db, row, async (trx) => {
18468
- 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
+ }
18469
18864
  return { complete: true, processed: 1, result };
18470
18865
  });
18471
18866
  } catch (error3) {
@@ -18855,11 +19250,16 @@ function exportHandlers(db, store, media) {
18855
19250
  });
18856
19251
  };
18857
19252
  const artifact_cleanup = async (task, signal) => {
18858
- const objects = await tenant(
18859
- db,
18860
- task.accountId,
18861
- (trx) => trx("export_objects").where("expiresAt", "<=", trx.fn.now()).orderBy("objectKey").limit(100)
18862
- );
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
+ });
18863
19263
  for (const object of objects) {
18864
19264
  signal.throwIfAborted();
18865
19265
  await store.remove(object.objectKey, signal);
@@ -19127,6 +19527,21 @@ var notebookLifecycleSchema = z16.object({
19127
19527
  fingerprint: z16.string().regex(/^[a-f0-9]{64}$/)
19128
19528
  }).strict();
19129
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
+
19130
19545
  // lib/memory/src/index.ts
19131
19546
  var missing3 = () => new GroveError("not_found", "Memory not found", 404);
19132
19547
  var forbidden = () => new GroveError(
@@ -21077,6 +21492,7 @@ var Billing = class {
21077
21492
  ) : [];
21078
21493
  return {
21079
21494
  enabled,
21495
+ units: billingUnits,
21080
21496
  ...state,
21081
21497
  prices,
21082
21498
  proLimits: this.options.proLimits ?? billingLimits.pro
@@ -21336,7 +21752,7 @@ function createBilling(env, service) {
21336
21752
  },
21337
21753
  synthesis: {
21338
21754
  daily: null,
21339
- monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_CHARACTERS`]
21755
+ monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_MS`]
21340
21756
  }
21341
21757
  });
21342
21758
  const prices = {
@@ -21391,7 +21807,7 @@ import {
21391
21807
  import { Upload } from "@aws-sdk/lib-storage";
21392
21808
  var validateKey = (key2) => {
21393
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}";
21394
- 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))
21395
21811
  throw new Error("invalid_artifact_key");
21396
21812
  return key2;
21397
21813
  };
@@ -21447,7 +21863,7 @@ function s3Artifacts(client, bucket) {
21447
21863
  Bucket: bucket,
21448
21864
  Key: validateKey(key2),
21449
21865
  Body: data,
21450
- ContentType: key2.startsWith("speech/") ? "audio/mpeg" : "application/x-ndjson",
21866
+ ContentType: key2.endsWith(".mp3") ? "audio/mpeg" : "application/x-ndjson",
21451
21867
  CacheControl: "private, no-store"
21452
21868
  };
21453
21869
  if (Buffer.isBuffer(data)) {
@@ -21760,6 +22176,9 @@ async function createRuntime() {
21760
22176
  "SELECT transcription_enabled,read_aloud_enabled,read_aloud_voice_id FROM accounts LIMIT 0"
21761
22177
  );
21762
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
+ );
21763
22182
  if (env.MEDIA_STORAGE !== "disabled") {
21764
22183
  await db.raw(
21765
22184
  "SELECT status,lease_id,object_key,duration_ms FROM media_objects LIMIT 0"
@@ -21803,42 +22222,23 @@ async function createRuntime() {
21803
22222
  artifacts?.close?.();
21804
22223
  throw error3;
21805
22224
  }
21806
- let speech2 = {};
21807
- if (env.SPEECH_ENABLED) {
21808
- if (!env.OPENAI_API_KEY?.trim()) {
21809
- artifacts?.close?.();
21810
- media?.close?.();
21811
- throw new Error("speech_api_key_required");
21812
- }
21813
- const remote = createOpenAiSpeech({
21814
- apiKey: env.OPENAI_API_KEY,
21815
- voice: env.TTS_VOICE
21816
- });
21817
- speech2 = {
21818
- ...media ? { transcription: remote.transcription } : {},
21819
- ...artifacts ? { synthesis: { reed: remote.synthesis } } : {}
21820
- };
21821
- if (env.MINIMAX_TTS_ENABLED) {
21822
- if (!env.MINIMAX_API_KEY?.trim() || !artifacts) {
21823
- artifacts?.close?.();
21824
- media?.close?.();
21825
- throw new Error("minimax_speech_key_and_storage_required");
21826
- }
21827
- speech2.synthesis = {
21828
- ...speech2.synthesis,
21829
- ...Object.fromEntries(
21830
- Object.entries(miniMaxSpeechVoices).map(([id, voice]) => [
21831
- id,
21832
- {
21833
- ...createMiniMaxSpeech({ apiKey: env.MINIMAX_API_KEY, voice }),
21834
- sampleId: `${id}-v1`
21835
- }
21836
- ])
21837
- )
21838
- };
21839
- }
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;
21840
22241
  }
21841
- const billingRuntime = createBilling(env, memories);
21842
22242
  return {
21843
22243
  env,
21844
22244
  db,
@@ -21849,6 +22249,7 @@ async function createRuntime() {
21849
22249
  speech: speech2,
21850
22250
  billing: billingRuntime?.billing,
21851
22251
  close: async () => {
22252
+ await speechFlags?.shutdown();
21852
22253
  await billingRuntime?.close();
21853
22254
  artifacts?.close?.();
21854
22255
  media?.close?.();
@@ -21860,6 +22261,37 @@ async function createRuntime() {
21860
22261
  throw error3;
21861
22262
  }
21862
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
+ }
21863
22295
 
21864
22296
  // packages/api/src/mail.ts
21865
22297
  init_define_GROVE_TELEMETRY();
@@ -21984,8 +22416,8 @@ This is a transactional account notification.`,
21984
22416
  // packages/api/src/broker.ts
21985
22417
  init_define_GROVE_TELEMETRY();
21986
22418
  import amqp from "amqplib";
21987
- import { z as z17 } from "zod";
21988
- 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();
21989
22421
  var queueName = (lane) => `grove.jobs.v2.${lane}`;
21990
22422
  var limits = {
21991
22423
  "x-message-ttl": 36e5,