@beyondwork/docx-react-component 1.0.136 → 1.0.137

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 (56) hide show
  1. package/dist/api/public-types.d.cts +1 -1
  2. package/dist/api/public-types.d.ts +1 -1
  3. package/dist/api/v3.cjs +645 -21
  4. package/dist/api/v3.d.cts +2 -2
  5. package/dist/api/v3.d.ts +2 -2
  6. package/dist/api/v3.js +2 -2
  7. package/dist/{chunk-NX7W6T7L.js → chunk-M3AEVSKU.js} +626 -21
  8. package/dist/{chunk-HUWZ7AHE.js → chunk-NYIMPM3Z.js} +20 -1
  9. package/dist/{chunk-JZZKTL7K.js → chunk-SMBDQV73.js} +141 -80
  10. package/dist/core/commands/formatting-commands.d.cts +1 -1
  11. package/dist/core/commands/formatting-commands.d.ts +1 -1
  12. package/dist/core/commands/image-commands.d.cts +1 -1
  13. package/dist/core/commands/image-commands.d.ts +1 -1
  14. package/dist/core/commands/section-layout-commands.d.cts +1 -1
  15. package/dist/core/commands/section-layout-commands.d.ts +1 -1
  16. package/dist/core/commands/style-commands.d.cts +1 -1
  17. package/dist/core/commands/style-commands.d.ts +1 -1
  18. package/dist/core/commands/table-structure-commands.d.cts +1 -1
  19. package/dist/core/commands/table-structure-commands.d.ts +1 -1
  20. package/dist/core/commands/text-commands.d.cts +1 -1
  21. package/dist/core/commands/text-commands.d.ts +1 -1
  22. package/dist/core/selection/mapping.d.cts +1 -1
  23. package/dist/core/selection/mapping.d.ts +1 -1
  24. package/dist/core/state/editor-state.d.cts +1 -1
  25. package/dist/core/state/editor-state.d.ts +1 -1
  26. package/dist/index.cjs +808 -111
  27. package/dist/index.d.cts +4 -4
  28. package/dist/index.d.ts +4 -4
  29. package/dist/index.js +26 -14
  30. package/dist/io/docx-session.d.cts +3 -3
  31. package/dist/io/docx-session.d.ts +3 -3
  32. package/dist/{loader-Cr35kVUi.d.cts → loader-BB7tRkY2.d.cts} +2 -2
  33. package/dist/{loader-uGY6nDZP.d.ts → loader-DGPbaboy.d.ts} +2 -2
  34. package/dist/{public-types-CSSH2Whc.d.cts → public-types-CIvw1GQa.d.cts} +126 -1
  35. package/dist/{public-types-8kVIB5HW.d.ts → public-types-COCDrgVX.d.ts} +126 -1
  36. package/dist/public-types.d.cts +1 -1
  37. package/dist/public-types.d.ts +1 -1
  38. package/dist/runtime/collab.d.cts +2 -2
  39. package/dist/runtime/collab.d.ts +2 -2
  40. package/dist/runtime/document-runtime.cjs +160 -80
  41. package/dist/runtime/document-runtime.d.cts +1 -1
  42. package/dist/runtime/document-runtime.d.ts +1 -1
  43. package/dist/runtime/document-runtime.js +2 -2
  44. package/dist/{session-Beg8ihOi.d.cts → session-CVU-rtCd.d.cts} +2 -2
  45. package/dist/{session-Dgp-2uYw.d.ts → session-DOqy1-Lf.d.ts} +2 -2
  46. package/dist/session.d.cts +4 -4
  47. package/dist/session.d.ts +4 -4
  48. package/dist/tailwind.d.cts +1 -1
  49. package/dist/tailwind.d.ts +1 -1
  50. package/dist/{types-Cin_abw3.d.ts → types-CB_tOnVp.d.ts} +1 -1
  51. package/dist/{types-qsS39ZkQ.d.cts → types-CZAll7OS.d.cts} +1 -1
  52. package/dist/ui-tailwind/editor-surface/search-plugin.d.cts +2 -2
  53. package/dist/ui-tailwind/editor-surface/search-plugin.d.ts +2 -2
  54. package/dist/ui-tailwind.d.cts +2 -2
  55. package/dist/ui-tailwind.d.ts +2 -2
  56. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -50258,13 +50258,32 @@ function storyKeyFromHandle(handle) {
50258
50258
  function textLeafEditableTargetHint(entry, semanticBlockRange) {
50259
50259
  const storyKey2 = storyKeyFromHandle(entry.handle);
50260
50260
  if (!storyKey2) return void 0;
50261
+ const semanticBlockPath = textLeafBlockPathFromSemanticPath(entry.handle.semanticPath, storyKey2);
50261
50262
  return {
50262
50263
  kind: "text-leaf",
50263
50264
  storyKey: storyKey2,
50264
- blockPath: `${storyKey2}/block[${entry.blockIndex}]`,
50265
+ blockPath: semanticBlockPath ?? `${storyKey2}/block[${entry.blockIndex}]`,
50265
50266
  semanticBlockRange
50266
50267
  };
50267
50268
  }
50269
+ function textLeafBlockPathFromSemanticPath(semanticPath, storyKey2) {
50270
+ if (!semanticPath) return null;
50271
+ const tableIndex = semanticPath.indexOf("table");
50272
+ const rowIndex = semanticPath.indexOf("row", tableIndex + 1);
50273
+ const cellIndex = semanticPath.indexOf("cell", rowIndex + 1);
50274
+ const paragraphIndex = semanticPath.indexOf("paragraph", cellIndex + 1);
50275
+ if (tableIndex < 0 || rowIndex < 0 || cellIndex < 0 || paragraphIndex < 0) {
50276
+ return null;
50277
+ }
50278
+ const table = Number(semanticPath[tableIndex + 1]);
50279
+ const row2 = Number(semanticPath[rowIndex + 1]);
50280
+ const cell = Number(semanticPath[cellIndex + 1]);
50281
+ const paragraph = Number(semanticPath[paragraphIndex + 1]);
50282
+ if (!Number.isInteger(table) || !Number.isInteger(row2) || !Number.isInteger(cell) || !Number.isInteger(paragraph)) {
50283
+ return null;
50284
+ }
50285
+ return `${storyKey2}/block[${table}]/row[${row2}]/cell[${cell}]/block[${paragraph}]`;
50286
+ }
50268
50287
  function compileParagraphReplacement(entry, proposed, options) {
50269
50288
  if (proposed.operation !== "replace" && proposed.operation !== "insert-before" && proposed.operation !== "insert-after") {
50270
50289
  return null;
@@ -57631,81 +57650,83 @@ function createWorkflowCoordinator(deps) {
57631
57650
  }
57632
57651
  function addScopes(paramsList) {
57633
57652
  if (paramsList.length === 0) return [];
57634
- let nextDocument = deps.getDocument();
57635
- let documentChanged = false;
57636
- const results = [];
57637
- const scopesToAdd = [];
57638
- const metadataEntriesToAdd = [];
57639
- const newScopeIds = /* @__PURE__ */ new Set();
57640
- for (const params of paramsList) {
57641
- const scopeId = params.scopeId ?? `scope-${clock().replace(/[^0-9]/gu, "")}-${Math.floor(Math.random() * 1e6)}`;
57642
- const anchor = params.anchor.kind === "range" ? { from: params.anchor.from, to: params.anchor.to } : null;
57643
- if (!anchor) {
57644
- results.push({ scopeId, anchor: params.anchor });
57645
- continue;
57653
+ return deps.runInRuntimeBatch("workflow.addScopes", () => {
57654
+ let nextDocument = deps.getDocument();
57655
+ let documentChanged = false;
57656
+ const results = [];
57657
+ const scopesToAdd = [];
57658
+ const metadataEntriesToAdd = [];
57659
+ const newScopeIds = /* @__PURE__ */ new Set();
57660
+ for (const params of paramsList) {
57661
+ const scopeId = params.scopeId ?? `scope-${clock().replace(/[^0-9]/gu, "")}-${Math.floor(Math.random() * 1e6)}`;
57662
+ const anchor = params.anchor.kind === "range" ? { from: params.anchor.from, to: params.anchor.to } : null;
57663
+ if (!anchor) {
57664
+ results.push({ scopeId, anchor: params.anchor });
57665
+ continue;
57666
+ }
57667
+ const callerAssoc = params.anchor.kind === "range" ? params.anchor.assoc : { start: -1, end: 1 };
57668
+ const plantResult = insertScopeMarkers(nextDocument, {
57669
+ scopeId,
57670
+ from: anchor.from,
57671
+ to: anchor.to
57672
+ });
57673
+ if (plantResult.status !== "planted") {
57674
+ results.push(
57675
+ createPlantFailureResult({
57676
+ scopeId,
57677
+ anchor,
57678
+ assoc: callerAssoc,
57679
+ plantResult
57680
+ })
57681
+ );
57682
+ continue;
57683
+ }
57684
+ nextDocument = plantResult.document;
57685
+ documentChanged = true;
57686
+ const publicAnchor = {
57687
+ kind: "range",
57688
+ from: plantResult.plantedRange.from,
57689
+ to: plantResult.plantedRange.to,
57690
+ assoc: callerAssoc
57691
+ };
57692
+ newScopeIds.add(scopeId);
57693
+ scopesToAdd.push(buildWorkflowScope({ params, scopeId, publicAnchor }));
57694
+ const entry = buildWorkflowMetadataEntry({ params, scopeId, publicAnchor });
57695
+ if (entry) metadataEntriesToAdd.push(entry);
57696
+ results.push({ scopeId, anchor: publicAnchor });
57646
57697
  }
57647
- const callerAssoc = params.anchor.kind === "range" ? params.anchor.assoc : { start: -1, end: 1 };
57648
- const plantResult = insertScopeMarkers(nextDocument, {
57649
- scopeId,
57650
- from: anchor.from,
57651
- to: anchor.to
57652
- });
57653
- if (plantResult.status !== "planted") {
57654
- results.push(
57655
- createPlantFailureResult({
57656
- scopeId,
57657
- anchor,
57658
- assoc: callerAssoc,
57659
- plantResult
57660
- })
57698
+ if (documentChanged) {
57699
+ deps.dispatch({
57700
+ type: "document.replace",
57701
+ document: nextDocument,
57702
+ mapping: createScopeMarkerMutationMapping(),
57703
+ origin: { source: "api", at: clock() }
57704
+ });
57705
+ }
57706
+ if (scopesToAdd.length > 0) {
57707
+ const currentOverlay = overlayStore.getOverlay() ?? {
57708
+ overlayVersion: "workflow-overlay/1",
57709
+ scopes: []
57710
+ };
57711
+ const existingScopes = currentOverlay.scopes.filter(
57712
+ (existing) => !newScopeIds.has(existing.scopeId)
57661
57713
  );
57662
- continue;
57714
+ deps.dispatch({
57715
+ type: "workflow.set-overlay",
57716
+ overlay: { ...currentOverlay, scopes: [...existingScopes, ...scopesToAdd] },
57717
+ origin: { source: "api", at: clock() }
57718
+ });
57663
57719
  }
57664
- nextDocument = plantResult.document;
57665
- documentChanged = true;
57666
- const publicAnchor = {
57667
- kind: "range",
57668
- from: plantResult.plantedRange.from,
57669
- to: plantResult.plantedRange.to,
57670
- assoc: callerAssoc
57671
- };
57672
- newScopeIds.add(scopeId);
57673
- scopesToAdd.push(buildWorkflowScope({ params, scopeId, publicAnchor }));
57674
- const entry = buildWorkflowMetadataEntry({ params, scopeId, publicAnchor });
57675
- if (entry) metadataEntriesToAdd.push(entry);
57676
- results.push({ scopeId, anchor: publicAnchor });
57677
- }
57678
- if (documentChanged) {
57679
- deps.dispatch({
57680
- type: "document.replace",
57681
- document: nextDocument,
57682
- mapping: createScopeMarkerMutationMapping(),
57683
- origin: { source: "api", at: clock() }
57684
- });
57685
- }
57686
- if (scopesToAdd.length > 0) {
57687
- const currentOverlay = overlayStore.getOverlay() ?? {
57688
- overlayVersion: "workflow-overlay/1",
57689
- scopes: []
57690
- };
57691
- const existingScopes = currentOverlay.scopes.filter(
57692
- (existing) => !newScopeIds.has(existing.scopeId)
57693
- );
57694
- deps.dispatch({
57695
- type: "workflow.set-overlay",
57696
- overlay: { ...currentOverlay, scopes: [...existingScopes, ...scopesToAdd] },
57697
- origin: { source: "api", at: clock() }
57698
- });
57699
- }
57700
- if (metadataEntriesToAdd.length > 0) {
57701
- const priorEntries = overlayStore.getMetadataEntries();
57702
- deps.dispatch({
57703
- type: "workflow.set-metadata-entries",
57704
- entries: [...priorEntries, ...metadataEntriesToAdd],
57705
- origin: { source: "api", at: clock() }
57706
- });
57707
- }
57708
- return results;
57720
+ if (metadataEntriesToAdd.length > 0) {
57721
+ const priorEntries = overlayStore.getMetadataEntries();
57722
+ deps.dispatch({
57723
+ type: "workflow.set-metadata-entries",
57724
+ entries: [...priorEntries, ...metadataEntriesToAdd],
57725
+ origin: { source: "api", at: clock() }
57726
+ });
57727
+ }
57728
+ return results;
57729
+ });
57709
57730
  }
57710
57731
  function removeScope(scopeId) {
57711
57732
  const overlay = overlayStore.getOverlay();
@@ -70856,6 +70877,10 @@ function createDocumentRuntime(options) {
70856
70877
  const sessionId = createSessionId(options.documentId, clock());
70857
70878
  const listeners = /* @__PURE__ */ new Set();
70858
70879
  const eventListeners = /* @__PURE__ */ new Set();
70880
+ let runtimeNotificationBatchDepth = 0;
70881
+ let pendingRuntimeListenerNotify = false;
70882
+ let pendingRenderSnapshotRefresh = false;
70883
+ const pendingRuntimeEvents = [];
70859
70884
  const loadScheduler = options.loadScheduler ?? createLoadScheduler({ backendOverride: "sync" });
70860
70885
  let effectiveMarkupModeProvider;
70861
70886
  const perfCounters = new PerfCounters();
@@ -72067,6 +72092,7 @@ function createDocumentRuntime(options) {
72067
72092
  deriveOpaqueWorkflowBlockedReason,
72068
72093
  isBlockedByProtection,
72069
72094
  dispatch: (command) => dispatchToRuntime(command),
72095
+ runInRuntimeBatch: runRuntimeNotificationBatch,
72070
72096
  emitEvent: (event) => emit2(event),
72071
72097
  editorStateChannel,
72072
72098
  suggestingUnsupportedCommands: SUGGESTING_UNSUPPORTED_COMMANDS
@@ -72416,9 +72442,7 @@ function createDocumentRuntime(options) {
72416
72442
  ...cachedRenderSnapshot,
72417
72443
  surface: newSurface
72418
72444
  };
72419
- for (const listener of listeners) {
72420
- listener();
72421
- }
72445
+ notifyRuntimeListeners();
72422
72446
  }
72423
72447
  function maybeRefreshSurfaceForViewport() {
72424
72448
  const fingerprint = `${storyTargetKey(activeStory)}|${viewportRangesKey}|${String(state.selection.anchor)}:${String(state.selection.head)}`;
@@ -75551,9 +75575,7 @@ function createDocumentRuntime(options) {
75551
75575
  code: cleared.code
75552
75576
  });
75553
75577
  }
75554
- for (const listener of listeners) {
75555
- listener();
75556
- }
75578
+ notifyRuntimeListeners();
75557
75579
  }
75558
75580
  function applyTextCommandInActiveStory(command, textOptions = {}) {
75559
75581
  emitStageToken(telemetryBus, "command", "command.dispatch.start", {
@@ -76146,7 +76168,7 @@ function createDocumentRuntime(options) {
76146
76168
  const warningDelta = workflowCoordinator.applyOverlayCommand(
76147
76169
  command,
76148
76170
  () => {
76149
- cachedRenderSnapshot = refreshRenderSnapshot();
76171
+ requestRuntimeRenderSnapshotRefresh();
76150
76172
  }
76151
76173
  );
76152
76174
  if (warningDelta) {
@@ -76204,11 +76226,69 @@ function createDocumentRuntime(options) {
76204
76226
  });
76205
76227
  }
76206
76228
  }
76229
+ notifyRuntimeListeners();
76230
+ }
76231
+ function runRuntimeNotificationBatch(label, fn) {
76232
+ runtimeNotificationBatchDepth += 1;
76233
+ perfCounters.increment(`runtime.notificationBatch.${label}.calls`);
76234
+ try {
76235
+ return fn();
76236
+ } finally {
76237
+ runtimeNotificationBatchDepth -= 1;
76238
+ if (runtimeNotificationBatchDepth === 0) {
76239
+ flushRuntimeNotificationBatch();
76240
+ }
76241
+ }
76242
+ }
76243
+ function requestRuntimeRenderSnapshotRefresh() {
76244
+ if (runtimeNotificationBatchDepth > 0) {
76245
+ pendingRenderSnapshotRefresh = true;
76246
+ perfCounters.increment("runtime.notificationBatch.renderRefreshDeferred");
76247
+ return;
76248
+ }
76249
+ cachedRenderSnapshot = refreshRenderSnapshot();
76250
+ }
76251
+ function notifyRuntimeListeners() {
76252
+ if (runtimeNotificationBatchDepth > 0) {
76253
+ pendingRuntimeListenerNotify = true;
76254
+ perfCounters.increment("runtime.notificationBatch.listenerNotifyDeferred");
76255
+ return;
76256
+ }
76257
+ notifyRuntimeListenersNow();
76258
+ }
76259
+ function notifyRuntimeListenersNow() {
76207
76260
  for (const listener of listeners) {
76208
76261
  listener();
76209
76262
  }
76210
76263
  }
76264
+ function flushRuntimeNotificationBatch() {
76265
+ if (pendingRenderSnapshotRefresh) {
76266
+ pendingRenderSnapshotRefresh = false;
76267
+ cachedRenderSnapshot = refreshRenderSnapshot();
76268
+ perfCounters.increment("runtime.notificationBatch.renderRefreshFlushed");
76269
+ }
76270
+ if (pendingRuntimeEvents.length > 0) {
76271
+ const queuedEvents = pendingRuntimeEvents.splice(0);
76272
+ perfCounters.increment("runtime.notificationBatch.eventsFlushed", queuedEvents.length);
76273
+ for (const event of queuedEvents) {
76274
+ emitInternalNow(event);
76275
+ }
76276
+ }
76277
+ if (pendingRuntimeListenerNotify) {
76278
+ pendingRuntimeListenerNotify = false;
76279
+ perfCounters.increment("runtime.notificationBatch.listenerNotifyFlushed");
76280
+ notifyRuntimeListenersNow();
76281
+ }
76282
+ }
76211
76283
  function emitInternal(event) {
76284
+ if (runtimeNotificationBatchDepth > 0) {
76285
+ pendingRuntimeEvents.push(event);
76286
+ perfCounters.increment("runtime.notificationBatch.eventsQueued");
76287
+ return;
76288
+ }
76289
+ emitInternalNow(event);
76290
+ }
76291
+ function emitInternalNow(event) {
76212
76292
  options.onEvent?.(event);
76213
76293
  for (const listener of eventListeners) {
76214
76294
  listener(event);
@@ -127503,6 +127583,7 @@ var LAYER_DEBUG_PANES = [
127503
127583
  snippets: [
127504
127584
  { label: "Selection context", expression: "ref?.getRuntimeContextAnalytics?.()" },
127505
127585
  { label: "Document context", expression: "ref?.getRuntimeContextAnalytics?.({ scopeKind: 'document' })" },
127586
+ { label: "API families", expression: "api ? Object.keys(api).sort() : null" },
127506
127587
  { label: "Hot edit trace", expression: "runtime?.debug?.getHotEditTraces?.()?.at(-1)" },
127507
127588
  { label: "View state", expression: "ref?.getViewState?.()" }
127508
127589
  ],
@@ -127517,7 +127598,8 @@ var LAYER_DEBUG_PANES = [
127517
127598
  focus: "Workflow scopes, markup, metadata, candidates, and scope-derived context.",
127518
127599
  snippets: [
127519
127600
  { label: "Scope snapshot", expression: "ref?.getWorkflowScopeSnapshot?.()" },
127520
- { label: "Query scopes", expression: "ref?.queryScopes?.({ includeHidden: true, includeInvisible: true, limit: 50 })" },
127601
+ { label: "Query scopes", expression: "api?.runtime.workflow.queryScopes({ includeHidden: true, includeInvisible: true, limit: 50 }) ?? ref?.queryScopes?.({ includeHidden: true, includeInvisible: true, limit: 50 })" },
127602
+ { label: "Bulk placeholder scopes", expression: "(() => { const r = api?.ai.actions.createPlaceholderScopes({ limit: 200 }); if (!r) return { status: 'api-unavailable' }; return { status: r.status, totalHits: r.totalHits, created: r.created, blocked: r.blocked, scopeIds: r.scopes.slice(0, 50).map((s) => s.scopeId ?? null), blockers: r.blockers?.slice(0, 20) ?? [] }; })()" },
127521
127603
  { label: "Workflow markup", expression: "(() => { const m = ref?.getWorkflowMarkupSnapshot?.(); return m ? { itemCount: m.items?.length ?? 0, items: m.items?.slice(0, 50) ?? [] } : m; })()" }
127522
127604
  ],
127523
127605
  routed: [
@@ -127532,7 +127614,8 @@ var LAYER_DEBUG_PANES = [
127532
127614
  snippets: [
127533
127615
  { label: "Document analytics", expression: "ref?.getRuntimeContextAnalytics?.({ scopeKind: 'document' })" },
127534
127616
  { label: "Workflow analytics", expression: "ref?.getRuntimeContextAnalytics?.({ scopeKind: 'workflow_scope', scopeId: ref?.getInteractionGuardSnapshot?.()?.matchedScopeId })" },
127535
- { label: "Available scopes", expression: "ref?.queryScopes?.({ includeHidden: true, includeInvisible: true, limit: 50 })" }
127617
+ { label: "Available scopes", expression: "api?.ai.listScopes({ limit: 50 }) ?? ref?.queryScopes?.({ includeHidden: true, includeInvisible: true, limit: 50 })" },
127618
+ { label: "Placeholder scope action", expression: "api?.ai.actions.createPlaceholderScopes({ limit: 200 })" }
127536
127619
  ],
127537
127620
  routed: [
127538
127621
  "AI audit references and action policy payloads are Layer 09-owned."
@@ -127695,10 +127778,12 @@ function TwRuntimeReplDialog(props) {
127695
127778
  return;
127696
127779
  }
127697
127780
  try {
127781
+ const refValue = editorRef?.current ?? null;
127698
127782
  const value = await evaluateReplExpression(
127699
127783
  code,
127700
127784
  runtime,
127701
- editorRef?.current ?? null
127785
+ refValue,
127786
+ resolveReplApi(refValue)
127702
127787
  );
127703
127788
  pushEntry({
127704
127789
  input: code,
@@ -127803,9 +127888,10 @@ function TwRuntimeReplDialog(props) {
127803
127888
  "evaluates against ",
127804
127889
  /* @__PURE__ */ (0, import_jsx_runtime83.jsx)("code", { children: "runtime" }),
127805
127890
  editorRef ? /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(import_jsx_runtime83.Fragment, { children: [
127806
- " ",
127807
- "and ",
127808
- /* @__PURE__ */ (0, import_jsx_runtime83.jsx)("code", { children: "ref" })
127891
+ ", ",
127892
+ /* @__PURE__ */ (0, import_jsx_runtime83.jsx)("code", { children: "ref" }),
127893
+ ", and ",
127894
+ /* @__PURE__ */ (0, import_jsx_runtime83.jsx)("code", { children: "api" })
127809
127895
  ] }) : null
127810
127896
  ] })
127811
127897
  ] }),
@@ -127952,10 +128038,10 @@ function TwRuntimeReplDialog(props) {
127952
128038
  "data-testid": "tw-runtime-repl__output",
127953
128039
  children: entries.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)("p", { className: "text-[var(--color-text-tertiary)]", children: [
127954
128040
  "Evaluate JavaScript against the active runtime",
127955
- editorRef ? " and editor ref" : "",
128041
+ editorRef ? ", editor ref, and API" : "",
127956
128042
  ". Example:",
127957
128043
  " ",
127958
- /* @__PURE__ */ (0, import_jsx_runtime83.jsx)("code", { children: editorRef ? "ref.getRenderSnapshot().surface?.blocks.length" : "runtime.getRenderSnapshot().surface?.blocks.length" })
128044
+ /* @__PURE__ */ (0, import_jsx_runtime83.jsx)("code", { children: editorRef ? "api.ai.listScopes({ limit: 5 })" : "runtime.getRenderSnapshot().surface?.blocks.length" })
127959
128045
  ] }) : entries.map((entry) => /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)("div", { className: "mb-3 last:mb-0", children: [
127960
128046
  /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)("div", { className: "flex items-start gap-2", children: [
127961
128047
  /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(
@@ -128005,7 +128091,7 @@ function TwRuntimeReplDialog(props) {
128005
128091
  onKeyDown: handleKeyDown,
128006
128092
  rows: 3,
128007
128093
  spellCheck: false,
128008
- placeholder: editorRef ? "ref.getRenderSnapshot().selection" : "runtime.getRenderSnapshot().selection",
128094
+ placeholder: editorRef ? "api.runtime.workflow.queryScopes({ limit: 10 })" : "runtime.getRenderSnapshot().selection",
128009
128095
  className: [
128010
128096
  "w-full resize-y rounded-[var(--radius-sm)] bg-[var(--color-bg-muted)]",
128011
128097
  "px-3 py-2 font-mono text-xs leading-relaxed",
@@ -128038,12 +128124,13 @@ function isReplToggleShortcut(event) {
128038
128124
  if (event.shiftKey) return false;
128039
128125
  return event.metaKey || event.ctrlKey;
128040
128126
  }
128041
- async function evaluateReplExpression(code, runtime, ref = null) {
128127
+ async function evaluateReplExpression(code, runtime, ref = null, api = resolveReplApi(ref)) {
128042
128128
  let fn = null;
128043
128129
  try {
128044
128130
  fn = new Function(
128045
128131
  "runtime",
128046
128132
  "ref",
128133
+ "api",
128047
128134
  `return (async () => { return (${code}); })();`
128048
128135
  );
128049
128136
  } catch (exprError) {
@@ -128053,11 +128140,16 @@ async function evaluateReplExpression(code, runtime, ref = null) {
128053
128140
  fn = new Function(
128054
128141
  "runtime",
128055
128142
  "ref",
128143
+ "api",
128056
128144
  `return (async () => { ${code}
128057
128145
  })();`
128058
128146
  );
128059
128147
  }
128060
- return await fn(runtime, ref);
128148
+ return await fn(runtime, ref, api);
128149
+ }
128150
+ function resolveReplApi(ref) {
128151
+ if (!ref || typeof ref.getApiV3 !== "function") return null;
128152
+ return ref.getApiV3();
128061
128153
  }
128062
128154
  function formatReplValue(value) {
128063
128155
  if (value === void 0) return "undefined";
@@ -129722,6 +129814,29 @@ var createScopeFromAnchorMetadata = {
129722
129814
  broadcastsVia: "crdt",
129723
129815
  rwdReference: "\xA7Runtime API \xA7 runtime.workflow.createScopeFromAnchor. Companion to createScope({blockId}) for sub-block ranges. Consumes from/to once to plant inline scope_marker_start/end; the returned scopeId is the durable reference (KI-P9)."
129724
129816
  };
129817
+ var createScopesMetadata = {
129818
+ name: "runtime.workflow.createScopes",
129819
+ status: "live-with-adapter",
129820
+ sourceLayer: "workflow-review",
129821
+ liveEvidence: {
129822
+ runnerTest: "test/api/v3/workflow-create-scope-live.test.ts",
129823
+ commit: "pending"
129824
+ },
129825
+ uxIntent: {
129826
+ uiVisible: true,
129827
+ expectsUxResponse: "scope-created",
129828
+ expectedDelta: "rail shows new scope chips; editor surface refreshes once after the bulk scope batch"
129829
+ },
129830
+ agentMetadata: {
129831
+ readOrMutate: "mutate",
129832
+ boundedScope: "selection",
129833
+ auditCategory: "scope-creation"
129834
+ },
129835
+ stateClass: "A-canonical",
129836
+ persistsTo: "customXml",
129837
+ broadcastsVia: "crdt",
129838
+ rwdReference: "\xA7Runtime API \xA7 runtime.workflow.createScopes. Bulk companion to createScope/createScopeFromAnchor; resolves blockId/range inputs, plants marker-backed scopes via one runtime addScopes batch, and returns per-item results."
129839
+ };
129725
129840
  var setScopeGuardPolicyMetadata = {
129726
129841
  name: "runtime.workflow.setScopeGuardPolicy",
129727
129842
  status: "live",
@@ -129817,6 +129932,228 @@ var setMarkupModePolicyMetadata = {
129817
129932
  broadcastsVia: "crdt",
129818
129933
  rwdReference: "\xA7Runtime API \xA7 runtime.workflow.setMarkupModePolicy"
129819
129934
  };
129935
+ function isAnchorScopeInput(input) {
129936
+ return "anchor" in input;
129937
+ }
129938
+ function normalizeCreateScopesAnchor(anchor) {
129939
+ const candidate = anchor;
129940
+ const activeRange = candidate.activeRange;
129941
+ if (activeRange?.kind === "range") {
129942
+ return {
129943
+ from: activeRange.from,
129944
+ to: activeRange.to,
129945
+ storyTarget: candidate.storyTarget
129946
+ };
129947
+ }
129948
+ if (candidate.kind === "range") {
129949
+ return {
129950
+ from: candidate.from ?? Number.NaN,
129951
+ to: candidate.to ?? Number.NaN,
129952
+ storyTarget: candidate.storyTarget
129953
+ };
129954
+ }
129955
+ return {
129956
+ from: candidate.from ?? Number.NaN,
129957
+ to: candidate.to ?? Number.NaN,
129958
+ storyTarget: candidate.storyTarget
129959
+ };
129960
+ }
129961
+ function stableRefMetadataFields(stableRefHint) {
129962
+ if (stableRefHint === void 0) return void 0;
129963
+ return [{
129964
+ key: "stableRefHint",
129965
+ valueType: "string",
129966
+ value: stableRefHint
129967
+ }];
129968
+ }
129969
+ function createRangeInvalidResult(inputIndex, reason, from, to, storyLength, detail) {
129970
+ const base = {
129971
+ inputIndex,
129972
+ scopeId: "",
129973
+ status: "range-invalid",
129974
+ reason,
129975
+ from,
129976
+ to,
129977
+ storyLength,
129978
+ ...detail?.blockIndex !== void 0 ? { blockIndex: detail.blockIndex } : {},
129979
+ ...detail?.blockKind !== void 0 ? { blockKind: detail.blockKind } : {}
129980
+ };
129981
+ switch (reason) {
129982
+ case "non-finite-range":
129983
+ return {
129984
+ ...base,
129985
+ message: `createScopes requires finite numeric from/to values (received from=${from}, to=${to}). Pass selection.activeRange or an object shaped as {from, to}.`,
129986
+ nextStep: "pass-selection-activeRange-or-finite-from-to"
129987
+ };
129988
+ case "from-negative":
129989
+ return {
129990
+ ...base,
129991
+ message: `createScopes requires from >= 0 (received from=${from}). Clamp negative values to 0 before calling.`,
129992
+ nextStep: "clamp-from-to-zero"
129993
+ };
129994
+ case "to-less-than-from":
129995
+ return {
129996
+ ...base,
129997
+ message: `createScopes requires to >= from (received from=${from}, to=${to}). Swap the two values before calling.`,
129998
+ nextStep: "swap-from-and-to"
129999
+ };
130000
+ case "range-exceeds-story-length":
130001
+ return {
130002
+ ...base,
130003
+ message: `createScopes requires to <= storyLength (received to=${to}, storyLength=${storyLength}). Re-derive positions from the current document and retry.`,
130004
+ nextStep: "clamp-to-to-storyLength-or-pick-a-different-range"
130005
+ };
130006
+ case "non-paragraph-target":
130007
+ return {
130008
+ ...base,
130009
+ message: `createScopes refused range [${from}, ${to}]: it targets a ${detail?.blockKind ?? "non-paragraph"} block. Pick a paragraph target or use a structural workflow scope.`,
130010
+ nextStep: "pick-a-paragraph-target"
130011
+ };
130012
+ case "empty-document":
130013
+ return {
130014
+ ...base,
130015
+ message: "createScopes refused: the target document has no blocks; initialize a document before creating scopes.",
130016
+ nextStep: "initialize-document-before-creating-scopes"
130017
+ };
130018
+ }
130019
+ }
130020
+ function plantFailureToCreateScopesResult(pending, result) {
130021
+ const status = result.plantStatus;
130022
+ if (!status || status.planted !== false) {
130023
+ return {
130024
+ inputIndex: pending.inputIndex,
130025
+ status: "created",
130026
+ scopeId: result.scopeId
130027
+ };
130028
+ }
130029
+ if (status.reason === "non-paragraph-target") {
130030
+ return createRangeInvalidResult(
130031
+ pending.inputIndex,
130032
+ "non-paragraph-target",
130033
+ pending.from,
130034
+ pending.to,
130035
+ status.storyLength ?? pending.storyLength,
130036
+ {
130037
+ blockIndex: status.blockIndex ?? -1,
130038
+ blockKind: status.blockKind ?? "unknown"
130039
+ }
130040
+ );
130041
+ }
130042
+ if (status.reason === "range-out-of-bounds") {
130043
+ return createRangeInvalidResult(
130044
+ pending.inputIndex,
130045
+ "range-exceeds-story-length",
130046
+ pending.from,
130047
+ pending.to,
130048
+ status.storyLength ?? pending.storyLength
130049
+ );
130050
+ }
130051
+ return createRangeInvalidResult(
130052
+ pending.inputIndex,
130053
+ "empty-document",
130054
+ pending.from,
130055
+ pending.to,
130056
+ status.storyLength ?? pending.storyLength
130057
+ );
130058
+ }
130059
+ function createScopesBulk(runtime, input) {
130060
+ const doc = runtime.getCanonicalDocument();
130061
+ const storyLength = runtime.getRenderSnapshot().surface?.storySize ?? 0;
130062
+ const results = [];
130063
+ const pending = [];
130064
+ input.scopes.forEach((item, inputIndex) => {
130065
+ const assoc = item.assoc ?? { start: 1, end: -1 };
130066
+ const scopeMetadataFields = stableRefMetadataFields(item.stableRefHint);
130067
+ if (isAnchorScopeInput(item)) {
130068
+ const normalizedAnchor = normalizeCreateScopesAnchor(item.anchor);
130069
+ const { from, to } = normalizedAnchor;
130070
+ const itemStoryLength = normalizedAnchor.storyTarget?.kind === void 0 || normalizedAnchor.storyTarget.kind === "main" ? storyLength : Number.MAX_SAFE_INTEGER;
130071
+ if (!Number.isFinite(from) || !Number.isFinite(to)) {
130072
+ results.push(createRangeInvalidResult(inputIndex, "non-finite-range", from, to, itemStoryLength));
130073
+ return;
130074
+ }
130075
+ if (from < 0) {
130076
+ results.push(createRangeInvalidResult(inputIndex, "from-negative", from, to, itemStoryLength));
130077
+ return;
130078
+ }
130079
+ if (to < from) {
130080
+ results.push(createRangeInvalidResult(inputIndex, "to-less-than-from", from, to, itemStoryLength));
130081
+ return;
130082
+ }
130083
+ if (to > itemStoryLength) {
130084
+ results.push(createRangeInvalidResult(inputIndex, "range-exceeds-story-length", from, to, itemStoryLength));
130085
+ return;
130086
+ }
130087
+ const anchor2 = {
130088
+ kind: "range",
130089
+ from,
130090
+ to,
130091
+ assoc
130092
+ };
130093
+ pending.push({
130094
+ inputIndex,
130095
+ request: {
130096
+ anchor: anchor2,
130097
+ scopeId: item.scopeId,
130098
+ mode: item.mode,
130099
+ persistence: item.persistence,
130100
+ metadata: item.metadata,
130101
+ label: item.label,
130102
+ storyTarget: normalizedAnchor.storyTarget ?? { kind: "main" },
130103
+ ...item.visibility ? { visibility: item.visibility } : {},
130104
+ ...item.guardPolicy ? { guardPolicy: item.guardPolicy } : {},
130105
+ ...scopeMetadataFields ? { scopeMetadataFields } : {}
130106
+ },
130107
+ from,
130108
+ to,
130109
+ storyLength: itemStoryLength
130110
+ });
130111
+ return;
130112
+ }
130113
+ const anchor = resolveBlockAnchorFromCanonical(doc, item.blockId, assoc);
130114
+ if (!anchor || anchor.kind !== "range") {
130115
+ results.push({
130116
+ inputIndex,
130117
+ scopeId: "",
130118
+ status: "block-not-found"
130119
+ });
130120
+ return;
130121
+ }
130122
+ pending.push({
130123
+ inputIndex,
130124
+ request: {
130125
+ anchor,
130126
+ scopeId: item.scopeId,
130127
+ mode: item.mode,
130128
+ persistence: item.persistence,
130129
+ metadata: item.metadata,
130130
+ label: item.label,
130131
+ ...item.visibility ? { visibility: item.visibility } : {},
130132
+ ...item.guardPolicy ? { guardPolicy: item.guardPolicy } : {},
130133
+ ...scopeMetadataFields ? { scopeMetadataFields } : {}
130134
+ },
130135
+ from: anchor.from,
130136
+ to: anchor.to,
130137
+ storyLength
130138
+ });
130139
+ });
130140
+ const created = runtime.addScopes(pending.map((item) => item.request));
130141
+ created.forEach((result, index) => {
130142
+ const item = pending[index];
130143
+ if (!item) return;
130144
+ results.push(plantFailureToCreateScopesResult(item, result));
130145
+ });
130146
+ const sorted = results.sort((a, b) => a.inputIndex - b.inputIndex);
130147
+ const createdCount = sorted.filter((item) => item.status === "created").length;
130148
+ const blocked2 = sorted.length - createdCount;
130149
+ return {
130150
+ status: blocked2 === 0 ? "created" : createdCount > 0 ? "partial" : "blocked",
130151
+ total: input.scopes.length,
130152
+ created: createdCount,
130153
+ blocked: blocked2,
130154
+ scopes: Object.freeze(sorted)
130155
+ };
130156
+ }
129820
130157
  function createWorkflowFamily(runtime) {
129821
130158
  return {
129822
130159
  queryScopes(filter) {
@@ -129831,7 +130168,10 @@ function createWorkflowFamily(runtime) {
129831
130168
  createScope(input) {
129832
130169
  const adapterResult = createScopeFromBlockId(runtime, {
129833
130170
  blockId: input.blockId,
130171
+ scopeId: input.scopeId,
129834
130172
  mode: input.mode,
130173
+ persistence: input.persistence,
130174
+ metadata: input.metadata,
129835
130175
  label: input.label,
129836
130176
  ...input.visibility ? { visibility: input.visibility } : {},
129837
130177
  ...input.guardPolicy ? { guardPolicy: input.guardPolicy } : {},
@@ -129865,6 +130205,25 @@ function createWorkflowFamily(runtime) {
129865
130205
  }
129866
130206
  return { scopeId: adapterResult.scopeId, status: "created" };
129867
130207
  },
130208
+ createScopes(input) {
130209
+ const result = createScopesBulk(runtime, input);
130210
+ emitUxResponse(runtime, {
130211
+ apiFn: createScopesMetadata.name,
130212
+ intent: createScopesMetadata.uxIntent.expectedDelta ?? "",
130213
+ mockOrLive: "live",
130214
+ uiVisible: true,
130215
+ expectedDelta: createScopesMetadata.uxIntent.expectedDelta,
130216
+ actualDelta: result.created > 0 ? {
130217
+ kind: "inline-change",
130218
+ payload: {
130219
+ created: result.created,
130220
+ blocked: result.blocked,
130221
+ scopeIds: result.scopes.filter((scope) => scope.status === "created").map((scope) => scope.scopeId)
130222
+ }
130223
+ } : void 0
130224
+ });
130225
+ return result;
130226
+ },
129868
130227
  getScopeGuardPolicy(scopeId) {
129869
130228
  return runtime.getScopeGuardPolicy(scopeId);
129870
130229
  },
@@ -129900,7 +130259,10 @@ function createWorkflowFamily(runtime) {
129900
130259
  createScopeFromAnchor(input) {
129901
130260
  const adapterResult = createScopeFromAnchor(runtime, {
129902
130261
  anchor: input.anchor,
130262
+ scopeId: input.scopeId,
129903
130263
  mode: input.mode,
130264
+ persistence: input.persistence,
130265
+ metadata: input.metadata,
129904
130266
  label: input.label,
129905
130267
  ...input.visibility ? { visibility: input.visibility } : {},
129906
130268
  ...input.guardPolicy ? { guardPolicy: input.guardPolicy } : {},
@@ -130985,6 +131347,12 @@ function createListsFamily2(runtime) {
130985
131347
  const resolved = resolveCurrentListTarget(runtime.getCanonicalDocument(), input);
130986
131348
  return resolved.kind === "resolved" ? toReadback(runtime.getCanonicalDocument(), resolved.target, resolved.paragraph) : null;
130987
131349
  },
131350
+ canJoin(input) {
131351
+ return sequencePreflight(runtime.getCanonicalDocument(), input, activeStoryKey(runtime));
131352
+ },
131353
+ canContinuePrevious(input) {
131354
+ return sequencePreflight(runtime.getCanonicalDocument(), input, activeStoryKey(runtime));
131355
+ },
130988
131356
  previewCommand(input) {
130989
131357
  return previewListCommand(runtime.getCanonicalDocument(), input, activeStoryKey(runtime));
130990
131358
  },
@@ -131049,6 +131417,37 @@ function createListsFamily2(runtime) {
131049
131417
  }
131050
131418
  };
131051
131419
  }
131420
+ function sequencePreflight(document2, input, activeStoryKey2) {
131421
+ const resolved = resolveCurrentListTarget(document2, input);
131422
+ if (resolved.kind !== "resolved") {
131423
+ return {
131424
+ canJoin: false,
131425
+ canContinuePrevious: false,
131426
+ blockers: [resolved.blocker]
131427
+ };
131428
+ }
131429
+ const target = toReadback(document2, resolved.target, resolved.paragraph);
131430
+ const targetRef = { targetKey: target.targetKey, addressKey: target.addressKey };
131431
+ if (activeStoryKey2 !== void 0 && target.storyKey !== activeStoryKey2) {
131432
+ return {
131433
+ target,
131434
+ canJoin: false,
131435
+ canContinuePrevious: false,
131436
+ blockers: [{
131437
+ code: "list-target-wrong-story",
131438
+ ownerLayer: "L07",
131439
+ message: "List target does not belong to the runtime active story.",
131440
+ ...targetRef
131441
+ }]
131442
+ };
131443
+ }
131444
+ return {
131445
+ target,
131446
+ canJoin: canJoinPreviousSequence(document2, resolved.paragraphIndex),
131447
+ canContinuePrevious: canContinuePreviousSequence(document2, resolved.paragraphIndex),
131448
+ blockers: []
131449
+ };
131450
+ }
131052
131451
  function previewListCommand(document2, input, activeStoryKey2) {
131053
131452
  const resolved = resolveCurrentListTarget(document2, input);
131054
131453
  if (resolved.kind !== "resolved") {
@@ -131240,7 +131639,7 @@ function collectParagraphEntriesInto(blocks, storyKey2, basePath, out) {
131240
131639
  const blockPath = `${basePath}/block[${blockIndex}]`;
131241
131640
  switch (block.type) {
131242
131641
  case "paragraph":
131243
- out.push({ paragraph: block, storyKey: storyKey2, blockPath });
131642
+ out.push({ paragraph: block, storyKey: storyKey2, blockPath, containerPath: basePath });
131244
131643
  break;
131245
131644
  case "table":
131246
131645
  for (let rowIndex = 0; rowIndex < block.rows.length; rowIndex += 1) {
@@ -131312,6 +131711,7 @@ function canContinuePreviousSequence(document2, paragraphIndex) {
131312
131711
  for (let index = paragraphIndex - 1; index >= 0; index -= 1) {
131313
131712
  const previousEntry = paragraphs[index];
131314
131713
  if (previousEntry?.storyKey !== currentEntry.storyKey) break;
131714
+ if (previousEntry.containerPath !== currentEntry.containerPath) break;
131315
131715
  const previous = previousEntry.paragraph;
131316
131716
  if (!previous?.numbering) continue;
131317
131717
  const previousKind = getListKind(document2.numbering, previous.numbering.numberingInstanceId);
@@ -131324,6 +131724,7 @@ function canJoinPreviousSequence(document2, paragraphIndex) {
131324
131724
  const currentEntry = paragraphs[paragraphIndex];
131325
131725
  const previousEntry = paragraphs[paragraphIndex - 1];
131326
131726
  if (previousEntry?.storyKey !== currentEntry?.storyKey) return false;
131727
+ if (previousEntry?.containerPath !== currentEntry?.containerPath) return false;
131327
131728
  const current = currentEntry?.paragraph;
131328
131729
  const previous = previousEntry?.paragraph;
131329
131730
  if (!current?.numbering || !previous?.numbering) return false;
@@ -136184,6 +136585,9 @@ function applyRewrite(runtime, target, input) {
136184
136585
  if (target.kind === "editable-text") {
136185
136586
  return applyEditableTextRewrite(runtime, target, input);
136186
136587
  }
136588
+ if (target.handle.provenance === "marker-backed" && (target.scope.kind === "paragraph" || target.scope.kind === "list-item")) {
136589
+ return applyMarkerBackedRangeRewrite(runtime, target, input);
136590
+ }
136187
136591
  if (target.scope.kind === "list-item") {
136188
136592
  const listTextTarget = uniqueListTextActionForScope(runtime, target.handle);
136189
136593
  if (!listTextTarget.ok) return blockedApplyFromResolution(listTextTarget);
@@ -136330,13 +136734,97 @@ function applyEditableTextRewrite(runtime, target, input) {
136330
136734
  afterReadback
136331
136735
  };
136332
136736
  }
136737
+ function applyMarkerBackedRangeRewrite(runtime, target, input) {
136738
+ const range = buildScopePositionMap(runtime.getCanonicalDocument()).markerScopes.get(
136739
+ target.handle.scopeId
136740
+ );
136741
+ if (!range) {
136742
+ return blockedApply(
136743
+ `actions:rewrite:marker-range-unresolved:${target.handle.scopeId}`,
136744
+ "unresolved-target",
136745
+ "The marker-backed scope could not be joined to its current marker range.",
136746
+ "Refresh placeholder scopes and retry; route persistent failures to L06 marker scope tracking."
136747
+ );
136748
+ }
136749
+ const beforeReadback = markerScopeReadback(runtime, target.handle.scopeId) ?? {
136750
+ text: target.scope.content.text,
136751
+ isEmpty: target.scope.content.text.length === 0
136752
+ };
136753
+ const before = runtime.getCanonicalDocument();
136754
+ const origin = actionOrigin(runtime, input);
136755
+ runtime.dispatch({
136756
+ type: "selection.set",
136757
+ selection: {
136758
+ anchor: range.from,
136759
+ head: range.to,
136760
+ isCollapsed: range.from === range.to,
136761
+ activeRange: {
136762
+ kind: "range",
136763
+ from: range.from,
136764
+ to: range.to,
136765
+ assoc: { start: -1, end: 1 }
136766
+ }
136767
+ },
136768
+ origin
136769
+ });
136770
+ const ack = runtime.applyActiveStoryTextCommand({
136771
+ type: "text.insert",
136772
+ text: input.text,
136773
+ origin
136774
+ });
136775
+ const changed = runtime.getCanonicalDocument() !== before;
136776
+ const afterReadback = markerScopeReadback(runtime, target.handle.scopeId);
136777
+ const compiledAfter = createScopeCompilerService(runtime).compileScopeById(target.handle.scopeId);
136778
+ if (!changed || afterReadback?.text !== input.text) {
136779
+ return {
136780
+ status: "blocked",
136781
+ applied: false,
136782
+ changed,
136783
+ target: summarizeTarget(
136784
+ compiledAfter ? { ...target, scope: compiledAfter.scope, handle: compiledAfter.scope.handle } : target
136785
+ ),
136786
+ posture: "suspect-readback",
136787
+ blockers: Object.freeze([
136788
+ `actions:rewrite:marker-range-readback-mismatch:${target.handle.scopeId}`
136789
+ ]),
136790
+ blockerDetails: Object.freeze([
136791
+ blocker(
136792
+ `actions:rewrite:marker-range-readback-mismatch:${target.handle.scopeId}`,
136793
+ "blocked",
136794
+ ack.kind === "rejected" ? "The marker-backed rewrite command was rejected or did not produce the requested marker readback." : "The marker-backed rewrite command did not produce the requested marker readback.",
136795
+ "Treat the mutation as suspect. Re-read the target and export before claiming success."
136796
+ )
136797
+ ]),
136798
+ ...afterReadback ? { afterReadback } : {}
136799
+ };
136800
+ }
136801
+ return {
136802
+ status: "applied",
136803
+ applied: true,
136804
+ changed: true,
136805
+ target: summarizeTarget(
136806
+ compiledAfter ? { ...target, scope: compiledAfter.scope, handle: compiledAfter.scope.handle } : target
136807
+ ),
136808
+ commandReference: {
136809
+ command: "text.insert",
136810
+ actorId: input.actorId ?? "v3-ai-api",
136811
+ origin: input.origin ?? "agent",
136812
+ emittedAtUtc: currentAuditTimestamp(runtime)
136813
+ },
136814
+ beforeReadback,
136815
+ afterReadback
136816
+ };
136817
+ }
136333
136818
  function applyTableScopedMarkerRewrite(runtime, target, action, input) {
136334
136819
  const workflowScope = runtime.getScope(target.handle.scopeId);
136820
+ const markerRange = buildScopePositionMap(runtime.getCanonicalDocument()).markerScopes.get(
136821
+ target.handle.scopeId
136822
+ );
136335
136823
  const editableTarget = tableEditableTargetForActionHandle(
136336
136824
  runtime,
136337
136825
  action.actionHandle
136338
136826
  );
136339
- if (!workflowScope || workflowScope.anchor.kind !== "range" || !editableTarget) {
136827
+ if (!workflowScope || !markerRange || !editableTarget) {
136340
136828
  return blockedApply(
136341
136829
  `actions:rewrite:table-marker-target-unresolved:${target.handle.scopeId}`,
136342
136830
  "unresolved-target",
@@ -136344,19 +136832,23 @@ function applyTableScopedMarkerRewrite(runtime, target, action, input) {
136344
136832
  "Refresh placeholder scopes and retry; route persistent failures to L08 table scope target mapping."
136345
136833
  );
136346
136834
  }
136835
+ const beforeReadback = markerScopeReadback(runtime, target.handle.scopeId) ?? {
136836
+ text: target.scope.content.text,
136837
+ isEmpty: target.scope.content.text.length === 0
136838
+ };
136347
136839
  const before = runtime.getCanonicalDocument();
136348
136840
  try {
136349
136841
  runtime.dispatch({
136350
136842
  type: "selection.set",
136351
136843
  selection: {
136352
- anchor: workflowScope.anchor.from,
136353
- head: workflowScope.anchor.to,
136354
- isCollapsed: workflowScope.anchor.from === workflowScope.anchor.to,
136844
+ anchor: markerRange.from,
136845
+ head: markerRange.to,
136846
+ isCollapsed: markerRange.from === markerRange.to,
136355
136847
  activeRange: {
136356
136848
  kind: "range",
136357
- from: workflowScope.anchor.from,
136358
- to: workflowScope.anchor.to,
136359
- assoc: workflowScope.anchor.assoc ?? { start: -1, end: 1 }
136849
+ from: markerRange.from,
136850
+ to: markerRange.to,
136851
+ assoc: { start: -1, end: 1 }
136360
136852
  }
136361
136853
  },
136362
136854
  origin: actionOrigin(runtime, input)
@@ -136391,12 +136883,19 @@ function applyTableScopedMarkerRewrite(runtime, target, action, input) {
136391
136883
  );
136392
136884
  const afterText = paragraph ? collectInlineText4(paragraph.children) : void 0;
136393
136885
  const afterReadback = afterText === void 0 ? void 0 : { text: afterText, isEmpty: afterText.length === 0 };
136394
- if (!changed || afterReadback?.text !== input.text) {
136886
+ const compiledAfter = createScopeCompilerService(runtime).compileScopeById(target.handle.scopeId);
136887
+ const scopeReadback = markerScopeReadback(runtime, target.handle.scopeId) ?? (compiledAfter ? {
136888
+ text: compiledAfter.scope.content.text,
136889
+ isEmpty: compiledAfter.scope.content.text.length === 0
136890
+ } : void 0);
136891
+ if (!changed || scopeReadback?.text !== input.text) {
136395
136892
  return {
136396
136893
  status: "blocked",
136397
136894
  applied: false,
136398
136895
  changed,
136399
- target: summarizeTarget({ kind: "table-text", action }),
136896
+ target: summarizeTarget(
136897
+ compiledAfter ? { ...target, scope: compiledAfter.scope, handle: compiledAfter.scope.handle } : target
136898
+ ),
136400
136899
  posture: "suspect-readback",
136401
136900
  blockers: Object.freeze([
136402
136901
  `actions:rewrite:table-marker-readback-mismatch:${target.handle.scopeId}`
@@ -136409,25 +136908,24 @@ function applyTableScopedMarkerRewrite(runtime, target, action, input) {
136409
136908
  "Treat the mutation as suspect. Re-read the target and export before claiming success."
136410
136909
  )
136411
136910
  ]),
136412
- ...afterReadback ? { afterReadback } : {}
136911
+ ...scopeReadback ? { afterReadback: scopeReadback } : afterReadback ? { afterReadback } : {}
136413
136912
  };
136414
136913
  }
136415
136914
  return {
136416
136915
  status: "applied",
136417
136916
  applied: true,
136418
136917
  changed: true,
136419
- target: summarizeTarget({
136420
- kind: "table-text",
136421
- action: { ...action, readback: afterReadback }
136422
- }),
136918
+ target: summarizeTarget(
136919
+ compiledAfter ? { ...target, scope: compiledAfter.scope, handle: compiledAfter.scope.handle } : { kind: "table-text", action: { ...action, readback: scopeReadback } }
136920
+ ),
136423
136921
  commandReference: {
136424
136922
  command: "text.insert",
136425
136923
  actorId: input.actorId ?? "v3-ai-api",
136426
136924
  origin: input.origin ?? "agent",
136427
136925
  emittedAtUtc: currentAuditTimestamp(runtime)
136428
136926
  },
136429
- ...action.readback ? { beforeReadback: action.readback } : {},
136430
- afterReadback
136927
+ beforeReadback,
136928
+ afterReadback: scopeReadback
136431
136929
  };
136432
136930
  }
136433
136931
  function projectRewriteScopeResult(runtime, result, target, beforeText, proposedText, documentMutated) {
@@ -136521,7 +137019,7 @@ function summarizeTarget(target) {
136521
137019
  if (target.kind === "editable-text") {
136522
137020
  return {
136523
137021
  kind: target.targetKind,
136524
- handle: target.ownerHandle,
137022
+ handle: publicActionScopeHandle(target.ownerHandle),
136525
137023
  actionHandle: target.actionHandle,
136526
137024
  readback: target.readback,
136527
137025
  canRewriteText: true,
@@ -136532,13 +137030,21 @@ function summarizeTarget(target) {
136532
137030
  }
136533
137031
  return {
136534
137032
  kind: target.scope.kind,
136535
- handle: target.handle,
137033
+ handle: publicActionScopeHandle(target.handle),
136536
137034
  canRewriteText: canRewriteScopeText(target.scope),
136537
137035
  canInsertAdjacentText: canInsertAdjacentScopeText(target.scope),
136538
137036
  canFlag: true,
136539
137037
  canMark: canMarkScope(target.scope)
136540
137038
  };
136541
137039
  }
137040
+ function publicActionScopeHandle(handle) {
137041
+ const parentScopeId = handle.parentScopeId;
137042
+ if (!parentScopeId || !/^(cell|table|row|column|span):/u.test(parentScopeId)) {
137043
+ return handle;
137044
+ }
137045
+ const { parentScopeId: _parentScopeId, ...rest } = handle;
137046
+ return rest;
137047
+ }
136542
137048
  function tableTextActionsForScope(runtime, handle) {
136543
137049
  const result = createTableActionFamily(runtime).listTableActions({
136544
137050
  handle,
@@ -136591,6 +137097,13 @@ function tableEditableTargetForActionHandle(runtime, actionHandle) {
136591
137097
  }
136592
137098
  return null;
136593
137099
  }
137100
+ function markerScopeReadback(runtime, scopeId) {
137101
+ const document2 = runtime.getCanonicalDocument();
137102
+ const range = buildScopePositionMap(document2).markerScopes.get(scopeId);
137103
+ if (!range) return null;
137104
+ const text = textForCanonicalRange(document2, range.from, range.to);
137105
+ return { text, isEmpty: text.length === 0 };
137106
+ }
136594
137107
  function editableTextActionsForScope(runtime, handle) {
136595
137108
  const bundle = createScopeCompilerService(runtime).compileBundleById(
136596
137109
  handle.scopeId,
@@ -137943,6 +138456,86 @@ function blockTextLength(block) {
137943
138456
  return 0;
137944
138457
  }
137945
138458
  }
138459
+ function textForCanonicalRange(document2, from, to) {
138460
+ let cursor = 0;
138461
+ let text = "";
138462
+ const append = (value, start, end) => {
138463
+ const clippedFrom = Math.max(from, start);
138464
+ const clippedTo = Math.min(to, end);
138465
+ if (clippedTo <= clippedFrom) return;
138466
+ const localFrom = clippedFrom - start;
138467
+ const localTo = clippedTo - start;
138468
+ text += Array.from(value).slice(localFrom, localTo).join("");
138469
+ };
138470
+ const walkInline = (inline) => {
138471
+ const start = cursor;
138472
+ switch (inline.type) {
138473
+ case "text": {
138474
+ const length = Array.from(inline.text).length;
138475
+ cursor += length;
138476
+ append(inline.text, start, cursor);
138477
+ return length;
138478
+ }
138479
+ case "tab":
138480
+ cursor += 1;
138481
+ append(" ", start, cursor);
138482
+ return 1;
138483
+ case "hard_break":
138484
+ cursor += 1;
138485
+ append("\n", start, cursor);
138486
+ return 1;
138487
+ case "hyperlink":
138488
+ case "field": {
138489
+ const before = cursor;
138490
+ for (const child of inline.children) {
138491
+ walkInline(child);
138492
+ }
138493
+ return cursor - before;
138494
+ }
138495
+ case "bookmark_start":
138496
+ case "bookmark_end":
138497
+ case "scope_marker_start":
138498
+ case "scope_marker_end":
138499
+ return 0;
138500
+ default:
138501
+ cursor += 1;
138502
+ return 1;
138503
+ }
138504
+ };
138505
+ const walkBlock = (block) => {
138506
+ if (!block) return 0;
138507
+ const before = cursor;
138508
+ switch (block.type) {
138509
+ case "paragraph":
138510
+ for (const child of block.children) walkInline(child);
138511
+ break;
138512
+ case "table":
138513
+ for (const row2 of block.rows) {
138514
+ for (const cell of row2.cells) {
138515
+ for (const child of cell.children) walkBlock(child);
138516
+ }
138517
+ }
138518
+ break;
138519
+ case "sdt":
138520
+ case "custom_xml":
138521
+ for (const child of block.children) walkBlock(child);
138522
+ break;
138523
+ default:
138524
+ cursor += 1;
138525
+ break;
138526
+ }
138527
+ return cursor - before;
138528
+ };
138529
+ const blocks = document2.content.children;
138530
+ for (let index = 0; index < blocks.length; index += 1) {
138531
+ walkBlock(blocks[index]);
138532
+ if (index < blocks.length - 1 && blocks[index + 1]?.type === "paragraph") {
138533
+ cursor += 1;
138534
+ append("\n", cursor - 1, cursor);
138535
+ }
138536
+ }
138537
+ return text;
138538
+ }
137946
138539
  function inlineTextLength(inline) {
137947
138540
  if (!inline) return 0;
137948
138541
  switch (inline.type) {
@@ -138098,6 +138691,109 @@ function summarizePlanResult(mode, steps) {
138098
138691
  };
138099
138692
  }
138100
138693
 
138694
+ // src/api/v3/ai/agent.ts
138695
+ function createAgentFamily(runtime, pe2Evidence) {
138696
+ const inspect = createInspectFamily(runtime, pe2Evidence);
138697
+ const resolve = createResolveFamily(runtime);
138698
+ const bundle = createBundleFamily(runtime, pe2Evidence);
138699
+ const actions2 = createActionsFamily(runtime).actions;
138700
+ const table = createTableActionFamily(runtime);
138701
+ const object = createObjectActionFamily(runtime);
138702
+ const policy = createPolicyFamily(runtime);
138703
+ const evaluate = createEvaluateFamily(runtime);
138704
+ const outline = createOutlineFamily(runtime);
138705
+ const stats = createStatsFamily(runtime);
138706
+ const explain = createExplainFamily(runtime);
138707
+ const review = createReviewFamily2(runtime);
138708
+ const exportFamily = createExportFamily(runtime);
138709
+ const read = Object.freeze({
138710
+ inspectDocument: inspect.inspectDocument,
138711
+ listScopes: inspect.listScopes,
138712
+ getScope: bundle.getScope,
138713
+ getScopeBundle: bundle.getScopeBundle,
138714
+ resolveReference: resolve.resolveReference,
138715
+ queryScopeAtPosition: resolve.queryScopeAtPosition,
138716
+ queryScopeInRange: resolve.queryScopeInRange,
138717
+ brief: actions2.brief,
138718
+ getDocumentOutline: outline.getDocumentOutline,
138719
+ getDocumentStatistics: stats.getDocumentStatistics,
138720
+ explainFormatting: explain.explainFormatting
138721
+ });
138722
+ const target = Object.freeze({
138723
+ discover: actions2.discover,
138724
+ locate: actions2.locate,
138725
+ locateAll: actions2.locateAll,
138726
+ createPlaceholderScopes: actions2.createPlaceholderScopes
138727
+ });
138728
+ const edit = Object.freeze({
138729
+ rewrite: actions2.rewrite,
138730
+ runPlan: actions2.runPlan,
138731
+ insertText: actions2.insertText,
138732
+ mark: actions2.mark,
138733
+ flag: actions2.flag,
138734
+ flagMany: actions2.flagMany,
138735
+ fieldRefresh: actions2.fieldRefresh,
138736
+ tocRefresh: actions2.tocRefresh,
138737
+ bookmarkEdit: actions2.bookmarkEdit,
138738
+ hyperlinkDestinationEdit: actions2.hyperlinkDestinationEdit,
138739
+ hyperlinkTextEdit: actions2.hyperlinkTextEdit
138740
+ });
138741
+ const template = Object.freeze({
138742
+ validateTargets: actions2.validateTemplateTargets,
138743
+ readTarget: actions2.templateTargetRead,
138744
+ fillField: actions2.templateFieldFill
138745
+ });
138746
+ const tableGroup = Object.freeze({
138747
+ replaceContent: actions2.tableContent,
138748
+ applyFragment: actions2.tableFragment,
138749
+ applySelection: actions2.tableSelection,
138750
+ listActions: table.listTableActions,
138751
+ applyAction: table.applyTableAction
138752
+ });
138753
+ const list = Object.freeze({
138754
+ applyOperation: actions2.listOperation
138755
+ });
138756
+ const objectGroup = Object.freeze({
138757
+ listActions: object.listObjectActions,
138758
+ applyAction: object.applyObjectAction
138759
+ });
138760
+ const reviewGroup = Object.freeze({
138761
+ acceptRevision: review.acceptRevision,
138762
+ rejectRevision: review.rejectRevision,
138763
+ resolveCommentThread: review.resolveCommentThread,
138764
+ resolveIssue: review.resolveIssue,
138765
+ reopenIssue: review.reopenIssue
138766
+ });
138767
+ const policyGroup = Object.freeze({
138768
+ getPolicy: policy.getPolicy,
138769
+ listActions: policy.listAIActions,
138770
+ evaluateAction: evaluate.evaluateAction
138771
+ });
138772
+ const exportGroup = Object.freeze({
138773
+ reviewedDocument: exportFamily.exportReviewedDocument
138774
+ });
138775
+ const category = Object.freeze({
138776
+ read,
138777
+ target,
138778
+ edit,
138779
+ template,
138780
+ table: tableGroup,
138781
+ list,
138782
+ object: objectGroup,
138783
+ review: reviewGroup,
138784
+ policy: policyGroup,
138785
+ export: exportGroup
138786
+ });
138787
+ const family = {
138788
+ agent() {
138789
+ return category;
138790
+ }
138791
+ };
138792
+ return {
138793
+ agent: family.agent()
138794
+ };
138795
+ }
138796
+
138101
138797
  // src/api/v3/_create.ts
138102
138798
  function createApiV3(handle, opts) {
138103
138799
  const ai = {
@@ -138115,7 +138811,8 @@ function createApiV3(handle, opts) {
138115
138811
  ...createOutlineFamily(handle),
138116
138812
  ...createTableActionFamily(handle),
138117
138813
  ...createObjectActionFamily(handle),
138118
- ...createActionsFamily(handle)
138814
+ ...createActionsFamily(handle),
138815
+ ...createAgentFamily(handle, opts?.pe2Evidence)
138119
138816
  };
138120
138817
  const runtime = {
138121
138818
  document: createDocumentFamily(handle),