@mastra/lance 1.0.4 → 1.0.5

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.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { connect, Index } from '@lancedb/lancedb';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
- import { MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, createStorageErrorId, normalizePerPage, calculatePagination, ScoresStorage, SCORERS_SCHEMA, TABLE_SCORERS, WorkflowsStorage, ensureDate, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, createVectorErrorId, getDefaultValue } from '@mastra/core/storage';
4
- import { MessageList } from '@mastra/core/agent';
3
+ import { BackgroundTasksStorage, TABLE_SCHEMAS, TABLE_BACKGROUND_TASKS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, createStorageErrorId, normalizePerPage, calculatePagination, ScoresStorage, SCORERS_SCHEMA, TABLE_SCORERS, WorkflowsStorage, ensureDate, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, createVectorErrorId, getDefaultValue } from '@mastra/core/storage';
5
4
  import { MastraBase } from '@mastra/core/base';
6
5
  import { Utf8, Float64, Binary, Float32, Int32, Field, Schema } from 'apache-arrow';
6
+ import { MessageList } from '@mastra/core/agent';
7
7
  import { saveScorePayloadSchema } from '@mastra/core/evals';
8
8
  import { MastraVector } from '@mastra/core/vector';
9
9
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
@@ -587,7 +587,188 @@ var LanceDB = class extends MastraBase {
587
587
  }
588
588
  };
589
589
 
