@exulu/backend 5.11.1 → 5.12.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/dist/index.d.cts CHANGED
@@ -1963,6 +1963,38 @@ declare class RecursiveChunker extends BaseChunker {
1963
1963
  toString(): string;
1964
1964
  }
1965
1965
 
1966
+ /**
1967
+ * The `routine` object a tool's execute receives when its turn is part of a
1968
+ * routine run (spec 2026-11-16-routine-work-status-design): during the
1969
+ * worker's run, and when a person continues that run's session in the chat.
1970
+ * `routine` itself is read-only; everything that writes hangs off
1971
+ * `routine.runs.current`.
1972
+ */
1973
+ type RoutineRunPatch = {
1974
+ /** Work status: a key from routine.statuses. */
1975
+ status?: string;
1976
+ };
1977
+ type RoutineHandle = {
1978
+ id: string;
1979
+ name: string;
1980
+ /** The routine's configured work statuses; [] when none are configured. */
1981
+ statuses: {
1982
+ key: string;
1983
+ label: string;
1984
+ done?: boolean;
1985
+ }[];
1986
+ runs: {
1987
+ current: {
1988
+ /** job_results id of this run. */
1989
+ id: string;
1990
+ /** Current work status of this run. */
1991
+ status: string | null;
1992
+ /** Updates the run. Only the fields of RoutineRunPatch are accepted. */
1993
+ update(patch: RoutineRunPatch): Promise<void>;
1994
+ };
1995
+ };
1996
+ };
1997
+
1966
1998
  interface AuthorizedReadOpts {
1967
1999
  itemIds?: string[];
1968
2000
  externalIds?: string[];
@@ -2855,4 +2887,4 @@ declare const ExuluPython: {
2855
2887
  instructions: typeof getPythonSetupInstructions;
2856
2888
  };
2857
2889
 
2858
- export { type AuditConfig, type AuditEvent, type AuditLogger, type ChunkerOperation, type ChunkerResponse, type CredentialField, CredentialInvalidError, type JOB_STATUS as EXULU_JOB_STATUS, JOB_STATUS_ENUM as EXULU_JOB_STATUS_ENUM, type STATISTICS_TYPE as EXULU_STATISTICS_TYPE, STATISTICS_TYPE_ENUM as EXULU_STATISTICS_TYPE_ENUM, type ExuluAgent, ExuluApp, type ExuluAuthConfig, ExuluAuthentication, ExuluChunkers, ExuluContext, type ExuluContextEmbedder, type ExuluCredentialsToolContext, ExuluDatabase, ExuluDefaultTools, ExuluDocumentProcessor, ExuluEval, type Item as ExuluItem, ExuluJobs, ExuluModels, type ExuluOauthConfig, type ExuluOauthToolContext, ExuluOtel, ExuluPython, queues as ExuluQueues, ExuluReadApi, ExuluRecall, ExuluReranker, ExuluTool, type ExuluUserCredentialsConfig, ExuluVariables, PROJECTION_VERSION, type VectorSearchChunkResult, backfillCoordinates, checkMemoryBase, defaultChunker, enableLiteLLMClientMode, fitContextProjection, listFittableContexts, postgresClient, recallMemories };
2890
+ export { type AuditConfig, type AuditEvent, type AuditLogger, type ChunkerOperation, type ChunkerResponse, type CredentialField, CredentialInvalidError, type JOB_STATUS as EXULU_JOB_STATUS, JOB_STATUS_ENUM as EXULU_JOB_STATUS_ENUM, type STATISTICS_TYPE as EXULU_STATISTICS_TYPE, STATISTICS_TYPE_ENUM as EXULU_STATISTICS_TYPE_ENUM, type ExuluAgent, ExuluApp, type ExuluAuthConfig, ExuluAuthentication, ExuluChunkers, ExuluContext, type ExuluContextEmbedder, type ExuluCredentialsToolContext, ExuluDatabase, ExuluDefaultTools, ExuluDocumentProcessor, ExuluEval, type Item as ExuluItem, ExuluJobs, ExuluModels, type ExuluOauthConfig, type ExuluOauthToolContext, ExuluOtel, ExuluPython, queues as ExuluQueues, ExuluReadApi, ExuluRecall, ExuluReranker, ExuluTool, type ExuluUserCredentialsConfig, ExuluVariables, PROJECTION_VERSION, type RoutineHandle, type RoutineRunPatch, type VectorSearchChunkResult, backfillCoordinates, checkMemoryBase, defaultChunker, enableLiteLLMClientMode, fitContextProjection, listFittableContexts, postgresClient, recallMemories };
package/dist/index.d.ts CHANGED
@@ -1963,6 +1963,38 @@ declare class RecursiveChunker extends BaseChunker {
1963
1963
  toString(): string;
1964
1964
  }
1965
1965
 
1966
+ /**
1967
+ * The `routine` object a tool's execute receives when its turn is part of a
1968
+ * routine run (spec 2026-11-16-routine-work-status-design): during the
1969
+ * worker's run, and when a person continues that run's session in the chat.
1970
+ * `routine` itself is read-only; everything that writes hangs off
1971
+ * `routine.runs.current`.
1972
+ */
1973
+ type RoutineRunPatch = {
1974
+ /** Work status: a key from routine.statuses. */
1975
+ status?: string;
1976
+ };
1977
+ type RoutineHandle = {
1978
+ id: string;
1979
+ name: string;
1980
+ /** The routine's configured work statuses; [] when none are configured. */
1981
+ statuses: {
1982
+ key: string;
1983
+ label: string;
1984
+ done?: boolean;
1985
+ }[];
1986
+ runs: {
1987
+ current: {
1988
+ /** job_results id of this run. */
1989
+ id: string;
1990
+ /** Current work status of this run. */
1991
+ status: string | null;
1992
+ /** Updates the run. Only the fields of RoutineRunPatch are accepted. */
1993
+ update(patch: RoutineRunPatch): Promise<void>;
1994
+ };
1995
+ };
1996
+ };
1997
+
1966
1998
  interface AuthorizedReadOpts {
1967
1999
  itemIds?: string[];
1968
2000
  externalIds?: string[];
@@ -2855,4 +2887,4 @@ declare const ExuluPython: {
2855
2887
  instructions: typeof getPythonSetupInstructions;
2856
2888
  };
2857
2889
 
2858
- export { type AuditConfig, type AuditEvent, type AuditLogger, type ChunkerOperation, type ChunkerResponse, type CredentialField, CredentialInvalidError, type JOB_STATUS as EXULU_JOB_STATUS, JOB_STATUS_ENUM as EXULU_JOB_STATUS_ENUM, type STATISTICS_TYPE as EXULU_STATISTICS_TYPE, STATISTICS_TYPE_ENUM as EXULU_STATISTICS_TYPE_ENUM, type ExuluAgent, ExuluApp, type ExuluAuthConfig, ExuluAuthentication, ExuluChunkers, ExuluContext, type ExuluContextEmbedder, type ExuluCredentialsToolContext, ExuluDatabase, ExuluDefaultTools, ExuluDocumentProcessor, ExuluEval, type Item as ExuluItem, ExuluJobs, ExuluModels, type ExuluOauthConfig, type ExuluOauthToolContext, ExuluOtel, ExuluPython, queues as ExuluQueues, ExuluReadApi, ExuluRecall, ExuluReranker, ExuluTool, type ExuluUserCredentialsConfig, ExuluVariables, PROJECTION_VERSION, type VectorSearchChunkResult, backfillCoordinates, checkMemoryBase, defaultChunker, enableLiteLLMClientMode, fitContextProjection, listFittableContexts, postgresClient, recallMemories };
2890
+ export { type AuditConfig, type AuditEvent, type AuditLogger, type ChunkerOperation, type ChunkerResponse, type CredentialField, CredentialInvalidError, type JOB_STATUS as EXULU_JOB_STATUS, JOB_STATUS_ENUM as EXULU_JOB_STATUS_ENUM, type STATISTICS_TYPE as EXULU_STATISTICS_TYPE, STATISTICS_TYPE_ENUM as EXULU_STATISTICS_TYPE_ENUM, type ExuluAgent, ExuluApp, type ExuluAuthConfig, ExuluAuthentication, ExuluChunkers, ExuluContext, type ExuluContextEmbedder, type ExuluCredentialsToolContext, ExuluDatabase, ExuluDefaultTools, ExuluDocumentProcessor, ExuluEval, type Item as ExuluItem, ExuluJobs, ExuluModels, type ExuluOauthConfig, type ExuluOauthToolContext, ExuluOtel, ExuluPython, queues as ExuluQueues, ExuluReadApi, ExuluRecall, ExuluReranker, ExuluTool, type ExuluUserCredentialsConfig, ExuluVariables, PROJECTION_VERSION, type RoutineHandle, type RoutineRunPatch, type VectorSearchChunkResult, backfillCoordinates, checkMemoryBase, defaultChunker, enableLiteLLMClientMode, fitContextProjection, listFittableContexts, postgresClient, recallMemories };
package/dist/index.js CHANGED
@@ -193,7 +193,7 @@ import {
193
193
  verifyCredentialNonce,
194
194
  willEmbedOnQueue,
195
195
  workflowTemplatesSchema
196
- } from "./chunk-3AEINUGF.js";
196
+ } from "./chunk-U4UIVZST.js";
197
197
  import {
198
198
  LITELLM_UI_PATH,
199
199
  ResolveModelError,
@@ -1637,6 +1637,177 @@ var clearStreamActive = (sessionID) => {
1637
1637
  };
1638
1638
  var isStreamActive = (sessionID) => active.has(sessionID);
1639
1639
 
1640
+ // src/exulu/routines/work-status.ts
1641
+ var WORK_STATUS_KEY_PATTERN = /^[a-z][a-z0-9_]{1,39}$/;
1642
+ var EMPTY = { statuses: [], default: null };
1643
+ var toObject = (raw) => {
1644
+ let value = raw;
1645
+ if (typeof value === "string") {
1646
+ try {
1647
+ value = JSON.parse(value);
1648
+ } catch {
1649
+ return void 0;
1650
+ }
1651
+ }
1652
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1653
+ };
1654
+ function parseWorkStatusConfig(raw) {
1655
+ const obj = toObject(raw);
1656
+ if (!obj || !Array.isArray(obj.statuses)) return { ...EMPTY, statuses: [] };
1657
+ const seen = /* @__PURE__ */ new Set();
1658
+ const statuses = [];
1659
+ for (const entry of obj.statuses) {
1660
+ if (!entry || typeof entry !== "object") continue;
1661
+ const { key, label, color, done } = entry;
1662
+ if (typeof key !== "string" || !WORK_STATUS_KEY_PATTERN.test(key) || seen.has(key)) continue;
1663
+ seen.add(key);
1664
+ statuses.push({
1665
+ key,
1666
+ label: typeof label === "string" && label.trim() ? label : key,
1667
+ ...typeof color === "string" ? { color } : {},
1668
+ ...typeof done === "boolean" ? { done } : {}
1669
+ });
1670
+ }
1671
+ const def = typeof obj.default === "string" && seen.has(obj.default) ? obj.default : null;
1672
+ return { statuses, default: def };
1673
+ }
1674
+ function validateWorkStatusConfig(next, _previous) {
1675
+ if (next === null || next === void 0) return [];
1676
+ const obj = toObject(next);
1677
+ if (!obj) return ["work_statuses must be an object { statuses, default }"];
1678
+ if (!Array.isArray(obj.statuses)) return ["work_statuses.statuses must be a list"];
1679
+ const problems = [];
1680
+ const keys = /* @__PURE__ */ new Set();
1681
+ const doneKeys = /* @__PURE__ */ new Set();
1682
+ obj.statuses.forEach((entry, index) => {
1683
+ const { key, label, done } = entry ?? {};
1684
+ if (typeof key !== "string" || !WORK_STATUS_KEY_PATTERN.test(key)) {
1685
+ problems.push(`status ${index + 1}: key ${JSON.stringify(key)} must match ${WORK_STATUS_KEY_PATTERN}`);
1686
+ return;
1687
+ }
1688
+ if (keys.has(key)) problems.push(`duplicate status key "${key}"`);
1689
+ keys.add(key);
1690
+ if (typeof label !== "string" || !label.trim()) problems.push(`status "${key}": label must not be empty`);
1691
+ if (done === true) doneKeys.add(key);
1692
+ });
1693
+ if (obj.statuses.length === 0) return problems;
1694
+ if (typeof obj.default !== "string" || !keys.has(obj.default)) {
1695
+ problems.push(`default ${JSON.stringify(obj.default ?? null)} must be one of the status keys`);
1696
+ } else if (doneKeys.has(obj.default)) {
1697
+ problems.push(`default "${obj.default}" must not be a done status`);
1698
+ }
1699
+ return problems;
1700
+ }
1701
+ function decideWorkStatusWrite(input) {
1702
+ const { config, routineName, current, next, origin } = input;
1703
+ if (next === null) {
1704
+ if (origin !== "manual") {
1705
+ return { action: "reject", message: "A work status can only be cleared by a person in the runs list." };
1706
+ }
1707
+ return current.status === null ? { action: "skip", reason: "unchanged" } : { action: "write", status: null };
1708
+ }
1709
+ if (config.statuses.length === 0) {
1710
+ return { action: "reject", message: `Routine "${routineName}" has no work statuses configured.` };
1711
+ }
1712
+ if (!config.statuses.some((status) => status.key === next)) {
1713
+ return {
1714
+ action: "reject",
1715
+ message: `Unknown work status "${next}" for routine "${routineName}". Allowed: ${config.statuses.map((s) => s.key).join(", ")}`
1716
+ };
1717
+ }
1718
+ if (origin === "worker" && current.updatedBy?.kind === "user") {
1719
+ return { action: "skip", reason: "human_set" };
1720
+ }
1721
+ if (current.status === next) return { action: "skip", reason: "unchanged" };
1722
+ return { action: "write", status: next };
1723
+ }
1724
+
1725
+ // src/exulu/routines/work-status-store.ts
1726
+ var parseActor = (raw) => {
1727
+ let value = raw;
1728
+ if (typeof value === "string") {
1729
+ try {
1730
+ value = JSON.parse(value);
1731
+ } catch {
1732
+ return null;
1733
+ }
1734
+ }
1735
+ return value && typeof value === "object" && typeof value.kind === "string" ? value : null;
1736
+ };
1737
+ var mapRow = (row) => row ? {
1738
+ id: row.id,
1739
+ workflow: row.workflow,
1740
+ work_status: row.work_status ?? null,
1741
+ work_status_updated_at: row.work_status_updated_at ?? null,
1742
+ work_status_updated_by: parseActor(row.work_status_updated_by)
1743
+ } : void 0;
1744
+ async function loadRunWorkStatus(db, jobResultId) {
1745
+ return mapRow(await db("job_results").where({ id: jobResultId }).first());
1746
+ }
1747
+ async function loadRoutineWorkStatusConfig(db, workflowId) {
1748
+ const row = await db("workflow_templates").where({ id: workflowId }).select("id", "name", "work_statuses").first();
1749
+ if (!row) return void 0;
1750
+ return { id: row.id, name: row.name, config: parseWorkStatusConfig(row.work_statuses) };
1751
+ }
1752
+ async function setRunWorkStatus(db, args) {
1753
+ const run = await loadRunWorkStatus(db, args.jobResultId);
1754
+ if (!run) throw new Error(`Run ${args.jobResultId} not found`);
1755
+ const routine = await loadRoutineWorkStatusConfig(db, run.workflow);
1756
+ if (!routine) throw new Error(`The routine of run ${args.jobResultId} was not found`);
1757
+ const decision = decideWorkStatusWrite({
1758
+ config: routine.config,
1759
+ routineName: routine.name,
1760
+ current: { status: run.work_status, updatedBy: run.work_status_updated_by },
1761
+ next: args.status,
1762
+ origin: args.origin
1763
+ });
1764
+ if (decision.action === "reject") throw new Error(decision.message);
1765
+ if (decision.action === "write") {
1766
+ let query = db("job_results").where({ id: args.jobResultId });
1767
+ if (args.origin === "worker") {
1768
+ query = query.whereRaw("(work_status_updated_by::jsonb)->>'kind' IS DISTINCT FROM 'user'");
1769
+ }
1770
+ const written = await query.update({
1771
+ work_status: decision.status,
1772
+ work_status_updated_at: /* @__PURE__ */ new Date(),
1773
+ work_status_updated_by: JSON.stringify(args.actor)
1774
+ });
1775
+ if (args.origin === "worker" && written === 0) {
1776
+ console.log(`[EXULU] work status of run ${args.jobResultId} left unchanged: a person set it.`);
1777
+ return { action: "skip", reason: "human_set" };
1778
+ }
1779
+ } else if (decision.reason === "human_set") {
1780
+ console.log(`[EXULU] work status of run ${args.jobResultId} left unchanged: a person set it.`);
1781
+ }
1782
+ return decision;
1783
+ }
1784
+ async function defaultWorkStatusColumns(db, workflowId) {
1785
+ try {
1786
+ const routine = await loadRoutineWorkStatusConfig(db, workflowId);
1787
+ if (!routine?.config.default) return {};
1788
+ return {
1789
+ work_status: routine.config.default,
1790
+ work_status_updated_at: /* @__PURE__ */ new Date(),
1791
+ work_status_updated_by: JSON.stringify({ kind: "default" })
1792
+ };
1793
+ } catch (error) {
1794
+ console.warn(`[EXULU] could not resolve the default work status of routine ${workflowId}:`, error);
1795
+ return {};
1796
+ }
1797
+ }
1798
+ async function setRunWorkStatusManually(db, args) {
1799
+ const row = await db("job_results").where({ id: args.id }).first();
1800
+ if (!row || row.type !== "workflow" || !row.workflow || !args.readableRoutineIds.includes(row.workflow)) {
1801
+ throw new Error("Routine run not found.");
1802
+ }
1803
+ await setRunWorkStatus(db, {
1804
+ jobResultId: args.id,
1805
+ status: args.status,
1806
+ actor: { kind: "user", id: args.userId },
1807
+ origin: "manual"
1808
+ });
1809
+ }
1810
+
1640
1811
  // src/exulu/routines/run-state.ts
1641
1812
  var parseRunMetadata = (value) => {
1642
1813
  if (value == null) {
@@ -1659,6 +1830,10 @@ async function casJobResultState(db, jobResultId, from, to) {
1659
1830
  async function upsertWorkflowRunStart(db, opts) {
1660
1831
  const triggerMetadataJson = opts.triggerMetadata ? JSON.stringify(opts.triggerMetadata) : null;
1661
1832
  const metadataJson = (currentStepIndex) => JSON.stringify({ ...opts.bookkeeping, current_step_index: currentStepIndex });
1833
+ const defaultStatusFor = async (row) => {
1834
+ if (row && (row.work_status != null || row.work_status_updated_by != null)) return {};
1835
+ return defaultWorkStatusColumns(db, opts.workflow);
1836
+ };
1662
1837
  if (opts.jobResultId) {
1663
1838
  const currentRow = await db.from("job_results").where({ id: opts.jobResultId }).first();
1664
1839
  const priorMetadata = parseRunMetadata(currentRow?.metadata);
@@ -1669,6 +1844,7 @@ async function upsertWorkflowRunStart(db, opts) {
1669
1844
  trigger: opts.trigger,
1670
1845
  trigger_metadata: triggerMetadataJson,
1671
1846
  ...opts.session ? { session: opts.session } : {},
1847
+ ...await defaultStatusFor(currentRow),
1672
1848
  metadata: JSON.stringify({
1673
1849
  ...priorMetadata,
1674
1850
  ...opts.bookkeeping,
@@ -1691,7 +1867,8 @@ async function upsertWorkflowRunStart(db, opts) {
1691
1867
  trigger: opts.trigger,
1692
1868
  trigger_metadata: triggerMetadataJson,
1693
1869
  metadata: metadataJson(resumeFromIndex),
1694
- tries: (existing.tries ?? 0) + 1
1870
+ tries: (existing.tries ?? 0) + 1,
1871
+ ...await defaultStatusFor(existing)
1695
1872
  });
1696
1873
  return {
1697
1874
  jobResultId: existing.id,
@@ -1710,7 +1887,8 @@ async function upsertWorkflowRunStart(db, opts) {
1710
1887
  workflow: opts.workflow,
1711
1888
  session: opts.session,
1712
1889
  trigger: opts.trigger,
1713
- trigger_metadata: triggerMetadataJson
1890
+ trigger_metadata: triggerMetadataJson,
1891
+ ...await defaultStatusFor(void 0)
1714
1892
  }).returning("id");
1715
1893
  return {
1716
1894
  jobResultId: inserted[0].id,
@@ -2639,7 +2817,7 @@ function resolveSetting(stored, envValue, codeDefault) {
2639
2817
  // src/exulu/transcripts-settings.ts
2640
2818
  var TRANSCRIPTS_SETTINGS_KEY = "transcripts_settings";
2641
2819
  var DEFAULT_BOT_NAME = "IMP Notetaker";
2642
- var EMPTY = {
2820
+ var EMPTY2 = {
2643
2821
  botName: null,
2644
2822
  notifyChat: null,
2645
2823
  recordersMayOverrideBot: null,
@@ -2668,13 +2846,13 @@ var getTranscriptsSettings = async () => {
2668
2846
  try {
2669
2847
  const { db } = await postgresClient();
2670
2848
  const row = await db.from("platform_configurations").where({ config_key: TRANSCRIPTS_SETTINGS_KEY }).first();
2671
- return { ...EMPTY, ...parseStoredSettings(row) ?? {} };
2849
+ return { ...EMPTY2, ...parseStoredSettings(row) ?? {} };
2672
2850
  } catch (err2) {
2673
2851
  console.warn(
2674
2852
  "[EXULU] Could not read the Transcripts settings:",
2675
2853
  err2.message
2676
2854
  );
2677
- return { ...EMPTY };
2855
+ return { ...EMPTY2 };
2678
2856
  }
2679
2857
  };
2680
2858
  var saveTranscriptsSettings = async (patch) => {
@@ -4340,6 +4518,69 @@ var isRunSessionMetadata = (metadata) => {
4340
4518
  return typeof parsed === "object" && parsed !== null && !!parsed.job_result_id;
4341
4519
  };
4342
4520
 
4521
+ // src/exulu/routines/routine-handle.ts
4522
+ var runIdFromSessionMetadata = (metadata) => {
4523
+ try {
4524
+ const parsed = typeof metadata === "string" ? JSON.parse(metadata) : metadata;
4525
+ const id = parsed?.job_result_id;
4526
+ return typeof id === "string" && id ? id : void 0;
4527
+ } catch {
4528
+ return void 0;
4529
+ }
4530
+ };
4531
+ var PATCH_FIELDS = ["status"];
4532
+ async function resolveRoutineHandleFactory(db, args) {
4533
+ const origin = args.jobResultId ? "worker" : "chat";
4534
+ try {
4535
+ const jobResultId = args.jobResultId ?? (isRunSessionMetadata(args.sessionMetadata) ? runIdFromSessionMetadata(args.sessionMetadata) : void 0);
4536
+ if (!jobResultId) return void 0;
4537
+ const run = await loadRunWorkStatus(db, jobResultId);
4538
+ if (!run) return void 0;
4539
+ const routine = await loadRoutineWorkStatusConfig(db, run.workflow);
4540
+ if (!routine) return void 0;
4541
+ const runId = run.id;
4542
+ const statuses = routine.config.statuses.map(({ key, label, done }) => ({
4543
+ key,
4544
+ label,
4545
+ ...done !== void 0 ? { done } : {}
4546
+ }));
4547
+ const state = { status: run.work_status };
4548
+ return (actor) => {
4549
+ const fullActor = origin === "chat" && args.actingUser !== void 0 ? { ...actor, user: args.actingUser } : actor;
4550
+ const updateWithResult = async (patch) => {
4551
+ const unknown = Object.keys(patch ?? {}).filter((key) => !PATCH_FIELDS.includes(key));
4552
+ if (unknown.length > 0) {
4553
+ throw new Error(`Unknown routine run field(s): ${unknown.join(", ")}. Allowed: ${PATCH_FIELDS.join(", ")}`);
4554
+ }
4555
+ if (patch?.status === void 0) return void 0;
4556
+ const decision = await setRunWorkStatus(db, { jobResultId: runId, status: patch.status, actor: fullActor, origin });
4557
+ if (decision.action === "write") state.status = decision.status;
4558
+ return decision;
4559
+ };
4560
+ return {
4561
+ id: routine.id,
4562
+ name: routine.name,
4563
+ statuses,
4564
+ runs: {
4565
+ current: {
4566
+ id: runId,
4567
+ get status() {
4568
+ return state.status;
4569
+ },
4570
+ update: async (patch) => {
4571
+ await updateWithResult(patch);
4572
+ },
4573
+ updateWithResult
4574
+ }
4575
+ }
4576
+ };
4577
+ };
4578
+ } catch (error) {
4579
+ console.warn("[EXULU] could not resolve the routine handle for this turn:", error);
4580
+ return void 0;
4581
+ }
4582
+ }
4583
+
4343
4584
  // src/exulu/task-description.ts
4344
4585
  import { generateText } from "ai";
4345
4586
  var AGENT_VISUALIZATION_ENABLED = process.env.NEXT_PUBLIC_AGENT_VISUALIZATION === "true";
@@ -4522,13 +4763,13 @@ function previousUserTexts(messages) {
4522
4763
  }
4523
4764
 
4524
4765
  // src/exulu/memory/recall.ts
4525
- var EMPTY2 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
4766
+ var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
4526
4767
  async function recallMemories({ agent, contexts, query, user, db, previousUserTurns }) {
4527
- if (!agent?.memory || !query) return { ...EMPTY2 };
4768
+ if (!agent?.memory || !query) return { ...EMPTY3 };
4528
4769
  const context = contexts?.find((c) => c.id === agent.memory);
4529
4770
  if (!context) {
4530
4771
  console.warn(`[EXULU] memory: context "${agent.memory}" configured on agent "${agent.id}" was not found; memory off for this turn.`);
4531
- return { ...EMPTY2 };
4772
+ return { ...EMPTY3 };
4532
4773
  }
4533
4774
  const config = resolveMemoryConfig(agent.memory_config);
4534
4775
  const collector = createRecallCollector(context, user, db);
@@ -5155,7 +5396,8 @@ var generateStream = async ({
5155
5396
  req,
5156
5397
  maxStepCount,
5157
5398
  contextWindow,
5158
- disabledTools
5399
+ disabledTools,
5400
+ routineRun
5159
5401
  }) => {
5160
5402
  if (!message) {
5161
5403
  console.error("[EXULU] Message is required for streaming.");
@@ -5166,12 +5408,14 @@ var generateStream = async ({
5166
5408
  let project;
5167
5409
  let sessionItems;
5168
5410
  let sessionOwnerId;
5411
+ let sessionMetadata;
5169
5412
  let lastTurnAt;
5170
5413
  if (session) {
5171
5414
  const sessionData = await getSession({ sessionID: session });
5172
5415
  project = sessionData.project;
5173
5416
  sessionItems = sessionData.session_items;
5174
5417
  sessionOwnerId = sessionData.user ?? void 0;
5418
+ sessionMetadata = sessionData.metadata;
5175
5419
  console.log("[EXULU] loading previous messages from session: " + session);
5176
5420
  const previousMessages2 = await getAgentMessages({
5177
5421
  session,
@@ -5317,6 +5561,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
5317
5561
  console.log("[EXULU] Skills", currentSkills?.map((x) => x.name));
5318
5562
  const memoryDecisions = collectMemoryDecisions(messages);
5319
5563
  const skillDecisions = collectSkillDecisions(messages);
5564
+ const routineHandleFactory = routineRun || session ? await resolveRoutineHandleFactory((await postgresClient()).db, {
5565
+ sessionId: session,
5566
+ sessionMetadata,
5567
+ jobResultId: routineRun?.jobResultId,
5568
+ actingUser: user?.id
5569
+ }) : void 0;
5320
5570
  const tools = await convertExuluToolsToAiSdkTools(
5321
5571
  currentTools,
5322
5572
  currentSkills,
@@ -5337,7 +5587,8 @@ When a tool execution is not approved by the user, do not retry it unless explic
5337
5587
  disabledTools,
5338
5588
  sessionOwnerId,
5339
5589
  memoryDecisions,
5340
- skillDecisions
5590
+ skillDecisions,
5591
+ routineHandleFactory
5341
5592
  );
5342
5593
  console.log("[EXULU] Converted tools", Object.keys(tools));
5343
5594
  const includesContextSearchTool = currentTools?.some(
@@ -7008,6 +7259,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
7008
7259
  variables: data.inputs,
7009
7260
  // Tag LLM spend to this routine (cron + ad-hoc share this path).
7010
7261
  routine: { id: workflow.id, name: workflow.name },
7262
+ jobResultId,
7011
7263
  sessionId,
7012
7264
  resumeFromIndex,
7013
7265
  // Approval-gated tools pause unless the routine opted
@@ -7780,6 +8032,7 @@ var processUiMessagesFlow = async ({
7780
8032
  config,
7781
8033
  variables,
7782
8034
  routine,
8035
+ jobResultId,
7783
8036
  sessionId,
7784
8037
  resumeFromIndex,
7785
8038
  respectToolApprovals
@@ -7887,6 +8140,7 @@ var processUiMessagesFlow = async ({
7887
8140
  currentTools: enabledTools,
7888
8141
  currentSkills: enabledSkills,
7889
8142
  allExuluTools: tools,
8143
+ routineRun: jobResultId ? { jobResultId } : void 0,
7890
8144
  languageModel: resolvedLanguageModel,
7891
8145
  toolConfigs: agent.tools,
7892
8146
  exuluConfig: config,
@@ -8046,8 +8300,28 @@ async function upsertJobStart(db, bullmqJob, label, fallbackType) {
8046
8300
  }
8047
8301
  }
8048
8302
 
8303
+ // src/exulu/routines/work-status-save.ts
8304
+ function assertWorkStatusConfigSavable(next, previous) {
8305
+ if (next === void 0) return;
8306
+ const problems = validateWorkStatusConfig(next, previous);
8307
+ if (problems.length > 0) {
8308
+ throw new Error(`Invalid work statuses: ${problems.join("; ")}`);
8309
+ }
8310
+ }
8311
+ var GUARDED = ["workflow_templatesCreateOne", "workflow_templatesUpdateOne", "workflow_templatesUpdateOneById"];
8312
+ function guardRoutineWorkStatusWrites(mutations) {
8313
+ for (const name of GUARDED) {
8314
+ const original = mutations[name];
8315
+ if (typeof original !== "function") continue;
8316
+ mutations[name] = async (parent, args, context, info) => {
8317
+ assertWorkStatusConfigSavable(args?.input?.work_statuses);
8318
+ return original(parent, args, context, info);
8319
+ };
8320
+ }
8321
+ }
8322
+
8049
8323
  // src/exulu/routines/runs-query.ts
8050
- var applyRoutineRunFilters = (query, args, allowedWorkflowIds) => {
8324
+ var applyRoutineRunFilters = (query, args, allowedWorkflowIds, doneKeys) => {
8051
8325
  let q = query.where("job_results.type", "workflow").whereIn("job_results.workflow", allowedWorkflowIds);
8052
8326
  if (args.states?.length) {
8053
8327
  q = q.whereIn("job_results.state", args.states);
@@ -8064,6 +8338,22 @@ var applyRoutineRunFilters = (query, args, allowedWorkflowIds) => {
8064
8338
  if (args.to) {
8065
8339
  q = q.where("job_results.createdAt", "<=", args.to);
8066
8340
  }
8341
+ if (args.workStatuses?.length) {
8342
+ q = q.whereIn("job_results.work_status", args.workStatuses);
8343
+ }
8344
+ if (typeof args.workStatusOpen === "boolean" && doneKeys) {
8345
+ if (args.workStatusOpen) {
8346
+ if (doneKeys.length > 0) {
8347
+ q = q.where((group) => {
8348
+ group.whereNull("job_results.work_status").orWhereNotIn("job_results.work_status", doneKeys);
8349
+ });
8350
+ }
8351
+ } else if (doneKeys.length > 0) {
8352
+ q = q.whereIn("job_results.work_status", doneKeys);
8353
+ } else {
8354
+ q = q.whereRaw("1 = 0");
8355
+ }
8356
+ }
8067
8357
  if (args.search) {
8068
8358
  q = q.leftJoin("agent_sessions", "job_results.session", "agent_sessions.id").where("agent_sessions.title", "ilike", `%${args.search}%`);
8069
8359
  }
@@ -8101,7 +8391,10 @@ var mapRoutineRunRow = (row, routineById) => {
8101
8391
  updatedAt: row.updatedAt,
8102
8392
  inputTokens: tokens?.inputTokens ?? null,
8103
8393
  outputTokens: tokens?.outputTokens ?? null,
8104
- costUsd: tokens?.costUsd ?? null
8394
+ costUsd: tokens?.costUsd ?? null,
8395
+ work_status: row.work_status ?? null,
8396
+ work_status_updated_at: row.work_status_updated_at ?? null,
8397
+ work_status_updated_by: parseMaybeJson(row.work_status_updated_by)
8105
8398
  };
8106
8399
  };
8107
8400
 
@@ -9922,10 +10215,10 @@ import { randomUUID as randomUUID6 } from "crypto";
9922
10215
 
9923
10216
  // src/graphql/resolvers/memory-base-stats.ts
9924
10217
  var num = (v) => typeof v === "number" ? v : Number(v) || 0;
9925
- var EMPTY3 = { total: 0, public: 0, private: 0, contributors: 0, visible: 0, lastSavedAt: null, lastSavedBy: null };
10218
+ var EMPTY4 = { total: 0, public: 0, private: 0, contributors: 0, visible: 0, lastSavedAt: null, lastSavedBy: null };
9926
10219
  async function memoryBaseStats({ context, user, db }) {
9927
10220
  const tableName = getTableName(context.id);
9928
- if (!await db.schema.hasTable(tableName)) return { ...EMPTY3 };
10221
+ if (!await db.schema.hasTable(tableName)) return { ...EMPTY4 };
9929
10222
  try {
9930
10223
  const table = convertContextToTableDefinition(context);
9931
10224
  const all = () => db(tableName).whereNot("archived", true);
@@ -9954,7 +10247,7 @@ async function memoryBaseStats({ context, user, db }) {
9954
10247
  };
9955
10248
  } catch (error) {
9956
10249
  console.error(`[EXULU] memoryBaseStats failed for context "${context.id}":`, error instanceof Error ? error.message : error);
9957
- return { ...EMPTY3 };
10250
+ return { ...EMPTY4 };
9958
10251
  }
9959
10252
  }
9960
10253
 
@@ -11721,7 +12014,7 @@ type PageInfo {
11721
12014
  workflowSchedule(workflow: ID!): WorkflowScheduleResult
11722
12015
  `;
11723
12016
  typeDefs += `
11724
- routineRuns(page: Int, limit: Int, workflow: ID, states: [String!], triggers: [String!], from: Date, to: Date, search: String, needsAttention: Boolean): RoutineRunPage
12017
+ routineRuns(page: Int, limit: Int, workflow: ID, states: [String!], triggers: [String!], from: Date, to: Date, search: String, needsAttention: Boolean, workStatuses: [String!], workStatusOpen: Boolean): RoutineRunPage
11725
12018
  routineRunsNeedingAttentionCount: Float!
11726
12019
  `;
11727
12020
  typeDefs += `
@@ -11838,6 +12131,7 @@ type PageInfo {
11838
12131
  `;
11839
12132
  mutationDefs += `
11840
12133
  cancelRoutineRun(id: ID!): RoutineRun
12134
+ setRoutineRunWorkStatus(id: ID!, status: String): RoutineRun
11841
12135
  retryRoutineRun(id: ID!): RoutineRun
11842
12136
  deleteRoutineRun(id: ID!): ID
11843
12137
  `;
@@ -12002,6 +12296,9 @@ type RoutineRun {
12002
12296
  inputTokens: Float
12003
12297
  outputTokens: Float
12004
12298
  costUsd: Float
12299
+ work_status: String
12300
+ work_status_updated_at: Date
12301
+ work_status_updated_by: JSON
12005
12302
  }
12006
12303
 
12007
12304
  type RoutineRunPage {
@@ -12469,7 +12766,10 @@ type EmbeddingModelOption {
12469
12766
  tries: 1,
12470
12767
  type: "workflow",
12471
12768
  workflow: workflow_template_id,
12472
- trigger: jobData.triggerSource ?? null
12769
+ trigger: jobData.triggerSource ?? null,
12770
+ // This path never passes upsertWorkflowRunStart, which gives
12771
+ // queued runs the routine's default work status.
12772
+ ...await defaultWorkStatusColumns(db, workflow_template_id)
12473
12773
  }).returning("id");
12474
12774
  const jobResultId = jobResult[0].id;
12475
12775
  try {
@@ -12508,7 +12808,10 @@ type EmbeddingModelOption {
12508
12808
  variables: args.variables,
12509
12809
  // Tag LLM spend to this routine (direct one-shot path mirrors the queued path).
12510
12810
  routine: { id: workflow.id, name: workflow.name },
12511
- sessionId
12811
+ sessionId,
12812
+ // Marks tool writes of the work status as the run's own
12813
+ // (never overriding a person), not as a chat continuation.
12814
+ jobResultId
12512
12815
  });
12513
12816
  resolve3(messages2);
12514
12817
  break;
@@ -12600,11 +12903,12 @@ type EmbeddingModelOption {
12600
12903
  }
12601
12904
  const page = Math.max(1, args.page ?? 1);
12602
12905
  const limit = Math.min(100, Math.max(1, args.limit ?? 20));
12603
- const countRows = await applyRoutineRunFilters(db("job_results"), args, allowedIds).count(
12906
+ const doneKeys = args.workflow && typeof args.workStatusOpen === "boolean" ? ((await loadRoutineWorkStatusConfig(db, args.workflow))?.config.statuses ?? []).filter((status) => status.done === true).map((status) => status.key) : void 0;
12907
+ const countRows = await applyRoutineRunFilters(db("job_results"), args, allowedIds, doneKeys).count(
12604
12908
  "* as count"
12605
12909
  );
12606
12910
  const total = Number(countRows[0]?.count ?? 0);
12607
- const rows = await applyRoutineRunFilters(db("job_results"), args, allowedIds).select("job_results.*").orderBy("job_results.createdAt", "desc").offset((page - 1) * limit).limit(limit);
12911
+ const rows = await applyRoutineRunFilters(db("job_results"), args, allowedIds, doneKeys).select("job_results.*").orderBy("job_results.createdAt", "desc").offset((page - 1) * limit).limit(limit);
12608
12912
  return {
12609
12913
  items: rows.map((row) => mapRoutineRunRow(row, routineById)),
12610
12914
  total
@@ -12620,6 +12924,20 @@ type EmbeddingModelOption {
12620
12924
  const rows = await db("job_results").where({ type: "workflow", state: JOB_STATUS_ENUM.waiting_approval }).whereIn("workflow", [...routineById.keys()]).count("* as count");
12621
12925
  return Number(rows[0]?.count ?? 0);
12622
12926
  };
12927
+ resolvers.Mutation["setRoutineRunWorkStatus"] = async (_, args, context) => {
12928
+ const user = context.user;
12929
+ const { db } = await postgresClient();
12930
+ const routineById = await readableRoutines(db, user);
12931
+ await setRunWorkStatusManually(db, {
12932
+ id: args.id,
12933
+ status: args.status ?? null,
12934
+ userId: user.id,
12935
+ readableRoutineIds: [...routineById.keys()]
12936
+ });
12937
+ const updated = await db.from("job_results").where({ id: args.id }).first();
12938
+ return mapRoutineRunRow(updated, routineById);
12939
+ };
12940
+ guardRoutineWorkStatusWrites(resolvers.Mutation);
12623
12941
  resolvers.Mutation["cancelRoutineRun"] = async (_, args, context) => {
12624
12942
  const user = context.user;
12625
12943
  const { db } = await postgresClient();
@@ -24822,6 +25140,10 @@ var up = async function(knex) {
24822
25140
  `CREATE INDEX IF NOT EXISTS job_results_workflow_state_trigger_created_idx
24823
25141
  ON job_results (workflow, state, trigger, "createdAt")`
24824
25142
  );
25143
+ await knex.raw(
25144
+ `CREATE INDEX IF NOT EXISTS job_results_workflow_work_status_created_idx
25145
+ ON job_results (workflow, work_status, "createdAt")`
25146
+ );
24825
25147
  await knex.raw(
24826
25148
  `CREATE INDEX IF NOT EXISTS job_results_session_waiting_idx
24827
25149
  ON job_results (session) WHERE state = 'waiting_approval'`