@miniaxolotl/grove-server 1.11.2 → 1.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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: "862ea7d1f1b5b843f5080d549c4a33c177f39a5e", version: "1.11.2", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
16
+ define_GROVE_TELEMETRY_default = { enabled: true, revision: "6ed25ff0ae691845950d57b87349be2ad4e36a9f", version: "1.11.4", component: "api", key: "phc_AqVrjhk7W2X2pFjyngY7uWxcSSRREfJhgr8mBmKbXYEh", cliDsn: "https://3f6d0711b5890dea4ce8e6ccf2a1a7fd@o4511632209346560.ingest.us.sentry.io/4512290791620608", apiDsn: "https://4524e8910e318110277babdfe818999b@o4511632209346560.ingest.us.sentry.io/4512290791489536" };
17
17
  }
18
18
  });
19
19
 
@@ -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,
@@ -12725,6 +12965,9 @@ var grantSchema = z6.object({
12725
12965
  var connectionSchema = grantSchema.extend({
12726
12966
  clientId: z6.string().min(1).max(500)
12727
12967
  });
12968
+ var connectionUpdateSchema = grantSchema.extend({
12969
+ expectedState: z6.string().regex(/^[a-f0-9]{64}$/).optional()
12970
+ });
12728
12971
  var agentSchema = z6.enum(["opencode", "claude", "codex"]);
12729
12972
  var agentNames = {
12730
12973
  opencode: "OpenCode",
@@ -12830,25 +13073,30 @@ var notebookToolLifecycleSchema = z7.object({
12830
13073
  );
12831
13074
  var memoryTools = {
12832
13075
  remember: {
13076
+ title: "Save a memory",
12833
13077
  schema: rememberSchema,
12834
13078
  description: "Save a concise memory or replace it by id/expectedVersion. Corrections replace metadata too: prefer update_memory for partial edits. Reuse operationId on retries. Handoffs default to 30 days; expired records are hidden and later soft-deleted."
12835
13079
  },
12836
13080
  recall: {
13081
+ title: "Recall saved context",
12837
13082
  schema: recallSchema,
12838
13083
  readOnly: true,
12839
13084
  description: "Recall bounded relevant active memories in the explicit project/personal scope. Without query, retrieve a compact profile and selected task handoff."
12840
13085
  },
12841
13086
  memories: {
13087
+ title: "Find memories",
12842
13088
  schema: listSchema,
12843
13089
  readOnly: true,
12844
13090
  description: "Search and list notes with IDs, versions, provenance, status/tag filters and cursor pagination. Omit projectId to inspect all granted scopes; null means Personal."
12845
13091
  },
12846
13092
  forget: {
13093
+ title: "Delete selected memories",
12847
13094
  schema: forgetSchema,
12848
13095
  destructive: true,
12849
13096
  description: "Soft-delete exact note IDs at their expectedVersion. Retained authored history is hidden, not physically erased. There is no ordinary restore/Undo for deletion. Inspect each outcome; previously delivered text cannot be retracted."
12850
13097
  },
12851
13098
  get_memory: {
13099
+ title: "Read a memory",
12852
13100
  schema: z7.object({
12853
13101
  id: uuidSchema,
12854
13102
  revision: z7.number().int().positive().optional()
@@ -12857,19 +13105,23 @@ var memoryTools = {
12857
13105
  description: "Read one exact note by ID, optionally at a historical revision. Current scope, deletion and historical-source expiry checks still apply."
12858
13106
  },
12859
13107
  memory_history: {
13108
+ title: "Read memory history",
12860
13109
  schema: z7.object({ id: uuidSchema }).strict(),
12861
13110
  readOnly: true,
12862
13111
  description: "Read up to 100 most recent revisions of an accessible note. Use get_memory with revision for historical content."
12863
13112
  },
12864
13113
  update_memory: {
13114
+ title: "Update a memory",
12865
13115
  schema: memoryUpdateSchema,
12866
13116
  description: "Partially update a note at expectedVersion. Omitted content, scope, kind, provenance and lifetime are preserved. projectId moves the note; null means Personal. Reuse operationId on retry."
12867
13117
  },
12868
13118
  move_memories: {
13119
+ title: "Move memories",
12869
13120
  schema: moveMemoriesSchema,
12870
13121
  description: "Atomically move up to 50 exact ID/version notes into an existing notebook (projectId) or Personal (null). Preserve content and metadata; source and destination must be granted. Reuse operationId."
12871
13122
  },
12872
13123
  archive_memory: {
13124
+ title: "Archive a memory",
12873
13125
  schema: z7.object({
12874
13126
  id: uuidSchema,
12875
13127
  operationId: operationSchema,
@@ -12878,23 +13130,28 @@ var memoryTools = {
12878
13130
  description: "Archive an exact note at expectedVersion, removing it from recall. Content/history remain available; restore_memory reverses archive. Reuse operationId."
12879
13131
  },
12880
13132
  restore_memory: {
13133
+ title: "Restore a memory",
12881
13134
  schema: versionSchema.extend({ id: uuidSchema }),
12882
13135
  description: "Restore an archived/expired note or a historical revision at expectedVersion. Deleted notes cannot be restored. Optional revision selects history; durable removes expiry. Reuse operationId."
12883
13136
  },
12884
13137
  notebooks: {
13138
+ title: "Find notebooks",
12885
13139
  schema: notebookListSchema,
12886
13140
  readOnly: true,
12887
13141
  description: "List/search granted notebooks (folders) with IDs, names, parentId, versions and cursor pagination. Follow every page to build a tree. Archived notebooks require an owner website session."
12888
13142
  },
12889
13143
  create_notebook: {
13144
+ title: "Create a notebook",
12890
13145
  schema: notebookCreateSchema,
12891
13146
  description: "Create a notebook, optionally under parentId. Requires all-project write access or an owner session. Reuse operationId for retry-safe creation."
12892
13147
  },
12893
13148
  update_notebook: {
13149
+ title: "Update a notebook",
12894
13150
  schema: notebookUpdateSchema,
12895
13151
  description: "Rename and/or move an existing notebook at expectedVersion. Omitted fields are preserved; parentId=null moves to root. Source and parent must be granted; cycles are rejected. Reuse operationId."
12896
13152
  },
12897
13153
  notebook_lifecycle: {
13154
+ title: "Manage notebook lifecycle",
12898
13155
  schema: notebookToolLifecycleSchema,
12899
13156
  destructive: true,
12900
13157
  description: "Owner website session only: preview a notebook subtree, then archive/restore/soft-delete using its fingerprint, expectedVersion and operationId. Agent OAuth/API keys cannot administer subtrees. Deletion hides retained history and has no ordinary Undo."
@@ -15346,18 +15603,24 @@ var billingFlagKey = "billing-enabled";
15346
15603
  var billingPriceFlagKey = "billing-pro-monthly-usd";
15347
15604
  var billingLimits = {
15348
15605
  free: {
15349
- generation: { daily: 10, monthly: 100 },
15350
- research: { daily: 3, monthly: 10 },
15351
- transcription: { daily: null, monthly: 6e5 },
15352
- 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 }
15353
15610
  },
15354
15611
  pro: {
15355
- generation: { daily: 200, monthly: 2e3 },
15356
- research: { daily: 20, monthly: 200 },
15357
- transcription: { daily: null, monthly: 72e5 },
15358
- 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 }
15359
15616
  }
15360
15617
  };
15618
+ var billingUnits = {
15619
+ generation: "requests",
15620
+ research: "calls",
15621
+ transcription: "milliseconds",
15622
+ synthesis: "milliseconds"
15623
+ };
15361
15624
 
15362
15625
  // lib/memory/src/billing-quotas.ts
15363
15626
  var configurations = /* @__PURE__ */ new WeakMap();
@@ -15368,13 +15631,16 @@ async function billingUsage(db, trx, accountId) {
15368
15631
  const config = configurations.get(db);
15369
15632
  if (!config) return null;
15370
15633
  const account = await trx("accounts").where({ id: accountId }).first("clerkSubject");
15371
- 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;
15372
15638
  const paid = await trx("billing_subscriptions").where({ accountId }).whereIn("status", ["active", "trialing"]).where((query) => {
15373
15639
  query.whereIn("priceId", config.priceIds);
15374
15640
  if (config.productId) query.orWhere({ productId: config.productId });
15375
15641
  }).where("periodEnd", ">", trx.fn.now()).first("id");
15376
- const plan = paid ? "pro" : "free";
15377
- const limits = (config.limits ?? billingLimits)[plan];
15642
+ const plan = override ?? (paid ? "pro" : "free");
15643
+ const limits = (config.limits ?? billingLimits)[plan === "unlimited" ? "pro" : plan];
15378
15644
  const {
15379
15645
  rows: [clock]
15380
15646
  } = await trx.raw(`SELECT
@@ -15385,7 +15651,7 @@ async function billingUsage(db, trx, accountId) {
15385
15651
  const metrics2 = {};
15386
15652
  for (const metric of Object.keys(limits)) {
15387
15653
  const table = metric === "generation" ? "inference_usage" : metric === "research" ? "research_account_usage" : "speech_usage";
15388
- const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : "units";
15654
+ const units = metric === "generation" ? "requests" : metric === "research" ? "calls" : metric === "synthesis" ? "durationMs" : "units";
15389
15655
  const query = trx(table).where({ accountId }).whereBetween("day", [clock.month, clock.today]);
15390
15656
  if (metric === "generation") query.where({ role: "generation" });
15391
15657
  if (metric === "transcription" || metric === "synthesis")
@@ -15401,8 +15667,8 @@ async function billingUsage(db, trx, accountId) {
15401
15667
  metrics2[metric] = {
15402
15668
  today: Number(usage.today),
15403
15669
  month: Number(usage.month),
15404
- dailyLimit: limits[metric].daily,
15405
- monthlyLimit: limits[metric].monthly
15670
+ dailyLimit: plan === "unlimited" ? null : limits[metric].daily,
15671
+ monthlyLimit: plan === "unlimited" ? null : limits[metric].monthly
15406
15672
  };
15407
15673
  }
15408
15674
  return {
@@ -15412,12 +15678,6 @@ async function billingUsage(db, trx, accountId) {
15412
15678
  metrics: metrics2
15413
15679
  };
15414
15680
  }
15415
- async function billingAllows(db, trx, accountId, metric, units = 1) {
15416
- const snapshot = await billingUsage(db, trx, accountId);
15417
- if (!snapshot) return true;
15418
- const usage = snapshot.metrics[metric];
15419
- return (usage.dailyLimit === null || usage.today + units <= usage.dailyLimit) && usage.month + units <= usage.monthlyLimit;
15420
- }
15421
15681
 
15422
15682
  // lib/memory/src/processing.ts
15423
15683
  var briefTarget = (scope) => `${scope.projectId ?? "personal"}${scope.taskId ? `:task:${scope.taskId}` : ""}`;
@@ -15615,10 +15875,15 @@ async function reserve(db, trx, accountId, role, limit) {
15615
15875
  await trx.raw("SELECT pg_advisory_xact_lock(hashtextextended(?, 6))", [
15616
15876
  accountId
15617
15877
  ]);
15618
- const result = await trx("inference_usage").whereRaw("day = (now() AT TIME ZONE 'UTC')::date").sum("requests as count").first();
15619
- if (Number(result?.count ?? 0) >= limit) return false;
15620
- if (role === "generation" && !await billingAllows(db, trx, accountId, "generation"))
15621
- 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;
15622
15887
  await trx.raw(
15623
15888
  `INSERT INTO inference_usage(account_id, role, day, requests) VALUES (?, ?, (now() AT TIME ZONE 'UTC')::date, 1)
15624
15889
  ON CONFLICT(account_id, day, role) DO UPDATE SET requests = inference_usage.requests + 1`,
@@ -16086,11 +16351,21 @@ var askToolIds = Object.keys(askToolCatalog);
16086
16351
 
16087
16352
  // lib/shared/src/conversations.ts
16088
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
+ );
16089
16358
  var toolSettingsSchema = z11.object({
16090
16359
  tools: askToolsSchema,
16091
16360
  expectedVersion: z11.number().int().nonnegative(),
16092
- saveDefault: z11.boolean().optional()
16093
- }).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
+ );
16094
16369
  var researchRequestSchema = z11.object({
16095
16370
  provider: z11.enum(["exa", "tavily"]),
16096
16371
  query: z11.string().max(500),
@@ -16567,6 +16842,14 @@ var summary = (row) => ({
16567
16842
  tools: row.tools ?? defaultAskTools,
16568
16843
  toolsVersion: row.toolsVersion ?? 0
16569
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
+ }
16570
16853
  var Conversations = class {
16571
16854
  constructor(service, present, revise) {
16572
16855
  this.service = service;
@@ -16629,11 +16912,23 @@ var Conversations = class {
16629
16912
  tools: JSON.stringify(row.tools),
16630
16913
  toolsVersion: row.toolsVersion
16631
16914
  });
16632
- if (input.saveDefault)
16633
- await trx("accounts").where({ id: account.id }).update({ askTools: JSON.stringify(row.tools) });
16634
- 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
+ };
16635
16920
  });
16636
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
+ }
16637
16932
  async get(principal, id) {
16638
16933
  return this.service.access(principal, "admin", async ({ trx }) => {
16639
16934
  const row = await trx("conversations").where({ id }).first();
@@ -17177,19 +17472,20 @@ var Conversations = class {
17177
17472
  );
17178
17473
  if (previous2) return { cached: previous2.sources };
17179
17474
  if (runs.length >= 6) return { limited: true };
17180
- if (!await billingAllows(
17475
+ const billing2 = await billingUsage(
17181
17476
  this.service.db,
17182
17477
  trx,
17183
- principal.accountId,
17184
- "research"
17185
- ))
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))
17186
17482
  return { limited: true };
17187
17483
  const { rows } = await trx.raw(
17188
17484
  "SELECT grove_research_reserve(?,?,?,?) AS admitted",
17189
17485
  [
17190
17486
  request2.provider,
17191
17487
  operation,
17192
- this.service.researchLimits.dailyCalls,
17488
+ usage ? usage.dailyLimit : this.service.researchLimits.dailyCalls,
17193
17489
  this.service.researchLimits.monthlyMicrodollars
17194
17490
  ]
17195
17491
  );
@@ -18342,6 +18638,7 @@ var Tasks = class {
18342
18638
 
18343
18639
  // lib/memory/src/speech.ts
18344
18640
  init_define_GROVE_TELEMETRY();
18641
+ import { createHash as createHash8, randomUUID as randomUUID5 } from "node:crypto";
18345
18642
  var kinds = ["speech_transcribe", "speech_synthesize"];
18346
18643
  var keys = (kind) => kind === "speech_transcribe" ? {
18347
18644
  preference: "transcriptionEnabled",
@@ -18358,7 +18655,15 @@ var changed = () => new GroveError(
18358
18655
  "The note, transcript or speech settings changed. Start again.",
18359
18656
  409
18360
18657
  );
18361
- 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
+ }
18362
18667
  function configuredProfile(configuration, kind, voiceId) {
18363
18668
  if (kind === "speech_transcribe") return configuration?.transcription;
18364
18669
  return configuration?.synthesis === synthesisProtocol && isSpeechVoice(voiceId) ? configuration.synthesisProfiles[voiceId] : void 0;
@@ -18409,6 +18714,8 @@ async function source2(trx, memoryId, version2, mediaId) {
18409
18714
  return {
18410
18715
  object: void 0,
18411
18716
  text: text3,
18717
+ textHash: createHash8("sha256").update(note.content).digest("hex"),
18718
+ expiresAt: note.expiresAt,
18412
18719
  units: text3.length,
18413
18720
  transcriptVersion: void 0
18414
18721
  };
@@ -18422,6 +18729,8 @@ async function validate(trx, row, providers) {
18422
18729
  if (!payload.profile || configuredProfile(configuration, row.kind, payload.voiceId) !== payload.profile || selectedProvider(providers, row.kind, payload.voiceId)?.profile !== payload.profile)
18423
18730
  throw changed();
18424
18731
  const control = await trx("processing_control").first("epoch");
18732
+ if (row.kind === "speech_synthesize" && !await synthesisAvailable(providers.synthesis?.[payload.voiceId]))
18733
+ throw unavailable2();
18425
18734
  const session = await trx.raw(
18426
18735
  "SELECT grove_speech_session_active(?::uuid) AS active",
18427
18736
  [row.id]
@@ -18437,6 +18746,8 @@ async function validate(trx, row, providers) {
18437
18746
  );
18438
18747
  if (current.object && (current.object.sha256 !== payload.sha256 || current.transcriptVersion !== payload.transcriptVersion))
18439
18748
  throw changed();
18749
+ if (row.kind === "speech_synthesize" && current.textHash !== payload.textHash)
18750
+ throw changed();
18440
18751
  return current;
18441
18752
  }
18442
18753
  var descriptor = (row, error3) => ({
@@ -18472,15 +18783,17 @@ var SpeechJobs = class {
18472
18783
  }
18473
18784
  async describe() {
18474
18785
  const configuration = await this.service.db("speech_configuration").first();
18475
- const voices = speechVoices2.map((voice) => {
18476
- const provider = this.providers.synthesis?.[voice.id];
18477
- const available = !!this.store && !!provider && configuredProfile(configuration, "speech_synthesize", voice.id) === provider.profile;
18478
- return {
18479
- ...voice,
18480
- available,
18481
- ...provider?.sampleId ? { sampleId: provider.sampleId } : {}
18482
- };
18483
- });
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
+ );
18484
18797
  return {
18485
18798
  speechVoices: voices,
18486
18799
  speechAvailable: {
@@ -18507,6 +18820,8 @@ var SpeechJobs = class {
18507
18820
  const voiceId = input.mediaId ? void 0 : input.voiceId ?? account.readAloudVoiceId;
18508
18821
  const provider = selectedProvider(this.providers, kind, voiceId);
18509
18822
  if (!provider || !input.mediaId && !this.store) throw unavailable2();
18823
+ if (!input.mediaId && !await synthesisAvailable(this.providers.synthesis?.[voiceId]))
18824
+ throw unavailable2();
18510
18825
  const current = await source2(trx, memoryId, input.version, input.mediaId);
18511
18826
  const { epoch } = await trx("processing_control").first("epoch");
18512
18827
  const owner = await trx("accounts").where({ id: account.id }).first();
@@ -18517,7 +18832,7 @@ var SpeechJobs = class {
18517
18832
  mediaId: input.mediaId,
18518
18833
  sha256: current.object.sha256,
18519
18834
  transcriptVersion: current.transcriptVersion
18520
- } : { voiceId },
18835
+ } : { voiceId, textHash: current.textHash },
18521
18836
  profile: provider.profile,
18522
18837
  preferenceVersion: owner[key2.version],
18523
18838
  epoch,
@@ -18528,7 +18843,7 @@ var SpeechJobs = class {
18528
18843
  payload.cacheKey = fingerprint([
18529
18844
  account.id,
18530
18845
  memoryId,
18531
- input.version,
18846
+ input.mediaId ? input.version : payload.textHash,
18532
18847
  voiceId,
18533
18848
  provider.profile,
18534
18849
  payload.preferenceVersion,
@@ -18544,21 +18859,21 @@ var SpeechJobs = class {
18544
18859
  "Wait for existing speech jobs, or cancel one.",
18545
18860
  429
18546
18861
  );
18547
- 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(
18548
- trx("export_objects as o").select(trx.raw("1")).whereRaw(
18549
- "o.account_id=t.account_id AND o.object_key=t.result->>'key'"
18550
- ).where("o.expiresAt", ">", trx.fn.now())
18551
- ).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();
18552
18863
  const [row] = await trx("background_tasks").insert({
18553
18864
  id: input.id,
18554
18865
  accountId: account.id,
18555
18866
  kind,
18556
18867
  dedupeKey: input.id,
18557
18868
  payload: JSON.stringify(payload),
18558
- expiresAt: cached ? cached.expiresAt : trx.raw("now()+interval '1 day'"),
18869
+ expiresAt: trx.raw("now()+interval '1 day'"),
18559
18870
  ...cached ? {
18560
18871
  status: "succeeded",
18561
- result: JSON.stringify(cached.result),
18872
+ result: JSON.stringify({
18873
+ key: cached.objectKey,
18874
+ bytes: Number(cached.bytes),
18875
+ sha256: cached.speechSha256
18876
+ }),
18562
18877
  finishedAt: trx.fn.now()
18563
18878
  } : {}
18564
18879
  }).onConflict("id").ignore().returning("*");
@@ -18639,7 +18954,7 @@ var importRequestSchema = z12.object({
18639
18954
 
18640
18955
  // lib/memory/src/connect.ts
18641
18956
  init_define_GROVE_TELEMETRY();
18642
- import { randomUUID as randomUUID5 } from "node:crypto";
18957
+ import { randomUUID as randomUUID6 } from "node:crypto";
18643
18958
  var unavailable3 = () => new GroveError(
18644
18959
  "connection_unavailable",
18645
18960
  "This connection link is unavailable. Run grove connect again, using the same Grove account in your browser.",
@@ -18696,7 +19011,7 @@ var ConnectionSetup = class {
18696
19011
  );
18697
19012
  const attempt = {
18698
19013
  ...input,
18699
- id: randomUUID5(),
19014
+ id: randomUUID6(),
18700
19015
  connectionId: connection.id,
18701
19016
  clientId: connection.clientId,
18702
19017
  status: hasAccess ? "approved" : "pending",
@@ -18714,9 +19029,9 @@ var ConnectionSetup = class {
18714
19029
  0,
18715
19030
  100
18716
19031
  ),
18717
- capabilities: ["memory:read", "memory:write"],
19032
+ capabilities: [...capabilities],
18718
19033
  personal: true,
18719
- allProjects: false,
19034
+ allProjects: true,
18720
19035
  projectIds: []
18721
19036
  }
18722
19037
  };
@@ -18824,10 +19139,10 @@ init_define_GROVE_TELEMETRY();
18824
19139
  import {
18825
19140
  createCipheriv,
18826
19141
  createDecipheriv,
18827
- createHash as createHash8,
19142
+ createHash as createHash9,
18828
19143
  createHmac as createHmac2,
18829
19144
  randomBytes,
18830
- randomUUID as randomUUID6,
19145
+ randomUUID as randomUUID7,
18831
19146
  timingSafeEqual as timingSafeEqual2
18832
19147
  } from "node:crypto";
18833
19148
 
@@ -18901,7 +19216,7 @@ function sharedNoteTitle(content3) {
18901
19216
  }
18902
19217
 
18903
19218
  // lib/memory/src/sharing.ts
18904
- var hash2 = (value) => createHash8("sha256").update(value).digest("hex");
19219
+ var hash2 = (value) => createHash9("sha256").update(value).digest("hex");
18905
19220
  var missing3 = () => new GroveError("not_found", "This shared content is unavailable", 404);
18906
19221
  var conflict3 = () => new GroveError(
18907
19222
  "version_conflict",
@@ -19090,7 +19405,7 @@ var Sharing = class {
19090
19405
  return existing;
19091
19406
  }
19092
19407
  const identity = {
19093
- id: existing?.id ?? randomUUID6(),
19408
+ id: existing?.id ?? randomUUID7(),
19094
19409
  accountId: account.id
19095
19410
  };
19096
19411
  const fields = {
@@ -19245,7 +19560,7 @@ var Sharing = class {
19245
19560
 
19246
19561
  // lib/memory/src/media.ts
19247
19562
  init_define_GROVE_TELEMETRY();
19248
- import { createHash as createHash9, randomUUID as randomUUID7 } from "node:crypto";
19563
+ import { createHash as createHash10, randomUUID as randomUUID8 } from "node:crypto";
19249
19564
 
19250
19565
  // lib/shared/src/media.ts
19251
19566
  init_define_GROVE_TELEMETRY();
@@ -19320,7 +19635,7 @@ var MediaAttachments = class {
19320
19635
  const quota = await trx("accounts").where({ id: account.id }).first("mediaBytes", "mediaAttempts");
19321
19636
  if (Number(quota.mediaBytes) + input.bytes > 1024 * 1024 * 1024 || quota.mediaAttempts >= 1e3)
19322
19637
  throw new GroveError("media_quota", "Media storage limit reached", 429);
19323
- const leaseId = randomUUID7(), objectKey = mediaObjectKey(account.id, input.id, leaseId);
19638
+ const leaseId = randomUUID8(), objectKey = mediaObjectKey(account.id, input.id, leaseId);
19324
19639
  const values = {
19325
19640
  memoryId: input.memoryId,
19326
19641
  bytes: input.bytes,
@@ -19406,7 +19721,7 @@ var MediaAttachments = class {
19406
19721
  throw new GroveError("rate_limited", "Retry later", 429);
19407
19722
  const { rows } = await this.service.db.raw(
19408
19723
  "SELECT grove_public_media(?,?::uuid,?::uuid) AS value",
19409
- [createHash9("sha256").update(token).digest("hex"), memoryId, id]
19724
+ [createHash10("sha256").update(token).digest("hex"), memoryId, id]
19410
19725
  );
19411
19726
  const value = rows[0].value;
19412
19727
  if (value?.limited)
@@ -19433,7 +19748,7 @@ var MediaAttachments = class {
19433
19748
  const object = await trx("media_objects").where({ id, memoryId, mime: "audio/wav", status: "ready" }).first();
19434
19749
  if (!object || !await trx("media_revision_bindings").where({ mediaId: id, memoryId, version: note.version }).first())
19435
19750
  throw missing4();
19436
- 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");
19437
19752
  if (old?.operationId === input.operationId) {
19438
19753
  if (old.fingerprint !== fingerprint2) throw conflict4();
19439
19754
  return { text: old.text, version: old.version };
@@ -19468,7 +19783,7 @@ var MediaAttachments = class {
19468
19783
 
19469
19784
  // lib/memory/src/conversation-history.ts
19470
19785
  init_define_GROVE_TELEMETRY();
19471
- 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";
19472
19787
 
19473
19788
  // lib/shared/src/conversation-history.ts
19474
19789
  init_define_GROVE_TELEMETRY();
@@ -19487,7 +19802,7 @@ var conversationHistoryCursorSchema = z14.object({
19487
19802
  // lib/memory/src/conversation-history.ts
19488
19803
  async function searchConversationHistory(service, principal, input) {
19489
19804
  return service.access(principal, "admin", async ({ trx, account }) => {
19490
- const queryHash = createHash10("sha256").update(input.query).digest("hex");
19805
+ const queryHash = createHash11("sha256").update(input.query).digest("hex");
19491
19806
  const signature2 = (value) => createHmac3("sha256", service.cursorSecret).update(`history:${value}`).digest();
19492
19807
  let cursor;
19493
19808
  if (input.after) {
@@ -19639,6 +19954,118 @@ async function executeMemoryTool(service, principal, tool, value, signal) {
19639
19954
  }
19640
19955
  }
19641
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
+
19642
20069
  // lib/memory/src/index.ts
19643
20070
  var missing5 = () => new GroveError("not_found", "Memory not found", 404);
19644
20071
  var forbidden = () => new GroveError(
@@ -19652,7 +20079,7 @@ var stable = (value) => JSON.stringify(
19652
20079
  Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))
19653
20080
  ) : entry
19654
20081
  );
19655
- var digest = (value) => createHash11("sha256").update(value).digest("hex");
20082
+ var digest = (value) => createHash12("sha256").update(value).digest("hex");
19656
20083
  var MemoryService = class _MemoryService {
19657
20084
  constructor(db, cursorSecret, embedder, providers = {}, dailyRequestLimit = 2e3) {
19658
20085
  this.db = db;
@@ -19986,7 +20413,7 @@ var MemoryService = class _MemoryService {
19986
20413
  version: input.expectedVersion + 1
19987
20414
  }) : await MemoryModel.query(trx).insertAndFetch({
19988
20415
  ...values,
19989
- id: randomUUID8(),
20416
+ id: randomUUID9(),
19990
20417
  status: input.archived ? "archived" : "active"
19991
20418
  });
19992
20419
  await this.revise(trx, row2);
@@ -20030,7 +20457,7 @@ var MemoryService = class _MemoryService {
20030
20457
  const domain = this.inTransaction(trx);
20031
20458
  for (const item of input.items)
20032
20459
  await domain.updateMemory(principal, {
20033
- operationId: randomUUID8(),
20460
+ operationId: randomUUID9(),
20034
20461
  ...item,
20035
20462
  projectId: input.projectId,
20036
20463
  capture: "explicit"
@@ -20807,11 +21234,33 @@ ${input.query}`.slice(-1e3) : input.query;
20807
21234
  if (created) currentTelemetry().capture("notebook_created");
20808
21235
  return result;
20809
21236
  }
21237
+ connectionState(connection) {
21238
+ return createHmac4("sha256", this.cursorSecret).update(
21239
+ JSON.stringify([
21240
+ "connection-review-v1",
21241
+ connection.accountId,
21242
+ connection.id,
21243
+ connection.clientId,
21244
+ connection.name,
21245
+ [...connection.capabilities].sort(),
21246
+ connection.personal,
21247
+ connection.allProjects,
21248
+ [...connection.projectIds].sort(),
21249
+ connection.expiresAt,
21250
+ connection.revokedAt,
21251
+ connection.authorizedAfter,
21252
+ connection.setup ?? null
21253
+ ])
21254
+ ).digest("hex");
21255
+ }
20810
21256
  async connections(principal) {
20811
21257
  return this.access(
20812
21258
  principal,
20813
21259
  "admin",
20814
- async ({ trx }) => trx("connections").orderBy("createdAt", "desc").limit(100)
21260
+ async ({ trx }) => (await trx("connections").orderBy("createdAt", "desc").limit(100)).map((connection) => ({
21261
+ ...connection,
21262
+ state: this.connectionState(connection)
21263
+ }))
20815
21264
  );
20816
21265
  }
20817
21266
  async grant(principal, input, options = {}) {
@@ -20831,6 +21280,12 @@ ${input.query}`.slice(-1e3) : input.query;
20831
21280
  const old = await trx("connections").where({ id: options.id }).forUpdate().first();
20832
21281
  if (!old)
20833
21282
  throw new GroveError("not_found", "Connection not found", 404);
21283
+ if (options.expectedState && options.expectedState !== this.connectionState(old))
21284
+ throw new GroveError(
21285
+ "connection_conflict",
21286
+ "Connection access changed. Close this dialog, refresh Connections, and review the current permissions before saving.",
21287
+ 409
21288
+ );
20834
21289
  if (old.revokedAt && !old.clientId)
20835
21290
  throw new GroveError(
20836
21291
  "connection_revoked",
@@ -20855,7 +21310,7 @@ ${input.query}`.slice(-1e3) : input.query;
20855
21310
  }).returning("*");
20856
21311
  }
20857
21312
  if (!options.key) return { connection };
20858
- const id = randomUUID8();
21313
+ const id = randomUUID9();
20859
21314
  const secret = `grv_${id}_${randomBytes2(32).toString("base64url")}`;
20860
21315
  await trx("api_keys").insert({
20861
21316
  id,
@@ -21241,6 +21696,7 @@ var Billing = class {
21241
21696
  ) : [];
21242
21697
  return {
21243
21698
  enabled,
21699
+ units: billingUnits,
21244
21700
  ...state,
21245
21701
  prices,
21246
21702
  proLimits: this.options.proLimits ?? billingLimits.pro
@@ -21277,7 +21733,7 @@ var Billing = class {
21277
21733
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
21278
21734
  checkoutId: null,
21279
21735
  checkoutPrice: price.id,
21280
- checkoutOperation: randomUUID9()
21736
+ checkoutOperation: randomUUID10()
21281
21737
  });
21282
21738
  }
21283
21739
  if (!row.checkoutPrice)
@@ -21327,7 +21783,7 @@ var Billing = class {
21327
21783
  await trx("billing_customers").where({ accountId: principal.accountId }).update({
21328
21784
  checkoutId: null,
21329
21785
  checkoutPrice: null,
21330
- checkoutOperation: randomUUID9()
21786
+ checkoutOperation: randomUUID10()
21331
21787
  });
21332
21788
  return null;
21333
21789
  }
@@ -21405,6 +21861,79 @@ var Billing = class {
21405
21861
  }
21406
21862
  };
21407
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
+
21408
21937
  // packages/api/src/billing-pricing.ts
21409
21938
  init_define_GROVE_TELEMETRY();
21410
21939
  var MonthlyPricing = class {
@@ -21479,7 +22008,7 @@ import { pipeline as pipeline2 } from "node:stream/promises";
21479
22008
 
21480
22009
  // lib/telemetry/src/index.ts
21481
22010
  init_define_GROVE_TELEMETRY();
21482
- import { createHmac as createHmac5, randomUUID as randomUUID11 } from "node:crypto";
22011
+ import { createHmac as createHmac5, randomUUID as randomUUID12 } from "node:crypto";
21483
22012
  import { performance as performance2 } from "node:perf_hooks";
21484
22013
 
21485
22014
  // node_modules/.pnpm/posthog-node@5.56.2_@opentelemetry+api@1.10.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs
@@ -37097,7 +37626,7 @@ function safeMetric(metric, identity) {
37097
37626
 
37098
37627
  // lib/telemetry/src/preference.ts
37099
37628
  init_define_GROVE_TELEMETRY();
37100
- import { randomUUID as randomUUID10 } from "node:crypto";
37629
+ import { randomUUID as randomUUID11 } from "node:crypto";
37101
37630
  import {
37102
37631
  chmodSync,
37103
37632
  closeSync,
@@ -37148,7 +37677,7 @@ function installationIdentity(directory = telemetryDirectory()) {
37148
37677
  try {
37149
37678
  const fd = openSync(path, "wx", 384);
37150
37679
  try {
37151
- writeFileSync(fd, `${randomUUID10()}
37680
+ writeFileSync(fd, `${randomUUID11()}
37152
37681
  `);
37153
37682
  } finally {
37154
37683
  closeSync(fd);
@@ -37512,7 +38041,7 @@ function telemetry(surface) {
37512
38041
  const server = surface === "api" || surface === "worker";
37513
38042
  const enabled = build.enabled && !environmentDisabled() && (!server || process.env.GROVE_TELEMETRY_ENABLED === "true");
37514
38043
  const directory = telemetryDirectory();
37515
- const identity = enabled ? server ? randomUUID11() : installationIdentity(directory) : "";
38044
+ const identity = enabled ? server ? randomUUID12() : installationIdentity(directory) : "";
37516
38045
  reporter = new Reporter({
37517
38046
  ...build,
37518
38047
  enabled,
@@ -37535,7 +38064,7 @@ var closeTelemetry = (timeoutMs = 550) => Promise.allSettled(
37535
38064
  // packages/api/src/app.ts
37536
38065
  import { Hono } from "hono";
37537
38066
  import { cors } from "hono/cors";
37538
- import { z as z16, ZodError as ZodError2 } from "zod";
38067
+ import { z as z18, ZodError as ZodError2 } from "zod";
37539
38068
  import { Webhook } from "svix";
37540
38069
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
37541
38070
 
@@ -37555,6 +38084,7 @@ function createMemoryMcp(execute) {
37555
38084
  server.registerTool(
37556
38085
  name,
37557
38086
  {
38087
+ title: tool.title,
37558
38088
  description: tool.description,
37559
38089
  inputSchema: tool.schema.shape,
37560
38090
  annotations: {
@@ -37685,7 +38215,7 @@ var defaultCapacity = {
37685
38215
 
37686
38216
  // packages/api/src/media-images.ts
37687
38217
  init_define_GROVE_TELEMETRY();
37688
- import { createHash as createHash12 } from "node:crypto";
38218
+ import { createHash as createHash13 } from "node:crypto";
37689
38219
  import sharp from "sharp";
37690
38220
 
37691
38221
  // packages/api/src/media-input.ts
@@ -37778,7 +38308,7 @@ async function verifyImage(source3, declaredMime, signal) {
37778
38308
  mime,
37779
38309
  width: meta.width,
37780
38310
  height: meta.height,
37781
- sha256: createHash12("sha256").update(bytes).digest("hex")
38311
+ sha256: createHash13("sha256").update(bytes).digest("hex")
37782
38312
  };
37783
38313
  } catch (error3) {
37784
38314
  signal.throwIfAborted();
@@ -37791,7 +38321,7 @@ async function verifyImage(source3, declaredMime, signal) {
37791
38321
 
37792
38322
  // packages/api/src/media-audio.ts
37793
38323
  init_define_GROVE_TELEMETRY();
37794
- import { createHash as createHash13 } from "node:crypto";
38324
+ import { createHash as createHash14 } from "node:crypto";
37795
38325
  async function verifyAudio(source3, signal) {
37796
38326
  const fail = () => new GroveError(
37797
38327
  "invalid_audio",
@@ -37827,7 +38357,7 @@ async function verifyAudio(source3, signal) {
37827
38357
  return {
37828
38358
  bytes,
37829
38359
  mime: "audio/wav",
37830
- sha256: createHash13("sha256").update(bytes).digest("hex"),
38360
+ sha256: createHash14("sha256").update(bytes).digest("hex"),
37831
38361
  width: 0,
37832
38362
  height: 0,
37833
38363
  durationMs
@@ -37836,7 +38366,7 @@ async function verifyAudio(source3, signal) {
37836
38366
 
37837
38367
  // packages/api/src/media-archive.ts
37838
38368
  init_define_GROVE_TELEMETRY();
37839
- import { createHash as createHash14 } from "node:crypto";
38369
+ import { createHash as createHash15 } from "node:crypto";
37840
38370
  import { Readable } from "node:stream";
37841
38371
  function header(name, size) {
37842
38372
  if (!/^(note\.md|manifest\.json|media\/[0-9a-f-]+\.(png|jpeg|webp|wav|txt))$/.test(
@@ -37943,7 +38473,7 @@ async function noteArchive(service, media, principal, id, expectedVersion, signa
37943
38473
  for (const object of objects) {
37944
38474
  await recheck();
37945
38475
  yield header(object.path, object.bytes);
37946
- const stream = await media.read(object.key, signal), hash3 = createHash14("sha256");
38476
+ const stream = await media.read(object.key, signal), hash3 = createHash15("sha256");
37947
38477
  let bytes = 0, checked = Date.now();
37948
38478
  for await (const chunk of stream) {
37949
38479
  signal.throwIfAborted();
@@ -37993,7 +38523,7 @@ function createApp(deps) {
37993
38523
  capacity.queueTimeoutMs
37994
38524
  );
37995
38525
  app.use("*", async (c, next) => {
37996
- c.set("requestId", randomUUID12());
38526
+ c.set("requestId", randomUUID13());
37997
38527
  c.header("X-Request-ID", c.get("requestId"));
37998
38528
  c.header("Cache-Control", "private, no-store");
37999
38529
  c.header("X-Content-Type-Options", "nosniff");
@@ -38117,6 +38647,11 @@ function createApp(deps) {
38117
38647
  };
38118
38648
  app.get("/.well-known/oauth-protected-resource/mcp", (c) => c.json(metadata));
38119
38649
  app.get("/.well-known/oauth-protected-resource", (c) => c.json(metadata));
38650
+ app.get("/.well-known/openai-apps-challenge", (c) => {
38651
+ if (!deps.openaiAppsChallenge) return c.notFound();
38652
+ c.header("Cache-Control", "no-store");
38653
+ return c.text(deps.openaiAppsChallenge);
38654
+ });
38120
38655
  app.get("/health/live", (c) => c.json({ status: "ok" }));
38121
38656
  app.get("/health/ready", async (c) => {
38122
38657
  await deps.ready();
@@ -38140,13 +38675,13 @@ function createApp(deps) {
38140
38675
  400
38141
38676
  );
38142
38677
  }
38143
- const payload = z16.object({
38144
- type: z16.string(),
38145
- timestamp: z16.number().int(),
38146
- data: z16.object({
38147
- id: z16.string().min(1),
38148
- banned: z16.boolean().optional(),
38149
- 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()
38150
38685
  })
38151
38686
  }).parse(event);
38152
38687
  await deps.memories.db.transaction(async (trx) => {
@@ -38187,6 +38722,38 @@ function createApp(deps) {
38187
38722
  });
38188
38723
  app.use("/mcp", authorize);
38189
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
+ );
38190
38757
  app.post("/v1/webhooks/stripe", async (c) => {
38191
38758
  if (!deps.billing)
38192
38759
  throw new GroveError("billing_disabled", "Billing is unavailable", 503);
@@ -38206,9 +38773,9 @@ function createApp(deps) {
38206
38773
  async (c) => c.json({ success: true, data: await billing2().status(c.get("principal")) })
38207
38774
  );
38208
38775
  app.post("/v1/billing/checkout", async (c) => {
38209
- const input = z16.object({
38210
- interval: z16.enum(["month", "year"]),
38211
- expectedAmount: z16.number().int().positive().optional()
38776
+ const input = z18.object({
38777
+ interval: z18.enum(["month", "year"]),
38778
+ expectedAmount: z18.number().int().positive().optional()
38212
38779
  }).strict().parse(await c.req.json());
38213
38780
  return c.json({
38214
38781
  success: true,
@@ -38247,7 +38814,7 @@ function createApp(deps) {
38247
38814
  service,
38248
38815
  c.get("principal"),
38249
38816
  c.req.param("tool"),
38250
- await mutation(c, z16.record(z16.string(), z16.unknown())),
38817
+ await mutation(c, z18.record(z18.string(), z18.unknown())),
38251
38818
  c.get("signal")
38252
38819
  )
38253
38820
  })
@@ -38259,7 +38826,7 @@ function createApp(deps) {
38259
38826
  "Media storage is not configured",
38260
38827
  503
38261
38828
  );
38262
- 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;
38263
38830
  const cancelled = new AbortController(), signal = AbortSignal.any([c.get("signal"), cancelled.signal]);
38264
38831
  const source3 = await noteArchive(
38265
38832
  service,
@@ -38293,10 +38860,10 @@ function createApp(deps) {
38293
38860
  const input = {
38294
38861
  id: uuidSchema.parse(c.req.param("id")),
38295
38862
  memoryId: uuidSchema.parse(c.req.param("memoryId")),
38296
- version: z16.coerce.number().int().positive().parse(c.req.header("x-grove-note-version")),
38297
- bytes: z16.coerce.number().int().min(1).max(imageLimits.bytes).parse(c.req.header("content-length")),
38298
- mime: z16.enum(mediaMimeTypes).parse(c.req.header("content-type")),
38299
- 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"))
38300
38867
  };
38301
38868
  const claim = await attachments.claim(principal, input);
38302
38869
  if (claim.replay)
@@ -38399,7 +38966,7 @@ function createApp(deps) {
38399
38966
  };
38400
38967
  app.get("/v1/memories/:memoryId/media/:id", async (c) => {
38401
38968
  const memoryId = uuidSchema.parse(c.req.param("memoryId")), id = uuidSchema.parse(c.req.param("id"));
38402
- 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;
38403
38970
  return mediaResponse(
38404
38971
  c,
38405
38972
  () => attachments.read(c.get("principal"), memoryId, id, version2)
@@ -38430,7 +38997,7 @@ function createApp(deps) {
38430
38997
  })
38431
38998
  );
38432
38999
  app.post("/v1/speech/:id/cancel", async (c) => {
38433
- await mutation(c, z16.object({}).strict());
39000
+ await mutation(c, z18.object({}).strict());
38434
39001
  return c.json({
38435
39002
  success: true,
38436
39003
  data: await speech2.cancel(
@@ -38468,10 +39035,10 @@ function createApp(deps) {
38468
39035
  uuidSchema.parse(c.req.param("id")),
38469
39036
  await body(
38470
39037
  c,
38471
- z16.object({
38472
- operationId: z16.uuid(),
38473
- expectedVersion: z16.number().int().min(0),
38474
- 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)
38475
39042
  }).strict()
38476
39043
  )
38477
39044
  )
@@ -38624,7 +39191,7 @@ function createApp(deps) {
38624
39191
  })
38625
39192
  );
38626
39193
  app.post("/v1/connect/:id/cancel", async (c) => {
38627
- await body(c, z16.object({}).strict());
39194
+ await body(c, z18.object({}).strict());
38628
39195
  return c.json({
38629
39196
  success: true,
38630
39197
  data: await setup.cancel(
@@ -38639,7 +39206,7 @@ function createApp(deps) {
38639
39206
  success: true,
38640
39207
  data: await service.projects(
38641
39208
  c.get("principal"),
38642
- z16.enum(["active", "archived"]).parse(c.req.query("status") ?? "active")
39209
+ z18.enum(["active", "archived"]).parse(c.req.query("status") ?? "active")
38643
39210
  )
38644
39211
  })
38645
39212
  );
@@ -38719,7 +39286,7 @@ function createApp(deps) {
38719
39286
  app.post("/v1/models/test", async (c) => {
38720
39287
  const input = await body(
38721
39288
  c,
38722
- z16.object({ role: z16.enum(["embedding", "decision", "generation"]) }).strict()
39289
+ z18.object({ role: z18.enum(["embedding", "decision", "generation"]) }).strict()
38723
39290
  );
38724
39291
  if (!deps.models)
38725
39292
  throw new GroveError(
@@ -38917,14 +39484,14 @@ function createApp(deps) {
38917
39484
  data: await service.sourceRevision(
38918
39485
  c.get("principal"),
38919
39486
  uuidSchema.parse(c.req.param("id")),
38920
- 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"))
38921
39488
  )
38922
39489
  })
38923
39490
  );
38924
39491
  app.post("/v1/memories/:id/reprocess", async (c) => {
38925
39492
  const input = await body(
38926
39493
  c,
38927
- z16.object({ expectedVersion: z16.number().int().positive() }).strict()
39494
+ z18.object({ expectedVersion: z18.number().int().positive() }).strict()
38928
39495
  );
38929
39496
  return c.json({
38930
39497
  success: true,
@@ -38990,6 +39557,16 @@ function createApp(deps) {
38990
39557
  )
38991
39558
  })
38992
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
+ );
38993
39570
  app.patch(
38994
39571
  "/v1/conversations/:id/tools",
38995
39572
  async (c) => c.json({
@@ -39018,7 +39595,7 @@ function createApp(deps) {
39018
39595
  success: true,
39019
39596
  data: await service.conversations.list(
39020
39597
  c.get("principal"),
39021
- z16.uuid().optional().parse(c.req.query("after"))
39598
+ z18.uuid().optional().parse(c.req.query("after"))
39022
39599
  )
39023
39600
  })
39024
39601
  );
@@ -39065,8 +39642,8 @@ function createApp(deps) {
39065
39642
  })
39066
39643
  );
39067
39644
  app.post("/v1/conversations/:id/turns/:turnId/:action", async (c) => {
39068
- const action = z16.enum(["apply", "undo"]).parse(c.req.param("action"));
39069
- 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());
39070
39647
  return c.json({
39071
39648
  success: true,
39072
39649
  data: await service.conversations.apply(
@@ -39102,17 +39679,16 @@ function createApp(deps) {
39102
39679
  data: await service.grant(c.get("principal"), grant, { clientId })
39103
39680
  });
39104
39681
  });
39105
- app.patch(
39106
- "/v1/connections/:id",
39107
- async (c) => c.json({
39682
+ app.patch("/v1/connections/:id", async (c) => {
39683
+ const { expectedState, ...grant } = await body(c, connectionUpdateSchema);
39684
+ return c.json({
39108
39685
  success: true,
39109
- data: await service.grant(
39110
- c.get("principal"),
39111
- await body(c, grantSchema),
39112
- { id: uuidSchema.parse(c.req.param("id")) }
39113
- )
39114
- })
39115
- );
39686
+ data: await service.grant(c.get("principal"), grant, {
39687
+ id: uuidSchema.parse(c.req.param("id")),
39688
+ expectedState
39689
+ })
39690
+ });
39691
+ });
39116
39692
  app.delete(
39117
39693
  "/v1/connections/:id",
39118
39694
  async (c) => c.json({
@@ -39157,7 +39733,7 @@ function createApp(deps) {
39157
39733
  app.post("/v1/account/delete", async (c) => {
39158
39734
  await body(
39159
39735
  c,
39160
- z16.object({ confirm: z16.literal("delete my account") }).strict()
39736
+ z18.object({ confirm: z18.literal("delete my account") }).strict()
39161
39737
  );
39162
39738
  return c.json(
39163
39739
  { success: true, data: await service.deleteAccount(c.get("principal")) },
@@ -39206,7 +39782,7 @@ function createApp(deps) {
39206
39782
  success: true,
39207
39783
  data: await tasks.list(
39208
39784
  c.get("principal"),
39209
- z16.uuid().optional().parse(c.req.query("projectId"))
39785
+ z18.uuid().optional().parse(c.req.query("projectId"))
39210
39786
  )
39211
39787
  })
39212
39788
  );
@@ -39285,11 +39861,22 @@ function createApp(deps) {
39285
39861
  });
39286
39862
  app.all("/mcp", async (c) => {
39287
39863
  const principal = c.get("principal");
39288
- await service.me(principal);
39289
- const execute = async (tool, value, signal) => withDatabaseSignal(
39290
- AbortSignal.any([databaseSignal(), ...signal ? [signal] : []]),
39291
- () => executeMemoryTool(service, principal, tool, value, signal)
39292
- );
39864
+ const identity = await service.me(principal);
39865
+ const execute = async (tool, value, signal) => {
39866
+ if (principal.type === "oauth" && !identity.capabilities.length) {
39867
+ const approval = new URL("/app/settings/connections", deps.siteUrl);
39868
+ approval.hash = `connection-${principal.connectionId}`;
39869
+ throw new GroveError(
39870
+ "connection_required",
39871
+ `Sign-in is complete. Approve OAuth client ${principal.clientId} in Grove Connections: ${approval.href} . Use the same Grove account, then return to your chat and retry. Sign-in alone grants no note access.`,
39872
+ 403
39873
+ );
39874
+ }
39875
+ return withDatabaseSignal(
39876
+ AbortSignal.any([databaseSignal(), ...signal ? [signal] : []]),
39877
+ () => executeMemoryTool(service, principal, tool, value, signal)
39878
+ );
39879
+ };
39293
39880
  const server = createMemoryMcp(execute);
39294
39881
  const transport = new WebStandardStreamableHTTPServerTransport({
39295
39882
  sessionIdGenerator: void 0,
@@ -39312,7 +39899,7 @@ function createApp(deps) {
39312
39899
 
39313
39900
  // packages/api/src/auth.ts
39314
39901
  init_define_GROVE_TELEMETRY();
39315
- import { createClerkClient } from "@clerk/backend";
39902
+ import { createClerkClient as createClerkClient2 } from "@clerk/backend";
39316
39903
  import { TokenVerificationError } from "@clerk/backend/errors";
39317
39904
  import { createRemoteJWKSet, decodeJwt, jwtVerify, errors } from "jose";
39318
39905
  var unauthorized = () => new GroveError("unauthorized", "Sign in to Grove", 401);
@@ -39321,7 +39908,7 @@ function clerkVerifier(env) {
39321
39908
  new URL("/.well-known/jwks.json", env.CLERK_ISSUER),
39322
39909
  { timeoutDuration: 5e3 }
39323
39910
  );
39324
- const clerk = createClerkClient({
39911
+ const clerk = createClerkClient2({
39325
39912
  secretKey: env.CLERK_SECRET_KEY,
39326
39913
  publishableKey: env.CLERK_PUBLISHABLE_KEY
39327
39914
  });
@@ -39471,103 +40058,125 @@ init_define_GROVE_TELEMETRY();
39471
40058
 
39472
40059
  // lib/environment/src/index.ts
39473
40060
  init_define_GROVE_TELEMETRY();
39474
- import { z as z17 } from "zod";
39475
- var origin = z17.url().transform((value, ctx) => {
40061
+ import { z as z19 } from "zod";
40062
+ var origin = z19.url().transform((value, ctx) => {
39476
40063
  const url = new URL(value);
39477
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))) {
39478
40065
  ctx.addIssue({
39479
40066
  code: "custom",
39480
40067
  message: "Use an HTTPS origin (HTTP is allowed on loopback)"
39481
40068
  });
39482
- return z17.NEVER;
40069
+ return z19.NEVER;
39483
40070
  }
39484
40071
  return url.origin;
39485
40072
  });
39486
- var allowance = (value) => z17.coerce.number().int().min(0).max(1e9).default(value);
39487
- var serverSchema = z17.object({
39488
- NODE_ENV: z17.enum(["development", "test", "production"]).default("development"),
39489
- PORT: z17.coerce.number().int().min(1).max(65535).default(26080),
39490
- DATABASE_URL: z17.string().min(1),
39491
- DATABASE_SSL: z17.enum(["require", "disable"]).default("disable"),
39492
- DATABASE_POOL_MAX: z17.coerce.number().int().min(1).max(64).default(8),
39493
- DATABASE_ACQUIRE_TIMEOUT_MS: z17.coerce.number().int().min(100).max(3e4).default(2e3),
39494
- DATABASE_STATEMENT_TIMEOUT_MS: z17.coerce.number().int().min(100).max(3e4).default(1e4),
39495
- API_MAX_IN_FLIGHT: z17.coerce.number().int().min(1).max(256).default(32),
39496
- API_MAX_QUEUED: z17.coerce.number().int().min(0).max(256).default(32),
39497
- API_QUEUE_TIMEOUT_MS: z17.coerce.number().int().min(1).max(5e3).default(250),
39498
- API_REQUEST_TIMEOUT_MS: z17.coerce.number().int().min(100).max(6e4).default(1e4),
39499
- API_INTERACTIVE_CONCURRENCY: z17.coerce.number().int().min(1).max(32).default(4),
39500
- 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),
39501
40088
  API_ORIGIN: origin,
39502
40089
  SITE_URL: origin,
39503
- CLERK_PUBLISHABLE_KEY: z17.string().startsWith("pk_"),
39504
- CLERK_SECRET_KEY: z17.string().startsWith("sk_"),
40090
+ // Public ownership proof, never an account credential. Empty values are omitted below.
40091
+ OPENAI_APPS_CHALLENGE: z19.string().min(1).max(512).refine(
40092
+ (value) => !/\s/.test(value),
40093
+ "Use the exact non-whitespace verification token"
40094
+ ).optional(),
40095
+ CLERK_PUBLISHABLE_KEY: z19.string().startsWith("pk_"),
40096
+ CLERK_SECRET_KEY: z19.string().startsWith("sk_"),
39505
40097
  CLERK_ISSUER: origin,
39506
- CLERK_WEBHOOK_SIGNING_SECRET: z17.string().min(1),
39507
- GROVE_EDITION: z17.enum(["self-hosted", "cloud"]).default("self-hosted"),
39508
- BILLING_CONFIGURED: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39509
- FLAGS: z17.string().min(1).optional(),
39510
- STRIPE_SECRET_KEY: z17.string().regex(/^(sk|rk)_(test|live)_/).optional(),
39511
- STRIPE_WEBHOOK_SECRET: z17.string().startsWith("whsec_").optional(),
39512
- STRIPE_PRO_PRODUCT_ID: z17.string().startsWith("prod_").optional(),
39513
- STRIPE_PORTAL_CONFIGURATION_ID: z17.string().startsWith("bpc_").optional(),
39514
- STRIPE_PRO_MONTHLY_PRICE_ID: z17.string().startsWith("price_").optional(),
39515
- STRIPE_PRO_YEARLY_PRICE_ID: z17.string().startsWith("price_").optional(),
39516
- BILLING_FREE_GENERATION_DAILY: allowance(10),
39517
- BILLING_FREE_GENERATION_MONTHLY: allowance(100),
39518
- BILLING_PRO_GENERATION_DAILY: allowance(200),
39519
- BILLING_PRO_GENERATION_MONTHLY: allowance(2e3),
39520
- BILLING_FREE_RESEARCH_DAILY: allowance(3),
39521
- BILLING_FREE_RESEARCH_MONTHLY: allowance(10),
39522
- BILLING_PRO_RESEARCH_DAILY: allowance(20),
39523
- BILLING_PRO_RESEARCH_MONTHLY: allowance(200),
39524
- BILLING_FREE_TRANSCRIPTION_MONTHLY_MS: allowance(6e5),
39525
- BILLING_PRO_TRANSCRIPTION_MONTHLY_MS: allowance(72e5),
39526
- BILLING_FREE_SYNTHESIS_MONTHLY_CHARACTERS: allowance(1e4),
39527
- BILLING_PRO_SYNTHESIS_MONTHLY_CHARACTERS: allowance(2e5),
39528
- EMBEDDING_MODE: z17.enum(["local", "remote", "disabled"]).optional(),
39529
- EMBEDDING_CACHE: z17.string().default("./data/models"),
39530
- EMBEDDING_URL: z17.string().optional(),
39531
- EMBEDDING_MODEL: z17.string().optional(),
39532
- EMBEDDING_API_KEY: z17.string().optional(),
39533
- EMBEDDING_DIMENSIONS: z17.coerce.number().int().min(32).max(16e3).optional(),
39534
- EMBEDDING_QUERY_PREFIX: z17.string().optional(),
39535
- EMBEDDING_DOCUMENT_PREFIX: z17.string().optional(),
39536
- EMBEDDING_DISTANCE_THRESHOLD: z17.coerce.number().min(0).max(2).optional(),
39537
- DECISION_PROVIDER: z17.enum(["system-one", "disabled"]).default("disabled"),
39538
- DECISION_URL: z17.string().optional(),
39539
- DECISION_MODEL: z17.string().optional(),
39540
- DECISION_API_KEY: z17.string().optional(),
39541
- DECISION_PATH: z17.enum(["/decisions", "/systemone"]).default("/decisions"),
39542
- GENERATION_PROVIDER: z17.enum(["minimax", "openai-compatible", "disabled"]).default("disabled"),
39543
- GENERATION_URL: z17.string().optional(),
39544
- GENERATION_MODEL: z17.string().optional(),
39545
- GENERATION_API_KEY: z17.string().optional(),
39546
- GENERATION_OUTPUT_FORMAT: z17.enum(["tool", "json-schema", "json"]).default("tool"),
39547
- GENERATION_REASONING_EFFORT: z17.enum(["low", "medium", "high", "omit"]).default("low"),
39548
- GENERATION_MAX_OUTPUT_TOKENS: z17.coerce.number().int().min(256).max(16384).default(4096),
39549
- DEEPINFRA_API_KEY: z17.string().optional(),
39550
- MINIMAX_API_KEY: z17.string().optional(),
39551
- OPENAI_API_KEY: z17.string().optional(),
39552
- SPEECH_ENABLED: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39553
- TTS_VOICE: z17.enum(["alloy", "echo", "fable", "onyx", "nova", "shimmer"]).default("alloy"),
39554
- MINIMAX_TTS_ENABLED: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39555
- SPEECH_PROVIDER_CONCURRENCY: z17.coerce.number().int().min(1).max(16).default(2),
39556
- EXA_API_KEY: z17.string().optional(),
39557
- TAVILY_API_KEY: z17.string().optional(),
39558
- RESEARCH_DAILY_CALL_LIMIT: z17.coerce.number().int().min(1).max(1e4).default(20),
39559
- RESEARCH_MONTHLY_BUDGET_USD: z17.coerce.number().min(0).max(1e5).default(100),
39560
- MODEL_ADMIN_SUBJECTS: z17.string().default(""),
39561
- MODEL_SETTINGS_KEY: z17.string().regex(/^[0-9a-f]{64}$/i).optional(),
39562
- AI_DAILY_REQUEST_LIMIT: z17.coerce.number().int().min(1).max(1e6).default(2e3),
39563
- AI_CONCURRENCY: z17.coerce.number().int().min(1).max(32).default(4),
39564
- INDEXING_CONCURRENCY: z17.coerce.number().int().min(0).max(32).default(2),
39565
- EMAIL_CONCURRENCY: z17.coerce.number().int().min(0).max(8).default(1),
39566
- MAINTENANCE_CONCURRENCY: z17.coerce.number().int().min(0).max(8).default(1),
39567
- BULK_CONCURRENCY: z17.coerce.number().int().min(0).max(8).default(1),
39568
- JOB_ACCOUNT_CONCURRENCY: z17.coerce.number().int().min(1).max(8).default(2),
39569
- JOB_PROVIDER_CONCURRENCY: z17.coerce.number().int().min(1).max(128).default(8),
39570
- 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(
39571
40180
  (value) => value.split(",").every(
39572
40181
  (lane) => ["indexing", "enrichment", "email", "maintenance", "bulk"].includes(
39573
40182
  lane
@@ -39575,38 +40184,47 @@ var serverSchema = z17.object({
39575
40184
  ),
39576
40185
  "Unknown worker lane"
39577
40186
  ),
39578
- WORKER_LEGACY_QUEUE: z17.enum(["true", "false"]).default("true").transform((value) => value === "true"),
39579
- 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(),
39580
40189
  // Explicit opt-in until the revision-scoped media API is available.
39581
- MEDIA_STORAGE: z17.enum(["disabled", "local", "s3"]).default("disabled"),
39582
- MEDIA_DIRECTORY: z17.string().default("./data/media"),
39583
- MEDIA_S3_ENDPOINT: z17.url().optional(),
39584
- MEDIA_S3_REGION: z17.string().default("us-east-1"),
39585
- MEDIA_S3_BUCKET: z17.string().optional(),
39586
- MEDIA_S3_ACCESS_KEY_ID: z17.string().optional(),
39587
- 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(),
39588
40197
  // Exact endpoint/bucket receipt from an operator lifecycle/ACL inspection.
39589
40198
  // Spaces scoped keys cannot read these settings; never use an account-wide key in runtime.
39590
- MEDIA_S3_LIFECYCLE_VERIFIED_FOR: z17.string().optional(),
39591
- MEDIA_S3_PATH_STYLE: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39592
- EXPORT_DIRECTORY: z17.string().default("./data/exports"),
39593
- EXPORT_S3_ENDPOINT: z17.url().optional(),
39594
- EXPORT_S3_REGION: z17.string().default("us-east-1"),
39595
- EXPORT_S3_BUCKET: z17.string().optional(),
39596
- EXPORT_S3_ACCESS_KEY_ID: z17.string().optional(),
39597
- EXPORT_S3_SECRET_ACCESS_KEY: z17.string().optional(),
39598
- EXPORT_S3_PATH_STYLE: z17.enum(["true", "false"]).default("false").transform((value) => value === "true"),
39599
- 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(
39600
40209
  (value) => new URL(value).protocol === "amqps:",
39601
40210
  "Use TLS for the job broker"
39602
40211
  ).optional(),
39603
- ORGANIZATION_INTERVAL_SECONDS: z17.coerce.number().int().min(60).max(86400).default(900),
39604
- RESEND_API_KEY: z17.string().startsWith("re_").optional(),
39605
- EMAIL_FROM: z17.string().email().default("notifications@mail.usegrove.cloud"),
39606
- CURSOR_SECRET: z17.string().min(32),
39607
- 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()
39608
40217
  });
39609
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
+ }
39610
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))
39611
40229
  ctx.addIssue({
39612
40230
  code: "custom",
@@ -39623,6 +40241,9 @@ function readServerEnvironment(env = process.env) {
39623
40241
  );
39624
40242
  }
39625
40243
 
40244
+ // packages/api/src/runtime.ts
40245
+ import { createClient as createClient2 } from "@vercel/flags-core";
40246
+
39626
40247
  // packages/api/src/models.ts
39627
40248
  init_define_GROVE_TELEMETRY();
39628
40249
  import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, randomBytes as randomBytes3 } from "node:crypto";
@@ -39966,7 +40587,7 @@ function createBilling(env, service) {
39966
40587
  },
39967
40588
  synthesis: {
39968
40589
  daily: null,
39969
- monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_CHARACTERS`]
40590
+ monthly: env[`BILLING_${tier}_SYNTHESIS_MONTHLY_MS`]
39970
40591
  }
39971
40592
  });
39972
40593
  const prices = {
@@ -40021,7 +40642,7 @@ import {
40021
40642
  import { Upload } from "@aws-sdk/lib-storage";
40022
40643
  var validateKey2 = (key2) => {
40023
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}";
40024
- 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))
40025
40646
  throw new Error("invalid_artifact_key");
40026
40647
  return key2;
40027
40648
  };
@@ -40077,7 +40698,7 @@ function s3Artifacts(client, bucket) {
40077
40698
  Bucket: bucket,
40078
40699
  Key: validateKey2(key2),
40079
40700
  Body: data,
40080
- ContentType: key2.startsWith("speech/") ? "audio/mpeg" : "application/x-ndjson",
40701
+ ContentType: key2.endsWith(".mp3") ? "audio/mpeg" : "application/x-ndjson",
40081
40702
  CacheControl: "private, no-store"
40082
40703
  };
40083
40704
  if (Buffer.isBuffer(data)) {
@@ -40151,7 +40772,7 @@ function createArtifacts(env) {
40151
40772
  init_define_GROVE_TELEMETRY();
40152
40773
  import { constants as constants3 } from "node:fs";
40153
40774
  import { link, lstat, mkdir as mkdir2, open as open2, realpath, unlink as unlink2 } from "node:fs/promises";
40154
- import { randomUUID as randomUUID13 } from "node:crypto";
40775
+ import { randomUUID as randomUUID14 } from "node:crypto";
40155
40776
  import { dirname as dirname4, resolve as resolve3, sep as sep4 } from "node:path";
40156
40777
  import { Readable as Readable4 } from "node:stream";
40157
40778
  import {
@@ -40212,7 +40833,7 @@ function localMedia(root) {
40212
40833
  signal.throwIfAborted();
40213
40834
  validImage(image);
40214
40835
  const target = await directories(key2, true);
40215
- const temporary = `${target}.${randomUUID13()}.partial`;
40836
+ const temporary = `${target}.${randomUUID14()}.partial`;
40216
40837
  const file = await open2(
40217
40838
  temporary,
40218
40839
  constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW,
@@ -40271,7 +40892,7 @@ function s3Media(client, bucket, spacesLifecycleVerified = false) {
40271
40892
  if (name !== "NoSuchLifecycleConfiguration" && !(name === "AccessDenied" && spacesLifecycleVerified))
40272
40893
  throw error3;
40273
40894
  }
40274
- const probe = `media-probes/${randomUUID13()}`;
40895
+ const probe = `media-probes/${randomUUID14()}`;
40275
40896
  try {
40276
40897
  const put = (body) => client.send(
40277
40898
  new PutObjectCommand2({
@@ -40390,6 +41011,9 @@ async function createRuntime() {
40390
41011
  "SELECT transcription_enabled,read_aloud_enabled,read_aloud_voice_id FROM accounts LIMIT 0"
40391
41012
  );
40392
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
+ );
40393
41017
  if (env.MEDIA_STORAGE !== "disabled") {
40394
41018
  await db.raw(
40395
41019
  "SELECT status,lease_id,object_key,duration_ms FROM media_objects LIMIT 0"
@@ -40433,42 +41057,23 @@ async function createRuntime() {
40433
41057
  artifacts?.close?.();
40434
41058
  throw error3;
40435
41059
  }
40436
- let speech2 = {};
40437
- if (env.SPEECH_ENABLED) {
40438
- if (!env.OPENAI_API_KEY?.trim()) {
40439
- artifacts?.close?.();
40440
- media?.close?.();
40441
- throw new Error("speech_api_key_required");
40442
- }
40443
- const remote = createOpenAiSpeech({
40444
- apiKey: env.OPENAI_API_KEY,
40445
- voice: env.TTS_VOICE
40446
- });
40447
- speech2 = {
40448
- ...media ? { transcription: remote.transcription } : {},
40449
- ...artifacts ? { synthesis: { reed: remote.synthesis } } : {}
40450
- };
40451
- if (env.MINIMAX_TTS_ENABLED) {
40452
- if (!env.MINIMAX_API_KEY?.trim() || !artifacts) {
40453
- artifacts?.close?.();
40454
- media?.close?.();
40455
- throw new Error("minimax_speech_key_and_storage_required");
40456
- }
40457
- speech2.synthesis = {
40458
- ...speech2.synthesis,
40459
- ...Object.fromEntries(
40460
- Object.entries(miniMaxSpeechVoices).map(([id, voice]) => [
40461
- id,
40462
- {
40463
- ...createMiniMaxSpeech({ apiKey: env.MINIMAX_API_KEY, voice }),
40464
- sampleId: `${id}-v1`
40465
- }
40466
- ])
40467
- )
40468
- };
40469
- }
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;
40470
41076
  }
40471
- const billingRuntime = createBilling(env, memories);
40472
41077
  return {
40473
41078
  env,
40474
41079
  db,
@@ -40479,6 +41084,7 @@ async function createRuntime() {
40479
41084
  speech: speech2,
40480
41085
  billing: billingRuntime?.billing,
40481
41086
  close: async () => {
41087
+ await speechFlags?.shutdown();
40482
41088
  await billingRuntime?.close();
40483
41089
  artifacts?.close?.();
40484
41090
  media?.close?.();
@@ -40490,6 +41096,37 @@ async function createRuntime() {
40490
41096
  throw error3;
40491
41097
  }
40492
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
+ }
40493
41130
 
40494
41131
  // packages/api/src/server.ts
40495
41132
  async function startServer() {
@@ -40498,6 +41135,7 @@ async function startServer() {
40498
41135
  await configureSpeech(db, runtime.speech);
40499
41136
  const reporter = telemetry("api");
40500
41137
  const app = createApp({
41138
+ adminDirectory: clerkAdminDirectory(env.CLERK_SECRET_KEY),
40501
41139
  memories,
40502
41140
  models: runtime.models,
40503
41141
  artifacts: runtime.artifacts,
@@ -40514,6 +41152,7 @@ async function startServer() {
40514
41152
  ),
40515
41153
  origin: env.API_ORIGIN,
40516
41154
  siteUrl: env.SITE_URL,
41155
+ openaiAppsChallenge: env.OPENAI_APPS_CHALLENGE,
40517
41156
  issuer: env.CLERK_ISSUER,
40518
41157
  webhookSecret: env.CLERK_WEBHOOK_SIGNING_SECRET,
40519
41158
  ready: async () => {