@haklex/rich-agent-core 0.69.1 → 0.70.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.
@@ -0,0 +1,27 @@
1
+ import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';
2
+ import type { ReviewEntry } from './review-types';
3
+ import type { AgentOperation } from './types';
4
+ export declare function getBlockId(node: SerializedLexicalNode): string | undefined;
5
+ export type SnapshotBlockIndex = {
6
+ children: SerializedLexicalNode[];
7
+ blockMap: Map<string, SerializedLexicalNode>;
8
+ indexMap: Map<string, number>;
9
+ fingerprintCache: Map<string, string>;
10
+ };
11
+ export declare function buildSnapshotBlockIndex(snapshot: SerializedEditorState): SnapshotBlockIndex;
12
+ export declare function getIndexedFingerprint(index: SnapshotBlockIndex, blockId: string): string | undefined;
13
+ export declare function getInsertAnchors(children: SerializedLexicalNode[], indexMap: Map<string, number>, position: Extract<AgentOperation, {
14
+ op: 'insert';
15
+ }>['position']): Pick<ReviewEntry, 'anchorAfterId' | 'anchorBeforeId' | 'targetBlockId'>;
16
+ export type AppliedBlock = {
17
+ blockId: string | undefined;
18
+ displayId: string;
19
+ node: SerializedLexicalNode;
20
+ };
21
+ export declare function applyOpsToBlocks(initial: ReadonlyArray<{
22
+ blockId: string | undefined;
23
+ node: SerializedLexicalNode;
24
+ }>, ops: AgentOperation[]): AppliedBlock[];
25
+ export declare function applyOpsToSnapshot(base: SerializedEditorState, ops: AgentOperation[]): SerializedEditorState;
26
+ export declare function fingerprint(node: SerializedLexicalNode): string;
27
+ //# sourceMappingURL=apply-ops.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply-ops.d.ts","sources":["../src/apply-ops.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAE5E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,cA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I,EAAE,qBAAqB,EAC3B,GAAG,EAAE,cAAc,EAAE,GACpB,qBAAqB,CAWvB;AACD,wBAAgB,WAAW,CAAC,IAAI,EAAE,qBAAqB,GAAG,MAAM,CAE/D"}
@@ -1 +1 @@
1
- {"version":3,"file":"document-tools.d.ts","sources":["../src/document-tools.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,sBAAsB,EAA0B,MAAM,WAAW,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,YAAY,CAAC;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AA0C9C,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,cAAc,EACxB,UAAU,EAAE,cAAc,EAAE,EAC5B,OAAO,CAAC,EAAE,sBAAsB,GAC/B,eAAe,EAAE,CAmMnB"}
1
+ {"version":3,"file":"document-tools.d.ts","sources":["../src/document-tools.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,sBAAsB,EAA0B,MAAM,WAAW,CAAC;AAChF,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,YAAY,CAAC;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AA2D9C,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,cAAc,EACxB,UAAU,EAAE,cAAc,EAAE,EAC5B,OAAO,CAAC,EAAE,sBAAsB,GAC/B,eAAe,EAAE,CAqMnB"}
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export type { AgentExecutorConfig, AgentExecutorResult } from './agent-executor'
2
2
  export { createAgentExecutor } from './agent-executor';
3
3
  export type { AgentExecutorPlugin, AgentExecutorPluginContext } from './agent-plugins';
4
4
  export { documentToolsPlugin } from './agent-plugins';
5
+ export { applyOpsToSnapshot } from './apply-ops';
5
6
  export { acceptAllDiffs, acceptDiff, createDiffEngine, rejectAllDiffs, rejectDiff, } from './diff-engine';
6
7
  export { buildDocumentContext } from './document-context';
7
8
  export { createDocumentTools } from './document-tools';
@@ -12,7 +13,7 @@ export { BaseEveryUserContentProvider, BaseFirstUserContentProvider, BaseFirstUs
12
13
  export type { AgentToolConfig, AgentToolResult, CapturedSelection, CapturedTextSelection, ChatMessage, DocumentContextOptions, LLMChunk, LLMProvider, MessageEngine, MessageEngineContext, PageContentContext, PageContentMetadata, PageSelection, PreparedMessages, ToolCall, ToolError, ToolSchema, } from './protocol';
13
14
  export type { ProviderType, TransportAdapter } from './provider';
14
15
  export { createDirectTransport, createProvider, createProxyTransport } from './provider';
15
- export { acceptAndRebaseBatch, acceptBatch, appendReviewBatch, applyOpsToSnapshot, createReviewBatch, detectConflicts, reconcileReviewBatches, rejectBatch, resolveReviewEntry, } from './review-engine';
16
+ export { acceptAndRebaseBatch, acceptBatch, appendReviewBatch, createReviewBatch, detectConflicts, reconcileReviewBatches, rejectBatch, resolveReviewEntry, } from './review-engine';
16
17
  export type { ReviewBatch, ReviewBatchStatus, ReviewEntry, ReviewEntryStatus, ReviewState, } from './review-types';
17
18
  export { agentStoreSelectors } from './selectors';
18
19
  export type { EditorSnapshot } from './snapshot';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,YAAY,EAAE,mBAAmB,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AACvF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EACL,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,UAAU,GACX,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,oBAAoB,EAAE,MAA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MAAM,eAAe,CAAC;AAC/C,YAAY,EACV,YAAY,EACZ,cAAc,EACd,SAAS,EACT,SAAS,EACT,YAAY,EACZ,iBAAiB,GAClB,MAAM,SAAS,CAAC"}
package/dist/index.mjs CHANGED
@@ -1,6 +1,267 @@
1
1
  import { createDefaultRegistry, deserializeNodesFromXml, serializeToXml } from "@haklex/rich-litexml";
2
2
  import { nanoid } from "nanoid";
3
3
  import { createStore } from "zustand/vanilla";
4
+ //#region src/apply-ops.ts
5
+ function getBlockId$1(node) {
6
+ return node.$?.blockId;
7
+ }
8
+ function resolveRootInsertIndex(index, length) {
9
+ return Math.min(Math.max(index ?? length, 0), length);
10
+ }
11
+ function getChildBlockId(children, index) {
12
+ const child = children[index];
13
+ return child ? getBlockId$1(child) : void 0;
14
+ }
15
+ function buildSnapshotBlockIndex(snapshot) {
16
+ const children = snapshotChildren(snapshot);
17
+ const blockMap = /* @__PURE__ */ new Map();
18
+ const indexMap = /* @__PURE__ */ new Map();
19
+ for (let i = 0; i < children.length; i++) {
20
+ const child = children[i];
21
+ const id = getBlockId$1(child);
22
+ if (id && !blockMap.has(id)) {
23
+ blockMap.set(id, child);
24
+ indexMap.set(id, i);
25
+ }
26
+ }
27
+ return {
28
+ children,
29
+ blockMap,
30
+ indexMap,
31
+ fingerprintCache: /* @__PURE__ */ new Map()
32
+ };
33
+ }
34
+ function getIndexedFingerprint(index, blockId) {
35
+ const cached = index.fingerprintCache.get(blockId);
36
+ if (cached !== void 0) return cached;
37
+ const node = index.blockMap.get(blockId);
38
+ if (!node) return void 0;
39
+ const fp = fingerprint(node);
40
+ index.fingerprintCache.set(blockId, fp);
41
+ return fp;
42
+ }
43
+ function getInsertAnchors(children, indexMap, position) {
44
+ if (position.type === "root") {
45
+ const index = resolveRootInsertIndex(position.index, children.length);
46
+ const anchorBeforeId = getChildBlockId(children, index - 1);
47
+ const anchorAfterId = getChildBlockId(children, index);
48
+ return {
49
+ targetBlockId: anchorAfterId ?? anchorBeforeId,
50
+ anchorBeforeId,
51
+ anchorAfterId
52
+ };
53
+ }
54
+ const index = indexMap.get(position.blockId);
55
+ if (index === void 0) return {
56
+ targetBlockId: position.blockId,
57
+ anchorBeforeId: position.type === "after" ? position.blockId : void 0,
58
+ anchorAfterId: position.type === "before" ? position.blockId : void 0
59
+ };
60
+ if (position.type === "after") return {
61
+ targetBlockId: position.blockId,
62
+ anchorBeforeId: getChildBlockId(children, index),
63
+ anchorAfterId: getChildBlockId(children, index + 1)
64
+ };
65
+ return {
66
+ targetBlockId: position.blockId,
67
+ anchorBeforeId: getChildBlockId(children, index - 1),
68
+ anchorAfterId: getChildBlockId(children, index)
69
+ };
70
+ }
71
+ function snapshotChildren(snapshot) {
72
+ return snapshot.root.children ?? [];
73
+ }
74
+ function applyOpsToBlocks(initial, ops) {
75
+ const list = {
76
+ head: null,
77
+ tail: null,
78
+ size: 0
79
+ };
80
+ let hasDuplicates = false;
81
+ const byId = /* @__PURE__ */ new Map();
82
+ const appendNode = (node) => {
83
+ node.prev = list.tail;
84
+ node.next = null;
85
+ if (list.tail) list.tail.next = node;
86
+ else list.head = node;
87
+ list.tail = node;
88
+ node.attached = true;
89
+ list.size++;
90
+ };
91
+ const insertBeforeNode = (anchor, node) => {
92
+ node.prev = anchor.prev;
93
+ node.next = anchor;
94
+ if (anchor.prev) anchor.prev.next = node;
95
+ else list.head = node;
96
+ anchor.prev = node;
97
+ node.attached = true;
98
+ list.size++;
99
+ };
100
+ const insertAfterNode = (anchor, node) => {
101
+ node.prev = anchor;
102
+ node.next = anchor.next;
103
+ if (anchor.next) anchor.next.prev = node;
104
+ else list.tail = node;
105
+ anchor.next = node;
106
+ node.attached = true;
107
+ list.size++;
108
+ };
109
+ const unlinkNode = (node) => {
110
+ if (node.prev) node.prev.next = node.next;
111
+ else list.head = node.next;
112
+ if (node.next) node.next.prev = node.prev;
113
+ else list.tail = node.prev;
114
+ node.prev = null;
115
+ node.next = null;
116
+ node.attached = false;
117
+ list.size--;
118
+ };
119
+ const nodeAt = (index) => {
120
+ if (index <= 0) return list.head;
121
+ if (index >= list.size) return null;
122
+ if (index <= list.size >> 1) {
123
+ let cur = list.head;
124
+ for (let i = 0; i < index && cur; i++) cur = cur.next;
125
+ return cur;
126
+ }
127
+ let cur = list.tail;
128
+ for (let i = list.size - 1; i > index && cur; i--) cur = cur.prev;
129
+ return cur;
130
+ };
131
+ const registerId = (id, node) => {
132
+ if (!id) return;
133
+ if (byId.has(id)) hasDuplicates = true;
134
+ else byId.set(id, node);
135
+ };
136
+ const refreshIdLookup = (id) => {
137
+ for (let cur = list.head; cur; cur = cur.next) if (cur.blockId === id) {
138
+ byId.set(id, cur);
139
+ return;
140
+ }
141
+ byId.delete(id);
142
+ };
143
+ for (const item of initial) {
144
+ const blockNode = {
145
+ blockId: item.blockId,
146
+ value: {
147
+ blockId: item.blockId,
148
+ displayId: item.blockId ?? "",
149
+ node: { ...item.node }
150
+ },
151
+ prev: null,
152
+ next: null,
153
+ attached: false
154
+ };
155
+ appendNode(blockNode);
156
+ registerId(item.blockId, blockNode);
157
+ }
158
+ const lastInsertedAfter = /* @__PURE__ */ new Map();
159
+ const lastInsertedAtRoot = /* @__PURE__ */ new Map();
160
+ let insertedCounter = 0;
161
+ for (const op of ops) if (op.op === "insert") {
162
+ if (!op.node?.type) continue;
163
+ const pos = op.position;
164
+ const nodeBlockId = getBlockId$1(op.node);
165
+ if (pos.type === "root") {
166
+ const newNode = {
167
+ blockId: nodeBlockId,
168
+ value: {
169
+ blockId: nodeBlockId,
170
+ displayId: nodeBlockId ?? `staged-${++insertedCounter}`,
171
+ node: op.node
172
+ },
173
+ prev: null,
174
+ next: null,
175
+ attached: false
176
+ };
177
+ if (pos.index === void 0) appendNode(newNode);
178
+ else {
179
+ const prevInserted = lastInsertedAtRoot.get(pos.index);
180
+ if (prevInserted?.attached) insertAfterNode(prevInserted, newNode);
181
+ else {
182
+ const atIdx = nodeAt(resolveRootInsertIndex(pos.index, list.size));
183
+ if (atIdx) insertBeforeNode(atIdx, newNode);
184
+ else appendNode(newNode);
185
+ }
186
+ lastInsertedAtRoot.set(pos.index, newNode);
187
+ }
188
+ registerId(nodeBlockId, newNode);
189
+ } else {
190
+ const anchor = byId.get(pos.blockId);
191
+ if (!anchor) continue;
192
+ const newNode = {
193
+ blockId: nodeBlockId,
194
+ value: {
195
+ blockId: nodeBlockId,
196
+ displayId: nodeBlockId ?? `staged-${++insertedCounter}`,
197
+ node: op.node
198
+ },
199
+ prev: null,
200
+ next: null,
201
+ attached: false
202
+ };
203
+ if (pos.type === "after") {
204
+ const prevInserted = lastInsertedAfter.get(pos.blockId);
205
+ if (prevInserted?.attached) insertAfterNode(prevInserted, newNode);
206
+ else insertAfterNode(anchor, newNode);
207
+ lastInsertedAfter.set(pos.blockId, newNode);
208
+ } else insertBeforeNode(anchor, newNode);
209
+ registerId(nodeBlockId, newNode);
210
+ }
211
+ } else if (op.op === "replace") {
212
+ if (!op.node?.type) continue;
213
+ const target = byId.get(op.blockId);
214
+ if (!target) continue;
215
+ const nextId = getBlockId$1(op.node);
216
+ target.value = {
217
+ blockId: nextId,
218
+ displayId: nextId ?? op.blockId,
219
+ node: op.node
220
+ };
221
+ if (nextId !== target.blockId) {
222
+ const oldId = target.blockId;
223
+ target.blockId = nextId;
224
+ if (oldId) {
225
+ if (hasDuplicates) refreshIdLookup(oldId);
226
+ else byId.delete(oldId);
227
+ }
228
+ registerId(nextId, target);
229
+ }
230
+ } else if (op.op === "delete") {
231
+ const target = byId.get(op.blockId);
232
+ if (!target) continue;
233
+ if (!hasDuplicates) {
234
+ unlinkNode(target);
235
+ byId.delete(op.blockId);
236
+ } else {
237
+ let cur = list.head;
238
+ while (cur) {
239
+ const next = cur.next;
240
+ if (cur.blockId === op.blockId) unlinkNode(cur);
241
+ cur = next;
242
+ }
243
+ byId.delete(op.blockId);
244
+ }
245
+ }
246
+ const result = Array.from({ length: list.size });
247
+ let i = 0;
248
+ for (let cur = list.head; cur; cur = cur.next) result[i++] = cur.value;
249
+ return result;
250
+ }
251
+ function applyOpsToSnapshot(base, ops) {
252
+ const children = applyOpsToBlocks(snapshotChildren(base).map((child) => ({
253
+ blockId: getBlockId$1(child),
254
+ node: child
255
+ })), ops).map((block) => block.node);
256
+ return { root: {
257
+ ...base.root,
258
+ children
259
+ } };
260
+ }
261
+ function fingerprint(node) {
262
+ return JSON.stringify(node);
263
+ }
264
+ //#endregion
4
265
  //#region src/litexml.ts
5
266
  function resolveLitexmlRegistry(options) {
6
267
  const provider = options?.litexmlRegistry;
@@ -9,6 +270,9 @@ function resolveLitexmlRegistry(options) {
9
270
  }
10
271
  //#endregion
11
272
  //#region src/document-tools.ts
273
+ function getBlockId(node) {
274
+ return node.$?.blockId;
275
+ }
12
276
  function extractText(node) {
13
277
  const n = node;
14
278
  if (n.text) return n.text;
@@ -17,30 +281,26 @@ function extractText(node) {
17
281
  }
18
282
  var STAGED_NOTE = "Staged for user review; the live document changes only after the user accepts. search_document already reflects staged edits — do not re-run the same edit to \"make it stick\".";
19
283
  function stagedBlocks(snapshot, operations) {
20
- let blocks = snapshot.blockIds.map((blockId) => ({
284
+ return applyOpsToBlocks(snapshot.blockIds.map((blockId) => ({
21
285
  blockId,
22
286
  node: snapshot.getBlock(blockId)
287
+ })), operations).map((block) => ({
288
+ blockId: block.displayId,
289
+ node: block.node
23
290
  }));
24
- let inserted = 0;
25
- for (const op of operations) if (op.op === "replace") blocks = blocks.map((b) => b.blockId === op.blockId ? {
26
- ...b,
27
- node: op.node
28
- } : b);
29
- else if (op.op === "delete") blocks = blocks.filter((b) => b.blockId !== op.blockId);
30
- else {
31
- const staged = {
32
- blockId: `staged-${++inserted}`,
33
- node: op.node
34
- };
35
- if (op.position.type === "root") blocks.splice(op.position.index ?? blocks.length, 0, staged);
36
- else {
37
- const anchor = op.position.blockId;
38
- const idx = blocks.findIndex((b) => b.blockId === anchor);
39
- if (idx === -1) blocks.push(staged);
40
- else blocks.splice(op.position.type === "after" ? idx + 1 : idx, 0, staged);
41
- }
42
- }
43
- return blocks;
291
+ }
292
+ function hasStagedBlock(snapshot, operations, blockId) {
293
+ let exists = snapshot.getBlock(blockId) !== void 0;
294
+ if (operations.length === 0) return exists;
295
+ for (const op of operations) if (op.op === "delete") {
296
+ if (op.blockId === blockId) exists = false;
297
+ } else if (op.op === "replace") {
298
+ if (!op.node?.type) continue;
299
+ if (op.blockId === blockId) {
300
+ if (exists && getBlockId(op.node) !== blockId) exists = false;
301
+ } else if (getBlockId(op.node) === blockId) return stagedBlocks(snapshot, operations).some((b) => b.blockId === blockId);
302
+ } else if (op.op === "insert" && op.node?.type && getBlockId(op.node) === blockId) return stagedBlocks(snapshot, operations).some((b) => b.blockId === blockId);
303
+ return exists;
44
304
  }
45
305
  function createDocumentTools(snapshot, operations, options) {
46
306
  const registry = resolveLitexmlRegistry(options);
@@ -87,7 +347,7 @@ function createDocumentTools(snapshot, operations, options) {
87
347
  message: "Missing or invalid \"xml\" parameter. Must be an XML string."
88
348
  }
89
349
  };
90
- if (position.type !== "root" && !snapshot.getBlock(position.blockId)) return {
350
+ if (position.type !== "root" && (!position.blockId || !hasStagedBlock(snapshot, operations, position.blockId))) return {
91
351
  ok: false,
92
352
  error: {
93
353
  error: "block_not_found",
@@ -158,7 +418,7 @@ function createDocumentTools(snapshot, operations, options) {
158
418
  message: "Missing or invalid \"xml\" parameter."
159
419
  }
160
420
  };
161
- if (!snapshot.getBlock(blockId)) return {
421
+ if (!hasStagedBlock(snapshot, operations, blockId)) return {
162
422
  ok: false,
163
423
  error: {
164
424
  error: "block_not_found",
@@ -225,7 +485,7 @@ function createDocumentTools(snapshot, operations, options) {
225
485
  },
226
486
  execute: async (params) => {
227
487
  const { blockId } = params;
228
- if (!snapshot.getBlock(blockId)) return {
488
+ if (!hasStagedBlock(snapshot, operations, blockId)) return {
229
489
  ok: false,
230
490
  error: {
231
491
  error: "block_not_found",
@@ -1261,139 +1521,104 @@ function createProxyTransport(config) {
1261
1521
  }
1262
1522
  //#endregion
1263
1523
  //#region src/review-engine.ts
1264
- function getBlockId(node) {
1265
- return node.$?.blockId;
1266
- }
1267
- function resolveRootInsertIndex(index, length) {
1268
- return Math.min(Math.max(index ?? length, 0), length);
1269
- }
1270
- function getChildBlockId(children, index) {
1271
- const child = children[index];
1272
- return child ? getBlockId(child) : void 0;
1273
- }
1274
- function getInsertAnchors(children, position) {
1275
- if (position.type === "root") {
1276
- const index = resolveRootInsertIndex(position.index, children.length);
1277
- const anchorBeforeId = getChildBlockId(children, index - 1);
1278
- const anchorAfterId = getChildBlockId(children, index);
1279
- return {
1280
- targetBlockId: anchorAfterId ?? anchorBeforeId,
1281
- anchorBeforeId,
1282
- anchorAfterId
1283
- };
1284
- }
1285
- const index = children.findIndex((child) => getBlockId(child) === position.blockId);
1286
- if (index === -1) return {
1287
- targetBlockId: position.blockId,
1288
- anchorBeforeId: position.type === "after" ? position.blockId : void 0,
1289
- anchorAfterId: position.type === "before" ? position.blockId : void 0
1290
- };
1291
- if (position.type === "after") return {
1292
- targetBlockId: position.blockId,
1293
- anchorBeforeId: getChildBlockId(children, index),
1294
- anchorAfterId: getChildBlockId(children, index + 1)
1295
- };
1296
- return {
1297
- targetBlockId: position.blockId,
1298
- anchorBeforeId: getChildBlockId(children, index - 1),
1299
- anchorAfterId: getChildBlockId(children, index)
1300
- };
1301
- }
1302
- function cloneChildren(root) {
1303
- return [...root.children ?? []].map((c) => ({ ...c }));
1304
- }
1305
- function snapshotChildren(snapshot) {
1306
- return snapshot.root.children ?? [];
1307
- }
1308
- function snapshotHasBlock(snapshot, blockId) {
1309
- return snapshotChildren(snapshot).some((child) => getBlockId(child) === blockId);
1310
- }
1311
- function canApplyOpToSnapshot(snapshot, op) {
1312
- if (op.op === "insert") return op.position.type === "root" || snapshotHasBlock(snapshot, op.position.blockId);
1313
- return snapshotHasBlock(snapshot, op.blockId);
1314
- }
1315
- function applyOpsToSnapshot(base, ops) {
1316
- let children = cloneChildren(base.root);
1317
- const insertOffset = /* @__PURE__ */ new Map();
1318
- for (const op of ops) if (op.op === "insert") {
1319
- if (!op.node?.type) continue;
1320
- const pos = op.position;
1321
- if (pos.type === "root") {
1322
- const idx = resolveRootInsertIndex(pos.index, children.length);
1323
- children.splice(idx, 0, op.node);
1324
- } else {
1325
- const idx = children.findIndex((c) => getBlockId(c) === pos.blockId);
1326
- if (idx === -1) continue;
1327
- const baseIdx = pos.type === "after" ? idx + 1 : idx;
1328
- const key = `${pos.type}:${pos.blockId}`;
1329
- const offset = insertOffset.get(key) ?? 0;
1330
- children.splice(baseIdx + offset, 0, op.node);
1331
- insertOffset.set(key, offset + 1);
1332
- }
1333
- } else if (op.op === "replace") {
1334
- if (!op.node?.type) continue;
1335
- const idx = children.findIndex((c) => getBlockId(c) === op.blockId);
1336
- if (idx === -1) continue;
1337
- children[idx] = op.node;
1338
- } else if (op.op === "delete") children = children.filter((c) => getBlockId(c) !== op.blockId);
1339
- return { root: {
1340
- ...base.root,
1341
- children
1342
- } };
1343
- }
1344
- function fingerprint(node) {
1345
- return JSON.stringify(node);
1346
- }
1347
1524
  function extractTouchedBlockIds(entries) {
1348
1525
  const ids = /* @__PURE__ */ new Set();
1349
1526
  for (const entry of entries) if (entry.targetBlockId) ids.add(entry.targetBlockId);
1350
1527
  return [...ids];
1351
1528
  }
1529
+ function isUnresolvedEntryStatus(status) {
1530
+ return status === "pending" || status === "conflicted";
1531
+ }
1532
+ function computeActivePreviewSnapshot(baseSnapshot, entries) {
1533
+ const activeOps = [];
1534
+ for (const entry of entries) if (entry.status !== "rejected") activeOps.push(entry.op);
1535
+ return applyOpsToSnapshot(baseSnapshot, activeOps);
1536
+ }
1352
1537
  function updateResolvedBatch(state, batchId, status) {
1353
1538
  return {
1354
1539
  ...state,
1355
- batches: state.batches.map((batch) => batch.id === batchId ? {
1356
- ...batch,
1357
- status,
1358
- entries: batch.entries.map((entry) => entry.status === "pending" ? {
1540
+ batches: state.batches.map((batch) => {
1541
+ if (batch.id !== batchId || isFinalBatchStatus(batch.status)) return batch;
1542
+ const entries = batch.entries.map((entry) => isUnresolvedEntryStatus(entry.status) ? {
1359
1543
  ...entry,
1360
1544
  status
1361
- } : entry)
1362
- } : batch)
1545
+ } : entry);
1546
+ const acceptedOps = [];
1547
+ let hasAccepted = false;
1548
+ for (const entry of entries) if (entry.status === "accepted") {
1549
+ hasAccepted = true;
1550
+ acceptedOps.push(entry.op);
1551
+ }
1552
+ const nextStatus = status === "accepted" && entries.length > 0 && !hasAccepted ? "rejected" : status;
1553
+ return {
1554
+ ...batch,
1555
+ status: nextStatus,
1556
+ entries,
1557
+ previewSnapshot: applyOpsToSnapshot(batch.baseSnapshot, acceptedOps)
1558
+ };
1559
+ })
1363
1560
  };
1364
1561
  }
1365
- function batchEntriesMatch(left, right, predicate) {
1366
- for (const leftEntry of left.entries) {
1367
- if (leftEntry.status !== "pending") continue;
1368
- for (const rightEntry of right.entries) {
1369
- if (rightEntry.status !== "pending") continue;
1370
- if (predicate(leftEntry, rightEntry)) return true;
1562
+ function makeInsertGapKey(entry) {
1563
+ return `${entry.anchorBeforeId ?? ""}\u0000${entry.anchorAfterId ?? ""}`;
1564
+ }
1565
+ function buildBatchEntryIndex(entries, pendingOnly) {
1566
+ const deletedIds = /* @__PURE__ */ new Set();
1567
+ const replacedIds = /* @__PURE__ */ new Set();
1568
+ const insertAnchorIds = /* @__PURE__ */ new Set();
1569
+ const insertGapKeys = /* @__PURE__ */ new Set();
1570
+ for (const entry of entries) {
1571
+ if (pendingOnly && entry.status !== "pending") continue;
1572
+ const { op } = entry;
1573
+ if (op.op === "delete") deletedIds.add(op.blockId);
1574
+ else if (op.op === "replace") replacedIds.add(op.blockId);
1575
+ else {
1576
+ if (entry.targetBlockId) insertAnchorIds.add(entry.targetBlockId);
1577
+ if (entry.anchorBeforeId) insertAnchorIds.add(entry.anchorBeforeId);
1578
+ if (entry.anchorAfterId) insertAnchorIds.add(entry.anchorAfterId);
1579
+ insertGapKeys.add(makeInsertGapKey(entry));
1371
1580
  }
1372
1581
  }
1582
+ return {
1583
+ deletedIds,
1584
+ replacedIds,
1585
+ insertAnchorIds,
1586
+ insertGapKeys
1587
+ };
1588
+ }
1589
+ function setsIntersect(a, b) {
1590
+ if (a.size === 0 || b.size === 0) return false;
1591
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a];
1592
+ for (const item of small) if (large.has(item)) return true;
1373
1593
  return false;
1374
1594
  }
1375
- function createReviewBatch(ops, baseSnapshot, baseRevision) {
1595
+ function entryConflictsWithIndex(entry, index) {
1596
+ const { op } = entry;
1597
+ if (op.op === "delete") return index.deletedIds.has(op.blockId) || index.replacedIds.has(op.blockId) || index.insertAnchorIds.has(op.blockId);
1598
+ if (op.op === "replace") return index.deletedIds.has(op.blockId) || index.replacedIds.has(op.blockId);
1599
+ return entry.targetBlockId !== void 0 && index.deletedIds.has(entry.targetBlockId) || entry.anchorBeforeId !== void 0 && index.deletedIds.has(entry.anchorBeforeId) || entry.anchorAfterId !== void 0 && index.deletedIds.has(entry.anchorAfterId);
1600
+ }
1601
+ function indexedBatchesConflict(left, right) {
1602
+ return setsIntersect(left.deletedIds, right.deletedIds) || setsIntersect(left.deletedIds, right.replacedIds) || setsIntersect(left.deletedIds, right.insertAnchorIds) || setsIntersect(right.deletedIds, left.replacedIds) || setsIntersect(right.deletedIds, left.insertAnchorIds) || setsIntersect(left.replacedIds, right.replacedIds);
1603
+ }
1604
+ function indexedBatchesAreOrderDependent(left, right) {
1605
+ return setsIntersect(left.insertGapKeys, right.insertGapKeys);
1606
+ }
1607
+ function createReviewBatchWithIndex(ops, baseSnapshot, baseRevision, index) {
1376
1608
  const previewSnapshot = applyOpsToSnapshot(baseSnapshot, ops);
1377
- const baseChildren = baseSnapshot.root.children ?? [];
1378
- const blockMap = /* @__PURE__ */ new Map();
1379
- for (const child of baseChildren) {
1380
- const id = getBlockId(child);
1381
- if (id) blockMap.set(id, child);
1382
- }
1383
- const entries = ops.filter((op) => {
1384
- if (op.op === "insert" || op.op === "replace") return !!op.node?.type;
1385
- return true;
1386
- }).map((op) => {
1609
+ const { children: baseChildren, indexMap } = index;
1610
+ const entries = [];
1611
+ for (const op of ops) {
1612
+ if ((op.op === "insert" || op.op === "replace") && !op.node?.type) continue;
1387
1613
  let targetBlockId;
1388
1614
  let anchorBeforeId;
1389
1615
  let anchorAfterId;
1390
1616
  let fp = "";
1391
1617
  if (op.op === "replace" || op.op === "delete") {
1392
1618
  targetBlockId = op.blockId;
1393
- const orig = blockMap.get(op.blockId);
1394
- if (orig) fp = fingerprint(orig);
1395
- } else if (op.op === "insert") ({targetBlockId, anchorBeforeId, anchorAfterId} = getInsertAnchors(baseChildren, op.position));
1396
- return {
1619
+ fp = getIndexedFingerprint(index, op.blockId) ?? "";
1620
+ } else if (op.op === "insert") ({targetBlockId, anchorBeforeId, anchorAfterId} = getInsertAnchors(baseChildren, indexMap, op.position));
1621
+ entries.push({
1397
1622
  id: nanoid(8),
1398
1623
  op,
1399
1624
  targetBlockId,
@@ -1401,8 +1626,8 @@ function createReviewBatch(ops, baseSnapshot, baseRevision) {
1401
1626
  anchorAfterId,
1402
1627
  originalFingerprint: fp,
1403
1628
  status: "pending"
1404
- };
1405
- });
1629
+ });
1630
+ }
1406
1631
  return {
1407
1632
  id: nanoid(8),
1408
1633
  baseRevision,
@@ -1413,25 +1638,40 @@ function createReviewBatch(ops, baseSnapshot, baseRevision) {
1413
1638
  touchedBlockIds: extractTouchedBlockIds(entries)
1414
1639
  };
1415
1640
  }
1641
+ function createReviewBatch(ops, baseSnapshot, baseRevision) {
1642
+ return createReviewBatchWithIndex(ops, baseSnapshot, baseRevision, buildSnapshotBlockIndex(baseSnapshot));
1643
+ }
1416
1644
  function withEntries(batch, entries) {
1645
+ const previewSnapshot = computeActivePreviewSnapshot(batch.baseSnapshot, entries);
1417
1646
  if (!entries.every((e) => e.status === "accepted" || e.status === "rejected")) return {
1418
1647
  ...batch,
1419
- entries
1648
+ entries,
1649
+ previewSnapshot
1420
1650
  };
1421
1651
  const allRejected = entries.every((e) => e.status === "rejected");
1422
1652
  return {
1423
1653
  ...batch,
1424
1654
  entries,
1655
+ previewSnapshot,
1425
1656
  status: allRejected ? "rejected" : "accepted"
1426
1657
  };
1427
1658
  }
1428
1659
  function appendReviewBatch(state, incoming) {
1660
+ const incomingIndex = buildBatchEntryIndex(incoming.entries, false);
1429
1661
  const batches = state.batches.map((batch) => {
1430
1662
  if (isFinalBatchStatus(batch.status)) return batch;
1431
- return withEntries(batch, batch.entries.map((entry) => entry.status === "pending" && incoming.entries.some((next) => entriesConflict(entry, next)) ? {
1432
- ...entry,
1433
- status: "rejected"
1434
- } : entry));
1663
+ let changed = false;
1664
+ const entries = batch.entries.map((entry) => {
1665
+ if (entry.status === "pending" && entryConflictsWithIndex(entry, incomingIndex)) {
1666
+ changed = true;
1667
+ return {
1668
+ ...entry,
1669
+ status: "rejected"
1670
+ };
1671
+ }
1672
+ return entry;
1673
+ });
1674
+ return changed ? withEntries(batch, entries) : batch;
1435
1675
  });
1436
1676
  return reconcileReviewBatches({
1437
1677
  ...state,
@@ -1444,47 +1684,55 @@ function acceptBatch(state, batchId) {
1444
1684
  function rejectBatch(state, batchId) {
1445
1685
  return updateResolvedBatch(state, batchId, "rejected");
1446
1686
  }
1447
- function batchesConflict(left, right) {
1448
- return batchEntriesMatch(left, right, entriesConflict);
1449
- }
1450
- function batchesAreOrderDependent(left, right) {
1451
- return batchEntriesMatch(left, right, entriesAreOrderDependent);
1452
- }
1453
- function entriesConflict(left, right) {
1454
- const leftOp = left.op;
1455
- const rightOp = right.op;
1456
- if (leftOp.op === "insert" && rightOp.op === "insert") return false;
1457
- if (leftOp.op === "delete") return conflictsWithDeletedBlock(leftOp.blockId, right);
1458
- if (rightOp.op === "delete") return conflictsWithDeletedBlock(rightOp.blockId, left);
1459
- if (leftOp.op === "replace" && rightOp.op === "replace") return leftOp.blockId === rightOp.blockId;
1460
- return false;
1461
- }
1462
- function entriesAreOrderDependent(left, right) {
1463
- if (left.op.op !== "insert" || right.op.op !== "insert") return false;
1464
- return left.anchorBeforeId === right.anchorBeforeId && left.anchorAfterId === right.anchorAfterId;
1465
- }
1466
- function conflictsWithDeletedBlock(deletedBlockId, entry) {
1467
- const op = entry.op;
1468
- if (op.op === "delete" || op.op === "replace") return op.blockId === deletedBlockId;
1469
- return entry.targetBlockId === deletedBlockId || entry.anchorBeforeId === deletedBlockId || entry.anchorAfterId === deletedBlockId;
1470
- }
1471
1687
  function isFinalBatchStatus(status) {
1472
1688
  return status === "accepted" || status === "rejected";
1473
1689
  }
1474
1690
  function getInitialBatchStatus(batch, documentRevision) {
1475
- return batch.baseRevision < documentRevision ? "conflicted" : "pending";
1691
+ if (batch.baseRevision < documentRevision || batch.entries.some((entry) => entry.status === "conflicted")) return "conflicted";
1692
+ return "pending";
1476
1693
  }
1477
1694
  function updateStatusUnlessConflicted(statuses, batchId, status) {
1478
1695
  if (statuses.get(batchId) === "conflicted") return;
1479
1696
  statuses.set(batchId, status);
1480
1697
  }
1481
- function rebaseBatch(batch, baseSnapshot, baseRevision) {
1482
- const ops = batch.entries.filter((entry) => entry.status === "pending").map((entry) => entry.op);
1483
- if (!ops.every((op) => canApplyOpToSnapshot(baseSnapshot, op))) return batch;
1484
- const rebased = createReviewBatch(ops, baseSnapshot, baseRevision);
1698
+ function entryConflictsWithBase(entry, baseIndex, modifiedBlockIds) {
1699
+ if (entry.status === "conflicted") return true;
1700
+ const { op } = entry;
1701
+ if (op.op === "insert") return op.position.type !== "root" && !baseIndex.blockMap.has(op.position.blockId);
1702
+ if (!baseIndex.blockMap.has(op.blockId)) return true;
1703
+ if (modifiedBlockIds.has(op.blockId)) return true;
1704
+ if (entry.originalFingerprint !== "") {
1705
+ if (getIndexedFingerprint(baseIndex, op.blockId) !== entry.originalFingerprint) return true;
1706
+ }
1707
+ return false;
1708
+ }
1709
+ function rebaseBatch(batch, baseSnapshot, baseRevision, baseIndex, modifiedBlockIds) {
1710
+ let hasConflict = false;
1711
+ const conflictFlags = Array.from({ length: batch.entries.length }, () => false);
1712
+ const pendingOps = [];
1713
+ for (let i = 0; i < batch.entries.length; i++) {
1714
+ const entry = batch.entries[i];
1715
+ if (!isUnresolvedEntryStatus(entry.status)) continue;
1716
+ if (entryConflictsWithBase(entry, baseIndex, modifiedBlockIds)) {
1717
+ hasConflict = true;
1718
+ conflictFlags[i] = true;
1719
+ } else pendingOps.push(entry.op);
1720
+ }
1721
+ if (hasConflict) {
1722
+ const entries = batch.entries.map((entry, idx) => conflictFlags[idx] && entry.status !== "conflicted" ? {
1723
+ ...entry,
1724
+ status: "conflicted"
1725
+ } : entry);
1726
+ return {
1727
+ ...batch,
1728
+ status: "conflicted",
1729
+ entries
1730
+ };
1731
+ }
1732
+ const rebased = createReviewBatchWithIndex(pendingOps, baseSnapshot, baseRevision, baseIndex);
1485
1733
  let nextPendingIndex = 0;
1486
1734
  const entries = batch.entries.map((entry) => {
1487
- if (entry.status !== "pending") return entry;
1735
+ if (!isUnresolvedEntryStatus(entry.status)) return entry;
1488
1736
  return {
1489
1737
  ...rebased.entries[nextPendingIndex++],
1490
1738
  id: entry.id
@@ -1499,20 +1747,32 @@ function rebaseBatch(batch, baseSnapshot, baseRevision) {
1499
1747
  }
1500
1748
  function reconcileReviewBatches(state) {
1501
1749
  const nextStatuses = /* @__PURE__ */ new Map();
1502
- const activeBatches = state.batches.filter((batch) => !isFinalBatchStatus(batch.status));
1503
- const currentRevisionBatches = activeBatches.filter((batch) => batch.baseRevision === state.documentRevision);
1504
- for (const batch of activeBatches) nextStatuses.set(batch.id, getInitialBatchStatus(batch, state.documentRevision));
1505
- for (let i = 0; i < currentRevisionBatches.length; i++) for (let j = i + 1; j < currentRevisionBatches.length; j++) {
1506
- const left = currentRevisionBatches[i];
1507
- const right = currentRevisionBatches[j];
1508
- if (batchesConflict(left, right)) {
1509
- nextStatuses.set(left.id, "conflicted");
1510
- nextStatuses.set(right.id, "conflicted");
1511
- continue;
1750
+ const currentRevisionBatches = [];
1751
+ const currentRevisionIndices = [];
1752
+ for (const batch of state.batches) {
1753
+ if (isFinalBatchStatus(batch.status)) continue;
1754
+ const initialStatus = getInitialBatchStatus(batch, state.documentRevision);
1755
+ nextStatuses.set(batch.id, initialStatus);
1756
+ if (batch.baseRevision === state.documentRevision && initialStatus !== "conflicted") {
1757
+ currentRevisionBatches.push(batch);
1758
+ currentRevisionIndices.push(buildBatchEntryIndex(batch.entries, true));
1512
1759
  }
1513
- if (batchesAreOrderDependent(left, right)) {
1514
- updateStatusUnlessConflicted(nextStatuses, left.id, "order_dependent");
1515
- updateStatusUnlessConflicted(nextStatuses, right.id, "order_dependent");
1760
+ }
1761
+ for (let i = 0; i < currentRevisionBatches.length; i++) {
1762
+ const left = currentRevisionBatches[i];
1763
+ const leftIndex = currentRevisionIndices[i];
1764
+ for (let j = i + 1; j < currentRevisionBatches.length; j++) {
1765
+ const right = currentRevisionBatches[j];
1766
+ const rightIndex = currentRevisionIndices[j];
1767
+ if (indexedBatchesConflict(leftIndex, rightIndex)) {
1768
+ nextStatuses.set(left.id, "conflicted");
1769
+ nextStatuses.set(right.id, "conflicted");
1770
+ continue;
1771
+ }
1772
+ if (indexedBatchesAreOrderDependent(leftIndex, rightIndex)) {
1773
+ updateStatusUnlessConflicted(nextStatuses, left.id, "order_dependent");
1774
+ updateStatusUnlessConflicted(nextStatuses, right.id, "order_dependent");
1775
+ }
1516
1776
  }
1517
1777
  }
1518
1778
  return {
@@ -1524,16 +1784,22 @@ function reconcileReviewBatches(state) {
1524
1784
  };
1525
1785
  }
1526
1786
  function acceptAndRebaseBatch(state, batchId) {
1787
+ const targetBatch = state.batches.find((batch) => batch.id === batchId);
1788
+ if (!targetBatch || isFinalBatchStatus(targetBatch.status)) return state;
1527
1789
  const acceptedState = acceptBatch(state, batchId);
1528
1790
  const acceptedBatch = acceptedState.batches.find((batch) => batch.id === batchId);
1529
1791
  if (!acceptedBatch) return state;
1792
+ const modifiedBlockIds = /* @__PURE__ */ new Set();
1793
+ for (const entry of acceptedBatch.entries) if (entry.status === "accepted" && (entry.op.op === "replace" || entry.op.op === "delete")) modifiedBlockIds.add(entry.op.blockId);
1530
1794
  const nextRevision = state.documentRevision + 1;
1795
+ const newBaseSnapshot = acceptedBatch.previewSnapshot;
1796
+ const newBaseIndex = buildSnapshotBlockIndex(newBaseSnapshot);
1531
1797
  return reconcileReviewBatches({
1532
1798
  ...acceptedState,
1533
1799
  documentRevision: nextRevision,
1534
1800
  batches: acceptedState.batches.map((batch) => {
1535
1801
  if (batch.id === batchId || isFinalBatchStatus(batch.status)) return batch;
1536
- return rebaseBatch(batch, acceptedBatch.previewSnapshot, nextRevision);
1802
+ return rebaseBatch(batch, newBaseSnapshot, nextRevision, newBaseIndex, modifiedBlockIds);
1537
1803
  })
1538
1804
  });
1539
1805
  }
@@ -1541,11 +1807,19 @@ function resolveReviewEntry(state, batchId, entryId, resolution) {
1541
1807
  return {
1542
1808
  ...state,
1543
1809
  batches: state.batches.map((batch) => {
1544
- if (batch.id !== batchId) return batch;
1545
- return withEntries(batch, batch.entries.map((entry) => entry.id === entryId ? {
1546
- ...entry,
1547
- status: resolution
1548
- } : entry));
1810
+ if (batch.id !== batchId || isFinalBatchStatus(batch.status)) return batch;
1811
+ let changed = false;
1812
+ const entries = batch.entries.map((entry) => {
1813
+ if (entry.id === entryId && isUnresolvedEntryStatus(entry.status)) {
1814
+ changed = true;
1815
+ return {
1816
+ ...entry,
1817
+ status: resolution
1818
+ };
1819
+ }
1820
+ return entry;
1821
+ });
1822
+ return changed ? withEntries(batch, entries) : batch;
1549
1823
  })
1550
1824
  };
1551
1825
  }
@@ -1,7 +1,6 @@
1
1
  import type { SerializedEditorState } from 'lexical';
2
2
  import type { ReviewBatch, ReviewState } from './review-types';
3
3
  import type { AgentOperation } from './types';
4
- export declare function applyOpsToSnapshot(base: SerializedEditorState, ops: AgentOperation[]): SerializedEditorState;
5
4
  export declare function createReviewBatch(ops: AgentOperation[], baseSnapshot: SerializedEditorState, baseRevision: number): ReviewBatch;
6
5
  export declare function appendReviewBatch(state: ReviewState, incoming: ReviewBatch): ReviewState;
7
6
  export declare function acceptBatch(state: ReviewState, batchId: string): ReviewState;
@@ -1 +1 @@
1
- {"version":3,"file":"review-engine.d.ts","sources":["../src/review-engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAyB,MAAM,SAAS,CAAC;AAG5E,OAAO,KAAK,EAAE,WAAW,EAAe,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AA2E9C,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,qBAAqB,EAC3B,GAAG,EAAE,cAAc,EAAE,GACpB,qBAAqB,CAkCvB;AAqDD,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,cAAc,EAAE,EACrB,YAAY,EAAE,qBAAqB,EACnC,YAAY,EAAE,MAAM,GACnB,WAAW,CAoDb;AASD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,GAAG,WAAW,CAWxF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAE5E;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAE5E;AA4GD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,CAqCtE;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAqBrF;AAED,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,UAAU,GAAG,UAAU,GAClC,WAAW,CAcb;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,CAE/D"}
1
+ {"version":3,"file":"review-engine.d.ts","sources":["../src/review-engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAUrD,OAAO,KAAK,EAAE,WAAW,EAAe,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAiM9C,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,cAAc,EAAE,EACrB,YAAY,EAAE,qBAAqB,EACnC,YAAY,EAAE,MAAM,GACnB,WAAW,CAOb;AAeD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,GAAG,WAAW,CAexF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAE5E;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAE5E;AAsHD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,CA2CtE;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,GAAG,WAAW,CAoCrF;AAED,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,UAAU,GAAG,UAAU,GAClC,WAAW,CAkBb;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,CAE/D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@haklex/rich-agent-core",
3
- "version": "0.69.1",
3
+ "version": "0.70.0",
4
4
  "description": "Headless AI agent protocol, diff engine, and store for Lexical editor",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,18 +20,18 @@
20
20
  "dist"
21
21
  ],
22
22
  "dependencies": {
23
- "@haklex/rich-litexml": "0.69.1",
23
+ "@haklex/rich-litexml": "0.70.0",
24
24
  "nanoid": "^6.0.2",
25
25
  "zustand": "^5.0.16"
26
26
  },
27
27
  "devDependencies": {
28
- "@haklex/rich-editor": "0.69.1",
28
+ "@haklex/rich-editor": "0.70.0",
29
29
  "lexical": "^0.53.0",
30
30
  "vite": "^8.3.5",
31
31
  "vitest": "^5.0.5"
32
32
  },
33
33
  "peerDependencies": {
34
- "@haklex/rich-editor": "^0.69.1",
34
+ "@haklex/rich-editor": "^0.70.0",
35
35
  "lexical": "^0.53.0"
36
36
  },
37
37
  "publishConfig": {