@xpert-ai/plugin-sdk 3.18.3 → 3.18.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +26 -1
  3. package/index.cjs.js +249 -27
  4. package/index.esm.js +244 -30
  5. package/model-provider.cjs.js +8 -0
  6. package/model-provider.esm.js +7 -1
  7. package/package.json +2 -2
  8. package/runtime-capabilities.md +49 -0
  9. package/src/lib/agent/middleware/capabilities/assistant-task.d.ts +3 -0
  10. package/src/lib/agent/middleware/runtime.d.ts +2 -14
  11. package/src/lib/ai-model/types/rerank.d.ts +2 -0
  12. package/src/lib/ai-model/utils/tokenizer.d.ts +6 -0
  13. package/src/lib/connector/runtime-capability.d.ts +19 -0
  14. package/src/lib/evolution/runtime-capability.d.ts +2 -1
  15. package/src/lib/mcp/resource-template.d.ts +2 -3
  16. package/src/lib/mcp/resource.d.ts +5 -1
  17. package/src/lib/rag/textsplitter/strategy.interface.d.ts +15 -4
  18. package/src/lib/rag/transformer/strategy.interface.d.ts +3 -0
  19. package/src/lib/runtime/capabilities/actor-token.d.ts +12 -0
  20. package/src/lib/runtime/capabilities/artifacts.d.ts +2 -0
  21. package/src/lib/runtime/capabilities/knowledge-document-visual-assets.d.ts +16 -5
  22. package/src/lib/runtime/capabilities/knowledgebase-documents.d.ts +50 -1
  23. package/src/lib/runtime/capabilities/knowledgebase.d.ts +1 -0
  24. package/src/lib/runtime/capabilities/workspace-files.d.ts +2 -0
  25. package/src/lib/runtime/index.d.ts +1 -0
  26. package/src/lib/runtime/runtime-scope.d.ts +14 -0
  27. package/src/lib/tool-provider/index.d.ts +2 -0
  28. package/src/lib/tool-provider/prepared-result.d.ts +18 -0
  29. package/src/lib/tool-provider/tool-result.d.ts +16 -0
  30. package/src/lib/tool-provider/types.d.ts +8 -2
  31. package/src/lib/toolset/define-tool.d.ts +2 -1
  32. package/src/lib/types.d.ts +12 -1
package/index.esm.js CHANGED
@@ -4,7 +4,7 @@ import { pick } from 'lodash-es';
4
4
  import { _ as _extends } from './_extends.esm.js';
5
5
  import { DiscoveryService, Reflector } from '@nestjs/core';
6
6
  import { Subject, filter } from 'rxjs';
7
- import { LanguagesEnum, ParameterType, AiModelTypeEnum, PriceType, FetchFrom, ModelFeature, ModelPropertyKey, MCP_TOOL_RISKS, MCP_TOOL_SIDE_EFFECTS, MCP_TOOL_IDEMPOTENCY, MCP_REQUIRED_CONTEXTS, MCP_CAPABILITY_VISIBILITIES } from '@xpert-ai/contracts';
7
+ import { LanguagesEnum, ParameterType, AiModelTypeEnum, PriceType, FetchFrom, ModelFeature, ModelPropertyKey, MCP_CAPABILITY_APPROVAL_MODES, MCP_TOOL_RISKS, MCP_TOOL_SIDE_EFFECTS, MCP_TOOL_IDEMPOTENCY, MCP_REQUIRED_CONTEXTS, MCP_CAPABILITY_VISIBILITIES } from '@xpert-ai/contracts';
8
8
  export { ASSISTANT_CHAT_SEND_MESSAGE_COMMAND, ASSISTANT_CONTEXT_SET_COMMAND } from '@xpert-ai/contracts';
9
9
  import { AsyncLocalStorage } from 'node:async_hooks';
10
10
  import { ExtractJwt } from 'passport-jwt';
@@ -16,7 +16,7 @@ import fs__default from 'fs';
16
16
  import http from 'http';
17
17
  import https from 'https';
18
18
  import { c as createRuntimeCapability, B as BuiltinToolset } from './model-provider.esm.js';
19
- export { A as ActorTokenRuntimeCapability, a as ArtifactsRuntimeCapability, b as BaseTool, d as BaseToolset, D as DefaultAgentMiddlewareRuntimeCapabilityRegistry, D as DefaultRuntimeCapabilityRegistry, K as KnowledgeDocumentVisualAssetsRuntimeCapability, e as KnowledgebaseDocumentsRuntimeCapability, f as KnowledgebaseProvisioningRuntimeCapability, g as KnowledgebaseRuntimeCapability, M as ModelProviderBuiltinToolset, P as ProjectAccessRuntimeCapability, h as ProjectProvisioningRuntimeCapability, S as SANDBOX_JOB_ERROR_CODES, i as SANDBOX_JOB_PROGRESS_PREFIX, j as SandboxJobRuntimeError, k as SandboxJobsRuntimeCapability, W as WORKSPACE_FILES_SOURCE, l as WorkspaceFilesRuntimeCapability, X as XPERT_RUNTIME_CAPABILITIES_TOKEN, m as isSandboxJobRuntimeError } from './model-provider.esm.js';
19
+ export { A as ActorTokenRuntimeCapability, a as ActorTokenRuntimeFactoryCapability, b as ArtifactsRuntimeCapability, d as BaseTool, e as BaseToolset, D as DefaultAgentMiddlewareRuntimeCapabilityRegistry, D as DefaultRuntimeCapabilityRegistry, K as KnowledgeDocumentVisualAssetsRuntimeCapability, f as KnowledgeDocumentVisualAssetsRuntimeFactoryCapability, g as KnowledgebaseDocumentsRuntimeCapability, h as KnowledgebaseProvisioningRuntimeCapability, i as KnowledgebaseRuntimeCapability, M as ModelProviderBuiltinToolset, P as ProjectAccessRuntimeCapability, j as ProjectProvisioningRuntimeCapability, S as SANDBOX_JOB_ERROR_CODES, k as SANDBOX_JOB_PROGRESS_PREFIX, l as SandboxJobRuntimeError, m as SandboxJobsRuntimeCapability, W as WORKSPACE_FILES_SOURCE, n as WorkspaceFilesRuntimeCapability, X as XPERT_RUNTIME_CAPABILITIES_TOKEN, o as isSandboxJobRuntimeError } from './model-provider.esm.js';
20
20
  import fsPromises from 'fs/promises';
21
21
  import * as path from 'path';
22
22
  import path__default, { join } from 'path';
@@ -41,7 +41,7 @@ import { assertConnectorDefinition } from './connector.esm.js';
41
41
  export { CONNECTOR_AUTHORIZATION_MODES, CONNECTOR_SCOPE_TYPES, getConnectorAuthMethods, getConnectorAuthorizationModes } from './connector.esm.js';
42
42
  export { base64ToBytes, bytesToBase64, createCollaborationClient, createCollaborationPresenceStore, createSocketIoTransportAdapter, createYjsDocumentAdapter } from './collaboration-client.esm.js';
43
43
  import { tool } from '@langchain/core/tools';
44
- import 'zod/v3';
44
+ import { ZodError, z } from 'zod/v3';
45
45
 
