@exulu/backend 4.2.0 → 4.3.0

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.
Files changed (3) hide show
  1. package/dist/index.cjs +391 -40
  2. package/dist/index.js +383 -40
  3. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -10800,6 +10800,10 @@ async function resolveEmbedder(input) {
10800
10800
  };
10801
10801
  }
10802
10802
 
10803
+ // types/rbac-rights-modes.ts
10804
+ init_cjs_shims();
10805
+ var VALID_RIGHTS_MODES = ["private", "users", "roles", "teams", "public"];
10806
+
10803
10807
  // src/exulu/context.ts
10804
10808
  init_statistics2();
10805
10809
  init_statistics();
@@ -12419,7 +12423,14 @@ var transcriptionJobsSchema = {
12419
12423
  // when RECALL_STORE_VIDEO_LOCALLY=true. Null when that flag is off (the
12420
12424
  // video then stays reachable only via ExuluRecall.getRecordingVideoUrl,
12421
12425
  // for as long as Recall itself retains it) or for Whisper upload jobs.
12422
- { name: "video", type: "file" }
12426
+ { name: "video", type: "file" },
12427
+ // Live (browser-microphone) recordings — spec
12428
+ // docs/superpowers/specs/2026-09-23-live-recording-transcription-design.md §2.
12429
+ // chunk_count is the NEXT expected chunk seq; the chunk route appends with
12430
+ // a compare-and-swap on it, so retries and duplicates can never double-append.
12431
+ { name: "chunk_count", type: "number", default: 0 },
12432
+ // Heartbeat of the last accepted chunk; shown in the queue row.
12433
+ { name: "last_chunk_at", type: "date" }
12423
12434
  ]
12424
12435
  };
