@exulu/backend 4.2.1 → 4.3.1

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 +386 -42
  2. package/dist/index.js +378 -42
  3. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -12423,7 +12423,14 @@ var transcriptionJobsSchema = {
12423
12423
  // when RECALL_STORE_VIDEO_LOCALLY=true. Null when that flag is off (the
12424
12424
  // video then stays reachable only via ExuluRecall.getRecordingVideoUrl,
12425
12425
  // for as long as Recall itself retains it) or for Whisper upload jobs.
12426
- { 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" }
12427
12434
  ]
12428
12435
  };
12429
12436
  var imageGenerationsSchema = {
@@ -21208,6 +21215,30 @@ var transcriptionService = {
21208
21215
  }
21209
21216
  };
21210
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
+
21211
21242
  // src/exulu/recall/service.ts
21212
21243
  init_cjs_shims();
21213
21244
  var import_ai8 = require("ai");
@@ -22154,6 +22185,106 @@ ${transcriptText}`,
22154
22185
  }
22155
22186
  };
22156
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
+
22157
22288
  // src/exulu/email-inbound/trigger-config.ts
22158
22289
  init_cjs_shims();
22159
22290
  var import_node_crypto9 = require("crypto");
@@ -22967,6 +23098,8 @@ type PageInfo {
22967
23098
  transcriptionJobCancel(id: ID!): transcription_job
22968
23099
  meetingBotStart(input: MeetingBotStartInput!): transcription_job
22969
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
22970
23103
  `;
