@axiom-lattice/gateway 2.1.91 → 2.1.93

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
@@ -56,8 +56,8 @@ async function createLarkSender(config, client) {
56
56
  };
57
57
  }
58
58
  async function createDefaultLarkClient(config) {
59
- const Lark = await import("@larksuiteoapi/node-sdk");
60
- return new Lark.Client({
59
+ const Lark2 = await import("@larksuiteoapi/node-sdk");
60
+ return new Lark2.Client({
61
61
  appId: config.appId,
62
62
  appSecret: config.appSecret
63
63
  });
@@ -303,7 +303,7 @@ async function handleTasksSend(request, reply) {
303
303
  taskStore.set(taskId, record);
304
304
  let agent;
305
305
  try {
306
- agent = import_core31.agentInstanceManager.getAgent({
306
+ agent = import_core34.agentInstanceManager.getAgent({
307
307
  assistant_id: assistantId,
308
308
  thread_id: threadId,
309
309
  tenant_id: tenantId,
@@ -395,7 +395,7 @@ async function handleTasksCancel(request, reply) {
395
395
  return;
396
396
  }
397
397
  try {
398
- const agent = import_core31.agentInstanceManager.getAgent({
398
+ const agent = import_core34.agentInstanceManager.getAgent({
399
399
  assistant_id: record.assistantId,
400
400
  thread_id: record.threadId,
401
401
  tenant_id: record.tenantId,
@@ -432,7 +432,7 @@ async function handleTasksStream(request, reply) {
432
432
  }
433
433
  let agent;
434
434
  try {
435
- agent = import_core31.agentInstanceManager.getAgent({
435
+ agent = import_core34.agentInstanceManager.getAgent({
436
436
  assistant_id: record.assistantId,
437
437
  thread_id: record.threadId,
438
438
  tenant_id: record.tenantId,
@@ -627,12 +627,12 @@ function registerA2ARoutes(app2) {
627
627
  handleApiKeyRotate
628
628
  );
629
629
  }
630
- var import_uuid9, import_core31, import_protocols4, taskStore, _a2aKeyStore, _storeKeyMap;
630
+ var import_uuid9, import_core34, import_protocols4, taskStore, _a2aKeyStore, _storeKeyMap;
631
631
  var init_a2a = __esm({
632
632
  "src/routes/a2a.ts"() {
633
633
  "use strict";
634
634
  import_uuid9 = require("uuid");
635
- import_core31 = require("@axiom-lattice/core");
635
+ import_core34 = require("@axiom-lattice/core");
636
636
  import_protocols4 = require("@axiom-lattice/protocols");
637
637
  taskStore = /* @__PURE__ */ new Map();
638
638
  _a2aKeyStore = null;
@@ -666,6 +666,11 @@ function getTenantId(request) {
666
666
  }
667
667
  return request.headers["x-tenant-id"] || "default";
668
668
  }
669
+ function getUserId(request) {
670
+ const userId = request.user?.id;
671
+ if (userId) return userId;
672
+ return request.headers["x-user-id"] || void 0;
673
+ }
669
674
  function convertAgentConfigToAssistant(config) {
670
675
  return {
671
676
  id: config.key,
@@ -698,12 +703,17 @@ async function getAssistantList(request, reply) {
698
703
  assistantMap.set(assistant.id, assistant);
699
704
  });
700
705
  const allAssistants = Array.from(assistantMap.values());
706
+ const userId = getUserId(request);
707
+ const filtered = allAssistants.filter((a) => {
708
+ if (!a.ownerUserId) return true;
709
+ return a.ownerUserId === userId;
710
+ });
701
711
  return {
702
712
  success: true,
703
713
  message: "Successfully retrieved assistant list",
704
714
  data: {
705
- records: allAssistants,
706
- total: allAssistants.length
715
+ records: filtered,
716
+ total: filtered.length
707
717
  }
708
718
  };
709
719
  }
@@ -849,7 +859,7 @@ var getAgentGraph = async (request, reply) => {
849
859
  var import_uuid = require("uuid");
850
860
  var import_core3 = require("@axiom-lattice/core");
851
861
  var import_protocols = require("@axiom-lattice/protocols");
852
- function getUserId(request) {
862
+ function getUserId2(request) {
853
863
  const authUser = request.user;
854
864
  if (authUser?.id) return authUser.id;
855
865
  return request.headers["x-user-id"] || void 0;
@@ -871,7 +881,7 @@ var createRun = async (request, reply) => {
871
881
  const workspace_id = request.headers["x-workspace-id"];
872
882
  const project_id = request.headers["x-project-id"];
873
883
  const x_request_id = request.headers["x-request-id"] || (0, import_uuid.v4)();
874
- const user_id = getUserId(request);
884
+ const user_id = getUserId2(request);
875
885
  const mergedConfig = user_id ? { ...custom_run_config, user_id } : custom_run_config;
876
886
  if (!assistant_id) {
877
887
  reply.status(400).send({
@@ -1025,6 +1035,33 @@ var abortRun = async (request, reply) => {
1025
1035
  });
1026
1036
  }
1027
1037
  };
1038
+ var recoverRun = async (request, reply) => {
1039
+ try {
1040
+ const { assistantId, threadId } = request.params;
1041
+ const tenant_id = request.headers["x-tenant-id"];
1042
+ const workspace_id = request.headers["x-workspace-id"] || "default";
1043
+ const project_id = request.headers["x-project-id"] || "default";
1044
+ const agent = import_core3.agentInstanceManager.getAgent({
1045
+ assistant_id: assistantId,
1046
+ thread_id: threadId,
1047
+ tenant_id,
1048
+ workspace_id,
1049
+ project_id
1050
+ });
1051
+ await agent.resumeTask();
1052
+ const status = await agent.getRunStatus();
1053
+ reply.status(200).send({
1054
+ success: true,
1055
+ threadId,
1056
+ status
1057
+ });
1058
+ } catch (error) {
1059
+ reply.status(500).send({
1060
+ success: false,
1061
+ error: `Recover failed: ${error.message}`
1062
+ });
1063
+ }
1064
+ };
1028
1065
 
1029
1066
  // src/controllers/memory.ts
1030
1067
  var import_core4 = require("@axiom-lattice/core");
@@ -1197,6 +1234,8 @@ var triggerAgentTask = async (request, reply) => {
1197
1234
  try {
1198
1235
  const { assistant_id, thread_id, input, command } = request.body;
1199
1236
  const tenant_id = request.headers["x-tenant-id"];
1237
+ const workspace_id = request.headers["x-workspace-id"];
1238
+ const project_id = request.headers["x-project-id"];
1200
1239
  if (!assistant_id) {
1201
1240
  reply.status(400).send({
1202
1241
  success: false,
@@ -1217,7 +1256,12 @@ var triggerAgentTask = async (request, reply) => {
1217
1256
  thread_id,
1218
1257
  input,
1219
1258
  command,
1220
- "x-tenant-id": tenant_id
1259
+ "x-tenant-id": tenant_id,
1260
+ runConfig: {
1261
+ workspaceId: workspace_id,
1262
+ projectId: project_id,
1263
+ user_id: request.user?.id
1264
+ }
1221
1265
  });
1222
1266
  reply.status(200).send({
1223
1267
  success: true
@@ -2450,6 +2494,16 @@ async function getAllWorkflowRuns(request, reply) {
2450
2494
  if (!store) {
2451
2495
  return reply.status(404).send({ success: false, message: "No workflow tracking store configured" });
2452
2496
  }
2497
+ const nameMap = {};
2498
+ try {
2499
+ const asStoreLattice = (0, import_core13.getStoreLattice)("default", "assistant");
2500
+ const assistantStore = asStoreLattice.store;
2501
+ const assistants = await assistantStore.getAllAssistants(tenantId);
2502
+ for (const a of assistants) {
2503
+ nameMap[a.id] = a.name;
2504
+ }
2505
+ } catch {
2506
+ }
2453
2507
  let runs;
2454
2508
  if (assistantId) {
2455
2509
  runs = await store.getWorkflowRunsByAssistantId(tenantId, assistantId);
@@ -2459,10 +2513,22 @@ async function getAllWorkflowRuns(request, reply) {
2459
2513
  if (status) {
2460
2514
  runs = runs.filter((r) => r.status === status);
2461
2515
  }
2516
+ const enrichedRuns = await Promise.all(
2517
+ runs.map(async (run) => {
2518
+ try {
2519
+ const steps = await store.getRunSteps(run.id);
2520
+ const totalSteps = steps.length;
2521
+ const completedSteps = steps.filter((s) => s.status === "completed").length;
2522
+ return { ...run, totalSteps, completedSteps, assistantName: nameMap[run.assistantId] || run.assistantId };
2523
+ } catch {
2524
+ return { ...run, totalSteps: 0, completedSteps: 0, assistantName: nameMap[run.assistantId] || run.assistantId };
2525
+ }
2526
+ })
2527
+ );
2462
2528
  return {
2463
2529
  success: true,
2464
2530
  message: "Successfully retrieved workflow runs",
2465
- data: { records: runs, total: runs.length }
2531
+ data: { records: enrichedRuns, total: enrichedRuns.length }
2466
2532
  };
2467
2533
  } catch (error) {
2468
2534
  request.log.error(error, "Failed to get workflow runs");
@@ -2487,17 +2553,40 @@ async function getInboxItems(request, reply) {
2487
2553
  } catch {
2488
2554
  }
2489
2555
  const runs = await store.getWorkflowRunsByTenantId(tenantId);
2490
- const runningRuns = runs.filter((r) => r.status === "running");
2491
- if (runningRuns.length === 0) {
2492
- return { success: true, message: "No running workflows", data: { records: [] } };
2556
+ const pendingRuns = runs.filter((r) => r.status === "interrupted");
2557
+ if (pendingRuns.length === 0) {
2558
+ return { success: true, message: "No pending workflows", data: { records: [] } };
2493
2559
  }
2494
- const checkPromises = runningRuns.map(async (r) => {
2560
+ const checkPromises = pendingRuns.map(async (r) => {
2495
2561
  try {
2496
- const agent = import_core13.agentInstanceManager.getAgent({
2497
- assistant_id: r.assistantId,
2498
- thread_id: r.threadId,
2499
- tenant_id: r.tenantId
2500
- });
2562
+ const [steps, agent] = await Promise.all([
2563
+ store.getRunSteps(r.id).catch(() => []),
2564
+ (async () => {
2565
+ try {
2566
+ return import_core13.agentInstanceManager.getAgent({
2567
+ assistant_id: r.assistantId,
2568
+ thread_id: r.threadId,
2569
+ tenant_id: r.tenantId
2570
+ });
2571
+ } catch {
2572
+ return null;
2573
+ }
2574
+ })()
2575
+ ]);
2576
+ if (!agent) {
2577
+ return [{
2578
+ runId: r.id,
2579
+ assistantId: r.assistantId,
2580
+ assistantName: nameMap[r.assistantId] || r.assistantId,
2581
+ threadId: r.threadId,
2582
+ tenantId: r.tenantId,
2583
+ status: r.status,
2584
+ startedAt: r.startedAt,
2585
+ totalEdges: r.totalEdges,
2586
+ completedEdges: r.completedEdges,
2587
+ steps
2588
+ }];
2589
+ }
2501
2590
  const runStatus = await agent.getRunStatus();
2502
2591
  if (runStatus !== "interrupted") return [];
2503
2592
  const state = await agent.getCurrentState();
@@ -2510,9 +2599,11 @@ async function getInboxItems(request, reply) {
2510
2599
  tenantId: r.tenantId,
2511
2600
  interruptId: i.id,
2512
2601
  interruptValue: i.value,
2602
+ status: r.status,
2513
2603
  startedAt: r.startedAt,
2514
2604
  totalEdges: r.totalEdges,
2515
- completedEdges: r.completedEdges
2605
+ completedEdges: r.completedEdges,
2606
+ steps
2516
2607
  }));
2517
2608
  } catch (err) {
2518
2609
  request.log.warn({ runId: r.id, error: err.message }, "Agent check skipped");
@@ -2758,6 +2849,268 @@ async function replyInboxTask(request, reply) {
2758
2849
  }
2759
2850
  }
2760
2851
 
2852
+ // src/controllers/personal-assistant.ts
2853
+ var import_core14 = require("@axiom-lattice/core");
2854
+ var import_crypto3 = require("crypto");
2855
+ function getWorkspaceId2(request) {
2856
+ return request.headers["x-workspace-id"] || "default";
2857
+ }
2858
+ function getTenantId7(request) {
2859
+ const userTenantId = request.user?.tenantId;
2860
+ if (userTenantId) return userTenantId;
2861
+ return request.headers["x-tenant-id"] || "default";
2862
+ }
2863
+ function getUserId3(request) {
2864
+ const userId = request.user?.id || request.headers["x-user-id"];
2865
+ if (!userId) throw new Error("User ID is required");
2866
+ return userId;
2867
+ }
2868
+ function getLinkStore() {
2869
+ return (0, import_core14.getStoreLattice)("default", "userTenantLink").store;
2870
+ }
2871
+ function getAssistantStore() {
2872
+ return (0, import_core14.getStoreLattice)("default", "assistant").store;
2873
+ }
2874
+ function getProjectStore() {
2875
+ return (0, import_core14.getStoreLattice)("default", "project").store;
2876
+ }
2877
+ async function getLinkMeta(userId, tenantId) {
2878
+ const link = await getLinkStore().getLink(userId, tenantId);
2879
+ return link?.metadata || {};
2880
+ }
2881
+ async function updateLinkMeta(userId, tenantId, meta) {
2882
+ await getLinkStore().updateLink(userId, tenantId, { metadata: meta });
2883
+ }
2884
+ async function createPersonalAssistant(request, reply) {
2885
+ const tenantId = getTenantId7(request);
2886
+ const userId = getUserId3(request);
2887
+ const { name, personality } = request.body;
2888
+ if (!name || !personality) {
2889
+ return reply.status(400).send({ success: false, message: "name and personality are required" });
2890
+ }
2891
+ const store = getAssistantStore();
2892
+ const existing = await store.getByOwner(tenantId, userId);
2893
+ if (existing) {
2894
+ return reply.status(409).send({ success: false, message: "You already have a personal assistant" });
2895
+ }
2896
+ const assistantId = (0, import_crypto3.randomUUID)();
2897
+ const projectStore = getProjectStore();
2898
+ const projectId = (0, import_crypto3.randomUUID)();
2899
+ const wsId = getWorkspaceId2(request);
2900
+ await projectStore.createProject(tenantId, wsId, projectId, {
2901
+ name: `${name}'s Space`,
2902
+ description: "Personal workspace for your assistant"
2903
+ });
2904
+ const config = import_core14.PersonalAssistantConfig.get();
2905
+ config.key = assistantId;
2906
+ import_core14.PersonalAssistantConfig.render(config, name, personality);
2907
+ const data = { name, graphDefinition: config, ownerUserId: userId };
2908
+ const assistant = await store.createAssistant(tenantId, assistantId, data);
2909
+ const meta = await getLinkMeta(userId, tenantId);
2910
+ meta.personalAssistantId = assistantId;
2911
+ meta.personalProjectId = projectId;
2912
+ meta.personalWorkspaceId = wsId;
2913
+ await updateLinkMeta(userId, tenantId, meta);
2914
+ return reply.status(201).send({
2915
+ success: true,
2916
+ message: "Personal assistant created",
2917
+ data: { id: assistant.id, name: assistant.name, projectId, workspaceId: wsId, createdAt: assistant.createdAt }
2918
+ });
2919
+ }
2920
+ async function getPersonalAssistant(request, reply) {
2921
+ const tenantId = getTenantId7(request);
2922
+ const userId = getUserId3(request);
2923
+ const store = getAssistantStore();
2924
+ const assistant = await store.getByOwner(tenantId, userId);
2925
+ if (!assistant) {
2926
+ return reply.status(404).send({ success: false, message: "No personal assistant found" });
2927
+ }
2928
+ const meta = await getLinkMeta(userId, tenantId);
2929
+ const projectId = meta.personalProjectId || "default";
2930
+ const workspaceId = meta.personalWorkspaceId || "default";
2931
+ return {
2932
+ success: true,
2933
+ message: "Personal assistant found",
2934
+ data: { id: assistant.id, name: assistant.name, projectId, workspaceId, createdAt: assistant.createdAt }
2935
+ };
2936
+ }
2937
+ async function deletePersonalAssistant(request, reply) {
2938
+ const tenantId = getTenantId7(request);
2939
+ const userId = getUserId3(request);
2940
+ const store = getAssistantStore();
2941
+ const assistant = await store.getByOwner(tenantId, userId);
2942
+ if (!assistant) {
2943
+ return reply.status(404).send({ success: false, message: "No personal assistant found" });
2944
+ }
2945
+ const deleted = await store.deleteAssistant(tenantId, assistant.id);
2946
+ if (!deleted) {
2947
+ return reply.status(500).send({ success: false, message: "Failed to delete personal assistant" });
2948
+ }
2949
+ const threadStore = (0, import_core14.getStoreLattice)("default", "thread").store;
2950
+ try {
2951
+ const threads = await threadStore.getThreadsByAssistantId(tenantId, assistant.id);
2952
+ for (const t of threads) {
2953
+ await threadStore.deleteThread(tenantId, t.id);
2954
+ }
2955
+ } catch {
2956
+ }
2957
+ const meta = await getLinkMeta(userId, tenantId);
2958
+ const projectId = meta.personalProjectId;
2959
+ const wsId = meta.personalWorkspaceId;
2960
+ if (projectId && wsId) {
2961
+ try {
2962
+ await getProjectStore().deleteProject(tenantId, projectId);
2963
+ } catch {
2964
+ }
2965
+ }
2966
+ delete meta.personalAssistantId;
2967
+ delete meta.personalProjectId;
2968
+ delete meta.personalWorkspaceId;
2969
+ await updateLinkMeta(userId, tenantId, meta);
2970
+ return { success: true, message: "Personal assistant deleted" };
2971
+ }
2972
+
2973
+ // src/controllers/tasks.ts
2974
+ var import_core15 = require("@axiom-lattice/core");
2975
+ function getTenantId8(request) {
2976
+ const userTenantId = request.user?.tenantId;
2977
+ if (userTenantId) return userTenantId;
2978
+ return request.headers["x-tenant-id"] || "default";
2979
+ }
2980
+ function getUserId4(request) {
2981
+ const userId = request.user?.id || request.headers["x-user-id"];
2982
+ if (!userId) throw new Error("User ID is required");
2983
+ return userId;
2984
+ }
2985
+ function getStore() {
2986
+ return (0, import_core15.getStoreLattice)("default", "task").store;
2987
+ }
2988
+ async function listTasks(request, reply) {
2989
+ try {
2990
+ const tenantId = getTenantId8(request);
2991
+ const userId = getUserId4(request);
2992
+ const query = request.query;
2993
+ const store = getStore();
2994
+ const tasks = await store.list({
2995
+ tenantId,
2996
+ ownerId: query.ownerId || userId,
2997
+ status: query.status,
2998
+ priority: query.priority,
2999
+ ownerType: query.ownerType,
3000
+ metadata: query.metadata ? JSON.parse(query.metadata) : void 0,
3001
+ limit: query.limit ? parseInt(query.limit) : void 0,
3002
+ offset: query.offset ? parseInt(query.offset) : void 0
3003
+ });
3004
+ return { success: true, data: tasks, count: tasks.length };
3005
+ } catch (error) {
3006
+ return { success: false, error: error.message };
3007
+ }
3008
+ }
3009
+ async function getTask(request, reply) {
3010
+ try {
3011
+ const tenantId = getTenantId8(request);
3012
+ const userId = getUserId4(request);
3013
+ const { id } = request.params;
3014
+ const store = getStore();
3015
+ const task = await store.getById(tenantId, id);
3016
+ if (!task) {
3017
+ return reply.status(404).send({ success: false, error: "Task not found" });
3018
+ }
3019
+ if (task.ownerType === "user" && task.ownerId !== userId) {
3020
+ return reply.status(403).send({ success: false, error: "Access denied" });
3021
+ }
3022
+ return { success: true, data: task };
3023
+ } catch (error) {
3024
+ return { success: false, error: error.message };
3025
+ }
3026
+ }
3027
+ async function createTask(request, reply) {
3028
+ try {
3029
+ const tenantId = getTenantId8(request);
3030
+ const userId = getUserId4(request);
3031
+ const body = request.body;
3032
+ if (!body.title) {
3033
+ return reply.status(400).send({ success: false, error: "title is required" });
3034
+ }
3035
+ const store = getStore();
3036
+ const task = await store.create({
3037
+ ...body,
3038
+ tenantId,
3039
+ ownerType: body.ownerType || "user",
3040
+ ownerId: body.ownerId || userId
3041
+ });
3042
+ return reply.status(201).send({ success: true, data: task });
3043
+ } catch (error) {
3044
+ return reply.status(500).send({ success: false, error: error.message });
3045
+ }
3046
+ }
3047
+ async function updateTask(request, reply) {
3048
+ try {
3049
+ const tenantId = getTenantId8(request);
3050
+ const userId = getUserId4(request);
3051
+ const { id } = request.params;
3052
+ const store = getStore();
3053
+ const existing = await store.getById(tenantId, id);
3054
+ if (!existing) {
3055
+ return reply.status(404).send({ success: false, error: "Task not found" });
3056
+ }
3057
+ if (existing.ownerType === "user" && existing.ownerId !== userId) {
3058
+ return reply.status(403).send({ success: false, error: "Access denied" });
3059
+ }
3060
+ const task = await store.update(tenantId, id, request.body);
3061
+ if (!task) {
3062
+ return reply.status(404).send({ success: false, error: "Task not found" });
3063
+ }
3064
+ return { success: true, data: task };
3065
+ } catch (error) {
3066
+ return reply.status(500).send({ success: false, error: error.message });
3067
+ }
3068
+ }
3069
+ async function deleteTask(request, reply) {
3070
+ try {
3071
+ const tenantId = getTenantId8(request);
3072
+ const userId = getUserId4(request);
3073
+ const { id } = request.params;
3074
+ const store = getStore();
3075
+ const existing = await store.getById(tenantId, id);
3076
+ if (!existing) {
3077
+ return reply.status(404).send({ success: false, error: "Task not found" });
3078
+ }
3079
+ if (existing.ownerType === "user" && existing.ownerId !== userId) {
3080
+ return reply.status(403).send({ success: false, error: "Access denied" });
3081
+ }
3082
+ const deleted = await store.delete(tenantId, id);
3083
+ if (!deleted) {
3084
+ return reply.status(404).send({ success: false, error: "Task not found" });
3085
+ }
3086
+ return { success: true, message: "Task deleted" };
3087
+ } catch (error) {
3088
+ return reply.status(500).send({ success: false, error: error.message });
3089
+ }
3090
+ }
3091
+ async function completeTask(request, reply) {
3092
+ try {
3093
+ const tenantId = getTenantId8(request);
3094
+ const userId = getUserId4(request);
3095
+ const { id } = request.params;
3096
+ const store = getStore();
3097
+ const existing = await store.getById(tenantId, id);
3098
+ if (!existing) {
3099
+ return reply.status(404).send({ success: false, error: "Task not found" });
3100
+ }
3101
+ if (existing.ownerType === "user" && existing.ownerId !== userId) {
3102
+ return reply.status(403).send({ success: false, error: "Access denied" });
3103
+ }
3104
+ const task = await store.update(tenantId, id, { status: "completed" });
3105
+ if (!task) {
3106
+ return reply.status(404).send({ success: false, error: "Task not found" });
3107
+ }
3108
+ return { success: true, data: task };
3109
+ } catch (error) {
3110
+ return reply.status(500).send({ success: false, error: error.message });
3111
+ }
3112
+ }
3113
+
2761
3114
  // src/schemas/data-query.ts
2762
3115
  var dataQuerySchema = {
2763
3116
  description: "Execute data query (semantic or SQL)",
@@ -3099,7 +3452,7 @@ var getHealthSchema = {
3099
3452
  };
3100
3453
 
3101
3454
  // src/controllers/thread_status.ts
3102
- var import_core14 = require("@axiom-lattice/core");
3455
+ var import_core16 = require("@axiom-lattice/core");
3103
3456
  async function removePendingMessageHandler(request, reply) {
3104
3457
  try {
3105
3458
  const { assistant_id, thread_id, message_id } = request.params;
@@ -3112,7 +3465,7 @@ async function removePendingMessageHandler(request, reply) {
3112
3465
  if (!assistant_id) {
3113
3466
  return reply.code(400).send({ error: "Missing assistant_id parameter" });
3114
3467
  }
3115
- const agent = import_core14.agentInstanceManager.getAgent({
3468
+ const agent = import_core16.agentInstanceManager.getAgent({
3116
3469
  assistant_id,
3117
3470
  thread_id,
3118
3471
  tenant_id,
@@ -3146,7 +3499,7 @@ async function removePendingMessageHandler(request, reply) {
3146
3499
  }
3147
3500
 
3148
3501
  // src/services/sandbox_service.ts
3149
- var import_core15 = require("@axiom-lattice/core");
3502
+ var import_core17 = require("@axiom-lattice/core");
3150
3503
  var ERROR_HTML = `<!DOCTYPE html>
3151
3504
  <html lang="zh-CN">
3152
3505
  <head>
@@ -3258,7 +3611,7 @@ var ERROR_HTML = `<!DOCTYPE html>
3258
3611
  </html>`;
3259
3612
  var SandboxService = class {
3260
3613
  getFilesystemVmIsolation(tenantId, assistantId) {
3261
- const agentLattice = import_core15.agentLatticeManager.getAgentLatticeWithTenant(tenantId, assistantId);
3614
+ const agentLattice = import_core17.agentLatticeManager.getAgentLatticeWithTenant(tenantId, assistantId);
3262
3615
  if (!agentLattice) {
3263
3616
  return null;
3264
3617
  }
@@ -3272,9 +3625,9 @@ var SandboxService = class {
3272
3625
  computeSandboxName(assistantId, threadId, vmIsolation, tenantId, workspaceId, projectId) {
3273
3626
  switch (vmIsolation) {
3274
3627
  case "agent":
3275
- return (0, import_core15.normalizeSandboxName)(`${tenantId ?? "default"}-${assistantId}`);
3628
+ return (0, import_core17.normalizeSandboxName)(`${tenantId ?? "default"}-${assistantId}`);
3276
3629
  case "project":
3277
- return (0, import_core15.normalizeSandboxName)(
3630
+ return (0, import_core17.normalizeSandboxName)(
3278
3631
  `${tenantId ?? "default"}-${workspaceId ?? "default"}-${projectId ?? "default"}`
3279
3632
  );
3280
3633
  case "global":
@@ -3322,15 +3675,15 @@ var SandboxService = class {
3322
3675
  );
3323
3676
  return rewritten;
3324
3677
  }
3325
- generateErrorHtml(assistantId, threadId, vmIsolation, errorMessage) {
3326
- const encodedError = encodeURIComponent(errorMessage);
3327
- return ERROR_HTML.replace("{assistantId}", assistantId).replace("{threadId}", threadId).replace("{vmIsolation}", vmIsolation).replace("{errorMessage}", errorMessage);
3678
+ generateErrorHtml(assistantId, threadId, vmIsolation, errorMessage2) {
3679
+ const encodedError = encodeURIComponent(errorMessage2);
3680
+ return ERROR_HTML.replace("{assistantId}", assistantId).replace("{threadId}", threadId).replace("{vmIsolation}", vmIsolation).replace("{errorMessage}", errorMessage2);
3328
3681
  }
3329
3682
  };
3330
3683
  var sandboxService = new SandboxService();
3331
3684
 
3332
3685
  // src/controllers/sandbox.ts
3333
- var import_core16 = require("@axiom-lattice/core");
3686
+ var import_core18 = require("@axiom-lattice/core");
3334
3687
  function getFilenameFromPath(path3) {
3335
3688
  const segments = path3.replace(/\/+$/, "").split("/");
3336
3689
  return segments[segments.length - 1] || "download";
@@ -3369,7 +3722,7 @@ function registerSandboxProxyRoutes(app2) {
3369
3722
  }
3370
3723
  const workspaceId = request.headers["x-workspace-id"];
3371
3724
  const projectId = request.headers["x-project-id"];
3372
- const sandboxManager = (0, import_core16.getSandBoxManager)();
3725
+ const sandboxManager = (0, import_core18.getSandBoxManager)();
3373
3726
  const sandbox = await sandboxManager.getSandboxFromConfig({
3374
3727
  assistant_id: assistantId,
3375
3728
  thread_id: threadId,
@@ -3417,7 +3770,7 @@ function registerSandboxProxyRoutes(app2) {
3417
3770
  }
3418
3771
  const workspaceId = request.headers["x-workspace-id"];
3419
3772
  const projectId = request.headers["x-project-id"];
3420
- const sandboxManager = (0, import_core16.getSandBoxManager)();
3773
+ const sandboxManager = (0, import_core18.getSandBoxManager)();
3421
3774
  const sandbox = await sandboxManager.getSandboxFromConfig({
3422
3775
  assistant_id: assistantId,
3423
3776
  thread_id: threadId,
@@ -3450,14 +3803,14 @@ function registerSandboxProxyRoutes(app2) {
3450
3803
  // src/controllers/workspace.ts
3451
3804
  var fs = __toESM(require("fs/promises"));
3452
3805
  var path = __toESM(require("path"));
3453
- var import_core17 = require("@axiom-lattice/core");
3454
- var import_core18 = require("@axiom-lattice/core");
3455
3806
  var import_core19 = require("@axiom-lattice/core");
3807
+ var import_core20 = require("@axiom-lattice/core");
3808
+ var import_core21 = require("@axiom-lattice/core");
3456
3809
  var import_uuid2 = require("uuid");
3457
3810
  var WorkspaceController = class {
3458
3811
  constructor() {
3459
- this.workspaceStore = (0, import_core17.getStoreLattice)("default", "workspace").store;
3460
- this.projectStore = (0, import_core17.getStoreLattice)("default", "project").store;
3812
+ this.workspaceStore = (0, import_core19.getStoreLattice)("default", "workspace").store;
3813
+ this.projectStore = (0, import_core19.getStoreLattice)("default", "project").store;
3461
3814
  }
3462
3815
  getTenantId(request) {
3463
3816
  const userTenantId = request.user?.tenantId;
@@ -3590,7 +3943,7 @@ var WorkspaceController = class {
3590
3943
  throw new Error("Workspace not found");
3591
3944
  }
3592
3945
  if (workspace.storageType === "sandbox") {
3593
- const sandboxManager = (0, import_core19.getSandBoxManager)();
3946
+ const sandboxManager = (0, import_core21.getSandBoxManager)();
3594
3947
  const volumeConfig = {
3595
3948
  assistant_id: assistantId || "",
3596
3949
  thread_id: "",
@@ -3604,14 +3957,14 @@ var WorkspaceController = class {
3604
3957
  }
3605
3958
  const sandbox = await sandboxManager.getSandboxFromConfig(volumeConfig);
3606
3959
  return {
3607
- backend: new import_core18.SandboxFilesystem({
3960
+ backend: new import_core20.SandboxFilesystem({
3608
3961
  sandboxInstance: sandbox
3609
3962
  }),
3610
3963
  workspace
3611
3964
  };
3612
3965
  } else {
3613
3966
  return {
3614
- backend: new import_core18.FilesystemBackend({
3967
+ backend: new import_core20.FilesystemBackend({
3615
3968
  rootDir: `/lattice_store/tenants/${tenantId}/workspaces/${workspaceId}/${projectId}`,
3616
3969
  virtualMode: true
3617
3970
  }),
@@ -3689,7 +4042,7 @@ var WorkspaceController = class {
3689
4042
  const { workspace } = await this.getBackend(tenantId, workspaceId, projectId, assistantId);
3690
4043
  const resolvedPath = filePath;
3691
4044
  if (workspace.storageType === "sandbox") {
3692
- const sandboxManager = (0, import_core19.getSandBoxManager)();
4045
+ const sandboxManager = (0, import_core21.getSandBoxManager)();
3693
4046
  const volumeConfig = {
3694
4047
  assistant_id: assistantId || "",
3695
4048
  thread_id: "",
@@ -3739,7 +4092,7 @@ var WorkspaceController = class {
3739
4092
  const { workspace } = await this.getBackend(tenantId, workspaceId, projectId, assistantId);
3740
4093
  const resolvedPath = filePath;
3741
4094
  if (workspace.storageType === "sandbox") {
3742
- const sandboxManager = (0, import_core19.getSandBoxManager)();
4095
+ const sandboxManager = (0, import_core21.getSandBoxManager)();
3743
4096
  const volumeConfig = {
3744
4097
  assistant_id: assistantId || "",
3745
4098
  thread_id: "",
@@ -3873,7 +4226,7 @@ var WorkspaceController = class {
3873
4226
  return reply.status(400).send({ success: false, error: "Invalid path parameter" });
3874
4227
  }
3875
4228
  if (workspace.storageType === "sandbox") {
3876
- const sandboxManager = (0, import_core19.getSandBoxManager)();
4229
+ const sandboxManager = (0, import_core21.getSandBoxManager)();
3877
4230
  const volumeConfig = {
3878
4231
  assistant_id: assistantId || "",
3879
4232
  thread_id: "",
@@ -3981,9 +4334,9 @@ function registerWorkspaceRoutes(app2) {
3981
4334
  }
3982
4335
 
3983
4336
  // src/controllers/database-configs.ts
3984
- var import_core20 = require("@axiom-lattice/core");
3985
- var import_crypto3 = require("crypto");
3986
- function getTenantId7(request) {
4337
+ var import_core22 = require("@axiom-lattice/core");
4338
+ var import_crypto4 = require("crypto");
4339
+ function getTenantId9(request) {
3987
4340
  const userTenantId = request.user?.tenantId;
3988
4341
  if (userTenantId) {
3989
4342
  return userTenantId;
@@ -3991,9 +4344,9 @@ function getTenantId7(request) {
3991
4344
  return request.headers["x-tenant-id"] || "default";
3992
4345
  }
3993
4346
  async function getDatabaseConfigList(request, reply) {
3994
- const tenantId = getTenantId7(request);
4347
+ const tenantId = getTenantId9(request);
3995
4348
  try {
3996
- const storeLattice = (0, import_core20.getStoreLattice)("default", "database");
4349
+ const storeLattice = (0, import_core22.getStoreLattice)("default", "database");
3997
4350
  const store = storeLattice.store;
3998
4351
  const configs = await store.getAllConfigs(tenantId);
3999
4352
  console.log("Backend: getAllConfigs returned:", configs);
@@ -4021,10 +4374,10 @@ async function getDatabaseConfigList(request, reply) {
4021
4374
  }
4022
4375
  }
4023
4376
  async function getDatabaseConfig(request, reply) {
4024
- const tenantId = getTenantId7(request);
4377
+ const tenantId = getTenantId9(request);
4025
4378
  const { key } = request.params;
4026
4379
  try {
4027
- const storeLattice = (0, import_core20.getStoreLattice)("default", "database");
4380
+ const storeLattice = (0, import_core22.getStoreLattice)("default", "database");
4028
4381
  const store = storeLattice.store;
4029
4382
  const config = await store.getConfigByKey(tenantId, key);
4030
4383
  if (!config) {
@@ -4047,10 +4400,10 @@ async function getDatabaseConfig(request, reply) {
4047
4400
  }
4048
4401
  }
4049
4402
  async function createDatabaseConfig(request, reply) {
4050
- const tenantId = getTenantId7(request);
4403
+ const tenantId = getTenantId9(request);
4051
4404
  const body = request.body;
4052
4405
  try {
4053
- const storeLattice = (0, import_core20.getStoreLattice)("default", "database");
4406
+ const storeLattice = (0, import_core22.getStoreLattice)("default", "database");
4054
4407
  const store = storeLattice.store;
4055
4408
  const existing = await store.getConfigByKey(tenantId, body.key);
4056
4409
  if (existing) {
@@ -4060,10 +4413,10 @@ async function createDatabaseConfig(request, reply) {
4060
4413
  message: "Database configuration with this key already exists"
4061
4414
  };
4062
4415
  }
4063
- const id = body.id || (0, import_crypto3.randomUUID)();
4416
+ const id = body.id || (0, import_crypto4.randomUUID)();
4064
4417
  const config = await store.createConfig(tenantId, id, body);
4065
4418
  try {
4066
- import_core20.sqlDatabaseManager.registerDatabase(tenantId, config.key, config.config);
4419
+ import_core22.sqlDatabaseManager.registerDatabase(tenantId, config.key, config.config);
4067
4420
  } catch (error) {
4068
4421
  console.warn("Failed to auto-register database:", error);
4069
4422
  }
@@ -4082,11 +4435,11 @@ async function createDatabaseConfig(request, reply) {
4082
4435
  }
4083
4436
  }
4084
4437
  async function updateDatabaseConfig(request, reply) {
4085
- const tenantId = getTenantId7(request);
4438
+ const tenantId = getTenantId9(request);
4086
4439
  const { key } = request.params;
4087
4440
  const updates = request.body;
4088
4441
  try {
4089
- const storeLattice = (0, import_core20.getStoreLattice)("default", "database");
4442
+ const storeLattice = (0, import_core22.getStoreLattice)("default", "database");
4090
4443
  const store = storeLattice.store;
4091
4444
  const existing = await store.getConfigByKey(tenantId, key);
4092
4445
  if (!existing) {
@@ -4105,7 +4458,7 @@ async function updateDatabaseConfig(request, reply) {
4105
4458
  }
4106
4459
  if (updates.config) {
4107
4460
  try {
4108
- import_core20.sqlDatabaseManager.registerDatabase(tenantId, updated.key, updated.config);
4461
+ import_core22.sqlDatabaseManager.registerDatabase(tenantId, updated.key, updated.config);
4109
4462
  } catch (error) {
4110
4463
  console.warn("Failed to re-register database:", error);
4111
4464
  }
@@ -4124,10 +4477,10 @@ async function updateDatabaseConfig(request, reply) {
4124
4477
  }
4125
4478
  }
4126
4479
  async function deleteDatabaseConfig(request, reply) {
4127
- const tenantId = getTenantId7(request);
4480
+ const tenantId = getTenantId9(request);
4128
4481
  const { keyOrId } = request.params;
4129
4482
  try {
4130
- const storeLattice = (0, import_core20.getStoreLattice)("default", "database");
4483
+ const storeLattice = (0, import_core22.getStoreLattice)("default", "database");
4131
4484
  const store = storeLattice.store;
4132
4485
  console.log("Delete request - keyOrId:", keyOrId);
4133
4486
  let config = await store.getConfigByKey(tenantId, keyOrId);
@@ -4154,8 +4507,8 @@ async function deleteDatabaseConfig(request, reply) {
4154
4507
  };
4155
4508
  }
4156
4509
  try {
4157
- if (import_core20.sqlDatabaseManager.hasDatabase(tenantId, configKey)) {
4158
- await import_core20.sqlDatabaseManager.removeDatabase(tenantId, configKey);
4510
+ if (import_core22.sqlDatabaseManager.hasDatabase(tenantId, configKey)) {
4511
+ await import_core22.sqlDatabaseManager.removeDatabase(tenantId, configKey);
4159
4512
  }
4160
4513
  } catch (error) {
4161
4514
  console.warn("Failed to remove from SqlDatabaseManager:", error);
@@ -4173,10 +4526,10 @@ async function deleteDatabaseConfig(request, reply) {
4173
4526
  }
4174
4527
  }
4175
4528
  async function testDatabaseConnection(request, reply) {
4176
- const tenantId = getTenantId7(request);
4529
+ const tenantId = getTenantId9(request);
4177
4530
  const { key } = request.params;
4178
4531
  try {
4179
- const storeLattice = (0, import_core20.getStoreLattice)("default", "database");
4532
+ const storeLattice = (0, import_core22.getStoreLattice)("default", "database");
4180
4533
  const store = storeLattice.store;
4181
4534
  const config = await store.getConfigByKey(tenantId, key);
4182
4535
  if (!config) {
@@ -4187,16 +4540,16 @@ async function testDatabaseConnection(request, reply) {
4187
4540
  };
4188
4541
  }
4189
4542
  const testKey = `__test_${key}_${Date.now()}`;
4190
- import_core20.sqlDatabaseManager.registerDatabase(tenantId, testKey, config.config);
4543
+ import_core22.sqlDatabaseManager.registerDatabase(tenantId, testKey, config.config);
4191
4544
  const startTime = Date.now();
4192
- const db = await import_core20.sqlDatabaseManager.getDatabase(tenantId, testKey);
4545
+ const db = await import_core22.sqlDatabaseManager.getDatabase(tenantId, testKey);
4193
4546
  try {
4194
4547
  await db.connect();
4195
4548
  await db.listTables();
4196
4549
  const latency = Date.now() - startTime;
4197
4550
  await new Promise((resolve) => setTimeout(resolve, 100));
4198
4551
  await db.disconnect();
4199
- await import_core20.sqlDatabaseManager.removeDatabase(tenantId, testKey);
4552
+ await import_core22.sqlDatabaseManager.removeDatabase(tenantId, testKey);
4200
4553
  return {
4201
4554
  success: true,
4202
4555
  message: "Connection test successful",
@@ -4208,7 +4561,7 @@ async function testDatabaseConnection(request, reply) {
4208
4561
  } catch (error) {
4209
4562
  try {
4210
4563
  await db.disconnect();
4211
- await import_core20.sqlDatabaseManager.removeDatabase(tenantId, testKey);
4564
+ await import_core22.sqlDatabaseManager.removeDatabase(tenantId, testKey);
4212
4565
  } catch {
4213
4566
  }
4214
4567
  return {
@@ -4260,9 +4613,9 @@ function registerDatabaseConfigRoutes(app2) {
4260
4613
  }
4261
4614
 
4262
4615
  // src/controllers/metrics-configs.ts
4263
- var import_core21 = require("@axiom-lattice/core");
4264
- var import_crypto4 = require("crypto");
4265
- function getTenantId8(request) {
4616
+ var import_core23 = require("@axiom-lattice/core");
4617
+ var import_crypto5 = require("crypto");
4618
+ function getTenantId10(request) {
4266
4619
  const userTenantId = request.user?.tenantId;
4267
4620
  if (userTenantId) {
4268
4621
  return userTenantId;
@@ -4270,9 +4623,9 @@ function getTenantId8(request) {
4270
4623
  return request.headers["x-tenant-id"] || "default";
4271
4624
  }
4272
4625
  async function getMetricsServerConfigList(request, reply) {
4273
- const tenantId = getTenantId8(request);
4626
+ const tenantId = getTenantId10(request);
4274
4627
  try {
4275
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4628
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4276
4629
  const store = storeLattice.store;
4277
4630
  const configs = await store.getAllConfigs(tenantId);
4278
4631
  return {
@@ -4296,10 +4649,10 @@ async function getMetricsServerConfigList(request, reply) {
4296
4649
  }
4297
4650
  }
4298
4651
  async function getMetricsServerConfig(request, reply) {
4299
- const tenantId = getTenantId8(request);
4652
+ const tenantId = getTenantId10(request);
4300
4653
  const { key } = request.params;
4301
4654
  try {
4302
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4655
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4303
4656
  const store = storeLattice.store;
4304
4657
  const config = await store.getConfigByKey(tenantId, key);
4305
4658
  if (!config) {
@@ -4322,10 +4675,10 @@ async function getMetricsServerConfig(request, reply) {
4322
4675
  }
4323
4676
  }
4324
4677
  async function createMetricsServerConfig(request, reply) {
4325
- const tenantId = getTenantId8(request);
4678
+ const tenantId = getTenantId10(request);
4326
4679
  const body = request.body;
4327
4680
  try {
4328
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4681
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4329
4682
  const store = storeLattice.store;
4330
4683
  const existing = await store.getConfigByKey(tenantId, body.key);
4331
4684
  if (existing) {
@@ -4342,7 +4695,7 @@ async function createMetricsServerConfig(request, reply) {
4342
4695
  message: "selectedDataSources is required for semantic metrics servers"
4343
4696
  };
4344
4697
  }
4345
- const id = body.id || (0, import_crypto4.randomUUID)();
4698
+ const id = body.id || (0, import_crypto5.randomUUID)();
4346
4699
  const configData = {
4347
4700
  key: body.key,
4348
4701
  name: body.name,
@@ -4354,7 +4707,7 @@ async function createMetricsServerConfig(request, reply) {
4354
4707
  };
4355
4708
  const config = await store.createConfig(tenantId, id, configData);
4356
4709
  try {
4357
- import_core21.metricsServerManager.registerServer(tenantId, config.key, config.config);
4710
+ import_core23.metricsServerManager.registerServer(tenantId, config.key, config.config);
4358
4711
  } catch (error) {
4359
4712
  console.warn("Failed to auto-register metrics server:", error);
4360
4713
  }
@@ -4373,11 +4726,11 @@ async function createMetricsServerConfig(request, reply) {
4373
4726
  }
4374
4727
  }
4375
4728
  async function updateMetricsServerConfig(request, reply) {
4376
- const tenantId = getTenantId8(request);
4729
+ const tenantId = getTenantId10(request);
4377
4730
  const { key } = request.params;
4378
4731
  const updates = request.body;
4379
4732
  try {
4380
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4733
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4381
4734
  const store = storeLattice.store;
4382
4735
  const existing = await store.getConfigByKey(tenantId, key);
4383
4736
  if (!existing) {
@@ -4405,7 +4758,7 @@ async function updateMetricsServerConfig(request, reply) {
4405
4758
  }
4406
4759
  if (updates.config) {
4407
4760
  try {
4408
- import_core21.metricsServerManager.registerServer(tenantId, updated.key, updated.config);
4761
+ import_core23.metricsServerManager.registerServer(tenantId, updated.key, updated.config);
4409
4762
  } catch (error) {
4410
4763
  console.warn("Failed to re-register metrics server:", error);
4411
4764
  }
@@ -4424,10 +4777,10 @@ async function updateMetricsServerConfig(request, reply) {
4424
4777
  }
4425
4778
  }
4426
4779
  async function deleteMetricsServerConfig(request, reply) {
4427
- const tenantId = getTenantId8(request);
4780
+ const tenantId = getTenantId10(request);
4428
4781
  const { keyOrId } = request.params;
4429
4782
  try {
4430
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4783
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4431
4784
  const store = storeLattice.store;
4432
4785
  let config = await store.getConfigByKey(tenantId, keyOrId);
4433
4786
  let configKey = keyOrId;
@@ -4452,8 +4805,8 @@ async function deleteMetricsServerConfig(request, reply) {
4452
4805
  };
4453
4806
  }
4454
4807
  try {
4455
- if (import_core21.metricsServerManager.hasServer(tenantId, configKey)) {
4456
- import_core21.metricsServerManager.removeServer(tenantId, configKey);
4808
+ if (import_core23.metricsServerManager.hasServer(tenantId, configKey)) {
4809
+ import_core23.metricsServerManager.removeServer(tenantId, configKey);
4457
4810
  }
4458
4811
  } catch (error) {
4459
4812
  console.warn("Failed to remove from MetricsServerManager:", error);
@@ -4471,10 +4824,10 @@ async function deleteMetricsServerConfig(request, reply) {
4471
4824
  }
4472
4825
  }
4473
4826
  async function testMetricsServerConnection(request, reply) {
4474
- const tenantId = getTenantId8(request);
4827
+ const tenantId = getTenantId10(request);
4475
4828
  const { key } = request.params;
4476
4829
  try {
4477
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4830
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4478
4831
  const store = storeLattice.store;
4479
4832
  const config = await store.getConfigByKey(tenantId, key);
4480
4833
  if (!config) {
@@ -4485,11 +4838,11 @@ async function testMetricsServerConnection(request, reply) {
4485
4838
  };
4486
4839
  }
4487
4840
  const testKey = `__test_${key}_${Date.now()}`;
4488
- import_core21.metricsServerManager.registerServer(tenantId, testKey, config.config);
4841
+ import_core23.metricsServerManager.registerServer(tenantId, testKey, config.config);
4489
4842
  try {
4490
- const client = await import_core21.metricsServerManager.getClient(tenantId, testKey);
4843
+ const client = await import_core23.metricsServerManager.getClient(tenantId, testKey);
4491
4844
  const result = await client.testConnection();
4492
- import_core21.metricsServerManager.removeServer(tenantId, testKey);
4845
+ import_core23.metricsServerManager.removeServer(tenantId, testKey);
4493
4846
  return {
4494
4847
  success: true,
4495
4848
  message: result.connected ? "Connection test successful" : "Connection test failed",
@@ -4497,7 +4850,7 @@ async function testMetricsServerConnection(request, reply) {
4497
4850
  };
4498
4851
  } catch (error) {
4499
4852
  try {
4500
- import_core21.metricsServerManager.removeServer(tenantId, testKey);
4853
+ import_core23.metricsServerManager.removeServer(tenantId, testKey);
4501
4854
  } catch {
4502
4855
  }
4503
4856
  return {
@@ -4522,10 +4875,10 @@ async function testMetricsServerConnection(request, reply) {
4522
4875
  }
4523
4876
  }
4524
4877
  async function listAvailableMetrics(request, reply) {
4525
- const tenantId = getTenantId8(request);
4878
+ const tenantId = getTenantId10(request);
4526
4879
  const { key } = request.params;
4527
4880
  try {
4528
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4881
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4529
4882
  const store = storeLattice.store;
4530
4883
  const config = await store.getConfigByKey(tenantId, key);
4531
4884
  if (!config) {
@@ -4535,10 +4888,10 @@ async function listAvailableMetrics(request, reply) {
4535
4888
  message: "Metrics server configuration not found"
4536
4889
  };
4537
4890
  }
4538
- if (!import_core21.metricsServerManager.hasServer(tenantId, key)) {
4539
- import_core21.metricsServerManager.registerServer(tenantId, key, config.config);
4891
+ if (!import_core23.metricsServerManager.hasServer(tenantId, key)) {
4892
+ import_core23.metricsServerManager.registerServer(tenantId, key, config.config);
4540
4893
  }
4541
- const client = await import_core21.metricsServerManager.getClient(tenantId, key);
4894
+ const client = await import_core23.metricsServerManager.getClient(tenantId, key);
4542
4895
  const metrics = await client.listMetrics();
4543
4896
  return {
4544
4897
  success: true,
@@ -4560,11 +4913,11 @@ async function listAvailableMetrics(request, reply) {
4560
4913
  }
4561
4914
  }
4562
4915
  async function queryMetricsData(request, reply) {
4563
- const tenantId = getTenantId8(request);
4916
+ const tenantId = getTenantId10(request);
4564
4917
  const { key } = request.params;
4565
4918
  const { metricName, startTime, endTime, step, labels } = request.body;
4566
4919
  try {
4567
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4920
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4568
4921
  const store = storeLattice.store;
4569
4922
  const config = await store.getConfigByKey(tenantId, key);
4570
4923
  if (!config) {
@@ -4581,10 +4934,10 @@ async function queryMetricsData(request, reply) {
4581
4934
  message: "metricName is required"
4582
4935
  };
4583
4936
  }
4584
- if (!import_core21.metricsServerManager.hasServer(tenantId, key)) {
4585
- import_core21.metricsServerManager.registerServer(tenantId, key, config.config);
4937
+ if (!import_core23.metricsServerManager.hasServer(tenantId, key)) {
4938
+ import_core23.metricsServerManager.registerServer(tenantId, key, config.config);
4586
4939
  }
4587
- const client = await import_core21.metricsServerManager.getClient(tenantId, key);
4940
+ const client = await import_core23.metricsServerManager.getClient(tenantId, key);
4588
4941
  const result = await client.queryMetricData(metricName, {
4589
4942
  startTime,
4590
4943
  endTime,
@@ -4608,10 +4961,10 @@ async function queryMetricsData(request, reply) {
4608
4961
  }
4609
4962
  }
4610
4963
  async function getDataSources(request, reply) {
4611
- const tenantId = getTenantId8(request);
4964
+ const tenantId = getTenantId10(request);
4612
4965
  const { key } = request.params;
4613
4966
  try {
4614
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
4967
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4615
4968
  const store = storeLattice.store;
4616
4969
  const config = await store.getConfigByKey(tenantId, key);
4617
4970
  if (!config) {
@@ -4629,7 +4982,7 @@ async function getDataSources(request, reply) {
4629
4982
  };
4630
4983
  }
4631
4984
  const semanticConfig = config.config;
4632
- const client = new import_core21.SemanticMetricsClient(semanticConfig);
4985
+ const client = new import_core23.SemanticMetricsClient(semanticConfig);
4633
4986
  const allDatasources = await client.getDataSources();
4634
4987
  const selectedIds = semanticConfig.selectedDataSources || [];
4635
4988
  const filteredDatasources = selectedIds.length > 0 ? allDatasources.filter((ds) => selectedIds.includes(String(ds.id))) : allDatasources;
@@ -4649,10 +5002,10 @@ async function getDataSources(request, reply) {
4649
5002
  }
4650
5003
  }
4651
5004
  async function getDatasourceMetrics(request, reply) {
4652
- const tenantId = getTenantId8(request);
5005
+ const tenantId = getTenantId10(request);
4653
5006
  const { key, datasourceId } = request.params;
4654
5007
  try {
4655
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
5008
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4656
5009
  const store = storeLattice.store;
4657
5010
  const config = await store.getConfigByKey(tenantId, key);
4658
5011
  if (!config) {
@@ -4670,7 +5023,7 @@ async function getDatasourceMetrics(request, reply) {
4670
5023
  };
4671
5024
  }
4672
5025
  const semanticConfig = config.config;
4673
- const client = new import_core21.SemanticMetricsClient(semanticConfig);
5026
+ const client = new import_core23.SemanticMetricsClient(semanticConfig);
4674
5027
  const metrics = await client.getDatasourceMetrics(datasourceId);
4675
5028
  return {
4676
5029
  success: true,
@@ -4686,11 +5039,11 @@ async function getDatasourceMetrics(request, reply) {
4686
5039
  }
4687
5040
  }
4688
5041
  async function querySemanticMetrics(request, reply) {
4689
- const tenantId = getTenantId8(request);
5042
+ const tenantId = getTenantId10(request);
4690
5043
  const { key } = request.params;
4691
5044
  const body = request.body;
4692
5045
  try {
4693
- const storeLattice = (0, import_core21.getStoreLattice)("default", "metrics");
5046
+ const storeLattice = (0, import_core23.getStoreLattice)("default", "metrics");
4694
5047
  const store = storeLattice.store;
4695
5048
  const config = await store.getConfigByKey(tenantId, key);
4696
5049
  if (!config) {
@@ -4715,7 +5068,7 @@ async function querySemanticMetrics(request, reply) {
4715
5068
  };
4716
5069
  }
4717
5070
  const semanticConfig = config.config;
4718
- const client = new import_core21.SemanticMetricsClient(semanticConfig);
5071
+ const client = new import_core23.SemanticMetricsClient(semanticConfig);
4719
5072
  const result = await client.semanticQuery(body);
4720
5073
  const columnNames = result.columns.map((col) => col.name);
4721
5074
  const allDataPoints = [];
@@ -4775,7 +5128,7 @@ async function testSemanticDataSources(request, reply) {
4775
5128
  password: body.password,
4776
5129
  headers: body.headers
4777
5130
  };
4778
- const client = new import_core21.SemanticMetricsClient(testConfig);
5131
+ const client = new import_core23.SemanticMetricsClient(testConfig);
4779
5132
  const datasources = await client.getDataSources();
4780
5133
  return {
4781
5134
  success: true,
@@ -4811,7 +5164,7 @@ async function testDatasourceMetrics(request, reply) {
4811
5164
  password: body.password,
4812
5165
  headers: body.headers
4813
5166
  };
4814
- const client = new import_core21.SemanticMetricsClient(testConfig);
5167
+ const client = new import_core23.SemanticMetricsClient(testConfig);
4815
5168
  const metrics = await client.getDatasourceMetrics(datasourceId);
4816
5169
  return {
4817
5170
  success: true,
@@ -4843,9 +5196,9 @@ function registerMetricsServerConfigRoutes(app2) {
4843
5196
  }
4844
5197
 
4845
5198
  // src/controllers/mcp-configs.ts
4846
- var import_core22 = require("@axiom-lattice/core");
4847
- var import_crypto5 = require("crypto");
4848
- function getTenantId9(request) {
5199
+ var import_core24 = require("@axiom-lattice/core");
5200
+ var import_crypto6 = require("crypto");
5201
+ function getTenantId11(request) {
4849
5202
  const userTenantId = request.user?.tenantId;
4850
5203
  if (userTenantId) {
4851
5204
  return userTenantId;
@@ -4853,9 +5206,9 @@ function getTenantId9(request) {
4853
5206
  return request.headers["x-tenant-id"] || "default";
4854
5207
  }
4855
5208
  async function getMcpServerConfigList(request, reply) {
4856
- const tenantId = getTenantId9(request);
5209
+ const tenantId = getTenantId11(request);
4857
5210
  try {
4858
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5211
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
4859
5212
  const store = storeLattice.store;
4860
5213
  const configs = await store.getAllConfigs(tenantId);
4861
5214
  return {
@@ -4879,10 +5232,10 @@ async function getMcpServerConfigList(request, reply) {
4879
5232
  }
4880
5233
  }
4881
5234
  async function getMcpServerConfig(request, reply) {
4882
- const tenantId = getTenantId9(request);
5235
+ const tenantId = getTenantId11(request);
4883
5236
  const { key } = request.params;
4884
5237
  try {
4885
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5238
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
4886
5239
  const store = storeLattice.store;
4887
5240
  const config = await store.getConfigByKey(tenantId, key);
4888
5241
  if (!config) {
@@ -4905,10 +5258,10 @@ async function getMcpServerConfig(request, reply) {
4905
5258
  }
4906
5259
  }
4907
5260
  async function createMcpServerConfig(request, reply) {
4908
- const tenantId = getTenantId9(request);
5261
+ const tenantId = getTenantId11(request);
4909
5262
  const body = request.body;
4910
5263
  try {
4911
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5264
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
4912
5265
  const store = storeLattice.store;
4913
5266
  const existing = await store.getConfigByKey(tenantId, body.key);
4914
5267
  if (existing) {
@@ -4918,7 +5271,7 @@ async function createMcpServerConfig(request, reply) {
4918
5271
  message: "MCP server configuration with this key already exists"
4919
5272
  };
4920
5273
  }
4921
- const id = body.id || (0, import_crypto5.randomUUID)();
5274
+ const id = body.id || (0, import_crypto6.randomUUID)();
4922
5275
  const config = await store.createConfig(tenantId, id, body);
4923
5276
  try {
4924
5277
  await connectAndRegisterTools(config);
@@ -4944,11 +5297,11 @@ async function createMcpServerConfig(request, reply) {
4944
5297
  }
4945
5298
  }
4946
5299
  async function updateMcpServerConfig(request, reply) {
4947
- const tenantId = getTenantId9(request);
5300
+ const tenantId = getTenantId11(request);
4948
5301
  const { key } = request.params;
4949
5302
  const updates = request.body;
4950
5303
  try {
4951
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5304
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
4952
5305
  const store = storeLattice.store;
4953
5306
  const existing = await store.getConfigByKey(tenantId, key);
4954
5307
  if (!existing) {
@@ -4968,8 +5321,8 @@ async function updateMcpServerConfig(request, reply) {
4968
5321
  }
4969
5322
  if (shouldReconnect) {
4970
5323
  try {
4971
- if (import_core22.mcpManager.hasServer(key)) {
4972
- await import_core22.mcpManager.removeServer(key);
5324
+ if (import_core24.mcpManager.hasServer(key)) {
5325
+ await import_core24.mcpManager.removeServer(key);
4973
5326
  }
4974
5327
  await connectAndRegisterTools(updated);
4975
5328
  await store.updateConfig(tenantId, existing.id, { status: "connected" });
@@ -4994,10 +5347,10 @@ async function updateMcpServerConfig(request, reply) {
4994
5347
  }
4995
5348
  }
4996
5349
  async function deleteMcpServerConfig(request, reply) {
4997
- const tenantId = getTenantId9(request);
5350
+ const tenantId = getTenantId11(request);
4998
5351
  const { keyOrId } = request.params;
4999
5352
  try {
5000
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5353
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
5001
5354
  const store = storeLattice.store;
5002
5355
  let config = await store.getConfigByKey(tenantId, keyOrId);
5003
5356
  let configKey = keyOrId;
@@ -5015,8 +5368,8 @@ async function deleteMcpServerConfig(request, reply) {
5015
5368
  };
5016
5369
  }
5017
5370
  try {
5018
- if (import_core22.mcpManager.hasServer(configKey)) {
5019
- await import_core22.mcpManager.removeServer(configKey);
5371
+ if (import_core24.mcpManager.hasServer(configKey)) {
5372
+ await import_core24.mcpManager.removeServer(configKey);
5020
5373
  }
5021
5374
  } catch (error) {
5022
5375
  console.warn("Failed to remove from MCP manager:", error);
@@ -5041,10 +5394,10 @@ async function deleteMcpServerConfig(request, reply) {
5041
5394
  }
5042
5395
  }
5043
5396
  async function testMcpServerConnection(request, reply) {
5044
- const tenantId = getTenantId9(request);
5397
+ const tenantId = getTenantId11(request);
5045
5398
  const { key } = request.params;
5046
5399
  try {
5047
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5400
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
5048
5401
  const store = storeLattice.store;
5049
5402
  const config = await store.getConfigByKey(tenantId, key);
5050
5403
  if (!config) {
@@ -5058,11 +5411,11 @@ async function testMcpServerConnection(request, reply) {
5058
5411
  try {
5059
5412
  const testKey = `__test_${key}_${Date.now()}`;
5060
5413
  const connection = convertToConnection(config.config);
5061
- import_core22.mcpManager.addServer(testKey, connection);
5062
- await import_core22.mcpManager.connect();
5063
- const tools = await import_core22.mcpManager.getAllTools();
5414
+ import_core24.mcpManager.addServer(testKey, connection);
5415
+ await import_core24.mcpManager.connect();
5416
+ const tools = await import_core24.mcpManager.getAllTools();
5064
5417
  const latency = Date.now() - startTime;
5065
- await import_core22.mcpManager.removeServer(testKey);
5418
+ await import_core24.mcpManager.removeServer(testKey);
5066
5419
  return {
5067
5420
  success: true,
5068
5421
  message: "Connection test successful",
@@ -5094,10 +5447,10 @@ async function testMcpServerConnection(request, reply) {
5094
5447
  }
5095
5448
  }
5096
5449
  async function listMcpServerTools(request, reply) {
5097
- const tenantId = getTenantId9(request);
5450
+ const tenantId = getTenantId11(request);
5098
5451
  const { key } = request.params;
5099
5452
  try {
5100
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5453
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
5101
5454
  const store = storeLattice.store;
5102
5455
  const config = await store.getConfigByKey(tenantId, key);
5103
5456
  if (!config) {
@@ -5107,10 +5460,10 @@ async function listMcpServerTools(request, reply) {
5107
5460
  message: "MCP server configuration not found"
5108
5461
  };
5109
5462
  }
5110
- if (!import_core22.mcpManager.hasServer(key)) {
5463
+ if (!import_core24.mcpManager.hasServer(key)) {
5111
5464
  await connectAndRegisterTools(config);
5112
5465
  }
5113
- const tools = await import_core22.mcpManager.getAllTools();
5466
+ const tools = await import_core24.mcpManager.getAllTools();
5114
5467
  return {
5115
5468
  success: true,
5116
5469
  message: "Tools retrieved successfully",
@@ -5127,10 +5480,10 @@ async function listMcpServerTools(request, reply) {
5127
5480
  }
5128
5481
  }
5129
5482
  async function connectMcpServer(request, reply) {
5130
- const tenantId = getTenantId9(request);
5483
+ const tenantId = getTenantId11(request);
5131
5484
  const { key } = request.params;
5132
5485
  try {
5133
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5486
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
5134
5487
  const store = storeLattice.store;
5135
5488
  const config = await store.getConfigByKey(tenantId, key);
5136
5489
  if (!config) {
@@ -5151,7 +5504,7 @@ async function connectMcpServer(request, reply) {
5151
5504
  };
5152
5505
  } catch (error) {
5153
5506
  console.error("Failed to connect MCP server:", error);
5154
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5507
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
5155
5508
  const store = storeLattice.store;
5156
5509
  const config = await store.getConfigByKey(tenantId, key);
5157
5510
  if (config) {
@@ -5164,10 +5517,10 @@ async function connectMcpServer(request, reply) {
5164
5517
  }
5165
5518
  }
5166
5519
  async function disconnectMcpServer(request, reply) {
5167
- const tenantId = getTenantId9(request);
5520
+ const tenantId = getTenantId11(request);
5168
5521
  const { key } = request.params;
5169
5522
  try {
5170
- const storeLattice = (0, import_core22.getStoreLattice)("default", "mcp");
5523
+ const storeLattice = (0, import_core24.getStoreLattice)("default", "mcp");
5171
5524
  const store = storeLattice.store;
5172
5525
  const config = await store.getConfigByKey(tenantId, key);
5173
5526
  if (!config) {
@@ -5177,8 +5530,8 @@ async function disconnectMcpServer(request, reply) {
5177
5530
  message: "MCP server configuration not found"
5178
5531
  };
5179
5532
  }
5180
- if (import_core22.mcpManager.hasServer(key)) {
5181
- await import_core22.mcpManager.removeServer(key);
5533
+ if (import_core24.mcpManager.hasServer(key)) {
5534
+ await import_core24.mcpManager.removeServer(key);
5182
5535
  }
5183
5536
  const updated = await store.updateConfig(tenantId, config.id, {
5184
5537
  status: "disconnected"
@@ -5208,10 +5561,10 @@ async function testMcpServerTools(request, reply) {
5208
5561
  }
5209
5562
  const testKey = `__test_${Date.now()}`;
5210
5563
  const connection = convertToConnection(body.config);
5211
- import_core22.mcpManager.addServer(testKey, connection);
5212
- await import_core22.mcpManager.connect();
5213
- const tools = await import_core22.mcpManager.getAllTools();
5214
- await import_core22.mcpManager.removeServer(testKey);
5564
+ import_core24.mcpManager.addServer(testKey, connection);
5565
+ await import_core24.mcpManager.connect();
5566
+ const tools = await import_core24.mcpManager.getAllTools();
5567
+ await import_core24.mcpManager.removeServer(testKey);
5215
5568
  return {
5216
5569
  success: true,
5217
5570
  message: "Tools retrieved successfully",
@@ -5248,14 +5601,14 @@ function convertToConnection(config) {
5248
5601
  }
5249
5602
  async function connectAndRegisterTools(config) {
5250
5603
  const connection = convertToConnection(config.config);
5251
- import_core22.mcpManager.addServer(config.key, connection);
5252
- await import_core22.mcpManager.connect();
5253
- const allTools = await import_core22.mcpManager.getAllTools();
5604
+ import_core24.mcpManager.addServer(config.key, connection);
5605
+ await import_core24.mcpManager.connect();
5606
+ const allTools = await import_core24.mcpManager.getAllTools();
5254
5607
  const selectedTools = allTools.filter(
5255
5608
  (tool) => config.selectedTools.includes(tool.name)
5256
5609
  );
5257
5610
  for (const tool of selectedTools) {
5258
- import_core22.toolLatticeManager.registerExistingTool(tool.name, tool);
5611
+ import_core24.toolLatticeManager.registerExistingTool(tool.name, tool);
5259
5612
  }
5260
5613
  }
5261
5614
  function registerMcpServerConfigRoutes(app2) {
@@ -5272,12 +5625,12 @@ function registerMcpServerConfigRoutes(app2) {
5272
5625
  }
5273
5626
 
5274
5627
  // src/controllers/eval.ts
5275
- var import_core24 = require("@axiom-lattice/core");
5628
+ var import_core26 = require("@axiom-lattice/core");
5276
5629
  var import_uuid4 = require("uuid");
5277
5630
 
5278
5631
  // src/services/eval-runner.ts
5279
5632
  var import_events = require("events");
5280
- var import_core23 = require("@axiom-lattice/core");
5633
+ var import_core25 = require("@axiom-lattice/core");
5281
5634
  var import_agent_eval = require("@axiom-lattice/agent-eval");
5282
5635
  var import_uuid3 = require("uuid");
5283
5636
  function mapLogs(logs) {
@@ -5339,7 +5692,7 @@ var EvalRunner = class {
5339
5692
  if (hasModelKey) {
5340
5693
  judgeModelConfig = { modelKey: judgeCfg.modelKey };
5341
5694
  } else if (!hasCredentials) {
5342
- const firstModel = import_core23.modelLatticeManager.getAllLattices()[0];
5695
+ const firstModel = import_core25.modelLatticeManager.getAllLattices()[0];
5343
5696
  if (firstModel) {
5344
5697
  judgeModelConfig = { modelKey: firstModel.key };
5345
5698
  } else {
@@ -5450,13 +5803,13 @@ var EvalRunner = class {
5450
5803
  return this.runs.has(runId);
5451
5804
  }
5452
5805
  getEvalStore() {
5453
- return (0, import_core23.getStoreLattice)("default", "eval").store;
5806
+ return (0, import_core25.getStoreLattice)("default", "eval").store;
5454
5807
  }
5455
5808
  };
5456
5809
  var evalRunner = new EvalRunner();
5457
5810
 
5458
5811
  // src/controllers/eval.ts
5459
- function getTenantId10(request) {
5812
+ function getTenantId12(request) {
5460
5813
  const userTenantId = request.user?.tenantId;
5461
5814
  if (userTenantId) {
5462
5815
  return userTenantId;
@@ -5464,11 +5817,11 @@ function getTenantId10(request) {
5464
5817
  return request.headers["x-tenant-id"] || "default";
5465
5818
  }
5466
5819
  function getEvalStore() {
5467
- return (0, import_core24.getStoreLattice)("default", "eval").store;
5820
+ return (0, import_core26.getStoreLattice)("default", "eval").store;
5468
5821
  }
5469
5822
  async function createProject(request, reply) {
5470
5823
  try {
5471
- const tenantId = getTenantId10(request);
5824
+ const tenantId = getTenantId12(request);
5472
5825
  const store = getEvalStore();
5473
5826
  const id = (0, import_uuid4.v4)();
5474
5827
  const data = request.body;
@@ -5493,7 +5846,7 @@ async function createProject(request, reply) {
5493
5846
  }
5494
5847
  async function listProjects(request, reply) {
5495
5848
  try {
5496
- const tenantId = getTenantId10(request);
5849
+ const tenantId = getTenantId12(request);
5497
5850
  const store = getEvalStore();
5498
5851
  let projects = await store.getProjectsByTenant(tenantId);
5499
5852
  if (projects.length === 0) {
@@ -5527,7 +5880,7 @@ async function listProjects(request, reply) {
5527
5880
  }
5528
5881
  async function getProject(request, reply) {
5529
5882
  try {
5530
- const tenantId = getTenantId10(request);
5883
+ const tenantId = getTenantId12(request);
5531
5884
  const store = getEvalStore();
5532
5885
  const { pid } = request.params;
5533
5886
  const project = await store.getProjectById(tenantId, pid);
@@ -5547,7 +5900,7 @@ async function getProject(request, reply) {
5547
5900
  }
5548
5901
  async function updateProject(request, reply) {
5549
5902
  try {
5550
- const tenantId = getTenantId10(request);
5903
+ const tenantId = getTenantId12(request);
5551
5904
  const store = getEvalStore();
5552
5905
  const { pid } = request.params;
5553
5906
  const existing = await store.getProjectById(tenantId, pid);
@@ -5567,7 +5920,7 @@ async function updateProject(request, reply) {
5567
5920
  }
5568
5921
  async function deleteProject(request, reply) {
5569
5922
  try {
5570
- const tenantId = getTenantId10(request);
5923
+ const tenantId = getTenantId12(request);
5571
5924
  const store = getEvalStore();
5572
5925
  const { pid } = request.params;
5573
5926
  const existing = await store.getProjectById(tenantId, pid);
@@ -5586,7 +5939,7 @@ async function deleteProject(request, reply) {
5586
5939
  }
5587
5940
  async function createSuite(request, reply) {
5588
5941
  try {
5589
- const tenantId = getTenantId10(request);
5942
+ const tenantId = getTenantId12(request);
5590
5943
  const store = getEvalStore();
5591
5944
  const { pid } = request.params;
5592
5945
  const project = await store.getProjectById(tenantId, pid);
@@ -5608,7 +5961,7 @@ async function createSuite(request, reply) {
5608
5961
  }
5609
5962
  async function updateSuite(request, reply) {
5610
5963
  try {
5611
- const tenantId = getTenantId10(request);
5964
+ const tenantId = getTenantId12(request);
5612
5965
  const store = getEvalStore();
5613
5966
  const { sid } = request.params;
5614
5967
  const existing = await store.getSuiteById(tenantId, sid);
@@ -5628,7 +5981,7 @@ async function updateSuite(request, reply) {
5628
5981
  }
5629
5982
  async function deleteSuite(request, reply) {
5630
5983
  try {
5631
- const tenantId = getTenantId10(request);
5984
+ const tenantId = getTenantId12(request);
5632
5985
  const store = getEvalStore();
5633
5986
  const { sid } = request.params;
5634
5987
  const existing = await store.getSuiteById(tenantId, sid);
@@ -5647,7 +6000,7 @@ async function deleteSuite(request, reply) {
5647
6000
  }
5648
6001
  async function createCase(request, reply) {
5649
6002
  try {
5650
- const tenantId = getTenantId10(request);
6003
+ const tenantId = getTenantId12(request);
5651
6004
  const store = getEvalStore();
5652
6005
  const { sid } = request.params;
5653
6006
  const suite = await store.getSuiteById(tenantId, sid);
@@ -5676,7 +6029,7 @@ async function createCase(request, reply) {
5676
6029
  }
5677
6030
  async function listCasesForSuite(request, reply) {
5678
6031
  try {
5679
- const tenantId = getTenantId10(request);
6032
+ const tenantId = getTenantId12(request);
5680
6033
  const store = getEvalStore();
5681
6034
  const { sid } = request.params;
5682
6035
  const cases = await store.getCasesBySuite(tenantId, sid);
@@ -5692,7 +6045,7 @@ async function listCasesForSuite(request, reply) {
5692
6045
  }
5693
6046
  async function updateCase(request, reply) {
5694
6047
  try {
5695
- const tenantId = getTenantId10(request);
6048
+ const tenantId = getTenantId12(request);
5696
6049
  const store = getEvalStore();
5697
6050
  const { cid } = request.params;
5698
6051
  const existing = await store.getCaseById(tenantId, cid);
@@ -5712,7 +6065,7 @@ async function updateCase(request, reply) {
5712
6065
  }
5713
6066
  async function deleteCase(request, reply) {
5714
6067
  try {
5715
- const tenantId = getTenantId10(request);
6068
+ const tenantId = getTenantId12(request);
5716
6069
  const store = getEvalStore();
5717
6070
  const { cid } = request.params;
5718
6071
  const existing = await store.getCaseById(tenantId, cid);
@@ -5744,7 +6097,7 @@ function registerEvalRoutes(app2) {
5744
6097
  app2.delete("/api/eval/projects/:pid/suites/:sid/cases/:cid", deleteCase);
5745
6098
  app2.post("/api/eval/projects/:pid/runs", async (request, reply) => {
5746
6099
  try {
5747
- const tenantId = getTenantId10(request);
6100
+ const tenantId = getTenantId12(request);
5748
6101
  const { pid } = request.params;
5749
6102
  const runId = await evalRunner.startRun(tenantId, pid);
5750
6103
  reply.status(202).send({ success: true, message: "Run started", data: { run_id: runId } });
@@ -5756,7 +6109,7 @@ function registerEvalRoutes(app2) {
5756
6109
  });
5757
6110
  app2.get("/api/eval/runs", async (request, reply) => {
5758
6111
  try {
5759
- const tenantId = getTenantId10(request);
6112
+ const tenantId = getTenantId12(request);
5760
6113
  const query = request.query;
5761
6114
  const runs = await getEvalStore().getRunsByTenant(tenantId, { projectId: query.project_id, status: query.status });
5762
6115
  reply.send({ success: true, message: "Ok", data: { records: runs, total: runs.length } });
@@ -5766,7 +6119,7 @@ function registerEvalRoutes(app2) {
5766
6119
  });
5767
6120
  app2.get("/api/eval/runs/:rid", async (request, reply) => {
5768
6121
  try {
5769
- const tenantId = getTenantId10(request);
6122
+ const tenantId = getTenantId12(request);
5770
6123
  const { rid } = request.params;
5771
6124
  const run = await getEvalStore().getRunById(tenantId, rid);
5772
6125
  if (!run) return reply.status(404).send({ success: false, message: "Run not found" });
@@ -5788,7 +6141,7 @@ function registerEvalRoutes(app2) {
5788
6141
  const emitter = evalRunner.getEventEmitter();
5789
6142
  const eventKey = `run:${rid}`;
5790
6143
  if (!evalRunner.isRunning(rid)) {
5791
- const tenantId = getTenantId10(request);
6144
+ const tenantId = getTenantId12(request);
5792
6145
  const run = await getEvalStore().getRunById(tenantId, rid);
5793
6146
  if (run) {
5794
6147
  const eventType = run.status === "completed" ? "completed" : "error";
@@ -5827,7 +6180,7 @@ data: ${JSON.stringify(event.data)}
5827
6180
  });
5828
6181
  app2.delete("/api/eval/runs/:rid", async (request, reply) => {
5829
6182
  try {
5830
- const tenantId = getTenantId10(request);
6183
+ const tenantId = getTenantId12(request);
5831
6184
  const { rid } = request.params;
5832
6185
  const deleted = await getEvalStore().deleteRun(tenantId, rid);
5833
6186
  if (!deleted) return reply.status(404).send({ success: false, message: "Run not found" });
@@ -5838,7 +6191,7 @@ data: ${JSON.stringify(event.data)}
5838
6191
  });
5839
6192
  app2.get("/api/eval/reports/projects/:pid", async (request, reply) => {
5840
6193
  try {
5841
- const tenantId = getTenantId10(request);
6194
+ const tenantId = getTenantId12(request);
5842
6195
  const { pid } = request.params;
5843
6196
  const report = await getEvalStore().getProjectReport(tenantId, pid);
5844
6197
  if (!report) return reply.status(404).send({ success: false, message: "Project not found" });
@@ -5850,11 +6203,11 @@ data: ${JSON.stringify(event.data)}
5850
6203
  }
5851
6204
 
5852
6205
  // src/controllers/users.ts
5853
- var import_core25 = require("@axiom-lattice/core");
6206
+ var import_core27 = require("@axiom-lattice/core");
5854
6207
  var import_uuid5 = require("uuid");
5855
6208
  var UsersController = class {
5856
6209
  constructor() {
5857
- this.userStore = (0, import_core25.getStoreLattice)("default", "user").store;
6210
+ this.userStore = (0, import_core27.getStoreLattice)("default", "user").store;
5858
6211
  }
5859
6212
  async listUsers(request, reply) {
5860
6213
  const { email } = request.query;
@@ -5932,11 +6285,11 @@ function registerUserRoutes(app2) {
5932
6285
  }
5933
6286
 
5934
6287
  // src/controllers/tenants.ts
5935
- var import_core26 = require("@axiom-lattice/core");
6288
+ var import_core28 = require("@axiom-lattice/core");
5936
6289
  var import_uuid6 = require("uuid");
5937
6290
  var TenantsController = class {
5938
6291
  constructor() {
5939
- this.tenantStore = (0, import_core26.getStoreLattice)("default", "tenant").store;
6292
+ this.tenantStore = (0, import_core28.getStoreLattice)("default", "tenant").store;
5940
6293
  }
5941
6294
  // ==================== Tenant CRUD ====================
5942
6295
  async listTenants(request, reply) {
@@ -6000,7 +6353,7 @@ function registerTenantRoutes(app2) {
6000
6353
  }
6001
6354
 
6002
6355
  // src/controllers/auth.ts
6003
- var import_core27 = require("@axiom-lattice/core");
6356
+ var import_core29 = require("@axiom-lattice/core");
6004
6357
  var import_uuid7 = require("uuid");
6005
6358
  var defaultAuthConfig = {
6006
6359
  autoApproveUsers: true,
@@ -6009,9 +6362,9 @@ var defaultAuthConfig = {
6009
6362
  };
6010
6363
  var AuthController = class {
6011
6364
  constructor(config = {}) {
6012
- this.userStore = (0, import_core27.getStoreLattice)("default", "user").store;
6013
- this.tenantStore = (0, import_core27.getStoreLattice)("default", "tenant").store;
6014
- this.userTenantLinkStore = (0, import_core27.getStoreLattice)("default", "userTenantLink").store;
6365
+ this.userStore = (0, import_core29.getStoreLattice)("default", "user").store;
6366
+ this.tenantStore = (0, import_core29.getStoreLattice)("default", "tenant").store;
6367
+ this.userTenantLinkStore = (0, import_core29.getStoreLattice)("default", "userTenantLink").store;
6015
6368
  this.config = { ...defaultAuthConfig, ...config };
6016
6369
  }
6017
6370
  async register(request, reply) {
@@ -6165,6 +6518,8 @@ var AuthController = class {
6165
6518
  });
6166
6519
  }
6167
6520
  const token = await this.generateToken(userId, tenantId);
6521
+ const link = await this.userTenantLinkStore.getLink(userId, tenantId);
6522
+ const linkMeta = link?.metadata || {};
6168
6523
  return {
6169
6524
  success: true,
6170
6525
  data: {
@@ -6173,7 +6528,12 @@ var AuthController = class {
6173
6528
  name: tenant.name,
6174
6529
  status: tenant.status
6175
6530
  },
6176
- token
6531
+ token,
6532
+ personalAssistant: linkMeta.personalAssistantId ? {
6533
+ assistantId: linkMeta.personalAssistantId,
6534
+ projectId: linkMeta.personalProjectId || "default",
6535
+ workspaceId: linkMeta.personalWorkspaceId || "default"
6536
+ } : null
6177
6537
  }
6178
6538
  };
6179
6539
  } catch (error) {
@@ -6419,82 +6779,6 @@ function normalizeChatType(chatType) {
6419
6779
  return chatType === "p2p" ? "direct" : "group";
6420
6780
  }
6421
6781
 
6422
- // src/channels/lark/LarkChannelAdapter.ts
6423
- var larkConfigSchema = import_zod.z.object({
6424
- appId: import_zod.z.string(),
6425
- appSecret: import_zod.z.string(),
6426
- verificationToken: import_zod.z.string().optional(),
6427
- encryptKey: import_zod.z.string().optional()
6428
- });
6429
- var larkChannelAdapter = {
6430
- channel: "lark",
6431
- configSchema: larkConfigSchema,
6432
- async receive(rawPayload, installation) {
6433
- const event = parseLarkMessageEvent(rawPayload);
6434
- if (!event) return null;
6435
- return {
6436
- channel: "lark",
6437
- channelInstallationId: installation.id,
6438
- tenantId: installation.tenantId,
6439
- sender: {
6440
- id: event.openId,
6441
- displayName: void 0
6442
- },
6443
- content: {
6444
- text: event.text,
6445
- metadata: {
6446
- chatId: event.chatId,
6447
- chatType: event.chatType,
6448
- messageId: event.messageId
6449
- }
6450
- },
6451
- conversation: {
6452
- id: event.chatId,
6453
- type: event.chatType
6454
- },
6455
- replyTarget: {
6456
- adapterChannel: "lark",
6457
- channelInstallationId: installation.id,
6458
- rawTarget: {
6459
- chatId: event.chatId,
6460
- messageId: event.messageId,
6461
- chatType: event.chatType
6462
- }
6463
- }
6464
- };
6465
- },
6466
- async sendReply(replyTarget, message, installation) {
6467
- const { createLarkSender: createLarkSender2 } = await Promise.resolve().then(() => (init_sender(), sender_exports));
6468
- const sender = await createLarkSender2(installation.config);
6469
- await sender.sendTextReply({
6470
- chatId: replyTarget.rawTarget.chatId,
6471
- text: message.text
6472
- });
6473
- }
6474
- };
6475
-
6476
- // src/channels/lark/verification.ts
6477
- var import_crypto6 = __toESM(require("crypto"));
6478
- function parseLarkRequestBody(body, encryptKey) {
6479
- const parsed = body || {};
6480
- if (encryptKey && typeof parsed.encrypt === "string") {
6481
- return decryptLarkPayload(encryptKey, parsed.encrypt);
6482
- }
6483
- return parsed;
6484
- }
6485
- function decryptLarkPayload(encryptKey, encryptedPayload) {
6486
- const key = import_crypto6.default.createHash("sha256").update(encryptKey).digest();
6487
- const buffer = Buffer.from(encryptedPayload, "base64");
6488
- const iv = buffer.subarray(0, 16);
6489
- const ciphertext = buffer.subarray(16);
6490
- const decipher = import_crypto6.default.createDecipheriv("aes-256-cbc", key, iv);
6491
- const plaintext = Buffer.concat([
6492
- decipher.update(ciphertext),
6493
- decipher.final()
6494
- ]).toString("utf8");
6495
- return JSON.parse(plaintext);
6496
- }
6497
-
6498
6782
  // src/logger/Logger.ts
6499
6783
  var import_pino = __toESM(require("pino"));
6500
6784
  var import_pino_pretty = require("pino-pretty");
@@ -6633,8 +6917,165 @@ var Logger = class _Logger {
6633
6917
  }
6634
6918
  };
6635
6919
 
6636
- // src/channels/lark/controller.ts
6920
+ // src/channels/lark/LarkChannelAdapter.ts
6921
+ var Lark = __toESM(require("@larksuiteoapi/node-sdk"));
6637
6922
  var logger = new Logger({ serviceName: "lattice/gateway/lark" });
6923
+ var activeConnections = /* @__PURE__ */ new Map();
6924
+ function parseTextContent(content) {
6925
+ if (!content) return null;
6926
+ try {
6927
+ const parsed = JSON.parse(content);
6928
+ return typeof parsed.text === "string" ? parsed.text : null;
6929
+ } catch {
6930
+ return null;
6931
+ }
6932
+ }
6933
+ function normalizeChatType2(chatType) {
6934
+ return chatType === "p2p" ? "direct" : "group";
6935
+ }
6936
+ function wsEventToInbound(event, installationId, tenantId) {
6937
+ const messageId = event.message?.message_id;
6938
+ const chatId = event.message?.chat_id;
6939
+ const openId = event.sender?.sender_id?.open_id;
6940
+ if (!messageId || !chatId || !openId) return null;
6941
+ if (event.message?.message_type !== "text") return null;
6942
+ const text = parseTextContent(event.message.content);
6943
+ if (!text) return null;
6944
+ const chatType = normalizeChatType2(event.message.chat_type);
6945
+ return {
6946
+ channel: "lark",
6947
+ channelInstallationId: installationId,
6948
+ tenantId,
6949
+ sender: { id: openId, displayName: void 0 },
6950
+ content: { text, metadata: { chatId, chatType, messageId } },
6951
+ conversation: { id: chatId, type: chatType },
6952
+ replyTarget: {
6953
+ adapterChannel: "lark",
6954
+ channelInstallationId: installationId,
6955
+ rawTarget: { chatId, messageId, chatType }
6956
+ }
6957
+ };
6958
+ }
6959
+ var larkConfigSchema = import_zod.z.object({
6960
+ appId: import_zod.z.string(),
6961
+ appSecret: import_zod.z.string(),
6962
+ verificationToken: import_zod.z.string().optional(),
6963
+ encryptKey: import_zod.z.string().optional()
6964
+ });
6965
+ var larkChannelAdapter = {
6966
+ channel: "lark",
6967
+ configSchema: larkConfigSchema,
6968
+ async receive(rawPayload, installation) {
6969
+ const event = parseLarkMessageEvent(rawPayload);
6970
+ if (!event) return null;
6971
+ return {
6972
+ channel: "lark",
6973
+ channelInstallationId: installation.id,
6974
+ tenantId: installation.tenantId,
6975
+ sender: { id: event.openId, displayName: void 0 },
6976
+ content: {
6977
+ text: event.text,
6978
+ metadata: { chatId: event.chatId, chatType: event.chatType, messageId: event.messageId }
6979
+ },
6980
+ conversation: { id: event.chatId, type: event.chatType },
6981
+ replyTarget: {
6982
+ adapterChannel: "lark",
6983
+ channelInstallationId: installation.id,
6984
+ rawTarget: { chatId: event.chatId, messageId: event.messageId, chatType: event.chatType }
6985
+ }
6986
+ };
6987
+ },
6988
+ async sendReply(replyTarget, message, installation) {
6989
+ const { createLarkSender: createLarkSender2 } = await Promise.resolve().then(() => (init_sender(), sender_exports));
6990
+ const sender = await createLarkSender2(installation.config);
6991
+ await sender.sendTextReply({
6992
+ chatId: replyTarget.rawTarget.chatId,
6993
+ text: message.text
6994
+ });
6995
+ },
6996
+ resolveThreadId(message, binding) {
6997
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
6998
+ const chatType = message.conversation?.type === "direct" ? "dm" : "group";
6999
+ const agentId = binding.agentId;
7000
+ if (chatType === "dm") {
7001
+ return `lark:dm:${message.sender.id}:${agentId}:${date}`;
7002
+ }
7003
+ return `lark:group:${message.conversation?.id ?? "unknown"}:${agentId}:${date}`;
7004
+ },
7005
+ async connect(installation, deps) {
7006
+ const { id: installationId, tenantId, config } = installation;
7007
+ if (!config.appId || !config.appSecret) {
7008
+ logger.warn("Lark installation missing credentials, skipping", { installationId });
7009
+ return;
7010
+ }
7011
+ if (activeConnections.has(installationId)) {
7012
+ logger.warn("Lark WS already connected for installation, skipping", { installationId });
7013
+ return;
7014
+ }
7015
+ logger.info("Lark WS client starting", { installationId, tenantId });
7016
+ const router = deps?.router;
7017
+ const eventDispatcher = new Lark.EventDispatcher({}).register({
7018
+ "im.message.receive_v1": async (data) => {
7019
+ try {
7020
+ const inbound = wsEventToInbound(data, installationId, tenantId);
7021
+ if (!inbound) return;
7022
+ logger.info("Lark WS message received", {
7023
+ installationId,
7024
+ senderId: inbound.sender.id,
7025
+ chatId: data.message?.chat_id
7026
+ });
7027
+ if (router) {
7028
+ const result = await router.dispatch(inbound);
7029
+ if (!result.success) {
7030
+ logger.warn("Lark WS dispatch failed", {
7031
+ installationId,
7032
+ error: result.error?.message
7033
+ });
7034
+ }
7035
+ }
7036
+ } catch (err) {
7037
+ logger.error("Lark WS event handler error", {
7038
+ installationId,
7039
+ error: err instanceof Error ? err.message : String(err)
7040
+ });
7041
+ }
7042
+ }
7043
+ });
7044
+ const client = new Lark.WSClient({
7045
+ appId: config.appId,
7046
+ appSecret: config.appSecret,
7047
+ loggerLevel: Lark.LoggerLevel.info
7048
+ });
7049
+ await client.start({ eventDispatcher });
7050
+ activeConnections.set(installationId, client);
7051
+ logger.info("Lark WS client connected", { installationId });
7052
+ }
7053
+ };
7054
+
7055
+ // src/channels/lark/verification.ts
7056
+ var import_crypto7 = __toESM(require("crypto"));
7057
+ function parseLarkRequestBody(body, encryptKey) {
7058
+ const parsed = body || {};
7059
+ if (encryptKey && typeof parsed.encrypt === "string") {
7060
+ return decryptLarkPayload(encryptKey, parsed.encrypt);
7061
+ }
7062
+ return parsed;
7063
+ }
7064
+ function decryptLarkPayload(encryptKey, encryptedPayload) {
7065
+ const key = import_crypto7.default.createHash("sha256").update(encryptKey).digest();
7066
+ const buffer = Buffer.from(encryptedPayload, "base64");
7067
+ const iv = buffer.subarray(0, 16);
7068
+ const ciphertext = buffer.subarray(16);
7069
+ const decipher = import_crypto7.default.createDecipheriv("aes-256-cbc", key, iv);
7070
+ const plaintext = Buffer.concat([
7071
+ decipher.update(ciphertext),
7072
+ decipher.final()
7073
+ ]).toString("utf8");
7074
+ return JSON.parse(plaintext);
7075
+ }
7076
+
7077
+ // src/channels/lark/controller.ts
7078
+ var logger2 = new Logger({ serviceName: "lattice/gateway/lark" });
6638
7079
  function createLarkEventHandler(deps) {
6639
7080
  return async function handleLarkEvent(request, reply) {
6640
7081
  const { installationId } = request.params;
@@ -6655,7 +7096,7 @@ function createLarkEventHandler(deps) {
6655
7096
  return;
6656
7097
  }
6657
7098
  deps.router.dispatch(inboundMessage).catch((error) => {
6658
- logger.error("Lark message dispatch error", {
7099
+ logger2.error("Lark message dispatch error", {
6659
7100
  error: error instanceof Error ? error.message : String(error)
6660
7101
  });
6661
7102
  });
@@ -6687,8 +7128,8 @@ function registerChannelRoutes(app2, dependencies) {
6687
7128
  }
6688
7129
 
6689
7130
  // src/controllers/channel-installations.ts
6690
- var import_crypto7 = require("crypto");
6691
- function getTenantId11(request) {
7131
+ var import_crypto8 = require("crypto");
7132
+ function getTenantId13(request) {
6692
7133
  const userTenantId = request.user?.tenantId;
6693
7134
  if (userTenantId) {
6694
7135
  return userTenantId;
@@ -6696,8 +7137,8 @@ function getTenantId11(request) {
6696
7137
  return request.headers["x-tenant-id"] || "default";
6697
7138
  }
6698
7139
  async function getInstallationStore() {
6699
- const { getStoreLattice: getStoreLattice16 } = await import("@axiom-lattice/core");
6700
- const store = getStoreLattice16("default", "channelInstallation").store;
7140
+ const { getStoreLattice: getStoreLattice18 } = await import("@axiom-lattice/core");
7141
+ const store = getStoreLattice18("default", "channelInstallation").store;
6701
7142
  if (store) return store;
6702
7143
  const { PostgreSQLChannelInstallationStore } = await import("@axiom-lattice/pg-stores");
6703
7144
  const databaseUrl = process.env.DATABASE_URL;
@@ -6709,7 +7150,7 @@ async function getInstallationStore() {
6709
7150
  });
6710
7151
  }
6711
7152
  async function getChannelInstallationList(request, reply) {
6712
- const tenantId = getTenantId11(request);
7153
+ const tenantId = getTenantId13(request);
6713
7154
  const { channel } = request.query;
6714
7155
  try {
6715
7156
  const store = await getInstallationStore();
@@ -6735,7 +7176,7 @@ async function getChannelInstallationList(request, reply) {
6735
7176
  }
6736
7177
  }
6737
7178
  async function getChannelInstallation(request, reply) {
6738
- const tenantId = getTenantId11(request);
7179
+ const tenantId = getTenantId13(request);
6739
7180
  const { installationId } = request.params;
6740
7181
  try {
6741
7182
  const store = await getInstallationStore();
@@ -6768,7 +7209,7 @@ async function getChannelInstallation(request, reply) {
6768
7209
  }
6769
7210
  }
6770
7211
  async function createChannelInstallation(request, reply) {
6771
- const tenantId = getTenantId11(request);
7212
+ const tenantId = getTenantId13(request);
6772
7213
  const body = request.body;
6773
7214
  try {
6774
7215
  if (!body.channel) {
@@ -6803,7 +7244,7 @@ async function createChannelInstallation(request, reply) {
6803
7244
  }
6804
7245
  }
6805
7246
  const store = await getInstallationStore();
6806
- const installationId = body.id || (0, import_crypto7.randomUUID)();
7247
+ const installationId = body.id || (0, import_crypto8.randomUUID)();
6807
7248
  const installation = await store.createInstallation(
6808
7249
  tenantId,
6809
7250
  installationId,
@@ -6831,7 +7272,7 @@ async function createChannelInstallation(request, reply) {
6831
7272
  }
6832
7273
  }
6833
7274
  async function updateChannelInstallation(request, reply) {
6834
- const tenantId = getTenantId11(request);
7275
+ const tenantId = getTenantId13(request);
6835
7276
  const { installationId } = request.params;
6836
7277
  const body = request.body;
6837
7278
  try {
@@ -6877,7 +7318,7 @@ async function updateChannelInstallation(request, reply) {
6877
7318
  }
6878
7319
  }
6879
7320
  async function deleteChannelInstallation(request, reply) {
6880
- const tenantId = getTenantId11(request);
7321
+ const tenantId = getTenantId13(request);
6881
7322
  const { installationId } = request.params;
6882
7323
  try {
6883
7324
  const store = await getInstallationStore();
@@ -6927,17 +7368,17 @@ function registerChannelInstallationRoutes(app2) {
6927
7368
  }
6928
7369
 
6929
7370
  // src/controllers/channel-bindings.ts
6930
- var import_core28 = require("@axiom-lattice/core");
6931
- function getTenantId12(request) {
7371
+ var import_core30 = require("@axiom-lattice/core");
7372
+ function getTenantId14(request) {
6932
7373
  const userTenantId = request.user?.tenantId;
6933
7374
  if (userTenantId) return userTenantId;
6934
7375
  return request.headers["x-tenant-id"] || "default";
6935
7376
  }
6936
7377
  async function getBindingList(request, _reply) {
6937
- const tenantId = getTenantId12(request);
7378
+ const tenantId = getTenantId14(request);
6938
7379
  const { channel, agentId, channelInstallationId, limit, offset } = request.query;
6939
7380
  try {
6940
- const registry = (0, import_core28.getBindingRegistry)();
7381
+ const registry = (0, import_core30.getBindingRegistry)();
6941
7382
  const bindings = await registry.list({ channel, agentId, tenantId, channelInstallationId, limit, offset });
6942
7383
  return { success: true, message: "Bindings retrieved", data: { records: bindings, total: bindings.length } };
6943
7384
  } catch (error) {
@@ -6946,9 +7387,9 @@ async function getBindingList(request, _reply) {
6946
7387
  }
6947
7388
  }
6948
7389
  async function getBinding(request, reply) {
6949
- const tenantId = getTenantId12(request);
7390
+ const tenantId = getTenantId14(request);
6950
7391
  try {
6951
- const registry = (0, import_core28.getBindingRegistry)();
7392
+ const registry = (0, import_core30.getBindingRegistry)();
6952
7393
  const bindings = await registry.list({ tenantId });
6953
7394
  const binding = bindings.find((b) => b.id === request.params.id);
6954
7395
  if (!binding || binding.tenantId !== tenantId) {
@@ -6962,9 +7403,9 @@ async function getBinding(request, reply) {
6962
7403
  }
6963
7404
  }
6964
7405
  async function createBinding(request, reply) {
6965
- const tenantId = getTenantId12(request);
7406
+ const tenantId = getTenantId14(request);
6966
7407
  try {
6967
- const registry = (0, import_core28.getBindingRegistry)();
7408
+ const registry = (0, import_core30.getBindingRegistry)();
6968
7409
  const binding = await registry.create({ ...request.body, tenantId });
6969
7410
  reply.status(201);
6970
7411
  return { success: true, message: "Binding created", data: binding };
@@ -6976,8 +7417,8 @@ async function createBinding(request, reply) {
6976
7417
  }
6977
7418
  async function updateBinding(request, reply) {
6978
7419
  try {
6979
- const tenantId = getTenantId12(request);
6980
- const registry = (0, import_core28.getBindingRegistry)();
7420
+ const tenantId = getTenantId14(request);
7421
+ const registry = (0, import_core30.getBindingRegistry)();
6981
7422
  const bindings = await registry.list({ tenantId });
6982
7423
  const existing = bindings.find((b) => b.id === request.params.id);
6983
7424
  if (!existing || existing.tenantId !== tenantId) {
@@ -6994,8 +7435,8 @@ async function updateBinding(request, reply) {
6994
7435
  }
6995
7436
  async function deleteBinding(request, reply) {
6996
7437
  try {
6997
- const tenantId = getTenantId12(request);
6998
- const registry = (0, import_core28.getBindingRegistry)();
7438
+ const tenantId = getTenantId14(request);
7439
+ const registry = (0, import_core30.getBindingRegistry)();
6999
7440
  const bindings = await registry.list({ tenantId });
7000
7441
  const existing = bindings.find((b) => b.id === request.params.id);
7001
7442
  if (!existing || existing.tenantId !== tenantId) {
@@ -7011,10 +7452,10 @@ async function deleteBinding(request, reply) {
7011
7452
  }
7012
7453
  }
7013
7454
  async function resolveBinding(request, _reply) {
7014
- const tenantId = getTenantId12(request);
7455
+ const tenantId = getTenantId14(request);
7015
7456
  const { channel, senderId, channelInstallationId } = request.query;
7016
7457
  try {
7017
- const registry = (0, import_core28.getBindingRegistry)();
7458
+ const registry = (0, import_core30.getBindingRegistry)();
7018
7459
  const binding = await registry.resolve({ channel, senderId, channelInstallationId, tenantId });
7019
7460
  if (!binding) {
7020
7461
  return { success: false, message: "No binding found", data: null };
@@ -7036,6 +7477,105 @@ function registerChannelBindingRoutes(app2) {
7036
7477
  app2.delete("/api/channel-bindings/:id", deleteBinding);
7037
7478
  }
7038
7479
 
7480
+ // src/controllers/menu-items.ts
7481
+ var import_core31 = require("@axiom-lattice/core");
7482
+ function getTenantId15(request) {
7483
+ const userTenantId = request.user?.tenantId;
7484
+ if (userTenantId) return userTenantId;
7485
+ return request.headers["x-tenant-id"] || "default";
7486
+ }
7487
+ function errorMessage(err) {
7488
+ return err instanceof Error ? err.message : "Unexpected error";
7489
+ }
7490
+ async function getMenuItemList(request, _reply) {
7491
+ const tenantId = getTenantId15(request);
7492
+ try {
7493
+ const registry = (0, import_core31.getMenuRegistry)();
7494
+ const items = await registry.list({ tenantId, menuTarget: request.query.menuTarget });
7495
+ return { success: true, message: "Menu items retrieved", data: { records: items, total: items.length } };
7496
+ } catch (error) {
7497
+ const msg = errorMessage(error);
7498
+ console.error("Failed to get menu items:", msg);
7499
+ return { success: false, message: msg, data: { records: [], total: 0 } };
7500
+ }
7501
+ }
7502
+ async function getMenuItem(request, reply) {
7503
+ const tenantId = getTenantId15(request);
7504
+ try {
7505
+ const registry = (0, import_core31.getMenuRegistry)();
7506
+ const item = await registry.getById(request.params.id);
7507
+ if (!item || item.tenantId !== tenantId) {
7508
+ reply.status(404);
7509
+ return { success: false, message: "Menu item not found" };
7510
+ }
7511
+ return { success: true, message: "Menu item retrieved", data: item };
7512
+ } catch (error) {
7513
+ const msg = errorMessage(error);
7514
+ console.error("Failed to get menu item:", msg);
7515
+ reply.status(500);
7516
+ return { success: false, message: msg };
7517
+ }
7518
+ }
7519
+ async function createMenuItem(request, reply) {
7520
+ const tenantId = getTenantId15(request);
7521
+ try {
7522
+ const registry = (0, import_core31.getMenuRegistry)();
7523
+ const item = await registry.create({ ...request.body, tenantId });
7524
+ reply.status(201);
7525
+ return { success: true, message: "Menu item created", data: item };
7526
+ } catch (error) {
7527
+ const msg = errorMessage(error);
7528
+ console.error("Failed to create menu item:", msg);
7529
+ reply.status(500);
7530
+ return { success: false, message: msg };
7531
+ }
7532
+ }
7533
+ async function updateMenuItem(request, reply) {
7534
+ try {
7535
+ const tenantId = getTenantId15(request);
7536
+ const registry = (0, import_core31.getMenuRegistry)();
7537
+ const existing = await registry.getById(request.params.id);
7538
+ if (!existing || existing.tenantId !== tenantId) {
7539
+ reply.status(404);
7540
+ return { success: false, message: "Menu item not found" };
7541
+ }
7542
+ const item = await registry.update(request.params.id, request.body);
7543
+ return { success: true, message: "Menu item updated", data: item };
7544
+ } catch (error) {
7545
+ const msg = errorMessage(error);
7546
+ console.error("Failed to update menu item:", msg);
7547
+ reply.status(500);
7548
+ return { success: false, message: msg };
7549
+ }
7550
+ }
7551
+ async function deleteMenuItem(request, reply) {
7552
+ try {
7553
+ const tenantId = getTenantId15(request);
7554
+ const registry = (0, import_core31.getMenuRegistry)();
7555
+ const existing = await registry.getById(request.params.id);
7556
+ if (!existing || existing.tenantId !== tenantId) {
7557
+ reply.status(404);
7558
+ return { success: false, message: "Menu item not found" };
7559
+ }
7560
+ await registry.delete(request.params.id);
7561
+ return { success: true, message: "Menu item deleted" };
7562
+ } catch (error) {
7563
+ const msg = errorMessage(error);
7564
+ console.error("Failed to delete menu item:", msg);
7565
+ reply.status(500);
7566
+ return { success: false, message: msg };
7567
+ }
7568
+ }
7569
+
7570
+ // src/routes/menu-items.ts
7571
+ function registerMenuItemRoutes(app2) {
7572
+ app2.get("/api/menu-items", getMenuItemList);
7573
+ app2.post("/api/menu-items", createMenuItem);
7574
+ app2.get("/api/menu-items/:id", getMenuItem);
7575
+ app2.put("/api/menu-items/:id", updateMenuItem);
7576
+ app2.delete("/api/menu-items/:id", deleteMenuItem);
7577
+ }
7578
+
7039
7579
  // src/routes/a2a-bridge.ts
7040
7580
  var import_uuid8 = require("uuid");
7041
7581
  var log = {
@@ -7216,6 +7756,7 @@ var registerLatticeRoutes = (app2, channelDeps) => {
7216
7756
  app2.post("/api/runs", createRun);
7217
7757
  app2.post("/api/resume_stream", resumeStream);
7218
7758
  app2.post("/api/assistants/:assistantId/threads/:threadId/abort", abortRun);
7759
+ app2.post("/api/assistants/:assistantId/threads/:threadId/recover", recoverRun);
7219
7760
  app2.get(
7220
7761
  "/api/assistants/:assistantId/:thread_id/memory",
7221
7762
  { schema: getAllMemoryItemsSchema },
@@ -7251,6 +7792,15 @@ var registerLatticeRoutes = (app2, channelDeps) => {
7251
7792
  app2.post("/api/assistants", createAssistant);
7252
7793
  app2.put("/api/assistants/:id", updateAssistant);
7253
7794
  app2.delete("/api/assistants/:id", deleteAssistant);
7795
+ app2.post("/api/personal-assistant", createPersonalAssistant);
7796
+ app2.get("/api/personal-assistant", getPersonalAssistant);
7797
+ app2.delete("/api/personal-assistant", deletePersonalAssistant);
7798
+ app2.get("/api/tasks", listTasks);
7799
+ app2.get("/api/tasks/:id", getTask);
7800
+ app2.post("/api/tasks", createTask);
7801
+ app2.put("/api/tasks/:id", updateTask);
7802
+ app2.delete("/api/tasks/:id", deleteTask);
7803
+ app2.patch("/api/tasks/:id/complete", completeTask);
7254
7804
  app2.get(
7255
7805
  "/api/assistants/:assistantId/graph",
7256
7806
  { schema: getAgentGraphSchema },
@@ -7349,6 +7899,7 @@ var registerLatticeRoutes = (app2, channelDeps) => {
7349
7899
  });
7350
7900
  registerChannelRoutes(app2, channelDeps);
7351
7901
  registerChannelInstallationRoutes(app2);
7902
+ registerMenuItemRoutes(app2);
7352
7903
  if (channelDeps) {
7353
7904
  registerChannelBindingRoutes(app2);
7354
7905
  }
@@ -7426,8 +7977,8 @@ var registerLatticeRoutes = (app2, channelDeps) => {
7426
7977
  };
7427
7978
 
7428
7979
  // src/router/MessageRouter.ts
7429
- var import_core29 = require("@axiom-lattice/core");
7430
- var import_crypto8 = require("crypto");
7980
+ var import_core32 = require("@axiom-lattice/core");
7981
+ var import_crypto9 = require("crypto");
7431
7982
  var BindingNotFoundError = class extends Error {
7432
7983
  constructor(message) {
7433
7984
  super(message);
@@ -7474,6 +8025,9 @@ var MessageRouter = class {
7474
8025
  inboundMessage: message,
7475
8026
  metadata: {}
7476
8027
  };
8028
+ let binding = null;
8029
+ let threadId;
8030
+ let agentId;
7477
8031
  try {
7478
8032
  await this.runMiddlewares(ctx, async () => {
7479
8033
  const tenantId = message.tenantId || (await this.installationStore.getInstallationById(message.channelInstallationId))?.tenantId;
@@ -7490,16 +8044,18 @@ var MessageRouter = class {
7490
8044
  );
7491
8045
  }
7492
8046
  console.log({ event: "dispatch:start", channel: message.channel, senderId: message.sender.id, tenantId }, "Message dispatch started");
7493
- let binding = await this.bindingRegistry.resolve({
8047
+ const adapter = this.adapterRegistry.get(message.channel);
8048
+ const hasAdapterThreadStrategy = !!adapter?.resolveThreadId;
8049
+ binding = await this.bindingRegistry.resolve({
7494
8050
  channel: message.channel,
7495
8051
  senderId: message.sender.id,
7496
8052
  channelInstallationId: message.channelInstallationId,
7497
8053
  tenantId
7498
8054
  });
8055
+ const installation = await this.installationStore.getInstallationById(
8056
+ message.channelInstallationId
8057
+ );
7499
8058
  if (!binding) {
7500
- const installation = await this.installationStore.getInstallationById(
7501
- message.channelInstallationId
7502
- );
7503
8059
  if (installation?.rejectWhenNoBinding) {
7504
8060
  console.warn({
7505
8061
  event: "dispatch:no_binding",
@@ -7532,7 +8088,7 @@ var MessageRouter = class {
7532
8088
  createdAt: /* @__PURE__ */ new Date(),
7533
8089
  updatedAt: /* @__PURE__ */ new Date()
7534
8090
  };
7535
- } else {
8091
+ } else if (!hasAdapterThreadStrategy) {
7536
8092
  console.error({
7537
8093
  event: "dispatch:no_fallback",
7538
8094
  channel: message.channel,
@@ -7544,47 +8100,99 @@ var MessageRouter = class {
7544
8100
  );
7545
8101
  }
7546
8102
  }
7547
- ctx.binding = binding;
7548
- console.log({
7549
- event: "dispatch:binding",
7550
- bindingId: binding.id,
7551
- agentId: binding.agentId,
7552
- threadId: binding.threadId,
7553
- threadMode: binding.threadMode,
7554
- workspaceId: binding.workspaceId,
7555
- projectId: binding.projectId
7556
- }, "Binding resolved");
7557
- if (!binding.enabled) {
7558
- console.warn({
7559
- event: "dispatch:binding_disabled",
8103
+ ctx.binding = binding ?? void 0;
8104
+ if (binding) {
8105
+ console.log({
8106
+ event: "dispatch:binding",
7560
8107
  bindingId: binding.id,
7561
8108
  agentId: binding.agentId,
7562
- senderId: message.sender.id
7563
- }, "Binding is disabled, rejecting message");
8109
+ threadId: binding.threadId,
8110
+ threadMode: binding.threadMode,
8111
+ workspaceId: binding.workspaceId,
8112
+ projectId: binding.projectId
8113
+ }, "Binding resolved");
8114
+ if (!binding.enabled) {
8115
+ console.warn({
8116
+ event: "dispatch:binding_disabled",
8117
+ bindingId: binding.id,
8118
+ agentId: binding.agentId,
8119
+ senderId: message.sender.id
8120
+ }, "Binding is disabled, rejecting message");
8121
+ throw new BindingNotFoundError(
8122
+ `Binding for sender "${message.sender.id}" is disabled`
8123
+ );
8124
+ }
8125
+ }
8126
+ agentId = binding?.agentId ?? installation?.fallbackAgentId;
8127
+ if (!agentId) {
7564
8128
  throw new BindingNotFoundError(
7565
- `Binding for sender "${message.sender.id}" is disabled`
8129
+ `No agent configured for sender "${message.sender.id}"`
7566
8130
  );
7567
8131
  }
7568
- let threadId = ctx.binding.threadMode === "per_conversation" ? void 0 : ctx.binding.threadId;
8132
+ if (hasAdapterThreadStrategy) {
8133
+ const resolvedThreadId = await adapter.resolveThreadId(message, binding);
8134
+ threadId = resolvedThreadId;
8135
+ console.log({
8136
+ event: "dispatch:thread:adapter",
8137
+ threadId,
8138
+ channel: message.channel,
8139
+ adapterChannel: adapter.channel
8140
+ }, "Thread resolved by adapter strategy");
8141
+ const threadStore = (0, import_core32.getStoreLattice)("default", "thread").store;
8142
+ try {
8143
+ await threadStore.createThread(
8144
+ tenantId,
8145
+ agentId,
8146
+ threadId,
8147
+ {
8148
+ metadata: {
8149
+ channel: message.channel,
8150
+ channelInstallationId: message.channelInstallationId,
8151
+ senderId: message.sender.id,
8152
+ bindingId: binding?.id,
8153
+ ...message.conversation ? {
8154
+ conversationId: message.conversation.id,
8155
+ conversationType: message.conversation.type
8156
+ } : {}
8157
+ }
8158
+ }
8159
+ );
8160
+ console.log({
8161
+ event: "dispatch:thread:adapter:created",
8162
+ threadId
8163
+ }, "Thread created by adapter strategy");
8164
+ } catch {
8165
+ console.log({
8166
+ event: "dispatch:thread:adapter:reuse",
8167
+ threadId
8168
+ }, "Thread already exists, reusing");
8169
+ }
8170
+ } else if (binding) {
8171
+ if (binding.threadMode === "per_conversation") {
8172
+ threadId = void 0;
8173
+ } else {
8174
+ threadId = binding.threadId;
8175
+ }
8176
+ }
7569
8177
  if (!threadId) {
7570
- const threadStore = (0, import_core29.getStoreLattice)("default", "thread").store;
7571
- const newThreadId = (0, import_crypto8.randomUUID)();
8178
+ const threadStore = (0, import_core32.getStoreLattice)("default", "thread").store;
8179
+ const newThreadId = (0, import_crypto9.randomUUID)();
7572
8180
  console.log({
7573
8181
  event: "dispatch:thread:create",
7574
- agentId: ctx.binding.agentId,
8182
+ agentId,
7575
8183
  newThreadId,
7576
8184
  tenantId
7577
8185
  }, "Creating new thread for binding");
7578
8186
  const newThread = await threadStore.createThread(
7579
8187
  tenantId,
7580
- ctx.binding.agentId,
8188
+ agentId,
7581
8189
  newThreadId,
7582
8190
  {
7583
8191
  metadata: {
7584
8192
  channel: message.channel,
7585
8193
  channelInstallationId: message.channelInstallationId,
7586
8194
  senderId: message.sender.id,
7587
- bindingId: ctx.binding.id,
8195
+ bindingId: binding?.id,
7588
8196
  ...message.conversation ? {
7589
8197
  conversationId: message.conversation.id,
7590
8198
  conversationType: message.conversation.type
@@ -7593,36 +8201,35 @@ var MessageRouter = class {
7593
8201
  }
7594
8202
  );
7595
8203
  threadId = newThread.id;
7596
- if (ctx.binding.id !== "fallback") {
7597
- await this.bindingRegistry.update(ctx.binding.id, { threadId });
7598
- ctx.binding.threadId = threadId;
7599
- } else {
7600
- ctx.binding.threadId = threadId;
8204
+ if (binding && binding.id !== "fallback") {
8205
+ await this.bindingRegistry.update(binding.id, { threadId });
8206
+ binding.threadId = threadId;
8207
+ } else if (binding) {
8208
+ binding.threadId = threadId;
7601
8209
  }
7602
8210
  }
7603
8211
  console.log({
7604
8212
  event: "dispatch:agent",
7605
- agentId: ctx.binding.agentId,
8213
+ agentId,
7606
8214
  threadId,
7607
- threadMode: ctx.binding.threadMode,
7608
8215
  senderId: message.sender.id,
7609
8216
  contentLength: message.content.text.length
7610
8217
  }, "Dispatching to agent");
7611
- const agent = import_core29.agentInstanceManager.getAgent({
8218
+ const agent = import_core32.agentInstanceManager.getAgent({
7612
8219
  tenant_id: tenantId,
7613
- assistant_id: ctx.binding.agentId,
8220
+ assistant_id: agentId,
7614
8221
  thread_id: threadId,
7615
- workspace_id: ctx.binding.workspaceId || "",
7616
- project_id: ctx.binding.projectId || ""
8222
+ workspace_id: binding?.workspaceId || "",
8223
+ project_id: binding?.projectId || ""
7617
8224
  });
7618
8225
  if (message.replyTarget) {
7619
8226
  const replySubKey = `${threadId}:${message.replyTarget.adapterChannel}:reply`;
7620
- const adapter = this.adapterRegistry.get(message.replyTarget.adapterChannel);
7621
- if (adapter) {
7622
- const installation = await this.installationStore.getInstallationById(
8227
+ const adapter2 = this.adapterRegistry.get(message.replyTarget.adapterChannel);
8228
+ if (adapter2) {
8229
+ const installation2 = await this.installationStore.getInstallationById(
7623
8230
  message.channelInstallationId
7624
8231
  );
7625
- if (installation) {
8232
+ if (installation2) {
7626
8233
  const existing = this._replySubs.get(replySubKey);
7627
8234
  if (!existing || existing.count === 0) {
7628
8235
  const timer = setTimeout(() => {
@@ -7662,7 +8269,7 @@ var MessageRouter = class {
7662
8269
  channel: message.replyTarget.adapterChannel,
7663
8270
  replyLength: replyText.length
7664
8271
  }, "Sending channel reply");
7665
- adapter.sendReply(message.replyTarget, { text: replyText }, installation).then(() => {
8272
+ adapter2.sendReply(message.replyTarget, { text: replyText }, installation2).then(() => {
7666
8273
  console.log({
7667
8274
  event: "dispatch:reply:sent",
7668
8275
  threadId,
@@ -7700,7 +8307,7 @@ var MessageRouter = class {
7700
8307
  });
7701
8308
  console.log({
7702
8309
  event: "dispatch:complete",
7703
- agentId: ctx.binding.agentId,
8310
+ agentId,
7704
8311
  threadId,
7705
8312
  messageId: addResult?.messageId,
7706
8313
  result: JSON.stringify(addResult)
@@ -7709,7 +8316,7 @@ var MessageRouter = class {
7709
8316
  return {
7710
8317
  success: true,
7711
8318
  bindingId: ctx.binding?.id,
7712
- threadId: ctx.binding?.threadId,
8319
+ threadId,
7713
8320
  result: ctx.result
7714
8321
  };
7715
8322
  } catch (error) {
@@ -7820,13 +8427,13 @@ function createRateLimitMiddleware(maxRequests = 10, windowMs = 60 * 1e3, maxEnt
7820
8427
  }
7821
8428
 
7822
8429
  // src/router/middlewares/auditLogger.ts
7823
- var logger2 = new Logger({ serviceName: "lattice/gateway/audit" });
8430
+ var logger3 = new Logger({ serviceName: "lattice/gateway/audit" });
7824
8431
  function createAuditLoggerMiddleware() {
7825
8432
  return async (ctx, next) => {
7826
8433
  const start2 = Date.now();
7827
8434
  try {
7828
8435
  await next();
7829
- logger2.info("message routed", {
8436
+ logger3.info("message routed", {
7830
8437
  event: "message:routed",
7831
8438
  channel: ctx.inboundMessage.channel,
7832
8439
  senderId: ctx.inboundMessage.sender.id,
@@ -7836,7 +8443,7 @@ function createAuditLoggerMiddleware() {
7836
8443
  status: "success"
7837
8444
  });
7838
8445
  } catch (error) {
7839
- logger2.error(
8446
+ logger3.error(
7840
8447
  error instanceof Error ? error.message : String(error),
7841
8448
  {
7842
8449
  event: "message:error",
@@ -7852,7 +8459,7 @@ function createAuditLoggerMiddleware() {
7852
8459
  }
7853
8460
 
7854
8461
  // src/index.ts
7855
- var import_core32 = require("@axiom-lattice/core");
8462
+ var import_core35 = require("@axiom-lattice/core");
7856
8463
 
7857
8464
  // src/swagger.ts
7858
8465
  var import_swagger = __toESM(require("@fastify/swagger"));
@@ -7917,7 +8524,7 @@ var configureSwagger = async (app2, customSwaggerConfig, customSwaggerUiConfig)
7917
8524
  };
7918
8525
 
7919
8526
  // src/services/agent_task_consumer.ts
7920
- var import_core30 = require("@axiom-lattice/core");
8527
+ var import_core33 = require("@axiom-lattice/core");
7921
8528
  var handleAgentTask = async (taskRequest, retryCount = 0) => {
7922
8529
  const {
7923
8530
  assistant_id,
@@ -7935,21 +8542,22 @@ var handleAgentTask = async (taskRequest, retryCount = 0) => {
7935
8542
  console.log(
7936
8543
  `\u5F00\u59CB\u5904\u7406\u4EFB\u52A1 [assistant_id: ${assistant_id}, thread_id: ${thread_id}]`
7937
8544
  );
7938
- const agent = import_core30.agentInstanceManager.getAgent({ assistant_id, thread_id, tenant_id, workspace_id: runConfig?.workspaceId, project_id: runConfig?.projectId, custom_run_config: runConfig });
7939
- await agent.addMessage({ input, command, custom_run_config: runConfig }, import_core30.QueueMode.STEER);
8545
+ const agent = import_core33.agentInstanceManager.getAgent({ assistant_id, thread_id, tenant_id, workspace_id: runConfig?.workspaceId, project_id: runConfig?.projectId, custom_run_config: runConfig });
8546
+ await agent.addMessage({ input, command, custom_run_config: runConfig }, import_core33.QueueMode.STEER);
7940
8547
  if (callback_event) {
7941
8548
  agent.subscribeOnce("message:completed", (evt) => {
7942
- import_core30.eventBus.publish(callback_event, {
8549
+ import_core33.eventBus.publish(callback_event, {
7943
8550
  success: true,
7944
- state: evt.state,
7945
- config: { assistant_id, thread_id, tenant_id }
8551
+ state: evt.state
7946
8552
  });
7947
8553
  if (main_thread_id && main_tenant_id) {
7948
8554
  try {
7949
- const mainAgent = import_core30.agentInstanceManager.getAgent({
8555
+ const mainAgent = import_core33.agentInstanceManager.getAgent({
7950
8556
  assistant_id: main_assistant_id ?? assistant_id,
7951
8557
  thread_id: main_thread_id,
7952
- tenant_id: main_tenant_id
8558
+ tenant_id: main_tenant_id,
8559
+ workspace_id: runConfig?.workspaceId,
8560
+ project_id: runConfig?.projectId
7953
8561
  });
7954
8562
  if (mainAgent) {
7955
8563
  const messages = evt.state?.values?.messages;
@@ -7974,10 +8582,9 @@ ${summary}`
7974
8582
  }
7975
8583
  });
7976
8584
  agent.subscribeOnce("message:interrupted", (evt) => {
7977
- import_core30.eventBus.publish(callback_event, {
8585
+ import_core33.eventBus.publish(callback_event, {
7978
8586
  success: true,
7979
- state: evt.state,
7980
- config: { assistant_id, thread_id, tenant_id }
8587
+ state: evt.state
7981
8588
  });
7982
8589
  });
7983
8590
  }
@@ -7998,10 +8605,9 @@ ${summary}`
7998
8605
  return handleAgentTask(taskRequest, nextRetryCount);
7999
8606
  }
8000
8607
  if (callback_event) {
8001
- import_core30.eventBus.publish(callback_event, {
8608
+ import_core33.eventBus.publish(callback_event, {
8002
8609
  success: false,
8003
- error: error instanceof Error ? error.message : String(error),
8004
- config: { assistant_id, thread_id, tenant_id }
8610
+ error: error instanceof Error ? error.message : String(error)
8005
8611
  });
8006
8612
  }
8007
8613
  console.error(
@@ -8036,7 +8642,7 @@ var _AgentTaskConsumer = class _AgentTaskConsumer {
8036
8642
  * 初始化事件监听和队列轮询
8037
8643
  */
8038
8644
  initialize() {
8039
- import_core30.eventBus.subscribe(import_core30.AGENT_TASK_EVENT, this.trigger_agent_task.bind(this));
8645
+ import_core33.eventBus.subscribe(import_core33.AGENT_TASK_EVENT, this.trigger_agent_task.bind(this));
8040
8646
  this.startPollingQueue();
8041
8647
  console.log("Agent\u4EFB\u52A1\u6D88\u8D39\u8005\u5DF2\u542F\u52A8\u5E76\u76D1\u542C\u4EFB\u52A1\u4E8B\u4EF6\u548C\u961F\u5217");
8042
8648
  }
@@ -8155,14 +8761,9 @@ var _AgentTaskConsumer = class _AgentTaskConsumer {
8155
8761
  handleAgentTask(taskRequest).catch((error) => {
8156
8762
  console.error("\u5904\u7406Agent\u4EFB\u52A1\u65F6\u53D1\u751F\u672A\u6355\u83B7\u7684\u9519\u8BEF:", error);
8157
8763
  if (taskRequest.callback_event) {
8158
- import_core30.eventBus.publish(taskRequest.callback_event, {
8764
+ import_core33.eventBus.publish(taskRequest.callback_event, {
8159
8765
  success: false,
8160
- error: error instanceof Error ? error.message : String(error),
8161
- config: {
8162
- assistant_id: taskRequest.assistant_id,
8163
- thread_id: taskRequest.thread_id,
8164
- tenant_id: taskRequest["x-tenant-id"]
8165
- }
8766
+ error: error instanceof Error ? error.message : String(error)
8166
8767
  });
8167
8768
  }
8168
8769
  });
@@ -8175,7 +8776,7 @@ _AgentTaskConsumer.agent_run_endpoint = "http://localhost:4001/api/runs";
8175
8776
  var AgentTaskConsumer = _AgentTaskConsumer;
8176
8777
 
8177
8778
  // src/index.ts
8178
- var import_core33 = require("@axiom-lattice/core");
8779
+ var import_core36 = require("@axiom-lattice/core");
8179
8780
  var import_protocols5 = require("@axiom-lattice/protocols");
8180
8781
  var import_meta = {};
8181
8782
  process.on("unhandledRejection", (reason, promise) => {
@@ -8189,13 +8790,13 @@ var DEFAULT_LOGGER_CONFIG = {
8189
8790
  loggerName: "lattice/gateway"
8190
8791
  };
8191
8792
  var loggerLattice = initializeLogger(DEFAULT_LOGGER_CONFIG);
8192
- var logger3 = loggerLattice.client;
8793
+ var logger4 = loggerLattice.client;
8193
8794
  function initializeLogger(config) {
8194
- if (import_core33.loggerLatticeManager.hasLattice("default")) {
8195
- import_core33.loggerLatticeManager.removeLattice("default");
8795
+ if (import_core36.loggerLatticeManager.hasLattice("default")) {
8796
+ import_core36.loggerLatticeManager.removeLattice("default");
8196
8797
  }
8197
- (0, import_core33.registerLoggerLattice)("default", config);
8198
- return (0, import_core33.getLoggerLattice)("default");
8798
+ (0, import_core36.registerLoggerLattice)("default", config);
8799
+ return (0, import_core36.getLoggerLattice)("default");
8199
8800
  }
8200
8801
  var app = (0, import_fastify.default)({
8201
8802
  logger: false,
@@ -8288,7 +8889,7 @@ app.setErrorHandler((error, request, reply) => {
8288
8889
  "x-request-id": getHeaderValue(request.headers["x-request-id"]),
8289
8890
  "x-user-id": getHeaderValue(request.headers["x-user-id"])
8290
8891
  };
8291
- logger3.error(
8892
+ logger4.error(
8292
8893
  `\u8BF7\u6C42\u9519\u8BEF: ${request.method} ${request.url} error:${error.message}`,
8293
8894
  {
8294
8895
  ...context,
@@ -8304,7 +8905,7 @@ app.setErrorHandler((error, request, reply) => {
8304
8905
  });
8305
8906
  function getConfiguredSandboxProvider() {
8306
8907
  const sandboxProviderType = process.env.SANDBOX_PROVIDER_TYPE || "microsandbox-remote";
8307
- return (0, import_core33.createSandboxProvider)({
8908
+ return (0, import_core36.createSandboxProvider)({
8308
8909
  type: sandboxProviderType,
8309
8910
  remoteBaseURL: process.env.SANDBOX_BASE_URL,
8310
8911
  microsandboxServiceBaseURL: process.env.MICROSANDBOX_SERVICE_BASE_URL,
@@ -8328,17 +8929,19 @@ var start = async (config) => {
8328
8929
  file: config.loggerConfig.file || DEFAULT_LOGGER_CONFIG.file
8329
8930
  };
8330
8931
  loggerLattice = initializeLogger(loggerConfig);
8331
- logger3 = loggerLattice.client;
8932
+ logger4 = loggerLattice.client;
8332
8933
  }
8333
8934
  app.decorate("loggerLattice", loggerLattice);
8334
8935
  let channelDeps;
8936
+ const adapterRegistry = new ChannelAdapterRegistry();
8937
+ adapterRegistry.register(larkChannelAdapter);
8335
8938
  try {
8336
- const { getStoreLattice: getStoreLattice16 } = await import("@axiom-lattice/core");
8337
- const bindingStore = getStoreLattice16("default", "channelBinding").store;
8338
- const installationStore = getStoreLattice16("default", "channelInstallation").store;
8339
- (0, import_core32.setBindingRegistry)(bindingStore);
8340
- const adapterRegistry = new ChannelAdapterRegistry();
8341
- adapterRegistry.register(larkChannelAdapter);
8939
+ const { getStoreLattice: getStore2 } = await import("@axiom-lattice/core");
8940
+ let bindingStore;
8941
+ let installationStore;
8942
+ bindingStore = getStore2("default", "channelBinding").store;
8943
+ installationStore = getStore2("default", "channelInstallation").store;
8944
+ (0, import_core35.setBindingRegistry)(bindingStore);
8342
8945
  const router = new MessageRouter({
8343
8946
  middlewares: [
8344
8947
  createDeduplicationMiddleware(),
@@ -8351,27 +8954,49 @@ var start = async (config) => {
8351
8954
  });
8352
8955
  channelDeps = { router, installationStore };
8353
8956
  try {
8354
- const a2aKeyStore = getStoreLattice16("default", "a2aApiKey").store;
8957
+ const a2aKeyStore = getStore2("default", "a2aApiKey").store;
8355
8958
  const a2a = await Promise.resolve().then(() => (init_a2a(), a2a_exports));
8356
8959
  a2a.setA2AKeyStore(a2aKeyStore);
8357
8960
  await a2a.refreshStoreKeyMap();
8358
- logger3.info("A2A key store initialized");
8961
+ logger4.info("A2A key store initialized");
8359
8962
  } catch {
8360
8963
  }
8964
+ } catch (err) {
8965
+ logger4.warn("Channel infrastructure unavailable", {
8966
+ error: err instanceof Error ? err.message : String(err)
8967
+ });
8968
+ }
8969
+ try {
8970
+ const menuStore = (0, import_core36.getStoreLattice)("default", "menu").store;
8971
+ (0, import_core35.setMenuRegistry)(menuStore);
8972
+ logger4.info("Menu registry initialized");
8361
8973
  } catch {
8362
8974
  }
8363
8975
  registerLatticeRoutes(app, channelDeps);
8364
- if (!import_core33.sandboxLatticeManager.hasLattice("default")) {
8365
- import_core33.sandboxLatticeManager.registerLattice("default", getConfiguredSandboxProvider());
8366
- logger3.info("Registered sandbox manager from env configuration");
8976
+ if (!import_core36.sandboxLatticeManager.hasLattice("default")) {
8977
+ import_core36.sandboxLatticeManager.registerLattice("default", getConfiguredSandboxProvider());
8978
+ logger4.info("Registered sandbox manager from env configuration");
8979
+ }
8980
+ if (channelDeps && process.env.CHANNELS_ENABLED !== "false") {
8981
+ const { connectAllChannels } = await import("@axiom-lattice/core");
8982
+ try {
8983
+ await connectAllChannels(
8984
+ (channel) => adapterRegistry.get(channel),
8985
+ { deps: { router: channelDeps.router } }
8986
+ );
8987
+ } catch (err) {
8988
+ logger4.error("Failed to start channel connections", {
8989
+ error: err instanceof Error ? err.message : String(err)
8990
+ });
8991
+ }
8367
8992
  }
8368
8993
  const target_port = config?.port || Number(process.env.PORT) || 4001;
8369
8994
  await app.listen({ port: target_port, host: "0.0.0.0" });
8370
- logger3.info(`Lattice Gateway is running on port: ${target_port}`);
8995
+ logger4.info(`Lattice Gateway is running on port: ${target_port}`);
8371
8996
  try {
8372
- logger3.info("AgentLifecycleManager initialized");
8997
+ logger4.info("AgentLifecycleManager initialized");
8373
8998
  } catch (error) {
8374
- logger3.warn("Failed to initialize AgentLifecycleManager", { error });
8999
+ logger4.warn("Failed to initialize AgentLifecycleManager", { error });
8375
9000
  }
8376
9001
  const queueServiceConfig = config?.queueServiceConfig;
8377
9002
  if (queueServiceConfig) {
@@ -8381,15 +9006,13 @@ var start = async (config) => {
8381
9006
  agentTaskConsumer.startPollingQueue();
8382
9007
  }
8383
9008
  }
8384
- try {
8385
- logger3.info("Starting agent instance recovery...");
8386
- const restoreStats = await import_core33.agentInstanceManager.restore();
8387
- logger3.info(`Agent recovery complete: ${restoreStats.restored} threads restored, ${restoreStats.errors} errors`);
8388
- } catch (error) {
8389
- logger3.error("Agent recovery failed", { error });
8390
- }
9009
+ import_core36.agentInstanceManager.restore().then((stats) => {
9010
+ logger4.info(`Agent recovery complete: ${stats.restored} threads restored, ${stats.errors} errors`);
9011
+ }).catch((error) => {
9012
+ logger4.error("Agent recovery failed", { error });
9013
+ });
8391
9014
  } catch (err) {
8392
- logger3.error("Server start failed", { error: err });
9015
+ logger4.error("Server start failed", { error: err });
8393
9016
  process.exit(1);
8394
9017
  }
8395
9018
  };