@axiom-lattice/core 10.0.5 → 10.1.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
@@ -11349,25 +11349,38 @@ domains your configured middleware exposes \u2014 and nothing beyond it.
11349
11349
 
11350
11350
  ## Client
11351
11351
 
11352
- The sandbox must have the zero-dependency \`@axiom-lattice/open-mcp-client\` package.
11353
- Get it one of two ways:
11354
-
11355
- - **Preinstalled in the sandbox image** (recommended): \`open-mcp\` is on \`PATH\`; for
11356
- \`require("@axiom-lattice/open-mcp-client")\` to resolve, install it into the working
11357
- directory or point \`NODE_PATH\` at the global \`node_modules\`.
11358
- - **Install it in this run** when the sandbox has network + npm:
11359
-
11360
- \`\`\`bash
11361
- npm install @axiom-lattice/open-mcp-client
11362
- # or use without installing:
11363
- npx @axiom-lattice/open-mcp-client tools list --json
11364
- \`\`\`
11352
+ The sandbox image provides the zero-dependency \`@axiom-lattice/open-mcp-client\`
11353
+ package. Use the bare module:
11365
11354
 
11366
11355
  \`\`\`js
11367
11356
  const { OpenMcpClient } = require("@axiom-lattice/open-mcp-client");
11368
11357
  const client = OpenMcpClient.fromEnv(); // reads API_GATEWAY_URL + OPEN_API_TOKEN
11369
11358
  \`\`\`
11370
11359
 
11360
+ ## Plugin handlers
11361
+
11362
+ A sandbox plugin handler reads the platform API key from its connection:
11363
+
11364
+ \`\`\`js
11365
+ const conn = JSON.parse(
11366
+ require("fs").readFileSync(process.env.PLUGIN_CONNECTION_FILE, "utf8"),
11367
+ ).connection;
11368
+ const client = new OpenMcpClient({
11369
+ url: process.env.API_GATEWAY_URL,
11370
+ token: conn.platformApiKey, // \u4F5C\u8005\u5728 connection.fields \u91CC\u5B9A\u4E49\u7684\u5B57\u6BB5
11371
+ });
11372
+ \`\`\`
11373
+
11374
+ - The platform key is a normal password field defined by the plugin author; the
11375
+ framework does not inject or rename it.
11376
+ - \`OPEN_API_TOKEN\` is only for agent \`code_eval\`; plugin handlers use the
11377
+ connection key directly.
11378
+ - Caller grants gate entry and connection selection; after that, the connection
11379
+ key's grants apply (service-account model).
11380
+
11381
+ Resource selection is not the handler's job: Open MCP tools are already bound to
11382
+ their resources. Use \`listTools()\` and \`callTool()\` only.
11383
+
11371
11384
  CLI equivalents (config comes from the same env vars):
11372
11385
 
11373
11386
  \`\`\`bash
@@ -12072,6 +12085,142 @@ var InMemoryMenuStore = class {
12072
12085
  }
12073
12086
  };
12074
12087
 
12088
+ // src/store_lattice/InMemorySharedResourceStore.ts
12089
+ var DuplicateShareTokenError = class extends Error {
12090
+ /**
12091
+ * Creates a duplicate share token error.
12092
+ *
12093
+ * @param token - Token that is already present in the store.
12094
+ */
12095
+ constructor(token) {
12096
+ super(`Share token '${token}' already exists`);
12097
+ /** Machine-readable failure code. */
12098
+ this.code = "DUPLICATE_SHARE_TOKEN";
12099
+ this.name = "DuplicateShareTokenError";
12100
+ this.token = token;
12101
+ }
12102
+ };
12103
+ var MUTABLE_FIELDS = [
12104
+ "title",
12105
+ "expiresAt",
12106
+ "maxAccess",
12107
+ "revoked",
12108
+ "visibility",
12109
+ "passwordHash"
12110
+ ];
12111
+ function cloneShareRecord(record) {
12112
+ return structuredClone(record);
12113
+ }
12114
+ var InMemorySharedResourceStore = class {
12115
+ constructor() {
12116
+ this.records = /* @__PURE__ */ new Map();
12117
+ }
12118
+ /**
12119
+ * Finds a share by its token.
12120
+ *
12121
+ * @param token - Share token to look up.
12122
+ * @returns An independent copy of the record, or `null` when absent.
12123
+ */
12124
+ async findByToken(token) {
12125
+ const record = this.records.get(token);
12126
+ return record ? cloneShareRecord(record) : null;
12127
+ }
12128
+ /**
12129
+ * Inserts a new share record with `accessCount: 0`, `version: 1`, and the
12130
+ * current `createdAt`.
12131
+ *
12132
+ * @param record - Insert shape for the new share.
12133
+ * @returns An independent copy of the stored record.
12134
+ * @throws {DuplicateShareTokenError} When the token is already stored.
12135
+ */
12136
+ async create(record) {
12137
+ if (this.records.has(record.token)) {
12138
+ throw new DuplicateShareTokenError(record.token);
12139
+ }
12140
+ const stored = {
12141
+ ...record,
12142
+ accessCount: 0,
12143
+ createdAt: /* @__PURE__ */ new Date(),
12144
+ version: 1
12145
+ };
12146
+ this.records.set(stored.token, cloneShareRecord(stored));
12147
+ return cloneShareRecord(stored);
12148
+ }
12149
+ /**
12150
+ * Applies a patch to an existing share.
12151
+ *
12152
+ * Only `title`, `expiresAt`, `maxAccess`, `revoked`, `visibility`, and
12153
+ * `passwordHash` are applied; other keys (for example `token`, `kind`, or
12154
+ * `address`) are ignored. `undefined` values are treated as "no change".
12155
+ * Missing tokens are a no-op.
12156
+ *
12157
+ * @param token - Token of the share to update.
12158
+ * @param patch - Mutable fields to apply.
12159
+ */
12160
+ async update(token, patch) {
12161
+ const current = this.records.get(token);
12162
+ if (!current) return;
12163
+ const updates = {};
12164
+ for (const field of MUTABLE_FIELDS) {
12165
+ if (patch[field] !== void 0) {
12166
+ updates[field] = patch[field];
12167
+ }
12168
+ }
12169
+ if (Object.keys(updates).length === 0) return;
12170
+ const next = cloneShareRecord(current);
12171
+ Object.assign(next, updates);
12172
+ this.records.set(token, cloneShareRecord(next));
12173
+ }
12174
+ /**
12175
+ * Lists a user's shares within a tenant, newest first by `createdAt`.
12176
+ *
12177
+ * @param tenantId - Tenant to scope the listing to.
12178
+ * @param userId - Creator (`createdBy`) to scope the listing to.
12179
+ * @returns Independent copies of matching records.
12180
+ */
12181
+ async listByUser(tenantId2, userId) {
12182
+ return [...this.records.values()].map((record, insertionIndex) => ({ record, insertionIndex })).filter(
12183
+ ({ record }) => record.tenantId === tenantId2 && record.createdBy === userId
12184
+ ).sort(
12185
+ (left, right) => right.record.createdAt.getTime() - left.record.createdAt.getTime() || right.insertionIndex - left.insertionIndex
12186
+ ).map(({ record }) => cloneShareRecord(record));
12187
+ }
12188
+ /**
12189
+ * Increments `accessCount` unconditionally when the token exists.
12190
+ *
12191
+ * Use {@link atomicIncrementAccess} when revocation, expiry, and `maxAccess`
12192
+ * must be enforced.
12193
+ *
12194
+ * @param token - Token of the share to count.
12195
+ */
12196
+ async incrementAccess(token) {
12197
+ const current = this.records.get(token);
12198
+ if (current) current.accessCount += 1;
12199
+ }
12200
+ /**
12201
+ * Atomically increments `accessCount` only when the share is usable and the
12202
+ * access limit has not been reached.
12203
+ *
12204
+ * A share is considered expired when `expiresAt.getTime() <= Date.now()`,
12205
+ * matching PostgreSQL's `expires_at > NOW()` check.
12206
+ *
12207
+ * @param token - Token of the share to count.
12208
+ * @returns `true` when access was granted, `false` otherwise.
12209
+ */
12210
+ async atomicIncrementAccess(token) {
12211
+ const current = this.records.get(token);
12212
+ if (!current || current.revoked) return false;
12213
+ if (current.expiresAt && current.expiresAt.getTime() <= Date.now()) {
12214
+ return false;
12215
+ }
12216
+ if (current.maxAccess !== null && current.accessCount >= current.maxAccess) {
12217
+ return false;
12218
+ }
12219
+ current.accessCount += 1;
12220
+ return true;
12221
+ }
12222
+ };
12223
+
12075
12224
  // src/model_lattice/ModelLatticeManager.ts
12076
12225
  var TENANT_DEFAULT_MISS_TTL_MS = 3e4;
12077
12226
  var ModelLatticeManager = class _ModelLatticeManager extends BaseLatticeManager {
@@ -12620,11 +12769,11 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
12620
12769
  * @param key Lattice键名
12621
12770
  * @param tool 已有的StructuredTool实例
12622
12771
  */
12623
- registerExistingTool(key5, tool67) {
12772
+ registerExistingTool(key5, tool68) {
12624
12773
  const config = {
12625
- name: tool67.name,
12626
- description: tool67.description,
12627
- schema: tool67.schema,
12774
+ name: tool68.name,
12775
+ description: tool68.description,
12776
+ schema: tool68.schema,
12628
12777
  // StructuredTool的schema已经是Zod兼容的
12629
12778
  needUserApprove: false
12630
12779
  // MCP工具默认不需要用户批准
@@ -12632,7 +12781,7 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
12632
12781
  const toolLattice = {
12633
12782
  key: key5,
12634
12783
  config,
12635
- client: tool67
12784
+ client: tool68
12636
12785
  };
12637
12786
  this.register(key5, toolLattice);
12638
12787
  }
@@ -12643,14 +12792,14 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
12643
12792
  * @param key - tool lattice key (no tenant prefix)
12644
12793
  * @param tool - the StructuredTool client
12645
12794
  */
12646
- registerExistingToolWithTenant(tenantId2, key5, tool67) {
12795
+ registerExistingToolWithTenant(tenantId2, key5, tool68) {
12647
12796
  const config = {
12648
- name: tool67.name,
12649
- description: tool67.description,
12650
- schema: tool67.schema,
12797
+ name: tool68.name,
12798
+ description: tool68.description,
12799
+ schema: tool68.schema,
12651
12800
  needUserApprove: false
12652
12801
  };
12653
- const toolLattice = { key: key5, config, client: tool67 };
12802
+ const toolLattice = { key: key5, config, client: tool68 };
12654
12803
  this.registerWithTenant(tenantId2, key5, toolLattice);
12655
12804
  }
12656
12805
  /**
@@ -12700,8 +12849,8 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
12700
12849
  };
12701
12850
  var toolLatticeManager = ToolLatticeManager.getInstance();
12702
12851
  var registerToolLattice = (key5, config, executor) => toolLatticeManager.registerLattice(key5, config, executor);
12703
- var registerExistingTool = (key5, tool67) => toolLatticeManager.registerExistingTool(key5, tool67);
12704
- var registerExistingToolWithTenant = (tenantId2, key5, tool67) => toolLatticeManager.registerExistingToolWithTenant(tenantId2, key5, tool67);
12852
+ var registerExistingTool = (key5, tool68) => toolLatticeManager.registerExistingTool(key5, tool68);
12853
+ var registerExistingToolWithTenant = (tenantId2, key5, tool68) => toolLatticeManager.registerExistingToolWithTenant(tenantId2, key5, tool68);
12705
12854
  var getToolLattice = (key5) => toolLatticeManager.getToolLattice(key5);
12706
12855
  var getToolClientWithTenant = (tenantId2, key5) => toolLatticeManager.getToolClientWithTenant(tenantId2, key5);
12707
12856
  var getToolDefinition = (key5) => toolLatticeManager.getToolDefinition(key5);
@@ -15691,6 +15840,7 @@ var SANDBOX_OPEN_GATEWAY_URL_ENV = "API_GATEWAY_URL";
15691
15840
  var SANDBOX_OPEN_TOKEN_ENV = "OPEN_API_TOKEN";
15692
15841
  var provider;
15693
15842
  var providerErrorHandler;
15843
+ var gatewayUrlProvider;
15694
15844
  function registerSandboxOpenCredentialProvider(next, options = {}) {
15695
15845
  provider = next;
15696
15846
  providerErrorHandler = options.onError;
@@ -15713,6 +15863,15 @@ async function getSandboxOpenCredential(context) {
15713
15863
  return void 0;
15714
15864
  }
15715
15865
  }
15866
+ function registerSandboxOpenGatewayUrlProvider(next) {
15867
+ gatewayUrlProvider = next;
15868
+ return () => {
15869
+ if (gatewayUrlProvider === next) gatewayUrlProvider = void 0;
15870
+ };
15871
+ }
15872
+ function getSandboxOpenGatewayUrl() {
15873
+ return gatewayUrlProvider?.();
15874
+ }
15716
15875
  function buildSandboxOpenEnv(credential) {
15717
15876
  return `export ${SANDBOX_OPEN_GATEWAY_URL_ENV}=${shellSingleQuote(credential.gatewayUrl)} && export ${SANDBOX_OPEN_TOKEN_ENV}=${shellSingleQuote(credential.token)}`;
15718
15877
  }
@@ -15722,6 +15881,7 @@ function shellSingleQuote(value) {
15722
15881
  function clearSandboxOpenCredentialProviderForTests() {
15723
15882
  provider = void 0;
15724
15883
  providerErrorHandler = void 0;
15884
+ gatewayUrlProvider = void 0;
15725
15885
  }
15726
15886
 
15727
15887
  // src/tool_lattice/shell_exec/index.ts
@@ -20556,11 +20716,13 @@ function errorFromStdout(stdout) {
20556
20716
  return text.slice(0, 4096);
20557
20717
  }
20558
20718
  function buildResidentPayload(args, timeoutMs) {
20719
+ const gatewayUrl = getSandboxOpenGatewayUrl();
20559
20720
  return {
20560
20721
  handler: args.handler,
20561
20722
  input: args.input,
20562
20723
  ...args.connection === void 0 ? {} : { connection: args.connection },
20563
20724
  ...args.connections === void 0 ? {} : { connections: args.connections },
20725
+ ...gatewayUrl === void 0 ? {} : { apiGatewayUrl: gatewayUrl },
20564
20726
  context: args.context,
20565
20727
  timeoutMs
20566
20728
  };
@@ -20815,15 +20977,7 @@ var SandboxPluginExecutor = class {
20815
20977
  workspaceId: args.runConfig?.workspaceId,
20816
20978
  projectId: args.runConfig?.projectId
20817
20979
  });
20818
- const openCredential = tenantId2 ? await getSandboxOpenCredential({
20819
- tenantId: tenantId2,
20820
- workspaceId: args.runConfig?.workspaceId,
20821
- projectId: args.runConfig?.projectId,
20822
- sandboxName: sandbox.name,
20823
- assistantId: args.runConfig?.assistantId,
20824
- threadId: args.runConfig?.threadId,
20825
- depth: args.runConfig?.depth
20826
- }) : void 0;
20980
+ const gatewayUrl = getSandboxOpenGatewayUrl();
20827
20981
  const timeoutMs = clamp(args.timeoutMs ?? DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS, MAX_TIMEOUT_MS);
20828
20982
  const cap = clamp(
20829
20983
  args.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,
@@ -20854,13 +21008,12 @@ var SandboxPluginExecutor = class {
20854
21008
  envParts.push(`PLUGIN_CONNECTION_FILE=${quotePosixShellArg(connectionFile)}`);
20855
21009
  }
20856
21010
  envParts.push(`PLUGIN_CONTEXT=${quotePosixShellArg(encode(args.context))}`);
20857
- if (openCredential) {
21011
+ if (gatewayUrl) {
20858
21012
  envParts.push(
20859
- `${SANDBOX_OPEN_GATEWAY_URL_ENV}=${quotePosixShellArg(openCredential.gatewayUrl)}`
21013
+ `${SANDBOX_OPEN_GATEWAY_URL_ENV}=${quotePosixShellArg(gatewayUrl)}`
20860
21014
  );
20861
- envParts.push(`${SANDBOX_OPEN_TOKEN_ENV}=${quotePosixShellArg(openCredential.token)}`);
20862
21015
  }
20863
- const command = `${envParts.join(" ")} node ${quotePosixShellArg(handlerAbs)}`;
21016
+ const command = `unset OPEN_API_TOKEN; unset API_GATEWAY_URL; ${envParts.join(" ")} node ${quotePosixShellArg(handlerAbs)}`;
20864
21017
  const execResult = await sandbox.shell.execCommand({
20865
21018
  command,
20866
21019
  exec_dir: pluginDir,
@@ -21011,7 +21164,7 @@ function isSafeUiPath(path8) {
21011
21164
  }
21012
21165
  function validateSandboxPluginManifest(args) {
21013
21166
  const diagnostics = [];
21014
- const error = (code, message, pluginType, tool67) => diagnostics.push({ level: "error", code, message, pluginType, tool: tool67 });
21167
+ const error = (code, message, pluginType, tool68) => diagnostics.push({ level: "error", code, message, pluginType, tool: tool68 });
21015
21168
  const raw = args.raw;
21016
21169
  if (!isRecord7(raw)) {
21017
21170
  error("MANIFEST_NOT_OBJECT", "manifest must be a JSON object", args.dirName);
@@ -21314,14 +21467,20 @@ function sandboxRunConfigFrom(exeConfig) {
21314
21467
  // src/mcp_lattice/mcpUi.ts
21315
21468
  import { DynamicStructuredTool } from "@langchain/core/tools";
21316
21469
  var isObj = (v) => typeof v === "object" && v !== null;
21317
- function extractAppsRef(meta, serverKey) {
21470
+ function extractAppsRef(meta, serverKey, toolName2) {
21318
21471
  if (!isObj(meta)) return null;
21319
21472
  const ui = isObj(meta.ui) ? meta.ui : void 0;
21320
21473
  const nested = ui && typeof ui.resourceUri === "string" ? ui.resourceUri : "";
21321
21474
  const flat = typeof meta["ui/resourceUri"] === "string" ? meta["ui/resourceUri"] : "";
21322
21475
  const uri = nested || flat;
21323
21476
  if (!uri.startsWith("ui://")) return null;
21324
- return { kind: "mcp", serverKey, resourceUri: uri, displayMode: "inline" };
21477
+ return {
21478
+ kind: "mcp",
21479
+ serverKey,
21480
+ resourceUri: uri,
21481
+ displayMode: "inline",
21482
+ ...toolName2 ? { toolName: toolName2 } : {}
21483
+ };
21325
21484
  }
21326
21485
  function extractLegacyRefs(content, serverKey) {
21327
21486
  const blocks = Array.isArray(content) ? content : [];
@@ -21601,6 +21760,7 @@ function compileSandboxPlugin(args) {
21601
21760
  pluginType: manifest.type,
21602
21761
  resource: ui.resource,
21603
21762
  displayMode: ui.displayMode ?? "inline",
21763
+ toolName: t.name,
21604
21764
  ...scope ? { scope } : {}
21605
21765
  } : null;
21606
21766
  return ref ? appendUiFence(text, ref) : text;
@@ -22373,9 +22533,9 @@ function freezeMetadata(metadata) {
22373
22533
  ...resourceSelector ? { resourceSelector } : {}
22374
22534
  });
22375
22535
  }
22376
- function toolName(tool67) {
22377
- if (typeof tool67 !== "object" || tool67 === null || !("name" in tool67)) return void 0;
22378
- return typeof tool67.name === "string" ? tool67.name : void 0;
22536
+ function toolName(tool68) {
22537
+ if (typeof tool68 !== "object" || tool68 === null || !("name" in tool68)) return void 0;
22538
+ return typeof tool68.name === "string" ? tool68.name : void 0;
22379
22539
  }
22380
22540
  function schemaHasConnectionKey(schema6) {
22381
22541
  const definition = isRecord10(schema6._def) ? schema6._def : void 0;
@@ -22383,10 +22543,10 @@ function schemaHasConnectionKey(schema6) {
22383
22543
  const fields = typeof shape === "function" ? shape() : shape;
22384
22544
  return isRecord10(fields) && Object.prototype.hasOwnProperty.call(fields, "connectionKey");
22385
22545
  }
22386
- function hasConnectionKeySchema(tool67) {
22387
- if (!isRecord10(tool67) || !isRecord10(tool67.schema)) return false;
22388
- if (schemaHasConnectionKey(tool67.schema)) return true;
22389
- const definition = isRecord10(tool67.schema._def) ? tool67.schema._def : void 0;
22546
+ function hasConnectionKeySchema(tool68) {
22547
+ if (!isRecord10(tool68) || !isRecord10(tool68.schema)) return false;
22548
+ if (schemaHasConnectionKey(tool68.schema)) return true;
22549
+ const definition = isRecord10(tool68.schema._def) ? tool68.schema._def : void 0;
22390
22550
  if (Array.isArray(definition?.options) && definition.options.length > 0) {
22391
22551
  return definition.options.every(
22392
22552
  (option) => isRecord10(option) && schemaHasConnectionKey(option)
@@ -22441,8 +22601,8 @@ var CapabilityToolRegistry = class {
22441
22601
  * @remarks Standard connection authorization is captured only for tools whose
22442
22602
  * schema declares `connectionKey`; legacy selectors remain explicit metadata.
22443
22603
  */
22444
- register(name, metadata, tool67) {
22445
- this.registerInternal(name, metadata, hasConnectionKeySchema(tool67));
22604
+ register(name, metadata, tool68) {
22605
+ this.registerInternal(name, metadata, hasConnectionKeySchema(tool68));
22446
22606
  }
22447
22607
  /**
22448
22608
  * Registers all tools actually exposed by a middleware instance.
@@ -22453,13 +22613,13 @@ var CapabilityToolRegistry = class {
22453
22613
  * @returns Nothing.
22454
22614
  */
22455
22615
  registerMiddleware(capabilityType, middleware, resourceSelectors = {}) {
22456
- for (const tool67 of middleware.tools ?? []) {
22457
- const name = toolName(tool67);
22616
+ for (const tool68 of middleware.tools ?? []) {
22617
+ const name = toolName(tool68);
22458
22618
  if (name) {
22459
22619
  this.registerInternal(name, {
22460
22620
  capabilityType,
22461
22621
  resourceSelector: resourceSelectors[name]
22462
- }, hasConnectionKeySchema(tool67));
22622
+ }, hasConnectionKeySchema(tool68));
22463
22623
  }
22464
22624
  }
22465
22625
  }
@@ -23142,9 +23302,9 @@ var ReActAgentGraphBuilder = class {
23142
23302
  */
23143
23303
  async build(agentLattice, params) {
23144
23304
  const tools = params.tools.map((t) => {
23145
- const tool67 = getToolClientWithTenant(params.tenantId ?? "default", t.key);
23146
- return tool67;
23147
- }).filter((tool67) => tool67 !== void 0);
23305
+ const tool68 = getToolClientWithTenant(params.tenantId ?? "default", t.key);
23306
+ return tool68;
23307
+ }).filter((tool68) => tool68 !== void 0);
23148
23308
  const stateSchema2 = createReactAgentSchema(params.stateSchema);
23149
23309
  const middlewareConfigs = params.middleware || [];
23150
23310
  const filesystemBackend = createFilesystemBackendFactory(middlewareConfigs);
@@ -25225,8 +25385,8 @@ function validateCapability(value, index) {
25225
25385
  fieldPath: `/capabilities/${index}/allowedTools`
25226
25386
  });
25227
25387
  }
25228
- for (const [toolIndex, tool67] of capability.allowedTools.entries()) {
25229
- if (typeof tool67 !== "string") {
25388
+ for (const [toolIndex, tool68] of capability.allowedTools.entries()) {
25389
+ if (typeof tool68 !== "string") {
25230
25390
  throw new CapabilityBundleValidationError(
25231
25391
  "CAPABILITY_BUNDLE_INVALID_CAPABILITY",
25232
25392
  "allowedTools entries must be strings",
@@ -25240,10 +25400,10 @@ function validateCapability(value, index) {
25240
25400
  fieldPath: `/capabilities/${index}/allowedTools`
25241
25401
  });
25242
25402
  }
25243
- const toolNames = new Set(plugin.meta.tools.map((tool67) => tool67.name));
25244
- for (const [toolIndex, tool67] of capability.allowedTools.entries()) {
25245
- if (typeof tool67 !== "string" || !toolNames.has(tool67)) {
25246
- throw new CapabilityBundleValidationError("CAPABILITY_BUNDLE_UNKNOWN_TOOL", `Unknown tool '${String(tool67)}'`, {
25403
+ const toolNames = new Set(plugin.meta.tools.map((tool68) => tool68.name));
25404
+ for (const [toolIndex, tool68] of capability.allowedTools.entries()) {
25405
+ if (typeof tool68 !== "string" || !toolNames.has(tool68)) {
25406
+ throw new CapabilityBundleValidationError("CAPABILITY_BUNDLE_UNKNOWN_TOOL", `Unknown tool '${String(tool68)}'`, {
25247
25407
  capabilityType,
25248
25408
  fieldPath: `/capabilities/${index}/allowedTools/${toolIndex}`
25249
25409
  });
@@ -25726,7 +25886,7 @@ function applyStaticCeiling(capabilities, staticMiddleware) {
25726
25886
  const projectTools = capability.allowedTools;
25727
25887
  const staticTools = ceiling.allowedTools;
25728
25888
  const effectiveStaticTools = staticTools?.length === 0 ? void 0 : staticTools;
25729
- const allowedTools = projectTools === void 0 ? effectiveStaticTools : effectiveStaticTools === void 0 ? projectTools : projectTools.filter((tool67) => effectiveStaticTools.includes(tool67));
25889
+ const allowedTools = projectTools === void 0 ? effectiveStaticTools : effectiveStaticTools === void 0 ? projectTools : projectTools.filter((tool68) => effectiveStaticTools.includes(tool68));
25730
25890
  runtime[capability.type] = structuredClone({
25731
25891
  ...capability,
25732
25892
  config: applyStaticResourceCeiling(capability, ceiling),
@@ -32323,7 +32483,7 @@ var DeepAgentGraphBuilder = class {
32323
32483
  const tools = params.tools.map((t) => {
32324
32484
  const toolClient = getToolClientWithTenant(params.tenantId ?? "default", t.key);
32325
32485
  return toolClient;
32326
- }).filter((tool67) => tool67 !== void 0);
32486
+ }).filter((tool68) => tool68 !== void 0);
32327
32487
  const subagents = await Promise.all(params.subAgents.map(async (sa) => {
32328
32488
  if (sa.client) {
32329
32489
  return {
@@ -33127,7 +33287,7 @@ function requireSkillDeclaration(skillLoaded) {
33127
33287
  return void 0;
33128
33288
  }
33129
33289
  async function validateAgentReferences(input, tenantId2) {
33130
- const availableTools = getAvailableTools(tenantId2).map((tool67) => tool67.key);
33290
+ const availableTools = getAvailableTools(tenantId2).map((tool68) => tool68.key);
33131
33291
  const availableMiddlewareTypes = await getAvailableMiddlewareTypes(tenantId2);
33132
33292
  const availableCustomMiddlewareKeys = CustomMiddlewareRegistry.list().filter(
33133
33293
  (key5) => CustomMiddlewareRegistry.get(key5) !== void 0
@@ -35700,11 +35860,11 @@ async function withTimeout(operation, ms, onTimeout) {
35700
35860
 
35701
35861
  // src/mcp_lattice/McpLatticeManager.ts
35702
35862
  var realClientFactory = ({ mcpServers }) => new MultiServerMCPClient({ mcpServers });
35703
- function extractRawCall(tool67) {
35704
- const rawCall = tool67._call;
35705
- if (typeof rawCall === "function") return rawCall.bind(tool67);
35863
+ function extractRawCall(tool68) {
35864
+ const rawCall = tool68._call;
35865
+ if (typeof rawCall === "function") return rawCall.bind(tool68);
35706
35866
  return async (...args) => {
35707
- const invoke = tool67.invoke.bind(tool67);
35867
+ const invoke = tool68.invoke.bind(tool68);
35708
35868
  return invoke(args[0], args[2]);
35709
35869
  };
35710
35870
  }
@@ -36252,16 +36412,16 @@ var McpLatticeManager = class _McpLatticeManager extends BaseLatticeManager {
36252
36412
  const metaByName = new Map(metaList.map((m) => [m.name, m.meta]));
36253
36413
  this.unregisterServerTools(tenantId2, serverKey);
36254
36414
  const keys = [];
36255
- for (const tool67 of tools) {
36256
- if (rt.selectedTools && !rt.selectedTools.includes(tool67.name)) continue;
36257
- const meta = metaByName.get(tool67.name);
36415
+ for (const tool68 of tools) {
36416
+ if (rt.selectedTools && !rt.selectedTools.includes(tool68.name)) continue;
36417
+ const meta = metaByName.get(tool68.name);
36258
36418
  const rawVisibility = meta?.ui?.visibility;
36259
36419
  const visibility = Array.isArray(rawVisibility) ? rawVisibility : typeof rawVisibility === "string" ? [rawVisibility] : void 0;
36260
36420
  if (visibility && !visibility.includes("model")) continue;
36261
- const ref = extractAppsRef(meta, serverKey);
36262
- const resilient = this.wrapToolForResilience(rt, tool67);
36421
+ const ref = extractAppsRef(meta, serverKey, tool68.name);
36422
+ const resilient = this.wrapToolForResilience(rt, tool68);
36263
36423
  const registered = ref ? wrapMcpToolWithUi(resilient, ref) : resilient;
36264
- const toolKey = _McpLatticeManager.buildToolKey(serverKey, tool67.name);
36424
+ const toolKey = _McpLatticeManager.buildToolKey(serverKey, tool68.name);
36265
36425
  try {
36266
36426
  toolLatticeManager.registerExistingToolWithTenant(tenantId2, toolKey, registered);
36267
36427
  keys.push(toolKey);
@@ -38643,6 +38803,7 @@ var TokenCache = class {
38643
38803
  import { randomBytes as randomBytes3 } from "crypto";
38644
38804
  import bcrypt from "bcryptjs";
38645
38805
  var TOKEN_BYTES = 24;
38806
+ var MAX_MCP_APP_PAYLOAD_BYTES = 256 * 1024;
38646
38807
  function generateToken() {
38647
38808
  return randomBytes3(TOKEN_BYTES).toString("base64url");
38648
38809
  }
@@ -38654,6 +38815,7 @@ function createSharePayload(tenantId2, workspaceId, projectId, userId, request)
38654
38815
  }
38655
38816
  }
38656
38817
  return {
38818
+ kind: "file",
38657
38819
  address: createResourceAddress({
38658
38820
  tenantId: tenantId2,
38659
38821
  workspaceId,
@@ -38675,6 +38837,46 @@ function createSharePayload(tenantId2, workspaceId, projectId, userId, request)
38675
38837
  revoked: false
38676
38838
  };
38677
38839
  }
38840
+ var SharePayloadError = class extends Error {
38841
+ /**
38842
+ * @param code - The stable failure code.
38843
+ */
38844
+ constructor(code) {
38845
+ super(code);
38846
+ this.code = code;
38847
+ this.name = "SharePayloadError";
38848
+ }
38849
+ };
38850
+ function createMcpAppSharePayload(input) {
38851
+ if (input.visibility === "internal") {
38852
+ throw new SharePayloadError("INTERNAL_NOT_SUPPORTED");
38853
+ }
38854
+ const app = { ...input.app, toolInput: input.app.toolInput ?? {} };
38855
+ if (typeof app.toolName !== "string" || app.toolName.trim() === "") {
38856
+ throw new SharePayloadError("TOOL_NAME_REQUIRED");
38857
+ }
38858
+ const size = Buffer.byteLength(JSON.stringify(app), "utf8");
38859
+ if (size > MAX_MCP_APP_PAYLOAD_BYTES) {
38860
+ throw new SharePayloadError("PAYLOAD_TOO_LARGE");
38861
+ }
38862
+ return {
38863
+ token: generateToken(),
38864
+ kind: "mcpApp",
38865
+ address: { kind: "mcpApp", app },
38866
+ title: input.title ?? app.title ?? app.toolName ?? "Shared app",
38867
+ createdBy: input.createdBy,
38868
+ tenantId: input.tenantId,
38869
+ workspaceId: input.workspaceId,
38870
+ projectId: input.projectId,
38871
+ assistantId: null,
38872
+ vmIsolation: "project",
38873
+ visibility: input.visibility,
38874
+ passwordHash: input.password ? bcrypt.hashSync(input.password, 10) : null,
38875
+ expiresAt: input.expiresAt ?? null,
38876
+ maxAccess: input.maxAccess ?? null,
38877
+ revoked: false
38878
+ };
38879
+ }
38678
38880
 
38679
38881
  // src/channel/connectAllChannels.ts
38680
38882
  async function connectAllChannels(getAdapter, options = {}) {
@@ -40862,6 +41064,42 @@ function snapshotCanonicalScoped(value, expected) {
40862
41064
  };
40863
41065
  }
40864
41066
 
41067
+ // src/services/ProjectRoomMessageNotifier.ts
41068
+ var ProjectRoomMessageNotifier = class {
41069
+ constructor() {
41070
+ this.listeners = /* @__PURE__ */ new Set();
41071
+ }
41072
+ /**
41073
+ * Registers a committed-message listener.
41074
+ *
41075
+ * @param listener Observer invoked for later commits.
41076
+ * @returns An idempotent unsubscribe callback.
41077
+ */
41078
+ subscribe(listener) {
41079
+ this.listeners.add(listener);
41080
+ return () => {
41081
+ this.listeners.delete(listener);
41082
+ };
41083
+ }
41084
+ /**
41085
+ * Delivers one committed message to every registered listener.
41086
+ *
41087
+ * @param message Canonical persisted room message.
41088
+ * @returns Nothing; each listener receives its own clone and failures are contained.
41089
+ */
41090
+ notify(message) {
41091
+ if (this.listeners.size === 0) return;
41092
+ for (const listener of [...this.listeners]) {
41093
+ try {
41094
+ const result = listener(structuredClone(message));
41095
+ if (result !== void 0) void Promise.resolve(result).catch(() => void 0);
41096
+ } catch {
41097
+ }
41098
+ }
41099
+ }
41100
+ };
41101
+ var projectRoomMessageNotifier = new ProjectRoomMessageNotifier();
41102
+
40865
41103
  // src/services/ProjectTaskOwnerPolicy.ts
40866
41104
  import { snapshotExactRecord as snapshotExactRecord6 } from "@axiom-lattice/protocols";
40867
41105
  var MEMBERSHIP_REQUIRED_KEYS = [
@@ -50931,7 +51169,8 @@ function createProjectRoomMiddleware() {
50931
51169
  try {
50932
51170
  const service3 = new RoomAgentMessageService({
50933
51171
  memberships: getStoreLattice("default", "projectBotMembership").store,
50934
- messages: getStoreLattice("default", "projectRoomMessage").store
51172
+ messages: getStoreLattice("default", "projectRoomMessage").store,
51173
+ onMessageCommitted: (message) => projectRoomMessageNotifier.notify(message)
50935
51174
  });
50936
51175
  await service3.post({
50937
51176
  tenantId: scope.tenantId,
@@ -51019,12 +51258,149 @@ import { createMiddleware as createMiddleware27, tool as tool65 } from "langchai
51019
51258
  import { z as z72 } from "zod";
51020
51259
  import { AgentType as AgentType10 } from "@axiom-lattice/protocols";
51021
51260
 
51261
+ // src/services/PluginUiToolRunner.ts
51262
+ var PluginNotFoundError = class extends Error {
51263
+ /**
51264
+ * @param pluginType - Plugin type that was not found or failed validation.
51265
+ */
51266
+ constructor(pluginType) {
51267
+ super(`plugin "${pluginType}" not found`);
51268
+ this.pluginType = pluginType;
51269
+ this.name = "PluginNotFoundError";
51270
+ }
51271
+ };
51272
+ var ToolNotFoundError = class extends Error {
51273
+ /**
51274
+ * @param toolName - Tool name that was not found.
51275
+ */
51276
+ constructor(toolName2) {
51277
+ super(`tool "${toolName2}" not found`);
51278
+ this.toolName = toolName2;
51279
+ this.name = "ToolNotFoundError";
51280
+ }
51281
+ };
51282
+ var ToolNotUiError = class extends Error {
51283
+ /**
51284
+ * @param toolName - Tool that has no `ui` resource.
51285
+ */
51286
+ constructor(toolName2) {
51287
+ super(`tool "${toolName2}" has no ui`);
51288
+ this.toolName = toolName2;
51289
+ this.name = "ToolNotUiError";
51290
+ }
51291
+ };
51292
+ var ScopeUnavailableError = class extends Error {
51293
+ /**
51294
+ * @param text - Redacted handler text produced before signing failed.
51295
+ */
51296
+ constructor(text) {
51297
+ super("MCP UI scope is unavailable");
51298
+ this.text = text;
51299
+ this.name = "ScopeUnavailableError";
51300
+ }
51301
+ };
51302
+ var PluginUiToolExecutionError = class extends Error {
51303
+ /**
51304
+ * @param detail - Handler error detail.
51305
+ * @param text - Redacted handler text produced by the failed invocation.
51306
+ */
51307
+ constructor(detail, text) {
51308
+ super(detail);
51309
+ this.detail = detail;
51310
+ this.text = text;
51311
+ this.name = "PluginUiToolExecutionError";
51312
+ }
51313
+ };
51314
+ async function runSandboxPluginUiTool(input) {
51315
+ const manifest = input.manifest ?? await input.catalog.getValidatedManifest(input.tenantId, input.pluginType);
51316
+ if (!manifest) throw new PluginNotFoundError(input.pluginType);
51317
+ const toolDef = manifest.tools?.find((tool68) => tool68.name === input.toolName);
51318
+ if (!toolDef) throw new ToolNotFoundError(input.toolName);
51319
+ if (!toolDef.ui?.resource) throw new ToolNotUiError(input.toolName);
51320
+ const executor = input.catalog.getExecutor();
51321
+ const result = await executor.invoke({
51322
+ manifest,
51323
+ handler: toolDef.handler,
51324
+ input: input.input,
51325
+ ...input.connection === void 0 ? {} : { connection: input.connection },
51326
+ ...input.connections === void 0 ? {} : { connections: input.connections },
51327
+ context: {
51328
+ tenantId: input.tenantId,
51329
+ pluginType: input.pluginType,
51330
+ tool: input.toolName
51331
+ },
51332
+ runConfig: input.runConfig
51333
+ });
51334
+ const redacted = input.redact ? input.redact(result) : result;
51335
+ const text = handlerResultText(redacted);
51336
+ if (!result.ok) {
51337
+ const detail = result.error ?? "sandbox plugin execution failed";
51338
+ throw new PluginUiToolExecutionError(
51339
+ input.redact ? input.redact(detail) : detail,
51340
+ text
51341
+ );
51342
+ }
51343
+ const scope = signMcpUiScope({
51344
+ tid: input.runConfig.tenantId || input.tenantId,
51345
+ thid: typeof input.runConfig.threadId === "string" ? input.runConfig.threadId : void 0,
51346
+ aid: typeof input.runConfig.assistantId === "string" ? input.runConfig.assistantId : void 0,
51347
+ wid: typeof input.runConfig.workspaceId === "string" ? input.runConfig.workspaceId : void 0,
51348
+ pid: typeof input.runConfig.projectId === "string" ? input.runConfig.projectId : void 0,
51349
+ plugin: input.pluginType,
51350
+ resource: toolDef.ui.resource,
51351
+ ck: input.connectionKey
51352
+ });
51353
+ if (!scope) throw new ScopeUnavailableError(text);
51354
+ return {
51355
+ text,
51356
+ toolResult: text,
51357
+ uiRef: {
51358
+ kind: "plugin",
51359
+ pluginType: input.pluginType,
51360
+ resource: toolDef.ui.resource,
51361
+ displayMode: toolDef.ui.displayMode ?? "inline",
51362
+ toolName: input.toolName,
51363
+ scope
51364
+ }
51365
+ };
51366
+ }
51367
+
51022
51368
  // src/connection/connectionSecretFields.ts
51023
51369
  function connectionSecretFields(plugin) {
51024
51370
  const fields = plugin?.connection?.fields ?? [];
51025
51371
  return fields.filter((field) => field.type === "password" || field.widget === "password").map((field) => field.key);
51026
51372
  }
51027
51373
 
51374
+ // src/services/connectionSecretRedaction.ts
51375
+ function collectSecretValues(connection, fields) {
51376
+ if (!connection) return [];
51377
+ const values = [];
51378
+ for (const field of fields) {
51379
+ const value = connection[field];
51380
+ if (typeof value === "string" && value.length > 0) values.push(value);
51381
+ }
51382
+ return values;
51383
+ }
51384
+ function redactString(value, secrets) {
51385
+ let out = value;
51386
+ for (const secret of secrets) out = out.split(secret).join("[redacted]");
51387
+ return out;
51388
+ }
51389
+ function redactSecretValues(payload, secrets) {
51390
+ if (secrets.length === 0) return payload;
51391
+ const walk = (node) => {
51392
+ if (typeof node === "string") return redactString(node, secrets);
51393
+ if (Array.isArray(node)) return node.map(walk);
51394
+ if (node !== null && typeof node === "object") {
51395
+ const out = {};
51396
+ for (const [key5, value] of Object.entries(node)) out[key5] = walk(value);
51397
+ return out;
51398
+ }
51399
+ return node;
51400
+ };
51401
+ return walk(payload);
51402
+ }
51403
+
51028
51404
  // src/middlewares/sandboxPluginsSkills.ts
51029
51405
  var PLUGIN_JSON_TEMPLATE = `{
51030
51406
  "schemaVersion": 1,
@@ -51574,6 +51950,12 @@ The official \`@modelcontextprotocol/ext-apps\` client SDK reports size
51574
51950
  automatically. Otherwise the panel stays at a default height and content taller
51575
51951
  than the host max scrolls; \`templates/ui.html\` already includes this helper.
51576
51952
 
51953
+ ## Sharing the UI as a link
51954
+ If the human explicitly asks to publish or share this UI, load
51955
+ \`app-share-publishing\` and use \`share_app\`. Public links delegate the selected
51956
+ connection and re-run the tool on every open; confirm visibility and warn about
51957
+ that delegation first.
51958
+
51577
51959
  ## Publishing the UI to external MCP clients
51578
51960
  If the tool also sets \`"expose": true\`, its UI is published to Axiom's Open/MCP
51579
51961
  surface as \`ui://<type>/<ui.resource>\`, gated by the API key's grants (item-level
@@ -51672,28 +52054,102 @@ MCP endpoint. Reach for this when a tool should orchestrate existing capabilitie
51672
52054
  (read the knowledge base, create a task, invoke an agent) instead of
51673
52055
  re-implementing them.
51674
52056
 
51675
- ## What the handler gets
51676
- When the gateway injects the credential, each handler process starts with:
51677
- - \`API_GATEWAY_URL\` \u2014 the gateway base URL.
51678
- - \`OPEN_API_TOKEN\` \u2014 a short-lived bearer **scoped to this tenant's plugin callers**.
52057
+ ## Two different keys \u2014 do not mix them
51679
52058
 
51680
- If the deployment does not inject them (no \`PUBLIC_GATEWAY_URL\`), the variables are
51681
- **absent** \u2014 detect that and degrade gracefully (report "platform tools
51682
- unavailable") rather than crashing.
52059
+ | Key | Where | Used for |
52060
+ |---|---|---|
52061
+ | External service key (e.g. \`boStoreKey\`) | connection config | calling your upstream service |
52062
+ | Platform key (e.g. \`platformApiKey\`) | connection config | calling \`/open/mcp\` |
52063
+
52064
+ Both are declared by **you** in \`connection.fields\`. The platform key is a normal
52065
+ password field; the framework does not inject or rename it. Use a password field
52066
+ so it is encrypted at rest, and never log or write the key from the handler.
52067
+
52068
+ ## Do not use \`OPEN_API_TOKEN\` / \`fromEnv()\` here
52069
+
52070
+ \`OpenMcpClient.fromEnv()\` reads \`API_GATEWAY_URL + OPEN_API_TOKEN\`. That pair is
52071
+ only for agent \`code_eval\`. A plugin handler must read the platform key from
52072
+ \`PLUGIN_CONNECTION_FILE\` and pass it explicitly:
52073
+
52074
+ \`\`\`js
52075
+ const client = new OpenMcpClient({
52076
+ url: process.env.API_GATEWAY_URL,
52077
+ token: conn.platformApiKey, // YOUR connection field
52078
+ });
52079
+ \`\`\`
52080
+
52081
+ \`OPEN_API_TOKEN\` is **not** injected for plugin handlers. If you find yourself
52082
+ calling \`fromEnv()\` in a plugin handler, stop and switch to the connection key.
52083
+
52084
+ ## Probe first (recommended)
52085
+
52086
+ The platform key belongs to a human. Before writing the real handler:
52087
+
52088
+ 1. Declare the platform-key password field in \`connection.fields\`.
52089
+ 2. Write a temporary \`handlers/probe.js\` that reads \`PLUGIN_CONNECTION_FILE\`,
52090
+ creates \`OpenMcpClient\` with the connection key, and prints
52091
+ \`listTools()\` (name, description, inputSchema) as JSON.
52092
+ 3. Ask the human to configure the connection + platform key (only a human can
52093
+ create the key). Use \`list_connections\` to check whether a connection exists.
52094
+ 4. Run \`manage_plugin test\` with the real \`connectionKey\`, e.g.
52095
+ \`{ "kind": "tool", "name": "probe", "input": {}, "connectionKey": "prod" }\`.
52096
+ 5. Read the returned tool list; use it to choose the downstream tool names and
52097
+ argument shapes.
52098
+ 6. Write the real handler. Delete the probe or keep it as a debug tool.
52099
+
52100
+ A ready-to-copy probe is in \`templates/probe-handler.js\`.
52101
+
52102
+ ### What the probe cannot show
52103
+
52104
+ \`listTools()\` shows the key's **tools**, not its full resource scope. The gateway
52105
+ enforces the key's tenant/project/selector on every call; the handler does **not**
52106
+ need to re-check them to call a tool.
52107
+
52108
+ Ask the human only when the plugin's behavior depends on which project/connection
52109
+ is used, or when a tool schema takes a \`connectionKey\` and multiple connections
52110
+ are possible. A key may intentionally point at another project/tenant \u2014 that is a
52111
+ feature, not an error. Do not guess a connection key.
52112
+
52113
+ ## Worked example
52114
+
52115
+
52116
+ ### 1. Declare the field in \`plugin.json\`
52117
+
52118
+ \`\`\`json
52119
+ {
52120
+ "connection": {
52121
+ "fields": [
52122
+ { "key": "baseUrl", "type": "string", "title": "Upstream URL" },
52123
+ { "key": "boStoreKey", "type": "password", "title": "Upstream password" },
52124
+ {
52125
+ "key": "platformApiKey",
52126
+ "type": "password",
52127
+ "widget": "password",
52128
+ "title": "Platform Open API Key"
52129
+ }
52130
+ ]
52131
+ }
52132
+ }
52133
+ \`\`\`
52134
+
52135
+ ### 2. Read it in the handler
51683
52136
 
51684
- ## Discover, then call
51685
- Never hardcode the tool list: the callable set is **reflected per tenant** and
51686
- changes as plugins are exposed. Call \`listTools()\` at runtime.
51687
52137
  \`\`\`js
52138
+ const fs = require("fs");
51688
52139
  const { OpenMcpClient } = require("@axiom-lattice/open-mcp-client");
51689
- // or require("/root/.agents/sdk/open-mcp-client/index.js") when provisioned there
51690
52140
 
51691
52141
  async function main() {
51692
52142
  const input = process.env.PLUGIN_INPUT_FILE
51693
- ? JSON.parse(require("fs").readFileSync(process.env.PLUGIN_INPUT_FILE, "utf8"))
52143
+ ? JSON.parse(fs.readFileSync(process.env.PLUGIN_INPUT_FILE, "utf8"))
51694
52144
  : JSON.parse(process.env.PLUGIN_INPUT || "{}");
52145
+ const conn = JSON.parse(
52146
+ fs.readFileSync(process.env.PLUGIN_CONNECTION_FILE, "utf8"),
52147
+ ).connection;
51695
52148
 
51696
- const client = OpenMcpClient.fromEnv(); // API_GATEWAY_URL + OPEN_API_TOKEN
52149
+ const client = new OpenMcpClient({
52150
+ url: process.env.API_GATEWAY_URL,
52151
+ token: conn.platformApiKey,
52152
+ });
51697
52153
  const tools = await client.listTools(); // exactly what this handler may call
51698
52154
  const kb = await client.callTool("kb_search", { collection: "docs", query: input.q });
51699
52155
 
@@ -51704,29 +52160,165 @@ main().catch((err) => {
51704
52160
  });
51705
52161
  \`\`\`
51706
52162
 
51707
- - Tool names are \`{domain}_{action}\` (e.g. \`kb_search\`, \`task_manage_task\`).
51708
- - Args follow the tool's \`inputSchema\`; \`listTools()\` returns name/description.
51709
- - Return the result through the normal handler envelope (\`{ ok: true, result }\`)
51710
- so it becomes this tool's output \u2014 see \`sandbox-plugins-handlers\`.
52163
+ ### 3. Ask a human to configure the connection
52164
+
52165
+ - Call \`list_connections { type }\`.
52166
+ - If the connection or key is missing, use \`ask_user_to_clarify\`: only a human can
52167
+ create the platform API key and fill the connection.
52168
+ - Never claim PTC works until a real \`connectionKey\` test passes.
52169
+
52170
+ ### 4. Test with a real connection
52171
+
52172
+ \`\`\`json
52173
+ {
52174
+ "type": "my-plugin",
52175
+ "target": {
52176
+ "kind": "tool",
52177
+ "name": "my_tool",
52178
+ "input": {},
52179
+ "connectionKey": "prod"
52180
+ }
52181
+ }
52182
+ \`\`\`
52183
+
52184
+ Use \`manage_plugin test\`. Test output redacts secret values; assert on functional
52185
+ output (e.g. the tool result), not on echoing the key.
52186
+
52187
+ ## Checklist
52188
+
52189
+ - [ ] \`connection.fields\` declares a password field for the platform key.
52190
+ - [ ] handler reads \`PLUGIN_CONNECTION_FILE.connection.<field>\`.
52191
+ - [ ] handler constructs \`OpenMcpClient\` with \`API_GATEWAY_URL\` + that field.
52192
+ - [ ] \`listTools()\` is called before \`callTool()\`.
52193
+ - [ ] the handler never logs or writes the platform key.
52194
+ - [ ] the key is least-privilege and does not grant the plugin's own domain.
52195
+ - [ ] a probe (if needed) was used to discover tool names and args.
52196
+ - [ ] resident handlers do not cache the client/key.
52197
+ - [ ] a human configured the connection + platform key.
52198
+ - [ ] \`manage_plugin test\` passed with a real \`connectionKey\`.
52199
+
52200
+ ## Discover, then call
52201
+
52202
+ Never hardcode the tool list: the callable set is the key's grants. Call
52203
+ \`listTools()\` at runtime. Tool names are \`{domain}_{action}\` (e.g. \`kb_search\`,
52204
+ \`task_manage_task\`); args follow the tool's \`inputSchema\`. Return the result
52205
+ through the normal handler envelope (\`{ ok: true, result }\`) \u2014 see
52206
+ \`sandbox-plugins-handlers\`.
52207
+
52208
+ ## Key design
52209
+
52210
+ - Grant only the domains/actions the handler actually calls.
52211
+ - Do **not** grant the plugin's own domain; that enables self-recursion.
52212
+ - Use \`selector.connections\` when the handler must be restricted to specific
52213
+ connections.
52214
+ - Use a separate key per plugin/connection so rotate/disable and audit stay
52215
+ attributable.
52216
+ - Put the key in the connection as a password field; never log or write it.
52217
+ - The key's project/tenant is the project/tenant the downstream tools operate in.
52218
+ It may intentionally differ from the plugin's project; confirm with the human
52219
+ only if the plugin's semantics depend on it.
51711
52220
 
51712
52221
  ## What the handler may call
51713
- The token carries the conservative sandbox defaults (\`sandbox_*\`, \`kb_search\`)
51714
- **plus the tenant's grantable Open catalog**: every exposed tenant/global plugin
51715
- tool and the tenant's agents. A call outside that set fails (tool-not-found or
51716
- \`GRANT_DENIED\`); retrying will not help.
52222
+
52223
+ The API key carries **only its own grants**. Unlike agent \`code_eval\`, a plugin
52224
+ key does not automatically get the sandbox/\`kb\` defaults; grant those explicitly
52225
+ on the key if the handler needs them. A call outside the key's grants fails
52226
+ (tool-not-found or \`GRANT_DENIED\`); retrying will not help. Give the plugin a
52227
+ least-privilege key.
52228
+
52229
+ Resource selection is not the handler's job: Open MCP tools are already bound to
52230
+ their resources. A key can pin connections via \`selector.connections\` in the key
52231
+ editor; the handler only passes tool arguments.
52232
+
52233
+ ## Multiple connections
52234
+
52235
+ - \`PLUGIN_CONNECTION_FILE\` contains \`connection\` (first selected) and
52236
+ \`connections\` (all selected).
52237
+ - If the tool schema has \`connectionKey\`, pick that entry:
52238
+ \`\`\`js
52239
+ const data = JSON.parse(fs.readFileSync(process.env.PLUGIN_CONNECTION_FILE, "utf8"));
52240
+ const conn = (data.connections ?? []).find((c) => c.key === input.connectionKey)?.config
52241
+ ?? data.connection;
52242
+ \`\`\`
52243
+ - Without a \`connectionKey\` input and with multiple connections, use
52244
+ \`connection\` (the first) or fail with a clear message; do not silently mix
52245
+ credentials.
52246
+ - Keep the platform key consistent across the connections the handler uses.
52247
+
52248
+ ## Resident deployment
52249
+
52250
+ Resident handlers run in a long-lived service, but each \`/invoke\` receives the
52251
+ current connection config and \`apiGatewayUrl\`. Do **not** cache
52252
+ \`OpenMcpClient\`, the key, or \`API_GATEWAY_URL\` at module scope; read
52253
+ \`PLUGIN_CONNECTION_FILE\` per invocation so rotate/disable and connection changes
52254
+ apply.
51717
52255
 
51718
52256
  ## Client availability
51719
- The zero-dependency \`@axiom-lattice/open-mcp-client\` must be present in the
51720
- sandbox: preinstalled in the image, at \`/root/.agents/sdk/open-mcp-client\`, or
51721
- installed in this run (\`npm install @axiom-lattice/open-mcp-client\`). The CLI is
51722
- also available: \`npx @axiom-lattice/open-mcp-client tools list --json\`.
52257
+
52258
+ The sandbox image provides \`@axiom-lattice/open-mcp-client\`; use the bare module.
52259
+
52260
+ ## Error handling
52261
+
52262
+ | Symptom | Meaning | Action |
52263
+ |---|---|---|
52264
+ | \`token is required\` / \`OpenMcpConfigError\` | connection has no platform key | ask the human to configure it |
52265
+ | \`OpenMcpAuthError\` / 401 | key disabled, rotated, or invalid | ask the human to rotate/configure |
52266
+ | tool-not-found | key has no such domain/action | do not retry; fix the key grant |
52267
+ | \`GRANT_DENIED\` | key lacks the action | do not retry; fix the key grant |
52268
+ | \`CONNECTION_NOT_ALLOWED\` / \`RESOURCE_DENIED\` | \`selector.connections\` mismatch | use an allowed connection or fix the key scope |
52269
+
52270
+ ## Migrating from \`OPEN_API_TOKEN\`
52271
+
52272
+ If the plugin previously called \`OpenMcpClient.fromEnv()\`:
52273
+
52274
+ 1. Add a password field to \`connection.fields\` (for example \`platformApiKey\`).
52275
+ 2. Read \`PLUGIN_CONNECTION_FILE.connection.platformApiKey\`.
52276
+ 3. Construct \`new OpenMcpClient({ url: process.env.API_GATEWAY_URL, token: ... })\`.
52277
+ 4. Ask the human to fill the connection key.
52278
+ 5. Re-test with \`manage_plugin test\` + \`connectionKey\`.
52279
+
52280
+ \`fromEnv()\` still works for agent \`code_eval\`, not for plugin handlers.
51723
52281
 
51724
52282
  ## Limits
51725
- - Nested sandbox orchestration is depth-limited (5); past the cap no token is
51726
- re-issued, so deep recursion fails fast.
52283
+
52284
+ - Plugin handlers do not mint tokens; they reuse the connection key. Agent
52285
+ \`code_eval\` keeps the depth-limited short token path.
51727
52286
  - Only call what \`listTools()\` returns, and handle a missing tool gracefully.
51728
52287
  `,
51729
- resources: {}
52288
+ resources: {
52289
+ "templates/probe-handler.js": {
52290
+ content: `const fs = require("fs");
52291
+ const { OpenMcpClient } = require("@axiom-lattice/open-mcp-client");
52292
+
52293
+ async function main() {
52294
+ const conn = JSON.parse(
52295
+ fs.readFileSync(process.env.PLUGIN_CONNECTION_FILE, "utf8"),
52296
+ ).connection;
52297
+ const client = new OpenMcpClient({
52298
+ url: process.env.API_GATEWAY_URL,
52299
+ token: conn.platformApiKey,
52300
+ timeoutMs: 5000,
52301
+ });
52302
+ const tools = await client.listTools();
52303
+ process.stdout.write(JSON.stringify({
52304
+ ok: true,
52305
+ result: tools.map((tool) => ({
52306
+ name: tool.name,
52307
+ description: tool.description,
52308
+ inputSchema: tool.inputSchema,
52309
+ })),
52310
+ }));
52311
+ }
52312
+
52313
+ main().catch((err) => {
52314
+ process.stdout.write(JSON.stringify({
52315
+ ok: false,
52316
+ error: String(err && err.message ? err.message : err),
52317
+ }));
52318
+ });
52319
+ `
52320
+ }
52321
+ }
51730
52322
  },
51731
52323
  "sandbox-plugins-handlers": {
51732
52324
  version: "1.0.0",
@@ -51972,8 +52564,17 @@ Follow the authoring skill's "Decide first" steps to confirm the goal
51972
52564
  (inputs/outputs). If the UI class applies, load "sandbox-plugins-ui" before
51973
52565
  authoring it. If the tool must be callable by external MCP clients via an API key,
51974
52566
  load "sandbox-plugins-expose" and follow it (\`expose: true\` + key grants).
51975
- If a tool must call the platform's own tools/agents from its handler, load
51976
- "sandbox-plugins-consume-open".
52567
+ If the human asks to publish or share the plugin's UI as a link, load
52568
+ "app-share-publishing" and follow it; never publish proactively. If a tool must
52569
+ call the platform's own tools/agents from its handler, load
52570
+ "sandbox-plugins-consume-open" and follow its checklist: declare a password field
52571
+ in connection.fields, read it from PLUGIN_CONNECTION_FILE, construct OpenMcpClient
52572
+ with API_GATEWAY_URL + that field, and never use
52573
+ OPEN_API_TOKEN/OpenMcpClient.fromEnv() in a plugin handler. A human must
52574
+ configure the connection before PTC can be verified. If the key's capabilities
52575
+ are unknown, author a probe handler first and run manage_plugin test with a real
52576
+ connectionKey; use the returned listTools names/inputSchema before writing the
52577
+ real handler.
51977
52578
 
51978
52579
  Design first, and iterate on it before you build \u2014 the design is a conversation, not
51979
52580
  a one-shot. Use the \`widget\` middleware to present it (a decision surface, not a showcase):
@@ -52219,15 +52820,6 @@ function tenantIdFrom(exeConfig) {
52219
52820
  const c = exeConfig;
52220
52821
  return c?.configurable?.runConfig?.tenantId ?? "default";
52221
52822
  }
52222
- function collectSecretValues(connection, fields) {
52223
- if (!connection) return [];
52224
- const values = [];
52225
- for (const field of fields) {
52226
- const value = connection[field];
52227
- if (typeof value === "string" && value.length > 0) values.push(value);
52228
- }
52229
- return values;
52230
- }
52231
52823
  function errorText(err) {
52232
52824
  return err instanceof Error ? err.message : String(err);
52233
52825
  }
@@ -52240,25 +52832,6 @@ function deploymentUnavailable(action) {
52240
52832
  function deploymentsResult(payload) {
52241
52833
  return appendUiFence(JSON.stringify(payload), SANDBOX_PLUGINS_UI_REF);
52242
52834
  }
52243
- function redactString(value, secrets) {
52244
- let out = value;
52245
- for (const secret of secrets) out = out.split(secret).join("[redacted]");
52246
- return out;
52247
- }
52248
- function redactSecretValues(payload, secrets) {
52249
- if (secrets.length === 0) return payload;
52250
- const walk = (node) => {
52251
- if (typeof node === "string") return redactString(node, secrets);
52252
- if (Array.isArray(node)) return node.map(walk);
52253
- if (node !== null && typeof node === "object") {
52254
- const out = {};
52255
- for (const [key5, value] of Object.entries(node)) out[key5] = walk(value);
52256
- return out;
52257
- }
52258
- return node;
52259
- };
52260
- return walk(payload);
52261
- }
52262
52835
  var managePluginSchema = z72.object({
52263
52836
  action: z72.enum([
52264
52837
  "list",
@@ -52327,6 +52900,14 @@ var sandboxPluginsPlugin = {
52327
52900
  enabled: true,
52328
52901
  config: {}
52329
52902
  },
52903
+ {
52904
+ id: "app-share",
52905
+ type: "app-share",
52906
+ name: "App Share",
52907
+ description: "Publish a plugin UI tool as a public/password share link",
52908
+ enabled: true,
52909
+ config: {}
52910
+ },
52330
52911
  {
52331
52912
  id: "skill",
52332
52913
  type: "skill",
@@ -52539,14 +53120,9 @@ var sandboxPluginsPlugin = {
52539
53120
  }
52540
53121
  }
52541
53122
  const executor = catalog2.getExecutor();
52542
- const manifestContent = await catalog2.readPluginFile(tenantId2, input.type, "plugin.json");
52543
- let parsedManifest;
52544
- try {
52545
- parsedManifest = JSON.parse(manifestContent);
52546
- } catch {
52547
- return JSON.stringify({ error: "plugin.json is not valid JSON" });
52548
- }
52549
- const toolDef = (parsedManifest.tools ?? []).find((t) => t.name === input.target?.name);
53123
+ const manifest = await catalog2.getValidatedManifest(tenantId2, input.type);
53124
+ if (!manifest) return `plugin "${input.type}" not found`;
53125
+ const toolDef = (manifest.tools ?? []).find((t) => t.name === input.target?.name);
52550
53126
  if (!toolDef) return `tool "${input.target.name ?? ""}" not found`;
52551
53127
  const runConfig = {
52552
53128
  ...sandboxRunConfigFrom(exeConfig),
@@ -52558,38 +53134,55 @@ var sandboxPluginsPlugin = {
52558
53134
  runConfig
52559
53135
  ) : {};
52560
53136
  const secrets = collectSecretValues(resolved.connection, connectionSecretFields(plugin));
53137
+ const ui = toolDef.ui;
53138
+ if (!ui?.resource) {
53139
+ try {
53140
+ const result = await executor.invoke({
53141
+ manifest,
53142
+ handler: toolDef.handler,
53143
+ input: input.target.input ?? null,
53144
+ connection: resolved.connection,
53145
+ connections: resolved.connections,
53146
+ context: { tenantId: tenantId2, pluginType: input.type, tool: toolDef.name },
53147
+ runConfig
53148
+ });
53149
+ return handlerResultText(redactSecretValues(result, secrets));
53150
+ } catch (err) {
53151
+ return JSON.stringify(redactSecretValues({ ok: false, error: errorText(err) }, secrets));
53152
+ }
53153
+ }
53154
+ const uiRefWithoutScope = {
53155
+ kind: "plugin",
53156
+ pluginType: input.type,
53157
+ resource: ui.resource,
53158
+ displayMode: ui.displayMode ?? "inline",
53159
+ toolName: toolDef.name
53160
+ };
52561
53161
  try {
52562
- const result = await executor.invoke({
52563
- manifest: parsedManifest,
52564
- handler: toolDef.handler,
53162
+ const run = await runSandboxPluginUiTool({
53163
+ tenantId: tenantId2,
53164
+ pluginType: input.type,
53165
+ toolName: toolDef.name,
52565
53166
  input: input.target.input ?? null,
53167
+ runConfig,
52566
53168
  connection: resolved.connection,
52567
53169
  connections: resolved.connections,
52568
- context: { tenantId: tenantId2, pluginType: input.type, tool: toolDef.name },
52569
- runConfig
53170
+ connectionKey: resolved.connections?.[0]?.key,
53171
+ catalog: catalog2,
53172
+ manifest,
53173
+ redact: (value) => redactSecretValues(value, secrets)
52570
53174
  });
52571
- const text = handlerResultText(redactSecretValues(result, secrets));
52572
- const ui = toolDef.ui;
52573
- if (!ui?.resource) return text;
52574
- const scope = result.ok && ui?.resource ? signMcpUiScope({
52575
- tid: runConfig.tenantId || tenantId2,
52576
- thid: runConfig.threadId,
52577
- aid: runConfig.assistantId,
52578
- wid: runConfig.workspaceId,
52579
- pid: runConfig.projectId,
52580
- plugin: input.type,
52581
- resource: ui.resource,
52582
- ck: resolved.connections?.[0]?.key
52583
- }) : void 0;
52584
- const uiRef = {
52585
- kind: "plugin",
52586
- pluginType: input.type,
52587
- resource: ui.resource,
52588
- displayMode: ui.displayMode ?? "inline",
52589
- ...scope ? { scope } : {}
52590
- };
52591
- return appendUiFence(text, uiRef);
53175
+ return appendUiFence(run.text, run.uiRef);
52592
53176
  } catch (err) {
53177
+ if (err instanceof ToolNotFoundError) {
53178
+ return `tool "${input.target.name ?? ""}" not found`;
53179
+ }
53180
+ if (err instanceof PluginUiToolExecutionError) {
53181
+ return appendUiFence(err.text ?? "", uiRefWithoutScope);
53182
+ }
53183
+ if (err instanceof ScopeUnavailableError) {
53184
+ return appendUiFence(err.text ?? "", uiRefWithoutScope);
53185
+ }
52593
53186
  return JSON.stringify(redactSecretValues({ ok: false, error: errorText(err) }, secrets));
52594
53187
  }
52595
53188
  }
@@ -52668,9 +53261,371 @@ var sandboxPluginsPlugin = {
52668
53261
  })
52669
53262
  };
52670
53263
 
52671
- // src/middlewares/longTermStoreMiddleware.ts
52672
- import { createMiddleware as createMiddleware28, tool as tool66 } from "langchain";
53264
+ // src/middlewares/appShareMiddleware.ts
53265
+ import { tool as tool66 } from "langchain";
52673
53266
  import { z as z73 } from "zod";
53267
+
53268
+ // src/middlewares/appShareUi.ts
53269
+ var SHARE_CARD_UI_RESOURCE = "ui://app-share/share-card";
53270
+ var SHARE_CARD_APP_HTML = `<!doctype html>
53271
+ <html lang="en">
53272
+ <head>
53273
+ <meta charset="utf-8" />
53274
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
53275
+ <title>Shared app</title>
53276
+ <style>
53277
+ :root { color-scheme: light dark; }
53278
+ body { margin: 0; padding: 12px 14px; font: 13px/1.45 Inter, -apple-system, "Segoe UI", sans-serif; }
53279
+ .title { font-weight: 600; font-size: 14px; }
53280
+ .tag { display: inline-block; margin-left: 8px; padding: 1px 7px; border-radius: 999px; font-size: 11px; background: #eef2ff; color: #4338ca; }
53281
+ .url { margin: 8px 0; padding: 7px 9px; border: 1px solid #e5e7eb; border-radius: 8px; font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; word-break: break-all; }
53282
+ .pwd { margin: 6px 0; color: #6b7280; font-size: 12px; }
53283
+ .actions { display: flex; gap: 8px; margin-top: 8px; }
53284
+ button { border: 1px solid #d1d5db; background: #fff; border-radius: 8px; padding: 5px 10px; font: inherit; cursor: pointer; }
53285
+ button.primary { background: #4f46e5; border-color: #4f46e5; color: #fff; }
53286
+ .warn { margin-top: 8px; color: #b45309; font-size: 11px; }
53287
+ </style>
53288
+ </head>
53289
+ <body>
53290
+ <div id="root"><p>Loading\u2026</p></div>
53291
+ <script>
53292
+ (function () {
53293
+ var root = document.getElementById("root");
53294
+ function post(message) { window.parent.postMessage(message, "*"); }
53295
+ function notify(method, params) { post({ jsonrpc: "2.0", method: method, params: params }); }
53296
+ var nextId = 1;
53297
+ function rpc(method, params) {
53298
+ var id = nextId++;
53299
+ return new Promise(function (resolve, reject) {
53300
+ function onMessage(event) {
53301
+ var data = event.data;
53302
+ if (!data || data.id !== id) return;
53303
+ window.removeEventListener("message", onMessage);
53304
+ if (data.error) reject(new Error((data.error && data.error.message) || "rpc error"));
53305
+ else resolve(data.result);
53306
+ }
53307
+ window.addEventListener("message", onMessage);
53308
+ post({ jsonrpc: "2.0", id: id, method: method, params: params });
53309
+ });
53310
+ }
53311
+ function sendSize() {
53312
+ notify("ui/notifications/size-changed", {
53313
+ width: Math.ceil(document.documentElement.scrollWidth || document.body.scrollWidth),
53314
+ height: Math.ceil(document.documentElement.scrollHeight || document.body.scrollHeight),
53315
+ });
53316
+ }
53317
+ var ZH = (navigator.language || "").toLowerCase().indexOf("zh") === 0;
53318
+ var COPY = ZH
53319
+ ? { copy: "\u590D\u5236", open: "\u6253\u5F00\u5E94\u7528", password: "\u53E3\u4EE4\uFF1A", unavailable: "\u5206\u4EAB\u6570\u636E\u4E0D\u53EF\u7528\u3002", failed: "\u521D\u59CB\u5316\u5931\u8D25\uFF1A" }
53320
+ : { copy: "Copy", open: "Open app", password: "Password: ", unavailable: "Share data unavailable.", failed: "Failed to initialize: " };
53321
+ function esc(v) {
53322
+ return String(v == null ? "" : v).replace(/[&<>"']/g, function (ch) {
53323
+ return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[ch];
53324
+ });
53325
+ }
53326
+ function readResult(params) {
53327
+ if (!params || typeof params !== "object") return null;
53328
+ if (params.structuredContent && typeof params.structuredContent === "object") return params.structuredContent;
53329
+ var content = params.content;
53330
+ var text = content && content[0] && typeof content[0].text === "string" ? content[0].text : "";
53331
+ if (!text) return null;
53332
+ try { return JSON.parse(text); } catch (err) { return null; }
53333
+ }
53334
+ function render(data) {
53335
+ if (!data) { root.innerHTML = "<p>" + COPY.unavailable + "</p>"; sendSize(); return; }
53336
+ var html = '<div class="title">' + esc(data.title || "Shared app") + "</div>";
53337
+ html += '<span class="tag">' + esc(data.visibility) + "</span>";
53338
+ html += '<div class="url">' + esc(data.url || data.path) + "</div>";
53339
+ if (data.password) html += '<div class="pwd">' + COPY.password + esc(data.password) + "</div>";
53340
+ html += '<div class="actions">';
53341
+ html += '<button id="copy">' + COPY.copy + "</button>";
53342
+ html += '<button class="primary" id="open">' + COPY.open + "</button>";
53343
+ html += "</div>";
53344
+ if (data.warnings && data.warnings.length) {
53345
+ html += '<div class="warn">' + esc(data.warnings.join(" ")) + "</div>";
53346
+ }
53347
+ root.innerHTML = html;
53348
+ document.getElementById("copy").onclick = function () {
53349
+ rpc("ui/copy-link", {
53350
+ title: data.title,
53351
+ url: data.url || data.path,
53352
+ password: data.password,
53353
+ passwordLabel: COPY.password
53354
+ }).catch(function () {});
53355
+ };
53356
+ document.getElementById("open").onclick = function () {
53357
+ rpc("ui/open-link", { url: data.url || data.path }).catch(function () {});
53358
+ };
53359
+ sendSize();
53360
+ }
53361
+ window.addEventListener("message", function (event) {
53362
+ var data = event.data;
53363
+ if (!data || typeof data !== "object" || typeof data.method !== "string") return;
53364
+ if (data.method === "ui/notifications/tool-result") render(readResult(data.params));
53365
+ });
53366
+ if (typeof ResizeObserver !== "undefined") new ResizeObserver(sendSize).observe(document.documentElement);
53367
+ else window.addEventListener("resize", sendSize);
53368
+ rpc("ui/initialize", {
53369
+ protocolVersion: "2025-06-18",
53370
+ capabilities: {},
53371
+ clientInfo: { name: "app-share-card", version: "1.0.0" },
53372
+ appCapabilities: { availableDisplayModes: ["inline"] },
53373
+ }).then(function () {
53374
+ notify("ui/notifications/initialized", {});
53375
+ sendSize();
53376
+ }).catch(function (err) {
53377
+ root.innerHTML = "<p>" + COPY.failed + esc((err && err.message) || err) + "</p>";
53378
+ sendSize();
53379
+ });
53380
+ })();
53381
+ </script>
53382
+ </body>
53383
+ </html>`;
53384
+
53385
+ // src/middlewares/appShareSkill.ts
53386
+ var APP_SHARE_PUBLISHING_SKILL = `---
53387
+ name: app-share-publishing
53388
+ description: Use when a user explicitly asks to publish or share a tenant plugin's MCP App UI as a public or password-protected link, or asks for a shareable app URL.
53389
+ ---
53390
+
53391
+ # Publishing a plugin UI as a share link
53392
+
53393
+ \`share_app\` publishes a UI-bearing tool from a tenant sandbox plugin. It does
53394
+ not publish agents, files, or MCP-server UIs.
53395
+
53396
+ ## Preconditions
53397
+ - The plugin is authored, and \`manage_plugin validate\` / \`reload\` / \`test\` passes.
53398
+ - The target tool declares \`ui.resource\`.
53399
+ - A connection is configured if the plugin needs one. Pass \`connectionKey\` when
53400
+ the plugin has multiple connections.
53401
+ - Publish only when the human explicitly asks. Never share proactively.
53402
+
53403
+ ## Ask before creating
53404
+ - visibility: \`public\` or \`password\` (required; there is no default).
53405
+ - password when visibility is \`password\`.
53406
+ - Optional: title, \`expiresInMinutes\`, \`maxAccess\`.
53407
+ - Confirm the initial \`input\`; it is stored and re-run on every open. Never put
53408
+ credentials or other secrets in \`input\`.
53409
+
53410
+ ## Call
53411
+ \`\`\`json
53412
+ {
53413
+ "pluginType": "<plugin type>",
53414
+ "toolName": "<UI-bearing tool>",
53415
+ "input": {},
53416
+ "connectionKey": "<selected connection, when needed>",
53417
+ "visibility": "public | password",
53418
+ "password": "<required for password>",
53419
+ "title": "<optional>",
53420
+ "expiresInMinutes": 1440,
53421
+ "maxAccess": 100
53422
+ }
53423
+ \`\`\`
53424
+
53425
+ The result contains the relative link (\`path\`), token, title, visibility,
53426
+ optional password, and warnings, plus an inline share card.
53427
+
53428
+ ## What the link does
53429
+ - Every open re-runs the saved tool with the saved input; results are not
53430
+ persisted. Tools with write side effects run on every open.
53431
+ - A public share delegates the selected plugin connection: anyone with the link
53432
+ can call any tool in that plugin through the gateway. Warn the human before
53433
+ creating it.
53434
+ - A password share requires the password cookie. Links can be listed and revoked
53435
+ on the Shares page.
53436
+
53437
+ ## Errors
53438
+ - \`TOOL_NOT_UI\` / \`TOOL_NOT_FOUND\`: choose a UI-bearing tool from the plugin.
53439
+ - \`CONNECTION_REQUIRED\`: ask the human to configure the plugin connection first.
53440
+ - \`CONNECTION_AMBIGUOUS\`: ask which \`connectionKey\` to use.
53441
+ - \`CONNECTION_NOT_FOUND\`: verify the requested connection key.
53442
+ - \`SCOPE_UNAVAILABLE\`: the deployment cannot sign MCP UI scopes.
53443
+ - \`PAYLOAD_TOO_LARGE\`: reduce the stored input.
53444
+ - \`USER_REQUIRED\`: invoke from an authenticated user context.
53445
+
53446
+ ## Do not
53447
+ - Do not use \`share_app\` for non-UI tools or file shares.
53448
+ - Do not claim the shared view is a frozen snapshot; it re-executes.
53449
+ - Do not include credentials or secrets in \`input\`.
53450
+ `;
53451
+
53452
+ // src/middlewares/appShareMiddleware.ts
53453
+ var SHARE_CARD_UI_REF = {
53454
+ kind: "plugin",
53455
+ pluginType: "app-share",
53456
+ resource: SHARE_CARD_UI_RESOURCE,
53457
+ displayMode: "inline",
53458
+ title: "Shared app"
53459
+ };
53460
+ function rawRunConfigFrom(exeConfig) {
53461
+ const config = exeConfig;
53462
+ return config?.configurable?.runConfig ?? {};
53463
+ }
53464
+ var shareAppSchema = z73.object({
53465
+ pluginType: z73.string().min(1),
53466
+ toolName: z73.string().min(1),
53467
+ input: z73.record(z73.unknown()).optional(),
53468
+ connectionKey: z73.string().min(1).optional(),
53469
+ title: z73.string().min(1).max(256).optional(),
53470
+ visibility: z73.enum(["public", "password"]),
53471
+ password: z73.string().min(1).max(1024).optional(),
53472
+ expiresInMinutes: z73.number().int().positive().max(525600).optional(),
53473
+ maxAccess: z73.number().int().positive().optional()
53474
+ });
53475
+ async function shareAppHandler(input, exeConfig) {
53476
+ const runConfig = { ...sandboxRunConfigFrom(exeConfig) };
53477
+ const rawRunConfig = rawRunConfigFrom(exeConfig);
53478
+ const tenantId2 = runConfig.tenantId;
53479
+ const createdBy = typeof rawRunConfig.user_id === "string" && rawRunConfig.user_id.length > 0 ? rawRunConfig.user_id : typeof rawRunConfig.userId === "string" && rawRunConfig.userId.length > 0 ? rawRunConfig.userId : "";
53480
+ if (!tenantId2 || !createdBy) return JSON.stringify({ error: "USER_REQUIRED" });
53481
+ if (input.visibility === "password" && !input.password) {
53482
+ return JSON.stringify({ error: "INVALID_REQUEST" });
53483
+ }
53484
+ if (input.visibility === "public" && input.password) {
53485
+ return JSON.stringify({ error: "INVALID_REQUEST" });
53486
+ }
53487
+ let store2;
53488
+ try {
53489
+ store2 = getStoreLattice("default", "sharedResource").store;
53490
+ } catch {
53491
+ return JSON.stringify({ error: "SHARE_STORE_UNAVAILABLE" });
53492
+ }
53493
+ const catalog2 = getSandboxPluginCatalog();
53494
+ const loaded = await catalog2.ensureLoaded(tenantId2);
53495
+ const plugin = loaded.plugins.find((p) => p.meta.type === input.pluginType);
53496
+ if (!plugin) return JSON.stringify({ error: "TOOL_NOT_FOUND" });
53497
+ const manifest = await catalog2.getValidatedManifest(tenantId2, input.pluginType);
53498
+ const toolDef = manifest?.tools?.find((t) => t.name === input.toolName);
53499
+ if (!toolDef) return JSON.stringify({ error: "TOOL_NOT_FOUND" });
53500
+ if (!toolDef.ui?.resource) return JSON.stringify({ error: "TOOL_NOT_UI" });
53501
+ const connections = await resolvePluginConnections(
53502
+ input.pluginType,
53503
+ input.connectionKey ? { connections: [input.connectionKey] } : { connectAll: true },
53504
+ { tenantId: tenantId2 }
53505
+ );
53506
+ if (input.connectionKey && connections.length === 0) {
53507
+ return JSON.stringify({ error: "CONNECTION_NOT_FOUND" });
53508
+ }
53509
+ if (!input.connectionKey && plugin.connection && connections.length === 0) {
53510
+ return JSON.stringify({ error: "CONNECTION_REQUIRED" });
53511
+ }
53512
+ if (!input.connectionKey && plugin.connection && connections.length > 1) {
53513
+ return JSON.stringify({
53514
+ error: "CONNECTION_AMBIGUOUS",
53515
+ keys: connections.map((c) => c.key)
53516
+ });
53517
+ }
53518
+ const connectionKey = input.connectionKey ?? connections[0]?.key;
53519
+ const scope = signMcpUiScope({
53520
+ tid: tenantId2,
53521
+ thid: runConfig.threadId,
53522
+ aid: runConfig.assistantId,
53523
+ wid: runConfig.workspaceId,
53524
+ pid: runConfig.projectId,
53525
+ plugin: input.pluginType,
53526
+ resource: toolDef.ui.resource,
53527
+ ck: connectionKey
53528
+ });
53529
+ if (!scope) return JSON.stringify({ error: "SCOPE_UNAVAILABLE" });
53530
+ let payload;
53531
+ try {
53532
+ payload = createMcpAppSharePayload({
53533
+ tenantId: tenantId2,
53534
+ createdBy,
53535
+ workspaceId: runConfig.workspaceId ?? "",
53536
+ projectId: runConfig.projectId ?? "",
53537
+ app: {
53538
+ kind: "plugin",
53539
+ pluginType: input.pluginType,
53540
+ resource: toolDef.ui.resource,
53541
+ scope,
53542
+ toolName: input.toolName,
53543
+ displayMode: toolDef.ui.displayMode ?? "inline",
53544
+ toolInput: input.input ?? {}
53545
+ },
53546
+ title: input.title,
53547
+ visibility: input.visibility,
53548
+ password: input.password,
53549
+ expiresAt: input.expiresInMinutes ? new Date(Date.now() + input.expiresInMinutes * 6e4) : void 0,
53550
+ maxAccess: input.maxAccess
53551
+ });
53552
+ } catch (error) {
53553
+ if (error instanceof SharePayloadError) {
53554
+ return JSON.stringify({ error: error.code });
53555
+ }
53556
+ throw error;
53557
+ }
53558
+ try {
53559
+ await store2.create(payload);
53560
+ } catch {
53561
+ return JSON.stringify({ error: "SHARE_CREATE_FAILED" });
53562
+ }
53563
+ console.info(JSON.stringify({
53564
+ event: "share.created",
53565
+ tenantId: tenantId2,
53566
+ userId: createdBy,
53567
+ kind: "mcpApp",
53568
+ appKind: "plugin",
53569
+ pluginType: input.pluginType,
53570
+ tool: input.toolName,
53571
+ visibility: input.visibility,
53572
+ tokenPrefix: payload.token.slice(0, 8)
53573
+ }));
53574
+ const path8 = `/s/${payload.token}`;
53575
+ const envBase = process.env.AXIOM_PUBLIC_BASE_URL?.replace(/\/$/, "");
53576
+ const result = {
53577
+ path: path8,
53578
+ ...envBase ? { url: `${envBase}${path8}` } : {},
53579
+ token: payload.token,
53580
+ title: payload.title ?? "Shared app",
53581
+ visibility: payload.visibility,
53582
+ ...input.visibility === "password" && input.password ? { password: input.password } : {},
53583
+ ...input.visibility === "public" ? { warnings: ["public share delegates the selected plugin connection"] } : {}
53584
+ };
53585
+ const resultText = JSON.stringify(result).replace(/`/g, "\\u0060");
53586
+ return appendUiFence(resultText, SHARE_CARD_UI_REF);
53587
+ }
53588
+ var appSharePlugin = {
53589
+ meta: {
53590
+ type: "app-share",
53591
+ name: "App Share",
53592
+ description: "Publish a sandbox plugin MCP App as a share link.",
53593
+ version: "1.0.0",
53594
+ tools: [{
53595
+ name: "share_app",
53596
+ description: "Publish a UI-bearing sandbox plugin tool as a share link. Only call when the user explicitly asks to publish or share an app. visibility is required (public or password). A public share delegates the selected plugin connection capability, so warn the user. The initial arguments are stored and the tool is re-run on every link open; the tool result is never persisted.",
53597
+ ui: { resource: SHARE_CARD_UI_RESOURCE, displayMode: "inline" }
53598
+ }],
53599
+ uiResources: {
53600
+ [SHARE_CARD_UI_RESOURCE]: { html: SHARE_CARD_APP_HTML }
53601
+ },
53602
+ configSchema: { type: "object", properties: {} },
53603
+ defaultConfig: {}
53604
+ },
53605
+ skills: {
53606
+ "app-share-publishing": {
53607
+ version: "1.0.0",
53608
+ content: APP_SHARE_PUBLISHING_SKILL
53609
+ }
53610
+ },
53611
+ middleware: () => ({
53612
+ name: "appShareMiddleware",
53613
+ tools: [
53614
+ tool66(
53615
+ async (input, exeConfig) => shareAppHandler(input, exeConfig),
53616
+ {
53617
+ name: "share_app",
53618
+ description: "Publish a UI-bearing sandbox plugin tool as a share link. Only call when the user explicitly asks to publish or share an app. visibility is required: ask the user whether the link should be public or password-protected. A public share delegates the selected plugin connection capability, so warn the user. The initial arguments are stored and the tool is re-run on every link open; the tool result is never persisted.",
53619
+ schema: shareAppSchema
53620
+ }
53621
+ )
53622
+ ]
53623
+ })
53624
+ };
53625
+
53626
+ // src/middlewares/longTermStoreMiddleware.ts
53627
+ import { createMiddleware as createMiddleware28, tool as tool67 } from "langchain";
53628
+ import { z as z74 } from "zod";
52674
53629
  import {
52675
53630
  STORE_IDENTITY_SEPARATOR as STORE_IDENTITY_SEPARATOR2,
52676
53631
  StoreValidationError
@@ -52769,34 +53724,34 @@ function store() {
52769
53724
  return void 0;
52770
53725
  }
52771
53726
  }
52772
- var namespaceSchema = z73.array(z73.string()).optional().describe(
53727
+ var namespaceSchema = z74.array(z74.string()).optional().describe(
52773
53728
  "Optional relative namespace segments for organization (appended to the scoped prefix)."
52774
53729
  );
52775
- var keySchema = z73.string().min(1).describe("Stable item key within the resolved namespace.");
52776
- var valueSchema = z73.record(z73.unknown()).describe("JSON object value to persist.");
52777
- var putSchema = z73.object({
53730
+ var keySchema = z74.string().min(1).describe("Stable item key within the resolved namespace.");
53731
+ var valueSchema = z74.record(z74.unknown()).describe("JSON object value to persist.");
53732
+ var putSchema = z74.object({
52778
53733
  key: keySchema,
52779
53734
  value: valueSchema,
52780
53735
  namespace: namespaceSchema,
52781
- ttlMinutes: z73.number().positive().optional().describe("Optional TTL in minutes; omit to use the plugin default.")
53736
+ ttlMinutes: z74.number().positive().optional().describe("Optional TTL in minutes; omit to use the plugin default.")
52782
53737
  });
52783
- var getSchema = z73.object({
53738
+ var getSchema = z74.object({
52784
53739
  key: keySchema,
52785
53740
  namespace: namespaceSchema
52786
53741
  });
52787
- var searchSchema2 = z73.object({
52788
- query: z73.string().optional().describe("Case-insensitive substring match over serialized values."),
52789
- filter: z73.record(z73.unknown()).optional().describe("Deep partial-equality filter over the value object."),
53742
+ var searchSchema2 = z74.object({
53743
+ query: z74.string().optional().describe("Case-insensitive substring match over serialized values."),
53744
+ filter: z74.record(z74.unknown()).optional().describe("Deep partial-equality filter over the value object."),
52790
53745
  namespace: namespaceSchema,
52791
- limit: z73.number().int().min(1).max(MAX_SEARCH_LIMIT).optional()
53746
+ limit: z74.number().int().min(1).max(MAX_SEARCH_LIMIT).optional()
52792
53747
  });
52793
- var deleteSchema = z73.object({
53748
+ var deleteSchema = z74.object({
52794
53749
  key: keySchema,
52795
53750
  namespace: namespaceSchema
52796
53751
  });
52797
- var namespacesSchema = z73.object({
53752
+ var namespacesSchema = z74.object({
52798
53753
  namespace: namespaceSchema,
52799
- limit: z73.number().int().min(1).max(MAX_SEARCH_LIMIT).optional()
53754
+ limit: z74.number().int().min(1).max(MAX_SEARCH_LIMIT).optional()
52800
53755
  });
52801
53756
  var STORE_SKILL_HINT = "Load long_term_store-usage for namespace/TTL guidance.";
52802
53757
  var STORE_DESCRIPTION = [
@@ -52915,7 +53870,7 @@ function createLongTermStoreMiddleware(config = {}) {
52915
53870
  }
52916
53871
  return resolveNamespace(config, scope, relative4);
52917
53872
  };
52918
- const putTool = tool66(
53873
+ const putTool = tool67(
52919
53874
  async (input, exeConfig) => {
52920
53875
  const resolved = resolve4(exeConfig, input.namespace);
52921
53876
  if (!resolved.namespace) return failure3(resolved.error ?? "Invalid namespace");
@@ -52946,7 +53901,7 @@ function createLongTermStoreMiddleware(config = {}) {
52946
53901
  schema: putSchema
52947
53902
  }
52948
53903
  );
52949
- const getTool = tool66(
53904
+ const getTool = tool67(
52950
53905
  async (input, exeConfig) => {
52951
53906
  const resolved = resolve4(exeConfig, input.namespace);
52952
53907
  if (!resolved.namespace) return failure3(resolved.error ?? "Invalid namespace");
@@ -52970,7 +53925,7 @@ function createLongTermStoreMiddleware(config = {}) {
52970
53925
  schema: getSchema
52971
53926
  }
52972
53927
  );
52973
- const searchTool = tool66(
53928
+ const searchTool = tool67(
52974
53929
  async (input, exeConfig) => {
52975
53930
  const resolved = resolve4(exeConfig, input.namespace);
52976
53931
  if (!resolved.namespace) return failure3(resolved.error ?? "Invalid namespace");
@@ -52997,7 +53952,7 @@ function createLongTermStoreMiddleware(config = {}) {
52997
53952
  schema: searchSchema2
52998
53953
  }
52999
53954
  );
53000
- const deleteTool = tool66(
53955
+ const deleteTool = tool67(
53001
53956
  async (input, exeConfig) => {
53002
53957
  const resolved = resolve4(exeConfig, input.namespace);
53003
53958
  if (!resolved.namespace) return failure3(resolved.error ?? "Invalid namespace");
@@ -53021,7 +53976,7 @@ function createLongTermStoreMiddleware(config = {}) {
53021
53976
  schema: deleteSchema
53022
53977
  }
53023
53978
  );
53024
- const namespacesTool = tool66(
53979
+ const namespacesTool = tool67(
53025
53980
  async (input, exeConfig) => {
53026
53981
  const resolved = resolve4(exeConfig, input.namespace);
53027
53982
  if (!resolved.namespace) return failure3(resolved.error ?? "Invalid namespace");
@@ -53141,6 +54096,7 @@ var BUILTIN_PLUGINS = [
53141
54096
  documentParserPlugin,
53142
54097
  projectRoomPlugin,
53143
54098
  sandboxPluginsPlugin,
54099
+ appSharePlugin,
53144
54100
  longTermStorePlugin
53145
54101
  ];
53146
54102
  function registerBuiltinPlugins() {
@@ -53575,8 +54531,11 @@ async function runHandler(body) {
53575
54531
  var needsTempDir = inputIsLarge || connectionPayload !== null;
53576
54532
  var tempDir = null;
53577
54533
  var env = Object.assign({}, process.env);
53578
- // Handler processes must never inherit scope signing secrets.
54534
+ // Handler processes must never inherit scope signing secrets or the
54535
+ // agent-only short-lived Open token.
53579
54536
  delete env.MCP_UI_SCOPE_SECRET;
54537
+ delete env.OPEN_API_TOKEN;
54538
+ delete env.API_GATEWAY_URL;
53580
54539
  try {
53581
54540
  if (needsTempDir) {
53582
54541
  tempDir = path.join(os.tmpdir(), "plugin-run-" + Date.now() + "-" + Math.random().toString(36).slice(2));
@@ -53595,6 +54554,9 @@ async function runHandler(body) {
53595
54554
  env.PLUGIN_CONNECTION_FILE = connectionFile;
53596
54555
  }
53597
54556
  env.PLUGIN_CONTEXT = encodeInput(body.context || {});
54557
+ if (typeof body.apiGatewayUrl === "string" && body.apiGatewayUrl) {
54558
+ env.API_GATEWAY_URL = body.apiGatewayUrl;
54559
+ }
53598
54560
  var handlerTimeoutMs = resolveHandlerTimeoutMs(body.timeoutMs);
53599
54561
  var exec = await runNode(handlerPath, pluginDir, env, handlerTimeoutMs);
53600
54562
  if (exec.error) {
@@ -54145,6 +55107,7 @@ export {
54145
55107
  DelegationService,
54146
55108
  DependencyResolver,
54147
55109
  DuplicateProjectRoomMessageIdempotencyKeyError,
55110
+ DuplicateShareTokenError,
54148
55111
  E2BInstance,
54149
55112
  E2BProvider,
54150
55113
  EMPTY_CONTENT_WARNING,
@@ -54180,6 +55143,7 @@ export {
54180
55143
  InMemoryProjectRoomMessageStore,
54181
55144
  InMemoryProjectRoomReadStateStore,
54182
55145
  InMemoryProjectRoomStore,
55146
+ InMemorySharedResourceStore,
54183
55147
  InMemoryStore,
54184
55148
  InMemoryTaskStore,
54185
55149
  InMemoryTaskWorkItemStore,
@@ -54236,6 +55200,7 @@ export {
54236
55200
  ProjectBotMembershipIdConflictError,
54237
55201
  ProjectMutationMutex,
54238
55202
  ProjectRoomMessageIdConflictError,
55203
+ ProjectRoomMessageNotifier,
54239
55204
  ProjectTaskAdmissionNotifier,
54240
55205
  ProjectTaskOwnerPolicy,
54241
55206
  ProjectTaskOwnerPolicyError,
@@ -54252,6 +55217,8 @@ export {
54252
55217
  SAFE_PATH_COMPONENT,
54253
55218
  SANDBOX_OPEN_GATEWAY_URL_ENV,
54254
55219
  SANDBOX_OPEN_TOKEN_ENV,
55220
+ SHARE_CARD_APP_HTML,
55221
+ SHARE_CARD_UI_RESOURCE,
54255
55222
  STTModelLattice,
54256
55223
  STTModelLatticeManager,
54257
55224
  SUMMARIZATION_TRIGGER_RATIO,
@@ -54261,6 +55228,7 @@ export {
54261
55228
  SandboxSkillStore,
54262
55229
  ScheduleLatticeManager,
54263
55230
  SemanticMetricsClient,
55231
+ SharePayloadError,
54264
55232
  SharedChunkBuffer,
54265
55233
  SimpleMemoryVectorStore,
54266
55234
  SkillLatticeManager,
@@ -54292,6 +55260,7 @@ export {
54292
55260
  abortWorkflowRun,
54293
55261
  agentInstanceManager,
54294
55262
  agentLatticeManager,
55263
+ appSharePlugin,
54295
55264
  appendReconciliationWarning,
54296
55265
  appendUiFence,
54297
55266
  assertQueueSources,
@@ -54344,6 +55313,7 @@ export {
54344
55313
  createListTablesSqlTool,
54345
55314
  createLongTermStoreMiddleware,
54346
55315
  createMapNode,
55316
+ createMcpAppSharePayload,
54347
55317
  createModelSelectorMiddleware,
54348
55318
  createNodeHandler,
54349
55319
  createProjectRoomMiddleware,
@@ -54437,6 +55407,7 @@ export {
54437
55407
  getSTTModelLattice,
54438
55408
  getSandBoxManager,
54439
55409
  getSandboxOpenCredential,
55410
+ getSandboxOpenGatewayUrl,
54440
55411
  getSandboxPluginCatalog,
54441
55412
  getScheduleLattice,
54442
55413
  getStoreLattice,
@@ -54510,6 +55481,7 @@ export {
54510
55481
  prepareTaskDispatch,
54511
55482
  probeThreadRunOwner,
54512
55483
  projectMutationMutex,
55484
+ projectRoomMessageNotifier,
54513
55485
  projectRoomPlugin,
54514
55486
  projectTaskAdmissionNotifier,
54515
55487
  provisionSandboxOpenClient,
@@ -54536,6 +55508,7 @@ export {
54536
55508
  registerQueueLattice,
54537
55509
  registerSTTModelLattice,
54538
55510
  registerSandboxOpenCredentialProvider,
55511
+ registerSandboxOpenGatewayUrlProvider,
54539
55512
  registerSandboxProviderType,
54540
55513
  registerScheduleLattice,
54541
55514
  registerStoreLattice,
@@ -54580,6 +55553,7 @@ export {
54580
55553
  setPluginDeploymentService,
54581
55554
  setRunCancelHeartbeatFallbackObserver,
54582
55555
  setSandboxPluginCatalog,
55556
+ shareAppSchema,
54583
55557
  signMcpUiScope,
54584
55558
  skillLatticeManager,
54585
55559
  sqlDatabaseManager,