@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/server.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
 
@@ -2005,6 +2005,237 @@ var billing = {
2005
2005
  }
2006
2006
  };
2007
2007
 
2008
+ // lib/database/src/system-admin-migration.ts
2009
+ init_define_GROVE_TELEMETRY();
2010
+ var systemAdministration = {
2011
+ name: "20261025_025_system_administration",
2012
+ async up(db) {
2013
+ await db.raw(`
2014
+ CREATE TABLE account_administration (
2015
+ account_id uuid PRIMARY KEY REFERENCES public.accounts(id),
2016
+ role text NOT NULL DEFAULT 'user' CHECK (role IN ('user','system_admin')),
2017
+ access text NOT NULL DEFAULT 'default' CHECK (access IN ('default','pro','unlimited')),
2018
+ version integer NOT NULL DEFAULT 0 CHECK (version >= 0)
2019
+ );
2020
+ ALTER TABLE account_administration ENABLE ROW LEVEL SECURITY;
2021
+ CREATE POLICY tenant ON account_administration FOR SELECT
2022
+ USING (account_id = NULLIF(current_setting('grove.account_id',true),'')::uuid);
2023
+ CREATE TABLE system_admin_audit (
2024
+ id uuid PRIMARY KEY, actor_id uuid REFERENCES public.accounts(id),
2025
+ account_id uuid NOT NULL REFERENCES public.accounts(id),
2026
+ kind text NOT NULL CHECK (kind IN ('change','bootstrap')),
2027
+ reason text NOT NULL CHECK (length(reason) BETWEEN 3 AND 300),
2028
+ before jsonb NOT NULL, after jsonb NOT NULL,
2029
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()
2030
+ );
2031
+ CREATE INDEX system_admin_audit_recent ON system_admin_audit(created_at DESC, id);
2032
+ ALTER TABLE system_admin_audit ENABLE ROW LEVEL SECURITY;
2033
+ REVOKE ALL ON account_administration,system_admin_audit FROM PUBLIC,grove_runtime,grove_worker;
2034
+ GRANT SELECT ON account_administration TO grove_runtime,grove_worker;
2035
+
2036
+ CREATE FUNCTION grove_admin_state(target uuid) RETURNS jsonb
2037
+ LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2038
+ SELECT jsonb_build_object('accountId',a.id,'subject',a.clerk_subject,
2039
+ 'status',a.status,'createdAt',a.created_at,
2040
+ 'role',COALESCE(s.role,'user'),'access',COALESCE(s.access,'default'),
2041
+ 'version',COALESCE(s.version,0))
2042
+ FROM public.accounts a LEFT JOIN public.account_administration s ON s.account_id=a.id
2043
+ WHERE a.id=target
2044
+ $$;
2045
+ CREATE FUNCTION grove_admin_guard() RETURNS uuid
2046
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2047
+ DECLARE actor uuid := NULLIF(current_setting('grove.account_id',true),'')::uuid;
2048
+ BEGIN
2049
+ -- A fresh role snapshot after the lock wait fences concurrent revocation.
2050
+ PERFORM pg_advisory_xact_lock(68142025);
2051
+ IF NOT EXISTS(SELECT 1 FROM public.account_administration s
2052
+ JOIN public.accounts a ON a.id=s.account_id
2053
+ WHERE s.account_id=actor AND s.role='system_admin' AND a.status='active') THEN
2054
+ RAISE EXCEPTION 'system_admin_required' USING ERRCODE='GA001';
2055
+ END IF;
2056
+ RETURN actor;
2057
+ END $$;
2058
+ CREATE FUNCTION grove_admin_accounts(wanted text[] DEFAULT NULL) RETURNS jsonb
2059
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2060
+ DECLARE result jsonb;
2061
+ BEGIN
2062
+ PERFORM public.grove_admin_guard();
2063
+ SELECT COALESCE(jsonb_agg(public.grove_admin_state(a.id) ORDER BY a.created_at DESC,a.id),'[]'::jsonb)
2064
+ INTO result FROM (SELECT id,created_at FROM public.accounts
2065
+ WHERE status IN ('active','disabled') AND (wanted IS NULL OR clerk_subject=ANY(wanted))
2066
+ ORDER BY created_at DESC,id LIMIT 30) a;
2067
+ RETURN result;
2068
+ END $$;
2069
+ CREATE FUNCTION grove_admin_change(target uuid, operation uuid, expected integer,
2070
+ wanted_role text, wanted_access text, explanation text) RETURNS jsonb
2071
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2072
+ DECLARE actor uuid; previous public.system_admin_audit; old jsonb; result jsonb;
2073
+ BEGIN
2074
+ actor := public.grove_admin_guard();
2075
+ IF wanted_role NOT IN ('user','system_admin') OR wanted_role IS NULL
2076
+ OR wanted_access NOT IN ('default','pro','unlimited') OR wanted_access IS NULL
2077
+ OR explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300
2078
+ OR expected IS NULL OR expected < 0 OR operation IS NULL THEN
2079
+ RAISE EXCEPTION 'invalid_request' USING ERRCODE='GA002';
2080
+ END IF;
2081
+ SELECT * INTO previous FROM public.system_admin_audit WHERE id=operation;
2082
+ IF FOUND THEN
2083
+ IF previous.actor_id IS DISTINCT FROM actor OR previous.account_id IS DISTINCT FROM target
2084
+ OR previous.reason IS DISTINCT FROM explanation
2085
+ OR previous.after->>'role' IS DISTINCT FROM wanted_role
2086
+ OR previous.after->>'access' IS DISTINCT FROM wanted_access
2087
+ OR (previous.before->>'version')::integer IS DISTINCT FROM expected THEN
2088
+ RAISE EXCEPTION 'operation_conflict' USING ERRCODE='GA003';
2089
+ END IF;
2090
+ RETURN previous.after;
2091
+ END IF;
2092
+ old := public.grove_admin_state(target);
2093
+ IF old IS NULL OR old->>'status' <> 'active' THEN
2094
+ RAISE EXCEPTION 'account_unavailable' USING ERRCODE='GA004';
2095
+ END IF;
2096
+ IF (old->>'version')::integer <> expected THEN
2097
+ RAISE EXCEPTION 'admin_version_conflict' USING ERRCODE='GA005';
2098
+ END IF;
2099
+ IF old->>'role'='system_admin' AND wanted_role='user' AND NOT EXISTS(
2100
+ SELECT 1 FROM public.account_administration s JOIN public.accounts a ON a.id=s.account_id
2101
+ WHERE s.role='system_admin' AND a.status='active' AND s.account_id<>target) THEN
2102
+ RAISE EXCEPTION 'last_system_admin' USING ERRCODE='GA006';
2103
+ END IF;
2104
+ INSERT INTO public.account_administration(account_id,role,access,version)
2105
+ VALUES(target,wanted_role,wanted_access,expected+1)
2106
+ ON CONFLICT(account_id) DO UPDATE SET role=EXCLUDED.role,access=EXCLUDED.access,version=EXCLUDED.version;
2107
+ result := public.grove_admin_state(target);
2108
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
2109
+ VALUES(operation,actor,target,'change',explanation,old,result);
2110
+ RETURN result;
2111
+ END $$;
2112
+ CREATE FUNCTION grove_admin_audit() RETURNS jsonb
2113
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2114
+ DECLARE result jsonb;
2115
+ BEGIN
2116
+ PERFORM public.grove_admin_guard();
2117
+ SELECT COALESCE(jsonb_agg(jsonb_build_object('id',id,'actorId',actor_id,
2118
+ 'accountId',account_id,'kind',kind,'reason',reason,'before',before,'after',after,
2119
+ 'createdAt',created_at) ORDER BY created_at DESC,id),'[]'::jsonb)
2120
+ INTO result FROM (SELECT * FROM public.system_admin_audit ORDER BY created_at DESC,id LIMIT 50) recent;
2121
+ RETURN result;
2122
+ END $$;
2123
+ CREATE FUNCTION grove_bootstrap_system_admin(subject text, explanation text) RETURNS uuid
2124
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
2125
+ DECLARE target uuid; old jsonb;
2126
+ BEGIN
2127
+ PERFORM pg_advisory_xact_lock(68142025);
2128
+ SELECT id INTO target FROM public.accounts WHERE clerk_subject=subject AND status='active';
2129
+ IF target IS NULL THEN RAISE EXCEPTION 'account_unavailable'; END IF;
2130
+ IF explanation IS NULL OR length(trim(explanation)) NOT BETWEEN 3 AND 300 THEN
2131
+ RAISE EXCEPTION 'invalid_request';
2132
+ END IF;
2133
+ IF EXISTS(SELECT 1 FROM public.account_administration WHERE account_id=target AND role='system_admin') THEN RETURN target; END IF;
2134
+ IF EXISTS(SELECT 1 FROM public.account_administration WHERE role='system_admin') THEN
2135
+ RAISE EXCEPTION 'already_bootstrapped';
2136
+ END IF;
2137
+ old := public.grove_admin_state(target);
2138
+ INSERT INTO public.account_administration(account_id,role,version) VALUES(target,'system_admin',1)
2139
+ ON CONFLICT(account_id) DO UPDATE SET role='system_admin',version=public.account_administration.version+1;
2140
+ INSERT INTO public.system_admin_audit(id,actor_id,account_id,kind,reason,before,after)
2141
+ VALUES(gen_random_uuid(),NULL,target,'bootstrap',explanation,old,public.grove_admin_state(target));
2142
+ RETURN target;
2143
+ END $$;
2144
+ REVOKE ALL ON FUNCTION grove_admin_state(uuid),grove_admin_guard(),grove_admin_accounts(text[]),
2145
+ grove_admin_change(uuid,uuid,integer,text,text,text),grove_admin_audit(),
2146
+ grove_bootstrap_system_admin(text,text) FROM PUBLIC,grove_runtime,grove_worker;
2147
+ GRANT EXECUTE ON FUNCTION grove_admin_accounts(text[]),grove_admin_change(uuid,uuid,integer,text,text,text),
2148
+ grove_admin_audit() TO grove_runtime;
2149
+ `);
2150
+ },
2151
+ async down() {
2152
+ throw new Error("Use a forward migration");
2153
+ }
2154
+ };
2155
+
2156
+ // lib/database/src/speech-cache-migration.ts
2157
+ init_define_GROVE_TELEMETRY();
2158
+ var speechCache = {
2159
+ name: "20261024_024_speech_cache",
2160
+ async up(db) {
2161
+ await db.raw(`
2162
+ -- Cache metadata belongs to the tracked object, not its short-lived request.
2163
+ -- Existing speech/ objects retain their original deadlines and lifecycle.
2164
+ ALTER TABLE export_objects
2165
+ ADD COLUMN speech_memory_id uuid,
2166
+ ADD COLUMN speech_text_hash text,
2167
+ ADD COLUMN speech_cache_key text,
2168
+ ADD COLUMN speech_sha256 text,
2169
+ ADD CONSTRAINT export_objects_speech_memory FOREIGN KEY(account_id,speech_memory_id)
2170
+ REFERENCES memories(account_id,id),
2171
+ ADD CONSTRAINT export_objects_speech_metadata CHECK (
2172
+ (speech_memory_id IS NULL AND speech_text_hash IS NULL AND speech_cache_key IS NULL AND speech_sha256 IS NULL)
2173
+ 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
2174
+ AND speech_text_hash ~ '^[a-f0-9]{64}$' AND speech_cache_key ~ '^[a-f0-9]{64}$'
2175
+ AND speech_sha256 ~ '^[a-f0-9]{64}$' AND object_key LIKE 'narration/%'));
2176
+ CREATE INDEX export_objects_speech_cache ON export_objects(account_id,speech_cache_key)
2177
+ WHERE speech_cache_key IS NOT NULL;
2178
+ CREATE INDEX export_objects_speech_memory ON export_objects(account_id,speech_memory_id)
2179
+ WHERE speech_memory_id IS NOT NULL;
2180
+
2181
+ -- Every write path (including Undo, imports and API edits) gets the same
2182
+ -- retention transition. Expired objects can already be claimed for removal:
2183
+ -- never revive one, even if its bytes have not been physically deleted yet.
2184
+ CREATE FUNCTION grove_speech_cache_text() RETURNS trigger LANGUAGE plpgsql
2185
+ SET search_path=pg_catalog,public,pg_temp AS $$
2186
+ BEGIN
2187
+ UPDATE export_objects SET expires_at=CASE
2188
+ WHEN NEW.status='active' AND NEW.deleted_at IS NULL
2189
+ AND (NEW.expires_at IS NULL OR NEW.expires_at>now())
2190
+ AND speech_text_hash=encode(sha256(convert_to(NEW.content,'UTF8')),'hex')
2191
+ THEN coalesce(NEW.expires_at+interval '7 days','infinity'::timestamptz)
2192
+ ELSE least(expires_at,now()+interval '7 days') END
2193
+ WHERE account_id=NEW.account_id AND speech_memory_id=NEW.id AND expires_at>now();
2194
+ RETURN NULL;
2195
+ END $$;
2196
+ REVOKE ALL ON FUNCTION grove_speech_cache_text() FROM PUBLIC;
2197
+ CREATE TRIGGER speech_cache_text AFTER UPDATE OF content,status,deleted_at,expires_at ON memories
2198
+ FOR EACH ROW EXECUTE FUNCTION grove_speech_cache_text();
2199
+ `);
2200
+ },
2201
+ async down() {
2202
+ throw new Error("Use a forward migration");
2203
+ }
2204
+ };
2205
+
2206
+ // lib/database/src/speech-duration-migration.ts
2207
+ init_define_GROVE_TELEMETRY();
2208
+ var speechDuration = {
2209
+ name: "20261025_026_speech_duration",
2210
+ async up(db) {
2211
+ await db.raw(`
2212
+ ALTER TABLE speech_usage ADD COLUMN duration_ms bigint NOT NULL DEFAULT 0 CHECK(duration_ms>=0);
2213
+ -- Retain character counters. Unknown historical audio/failed attempts get
2214
+ -- a conservative bound: 3 MiB of MP3 at minimum 8 kbps plus one 72 ms frame.
2215
+ -- Do not reset current-month usage or claim an exact conversion from text.
2216
+ UPDATE speech_usage SET duration_ms=requests::bigint*3145800 WHERE kind='speech_synthesize';
2217
+ CREATE FUNCTION grove_speech_legacy_duration() RETURNS trigger LANGUAGE plpgsql
2218
+ SET search_path=pg_catalog,public,pg_temp AS $$
2219
+ BEGIN
2220
+ IF NEW.kind='speech_synthesize' THEN
2221
+ IF TG_OP='INSERT' AND NEW.requests>0 AND NEW.duration_ms=0 THEN
2222
+ NEW.duration_ms:=NEW.requests::bigint*3145800;
2223
+ ELSIF TG_OP='UPDATE' AND NEW.requests>OLD.requests AND NEW.duration_ms=OLD.duration_ms THEN
2224
+ NEW.duration_ms:=OLD.duration_ms+(NEW.requests-OLD.requests)::bigint*3145800;
2225
+ END IF;
2226
+ END IF;
2227
+ RETURN NEW;
2228
+ END $$;
2229
+ REVOKE ALL ON FUNCTION grove_speech_legacy_duration() FROM PUBLIC;
2230
+ CREATE TRIGGER speech_legacy_duration BEFORE INSERT OR UPDATE ON speech_usage
2231
+ FOR EACH ROW EXECUTE FUNCTION grove_speech_legacy_duration();
2232
+ `);
2233
+ },
2234
+ async down() {
2235
+ throw new Error("Use a forward migration");
2236
+ }
2237
+ };
2238
+
2008
2239
  // lib/database/src/speech-voices-migration.ts