22971
23104
  mutationDefs += `
22972
23105
  upsertWorkflowEmailTrigger(workflow: ID!, enabled: Boolean!, config: JSON!): WorkflowTrigger
@@ -23022,6 +23155,21 @@ type PageInfo {
23022
23155
  agent_id: ID!
23023
23156
  }
23024
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
+
23025
23173
  type MeetingRecordingUsage {
23026
23174
  enabled: Boolean!
23027
23175
  used_seconds: Float!
@@ -23935,16 +24083,7 @@ type LiteLLMModel {
23935
24083
  }
23936
24084
  return { success: true };
23937
24085
  };
23938
- const assertOwnsTranscriptionJob = async (id, context) => {
23939
- const { db: db2, user } = context;
23940
- if (!user) throw new Error("Authentication required");
23941
- if (user.super_admin === true) return;
23942
- const row = await db2.from("transcription_jobs").select(["created_by", "rights_mode"]).where({ id }).first();
23943
- if (!row) throw new Error(`transcription_job ${id} not found`);
23944
- if (row.rights_mode === "public") return;
23945
- if (row.created_by != null && String(row.created_by) === String(user.id)) return;
23946
- throw new Error("Not authorized to act on this transcription job");
23947
- };
24086
+ const assertOwnsTranscriptionJob2 = async (id, context) => assertOwnsTranscriptionJob(context.db, context.user, id);
23948
24087
  resolvers.Mutation["transcriptionJobStart"] = async (_, args, context) => {
23949
24088
  const { user } = context;
23950
24089
  if (!user) throw new Error("Authentication required");
@@ -23968,7 +24107,7 @@ type LiteLLMModel {
23968
24107
  });
23969
24108
  };
23970
24109
  resolvers.Mutation["transcriptionJobFinalize"] = async (_, args, context) => {
23971
- await assertOwnsTranscriptionJob(args.id, context);
24110
+ await assertOwnsTranscriptionJob2(args.id, context);
23972
24111
  const { item, row } = await transcriptionService.finalize(args.id, {
23973
24112
  title: args.input.title,
23974
24113
  speakers: args.input.speakers,
@@ -23980,7 +24119,7 @@ type LiteLLMModel {
23980
24119
  return { job: row, item_id: item.id };
23981
24120
  };
23982
24121
  resolvers.Mutation["transcriptionJobCancel"] = async (_, args, context) => {
23983
- await assertOwnsTranscriptionJob(args.id, context);
24122
+ await assertOwnsTranscriptionJob2(args.id, context);
23984
24123
  return transcriptionService.cancelJob(args.id);
23985
24124
  };
23986
24125
  resolvers.Mutation["meetingBotStart"] = async (_, args, context) => {
@@ -24005,17 +24144,41 @@ type LiteLLMModel {
24005
24144
  });
24006
24145
  };
24007
24146
  resolvers.Mutation["runTranscriptPostProcessing"] = async (_, args, context) => {
24008
- await assertOwnsTranscriptionJob(args.id, context);
24147
+ await assertOwnsTranscriptionJob2(args.id, context);
24009
24148
  await recallService.runOnePostProcessing(args.id, args.prompt_id, args.agent_id);
24010
24149
  const { db: db2 } = context;
24011
24150
  return db2.from("transcription_jobs").where({ id: args.id }).first();
24012
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
+ };
24013
24176
  resolvers.Query["meetingRecordingUsage"] = async (_, __, context) => {
24014
24177
  if (!context.user) throw new Error("Authentication required");
24015
24178
  return recallService.getUsage();
24016
24179
  };
24017
24180
  resolvers.Query["recordingVideoUrl"] = async (_, args, context) => {
24018
- await assertOwnsTranscriptionJob(args.job_id, context);
24181
+ await assertOwnsTranscriptionJob2(args.job_id, context);
24019
24182
  const { db: db2 } = context;
24020
24183
  const row = await db2.from("transcription_jobs").select(["recall_recording_id"]).where({ id: args.job_id }).first();
24021
24184
  if (!row?.recall_recording_id) return null;
@@ -25137,6 +25300,13 @@ var TranscriptionError = class extends Error {
25137
25300
  this.name = "TranscriptionError";
25138
25301
  }
25139
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
+ }
25140
25310
  async function transcribeAudio(args) {
25141
25311
  const target = resolveLiteLLMTarget();
25142
25312
  const model = process.env.TRANSCRIPTION_MODEL;
@@ -25156,6 +25326,7 @@ async function transcribeViaAudioEndpoint(args, target, model) {
25156
25326
  );
25157
25327
  form.append("model", model);
25158
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));
25159
25330
  const res = await fetch(`${target.baseUrl}/v1/audio/transcriptions`, {
25160
25331
  method: "POST",
25161
25332
  headers: { ...target.authHeaders },
@@ -25183,14 +25354,18 @@ async function transcribeViaChat(args, target, model) {
25183
25354
  {
25184
25355
  role: "user",
25185
25356
  content: [
25186
- { type: "text", text: "Transcribe this audio." },
25357
+ { type: "text", text: buildTranscribeUserText(args.priorText) },
25187
25358
  {
25188
25359
  type: "input_audio",
25189
25360
  input_audio: { data: args.file.buffer.toString("base64"), format }
25190
25361
  }
25191
25362
  ]
25192
25363
  }
25193
- ]
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 } } : {}
25194
25369
  };
25195
25370
  const res = await fetch(`${target.baseUrl}/v1/chat/completions`, {
25196
25371
  method: "POST",
@@ -25208,6 +25383,144 @@ async function transcribeViaChat(args, target, model) {
25208
25383
  return { text: cleanTranscript(json.choices?.[0]?.message?.content) };
25209
25384
  }
25210
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
+
25211
25524
  // src/exulu/speech.ts
25212
25525
  init_cjs_shims();
25213
25526
  init_env();
@@ -25667,15 +25980,21 @@ init_entitlements();
25667
25980
 
25668
25981
  // src/utils/enabled-skills.ts
25669
25982
  init_cjs_shims();
25983
+ init_client();
25670
25984
  var getEnabledSkills = async (agent, disabledSkills = []) => {
25671
- let enabledSkills = [];
25672
- if (agent.skills) {
25673
- enabledSkills = agent.skills.filter(Boolean);
25674
- }
25675
- console.log("[EXULU] available skills", enabledSkills?.length);
25985
+ const refs = (agent.skills?.filter(Boolean) ?? []).filter(
25986
+ (skill) => !disabledSkills.includes(skill.id)
25987
+ );
25988
+ if (refs.length === 0) return [];
25989
+ const { db: db2 } = await postgresClient();
25990
+ const rows = await db2.from("skills").whereIn(
25991
+ "id",
25992
+ refs.map((skill) => skill.id)
25993
+ );
25994
+ const rowById = new Map(rows.map((row) => [row.id, row]));
25995
+ console.log("[EXULU] available skills", refs.length, "resolved", rows.length);
25676
25996
  console.log("[EXULU] disabled skills", disabledSkills?.length);
25677
- enabledSkills = enabledSkills.filter((skill) => !disabledSkills.includes(skill.id));
25678
- return enabledSkills;
25997
+ return refs.map((ref) => rowById.get(ref.id)).filter((row) => row != null);
25679
25998
  };
25680
25999
 
25681
26000
  // src/exulu/auth/callback-handler.ts
@@ -26555,6 +26874,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
26555
26874
  },
26556
26875
  recall: {
26557
26876
  enabled: recallEnabled()
26877
+ },
26878
+ // Whisper upload transcription (TRANSCRIPTION_SERVER). The Transcripts
26879
+ // page gates its "Upload a file" mode on this — previously it was gated
26880
+ // on the composer-mic flag and showed an upload mode that could not work.
26881
+ whisper: {
26882
+ enabled: transcriptionClient.isConfigured()
26558
26883
  }
26559
26884
  });
26560
26885
  });
@@ -27076,19 +27401,20 @@ ${customInstructions}` : agent.instructions,
27076
27401
  storage: import_multer.default.memoryStorage(),
