@xpert-ai/plugin-sdk 3.26.2 → 3.28.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.
Files changed (67) hide show
  1. package/artifact-document.cjs.js +55 -16
  2. package/artifact-document.esm.js +53 -17
  3. package/collaboration-client.cjs.js +31 -5
  4. package/collaboration-client.esm.js +31 -5
  5. package/data-workbench.cjs.js +4 -2
  6. package/data-workbench.esm.js +4 -2
  7. package/docs/artifact-documents.md +8 -2
  8. package/docs/en/runtime-capabilities.md +103 -0
  9. package/index.cjs.js +479 -70
  10. package/index.esm.js +461 -73
  11. package/model-provider.cjs.js +17 -1
  12. package/model-provider.esm.js +15 -2
  13. package/package.json +2 -2
  14. package/src/artifact-document.d.ts +1 -0
  15. package/src/index.d.ts +2 -0
  16. package/src/lib/agent/handoff/types.d.ts +5 -0
  17. package/src/lib/agent/middleware/capabilities/assistant-task.d.ts +6 -1
  18. package/src/lib/agent/middleware/runtime.d.ts +2 -0
  19. package/src/lib/agent/runtime/capability.d.ts +4 -0
  20. package/src/lib/agent/runtime/cli-model-profile.d.ts +1 -1
  21. package/src/lib/agent/runtime/execution-runner.d.ts +11 -0
  22. package/src/lib/agent/runtime/index.d.ts +2 -0
  23. package/src/lib/agent/runtime/managed.d.ts +94 -0
  24. package/src/lib/agent/runtime/process-supervisor.d.ts +1 -0
  25. package/src/lib/agent/runtime/strategy.d.ts +14 -0
  26. package/src/lib/agent/runtime/types.d.ts +30 -1
  27. package/src/lib/ai-model/native-model.d.ts +5 -1
  28. package/src/lib/artifact-document/host.d.ts +3 -0
  29. package/src/lib/artifact-document/network.d.ts +21 -0
  30. package/src/lib/artifact-document/runtime.d.ts +2 -1
  31. package/src/lib/assistant-capability/index.d.ts +3 -0
  32. package/src/lib/assistant-capability/middleware.d.ts +10 -0
  33. package/src/lib/collaboration/types.d.ts +12 -1
  34. package/src/lib/connector/document-source.d.ts +31 -0
  35. package/src/lib/connector/documents.d.ts +38 -0
  36. package/src/lib/connector/index.d.ts +1 -0
  37. package/src/lib/connector/strategy.interface.d.ts +3 -0
  38. package/src/lib/content-resource/catalog.d.ts +88 -0
  39. package/src/lib/content-resource/document.d.ts +142 -0
  40. package/src/lib/content-resource/editor-compatibility.d.ts +3 -0
  41. package/src/lib/content-resource/editor.d.ts +105 -0
  42. package/src/lib/content-resource/index.d.ts +94 -0
  43. package/src/lib/content-resource/reference.d.ts +38 -0
  44. package/src/lib/data/datasource/workbench-adapter.d.ts +5 -3
  45. package/src/lib/data/datasource/workbench-sql.d.ts +0 -4
  46. package/src/lib/execution-control/context.d.ts +7 -0
  47. package/src/lib/execution-control/index.d.ts +2 -0
  48. package/src/lib/managed-queue/index.d.ts +12 -0
  49. package/src/lib/project-pipeline/contribution-failure.d.ts +17 -0
  50. package/src/lib/project-pipeline/registry.d.ts +16 -1
  51. package/src/lib/runtime/actor.d.ts +10 -0
  52. package/src/lib/runtime/capabilities/artifact-drafts.d.ts +10 -1
  53. package/src/lib/runtime/capabilities/artifacts.d.ts +5 -0
  54. package/src/lib/runtime/capabilities/assistant-middleware-access.d.ts +28 -0
  55. package/src/lib/runtime/capabilities/index.d.ts +4 -0
  56. package/src/lib/runtime/capabilities/mcp-client-runtime.d.ts +2 -0
  57. package/src/lib/runtime/capabilities/project-access.d.ts +10 -7
  58. package/src/lib/runtime/capabilities/project-files.d.ts +40 -0
  59. package/src/lib/runtime/capabilities/project-knowledge.d.ts +14 -0
  60. package/src/lib/runtime/capabilities/project-provisioning.d.ts +6 -0
  61. package/src/lib/runtime/capabilities/sandbox-jobs.d.ts +12 -3
  62. package/src/lib/runtime/capabilities/workspace-files.d.ts +2 -0
  63. package/src/lib/sandbox/file-edit-command.d.ts +2 -0
  64. package/src/lib/sandbox/file-edit-diff.d.ts +1 -0
  65. package/src/lib/sandbox/protocol.d.ts +13 -1
  66. package/src/lib/sandbox/runtime-provider.d.ts +12 -0
  67. package/src/lib/view-extension/middleware-runtime.d.ts +2 -3