46
46
  /**
47
47
  * Metadata keys used in plugins for defining various aspects like entities, subscribers, and configurations.
@@ -3579,17 +3579,11 @@ class OpenAICompatibleReranker {
3579
3579
  if (!Array.isArray(output)) {
3580
3580
  throw new Error('Invalid response format: missing results array');
3581
3581
  }
3582
- // Collect raw scores and normalize them.
3583
- const scores = output.map((r)=>r.relevance_score);
3584
- const minScore = Math.min(...scores);
3585
- const maxScore = Math.max(...scores);
3586
- const scoreRange = maxScore !== minScore ? maxScore - minScore : 1.0;
3587
3582
  const reranked = output.map((r)=>{
3588
3583
  const index = r.index;
3589
- const normalizedScore = (r.relevance_score - minScore) / scoreRange;
3590
3584
  const result = {
3591
3585
  index,
3592
- relevanceScore: normalizedScore
3586
+ relevanceScore: r.relevance_score
3593
3587
  };
3594
3588
  if (options.returnDocuments) {
3595
3589
  var _r_document, _docs_index, _docs_index1;
@@ -3639,6 +3633,44 @@ class Speech2TextChatModel extends BaseChatModel {
3639
3633
  }
3640
3634
 
3641
3635
  const encodingCache = new Map();
3636
+ /** Exact, model-independent text count for hard chunk limits. Treat special-token spellings as literal document text. */ function textEncoding() {
3637
+ const cacheKey = 'encoding:cl100k_base';
3638
+ let encoder = encodingCache.get(cacheKey);
3639
+ if (!encoder) {
3640
+ encoder = getEncoding('cl100k_base');
3641
+ encodingCache.set(cacheKey, encoder);
3642
+ }
3643
+ return encoder;
3644
+ }
3645
+ function countTextTokens(text) {
3646
+ if (!text) return 0;
3647
+ // A hard limit must fail if tokenization fails, never fall back to an estimate.
3648
+ return textEncoding().encode(text, [], []).length;
3649
+ }
3650
+ /** Token boundaries that also end on complete Unicode characters, in UTF-16 source offsets. */ function textTokenBoundaries(text) {
3651
+ const encoder = textEncoding();
3652
+ const tokens = encoder.encode(text, [], []);
3653
+ const boundaries = [
3654
+ {
3655
+ offset: 0,
3656
+ tokens: 0
3657
+ }
3658
+ ];
3659
+ let offset = 0;
3660
+ let start = 0;
3661
+ for(let end = 1; end <= tokens.length; end++){
3662
+ const decoded = encoder.decode(tokens.slice(start, end));
3663
+ if (!decoded || !text.startsWith(decoded, offset)) continue;
3664
+ offset += decoded.length;
3665
+ boundaries.push({
3666
+ offset,
3667
+ tokens: end
3668
+ });
3669
+ start = end;
3670
+ }
3671
+ if (offset !== text.length) throw new Error('Tokenization could not preserve the source text.');
3672
+ return boundaries;
3673
+ }
3642
3674
  /**
3643
3675
  * Fallback token estimation method.
3644
3676
  *
@@ -4103,6 +4135,9 @@ SSOProviderRegistry = __decorate([
4103
4135
  const ConnectorRuntimeCapability = createRuntimeCapability('platform.connector', {
4104
4136
  description: 'Resolve connector credentials for agent middleware.'
4105
4137
  });
4138
+ const ConnectorRuntimeFactoryCapability = createRuntimeCapability('platform.connector.factory', {
4139
+ description: 'Create a connector API restricted to host-granted connectors and the authorized execution identity.'
4140
+ });
4106
4141
 
4107
4142
  const CONNECTOR_STRATEGY = 'CONNECTOR_STRATEGY';
4108
4143
  const ConnectorStrategyKey = (provider)=>applyDecorators(SetMetadata(CONNECTOR_STRATEGY, provider), SetMetadata(STRATEGY_META_KEY, CONNECTOR_STRATEGY));
@@ -5866,6 +5901,9 @@ const EVOLUTION_RUNTIME_SERVICE_TOKEN = 'XPERT_EVOLUTION_RUNTIME_SERVICE';
5866
5901
  const EvolutionRuntimeCapability = createRuntimeCapability('platform.agent-evolution', {
5867
5902
  description: 'Ingest learning signals and resolve immutable capability versions for domain runtimes.'
5868
5903
  });
5904
+ const EvolutionChangeRuntimeCapability = createRuntimeCapability('platform.agent-evolution.changes', {
5905
+ description: 'Prepare, evaluate and publish versioned changes through target-owned validators and effect providers.'
5906
+ });
5869
5907
 
5870
5908
  function defineMcpApp(definition) {
5871
5909
  return Object.freeze(definition);
@@ -6029,6 +6067,12 @@ function validateProviderOptions(options) {
6029
6067
  }
6030
6068
  function validateToolOptions(options, methodName) {
6031
6069
  var _options_description;
6070
+ if (options.resultFormat && options.resultFormat !== 'dto' && options.resultFormat !== 'tool_result') {
6071
+ throw new Error(`Tool '${options.name}' declares an invalid resultFormat.`);
6072
+ }
6073
+ if (options.resultFormat === 'tool_result' && !options.outputSchema) {
6074
+ throw new Error(`Tool '${options.name}' requires outputSchema for tool_result.`);
6075
+ }
6032
6076
  if (!TOOL_NAME_PATTERN.test(options.name) || options.name.length > 191) {
6033
6077
  throw new Error(`Method '${methodName}' declares invalid Tool name '${options.name}'.`);
6034
6078
  }
@@ -6044,6 +6088,9 @@ function validateToolOptions(options, methodName) {
6044
6088
  throw new Error(`MCP Tool '${options.name}' requires at least one execution context.`);
6045
6089
  }
6046
6090
  if (options.mcp) {
6091
+ if (options.mcp.defaultApprovalMode !== undefined && !includesValue(MCP_CAPABILITY_APPROVAL_MODES, options.mcp.defaultApprovalMode)) {
6092
+ throw new Error(`MCP Tool '${options.name}' declares invalid defaultApprovalMode.`);
6093
+ }
6047
6094
  const behavior = options.mcp.behavior;
6048
6095
  if (!includesValue(MCP_TOOL_RISKS, behavior == null ? void 0 : behavior.risk) || !includesValue(MCP_TOOL_SIDE_EFFECTS, behavior == null ? void 0 : behavior.sideEffect) || !includesValue(MCP_TOOL_IDEMPOTENCY, behavior == null ? void 0 : behavior.idempotency)) {
6049
6096
  throw new Error(`MCP Tool '${options.name}' requires valid behavior annotations.`);
@@ -6070,6 +6117,19 @@ function assertStrictObjectSchema(schema, toolName, role) {
6070
6117
  if (!schema || typeof Reflect.get(schema, 'parseAsync') !== 'function') {
6071
6118
  throw new Error(`Tool '${toolName}' requires a Zod ${role} schema.`);
6072
6119
  }
6120
+ // Refinements preserve the strict object shape while enforcing cross-field invariants.
6121
+ // Plugins can load a different physical copy of Zod; use its explicit type tag.
6122
+ while(schema._def.typeName === 'ZodEffects'){
6123
+ const refinement = schema;
6124
+ if (refinement._def.effect.type !== 'refinement') break;
6125
+ schema = refinement.innerType();
6126
+ }
6127
+ if (role === 'output' && schema._def.typeName === 'ZodUnion') {
6128
+ // Recovery receipts may have a different shape, but every branch must reject extra fields.
6129
+ const union = schema;
6130
+ for (const option of union.options)assertStrictObjectSchema(option, toolName, role);
6131
+ return;
6132
+ }
6073
6133
  const definition = Reflect.get(schema, '_def');
6074
6134
  if (!definition || Reflect.get(definition, 'unknownKeys') !== 'strict') {
6075
6135
  throw new Error(`Tool '${toolName}' ${role} schema must be a strict Zod object.`);
@@ -6143,6 +6203,141 @@ XpertToolProviderRegistry = __decorate([
6143
6203
  ])
6144
6204
  ], XpertToolProviderRegistry);
6145
6205
 
6206
+ // Invariants: recovery starts only after the business method returns successfully.
6207
+ // Projection and recovery callbacks must be free of business side effects.
6208
+ // The adapter validates normal output once and validates any fallback separately;
6209
+ // neither path may rerun the operation or suppress input, authorization or commit failures.
6210
+ // Installed plugins may resolve a different physical SDK copy from the host.
6211
+ const PREPARED_RESULT = Symbol.for('xpert.tool.prepared-result.v1');
6212
+ /** Defer output projection until the adapter can validate and recover its result. */ function prepareToolResult(project, recover) {
6213
+ return {
6214
+ [PREPARED_RESULT]: true,
6215
+ project,
6216
+ recover
6217
+ };
6218
+ }
6219
+ function isPrepared(value) {
6220
+ return typeof value === 'object' && value !== null && PREPARED_RESULT in value && value[PREPARED_RESULT] === true && 'project' in value && typeof value.project === 'function' && 'recover' in value && typeof value.recover === 'function';
6221
+ }
6222
+ async function resolveToolResult(value, validate) {
6223
+ if (!isPrepared(value)) return validate(value);
6224
+ try {
6225
+ return await validate(await value.project());
6226
+ } catch (error) {
6227
+ const diagnostic = {
6228
+ code: 'tool_output_invalid',
6229
+ issues: error instanceof ZodError ? error.issues.slice(0, 10).map((issue)=>({
6230
+ path: issue.path.join('.').slice(0, 240),
6231
+ code: issue.code
6232
+ })) : []
6233
+ };
6234
+ // A malformed fallback is a programming error too; never send unchecked data.
6235
+ return validate(await value.recover(diagnostic));
6236
+ }
6237
+ }
6238
+
6239
+ // Why this exists: MCP media blocks and business metadata have different contracts.
6240
+ // Validate metadata with the declared output schema, preserve bounded media blocks,
6241
+ // and include the same DTO in text for clients that hide structuredContent.
6242
+ const XPERT_TOOL_RESULT_FORMAT_VERSION = 1;
6243
+ const contentSchema = z.discriminatedUnion('type', [
6244
+ z.object({
6245
+ type: z.literal('text'),
6246
+ text: z.string().max(2 * 1024 * 1024)
6247
+ }).strict(),
6248
+ z.object({
6249
+ type: z.literal('image'),
6250
+ data: z.string().min(1).max(8 * 1024 * 1024),
6251
+ mimeType: z.enum([
6252
+ 'image/png',
6253
+ 'image/jpeg',
6254
+ 'image/webp',
6255
+ 'image/gif'
6256
+ ])
6257
+ }).strict(),
6258
+ z.object({
6259
+ type: z.literal('audio'),
6260
+ data: z.string().min(1).max(8 * 1024 * 1024),
6261
+ mimeType: z.string().min(1).max(100)
6262
+ }).strict(),
6263
+ z.object({
6264
+ type: z.literal('resource_link'),
6265
+ uri: z.string().min(1).max(4096),
6266
+ name: z.string().max(240).optional()
6267
+ }).strict()
6268
+ ]);
6269
+ /** Validate the envelope separately so binary content never enters the business DTO. */ async function parseDecoratedToolResult(value, outputSchema) {
6270
+ var _result_content;
6271
+ const envelope = z.object({
6272
+ content: z.array(contentSchema).max(32).optional(),
6273
+ structuredContent: outputSchema,
6274
+ isError: z.boolean().optional()
6275
+ }).strict();
6276
+ const result = await envelope.parseAsync(value);
6277
+ var _result_content_map;
6278
+ const content = (_result_content_map = (_result_content = result.content) == null ? void 0 : _result_content.map((item)=>{
6279
+ switch(item.type){
6280
+ case 'text':
6281
+ return {
6282
+ type: 'text',
6283
+ text: item.text
6284
+ };
6285
+ case 'image':
6286
+ return {
6287
+ type: 'image',
6288
+ data: item.data,
6289
+ mimeType: item.mimeType
6290
+ };
6291
+ case 'audio':
6292
+ return {
6293
+ type: 'audio',
6294
+ data: item.data,
6295
+ mimeType: item.mimeType
6296
+ };
6297
+ case 'resource_link':
6298
+ return _extends({
6299
+ type: 'resource_link',
6300
+ uri: item.uri
6301
+ }, item.name ? {
6302
+ name: item.name
6303
+ } : {});
6304
+ }
6305
+ })) != null ? _result_content_map : [];
6306
+ // MCP clients may expose only content to the model. Keep the validated DTO
6307
+ // readable there too, while retaining binary blocks and App structured data.
6308
+ const text = JSON.stringify(result.structuredContent);
6309
+ if (!content.some((item)=>item.type === 'text' && item.text === text)) content.push({
6310
+ type: 'text',
6311
+ text
6312
+ });
6313
+ return _extends({
6314
+ structuredContent: result.structuredContent,
6315
+ content
6316
+ }, result.isError === undefined ? {} : {
6317
+ isError: result.isError
6318
+ });
6319
+ }
6320
+ function agentContent(content) {
6321
+ return (content != null ? content : []).map((item)=>{
6322
+ if (item.type === 'image') return {
6323
+ type: 'image_url',
6324
+ image_url: {
6325
+ url: `data:${item.mimeType};base64,${item.data}`
6326
+ }
6327
+ };
6328
+ if (item.type === 'text') return item;
6329
+ var _item_name;
6330
+ if (item.type === 'resource_link') return {
6331
+ type: 'text',
6332
+ text: `${(_item_name = item.name) != null ? _item_name : 'Resource'}: ${item.uri}`
6333
+ };
6334
+ return {
6335
+ type: 'text',
6336
+ text: `Audio content (${item.mimeType}) is available through MCP.`
6337
+ };
6338
+ });
6339
+ }
6340
+
6146
6341
  class DecoratedToolsetStrategy {
6147
6342
  validateConfig() {
6148
6343
  return Promise.resolve();
@@ -6247,13 +6442,27 @@ function createAgentTool(instance, descriptor, middlewareContext, middlewareOpti
6247
6442
  return tool(async (input, config)=>{
6248
6443
  const parsedInput = await descriptor.options.inputSchema.parseAsync(input);
6249
6444
  const output = await invoke(parsedInput, agentExecutionContext(middlewareContext, middlewareOptions, config));
6250
- const parsedOutput = descriptor.options.outputSchema ? await descriptor.options.outputSchema.parseAsync(output) : output;
6251
- return stringifyDto(parsedOutput, descriptor.options.name);
6445
+ if (descriptor.options.resultFormat === 'tool_result' && descriptor.options.outputSchema) {
6446
+ const result = await resolveToolResult(output, (value)=>parseDecoratedToolResult(value, descriptor.options.outputSchema));
6447
+ var _result_isError;
6448
+ return [
6449
+ agentContent(result.content),
6450
+ {
6451
+ structuredContent: result.structuredContent,
6452
+ isError: (_result_isError = result.isError) != null ? _result_isError : false
6453
+ }
6454
+ ];
6455
+ }
6456
+ return resolveToolResult(output, async (value)=>{
6457
+ const parsedOutput = descriptor.options.outputSchema ? await descriptor.options.outputSchema.parseAsync(value) : value;
6458
+ return stringifyDto(parsedOutput, descriptor.options.name);
6459
+ });
6252
6460
  }, _extends({
6253
6461
  name: descriptor.options.name,
6254
6462
  description: descriptor.options.description,
6255
6463
  schema: descriptor.options.inputSchema,
6256
- verboseParsingErrors: true
6464
+ verboseParsingErrors: true,
6465
+ responseFormat: descriptor.options.resultFormat === 'tool_result' ? 'content_and_artifact' : 'content'
6257
6466
  }, descriptor.options.metadata ? {
6258
6467
  metadata: descriptor.options.metadata
6259
6468
  } : {}));
@@ -6277,7 +6486,10 @@ function createMcpTool(instance, descriptor) {
6277
6486
  eligible: true
6278
6487
  }
6279
6488
  },
6280
- behavior: mcp.behavior,
6489
+ behavior: mcp.behavior
6490
+ }, mcp.defaultApprovalMode ? {
6491
+ defaultApprovalMode: mcp.defaultApprovalMode
6492
+ } : {}, {
6281
6493
  requiredContext: [
6282
6494
  ...mcp.requiredContext
6283
6495
  ],
@@ -6297,18 +6509,23 @@ function createMcpTool(instance, descriptor) {
6297
6509
  execute: async (input, context)=>{
6298
6510
  const parsedInput = await descriptor.options.inputSchema.parseAsync(input);
6299
6511
  const output = await invoke(parsedInput, mcpExecutionContext(context));
6300
- const parsedOutput = await outputSchema.parseAsync(output);
6301
- const dto = jsonDto(parsedOutput, descriptor.options.name);
6302
- var _descriptor_options_title;
6303
- return {
6304
- content: [
6305
- {
6306
- type: 'text',
6307
- text: `${(_descriptor_options_title = descriptor.options.title) != null ? _descriptor_options_title : descriptor.options.name} completed. See structuredContent for the result.`
6308
- }
6309
- ],
6310
- structuredContent: dto
6311
- };
6512
+ if (descriptor.options.resultFormat === 'tool_result') {
6513
+ return resolveToolResult(output, (value)=>parseDecoratedToolResult(value, outputSchema));
6514
+ }
6515
+ return resolveToolResult(output, async (value)=>{
6516
+ const parsedOutput = await outputSchema.parseAsync(value);
6517
+ // Serialize once so text-only clients and MCP Apps receive the same JSON-safe DTO.
6518
+ const text = stringifyDto(parsedOutput, descriptor.options.name);
6519
+ return {
6520
+ content: [
6521
+ {
6522
+ type: 'text',
6523
+ text
6524
+ }
6525
+ ],
6526
+ structuredContent: JSON.parse(text)
6527
+ };
6528
+ });
6312
6529
  }
6313
6530
  });
6314
6531
  }
