@exulu/backend 5.12.0 → 5.13.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.
package/ee/workers.ts CHANGED
@@ -41,7 +41,7 @@ import { exuluApp } from "@SRC/exulu/app/singleton";
41
41
  import { handleEmailIntake } from "@SRC/exulu/email-inbound/intake";
42
42
  import { markStreamActive, clearStreamActive } from "@SRC/exulu/active-streams.ts";
43
43
  import { messageHasPendingApproval, substituteVariablesInMessage } from "@SRC/exulu/routines/flow-steps.ts";
44
- import { createRunSession } from "@SRC/exulu/routines/run-session.ts";
44
+ import { withRunSession } from "@SRC/exulu/routines/run-session.ts";
45
45
  import { casJobResultState, parseRunMetadata, upsertWorkflowRunStart } from "@SRC/exulu/routines/run-state.ts";
46
46
  import { findLiteLLMModel } from "@SRC/exulu/litellm/catalog.ts";
47
47
  import { computeRunCostUsd } from "@SRC/exulu/routines/run-cost.ts";
@@ -559,105 +559,106 @@ export const createWorkers = async (
559
559
 
560
560
  // Session-backed runs (spec §3.4): reuse the session provided by
561
561
  // the enqueuer (email intake / continuation / retry / previous
562
- // BullMQ attempt), otherwise create one with the routine's rbac
563
- // snapshot under the run identity.
564
- let sessionId = started.session ?? undefined;
565
- if (!sessionId) {
566
- sessionId = await createRunSession({
567
- db,
562
+ // BullMQ attempt) once it is verified to be this routine's run
563
+ // session, otherwise create one with the routine's rbac snapshot
564
+ // under the run identity. A foreign session fails the run before
565
+ // the flow below is ever invoked (withRunSession).
566
+ const result = await withRunSession(
567
+ db,
568
+ {
569
+ existingSession: started.session,
570
+ jobResultId,
568
571
  workflow: {
569
572
  id: workflow.id,
570
573
  name: workflow.name,
571
574
  agent: workflow.agent,
572
575
  rights_mode: workflow.rights_mode,
573
576
  },
574
- userId: user.id,
575
- title: `${workflow.name} — ${new Date().toISOString()}`,
577
+ runUser: user,
576
578
  trigger: data.triggerSource ?? "api",
577
- jobResultId,
578
- });
579
- await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
580
- }
581
-
582
- const retries = 3;
583
- let attempts = 0;
579
+ },
580
+ async (sessionId) => {
581
+ const retries = 3;
582
+ let attempts = 0;
584
583
 
585
- const promise = new Promise<{
586
- messages: UIMessage[];
587
- metadata: {
588
- tokens: {
589
- totalTokens: number;
590
- reasoningTokens: number;
591
- inputTokens: number;
592
- outputTokens: number;
593
- cachedInputTokens: number;
594
- };
595
- duration: number;
596
- };
597
- pausedAtStepIndex?: number;
598
- }>(async (resolve, reject) => {
599
- while (attempts < retries) {
600
- try {
601
- // processUiMessagesFlow mutates inputMessages in place (ids
602
- // + substituted text) — pass a fresh deep copy each attempt
603
- // so a retry/resume never reuses the mutated array.
604
- const messages = await processUiMessagesFlow({
605
- agent,
606
- inputMessages: structuredClone(inputMessages),
607
- contexts,
608
- user,
609
- tools,
610
- config,
611
- variables: data.inputs,
612
- // Tag LLM spend to this routine (cron + ad-hoc share this path).
613
- routine: { id: workflow.id, name: workflow.name },
614
- jobResultId,
615
- sessionId,
616
- resumeFromIndex,
617
- // Approval-gated tools pause unless the routine opted
618
- // back into blanket pre-approval (spec §5.2).
619
- respectToolApprovals: workflow.auto_approve_tools !== true,
620
- });
621
- resolve(messages);
622
- break;
623
- } catch (error: unknown) {
624
- console.error(
625
- `[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
626
- error instanceof Error ? error.message : String(error),
627
- );
628
- if (error instanceof FlowStepError) {
629
- // Completed steps already persisted their messages —
630
- // resume at the failed step (spec §5.4).
631
- resumeFromIndex = error.stepIndex;
632
- }
633
- attempts++;
634
- if (attempts >= retries) {
635
- // Persist progress so BullMQ attempt-level retries and
636
- // retryRoutineRun resume from the failed step.
584
+ const promise = new Promise<{
585
+ messages: UIMessage[];
586
+ metadata: {
587
+ tokens: {
588
+ totalTokens: number;
589
+ reasoningTokens: number;
590
+ inputTokens: number;
591
+ outputTokens: number;
592
+ cachedInputTokens: number;
593
+ };
594
+ duration: number;
595
+ };
596
+ pausedAtStepIndex?: number;
597
+ }>(async (resolve, reject) => {
598
+ while (attempts < retries) {
637
599
  try {
638
- await db
639
- .from("job_results")
640
- .where({ id: jobResultId })
641
- .update({
642
- metadata: JSON.stringify({
643
- ...runBookkeeping,
644
- current_step_index: resumeFromIndex,
645
- }),
646
- });
647
- } catch (persistError) {
600
+ // processUiMessagesFlow mutates inputMessages in place (ids
601
+ // + substituted text) — pass a fresh deep copy each attempt
602
+ // so a retry/resume never reuses the mutated array.
603
+ const messages = await processUiMessagesFlow({
604
+ agent,
605
+ inputMessages: structuredClone(inputMessages),
606
+ contexts,
607
+ user,
608
+ tools,
609
+ config,
610
+ variables: data.inputs,
611
+ // Tag LLM spend to this routine (cron + ad-hoc share this path).
612
+ routine: { id: workflow.id, name: workflow.name },
613
+ jobResultId,
614
+ sessionId,
615
+ resumeFromIndex,
616
+ // Approval-gated tools pause unless the routine opted
617
+ // back into blanket pre-approval (spec §5.2).
618
+ respectToolApprovals: workflow.auto_approve_tools !== true,
619
+ });
620
+ resolve(messages);
621
+ break;
622
+ } catch (error: unknown) {
648
623
  console.error(
649
- `[EXULU] failed to persist run progress for job ${bullmqJob.id}.`,
650
- persistError,
624
+ `[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
625
+ error instanceof Error ? error.message : String(error),
651
626
  );
627
+ if (error instanceof FlowStepError) {
628
+ // Completed steps already persisted their messages —
629
+ // resume at the failed step (spec §5.4).
630
+ resumeFromIndex = error.stepIndex;
631
+ }
632
+ attempts++;
633
+ if (attempts >= retries) {
634
+ // Persist progress so BullMQ attempt-level retries and
635
+ // retryRoutineRun resume from the failed step.
636
+ try {
637
+ await db
638
+ .from("job_results")
639
+ .where({ id: jobResultId })
640
+ .update({
641
+ metadata: JSON.stringify({
642
+ ...runBookkeeping,
643
+ current_step_index: resumeFromIndex,
644
+ }),
645
+ });
646
+ } catch (persistError) {
647
+ console.error(
648
+ `[EXULU] failed to persist run progress for job ${bullmqJob.id}.`,
649
+ persistError,
650
+ );
651
+ }
652
+ reject(new Error(error instanceof Error ? error.message : String(error)));
653
+ }
654
+ await new Promise((resolve) => setTimeout(() => resolve(true), 2000));
652
655
  }
653
- reject(new Error(error instanceof Error ? error.message : String(error)));
654
656
  }
655
- await new Promise((resolve) => setTimeout(() => resolve(true), 2000));
656
- }
657
- }
658
- });
657
+ });
659
658
 
660
- const result = await promise;
659
+ return await promise;
660
+ },
661
+ );
661
662
  const messages = result.messages;
662
663
  const metadata = result.metadata;
663
664
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.12.0",
4
+ "version": "5.13.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {