@xpert-ai/plugin-sdk 3.23.0 → 3.23.1

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 (55) hide show
  1. package/_object_without_properties_loose.cjs.js +16 -0
  2. package/_object_without_properties_loose.esm.js +14 -0
  3. package/analytics-result.cjs.js +212 -0
  4. package/analytics-result.esm.js +201 -0
  5. package/analytics.cjs.default.js +1 -0
  6. package/analytics.cjs.js +17 -0
  7. package/analytics.cjs.mjs +2 -0
  8. package/analytics.d.ts +1 -0
  9. package/analytics.esm.js +2 -0
  10. package/artifact-document.cjs.default.js +1 -0
  11. package/artifact-document.cjs.js +581 -0
  12. package/artifact-document.cjs.mjs +2 -0
  13. package/artifact-document.d.ts +1 -0
  14. package/artifact-document.esm.js +563 -0
  15. package/data-workbench.cjs.js +23 -6
  16. package/data-workbench.esm.js +23 -6
  17. package/docs/analytics.md +66 -0
  18. package/docs/artifact-documents.md +74 -0
  19. package/docs/artifact-drafts.md +24 -0
  20. package/docs/json-encoded-schema.md +19 -0
  21. package/docs/workspace-dataset-pipelines.md +120 -0
  22. package/docs/workspace-file-tools.md +60 -0
  23. package/index.cjs.js +84 -19
  24. package/index.esm.js +127 -82
  25. package/model-provider-toolset.cjs.js +1 -1
  26. package/model-provider-toolset.esm.js +1 -1
  27. package/model-provider.cjs.js +37 -1
  28. package/model-provider.esm.js +33 -2
  29. package/package.json +14 -2
  30. package/src/analytics.d.ts +3 -0
  31. package/src/artifact-document.d.ts +5 -0
  32. package/src/lib/agent/handoff/agent-runtime-message.contract.d.ts +10 -10
  33. package/src/lib/artifact-document/dependencies.d.ts +101 -0
  34. package/src/lib/artifact-document/host.d.ts +30 -0
  35. package/src/lib/artifact-document/protocol.d.ts +60 -0
  36. package/src/lib/artifact-document/runtime.d.ts +4 -0
  37. package/src/lib/artifact-document/sha256.d.ts +2 -0
  38. package/src/lib/core/index.d.ts +1 -0
  39. package/src/lib/core/json-encoded-schema.d.ts +15 -0
  40. package/src/lib/data/analytics/analytics-provider.d.ts +74 -0
  41. package/src/lib/data/analytics/analytics-result.d.ts +4 -0
  42. package/src/lib/data/analytics/analytics.registry.d.ts +10 -0
  43. package/src/lib/data/analytics/analytics.schema.d.ts +206 -0
  44. package/src/lib/data/analytics/index.d.ts +4 -0
  45. package/src/lib/data/datasource/index.d.ts +1 -0
  46. package/src/lib/data/datasource/workbench-adapter.d.ts +11 -1
  47. package/src/lib/data/datasource/workbench-sql.d.ts +12 -0
  48. package/src/lib/runtime/capabilities/artifact-drafts.d.ts +29 -0
  49. package/src/lib/runtime/capabilities/artifacts.d.ts +10 -0
  50. package/src/lib/runtime/capabilities/index.d.ts +1 -0
  51. package/src/lib/runtime/capabilities/sandbox-jobs.d.ts +36 -2
  52. package/src/lib/runtime/index.d.ts +2 -0
  53. package/src/lib/runtime/mutation-evidence.d.ts +7 -0
  54. package/src/lib/runtime/workspace-file-tools.d.ts +11 -0
  55. package/src/lib/sandbox/runtime-provider.d.ts +4 -0
@@ -192,11 +192,17 @@ const FORBIDDEN = new Set([
192
192
  'ATTACH',
193
193
  'DETACH'
194
194
  ]);
195
- 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_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(' '));
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
- function splitWorkbenchSql(source) {
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
- function requireReadStatement(sql) {
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
- function quoteDatabaseIdentifier(name, engine) {
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
- /** One adapter per physical connection. A host session must not share it across users. */ class SqlDatabaseWorkbenchAdapter {
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');
@@ -0,0 +1,66 @@
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
+ ## Execution
32
+
33
+ - `GET /api/data-source/analytics/sources`: authorized IDs and supported providers, never credentials.
34
+ - `POST /api/data-source/analytics/query`: `{ binding, controls }`; body cannot set actor/tenant/organization.
35
+ - Requires `DATA_SOURCE_VIEW`; capability callers must match the current host request actor.
36
+ - 30-second deadline, 1,000 rows and 2 MB normalized result budget per query.
37
+ - Known result/parameter validation failures return safe error codes so Agents can repair their bindings; arbitrary provider exception text is never surfaced.
38
+ - After execution, source revision and provider registration are checked again. Missing/ambiguous columns, invalid cells, duplicate grain and inconsistent completeness fail closed.
39
+ - No shared result cache. `sourceFetchedAt` means source query time, not last business-data change; `dataAsOf` is optional and source-owned.
40
+ - `int64` and `decimal` use exact strings. Timestamps include a timezone. Renderers must reject unsupported precision rather than silently round canonical data.
41
+
42
+ 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.
43
+
44
+ ## Reusable Artifacts changes
45
+
46
+ `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.
47
+
48
+ `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.
49
+ `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.
50
+
51
+ No dashboard table, renderer schema or data-xpert dependency is added to the platform.
52
+
53
+ ## Presentation is independent of providers
54
+
55
+ Bindings specify data access and the output contract, not page layout. The Live Dashboard plugin supports two consumers of the same Dataset:
56
+
57
+ - Standard mode uses Bindings, Controls and chart/table definitions with the Data Analytics renderer.
58
+ - 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.
59
+
60
+ 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.
61
+
62
+ ## Workspace script provider
63
+
64
+ [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.
65
+
66
+ 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.
@@ -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,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,120 @@
1
+ # Workspace live script queries and dashboard Datasets
2
+
3
+ Status: implemented in the current source tree. The platform provides generic execution capabilities, and `@xpert-ai/plugin-analytics-workspace-script` provides the Python/JavaScript adapter. Before deployment, independently verify compatible SDK/contracts packages, the compute image and the Runtime Binding. Successful local integration does not establish production release readiness.
4
+
5
+ This document uses the script provider to illustrate how platform capabilities compose. `workspace_script.*`, script definitions, language entrypoints and the plugin limits below belong to this plugin; they are not a protocol that every Analytics provider must adopt. See [Analytics](analytics.md) for the generic data and presentation boundaries, and the [HTML document host](artifact-documents.md) for the browser isolation protocol.
6
+
7
+ Each dashboard open, filter change or manual refresh reruns the script against current inputs and returns a normalized Dataset. Routine refreshes require no LLM calls. Automatic push updates and scheduled polling are outside this version's scope.
8
+
9
+ ## Query flow
10
+
11
+ ```text
12
+ Dashboard Artifact + controls
13
+ → Analytics Runtime (current actor, parameters, executionId, deadline, signal)
14
+ → workspace_script.query provider
15
+ → Definition Artifact/version + current file authorization + execution code snapshot
16
+ → Sandbox Jobs / compute Runtime
17
+ query(ctx)
18
+ ├─ sources.query(alias, controls) → invocation → Analytics → source plugin
19
+ └─ files.read(alias) → invocation → Workspace Files
20
+ → Plugin validates columns/rows and trusted execution evidence
21
+ → Platform normalizeAnalyticsResult
22
+ → Live Dashboard: Data Analytics renderer or isolated HTML page
23
+ ```
24
+
25
+ Multiple charts can reuse the same Dataset. Each actual query receives a new executionId and Job idempotency key, so it runs again even when parameters are unchanged. This does not automatically deduplicate separate page calls. Temporary outputs belong to the current execution and cannot serve as a cache for the next query.
26
+
27
+ ## Modules and responsibility boundaries
28
+
29
+ | Module | Implemented responsibilities |
30
+ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
31
+ | `plugin-sdk` Analytics capability | Generic Dataset/Binding/discovery interfaces; provider context includes executionId, deadlineAt and ancestry; trusted internal query execution propagates signal/deadline |
32
+ | `server/data-source/analytics` | Assign execution IDs before dispatch; enforce parent/child deadlines, cancellation, source reauthorization, nesting depth and recursion limits |
33
+ | `plugin-sdk` jsonEncodedSchema | Decode JSON text once at explicitly enabled input boundaries, then apply the original strict schema; shared by script registration and dashboard saves without automatically relaxing HTTP or persistence protocols |
34
+ | `plugin-sdk` Sandbox Jobs capability | `run(input, options?)`, with signal and a named invocation handler in options; callbacks are not serialized, and actor parameters are not accepted from HTTP |
35
+ | `server-ai/sandbox/sandbox-job` | Job lifecycle, bounded stdout invocation sessions, actor context preservation, cancellation and cleanup; no SQL/ontology/CSV logic |
36
+ | `server-ai/shared/volume` and Workspace Files | Existing published Assistant/Project ACLs, portable references, path and symlink restrictions; a dedicated cleanup entrypoint for Job roots |
37
+ | Sandbox Runtime Suite | Generic compute profile and Node/Python image; non-root execution, no network, read-only inputs and resource limits |
38
+ | Pro Docker Runtime Provider | Read-only task mounts, separate output tmpfs, live output streaming, bounded output reads and cancellation cleanup; replaceable by a provider with equivalent capabilities |
39
+ | `analytics-workspace-script` plugin | Definition schema, language entrypoints, CSV helpers, alias authorization, result constraints and lineage |
40
+ | PostgreSQL / data-xpert plugins | Native queries, credentials, resource policies and data semantics; scripts invoke only Binding aliases |
41
+ | Live Dashboard plugin | Saves, filters, refreshes, stale-response protection, preview receipts, standard charts/tables and custom HTML presentation |
42
+
43
+ No script-specific business table is introduced. Definitions and execution evidence use existing Artifact/ArtifactVersion records; tasks use SandboxJob. The platform does not interpret script business semantics, and charts do not interpret SQL, ontology Actions or script languages.
44
+
45
+ ## Protocol and persistence
46
+
47
+ The generic Binding uses `providerId: workspace_script.query`, `operation: query` and `contractVersion: 1`, with source type `workspace-script`. Its payload contains only the definition's `artifactId/versionId`; parameters bind controls, and output declares the datasetId, stable field IDs, types, units and grain.
48
+
49
+ The plugin definition uses `xpert.analytics-script/v1`:
50
+
51
+ - `runtime` pins the Action name and version, currently `workspace_script.execute@1.0.0`.
52
+ - `language`, `mode`, the `script` portable reference and `scriptSha256` identify the code.
53
+ - `authorization` retains the original Assistant file reference; pinned snapshots still require rechecking the original permissions.
54
+ - `files` maps aliases to authorized portable references; `sources` maps aliases to complete source Bindings.
55
+ - `parameters/output` must exactly match the outer Binding; saving cannot silently substitute a different contract.
56
+
57
+ `pinned` fixes the code snapshot while reading current inputs. `current` rereads the code on each execution and creates an immutable snapshot for that execution. Definitions are currently owned by their creator; sharing a dashboard does not automatically expand script or file permissions.
58
+
59
+ Execution Artifacts store the executionId, Job ID, definition version, code SHA, parameter digest, input file SHAs/read times, child queries and source execution IDs, and output SHA. The source timestamp uses the earliest input read time in the execution; execution time is not presented as business dataAsOf. No automatic audit-retention TTL is introduced.
60
+
61
+ ## Script entrypoints
62
+
63
+ ```python
64
+ async def query(ctx):
65
+ dataset = await ctx.sources.query("sales", {"region": ctx.parameters.get("region")})
66
+ return ctx.dataset([
67
+ {"region": row["region"], "amount": row["amount"]}
68
+ for row in dataset["rows"]
69
+ ])
70
+ ```
71
+
72
+ ```javascript
73
+ export async function query(ctx) {
74
+ const file = await ctx.files.read('orders')
75
+ const records = ctx.csv.parse(file.text)
76
+ return ctx.dataset(records.map((row) => ({ region: row.region, amount: row.amount })))
77
+ }
78
+ ```
79
+
80
+ Source Dataset rows use `field.id`; script output uses the definition's `sourceField`. decimal/int64 values must remain exact strings. Python can use Decimal, and JavaScript can use integer minor units/BigInt, converting results back to exact strings. Results may contain only columns/rows; scripts cannot issue freshness, provenance or completeness claims.
81
+
82
+ The second argument to a source query supplies controls for the predeclared Binding, mapped by controlId. Scripts cannot replace the source, native payload, actor or credentials. CSV helpers remain in the plugin. Only the Python/Node standard libraries are available by default; arbitrary packages are not installed.
83
+
84
+ ## Invocation during generic execution
85
+
86
+ `SandboxJobRunOptions.invocation` registers operations, maxCalls, maxBytes and a trusted handler. Dedicated JSONL frames on container stdout carry id/operation/payload. After validation, the platform calls the handler and writes the response through the Runtime file API into the current Job's response directory, which is read-only inside the container. Docker has no network access; scripts receive neither tokens nor HTTP addresses.
87
+
88
+ The platform uses AsyncResource to preserve the trusted caller context and checks duplicate IDs, allowed operations and quotas. Sessions close when the Job completes, fails or is cancelled. Any Runtime Provider can implement this protocol through live output and file uploads. Requests currently execute in the owning API process; reconnect recovery and resumption across API processes are not implemented.
89
+
90
+ The plugin forwards `source.query` to Analytics Runtime and `file.read` to Workspace Files. Each call revalidates the definition, original Assistant and input permissions. Source actor tokens and database passwords remain in the platform/source plugins. Child queries inherit the parent deadline and cancellation signal, and recursive source calls are prohibited.
91
+
92
+ ## Isolation and limits
93
+
94
+ The compute profile requires hardened, ephemeral execution, resource limits, no network, a non-root user, a read-only root filesystem and a read-only Workspace. Development mode cannot bypass the readOnlyWorkspace capability requirement. The Pro provider uses read-only task mounts and a separate 64 MB output tmpfs, with a trusted reader that rejects output symlinks and oversized files.
95
+
96
+ The total query deadline is 30 seconds. Compute execution defaults to 25 seconds with a hard limit of 30 seconds, 1 CPU and 256 MB of memory. Scripts are limited to 64 KB; up to 8 file aliases, each with a 1 MB UTF-8 file; up to 4 source aliases; 16 invocations/8 MB of invocation data; at most 4,000 source rows in total; and at most 1,000 result rows/2 MB. Longer tasks require a future unified asynchronous query protocol.
97
+
98
+ Files remain consistent within an execution after their first read. Reading multiple sources does not create a cross-system transactional snapshot. Upstream truncation/pagination propagates to the final result; aggregates over partial inputs cannot claim to be complete totals. The platform validates output fields, types and grain before returning the result, then removes temporary outputs.
99
+
100
+ The frontend uses request sequence numbers to discard late responses. The server uses deadlines and cancellation signals to reclaim executions. The current UI has no user-facing Job cancellation button, and changing filters does not guarantee immediate interruption of all previous queries.
101
+
102
+ ## Two presentation modes
103
+
104
+ Standard mode uses `bindings + controls + charts/tables`. The plugin maps the normalized Dataset to the existing Data Analytics renderer; a Binding itself does not describe chart types or layout.
105
+
106
+ HTML mode uses `bindings + controls + presentation.html`, with empty `charts/tables`. The page calls `window.xpertLiveArtifact.query(bindingId, controls)` to obtain a Dataset, then uses its own JavaScript and stable field IDs to render DOM/SVG/Canvas. `subscribe` receives filter and refresh results. Host refreshes reuse the latest control values without reloading the HTML. The page does not need to know whether data comes from SQL, an ontology or a script.
107
+
108
+ Both modes save query definitions, not result snapshots. HTML and Bindings belong to the same Artifact version; the backend loads the Binding from that version and reauthorizes the current user. Frontend chart scripts in HTML and the backend Workspace data-processing scripts described here run in separate environments: the former render the page, while the latter access inputs through governed aliases in a Sandbox Job.
109
+
110
+ ## One-sentence Agent generation
111
+
112
+ The Agent first discovers actual data and metric definitions, writes a script through Workspace tools, and registers it with structured parameters. Before registration, source Bindings are checked with default parameters, so invalid native query configurations fail before the script starts. Registration returns the complete bindingJson. `dashboard_preview_binding` previews it unchanged and issues a receipt for the current generation run; `dashboard_create` or `dashboard_create_html` can save only with successful receipts. HTML mode also reads the page from an authorized Workspace and runs an isolated browser preflight with real default Dataset results before saving. This flow reuses normal dashboard validation for business semantics, grain and default filters; it does not save model-invented result snapshots. A dedicated Assistant can configure allowedFinalProviders in LiveDashboard middleware to restrict the final saved provider while permitting upstream previews from other providers. The script acceptance Assistant uses workspace_script.query; ordinary Assistants have no such restriction by default.
113
+
114
+ Earlier live acceptance runs used the same nine-order fixture through Python CSV, JavaScript PostgreSQL, data-xpert semantic sources and data-xpert SSO pages. Historical results and repeatable isolated tests are documented in `xpert-plugins/community/tools/analytics-workspace-script/docs/acceptance.md`. Historical model and SSO acceptance for standard/HTML dashboards is in `xpert-plugins/community/apps/live-dashboard/docs/`. This documentation review does not mean those scenarios were rerun.
115
+
116
+ ## Release boundaries
117
+
118
+ Local compute images and integration against a source checkout do not constitute a production release. Release requires updated SDK/contracts packages, a built and published compute image, a generated digest catalog/Binding, and validation of the target Runtime Provider's capabilities. Existing local execution receipts do not replace these steps.
119
+
120
+ New exports such as `jsonEncodedSchema` must exist in the SDK actually used. An old peer semver range or stale local dist does not establish compatibility. Before migrating an existing plugin to a shared helper, verify the SDK release version and dependency constraints, then remove the original implementation. Temporary SDK builds and test doubles do not prove that an older published package supports a new API.
@@ -0,0 +1,60 @@
1
+ # Workspace file tools
2
+
3
+ Use the platform `SandboxFile` middleware to read, write, append and edit HTML,
4
+ Python, JavaScript and other text files. Domain plugins should consume the files
5
+ through `WorkspaceFilesRuntimeCapability` instead of adding duplicate writers.
6
+ The Assistant must enable the sandbox feature and include the file middleware;
7
+ these helpers do not enable tools or grant file access.
8
+
9
+ ## Agent arguments
10
+
11
+ File paths are relative to the Assistant's file workspace, for example
12
+ `dashboards/sales.html` or `scripts/sales.py`. The SDK exports
13
+ `workspaceRelativeFilePathSchema` for the same portable input contract:
14
+
15
+ - At most 1024 characters, with non-empty `/`-separated segments.
16
+ - No absolute paths, Windows drive prefixes, backslashes, control characters,
17
+ `.`/`..` segments or whitespace at either edge of a segment.
18
+ - Unicode names and spaces inside a segment are supported.
19
+
20
+ Write and append accept `{ file_path, content }`, with `content` as one string
21
+ (including an empty string). Arrays, `html` aliases and extra fields are rejected.
22
+ Edit uses `old_string`, `new_string` and optional `replace_all`; multi-edit takes
23
+ `edits` containing `oldString`, `newString` and optional `replaceAll`. Unknown keys
24
+ are rejected inside each edit as well as at the top level.
25
+
26
+ This is a file-path contract. Directory listing and search retain their own
27
+ schemas, including support for the workspace root. Input validation does not
28
+ replace host authorization, filesystem containment or symlink protection.
29
+
30
+ ## Observing file mutation intent
31
+
32
+ The four mutating platform tools declare host-owned metadata:
33
+
34
+ ```ts
35
+ metadata: workspaceFileMutationMetadata
36
+ // { workspaceFileOperation: { type: 'mutation', pathArgument: 'file_path' } }
37
+ ```
38
+
39
+ A plugin can call `workspaceFileMutationPath(tool.metadata, toolCall.args)` to
40
+ obtain the validated relative path. Other tool implementations may declare their
41
+ own `pathArgument`. Missing or malformed metadata, non-mutation operations and
42
+ invalid paths return `undefined`; consumers must not infer mutation behavior
43
+ from tool names, labels or file extensions.
44
+
45
+ Metadata describes an attempted operation, not its success. A plugin may mark an
46
+ already registered document as potentially changed before execution, but must
47
+ inspect the tool result and actual file content before accepting a save. Writing
48
+ a file does not save an Artifact draft or publish a version. Artifact saves need
49
+ their own successful, revision-bearing receipt. Business rules for selecting
50
+ files, validating dashboards, saving drafts and publishing remain in plugins.
51
+
52
+ ## Runtime path mapping
53
+
54
+ Plugins exchange relative paths, never container or server absolute paths. After
55
+ sandbox acquisition, the invocation handler uses the acquired provider's workspace
56
+ mapper when it differs from the requested provider, including when the host
57
+ chooses a default provider. Graph compilation and runtime workspace paths use this
58
+ mapped work area; server-side file access retains the Volume path and scope.
59
+ This does not add default-provider selection to hosts that require an explicit
60
+ provider, or change workspace authorization and sandbox lifecycle ownership.