@axiom-lattice/core 9.0.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  resolvePath,
24
24
  unregisterWorkflowRun,
25
25
  validateDSL
26
- } from "./chunk-BKUBS44O.mjs";
26
+ } from "./chunk-AZAZEYKO.mjs";
27
27
  import {
28
28
  parseYaml,
29
29
  toJsonSchema,
@@ -4275,6 +4275,7 @@ var InMemoryTaskStore = class {
4275
4275
  if (filter2.ownerId) results = results.filter((t) => t.ownerId === filter2.ownerId);
4276
4276
  if (filter2.status) results = results.filter((t) => t.status === filter2.status);
4277
4277
  if (filter2.priority) results = results.filter((t) => t.priority === filter2.priority);
4278
+ if (filter2.threadId) results = results.filter((t) => t.context?.thread_id === filter2.threadId);
4278
4279
  if (filter2.workspaceId) results = results.filter((t) => t.workspaceId === filter2.workspaceId);
4279
4280
  if (filter2.projectId === null) results = results.filter((task) => !task.projectId || task.projectId === "default");
4280
4281
  else if (filter2.projectId !== void 0) results = results.filter((task) => task.projectId === filter2.projectId);
@@ -5715,6 +5716,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
5715
5716
  }
5716
5717
  // ===== Recovery =====
5717
5718
  async restore() {
5719
+ this.clearAllTimers();
5718
5720
  try {
5719
5721
  const requeued = await this.storage.requeueStaleRunning(STALE_RUNNING_MS);
5720
5722
  if (requeued > 0) {
@@ -5728,41 +5730,89 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
5728
5730
  error
5729
5731
  );
5730
5732
  }
5733
+ const restored = await this.reconcileTimers(true);
5734
+ console.log(`[Scheduler] Restored ${restored} tasks`);
5735
+ return restored;
5736
+ }
5737
+ /**
5738
+ * Reconcile this replica's timers with the shared schedule store.
5739
+ *
5740
+ * @remarks Safe to call periodically and on every replica. Execution still
5741
+ * goes through `claimScheduledRun`, so duplicate timer fires execute once.
5742
+ */
5743
+ async reconcile() {
5744
+ try {
5745
+ await this.storage.requeueStaleRunning(STALE_RUNNING_MS);
5746
+ } catch (error) {
5747
+ console.error(
5748
+ "[Scheduler] Failed to requeue stale running tasks during reconcile:",
5749
+ error
5750
+ );
5751
+ }
5752
+ return this.reconcileTimers(false);
5753
+ }
5754
+ clearTimer(taskId) {
5755
+ const timer = this.timers.get(taskId);
5756
+ if (!timer) return;
5757
+ clearTimeout(timer.timerId);
5758
+ this.timers.delete(taskId);
5759
+ }
5760
+ clearAllTimers() {
5761
+ for (const timer of this.timers.values()) clearTimeout(timer.timerId);
5762
+ this.timers.clear();
5763
+ }
5764
+ async reconcileTimers(recomputeCronNextRun) {
5731
5765
  const activeTasks = await this.storage.getActiveTasks();
5732
- let restored = 0;
5766
+ const activeById = new Map(activeTasks.map((task) => [task.taskId, task]));
5767
+ for (const taskId of [...this.timers.keys()]) {
5768
+ const task = activeById.get(taskId);
5769
+ if (!task || task.status === ScheduledTaskStatus2.PAUSED) {
5770
+ this.clearTimer(taskId);
5771
+ }
5772
+ }
5773
+ let reconciled = 0;
5733
5774
  for (const task of activeTasks) {
5734
5775
  if (!this.handlers.has(task.taskType)) {
5735
5776
  console.warn(
5736
- `[Scheduler] No handler for task type ${task.taskType}, skipping restore for task ${task.taskId}`
5777
+ `[Scheduler] No handler for task type ${task.taskType}, skipping reconcile for task ${task.taskId}`
5737
5778
  );
5779
+ this.clearTimer(task.taskId);
5738
5780
  continue;
5739
5781
  }
5740
5782
  if (task.status === ScheduledTaskStatus2.PAUSED) {
5783
+ this.clearTimer(task.taskId);
5741
5784
  continue;
5742
5785
  }
5743
5786
  if (task.executionType === ScheduleExecutionType2.ONCE) {
5744
- if (task.executeAt && task.executeAt <= Date.now()) {
5745
- console.log(
5746
- `[Scheduler] Executing overdue one-time task: ${task.taskId}`
5747
- );
5748
- this.executeTask(task);
5749
- } else {
5787
+ if (task.executeAt !== void 0 && task.executeAt <= Date.now()) {
5788
+ this.clearTimer(task.taskId);
5789
+ void this.executeTask(task);
5790
+ } else if (task.executeAt !== void 0) {
5750
5791
  this.scheduleTimer(task);
5751
5792
  }
5752
5793
  } else if (task.executionType === ScheduleExecutionType2.CRON) {
5753
- const nextRunAt = getNextCronTime(task.cronExpression, /* @__PURE__ */ new Date(), task.timezone);
5754
- await this.storage.update(task.taskId, {
5755
- nextRunAt: nextRunAt.getTime()
5756
- });
5757
- const updatedTask = await this.storage.get(task.taskId);
5758
- if (updatedTask) {
5759
- this.scheduleTimer(updatedTask);
5794
+ let nextRunAt = task.nextRunAt;
5795
+ if (recomputeCronNextRun || nextRunAt === void 0) {
5796
+ nextRunAt = getNextCronTime(task.cronExpression, /* @__PURE__ */ new Date(), task.timezone).getTime();
5797
+ await this.storage.update(task.taskId, { nextRunAt });
5798
+ const updated = await this.storage.get(task.taskId);
5799
+ if (!updated) continue;
5800
+ if (updated.nextRunAt !== void 0 && updated.nextRunAt <= Date.now()) {
5801
+ this.clearTimer(updated.taskId);
5802
+ void this.executeTask(updated);
5803
+ } else {
5804
+ this.scheduleTimer(updated);
5805
+ }
5806
+ } else if (nextRunAt <= Date.now()) {
5807
+ this.clearTimer(task.taskId);
5808
+ void this.executeTask(task);
5809
+ } else {
5810
+ this.scheduleTimer(task);
5760
5811
  }
5761
5812
  }
5762
- restored++;
5813
+ reconciled++;
5763
5814
  }
5764
- console.log(`[Scheduler] Restored ${restored} tasks`);
5765
- return restored;
5815
+ return reconciled;
5766
5816
  }
5767
5817
  // ===== Storage =====
5768
5818
  setStorage(storage) {
@@ -5773,6 +5823,7 @@ var _DefaultScheduleClient = class _DefaultScheduleClient {
5773
5823
  }
5774
5824
  // ===== Private Methods =====
5775
5825
  scheduleTimer(task) {
5826
+ this.clearTimer(task.taskId);
5776
5827
  const targetTime = task.executionType === ScheduleExecutionType2.CRON ? task.nextRunAt : task.executeAt;
5777
5828
  if (targetTime === void 0) {
5778
5829
  console.error(`[Scheduler] No execution time for task: ${task.taskId}`);
@@ -6041,6 +6092,9 @@ var ScheduleLatticeManager = class _ScheduleLatticeManager extends BaseLatticeMa
6041
6092
  // Recovery
6042
6093
  restore: async () => {
6043
6094
  return scheduleClient.restore();
6095
+ },
6096
+ reconcile: async () => {
6097
+ return scheduleClient.reconcile?.() ?? 0;
6044
6098
  }
6045
6099
  };
6046
6100
  this.register(key5, scheduleLattice);
@@ -20657,6 +20711,19 @@ async function resolveSandboxPluginConnections(type, config, runConfig) {
20657
20711
  return { connection: connections[0]?.config, connections };
20658
20712
  }
20659
20713
 
20714
+ // src/sandbox_plugin/sandboxRunConfig.ts
20715
+ function sandboxRunConfigFrom(exeConfig) {
20716
+ const config = exeConfig;
20717
+ const raw = config?.configurable?.runConfig ?? {};
20718
+ return {
20719
+ tenantId: typeof raw.tenantId === "string" && raw.tenantId.length > 0 ? raw.tenantId : void 0,
20720
+ assistantId: typeof raw.assistant_id === "string" && raw.assistant_id.length > 0 ? raw.assistant_id : void 0,
20721
+ threadId: typeof raw.thread_id === "string" && raw.thread_id.length > 0 ? raw.thread_id : void 0,
20722
+ workspaceId: typeof raw.workspaceId === "string" && raw.workspaceId.length > 0 ? raw.workspaceId : void 0,
20723
+ projectId: typeof raw.projectId === "string" && raw.projectId.length > 0 ? raw.projectId : void 0
20724
+ };
20725
+ }
20726
+
20660
20727
  // src/mcp_lattice/mcpUi.ts
20661
20728
  import { DynamicStructuredTool } from "@langchain/core/tools";
20662
20729
  var isObj = (v) => typeof v === "object" && v !== null;
@@ -20737,6 +20804,145 @@ function wrapMcpToolWithUi(raw, ref) {
20737
20804
  });
20738
20805
  }
20739
20806
 
20807
+ // src/mcp_lattice/mcpUiScope.ts
20808
+ import { createHmac, hkdfSync, randomUUID as randomUUID7, timingSafeEqual } from "crypto";
20809
+ var MIN_SECRET_LENGTH = 32;
20810
+ var MAX_PAYLOAD_BYTES = 2048;
20811
+ var MAX_TOKEN_LENGTH = 4096;
20812
+ var SCOPE_KEY_INFO = "mcp-ui-scope";
20813
+ var warnedMessages = /* @__PURE__ */ new Set();
20814
+ function getMcpUiScopeSecret() {
20815
+ const explicit = process.env.MCP_UI_SCOPE_SECRET;
20816
+ if (explicit) {
20817
+ return explicit.length >= MIN_SECRET_LENGTH ? explicit : void 0;
20818
+ }
20819
+ const encryptionKey = process.env.LATTICE_ENCRYPTION_KEY;
20820
+ if (!encryptionKey) return void 0;
20821
+ return Buffer.from(
20822
+ hkdfSync("sha256", encryptionKey, "", SCOPE_KEY_INFO, 32)
20823
+ ).toString("base64url");
20824
+ }
20825
+ function warnOnce(message) {
20826
+ if (warnedMessages.has(message)) return;
20827
+ warnedMessages.add(message);
20828
+ console.warn(JSON.stringify({ event: "mcp-ui-scope:warning", message }));
20829
+ }
20830
+ function isRecord8(value) {
20831
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20832
+ }
20833
+ function signMcpUiScope(input, secret = getMcpUiScopeSecret()) {
20834
+ if (!secret || secret.length < MIN_SECRET_LENGTH) {
20835
+ warnOnce(
20836
+ "no usable MCP UI scope signing secret (set MCP_UI_SCOPE_SECRET or LATTICE_ENCRYPTION_KEY)"
20837
+ );
20838
+ return void 0;
20839
+ }
20840
+ if (typeof input.tid !== "string" || input.tid === "" || typeof input.plugin !== "string" || input.plugin === "" || typeof input.resource !== "string" || input.resource === "") {
20841
+ warnOnce("scope identity is missing tid/plugin/resource");
20842
+ return void 0;
20843
+ }
20844
+ const optionalStrings = [input.thid, input.aid, input.wid, input.pid, input.ck];
20845
+ if (optionalStrings.some(
20846
+ (value) => value !== void 0 && typeof value !== "string"
20847
+ )) {
20848
+ warnOnce("scope optional identity fields must be strings");
20849
+ return void 0;
20850
+ }
20851
+ if (input.iat !== void 0 && (typeof input.iat !== "number" || !Number.isFinite(input.iat))) {
20852
+ warnOnce("scope iat must be a finite number");
20853
+ return void 0;
20854
+ }
20855
+ if (input.jti !== void 0 && typeof input.jti !== "string") {
20856
+ warnOnce("scope jti must be a string");
20857
+ return void 0;
20858
+ }
20859
+ const payload = {
20860
+ v: 1,
20861
+ tid: input.tid,
20862
+ thid: input.thid,
20863
+ aid: input.aid,
20864
+ wid: input.wid,
20865
+ pid: input.pid,
20866
+ plugin: input.plugin,
20867
+ resource: input.resource,
20868
+ ck: input.ck === "" ? void 0 : input.ck,
20869
+ iat: input.iat ?? Math.floor(Date.now() / 1e3),
20870
+ jti: input.jti ?? randomUUID7()
20871
+ };
20872
+ const json = JSON.stringify(payload);
20873
+ if (Buffer.byteLength(json, "utf8") > MAX_PAYLOAD_BYTES) {
20874
+ warnOnce("scope payload exceeds 2048 bytes");
20875
+ return void 0;
20876
+ }
20877
+ const body = Buffer.from(json, "utf8").toString("base64url");
20878
+ const sig = createHmac("sha256", secret).update(body).digest("base64url");
20879
+ const token = `${body}.${sig}`;
20880
+ if (token.length > MAX_TOKEN_LENGTH) {
20881
+ warnOnce("signed scope token exceeds 4096 characters");
20882
+ return void 0;
20883
+ }
20884
+ return token;
20885
+ }
20886
+ function verifyMcpUiScope(token, secret = getMcpUiScopeSecret()) {
20887
+ if (!token || token.length > MAX_TOKEN_LENGTH || !secret || secret.length < MIN_SECRET_LENGTH) {
20888
+ return null;
20889
+ }
20890
+ const parts = token.split(".");
20891
+ if (parts.length !== 2) return null;
20892
+ const [body, sig] = parts;
20893
+ if (!body || !sig) return null;
20894
+ try {
20895
+ const expected = createHmac("sha256", secret).update(body).digest("base64url");
20896
+ const expectedBuf = Buffer.from(expected, "utf8");
20897
+ const sigBuf = Buffer.from(sig, "utf8");
20898
+ if (expectedBuf.length !== sigBuf.length || !timingSafeEqual(expectedBuf, sigBuf)) {
20899
+ return null;
20900
+ }
20901
+ } catch {
20902
+ return null;
20903
+ }
20904
+ let parsed;
20905
+ try {
20906
+ parsed = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
20907
+ } catch {
20908
+ return null;
20909
+ }
20910
+ if (!isRecord8(parsed) || parsed.v !== 1) return null;
20911
+ const tid = parsed.tid;
20912
+ const plugin = parsed.plugin;
20913
+ const resource = parsed.resource;
20914
+ const thid = parsed.thid;
20915
+ const aid = parsed.aid;
20916
+ const wid = parsed.wid;
20917
+ const pid = parsed.pid;
20918
+ const ck = parsed.ck;
20919
+ const iat = parsed.iat;
20920
+ const jti = parsed.jti;
20921
+ if (typeof tid !== "string" || tid === "") return null;
20922
+ if (typeof plugin !== "string" || plugin === "") return null;
20923
+ if (typeof resource !== "string" || resource === "") return null;
20924
+ if (thid !== void 0 && typeof thid !== "string") return null;
20925
+ if (aid !== void 0 && typeof aid !== "string") return null;
20926
+ if (wid !== void 0 && typeof wid !== "string") return null;
20927
+ if (pid !== void 0 && typeof pid !== "string") return null;
20928
+ if (ck !== void 0 && (typeof ck !== "string" || ck === "")) return null;
20929
+ if (typeof iat !== "number" || !Number.isFinite(iat)) return null;
20930
+ if (typeof jti !== "string") return null;
20931
+ return {
20932
+ v: 1,
20933
+ tid,
20934
+ ...thid === void 0 ? {} : { thid },
20935
+ ...aid === void 0 ? {} : { aid },
20936
+ ...wid === void 0 ? {} : { wid },
20937
+ ...pid === void 0 ? {} : { pid },
20938
+ plugin,
20939
+ resource,
20940
+ ...ck === void 0 ? {} : { ck },
20941
+ iat,
20942
+ jti
20943
+ };
20944
+ }
20945
+
20740
20946
  // src/sandbox_plugin/SandboxPluginCompiler.ts
20741
20947
  var EMPTY_CONFIG_SCHEMA = Object.freeze({ type: "object", properties: Object.freeze({}) });
20742
20948
  var STANDARD_CONNECTION_SCHEMA = Object.freeze({
@@ -20751,20 +20957,9 @@ var STANDARD_CONNECTION_DEFAULT_CONFIG = Object.freeze({
20751
20957
  connectAll: false
20752
20958
  });
20753
20959
  var EMPTY_DEFAULT_CONFIG = Object.freeze({});
20754
- function isRecord8(value) {
20960
+ function isRecord9(value) {
20755
20961
  return typeof value === "object" && value !== null && !Array.isArray(value);
20756
20962
  }
20757
- function runConfigFrom(exeConfig) {
20758
- const c = exeConfig;
20759
- const r = c?.configurable?.runConfig ?? {};
20760
- return {
20761
- tenantId: typeof r.tenantId === "string" ? r.tenantId : void 0,
20762
- assistantId: typeof r.assistant_id === "string" ? r.assistant_id : void 0,
20763
- threadId: typeof r.thread_id === "string" ? r.thread_id : void 0,
20764
- workspaceId: typeof r.workspaceId === "string" ? r.workspaceId : void 0,
20765
- projectId: typeof r.projectId === "string" ? r.projectId : void 0
20766
- };
20767
- }
20768
20963
  function compileSandboxPlugin(args) {
20769
20964
  const { manifest, executor, tenantId: tenantId2 } = args;
20770
20965
  const plugin = {
@@ -20781,11 +20976,10 @@ function compileSandboxPlugin(args) {
20781
20976
  defaultConfig: manifest.defaultConfig ?? (manifest.connection ? STANDARD_CONNECTION_DEFAULT_CONFIG : EMPTY_DEFAULT_CONFIG)
20782
20977
  },
20783
20978
  middleware: (config) => {
20784
- const runConfigFor = (exeConfig) => runConfigFrom(exeConfig);
20785
20979
  const tools = manifest.tools.map(
20786
20980
  (t) => tool40(
20787
20981
  async (input, exeConfig) => {
20788
- const runConfig = runConfigFor(exeConfig);
20982
+ const runConfig = sandboxRunConfigFrom(exeConfig);
20789
20983
  const resolution = await resolveConnection(manifest.type, config, runConfig);
20790
20984
  const result = await executor.invoke({
20791
20985
  manifest,
@@ -20804,7 +20998,24 @@ function compileSandboxPlugin(args) {
20804
20998
  });
20805
20999
  if (!result.ok) return result.error ?? "sandbox plugin execution failed";
20806
21000
  const text = handlerResultText(result);
20807
- const ref = t.ui ? { kind: "plugin", pluginType: manifest.type, resource: t.ui.resource, displayMode: t.ui.displayMode ?? "inline" } : null;
21001
+ const ui = t.ui;
21002
+ const scope = ui ? signMcpUiScope({
21003
+ tid: runConfig.tenantId || tenantId2,
21004
+ thid: runConfig.threadId,
21005
+ aid: runConfig.assistantId,
21006
+ wid: runConfig.workspaceId,
21007
+ pid: runConfig.projectId,
21008
+ plugin: manifest.type,
21009
+ resource: ui.resource,
21010
+ ck: resolution.connections?.[0]?.key
21011
+ }) : void 0;
21012
+ const ref = ui ? {
21013
+ kind: "plugin",
21014
+ pluginType: manifest.type,
21015
+ resource: ui.resource,
21016
+ displayMode: ui.displayMode ?? "inline",
21017
+ ...scope ? { scope } : {}
21018
+ } : null;
20808
21019
  return ref ? appendUiFence(text, ref) : text;
20809
21020
  },
20810
21021
  { name: t.name, description: t.description, schema: jsonSchemaToZod(t.schema) }
@@ -20841,11 +21052,11 @@ async function runConnectionHandler(executor, manifest, handler, config, tenantI
20841
21052
  return { ok: false, message: result.error ?? "connection test failed" };
20842
21053
  }
20843
21054
  const value = result.result;
20844
- if (isRecord8(value) && typeof value.ok === "boolean" && typeof value.message === "string") {
21055
+ if (isRecord9(value) && typeof value.ok === "boolean" && typeof value.message === "string") {
20845
21056
  return {
20846
21057
  ok: value.ok,
20847
21058
  message: value.message,
20848
- details: isRecord8(value.details) ? value.details : void 0
21059
+ details: isRecord9(value.details) ? value.details : void 0
20849
21060
  };
20850
21061
  }
20851
21062
  return { ok: false, message: result.error ?? "connection test returned an invalid result" };
@@ -21580,23 +21791,23 @@ function toolName(tool67) {
21580
21791
  return typeof tool67.name === "string" ? tool67.name : void 0;
21581
21792
  }
21582
21793
  function schemaHasConnectionKey(schema6) {
21583
- const definition = isRecord9(schema6._def) ? schema6._def : void 0;
21794
+ const definition = isRecord10(schema6._def) ? schema6._def : void 0;
21584
21795
  const shape = definition?.shape;
21585
21796
  const fields = typeof shape === "function" ? shape() : shape;
21586
- return isRecord9(fields) && Object.prototype.hasOwnProperty.call(fields, "connectionKey");
21797
+ return isRecord10(fields) && Object.prototype.hasOwnProperty.call(fields, "connectionKey");
21587
21798
  }
21588
21799
  function hasConnectionKeySchema(tool67) {
21589
- if (!isRecord9(tool67) || !isRecord9(tool67.schema)) return false;
21800
+ if (!isRecord10(tool67) || !isRecord10(tool67.schema)) return false;
21590
21801
  if (schemaHasConnectionKey(tool67.schema)) return true;
21591
- const definition = isRecord9(tool67.schema._def) ? tool67.schema._def : void 0;
21802
+ const definition = isRecord10(tool67.schema._def) ? tool67.schema._def : void 0;
21592
21803
  if (Array.isArray(definition?.options) && definition.options.length > 0) {
21593
21804
  return definition.options.every(
21594
- (option) => isRecord9(option) && schemaHasConnectionKey(option)
21805
+ (option) => isRecord10(option) && schemaHasConnectionKey(option)
21595
21806
  );
21596
21807
  }
21597
21808
  return false;
21598
21809
  }
21599
- function isRecord9(value) {
21810
+ function isRecord10(value) {
21600
21811
  return typeof value === "object" && value !== null && !Array.isArray(value);
21601
21812
  }
21602
21813
  var CapabilityToolRegistry = class {
@@ -21688,17 +21899,17 @@ var CapabilityToolRegistry = class {
21688
21899
  // src/middlewares/capabilityGuardMiddleware.ts
21689
21900
  import { ToolMessage as ToolMessage5 } from "@langchain/core/messages";
21690
21901
  import { createMiddleware as createMiddleware13 } from "langchain";
21691
- function isRecord10(value) {
21902
+ function isRecord11(value) {
21692
21903
  return typeof value === "object" && value !== null && !Array.isArray(value);
21693
21904
  }
21694
21905
  function capabilityRuntimeFromRequest(request) {
21695
- if (!isRecord10(request) || !isRecord10(request.runtime)) return void 0;
21906
+ if (!isRecord11(request) || !isRecord11(request.runtime)) return void 0;
21696
21907
  const configurable = request.runtime.configurable;
21697
21908
  const context = request.runtime.context;
21698
- const runConfig = isRecord10(configurable) && isRecord10(configurable.runConfig) ? configurable.runConfig : isRecord10(context) && isRecord10(context.runConfig) ? context.runConfig : void 0;
21909
+ const runConfig = isRecord11(configurable) && isRecord11(configurable.runConfig) ? configurable.runConfig : isRecord11(context) && isRecord11(context.runConfig) ? context.runConfig : void 0;
21699
21910
  if (!runConfig) return void 0;
21700
21911
  const value = runConfig.capabilityRuntime;
21701
- if (!isRecord10(value) || typeof value.revision !== "string" || !isRecord10(value.middleware)) {
21912
+ if (!isRecord11(value) || typeof value.revision !== "string" || !isRecord11(value.middleware)) {
21702
21913
  return void 0;
21703
21914
  }
21704
21915
  return value;
@@ -21710,10 +21921,10 @@ function hasActiveRuntimePolicy(runtime) {
21710
21921
  return Object.keys(runtime.middleware).length > 0;
21711
21922
  }
21712
21923
  function tenantIdFromRequest(request) {
21713
- if (!isRecord10(request) || !isRecord10(request.runtime)) return void 0;
21924
+ if (!isRecord11(request) || !isRecord11(request.runtime)) return void 0;
21714
21925
  const configurable = request.runtime.configurable;
21715
21926
  const context = request.runtime.context;
21716
- const runConfig = isRecord10(configurable) && isRecord10(configurable.runConfig) ? configurable.runConfig : isRecord10(context) && isRecord10(context.runConfig) ? context.runConfig : void 0;
21927
+ const runConfig = isRecord11(configurable) && isRecord11(configurable.runConfig) ? configurable.runConfig : isRecord11(context) && isRecord11(context.runConfig) ? context.runConfig : void 0;
21717
21928
  return runConfig && typeof runConfig.tenantId === "string" ? runConfig.tenantId : void 0;
21718
21929
  }
21719
21930
  async function standardConnectionAllowed(request, capabilityType, config) {
@@ -21721,8 +21932,8 @@ async function standardConnectionAllowed(request, capabilityType, config) {
21721
21932
  const hasConnectAll = Object.prototype.hasOwnProperty.call(config, "connectAll");
21722
21933
  if (!hasConnections && (!hasConnectAll || config.connectAll !== true)) return false;
21723
21934
  const tenantId2 = tenantIdFromRequest(request);
21724
- const resource = isRecord10(request.toolCall) && isRecord10(request.toolCall.args) ? request.toolCall.args.connectionKey : void 0;
21725
- const hasConnectionKey = isRecord10(request.toolCall) && isRecord10(request.toolCall.args) && Object.prototype.hasOwnProperty.call(
21935
+ const resource = isRecord11(request.toolCall) && isRecord11(request.toolCall.args) ? request.toolCall.args.connectionKey : void 0;
21936
+ const hasConnectionKey = isRecord11(request.toolCall) && isRecord11(request.toolCall.args) && Object.prototype.hasOwnProperty.call(
21726
21937
  request.toolCall.args,
21727
21938
  "connectionKey"
21728
21939
  );
@@ -21788,10 +21999,10 @@ function createCapabilityGuardMiddleware(registry4) {
21788
21999
  toolName: toolName2
21789
22000
  });
21790
22001
  }
21791
- const standardConfig = isRecord10(policy.config) ? policy.config : {};
22002
+ const standardConfig = isRecord11(policy.config) ? policy.config : {};
21792
22003
  if (registry4.isStandardConnectionTool(toolName2) && !await standardConnectionAllowed(request, metadata.capabilityType, standardConfig)) {
21793
22004
  const args2 = request.toolCall.args;
21794
- const resource = isRecord10(args2) && typeof args2.connectionKey === "string" ? args2.connectionKey : void 0;
22005
+ const resource = isRecord11(args2) && typeof args2.connectionKey === "string" ? args2.connectionKey : void 0;
21795
22006
  return denialMessage(request.toolCall, {
21796
22007
  code: "RESOURCE_NOT_ALLOWED",
21797
22008
  message: typeof resource === "string" ? `Resource '${resource}' is not allowed by the capability policy` : "Resource selector 'connectionKey' must be a permitted string",
@@ -21804,8 +22015,8 @@ function createCapabilityGuardMiddleware(registry4) {
21804
22015
  const selector = metadata.resourceSelector;
21805
22016
  const args = request.toolCall.args;
21806
22017
  if (selector) {
21807
- const resource = isRecord10(args) ? args[selector.argumentField] : void 0;
21808
- const config = isRecord10(policy.config) ? policy.config : {};
22018
+ const resource = isRecord11(args) ? args[selector.argumentField] : void 0;
22019
+ const config = isRecord11(policy.config) ? policy.config : {};
21809
22020
  const hasExplicitResources = Object.prototype.hasOwnProperty.call(config, selector.configField);
21810
22021
  const allowsAll = !hasExplicitResources && selector.allowAllField !== void 0 && config[selector.allowAllField] === true;
21811
22022
  const allowedResources = config[selector.configField];
@@ -22397,7 +22608,17 @@ import {
22397
22608
  import { resolveRunScope } from "@axiom-lattice/protocols";
22398
22609
 
22399
22610
  // src/services/Agent.ts
22400
- import { randomUUID as randomUUID8 } from "crypto";
22611
+ import { randomUUID as randomUUID9 } from "crypto";
22612
+
22613
+ // src/services/agentRecursionLimit.ts
22614
+ var DEFAULT_AGENT_RECURSION_LIMIT = 500;
22615
+ function readAgentRecursionLimit(env = process.env) {
22616
+ const raw = env.AGENT_RECURSION_LIMIT;
22617
+ if (raw === void 0 || raw.trim() === "") return DEFAULT_AGENT_RECURSION_LIMIT;
22618
+ const parsed = Number(raw);
22619
+ if (!Number.isFinite(parsed) || parsed < 1) return DEFAULT_AGENT_RECURSION_LIMIT;
22620
+ return Math.floor(parsed);
22621
+ }
22401
22622
 
22402
22623
  // src/services/DelegationCancellation.ts
22403
22624
  var DelegationCancellationRegistry = class {
@@ -23005,7 +23226,7 @@ import { Command as Command2 } from "@langchain/langgraph";
23005
23226
 
23006
23227
  // src/services/agentInterrupts.ts
23007
23228
  var FENCE = /^```([A-Za-z0-9_-]+)\n([\s\S]*?)\n```$/;
23008
- function isRecord11(value) {
23229
+ function isRecord12(value) {
23009
23230
  return typeof value === "object" && value !== null && !Array.isArray(value);
23010
23231
  }
23011
23232
  function parseFence(value) {
@@ -23019,7 +23240,7 @@ function parseFence(value) {
23019
23240
  }
23020
23241
  }
23021
23242
  function isTaskReview(value) {
23022
- return isRecord11(value) && (value.type === "task_review" || value.kind === "task_review" || "task_review" in value);
23243
+ return isRecord12(value) && (value.type === "task_review" || value.kind === "task_review" || "task_review" in value);
23023
23244
  }
23024
23245
  function isOfficialInterruptId(interruptId) {
23025
23246
  return /^[a-f0-9]{32}$/i.test(interruptId);
@@ -23034,28 +23255,28 @@ function hasExpectedInterrupt(interrupts, expectedInterruptId) {
23034
23255
  ).length === 1;
23035
23256
  }
23036
23257
  function normalizeAgentInterrupts(state, threadId) {
23037
- if (!isRecord11(state) || !Array.isArray(state.tasks)) return [];
23258
+ if (!isRecord12(state) || !Array.isArray(state.tasks)) return [];
23038
23259
  const result = [];
23039
23260
  state.tasks.forEach((task, taskIndex) => {
23040
- if (!isRecord11(task) || !Array.isArray(task.interrupts)) return;
23261
+ if (!isRecord12(task) || !Array.isArray(task.interrupts)) return;
23041
23262
  const rawTaskId = task.id;
23042
23263
  const taskId = typeof rawTaskId === "string" || typeof rawTaskId === "number" ? String(rawTaskId) : void 0;
23043
23264
  task.interrupts.forEach((interrupt5, index) => {
23044
- const record = isRecord11(interrupt5) ? interrupt5 : {};
23265
+ const record = isRecord12(interrupt5) ? interrupt5 : {};
23045
23266
  const rawId = record.id;
23046
23267
  const interruptId = typeof rawId === "string" || typeof rawId === "number" ? String(rawId) : `${taskId ?? `task-${taskIndex}`}:${index}`;
23047
- const rawValue = isRecord11(interrupt5) ? record.value : interrupt5;
23268
+ const rawValue = isRecord12(interrupt5) ? record.value : interrupt5;
23048
23269
  const fenced = parseFence(rawValue);
23049
23270
  const value = fenced ? fenced.payload : rawValue;
23050
23271
  let type;
23051
- if (fenced?.type === "clarify" || isRecord11(value) && Array.isArray(value.questions)) {
23272
+ if (fenced?.type === "clarify" || isRecord12(value) && Array.isArray(value.questions)) {
23052
23273
  type = "clarify";
23053
23274
  } else if (fenced?.type === "task_review" || isTaskReview(value)) {
23054
23275
  type = "task_review";
23055
23276
  } else {
23056
23277
  type = "custom";
23057
23278
  }
23058
- const payload = type === "clarify" && isRecord11(value) && Array.isArray(value.questions) ? { questions: value.questions } : value;
23279
+ const payload = type === "clarify" && isRecord12(value) && Array.isArray(value.questions) ? { questions: value.questions } : value;
23059
23280
  result.push({
23060
23281
  interruptId,
23061
23282
  type,
@@ -25020,6 +25241,113 @@ var CapabilityRuntimeResolver = class {
25020
25241
  }
25021
25242
  };
25022
25243
 
25244
+ // src/observability_lattice/ObservabilityProvider.ts
25245
+ var ObservabilityDashboardUnsupportedError = class extends Error {
25246
+ /**
25247
+ * @param message - Stable diagnostic message.
25248
+ */
25249
+ constructor(message = "Observability dashboard is not supported") {
25250
+ super(message);
25251
+ this.name = "ObservabilityDashboardUnsupportedError";
25252
+ }
25253
+ };
25254
+ var ObservabilityDashboardUnavailableError = class extends Error {
25255
+ /**
25256
+ * @param message - Stable diagnostic message.
25257
+ */
25258
+ constructor(message = "Observability dashboard is unavailable") {
25259
+ super(message);
25260
+ this.name = "ObservabilityDashboardUnavailableError";
25261
+ }
25262
+ };
25263
+
25264
+ // src/observability_lattice/ObservabilityLatticeManager.ts
25265
+ var ObservabilityLatticeManager = class _ObservabilityLatticeManager extends BaseLatticeManager {
25266
+ constructor() {
25267
+ super(...arguments);
25268
+ this.defaultKey = "default";
25269
+ }
25270
+ /** Returns the process-wide singleton manager. */
25271
+ static getInstance() {
25272
+ if (!_ObservabilityLatticeManager.instance) {
25273
+ _ObservabilityLatticeManager.instance = new _ObservabilityLatticeManager();
25274
+ }
25275
+ return _ObservabilityLatticeManager.instance;
25276
+ }
25277
+ getLatticeType() {
25278
+ return "observability";
25279
+ }
25280
+ /** Registers a provider under a caller-chosen key. */
25281
+ registerLattice(key5, provider2) {
25282
+ this.register(key5, provider2);
25283
+ }
25284
+ /**
25285
+ * Returns the provider registered under `key`.
25286
+ *
25287
+ * @throws Error when no provider is registered under `key`.
25288
+ */
25289
+ getObservabilityLattice(key5) {
25290
+ const provider2 = this.get(key5);
25291
+ if (!provider2) throw new Error(`Observability lattice "${key5}" not registered`);
25292
+ return provider2;
25293
+ }
25294
+ /** Returns whether a provider is registered under `key`. */
25295
+ hasLattice(key5) {
25296
+ return this.has(key5);
25297
+ }
25298
+ /**
25299
+ * Removes the provider under `key`.
25300
+ *
25301
+ * @returns `true` when a provider was removed. Removing the active default
25302
+ * falls back to the `"default"` key.
25303
+ */
25304
+ removeLattice(key5) {
25305
+ const removed = this.remove(key5);
25306
+ if (removed && this.defaultKey === key5) this.defaultKey = "default";
25307
+ return removed;
25308
+ }
25309
+ /** Removes all providers and resets the active default. */
25310
+ clear() {
25311
+ super.clear();
25312
+ this.defaultKey = "default";
25313
+ }
25314
+ /**
25315
+ * Selects the provider used for new invocations.
25316
+ *
25317
+ * @throws Error when no provider is registered under `key`.
25318
+ */
25319
+ setDefault(key5) {
25320
+ if (!this.has(key5)) {
25321
+ throw new Error(`Observability lattice "${key5}" is not registered`);
25322
+ }
25323
+ this.defaultKey = key5;
25324
+ }
25325
+ /** Returns the key of the active default provider. */
25326
+ getDefaultKey() {
25327
+ return this.defaultKey;
25328
+ }
25329
+ /** Returns the active default provider, if registered. */
25330
+ getDefault() {
25331
+ return this.get(this.defaultKey);
25332
+ }
25333
+ };
25334
+ var observabilityLatticeManager = ObservabilityLatticeManager.getInstance();
25335
+ function registerObservabilityLattice(key5, provider2) {
25336
+ observabilityLatticeManager.registerLattice(key5, provider2);
25337
+ }
25338
+ function setDefaultObservabilityLattice(key5) {
25339
+ observabilityLatticeManager.setDefault(key5);
25340
+ }
25341
+ function resolveObservabilityCallbacks(context) {
25342
+ const provider2 = observabilityLatticeManager.getDefault();
25343
+ if (!provider2?.createCallbacks) return [];
25344
+ try {
25345
+ return [...provider2.createCallbacks(context) ?? []];
25346
+ } catch {
25347
+ return [];
25348
+ }
25349
+ }
25350
+
25023
25351
  // src/services/TaskExecutionContext.ts
25024
25352
  var DELEGATED_WORKER_SCOPE_TOKEN = Symbol("delegated-worker-scope");
25025
25353
  var delegatedWorkerScopeSecret = Object.freeze({});
@@ -25110,13 +25438,13 @@ function preserveDelegationContext(source, target) {
25110
25438
  var TRUSTED_AGENT_DISPATCH = Symbol("axiom.trustedAgentDispatch");
25111
25439
 
25112
25440
  // src/services/threadRunLease.ts
25113
- import { randomUUID as randomUUID7 } from "crypto";
25441
+ import { randomUUID as randomUUID8 } from "crypto";
25114
25442
  function threadRunLeaseKey(tenantId2, assistantId, threadId) {
25115
25443
  return `thread-run:${tenantId2}:${assistantId}:${threadId}`;
25116
25444
  }
25117
25445
  async function tryAcquireThreadRun(input) {
25118
25446
  const key5 = threadRunLeaseKey(input.tenantId, input.assistantId, input.threadId);
25119
- const holder = `${input.owner}#${randomUUID7()}`;
25447
+ const holder = `${input.owner}#${randomUUID8()}`;
25120
25448
  if (!await input.store.tryAcquire(key5, holder, input.ttlMs)) return null;
25121
25449
  const heartbeatMs = input.heartbeatMs ?? Math.max(1e3, Math.floor(input.ttlMs / 3));
25122
25450
  let released = false;
@@ -25837,7 +26165,6 @@ function checkpointCapabilityRevision(state) {
25837
26165
  }
25838
26166
  var QUEUE_PROCESSOR_RETRY_BASE_MS = 100;
25839
26167
  var QUEUE_PROCESSOR_MAX_RETRIES = 3;
25840
- var AGENT_RECURSION_LIMIT = 1e3;
25841
26168
  var THREAD_RUN_LEASE_TTL_MS = 6e4;
25842
26169
  var THREAD_RUN_LEASE_RETRY_BASE_MS = 150;
25843
26170
  var THREAD_RUN_LEASE_RETRY_CAP_MS = 1500;
@@ -25888,7 +26215,7 @@ var Agent = class {
25888
26215
  */
25889
26216
  this.threadRunLease = null;
25890
26217
  this.threadRunLeaseRetryAttempt = 0;
25891
- this.runIdFactory = randomUUID8;
26218
+ this.runIdFactory = randomUUID9;
25892
26219
  this.ledgerChain = Promise.resolve();
25893
26220
  this.agentExecutor = async ({ input, command, custom_run_config, expected_capability_revision, trusted_run_context }, signal) => {
25894
26221
  const { runnable_agent, runConfig } = await this.getLatticeClientAndRuntimeConfig(
@@ -25902,6 +26229,8 @@ var Agent = class {
25902
26229
  throw new Error("Agent execution was aborted");
25903
26230
  }
25904
26231
  try {
26232
+ const runId = v42();
26233
+ const callbacks = this.observabilityCallbacks(executionRunConfig, runId, "agent-executor");
25905
26234
  const result = await runnable_agent.invoke(
25906
26235
  command ? new Command2(command) : { ...stateInput, "x-tenant-id": this.tenant_id },
25907
26236
  {
@@ -25909,11 +26238,12 @@ var Agent = class {
25909
26238
  runConfig: executionRunConfig
25910
26239
  },
25911
26240
  configurable: {
25912
- run_id: v42(),
25913
26241
  ...executionRunConfig,
26242
+ run_id: runId,
25914
26243
  runConfig: executionRunConfig
25915
26244
  },
25916
- recursionLimit: AGENT_RECURSION_LIMIT,
26245
+ ...callbacks ? { callbacks } : {},
26246
+ recursionLimit: readAgentRecursionLimit(),
25917
26247
  signal
25918
26248
  }
25919
26249
  );
@@ -25979,6 +26309,8 @@ var Agent = class {
25979
26309
  data: { id: message.id, content: message.content }
25980
26310
  });
25981
26311
  });
26312
+ const runId = execution_run_id ?? v42();
26313
+ const callbacks = this.observabilityCallbacks(executionRunConfig, runId, "stream");
25982
26314
  const agentStream = await runnable_agent.stream(
25983
26315
  command ? new Command2(command) : {
25984
26316
  ...stateInput,
@@ -25989,15 +26321,16 @@ var Agent = class {
25989
26321
  runConfig: executionRunConfig
25990
26322
  },
25991
26323
  configurable: {
25992
- run_id: execution_run_id ?? v42(),
25993
26324
  ...executionRunConfig,
26325
+ run_id: runId,
25994
26326
  runConfig: executionRunConfig
25995
26327
  // Inject runConfig for tools to access
25996
26328
  },
26329
+ ...callbacks ? { callbacks } : {},
25997
26330
  ...execution_run_id === void 0 ? {} : { metadata: { run_id: execution_run_id } },
25998
26331
  streamMode: ["updates", "messages"],
25999
26332
  subgraphs: false,
26000
- recursionLimit: AGENT_RECURSION_LIMIT,
26333
+ recursionLimit: readAgentRecursionLimit(),
26001
26334
  signal
26002
26335
  }
26003
26336
  );
@@ -26405,6 +26738,28 @@ var Agent = class {
26405
26738
  this.queue_project_id = project_id == null || project_id === "" ? null : this.project_id;
26406
26739
  this.custom_run_config = custom_run_config;
26407
26740
  }
26741
+ /**
26742
+ * Re-pins the workspace/project scope used by the next execution.
26743
+ *
26744
+ * @param params - Concrete scope of the run about to execute; absent or
26745
+ * `null`/empty values keep the run unscoped.
26746
+ * @throws {Error} When this Agent is actively executing.
26747
+ * @remarks `AgentInstanceManager` is keyed by
26748
+ * `(tenant_id, assistant_id, thread_id)` only, so a control-plane caller can
26749
+ * create the instance before the durable run worker does. The worker calls
26750
+ * this method while holding the thread-run lease (no other execution can be
26751
+ * active) so the run's authoritative scope cannot inherit a stale default and
26752
+ * fail capability resolution with `Project 'default' was not found`.
26753
+ */
26754
+ applyExecutionScope(params) {
26755
+ if (this.activeExecutionPromise !== void 0) {
26756
+ throw new Error("Cannot re-pin execution scope while the agent is executing");
26757
+ }
26758
+ this.workspace_id = params.workspace_id || "default";
26759
+ this.project_id = params.project_id || "default";
26760
+ this.queue_workspace_id = params.workspace_id === null ? null : this.workspace_id;
26761
+ this.queue_project_id = params.project_id == null || params.project_id === "" ? null : this.project_id;
26762
+ }
26408
26763
  /**
26409
26764
  * Accepts host-authenticated queue metadata through the package-private symbol capability.
26410
26765
  *
@@ -26531,6 +26886,22 @@ var Agent = class {
26531
26886
  }
26532
26887
  return base;
26533
26888
  }
26889
+ observabilityCallbacks(runConfig, runId, source) {
26890
+ const execution = isPlainRecord(runConfig.execution) ? runConfig.execution : void 0;
26891
+ const taskId = typeof runConfig.taskId === "string" ? runConfig.taskId : execution && typeof execution.taskId === "string" ? execution.taskId : void 0;
26892
+ const callbacks = resolveObservabilityCallbacks({
26893
+ tenantId: this.tenant_id,
26894
+ ...this.queue_project_id ? { projectId: this.queue_project_id } : {},
26895
+ ...this.workspace_id ? { workspaceId: this.workspace_id } : {},
26896
+ assistantId: this.assistant_id,
26897
+ threadId: this.thread_id,
26898
+ runId,
26899
+ ...taskId ? { taskId } : {},
26900
+ ...typeof runConfig.user_id === "string" ? { userId: runConfig.user_id } : {},
26901
+ source: typeof runConfig.source === "string" ? runConfig.source : source
26902
+ });
26903
+ return callbacks.length > 0 ? callbacks : void 0;
26904
+ }
26534
26905
  getHumanPendingContent(message) {
26535
26906
  if (typeof message.content === "string" || !message.content || !("id" in message.content) || !("message" in message.content)) {
26536
26907
  throw new Error(`Expected human pending message content for message ${message.id}`);
@@ -26761,16 +27132,19 @@ var Agent = class {
26761
27132
  if (combinedSignal.aborted) {
26762
27133
  throw new Error("Agent execution was aborted");
26763
27134
  }
27135
+ const runId = v42();
27136
+ const callbacks = this.observabilityCallbacks(executionRunConfig, runId, "invoke");
26764
27137
  const result = await runnable_agent.invoke(
26765
27138
  inputMessage.command ? new Command2(inputMessage.command) : { ...rest, messages, "x-tenant-id": this.tenant_id },
26766
27139
  {
26767
27140
  context: { runConfig: executionRunConfig },
26768
27141
  configurable: {
26769
- run_id: v42(),
26770
27142
  ...executionRunConfig,
27143
+ run_id: runId,
26771
27144
  runConfig: executionRunConfig
26772
27145
  },
26773
- recursionLimit: AGENT_RECURSION_LIMIT,
27146
+ ...callbacks ? { callbacks } : {},
27147
+ recursionLimit: readAgentRecursionLimit(),
26774
27148
  signal: combinedSignal
26775
27149
  }
26776
27150
  );
@@ -27170,6 +27544,8 @@ var Agent = class {
27170
27544
  capabilityRuntimeRevision
27171
27545
  );
27172
27546
  const executionRunConfig = this.executionRunConfig(runConfig, trustedRunContext);
27547
+ const runId = executionRunId ?? v42();
27548
+ const callbacks = this.observabilityCallbacks(executionRunConfig, runId, "stream");
27173
27549
  const agentStream = await runnable_agent.stream(
27174
27550
  null,
27175
27551
  {
@@ -27178,13 +27554,14 @@ var Agent = class {
27178
27554
  },
27179
27555
  configurable: {
27180
27556
  ...executionRunConfig,
27181
- ...executionRunId === void 0 ? {} : { run_id: executionRunId },
27557
+ run_id: runId,
27182
27558
  runConfig: executionRunConfig
27183
27559
  },
27560
+ ...callbacks ? { callbacks } : {},
27184
27561
  ...executionRunId === void 0 ? {} : { metadata: { run_id: executionRunId } },
27185
27562
  streamMode: ["updates", "messages"],
27186
27563
  subgraphs: false,
27187
- recursionLimit: AGENT_RECURSION_LIMIT,
27564
+ recursionLimit: readAgentRecursionLimit(),
27188
27565
  signal
27189
27566
  }
27190
27567
  );
@@ -28534,6 +28911,25 @@ var AgentInstanceManager = class _AgentInstanceManager {
28534
28911
  }
28535
28912
  return this.agents.get(key5);
28536
28913
  }
28914
+ /**
28915
+ * Get the managed Agent for an exclusive execution and re-pin its scope.
28916
+ *
28917
+ * @param params - Thread identity plus the authoritative run scope.
28918
+ * @returns The singleton Agent whose next execution uses `params` scope.
28919
+ * @throws {Error} When the resolved Agent is actively executing.
28920
+ * @remarks Callers must already hold the thread-run lease (the durable run
28921
+ * worker does), so no execution can be in flight. This keeps the one-instance
28922
+ * identity while preventing a control-plane caller's default scope from
28923
+ * deciding how the durable run resolves Projects.
28924
+ */
28925
+ getAgentForExecution(params) {
28926
+ const agent = this.getAgent(params);
28927
+ agent.applyExecutionScope({
28928
+ workspace_id: params.workspace_id,
28929
+ project_id: params.project_id
28930
+ });
28931
+ return agent;
28932
+ }
28537
28933
  /**
28538
28934
  * Get the managed Agent for a thread WITHOUT creating or registering one.
28539
28935
  *
@@ -28663,8 +29059,13 @@ var DelegationService = class {
28663
29059
  if (!agent) {
28664
29060
  throw new Error(`Delegated agent ${request.assistant_id} not found`);
28665
29061
  }
29062
+ let childAbort;
29063
+ const abortChild = () => {
29064
+ childAbort ?? (childAbort = agent.abort().catch(() => void 0));
29065
+ return childAbort;
29066
+ };
28666
29067
  const onCancel = () => {
28667
- void agent.abort().catch(() => void 0);
29068
+ void abortChild();
28668
29069
  };
28669
29070
  if (cancellation) {
28670
29071
  if (cancellation.signal.aborted) onCancel();
@@ -28685,7 +29086,14 @@ var DelegationService = class {
28685
29086
  });
28686
29087
  try {
28687
29088
  await Promise.race([invocation, aborted]);
29089
+ if (signal.aborted) {
29090
+ await abortChild();
29091
+ throw new Error("Delegated child aborted");
29092
+ }
28688
29093
  return await agent.getCurrentState();
29094
+ } catch (error) {
29095
+ if (signal.aborted) await abortChild();
29096
+ throw error;
28689
29097
  } finally {
28690
29098
  signal.removeEventListener("abort", onAbort);
28691
29099
  }
@@ -28854,7 +29262,15 @@ var agentWorkerGraph = createAgentWorkerGraph();
28854
29262
 
28855
29263
  // src/deep_agent_new/middleware/subagents.ts
28856
29264
  var DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools.";
28857
- var EXCLUDED_STATE_KEYS = ["messages", "todos", "jumpTo"];
29265
+ var EXCLUDED_STATE_KEYS = [
29266
+ "messages",
29267
+ "todos",
29268
+ "jumpTo",
29269
+ "repeatedToolCallSignature",
29270
+ "repeatedToolCallCount",
29271
+ "repeatedToolCallRunMarker",
29272
+ "repeatedToolCallMemberSignatures"
29273
+ ];
28858
29274
  var DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.";
28859
29275
  function createGeneralPurposeAgent(options) {
28860
29276
  const middleware = [...options.middleware];
@@ -29450,8 +29866,12 @@ function registerAgentAddMessageHandler() {
29450
29866
  tenant_id: taskInfo.tenantId,
29451
29867
  assistant_id: taskInfo.assistantId ?? "",
29452
29868
  thread_id: taskInfo.threadId ?? "",
29453
- workspace_id: runConfigFromMetadata?.workspaceId ?? "default",
29454
- project_id: runConfigFromMetadata?.projectId ?? "default"
29869
+ // An absent scope must stay unscoped: defaulting the project to
29870
+ // `"default"` pinned the shared thread Agent to a project that may not
29871
+ // exist, so later runs on the same thread failed capability resolution
29872
+ // with `Project 'default' was not found`.
29873
+ workspace_id: runConfigFromMetadata?.workspaceId ?? "",
29874
+ project_id: runConfigFromMetadata?.projectId ?? ""
29455
29875
  });
29456
29876
  await agent.addMessage({
29457
29877
  input: {
@@ -31282,6 +31702,7 @@ var DeepAgentGraphBuilder = class {
31282
31702
  const deepAgent = createDeepAgent({
31283
31703
  tools,
31284
31704
  model: params.model,
31705
+ name: agentLattice.config.name,
31285
31706
  contextSchema: params.stateSchema,
31286
31707
  systemPrompt: params.prompt,
31287
31708
  subagents,
@@ -31748,6 +32169,7 @@ var WorkflowAgentGraphBuilder = class {
31748
32169
  }
31749
32170
  const config = agentLattice.config;
31750
32171
  const yaml = config.workflowYaml;
32172
+ const agentName = config.name?.trim() || config.key;
31751
32173
  const tenantId2 = agentLattice.config.tenantId ?? "default";
31752
32174
  const checkpointer = getCheckpointSaver("default");
31753
32175
  const tools = params.tools.map((t) => t.executor).filter(Boolean);
@@ -31770,6 +32192,7 @@ var WorkflowAgentGraphBuilder = class {
31770
32192
  model: params.model,
31771
32193
  tools,
31772
32194
  systemPrompt: buildStepSystemPrompt(false, params.prompt),
32195
+ name: agentName,
31773
32196
  checkpointer,
31774
32197
  middleware: middlewares,
31775
32198
  stateSchema: withToolCallLimitStateSchema()
@@ -31791,6 +32214,7 @@ var WorkflowAgentGraphBuilder = class {
31791
32214
  model: params.model,
31792
32215
  tools,
31793
32216
  systemPrompt: buildStepSystemPrompt(isAsk, params.prompt),
32217
+ name: agentName,
31794
32218
  checkpointer,
31795
32219
  middleware: isAsk ? noWrapAskMiddlewares : noWrapMiddlewares,
31796
32220
  stateSchema: withToolCallLimitStateSchema(),
@@ -31808,6 +32232,7 @@ var WorkflowAgentGraphBuilder = class {
31808
32232
  model: params.model,
31809
32233
  tools,
31810
32234
  systemPrompt: buildStepSystemPrompt(true, params.prompt),
32235
+ name: agentName,
31811
32236
  checkpointer,
31812
32237
  middleware: askMiddlewares
31813
32238
  });
@@ -31826,7 +32251,13 @@ var WorkflowAgentGraphBuilder = class {
31826
32251
  } catch {
31827
32252
  console.warn(`[WF BUILDER] no trackingStore registered`);
31828
32253
  }
31829
- const graph = compileWorkflow(yaml, resolveAgent, checkpointer, trackingStore);
32254
+ const graph = compileWorkflow(
32255
+ yaml,
32256
+ resolveAgent,
32257
+ checkpointer,
32258
+ trackingStore,
32259
+ { name: agentName }
32260
+ );
31830
32261
  return graph;
31831
32262
  }
31832
32263
  };
@@ -32232,7 +32663,7 @@ registerToolLattice(
32232
32663
  if (taskConfigIssue) return JSON.stringify(taskConfigIssue);
32233
32664
  const id = await generateAgentId(tenantId2, input.name);
32234
32665
  try {
32235
- const { compileWorkflow: compileWorkflow2 } = await import("./compile-QEFI6YTD.mjs");
32666
+ const { compileWorkflow: compileWorkflow2 } = await import("./compile-LYA47THO.mjs");
32236
32667
  const { getCheckpointSaver: getCheckpointSaver2 } = await import("./memory_lattice-E66HTTVV.mjs");
32237
32668
  await compileWorkflow2(input.yaml, async () => ({ invoke: async () => ({}) }), getCheckpointSaver2("default"));
32238
32669
  } catch (e) {
@@ -32287,7 +32718,7 @@ registerToolLattice(
32287
32718
  return JSON.stringify({ error: `Agent '${input.id}' has no workflow DSL` });
32288
32719
  }
32289
32720
  try {
32290
- const { compileWorkflow: compileWorkflow2 } = await import("./compile-QEFI6YTD.mjs");
32721
+ const { compileWorkflow: compileWorkflow2 } = await import("./compile-LYA47THO.mjs");
32291
32722
  const { getCheckpointSaver: getCheckpointSaver2 } = await import("./memory_lattice-E66HTTVV.mjs");
32292
32723
  await compileWorkflow2(yaml, async () => ({ invoke: async () => ({}) }), getCheckpointSaver2("default"));
32293
32724
  } catch (e) {
@@ -32442,7 +32873,7 @@ registerToolLattice(
32442
32873
  if (input.yaml !== void 0) {
32443
32874
  console.log(`[update_workflow] validating DSL: ${input.id}`);
32444
32875
  try {
32445
- const { compileWorkflow: compileWorkflow2 } = await import("./compile-QEFI6YTD.mjs");
32876
+ const { compileWorkflow: compileWorkflow2 } = await import("./compile-LYA47THO.mjs");
32446
32877
  const { getCheckpointSaver: getCheckpointSaver2 } = await import("./memory_lattice-E66HTTVV.mjs");
32447
32878
  await compileWorkflow2(input.yaml, async () => ({ invoke: async () => ({}) }), getCheckpointSaver2("default"));
32448
32879
  console.log(`[update_workflow] DSL validation passed: ${input.id}`);
@@ -35801,7 +36232,7 @@ function getDefaultMicrosandboxRemoteConfig() {
35801
36232
  image: process.env.MICROSANDBOX_IMAGE ?? "kioko12520/sandbox:0.1.0",
35802
36233
  //"daytonaio/sandbox:0.6.0",
35803
36234
  cpus: parseOptionalNumberEnv("MICROSANDBOX_CPUS", 1),
35804
- memoryMib: parseOptionalNumberEnv("MICROSANDBOX_MEMORY", 512),
36235
+ memoryMib: parseOptionalNumberEnv("MICROSANDBOX_MEMORY", 1024),
35805
36236
  user: "root"
35806
36237
  };
35807
36238
  }
@@ -36945,7 +37376,8 @@ var PLATFORM_SECRET_ENV_VARS = [
36945
37376
  "TAVILY_API_KEY",
36946
37377
  "VAPID_PRIVATE_KEY",
36947
37378
  "SUPABASE_KEY",
36948
- "A2A_API_KEYS"
37379
+ "A2A_API_KEYS",
37380
+ "MCP_UI_SCOPE_SECRET"
36949
37381
  ];
36950
37382
  function stripPlatformSecrets(env) {
36951
37383
  const rest = { ...env };
@@ -37632,11 +38064,20 @@ async function disconnectAllChannels(getAdapter) {
37632
38064
  }
37633
38065
 
37634
38066
  // src/channel/ChannelConnectionLeader.ts
37635
- import { randomUUID as randomUUID9 } from "crypto";
38067
+ import { createHash as createHash5, randomUUID as randomUUID10 } from "crypto";
37636
38068
  var LEASE_KEY = "leader:channel-connections";
38069
+ function channelShardForInstallation(installationId, shardCount) {
38070
+ if (!Number.isSafeInteger(shardCount) || shardCount < 1) {
38071
+ throw new RangeError("shardCount must be a positive integer");
38072
+ }
38073
+ if (shardCount === 1) return 0;
38074
+ return createHash5("sha256").update(installationId).digest().readUInt32BE(0) % shardCount;
38075
+ }
37637
38076
  var ChannelConnectionLeader = class {
37638
38077
  constructor(deps) {
38078
+ this.active = /* @__PURE__ */ new Map();
37639
38079
  this.holder = null;
38080
+ this.renewFailures = 0;
37640
38081
  this.connected = false;
37641
38082
  this.attempted = false;
37642
38083
  this.inFlight = null;
@@ -37646,6 +38087,33 @@ var ChannelConnectionLeader = class {
37646
38087
  this.deps = deps;
37647
38088
  this.ttlMs = deps.ttlMs ?? 6e4;
37648
38089
  this.retryMs = deps.retryMs ?? Math.max(5e3, Math.floor(this.ttlMs / 3));
38090
+ this.shardCount = deps.shardCount ?? 1;
38091
+ this.shard = deps.shard ?? 0;
38092
+ if (!Number.isSafeInteger(this.shardCount) || this.shardCount < 1) {
38093
+ throw new RangeError("ChannelConnectionLeader shardCount must be a positive integer");
38094
+ }
38095
+ if (!Number.isSafeInteger(this.shard) || this.shard < 0 || this.shard >= this.shardCount) {
38096
+ throw new RangeError("ChannelConnectionLeader shard must be within shardCount");
38097
+ }
38098
+ this.leaseKey = deps.leaseKey ?? (this.shardCount === 1 ? LEASE_KEY : `${LEASE_KEY}:${this.shard}`);
38099
+ this.reconciler = deps.loadDesired !== void 0;
38100
+ if (this.reconciler && (!deps.connectInstallation || !deps.disconnectInstallation)) {
38101
+ throw new Error("ChannelConnectionLeader reconcile mode requires connectInstallation and disconnectInstallation");
38102
+ }
38103
+ }
38104
+ /** Whether this shard owns an installation id. */
38105
+ owns(installationId) {
38106
+ return channelShardForInstallation(installationId, this.shardCount) === this.shard;
38107
+ }
38108
+ /** Wake the current leader so it reconciles the shared desired state. */
38109
+ wake() {
38110
+ if (this.stopped) return;
38111
+ void this.tickOnce();
38112
+ }
38113
+ /** Reconcile now when this instance currently holds the lease. */
38114
+ async reconcile() {
38115
+ if (!this.reconciler || !this.holder || this.stopped) return;
38116
+ await this.reconcileChannels();
37649
38117
  }
37650
38118
  /** Starts the ownership loop (immediate tick, then every `retryMs`). */
37651
38119
  start() {
@@ -37672,13 +38140,17 @@ var ChannelConnectionLeader = class {
37672
38140
  if (this.holder) {
37673
38141
  const holder = this.holder;
37674
38142
  this.holder = null;
37675
- await this.deps.leaseStore.release(LEASE_KEY, holder).catch((error) => {
38143
+ await this.deps.leaseStore.release(this.leaseKey, holder).catch((error) => {
37676
38144
  this.deps.log?.warn("Channel leader lease release failed", {
37677
38145
  error: error instanceof Error ? error.message : String(error)
37678
38146
  });
37679
38147
  });
37680
38148
  }
37681
- await this.disconnectChannels();
38149
+ if (this.reconciler) {
38150
+ await this.disconnectTracked();
38151
+ } else {
38152
+ await this.disconnectChannels();
38153
+ }
37682
38154
  }
37683
38155
  /**
37684
38156
  * Runs one ownership/health step. Public for deterministic tests.
@@ -37709,39 +38181,64 @@ var ChannelConnectionLeader = class {
37709
38181
  let renewed = false;
37710
38182
  let renewFailed = false;
37711
38183
  try {
37712
- renewed = await this.deps.leaseStore.renew(LEASE_KEY, this.holder, this.ttlMs);
38184
+ renewed = await this.deps.leaseStore.renew(this.leaseKey, this.holder, this.ttlMs);
37713
38185
  } catch (error) {
37714
38186
  renewFailed = true;
37715
38187
  this.deps.log?.warn("Channel leader lease renew failed", {
37716
38188
  error: error instanceof Error ? error.message : String(error)
37717
38189
  });
37718
38190
  }
37719
- if (renewFailed) return;
38191
+ if (renewFailed) {
38192
+ this.renewFailures += 1;
38193
+ if (this.renewFailures * this.retryMs < this.ttlMs) return;
38194
+ await this.loseLeadership();
38195
+ return;
38196
+ }
38197
+ this.renewFailures = 0;
37720
38198
  if (renewed) {
37721
- if (!this.connected) await this.connectChannels();
38199
+ if (this.reconciler) {
38200
+ await this.reconcileChannels();
38201
+ } else if (!this.connected) {
38202
+ await this.connectChannels();
38203
+ }
37722
38204
  return;
37723
38205
  }
37724
38206
  await this.loseLeadership();
37725
38207
  }
38208
+ if (this.reconciler && this.active.size > 0) {
38209
+ await this.disconnectTracked();
38210
+ if (this.active.size > 0) return;
38211
+ }
37726
38212
  await this.tryAcquire();
37727
38213
  }
37728
38214
  async tryAcquire() {
37729
- const holder = `${this.deps.owner}#${randomUUID9()}`;
37730
- const acquired = await this.deps.leaseStore.tryAcquire(LEASE_KEY, holder, this.ttlMs).catch((error) => {
38215
+ const holder = `${this.deps.owner}#${randomUUID10()}`;
38216
+ const acquired = await this.deps.leaseStore.tryAcquire(this.leaseKey, holder, this.ttlMs).catch((error) => {
37731
38217
  this.deps.log?.warn("Channel leader lease acquire failed", {
37732
38218
  error: error instanceof Error ? error.message : String(error)
37733
38219
  });
37734
38220
  return false;
37735
38221
  });
37736
38222
  if (!acquired) return;
38223
+ this.renewFailures = 0;
37737
38224
  this.holder = holder;
37738
- await this.connectChannels();
38225
+ if (this.reconciler) {
38226
+ await this.reconcileChannels();
38227
+ } else {
38228
+ await this.connectChannels();
38229
+ }
37739
38230
  }
37740
38231
  async loseLeadership() {
37741
38232
  this.holder = null;
37742
- await this.disconnectChannels();
38233
+ this.renewFailures = 0;
38234
+ if (this.reconciler) {
38235
+ await this.disconnectTracked();
38236
+ } else {
38237
+ await this.disconnectChannels();
38238
+ }
37743
38239
  }
37744
38240
  async connectChannels() {
38241
+ if (!this.deps.connect) return;
37745
38242
  this.attempted = true;
37746
38243
  try {
37747
38244
  await this.deps.connect();
@@ -37754,7 +38251,7 @@ var ChannelConnectionLeader = class {
37754
38251
  }
37755
38252
  }
37756
38253
  async disconnectChannels() {
37757
- if (!this.attempted) return;
38254
+ if (!this.attempted || !this.deps.disconnect) return;
37758
38255
  this.attempted = false;
37759
38256
  this.connected = false;
37760
38257
  try {
@@ -37765,6 +38262,74 @@ var ChannelConnectionLeader = class {
37765
38262
  });
37766
38263
  }
37767
38264
  }
38265
+ /** Reconcile desired installations against the connections this shard holds. */
38266
+ async reconcileChannels() {
38267
+ if (!this.reconciler || !this.holder || this.stopped) return;
38268
+ let desired;
38269
+ try {
38270
+ desired = (await this.deps.loadDesired()).filter(
38271
+ (installation) => installation.enabled && this.owns(installation.id)
38272
+ );
38273
+ } catch (error) {
38274
+ this.deps.log?.warn("Channel leader desired-state read failed", {
38275
+ error: error instanceof Error ? error.message : String(error)
38276
+ });
38277
+ return;
38278
+ }
38279
+ const desiredById = new Map(desired.map((installation) => [installation.id, installation]));
38280
+ for (const [id, active] of [...this.active]) {
38281
+ const next = desiredById.get(id);
38282
+ if (next && this.fingerprint(next) === active.fingerprint) continue;
38283
+ if (await this.safeDisconnect(active.installation)) this.active.delete(id);
38284
+ }
38285
+ for (const installation of desired) {
38286
+ if (this.active.has(installation.id)) continue;
38287
+ if (await this.safeConnect(installation)) {
38288
+ this.active.set(installation.id, {
38289
+ installation,
38290
+ fingerprint: this.fingerprint(installation)
38291
+ });
38292
+ }
38293
+ }
38294
+ }
38295
+ fingerprint(installation) {
38296
+ if (this.deps.fingerprint) return this.deps.fingerprint(installation);
38297
+ return JSON.stringify({
38298
+ channel: installation.channel,
38299
+ config: installation.config,
38300
+ fallbackAgentId: installation.fallbackAgentId,
38301
+ rejectWhenNoBinding: installation.rejectWhenNoBinding
38302
+ });
38303
+ }
38304
+ async safeConnect(installation) {
38305
+ try {
38306
+ await this.deps.connectInstallation(installation);
38307
+ return true;
38308
+ } catch (error) {
38309
+ this.deps.log?.warn("Channel installation connect failed", {
38310
+ installationId: installation.id,
38311
+ error: error instanceof Error ? error.message : String(error)
38312
+ });
38313
+ return false;
38314
+ }
38315
+ }
38316
+ async safeDisconnect(installation) {
38317
+ try {
38318
+ await this.deps.disconnectInstallation(installation);
38319
+ return true;
38320
+ } catch (error) {
38321
+ this.deps.log?.warn("Channel installation disconnect failed", {
38322
+ installationId: installation.id,
38323
+ error: error instanceof Error ? error.message : String(error)
38324
+ });
38325
+ return false;
38326
+ }
38327
+ }
38328
+ async disconnectTracked() {
38329
+ for (const [id, active] of [...this.active]) {
38330
+ if (await this.safeDisconnect(active.installation)) this.active.delete(id);
38331
+ }
38332
+ }
37768
38333
  };
37769
38334
 
37770
38335
  // src/eval_lattice/LatticeEval.ts
@@ -39228,7 +39793,7 @@ function getCoordinationLeaseStore() {
39228
39793
  }
39229
39794
 
39230
39795
  // src/services/withLease.ts
39231
- import { randomUUID as randomUUID10 } from "crypto";
39796
+ import { randomUUID as randomUUID11 } from "crypto";
39232
39797
  var LeaseAcquisitionTimeoutError = class extends Error {
39233
39798
  /**
39234
39799
  * @param key Lease key that could not be acquired.
@@ -39253,7 +39818,7 @@ async function withLease(store2, key5, ownerLabel, fn, options = {}) {
39253
39818
  const acquireTimeoutMs = options.acquireTimeoutMs ?? 1e4;
39254
39819
  const retryDelayMs = options.retryDelayMs ?? 50;
39255
39820
  const heartbeatMs = options.heartbeatMs ?? Math.max(1e3, Math.floor(ttlMs / 3));
39256
- const holder = `${ownerLabel}#${randomUUID10()}`;
39821
+ const holder = `${ownerLabel}#${randomUUID11()}`;
39257
39822
  const deadline = Date.now() + acquireTimeoutMs;
39258
39823
  for (; ; ) {
39259
39824
  if (await store2.tryAcquire(key5, holder, ttlMs)) break;
@@ -39360,7 +39925,7 @@ function createTrustedAgentMessageDispatcher(resolve4) {
39360
39925
  }
39361
39926
 
39362
39927
  // src/services/RoomAgentMessageService.ts
39363
- import { randomUUID as randomUUID11 } from "crypto";
39928
+ import { randomUUID as randomUUID12 } from "crypto";
39364
39929
  import { snapshotExactArray, snapshotExactRecord as snapshotExactRecord5 } from "@axiom-lattice/protocols";
39365
39930
  var INPUT_KEYS = [
39366
39931
  "tenantId",
@@ -39450,7 +40015,7 @@ var RoomAgentMessageService = class {
39450
40015
  throw new Error("Invalid project room membership");
39451
40016
  }
39452
40017
  const candidate = {
39453
- id: (this.deps.idFactory ?? randomUUID11)(),
40018
+ id: (this.deps.idFactory ?? randomUUID12)(),
39454
40019
  tenantId: member.tenantId,
39455
40020
  workspaceId: member.workspaceId,
39456
40021
  projectId: member.projectId,
@@ -39493,7 +40058,7 @@ var RoomAgentMessageService = class {
39493
40058
  throw new Error("Invalid project room membership");
39494
40059
  }
39495
40060
  const candidate = {
39496
- id: (this.deps.idFactory ?? randomUUID11)(),
40061
+ id: (this.deps.idFactory ?? randomUUID12)(),
39497
40062
  tenantId: input.tenantId,
39498
40063
  workspaceId: input.workspaceId,
39499
40064
  projectId: input.projectId,
@@ -40085,11 +40650,11 @@ function describe(error) {
40085
40650
  }
40086
40651
 
40087
40652
  // src/services/TaskLifecycleService.ts
40088
- import { createHash as createHash6 } from "crypto";
40653
+ import { createHash as createHash7 } from "crypto";
40089
40654
  import { parseTaskBeliefState, replaceTaskBeliefState, taskBeliefStatesEqual } from "@axiom-lattice/protocols";
40090
40655
 
40091
40656
  // src/middlewares/taskBelief.ts
40092
- import { createHash as createHash5 } from "crypto";
40657
+ import { createHash as createHash6 } from "crypto";
40093
40658
  function buildBeliefCompletionEventKey(taskId, result, impacts) {
40094
40659
  const canonical = JSON.stringify({
40095
40660
  beliefImpact: impacts.map((impact) => ({
@@ -40100,7 +40665,7 @@ function buildBeliefCompletionEventKey(taskId, result, impacts) {
40100
40665
  })),
40101
40666
  result: result.trim()
40102
40667
  });
40103
- return createHash5("sha256").update(canonical).digest("hex");
40668
+ return createHash6("sha256").update(canonical).digest("hex");
40104
40669
  }
40105
40670
  function buildCompletionEvidenceDetail(result, impacts, eventKey) {
40106
40671
  return { result, beliefImpact: impacts, eventKey };
@@ -40303,7 +40868,7 @@ function canonicalJson(value) {
40303
40868
  return JSON.stringify(value);
40304
40869
  }
40305
40870
  function sha256(value) {
40306
- return createHash6("sha256").update(canonicalJson(value)).digest("hex");
40871
+ return createHash7("sha256").update(canonicalJson(value)).digest("hex");
40307
40872
  }
40308
40873
  function sameEvidenceDetail(detail, taskId, result, impacts, eventKey, beliefOwner) {
40309
40874
  const storedOwner = detail.beliefOwner;
@@ -42385,7 +42950,7 @@ function createTaskLifecycleService(deps) {
42385
42950
  }
42386
42951
 
42387
42952
  // src/services/TaskExecutionService.ts
42388
- import { randomUUID as randomUUID13 } from "crypto";
42953
+ import { randomUUID as randomUUID14 } from "crypto";
42389
42954
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
42390
42955
  import { isExecutionResultEventKey as isExecutionResultEventKey2 } from "@axiom-lattice/protocols";
42391
42956
 
@@ -42741,13 +43306,13 @@ async function reconcileAllTenantTaskRuns(input) {
42741
43306
  }
42742
43307
 
42743
43308
  // src/services/taskRunLease.ts
42744
- import { randomUUID as randomUUID12 } from "crypto";
43309
+ import { randomUUID as randomUUID13 } from "crypto";
42745
43310
  function taskRunLeaseKey(taskId) {
42746
43311
  return `task-run:${taskId}`;
42747
43312
  }
42748
43313
  async function tryAcquireTaskRun(input) {
42749
43314
  const key5 = taskRunLeaseKey(input.taskId);
42750
- const holder = `${input.owner}#${randomUUID12()}`;
43315
+ const holder = `${input.owner}#${randomUUID13()}`;
42751
43316
  if (!await input.store.tryAcquire(key5, holder, input.ttlMs)) return null;
42752
43317
  const heartbeatMs = input.heartbeatMs ?? Math.max(1e3, Math.floor(input.ttlMs / 3));
42753
43318
  let released = false;
@@ -43167,11 +43732,11 @@ function createTaskExecutionService(deps) {
43167
43732
  let threadId;
43168
43733
  let runId;
43169
43734
  try {
43170
- threadId = storedThreadId ?? (deps.createThreadId ?? randomUUID13)();
43735
+ threadId = storedThreadId ?? (deps.createThreadId ?? randomUUID14)();
43171
43736
  if (task.status === "interrupted" && reuseCurrentRun) {
43172
43737
  runId = storedRunId;
43173
43738
  } else if (task.status === "interrupted" || task.status === "failed") {
43174
- runId = (deps.createRunId ?? randomUUID13)();
43739
+ runId = (deps.createRunId ?? randomUUID14)();
43175
43740
  }
43176
43741
  } catch (error) {
43177
43742
  return {
@@ -43451,11 +44016,11 @@ function createTaskExecutionService(deps) {
43451
44016
  }
43452
44017
 
43453
44018
  // src/services/leadership.ts
43454
- import { randomUUID as randomUUID14 } from "crypto";
44019
+ import { randomUUID as randomUUID15 } from "crypto";
43455
44020
  async function runAsLeader(store2, name, fn, options = {}) {
43456
44021
  const key5 = `leader:${name}`;
43457
44022
  const owner3 = options.owner ?? getReplicaId();
43458
- const holder = `${owner3}#${randomUUID14()}`;
44023
+ const holder = `${owner3}#${randomUUID15()}`;
43459
44024
  const ttlMs = options.ttlMs ?? 6e4;
43460
44025
  if (!await store2.tryAcquire(key5, holder, ttlMs)) return { ran: false };
43461
44026
  const heartbeat = setInterval(() => {
@@ -44704,16 +45269,16 @@ function createAskUserToClarifyTool() {
44704
45269
  }
44705
45270
 
44706
45271
  // src/middlewares/askUserClarifyMiddleware.ts
44707
- function isRecord12(value) {
45272
+ function isRecord13(value) {
44708
45273
  return typeof value === "object" && value !== null && !Array.isArray(value);
44709
45274
  }
44710
45275
  function isProjectRoomRun(request) {
44711
- if (!isRecord12(request) || !isRecord12(request.runtime)) return false;
45276
+ if (!isRecord13(request) || !isRecord13(request.runtime)) return false;
44712
45277
  const runtime = request.runtime;
44713
- const configurable = isRecord12(runtime.configurable) ? runtime.configurable.runConfig : void 0;
44714
- const context = isRecord12(runtime.context) ? runtime.context.runConfig : void 0;
44715
- const runConfig = isRecord12(configurable) ? configurable : isRecord12(context) ? context : void 0;
44716
- return isRecord12(runConfig?.projectRoom);
45278
+ const configurable = isRecord13(runtime.configurable) ? runtime.configurable.runConfig : void 0;
45279
+ const context = isRecord13(runtime.context) ? runtime.context.runConfig : void 0;
45280
+ const runConfig = isRecord13(configurable) ? configurable : isRecord13(context) ? context : void 0;
45281
+ return isRecord13(runConfig?.projectRoom);
44717
45282
  }
44718
45283
  function createAskUserClarifyMiddleware() {
44719
45284
  return createMiddleware20({
@@ -49563,7 +50128,7 @@ var documentParserPlugin = {
49563
50128
  };
49564
50129
 
49565
50130
  // src/middlewares/projectRoomMiddleware.ts
49566
- import { createHash as createHash7 } from "crypto";
50131
+ import { createHash as createHash8 } from "crypto";
49567
50132
  import {
49568
50133
  descriptorDataValue as descriptorDataValue2,
49569
50134
  parseTrustedRunContext as parseTrustedRunContext3,
@@ -49686,7 +50251,7 @@ function createProjectRoomMiddleware() {
49686
50251
  const { text } = input;
49687
50252
  const scope = readTrustedRoomScope(config);
49688
50253
  if (!scope) return CONTEXT_REQUIRED;
49689
- const digest = createHash7("sha256").update(text).digest("hex");
50254
+ const digest = createHash8("sha256").update(text).digest("hex");
49690
50255
  try {
49691
50256
  const service3 = new RoomAgentMessageService({
49692
50257
  memberships: getStoreLattice("default", "projectBotMembership").store,
@@ -51307,11 +51872,14 @@ var sandboxPluginsPlugin = {
51307
51872
  }
51308
51873
  const toolDef = (parsedManifest.tools ?? []).find((t) => t.name === input.target?.name);
51309
51874
  if (!toolDef) return `tool "${input.target.name ?? ""}" not found`;
51310
- const runCfg = exeConfig?.configurable?.runConfig ?? {};
51875
+ const runConfig = {
51876
+ ...sandboxRunConfigFrom(exeConfig),
51877
+ tenantId: tenantId2
51878
+ };
51311
51879
  const resolved = input.target.connectionKey ? await resolveSandboxPluginConnections(
51312
51880
  input.type,
51313
51881
  { connections: [input.target.connectionKey] },
51314
- { tenantId: tenantId2 }
51882
+ runConfig
51315
51883
  ) : {};
51316
51884
  const secrets = collectSecretValues(resolved.connection, connectionSecretFields(plugin));
51317
51885
  try {
@@ -51322,19 +51890,27 @@ var sandboxPluginsPlugin = {
51322
51890
  connection: resolved.connection,
51323
51891
  connections: resolved.connections,
51324
51892
  context: { tenantId: tenantId2, pluginType: input.type, tool: toolDef.name },
51325
- runConfig: {
51326
- tenantId: tenantId2,
51327
- assistantId: typeof runCfg.assistant_id === "string" ? runCfg.assistant_id : void 0
51328
- }
51893
+ runConfig
51329
51894
  });
51330
51895
  const text = handlerResultText(redactSecretValues(result, secrets));
51331
51896
  const ui = toolDef.ui;
51332
51897
  if (!ui?.resource) return text;
51898
+ const scope = result.ok && ui?.resource ? signMcpUiScope({
51899
+ tid: runConfig.tenantId || tenantId2,
51900
+ thid: runConfig.threadId,
51901
+ aid: runConfig.assistantId,
51902
+ wid: runConfig.workspaceId,
51903
+ pid: runConfig.projectId,
51904
+ plugin: input.type,
51905
+ resource: ui.resource,
51906
+ ck: resolved.connections?.[0]?.key
51907
+ }) : void 0;
51333
51908
  const uiRef = {
51334
51909
  kind: "plugin",
51335
51910
  pluginType: input.type,
51336
51911
  resource: ui.resource,
51337
- displayMode: ui.displayMode ?? "inline"
51912
+ displayMode: ui.displayMode ?? "inline",
51913
+ ...scope ? { scope } : {}
51338
51914
  };
51339
51915
  return appendUiFence(text, uiRef);
51340
51916
  } catch (err) {
@@ -52035,11 +52611,11 @@ var INLINE_INPUT_LIMIT_BYTES2 = 48 * 1024;
52035
52611
  var DEFAULT_HANDLER_TIMEOUT_MS = 6e4;
52036
52612
  var MIN_HANDLER_TIMEOUT_MS = 1e3;
52037
52613
  var MAX_HANDLER_TIMEOUT_MS = 3e5;
52038
- function isRecord13(value) {
52614
+ function isRecord14(value) {
52039
52615
  return typeof value === "object" && value !== null && !Array.isArray(value);
52040
52616
  }
52041
52617
  function isEnvelope3(value) {
52042
- return isRecord13(value) && typeof value.ok === "boolean";
52618
+ return isRecord14(value) && typeof value.ok === "boolean";
52043
52619
  }
52044
52620
  function parseHostArgs(argv) {
52045
52621
  let type;
@@ -52121,7 +52697,7 @@ function normalizeEnvelope(parsed) {
52121
52697
  }
52122
52698
 
52123
52699
  // src/sandbox_plugin/host/pluginHostSource.ts
52124
- import { createHash as createHash8 } from "crypto";
52700
+ import { createHash as createHash9 } from "crypto";
52125
52701
  var PLUGIN_HOST_VERSION = "1.1.0";
52126
52702
  var PLUGIN_HOST_SERVER_SOURCE = String.raw`#!/usr/bin/env node
52127
52703
  "use strict";
@@ -52323,6 +52899,8 @@ async function runHandler(body) {
52323
52899
  var needsTempDir = inputIsLarge || connectionPayload !== null;
52324
52900
  var tempDir = null;
52325
52901
  var env = Object.assign({}, process.env);
52902
+ // Handler processes must never inherit scope signing secrets.
52903
+ delete env.MCP_UI_SCOPE_SECRET;
52326
52904
  try {
52327
52905
  if (needsTempDir) {
52328
52906
  tempDir = path.join(os.tmpdir(), "plugin-run-" + Date.now() + "-" + Math.random().toString(36).slice(2));
@@ -52414,7 +52992,7 @@ server.listen(config.port, "0.0.0.0", function () {
52414
52992
  });
52415
52993
  `;
52416
52994
  function pluginHostContentHash() {
52417
- return createHash8("sha256").update(`${PLUGIN_HOST_VERSION}:${PLUGIN_HOST_SERVER_SOURCE}`).digest("hex").slice(0, 16);
52995
+ return createHash9("sha256").update(`${PLUGIN_HOST_VERSION}:${PLUGIN_HOST_SERVER_SOURCE}`).digest("hex").slice(0, 16);
52418
52996
  }
52419
52997
 
52420
52998
  // src/sandbox_plugin/host/pluginHostInstaller.ts
@@ -52821,16 +53399,16 @@ var IdRemapper = class {
52821
53399
  };
52822
53400
 
52823
53401
  // src/util/directRoomId.ts
52824
- import { createHash as createHash9 } from "crypto";
53402
+ import { createHash as createHash10 } from "crypto";
52825
53403
  function generateDirectHumanProjectId(tenantId2, workspaceId, userId1, userId2) {
52826
53404
  const sortedUserIds = [userId1, userId2].sort();
52827
53405
  const parts = [tenantId2, workspaceId, ...sortedUserIds];
52828
- const hash = createHash9("sha256").update(parts.join(":")).digest("hex");
53406
+ const hash = createHash10("sha256").update(parts.join(":")).digest("hex");
52829
53407
  return `direct_human_${hash}`;
52830
53408
  }
52831
53409
  function generateDirectBotProjectId(tenantId2, workspaceId, userId, assistantId) {
52832
53410
  const parts = [tenantId2, workspaceId, userId, assistantId];
52833
- const hash = createHash9("sha256").update(parts.join(":")).digest("hex");
53411
+ const hash = createHash10("sha256").update(parts.join(":")).digest("hex");
52834
53412
  return `direct_bot_${hash}`;
52835
53413
  }
52836
53414
  function parseDirectRoomType(projectId) {
@@ -52961,6 +53539,9 @@ export {
52961
53539
  MicrosandboxServiceClient,
52962
53540
  ModelLatticeManager,
52963
53541
  MysqlDatabase,
53542
+ ObservabilityDashboardUnavailableError,
53543
+ ObservabilityDashboardUnsupportedError,
53544
+ ObservabilityLatticeManager,
52964
53545
  OutboxPoller,
52965
53546
  PACK_DIRECTORY_TIMEOUT_MS,
52966
53547
  PLATFORM_SECRET_ENV_VARS,
@@ -53054,6 +53635,7 @@ export {
53054
53635
  buildTaskMutationFallback,
53055
53636
  buildTaskNormalizationFallback,
53056
53637
  canConvergeOrphan,
53638
+ channelShardForInstallation,
53057
53639
  checkEmptyContent,
53058
53640
  chunkBufferStreamKey,
53059
53641
  clearEncryptionKeyCache,
@@ -53158,6 +53740,7 @@ export {
53158
53740
  getEncryptionKey,
53159
53741
  getEvalRunService,
53160
53742
  getLoggerLattice,
53743
+ getMcpUiScopeSecret,
53161
53744
  getMenuRegistry,
53162
53745
  getModelLattice,
53163
53746
  getNextCronTime,
@@ -53226,6 +53809,7 @@ export {
53226
53809
  normalizeAgentInterrupts,
53227
53810
  normalizeAgentRunMessageIds,
53228
53811
  normalizeSandboxName,
53812
+ observabilityLatticeManager,
53229
53813
  ownTaskResponseField,
53230
53814
  parallelLimit,
53231
53815
  parseCronExpression,
@@ -53266,6 +53850,7 @@ export {
53266
53850
  registerLoggerLattice,
53267
53851
  registerModelLattice,
53268
53852
  registerModelLatticeForTenant,
53853
+ registerObservabilityLattice,
53269
53854
  registerQueueLattice,
53270
53855
  registerSTTModelLattice,
53271
53856
  registerSandboxOpenCredentialProvider,
@@ -53283,6 +53868,7 @@ export {
53283
53868
  resolveHandlerTimeoutMs,
53284
53869
  resolveJudgeModelKey,
53285
53870
  resolveModelLatticeForTenant,
53871
+ resolveObservabilityCallbacks,
53286
53872
  resolvePath,
53287
53873
  resolvePluginConnections,
53288
53874
  resolveSandboxPluginConnections,
@@ -53303,11 +53889,13 @@ export {
53303
53889
  serializeTaskReadResponse,
53304
53890
  setAgentLifecycleTap,
53305
53891
  setBindingRegistry,
53892
+ setDefaultObservabilityLattice,
53306
53893
  setEvalRunService,
53307
53894
  setMenuRegistry,
53308
53895
  setPluginDeploymentService,
53309
53896
  setRunCancelHeartbeatFallbackObserver,
53310
53897
  setSandboxPluginCatalog,
53898
+ signMcpUiScope,
53311
53899
  skillLatticeManager,
53312
53900
  sqlDatabaseManager,
53313
53901
  storeLatticeManager,
@@ -53336,6 +53924,7 @@ export {
53336
53924
  validateToolInput,
53337
53925
  vectorStoreLatticeManager,
53338
53926
  vectorStoreProviderManager,
53927
+ verifyMcpUiScope,
53339
53928
  withLease,
53340
53929
  withTimeout,
53341
53930
  wrapMcpToolWithUi