@xpert-ai/plugin-sdk 3.36.0 → 3.37.2

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/index.cjs.js CHANGED
@@ -5224,6 +5224,105 @@ function resolveSandboxBackend(sandbox) {
5224
5224
  return isSandboxBackend(candidate) ? candidate : null;
5225
5225
  }
5226
5226
 
5227
+ // Embedded in the existing sandbox Node process; no Git, subprocess, or temporary files.
5228
+ const FILE_EDIT_DIFF_SCRIPT = String.raw`
5229
+ function inspectLineDiff(before, after) {
5230
+ if (before === after) return { diff: { removed: 0, added: 0 } };
5231
+ // Include line terminators so a missing final newline is an actual line change.
5232
+ const oldLines = before.match(/[^\n]*\n|[^\n]+$/g) || [];
5233
+ const newLines = after.match(/[^\n]*\n|[^\n]+$/g) || [];
5234
+ let start = 0, oldEnd = oldLines.length, newEnd = newLines.length;
5235
+ while (start < oldEnd && start < newEnd && oldLines[start] === newLines[start]) start++;
5236
+ while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
5237
+ oldEnd--;
5238
+ newEnd--;
5239
+ }
5240
+ const removed = oldEnd - start, added = newEnd - start;
5241
+ if (!removed || !added) return { diff: { removed, added } };
5242
+
5243
+ // Myers shortest edit distance needs only a frontier when reporting counts, not a patch.
5244
+ // Bound the optional quadratic search on broad rewrites; never limit the edit itself.
5245
+ const maxDistance = Math.min(removed + added, 2000);
5246
+ const offset = maxDistance + 1;
5247
+ const frontier = new Int32Array(2 * maxDistance + 3);
5248
+ let work = 0;
5249
+ for (let distance = 0; distance <= maxDistance; distance++) {
5250
+ for (let diagonal = -distance; diagonal <= distance; diagonal += 2) {
5251
+ if (++work > 1000000) return { diffUnavailable: 'comparison_budget_exceeded' };
5252
+ const index = offset + diagonal;
5253
+ let x = diagonal === -distance || (diagonal !== distance && frontier[index - 1] < frontier[index + 1])
5254
+ ? frontier[index + 1]
5255
+ : frontier[index - 1] + 1;
5256
+ let y = x - diagonal;
5257
+ while (x < removed && y < added && oldLines[start + x] === newLines[start + y]) {
5258
+ if (++work > 1000000) return { diffUnavailable: 'comparison_budget_exceeded' };
5259
+ x++;
5260
+ y++;
5261
+ }
5262
+ if (x >= removed && y >= added) {
5263
+ return { diff: { removed: (distance + removed - added) / 2, added: (distance + added - removed) / 2 } };
5264
+ }
5265
+ frontier[index] = x;
5266
+ }
5267
+ }
5268
+ return { diffUnavailable: 'comparison_budget_exceeded' };
5269
+ }
5270
+ `;
5271
+
5272
+ // The same comparison runs for single and grouped edits. Only values encoded as
5273
+ // JSON/base64 enter the shell, never literal paths or replacement strings.
5274
+ function command(filePath, edits, batch) {
5275
+ const encoded = Buffer.from(JSON.stringify({
5276
+ filePath,
5277
+ edits,
5278
+ batch
5279
+ })).toString('base64');
5280
+ const script = `
5281
+ const fs = require('node:fs');
5282
+ const input = JSON.parse(Buffer.from('${encoded}', 'base64').toString('utf8'));
5283
+ const lines = text => text.length ? text.split('\\n').length - Number(text.endsWith('\\n')) : 0;
5284
+ ${FILE_EDIT_DIFF_SCRIPT}
5285
+ let source;
5286
+ try { source = fs.readFileSync(input.filePath, 'utf8'); } catch {}
5287
+ let content = source;
5288
+ const steps = [];
5289
+ for (const edit of input.edits) {
5290
+ const metrics = { oldLines: lines(edit.oldString), newLines: lines(edit.newString) };
5291
+ const parts = content === undefined ? [] : content.split(edit.oldString);
5292
+ const count = parts.length - 1;
5293
+ const code = content === undefined ? 3 : count === 0 ? 1 : count > 1 && !edit.replaceAll ? 2 : 0;
5294
+ if (code) {
5295
+ steps.push({ code, metrics: { ...metrics, occurrences: 0, changed: false, diff: { removed: 0, added: 0 } } });
5296
+ break;
5297
+ }
5298
+ const after = parts.join(edit.newString);
5299
+ try { Object.assign(metrics, inspectLineDiff(content, after)); } catch { metrics.diffUnavailable = 'diff_unavailable'; }
5300
+ // A direct SDK edit of empty search text in an empty file historically reports one no-op.
5301
+ const occurrences = input.batch && count < 0 ? 1 : count;
5302
+ steps.push({ code, metrics: { ...metrics, occurrences, changed: content !== after } });
5303
+ content = after;
5304
+ }
5305
+ // A logical mismatch commits its valid prefix. An I/O failure must never emit
5306
+ // a successful receipt (or cause the host to replay a possibly committed edit).
5307
+ if (source !== content) fs.writeFileSync(input.filePath, content, 'utf8');
5308
+ if (input.batch) console.log(JSON.stringify(steps));
5309
+ else { console.log(JSON.stringify(steps[0].metrics)); process.exitCode = steps[0].code; }
5310
+ `;
5311
+ return `node -e '${script.replace(/'/g, "'\\''")}'`;
5312
+ }
5313
+ function buildEditCommand(filePath, oldString, newString, replaceAll) {
5314
+ return command(filePath, [
5315
+ {
5316
+ oldString,
5317
+ newString,
5318
+ replaceAll
5319
+ }
5320
+ ], false);
5321
+ }
5322
+ function buildBatchEditCommand(filePath, edits) {
5323
+ return command(filePath, edits, true);
5324
+ }
5325
+
5227
5326
  const editMetricsSchema = v3.z.object({
5228
5327
  occurrences: v3.z.number().int().nonnegative(),
5229
5328
  oldLines: v3.z.number().int().nonnegative(),
@@ -5283,121 +5382,124 @@ function editCommandResult(filePath, result) {
5283
5382
  };
5284
5383
  }
5285
5384
  }
5286
- /** Stops on failure; never promises rollback or silently reapplies completed edits. */ async function sequentialFileEdits(filePath, edits, apply) {
5287
- const results = [];
5288
- if (!(edits == null ? void 0 : edits.length)) return {
5385
+ function sequenceResult(path, results) {
5386
+ const count = results.length;
5387
+ if (!count) return {
5289
5388
  error: 'No edits provided',
5290
5389
  progress: {
5291
5390
  mode: 'sequential',
5292
5391
  appliedEdits: 0
5293
5392
  }
5294
5393
  };
5295
- for (const edit of edits){
5296
- const result = await apply(edit);
5297
- results.push(result);
5298
- if (result.error) return {
5299
- error: `Multi-edit failed at edit ${results.length}: ${result.error}`,
5300
- path: filePath,
5394
+ const last = results[count - 1];
5395
+ if (last.error) {
5396
+ return {
5397
+ path,
5301
5398
  filesUpdate: null,
5302
5399
  results,
5400
+ error: `Multi-edit failed at edit ${count}: ${last.error}`,
5303
5401
  progress: {
5304
5402
  mode: 'sequential',
5305
- appliedEdits: results.length - 1,
5306
- failedEdit: results.length
5403
+ appliedEdits: count - 1,
5404
+ failedEdit: count
5307
5405
  }
5308
5406
  };
5309
5407
  }
5310
5408
  return {
5311
- path: filePath,
5409
+ path,
5312
5410
  filesUpdate: null,
5313
5411
  results,
5314
5412
  progress: {
5315
5413
  mode: 'sequential',
5316
- appliedEdits: results.length
5414
+ appliedEdits: count
5317
5415
  }
5318
5416
  };
5319
5417
  }
5320
-
5321
- // Embedded in the existing sandbox Node process; no Git, subprocess, or temporary files.
5322
- const FILE_EDIT_DIFF_SCRIPT = String.raw`
5323
- function inspectLineDiff(before, after) {
5324
- if (before === after) return { diff: { removed: 0, added: 0 } };
5325
- // Include line terminators so a missing final newline is an actual line change.
5326
- const oldLines = before.match(/[^\n]*\n|[^\n]+$/g) || [];
5327
- const newLines = after.match(/[^\n]*\n|[^\n]+$/g) || [];
5328
- let start = 0, oldEnd = oldLines.length, newEnd = newLines.length;
5329
- while (start < oldEnd && start < newEnd && oldLines[start] === newLines[start]) start++;
5330
- while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
5331
- oldEnd--;
5332
- newEnd--;
5333
- }
5334
- const removed = oldEnd - start, added = newEnd - start;
5335
- if (!removed || !added) return { diff: { removed, added } };
5336
-
5337
- // Myers shortest edit distance needs only a frontier when reporting counts, not a patch.
5338
- // Bound the optional quadratic search on broad rewrites; never limit the edit itself.
5339
- const maxDistance = Math.min(removed + added, 2000);
5340
- const offset = maxDistance + 1;
5341
- const frontier = new Int32Array(2 * maxDistance + 3);
5342
- let work = 0;
5343
- for (let distance = 0; distance <= maxDistance; distance++) {
5344
- for (let diagonal = -distance; diagonal <= distance; diagonal += 2) {
5345
- if (++work > 1000000) return { diffUnavailable: 'comparison_budget_exceeded' };
5346
- const index = offset + diagonal;
5347
- let x = diagonal === -distance || (diagonal !== distance && frontier[index - 1] < frontier[index + 1])
5348
- ? frontier[index + 1]
5349
- : frontier[index - 1] + 1;
5350
- let y = x - diagonal;
5351
- while (x < removed && y < added && oldLines[start + x] === newLines[start + y]) {
5352
- if (++work > 1000000) return { diffUnavailable: 'comparison_budget_exceeded' };
5353
- x++;
5354
- y++;
5355
- }
5356
- if (x >= removed && y >= added) {
5357
- return { diff: { removed: (distance + removed - added) / 2, added: (distance + added - removed) / 2 } };
5358
- }
5359
- frontier[index] = x;
5418
+ /** Stops on failure; never promises rollback or silently reapplies completed edits. */ async function sequentialFileEdits(filePath, edits, apply) {
5419
+ const results = [];
5420
+ for (const edit of edits != null ? edits : []){
5421
+ const result = await apply(edit);
5422
+ results.push(result);
5423
+ if (result.error) break;
5424
+ }
5425
+ return sequenceResult(filePath, results);
5426
+ }
5427
+ const batchReceiptSchema = v3.z.array(v3.z.object({
5428
+ code: v3.z.union([
5429
+ v3.z.literal(0),
5430
+ v3.z.literal(1),
5431
+ v3.z.literal(2),
5432
+ v3.z.literal(3)
5433
+ ]),
5434
+ metrics: editMetricsSchema
5435
+ }));
5436
+ function batchSteps(output, count) {
5437
+ let raw;
5438
+ try {
5439
+ raw = JSON.parse(output);
5440
+ } catch (e) {
5441
+ return undefined;
5360
5442
  }
5361
- }
5362
- return { diffUnavailable: 'comparison_budget_exceeded' };
5363
- }
5364
- `;
5365
-
5366
- /** Compare actual file contents inside the sandbox; reporting must never prevent an edit. */ function buildEditCommand(filePath, oldString, newString, replaceAll) {
5367
- const encoded = Buffer.from(JSON.stringify({
5368
- filePath,
5369
- oldString,
5370
- newString,
5371
- replaceAll
5372
- })).toString('base64');
5373
- const script = `
5374
- const fs = require('node:fs');
5375
- const input = JSON.parse(Buffer.from('${encoded}', 'base64').toString('utf8'));
5376
- const lines = text => text.length ? text.split('\\n').length - Number(text.endsWith('\\n')) : 0;
5377
- const metrics = { oldLines: lines(input.oldString), newLines: lines(input.newString) };
5378
-
5379
- ${FILE_EDIT_DIFF_SCRIPT}
5380
-
5381
- function unchanged(exitCode) {
5382
- console.log(JSON.stringify({ ...metrics, occurrences: 0, changed: false, diff: { removed: 0, added: 0 } }));
5383
- process.exit(exitCode);
5384
- }
5385
- let before;
5386
- try { before = fs.readFileSync(input.filePath, 'utf8'); } catch { unchanged(3); }
5387
- const occurrences = before.split(input.oldString).length - 1;
5388
- if (occurrences === 0) unchanged(1);
5389
- if (occurrences > 1 && !input.replaceAll) unchanged(2);
5390
- const after = before.split(input.oldString).join(input.newString);
5391
- const changed = before !== after;
5392
- if (changed) fs.writeFileSync(input.filePath, after, 'utf8');
5393
- try {
5394
- Object.assign(metrics, inspectLineDiff(before, after));
5395
- } catch {
5396
- metrics.diffUnavailable = 'diff_unavailable';
5397
- }
5398
- console.log(JSON.stringify({ ...metrics, occurrences, changed }));
5399
- `;
5400
- return `node -e '${script.replace(/'/g, "'\\''")}'`;
5443
+ const parsed = batchReceiptSchema.safeParse(raw);
5444
+ if (!parsed.success) return undefined;
5445
+ const steps = parsed.data;
5446
+ const failure = steps.findIndex((step)=>step.code !== 0);
5447
+ if (!steps.length || steps.length > count) return undefined;
5448
+ if (steps.some(({ code, metrics })=>code === 0 ? metrics.occurrences === 0 : metrics.changed || metrics.occurrences !== 0)) return undefined;
5449
+ if (failure < 0 ? steps.length !== count : failure !== steps.length - 1) return undefined;
5450
+ return steps;
5451
+ }
5452
+ /** Keep the encoded shell argument bounded. An oversized edit runs alone. */ function batchEnd(path, edits, start) {
5453
+ let bytes = Buffer.byteLength(JSON.stringify(path));
5454
+ let end = start;
5455
+ while(end < edits.length && end - start < 32){
5456
+ bytes += Buffer.byteLength(JSON.stringify(edits[end])) + 1;
5457
+ if (bytes > 64 * 1024) break;
5458
+ end++;
5459
+ }
5460
+ return Math.max(start + 1, end);
5461
+ }
5462
+ async function groupedFileEdits(path, edits, execute) {
5463
+ const results = [];
5464
+ var _edits_length;
5465
+ while(results.length < ((_edits_length = edits == null ? void 0 : edits.length) != null ? _edits_length : 0)){
5466
+ const start = results.length;
5467
+ const end = batchEnd(path, edits, start);
5468
+ const unconfirmed = (reason)=>({
5469
+ path,
5470
+ filesUpdate: null,
5471
+ results,
5472
+ error: `Sandbox multi-edit: ${reason}. Read the current file before retrying edits ${start + 1}–${end}.`,
5473
+ progress: {
5474
+ mode: 'sequential',
5475
+ appliedEdits: start,
5476
+ unconfirmedEdits: {
5477
+ from: start + 1,
5478
+ to: end
5479
+ }
5480
+ }
5481
+ });
5482
+ const command = buildBatchEditCommand(path, edits.slice(start, end));
5483
+ let response;
5484
+ try {
5485
+ response = await execute(command);
5486
+ } catch (e) {
5487
+ return unconfirmed('execution receipt unavailable');
5488
+ }
5489
+ if (response.timedOut) return unconfirmed('execution timed out');
5490
+ if (response.terminationReason) return unconfirmed(`execution terminated (${response.terminationReason})`);
5491
+ if (response.exitCode !== 0) return unconfirmed('execution did not exit successfully');
5492
+ if (response.truncated) return unconfirmed('truncated execution receipt');
5493
+ const steps = batchSteps(response.output, end - start);
5494
+ if (!steps) return unconfirmed('invalid execution receipt');
5495
+ for (const step of steps){
5496
+ results.push(editCommandResult(path, {
5497
+ output: JSON.stringify(step.metrics),
5498
+ exitCode: step.code}));
5499
+ }
5500
+ if (results[results.length - 1].error) break;
5501
+ }
5502
+ return sequenceResult(path, results);
5401
5503
  }
5402
5504
 
5403
5505
  const INDENTATION_SPACES = 2;
@@ -6226,10 +6328,13 @@ try {
6226
6328
  return editCommandResult(filePath, result);
6227
6329
  }
6228
6330
  /** Earlier successful edits remain persisted if a later edit fails. */ multiEdit(filePath, edits) {
6229
- return sequentialFileEdits(filePath, edits, (edit)=>{
6331
+ const single = (edit)=>{
6230
6332
  var _edit_replaceAll;
6231
6333
  return this.edit(filePath, edit.oldString, edit.newString, (_edit_replaceAll = edit.replaceAll) != null ? _edit_replaceAll : false);
6232
- });
6334
+ };
6335
+ // Backends with their own edit storage/authorization semantics retain that implementation.
6336
+ if (this.edit !== BaseSandbox.prototype.edit) return sequentialFileEdits(filePath, edits, single);
6337
+ return groupedFileEdits(filePath, edits, (command)=>this.executeOperation(command, DEFAULT_SANDBOX_FILE_OPERATION_EXECUTION_OPTIONS));
6233
6338
  }
6234
6339
  }
6235
6340
 
@@ -6904,6 +7009,13 @@ const ViewMiddlewareRuntimeCapability = modelProvider.createRuntimeCapability('p
6904
7009
  description: 'Resolve a View capability through its authorized Assistant middleware and scoped runtime.'
6905
7010
  });
6906
7011
 
7012
+ /**
7013
+ * Lets a plugin's server-side View provider submit a human decision during an authorized
7014
+ * assistant or project workbench action. The host takes the actor and plugin identity from
7015
+ * the current action and routes the submission to their active source binding.
7016
+ * The event source checks who can decide the business matter and records the choice.
7017
+ */ const WorkbenchDecisionCapability = modelProvider.createRuntimeCapability('platform.view.workbench-decision');
7018
+
6907
7019
  const ARTIFACT_PRESENTATION_PROVIDER = 'ARTIFACT_PRESENTATION_PROVIDER';
6908
7020
  const artifactPresentationKey = (source)=>`${source.pluginName}:${source.resourceType}`;
6909
7021
  /** Registers a read-only renderer for an explicit Artifact source, independently of Workbench actions. */ const ArtifactPresentationProvider = (source)=>common.applyDecorators(common.SetMetadata(ARTIFACT_PRESENTATION_PROVIDER, artifactPresentationKey(source)), common.SetMetadata(STRATEGY_META_KEY, ARTIFACT_PRESENTATION_PROVIDER));
@@ -11633,6 +11745,14 @@ Object.defineProperty(exports, "createResourceCardContent", {
11633
11745
  enumerable: true,
11634
11746
  get: function () { return contracts.createResourceCardContent; }
11635
11747
  });
11748
+ Object.defineProperty(exports, "humanDecisionInputSchema", {
11749
+ enumerable: true,
11750
+ get: function () { return contracts.humanDecisionInputSchema; }
11751
+ });
11752
+ Object.defineProperty(exports, "humanDecisionSchema", {
11753
+ enumerable: true,
11754
+ get: function () { return contracts.humanDecisionSchema; }
11755
+ });
11636
11756
  Object.defineProperty(exports, "parseResourceCard", {
11637
11757
  enumerable: true,
11638
11758
  get: function () { return contracts.parseResourceCard; }
@@ -11946,6 +12066,7 @@ exports.ViewExtensionProvider = ViewExtensionProvider;
11946
12066
  exports.ViewMiddlewareRuntimeCapability = ViewMiddlewareRuntimeCapability;
11947
12067
  exports.WORKFLOW_NODE_STRATEGY = WORKFLOW_NODE_STRATEGY;
11948
12068
  exports.WORKFLOW_TRIGGER_STRATEGY = WORKFLOW_TRIGGER_STRATEGY;
12069
+ exports.WorkbenchDecisionCapability = WorkbenchDecisionCapability;
11949
12070
  exports.WorkflowNodeStrategy = WorkflowNodeStrategy;
11950
12071
  exports.WorkflowTriggerStrategy = WorkflowTriggerStrategy;
11951
12072
  exports.WrapWorkflowNodeExecutionCommand = WrapWorkflowNodeExecutionCommand;