590
- // src/storage/domains/memory/index.ts
590
+ // src/storage/domains/background-tasks/index.ts
591
+ function serializeJson(v) {
592
+ if (typeof v === "object" && v != null) return JSON.stringify(v);
593
+ return v ?? void 0;
594
+ }
595
+ function toRecord(task) {
596
+ return {
597
+ id: task.id,
598
+ tool_call_id: task.toolCallId,
599
+ tool_name: task.toolName,
600
+ agent_id: task.agentId,
601
+ thread_id: task.threadId ?? "",
602
+ resource_id: task.resourceId ?? "",
603
+ run_id: task.runId,
604
+ status: task.status,
605
+ args: serializeJson(task.args),
606
+ result: serializeJson(task.result),
607
+ error: serializeJson(task.error),
608
+ retry_count: task.retryCount,
609
+ max_retries: task.maxRetries,
610
+ timeout_ms: task.timeoutMs,
611
+ createdAt: task.createdAt,
612
+ startedAt: task.startedAt ?? /* @__PURE__ */ new Date(0),
613
+ completedAt: task.completedAt ?? /* @__PURE__ */ new Date(0)
614
+ };
615
+ }
616
+ function fromRecord(row) {
617
+ const parseJson = (val) => {
618
+ if (val == null || val === "") return void 0;
619
+ if (typeof val === "string") {
620
+ try {
621
+ return JSON.parse(val);
622
+ } catch {
623
+ return val;
624
+ }
625
+ }
626
+ return val;
627
+ };
628
+ const startedAt = row.startedAt instanceof Date ? row.startedAt : row.startedAt ? new Date(row.startedAt) : void 0;
629
+ const completedAt = row.completedAt instanceof Date ? row.completedAt : row.completedAt ? new Date(row.completedAt) : void 0;
630
+ return {
631
+ id: String(row.id),
632
+ status: String(row.status),
633
+ toolName: String(row.tool_name),
634
+ toolCallId: String(row.tool_call_id),
635
+ args: parseJson(row.args) ?? {},
636
+ agentId: String(row.agent_id),
637
+ threadId: row.thread_id && row.thread_id !== "" ? String(row.thread_id) : void 0,
638
+ resourceId: row.resource_id && row.resource_id !== "" ? String(row.resource_id) : void 0,
639
+ runId: row.run_id ?? "",
640
+ result: parseJson(row.result),
641
+ error: parseJson(row.error),
642
+ retryCount: Number(row.retry_count ?? 0),
643
+ maxRetries: Number(row.max_retries ?? 0),
644
+ timeoutMs: Number(row.timeout_ms ?? 3e5),
645
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt),
646
+ startedAt: startedAt && startedAt.getTime() > 0 ? startedAt : void 0,
647
+ completedAt: completedAt && completedAt.getTime() > 0 ? completedAt : void 0
648
+ };
649
+ }
650
+ function escapeStr(val) {
651
+ return val.replace(/'/g, "''");
652
+ }
653
+ var StoreBackgroundTasksLance = class extends BackgroundTasksStorage {
654
+ client;
655
+ #db;
656
+ constructor(config) {
657
+ super();
658
+ const client = resolveLanceConfig(config);
659
+ this.client = client;
660
+ this.#db = new LanceDB({ client });
661
+ }
662
+ async init() {
663
+ await this.#db.createTable({
664
+ tableName: TABLE_BACKGROUND_TASKS,
665
+ schema: TABLE_SCHEMAS[TABLE_BACKGROUND_TASKS]
666
+ });
667
+ }
668
+ async dangerouslyClearAll() {
669
+ await this.#db.clearTable({ tableName: TABLE_BACKGROUND_TASKS });
670
+ }
671
+ async createTask(task) {
672
+ const table = await this.client.openTable(TABLE_BACKGROUND_TASKS);
673
+ await table.add([toRecord(task)], { mode: "append" });
674
+ }
675
+ async updateTask(taskId, update) {
676
+ const existing = await this.getTask(taskId);
677
+ if (!existing) return;
678
+ const merged = { ...existing };
679
+ if ("status" in update) merged.status = update.status;
680
+ if ("result" in update) merged.result = update.result;
681
+ if ("error" in update) merged.error = update.error;
682
+ if ("retryCount" in update) merged.retryCount = update.retryCount;
683
+ if ("startedAt" in update) merged.startedAt = update.startedAt;
684
+ if ("completedAt" in update) merged.completedAt = update.completedAt;
685
+ const table = await this.client.openTable(TABLE_BACKGROUND_TASKS);
686
+ await table.delete(`id = '${escapeStr(taskId)}'`);
687
+ await table.add([toRecord(merged)], { mode: "append" });
688
+ }
689
+ async getTask(taskId) {
690
+ try {
691
+ const table = await this.client.openTable(TABLE_BACKGROUND_TASKS);
692
+ const records = await table.query().where(`id = '${escapeStr(taskId)}'`).limit(1).toArray();
693
+ if (records.length === 0) return null;
694
+ return fromRecord(records[0]);
695
+ } catch {
696
+ return null;
697
+ }
698
+ }
699
+ async listTasks(filter) {
700
+ try {
701
+ const table = await this.client.openTable(TABLE_BACKGROUND_TASKS);
702
+ const conditions = [];
703
+ if (filter.status) {
704
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
705
+ const inList = statuses.map((s) => `'${escapeStr(s)}'`).join(", ");
706
+ conditions.push(`status IN (${inList})`);
707
+ }
708
+ if (filter.agentId) conditions.push(`agent_id = '${escapeStr(filter.agentId)}'`);
709
+ if (filter.threadId) conditions.push(`thread_id = '${escapeStr(filter.threadId)}'`);
710
+ if (filter.resourceId) conditions.push(`resource_id = '${escapeStr(filter.resourceId)}'`);
711
+ if (filter.runId) conditions.push(`run_id = '${escapeStr(filter.runId)}'`);
712
+ if (filter.toolName) conditions.push(`tool_name = '${escapeStr(filter.toolName)}'`);
713
+ let query = table.query();
714
+ if (conditions.length > 0) {
715
+ query = query.where(conditions.join(" AND "));
716
+ }
717
+ const records = await query.toArray();
718
+ let tasks = records.map(fromRecord);
719
+ const dateCol = filter.dateFilterBy ?? "createdAt";
720
+ if (filter.fromDate) {
721
+ tasks = tasks.filter((t) => {
722
+ const val = t[dateCol];
723
+ return val != null && val >= filter.fromDate;
724
+ });
725
+ }
726
+ if (filter.toDate) {
727
+ tasks = tasks.filter((t) => {
728
+ const val = t[dateCol];
729
+ return val != null && val < filter.toDate;
730
+ });
731
+ }
732
+ const orderBy = filter.orderBy ?? "createdAt";
733
+ const direction = filter.orderDirection ?? "asc";
734
+ tasks.sort((a, b) => {
735
+ const aVal = a[orderBy]?.getTime() ?? 0;
736
+ const bVal = b[orderBy]?.getTime() ?? 0;
737
+ return direction === "asc" ? aVal - bVal : bVal - aVal;
738
+ });
739
+ const total = tasks.length;
740
+ if (filter.page != null && filter.perPage != null) {
741
+ const start = filter.page * filter.perPage;
742
+ tasks = tasks.slice(start, start + filter.perPage);
743
+ } else if (filter.perPage != null) {
744
+ tasks = tasks.slice(0, filter.perPage);
745
+ }
746
+ return { tasks, total };
747
+ } catch {
748
+ return { tasks: [], total: 0 };
749
+ }
750
+ }
751
+ async deleteTask(taskId) {
752
+ const table = await this.client.openTable(TABLE_BACKGROUND_TASKS);
753
+ await table.delete(`id = '${escapeStr(taskId)}'`);
754
+ }
755
+ async deleteTasks(filter) {
756
+ const { tasks } = await this.listTasks(filter);
757
+ if (tasks.length === 0) return;
758
+ const table = await this.client.openTable(TABLE_BACKGROUND_TASKS);
759
+ for (const task of tasks) {
760
+ await table.delete(`id = '${escapeStr(task.id)}'`);
761
+ }
762
+ }
763
+ async getRunningCount() {
764
+ const { total } = await this.listTasks({ status: "running" });
765
+ return total;
766
+ }
767
+ async getRunningCountByAgent(agentId) {
768
+ const { total } = await this.listTasks({ status: "running", agentId });
769
+ return total;
770
+ }
771
+ };
591
772
  var StoreMemoryLance = class extends MemoryStorage {
592
773
  client;
593
774
  #db;
@@ -2008,7 +2189,8 @@ var LanceStorage = class _LanceStorage extends MastraCompositeStore {
2008
2189
  instance.stores = {
2009
2190
  workflows: new StoreWorkflowsLance({ client: instance.lanceClient }),
2010
2191
  scores: new StoreScoresLance({ client: instance.lanceClient }),
2011
- memory: new StoreMemoryLance({ client: instance.lanceClient })
2192
+ memory: new StoreMemoryLance({ client: instance.lanceClient }),
2193
+ backgroundTasks: new StoreBackgroundTasksLance({ client: instance.lanceClient })
2012
2194
  };
2013
2195
  return instance;
2014
2196
  } catch (e) {
@@ -2050,7 +2232,8 @@ var LanceStorage = class _LanceStorage extends MastraCompositeStore {
2050
2232
  instance.stores = {
2051
2233
  workflows: new StoreWorkflowsLance({ client }),
2052
2234
  scores: new StoreScoresLance({ client }),
2053
- memory: new StoreMemoryLance({ client })
2235
+ memory: new StoreMemoryLance({ client }),
2236
+ backgroundTasks: new StoreBackgroundTasksLance({ client })
2054
2237
  };
2055
2238
  return instance;
2056
2239
  }
@@ -3395,6 +3578,6 @@ var LanceVectorStore = class _LanceVectorStore extends MastraVector {
3395
3578
  }
3396
3579
  };
3397
3580
 
3398
- export { LanceStorage, LanceVectorStore, StoreMemoryLance, StoreScoresLance, StoreWorkflowsLance };
3581
+ export { LanceStorage, LanceVectorStore, StoreBackgroundTasksLance, StoreMemoryLance, StoreScoresLance, StoreWorkflowsLance };
3399
3582
  //# sourceMappingURL=index.js.map
3400
3583
  //# sourceMappingURL=index.js.map