2009
2240
  init_define_GROVE_TELEMETRY();
2010
2241
  var speechVoices = {
@@ -4357,7 +4588,10 @@ var migrations = [
4357
4588
  researchTools,
4358
4589
  speechDefaults,
4359
4590
  speechVoices,
4360
- billing
4591
+ billing,
4592
+ speechCache,
4593
+ systemAdministration,
4594
+ speechDuration
4361
4595
  ];
4362
4596
  var migrationSource = {
4363
4597
  getMigrations: async () => migrations,
@@ -4437,6 +4671,7 @@ async function probeDatabase(db) {
4437
4671
  );
4438
4672
  await db.raw("SELECT id, lane, lease_id FROM background_tasks LIMIT 0");
4439
4673
  await db.raw("SELECT status, archive_operation_id FROM projects LIMIT 0");
4674
+ await db.raw("SELECT duration_ms FROM speech_usage LIMIT 0");
4440
4675
  await db.raw("SELECT archive_operation_id FROM memories LIMIT 0");
4441
4676
  await db.raw("SELECT tools, tools_version FROM conversations LIMIT 0");
4442
4677
  const versions = await db.raw(
@@ -4466,19 +4701,19 @@ var MemoryModel = class extends Model {
4466
4701
 
4467
4702
  // packages/api/src/app.ts
4468
4703
  init_define_GROVE_TELEMETRY();
4469
- import { randomUUID as randomUUID12 } from "node:crypto";
4704
+ import { randomUUID as randomUUID13 } from "node:crypto";
4470
4705
 
4471
4706
  // packages/api/src/billing.ts
4472
4707
  init_define_GROVE_TELEMETRY();
4473
- import { randomUUID as randomUUID9 } from "node:crypto";
4708
+ import { randomUUID as randomUUID10 } from "node:crypto";
4474
4709
 
4475
4710
  // lib/memory/src/index.ts
4476
4711
  init_define_GROVE_TELEMETRY();
4477
4712
  import {
4478
- createHash as createHash11,
4713
+ createHash as createHash12,
4479
4714
  createHmac as createHmac4,
4480
4715
  randomBytes as randomBytes2,
4481
- randomUUID as randomUUID8,
4716
+ randomUUID as randomUUID9,
4482
4717
  timingSafeEqual as timingSafeEqual4
4483
4718
  } from "node:crypto";
4484
4719
 
@@ -4501,9 +4736,8 @@ var policy = {
4501
4736
  init_define_GROVE_TELEMETRY();
4502
4737
  import { createHash as createHash2 } from "node:crypto";
4503
4738
 
4504
- // lib/ai/src/speech.ts
4739
+ // lib/ai/src/audio-duration.ts
4505
4740
  init_define_GROVE_TELEMETRY();
4506
- import { createHash } from "node:crypto";
4507
4741
 
4508
4742
  // lib/shared/src/speech.ts
4509
4743
  init_define_GROVE_TELEMETRY();
@@ -11659,6 +11893,7 @@ function defaultOnError(left, right) {
11659
11893
 
11660
11894
  // lib/shared/src/speech-voices.ts
11661
11895
  init_define_GROVE_TELEMETRY();
11896
+ var miniMaxTtsFlagKey = "minimax-tts-enabled";
11662
11897
  var speechVoiceIds = ["reed", "willow", "cedar", "brook"];
11663
11898
  var defaultSpeechVoice = "reed";
11664
11899
  var speechVoices2 = [
@@ -11700,7 +11935,10 @@ var speechLimits = {
11700
11935
  audioBytes: 3 * 1024 * 1024,
11701
11936
  dailyRequests: 20,
11702
11937
  dailyAudioMs: 6e5,
11703
- dailyCharacters: 6e4
11938
+ dailyCharacters: 6e4,
11939
+ // MPEG Layer III's minimum supported bitrate is 8 kbps (one byte/ms).
11940
+ // Include one maximum-length frame for conservative pre-dispatch reservations.
11941
+ maximumAudioMs: 3 * 1024 * 1024 + 72
11704
11942
  };
11705
11943
  function speechText(content3) {
11706
11944
  const tree = fromMarkdown(content3);
@@ -11739,6 +11977,8 @@ function speechText(content3) {
11739
11977
  }
11740
11978
 
11741
11979
  // lib/ai/src/speech.ts
11980
+ init_define_GROVE_TELEMETRY();
11981
+ import { createHash } from "node:crypto";
11742
11982
  async function requestSpeech(config, url, body, parent, maximum, contentType = "application/json") {
11743
11983
  const signal = AbortSignal.any([
11744
11984
  parent,
@@ -15363,18 +15603,24 @@ var billingFlagKey = "billing-enabled";
15363
15603
  var billingPriceFlagKey = "billing-pro-monthly-usd";
15364
15604
  var billingLimits = {
15365
15605
  free: {
15366
- generation: { daily: 10, monthly: 100 },
15367
- research: { daily: 3, monthly: 10 },
15368
- transcription: { daily: null, monthly: 6e5 },
15369
- synthesis: { daily: null, monthly: 1e4 }
15606
+ generation: { daily: 1e3, monthly: 31e3 },
15607
+ research: { daily: 20, monthly: 620 },
15608
+ transcription: { daily: null, monthly: 72e5 },
15609
+ synthesis: { daily: null, monthly: 72e5 }
15370
15610
  },
15371
15611
  pro: {
15372
- generation: { daily: 200, monthly: 2e3 },
15373
- research: { daily: 20, monthly: 200 },
15374
- transcription: { daily: null, monthly: 72e5 },
15375
- synthesis: { daily: null, monthly: 2e5 }
15612
+ generation: { daily: 5e3, monthly: 155e3 },
15613
+ research: { daily: 100, monthly: 3100 },
15614
+ transcription: { daily: null, monthly: 288e5 },
15615
+ synthesis: { daily: null, monthly: 288e5 }
15376
15616
  }
15377
15617
  };
15618
+ var billingUnits = {
15619
+ generation: "requests",
15620
+ research: "calls",
15621
+ transcription: "milliseconds",
15622
+ synthesis: "milliseconds"
15623
+ };
15378
15624
 
15379
15625
  // lib/memory/src/billing-quotas.ts
15380
15626
  var configurations = /* @__PURE__ */ new WeakMap();
@@ -15385,13 +15631,16 @@ async function billingUsage(db, trx, accountId) {
15385
15631
  const config = configurations.get(db);
15386
15632
  if (!config) return null;
15387
15633
  const account = await trx("accounts").where({ id: accountId }).first("clerkSubject");
15388
- if (!account || !await config.enabled(account.clerkSubject)) return null;
15634
+ if (!account) return null;
15635
+ const grant = await trx("account_administration").where({ accountId }).first("access");
15636
+ const override = grant?.access === "pro" || grant?.access === "unlimited" ? grant.access : null;
15637
+ if (!override && !await config.enabled(account.clerkSubject)) return null;
15389
15638
  const paid = await trx("billing_subscriptions").where({ accountId }).whereIn("status", ["active", "trialing"]).where((query) => {
15390
15639
  query.whereIn("priceId", config.priceIds);
15391
15640
  if (config.productId) query.orWhere({ productId: config.productId });
15392
15641
  }).where("periodEnd", ">", trx.fn.now()).first("id");
15393
- const plan = paid ? "pro" : "free";
15394
- const limits = (config.limits ?? billingLimits)[plan];
15642
+ const plan = override ?? (paid ? "pro" : "free");
15643
+ const limits = (config.limits ?? billingLimits)[plan === "unlimited" ? "pro" : plan];
15395
15644
  const {
15396
15645
  rows: [clock]
15397
15646
  } = await trx.raw(`SELECT
@@ -15402,7 +15651,7 @@ async function billingUsage(db, trx, accountId) {
15402
15651
  const metrics2 = {};
15403
15652
  for (const metric of Object.keys(limits)) {
15404
15653
  const table = metric === "generation" ? "inference_usage" : metric === "research" ? "research_account_usage" : "speech_usage";
15405
- const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : "units";
15654
+ const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : metric === "synthesis" ? "durationMs" : "units";
15406
15655
  const query = trx(table).where({ accountId }).whereBetween("day", [clock.month, clock.today]);
15407
15656
  if (metric === "generation") query.where({ role: "generation" });
15408
15657
  if (metric === "transcription" || metric === "synthesis")
@@ -15418,8 +15667,8 @@ async function billingUsage(db, trx, accountId) {
15418
15667
  metrics2[metric] = {
15419
15668
  today: Number(usage.today),
15420
15669
  month: Number(usage.month),
15421
- dailyLimit: limits[metric].daily,
15422
- monthlyLimit: limits[metric].monthly
15670
+ dailyLimit: plan === "unlimited" ? null : limits[metric].daily,
15671
+ monthlyLimit: plan === "unlimited" ? null : limits[metric].monthly
15423
15672
  };
15424
15673
  }
15425
15674
  return {
@@ -15429,12 +15678,6 @@ async function billingUsage(db, trx, accountId) {
15429
15678
  metrics: metrics2
15430
15679
  };
15431
15680
  }
15432
- async function billingAllows(db, trx, accountId, metric, units = 1) {
15433
- const snapshot = await billingUsage(db, trx, accountId);
15434
- if (!snapshot) return true;
15435
- const usage = snapshot.metrics[metric];
15436
- return (usage.dailyLimit === null || usage.today + units <= usage.dailyLimit) && usage.month + units <= usage.monthlyLimit;
15437
- }
15438
15681
 
15439
15682
  // lib/memory/src/processing.ts
15440
15683
  var briefTarget = (scope) => `${scope.projectId ?? "personal"}${scope.taskId ? `:task:${scope.taskId}` : ""}`;
@@ -15632,10 +15875,15 @@ async function reserve(db, trx, accountId, role, limit) {
15632
15875
  await trx.raw("SELECT pg_advisory_xact_lock(hashtextextended(?, 6))", [
15633
15876
  accountId
15634
15877
  ]);
15635
- const result = await trx("inference_usage").whereRaw("day = (now() AT TIME ZONE 'UTC')::date").sum("requests as count").first();
15636
- if (Number(result?.count ?? 0) >= limit) return false;
15637
- if (role === "generation" && !await billingAllows(db, trx, accountId, "generation"))
15638
- return false;
15878
+ const billing2 = await billingUsage(db, trx, accountId);
15879
+ const result = await trx("inference_usage").whereRaw("day = (now() AT TIME ZONE 'UTC')::date").modify((query) => {
15880
+ if (billing2) query.whereNot({ role: "generation" });
15881
+ }).sum("requests as count").first();
15882
+ if (billing2 && role === "generation") {
15883
+ const usage = billing2.metrics.generation;
15884
+ if (usage.dailyLimit !== null && usage.today >= usage.dailyLimit || usage.monthlyLimit !== null && usage.month >= usage.monthlyLimit)
15885
+ return false;
15886
+ } else if (Number(result?.count ?? 0) >= limit) return false;
15639
15887
  await trx.raw(
15640
15888
  `INSERT INTO inference_usage(account_id, role, day, requests) VALUES (?, ?, (now() AT TIME ZONE 'UTC')::date, 1)
15641
15889
  ON CONFLICT(account_id, day, role) DO UPDATE SET requests = inference_usage.requests + 1`,
@@ -16103,11 +16351,21 @@ var askToolIds = Object.keys(askToolCatalog);
16103
16351
 
16104
16352
  // lib/shared/src/conversations.ts
16105
16353
  var askToolsSchema = z11.object({ exa: z11.boolean(), tavily: z11.boolean(), organize: z11.boolean() }).strict();
16354
+ var askToolsPatchSchema = askToolsSchema.partial().refine(
16355
+ (patch) => Object.keys(patch).length > 0,
16356
+ "Choose at least one tool to update"
16357
+ );
16106
16358
  var toolSettingsSchema = z11.object({
16107
16359
  tools: askToolsSchema,
16108
16360
  expectedVersion: z11.number().int().nonnegative(),
16109
- saveDefault: z11.boolean().optional()
16110
- }).strict();
16361
+ saveDefault: z11.boolean().optional(),
16362
+ defaultPatch: askToolsPatchSchema.optional()
16363
+ }).strict().refine(
16364
+ ({ tools, saveDefault, defaultPatch }) => !defaultPatch || saveDefault && Object.entries(defaultPatch).every(
16365
+ ([key2, value]) => tools[key2] === value
16366
+ ),
16367
+ "Saved defaults must match the changed conversation tools"
16368
+ );
16111
16369
  var researchRequestSchema = z11.object({
16112
16370
  provider: z11.enum(["exa", "tavily"]),
16113
16371
  query: z11.string().max(500),
@@ -16584,6 +16842,14 @@ var summary = (row) => ({
16584
16842
  tools: row.tools ?? defaultAskTools,
16585
16843
  toolsVersion: row.toolsVersion ?? 0
16586
16844
  });
16845
+ async function saveToolDefaults(trx, account, patch) {
16846
+ const defaults2 = {
16847
+ ...askToolsSchema.parse(account.askTools ?? defaultAskTools),
16848
+ ...patch
16849
+ };
16850
+ await trx("accounts").where({ id: account.id }).update({ askTools: JSON.stringify(defaults2) });
16851
+ return defaults2;
16852
+ }
16587
16853
  var Conversations = class {
16588
16854
  constructor(service, present, revise) {
16589
16855
  this.service = service;
@@ -16646,11 +16912,23 @@ var Conversations = class {
16646
16912
  tools: JSON.stringify(row.tools),
16647
16913
  toolsVersion: row.toolsVersion
16648
16914
  });
16649
- if (input.saveDefault)
16650
- await trx("accounts").where({ id: account.id }).update({ askTools: JSON.stringify(row.tools) });
16651
- return this.read(trx, row);
16915
+ const defaults2 = input.saveDefault ? await saveToolDefaults(trx, account, input.defaultPatch ?? row.tools) : void 0;
16916
+ return {
16917
+ ...await this.read(trx, row),
16918
+ ...defaults2 ? { defaults: defaults2 } : {}
16919
+ };
16652
16920
  });
16653
16921
  }
16922
+ async configureDefaults(principal, input) {
16923
+ const patch = askToolsPatchSchema.parse(input);
16924
+ return this.service.access(
16925
+ principal,
16926
+ "admin",
16927
+ async ({ trx, account }) => ({
16928
+ defaults: await saveToolDefaults(trx, account, patch)
16929
+ })
16930
+ );
16931
+ }
16654
16932
  async get(principal, id) {
16655
16933
  return this.service.access(principal, "admin", async ({ trx }) => {
16656
16934
  const row = await trx("conversations").where({ id }).first();
@@ -17194,19 +17472,20 @@ var Conversations = class {
17194
17472
  );
17195
17473
  if (previous2) return { cached: previous2.sources };
17196
17474
  if (runs.length >= 6) return { limited: true };
17197
- if (!await billingAllows(
17475
+ const billing2 = await billingUsage(
17198
17476
  this.service.db,
17199
17477
  trx,
17200
- principal.accountId,
17201
- "research"
17202
- ))
17478
+ principal.accountId
17479
+ );
17480
+ const usage = billing2?.metrics.research;
17481
+ if (usage && (usage.dailyLimit !== null && usage.today >= usage.dailyLimit || usage.monthlyLimit !== null && usage.month >= usage.monthlyLimit))
17203
17482
  return { limited: true };
17204
17483
  const { rows } = await trx.raw(
17205
17484
  "SELECT grove_research_reserve(?,?,?,?) AS admitted",
17206
17485
  [
17207
17486
  request2.provider,
17208
17487
  operation,
17209
- this.service.researchLimits.dailyCalls,
17488
+ usage ? usage.dailyLimit : this.service.researchLimits.dailyCalls,
17210
17489
  this.service.researchLimits.monthlyMicrodollars
17211
17490
  ]
17212
17491
  );
@@ -18359,6 +18638,7 @@ var Tasks = class {
18359
18638
 
18360
18639
  // lib/memory/src/speech.ts
18361
18640
  init_define_GROVE_TELEMETRY();
18641
+ import { createHash as createHash8, randomUUID as randomUUID5 } from "node:crypto";
18362
18642
  var kinds = ["speech_transcribe", "speech_synthesize"];
18363
18643
  var keys = (kind) => kind === "speech_transcribe" ? {
18364
18644
  preference: "transcriptionEnabled",
@@ -18375,7 +18655,15 @@ var changed = () => new GroveError(
18375
18655
  "The note, transcript or speech settings changed. Start again.",
18376
18656
  409
18377
18657
  );
18378
- var synthesisProtocol = "speech-voices-v1";
18658
+ var synthesisProtocol = "speech-content-cache-v1";
18659
+ async function synthesisAvailable(provider) {
18660
+ if (!provider) return false;
18661
+ try {
18662
+ return provider.available ? await provider.available() === true : true;
18663
+ } catch {
18664
+ return false;
18665
+ }
18666
+ }
18379
18667
  function configuredProfile(configuration, kind, voiceId) {
18380
18668
  if (kind === "speech_transcribe") return configuration?.transcription;
18381
18669
  return configuration?.synthesis === synthesisProtocol && isSpeechVoice(voiceId) ? configuration.synthesisProfiles[voiceId] : void 0;
@@ -18426,6 +18714,8 @@ async function source2(trx, memoryId, version2, mediaId) {
18426
18714
  return {
18427
18715
  object: void 0,
18428
18716
  text: text3,
18717
+ textHash: createHash8("sha256").update(note.content).digest("hex"),
18718
+ expiresAt: note.expiresAt,
18429
18719
  units: text3.length,
18430
18720
  transcriptVersion: void 0
18431
18721
  };
@@ -18439,6 +18729,8 @@ async function validate(trx, row, providers) {
18439
18729
  if (!payload.profile || configuredProfile(configuration, row.kind, payload.voiceId) !== payload.profile || selectedProvider(providers, row.kind, payload.voiceId)?.profile !== payload.profile)
18440
18730
  throw changed();
18441
18731
  const control = await trx("processing_control").first("epoch");
18732
+ if (row.kind === "speech_synthesize" && !await synthesisAvailable(providers.synthesis?.[payload.voiceId]))
18733
+ throw unavailable2();
18442
18734
  const session = await trx.raw(
18443
18735
  "SELECT grove_speech_session_active(?::uuid) AS active",
18444
18736
  [row.id]
@@ -18454,6 +18746,8 @@ async function validate(trx, row, providers) {
18454
18746
  );
18455
18747
  if (current.object && (current.object.sha256 !== payload.sha256 || current.transcriptVersion !== payload.transcriptVersion))
18456
18748
  throw changed();
18749
+ if (row.kind === "speech_synthesize" && current.textHash !== payload.textHash)
18750
+ throw changed();
18457
18751
  return current;
18458
18752
  }
18459
18753
  var descriptor = (row, error3) => ({
@@ -18489,15 +18783,17 @@ var SpeechJobs = class {
18489
18783
  }
18490
18784
  async describe() {
18491
18785
  const configuration = await this.service.db("speech_configuration").first();
18492
- const voices = speechVoices2.map((voice) => {
18493
- const provider = this.providers.synthesis?.[voice.id];
18494
- const available = !!this.store && !!provider && configuredProfile(configuration, "speech_synthesize", voice.id) === provider.profile;
18495
- return {
18496
- ...voice,
18497
- available,
18498
- ...provider?.sampleId ? { sampleId: provider.sampleId } : {}
18499
- };
18500
- });
18786
+ const voices = await Promise.all(
18787
+ speechVoices2.map(async (voice) => {
18788
+ const provider = this.providers.synthesis?.[voice.id];
18789
+ const available = !!this.store && await synthesisAvailable(provider) && configuredProfile(configuration, "speech_synthesize", voice.id) === provider?.profile;
18790
+ return {
18791
+ ...voice,
18792
+ available,
18793
+ ...provider?.sampleId ? { sampleId: provider.sampleId } : {}
18794
+ };
18795
+ })
18796
+ );
18501
18797
  return {
18502
18798
  speechVoices: voices,
18503
18799
  speechAvailable: {
@@ -18524,6 +18820,8 @@ var SpeechJobs = class {
18524
18820
  const voiceId = input.mediaId ? void 0 : input.voiceId ?? account.readAloudVoiceId;
18525
18821
  const provider = selectedProvider(this.providers, kind, voiceId);
18526
18822
  if (!provider || !input.mediaId && !this.store) throw unavailable2();
18823
+ if (!input.mediaId && !await synthesisAvailable(this.providers.synthesis?.[voiceId]))
18824
+ throw unavailable2();
18527
18825
  const current = await source2(trx, memoryId, input.version, input.mediaId);
18528
18826
  const { epoch } = await trx("processing_control").first("epoch");
18529
18827
  const owner = await trx("accounts").where({ id: account.id }).first();
@@ -18534,7 +18832,7 @@ var SpeechJobs = class {
18534
18832
  mediaId: input.mediaId,
18535
18833
  sha256: current.object.sha256,
18536
18834
  transcriptVersion: current.transcriptVersion
18537
- } : { voiceId },
18835
+ } : { voiceId, textHash: current.textHash },
18538
18836
  profile: provider.profile,
18539
18837
  preferenceVersion: owner[key2.version],
18540
18838
  epoch,
@@ -18545,7 +18843,7 @@ var SpeechJobs = class {
18545
18843
  payload.cacheKey = fingerprint([
18546
18844
  account.id,
18547
18845
  memoryId,
18548
- input.version,
18846
+ input.mediaId ? input.version : payload.textHash,
18549
18847
  voiceId,
18550
18848
  provider.profile,
18551
18849
  payload.preferenceVersion,
@@ -18561,21 +18859,21 @@ var SpeechJobs = class {
18561
18859
  "Wait for existing speech jobs, or cancel one.",
18562
18860
  429
18563
18861
  );
18564
- const cached = kind === "speech_synthesize" && await trx("background_tasks as t").where({ "t.kind": kind, "t.status": "succeeded" }).whereRaw("t.payload->>'cacheKey'=?", [payload.cacheKey]).where("t.expiresAt", ">", trx.fn.now()).whereExists(
18565
- trx("export_objects as o").select(trx.raw("1")).whereRaw(
18566
- "o.account_id=t.account_id AND o.object_key=t.result->>'key'"
18567
- ).where("o.expiresAt", ">", trx.fn.now())
18568
- ).first("t.*");
18862
+ const cached = kind === "speech_synthesize" && await trx("export_objects").where({ accountId: account.id, speechCacheKey: payload.cacheKey }).where("expiresAt", ">", trx.fn.now()).first();
18569
18863
  const [row] = await trx("background_tasks").insert({
18570
18864
  id: input.id,
18571
18865
  accountId: account.id,
18572
18866
  kind,
18573
18867
  dedupeKey: input.id,
18574
18868
  payload: JSON.stringify(payload),
18575
- expiresAt: cached ? cached.expiresAt : trx.raw("now()+interval '1 day'"),
18869
+ expiresAt: trx.raw("now()+interval '1 day'"),
18576
18870
  ...cached ? {
18577
18871
  status: "succeeded",
18578
- result: JSON.stringify(cached.result),
18872
+ result: JSON.stringify({
18873
+ key: cached.objectKey,
18874
+ bytes: Number(cached.bytes),
18875
+ sha256: cached.speechSha256
18876
+ }),
18579
18877
  finishedAt: trx.fn.now()
18580
18878
  } : {}
18581
18879
  }).onConflict("id").ignore().returning("*");
@@ -18656,7 +18954,7 @@ var importRequestSchema = z12.object({
18656
18954
 
18657
18955
  // lib/memory/src/connect.ts
18658
18956
  init_define_GROVE_TELEMETRY();
18659
- import { randomUUID as randomUUID5 } from "node:crypto";
18957
+ import { randomUUID as randomUUID6 } from "node:crypto";
18660
18958
  var unavailable3 = () => new GroveError(
18661
18959
  "connection_unavailable",
18662
18960
  "This connection link is unavailable. Run grove connect again, using the same Grove account in your browser.",
@@ -18713,7 +19011,7 @@ var ConnectionSetup = class {
18713
19011
  );
18714
19012
  const attempt = {
18715
19013
  ...input,
18716
- id: randomUUID5(),
19014
+ id: randomUUID6(),
18717
19015
  connectionId: connection.id,
18718
19016
  clientId: connection.clientId,
18719
19017
  status: hasAccess ? "approved" : "pending",
@@ -18841,10 +19139,10 @@ init_define_GROVE_TELEMETRY();
18841
19139
  import {
18842
19140
  createCipheriv,
18843
19141
  createDecipheriv,
18844
- createHash as createHash8,
19142
+ createHash as createHash9,
18845
19143
  createHmac as createHmac2,
18846
19144
  randomBytes,
18847
- randomUUID as randomUUID6,
19145
+ randomUUID as randomUUID7,
18848
19146
  timingSafeEqual as timingSafeEqual2
18849
19147
  } from "node:crypto";
18850
19148
 
@@ -18918,7 +19216,7 @@ function sharedNoteTitle(content3) {
18918
19216
  }
18919
19217
 
18920
19218
  // lib/memory/src/sharing.ts
18921
- var hash2 = (value) => createHash8("sha256").update(value).digest("hex");
19219
+ var hash2 = (value) => createHash9("sha256").update(value).digest("hex");
18922
19220
  var missing3 = () => new GroveError("not_found", "This shared content is unavailable", 404);
18923
19221
  var conflict3 = () => new GroveError(
18924
19222
  "version_conflict",
@@ -19107,7 +19405,7 @@ var Sharing = class {
19107
19405
  return existing;
19108
19406
  }
19109
19407
  const identity = {
19110
- id: existing?.id ?? randomUUID6(),
19408
+ id: existing?.id ?? randomUUID7(),
19111
19409
  accountId: account.id
19112
19410
  };
19113
19411
  const fields = {
@@ -19262,7 +19560,7 @@ var Sharing = class {
19262
19560
 
19263
19561
  // lib/memory/src/media.ts
19264
19562
  init_define_GROVE_TELEMETRY();
19265
- import { createHash as createHash9, randomUUID as randomUUID7 } from "node:crypto";
19563
+ import { createHash as createHash10, randomUUID as randomUUID8 } from "node:crypto";
19266
19564
 
19267
19565
  // lib/shared/src/media.ts
19268
19566
  init_define_GROVE_TELEMETRY();
@@ -19337,7 +19635,7 @@ var MediaAttachments = class {
19337
19635
  const quota = await trx("accounts").where({ id: account.id }).first("mediaBytes", "mediaAttempts");
19338
19636
  if (Number(quota.mediaBytes) + input.bytes > 1024 * 1024 * 1024 || quota.mediaAttempts >= 1e3)
19339
19637
  throw new GroveError("media_quota", "Media storage limit reached", 429);
19340
- const leaseId = randomUUID7(), objectKey = mediaObjectKey(account.id, input.id, leaseId);
19638
+ const leaseId = randomUUID8(), objectKey = mediaObjectKey(account.id, input.id, leaseId);
19341
19639
  const values = {
19342
19640
  memoryId: input.memoryId,
19343
19641
  bytes: input.bytes,
@@ -19423,7 +19721,7 @@ var MediaAttachments = class {
19423
19721
  throw new GroveError("rate_limited", "Retry later", 429);
19424
19722
  const { rows } = await this.service.db.raw(
19425
19723
  "SELECT grove_public_media(?,?::uuid,?::uuid) AS value",
19426
- [createHash9("sha256").update(token).digest("hex"), memoryId, id]
19724
+ [createHash10("sha256").update(token).digest("hex"), memoryId, id]
19427
19725
  );
19428
19726
  const value = rows[0].value;
19429
19727
  if (value?.limited)
@@ -19450,7 +19748,7 @@ var MediaAttachments = class {
19450
19748
  const object = await trx("media_objects").where({ id, memoryId, mime: "audio/wav", status: "ready" }).first();
19451
19749
  if (!object || !await trx("media_revision_bindings").where({ mediaId: id, memoryId, version: note.version }).first())
19452
19750
  throw missing4();
19453
- const old = await trx("media_transcripts").where({ mediaId: id }).first(), fingerprint2 = createHash9("sha256").update(JSON.stringify(input)).digest("hex");
19751
+ const old = await trx("media_transcripts").where({ mediaId: id }).first(), fingerprint2 = createHash10("sha256").update(JSON.stringify(input)).digest("hex");
19454
19752
  if (old?.operationId === input.operationId) {
19455
19753
  if (old.fingerprint !== fingerprint2) throw conflict4();
19456
19754
  return { text: old.text, version: old.version };
@@ -19485,7 +19783,7 @@ var MediaAttachments = class {
19485
19783
 
19486
19784
  // lib/memory/src/conversation-history.ts
19487
19785
  init_define_GROVE_TELEMETRY();
19488
- import { createHash as createHash10, createHmac as createHmac3, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
19786
+ import { createHash as createHash11, createHmac as createHmac3, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
19489
19787
 
19490
19788
  // lib/shared/src/conversation-history.ts
19491
19789
  init_define_GROVE_TELEMETRY();
@@ -19504,7 +19802,7 @@ var conversationHistoryCursorSchema = z14.object({
19504
19802
  // lib/memory/src/conversation-history.ts
19505
19803
  async function searchConversationHistory(service, principal, input) {
19506
19804
  return service.access(principal, "admin", async ({ trx, account }) => {
19507
- const queryHash = createHash10("sha256").update(input.query).digest("hex");
19805
+ const queryHash = createHash11("sha256").update(input.query).digest("hex");
19508
19806
  const signature2 = (value) => createHmac3("sha256", service.cursorSecret).update(`history:${value}`).digest();
19509
19807
  let cursor;
19510
19808
  if (input.after) {
@@ -19656,6 +19954,118 @@ async function executeMemoryTool(service, principal, tool, value, signal) {
19656
19954
  }
19657
19955
  }
19658
19956
 
19957
+ // lib/memory/src/system-admin.ts
19958
+ init_define_GROVE_TELEMETRY();
19959
+
19960
+ // lib/shared/src/system-admin.ts
19961
+ init_define_GROVE_TELEMETRY();
19962
+ import { z as z16 } from "zod";
19963
+ var adminChangeSchema = z16.object({
19964
+ accountId: uuidSchema,
19965
+ operationId: uuidSchema,
19966
+ expectedVersion: z16.number().int().min(0),
19967
+ role: z16.enum(["user", "system_admin"]),
19968
+ access: z16.enum(["default", "pro", "unlimited"]),
19969
+ reason: z16.string().trim().min(3).max(300)
19970
+ }).strict();
19971
+
19972
+ // lib/memory/src/system-admin.ts
19973
+ var denied = () => new GroveError(
19974
+ "system_admin_required",
19975
+ "System administrator access is required",
19976
+ 403
19977
+ );
19978
+ var SystemAdministration = class {
19979
+ constructor(service) {
19980
+ this.service = service;
19981
+ }
19982
+ service;
19983
+ access(principal, run, serialize = true) {
19984
+ const sessionId = principal.sessionId;
19985
+ if (principal.type !== "session" || !sessionId)
19986
+ return Promise.reject(denied());
19987
+ return this.service.access(principal, "admin", async ({ trx, account }) => {
19988
+ if (account.clerkSubject !== principal.subject) throw denied();
19989
+ if (serialize) {
19990
+ await trx.raw("SELECT pg_advisory_xact_lock(68142025)");
19991
+ if ((await trx.raw("SELECT grove_session_revoked(?) AS revoked", [
19992
+ sessionId
19993
+ ])).rows[0].revoked)
19994
+ throw new GroveError("unauthorized", "Session revoked", 401);
19995
+ }
19996
+ return run(trx);
19997
+ }).catch((error3) => {
19998
+ const code = error3.code;
19999
+ if (code === "GA001") throw denied();
20000
+ if (code === "GA002")
20001
+ throw new GroveError(
20002
+ "invalid_request",
20003
+ "Check the request fields",
20004
+ 400
20005
+ );
20006
+ if (code === "GA003" || code === "GA005")
20007
+ throw new GroveError(
20008
+ code === "GA003" ? "operation_conflict" : "admin_version_conflict",
20009
+ "This account changed. Refresh and review it again.",
20010
+ 409
20011
+ );
20012
+ if (code === "GA004")
20013
+ throw new GroveError(
20014
+ "account_unavailable",
20015
+ "This account is unavailable",
20016
+ 404
20017
+ );
20018
+ if (code === "GA006")
20019
+ throw new GroveError(
20020
+ "last_system_admin",
20021
+ "Keep at least one active system administrator",
20022
+ 409
20023
+ );
20024
+ throw error3;
20025
+ });
20026
+ }
20027
+ status(principal) {
20028
+ return this.access(
20029
+ principal,
20030
+ async (trx) => ({
20031
+ role: (await trx("account_administration").where({ accountId: principal.accountId }).first("role"))?.role ?? "user"
20032
+ }),
20033
+ false
20034
+ );
20035
+ }
20036
+ accounts(principal, subjects) {
20037
+ return this.access(
20038
+ principal,
20039
+ async (trx) => (await trx.raw("SELECT grove_admin_accounts(?::text[]) AS result", [
20040
+ subjects ?? null
20041
+ ])).rows[0].result
20042
+ );
20043
+ }
20044
+ async change(principal, raw) {
20045
+ const input = adminChangeSchema.parse(raw);
20046
+ return this.access(
20047
+ principal,
20048
+ async (trx) => (await trx.raw(
20049
+ "SELECT grove_admin_change(?::uuid,?::uuid,?,?,?,?) AS result",
20050
+ [
20051
+ input.accountId,
20052
+ input.operationId,
20053
+ input.expectedVersion,
20054
+ input.role,
20055
+ input.access,
20056
+ input.reason
20057
+ ]
20058
+ )).rows[0].result
20059
+ );
20060
+ }
20061
+ audit(principal) {
20062
+ return this.access(
20063
+ principal,
20064
+ async (trx) => (await trx.raw("SELECT grove_admin_audit() AS result")).rows[0].result
20065
+ );
20066
+ }
20067
+ };
20068
+
19659
20069
  // lib/memory/src/index.ts
19660
20070
  var missing5 = () => new GroveError("not_found", "Memory not found", 404);
19661
20071
  var forbidden = () => new GroveError(
@@ -19669,7 +20079,7 @@ var stable = (value) => JSON.stringify(
19669
20079
  Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))
19670
20080
  ) : entry
19671
20081
  );
19672
- var digest = (value) => createHash11("sha256").update(value).digest("hex");
20082
+ var digest = (value) => createHash12("sha256").update(value).digest("hex");
19673
20083
  var MemoryService = class _MemoryService {
19674
20084
  constructor(db, cursorSecret, embedder, providers = {}, dailyRequestLimit = 2e3) {
19675
20085
  this.db = db;
@@ -20003,7 +20413,7 @@ var MemoryService = class _MemoryService {
20003
20413
  version: input.expectedVersion + 1
20004
20414
  }) : await MemoryModel.query(trx).insertAndFetch({
20005
20415
  ...values,
20006
- id: randomUUID8(),
20416
+ id: randomUUID9(),
20007
20417
  status: input.archived ? "archived" : "active"
20008
20418
  });
20009
20419
  await this.revise(trx, row2);
@@ -20047,7 +20457,7 @@ var MemoryService = class _MemoryService {
20047
20457
  const domain = this.inTransaction(trx);
20048
20458
  for (const item of input.items)
20049
20459
  await domain.updateMemory(principal, {
20050
- operationId: randomUUID8(),
20460
+ operationId: randomUUID9(),
20051
20461
  ...item,
20052
20462
  projectId: input.projectId,
20053
20463
  capture: "explicit"
@@ -20900,7 +21310,7 @@ ${input.query}`.slice(-1e3) : input.query;
20900
21310
  }).returning("*");
20901
21311
  }
20902
21312
  if (!options.key) return { connection };
20903
- const id = randomUUID8();
21313
+ const id = randomUUID9();
20904
21314
  const secret = `grv_${id}_${randomBytes2(32).toString("base64url")}`;
20905
21315
  await trx("api_keys").insert({
20906
21316
  id,
@@ -21286,6 +21696,7 @@ var Billing = class {
21286
21696
  ) : [];
21287
21697
  return {
21288
21698
  enabled,
21699
+ units: billingUnits,
21289
21700
  ...state,
21290
21701
  prices,
21291
21702
  proLimits: this.options.proLimits ?? billingLimits.pro
@@ -21322,7 +21733,7 @@ var Billing = class {
21322
21733
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
21323
21734
  checkoutId: null,
21324
21735
  checkoutPrice: price.id,
21325
- checkoutOperation: randomUUID9()
21736
+ checkoutOperation: randomUUID10()
21326
21737
  });
21327
21738
  }
21328
21739
  if (!row.checkoutPrice)
@@ -21372,7 +21783,7 @@ var Billing = class {
21372
21783
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
21373
21784
  checkoutId: null,
21374
21785
  checkoutPrice: null,
21375
- checkoutOperation: randomUUID9()
21786
+ checkoutOperation: randomUUID10()
21376
21787
  });
21377
21788
  return null;
21378
21789
  }
@@ -21450,6 +21861,79 @@ var Billing = class {
21450
21861
  }
21451
21862
  };
21452
21863
 
21864
+ // packages/api/src/system-admin.ts
21865
+ init_define_GROVE_TELEMETRY();
21866
+ import { createClerkClient } from "@clerk/backend";
21867
+ import { z as z17 } from "zod";
21868
+ function clerkAdminDirectory(secretKey) {
21869
+ const clerk = createClerkClient({ secretKey });
21870
+ return {
21871
+ async find(email) {
21872
+ const result = await clerk.users.getUserList({
21873
+ emailAddress: [email],
21874
+ limit: 30
21875
+ });
21876
+ return result.data.map((user) => user.id);
21877
+ },
21878
+ async users(subjects) {
21879
+ if (!subjects.length) return [];
21880
+ const result = await clerk.users.getUserList({
21881
+ userId: subjects,
21882
+ limit: 30
21883
+ });
21884
+ return result.data.map((user) => ({
21885
+ subject: user.id,
21886
+ name: [user.firstName, user.lastName].filter(Boolean).join(" ") || null,
21887
+ email: user.emailAddresses.find(
21888
+ (email) => email.id === user.primaryEmailAddressId
21889
+ )?.emailAddress ?? null
21890
+ }));
21891
+ }
21892
+ };
21893
+ }
21894
+ var AdminAccounts = class {
21895
+ constructor(service, directory) {
21896
+ this.directory = directory;
21897
+ this.administration = new SystemAdministration(service);
21898
+ }
21899
+ directory;
21900
+ administration;
21901
+ async search(principal, raw) {
21902
+ await this.administration.accounts(principal, []);
21903
+ const { query } = z17.object({ query: z17.string().trim().max(254) }).strict().parse(raw);
21904
+ let subjects;
21905
+ if (query.startsWith("user_") && /^user_[A-Za-z0-9_-]{1,128}$/.test(query))
21906
+ subjects = [query];
21907
+ else if (query) {
21908
+ if (!z17.email().safeParse(query).success)
21909
+ throw new GroveError(
21910
+ "invalid_request",
21911
+ "Search by exact email or user ID",
21912
+ 400
21913
+ );
21914
+ if (!this.directory)
21915
+ throw new GroveError(
21916
+ "unavailable",
21917
+ "Account search is unavailable",
21918
+ 503
21919
+ );
21920
+ subjects = await this.directory.find(query);
21921
+ }
21922
+ const accounts = await this.administration.accounts(principal, subjects);
21923
+ const identities = new Map(
21924
+ (await this.directory?.users(
21925
+ accounts.map((account) => account.subject)
21926
+ ) ?? []).map((user) => [user.subject, user])
21927
+ );
21928
+ await this.administration.accounts(principal, []);
21929
+ return accounts.map((account) => ({
21930
+ ...account,
21931
+ name: identities.get(account.subject)?.name ?? null,
21932
+ email: identities.get(account.subject)?.email ?? null
21933
+ }));
21934
+ }
21935
+ };
21936
+
21453
21937
  // packages/api/src/billing-pricing.ts
21454
21938
  init_define_GROVE_TELEMETRY();
21455
21939
  var MonthlyPricing = class {
@@ -21524,7 +22008,7 @@ import { pipeline as pipeline2 } from "node:stream/promises";
21524
22008
 
21525
22009
  // lib/telemetry/src/index.ts
21526
22010
  init_define_GROVE_TELEMETRY();
21527
- import { createHmac as createHmac5, randomUUID as randomUUID11 } from "node:crypto";
22011
+ import { createHmac as createHmac5, randomUUID as randomUUID12 } from "node:crypto";
21528
22012
  import { performance as performance2 } from "node:perf_hooks";
21529
22013
 
21530
22014
  // node_modules/.pnpm/posthog-node@5.56.2_@opentelemetry+api@1.10.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs
@@ -37142,7 +37626,7 @@ function safeMetric(metric, identity) {
37142
37626
 
37143
37627
  // lib/telemetry/src/preference.ts
37144
37628
  init_define_GROVE_TELEMETRY();
37145
- import { randomUUID as randomUUID10 } from "node:crypto";
37629
+ import { randomUUID as randomUUID11 } from "node:crypto";
37146
37630
  import {
37147
37631
  chmodSync,
37148
37632
  closeSync,
@@ -37193,7 +37677,7 @@ function installationIdentity(directory = telemetryDirectory()) {
37193
37677
  try {
37194
37678
  const fd = openSync(path, "wx", 384);
37195
37679
  try {
37196
- writeFileSync(fd, `${randomUUID10()}
37680
+ writeFileSync(fd, `${randomUUID11()}
37197
37681
  `);
37198
37682
  } finally {
37199
37683
  closeSync(fd);
@@ -37557,7 +38041,7 @@ function telemetry(surface) {
37557
38041
  const server = surface === "api" || surface === "worker";
37558
38042
  const enabled = build.enabled && !environmentDisabled() && (!server || process.env.GROVE_TELEMETRY_ENABLED === "true");
37559
38043
  const directory = telemetryDirectory();
37560
- const identity = enabled ? server ? randomUUID11() : installationIdentity(directory) : "";
38044
+ const identity = enabled ? server ? randomUUID12() : installationIdentity(directory) : "";
37561
38045
  reporter = new Reporter({
37562
38046
  ...build,
37563
38047
  enabled,
@@ -37580,7 +38064,7 @@ var closeTelemetry = (timeoutMs = 550) => Promise.allSettled(
37580
38064
  // packages/api/src/app.ts
37581
38065
  import { Hono } from "hono";
37582
38066
  import { cors } from "hono/cors";
37583
- import { z as z16, ZodError as ZodError2 } from "zod";
38067
+ import { z as z18, ZodError as ZodError2 } from "zod";
37584
38068
  import { Webhook } from "svix";
37585
38069
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
37586
38070
 
@@ -37731,7 +38215,7 @@ var defaultCapacity = {
37731
38215
 
37732
38216
  // packages/api/src/media-images.ts
37733
38217
  init_define_GROVE_TELEMETRY();
37734
- import { createHash as createHash12 } from "node:crypto";
38218
+ import { createHash as createHash13 } from "node:crypto";
37735
38219
  import sharp from "sharp";
37736
38220
 
37737
38221
  // packages/api/src/media-input.ts
@@ -37824,7 +38308,7 @@ async function verifyImage(source3, declaredMime, signal) {
37824
38308
  mime,
37825
38309
  width: meta.width,
37826
38310
  height: meta.height,
37827
- sha256: createHash12("sha256").update(bytes).digest("hex")
38311
+ sha256: createHash13("sha256").update(bytes).digest("hex")
37828
38312
  };
37829
38313
  } catch (error3) {
37830
38314
  signal.throwIfAborted();
@@ -37837,7 +38321,7 @@ async function verifyImage(source3, declaredMime, signal) {
37837
38321
 
37838
38322
  // packages/api/src/media-audio.ts
37839
38323
  init_define_GROVE_TELEMETRY();
37840
- import { createHash as createHash13 } from "node:crypto";
38324
+ import { createHash as createHash14 } from "node:crypto";
37841
38325
  async function verifyAudio(source3, signal) {
37842
38326
  const fail = () => new GroveError(
37843
38327
  "invalid_audio",
@@ -37873,7 +38357,7 @@ async function verifyAudio(source3, signal) {
37873
38357
  return {
37874
38358
  bytes,
37875
38359
  mime: "audio/wav",
37876
- sha256: createHash13("sha256").update(bytes).digest("hex"),
38360
+ sha256: createHash14("sha256").update(bytes).digest("hex"),
37877
38361
  width: 0,
37878
38362
  height: 0,
37879
38363
  durationMs
@@ -37882,7 +38366,7 @@ async function verifyAudio(source3, signal) {
37882
38366
 
37883
38367
  // packages/api/src/media-archive.ts
37884
38368
  init_define_GROVE_TELEMETRY();
37885
- import { createHash as createHash14 } from "node:crypto";
38369
+ import { createHash as createHash15 } from "node:crypto";
37886
38370
  import { Readable } from "node:stream";
37887
38371
  function header(name, size) {
37888
38372
  if (!/^(note\.md|manifest\.json|media\/[0-9a-f-]+\.(png|jpeg|webp|wav|txt))$/.test(
@@ -37989,7 +38473,7 @@ async function noteArchive(service, media, principal, id, expectedVersion, signa
37989
38473
  for (const object of objects) {
37990
38474
  await recheck();
37991
38475
  yield header(object.path, object.bytes);
37992
- const stream = await media.read(object.key, signal), hash3 = createHash14("sha256");
38476
+ const stream = await media.read(object.key, signal), hash3 = createHash15("sha256");
37993
38477
  let bytes = 0, checked = Date.now();
37994
38478
  for await (const chunk of stream) {
37995
38479
  signal.throwIfAborted();
@@ -38039,7 +38523,7 @@ function createApp(deps) {
38039
38523
  capacity.queueTimeoutMs
38040
38524
  );
38041
38525
  app.use("*", async (c, next) => {
38042
- c.set("requestId", randomUUID12());
38526
+ c.set("requestId", randomUUID13());
38043
38527
  c.header("X-Request-ID", c.get("requestId"));
38044
38528
  c.header("Cache-Control", "private, no-store");
38045
38529
  c.header("X-Content-Type-Options", "nosniff");
@@ -38191,13 +38675,13 @@ function createApp(deps) {
38191
38675
  400
38192
38676
  );
38193
38677
  }
38194
- const payload = z16.object({
38195
- type: z16.string(),
38196
- timestamp: z16.number().int(),
38197
- data: z16.object({
38198
- id: z16.string().min(1),
38199
- banned: z16.boolean().optional(),
38200
- locked: z16.boolean().optional()
38678
+ const payload = z18.object({
38679
+ type: z18.string(),
38680
+ timestamp: z18.number().int(),
38681
+ data: z18.object({
38682
+ id: z18.string().min(1),
38683
+ banned: z18.boolean().optional(),
38684
+ locked: z18.boolean().optional()
38201
38685
  })
38202
38686
  }).parse(event);
38203
38687
  await deps.memories.db.transaction(async (trx) => {
@@ -38238,6 +38722,38 @@ function createApp(deps) {
38238
38722
  });
38239
38723
  app.use("/mcp", authorize);
38240
38724
  const service = deps.memories;
38725
+ const admin = new AdminAccounts(service, deps.adminDirectory);
38726
+ app.get(
38727
+ "/v1/admin",
38728
+ async (c) => c.json({
38729
+ success: true,
38730
+ data: await admin.administration.status(c.get("principal"))
38731
+ })
38732
+ );
38733
+ app.post(
38734
+ "/v1/admin/accounts/search",
38735
+ async (c) => c.json({
38736
+ success: true,
38737
+ data: await admin.search(c.get("principal"), await c.req.json())
38738
+ })
38739
+ );
38740
+ app.patch(
38741
+ "/v1/admin/accounts",
38742
+ async (c) => c.json({
38743
+ success: true,
38744
+ data: await admin.administration.change(
38745
+ c.get("principal"),
38746
+ await c.req.json()
38747
+ )
38748
+ })
38749
+ );
38750
+ app.get(
38751
+ "/v1/admin/audit",
38752
+ async (c) => c.json({
38753
+ success: true,
38754
+ data: await admin.administration.audit(c.get("principal"))
38755
+ })
38756
+ );
38241
38757
  app.post("/v1/webhooks/stripe", async (c) => {
38242
38758
  if (!deps.billing)
38243
38759
  throw new GroveError("billing_disabled", "Billing is unavailable", 503);
@@ -38257,9 +38773,9 @@ function createApp(deps) {
38257
38773
  async (c) => c.json({ success: true, data: await billing2().status(c.get("principal")) })
38258
38774
  );
38259
38775
  app.post("/v1/billing/checkout", async (c) => {
38260
- const input = z16.object({
38261
- interval: z16.enum(["month", "year"]),
38262
- expectedAmount: z16.number().int().positive().optional()
38776
+ const input = z18.object({
38777
+ interval: z18.enum(["month", "year"]),
38778
+ expectedAmount: z18.number().int().positive().optional()
38263
38779
  }).strict().parse(await c.req.json());
38264
38780
  return c.json({
38265
38781
  success: true,
@@ -38298,7 +38814,7 @@ function createApp(deps) {
38298
38814
  service,
38299
38815
  c.get("principal"),
38300
38816
  c.req.param("tool"),
38301
- await mutation(c, z16.record(z16.string(), z16.unknown())),
38817
+ await mutation(c, z18.record(z18.string(), z18.unknown())),
38302
38818
  c.get("signal")
38303
38819
  )
38304
38820
  })
@@ -38310,7 +38826,7 @@ function createApp(deps) {
38310
38826
  "Media storage is not configured",
38311
38827
  503
38312
38828
  );
38313
- const id = uuidSchema.parse(c.req.param("id")), version2 = c.req.query("version") ? z16.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
38829
+ const id = uuidSchema.parse(c.req.param("id")), version2 = c.req.query("version") ? z18.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
38314
38830
  const cancelled = new AbortController(), signal = AbortSignal.any([c.get("signal"), cancelled.signal]);
38315
38831
  const source3 = await noteArchive(
38316
38832
  service,
@@ -38344,10 +38860,10 @@ function createApp(deps) {
38344
38860
  const input = {
38345
38861
  id: uuidSchema.parse(c.req.param("id")),
38346
38862
  memoryId: uuidSchema.parse(c.req.param("memoryId")),
38347
- version: z16.coerce.number().int().positive().parse(c.req.header("x-grove-note-version")),
38348
- bytes: z16.coerce.number().int().min(1).max(imageLimits.bytes).parse(c.req.header("content-length")),
38349
- mime: z16.enum(mediaMimeTypes).parse(c.req.header("content-type")),
38350
- sha256: z16.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"))
38863
+ version: z18.coerce.number().int().positive().parse(c.req.header("x-grove-note-version")),
38864
+ bytes: z18.coerce.number().int().min(1).max(imageLimits.bytes).parse(c.req.header("content-length")),
38865
+ mime: z18.enum(mediaMimeTypes).parse(c.req.header("content-type")),
38866
+ sha256: z18.string().regex(/^[0-9a-f]{64}$/).parse(c.req.header("x-grove-content-sha256"))
38351
38867
  };
38352
38868
  const claim = await attachments.claim(principal, input);
38353
38869
  if (claim.replay)
@@ -38450,7 +38966,7 @@ function createApp(deps) {
38450
38966
  };
38451
38967
  app.get("/v1/memories/:memoryId/media/:id", async (c) => {
38452
38968
  const memoryId = uuidSchema.parse(c.req.param("memoryId")), id = uuidSchema.parse(c.req.param("id"));
38453
- const version2 = c.req.query("version") ? z16.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
38969
+ const version2 = c.req.query("version") ? z18.coerce.number().int().positive().parse(c.req.query("version")) : void 0;
38454
38970
  return mediaResponse(
38455
38971
  c,
38456
38972
  () => attachments.read(c.get("principal"), memoryId, id, version2)
@@ -38481,7 +38997,7 @@ function createApp(deps) {
38481
38997
  })
38482
38998
  );
38483
38999
  app.post("/v1/speech/:id/cancel", async (c) => {
38484
- await mutation(c, z16.object({}).strict());
39000
+ await mutation(c, z18.object({}).strict());
38485
39001
  return c.json({
38486
39002
  success: true,
38487
39003
  data: await speech2.cancel(
@@ -38519,10 +39035,10 @@ function createApp(deps) {
38519
39035
  uuidSchema.parse(c.req.param("id")),
38520
39036
  await body(
38521
39037
  c,
38522
- z16.object({
38523
- operationId: z16.uuid(),
38524
- expectedVersion: z16.number().int().min(0),
38525
- text: z16.string().max(6e3)
39038
+ z18.object({
39039
+ operationId: z18.uuid(),
39040
+ expectedVersion: z18.number().int().min(0),
39041
+ text: z18.string().max(6e3)
38526
39042
  }).strict()
38527
39043
  )
38528
39044
  )
@@ -38675,7 +39191,7 @@ function createApp(deps) {
38675
39191
  })
38676
39192
  );
38677
39193
  app.post("/v1/connect/:id/cancel", async (c) => {
38678
- await body(c, z16.object({}).strict());
39194
+ await body(c, z18.object({}).strict());
38679
39195
  return c.json({
38680
39196
  success: true,
38681
39197
  data: await setup.cancel(
@@ -38690,7 +39206,7 @@ function createApp(deps) {
38690
39206
  success: true,
38691
39207
  data: await service.projects(
38692
39208
  c.get("principal"),
38693
- z16.enum(["active", "archived"]).parse(c.req.query("status") ?? "active")
39209
+ z18.enum(["active", "archived"]).parse(c.req.query("status") ?? "active")
38694
39210
  )
38695
39211
  })
38696
39212
  );
@@ -38770,7 +39286,7 @@ function createApp(deps) {
38770
39286
  app.post("/v1/models/test", async (c) => {
38771
39287
  const input = await body(
38772
39288
  c,
38773
- z16.object({ role: z16.enum(["embedding", "decision", "generation"]) }).strict()
39289
+ z18.object({ role: z18.enum(["embedding", "decision", "generation"]) }).strict()
38774
39290
  );
38775
39291
  if (!deps.models)
38776
39292
  throw new GroveError(
@@ -38968,14 +39484,14 @@ function createApp(deps) {
38968
39484
  data: await service.sourceRevision(
38969
39485
  c.get("principal"),
38970
39486
  uuidSchema.parse(c.req.param("id")),
38971
- z16.coerce.number().int().positive().max(2147483647).parse(c.req.param("version"))
39487
+ z18.coerce.number().int().positive().max(2147483647).parse(c.req.param("version"))
38972
39488
  )
38973
39489
  })
38974
39490
  );
38975
39491
  app.post("/v1/memories/:id/reprocess", async (c) => {
38976
39492
  const input = await body(
38977
39493
  c,
38978
- z16.object({ expectedVersion: z16.number().int().positive() }).strict()
39494
+ z18.object({ expectedVersion: z18.number().int().positive() }).strict()
38979
39495
  );
38980
39496
  return c.json({
38981
39497
  success: true,
@@ -39041,6 +39557,16 @@ function createApp(deps) {
39041
39557
  )
39042
39558
  })
39043
39559
  );
39560
+ app.patch(
39561
+ "/v1/ask-tools",
39562
+ async (c) => c.json({
39563
+ success: true,
39564
+ data: await service.conversations.configureDefaults(
39565
+ c.get("principal"),
39566
+ await body(c, askToolsPatchSchema)
39567
+ )
39568
+ })
39569
+ );
39044
39570
  app.patch(
39045
39571
  "/v1/conversations/:id/tools",
39046
39572
  async (c) => c.json({
@@ -39069,7 +39595,7 @@ function createApp(deps) {
39069
39595
  success: true,
39070
39596
  data: await service.conversations.list(
39071
39597
  c.get("principal"),
39072
- z16.uuid().optional().parse(c.req.query("after"))
39598
+ z18.uuid().optional().parse(c.req.query("after"))
39073
39599
  )
39074
39600
  })
39075
39601
  );
@@ -39116,8 +39642,8 @@ function createApp(deps) {
39116
39642
  })
39117
39643
  );
39118
39644
  app.post("/v1/conversations/:id/turns/:turnId/:action", async (c) => {
39119
- const action = z16.enum(["apply", "undo"]).parse(c.req.param("action"));
39120
- await body(c, z16.object({}).strict());
39645
+ const action = z18.enum(["apply", "undo"]).parse(c.req.param("action"));
39646
+ await body(c, z18.object({}).strict());
39121
39647
  return c.json({
39122
39648
  success: true,
39123
39649
  data: await service.conversations.apply(
@@ -39207,7 +39733,7 @@ function createApp(deps) {
39207
39733
  app.post("/v1/account/delete", async (c) => {
39208
39734
  await body(
39209
39735
  c,
39210
- z16.object({ confirm: z16.literal("delete my account") }).strict()
39736
+ z18.object({ confirm: z18.literal("delete my account") }).strict()
39211
39737
  );
39212
39738
  return c.json(
39213
39739
  { success: true, data: await service.deleteAccount(c.get("principal")) },
@@ -39256,7 +39782,7 @@ function createApp(deps) {
39256
39782
  success: true,
39257
39783
  data: await tasks.list(
39258
39784
  c.get("principal"),
39259
- z16.uuid().optional().parse(c.req.query("projectId"))
39785
+ z18.uuid().optional().parse(c.req.query("projectId"))
39260
39786
  )
39261
39787
  })
39262
39788
  );
@@ -39373,7 +39899,7 @@ function createApp(deps) {
39373
39899
 
39374
39900
  // packages/api/src/auth.ts
39375
39901
  init_define_GROVE_TELEMETRY();
39376
- import { createClerkClient } from "@clerk/backend";
39902
+ import { createClerkClient as createClerkClient2 } from "@clerk/backend";
39377
39903
  import { TokenVerificationError } from "@clerk/backend/errors";
39378
39904
  import { createRemoteJWKSet, decodeJwt, jwtVerify, errors } from "jose";
39379
39905
  var unauthorized = () => new GroveError("unauthorized", "Sign in to Grove", 401);
@@ -39382,7 +39908,7 @@ function clerkVerifier(env) {
39382
39908
  new URL("/.well-known/jwks.json", env.CLERK_ISSUER),
39383
39909
  { timeoutDuration: 5e3 }
39384
39910
  );
39385
- const clerk = createClerkClient({
39911
+ const clerk = createClerkClient2({
39386
39912
  secretKey: env.CLERK_SECRET_KEY,
39387
39913
  publishableKey: env.CLERK_PUBLISHABLE_KEY
39388
39914
  });
@@ -39532,108 +40058,125 @@ init_define_GROVE_TELEMETRY();
39532
40058
 
39533
40059
  // lib/environment/src/index.ts
39534
40060
  init_define_GROVE_TELEMETRY();
39535
- import { z as z17 } from "zod";
39536
- var origin = z17.url().transform((value, ctx) => {
40061
+ import { z as z19 } from "zod";
40062
+ var origin = z19.url().transform((value, ctx) => {
39537
40063
  const url = new URL(value);
39538
40064
  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))) {
39539
40065
  ctx.addIssue({
39540
40066
  code: "custom",
39541
40067
  message: "Use an HTTPS origin (HTTP is allowed on loopback)"
39542
40068
  });
39543
- return z17.NEVER;
40069
+ return z19.NEVER;
39544
40070
  }
39545
40071
  return url.origin;
39546
40072
  });
39547
- var allowance = (value) => z17.coerce.number().int().min(0).max(1e9).default(value);
39548
- var serverSchema = z17.object({
39549
- NODE_ENV: z17.enum(["development", "test", "production"]).default("development"),
39550
- PORT: z17.coerce.number().int().min(1).max(65535).default(26080),
39551
- DATABASE_URL: z17.string().min(1),
39552
- DATABASE_SSL: z17.enum(["require", "disable"]).default("disable"),
39553
- DATABASE_POOL_MAX: z17.coerce.number().int().min(1).max(64).default(8),
39554
- DATABASE_ACQUIRE_TIMEOUT_MS: z17.coerce.number().int().min(100).max(3e4).default(2e3),
39555
- DATABASE_STATEMENT_TIMEOUT_MS: z17.coerce.number().int().min(100).max(3e4).default(1e4),
39556
- API_MAX_IN_FLIGHT: z17.coerce.number().int().min(1).max(256).default(32),
39557
- API_MAX_QUEUED: z17.coerce.number().int().min(0).max(256).default(32),
39558
- API_QUEUE_TIMEOUT_MS: z17.coerce.number().int().min(1).max(5e3).default(250),
39559
- API_REQUEST_TIMEOUT_MS: z17.coerce.number().int().min(100).max(6e4).default(1e4),
39560
- API_INTERACTIVE_CONCURRENCY: z17.coerce.number().int().min(1).max(32).default(4),
39561
- API_INTERACTIVE_TIMEOUT_MS: z17.coerce.number().int().min(100).max(18e4).default(9e4),
40073
+ var allowance = (value) => z19.coerce.number().int().min(0).max(1e9).default(value);
40074
+ var serverSchema = z19.object({
40075
+ NODE_ENV: z19.enum(["development", "test", "production"]).default("development"),
40076
+ PORT: z19.coerce.number().int().min(1).max(65535).default(26080),
40077
+ DATABASE_URL: z19.string().min(1),
40078
+ DATABASE_SSL: z19.enum(["require", "disable"]).default("disable"),
40079
+ DATABASE_POOL_MAX: z19.coerce.number().int().min(1).max(64).default(8),
40080
+ DATABASE_ACQUIRE_TIMEOUT_MS: z19.coerce.number().int().min(100).max(3e4).default(2e3),
40081
+ DATABASE_STATEMENT_TIMEOUT_MS: z19.coerce.number().int().min(100).max(3e4).default(1e4),
40082
+ API_MAX_IN_FLIGHT: z19.coerce.number().int().min(1).max(256).default(32),
40083
+ API_MAX_QUEUED: z19.coerce.number().int().min(0).max(256).default(32),
40084
+ API_QUEUE_TIMEOUT_MS: z19.coerce.number().int().min(1).max(5e3).default(250),
40085
+ API_REQUEST_TIMEOUT_MS: z19.coerce.number().int().min(100).max(6e4).default(1e4),
40086
+ API_INTERACTIVE_CONCURRENCY: z19.coerce.number().int().min(1).max(32).default(4),
40087
+ API_INTERACTIVE_TIMEOUT_MS: z19.coerce.number().int().min(100).max(18e4).default(9e4),
39562
40088
  API_ORIGIN: origin,
39563
40089
  SITE_URL: origin,
39564
40090
  // Public ownership proof, never an account credential. Empty values are omitted below.
39565
- OPENAI_APPS_CHALLENGE: z17.string().min(1).max(512).refine(
40091
+ OPENAI_APPS_CHALLENGE: z19.string().min(1).max(512).refine(
39566
40092
  (value) => !/\s/.test(value),
39567
40093
  "Use the exact non-whitespace verification token"
39568
40094
  ).optional(),
39569
- CLERK_PUBLISHABLE_KEY: z17.string().startsWith("pk_"),
39570
- CLERK_SECRET_KEY: z17.string().startsWith("sk_"),
40095
+ CLERK_PUBLISHABLE_KEY: z19.string().startsWith("pk_"),
40096
+ CLERK_SECRET_KEY: z19.string().startsWith("sk_"),
39571
40097
  CLERK_ISSUER: origin,
39572
- CLERK_WEBHOOK_SIGNING_SECRET: z17.string().min(1),
39573
- GROVE_EDITION: z17.enum(["self-hosted", "cloud"]).default("self-hosted"),
39574
- BILLING_CONFIGURED: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39575
- FLAGS: z17.string().min(1).optional(),
39576
- STRIPE_SECRET_KEY: z17.string().regex(/^(sk|rk)_(test|live)_/).optional(),
39577
- STRIPE_WEBHOOK_SECRET: z17.string().startsWith("whsec_").optional(),
39578
- STRIPE_PRO_PRODUCT_ID: z17.string().startsWith("prod_").optional(),
39579
- STRIPE_PORTAL_CONFIGURATION_ID: z17.string().startsWith("bpc_").optional(),
39580
- STRIPE_PRO_MONTHLY_PRICE_ID: z17.string().startsWith("price_").optional(),
39581
- STRIPE_PRO_YEARLY_PRICE_ID: z17.string().startsWith("price_").optional(),
39582
- BILLING_FREE_GENERATION_DAILY: allowance(10),
39583
- BILLING_FREE_GENERATION_MONTHLY: allowance(100),
39584
- BILLING_PRO_GENERATION_DAILY: allowance(200),
39585
- BILLING_PRO_GENERATION_MONTHLY: allowance(2e3),
39586
- BILLING_FREE_RESEARCH_DAILY: allowance(3),
39587
- BILLING_FREE_RESEARCH_MONTHLY: allowance(10),
39588
- BILLING_PRO_RESEARCH_DAILY: allowance(20),
39589
- BILLING_PRO_RESEARCH_MONTHLY: allowance(200),
39590
- BILLING_FREE_TRANSCRIPTION_MONTHLY_MS: allowance(6e5),
39591
- BILLING_PRO_TRANSCRIPTION_MONTHLY_MS: allowance(72e5),
39592
- BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: allowance(1e4),
39593
- BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: allowance(2e5),
39594
- EMBEDDING_MODE: z17.enum(["local", "remote", "disabled"]).optional(),
39595
- EMBEDDING_CACHE: z17.string().default("./data/models"),
39596
- EMBEDDING_URL: z17.string().optional(),
39597
- EMBEDDING_MODEL: z17.string().optional(),
39598
- EMBEDDING_API_KEY: z17.string().optional(),
39599
- EMBEDDING_DIMENSIONS: z17.coerce.number().int().min(32).max(16e3).optional(),
39600
- EMBEDDING_QUERY_PREFIX: z17.string().optional(),
39601
- EMBEDDING_DOCUMENT_PREFIX: z17.string().optional(),
39602
- EMBEDDING_DISTANCE_THRESHOLD: z17.coerce.number().min(0).max(2).optional(),
39603
- DECISION_PROVIDER: z17.enum(["system-one", "disabled"]).default("disabled"),
39604
- DECISION_URL: z17.string().optional(),
39605
- DECISION_MODEL: z17.string().optional(),
39606
- DECISION_API_KEY: z17.string().optional(),
39607
- DECISION_PATH: z17.enum(["/decisions", "/systemone"]).default("/decisions"),
39608
- GENERATION_PROVIDER: z17.enum(["minimax", "openai-compatible", "disabled"]).default("disabled"),
39609
- GENERATION_URL: z17.string().optional(),
39610
- GENERATION_MODEL: z17.string().optional(),
39611
- GENERATION_API_KEY: z17.string().optional(),
39612
- GENERATION_OUTPUT_FORMAT: z17.enum(["tool", "json-schema", "json"]).default("tool"),
39613
- GENERATION_REASONING_EFFORT: z17.enum(["low", "medium", "high", "omit"]).default("low"),
39614
- GENERATION_MAX_OUTPUT_TOKENS: z17.coerce.number().int().min(256).max(16384).default(4096),
39615
- DEEPINFRA_API_KEY: z17.string().optional(),
39616
- MINIMAX_API_KEY: z17.string().optional(),
39617
- OPENAI_API_KEY: z17.string().optional(),
39618
- SPEECH_ENABLED: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39619
- TTS_VOICE: z17.enum(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]).default("alloy"),
39620
- MINIMAX_TTS_ENABLED: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39621
- SPEECH_PROVIDER_CONCURRENCY: z17.coerce.number().int().min(1).max(16).default(2),
39622
- EXA_API_KEY: z17.string().optional(),
39623
- TAVILY_API_KEY: z17.string().optional(),
39624
- RESEARCH_DAILY_CALL_LIMIT: z17.coerce.number().int().min(1).max(1e4).default(20),
39625
- RESEARCH_MONTHLY_BUDGET_USD: z17.coerce.number().min(0).max(1e5).default(100),
39626
- MODEL_ADMIN_SUBJECTS: z17.string().default(""),
39627
- MODEL_SETTINGS_KEY: z17.string().regex(/^[0-9a-f]{64}$/i).optional(),
39628
- AI_DAILY_REQUEST_LIMIT: z17.coerce.number().int().min(1).max(1e6).default(2e3),
39629
- AI_CONCURRENCY: z17.coerce.number().int().min(1).max(32).default(4),
39630
- INDEXING_CONCURRENCY: z17.coerce.number().int().min(0).max(32).default(2),
39631
- EMAIL_CONCURRENCY: z17.coerce.number().int().min(0).max(8).default(1),
39632
- MAINTENANCE_CONCURRENCY: z17.coerce.number().int().min(0).max(8).default(1),
39633
- BULK_CONCURRENCY: z17.coerce.number().int().min(0).max(8).default(1),
39634
- JOB_ACCOUNT_CONCURRENCY: z17.coerce.number().int().min(1).max(8).default(2),
39635
- JOB_PROVIDER_CONCURRENCY: z17.coerce.number().int().min(1).max(128).default(8),
39636
- WORKER_LANES: z17.string().default("indexing,enrichment,email,maintenance,bulk").refine(
40098
+ CLERK_WEBHOOK_SIGNING_SECRET: z19.string().min(1),
40099
+ GROVE_EDITION: z19.enum(["self-hosted", "cloud"]).default("self-hosted"),
40100
+ BILLING_CONFIGURED: z19.enum(["true", "false"]).default("false").transform((value) => value === "true"),
40101
+ FLAGS: z19.string().min(1).optional(),
40102
+ STRIPE_SECRET_KEY: z19.string().regex(/^(sk|rk)_(test|live)_/).optional(),
40103
+ STRIPE_WEBHOOK_SECRET: z19.string().startsWith("whsec_").optional(),
40104
+ STRIPE_PRO_PRODUCT_ID: z19.string().startsWith("prod_").optional(),
40105
+ STRIPE_PORTAL_CONFIGURATION_ID: z19.string().startsWith("bpc_").optional(),
40106
+ STRIPE_PRO_MONTHLY_PRICE_ID: z19.string().startsWith("price_").optional(),
40107
+ STRIPE_PRO_YEARLY_PRICE_ID: z19.string().startsWith("price_").optional(),
40108
+ BILLING_FREE_GENERATION_DAILY: allowance(
40109
+ billingLimits.free.generation.daily
40110
+ ),
40111
+ BILLING_FREE_GENERATION_MONTHLY: allowance(
40112
+ billingLimits.free.generation.monthly
40113
+ ),
40114
+ BILLING_PRO_GENERATION_DAILY: allowance(billingLimits.pro.generation.daily),
40115
+ BILLING_PRO_GENERATION_MONTHLY: allowance(
40116
+ billingLimits.pro.generation.monthly
40117
+ ),
40118
+ BILLING_FREE_RESEARCH_DAILY: allowance(billingLimits.free.research.daily),
40119
+ BILLING_FREE_RESEARCH_MONTHLY: allowance(billingLimits.free.research.monthly),
40120
+ BILLING_PRO_RESEARCH_DAILY: allowance(billingLimits.pro.research.daily),
40121
+ BILLING_PRO_RESEARCH_MONTHLY: allowance(billingLimits.pro.research.monthly),
40122
+ BILLING_FREE_TRANSCRIPTION_MONTHLY_MS: allowance(
40123
+ billingLimits.free.transcription.monthly
40124
+ ),
40125
+ BILLING_PRO_TRANSCRIPTION_MONTHLY_MS: allowance(
40126
+ billingLimits.pro.transcription.monthly
40127
+ ),
40128
+ BILLING_FREE_SYNTHESIS_MONTHLY_MS: allowance(
40129
+ billingLimits.free.synthesis.monthly
40130
+ ),
40131
+ BILLING_PRO_SYNTHESIS_MONTHLY_MS: allowance(
40132
+ billingLimits.pro.synthesis.monthly
40133
+ ),
40134
+ // Reject old deployment settings instead of silently treating characters as time.
40135
+ BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: z19.string().optional(),
40136
+ BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: z19.string().optional(),
40137
+ EMBEDDING_MODE: z19.enum(["local", "remote", "disabled"]).optional(),
40138
+ EMBEDDING_CACHE: z19.string().default("./data/models"),
40139
+ EMBEDDING_URL: z19.string().optional(),
40140
+ EMBEDDING_MODEL: z19.string().optional(),
40141
+ EMBEDDING_API_KEY: z19.string().optional(),
40142
+ EMBEDDING_DIMENSIONS: z19.coerce.number().int().min(32).max(16e3).optional(),
40143
+ EMBEDDING_QUERY_PREFIX: z19.string().optional(),
40144
+ EMBEDDING_DOCUMENT_PREFIX: z19.string().optional(),
40145
+ EMBEDDING_DISTANCE_THRESHOLD: z19.coerce.number().min(0).max(2).optional(),
40146
+ DECISION_PROVIDER: z19.enum(["system-one", "disabled"]).default("disabled"),
40147
+ DECISION_URL: z19.string().optional(),
40148
+ DECISION_MODEL: z19.string().optional(),
40149
+ DECISION_API_KEY: z19.string().optional(),
40150
+ DECISION_PATH: z19.enum(["/decisions", "/systemone"]).default("/decisions"),
40151
+ GENERATION_PROVIDER: z19.enum(["minimax", "openai-compatible", "disabled"]).default("disabled"),
40152
+ GENERATION_URL: z19.string().optional(),
40153
+ GENERATION_MODEL: z19.string().optional(),
40154
+ GENERATION_API_KEY: z19.string().optional(),
40155
+ GENERATION_OUTPUT_FORMAT: z19.enum(["tool", "json-schema", "json"]).default("tool"),
40156
+ GENERATION_REASONING_EFFORT: z19.enum(["low", "medium", "high", "omit"]).default("low"),
40157
+ GENERATION_MAX_OUTPUT_TOKENS: z19.coerce.number().int().min(256).max(16384).default(4096),
40158
+ DEEPINFRA_API_KEY: z19.string().optional(),
40159
+ MINIMAX_API_KEY: z19.string().optional(),
40160
+ OPENAI_API_KEY: z19.string().optional(),
40161
+ SPEECH_ENABLED: z19.enum(["true", "false"]).default("false").transform((value) => value === "true"),
40162
+ TTS_VOICE: z19.enum(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]).default("alloy"),
40163
+ MINIMAX_TTS_ENABLED: z19.enum(["true", "false"]).default("false").transform((value) => value === "true"),
40164
+ SPEECH_PROVIDER_CONCURRENCY: z19.coerce.number().int().min(1).max(16).default(2),
40165
+ EXA_API_KEY: z19.string().optional(),
40166
+ TAVILY_API_KEY: z19.string().optional(),
40167
+ RESEARCH_DAILY_CALL_LIMIT: z19.coerce.number().int().min(1).max(1e4).default(20),
40168
+ RESEARCH_MONTHLY_BUDGET_USD: z19.coerce.number().min(0).max(1e5).default(100),
40169
+ MODEL_ADMIN_SUBJECTS: z19.string().default(""),
40170
+ MODEL_SETTINGS_KEY: z19.string().regex(/^[0-9a-f]{64}$/i).optional(),
40171
+ AI_DAILY_REQUEST_LIMIT: z19.coerce.number().int().min(1).max(1e6).default(2e3),
40172
+ AI_CONCURRENCY: z19.coerce.number().int().min(1).max(32).default(4),
40173
+ INDEXING_CONCURRENCY: z19.coerce.number().int().min(0).max(32).default(2),
40174
+ EMAIL_CONCURRENCY: z19.coerce.number().int().min(0).max(8).default(1),
40175
+ MAINTENANCE_CONCURRENCY: z19.coerce.number().int().min(0).max(8).default(1),
40176
+ BULK_CONCURRENCY: z19.coerce.number().int().min(0).max(8).default(1),
40177
+ JOB_ACCOUNT_CONCURRENCY: z19.coerce.number().int().min(1).max(8).default(2),
40178
+ JOB_PROVIDER_CONCURRENCY: z19.coerce.number().int().min(1).max(128).default(8),
40179
+ WORKER_LANES: z19.string().default("indexing,enrichment,email,maintenance,bulk").refine(
39637
40180
  (value) => value.split(",").every(
39638
40181
  (lane) => ["indexing", "enrichment", "email", "maintenance", "bulk"].includes(
39639
40182
  lane
@@ -39641,38 +40184,47 @@ var serverSchema = z17.object({
39641
40184
  ),
39642
40185
  "Unknown worker lane"
39643
40186
  ),
39644
- WORKER_LEGACY_QUEUE: z17.enum(["true", "false"]).default("true").transform((value) => value === "true"),
39645
- EXPORT_STORAGE: z17.enum(["disabled", "local", "s3"]).optional(),
40187
+ WORKER_LEGACY_QUEUE: z19.enum(["true", "false"]).default("true").transform((value) => value === "true"),
40188
+ EXPORT_STORAGE: z19.enum(["disabled", "local", "s3"]).optional(),
39646
40189
  // Explicit opt-in until the revision-scoped media API is available.
39647
- MEDIA_STORAGE: z17.enum(["disabled", "local", "s3"]).default("disabled"),
39648
- MEDIA_DIRECTORY: z17.string().default("./data/media"),
39649
- MEDIA_S3_ENDPOINT: z17.url().optional(),
39650
- MEDIA_S3_REGION: z17.string().default("us-east-1"),
39651
- MEDIA_S3_BUCKET: z17.string().optional(),
39652
- MEDIA_S3_ACCESS_KEY_ID: z17.string().optional(),
39653
- MEDIA_S3_SECRET_ACCESS_KEY: z17.string().optional(),
40190
+ MEDIA_STORAGE: z19.enum(["disabled", "local", "s3"]).default("disabled"),
40191
+ MEDIA_DIRECTORY: z19.string().default("./data/media"),
40192
+ MEDIA_S3_ENDPOINT: z19.url().optional(),
40193
+ MEDIA_S3_REGION: z19.string().default("us-east-1"),
40194
+ MEDIA_S3_BUCKET: z19.string().optional(),
40195
+ MEDIA_S3_ACCESS_KEY_ID: z19.string().optional(),
40196
+ MEDIA_S3_SECRET_ACCESS_KEY: z19.string().optional(),
39654
40197
  // Exact endpoint/bucket receipt from an operator lifecycle/ACL inspection.
39655
40198
  // Spaces scoped keys cannot read these settings; never use an account-wide key in runtime.
39656
- MEDIA_S3_LIFECYCLE_VERIFIED_FOR: z17.string().optional(),
39657
- MEDIA_S3_PATH_STYLE: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39658
- EXPORT_DIRECTORY: z17.string().default("./data/exports"),
39659
- EXPORT_S3_ENDPOINT: z17.url().optional(),
39660
- EXPORT_S3_REGION: z17.string().default("us-east-1"),
39661
- EXPORT_S3_BUCKET: z17.string().optional(),
39662
- EXPORT_S3_ACCESS_KEY_ID: z17.string().optional(),
39663
- EXPORT_S3_SECRET_ACCESS_KEY: z17.string().optional(),
39664
- EXPORT_S3_PATH_STYLE: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39665
- AMQP_URL: z17.url().refine(
40199
+ MEDIA_S3_LIFECYCLE_VERIFIED_FOR: z19.string().optional(),
40200
+ MEDIA_S3_PATH_STYLE: z19.enum(["true", "false"]).default("false").transform((value) => value === "true"),
40201
+ EXPORT_DIRECTORY: z19.string().default("./data/exports"),
40202
+ EXPORT_S3_ENDPOINT: z19.url().optional(),
40203
+ EXPORT_S3_REGION: z19.string().default("us-east-1"),
40204
+ EXPORT_S3_BUCKET: z19.string().optional(),
40205
+ EXPORT_S3_ACCESS_KEY_ID: z19.string().optional(),
40206
+ EXPORT_S3_SECRET_ACCESS_KEY: z19.string().optional(),
40207
+ EXPORT_S3_PATH_STYLE: z19.enum(["true", "false"]).default("false").transform((value) => value === "true"),
40208
+ AMQP_URL: z19.url().refine(
39666
40209
  (value) => new URL(value).protocol === "amqps:",
39667
40210
  "Use TLS for the job broker"
39668
40211
  ).optional(),
39669
- ORGANIZATION_INTERVAL_SECONDS: z17.coerce.number().int().min(60).max(86400).default(900),
39670
- RESEND_API_KEY: z17.string().startsWith("re_").optional(),
39671
- EMAIL_FROM: z17.string().email().default("notifications@mail.usegrove.cloud"),
39672
- CURSOR_SECRET: z17.string().min(32),
39673
- SHARE_LINK_KEY: z17.string().regex(/^[0-9a-f]{64}$/i).optional()
40212
+ ORGANIZATION_INTERVAL_SECONDS: z19.coerce.number().int().min(60).max(86400).default(900),
40213
+ RESEND_API_KEY: z19.string().startsWith("re_").optional(),
40214
+ EMAIL_FROM: z19.string().email().default("notifications@mail.usegrove.cloud"),
40215
+ CURSOR_SECRET: z19.string().min(32),
40216
+ SHARE_LINK_KEY: z19.string().regex(/^[0-9a-f]{64}$/i).optional()
39674
40217
  });
39675
40218
  var serverEnvironmentSchema = serverSchema.superRefine((env, ctx) => {
40219
+ for (const tier of ["FREE", "PRO"]) {
40220
+ const path = `BILLING_${tier}_SYNTHESIS_MONTHLY_CHARACTERS`;
40221
+ if (env[path] !== void 0)
40222
+ ctx.addIssue({
40223
+ code: "custom",
40224
+ path: [path],
40225
+ message: "Replace SYNTHESIS_MONTHLY_CHARACTERS with SYNTHESIS_MONTHLY_MS; characters are not audio duration"
40226
+ });
40227
+ }
39676
40228
  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))
39677
40229
  ctx.addIssue({
39678
40230
  code: "custom",
@@ -39689,6 +40241,9 @@ function readServerEnvironment(env = process.env) {
39689
40241
  );
39690
40242
  }
39691
40243
 
40244
+ // packages/api/src/runtime.ts
40245
+ import { createClient as createClient2 } from "@vercel/flags-core";
40246
+
39692
40247
  // packages/api/src/models.ts
39693
40248
  init_define_GROVE_TELEMETRY();
39694
40249
  import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes3 } from "node:crypto";
@@ -40032,7 +40587,7 @@ function createBilling(env, service) {
40032
40587
  },
40033
40588
  synthesis: {
40034
40589
  daily: null,
40035
- monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_CHARACTERS`]
40590
+ monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_MS`]
40036
40591
  }
40037
40592
  });
40038
40593
  const prices = {
@@ -40087,7 +40642,7 @@ import {
40087
40642
  import { Upload } from "@aws-sdk/lib-storage";
40088
40643
  var validateKey2 = (key2) => {
40089
40644
  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}";
40090
- if (!/^exports\/[a-f0-9-]+\/[a-f0-9-]+\/[a-f0-9-]+\.ndjson$/.test(key2) && !new RegExp(`^speech/${uuid2}/${uuid2}/${uuid2}\\.mp3$`).test(key2))
40645
+ if (!/^exports\/[a-f0-9-]+\/[a-f0-9-]+\/[a-f0-9-]+\.ndjson$/.test(key2) && !new RegExp(`^(speech|narration)/${uuid2}/${uuid2}/${uuid2}\\.mp3$`).test(key2))
40091
40646
  throw new Error("invalid_artifact_key");
40092
40647
  return key2;
40093
40648
  };
@@ -40143,7 +40698,7 @@ function s3Artifacts(client, bucket) {
40143
40698
  Bucket: bucket,
40144
40699
  Key: validateKey2(key2),
40145
40700
  Body: data,
40146
- ContentType: key2.startsWith("speech/") ? "audio/mpeg" : "application/x-ndjson",
40701
+ ContentType: key2.endsWith(".mp3") ? "audio/mpeg" : "application/x-ndjson",
40147
40702
  CacheControl: "private, no-store"
40148
40703
  };
40149
40704
  if (Buffer.isBuffer(data)) {
@@ -40217,7 +40772,7 @@ function createArtifacts(env) {
40217
40772
  init_define_GROVE_TELEMETRY();
40218
40773
  import { constants as constants3 } from "node:fs";
40219
40774
  import { link, lstat, mkdir as mkdir2, open as open2, realpath, unlink as unlink2 } from "node:fs/promises";
40220
- import { randomUUID as randomUUID13 } from "node:crypto";
40775
+ import { randomUUID as randomUUID14 } from "node:crypto";
40221
40776
  import { dirname as dirname4, resolve as resolve3, sep as sep4 } from "node:path";
40222
40777
  import { Readable as Readable4 } from "node:stream";
40223
40778
  import {
@@ -40278,7 +40833,7 @@ function localMedia(root) {
40278
40833
  signal.throwIfAborted();
40279
40834
  validImage(image);
40280
40835
  const target = await directories(key2, true);
40281
- const temporary = `${target}.${randomUUID13()}.partial`;
40836
+ const temporary = `${target}.${randomUUID14()}.partial`;
40282
40837
  const file = await open2(
40283
40838
  temporary,
40284
40839
  constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW,
@@ -40337,7 +40892,7 @@ function s3Media(client, bucket, spacesLifecycleVerified = false) {
40337
40892
  if (name !== "NoSuchLifecycleConfiguration" && !(name === "AccessDenied" && spacesLifecycleVerified))
40338
40893
  throw error3;
40339
40894
  }
40340
- const probe = `media-probes/${randomUUID13()}`;
40895
+ const probe = `media-probes/${randomUUID14()}`;
40341
40896
  try {
40342
40897
  const put = (body) => client.send(
40343
40898
  new PutObjectCommand2({
@@ -40456,6 +41011,9 @@ async function createRuntime() {
40456
41011
  "SELECT transcription_enabled,read_aloud_enabled,read_aloud_voice_id FROM accounts LIMIT 0"
40457
41012
  );
40458
41013
  await db.raw("SELECT synthesis_profiles FROM speech_configuration LIMIT 0");
41014
+ await db.raw(
41015
+ "SELECT speech_cache_key,speech_text_hash FROM export_objects LIMIT 0"
41016
+ );
40459
41017
  if (env.MEDIA_STORAGE !== "disabled") {
40460
41018
  await db.raw(
40461
41019
  "SELECT status,lease_id,object_key,duration_ms FROM media_objects LIMIT 0"
@@ -40499,42 +41057,23 @@ async function createRuntime() {
40499
41057
  artifacts?.close?.();
40500
41058
  throw error3;
40501
41059
  }
40502
- let speech2 = {};
40503
- if (env.SPEECH_ENABLED) {
40504
- if (!env.OPENAI_API_KEY?.trim()) {
40505
- artifacts?.close?.();
40506
- media?.close?.();
40507
- throw new Error("speech_api_key_required");
40508
- }
40509
- const remote = createOpenAiSpeech({
40510
- apiKey: env.OPENAI_API_KEY,
40511
- voice: env.TTS_VOICE
40512
- });
40513
- speech2 = {
40514
- ...media ? { transcription: remote.transcription } : {},
40515
- ...artifacts ? { synthesis: { reed: remote.synthesis } } : {}
40516
- };
40517
- if (env.MINIMAX_TTS_ENABLED) {
40518
- if (!env.MINIMAX_API_KEY?.trim() || !artifacts) {
40519
- artifacts?.close?.();
40520
- media?.close?.();
40521
- throw new Error("minimax_speech_key_and_storage_required");
40522
- }
40523
- speech2.synthesis = {
40524
- ...speech2.synthesis,
40525
- ...Object.fromEntries(
40526
- Object.entries(miniMaxSpeechVoices).map(([id, voice]) => [
40527
- id,
40528
- {
40529
- ...createMiniMaxSpeech({ apiKey: env.MINIMAX_API_KEY, voice }),
40530
- sampleId: `${id}-v1`
40531
- }
40532
- ])
40533
- )
40534
- };
40535
- }
41060
+ const speechFlags = env.SPEECH_ENABLED && env.FLAGS ? createClient2(env.FLAGS, { staleIfError: 0, staleWhileRevalidate: 0 }) : void 0;
41061
+ let speech2;
41062
+ let billingRuntime;
41063
+ try {
41064
+ speech2 = createSpeechProviders(
41065
+ env,
41066
+ !!media,
41067
+ !!artifacts,
41068
+ speechFlags ? async () => (await speechFlags.evaluate(miniMaxTtsFlagKey, false)).value === true : void 0
41069
+ );
41070
+ billingRuntime = createBilling(env, memories);
41071
+ } catch (error3) {
41072
+ await speechFlags?.shutdown();
41073
+ artifacts?.close?.();
41074
+ media?.close?.();
41075
+ throw error3;
40536
41076
  }
40537
- const billingRuntime = createBilling(env, memories);
40538
41077
  return {
40539
41078
  env,
40540
41079
  db,
@@ -40545,6 +41084,7 @@ async function createRuntime() {
40545
41084
  speech: speech2,
40546
41085
  billing: billingRuntime?.billing,
40547
41086
  close: async () => {
41087
+ await speechFlags?.shutdown();
40548
41088
  await billingRuntime?.close();
40549
41089
  artifacts?.close?.();
40550
41090
  media?.close?.();
@@ -40556,6 +41096,37 @@ async function createRuntime() {
40556
41096
  throw error3;
40557
41097
  }
40558
41098
  }
41099
+ function createSpeechProviders(env, media, artifacts, minimaxEnabled) {
41100
+ if (!env.SPEECH_ENABLED) return {};
41101
+ if (!env.OPENAI_API_KEY?.trim()) throw new Error("speech_api_key_required");
41102
+ const remote = createOpenAiSpeech({
41103
+ apiKey: env.OPENAI_API_KEY,
41104
+ voice: env.TTS_VOICE
41105
+ });
41106
+ const speech2 = {
41107
+ ...media ? { transcription: remote.transcription } : {},
41108
+ ...artifacts ? { synthesis: { reed: remote.synthesis } } : {}
41109
+ };
41110
+ const configured = !!env.MINIMAX_API_KEY?.trim() && artifacts;
41111
+ if (!env.FLAGS && env.MINIMAX_TTS_ENABLED && !configured)
41112
+ throw new Error("minimax_speech_key_and_storage_required");
41113
+ if (configured && (env.FLAGS ? !!minimaxEnabled : env.MINIMAX_TTS_ENABLED)) {
41114
+ speech2.synthesis = {
41115
+ ...speech2.synthesis,
41116
+ ...Object.fromEntries(
41117
+ Object.entries(miniMaxSpeechVoices).map(([id, voice]) => [
41118
+ id,
41119
+ {
41120
+ ...createMiniMaxSpeech({ apiKey: env.MINIMAX_API_KEY, voice }),
41121
+ sampleId: `${id}-v1`,
41122
+ ...env.FLAGS ? { available: minimaxEnabled } : {}
41123
+ }
41124
+ ])
41125
+ )
41126
+ };
41127
+ }
41128
+ return speech2;
41129
+ }
40559
41130
 
40560
41131
  // packages/api/src/server.ts
40561
41132
  async function startServer() {
@@ -40564,6 +41135,7 @@ async function startServer() {
40564
41135
  await configureSpeech(db, runtime.speech);
40565
41136
  const reporter = telemetry("api");
40566
41137
  const app = createApp({
41138
+ adminDirectory: clerkAdminDirectory(env.CLERK_SECRET_KEY),
40567
41139
  memories,
40568
41140
  models: runtime.models,
40569
41141
  artifacts: runtime.artifacts,