@xpert-ai/plugin-sdk 3.23.0 → 3.25.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/_object_without_properties_loose.cjs.js +16 -0
- package/_object_without_properties_loose.esm.js +14 -0
- package/analytics-result.cjs.js +212 -0
- package/analytics-result.esm.js +201 -0
- package/analytics.cjs.default.js +1 -0
- package/analytics.cjs.js +17 -0
- package/analytics.cjs.mjs +2 -0
- package/analytics.d.ts +1 -0
- package/analytics.esm.js +2 -0
- package/artifact-document.cjs.default.js +1 -0
- package/artifact-document.cjs.js +581 -0
- package/artifact-document.cjs.mjs +2 -0
- package/artifact-document.d.ts +1 -0
- package/artifact-document.esm.js +563 -0
- package/data-workbench.cjs.js +23 -6
- package/data-workbench.esm.js +23 -6
- package/docs/README.md +8 -0
- package/docs/analytics.md +108 -0
- package/docs/artifact-documents.md +74 -0
- package/docs/artifact-drafts.md +24 -0
- package/docs/artifact-presentations.md +43 -0
- package/docs/json-encoded-schema.md +19 -0
- package/docs/mcp-client.md +63 -0
- package/docs/provider-credential-validation.md +34 -0
- package/docs/rest-client.md +24 -0
- package/docs/workspace-dataset-pipelines.md +120 -0
- package/docs/workspace-file-tools.md +66 -0
- package/index.cjs.js +555 -108
- package/index.esm.js +573 -172
- package/model-provider-toolset.cjs.js +1 -1
- package/model-provider-toolset.esm.js +1 -1
- package/model-provider.cjs.js +47 -1
- package/model-provider.esm.js +41 -2
- package/package.json +14 -2
- package/src/analytics.d.ts +3 -0
- package/src/artifact-document.d.ts +5 -0
- package/src/index.d.ts +2 -0
- package/src/lib/agent/handoff/agent-runtime-message.contract.d.ts +80 -80
- package/src/lib/agent/middleware/capabilities/assistant-task.d.ts +36 -1
- package/src/lib/agent/runtime/dispatch.d.ts +284 -284
- package/src/lib/agent/runtime/index.d.ts +1 -0
- package/src/lib/agent/runtime/pipeline-scope.d.ts +110 -0
- package/src/lib/agent/runtime/types.d.ts +4 -2
- package/src/lib/ai-model/ai-model-provider.interface.d.ts +3 -1
- package/src/lib/ai-model/utils/limits.d.ts +4 -2
- package/src/lib/artifact-document/dependencies.d.ts +101 -0
- package/src/lib/artifact-document/host.d.ts +30 -0
- package/src/lib/artifact-document/protocol.d.ts +60 -0
- package/src/lib/artifact-document/runtime.d.ts +4 -0
- package/src/lib/artifact-document/sha256.d.ts +2 -0
- package/src/lib/artifact-presentation/index.d.ts +35 -0
- package/src/lib/core/index.d.ts +1 -0
- package/src/lib/core/json-encoded-schema.d.ts +15 -0
- package/src/lib/data/analytics/analytics-payload.d.ts +3 -0
- package/src/lib/data/analytics/analytics-provider.d.ts +74 -0
- package/src/lib/data/analytics/analytics-result.d.ts +4 -0
- package/src/lib/data/analytics/analytics.registry.d.ts +10 -0
- package/src/lib/data/analytics/analytics.schema.d.ts +206 -0
- package/src/lib/data/analytics/index.d.ts +5 -0
- package/src/lib/data/datasource/index.d.ts +1 -0
- package/src/lib/data/datasource/types.d.ts +1 -1
- package/src/lib/data/datasource/workbench-adapter.d.ts +11 -1
- package/src/lib/data/datasource/workbench-sql.d.ts +12 -0
- package/src/lib/project-pipeline/adapters.d.ts +87 -0
- package/src/lib/project-pipeline/capability.d.ts +100 -0
- package/src/lib/project-pipeline/index.d.ts +5 -0
- package/src/lib/project-pipeline/projection.d.ts +71 -0
- package/src/lib/project-pipeline/registry.d.ts +509 -0
- package/src/lib/project-pipeline/runtime-registry.d.ts +45 -0
- package/src/lib/project-pipeline/scoped-registry.d.ts +10 -0
- package/src/lib/project-task/index.d.ts +6 -0
- package/src/lib/project-type/index.d.ts +17 -1
- package/src/lib/rag/types.d.ts +1 -1
- package/src/lib/runtime/capabilities/artifact-drafts.d.ts +29 -0
- package/src/lib/runtime/capabilities/artifacts.d.ts +12 -0
- package/src/lib/runtime/capabilities/index.d.ts +3 -0
- package/src/lib/runtime/capabilities/mcp-client-runtime.d.ts +41 -0
- package/src/lib/runtime/capabilities/rest-client-runtime.d.ts +34 -0
- package/src/lib/runtime/capabilities/sandbox-jobs.d.ts +36 -2
- package/src/lib/runtime/index.d.ts +2 -0
- package/src/lib/runtime/mutation-evidence.d.ts +7 -0
- package/src/lib/runtime/workspace-file-tools.d.ts +11 -0
- package/src/lib/sandbox/file-edits.d.ts +4 -0
- package/src/lib/sandbox/protocol.d.ts +7 -1
- package/src/lib/sandbox/runtime-provider.d.ts +4 -0
- package/src/lib/sandbox/sandbox.d.ts +2 -8
- package/src/lib/tool-provider/adapters.d.ts +1 -1
- package/src/lib/tool-provider/types.d.ts +2 -0
package/data-workbench.esm.js
CHANGED
|
@@ -192,11 +192,17 @@ const FORBIDDEN = new Set([
|
|
|
192
192
|
'ATTACH',
|
|
193
193
|
'DETACH'
|
|
194
194
|
]);
|
|
195
|
-
|
|
195
|
+
// Legacy SQL Workbench policy shared by supported database plugins.
|
|
196
|
+
// TODO: separate dialect function policies through plugin-owned strategies; preserve fail-closed checks.
|
|
197
|
+
// Allowlisting permits parsing; the selected database still determines function availability.
|
|
198
|
+
const SAFE_FUNCTIONS = new Set('ABS ACOS ASIN ATAN ATAN2 AVG CAST CEIL CEILING COALESCE CONCAT CONCAT_WS CONVERT COS COUNT CURDATE CURRENT_DATE CURRENT_TIMESTAMP DATE DATE_TRUNC DATE_ADD DATE_SUB DATE_FORMAT DATEDIFF DAY DAYOFMONTH DAYOFWEEK EXTRACT FLOOR FORMAT GREATEST GROUP_CONCAT IF IFNULL JSON_EXTRACT JSON_LENGTH JSON_UNQUOTE LEAST LEFT LENGTH LN LOG LOWER LPAD LTRIM MAX MD5 MIN MOD MONTH NOW NULLIF POWER RAND REPLACE REVERSE RIGHT ROUND ROW_NUMBER RANK DENSE_RANK LAG LEAD FIRST_VALUE LAST_VALUE LPAD RPAD RTRIM SIGN SIN SQRT STDDEV STDDEV_POP STDDEV_SAMP SUBSTR SUBSTRING SUM TAN TO_CHAR TO_DATE TO_TIMESTAMP TRIM TRUNC UPPER VAR_POP VAR_SAMP VERSION WEEK YEAR DATABASE CURRENT_DATABASE CURRENT_SCHEMA ARRAY_AGG STRING_AGG JSON_AGG JSON_BUILD_OBJECT PG_GET_VIEWDEF'.split(' '));
|
|
196
199
|
// FROM/JOIN can introduce a parenthesized subquery, not a function call.
|
|
197
200
|
const SQL_PARENS = new Set('IN AS EXISTS OVER PARTITION VALUES SELECT WITH FROM JOIN AND OR NOT ON USING FILTER GROUPING ROLLUP CUBE DISTINCT EXPLAIN'.split(' '));
|
|
198
201
|
const UNSAFE_FUNCTIONS = /\b(pg_sleep|sleep|benchmark|dblink\w*|lo_\w+|pg_(?:read|write|ls|stat|terminate|cancel|reload|rotate|log|create|drop|promote|switch|backup|replication|advisory)\w*|get_lock|release_lock|load_file|nextval|setval|set_config|http\w*|s3|hdfs|jdbc|mysql|postgresql|file|url)\s*\(/i;
|
|
199
|
-
|
|
202
|
+
/**
|
|
203
|
+
* @deprecated Mixed-dialect Workbench policy. New adapters should own dialect-aware statement
|
|
204
|
+
* validation. Existing callers must retain this guard until an equivalent replacement is in place.
|
|
205
|
+
*/ function splitWorkbenchSql(source) {
|
|
200
206
|
const { masked, tokens } = lexWorkbenchSql(source);
|
|
201
207
|
const statements = [];
|
|
202
208
|
let start = 0;
|
|
@@ -236,12 +242,18 @@ function splitWorkbenchSql(source) {
|
|
|
236
242
|
if (!statements.length || statements.length > 50) throw new Error('statement_count_exceeded');
|
|
237
243
|
return statements;
|
|
238
244
|
}
|
|
239
|
-
|
|
245
|
+
/**
|
|
246
|
+
* @deprecated Uses the legacy mixed-dialect policy. New adapters should enforce read-only execution
|
|
247
|
+
* with dialect-aware validation and database permissions. Keep this guard until safely migrated.
|
|
248
|
+
*/ function requireReadStatement(sql) {
|
|
240
249
|
const statements = splitWorkbenchSql(sql);
|
|
241
250
|
if (statements.length !== 1 || statements[0].effect !== 'read') throw new Error('read_only_violation');
|
|
242
251
|
return statements[0].sql;
|
|
243
252
|
}
|
|
244
|
-
|
|
253
|
+
/**
|
|
254
|
+
* @deprecated Built-in engine switch. New adapters should own dialect-specific identifier quoting
|
|
255
|
+
* while preserving identifier validation and escaping.
|
|
256
|
+
*/ function quoteDatabaseIdentifier(name, engine) {
|
|
245
257
|
// eslint-disable-next-line no-control-regex -- intentional: reject control characters in identifiers
|
|
246
258
|
if (!name || name.length > 256 || /[\0-\x1f]/.test(name)) throw new Error('invalid_identifier');
|
|
247
259
|
const quote = engine === 'postgres' ? '"' : '`';
|
|
@@ -298,7 +310,11 @@ function quoteDatabaseIdentifier(name, engine) {
|
|
|
298
310
|
const number = (value)=>Number(value != null ? value : 0);
|
|
299
311
|
const string = (value)=>value == null ? '' : String(value);
|
|
300
312
|
const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.name.toLowerCase() === name.toLowerCase())];
|
|
301
|
-
/**
|
|
313
|
+
/**
|
|
314
|
+
* One adapter per physical connection. A host session must not share it across users.
|
|
315
|
+
* @deprecated Legacy SDK-owned SQL dialects. New plugins should implement DatabaseWorkbenchAdapter
|
|
316
|
+
* with plugin-owned dialect behavior. Retained for compatibility with existing plugins.
|
|
317
|
+
*/ class SqlDatabaseWorkbenchAdapter {
|
|
302
318
|
quote(name) {
|
|
303
319
|
return quoteDatabaseIdentifier(name, this.engine);
|
|
304
320
|
}
|
|
@@ -399,7 +415,7 @@ const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.
|
|
|
399
415
|
var _object_schema, _ref, _object_database, _ref1;
|
|
400
416
|
const namespace = this.engine === 'postgres' ? (_ref = (_object_schema = object.schema) != null ? _object_schema : this.initial.schema) != null ? _ref : 'public' : (_ref1 = (_object_database = object.database) != null ? _object_database : this.initial.database) != null ? _ref1 : '';
|
|
401
417
|
const p = (i)=>this.engine === 'postgres' ? `$${i}` : '?';
|
|
402
|
-
const metadata = await this.raw(this.engine === 'postgres' ? `SELECT a.attname AS column_name, pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable, a.attnum AS ordinal_position, pg_get_expr(d.adbin,d.adrelid) AS column_default FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE n.nspname=$1 AND c.relname=$2 AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum LIMIT 1000` : `SELECT column_name, column_type AS data_type, is_nullable, ordinal_position, column_default FROM information_schema.columns WHERE table_schema = ${p(1)} AND table_name = ${p(2)} ORDER BY ordinal_position LIMIT 1000`, [
|
|
418
|
+
const metadata = await this.raw(this.engine === 'postgres' ? `SELECT a.attname AS column_name, pg_catalog.format_type(a.atttypid,a.atttypmod) AS data_type, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable, a.attnum AS ordinal_position, pg_get_expr(d.adbin,d.adrelid) AS column_default, pg_catalog.col_description(c.oid,a.attnum) AS column_comment FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE n.nspname=$1 AND c.relname=$2 AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum LIMIT 1000` : `SELECT column_name, column_type AS data_type, is_nullable, ordinal_position, column_default, column_comment FROM information_schema.columns WHERE table_schema = ${p(1)} AND table_name = ${p(2)} ORDER BY ordinal_position LIMIT 1000`, [
|
|
403
419
|
namespace,
|
|
404
420
|
object.name
|
|
405
421
|
]);
|
|
@@ -409,6 +425,7 @@ const cell = (result, row, name)=>row[result.columns.findIndex((column)=>column.
|
|
|
409
425
|
dataType: string(cell(metadata, row, 'data_type')),
|
|
410
426
|
nullable: string(cell(metadata, row, 'is_nullable')) === 'YES',
|
|
411
427
|
ordinal: number(cell(metadata, row, 'ordinal_position')),
|
|
428
|
+
comment: string(cell(metadata, row, 'column_comment')) || undefined,
|
|
412
429
|
defaultValue: cell(metadata, row, 'column_default') == null ? null : string(cell(metadata, row, 'column_default'))
|
|
413
430
|
}));
|
|
414
431
|
if (!columns.length) throw new Error('object_not_found_or_denied');
|
package/docs/README.md
CHANGED
|
@@ -69,6 +69,14 @@ export class OrderOperationsTools {
|
|
|
69
69
|
|
|
70
70
|
MCP exposure is explicit. Provide strict Zod input/output schemas and return an allowlisted DTO; the host validates the output and maps it to `structuredContent` and a JSON `TextContent` block so clients that only expose text can still read the result. With `resultFormat: 'tool_result'`, image and other content blocks are preserved and the validated structured metadata also receives a JSON text fallback. Invocation context is constructed for every call and must never be cached on the Provider singleton. `getMiddlewareExtensions()` may add Agent-only hooks such as `wrapToolCall`, but business-critical behavior belongs in the method or shared service.
|
|
71
71
|
|
|
72
|
+
For connection configuration, declare the form in `configSchema` and optionally implement
|
|
73
|
+
`validateConfig(config: unknown): void | Promise<void>` on the Provider. The native Toolset
|
|
74
|
+
adapter awaits this hook when a host configuration-save path invokes `validateConfig`,
|
|
75
|
+
including MCP service configuration tabs. Reuse invocation validation rules and reject
|
|
76
|
+
invalid values with a sanitized error; never include credentials in the error message.
|
|
77
|
+
The hook validates values only: it does not persist or normalize them, and does not replace
|
|
78
|
+
per-invocation authorization. Providers without the hook retain their existing behavior.
|
|
79
|
+
|
|
72
80
|
Use the same `@XpertToolProvider` class for every capability:
|
|
73
81
|
|
|
74
82
|
| Decorator | Method signature | Result |
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Read-only analytics capability
|
|
2
|
+
|
|
3
|
+
`platform.datasource.analytics` separates source query syntax from chart binding. It is additive; it does not replace database Workbench, Semantic Models or Artifacts.
|
|
4
|
+
|
|
5
|
+
| Layer | Responsibility |
|
|
6
|
+
| ------------------- | -------------------------------------------------------------------------- |
|
|
7
|
+
| contracts | Versioned Binding, Dataset, fields, parameters, completeness and freshness |
|
|
8
|
+
| plugin-sdk | Provider registration, runtime capability, validation and normalization |
|
|
9
|
+
| Platform DataSource | Actor authorization, scoped lookup, deadlines, limits and dispatch |
|
|
10
|
+
| Source plugin | Native syntax, connection schema, typed parameters and result projection |
|
|
11
|
+
| Dashboard plugin | Definition, controls, chart mapping, renderer integration and persistence |
|
|
12
|
+
|
|
13
|
+
The platform and renderer do not interpret SQL, MDX, REST paths or ontology Actions. Only the provider interprets `binding.payload`. Views reference `output.datasetId` and stable `output.fields[].id`; `sourceField` or an exact `semanticRef` selects native columns.
|
|
14
|
+
|
|
15
|
+
## Provider contract
|
|
16
|
+
|
|
17
|
+
Implement `AnalyticsQueryProvider`, decorate with `@AnalyticsProvider('vendor.operation')`, and include the provider in the plugin module. Declare supported source types and operation contract versions. Optional `descriptor.connectionType` contributes a non-SQL connection schema through DataSourceType sync.
|
|
18
|
+
|
|
19
|
+
`execute(binding, parameters, context)` receives typed scalar parameters and authenticated source context. Connection options stay on the server. Honor `signal`, `maxRows`, `timeoutMs` and the absolute `deadlineAt`; return explicit columns even for zero rows. Providers must enforce read-only operations at the source, not merely advertise them.
|
|
20
|
+
|
|
21
|
+
Use the root SDK entry on the server. Browser code uses `@xpert-ai/plugin-sdk/analytics`, which contains schemas/normalization without Nest runtime imports.
|
|
22
|
+
|
|
23
|
+
## Business metadata discovery
|
|
24
|
+
|
|
25
|
+
Optional `provider.discover(request, context)` returns a versioned `AnalyticsDiscoveryResult`: bounded `items`, opaque `inspectRequest` / `nextRequest`, and a native `queryContract` with operation/version/payloadSchema/instructions. A provider owns navigation syntax and business metadata; the platform validates the envelope and reuses query authorization, source revision checks and deadlines.
|
|
26
|
+
|
|
27
|
+
`POST /api/data-source/analytics/discover` accepts `{ dataSourceId, providerId, request }`. Catalogs and inspect results must include authored descriptions, declared types and metric definitions when available. Missing metadata is not permission to infer business semantics from labels. Results have a 128 KB/50 item limit; pagination is provider-owned. Discovery does not grant execution permission or certify a metric.
|
|
28
|
+
|
|
29
|
+
PostgreSQL discovery uses the platform Workbench adapter's comments, types and keys. data-xpert discovery uses Assistant resource bindings, current actor policies, published entity analysis contracts and permitted Action input schemas. These implementations stay in their source plugins.
|
|
30
|
+
|
|
31
|
+
## Existing MCP connections
|
|
32
|
+
|
|
33
|
+
The generic [MCP Client Runtime](./mcp-client.md) exposes
|
|
34
|
+
`McpClientRuntimeCapability` (`platform.mcp.client`). Analytics plugins use
|
|
35
|
+
`client.tools.list(scope)` and `client.tools.call(scope, { toolName, contractHash, arguments })`.
|
|
36
|
+
The initial tools API enforces read-only selection and current-viewer authorization on the host.
|
|
37
|
+
|
|
38
|
+
`@xpert-ai/plugin-analytics-mcp` implements the `mcp.tool` provider. Its dataset catalog,
|
|
39
|
+
parameter paths, JSON projection and completeness rules remain plugin-owned; it does not add
|
|
40
|
+
MCP branches to Dataset normalization or the dashboard renderer. Build and deploy the matching
|
|
41
|
+
SDK/host capability before using the plugin; an older published SDK is insufficient.
|
|
42
|
+
|
|
43
|
+
## Existing REST/OpenAPI connections
|
|
44
|
+
|
|
45
|
+
The generic [REST Client Runtime](./rest-client.md) exposes
|
|
46
|
+
`RestClientRuntimeCapability` (`platform.rest.client`) with `operations.list/call`.
|
|
47
|
+
It reuses saved OpenAPI toolsets, credentials and current-viewer workspace permissions.
|
|
48
|
+
`@xpert-ai/plugin-analytics-rest` supplies the `rest.json` provider with an approved
|
|
49
|
+
dataset catalog, typed JSON projection and bounded offset/cursor pagination. Binding
|
|
50
|
+
payloads cannot supply URLs, headers, credentials or result mappings. Incomplete page
|
|
51
|
+
traversal stays explicitly partial. Deploy the matching SDK and host before installation.
|
|
52
|
+
|
|
53
|
+
## Execution
|
|
54
|
+
|
|
55
|
+
- `GET /api/data-source/analytics/sources`: authorized IDs and supported providers, never credentials.
|
|
56
|
+
- `POST /api/data-source/analytics/query`: `{ binding, controls }`; body cannot set actor/tenant/organization.
|
|
57
|
+
- Requires `DATA_SOURCE_VIEW`; capability callers must match the current host request actor.
|
|
58
|
+
- 30-second deadline, 1,000 rows and 2 MB normalized result budget per query.
|
|
59
|
+
- Known result/parameter validation failures return safe error codes so Agents can repair their bindings; arbitrary provider exception text is never surfaced.
|
|
60
|
+
- After execution, source revision and provider registration are checked again. Missing/ambiguous columns, invalid cells, duplicate grain and inconsistent completeness fail closed.
|
|
61
|
+
- No shared result cache. `sourceFetchedAt` means source query time, not last business-data change; `dataAsOf` is optional and source-owned.
|
|
62
|
+
- `int64` and `decimal` use exact strings. Timestamps include a timezone. Renderers must reject unsupported precision rather than silently round canonical data.
|
|
63
|
+
|
|
64
|
+
For composed queries, the platform assigns `executionId` before provider execution. Forward `signal`, `deadlineAt` and `ancestry` through the optional third argument of `AnalyticsRuntimeApi.query`. These are trusted execution constraints, not fields accepted from an HTTP body or Binding payload. Child queries cannot extend the parent deadline; the platform checks provider cycles and nesting depth.
|
|
65
|
+
|
|
66
|
+
## Authorization and revocation
|
|
67
|
+
|
|
68
|
+
HTTP and WebSocket JWT validation loads current database role permissions, including for third-party identities. Explicit token permission claims narrow those grants; they cannot recreate deleted or disabled permissions. An empty claim grants no permissions; missing or null claims retain the current database grants for older tokens. Permissions newly granted outside an explicit token ceiling require a refreshed token.
|
|
69
|
+
|
|
70
|
+
Permission guards reuse role permissions freshly loaded by authentication for the current request, including token restrictions, without issuing a duplicate policy query. Enabled grants must match the current tenant and role. A loaded empty list denies access and never triggers a broader database lookup. When authentication has not loaded the permission relation, the guard queries current tenant/role policy without a cross-request decision cache. Authentication must reload permissions on each request, so revocation applies to subsequent requests without waiting for token expiry. This is a request-time authorization snapshot, not cancellation of operations already authorized and running; capability and resource access checks remain necessary during execution.
|
|
71
|
+
|
|
72
|
+
## Reusable Artifacts changes
|
|
73
|
+
|
|
74
|
+
`listArtifacts.resourceIdPrefix` matches a literal resource ID prefix, never a pattern, within the caller's existing access scope. Storage-specific matching stays inside the platform Artifacts service.
|
|
75
|
+
|
|
76
|
+
`listArtifacts.includeCurrentVersion` optionally includes each result's active current-version metadata (for example its latest title). The platform loads pointers for the authorized, paginated result in one scoped batch; it does not expand access or load document content. Plugins should use this metadata instead of maintaining a separate copy of versioned titles.
|
|
77
|
+
`ensureArtifactVersion.expectedCurrentVersionId` enables compare-and-set inside the existing Artifact row lock; null means no current version. An idempotent retry may reuse the current version but cannot resurrect an old save over a newer one. Callers that omit it retain existing behavior.
|
|
78
|
+
|
|
79
|
+
No dashboard table, renderer schema or data-xpert dependency is added to the platform.
|
|
80
|
+
|
|
81
|
+
## Presentation is independent of providers
|
|
82
|
+
|
|
83
|
+
Bindings specify data access and the output contract, not page layout. The Live Dashboard plugin supports two consumers of the same Dataset:
|
|
84
|
+
|
|
85
|
+
- Standard mode uses Bindings, Controls and chart/table definitions with the Data Analytics renderer.
|
|
86
|
+
- HTML mode saves Bindings, Controls and HTML/JavaScript together. The page selects a `bindingId` and passes declared control values; it renders the returned Dataset fields itself.
|
|
87
|
+
|
|
88
|
+
The generic [isolated HTML document host](artifact-documents.md) provides the iframe and message protocol. The dashboard plugin owns version lookup and its query callback; the backend resolves the saved Binding and reauthorizes the current actor. Pages cannot supply replacement providers, data sources or native query payloads. Source providers do not implement page rendering or depend on a dashboard plugin.
|
|
89
|
+
|
|
90
|
+
## Workspace script provider
|
|
91
|
+
|
|
92
|
+
[Workspace live script queries](workspace-dataset-pipelines.md) documents the implemented `@xpert-ai/plugin-analytics-workspace-script` example. Its Python/JavaScript entrypoints, file/source aliases, CSV helpers and execution evidence belong to the plugin. The platform supplies the reusable Analytics, Workspace Files, Artifacts and Sandbox Jobs capabilities, including execution-time invocation and parent deadline/cancellation propagation.
|
|
93
|
+
|
|
94
|
+
Each query executes the script against current authorized inputs and returns the same Dataset contract to either presentation mode. Script or dependency reuse must not turn a dashboard refresh into reuse of a previous result. Deployment requires compatible SDK/contracts exports, a compute runtime artifact and a matching Runtime Binding; local source validation does not establish published-package compatibility.
|
|
95
|
+
|
|
96
|
+
## Declarative Workspace files
|
|
97
|
+
|
|
98
|
+
The `file.table` provider in `@xpert-ai/plugin-analytics-files` registers the `workspace-files` source type. Its administrator-owned catalog specifies authorized Workspace file references, explicit CSV/JSON/XLSX readers, field types and business descriptions. Provider discovery returns its native query schema and real bounded previews. Queries select/filter/group/aggregate/sort; neither Binding payloads nor controls may replace file references or reader options.
|
|
99
|
+
|
|
100
|
+
The plugin reuses `WorkspaceFilesRuntimeCapability` for file access and `ProjectAccessRuntimeCapability` for human Project membership. Assistant files retain the exact published Assistant ACL, and private file references bind the current viewer. Parsing, format dependencies, decimal aggregation and Worker execution remain plugin-owned. No parser or file-query dialect is added to the platform.
|
|
101
|
+
|
|
102
|
+
Each execution rereads the current source and records a content digest. Input limits fail closed before partial-input aggregation; output limits preserve Dataset completeness. Artifact history pins declarations, not file bytes. See the plugin's bilingual configuration and verification documentation for formula-cache, type and format limits.
|
|
103
|
+
|
|
104
|
+
## Discovered payload feedback for Agent tools
|
|
105
|
+
|
|
106
|
+
`validateAnalyticsPayload(payload, queryContract.payloadSchema)`, exported from `@xpert-ai/plugin-sdk`, is a synchronous server SDK helper for structural feedback before a preview call. It uses the provider's declared JSON Schema and reports a bounded field path and failing keyword without echoing payload values. It does not coerce values, remove properties, inject defaults, resolve remote references or validate JSON Schema `format` annotations. Malformed/unresolved schemas and asynchronous (`$async`) schemas fail explicitly. Provider semantic validation, current-actor authorization and bounded execution remain mandatory after this check. A successful structural check is not a preview receipt or permission grant.
|
|
107
|
+
|
|
108
|
+
Live Dashboard uses this helper on both canonical and simplified preview tools. Keep provider-specific syntax in discovery; do not introduce SQL/file/MCP branches in the dashboard middleware to repair input.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# 隔离 HTML 文档宿主
|
|
2
|
+
|
|
3
|
+
`@xpert-ai/plugin-sdk/artifact-document` 是浏览器安全的 SDK 子入口,不依赖 Nest、具体数据源或图表库。
|
|
4
|
+
|
|
5
|
+
## 所有权
|
|
6
|
+
|
|
7
|
+
- 平台 SDK 提供 `mountArtifactDocument`、严格的查询消息协议、隔离 iframe、CSP 和页面 SDK。
|
|
8
|
+
- 插件提供文档生命周期、Binding 白名单和 `query` 回调。回调必须调用服务端,以当前用户重新授权,并从已保存版本中读取 Binding。
|
|
9
|
+
- 文档只能调用 `window.xpertLiveArtifact`,不能调用宿主通用 View Actions,也不能选择 Artifact 版本、Provider 或提交查询定义。
|
|
10
|
+
- 文档内容由 Artifacts 保存;平台宿主不规定数据库、插件页面结构、业务模型和图表类型。
|
|
11
|
+
|
|
12
|
+
## 宿主
|
|
13
|
+
|
|
14
|
+
在专用文档宿主页调用 `installArtifactDocumentFramePolicy(document)`,再挂载 iframe;未安装时 mount 会拒绝挂载。该策略作用于整个宿主页,禁止子框架的 URL 导航;允许 `srcdoc`。不要装到需要加载其他远程 iframe 的应用根文档。
|
|
15
|
+
|
|
16
|
+
`mountArtifactDocument(frame, { html, dependencies, context, query, onBusy, onResult, onError })` 返回 `refresh()` 和 `dispose()`。上下文只含 Binding ID(最多 64 个)、默认控件值(最多 24 个)、语言及主题;它在挂载时严格校验并复制,后续修改原对象不会扩大允许的 Binding 集合。Artifact ID、版本和身份由可信回调闭包持有,不交给文档选择。
|
|
17
|
+
|
|
18
|
+
## 固定前端依赖
|
|
19
|
+
|
|
20
|
+
可选的 `dependencies` 接受 `ArtifactDocumentDependencyAsset[]`:每项包含 `id`、精确 `version`、
|
|
21
|
+
`format: 'classic-script'`、导出的 `global`、UTF-8 源码的 `sha256` 和 `source`。
|
|
22
|
+
对应的 `ArtifactDocumentDependencyLock` 不包含源码,适合返回给 Agent 和保存在页面定义中。
|
|
23
|
+
插件负责允许哪些库、构建 bundle 及其许可证;平台不导入 ECharts、Three.js 或任何业务图表库。
|
|
24
|
+
|
|
25
|
+
`verifyArtifactDocumentDependencies(assets, locks)` 校验完整性、完整且有序的依赖集合、唯一 ID/global,
|
|
26
|
+
拒绝 URL 字段、保留的 SDK 全局名称、单包超过 4 MB 或合计超过 8 MB 的代码。
|
|
27
|
+
最多允许 8 项。摘要只证明完整性,不是权限判断:调用方必须从可信包或授权 Artifact 快照解析资产,
|
|
28
|
+
不能根据页面传来的名称、URL 或源码任意下载和执行。
|
|
29
|
+
|
|
30
|
+
摘要校验使用 SDK 内部无第三方依赖的同步 SHA-256(FIPS 180-4),不要求 Web Crypto、
|
|
31
|
+
Node 内置模块或安全上下文,因此浏览器 HTTPS、普通 HTTP 内网、隔离文档与 Node 均使用同一实现。
|
|
32
|
+
该实现仅用于有大小限制的公开依赖源码校验,不作为密码、密钥或签名 API 对外导出。
|
|
33
|
+
|
|
34
|
+
宿主在 CSP 和页面 SDK 之后、作者 HTML 之前同步注入依赖。
|
|
35
|
+
通过 `script.textContent` 安装精确源码,避免字符串中的结束标签改变 HTML 结构;无需 `eval`。
|
|
36
|
+
依赖运行在同一个隔离文档内,不能因此访问宿主 DOM、凭据或通用 Action。
|
|
37
|
+
部署端预检应使用同一 SDK 与相同资产,不能使用 CDN 或另一个版本替代。
|
|
38
|
+
|
|
39
|
+
为了在插件升级后重开历史版本,插件应将依赖实际代码与定义一起纳入不可变 Artifact Version,
|
|
40
|
+
由该版本的内容摘要覆盖。只存版本号或 hash、再从当前插件目录寻找代码,不能保证历史可用性。
|
|
41
|
+
读取时验证版本内容摘要及每项依赖锁;修改页面默认继承原快照,升级依赖必须显式生成新版本。
|
|
42
|
+
|
|
43
|
+
SDK 使用独立 MessageChannel,只接受当前 iframe、当前挂载随机标识的一次初始化请求;旧文档的延迟消息不能初始化新挂载。每条查询严格解析、检查 Binding 白名单、拒绝当前一分钟窗口内的重放,执行中的请求 ID 跨窗口继续受保护,最多 8 个并发、每分钟 60 次。关闭宿主后丢弃返回结果并清理 busy 状态;实际服务端取消/期限由查询能力负责。
|
|
44
|
+
|
|
45
|
+
## 文档 SDK
|
|
46
|
+
|
|
47
|
+
```javascript
|
|
48
|
+
const live = window.xpertLiveArtifact
|
|
49
|
+
live.bindSelect(document.querySelector('select'), {
|
|
50
|
+
bindingId: 'sales',
|
|
51
|
+
controlId: 'region',
|
|
52
|
+
fieldId: 'region',
|
|
53
|
+
allLabel: '全部区域'
|
|
54
|
+
})
|
|
55
|
+
live.subscribe('sales', (dataset) => render(dataset))
|
|
56
|
+
await live.ready()
|
|
57
|
+
await live.query('sales', { region: null })
|
|
58
|
+
// 筛选值是声明的 controlId;刷新沿用此 Binding 最近一次请求的控件值。
|
|
59
|
+
await live.refresh('sales')
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
订阅会接收普通查询和宿主刷新结果。同一 Binding 的旧响应不会覆盖新响应。页面自行处理 loading/error/empty 和数据完整性;可信宿主独立显示新鲜度、部分结果及错误状态。
|
|
63
|
+
|
|
64
|
+
`bindSelect` 是可选的通用 Dataset 控件适配器:从已收到的数据行收集唯一值、保留筛选前的候选值、维持选择并发起查询。option.value 使用 JSON 编码以保留标量类型,页面不应再添加第二个 change handler。`allValue` 默认 null,可显式指定声明的全选值。它不会额外查询隐藏数据,也不会把候选列表当作授权;字段和参数访问始终由后端校验。查询失败触发冒泡的 `xpert-query-error` 事件。其他控件可直接使用 query。
|
|
65
|
+
|
|
66
|
+
## 隔离边界
|
|
67
|
+
|
|
68
|
+
HTML 在 `sandbox="allow-scripts"` 内执行,无同源权限、表单、弹窗和下载授权。内容前缀首先安装 CSP,允许内联 JS/CSS 和 data/blob 图片,拒绝网络请求、外部脚本、外部字体、子 iframe、worker、eval、对象和表单。宿主页额外的 frame-src 策略拒绝文档自身导航。
|
|
69
|
+
|
|
70
|
+
HTML 格式验证不是 sanitizer,也不证明业务正确性。Agent 代码仍可画出错误图形或阻塞自己的文档;业务口径、数值与实际页面都需要验收。该能力不提供后端写操作、任意网络代理或自动推送。
|
|
71
|
+
|
|
72
|
+
## 验证
|
|
73
|
+
|
|
74
|
+
运行定向 `protocol.spec.ts`。从平台根目录执行 `node packages/plugin-sdk/tests/artifact-document-browser.cjs` 可使用真实 Chromium 验证消息边界、筛选刷新、并发响应、CSP、父 DOM/Web Storage 隔离、自身导航、旧握手拒绝、并发/频率限制和销毁后的响应丢弃。网络验证使用实际监听的本机 HTTP 服务,不能仅根据浏览器 request 事件判断是否发生外部通信。
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Artifact working drafts
|
|
2
|
+
|
|
3
|
+
`ArtifactDraftsRuntimeCapability` (`platform.artifact-drafts`) is a generic platform API for mutable working copies. It has no dashboard, SQL, chart, or Agent tool semantics. Workspace Files stores the bytes; `artifact_draft` stores a content pointer, checksum and monotonically increasing revision.
|
|
4
|
+
|
|
5
|
+
- `list(artifactIds)` reads up to 100 authorized draft records in one batch for selectors and lists.
|
|
6
|
+
- `get(artifactId)` returns the authorized owner's current working copy.
|
|
7
|
+
- `save({artifactId, expectedRevision, expectedCurrentVersionId, ...content})` verifies the Workspace file and saves a revision. Use revision `0` when no draft exists. It never creates a formal Artifact version.
|
|
8
|
+
- `publish({artifactId, expectedRevision, expectedCurrentVersionId})` is a trusted application action after human confirmation. Do not expose it as an Agent tool. It publishes the exact reviewed draft as an immutable Artifact version and records the confirming actor and revision in version metadata.
|
|
9
|
+
|
|
10
|
+
Both mutations lock the Artifact row, sharing the same lock as ordinary version writes. Publication checks the draft revision and its base version, inserts the snapshot, advances the formal current version, and marks the draft published in one transaction. An identical publication retry returns the same version; stale writes or publication against a different current version fail. Publishing never silently rebases a draft.
|
|
11
|
+
|
|
12
|
+
Draft access is owner scoped and requires an active Artifact. Saving a draft leaves the formal current-version pointer and title unchanged; draft-aware selectors read the working title from the draft. Confirmed publication updates the formal title and version pointer atomically. Published versions and share links retain their existing behavior; links never expose unpublished drafts. File checksums, MIME policy and canonical Workspace authorization apply to drafts. Dependency snapshots can be part of the application-owned content package and therefore remain pinned in both drafts and published versions.
|
|
13
|
+
|
|
14
|
+
Installations with external schema management must apply `packages/server-ai/src/artifacts/drafts/migrations/20261017-artifact-drafts.sql`. Existing Artifacts require no backfill: the first edit starts at revision 0 against the current formal version. There is one current working copy per Artifact; immutable formal version history is retained. Intermediate draft revisions are concurrency markers, not a browsable version-history feature.
|
|
15
|
+
|
|
16
|
+
## Verification
|
|
17
|
+
|
|
18
|
+
Set `ARTIFACT_DRAFTS_TEST_DATABASE_URL` to a dedicated PostgreSQL database whose name starts with `xpert_artifact_drafts_test_`, then run `corepack pnpm exec jest --config packages/server-ai/jest.config.ts --runInBand --runTestsByPath packages/server-ai/src/artifacts/drafts/artifact-drafts.integration.spec.ts`. The suite creates and drops its own schema and temporary files, runs the SQL migration twice, and uses real platform authorization, file reads, row locks and transactions. Without the variable, this database suite is skipped. Existing Artifact share-session regression tests additionally require a test-only `JWT_SECRET` when run outside a configured local environment.
|
|
19
|
+
|
|
20
|
+
## Agent completion evidence
|
|
21
|
+
|
|
22
|
+
`createMutationEvidence<T>()` tracks pending writes and successful domain receipts within a run. Adapters decide which tools begin mutations and which exact receipts prove a commit. A late receipt cannot clear a newer pending write. Use this to require further tool calls while a write is pending and to fail truthfully when the tool budget is exhausted. A Workspace file-write acknowledgement is not a domain save receipt.
|
|
23
|
+
|
|
24
|
+
The Live Dashboard plugin owns its schema, preflight, Binding queries, tool policy, preview UI and publication confirmation. After editing the Workspace copy, the Agent must call the dashboard create/update tool to validate and save it. Middleware tracks pending edits and requires a matching domain save receipt before reporting completion; writing a file alone never saves a dashboard. The Workbench pins query requests to the saved draft revision or immutable formal version; neither target accepts browser-supplied bindings or native queries.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Authenticated Artifact presentations
|
|
3
|
+
description: Plugin renderers for immutable shared Artifact versions
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Artifact presentations separate authenticated display from owner-only management. The platform owns link policy, version resolution, plugin registration, request context and the isolated browser host. Providers own content schemas and rendering. No new Artifact kind or share table is needed.
|
|
7
|
+
|
|
8
|
+
## Provider contract
|
|
9
|
+
|
|
10
|
+
Register a Nest provider with `@ArtifactPresentationProvider({pluginName, resourceType})`, implement `IArtifactPresentationProvider`, and include it in the plugin module. Registry discovery uses the explicit source pair and plugin provenance in the authorized organization.
|
|
11
|
+
|
|
12
|
+
- `getEntry()` returns `{html}` with its packaged frontend assets.
|
|
13
|
+
- `read(context)` returns the provider's initial JSON data.
|
|
14
|
+
- `operations` declares the read-only operation names available to the page.
|
|
15
|
+
- `query(context, request)` validates application input and executes those operations as `context.actor`.
|
|
16
|
+
|
|
17
|
+
The context contains the current viewer, authorized Artifact metadata, the exact formal version and its bytes. It does not grant access to the creator's Workspace or other sources. Never replace the viewer with the Artifact owner. Validate the application's content package, identity, limits and integrity before use. Keep draft, save and publish operations out of this interface.
|
|
18
|
+
|
|
19
|
+
## Platform transport
|
|
20
|
+
|
|
21
|
+
`ArtifactLinkRecord.presentationUrl` points to `/artifacts/view/:slug`. It is derived by the platform from its configured public URL. Use it directly rather than constructing plugin-specific URLs. The page requires normal authenticated login and preserves the return URL.
|
|
22
|
+
|
|
23
|
+
`GET /api/artifacts/shared-links/:slug/presentation` returns schema version 1, `target: {artifactId, versionId}`, published title/version number, `readOnly: true`, entry HTML, data and allowed operations. `POST` to the same path plus `/query` takes `{target, operation, input}`. These are authenticated management-session APIs, not ChatKit client-secret endpoints or anonymous content URLs.
|
|
24
|
+
|
|
25
|
+
Every read/query resolves current link status, membership and its formal target. Queries reject target changes before dispatch. Access and target are rechecked before returning results, so in-flight revocation or publication cannot release stale results. Follow-latest links require reopening after publication; fixed links remain on their selected formal version. Source authorization remains the provider's existing governed capability boundary.
|
|
26
|
+
|
|
27
|
+
To open `presentationUrl` from an authoring Workbench iframe, declare the `artifact.presentation.open` client command in its View manifest and invoke it with `{url: presentationUrl}` (`ArtifactPresentationOpenRequest`). The platform opens a separate window with no opener, accepts only its own `/artifacts/view/:slug` URL, and reports blocked popups as a failed result. The new page performs normal authentication and authorization. A raw `target="_blank"` link inherits the remote iframe's sandbox and can prevent the login application from starting. Keep the iframe sandbox unchanged. The standalone read-only presentation does not expose this command. Browser bundles can use a type-only contracts import and the command string to avoid pulling server-oriented runtime exports into their CSP-restricted entry.
|
|
28
|
+
|
|
29
|
+
The Cloud application opts in through `provideArtifactPresentationCommands()` in its root providers. Registration and cleanup belong to the Artifact feature; `ViewClientCommandRegistry` only stores and dispatches commands and has no dependency on Artifact presentation code.
|
|
30
|
+
|
|
31
|
+
## Browser protocol
|
|
32
|
+
|
|
33
|
+
The generic component hosts the entry in an opaque `sandbox="allow-scripts"` iframe with no-network CSP. It accepts remote-component protocol v1 `ready`, `requestData` and `executeAction` messages only. The host validates the exact source window and instance ID, and relays only declared read operations with the server-resolved target. It exposes no file, navigation, client-command or authoring channels and never sends credentials to the iframe. Theme and locale changes resend `init` for the same instance; providers must handle it without resetting the selected resource or reloading unchanged data. Changing the share route cancels in-flight requests and creates a new instance.
|
|
34
|
+
|
|
35
|
+
Bundle assets into the entry or immutable application package. External scripts, network fetches, forms, frames to network URLs and direct parent access are unavailable. Reuse Artifact document dependency snapshots for version-pinned HTML libraries.
|
|
36
|
+
|
|
37
|
+
The Live Dashboard plugin is a reference implementation: it reuses one React bundle in authoring/read-only modes, routes only `query` / `query-binding`, and resolves each Binding from the authorized immutable package. Its source capability still receives the current viewer.
|
|
38
|
+
|
|
39
|
+
## Source collaboration restrictions
|
|
40
|
+
|
|
41
|
+
`AnalyticsProviderDescriptor.sharing` optionally declares `viewer_permissions` or `owner_only`, with a stable diagnostic `reasonCode`. This is a compatibility restriction, never an authorization grant. Omission retains ordinary per-viewer source checks. Providers with private transitive dependencies should declare `owner_only` until those dependencies support explicit collaborative authorization.
|
|
42
|
+
|
|
43
|
+
No database migration is needed. Deploy platform contracts, SDK, backend and Cloud support together before loading plugins using this registry. Older hosts cannot provide the standalone page merely by upgrading the plugin.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# JSON-encoded schema inputs
|
|
2
|
+
|
|
3
|
+
Use `jsonEncodedSchema` at an input boundary that explicitly accepts either a native value or that value encoded once as JSON text. It uses `zod/v3` and preserves the supplied schema's validation and output type.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { jsonEncodedSchema } from '@xpert-ai/plugin-sdk'
|
|
7
|
+
import { z } from 'zod/v3'
|
|
8
|
+
|
|
9
|
+
const files = jsonEncodedSchema(z.array(z.object({ path: z.string().min(1).max(300) }).strict()).max(10), {
|
|
10
|
+
maxChars: 64_000
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
files.parse([{ path: 'data/orders.csv' }])
|
|
14
|
+
files.parse('[{"path":"data/orders.csv"}]')
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The helper decodes at most once. Malformed or oversized text is passed unchanged to the original schema, so use it with schemas whose native input excludes strings. Object fields, array limits, refinements, defaults and transforms continue to belong to that schema. Strings nested inside objects or arrays remain unchanged.
|
|
18
|
+
|
|
19
|
+
`maxChars` defaults to 200,000 UTF-16 code units and limits only text decoding. Bound native objects and arrays in the supplied schema. Keep domain schemas strict and wrap only the intended boundary fields; importing this helper does not change HTTP, persistence or other inputs automatically.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# MCP Client Runtime
|
|
2
|
+
|
|
3
|
+
`McpClientRuntimeCapability` (`platform.mcp.client`) resolves a `McpClientRuntimeApi`
|
|
4
|
+
for governed access to existing platform MCP connections. It is shared by plugin consumers,
|
|
5
|
+
independent of Analytics, Dataset, Binding and dashboard rendering.
|
|
6
|
+
|
|
7
|
+
The initial API implements **read-only `tools.list/call` only**. Resources, Prompts,
|
|
8
|
+
Tasks and subscriptions are not exposed. The host fixes the tools policy; a request cannot
|
|
9
|
+
enable writes, interaction, asynchronous tasks or arbitrary protocol methods.
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { McpClientRuntimeCapability } from '@xpert-ai/plugin-sdk'
|
|
15
|
+
|
|
16
|
+
const client = runtime.require(McpClientRuntimeCapability)
|
|
17
|
+
const tools = await client.tools.list(scope)
|
|
18
|
+
// Select an exact tool from the application's approved catalog and discovery result.
|
|
19
|
+
const result = await client.tools.call(scope, {
|
|
20
|
+
toolName: selected.name,
|
|
21
|
+
contractHash: selected.contractHash,
|
|
22
|
+
arguments: validatedArguments
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`runtime` is the injected platform capability registry. `scope: McpClientScope` contains
|
|
27
|
+
the current `actor` (tenant, organization, user), an existing
|
|
28
|
+
`workspaceId`/`toolsetId`/`serverName`, `signal` and an absolute `deadlineAt`.
|
|
29
|
+
Supply identity from trusted execution context. The host requires an exact match with
|
|
30
|
+
the current authenticated request and rechecks workspace read access. The toolset must
|
|
31
|
+
belong to the same tenant, organization and workspace and have category MCP.
|
|
32
|
+
URLs, credentials, connection snapshots and policy overrides are rejected inputs.
|
|
33
|
+
|
|
34
|
+
## Tools policy and contracts
|
|
35
|
+
|
|
36
|
+
- Discovery includes enabled, model-visible tools with `readOnlyHint: true` and without
|
|
37
|
+
`destructiveHint: true` or required task execution. Calls repeat this selection.
|
|
38
|
+
- Consumers additionally restrict operations to their own approved catalog. Read-only
|
|
39
|
+
annotations narrow selection; they neither grant permission nor prove remote behavior.
|
|
40
|
+
- `contractHash` pins input/output schemas and annotations. Changed contracts require
|
|
41
|
+
rediscovery and an explicit caller-side update; the hash does not pin remote code.
|
|
42
|
+
- Arguments and structured output use JSON Schema validation without coercion. Remote
|
|
43
|
+
schemas are isolated so repeated refreshes and reused `$id` values cannot collide.
|
|
44
|
+
- A successful result contains optional JSON `structuredContent` and plain `text` blocks.
|
|
45
|
+
Tool errors, invalid output and interaction requests fail. Resource links are not fetched.
|
|
46
|
+
Consumers must explicitly choose whether to accept structured JSON or text JSON.
|
|
47
|
+
|
|
48
|
+
## Execution boundary
|
|
49
|
+
|
|
50
|
+
The platform reuses ToolRuntime and MCP Consumer authentication. A shared internal connection
|
|
51
|
+
lifecycle owns authorization, cancellation, cleanup and safe runtime errors; protocol clients
|
|
52
|
+
and connection credentials stay internal. Access and connection/tool selection are checked
|
|
53
|
+
around remote I/O and immediately before tool execution. Revoked access discards the result.
|
|
54
|
+
|
|
55
|
+
Each operation has a 30-second maximum budget bounded by its caller's deadline. Discovery
|
|
56
|
+
has at most 20 pages and 1,000 tools, with cyclic cursors rejected. Call envelopes and individual
|
|
57
|
+
tool metadata are bounded to 64,000 bytes; remote tool results are bounded to 2,500,000 bytes.
|
|
58
|
+
Consumers such as Analytics may enforce tighter limits. Successful results are not cached.
|
|
59
|
+
|
|
60
|
+
Future capabilities must define their own host-authorized policies before being exposed;
|
|
61
|
+
expanding this API must preserve the read-only contract used by analytics consumers.
|
|
62
|
+
Deploy the matching host and SDK before consuming this capability. This new export does not
|
|
63
|
+
imply that an older published SDK or host supports it.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Provider credential validation
|
|
2
|
+
|
|
3
|
+
The credential dialog can test unsaved credentials without creating a provider record. The host selects a verification method from the provider strategy's explicit capabilities:
|
|
4
|
+
|
|
5
|
+
1. If `discoverModels(credentials)` exists, use it to fetch the account-visible model list. An empty successful list is valid. Discovery failures never trigger an automatic inference fallback.
|
|
6
|
+
2. Otherwise, if `credentialValidation.mode` is `model`, require a user-selected model type and Model ID or Endpoint ID. Run the provider's local credential checks, then that model manager's `validateCredentials(model, credentials)`.
|
|
7
|
+
3. Otherwise, retain the provider's existing `validateProviderCredentials(credentials)` behavior.
|
|
8
|
+
|
|
9
|
+
## Discovery
|
|
10
|
+
|
|
11
|
+
Implement the existing optional `IAIModelProviderStrategy.discoverModels` method. Use `discoverOpenAIModels` only when the upstream documents an authenticated OpenAI-compatible model-list endpoint. Public catalog metadata is not credential verification. Do not invoke inference, persist models or return credentials from discovery.
|
|
12
|
+
|
|
13
|
+
## Model-based verification
|
|
14
|
+
|
|
15
|
+
Providers without an API-key model-list endpoint can declare:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
readonly credentialValidation = {
|
|
19
|
+
mode: 'model' as const,
|
|
20
|
+
modelTypes: [AiModelTypeEnum.LLM]
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Declare only types whose model manager can perform a real, bounded validation request. The provider-level validator should check local fields, without choosing a fixed model. The host obtains suggestions from the provider catalog, but permits user-entered IDs that are absent from it. Catalog membership is not evidence of access.
|
|
25
|
+
|
|
26
|
+
## HTTP and persistence
|
|
27
|
+
|
|
28
|
+
- `GET /api/ai-model/provider/:provider/credential-validation` returns the supported verification method and, for model tests, model types and reference suggestions.
|
|
29
|
+
- `POST` to the same path accepts `{ credentials, validationTarget? }`, where the target is `{ modelType, model }`. It requires `COPILOT_EDIT`, does not save credentials or models, and returns only a verification result.
|
|
30
|
+
- Provider create/update requests can include the same `validationTarget`. The controller validates and strips it from the persisted entity, then passes it through the upsert and credential-validation commands.
|
|
31
|
+
- The save path repeats verification with the submitted credentials. Client-side success is never used as authorization or a reason to skip verification. Editing credentials or the test target invalidates the dialog's current result.
|
|
32
|
+
- Discovery proves access to the model-list API; successful inference validates only the selected target. Neither guarantees access to every listed model.
|
|
33
|
+
|
|
34
|
+
Deploy this host update before a plugin that relies on `credentialValidation`: older hosts do not enforce selected-model verification. Existing saved credentials and configured models are not migrated by this change.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# REST Client Runtime
|
|
2
|
+
|
|
3
|
+
`RestClientRuntimeCapability` (`platform.rest.client`) resolves a generic `RestClientRuntimeApi` independently of Analytics and dashboard plugins. The first version exposes `operations.list/call` for governed JSON reads on existing platform OpenAPI toolsets.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
const client = runtime.require(RestClientRuntimeCapability)
|
|
7
|
+
const operations = await client.operations.list(scope)
|
|
8
|
+
const result = await client.operations.call(scope, {
|
|
9
|
+
operationId: selected.operationId,
|
|
10
|
+
contractHash: selected.contractHash,
|
|
11
|
+
arguments: { query: { region: 'East' } }
|
|
12
|
+
})
|
|
13
|
+
// result.body is JSON; result.sourceFetchedAt records this fetch.
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`scope: RestClientScope` requires the current actor's tenant, organization and user, the saved workspace/toolset IDs, an AbortSignal and an absolute deadline. The host requires an exact identity match, workspace read access and a toolset in the same tenant/organization/workspace, with category API and type `openapi`. A caller cannot supply a URL, credential snapshot or policy override.
|
|
17
|
+
|
|
18
|
+
Discovery returns enabled operations, descriptions, an argument schema and an opaque contract hash. Calls pin endpoint, method, serialization and schema to that hash. GET is supported; POST requires a persisted `x-xpert-read-only: true` declaration and an optional JSON body. The declaration narrows eligible operations but cannot prove a remote service is read-only. Only approved, trusted connections should be registered.
|
|
19
|
+
|
|
20
|
+
Arguments are grouped by `query`, `path` and `body` and validated without coercion or defaults. Query scalars/arrays use OpenAPI form serialization and path scalars use simple serialization; header/cookie parameters and unsupported serializers fail closed. Path values cannot traverse segments or change host, method or query. Caller headers are absent. HTTP(S) endpoints are selected from saved definitions; an administrator may intentionally configure an internal service. There is no arbitrary destination fetch API.
|
|
21
|
+
|
|
22
|
+
Authentication reuses saved OpenAPI `none` or `api_key` settings and the shared API-key header builder, including existing bearer/basic prefixes. The legacy UI spelling `bearar` is accepted as `bearer`; empty prefixes preserve the raw API-key value. Header assembly never modifies saved credentials. Credentials are never returned to consumers. Redirects are disabled. Responses must be successful JSON, bounded to 2,500,000 bytes. Input contracts and envelopes are bounded to 64,000 bytes; lists have at most 1,000 operations. Each request has a 30-second maximum budget bounded by the parent deadline. Raw HTTP failures and source content are not included in errors.
|
|
23
|
+
|
|
24
|
+
Access and connection definitions are checked before and after I/O. A changed connection, disabled operation or revoked grant discards the response. Pagination and Dataset projection belong to consumers and must preserve the same caller identity/deadline for each call. Successful results are not cached. Deploy the matching SDK and host before consuming this new capability; older published SDK packages do not supply it.
|