@axiom-lattice/core 13.3.0 → 13.4.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.js CHANGED
@@ -2788,6 +2788,32 @@ var InMemoryThreadStore = class {
2788
2788
  total: filtered.length
2789
2789
  };
2790
2790
  }
2791
+ async listChannelSenders(tenantId2, channelInstallationId, limit) {
2792
+ const tenantThreads = this.threads.get(tenantId2);
2793
+ if (!tenantThreads) return [];
2794
+ const bySender = /* @__PURE__ */ new Map();
2795
+ for (const assistantThreads of tenantThreads.values()) {
2796
+ for (const thread of assistantThreads.values()) {
2797
+ const metadata = thread.metadata ?? {};
2798
+ if (metadata.channelInstallationId !== channelInstallationId) continue;
2799
+ if (typeof metadata.senderId !== "string" || !metadata.senderId) continue;
2800
+ const existing = bySender.get(metadata.senderId);
2801
+ if (existing && existing.lastSeenAt.getTime() >= thread.updatedAt.getTime()) {
2802
+ continue;
2803
+ }
2804
+ bySender.set(metadata.senderId, {
2805
+ senderId: metadata.senderId,
2806
+ ...typeof metadata.senderDisplayName === "string" && metadata.senderDisplayName ? { displayName: metadata.senderDisplayName } : {},
2807
+ lastSeenAt: thread.updatedAt,
2808
+ lastThreadId: thread.id
2809
+ });
2810
+ }
2811
+ }
2812
+ const bounded = Math.max(1, Math.min(200, Math.floor(limit)));
2813
+ return [...bySender.values()].sort(
2814
+ (left, right) => right.lastSeenAt.getTime() - left.lastSeenAt.getTime()
2815
+ ).slice(0, bounded);
2816
+ }
2791
2817
  /**
2792
2818
  * Get a thread by ID for a specific tenant
2793
2819
  */
@@ -6608,6 +6634,8 @@ var InMemoryChannelInstallationStore = class {
6608
6634
  config: { ...data.config },
6609
6635
  enabled: data.enabled ?? true,
6610
6636
  fallbackAgentId: data.fallbackAgentId,
6637
+ workspaceId: data.workspaceId,
6638
+ projectId: data.projectId,
6611
6639
  rejectWhenNoBinding: data.rejectWhenNoBinding ?? true,
6612
6640
  createdAt: now,
6613
6641
  updatedAt: now
@@ -6631,7 +6659,9 @@ var InMemoryChannelInstallationStore = class {
6631
6659
  name: updates.name !== void 0 ? updates.name : existing.name,
6632
6660
  config: updates.config !== void 0 ? { ...existing.config, ...updates.config } : existing.config,
6633
6661
  enabled: updates.enabled !== void 0 ? updates.enabled : existing.enabled,
6634
- fallbackAgentId: updates.fallbackAgentId !== void 0 ? updates.fallbackAgentId : existing.fallbackAgentId,
6662
+ fallbackAgentId: updates.fallbackAgentId === null || updates.fallbackAgentId === "" ? void 0 : updates.fallbackAgentId !== void 0 ? updates.fallbackAgentId : existing.fallbackAgentId,
6663
+ workspaceId: updates.workspaceId === "" ? void 0 : updates.workspaceId !== void 0 ? updates.workspaceId : existing.workspaceId,
6664
+ projectId: updates.projectId === "" ? void 0 : updates.projectId !== void 0 ? updates.projectId : existing.projectId,
6635
6665
  rejectWhenNoBinding: updates.rejectWhenNoBinding !== void 0 ? updates.rejectWhenNoBinding : existing.rejectWhenNoBinding,
6636
6666
  updatedAt: /* @__PURE__ */ new Date()
6637
6667
  };
@@ -6740,8 +6770,8 @@ var InMemoryBindingStore = class {
6740
6770
  ...existing,
6741
6771
  agentId: patch.agentId ?? existing.agentId,
6742
6772
  threadId: patch.threadId !== void 0 ? patch.threadId : existing.threadId,
6743
- workspaceId: patch.workspaceId !== void 0 ? patch.workspaceId : existing.workspaceId,
6744
- projectId: patch.projectId !== void 0 ? patch.projectId : existing.projectId,
6773
+ workspaceId: patch.workspaceId === "" ? void 0 : patch.workspaceId !== void 0 ? patch.workspaceId : existing.workspaceId,
6774
+ projectId: patch.projectId === "" ? void 0 : patch.projectId !== void 0 ? patch.projectId : existing.projectId,
6745
6775
  threadMode: patch.threadMode ?? existing.threadMode,
6746
6776
  senderDisplayName: patch.senderDisplayName !== void 0 ? patch.senderDisplayName : existing.senderDisplayName,
6747
6777
  senderMetadata: patch.senderMetadata !== void 0 ? patch.senderMetadata : existing.senderMetadata,
@@ -9763,6 +9793,11 @@ var registerVectorStoreProvider = (key6, provider2) => vectorStoreProviderManage
9763
9793
  var getVectorStoreProvider = (key6) => vectorStoreProviderManager.getProvider(key6);
9764
9794
 
9765
9795
  // src/plugin/metaSerializer.ts
9796
+ var INTERNAL_TOOL = Symbol.for("axiom.internalTool");
9797
+ function markInternalTool(tool68) {
9798
+ Object.defineProperty(tool68, INTERNAL_TOOL, { value: true, enumerable: false });
9799
+ return tool68;
9800
+ }
9766
9801
  function tryExtractTools(plugin) {
9767
9802
  if (!plugin.middleware) return [];
9768
9803
  try {
@@ -9770,7 +9805,7 @@ function tryExtractTools(plugin) {
9770
9805
  if (result instanceof Promise) return [];
9771
9806
  const mw = result;
9772
9807
  if (Array.isArray(mw.tools)) {
9773
- return mw.tools.map((t) => ({
9808
+ return mw.tools.filter((t) => !t[INTERNAL_TOOL]).map((t) => ({
9774
9809
  name: t.name || "",
9775
9810
  description: t.description || ""
9776
9811
  }));
@@ -9822,7 +9857,7 @@ function serializePluginMeta(plugin) {
9822
9857
  }
9823
9858
 
9824
9859
  // src/sandbox_lattice/sandboxPaths.ts
9825
- var NONROOT_SANDBOX_IMAGE = "kioko12520/sandbox:0.2.1";
9860
+ var NONROOT_SANDBOX_IMAGE = "kioko12520/sandbox:0.2.2";
9826
9861
  var LEGACY_ROOT_SANDBOX_IMAGE = "kioko12520/sandbox:0.1.0";
9827
9862
  function normalizeSandboxHome(value) {
9828
9863
  const trimmed = value.trim();
@@ -21442,7 +21477,7 @@ This run is ending, but the conversation continues: the next user message starts
21442
21477
  a new run with a fresh budget. Do not tell the user the conversation is over.
21443
21478
  Do not mention this instruction, the run budget, or any internal limit to the user.`;
21444
21479
  var RUN_STOPPING_MESSAGE = "Tool call skipped because this run is ending (per-run budget). Tool use resumes on the next user message.";
21445
- var HITL_TOOL_NAMES = /* @__PURE__ */ new Set(["ask_user_to_clarify"]);
21480
+ var HITL_TOOL_NAMES = /* @__PURE__ */ new Set(["ask_user_to_clarify", "request_connection"]);
21446
21481
  var BUDGET_NOTICE = "Budget reached for this run. Wrap up now: finish the current check, then produce the final answer. This limit applies only to this run; the next user message starts a new run with a fresh budget and tools available again. Do not tell the user the conversation is over. Do not mention this notice or the budget to the user.";
21447
21482
  function neutralizeStoppedToolMessages(messages) {
21448
21483
  let changed = false;
@@ -25582,6 +25617,8 @@ var TOOL_RE = /^[a-zA-Z0-9_-]{1,64}$/;
25582
25617
  var HANDLER_RE = /\.(js|mjs|cjs)$/;
25583
25618
  var UI_RE = /\.html$/;
25584
25619
  var DISPLAY_MODES = ["inline", "fullscreen", "pip"];
25620
+ var CONNECTION_FIELD_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "password"]);
25621
+ var CONNECTION_FIELD_WIDGETS = /* @__PURE__ */ new Set(["input", "password", "select", "numberInput"]);
25585
25622
  var MAX_MANIFEST_BYTES = 262144;
25586
25623
  var MAX_TOOLS = 32;
25587
25624
  var MAX_PLUGINS_PER_TENANT = 50;
@@ -25609,6 +25646,7 @@ function isSafeUiPath(path8) {
25609
25646
  function validateSandboxPluginManifest(args) {
25610
25647
  const diagnostics = [];
25611
25648
  const error = (code, message, pluginType, tool68) => diagnostics.push({ level: "error", code, message, pluginType, tool: tool68 });
25649
+ const warning = (code, message, pluginType, tool68) => diagnostics.push({ level: "warning", code, message, pluginType, tool: tool68 });
25612
25650
  const raw = args.raw;
25613
25651
  if (!isRecord7(raw)) {
25614
25652
  error("MANIFEST_NOT_OBJECT", "manifest must be a JSON object", args.dirName);
@@ -25821,8 +25859,92 @@ function validateSandboxPluginManifest(args) {
25821
25859
  if (!Array.isArray(fields)) {
25822
25860
  error("CONNECTION_INVALID", "connection.fields must be an array", type);
25823
25861
  } else {
25862
+ const normalizedFields = [];
25863
+ fields.forEach((field, index) => {
25864
+ if (!isRecord7(field)) {
25865
+ error(
25866
+ "CONNECTION_FIELD_INVALID",
25867
+ `connection.fields[${index}] must be an object`,
25868
+ type
25869
+ );
25870
+ return;
25871
+ }
25872
+ const key6 = field.key;
25873
+ const fieldType = field.type;
25874
+ const title = field.title;
25875
+ if (typeof key6 !== "string" || key6.trim() === "") {
25876
+ error(
25877
+ "CONNECTION_FIELD_INVALID",
25878
+ `connection.fields[${index}] requires a non-empty string key`,
25879
+ type
25880
+ );
25881
+ return;
25882
+ }
25883
+ if (typeof fieldType !== "string" || !CONNECTION_FIELD_TYPES.has(fieldType)) {
25884
+ error(
25885
+ "CONNECTION_FIELD_INVALID",
25886
+ `connection.fields[${index}] (${key6}) type must be one of ${[
25887
+ ...CONNECTION_FIELD_TYPES
25888
+ ].join(", ")}`,
25889
+ type
25890
+ );
25891
+ return;
25892
+ }
25893
+ if (typeof title !== "string" || title.trim() === "") {
25894
+ error(
25895
+ "CONNECTION_FIELD_INVALID",
25896
+ `connection.fields[${index}] (${key6}) requires a non-empty string title (the human-visible label; use "title", not "label")`,
25897
+ type
25898
+ );
25899
+ return;
25900
+ }
25901
+ if (field.widget !== void 0 && (typeof field.widget !== "string" || !CONNECTION_FIELD_WIDGETS.has(field.widget))) {
25902
+ error(
25903
+ "CONNECTION_FIELD_INVALID",
25904
+ `connection.fields[${index}] (${key6}) widget must be one of ${[
25905
+ ...CONNECTION_FIELD_WIDGETS
25906
+ ].join(", ")}`,
25907
+ type
25908
+ );
25909
+ return;
25910
+ }
25911
+ if (field.required !== void 0 && typeof field.required !== "boolean") {
25912
+ error(
25913
+ "CONNECTION_FIELD_INVALID",
25914
+ `connection.fields[${index}] (${key6}) required must be a boolean`,
25915
+ type
25916
+ );
25917
+ return;
25918
+ }
25919
+ if (field.enumValues !== void 0 && (!Array.isArray(field.enumValues) || field.enumValues.some((value) => typeof value !== "string"))) {
25920
+ error(
25921
+ "CONNECTION_FIELD_INVALID",
25922
+ `connection.fields[${index}] (${key6}) enumValues must be an array of strings`,
25923
+ type
25924
+ );
25925
+ return;
25926
+ }
25927
+ if (field.helpText !== void 0 && typeof field.helpText !== "string") {
25928
+ error(
25929
+ "CONNECTION_FIELD_INVALID",
25930
+ `connection.fields[${index}] (${key6}) helpText must be a string`,
25931
+ type
25932
+ );
25933
+ return;
25934
+ }
25935
+ if (title.trim().toLowerCase() === "label" || title.trim() === key6) {
25936
+ warning(
25937
+ "CONNECTION_FIELD_TITLE_PLACEHOLDER",
25938
+ `connection.fields[${index}] (${key6}) title "${title}" looks like a placeholder; use the human-visible label (for example "API Key")`,
25939
+ type
25940
+ );
25941
+ }
25942
+ normalizedFields.push(
25943
+ field
25944
+ );
25945
+ });
25824
25946
  const normalized = {
25825
- fields
25947
+ fields: normalizedFields
25826
25948
  };
25827
25949
  if (typeof raw.connection.resourceLabel === "string") {
25828
25950
  normalized.resourceLabel = raw.connection.resourceLabel;
@@ -28432,7 +28554,7 @@ function hasExpectedInterrupt(interrupts, expectedInterruptId) {
28432
28554
  return interrupts.length === 1 && interrupts[0]?.interruptId === expectedInterruptId;
28433
28555
  }
28434
28556
  return interrupts.filter(
28435
- (interrupt5) => interrupt5.interruptId === expectedInterruptId
28557
+ (interrupt6) => interrupt6.interruptId === expectedInterruptId
28436
28558
  ).length === 1;
28437
28559
  }
28438
28560
  function normalizeAgentInterrupts(state, threadId) {
@@ -28442,11 +28564,11 @@ function normalizeAgentInterrupts(state, threadId) {
28442
28564
  if (!isRecord12(task) || !Array.isArray(task.interrupts)) return;
28443
28565
  const rawTaskId = task.id;
28444
28566
  const taskId = typeof rawTaskId === "string" || typeof rawTaskId === "number" ? String(rawTaskId) : void 0;
28445
- task.interrupts.forEach((interrupt5, index) => {
28446
- const record = isRecord12(interrupt5) ? interrupt5 : {};
28567
+ task.interrupts.forEach((interrupt6, index) => {
28568
+ const record = isRecord12(interrupt6) ? interrupt6 : {};
28447
28569
  const rawId = record.id;
28448
28570
  const interruptId = typeof rawId === "string" || typeof rawId === "number" ? String(rawId) : `${taskId ?? `task-${taskIndex}`}:${index}`;
28449
- const rawValue = isRecord12(interrupt5) ? record.value : interrupt5;
28571
+ const rawValue = isRecord12(interrupt6) ? record.value : interrupt6;
28450
28572
  const fenced = parseFence(rawValue);
28451
28573
  const value = fenced ? fenced.payload : rawValue;
28452
28574
  let type;
@@ -31975,6 +32097,27 @@ var Agent = class {
31975
32097
  this.queue_workspace_id = params.workspace_id === null ? null : this.workspace_id;
31976
32098
  this.queue_project_id = params.project_id == null || params.project_id === "" ? null : this.project_id;
31977
32099
  }
32100
+ /**
32101
+ * Re-pins scope for a dispatch without racing an in-flight run.
32102
+ *
32103
+ * Legacy entry points reuse one Agent per thread; when they carry a project
32104
+ * scope they must make it authoritative before the next sandbox is created.
32105
+ * If a run is already active, defer the update until it settles.
32106
+ */
32107
+ applyExecutionScopeIfIdle(params) {
32108
+ if (this.activeExecutionPromise !== void 0) {
32109
+ this.pendingExecutionScope = params;
32110
+ return;
32111
+ }
32112
+ this.applyExecutionScope(params);
32113
+ }
32114
+ /** Applies a scope requested during the previous active execution. */
32115
+ applyPendingExecutionScope() {
32116
+ const pending = this.pendingExecutionScope;
32117
+ if (pending === void 0) return;
32118
+ this.pendingExecutionScope = void 0;
32119
+ this.applyExecutionScope(pending);
32120
+ }
31978
32121
  /**
31979
32122
  * Accepts host-authenticated queue metadata through the package-private symbol capability.
31980
32123
  *
@@ -32781,7 +32924,7 @@ var Agent = class {
32781
32924
  try {
32782
32925
  const state = await this.getCurrentState();
32783
32926
  const durable = (state?.tasks ?? []).some(
32784
- (task) => (task.interrupts ?? []).some((interrupt5) => interrupt5.id === interruptId)
32927
+ (task) => (task.interrupts ?? []).some((interrupt6) => interrupt6.id === interruptId)
32785
32928
  );
32786
32929
  if (durable) return;
32787
32930
  } catch {
@@ -33962,7 +34105,9 @@ var Agent = class {
33962
34105
  trackActiveExecution(execution) {
33963
34106
  this.activeExecutionPromise = execution;
33964
34107
  const clear = () => {
33965
- if (this.activeExecutionPromise === execution) this.activeExecutionPromise = void 0;
34108
+ if (this.activeExecutionPromise !== execution) return;
34109
+ this.activeExecutionPromise = void 0;
34110
+ this.applyPendingExecutionScope();
33966
34111
  };
33967
34112
  void execution.then(clear, clear);
33968
34113
  return execution;
@@ -34174,8 +34319,11 @@ var AgentInstanceManager = class _AgentInstanceManager {
34174
34319
  });
34175
34320
  }
34176
34321
  /**
34177
- * Get or create Agent instance for a thread
34178
- * Ensures only one instance per thread exists
34322
+ * Get or create Agent instance for a thread.
34323
+ *
34324
+ * Ensures only one instance per thread exists. Read-only callers should use
34325
+ * {@link getAgentForRead}; dispatch callers use {@link getAgentForDispatch}
34326
+ * so the run's project scope is applied before a sandbox is created.
34179
34327
  */
34180
34328
  getAgent(params) {
34181
34329
  const key6 = this.getKey(params);
@@ -34186,6 +34334,26 @@ var AgentInstanceManager = class _AgentInstanceManager {
34186
34334
  }
34187
34335
  return this.agents.get(key6);
34188
34336
  }
34337
+ /**
34338
+ * Resolve the managed Agent for a dispatch and apply its explicit project.
34339
+ *
34340
+ * Legacy execution paths (channels, commands, cron, scheduler, Web App,
34341
+ * Open API, task comments, queue recovery) reuse the same per-thread Agent
34342
+ * instance. An explicit project must become authoritative before the next
34343
+ * sandbox is created; while a run is active it is deferred by
34344
+ * {@link Agent.applyExecutionScopeIfIdle}. Calls without a project do not
34345
+ * clear an already-established scope.
34346
+ */
34347
+ getAgentForDispatch(params) {
34348
+ const agent = this.getAgent(params);
34349
+ if (typeof params.project_id === "string" && params.project_id.length > 0) {
34350
+ agent.applyExecutionScopeIfIdle({
34351
+ workspace_id: params.workspace_id,
34352
+ project_id: params.project_id
34353
+ });
34354
+ }
34355
+ return agent;
34356
+ }
34189
34357
  /**
34190
34358
  * Get the managed Agent for an exclusive execution and re-pin its scope.
34191
34359
  *
@@ -34208,14 +34376,11 @@ var AgentInstanceManager = class _AgentInstanceManager {
34208
34376
  /**
34209
34377
  * Get the managed Agent for a thread WITHOUT creating or registering one.
34210
34378
  *
34211
- * Read-only control-plane callers (state, memory, inbox) must not be the first
34212
- * to establish a thread's execution scope: since identity is
34213
- * `(tenant_id, assistant_id, thread_id)`, whichever caller reaches
34214
- * {@link getAgent} first fixes the instance's workspace/project for its whole
34215
- * lifetime, and a later trusted dispatch on that thread would then fail
34216
- * trusted-scope validation. This returns the existing managed instance when
34379
+ * Read-only control-plane callers (state, memory, inbox) must not mutate a
34380
+ * thread's execution scope. This returns the existing managed instance when
34217
34381
  * present, otherwise a transient unregistered Agent that is sufficient for
34218
- * state reads and disappears with the request.
34382
+ * state reads and disappears with the request. Dispatch callers use
34383
+ * {@link getAgentForDispatch}.
34219
34384
  *
34220
34385
  * @param params - Thread identity; scope is only used for the transient Agent.
34221
34386
  * @returns The managed instance if any, else an unregistered read-only Agent.
@@ -34328,7 +34493,7 @@ var DelegationService = class {
34328
34493
  throw new DelegatedThreadBusyError(request.thread_id);
34329
34494
  }
34330
34495
  try {
34331
- const agent = agentInstanceManager.getAgent({
34496
+ const agent = agentInstanceManager.getAgentForDispatch({
34332
34497
  assistant_id: request.assistant_id,
34333
34498
  thread_id: request.thread_id,
34334
34499
  tenant_id: request.tenantId,
@@ -35173,7 +35338,7 @@ function registerAgentAddMessageHandler() {
35173
35338
  workspace_id: runConfigFromMetadata?.workspaceId ?? "",
35174
35339
  project_id: runConfigFromMetadata?.projectId ?? ""
35175
35340
  }));
35176
- const agent = agentInstanceManager.getAgent({
35341
+ const agent = agentInstanceManager.getAgentForDispatch({
35177
35342
  tenant_id: taskInfo.tenantId,
35178
35343
  assistant_id: taskInfo.assistantId ?? "",
35179
35344
  thread_id: taskInfo.threadId ?? "",
@@ -44712,7 +44877,7 @@ function parseJudgeVerdict(raw) {
44712
44877
  }
44713
44878
  }
44714
44879
  var MAX_INTERRUPT_RESUMES = 5;
44715
- function resolveInterruptResponse(policy, interrupt5) {
44880
+ function resolveInterruptResponse(policy, interrupt6) {
44716
44881
  if (policy.mode === "auto-approve") return policy.value ?? "\u540C\u610F";
44717
44882
  if (policy.mode === "auto-reject") return policy.value ?? "\u62D2\u7EDD";
44718
44883
  return policy.value ?? "";
@@ -44803,7 +44968,7 @@ var _LatticeEval = class _LatticeEval {
44803
44968
  workspace_id: this.config.workspace_id || "default",
44804
44969
  project_id: this.config.project_id || "default"
44805
44970
  };
44806
- const agent = agentInstanceManager.getAgent(agentParams);
44971
+ const agent = agentInstanceManager.getAgentForDispatch(agentParams);
44807
44972
  try {
44808
44973
  const stepInput = {
44809
44974
  message: step.override_message || inputMessage,
@@ -44814,31 +44979,31 @@ var _LatticeEval = class _LatticeEval {
44814
44979
  let pendingInterrupt;
44815
44980
  let interrupts = Array.isArray(result?.__interrupt__) ? result.__interrupt__ : [];
44816
44981
  while (interrupts.length > 0) {
44817
- const interrupt5 = interrupts[0];
44818
- if (!interrupt5) break;
44982
+ const interrupt6 = interrupts[0];
44983
+ if (!interrupt6) break;
44819
44984
  const policy = interruptPolicy;
44820
44985
  if (!policy || policy.mode === "stop" || resumeCount >= MAX_INTERRUPT_RESUMES) {
44821
- pendingInterrupt = interrupt5;
44986
+ pendingInterrupt = interrupt6;
44822
44987
  break;
44823
44988
  }
44824
- const response = resolveInterruptResponse(policy, interrupt5);
44989
+ const response = resolveInterruptResponse(policy, interrupt6);
44825
44990
  hitlEvents.push({
44826
44991
  type: "interrupt",
44827
- id: interrupt5.id,
44828
- value: interrupt5.value
44992
+ id: interrupt6.id,
44993
+ value: interrupt6.value
44829
44994
  });
44830
44995
  this.log("Auto-resolving HITL interrupt", {
44831
44996
  agent_id: step.agent_id,
44832
44997
  thread_id: threadId,
44833
44998
  mode: policy.mode,
44834
- interrupt_id: interrupt5.id,
44999
+ interrupt_id: interrupt6.id,
44835
45000
  response,
44836
45001
  resume_count: resumeCount + 1
44837
45002
  });
44838
45003
  result = await agent.invokeWithState({ input: stepInput, command: { resume: response } });
44839
45004
  hitlEvents.push({
44840
45005
  type: "interrupt_response",
44841
- id: interrupt5.id,
45006
+ id: interrupt6.id,
44842
45007
  mode: policy.mode,
44843
45008
  response
44844
45009
  });
@@ -44935,7 +45100,7 @@ var _LatticeEval = class _LatticeEval {
44935
45100
  });
44936
45101
  let currentThreadId = threadId;
44937
45102
  let lastResponseData = null;
44938
- let interrupt5;
45103
+ let interrupt6;
44939
45104
  for (const step of evalCase.steps) {
44940
45105
  const result = await this.executeAgentStep(
44941
45106
  step,
@@ -45001,10 +45166,10 @@ ${toolCallStr}` : toolCallStr;
45001
45166
  }
45002
45167
  }
45003
45168
  if (result.interrupted) {
45004
- interrupt5 = result.interrupt;
45169
+ interrupt6 = result.interrupt;
45005
45170
  this.log("Case paused for HITL \u2014 remaining steps skipped; judge will evaluate the pause", {
45006
45171
  case_id: evalCase.caseId,
45007
- interrupt_id: interrupt5?.id
45172
+ interrupt_id: interrupt6?.id
45008
45173
  });
45009
45174
  break;
45010
45175
  }
@@ -45014,7 +45179,7 @@ ${toolCallStr}` : toolCallStr;
45014
45179
  final_thread_id: currentThreadId,
45015
45180
  message_count: this.lastMessages.length
45016
45181
  });
45017
- const finalOutput = interrupt5 ? typeof interrupt5.value === "string" ? interrupt5.value : JSON.stringify(interrupt5.value ?? "") : this.extractFinalMessage(lastResponseData);
45182
+ const finalOutput = interrupt6 ? typeof interrupt6.value === "string" ? interrupt6.value : JSON.stringify(interrupt6.value ?? "") : this.extractFinalMessage(lastResponseData);
45018
45183
  this.lastFinalOutput = finalOutput;
45019
45184
  const trajectory = this.buildTrajectory();
45020
45185
  this.log("Final output extracted", {
@@ -45234,8 +45399,8 @@ Note: if final_score >= 80 and there are no fatal errors, pass should be true; o
45234
45399
  final_score: finalScore,
45235
45400
  dimension_results: dimensionResults,
45236
45401
  summary: parsedResult.summary || testResultContent,
45237
- interrupted: interrupt5 ? true : void 0,
45238
- interrupt: interrupt5 ? { id: interrupt5.id, value: interrupt5.value } : void 0
45402
+ interrupted: interrupt6 ? true : void 0,
45403
+ interrupt: interrupt6 ? { id: interrupt6.id, value: interrupt6.value } : void 0
45239
45404
  };
45240
45405
  }
45241
45406
  };
@@ -46790,7 +46955,7 @@ var ThreadExecutionSupervisor = class {
46790
46955
  this.probeCooldownMs = positiveOr(options.probeCooldownMs, this.cooldownMs);
46791
46956
  this.reapEveryNTicks = positiveIntegerOr(options.reapEveryNTicks, 10);
46792
46957
  this.maxInFlightAgeMs = positiveOr(options.maxInFlightAgeMs, 30 * 60 * 1e3);
46793
- this.getAgent = options.getAgent ?? ((params) => agentInstanceManager.getAgent(params));
46958
+ this.getAgent = options.getAgent ?? ((params) => agentInstanceManager.getAgentForDispatch(params));
46794
46959
  this.probeThreadRunOwner = options.probeThreadRunOwner ?? probeThreadRunOwner;
46795
46960
  this.log = options.log;
46796
46961
  }
@@ -56735,6 +56900,7 @@ var projectRoomPlugin = {
56735
56900
 
56736
56901
  // src/middlewares/sandboxPluginsMiddleware.ts
56737
56902
  var import_langchain87 = require("langchain");
56903
+ var import_langgraph14 = require("@langchain/langgraph");
56738
56904
  var import_zod75 = require("zod");
56739
56905
  var import_protocols62 = require("@axiom-lattice/protocols");
56740
56906
 
@@ -57269,7 +57435,7 @@ description: Field-by-field reference for plugin.json of a tenant sandbox plugin
57269
57435
  | \`name\` / \`description\` | Display strings. |
57270
57436
  | \`version\` | Non-empty string; bump it when files change so the hash refreshes. |
57271
57437
  | \`tools[]\` | See below. Max 32 tools. |
57272
- | \`connection\` | Optional; see the sandbox-plugins-connection skill. |
57438
+ | \`connection\` | Optional; \`connection.fields[]\` uses \`{ key, type, title, widget?, required?, default?, enumValues?, helpText? }\` \u2014 \`title\` is the human-visible label (not \`label\`). See the sandbox-plugins-connection skill. |
57273
57439
  | \`skills\` | Optional; keys must start with \`<type>-\`. |
57274
57440
  | \`agents\` | The schema accepts it and tenant plugin agents are registered, but this is **not a supported authoring path** \u2014 do not declare it. Build standalone agents with the Agent Architect (\`agent-architecture\`/\`agent-build\`); built-in plugins may still use this field. |
57275
57441
 
@@ -57622,8 +57788,10 @@ The platform key belongs to a human. Before writing the real handler:
57622
57788
  2. Write a temporary \`handlers/probe.js\` that reads \`PLUGIN_CONNECTION_FILE\`,
57623
57789
  creates \`OpenMcpClient\` with the connection key, and prints
57624
57790
  \`listTools()\` (name, description, inputSchema) as JSON.
57625
- 3. Ask the human to configure the connection + platform key (only a human can
57626
- create the key). Use \`list_connections\` to check whether a connection exists.
57791
+ 3. Call \`list_connections\` first; if no usable connection exists, call
57792
+ \`request_connection { type, pluginKey, toolName, reason }\` \u2014 it opens an inline
57793
+ connection form in the chat. Never ask the user to type, paste, or share any
57794
+ secret (password, API key, token) in chat.
57627
57795
  4. Run \`manage_plugin test\` with the real \`connectionKey\`, e.g.
57628
57796
  \`{ "kind": "tool", "name": "probe", "input": {}, "connectionKey": "prod" }\`.
57629
57797
  5. Read the returned tool list; use it to choose the downstream tool names and
@@ -57823,11 +57991,15 @@ main().catch((err) => {
57823
57991
  });
57824
57992
  \`\`\`
57825
57993
 
57826
- ### 3. Ask a human to configure the connection
57994
+ ### 3. Request the connection
57827
57995
 
57828
57996
  - Call \`list_connections { type }\`.
57829
- - If the connection or key is missing, use \`ask_user_to_clarify\`: only a human can
57830
- create the platform API key and fill the connection.
57997
+ - If no usable connection exists, call
57998
+ \`request_connection { type, pluginKey, toolName, reason }\`; it opens an inline
57999
+ connection form in the chat. Only a human can create the platform API key and
58000
+ fill the connection.
58001
+ - Never ask the user to type, paste, or share any secret (password, API key,
58002
+ token) in chat.
57831
58003
  - Never claim PTC works until a real \`connectionKey\` test passes.
57832
58004
 
57833
58005
  ### 4. Test with a real connection
@@ -57946,8 +58118,8 @@ resolution path. See \`sandbox-plugins-handlers\` \u2192 "Dependencies".
57946
58118
  | every input field missing / \`{}\` | parsed base64 \`PLUGIN_INPUT\` as plaintext and swallowed the error | decode base64 with a plaintext fallback; fail visibly |
57947
58119
  | \`API_GATEWAY_URL\` empty | Gateway has no \`PUBLIC_GATEWAY_URL\` | ask a human to set it; do not guess a host |
57948
58120
  | \`OPEN_API_TOKEN\` empty | expected in plugin handlers (cleared by design) | use the connection password field, never the env token |
57949
- | \`token is required\` / \`OpenMcpConfigError\` | connection has no platform key | ask the human to configure it |
57950
- | \`OpenMcpAuthError\` / 401 | key disabled, rotated, or invalid | ask the human to rotate/configure |
58121
+ | \`token is required\` / \`OpenMcpConfigError\` | connection has no platform key | call \`request_connection\` (inline form) |
58122
+ | \`OpenMcpAuthError\` / 401 | key disabled, rotated, or invalid | call \`request_connection\` (inline form) to reconfigure |
57951
58123
  | tool-not-found | key has no such domain/action | do not retry; fix the key grant |
57952
58124
  | \`GRANT_DENIED\` | key lacks the action | do not retry; fix the key grant |
57953
58125
  | \`CONNECTION_NOT_ALLOWED\` / \`RESOURCE_DENIED\` | \`selector.connections\` mismatch | use an allowed connection or fix the key scope |
@@ -57959,7 +58131,8 @@ If the plugin previously called \`OpenMcpClient.fromEnv()\`:
57959
58131
  1. Add a password field to \`connection.fields\` (for example \`platformApiKey\`).
57960
58132
  2. Read \`PLUGIN_CONNECTION_FILE.connection.platformApiKey\`.
57961
58133
  3. Construct \`new OpenMcpClient({ url: process.env.API_GATEWAY_URL, token: ... })\`.
57962
- 4. Ask the human to fill the connection key.
58134
+ 4. If no usable connection exists, call
58135
+ \`request_connection { type, pluginKey, toolName, reason }\`.
57963
58136
  5. Re-test with \`manage_plugin test\` + \`connectionKey\`.
57964
58137
 
57965
58138
  \`fromEnv()\` still works for agent \`code_eval\`, not for plugin handlers.
@@ -58124,8 +58297,32 @@ description: Define connection fields and test/discover handlers for a tenant sa
58124
58297
 
58125
58298
  # Connections
58126
58299
 
58127
- Define \`connection.fields\` in plugin.json. Field widgets: \`input\`, \`password\`,
58128
- \`select\` (with \`enumValues\`), \`numberInput\`. Mark secrets as \`type: "password"\`.
58300
+ Define \`connection.fields\` in plugin.json. Each field is:
58301
+
58302
+ \`{ key, type, title, widget?, required?, default?, enumValues?, helpText? }\`
58303
+
58304
+ - \`key\` (required): the config key your handler reads from \`PLUGIN_CONNECTION_FILE\`.
58305
+ - \`type\` (required): \`"string"\`, \`"number"\`, \`"boolean"\`, or \`"password"\`.
58306
+ - \`title\` (required): the human-visible label shown in the connection form.
58307
+ Use the real field name (for example \`"API Key"\` or \`"Server URL"\`);
58308
+ never use a placeholder such as \`"label"\`, and never use \`label\` as the
58309
+ property name.
58310
+ - \`widget\` (optional): \`"input"\`, \`"password"\`, \`"select"\`, or \`"numberInput"\`.
58311
+ - \`required\` (optional boolean), \`default\` (optional value),
58312
+ \`enumValues\` (required for \`select\`; string array), \`helpText\` (optional string).
58313
+
58314
+ \`\`\`json
58315
+ {
58316
+ "connection": {
58317
+ "fields": [
58318
+ { "key": "baseUrl", "type": "string", "title": "Server URL", "required": true },
58319
+ { "key": "apiKey", "type": "password", "title": "API Key", "widget": "password", "required": true }
58320
+ ]
58321
+ }
58322
+ }
58323
+ \`\`\`
58324
+
58325
+ Mark secrets as \`type: "password"\`.
58129
58326
 
58130
58327
  The resolved connection is injected at execution time as an
58131
58328
  \`{ connection?, connections? }\` envelope in a JSON file path passed through
@@ -58171,10 +58368,18 @@ Use the \`manage_plugin\` tool. The loop:
58171
58368
  2. \`action: "validate"\` with \`{ type }\` \u2014 reads the plugin back **from the sandbox** and returns diagnostics (no writes). The files must already be on disk; a \`type\` with no files reports a read error.
58172
58369
  3. If the plugin has \`connection.fields\` and a tool reads credentials: a **human**
58173
58370
  must configure a connection of this plugin type. You cannot create credentials.
58174
- Call \`list_connections { type }\` first \u2014 if none exist, use \`ask_user_to_clarify\`
58175
- to state explicitly that only the human can configure the connector, ask them to
58176
- add it (Console \u2192 Connections) and to give you the connection key. Do not claim
58177
- the tool works until a real \`connectionKey\` test passes.
58371
+ Call \`list_connections { type }\` first \u2014 if no usable connection exists, call
58372
+ \`request_connection { type, pluginKey, toolName, reason }\`; it opens an inline
58373
+ connection form in the chat. The human configures, tests, and saves it; you
58374
+ receive only the connection key and whether the test passed \u2014 never the
58375
+ secret values.
58376
+ Never ask the user to type, paste, or share any secret (password, API key,
58377
+ token) in chat. Do not claim the tool works until a real \`connectionKey\` test
58378
+ passes. If the human cancels, report it as unverified (missing credentials) and
58379
+ end the run; do not call \`request_connection\` again in this run.
58380
+ If you just authored or changed this plugin, call \`manage_plugin { action: "reload" }\`
58381
+ before \`request_connection\`; \`/api/middleware-types\` only sees the new connection
58382
+ schema after the catalog reloads.
58178
58383
  4. \`action: "reload"\` \u2014 refresh the compiled catalog after writing/editing files (the catalog caches; an edited file is invisible to \`test\` until you reload).
58179
58384
  5. \`action: "test"\` to exercise a handler without an LLM:
58180
58385
  - Tool: \`{ type, target: { kind: "tool", name, input, connectionKey? } }\`
@@ -58368,13 +58573,22 @@ After the human confirms the design, author the plugin files directly with the f
58368
58573
  the sandbox) \u2192 \`manage_plugin { action: "reload", type }\` (the catalog caches, so a
58369
58574
  freshly written file is invisible to \`test\` until you reload) \u2192 \`manage_plugin
58370
58575
  { action: "test", type, target }\`.
58371
- If a tool needs credentials, a human must configure the connection \u2014 use
58372
- \`list_connections\` to check, and \`ask_user_to_clarify\` to ask the human to add
58373
- the connector and give you its key. Only after a real \`connectionKey\` test
58374
- passes may you call the tool verified; without it, report functionality as
58375
- unverified (missing credentials), not as passing. Use \`shell_exec\` (the tool
58376
- provided by the \`code_eval\` middleware) to run \`node handlers/x.js\` for manual
58377
- checks when reproducing a failure.
58576
+ If a tool needs credentials, check \`list_connections\` first. If no usable
58577
+ connection exists, call \`request_connection { type, pluginKey, toolName, reason }\`
58578
+ \u2014 it opens an inline connection form in the chat. The human fills it in, tests
58579
+ it, and saves; you receive only the connection key and whether the test passed
58580
+ \u2014 never the secret values. If you just authored or changed this plugin, call
58581
+ \`manage_plugin { action: "reload" }\` before \`request_connection\`;
58582
+ \`/api/middleware-types\` only sees the new connection schema after the catalog
58583
+ reloads.
58584
+ Never ask the user to type, paste, or share any secret (password, API key,
58585
+ token) in chat. Only after a real \`connectionKey\` test passes may you call the
58586
+ tool verified; without it, report functionality as unverified (missing
58587
+ credentials), not as passing. If the human cancels, report it as unverified
58588
+ (missing credentials) and end the run; do not call \`request_connection\`
58589
+ again in this run. Use \`shell_exec\` (the tool provided by the \`code_eval\`
58590
+ middleware) to run \`node handlers/x.js\` for manual checks when reproducing a
58591
+ failure.
58378
58592
 
58379
58593
  Deployment is human-gated: do NOT deploy on your own after the tests pass.
58380
58594
  Only deploy when the human explicitly asks for it or approves it, then load
@@ -58573,6 +58787,21 @@ function tenantIdFrom(exeConfig) {
58573
58787
  function errorText(err) {
58574
58788
  return err instanceof Error ? err.message : String(err);
58575
58789
  }
58790
+ function isRecord14(value) {
58791
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58792
+ }
58793
+ function truncate2(value, max) {
58794
+ if (typeof value !== "string") return void 0;
58795
+ return value.length > max ? `${value.slice(0, max)}\u2026` : value;
58796
+ }
58797
+ function isProjectRoomRun2(request) {
58798
+ if (!isRecord14(request) || !isRecord14(request.runtime)) return false;
58799
+ const runtime = request.runtime;
58800
+ const configurable = isRecord14(runtime.configurable) ? runtime.configurable.runConfig : void 0;
58801
+ const context = isRecord14(runtime.context) ? runtime.context.runConfig : void 0;
58802
+ const runConfig = isRecord14(configurable) ? configurable : isRecord14(context) ? context : void 0;
58803
+ return isRecord14(runConfig?.projectRoom);
58804
+ }
58576
58805
  function deploymentUnavailable(action) {
58577
58806
  const error = `plugin deployment service is not configured; cannot ${action}. Resident plugin services are unavailable in this environment.`;
58578
58807
  if (action === "undeploy") return JSON.stringify({ undeployed: false, error });
@@ -58609,6 +58838,13 @@ var managePluginSchema = import_zod75.z.object({
58609
58838
  connectionKey: import_zod75.z.string().optional()
58610
58839
  }).optional()
58611
58840
  });
58841
+ var requestConnectionSchema = import_zod75.z.object({
58842
+ type: import_zod75.z.string().trim().min(1).max(120).describe("Plugin connection type (the plugin meta.type)."),
58843
+ pluginKey: import_zod75.z.string().optional().describe("Plugin type being built, for display only."),
58844
+ toolName: import_zod75.z.string().optional().describe("Tool that needs the connection, for display only."),
58845
+ reason: import_zod75.z.string().optional().describe("Short reason shown to the human."),
58846
+ suggestedKey: import_zod75.z.string().optional().describe("Optional connection key prefill.")
58847
+ });
58612
58848
  var sandboxPluginsPlugin = {
58613
58849
  meta: {
58614
58850
  type: "sandbox-plugins",
@@ -59006,8 +59242,68 @@ var sandboxPluginsPlugin = {
59006
59242
  description: "Author and manage tenant sandbox plugins (list/get/validate/create/delete/reload/test/backup/restore) and deploy/undeploy/status a plugin as a resident service.",
59007
59243
  schema: managePluginSchema
59008
59244
  }
59245
+ ),
59246
+ markInternalTool(
59247
+ (0, import_langchain87.tool)(
59248
+ async (input) => JSON.stringify(input),
59249
+ {
59250
+ name: "request_connection",
59251
+ description: "Ask the human to configure a connection for the plugin being built. Use only when list_connections shows no usable connection. Opens an inline connection form in the chat; the human configures and tests the connector, and you receive only the connection key. Never ask the human to paste secrets into the chat. Call this tool alone, not in parallel with other tools.",
59252
+ schema: requestConnectionSchema
59253
+ }
59254
+ )
59009
59255
  )
59010
- ]
59256
+ ],
59257
+ wrapToolCall: async (request, handler) => {
59258
+ const toolCall = request.toolCall;
59259
+ if (toolCall?.name !== "request_connection") {
59260
+ return handler(request);
59261
+ }
59262
+ if (isProjectRoomRun2(request)) {
59263
+ return new import_langchain87.ToolMessage({
59264
+ content: "You are replying inside a project room, which has no interactive connection setup UI. Ask the user in plain text to configure the connection, then continue after their next message.",
59265
+ tool_call_id: toolCall.id,
59266
+ name: toolCall.name
59267
+ });
59268
+ }
59269
+ const parsed = requestConnectionSchema.safeParse(toolCall.args);
59270
+ if (!parsed.success) {
59271
+ return new import_langchain87.ToolMessage({
59272
+ content: `Invalid request_connection tool arguments: ${parsed.error.message}`,
59273
+ tool_call_id: toolCall.id,
59274
+ name: toolCall.name
59275
+ });
59276
+ }
59277
+ const input = parsed.data;
59278
+ const md = genUIMarkdown("connection_setup", {
59279
+ type: input.type,
59280
+ pluginKey: truncate2(input.pluginKey, 120),
59281
+ toolName: truncate2(input.toolName, 120),
59282
+ reason: truncate2(input.reason, 500),
59283
+ suggestedKey: truncate2(input.suggestedKey, 120)
59284
+ });
59285
+ const feedback = await (0, import_langgraph14.interrupt)(md);
59286
+ if (feedback?.action === "saved" && isRecord14(feedback.data)) {
59287
+ const connectionKey = feedback.data.connectionKey;
59288
+ if (typeof connectionKey === "string" && connectionKey.trim() !== "") {
59289
+ const testOk = feedback.data.testOk;
59290
+ const testPassed = testOk === true ? true : testOk === false ? false : null;
59291
+ return new import_langchain87.ToolMessage({
59292
+ content: JSON.stringify({
59293
+ connectionKey: connectionKey.trim(),
59294
+ testPassed
59295
+ }),
59296
+ tool_call_id: toolCall.id,
59297
+ name: toolCall.name
59298
+ });
59299
+ }
59300
+ }
59301
+ return new import_langchain87.ToolMessage({
59302
+ content: JSON.stringify({ cancelled: true }),
59303
+ tool_call_id: toolCall.id,
59304
+ name: toolCall.name
59305
+ });
59306
+ }
59011
59307
  })
59012
59308
  };
59013
59309
 
@@ -60374,11 +60670,11 @@ var INLINE_INPUT_LIMIT_BYTES2 = 48 * 1024;
60374
60670
  var DEFAULT_HANDLER_TIMEOUT_MS = 6e4;
60375
60671
  var MIN_HANDLER_TIMEOUT_MS = 1e3;
60376
60672
  var MAX_HANDLER_TIMEOUT_MS = 3e5;
60377
- function isRecord14(value) {
60673
+ function isRecord15(value) {
60378
60674
  return typeof value === "object" && value !== null && !Array.isArray(value);
60379
60675
  }
60380
60676
  function isEnvelope3(value) {
60381
- return isRecord14(value) && typeof value.ok === "boolean";
60677
+ return isRecord15(value) && typeof value.ok === "boolean";
60382
60678
  }
60383
60679
  function parseHostArgs(argv) {
60384
60680
  let type;