@exulu/backend 5.11.1 → 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,104 +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
- 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) {
623
- console.error(
624
- `[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
625
- error instanceof Error ? error.message : String(error),
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.
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) {
636
599
  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) {
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) {
647
623
  console.error(
648
- `[EXULU] failed to persist run progress for job ${bullmqJob.id}.`,
649
- persistError,
624
+ `[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
625
+ error instanceof Error ? error.message : String(error),
650
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));
651
655
  }
652
- reject(new Error(error instanceof Error ? error.message : String(error)));
653
656
  }
654
- await new Promise((resolve) => setTimeout(() => resolve(true), 2000));
655
- }
656
- }
657
- });
657
+ });
658
658
 
659
- const result = await promise;
659
+ return await promise;
660
+ },
661
+ );
660
662
  const messages = result.messages;
661
663
  const metadata = result.metadata;
662
664
 
@@ -1689,6 +1691,7 @@ export const processUiMessagesFlow = async ({
1689
1691
  config,
1690
1692
  variables,
1691
1693
  routine,
1694
+ jobResultId,
1692
1695
  sessionId,
1693
1696
  resumeFromIndex,
1694
1697
  respectToolApprovals,
@@ -1708,6 +1711,12 @@ export const processUiMessagesFlow = async ({
1708
1711
  * callers leave this undefined — they have no routine context.
1709
1712
  */
1710
1713
  routine?: { id: string; name: string };
1714
+ /**
1715
+ * The job_results row of this run. Tools then receive a `routine` object
1716
+ * (routine.runs.current.update) and writes count as coming from the
1717
+ * worker's run (spec 2026-11-16-routine-work-status-design).
1718
+ */
1719
+ jobResultId?: string;
1711
1720
  /**
1712
1721
  * Session-backed runs (spec §5.1): persist each step's messages to
1713
1722
  * agent_messages at the step boundary, pass the session to generateStream
@@ -1909,6 +1918,7 @@ export const processUiMessagesFlow = async ({
1909
1918
  currentTools: enabledTools,
1910
1919
  currentSkills: enabledSkills,
1911
1920
  allExuluTools: tools,
1921
+ routineRun: jobResultId ? { jobResultId } : undefined,
1912
1922
  languageModel: resolvedLanguageModel,
1913
1923
  toolConfigs: agent.tools,
1914
1924
  exuluConfig: config,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.11.1",
4
+ "version": "5.13.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {