@axiom-lattice/gateway 4.6.1 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/OrphanRecoveryRuntime-MQDEJX3M.mjs +8 -0
  2. package/dist/OrphanRecoveryRuntime-MQDEJX3M.mjs.map +1 -0
  3. package/dist/RecoveryCallerDeps-6SJUYJ5S.mjs +8 -0
  4. package/dist/RecoveryCallerDeps-6SJUYJ5S.mjs.map +1 -0
  5. package/dist/{a2a-standard-PIOKEHPS.mjs → a2a-standard-PBYPNHOA.mjs} +59 -21
  6. package/dist/a2a-standard-PBYPNHOA.mjs.map +1 -0
  7. package/dist/chunk-KDQKTU3N.mjs +288 -0
  8. package/dist/chunk-KDQKTU3N.mjs.map +1 -0
  9. package/dist/chunk-NOXGKYUV.mjs +37 -0
  10. package/dist/chunk-NOXGKYUV.mjs.map +1 -0
  11. package/dist/{chunk-526UYVNQ.mjs → chunk-NPHK4SZ6.mjs} +4 -4
  12. package/dist/embed/{embed-page-AgentDetailSideApp-7NYLPLAX.js → embed-page-AgentDetailSideApp-2C2ZR62Q.js} +1 -1
  13. package/dist/embed/{embed-page-AgentGovernanceWorkbench-LNGNSI7X.js → embed-page-AgentGovernanceWorkbench-GG4ONSTS.js} +1 -1
  14. package/dist/embed/{embed-page-MessageGraph-E6DZDT65.js → embed-page-MessageGraph-WMYTVUUC.js} +1 -1
  15. package/dist/embed/{embed-page-ReactChart-3VE7F5VJ.js → embed-page-ReactChart-7XCMDMH6.js} +1 -1
  16. package/dist/embed/{embed-page-TasksSideApp-QM5TZ7EG.js → embed-page-TasksSideApp-4ZJ4Q4CL.js} +1 -1
  17. package/dist/embed/{embed-page-TeamWorkspace-E7RFY3ZY.js → embed-page-TeamWorkspace-H5OOEN3K.js} +1 -1
  18. package/dist/embed/{embed-page-TopologyRuntimeView-DLPDUB7Z.js → embed-page-TopologyRuntimeView-QMXWERVC.js} +1 -1
  19. package/dist/embed/{embed-page-WorkflowAutomationView-FKSVOHHB.js → embed-page-WorkflowAutomationView-L2OEGCA5.js} +1 -1
  20. package/dist/embed/{embed-page-chunk-H6TK3FAR.js → embed-page-chunk-2G54EIW2.js} +1 -1
  21. package/dist/embed/{embed-page-chunk-I7PWCKAG.js → embed-page-chunk-CZE4IEB3.js} +1 -1
  22. package/dist/embed/{embed-page-chunk-WWTU55RX.js → embed-page-chunk-N2ISCAS7.js} +1 -1
  23. package/dist/embed/{embed-page-chunk-EXCJ42IB.js → embed-page-chunk-OHDEKFTU.js} +1 -1
  24. package/dist/embed/{embed-page-chunk-KN7D66KL.js → embed-page-chunk-SUMYB6ZA.js} +1 -1
  25. package/dist/embed/{embed-page-chunk-U276WBDI.js → embed-page-chunk-XIXSRYJY.js} +6 -6
  26. package/dist/embed/embed-page.js +1 -1
  27. package/dist/index.d.mts +226 -3
  28. package/dist/index.d.ts +226 -3
  29. package/dist/index.js +638 -257
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +86 -78
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/{open-AMEMJOFJ.mjs → open-STFMNRO5.mjs} +8 -8
  34. package/dist/{open-exposure-I44Q4M3T.mjs → open-exposure-VU227IO3.mjs} +5 -5
  35. package/dist/{open-files-EJ6O2SGX.mjs → open-files-NPNQQ6TY.mjs} +4 -4
  36. package/dist/{open-session-LBTCU3AE.mjs → open-session-IHDGAXL3.mjs} +4 -4
  37. package/package.json +7 -7
  38. package/dist/a2a-standard-PIOKEHPS.mjs.map +0 -1
  39. /package/dist/{chunk-526UYVNQ.mjs.map → chunk-NPHK4SZ6.mjs.map} +0 -0
  40. /package/dist/{open-AMEMJOFJ.mjs.map → open-STFMNRO5.mjs.map} +0 -0
  41. /package/dist/{open-exposure-I44Q4M3T.mjs.map → open-exposure-VU227IO3.mjs.map} +0 -0
  42. /package/dist/{open-files-EJ6O2SGX.mjs.map → open-files-NPNQQ6TY.mjs.map} +0 -0
  43. /package/dist/{open-session-LBTCU3AE.mjs.map → open-session-IHDGAXL3.mjs.map} +0 -0
package/dist/index.js CHANGED
@@ -874,6 +874,44 @@ var init_wechat_client = __esm({
874
874
  }
875
875
  });
876
876
 
877
+ // src/services/collaboration/projectTaskScope.ts
878
+ function isProjectLifecycleTask(task) {
879
+ const source = task.context?.source;
880
+ return typeof task.workspaceId === "string" && task.workspaceId.length > 0 && typeof task.projectId === "string" && task.projectId.length > 0 && (source === "project_room" || source === "project_task" || source === "user");
881
+ }
882
+ function isRosterExemptProject(project) {
883
+ return project?.kind === "public";
884
+ }
885
+ function resolveTaskOwnerMembership(task, project, room, membership) {
886
+ const active = membership && membership.status === "active" && membership.tenantId === task.tenantId && membership.workspaceId === task.workspaceId && membership.projectId === task.projectId && membership.assistantId === task.ownerId && membership.roomId === room.id;
887
+ if (active) return membership;
888
+ if (!isRosterExemptProject(project)) return void 0;
889
+ return syntheticPublicProjectOwnerMembership(task, room);
890
+ }
891
+ function syntheticPublicProjectOwnerMembership(task, room) {
892
+ const threadId = typeof task.context?.thread_id === "string" && task.context.thread_id.length > 0 ? task.context.thread_id : task.ownerId;
893
+ return {
894
+ id: `public-project-owner:${task.projectId}:${task.ownerId}`,
895
+ tenantId: task.tenantId,
896
+ workspaceId: task.workspaceId,
897
+ projectId: task.projectId,
898
+ roomId: room.id,
899
+ assistantId: task.ownerId,
900
+ role: "specialist",
901
+ title: task.ownerId,
902
+ mentionName: task.ownerId,
903
+ status: "active",
904
+ roomThreadId: threadId,
905
+ joinedAt: task.createdAt,
906
+ updatedAt: task.updatedAt
907
+ };
908
+ }
909
+ var init_projectTaskScope = __esm({
910
+ "src/services/collaboration/projectTaskScope.ts"() {
911
+ "use strict";
912
+ }
913
+ });
914
+
877
915
  // src/services/files/task-file-refs.ts
878
916
  function formatFileRefsSection(refs) {
879
917
  const lines = refs.map((ref) => {
@@ -889,6 +927,298 @@ var init_task_file_refs = __esm({
889
927
  }
890
928
  });
891
929
 
930
+ // src/services/collaboration/TopCallerRecovery.ts
931
+ function hasPendingInterrupts(state) {
932
+ return (state.tasks ?? []).some((t2) => (t2.interrupts?.length ?? 0) > 0);
933
+ }
934
+ function pendingTaskCalls(state) {
935
+ const messages = state.values?.messages ?? [];
936
+ const resolved = new Set(
937
+ messages.filter((m) => m.tool_call_id).map((m) => m.tool_call_id)
938
+ );
939
+ const calls = [];
940
+ for (const m of messages) {
941
+ const typed = m;
942
+ if (typeof typed.getType !== "function" || typed.getType() !== "ai") continue;
943
+ const toolCalls = m.tool_calls;
944
+ if (!Array.isArray(toolCalls)) continue;
945
+ for (const c2 of toolCalls) {
946
+ if (c2.name !== "task" || !c2.id || resolved.has(c2.id)) continue;
947
+ const taskId = typeof c2.args?.taskId === "string" ? c2.args.taskId : void 0;
948
+ calls.push({ id: c2.id, ...taskId ? { taskId } : {} });
949
+ }
950
+ }
951
+ return calls;
952
+ }
953
+ function outcome(task) {
954
+ if (task.status === "completed") {
955
+ return JSON.stringify({ success: true, taskId: task.id, result: task.result ?? "" });
956
+ }
957
+ if (task.status === "failed") {
958
+ return JSON.stringify({ success: false, code: "TASK_FAILED", retryable: false, taskId: task.id, error: task.failureReason ?? "" });
959
+ }
960
+ return JSON.stringify({
961
+ success: false,
962
+ code: "TASK_INTERRUPTED",
963
+ retryable: false,
964
+ taskId: task.id,
965
+ error: "Run ended before completion; the task is interrupted and awaiting a decision."
966
+ });
967
+ }
968
+ async function backfillTopCallerGroup(tasks, top, deps) {
969
+ const registry = deps.registry ?? import_core66.taskRunRegistry;
970
+ const results = [];
971
+ const eligible = [];
972
+ for (const task of tasks) {
973
+ if (!task.context?.caller_thread_id) {
974
+ results.push({ id: task.id, reason: "skipped:no_caller_link" });
975
+ continue;
976
+ }
977
+ if (registry.isLive(task.id)) {
978
+ results.push({ id: task.id, reason: "skipped:live" });
979
+ continue;
980
+ }
981
+ eligible.push(task);
982
+ }
983
+ if (eligible.length === 0) return results;
984
+ const target = await deps.callerFor(top, eligible[0].tenantId);
985
+ if (!target) {
986
+ return [...results, ...eligible.map((task) => ({ id: task.id, reason: "skipped:no_caller_client" }))];
987
+ }
988
+ const state = await target.client.getState(target.config);
989
+ if (hasPendingInterrupts(state)) {
990
+ return [...results, ...eligible.map((task) => ({ id: task.id, reason: "skipped:hitl" }))];
991
+ }
992
+ const nodeName = (state.tasks ?? [])[0]?.name;
993
+ if (!nodeName) {
994
+ return [...results, ...eligible.map((task) => ({ id: task.id, reason: "skipped:no_pending_node" }))];
995
+ }
996
+ const calls = pendingTaskCalls(state);
997
+ const matched = [];
998
+ for (const task of eligible) {
999
+ const call = calls.find((candidate) => candidate.taskId === task.id);
1000
+ if (!call) {
1001
+ results.push({ id: task.id, reason: "skipped:no_pending_task_call" });
1002
+ continue;
1003
+ }
1004
+ matched.push({ task, call });
1005
+ }
1006
+ if (matched.length === 0) return results;
1007
+ await target.client.updateState(target.config, {
1008
+ messages: matched.map(({ task, call }) => new import_messages.ToolMessage({ content: outcome(task), tool_call_id: call.id, name: "task" }))
1009
+ }, nodeName);
1010
+ await deps.resume(target.client, target.config, target.agent);
1011
+ return [...results, ...matched.map(({ task }) => ({ id: task.id, reason: "recovered" }))];
1012
+ }
1013
+ async function recoverTopCaller(task, top, deps) {
1014
+ if (!task.context?.caller_thread_id) return "skipped:no_caller_link";
1015
+ if (task.context.caller_thread_id !== top.threadId) return "skipped:middle";
1016
+ const [first] = await backfillTopCallerGroup([task], top, deps);
1017
+ return first?.reason ?? "skipped:no_pending_task_call";
1018
+ }
1019
+ async function recoverTask(task, deps) {
1020
+ if (task.status !== "in_progress") {
1021
+ return { kind: "skipped", reason: "not_in_progress" };
1022
+ }
1023
+ const registry = deps.registry ?? import_core66.taskRunRegistry;
1024
+ if (registry.isLive(task.id)) {
1025
+ return { kind: "skipped", reason: "live" };
1026
+ }
1027
+ const { convergedTasks } = await (0, import_core66.reconcileStaleTaskRuns)({
1028
+ tasks: [task],
1029
+ actor: "system:on-demand-recovery",
1030
+ lifecycle: deps.lifecycle,
1031
+ ...deps.registry ? { registry: deps.registry } : {}
1032
+ });
1033
+ const converged = convergedTasks[0];
1034
+ if (!converged) {
1035
+ return { kind: "skipped", reason: "convergence_failed" };
1036
+ }
1037
+ const top = resolveTopCaller(converged, deps.orphans ?? [converged]);
1038
+ if (!top) {
1039
+ return { kind: "skipped", reason: "no_top_caller" };
1040
+ }
1041
+ if (converged.context?.caller_thread_id !== top.threadId) {
1042
+ return { kind: "skipped", reason: "middle" };
1043
+ }
1044
+ const reason = await recoverTopCaller(converged, top, {
1045
+ callerFor: deps.callerFor,
1046
+ resume: deps.resume,
1047
+ ...deps.registry ? { registry: deps.registry } : {}
1048
+ });
1049
+ if (reason === "recovered") return { kind: "recovered" };
1050
+ if (reason === "skipped:no_pending_task_call") return { kind: "converged_no_call" };
1051
+ return { kind: "skipped", reason: reason.replace(/^skipped:/, "") };
1052
+ }
1053
+ function resolveTopCaller(task, orphans) {
1054
+ const tenantId = task.tenantId;
1055
+ const runThreadToTask = new Map(
1056
+ orphans.map((orphan) => [`${orphan.tenantId}:${orphan.context?.thread_id}`, orphan])
1057
+ );
1058
+ let threadId = task.context?.caller_thread_id;
1059
+ let assistantId = task.context?.caller_assistant_id;
1060
+ const seen = /* @__PURE__ */ new Set();
1061
+ while (threadId) {
1062
+ const scopeKey3 = `${tenantId}:${threadId}`;
1063
+ if (!runThreadToTask.has(scopeKey3) || seen.has(scopeKey3)) break;
1064
+ seen.add(scopeKey3);
1065
+ const parent = runThreadToTask.get(scopeKey3);
1066
+ threadId = parent.context?.caller_thread_id;
1067
+ assistantId = parent.context?.caller_assistant_id;
1068
+ }
1069
+ return threadId ? { threadId, ...assistantId ? { assistantId } : {} } : void 0;
1070
+ }
1071
+ async function runOrphanRecovery(deps) {
1072
+ let convergedTasks;
1073
+ try {
1074
+ ({ convergedTasks } = await deps.reconcile());
1075
+ } catch (error) {
1076
+ deps.log.warn("Task orphan recovery reconcile failed", {
1077
+ error: error instanceof Error ? error.message : String(error)
1078
+ });
1079
+ return { recovered: [], skipped: ["reconcile:error"] };
1080
+ }
1081
+ const orphans = convergedTasks;
1082
+ const recovered = [];
1083
+ const skipped = [];
1084
+ const groups = /* @__PURE__ */ new Map();
1085
+ for (const task of orphans) {
1086
+ const top = resolveTopCaller(task, orphans);
1087
+ if (!top) {
1088
+ skipped.push(`${task.id}:skipped:no_top_caller`);
1089
+ continue;
1090
+ }
1091
+ if (task.context?.caller_thread_id !== top.threadId) {
1092
+ skipped.push(`${task.id}:skipped:middle`);
1093
+ continue;
1094
+ }
1095
+ const key = `${task.tenantId}:${top.threadId}`;
1096
+ const group = groups.get(key);
1097
+ if (group) group.tasks.push(task);
1098
+ else groups.set(key, { top, tasks: [task] });
1099
+ }
1100
+ for (const { top, tasks } of groups.values()) {
1101
+ try {
1102
+ const results = await backfillTopCallerGroup(tasks, top, {
1103
+ callerFor: deps.callerFor,
1104
+ resume: deps.resume
1105
+ });
1106
+ for (const { id: id3, reason } of results) {
1107
+ (reason === "recovered" ? recovered : skipped).push(`${id3}:${reason}`);
1108
+ }
1109
+ } catch (error) {
1110
+ for (const task of tasks) skipped.push(`${task.id}:error`);
1111
+ deps.log.warn("Task orphan recovery group failed", {
1112
+ threadId: top.threadId,
1113
+ error: error instanceof Error ? error.message : String(error)
1114
+ });
1115
+ }
1116
+ }
1117
+ deps.log.info("Task orphan recovery complete", { recovered, skipped });
1118
+ return { recovered, skipped };
1119
+ }
1120
+ var import_messages, import_core66;
1121
+ var init_TopCallerRecovery = __esm({
1122
+ "src/services/collaboration/TopCallerRecovery.ts"() {
1123
+ "use strict";
1124
+ import_messages = require("@langchain/core/messages");
1125
+ import_core66 = require("@axiom-lattice/core");
1126
+ }
1127
+ });
1128
+
1129
+ // src/services/collaboration/OrphanRecoveryRuntime.ts
1130
+ var OrphanRecoveryRuntime_exports = {};
1131
+ __export(OrphanRecoveryRuntime_exports, {
1132
+ createOrphanRecoveryRuntime: () => createOrphanRecoveryRuntime
1133
+ });
1134
+ function createOrphanRecoveryRuntime(deps) {
1135
+ const lifecycle = deps.lifecycle ?? (0, import_core67.createTaskLifecycleService)({
1136
+ taskStore: deps.taskStore,
1137
+ workItemStore: deps.workItemStore
1138
+ });
1139
+ return {
1140
+ async recoverAll() {
1141
+ return runOrphanRecovery({
1142
+ reconcile: () => (0, import_core67.reconcileAllTenantTaskRuns)({
1143
+ actor: "system:orphan-recovery",
1144
+ tenantStore: {
1145
+ listTenants: async () => (await deps.tenantStore.getAllTenants()).map((tenant2) => ({ id: tenant2.id }))
1146
+ },
1147
+ taskStore: deps.taskStore,
1148
+ lifecycle,
1149
+ include: (t2) => !isProjectLifecycleTask(t2)
1150
+ }),
1151
+ callerFor: deps.callerFor,
1152
+ resume: deps.resume,
1153
+ log: deps.log
1154
+ });
1155
+ },
1156
+ async recoverTask(input) {
1157
+ const task = await deps.taskStore.getById(input.tenantId, input.taskId);
1158
+ if (!task) return { kind: "skipped", reason: "not_found" };
1159
+ if (isProjectLifecycleTask(task)) {
1160
+ return { kind: "skipped", reason: "project_task" };
1161
+ }
1162
+ const orphans = await deps.taskStore.list({ tenantId: input.tenantId, status: "in_progress" });
1163
+ return recoverTask(task, {
1164
+ lifecycle,
1165
+ registry: import_core67.taskRunRegistry,
1166
+ orphans,
1167
+ callerFor: deps.callerFor,
1168
+ resume: deps.resume
1169
+ });
1170
+ }
1171
+ };
1172
+ }
1173
+ var import_core67;
1174
+ var init_OrphanRecoveryRuntime = __esm({
1175
+ "src/services/collaboration/OrphanRecoveryRuntime.ts"() {
1176
+ "use strict";
1177
+ import_core67 = require("@axiom-lattice/core");
1178
+ init_TopCallerRecovery();
1179
+ init_projectTaskScope();
1180
+ }
1181
+ });
1182
+
1183
+ // src/services/collaboration/RecoveryCallerDeps.ts
1184
+ var RecoveryCallerDeps_exports = {};
1185
+ __export(RecoveryCallerDeps_exports, {
1186
+ createRecoveryCallerDeps: () => createRecoveryCallerDeps
1187
+ });
1188
+ function createRecoveryCallerDeps() {
1189
+ return {
1190
+ callerFor: async (top, tenantId) => {
1191
+ if (!top.assistantId) return void 0;
1192
+ const load = import_core68.getAgentClientAsync ?? import_core68.getAgentClient;
1193
+ const client = await load(tenantId, top.assistantId);
1194
+ const config = { configurable: { thread_id: top.threadId, runConfig: { tenantId, assistant_id: top.assistantId } } };
1195
+ let agent;
1196
+ try {
1197
+ agent = import_core68.agentInstanceManager.getAgent({ assistant_id: top.assistantId, thread_id: top.threadId, tenant_id: tenantId });
1198
+ } catch {
1199
+ }
1200
+ return agent ? { client, config, agent } : { client, config };
1201
+ },
1202
+ resume: async (client, config, agent) => {
1203
+ if (agent && typeof agent.resumeTask === "function") {
1204
+ try {
1205
+ await agent.resumeTask();
1206
+ return;
1207
+ } catch {
1208
+ }
1209
+ }
1210
+ await client.invoke(null, config);
1211
+ }
1212
+ };
1213
+ }
1214
+ var import_core68;
1215
+ var init_RecoveryCallerDeps = __esm({
1216
+ "src/services/collaboration/RecoveryCallerDeps.ts"() {
1217
+ "use strict";
1218
+ import_core68 = require("@axiom-lattice/core");
1219
+ }
1220
+ });
1221
+
892
1222
  // src/channels/wechat/context-store.ts
893
1223
  function makeKey(installationId, senderId) {
894
1224
  return `${installationId}::${senderId}`;
@@ -1179,11 +1509,11 @@ function devModeDefaults() {
1179
1509
  const projectId = process.env[DEFAULT_PROJECT_ENV] || void 0;
1180
1510
  return { tenantId, projectId };
1181
1511
  }
1182
- var import_protocols33, A2AAuthError, DEFAULT_TENANT_ENV, DEFAULT_TENANT_ID, DEFAULT_PROJECT_ENV, BEARER_SCHEME_RE, A2AAuthService;
1512
+ var import_protocols34, A2AAuthError, DEFAULT_TENANT_ENV, DEFAULT_TENANT_ID, DEFAULT_PROJECT_ENV, BEARER_SCHEME_RE, A2AAuthService;
1183
1513
  var init_A2AAuthService = __esm({
1184
1514
  "src/services/a2a/A2AAuthService.ts"() {
1185
1515
  "use strict";
1186
- import_protocols33 = require("@axiom-lattice/protocols");
1516
+ import_protocols34 = require("@axiom-lattice/protocols");
1187
1517
  A2AAuthError = class extends Error {
1188
1518
  constructor(message, statusCode) {
1189
1519
  super(message);
@@ -1238,7 +1568,7 @@ var init_A2AAuthService = __esm({
1238
1568
  const entry = merged.get(token);
1239
1569
  if (!entry) return { authenticated: false };
1240
1570
  const hasExplicitGrants = Array.isArray(entry.grants) && entry.grants.length > 0;
1241
- const agentGrant = (0, import_protocols33.effectiveGrants)(entry).find((g) => g.domain === "agent");
1571
+ const agentGrant = (0, import_protocols34.effectiveGrants)(entry).find((g) => g.domain === "agent");
1242
1572
  const assistantIds = hasExplicitGrants ? agentGrant?.items ?? [] : entry.assistantIds;
1243
1573
  return {
1244
1574
  authenticated: true,
@@ -1475,13 +1805,13 @@ function isA2ATaskSnapshot(value) {
1475
1805
  function snapshotSequence(value) {
1476
1806
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1477
1807
  }
1478
- var import_node_crypto28, import_node_util, import_core66, TASK_STATUS_TO_A2A_STATE, TITLE_MAX_LENGTH, A2ATaskScopeConflictError, A2ATaskStoreAdapter;
1808
+ var import_node_crypto28, import_node_util, import_core69, TASK_STATUS_TO_A2A_STATE, TITLE_MAX_LENGTH, A2ATaskScopeConflictError, A2ATaskStoreAdapter;
1479
1809
  var init_A2ATaskStoreAdapter = __esm({
1480
1810
  "src/services/a2a/A2ATaskStoreAdapter.ts"() {
1481
1811
  "use strict";
1482
1812
  import_node_crypto28 = require("crypto");
1483
1813
  import_node_util = require("util");
1484
- import_core66 = require("@axiom-lattice/core");
1814
+ import_core69 = require("@axiom-lattice/core");
1485
1815
  TASK_STATUS_TO_A2A_STATE = {
1486
1816
  pending: "submitted",
1487
1817
  in_progress: "working",
@@ -1507,7 +1837,7 @@ var init_A2ATaskStoreAdapter = __esm({
1507
1837
  this.workItemStore = options.workItemStore;
1508
1838
  this.lifecycle = options.lifecycle;
1509
1839
  this.scope = options.scope;
1510
- this.runBridge = (0, import_core66.createTaskRunBridge)({
1840
+ this.runBridge = (0, import_core69.createTaskRunBridge)({
1511
1841
  lifecycle: this.lifecycle,
1512
1842
  taskStore: this.taskStore,
1513
1843
  workItemStore: this.workItemStore
@@ -1858,13 +2188,13 @@ function assistantHasGovernedTask(assistant) {
1858
2188
  const allowedTools = taskMiddleware?.allowedTools;
1859
2189
  return !!taskMiddleware && (allowedTools === void 0 || Array.isArray(allowedTools) && (allowedTools.length === 0 || allowedTools.includes("manage_task")));
1860
2190
  }
1861
- var import_uuid11, import_core67, import_protocols34, _AxiomAgentExecutor, AxiomAgentExecutor;
2191
+ var import_uuid11, import_core70, import_protocols35, _AxiomAgentExecutor, AxiomAgentExecutor;
1862
2192
  var init_AxiomAgentExecutor = __esm({
1863
2193
  "src/services/a2a/AxiomAgentExecutor.ts"() {
1864
2194
  "use strict";
1865
2195
  import_uuid11 = require("uuid");
1866
- import_core67 = require("@axiom-lattice/core");
1867
- import_protocols34 = require("@axiom-lattice/protocols");
2196
+ import_core70 = require("@axiom-lattice/core");
2197
+ import_protocols35 = require("@axiom-lattice/protocols");
1868
2198
  init_a2aFileRefs();
1869
2199
  init_task_file_refs();
1870
2200
  _AxiomAgentExecutor = class _AxiomAgentExecutor {
@@ -1897,16 +2227,31 @@ var init_AxiomAgentExecutor = __esm({
1897
2227
  status: { state: "working", timestamp: isoNow() },
1898
2228
  metadata: { threadId, dependencies, inputFiles }
1899
2229
  });
1900
- const publishFailed = (err) => {
1901
- bus.publish({
1902
- kind: "status-update",
1903
- taskId: ctx.taskId,
1904
- contextId: ctx.contextId,
2230
+ const failTask = async (baseTask, err) => {
2231
+ const failedTask = {
2232
+ ...baseTask,
1905
2233
  status: {
1906
2234
  state: "failed",
1907
2235
  message: agentMessage(err instanceof Error ? err.message : String(err)),
1908
2236
  timestamp: isoNow()
1909
- },
2237
+ }
2238
+ };
2239
+ if (this.taskStore) {
2240
+ try {
2241
+ await this.taskStore.save(failedTask);
2242
+ } catch (saveError) {
2243
+ console.warn({
2244
+ event: "a2a:settle:save_failed",
2245
+ taskId: ctx.taskId,
2246
+ error: saveError instanceof Error ? saveError.message : String(saveError)
2247
+ });
2248
+ }
2249
+ }
2250
+ bus.publish({
2251
+ kind: "status-update",
2252
+ taskId: ctx.taskId,
2253
+ contextId: ctx.contextId,
2254
+ status: failedTask.status,
1910
2255
  final: true
1911
2256
  });
1912
2257
  };
@@ -1914,7 +2259,7 @@ var init_AxiomAgentExecutor = __esm({
1914
2259
  if (!this.taskStore) {
1915
2260
  const initialTask2 = createTask([]);
1916
2261
  bus.publish(initialTask2);
1917
- publishFailed(new Error("A2A execution requires a canonical task store"));
2262
+ await failTask(initialTask2, new Error("A2A execution requires a canonical task store"));
1918
2263
  return;
1919
2264
  }
1920
2265
  const governed = this.hasGovernedTaskCapability();
@@ -1938,14 +2283,14 @@ var init_AxiomAgentExecutor = __esm({
1938
2283
  const initialTask2 = createTask([]);
1939
2284
  if (this.taskStore) await this.taskStore.save(initialTask2);
1940
2285
  bus.publish(initialTask2);
1941
- publishFailed(err);
2286
+ await failTask(initialTask2, err);
1942
2287
  return;
1943
2288
  }
1944
2289
  const initialTask = createTask(inputFiles);
1945
2290
  await this.taskStore.save(initialTask);
1946
2291
  bus.publish(initialTask);
1947
2292
  try {
1948
- const agent = import_core67.agentInstanceManager.getAgent(this.agentParams(threadId));
2293
+ const agent = import_core70.agentInstanceManager.getAgent(this.agentParams(threadId));
1949
2294
  const requestText = inputFiles.length > 0 ? `${text}
1950
2295
 
1951
2296
  ${formatFileRefsSection(inputFiles)}` : text;
@@ -1963,7 +2308,7 @@ ${formatFileRefsSection(inputFiles)}` : text;
1963
2308
  custom_run_config: { taskId: ctx.taskId, execution: { taskId: ctx.taskId } }
1964
2309
  });
1965
2310
  const stream = agent.chunkStream(messageId, [
1966
- import_protocols34.MessageChunkTypes.MESSAGE_COMPLETED
2311
+ import_protocols35.MessageChunkTypes.MESSAGE_COMPLETED
1967
2312
  ]);
1968
2313
  let outputText = "";
1969
2314
  let interrupted = false;
@@ -1971,14 +2316,14 @@ ${formatFileRefsSection(inputFiles)}` : text;
1971
2316
  if (execution.canceled) return;
1972
2317
  const chunkType = chunk.type;
1973
2318
  const chunkText = chunk.data?.content ?? "";
1974
- if (chunkType === import_protocols34.MessageChunkTypes.INTERRUPT) {
2319
+ if (chunkType === import_protocols35.MessageChunkTypes.INTERRUPT) {
1975
2320
  interrupted = true;
1976
2321
  break;
1977
2322
  }
1978
- if (chunkType === import_protocols34.MessageChunkTypes.AI && chunkText) {
2323
+ if (chunkType === import_protocols35.MessageChunkTypes.AI && chunkText) {
1979
2324
  outputText += chunkText;
1980
2325
  }
1981
- if (chunkType === import_protocols34.MessageChunkTypes.AI || chunkType === import_protocols34.MessageChunkTypes.TOOL) {
2326
+ if (chunkType === import_protocols35.MessageChunkTypes.AI || chunkType === import_protocols35.MessageChunkTypes.TOOL) {
1982
2327
  if (chunkText) {
1983
2328
  bus.publish({
1984
2329
  kind: "status-update",
@@ -2081,19 +2426,12 @@ ${formatFileRefsSection(inputFiles)}` : text;
2081
2426
  });
2082
2427
  return;
2083
2428
  }
2084
- bus.publish({
2085
- kind: "status-update",
2086
- taskId: ctx.taskId,
2087
- contextId: ctx.contextId,
2088
- status: {
2089
- state: "failed",
2090
- message: agentMessage("Agent did not complete governed task lifecycle"),
2091
- timestamp: isoNow()
2092
- },
2093
- final: true
2094
- });
2429
+ await failTask(
2430
+ createTask(inputFiles),
2431
+ new Error("Agent did not complete governed task lifecycle")
2432
+ );
2095
2433
  } catch (err) {
2096
- publishFailed(err);
2434
+ await failTask(createTask(inputFiles), err);
2097
2435
  }
2098
2436
  } finally {
2099
2437
  active.delete(execution);
@@ -2140,7 +2478,7 @@ ${formatFileRefsSection(inputFiles)}` : text;
2140
2478
  const threadId = task ? asString2(task.metadata?.threadId) : void 0;
2141
2479
  if (threadId) {
2142
2480
  try {
2143
- const agent = import_core67.agentInstanceManager.getAgent(this.agentParams(threadId));
2481
+ const agent = import_core70.agentInstanceManager.getAgent(this.agentParams(threadId));
2144
2482
  await agent.abort();
2145
2483
  } catch (err) {
2146
2484
  console.warn({
@@ -2151,6 +2489,26 @@ ${formatFileRefsSection(inputFiles)}` : text;
2151
2489
  });
2152
2490
  }
2153
2491
  }
2492
+ if (this.taskStore) {
2493
+ const canceledTask = {
2494
+ ...task ?? {
2495
+ kind: "task",
2496
+ id: taskId,
2497
+ contextId: "",
2498
+ status: { state: "canceled" }
2499
+ },
2500
+ status: { state: "canceled", timestamp: isoNow() }
2501
+ };
2502
+ try {
2503
+ await this.taskStore.save(canceledTask);
2504
+ } catch (saveError) {
2505
+ console.warn({
2506
+ event: "a2a:settle:save_failed",
2507
+ taskId,
2508
+ error: saveError instanceof Error ? saveError.message : String(saveError)
2509
+ });
2510
+ }
2511
+ }
2154
2512
  bus.publish({
2155
2513
  kind: "status-update",
2156
2514
  taskId,
@@ -2494,10 +2852,10 @@ function isAsyncGenerator(value) {
2494
2852
  }
2495
2853
  function registerA2AStandardRoutes(app2, deps) {
2496
2854
  const authService = deps.authService;
2497
- const resolveTasks = deps.getTaskStoreLattice ?? (() => (0, import_core68.getStoreLattice)("default", "task").store);
2498
- const resolveTaskWorkItems = deps.getTaskWorkItemStore ?? (() => (0, import_core68.getStoreLattice)("default", "taskWorkItem").store);
2499
- const getAssistantStore2 = deps.getAssistantStore ?? (() => (0, import_core68.getStoreLattice)("default", "assistant").store);
2500
- const getProjectStore2 = deps.getProjectStore ?? (() => (0, import_core68.getStoreLattice)("default", "project").store);
2855
+ const resolveTasks = deps.getTaskStoreLattice ?? (() => (0, import_core71.getStoreLattice)("default", "task").store);
2856
+ const resolveTaskWorkItems = deps.getTaskWorkItemStore ?? (() => (0, import_core71.getStoreLattice)("default", "taskWorkItem").store);
2857
+ const getAssistantStore2 = deps.getAssistantStore ?? (() => (0, import_core71.getStoreLattice)("default", "assistant").store);
2858
+ const getProjectStore2 = deps.getProjectStore ?? (() => (0, import_core71.getStoreLattice)("default", "project").store);
2501
2859
  const runtimeRegistry = deps.runtimeRegistry ?? new A2ARuntimeRegistry();
2502
2860
  app2.addHook("onClose", async () => {
2503
2861
  runtimeRegistry.close();
@@ -2580,7 +2938,7 @@ function registerA2AStandardRoutes(app2, deps) {
2580
2938
  const taskStore = assistantHasGovernedTask(assistant) ? new A2ATaskStoreAdapter({
2581
2939
  taskStore: internalTasks,
2582
2940
  workItemStore: workItems,
2583
- lifecycle: (0, import_core68.createTaskLifecycleService)({
2941
+ lifecycle: (0, import_core71.createTaskLifecycleService)({
2584
2942
  taskStore: internalTasks,
2585
2943
  workItemStore: workItems
2586
2944
  }),
@@ -2699,7 +3057,7 @@ data: ${JSON.stringify(errorResponse)}
2699
3057
  const taskStore = assistantHasGovernedTask(assistant) ? new A2ATaskStoreAdapter({
2700
3058
  taskStore: internalTasks,
2701
3059
  workItemStore: workItems,
2702
- lifecycle: (0, import_core68.createTaskLifecycleService)({
3060
+ lifecycle: (0, import_core71.createTaskLifecycleService)({
2703
3061
  taskStore: internalTasks,
2704
3062
  workItemStore: workItems
2705
3063
  }),
@@ -2731,6 +3089,16 @@ data: ${JSON.stringify(data)}
2731
3089
  await executor.execute(requestContext, bus);
2732
3090
  } catch (err) {
2733
3091
  request.log.error({ err }, "a2a:test-call:execution");
3092
+ try {
3093
+ await taskStore.save({
3094
+ kind: "task",
3095
+ id: taskId,
3096
+ contextId,
3097
+ status: { state: "failed", timestamp: (/* @__PURE__ */ new Date()).toISOString() }
3098
+ });
3099
+ } catch (saveError) {
3100
+ request.log.error({ err: saveError }, "a2a:test-call:settle");
3101
+ }
2734
3102
  sendEvent("status-update", {
2735
3103
  kind: "status-update",
2736
3104
  taskId,
@@ -2744,13 +3112,13 @@ data: ${JSON.stringify(data)}
2744
3112
  }
2745
3113
  );
2746
3114
  }
2747
- var import_uuid12, import_server2, import_core68, SSE_HEADERS;
3115
+ var import_uuid12, import_server2, import_core71, SSE_HEADERS;
2748
3116
  var init_a2a_standard = __esm({
2749
3117
  "src/routes/a2a-standard.ts"() {
2750
3118
  "use strict";
2751
3119
  import_uuid12 = require("uuid");
2752
3120
  import_server2 = require("@a2a-js/sdk/server");
2753
- import_core68 = require("@axiom-lattice/core");
3121
+ import_core71 = require("@axiom-lattice/core");
2754
3122
  init_A2AAuthService();
2755
3123
  init_A2AAgentCardBuilder();
2756
3124
  init_A2ATaskStoreAdapter();
@@ -2958,11 +3326,11 @@ var init_a2a = __esm({
2958
3326
  });
2959
3327
 
2960
3328
  // src/services/open/openAuthService.ts
2961
- var import_protocols35, OpenAuthService;
3329
+ var import_protocols36, OpenAuthService;
2962
3330
  var init_openAuthService = __esm({
2963
3331
  "src/services/open/openAuthService.ts"() {
2964
3332
  "use strict";
2965
- import_protocols35 = require("@axiom-lattice/protocols");
3333
+ import_protocols36 = require("@axiom-lattice/protocols");
2966
3334
  OpenAuthService = class {
2967
3335
  constructor(keyStore) {
2968
3336
  this.keyStore = keyStore;
@@ -2976,7 +3344,7 @@ var init_openAuthService = __esm({
2976
3344
  kind: "api_key",
2977
3345
  tenantId: record.tenantId,
2978
3346
  projectId: record.projectId,
2979
- grants: (0, import_protocols35.effectiveGrants)(record)
3347
+ grants: (0, import_protocols36.effectiveGrants)(record)
2980
3348
  };
2981
3349
  }
2982
3350
  };
@@ -2984,11 +3352,11 @@ var init_openAuthService = __esm({
2984
3352
  });
2985
3353
 
2986
3354
  // src/services/open/openCredentialService.ts
2987
- var import_protocols36, OpenCredentialService;
3355
+ var import_protocols37, OpenCredentialService;
2988
3356
  var init_openCredentialService = __esm({
2989
3357
  "src/services/open/openCredentialService.ts"() {
2990
3358
  "use strict";
2991
- import_protocols36 = require("@axiom-lattice/protocols");
3359
+ import_protocols37 = require("@axiom-lattice/protocols");
2992
3360
  init_openToken();
2993
3361
  init_openAuthService();
2994
3362
  OpenCredentialService = class {
@@ -3501,8 +3869,8 @@ function exposedDeclarations(plugin) {
3501
3869
  return (plugin.meta.tools ?? []).filter((t2) => t2.expose);
3502
3870
  }
3503
3871
  async function registerExposedPluginTools() {
3504
- for (const key of import_core69.PluginRegistry.list()) {
3505
- const plugin = import_core69.PluginRegistry.get(key);
3872
+ for (const key of import_core72.PluginRegistry.list()) {
3873
+ const plugin = import_core72.PluginRegistry.get(key);
3506
3874
  if (!plugin?.middleware) continue;
3507
3875
  const exposed = exposedDeclarations(plugin);
3508
3876
  if (exposed.length === 0) continue;
@@ -3537,8 +3905,8 @@ async function registerExposedPluginTools() {
3537
3905
  }
3538
3906
  function collectExposedPluginUiResources(grants) {
3539
3907
  const resources = /* @__PURE__ */ new Map();
3540
- for (const type of import_core69.PluginRegistry.list()) {
3541
- const plugin = import_core69.PluginRegistry.get(type);
3908
+ for (const type of import_core72.PluginRegistry.list()) {
3909
+ const plugin = import_core72.PluginRegistry.get(type);
3542
3910
  if (!plugin?.middleware) continue;
3543
3911
  const exposedNames = new Set(exposedDeclarations(plugin).map((d) => d.name));
3544
3912
  if (exposedNames.size === 0) continue;
@@ -3562,11 +3930,11 @@ function collectExposedPluginUiResources(grants) {
3562
3930
  }
3563
3931
  return resources;
3564
3932
  }
3565
- var import_core69;
3933
+ var import_core72;
3566
3934
  var init_registerExposedPlugins = __esm({
3567
3935
  "src/services/open/registerExposedPlugins.ts"() {
3568
3936
  "use strict";
3569
- import_core69 = require("@axiom-lattice/core");
3937
+ import_core72 = require("@axiom-lattice/core");
3570
3938
  init_openLattice();
3571
3939
  init_pluginExposeAdapter();
3572
3940
  }
@@ -3581,14 +3949,14 @@ function toText(result) {
3581
3949
  }
3582
3950
  function defaultCatalog() {
3583
3951
  return {
3584
- getValidatedManifest: (tenantId, type) => (0, import_core70.getSandboxPluginCatalog)().getValidatedManifest(tenantId, type),
3585
- getExecutor: () => (0, import_core70.getSandboxPluginCatalog)().getExecutor(),
3586
- readPluginFile: (tenantId, type, relPath) => (0, import_core70.getSandboxPluginCatalog)().readPluginFile(tenantId, type, relPath)
3952
+ getValidatedManifest: (tenantId, type) => (0, import_core73.getSandboxPluginCatalog)().getValidatedManifest(tenantId, type),
3953
+ getExecutor: () => (0, import_core73.getSandboxPluginCatalog)().getExecutor(),
3954
+ readPluginFile: (tenantId, type, relPath) => (0, import_core73.getSandboxPluginCatalog)().readPluginFile(tenantId, type, relPath)
3587
3955
  };
3588
3956
  }
3589
3957
  async function defaultResolveConnections(pluginType, ctx) {
3590
3958
  try {
3591
- return await (0, import_core70.resolveSandboxPluginConnections)(
3959
+ return await (0, import_core73.resolveSandboxPluginConnections)(
3592
3960
  pluginType,
3593
3961
  { connectAll: true },
3594
3962
  {
@@ -3617,7 +3985,7 @@ function mergeOpenCatalog(globalCatalog, tenantTools) {
3617
3985
  async function buildTenantOpenPlugins(tenantId, grants, deps = {}) {
3618
3986
  const catalog = deps.catalog ?? defaultCatalog();
3619
3987
  const listPlugins = deps.listPlugins ?? (async (tenant2) => {
3620
- const snapshot = await (0, import_core70.getSandboxPluginCatalog)().ensureLoaded(tenant2);
3988
+ const snapshot = await (0, import_core73.getSandboxPluginCatalog)().ensureLoaded(tenant2);
3621
3989
  return { plugins: snapshot.plugins, diagnostics: snapshot.diagnostics };
3622
3990
  });
3623
3991
  const resolveConnections = deps.resolveConnections ?? defaultResolveConnections;
@@ -3659,7 +4027,7 @@ async function buildTenantOpenPlugins(tenantId, grants, deps = {}) {
3659
4027
  domain,
3660
4028
  action: tool.name,
3661
4029
  description: tool.description,
3662
- schema: (0, import_core70.jsonSchemaToZod)(tool.schema),
4030
+ schema: (0, import_core73.jsonSchemaToZod)(tool.schema),
3663
4031
  annotations: {
3664
4032
  readOnlyHint: tool.readOnly ?? false,
3665
4033
  destructiveHint: tool.destructive ?? false
@@ -3710,11 +4078,11 @@ async function buildTenantOpenPlugins(tenantId, grants, deps = {}) {
3710
4078
  }
3711
4079
  };
3712
4080
  }
3713
- var import_core70;
4081
+ var import_core73;
3714
4082
  var init_tenantOpenPlugins = __esm({
3715
4083
  "src/services/open/tenantOpenPlugins.ts"() {
3716
4084
  "use strict";
3717
- import_core70 = require("@axiom-lattice/core");
4085
+ import_core73 = require("@axiom-lattice/core");
3718
4086
  init_openLattice();
3719
4087
  init_pluginToolExecution();
3720
4088
  }
@@ -3751,13 +4119,13 @@ function emptyTenantPlugins() {
3751
4119
  }
3752
4120
  function registerOpenRoutes(app2, deps = {}) {
3753
4121
  const openAuth = deps.openAuth ?? new OpenCredentialService(
3754
- (0, import_core71.getStoreLattice)("default", "a2aApiKey").store,
3755
- (0, import_core71.getStoreLattice)("default", "project").store
4122
+ (0, import_core74.getStoreLattice)("default", "a2aApiKey").store,
4123
+ (0, import_core74.getStoreLattice)("default", "project").store
3756
4124
  );
3757
4125
  const grantsSource = deps.grantsSource ?? ((ctx) => ctx.grants);
3758
4126
  const audit = deps.audit ?? (() => {
3759
4127
  try {
3760
- const store2 = (0, import_core71.getStoreLattice)("default", "openAudit").store;
4128
+ const store2 = (0, import_core74.getStoreLattice)("default", "openAudit").store;
3761
4129
  return new OpenAuditService(store2);
3762
4130
  } catch {
3763
4131
  return void 0;
@@ -3911,12 +4279,12 @@ function registerOpenRoutes(app2, deps = {}) {
3911
4279
  }
3912
4280
  );
3913
4281
  }
3914
- var import_types, import_core71, RPC_ERROR;
4282
+ var import_types, import_core74, RPC_ERROR;
3915
4283
  var init_open = __esm({
3916
4284
  "src/routes/open.ts"() {
3917
4285
  "use strict";
3918
4286
  import_types = require("@modelcontextprotocol/sdk/types.js");
3919
- import_core71 = require("@axiom-lattice/core");
4287
+ import_core74 = require("@axiom-lattice/core");
3920
4288
  init_openCredentialService();
3921
4289
  init_openAuditService();
3922
4290
  init_openRateLimiter();
@@ -3949,7 +4317,7 @@ function registerOpenSessionRoutes(app2) {
3949
4317
  if (typeof shareToken !== "string" || shareToken.length === 0) {
3950
4318
  return reply.status(400).send({ error: "SHARE_TOKEN_REQUIRED" });
3951
4319
  }
3952
- const store2 = (0, import_core72.getStoreLattice)("default", "sharedResource").store;
4320
+ const store2 = (0, import_core75.getStoreLattice)("default", "sharedResource").store;
3953
4321
  const record = await store2.findByToken(shareToken);
3954
4322
  if (!record || record.revoked) {
3955
4323
  return reply.status(404).send({ error: "SHARE_NOT_FOUND" });
@@ -3974,11 +4342,11 @@ function registerOpenSessionRoutes(app2) {
3974
4342
  }
3975
4343
  );
3976
4344
  }
3977
- var import_core72;
4345
+ var import_core75;
3978
4346
  var init_open_session = __esm({
3979
4347
  "src/routes/open-session.ts"() {
3980
4348
  "use strict";
3981
- import_core72 = require("@axiom-lattice/core");
4349
+ import_core75 = require("@axiom-lattice/core");
3982
4350
  init_openToken();
3983
4351
  init_previewToken();
3984
4352
  init_openLattice();
@@ -3987,13 +4355,13 @@ var init_open_session = __esm({
3987
4355
 
3988
4356
  // src/services/open/openCatalogService.ts
3989
4357
  async function defaultListTenantPlugins(tenantId) {
3990
- return (await (0, import_core73.getSandboxPluginCatalog)().ensureLoaded(tenantId)).plugins;
4358
+ return (await (0, import_core76.getSandboxPluginCatalog)().ensureLoaded(tenantId)).plugins;
3991
4359
  }
3992
- var import_core73, OpenCatalogService;
4360
+ var import_core76, OpenCatalogService;
3993
4361
  var init_openCatalogService = __esm({
3994
4362
  "src/services/open/openCatalogService.ts"() {
3995
4363
  "use strict";
3996
- import_core73 = require("@axiom-lattice/core");
4364
+ import_core76 = require("@axiom-lattice/core");
3997
4365
  init_openLattice();
3998
4366
  OpenCatalogService = class {
3999
4367
  constructor(assistantStore, lattice = openLattice, listTenantPlugins2 = defaultListTenantPlugins) {
@@ -4068,17 +4436,17 @@ function registerOpenCatalogRoutes(app2) {
4068
4436
  if (!tenantId) {
4069
4437
  return reply.status(401).send({ success: false, error: "Unauthorized" });
4070
4438
  }
4071
- const assistantStore = (0, import_core74.getStoreLattice)("default", "assistant").store;
4439
+ const assistantStore = (0, import_core77.getStoreLattice)("default", "assistant").store;
4072
4440
  const service2 = new OpenCatalogService(assistantStore);
4073
4441
  const catalog = await service2.buildForTenant(tenantId);
4074
4442
  return reply.status(200).send({ success: true, data: catalog });
4075
4443
  });
4076
4444
  }
4077
- var import_core74;
4445
+ var import_core77;
4078
4446
  var init_open_catalog = __esm({
4079
4447
  "src/routes/open-catalog.ts"() {
4080
4448
  "use strict";
4081
- import_core74 = require("@axiom-lattice/core");
4449
+ import_core77 = require("@axiom-lattice/core");
4082
4450
  init_openCatalogService();
4083
4451
  }
4084
4452
  });
@@ -4090,7 +4458,7 @@ __export(sandboxProvider_exports, {
4090
4458
  resolveContextSandbox: () => resolveContextSandbox
4091
4459
  });
4092
4460
  async function resolveContextSandbox(ctx) {
4093
- return import_core75.sandboxLatticeManager.getSandboxFromConfig({
4461
+ return import_core78.sandboxLatticeManager.getSandboxFromConfig({
4094
4462
  assistant_id: "",
4095
4463
  thread_id: "",
4096
4464
  tenantId: ctx.tenantId,
@@ -4188,12 +4556,12 @@ ${truncated}`
4188
4556
  }
4189
4557
  };
4190
4558
  }
4191
- var import_zod21, import_core75, MAX_OUTPUT_BYTES;
4559
+ var import_zod21, import_core78, MAX_OUTPUT_BYTES;
4192
4560
  var init_sandboxProvider = __esm({
4193
4561
  "src/services/open/providers/sandboxProvider.ts"() {
4194
4562
  "use strict";
4195
4563
  import_zod21 = require("zod");
4196
- import_core75 = require("@axiom-lattice/core");
4564
+ import_core78 = require("@axiom-lattice/core");
4197
4565
  MAX_OUTPUT_BYTES = 64e3;
4198
4566
  }
4199
4567
  });
@@ -4215,12 +4583,12 @@ function safePath(raw) {
4215
4583
  }
4216
4584
  function registerOpenFilesRoutes(app2, deps = {}) {
4217
4585
  const openAuth = deps.openAuth ?? new OpenCredentialService(
4218
- (0, import_core76.getStoreLattice)("default", "a2aApiKey").store,
4219
- (0, import_core76.getStoreLattice)("default", "project").store
4586
+ (0, import_core79.getStoreLattice)("default", "a2aApiKey").store,
4587
+ (0, import_core79.getStoreLattice)("default", "project").store
4220
4588
  );
4221
4589
  const audit = deps.audit ?? (() => {
4222
4590
  try {
4223
- const store2 = (0, import_core76.getStoreLattice)("default", "openAudit").store;
4591
+ const store2 = (0, import_core79.getStoreLattice)("default", "openAudit").store;
4224
4592
  return new OpenAuditService(store2);
4225
4593
  } catch {
4226
4594
  return void 0;
@@ -4330,11 +4698,11 @@ function registerOpenFilesRoutes(app2, deps = {}) {
4330
4698
  }
4331
4699
  });
4332
4700
  }
4333
- var import_core76;
4701
+ var import_core79;
4334
4702
  var init_open_files = __esm({
4335
4703
  "src/routes/open-files.ts"() {
4336
4704
  "use strict";
4337
- import_core76 = require("@axiom-lattice/core");
4705
+ import_core79 = require("@axiom-lattice/core");
4338
4706
  init_openCredentialService();
4339
4707
  init_openLattice();
4340
4708
  init_sandboxProvider();
@@ -4356,7 +4724,7 @@ function registerOpenAuditRoutes(app2) {
4356
4724
  return reply.status(401).send({ success: false, error: "Unauthorized" });
4357
4725
  }
4358
4726
  const status = request.query.status === "ok" || request.query.status === "error" ? request.query.status : void 0;
4359
- const store2 = (0, import_core77.getStoreLattice)("default", "openAudit").store;
4727
+ const store2 = (0, import_core80.getStoreLattice)("default", "openAudit").store;
4360
4728
  const records = await store2.query({
4361
4729
  tenantId,
4362
4730
  credentialId: request.query.credentialId,
@@ -4371,11 +4739,11 @@ function registerOpenAuditRoutes(app2) {
4371
4739
  }
4372
4740
  );
4373
4741
  }
4374
- var import_core77;
4742
+ var import_core80;
4375
4743
  var init_open_audit = __esm({
4376
4744
  "src/routes/open-audit.ts"() {
4377
4745
  "use strict";
4378
- import_core77 = require("@axiom-lattice/core");
4746
+ import_core80 = require("@axiom-lattice/core");
4379
4747
  }
4380
4748
  });
4381
4749
 
@@ -4392,12 +4760,12 @@ function registerOpenExposureRoutes(app2, deps = {}) {
4392
4760
  if (!tenantId) {
4393
4761
  return reply.status(401).send({ success: false, error: "Unauthorized" });
4394
4762
  }
4395
- const keyStore = (0, import_core78.getStoreLattice)("default", "a2aApiKey").store;
4763
+ const keyStore = (0, import_core81.getStoreLattice)("default", "a2aApiKey").store;
4396
4764
  const record = await keyStore.findById(request.params.id);
4397
4765
  if (!record || record.tenantId !== tenantId) {
4398
4766
  return reply.status(404).send({ success: false, error: "Key not found" });
4399
4767
  }
4400
- const grants = (0, import_protocols37.effectiveGrants)(record);
4768
+ const grants = (0, import_protocols38.effectiveGrants)(record);
4401
4769
  const forwardedHost = request.headers["x-forwarded-host"];
4402
4770
  const host = (Array.isArray(forwardedHost) ? forwardedHost[0] : forwardedHost) ?? (Array.isArray(request.headers.host) ? request.headers.host[0] : request.headers.host) ?? request.hostname;
4403
4771
  const baseUrl = `${request.protocol}://${host}`;
@@ -4426,7 +4794,7 @@ function registerOpenExposureRoutes(app2, deps = {}) {
4426
4794
  hasUi: Boolean(t2.ui)
4427
4795
  }));
4428
4796
  const agentGrant = grants.find((g) => g.domain === "agent");
4429
- const assistantStore = (0, import_core78.getStoreLattice)("default", "assistant").store;
4797
+ const assistantStore = (0, import_core81.getStoreLattice)("default", "assistant").store;
4430
4798
  const agents = [];
4431
4799
  for (const assistantId of agentGrant?.items ?? []) {
4432
4800
  const assistant = await assistantStore.getAssistantById(
@@ -4461,12 +4829,12 @@ function registerOpenExposureRoutes(app2, deps = {}) {
4461
4829
  }
4462
4830
  );
4463
4831
  }
4464
- var import_core78, import_protocols37;
4832
+ var import_core81, import_protocols38;
4465
4833
  var init_open_exposure = __esm({
4466
4834
  "src/routes/open-exposure.ts"() {
4467
4835
  "use strict";
4468
- import_core78 = require("@axiom-lattice/core");
4469
- import_protocols37 = require("@axiom-lattice/protocols");
4836
+ import_core81 = require("@axiom-lattice/core");
4837
+ import_protocols38 = require("@axiom-lattice/protocols");
4470
4838
  init_openLattice();
4471
4839
  init_tenantOpenPlugins();
4472
4840
  init_A2AAgentCardBuilder();
@@ -4585,7 +4953,7 @@ function createAgentProvider(deps = {}) {
4585
4953
  } catch {
4586
4954
  }
4587
4955
  }
4588
- const agent = import_core79.agentInstanceManager.getAgent({
4956
+ const agent = import_core82.agentInstanceManager.getAgent({
4589
4957
  tenant_id: ctx.tenantId,
4590
4958
  assistant_id: assistantId,
4591
4959
  thread_id: threadId,
@@ -4599,8 +4967,8 @@ function createAgentProvider(deps = {}) {
4599
4967
  const stream = agent.chunkStream(messageId, [...STOP_TYPES]);
4600
4968
  for await (const chunk of stream) {
4601
4969
  const text = chunk.data?.content;
4602
- if (chunk.type === import_protocols38.MessageChunkTypes.INTERRUPT) break;
4603
- if (chunk.type === import_protocols38.MessageChunkTypes.AI && text) {
4970
+ if (chunk.type === import_protocols39.MessageChunkTypes.INTERRUPT) break;
4971
+ if (chunk.type === import_protocols39.MessageChunkTypes.AI && text) {
4604
4972
  parts.push(text);
4605
4973
  }
4606
4974
  }
@@ -4610,14 +4978,14 @@ function createAgentProvider(deps = {}) {
4610
4978
  }
4611
4979
  };
4612
4980
  }
4613
- var import_zod23, import_core79, import_protocols38, STOP_TYPES;
4981
+ var import_zod23, import_core82, import_protocols39, STOP_TYPES;
4614
4982
  var init_agentProvider = __esm({
4615
4983
  "src/services/open/providers/agentProvider.ts"() {
4616
4984
  "use strict";
4617
4985
  import_zod23 = require("zod");
4618
- import_core79 = require("@axiom-lattice/core");
4619
- import_protocols38 = require("@axiom-lattice/protocols");
4620
- STOP_TYPES = [import_protocols38.MessageChunkTypes.MESSAGE_COMPLETED];
4986
+ import_core82 = require("@axiom-lattice/core");
4987
+ import_protocols39 = require("@axiom-lattice/protocols");
4988
+ STOP_TYPES = [import_protocols39.MessageChunkTypes.MESSAGE_COMPLETED];
4621
4989
  }
4622
4990
  });
4623
4991
 
@@ -4647,12 +5015,12 @@ var resources_exports = {};
4647
5015
  __export(resources_exports, {
4648
5016
  ResourceController: () => ResourceController
4649
5017
  });
4650
- var import_bcryptjs, import_core80, ResourceController;
5018
+ var import_bcryptjs, import_core83, ResourceController;
4651
5019
  var init_resources = __esm({
4652
5020
  "src/controllers/resources.ts"() {
4653
5021
  "use strict";
4654
5022
  import_bcryptjs = __toESM(require("bcryptjs"));
4655
- import_core80 = require("@axiom-lattice/core");
5023
+ import_core83 = require("@axiom-lattice/core");
4656
5024
  init_mime();
4657
5025
  init_http_range();
4658
5026
  init_sandboxGrants();
@@ -4669,14 +5037,14 @@ var init_resources = __esm({
4669
5037
  if (!workspaceId || !projectId) {
4670
5038
  return reply.status(400).send({ error: "x-workspace-id and x-project-id headers required" });
4671
5039
  }
4672
- const payload = (0, import_core80.createSharePayload)(
5040
+ const payload = (0, import_core83.createSharePayload)(
4673
5041
  tenantId,
4674
5042
  workspaceId,
4675
5043
  projectId,
4676
5044
  userId,
4677
5045
  body
4678
5046
  );
4679
- const token = (0, import_core80.generateToken)();
5047
+ const token = (0, import_core83.generateToken)();
4680
5048
  try {
4681
5049
  await this.deps.store.create({ ...payload, token });
4682
5050
  this.deps.logger.info(
@@ -4828,7 +5196,7 @@ var init_resources = __esm({
4828
5196
  resourcePath: subPath
4829
5197
  }, subPath, ext, request, reply);
4830
5198
  }
4831
- const volume = (0, import_core80.buildNamedVolumeName)("p", "project", tenantId, workspaceId, projectId);
5199
+ const volume = (0, import_core83.buildNamedVolumeName)("p", "project", tenantId, workspaceId, projectId);
4832
5200
  return this._resolveAndServe(
4833
5201
  volume,
4834
5202
  subPath,
@@ -5039,7 +5407,13 @@ var init_resources = __esm({
5039
5407
  // src/index.ts
5040
5408
  var index_exports = {};
5041
5409
  __export(index_exports, {
5042
- LatticeGateway: () => LatticeGateway
5410
+ LatticeGateway: () => LatticeGateway,
5411
+ createOrphanRecoveryRuntime: () => createOrphanRecoveryRuntime,
5412
+ createRecoveryCallerDeps: () => createRecoveryCallerDeps,
5413
+ recoverTask: () => recoverTask,
5414
+ recoverTopCaller: () => recoverTopCaller,
5415
+ resolveTopCaller: () => resolveTopCaller,
5416
+ runOrphanRecovery: () => runOrphanRecovery
5043
5417
  });
5044
5418
  module.exports = __toCommonJS(index_exports);
5045
5419
  var import_config2 = require("dotenv/config");
@@ -5715,7 +6089,7 @@ var getAgentGraph = async (request, reply) => {
5715
6089
  try {
5716
6090
  const { assistantId } = request.params;
5717
6091
  const tenant_id = getTenantId(request);
5718
- const agent = import_core.agentInstanceManager.getAgent({ assistant_id: assistantId, tenant_id, thread_id: "" });
6092
+ const agent = import_core.agentInstanceManager.getAgentForRead({ assistant_id: assistantId, tenant_id, thread_id: "" });
5719
6093
  const imageData = await agent.get_draw_graph();
5720
6094
  reply.header("Content-Type", "application/json").send({
5721
6095
  image: imageData
@@ -5852,6 +6226,21 @@ var import_uuid = require("uuid");
5852
6226
  var import_core3 = require("@axiom-lattice/core");
5853
6227
  var import_protocols2 = require("@axiom-lattice/protocols");
5854
6228
 
6229
+ // src/utils/agentScope.ts
6230
+ function headerValue(value) {
6231
+ if (Array.isArray(value)) return value[0];
6232
+ return value;
6233
+ }
6234
+ function resolveAgentScope(request) {
6235
+ const workspace = headerValue(request.headers["x-workspace-id"]);
6236
+ const project = headerValue(request.headers["x-project-id"]);
6237
+ return {
6238
+ tenant_id: headerValue(request.headers["x-tenant-id"]),
6239
+ workspace_id: workspace || "default",
6240
+ project_id: project || void 0
6241
+ };
6242
+ }
6243
+
5855
6244
  // src/services/agents/ScopedAgentExecution.ts
5856
6245
  async function executeScopedAgentMessage(agent, request, stopTypes, options) {
5857
6246
  const { messageId } = options === void 0 ? await agent.addMessage(request) : await agent.addMessage(request, options.queueMode);
@@ -5953,9 +6342,7 @@ var createRun = async (request, reply) => {
5953
6342
  mode,
5954
6343
  ...input
5955
6344
  } = request.body;
5956
- const tenant_id = request.headers["x-tenant-id"];
5957
- const workspace_id = request.headers["x-workspace-id"];
5958
- const project_id = request.headers["x-project-id"];
6345
+ const { tenant_id, workspace_id, project_id } = resolveAgentScope(request);
5959
6346
  const x_request_id = request.headers["x-request-id"] || (0, import_uuid.v4)();
5960
6347
  const user_id = getUserId2(request);
5961
6348
  const mergedConfig = {
@@ -6054,9 +6441,7 @@ var createRun = async (request, reply) => {
6054
6441
  var resumeStream = async (request, reply) => {
6055
6442
  try {
6056
6443
  const { thread_id, message_id, assistant_id, known_content, poll_interval } = request.body;
6057
- const tenant_id = request.headers["x-tenant-id"];
6058
- const workspace_id = request.headers["x-workspace-id"];
6059
- const project_id = request.headers["x-project-id"];
6444
+ const { tenant_id, workspace_id, project_id } = resolveAgentScope(request);
6060
6445
  if (!thread_id || !message_id || !assistant_id || known_content === void 0) {
6061
6446
  reply.status(400).send({
6062
6447
  success: false,
@@ -6114,9 +6499,7 @@ var resumeStream = async (request, reply) => {
6114
6499
  var abortRun = async (request, reply) => {
6115
6500
  try {
6116
6501
  const { assistantId, threadId } = request.params;
6117
- const tenant_id = request.headers["x-tenant-id"];
6118
- const workspace_id = request.headers["x-workspace-id"] || "default";
6119
- const project_id = request.headers["x-project-id"] || "default";
6502
+ const { tenant_id, workspace_id, project_id } = resolveAgentScope(request);
6120
6503
  const agent = import_core3.agentInstanceManager.getAgent({
6121
6504
  assistant_id: assistantId,
6122
6505
  thread_id: threadId,
@@ -6139,9 +6522,7 @@ var abortRun = async (request, reply) => {
6139
6522
  var recoverRun = async (request, reply) => {
6140
6523
  try {
6141
6524
  const { assistantId, threadId } = request.params;
6142
- const tenant_id = request.headers["x-tenant-id"];
6143
- const workspace_id = request.headers["x-workspace-id"] || "default";
6144
- const project_id = request.headers["x-project-id"];
6525
+ const { tenant_id, workspace_id, project_id } = resolveAgentScope(request);
6145
6526
  const agent = import_core3.agentInstanceManager.getAgent({
6146
6527
  assistant_id: assistantId,
6147
6528
  thread_id: threadId,
@@ -6229,7 +6610,7 @@ var getAllMemoryItems = async (request, reply) => {
6229
6610
  });
6230
6611
  return;
6231
6612
  }
6232
- const agent = import_core4.agentInstanceManager.getAgent({ assistant_id: assistantId, tenant_id, thread_id });
6613
+ const agent = import_core4.agentInstanceManager.getAgentForRead({ assistant_id: assistantId, tenant_id, thread_id });
6233
6614
  const result = await agent.getCurrentMessages();
6234
6615
  if (!result) {
6235
6616
  reply.status(500).send(result);
@@ -6261,7 +6642,7 @@ var getAgentState = async (request, reply) => {
6261
6642
  return;
6262
6643
  }
6263
6644
  const tenant_id = request.headers["x-tenant-id"];
6264
- const agent = import_core4.agentInstanceManager.getAgent({ assistant_id: assistantId, tenant_id, thread_id });
6645
+ const agent = import_core4.agentInstanceManager.getAgentForRead({ assistant_id: assistantId, tenant_id, thread_id });
6265
6646
  const result = await agent.getCurrentState();
6266
6647
  const pendingMessages = await agent.getPendingMessages();
6267
6648
  if (!result) {
@@ -8072,7 +8453,7 @@ async function getInboxItems(request, reply) {
8072
8453
  store2.getRunSteps(r.id).catch(() => []),
8073
8454
  (async () => {
8074
8455
  try {
8075
- return import_core15.agentInstanceManager.getAgent({
8456
+ return import_core15.agentInstanceManager.getAgentForRead({
8076
8457
  assistant_id: r.assistantId,
8077
8458
  thread_id: r.threadId,
8078
8459
  tenant_id: r.tenantId
@@ -10231,9 +10612,9 @@ function isRoomPresenceMetadata(metadata, expected) {
10231
10612
  // src/services/collaboration/RoomCoordinatorEnsurer.ts
10232
10613
  var RoomCoordinatorEnsureError = class extends Error {
10233
10614
  /** Creates a typed ensure failure with the underlying store outcome. */
10234
- constructor(outcome) {
10235
- super(`Room coordinator could not be ensured: ${outcome}`);
10236
- this.outcome = outcome;
10615
+ constructor(outcome2) {
10616
+ super(`Room coordinator could not be ensured: ${outcome2}`);
10617
+ this.outcome = outcome2;
10237
10618
  this.name = "RoomCoordinatorEnsureError";
10238
10619
  }
10239
10620
  };
@@ -15309,7 +15690,7 @@ function verifyLarkParsedBody(body, config) {
15309
15690
  }
15310
15691
  return extractVerificationToken(body) === config.verificationToken;
15311
15692
  }
15312
- function headerValue(request, name) {
15693
+ function headerValue2(request, name) {
15313
15694
  const value = request.headers[name];
15314
15695
  return Array.isArray(value) ? value[0] : value;
15315
15696
  }
@@ -15317,9 +15698,9 @@ function verifyLarkRequestSignature(request, config) {
15317
15698
  if (!config.encryptKey) {
15318
15699
  return true;
15319
15700
  }
15320
- const timestamp = headerValue(request, "x-lark-request-timestamp");
15321
- const nonce = headerValue(request, "x-lark-request-nonce");
15322
- const signature = headerValue(request, "x-lark-signature");
15701
+ const timestamp = headerValue2(request, "x-lark-request-timestamp");
15702
+ const nonce = headerValue2(request, "x-lark-request-nonce");
15703
+ const signature = headerValue2(request, "x-lark-signature");
15323
15704
  if (!timestamp || !nonce || !signature) {
15324
15705
  return false;
15325
15706
  }
@@ -16929,40 +17310,8 @@ function isTaskFileRef(value) {
16929
17310
  return !!row && typeof row.uri === "string" && !!row.uri && (row.name === void 0 || typeof row.name === "string") && (row.mimeType === void 0 || typeof row.mimeType === "string") && (row.addedBy === void 0 || row.addedBy === "user" || row.addedBy === "agent");
16930
17311
  }
16931
17312
 
16932
- // src/services/collaboration/projectTaskScope.ts
16933
- function isProjectLifecycleTask(task) {
16934
- const source = task.context?.source;
16935
- return typeof task.workspaceId === "string" && task.workspaceId.length > 0 && typeof task.projectId === "string" && task.projectId.length > 0 && (source === "project_room" || source === "project_task" || source === "user");
16936
- }
16937
- function isRosterExemptProject(project) {
16938
- return project?.kind === "public";
16939
- }
16940
- function resolveTaskOwnerMembership(task, project, room, membership) {
16941
- const active = membership && membership.status === "active" && membership.tenantId === task.tenantId && membership.workspaceId === task.workspaceId && membership.projectId === task.projectId && membership.assistantId === task.ownerId && membership.roomId === room.id;
16942
- if (active) return membership;
16943
- if (!isRosterExemptProject(project)) return void 0;
16944
- return syntheticPublicProjectOwnerMembership(task, room);
16945
- }
16946
- function syntheticPublicProjectOwnerMembership(task, room) {
16947
- const threadId = typeof task.context?.thread_id === "string" && task.context.thread_id.length > 0 ? task.context.thread_id : task.ownerId;
16948
- return {
16949
- id: `public-project-owner:${task.projectId}:${task.ownerId}`,
16950
- tenantId: task.tenantId,
16951
- workspaceId: task.workspaceId,
16952
- projectId: task.projectId,
16953
- roomId: room.id,
16954
- assistantId: task.ownerId,
16955
- role: "specialist",
16956
- title: task.ownerId,
16957
- mentionName: task.ownerId,
16958
- status: "active",
16959
- roomThreadId: threadId,
16960
- joinedAt: task.createdAt,
16961
- updatedAt: task.updatedAt
16962
- };
16963
- }
16964
-
16965
17313
  // src/services/collaboration/ProjectTaskThreadService.ts
17314
+ init_projectTaskScope();
16966
17315
  var ProjectTaskThreadError = class extends Error {
16967
17316
  /**
16968
17317
  * @param code Stable machine-readable failure code.
@@ -17078,6 +17427,7 @@ var import_node_crypto9 = require("crypto");
17078
17427
  var import_node_crypto8 = require("crypto");
17079
17428
  var import_core44 = require("@axiom-lattice/core");
17080
17429
  var import_protocols12 = require("@axiom-lattice/protocols");
17430
+ init_projectTaskScope();
17081
17431
 
17082
17432
  // src/router/roomInterrupt.ts
17083
17433
  var CLARIFY_FENCE = /^```clarify\n([\s\S]*?)\n```$/;
@@ -17332,16 +17682,16 @@ var ProjectTaskExecutionService = class {
17332
17682
  );
17333
17683
  if (resumed.status === import_core44.ThreadStatus.INTERRUPTED && settlement.tryClaim()) {
17334
17684
  settlement.cleanup();
17335
- const outcome = await this.settleInterruptedEvent(input.task, input.thread, input.inputMessageId);
17336
- settlement.resolve(outcome);
17337
- return outcome;
17685
+ const outcome2 = await this.settleInterruptedEvent(input.task, input.thread, input.inputMessageId);
17686
+ settlement.resolve(outcome2);
17687
+ return outcome2;
17338
17688
  }
17339
17689
  if ((resumed.status === import_core44.ThreadStatus.IDLE || resumed.status === import_core44.ThreadStatus.ERROR) && settlement.tryClaim()) {
17340
17690
  settlement.cleanup();
17341
17691
  const reason = resumed.status === import_core44.ThreadStatus.IDLE ? "Project task execution ended without lifecycle transition" : "Recovered Agent execution is in error state";
17342
- const outcome = await this.settleEndedRecovery(input, reason);
17343
- settlement.resolve(outcome);
17344
- return outcome;
17692
+ const outcome2 = await this.settleEndedRecovery(input, reason);
17693
+ settlement.resolve(outcome2);
17694
+ return outcome2;
17345
17695
  }
17346
17696
  return await this.awaitSettlementCancellation(
17347
17697
  settlement,
@@ -17353,7 +17703,7 @@ var ProjectTaskExecutionService = class {
17353
17703
  } catch (error) {
17354
17704
  if (!settlement.tryClaim()) return settlement.promise;
17355
17705
  settlement.cleanup();
17356
- const outcome = {
17706
+ const outcome2 = {
17357
17707
  kind: "failed",
17358
17708
  task: input.task,
17359
17709
  thread: input.thread,
@@ -17362,8 +17712,8 @@ var ProjectTaskExecutionService = class {
17362
17712
  cause: "recovery_ended",
17363
17713
  lifecycleHandled: false
17364
17714
  };
17365
- settlement.resolve(outcome);
17366
- return outcome;
17715
+ settlement.resolve(outcome2);
17716
+ return outcome2;
17367
17717
  }
17368
17718
  }
17369
17719
  /** Classifies one exact Task Thread queue fact with transition-safe repeated reads. */
@@ -17581,9 +17931,9 @@ var ProjectTaskExecutionService = class {
17581
17931
  async claimDispatchFailure(settlement, task, thread, messageId, error) {
17582
17932
  if (!settlement.tryClaim()) return settlement.promise;
17583
17933
  settlement.cleanup();
17584
- const outcome = await this.failSettledTaskAwaited(task, thread, messageId, error);
17585
- settlement.resolve(outcome);
17586
- return outcome;
17934
+ const outcome2 = await this.failSettledTaskAwaited(task, thread, messageId, error);
17935
+ settlement.resolve(outcome2);
17936
+ return outcome2;
17587
17937
  }
17588
17938
  armSettlement(task, thread, messageId) {
17589
17939
  let claimed = false;
@@ -17674,9 +18024,9 @@ var ProjectTaskExecutionService = class {
17674
18024
  } catch {
17675
18025
  }
17676
18026
  }
17677
- const outcome = await this.compensateCancellation(task, thread, messageId, false);
17678
- settlement.resolve(outcome);
17679
- return outcome;
18027
+ const outcome2 = await this.compensateCancellation(task, thread, messageId, false);
18028
+ settlement.resolve(outcome2);
18029
+ return outcome2;
17680
18030
  }
17681
18031
  compensateCancellation(task, thread, messageId, abortAgent) {
17682
18032
  if (abortAgent) {
@@ -22413,8 +22763,8 @@ var RoomMessageService = class {
22413
22763
  const resolved = await promise;
22414
22764
  return this.resultForCaller(resolved, resolved.replayed);
22415
22765
  }
22416
- const outcome = await this.createAndDispatchOutcome(actor3, normalized, room);
22417
- return this.resultForCaller(outcome, outcome.replayed);
22766
+ const outcome2 = await this.createAndDispatchOutcome(actor3, normalized, room);
22767
+ return this.resultForCaller(outcome2, outcome2.replayed);
22418
22768
  }
22419
22769
  async createAndDispatchOutcome(actor3, input, room) {
22420
22770
  const persisted = await this.persistNormalizedHumanMessage(actor3, input, room);
@@ -22463,8 +22813,8 @@ var RoomMessageService = class {
22463
22813
  }
22464
22814
  throw new RoomMessageServiceError("ROOM_DISPATCH_OVERLOADED", 429, "Room dispatch capacity is full", true);
22465
22815
  }
22466
- resultForCaller(outcome, replayed) {
22467
- return { message: cloneRoomMessage(outcome.message), dispatch: outcome.dispatch.map((entry) => ({ ...entry })), replayed };
22816
+ resultForCaller(outcome2, replayed) {
22817
+ return { message: cloneRoomMessage(outcome2.message), dispatch: outcome2.dispatch.map((entry) => ({ ...entry })), replayed };
22468
22818
  }
22469
22819
  /** Retries an existing human message using the current roster without creating a copy. */
22470
22820
  async retry(actor3, messageId) {
@@ -23843,6 +24193,7 @@ function exactValues(value, required, optional = []) {
23843
24193
  // src/services/collaboration/CoordinatorWakeNotifier.ts
23844
24194
  var import_node_crypto21 = require("crypto");
23845
24195
  var import_protocols21 = require("@axiom-lattice/protocols");
24196
+ init_projectTaskScope();
23846
24197
  var SYNTHETIC_WAKE_AUTHOR = "coordinator-wake";
23847
24198
  var CoordinatorWakeNotifier = class {
23848
24199
  /** Creates a bounded Project Task lifecycle observer that wakes the Room Coordinator. */
@@ -23900,10 +24251,10 @@ var CoordinatorWakeNotifier = class {
23900
24251
  timer = setTimeout(() => resolve4("timeout"), timeoutMs);
23901
24252
  timer.unref?.();
23902
24253
  });
23903
- const outcome = await Promise.race([work.then(() => "drained"), timeout]);
24254
+ const outcome2 = await Promise.race([work.then(() => "drained"), timeout]);
23904
24255
  if (timer) clearTimeout(timer);
23905
24256
  this.closed = true;
23906
- if (outcome === "timeout") this.queues.clear();
24257
+ if (outcome2 === "timeout") this.queues.clear();
23907
24258
  }
23908
24259
  /** Closes admission and drains accepted work. */
23909
24260
  async dispose() {
@@ -24213,6 +24564,7 @@ var ProjectTaskExecutionMutex = class {
24213
24564
  var import_node_crypto22 = require("crypto");
24214
24565
  var import_core49 = require("@axiom-lattice/core");
24215
24566
  var import_protocols23 = require("@axiom-lattice/protocols");
24567
+ init_projectTaskScope();
24216
24568
  var SYSTEM_ACTOR2 = "system";
24217
24569
  var TERMINAL_ACTIONS = ["completed", "failed", "interrupted", "cancelled"];
24218
24570
  var ProjectTaskObserver = class {
@@ -24412,7 +24764,7 @@ var ProjectTaskObserver = class {
24412
24764
  try {
24413
24765
  await this.requireActiveOwner(task);
24414
24766
  } catch (error) {
24415
- await this.convergeInterrupted(task, `No active executor: ${errorMessage3(error)}`);
24767
+ await this.convergeFailed(task, `No active executor: ${errorMessage3(error)}`);
24416
24768
  return;
24417
24769
  }
24418
24770
  }
@@ -24511,7 +24863,7 @@ var ProjectTaskObserver = class {
24511
24863
  const classification = await this.deps.execution.classifyRecovery(current, ensured.thread);
24512
24864
  if (signal?.aborted || this.disposed) return;
24513
24865
  if (classification.kind === "invalid") {
24514
- await this.convergeInterrupted(
24866
+ await this.convergeFailed(
24515
24867
  current,
24516
24868
  `Task execution state is not recoverable: ${classification.reason}`
24517
24869
  );
@@ -24532,40 +24884,40 @@ var ProjectTaskObserver = class {
24532
24884
  }
24533
24885
  }, signal);
24534
24886
  }
24535
- async mapOutcome(outcome) {
24536
- if (outcome.kind === "aborted") return;
24537
- const current = snapshotTaskItem(await this.deps.tasks.getById(outcome.task.tenantId, outcome.task.id));
24538
- if (!current || current.ownerId !== outcome.thread.assistantId || current.context?.thread_id !== outcome.thread.id) return;
24887
+ async mapOutcome(outcome2) {
24888
+ if (outcome2.kind === "aborted") return;
24889
+ const current = snapshotTaskItem(await this.deps.tasks.getById(outcome2.task.tenantId, outcome2.task.id));
24890
+ if (!current || current.ownerId !== outcome2.thread.assistantId || current.context?.thread_id !== outcome2.thread.id) return;
24539
24891
  if (isTerminal(current.status) || current.status === "review") return;
24540
- if (outcome.kind === "completed") {
24892
+ if (outcome2.kind === "completed") {
24541
24893
  const result2 = await this.runBridge.settleRun({
24542
24894
  tenantId: current.tenantId,
24543
24895
  task: current,
24544
24896
  actor: SYSTEM_ACTOR2,
24545
- threadId: outcome.thread.id,
24897
+ threadId: outcome2.thread.id,
24546
24898
  outcome: { kind: "completed" }
24547
24899
  });
24548
24900
  await this.checkLifecycle(current, "outcome-completed", result2);
24549
24901
  return;
24550
24902
  }
24551
- if (outcome.kind === "cancelled") {
24903
+ if (outcome2.kind === "cancelled") {
24552
24904
  const result2 = await this.runBridge.settleRun({
24553
24905
  tenantId: current.tenantId,
24554
24906
  task: current,
24555
24907
  actor: SYSTEM_ACTOR2,
24556
- threadId: outcome.thread.id,
24908
+ threadId: outcome2.thread.id,
24557
24909
  outcome: { kind: "cancelled" }
24558
24910
  });
24559
24911
  await this.checkLifecycle(current, "outcome-cancelled", result2);
24560
24912
  return;
24561
24913
  }
24562
- if (outcome.kind === "failed" && outcome.lifecycleHandled) return;
24563
- if (outcome.kind === "interrupted") {
24914
+ if (outcome2.kind === "failed" && outcome2.lifecycleHandled) return;
24915
+ if (outcome2.kind === "interrupted") {
24564
24916
  const result2 = await this.runBridge.settleRun({
24565
24917
  tenantId: current.tenantId,
24566
24918
  task: current,
24567
24919
  actor: SYSTEM_ACTOR2,
24568
- threadId: outcome.thread.id,
24920
+ threadId: outcome2.thread.id,
24569
24921
  outcome: { kind: "interrupted" }
24570
24922
  });
24571
24923
  await this.checkLifecycle(current, "outcome-interrupted", result2);
@@ -24575,10 +24927,10 @@ var ProjectTaskObserver = class {
24575
24927
  tenantId: current.tenantId,
24576
24928
  task: current,
24577
24929
  actor: SYSTEM_ACTOR2,
24578
- threadId: outcome.thread.id,
24579
- outcome: { kind: "failed", lifecycleHandled: false, error: outcome.error }
24930
+ threadId: outcome2.thread.id,
24931
+ outcome: { kind: "failed", lifecycleHandled: false, error: outcome2.error }
24580
24932
  });
24581
- await this.checkLifecycle(current, `outcome-${outcome.cause}`, result);
24933
+ await this.checkLifecycle(current, `outcome-${outcome2.cause}`, result);
24582
24934
  }
24583
24935
  async collectDependentIds(task) {
24584
24936
  const rows = /* @__PURE__ */ new Map();
@@ -24778,25 +25130,26 @@ var ProjectTaskObserver = class {
24778
25130
  }
24779
25131
  }
24780
25132
  /**
24781
- * Converges an unexecutable task to a durable interruption.
25133
+ * Converges a mechanically unexecutable task to a durable failure.
24782
25134
  *
24783
25135
  * @param task Exact task snapshot that cannot make progress through automation.
24784
- * @param summary Human-readable reason recorded with the interruption.
25136
+ * @param failureReason Human-readable reason recorded with the failure.
24785
25137
  * @remarks Never leaves a task silently pending behind a warning; an `in_progress`
24786
25138
  * task with no dispatched queue rows is intentionally left untouched by recovery.
24787
- * The interruption is visible and resumable once an executor is available.
25139
+ * A no-executor/unrecoverable state is a mechanical failure (`failed`), not HITL
25140
+ * (ADR-143); `failed` remains retryable.
24788
25141
  */
24789
- async convergeInterrupted(task, summary) {
25142
+ async convergeFailed(task, failureReason) {
24790
25143
  if (this.disposed) return;
24791
25144
  try {
24792
25145
  const result = await this.runBridge.settleRun({
24793
25146
  tenantId: task.tenantId,
24794
25147
  task,
24795
25148
  actor: SYSTEM_ACTOR2,
24796
- outcome: { kind: "interrupted", summary }
25149
+ outcome: { kind: "failed", lifecycleHandled: false, error: failureReason }
24797
25150
  });
24798
25151
  if (!result.success && result.code !== "TASK_STATUS_CONFLICT") {
24799
- await this.safeWarning(task, "converge", `${result.code ?? "LIFECYCLE_REJECTED"}: ${result.error ?? summary}`);
25152
+ await this.safeWarning(task, "converge", `${result.code ?? "LIFECYCLE_REJECTED"}: ${result.error ?? failureReason}`);
24800
25153
  }
24801
25154
  } catch (error) {
24802
25155
  await this.safeWarning(task, "converge", error);
@@ -25074,6 +25427,7 @@ function combineSignals(left, right) {
25074
25427
  // src/services/collaboration/RoomProjectionService.ts
25075
25428
  var import_node_crypto23 = require("crypto");
25076
25429
  var import_protocols24 = require("@axiom-lattice/protocols");
25430
+ init_projectTaskScope();
25077
25431
  var ROOM_PROJECTABLE_ACTIONS = [
25078
25432
  "interrupted",
25079
25433
  "failed",
@@ -25443,6 +25797,9 @@ function isRecord3(value) {
25443
25797
  return typeof value === "object" && value !== null && !Array.isArray(value);
25444
25798
  }
25445
25799
 
25800
+ // src/routes/index.ts
25801
+ init_projectTaskScope();
25802
+
25446
25803
  // src/services/collaboration/ProjectRoomRealtimeRuntime.ts
25447
25804
  var import_core50 = require("@axiom-lattice/core");
25448
25805
 
@@ -25961,6 +26318,7 @@ function safeErrorCode(error) {
25961
26318
 
25962
26319
  // src/services/collaboration/ProjectRoomTaskEventSubscriber.ts
25963
26320
  var import_protocols27 = require("@axiom-lattice/protocols");
26321
+ init_projectTaskScope();
25964
26322
  var ProjectRoomTaskEventSubscriber = class {
25965
26323
  /** Creates a bounded Project task lifecycle observer. */
25966
26324
  constructor(deps) {
@@ -26015,10 +26373,10 @@ var ProjectRoomTaskEventSubscriber = class {
26015
26373
  timer = setTimeout(() => resolve4("timeout"), timeoutMs);
26016
26374
  timer.unref?.();
26017
26375
  });
26018
- const outcome = await Promise.race([work.then(() => "drained"), timeout]);
26376
+ const outcome2 = await Promise.race([work.then(() => "drained"), timeout]);
26019
26377
  if (timer) clearTimeout(timer);
26020
26378
  this.closed = true;
26021
- if (outcome === "timeout") this.queues.clear();
26379
+ if (outcome2 === "timeout") this.queues.clear();
26022
26380
  }
26023
26381
  /** Closes admission and drains accepted work. */
26024
26382
  async dispose() {
@@ -27388,7 +27746,7 @@ var registerLatticeRoutes = (app2, channelDeps, options = {}) => {
27388
27746
  label: (key) => key
27389
27747
  },
27390
27748
  messageReader: {
27391
- getCurrentMessages: ({ tenantId, assistantId, threadId, workspaceId, projectId }) => import_core51.agentInstanceManager.getAgent({
27749
+ getCurrentMessages: ({ tenantId, assistantId, threadId, workspaceId, projectId }) => import_core51.agentInstanceManager.getAgentForRead({
27392
27750
  tenant_id: tenantId,
27393
27751
  assistant_id: assistantId,
27394
27752
  thread_id: threadId,
@@ -29368,7 +29726,7 @@ function createAuditLoggerMiddleware() {
29368
29726
  }
29369
29727
 
29370
29728
  // src/index.ts
29371
- var import_core81 = require("@axiom-lattice/core");
29729
+ var import_core84 = require("@axiom-lattice/core");
29372
29730
 
29373
29731
  // src/swagger.ts
29374
29732
  var import_swagger = __toESM(require("@fastify/swagger"));
@@ -29435,6 +29793,7 @@ var configureSwagger = async (app2, customSwaggerConfig, customSwaggerUiConfig)
29435
29793
  // src/services/agent_task_consumer.ts
29436
29794
  var import_node_crypto27 = require("crypto");
29437
29795
  var import_core63 = require("@axiom-lattice/core");
29796
+ var import_protocols31 = require("@axiom-lattice/protocols");
29438
29797
  var handleAgentTask = async (taskRequest, retryCount = 0) => {
29439
29798
  const {
29440
29799
  assistant_id,
@@ -29452,7 +29811,8 @@ var handleAgentTask = async (taskRequest, retryCount = 0) => {
29452
29811
  console.log(
29453
29812
  `\u5F00\u59CB\u5904\u7406\u4EFB\u52A1 [assistant_id: ${assistant_id}, thread_id: ${thread_id}]`
29454
29813
  );
29455
- const agent = import_core63.agentInstanceManager.getAgent({ assistant_id, thread_id, tenant_id, workspace_id: runConfig?.workspaceId, project_id: runConfig?.projectId, custom_run_config: runConfig });
29814
+ const scope = (0, import_protocols31.resolveRunScope)(runConfig);
29815
+ const agent = import_core63.agentInstanceManager.getAgent({ assistant_id, thread_id, tenant_id, workspace_id: scope.workspaceId, project_id: scope.projectId, custom_run_config: runConfig });
29456
29816
  if (callback_event) {
29457
29817
  const callbackEvent = callback_event;
29458
29818
  const messageId = typeof input?.id === "string" && input.id !== "" ? input.id : (0, import_node_crypto27.randomUUID)();
@@ -29483,8 +29843,8 @@ var handleAgentTask = async (taskRequest, retryCount = 0) => {
29483
29843
  assistant_id: main_assistant_id ?? assistant_id,
29484
29844
  thread_id: main_thread_id,
29485
29845
  tenant_id: main_tenant_id,
29486
- workspace_id: runConfig?.workspaceId,
29487
- project_id: runConfig?.projectId
29846
+ workspace_id: scope.workspaceId,
29847
+ project_id: scope.projectId
29488
29848
  });
29489
29849
  if (mainAgent) {
29490
29850
  const messages = evt.state?.values?.messages;
@@ -29732,14 +30092,14 @@ _AgentTaskConsumer.agent_run_endpoint = "http://localhost:4001/api/runs";
29732
30092
  var AgentTaskConsumer = _AgentTaskConsumer;
29733
30093
 
29734
30094
  // src/index.ts
29735
- var import_core82 = require("@axiom-lattice/core");
30095
+ var import_core85 = require("@axiom-lattice/core");
29736
30096
 
29737
30097
  // src/channels/ChannelInfrastructure.ts
29738
30098
  var import_core65 = require("@axiom-lattice/core");
29739
30099
 
29740
30100
  // src/router/MessageRouter.ts
29741
30101
  var import_core64 = require("@axiom-lattice/core");
29742
- var import_protocols31 = require("@axiom-lattice/protocols");
30102
+ var import_protocols32 = require("@axiom-lattice/protocols");
29743
30103
  var import_crypto12 = require("crypto");
29744
30104
  var BindingNotFoundError = class extends Error {
29745
30105
  constructor(message) {
@@ -29774,10 +30134,10 @@ function clarifyText(clarify) {
29774
30134
  return ["```clarify", JSON.stringify({ questions: clarify.questions }), "```"].join("\n");
29775
30135
  }
29776
30136
  function exactDataValues(value, required, optional = []) {
29777
- return (0, import_protocols31.snapshotExactRecord)(value, required, optional);
30137
+ return (0, import_protocols32.snapshotExactRecord)(value, required, optional);
29778
30138
  }
29779
30139
  function uniqueNonemptyStrings(value) {
29780
- const snapshot = (0, import_protocols31.snapshotExactArray)(value);
30140
+ const snapshot = (0, import_protocols32.snapshotExactArray)(value);
29781
30141
  if (!snapshot || snapshot.length === 0 || snapshot.some((entry) => typeof entry !== "string" || entry.length === 0)) return void 0;
29782
30142
  const values = snapshot;
29783
30143
  return new Set(values).size === values.length ? values : void 0;
@@ -30289,7 +30649,7 @@ var MessageRouter = class {
30289
30649
 
30290
30650
  // src/channels/room/RoomChannelAdapter.ts
30291
30651
  var import_zod17 = require("zod");
30292
- var import_protocols32 = require("@axiom-lattice/protocols");
30652
+ var import_protocols33 = require("@axiom-lattice/protocols");
30293
30653
  var roomConfigSchema = import_zod17.z.object({}).strict();
30294
30654
  function createRoomChannelAdapter(writer) {
30295
30655
  return {
@@ -30350,7 +30710,7 @@ function exactStrings(value, keys2) {
30350
30710
  function exactValues2(value, required, optional = []) {
30351
30711
  try {
30352
30712
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
30353
- return (0, import_protocols32.snapshotExactRecord)(value, required, optional);
30713
+ return (0, import_protocols33.snapshotExactRecord)(value, required, optional);
30354
30714
  } catch {
30355
30715
  return void 0;
30356
30716
  }
@@ -30395,25 +30755,28 @@ async function prepareProjectTaskRuntime(runtime, log2) {
30395
30755
  }
30396
30756
 
30397
30757
  // src/index.ts
30398
- var import_protocols39 = require("@axiom-lattice/protocols");
30758
+ var import_protocols40 = require("@axiom-lattice/protocols");
30759
+ init_TopCallerRecovery();
30760
+ init_OrphanRecoveryRuntime();
30761
+ init_RecoveryCallerDeps();
30399
30762
  process.on("unhandledRejection", (reason, promise) => {
30400
30763
  console.error("\u672A\u5904\u7406\u7684Promise\u62D2\u7EDD:", reason);
30401
30764
  });
30402
30765
  var DEFAULT_LOGGER_CONFIG = {
30403
30766
  name: "default",
30404
30767
  description: "Default logger for lattice-gateway service",
30405
- type: import_protocols39.LoggerType.PINO,
30768
+ type: import_protocols40.LoggerType.PINO,
30406
30769
  serviceName: "lattice/gateway",
30407
30770
  loggerName: "lattice/gateway"
30408
30771
  };
30409
30772
  var loggerLattice = initializeLogger(DEFAULT_LOGGER_CONFIG);
30410
30773
  var logger7 = loggerLattice.client;
30411
30774
  function initializeLogger(config) {
30412
- if (import_core82.loggerLatticeManager.hasLattice("default")) {
30413
- import_core82.loggerLatticeManager.removeLattice("default");
30775
+ if (import_core85.loggerLatticeManager.hasLattice("default")) {
30776
+ import_core85.loggerLatticeManager.removeLattice("default");
30414
30777
  }
30415
- (0, import_core82.registerLoggerLattice)("default", config);
30416
- return (0, import_core82.getLoggerLattice)("default");
30778
+ (0, import_core85.registerLoggerLattice)("default", config);
30779
+ return (0, import_core85.getLoggerLattice)("default");
30417
30780
  }
30418
30781
  var app = (0, import_fastify.default)({
30419
30782
  logger: false,
@@ -30510,7 +30873,7 @@ app.setErrorHandler((error, request, reply) => {
30510
30873
  });
30511
30874
  function getConfiguredSandboxProvider() {
30512
30875
  const sandboxProviderType = process.env.SANDBOX_PROVIDER_TYPE || "microsandbox-remote";
30513
- return (0, import_core82.createSandboxProvider)({
30876
+ return (0, import_core85.createSandboxProvider)({
30514
30877
  type: sandboxProviderType,
30515
30878
  remoteBaseURL: process.env.SANDBOX_BASE_URL,
30516
30879
  microsandboxServiceBaseURL: process.env.MICROSANDBOX_SERVICE_BASE_URL,
@@ -30526,7 +30889,7 @@ function getConfiguredSandboxProvider() {
30526
30889
  }
30527
30890
  async function restoreMcpConnections() {
30528
30891
  try {
30529
- const storeLattice = (0, import_core82.getStoreLattice)("default", "mcp");
30892
+ const storeLattice = (0, import_core85.getStoreLattice)("default", "mcp");
30530
30893
  const store2 = storeLattice.store;
30531
30894
  if (!store2) {
30532
30895
  logger7.info("MCP store not configured, skipping connection restoration");
@@ -30539,8 +30902,8 @@ async function restoreMcpConnections() {
30539
30902
  logger7.info(`Restoring ${configs.length} MCP server connections...`);
30540
30903
  for (const config of configs) {
30541
30904
  try {
30542
- const connection = (0, import_core82.convertToConnection)(config.config);
30543
- import_core82.mcpManager.registerServer(config.tenantId, config.key, connection, {
30905
+ const connection = (0, import_core85.convertToConnection)(config.config);
30906
+ import_core85.mcpManager.registerServer(config.tenantId, config.key, connection, {
30544
30907
  timeoutMs: config.config.timeout,
30545
30908
  maxAttempts: config.config.retryAttempts,
30546
30909
  selectedTools: config.selectedTools
@@ -30549,10 +30912,10 @@ async function restoreMcpConnections() {
30549
30912
  logger7.warn(`Failed to prepare MCP server "${config.tenantId}/${config.key}"`, { error: err });
30550
30913
  }
30551
30914
  }
30552
- await import_core82.mcpManager.connectAll();
30915
+ await import_core85.mcpManager.connectAll();
30553
30916
  const results = await Promise.allSettled(
30554
30917
  configs.map(
30555
- (config) => import_core82.mcpManager.registerToolsToToolLattice(
30918
+ (config) => import_core85.mcpManager.registerToolsToToolLattice(
30556
30919
  config.tenantId,
30557
30920
  config.key,
30558
30921
  config.selectedTools
@@ -30590,9 +30953,9 @@ var start = async (config) => {
30590
30953
  let projectRoomRealtimeRuntime;
30591
30954
  if (projectRoomRealtimeMode === "single-gateway") {
30592
30955
  projectRoomRealtimeRuntime = createProjectRoomRealtimeRuntime({
30593
- tasks: (0, import_core82.getStoreLattice)("default", "task").store,
30594
- rooms: (0, import_core82.getStoreLattice)("default", "projectRoom").store,
30595
- memberships: (0, import_core82.getStoreLattice)("default", "projectBotMembership").store,
30956
+ tasks: (0, import_core85.getStoreLattice)("default", "task").store,
30957
+ rooms: (0, import_core85.getStoreLattice)("default", "projectRoom").store,
30958
+ memberships: (0, import_core85.getStoreLattice)("default", "projectBotMembership").store,
30596
30959
  log: { warn: (message, context) => logger7.warn(message, context) }
30597
30960
  });
30598
30961
  }
@@ -30606,7 +30969,7 @@ var start = async (config) => {
30606
30969
  const infrastructure = createChannelInfrastructure({
30607
30970
  adapterRegistry,
30608
30971
  getStore: ((kind) => getStore11("default", kind).store),
30609
- trustedDispatcher: (0, import_core82.createTrustedAgentMessageDispatcher)((scope) => import_core82.agentInstanceManager.getAgent(scope)),
30972
+ trustedDispatcher: (0, import_core85.createTrustedAgentMessageDispatcher)((scope) => import_core85.agentInstanceManager.getAgent(scope)),
30610
30973
  middlewares: [
30611
30974
  createDeduplicationMiddleware(),
30612
30975
  createRateLimitMiddleware(),
@@ -30617,7 +30980,7 @@ var start = async (config) => {
30617
30980
  });
30618
30981
  const bindingStore = infrastructure.bindingRegistry;
30619
30982
  const installationStore = infrastructure.installationStore;
30620
- (0, import_core81.setBindingRegistry)(bindingStore);
30983
+ (0, import_core84.setBindingRegistry)(bindingStore);
30621
30984
  const router = infrastructure.router;
30622
30985
  app.addHook("onClose", async () => router.dispose());
30623
30986
  channelDeps = {
@@ -30633,10 +30996,10 @@ var start = async (config) => {
30633
30996
  error: err instanceof Error ? err.message : String(err)
30634
30997
  });
30635
30998
  }
30636
- (0, import_core81.setEvalRunService)(evalRunner);
30999
+ (0, import_core84.setEvalRunService)(evalRunner);
30637
31000
  try {
30638
- const menuStore = (0, import_core82.getStoreLattice)("default", "menu").store;
30639
- (0, import_core81.setMenuRegistry)(menuStore);
31001
+ const menuStore = (0, import_core85.getStoreLattice)("default", "menu").store;
31002
+ (0, import_core84.setMenuRegistry)(menuStore);
30640
31003
  logger7.info("Menu registry initialized");
30641
31004
  } catch {
30642
31005
  }
@@ -30653,10 +31016,10 @@ var start = async (config) => {
30653
31016
  const { A2AAuthService: A2AAuthService2, parseEnvKeys: parseEnvKeys2 } = await Promise.resolve().then(() => (init_A2AAuthService(), A2AAuthService_exports));
30654
31017
  const { registerA2AStandardRoutes: registerA2AStandardRoutes2 } = await Promise.resolve().then(() => (init_a2a_standard(), a2a_standard_exports));
30655
31018
  const a2a = await Promise.resolve().then(() => (init_a2a(), a2a_exports));
30656
- const a2aKeyStore = (0, import_core82.getStoreLattice)("default", "a2aApiKey").store;
30657
- const assistantStore = (0, import_core82.getStoreLattice)("default", "assistant").store;
30658
- const projectStore = (0, import_core82.getStoreLattice)("default", "project").store;
30659
- const taskStore = (0, import_core82.getStoreLattice)("default", "task").store;
31019
+ const a2aKeyStore = (0, import_core85.getStoreLattice)("default", "a2aApiKey").store;
31020
+ const assistantStore = (0, import_core85.getStoreLattice)("default", "assistant").store;
31021
+ const projectStore = (0, import_core85.getStoreLattice)("default", "project").store;
31022
+ const taskStore = (0, import_core85.getStoreLattice)("default", "task").store;
30660
31023
  const authService = new A2AAuthService2({
30661
31024
  keyStore: a2aKeyStore,
30662
31025
  assistantStore,
@@ -30695,8 +31058,8 @@ var start = async (config) => {
30695
31058
  const { CollectionService: CollectionService2 } = await Promise.resolve().then(() => (init_collection_service(), collection_service_exports));
30696
31059
  openLattice2.register(createKbProvider2(new CollectionService2()));
30697
31060
  openLattice2.register(createOpenSandboxProvider2());
30698
- const threadStore = (0, import_core82.getStoreLattice)("default", "thread").store;
30699
- const assistantStore = (0, import_core82.getStoreLattice)("default", "assistant").store;
31061
+ const threadStore = (0, import_core85.getStoreLattice)("default", "thread").store;
31062
+ const assistantStore = (0, import_core85.getStoreLattice)("default", "assistant").store;
30700
31063
  openLattice2.register(
30701
31064
  createAgentProvider2({
30702
31065
  threadStore,
@@ -30719,17 +31082,17 @@ var start = async (config) => {
30719
31082
  error: err instanceof Error ? err.message : String(err)
30720
31083
  });
30721
31084
  }
30722
- if (!import_core82.sandboxLatticeManager.hasLattice("default")) {
30723
- import_core82.sandboxLatticeManager.registerLattice("default", getConfiguredSandboxProvider());
31085
+ if (!import_core85.sandboxLatticeManager.hasLattice("default")) {
31086
+ import_core85.sandboxLatticeManager.registerLattice("default", getConfiguredSandboxProvider());
30724
31087
  logger7.info("Registered sandbox manager from env configuration");
30725
31088
  }
30726
31089
  try {
30727
31090
  const { ResourceController: ResourceController2 } = await Promise.resolve().then(() => (init_resources(), resources_exports));
30728
- const sharedResourceStore = (0, import_core82.getStoreLattice)("default", "sharedResource").store;
30729
- const cache = new import_core82.TokenCache();
31091
+ const sharedResourceStore = (0, import_core85.getStoreLattice)("default", "sharedResource").store;
31092
+ const cache = new import_core85.TokenCache();
30730
31093
  const resourceController = new ResourceController2({
30731
31094
  store: sharedResourceStore,
30732
- sandboxManager: import_core82.sandboxLatticeManager,
31095
+ sandboxManager: import_core85.sandboxLatticeManager,
30733
31096
  cache,
30734
31097
  logger: logger7
30735
31098
  });
@@ -30757,6 +31120,25 @@ var start = async (config) => {
30757
31120
  if (routes.projectTaskRuntime) {
30758
31121
  await prepareProjectTaskRuntime(routes.projectTaskRuntime, logger7);
30759
31122
  }
31123
+ if (process.env.AXIOM_TASK_ORPHAN_RECOVERY === "true") {
31124
+ try {
31125
+ const { createOrphanRecoveryRuntime: createOrphanRecoveryRuntime2 } = await Promise.resolve().then(() => (init_OrphanRecoveryRuntime(), OrphanRecoveryRuntime_exports));
31126
+ const { createRecoveryCallerDeps: createRecoveryCallerDeps2 } = await Promise.resolve().then(() => (init_RecoveryCallerDeps(), RecoveryCallerDeps_exports));
31127
+ const taskStore = (0, import_core85.getStoreLattice)("default", "task").store;
31128
+ const workItemStore = (0, import_core85.getStoreLattice)("default", "taskWorkItem").store;
31129
+ const tenantStore = (0, import_core85.getStoreLattice)("default", "tenant").store;
31130
+ const runtime = createOrphanRecoveryRuntime2({
31131
+ taskStore,
31132
+ workItemStore,
31133
+ tenantStore,
31134
+ ...createRecoveryCallerDeps2(),
31135
+ log: logger7
31136
+ });
31137
+ await runtime.recoverAll();
31138
+ } catch (err) {
31139
+ logger7.warn("Task orphan recovery failed", { error: err instanceof Error ? err.message : String(err) });
31140
+ }
31141
+ }
30760
31142
  await app.listen({ port: target_port, host: "0.0.0.0" });
30761
31143
  logger7.info(`Lattice Gateway is running on port: ${target_port}`);
30762
31144
  const queueServiceConfig = config?.queueServiceConfig;
@@ -30767,13 +31149,6 @@ var start = async (config) => {
30767
31149
  agentTaskConsumer.startPollingQueue();
30768
31150
  }
30769
31151
  }
30770
- if (process.env.AXIOM_RESTORE_PENDING_ON_STARTUP === "true") {
30771
- import_core82.agentInstanceManager.restore().then((stats) => {
30772
- logger7.info(`Agent recovery complete: ${stats.restored} threads restored, ${stats.errors} errors`);
30773
- }).catch((error) => {
30774
- logger7.error("Agent recovery failed", { error });
30775
- });
30776
- }
30777
31152
  restoreMcpConnections().catch((error) => {
30778
31153
  logger7.error("MCP connection restoration failed", { error });
30779
31154
  });
@@ -30791,6 +31166,12 @@ var LatticeGateway = {
30791
31166
  };
30792
31167
  // Annotate the CommonJS export names for ESM import in node:
30793
31168
  0 && (module.exports = {
30794
- LatticeGateway
31169
+ LatticeGateway,
31170
+ createOrphanRecoveryRuntime,
31171
+ createRecoveryCallerDeps,
31172
+ recoverTask,
31173
+ recoverTopCaller,
31174
+ resolveTopCaller,
31175
+ runOrphanRecovery
30795
31176
  });
30796
31177
  //# sourceMappingURL=index.js.map