@@ -235,23 +235,59 @@ const artifactDocumentDependencyAssets = v3.z.array(dependencyLockObject.extend(
235
235
  return verifyArtifactDocumentDependencies(assets).map((asset)=>`<script>(()=>{const s=document.createElement('script');s.textContent=${literal(asset.source)};document.head.appendChild(s);s.remove();if(typeof window[${literal(asset.global)}]==='undefined')throw new Error('DOCUMENT_DEPENDENCY_GLOBAL_MISSING');})();</script>`).join('');
236
236
  }
237
237
 
238
- const ARTIFACT_DOCUMENT_CSP = [
239
- "default-src 'none'",
240
- "script-src 'unsafe-inline'",
241
- "style-src 'unsafe-inline'",
242
- 'img-src data: blob:',
243
- 'font-src data:',
244
- "connect-src 'none'",
245
- "frame-src 'none'",
246
- "worker-src 'none'",
247
- "object-src 'none'",
248
- "base-uri 'none'",
249
- "form-action 'none'"
250
- ].join('; ');
251
- /** Host-owned prefix precedes all authored markup, including malformed/duplicate heads. */ function renderArtifactDocument(html, sessionId, dependencies = []) {
238
+ // Only the trusted host supplies this policy. Authored HTML cannot expand it.
239
+ const origin = v3.z.string().max(250).refine((value)=>{
240
+ try {
241
+ const url = new URL(value);
242
+ return url.protocol === 'https:' && url.origin === value && !url.username && !url.password && /^(?:[a-z0-9.-]+|\[[a-f0-9:]+\])$/i.test(url.hostname);
243
+ } catch (e) {
244
+ return false;
245
+ }
246
+ }, 'Use an exact HTTPS origin without a path, credentials or wildcard');
247
+ const origins = v3.z.array(origin).max(16);
248
+ const artifactDocumentNetworkPolicy = v3.z.object({
249
+ scripts: origins.optional(),
250
+ styles: origins.optional(),
251
+ fonts: origins.optional(),
252
+ images: origins.optional()
253
+ }).strict();
254
+ function artifactDocumentCsp(input) {
255
+ const policy = artifactDocumentNetworkPolicy.parse(input != null ? input : {});
256
+ const sources = (values)=>(values == null ? void 0 : values.length) ? ` ${[
257
+ ...new Set(values)
258
+ ].join(' ')}` : '';
259
+ return [
260
+ "default-src 'none'",
261
+ `script-src 'unsafe-inline'${sources(policy.scripts)}`,
262
+ `style-src 'unsafe-inline'${sources(policy.styles)}`,
263
+ `img-src data: blob:${sources(policy.images)}`,
264
+ `font-src data:${sources(policy.fonts)}`,
265
+ "connect-src 'none'",
266
+ "frame-src 'none'",
267
+ "worker-src 'none'",
268
+ "object-src 'none'",
269
+ "base-uri 'none'",
270
+ "form-action 'none'"
271
+ ].join('; ');
272
+ }
273
+ /** For preview browser routing; CSP remains the enforcement in the displayed frame. */ function isArtifactDocumentResourceAllowed(policy, resourceType, value) {
274
+ let url;
275
+ try {
276
+ url = new URL(value);
277
+ } catch (e) {
278
+ return false;
279
+ }
280
+ if (url.protocol !== 'https:' || url.username || url.password) return false;
281
+ const allowed = resourceType === 'script' ? policy.scripts : resourceType === 'stylesheet' ? policy.styles : resourceType === 'font' ? policy.fonts : resourceType === 'image' ? policy.images : undefined;
282
+ var _allowed_includes;
283
+ return (_allowed_includes = allowed == null ? void 0 : allowed.includes(url.origin)) != null ? _allowed_includes : false;
284
+ }
285
+
286
+ const ARTIFACT_DOCUMENT_CSP = artifactDocumentCsp();
287
+ /** Host-owned prefix precedes all authored markup, including malformed/duplicate heads. */ function renderArtifactDocument(html, sessionId, dependencies = [], networkPolicy) {
252
288
  artifactDocumentHtml.parse(html);
253
289
  if (!/^[a-f0-9]{32}$/.test(sessionId)) throw new Error('Invalid Artifact document session ID');
254
- return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${ARTIFACT_DOCUMENT_CSP}"><script>${ARTIFACT_DOCUMENT_RUNTIME.replace('__XPERT_DOCUMENT_SESSION__', sessionId)}</script>${renderArtifactDocumentDependencies(dependencies)}${html}`;
290
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${artifactDocumentCsp(networkPolicy)}"><script>${ARTIFACT_DOCUMENT_RUNTIME.replace('__XPERT_DOCUMENT_SESSION__', sessionId)}</script>${renderArtifactDocumentDependencies(dependencies)}${html}`;
255
291
  }
256
292
  const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
257
293
  ;(() => {
@@ -423,7 +459,7 @@ const diagnosticSchema = v3.z.object({
423
459
  const context = artifactDocumentContext.parse(options.context);
424
460
  const sessionId = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte)=>byte.toString(16).padStart(2, '0')).join('');
425
461
  // Validate/render before allocating a channel or installing listeners.
426
- const source = renderArtifactDocument(options.html, sessionId, options.dependencies);
462
+ const source = renderArtifactDocument(options.html, sessionId, options.dependencies, options.networkPolicy);
427
463
  const channel = new MessageChannel();
428
464
  const bindingIds = new Set(context.bindingIds);
429
465
  const requestIds = new Set();
@@ -567,14 +603,17 @@ exports.ARTIFACT_DOCUMENT_CSP = ARTIFACT_DOCUMENT_CSP;
567
603
  exports.ARTIFACT_DOCUMENT_VERSION = ARTIFACT_DOCUMENT_VERSION;
568
604
  exports.artifactDocumentContext = artifactDocumentContext;
569
605
  exports.artifactDocumentControls = artifactDocumentControls;
606
+ exports.artifactDocumentCsp = artifactDocumentCsp;
570
607
  exports.artifactDocumentDependencyAssets = artifactDocumentDependencyAssets;
571
608
  exports.artifactDocumentDependencyLock = artifactDocumentDependencyLock;
572
609
  exports.artifactDocumentDependencyLocks = artifactDocumentDependencyLocks;
573
610
  exports.artifactDocumentHtml = artifactDocumentHtml;
574
611
  exports.artifactDocumentId = artifactDocumentId;
612
+ exports.artifactDocumentNetworkPolicy = artifactDocumentNetworkPolicy;
575
613
  exports.artifactDocumentQuery = artifactDocumentQuery;
576
614
  exports.artifactDocumentValue = artifactDocumentValue;
577
615
  exports.installArtifactDocumentFramePolicy = installArtifactDocumentFramePolicy;
616
+ exports.isArtifactDocumentResourceAllowed = isArtifactDocumentResourceAllowed;
578
617
  exports.mountArtifactDocument = mountArtifactDocument;
579
618
  exports.renderArtifactDocument = renderArtifactDocument;
580
619
  exports.renderArtifactDocumentDependencies = renderArtifactDocumentDependencies;
@@ -233,23 +233,59 @@ const artifactDocumentDependencyAssets = z.array(dependencyLockObject.extend({
233
233
  return verifyArtifactDocumentDependencies(assets).map((asset)=>`<script>(()=>{const s=document.createElement('script');s.textContent=${literal(asset.source)};document.head.appendChild(s);s.remove();if(typeof window[${literal(asset.global)}]==='undefined')throw new Error('DOCUMENT_DEPENDENCY_GLOBAL_MISSING');})();</script>`).join('');
234
234
  }
235
235
 
236
- const ARTIFACT_DOCUMENT_CSP = [
237
- "default-src 'none'",
238
- "script-src 'unsafe-inline'",
239
- "style-src 'unsafe-inline'",
240
- 'img-src data: blob:',
241
- 'font-src data:',
242
- "connect-src 'none'",
243
- "frame-src 'none'",
244
- "worker-src 'none'",
245
- "object-src 'none'",
246
- "base-uri 'none'",
247
- "form-action 'none'"
248
- ].join('; ');
249
- /** Host-owned prefix precedes all authored markup, including malformed/duplicate heads. */ function renderArtifactDocument(html, sessionId, dependencies = []) {
236
+ // Only the trusted host supplies this policy. Authored HTML cannot expand it.
237
+ const origin = z.string().max(250).refine((value)=>{
238
+ try {
239
+ const url = new URL(value);
240
+ return url.protocol === 'https:' && url.origin === value && !url.username && !url.password && /^(?:[a-z0-9.-]+|\[[a-f0-9:]+\])$/i.test(url.hostname);
241
+ } catch (e) {
242
+ return false;
243
+ }
244
+ }, 'Use an exact HTTPS origin without a path, credentials or wildcard');
245
+ const origins = z.array(origin).max(16);
246
+ const artifactDocumentNetworkPolicy = z.object({
247
+ scripts: origins.optional(),
248
+ styles: origins.optional(),
249
+ fonts: origins.optional(),
250
+ images: origins.optional()
251
+ }).strict();
252
+ function artifactDocumentCsp(input) {
253
+ const policy = artifactDocumentNetworkPolicy.parse(input != null ? input : {});
254
+ const sources = (values)=>(values == null ? void 0 : values.length) ? ` ${[
255
+ ...new Set(values)
256
+ ].join(' ')}` : '';
257
+ return [
258
+ "default-src 'none'",
259
+ `script-src 'unsafe-inline'${sources(policy.scripts)}`,
260
+ `style-src 'unsafe-inline'${sources(policy.styles)}`,
261
+ `img-src data: blob:${sources(policy.images)}`,
262
+ `font-src data:${sources(policy.fonts)}`,
263
+ "connect-src 'none'",
264
+ "frame-src 'none'",
265
+ "worker-src 'none'",
266
+ "object-src 'none'",
267
+ "base-uri 'none'",
268
+ "form-action 'none'"
269
+ ].join('; ');
270
+ }
271
+ /** For preview browser routing; CSP remains the enforcement in the displayed frame. */ function isArtifactDocumentResourceAllowed(policy, resourceType, value) {
272
+ let url;
273
+ try {
274
+ url = new URL(value);
275
+ } catch (e) {
276
+ return false;
277
+ }
278
+ if (url.protocol !== 'https:' || url.username || url.password) return false;
279
+ const allowed = resourceType === 'script' ? policy.scripts : resourceType === 'stylesheet' ? policy.styles : resourceType === 'font' ? policy.fonts : resourceType === 'image' ? policy.images : undefined;
280
+ var _allowed_includes;
281
+ return (_allowed_includes = allowed == null ? void 0 : allowed.includes(url.origin)) != null ? _allowed_includes : false;
282
+ }
283
+
284
+ const ARTIFACT_DOCUMENT_CSP = artifactDocumentCsp();
285
+ /** Host-owned prefix precedes all authored markup, including malformed/duplicate heads. */ function renderArtifactDocument(html, sessionId, dependencies = [], networkPolicy) {
250
286
  artifactDocumentHtml.parse(html);
251
287
  if (!/^[a-f0-9]{32}$/.test(sessionId)) throw new Error('Invalid Artifact document session ID');
252
- return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${ARTIFACT_DOCUMENT_CSP}"><script>${ARTIFACT_DOCUMENT_RUNTIME.replace('__XPERT_DOCUMENT_SESSION__', sessionId)}</script>${renderArtifactDocumentDependencies(dependencies)}${html}`;
288
+ return `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${artifactDocumentCsp(networkPolicy)}"><script>${ARTIFACT_DOCUMENT_RUNTIME.replace('__XPERT_DOCUMENT_SESSION__', sessionId)}</script>${renderArtifactDocumentDependencies(dependencies)}${html}`;
253
289
  }
254
290
  const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
255
291
  ;(() => {
@@ -421,7 +457,7 @@ const diagnosticSchema = z.object({
421
457
  const context = artifactDocumentContext.parse(options.context);
422
458
  const sessionId = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte)=>byte.toString(16).padStart(2, '0')).join('');
423
459
  // Validate/render before allocating a channel or installing listeners.
424
- const source = renderArtifactDocument(options.html, sessionId, options.dependencies);
460
+ const source = renderArtifactDocument(options.html, sessionId, options.dependencies, options.networkPolicy);
425
461
  const channel = new MessageChannel();
426
462
  const bindingIds = new Set(context.bindingIds);
427
463
  const requestIds = new Set();
@@ -560,4 +596,4 @@ const diagnosticSchema = z.object({
560
596
  hostDocument.head.prepend(meta);
561
597
  }
562
598
 
563
- export { ARTIFACT_DOCUMENT_CHANNEL, ARTIFACT_DOCUMENT_CSP, ARTIFACT_DOCUMENT_VERSION, artifactDocumentContext, artifactDocumentControls, artifactDocumentDependencyAssets, artifactDocumentDependencyLock, artifactDocumentDependencyLocks, artifactDocumentHtml, artifactDocumentId, artifactDocumentQuery, artifactDocumentValue, installArtifactDocumentFramePolicy, mountArtifactDocument, renderArtifactDocument, renderArtifactDocumentDependencies, verifyArtifactDocumentDependencies };
599
+ export { ARTIFACT_DOCUMENT_CHANNEL, ARTIFACT_DOCUMENT_CSP, ARTIFACT_DOCUMENT_VERSION, artifactDocumentContext, artifactDocumentControls, artifactDocumentCsp, artifactDocumentDependencyAssets, artifactDocumentDependencyLock, artifactDocumentDependencyLocks, artifactDocumentHtml, artifactDocumentId, artifactDocumentNetworkPolicy, artifactDocumentQuery, artifactDocumentValue, installArtifactDocumentFramePolicy, isArtifactDocumentResourceAllowed, mountArtifactDocument, renderArtifactDocument, renderArtifactDocumentDependencies, verifyArtifactDocumentDependencies };
@@ -113,6 +113,8 @@ function createSocketIoTransportAdapter(socket) {
113
113
  var _options_initialPresence;
114
114
  let presence = _extends._extends({}, (_options_initialPresence = options.initialPresence) != null ? _options_initialPresence : {});
115
115
  let pending = [];
116
+ let inFlight = [];
117
+ let synchronized = false;
116
118
  let flushTimer;
117
119
  let syncTimer;
118
120
  let presenceTimer;
@@ -128,9 +130,12 @@ function createSocketIoTransportAdapter(socket) {
128
130
  const flush = ()=>{
129
131
  if (flushTimer) clearTimeout(flushTimer);
130
132
  flushTimer = undefined;
131
- if (!pending.length || !options.transport.connected) return;
133
+ if (!pending.length || inFlight.length || !synchronized || !options.transport.connected) return;
132
134
  const updates = pending;
133
135
  pending = [];
136
+ // Keep bytes until the server acknowledges persistence. Replaying a Yjs update
137
+ // after a lost acknowledgement is idempotent; dropping it could lose an edit.
138
+ inFlight = updates;
134
139
  options.transport.emit('update', {
135
140
  updateBase64: bytesToBase64(options.document.mergeUpdates(updates)),
136
141
  origin: 'plugin-client'
@@ -159,23 +164,44 @@ function createSocketIoTransportAdapter(socket) {
159
164
  started = true;
160
165
  options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connecting');
161
166
  cleanups.push(options.document.onUpdate((update, origin)=>{
162
- if (origin === remoteOrigin) return;
167
+ if (origin === remoteOrigin || options.session.access !== 'write') return;
163
168
  pending.push(update);
164
169
  if (!flushTimer) flushTimer = setTimeout(flush, batchMs);
165
170
  }));
166
171
  cleanups.push(options.transport.on('connect', ()=>{
172
+ synchronized = false;
167
173
  var _options_transport_clientId;
168
174
  selfClientId = (_options_transport_clientId = options.transport.clientId) != null ? _options_transport_clientId : selfClientId;
169
175
  options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connected');
170
176
  requestSync();
171
177
  emitPresence();
172
178
  }));
173
- cleanups.push(options.transport.on('disconnect', ()=>options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected')));
174
- cleanups.push(options.transport.on('sync', applyRemote));
179
+ cleanups.push(options.transport.on('disconnect', ()=>{
180
+ synchronized = false;
181
+ pending = [
182
+ ...inFlight,
183
+ ...pending
184
+ ];
185
+ inFlight = [];
186
+ options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected');
187
+ }));
188
+ cleanups.push(options.transport.on('sync', (payload)=>{
189
+ applyRemote(payload);
190
+ // The initial sync is sent only after session authorization and room setup.
191
+ // A raw socket connect can precede that setup, so do not flush on connect.
192
+ if (stringValue(payload['updateBase64'])) {
193
+ synchronized = true;
194
+ flush();
195
+ }
196
+ }));
175
197
  cleanups.push(options.transport.on('update', applyRemote));
176
198
  cleanups.push(options.transport.on('update-ack', (payload)=>{
177
199
  const ack = parseAck(payload);
178
- if (ack) options.onAck == null ? void 0 : options.onAck.call(options, ack);
200
+ if (ack && ack.documentId === options.session.documentId) {
201
+ inFlight = [];
202
+ options.onAck == null ? void 0 : options.onAck.call(options, ack);
203
+ flush();
204
+ }
179
205
  }));
180
206
  cleanups.push(options.transport.on('presence', (payload)=>{
181
207
  const item = parsePresence(payload);
@@ -111,6 +111,8 @@ function createSocketIoTransportAdapter(socket) {
111
111
  var _options_initialPresence;
112
112
  let presence = _extends({}, (_options_initialPresence = options.initialPresence) != null ? _options_initialPresence : {});
113
113
  let pending = [];
114
+ let inFlight = [];
115
+ let synchronized = false;
114
116
  let flushTimer;
115
117
  let syncTimer;
116
118
  let presenceTimer;
@@ -126,9 +128,12 @@ function createSocketIoTransportAdapter(socket) {
126
128
  const flush = ()=>{
127
129
  if (flushTimer) clearTimeout(flushTimer);
128
130
  flushTimer = undefined;
129
- if (!pending.length || !options.transport.connected) return;
131
+ if (!pending.length || inFlight.length || !synchronized || !options.transport.connected) return;
130
132
  const updates = pending;
131
133
  pending = [];
134
+ // Keep bytes until the server acknowledges persistence. Replaying a Yjs update
135
+ // after a lost acknowledgement is idempotent; dropping it could lose an edit.
136
+ inFlight = updates;
132
137
  options.transport.emit('update', {
133
138
  updateBase64: bytesToBase64(options.document.mergeUpdates(updates)),
134
139
  origin: 'plugin-client'
@@ -157,23 +162,44 @@ function createSocketIoTransportAdapter(socket) {
157
162
  started = true;
158
163
  options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connecting');
159
164
  cleanups.push(options.document.onUpdate((update, origin)=>{
160
- if (origin === remoteOrigin) return;
165
+ if (origin === remoteOrigin || options.session.access !== 'write') return;
161
166
  pending.push(update);
162
167
  if (!flushTimer) flushTimer = setTimeout(flush, batchMs);
163
168
  }));
164
169
  cleanups.push(options.transport.on('connect', ()=>{
170
+ synchronized = false;
165
171
  var _options_transport_clientId;
166
172
  selfClientId = (_options_transport_clientId = options.transport.clientId) != null ? _options_transport_clientId : selfClientId;
167
173
  options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'connected');
168
174
  requestSync();
169
175
  emitPresence();
170
176
  }));
171
- cleanups.push(options.transport.on('disconnect', ()=>options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected')));
172
- cleanups.push(options.transport.on('sync', applyRemote));
177
+ cleanups.push(options.transport.on('disconnect', ()=>{
178
+ synchronized = false;
179
+ pending = [
180
+ ...inFlight,
181
+ ...pending
182
+ ];
183
+ inFlight = [];
184
+ options.onConnectionChange == null ? void 0 : options.onConnectionChange.call(options, 'disconnected');
185
+ }));
186
+ cleanups.push(options.transport.on('sync', (payload)=>{
187
+ applyRemote(payload);
188
+ // The initial sync is sent only after session authorization and room setup.
189
+ // A raw socket connect can precede that setup, so do not flush on connect.
190
+ if (stringValue(payload['updateBase64'])) {
191
+ synchronized = true;
192
+ flush();
193
+ }
194
+ }));
173
195
  cleanups.push(options.transport.on('update', applyRemote));
174
196
  cleanups.push(options.transport.on('update-ack', (payload)=>{
175
197
  const ack = parseAck(payload);
176
- if (ack) options.onAck == null ? void 0 : options.onAck.call(options, ack);
198
+ if (ack && ack.documentId === options.session.documentId) {
199
+ inFlight = [];
200
+ options.onAck == null ? void 0 : options.onAck.call(options, ack);
201
+ flush();
202
+ }
177
203
  }));
178
204
  cleanups.push(options.transport.on('presence', (payload)=>{
179
205
  const item = parsePresence(payload);
@@ -198,8 +198,10 @@ const FORBIDDEN = new Set([
198
198
  // TODO: separate dialect function policies through plugin-owned strategies; preserve fail-closed checks.
199
199
  // Allowlisting permits parsing; the selected database still determines function availability.
200
200
  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(' '));
201
- // FROM/JOIN can introduce a parenthesized subquery, not a function call.
202
- 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(' '));
201
+ // SQL keywords introduce grouped expressions/subqueries, not function calls.
202
+ // Their contents are still scanned for unsafe or unknown calls (including inside CASE).
203
+ // Compatibility heuristic, not a SQL grammar: migrate with plugin-owned dialect validation.
204
+ 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 WHERE HAVING CASE WHEN THEN ELSE'.split(' '));
203
205
  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;
204
206
  /**
205
207
  * @deprecated Mixed-dialect Workbench policy. New adapters should own dialect-aware statement
@@ -196,8 +196,10 @@ const FORBIDDEN = new Set([
196
196
  // TODO: separate dialect function policies through plugin-owned strategies; preserve fail-closed checks.
197
197
  // Allowlisting permits parsing; the selected database still determines function availability.
198
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(' '));
199
- // FROM/JOIN can introduce a parenthesized subquery, not a function call.
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(' '));
199
+ // SQL keywords introduce grouped expressions/subqueries, not function calls.
200
+ // Their contents are still scanned for unsafe or unknown calls (including inside CASE).
201
+ // Compatibility heuristic, not a SQL grammar: migrate with plugin-owned dialect validation.
202
+ 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 WHERE HAVING CASE WHEN THEN ELSE'.split(' '));
201
203
  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;
202
204
  /**
203
205
  * @deprecated Mixed-dialect Workbench policy. New adapters should own dialect-aware statement
@@ -13,7 +13,13 @@
13
13
 
14
14
  在专用文档宿主页调用 `installArtifactDocumentFramePolicy(document)`,再挂载 iframe;未安装时 mount 会拒绝挂载。该策略作用于整个宿主页,禁止子框架的 URL 导航;允许 `srcdoc`。不要装到需要加载其他远程 iframe 的应用根文档。
15
15
 
16
- `mountArtifactDocument(frame, { html, dependencies, context, query, onBusy, onResult, onError })` 返回 `refresh()` 和 `dispose()`。上下文只含 Binding ID(最多 64 个)、默认控件值(最多 24 个)、语言及主题;它在挂载时严格校验并复制,后续修改原对象不会扩大允许的 Binding 集合。Artifact ID、版本和身份由可信回调闭包持有,不交给文档选择。
16
+ `mountArtifactDocument(frame, { html, dependencies, networkPolicy, context, query, onBusy, onResult, onError })` 返回 `refresh()` 和 `dispose()`。上下文只含 Binding ID(最多 64 个)、默认控件值(最多 24 个)、语言及主题;它在挂载时严格校验并复制,后续修改原对象不会扩大允许的 Binding 集合。Artifact ID、版本和身份由可信回调闭包持有,不交给文档选择。
17
+
18
+ ## 可选在线资源
19
+
20
+ 可信宿主可通过 `networkPolicy` 为 `scripts`、`styles`、`fonts`、`images` 分别指定 HTTPS origin 数组;每类最多 16 项。省略时保持原有离线限制。策略不接受通配符、路径、凭据或额外 CSP 指令,不能由 HTML 或页面消息提供。CSP 在作者 HTML 之前生成,页面无法放宽它。`isArtifactDocumentResourceAllowed(policy, resourceType, url)` 可供预检路由复用相同的资源类型和 origin 检查。
21
+
22
+ 例如 `{ scripts: ['https://cdn.tailwindcss.com'] }` 允许该 origin 的 script 标签加载,但不会开放 fetch/XHR、eval、worker、iframe、宿主存储或额外 Binding 权限。调用方负责资源准入和固定版本;在线资源需要网络,内容不具备打包依赖的不可变快照保证。保存前预检与实际展示必须使用同一策略,加载失败应阻止保存。
17
23
 
18
24
  ## 固定前端依赖
19
25
 
@@ -65,7 +71,7 @@ await live.refresh('sales')
65
71
 
66
72
  ## 隔离边界
67
73
 
68
- HTML 在 `sandbox="allow-scripts"` 内执行,无同源权限、表单、弹窗和下载授权。内容前缀首先安装 CSP,允许内联 JS/CSS 和 data/blob 图片,拒绝网络请求、外部脚本、外部字体、子 iframe、worker、eval、对象和表单。宿主页额外的 frame-src 策略拒绝文档自身导航。
74
+ HTML 在 `sandbox="allow-scripts"` 内执行,无同源权限、表单、弹窗和下载授权。内容前缀首先安装 CSP,允许内联 JS/CSS 和 data/blob 图片。默认拒绝外部资源;可信宿主可显式开启上述 HTTPS 资源白名单。数据网络请求、子 iframe、worker、eval、对象和表单始终拒绝。宿主页额外的 frame-src 策略拒绝文档自身导航。
69
75
 
70
76
  HTML 格式验证不是 sanitizer,也不证明业务正确性。Agent 代码仍可画出错误图形或阻塞自己的文档;业务口径、数值与实际页面都需要验收。该能力不提供后端写操作、任意网络代理或自动推送。
71
77
 
@@ -82,3 +82,106 @@ owns binding authorization, persistence, idempotency, waiting and audit history.
82
82
  The native Xpert graph and native background Task transports are separate
83
83
  strategies behind that same boundary. Providers must not call the Task facade
84
84
  back from their own executor.
85
+
86
+
87
+ ## Artifact source, ownership and resource authorization
88
+
89
+ `pluginName`, `resourceType`, and `resourceId` are the canonical source identity.
90
+ An optional `authorizationProviderKey` selects a registered content resource provider;
91
+ it authorizes that same `resourceId`. It does not change the owner, hide the artifact
92
+ from lists, or replace the share link's audience policy. Missing providers deny access.
93
+
94
+ ```ts
95
+ await artifacts.createArtifact({
96
+ source: { pluginName: '@example/documents', resourceType: 'page', resourceId: page.id },
97
+ authorizationProviderKey: 'example.pages',
98
+ scope: { projectId, userId: null },
99
+ kind: 'markdown',
100
+ title: page.title
101
+ })
102
+ ```
103
+
104
+ Omit `scope.userId` to retain the current runtime user's ownership. Explicitly set it
105
+ to `null` with `projectId` for shared Project ownership. This clears only the stored
106
+ owner; authorization and `createdById` continue using the authenticated actor.
107
+ Project-owned artifacts require current Project read/edit/manage access even without
108
+ a resource provider. Ordinary user-owned artifacts retain their owner restriction
109
+ for management, including when a provider is configured.
110
+
111
+ Repeated creation preserves the resource authorization policy and Project ownership.
112
+ `findArtifactBySource` first resolves the current user's source identity, then a
113
+ Project-owned match, and reauthorizes it. Lists include currently authorized artifacts
114
+ and calculate pagination and totals after authorization. Provider checks currently
115
+ scan candidates in bounded batches; a future bulk-authorize API can optimize large lists.
116
+ Public/signed links still need their own audience/token checks; they cannot bypass a
117
+ protected resource's current ACL or a shared artifact's Project membership.
118
+
119
+
120
+ ## Project content capabilities
121
+
122
+ Content extensions use server-authenticated `RuntimeActor` identities. Organization-bound APIs
123
+ require `OrganizationRuntimeActor`; Project APIs also support tenant-level Projects.
124
+ Never copy actor fields from a view action body. Views derive actors from their resolved host,
125
+ and jobs retain the authorized execution context.
126
+
127
+ | Capability | Responsibility |
128
+ | --- | --- |
129
+ | `platform.assistant.middleware-access` | `assertAccess({ actor, assistantId, scope, provider, requiredFeature })` checks the exact installed middleware using standalone Assistant access or Project membership + binding. Does not grant file/resource operations. |
130
+ | `platform.project.access` | Human membership, editing/management and explicit Assistant binding. |
131
+ | `platform.project.files` | Authorized Project file facade with CAS writes; shares Volume IO with WorkspaceFiles. |
132
+ | `platform.project.knowledge` | `ensureBinding({ actor, projectId, title })` creates/binds one Project-owned knowledge library. |
133
+ | `platform.content.resources` | Resource authorization, plus an `identities` subinterface for organization principal/directory resolution. |
134
+ | `platform.content.documents` | Model-backed collaborative documents, immutable revisions, publication and Assistant review. |
135
+ | `platform.content.references` | Authorize containing document and target before dispatching reference hooks. |
136
+ | `platform.content.editors` | Editor discovery and resource routing; versioned opaque file IO with Project and source ACL checks. Concrete formats and edit operations belong to plugins. |
137
+ | `platform.connector.documents` | Credential-bound remote document discovery/read; no implicit synchronization or remote write-back. |
138
+
139
+ `IContentResourceProvider.authorize` is mandatory. Optional `references`, `pages`, `publication`
140
+ and `locations` extension objects are independently composed in the same registration. Registering
141
+ an extension never grants access. The platform authorizes first, and the plugin validates its
142
+ source-specific relationships. Publication/location callbacks must tolerate retry.
143
+
144
+ `ContentDocumentInput.resourceId` identifies the **platform document**. `ContentSourceInput.sourceResourceId`
145
+ identifies the **provider's source**; never exchange them just because one plugin happens to use
146
+ the same UUID for both. `createChildPage` returns `{ documentId }`, reauthorized in the original Project.
147
+
148
+ Create/register a Markdown file directly through `ContentDocuments.register`. There is no old
149
+ editor migration API. Markdown model state stays in the platform; Spaces does not own parallel
150
+ collaboration rooms or review tables. Spreadsheet adapters only convert bytes to/from a typed grid;
151
+ callers still own source ACL, file versions and conflict handling.
152
+
153
+ Knowledge binding uses `platform.project` resource authority, independent of a Spaces installation.
154
+ Provisioning reuses the knowledge pipeline and requires its request/job context to match the explicit
155
+ actor. Project membership changes apply immediately to the bound library.
156
+
157
+ View providers that need middleware configuration or a scoped runtime use
158
+ `ViewMiddlewareRuntimeCapability.resolve({ context, provider, requiredFeature })`.
159
+ For capability entry points needing only an access assertion (Views, tools or trusted persisted jobs),
160
+ use `AssistantMiddlewareAccessRuntimeCapability.assertAccess` once per invocation:
161
+
162
+ ```ts
163
+ await access.assertAccess({
164
+ actor, assistantId, provider: 'spaces', requiredFeature: 'spaces',
165
+ scope: projectId ? { type: 'project', projectId } : { type: 'assistant' }
166
+ })
167
+ ```
168
+
169
+ The actor and scope come from trusted server context, not iframe/tool input. `assistant` scope
170
+ uses the published Assistant catalog policy. `project` scope uses current Project membership
171
+ and the requested Assistant binding, without adding catalog/workspace visibility requirements.
172
+ Project denial never falls back to standalone authority. Both scopes check active organization
173
+ membership and the requested published Assistant's graph. Resource services retain their own
174
+ Project, binding and operation ACLs; do not repeat middleware authorization per document or
175
+ collaboration recipient. Removing a feature disables its entry points, not the Project's documents.
176
+ Both share the same connected-provider/feature resolver; feature flags or a different provider
177
+ advertising the same feature are not authorization. Multiple connections to the requested provider
178
+ are rejected as ambiguous. There is no cross-request authorization cache.
179
+ Explicit-actor access is independent of content-resource identities and the ambient sender's credentials.
180
+
181
+ ### File editors and text collaboration
182
+
183
+ Register editors with `@ContentEditorProvider(key)`. Metadata identifies the remote view and distinguishes `text-document` (Yjs model) from `file` (versioned binary codec). `ContentEditorRegistry.getTextModel` is reserved for the text collaboration pipeline.
184
+
185
+ A file editor supplies `create` and `validateFile`; its own service and Remote View implement concrete models and edit operations. The platform has no cell, workbook, slide or format patch protocol. A content resource provider exposes `editor.describe` and optional `editor.files.read/write` hooks. It owns location and atomic revision checks. Every capability call verifies the live actor, Project, Assistant binding and source permissions.
186
+
187
+ Use `workbench.content.resolve` with `{ resourceId, providerKey }`, then pass the returned `navigation` unchanged to `workbench.navigation.open`. The returned parameters preserve the source provider. Do not navigate the outer host or infer an editor from a filename in the remote UI. Text documents continue to use `platform.content.documents`; raw file writes cannot bypass its collaboration/publication pipeline.