12425
12436
  var imageGenerationsSchema = {
@@ -14066,6 +14077,13 @@ var bullmqDecorator = async ({
14066
14077
  };
14067
14078
 
14068
14079
  // src/exulu/context.ts
14080
+ function sanitizeItemRightsMode(rightsMode, defaultMode) {
14081
+ if (rightsMode == null) return rightsMode;
14082
+ if (VALID_RIGHTS_MODES.includes(rightsMode)) {
14083
+ return rightsMode;
14084
+ }
14085
+ return defaultMode ?? "private";
14086
+ }
14069
14087
  var ExuluContext2 = class {
14070
14088
  // Must begin with a letter (a-z) or underscore (_). Subsequent characters in a name can be letters, digits (0-9), or
14071
14089
  // underscores and be a max length of 80 characters and at least 5 characters long.
@@ -14373,6 +14391,12 @@ var ExuluContext2 = class {
14373
14391
  if (upsert2 && !item.id && !item.external_id) {
14374
14392
  throw new Error("Item id or external id is required for upsert.");
14375
14393
  }
14394
+ if (item.rights_mode != null && !VALID_RIGHTS_MODES.includes(item.rights_mode)) {
14395
+ console.warn(
14396
+ `[EXULU] createItem: invalid rights_mode "${item.rights_mode}" for context "${this.id}" (item ${item.id ?? item.external_id ?? "(new)"}) \u2014 falling back to the configured default.`
14397
+ );
14398
+ }
14399
+ item.rights_mode = sanitizeItemRightsMode(item.rights_mode, this.configuration.defaultRightsMode);
14376
14400
  const { db: db2 } = await postgresClient();
14377
14401
  Object.keys(item).forEach((key) => {
14378
14402
  if (this.fields.find((field) => field.name === key)?.type === "json") {
@@ -16369,7 +16393,7 @@ var shouldGenerateEmbeddings = ({
16369
16393
  };
16370
16394
 
16371
16395
  // src/graphql/mutations/index.ts
16372
- var VALID_RIGHTS_MODES = ["private", "users", "roles", "teams", "public"];
16396
+ var VALID_RIGHTS_MODES2 = ["private", "users", "roles", "teams", "public"];
16373
16397
  var postprocessDeletion = async ({
16374
16398
  table,
16375
16399
  requestedFields,
@@ -16694,9 +16718,9 @@ function createMutations(table, contexts, tools, config) {
16694
16718
  input.id = db2.fn.uuid();
16695
16719
  }
16696
16720
  }
16697
- if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES.includes(input.rights_mode)) {
16721
+ if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES2.includes(input.rights_mode)) {
16698
16722
  throw new Error(
16699
- `Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES.join(", ")}`
16723
+ `Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
16700
16724
  );
16701
16725
  }
16702
16726
  const columns = await db2(tableNamePlural).columnInfo();
@@ -17276,9 +17300,9 @@ function createMutations(table, contexts, tools, config) {
17276
17300
  if (!Array.isArray(ids) || ids.length === 0) {
17277
17301
  throw new Error("ids is required and must be a non-empty array.");
17278
17302
  }
17279
- if (!VALID_RIGHTS_MODES.includes(rights_mode)) {
17303
+ if (!VALID_RIGHTS_MODES2.includes(rights_mode)) {
17280
17304
  throw new Error(
17281
- `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES.join(", ")}`
17305
+ `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
17282
17306
  );
17283
17307
  }
17284
17308
  for (const id of ids) {
@@ -21191,6 +21215,30 @@ var transcriptionService = {
21191
21215
  }
21192
21216
  };
21193
21217
 
21218
+ // src/exulu/transcription/authorize.ts
21219
+ init_cjs_shims();
21220
+ var TranscriptionJobAccessError = class extends Error {
21221
+ constructor(code, message) {
21222
+ super(message);
21223
+ this.code = code;
21224
+ this.name = "TranscriptionJobAccessError";
21225
+ }
21226
+ };
21227
+ async function assertOwnsTranscriptionJob(db2, user, id) {
21228
+ if (!user) throw new TranscriptionJobAccessError(403, "Authentication required");
21229
+ if (user.super_admin === true) return;
21230
+ const row = await db2.from("transcription_jobs").select(["created_by", "rights_mode"]).where({ id }).first();
21231
+ if (!row) throw new TranscriptionJobAccessError(404, `transcription_job ${id} not found`);
21232
+ if (row.rights_mode === "public") return;
21233
+ if (row.created_by != null && String(row.created_by) === String(user.id)) return;
21234
+ throw new TranscriptionJobAccessError(403, "Not authorized to act on this transcription job");
21235
+ }
21236
+
21237
+ // src/exulu/transcription/live-recording.ts
21238
+ init_cjs_shims();
21239
+ init_client();
21240
+ init_supervisor();
21241
+
21194
21242
  // src/exulu/recall/service.ts
21195
21243
  init_cjs_shims();
21196
21244
  var import_ai8 = require("ai");
@@ -22137,6 +22185,106 @@ ${transcriptText}`,
22137
22185
  }
22138
22186
  };
22139
22187
 
22188
+ // src/exulu/transcription/live-recording.ts
22189
+ var TABLE4 = "transcription_jobs";
22190
+ var log5 = (msg) => console.log(`[EXULU-LIVE-RECORDING] ${msg}`);
22191
+ var LIVE_RECORDING_DISABLED_MESSAGE = "Speech-to-text is not enabled on this deployment. Set EXULU_USE_LITELLM=true and TRANSCRIPTION_MODEL in the environment.";
22192
+ function liveRecordingEnabled() {
22193
+ return isLiteLLMEnabled() && Boolean(process.env.TRANSCRIPTION_MODEL);
22194
+ }
22195
+ var parseJson2 = (v) => {
22196
+ if (v == null) return null;
22197
+ if (typeof v === "string") {
22198
+ try {
22199
+ return JSON.parse(v);
22200
+ } catch {
22201
+ return null;
22202
+ }
22203
+ }
22204
+ return v;
22205
+ };
22206
+ var rowFromDb = (dbRow) => ({
22207
+ ...dbRow,
22208
+ chunk_count: Number(dbRow.chunk_count ?? 0),
22209
+ raw_segments: parseJson2(dbRow.raw_segments)
22210
+ });
22211
+ var liveRecordingService = {
22212
+ async start(input) {
22213
+ const { db: db2 } = await postgresClient();
22214
+ const now = /* @__PURE__ */ new Date();
22215
+ const [inserted] = await db2(TABLE4).insert({
22216
+ source: "live",
22217
+ status: "recording",
22218
+ chunk_count: 0,
22219
+ raw_segments: "[]",
22220
+ title: input.title?.trim() ? input.title.trim() : null,
22221
+ language: input.language && input.language !== "auto" ? input.language : null,
22222
+ project_id: input.project_id ?? null,
22223
+ target_rights_mode: input.target_rights_mode ?? "private",
22224
+ target_rbac_users: input.target_rbac_users ? JSON.stringify(input.target_rbac_users) : null,
22225
+ target_rbac_roles: input.target_rbac_roles ? JSON.stringify(input.target_rbac_roles) : null,
22226
+ // NULL when empty — mirrors recallService.createMeetingBot so
22227
+ // runPostProcessing's "no prompts" short-circuit works unchanged.
22228
+ post_processing_prompts: input.post_processing_prompts?.length ? JSON.stringify(input.post_processing_prompts) : null,
22229
+ rights_mode: "private",
22230
+ created_by: input.userId,
22231
+ createdAt: now,
22232
+ updatedAt: now
22233
+ }).returning("*");
22234
+ log5(`started live recording ${inserted.id} for user ${input.userId}`);
22235
+ return rowFromDb(inserted);
22236
+ },
22237
+ async appendChunk(input) {
22238
+ const { db: db2 } = await postgresClient();
22239
+ const segment = {
22240
+ start: input.offsetMs / 1e3,
22241
+ end: (input.offsetMs + input.durationMs) / 1e3,
22242
+ text: input.text,
22243
+ speaker: "unknown"
22244
+ };
22245
+ const affected = await db2(TABLE4).where({ id: input.id, status: "recording", chunk_count: input.seq }).update({
22246
+ raw_segments: db2.raw("COALESCE(raw_segments, '[]'::jsonb) || ?::jsonb", [
22247
+ JSON.stringify([segment])
22248
+ ]),
22249
+ chunk_count: input.seq + 1,
22250
+ duration_seconds: db2.raw("GREATEST(COALESCE(duration_seconds, 0), ?)", [segment.end]),
22251
+ last_chunk_at: /* @__PURE__ */ new Date(),
22252
+ updatedAt: /* @__PURE__ */ new Date()
22253
+ });
22254
+ if (affected === 1) return { kind: "appended", chunkCount: input.seq + 1 };
22255
+ const row = await db2(TABLE4).select(["status", "chunk_count", "raw_segments"]).where({ id: input.id }).first();
22256
+ if (!row) throw new Error(`transcription_job ${input.id} not found`);
22257
+ if (row.status !== "recording") return { kind: "not_recording", status: row.status };
22258
+ const chunkCount = Number(row.chunk_count ?? 0);
22259
+ if (chunkCount > input.seq) {
22260
+ const segments = parseJson2(row.raw_segments) ?? [];
22261
+ return { kind: "duplicate", text: segments[input.seq]?.text ?? "", chunkCount };
22262
+ }
22263
+ return { kind: "out_of_order", chunkCount };
22264
+ },
22265
+ async stop(id, input) {
22266
+ const { db: db2 } = await postgresClient();
22267
+ const patch = { status: "awaiting_review", updatedAt: /* @__PURE__ */ new Date() };
22268
+ if (input.audio_s3key) patch.audio_s3key = input.audio_s3key;
22269
+ if (typeof input.duration_seconds === "number" && input.duration_seconds > 0) {
22270
+ patch.duration_seconds = input.duration_seconds;
22271
+ }
22272
+ const [updated] = await db2(TABLE4).where({ id, status: "recording" }).update(patch).returning("*");
22273
+ if (!updated) {
22274
+ const row = await db2(TABLE4).where({ id }).first();
22275
+ if (!row) throw new Error(`transcription_job ${id} not found`);
22276
+ throw new Error(
22277
+ `transcription_job ${id} is in status '${row.status}'; can only stop from 'recording'`
22278
+ );
22279
+ }
22280
+ log5(`live recording ${id} stopped \u2192 awaiting_review`);
22281
+ void recallService.runPostProcessing(id).catch((err) => {
22282
+ log5(`post-processing for job ${id} failed: ${err.message}`);
22283
+ });
22284
+ return rowFromDb(updated);
22285
+ }
22286
+ };
22287
+
22140
22288
  // src/exulu/email-inbound/trigger-config.ts
22141
22289
  init_cjs_shims();
22142
22290
  var import_node_crypto9 = require("crypto");
@@ -22950,6 +23098,8 @@ type PageInfo {
22950
23098
  transcriptionJobCancel(id: ID!): transcription_job
22951
23099
  meetingBotStart(input: MeetingBotStartInput!): transcription_job
22952
23100
  runTranscriptPostProcessing(id: ID!, prompt_id: ID!, agent_id: ID!): transcription_job
23101
+ liveRecordingStart(input: LiveRecordingStartInput!): transcription_job
23102
+ liveRecordingStop(id: ID!, input: LiveRecordingStopInput): transcription_job
22953
23103
  `;
22954
23104
  mutationDefs += `
22955
23105
  upsertWorkflowEmailTrigger(workflow: ID!, enabled: Boolean!, config: JSON!): WorkflowTrigger
@@ -23005,6 +23155,21 @@ type PageInfo {
23005
23155
  agent_id: ID!
23006
23156
  }
23007
23157
 
23158
+ input LiveRecordingStartInput {
23159
+ title: String
23160
+ language: String
23161
+ project_id: ID
23162
+ target_rights_mode: String
23163
+ target_rbac_users: [RBACUserInput!]
23164
+ target_rbac_roles: [RBACRoleInput!]
23165
+ post_processing_prompts: [PostProcessingPromptInput!]
23166
+ }
23167
+
23168
+ input LiveRecordingStopInput {
23169
+ audio_s3key: String
23170
+ duration_seconds: Float
23171
+ }
23172
+
23008
23173
  type MeetingRecordingUsage {
23009
23174
  enabled: Boolean!
23010
23175
  used_seconds: Float!
@@ -23918,16 +24083,7 @@ type LiteLLMModel {
23918
24083
  }
23919
24084
  return { success: true };
23920
24085
  };
23921
- const assertOwnsTranscriptionJob = async (id, context) => {
23922
- const { db: db2, user } = context;
23923
- if (!user) throw new Error("Authentication required");
23924
- if (user.super_admin === true) return;
23925
- const row = await db2.from("transcription_jobs").select(["created_by", "rights_mode"]).where({ id }).first();
23926
- if (!row) throw new Error(`transcription_job ${id} not found`);
23927
- if (row.rights_mode === "public") return;
23928
- if (row.created_by != null && String(row.created_by) === String(user.id)) return;
23929
- throw new Error("Not authorized to act on this transcription job");
23930
- };
24086
+ const assertOwnsTranscriptionJob2 = async (id, context) => assertOwnsTranscriptionJob(context.db, context.user, id);
23931
24087
  resolvers.Mutation["transcriptionJobStart"] = async (_, args, context) => {
23932
24088
  const { user } = context;
23933
24089
  if (!user) throw new Error("Authentication required");
@@ -23951,7 +24107,7 @@ type LiteLLMModel {
23951
24107
  });
23952
24108
  };
23953
24109
  resolvers.Mutation["transcriptionJobFinalize"] = async (_, args, context) => {
23954
- await assertOwnsTranscriptionJob(args.id, context);
24110
+ await assertOwnsTranscriptionJob2(args.id, context);
23955
24111
  const { item, row } = await transcriptionService.finalize(args.id, {
23956
24112
  title: args.input.title,
23957
24113
  speakers: args.input.speakers,
@@ -23963,7 +24119,7 @@ type LiteLLMModel {
23963
24119
  return { job: row, item_id: item.id };
23964
24120
  };
23965
24121
  resolvers.Mutation["transcriptionJobCancel"] = async (_, args, context) => {
23966
- await assertOwnsTranscriptionJob(args.id, context);
24122
+ await assertOwnsTranscriptionJob2(args.id, context);
23967
24123
  return transcriptionService.cancelJob(args.id);
23968
24124
  };
23969
24125
  resolvers.Mutation["meetingBotStart"] = async (_, args, context) => {
@@ -23988,17 +24144,41 @@ type LiteLLMModel {
23988
24144
  });
23989
24145
  };
23990
24146
  resolvers.Mutation["runTranscriptPostProcessing"] = async (_, args, context) => {
23991
- await assertOwnsTranscriptionJob(args.id, context);
24147
+ await assertOwnsTranscriptionJob2(args.id, context);
23992
24148
  await recallService.runOnePostProcessing(args.id, args.prompt_id, args.agent_id);
23993
24149
  const { db: db2 } = context;
23994
24150
  return db2.from("transcription_jobs").where({ id: args.id }).first();
23995
24151
  };
24152
+ resolvers.Mutation["liveRecordingStart"] = async (_, args, context) => {
24153
+ const { user } = context;
24154
+ if (!user) throw new Error("Authentication required");
24155
+ if (!liveRecordingEnabled()) {
24156
+ throw new Error(`LIVE_RECORDING_DISABLED: ${LIVE_RECORDING_DISABLED_MESSAGE}`);
24157
+ }
24158
+ return liveRecordingService.start({
24159
+ userId: user.id,
24160
+ title: args.input.title ?? null,
24161
+ language: args.input.language ?? null,
24162
+ project_id: args.input.project_id ?? null,
24163
+ target_rights_mode: args.input.target_rights_mode ?? null,
24164
+ target_rbac_users: args.input.target_rbac_users ?? null,
24165
+ target_rbac_roles: args.input.target_rbac_roles ?? null,
24166
+ post_processing_prompts: args.input.post_processing_prompts ?? null
24167
+ });
24168
+ };
24169
+ resolvers.Mutation["liveRecordingStop"] = async (_, args, context) => {
24170
+ await assertOwnsTranscriptionJob2(args.id, context);
24171
+ return liveRecordingService.stop(args.id, {
24172
+ audio_s3key: args.input?.audio_s3key ?? null,
24173
+ duration_seconds: args.input?.duration_seconds ?? null
24174
+ });
24175
+ };
23996
24176
  resolvers.Query["meetingRecordingUsage"] = async (_, __, context) => {
23997
24177
  if (!context.user) throw new Error("Authentication required");
23998
24178
  return recallService.getUsage();
23999
24179
  };
24000
24180
  resolvers.Query["recordingVideoUrl"] = async (_, args, context) => {
24001
- await assertOwnsTranscriptionJob(args.job_id, context);
24181
+ await assertOwnsTranscriptionJob2(args.job_id, context);
24002
24182
  const { db: db2 } = context;
24003
24183
  const row = await db2.from("transcription_jobs").select(["recall_recording_id"]).where({ id: args.job_id }).first();
24004
24184
  if (!row?.recall_recording_id) return null;
@@ -25120,6 +25300,13 @@ var TranscriptionError = class extends Error {
25120
25300
  this.name = "TranscriptionError";
25121
25301
  }
25122
25302
  };
25303
+ var PRIOR_TEXT_MAX_CHARS = 300;
25304
+ function buildTranscribeUserText(priorText) {
25305
+ const tail = (priorText ?? "").trim();
25306
+ if (!tail) return "Transcribe this audio.";
25307
+ const clipped = tail.length > PRIOR_TEXT_MAX_CHARS ? tail.slice(-PRIOR_TEXT_MAX_CHARS) : tail;
25308
+ return `Transcribe this audio. It is one part of a longer recording. The previous part ended with: \xAB${clipped}\xBB. Continue from there \u2014 do not repeat that text, do not summarise, do not add speaker labels.`;
25309
+ }
25123
25310
  async function transcribeAudio(args) {
25124
25311
  const target = resolveLiteLLMTarget();
25125
25312
  const model = process.env.TRANSCRIPTION_MODEL;
@@ -25139,6 +25326,7 @@ async function transcribeViaAudioEndpoint(args, target, model) {
25139
25326
  );
25140
25327
  form.append("model", model);
25141
25328
  if (args.language) form.append("language", args.language);
25329
+ if (args.priorText?.trim()) form.append("prompt", args.priorText.trim().slice(-PRIOR_TEXT_MAX_CHARS));
25142
25330
  const res = await fetch(`${target.baseUrl}/v1/audio/transcriptions`, {
25143
25331
  method: "POST",
25144
25332
  headers: { ...target.authHeaders },
@@ -25166,14 +25354,18 @@ async function transcribeViaChat(args, target, model) {
25166
25354
  {
25167
25355
  role: "user",
25168
25356
  content: [
25169
- { type: "text", text: "Transcribe this audio." },
25357
+ { type: "text", text: buildTranscribeUserText(args.priorText) },
25170
25358
  {
25171
25359
  type: "input_audio",
25172
25360
  input_audio: { data: args.file.buffer.toString("base64"), format }
25173
25361
  }
25174
25362
  ]
25175
25363
  }
25176
- ]
25364
+ ],
25365
+ // LiteLLM reads metadata.tags for tag-based spend tracking (same mechanism
25366
+ // as resolve-ocr.ts). Omitted entirely when empty so the composer's body is
25367
+ // byte-for-byte unchanged.
25368
+ ...args.tags && args.tags.length > 0 ? { metadata: { tags: args.tags } } : {}
25177
25369
  };
25178
25370
  const res = await fetch(`${target.baseUrl}/v1/chat/completions`, {
25179
25371
  method: "POST",
@@ -25191,6 +25383,144 @@ async function transcribeViaChat(args, target, model) {
25191
25383
  return { text: cleanTranscript(json.choices?.[0]?.message?.content) };
25192
25384
  }
25193
25385
 
25386
+ // src/exulu/transcription/chunk-route.ts
25387
+ init_cjs_shims();
25388
+ var CHUNK_ROUTE_PATH = "/transcription-jobs/:id/chunks";
25389
+ var LIVE_PRIOR_TEXT_ENABLED = true;
25390
+ var PRIOR_TEXT_MAX_CHARS2 = 300;
25391
+ var LITELLM_READY_TIMEOUT_MS = 5e3;
25392
+ var parseSegments = (raw) => {
25393
+ if (!raw) return [];
25394
+ if (typeof raw === "string") {
25395
+ try {
25396
+ return JSON.parse(raw);
25397
+ } catch {
25398
+ return [];
25399
+ }
25400
+ }
25401
+ return Array.isArray(raw) ? raw : [];
25402
+ };
25403
+ function priorTextFrom(raw) {
25404
+ const segments = parseSegments(raw);
25405
+ for (let i = segments.length - 1; i >= 0; i--) {
25406
+ const text = (segments[i]?.text ?? "").trim();
25407
+ if (text) return text.length > PRIOR_TEXT_MAX_CHARS2 ? text.slice(-PRIOR_TEXT_MAX_CHARS2) : text;
25408
+ }
25409
+ return void 0;
25410
+ }
25411
+ var intField = (value) => {
25412
+ if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
25413
+ return Number(value);
25414
+ };
25415
+ function registerLiveRecordingChunkRoute(app, deps) {
25416
+ app.post(CHUNK_ROUTE_PATH, deps.upload, async (req, res) => {
25417
+ if (!deps.enabled()) {
25418
+ res.status(503).json({ detail: LIVE_RECORDING_DISABLED_MESSAGE });
25419
+ return;
25420
+ }
25421
+ const auth = await deps.authenticate(req);
25422
+ if (!auth.user?.id) {
25423
+ res.status(auth.code || 401).json({ detail: auth.message ?? "Authentication required" });
25424
+ return;
25425
+ }
25426
+ const user = auth.user;
25427
+ const jobId = req.params.id ?? "";
25428
+ const db2 = await deps.getDb();
25429
+ try {
25430
+ await deps.assertOwns(db2, user, jobId);
25431
+ } catch (err) {
25432
+ if (err instanceof TranscriptionJobAccessError) {
25433
+ res.status(err.code).json({ detail: err.message });
25434
+ return;
25435
+ }
25436
+ throw err;
25437
+ }
25438
+ const row = await db2.from("transcription_jobs").select(["status", "raw_segments", "project_id"]).where({ id: jobId }).first();
25439
+ if (!row) {
25440
+ res.status(404).json({ detail: `transcription_job ${jobId} not found` });
25441
+ return;
25442
+ }
25443
+ if (row.status !== "recording") {
25444
+ res.status(409).json({ detail: `Recording is not active (status '${row.status}').`, kind: "not_recording" });
25445
+ return;
25446
+ }
25447
+ const seq = intField(req.body?.seq);
25448
+ const offsetMs = intField(req.body?.offset_ms);
25449
+ const durationMs = intField(req.body?.duration_ms);
25450
+ if (seq == null || offsetMs == null || durationMs == null || durationMs <= 0) {
25451
+ res.status(400).json({ detail: "seq, offset_ms (\u2265 0) and duration_ms (> 0) are required integers." });
25452
+ return;
25453
+ }
25454
+ const skipped = req.body?.skipped === "true";
25455
+ let text = "";
25456
+ if (!skipped) {
25457
+ const file = req.file;
25458
+ if (!file) {
25459
+ res.status(400).json({ detail: "No audio file provided in 'file' field." });
25460
+ return;
25461
+ }
25462
+ if (!file.mimetype.startsWith("audio/")) {
25463
+ res.status(400).json({ detail: `Unsupported mimetype: ${file.mimetype}. Expected audio/*.` });
25464
+ return;
25465
+ }
25466
+ let readyTimer;
25467
+ try {
25468
+ await Promise.race([
25469
+ deps.waitForLiteLLMReady(),
25470
+ new Promise((_, reject) => {
25471
+ readyTimer = setTimeout(() => reject(new Error("LiteLLM not ready")), deps.readyTimeoutMs ?? LITELLM_READY_TIMEOUT_MS);
25472
+ })
25473
+ ]);
25474
+ } catch {
25475
+ res.status(503).json({ detail: "Transcription service is not ready. Try again shortly." });
25476
+ return;
25477
+ } finally {
25478
+ clearTimeout(readyTimer);
25479
+ }
25480
+ const tags = deps.buildTags({
25481
+ user_id: user.id,
25482
+ user_name: user.type === "api" ? user.firstname ?? user.email ?? void 0 : user.email ?? void 0,
25483
+ project_id: row.project_id ?? void 0
25484
+ });
25485
+ try {
25486
+ ({ text } = await deps.transcribe({
25487
+ file,
25488
+ priorText: LIVE_PRIOR_TEXT_ENABLED ? priorTextFrom(row.raw_segments) : void 0,
25489
+ tags
25490
+ }));
25491
+ } catch (err) {
25492
+ if (err instanceof TranscriptionError) {
25493
+ const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
25494
+ res.status(code).json({ detail: err.message });
25495
+ return;
25496
+ }
25497
+ console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err);
25498
+ res.status(500).json({ detail: err instanceof Error ? err.message : "Transcription failed." });
25499
+ return;
25500
+ }
25501
+ }
25502
+ const result = await deps.service.appendChunk({ id: jobId, seq, text, offsetMs, durationMs });
25503
+ switch (result.kind) {
25504
+ case "appended":
25505
+ res.status(200).json({ seq, text, chunk_count: result.chunkCount });
25506
+ return;
25507
+ case "duplicate":
25508
+ res.status(200).json({ seq, text: result.text, chunk_count: result.chunkCount, duplicate: true });
25509
+ return;
25510
+ case "out_of_order":
25511
+ res.status(409).json({
25512
+ detail: `Chunk ${seq} is ahead of the next expected chunk ${result.chunkCount}.`,
25513
+ kind: "out_of_order",
25514
+ chunk_count: result.chunkCount
25515
+ });
25516
+ return;
25517
+ case "not_recording":
25518
+ res.status(409).json({ detail: `Recording is not active (status '${result.status}').`, kind: "not_recording" });
25519
+ return;
25520
+ }
25521
+ });
25522
+ }
25523
+
25194
25524
  // src/exulu/speech.ts
25195
25525
  init_cjs_shims();
25196
25526
  init_env();
@@ -26538,6 +26868,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
26538
26868
  },
26539
26869
  recall: {
26540
26870
  enabled: recallEnabled()
26871
+ },
26872
+ // Whisper upload transcription (TRANSCRIPTION_SERVER). The Transcripts
26873
+ // page gates its "Upload a file" mode on this — previously it was gated
26874
+ // on the composer-mic flag and showed an upload mode that could not work.
26875
+ whisper: {
26876
+ enabled: transcriptionClient.isConfigured()
26541
26877
  }
26542
26878
  });
26543
26879
  });
@@ -27059,19 +27395,20 @@ ${customInstructions}` : agent.instructions,
27059
27395
  storage: import_multer.default.memoryStorage(),
27060
27396
  limits: { fileSize: MAX_TRANSCRIBE_BYTES }
27061
27397
  });
27398
+ const transcribeUploadMiddleware = (req, res, next) => {
27399
+ transcribeUpload.single("file")(req, res, (err) => {
27400
+ if (!err) return next();
27401
+ const code = err?.code;
27402
+ if (code === "LIMIT_FILE_SIZE") {
27403
+ res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
27404
+ return;
27405
+ }
27406
+ res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
27407
+ });
27408
+ };
27062
27409
  app.post(
27063
27410
  "/transcribe",
27064
- (req, res, next) => {
27065
- transcribeUpload.single("file")(req, res, (err) => {
27066
- if (!err) return next();
27067
- const code = err?.code;
27068
- if (code === "LIMIT_FILE_SIZE") {
27069
- res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
27070
- return;
27071
- }
27072
- res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
27073
- });
27074
- },
27411
+ transcribeUploadMiddleware,
27075
27412
  async (req, res) => {
27076
27413
  if (!isLiteLLMEnabled() || !process.env.TRANSCRIPTION_MODEL) {
27077
27414
  res.status(503).json({
@@ -27123,6 +27460,17 @@ ${customInstructions}` : agent.instructions,
27123
27460
  }
27124
27461
  }
27125
27462
  );
27463
+ registerLiveRecordingChunkRoute(app, {
27464
+ upload: transcribeUploadMiddleware,
27465
+ enabled: liveRecordingEnabled,
27466
+ authenticate: (req) => requestValidators.authenticate(req),
27467
+ getDb: async () => (await postgresClient()).db,
27468
+ assertOwns: assertOwnsTranscriptionJob,
27469
+ waitForLiteLLMReady,
27470
+ buildTags,
27471
+ transcribe: transcribeAudio,
27472
+ service: liveRecordingService
27473
+ });
27126
27474
  const MAX_TTS_INPUT_CHARS = 4e3;
27127
27475
  app.post(
27128
27476
  "/speech",
@@ -31477,6 +31825,9 @@ var ExuluApp = class {
31477
31825
  "[EXULU] TRANSCRIPTION_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /transcribe endpoint will return 503 until LiteLLM is enabled."
31478
31826
  );
31479
31827
  }
31828
+ console.log(
31829
+ `[EXULU] Live recording (Transcripts page): ${liveRecordingEnabled() ? "enabled" : "disabled"} (EXULU_USE_LITELLM=${process.env.EXULU_USE_LITELLM ?? "unset"}, TRANSCRIPTION_MODEL=${process.env.TRANSCRIPTION_MODEL ? "set" : "unset"})`
31830
+ );
31480
31831
  if (process.env.TTS_MODEL && !isLiteLLMEnabled()) {
31481
31832
  console.warn(
31482
31833
  "[EXULU] TTS_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /speech endpoint will return 503 until LiteLLM is enabled."
@@ -32969,7 +33320,7 @@ ${WARNING_BANNER}`);
32969
33320
  console.warn(`${WARNING_BANNER}
32970
33321
  `);
32971
33322
  };
32972
- var log5 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
33323
+ var log6 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
32973
33324
  var initLiteLLMDatabase = async (packageRoot) => {
32974
33325
  const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path11.resolve)(process.cwd(), "./config.litellm.yaml");
32975
33326
  const safety = checkLiteLLMDatabaseSafety(configPath);
@@ -33003,7 +33354,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33003
33354
  return;
33004
33355
  }
33005
33356
  const target = "litellmTarget" in safety ? safety.litellmTarget : void 0;
33006
- log5(
33357
+ log6(
33007
33358
  `LiteLLM database mode detected (${target?.host}:${target?.port}/${target?.database}).`
33008
33359
  );
33009
33360
  const ensureDatabaseExists2 = async () => {
@@ -33031,7 +33382,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33031
33382
  return false;
33032
33383
  }
33033
33384
  url.pathname = "/postgres";
33034
- log5(`Target database "${targetDbName}" does not exist; creating it\u2026`);
33385
+ log6(`Target database "${targetDbName}" does not exist; creating it\u2026`);
33035
33386
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(targetDbName)) {
33036
33387
  warn2([
33037
33388
  `Refusing to auto-create database "${targetDbName}" \u2014 name`,
@@ -33044,7 +33395,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33044
33395
  try {
33045
33396
  await admin.connect();
33046
33397
  await admin.query(`CREATE DATABASE "${targetDbName}"`);
33047
- log5(`\u2713 Created database "${targetDbName}".`);
33398
+ log6(`\u2713 Created database "${targetDbName}".`);
33048
33399
  return true;
33049
33400
  } catch (createErr) {
33050
33401
  warn2([
@@ -33066,7 +33417,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33066
33417
  }
33067
33418
  };
33068
33419
  if (!await ensureDatabaseExists2()) return;
33069
- log5("Checking that the target database is safe to push into\u2026");
33420
+ log6("Checking that the target database is safe to push into\u2026");
33070
33421
  const client2 = new import_pg.Client({ connectionString: litellmUrl });
33071
33422
  let foreignTables = [];
33072
33423
  try {
@@ -33142,7 +33493,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33142
33493
  ]);
33143
33494
  return;
33144
33495
  }
33145
- log5("Running `prisma db push` against LiteLLM's schema\u2026");
33496
+ log6("Running `prisma db push` against LiteLLM's schema\u2026");
33146
33497
  const result = (0, import_node_child_process6.spawnSync)(prismaCli, ["db", "push", "--skip-generate"], {
33147
33498
  cwd: litellmProxyDir,
33148
33499
  env: {
@@ -33172,7 +33523,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33172
33523
  ]);
33173
33524
  return;
33174
33525
  }
33175
- log5("\u2713 LiteLLM database ready.");
33526
+ log6("\u2713 LiteLLM database ready.");
33176
33527
  };
33177
33528
 
33178
33529
  // src/postgres/init-litellm-db.ts
package/dist/index.js CHANGED
@@ -1299,6 +1299,9 @@ async function resolveEmbedder(input) {
1299
1299
  };
1300
1300
  }
1301
1301
 
1302
+ // types/rbac-rights-modes.ts
1303
+ var VALID_RIGHTS_MODES = ["private", "users", "roles", "teams", "public"];
1304
+
1302
1305
  // src/utils/query-preprocessing.ts
1303
1306
  import { franc } from "franc";
1304
1307
  import natural from "natural";
@@ -2885,7 +2888,14 @@ var transcriptionJobsSchema = {
2885
2888
  // when RECALL_STORE_VIDEO_LOCALLY=true. Null when that flag is off (the
2886
2889
  // video then stays reachable only via ExuluRecall.getRecordingVideoUrl,
2887
2890
  // for as long as Recall itself retains it) or for Whisper upload jobs.
2888
- { name: "video", type: "file" }
2891
+ { name: "video", type: "file" },
2892
+ // Live (browser-microphone) recordings — spec
2893
+ // docs/superpowers/specs/2026-09-23-live-recording-transcription-design.md §2.
2894
+ // chunk_count is the NEXT expected chunk seq; the chunk route appends with
2895
+ // a compare-and-swap on it, so retries and duplicates can never double-append.
2896
+ { name: "chunk_count", type: "number", default: 0 },
2897
+ // Heartbeat of the last accepted chunk; shown in the queue row.
2898
+ { name: "last_chunk_at", type: "date" }
2889
2899
  ]
2890
2900
  };
2891
2901
  var imageGenerationsSchema = {
@@ -4505,6 +4515,13 @@ var bullmqDecorator = async ({
4505
4515
  };
4506
4516
 
4507
4517
  // src/exulu/context.ts
4518
+ function sanitizeItemRightsMode(rightsMode, defaultMode) {
4519
+ if (rightsMode == null) return rightsMode;
4520
+ if (VALID_RIGHTS_MODES.includes(rightsMode)) {
4521
+ return rightsMode;
4522
+ }
4523
+ return defaultMode ?? "private";
4524
+ }
4508
4525
  var ExuluContext2 = class {
4509
4526
  // Must begin with a letter (a-z) or underscore (_). Subsequent characters in a name can be letters, digits (0-9), or
4510
4527
  // underscores and be a max length of 80 characters and at least 5 characters long.
@@ -4812,6 +4829,12 @@ var ExuluContext2 = class {
4812
4829
  if (upsert && !item.id && !item.external_id) {
4813
4830
  throw new Error("Item id or external id is required for upsert.");
4814
4831
  }
4832
+ if (item.rights_mode != null && !VALID_RIGHTS_MODES.includes(item.rights_mode)) {
4833
+ console.warn(
4834
+ `[EXULU] createItem: invalid rights_mode "${item.rights_mode}" for context "${this.id}" (item ${item.id ?? item.external_id ?? "(new)"}) \u2014 falling back to the configured default.`
4835
+ );
4836
+ }
4837
+ item.rights_mode = sanitizeItemRightsMode(item.rights_mode, this.configuration.defaultRightsMode);
4815
4838
  const { db } = await postgresClient();
4816
4839
  Object.keys(item).forEach((key) => {
4817
4840
  if (this.fields.find((field) => field.name === key)?.type === "json") {
@@ -6756,7 +6779,7 @@ var shouldGenerateEmbeddings = ({
6756
6779
  };
6757
6780
 
6758
6781
  // src/graphql/mutations/index.ts
6759
- var VALID_RIGHTS_MODES = ["private", "users", "roles", "teams", "public"];
6782
+ var VALID_RIGHTS_MODES2 = ["private", "users", "roles", "teams", "public"];
6760
6783
  var postprocessDeletion = async ({
6761
6784
  table,
6762
6785
  requestedFields,
@@ -7081,9 +7104,9 @@ function createMutations(table, contexts, tools, config) {
7081
7104
  input.id = db.fn.uuid();
7082
7105
  }
7083
7106
  }
7084
- if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES.includes(input.rights_mode)) {
7107
+ if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES2.includes(input.rights_mode)) {
7085
7108
  throw new Error(
7086
- `Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES.join(", ")}`
7109
+ `Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
7087
7110
  );
7088
7111
  }
7089
7112
  const columns = await db(tableNamePlural).columnInfo();
@@ -7663,9 +7686,9 @@ function createMutations(table, contexts, tools, config) {
7663
7686
  if (!Array.isArray(ids) || ids.length === 0) {
7664
7687
  throw new Error("ids is required and must be a non-empty array.");
7665
7688
  }
7666
- if (!VALID_RIGHTS_MODES.includes(rights_mode)) {
7689
+ if (!VALID_RIGHTS_MODES2.includes(rights_mode)) {
7667
7690
  throw new Error(
7668
- `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES.join(", ")}`
7691
+ `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
7669
7692
  );
7670
7693
  }
7671
7694
  for (const id of ids) {
@@ -11497,6 +11520,24 @@ var transcriptionService = {
11497
11520
  }
11498
11521
  };
11499
11522
 
11523
+ // src/exulu/transcription/authorize.ts
11524
+ var TranscriptionJobAccessError = class extends Error {
11525
+ constructor(code, message) {
11526
+ super(message);
11527
+ this.code = code;
11528
+ this.name = "TranscriptionJobAccessError";
11529
+ }
11530
+ };
11531
+ async function assertOwnsTranscriptionJob(db, user, id) {
11532
+ if (!user) throw new TranscriptionJobAccessError(403, "Authentication required");
11533
+ if (user.super_admin === true) return;
11534
+ const row = await db.from("transcription_jobs").select(["created_by", "rights_mode"]).where({ id }).first();
11535
+ if (!row) throw new TranscriptionJobAccessError(404, `transcription_job ${id} not found`);
11536
+ if (row.rights_mode === "public") return;
11537
+ if (row.created_by != null && String(row.created_by) === String(user.id)) return;
11538
+ throw new TranscriptionJobAccessError(403, "Not authorized to act on this transcription job");
11539
+ }
11540
+
11500
11541
  // src/exulu/recall/service.ts
11501
11542
  import { generateText as generateText4 } from "ai";
11502
11543
 
@@ -12432,6 +12473,106 @@ ${transcriptText}`,
12432
12473
  }
12433
12474
  };
12434
12475
 
12476
+ // src/exulu/transcription/live-recording.ts
12477
+ var TABLE3 = "transcription_jobs";
12478
+ var log4 = (msg) => console.log(`[EXULU-LIVE-RECORDING] ${msg}`);
12479
+ var LIVE_RECORDING_DISABLED_MESSAGE = "Speech-to-text is not enabled on this deployment. Set EXULU_USE_LITELLM=true and TRANSCRIPTION_MODEL in the environment.";
12480
+ function liveRecordingEnabled() {
12481
+ return isLiteLLMEnabled() && Boolean(process.env.TRANSCRIPTION_MODEL);
12482
+ }
12483
+ var parseJson2 = (v) => {
12484
+ if (v == null) return null;
12485
+ if (typeof v === "string") {
12486
+ try {
12487
+ return JSON.parse(v);
12488
+ } catch {
12489
+ return null;
12490
+ }
12491
+ }
12492
+ return v;
12493
+ };
12494
+ var rowFromDb = (dbRow) => ({
12495
+ ...dbRow,
12496
+ chunk_count: Number(dbRow.chunk_count ?? 0),
12497
+ raw_segments: parseJson2(dbRow.raw_segments)
12498
+ });
12499
+ var liveRecordingService = {
12500
+ async start(input) {
12501
+ const { db } = await postgresClient();
12502
+ const now = /* @__PURE__ */ new Date();
12503
+ const [inserted] = await db(TABLE3).insert({
12504
+ source: "live",
12505
+ status: "recording",
12506
+ chunk_count: 0,
12507
+ raw_segments: "[]",
12508
+ title: input.title?.trim() ? input.title.trim() : null,
12509
+ language: input.language && input.language !== "auto" ? input.language : null,
12510
+ project_id: input.project_id ?? null,
12511
+ target_rights_mode: input.target_rights_mode ?? "private",
12512
+ target_rbac_users: input.target_rbac_users ? JSON.stringify(input.target_rbac_users) : null,
12513
+ target_rbac_roles: input.target_rbac_roles ? JSON.stringify(input.target_rbac_roles) : null,
12514
+ // NULL when empty — mirrors recallService.createMeetingBot so
12515
+ // runPostProcessing's "no prompts" short-circuit works unchanged.
12516
+ post_processing_prompts: input.post_processing_prompts?.length ? JSON.stringify(input.post_processing_prompts) : null,
12517
+ rights_mode: "private",
12518
+ created_by: input.userId,
12519
+ createdAt: now,
12520
+ updatedAt: now
12521
+ }).returning("*");
12522
+ log4(`started live recording ${inserted.id} for user ${input.userId}`);
12523
+ return rowFromDb(inserted);
12524
+ },
12525
+ async appendChunk(input) {
12526
+ const { db } = await postgresClient();
12527
+ const segment = {
12528
+ start: input.offsetMs / 1e3,
12529
+ end: (input.offsetMs + input.durationMs) / 1e3,
12530
+ text: input.text,
12531
+ speaker: "unknown"
12532
+ };
12533
+ const affected = await db(TABLE3).where({ id: input.id, status: "recording", chunk_count: input.seq }).update({
12534
+ raw_segments: db.raw("COALESCE(raw_segments, '[]'::jsonb) || ?::jsonb", [
12535
+ JSON.stringify([segment])
12536
+ ]),
12537
+ chunk_count: input.seq + 1,
12538
+ duration_seconds: db.raw("GREATEST(COALESCE(duration_seconds, 0), ?)", [segment.end]),
12539
+ last_chunk_at: /* @__PURE__ */ new Date(),
12540
+ updatedAt: /* @__PURE__ */ new Date()
12541
+ });
12542
+ if (affected === 1) return { kind: "appended", chunkCount: input.seq + 1 };
12543
+ const row = await db(TABLE3).select(["status", "chunk_count", "raw_segments"]).where({ id: input.id }).first();
12544
+ if (!row) throw new Error(`transcription_job ${input.id} not found`);
12545
+ if (row.status !== "recording") return { kind: "not_recording", status: row.status };
12546
+ const chunkCount = Number(row.chunk_count ?? 0);
12547
+ if (chunkCount > input.seq) {
12548
+ const segments = parseJson2(row.raw_segments) ?? [];
12549
+ return { kind: "duplicate", text: segments[input.seq]?.text ?? "", chunkCount };
12550
+ }
12551
+ return { kind: "out_of_order", chunkCount };
12552
+ },
12553
+ async stop(id, input) {
12554
+ const { db } = await postgresClient();
12555
+ const patch = { status: "awaiting_review", updatedAt: /* @__PURE__ */ new Date() };
12556
+ if (input.audio_s3key) patch.audio_s3key = input.audio_s3key;
12557
+ if (typeof input.duration_seconds === "number" && input.duration_seconds > 0) {
12558
+ patch.duration_seconds = input.duration_seconds;
12559
+ }
12560
+ const [updated] = await db(TABLE3).where({ id, status: "recording" }).update(patch).returning("*");
12561
+ if (!updated) {
12562
+ const row = await db(TABLE3).where({ id }).first();
12563
+ if (!row) throw new Error(`transcription_job ${id} not found`);
12564
+ throw new Error(
12565
+ `transcription_job ${id} is in status '${row.status}'; can only stop from 'recording'`
12566
+ );
12567
+ }
12568
+ log4(`live recording ${id} stopped \u2192 awaiting_review`);
12569
+ void recallService.runPostProcessing(id).catch((err) => {
12570
+ log4(`post-processing for job ${id} failed: ${err.message}`);
12571
+ });
12572
+ return rowFromDb(updated);
12573
+ }
12574
+ };
12575
+
12435
12576
  // src/exulu/email-inbound/trigger-config.ts
12436
12577
  import { randomBytes } from "crypto";
12437
12578
  import safeRegex from "safe-regex";
@@ -13237,6 +13378,8 @@ type PageInfo {
13237
13378
  transcriptionJobCancel(id: ID!): transcription_job
13238
13379
  meetingBotStart(input: MeetingBotStartInput!): transcription_job
13239
13380
  runTranscriptPostProcessing(id: ID!, prompt_id: ID!, agent_id: ID!): transcription_job
13381
+ liveRecordingStart(input: LiveRecordingStartInput!): transcription_job
13382
+ liveRecordingStop(id: ID!, input: LiveRecordingStopInput): transcription_job
13240
13383
  `;
13241
13384
  mutationDefs += `
13242
13385
  upsertWorkflowEmailTrigger(workflow: ID!, enabled: Boolean!, config: JSON!): WorkflowTrigger
@@ -13292,6 +13435,21 @@ type PageInfo {
13292
13435
  agent_id: ID!
13293
13436
  }
13294
13437
 
13438
+ input LiveRecordingStartInput {
13439
+ title: String
13440
+ language: String
13441
+ project_id: ID
13442
+ target_rights_mode: String
13443
+ target_rbac_users: [RBACUserInput!]
13444
+ target_rbac_roles: [RBACRoleInput!]
13445
+ post_processing_prompts: [PostProcessingPromptInput!]
13446
+ }
13447
+
13448
+ input LiveRecordingStopInput {
13449
+ audio_s3key: String
13450
+ duration_seconds: Float
13451
+ }
13452
+
13295
13453
  type MeetingRecordingUsage {
13296
13454
  enabled: Boolean!
13297
13455
  used_seconds: Float!
@@ -14205,16 +14363,7 @@ type LiteLLMModel {
14205
14363
  }
14206
14364
  return { success: true };
14207
14365
  };
14208
- const assertOwnsTranscriptionJob = async (id, context) => {
14209
- const { db, user } = context;
14210
- if (!user) throw new Error("Authentication required");
14211
- if (user.super_admin === true) return;
14212
- const row = await db.from("transcription_jobs").select(["created_by", "rights_mode"]).where({ id }).first();
14213
- if (!row) throw new Error(`transcription_job ${id} not found`);
14214
- if (row.rights_mode === "public") return;
14215
- if (row.created_by != null && String(row.created_by) === String(user.id)) return;
14216
- throw new Error("Not authorized to act on this transcription job");
14217
- };
14366
+ const assertOwnsTranscriptionJob2 = async (id, context) => assertOwnsTranscriptionJob(context.db, context.user, id);
14218
14367
  resolvers.Mutation["transcriptionJobStart"] = async (_, args, context) => {
14219
14368
  const { user } = context;
14220
14369
  if (!user) throw new Error("Authentication required");
@@ -14238,7 +14387,7 @@ type LiteLLMModel {
14238
14387
  });
14239
14388
  };
14240
14389
  resolvers.Mutation["transcriptionJobFinalize"] = async (_, args, context) => {
14241
- await assertOwnsTranscriptionJob(args.id, context);
14390
+ await assertOwnsTranscriptionJob2(args.id, context);
14242
14391
  const { item, row } = await transcriptionService.finalize(args.id, {
14243
14392
  title: args.input.title,
14244
14393
  speakers: args.input.speakers,
@@ -14250,7 +14399,7 @@ type LiteLLMModel {
14250
14399
  return { job: row, item_id: item.id };
14251
14400
  };
14252
14401
  resolvers.Mutation["transcriptionJobCancel"] = async (_, args, context) => {
14253
- await assertOwnsTranscriptionJob(args.id, context);
14402
+ await assertOwnsTranscriptionJob2(args.id, context);
14254
14403
  return transcriptionService.cancelJob(args.id);
14255
14404
  };
14256
14405
  resolvers.Mutation["meetingBotStart"] = async (_, args, context) => {
@@ -14275,17 +14424,41 @@ type LiteLLMModel {
14275
14424
  });
14276
14425
  };
14277
14426
  resolvers.Mutation["runTranscriptPostProcessing"] = async (_, args, context) => {
14278
- await assertOwnsTranscriptionJob(args.id, context);
14427
+ await assertOwnsTranscriptionJob2(args.id, context);
14279
14428
  await recallService.runOnePostProcessing(args.id, args.prompt_id, args.agent_id);
14280
14429
  const { db } = context;
14281
14430
  return db.from("transcription_jobs").where({ id: args.id }).first();
14282
14431
  };
14432
+ resolvers.Mutation["liveRecordingStart"] = async (_, args, context) => {
14433
+ const { user } = context;
14434
+ if (!user) throw new Error("Authentication required");
14435
+ if (!liveRecordingEnabled()) {
14436
+ throw new Error(`LIVE_RECORDING_DISABLED: ${LIVE_RECORDING_DISABLED_MESSAGE}`);
14437
+ }
14438
+ return liveRecordingService.start({
14439
+ userId: user.id,
14440
+ title: args.input.title ?? null,
14441
+ language: args.input.language ?? null,
14442
+ project_id: args.input.project_id ?? null,
14443
+ target_rights_mode: args.input.target_rights_mode ?? null,
14444
+ target_rbac_users: args.input.target_rbac_users ?? null,
14445
+ target_rbac_roles: args.input.target_rbac_roles ?? null,
14446
+ post_processing_prompts: args.input.post_processing_prompts ?? null
14447
+ });
14448
+ };
14449
+ resolvers.Mutation["liveRecordingStop"] = async (_, args, context) => {
14450
+ await assertOwnsTranscriptionJob2(args.id, context);
14451
+ return liveRecordingService.stop(args.id, {
14452
+ audio_s3key: args.input?.audio_s3key ?? null,
14453
+ duration_seconds: args.input?.duration_seconds ?? null
14454
+ });
14455
+ };
14283
14456
  resolvers.Query["meetingRecordingUsage"] = async (_, __, context) => {
14284
14457
  if (!context.user) throw new Error("Authentication required");
14285
14458
  return recallService.getUsage();
14286
14459
  };
14287
14460
  resolvers.Query["recordingVideoUrl"] = async (_, args, context) => {
14288
- await assertOwnsTranscriptionJob(args.job_id, context);
14461
+ await assertOwnsTranscriptionJob2(args.job_id, context);
14289
14462
  const { db } = context;
14290
14463
  const row = await db.from("transcription_jobs").select(["recall_recording_id"]).where({ id: args.job_id }).first();
14291
14464
  if (!row?.recall_recording_id) return null;
@@ -15385,6 +15558,13 @@ var TranscriptionError = class extends Error {
15385
15558
  this.name = "TranscriptionError";
15386
15559
  }
15387
15560
  };
15561
+ var PRIOR_TEXT_MAX_CHARS = 300;
15562
+ function buildTranscribeUserText(priorText) {
15563
+ const tail = (priorText ?? "").trim();
15564
+ if (!tail) return "Transcribe this audio.";
15565
+ const clipped = tail.length > PRIOR_TEXT_MAX_CHARS ? tail.slice(-PRIOR_TEXT_MAX_CHARS) : tail;
15566
+ return `Transcribe this audio. It is one part of a longer recording. The previous part ended with: \xAB${clipped}\xBB. Continue from there \u2014 do not repeat that text, do not summarise, do not add speaker labels.`;
15567
+ }
15388
15568
  async function transcribeAudio(args) {
15389
15569
  const target = resolveLiteLLMTarget();
15390
15570
  const model = process.env.TRANSCRIPTION_MODEL;
@@ -15404,6 +15584,7 @@ async function transcribeViaAudioEndpoint(args, target, model) {
15404
15584
  );
15405
15585
  form.append("model", model);
15406
15586
  if (args.language) form.append("language", args.language);
15587
+ if (args.priorText?.trim()) form.append("prompt", args.priorText.trim().slice(-PRIOR_TEXT_MAX_CHARS));
15407
15588
  const res = await fetch(`${target.baseUrl}/v1/audio/transcriptions`, {
15408
15589
  method: "POST",
15409
15590
  headers: { ...target.authHeaders },
@@ -15431,14 +15612,18 @@ async function transcribeViaChat(args, target, model) {
15431
15612
  {
15432
15613
  role: "user",
15433
15614
  content: [
15434
- { type: "text", text: "Transcribe this audio." },
15615
+ { type: "text", text: buildTranscribeUserText(args.priorText) },
15435
15616
  {
15436
15617
  type: "input_audio",
15437
15618
  input_audio: { data: args.file.buffer.toString("base64"), format }
15438
15619
  }
15439
15620
  ]
15440
15621
  }
15441
- ]
15622
+ ],
15623
+ // LiteLLM reads metadata.tags for tag-based spend tracking (same mechanism
15624
+ // as resolve-ocr.ts). Omitted entirely when empty so the composer's body is
15625
+ // byte-for-byte unchanged.
15626
+ ...args.tags && args.tags.length > 0 ? { metadata: { tags: args.tags } } : {}
15442
15627
  };
15443
15628
  const res = await fetch(`${target.baseUrl}/v1/chat/completions`, {
15444
15629
  method: "POST",
@@ -15456,6 +15641,143 @@ async function transcribeViaChat(args, target, model) {
15456
15641
  return { text: cleanTranscript(json.choices?.[0]?.message?.content) };
15457
15642
  }
15458
15643
 
15644
+ // src/exulu/transcription/chunk-route.ts
15645
+ var CHUNK_ROUTE_PATH = "/transcription-jobs/:id/chunks";
15646
+ var LIVE_PRIOR_TEXT_ENABLED = true;
15647
+ var PRIOR_TEXT_MAX_CHARS2 = 300;
15648
+ var LITELLM_READY_TIMEOUT_MS = 5e3;
15649
+ var parseSegments = (raw) => {
15650
+ if (!raw) return [];
15651
+ if (typeof raw === "string") {
15652
+ try {
15653
+ return JSON.parse(raw);
15654
+ } catch {
15655
+ return [];
15656
+ }
15657
+ }
15658
+ return Array.isArray(raw) ? raw : [];
15659
+ };
15660
+ function priorTextFrom(raw) {
15661
+ const segments = parseSegments(raw);
15662
+ for (let i = segments.length - 1; i >= 0; i--) {
15663
+ const text = (segments[i]?.text ?? "").trim();
15664
+ if (text) return text.length > PRIOR_TEXT_MAX_CHARS2 ? text.slice(-PRIOR_TEXT_MAX_CHARS2) : text;
15665
+ }
15666
+ return void 0;
15667
+ }
15668
+ var intField = (value) => {
15669
+ if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
15670
+ return Number(value);
15671
+ };
15672
+ function registerLiveRecordingChunkRoute(app, deps) {
15673
+ app.post(CHUNK_ROUTE_PATH, deps.upload, async (req, res) => {
15674
+ if (!deps.enabled()) {
15675
+ res.status(503).json({ detail: LIVE_RECORDING_DISABLED_MESSAGE });
15676
+ return;
15677
+ }
15678
+ const auth = await deps.authenticate(req);
15679
+ if (!auth.user?.id) {
15680
+ res.status(auth.code || 401).json({ detail: auth.message ?? "Authentication required" });
15681
+ return;
15682
+ }
15683
+ const user = auth.user;
15684
+ const jobId = req.params.id ?? "";
15685
+ const db = await deps.getDb();
15686
+ try {
15687
+ await deps.assertOwns(db, user, jobId);
15688
+ } catch (err) {
15689
+ if (err instanceof TranscriptionJobAccessError) {
15690
+ res.status(err.code).json({ detail: err.message });
15691
+ return;
15692
+ }
15693
+ throw err;
15694
+ }
15695
+ const row = await db.from("transcription_jobs").select(["status", "raw_segments", "project_id"]).where({ id: jobId }).first();
15696
+ if (!row) {
15697
+ res.status(404).json({ detail: `transcription_job ${jobId} not found` });
15698
+ return;
15699
+ }
15700
+ if (row.status !== "recording") {
15701
+ res.status(409).json({ detail: `Recording is not active (status '${row.status}').`, kind: "not_recording" });
15702
+ return;
15703
+ }
15704
+ const seq = intField(req.body?.seq);
15705
+ const offsetMs = intField(req.body?.offset_ms);
15706
+ const durationMs = intField(req.body?.duration_ms);
15707
+ if (seq == null || offsetMs == null || durationMs == null || durationMs <= 0) {
15708
+ res.status(400).json({ detail: "seq, offset_ms (\u2265 0) and duration_ms (> 0) are required integers." });
15709
+ return;
15710
+ }
15711
+ const skipped = req.body?.skipped === "true";
15712
+ let text = "";
15713
+ if (!skipped) {
15714
+ const file = req.file;
15715
+ if (!file) {
15716
+ res.status(400).json({ detail: "No audio file provided in 'file' field." });
15717
+ return;
15718
+ }
15719
+ if (!file.mimetype.startsWith("audio/")) {
15720
+ res.status(400).json({ detail: `Unsupported mimetype: ${file.mimetype}. Expected audio/*.` });
15721
+ return;
15722
+ }
15723
+ let readyTimer;
15724
+ try {
15725
+ await Promise.race([
15726
+ deps.waitForLiteLLMReady(),
15727
+ new Promise((_, reject) => {
15728
+ readyTimer = setTimeout(() => reject(new Error("LiteLLM not ready")), deps.readyTimeoutMs ?? LITELLM_READY_TIMEOUT_MS);
15729
+ })
15730
+ ]);
15731
+ } catch {
15732
+ res.status(503).json({ detail: "Transcription service is not ready. Try again shortly." });
15733
+ return;
15734
+ } finally {
15735
+ clearTimeout(readyTimer);
15736
+ }
15737
+ const tags = deps.buildTags({
15738
+ user_id: user.id,
15739
+ user_name: user.type === "api" ? user.firstname ?? user.email ?? void 0 : user.email ?? void 0,
15740
+ project_id: row.project_id ?? void 0
15741
+ });
15742
+ try {
15743
+ ({ text } = await deps.transcribe({
15744
+ file,
15745
+ priorText: LIVE_PRIOR_TEXT_ENABLED ? priorTextFrom(row.raw_segments) : void 0,
15746
+ tags
15747
+ }));
15748
+ } catch (err) {
15749
+ if (err instanceof TranscriptionError) {
15750
+ const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
15751
+ res.status(code).json({ detail: err.message });
15752
+ return;
15753
+ }
15754
+ console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err);
15755
+ res.status(500).json({ detail: err instanceof Error ? err.message : "Transcription failed." });
15756
+ return;
15757
+ }
15758
+ }
15759
+ const result = await deps.service.appendChunk({ id: jobId, seq, text, offsetMs, durationMs });
15760
+ switch (result.kind) {
15761
+ case "appended":
15762
+ res.status(200).json({ seq, text, chunk_count: result.chunkCount });
15763
+ return;
15764
+ case "duplicate":
15765
+ res.status(200).json({ seq, text: result.text, chunk_count: result.chunkCount, duplicate: true });
15766
+ return;
15767
+ case "out_of_order":
15768
+ res.status(409).json({
15769
+ detail: `Chunk ${seq} is ahead of the next expected chunk ${result.chunkCount}.`,
15770
+ kind: "out_of_order",
15771
+ chunk_count: result.chunkCount
15772
+ });
15773
+ return;
15774
+ case "not_recording":
15775
+ res.status(409).json({ detail: `Recording is not active (status '${result.status}').`, kind: "not_recording" });
15776
+ return;
15777
+ }
15778
+ });
15779
+ }
15780
+
15459
15781
  // src/exulu/speech.ts
15460
15782
  var SpeechError = class extends Error {
15461
15783
  constructor(upstreamStatus, message) {
@@ -16757,6 +17079,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
16757
17079
  },
16758
17080
  recall: {
16759
17081
  enabled: recallEnabled()
17082
+ },
17083
+ // Whisper upload transcription (TRANSCRIPTION_SERVER). The Transcripts
17084
+ // page gates its "Upload a file" mode on this — previously it was gated
17085
+ // on the composer-mic flag and showed an upload mode that could not work.
17086
+ whisper: {
17087
+ enabled: transcriptionClient.isConfigured()
16760
17088
  }
16761
17089
  });
16762
17090
  });
@@ -17278,19 +17606,20 @@ ${customInstructions}` : agent.instructions,
17278
17606
  storage: multer.memoryStorage(),
17279
17607
  limits: { fileSize: MAX_TRANSCRIBE_BYTES }
17280
17608
  });
17609
+ const transcribeUploadMiddleware = (req, res, next) => {
17610
+ transcribeUpload.single("file")(req, res, (err) => {
17611
+ if (!err) return next();
17612
+ const code = err?.code;
17613
+ if (code === "LIMIT_FILE_SIZE") {
17614
+ res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
17615
+ return;
17616
+ }
17617
+ res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
17618
+ });
17619
+ };
17281
17620
  app.post(
17282
17621
  "/transcribe",
17283
- (req, res, next) => {
17284
- transcribeUpload.single("file")(req, res, (err) => {
17285
- if (!err) return next();
17286
- const code = err?.code;
17287
- if (code === "LIMIT_FILE_SIZE") {
17288
- res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
17289
- return;
17290
- }
17291
- res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
17292
- });
17293
- },
17622
+ transcribeUploadMiddleware,
17294
17623
  async (req, res) => {
17295
17624
  if (!isLiteLLMEnabled() || !process.env.TRANSCRIPTION_MODEL) {
17296
17625
  res.status(503).json({
@@ -17342,6 +17671,17 @@ ${customInstructions}` : agent.instructions,
17342
17671
  }
17343
17672
  }
17344
17673
  );
17674
+ registerLiveRecordingChunkRoute(app, {
17675
+ upload: transcribeUploadMiddleware,
17676
+ enabled: liveRecordingEnabled,
17677
+ authenticate: (req) => requestValidators.authenticate(req),
17678
+ getDb: async () => (await postgresClient()).db,
17679
+ assertOwns: assertOwnsTranscriptionJob,
17680
+ waitForLiteLLMReady,
17681
+ buildTags,
17682
+ transcribe: transcribeAudio,
17683
+ service: liveRecordingService
17684
+ });
17345
17685
  const MAX_TTS_INPUT_CHARS = 4e3;
17346
17686
  app.post(
17347
17687
  "/speech",
@@ -21640,6 +21980,9 @@ var ExuluApp = class {
21640
21980
  "[EXULU] TRANSCRIPTION_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /transcribe endpoint will return 503 until LiteLLM is enabled."
21641
21981
  );
21642
21982
  }
21983
+ console.log(
21984
+ `[EXULU] Live recording (Transcripts page): ${liveRecordingEnabled() ? "enabled" : "disabled"} (EXULU_USE_LITELLM=${process.env.EXULU_USE_LITELLM ?? "unset"}, TRANSCRIPTION_MODEL=${process.env.TRANSCRIPTION_MODEL ? "set" : "unset"})`
21985
+ );
21643
21986
  if (process.env.TTS_MODEL && !isLiteLLMEnabled()) {
21644
21987
  console.warn(
21645
21988
  "[EXULU] TTS_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /speech endpoint will return 503 until LiteLLM is enabled."
@@ -23105,7 +23448,7 @@ ${WARNING_BANNER}`);
23105
23448
  console.warn(`${WARNING_BANNER}
23106
23449
  `);
23107
23450
  };
23108
- var log4 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
23451
+ var log5 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
23109
23452
  var initLiteLLMDatabase = async (packageRoot) => {
23110
23453
  const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve3(process.cwd(), "./config.litellm.yaml");
23111
23454
  const safety = checkLiteLLMDatabaseSafety(configPath);
@@ -23139,7 +23482,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23139
23482
  return;
23140
23483
  }
23141
23484
  const target = "litellmTarget" in safety ? safety.litellmTarget : void 0;
23142
- log4(
23485
+ log5(
23143
23486
  `LiteLLM database mode detected (${target?.host}:${target?.port}/${target?.database}).`
23144
23487
  );
23145
23488
  const ensureDatabaseExists = async () => {
@@ -23167,7 +23510,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23167
23510
  return false;
23168
23511
  }
23169
23512
  url.pathname = "/postgres";
23170
- log4(`Target database "${targetDbName}" does not exist; creating it\u2026`);
23513
+ log5(`Target database "${targetDbName}" does not exist; creating it\u2026`);
23171
23514
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(targetDbName)) {
23172
23515
  warn2([
23173
23516
  `Refusing to auto-create database "${targetDbName}" \u2014 name`,
@@ -23180,7 +23523,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23180
23523
  try {
23181
23524
  await admin.connect();
23182
23525
  await admin.query(`CREATE DATABASE "${targetDbName}"`);
23183
- log4(`\u2713 Created database "${targetDbName}".`);
23526
+ log5(`\u2713 Created database "${targetDbName}".`);
23184
23527
  return true;
23185
23528
  } catch (createErr) {
23186
23529
  warn2([
@@ -23202,7 +23545,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23202
23545
  }
23203
23546
  };
23204
23547
  if (!await ensureDatabaseExists()) return;
23205
- log4("Checking that the target database is safe to push into\u2026");
23548
+ log5("Checking that the target database is safe to push into\u2026");
23206
23549
  const client2 = new Client({ connectionString: litellmUrl });
23207
23550
  let foreignTables = [];
23208
23551
  try {
@@ -23278,7 +23621,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23278
23621
  ]);
23279
23622
  return;
23280
23623
  }
23281
- log4("Running `prisma db push` against LiteLLM's schema\u2026");
23624
+ log5("Running `prisma db push` against LiteLLM's schema\u2026");
23282
23625
  const result = spawnSync(prismaCli, ["db", "push", "--skip-generate"], {
23283
23626
  cwd: litellmProxyDir,
23284
23627
  env: {
@@ -23308,7 +23651,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23308
23651
  ]);
23309
23652
  return;
23310
23653
  }
23311
- log4("\u2713 LiteLLM database ready.");
23654
+ log5("\u2713 LiteLLM database ready.");
23312
23655
  };
23313
23656
 
23314
23657
  // src/postgres/init-litellm-db.ts
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "4.2.0",
4
+ "version": "4.3.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {