@kivacore/ui-pro-agent-canvas 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +186 -2
  2. package/dist/chunk-6VEULBW4.js +350 -0
  3. package/dist/chunk-6VEULBW4.js.map +1 -0
  4. package/dist/chunk-NBZZMLSJ.js +49 -0
  5. package/dist/chunk-NBZZMLSJ.js.map +1 -0
  6. package/dist/chunk-X5MPJL3E.js +1291 -0
  7. package/dist/chunk-X5MPJL3E.js.map +1 -0
  8. package/dist/chunk-ZYDFOGKV.js +343 -0
  9. package/dist/chunk-ZYDFOGKV.js.map +1 -0
  10. package/dist/commands/args.d.ts +27 -0
  11. package/dist/commands/canvas-commands.d.ts +3 -0
  12. package/dist/commands/cli.d.ts +22 -0
  13. package/dist/commands/doc-commands.d.ts +2 -0
  14. package/dist/commands/index.d.ts +3 -0
  15. package/dist/commands/index.js +4 -0
  16. package/dist/commands/index.js.map +1 -0
  17. package/dist/commands/instructions.d.ts +6 -0
  18. package/dist/commands/sheet-commands.d.ts +2 -0
  19. package/dist/commands/types.d.ts +46 -0
  20. package/dist/core/canvas.d.ts +201 -0
  21. package/dist/core/diff.d.ts +20 -0
  22. package/dist/core/document.d.ts +62 -0
  23. package/dist/core/errors.d.ts +11 -0
  24. package/dist/core/index.d.ts +5 -0
  25. package/dist/core/index.js +5 -0
  26. package/dist/core/index.js.map +1 -0
  27. package/dist/core/sheet.d.ts +66 -0
  28. package/dist/document-view-IQMA44RC.js +230 -0
  29. package/dist/document-view-IQMA44RC.js.map +1 -0
  30. package/dist/index.d.ts +5 -0
  31. package/dist/index.js +343 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/react/agent-canvas.d.ts +27 -0
  34. package/dist/react/document-kit.d.ts +6 -0
  35. package/dist/react/document-sync.d.ts +17 -0
  36. package/dist/react/document-view.d.ts +13 -0
  37. package/dist/react/labels.d.ts +24 -0
  38. package/dist/react/sheet-view.d.ts +15 -0
  39. package/dist/react/use-agent-canvas.d.ts +5 -0
  40. package/dist/sheet-view-4EXLWEWY.js +42 -0
  41. package/dist/sheet-view-4EXLWEWY.js.map +1 -0
  42. package/package.json +63 -3
package/README.md CHANGED
@@ -1,3 +1,187 @@
1
- # Temporary Holding Version
1
+ # @kivacore/ui-pro-agent-canvas
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A canvas that an agent and a person edit together. It holds documents (the Kiva UI Plate editor) and spreadsheets (`@kivacore/ui-pro-sheets`) as tabs in one panel, and it comes with a command library, so an agent can open the panel and read and write everything on it from its shell.
4
+
5
+ The package has three parts:
6
+
7
+ | Part | Import | What it is |
8
+ | --- | --- | --- |
9
+ | Canvas | `createAgentCanvas()` | The canvas itself: an in-memory object that holds the items. No React. |
10
+ | Panel | `<AgentCanvas>` | The React component that shows a canvas and lets the person edit it. |
11
+ | Commands | `createCanvasCli()` | The canvas as a command line (`canvas doc read`, `canvas sheet write A1 ...`) for an agent. No React. |
12
+
13
+ The panel and the commands both work on the same canvas object. That is what keeps them in step: the agent's write shows up in the panel as it happens, and the agent's next read includes what the person typed.
14
+
15
+ Nothing is saved. A canvas lives as long as the object does, and is gone on reload.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pnpm add @kivacore/ui-pro-agent-canvas @kivacore/ui-pro-shared
21
+ ```
22
+
23
+ The package follows the same styling contract as the other Kiva UI Pro packages: it ships Tailwind v4 class names and your app's Tailwind build generates the CSS.
24
+
25
+ ```css
26
+ /* your app's globals.css */
27
+ @import "@kivacore/ui-pro-sheets/styles.css";
28
+
29
+ @source "../node_modules/@kivacore/ui-pro-agent-canvas/dist/**/*.js";
30
+ @source "../node_modules/@kivacore/ui-pro-shared/src/**/*.{ts,tsx}";
31
+ ```
32
+
33
+ Theme tokens (`--background`, `--foreground`, `--primary`, `--border`, `--muted` and the rest of the shadcn set) come from your app.
34
+
35
+ ## Use
36
+
37
+ ```tsx
38
+ import { useMemo } from 'react';
39
+
40
+ import { AgentCanvas, createAgentCanvas, useAgentCanvasState } from '@kivacore/ui-pro-agent-canvas';
41
+
42
+ function Workspace() {
43
+ const canvas = useMemo(() => createAgentCanvas(), []);
44
+ const { open } = useAgentCanvasState(canvas);
45
+
46
+ return (
47
+ <div className="flex h-screen">
48
+ <Conversation className="min-w-0 flex-1" />
49
+ {open && (
50
+ <aside className="w-1/2 min-w-0 border-l">
51
+ <AgentCanvas canvas={canvas} />
52
+ </aside>
53
+ )}
54
+ </div>
55
+ );
56
+ }
57
+ ```
58
+
59
+ The panel fills its parent, so give the parent a bounded size.
60
+
61
+ Whether the panel is on screen is the host's decision. The canvas only records what was asked for: `canvas.open()` and `canvas.close()` set `open`, and so do the agent's `canvas open` and `canvas close` commands and the panel's close button. The host reads `open` and shows or hides its side panel.
62
+
63
+ The host may unmount the panel while it is closed, or keep it mounted and hidden. Both work: when the panel unmounts, each editor saves its content back to the canvas, and the agent can keep reading and writing while nothing is mounted.
64
+
65
+ ### `<AgentCanvas>` props
66
+
67
+ | Prop | Description |
68
+ | --- | --- |
69
+ | `canvas` | The canvas to show. Required. |
70
+ | `closable` | Show a close button, which calls `canvas.close()`. Default `true`. |
71
+ | `readOnly` | The person can look but not edit. The agent can still write. |
72
+ | `locale` | `en` (default) or `tr`. |
73
+ | `labels` | Replaces single pieces of text, for a language that is not built in. |
74
+ | `theme` | Colour mode of the spreadsheet grid: `light`, `dark` or `auto` (follows a `.dark` ancestor). |
75
+ | `headerExtra` | Extra controls at the end of the header. |
76
+ | `className` | Class names for the panel's root element. |
77
+
78
+ The document and spreadsheet editors are separate chunks. Each loads the first time an item of its kind is shown.
79
+
80
+ ## Give it to an agent
81
+
82
+ `createCanvasCli(canvas)` turns the canvas into a command line. `run` takes the arguments and returns `{ stdout, stderr, exitCode }`. It never throws.
83
+
84
+ ```ts
85
+ import { canvasAgentInstructions, createCanvasCli } from '@kivacore/ui-pro-agent-canvas/commands';
86
+
87
+ const cli = createCanvasCli(canvas);
88
+
89
+ await cli.run(['new', 'doc', 'Launch plan'], { stdin: '# Launch plan\n\nShip in March.\n' });
90
+ await cli.run(['doc', 'replace', '--old', 'March', '--new', 'April']);
91
+ await cli.run(['sheet', 'write', 'A1', 'Region', 'Planned', 'Actual']);
92
+ ```
93
+
94
+ Register `run` as a command in whatever runs the agent's shell. With a shell that takes host commands of the form `({ argv, stdin, cwd, files }) => Promise<{ stdout, stderr, exitCode }>`, that is one entry:
95
+
96
+ ```ts
97
+ const hostCommands = {
98
+ canvas: ({ argv, stdin, cwd, files }) => cli.run(argv, {
99
+ stdin,
100
+ readFile: path => files.readFile(resolve(cwd, path)),
101
+ writeFile: (path, data) => files.writeFile(resolve(cwd, path), data)
102
+ })
103
+ };
104
+ ```
105
+
106
+ Here `resolve` stands for whatever turns the path the agent typed into one your file system accepts. `readFile` and `writeFile` are optional. They let the agent pass `--file notes.md` and `--out budget.xlsx`. Without them the agent pipes content in and out, which covers everything except binary workbook files.
107
+
108
+ Add `canvasAgentInstructions()` to the agent's instructions. It explains when to use the canvas and how to work beside a person who edits it too, and it points the agent at `canvas --help` for the command reference, so the two cannot drift apart.
109
+
110
+ ### Commands
111
+
112
+ `canvas --help` lists every command and `canvas <command> --help` shows its options and examples. In short:
113
+
114
+ | Command | What it does |
115
+ | --- | --- |
116
+ | `canvas` | List the items, which one is in front, what the person selected, and whether they changed anything since the agent last read it. |
117
+ | `canvas open [item]`, `canvas close`, `canvas show <item>` | Show or hide the panel. |
118
+ | `canvas new doc [title]`, `canvas new sheet [title]` | Create an item, filled from stdin, `--file` or `--text`. A sheet takes CSV, TSV, JSON or a workbook file. |
119
+ | `canvas rename`, `canvas remove`, `canvas selection` | Manage items and read the person's selection. |
120
+ | `canvas doc read`, `outline` | Read a document as markdown: all of it, one `--section`, or `--lines 10:40`. |
121
+ | `canvas doc write`, `append`, `prepend`, `insert`, `replace`, `remove`, `clear` | Edit a document: the whole of it, one section, a line position, or an exact piece of text. |
122
+ | `canvas sheet info`, `read`, `find` | Read a workbook: a grid with cell addresses, or CSV, TSV, JSON and markdown. |
123
+ | `canvas sheet write`, `append`, `clear` | Write values and formulas. |
124
+ | `canvas sheet style`, `width`, `height`, `freeze`, `merge`, `unmerge`, `sort` | Format and arrange. |
125
+ | `canvas sheet rows`, `cols`, `tab`, `chart` | Rows, columns, worksheets and charts. |
126
+ | `canvas sheet export`, `undo`, `redo`, `call` | Save a file, step through history, and reach the rest of the spreadsheet API. |
127
+
128
+ Reads print content to stdout, so they compose with a shell: `canvas doc read > notes.md`, `canvas sheet read --format csv | head`. Writes print one line that says what changed. Errors go to stderr and say what to do next. The exit code is 1 when a command failed and 2 when it was malformed.
129
+
130
+ Pass `{ name: 'kiva-canvas' }` to `createCanvasCli` to install the command under another name. The help, the errors and `canvasAgentInstructions('kiva-canvas')` follow it.
131
+
132
+ ## Use the canvas from code
133
+
134
+ Everything the commands do goes through the canvas object, which you can call directly.
135
+
136
+ ```ts
137
+ const canvas = createAgentCanvas();
138
+
139
+ const doc = canvas.createDocument({ title: 'Plan', markdown: '# Plan' });
140
+ canvas.writeDocument(doc.id, '# Plan\n\nShip in April.');
141
+ canvas.readDocument(doc.id);
142
+
143
+ const sheet = canvas.createSheet({ title: 'Budget' });
144
+ canvas.editSheet(sheet.id, (workbook) => {
145
+ workbook.getActiveSheet().setValues(0, 0, [['Planned', 'Actual'], [12000, '=A2*1.1']]);
146
+ });
147
+ canvas.workbook(sheet.id).getActiveSheet().getValue(1, 1);
148
+
149
+ canvas.on(event => console.log(event.type));
150
+ ```
151
+
152
+ `canvas.workbook(id)` is the `Workbook` from `@kivacore/ui-pro-sheets/engine`, so its whole API is available.
153
+
154
+ Changes made through these methods count as the agent's, unless `by: 'user'` is passed. The canvas keeps track of who changed what, per item:
155
+
156
+ - `changedSinceAgentRead`: the person changed it and the agent has not read it since. `canvas` shows this, so the agent knows to read again before it writes.
157
+ - `unread`: the agent changed it while the person had something else in front of them. The panel shows a dot on the tab.
158
+
159
+ Change a workbook inside `canvas.editSheet(...)` so the change is recorded as the agent's. Changes to a workbook outside that call are taken to be the person working in the grid.
160
+
161
+ ## How documents are edited
162
+
163
+ A document is a Plate editor for the person and markdown for the agent.
164
+
165
+ While an editor is mounted, it is the document. The agent's read is serialized from the editor at that moment. The agent's write is parsed into blocks and compared with the blocks in the editor, and only the blocks that differ are replaced. So an edit to one paragraph leaves the rest of the page untouched: the person's cursor stays where it was, the edit is one step in the editor's undo history, and formatting that markdown cannot express (alignment, colours, columns) survives on every block the agent did not rewrite. The changed blocks are tinted for a moment and scrolled into view.
166
+
167
+ Two consequences are worth knowing:
168
+
169
+ - The canvas rewrites markdown as it stores it (`-` bullets become `*`, tables are padded). `canvas doc replace` therefore needs the old text as `canvas doc read` prints it. The error says so when the text is not found.
170
+ - A block the agent rewrites is rebuilt from markdown, so formatting markdown cannot express is lost on that block.
171
+
172
+ ## Limits of this version
173
+
174
+ - No persistence and no collaboration between browsers. One canvas, one page, in memory.
175
+ - Documents go to and from the agent as markdown only. There is no command for the editor's raw value.
176
+ - The document editor has no image upload, no comments and no AI commands. They need a server, which this version does not assume.
177
+ - `canvas remove` and the panel's Remove cannot be undone. The panel asks first. The command does not.
178
+
179
+ ## Development
180
+
181
+ ```bash
182
+ pnpm --filter @kivacore/ui-pro-agent-canvas test # core and commands, in Node
183
+ pnpm --filter @kivacore/ui-pro-agent-canvas typecheck
184
+ pnpm --filter @kivacore/ui-pro-agent-canvas build
185
+ ```
186
+
187
+ The playground has a page for it at `/components/agent-canvas`. Its left side stands in for an agent: it runs `canvas` commands against the panel on the right.
@@ -0,0 +1,350 @@
1
+ import { normalizeMarkdown, CanvasError } from './chunk-ZYDFOGKV.js';
2
+ import { Workbook, createSheet, rangeToString } from '@kivacore/ui-pro-sheets/engine';
3
+
4
+ var DEFAULT_TITLES = { document: "Untitled document", sheet: "Untitled sheet" };
5
+ var ID_PREFIX = { document: "doc", sheet: "sheet" };
6
+ var AgentCanvasController = class {
7
+ records = [];
8
+ isOpen = false;
9
+ activeId = null;
10
+ state = { open: false, items: [], activeId: null };
11
+ counters = { document: 0, sheet: 0 };
12
+ stateListeners = /* @__PURE__ */ new Set();
13
+ eventListeners = /* @__PURE__ */ new Set();
14
+ /** Who answers for a workbook change happening right now. */
15
+ sheetActor = "user";
16
+ // State
17
+ /** A snapshot that keeps its identity until something changes, for `useSyncExternalStore`. */
18
+ getState = () => this.state;
19
+ /** Calls back after every state change. Returns the unsubscribe function. */
20
+ subscribe = (listener) => {
21
+ this.stateListeners.add(listener);
22
+ return () => {
23
+ this.stateListeners.delete(listener);
24
+ };
25
+ };
26
+ /** Reports what happened and who did it. Returns the unsubscribe function. */
27
+ on(listener) {
28
+ this.eventListeners.add(listener);
29
+ return () => {
30
+ this.eventListeners.delete(listener);
31
+ };
32
+ }
33
+ get items() {
34
+ return this.state.items;
35
+ }
36
+ get activeItem() {
37
+ return this.state.items.find((item) => item.id === this.activeId) ?? null;
38
+ }
39
+ // Panel
40
+ /** Asks the host to show the panel, optionally on one item. */
41
+ open(ref) {
42
+ const target = ref === void 0 ? null : this.record(ref);
43
+ const wasOpen = this.isOpen;
44
+ const wasActive = this.activeId;
45
+ if (target) this.activeId = target.id;
46
+ this.isOpen = true;
47
+ this.markActiveRead();
48
+ this.publish();
49
+ if (this.activeId !== wasActive) this.emit({ type: "active", id: this.activeId });
50
+ if (!wasOpen) this.emit({ type: "open" });
51
+ }
52
+ /** Asks the host to hide the panel. The contents stay. */
53
+ close() {
54
+ if (!this.isOpen) return;
55
+ this.isOpen = false;
56
+ this.publish();
57
+ this.emit({ type: "close" });
58
+ }
59
+ /** Makes an item the one the panel shows. */
60
+ activate(ref) {
61
+ const record = this.record(ref);
62
+ if (this.activeId !== record.id) {
63
+ this.activeId = record.id;
64
+ this.markActiveRead();
65
+ this.publish();
66
+ this.emit({ type: "active", id: record.id });
67
+ }
68
+ return this.view(record);
69
+ }
70
+ // Items
71
+ /**
72
+ * Finds an item by its id, by its position (`1` is the first) or by its
73
+ * title. `kind` narrows a title or a position to documents or to sheets.
74
+ */
75
+ find(ref, kind) {
76
+ const record = this.lookup(ref, kind);
77
+ return record ? this.view(record) : null;
78
+ }
79
+ /**
80
+ * The item a command means. Without a reference that is the active item when
81
+ * it has the right kind, and otherwise the only item of that kind.
82
+ */
83
+ resolve(ref, kind) {
84
+ return this.view(this.record(ref, kind));
85
+ }
86
+ createDocument(options = {}) {
87
+ const record = this.add("document", options.title);
88
+ record.document = { markdown: normalizeMarkdown(options.markdown ?? "") };
89
+ return this.finishCreate(record, options);
90
+ }
91
+ createSheet(options = {}) {
92
+ const record = this.add("sheet", options.title ?? this.workbookTitle(options.workbook));
93
+ const workbook = options.workbook ?? new Workbook({ name: record.title, sheets: [createSheet("Sheet1")] });
94
+ record.sheet = { workbook, stop: this.watch(record, workbook) };
95
+ return this.finishCreate(record, options);
96
+ }
97
+ rename(ref, title, by = "agent") {
98
+ const record = this.record(ref);
99
+ const next = title.trim();
100
+ if (!next) throw new CanvasError("A title cannot be empty.");
101
+ record.title = next;
102
+ this.publish();
103
+ this.emit({ type: "renamed", item: this.view(record), by });
104
+ return this.view(record);
105
+ }
106
+ remove(ref, by = "agent") {
107
+ const record = this.record(ref);
108
+ const index = this.records.indexOf(record);
109
+ const removed = this.view(record);
110
+ record.sheet?.stop();
111
+ this.records.splice(index, 1);
112
+ if (this.activeId === record.id) {
113
+ this.activeId = (this.records[index] ?? this.records[index - 1])?.id ?? null;
114
+ this.markActiveRead();
115
+ }
116
+ this.publish();
117
+ this.emit({ type: "removed", item: removed, by });
118
+ return removed;
119
+ }
120
+ /** Empties the canvas and hides the panel. */
121
+ clear() {
122
+ for (const record of [...this.records]) this.remove(record.id);
123
+ this.close();
124
+ }
125
+ // Documents
126
+ /** The document as markdown, including what the person has typed up to now. */
127
+ readDocument(ref, by = "agent") {
128
+ const record = this.record(ref, "document");
129
+ const markdown = this.currentMarkdown(record);
130
+ if (by === "agent") this.agentSaw(record);
131
+ return markdown;
132
+ }
133
+ /**
134
+ * Replaces the document with new markdown. A mounted editor applies only the
135
+ * blocks that differ, so the rest of the page, and the person's place in it,
136
+ * stay as they were.
137
+ */
138
+ writeDocument(ref, markdown, by = "agent") {
139
+ const record = this.record(ref, "document");
140
+ const document = this.documentOf(record);
141
+ const next = normalizeMarkdown(markdown);
142
+ if (next === this.currentMarkdown(record)) return this.view(record);
143
+ document.markdown = next;
144
+ document.value = void 0;
145
+ document.binding?.write(next);
146
+ this.touch(record, by);
147
+ return this.view(record);
148
+ }
149
+ /** The text the person has selected in a document, when its editor is on screen. */
150
+ documentSelection(ref) {
151
+ return this.documentOf(this.record(ref, "document")).binding?.selection() ?? null;
152
+ }
153
+ // Sheets
154
+ /** The workbook behind a sheet item. Its engine API is the full read and write surface. */
155
+ workbook(ref) {
156
+ return this.sheetOf(this.record(ref, "sheet")).workbook;
157
+ }
158
+ /**
159
+ * Runs workbook changes on the agent's behalf, so they are recorded as the
160
+ * agent's. Anything that changes a workbook outside this call is taken to
161
+ * be the person working in the grid.
162
+ */
163
+ editSheet(ref, edit, by = "agent") {
164
+ const record = this.record(ref, "sheet");
165
+ const previous = this.sheetActor;
166
+ this.sheetActor = by;
167
+ try {
168
+ return edit(this.sheetOf(record).workbook);
169
+ } finally {
170
+ this.sheetActor = previous;
171
+ }
172
+ }
173
+ /** Records that the agent has read a sheet, which settles `changedSinceAgentRead`. */
174
+ markSheetRead(ref) {
175
+ this.agentSaw(this.record(ref, "sheet"));
176
+ }
177
+ /** The cells the person has selected, when the sheet is on screen. */
178
+ sheetSelection(ref) {
179
+ const sheet = this.sheetOf(this.record(ref, "sheet"));
180
+ const selection = sheet.binding?.selection();
181
+ if (!selection) return null;
182
+ return { sheet: sheet.workbook.getSheet(selection.sheetId).name, range: rangeToString(selection.range) };
183
+ }
184
+ /** Shows the person where the agent wrote, when the sheet is on screen. */
185
+ revealRange(ref, sheetId, range) {
186
+ this.sheetOf(this.record(ref, "sheet")).binding?.reveal(sheetId, range);
187
+ }
188
+ // Bindings: used by the panel's views
189
+ /** What a document editor should start from. */
190
+ documentSeed(id) {
191
+ const document = this.documentOf(this.record(id, "document"));
192
+ return { markdown: document.markdown, value: document.value };
193
+ }
194
+ /**
195
+ * Connects a mounted editor. When it disconnects, its content is saved back,
196
+ * so the document outlives the editor.
197
+ */
198
+ bindDocument(id, binding) {
199
+ const document = this.documentOf(this.record(id, "document"));
200
+ document.binding = binding;
201
+ return () => {
202
+ if (document.binding !== binding) return;
203
+ document.markdown = normalizeMarkdown(binding.read());
204
+ document.value = binding.snapshot();
205
+ document.binding = void 0;
206
+ };
207
+ }
208
+ bindSheet(id, binding) {
209
+ const sheet = this.sheetOf(this.record(id, "sheet"));
210
+ sheet.binding = binding;
211
+ return () => {
212
+ if (sheet.binding === binding) sheet.binding = void 0;
213
+ };
214
+ }
215
+ /** Called by a document editor when the person changes the text. */
216
+ noteUserEdit(id) {
217
+ const record = this.lookup(id);
218
+ if (record) this.touch(record, "user");
219
+ }
220
+ // Internals
221
+ add(kind, title) {
222
+ this.counters[kind] += 1;
223
+ const record = {
224
+ id: `${ID_PREFIX[kind]}-${this.counters[kind]}`,
225
+ kind,
226
+ title: title?.trim() || DEFAULT_TITLES[kind],
227
+ revision: 0,
228
+ changedBy: null,
229
+ unread: false,
230
+ agentRevision: 0
231
+ };
232
+ this.records.push(record);
233
+ return record;
234
+ }
235
+ finishCreate(record, options) {
236
+ const by = options.by ?? "agent";
237
+ const show = options.show ?? true;
238
+ const wasOpen = this.isOpen;
239
+ if (show || this.activeId === null) this.activeId = record.id;
240
+ if (show) this.isOpen = true;
241
+ record.unread = by === "agent" && !this.isInFront(record);
242
+ this.publish();
243
+ this.emit({ type: "added", item: this.view(record), by });
244
+ if (this.isOpen && !wasOpen) this.emit({ type: "open" });
245
+ return this.view(record);
246
+ }
247
+ workbookTitle(workbook) {
248
+ const name = workbook?.name;
249
+ return name && name !== "Workbook" ? name : void 0;
250
+ }
251
+ /** Counts each finished transaction, undo and redo as one change. */
252
+ watch(record, workbook) {
253
+ return workbook.on((event) => {
254
+ if (event.type === "history") this.touch(record, this.sheetActor);
255
+ });
256
+ }
257
+ touch(record, by) {
258
+ record.revision += 1;
259
+ record.changedBy = by;
260
+ if (by === "agent") {
261
+ record.agentRevision = record.revision;
262
+ record.unread = !this.isInFront(record);
263
+ }
264
+ this.publish();
265
+ this.emit({ type: "changed", item: this.view(record), by });
266
+ }
267
+ agentSaw(record) {
268
+ if (record.agentRevision === record.revision) return;
269
+ record.agentRevision = record.revision;
270
+ this.publish();
271
+ }
272
+ isInFront(record) {
273
+ return this.isOpen && this.activeId === record.id;
274
+ }
275
+ markActiveRead() {
276
+ const active = this.records.find((record) => record.id === this.activeId);
277
+ if (active && this.isOpen) active.unread = false;
278
+ }
279
+ currentMarkdown(record) {
280
+ const document = this.documentOf(record);
281
+ return document.binding ? normalizeMarkdown(document.binding.read()) : document.markdown;
282
+ }
283
+ documentOf(record) {
284
+ if (!record.document) throw new CanvasError(`"${record.title}" (${record.id}) is a sheet, not a document. Use the sheet commands for it.`);
285
+ return record.document;
286
+ }
287
+ sheetOf(record) {
288
+ if (!record.sheet) throw new CanvasError(`"${record.title}" (${record.id}) is a document, not a sheet. Use the doc commands for it.`);
289
+ return record.sheet;
290
+ }
291
+ lookup(ref, kind) {
292
+ const pool = kind ? this.records.filter((record) => record.kind === kind) : this.records;
293
+ const text = ref.trim();
294
+ const byId = this.records.find((record) => record.id === text.toLowerCase());
295
+ if (byId) return byId;
296
+ if (/^\d+$/.test(text)) return pool[Number(text) - 1] ?? null;
297
+ const titled = pool.filter((record) => record.title.toLowerCase() === text.toLowerCase());
298
+ if (titled.length > 1) {
299
+ throw new CanvasError(`${titled.length} items are titled "${text}" (${titled.map((record) => record.id).join(", ")}). Name one by its id.`);
300
+ }
301
+ return titled[0] ?? null;
302
+ }
303
+ record(ref, kind) {
304
+ if (ref !== void 0 && ref !== "") {
305
+ const found = this.lookup(ref, kind);
306
+ if (!found) throw new CanvasError(`No canvas item "${ref}". ${this.inventory()}`);
307
+ if (kind && found.kind !== kind) {
308
+ throw new CanvasError(`"${found.title}" (${found.id}) is a ${found.kind}, not a ${kind}. Use the ${found.kind === "document" ? "doc" : "sheet"} commands for it.`);
309
+ }
310
+ return found;
311
+ }
312
+ const active = this.records.find((record) => record.id === this.activeId);
313
+ if (active && (!kind || active.kind === kind)) return active;
314
+ const candidates = kind ? this.records.filter((record) => record.kind === kind) : this.records;
315
+ if (candidates.length === 1) return candidates[0];
316
+ if (candidates.length === 0) {
317
+ throw new CanvasError(kind ? `The canvas has no ${kind}. Create one with "new ${kind === "document" ? "doc" : "sheet"}".` : 'The canvas is empty. Create something with "new doc" or "new sheet".');
318
+ }
319
+ throw new CanvasError(`The canvas has ${candidates.length} ${kind ?? "item"}s and none of them is active. Name one with --item. ${this.inventory()}`);
320
+ }
321
+ inventory() {
322
+ if (this.records.length === 0) return "The canvas is empty.";
323
+ return `Items: ${this.records.map((record) => `${record.id} "${record.title}"`).join(", ")}.`;
324
+ }
325
+ view(record) {
326
+ return {
327
+ id: record.id,
328
+ kind: record.kind,
329
+ title: record.title,
330
+ revision: record.revision,
331
+ changedBy: record.changedBy,
332
+ unread: record.unread,
333
+ changedSinceAgentRead: record.revision > record.agentRevision
334
+ };
335
+ }
336
+ publish() {
337
+ this.state = { open: this.isOpen, items: this.records.map((record) => this.view(record)), activeId: this.activeId };
338
+ for (const listener of [...this.stateListeners]) listener();
339
+ }
340
+ emit(event) {
341
+ for (const listener of [...this.eventListeners]) listener(event);
342
+ }
343
+ };
344
+ function createAgentCanvas() {
345
+ return new AgentCanvasController();
346
+ }
347
+
348
+ export { AgentCanvasController, createAgentCanvas };
349
+ //# sourceMappingURL=chunk-6VEULBW4.js.map
350
+ //# sourceMappingURL=chunk-6VEULBW4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/canvas.ts"],"names":[],"mappings":";;;AA0GA,IAAM,cAAA,GAAiD,EAAE,QAAA,EAAU,mBAAA,EAAqB,O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AAAA,KAClD;AAAA,EACF;AAAA,EAEQ,OAAA,GAAgB;AACtB,IAAA,IAAA,CAAK,QAAQ,EAAE,IAAA,EAAM,IAAA,CAAK,MAAA,EAAQ,OAAO,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,KAAU,KAAK,IAAA,CAAK,MAAM,CAAC,CAAA,EAAG,QAAA,EAAU,KAAK,QAAA,EAAS;AAChH,IAAA,KAAA,MAAW,YAAY,CAAC,GAAG,IAAA,CAAK,cAAc,GAAG,QAAA,EAAS;AAAA,EAC5D;AAAA,EAEQ,KAAK,KAAA,EAA0B;AACrC,IAAA,KAAA,MAAW,YAAY,CAAC,GAAG,KAAK,cAAc,CAAA,WAAY,KAAK,CAAA;AAAA,EACjE;AACF;AAEO,SAAS,iBAAA,GAA2C;AACzD,EAAA,OAAO,IAAI,qBAAA,EAAsB;AACnC","file":"chunk-6VEULBW4.js","sourcesContent":["import {\n createSheet, rangeToString, Workbook, type Range\n} from '@kivacore/ui-pro-sheets/engine';\n\nimport { normalizeMarkdown } from './document';\nimport { CanvasError } from './errors';\n\nexport type CanvasItemKind = 'document' | 'sheet';\n\n/** Who changed something: the agent through the command library, or the person in the panel. */\nexport type CanvasActor = 'agent' | 'user';\n\nexport interface CanvasItem {\n /** Short and stable for the life of the canvas: `doc-1`, `sheet-2`. */\n readonly id: string;\n readonly kind: CanvasItemKind;\n readonly title: string;\n /** Goes up by one with every change to the content. */\n readonly revision: number;\n /** Who made the latest change, or `null` for an untouched item. */\n readonly changedBy: CanvasActor | null;\n /** The agent changed it and the person has not had it in front of them since. */\n readonly unread: boolean;\n /** The person changed it and the agent has not read it since. */\n readonly changedSinceAgentRead: boolean;\n}\n\nexport interface CanvasState {\n /** Whether the host should show the canvas panel. */\n readonly open: boolean;\n readonly items: readonly CanvasItem[];\n readonly activeId: string | null;\n}\n\nexport type CanvasEvent\n = | { type: 'open' }\n | { type: 'close' }\n | { type: 'active'; id: string | null }\n | { type: 'added'; item: CanvasItem; by: CanvasActor }\n | { type: 'removed'; item: CanvasItem; by: CanvasActor }\n | { type: 'renamed'; item: CanvasItem; by: CanvasActor }\n | { type: 'changed'; item: CanvasItem; by: CanvasActor };\n\n/**\n * What a mounted document editor gives the canvas. While an editor is bound it\n * is the document: reads come from it, so they include what the person typed\n * a moment ago, and writes go to it, so they show up at once.\n */\nexport interface DocumentBinding {\n read(): string;\n write(markdown: string): void;\n /** The text the person has selected, or `null` without a selection. */\n selection(): string | null;\n /** The editor's own value, kept so a later mount restores what markdown cannot carry. */\n snapshot(): unknown;\n}\n\n/** What a mounted spreadsheet gives the canvas. */\nexport interface SheetBinding {\n selection(): { sheetId: string; range: Range } | null;\n /** Brings the cells the agent just wrote into view. */\n reveal(sheetId: string, range: Range): void;\n}\n\nexport interface DocumentSeed {\n markdown: string;\n /** The editor value saved by the last mount, when the markdown has not changed since. */\n value?: unknown;\n}\n\nexport interface SheetSelection {\n /** Worksheet name. */\n sheet: string;\n /** A1 notation, such as `B2:D9`. */\n range: string;\n}\n\nexport interface CreateDocumentOptions {\n title?: string;\n markdown?: string;\n /** Show it: make it the active item and open the panel. Default `true`. */\n show?: boolean;\n by?: CanvasActor;\n}\n\nexport interface CreateSheetOptions {\n title?: string;\n /** A workbook to put on the canvas. Without one the sheet starts empty. */\n workbook?: Workbook;\n show?: boolean;\n by?: CanvasActor;\n}\n\ninterface ItemRecord {\n id: string;\n kind: CanvasItemKind;\n title: string;\n revision: number;\n changedBy: CanvasActor | null;\n unread: boolean;\n /** The revision the agent last read or wrote. */\n agentRevision: number;\n document?: { markdown: string; value?: unknown; binding?: DocumentBinding };\n sheet?: { workbook: Workbook; binding?: SheetBinding; stop: () => void };\n}\n\nconst DEFAULT_TITLES: Record<CanvasItemKind, string> = { document: 'Untitled document', sheet: 'Untitled sheet' };\n\nconst ID_PREFIX: Record<CanvasItemKind, string> = { document: 'doc', sheet: 'sheet' };\n\n/**\n * The canvas: a set of documents and spreadsheets that an agent and a person\n * edit together. It holds everything in memory and nothing else, so a canvas\n * lives exactly as long as the object does.\n *\n * The panel (`<AgentCanvas>`) renders it and the command library\n * (`createCanvasCli`) drives it. Both go through this object, which is what\n * keeps them in step.\n *\n * Changes made through these methods count as the agent's unless `by: 'user'`\n * is passed. The panel passes it for what the person does.\n */\nexport class AgentCanvasController {\n private records: ItemRecord[] = [];\n\n private isOpen = false;\n\n private activeId: string | null = null;\n\n private state: CanvasState = { open: false, items: [], activeId: null };\n\n private readonly counters: Record<CanvasItemKind, number> = { document: 0, sheet: 0 };\n\n private readonly stateListeners = new Set<() => void>();\n\n private readonly eventListeners = new Set<(event: CanvasEvent) => void>();\n\n /** Who answers for a workbook change happening right now. */\n private sheetActor: CanvasActor = 'user';\n\n // State\n\n /** A snapshot that keeps its identity until something changes, for `useSyncExternalStore`. */\n getState = (): CanvasState => this.state;\n\n /** Calls back after every state change. Returns the unsubscribe function. */\n subscribe = (listener: () => void): (() => void) => {\n this.stateListeners.add(listener);\n\n return () => {\n this.stateListeners.delete(listener);\n };\n };\n\n /** Reports what happened and who did it. Returns the unsubscribe function. */\n on(listener: (event: CanvasEvent) => void): () => void {\n this.eventListeners.add(listener);\n\n return () => {\n this.eventListeners.delete(listener);\n };\n }\n\n get items(): readonly CanvasItem[] {\n return this.state.items;\n }\n\n get activeItem(): CanvasItem | null {\n return this.state.items.find(item => item.id === this.activeId) ?? null;\n }\n\n // Panel\n\n /** Asks the host to show the panel, optionally on one item. */\n open(ref?: string): void {\n const target = ref === undefined ? null : this.record(ref);\n const wasOpen = this.isOpen;\n const wasActive = this.activeId;\n\n if (target) this.activeId = target.id;\n this.isOpen = true;\n this.markActiveRead();\n this.publish();\n if (this.activeId !== wasActive) this.emit({ type: 'active', id: this.activeId });\n if (!wasOpen) this.emit({ type: 'open' });\n }\n\n /** Asks the host to hide the panel. The contents stay. */\n close(): void {\n if (!this.isOpen) return;\n this.isOpen = false;\n this.publish();\n this.emit({ type: 'close' });\n }\n\n /** Makes an item the one the panel shows. */\n activate(ref: string): CanvasItem {\n const record = this.record(ref);\n\n if (this.activeId !== record.id) {\n this.activeId = record.id;\n this.markActiveRead();\n this.publish();\n this.emit({ type: 'active', id: record.id });\n }\n\n return this.view(record);\n }\n\n // Items\n\n /**\n * Finds an item by its id, by its position (`1` is the first) or by its\n * title. `kind` narrows a title or a position to documents or to sheets.\n */\n find(ref: string, kind?: CanvasItemKind): CanvasItem | null {\n const record = this.lookup(ref, kind);\n\n return record ? this.view(record) : null;\n }\n\n /**\n * The item a command means. Without a reference that is the active item when\n * it has the right kind, and otherwise the only item of that kind.\n */\n resolve(ref?: string, kind?: CanvasItemKind): CanvasItem {\n return this.view(this.record(ref, kind));\n }\n\n createDocument(options: CreateDocumentOptions = {}): CanvasItem {\n const record = this.add('document', options.title);\n\n record.document = { markdown: normalizeMarkdown(options.markdown ?? '') };\n\n return this.finishCreate(record, options);\n }\n\n createSheet(options: CreateSheetOptions = {}): CanvasItem {\n const record = this.add('sheet', options.title ?? this.workbookTitle(options.workbook));\n const workbook = options.workbook ?? new Workbook({ name: record.title, sheets: [createSheet('Sheet1')] });\n\n record.sheet = { workbook, stop: this.watch(record, workbook) };\n\n return this.finishCreate(record, options);\n }\n\n rename(ref: string, title: string, by: CanvasActor = 'agent'): CanvasItem {\n const record = this.record(ref);\n const next = title.trim();\n\n if (!next) throw new CanvasError('A title cannot be empty.');\n record.title = next;\n this.publish();\n this.emit({ type: 'renamed', item: this.view(record), by });\n\n return this.view(record);\n }\n\n remove(ref: string, by: CanvasActor = 'agent'): CanvasItem {\n const record = this.record(ref);\n const index = this.records.indexOf(record);\n const removed = this.view(record);\n\n record.sheet?.stop();\n this.records.splice(index, 1);\n if (this.activeId === record.id) {\n this.activeId = (this.records[index] ?? this.records[index - 1])?.id ?? null;\n this.markActiveRead();\n }\n this.publish();\n this.emit({ type: 'removed', item: removed, by });\n\n return removed;\n }\n\n /** Empties the canvas and hides the panel. */\n clear(): void {\n for (const record of [...this.records]) this.remove(record.id);\n this.close();\n }\n\n // Documents\n\n /** The document as markdown, including what the person has typed up to now. */\n readDocument(ref?: string, by: CanvasActor = 'agent'): string {\n const record = this.record(ref, 'document');\n const markdown = this.currentMarkdown(record);\n\n if (by === 'agent') this.agentSaw(record);\n\n return markdown;\n }\n\n /**\n * Replaces the document with new markdown. A mounted editor applies only the\n * blocks that differ, so the rest of the page, and the person's place in it,\n * stay as they were.\n */\n writeDocument(ref: string | undefined, markdown: string, by: CanvasActor = 'agent'): CanvasItem {\n const record = this.record(ref, 'document');\n const document = this.documentOf(record);\n const next = normalizeMarkdown(markdown);\n\n if (next === this.currentMarkdown(record)) return this.view(record);\n\n document.markdown = next;\n document.value = undefined;\n document.binding?.write(next);\n this.touch(record, by);\n\n return this.view(record);\n }\n\n /** The text the person has selected in a document, when its editor is on screen. */\n documentSelection(ref?: string): string | null {\n return this.documentOf(this.record(ref, 'document')).binding?.selection() ?? null;\n }\n\n // Sheets\n\n /** The workbook behind a sheet item. Its engine API is the full read and write surface. */\n workbook(ref?: string): Workbook {\n return this.sheetOf(this.record(ref, 'sheet')).workbook;\n }\n\n /**\n * Runs workbook changes on the agent's behalf, so they are recorded as the\n * agent's. Anything that changes a workbook outside this call is taken to\n * be the person working in the grid.\n */\n editSheet<T>(ref: string | undefined, edit: (workbook: Workbook) => T, by: CanvasActor = 'agent'): T {\n const record = this.record(ref, 'sheet');\n const previous = this.sheetActor;\n\n this.sheetActor = by;\n try {\n return edit(this.sheetOf(record).workbook);\n } finally {\n this.sheetActor = previous;\n }\n }\n\n /** Records that the agent has read a sheet, which settles `changedSinceAgentRead`. */\n markSheetRead(ref?: string): void {\n this.agentSaw(this.record(ref, 'sheet'));\n }\n\n /** The cells the person has selected, when the sheet is on screen. */\n sheetSelection(ref?: string): SheetSelection | null {\n const sheet = this.sheetOf(this.record(ref, 'sheet'));\n const selection = sheet.binding?.selection();\n\n if (!selection) return null;\n\n return { sheet: sheet.workbook.getSheet(selection.sheetId).name, range: rangeToString(selection.range) };\n }\n\n /** Shows the person where the agent wrote, when the sheet is on screen. */\n revealRange(ref: string | undefined, sheetId: string, range: Range): void {\n this.sheetOf(this.record(ref, 'sheet')).binding?.reveal(sheetId, range);\n }\n\n // Bindings: used by the panel's views\n\n /** What a document editor should start from. */\n documentSeed(id: string): DocumentSeed {\n const document = this.documentOf(this.record(id, 'document'));\n\n return { markdown: document.markdown, value: document.value };\n }\n\n /**\n * Connects a mounted editor. When it disconnects, its content is saved back,\n * so the document outlives the editor.\n */\n bindDocument(id: string, binding: DocumentBinding): () => void {\n const document = this.documentOf(this.record(id, 'document'));\n\n document.binding = binding;\n\n return () => {\n if (document.binding !== binding) return;\n document.markdown = normalizeMarkdown(binding.read());\n document.value = binding.snapshot();\n document.binding = undefined;\n };\n }\n\n bindSheet(id: string, binding: SheetBinding): () => void {\n const sheet = this.sheetOf(this.record(id, 'sheet'));\n\n sheet.binding = binding;\n\n return () => {\n if (sheet.binding === binding) sheet.binding = undefined;\n };\n }\n\n /** Called by a document editor when the person changes the text. */\n noteUserEdit(id: string): void {\n const record = this.lookup(id);\n\n if (record) this.touch(record, 'user');\n }\n\n // Internals\n\n private add(kind: CanvasItemKind, title: string | undefined): ItemRecord {\n this.counters[kind] += 1;\n\n const record: ItemRecord = {\n id: `${ID_PREFIX[kind]}-${this.counters[kind]}`,\n kind,\n title: title?.trim() || DEFAULT_TITLES[kind],\n revision: 0,\n changedBy: null,\n unread: false,\n agentRevision: 0\n };\n\n this.records.push(record);\n\n return record;\n }\n\n private finishCreate(record: ItemRecord, options: { show?: boolean; by?: CanvasActor }): CanvasItem {\n const by = options.by ?? 'agent';\n const show = options.show ?? true;\n const wasOpen = this.isOpen;\n\n if (show || this.activeId === null) this.activeId = record.id;\n if (show) this.isOpen = true;\n record.unread = by === 'agent' && !this.isInFront(record);\n this.publish();\n this.emit({ type: 'added', item: this.view(record), by });\n if (this.isOpen && !wasOpen) this.emit({ type: 'open' });\n\n return this.view(record);\n }\n\n private workbookTitle(workbook: Workbook | undefined): string | undefined {\n const name = workbook?.name;\n\n return name && name !== 'Workbook' ? name : undefined;\n }\n\n /** Counts each finished transaction, undo and redo as one change. */\n private watch(record: ItemRecord, workbook: Workbook): () => void {\n return workbook.on((event) => {\n if (event.type === 'history') this.touch(record, this.sheetActor);\n });\n }\n\n private touch(record: ItemRecord, by: CanvasActor): void {\n record.revision += 1;\n record.changedBy = by;\n if (by === 'agent') {\n record.agentRevision = record.revision;\n record.unread = !this.isInFront(record);\n }\n this.publish();\n this.emit({ type: 'changed', item: this.view(record), by });\n }\n\n private agentSaw(record: ItemRecord): void {\n if (record.agentRevision === record.revision) return;\n record.agentRevision = record.revision;\n this.publish();\n }\n\n private isInFront(record: ItemRecord): boolean {\n return this.isOpen && this.activeId === record.id;\n }\n\n private markActiveRead(): void {\n const active = this.records.find(record => record.id === this.activeId);\n\n if (active && this.isOpen) active.unread = false;\n }\n\n private currentMarkdown(record: ItemRecord): string {\n const document = this.documentOf(record);\n\n return document.binding ? normalizeMarkdown(document.binding.read()) : document.markdown;\n }\n\n private documentOf(record: ItemRecord): NonNullable<ItemRecord['document']> {\n if (!record.document) throw new CanvasError(`\"${record.title}\" (${record.id}) is a sheet, not a document. Use the sheet commands for it.`);\n\n return record.document;\n }\n\n private sheetOf(record: ItemRecord): NonNullable<ItemRecord['sheet']> {\n if (!record.sheet) throw new CanvasError(`\"${record.title}\" (${record.id}) is a document, not a sheet. Use the doc commands for it.`);\n\n return record.sheet;\n }\n\n private lookup(ref: string, kind?: CanvasItemKind): ItemRecord | null {\n const pool = kind ? this.records.filter(record => record.kind === kind) : this.records;\n const text = ref.trim();\n const byId = this.records.find(record => record.id === text.toLowerCase());\n\n if (byId) return byId;\n if (/^\\d+$/.test(text)) return pool[Number(text) - 1] ?? null;\n\n const titled = pool.filter(record => record.title.toLowerCase() === text.toLowerCase());\n\n if (titled.length > 1) {\n throw new CanvasError(`${titled.length} items are titled \"${text}\" (${titled.map(record => record.id).join(', ')}). Name one by its id.`);\n }\n\n return titled[0] ?? null;\n }\n\n private record(ref?: string, kind?: CanvasItemKind): ItemRecord {\n if (ref !== undefined && ref !== '') {\n const found = this.lookup(ref, kind);\n\n if (!found) throw new CanvasError(`No canvas item \"${ref}\". ${this.inventory()}`);\n if (kind && found.kind !== kind) {\n throw new CanvasError(`\"${found.title}\" (${found.id}) is a ${found.kind}, not a ${kind}. Use the ${found.kind === 'document' ? 'doc' : 'sheet'} commands for it.`);\n }\n\n return found;\n }\n\n const active = this.records.find(record => record.id === this.activeId);\n\n if (active && (!kind || active.kind === kind)) return active;\n\n const candidates = kind ? this.records.filter(record => record.kind === kind) : this.records;\n\n if (candidates.length === 1) return candidates[0] as ItemRecord;\n if (candidates.length === 0) {\n throw new CanvasError(kind ? `The canvas has no ${kind}. Create one with \"new ${kind === 'document' ? 'doc' : 'sheet'}\".` : 'The canvas is empty. Create something with \"new doc\" or \"new sheet\".');\n }\n\n throw new CanvasError(`The canvas has ${candidates.length} ${kind ?? 'item'}s and none of them is active. Name one with --item. ${this.inventory()}`);\n }\n\n private inventory(): string {\n if (this.records.length === 0) return 'The canvas is empty.';\n\n return `Items: ${this.records.map(record => `${record.id} \"${record.title}\"`).join(', ')}.`;\n }\n\n private view(record: ItemRecord): CanvasItem {\n return {\n id: record.id,\n kind: record.kind,\n title: record.title,\n revision: record.revision,\n changedBy: record.changedBy,\n unread: record.unread,\n changedSinceAgentRead: record.revision > record.agentRevision\n };\n }\n\n private publish(): void {\n this.state = { open: this.isOpen, items: this.records.map(record => this.view(record)), activeId: this.activeId };\n for (const listener of [...this.stateListeners]) listener();\n }\n\n private emit(event: CanvasEvent): void {\n for (const listener of [...this.eventListeners]) listener(event);\n }\n}\n\nexport function createAgentCanvas(): AgentCanvasController {\n return new AgentCanvasController();\n}\n"]}
@@ -0,0 +1,49 @@
1
+ // src/core/diff.ts
2
+ var LCS_BUDGET = 4e5;
3
+ function diffSequences(before, after) {
4
+ let head = 0;
5
+ while (head < before.length && head < after.length && before[head] === after[head]) head += 1;
6
+ let tail = 0;
7
+ while (tail < before.length - head && tail < after.length - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail += 1;
8
+ const oldCount = before.length - head - tail;
9
+ const newCount = after.length - head - tail;
10
+ if (oldCount === 0 && newCount === 0) return [];
11
+ const whole = () => [{ at: head, remove: oldCount, insert: Array.from({ length: newCount }, (_, index) => head + index) }];
12
+ if (oldCount === 0 || newCount === 0 || oldCount * newCount > LCS_BUDGET) return whole();
13
+ const width = newCount + 1;
14
+ const lengths = new Uint32Array((oldCount + 1) * width);
15
+ for (let i2 = oldCount - 1; i2 >= 0; i2--) {
16
+ for (let j2 = newCount - 1; j2 >= 0; j2--) {
17
+ lengths[i2 * width + j2] = before[head + i2] === after[head + j2] ? (lengths[(i2 + 1) * width + j2 + 1] ?? 0) + 1 : Math.max(lengths[(i2 + 1) * width + j2] ?? 0, lengths[i2 * width + j2 + 1] ?? 0);
18
+ }
19
+ }
20
+ const patches = [];
21
+ let open = null;
22
+ let i = 0;
23
+ let j = 0;
24
+ const change = () => {
25
+ if (!open) {
26
+ open = { at: head + i, remove: 0, insert: [] };
27
+ patches.push(open);
28
+ }
29
+ return open;
30
+ };
31
+ while (i < oldCount || j < newCount) {
32
+ if (i < oldCount && j < newCount && before[head + i] === after[head + j]) {
33
+ open = null;
34
+ i += 1;
35
+ j += 1;
36
+ } else if (j < newCount && (i === oldCount || (lengths[i * width + j + 1] ?? 0) >= (lengths[(i + 1) * width + j] ?? 0))) {
37
+ change().insert.push(head + j);
38
+ j += 1;
39
+ } else {
40
+ change().remove += 1;
41
+ i += 1;
42
+ }
43
+ }
44
+ return patches;
45
+ }
46
+
47
+ export { diffSequences };
48
+ //# sourceMappingURL=chunk-NBZZMLSJ.js.map
49
+ //# sourceMappingURL=chunk-NBZZMLSJ.js.map