@@ -6373,9 +6590,6 @@ function stringifyDto(value, toolName) {
6373
6590
  if (result === undefined) throw new Error(`Tool '${toolName}' returned a non-JSON value.`);
6374
6591
  return result;
6375
6592
  }
6376
- function jsonDto(value, toolName) {
6377
- return JSON.parse(stringifyDto(value, toolName));
6378
- }
6379
6593
  function asI18n(value) {
6380
6594
  return {
6381
6595
  en_US: value,
@@ -6455,4 +6669,4 @@ XpertToolProviderCoordinator = __decorate([
6455
6669
  ])
6456
6670
  ], XpertToolProviderCoordinator);
6457
6671
 
6458
- export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_ERROR_STEER_TARGET_NOT_RUNNING, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModel, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, COLLABORATION_DOCUMENT_PROVIDER, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CollaborationDocumentProvider, CollaborationDocumentProviderRegistry, CollaborationRuntimeCapability, CommonParameterRules, ConnectorRuntimeCapability, ConnectorStrategyKey, ConnectorStrategyRegistry, CreateModelClientCommand, CredentialsValidateFailedError, DATASOURCE_STRATEGY, DBCreateTableMode, DBProtocolEnum, DBSyntaxEnum, DBTableAction, DBTableDataAction, DEFAULT_EXECUTION_CONFIG, DEFAULT_SANDBOX_EXECUTION_MAX_OUTPUT_BYTES, DEFAULT_SANDBOX_FILE_OPERATION_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_SEC, DEFAULT_SANDBOX_FILE_SEARCH_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_SEC, DEFAULT_SANDBOX_SHELL_EXECUTION_OPTIONS, DEFAULT_SANDBOX_SHELL_TIMEOUT_MS, DEFAULT_SANDBOX_SHELL_TIMEOUT_SEC, DOCUMENT_SOURCE_STRATEGY, DOCUMENT_TRANSFORMER_STRATEGY, DataSourceStrategy, DataSourceStrategyRegistry, DecoratedAgentMiddlewareStrategy, DecoratedToolsetStrategy, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, EVOLUTION_RUNTIME_SERVICE_TOKEN, EVOLUTION_TARGET_PROVIDER, EvolutionRuntimeCapability, EvolutionTargetProviderRegistry, EvolutionTargetProviderStrategy, FILE_STORAGE_PROVIDER, FILE_UPLOAD_TARGET_STRATEGY, FileRuntimeCapability, FileStorageProvider, FileStorageProviderRegistry, FileUploadTargetRegistry, FileUploadTargetStrategy, GLOBAL_ORGANIZATION_SCOPE, HANDOFF_PERMISSION_SERVICE_TOKEN, HANDOFF_PROCESSOR_STRATEGY, HANDOFF_QUEUE_SERVICE_TOKEN, HandoffProcessorRegistry, HandoffProcessorStrategy, IMAGE_UNDERSTANDING_STRATEGY, INTEGRATION_PERMISSION_SERVICE_TOKEN, INTEGRATION_STRATEGY, ImageGenerationModel, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, LLMUsage, LargeLanguageModel, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, MCP_CAPABILITY_CHANGE_EVENT_TYPES, MODEL_OUTPUT_VALIDATION_ERROR_CODE, ModelOutputValidationError, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_CONFIG_RESOLVER_TOKEN, PLUGIN_JOB_PROCESSOR_METADATA, PLUGIN_METADATA, PLUGIN_METADATA_KEY, PLUGIN_VERSION_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_SERVICE_TOKEN, PROVIDE_AI_MODEL_LLM, PROVIDE_AI_MODEL_MODERATION, PROVIDE_AI_MODEL_RERANK, PROVIDE_AI_MODEL_SPEECH2TEXT, PROVIDE_AI_MODEL_TEXT_EMBEDDING, PROVIDE_AI_MODEL_TTS, PluginJobProcessor, PluginWebhookAuth, PluginWebhookAuthGuard, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, RetrieverRegistry, RetrieverStrategy, SANDBOX_PROVIDER, SANDBOX_RUNTIME_PROVIDER, SANDBOX_SHELL_TIMEOUT_LIMITS_SEC, SANDBOX_WORKSPACE_MAPPER, SKILL_SOURCE_PROVIDER, SPEECH_TO_TEXT_PERMISSION_SERVICE_TOKEN, SPEECH_TO_TEXT_SERVICE_TOKEN, SSOProviderRegistry, SSOProviderStrategyKey, SSO_BINDING_PERMISSION_SERVICE_TOKEN, SSO_PROVIDER, STRATEGY_META_KEY, SYSTEM_GLOBAL_SCOPE, SandboxProviderRegistry, SandboxProviderStrategy, SandboxRuntimeProviderRegistry, SandboxRuntimeProviderStrategy, SandboxWorkspaceMapperRegistry, SandboxWorkspaceMapperStrategy, SkillSourceProviderRegistry, SkillSourceProviderStrategy, Speech2TextChatModel, SpeechToTextModel, StrategyBus, TENANT_GLOBAL_SCOPE_PREFIX, TENANT_GLOBAL_SCOPE_SUFFIX, TEXT_SPLITTER_STRATEGY, TOOLSET_STRATEGY, TextEmbeddingModelManager, TextSplitterRegistry, TextSplitterStrategy, TextToSpeechModel, ToolsetRegistry, ToolsetStrategy, USER_PERMISSION_SERVICE_TOKEN, VECTOR_STORE_STRATEGY, VIDEO_GENERATION_PERMISSION_SERVICE_TOKEN, VIDEO_GENERATION_SERVICE_TOKEN, VIDEO_GENERATOR_FAMILIES, VIEW_EXTENSION_CACHE_SERVICE_TOKEN, VIEW_EXTENSION_PROVIDER, VectorStoreRegistry, VectorStoreStrategy, VideoGenerationModel, ViewExtensionProvider, ViewExtensionProviderRegistry, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WrapWorkflowNodeExecutionCommand, XPERT_AGENT_MIDDLEWARE_RUNTIME_TOKEN, XPERT_TOOL_METHOD_METADATA, XPERT_TOOL_PROVIDER, XPERT_TOOL_PROVIDER_METADATA, XpFileSystem, XpertServerPlugin, XpertTool, XpertToolProvider, XpertToolProviderCoordinator, XpertToolProviderRegistry, als, appendSandboxMessage, assertConnectorDefinition, buildSandboxTimeoutMessage, calcTokenUsage, calculateLLMUsagePrice, calculateModelPrice, calculateModelUsageCharge, chunkText, countTokensSafe, createI18nInstance, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, defineMcpApp, defineMcpCapabilities, defineMcpPrompt, defineMcpResource, defineMcpResourceTemplate, defineXpertTool, derivePluginArtifactNamespace, describeXpertToolProvider, downloadRemoteFile, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, getXpertToolMethod, isDevelopmentSandboxRuntimeEnvironment, isModelOutputValidationError, isModelUsagePricingConfig, isRemoteFile, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStrategyInstance, isStructuredMessageType, isTenantGlobalScopeKey, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, pluginArtifactTableName, processAsyncAIGCManagedJob, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveModelUsagePricingSnapshot, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveStrategyMetadataTarget, resolveTenantGlobalScopeKey, resolveTokenUsage, runWithRequestContext, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage };
6672
+ export { ACCOUNT_BINDING_PERMISSION_SERVICE_TOKEN, AGENT_CHAT_DISPATCH_ERROR_STEER_TARGET_NOT_RUNNING, AGENT_CHAT_DISPATCH_MESSAGE_TYPE, AGENT_MIDDLEWARE_STRATEGY, AIModel, AIModelProviderNotFoundException, AIModelProviderRegistry, AIModelProviderStrategy, AI_MODEL_PROVIDER, AdapterDataSourceStrategy, AgentMiddlewareRegistry, AgentMiddlewareStrategy, AiModelNotFoundException, AssistantTaskRuntimeCapability, BOUND_IDENTITY_LOGIN_PERMISSION_SERVICE_TOKEN, BUILTIN_GLOBAL_SCOPE, BaseHTTPQueryRunner, BaseQueryRunner, BaseSQLQueryRunner, BaseSandbox, BaseStrategyRegistry, BuiltinToolset, CHAT_CHANNEL, CHAT_CHANNEL_TEXT_LIMITS, COLLABORATION_DOCUMENT_PROVIDER, CONNECTION_COMMAND_ROUTER_TOKEN, CONNECTOR_STRATEGY, CancelConversationCommand, ChatChannel, ChatChannelRegistry, ChatOAICompatReasoningModel, CollaborationDocumentProvider, CollaborationDocumentProviderRegistry, CollaborationRuntimeCapability, CommonParameterRules, ConnectorRuntimeCapability, ConnectorRuntimeFactoryCapability, ConnectorStrategyKey, ConnectorStrategyRegistry, CreateModelClientCommand, CredentialsValidateFailedError, DATASOURCE_STRATEGY, DBCreateTableMode, DBProtocolEnum, DBSyntaxEnum, DBTableAction, DBTableDataAction, DEFAULT_EXECUTION_CONFIG, DEFAULT_SANDBOX_EXECUTION_MAX_OUTPUT_BYTES, DEFAULT_SANDBOX_FILE_OPERATION_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_OPERATION_TIMEOUT_SEC, DEFAULT_SANDBOX_FILE_SEARCH_EXECUTION_OPTIONS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_MS, DEFAULT_SANDBOX_FILE_SEARCH_TIMEOUT_SEC, DEFAULT_SANDBOX_SHELL_EXECUTION_OPTIONS, DEFAULT_SANDBOX_SHELL_TIMEOUT_MS, DEFAULT_SANDBOX_SHELL_TIMEOUT_SEC, DOCUMENT_SOURCE_STRATEGY, DOCUMENT_TRANSFORMER_STRATEGY, DataSourceStrategy, DataSourceStrategyRegistry, DecoratedAgentMiddlewareStrategy, DecoratedToolsetStrategy, DocumentSourceRegistry, DocumentSourceStrategy, DocumentTransformerRegistry, DocumentTransformerStrategy, EVOLUTION_RUNTIME_SERVICE_TOKEN, EVOLUTION_TARGET_PROVIDER, EvolutionChangeRuntimeCapability, EvolutionRuntimeCapability, EvolutionTargetProviderRegistry, EvolutionTargetProviderStrategy, FILE_STORAGE_PROVIDER, FILE_UPLOAD_TARGET_STRATEGY, FileRuntimeCapability, FileStorageProvider, FileStorageProviderRegistry, FileUploadTargetRegistry, FileUploadTargetStrategy, GLOBAL_ORGANIZATION_SCOPE, HANDOFF_PERMISSION_SERVICE_TOKEN, HANDOFF_PROCESSOR_STRATEGY, HANDOFF_QUEUE_SERVICE_TOKEN, HandoffProcessorRegistry, HandoffProcessorStrategy, IMAGE_UNDERSTANDING_STRATEGY, INTEGRATION_PERMISSION_SERVICE_TOKEN, INTEGRATION_STRATEGY, ImageGenerationModel, ImageUnderstandingRegistry, ImageUnderstandingStrategy, IntegrationStrategyKey, IntegrationStrategyRegistry, JUMP_TO_TARGETS, JsonSchemaValidator, KNOWLEDGE_STRATEGY, KnowledgeStrategyKey, KnowledgeStrategyRegistry, LLMUsage, LargeLanguageModel, MANAGED_CONNECTION_REGISTRY_TOKEN, MANAGED_QUEUE_HANDLER_REGISTRY_TOKEN, MANAGED_QUEUE_SERVICE_TOKEN, MCP_CAPABILITY_CHANGE_EVENT_TYPES, MODEL_OUTPUT_VALIDATION_ERROR_CODE, ModelOutputValidationError, ModelProvider, ORGANIZATION_METADATA_KEY, OpenAICompatibleReranker, PERMISSION_OPERATION_METADATA_KEY, PLUGIN_CONFIG_RESOLVER_TOKEN, PLUGIN_JOB_PROCESSOR_METADATA, PLUGIN_METADATA, PLUGIN_METADATA_KEY, PLUGIN_VERSION_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_METADATA_KEY, PLUGIN_WEBHOOK_AUTH_SERVICE_TOKEN, PROVIDE_AI_MODEL_LLM, PROVIDE_AI_MODEL_MODERATION, PROVIDE_AI_MODEL_RERANK, PROVIDE_AI_MODEL_SPEECH2TEXT, PROVIDE_AI_MODEL_TEXT_EMBEDDING, PROVIDE_AI_MODEL_TTS, PluginJobProcessor, PluginWebhookAuth, PluginWebhookAuthGuard, RETRIEVER_STRATEGY, RequestContext, RequestContextMiddleware, RequirePermissionOperation, RerankModel, RetrieverRegistry, RetrieverStrategy, SANDBOX_PROVIDER, SANDBOX_RUNTIME_PROVIDER, SANDBOX_SHELL_TIMEOUT_LIMITS_SEC, SANDBOX_WORKSPACE_MAPPER, SKILL_SOURCE_PROVIDER, SPEECH_TO_TEXT_PERMISSION_SERVICE_TOKEN, SPEECH_TO_TEXT_SERVICE_TOKEN, SSOProviderRegistry, SSOProviderStrategyKey, SSO_BINDING_PERMISSION_SERVICE_TOKEN, SSO_PROVIDER, STRATEGY_META_KEY, SYSTEM_GLOBAL_SCOPE, SandboxProviderRegistry, SandboxProviderStrategy, SandboxRuntimeProviderRegistry, SandboxRuntimeProviderStrategy, SandboxWorkspaceMapperRegistry, SandboxWorkspaceMapperStrategy, SkillSourceProviderRegistry, SkillSourceProviderStrategy, Speech2TextChatModel, SpeechToTextModel, StrategyBus, TENANT_GLOBAL_SCOPE_PREFIX, TENANT_GLOBAL_SCOPE_SUFFIX, TEXT_SPLITTER_STRATEGY, TOOLSET_STRATEGY, TextEmbeddingModelManager, TextSplitterRegistry, TextSplitterStrategy, TextToSpeechModel, ToolsetRegistry, ToolsetStrategy, USER_PERMISSION_SERVICE_TOKEN, VECTOR_STORE_STRATEGY, VIDEO_GENERATION_PERMISSION_SERVICE_TOKEN, VIDEO_GENERATION_SERVICE_TOKEN, VIDEO_GENERATOR_FAMILIES, VIEW_EXTENSION_CACHE_SERVICE_TOKEN, VIEW_EXTENSION_PROVIDER, VectorStoreRegistry, VectorStoreStrategy, VideoGenerationModel, ViewExtensionProvider, ViewExtensionProviderRegistry, WORKFLOW_NODE_STRATEGY, WORKFLOW_TRIGGER_STRATEGY, WorkflowNodeRegistry, WorkflowNodeStrategy, WorkflowTriggerRegistry, WorkflowTriggerStrategy, WrapWorkflowNodeExecutionCommand, XPERT_AGENT_MIDDLEWARE_RUNTIME_TOKEN, XPERT_TOOL_METHOD_METADATA, XPERT_TOOL_PROVIDER, XPERT_TOOL_PROVIDER_METADATA, XPERT_TOOL_RESULT_FORMAT_VERSION, XpFileSystem, XpertServerPlugin, XpertTool, XpertToolProvider, XpertToolProviderCoordinator, XpertToolProviderRegistry, als, appendSandboxMessage, assertConnectorDefinition, buildSandboxTimeoutMessage, calcTokenUsage, calculateLLMUsagePrice, calculateModelPrice, calculateModelUsageCharge, chunkText, countTextTokens, countTokensSafe, createI18nInstance, createPluginLogger, createRuntimeCapability, defineAgentMessageType, defineChannelMessageType, defineMcpApp, defineMcpCapabilities, defineMcpPrompt, defineMcpResource, defineMcpResourceTemplate, defineXpertTool, derivePluginArtifactNamespace, describeXpertToolProvider, downloadRemoteFile, formatSandboxTimeout, getDefaultTenantId, getErrorMessage, getModelContextSize, getPermissionOperationMetadata, getPositionList, getPositionMap, getRequestContext, getRequiredPermissionOperation, getTenantGlobalScopeKey, getXpertToolMethod, isDevelopmentSandboxRuntimeEnvironment, isModelOutputValidationError, isModelUsagePricingConfig, isRemoteFile, isSandboxBackend, isSandboxManagedServiceAdapter, isSandboxServiceProxyAdapter, isSandboxTerminalAdapter, isStrategyInstance, isStructuredMessageType, isTenantGlobalScopeKey, loadYamlFile, mergeCredentials, mergeParentChildChunks, normalizeContextSize, pluginArtifactTableName, prepareToolResult, processAsyncAIGCManagedJob, renderRemoteModuleIframeHtml, renderRemoteReactIframeHtml, renderRemoteVueIframeHtml, resolveModelUsagePricingSnapshot, resolveSandboxBackend, resolveSandboxExecutionOptions, resolveSandboxManagedServiceAdapter, resolveSandboxServiceProxyAdapter, resolveSandboxTerminalAdapter, resolveStrategyMetadataTarget, resolveTenantGlobalScopeKey, resolveTokenUsage, runWithRequestContext, secondsToMilliseconds, setDefaultTenantId, sumTokenUsage, textTokenBoundaries };
@@ -199,10 +199,16 @@ const KnowledgebaseDocumentsRuntimeCapability = createRuntimeCapability('platfor
199
199
  const KnowledgeDocumentVisualAssetsRuntimeCapability = createRuntimeCapability('platform.knowledgebase.visual-assets', {
200
200
  description: 'Issue execution-scoped logical KnowledgeDocument image paths and inject validated images without exposing host storage paths.'
201
201
  });
202
+ const KnowledgeDocumentVisualAssetsRuntimeFactoryCapability = createRuntimeCapability('platform.knowledge-document.visual-assets.factory', {
203
+ description: 'Create a visual-assets API with an execution-local image allow-list and authorized workspace writer.'
204
+ });
202
205
 
203
206
  const ActorTokenRuntimeCapability = createRuntimeCapability('platform.actor-token', {
204
207
  description: 'Mint a short-lived host-issued actor bearer token for outbound API calls.'
205
208
  });
209
+ /** Platform registry entry. The operation capability above is bound only inside a caller runtime. */ const ActorTokenRuntimeFactoryCapability = createRuntimeCapability('platform.actor-token.factory', {
210
+ description: 'Create an actor-token API with host-bound identity, delegation claims and an isolated token cache.'
211
+ });
206
212
 
207
213
  const ArtifactsRuntimeCapability = createRuntimeCapability('platform.artifacts', {
208
214
  description: 'Create, version, preview, download, share, archive, and delete platform-managed plugin and Agent artifacts.'
@@ -375,12 +381,14 @@ function normalizeWorkspaceScope(scope) {
375
381
  }
376
382
 
377
383
  exports.ActorTokenRuntimeCapability = ActorTokenRuntimeCapability;
384
+ exports.ActorTokenRuntimeFactoryCapability = ActorTokenRuntimeFactoryCapability;
378
385
  exports.ArtifactsRuntimeCapability = ArtifactsRuntimeCapability;
379
386
  exports.BaseTool = BaseTool;
380
387
  exports.BaseToolset = BaseToolset;
381
388
  exports.BuiltinToolset = BuiltinToolset;
382
389
  exports.DefaultRuntimeCapabilityRegistry = DefaultRuntimeCapabilityRegistry;
383
390
  exports.KnowledgeDocumentVisualAssetsRuntimeCapability = KnowledgeDocumentVisualAssetsRuntimeCapability;
391
+ exports.KnowledgeDocumentVisualAssetsRuntimeFactoryCapability = KnowledgeDocumentVisualAssetsRuntimeFactoryCapability;
384
392
  exports.KnowledgebaseDocumentsRuntimeCapability = KnowledgebaseDocumentsRuntimeCapability;
385
393
  exports.KnowledgebaseProvisioningRuntimeCapability = KnowledgebaseProvisioningRuntimeCapability;
386
394
  exports.KnowledgebaseRuntimeCapability = KnowledgebaseRuntimeCapability;
@@ -197,10 +197,16 @@ const KnowledgebaseDocumentsRuntimeCapability = createRuntimeCapability('platfor
197
197
  const KnowledgeDocumentVisualAssetsRuntimeCapability = createRuntimeCapability('platform.knowledgebase.visual-assets', {
198
198
  description: 'Issue execution-scoped logical KnowledgeDocument image paths and inject validated images without exposing host storage paths.'
199
199
  });
200
+ const KnowledgeDocumentVisualAssetsRuntimeFactoryCapability = createRuntimeCapability('platform.knowledge-document.visual-assets.factory', {
201
+ description: 'Create a visual-assets API with an execution-local image allow-list and authorized workspace writer.'
202
+ });
200
203
 
201
204
  const ActorTokenRuntimeCapability = createRuntimeCapability('platform.actor-token', {
202
205
  description: 'Mint a short-lived host-issued actor bearer token for outbound API calls.'
203
206
  });
207
+ /** Platform registry entry. The operation capability above is bound only inside a caller runtime. */ const ActorTokenRuntimeFactoryCapability = createRuntimeCapability('platform.actor-token.factory', {
208
+ description: 'Create an actor-token API with host-bound identity, delegation claims and an isolated token cache.'
209
+ });
204
210
 
205
211
  const ArtifactsRuntimeCapability = createRuntimeCapability('platform.artifacts', {
206
212
  description: 'Create, version, preview, download, share, archive, and delete platform-managed plugin and Agent artifacts.'
@@ -372,4 +378,4 @@ function normalizeWorkspaceScope(scope) {
372
378
  } : {});
373
379
  }
374
380
 
375
- export { ActorTokenRuntimeCapability as A, BuiltinToolset as B, DefaultRuntimeCapabilityRegistry as D, KnowledgeDocumentVisualAssetsRuntimeCapability as K, ModelProviderBuiltinToolset as M, ProjectAccessRuntimeCapability as P, SANDBOX_JOB_ERROR_CODES as S, WORKSPACE_FILES_SOURCE as W, XPERT_RUNTIME_CAPABILITIES_TOKEN as X, ArtifactsRuntimeCapability as a, BaseTool as b, createRuntimeCapability as c, BaseToolset as d, KnowledgebaseDocumentsRuntimeCapability as e, KnowledgebaseProvisioningRuntimeCapability as f, KnowledgebaseRuntimeCapability as g, ProjectProvisioningRuntimeCapability as h, SANDBOX_JOB_PROGRESS_PREFIX as i, SandboxJobRuntimeError as j, SandboxJobsRuntimeCapability as k, WorkspaceFilesRuntimeCapability as l, isSandboxJobRuntimeError as m };
381
+ export { ActorTokenRuntimeCapability as A, BuiltinToolset as B, DefaultRuntimeCapabilityRegistry as D, KnowledgeDocumentVisualAssetsRuntimeCapability as K, ModelProviderBuiltinToolset as M, ProjectAccessRuntimeCapability as P, SANDBOX_JOB_ERROR_CODES as S, WORKSPACE_FILES_SOURCE as W, XPERT_RUNTIME_CAPABILITIES_TOKEN as X, ActorTokenRuntimeFactoryCapability as a, ArtifactsRuntimeCapability as b, createRuntimeCapability as c, BaseTool as d, BaseToolset as e, KnowledgeDocumentVisualAssetsRuntimeFactoryCapability as f, KnowledgebaseDocumentsRuntimeCapability as g, KnowledgebaseProvisioningRuntimeCapability as h, KnowledgebaseRuntimeCapability as i, ProjectProvisioningRuntimeCapability as j, SANDBOX_JOB_PROGRESS_PREFIX as k, SandboxJobRuntimeError as l, SandboxJobsRuntimeCapability as m, WorkspaceFilesRuntimeCapability as n, isSandboxJobRuntimeError as o };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xpert-ai/plugin-sdk",
3
- "version": "3.18.3",
3
+ "version": "3.18.5",
4
4
  "license": "AGPL-3.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "@langchain/openai": "0.6.9",
20
- "@xpert-ai/contracts": "3.18.2",
20
+ "@xpert-ai/contracts": "3.18.5",
21
21
  "express": "^4.22.1",
22
22
  "js-tiktoken": "^1.0.21"
23
23
  },
@@ -0,0 +1,49 @@
1
+ # Platform capabilities and scoped factories
2
+
3
+ The platform registry is populated by `RuntimeCapabilityProvider` discovery after Nest has instantiated the application modules. Domain modules own their providers. HTTP handlers, View Actions, background jobs and Agent runtimes can consume this registry without constructing an Agent middleware runtime.
4
+
5
+ ## Choose the correct registry entry
6
+
7
+ Stateless domain APIs such as ProjectProvisioning, Knowledgebase, Artifacts and File are registered directly. Their domain authorization checks still run for each operation. Agent runtimes may bind additional defaults to the same domain service, such as the conversation for File access.
8
+
9
+ Three capabilities expose a **factory** in the platform registry. The operation API has a separate key and belongs only to a caller's scoped runtime:
10
+
11
+ | Platform factory key | Scoped operation key | State owned by one API |
12
+ | ------------------------------------------------------- | ------------------------------------------------ | ---------------------------------------------------------- |
13
+ | `ConnectorRuntimeFactoryCapability` | `ConnectorRuntimeCapability` | Host-selected connector binding IDs and execution identity |
14
+ | `ActorTokenRuntimeFactoryCapability` | `ActorTokenRuntimeCapability` | Caller identity, fixed delegation claims and token cache |
15
+ | `KnowledgeDocumentVisualAssetsRuntimeFactoryCapability` | `KnowledgeDocumentVisualAssetsRuntimeCapability` | Issued image paths and execution binding |
16
+
17
+ The platform registry deliberately does not return a shared operation API for these three keys. Checking the scoped operation key on the platform registry is not a provider availability check; check the factory key there instead.
18
+
19
+ ## Bind once for a caller operation
20
+
21
+ ```ts
22
+ import {
23
+ ActorTokenRuntimeFactoryCapability,
24
+ type ActorTokenRuntimeScope,
25
+ type RuntimeCapabilityRegistry
26
+ } from '@xpert-ai/plugin-sdk'
27
+
28
+ // authorizedScope comes from the host's authenticated, authorized request/job context.
29
+ function bindJobTokenApi(capabilities: RuntimeCapabilityRegistry, authorizedScope: ActorTokenRuntimeScope) {
30
+ return capabilities.require(ActorTokenRuntimeFactoryCapability).createScopedApi({
31
+ ...authorizedScope,
32
+ act: { sub: 'background-task' }
33
+ })
34
+ }
35
+ ```
36
+
37
+ Reuse the returned API during that one operation. Create a new API for the next caller/execution. Never keep a scoped API in a singleton, or register it back into the platform registry. Factory resolution must happen after provider discovery, not in service constructors.
38
+
39
+ `RuntimeIdentityScope` carries the authorized tenant, organization, user and optional project/Assistant/conversation/execution identity. It is an in-process host contract, not an HTTP DTO or model-visible tool input. A factory does not grant access: callers must first validate request/job ownership, and operations retain their domain checks.
40
+
41
+ - Connector APIs copy the selected binding IDs. Empty selection denies access. Credential access retains identity, Assistant, project membership, personal/shared authorization and audit checks. Existing connector execution binding requirements remain in force.
42
+ - ActorToken APIs capture identity and host-defined `act` claims. Per-call `act` adds metadata but cannot replace fixed host claims. Cached tokens are rejected if used under a different caller identity.
43
+ - Visual-assets APIs require a complete authorized execution binding when used. They only read paths issued to the same API/execution and recheck document fingerprints. The caller supplies an already scoped WorkspaceFiles writer.
44
+
45
+ ## Agent integration
46
+
47
+ The Agent facade resolves the platform factories when initializing a scoped runtime and registers the resulting operation APIs in that runtime's child registry. This does not change the model-visible tool list inside a tool-call loop.
48
+
49
+ Some child Agent identities are assigned after graph construction. Visual-assets factories accept an optional host-owned `resolveExecutionScope` callback for this case. The Agent integration supplies the LangGraph resolver; the domain factory has no LangGraph dependency. Platform callers that omit the callback use the fixed scope captured at API creation. Every image issuance and consumption still verifies the execution binding.
@@ -95,6 +95,8 @@ export type AgentMiddlewareCorrelatedExecution = {
95
95
  };
96
96
  export type AgentMiddlewareAssistantTaskInput = {
97
97
  xpertId: string;
98
+ /** Selects the Assistant base and Primary models; child Agents retain authored models. */
99
+ modelId?: string;
98
100
  agentKey?: string;
99
101
  /** Resolve an organization-owned external Assistant from the requester's published graph. */
100
102
  target?: AgentMiddlewareAssistantTaskTarget;
@@ -137,6 +139,7 @@ export type AgentMiddlewareAssistantTaskCancelResult = {
137
139
  canceledExecutionIds: string[];
138
140
  };
139
141
  export interface AgentMiddlewareAssistantTaskApi {
142
+ getModels?(xpertId: string): Promise<import('@xpert-ai/contracts').TAssistantModelsResponse>;
140
143
  startTask(input: AgentMiddlewareAssistantTaskInput): Promise<AgentMiddlewareAssistantTaskResult>;
141
144
  /** Return only safe binding descriptors; internal Assistant instance IDs are intentionally omitted. */
142
145
  listExternalAssistantBindings?(input: AgentMiddlewareListExternalAssistantBindingsInput): Promise<AgentMiddlewareExternalAssistantBinding[]>;
@@ -7,6 +7,7 @@ import { ICopilotModel, IModelAccessResolution, IXpertAgentExecution, JSONValue,
7
7
  import { Subscriber } from 'rxjs';
8
8
  import { AIGCModelClient, AsyncAIGCModelClient, IRerank, TLLMUsage } from '../../ai-model/types';
9
9
  import type { RuntimeCapabilityRegistry } from '../../core';
10
+ import type { ConnectorRuntimeScope } from '../../connector/runtime-capability';
10
11
  import type { WorkspaceFileCatalog } from '../../runtime/capabilities/workspace-files';
11
12
  export * from './runtime-capability';
12
13
  export * from './capabilities';
@@ -92,27 +93,14 @@ export type AgentMiddlewareModelProviderConnection = {
92
93
  /** Persist final authoritative usage and calculate its charge exactly once. */
93
94
  reportUsage(report: ModelUsageReport, modelAccess?: IModelAccessResolution): Promise<ModelUsageReportResult>;
94
95
  };
95
- export type AgentMiddlewareRuntimeScope = {
96
- tenantId?: string | null;
97
- organizationId?: string | null;
96
+ export type AgentMiddlewareRuntimeScope = ConnectorRuntimeScope & {
98
97
  providerScopeId?: string | null;
99
- userId?: string | null;
100
- workspaceId?: string | null;
101
- projectId?: string | null;
102
- xpertId?: string | null;
103
98
  /** Authoritative Volume catalog for runtime workspace files. */
104
99
  catalog?: WorkspaceFileCatalog | null;
105
100
  /** Authoritative catalog identity for portable workspace references. */
106
101
  scopeId?: string | null;
107
102
  /** Legacy xperts catalog compatibility flag; new runtimes use user-xperts instead. */
108
103
  isolateByUser?: boolean | null;
109
- xpertName?: string | null;
110
- conversationId?: string | null;
111
- threadId?: string | null;
112
- agentKey?: string | null;
113
- executionId?: string | null;
114
- /** Connector bindings selected for this conversation. An empty list denies connector resolution. */
115
- connectorBindingIds?: string[] | null;
116
104
  usageCallback?: (usage: TLLMUsage) => void | Promise<void>;
117
105
  workspaceRoot?: string | null;
118
106
  workspacePath?: string | null;
@@ -4,6 +4,7 @@ import { AIModel } from '../ai-model';
4
4
  import { TChatModelOptions } from './model';
5
5
  export type RerankResult = {
6
6
  index: number;
7
+ /** Relevance score reported by the rerank provider. Higher values are more relevant. */
7
8
  relevanceScore: number;
8
9
  document?: Document<Record<string, any>>;
9
10
  };
@@ -14,6 +15,7 @@ export declare abstract class RerankModel extends AIModel {
14
15
  export interface IRerank {
15
16
  rerank(docs: Document<Record<string, any>>[], query: string, options: {
16
17
  topN?: number;
18
+ /** Minimum relevanceScore, applied before the Top N limit. */
17
19
  scoreThreshold?: number;
18
20
  model?: string;
19
21
  }): Promise<RerankResult[]>;
@@ -1,4 +1,10 @@
1
1
  import type { TiktokenEncoding } from 'js-tiktoken';
2
+ export declare function countTextTokens(text: string): number;
3
+ /** Token boundaries that also end on complete Unicode characters, in UTF-16 source offsets. */
4
+ export declare function textTokenBoundaries(text: string): {
5
+ offset: number;
6
+ tokens: number;
7
+ }[];
2
8
  /**
3
9
  * Count tokens in text
4
10
  * 1) Preferred: js-tiktoken precise encoding