27077
27402
  limits: { fileSize: MAX_TRANSCRIBE_BYTES }
27078
27403
  });
27404
+ const transcribeUploadMiddleware = (req, res, next) => {
27405
+ transcribeUpload.single("file")(req, res, (err) => {
27406
+ if (!err) return next();
27407
+ const code = err?.code;
27408
+ if (code === "LIMIT_FILE_SIZE") {
27409
+ res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
27410
+ return;
27411
+ }
27412
+ res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
27413
+ });
27414
+ };
27079
27415
  app.post(
27080
27416
  "/transcribe",
27081
- (req, res, next) => {
27082
- transcribeUpload.single("file")(req, res, (err) => {
27083
- if (!err) return next();
27084
- const code = err?.code;
27085
- if (code === "LIMIT_FILE_SIZE") {
27086
- res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
27087
- return;
27088
- }
27089
- res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
27090
- });
27091
- },
27417
+ transcribeUploadMiddleware,
27092
27418
  async (req, res) => {
27093
27419
  if (!isLiteLLMEnabled() || !process.env.TRANSCRIPTION_MODEL) {
27094
27420
  res.status(503).json({
@@ -27140,6 +27466,17 @@ ${customInstructions}` : agent.instructions,
27140
27466
  }
27141
27467
  }
27142
27468
  );
27469
+ registerLiveRecordingChunkRoute(app, {
27470
+ upload: transcribeUploadMiddleware,
27471
+ enabled: liveRecordingEnabled,
27472
+ authenticate: (req) => requestValidators.authenticate(req),
27473
+ getDb: async () => (await postgresClient()).db,
27474
+ assertOwns: assertOwnsTranscriptionJob,
27475
+ waitForLiteLLMReady,
27476
+ buildTags,
27477
+ transcribe: transcribeAudio,
27478
+ service: liveRecordingService
27479
+ });
27143
27480
  const MAX_TTS_INPUT_CHARS = 4e3;
27144
27481
  app.post(
27145
27482
  "/speech",
@@ -28619,6 +28956,7 @@ ${style.markdown}` : params.prompt;
28619
28956
  const history = Array.isArray(existing.history) ? existing.history : [];
28620
28957
  await db2("skills").where({ id: existing.id }).update({
28621
28958
  current_version: nextVersion,
28959
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
28622
28960
  history: JSON.stringify([
28623
28961
  ...history,
28624
28962
  { version: nextVersion, created_at: (/* @__PURE__ */ new Date()).toISOString(), label: "Published from agent" }
@@ -28735,6 +29073,7 @@ ${style.markdown}` : params.prompt;
28735
29073
  await db2("skills").where({ id: skillId }).update({
28736
29074
  s3folder: `skills/${skillId}`,
28737
29075
  current_version: 1,
29076
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
28738
29077
  history: JSON.stringify([
28739
29078
  { version: 1, created_at: (/* @__PURE__ */ new Date()).toISOString(), label: "Initial" }
28740
29079
  ])
@@ -28839,6 +29178,7 @@ ${style.markdown}` : params.prompt;
28839
29178
  await db2("skills").where({ id: skillId }).update({
28840
29179
  s3folder: `skills/${skillId}`,
28841
29180
  current_version: 1,
29181
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
28842
29182
  history: JSON.stringify([
28843
29183
  { version: 1, created_at: (/* @__PURE__ */ new Date()).toISOString(), label: "Uploaded bundle" }
28844
29184
  ])
@@ -29066,6 +29406,7 @@ ${style.markdown}` : params.prompt;
29066
29406
  ];
29067
29407
  await db2("skills").where({ id: skillId }).update({
29068
29408
  current_version: newVersion,
29409
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
29069
29410
  history: JSON.stringify(newHistory)
29070
29411
  });
29071
29412
  res.json({ newVersion, fileCount: files.length });
@@ -31494,6 +31835,9 @@ var ExuluApp = class {
31494
31835
  "[EXULU] TRANSCRIPTION_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /transcribe endpoint will return 503 until LiteLLM is enabled."
31495
31836
  );
31496
31837
  }
31838
+ console.log(
31839
+ `[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"})`
31840
+ );
31497
31841
  if (process.env.TTS_MODEL && !isLiteLLMEnabled()) {
31498
31842
  console.warn(
31499
31843
  "[EXULU] TTS_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /speech endpoint will return 503 until LiteLLM is enabled."
@@ -32986,7 +33330,7 @@ ${WARNING_BANNER}`);
32986
33330
  console.warn(`${WARNING_BANNER}
32987
33331
  `);
32988
33332
  };
32989
- var log5 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
33333
+ var log6 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
32990
33334
  var initLiteLLMDatabase = async (packageRoot) => {
32991
33335
  const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path11.resolve)(process.cwd(), "./config.litellm.yaml");
32992
33336
  const safety = checkLiteLLMDatabaseSafety(configPath);
@@ -33020,7 +33364,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33020
33364
  return;
33021
33365
  }
33022
33366
  const target = "litellmTarget" in safety ? safety.litellmTarget : void 0;
33023
- log5(
33367
+ log6(
33024
33368
  `LiteLLM database mode detected (${target?.host}:${target?.port}/${target?.database}).`
33025
33369
  );
33026
33370
  const ensureDatabaseExists2 = async () => {
@@ -33048,7 +33392,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33048
33392
  return false;
33049
33393
  }
33050
33394
  url.pathname = "/postgres";
33051
- log5(`Target database "${targetDbName}" does not exist; creating it\u2026`);
33395
+ log6(`Target database "${targetDbName}" does not exist; creating it\u2026`);
33052
33396
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(targetDbName)) {
33053
33397
  warn2([
33054
33398
  `Refusing to auto-create database "${targetDbName}" \u2014 name`,
@@ -33061,7 +33405,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33061
33405
  try {
33062
33406
  await admin.connect();
33063
33407
  await admin.query(`CREATE DATABASE "${targetDbName}"`);
33064
- log5(`\u2713 Created database "${targetDbName}".`);
33408
+ log6(`\u2713 Created database "${targetDbName}".`);
33065
33409
  return true;
33066
33410
  } catch (createErr) {
33067
33411
  warn2([
@@ -33083,7 +33427,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33083
33427
  }
33084
33428
  };
33085
33429
  if (!await ensureDatabaseExists2()) return;
33086
- log5("Checking that the target database is safe to push into\u2026");
33430
+ log6("Checking that the target database is safe to push into\u2026");
33087
33431
  const client2 = new import_pg.Client({ connectionString: litellmUrl });
33088
33432
  let foreignTables = [];
33089
33433
  try {
@@ -33159,7 +33503,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33159
33503
  ]);
33160
33504
  return;
33161
33505
  }
33162
- log5("Running `prisma db push` against LiteLLM's schema\u2026");
33506
+ log6("Running `prisma db push` against LiteLLM's schema\u2026");
33163
33507
  const result = (0, import_node_child_process6.spawnSync)(prismaCli, ["db", "push", "--skip-generate"], {
33164
33508
  cwd: litellmProxyDir,
33165
33509
  env: {
@@ -33189,7 +33533,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
33189
33533
  ]);
33190
33534
  return;
33191
33535
  }
33192
- log5("\u2713 LiteLLM database ready.");
33536
+ log6("\u2713 LiteLLM database ready.");
33193
33537
  };
33194
33538
 
33195
33539
  // src/postgres/init-litellm-db.ts
package/dist/index.js CHANGED
@@ -2888,7 +2888,14 @@ var transcriptionJobsSchema = {
2888
2888
  // when RECALL_STORE_VIDEO_LOCALLY=true. Null when that flag is off (the
2889
2889
  // video then stays reachable only via ExuluRecall.getRecordingVideoUrl,
2890
2890
  // for as long as Recall itself retains it) or for Whisper upload jobs.
2891
- { 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" }
2892
2899
  ]
2893
2900
  };
2894
2901
  var imageGenerationsSchema = {
@@ -11513,6 +11520,24 @@ var transcriptionService = {
11513
11520
  }
11514
11521
  };
11515
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
+
11516
11541
  // src/exulu/recall/service.ts
11517
11542
  import { generateText as generateText4 } from "ai";
11518
11543
 
@@ -12448,6 +12473,106 @@ ${transcriptText}`,
12448
12473
  }
12449
12474
  };
12450
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
+
12451
12576
  // src/exulu/email-inbound/trigger-config.ts
12452
12577
  import { randomBytes } from "crypto";
12453
12578
  import safeRegex from "safe-regex";
@@ -13253,6 +13378,8 @@ type PageInfo {
13253
13378
  transcriptionJobCancel(id: ID!): transcription_job
13254
13379
  meetingBotStart(input: MeetingBotStartInput!): transcription_job
13255
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
13256
13383
  `;
13257
13384
  mutationDefs += `
13258
13385
  upsertWorkflowEmailTrigger(workflow: ID!, enabled: Boolean!, config: JSON!): WorkflowTrigger
@@ -13308,6 +13435,21 @@ type PageInfo {
13308
13435
  agent_id: ID!
13309
13436
  }
13310
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
+
13311
13453
  type MeetingRecordingUsage {
13312
13454
  enabled: Boolean!
13313
13455
  used_seconds: Float!
@@ -14221,16 +14363,7 @@ type LiteLLMModel {
14221
14363
  }
14222
14364
  return { success: true };
14223
14365
  };
14224
- const assertOwnsTranscriptionJob = async (id, context) => {
14225
- const { db, user } = context;
14226
- if (!user) throw new Error("Authentication required");
14227
- if (user.super_admin === true) return;
14228
- const row = await db.from("transcription_jobs").select(["created_by", "rights_mode"]).where({ id }).first();
14229
- if (!row) throw new Error(`transcription_job ${id} not found`);
14230
- if (row.rights_mode === "public") return;
14231
- if (row.created_by != null && String(row.created_by) === String(user.id)) return;
14232
- throw new Error("Not authorized to act on this transcription job");
14233
- };
14366
+ const assertOwnsTranscriptionJob2 = async (id, context) => assertOwnsTranscriptionJob(context.db, context.user, id);
14234
14367
  resolvers.Mutation["transcriptionJobStart"] = async (_, args, context) => {
14235
14368
  const { user } = context;
14236
14369
  if (!user) throw new Error("Authentication required");
@@ -14254,7 +14387,7 @@ type LiteLLMModel {
14254
14387
  });
14255
14388
  };
14256
14389
  resolvers.Mutation["transcriptionJobFinalize"] = async (_, args, context) => {
14257
- await assertOwnsTranscriptionJob(args.id, context);
14390
+ await assertOwnsTranscriptionJob2(args.id, context);
14258
14391
  const { item, row } = await transcriptionService.finalize(args.id, {
14259
14392
  title: args.input.title,
14260
14393
  speakers: args.input.speakers,
@@ -14266,7 +14399,7 @@ type LiteLLMModel {
14266
14399
  return { job: row, item_id: item.id };
14267
14400
  };
14268
14401
  resolvers.Mutation["transcriptionJobCancel"] = async (_, args, context) => {
14269
- await assertOwnsTranscriptionJob(args.id, context);
14402
+ await assertOwnsTranscriptionJob2(args.id, context);
14270
14403
  return transcriptionService.cancelJob(args.id);
14271
14404
  };
14272
14405
  resolvers.Mutation["meetingBotStart"] = async (_, args, context) => {
@@ -14291,17 +14424,41 @@ type LiteLLMModel {
14291
14424
  });
14292
14425
  };
14293
14426
  resolvers.Mutation["runTranscriptPostProcessing"] = async (_, args, context) => {
14294
- await assertOwnsTranscriptionJob(args.id, context);
14427
+ await assertOwnsTranscriptionJob2(args.id, context);
14295
14428
  await recallService.runOnePostProcessing(args.id, args.prompt_id, args.agent_id);
14296
14429
  const { db } = context;
14297
14430
  return db.from("transcription_jobs").where({ id: args.id }).first();
14298
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
+ };
14299
14456
  resolvers.Query["meetingRecordingUsage"] = async (_, __, context) => {
14300
14457
  if (!context.user) throw new Error("Authentication required");
14301
14458
  return recallService.getUsage();
14302
14459
  };
14303
14460
  resolvers.Query["recordingVideoUrl"] = async (_, args, context) => {
14304
- await assertOwnsTranscriptionJob(args.job_id, context);
14461
+ await assertOwnsTranscriptionJob2(args.job_id, context);
14305
14462
  const { db } = context;
14306
14463
  const row = await db.from("transcription_jobs").select(["recall_recording_id"]).where({ id: args.job_id }).first();
14307
14464
  if (!row?.recall_recording_id) return null;
@@ -15401,6 +15558,13 @@ var TranscriptionError = class extends Error {
15401
15558
  this.name = "TranscriptionError";
15402
15559
  }
15403
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
+ }
15404
15568
  async function transcribeAudio(args) {
15405
15569
  const target = resolveLiteLLMTarget();
15406
15570
  const model = process.env.TRANSCRIPTION_MODEL;
@@ -15420,6 +15584,7 @@ async function transcribeViaAudioEndpoint(args, target, model) {
15420
15584
  );
15421
15585
  form.append("model", model);
15422
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));
15423
15588
  const res = await fetch(`${target.baseUrl}/v1/audio/transcriptions`, {
15424
15589
  method: "POST",
15425
15590
  headers: { ...target.authHeaders },
@@ -15447,14 +15612,18 @@ async function transcribeViaChat(args, target, model) {
15447
15612
  {
15448
15613
  role: "user",
15449
15614
  content: [
15450
- { type: "text", text: "Transcribe this audio." },
15615
+ { type: "text", text: buildTranscribeUserText(args.priorText) },
15451
15616
  {
15452
15617
  type: "input_audio",
15453
15618
  input_audio: { data: args.file.buffer.toString("base64"), format }
15454
15619
  }
15455
15620
  ]
15456
15621
  }
15457
- ]
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 } } : {}
15458
15627
  };
15459
15628
  const res = await fetch(`${target.baseUrl}/v1/chat/completions`, {
15460
15629
  method: "POST",
@@ -15472,6 +15641,143 @@ async function transcribeViaChat(args, target, model) {
15472
15641
  return { text: cleanTranscript(json.choices?.[0]?.message?.content) };
15473
15642
  }
15474
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
+
15475
15781
  // src/exulu/speech.ts
15476
15782
  var SpeechError = class extends Error {
15477
15783
  constructor(upstreamStatus, message) {
@@ -15908,14 +16214,19 @@ function checkApiKeyScope(user, agentId) {
15908
16214
 
15909
16215
  // src/utils/enabled-skills.ts
15910
16216
  var getEnabledSkills = async (agent, disabledSkills = []) => {
15911
- let enabledSkills = [];
15912
- if (agent.skills) {
15913
- enabledSkills = agent.skills.filter(Boolean);
15914
- }
15915
- console.log("[EXULU] available skills", enabledSkills?.length);
16217
+ const refs = (agent.skills?.filter(Boolean) ?? []).filter(
16218
+ (skill) => !disabledSkills.includes(skill.id)
16219
+ );
16220
+ if (refs.length === 0) return [];
16221
+ const { db } = await postgresClient();
16222
+ const rows = await db.from("skills").whereIn(
16223
+ "id",
16224
+ refs.map((skill) => skill.id)
16225
+ );
16226
+ const rowById = new Map(rows.map((row) => [row.id, row]));
16227
+ console.log("[EXULU] available skills", refs.length, "resolved", rows.length);
15916
16228
  console.log("[EXULU] disabled skills", disabledSkills?.length);
15917
- enabledSkills = enabledSkills.filter((skill) => !disabledSkills.includes(skill.id));
15918
- return enabledSkills;
16229
+ return refs.map((ref) => rowById.get(ref.id)).filter((row) => row != null);
15919
16230
  };
15920
16231
 
15921
16232
  // src/exulu/auth/callback-handler.ts
@@ -16773,6 +17084,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
16773
17084
  },
16774
17085
  recall: {
16775
17086
  enabled: recallEnabled()
17087
+ },
17088
+ // Whisper upload transcription (TRANSCRIPTION_SERVER). The Transcripts
17089
+ // page gates its "Upload a file" mode on this — previously it was gated
17090
+ // on the composer-mic flag and showed an upload mode that could not work.
17091
+ whisper: {
17092
+ enabled: transcriptionClient.isConfigured()
16776
17093
  }
16777
17094
  });
16778
17095
  });
@@ -17294,19 +17611,20 @@ ${customInstructions}` : agent.instructions,
17294
17611
  storage: multer.memoryStorage(),
17295
17612
  limits: { fileSize: MAX_TRANSCRIBE_BYTES }
17296
17613
  });
17614
+ const transcribeUploadMiddleware = (req, res, next) => {
17615
+ transcribeUpload.single("file")(req, res, (err) => {
17616
+ if (!err) return next();
17617
+ const code = err?.code;
17618
+ if (code === "LIMIT_FILE_SIZE") {
17619
+ res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
17620
+ return;
17621
+ }
17622
+ res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
17623
+ });
17624
+ };
17297
17625
  app.post(
17298
17626
  "/transcribe",
17299
- (req, res, next) => {
17300
- transcribeUpload.single("file")(req, res, (err) => {
17301
- if (!err) return next();
17302
- const code = err?.code;
17303
- if (code === "LIMIT_FILE_SIZE") {
17304
- res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
17305
- return;
17306
- }
17307
- res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
17308
- });
17309
- },
17627
+ transcribeUploadMiddleware,
17310
17628
  async (req, res) => {
17311
17629
  if (!isLiteLLMEnabled() || !process.env.TRANSCRIPTION_MODEL) {
17312
17630
  res.status(503).json({
@@ -17358,6 +17676,17 @@ ${customInstructions}` : agent.instructions,
17358
17676
  }
17359
17677
  }
17360
17678
  );
17679
+ registerLiveRecordingChunkRoute(app, {
17680
+ upload: transcribeUploadMiddleware,
17681
+ enabled: liveRecordingEnabled,
17682
+ authenticate: (req) => requestValidators.authenticate(req),
17683
+ getDb: async () => (await postgresClient()).db,
17684
+ assertOwns: assertOwnsTranscriptionJob,
17685
+ waitForLiteLLMReady,
17686
+ buildTags,
17687
+ transcribe: transcribeAudio,
17688
+ service: liveRecordingService
17689
+ });
17361
17690
  const MAX_TTS_INPUT_CHARS = 4e3;
17362
17691
  app.post(
17363
17692
  "/speech",
@@ -18837,6 +19166,7 @@ ${style.markdown}` : params.prompt;
18837
19166
  const history = Array.isArray(existing.history) ? existing.history : [];
18838
19167
  await db("skills").where({ id: existing.id }).update({
18839
19168
  current_version: nextVersion,
19169
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
18840
19170
  history: JSON.stringify([
18841
19171
  ...history,
18842
19172
  { version: nextVersion, created_at: (/* @__PURE__ */ new Date()).toISOString(), label: "Published from agent" }
@@ -18953,6 +19283,7 @@ ${style.markdown}` : params.prompt;
18953
19283
  await db("skills").where({ id: skillId }).update({
18954
19284
  s3folder: `skills/${skillId}`,
18955
19285
  current_version: 1,
19286
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
18956
19287
  history: JSON.stringify([
18957
19288
  { version: 1, created_at: (/* @__PURE__ */ new Date()).toISOString(), label: "Initial" }
18958
19289
  ])
@@ -19057,6 +19388,7 @@ ${style.markdown}` : params.prompt;
19057
19388
  await db("skills").where({ id: skillId }).update({
19058
19389
  s3folder: `skills/${skillId}`,
19059
19390
  current_version: 1,
19391
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
19060
19392
  history: JSON.stringify([
19061
19393
  { version: 1, created_at: (/* @__PURE__ */ new Date()).toISOString(), label: "Uploaded bundle" }
19062
19394
  ])
@@ -19284,6 +19616,7 @@ ${style.markdown}` : params.prompt;
19284
19616
  ];
19285
19617
  await db("skills").where({ id: skillId }).update({
19286
19618
  current_version: newVersion,
19619
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
19287
19620
  history: JSON.stringify(newHistory)
19288
19621
  });
19289
19622
  res.json({ newVersion, fileCount: files.length });
@@ -21656,6 +21989,9 @@ var ExuluApp = class {
21656
21989
  "[EXULU] TRANSCRIPTION_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /transcribe endpoint will return 503 until LiteLLM is enabled."
21657
21990
  );
21658
21991
  }
21992
+ console.log(
21993
+ `[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"})`
21994
+ );
21659
21995
  if (process.env.TTS_MODEL && !isLiteLLMEnabled()) {
21660
21996
  console.warn(
21661
21997
  "[EXULU] TTS_MODEL is set but EXULU_USE_LITELLM is not 'true'. The /speech endpoint will return 503 until LiteLLM is enabled."
@@ -23121,7 +23457,7 @@ ${WARNING_BANNER}`);
23121
23457
  console.warn(`${WARNING_BANNER}
23122
23458
  `);
23123
23459
  };
23124
- var log4 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
23460
+ var log5 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
23125
23461
  var initLiteLLMDatabase = async (packageRoot) => {
23126
23462
  const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve3(process.cwd(), "./config.litellm.yaml");
23127
23463
  const safety = checkLiteLLMDatabaseSafety(configPath);
@@ -23155,7 +23491,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23155
23491
  return;
23156
23492
  }
23157
23493
  const target = "litellmTarget" in safety ? safety.litellmTarget : void 0;
23158
- log4(
23494
+ log5(
23159
23495
  `LiteLLM database mode detected (${target?.host}:${target?.port}/${target?.database}).`
23160
23496
  );
23161
23497
  const ensureDatabaseExists = async () => {
@@ -23183,7 +23519,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23183
23519
  return false;
23184
23520
  }
23185
23521
  url.pathname = "/postgres";
23186
- log4(`Target database "${targetDbName}" does not exist; creating it\u2026`);
23522
+ log5(`Target database "${targetDbName}" does not exist; creating it\u2026`);
23187
23523
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(targetDbName)) {
23188
23524
  warn2([
23189
23525
  `Refusing to auto-create database "${targetDbName}" \u2014 name`,
@@ -23196,7 +23532,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23196
23532
  try {
23197
23533
  await admin.connect();
23198
23534
  await admin.query(`CREATE DATABASE "${targetDbName}"`);
23199
- log4(`\u2713 Created database "${targetDbName}".`);
23535
+ log5(`\u2713 Created database "${targetDbName}".`);
23200
23536
  return true;
23201
23537
  } catch (createErr) {
23202
23538
  warn2([
@@ -23218,7 +23554,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23218
23554
  }
23219
23555
  };
23220
23556
  if (!await ensureDatabaseExists()) return;
23221
- log4("Checking that the target database is safe to push into\u2026");
23557
+ log5("Checking that the target database is safe to push into\u2026");
23222
23558
  const client2 = new Client({ connectionString: litellmUrl });
23223
23559
  let foreignTables = [];
23224
23560
  try {
@@ -23294,7 +23630,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23294
23630
  ]);
23295
23631
  return;
23296
23632
  }
23297
- log4("Running `prisma db push` against LiteLLM's schema\u2026");
23633
+ log5("Running `prisma db push` against LiteLLM's schema\u2026");
23298
23634
  const result = spawnSync(prismaCli, ["db", "push", "--skip-generate"], {
23299
23635
  cwd: litellmProxyDir,
23300
23636
  env: {
@@ -23324,7 +23660,7 @@ var initLiteLLMDatabase = async (packageRoot) => {
23324
23660
  ]);
23325
23661
  return;
23326
23662
  }
23327
- log4("\u2713 LiteLLM database ready.");
23663
+ log5("\u2713 LiteLLM database ready.");
23328
23664
  };
23329
23665
 
23330
23666
  // 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.1",
4
+ "version": "4.3.1",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {