@axiom-lattice/core 2.1.41 → 2.1.43

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
@@ -6654,36 +6654,35 @@ var InMemoryThreadMessageQueueStore = class {
6654
6654
  }
6655
6655
  async addMessageAtHead(threadId, content, type = "system") {
6656
6656
  const threadMessages = this.getMessagesForThread(threadId);
6657
- threadMessages.forEach((msg) => {
6658
- msg.sequence += 1;
6659
- });
6660
6657
  let tenantId = "default";
6661
6658
  let assistantId = "";
6662
6659
  if (threadMessages.length > 0) {
6663
6660
  tenantId = threadMessages[0].tenantId || "default";
6664
6661
  assistantId = threadMessages[0].assistantId || "";
6665
6662
  }
6663
+ const nextSequence = threadMessages.length;
6666
6664
  const message = {
6667
6665
  id: this.generateId(),
6668
6666
  content,
6669
6667
  type,
6670
- sequence: 0,
6668
+ sequence: nextSequence,
6671
6669
  createdAt: /* @__PURE__ */ new Date(),
6672
6670
  status: "pending",
6673
6671
  tenantId,
6674
6672
  assistantId,
6675
- priority: 0
6673
+ priority: 100
6674
+ // High priority for head messages (STEER/Command)
6676
6675
  };
6677
- threadMessages.unshift(message);
6676
+ threadMessages.push(message);
6678
6677
  return message;
6679
6678
  }
6680
6679
  async getPendingMessages(threadId) {
6681
6680
  const threadMessages = this.getMessagesForThread(threadId);
6682
- return threadMessages.filter((msg) => msg.status === "pending" || !msg.status).sort((a, b) => a.sequence - b.sequence).map(({ status, tenantId, assistantId, ...message }) => message);
6681
+ return threadMessages.filter((msg) => msg.status === "pending" || !msg.status).sort((a, b) => (b.priority || 0) - (a.priority || 0) || a.sequence - b.sequence).map(({ status, tenantId, assistantId, ...message }) => message);
6683
6682
  }
6684
6683
  async getProcessingMessages(threadId) {
6685
6684
  const threadMessages = this.getMessagesForThread(threadId);
6686
- return threadMessages.filter((msg) => msg.status === "processing").sort((a, b) => a.sequence - b.sequence).map(({ status, tenantId, assistantId, ...message }) => message);
6685
+ return threadMessages.filter((msg) => msg.status === "processing").sort((a, b) => (b.priority || 0) - (a.priority || 0) || a.sequence - b.sequence).map(({ status, tenantId, assistantId, ...message }) => message);
6687
6686
  }
6688
6687
  async getQueueSize(threadId) {
6689
6688
  const pending = await this.getPendingMessages(threadId);
@@ -6692,11 +6691,11 @@ var InMemoryThreadMessageQueueStore = class {
6692
6691
  async getThreadsWithPendingMessages() {
6693
6692
  const result = [];
6694
6693
  for (const [threadId, messages] of this.messages.entries()) {
6695
- const pendingMessages = messages.filter(
6696
- (msg) => msg.status === "pending" || !msg.status
6694
+ const pendingOrProcessingMessages = messages.filter(
6695
+ (msg) => msg.status === "pending" || msg.status === "processing" || !msg.status
6697
6696
  );
6698
- if (pendingMessages.length > 0) {
6699
- const firstMessage = pendingMessages[0];
6697
+ if (pendingOrProcessingMessages.length > 0) {
6698
+ const firstMessage = pendingOrProcessingMessages[0];
6700
6699
  result.push({
6701
6700
  tenantId: firstMessage.tenantId || "default",
6702
6701
  assistantId: firstMessage.assistantId || "",
@@ -6746,6 +6745,20 @@ var InMemoryThreadMessageQueueStore = class {
6746
6745
  this.messages.set(threadId, filtered);
6747
6746
  }
6748
6747
  }
6748
+ async resetProcessingToPending(threadId) {
6749
+ const messages = this.messages.get(threadId);
6750
+ if (!messages) {
6751
+ return 0;
6752
+ }
6753
+ let count = 0;
6754
+ for (const msg of messages) {
6755
+ if (msg.status === "processing") {
6756
+ msg.status = "pending";
6757
+ count++;
6758
+ }
6759
+ }
6760
+ return count;
6761
+ }
6749
6762
  };
6750
6763
 
6751
6764
  // src/store_lattice/StoreLatticeManager.ts
@@ -10760,6 +10773,9 @@ function createTaskTool(options) {
10760
10773
  }
10761
10774
  return returnCommandWithStateUpdate(result, config.toolCall.id);
10762
10775
  } catch (error) {
10776
+ if (error instanceof import_langgraph7.GraphInterrupt) {
10777
+ throw error;
10778
+ }
10763
10779
  return new import_langgraph7.Command({
10764
10780
  update: {
10765
10781
  messages: [
@@ -10949,13 +10965,13 @@ var StoreBackend = class {
10949
10965
  * @returns List of all items matching the search criteria
10950
10966
  */
10951
10967
  async searchStorePaginated(store, namespace, options = {}) {
10952
- const { query, filter, pageSize = 100 } = options;
10968
+ const { query, filter: filter2, pageSize = 100 } = options;
10953
10969
  const allItems = [];
10954
10970
  let offset = 0;
10955
10971
  while (true) {
10956
10972
  const pageItems = await store.search(namespace, {
10957
10973
  query,
10958
- filter,
10974
+ filter: filter2,
10959
10975
  limit: pageSize,
10960
10976
  offset
10961
10977
  });
@@ -14105,7 +14121,7 @@ var AgentParamsBuilder = class {
14105
14121
  * @param options build options
14106
14122
  * @returns Agent build parameters
14107
14123
  */
14108
- buildParams(agentLattice, options) {
14124
+ async buildParams(agentLattice, options) {
14109
14125
  const skills = (0, import_protocols4.isDeepAgentConfig)(agentLattice.config) ? agentLattice.config.skillCategories : void 0;
14110
14126
  const toolKeys = options?.overrideTools || (0, import_protocols4.getToolsFromConfig)(agentLattice.config);
14111
14127
  const tools = toolKeys.map((toolKey) => {
@@ -14125,8 +14141,8 @@ var AgentParamsBuilder = class {
14125
14141
  throw new Error(`Model "${modelKey}" does not exist`);
14126
14142
  }
14127
14143
  const subAgentKeys = (0, import_protocols4.getSubAgentsFromConfig)(agentLattice.config);
14128
- const subAgents = subAgentKeys.map((agentKey) => {
14129
- const subAgentLattice = this.getAgentLatticeFunc(agentKey);
14144
+ const subAgents = await Promise.all(subAgentKeys.map(async (agentKey) => {
14145
+ const subAgentLattice = await this.getAgentLatticeFunc(agentKey);
14130
14146
  if (!subAgentLattice) {
14131
14147
  throw new Error(`SubAgent "${agentKey}" does not exist`);
14132
14148
  }
@@ -14135,7 +14151,7 @@ var AgentParamsBuilder = class {
14135
14151
  config: subAgentLattice.config,
14136
14152
  client: subAgentLattice.client
14137
14153
  };
14138
- });
14154
+ }));
14139
14155
  let internalSubAgents = [];
14140
14156
  if ((0, import_protocols4.isDeepAgentConfig)(agentLattice.config)) {
14141
14157
  internalSubAgents = agentLattice.config.internalSubAgents?.map((i) => ({
@@ -14213,7 +14229,7 @@ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager
14213
14229
  }
14214
14230
  const config = assistantToConfig(assistant);
14215
14231
  const agentLattice = {
14216
- config,
14232
+ config: { ...config, tenantId },
14217
14233
  client: void 0
14218
14234
  };
14219
14235
  return agentLattice;
@@ -14520,13 +14536,13 @@ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager
14520
14536
  * @param options 构建选项
14521
14537
  * @returns 返回Agent构建参数
14522
14538
  */
14523
- buildAgentParams(agentLattice, options) {
14539
+ async buildAgentParams(agentLattice, options) {
14524
14540
  const tenantId = agentLattice.config.tenantId || "default";
14525
- const paramsBuilder = new AgentParamsBuilder((key) => {
14526
- this.initializeClient(tenantId, key);
14541
+ const paramsBuilder = new AgentParamsBuilder(async (key) => {
14542
+ await this.initializeClientAsync(tenantId, key);
14527
14543
  return this.getAgentLatticeWithTenant(tenantId, key);
14528
14544
  });
14529
- const params = paramsBuilder.buildParams(agentLattice, options);
14545
+ const params = await paramsBuilder.buildParams(agentLattice, options);
14530
14546
  return {
14531
14547
  ...params,
14532
14548
  tenantId
@@ -14547,7 +14563,7 @@ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager
14547
14563
  };
14548
14564
  const factory = AgentGraphBuilderFactory.getInstance();
14549
14565
  const builder = factory.getBuilder(resolvedConfig.type);
14550
- const params = this.buildAgentParams(resolvedLattice, options);
14566
+ const params = await this.buildAgentParams(resolvedLattice, options);
14551
14567
  return await builder.build(resolvedLattice, params);
14552
14568
  }
14553
14569
  /**
@@ -14625,7 +14641,10 @@ var ChunkBuffer = class {
14625
14641
  };
14626
14642
 
14627
14643
  // src/chunk_buffer_lattice/InMemoryChunkBuffer.ts
14644
+ var import_protocols5 = require("@axiom-lattice/protocols");
14628
14645
  var import_rxjs = require("rxjs");
14646
+ var import_rxjs_for_await = require("rxjs-for-await");
14647
+ var import_operators = require("rxjs/operators");
14629
14648
  var InMemoryChunkBuffer = class extends ChunkBuffer {
14630
14649
  constructor(config) {
14631
14650
  super();
@@ -14710,7 +14729,7 @@ var InMemoryChunkBuffer = class extends ChunkBuffer {
14710
14729
  let chunk;
14711
14730
  if (typeof arg2 === "string" && arg3 !== void 0) {
14712
14731
  chunk = {
14713
- type: "message_chunk",
14732
+ type: import_protocols5.MessageChunkTypes.AI,
14714
14733
  data: {
14715
14734
  id: arg2,
14716
14735
  content: arg3
@@ -14726,7 +14745,6 @@ var InMemoryChunkBuffer = class extends ChunkBuffer {
14726
14745
  buffer2.status = "active" /* ACTIVE */;
14727
14746
  }
14728
14747
  async completeThread(threadId) {
14729
- console.log("completeThread");
14730
14748
  const buffer2 = this.getBufferIfValid(threadId);
14731
14749
  if (buffer2) {
14732
14750
  buffer2.status = "completed" /* COMPLETED */;
@@ -14825,75 +14843,27 @@ var InMemoryChunkBuffer = class extends ChunkBuffer {
14825
14843
  buffer2.updatedAt = Date.now();
14826
14844
  }
14827
14845
  }
14828
- async *getNewChunksSinceContentIterator(threadId, messageId, knownContent) {
14846
+ async *getNewChunksSinceContentIterator(threadId, messageId, knownContent, stopTypes) {
14829
14847
  const buffer2 = this.getBufferIfValid(threadId);
14830
14848
  if (!buffer2) return;
14831
- let accumulatedContent = "";
14832
- const queue = [];
14833
- let resolveNext = null;
14834
- let errorNext = null;
14835
- let isCompleted = false;
14836
- let pendingError = null;
14837
- const subscription = buffer2.chunks$.pipe((0, import_rxjs.observeOn)(import_rxjs.asyncScheduler)).subscribe({
14838
- next: (chunk) => {
14839
- queue.push(chunk);
14840
- if (resolveNext) {
14841
- const resolve3 = resolveNext;
14842
- resolveNext = null;
14843
- resolve3();
14844
- }
14845
- },
14846
- error: (err) => {
14847
- pendingError = err;
14848
- if (errorNext) {
14849
- const reject = errorNext;
14850
- errorNext = null;
14851
- reject(err);
14852
- } else if (resolveNext) {
14853
- const resolve3 = resolveNext;
14854
- resolveNext = null;
14855
- resolve3();
14856
- }
14857
- },
14858
- complete: () => {
14859
- isCompleted = true;
14860
- if (resolveNext) {
14861
- const resolve3 = resolveNext;
14862
- resolveNext = null;
14863
- resolve3();
14864
- }
14865
- }
14866
- });
14849
+ const defaultStopTypes = [
14850
+ import_protocols5.MessageChunkTypes.MESSAGE_COMPLETED,
14851
+ import_protocols5.MessageChunkTypes.THREAD_IDLE
14852
+ ];
14853
+ const typesToStop = stopTypes ?? defaultStopTypes;
14867
14854
  let startYieldChunk = false;
14868
- try {
14869
- while (true) {
14870
- if (pendingError) {
14871
- throw pendingError;
14872
- }
14873
- if (queue.length === 0) {
14874
- if (isCompleted) break;
14875
- await new Promise((resolve3, reject) => {
14876
- resolveNext = resolve3;
14877
- errorNext = reject;
14878
- });
14879
- }
14880
- if (pendingError) {
14881
- throw pendingError;
14882
- }
14883
- while (queue.length > 0) {
14884
- const chunk = queue.shift();
14885
- if (!chunk) continue;
14886
- if (chunk.data?.id === messageId) {
14887
- startYieldChunk = true;
14888
- }
14889
- if (startYieldChunk) {
14890
- yield chunk;
14891
- }
14892
- }
14893
- }
14894
- } finally {
14895
- subscription.unsubscribe();
14896
- }
14855
+ console.log("start from messageId", messageId);
14856
+ const filtered$ = buffer2.chunks$.pipe(
14857
+ (0, import_rxjs.observeOn)(import_rxjs.asyncScheduler),
14858
+ // 1. 从指定 messageId 开始
14859
+ (0, import_operators.filter)((chunk) => {
14860
+ if (chunk.data?.id === messageId) startYieldChunk = true;
14861
+ return startYieldChunk;
14862
+ }),
14863
+ // 2. 包含指定的停止类型,但收到后停止
14864
+ (0, import_operators.takeWhile)((chunk) => !typesToStop.includes(chunk.type), true)
14865
+ );
14866
+ yield* (0, import_rxjs_for_await.eachValueFrom)(filtered$);
14897
14867
  }
14898
14868
  getStats() {
14899
14869
  let activeCount = 0;
@@ -14973,13 +14943,13 @@ var buffer = new InMemoryChunkBuffer({
14973
14943
  registerChunkBuffer("default", buffer);
14974
14944
 
14975
14945
  // src/schedule_lattice/ScheduleLatticeManager.ts
14976
- var import_protocols7 = require("@axiom-lattice/protocols");
14946
+ var import_protocols8 = require("@axiom-lattice/protocols");
14977
14947
 
14978
14948
  // src/schedule_lattice/DefaultScheduleClient.ts
14979
- var import_protocols6 = require("@axiom-lattice/protocols");
14949
+ var import_protocols7 = require("@axiom-lattice/protocols");
14980
14950
 
14981
14951
  // src/schedule_lattice/MemoryScheduleStorage.ts
14982
- var import_protocols5 = require("@axiom-lattice/protocols");
14952
+ var import_protocols6 = require("@axiom-lattice/protocols");
14983
14953
  var MemoryScheduleStorage = class {
14984
14954
  constructor() {
14985
14955
  this.tasks = /* @__PURE__ */ new Map();
@@ -15022,7 +14992,7 @@ var MemoryScheduleStorage = class {
15022
14992
  async getActiveTasks() {
15023
14993
  const result = [];
15024
14994
  for (const task of this.tasks.values()) {
15025
- if (task.status === import_protocols5.ScheduledTaskStatus.PENDING || task.status === import_protocols5.ScheduledTaskStatus.PAUSED) {
14995
+ if (task.status === import_protocols6.ScheduledTaskStatus.PENDING || task.status === import_protocols6.ScheduledTaskStatus.PAUSED) {
15026
14996
  result.push({ ...task });
15027
14997
  }
15028
14998
  }
@@ -15165,7 +15135,7 @@ var MemoryScheduleStorage = class {
15165
15135
  const cutoff = Date.now() - olderThanMs;
15166
15136
  let deleted = 0;
15167
15137
  for (const [taskId, task] of this.tasks.entries()) {
15168
- if ((task.status === import_protocols5.ScheduledTaskStatus.COMPLETED || task.status === import_protocols5.ScheduledTaskStatus.CANCELLED || task.status === import_protocols5.ScheduledTaskStatus.FAILED) && task.updatedAt < cutoff) {
15138
+ if ((task.status === import_protocols6.ScheduledTaskStatus.COMPLETED || task.status === import_protocols6.ScheduledTaskStatus.CANCELLED || task.status === import_protocols6.ScheduledTaskStatus.FAILED) && task.updatedAt < cutoff) {
15169
15139
  this.tasks.delete(taskId);
15170
15140
  deleted++;
15171
15141
  }
@@ -15446,10 +15416,10 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15446
15416
  tenantId: options.tenantId ?? "default",
15447
15417
  assistantId: options.assistantId,
15448
15418
  threadId: options.threadId,
15449
- executionType: import_protocols6.ScheduleExecutionType.ONCE,
15419
+ executionType: import_protocols7.ScheduleExecutionType.ONCE,
15450
15420
  executeAt,
15451
15421
  delayMs: options.delayMs,
15452
- status: import_protocols6.ScheduledTaskStatus.PENDING,
15422
+ status: import_protocols7.ScheduledTaskStatus.PENDING,
15453
15423
  runCount: 0,
15454
15424
  retryCount: 0,
15455
15425
  maxRetries: options.maxRetries ?? 0,
@@ -15492,11 +15462,11 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15492
15462
  tenantId: options.tenantId ?? "default",
15493
15463
  assistantId: options.assistantId,
15494
15464
  threadId: options.threadId,
15495
- executionType: import_protocols6.ScheduleExecutionType.CRON,
15465
+ executionType: import_protocols7.ScheduleExecutionType.CRON,
15496
15466
  cronExpression: options.cronExpression,
15497
15467
  timezone: options.timezone,
15498
15468
  nextRunAt: nextRunAt.getTime(),
15499
- status: import_protocols6.ScheduledTaskStatus.PENDING,
15469
+ status: import_protocols7.ScheduledTaskStatus.PENDING,
15500
15470
  runCount: 0,
15501
15471
  maxRuns: options.maxRuns,
15502
15472
  retryCount: 0,
@@ -15523,7 +15493,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15523
15493
  const task = await this.storage.get(taskId);
15524
15494
  if (task) {
15525
15495
  await this.storage.update(taskId, {
15526
- status: import_protocols6.ScheduledTaskStatus.CANCELLED
15496
+ status: import_protocols7.ScheduledTaskStatus.CANCELLED
15527
15497
  });
15528
15498
  console.log(`[Scheduler] Task cancelled: ${taskId}`);
15529
15499
  return true;
@@ -15532,11 +15502,11 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15532
15502
  }
15533
15503
  async pause(taskId) {
15534
15504
  const task = await this.storage.get(taskId);
15535
- if (!task || task.executionType !== import_protocols6.ScheduleExecutionType.CRON) {
15505
+ if (!task || task.executionType !== import_protocols7.ScheduleExecutionType.CRON) {
15536
15506
  console.error(`[Scheduler] Can only pause CRON tasks: ${taskId}`);
15537
15507
  return false;
15538
15508
  }
15539
- if (task.status !== import_protocols6.ScheduledTaskStatus.PENDING) {
15509
+ if (task.status !== import_protocols7.ScheduledTaskStatus.PENDING) {
15540
15510
  console.error(`[Scheduler] Can only pause PENDING tasks: ${taskId}`);
15541
15511
  return false;
15542
15512
  }
@@ -15546,24 +15516,24 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15546
15516
  this.timers.delete(taskId);
15547
15517
  }
15548
15518
  await this.storage.update(taskId, {
15549
- status: import_protocols6.ScheduledTaskStatus.PAUSED
15519
+ status: import_protocols7.ScheduledTaskStatus.PAUSED
15550
15520
  });
15551
15521
  console.log(`[Scheduler] Task paused: ${taskId}`);
15552
15522
  return true;
15553
15523
  }
15554
15524
  async resume(taskId) {
15555
15525
  const task = await this.storage.get(taskId);
15556
- if (!task || task.executionType !== import_protocols6.ScheduleExecutionType.CRON) {
15526
+ if (!task || task.executionType !== import_protocols7.ScheduleExecutionType.CRON) {
15557
15527
  console.error(`[Scheduler] Can only resume CRON tasks: ${taskId}`);
15558
15528
  return false;
15559
15529
  }
15560
- if (task.status !== import_protocols6.ScheduledTaskStatus.PAUSED) {
15530
+ if (task.status !== import_protocols7.ScheduledTaskStatus.PAUSED) {
15561
15531
  console.error(`[Scheduler] Can only resume PAUSED tasks: ${taskId}`);
15562
15532
  return false;
15563
15533
  }
15564
15534
  const nextRunAt = getNextCronTime(task.cronExpression);
15565
15535
  await this.storage.update(taskId, {
15566
- status: import_protocols6.ScheduledTaskStatus.PENDING,
15536
+ status: import_protocols7.ScheduledTaskStatus.PENDING,
15567
15537
  nextRunAt: nextRunAt.getTime()
15568
15538
  });
15569
15539
  const updatedTask = await this.storage.get(taskId);
@@ -15585,7 +15555,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15585
15555
  if (!task) {
15586
15556
  return -1;
15587
15557
  }
15588
- const targetTime = task.executionType === import_protocols6.ScheduleExecutionType.CRON ? task.nextRunAt : task.executeAt;
15558
+ const targetTime = task.executionType === import_protocols7.ScheduleExecutionType.CRON ? task.nextRunAt : task.executeAt;
15589
15559
  if (targetTime === void 0) {
15590
15560
  return -1;
15591
15561
  }
@@ -15607,7 +15577,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15607
15577
  const activeTasks = await this.storage.getActiveTasks();
15608
15578
  for (const task of activeTasks) {
15609
15579
  await this.storage.update(task.taskId, {
15610
- status: import_protocols6.ScheduledTaskStatus.CANCELLED
15580
+ status: import_protocols7.ScheduledTaskStatus.CANCELLED
15611
15581
  });
15612
15582
  }
15613
15583
  console.log(`[Scheduler] All tasks cancelled`);
@@ -15623,10 +15593,10 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15623
15593
  );
15624
15594
  continue;
15625
15595
  }
15626
- if (task.status === import_protocols6.ScheduledTaskStatus.PAUSED) {
15596
+ if (task.status === import_protocols7.ScheduledTaskStatus.PAUSED) {
15627
15597
  continue;
15628
15598
  }
15629
- if (task.executionType === import_protocols6.ScheduleExecutionType.ONCE) {
15599
+ if (task.executionType === import_protocols7.ScheduleExecutionType.ONCE) {
15630
15600
  if (task.executeAt && task.executeAt <= Date.now()) {
15631
15601
  console.log(
15632
15602
  `[Scheduler] Executing overdue one-time task: ${task.taskId}`
@@ -15635,7 +15605,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15635
15605
  } else {
15636
15606
  this.scheduleTimer(task);
15637
15607
  }
15638
- } else if (task.executionType === import_protocols6.ScheduleExecutionType.CRON) {
15608
+ } else if (task.executionType === import_protocols7.ScheduleExecutionType.CRON) {
15639
15609
  const nextRunAt = getNextCronTime(task.cronExpression);
15640
15610
  await this.storage.update(task.taskId, {
15641
15611
  nextRunAt: nextRunAt.getTime()
@@ -15659,7 +15629,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15659
15629
  }
15660
15630
  // ===== Private Methods =====
15661
15631
  scheduleTimer(task) {
15662
- const targetTime = task.executionType === import_protocols6.ScheduleExecutionType.CRON ? task.nextRunAt : task.executeAt;
15632
+ const targetTime = task.executionType === import_protocols7.ScheduleExecutionType.CRON ? task.nextRunAt : task.executeAt;
15663
15633
  if (targetTime === void 0) {
15664
15634
  console.error(`[Scheduler] No execution time for task: ${task.taskId}`);
15665
15635
  return;
@@ -15680,13 +15650,13 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15680
15650
  `[Scheduler] No handler for task type: ${task.taskType}, task: ${task.taskId}`
15681
15651
  );
15682
15652
  await this.storage.update(task.taskId, {
15683
- status: import_protocols6.ScheduledTaskStatus.FAILED,
15653
+ status: import_protocols7.ScheduledTaskStatus.FAILED,
15684
15654
  lastError: `No handler registered for task type: ${task.taskType}`
15685
15655
  });
15686
15656
  return;
15687
15657
  }
15688
15658
  await this.storage.update(task.taskId, {
15689
- status: import_protocols6.ScheduledTaskStatus.RUNNING
15659
+ status: import_protocols7.ScheduledTaskStatus.RUNNING
15690
15660
  });
15691
15661
  console.log(`[Scheduler] Executing task: ${task.taskId}`);
15692
15662
  try {
@@ -15698,17 +15668,17 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15698
15668
  await handler(latestTask.payload, latestTask);
15699
15669
  const newRunCount = latestTask.runCount + 1;
15700
15670
  console.log(`[Scheduler] Task completed: ${task.taskId}`);
15701
- if (task.executionType === import_protocols6.ScheduleExecutionType.ONCE) {
15671
+ if (task.executionType === import_protocols7.ScheduleExecutionType.ONCE) {
15702
15672
  await this.storage.update(task.taskId, {
15703
- status: import_protocols6.ScheduledTaskStatus.COMPLETED,
15673
+ status: import_protocols7.ScheduledTaskStatus.COMPLETED,
15704
15674
  runCount: newRunCount,
15705
15675
  lastRunAt: Date.now()
15706
15676
  });
15707
15677
  this.timers.delete(task.taskId);
15708
- } else if (task.executionType === import_protocols6.ScheduleExecutionType.CRON) {
15678
+ } else if (task.executionType === import_protocols7.ScheduleExecutionType.CRON) {
15709
15679
  if (task.maxRuns !== void 0 && newRunCount >= task.maxRuns) {
15710
15680
  await this.storage.update(task.taskId, {
15711
- status: import_protocols6.ScheduledTaskStatus.COMPLETED,
15681
+ status: import_protocols7.ScheduledTaskStatus.COMPLETED,
15712
15682
  runCount: newRunCount,
15713
15683
  lastRunAt: Date.now()
15714
15684
  });
@@ -15720,7 +15690,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15720
15690
  }
15721
15691
  if (task.expiresAt !== void 0 && Date.now() >= task.expiresAt) {
15722
15692
  await this.storage.update(task.taskId, {
15723
- status: import_protocols6.ScheduledTaskStatus.COMPLETED,
15693
+ status: import_protocols7.ScheduledTaskStatus.COMPLETED,
15724
15694
  runCount: newRunCount,
15725
15695
  lastRunAt: Date.now()
15726
15696
  });
@@ -15732,7 +15702,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15732
15702
  }
15733
15703
  const nextRunAt = getNextCronTime(task.cronExpression);
15734
15704
  await this.storage.update(task.taskId, {
15735
- status: import_protocols6.ScheduledTaskStatus.PENDING,
15705
+ status: import_protocols7.ScheduledTaskStatus.PENDING,
15736
15706
  runCount: newRunCount,
15737
15707
  lastRunAt: Date.now(),
15738
15708
  nextRunAt: nextRunAt.getTime(),
@@ -15758,7 +15728,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15758
15728
  `[Scheduler] Retrying task: ${task.taskId} (attempt ${newRetryCount}/${latestTask.maxRetries})`
15759
15729
  );
15760
15730
  await this.storage.update(task.taskId, {
15761
- status: import_protocols6.ScheduledTaskStatus.PENDING,
15731
+ status: import_protocols7.ScheduledTaskStatus.PENDING,
15762
15732
  retryCount: newRetryCount,
15763
15733
  lastError: errorMessage
15764
15734
  });
@@ -15768,7 +15738,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15768
15738
  );
15769
15739
  const retryTask = await this.storage.get(task.taskId);
15770
15740
  if (retryTask) {
15771
- if (task.executionType === import_protocols6.ScheduleExecutionType.ONCE) {
15741
+ if (task.executionType === import_protocols7.ScheduleExecutionType.ONCE) {
15772
15742
  retryTask.executeAt = Date.now() + retryDelay;
15773
15743
  } else {
15774
15744
  retryTask.nextRunAt = Date.now() + retryDelay;
@@ -15781,7 +15751,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
15781
15751
  }
15782
15752
  } else {
15783
15753
  await this.storage.update(task.taskId, {
15784
- status: import_protocols6.ScheduledTaskStatus.FAILED,
15754
+ status: import_protocols7.ScheduledTaskStatus.FAILED,
15785
15755
  retryCount: newRetryCount,
15786
15756
  lastError: errorMessage
15787
15757
  });
@@ -15833,9 +15803,9 @@ var ScheduleLatticeManager = class _ScheduleLatticeManager extends BaseLatticeMa
15833
15803
  } else {
15834
15804
  storage = new MemoryScheduleStorage();
15835
15805
  }
15836
- if (config.type === import_protocols7.ScheduleType.MEMORY) {
15806
+ if (config.type === import_protocols8.ScheduleType.MEMORY) {
15837
15807
  scheduleClient = new DefaultScheduleClient(storage);
15838
- } else if (config.type === import_protocols7.ScheduleType.POSTGRES) {
15808
+ } else if (config.type === import_protocols8.ScheduleType.POSTGRES) {
15839
15809
  if (!config.storage) {
15840
15810
  throw new Error(
15841
15811
  `PostgreSQL schedule storage must be provided. Please install @axiom-lattice/pg-stores and pass the storage in config.storage.`
@@ -16145,7 +16115,7 @@ var getVectorStoreLattice = (key) => vectorStoreLatticeManager.getVectorStoreLat
16145
16115
  var getVectorStoreClient = (key) => vectorStoreLatticeManager.getVectorStoreClient(key);
16146
16116
 
16147
16117
  // src/logger_lattice/LoggerLatticeManager.ts
16148
- var import_protocols8 = require("@axiom-lattice/protocols");
16118
+ var import_protocols9 = require("@axiom-lattice/protocols");
16149
16119
 
16150
16120
  // src/logger_lattice/PinoLoggerClient.ts
16151
16121
  var import_pino = __toESM(require("pino"));
@@ -16367,11 +16337,11 @@ var LoggerLatticeManager = class _LoggerLatticeManager extends BaseLatticeManage
16367
16337
  if (client) {
16368
16338
  loggerClient = client;
16369
16339
  } else {
16370
- if (config.type === import_protocols8.LoggerType.PINO) {
16340
+ if (config.type === import_protocols9.LoggerType.PINO) {
16371
16341
  loggerClient = new PinoLoggerClient(config);
16372
- } else if (config.type === import_protocols8.LoggerType.CONSOLE) {
16342
+ } else if (config.type === import_protocols9.LoggerType.CONSOLE) {
16373
16343
  loggerClient = new ConsoleLoggerClient(config);
16374
- } else if (config.type === import_protocols8.LoggerType.CUSTOM) {
16344
+ } else if (config.type === import_protocols9.LoggerType.CUSTOM) {
16375
16345
  throw new Error(
16376
16346
  `Custom logger client must be provided. Please pass the client to registerLattice.`
16377
16347
  );
@@ -17008,7 +16978,7 @@ var Agent = class {
17008
16978
  command,
17009
16979
  custom_run_config
17010
16980
  }, signal) => {
17011
- const runnable_agent = await getAgentClient(this.tenant_id, this.assistant_id);
16981
+ const runnable_agent = await getAgentClientAsync(this.tenant_id, this.assistant_id);
17012
16982
  const agentLattice = agentLatticeManager.getAgentLatticeWithTenant(this.tenant_id, this.assistant_id);
17013
16983
  const { messages, ...rest } = input;
17014
16984
  const lifecycleManager = this;
@@ -17090,9 +17060,7 @@ var Agent = class {
17090
17060
  };
17091
17061
  }
17092
17062
  if (data) {
17093
- if (data.type !== "interrupt") {
17094
- await lifecycleManager.addChunk(data);
17095
- }
17063
+ lifecycleManager.addChunk(data);
17096
17064
  }
17097
17065
  }
17098
17066
  } catch (error) {
@@ -17109,8 +17077,8 @@ var Agent = class {
17109
17077
  while (!signal?.aborted) {
17110
17078
  const pendings = await this.getPendingMessages();
17111
17079
  if (pendings.length === 0) {
17112
- await this.tryToCompleteThread();
17113
17080
  const state = await this.getCurrentState();
17081
+ const runStatus = await this.getRunStatus();
17114
17082
  const pendingCount = await this.getQueueStore().getQueueSize(this.thread_id);
17115
17083
  this.publish("thread:idle", {
17116
17084
  type: "thread:idle",
@@ -17118,6 +17086,15 @@ var Agent = class {
17118
17086
  pendingCount,
17119
17087
  state
17120
17088
  });
17089
+ if (runStatus === "idle" /* IDLE */) {
17090
+ this.addChunk({
17091
+ type: "thread_idle",
17092
+ data: {
17093
+ id: this.thread_id,
17094
+ content: ""
17095
+ }
17096
+ });
17097
+ }
17121
17098
  break;
17122
17099
  }
17123
17100
  const firstMessage = pendings[0];
@@ -17138,22 +17115,49 @@ var Agent = class {
17138
17115
  const input = {
17139
17116
  messages: [new import_langchain61.HumanMessage({ id: p.content.id, content: p.content.message })]
17140
17117
  };
17118
+ const queueMessageData = p.content.queueMessage || {};
17141
17119
  try {
17142
17120
  await this.agentStreamExecutor({
17143
17121
  input,
17144
- command: p.content.command
17122
+ command: queueMessageData.command || p.content.command,
17123
+ custom_run_config: queueMessageData.custom_run_config
17145
17124
  }, signal);
17146
17125
  await this.queueStore?.markCompleted(p.id);
17126
+ const runStatus = await this.getRunStatus();
17147
17127
  const state = await this.getCurrentState();
17148
- this.publish("message:completed", {
17149
- type: "message:completed",
17150
- messageId: p.content.id,
17151
- timestamp: /* @__PURE__ */ new Date(),
17152
- duration: Date.now() - startTime,
17153
- state
17154
- });
17128
+ if (runStatus === "interrupted" /* INTERRUPTED */) {
17129
+ this.publish("message:interrupted", {
17130
+ type: "message:interrupted",
17131
+ messageId: p.content.id,
17132
+ timestamp: /* @__PURE__ */ new Date(),
17133
+ duration: Date.now() - startTime,
17134
+ state
17135
+ });
17136
+ } else {
17137
+ this.addChunk({
17138
+ type: "message_completed",
17139
+ data: {
17140
+ id: p.content.id,
17141
+ content: ""
17142
+ }
17143
+ });
17144
+ this.publish("message:completed", {
17145
+ type: "message:completed",
17146
+ messageId: p.content.id,
17147
+ timestamp: /* @__PURE__ */ new Date(),
17148
+ duration: Date.now() - startTime,
17149
+ state
17150
+ });
17151
+ }
17155
17152
  } catch (error) {
17156
17153
  console.error(`STEER/Command message ${p.id} execution failed:`, error);
17154
+ this.addChunk({
17155
+ type: "message_failed",
17156
+ data: {
17157
+ id: p.content.id,
17158
+ content: error instanceof Error ? error.message : String(error)
17159
+ }
17160
+ });
17157
17161
  this.publish("message:failed", {
17158
17162
  type: "message:failed",
17159
17163
  messageId: p.content.id,
@@ -17180,22 +17184,51 @@ var Agent = class {
17180
17184
  queueMode: "collect" /* COLLECT */
17181
17185
  });
17182
17186
  });
17187
+ const firstQueueMessage = remainingPendings[0]?.content?.queueMessage || {};
17183
17188
  try {
17184
- await this.agentStreamExecutor({ input: { messages: userMessages } }, signal);
17189
+ await this.agentStreamExecutor({
17190
+ input: { messages: userMessages },
17191
+ custom_run_config: firstQueueMessage.custom_run_config
17192
+ }, signal);
17193
+ const runStatus = await this.getRunStatus();
17185
17194
  const state = await this.getCurrentState();
17186
17195
  for (const p of remainingPendings) {
17187
17196
  await this.queueStore?.markCompleted(p.id);
17188
- this.publish("message:completed", {
17189
- type: "message:completed",
17190
- messageId: p.content.id,
17191
- timestamp: /* @__PURE__ */ new Date(),
17192
- duration: Date.now() - startTime,
17193
- state
17194
- });
17197
+ if (runStatus === "interrupted" /* INTERRUPTED */) {
17198
+ this.publish("message:interrupted", {
17199
+ type: "message:interrupted",
17200
+ messageId: p.content.id,
17201
+ timestamp: /* @__PURE__ */ new Date(),
17202
+ duration: Date.now() - startTime,
17203
+ state
17204
+ });
17205
+ } else {
17206
+ this.addChunk({
17207
+ type: "message_completed",
17208
+ data: {
17209
+ id: p.content.id,
17210
+ content: ""
17211
+ }
17212
+ });
17213
+ this.publish("message:completed", {
17214
+ type: "message:completed",
17215
+ messageId: p.content.id,
17216
+ timestamp: /* @__PURE__ */ new Date(),
17217
+ duration: Date.now() - startTime,
17218
+ state
17219
+ });
17220
+ }
17195
17221
  }
17196
17222
  } catch (error) {
17197
17223
  console.error(`COLLECT mode execution failed:`, error);
17198
17224
  for (const p of remainingPendings) {
17225
+ this.addChunk({
17226
+ type: "message_failed",
17227
+ data: {
17228
+ id: p.content.id,
17229
+ content: error instanceof Error ? error.message : String(error)
17230
+ }
17231
+ });
17199
17232
  this.publish("message:failed", {
17200
17233
  type: "message:failed",
17201
17234
  messageId: p.content.id,
@@ -17218,19 +17251,48 @@ var Agent = class {
17218
17251
  timestamp: /* @__PURE__ */ new Date(),
17219
17252
  queueMode: "followup" /* FOLLOWUP */
17220
17253
  });
17254
+ const queueMessageData = p.content.queueMessage || {};
17221
17255
  try {
17222
- await this.agentStreamExecutor({ input: { messages: [message] } }, signal);
17256
+ await this.agentStreamExecutor({
17257
+ input: { messages: [message] },
17258
+ custom_run_config: queueMessageData.custom_run_config
17259
+ }, signal);
17223
17260
  await this.queueStore?.markCompleted(p.id);
17261
+ const runStatus = await this.getRunStatus();
17224
17262
  const state = await this.getCurrentState();
17225
- this.publish("message:completed", {
17226
- type: "message:completed",
17227
- messageId: p.content.id,
17228
- timestamp: /* @__PURE__ */ new Date(),
17229
- duration: Date.now() - startTime,
17230
- state
17231
- });
17263
+ if (runStatus === "interrupted" /* INTERRUPTED */) {
17264
+ this.publish("message:interrupted", {
17265
+ type: "message:interrupted",
17266
+ messageId: p.content.id,
17267
+ timestamp: /* @__PURE__ */ new Date(),
17268
+ duration: Date.now() - startTime,
17269
+ state
17270
+ });
17271
+ } else {
17272
+ this.addChunk({
17273
+ type: "message_completed",
17274
+ data: {
17275
+ id: p.content.id,
17276
+ content: ""
17277
+ }
17278
+ });
17279
+ this.publish("message:completed", {
17280
+ type: "message:completed",
17281
+ messageId: p.content.id,
17282
+ timestamp: /* @__PURE__ */ new Date(),
17283
+ duration: Date.now() - startTime,
17284
+ state
17285
+ });
17286
+ }
17232
17287
  } catch (error) {
17233
17288
  console.error(`FOLLOWUP mode message ${p.id} execution failed:`, error);
17289
+ this.addChunk({
17290
+ type: "message_failed",
17291
+ data: {
17292
+ id: p.content.id,
17293
+ content: error instanceof Error ? error.message : String(error)
17294
+ }
17295
+ });
17234
17296
  this.publish("message:failed", {
17235
17297
  type: "message:failed",
17236
17298
  messageId: p.content.id,
@@ -17260,11 +17322,12 @@ var Agent = class {
17260
17322
  addChunk(content) {
17261
17323
  return this.chunkBuffer.addChunk(this.thread_id, content);
17262
17324
  }
17263
- chunkStream(message_id, known_content = "") {
17325
+ chunkStream(message_id, stopTypes) {
17264
17326
  const stream = this.chunkBuffer.getNewChunksSinceContentIterator(
17265
17327
  this.thread_id,
17266
17328
  message_id,
17267
- known_content
17329
+ "",
17330
+ stopTypes
17268
17331
  );
17269
17332
  return {
17270
17333
  [Symbol.asyncIterator]: async function* () {
@@ -17319,11 +17382,6 @@ var Agent = class {
17319
17382
  const store = this.getQueueStore();
17320
17383
  return await store.getPendingMessages(this.thread_id);
17321
17384
  }
17322
- async tryToCompleteThread() {
17323
- setTimeout(async () => {
17324
- await this.chunkBuffer.completeThread(this.thread_id);
17325
- }, 100);
17326
- }
17327
17385
  getQueueStore() {
17328
17386
  if (!this.queueStore) {
17329
17387
  try {
@@ -17379,11 +17437,14 @@ var Agent = class {
17379
17437
  }
17380
17438
  const content = {
17381
17439
  message: queueMessage.input.message,
17382
- id: messageId
17440
+ id: messageId,
17441
+ // Store complete queue message data for recovery
17442
+ queueMessage: {
17443
+ input: queueMessage.input,
17444
+ command: queueMessage.command,
17445
+ custom_run_config: queueMessage.custom_run_config
17446
+ }
17383
17447
  };
17384
- if (queueMessage.command) {
17385
- content.command = queueMessage.command;
17386
- }
17387
17448
  if (isHighPriority) {
17388
17449
  await store.addMessageAtHead(this.thread_id, content, "human");
17389
17450
  } else {
@@ -17411,7 +17472,7 @@ var Agent = class {
17411
17472
  }
17412
17473
  /**
17413
17474
  * Start queue processor if not already running
17414
- * Private method used internally by addMessage
17475
+ * Public method to allow external triggering (e.g., from recovery)
17415
17476
  */
17416
17477
  async startQueueProcessorIfNeeded() {
17417
17478
  const store = this.getQueueStore();
@@ -17499,6 +17560,30 @@ var Agent = class {
17499
17560
  }
17500
17561
  return "idle" /* IDLE */;
17501
17562
  }
17563
+ /**
17564
+ * Resume task processing after server restart
17565
+ * Resets any stuck processing messages to pending and starts queue processing
17566
+ * Note: Does not rely on LangGraph state as it may be stale after crash/restart
17567
+ */
17568
+ async resumeTask() {
17569
+ try {
17570
+ await agentLatticeManager.initializeClientAsync(this.tenant_id, this.assistant_id);
17571
+ } catch (error) {
17572
+ console.error(`[Agent] Failed to initialize agent lattice for ${this.assistant_id} (tenant: ${this.tenant_id}):`, error);
17573
+ throw error;
17574
+ }
17575
+ const runStatus = await this.getRunStatus();
17576
+ if (runStatus === "interrupted" /* INTERRUPTED */) {
17577
+ console.log(`[Agent] Skipping resume for ${this.assistant_id} (tenant: ${this.tenant_id}) - agent is in interrupted state`);
17578
+ return;
17579
+ }
17580
+ const store = this.getQueueStore();
17581
+ const resetCount = await store.resetProcessingToPending(this.thread_id);
17582
+ if (resetCount > 0) {
17583
+ console.log(`[Agent] Reset ${resetCount} processing messages to pending for thread ${this.thread_id}`);
17584
+ }
17585
+ await this.startQueueProcessorIfNeeded();
17586
+ }
17502
17587
  /**
17503
17588
  * Abort the current agent execution
17504
17589
  * This will cancel any ongoing invoke or stream operations
@@ -17542,6 +17627,7 @@ var Agent = class {
17542
17627
  */
17543
17628
  publish(eventName, data) {
17544
17629
  const namespacedEvent = `${eventName}:${this.tenant_id}:${this.thread_id}`;
17630
+ console.log(namespacedEvent);
17545
17631
  event_bus_default.publish(namespacedEvent, data);
17546
17632
  }
17547
17633
  };
@@ -17607,6 +17693,57 @@ var AgentInstanceManager = class _AgentInstanceManager {
17607
17693
  });
17608
17694
  this.agents.clear();
17609
17695
  }
17696
+ /**
17697
+ * Restore agent instances for threads with pending messages after server restart
17698
+ * Queries the message queue store for threads with pending/processing messages
17699
+ * and recreates agent instances to resume processing
17700
+ */
17701
+ async restore() {
17702
+ const stats = { restored: 0, errors: 0 };
17703
+ try {
17704
+ const queueStoreLattice = storeLatticeManager.getStoreLattice("default", "threadMessageQueue");
17705
+ const queueStore = queueStoreLattice.store;
17706
+ const threadsWithPending = await queueStore.getThreadsWithPendingMessages();
17707
+ if (threadsWithPending.length === 0) {
17708
+ console.log("[AgentInstanceManager] No threads with pending messages found");
17709
+ return stats;
17710
+ }
17711
+ console.log(`[AgentInstanceManager] Found ${threadsWithPending.length} threads with pending messages, restoring...`);
17712
+ for (const threadInfo of threadsWithPending) {
17713
+ try {
17714
+ await this.restoreThread(threadInfo, queueStore);
17715
+ stats.restored++;
17716
+ } catch (error) {
17717
+ console.error(`[AgentInstanceManager] Failed to restore thread ${threadInfo.threadId}:`, error);
17718
+ stats.errors++;
17719
+ }
17720
+ }
17721
+ console.log(`[AgentInstanceManager] Restore complete: ${stats.restored} restored, ${stats.errors} errors`);
17722
+ return stats;
17723
+ } catch (error) {
17724
+ console.error("[AgentInstanceManager] Restore failed:", error);
17725
+ throw error;
17726
+ }
17727
+ }
17728
+ /**
17729
+ * Restore a single thread
17730
+ * Delegates actual recovery logic to Agent.resumeTask()
17731
+ */
17732
+ async restoreThread(threadInfo, queueStore) {
17733
+ const { tenantId, assistantId, threadId } = threadInfo;
17734
+ const threadParams = {
17735
+ tenant_id: tenantId,
17736
+ assistant_id: assistantId,
17737
+ thread_id: threadId,
17738
+ workspace_id: "default",
17739
+ // TODO: Get from thread store
17740
+ project_id: "default"
17741
+ // TODO: Get from thread store
17742
+ };
17743
+ const agent = this.getAgent(threadParams);
17744
+ await agent.resumeTask();
17745
+ console.log(`[AgentInstanceManager] Restored thread ${threadId}`);
17746
+ }
17610
17747
  };
17611
17748
  var agentInstanceManager = AgentInstanceManager.getInstance();
17612
17749